text:
package io.paradoxical.cassieq.unittests.tests.repos;

import categories.BuildVerification;
import io.paradoxical.cassieq.dataAccess.exceptions.QueueAlreadyDeletingException;
import io.paradoxical.cassieq.dataAccess.interfaces.QueueRepository;
import io.paradoxical.cassieq.exceptions.QueueNotFoundException;
import io.paradoxical.cassieq.model.QueueDefinition;
import io.paradoxical.cassieq.model.QueueName;
import io.paradoxical.cassieq.model.QueueStatus;
import io.paradoxical.cassieq.unittests.DbTestBase;
import io.paradoxical.cassieq.unittests.TestQueueContext;
import io.paradoxical.cassieq.workers.QueueDeleter;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import java.util.Optional;
import java.util.stream.IntStream;

import static org.assertj.core.api.Assertions.assertThat;

@Category(BuildVerification.class)
public class QueueRepositoryTester extends DbTestBase {
    @Test
    public void queue_operations() throws Exception {
        final QueueName queueName = QueueName.valueOf("queue_operations");
        final TestQueueContext testContext = createTestQueueContext(queueName);

        assertThat(testContext.getQueueRepository().getQueueUnsafe(queueName).isPresent()).isEqualTo(true);
        assertThat(testContext.getQueueRepository().getActiveQueue(queueName).isPresent()).isEqualTo(true);

        assertThat(testContext.getQueueRepository().getQueueNames()).contains(queueName);
    }

    @Test
    public void queue_size_grows_and_shrinks() throws Exception {
        final QueueName queueName = QueueName.valueOf("queue_size_grows_and_shrinks");

        final TestQueueContext testContext = createTestQueueContext(queueName);

        int numMessages = 10;

        for (int i = 0; i < numMessages; i++) {
            testContext.putMessage(Integer.valueOf(i).toString());
        }

        final QueueRepository queueRepository = testContext.getQueueRepository();

        Optional<Long> queueSize = queueRepository.getQueueSize(testContext.getQueueDefinition());

        assertThat(queueSize.get()).isEqualTo(numMessages);

        int ackCount = 0;
        for (int i = numMessages - 1; i >= 0; i--) {

            testContext.readAndAckMessage(Integer.valueOf(ackCount).toString());

            final Optional<Long> newQueueSize = queueRepository.getQueueSize(testContext.getQueueDefinition());

            ackCount++;

            assertThat(newQueueSize.get()).isEqualTo(numMessages - ackCount);
        }

        queueSize = queueRepository.getQueueSize(testContext.getQueueDefinition());

        assertThat(queueSize.get()).isEqualTo(0);
    }

    @Test
    public void cannot_create_same_queue_twice() throws Exception {
        final QueueName queueName = QueueName.valueOf("cannot_create_same_queue_twice");

        final TestQueueContext testContext = createTestQueueContext(queueName);

        final QueueRepository queueRepository = testContext.getQueueRepository();

        assertThat(queueRepository.getQueueUnsafe(queueName).isPresent()).isEqualTo(true);
        assertThat(queueRepository.getActiveQueue(queueName).isPresent()).isEqualTo(true);

        assertThat(queueRepository.getQueueNames()).contains(queueName);

        assertThat(queueRepository.createQueue(testContext.getQueueDefinition())).isEmpty();
    }

    @Test
    public void queue_definition_once_in_status_cant_move_backwards() {

        final QueueName queueName = QueueName.valueOf("queue_definition_once_in_status_cant_move_backwards");

        final TestQueueContext testContext = createTestQueueContext(queueName);
        final QueueRepository queueRepository = testContext.getQueueRepository();

        final QueueDefinition queueDefinition = QueueDefinition.builder().accountName(testAccountName).queueName(queueName).build();

        queueRepository.createQueue(queueDefinition);

        assertThat(queueRepository.getQueueUnsafe(queueName).isPresent()).isEqualTo(true);

        assertThat(queueRepository.getQueueUnsafe(queueName).get().getStatus()).isEqualTo(QueueStatus.Active);

        // no skipping a state
        assertThat(queueRepository.tryAdvanceQueueStatus(queueDefinition.getQueueName(), QueueStatus.Inactive)).isFalse();

        assertThat(queueRepository.tryAdvanceQueueStatus(queueDefinition.getQueueName(), QueueStatus.PendingDelete)).isTrue();

        // ok to move to the same again
        assertThat(queueRepository.tryAdvanceQueueStatus(queueDefinition.getQueueName(), QueueStatus.Deleting)).isTrue();
        assertThat(queueRepository.tryAdvanceQueueStatus(queueDefinition.getQueueName(), QueueStatus.Deleting)).isTrue();

        assertThat(queueRepository.tryAdvanceQueueStatus(queueDefinition.getQueueName(), QueueStatus.Inactive)).isTrue();

        // can't go backwards
        assertThat(queueRepository.tryAdvanceQueueStatus(queueDefinition.getQueueName(), QueueStatus.Active)).isFalse();
    }

    @Test
    public void can_create_new_queue_while_old_queue_is_deleting() {

        final QueueName queueName = QueueName.valueOf("can_create_new_queue_while_old_queue_is_deleting");

        final TestQueueContext testContext = createTestQueueContext(queueName);

        final QueueRepository queueRepository = testContext.getQueueRepository();

        assertThat(queueRepository.getQueueUnsafe(queueName).isPresent()).isEqualTo(true);

        queueRepository.tryMarkForDeletion(testContext.getQueueDefinition());

        // should be able to create a new definition here
        queueRepository.createQueue(testContext.getQueueDefinition());
    }

    @Test
    public void delete_queue() throws QueueAlreadyDeletingException {

        final QueueName queueName = QueueName.valueOf("delete_queue");

        final TestQueueContext testContext = createTestQueueContext(queueName);
        final QueueRepository queueRepository = testContext.getQueueRepository();

        final QueueDefinition queueDefinition = testContext.getQueueDefinition();

        queueRepository.createQueue(queueDefinition);

        assertThat(queueRepository.getQueueUnsafe(queueName).isPresent()).isEqualTo(true);

        assertThat(queueRepository.getQueueNames()).contains(queueName);

        final QueueDeleter queueDeleter = testContext.createQueueDeleter();

        queueDeleter.delete(queueName);

        assertThat(queueRepository.getActiveQueue(queueName).isPresent())
                .isEqualTo(false)
                .withFailMessage("Deleted queue still shows up as active");

        assertThat(queueRepository.getQueueUnsafe(queueName).isPresent())
                .isEqualTo(false)
                .withFailMessage("Raw queue definition should not have existed. Queue definition was not removed");

        assertThat(queueRepository.getQueueNames()).doesNotContain(queueName);
    }

    @Test
    public void counters_work_after_complete_delete() throws Exception {

        final QueueName queueName = QueueName.valueOf("counters_work_after_complete_delete");

        final TestQueueContext testContext = createTestQueueContext(queueName);

        final QueueRepository queueRepository = testContext.getQueueRepository();

        final QueueDefinition queueDefinition = testContext.getQueueDefinition();

        assertThat(queueRepository.getQueueSize(queueDefinition)).isEmpty();

        assertThat(queueRepository.getQueueUnsafe(queueName).isPresent()).isEqualTo(true);

        assertThat(queueRepository.getQueueNames()).contains(queueName);

        // attempt a delete

        final QueueDeleter queueDeleter = testContext.createQueueDeleter();

        queueDeleter.delete(queueName);

        assertThat(queueRepository.getActiveQueue(queueName).isPresent())
                .isEqualTo(false)
                .withFailMessage("Deleted queue still shows up as active");

        assertThat(queueRepository.getQueueUnsafe(queueName).isPresent())
                .isEqualTo(false)
                .withFailMessage("Raw queue definition should not have existed. Queue definition was not removed");

        assertThat(queueRepository.getQueueNames()).doesNotContain(queueName);

        // make sure that after a delete occurred we can get a valid counter result
        // it should have a new counter id
        final QueueDefinition recreatedDefinition = queueRepository.createQueue(queueDefinition).get();

        final TestQueueContext newContext = new TestQueueContext(recreatedDefinition, getDefaultInjector());

        newContext.putMessage("0");

        final Long afterRecreateSize = newContext.getQueueRepository().getQueueSize(recreatedDefinition).get();

        assertThat(afterRecreateSize).isEqualTo(1);
    }

    @Test
    public void only_one_active_ever() {

        final QueueName queueName = QueueName.valueOf("only_one_active_ever");

        final TestQueueContext testContext = createTestQueueContext(queueName);
        final QueueRepository queueRepository = testContext.getQueueRepository();

        final QueueDeleter queueDeleter = testContext.createQueueDeleter();

        final QueueDefinition queueDefinition = QueueDefinition.builder().accountName(testAccountName).queueName(queueName).build();

        IntStream.range(0, 1000)
                 .parallel()
                 .forEach(i -> {
                     queueRepository.createQueue(queueDefinition);

                     try {
                         queueDeleter.delete(queueName);
                     }
                     catch (QueueAlreadyDeletingException | QueueNotFoundException e) {
                         // ok
                     }
                 });

        queueRepository.createQueue(queueDefinition);

        final long count = queueRepository.getActiveQueues().stream().filter(i -> i.getQueueName().equals(queueName)).count();

        assertThat(count).isBetween(0L, 1L).withFailMessage("Too many active queues created");
    }
}


text:
class AddGithubTokenToPeople < ActiveRecord::Migration
  def change
    add_column :people, :github_token, :string
  end
end

redpajama_set_name: RedPajamaGithub


text: Rails.application.config.session_store :cookie_store, key: '_contactbook_session'


text:
/*
  What is the dead simplest thing to do?
  Extend AbstractMap and don't optimize for anything.

  The only new api is 'getValues()' which returns the values struct as
  long as no map api has been called.  If any map api is called,
  create a real map and forward to it, and nuke values because of the
  possibility that the map has been changed.  This is easier than
  trying to create a map that only clears values if the map has been
  changed, or implementing the map API directly on top of the values
  struct.  We can always do that later if need be.
*/

package sun.font;

import java.awt.Paint;
import java.awt.font.GraphicAttribute;
import java.awt.font.NumericShaper;
import java.awt.font.TextAttribute;
import java.awt.font.TransformAttribute;
import java.awt.geom.AffineTransform;
import java.awt.im.InputMethodHighlight;
import java.text.AttributedCharacterIterator.Attribute;
import java.util.AbstractMap;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import static sun.font.AttributeValues.*;

public final class AttributeMap extends AbstractMap<TextAttribute, Object> {
    private AttributeValues values;
    private Map<TextAttribute, Object> delegateMap;

    public AttributeMap(AttributeValues values) {
        this.values = values;
    }

    public Set<Entry<TextAttribute, Object>> entrySet() {
        return delegate().entrySet();
    }

    public Object put(TextAttribute key, Object value) {
        return delegate().put(key, value);
    }

    // internal API
    public AttributeValues getValues() {
        return values;
    }

    private static boolean first = false; // debug
    private Map<TextAttribute, Object> delegate() {
        if (delegateMap == null) {
            if (first) {
                first = false;
                Thread.dumpStack();
            }
            delegateMap = values.toMap(new HashMap<TextAttribute, Object>(27));

            // nuke values, once map is accessible it might be mutated and values would
            // no longer reflect its contents
            values = null;
        }

        return delegateMap;
    }

    public String toString() {
        if (values != null) {
            return "map of " + values.toString();
        }
        return super.toString();
    }
}


text:
package org.eclipse.rdf4j.query.algebra.evaluation.impl;

import org.eclipse.rdf4j.query.Dataset;
import org.eclipse.rdf4j.query.algebra.evaluation.EvaluationStrategy;
import org.eclipse.rdf4j.query.algebra.evaluation.TripleSource;
import org.eclipse.rdf4j.query.algebra.evaluation.federation.FederatedServiceResolver;
import org.eclipse.rdf4j.query.algebra.evaluation.federation.FederatedServiceResolverClient;

public class StrictEvaluationStrategyFactory extends AbstractEvaluationStrategyFactory
		implements FederatedServiceResolverClient {

	private FederatedServiceResolver serviceResolver;

	public StrictEvaluationStrategyFactory() {
	}

	public StrictEvaluationStrategyFactory(FederatedServiceResolver resolver) {
		this.serviceResolver = resolver;
	}

	@Override
	public void setFederatedServiceResolver(FederatedServiceResolver resolver) {
		this.serviceResolver = resolver;
	}

	public FederatedServiceResolver getFederatedServiceResolver() {
		return serviceResolver;
	}

	@Override
	public EvaluationStrategy createEvaluationStrategy(Dataset dataset, TripleSource tripleSource,
			EvaluationStatistics evaluationStatistics) {
		StrictEvaluationStrategy strategy = new StrictEvaluationStrategy(tripleSource, dataset, serviceResolver,
				getQuerySolutionCacheThreshold(), evaluationStatistics, isTrackResultSize());
		getOptimizerPipeline().ifPresent(strategy::setOptimizerPipeline);

		return strategy;
	}

}


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

namespace Microsoft.Azure.Commands.LogicApp.Test.ScenarioTests
{
    using Microsoft.WindowsAzure.Commands.ScenarioTest;
    using Microsoft.WindowsAzure.Commands.Test.Utilities.Common;
    using Xunit;

    /// <summary>
    /// Scenario tests for integration account received control number commands.
    /// </summary>
    public class IntegrationAccountReceivedIcnTests : RMTestBase
    {
        /// <summary>
        /// Test Get-AzureRmIntegrationAccountReceivedIcn command to get the integration account generated interchange control number.
        /// </summary>
        [Fact]
        [Trait(Category.AcceptanceType, Category.CheckIn)]
        public void TestGetIntegrationAccountReceivedIcn()
        {
            WorkflowController.NewInstance.RunPowerShellTest("Test-GetIntegrationAccountReceivedIcn");
        }

        /// <summary>
        /// Test Remove-AzureRmIntegrationAccountReceivedIcn command to update the integration account generated interchange control number.
        /// </summary>
        /// <remarks>The test method name is abbreviated to avoid running into legacy path length limit inside the underlying http mock recorder.</remarks>
        [Fact]
        [Trait(Category.AcceptanceType, Category.CheckIn)]
        public void TestRemoveIntegrationAccountReceivedIcn()
        {
            WorkflowController.NewInstance.RunPowerShellTest("Test-RemoveIntegrationAccountReceivedIcn");
        }

        /// <summary>
        /// Test Set-AzureRmIntegrationAccountReceivedIcn command to update the integration account generated interchange control number.
        /// </summary>
        /// <remarks>The test method name is abbreviated to avoid running into legacy path length limit inside the underlying http mock recorder.</remarks>
        [Fact]
        [Trait(Category.AcceptanceType, Category.CheckIn)]
        public void TestUpdateIntegrationAccountReceivedIcn()
        {
            WorkflowController.NewInstance.RunPowerShellTest("Test-UpdateIntegrationAccountReceivedIcn");
        }
    }
}


text:
package io.taotao.web;

import com.google.gson.Gson;
import com.paypal.api.payments.*;
import com.paypal.base.rest.APIContext;
import com.paypal.base.rest.PayPalRESTException;
import io.taotao.bean.PaymentError;
import io.taotao.bean.Record;
import io.taotao.dao.RecordRepository;
import io.taotao.util.CardUtil;
import io.taotao.util.PaypalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
public class PaypalController {

    @Autowired
    private RecordRepository recordRepository;

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    @Resource(name="redisTemplate")
    private ValueOperations<Object, Object> operations;

    @RequestMapping(value = "/paypal", method = RequestMethod.GET)
    public String root(Model model) {
        return "paypal/index";
    }

    @RequestMapping(value = "/paypal", method = RequestMethod.POST)
    public String pay(@RequestParam("first-name") String firstName, @RequestParam("last-name") String lastName,
                      @RequestParam("amount") String price, @RequestParam("currency") String currency,
                      @RequestParam("card-number") String number, @RequestParam("card-expiration") String expiration,
                      @RequestParam("card-cvv") String ccv, @RequestParam("phone") String phone, Model model) {
        number = number.replaceAll("\\s", "");
        String [] exp = expiration.split("/");

        CreditCard creditCard = new CreditCard();
        creditCard.setCvv2(ccv);
        creditCard.setExpireMonth(Integer.parseInt(exp[0]));
        creditCard.setExpireYear(Integer.parseInt(exp[1]));
        creditCard.setFirstName(firstName);
        creditCard.setLastName(lastName);
        creditCard.setNumber(number);

        String type = CardUtil.getCreditCardType(number);
        creditCard.setType(type);

        // ###Amount
        Amount amount = new Amount();
        amount.setCurrency(currency);
        amount.setTotal(price);

        // ###Record
        Transaction transaction = new Transaction();
        transaction.setAmount(amount);
        transaction.setDescription("sandbox sample payment");

        // The Payment creation API requires a list of
        // Record; add the created `Record`
        // to a List
        List<Transaction> transactions = new ArrayList<>();
        transactions.add(transaction);

        // ###FundingInstrument
        FundingInstrument fundingInstrument = new FundingInstrument();
        fundingInstrument.setCreditCard(creditCard);

        // The Payment creation API requires a list of
        // FundingInstrument; add the created `FundingInstrument`
        // to a List
        List<FundingInstrument> fundingInstrumentList = new ArrayList<>();
        fundingInstrumentList.add(fundingInstrument);

        // ###Payer
        Payer payer = new Payer();
        payer.setFundingInstruments(fundingInstrumentList);
        payer.setPaymentMethod("credit_card");

        // ###Payment
        Payment payment = new Payment();
        payment.setIntent("sale");
        payment.setPayer(payer);
        payment.setTransactions(transactions);

        Record record = new Record();
        record.setFirstName(firstName);
        record.setLastName(lastName);
        record.setPhone(phone);
        record.setAmount(Double.parseDouble(price));
        record.setCurrency(currency);
        record.setPaymentType(1);

        Payment createdPayment = null;
        PaymentError error = null;
        boolean isSuccess = true;

        try {
            APIContext context = PaypalUtil.getPaypalContext(currency);
            createdPayment = payment.create(context);
            record.setPaymentId(payment.getId());
            record.setPaymentId(createdPayment.getId());
            DateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            format.setTimeZone(TimeZone.getTimeZone("GMT"));
            Date date = format.parse(createdPayment.getCreateTime()
                    .replace("T", " ")
                    .replace("Z", ""));
            record.setCreateTime(date);
        } catch (PayPalRESTException e) {
            String message = e.getMessage();
            int index = message.indexOf("{\"");
            if (index > -1) {
                Gson gson = new Gson();
                error = gson.fromJson(message.substring(index), PaymentError.class);
            } else {
                error = new PaymentError();
                error.setMessage(e.getMessage());
            }
        } catch (Exception e) {
            error = new PaymentError();
            error.setMessage(e.getMessage());
        }

        if (error != null) {
            isSuccess = false;
            record.setError(error.getMessage());
        }

        record.setStatus(isSuccess);
        recordRepository.save(record);
        if (createdPayment != null) {
            operations.set(createdPayment.getId(), record);
        }

        model.addAttribute("isSuccess", isSuccess);
        model.addAttribute("error", error);
        model.addAttribute("record", record);

        return "paypal/result";
    }
}


text:
angular.module("form-service", [])

.factory("formService", ["$http", function($http) {

    var urlBase="api/";
    var formService = {};

	// get the editable fields
    formService.getFields = function(section) {

        // format the objects to be more angular friendly
        // for ease of use in forms

        var disclude = "items, id";
        var keys = Object.keys(section);
        var fields = [];

        angular.forEach(keys, function(value, key) {

            // check against keys not wanted in forms
            if (disclude.match(value) == null && value != "$$hashKey") {

                var obj = {};
                obj["label"] = value;
                obj["value"] = section[value];

                // add to fields
                this.push(obj);

            };

        }, fields);

        // get info to pass to edit
        return { fields: fields, id: section.id };

    };

    return formService;

}]);


text:
package	org.apache.derby.impl.sql.compile;

import java.util.List;
import org.apache.derby.shared.common.error.StandardException;
import org.apache.derby.shared.common.reference.SQLState;
import org.apache.derby.iapi.services.compiler.MethodBuilder;
import org.apache.derby.iapi.services.context.ContextManager;
import org.apache.derby.shared.common.sanity.SanityManager;
import org.apache.derby.iapi.sql.compile.Optimizable;
import org.apache.derby.iapi.sql.compile.TypeCompiler;
import org.apache.derby.iapi.store.access.Qualifier;
import org.apache.derby.iapi.types.DataTypeDescriptor;
import org.apache.derby.iapi.types.DataValueFactory;
import org.apache.derby.iapi.types.StringDataValue;
import org.apache.derby.iapi.types.TypeId;
import org.apache.derby.iapi.util.JBitSet;

/**
 * A ValueNode is an abstract class for all nodes that can represent data
 * values, that is, constants, columns, and expressions.
 *
 */

public abstract class ValueNode extends QueryTreeNode
{
    /**
     * The data type for this node.
     */
	private DataTypeDescriptor	dataTypeServices;

	// Whether or not additional predicates have been created from this one.
	boolean	transformed;

	/*
	** Constructor for untyped ValueNodes, for example, untyped NULLs
	** and parameter nodes.
	**
	** Binding will replace all untyped ValueNodes with typed ValueNodes
	** when it figures out what their types should be.
	*/
    ValueNode(ContextManager cm) {
        super(cm);
	}

    /**
     * Set this node's type from type components.
     */
    final void setType(TypeId typeId,
            boolean isNullable,
            int maximumWidth)
       throws StandardException

       {
        setType(new DataTypeDescriptor(typeId, isNullable, maximumWidth));
       }

    /**
     * Set this node's type from type components.
     */
    final void setType(TypeId typeId,
            int precision, int scale,
            boolean isNullable,
            int maximumWidth)
       throws StandardException
    {
        setType(
                new DataTypeDescriptor(
                            typeId,
                            precision,
                            scale,
                            isNullable,
                            maximumWidth
                        )
                    );
    }

	/**
	 * Convert this object to a String.  See comments in QueryTreeNode.java
	 * for how this should be done for tree printing.
	 *
	 * @return	This object as a String
	 */

    @Override
	public String toString()
	{
		if (SanityManager.DEBUG)
		{
			return "dataTypeServices: " +
				( ( dataTypeServices != null) ?
						dataTypeServices.toString() : "null" ) + "\n" +
				super.toString();
		}
		else
		{
			return "";
		}
	}

	/**
	 * Get the DataTypeServices from this ValueNode.
	 *
	 * @return	The DataTypeServices from this ValueNode.  This
	 *		may be null if the node isn't bound yet.
	 */
    DataTypeDescriptor getTypeServices()
	{
		return dataTypeServices;
	}

    /**
     * Set the nullability of this value.
     * @throws StandardException
     */
    public void setNullability(boolean nullability) throws StandardException
    {
        setType(getTypeServices().getNullabilityType(nullability));
    }

    /**
     * Set the collation type and derivation of this node based upon
     * the collation information in the passed in type. Note that the
     * base type of this node is not changed (e.g. INTEGER), only its
     * collation settings. This may result in a different object being
     * returned from getTypeServices().
     *
     * @param collationInfoType Type to take collation type and derivation from.
     * @throws StandardException Error setting type.
     */
    public void setCollationInfo(DataTypeDescriptor collationInfoType)
    throws StandardException
    {
        setCollationInfo(collationInfoType.getCollationType(),
                collationInfoType.getCollationDerivation());
    }

    /**
     * Set the collation type and derivation of this node based upon
     * the collation information passed in.
     * This may result in a different object being
     * returned from getTypeServices().
     *
     * @param collationType Collation type
     * @param collationDerivation Collation derivation
     * @throws StandardException Error setting type
     */
    public void setCollationInfo(int collationType, int collationDerivation)
        throws StandardException
    {
        setType(getTypeServices().getCollatedType(
                collationType, collationDerivation));
    }

	/**
	 * Get the TypeId from this ValueNode.
	 *
	 * @return	The TypeId from this ValueNode.  This
	 *		may be null if the node isn't bound yet.
	 */
    TypeId getTypeId() throws StandardException
	{
        DataTypeDescriptor dtd = getTypeServices();
        if (dtd != null)
            return dtd.getTypeId();
		return null;
	}

	/**
		Return the DataValueFactory
	*/
	protected final DataValueFactory getDataValueFactory() {
		return getLanguageConnectionContext().getDataValueFactory();
	}

	/**
	 * Get the TypeCompiler from this ValueNode, based on its TypeId
     * using getTypeId().
	 *
	 * @return	This ValueNode's TypeCompiler
	 *
	 */
    final TypeCompiler getTypeCompiler() throws StandardException
	{
		return getTypeCompiler(getTypeId());
	}

	/**
	 * Set the DataTypeServices for this ValueNode.  This method is
	 * overridden in ParameterNode.
	 *
	 * @param dataTypeServices	The DataTypeServices to set in this
	 *				ValueNode
	 */

    void setType(DataTypeDescriptor dataTypeServices) throws StandardException
	{
        // bind the type in case it is a user defined type. this will create a dependency on the udt.
        if ( dataTypeServices != null )
        {
            dataTypeServices = bindUserType( dataTypeServices );
        }

		this.dataTypeServices = dataTypeServices;

        // create a dependency on this type if it is an ANSI UDT
        if ( dataTypeServices != null ) { createTypeDependency( dataTypeServices ); }
	}

	/**
	 * Set the collation based upon the current schema with derivation
	 * type implicit.
	 *
	 * @throws StandardException
	 */
	protected final void setCollationUsingCompilationSchema()
	throws StandardException {
		setCollationUsingCompilationSchema(
				StringDataValue.COLLATION_DERIVATION_IMPLICIT);
	}

	/**
	 * There are many subclasses of ValueNode where we want the
	 * DataTypeDescriptor of the node to have the same collation type as the
	 * compilation schema's collation type. For that purpose, this method in
	 * the baseclass here can be utilized by the subclasses. In addition, the
	 * subclasses can pass the collationDerivation that they expect the
	 * DataTypeDescriptor to have.
	 *
	 * @param collationDerivation This can be
	 * StringDataValue#COLLATION_DERIVATION_IMPLICIT
	 * StringDataValue#COLLATION_DERIVATION_NONE
	 * StringDataValue#COLLATION_DERIVATION_EXPLICIT
	 *
	 * @throws StandardException
	 */
	protected final void setCollationUsingCompilationSchema(int collationDerivation)
	throws StandardException {
        setCollationInfo(
                getSchemaDescriptor(null, false).getCollationType(),
                collationDerivation);
	}

	/**
	 * Get the source for this ValueNode.
	 *
	 * @return	The source of this ValueNode, null if this node
     * is not sourced by a column.
	 */

    ResultColumn getSourceResultColumn()
	{
		return null;
	}

	/**
	 * Mark this predicate has having been transformed (other predicates
	 * were generated from it).  This will help us with ensure that the
	 * predicate does not get calculated into the selectivity multiple
	 * times.
	 */
	void setTransformed()
	{
		transformed = true;
	}

	/**
	 * Return whether or not this predicate has been transformed.
	 *
	 * @return Whether or not this predicate has been transformed.
	 */
	boolean getTransformed()
	{
		return transformed;
	}

    ValueNode bindExpression(
            FromList fromList, SubqueryList subqueryList, List<AggregateNode> aggregates)
		throws StandardException
	{
        return bindExpression(fromList, subqueryList, aggregates, false);
	}

	/**
	 * Bind this expression.  This is a place-holder method - it should never
	 * be called.
	 *
	 * @param fromList			The FROM list to use for binding
	 * @param subqueryList		The SubqueryList we are building as we hit
	 *							SubqueryNodes.
     * @param aggregates        The aggregate list being built as we find AggregateNodes
	 *
	 * @return	The new top of the expression tree.
	 *
	 * @exception StandardException	Thrown on error
	 */

    ValueNode bindExpression(FromList fromList,
                             SubqueryList subqueryList,
                             List<AggregateNode> aggregates,
                             boolean forQueryRewrite) throws StandardException
	{
		/* There are a bizillion classes which extend ValueNode.  Here is info
		 * on some of the classes that bindExpression() should not be called on
		 * and why:
		 *	o  BaseColumnNodes should only appear under the ResultColumnList
		 *     in the FromBaseTable.  They are created/bound when binding the
		 *     FromBaseTable.
		 */
		if (SanityManager.DEBUG)
		{
			SanityManager.ASSERT(false,
						"bindExpression() not expected to be called on a " +
						this.getClass().toString());
		}

		return this;
	}

	/**
	 * Generate a SQL->Java->SQL conversion tree above the current node
	 * and bind the new nodes individually.
	 * This is useful when doing comparisons, built-in functions, etc. on
	 * java types which have a direct mapping to system built-in types.
	 *
	 * @return ValueNode	The new tree.
	 *
	 * @exception StandardException	Thrown on error
	 */
    ValueNode genSQLJavaSQLTree()
		throws StandardException
	{
		if (SanityManager.DEBUG)
		{
			SanityManager.ASSERT(getTypeId() != null,
				"genSQLJavaSQLTree() only expected to be called on a bound node");
			SanityManager.ASSERT(getTypeId().userType(),
				"genSQLJavaSQLTree() only expected to be called on user types");
		}

        final ContextManager cm = getContextManager();
        JavaValueNode stjvn = new SQLToJavaValueNode(this, cm);

        ValueNode jtsvn = new JavaToSQLValueNode(stjvn, cm);

        DataTypeDescriptor  resultType;
        if ( (getTypeServices() != null) && getTypeId().userType() ) { resultType = getTypeServices(); }
        else { resultType = DataTypeDescriptor.getSQLDataTypeDescriptor(stjvn.getJavaTypeName()); }

		jtsvn.setType( resultType );

		return jtsvn;
	}

	/**
	 * Preprocess an expression tree.  We do a number of transformations
	 * here (including subqueries, IN lists, LIKE and BETWEEN) plus
	 * subquery flattening.
	 * NOTE: This is done before the outer ResultSetNode is preprocessed.
	 *
	 * @param	numTables			Number of tables in the DML Statement
	 * @param	outerFromList		FromList from outer query block
	 * @param	outerSubqueryList	SubqueryList from outer query block
	 * @param	outerPredicateList	PredicateList from outer query block
	 *
	 * @return		The modified expression
	 *
	 * @exception StandardException		Thrown on error
	 */
    ValueNode preprocess(int numTables,
								FromList outerFromList,
								SubqueryList outerSubqueryList,
								PredicateList outerPredicateList)
					throws StandardException
	{
		return this;
	}

    /**
     * If this node is known to always evaluate to the same value, return a
     * node that represents that known value as a constant. Typically used to
     * transform operators with constant operands into constants.
     *
     * @return a constant representing the value to which this node is
     * guaranteed to evaluate, or {@code this} if the value is not known
     * @throws StandardException if an error occurs during evaluation
     * @see ConstantExpressionVisitor
     */
    ValueNode evaluateConstantExpressions() throws StandardException {
        // We normally don't know what the node evaluates to up front, so
        // don't do anything in the default implementation.
        return this;
    }

	/**
	 * Eliminate NotNodes in the current query block.  We traverse the tree,
	 * inverting ANDs and ORs and eliminating NOTs as we go.  We stop at
	 * ComparisonOperators and boolean expressions.  We invert
	 * ComparisonOperators and replace boolean expressions with
	 * boolean expression = false.
	 * NOTE: Since we do not recurse under ComparisonOperators, there
	 * still could be NotNodes left in the tree.
	 *
	 * @param	underNotNode		Whether or not we are under a NotNode.
	 *
	 *
	 * @return		The modified expression
	 *
	 * @exception StandardException		Thrown on error
	 */
	ValueNode eliminateNots(boolean underNotNode)
					throws StandardException
	{
		if (! underNotNode)
		{
			return this;
		}

		/* bind() has ensured that this node's type is SQLBoolean */
		if (SanityManager.DEBUG)
		SanityManager.ASSERT(
				getTypeId().isBooleanTypeId(),
					"Node's type (" +
					getTypeId().getSQLTypeName() +
					") is expected to be boolean");

		/* Return ValueNode = false */
		return genEqualsFalseTree();
	}

	/**
	 * Transform this into this = false.  Useful for NOT elimination.
	 *
	 *
	 * @return		The modified expression
	 *
	 * @exception StandardException		Thrown on error
	 */
    ValueNode genEqualsFalseTree()
			throws StandardException
	{
		BinaryRelationalOperatorNode equalsNode;
		BooleanConstantNode		 falseNode;
		boolean 				nullableResult;

        falseNode = new BooleanConstantNode(false, getContextManager());
        equalsNode = new BinaryRelationalOperatorNode(
                BinaryRelationalOperatorNode.K_EQUALS,
                this,
                falseNode,
                false,
                getContextManager());
		nullableResult = getTypeServices().isNullable();
		equalsNode.setType(new DataTypeDescriptor(
									TypeId.BOOLEAN_ID,
									nullableResult)
						  );
		return equalsNode;
	}

	/**
     * Transform this into this IS NULL or IS NOT NULL.
	 *
     * @param notNull if true, transform this into IS NOT NULL;
     *                otherwise, transform this into IS NULL
	 * @return		The modified expression
	 *
	 * @exception StandardException		Thrown on error
	 */
    ValueNode genIsNullTree(boolean notNull)
			throws StandardException
	{
		IsNullNode isNullNode;

        isNullNode = new IsNullNode(this, notNull, getContextManager());
		isNullNode.setType(new DataTypeDescriptor(
									TypeId.BOOLEAN_ID,
									false)
						  );
		return isNullNode;
	}

	/**
	 * Verify that eliminateNots() did its job correctly.  Verify that
	 * there are no NotNodes above the top level comparison operators
	 * and boolean expressions.
	 *
	 * @return		Boolean which reflects validity of the tree.
	 */
	boolean verifyEliminateNots()
	{
		if (SanityManager.ASSERT)
		{
			return (! (this instanceof NotNode));
		}
		else
		{
			return true;
		}
	}

	/**
	 * Do the 1st step in putting an expression into conjunctive normal
	 * form.  This step ensures that the top level of the expression is
	 * a chain of AndNodes.
	 *
	 * @return		The modified expression
	 *
	 * @exception StandardException		Thrown on error
	 */
    ValueNode putAndsOnTop()
					throws StandardException
	{
        BooleanConstantNode trueNode =
                new BooleanConstantNode(true, getContextManager());
        AndNode andNode = new AndNode(this, trueNode, getContextManager());
		andNode.postBindFixup();
		return andNode;
	}

	/**
	 * Verify that putAndsOnTop() did its job correctly.  Verify that the top level
	 * of the expression is a chain of AndNodes.
	 *
	 * @return		Boolean which reflects validity of the tree.
	 */
    boolean verifyPutAndsOnTop()
	{
		return true;
	}

	/**
	 * Finish putting an expression into conjunctive normal
	 * form.  An expression tree in conjunctive normal form meets
	 * the following criteria:
	 *		o  If the expression tree is not null,
	 *		   the top level will be a chain of AndNodes terminating
	 *		   in a true BooleanConstantNode.
	 *		o  The left child of an AndNode will never be an AndNode.
	 *		o  Any right-linked chain that includes an AndNode will
	 *		   be entirely composed of AndNodes terminated by a true BooleanConstantNode.
	 *		o  The left child of an OrNode will never be an OrNode.
	 *		o  Any right-linked chain that includes an OrNode will
	 *		   be entirely composed of OrNodes terminated by a false BooleanConstantNode.
	 *		o  ValueNodes other than AndNodes and OrNodes are considered
	 *		   leaf nodes for purposes of expression normalization.
	 *		   In other words, we won't do any normalization under
	 *		   those nodes.
	 *
	 * In addition, we track whether or not we are under a top level AndNode.
	 * SubqueryNodes need to know this for subquery flattening.
	 *
	 * @param	underTopAndNode		Whether or not we are under a top level AndNode.
	 *
	 *
	 * @return		The modified expression
	 *
	 * @exception StandardException		Thrown on error
	 */
    ValueNode changeToCNF(boolean underTopAndNode)
					throws StandardException
	{
		return this;
	}

	/**
	 * Verify that changeToCNF() did its job correctly.  Verify that:
	 *		o  AndNode  - rightOperand is not instanceof OrNode
	 *				      leftOperand is not instanceof AndNode
	 *		o  OrNode	- rightOperand is not instanceof AndNode
	 *					  leftOperand is not instanceof OrNode
	 *
	 * @return		Boolean which reflects validity of the tree.
	 */
    boolean verifyChangeToCNF()
	{
		return true;
	}

	/**
	 * Categorize this predicate.  Initially, this means
	 * building a bit map of the referenced tables for each predicate.
	 * If the source of this ColumnReference (at the next underlying level)
	 * is not a ColumnReference or a VirtualColumnNode then this predicate
	 * will not be pushed down.
	 *
	 * For example, in:
	 *		select * from (select 1 from s) a (x) where x = 1
	 * we will not push down x = 1.
	 * NOTE: It would be easy to handle the case of a constant, but if the
	 * inner SELECT returns an arbitrary expression, then we would have to copy
	 * that tree into the pushed predicate, and that tree could contain
	 * subqueries and method calls.
	 * RESOLVE - revisit this issue once we have views.
	 *
	 * @param referencedTabs	JBitSet with bit map of referenced FromTables
	 * @param simplePredsOnly	Whether or not to consider method
	 *							calls, field references and conditional nodes
	 *							when building bit map
	 *
	 * @return boolean		Whether or not source.expression is a ColumnReference
	 *						or a VirtualColumnNode.
	 *
	 * @exception StandardException			Thrown on error
	 */
    boolean categorize(JBitSet referencedTabs, boolean simplePredsOnly)
		throws StandardException
	{
		return true;
	}

	/**
	 * This returns the user-supplied schema name of the column.
	 * At this class level, it simply returns null. But, the subclasses
	 * of ValueNode will overwrite this method to return the
	 * user-supplied schema name.
	 *
	 * When the value node is in a result column of a select list,
	 * the user can request metadata information. The result column
	 * won't have a column descriptor, so we return some default
	 * information through the expression. This lets expressions that
	 * are simply columns return all of the info, and others use
	 * this supertype's default values.
	 *
	 * @return the default schema name for an expression -- null
	 */
    String getSchemaName() throws StandardException
	{
		return null;
	}

	/**
	 * This returns the user-supplied table name of the column.
	 * At this class level, it simply returns null. But, the subclasses
	 * of ValueNode will overwrite this method to return the
	 * user-supplied table name.
	 *
	 * When the value node is in a result column of a select list,
	 * the user can request metadata information. The result column
	 * won't have a column descriptor, so we return some default
	 * information through the expression. This lets expressions that
	 * are simply columns return all of the info, and others use
	 * this supertype's default values.
	 *
	 * @return the default table name for an expression -- null
	 */
    String getTableName()
	{
		return null;
	}

	/**
	 * @return the default updatability for an expression - false
	 */
	public boolean updatableByCursor()
	{
		return false;
	}

	/**
	 * This is null so that the caller will substitute in the resultset generated
	 * name as needed.
	 *
	 * @return the default column name for an expression -- null.
	 */
    String getColumnName()
	{
		return null;
	}

	/**
	 * Get a bit map of table references in this expression
	 *
	 * @return	A bit map of table numbers referred to in this expression
	 *
	 * @exception StandardException			Thrown on error
	 */
	JBitSet getTablesReferenced()
		throws StandardException
	{
		ReferencedTablesVisitor rtv = new ReferencedTablesVisitor(new JBitSet(0));
		accept(rtv);
		return rtv.getTableMap();
	}

	/**
	 * Return whether or not this expression tree is cloneable.
	 *
	 * @return boolean	Whether or not this expression tree is cloneable.
	 */
    boolean isCloneable()
	{
		return false;
	}

	/**
	 * Return a clone of this node.
	 *
	 * @return ValueNode	A clone of this node.
	 *
	 * @exception StandardException			Thrown on error
	 */
    ValueNode getClone() throws StandardException
	{
		if (SanityManager.DEBUG)
		{
			SanityManager.ASSERT(false,
				"getClone() not expected to be called for " +
				getClass().getName());
		}
		return null;
	}

	/**
	 * Copy all of the "appropriate fields" for a shallow copy.
	 *
	 * @param oldVN		The ValueNode to copy from.
	 *
	 */
    void copyFields(ValueNode oldVN) throws StandardException
	{
		dataTypeServices = oldVN.getTypeServices();
	}

	/**
	 * Remap all ColumnReferences in this tree to be clones of the
	 * underlying expression.
	 *
	 * @return ValueNode			The remapped expression tree.
	 *
	 * @exception StandardException			Thrown on error
	 */
    ValueNode remapColumnReferencesToExpressions() throws StandardException
	{
		return this;
	}

	/**
	 * Return whether or not this expression tree represents a constant expression.
	 *
	 * @return	Whether or not this expression tree represents a constant expression.
	 */
    boolean isConstantExpression()
	{
		return false;
	}

	/**
	 * Return whether or not this expression tree represents a constant value.
	 * In this case, "constant" means that it will always evaluate to the
	 * same thing, even if it includes columns.  A column is constant if it
	 * is compared to a constant expression.
	 *
	 * @return	True means this expression tree represents a constant value.
	 */
    boolean constantExpression(PredicateList whereClause)
	{
		return false;
	}

	/**
	 * Return the variant type for the underlying expression.
	 * The variant type can be:
	 *		VARIANT				- variant within a scan
	 *							  (method calls and non-static field access)
	 *		SCAN_INVARIANT		- invariant within a scan
	 *							  (column references from outer tables)
	 *		QUERY_INVARIANT		- invariant within the life of a query
	 *							  (constant expressions)
	 *
	 * @return	The variant type for the underlying expression.
	 * @exception StandardException		Thrown on error
	 */
	protected int getOrderableVariantType() throws StandardException
	{
		// The default is VARIANT
		return Qualifier.VARIANT;
	}

	/**
	  * Bind time logic. Raises an error if this ValueNode does not resolve to
	  *	a boolean value. This method is called by WHERE clauses.
	  *
	  *	@return	bound coercion of this node to a builtin type as necessary
	  *
	  * @exception StandardException		Thrown on error
	  */
	public	ValueNode	checkIsBoolean()
		throws StandardException
	{
		ValueNode	whereClause = this;

		/*
		** Is the datatype of the WHERE clause BOOLEAN?
		**
		** NOTE: This test is not necessary in SQL92 entry level, because
		** it is syntactically impossible to have a non-Boolean WHERE clause
		** in that level of the standard.  But we intend to extend the
		** language to allow Boolean user functions in the WHERE clause,
		** so we need to test for the error condition.
		*/
		TypeId whereTypeId = whereClause.getTypeId();

		/* If the where clause is not a built-in type, then generate a bound
		 * conversion tree to a built-in type.
		 */
		if (whereTypeId.userType())
		{
			whereClause = whereClause.genSQLJavaSQLTree();
			whereTypeId = whereClause.getTypeId();
		}

		if (! whereTypeId.equals(TypeId.BOOLEAN_ID))
		{
			throw StandardException.newException(SQLState.LANG_NON_BOOLEAN_WHERE_CLAUSE,
				whereTypeId.getSQLTypeName()
				);
		}

		return	whereClause;
	}

	/**
	 * Return an Object representing the bind time value of this
	 * expression tree.  If the expression tree does not evaluate to
	 * a constant at bind time then we return null.
	 * This is useful for bind time resolution of VTIs.
	 * RESOLVE: What do we do for primitives?
	 *
	 * @return	An Object representing the bind time value of this expression tree.
	 *			(null if not a bind time constant.)
	 *
	 * @exception StandardException		Thrown on error
	 */
	Object getConstantValueAsObject()
		throws StandardException
	{
		return null;
	}

	/////////////////////////////////////////////////////////////////////////
	//
	//	The ValueNode defers its generate() work to a method that works on
	//	ExpressionClassBuilders rather than ActivationClassBuilders. This
	//	is so that expression generation can be shared by the Core compiler
	//	AND the Replication Filter compiler.
	//
	/////////////////////////////////////////////////////////////////////////

	/**
	 * Do the code generation for this node.  Call the more general
	 * routine that generates expressions.
	 *
	 * @param acb	The ActivationClassBuilder for the class being built
	 * @param mb	The method the expression will go into
	 *
	 *
	 * @exception StandardException		Thrown on error
	 */
    @Override
    final void generate(ActivationClassBuilder acb, MethodBuilder mb)
								throws StandardException
	{
		generateExpression( acb, mb );
	}

	/**
	 * The default selectivity for value nodes is 50%.  This is overridden
	 * in specific cases, such as the RelationalOperators.
	 */
	public double selectivity(Optimizable optTable)
	throws StandardException
	{
		// Return 1 if additional predicates have been generated from this one.
		if (transformed)
		{
			return 1.0;
		}
		else
		{
			return 0.5d;
		}
	}

	/**
	 * Update the array of columns in = conditions with expressions without
	 * column references from the same table.  This is useful when doing
	 * subquery flattening on the basis of an equality condition.
	 * eqOuterCols or tableColMap may be null if the calling routine
	 * doesn't need the information provided
	 *
	 * @param tableNumber	The tableNumber of the table from which
	 *						the columns of interest come from.
	 * @param eqOuterCols	Array of booleans for noting which columns
	 *						are in = predicates without columns from the
	 *						subquery block. May be null.
	 * @param tableNumbers	Array of table numbers in this query block.
	 * @param tableColMap	Array of bits for noting which columns
	 *						are in = predicates for each table in the
	 *						query block. May be null.
	 * @param resultColTable True if tableNumber is the table containing result
	 * 						columns
	 *
	 * @exception StandardException			Thrown on error
	 *
	 */
	void checkTopPredicatesForEqualsConditions(
				int tableNumber, boolean[] eqOuterCols, int[] tableNumbers,
				JBitSet[] tableColMap, boolean resultColTable)
		throws StandardException
	{
		for (ValueNode whereWalker = this; whereWalker instanceof AndNode;
			 whereWalker = ((AndNode) whereWalker).getRightOperand())
		{
			// See if this is a candidate =
			AndNode and = (AndNode) whereWalker;

			if (!and.getLeftOperand().isRelationalOperator() ||
				!(((RelationalOperator)(and.getLeftOperand())).getOperator() == RelationalOperator.EQUALS_RELOP))
			{
				continue;
			}

			BinaryRelationalOperatorNode beon =
					(BinaryRelationalOperatorNode) and.getLeftOperand();
			ValueNode left = beon.getLeftOperand();
			ValueNode right = beon.getRightOperand();
			int resultTable = 0;
			if (resultColTable)
			{
				for ( ; resultTable < tableNumbers.length; resultTable++)
				{
					if (tableNumbers[resultTable] == tableNumber)
						break;
				}
			}
			else
				resultTable = -1;

			/* Is this = of the right form? */
			if ((left instanceof ColumnReference) &&
				((ColumnReference) left).getTableNumber() == tableNumber)
			{
				updateMaps(tableColMap, eqOuterCols, tableNumbers, tableNumber,
					resultTable, right, left);
			}
			else if ((right instanceof ColumnReference) &&
					 ((ColumnReference) right).getTableNumber() == tableNumber)
			{
				updateMaps(tableColMap, eqOuterCols, tableNumbers, tableNumber,
					resultTable, left, right);
			}
		}
	}

	/**
	 * Does this represent a true constant.
	 *
	 * @return Whether or not this node represents a true constant.
	 */
	boolean isBooleanTrue()
	{
		return false;
	}

	/**
	 * Does this represent a false constant.
	 *
	 * @return Whether or not this node represents a false constant.
	 */
	boolean isBooleanFalse()
	{
		return false;
	}

	/**
	 * Generate code for this calculation.  This is a place-holder method -
	 * it should not be called.
	 *
	 * @param acb	The ExpressionClassBuilder for the class being built
	 * @param mb	The method the expression will go into
	 *
	 *
	 * @exception StandardException		Thrown on error
	 */

    void generateExpression(ExpressionClassBuilder acb, MethodBuilder mb)
						throws StandardException
	{
		if (SanityManager.DEBUG)
		SanityManager.ASSERT(false, "Code generation for this type of ValueNode is unimplemented");
	}

	/**
	 * Set the correct bits in tableColMap and set the boolean value in eqOuterCols
	 * given two arguments to an = predicate
	 * tableColMap[t] - bit is set if the column is in an = predicate with a column
	 *					in table t, or a bit is set if the column is in an
	 *					= predicate with a constant,parameter or correlation variable
	 *				    (for all table t, if this tableColMap is not for the
  	 *					table with the result columns)
	 * eqOuterCols[c] - is true if the column is in an = predicate with a constant,
	 *					parameter or correlation variable
	 *
	 *
	 * @param tableColMap	Array of bitmaps for noting which columns are in =
	 *						predicates with columns from each table
	 * @param eqOuterCols	Array of booleans for noting which columns
	 *						are in = predicates without columns from the
	 *						subquery block.
	 * @param tableNumber	table number for which we are setting up the Maps
	 * @param resultTable	-1 if this table is not the result table; otherwise
	 *						the index into tableNumbers for the result table
	 * @param arg1			one side of the = predicate
	 * @param arg2			other side of the = predicate
	 *
	 *
	 * @exception StandardException		Thrown on error
	 */
	private void updateMaps(JBitSet[] tableColMap, boolean[] eqOuterCols,
		int[] tableNumbers,  int tableNumber, int resultTable,
		ValueNode arg1, ValueNode arg2)
			throws StandardException
	{
		/* arg2 is a column from our table.  This
		 * is a good = for both All tables and Outer arrays
		 * if the right side is a constant or a parameter
		 * or a column from an outer table.
		 * It is a good = for only the All array if
		 * the right side is a column from this query block.
		 */
		if ((arg1 instanceof ConstantNode) || (arg1.requiresTypeFromContext()))
		{
			setValueCols(tableColMap, eqOuterCols,
				((ColumnReference) arg2).getColumnNumber(), resultTable);
		}
		else if((arg1 instanceof ColumnReference &&
					((ColumnReference) arg1).getTableNumber() != tableNumber))
		{
			/* See if other columns is a correlation column */
			int otherTN = ((ColumnReference) arg1).getTableNumber();
			int index = 0;
			int colNumber =	((ColumnReference) arg2).getColumnNumber();

			for ( ; index < tableNumbers.length; index++)
			{
				if (otherTN == tableNumbers[index])
				{
					break;
				}
			}
			/* Correlation column, so we can treat it as a constant */
			if (index == tableNumbers.length)
			{
				setValueCols(tableColMap, eqOuterCols, colNumber, resultTable);
			}
			else if (tableColMap != null)
			{
				tableColMap[index].set(colNumber);
			}

		}
		else
		{
			/* See if other side contains a column reference from the same table */
			JBitSet referencedTables = arg1.getTablesReferenced();
			/* See if other columns are all correlation columns */
			int index = 0;
			int colNumber =	((ColumnReference) arg2).getColumnNumber();
			for ( ; index < tableNumbers.length; index++)
			{
				if (referencedTables.get(tableNumbers[index]))
				{
					break;
				}
			}
			/* Correlation column, so we can treat it as a constant */
			if (index == tableNumbers.length)
			{
				setValueCols(tableColMap, eqOuterCols, colNumber, resultTable);
			}
			else if (tableColMap != null && !referencedTables.get(tableNumber))
			{
				tableColMap[index].set(colNumber);
			}
		}
	}
	/**
	 * Set eqOuterCols and the column in all the tables for constants,
	 * parmeters and correlation columns
	 * The column in the tableColMap is set only for the current table
	 * if the table is the result column table.  For other tables in the
	 * query we set the column for all the tables since the constant will
	 * reduced the number of columns required in a unique multicolumn index for
	 * distinctness.
	 * For example, given an unique index on t1(a,b), setting b=1 means that
	 * t1(a) is unique since there can be no duplicates for a where b=1 without
	 * destroying the uniqueness of t1(a,b).  However, for the result columns
	 * setting b=1, does not mean that a select list of t1.a is distinct if
	 * t1.a is the only column used in joining with another table
	 * e.g. select t1.a from t1, t2 where t1.a = t2.a and t1.b = 1;
	 *
	 * 	t1			t2			result
	 *	a	b		a			a
	 *  1	1		1			1
	 *  1 	2		2			1
	 *	2	1
	 *
	 *
	 * @param tableColMap	Array of bitmaps for noting which columns are in =
	 *						predicates with columns from each table
	 * @param eqOuterCols	Array of booleans for noting which columns
	 *						are in = predicates without columns from the
	 *						subquery block.
	 * @param colReference	The column to set
	 * @param resultTable	If -1 set all the bit for all the tables for that
	 *						column; otherwise set the bit for the specified table
	 *
	 *
	 */
	private void setValueCols(JBitSet[] tableColMap, boolean[] eqOuterCols,
		int colReference, int resultTable)
	{
		if (eqOuterCols != null)
			eqOuterCols[colReference] = true;

		if (tableColMap != null)
		{
			if (resultTable == -1)
			{
				for (int i = 0; i < tableColMap.length; i++)
					tableColMap[i].set(colReference);
			}
			else
				tableColMap[resultTable].set(colReference);
		}
	}

	/**
	 * Returns true if this ValueNode is a relational operator. Relational
	 * Operators are <, <=, =, >, >=, <> as well as IS NULL and IS NOT
	 * NULL. This is the preferred way of figuring out if a ValueNode is
	 * relational or not.
	 * @see RelationalOperator
	 * @see BinaryRelationalOperatorNode
	 * @see IsNullNode
	*/
    boolean isRelationalOperator()
	{
		return false;
	}

	/**
	 * Returns true if this value node is a <em>equals</em> operator.
	 *
	 * @see ValueNode#isRelationalOperator
	 */
    boolean isBinaryEqualsOperatorNode()
	{
		return false;
	}

	/**
	 * Returns true if this value node is an operator created
	 * for optimized performance of an IN list.
	 *
	 * Or more specifically, returns true if this value node is
	 * an equals operator of the form "col = ?" that we generated
	 * during preprocessing to allow index multi-probing.
	 */
    boolean isInListProbeNode()
	{
		return false;
	}

	/** Return true if the predicate represents an optimizable equality node.
	 * an expression is considered to be an optimizable equality node if all the
	 * following conditions are met:
	 * <ol>
	 * <li> the operator is an <em>=</em> or <em>IS NULL</em> operator </li>
	 * <li> one of the operands is a column specified by optTable/columnNumber</li>
	 * <li> Both operands are not the same column; i.e tab.col = tab.col </li>
	 * <li> There are no implicit varchar comparisons of the operands; i.e
	 * either both operands are string like (varchar, char, longvarchar) or
	 * neither operand is string like </li>
	 * </ol>
	 *
	 * @param optTable	the table being optimized. Column reference must be from
	 * this table.
	 * @param columnNumber the column number. One of the operands of this
	 * predicate must be the column number specified by optTable/columnNumber
	 * @param isNullOkay if set to true we also consider IS NULL predicates;
	 * otherwise consider only = predicates.
	 */
    boolean optimizableEqualityNode(Optimizable optTable,
										   int columnNumber,
										   boolean isNullOkay)
		throws StandardException
	{
		return false;
	}

	/**
	 * Returns TRUE if the type of this node will be determined from the
	 * context in which it is getting used. If true is returned then
     * after bindExpression() is called on the node, its type
     * must be set (from the relevant context) using setType().
	 *
	 * @return Whether this node's type will be determined from the context
	 */
    boolean requiresTypeFromContext()
	{
		return false;
	}

	/**
	 * Returns TRUE if this is a parameter node. We do lots of special things
	 * with Parameter Nodes.
	 *
	 */
    boolean isParameterNode()
	{
		return false;
	}

	/**
	 * Tests if this node is equivalent to the specified ValueNode. Two
	 * ValueNodes are considered equivalent if they will evaluate to the same
	 * value during query execution.
	 * <p>
	 * This method provides basic expression matching facility for the derived
	 * class of ValueNode and it is used by the language layer to compare the
	 * node structural form of the two expressions for equivalence at bind
	 * phase.
	 *  <p>
	 * Note that it is not comparing the actual row values at runtime to produce
	 * a result; hence, when comparing SQL NULLs, they are considered to be
	 * equivalent and not unknown.
	 *  <p>
	 * One usage case of this method in this context is to compare the select
	 * column expression against the group by expression to check if they are
	 * equivalent.  e.g.:
	 *  <p>
	 * SELECT c1+c2 FROM t1 GROUP BY c1+c2
	 *  <p>
	 * In general, node equivalence is determined by the derived class of
	 * ValueNode.  But they generally abide to the rules below:
	 *  <ul>
	 * <li>The two ValueNodes must be of the same node type to be considered
	 *   equivalent.  e.g.:  CastNode vs. CastNode - equivalent (if their args
	 *   also match), ColumnReference vs CastNode - not equivalent.
	 *
	 * <li>If node P contains other ValueNode(s) and so on, those node(s) must
	 *   also be of the same node type to be considered equivalent.
	 *
	 * <li>If node P takes a parameter list, then the number of arguments and its
	 *   arguments for the two nodes must also match to be considered
	 *   equivalent.  e.g.:  CAST(c1 as INTEGER) vs CAST(c1 as SMALLINT), they
	 *   are not equivalent.
	 *
	 * <li>When comparing SQL NULLs in this context, they are considered to be
	 *   equivalent.
	 *
	 * <li>If this does not apply or it is determined that the two nodes are not
	 *   equivalent then the derived class of this method should return false;
	 *   otherwise, return true.
	 * </ul>
	 *
	 * @param other the node to compare this ValueNode against.
	 * @return <code>true</code> if the two nodes are equivalent,
	 * <code>false</code> otherwise.
	 *
	 * @throws StandardException
	 */
    abstract boolean isEquivalent(ValueNode other)
		throws StandardException;

    /**
     * Some node classes represent several logical node types (to reduce
     * footprint), which we call <em>kinds</em>.
     * This means that implementations of {@link #isEquivalent}
     * cannot always just use {@code instanceof} to check if the other node
     * represents the same kind. Hence this method needs to be
     * overridden by all node classes that represent several kinds.
     * This default implementation does not look at kinds.
     * It is only called from implementations of {@code isEquivalent}.
     *
     * @param other The other value node whose kind we want to compare with.
     * @return {@code true} if {@code this} and {@code o} represent the same
     *         logical node type, i.e. kind.
     */
    boolean isSameNodeKind(ValueNode other) {
        // Default implementation does not look at kinds.
        return other != null && other.getClass().equals(this.getClass());
    }
}


text:
// -*- C++ -*-

//=============================================================================
/**
 *  @file    ArrayDef_i.h
 *
 *  $Id: ArrayDef_i.h 1861 2011-08-31 16:18:08Z mesnierp $
 *
 *  ArrayDef servant class.
 *
 *
 *  @author Jeff Parsons <parsons@cs.wustl.edu>
 */
//=============================================================================

#ifndef TAO_ARRAYDEF_I_H
#define TAO_ARRAYDEF_I_H

#include "orbsvcs/IFRService/IDLType_i.h"
#include "orbsvcs/IFRService/ifr_service_export.h"

#if !defined (ACE_LACKS_PRAGMA_ONCE)
# pragma once
#endif /* ACE_LACKS_PRAGMA_ONCE */

#if defined(_MSC_VER)
#pragma warning(push)
#pragma warning(disable:4250)
#endif /* _MSC_VER */

TAO_BEGIN_VERSIONED_NAMESPACE_DECL

/**
 * @class TAO_ArrayDef_i
 *
 * @brief TAO_ArrayDef_i
 *
 * Represents an IDL array type.
 */
class TAO_IFRService_Export TAO_ArrayDef_i : public virtual TAO_IDLType_i
{
public:
  /// Constructor
  TAO_ArrayDef_i (TAO_Repository_i *repo);

  /// Destructor
  virtual ~TAO_ArrayDef_i (void);

  /// Return our definition kind.
  virtual CORBA::DefinitionKind def_kind ();

  /// Remove the repository entry.
  virtual void destroy ();

  virtual void destroy_i ();

  virtual CORBA::TypeCode_ptr type ();

  virtual CORBA::TypeCode_ptr type_i ();

  virtual CORBA::ULong length ();

  CORBA::ULong length_i ();

  virtual void length (CORBA::ULong length);

  void length_i (CORBA::ULong length);

  virtual CORBA::TypeCode_ptr element_type ();

  CORBA::TypeCode_ptr element_type_i ();

  virtual CORBA::IDLType_ptr element_type_def ();

  CORBA::IDLType_ptr element_type_def_i ();

  virtual void element_type_def (CORBA::IDLType_ptr element_type_def);

  void element_type_def_i (CORBA::IDLType_ptr element_type_def);

private:
  /// Destroys an anonymous non-primitive element type.
  void destroy_element_type ();
};

TAO_END_VERSIONED_NAMESPACE_DECL

#if defined(_MSC_VER)
#pragma warning(pop)
#endif /* _MSC_VER */

#endif /* TAO_ARRAYDEF_I_H */


text:
class ApplicationController < ActionController::API
  before_filter :cors_preflight_check, :restrict_access
  after_filter :call_callback, :cors_set_access_control_headers

  # For all responses in this controller, return the CORS access control headers.
  def cors_set_access_control_headers
    headers['Access-Control-Allow-Origin'] = '*'
    headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS, PUT, DELETE'
    headers['Access-Control-Max-Age'] = "1728000"
  end

  # If this is a preflight OPTIONS request, then short-circuit the
  # request, return only the necessary headers and return an empty
  # text/plain.
  def cors_preflight_check
    if request.method == :options
      headers['Access-Control-Allow-Origin'] = '*'
      headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS, PUT, DELETE'
      headers['Access-Control-Allow-Headers'] = 'X-Requested-With, X-Prototype-Version'
      headers['Access-Control-Max-Age'] = '1728000'
      render :text => '', :content_type => 'text/plain'
    end
  end

  # Method called in every API where is mandatory (via before filter) to confirm user is the master of the requested resource
  def authorize_resource
    head :unauthorized  unless !@user_id.nil? and @user_id.user_reference.to_s == params[:user_id]
  end

  private

  def is_admin
    return @user_id.is_admin?
  end

  # Method called in every API (via before filter) to check token validity. The token must be passet via GET patameter "st"
  def restrict_access
    logger.debug "Inside Restrict Access"
    unless controller_name == 'semi_static'

      user_id_from_api=nil

      unless controller_name == 'dns_server_statuses' or controller_name == 'dns_server_logs' or controller_name == 'dns_datas'
        if params[:auth_method] == 'zotsell' or (params[:auth_method].nil? and Settings.auth_method == 'zotsell')
          user_id_from_api=check_token_on_zotsell params[:st]
        elsif params[:auth_method] == 'keystone' or (params[:auth_method].nil? and Settings.auth_method == 'keystone')
          # key,value = request.query_string.split '=',2
          user_id_from_api = check_token_on_keystone params[:st] #value
        elsif params[:auth_method] == 'openebula' or (params[:auth_method].nil? and Settings.auth_method == 'openebula')
          user_id_from_api=check_token_on_zotsell params[:st]
        elsif params[:auth_method] == 'oauth2' or (params[:auth_method].nil? and Settings.auth_method == 'oauth2')
          logger.debug "Scelgo OAuth2 per l'autenticazione"
          user_id_from_api=check_token_on_oauth2(params[:st],request.headers['X-Auth-Token'])
          logger.debug "user_id_from_api dopo oauth2: #{user_id_from_api}"
        end
      end

      if user_id_from_api.nil? or !user_id_from_api
        logger.debug 'user not found, trying with api'
        unless params[:api_key].nil?
          api_account = ApiAccount.find(params[:api_key])
          logger.debug "Api Secret: " + api_account.api_secret.to_s
          logger.debug "Api Secret: " + params[:api_secret]
          logger.debug "#{api_account.api_secret == params[:api_secret]}"
          logger.debug "Controller name: " + controller_name.to_s
          logger.debug "Controller name included: #{api_account.rights.include?(controller_name)}"

          user_id_from_api = api_account.user.user_reference if api_account.api_secret == params[:api_secret] and
              api_account.rights.include?(controller_name)

          logger.debug "User reference: #{api_account.user.user_reference}"
          logger.debug "User ID prima dell'uscita #{user_id_from_api}"
        end
      end

      logger.debug "User from api key/secret: #{user_id_from_api}"

      if user_id_from_api.nil? || !user_id_from_api
        head :unauthorized
      else
        logger.debug("User ID from api: #{user_id_from_api}")
        begin
          @user_id = User.find(user_id_from_api)
        rescue
          @user_id = User.create(:user_reference => user_id_from_api)
        end
        # @user_id.save
      end
    end
  end

  # Check the token validity in Zotsell compatible SSO
  def check_token_on_zotsell(token)
    url = URI.parse("#{Settings.auth_zotsell_url}#{Settings.token_zotsell_path}")
    req = Net::HTTP::Post.new(url.path)
    req.set_form_data({:token => token})
    sock = Net::HTTP.new(url.host, url.port)
    if Settings.auth_zotsell_url.starts_with? 'https'
      sock.use_ssl = true
      sock.verify_mode = OpenSSL::SSL::VERIFY_NONE
    end
    response=sock.start {|http| http.request(req) }
    begin
      parsed = JSON.parse(response.body)

      if parsed['status'].to_i == 1
        return parsed['info']['uid']  + '-zotsell'
      else
        false
      end

    rescue
      false
    end
  end

  # Check the token validity in OpenStack Keystone SSO
  def check_token_on_keystone(token)
    url = URI.parse("#{Settings.auth_keystone_url}#{Settings.token_keystone_path}")

    payload = {
        "auth" => {
            "passwordCredentials" => {
                "username" => Settings.keystone_admin_user,
                "password" => Settings.keystone_admin_password
            },
            "tenantId"=> Settings.keystone_admin_tenant
        }
    }
    # Retrieve the admin token
    admin_token_req = Net::HTTP::Post.new(url.path, initheader = {'Content-Type' =>'application/json'})
    admin_token_req.body = payload.to_json
    sock = Net::HTTP.new(url.host, url.port)
    if Settings.auth_keystone_url.starts_with? 'https'
      sock.use_ssl = true
      sock.verify_mode = OpenSSL::SSL::VERIFY_NONE
    end
    begin
      response=sock.start {|http| http.request(admin_token_req) }
      parsed = JSON.parse(response.body)
      logger.debug "Admin token: #{parsed['access']['token']['id']}"
      keystone_admin_token = parsed['access']['token']['id']

    rescue
      keystone_admin_token = false
    end
    if keystone_admin_token
      url = URI.parse("#{Settings.auth_keystone_url}#{Settings.token_keystone_path}#{token}")
      user_id_req = Net::HTTP::Get.new(url.path, initheader = {'X-Auth-Token' => keystone_admin_token})
      sock = Net::HTTP.new(url.host, url.port)
      if Settings.auth_keystone_url.starts_with? 'https'
        sock.use_ssl = true
        sock.verify_mode = OpenSSL::SSL::VERIFY_NONE
      end
      begin
        response=sock.start {|http| http.request(user_id_req) }
        parsed = JSON.parse(response.body)
        if parsed['access']['token']['tenant']['id'].nil?
          return parsed['access']['user']['id'] + '-keystone'
        else
          return parsed['access']['user']['id'] + '-' + parsed['access']['token']['tenant']['id'] + '-keystone'
        end
      rescue
        false
      end
    else
      false
    end
  end

  # Check the token validity in OpenNebula Auth system
  def check_token_on_opennebula(token)
    false
  end

  # Check the token validity in OAuth2 system
  def check_token_on_oauth2(st,hd)
    token = st || hd
    begin
      user_from_token = JSON.parse(JWT.decode(token, Settings.oauth2_id).first)
      logger.debug user_from_token
    rescue
      logger.debug 'Token not correct: '
      logger.debug token unless token.nil?
      return false
    end
    url = URI.parse("#{Settings.auth_oauth2_url}#{Settings.token_oauth2_path}/?format=json")
    logger.debug "url: #{url}, token: #{token}"
    req = Net::HTTP::Post.new(url.path, initheader = {'Authorization' => token})

    sock = Net::HTTP.new(url.host, url.port)
    if Settings.auth_oauth2_url.starts_with? 'https'
      sock.use_ssl = true
      sock.verify_mode = OpenSSL::SSL::VERIFY_NONE
    end
    response=sock.start {|http| http.request(req) }
    begin
      logger.debug 'Dati da oauth2'
      logger.debug response.body

      if response.body == 'Error'
        false
      elsif user_from_token.nil? or user_from_token["_id"].nil? or user_from_token["_id"]["$oid"].nil? or user_from_token.blank? or user_from_token["_id"].blank? or user_from_token["_id"]["$oid"].blank?
        false
      else
        user_from_token["_id"]["$oid"] + '-oauth2'
      end

    rescue

      false
    end
  end

  # Check admin credential
  #def check_admin
  #  unless params[:key] == Settings.admin_key and params[:password] == Settings.admin_password
  #    head :unauthorized
  #  end
  #end

  # Method called after every action that calls a callback URL to notify your App of the action done by the user
  def call_callback
    if Settings.send_callback == 'true'
      logger.debug "Call callback #{controller_name} - #{action_name} - #{params}"
      url = URI.parse("#{Settings.callback_url}#{Settings.callback_path}")
      if Settings.callback_method == 'POST'
        req = Net::HTTP::Post.new(url.path)
      else
        req = Net::HTTP::Get.new(url.path)
      end

      req.set_form_data({:params => params})
      sock = Net::HTTP.new(url.host, url.port)
      if Settings.callback_url.starts_with? 'https'
        sock.use_ssl = true
        sock.verify_mode = OpenSSL::SSL::VERIFY_NONE
      end
      response=sock.start {|http| http.request(req) }
    end
  end

  # Method to check if a record is enabled
  def enabled?(parameter)
    (parameter.upcase == 'TRUE') or (parameter == '1') or (parameter == 1) or (parameter == true)
  end

end


text:
<!doctype html>

    <meta charset="utf-8">
    <title>Blog</title>
    <link rel="stylesheet" href="/assets/css/styles.css">

    Home

    About

    Blog

    Staff

Latest Posts

Kiwifruit

Kiwifruit (often abbreviated as kiwi), or Chinese gooseberry is the edible
berry of several species of woody vines in the genus Actinidia.

The most common cultivar group of kiwifruit is oval, about the size of a large
hen's egg (5–8 cm (2.0–3.1 in) in length and 4.5–5.5 cm (1.8–2.2 in) in
diameter). It has a fibrous, dull greenish-brown skin and bright green or
golden flesh with rows of tiny, black, edible seeds. The fruit has a soft
texture, with a sweet and unique flavor.

Apples

An apple is a sweet, edible fruit produced by an apple tree.

Apple trees are cultivated worldwide, and are the most widely grown species in
the genus Malus. The tree originated in Central Asia, where its wild ancestor,
Malus sieversii, is still found today. Apples have been grown for thousands of
years in Asia and Europe, and were brought to North America by European
colonists.

Bananas

A banana is an edible fruit – botanically a berry – produced by several kinds
of large herbaceous flowering plants in the genus Musa.

In some countries, bananas used for cooking may be called "plantains",
distinguishing them from dessert bananas. The fruit is variable in size, color,
and firmness, but is usually elongated and curved, with soft flesh rich in
starch covered with a rind, which may be green, yellow, red, purple, or brown
when ripe.


text:
#include <stdio.h>
#include <string.h>

#include <rte_eal.h>
#include <rte_lcore.h>
#include <rte_debug.h>
#include <rte_memzone.h>
#include <rte_timer.h>
#include <rte_cycles.h>
#include <rte_mempool.h>
#include <rte_random.h>

#include "test.h"

#ifdef RTE_EXEC_ENV_WINDOWS
int
test_timer_secondary(void)
{
	printf("timer_secondary not supported on Windows, skipping test\n");
	return TEST_SKIPPED;
}
#else

#include "process.h"

#define NUM_TIMERS		(1 << 20) /* ~1M timers */
#define NUM_LCORES_NEEDED	3
#define TEST_INFO_MZ_NAME	"test_timer_info_mz"
#define MSECPERSEC		1E3

#define launch_proc(ARGV) process_dup(ARGV, RTE_DIM(ARGV), __func__)

struct test_info {
	unsigned int main_lcore;
	unsigned int mgr_lcore;
	unsigned int sec_lcore;
	uint32_t timer_data_id;
	volatile int expected_count;
	volatile int expired_count;
	struct rte_mempool *tim_mempool;
	struct rte_timer *expired_timers[NUM_TIMERS];
	int expired_timers_idx;
	volatile int exit_flag;
};

static int
timer_secondary_spawn_wait(unsigned int lcore)
{
	char coremask[10];
#ifdef RTE_EXEC_ENV_LINUXAPP
	char tmp[PATH_MAX] = {0};
	char prefix[PATH_MAX] = {0};

	get_current_prefix(tmp, sizeof(tmp));

	snprintf(prefix, sizeof(prefix), "--file-prefix=%s", tmp);
#else
	const char *prefix = "";
#endif
	char const *argv[] = {
		prgname,
		"-c", coremask,
		"--proc-type=secondary",
		prefix
	};

	snprintf(coremask, sizeof(coremask), "%x", (1 << lcore));

	return launch_proc(argv);
}

static void
handle_expired_timer(struct rte_timer *tim)
{
	struct test_info *test_info = tim->arg;

	test_info->expired_count++;
	test_info->expired_timers[test_info->expired_timers_idx++] = tim;
}

static int
timer_manage_loop(void *arg)
{
#define TICK_MSECS 1
	uint64_t tick_cycles = TICK_MSECS * rte_get_timer_hz() / MSECPERSEC;
	uint64_t prev_tsc = 0, cur_tsc, diff_tsc;
	struct test_info *test_info = arg;

	while (!test_info->exit_flag) {
		cur_tsc = rte_rdtsc();
		diff_tsc = cur_tsc - prev_tsc;

		if (diff_tsc > tick_cycles) {
			/* Scan timer list for expired timers */
			rte_timer_alt_manage(test_info->timer_data_id,
					     NULL,
					     0,
					     handle_expired_timer);

			/* Return expired timer objects back to mempool */
			rte_mempool_put_bulk(test_info->tim_mempool,
					     (void **)test_info->expired_timers,
					     test_info->expired_timers_idx);

			test_info->expired_timers_idx = 0;

			prev_tsc = cur_tsc;
		}

		rte_pause();
	}

	return 0;
}

int
test_timer_secondary(void)
{
	int proc_type = rte_eal_process_type();
	const struct rte_memzone *mz;
	struct test_info *test_info;
	int ret;

	if (proc_type == RTE_PROC_PRIMARY) {
		if (rte_lcore_count() < NUM_LCORES_NEEDED) {
			printf("Not enough cores for test_timer_secondary, expecting at least %u\n",
			       NUM_LCORES_NEEDED);
			return TEST_SKIPPED;
		}

		mz = rte_memzone_reserve(TEST_INFO_MZ_NAME, sizeof(*test_info),
					 SOCKET_ID_ANY, 0);
		TEST_ASSERT_NOT_NULL(mz, "Couldn't allocate memory for "
				     "test data");
		test_info = mz->addr;

		test_info->tim_mempool = rte_mempool_create("test_timer_mp",
				NUM_TIMERS, sizeof(struct rte_timer), 0, 0,
				NULL, NULL, NULL, NULL, rte_socket_id(), 0);

		ret = rte_timer_data_alloc(&test_info->timer_data_id);
		TEST_ASSERT_SUCCESS(ret, "Failed to allocate timer data "
				    "instance");

		unsigned int *main_lcorep = &test_info->main_lcore;
		unsigned int *mgr_lcorep = &test_info->mgr_lcore;
		unsigned int *sec_lcorep = &test_info->sec_lcore;

		*main_lcorep = rte_get_main_lcore();
		*mgr_lcorep = rte_get_next_lcore(*main_lcorep, 1, 1);
		*sec_lcorep = rte_get_next_lcore(*mgr_lcorep, 1, 1);

		ret = rte_eal_remote_launch(timer_manage_loop,
					    (void *)test_info,
					    *mgr_lcorep);
		TEST_ASSERT_SUCCESS(ret, "Failed to launch timer manage loop");

		ret = timer_secondary_spawn_wait(*sec_lcorep);
		TEST_ASSERT_SUCCESS(ret, "Secondary process execution failed");

		rte_delay_ms(2000);

		test_info->exit_flag = 1;
		rte_eal_wait_lcore(*mgr_lcorep);

#ifdef RTE_LIBRTE_TIMER_DEBUG
		rte_timer_alt_dump_stats(test_info->timer_data_id, stdout);
#endif

		return test_info->expected_count == test_info->expired_count ?
			TEST_SUCCESS : TEST_FAILED;

	} else if (proc_type == RTE_PROC_SECONDARY) {
		uint64_t ticks, timeout_ms;
		struct rte_timer *tim;
		int i;

		mz = rte_memzone_lookup(TEST_INFO_MZ_NAME);
		TEST_ASSERT_NOT_NULL(mz, "Couldn't lookup memzone for "
				     "test info");
		test_info = mz->addr;

		for (i = 0; i < NUM_TIMERS; i++) {
			rte_mempool_get(test_info->tim_mempool, (void **)&tim);

			rte_timer_init(tim);

			/* generate timeouts between 10 and 160 ms */
			timeout_ms = ((rte_rand() & 0xF) + 1) * 10;
			ticks = timeout_ms * rte_get_timer_hz() / MSECPERSEC;

			ret = rte_timer_alt_reset(test_info->timer_data_id,
						  tim, ticks, SINGLE,
						  test_info->mgr_lcore, NULL,
						  test_info);
			if (ret < 0)
				return TEST_FAILED;

			test_info->expected_count++;

			/* randomly leave timer running or stop it */
			if (rte_rand() & 1)
				continue;

			ret = rte_timer_alt_stop(test_info->timer_data_id,
						 tim);
			if (ret == 0) {
				test_info->expected_count--;
				rte_mempool_put(test_info->tim_mempool,
						(void *)tim);
			}

		}

		return TEST_SUCCESS;
	}

	return TEST_FAILED;
}

#endif /* !RTE_EXEC_ENV_WINDOWS */

REGISTER_TEST_COMMAND(timer_secondary_autotest, test_timer_secondary);


text:
var SuiteFactory = require('../SuiteFactory');
var ImmutableModelFactory = require('../../src/ImmutableModelFactory');

var SimpleFrozenTextImmutableModel = ImmutableModelFactory.extend(function SimpleTextImmutableModel(text) {
    this.text = text;
    Object.freeze(this);
});

var enumerableFrozen = {
    'one': new SimpleFrozenTextImmutableModel('one'),
    'two': new SimpleFrozenTextImmutableModel('two'),
    'three': new SimpleFrozenTextImmutableModel('three')
};

var enumerableUnfrozen = {
    'one': new SimpleFrozenTextImmutableModel('one'),
    'two': new SimpleFrozenTextImmutableModel('two'),
    'three': new SimpleFrozenTextImmutableModel('three')
};

var enumerableFrozenKeys = Object.keys(enumerableFrozen);
var enumerableUnfrozenKeys = Object.keys(enumerableUnfrozen);

Object.freeze(enumerableFrozen);
Object.freeze(enumerableFrozenKeys);

SuiteFactory.create('Looping over the keys of a frozen vs unfrozen object')
    .add('frozen for (... in ...)', function() {
        var keys = [];

        for (var key in enumerableFrozen) {
            if (enumerableFrozen.hasOwnProperty(key)) {
                keys.push(key);
            }
        }
    })
    .add('frozen Object.keys(...).forEach', function() {
        var keys = [];

        Object.keys(enumerableFrozen).forEach(function(key) {
            keys.push(key);
        });
    })
    .add('frozen Object.keys(...).forEach with cached keys', function() {
        var keys = [];

        enumerableFrozenKeys.forEach(function(key) {
            keys.push(key);
        });
    })
    .add('frozen for (...) with cached keys', function() {
        var keys = [];

        for (var offset = 0; offset < enumerableFrozenKeys.length; offset++) {
            keys.push(enumerableFrozenKeys[offset]);
        }
    })

    .add('unfrozen for (... in ...)', function() {
        var keys = [];

        for (var key in enumerableUnfrozen) {
            if (enumerableUnfrozen.hasOwnProperty(key)) {
                keys.push(key);
            }
        }
    })
    .add('unfrozen Object.keys(...).forEach', function() {
        var keys = [];

        Object.keys(enumerableUnfrozen).forEach(function(key) {
            keys.push(key);
        });
    })
    .add('unfrozen Object.keys(...).forEach with cached keys', function() {
        var keys = [];

        enumerableUnfrozenKeys.forEach(function(key) {
            keys.push(key);
        });
    })
    .add('unfrozen for (...) with cached keys', function() {
        var keys = [];

        for (var offset = 0; offset < enumerableUnfrozenKeys.length; offset++) {
            keys.push(enumerableUnfrozenKeys[offset]);
        }
    })

    .run();


text:
package valuestore

import (
	"encoding/binary"
	"io"
	"time"
)

// bsm: senderNodeID:8 entries:n
// bsm entry: keyA:8, keyB:8, timestampbits:8, length:4, value:n
const _BULK_SET_MSG_TYPE = 0x44f58445991a4aa1
const _BULK_SET_MSG_HEADER_LENGTH = 8
const _BULK_SET_MSG_ENTRY_HEADER_LENGTH = 28
const _BULK_SET_MSG_MIN_ENTRY_LENGTH = 28

type bulkSetState struct {
	msgCap             int
	inMsgChan          chan *bulkSetMsg
	inFreeMsgChan      chan *bulkSetMsg
	inMsgTimeout       time.Duration
	outFreeMsgChan     chan *bulkSetMsg
	inBulkSetDoneChans []chan struct{}
}

type bulkSetMsg struct {
	vs     *DefaultValueStore
	header []byte
	body   []byte
}

func (vs *DefaultValueStore) bulkSetConfig(cfg *Config) {
	if vs.msgRing != nil {
		vs.msgRing.SetMsgHandler(_BULK_SET_MSG_TYPE, vs.newInBulkSetMsg)
		vs.bulkSetState.inMsgChan = make(chan *bulkSetMsg, cfg.InBulkSetMsgs)
		vs.bulkSetState.inFreeMsgChan = make(chan *bulkSetMsg, cfg.InBulkSetMsgs)
		for i := 0; i < cap(vs.bulkSetState.inFreeMsgChan); i++ {
			vs.bulkSetState.inFreeMsgChan <- &bulkSetMsg{
				vs:     vs,
				header: make([]byte, _BULK_SET_MSG_HEADER_LENGTH),
				body:   make([]byte, cfg.BulkSetMsgCap),
			}
		}
		vs.bulkSetState.inBulkSetDoneChans = make([]chan struct{}, cfg.InBulkSetWorkers)
		for i := 0; i < len(vs.bulkSetState.inBulkSetDoneChans); i++ {
			vs.bulkSetState.inBulkSetDoneChans[i] = make(chan struct{}, 1)
		}
		vs.bulkSetState.msgCap = cfg.BulkSetMsgCap
		vs.bulkSetState.outFreeMsgChan = make(chan *bulkSetMsg, cfg.OutBulkSetMsgs)
		for i := 0; i < cap(vs.bulkSetState.outFreeMsgChan); i++ {
			vs.bulkSetState.outFreeMsgChan <- &bulkSetMsg{
				vs:     vs,
				header: make([]byte, _BULK_SET_MSG_HEADER_LENGTH),
				body:   make([]byte, cfg.BulkSetMsgCap),
			}
		}
		vs.bulkSetState.inMsgTimeout = time.Duration(cfg.InBulkSetMsgTimeout) * time.Second
	}
}

func (vs *DefaultValueStore) bulkSetLaunch() {
	for i := 0; i < len(vs.bulkSetState.inBulkSetDoneChans); i++ {
		go vs.inBulkSet(vs.bulkSetState.inBulkSetDoneChans[i])
	}
}

// newInBulkSetMsg reads bulk-set messages from the MsgRing and puts them on
// the inMsgChan for the inBulkSet workers to work on.
func (vs *DefaultValueStore) newInBulkSetMsg(r io.Reader, l uint64) (uint64, error) {
	var bsm *bulkSetMsg
	select {
	case bsm = <-vs.bulkSetState.inFreeMsgChan:
		// If there isn't a free bulkSetMsg after some time, give up and just
		// read and discard the incoming bulk-set message.
	case <-time.After(vs.bulkSetState.inMsgTimeout):
		left := l
		var sn int
		var err error
		for left > 0 {
			t := toss
			if left < uint64(len(t)) {
				t = t[:left]
			}
			sn, err = r.Read(t)
			left -= uint64(sn)
			if err != nil {
				return l - left, err
			}
		}
		return l, nil
	}
	// If the message is obviously too short, just throw it away.
	if l < _BULK_SET_MSG_HEADER_LENGTH+_BULK_SET_MSG_MIN_ENTRY_LENGTH {
		vs.bulkSetState.inFreeMsgChan <- bsm
		left := l
		var sn int
		var err error
		for left > 0 {
			t := toss
			if left < uint64(len(t)) {
				t = t[:left]
			}
			sn, err = r.Read(t)
			left -= uint64(sn)
			if err != nil {
				return l - left, err
			}
		}
		return l, nil
	}
	var n int
	var sn int
	var err error
	for n != len(bsm.header) {
		sn, err = r.Read(bsm.header[n:])
		n += sn
		if err != nil {
			vs.bulkSetState.inFreeMsgChan <- bsm
			return uint64(n), err
		}
	}
	l -= uint64(len(bsm.header))
	// TODO: I think we should cap the body size to vs.bulkSetState.msgCap but
	// that also means that the inBulkSet worker will need to handle the likely
	// trailing truncated entry. Once all this is done, the overall cluster
	// should work even if the caps are set differently from node to node
	// (definitely not recommended though), as the bulk-set messages would
	// eventually start falling under the minimum cap as the front-end data is
	// tranferred and acknowledged. Anyway, I think this is needed in case
	// someone accidentally screws up the cap on one node, making it way too
	// big. Rather just have that one node abuse/run-out-of memory instead of
	// it causing every other node it sends bulk-set messages to also have
	// memory issues.
	if l > uint64(cap(bsm.body)) {
		bsm.body = make([]byte, l)
	}
	bsm.body = bsm.body[:l]
	n = 0
	for n != len(bsm.body) {
		sn, err = r.Read(bsm.body[n:])
		n += sn
		if err != nil {
			vs.bulkSetState.inFreeMsgChan <- bsm
			return uint64(len(bsm.header)) + uint64(n), err
		}
	}
	vs.bulkSetState.inMsgChan <- bsm
	return uint64(len(bsm.header)) + l, nil
}

// inBulkSet actually processes incoming bulk-set messages; there may be more
// than one of these workers.
func (vs *DefaultValueStore) inBulkSet(doneChan chan struct{}) {
	for {
		bsm := <-vs.bulkSetState.inMsgChan
		if bsm == nil {
			break
		}
		body := bsm.body
		var err error
		ring := vs.msgRing.Ring()
		var rightwardPartitionShift uint64
		var bsam *bulkSetAckMsg
		if ring != nil {
			rightwardPartitionShift = 64 - uint64(ring.PartitionBitCount())
			// Only ack if there is someone to ack to, which should always be
			// the case but just in case.
			if bsm.nodeID() != 0 {
				bsam = vs.newOutBulkSetAckMsg()
			}
		}
		for len(body) > _BULK_SET_MSG_ENTRY_HEADER_LENGTH {
			keyA := binary.BigEndian.Uint64(body)
			keyB := binary.BigEndian.Uint64(body[8:])
			timestampbits := binary.BigEndian.Uint64(body[16:])
			l := binary.BigEndian.Uint32(body[24:])
			// Attempt to store everything received...
			_, err = vs.write(keyA, keyB, timestampbits, body[_BULK_SET_MSG_ENTRY_HEADER_LENGTH:_BULK_SET_MSG_ENTRY_HEADER_LENGTH+l])
			// But only ack on success, there is someone to ack to, and the
			// local node is responsible for the data.
			if err == nil && bsam != nil && ring != nil && ring.Responsible(uint32(keyA>>rightwardPartitionShift)) {
				bsam.add(keyA, keyB, timestampbits)
			}
			body = body[_BULK_SET_MSG_ENTRY_HEADER_LENGTH+l:]
		}
		if bsam != nil {
			vs.msgRing.MsgToNode(bsm.nodeID(), bsam)
		}
		vs.bulkSetState.inFreeMsgChan <- bsm
	}
	doneChan <- struct{}{}
}

// newOutBulkSetMsg gives an initialized bulkSetMsg for filling out and
// eventually sending using the MsgRing. The MsgRing (or someone else if the
// message doesn't end up with the MsgRing) will call bulkSetMsg.Done()
// eventually and the bulkSetMsg will be requeued for reuse later. There is a
// fixed number of outgoing bulkSetMsg instances that can exist at any given
// time, capping memory usage. Once the limit is reached, this method will
// block until a bulkSetMsg is available to return.
func (vs *DefaultValueStore) newOutBulkSetMsg() *bulkSetMsg {
	bsm := <-vs.bulkSetState.outFreeMsgChan
	if vs.msgRing != nil {
		if r := vs.msgRing.Ring(); r != nil {
			if n := r.LocalNode(); n != nil {
				binary.BigEndian.PutUint64(bsm.header, n.ID())
			}
		}
	}
	bsm.body = bsm.body[:0]
	return bsm
}

func (bsm *bulkSetMsg) MsgType() uint64 {
	return _BULK_SET_MSG_TYPE
}

func (bsm *bulkSetMsg) MsgLength() uint64 {
	return uint64(len(bsm.header) + len(bsm.body))
}

func (bsm *bulkSetMsg) WriteContent(w io.Writer) (uint64, error) {
	n, err := w.Write(bsm.header)
	if err != nil {
		return uint64(n), err
	}
	n, err = w.Write(bsm.body)
	return uint64(len(bsm.header)) + uint64(n), err
}

func (bsm *bulkSetMsg) Done() {
	bsm.vs.bulkSetState.outFreeMsgChan <- bsm
}

func (bsm *bulkSetMsg) nodeID() uint64 {
	return binary.BigEndian.Uint64(bsm.header)
}

func (bsm *bulkSetMsg) add(keyA uint64, keyB uint64, timestampbits uint64, value []byte) bool {
	// CONSIDER: I'd rather not have "useless" checks every place wasting
	// cycles when the caller should have already validated the input; but here
	// len(value) must not exceed math.MaxUint32.
	o := len(bsm.body)
	if o+_BULK_SET_MSG_ENTRY_HEADER_LENGTH+len(value) >= cap(bsm.body) {
		return false
	}
	bsm.body = bsm.body[:o+_BULK_SET_MSG_ENTRY_HEADER_LENGTH+len(value)]
	binary.BigEndian.PutUint64(bsm.body[o:], keyA)
	binary.BigEndian.PutUint64(bsm.body[o+8:], keyB)
	binary.BigEndian.PutUint64(bsm.body[o+16:], timestampbits)
	binary.BigEndian.PutUint32(bsm.body[o+24:], uint32(len(value)))
	copy(bsm.body[o+_BULK_SET_MSG_ENTRY_HEADER_LENGTH:], value)
	return true
}


text:
namespace views {
class ImageView;
}

namespace ash {

// Status area tray for showing a toggle for Overview Mode. Overview Mode
// is equivalent to OverviewController being in selection mode.
// This hosts a ShellObserver that listens for the activation of Maximize Mode
// This tray will only be visible while in this state. This tray does not
// provide any bubble view windows.
class ASH_EXPORT OverviewButtonTray : public TrayBackgroundView,
                                      public SessionObserver,
                                      public OverviewObserver,
                                      public TabletModeObserver,
                                      public ShelfConfig::Observer {
 public:
  // Second taps within this time will be counted as double taps. Use this
  // instead of ui::Event's click_count and tap_count as those have a minimum
  // time bewtween events before the second tap counts as a double tap.
  // TODO(crbug.com/817883): We should the gesture detector double tap time or
  // overview enter animation time, once ux decides which one to match (both are
  // 300ms currently).
  static constexpr base::TimeDelta kDoubleTapThresholdMs =
      base::TimeDelta::FromMilliseconds(300);

  explicit OverviewButtonTray(Shelf* shelf);
  ~OverviewButtonTray() override;

  // Sets the ink drop ripple to ACTIVATED immediately with no animations.
  void SnapRippleToActivated();

  // views::Button:
  void OnGestureEvent(ui::GestureEvent* event) override;

  // ActionableView:
  bool PerformAction(const ui::Event& event) override;
  void HandlePerformActionResult(bool action_performed,
                                 const ui::Event& event) override;

  // SessionObserver:
  void OnSessionStateChanged(session_manager::SessionState state) override;

  // OverviewObserver:
  void OnOverviewModeStarting() override;
  void OnOverviewModeEnded() override;

  // TabletModeObserver:
  void OnTabletModeEventsBlockingChanged() override;

  // ShelfConfigObserver:
  void OnShelfConfigUpdated() override;

  // TrayBackgroundView:
  void UpdateAfterLoginStatusChange() override;
  void ClickedOutsideBubble() override;
  base::string16 GetAccessibleNameForTray() override;
  void HideBubbleWithView(const TrayBubbleView* bubble_view) override;

  // views::View:
  const char* GetClassName() const override;

 private:
  friend class OverviewButtonTrayTest;

  // Sets the icon to visible if tablet mode is enabled and
  // OverviewController::CanSelect.
  void UpdateIconVisibility();

  // Weak pointer, will be parented by TrayContainer for its lifetime.
  views::ImageView* icon_;

  ScopedSessionObserver scoped_session_observer_;

  // Stores the timestamp of the last tap event time that happened while not
  // in overview mode. Used to check for double taps, which invoke quick switch.
  base::Optional<base::TimeTicks> last_press_event_time_;

  DISALLOW_COPY_AND_ASSIGN(OverviewButtonTray);
};

}  // namespace ash

#endif  // ASH_SYSTEM_OVERVIEW_OVERVIEW_BUTTON_TRAY_H_


text:
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;
using System.Json;

namespace SuperMap.Web.iServerJava6R
{
    ///
    /// 	<para>${iServerJava6R_ThemeGridUniqueItem_Title}</para>
    /// 	<para>${iServerJava6R_ThemeGridUniqueItem_Description}</para>
    ///
   public class ThemeGridUniqueItem
    {
        /// ${iServerJava6R_ThemeGridUniqueItem_constructor_D}
	   public ThemeGridUniqueItem()
       {

       }
       /// ${iServerJava6R_ThemeGridUniqueItem_attribute_Unique_D}
        public String Unique
		{
			get;
            set;
		}
		/// ${iServerJava6R_ThemeGridUniqueItem_attribute_Visible_D}
		public Boolean Visible
		{
			get;
            set;
		}

		/// ${iServerJava6R_ThemeGridUniqueItem_attribute_Color_D}
		public ServerColor Color
		{
			get;
            set;
		}

		/// ${iServerJava6R_ThemeGridUniqueItem_attribute_Caption_D}
		public String Caption
		{
			get;
            set;
		}

        internal static string ToJson(ThemeGridUniqueItem item)
        {
            string json = "{";

            List<string> list = new List<string>();
            if (!string.IsNullOrEmpty(item.Caption))
            {
                list.Add(string.Format("\"caption\":\"{0}\"", item.Caption));
            }
            else
            {
                list.Add("\"caption\":\"\"");
            }

            //默认值这边儿是个问题,要不要判断呢?
            list.Add(string.Format("\"visible\":{0}", item.Visible.ToString(System.Globalization.CultureInfo.InvariantCulture).ToLower()));

            if (item.Caption != null)
            {
                list.Add(string.Format("\"color\":{0}", ServerColor.ToJson(item.Color)));
            }
            else
            {
                list.Add(string.Format("\"color\":{0}", ServerColor.ToJson(new ServerColor())));
            }

            if (!string.IsNullOrEmpty(item.Unique))
            {
                list.Add(string.Format("\"unique\":\"{0}\"", item.Unique));
            }
            else
            {
                list.Add("\"unique\":\"\"");
            }

            json += string.Join(",", list.ToArray());
            json += "}";
            return json;
        }

        internal static ThemeGridUniqueItem FromJson(System.Json.JsonValue jsonValue)
        {
            if (jsonValue == null) { return null; };
            ThemeGridUniqueItem item = new ThemeGridUniqueItem();

            item.Caption = jsonValue["caption"];
            item.Color = ServerColor.FromJson((JsonObject)jsonValue["color"]);
            item.Unique = jsonValue["unique"];
            item.Visible = (bool)jsonValue["visible"];
            return item;
        }

    }
}