text:
//=============================================================================================================

#ifndef COSINEFILTER_H
#define COSINEFILTER_H

//*************************************************************************************************************
//=============================================================================================================
// INCLUDES
//=============================================================================================================

#include "../utils_global.h"

//*************************************************************************************************************
//=============================================================================================================
// Qt INCLUDES
//=============================================================================================================

//*************************************************************************************************************
//=============================================================================================================
// Eigen INCLUDES
//=============================================================================================================

#include <Eigen/Core>
#include <unsupported/Eigen/FFT>

//*************************************************************************************************************
//=============================================================================================================
// DEFINE NAMESPACE UTILSLIB
//=============================================================================================================

namespace UTILSLIB
{

//*************************************************************************************************************
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================

using namespace Eigen;

//*************************************************************************************************************
//=============================================================================================================
// DEFINES
//=============================================================================================================
#ifndef M_PI
#define	M_PI		3.14159265358979323846	/* pi */
#endif

#ifndef EIGEN_FFTW_DEFAULT
#define EIGEN_FFTW_DEFAULT
#endif

//=============================================================================================================
/**
* Creates a cosine filter response in the frequency domain.
*
* @brief Creates a cosine filter response in the frequency domain.
*/
class UTILSSHARED_EXPORT CosineFilter
{
public:
    enum TPassType {LPF, HPF, BPF, NOTCH };

    //=========================================================================================================
    /**
    * Constructs a CosineFilter object.
    *
    */
    CosineFilter();

    //=========================================================================================================
    /**
    * Constructs a CosineFilter object.
    *
    * @param fftLength length of the fft (multiple integer of 2^x)
    * @param lowpass low cutoff frequency in Hz (not normed to sampling freq)
    * @param lowpass_width determines the width of the filter slopes (steepness) in Hz (not normed to sampling freq)
    * @param highpass highpass high cutoff frequency in Hz (not normed to sampling freq)
    * @param highpass_width determines the width of the filter slopes (steepness) in Hz (not normed to sampling freq)
    * @param sFreq sampling frequency
    * @param type filter type (lowpass, highpass, etc.)
    */
    CosineFilter(int fftLength, float lowpass, float lowpass_width, float highpass, float highpass_width, double sFreq, TPassType type);

    RowVectorXcd    m_dFFTCoeffA;   /**< the FFT-transformed forward filter coefficient set, required for frequency-domain filtering, zero-padded to m_iFFTlength. */
    RowVectorXd     m_dCoeffA;      /**< the time filter coefficient set*/

    int             m_iFilterOrder;
};

} // NAMESPACE UTILSLIB

#endif // COSINEFILTER_H


text:
#ifndef MIRTK_MeshlessHarmonicVolumeMapper_H
#define MIRTK_MeshlessHarmonicVolumeMapper_H

#include "mirtk/MeshlessVolumeMapper.h"

#include "mirtk/Matrix.h"

namespace mirtk {

/**
 * Harmonic volumetric map using the method of fundamental solutions (MFS)
 *
 * This class finds a harmonic volumetric map which maps each point of the
 * input volume to a point in the target domain using the method of fundamental
 * solutions (MFS).
 *
 * - Li et al. (2009). Meshless harmonic volumetric mapping using fundamental solution methods.
 *   IEEE Transactions on Automation Science and Engineering, 6(3), 409–422.
 * - Li et al. (2010). Feature-aligned harmonic volumetric mapping using MFS.
 *   Computers and Graphics (Pergamon), 34(3), 242–251.
 */
class MeshlessHarmonicVolumeMapper : public MeshlessVolumeMapper
{
  mirtkObjectMacro(MeshlessHarmonicVolumeMapper);

  // ---------------------------------------------------------------------------
  // Attributes

  /// Precomputed kernel function values
  mirtkAttributeMacro(Matrix, Kernel);

  /// Whether to use SVD to solve linear system
  mirtkPublicAttributeMacro(bool, UseSVD);

  /// Copy attributes of this class from another instance
  void CopyAttributes(const MeshlessHarmonicVolumeMapper &);

  // ---------------------------------------------------------------------------
  // Construction/Destruction

public:

  /// Default constructor
  MeshlessHarmonicVolumeMapper();

  /// Copy constructor
  MeshlessHarmonicVolumeMapper(const MeshlessHarmonicVolumeMapper &);

  /// Assignment operator
  MeshlessHarmonicVolumeMapper &operator =(const MeshlessHarmonicVolumeMapper &);

  /// Destructor
  virtual ~MeshlessHarmonicVolumeMapper();

  // ---------------------------------------------------------------------------
  // Execution

protected:

  /// Initialize filter after input and parameters are set
  virtual void Initialize();

  /// Add source point after filter initialization
  ///
  /// \param[in] q Source point coordinates.
  ///
  /// \returns Whether source point was added or too close to existing point.
  virtual bool AddSourcePoint(double q[3]);

  /// Compute meshless map coefficients
  virtual void Solve();

  // ---------------------------------------------------------------------------
  // Linear system

  /// Get coefficients matrix corresponding to the least squares fitting term(s)
  /// of the quadratic energy function at constraints points
  ///
  /// \param[in]  k     Index of source points subset.
  /// \param[out] coeff Coefficients matrix.
  virtual void GetCoefficients(int k, Matrix &coeff) const;

  /// Get right-hand side of linear system
  ///
  /// \param[in]  k Index of source points subset.
  /// \param[out] b Right-hand side of linear system.
  virtual void GetConstraints(int k, Matrix &b) const;

  /// Add solution of linear system to weights of volumetric map
  ///
  /// \param[in] k Index of source points subset.
  /// \param[in] w Solution of linear system.
  virtual void AddWeights(int k, const Matrix &w);

};

} // namespace mirtk

#endif // MIRTK_MeshlessHarmonicVolumeMapper_H

redpajama_set_name: RedPajamaGithub


text:
package org.jetbrains.plugins.scala.lang.completion

import com.intellij.codeInsight.CodeInsightSettings
import com.intellij.codeInsight.completion._
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.featureStatistics.FeatureUsageTracker
import com.intellij.openapi.actionSystem.{ActionManager, IdeActions}
import com.intellij.openapi.keymap.KeymapUtil
import com.intellij.patterns.PlatformPatterns.psiElement
import com.intellij.psi._
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.search.searches.ClassInheritorsSearch
import com.intellij.psi.stubs.StubIndex
import com.intellij.util.ProcessingContext
import gnu.trove.THashSet
import org.jetbrains.plugins.scala.caches.ScalaShortNamesCacheManager
import org.jetbrains.plugins.scala.extensions._
import org.jetbrains.plugins.scala.lang.completion.lookups.{LookupElementManager, ScalaLookupItem}
import org.jetbrains.plugins.scala.lang.psi.ScalaPsiUtil
import org.jetbrains.plugins.scala.lang.psi.api.ScalaFile
import org.jetbrains.plugins.scala.lang.psi.api.expr.{ScInfixExpr, ScPostfixExpr, ScPrefixExpr, ScReferenceExpression}
import org.jetbrains.plugins.scala.lang.psi.api.statements.{ScFunction, ScValue, ScVariable}
import org.jetbrains.plugins.scala.lang.psi.api.toplevel.typedef.{ScClass, ScMember, ScObject, ScTypeDefinition}
import org.jetbrains.plugins.scala.lang.psi.implicits.ScImplicitlyConvertible
import org.jetbrains.plugins.scala.lang.psi.stubs.index.ScalaIndexKeys
import org.jetbrains.plugins.scala.lang.psi.types.ScType
import org.jetbrains.plugins.scala.lang.psi.types.api.TypeSystem
import org.jetbrains.plugins.scala.lang.resolve.processor.CompletionProcessor
import org.jetbrains.plugins.scala.lang.resolve.{ResolveUtils, ScalaResolveResult, StdKinds}

import scala.collection.mutable

/**
 * @author Alexander Podkhalyuzin
 */
class ScalaGlobalMembersCompletionContributor extends ScalaCompletionContributor {
  extend(CompletionType.BASIC, psiElement, new CompletionProvider[CompletionParameters]() {
    def addCompletions(parameters: CompletionParameters, context: ProcessingContext,
                       result: CompletionResultSet) {
      if (parameters.getInvocationCount < 2) return
      val position: PsiElement = positionFromParameters(parameters)
      if (!ScalaPsiUtil.fileContext(position).isInstanceOf[ScalaFile]) return
      val parent: PsiElement = position.getContext
      parent match {
        case ref: ScReferenceExpression =>
          val qualifier = ref.qualifier match {
            case Some(qual) => qual
            case None =>
              ref.getContext match {
                case inf: ScInfixExpr if inf.operation == ref => inf.getBaseExpr
                case posf: ScPostfixExpr if posf.operation == ref => posf.getBaseExpr
                case pref: ScPrefixExpr if pref.operation == ref => pref.getBaseExpr
                case _ =>
                  if (result.getPrefixMatcher.getPrefix == "") return
                  complete(ref, result, parameters.getOriginalFile, parameters.getInvocationCount)
                  return
              }
          }
          val typeWithoutImplicits = qualifier.getTypeWithoutImplicits()
          if (typeWithoutImplicits.isEmpty) return
          val tp = typeWithoutImplicits.get
          completeImplicits(ref, result, parameters.getOriginalFile, tp)
        case _ =>
      }
    }
  })

  private def isStatic(member: PsiNamedElement): Boolean = {
    ScalaPsiUtil.nameContext(member) match {
      case memb: PsiMember =>
       isStatic(member, memb.containingClass)
    }
  }

  private def isStatic(member: PsiNamedElement, containingClass: PsiClass): Boolean = {
    ScalaPsiUtil.nameContext(member) match {
      case memb: PsiMember =>
        if (containingClass == null) return false
        val qualifiedName = containingClass.qualifiedName + "." + member.name
        for (excluded <- CodeInsightSettings.getInstance.EXCLUDED_PACKAGES) {
          if (qualifiedName == excluded || qualifiedName.startsWith(excluded + ".")) {
            return false
          }
        }
        containingClass match {
          case o: ScObject if o.isStatic =>
            // filter out type class instances, such as scala.math.Numeric.String, to avoid too many results.
            !o.hasModifierProperty("implicit")
          case _: ScTypeDefinition => false
          case _ => memb.hasModifierProperty("static")
        }
    }
  }

  private def completeImplicits(ref: ScReferenceExpression, result: CompletionResultSet, originalFile: PsiFile,
                                originalType: ScType)
                               (implicit typeSystem: TypeSystem = originalFile.typeSystem) {
    FeatureUsageTracker.getInstance.triggerFeatureUsed(JavaCompletionFeatures.GLOBAL_MEMBER_NAME)
    val scope: GlobalSearchScope = ref.getResolveScope
    val file = ref.getContainingFile

    val elemsSet = new mutable.HashSet[PsiNamedElement]
    def addElemToSet(elem: PsiNamedElement) {
      elemsSet += elem
    }

    def elemsSetContains(elem: PsiNamedElement): Boolean = {
      if (elem.getContainingFile == originalFile) {
        //complex logic to detect static methods in same file, which we shouldn't import
        val name = elem.name
        val containingClass = ScalaPsiUtil.nameContext(elem) match {
          case member: PsiMember => member.containingClass
          case _ => null
        }
        if (containingClass == null) return false
        val qualName = containingClass.qualifiedName
        if (qualName == null) return false
        for {
          element <- elemsSet
          if element.name == name
          if element.getContainingFile == file
          cClass = ScalaPsiUtil.nameContext(element) match {
            case member: PsiMember => member.containingClass
            case _ => null
          }
          if cClass != null
          if cClass.qualifiedName != null
          if cClass.qualifiedName == qualName
        } {
          return true
        }
        false
      } else elemsSet.contains(elem)
    }

    val collection = StubIndex.getElements(ScalaIndexKeys.IMPLICITS_KEY, "implicit", file.getProject, scope, classOf[ScMember])

    import scala.collection.JavaConversions._

    val convertible = new ScImplicitlyConvertible(ref)
    val proc = new convertible.CollectImplicitsProcessor(true)
    for (element <- collection) {
      element match {
        case v: ScValue =>
          for (d <- v.declaredElements if isStatic(d)) {
            proc.execute(d, ResolveState.initial())
          }
        case f: ScFunction if isStatic(f) =>
          proc.execute(element, ResolveState.initial())
        case c: ScClass if isStatic(c) =>
          c.getSyntheticImplicitMethod match {
            case Some(f: ScFunction) =>
              proc.execute(f, ResolveState.initial())
            case _ =>
          }
        case _ =>
      }
    }
    val candidates = proc.candidates.map(convertible.forMap(_, originalType))

    ref.getVariants(implicits = false, filterNotNamedVariants = false).foreach {
      case ScalaLookupItem(elem: PsiNamedElement) => addElemToSet(elem)
      case elem: PsiNamedElement => addElemToSet(elem)
    }

    val iterator = candidates.iterator
    while (iterator.hasNext) {
      val next = iterator.next()
      if (next.condition) {
        val retTp = next.rt
        val c = new CompletionProcessor(StdKinds.methodRef, ref)
        c.processType(retTp, ref)
        for (elem <- c.candidates) {
          val shouldImport = !elemsSetContains(elem.getElement)
          //todo: overloads?
          val lookup: ScalaLookupItem = LookupElementManager.getLookupElement(elem, isClassName = true,
            isOverloadedForClassName = false, shouldImport = shouldImport, isInStableCodeReference = false).head
          lookup.usedImportStaticQuickfix = true
          lookup.elementToImport = next.resolveResult.getElement
          result.addElement(lookup)
        }
      }
    }
  }

  private def complete(ref: ScReferenceExpression, result: CompletionResultSet, originalFile: PsiFile, invocationCount: Int) {
    FeatureUsageTracker.getInstance.triggerFeatureUsed(JavaCompletionFeatures.GLOBAL_MEMBER_NAME)
    val matcher: PrefixMatcher = result.getPrefixMatcher
    val scope: GlobalSearchScope = ref.getResolveScope
    val file = ref.getContainingFile

    var hintShown: Boolean = false
    def showHint(shouldImport: Boolean) {
      if (!hintShown && !shouldImport && CompletionService.getCompletionService.getAdvertisementText == null) {
        val actionId = IdeActions.ACTION_SHOW_INTENTION_ACTIONS
        val shortcut: String =
          KeymapUtil.getFirstKeyboardShortcutText(ActionManager.getInstance.getAction(actionId))
        if (shortcut != null) {
          result.addLookupAdvertisement(s"To import a method statically, press $shortcut")
        }
        hintShown = true
      }
    }

    val elemsSet = new mutable.HashSet[PsiNamedElement]
    def addElemToSet(elem: PsiNamedElement) {
      elemsSet += elem
    }

    def elemsSetContains(elem: PsiNamedElement): Boolean = {
      if (elem.getContainingFile == originalFile) {
        //complex logic to detect static methods in same file, which we shouldn't import
        val name = elem.name
        val containingClass = ScalaPsiUtil.nameContext(elem) match {
          case member: PsiMember => member.containingClass
          case _ => null
        }
        if (containingClass == null) return false
        val qualName = containingClass.qualifiedName
        if (qualName == null) return false
        for {
          element <- elemsSet
          if element.name == name
          if element.getContainingFile == file
          cClass = ScalaPsiUtil.nameContext(element) match {
            case member: PsiMember => member.containingClass
            case _ => null
          }
          if cClass != null
          if cClass.qualifiedName != null
          if cClass.qualifiedName == qualName
        } {
          return true
        }
        false
      } else elemsSet.contains(elem)
    }

    ref.getVariants(implicits = false, filterNotNamedVariants = false).foreach {
      case ScalaLookupItem(elem) => addElemToSet(elem)
      case elem: PsiNamedElement => addElemToSet(elem)
    }

    val namesCache = ScalaShortNamesCacheManager.getInstance(ref.getProject)

    val methodNamesIterator = namesCache.getAllMethodNames.iterator ++ namesCache.getAllJavaMethodNames.iterator

    def isAccessible(member: PsiMember, containingClass: PsiClass): Boolean = {
      invocationCount >= 3 || (ResolveUtils.isAccessible(member, ref, forCompletion = true) && ResolveUtils.isAccessible(containingClass, ref, forCompletion = true))
    }

    while (methodNamesIterator.hasNext) {
      val methodName = methodNamesIterator.next()
      if (matcher.prefixMatches(methodName)) {
        val classes = new THashSet[PsiClass]
        val methodsIterator = namesCache.getMethodsByName(methodName, scope).iterator
        while (methodsIterator.hasNext) {
          val method = methodsIterator.next()
          val cClass = method.containingClass
          if (cClass != null) {
            val inheritors: Array[PsiClass] = {
              if (method.isInstanceOf[ScFunction])
                ClassInheritorsSearch.search(cClass, scope, true).toArray(PsiClass.EMPTY_ARRAY)
              else Array.empty
            }
            val currentAndInheritors = Iterator(cClass) ++ inheritors.iterator
            for {
              containingClass <- currentAndInheritors
              if isStatic(method, containingClass)
            } {
              assert(containingClass != null)
              if (classes.add(containingClass) && isAccessible(method, containingClass)) {
                val shouldImport = !elemsSetContains(method)
                showHint(shouldImport)

                val overloads = containingClass match {
                  case o: ScObject => o.functionsByName(methodName)
                  case _ => containingClass.getAllMethods.toSeq.filter(m => m.name == methodName)
                }
                if (overloads.size == 1) {
                  result.addElement(createLookupElement(method, containingClass, shouldImport))
                }
                else if (overloads.size > 1) {
                  val lookup = createLookupElement(if (overloads.head.getParameterList.getParametersCount == 0)
                    overloads(1)
                  else overloads.head, containingClass, shouldImport, overloaded = true)
                  result.addElement(lookup)
                }
              }
            }
          }
        }
      }
    }

    val fieldNamesIterator = namesCache.getAllFieldNames.iterator

    while (fieldNamesIterator.hasNext) {
      val fieldName = fieldNamesIterator.next()
      if (matcher.prefixMatches(fieldName)) {
        val fieldsIterator = namesCache.getFieldsByName(fieldName, scope).iterator
        while (fieldsIterator.hasNext) {
          val field = fieldsIterator.next()
          if (isStatic(field)) {
            val containingClass: PsiClass = field.containingClass
            assert(containingClass != null)
            if (isAccessible(field, containingClass)) {
              val shouldImport = !elemsSetContains(field)
              showHint(shouldImport)

              result.addElement(createLookupElement(field, containingClass, shouldImport))
            }
          }
        }
      }
    }

    val scalaFieldsIterator = ScalaShortNamesCacheManager.getInstance(ref.getProject).getAllScalaFieldNames.iterator

    while (scalaFieldsIterator.hasNext) {
      val fieldName = scalaFieldsIterator.next()
      if (matcher.prefixMatches(fieldName)) {
        val fieldsIterator = ScalaShortNamesCacheManager.getInstance(ref.getProject).
          getScalaFieldsByName(fieldName, scope).iterator
        while (fieldsIterator.hasNext) {
          val field = fieldsIterator.next()
          val namedElement = field match {
            case v: ScValue => v.declaredElements.find(_.name == fieldName).orNull
            case v: ScVariable => v.declaredElements.find(_.name == fieldName).orNull
          }
          if (field.containingClass != null) {
            val inheritors = ClassInheritorsSearch.search(field.containingClass, scope, true).toArray(PsiClass.EMPTY_ARRAY)
            val currentAndInheritors = Iterator(field.containingClass) ++ inheritors.iterator
            for {
              containingClass <- currentAndInheritors
              if namedElement != null && isStatic(namedElement, containingClass)
            } {
              assert(containingClass != null)
              if (isAccessible(field, containingClass)) {
                val shouldImport = !elemsSetContains(namedElement)
                showHint(shouldImport)

                result.addElement(createLookupElement(namedElement, containingClass, shouldImport))
              }
            }
          }
        }
      }
    }
  }

  private def createLookupElement(member: PsiNamedElement, clazz: PsiClass, shouldImport: Boolean,
                                  overloaded: Boolean = false): LookupElement = {
    LookupElementManager.getLookupElement(new ScalaResolveResult(member), isClassName = true,
      isOverloadedForClassName = overloaded, shouldImport = shouldImport,
      isInStableCodeReference = false, containingClass = Some(clazz)).head
  }
}


text:
VERSION = "1.3.2"

SDK_MONIKER = "communication-identity/{}".format(VERSION)  # type: str


text:
'use strict';

var vows = require('vows');
var assert = require('assert');
var spec = require('vows/lib/vows/reporters/spec');
var d = require('./data');
var utils = require('./utils');

var cjson = null;
try {
    // See if we have cjson
    cjson = require('cjson');
} catch(e) {
    cjson = null;
}

try {
    process.chdir(__dirname);
}
catch (err) {
    console.log('Changing directory failed, test must be run with current working directory being ..easy-config/test');
    console.log('exiting');
    process.exit();
}

var tmpArgs = [];

// Clear variables for tests
function clearEnv() {
    Object.keys(process.env).forEach(function (key) {
        if(key.indexOf('NODE_') === 0) {
            delete process.env[key];
        }
    });
}
clearEnv();

vows.describe('Easy-config').addBatch({
    'Simple include':{
        topic:function(){
            this.callback(null, require('../lib/config'));
        },
        'is correct':function(config){
            assert.strictEqual(true, utils.deepDiff(config, d.simple));
        },
        'Extend':function(config){
            config = config.extend({correct:false});
            assert.strictEqual(true, utils.deepDiff(config, d.simpleE));
        }
    }
}).addBatch({
    'With env false':{
        topic:function(){
            this.callback(null, require('../lib/config').loadConfig({env:false}));
        },
        'is correct':function(config){
            assert.strictEqual(true, utils.deepDiff(config, d.noEnv));
        }
    }
}).addBatch({
    'With other folder':{
        topic:function(){
            this.callback(null, require('../lib/config').loadConfig({folder:'other'}));
        },
        'is correct':function(config){
            assert.strictEqual(true, utils.deepDiff(config, d.other));
        }
    }
}).addBatch({
    'With comments folder':{
        topic: function(){
            if(cjson) {
                this.callback(null, require('../lib/config').loadConfig({folder:'comment'}));
            } else {
                // No cjson so skip
                this.callback(null, null);
            }
        },
        'is correct':function(config){
            if(cjson) {
                assert.strictEqual(true, utils.deepDiff(config, d.other));
            }
        }
    }
}).addBatch({
    'With no NS':{
        topic:function(){
            this.callback(null, require('../lib/config').loadConfig({ns:false}));
        },
        'is correct':function(config){
            assert.strictEqual(true, utils.deepDiff(config, d.noNS));
        }
    }
}).addBatch({
    'JS files':{
        topic:function(){
            this.callback(null, require('../lib/config').loadConfig({folder:'other2', type: 'js'}));
        },
        'is correct':function(config){
            assert.strictEqual(true, utils.deepDiff(config, d.other));
        }
    }
}).addBatch({
    'Modifiers':{
        topic:function(){
            this.callback(null, require('../lib/config').modify({'test':true}));
        },
        'is correct':function(config){
            assert.strictEqual(true, utils.deepDiff(config, d.mod));
        },
        'is buffered':function(){
            assert.strictEqual(true, utils.deepDiff(require('../lib/config'), d.mod));
        },
        'modifications propagate to loadConfig':function(){
            assert.strictEqual(true, utils.deepDiff(require('../lib/config').loadConfig(), d.mod));
        },
        'can undo':function(){
            assert.strictEqual(true, utils.deepDiff(require('../lib/config').unmodify(), d.simple));
        }
    }
}).addBatch({
    'writeConfigFile':{
        topic:function(){
            this.callback(null, require('../lib/config').writeConfigFile('config.here.json', {'test':true}));
        },
        'returns correct':function(config){
            assert.strictEqual(true, utils.deepDiff(config, d.writeF1));
        },
        'is buffered':function(){
            assert.strictEqual(true, utils.deepDiff(require('../lib/config'), d.writeF1));
        },
        'modifications propagate to loadConfig':function(){
            assert.strictEqual(true, utils.deepDiff(require('../lib/config').loadConfig(), d.writeF1));
        },
        'overwrite returns correct':function(){
            assert.strictEqual(true, utils.deepDiff(require('../lib/config').writeConfigFile('config.here.json', {'test':false}), d.writeF2));
        },
        'is also buffered':function(){
            assert.strictEqual(true, utils.deepDiff(require('../lib/config'), d.writeF2));
        }
    }
}).addBatch({
    'changeConfigFile':{
        topic:function(){
            this.callback(null, require('../lib/config').changeConfigFile('config.here.json', {'test2':true}));
        },
        'returns correct':function(config){
            assert.strictEqual(true, utils.deepDiff(config, d.writeF3));
        },
        'is buffered':function(){
            assert.strictEqual(true, utils.deepDiff(require('../lib/config'), d.writeF3));
        },
        'modifications propagate to loadConfig':function(){
            assert.strictEqual(true, utils.deepDiff(require('../lib/config').loadConfig(), d.writeF3));
        }
    }
}).addBatch({
    'deleteConfigFile':{
        topic:function(){
            this.callback(null, require('../lib/config').deleteConfigFile('config.here.json'));
        },
        'returns correct':function(config){
            assert.strictEqual(true, utils.deepDiff(config, d.simple));
        },
        'is buffered':function(){
            assert.strictEqual(true, utils.deepDiff(require('../lib/config'), d.simple));
        },
        'modifications propagate to loadConfig':function(){
            assert.strictEqual(true, utils.deepDiff(require('../lib/config').loadConfig(), d.simple));
        }
    }
}).addBatch({
    'writeConfigFile with just name':{
        topic:function(){
            this.callback(null, require('../lib/config').writeConfigFile('here', {'test':true}));
        },
        'returns correct':function(config){
            assert.strictEqual(true, utils.deepDiff(config, d.writeF1));
        }
    }
}).addBatch({
    'changeConfigFile with just name':{
        topic:function(){
            this.callback(null, require('../lib/config').changeConfigFile('here', {'test2':true}));
        },
        'returns correct':function(config){
            assert.strictEqual(true, utils.deepDiff(config, d.writeF4));
        }
    }
}).addBatch({
    'deleteConfigFile with just name':{
        topic:function(){
            this.callback(null, require('../lib/config').deleteConfigFile('here'));
        },
        'returns correct':function(config){
            assert.strictEqual(true, utils.deepDiff(config, d.simple));
        },
        'is buffered':function(){
            assert.strictEqual(true, utils.deepDiff(require('../lib/config'), d.simple));
        },
        'modifications propagate to loadConfig':function(){
            assert.strictEqual(true, utils.deepDiff(require('../lib/config').loadConfig(), d.simple));
        }
    }
}).addBatch({
    'getDefinedOptions':{
        topic:function(){
            this.callback(null, require('../lib/config').getDefinedOptions());
        },
        'returns correct':function(options){
            assert.strictEqual(true, utils.deepDiff(options, d.options));
        }
    }
}).addBatch({
    'getDefinedOptions custom':{
        topic:function(){
            this.callback(null, require('../lib/config').loadConfig({ns:false,env:'pro'}).getDefinedOptions());
        },
        'returns correct':function(options){
            assert.strictEqual(true, utils.deepDiff(options, d.options2));
        }
    }
}).addBatch({
    'isProduction true':{
        topic:function(){
            this.callback(null, require('../lib/config').loadConfig({ns:false, env:'pro'}).isProduction());
        },
        'returns correct':function(production){
            assert.strictEqual(true, production);
        }
    }
}).addBatch({
    'isProduction false':{
        topic:function(){
            this.callback(null, require('../lib/config').loadConfig({ns:false, env:'dev'}).isProduction());
        },
        'returns correct':function(production){
            assert.strictEqual(false, production);
        }
    }
}).addBatch({
    'load environment variables':{
        topic:function(){
            clearEnv();
            process.env.NODE_TEST_VAR = 'true';
            this.callback(null, require('../lib/config').loadConfig({ns:false, env:'dev'}));
        },
        'returns correct':function(config){
            assert.strictEqual(true, utils.deepDiff(config, d.noNSWEnv));
            clearEnv();
        }
    }
}).addBatch({
    'load case insensitive environment variables':{
        topic:function(){
            clearEnv();
            process.env.NODE_CLIENTID = 'super';
            this.callback(null, require('../lib/config').loadConfig({ns:false, env:'dev'}));
        },
        'returns correct':function(config){
            assert.strictEqual(true, utils.deepDiff(config, d.noNSWCIEnv));
            clearEnv();
        }
    }
}).addBatch({
    'load JSON environment variables':{
        topic:function(){
            clearEnv();
            process.env.NODE_LANG = JSON.stringify(['en', 'es', 'de']);
            this.callback(null, require('../lib/config').loadConfig({ns:false, env:'dev'}));
        },
        'returns correct':function(config){
            assert.strictEqual(true, utils.deepDiff(config, d.noNSWCIEnvJSON));
            clearEnv();
        }
    }
}).addBatch({
    'ignore environment variables':{
        topic:function(){
            clearEnv();
            process.env.NODE_CLIENTID = 'super';
            this.callback(null, require('../lib/config').loadConfig({ns:false, env:'dev', envVars: false}));
        },
        'returns correct':function(config){
            assert.strictEqual(true, utils.deepDiff(config, d.noNS));
            clearEnv();
        }
    }
}).addBatch({
    'load environment variables with different prefix':{
        topic:function(){
            clearEnv();
            process.env.PREFIX_CLIENTID = 'super';
            this.callback(null, require('../lib/config').loadConfig({ns:false, env:'dev', envPrefix: 'PREFIX_'}));
        },
        'returns correct':function(config){
            assert.strictEqual(true, utils.deepDiff(config, d.noNSWCIEnv));
            clearEnv();
        }
    }
}).addBatch({
    'load simple cmdline variable':{
        topic:function(){
            tmpArgs = process.argv.slice(0);
            process.argv = process.argv.slice(0);
            process.argv.push('--test=here');
            this.callback(null, require('../lib/config').loadConfig({}));
        },
        'returns correct':function(config){
            assert.strictEqual(true, utils.deepDiff(config, d.simpleCmd));
            process.argv = tmpArgs.slice(0);
        }
    }
}).addBatch({
    'load simple nested cmdline variable':{
        topic:function(){
            tmpArgs = process.argv.slice(0);
            process.argv = process.argv.slice(0);
            process.argv.push('--test.is=here');
            this.callback(null, require('../lib/config').loadConfig({}));
        },
        'returns correct':function(config){
            assert.strictEqual(true, utils.deepDiff(config, d.simpleCmdNested));
            process.argv = tmpArgs.slice(0);
        }
    }
}).addBatch({
    'load simple cmdline value ommited (boolean) variable':{
        topic:function(){
            tmpArgs = process.argv.slice(0);
            process.argv = process.argv.slice(0);
            process.argv.push('--test');
            this.callback(null, require('../lib/config').loadConfig({}));
        },
        'returns correct':function(config){
            assert.strictEqual(true, utils.deepDiff(config, d.simpleCmdBoolean));
            process.argv = tmpArgs.slice(0);
        }
    }
}).addBatch({
    'favor cmdline to environment variables':{
        topic:function(){
            tmpArgs = process.argv.slice(0);
            process.argv = process.argv.slice(0);
            process.argv.push('--test.is=here');
            clearEnv();
            process.env.NODE_TEST_IS = 'super';
            this.callback(null, require('../lib/config').loadConfig({}));
        },
        'returns correct':function(config){
            assert.strictEqual(true, utils.deepDiff(config, d.simpleCmdNested));
            process.argv = tmpArgs.slice(0);
        }
    }
}).addBatch({
    'isEnvironment to return true on correct':{
        topic:function(){
            this.callback(null, require('../lib/config').loadConfig({ns:false, env:'pro'}).isEnvironment('pro'));
        },
        'returns correct':function(isEnv){
            assert.strictEqual(true, isEnv);
        }
    }
}).addBatch({
    'isEnvironment to return false on wrong':{
        topic:function(){
            this.callback(null, require('../lib/config').loadConfig({ns:false, env:'pro'}).isEnvironment('dev'));
        },
        'returns correct':function(isEnv){
            assert.strictEqual(false, isEnv);
        }
    }
}).addBatch({
    'isEnvironment to return true on array input with right element':{
        topic:function(){
            this.callback(null, require('../lib/config').loadConfig({ns:false, env:'pro'}).isEnvironment(['pro', 'production']));
        },
        'returns correct':function(isEnv){
            assert.strictEqual(true, isEnv);
        }
    }
}).addBatch({
    'isEnvironment to return false on array input with no right element':{
        topic:function(){
            this.callback(null, require('../lib/config').loadConfig({ns:false, env:'pro'}).isEnvironment(['dev', 'development']));
        },
        'returns correct':function(isEnv){
            assert.strictEqual(false, isEnv);
        }
    }
}).run({reporter:spec});


text:
The format is based on [Keep a Changelog](http://keepachangelog.com/) and adheres to [Semantic Versioning](http://semver.org/).

## 0.10.0 (UNRELEASED)

### DynamicSpout Framework
#### Breaking Changes
- [PR-37](https://github.com/salesforce/storm-dynamic-spout/pull/37) Moved `FilterChain` back to the `dynamic` package.
- [PR-52](https://github.com/salesforce/storm-dynamic-spout/pull/52) Remove Kafka-Test-Server.  Replace with Kafka-JUnit external dependency.
- [PR-66](https://github.com/salesforce/storm-dynamic-spout/pull/66) DynamicSpout.open() now throws IllegalStateException if you attempt to open it more than once.

### Improvements
- [PR-38](https://github.com/salesforce/storm-dynamic-spout/pull/38) Removed unused method `Deserializer.getOutputFields()`.
- [PR-37](https://github.com/salesforce/storm-dynamic-spout/pull/37) Added hasStep() and getStep() to `FilterChain` and added a specific exception for serializing/deserializing `FilterChainStep` objects.
- [PR-40](https://github.com/salesforce/storm-dynamic-spout/pull/40) Timer metrics will now publish a counter metric containing the total time spent within each metric key.  Start publishing developer performance metrics within VirtualSpout via MetricRecorder.
- [PR-45](https://github.com/salesforce/storm-dynamic-spout/pull/45) MetricRecorder is now passed into Consumer interface via open() method.
- [PR-55](https://github.com/salesforce/storm-dynamic-spout/pull/55) Refactored how DynamicSpout coordinates with VirtualSpouts internally.
- [PR-85](https://github.com/salesforce/storm-dynamic-spout/pull/85) Fix ordering bug in DefaultRetryManager. Always retry the earliest messageId.
- [PR-90](https://github.com/salesforce/storm-dynamic-spout/pull/90) Adds new 'Permanently Failed' output stream.  Tuples that exceed the configured retry limit will now be emitted out a 'failed' stream un-anchored. This allows you to do your own error handling within the topology by subscribing to this stream. The name of this output stream defaults to 'failed', but is configurable via the `spout.permanently_failed_output_stream_id` configuration item.
- [PR-101](https://github.com/salesforce/storm-dynamic-spout/pull/101) Fix NPE in RatioMessageBuffer on Spout deploy.
- [PR-104](https://github.com/salesforce/storm-dynamic-spout/pull/104) Allow curator exceptions to bubble up
- [PR-110](https://github.com/salesforce/storm-dynamic-spout/pull/110) Fix exponential retry delay growth in DefaultRetryManager.
- [PR-111](https://github.com/salesforce/storm-dynamic-spout/pull/111) Update dependencies and cleanup

#### Removed
- [PR-45](https://github.com/salesforce/storm-dynamic-spout/pull/45) Removed getMaxLag() from Consumer interface.
- [PR-81](https://github.com/salesforce/storm-dynamic-spout/pull/81) Removed getPersistenceAdapter() from Consumer interface.

### Sideline Framework
In this release the 'stop' sideline state was split into 'resume' and 'resolve', allowing for one to begin processing a sideline without designating an ending offset and then applying an ending offset later on. Based upon our experience this is a more practical division of state for sidelining.

#### Breaking Changes
- [PR-79](https://github.com/salesforce/storm-dynamic-spout/pull/79) Add support for resume state when sidelining.
- [PR-37](https://github.com/salesforce/storm-dynamic-spout/pull/37) Replaced `SpoutTriggerProxy` with `SidelineController` interface.

#### Removed
- [PR-37](https://github.com/salesforce/storm-dynamic-spout/pull/37) Removed deprecated code.
    - Remove deprecated constructor from SidelineRequest
    - Removed deprecated constructors from SidelineRequestIdentifier

#### Improvements
- [PR-37](https://github.com/salesforce/storm-dynamic-spout/pull/37) Added isSidelineStarted() and isSidelineStopped() to the `SidelineController`
- [PR-37](https://github.com/salesforce/storm-dynamic-spout/pull/37) When deserializing an invalid FilterChainStep it would crash the spout instance.
- [PR-37](https://github.com/salesforce/storm-dynamic-spout/pull/37) Replaced `SidelineRequestIdentifier` with `FilterChainStepIdentifier` in the FilterChain.
- [PR-37](https://github.com/salesforce/storm-dynamic-spout/pull/37) Added `is*()` methods to the `SidelineController` for the respective sideline states.
- [PR-47](https://github.com/salesforce/storm-dynamic-spout/pull/47) Sidelining periodically checks to ensure `VirtualSpout` instances are running and have the proper `FilterChainStep` objects applied to them.
- [PR-97](https://github.com/salesforce/storm-dynamic-spout/pull/97) Sideline config defaults are now set properly.
- [PR-99](https://github.com/salesforce/storm-dynamic-spout/pull/99) Do not pass empty ending state when loading sidelines.

### Kafka Consumer
#### Removed
- [PR-38](https://github.com/salesforce/storm-dynamic-spout/pull/38) Removed unused method Deserializer.getOutputFields()

#### Improvements
- [PR-45](https://github.com/salesforce/storm-dynamic-spout/pull/45) Added lag, currentOffset, endOffset metrics to Kafka Consumer.
- [PR-43](https://github.com/salesforce/storm-dynamic-spout/pull/43) Fixed unbounded recursion when calling fillBuffer() in the KafkaConsumer.
- [PR-98](https://github.com/salesforce/storm-dynamic-spout/pull/98) Allow null keys from Kafka in the Utf8Deserializer and handle null values properly.

## 0.9.2 (2017-12-13)

### Improvement
- [PR=87](https://github.com/salesforce/storm-dynamic-spout/pull/87) More fair partition distribution

### Bug Fixes
- [ISSUE-92](https://github.com/salesforce/storm-dynamic-spout/issues/92) Fix race condition while cleaning up consumer state.
- [PR-86](https://github.com/salesforce/storm-dynamic-spout/pull/86) Sideline payload null checking
- [PR-88](https://github.com/salesforce/storm-dynamic-spout/pull/88) Sideline payload null checking

## 0.9.1 (2017-12-05)
### Bug Fixes
- [PR-85](https://github.com/salesforce/storm-dynamic-spout/pull/85) Fix ordering bug in DefaultRetryManager. Always retry the earliest messageId.

## 0.9.0 (2017-10-26)
### Improvements
- [PR-14](https://github.com/salesforce/storm-dynamic-spout/pull/14) Update Kafka dependencies to 0.11.0.1
- [PR-15](https://github.com/salesforce/storm-dynamic-spout/pull/15) Update Storm dependencies to 1.1.1
- [PR-24](https://github.com/salesforce/storm-dynamic-spout/pull/24) Add ability for errors to be reported up to the Storm web UI.
- [PR-34](https://github.com/salesforce/storm-dynamic-spout/pull/34) Add removeVirtualSpout() method to DynamicSpout
- [PR-35](https://github.com/salesforce/storm-dynamic-spout/pull/35/files) Output fields should now be declared as a List of String objects. In 0.10 we will drop the comma delimited strings, in the interim we are also now trimming whitespace off of the comma delimited version.

### Bug Fixes
##### Kafka Consumer
- [PR-16](https://github.com/salesforce/storm-dynamic-spout/pull/16) Improved handling of Out Of Range exceptions
##### Sideline Spout
- [PR-13](https://github.com/salesforce/storm-dynamic-spout/pull/13) Fixed race condition on-redeploy of Spout when a
sideline is active for firehose.

### Removed
##### Kafka Consumer
- [PR-31](https://github.com/salesforce/storm-dynamic-spout/pull/31) Removed configuration items: `spout.kafka.autocommit` and `spout.kafka.autocommit_interval_ms`.  This functionality is covered by configuration item `spout.cordinator.consumer_state_flush_interval_ms`

## 0.8.x
- Split the dynamic spout framework into `com.salesforce.storm.spout.dynamic`.
  - Anyone implementing a `DynamicSpout` will need to update package names.
- Checkstyle is enforced everywhere now.

## 0.7.x
- Simplified triggers, new singular and cleaner interface for implementing.

## 0.6.x
- MetricsRecorder is now a required dependency for VirtualSpout instances.

## 0.5.x
- Restructured config.

## 0.4.x
The goal of this release was to split off the sideline specific code from the dynamic spout framework such that it can be reused in other projects.
- DynamicSpout is no longer an abstract class, now it can be attached directly to Storm as is.
- SidelineSpout does nothing other than change configuration, specifically setting the handler classes.
- SpoutHandler is a new way to define methods to tie into the DynamicSpout lifecycle.
- VirtualSpoutHandler is a new way to define methods to tie into the VirtualSpout lifecycle.
- New sidelining tests that are leaner and faster.
- Renamed SidelineSpoutConfig to SpoutConfig and changed the sideline_spout.* keys to spout.*, the sideline specific ones have been renamed to just sideline.*
- SpoutConfig uses a new annotation for config, and there's a new script to auto-generate the markdown table for it.

## 0.3.x
- Renamed and reorganized classes to separate kafka specific implementation details

## 0.2.x
- `SidelineRequest`'s now include the `SidelineIdentifier` which can now be explicitly supplied.  The original constructor that generated a UUID is now deprecated.

## 0.1.x
- Initial release!


text:
function editCurrentMarkdownDocument () {
	var objApp = WizExplorerApp;
	var objWindow = objApp.Window;
	var objDocument = objWindow.CurrentDocument;

	if (objDocument == null) {
		return;
	}

	var objCommon = objApp.CreateWizObject("WizKMControls.WizCommonUI");
	var tempPath = objCommon.GetSpecialFolder("TemporaryFolder");
	tempPath += "editor_md_temp/";
	objCommon.CreateDirectory(tempPath);
	tempPath += objDocument.GUID + "/";
	objCommon.CreateDirectory(tempPath);
	objCommon.CreateDirectory(tempPath + "index_files/");

	var tempFile = tempPath + "index.html";
	objDocument.SaveToHtml(tempFile, 0);

	var pluginPath = objApp.GetPluginPathByScriptFileName("md_editor.js");
	objCommon.CopyFile(pluginPath + "index.html", tempFile);

	var tempText = objCommon.LoadTextFromFile(tempFile);
	tempText = tempText.replace(/(<script src=")/g, "$1" + encodeURI(pluginPath))
					   .replace(/(<link rel="stylesheet" href=")/g, "$1" + encodeURI(pluginPath));
	objCommon.SaveTextToFile(tempFile, tempText, "utf-8-bom");

	var editorFileName = tempFile + "?guid=" + objDocument.GUID + "&kbguid=" + objDocument.Database.KbGUID;
	objWindow.ViewHtml(editorFileName, true);
}

editCurrentMarkdownDocument();


text:
package com.zhuinden.simplestack;

import android.os.Parcelable;

/**
 * An interface to allow using any key in the backstack, as long as it is possible to persist and restore it as a Parcelable.
 */
public interface KeyParceler {
    /**
     * Transforms the input parameter into a Parcelable.
     *
     * @param object The key that is to be transformed into a Parcelable.
     * @return the Parcelable the key is transformed into.
     */
    Parcelable toParcelable(Object object);

    /**
     * Creates the original key based on the input Parcelable.
     *
     * @param parcelable the Parcelable the key was transformed into.
     * @return The key that was transformed into a Parcelable.
     */
    Object fromParcelable(Parcelable parcelable);
}


text:
Spectrum-analysis-program: Integrate the supplied spectrum

Keys:

     infile       nokeyok             input spectrum file [-]
     xc                               x-column [1]
     yc                               y-column [2]
     xmin                             } range over which to integrate
     xmax                             } [full range of x]

A simple integration of the data within the specified range is performed.
The y data are integrated with respect to x using a trapezoidal rule and
the result of the integration is printed on the standard output.

Example:

Integrate column-3 with respect to column 1 in the range 0,100

  sp_integrate my_data.dat xmin 0.0 xmax 100.0 xc 1 yc 3


text:
from formalchemy.tests import *
from formalchemy.fatypes import *
from formalchemy import tests
try:
    from webtest import SeleniumApp, selenium
except ImportError:
    from unittest.case import SkipTest
    raise SkipTest("Selenium is not available")

def test_render():
    """
    >>> html5_test_fieldset = FieldSet(Three)
    >>> print(html5_test_fieldset.foo.url().render())
    <input id="Three--foo" name="Three--foo" type="url" />

    >>> print(html5_test_fieldset.foo.email().render())
    <input id="Three--foo" name="Three--foo" type="email" />

    >>> print(html5_test_fieldset.foo.range(min_=2, max_=10, step=5).render())
    <input id="Three--foo" max="10" min="2" name="Three--foo" step="5" type="range" />

    >>> print(html5_test_fieldset.foo.number(min_=2, max_=10, step=5).render())
    <input id="Three--foo" max="10" min="2" name="Three--foo" step="5" type="number" />

    >>> print(html5_test_fieldset.foo.time().render())
    <input id="Three--foo" name="Three--foo" type="time" />

    >>> print(html5_test_fieldset.foo.date().render())
    <input id="Three--foo" name="Three--foo" type="date" />

    >>> print(html5_test_fieldset.foo.datetime().render())
    <input id="Three--foo" name="Three--foo" type="datetime" />

    >>> print(html5_test_fieldset.foo.datetime_local().render())
    <input id="Three--foo" name="Three--foo" type="date" />

    >>> print(html5_test_fieldset.foo.week().render())
    <input id="Three--foo" name="Three--foo" type="week" />

    >>> print(html5_test_fieldset.foo.month().render())
    <input id="Three--foo" name="Three--foo" type="month" />

    >>> print(html5_test_fieldset.foo.color().render())
    <input id="Three--foo" name="Three--foo" type="color" />
    """

class HTML5(Base):
    __tablename__ = 'html5'
    id = Column('id', Integer, primary_key=True)
    date = Column(HTML5Date, nullable=True)
    time = Column(HTML5Time, nullable=True)
    datetime = Column(HTML5DateTime, nullable=True)
    color = Column(HTML5Color, nullable=True)

@selenium
class TestDateTime(unittest.TestCase):

    def setUp(self):
        self.app = SeleniumApp(application(HTML5))

    def test_render(self):
        resp = self.app.get('/')
        form = resp.form
        form['HTML5--date'] = '2011-01-1'
        form['HTML5--time'] = '12:10'
        form['HTML5--datetime'] = '2011-01-1T10:11Z'
        form['HTML5--color'] = '#fff'
        resp = form.submit()
        resp.mustcontain('OK')
        resp.mustcontain('2011-01-01 10:11:00')

    def tearDown(self):
        self.app.close()


text:
import Router from 'koa-router';
import { getList, add, del } from '../controllers/group';

const router = new Router({
  prefix: '/group'
});

router
  .get('/', getList)
  .post('/', add)
  .del('/:id', del);

export default router;


text:
using DivineInject.Test.DummyModel;

namespace DivineInject.Test.FactoryGenerator
{
    public interface ICreateDomainObjectWithSingleArgConstructor
    {
        IDomainObjectWithName Create(string name);
    }
}


text:
$LOAD_PATH.unshift File.expand_path("../../lib", __FILE__)
require "scrunch"


text:
//-----------------------------------------------------------------------
// <copyright file="ObservableBindingList.cs" company="Marimer LLC">
//     Copyright (c) Marimer LLC. All rights reserved.
//     Website: https://cslanet.com
// </copyright>
// <summary>Extends ObservableCollection with behaviors required</summary>
//-----------------------------------------------------------------------
using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using Csla.Serialization.Mobile;
using Csla.Core.FieldManager;
using Csla.Core;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using Csla.Properties;

namespace Csla.Core
{
  /// <summary>
  /// Extends ObservableCollection with behaviors required
  /// by CSLA .NET collections.
  /// </summary>
  /// <typeparam name="T"></typeparam>
  [Serializable]
  public class ObservableBindingList<T> : MobileObservableCollection<T>,
    IObservableBindingList,
    INotifyBusy,
    INotifyChildChanged,
    ISerializationNotification
  {
    #region SupportsChangeNotification

    private bool _supportsChangeNotificationCore = true;
    /// <summary>
    /// Gets a value indicating whether this object
    /// supports change notification.
    /// </summary>
    protected virtual bool SupportsChangeNotificationCore { get { return _supportsChangeNotificationCore; } }

    #endregion

    #region AddNew

    private bool _raiseListChangedEvents = true;

    /// <summary>
    /// Gets or sets a value indicating whether data binding
    /// can automatically edit items in this collection.
    /// </summary>
    public bool AllowEdit
    {
      get { return _allowEdit; }
      protected set { _allowEdit = value; }
    }

    /// <summary>
    /// Gets or sets a value indicating whether data binding
    /// can automatically add new items to this collection.
    /// </summary>
    public bool AllowNew
    {
      get { return _allowNew; }
      protected set { _allowNew = value; }
    }

    /// <summary>
    /// Gets or sets a value indicating whether data binding
    /// can automatically remove items from this collection.
    /// </summary>
    public bool AllowRemove
    {
      get { return _allowRemove; }
      protected set { _allowRemove = value; }
    }

    /// <summary>
    /// Gets or sets a value indicating whether the
    /// collection should raise changed events.
    /// </summary>
    public bool RaiseListChangedEvents
    {
      get { return _raiseListChangedEvents; }
      set { _raiseListChangedEvents = value; }
    }

#if (ANDROID || IOS) || NETFX_CORE
    /// <summary>
    /// Adds a new item to this collection.
    /// </summary>
    public void AddNew()
    {
      AddNewCore();
    }

    void IObservableBindingList.AddNew()
    {
      AddNew();
    }
#else
    /// <summary>
    /// Adds a new item to this collection.
    /// </summary>
    public T AddNew()
    {
      var result = AddNewCore();
      OnAddedNew(result);
      return result;
    }

    object IObservableBindingList.AddNew()
    {
      return AddNew();
    }
#endif

    #endregion

    #region RemovingItem event

    [NonSerialized()]
    private EventHandler<RemovingItemEventArgs> _removingItemHandler;

    /// <summary>
    /// Implements a serialization-safe RemovingItem event.
    /// </summary>
    public event EventHandler<RemovingItemEventArgs> RemovingItem
    {
      add
      {
        _removingItemHandler = (EventHandler<RemovingItemEventArgs>)
          System.Delegate.Combine(_removingItemHandler, value);
      }
      remove
      {
        _removingItemHandler = (EventHandler<RemovingItemEventArgs>)
          System.Delegate.Remove(_removingItemHandler, value);
      }
    }

    /// <summary>
    /// Raise the RemovingItem event.
    /// </summary>
    /// <param name="removedItem">
    /// A reference to the item that
    /// is being removed.
    /// </param>
    [EditorBrowsable(EditorBrowsableState.Advanced)]
    protected void OnRemovingItem(T removedItem)
    {
      if (_removingItemHandler != null)
        _removingItemHandler.Invoke(this,
          new RemovingItemEventArgs(removedItem));
    }

    #endregion

    #region RemoveItem

    /// <summary>
    /// Remove the item at the
    /// specified index.
    /// </summary>
    /// <param name="index">
    /// The zero-based index of the item
    /// to remove.
    /// </param>
    protected override void RemoveItem(int index)
    {
      OnRemovingItem(this[index]);
      OnRemoveEventHooks(this[index]);
      base.RemoveItem(index);
    }

    #endregion

    #region AddRange

    /// <summary>
    /// Add a range of items to the list.
    /// </summary>
    /// <param name="range">List of items to add.</param>
    public void AddRange(System.Collections.Generic.IEnumerable<T> range)
    {
      foreach (var element in range)
        this.Add(element);
    }

    #endregion

    #region INotifyPropertyBusy Members

    [NotUndoable]
    [NonSerialized]
    private BusyChangedEventHandler _busyChanged = null;

    /// <summary>
    /// Event indicating that the busy status of the
    /// object has changed.
    /// </summary>
    public event BusyChangedEventHandler BusyChanged
    {
      add { _busyChanged = (BusyChangedEventHandler)Delegate.Combine(_busyChanged, value); }
      remove { _busyChanged = (BusyChangedEventHandler)Delegate.Remove(_busyChanged, value); }
    }

    /// <summary>
    /// Override this method to be notified when the
    /// IsBusy property has changed.
    /// </summary>
    /// <param name="args">Event arguments.</param>
    protected virtual void OnBusyChanged(BusyChangedEventArgs args)
    {
      if (_busyChanged != null)
        _busyChanged(this, args);
    }

    /// <summary>
    /// Raises the BusyChanged event for a specific property.
    /// </summary>
    /// <param name="propertyName">Name of the property.</param>
    /// <param name="busy">New busy value.</param>
    protected void OnBusyChanged(string propertyName, bool busy)
    {
      OnBusyChanged(new BusyChangedEventArgs(propertyName, busy));
    }

    /// <summary>
    /// Gets the busy status for this object and its child objects.
    /// </summary>
    [Browsable(false)]
    [Display(AutoGenerateField = false)]
#if !PCL46 && !PCL259
    [System.ComponentModel.DataAnnotations.ScaffoldColumn(false)]
#endif
    public virtual bool IsBusy
    {
      get { return false; }
    }

    /// <summary>
    /// Gets the busy status for this object.
    /// </summary>
    [Browsable(false)]
    [Display(AutoGenerateField = false)]
#if !PCL46 && !PCL259
    [System.ComponentModel.DataAnnotations.ScaffoldColumn(false)]
#endif
    public virtual bool IsSelfBusy
    {
      get { return IsBusy; }
    }

    void busy_BusyChanged(object sender, BusyChangedEventArgs e)
    {
      OnBusyChanged(e);
    }

    #endregion

    #region INotifyUnhandledAsyncException Members

    [NotUndoable]
    [NonSerialized]
    private EventHandler<ErrorEventArgs> _unhandledAsyncException;

    /// <summary>
    /// Event indicating that an exception occurred during
    /// an async operation.
    /// </summary>
    public event EventHandler<ErrorEventArgs> UnhandledAsyncException
    {
      add { _unhandledAsyncException = (EventHandler<ErrorEventArgs>)Delegate.Combine(_unhandledAsyncException, value); }
      remove { _unhandledAsyncException = (EventHandler<ErrorEventArgs>)Delegate.Remove(_unhandledAsyncException, value); }
    }

    /// <summary>
    /// Method invoked when an unhandled async exception has
    /// occurred.
    /// </summary>
    /// <param name="error">Event arguments.</param>
    protected virtual void OnUnhandledAsyncException(ErrorEventArgs error)
    {
      if (_unhandledAsyncException != null)
        _unhandledAsyncException(this, error);
    }

    /// <summary>
    /// Raises the UnhandledAsyncException event.
    /// </summary>
    /// <param name="originalSender">Original sender of event.</param>
    /// <param name="error">Exception that occurred.</param>
    protected void OnUnhandledAsyncException(object originalSender, Exception error)
    {
      OnUnhandledAsyncException(new ErrorEventArgs(originalSender, error));
    }

    void unhandled_UnhandledAsyncException(object sender, ErrorEventArgs e)
    {
      OnUnhandledAsyncException(e);
    }

    #endregion

    #region AddChildHooks

    /// <summary>
    /// Invoked when an item is inserted into the list.
    /// </summary>
    /// <param name="index">Index of new item.</param>
    /// <param name="item">Reference to new item.</param>
    protected override void InsertItem(int index, T item)
    {
      base.InsertItem(index, item);
      OnAddEventHooks(item);
    }

    /// <summary>
    /// Method invoked when events are hooked for a child
    /// object.
    /// </summary>
    /// <param name="item">Reference to child object.</param>
    [EditorBrowsable(EditorBrowsableState.Never)]
    protected virtual void OnAddEventHooks(T item)
    {
      INotifyBusy busy = item as INotifyBusy;
      if (busy != null)
        busy.BusyChanged += new BusyChangedEventHandler(busy_BusyChanged);

      INotifyUnhandledAsyncException unhandled = item as INotifyUnhandledAsyncException;
      if (unhandled != null)
        unhandled.UnhandledAsyncException += new EventHandler<ErrorEventArgs>(unhandled_UnhandledAsyncException);

      INotifyPropertyChanged c = item as INotifyPropertyChanged;
      if (c != null)
        c.PropertyChanged += Child_PropertyChanged;

      //IBindingList list = item as IBindingList;
      //if (list != null)
      //  list.ListChanged += new ListChangedEventHandler(Child_ListChanged);

      INotifyChildChanged child = item as INotifyChildChanged;
      if (child != null)
        child.ChildChanged += Child_Changed;
    }

    /// <summary>
    /// Method invoked when events are unhooked for a child
    /// object.
    /// </summary>
    /// <param name="item">Reference to child object.</param>
    [EditorBrowsable(EditorBrowsableState.Never)]
    protected virtual void OnRemoveEventHooks(T item)
    {
      INotifyBusy busy = item as INotifyBusy;
      if (busy != null)
        busy.BusyChanged -= new BusyChangedEventHandler(busy_BusyChanged);

      INotifyUnhandledAsyncException unhandled = item as INotifyUnhandledAsyncException;
      if (unhandled != null)
        unhandled.UnhandledAsyncException -= new EventHandler<ErrorEventArgs>(unhandled_UnhandledAsyncException);

      INotifyPropertyChanged c = item as INotifyPropertyChanged;
      if (c != null)
        c.PropertyChanged -= Child_PropertyChanged;

      //IBindingList list = item as IBindingList;
      //if(list!=null)
      //  list.ListChanged -= new ListChangedEventHandler(Child_ListChanged);

      INotifyChildChanged child = item as INotifyChildChanged;
      if (child != null)
        child.ChildChanged -= new EventHandler<ChildChangedEventArgs>(Child_Changed);
    }

    #endregion

    #region ISerializationNotification Members

    /// <summary>
    /// This method is called on a newly deserialized object
    /// after deserialization is complete.
    /// </summary>
    [EditorBrowsable(EditorBrowsableState.Advanced)]
    protected virtual void OnDeserialized()
    {
      // do nothing - this is here so a subclass
      // could override if needed
    }

#if !NETFX_CORE || PCL46 || WINDOWS_UWP || PCL259
    [System.Runtime.Serialization.OnDeserialized]
#endif
    private void OnDeserializedHandler(System.Runtime.Serialization.StreamingContext context)
    {
      foreach (T item in this)
        OnAddEventHooks(item);

      OnDeserialized();
    }

    void ISerializationNotification.Deserialized()
    {
      // don't rehook events here, because the MobileFormatter has
      // created new objects and so the lists will auto-subscribe
      // the events
      OnDeserialized();
    }

    #endregion

    #region Child Change Notification

    [NonSerialized]
    [NotUndoable]
    private EventHandler<Csla.Core.ChildChangedEventArgs> _childChangedHandlers;

    /// <summary>
    /// Event raised when a child object has been changed.
    /// </summary>
    public event EventHandler<Csla.Core.ChildChangedEventArgs> ChildChanged
    {
      add
      {
        _childChangedHandlers = (EventHandler<Csla.Core.ChildChangedEventArgs>)
          System.Delegate.Combine(_childChangedHandlers, value);
      }
      remove
      {
        _childChangedHandlers = (EventHandler<Csla.Core.ChildChangedEventArgs>)
          System.Delegate.Remove(_childChangedHandlers, value);
      }
    }

    /// <summary>
    /// Raises the ChildChanged event, indicating that a child
    /// object has been changed.
    /// </summary>
    /// <param name="e">
    /// ChildChangedEventArgs object.
    /// </param>
    [EditorBrowsable(EditorBrowsableState.Advanced)]
    protected virtual void OnChildChanged(ChildChangedEventArgs e)
    {
      if (_childChangedHandlers != null)
        _childChangedHandlers.Invoke(this, e);
    }

    /// <summary>
    /// Creates a ChildChangedEventArgs and raises the event.
    /// </summary>
    private void RaiseChildChanged(
      object childObject, PropertyChangedEventArgs propertyArgs, NotifyCollectionChangedEventArgs listArgs)
    {
      ChildChangedEventArgs args = new ChildChangedEventArgs(childObject, propertyArgs, listArgs);
      OnChildChanged(args);
    }

    /// <summary>
    /// Handles any PropertyChanged event from
    /// a child object and echoes it up as
    /// a ChildChanged event.
    /// </summary>
    /// <param name="sender">Object that raised the event.</param>
    /// <param name="e">Property changed args.</param>
    [EditorBrowsable(EditorBrowsableState.Never)]
    protected virtual void Child_PropertyChanged(object sender, PropertyChangedEventArgs e)
    {
      // Issue 813
      // MetaPropertyHasChanged calls in OnChildChanged we're leading to exponential growth in OnChildChanged calls
      // Those notifications are for the UI. Ignore them in the parent
      if (!(e is MetaPropertyChangedEventArgs))
      {
        RaiseChildChanged(sender, e, null);
      }
    }

    /// <summary>
    /// Handles any ChildChanged event from
    /// a child object and echoes it up as
    /// a ChildChanged event.
    /// </summary>
    private void Child_Changed(object sender, ChildChangedEventArgs e)
    {
      RaiseChildChanged(e.ChildObject, e.PropertyChangedArgs, e.CollectionChangedArgs);
    }

    #endregion

    #region AddNewCore

    [NotUndoable]
    [NonSerialized]
    private EventHandler<AddedNewEventArgs<T>> _addedNewHandlers = null;

    private bool _allowEdit;
    private bool _allowNew;
    private bool _allowRemove;

    /// <summary>
    /// Event raised when a new object has been
    /// added to the collection.
    /// </summary>
    public event EventHandler<AddedNewEventArgs<T>> AddedNew
    {
      add
      {
        _addedNewHandlers = (EventHandler<AddedNewEventArgs<T>>)
          System.Delegate.Combine(_addedNewHandlers, value);
      }
      remove
      {
        _addedNewHandlers = (EventHandler<AddedNewEventArgs<T>>)
          System.Delegate.Remove(_addedNewHandlers, value);
      }
    }

    /// <summary>
    /// Raises the AddedNew event.
    /// </summary>
    /// <param name="item"></param>
    [EditorBrowsable(EditorBrowsableState.Advanced)]
    public virtual void OnAddedNew(T item)
    {
      if (_addedNewHandlers != null)
      {
        var args = new AddedNewEventArgs<T>(item);
        _addedNewHandlers(this, args);
      }
    }

#if (ANDROID || IOS) || NETFX_CORE
    /// <summary>
    /// Override this method to create a new object that is added
    /// to the collection.
    /// </summary>
    protected virtual void AddNewCore()
    {
      throw new NotImplementedException(Resources.AddNewCoreMustBeOverriden);
    }
#else
    /// <summary>
    /// Override this method to create a new object that is added
    /// to the collection.
    /// </summary>
    protected virtual T AddNewCore()
    {
      throw new NotImplementedException(Resources.AddNewCoreMustBeOverriden);
    }
#endif

    #endregion

    #region OnCollectionChanged

    /// <summary>
    /// Raises the CollectionChanged event.
    /// </summary>
    /// <param name="e">Event arguments.</param>
    [EditorBrowsable(EditorBrowsableState.Advanced)]
    protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
    {
      if (SupportsChangeNotificationCore && RaiseListChangedEvents)
        base.OnCollectionChanged(e);
    }

    #endregion

    #region MobileObject

    /// <summary>
    /// Override this method to get custom field values
    /// from the serialization stream.
    /// </summary>
    /// <param name="info">Serialization info.</param>
    [EditorBrowsable(EditorBrowsableState.Advanced)]
    protected override void OnGetState(SerializationInfo info)
    {
      base.OnGetState(info);
      info.AddValue("Csla.Core.MobileList.AllowEdit", AllowEdit);
      info.AddValue("Csla.Core.MobileList.AllowNew", AllowNew);
      info.AddValue("Csla.Core.MobileList.AllowRemove", AllowRemove);
      info.AddValue("Csla.Core.MobileList.RaiseListChangedEvents", RaiseListChangedEvents);
      info.AddValue("Csla.Core.MobileList._supportsChangeNotificationCore", _supportsChangeNotificationCore);
    }

    /// <summary>
    /// Override this method to set custom field values
    /// into the serialization stream.
    /// </summary>
    /// <param name="info">Serialization info.</param>
    [EditorBrowsable(EditorBrowsableState.Advanced)]
    protected override void OnSetState(SerializationInfo info)
    {
      base.OnSetState(info);
      AllowEdit = info.GetValue<bool>("Csla.Core.MobileList.AllowEdit");
      AllowNew = info.GetValue<bool>("Csla.Core.MobileList.AllowNew");
      AllowRemove = info.GetValue<bool>("Csla.Core.MobileList.AllowRemove");
      RaiseListChangedEvents = info.GetValue<bool>("Csla.Core.MobileList.RaiseListChangedEvents");
      _supportsChangeNotificationCore = info.GetValue<bool>("Csla.Core.MobileList._supportsChangeNotificationCore");
    }

    #endregion

    #region SuppressLListChanged

    /// <summary>
    /// Use this object to suppress ListChangedEvents for an entire code block.
    /// May be nested in multiple levels for the same object.
    /// </summary>
    public IDisposable SuppressListChangedEvents
    {
      get { return new SuppressListChangedEventsClass<T>(this); }
    }

    /// <summary>
    /// Handles the suppressing of raising ChangedEvents when altering the content of an ObservableBindingList.
    /// Will be instanciated by a factory property on the ObservableBindingList implementation.
    /// </summary>
    /// <typeparam name="TC">The type of the C.</typeparam>
    class SuppressListChangedEventsClass<TC> : IDisposable
    {
      private readonly ObservableBindingList<TC> _businessObject;
      private readonly bool _initialRaiseListChangedEvents;

      public SuppressListChangedEventsClass(ObservableBindingList<TC> businessObject)
      {
        this._businessObject = businessObject;
        _initialRaiseListChangedEvents = businessObject.RaiseListChangedEvents;
        businessObject.RaiseListChangedEvents = false;
      }

      public void Dispose()
      {
        _businessObject.RaiseListChangedEvents = _initialRaiseListChangedEvents;
      }
    }

    #endregion
  }
}


text:
package net.kurikagononaka.mapImager.model.input;

import com.flowpowered.nbt.Tag;
import com.flowpowered.nbt.stream.NBTInputStream;
import net.kurikagononaka.mapImager.model.map.SingleMapFile;
import net.kurikagononaka.mapImager.model.nbt.MapFileNbt;
import net.kurikagononaka.mapImager.model.nbt.nbtMapper.NbtMapper;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class MapFileLoader {

    public MapFileLoader() {
    }

    public SingleMapFile loadMapFile(String fileName) throws IOException {
        try (FileInputStream inputStream = new FileInputStream(fileName)) {
            NBTInputStream nbtInputStream = new NBTInputStream(inputStream);

            Tag<?> tag = nbtInputStream.readTag();

            MapFileNbt mapNbt = (MapFileNbt) NbtMapper.parse(MapFileNbt.class, tag);

            File file = new File(fileName);
            return new SingleMapFile(mapNbt, file.getName());
        }
    }
}


text:
//! \file mgparallel.h
//! \brief 定义平行四边形图形类 MgParallel
// Copyright (c) 2004-2014, Zhang Yungui
// License: LGPL, https://github.com/rhcad/vgcore

#ifndef TOUCHVG_PARALLEL_SHAPE_H_
#define TOUCHVG_PARALLEL_SHAPE_H_

#include "mgbasesp.h"

//! 平行四边形图形类
/*! \ingroup CORE_SHAPE
 */
class MgParallel : public MgBaseShape
{
    MG_DECLARE_CREATE(MgParallel, MgBaseShape, 17)
public:
    //! 返回中心点
    Point2d getCenter() const { return (_points[0] + _points[2]) / 2; }

    //! 返回矩形框,是本对象未旋转时的形状
    Box2d getRect() const { return Box2d(getCenter(), getWidth(), getHeight()); }

    //! 返回宽度
    float getWidth() const { return _points[0].distanceTo(_points[1]); }

    //! 返回高度
    float getHeight() const { return _points[2].distanceTo(_points[1]); }

    //! 返回角度, [-PI, PI)
    float angle() const { return (_points[2] - _points[3]).angleTo2(_points[0] - _points[3]); }

    //! 返回是否为空矩形
    bool isEmpty(float minDist) const {
        return getWidth() <= minDist || getHeight() <= minDist; }

#ifndef SWIG
    virtual const Point2d* getPoints() const { return _points; }
#endif

protected:
    bool _isClosed() const { return true; }
    int _getHandleCount() const;
    Point2d _getHandlePoint(int index) const;
    bool _setHandlePoint(int index, const Point2d& pt, float tol);
    int _getHandleType(int index) const;
    bool _isHandleFixed(int index) const;
    bool _offset(const Vector2d& vec, int segment);
    bool _rotateHandlePoint(int index, const Point2d& pt);
    bool _hitTestBox(const Box2d& rect) const;
    void _output(MgPath& path) const;
    bool _save(MgStorage* s) const;
    bool _load(MgShapeFactory* factory, MgStorage* s);

protected:
    Point2d     _points[4]; // 从左上角起顺时针的四个角点
};

#endif // TOUCHVG_PARALLEL_SHAPE_H_


text:
<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
namespace Agp\AdminBundle\Entity\Dummy;
use Doctrine\ORM\Mapping as ORM;

use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * Description of ProdutoDummy
 *
 * @author bondcs
 */
class ProdutoDummy {

    /**
     * @Assert\Valid
     */
    public $produtos;

    public function __construct() {
        $this->produtos = new ArrayCollection();
    }

    /**
     * Get produtos
     *
     * @return Doctrine\Common\Collections\Collection
     */
    public function setProdutos(ArrayCollection $produtos)
    {
        $this->produtos = $produtos;
    }

    /**
     * Get produtos
     *
     * @return Doctrine\Common\Collections\Collection
     */
    public function getProdutos()
    {
        return $this->produtos;
    }

}

?>