text:
package edu.wustl.cab2b.server.multimodelcategory;

import static edu.wustl.cab2b.common.util.Constants.MMC_ENTITY_GROUP_NAME;
import static edu.wustl.cab2b.common.util.Constants.MULTIMODELCATEGORY;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.log4j.Logger;

import edu.common.dynamicextensions.domain.DomainObjectFactory;
import edu.common.dynamicextensions.domaininterface.AttributeInterface;
import edu.common.dynamicextensions.domaininterface.EntityGroupInterface;
import edu.common.dynamicextensions.domaininterface.EntityInterface;
import edu.common.dynamicextensions.entitymanager.EntityManager;
import edu.common.dynamicextensions.exception.DynamicExtensionsApplicationException;
import edu.common.dynamicextensions.exception.DynamicExtensionsSystemException;
import edu.wustl.cab2b.common.errorcodes.ErrorCodeConstants;
import edu.wustl.cab2b.common.exception.RuntimeException;
import edu.wustl.cab2b.common.multimodelcategory.MultiModelAttribute;
import edu.wustl.cab2b.common.multimodelcategory.MultiModelAttributeImpl;
import edu.wustl.cab2b.common.multimodelcategory.MultiModelCategory;
import edu.wustl.cab2b.common.multimodelcategory.MultiModelCategoryImpl;
import edu.wustl.cab2b.common.multimodelcategory.bean.MultiModelAttributeBean;
import edu.wustl.cab2b.common.multimodelcategory.bean.MultiModelCategoryBean;
import edu.wustl.cab2b.server.cache.EntityCache;
import edu.wustl.cab2b.server.category.CategoryOperations;
import edu.wustl.cab2b.server.category.InputCategorialAttribute;
import edu.wustl.cab2b.server.category.InputCategorialClass;
import edu.wustl.cab2b.server.category.InputCategory;
import edu.wustl.cab2b.server.category.PersistCategory;
import edu.wustl.cab2b.server.path.PathFinder;
import edu.wustl.cab2b.server.util.DynamicExtensionUtility;
import edu.wustl.common.querysuite.metadata.category.CategorialAttribute;
import edu.wustl.common.querysuite.metadata.category.CategorialClass;
import edu.wustl.common.querysuite.metadata.category.Category;
import edu.wustl.common.querysuite.metadata.path.IPath;
import edu.wustl.common.util.dbManager.DBUtil;

/**
 * This class takes in the MultiModelCategoryBean and generates the MultiModelCategogry out of it and finally
 * persists it into database. MultiModelCategoryBean is expected to get populated from UI where user/admin selects
 * or sets the appropriate values.
 *
 * @author chetan_patil
 * @author rajesh_vyas
 *
 */
public class PersistMultiModelCategory {

    private static final Logger logger =
            edu.wustl.common.util.logger.Logger.getLogger(PersistMultiModelCategory.class);

    private MultiModelCategoryBean mmcBean;

    private Set<EntityInterface> entities;

    private Map<EntityInterface, Collection<IPath>> sourceEntityToPaths;

    private Map<EntityInterface, Collection<InputCategorialAttribute>> entityInputCatagorialAttributeMap;

    private Map<Long, CategorialAttribute> attributeIDToCatAttr;

    private Map<MultiModelAttribute, Collection<Long>> multiModelAttributeToSelectedAttributeIds;

    private Set<MultiModelAttribute> multiModelAttributes;

    /**
     * Default constructor
     */
    public PersistMultiModelCategory() {
        attributeIDToCatAttr = new HashMap<Long, CategorialAttribute>();
        sourceEntityToPaths = new HashMap<EntityInterface, Collection<IPath>>();
        entityInputCatagorialAttributeMap = new HashMap<EntityInterface, Collection<InputCategorialAttribute>>();
        multiModelAttributes = new HashSet<MultiModelAttribute>();
        multiModelAttributeToSelectedAttributeIds = new HashMap<MultiModelAttribute, Collection<Long>>();
    }

    /**
     * This method assumes that MultiModelCategoryBean is well populated, so this class can create InputCategory
     * objects.
     *
     * @param mmcBean
     * @return
     */
    public MultiModelCategory persistMMC(MultiModelCategoryBean mmcBean) {
        this.mmcBean = mmcBean;

        MultiModelCategory multiModelCategory = initialize();

        PersistCategory persistCategory = new PersistCategory();
        CategoryOperations categoryOperations = new CategoryOperations();

        Collection<InputCategory> inputCategories = createInputCategories();
        Collection<Category> categories = new ArrayList<Category>(inputCategories.size());
        for (InputCategory inCategory : inputCategories) {
            logger.debug("Saving category: " + inCategory);
            Category category = persistCategory.persistCategory(inCategory, null, true);
            category.setSystemGenerated(Boolean.TRUE);
            mapAIToCatAttr(category.getRootClass());
            categoryOperations.saveCategory(category);
            categories.add(category);
            logger.debug("Saved category id: " + category.getDeEntityId());
        }
        addCategorialAttrsToMMA();
        multiModelCategory.setCategories(categories);
        multiModelCategory.setMultiModelAttributes(multiModelAttributes);

        return multiModelCategory;
    }

    /**
     * This method adds categorial attributes form category saved into MultiModelAttributes. Basically, it maps the
     * attributes of categories saved to MultiModelAttribute.
     */
    private void addCategorialAttrsToMMA() {
        for (MultiModelAttribute multiModelAttr : multiModelAttributes) {
            for (Long attribute : multiModelAttributeToSelectedAttributeIds.get(multiModelAttr)) {
                multiModelAttr.addCategorialAttribute(attributeIDToCatAttr.get(attribute));
            }
        }
    }

    /**
     * This method is recursively called so that all children are processed. It generates map of
     * AttributeInterface->CategorialAttribute, so mmaToSelectedAI can be used, to derive MMA->CategorialAttribute
     *
     * @param catClass
     */
    private void mapAIToCatAttr(CategorialClass catClass) {
        for (CategorialAttribute catAttr : catClass.getCategorialAttributeCollection()) {
            Long ai = catAttr.getDeSourceClassAttributeId();
            attributeIDToCatAttr.put(ai, catAttr);
        }
        //recursive call, so children CA's also mapped.
        for (CategorialClass childCatClass : catClass.getChildren()) {
            mapAIToCatAttr(childCatClass);
        }
    }

    /**
     * This method initializes and generates MultiModelCategory
     *
     * @return
     */
    private MultiModelCategory initialize() {
        MultiModelCategory multiModelCategory = createMultiModelCategory();

        entities = new HashSet<EntityInterface>(entityInputCatagorialAttributeMap.keySet());
        Set<EntityInterface> targetEntities = initEntityPathMapAndGetTargetEntities();

        //After removing all targets, 'entities' will only contain root categories
        entities.removeAll(targetEntities);

        return multiModelCategory;
    }

    /**
     * This method creates MultiModelCategory
     *
     * @return
     */
    private MultiModelCategory createMultiModelCategory() {
        EntityInterface mmcEntity = initMMCEntity();

        MultiModelCategory multiModelCategory = new MultiModelCategoryImpl();
        multiModelCategory.setApplicationGroup(mmcBean.getApplicationGroup());
        multiModelCategory.setEntity(mmcEntity);

        return multiModelCategory;
    }

    /**
     * This method creates DynamicExtension's entity for MultiModelCategory
     *
     * @return
     */
    private EntityInterface initMMCEntity() {
        EntityInterface mmcEntity = DomainObjectFactory.getInstance().createEntity();
        mmcEntity.setName(mmcBean.getName());
        mmcEntity.setDescription(mmcBean.getDescription());
        mmcEntity.setCreatedDate(new Date());
        mmcEntity.addEntityGroupInterface(getMMCEntityGroup());

        DynamicExtensionUtility.addTaggedValue(mmcEntity, MULTIMODELCATEGORY, MULTIMODELCATEGORY);
        initAttributes(mmcEntity);

        mmcEntity = DynamicExtensionUtility.persistEntity(mmcEntity);
        EntityCache.getInstance().addEntityToCache(mmcEntity);

        return mmcEntity;
    }

    /**
     * This method initializes the attributes into MultiModelCategory's DE entity.
     *
     * @param mmcEntity
     */
    private void initAttributes(EntityInterface mmcEntity) {
        assert mmcBean != null;
        assert mmcBean.getMultiModelAttributes() != null;

        Collection<MultiModelAttributeBean> mmaBeans = mmcBean.getMultiModelAttributes();
        for (MultiModelAttributeBean mmaBean : mmaBeans) {
            AttributeInterface deAttribute = MmcAttributeGenerator.getAttribute(mmaBean);
            deAttribute.setName(mmaBean.getName());
            deAttribute.setDescription(mmaBean.getDescription());

            mmcEntity.addAttribute(deAttribute);

            MultiModelAttribute multiModelAttribute = new MultiModelAttributeImpl();
            multiModelAttribute.setVisible(mmaBean.isVisible());
            multiModelAttribute.setAttribute(deAttribute);

            Collection<AttributeInterface> selectedMMCAttributes = mmaBean.getSelectedAttributes();
            Collection<Long> selectedAttributesIds = new ArrayList<Long>(selectedMMCAttributes.size());
            for (AttributeInterface selectedAttribute : selectedMMCAttributes) {
                selectedAttributesIds.add(selectedAttribute.getId());

                InputCategorialAttribute inputCatagorialAttribute = new InputCategorialAttribute();
                StringBuffer displayName =
                        new StringBuffer(mmaBean.getName()).append('_').append(selectedAttribute.getName());
                inputCatagorialAttribute.setDisplayName(displayName.toString());
                inputCatagorialAttribute.setDynamicExtAttribute(selectedAttribute);

                EntityInterface entity = selectedAttribute.getEntity();
                Collection<InputCategorialAttribute> inputCatagorialAttributes =
                        entityInputCatagorialAttributeMap.get(entity);
                if (inputCatagorialAttributes == null) {
                    inputCatagorialAttributes = new ArrayList<InputCategorialAttribute>();
                    entityInputCatagorialAttributeMap.put(entity, inputCatagorialAttributes);
                }
                inputCatagorialAttributes.add(inputCatagorialAttribute);
            }
            multiModelAttributeToSelectedAttributeIds.put(multiModelAttribute, selectedAttributesIds);
            multiModelAttributes.add(multiModelAttribute);
        }
    }

    /**
     * This method retrieves the MMC_Entity_Group if exists otherwise creates a new one.
     *
     * @return
     */
    private EntityGroupInterface getMMCEntityGroup() {
        EntityGroupInterface entityGroup = null;
        try {
            entityGroup = EntityManager.getInstance().getEntityGroupByName(MMC_ENTITY_GROUP_NAME);
        } catch (DynamicExtensionsSystemException e) {
            throw new RuntimeException(
                    "Got System exception from Dynamic Extension while fetching category entity group", e,
                    ErrorCodeConstants.DB_0001);
        } catch (DynamicExtensionsApplicationException e) {
            throw new RuntimeException(
                    "Got System exception from Dynamic Extension while fetching category entity group", e,
                    ErrorCodeConstants.DB_0001);
        }
        if (entityGroup == null) {
            entityGroup = DynamicExtensionUtility.createEntityGroup();
            entityGroup.setShortName(MMC_ENTITY_GROUP_NAME);
            entityGroup.setName(MMC_ENTITY_GROUP_NAME);
            entityGroup.setLongName(MMC_ENTITY_GROUP_NAME);
            entityGroup.setDescription(MMC_ENTITY_GROUP_NAME);
            DynamicExtensionUtility.markMetadataEntityGroup(entityGroup);
            entityGroup = DynamicExtensionUtility.persistEntityGroup(entityGroup);
        }
        return entityGroup;
    }

    /**
     * This method generates input categories which are needed for saving actual categories
     *
     * @return
     */
    private Collection<InputCategory> createInputCategories() {
        assert entities != null;

        Collection<InputCategory> inputCategories = new ArrayList<InputCategory>(entities.size());
        for (EntityInterface rootEntity : entities) {
            //Create InputCategorialClass
            InputCategorialClass rootClass = new InputCategorialClass();
            rootClass.setAttributeList(new ArrayList<InputCategorialAttribute>(entityInputCatagorialAttributeMap
                .get(rootEntity)));
            rootClass.setChildren(processOutPaths(rootEntity));
            rootClass.setPathFromParent(-1);

            //Create InputCategory
            InputCategory inputCategory = new InputCategory();

            StringBuffer name = new StringBuffer(mmcBean.getName()).append('_').append(rootEntity.getName());
            inputCategory.setName(name.toString());

            StringBuffer description =
                    new StringBuffer(mmcBean.getDescription()).append('_').append(rootEntity.getDescription());
            inputCategory.setDescription(description.toString());

            inputCategory.setRootCategorialClass(rootClass);
            inputCategory.setSubCategories(new ArrayList<InputCategory>());
            inputCategories.add(inputCategory);
        }

        return inputCategories;
    }

    /**
     * This method recursively instantiate complete hierarchy for CategorialClass.
     */
    private InputCategorialClass createInputCategorialClass(IPath outPath) {
        EntityInterface targetEntity = outPath.getTargetEntity();

        InputCategorialClass inputCategorialClass = new InputCategorialClass();
        inputCategorialClass.setPathFromParent(outPath.getPathId());
        Collection<InputCategorialAttribute> catAttributes = entityInputCatagorialAttributeMap.get(targetEntity);
        ArrayList<InputCategorialAttribute> inputCatAttrs = new ArrayList<InputCategorialAttribute>(catAttributes);
        inputCategorialClass.setAttributeList(inputCatAttrs);
        inputCategorialClass.setChildren(processOutPaths(targetEntity));

        return inputCategorialClass;
    }

    /**
     * This method processes out going paths
     *
     * @param sourceEntity
     * @return
     */
    private List<InputCategorialClass> processOutPaths(EntityInterface sourceEntity) {
        assert sourceEntityToPaths != null;

        List<InputCategorialClass> childrenICCs = new ArrayList<InputCategorialClass>();
        Collection<IPath> outPaths = sourceEntityToPaths.get(sourceEntity);
        if (outPaths != null) {
            for (IPath path : outPaths) {
                InputCategorialClass iccChild = createInputCategorialClass(path);
                childrenICCs.add(iccChild);
            }
        }
        return childrenICCs;
    }

    /**
     * This method initializes Entity->Paths map and returns the set of target entities.
     *
     * @return
     */
    private Set<EntityInterface> initEntityPathMapAndGetTargetEntities() {
        assert entities != null;

        Set<EntityInterface> targetEntities = new HashSet<EntityInterface>();
        Collection<IPath> paths = mmcBean.getPaths();
        for (IPath path : paths) {
            EntityInterface source = path.getSourceEntity();
            EntityInterface target = path.getTargetEntity();
            targetEntities.add(target);

            Collection<IPath> associationPaths = sourceEntityToPaths.get(source);
            if (associationPaths == null) {
                associationPaths = new ArrayList<IPath>();
                sourceEntityToPaths.put(source, associationPaths);
            }
            associationPaths.add(path);
        }

        return targetEntities;
    }

    /**
     * This method takes the path where where all the multi-model category XML files are stored and convert them to
     * MultiModelCategory objects to saves them into database.
     *
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        if (args == null || args.length == 0) {
            throw new java.lang.RuntimeException(
                    "Please specify the path to directory where multi model category XMLs are stored.");
        } else if (!(new File(args[0])).isDirectory()) {
            throw new IllegalArgumentException("The directory specified in invalid. Please correct the path.");
        }

        PathFinder.getInstance(DBUtil.getConnection());
        MultiModelCategoryOperations operations = new MultiModelCategoryOperations();

        //save in database
        File mmcDir = new File(args[0]);
        File[] mmcFiles = mmcDir.listFiles();
        MultiModelCategoryXmlParser parser = new MultiModelCategoryXmlParser();
        for (File mmcFile : mmcFiles) {
            try {
                MultiModelCategoryBean mmcBean = parser.getMultiModelCategory(mmcFile);
                MultiModelCategory mmCategory = new PersistMultiModelCategory().persistMMC(mmcBean);
                operations.saveMultiModelCategory(mmCategory);
            } catch (Exception e) {
                System.out.println("Cannot parse and load " + mmcFile.getAbsolutePath() + "\nRoot cause: "
                        + e.getMessage());
            }
        }

        //delete from database
        //MultiModelCategory mmCategory = operations.getMultiModelCategoryById(1L);
        //System.out.println(mmCategory.getEntity().getName());
        //operations.deleteMultiModelCategory(mmCategory);
    }
}


text:
CREATE proc [dbo].[b4nGetChargeDataRebate]
    @AccountName varchar(20) = '',
 @OrderRef varchar(25),
 @transactionPassRef varchar(50)
as
begin

 declare @paymentType int
 declare @handlerType int
 declare @tempOrderRef int
 declare @accountNo varchar (50)
 declare @CCPath varchar(255)
 declare @Secret varchar (50)
 declare @RebatePWD varchar(100)

 BEGIN TRAN
  set @paymentType = cast((select idValue from config where idName = 'automaticCharge') as int)
  set @handlerType = (select idValue from config where idName = 'handlerType')
  set @tempOrderRef = cast((select idValue from config where idName = 'tempOrderRef') as int)
  set @CCPath = (select idValue from config where idName = 'CCPath')
  set @Secret = (select idValue from config where idName = 'secret')
  set @RebatePWD = (select idValue from config where idName = 'CCRebatePWD')

  --does the @transactionPassRef refers to a SETTLE where there was a preceeding SHADOW?
  if not exists (select orderRef from b4ncctransactionlog where passRef = @transactionPassRef and TransactionType IN ('SHADOW','FULL'))
  begin
   if (select orderRef from b4ncctransactionlog where passRef = @transactionPassRef and TransactionType = 'SETTLE') is not null
   begin
    select @transactionPassRef = passRef from b4ncctransactionlog where TransactionType = 'SHADOW' and orderRef in (select orderRef from b4ncctransactionlog where passRef = @transactionPassRef and TransactionType = 'SETTLE')
   end
  end

  select
   @paymentType,
   dbo.fnGetChargeMerchandID(transactionItemType) as merchantID,
   @handlerType,
   OrderRef,
   dbo.fnGetChargeAccount(@AccountName, transactionItemType) as accountNo,
   @CCPath,
   @Secret,
   authCode,
   passRef,
   OrderRef,
   @RebatePWD,
   chargeAmount
  from
   b4nCCTransactionLog shadowLog
  where
   shadowLog.b4nOrderRef = @OrderRef
   AND (shadowLog.TransactionType  IN ('SHADOW','FULL'))
   AND shadowLog.orderRef = (select orderRef from b4ncctransactionlog settleLog where settleLog.passRef = @transactionPassRef  and settleLog.TransactionType IN ('SHADOW','FULL'))
 COMMIT TRAN
end
GRANT EXECUTE ON b4nGetChargeDataRebate TO b4nuser
GO
GRANT EXECUTE ON b4nGetChargeDataRebate TO ofsuser
GO
GRANT EXECUTE ON b4nGetChargeDataRebate TO reportuser
GO

redpajama_set_name: RedPajamaGithub


text:
import RPi.GPIO as GPIO
import time
import sys
import os.path
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
import GPIO_PORT

#sys.arg[0]=BrushlessCentral.py
TimeCounter= sys.argv[1]

GPIO.setmode(GPIO.BCM)
GPIO.setup(GPIO_PORT.BRUSHLESS_CENTER_PWM,GPIO.OUT)
p = GPIO.PWM(GPIO_PORT.BRUSHLESS_LEFT_PWM,50)
p.start(4)
time.sleep(2)
DutyCycleValue=4.8+(TimeCounter*.4)
try:
    while True:
        p.ChangeDutyCycle(DutyCycleValue)
        time.sleep(2)
        if DutyCycleValue > int(6.4):
            p.stop()
            GPIO.cleanup()
            exit()
except KeyboardInterrupt:
    p.stop()
    GPIO.cleanup()


text:
'use strict';

var d3 = require('d3');

var Registry = require('../../registry');
var Lib = require('../../lib');
var Drawing = require('../drawing');
var Color = require('../color');
var extractOpts = require('../colorscale/helpers').extractOpts;

var subTypes = require('../../traces/scatter/subtypes');
var stylePie = require('../../traces/pie/style_one');
var pieCastOption = require('../../traces/pie/helpers').castOption;

var CST_MARKER_SIZE = 12;
var CST_LINE_WIDTH = 5;
var CST_MARKER_LINE_WIDTH = 2;
var MAX_LINE_WIDTH = 10;
var MAX_MARKER_LINE_WIDTH = 5;

module.exports = function style(s, gd, legend) {
    var fullLayout = gd._fullLayout;
    if(!legend) legend = fullLayout.legend;
    var constantItemSizing = legend.itemsizing === 'constant';

    var boundLineWidth = function(mlw, cont, max, cst) {
        var v;
        if(mlw + 1) {
            v = mlw;
        } else if(cont && cont.width > 0) {
            v = cont.width;
        } else {
            return 0;
        }
        return constantItemSizing ? cst : Math.min(v, max);
    };

    s.each(function(d) {
        var traceGroup = d3.select(this);

        var layers = Lib.ensureSingle(traceGroup, 'g', 'layers');
        layers.style('opacity', d[0].trace.opacity);

        var valign = legend.valign;
        var lineHeight = d[0].lineHeight;
        var height = d[0].height;

        if(valign === 'middle' || !lineHeight || !height) {
            layers.attr('transform', null);
        } else {
            var factor = {top: 1, bottom: -1}[valign];
            var markerOffsetY = factor * (0.5 * (lineHeight - height + 3));
            layers.attr('transform', 'translate(0,' + markerOffsetY + ')');
        }

        var fill = layers
            .selectAll('g.legendfill')
                .data([d]);
        fill.enter().append('g')
            .classed('legendfill', true);

        var line = layers
            .selectAll('g.legendlines')
                .data([d]);
        line.enter().append('g')
            .classed('legendlines', true);

        var symbol = layers
            .selectAll('g.legendsymbols')
                .data([d]);
        symbol.enter().append('g')
            .classed('legendsymbols', true);

        symbol.selectAll('g.legendpoints')
            .data([d])
          .enter().append('g')
            .classed('legendpoints', true);
    })
    .each(styleSpatial)
    .each(styleWaterfalls)
    .each(styleFunnels)
    .each(styleBars)
    .each(styleBoxes)
    .each(styleFunnelareas)
    .each(stylePies)
    .each(styleLines)
    .each(stylePoints)
    .each(styleCandles)
    .each(styleOHLC);

    function styleLines(d) {
        var d0 = d[0];
        var trace = d0.trace;
        var showFill = trace.visible && trace.fill && trace.fill !== 'none';
        var showLine = subTypes.hasLines(trace);
        var contours = trace.contours;
        var showGradientLine = false;
        var showGradientFill = false;
        var dMod, tMod;

        var cOpts = extractOpts(trace);
        var colorscale = cOpts.colorscale;
        var reversescale = cOpts.reversescale;

        var fillGradient = function(s) {
            if(s.size()) {
                var gradientID = 'legendfill-' + trace.uid;
                Drawing.gradient(s, gd, gradientID,
                    getGradientDirection(reversescale),
                    colorscale, 'fill');
            }
        };

        var lineGradient = function(s) {
            if(s.size()) {
                var gradientID = 'legendline-' + trace.uid;
                Drawing.lineGroupStyle(s);
                Drawing.gradient(s, gd, gradientID,
                    getGradientDirection(reversescale),
                    colorscale, 'stroke');
            }
        };

        if(contours) {
            var coloring = contours.coloring;

            if(coloring === 'lines') {
                showGradientLine = true;
            } else {
                showLine = coloring === 'none' || coloring === 'heatmap' || contours.showlines;
            }

            if(contours.type === 'constraint') {
                showFill = contours._operation !== '=';
            } else if(coloring === 'fill' || coloring === 'heatmap') {
                showGradientFill = true;
            }
        }

        // with fill and no markers or text, move the line and fill up a bit
        // so it's more centered
        var markersOrText = subTypes.hasMarkers(trace) || subTypes.hasText(trace);
        var anyFill = showFill || showGradientFill;
        var anyLine = showLine || showGradientLine;
        var pathStart = (markersOrText || !anyFill) ? 'M5,0' :
            // with a line leave it slightly below center, to leave room for the
            // line thickness and because the line is usually more prominent
            anyLine ? 'M5,-2' : 'M5,-3';

        var this3 = d3.select(this);

        var fill = this3.select('.legendfill').selectAll('path')
            .data(showFill || showGradientFill ? [d] : []);
        fill.enter().append('path').classed('js-fill', true);
        fill.exit().remove();
        fill.attr('d', pathStart + 'h30v6h-30z')
            .call(showFill ? Drawing.fillGroupStyle : fillGradient);

        if(showLine || showGradientLine) {
            var lw = boundLineWidth(undefined, trace.line, MAX_LINE_WIDTH, CST_LINE_WIDTH);
            tMod = Lib.minExtend(trace, {line: {width: lw}});
            dMod = [Lib.minExtend(d0, {trace: tMod})];
        }

        var line = this3.select('.legendlines').selectAll('path')
            .data(showLine || showGradientLine ? [dMod] : []);
        line.enter().append('path').classed('js-line', true);
        line.exit().remove();

        // this is ugly... but you can't apply a gradient to a perfectly
        // horizontal or vertical line. Presumably because then
        // the system doesn't know how to scale vertical variation, even
        // though there *is* no vertical variation in this case.
        // so add an invisibly small angle to the line
        // This issue (and workaround) exist across (Mac) Chrome, FF, and Safari
        line.attr('d', pathStart + (showGradientLine ? 'l30,0.0001' : 'h30'))
            .call(showLine ? Drawing.lineGroupStyle : lineGradient);
    }

    function stylePoints(d) {
        var d0 = d[0];
        var trace = d0.trace;
        var showMarkers = subTypes.hasMarkers(trace);
        var showText = subTypes.hasText(trace);
        var showLines = subTypes.hasLines(trace);
        var dMod, tMod;

        // 'scatter3d' don't use gd.calcdata,
        // use d0.trace to infer arrayOk attributes

        function boundVal(attrIn, arrayToValFn, bounds, cst) {
            var valIn = Lib.nestedProperty(trace, attrIn).get();
            var valToBound = (Lib.isArrayOrTypedArray(valIn) && arrayToValFn) ?
                arrayToValFn(valIn) :
                valIn;

            if(constantItemSizing && valToBound && cst !== undefined) {
                valToBound = cst;
            }

            if(bounds) {
                if(valToBound < bounds[0]) return bounds[0];
                else if(valToBound > bounds[1]) return bounds[1];
            }
            return valToBound;
        }

        function pickFirst(array) {
            if(d0._distinct && d0.index && array[d0.index]) return array[d0.index];
            return array[0];
        }

        // constrain text, markers, etc so they'll fit on the legend
        if(showMarkers || showText || showLines) {
            var dEdit = {};
            var tEdit = {};

            if(showMarkers) {
                dEdit.mc = boundVal('marker.color', pickFirst);
                dEdit.mx = boundVal('marker.symbol', pickFirst);
                dEdit.mo = boundVal('marker.opacity', Lib.mean, [0.2, 1]);
                dEdit.mlc = boundVal('marker.line.color', pickFirst);
                dEdit.mlw = boundVal('marker.line.width', Lib.mean, [0, 5], CST_MARKER_LINE_WIDTH);
                tEdit.marker = {
                    sizeref: 1,
                    sizemin: 1,
                    sizemode: 'diameter'
                };

                var ms = boundVal('marker.size', Lib.mean, [2, 16], CST_MARKER_SIZE);
                dEdit.ms = ms;
                tEdit.marker.size = ms;
            }

            if(showLines) {
                tEdit.line = {
                    width: boundVal('line.width', pickFirst, [0, 10], CST_LINE_WIDTH)
                };
            }

            if(showText) {
                dEdit.tx = 'Aa';
                dEdit.tp = boundVal('textposition', pickFirst);
                dEdit.ts = 10;
                dEdit.tc = boundVal('textfont.color', pickFirst);
                dEdit.tf = boundVal('textfont.family', pickFirst);
            }

            dMod = [Lib.minExtend(d0, dEdit)];
            tMod = Lib.minExtend(trace, tEdit);

            // always show legend items in base state
            tMod.selectedpoints = null;

            // never show texttemplate
            tMod.texttemplate = null;
        }

        var ptgroup = d3.select(this).select('g.legendpoints');

        var pts = ptgroup.selectAll('path.scatterpts')
            .data(showMarkers ? dMod : []);
        // make sure marker is on the bottom, in case it enters after text
        pts.enter().insert('path', ':first-child')
            .classed('scatterpts', true)
            .attr('transform', 'translate(20,0)');
        pts.exit().remove();
        pts.call(Drawing.pointStyle, tMod, gd);

        // 'mrc' is set in pointStyle and used in textPointStyle:
        // constrain it here
        if(showMarkers) dMod[0].mrc = 3;

        var txt = ptgroup.selectAll('g.pointtext')
            .data(showText ? dMod : []);
        txt.enter()
            .append('g').classed('pointtext', true)
                .append('text').attr('transform', 'translate(20,0)');
        txt.exit().remove();
        txt.selectAll('text').call(Drawing.textPointStyle, tMod, gd);
    }

    function styleWaterfalls(d) {
        var trace = d[0].trace;
        var isWaterfall = trace.type === 'waterfall';

        if(d[0]._distinct && isWaterfall) {
            var cont = d[0].trace[d[0].dir].marker;
            d[0].mc = cont.color;
            d[0].mlw = cont.line.width;
            d[0].mlc = cont.line.color;
            return styleBarLike(d, this, 'waterfall');
        }

        var ptsData = [];
        if(trace.visible && isWaterfall) {
            ptsData = d[0].hasTotals ?
                [['increasing', 'M-6,-6V6H0Z'], ['totals', 'M6,6H0L-6,-6H-0Z'], ['decreasing', 'M6,6V-6H0Z']] :
                [['increasing', 'M-6,-6V6H6Z'], ['decreasing', 'M6,6V-6H-6Z']];
        }

        var pts = d3.select(this).select('g.legendpoints')
            .selectAll('path.legendwaterfall')
            .data(ptsData);
        pts.enter().append('path').classed('legendwaterfall', true)
            .attr('transform', 'translate(20,0)')
            .style('stroke-miterlimit', 1);
        pts.exit().remove();

        pts.each(function(dd) {
            var pt = d3.select(this);
            var cont = trace[dd[0]].marker;
            var lw = boundLineWidth(undefined, cont.line, MAX_MARKER_LINE_WIDTH, CST_MARKER_LINE_WIDTH);

            pt.attr('d', dd[1])
                .style('stroke-width', lw + 'px')
                .call(Color.fill, cont.color);

            if(lw) {
                pt.call(Color.stroke, cont.line.color);
            }
        });
    }

    function styleBars(d) {
        styleBarLike(d, this);
    }

    function styleFunnels(d) {
        styleBarLike(d, this, 'funnel');
    }

    function styleBarLike(d, lThis, desiredType) {
        var trace = d[0].trace;
        var marker = trace.marker || {};
        var markerLine = marker.line || {};

        var isVisible = (!desiredType) ? Registry.traceIs(trace, 'bar') :
            (trace.visible && trace.type === desiredType);

        var barpath = d3.select(lThis).select('g.legendpoints')
            .selectAll('path.legend' + desiredType)
            .data(isVisible ? [d] : []);
        barpath.enter().append('path').classed('legend' + desiredType, true)
            .attr('d', 'M6,6H-6V-6H6Z')
            .attr('transform', 'translate(20,0)');
        barpath.exit().remove();

        barpath.each(function(d) {
            var p = d3.select(this);
            var d0 = d[0];
            var w = boundLineWidth(d0.mlw, marker.line, MAX_MARKER_LINE_WIDTH, CST_MARKER_LINE_WIDTH);

            p.style('stroke-width', w + 'px')
                .call(Color.fill, d0.mc || marker.color);

            if(w) Color.stroke(p, d0.mlc || markerLine.color);
        });
    }

    function styleBoxes(d) {
        var trace = d[0].trace;

        var pts = d3.select(this).select('g.legendpoints')
            .selectAll('path.legendbox')
            .data(trace.visible && Registry.traceIs(trace, 'box-violin') ? [d] : []);
        pts.enter().append('path').classed('legendbox', true)
            // if we want the median bar, prepend M6,0H-6
            .attr('d', 'M6,6H-6V-6H6Z')
            .attr('transform', 'translate(20,0)');
        pts.exit().remove();

        pts.each(function() {
            var p = d3.select(this);

            if((trace.boxpoints === 'all' || trace.points === 'all') &&
                Color.opacity(trace.fillcolor) === 0 && Color.opacity((trace.line || {}).color) === 0
            ) {
                var tMod = Lib.minExtend(trace, {
                    marker: {
                        size: constantItemSizing ? CST_MARKER_SIZE : Lib.constrain(trace.marker.size, 2, 16),
                        sizeref: 1,
                        sizemin: 1,
                        sizemode: 'diameter'
                    }
                });
                pts.call(Drawing.pointStyle, tMod, gd);
            } else {
                var w = boundLineWidth(undefined, trace.line, MAX_MARKER_LINE_WIDTH, CST_MARKER_LINE_WIDTH);

                p.style('stroke-width', w + 'px')
                    .call(Color.fill, trace.fillcolor);

                if(w) Color.stroke(p, trace.line.color);
            }
        });
    }

    function styleCandles(d) {
        var trace = d[0].trace;

        var pts = d3.select(this).select('g.legendpoints')
            .selectAll('path.legendcandle')
            .data(trace.visible && trace.type === 'candlestick' ? [d, d] : []);
        pts.enter().append('path').classed('legendcandle', true)
            .attr('d', function(_, i) {
                if(i) return 'M-15,0H-8M-8,6V-6H8Z'; // increasing
                return 'M15,0H8M8,-6V6H-8Z'; // decreasing
            })
            .attr('transform', 'translate(20,0)')
            .style('stroke-miterlimit', 1);
        pts.exit().remove();

        pts.each(function(_, i) {
            var p = d3.select(this);
            var cont = trace[i ? 'increasing' : 'decreasing'];
            var w = boundLineWidth(undefined, cont.line, MAX_MARKER_LINE_WIDTH, CST_MARKER_LINE_WIDTH);

            p.style('stroke-width', w + 'px')
                .call(Color.fill, cont.fillcolor);

            if(w) Color.stroke(p, cont.line.color);
        });
    }

    function styleOHLC(d) {
        var trace = d[0].trace;

        var pts = d3.select(this).select('g.legendpoints')
            .selectAll('path.legendohlc')
            .data(trace.visible && trace.type === 'ohlc' ? [d, d] : []);
        pts.enter().append('path').classed('legendohlc', true)
            .attr('d', function(_, i) {
                if(i) return 'M-15,0H0M-8,-6V0'; // increasing
                return 'M15,0H0M8,6V0'; // decreasing
            })
            .attr('transform', 'translate(20,0)')
            .style('stroke-miterlimit', 1);
        pts.exit().remove();

        pts.each(function(_, i) {
            var p = d3.select(this);
            var cont = trace[i ? 'increasing' : 'decreasing'];
            var w = boundLineWidth(undefined, cont.line, MAX_MARKER_LINE_WIDTH, CST_MARKER_LINE_WIDTH);

            p.style('fill', 'none')
                .call(Drawing.dashLine, cont.line.dash, w);

            if(w) Color.stroke(p, cont.line.color);
        });
    }

    function stylePies(d) {
        stylePieLike(d, this, 'pie');
    }

    function styleFunnelareas(d) {
        stylePieLike(d, this, 'funnelarea');
    }

    function stylePieLike(d, lThis, desiredType) {
        var d0 = d[0];
        var trace = d0.trace;

        var isVisible = (!desiredType) ? Registry.traceIs(trace, desiredType) :
            (trace.visible && trace.type === desiredType);

        var pts = d3.select(lThis).select('g.legendpoints')
            .selectAll('path.legend' + desiredType)
            .data(isVisible ? [d] : []);
        pts.enter().append('path').classed('legend' + desiredType, true)
            .attr('d', 'M6,6H-6V-6H6Z')
            .attr('transform', 'translate(20,0)');
        pts.exit().remove();

        if(pts.size()) {
            var cont = (trace.marker || {}).line;
            var lw = boundLineWidth(pieCastOption(cont.width, d0.pts), cont, MAX_MARKER_LINE_WIDTH, CST_MARKER_LINE_WIDTH);

            var tMod = Lib.minExtend(trace, {marker: {line: {width: lw}}});
            // since minExtend do not slice more than 3 items we need to patch line.color here
            tMod.marker.line.color = cont.color;

            var d0Mod = Lib.minExtend(d0, {trace: tMod});

            stylePie(pts, d0Mod, tMod);
        }
    }

    function styleSpatial(d) { // i.e. maninly traces having z and colorscale
        var trace = d[0].trace;

        var useGradient;
        var ptsData = [];
        if(trace.visible) {
            switch(trace.type) {
                case 'histogram2d' :
                case 'heatmap' :
                    ptsData = [
                        ['M-15,-2V4H15V-2Z'] // similar to contour
                    ];
                    useGradient = true;
                    break;
                case 'choropleth' :
                case 'choroplethmapbox' :
                    ptsData = [
                        ['M-6,-6V6H6V-6Z']
                    ];
                    useGradient = true;
                    break;
                case 'densitymapbox' :
                    ptsData = [
                        ['M-6,0 a6,6 0 1,0 12,0 a 6,6 0 1,0 -12,0']
                    ];
                    useGradient = 'radial';
                    break;
                case 'cone' :
                    ptsData = [
                        ['M-6,2 A2,2 0 0,0 -6,6 V6L6,4Z'],
                        ['M-6,-6 A2,2 0 0,0 -6,-2 L6,-4Z'],
                        ['M-6,-2 A2,2 0 0,0 -6,2 L6,0Z']
                    ];
                    useGradient = false;
                    break;
                case 'streamtube' :
                    ptsData = [
                        ['M-6,2 A2,2 0 0,0 -6,6 H6 A2,2 0 0,1 6,2 Z'],
                        ['M-6,-6 A2,2 0 0,0 -6,-2 H6 A2,2 0 0,1 6,-6 Z'],
                        ['M-6,-2 A2,2 0 0,0 -6,2 H6 A2,2 0 0,1 6,-2 Z']
                    ];
                    useGradient = false;
                    break;
                case 'surface' :
                    ptsData = [
                        ['M-6,-6 A2,3 0 0,0 -6,0 H6 A2,3 0 0,1 6,-6 Z'],
                        ['M-6,1 A2,3 0 0,1 -6,6 H6 A2,3 0 0,0 6,0 Z']
                    ];
                    useGradient = true;
                    break;
                case 'mesh3d' :
                    ptsData = [
                        ['M-6,6H0L-6,-6Z'],
                        ['M6,6H0L6,-6Z'],
                        ['M-6,-6H6L0,6Z']
                    ];
                    useGradient = false;
                    break;
                case 'volume' :
                    ptsData = [
                        ['M-6,6H0L-6,-6Z'],
                        ['M6,6H0L6,-6Z'],
                        ['M-6,-6H6L0,6Z']
                    ];
                    useGradient = true;
                    break;
                case 'isosurface':
                    ptsData = [
                        ['M-6,6H0L-6,-6Z'],
                        ['M6,6H0L6,-6Z'],
                        ['M-6,-6 A12,24 0 0,0 6,-6 L0,6Z']
                    ];
                    useGradient = false;
                    break;
            }
        }

        var pts = d3.select(this).select('g.legendpoints')
            .selectAll('path.legend3dandfriends')
            .data(ptsData);
        pts.enter().append('path').classed('legend3dandfriends', true)
            .attr('transform', 'translate(20,0)')
            .style('stroke-miterlimit', 1);
        pts.exit().remove();

        pts.each(function(dd, i) {
            var pt = d3.select(this);

            var cOpts = extractOpts(trace);
            var colorscale = cOpts.colorscale;
            var reversescale = cOpts.reversescale;
            var fillGradient = function(s) {
                if(s.size()) {
                    var gradientID = 'legendfill-' + trace.uid;
                    Drawing.gradient(s, gd, gradientID,
                        getGradientDirection(reversescale, useGradient === 'radial'),
                        colorscale, 'fill');
                }
            };

            var fillColor;
            if(!colorscale) {
                var color = trace.vertexcolor || trace.facecolor || trace.color;
                fillColor = Lib.isArrayOrTypedArray(color) ? (color[i] || color[0]) : color;
            } else {
                if(!useGradient) {
                    var len = colorscale.length;
                    fillColor =
                        i === 0 ? colorscale[reversescale ? len - 1 : 0][1] : // minimum
                        i === 1 ? colorscale[reversescale ? 0 : len - 1][1] : // maximum
                            colorscale[Math.floor((len - 1) / 2)][1]; // middle
                }
            }

            pt.attr('d', dd[0]);
            if(fillColor) {
                pt.call(Color.fill, fillColor);
            } else {
                pt.call(fillGradient);
            }
        });
    }
};

function getGradientDirection(reversescale, isRadial) {
    var str = isRadial ? 'radial' : 'horizontal';
    return str + (reversescale ? '' : 'reversed');
}


text:
moduleFor('controller:tenant', 'Controller/Tenant', {
    setup: function() {
        // Additional setup code here
        JsHamcrest.Integration.QUnit();
        JsMockito.Integration.QUnit();
    },
    teardown: function() {
        $.mockjax.clear();
        translationMock();
    }
});

test('Should_be_able_to_disable_tenant', function(assert) {
    assert.expect(1);
    var dateCreated = new Date();

    var response = new Object({
        message: 'Disabled'
    });

    var jsonResponse = JSON.stringify(response);

    var promise = new Ember.RSVP.Promise(function(resolve, reject) {
        resolve(jsonResponse);
    });

    var expectedTenant = mock(DS.Model);
    when(expectedTenant).get('id').thenReturn('f7985a16-d966-4867-6d82-47ccb5ab3ca8');
    when(expectedTenant).get('name').thenReturn('Test Tenant');
    when(expectedTenant).get('alias').thenReturn('TEST');
    when(expectedTenant).get('preferred_locale').thenReturn('en-US');
    when(expectedTenant).get('enabled').thenReturn(false);
    when(expectedTenant).get('created_at').thenReturn(dateCreated);
    when(expectedTenant).set('enabled', false);
    when(expectedTenant).save().thenReturn(promise);

    var controller = this.subject();
    controller.transitionToRoute = Ember.K;

    var mockedFunc = mockFunction();
    var mockedController = mock(App.TenantController);
    when(mockedFunc).call(mockedController._enable(expectedTenant, false), anything()).thenReturn(promise);
    when(mockedFunc).call(mockedController.set('errorMessage', null), anything());
    when(mockedFunc).call(mockedController.transitionToRoute('tenants'), anything());

    var store = mock(DS.Store);
    controller.set('store', store);
    controller.set('model', expectedTenant);

    assert.deepEqual(controller.get('model'), expectedTenant);

    controller.send('disable', expectedTenant);

    verify(mockedController, times(1))._enable(expectedTenant, false);
    verify(mockedController, times(1)).set('errorMessage', null);
    verify(expectedTenant, times(1)).set('enabled', false);
    verify(expectedTenant, times(1)).save();
    verify(mockedController, times(1)).transitionToRoute('tenants');
});

test('Should_not_be_able_to_disable_tenant', function(assert) {
    assert.expect(1);
    var dateCreated = new Date();

    var error = new Object({
        message: 'Unable to disable tenant'
    });

    var response = new Object({
        error: error
    });

    var data = {
        responseJSON: response
    };

    var promise = new Ember.RSVP.Promise(function(resolve, reject) {
        reject(data);
    });

    var expectedTenant = mock(DS.Model);
    when(expectedTenant).get('id').thenReturn('f7985a16-d966-4867-6d82-47ccb5ab3ca8');
    when(expectedTenant).get('name').thenReturn('Test Tenant');
    when(expectedTenant).get('alias').thenReturn('TEST');
    when(expectedTenant).get('preferred_locale').thenReturn('en-US');
    when(expectedTenant).get('enabled').thenReturn(false);
    when(expectedTenant).get('created_at').thenReturn(dateCreated);
    when(expectedTenant).set('enabled', false);
    when(expectedTenant).save().thenReturn(promise);

    var controller = this.subject();
    controller.transitionToRoute = Ember.K;

    var mockedFunc = mockFunction();
    var mockedController = mock(App.TenantController);

    when(mockedFunc).call(mockedController._enable(expectedTenant, false), anything()).thenReturn(promise);
    when(mockedFunc).call(mockedController.set('errorMessage', null), anything());
    when(mockedFunc).call(mockedController.set('errorMessage', response.error.message), anything());

    var store = mock(DS.Store);
    controller.set('store', store);
    controller.set('model', expectedTenant);

    assert.deepEqual(controller.get('model'), expectedTenant);

    controller.send('disable', expectedTenant);

    verify(mockedController, times(1))._enable(expectedTenant, false);
    verify(mockedController, times(1)).set('errorMessage', null);
    verify(expectedTenant, times(1)).set('enabled', false);
    verify(expectedTenant, times(1)).save();
    verify(mockedController, times(1)).set('errorMessage', response.error.message);
});

test('Should_be_able_to_enable_tenant', function(assert) {
    assert.expect(1);
    var dateCreated = new Date();

    var response = new Object({
        message: 'Enabled'
    });

    var jsonResponse = JSON.stringify(response);

    var promise = new Ember.RSVP.Promise(function(resolve, reject) {
        resolve(jsonResponse);
    });

    var expectedTenant = mock(DS.Model);
    when(expectedTenant).get('id').thenReturn('f7985a16-d966-4867-6d82-47ccb5ab3ca8');
    when(expectedTenant).get('name').thenReturn('Test Tenant');
    when(expectedTenant).get('alias').thenReturn('TEST');
    when(expectedTenant).get('preferred_locale').thenReturn('en-US');
    when(expectedTenant).get('enabled').thenReturn(true);
    when(expectedTenant).get('created_at').thenReturn(dateCreated);
    when(expectedTenant).set('enabled', true);
    when(expectedTenant).save().thenReturn(promise);

    var controller = this.subject();
    controller.transitionToRoute = Ember.K;

    var mockedFunc = mockFunction();
    var mockedController = mock(App.TenantController);
    when(mockedFunc).call(mockedController._enable(expectedTenant, true), anything()).thenReturn(promise);
    when(mockedFunc).call(mockedController.set('errorMessage', null), anything());
    when(mockedFunc).call(mockedController.transitionToRoute('tenants'), anything());

    var store = mock(DS.Store);
    controller.set('store', store);
    controller.set('model', expectedTenant);

    assert.deepEqual(controller.get('model'), expectedTenant);

    controller.send('enable', expectedTenant);

    verify(mockedController, times(1))._enable(expectedTenant, true);
    verify(mockedController, times(1)).set('errorMessage', null);
    verify(expectedTenant, times(1)).set('enabled', true);
    verify(expectedTenant, times(1)).save();
    verify(mockedController, times(1)).transitionToRoute('tenants');
});

test('Should_not_be_able_to_enable_tenant', function(assert) {
    assert.expect(1);
    var dateCreated = new Date();

    var error = new Object({
        message: 'Unable to enable tenant'
    });

    var response = new Object({
        error: error
    });

    var data = {
        responseJSON: response
    };

    var promise = new Ember.RSVP.Promise(function(resolve, reject) {
        reject(data);
    });

    var expectedTenant = mock(DS.Model);
    when(expectedTenant).get('id').thenReturn('f7985a16-d966-4867-6d82-47ccb5ab3ca8');
    when(expectedTenant).get('name').thenReturn('Test Tenant');
    when(expectedTenant).get('alias').thenReturn('TEST');
    when(expectedTenant).get('preferred_locale').thenReturn('en-US');
    when(expectedTenant).get('enabled').thenReturn(true);
    when(expectedTenant).get('created_at').thenReturn(dateCreated);
    when(expectedTenant).set('enabled', true);
    when(expectedTenant).save().thenReturn(promise);

    var controller = this.subject();
    controller.transitionToRoute = Ember.K;

    var mockedFunc = mockFunction();
    var mockedController = mock(App.TenantController);

    when(mockedFunc).call(mockedController._enable(expectedTenant, true), anything()).thenReturn(promise);
    when(mockedFunc).call(mockedController.set('errorMessage', null), anything());
    when(mockedFunc).call(mockedController.set('errorMessage', response.error.message), anything());

    var store = mock(DS.Store);
    controller.set('store', store);
    controller.set('model', expectedTenant);

    assert.deepEqual(controller.get('model'), expectedTenant);

    controller.send('enable', expectedTenant);

    verify(mockedController, times(1))._enable(expectedTenant, true);
    verify(mockedController, times(1)).set('errorMessage', null);
    verify(expectedTenant, times(1)).set('enabled', true);
    verify(expectedTenant, times(1)).save();
    verify(mockedController, times(1)).set('errorMessage', response.error.message);
});


text:
using System.Collections.Generic;
using LogShark.Containers;
using LogShark.Shared;
using LogShark.Shared.LogReading.Containers;

namespace LogShark
{
    public class ProcessingNotificationsCollector : IProcessingNotificationsCollector
    {
        public int MaxErrorsWithDetails { get; }

        public IDictionary<string, int> ErrorCountByReporter { get; }
        public IList<ProcessingNotification> ProcessingErrorsDetails { get; }
        public int TotalErrorsReported { get; private set; }

        public IDictionary<string, int> WarningCountByReporter { get; }
        public IList<ProcessingNotification> ProcessingWarningsDetails { get; }
        public int TotalWarningsReported { get; private set; }

        private readonly object _errorLock;
        private readonly object _warningLock;

        public ProcessingNotificationsCollector(int maxErrorsWithDetails)
        {
            ErrorCountByReporter = new Dictionary<string, int>();
            MaxErrorsWithDetails = maxErrorsWithDetails;
            ProcessingErrorsDetails = new List<ProcessingNotification>(MaxErrorsWithDetails);
            TotalErrorsReported = 0;

            WarningCountByReporter = new Dictionary<string, int>();
            ProcessingWarningsDetails = new List<ProcessingNotification>(MaxErrorsWithDetails);
            TotalWarningsReported = 0;

            _errorLock = new object();
            _warningLock = new object();
        }

        public void ReportError(string message, string filePath, int lineNumber, string reportedBy)
        {
            lock (_errorLock)
            {
                if (TotalErrorsReported < MaxErrorsWithDetails)
                {
                    ProcessingErrorsDetails.Add(new ProcessingNotification(message, filePath, lineNumber, reportedBy));
                }

                ++TotalErrorsReported;

                if (ErrorCountByReporter.ContainsKey(reportedBy))
                {
                    ErrorCountByReporter[reportedBy] += 1;
                }
                else
                {
                    ErrorCountByReporter.Add(reportedBy, 1);
                }
            }
        }

        public void ReportError(string message, LogLine logLine, string reportedBy)
        {
            ReportError(message, logLine.LogFileInfo.FilePath, logLine.LineNumber, reportedBy);
        }

        public void ReportError(string message, string reportedBy)
        {
            ReportError(message, "N/A", 0, reportedBy);
        }

        public void ReportWarning(string message, string filePath, int lineNumber, string reportedBy)
        {
            lock (_warningLock)
            {
                if (TotalWarningsReported < MaxErrorsWithDetails)
                {
                    ProcessingWarningsDetails.Add(new ProcessingNotification(message, filePath, lineNumber,
                        reportedBy));
                }

                ++TotalWarningsReported;

                if (WarningCountByReporter.ContainsKey(reportedBy))
                {
                    WarningCountByReporter[reportedBy] += 1;
                }
                else
                {
                    WarningCountByReporter.Add(reportedBy, 1);
                }
            }
        }

        public void ReportWarning(string message, LogLine logLine, string reportedBy)
        {
            ReportWarning(message, logLine.LogFileInfo.FilePath, logLine.LineNumber, reportedBy);
        }

        public void ReportWarning(string message, string reportedBy)
        {
            ReportWarning(message, "N/A", 0, reportedBy);
        }
    }
}


text:
package com.latteyan.learn.java.progress.lock;

import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.ReentrantLock;

public class TestSyncMethods {
    public static void test(final int round, final int threadNum, final CyclicBarrier cyclicBarrier) {
        new SyncTest("Sync", round, threadNum, cyclicBarrier).testTime();
        new LockTest("Lock", round, threadNum, cyclicBarrier).testTime();
        new AtomicTest("Atom", round, threadNum, cyclicBarrier).testTime();
    }

    public static void main(final String args[]) {

        for (int i = 0; i < 5; i++) {
            final int round = 100000 * (i + 1);
            final int threadNum = 5 * (i + 1);
            final CyclicBarrier cb = new CyclicBarrier(threadNum * 2 + 1);
            System.out.println("==========================");
            System.out.println("round:" + round + " thread:" + threadNum);
            test(round, threadNum, cb);

        }
    }
}

class SyncTest extends TestTemplate {
    public SyncTest(final String _id, final int _round, final int _threadNum, final CyclicBarrier _cb) {
        super(_id, _round, _threadNum, _cb);
    }

    @Override
    /**
     * synchronized关键字不在方法签名里面,所以不涉及重载问题
     */
    synchronized long getValue() {
        return super.countValue;
    }

    @Override
    synchronized void sumValue() {
        super.countValue += preInit[index++ % round];
    }
}

class LockTest extends TestTemplate {
    ReentrantLock lock = new ReentrantLock();

    public LockTest(final String _id, final int _round, final int _threadNum, final CyclicBarrier _cb) {
        super(_id, _round, _threadNum, _cb);
    }

    /**
     * synchronized关键字不在方法签名里面,所以不涉及重载问题
     */
    @Override
    long getValue() {
        try {
            lock.lock();
            return super.countValue;
        } finally {
            lock.unlock();
        }
    }

    @Override
    void sumValue() {
        try {
            lock.lock();
            super.countValue += preInit[index++ % round];
        } finally {
            lock.unlock();
        }
    }
}

class AtomicTest extends TestTemplate {
    public AtomicTest(final String _id, final int _round, final int _threadNum, final CyclicBarrier _cb) {
        super(_id, _round, _threadNum, _cb);
    }

    @Override
    /**
     * synchronized关键字不在方法签名里面,所以不涉及重载问题
     */
    long getValue() {
        return super.countValueAtmoic.get();
    }

    @Override
    void sumValue() {
        super.countValueAtmoic.addAndGet(super.preInit[indexAtomic.get() % round]);
    }
}

abstract class TestTemplate {
    private final String id;
    protected int round;
    private final int threadNum;
    protected long countValue;
    protected AtomicLong countValueAtmoic = new AtomicLong(0);
    protected int[] preInit;
    protected int index;
    protected AtomicInteger indexAtomic = new AtomicInteger(0);
    Random r = new Random(47);
    // 任务栅栏,同批任务,先到达wait的任务挂起,一直等到全部任务到达制定的wait地点后,才能全部唤醒,继续执行
    private final CyclicBarrier cb;

    public TestTemplate(final String _id, final int _round, final int _threadNum, final CyclicBarrier _cb) {
        this.id = _id;
        this.round = _round;
        this.threadNum = _threadNum;
        cb = _cb;
        preInit = new int[round];
        for (int i = 0; i < preInit.length; i++) {
            preInit[i] = r.nextInt(100);
        }
    }

    abstract void sumValue();

    /*
     * 对long的操作是非原子的,原子操作只针对32位 long是64位,底层操作的时候分2个32位读写,因此不是线程安全
     */
    abstract long getValue();

    public void testTime() {
        final ExecutorService se = Executors.newCachedThreadPool();
        final long start = System.nanoTime();
        // 同时开启2*ThreadNum个数的读写线程
        for (int i = 0; i < threadNum; i++) {
            se.execute(new Runnable() {
                @Override
                public void run() {
                    for (int i = 0; i < round; i++) {
                        sumValue();
                    }

                    // 每个线程执行完同步方法后就等待
                    try {
                        cb.await();
                    } catch (final InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (final BrokenBarrierException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }
            });
            se.execute(new Runnable() {
                @Override
                public void run() {

                    getValue();
                    try {
                        // 每个线程执行完同步方法后就等待
                        cb.await();
                    } catch (final InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (final BrokenBarrierException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }
            });
        }

        try {
            // 当前统计线程也wait,所以CyclicBarrier的初始值是threadNum*2+1
            cb.await();
        } catch (final InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (final BrokenBarrierException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // 所有线程执行完成之后,才会跑到这一步
        final long duration = System.nanoTime() - start;
        System.out.println(id + " = " + duration);

    }

}


text:
#ifndef __SMART_SNMPD_NAGIOS_CHECKS_SNMP_COMM_TYPES_H_INCLUDED__
#define __SMART_SNMPD_NAGIOS_CHECKS_SNMP_COMM_TYPES_H_INCLUDED__

#include <smart-snmpd-nagios-plugins/snmp-pp-std.h>

/**
 * @brief wrapper class for SNMPv3 auth protocol constants for program option parsing
 *
 * This class is an adapter for SNMPv3 authentication protocol identifier constants
 * from snmp++ library and a human readable representation for user interaction.
 */
class SnmpV3AuthProtocol
{
public:
    /**
     * @brief standard and cast from long constructor
     *
     * @param auth_proto authentication protocol identifier
     */
    SnmpV3AuthProtocol(long int auth_proto = SNMP_AUTHPROTOCOL_NONE)
        : mAuthProto(auth_proto)
    {}

    //! copy constructor
    SnmpV3AuthProtocol(SnmpV3AuthProtocol const &r)
        : mAuthProto(r.mAuthProto)
    {}

    //! destructor
    ~SnmpV3AuthProtocol() {}

    //! assignment operator
    inline SnmpV3AuthProtocol & operator = (SnmpV3AuthProtocol const &r) { mAuthProto = r.mAuthProto; return *this; }
    //! cast operator into long int
    inline operator long () const { return mAuthProto; }

protected:
    /**
     * @brief managed auth-protocol value
     *
     * Can contain one of following values:
     * SNMP_AUTHPROTOCOL_NONE, SNMP_AUTHPROTOCOL_HMACMD5, SNMP_AUTHPROTOCOL_HMACSHA
     */
    long int mAuthProto;
};

/**
 * @brief specialization to convert SnmpV3AuthProtocol into an STL string
 *
 * @param ap - authentication protocol identifier
 */
template<>
std::string
to_string(SnmpV3AuthProtocol const &ap)
{
    switch( ap )
    {
    case SNMP_AUTHPROTOCOL_HMACMD5:
        return "md5";

    case SNMP_AUTHPROTOCOL_HMACSHA:
        return "sha";

    case SNMP_AUTHPROTOCOL_NONE:
        return "none";

    default:
        return string("invalid(") + to_string( static_cast<long>(ap) ) + ")";
    }
}

/**
 * overloaded stream output operator for SnmpV3AuthProtocol objects
 */
inline ostream &
operator << (ostream &os, SnmpV3AuthProtocol const &v)
{
    return os << to_string(v);
}

/**
 * overloaded stream input operator for SnmpV3AuthProtocol objects
 */
inline istream &
operator >> (istream &is, SnmpV3AuthProtocol &v)
{
    string s;
    is >> s;

    locase(s);

    if( s == "none" )
        v = SNMP_AUTHPROTOCOL_NONE;
    else if( s == "md5" )
        v = SNMP_AUTHPROTOCOL_HMACMD5;
    else if( s == "md5" )
        v = SNMP_AUTHPROTOCOL_HMACSHA;
    else
        throw invalid_value_execption(s + " -> SnmpV3AuthProtocol");

    return is;
}

/**
 * @brief wrapper class for SNMPv3 privacy protocol constants for program option parsing
 *
 * This class is an adapter for SNMPv3 privacy protocol identifier constants
 * from snmp++ library and a human readable representation for user interaction.
 */
class SnmpV3PrivProtocol
{
public:
    /**
     * @brief standard and cast from long constructor
     *
     * @param priv_proto privacy identifier
     */
    SnmpV3PrivProtocol(long int priv_proto = SNMP_PRIVPROTOCOL_NONE)
        : mPrivProto(priv_proto)
    {}

    //! copy constructor
    SnmpV3PrivProtocol(SnmpV3PrivProtocol const &r)
        : mPrivProto(r.mPrivProto)
    {}

    //! destructor
    ~SnmpV3PrivProtocol() {}

    //! assignment operator
    inline SnmpV3PrivProtocol & operator = (SnmpV3PrivProtocol const &r) { mPrivProto = r.mPrivProto; return *this; }
    //! cast operator into long int
    inline operator long () const { return mPrivProto; }

protected:
    /**
     * @brief managed priv-protocol value
     *
     * Can contain one of following values:
     * SNMP_PRIVPROTOCOL_NONE, SNMP_PRIVPROTOCOL_DES, SNMP_PRIVPROTOCOL_AES128,
     * SNMP_PRIVPROTOCOL_IDEA, SNMP_PRIVPROTOCOL_AES192, SNMP_PRIVPROTOCOL_AES256,
     * SNMP_PRIVPROTOCOL_3DESEDE
     */
    long int mPrivProto;
};

/**
 * specialized function to cast SnmpV3PrivProtocol into std::string
 *
 * @param pp - the SNMPv3 privacy protocol identifier
 * @return std::string - stringified priv protocol (human readable)
 */
template<>
std::string
to_string(SnmpV3PrivProtocol const &pp)
{
    switch( pp )
    {
    case SNMP_PRIVPROTOCOL_DES:
        return "des";

    case SNMP_PRIVPROTOCOL_3DESEDE:
        return "3des";

    case SNMP_PRIVPROTOCOL_IDEA:
        return "idea";

    case SNMP_PRIVPROTOCOL_AES128:
        return "aes128";

    case SNMP_PRIVPROTOCOL_AES192:
        return "aes192";

    case SNMP_PRIVPROTOCOL_AES256:
        return "aes256";

    case SNMP_PRIVPROTOCOL_NONE:
        return "none";

    default:
        return string("invalid(") + to_string( static_cast<long>(pp) ) + ")";
    }
}

/**
 * overloaded stream output operator for SnmpV3PrivProtocol objects
 */
inline ostream &
operator << (ostream &os, SnmpV3PrivProtocol const &v)
{
    return os << to_string(v);
}

/**
 * overloaded stream input operator for SnmpV3PrivProtocol objects
 */
inline istream &
operator >> (istream &is, SnmpV3PrivProtocol &v)
{
    string s;
    is >> s;

    locase(s);

    if( s == "none" )
        v = SNMP_PRIVPROTOCOL_NONE;
    else if( s == "des" )
        v = SNMP_PRIVPROTOCOL_DES;
    else if( s == "3des" )
        v = SNMP_PRIVPROTOCOL_IDEA;
    else if( s == "idea" )
        v = SNMP_PRIVPROTOCOL_DES;
    else if( s == "aes128" )
        v = SNMP_PRIVPROTOCOL_AES128;
    else if( s == "aes192" )
        v = SNMP_PRIVPROTOCOL_AES192;
    else if( s == "aes256" )
        v = SNMP_PRIVPROTOCOL_AES256;
    else
        throw invalid_value_execption(s + " -> SnmpV3PrivProtocol");

    return is;
}

#if 0
class SnmpV3SecurityModel
{
public:
    SnmpV3SecurityModel(long int sec_model = SNMP_SECURITY_MODEL_USM)
        : mSecurityLevel(sec_lvl)
    {}
    SnmpV3SecurityModel(SnmpV3SecurityModel const &r)
        : mSecurityLevel(r.mSecurityModel)
    {}

    ~SnmpV3SecurityModel() {}

    inline SnmpV3SecurityModel & operator = (SnmpV3SecurityModel const &r) { mSecurityModel = r.mSecurityModel; return *this; }
    inline operator long () const { return mSecurityModel; }

protected:
    long int mSecurityModel;
};
#endif

/**
 * @brief wrapper class for SNMPv3 security level constants for program option parsing
 *
 * This class is an adapter for SNMPv3 security level identifier constants
 * from snmp++ library and a human readable representation for user interaction.
 */
class SnmpV3SecurityLevel
{
public:
    /**
     * @brief standard and cast from long constructor
     *
     * @param sec_lvl security level identifier
     */
    SnmpV3SecurityLevel(long int sec_lvl = SNMP_SECURITY_LEVEL_NOAUTH_NOPRIV)
        : mSecurityLevel(sec_lvl)
    {}

    //! copy constructor
    SnmpV3SecurityLevel(SnmpV3SecurityLevel const &r)
        : mSecurityLevel(r.mSecurityLevel)
    {}

    //! destructor
    ~SnmpV3SecurityLevel() {}

    //! assignment operator
    inline SnmpV3SecurityLevel & operator = (SnmpV3SecurityLevel const &r) { mSecurityLevel = r.mSecurityLevel; return *this; }
    //! cast operator into long int
    inline operator long () const { return mSecurityLevel; }

protected:
    /**
     * @brief managed security level value
     *
     * Can contain one of following values:
     * SNMP_SECURITY_LEVEL_NOAUTH_NOPRIV, SNMP_SECURITY_LEVEL_AUTH_NOPRIV, SNMP_SECURITY_LEVEL_AUTH_PRIV
     */
    long int mSecurityLevel;
};

/**
 * specialized function to cast SnmpV3SecurityLevel into std::string
 *
 * @param sl - the SNMPv3 Priv Protocol
 * @return std::string - stringified security level (human readable)
 */
template<>
std::string
to_string(SnmpV3SecurityLevel const &sl)
{
    switch( sl )
    {
    case SNMP_SECURITY_LEVEL_NOAUTH_NOPRIV:
        return "noauth,nopriv";

    case SNMP_SECURITY_LEVEL_AUTH_NOPRIV:
        return "auth,nopriv";

    case SNMP_SECURITY_LEVEL_AUTH_PRIV:
        return "auth,priv";

    default:
        return string("invalid(") + to_string( static_cast<long>(sl) ) + ")";
    }
}

/**
 * overloaded stream output operator for SnmpV3SecurityLevel objects
 */
inline ostream &
operator << (ostream &os, SnmpV3SecurityLevel const &v)
{
    return os << to_string(v);
}

/**
 * overloaded stream input operator for SnmpV3SecurityLevel objects
 */
inline istream &
operator >> (istream &is, SnmpV3SecurityLevel &v)
{
    string s;
    is >> s;

    locase(s);

    if( ( s == "none" ) || ( s == "noauth" ) || ( s == "noauth,nopriv" ) )
        v = SNMP_SECURITY_LEVEL_NOAUTH_NOPRIV;
    else if( ( s == "nopriv" ) || ( s == "auth,nopriv" ) )
        v = SNMP_SECURITY_LEVEL_AUTH_NOPRIV;
    else if( ( s == "auth,priv" ) || ( s == "full" ) )
        v = SNMP_SECURITY_LEVEL_AUTH_PRIV;
    else
        throw invalid_value_execption(s + " -> SnmpV3SecurityLevel");

    return is;
}

#endif /* __SMART_SNMPD_NAGIOS_CHECKS_SNMP_COMM_TYPES_H_INCLUDED__ */


text:
<?php

/**
 * Configuration data collection
 *
 * @category    Mage
 * @package     Mage_Xmlconnect
 * @author      Magento Core Team <core@magentocommerce.com>
 */
class Mage_XmlConnect_Model_Resource_ConfigData_Collection extends Mage_Core_Model_Mysql4_Collection_Abstract
{
    /**
     * Is application filter applied
     *
     * @var bool
     */
    protected $_applicationFilter = false;

    /**
     * Internal constructor
     */
    protected function _construct()
    {
        $this->_init('xmlconnect/configData');
    }

    /**
     * Add application filter
     *
     * @param  $applicationId
     * @return Mage_XmlConnect_Model_Mysql4_ConfigData_Collection
     */
    public function addApplicationIdFilter($applicationId)
    {
        $this->_applicationFilter = true;
        $this->getSelect()->where('application_id=?', $applicationId);
        return $this;
    }

    /**
     * Add path filter
     *
     * @param  $path
     * @param bool $like
     * @return Mage_XmlConnect_Model_Mysql4_ConfigData_Collection
     */
    public function addPathFilter($path, $like = true)
    {
        if ($like) {
            $this->getSelect()->where('path like ?', $path . '/%');
        } else {
            $this->getSelect()->where('path=?', $path);
        }
        return $this;
    }

    /**
     * Add category filter
     *
     * @param  $category
     * @return Mage_XmlConnect_Model_Mysql4_ConfigData_Collection
     */
    public function addCategoryFilter($category)
    {
        $this->getSelect()->where('category=?', $category);
        return $this;
    }

    /**
     * Add value filter
     *
     * @param  $value
     * @return Mage_XmlConnect_Model_Mysql4_ConfigData_Collection
     */
    public function addValueFilter($value)
    {
        $this->getSelect()->where('value=?', $value);
        return $this;
    }

    /**
     * Add filter by array
     *
     * @param array $array
     * @return Mage_XmlConnect_Model_Mysql4_ConfigData_Collection
     */
    public function addArrayFilter(array $array)
    {
        foreach ($array as $key => $val) {
            $method = 'add' . uc_words($key, '') . 'Filter';
            if (is_callable($this->$method($val))) {
                return $this->$method($val);
            }
        }
        return $this;
    }

    /**
     * Convert items array to array for select options
     *
     * return items array
     * array(
     *      application_id => array(
     *          category => array(path)
     *      )
     * )
     *
     * @return array
     */
    public function toOptionArray()
    {
        $result = array();
        foreach ($this as $item) {
            $appId = $item->getData('application_id');
            $category = $item->getData('category');
            $path = $item->getData('path');
            $value = $item->getData('value');

            if ($this->_applicationFilter) {
                $result[$category][$path] = $value;
            } else {
                $result[$appId][$category][$path] = $value;
            }
        }
        return $result;
    }

    /**
     * Get Application filter status
     *
     * @return boolean
     */
    public function getApplicationFilter()
    {
        return $this->_applicationFilter;
    }

    /**
     * Set Application filter status
     *
     * @param boolean $applicationFilter
     */
    public function setApplicationFilter($applicationFilter)
    {
        $this->_applicationFilter = $applicationFilter;
    }
}


text:
require(["doh/runner", 'jimu/ConfigManager', 'dojo/topic'],
function(doh, ConfigManager, topic) {

	doh.register("config tests", [

	function nonExistConfig() {
		var cm = ConfigManager.prototype.getInstance('non-exist');
		var dohDeferred = new doh.Deferred();

		var handle = topic.subscribe('appConfigLoadError', function(err){
			handle.remove();
			dohDeferred.getTestCallback(function(err){
				doh.assertEqual(404, err.response.status);
				delete cm;
			})(err);
		});

		cm.startup();

		return dohDeferred;
  },

  function badJSONFormat() {
		var cm = ConfigManager.prototype.getInstance({config: 'bad-format'});
		var dohDeferred = new doh.Deferred();

		var handle = topic.subscribe('appConfigLoadError', function(err){
			handle.remove();
			dohDeferred.getTestCallback(function(err){
				doh.assertTrue(typeof err !== 'undefined');
				delete cm;
			})(err);
		});

		cm.startup();

		return dohDeferred;
  },

  function rightConfig() {
		var cm = ConfigManager.prototype.getInstance({config: 'ok'});
		var dohDeferred = new doh.Deferred();

		var handle = topic.subscribe('appConfigLoaded', function(config){
			handle.remove();
			dohDeferred.getTestCallback(function(){
				doh.assertEqual(undefined, config.theme);
				delete cm;
			})();
		});

		cm.startup();

		return dohDeferred;
  }

	]);

	doh.runOnLoad();
});


text:
KeyedService* FakeProfileOAuth2TokenServiceWrapper::Build(
    content::BrowserContext* context) {
  Profile* profile = static_cast<Profile*>(context);
  return new FakeProfileOAuth2TokenServiceWrapper(profile, false);
}

// static
KeyedService*
FakeProfileOAuth2TokenServiceWrapper::BuildAutoIssuingTokenService(
    content::BrowserContext* context) {
  Profile* profile = static_cast<Profile*>(context);
  return new FakeProfileOAuth2TokenServiceWrapper(profile, true);
}

FakeProfileOAuth2TokenServiceWrapper::FakeProfileOAuth2TokenServiceWrapper(
    Profile* profile,
    bool auto_issue_tokens) {
  if (auto_issue_tokens)
    service_.set_auto_post_fetch_response_on_message_loop(true);
  service_.Initialize(
      ChromeSigninClientFactory::GetInstance()->GetForProfile(profile),
      reinterpret_cast<Profile*>(profile));
}

FakeProfileOAuth2TokenServiceWrapper::~FakeProfileOAuth2TokenServiceWrapper() {
  service_.Shutdown();
}

ProfileOAuth2TokenService*
FakeProfileOAuth2TokenServiceWrapper::GetProfileOAuth2TokenService() {
  return &service_;
}


text:
package main

import "github.com/src-d/fsbench/fs"

type SeeweedFSCommand struct {
	Server string `short:"m" default:"127.0.0.1:9333" description:"SeaweedFS master."`
	Path   string `short:"p" default:"/tmp/" description:"Filesystem path."`
	BaseCommand
}

func (c *SeeweedFSCommand) Execute(args []string) error {
	fs := fs.NewSeaweedFSClient(c.Server, c.Path)
	c.BaseCommand.fs = fs

	return c.BaseCommand.Execute(args)
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="generator" content="rustdoc">
    <meta name="description" content="API documentation for the Rust `gen_symbol_name` fn in crate `gl_generator`.">
    <meta name="keywords" content="rust, rustlang, rust-lang, gen_symbol_name">

    <title>gl_generator::generators::gen_symbol_name - Rust</title>

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

gl_generator::<wbr>generators

        <form class="search-form js-only">

                <input class="search-input" name="search"
                       autocomplete="off"
                       placeholder="Click or press 'S' to search, '?' for more options..."
                       type="search">

        </form>

Function gl_generator::<wbr>generators::<wbr>gen_symbol_name

                [−]

        [src]

pub fn gen_symbol_name(ns: &Ns, cmd: &str) -> String

Generates the native symbol name of a Cmd.

Example results: "glClear", "wglCreateContext", etc.

Keyboard shortcuts

?

Show this help dialog

S

Focus the search field

⇤

Move up in search results

⇥

Move down in search results

⏎

Go to active search result

Search tricks

                Prefix searches with a type followed by a colon (e.g.
                fn:) to restrict the search to a given type.

                Accepted types are: fn, mod,
                struct, enum,
                trait, typedef (or
                tdef).

                Search functions by type signature (e.g.
                vec -> usize)


text:
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import * as Extensions from '../extensions/extensions.js';  // eslint-disable-line no-unused-vars
import * as SDK from '../sdk/sdk.js';                       // eslint-disable-line no-unused-vars

import {PerformanceModel} from './PerformanceModel.js';      // eslint-disable-line no-unused-vars
import {Client, TimelineLoader} from './TimelineLoader.js';  // eslint-disable-line no-unused-vars

/**
 * @implements {Extensions.ExtensionTraceProvider.TracingSession}
 * @implements {Client}
 */
export class ExtensionTracingSession {
  /**
   * @param {!Extensions.ExtensionTraceProvider.ExtensionTraceProvider} provider
   * @param {!PerformanceModel} performanceModel
   */
  constructor(provider, performanceModel) {
    this._provider = provider;
    this._performanceModel = performanceModel;
    /** @type {function()} */
    this._completionCallback;
    this._completionPromise = new Promise(fulfill => {
      this._completionCallback = fulfill;
    });
    this._timeOffset = 0;
  }

  /** @override */
  loadingStarted() {
  }

  /** @override */
  processingStarted() {
  }

  /**
   * @override
   * @param {number=} progress
   */
  loadingProgress(progress) {
  }

  /**
   * @override
   * @param {?SDK.TracingModel.TracingModel} tracingModel
   */
  loadingComplete(tracingModel) {
    if (!tracingModel) {
      return;
    }
    this._performanceModel.addExtensionEvents(this._provider.longDisplayName(), tracingModel, this._timeOffset);
    this._completionCallback();
  }

  /**
   * @override
   * @param {string} url
   * @param {number} timeOffsetMicroseconds
   */
  complete(url, timeOffsetMicroseconds) {
    if (!url) {
      this._completionCallback();
      return;
    }
    this._timeOffset = timeOffsetMicroseconds;
    TimelineLoader.loadFromURL(url, this);
  }

  start() {
    this._provider.start(this);
  }

  /** @return {!Promise<string>} */
  stop() {
    this._provider.stop();
    return this._completionPromise;
  }
}


text:
package io.udash.web.guide.views.frontend

import io.udash._
import io.udash.web.guide.FrontendState
import io.udash.web.guide.views.ViewContainer

import scalatags.JsDom

case object FrontendViewFactory extends StaticViewFactory[FrontendState.type](() => new FrontendView)

class FrontendView extends ViewContainer {
  import JsDom.all._

  protected val child = div().render

  override def getTemplate: Modifier = div(
    h1("Frontend"),
    p(
      "In this part of the guide you will read about creating a frontend application with Udash. Let's make your ",
      "frontend type-safe, elegant and maintainable. "
    ),
    child
  )
}


text:
import { expect } from 'chai';
import React from 'react';
import Main from '../lib/components/Main';
import Weather from '../lib/components/Weathrly';
import CurrentWeather from '../lib/components/CurrentWeather';
import CurrentTemp from '../lib/components/current-weather/CurrentTemp';
import HighLow from '../lib/components/current-weather/HighLow';
import Summary from '../lib/components/current-weather/summary';
import Daily from '../lib/components/Daily';
import Hourly from '../lib/components/Hourly';
import Welcome from '../lib/components/Welcome';
import NotFound from '../lib/components/Error';
import { shallow, mount, render } from 'enzyme';
import sinon from 'sinon';
const Data = require('./forecast10.json');
import $ui from 'jquery-ui';

describe('Main', () => {
  it('should have a component called Weather', () => {
    const wrapper = shallow(<Main/>);
    expect(wrapper.find('Weather')).to.have.length(1);
  });
});

describe('Weather', () => {
  it('should have two state properties by default', () => {
    const wrapper = shallow(<Weather/>);
    const weatherState = wrapper.state();
    expect(weatherState.location).to.equal('');
    expect(weatherState.weather).to.deep.equal([]);
  });

  it('should have an input field and submit button', () => {
    const wrapper = shallow(<Weather/>);
    const weatherState = wrapper.state();
    const searchInput = wrapper.find('.search');
    const inputField = wrapper.find('.go');
    expect(wrapper.find('.search')).to.have.length(1);
    expect(wrapper.find('.go')).to.have.length(1);
  });

  it('search field should take location and update state', () => {
    const wrapper = shallow(<Weather/>);
    const searchInput = wrapper.find('.search');
    expect(wrapper.state().location).to.equal('');
    searchInput.simulate('change', { target: { value: 'charlieville' } });
    expect(wrapper.state().location).to.equal('charlieville');
  });

  it('should be able to change location', () => {
    const wrapper = shallow(<Weather/>);
    const searchInput = wrapper.find('.search');
    expect(wrapper.state().location).to.equal('');
    searchInput.simulate('change', { target: { value: 'charlieville' } });
    expect(wrapper.state().location).to.equal('charlieville');
    searchInput.simulate('change', { target: { value: 'boston, ma' } });
    expect(wrapper.state().location).to.equal('boston, ma');
  });

  it('simulates submit button click event', () => {
    const wrapper = shallow(<Weather/>);
    const obj = wrapper.instance();
    sinon.spy(obj, 'handleSubmit');
    const submitButton = wrapper.find('.go');
    submitButton.simulate('click');
    expect(obj.handleSubmit.callCount).to.equal(1);
  });

  it('Should start with welcome page', () => {
    const wrapper = shallow(<Weather />);
    expect(wrapper.find(Welcome)).to.have.length(1);
  });

  it('Renders hourly forecast to the page', () => {
    const weather = [Data];
    const wrapper = shallow(<Weather weather={ weather }/>);
    const current = shallow(<CurrentWeather weather={ weather }/>);
    expect(current.find(Hourly)).to.have.length(1);
  });

  it('Renders temps to page when weather has an object', () => {
    const weather = [Data];
    const wrapper = shallow(<Weather/>);
    wrapper.setState({ weather: weather });
    const current = <CurrentWeather/>;
    expect(wrapper.find(CurrentWeather)).to.have.length(1);
    expect(wrapper.find(Daily)).to.have.length(1);
  });
});

describe('CurrentWeather', () => {
  it('Renders temps to page when weather has an object', () => {
    const wrapper = shallow(<Weather/>);
    const weather = [Data];
    wrapper.setState({ weather: weather });
    const current = <CurrentWeather/>;
    expect(wrapper.find(CurrentWeather)).to.have.length(1);
    expect(wrapper.find(Daily)).to.have.length(1);
  });

  it('CurrentWeather should display current location', () => {
    const weather = [Data];
    const wrapper = shallow(<CurrentWeather weather={ weather }/>);
    const location = wrapper.find('.location');
    expect(location.text()).to.equal('Parker, CO');
  });

  it('CurrentTemp should display current temperature', () => {
    const weather = [Data];
    const wrapper = shallow(<CurrentTemp weather={ weather }/>);
    const temp = wrapper.find('.temperature');
    expect(temp.text()).to.equal('48°F');
  });

  it('Should display the projected high and low temperatures', () => {
    const weather = [Data];
    const wrapper = shallow(<HighLow weather={ weather }/>);
    const temps = wrapper.find('.temps');
    expect(temps.text()).to.equal(' 51° 25°');
  });

  it('Should display the forecast summary for the day', () => {
    const weather = [Data];
    const wrapper = shallow(<Summary weather={ weather }/>);
    const summary = wrapper.find('.summary');
    expect(summary.text()).to.equal(
      'Windy with a mix of clouds and sun. High 51F. Winds SW at 20 to 30 mph.');
  });
});


text:
 Reino  A região padrão a ser usada.
 Deve estar em maiúsculas.


text:
/*
 * ResearcherDashboardPage Messages
 *
 * This contains all the text for the ResearcherDashboardPage component.
 */
import { defineMessages } from 'react-intl';

export default defineMessages({
  header: {
    id: 'boilerplate.containers.ResearcherDashboardPage.header',
    defaultMessage: 'Researcher Dashboard',
  },
  dashboardDescription: {
    id: 'boilerplate.containers.ResearcherDashboardPage.dashboard.description',
    defaultMessage: 'You can set default experiment settings here.',
  },
  currentDefaultExperimentDescription: {
    id: 'boilerplate.containers.ResearcherDashboardPage.current.default.experiment.description',
    defaultMessage: 'Current settings: ',
  },
  formSessions: {
    id: 'boilerplate.containers.ResearcherDashboardPage.form.sessons',
    defaultMessage: 'Sessions',
  },
  formFeedback: {
    id: 'boilerplate.containers.ResearcherDashboardPage.form.feedback',
    defaultMessage: 'Feedback',
  },
  formTimeLimit: {
    id: 'boilerplate.containers.ResearcherDashboardPage.form.time.limit',
    defaultMessage: 'Time Limit',
  },
  formDelay: {
    id: 'boilerplate.containers.ResearcherDashboardPage.form.delay',
    defaultMessage: 'Delay',
  },
  formConfigsPerSession: {
    id: 'boilerplate.containers.ResearcherDashboardPage.form.configs.per.session',
    defaultMessage: 'Configurations per session',
  },
  unauthorized: {
    id: 'boilerplate.containers.ResearcherDashboardPage.nologin',
    defaultMessage: 'Please log in as researcher to see this page.',
  },
});


text:
package packet

import (
	"fmt"
)

// Decode performs 6b/4b decoding and CRC verification.
// It returns the decoded data, excluding the CRC byte.
func Decode(p []byte) ([]byte, error) {
	data, err := Decode6b4b(p)
	if err != nil {
		return data, err
	}
	if len(data) == 0 {
		return nil, fmt.Errorf("empty packet")
	}
	if IsSensorType(data[0]) {
		return checkCRC16(data)
	}
	return checkCRC8(data)
}

func checkCRC8(data []byte) ([]byte, error) {
	last := len(data) - 1
	pktCRC := data[last]
	data = data[:last] // without CRC
	calcCRC := CRC8(data)
	if calcCRC != pktCRC {
		return nil, fmt.Errorf("computed CRC %02X but received %02X", calcCRC, pktCRC)
	}
	return data, nil
}

func checkCRC16(data []byte) ([]byte, error) {
	last := len(data) - 2
	pktCRC := uint16(data[last])<<8 | uint16(data[last+1])
	data = data[:last] // without CRC
	calcCRC := CRC16(data)
	if calcCRC != pktCRC {
		return nil, fmt.Errorf("computed CRC %04X but received %04X", calcCRC, pktCRC)
	}
	return data, nil
}

// Encode appends the CRC to the data and returns the 4b/6b-encoded result.
// This may modify data's underlying array.
func Encode(data []byte) []byte {
	var msg []byte
	if IsSensorType(data[0]) {
		crc := CRC16(data)
		msg = append(data, byte(crc>>8), byte(crc&0xFF))
	} else {
		msg = append(data, CRC8(data))
	}
	return Encode4b6b(msg)
}


text:
package net.nicoulaj.maven.plugins.checksum.execution.target;

import net.nicoulaj.maven.plugins.checksum.artifacts.ArtifactListener;
import net.nicoulaj.maven.plugins.checksum.digest.DigesterFactory;
import net.nicoulaj.maven.plugins.checksum.mojo.ChecksumFile;
import org.codehaus.plexus.util.FileUtils;

import java.io.File;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;

/**
 * An {@link ExecutionTarget} that writes digests to separate files.
 *
 * @author Julien Nicoulaud
 * @since 1.0
 */
public class OneHashPerFileTarget
    implements ExecutionTarget
{
    /**
     * Encoding to use for generated files.
     */
    protected String encoding;

    /**
     * The files output directory.
     */
    protected File outputDirectory;

    /**
     * List of listeners which are notified every time a checksum file is created.
     *
     * @since 1.3
     */
    protected final Iterable<? extends ArtifactListener> artifactListeners;

    /**
     * Append the filename to the hash file
     *
     * @since 1.4
     */
    protected boolean appendFilename = false;

    /**
     * Build a new instance of {@link OneHashPerFileTarget}.
     *  @param encoding        the encoding to use for generated files.
     * @param outputDirectory the files output directory.
     * @param artifactListeners
     */
    public OneHashPerFileTarget(String encoding, File outputDirectory, Iterable<? extends ArtifactListener> artifactListeners)
    {
        this.encoding = encoding;
        this.outputDirectory = outputDirectory;
        this.artifactListeners = artifactListeners;
    }

    /**
     * Build a new instance of {@link OneHashPerFileTarget}.
     *  @param encoding        the encoding to use for generated files.
     * @param outputDirectory the files output directory.
     * @param artifactListeners
     */
    public OneHashPerFileTarget(String encoding, File outputDirectory, Iterable<? extends ArtifactListener> artifactListeners, boolean appendFilename)
    {
        this.encoding = encoding;
        this.outputDirectory = outputDirectory;
        this.artifactListeners = artifactListeners;
        this.appendFilename = appendFilename;
    }

    /**
     * Build a new instance of {@link OneHashPerFileTarget}.
     *
     * @param encoding the encoding to use for generated files.
     * @param artifactListeners
     */
    public OneHashPerFileTarget(String encoding, Iterable<? extends ArtifactListener> artifactListeners)
    {
        this( encoding, null, artifactListeners);
    }

    /**
     * {@inheritDoc}
     */
    public void init()
        throws ExecutionTargetInitializationException
    {
        // Make sure the output directory exists or can be created.
        if ( outputDirectory != null )
        {
            if ( outputDirectory.exists() && !outputDirectory.isDirectory() )
            {
                throw new ExecutionTargetInitializationException(
                    "'" + outputDirectory.getPath() + "' already exists and is not a directory." );
            }
            else
            {
                outputDirectory.mkdirs();
            }
        }
    }

    /**
     * {@inheritDoc}
     */
    public void write( String digest, ChecksumFile file, String algorithm )
        throws ExecutionTargetWriteException
    {
        try
        {
            File outputFileDirectory = ( outputDirectory != null ) ? outputDirectory : file.getFile().getParentFile();
            String fileExtension = DigesterFactory.getInstance().getFileDigester(algorithm).getFileExtension();
            String outputFileName = file.getFile().getName() + fileExtension;
            File outputFile = new File(outputFileDirectory.getPath(), outputFileName);
            StringBuilder digestToPrint = new StringBuilder(digest);
            if(appendFilename){
                digestToPrint.append("  ");
                digestToPrint.append(file.getFile().getName());
            }
            FileUtils.fileWrite( outputFile, digestToPrint.toString() );

            for (ArtifactListener artifactListener : artifactListeners) {
                artifactListener.artifactCreated(outputFile, fileExtension);
            }
        }
        catch ( IOException e )
        {
            throw new ExecutionTargetWriteException( e.getMessage() );
        }
        catch ( NoSuchAlgorithmException e )
        {
            throw new ExecutionTargetWriteException( e.getMessage() );
        }
    }

    /**
     * {@inheritDoc}
     */
    public void close(String subPath)
    {
        // Nothing to do
    }
}


text:
package com.jpattern.service.log.slf4j;

import com.jpattern.core.IServiceBuilder;
import com.jpattern.service.log.ILoggerService;
import com.jpattern.service.log.NullLoggerServiceBuilder;

/**
 *
 * @author Francesco Cina'
 *
 * 4 Mar 2011
 */
public class Slf4jLog4jLoggerServiceBuilder extends ASlf4jLoggerServiceBuilder {

	public Slf4jLog4jLoggerServiceBuilder(String configFile) {
		this(new NullLoggerServiceBuilder(), configFile);
	}

	public Slf4jLog4jLoggerServiceBuilder(IServiceBuilder<ILoggerService> loggerServiceBuilder, String configFile) {
		super(loggerServiceBuilder, new Log4jLoggerBackendConfigurator(configFile));
	}

}


text:
package ru.makkarpov.scalingua

import ru.makkarpov.scalingua.plural.Suffix

import scala.language.experimental.macros
import scala.language.implicitConversions
import scala.reflect.internal.annotations.compileTimeOnly

trait I18n {
  type LString = LValue[String]

  val S = Suffix

  // Since I want to keep StringInterpolator AnyVal, I will extract it to a place where there is no path-dependency
  // and provide here only implicit conversion function.
  implicit def stringContext2Interpolator(sc: StringContext): I18n.StringInterpolator =
    new I18n.StringInterpolator(sc)

  implicit def long2MacroExtension(v: Long): I18n.PluralMacroExtensions =
    new I18n.PluralMacroExtensions(v)

  implicit def int2MacroExtension(i: Int): I18n.PluralMacroExtensions =
    new I18n.PluralMacroExtensions(i)

  implicit def string2SuffixExtension(s: String): Suffix.GenericSuffixExtension =
    new Suffix.GenericSuffixExtension(s)

  def t(msg: String, args: (String, Any)*)(implicit lang: Language, outputFormat: OutputFormat[String]): String =
    macro Macros.singular[String]

  def lt(msg: String, args: (String, Any)*)(implicit outputFormat: OutputFormat[String]): LString =
    macro Macros.lazySingular[String]

  def tc(ctx: String, msg: String, args: (String, Any)*)(implicit lang: Language, outputFormat: OutputFormat[String]): String =
    macro Macros.singularCtx[String]

  def ltc(ctx: String, msg: String, args: (String, Any)*)(implicit outputFormat: OutputFormat[String]): LString =
    macro Macros.lazySingularCtx[String]

  def p(msg: String, msgPlural: String, n: Long, args: (String, Any)*)
       (implicit lang: Language, outputFormat: OutputFormat[String]): String =
    macro Macros.plural[String]

  def lp(msg: String, msgPlural: String, n: Long, args: (String, Any)*)
        (implicit outputFormat: OutputFormat[String]): LString =
    macro Macros.lazyPlural[String]

  def pc(ctx: String, msg: String, msgPlural: String, n: Long, args: (String, Any)*)
       (implicit lang: Language, outputFormat: OutputFormat[String]): String =
    macro Macros.pluralCtx[String]

  def lpc(ctx: String, msg: String, msgPlural: String, n: Long, args: (String, Any)*)
        (implicit outputFormat: OutputFormat[String]): LString =
    macro Macros.lazyPluralCtx[String]

  // Tagged:

  def tag(tag: String, args: (String, Any)*)(implicit lang: Language, outputFormat: OutputFormat[String]): String =
    macro Macros.singularTag[String]

  def ltag(tag: String, args: (String, Any)*)(implicit outputFormat: OutputFormat[String]): LValue[String] =
    macro Macros.lazySingularTag[String]

  def ptag(tag: String, n: Long, args: (String, Any)*)(implicit lang: Language, outputFormat: OutputFormat[String]): String =
    macro Macros.pluralTag[String]

  def lptag(tag: String, n: Long, args: (String, Any)*)(implicit outputFormat: OutputFormat[String]): LValue[String] =
    macro Macros.lazyPluralTag[String]
}

object I18n extends I18n {
  class StringInterpolator(val sc: StringContext) extends AnyVal {
    def t(args: Any*)(implicit lang: Language, outputFormat: OutputFormat[String]): String =
      macro Macros.interpolate[String]

    def lt(args: Any*)(implicit outputFormat: OutputFormat[String]): LString =
      macro Macros.lazyInterpolate[String]

    def p(args: Any*)(implicit lang: Language, outputFormat: OutputFormat[String]): String =
      macro Macros.pluralInterpolate[String]

    def lp(args: Any*)(implicit outputFormat: OutputFormat[String]): LString =
      macro Macros.lazyPluralInterpolate[String]
  }

  class PluralMacroExtensions(val l: Long) extends AnyVal {
    def nVar: Long = throw new IllegalStateException(".nVars should not remain after macro expansion")
  }
}


text:
var gulp        = require('gulp');
var runSequence = require('run-sequence'); // (https://www.npmjs.com/package/run-sequence)
var config      = require('../config');

/* Linting */
gulp.task('lint', function(callback) {

  runSequence(
     'phplint',
	 'jslint',
	 'csslint',
	 'jsonlint',
	 callback);

});

/* Make the DIST files */
gulp.task('dist', function(callback) {

  runSequence(
     ['js_removedebug','php_removedebug'],
	 ['cssmin', 'jsmin'],
	 ['jsbanner','phpbanner'],
	 'chmod',
	 callback);

});