text:
require 'yaml'

require File.join(File.dirname(__FILE__),'auth-callback')

def show_fault result
  fault = Openwsman::Fault.new result
  STDERR.puts "Fault code #{fault.code}, subcode #{fault.subcode}"
  STDERR.puts "\treason #{fault.reason}"
  STDERR.puts "\tdetail #{fault.detail}"
end

def show_error client
  STDERR.puts "Client failed"
  STDERR.puts "\tResult code #{client.response_code}, Fault: #{client.fault_string.inspect}"
end

def fault? client, result
  if result
    if result.fault?
      show_fault result
      true
    end
  else
    show_error client
    true
  end
end

class Client
  @wsmcs = YAML.load( File.open( File.join(File.dirname(__FILE__),"clients.yml") ) )
  def Client.open( name=nil )
    name = ENV["WSMANCLIENT"] if name.nil?
    name = "localhost" unless name
    client = @wsmcs[name]
    if client.nil?
      STDERR.puts "Client.open unknown name '#{name}'"
      raise "Check WSMANCLIENT environment variable against clients.yml"
    end
    wsmc = Openwsman::Client.new( client["host"], client["port"], client["path"], client["scheme"], client["username"], client["password"] )
    wsmc.transport.timeout = 120
    #
    # Allow to enforce auth scheme
    # e.g. required for Windows which offers BASIC|GSS and Openwsman chooses the strongest (GSS) but non-working
    #
    case client["auth"]
    when nil
      wsmc.transport.auth_method = nil
    when /none/i
      wsmc.transport.auth_method = Openwsman::NO_AUTH_STR
    when /basic/i
      wsmc.transport.auth_method = Openwsman::BASIC_AUTH_STR
    when /digest/i
      wsmc.transport.auth_method = Openwsman::DIGEST_AUTH_STR
    when /pass/i
      wsmc.transport.auth_method = Openwsman::PASS_AUTH_STR
    when /ntlm/i
      wsmc.transport.auth_method = Openwsman::NTLM_AUTH_STR
    when /gss/i
      wsmc.transport.auth_method = Openwsman::GSSNEGOTIATE_AUTH_STR
    else
      raise "Unknown auth_scheme #{@auth_scheme.inspect}"
    end

    if client["scheme"] == "https"
      wsmc.transport.verify_peer = 0
      wsmc.transport.verify_host = 0
    end

    wsmc
  end
end


text:
using Atomiv.Core.Application;
using System.Collections.Generic;

namespace Generator.Core.Application.Orders.Responses
{
    public class ListOrdersResponse : ICollectionResponse<ListOrdersRecordResponse, int>
    {
        public List<ListOrdersRecordResponse> Records { get; set; }

        public int Count { get; set; }
    }

    public class ListOrdersRecordResponse : IResponse<int>
    {
        public int Id { get; set; }
    }
}

redpajama_set_name: RedPajamaGithub


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>com.communote.plugins.api.rest.v30.resource.user.preference (Communote 3.5 API)</title>
<meta name="date" content="2019-02-02">
<link rel="stylesheet" type="text/css" href="../../../../../../../../../stylesheet.css" title="Style">

com.communote.plugins.api.rest.v30.resource.user.preference

Classes

UserPreferenceResourceHandler


text:
package org.auraframework.impl.css;

import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import org.auraframework.def.ApplicationDef;
import org.auraframework.def.BaseStyleDef;
import org.auraframework.def.ComponentDef;
import org.auraframework.def.DefDescriptor;
import org.auraframework.def.FlavoredStyleDef;
import org.auraframework.def.FlavorsDef;
import org.auraframework.def.StyleDef;
import org.auraframework.def.TokensDef;
import org.auraframework.impl.AuraImplTestCase;
import org.auraframework.impl.css.util.Flavors;
import org.auraframework.service.ContextService;
import org.auraframework.service.DefinitionService;
import org.auraframework.system.AuraContext;
import org.auraframework.system.AuraContext.Authentication;
import org.auraframework.system.AuraContext.Format;
import org.auraframework.system.AuraContext.Mode;
import org.auraframework.throwable.quickfix.QuickFixException;

import javax.inject.Inject;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * for testing stuff that needs StyleDef, TokenDef sources.
 */
public abstract class StyleTestCase extends AuraImplTestCase {
    private static AtomicLong counter = new AtomicLong();
    private String ns1;
    private String ns2;

    @Inject
    protected DefinitionService definitionService;

    @Inject
    protected ContextService contextService;

    @Override
    public void setUp() throws Exception {
        super.setUp();
        long num = counter.incrementAndGet();
        this.ns1 = "nsA" + num;
        this.ns2 = "nsB" + num;

        // make sure the registry is aware of the new namespaces
        String desc = ns1 + ":dummy";
        DefDescriptor<ComponentDef> dummy = definitionService.getDefDescriptor(desc, ComponentDef.class);
        addSourceAutoCleanup(dummy, "<aura:component></aura:component>");

        desc = ns2 + ":dummy";
        dummy = definitionService.getDefDescriptor(desc, ComponentDef.class);
        addSourceAutoCleanup(dummy, "<aura:component></aura:component>");

        if (contextService.isEstablished()) {
            contextService.endContext();
        }
        contextService.startContext(Mode.UTEST, Format.JSON, Authentication.AUTHENTICATED);
    }

    /** gets the name of the first namespace */
    public String getNs1() {
        return ns1;
    }

    /** gets the name of the second namespace */
    public String getNs2() {
        return ns2;
    }

    /** adds a {@link StyleDef} to the namespace with the given source */
    public DefDescriptor<StyleDef> addStyleDef(CharSequence src) {
        DefDescriptor<ComponentDef> bundle = addSourceAutoCleanup(ComponentDef.class, "<aura:component/>",
                getNs1() + ":style");
        DefDescriptor<StyleDef> desc = definitionService.getDefDescriptor(
                String.format("%s://%s.%s", DefDescriptor.CSS_PREFIX, bundle.getNamespace(), bundle.getName()),
                StyleDef.class);
        return addSourceAutoCleanup(desc, src.toString());
    }

    /** adds a {@link StyleDef} in the "other" namespace with the given source */
    public DefDescriptor<StyleDef> addStyleDefOtherNamespace(CharSequence src) {
        DefDescriptor<ComponentDef> bundle = addSourceAutoCleanup(ComponentDef.class, "<aura:component/>",
                getNs2() + ":style");
        DefDescriptor<StyleDef> desc = definitionService.getDefDescriptor(
                String.format("%s://%s.%s", DefDescriptor.CSS_PREFIX, bundle.getNamespace(), bundle.getName()),
                StyleDef.class);
        return addSourceAutoCleanup(desc, src.toString());
    }

    /** adds a {@link ComponentDef} to the namespace with a basic source */
    public DefDescriptor<ComponentDef> addComponentDef() {
        return addComponentDef("<aura:component/>");
    }

    /** adds a {@link ComponentDef} to the namespace with a flavorable div */
    public DefDescriptor<ComponentDef> addFlavorableComponentDef() {
        return addComponentDef("<aura:component><div aura:flavorable='true'></div></aura:component>");
    }

    /** adds a {@link ComponentDef} to the namespace with the given source */
    public DefDescriptor<ComponentDef> addComponentDef(CharSequence src) {
        return addSourceAutoCleanup(ComponentDef.class, src.toString(), getNs1() + ":" + "cmp");
    }

    /** adds a {@link ComponentDef} to the namespace with the given source */
    public DefDescriptor<ComponentDef> addComponentDefOtherNamespace(CharSequence src) {
        return addSourceAutoCleanup(ComponentDef.class, src.toString(), getNs2() + ":" + "cmp");
    }

    /** gets the parsed output of the given style */
    public String getParsedCss(DefDescriptor<? extends BaseStyleDef> styleDesc) throws QuickFixException {
        return definitionService.getDefinition(styleDesc).getCode();
    }

    /** gets the parsed output of the given style. This ensures the application explicit tokens are registered */
    public String getParsedCssUseAppTokens(DefDescriptor<? extends BaseStyleDef> styleDesc) throws QuickFixException {
        // ensures app's tokens are added to the context
        // create style context?
        return definitionService.getDefinition(styleDesc).getCode();
    }

    /** adds the namespace-default {@link TokensDef} to the namespace with the given source */
    public DefDescriptor<TokensDef> addNsTokens(CharSequence src) {
        String fmt = String.format("%s:%sNamespace", ns1, ns1);
        DefDescriptor<TokensDef> desc = definitionService.getDefDescriptor(fmt, TokensDef.class);
        addSourceAutoCleanup(desc, src.toString());
        return desc;
    }

    /** adds the namespace-default {@link TokensDef} to the "other" namespace with the given source */
    public DefDescriptor<TokensDef> addNsTokensOtherNamespace(CharSequence src) {
        String fmt = String.format("%s:%sNamespace", ns2, ns2);
        DefDescriptor<TokensDef> desc = definitionService.getDefDescriptor(fmt, TokensDef.class);
        addSourceAutoCleanup(desc, src.toString());
        return desc;
    }

    /** adds an extra {@link TokensDef} to the namespace */
    public DefDescriptor<TokensDef> addSeparateTokens(CharSequence src) {
        String fmt = String.format("%s:%s", ns1, getAuraTestingUtil().getNonce("testTokens"));
        DefDescriptor<TokensDef> desc = definitionService.getDefDescriptor(fmt, TokensDef.class);
        addSourceAutoCleanup(desc, src.toString());
        return desc;
    }

    /** adds an extra {@link TokensDef} to the "other" namespace */
    public DefDescriptor<TokensDef> addSeparateTokensOtherNamespace(CharSequence src) {
        String fmt = String.format("%s:%s", ns2, getAuraTestingUtil().getNonce("testTokens"));
        DefDescriptor<TokensDef> desc = definitionService.getDefDescriptor(fmt, TokensDef.class);
        addSourceAutoCleanup(desc, src.toString());
        return desc;
    }

    /**
     * adds an app to the ns, and restarts the context with new app. Must be called after any other addContextApp*
     * methods.
     */
    public DefDescriptor<ApplicationDef> addContextApp(CharSequence src) throws QuickFixException {
        String fmt = String.format("%s:%s", ns1, "testApp");
        DefDescriptor<ApplicationDef> appDesc = definitionService.getDefDescriptor(fmt, ApplicationDef.class);
        addSourceAutoCleanup(appDesc, src.toString());

        // restart the context with the new app
        if (contextService.isEstablished()) {
            contextService.endContext();
        }
        AuraContext ctx = contextService.startContext(Mode.UTEST, Format.JSON, Authentication.AUTHENTICATED, appDesc);
        ctx.setApplicationDescriptor(appDesc);
        definitionService.updateLoaded(appDesc);
        return appDesc;
    }

    /** adds a style with the given source to the same bundle as the context app */
    public DefDescriptor<StyleDef> addContextAppBundleStyle(CharSequence src) {
        String fmt = String.format("%s.%s", ns1, "testApp");
        DefDescriptor<StyleDef> styleDesc = definitionService.getDefDescriptor(fmt, StyleDef.class);
        return addSourceAutoCleanup(styleDesc, src.toString());
    }

    /** adds a flavor def for the given component in the same bundle */
    public DefDescriptor<FlavoredStyleDef> addStandardFlavor(DefDescriptor<ComponentDef> flavored, CharSequence src) {
        DefDescriptor<FlavoredStyleDef> desc = Flavors.standardFlavorDescriptor(flavored);
        addSourceAutoCleanup(desc, src.toString());
        return desc;
    }

    /** adds a flavor def for the given component, but in a different namespace and within a bundle called "flavors". */
    public DefDescriptor<FlavoredStyleDef> addCustomFlavor(DefDescriptor<ComponentDef> flavored, CharSequence src) {
        DefDescriptor<FlavoredStyleDef> desc = Flavors.customFlavorDescriptor(flavored, ns2, "flavors");
        addSourceAutoCleanup(desc, src.toString());
        return desc;
    }

    /** adds a flavor def for the given component, in the same namespace and within a bundle called "flavors". */
    public DefDescriptor<FlavoredStyleDef> addCustomFlavorToFirstNamespace(DefDescriptor<ComponentDef> flavored, CharSequence src) {
        DefDescriptor<FlavoredStyleDef> desc = Flavors.customFlavorDescriptor(flavored, ns1, "flavors");
        addSourceAutoCleanup(desc, src.toString());
        return desc;
    }

    /** adds a flavor assortment def */
    public DefDescriptor<FlavorsDef> addFlavorAssortment(CharSequence src) {
        return addSourceAutoCleanup(FlavorsDef.class, src.toString(), getNs1() + ":" + "fa");
    }

    /** adds a flavor assortment def to the "other" namespace */
    public DefDescriptor<FlavorsDef> addFlavorAssortmentOtherNamespace(CharSequence src) {
        return addSourceAutoCleanup(FlavorsDef.class, src.toString(), getNs2() + ":" + "fa");
    }

    /** adds a flavor assortment with the given source to the same bundle as the context app */
    public DefDescriptor<FlavorsDef> addContextAppFlavorAssortment(CharSequence src) {
        String fmt = String.format("%s:%s", ns1, "testApp");
        DefDescriptor<FlavorsDef> faDesc = definitionService.getDefDescriptor(fmt, FlavorsDef.class);
        return addSourceAutoCleanup(faDesc, src.toString());
    }

    /** helper for building a tokens def string source */
    public TokensSrcBuilder tokens() {
        return new TokensSrcBuilder();
    }

    public static final class TokensSrcBuilder implements CharSequence {
        private DefDescriptor<TokensDef> parent;
        private final List<String> content = Lists.newArrayList();
        private String descriptorProvider;
        private String mapProvider;

        public TokensSrcBuilder token(String name, String value) {
            content.add(String.format("<aura:token name='%s' value='%s'/>", name, value));
            return this;
        }

        public TokensSrcBuilder parent(DefDescriptor<TokensDef> parent) {
            this.parent = checkNotNull(parent, "parent cannot be null");
            return this;
        }

        public TokensSrcBuilder descriptorProvider(String descriptorProvider) {
            this.descriptorProvider = descriptorProvider;
            return this;
        }

        public TokensSrcBuilder mapProvider(String mapProvider) {
            this.mapProvider = mapProvider;
            return this;
        }

        public TokensSrcBuilder imported(DefDescriptor<TokensDef> imported) {
            content.add(String.format("<aura:import name='%s'/>", imported.getDescriptorName()));
            return this;
        }

        @Override
        public String toString() {
            StringBuilder builder = new StringBuilder();

            builder.append("<aura:tokens");

            if (descriptorProvider != null) {
                builder.append(" provider='");
                builder.append(descriptorProvider);
                builder.append("'");
            }

            if (mapProvider != null) {
                builder.append(" mapProvider='");
                builder.append(mapProvider);
                builder.append("'");
            }

            if (parent != null) {
                builder.append(" extends='");
                builder.append(parent.getDescriptorName());
                builder.append("'");
            }
            builder.append(">");

            builder.append(Joiner.on("").join(content));

            builder.append("</aura:tokens>");
            return builder.toString();
        }

        @Override
        public int length() {
            throw new UnsupportedOperationException();
        }

        @Override
        public char charAt(int index) {
            throw new UnsupportedOperationException();
        }

        @Override
        public CharSequence subSequence(int start, int end) {
            throw new UnsupportedOperationException();
        }
    }
}


text:
<?php

namespace App\Tests\Unit\Pipes\Transaction\Update;

use App\Models\Transaction;
use App\Passables\Transaction\Update;
use App\Pipes\Transaction\Update\Format as PipeFormat;
use App\Tests\Unit\Pipes\Update\Format;
use Exception;

/**
 * Class FormatTest
 * @package App\Tests\Unit\Pipes\Transaction\Update
 */
class FormatTest extends Format
{
    /**
     * UpdateTest constructor.
     *
     * @param null   $name
     * @param array  $data
     * @param string $dataName
     */
    public function __construct($name = null, array $data = [], $dataName = '')
    {
        parent::__construct(
            $name,
            $data,
            $dataName
        );

        $this->setPassable(Update::class);
        $this->setPipe(PipeFormat::class);
        $this->setModel(Transaction::class);
    }

    /**
     * @group App
     * @group App.Pipes
     * @group App.Pipes.Transaction
     * @group App.Pipes.Transaction.Update
     * @group App.Pipes.Transaction.Update.Format
     * @group App.Pipes.Transaction.Update.Format.Success
     */
    public function testFormatSuccess()
    {
        $this->formatSuccess();
    }

    /**
     * @group                    App
     * @group                    App.Pipes
     * @group                    App.Pipes.Transaction
     * @group                    App.Pipes.Transaction.Update
     * @group                    App.Pipes.Transaction.Update.Format
     * @group                    App.Pipes.Transaction.Update.Format.Failure
     * @expectedExceptionCode    500
     * @expectedException Exception
     * @expectedExceptionMessage Transaction format failed.
     */
    public function testFormatFailure()
    {
        $this->formatFailure();
    }
}


text:
package org.mifos.application.productdefinition.business;

import java.util.Date;
import java.util.Set;

import org.mifos.application.office.business.OfficeBO;
import org.mifos.application.office.persistence.OfficePersistence;
import org.mifos.application.productdefinition.exceptions.ProductDefinitionException;
import org.mifos.application.productdefinition.persistence.PrdOfferingPersistence;
import org.mifos.application.productdefinition.util.helpers.ApplicableTo;
import org.mifos.application.productdefinition.util.helpers.PrdStatus;
import org.mifos.application.productdefinition.util.helpers.ProductDefinitionConstants;
import org.mifos.application.productdefinition.util.helpers.ProductType;
import org.mifos.application.util.helpers.YesNoFlag;
import org.mifos.framework.business.BusinessObject;
import org.mifos.framework.components.logger.LoggerConstants;
import org.mifos.framework.components.logger.MifosLogManager;
import org.mifos.framework.components.logger.MifosLogger;
import org.mifos.framework.exceptions.PersistenceException;
import org.mifos.framework.security.util.UserContext;
import org.mifos.framework.util.helpers.DateUtils;
import org.mifos.framework.util.helpers.StringUtils;

/**
 * A product is a set of rules (interest rate, number of installments, maximum
 * amount, etc) which describes what an MFI offers.
 *
 * Although we may sometimes call these "offerings", the preferred word is
 * "products" (that is what they are called in the functional specification, and
 * the wider microfinance industry).
 */
public abstract class PrdOfferingBO extends BusinessObject {

    private static final MifosLogger prdLogger = MifosLogManager.getLogger(LoggerConstants.PRDDEFINITIONLOGGER);
    private final Short prdOfferingId;

    private String prdOfferingName;

    private String prdOfferingShortName;

    private final String globalPrdOfferingNum;

    private final ProductTypeEntity prdType;

    private ProductCategoryBO prdCategory;

    private PrdStatusEntity prdStatus;

    private PrdApplicableMasterEntity prdApplicableMaster;

    private Date startDate;

    private Date endDate;

    private final OfficeBO office;

    private String description;

    private Set<PrdOfferingBO> collectionProductMix;

    private Set<PrdOfferingBO> prdOfferingNotAllowedId; // For Not allowed
                                                        // products

    private Short prdMixFlag; // Tagging products for which mixes were defined

    /**
     * default constructor for hibernate usage
     */
    protected PrdOfferingBO() {
        this(null, null, null, null);
    }

    protected PrdOfferingBO(final Short prdOfferingId) {
        this(prdOfferingId, null, null, null);
    }

    protected PrdOfferingBO(final Short prdOfferingId, final String globalPrdOfferingNum,
            final ProductTypeEntity prdType, final OfficeBO office) {
        this.prdOfferingId = prdOfferingId;
        this.globalPrdOfferingNum = globalPrdOfferingNum;
        this.prdType = prdType;
        this.office = office;
    }

    /**
     * TODO - keithw - work in progress -
     *
     * Minimal legal constructor
     *
     * @param productStatus
     */
    public PrdOfferingBO(final String name, final String shortName, final String globalProductNumber,
            final Date startDate, final ApplicableTo applicableToCustomer, final ProductCategoryBO category,
            final PrdStatus productStatus, final Date createdDate, final Short createdByUserId) {
        this.prdOfferingName = name;
        this.prdOfferingShortName = shortName;
        this.globalPrdOfferingNum = globalProductNumber;
        this.startDate = startDate;
        this.prdApplicableMaster = new PrdApplicableMasterEntity(applicableToCustomer);
        this.prdCategory = category;
        this.createdDate = createdDate;
        this.createdBy = createdByUserId;
        this.prdType = category.getProductType();
        // this.prdStatus = new PrdStatusEntity(prdType, productStatus);
        this.prdOfferingId = null;
        this.office = null;
    }

    protected PrdOfferingBO(final UserContext userContext, final String prdOfferingName, final String prdOfferingShortName,
            final ProductCategoryBO prdCategory, final PrdApplicableMasterEntity prdApplicableMaster, final Date startDate)
            throws ProductDefinitionException {
        this(userContext, prdOfferingName, prdOfferingShortName, prdCategory, prdApplicableMaster, startDate, null,
                null);
    }

    protected PrdOfferingBO(final UserContext userContext, final String prdOfferingName, final String prdOfferingShortName,
            final ProductCategoryBO prdCategory, final PrdApplicableMasterEntity prdApplicableMaster, final Date startDate, final Date endDate,
            final String description) throws ProductDefinitionException {
        super(userContext);
        prdLogger.debug("creating product offering");
        validateUserContext(userContext);
        vaildate(prdOfferingName, prdOfferingShortName, prdCategory, prdApplicableMaster, startDate);
        validateStartDateAgainstCurrentDate(startDate);
        validateEndDateAgainstCurrentDate(startDate, endDate);
        validateDuplicateProductOfferingName(prdOfferingName);
        validateDuplicateProductOfferingShortName(prdOfferingShortName);
        prdOfferingId = null;
        this.prdOfferingName = prdOfferingName;
        this.prdOfferingShortName = prdOfferingShortName;
        this.prdCategory = prdCategory;
        this.prdType = prdCategory.getProductType();
        this.prdApplicableMaster = prdApplicableMaster;
        this.startDate = startDate;
        this.endDate = endDate;
        this.description = description;
        this.globalPrdOfferingNum = generatePrdOfferingGlobalNum();
        this.prdStatus = getPrdStatus(startDate, prdType);

        try {
            this.office = new OfficePersistence().getOffice(userContext.getBranchId());
        } catch (PersistenceException e) {
            throw new ProductDefinitionException(e);
        }
        prdLogger.debug("creating product offering done");
    }

    public Short getPrdOfferingId() {
        return prdOfferingId;
    }

    public String getPrdOfferingName() {
        return prdOfferingName;
    }

    public String getPrdOfferingShortName() {
        return prdOfferingShortName;
    }

    public String getGlobalPrdOfferingNum() {
        return globalPrdOfferingNum;
    }

    public ProductTypeEntity getPrdType() {
        return prdType;
    }

    public ProductCategoryBO getPrdCategory() {
        return prdCategory;
    }

    /**
     * Most callers will want {@link #isActive()} instead (or perhaps
     * {@link #getStatus()}.
     */
    public PrdStatusEntity getPrdStatus() {
        return prdStatus;
    }

    public PrdStatus getStatus() {
        return PrdStatus.fromInt(prdStatus.getOfferingStatusId());
    }

    public abstract boolean isActive();

    public PrdApplicableMasterEntity getPrdApplicableMaster() {
        return prdApplicableMaster;
    }

    public ApplicableTo getPrdApplicableMasterEnum() {
        return prdApplicableMaster.asEnum();
    }

    public Date getStartDate() {
        return startDate;
    }

    public Date getEndDate() {
        return endDate;
    }

    public OfficeBO getOffice() {
        return office;
    }

    public String getDescription() {
        return description;
    }

    void setPrdOfferingName(final String prdOfferingName) {
        this.prdOfferingName = prdOfferingName;
    }

    public void setPrdOfferingShortName(final String prdOfferingShortName) {
        this.prdOfferingShortName = prdOfferingShortName;
    }

    public void setPrdCategory(final ProductCategoryBO prdCategory) {
        this.prdCategory = prdCategory;
    }

    public void setPrdStatus(final PrdStatusEntity prdStatus) {
        this.prdStatus = prdStatus;
    }

    public void setPrdApplicableMaster(final PrdApplicableMasterEntity prdApplicableMaster) {
        this.prdApplicableMaster = prdApplicableMaster;
    }

    void setStartDate(final Date startDate) {
        this.startDate = startDate;
    }

    void setEndDate(final Date endDate) {
        this.endDate = endDate;
    }

    public void setDescription(final String description) {
        this.description = description;
    }

    public Set<PrdOfferingBO> getCollectionProductMix() {
        return collectionProductMix;
    }

    public void setCollectionProductMix(final Set<PrdOfferingBO> collectionProductMix) {
        this.collectionProductMix = collectionProductMix;
    }

    public Set<PrdOfferingBO> getPrdOfferingNotAllowedId() {
        return prdOfferingNotAllowedId;
    }

    public void setPrdOfferingNotAllowedId(final Set<PrdOfferingBO> prdOfferingNotAllowedId) {
        this.prdOfferingNotAllowedId = prdOfferingNotAllowedId;
    }

    public Short getPrdMixFlag() {
        return prdMixFlag;
    }

    public void setPrdMixFlag(final Short prdMixFlag) {
        this.prdMixFlag = prdMixFlag;
    }

    private String generatePrdOfferingGlobalNum() throws ProductDefinitionException {
        prdLogger.debug("Generating new product Offering global number");
        StringBuilder globalPrdOfferingNum = new StringBuilder();
        globalPrdOfferingNum.append(userContext.getBranchId());
        globalPrdOfferingNum.append("-");
        Short maxPrdID = null;
        try {
            maxPrdID = new PrdOfferingPersistence().getMaxPrdOffering();
        } catch (PersistenceException e) {
            throw new ProductDefinitionException(e);
        }
        globalPrdOfferingNum.append(StringUtils.lpad(String.valueOf(maxPrdID != null ? maxPrdID + 1
                : ProductDefinitionConstants.DEFAULTMAX + 1), '0', 3));
        prdLogger.debug("Generation of new product Offering global number done" + globalPrdOfferingNum);
        return globalPrdOfferingNum.toString();
    }

    private void vaildate(final String prdOfferingName, final String prdOfferingShortName, final ProductCategoryBO prdCategory,
            final PrdApplicableMasterEntity prdApplicableMaster, final Date startDate) throws ProductDefinitionException {
        prdLogger.debug("Validating the fields in Prd Offering");
        if (prdOfferingName == null || prdOfferingShortName == null || prdCategory == null
                || prdApplicableMaster == null || prdOfferingShortName.length() > 4 || startDate == null) {
            throw new ProductDefinitionException(ProductDefinitionConstants.ERROR_CREATE);
        }
        prdLogger.debug("Validation of the fields in Prd Offering done.");
    }

    private void validateUserContext(final UserContext userContext) throws ProductDefinitionException {
        prdLogger.debug("Validating the usercontext in Prd Offering");
        if (userContext == null) {
            throw new ProductDefinitionException(ProductDefinitionConstants.ERROR_CREATE);
        }
        prdLogger.debug("Validation of the fields in Prd Offering done.");
    }

    protected void validateStartDateAgainstCurrentDate(final Date startDate) throws ProductDefinitionException {
        if (DateUtils.getDateWithoutTimeStamp(startDate.getTime())
                .compareTo(DateUtils.getCurrentDateWithoutTimeStamp()) < 0) {
            throw new ProductDefinitionException(ProductDefinitionConstants.INVALIDSTARTDATE);
        }
    }

    private void validateEndDateAgainstCurrentDate(final Date startDate, final Date endDate) throws ProductDefinitionException {
        if (endDate != null
                && DateUtils.getDateWithoutTimeStamp(startDate.getTime()).compareTo(
                        DateUtils.getDateWithoutTimeStamp(endDate.getTime())) >= 0) {
            throw new ProductDefinitionException(ProductDefinitionConstants.INVALIDENDDATE);
        }
    }

    private PrdStatusEntity getPrdStatus(final Date startDate, final ProductTypeEntity prdType) throws ProductDefinitionException {
        prdLogger.debug("getting the Product status for prdouct offering with start date :" + startDate
                + " and product Type :" + prdType.getProductTypeID());
        PrdStatus prdStatus = null;
        if (startDate.compareTo(DateUtils.getCurrentDateWithoutTimeStamp()) == 0) {
            prdStatus = getActivePrdStatus(prdType);
        } else {
            prdStatus = getInActivePrdStatus(prdType);
        }
        try {
            prdLogger.debug("getting the Product status for product status :" + prdStatus);
            return new PrdOfferingPersistence().getPrdStatus(prdStatus);
        } catch (PersistenceException e) {
            throw new ProductDefinitionException(e);
        }
    }

    private PrdStatus getActivePrdStatus(final ProductTypeEntity prdType) {
        prdLogger.debug("getting the Active Product status for product Type :" + prdType.getProductTypeID());
        if (prdType.getProductTypeID().equals(ProductType.LOAN.getValue())) {
            return PrdStatus.LOAN_ACTIVE;
        } else {
            return PrdStatus.SAVINGS_ACTIVE;
        }
    }

    private PrdStatus getInActivePrdStatus(final ProductTypeEntity prdType) {
        prdLogger.debug("getting the In Active Product status for product Type :" + prdType.getProductTypeID());
        if (prdType.getProductTypeID().equals(ProductType.LOAN.getValue())) {
            return PrdStatus.LOAN_INACTIVE;
        } else {
            return PrdStatus.SAVINGS_INACTIVE;
        }
    }

    private void validateDuplicateProductOfferingName(final String productOfferingName) throws ProductDefinitionException {
        prdLogger.debug("Checking for duplicate product offering name");
        try {
            if (!new PrdOfferingPersistence().getProductOfferingNameCount(productOfferingName).equals(
                    Integer.valueOf("0"))) {
                throw new ProductDefinitionException(ProductDefinitionConstants.DUPLPRDINSTNAME);
            }
        } catch (PersistenceException e) {
            throw new ProductDefinitionException(e);
        }
    }

    private void validateDuplicateProductOfferingShortName(final String productOfferingShortName)
            throws ProductDefinitionException {
        prdLogger.debug("Checking for duplicate product offering short name");
        try {
            if (!new PrdOfferingPersistence().getProductOfferingShortNameCount(productOfferingShortName).equals(
                    Integer.valueOf("0"))) {
                throw new ProductDefinitionException(ProductDefinitionConstants.DUPLPRDINSTSHORTNAME);
            }
        } catch (PersistenceException e) {
            throw new ProductDefinitionException(e);
        }
    }

    public void update(final Short userId, final String prdOfferingName, final String prdOfferingShortName,
            final ProductCategoryBO prdCategory, final PrdApplicableMasterEntity prdApplicableMaster, final Date startDate, final Date endDate,
            final String description, final PrdStatus status) throws ProductDefinitionException {
        vaildate(prdOfferingName, prdOfferingShortName, prdCategory, prdApplicableMaster, startDate);
        validateStartDateForUpdate(startDate);
        validateEndDateAgainstCurrentDate(startDate, endDate);
        if (!prdOfferingName.equals(this.prdOfferingName)) {
            validateDuplicateProductOfferingName(prdOfferingName);
        }
        if (!prdOfferingShortName.equals(this.prdOfferingShortName)) {
            validateDuplicateProductOfferingShortName(prdOfferingShortName);
        }
        this.prdOfferingName = prdOfferingName;
        this.prdOfferingShortName = prdOfferingShortName;
        this.prdCategory = prdCategory;
        this.prdApplicableMaster = prdApplicableMaster;
        this.startDate = startDate;
        this.endDate = endDate;
        this.description = description;
        try {
            this.prdStatus = new PrdOfferingPersistence().getPrdStatus(status);
        } catch (PersistenceException pe) {
            throw new ProductDefinitionException(pe);
        }
        prdLogger.debug("creating product offering done");

    }

    private void validateStartDateForUpdate(final Date startDate) throws ProductDefinitionException {
        if (DateUtils.getDateWithoutTimeStamp(this.startDate.getTime()).compareTo(
                DateUtils.getCurrentDateWithoutTimeStamp()) <= 0
                && DateUtils.getDateWithoutTimeStamp(startDate.getTime()).compareTo(
                        DateUtils.getDateWithoutTimeStamp(this.startDate.getTime())) != 0) {
            throw new ProductDefinitionException(ProductDefinitionConstants.STARTDATEUPDATEEXCEPTION);
        } else if (DateUtils.getDateWithoutTimeStamp(this.startDate.getTime()).compareTo(
                DateUtils.getCurrentDateWithoutTimeStamp()) > 0) {
            validateStartDateAgainstCurrentDate(startDate);
        }

    }

    public void updatePrdOfferingFlag() throws PersistenceException {
        this.setPrdMixFlag(YesNoFlag.YES.getValue());
        new PrdOfferingPersistence().createOrUpdate(this);
    }

    @Override
    public int hashCode() {
        final int PRIME = 31;
        int result = 1;
        result = PRIME * result + (prdOfferingId == null ? 0 : prdOfferingId.hashCode());
        return result;
    }

    @Override
    public boolean equals(final Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final PrdOfferingBO other = (PrdOfferingBO) obj;
        return isOfSameOffering(other);
    }

    public boolean isOfSameOffering(final PrdOfferingBO other) {
        if (prdOfferingId == null) {
            if (other.prdOfferingId != null) {
                return false;
            }
        } else if (!prdOfferingId.equals(other.getPrdOfferingId())) {
            return false;
        }
        return true;
    }
}


text:
namespace mozc {

namespace {
bool StringAsIntegerComparator(const string &lhs, const string &rhs) {
  return NumberUtil::SimpleAtoi(lhs) < NumberUtil::SimpleAtoi(rhs);
}
}  // namespace

string Version::GetMozcVersion() {
  return version::kMozcVersion;
}

#ifdef OS_WIN
wstring Version::GetMozcVersionW() {
  wstring version;
  Util::UTF8ToWide(version::kMozcVersion, &version);
  return version;
}
#endif

int Version::GetMozcVersionMajor() {
  return version::kMozcVersionMajor;
}

int Version::GetMozcVersionMinor() {
  return version::kMozcVersionMinor;
}

int Version::GetMozcVersionBuildNumber() {
  return version::kMozcVersionBuildNumber;
}

int Version::GetMozcVersionRevision() {
  return version::kMozcVersionRevision;
}

bool Version::CompareVersion(const string &lhs, const string &rhs) {
  if (lhs == rhs) {
    return false;
  }
  if (lhs.find("Unknown") != string::npos ||
      rhs.find("Unknown") != string::npos) {
    LOG(WARNING) << "Unknown is given as version";
    return false;
  }
  vector<string> vlhs;
  Util::SplitStringUsing(lhs, ".", &vlhs);
  vector<string> vrhs;
  Util::SplitStringUsing(rhs, ".", &vrhs);
  return std::lexicographical_compare(vlhs.begin(), vlhs.end(), vrhs.begin(),
                                      vrhs.end(), StringAsIntegerComparator);
}

}  // namespace mozc


text:
namespace location
{

class LocationObserver
{
public:
  virtual void OnLocationError(TLocationError errorCode) = 0;
  virtual void OnLocationUpdated(GpsInfo const & info) = 0;
};

class LocationService
{
protected:
  LocationObserver & m_observer;

public:
  LocationService(LocationObserver & observer) : m_observer(observer) {}
  virtual ~LocationService() {}

  virtual void Start() = 0;
  virtual void Stop() = 0;
};

} // namespace location

extern "C" location::LocationService * CreateDesktopLocationService(location::LocationObserver & observer);


text:
""" Testing miobase module
"""

import numpy as np

from numpy.testing import (assert_almost_equal,
                           assert_array_equal)

from nose.tools import (assert_true, assert_false, assert_raises,
                        assert_equal, assert_not_equal)

from scipy.io.matlab.miobase import matdims

def test_matdims():
    # Test matdims dimension finder
    assert_equal(matdims(np.array(1)), (1, 1))  # numpy scalar
    assert_equal(matdims(np.array([1])), (1, 1))  # 1d array, 1 element
    assert_equal(matdims(np.array([1,2])), (2, 1))  # 1d array, 2 elements
    assert_equal(matdims(np.array([[2],[3]])), (2, 1))  # 2d array, column vector
    assert_equal(matdims(np.array([[2,3]])), (1, 2))  # 2d array, row vector
    # 3d array, rowish vector
    assert_equal(matdims(np.array([[[2,3]]])), (1, 1, 2))
    assert_equal(matdims(np.array([])), (0, 0))  # empty 1d array
    assert_equal(matdims(np.array([[]])), (0, 0))  # empty 2d
    assert_equal(matdims(np.array([[[]]])), (0, 0, 0))  # empty 3d
    # Optional argument flips 1-D shape behavior.
    assert_equal(matdims(np.array([1,2]), 'row'), (1, 2))  # 1d array, 2 elements
    # The argument has to make sense though
    assert_raises(ValueError, matdims, np.array([1,2]), 'bizarre')
    # Check empty sparse matrices get their own shape
    from scipy.sparse import csr_matrix, csc_matrix
    assert_equal(matdims(csr_matrix(np.zeros((3, 3)))), (3, 3))
    assert_equal(matdims(csc_matrix(np.zeros((2, 2)))), (2, 2))


text:
import React from 'react';
import { shallow, mount } from 'enzyme';
import sinon from 'sinon';
import { MemoryRouter } from 'react-router';
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import { PostedMessage, mapStateToProps } from '../../../components/PostMessage/PostedMessage.jsx';
import { mockData } from '../../../__mocks__/mockData';

const middleware = [thunk];
const mockStore = configureMockStore(middleware);
describe('<PostMessage />', () => {
  beforeEach(() => {
    const setup = () => {
      return mapStateToProps(mockData.postedMessage.state);
    };
    const state = setup();
  });

  it('Component should render correctly', () => {
    const wrapper = shallow(<PostedMessage
     { ...mockData.postedMessage.props } />,
      { context: { store: mockStore(mockData.postedMessage.initialState) } });
    expect(wrapper.contains('View message board')).toBe(true);
    expect(wrapper.contains('Messages')).toBe(true);
  });

  it('calls componentDidMount', () => {
    sinon.spy(PostedMessage.prototype, 'componentDidMount');
    const wrapper = mount(
      <MemoryRouter>
        <PostedMessage {...mockData.postedMessage.props } />
      </MemoryRouter>
    );
    expect(PostedMessage.prototype.componentDidMount.calledOnce).toBe(true);
    expect(wrapper.node.state).toEqual(null);
  });
});


text:
import { Form, Input, Icon, InputNumber, Button, DatePicker, AutoComplete, Modal, } from "antd";
import BudgetCategoryPicker from "components/BudgetCategoryPicker";
import AmountInput from "components/AmountInput";
import React from "react";
import _ from "lodash";

const FormItem = Form.Item;
const InputGroup = Input.Group;
let uuid = 0;

class BudgetForm extends React.Component {

  render () {
    const { getFieldDecorator, getFieldValue, } = this.props.form;
    getFieldDecorator("budget_categories", { initialValue: [], });
    getFieldDecorator("amounts", { initialValue: [], });
    const keys = getFieldValue("budget_categories");
    const formItems = keys.map((k, index) => {
      return (

          <FormItem
            required={false}
          >
            {getFieldDecorator(`budget_categories${k}`,
              { required: true, message: "Please select a budget category",
            })(
              <BudgetCategoryPicker />
            )}
          </FormItem>
          <FormItem>
            {getFieldDecorator(`amounts${k}`, {
              initialValue: 100,
            })(
              <AmountInput />
            )}
          </FormItem>

      );
    });

    const add = () => {
      uuid += 1;
      // can use data-binding to get
      const keys = this.props.form.getFieldValue("budget_categories");
      const amts = this.props.form.getFieldValue("amounts");
      const nextKeys = keys.concat(uuid);
      const amtKeys = amts.concat(uuid);
      // can use data-binding to set
      // important! notify form to detect changes
      this.props.form.setFieldsValue({
        budget_categories: nextKeys,
        amounts: amtKeys,
      });
    };

    return (
      <Modal title="New Budget" visible={this.props.visible} onOk={this.props.onCreate} onCancel={this.props.onCancel}>

          <FormItem>
            { getFieldDecorator("name", { rules: [
              { required: true, message: "Please enter a budget name", },
            ], })(
              <Input placeholder="name" />
            )
            }
          </FormItem>
          <FormItem>
            { getFieldDecorator("budget_start_date",{ rules: [
                { type: "object",
                  required: true, message: "Please select a budget date!",
                },
              ], }
            )(<DatePicker placeholder='Budget Start Date' />)}
          </FormItem>
          <FormItem>
            { getFieldDecorator("budget_end_date",{ rules: [
                { type: "object",
                  required: true, message: "Please select a budget end date!",
                },
              ], }
            )(<DatePicker placeholder='Budget End Date' />)}
          </FormItem>
          <FormItem>
            { getFieldDecorator("description", {})(
              <Input placeholder="Description" />
            )}
          </FormItem>
          <Button type="dashed" onClick={add}>
            <Icon type="plus" /> Add field
          </Button>
          {formItems}

      </Modal>
    );
  }

}

const WrappedBudgetForm = Form.create()(BudgetForm);
export default WrappedBudgetForm;


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="@dimen/m4399_rec_foot_height"
    android:background="@drawable/m4399_rec_mvcenter_foot_bg"
    android:gravity="center_vertical"
    android:paddingLeft="@dimen/m4399_rec_paddingLeft"
    android:paddingRight="@dimen/m4399_rec_paddingRight" >

    <ImageView
        android:id="@+id/sdk_help"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="4dp"
        android:src="@drawable/m4399_rec_sdk_help" />

    <TextView
        android:id="@+id/sdk_help_message"
        style="@style/m4399RecFooterTextStyle"
        android:text="@string/m439_rec_hotline_prefix" />

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1.0" >

        <TextView
            android:id="@+id/sdk_telephone"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/m4399_rec_link_text_bg"
            android:clickable="true"
            android:focusable="true"
            android:text="@string/m4399_rec_hotline_4399"
            android:textColor="#32beff"
            android:textSize="@dimen/m4399_rec_foot_text_size" />
    </LinearLayout>

    <ImageView
        android:id="@+id/sdk_ftnn_logo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/m4399_rec_sdk_ftnn_logo" />

</LinearLayout>


text:
package io.compgen.cgseq;

public class CGSUtilsException extends Exception {

	public CGSUtilsException(String string) {
		super(string);
	}

	/**
	 *
	 */
	private static final long serialVersionUID = -409000510259617015L;

}


text:
<?php

namespace common\models;

use common\components\Helper;
use Yii;
use yii\helpers\HtmlPurifier;
use yii\helpers\Markdown;

/**
 * This is the model class for table "reply".
 *
 * @property integer $id
 * @property integer $user_id
 * @property integer $topic_id
 * @property string $content
 * @property integer $created
 */
class Reply extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'reply';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['topic_id', 'content'], 'required'],
            [['topic_id', 'created'], 'integer'],
            ['user_id', 'default', 'value' => Yii::$app->user->id],
            ['created', 'default', 'value' => time()],
            [['content'], 'string', 'max' => 20000]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => '回复ID',
            'user_id' => '回复者',
            'topic_id' => '主题',
            'content' => '回复内容',
            'created' => '创建时间',
        ];
    }

    /**
     * @param boolean $insert
     * @param array $changedAttributes
     * @return bool
     */
    public function afterSave($insert, $changedAttributes)
    {
        $topic = Topic::findOne($this->topic_id);
        $topic->reply = $topic->reply + 1;
        $topic->last_reply_time = time();
        $topic->updated_at = time();
        $topic->last_reply_user = Yii::$app->user->identity->username;
        $rst = $topic->update();

        //给用户发回复或者@通知,回复自己的不通知
        if($rst && Yii::$app->user->id != $topic->user_id)
        {
            $notice = new Notice();
            $notice->from_user_id = $this->user_id;
            $notice->to_user_id = $topic->user_id;
            $notice->topic_id = $this->topic_id;
            $notice->type = 1;
            $notice->msg = $this->content;
            $notice->created = time();
            $notice->save();
        }

        //回复中提到其他人,通知其他人
        if(strstr($this->content, '@'))
        {
            preg_match_all('/@(.*?)\s/', $this->content, $match);
            if(isset($match[1]) && count($match[1]) > 0)
            {
                $notice_user = array_unique($match[1]);
                foreach ($notice_user as $v) {
                    $to_user = User::findOne(['username' => $v]);
                    if($v == $topic->user->username || $v == Yii::$app->user->identity->username || empty($to_user->id)) continue;
                    $notice = new Notice();
                    $notice->from_user_id = $this->user_id;
                    $notice->to_user_id = $to_user->id;
                    $notice->topic_id = $this->topic_id;
                    $notice->type = 2;
                    $notice->msg = $this->content;
                    $notice->created = time();
                    $notice->save();
                }
            }
        }

        return parent::afterSave($insert, $changedAttributes);
    }

    public function afterFind()
    {
        $this->content  = Helper::autoLink(HtmlPurifier::process(Markdown::process($this->content, 'gfm-comment')));
        parent::afterFind();
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getUser()
    {
        return $this->hasOne(User::className(), ['id' => 'user_id']);
    }

    public function getTopic()
    {
        return $this->hasOne(Topic::className(), ['id' => 'topic_id']);
    }

    static function Count()
    {
        return Reply::find()->count();
    }

}


text:
(async function() {
  TestRunner.addResult(
      `Test that checks whether the returned stackTrace of a timeline correctly formats the scriptId as a string.\n`);
  await TestRunner.loadLegacyModule('timeline'); await TestRunner.loadTestModule('performance_test_runner');
  await TestRunner.loadLegacyModule('components');
  await TestRunner.showPanel('timeline');

  function performActions() {
    let callback;
    const promise = new Promise((fulfill) => callback = fulfill);
    const timer = setInterval(intervalTimerWork, 20);
    let iteration = 0;
    return promise;

    function intervalTimerWork() {
      if (++iteration < 2)
        return;
      clearInterval(timer);
      callback();
    }
  }

  const source = performActions.toString() + '\n//# sourceURL=performActions.js';
  await new Promise(resolve => TestRunner.evaluateInPage(source, resolve));

  const linkifier = new Components.Linkifier();
  const recordTypes = new Set(['TimerInstall', 'TimerRemove']);

  await PerformanceTestRunner.invokeAsyncWithTimeline('performActions');
  await PerformanceTestRunner.walkTimelineEventTree(formatter);
  TestRunner.completeTest();

  async function formatter(event) {
    if (!recordTypes.has(event.name))
      return;

    TestRunner.addResult('Stack trace for: ' + event.name)
    TestRunner.addResult(JSON.stringify(event.args.data.stackTrace));
  }
})();


text:
'use strict';

const utils = require('../utils');
const AnyType = require('./any');

const supportBuffer = typeof Buffer !== 'undefined';

class BufferType extends AnyType {
  constructor() {
    super();

    this._type = 'buffer';
    this._defaultValidator = 'isBuffer';
  }

  convert(val) {
    return supportBuffer ? (val instanceof Buffer ? val : new Buffer(val)) : val;
  }
}

const chainable = utils.chainable(BufferType.prototype, 'buffer');

chainable('isBuffer', {
  method: function(val) {
    return supportBuffer ? (val instanceof Buffer) : false;
  }
});

module.exports = BufferType;


text:
package org.renjin.cran.DBI.columns;

import org.renjin.sexp.AtomicVector;
import org.renjin.sexp.LogicalArrayVector;

import java.sql.ResultSet;
import java.sql.SQLException;

public class LogicalColumnBuilder implements ColumnBuilder {
    private LogicalArrayVector.Builder vector = new LogicalArrayVector.Builder();

    public static boolean acceptsType(String columnType) {
      return columnType.equals("boolean") ||
             columnType.equals("bit");
    }

    @Override
    public void addValue(ResultSet rs, int columnIndex) throws SQLException {
        boolean value = rs.getBoolean(columnIndex);
        if(rs.wasNull()) {
            vector.addNA();
        } else {
            vector.add(value);
        }
    }

    @Override
    public AtomicVector build() {
        return vector.build();
    }
}


text:
title: CSS Classes
localeTitle: Classes CSS
---
## Classes CSS

Classes são uma maneira eficiente de agrupar elementos HTML para que eles possam compartilhar os mesmos estilos. As classes CSS (Cascading Style Sheets) podem ser usadas para organizar e decorar elementos de páginas da web.

Ao escrever HTML, você pode adicionar classes a um elemento. Basta adicionar o atributo `class="myclass"` ao elemento. Vários elementos podem ter a mesma classe e um elemento pode ter várias classes. Você pode atribuir várias classes a um elemento adicionando todos os nomes de classes desejados separados por um espaço ao atributo de `class` em HTML.

```html

<h1 class="super-man other-class third-class">"Here I come to save the day!"</h1>
 <p>is a popular catchphrase that <span class="super-man">Super Man</span> often said.</p>
```

Você pode, então, estilizar esses elementos com CSS. As classes são referenciadas com o período (.) Antes delas no CSS, mas você não deve colocar pontos no seu HTML.

```css
.super-man {
  color: red;
  background-color: blue;
 }
```

Este código dão um fundo azul e uma cor de texto vermelho para todos os elementos que têm o `super-man` de classe. [Veja este exemplo no CodePen](https://codepen.io/Tlandis/pen/RLvomV) .

Você também pode declarar mais de uma classe para seu elemento, como:

```html

<div class="ironMan alfred">
 We're going to save you.
 </div>
```

Então no seu arquivo css:

```css
.ironMan{
 color:red;
 }

 .alfred{
 background-color: black;
 }
```

**Nota:** nomes de classes são tradicionalmente todos minúsculos, com cada palavra em um nome de classe com várias palavras separadas por hífens (por exemplo, "super-homem").

Você também pode combinar classes na mesma linha:

```css
.superMan .spiderMan {
 color: red;
 background-color: blue;
 }
```

Você pode ver o resultado do código acima [aqui](https://codepen.io/Tlandis/pen/RLvomV) . Aprenda como combinar classes css usando seletores [aqui](https://www.w3schools.com/css/css_combinators.asp) .

#### Mais Informações:

*   [Seletor de Classe CSS, w3 schools](https://www.w3schools.com/cssref/sel_class.asp)
*   [Classes HTML, w3 Escolas](https://www.w3schools.com/html/html_classes.asp)
*   [truques css](https://css-tricks.com/how-css-selectors-work/)
*   [Como codificar em HTML5 e CSS3](http://howtocodeinhtml.com/chapter7.html)
*   [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/class)


text:
{-|
Description: reference parts of the api

types and tools to make it easy to reference parts of the chatless API
-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances #-}
module Chatless.Client.PathPointers where

import qualified Data.Text as T
import qualified Data.ByteString as BS
import qualified Data.Text.Encoding as Tenc
import Web.PathPieces
import qualified Data.Sequence as S
import Data.Foldable (fold)
import Data.Monoid ((<>))

import Chatless.Model.ID

-- * working with paths
type Path = S.Seq T.Text

emptyPath :: Path
emptyPath = S.empty

type Sub = T.Text

-- | how to encode a pointer into a path
class PathPointer a where
    toPath :: a -> Path

instance PathPointer Path where
    toPath = id

pathSub :: PathPointer a => Sub -> a -> Path
pathSub sub p = toPath p S.|> sub

-- | puts all the slashes before all the elements of the path, and concats
-- the whole thing
mkAbsPath :: Path -> BS.ByteString
mkAbsPath pth = Tenc.encodeUtf8 $ fold $ pth >>= (S.singleton "/" S.|>)

-- * pointing at users

-- | pointer to a user
data UserPtr =
    MePtr |
    LocalUserPtr UserId |
    AnyUserPtr ServerId UserId
    deriving (Eq, Show)

instance PathPointer UserPtr where
    toPath MePtr = S.singleton "me"
    toPath (LocalUserPtr uid) = S.singleton "user" S.|> toPathPiece uid
    toPath (AnyUserPtr sid uid) = S.singleton "server" S.|> toPathPiece sid S.|> "user" S.|> toPathPiece uid

-- ** pointing at things users have

-- | name of topics sub
userTopicsSub :: Sub
userTopicsSub = "topic"

-- | name of about topics sub
userAboutSub :: Sub
userAboutSub = "about"

-- | name of invite topics sub
userInviteSub :: Sub
userInviteSub = "invite"

-- | path to the list of a user's topics
userTopicsPath :: UserPtr -> Path
userTopicsPath = pathSub userTopicsSub

-- ** constructing user pointers

-- * pointing at topics

-- | point to topics
data TopicPtr =
    AnyTopicPtr UserPtr TopicId |
    AboutTopicPtr UserPtr |
    InviteTopicPtr UserPtr
    deriving (Eq, Show)

instance PathPointer TopicPtr where
    toPath (AnyTopicPtr userPtr tid) = pathSub userTopicsSub userPtr S.|> toPathPiece tid
    toPath (AboutTopicPtr userPtr) = pathSub userAboutSub userPtr
    toPath (InviteTopicPtr userPtr) = pathSub userInviteSub userPtr

-- ** pointing at their members

-- | name of topic members sub
topicMembersSub :: Sub
topicMembersSub = "member"

-- | path to the base of a topic's members api
topicMembersPath :: TopicPtr -> Path
topicMembersPath = pathSub topicMembersSub

-- | pointer to a specific member in a topic
data MemberPtr =
    LocalMemberPtr TopicPtr UserId |
    AnyMemberPtr TopicPtr ServerId UserId
    deriving (Eq, Show)

instance PathPointer MemberPtr where
    toPath (LocalMemberPtr topicPtr uid) = pathSub topicMembersSub topicPtr S.|> "user" S.|> toPathPiece uid
    toPath (AnyMemberPtr topicPtr sid uid) = pathSub topicMembersSub topicPtr S.|> "server" S.|> toPathPiece sid S.|> "user" S.|> toPathPiece uid

-- ** referencing messages

-- | name of topic messages sub
topicMessagesSub :: Sub
topicMessagesSub = "message"

-- | path to the base of a topic's message api
topicMessagesPath :: TopicPtr -> Path
topicMessagesPath = pathSub topicMessagesSub

data MQBase =
    MQFirst |
    MQLast |
    MQBefore MessageId |
    MQAfter MessageId |
    MQAt MessageId |
    MQFrom MessageId
    deriving (Eq, Show)

instance PathPointer MQBase where
    toPath MQFirst = S.singleton "first"
    toPath MQLast = S.singleton "last"
    toPath (MQBefore mid) = S.singleton "before" S.|> toPathPiece mid
    toPath (MQAfter mid) = S.singleton "after" S.|> toPathPiece mid
    toPath (MQAt mid) = S.singleton "at" S.|> toPathPiece mid
    toPath (MQFrom mid) = S.singleton "from" S.|> toPathPiece mid

-- | message query represents the way you can query a topic's messages
data MessageQueryPtr = MessageQueryPtr TopicPtr MQBase Int deriving (Eq, Show)

instance PathPointer MessageQueryPtr where
    toPath (MessageQueryPtr topicPtr mqbase count) = pathSub topicMessagesSub topicPtr <> toPath mqbase S.|> toPathPiece count

-- *** getting your hands on message queries

queryFirst :: TopicPtr -> Int -> MessageQueryPtr
queryFirst = flip MessageQueryPtr MQFirst

queryLast :: TopicPtr -> Int -> MessageQueryPtr
queryLast = flip MessageQueryPtr MQLast

queryBefore :: TopicPtr -> MessageId -> Int -> MessageQueryPtr
queryBefore = (. MQBefore) . MessageQueryPtr

queryAfter :: TopicPtr -> MessageId -> Int -> MessageQueryPtr
queryAfter = (. MQAfter) . MessageQueryPtr

queryAt :: TopicPtr -> MessageId -> Int -> MessageQueryPtr
queryAt = (. MQAt) . MessageQueryPtr

queryFrom :: TopicPtr -> MessageId -> Int -> MessageQueryPtr
queryFrom = (. MQFrom) . MessageQueryPtr

-- *** referencing a specific message

data JustMessagePtr = JustMessagePtr TopicPtr MessageId deriving (Eq, Show)

instance PathPointer JustMessagePtr where
    toPath (JustMessagePtr topicPtr mid) = pathSub topicMessagesSub topicPtr S.|> "just" S.|> toPathPiece mid


text:
<?xml version="1.0" encoding="UTF-8"?>
<templateSet group="dos">
  <template name="$m" value="$scope$.$method("$functionName$", function($args$) {
    $END$
});" description="adds a new DOS method" toReformat="true" toShortenFQNames="true">
    <variable name="scope" expression="jsArrayVariable()" defaultValue=""Public"" alwaysStopAt="true" />
    <variable name="functionName" expression="jsMethodName()" defaultValue="" alwaysStopAt="true" />
    <variable name="args" expression="jsSuggestVariableName()" defaultValue="" alwaysStopAt="true" />
    <context>
      <option name="JAVA_SCRIPT" value="true" />
    </context>
  </template>
  <template name="$f" value="$scope$.$field("$fieldName$");$END$" description="adds a new DOS field" toReformat="true" toShortenFQNames="true">
    <variable name="scope" expression="jsArrayVariable()" defaultValue=""Private"" alwaysStopAt="true" />
    <variable name="fieldName" expression="jsSuggestVariableName()" defaultValue="" alwaysStopAt="true" />
    <context>
      <option name="JAVA_SCRIPT" value="true" />
    </context>
  </template>
  <template name="$g" value="$scope$.$getter("$getterName$", function() {
    return $END$;
});" description="adds a new DOS getter" toReformat="true" toShortenFQNames="true">
    <variable name="scope" expression="jsArrayVariable()" defaultValue=""Public"" alwaysStopAt="true" />
    <variable name="getterName" expression="" defaultValue="" alwaysStopAt="true" />
    <context>
      <option name="JAVA_SCRIPT" value="true" />
    </context>
  </template>
  <template name="$s" value="$scope$.$setter("$setterName$", function($arg$) {
    $scope2$.$setterName$ = $arg$;
});" description="adds a new DOS setter" toReformat="true" toShortenFQNames="true">
    <variable name="scope" expression="jsArrayVariable()" defaultValue=""Public"" alwaysStopAt="true" />
    <variable name="setterName" expression="" defaultValue="" alwaysStopAt="true" />
    <variable name="arg" expression="" defaultValue=""v"" alwaysStopAt="true" />
    <variable name="scope2" expression="" defaultValue=""Private"" alwaysStopAt="true" />
    <context>
      <option name="JAVA_SCRIPT" value="true" />
    </context>
  </template>
  <template name="$cl" value="dos.$class($namespace$, "$className$", {
    extends: $extends$,
    static: function(This, Super, Public, Protected, Private) {
    },
    $: function(This, Super, Static, Public, Protected, Private) {
        Public.$init(function(Defaults) {
        }, function(Params) {
        });

        Public.$dispose(function() {
        });

        $END$
    }
});" description="adds a new DOS class" toReformat="true" toShortenFQNames="true">
    <variable name="namespace" expression="jsSuggestVariableName()" defaultValue="" alwaysStopAt="true" />
    <variable name="className" expression="jsQualifiedClassName()" defaultValue="" alwaysStopAt="true" />
    <variable name="extends" expression="jsQualifiedClassName()" defaultValue="" alwaysStopAt="true" />
    <context>
      <option name="JAVA_SCRIPT" value="true" />
    </context>
  </template>
  <template name="$co" value="$scope$.$const("$constName$", { value: "$val$" });$END$" description="adds a new DOS constant" toReformat="true" toShortenFQNames="true">
    <variable name="scope" expression="jsArrayVariable()" defaultValue=""Public"" alwaysStopAt="true" />
    <variable name="constName" expression="" defaultValue=""UPPER_CASE"" alwaysStopAt="true" />
    <variable name="val" expression="" defaultValue="" alwaysStopAt="true" />
    <context>
      <option name="JAVA_SCRIPT" value="true" />
    </context>
  </template>
  <template name="$i" value="Public.$init(function(Defaults) {
    }, function(Params) {
        $END$
    });" description="adds a new DOS constructor" toReformat="true" toShortenFQNames="true">
    <context>
      <option name="JAVA_SCRIPT" value="true" />
    </context>
  </template>
  <template name="$st" value="static: function(This, Super, Public, Protected, Private) {
    $END$
},   " description="adds a new DOS static part" toReformat="true" toShortenFQNames="true">
    <context>
      <option name="JAVA_SCRIPT" value="true" />
    </context>
  </template>
  <template name="$b" value="$: function(This, Super, Static, Public, Protected, Private) {
    Public.$init(function(Defaults) {
    }, function(Params) {
    });

    Public.$dispose(function() {
    });

    $END$
}" description="adds a new DOS class body" toReformat="true" toShortenFQNames="true">
    <context>
      <option name="JAVA_SCRIPT" value="true" />
    </context>
  </template>
</templateSet>


text:
namespace MinidumpExplorer.Dialogs
{
    partial class DialogBase
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.SuspendLayout();
            //
            // DialogBase
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(284, 261);
            this.ControlBox = false;
            this.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
            this.Name = "DialogBase";
            this.Text = "DialogBase";
            this.ResumeLayout(false);

        }

        #endregion
    }
}


text:
package com.ycsoft.daos.core.setter;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.jdbc.core.BatchPreparedStatementSetter;

/**
 *
 实现<tt>Spring</tt>的参数接口设置,

 * @see org.springframework.jdbc.core.BatchPreparedStatementSetter
 * @author hh
 */
public class BatchPreparedStatementSetterImpl extends ParameterSetter
			implements BatchPreparedStatementSetter {
	private  int size;
	private  List<Object[]> values ;

	/**
	 *
 SQL结构中有多个参数时,将对应的参数位置封装置数组中

	 * @param values 所传递的参数行、列的格式
	 */
	public BatchPreparedStatementSetterImpl(List<Object[]> values){
		size = values.size() ;
		this.values = values ;
	}

	/**
	 *
  如果批量处理中只有一个参数,使用该函数

	 * @param values
	 */
	public BatchPreparedStatementSetterImpl(Object[] values){
		List<Object[]> params = new ArrayList<Object[]>();
		for (Object o : values) {
			params.add(new Object[]{ o });
		}
		size = params.size() ;
		this.values = params ;
	}

	/**
	 *  获取批量执行的命令数
	 */
	public int getBatchSize() {
		return size;
	}

	/**
	 * 将对应的行数的参数封装进去
	 */
	public void setValues(PreparedStatement ps, int row) throws SQLException {
		setParameters(ps, values.get( row ));
	}
}


text:
code copy from quilkin

``` rust
/// Server is the UDP server main implementation
pub struct Server {
    // We use pub(super) to limit instantiation only to the Builder.
    pub(super) log: Logger,
    pub(super) config: Arc<ValidatedConfig>,
    // Admin may be turned off, primarily for testing.
    pub(super) admin: Option<Admin>,
    pub(super) metrics: Arc<Metrics>,
    pub(super) proxy_metrics: ProxyMetrics,
    pub(super) session_metrics: SessionMetrics,
    pub(super) filter_registry: FilterRegistry,
}

impl Server {
    pub async fn run(self, mut shutdown_rx: watch::Receiver<()>) -> Result<()> {
        self.log_config();

        if let Some(admin) = &self.admin {
            admin.run(shutdown_rx.clone());
        }

        let socket = Arc::new(Server::bind(self.config.proxy.port).await?);
        let session_manager = SessionManager::new(self.log.clone(), shutdown_rx.clone());
        let (send_packets, receive_packets) = mpsc::channel::<Packet>(1024);

        let session_ttl = Duration::from_secs(SESSION_TIMEOUT_SECONDS);

        let (cluster_manager, filter_manager) =
            self.create_resource_managers(shutdown_rx.clone()).await?;
        self.run_receive_packet(socket.clone(), receive_packets);
        let recv_loop = self.run_recv_from(RunRecvFromArgs {
            cluster_manager,
            filter_manager,
            socket,
            session_manager,
            session_ttl,
            send_packets,
            shutdown_rx: shutdown_rx.clone(),
        });

        tokio::select! {
            join_result = recv_loop => {
                join_result
                    .map_err(|join_err| Error::RecvLoop(format!("{}", join_err)))
                    .and_then(|inner| inner.map_err(Error::RecvLoop))
            }
            _ = shutdown_rx.changed() => {
                Ok(())
            }
        }
    }

    fn run_recv_from(&self, args: RunRecvFromArgs) -> JoinHandle<StdResult<(), String>> {
        let session_manager = args.session_manager;
        let log = self.log.clone();
        let proxy_metrics = self.proxy_metrics.clone();
        let session_metrics = self.session_metrics.clone();

        // The number of worker tasks to spawn. Each task gets a dedicated queue to
        // consume packets off.
        let num_workers = num_cpus::get();

        // Contains channel Senders for each worker task.
        let mut packet_txs = vec![];
        // Contains config for each worker task.
        let mut worker_configs = vec![];
        for worker_id in 0..num_workers {
            let (packet_tx, packet_rx) = mpsc::channel(num_workers);
            packet_txs.push(packet_tx);
            worker_configs.push(DownstreamReceiveWorkerConfig {
                worker_id,
                packet_rx,
                shutdown_rx: args.shutdown_rx.clone(),
                receive_config: ProcessDownstreamReceiveConfig {
                    log: log.clone(),
                    proxy_metrics: proxy_metrics.clone(),
                    session_metrics: session_metrics.clone(),
                    cluster_manager: args.cluster_manager.clone(),
                    filter_manager: args.filter_manager.clone(),
                    session_manager: session_manager.clone(),
                    session_ttl: args.session_ttl,
                    send_packets: args.send_packets.clone(),
                },
            })
        }

        // Start the worker tasks that pick up received packets from their queue
        // and processes them.
        Self::spawn_downstream_receive_workers(log.clone(), worker_configs);

        // Start the background task to receive downstream packets from the socket
        // and place them onto the worker tasks' queue for processing.
        let socket = args.socket;
        tokio::spawn(async move {
            // Index to round-robin over workers to process packets.
            let mut next_worker = 0;
            let num_workers = num_workers;

            // Initialize a buffer for the UDP packet. We use the maximum size of a UDP
            // packet, which is the maximum value of 16 a bit integer.
            let mut buf = vec![0; 1 << 16];
            loop {
                match socket.recv_from(&mut buf).await {
                    Ok((size, recv_addr)) => {
                        let packet_tx = &mut packet_txs[next_worker % num_workers];
                        next_worker += 1;

                        if packet_tx
                            .send((recv_addr, (&buf[..size]).to_vec()))
                            .await
                            .is_err()
                        {
                            // We cannot recover from this error since
                            // it implies that the receiver has been dropped.
                            let reason =
                                "Failed to send received packet over channel to worker".into();
                            error!(log, "{}", reason);
                            return Err(reason);
                        }
                    }
                    err => {
                        // Socket error, we cannot recover from this so return an error instead.
                        error!(log, "Error processing receive socket"; "error" => #?err);
                        return Err(format!("error processing receive socket: {:?}", err));
                    }
                }
            }
        })
    }
```

in the runner.rs

``` rust
/// Start and run a proxy. Any passed in [`FilterFactory`]s are included
/// alongside the default filter factories.
pub async fn run_with_config(
    base_log: slog::Logger,
    config: Arc<Config>,
    filter_factories: impl IntoIterator<Item = DynFilterFactory>,
) -> Result<(), Error> {
    let log = base_log.new(o!("source" => "run"));
    let server = Builder::from(config)
        .with_log(base_log)
        .with_filter_registry(FilterRegistry::new(FilterSet::default_with(
            &log,
            filter_factories.into_iter(),
        )))
        .validate()?
        .build();

    let (shutdown_tx, shutdown_rx) = watch::channel::<()>(());
    tokio::spawn(async move {
        // Don't unwrap in order to ensure that we execute
        // any subsequent shutdown tasks.
        signal::ctrl_c().await.ok();
        shutdown_tx.send(()).ok();
    });

    if let Err(err) = server.run(shutdown_rx).await {
        info!(log, "Shutting down with error"; "error" => %err);
        Err(Error::from(err))
    } else {
        info!(log, "Shutting down");
        Ok(())
    }
}
```

## normal loop

``` rust
    fn spawn_updater(
        log: Logger,
        filter_manager: SharedFilterManager,
        mut filter_chain_updates_rx: mpsc::Receiver<Arc<FilterChain>>,
        mut shutdown_rx: watch::Receiver<()>,
    ) {
        tokio::spawn(async move {
            loop {
                tokio::select! {
                    update = filter_chain_updates_rx.recv() => {
                        match update {
                            Some(filter_chain) => {
                                debug!(log, "Received a filter chain update.");
                                filter_manager.write().update(filter_chain);
                            }
                            None => {
                                warn!(log, "Exiting filter chain update receive loop because the sender dropped the channel.");
                                return;
                            }
                        }
                    }
                    _ = shutdown_rx.changed() => {
                        debug!(log, "Exiting filter chain update receive loop because a shutdown signal was received.");
                        return;
                    },
                }
            }
        });
    }
```

## session_manager
copy from session_manager.rs
``` rust
// Tracks current sessions by their [`SessionKey`]
type SessionsMap = HashMap<SessionKey, Session>;
type Sessions = Arc<RwLock<SessionsMap>>;
pub struct SessionManager(Sessions);

impl SessionManager {
    pub fn new(log: Logger, shutdown_rx: watch::Receiver<()>) -> Self {
        let poll_interval = Duration::from_secs(SESSION_EXPIRY_POLL_INTERVAL);
        let sessions: Sessions = Arc::new(RwLock::new(HashMap::new()));

        Self::run_prune_sessions(log.clone(), sessions.clone(), poll_interval, shutdown_rx);

        Self(sessions)
    }

    /// run_prune_sessions starts the timer for pruning sessions and runs prune_sessions every
    /// SESSION_TIMEOUT_SECONDS, via a tokio::spawn, i.e. it's non-blocking.
    /// Pruning will occur ~ every interval period. So the timeout expiration may sometimes
    /// exceed the expected, but we don't have to write lock the Sessions map as often to clean up.
    fn run_prune_sessions(
        log: Logger,
        mut sessions: Sessions,
        poll_interval: Duration,
        mut shutdown_rx: watch::Receiver<()>,
    ) {
        let mut interval = tokio::time::interval(poll_interval);

        tokio::spawn(async move {
            loop {
                tokio::select! {
                    _ = shutdown_rx.changed() => {
                        debug!(log, "Exiting Prune Sessions due to shutdown signal.");
                        break;
                    }
                    _ = interval.tick() => {
                        debug!(log, "Attempting to Prune Sessions");
                        Self::prune_sessions(&log, &mut sessions).await;

                    }
                }
            }
        });
    }
}
```

## session

``` rust
/// Session encapsulates a UDP stream session
pub struct Session {
    log: Logger,
    metrics: Metrics,
    filter_manager: SharedFilterManager,
    /// created_at is time at which the session was created
    created_at: Instant,
    socket: Arc<UdpSocket>,
    /// dest is where to send data to
    dest: Endpoint,
    /// from is the original sender
    from: SocketAddr,
    /// The time at which the session is considered expired and can be removed.
    expiration: Arc<AtomicU64>,
    /// a channel to broadcast on if we are shutting down this Session
    shutdown_tx: watch::Sender<()>,
}

/ A (source, destination) address pair that uniquely identifies a session.
#[derive(Clone, Eq, Hash, PartialEq, Debug, PartialOrd, Ord)]
pub struct SessionKey {
    pub source: SocketAddr,
    pub destination: SocketAddr,
}

impl Session {
    /// new creates a new Session, and starts the process of receiving udp sockets
    /// from its ephemeral port from endpoint(s)
    pub async fn new(
        base: &Logger,
        metrics: Metrics,
        filter_manager: SharedFilterManager,
        from: SocketAddr,
        dest: Endpoint,
        sender: mpsc::Sender<Packet>,
        ttl: Duration,
    ) -> Result<Self> {
        let log = base
            .new(o!("source" => "proxy::Session", "from" => from, "dest_address" => dest.address));
        let addr = SocketAddrV4::new(Ipv4Addr::new(0, 0, 0, 0), 0);
        let socket = Arc::new(UdpSocket::bind(addr).await.map_err(Error::BindUdpSocket)?);
        let (shutdown_tx, shutdown_rx) = watch::channel::<()>(());

        let expiration = Arc::new(AtomicU64::new(0));
        Self::do_update_expiration(&expiration, ttl)?;

        let s = Session {
            metrics,
            log,
            filter_manager,
            socket: socket.clone(),
            from,
            dest,
            created_at: Instant::now(),
            expiration,
            shutdown_tx,
        };
        debug!(s.log, "Session created");

        s.metrics.sessions_total.inc();
        s.metrics.active_sessions.inc();
        s.run(ttl, socket, sender, shutdown_rx);
        Ok(s)
    }

    /// run starts processing received udp packets on its UdpSocket
    fn run(
        &self,
        ttl: Duration,
        socket: Arc<UdpSocket>,
        mut sender: mpsc::Sender<Packet>,
        mut shutdown_rx: watch::Receiver<()>,
    ) {
        let log = self.log.clone();
        let from = self.from;
        let expiration = self.expiration.clone();
        let filter_manager = self.filter_manager.clone();
        let endpoint = self.dest.clone();
        let metrics = self.metrics.clone();
        tokio::spawn(async move {
            let mut buf: Vec<u8> = vec![0; 65535];
            loop {
                debug!(log, "Awaiting incoming packet");
                select! {
                    received = socket.recv_from(&mut buf) => {
                        match received {
                            Err(err) => {
                                metrics.rx_errors_total.inc();
                                error!(log, "Error receiving packet"; "error" => %err);
                            },
                            Ok((size, recv_addr)) => {
                                metrics.rx_bytes_total.inc_by(size as u64);
                                metrics.rx_packets_total.inc();
                                Session::process_recv_packet(
                                    &log,
                                    &metrics,
                                    &mut sender,
                                    &expiration,
                                    ttl,
                                    ReceivedPacketContext {
                                        filter_manager: filter_manager.clone(),
                                        packet: &buf[..size],
                                        endpoint: &endpoint,
                                        from: recv_addr,
                                        to: from,
                                    }).await
                            }
                        };
                    }
                    _ = shutdown_rx.changed() => {
                        debug!(log, "Closing Session");
                        return;
                    }
                };
            }
        });
    }
}
```

## ClusterManager

``` rust
    /// Spawns a task to run a loop that receives cluster updates
    /// and updates the ClusterManager's state in turn.
    fn spawn_updater(
        log: Logger,
        metrics: Metrics,
        cluster_manager: Arc<RwLock<ClusterManager>>,
        mut cluster_updates_rx: mpsc::Receiver<ClusterUpdate>,
        mut shutdown_rx: watch::Receiver<()>,
    ) {
        tokio::spawn(async move {
            loop {
                tokio::select! {
                    update = cluster_updates_rx.recv() => {
                        match update {
                            Some(update) => {
                                debug!(log, "Received a cluster update.");
                                cluster_manager.write().update(Self::process_cluster_update(&metrics, update));
                            }
                            None => {
                                warn!(log, "Exiting cluster update receive loop because the sender dropped the channel.");
                                return;
                            }
                        }
                    }
                    _ = shutdown_rx.changed() => {
                        debug!(log, "Exiting cluster update receive loop because a shutdown signal was received.");
                        return;
                    },
                }
            }
        });
    }
```

## reactor

``` rust
loop {
    poll.poll(&events, timeout);
    for event in events.iter() {
        if (event.is_readable()) {
            for waker in event.readers.wakers {
                waker.wake();
            }
        }
        if (event.is_writeable()) {
            for waker in event.writers.wakers {
                waker.wake();
            }
        }
    }
}
```
copy from [Rust异步浅谈](https://leaxoy.github.io/2020/03/rust-async-runtime/)

## loop example
see [Is it possible to take ownership of data back from a for loop once the loop completes](https://users.rust-lang.org/t/is-it-possible-to-take-ownership-of-data-back-from-a-for-loop-once-the-loop-completes/3363)
see [Rust borrowing rules in `for...in` loop](https://stackoverflow.com/questions/60461475/rust-borrowing-rules-in-for-in-loop)
see [Rust: Looping on a member variable without mutably borrowing self](http://blog.ssokolow.com/archives/2017/06/23/rust-looping-on-a-member-variable-without-mutably-borrowing-self/)


text:
package com.manulaiko.notdarkorbit.client;

import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.backends.gwt.GwtApplication;
import com.badlogic.gdx.backends.gwt.GwtApplicationConfiguration;
import com.manulaiko.notdarkorbit.NotDarkOrbit;

public class HtmlLauncher extends GwtApplication {

        @Override
        public GwtApplicationConfiguration getConfig () {
                return new GwtApplicationConfiguration(480, 320);
        }

        @Override
        public ApplicationListener createApplicationListener () {
                return new NotDarkOrbit();
        }
}


text:
require 'formatted_date'
ActiveRecord::Base.send(:include, FormattedDate)


text:
import React from 'react';
import PropTypes from 'prop-types';
import { WidgetPreviewContainer } from 'netlify-cms-ui-default';

function NumberPreview({ value }) {
  return <WidgetPreviewContainer>{value}</WidgetPreviewContainer>;
}

NumberPreview.propTypes = {
  value: PropTypes.node,
};

export default NumberPreview;


text:
{% extends 'base/base.html' %}
{% load static %}
{% load i18n %}
{% block content %}

{% trans 'Lists' %}

{% trans 'List number'%} 1

{% trans 'List item number'%} 11

{% trans 'List item number'%} 223

{% trans 'List item number'%} 312

{% trans 'List item number'%} 414

{% trans 'List item number'%} 51

{% trans 'List item number'%} 623

{% trans 'List item number'%} 712

{% trans 'List item number'%} 814

{% trans 'List number'%} 2

{% trans 'Item title '%} 1

I ought to just try that with my boss. I'd get kicked out on the spot.

{% trans 'Item title '%} 2

Doing business like this takes much more effort than doing your own business at home.

{% trans 'Item title '%} 3

However hard the threw himself onto his right, he always rolled back to where he was.

{% trans 'Item title '%} 4

Gregor then turned to look out the window at the dull weather.

{% trans 'List number'%} 3

{% trans 'Comment' %} 1

I ought to just try that with my boss. I'd get kicked out on the spot.

{% trans 'Comment' %} 2

I ought to just try that with my boss. I'd get kicked out on the spot.

{% trans 'Comment' %} 3

I ought to just try that with my boss. I'd get kicked out on the spot.

{% trans 'Comment' %} 4

I ought to just try that with my boss. I'd get kicked out on the spot.

{% endblock content %}


text:
package com.github.lothar.security.acl.jpa;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.jpa.domain.Specification;

import com.github.lothar.security.acl.AclStrategy;
import com.github.lothar.security.acl.AclStrategyProvider;

public class JpaSpecProvider<T> {

  private Logger logger = LoggerFactory.getLogger(getClass());
  private AclStrategyProvider strategyProvider;
  private JpaSpecFeature<T> jpaSpecFeature;
  private Specification<T> defaultJpaSpec;

  public JpaSpecProvider(AclStrategyProvider strategyProvider, JpaSpecFeature<T> jpaSpecFeature,
      Specification<T> defaultJpaSpec) {
    super();
    this.strategyProvider = strategyProvider;
    this.jpaSpecFeature = jpaSpecFeature;
    this.defaultJpaSpec = defaultJpaSpec;
  }

  public Specification<T> jpaSpecFor(Class<? extends T> domainType) {
    Specification<T> aclJpaSpec = defaultJpaSpec;

    AclStrategy strategy = strategyProvider.strategyFor(domainType);
    if (strategy == null) {
      logger.debug("No strategy found for '{}' in strategy provider", domainType.getSimpleName());

    } else {
      Specification<T> aclJpaSpecification = strategy.handlerFor(jpaSpecFeature);
      if (aclJpaSpecification == null) {
        logger.debug(
            "No ACL JPA specification found in strategy {} > fall back on default ACL JPA specification",
            strategy);
      } else {
        aclJpaSpec = aclJpaSpecification;
      }
    }

    logger.debug("Using ACL JPA specification for '{}': {}", domainType.getSimpleName(),
        aclJpaSpec);
    return aclJpaSpec;
  }
}


text:
namespace scalan
{

const boost::blank unit_value = boost::blank();

template<class To, class What>
struct Assign {
    static void doIt(To& to, const What& what) {
        to = what;
    }
};

} //namespace scalan

#endif // __SCALAN_COMMON_HPP__


text:
package de.dk.util;

import de.dk.util.function.UnsafeConsumer;
import de.dk.util.function.UnsafeSupplier;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.Supplier;

/**
 * Some static utility methods, that can sometimes be useful.
 *
 * @author David Koettlitz
 *
Erstellt am 30.08.2016
 */
public final class Util {

   private Util() {}

   /**
    * Ensures that an object is created, if null
    *
    * @param object the object to do the nullcheck on
    * @param supplier the supplier of the object, if object is null
    * @param <E> the objects type
    *
    * @return the object if not null, otherwise the created object from the given
    * supplier
    */
   public static <E> E nonNull(E object, Supplier<E> supplier) {
      return object != null ? object : supplier.get();
   }

   public static int[] indicesOfEquals(Object[] a, Object[] b) {
      if (Objects.requireNonNull(a).length == 0
          | Objects.requireNonNull(b).length == 0) {

         return new int[0];
      }

      List<Integer> indices = new ArrayList<>(Math.max(a.length, b.length));
      for (int i = 0; i < a.length; i++) {
         for (int j = 0; j < b.length; j++) {
            if (a[i].equals(b[j])) {
               indices.add(i);
               break;
            }
         }
      }
      return box(indices.toArray(new Integer[indices.size()]));
   }

   /**
    * Inverts the array.
    *
    * @param array The array to be inverted
    * @param <T> The type of the array
    *
    * @return the inverted array which is the same object as the parameter array
    */
   public static <T> T[] invert(T[] array) {
      if (array == null)
         return null;

      int j = array.length - 1;
      for (int i = 0; i < array.length / 2; i++) {
         T element = array[i];
         array[i] = array[j];
         array[j--] = element;
      }
      return array;
   }

   /**
    * Inverts the array.
    *
    * @param array The array to be inverted
    *
    * @return the inverted array which is the same object as the parameter array
    */
   public static byte[] invertByteArray(byte[] array) {
      if (array == null)
         return null;

      int j = array.length - 1;
      for (int i = 0; i < array.length / 2; i++) {
         byte b = array[i];
         array[i] = array[j];
         array[j--] = b;
      }
      return array;
   }

   /**
    * Inverts the array.
    *
    * @param array The array to be inverted
    *
    * @return the inverted array which is the same object as the parameter array
    */
   public static short[] invertShortArray(short[] array) {
      if (array == null)
         return null;

      int j = array.length - 1;
      for (int i = 0; i < array.length / 2; i++) {
         short value = array[i];
         array[i] = array[j];
         array[j--] = value;
      }
      return array;
   }

   /**
    * Inverts the array.
    *
    * @param array The array to be inverted
    *
    * @return the inverted array which is the same object as the parameter array
    */
   public static int[] invertIntArray(int[] array) {
      if (array == null)
         return null;

      int j = array.length - 1;
      for (int i = 0; i < array.length / 2; i++) {
         int value = array[i];
         array[i] = array[j];
         array[j--] = value;
      }
      return array;
   }

   /**
    * Inverts the array.
    *
    * @param array The array to be inverted
    *
    * @return the inverted array which is the same object as the parameter array
    */
   public static long[] invertLongArray(long[] array) {
      if (array == null)
         return null;

      int j = array.length - 1;
      for (int i = 0; i < array.length / 2; i++) {
         long value = array[i];
         array[i] = array[j];
         array[j--] = value;
      }
      return array;
   }

   /**
    * Inverts the array.
    *
    * @param array The array to be inverted
    *
    * @return the inverted array which is the same object as the parameter array
    */
   public static boolean[] invertBoolArray(boolean[] array) {
      if (array == null)
         return null;

      int j = array.length - 1;
      for (int i = 0; i < array.length / 2; i++) {
         boolean value = array[i];
         array[i] = array[j];
         array[j--] = value;
      }
      return array;
   }

   /**
    * Inverts the array.
    *
    * @param array The array to be inverted
    *
    * @return the inverted array which is the same object as the parameter array
    */
   public static char[] invertCharArray(char[] array) {
      if (array == null)
         return null;

      int j = array.length - 1;
      for (int i = 0; i < array.length / 2; i++) {
         char value = array[i];
         array[i] = array[j];
         array[j--] = value;
      }
      return array;
   }

   /**
    * Get the last item of the array
    *
    * @param array The array from which to get the last item
    * @param <T> The type of the array
    *
    * @return The last item of the given array
    */
   public static <T> T lastItemOf(T[] array) {
      return array[array.length - 1];
   }

   /**
    * This method is equivalent to flag ? 1 : -1.
    *
    * @param flag The boolean to be converted to an int
    *
    * @return the value 1 if true is passed, otherwise -1.
    */
   public static int toInt(boolean flag) {
      return flag ? 1 : -1;
   }

   public static <T, E extends Exception> void loop(UnsafeSupplier<T, E> varSupplier,
                                                    Predicate<? super T> condition,
                                                    UnsafeConsumer<? super T, E> action) throws E {
      for (T var = varSupplier.get(); condition.test(var); var = varSupplier.get())
         action.accept(var);
   }

   /**
    * Processes the time to run the {@link Runnable}.
    *
    * @param r The runnable to be timed.
    * @return The time in nanoseconds the runnable took to run.
    */
   public static long time(Runnable r) {
      long nanos = System.nanoTime();
      r.run();
      return System.nanoTime() - nanos;
   }

   public static <T> Consumer<T> noOp() {
      return t -> {};
   }

   /**
    * Checks the equality of two objects considering null values.
    * Calls the equals method of object a if it is not null.
    *
    * @param a the object to check for equality to b
    * @param b the object to check for equality to a
    *
    * @return true if a AND b are null or if a.equals(b).
    * false if only one of the objects is null or if !a.equals(b).
    */
   public static boolean checkEquality(Object a, Object b) {
      if (a == null)
         return b == null;

      return a.equals(b);
   }

   /**
    * This method is equivalent to flag >= 0.
    *
    * @param flag The integer value to be converted to boolean
    *
    * @return true if the value is greater than or equal 0.
    * Otherwise false.
    */
   public static boolean toFlag(int flag) {
      return flag >= 0;
   }

   public static boolean[] box(Boolean[] array) {
      boolean[] result = new boolean[array.length];
      for (int i = 0; i < result.length; i++)
         result[i] = array[i];

      return result;
   }

   public static char[] box(Character[] array) {
      char[] result = new char[array.length];
      for (int i = 0; i < result.length; i++)
         result[i] = array[i];

      return result;
   }

   public static Character[] box(char[] array) {
      Character[] result = new Character[array.length];
      for (int i = 0; i < result.length; i++)
         result[i] = array[i];

      return result;
   }

   public static Integer[] box(int[] array) {
      Integer[] result = new Integer[array.length];
      for (int i = 0; i < result.length; i++)
         result[i] = array[i];

      return result;
   }

   public static int[] box(Integer[] array) {
      int[] result = new int[array.length];
      for (int i = 0; i < result.length; i++)
         result[i] = array[i];

      return result;
   }

   /**
    * Compares 2 objects by their {@link #toString()} method.
    *
    * @param a The first object to be compared
    * @param b The second object to be compared
    *
    * @return a negative integer, zero, or a positive integer as the
    * first argument is less than, equal to, or greater than the
    * second.
    *
    * @see Comparator
    */
   public static int compareByToString(Object a, Object b) {
      return a.toString().compareTo(b.toString());
   }
}


text:
package util

import (
	"fmt"
	"os"
)

func Error(format string, args ...interface{}) {
	fmt.Fprintf(os.Stderr, format, args...)
}

func Fatal(format string, args ...interface{}) {
	Error(format, args...)
	os.Exit(1)
}

func Message(format string, args ...interface{}) {
	fmt.Printf(format, args...)
}