text:
import {
  AsyncTestCompleter,
  beforeEach,
  ddescribe,
  xdescribe,
  describe,
  el,
  dispatchEvent,
  expect,
  iit,
  inject,
  beforeEachBindings,
  it,
  xit,
  SpyObject,
  proxy
} from 'angular2/test_lib';
import {Injector, bind} from 'angular2/di';
import {IMPLEMENTS, isBlank, isPresent} from 'angular2/src/facade/lang';
import {MapWrapper, ListWrapper, StringMapWrapper} from 'angular2/src/facade/collection';

import {AppProtoView, AppView, AppViewContainer} from 'angular2/src/core/compiler/view';
import {ProtoViewRef, ViewRef, internalView} from 'angular2/src/core/compiler/view_ref';
import {Renderer, RenderViewRef, RenderProtoViewRef} from 'angular2/src/render/api';
import {ElementBinder} from 'angular2/src/core/compiler/element_binder';
import {DirectiveBinding, ElementInjector} from 'angular2/src/core/compiler/element_injector';
import {DirectiveResolver} from 'angular2/src/core/compiler/directive_resolver';
import {Component} from 'angular2/annotations';
import {AppViewManager} from 'angular2/src/core/compiler/view_manager';
import {AppViewManagerUtils} from 'angular2/src/core/compiler/view_manager_utils';
import {AppViewListener} from 'angular2/src/core/compiler/view_listener';
import {AppViewPool} from 'angular2/src/core/compiler/view_pool';

export function main() {
  // TODO(tbosch): add missing tests

  describe('AppViewManager', () => {
    var renderer;
    var utils;
    var viewListener;
    var viewPool;
    var manager;
    var directiveResolver;
    var createdViews: any[];
    var createdRenderViews: any[];

    function wrapPv(protoView: AppProtoView): ProtoViewRef { return new ProtoViewRef(protoView); }

    function wrapView(view: AppView): ViewRef { return new ViewRef(view); }

    function elementRef(parentView, boundElementIndex) {
      return parentView.elementRefs[boundElementIndex];
    }

    function createDirectiveBinding(type) {
      var annotation = directiveResolver.resolve(type);
      return DirectiveBinding.createFromType(type, annotation);
    }

    function createEmptyElBinder() { return new ElementBinder(0, null, 0, null, null); }

    function createComponentElBinder(nestedProtoView = null) {
      var binding = createDirectiveBinding(SomeComponent);
      var binder = new ElementBinder(0, null, 0, null, binding);
      binder.nestedProtoView = nestedProtoView;
      return binder;
    }

    function createProtoView(binders = null) {
      if (isBlank(binders)) {
        binders = [];
      }
      var staticChildComponentCount = 0;
      for (var i = 0; i < binders.length; i++) {
        if (binders[i].hasStaticComponent()) {
          staticChildComponentCount++;
        }
      }
      var res = new AppProtoView(new MockProtoViewRef(staticChildComponentCount), null, null, null);
      res.elementBinders = binders;
      return res;
    }

    function createElementInjector() {
      return SpyObject.stub(new SpyElementInjector(),
                            {
                              'isExportingComponent': false,
                              'isExportingElement': false,
                              'getEventEmitterAccessors': [],
                              'getComponent': null
                            },
                            {});
    }

    function createView(pv = null, renderViewRef = null) {
      if (isBlank(pv)) {
        pv = createProtoView();
      }
      if (isBlank(renderViewRef)) {
        renderViewRef = new RenderViewRef();
      }
      var view = new AppView(renderer, pv, new Map());
      view.render = renderViewRef;
      var elementInjectors = ListWrapper.createFixedSize(pv.elementBinders.length);
      for (var i = 0; i < pv.elementBinders.length; i++) {
        elementInjectors[i] = createElementInjector();
      }
      view.init(null, elementInjectors, [], ListWrapper.createFixedSize(pv.elementBinders.length),
                ListWrapper.createFixedSize(pv.elementBinders.length));
      return view;
    }

    beforeEach(() => {
      directiveResolver = new DirectiveResolver();
      renderer = new SpyRenderer();
      utils = new SpyAppViewManagerUtils();
      viewListener = new SpyAppViewListener();
      viewPool = new SpyAppViewPool();
      manager = new AppViewManager(viewPool, viewListener, utils, renderer);
      createdViews = [];
      createdRenderViews = [];

      utils.spy('createView')
          .andCallFake((proto, renderViewRef, _a, _b) => {
            var view = createView(proto, renderViewRef);
            createdViews.push(view);
            return view;
          });
      utils.spy('attachComponentView')
          .andCallFake((hostView, elementIndex, childView) => {
            hostView.componentChildViews[elementIndex] = childView;
          });
      utils.spy('attachViewInContainer')
          .andCallFake((parentView, elementIndex, _a, _b, atIndex, childView) => {
            var viewContainer = parentView.viewContainers[elementIndex];
            if (isBlank(viewContainer)) {
              viewContainer = new AppViewContainer();
              parentView.viewContainers[elementIndex] = viewContainer;
            }
            ListWrapper.insert(viewContainer.views, atIndex, childView);
          });
      renderer.spy('createRootHostView')
          .andCallFake((_b, _c) => {
            var rv = new RenderViewRef();
            createdRenderViews.push(rv);
            return rv;
          });
      renderer.spy('createView')
          .andCallFake((_a) => {
            var rv = new RenderViewRef();
            createdRenderViews.push(rv);
            return rv;
          });
      viewPool.spy('returnView').andReturn(true);
    });

    describe('static child components', () => {

      describe('recursively create when not cached', () => {
        var rootProtoView, hostProtoView, componentProtoView, hostView, componentView;
        beforeEach(() => {
          componentProtoView = createProtoView();
          hostProtoView = createProtoView([createComponentElBinder(componentProtoView)]);
          rootProtoView = createProtoView([createComponentElBinder(hostProtoView)]);
          manager.createRootHostView(wrapPv(rootProtoView), null, null);
          hostView = createdViews[1];
          componentView = createdViews[2];
        });

        it('should create the view', () => {
          expect(hostView.proto).toBe(hostProtoView);
          expect(componentView.proto).toBe(componentProtoView);
        });

        it('should hydrate the view', () => {
          expect(utils.spy('hydrateComponentView')).toHaveBeenCalledWith(hostView, 0);
          expect(renderer.spy('hydrateView')).toHaveBeenCalledWith(componentView.render);
        });

        it('should set the render view',
           () => {expect(componentView.render).toBe(createdRenderViews[2])});

        it('should set the event dispatcher', () => {
          expect(renderer.spy('setEventDispatcher'))
              .toHaveBeenCalledWith(componentView.render, componentView);
        });
      });

      describe('recursively hydrate when getting from from the cache',
               () => {
                   // TODO(tbosch): implement this
               });

      describe('recursively dehydrate', () => {
                                            // TODO(tbosch): implement this
                                        });

    });

    describe('createRootHostView', () => {

      var hostProtoView;
      beforeEach(() => { hostProtoView = createProtoView([createComponentElBinder(null)]); });

      it('should create the view', () => {
        expect(internalView(manager.createRootHostView(wrapPv(hostProtoView), null, null)))
            .toBe(createdViews[0]);
        expect(createdViews[0].proto).toBe(hostProtoView);
        expect(viewListener.spy('viewCreated')).toHaveBeenCalledWith(createdViews[0]);
      });

      it('should hydrate the view', () => {
        var injector = new Injector([], null, false);
        manager.createRootHostView(wrapPv(hostProtoView), null, injector);
        expect(utils.spy('hydrateRootHostView')).toHaveBeenCalledWith(createdViews[0], injector);
        expect(renderer.spy('hydrateView')).toHaveBeenCalledWith(createdViews[0].render);
      });

      it('should create and set the render view using the component selector', () => {
        manager.createRootHostView(wrapPv(hostProtoView), null, null)
            expect(renderer.spy('createRootHostView'))
                .toHaveBeenCalledWith(hostProtoView.render, 'someComponent');
        expect(createdViews[0].render).toBe(createdRenderViews[0]);
      });

      it('should allow to override the selector', () => {
        var selector = 'someOtherSelector';
        manager.createRootHostView(wrapPv(hostProtoView), selector, null)
            expect(renderer.spy('createRootHostView'))
                .toHaveBeenCalledWith(hostProtoView.render, selector);
      });

      it('should set the event dispatcher', () => {
        manager.createRootHostView(wrapPv(hostProtoView), null, null);
        var cmpView = createdViews[0];
        expect(renderer.spy('setEventDispatcher')).toHaveBeenCalledWith(cmpView.render, cmpView);
      });

    });

    describe('destroyRootHostView', () => {
      var hostProtoView, hostView, hostRenderViewRef;
      beforeEach(() => {
        hostProtoView = createProtoView([createComponentElBinder(null)]);
        hostView = internalView(manager.createRootHostView(wrapPv(hostProtoView), null, null));
        hostRenderViewRef = hostView.render;
      });

      it('should dehydrate', () => {
        manager.destroyRootHostView(wrapView(hostView));
        expect(utils.spy('dehydrateView')).toHaveBeenCalledWith(hostView);
        expect(renderer.spy('dehydrateView')).toHaveBeenCalledWith(hostView.render);
      });

      it('should destroy the render view', () => {
        manager.destroyRootHostView(wrapView(hostView));
        expect(renderer.spy('destroyView')).toHaveBeenCalledWith(hostRenderViewRef);
        expect(viewListener.spy('viewDestroyed')).toHaveBeenCalledWith(hostView);
      });

      it('should not return the view to the pool', () => {
        manager.destroyRootHostView(wrapView(hostView));
        expect(viewPool.spy('returnView')).not.toHaveBeenCalled();
      });

    });

    describe('createViewInContainer', () => {

      describe('basic functionality', () => {
        var parentView, childProtoView;
        beforeEach(() => {
          parentView = createView(createProtoView([createEmptyElBinder()]));
          childProtoView = createProtoView();
        });

        it('should create a ViewContainerRef if not yet existing', () => {
          manager.createViewInContainer(elementRef(parentView, 0), 0, wrapPv(childProtoView), null);
          expect(parentView.viewContainers[0]).toBeTruthy();
        });

        it('should create the view', () => {
          expect(internalView(manager.createViewInContainer(elementRef(parentView, 0), 0,
                                                            wrapPv(childProtoView), null)))
              .toBe(createdViews[0]);
          expect(createdViews[0].proto).toBe(childProtoView);
          expect(viewListener.spy('viewCreated')).toHaveBeenCalledWith(createdViews[0]);
        });

        it('should attach the view', () => {
          var contextView =
              createView(createProtoView([createEmptyElBinder(), createEmptyElBinder()]));
          var elRef = elementRef(parentView, 0);
          manager.createViewInContainer(elRef, 0, wrapPv(childProtoView),
                                        elementRef(contextView, 1), null);
          expect(utils.spy('attachViewInContainer'))
              .toHaveBeenCalledWith(parentView, 0, contextView, 1, 0, createdViews[0]);
          expect(renderer.spy('attachViewInContainer'))
              .toHaveBeenCalledWith(elRef, 0, createdViews[0].render);
        });

        it('should hydrate the view', () => {
          var injector = new Injector([], null, false);
          var contextView =
              createView(createProtoView([createEmptyElBinder(), createEmptyElBinder()]));
          manager.createViewInContainer(elementRef(parentView, 0), 0, wrapPv(childProtoView),
                                        elementRef(contextView, 1), injector);
          expect(utils.spy('hydrateViewInContainer'))
              .toHaveBeenCalledWith(parentView, 0, contextView, 1, 0, injector);
          expect(renderer.spy('hydrateView')).toHaveBeenCalledWith(createdViews[0].render);
        });

        it('should create and set the render view', () => {
          manager.createViewInContainer(elementRef(parentView, 0), 0, wrapPv(childProtoView), null,
                                        null);
          expect(renderer.spy('createView')).toHaveBeenCalledWith(childProtoView.render);
          expect(createdViews[0].render).toBe(createdRenderViews[0]);
        });

        it('should set the event dispatcher', () => {
          manager.createViewInContainer(elementRef(parentView, 0), 0, wrapPv(childProtoView), null,
                                        null);
          var childView = createdViews[0];
          expect(renderer.spy('setEventDispatcher'))
              .toHaveBeenCalledWith(childView.render, childView);
        });

      });
    });

    describe('destroyViewInContainer', () => {

      describe('basic functionality', () => {
        var parentView, childProtoView, childView;
        beforeEach(() => {
          parentView = createView(createProtoView([createEmptyElBinder()]));
          childProtoView = createProtoView();
          childView = internalView(manager.createViewInContainer(elementRef(parentView, 0), 0,
                                                                 wrapPv(childProtoView), null));
        });

        it('should dehydrate', () => {
          manager.destroyViewInContainer(elementRef(parentView, 0), 0);
          expect(utils.spy('dehydrateView'))
              .toHaveBeenCalledWith(parentView.viewContainers[0].views[0]);
          expect(renderer.spy('dehydrateView')).toHaveBeenCalledWith(childView.render);
        });

        it('should detach', () => {
          var elRef = elementRef(parentView, 0);
          manager.destroyViewInContainer(elRef, 0);
          expect(utils.spy('detachViewInContainer')).toHaveBeenCalledWith(parentView, 0, 0);
          expect(renderer.spy('detachViewInContainer'))
              .toHaveBeenCalledWith(elRef, 0, childView.render);
        });

        it('should return the view to the pool', () => {
          manager.destroyViewInContainer(elementRef(parentView, 0), 0);
          expect(viewPool.spy('returnView')).toHaveBeenCalledWith(childView);
        });
      });

      describe('recursively destroy views in ViewContainers', () => {
        var parentView, childProtoView, childView;
        beforeEach(() => {
          parentView = createView(createProtoView([createEmptyElBinder()]));
          childProtoView = createProtoView();
          childView = internalView(manager.createViewInContainer(elementRef(parentView, 0), 0,
                                                                 wrapPv(childProtoView), null));
        });

        it('should dehydrate', () => {
          manager.destroyRootHostView(wrapView(parentView));
          expect(utils.spy('dehydrateView'))
              .toHaveBeenCalledWith(parentView.viewContainers[0].views[0]);
          expect(renderer.spy('dehydrateView')).toHaveBeenCalledWith(childView.render);
        });

        it('should detach', () => {
          manager.destroyRootHostView(wrapView(parentView));
          expect(utils.spy('detachViewInContainer')).toHaveBeenCalledWith(parentView, 0, 0);
          expect(renderer.spy('detachViewInContainer'))
              .toHaveBeenCalledWith(parentView.elementRefs[0], 0, childView.render);
        });

        it('should return the view to the pool', () => {
          manager.destroyRootHostView(wrapView(parentView));
          expect(viewPool.spy('returnView')).toHaveBeenCalledWith(childView);
        });

      });

    });

    describe('attachViewInContainer', () => {

                                      });

    describe('detachViewInContainer', () => {

                                      });
  });
}

class MockProtoViewRef extends RenderProtoViewRef {
  nestedComponentCount: number;
  constructor(nestedComponentCount: number) {
    super();
    this.nestedComponentCount = nestedComponentCount;
  }
}

@Component({selector: 'someComponent'})
class SomeComponent {
}

@proxy
@IMPLEMENTS(Renderer)
class SpyRenderer extends SpyObject {
  constructor() { super(Renderer); }
  noSuchMethod(m) { return super.noSuchMethod(m) }
}

@proxy
@IMPLEMENTS(AppViewPool)
class SpyAppViewPool extends SpyObject {
  constructor() { super(AppViewPool); }
  noSuchMethod(m) { return super.noSuchMethod(m) }
}

@proxy
@IMPLEMENTS(AppViewManagerUtils)
class SpyAppViewManagerUtils extends SpyObject {
  constructor() { super(AppViewManagerUtils); }
  noSuchMethod(m) { return super.noSuchMethod(m) }
}

@proxy
@IMPLEMENTS(AppViewListener)
class SpyAppViewListener extends SpyObject {
  constructor() { super(AppViewListener); }
  noSuchMethod(m) { return super.noSuchMethod(m) }
}

@proxy
@IMPLEMENTS(ElementInjector)
class SpyElementInjector extends SpyObject {
  constructor() { super(ElementInjector); }
  noSuchMethod(m) { return super.noSuchMethod(m) }
}


text:
"""Tests for Scikit-learn API wrapper."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import numpy as np

from tensorflow.python import keras
from tensorflow.python.keras import testing_utils
from tensorflow.python.keras.wrappers import scikit_learn
from tensorflow.python.platform import test

INPUT_DIM = 5
HIDDEN_DIM = 5
TRAIN_SAMPLES = 10
TEST_SAMPLES = 5
NUM_CLASSES = 2
BATCH_SIZE = 5
EPOCHS = 1

def build_fn_clf(hidden_dim):
  model = keras.models.Sequential()
  model.add(keras.layers.Dense(INPUT_DIM, input_shape=(INPUT_DIM,)))
  model.add(keras.layers.Activation('relu'))
  model.add(keras.layers.Dense(hidden_dim))
  model.add(keras.layers.Activation('relu'))
  model.add(keras.layers.Dense(NUM_CLASSES))
  model.add(keras.layers.Activation('softmax'))
  model.compile(
      optimizer='sgd', loss='categorical_crossentropy', metrics=['accuracy'])
  return model

def assert_classification_works(clf):
  np.random.seed(42)
  (x_train, y_train), (x_test, _) = testing_utils.get_test_data(
      train_samples=TRAIN_SAMPLES,
      test_samples=TEST_SAMPLES,
      input_shape=(INPUT_DIM,),
      num_classes=NUM_CLASSES)

  clf.fit(x_train, y_train, batch_size=BATCH_SIZE, epochs=EPOCHS)

  score = clf.score(x_train, y_train, batch_size=BATCH_SIZE)
  assert np.isscalar(score) and np.isfinite(score)

  preds = clf.predict(x_test, batch_size=BATCH_SIZE)
  assert preds.shape == (TEST_SAMPLES,)
  for prediction in np.unique(preds):
    assert prediction in range(NUM_CLASSES)

  proba = clf.predict_proba(x_test, batch_size=BATCH_SIZE)
  assert proba.shape == (TEST_SAMPLES, NUM_CLASSES)
  assert np.allclose(np.sum(proba, axis=1), np.ones(TEST_SAMPLES))

def build_fn_reg(hidden_dim):
  model = keras.models.Sequential()
  model.add(keras.layers.Dense(INPUT_DIM, input_shape=(INPUT_DIM,)))
  model.add(keras.layers.Activation('relu'))
  model.add(keras.layers.Dense(hidden_dim))
  model.add(keras.layers.Activation('relu'))
  model.add(keras.layers.Dense(1))
  model.add(keras.layers.Activation('linear'))
  model.compile(
      optimizer='sgd', loss='mean_absolute_error', metrics=['accuracy'])
  return model

def assert_regression_works(reg):
  np.random.seed(42)
  (x_train, y_train), (x_test, _) = testing_utils.get_test_data(
      train_samples=TRAIN_SAMPLES,
      test_samples=TEST_SAMPLES,
      input_shape=(INPUT_DIM,),
      num_classes=NUM_CLASSES)

  reg.fit(x_train, y_train, batch_size=BATCH_SIZE, epochs=EPOCHS)

  score = reg.score(x_train, y_train, batch_size=BATCH_SIZE)
  assert np.isscalar(score) and np.isfinite(score)

  preds = reg.predict(x_test, batch_size=BATCH_SIZE)
  assert preds.shape == (TEST_SAMPLES,)

class ScikitLearnAPIWrapperTest(test.TestCase):

  def test_classify_build_fn(self):
    with self.cached_session():
      clf = scikit_learn.KerasClassifier(
          build_fn=build_fn_clf,
          hidden_dim=HIDDEN_DIM,
          batch_size=BATCH_SIZE,
          epochs=EPOCHS)

      assert_classification_works(clf)

  def test_classify_class_build_fn(self):

    class ClassBuildFnClf(object):

      def __call__(self, hidden_dim):
        return build_fn_clf(hidden_dim)

    with self.cached_session():
      clf = scikit_learn.KerasClassifier(
          build_fn=ClassBuildFnClf(),
          hidden_dim=HIDDEN_DIM,
          batch_size=BATCH_SIZE,
          epochs=EPOCHS)

      assert_classification_works(clf)

  def test_classify_inherit_class_build_fn(self):

    class InheritClassBuildFnClf(scikit_learn.KerasClassifier):

      def __call__(self, hidden_dim):
        return build_fn_clf(hidden_dim)

    with self.cached_session():
      clf = InheritClassBuildFnClf(
          build_fn=None,
          hidden_dim=HIDDEN_DIM,
          batch_size=BATCH_SIZE,
          epochs=EPOCHS)

      assert_classification_works(clf)

  def test_regression_build_fn(self):
    with self.cached_session():
      reg = scikit_learn.KerasRegressor(
          build_fn=build_fn_reg,
          hidden_dim=HIDDEN_DIM,
          batch_size=BATCH_SIZE,
          epochs=EPOCHS)

      assert_regression_works(reg)

  def test_regression_class_build_fn(self):

    class ClassBuildFnReg(object):

      def __call__(self, hidden_dim):
        return build_fn_reg(hidden_dim)

    with self.cached_session():
      reg = scikit_learn.KerasRegressor(
          build_fn=ClassBuildFnReg(),
          hidden_dim=HIDDEN_DIM,
          batch_size=BATCH_SIZE,
          epochs=EPOCHS)

      assert_regression_works(reg)

  def test_regression_inherit_class_build_fn(self):

    class InheritClassBuildFnReg(scikit_learn.KerasRegressor):

      def __call__(self, hidden_dim):
        return build_fn_reg(hidden_dim)

    with self.cached_session():
      reg = InheritClassBuildFnReg(
          build_fn=None,
          hidden_dim=HIDDEN_DIM,
          batch_size=BATCH_SIZE,
          epochs=EPOCHS)

      assert_regression_works(reg)

if __name__ == '__main__':
  test.main()

redpajama_set_name: RedPajamaGithub


text:
package de.knightsoftnet.validators.shared.impl;

import de.knightsoftnet.validators.server.data.CreateVatIdMapConstantsClass;
import de.knightsoftnet.validators.shared.VatId;
import de.knightsoftnet.validators.shared.data.VatIdMapSharedConstants;
import de.knightsoftnet.validators.shared.util.BeanPropertyReaderUtil;

import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * Check if a vat id field is valid for the selected country.
 *
 * @author Manfred Tremmel
 *
 */
public class VatIdValidator implements ConstraintValidator<VatId, Object> {
  /**
   * modulo 11.
   */
  private static final int MODULO_11 = 11;
  /**
   * modulo 97.
   */
  private static final int MODULO_97 = 97;

  /**
   * map of vat id regex values for the different countries.
   */
  private static final VatIdMapSharedConstants VATID_MAP = CreateVatIdMapConstantsClass.create();

  /**
   * error message key.
   */
  private String message;

  /**
   * field name of the country code field.
   */
  private String fieldCountryCode;

  /**
   * are lower case country codes allowed (true/false).
   */
  private boolean allowLowerCaseCountryCode;

  /**
   * field name of the vat id field.
   */
  private String fieldVatId;

  /**
   * {@inheritDoc} initialize the validator.
   *
   * @see javax.validation.ConstraintValidator#initialize(java.lang.annotation.Annotation)
   */
  @Override
  public final void initialize(final VatId pconstraintAnnotation) {
    message = pconstraintAnnotation.message();
    fieldCountryCode = pconstraintAnnotation.fieldCountryCode();
    allowLowerCaseCountryCode = pconstraintAnnotation.allowLowerCaseCountryCode();
    fieldVatId = pconstraintAnnotation.fieldVatId();
  }

  @Override
  public final boolean isValid(final Object pvalue, final ConstraintValidatorContext pcontext) {
    if (pvalue == null) {
      return true;
    }
    try {
      String countryCode =
          BeanPropertyReaderUtil.getNullSaveStringProperty(pvalue, fieldCountryCode);
      if (StringUtils.isEmpty(countryCode)) {
        return true;
      }
      final String vatId = BeanPropertyReaderUtil.getNullSaveStringProperty(pvalue, fieldVatId);
      if (StringUtils.isEmpty(vatId)) {
        return true;
      }

      if (allowLowerCaseCountryCode) {
        countryCode = StringUtils.upperCase(countryCode);
      }

      final String regExCheck = VATID_MAP.vatIds().get(countryCode);
      if (regExCheck == null) {
        return true;
      }
      if (vatId.matches(regExCheck) && checkSumTest(countryCode, vatId)) {
        return true;
      }
      switchContext(pcontext);
      return false;
    } catch (final Exception ignore) {
      switchContext(pcontext);
      return false;
    }
  }

  private void switchContext(final ConstraintValidatorContext pcontext) {
    pcontext.disableDefaultConstraintViolation();
    pcontext.buildConstraintViolationWithTemplate(message).addPropertyNode(fieldVatId)
        .addConstraintViolation();
  }

  private boolean checkSumTest(final String pcountryCode, final String pvatId) {
    boolean checkSumOk = false;
    switch (pcountryCode) {
      case "AT":
        checkSumOk = checkAtVatId(pvatId);
        break;
      case "BE":
        checkSumOk = checkBeVatId(pvatId);
        break;
      case "DE":
        checkSumOk = checkDeVatId(pvatId);
        break;
      case "DK":
        checkSumOk = checkDkVatId(pvatId);
        break;
      case "ES":
        checkSumOk = checkEsVatId(pvatId);
        break;
      case "FI":
        checkSumOk = checkFiVatId(pvatId);
        break;
      case "FR":
        checkSumOk = checkFrVatId(pvatId);
        break;
      case "GR":
        checkSumOk = checkGrVatId(pvatId);
        break;
      case "IE":
        checkSumOk = checkIeVatId(pvatId);
        break;
      case "IT":
        checkSumOk = checkItVatId(pvatId);
        break;
      case "LU":
        checkSumOk = checkLuVatId(pvatId);
        break;
      case "NL":
        checkSumOk = checkNlVatId(pvatId);
        break;
      case "NO":
        checkSumOk = checkNoVatId(pvatId);
        break;
      case "PL":
        checkSumOk = checkPlVatId(pvatId);
        break;
      case "PT":
        checkSumOk = checkPtVatId(pvatId);
        break;
      case "SE":
        checkSumOk = checkSeVatId(pvatId);
        break;
      case "SI":
        checkSumOk = checkSiVatId(pvatId);
        break;
      default:
        // for other countries, I haven't found checksum rules
        checkSumOk = true;
        break;
    }
    return checkSumOk;
  }

  /**
   * check the VAT identification number, country version for Austria.
   *
   * @param pvatId vat id to check
   * @return true if checksum is ok
   */
  private boolean checkAtVatId(final String pvatId) {
    final int checkSum = pvatId.charAt(10) - '0';
    final int sum = pvatId.charAt(3) - '0' + squareSum((pvatId.charAt(4) - '0') * 2)
        + pvatId.charAt(5) - '0' + squareSum((pvatId.charAt(6) - '0') * 2) + pvatId.charAt(7) - '0'
        + squareSum((pvatId.charAt(8) - '0') * 2) + pvatId.charAt(9) - '0';
    final int calculatedCheckSum = (96 - sum) % 10;
    return checkSum == calculatedCheckSum;
  }

  /**
   * check the VAT identification number, country version for Belgium.
   *
   * @param pvatId vat id to check
   * @return true if checksum is ok
   */
  private boolean checkBeVatId(final String pvatId) {
    final int numberPart = Integer.parseInt(pvatId.substring(2, 10));
    final int checkSum = Integer.parseInt(pvatId.substring(10));
    final int calculatedCheckSumBe = MODULO_97 - numberPart % MODULO_97;
    return checkSum == calculatedCheckSumBe;
  }

  /**
   * check the VAT identification number, country version for Denmark.
   *
   * @param pvatId vat id to check
   * @return true if checksum is ok
   */
  private boolean checkDkVatId(final String pvatId) {
    final int sum = (pvatId.charAt(2) - '0') * 2 + (pvatId.charAt(3) - '0') * 7
        + (pvatId.charAt(4) - '0') * 6 + (pvatId.charAt(5) - '0') * 5 + (pvatId.charAt(6) - '0') * 4
        + (pvatId.charAt(7) - '0') * 3 + (pvatId.charAt(8) - '0') * 2 + pvatId.charAt(9) - '0';
    return sum % MODULO_11 == 0;
  }

  /**
   * check the VAT identification number, country version for Germany.
   *
   * @param pvatId vat id to check
   * @return true if checksum is ok
   */
  private boolean checkDeVatId(final String pvatId) {
    final int checkSum = pvatId.charAt(10) - '0';
    int sum = 10;
    for (int i = 2; i < 10; i++) {
      int summe = (pvatId.charAt(i) - '0' + sum) % 10;
      if (summe == 0) {
        summe = 10;
      }
      sum = 2 * summe % MODULO_11;
    }
    int calculatedCheckSum = MODULO_11 - sum;
    if (calculatedCheckSum == 10) {
      calculatedCheckSum = 0;
    }
    return checkSum == calculatedCheckSum;
  }

  /**
   * check the VAT identification number, country version for Finland.
   *
   * @param pvatId vat id to check
   * @return true if checksum is ok
   */
  private boolean checkFiVatId(final String pvatId) {
    final int checkSum = pvatId.charAt(9) - '0';
    final int sum =
        (pvatId.charAt(2) - '0') * 7 + (pvatId.charAt(3) - '0') * 9 + (pvatId.charAt(4) - '0') * 10
            + (pvatId.charAt(5) - '0') * 5 + (pvatId.charAt(6) - '0') * 8
            + (pvatId.charAt(7) - '0') * 4 + (pvatId.charAt(8) - '0') * 2;
    final int calculatedCheckSum = MODULO_11 - sum % MODULO_11;
    return checkSum == calculatedCheckSum;
  }

  /**
   * check the VAT identification number, country version for France.
   *
   * @param pvatId vat id to check
   * @return true if checksum is ok
   */
  private boolean checkFrVatId(final String pvatId) {
    final int checkSum = Integer.parseInt(pvatId.substring(2, 4));
    final int sum = Integer.parseInt(pvatId.substring(4));
    final int calculatedCheckSum = (12 + 3 * (sum % MODULO_97)) % MODULO_97;
    return checkSum == calculatedCheckSum;
  }

  /**
   * check the VAT identification number, country version for Greece.
   *
   * @param pvatId vat id to check
   * @return true if checksum is ok
   */
  private boolean checkGrVatId(final String pvatId) {
    final int checkSum = pvatId.charAt(10) - '0';
    final int sum = (pvatId.charAt(2) - '0') * 256 + (pvatId.charAt(3) - '0') * 128
        + (pvatId.charAt(4) - '0') * 64 + (pvatId.charAt(5) - '0') * 32
        + (pvatId.charAt(6) - '0') * 16 + (pvatId.charAt(7) - '0') * 8
        + (pvatId.charAt(8) - '0') * 4 + (pvatId.charAt(9) - '0') * 2;
    int calculatedCheckSum = sum % MODULO_11;
    if (calculatedCheckSum > 9) {
      calculatedCheckSum = 0;
    }
    return checkSum == calculatedCheckSum;
  }

  /**
   * check the VAT identification number, country version for Ireland.
   *
   * @param pvatId vat id to check
   * @return true if checksum is ok
   */
  private boolean checkIeVatId(final String pvatId) {
    final char checkSum = pvatId.charAt(9);
    String vatId = pvatId;
    if (pvatId.charAt(3) >= 'A' && pvatId.charAt(3) <= 'Z') {
      // old id, can be transfered to new form
      vatId = pvatId.substring(0, 2) + "0" + pvatId.substring(4, 9) + pvatId.substring(2, 3)
          + pvatId.substring(9);
    }
    final int sum = (vatId.charAt(2) - '0') * 8 + (vatId.charAt(3) - '0') * 7
        + (vatId.charAt(4) - '0') * 6 + (vatId.charAt(5) - '0') * 5 + (vatId.charAt(6) - '0') * 4
        + (vatId.charAt(7) - '0') * 3 + (vatId.charAt(8) - '0') * 2;
    final int calculatedCheckSum = sum % 23;
    final char calculatedCheckSumCharIe;
    if (calculatedCheckSum == 0) {
      calculatedCheckSumCharIe = 'W';
    } else {
      calculatedCheckSumCharIe = (char) ('A' + calculatedCheckSum - 1);
    }
    return checkSum == calculatedCheckSumCharIe;
  }

  /**
   * check the VAT identification number, country version for Italy.
   *
   * @param pvatId vat id to check
   * @return true if checksum is ok
   */
  private boolean checkItVatId(final String pvatId) {
    final int checkSum = pvatId.charAt(12) - '0';
    final int sum = pvatId.charAt(2) - '0' + squareSum((pvatId.charAt(3) - '0') * 2)
        + pvatId.charAt(4) - '0' + squareSum((pvatId.charAt(5) - '0') * 2) + pvatId.charAt(6) - '0'
        + squareSum((pvatId.charAt(7) - '0') * 2) + pvatId.charAt(8) - '0'
        + squareSum((pvatId.charAt(9) - '0') * 2) + pvatId.charAt(10) - '0'
        + squareSum((pvatId.charAt(11) - '0') * 2);
    final int calculatedCheckSumIt = 10 - sum % 10;
    return checkSum == calculatedCheckSumIt;
  }

  /**
   * check the VAT identification number, country version for Luxembourg.
   *
   * @param pvatId vat id to check
   * @return true if checksum is ok
   */
  private boolean checkLuVatId(final String pvatId) {
    final int numberPart = Integer.parseInt(pvatId.substring(2, 8));
    final int checkSum = Integer.parseInt(pvatId.substring(8));
    final int calculatedCheckSum = numberPart % 89;
    return checkSum == calculatedCheckSum;
  }

  /**
   * check the VAT identification number, country version for Netherlands.
   *
   * @param pvatId vat id to check
   * @return true if checksum is ok
   */
  private boolean checkNlVatId(final String pvatId) {
    final int checkSum = pvatId.charAt(10) - '0';
    final int sum = (pvatId.charAt(2) - '0') * 9 + (pvatId.charAt(3) - '0') * 8
        + (pvatId.charAt(4) - '0') * 7 + (pvatId.charAt(5) - '0') * 6 + (pvatId.charAt(6) - '0') * 5
        + (pvatId.charAt(7) - '0') * 4 + (pvatId.charAt(8) - '0') * 3
        + (pvatId.charAt(9) - '0') * 2;
    final int calculatedCheckSum = sum % MODULO_11;
    return checkSum == calculatedCheckSum;
  }

  /**
   * check the VAT identification number, country version for Norway.
   *
   * @param pvatId vat id to check
   * @return true if checksum is ok
   */
  private boolean checkNoVatId(final String pvatId) {
    final int checkSum = pvatId.charAt(10) - '0';
    final int sum = (pvatId.charAt(2) - '0') * 3 + (pvatId.charAt(3) - '0') * 2
        + (pvatId.charAt(4) - '0') * 7 + (pvatId.charAt(5) - '0') * 6 + (pvatId.charAt(6) - '0') * 5
        + (pvatId.charAt(7) - '0') * 4 + (pvatId.charAt(8) - '0') * 3
        + (pvatId.charAt(9) - '0') * 2;
    final int calculatedCheckSum = MODULO_11 - sum % MODULO_11;
    return checkSum == calculatedCheckSum;
  }

  /**
   * check the VAT identification number, country version for Poland.
   *
   * @param pvatId vat id to check
   * @return true if checksum is ok
   */
  private boolean checkPlVatId(final String pvatId) {
    final int checkSum = pvatId.charAt(11) - '0';
    final int sum = (pvatId.charAt(2) - '0') * 6 + (pvatId.charAt(3) - '0') * 5
        + (pvatId.charAt(4) - '0') * 7 + (pvatId.charAt(5) - '0') * 2 + (pvatId.charAt(6) - '0') * 3
        + (pvatId.charAt(7) - '0') * 4 + (pvatId.charAt(8) - '0') * 5 + (pvatId.charAt(9) - '0') * 6
        + (pvatId.charAt(10) - '0') * 7;
    final int calculatedCheckSumPl = sum % MODULO_11;
    return checkSum == calculatedCheckSumPl;
  }

  /**
   * check the VAT identification number, country version for Portugal.
   *
   * @param pvatId vat id to check
   * @return true if checksum is ok
   */
  private boolean checkPtVatId(final String pvatId) {
    final int checkSum = pvatId.charAt(10) - '0';
    final int sum = (pvatId.charAt(2) - '0') * 9 + (pvatId.charAt(3) - '0') * 8
        + (pvatId.charAt(4) - '0') * 7 + (pvatId.charAt(5) - '0') * 6 + (pvatId.charAt(6) - '0') * 5
        + (pvatId.charAt(7) - '0') * 4 + (pvatId.charAt(8) - '0') * 3
        + (pvatId.charAt(9) - '0') * 2;
    int calculatedCheckSum = MODULO_11 - sum % MODULO_11;
    if (calculatedCheckSum > 9) {
      calculatedCheckSum = 0;
    }
    return checkSum == calculatedCheckSum;
  }

  /**
   * check the VAT identification number, country version for Sweden.
   *
   * @param pvatId vat id to check
   * @return true if checksum is ok
   */
  private boolean checkSeVatId(final String pvatId) {
    final int checkSum = pvatId.charAt(11) - '0';
    final int sum = squareSum((pvatId.charAt(2) - '0') * 2) + pvatId.charAt(3) - '0'
        + squareSum((pvatId.charAt(4) - '0') * 2) + pvatId.charAt(5) - '0'
        + squareSum((pvatId.charAt(6) - '0') * 2) + pvatId.charAt(7) - '0'
        + squareSum((pvatId.charAt(8) - '0') * 2) + pvatId.charAt(9) - '0'
        + squareSum((pvatId.charAt(10) - '0') * 2);
    int calculatedCheckSum = 10 - sum % 10;
    if (calculatedCheckSum == 10) {
      calculatedCheckSum = 0;
    }
    return checkSum == calculatedCheckSum;
  }

  /**
   * check the VAT identification number, country version for Slovenia.
   *
   * @param pvatId vat id to check
   * @return true if checksum is ok
   */
  private boolean checkSiVatId(final String pvatId) {
    boolean checkSumOk;
    final int checkSum = pvatId.charAt(9) - '0';
    final int sum = (pvatId.charAt(2) - '0') * 8 + (pvatId.charAt(3) - '0') * 7
        + (pvatId.charAt(4) - '0') * 6 + (pvatId.charAt(5) - '0') * 5 + (pvatId.charAt(6) - '0') * 4
        + (pvatId.charAt(7) - '0') * 3 + (pvatId.charAt(8) - '0') * 2;
    int calculatedCheckSum = MODULO_11 - sum % MODULO_11;
    if (calculatedCheckSum == 11) {
      checkSumOk = false;
    } else {
      if (calculatedCheckSum == 10) {
        calculatedCheckSum = 0;
      }
      checkSumOk = checkSum == calculatedCheckSum;
    }
    return checkSumOk;
  }

  /**
   * check the VAT identification number, country version for Spain. TODO
   * http://www.pruefziffernberechnung.de/U/USt-IdNr.shtml routine doesn't work for alphabetic
   * checksums, so it's not used at the moment
   *
   * @param pvatId vat id to check
   * @return true if checksum is ok
   */
  private boolean checkEsVatId(final String pvatId) { // NOPMD
    // final boolean checkSumOk = true;
    // if (pvatId.charAt(2) >= 'A' && pvatId.charAt(2) <= 'Z') {
    // final int checkSumEs;
    // if (pvatId.charAt(10) >= 'A' && pvatId.charAt(10) <= 'Z') {
    // checkSumEs = pvatId.charAt(10) - 'A';
    // } else {
    // checkSumEs = pvatId.charAt(10) - '0';
    // }
    // final int sumEs =
    // squareSum((pvatId.charAt(3) - '0') * 2) + pvatId.charAt(4) - '0'
    // + squareSum((pvatId.charAt(5) - '0') * 2) + pvatId.charAt(6) - '0'
    // + squareSum((pvatId.charAt(7) - '0') * 2) + pvatId.charAt(8) - '0'
    // + squareSum((pvatId.charAt(9) - '0') * 2);
    // int calculatedCheckSumEs = 10 - sumEs % 10;
    // if (calculatedCheckSumEs == 10) {
    // calculatedCheckSumEs = 0;
    // }
    // checkSumOk = checkSumEs == calculatedCheckSumEs;
    // } else {
    // final char checkSumEs = pvatId.charAt(10);
    // final int sumEs = Integer.parseInt(pvatId.substring(2, 10));
    // final char calculatedCheckSumEs;
    // switch (sumEs % 23) {
    // case 0:
    // calculatedCheckSumEs = 'T';
    // break;
    // case 1:
    // calculatedCheckSumEs = 'R';
    // break;
    // case 2:
    // calculatedCheckSumEs = 'W';
    // break;
    // case 3:
    // calculatedCheckSumEs = 'A';
    // break;
    // case 4:
    // calculatedCheckSumEs = 'G';
    // break;
    // case 5:
    // calculatedCheckSumEs = 'M';
    // break;
    // case 6:
    // calculatedCheckSumEs = 'Y';
    // break;
    // case 7:
    // calculatedCheckSumEs = 'F';
    // break;
    // case 8:
    // calculatedCheckSumEs = 'P';
    // break;
    // case 9:
    // calculatedCheckSumEs = 'D';
    // break;
    // case 10:
    // calculatedCheckSumEs = 'X';
    // break;
    // case 11:
    // calculatedCheckSumEs = 'B';
    // break;
    // case 12:
    // calculatedCheckSumEs = 'N';
    // break;
    // case 13:
    // calculatedCheckSumEs = 'J';
    // break;
    // case 14:
    // calculatedCheckSumEs = 'Z';
    // break;
    // case 15:
    // calculatedCheckSumEs = 'S';
    // break;
    // case 16:
    // calculatedCheckSumEs = 'Q';
    // break;
    // case 17:
    // calculatedCheckSumEs = 'V';
    // break;
    // case 18:
    // calculatedCheckSumEs = 'H';
    // break;
    // case 19:
    // calculatedCheckSumEs = 'L';
    // break;
    // case 20:
    // calculatedCheckSumEs = 'C';
    // break;
    // case 21:
    // calculatedCheckSumEs = 'K';
    // break;
    // case 22:
    // calculatedCheckSumEs = 'E';
    // break;
    // default:
    // calculatedCheckSumEs = ' ';
    // break;
    // }
    // checkSumOk = calculatedCheckSumEs == checkSumEs;
    // }
    // return checkSumOk;
    return true;
  }

  /**
   * calculate square sum.
   *
   * @param pvalue value to calculate square sum for
   * @return square sum
   */
  private static int squareSum(final int pvalue) {
    int result = 0;
    for (final char valueDigit : String.valueOf(pvalue).toCharArray()) {
      result += Character.digit(valueDigit, 10);
    }
    return result;
  }
}


text:
def store_tokens(access_token, refresh_token):
    import os
    py_dir = os.path.dirname(os.path.realpath(__file__))
    os.chdir(py_dir)
    # storage_file = os.path.join(os.path.dirname(py_dir), 'calendar.dat')
    storage_file = os.path.join(py_dir, 'boxapi' + '.dat')
    STORAGE.put(access_token, refresh_token)
    return

def authorize_client(**kwargs):
    from boxsdk import OAuth2
    oauth = OAuth2(
        client_secret= kwargs.get('client_secret'),
        client_id = kwargs.get('client_id'),
        access_token= kwargs.get('access_token') #DTPwrgGkhZkxKvTWVTT4KBwLwr6ELPvj'
        #store_tokens=store_tokens,
    )

#    auth_url, csrf_token = oauth.get_authorization_url(kwargs.get('redirect_uri'))
#    print auth_url
#    access_token, refresh_token = oauth.authenticate('DTPwrgGkhZkxKvTWVTT4KBwLwr6ELPvj')
    return oauth #auth_url, csrf_token

def instantiate_boxapi_client():
    from boxsdk import Client
    client_secret = 'g4R1o909fgf1PSsa5mLMDslpAwcbfIQl'
    client_id = 'bxccmj5xnkngs8mggxv5ev49zuh80xs9'
    #scope = 'https://app.box.com/services/auth_download_client'
    access_token = 'DTPwrgGkhZkxKvTWVTT4KBwLwr6ELPvj'
    redirect_uri = 'http://localhost:51711' #'urn:ietf:wg:oauth:2.0:oob'
    oauth  = authorize_client(client_secret=client_secret, client_id=client_id,access_token=access_token,redirect_uri=redirect_uri)
    client = Client(oauth)
    return client

def regex_boxapi_ret_fileid(url):
    import re
    regex_boxapi  = re.compile(r'^(https?)?(?:\://)?(.+)\.box\.com/(.+)?(\.?[jpngJPNG]{3,4})?(.*?)?\??(.*?)?$', re.U)
    matches = regex_boxapi.match(url)
    if matches:
        protocol = matches.groups()[0]
        appname  = matches.groups()[1]
        file_id   = {'file_id': matches.groups()[2].split('/')[-1]}
        return file_id
    else:
        pass

def download_boxapi_auth_file(client=None, image_url=None, destpath=None, **kwargs):
    if not kwargs.get('file_id'):
        try:
            file_id = qstring2kvpairs(image_url)['id'][0]
        except IndexError:
            file_id = regex_boxapi_ret_fileid(image_url)
            pass
    else:
        file_id = kwargs.get('file_id').values()
    content = client.file(file_id=file_id).content()
    if not destpath:
        return content
    else:
        with open(destpath,'w') as f:
            f.write(content)
            f.close()
        return destpath

url1 = 'https://capturemrg.box.com/s/cy5fuoata8eiq5n53i5gvwphqfvb061x'
url2 = 'https://relic7.box.com/s/amf29gle65fs87a9ulayi66cacb16aby'

import requests

res = requests.get(url2)
print dir(res)
print res

print requests.head(url2).raw
file_id = regex_boxapi_ret_fileid(url)

if file_id:
    print file_id
client = instantiate_boxapi_client()

print client.file(file_id.values()[0]).content()


text:
package org.dominokit.domino.api.client.annotations.presenter;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Marks a class as a Listener for a {@link org.dominokit.domino.api.shared.extension.DominoEvent}
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Listener {}