text:
<?php
namespace test\cms\routes\Nav;

/**
 * @coversDefaultClass \cms\routes\Nav\Nav
 */
class NavTest extends \test\helpers\cases\RouteController
{

    protected function setUp()
    {
        $testedClass = '\cms\routes\Nav\Nav';

        $mockedMethods = [
            'standardView',//implemented by parent
            'standardAction',//implemented by parent
            'getArguments',//trait implemented
            'routeAuth',//trait implemented
        ];
        $this->testObj = $this->getMockBuilder($testedClass)
                              ->disableOriginalConstructor()
                              ->setMethods($mockedMethods)
                              ->getMock();

        $this->createRoutedMethodsList();
    }

    /**
     * @covers ::Index
     */
    public function testIndex()
    {
        $this->assertContains('index', $this->routedMethods);

        $this->testObj->expects($this->once())
                      ->method('routeAuth');
        $this->testObj->expects($this->once())
                      ->method('standardView')
                      ->with($this->isType('string'));

        $this->testObj->Index();
    }

    /**
     * @covers ::Editing
     */
    public function testEditing()
    {
        $this->assertContains('editing', $this->routedMethods);

        $parameters = ['route' => 'foobar'];

        $this->testObj->expects($this->once())
                      ->method('routeAuth');
        $this->testObj->expects($this->once())
                      ->method('getArguments')
                      ->with($this->isType('array'))
                      ->willReturn($parameters);
        $this->testObj->expects($this->once())
                      ->method('standardView')
                      ->with($this->isType('string'),
                             $this->identicalTo($parameters));

        $this->testObj->Editing();
    }

    /**
     * @covers ::Add
     */
    public function testAdd()
    {
        $this->assertContains('add', $this->routedMethods);

        $this->testObj->expects($this->once())
                      ->method('routeAuth');
        $this->testObj->expects($this->once())
                      ->method('standardAction')
                      ->with($this->isType('string'));

        $this->testObj->Add();
    }

    /**
     * @covers ::Edit
     */
    public function testEdit()
    {
        $this->assertContains('edit', $this->routedMethods);

        $this->testObj->expects($this->once())
                      ->method('routeAuth');
        $this->testObj->expects($this->once())
                      ->method('standardAction')
                      ->with($this->isType('string'));

        $this->testObj->Edit();
    }

    /**
     * @covers ::Delete
     */
    public function testDelete()
    {
        $this->assertContains('delete', $this->routedMethods);

        $this->testObj->expects($this->once())
                      ->method('routeAuth');
        $this->testObj->expects($this->once())
                      ->method('standardAction')
                      ->with($this->isType('string'));

        $this->testObj->Delete();
    }
}


text:
define(['backbone','collections/IncidentRecordList'],function(Backbone, IncidentRecordList){
  'use strict';

  return Backbone.Model.extend({
//    defaults: {
//      title     : '',
//      created   : 0
//    },
    initialize : function() {
      //if (this.isNew()) this.set('created', Date.now());
//      this.records =  new IncidentRecordList;
    }
  });

});

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Reflection;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace YUI.WPF.YUtil
{
    /// <summary>
    /// DPI信息
    /// </summary>
    public class DpiInfo
    {
        /// <summary>
        /// DPI在X轴的缩放
        /// </summary>
        public double DpiXScale => DpiX / 96.0;

        /// <summary>
        /// DPI在Y轴的缩放
        /// </summary>
        public double DpiYScale => DpiY / 96.0;

        /// <summary>
        /// X轴DPI
        /// </summary>
        public int DpiX { get; set; }

        /// <summary>
        /// Y轴DPI
        /// </summary>
        public int DpiY { get; set; }
    }

    /// <summary>
    /// 系统信息辅助类
    /// </summary>
    public static class YSystemHelper
    {
        /// <summary>
        /// 获取系统DPI
        /// </summary>
        /// <returns></returns>
        public static DpiInfo GetDpiInfo()
        {
            var dpiXProperty = typeof(SystemParameters).GetProperty("DpiX", BindingFlags.NonPublic | BindingFlags.Static);
            var dpiYProperty = typeof(SystemParameters).GetProperty("Dpi", BindingFlags.NonPublic | BindingFlags.Static);

            if (dpiXProperty == null || dpiYProperty == null)
                throw new Exception("获取DPI失败");

            var dpiX = (int)dpiXProperty.GetValue(null, null);
            var dpiY = (int)dpiYProperty.GetValue(null, null);

            return new DpiInfo() { DpiX = dpiX, DpiY = dpiY };
        }

        /// <summary>
        /// 获取经过DPI处理过的点
        /// </summary>
        /// <param name="p"></param>
        /// <returns></returns>
        public static Point GetPointDealWithDpi(Point p)
        {
            var dpi = GetDpiInfo();
            return new Point(p.X / dpi.DpiXScale, p.Y / dpi.DpiYScale);
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static ImageSource GetIcon(string fileName)
        {
            var icon = System.Drawing.Icon.ExtractAssociatedIcon(fileName);
            if (icon == null) return null;
            return System.Windows.Interop.Imaging.CreateBitmapSourceFromHIcon(
                icon.Handle,
                new Int32Rect(0, 0, icon.Width, icon.Height),
                BitmapSizeOptions.FromEmptyOptions());
        }
    }
}


text:
import React, {Component, PropTypes} from 'react'
import { reduxForm } from 'redux-form'
import {Button, Input} from "react-bootstrap"
import _ from 'lodash'

export const fields = []

const validate = (values) => {
  const errors = {}

  if (!values.answer) {
    errors.answer = "Answer shouldn't be empty"
  }
  if (!values.author) {
    errors.author = "Author field shouldn't be empty"
  }

  return errors
}

export class NewAnswerForm extends Component {
  static propTypes = {
    handleSubmit: PropTypes.func,
    onSuccessSubmit: PropTypes.func,
    resetForm: PropTypes.func,
    fields: PropTypes.object,
    errors: PropTypes.object,
    footerComponent: PropTypes.element
  }

  defaultProps = {
    fields: {}
  }

  onSubmit(ev) {
    ev.preventDefault()
    this.props.handleSubmit()
    this.props.resetForm()
    this.props.onSuccessSubmit()
  }

  render() {
    const { fields: {answer, author}, errors, footerComponent } = this.props
    return (
      <form onSubmit={this.onSubmit.bind(this)}>
        <Input type="textarea" bsStyle={answer.error ? "error" : 'success'}
               placeholder="Your answer"
               label={answer.error}
               {...answer} />
        <Input type="text" bsStyle={author.error ? "error" : 'success'}
              placeholder="Your name"
              label={author.error}
              {...author} />
        <div className="f-box f-gap--L">
          <Button type="submit" disabled={!_.isEmpty(errors)}>Create Answer</Button>
          {footerComponent}
        </div>
      </form>
    )
  }
}

NewAnswerForm = reduxForm({
  form: 'NewAnswerForm',
  fields: ['answer', 'author'],
  validate
})(NewAnswerForm)

export default NewAnswerForm


text:
'use strict';

const chai = require('chai');
const expect = chai.expect;

const noImportInComponents = require('./no-imports-in-components');
const result = require('../result');

module.exports = function() {
  describe('no-imports-in-components', function() {
    it(`should accept valid '<template>'`, function() {
      const ast = [{
        name: 'template',
        children: [{
          name: 'div',
          children: [{
            name: 'span',
            children: []
          }]
        }]
      }];
      const res = noImportInComponents(ast).build();

      expect(res).to.deep.equal(result.empty().build());
    });

    it(`should reject '<link>' in '<template>'`, function() {
      const ast = [{
        name: 'template',
        children: [{
          name: 'div',
          children: [{
            name: 'link',
            meta: {}
          }]
        }]
      }];
      const res = noImportInComponents(ast).build();

      expect(res.errors.length).to.equal(1);
    });
  });
};


text:
<Type Name="Source+OpenPropertiesDelegate" FullName="Banshee.Sources.Source+OpenPropertiesDelegate">
  <TypeSignature Language="C#" Value="public delegate void Source.OpenPropertiesDelegate();" />
  <TypeSignature Language="ILAsm" Value=".class nested public auto ansi sealed Source/OpenPropertiesDelegate extends System.MulticastDelegate" />
  <AssemblyInfo>
    <AssemblyName>Banshee.Services</AssemblyName>
    <AssemblyVersion>1.3.1.0</AssemblyVersion>
    <AssemblyVersion>1.4.0.0</AssemblyVersion>
    <AssemblyVersion>2.4.0.0</AssemblyVersion>
  </AssemblyInfo>
  <Base>
    <BaseTypeName>System.Delegate</BaseTypeName>
  </Base>
  <Parameters />
  <ReturnValue>
    <ReturnType>System.Void</ReturnType>
  </ReturnValue>
  <Docs>
    <summary>To be added.</summary>
    <remarks>To be added.</remarks>
  </Docs>
</Type>


text:
package org.neo4j.cypher.internal.frontend.v2_3.ast

import org.neo4j.cypher.internal.frontend.v2_3.DummyPosition
import org.neo4j.cypher.internal.frontend.v2_3.symbols._

class ModuloTest extends InfixExpressionTestBase(Modulo(_, _)(DummyPosition(0))) {

  // Infix specializations:
  // 1 % 1 => 0
  // 1 % 1.1 => 1.0
  // 1.1 % 1 => 0.1
  // 1.1 % 1.1 => 0.0

  test("should handle all specializations") {
    testValidTypes(CTInteger, CTInteger)(CTInteger)
    testValidTypes(CTInteger, CTFloat)(CTFloat)
    testValidTypes(CTFloat, CTInteger)(CTFloat)
    testValidTypes(CTFloat, CTFloat)(CTFloat)
  }

  test("should handle combined specializations") {
    testValidTypes(CTFloat | CTInteger, CTFloat | CTInteger)(CTFloat | CTInteger)
  }

  test("should fail type check when adding incompatible") {
    testInvalidApplication(CTInteger, CTBoolean)(
      "Type mismatch: expected Float or Integer but was Boolean"
    )
    testInvalidApplication(CTBoolean, CTInteger)(
      "Type mismatch: expected Float or Integer but was Boolean"
    )
  }
}


text:
using System.Dynamic;

namespace NQuery.Dynamic
{
    internal sealed class DynamicRow : DynamicObject
    {
        private readonly IDictionary<string, object> _values;

        public DynamicRow(IDictionary<string, object> values)
        {
            _values = values;
        }

        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            return _values.TryGetValue(binder.Name, out result);
        }
    }
}


text:
<?php

namespace AppBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class TaskType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('title', TextType::class)
            ->add('comments', TextType::class);
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'AppBundle\Entity\Task'
        ));
    }
}


text:
from django.conf import settings
from django.contrib.auth import get_user_model, update_session_auth_hash
from django.core.paginator import Paginator
from django.db.models import Q
from django.shortcuts import get_object_or_404, redirect, render
from django.urls import reverse
from django.utils.translation import ugettext as _
from django.views.decorators.vary import vary_on_headers

from wagtail.admin import messages
from wagtail.admin.auth import any_permission_required, permission_denied, permission_required
from wagtail.admin.forms.search import SearchForm
from wagtail.core import hooks
from wagtail.core.compat import AUTH_USER_APP_LABEL, AUTH_USER_MODEL_NAME
from wagtail.users.forms import UserCreationForm, UserEditForm
from wagtail.users.utils import user_can_delete_user
from wagtail.utils.loading import get_custom_form

User = get_user_model()

# Typically we would check the permission 'auth.change_user' (and 'auth.add_user' /
# 'auth.delete_user') for user management actions, but this may vary according to
# the AUTH_USER_MODEL setting
add_user_perm = "{0}.add_{1}".format(AUTH_USER_APP_LABEL, AUTH_USER_MODEL_NAME.lower())
change_user_perm = "{0}.change_{1}".format(AUTH_USER_APP_LABEL, AUTH_USER_MODEL_NAME.lower())
delete_user_perm = "{0}.delete_{1}".format(AUTH_USER_APP_LABEL, AUTH_USER_MODEL_NAME.lower())

def get_user_creation_form():
    form_setting = 'WAGTAIL_USER_CREATION_FORM'
    if hasattr(settings, form_setting):
        return get_custom_form(form_setting)
    else:
        return UserCreationForm

def get_user_edit_form():
    form_setting = 'WAGTAIL_USER_EDIT_FORM'
    if hasattr(settings, form_setting):
        return get_custom_form(form_setting)
    else:
        return UserEditForm

@any_permission_required(add_user_perm, change_user_perm, delete_user_perm)
@vary_on_headers('X-Requested-With')
def index(request):
    q = None
    is_searching = False

    model_fields = [f.name for f in User._meta.get_fields()]

    if 'q' in request.GET:
        form = SearchForm(request.GET, placeholder=_("Search users"))
        if form.is_valid():
            q = form.cleaned_data['q']
            is_searching = True
            conditions = Q()

            for term in q.split():
                if 'username' in model_fields:
                    conditions |= Q(username__icontains=term)

                if 'first_name' in model_fields:
                    conditions |= Q(first_name__icontains=term)

                if 'last_name' in model_fields:
                    conditions |= Q(last_name__icontains=term)

                if 'email' in model_fields:
                    conditions |= Q(email__icontains=term)

            users = User.objects.filter(conditions)
    else:
        form = SearchForm(placeholder=_("Search users"))

    if not is_searching:
        users = User.objects.all()

    if 'last_name' in model_fields and 'first_name' in model_fields:
        users = users.order_by('last_name', 'first_name')

    if 'ordering' in request.GET:
        ordering = request.GET['ordering']

        if ordering == 'username':
            users = users.order_by(User.USERNAME_FIELD)
    else:
        ordering = 'name'

    paginator = Paginator(users, per_page=20)
    users = paginator.get_page(request.GET.get('p'))

    if request.is_ajax():
        return render(request, "wagtailusers/users/results.html", {
            'users': users,
            'is_searching': is_searching,
            'query_string': q,
            'ordering': ordering,
        })
    else:
        return render(request, "wagtailusers/users/index.html", {
            'search_form': form,
            'users': users,
            'is_searching': is_searching,
            'ordering': ordering,
            'query_string': q,
        })

@permission_required(add_user_perm)
def create(request):
    for fn in hooks.get_hooks('before_create_user'):
        result = fn(request)
        if hasattr(result, 'status_code'):
            return result
    if request.method == 'POST':
        form = get_user_creation_form()(request.POST, request.FILES)
        if form.is_valid():
            user = form.save()
            messages.success(request, _("User '{0}' created.").format(user), buttons=[
                messages.button(reverse('wagtailusers_users:edit', args=(user.pk,)), _('Edit'))
            ])
            for fn in hooks.get_hooks('after_create_user'):
                result = fn(request, user)
                if hasattr(result, 'status_code'):
                    return result
            return redirect('wagtailusers_users:index')
        else:
            messages.error(request, _("The user could not be created due to errors."))
    else:
        form = get_user_creation_form()()

    return render(request, 'wagtailusers/users/create.html', {
        'form': form,
    })

@permission_required(change_user_perm)
def edit(request, user_id):
    user = get_object_or_404(User, pk=user_id)
    can_delete = user_can_delete_user(request.user, user)
    editing_self = request.user == user

    for fn in hooks.get_hooks('before_edit_user'):
        result = fn(request, user)
        if hasattr(result, 'status_code'):
            return result
    if request.method == 'POST':
        form = get_user_edit_form()(request.POST, request.FILES, instance=user, editing_self=editing_self)
        if form.is_valid():
            user = form.save()

            if user == request.user and 'password1' in form.changed_data:
                # User is changing their own password; need to update their session hash
                update_session_auth_hash(request, user)

            messages.success(request, _("User '{0}' updated.").format(user), buttons=[
                messages.button(reverse('wagtailusers_users:edit', args=(user.pk,)), _('Edit'))
            ])
            for fn in hooks.get_hooks('after_edit_user'):
                result = fn(request, user)
                if hasattr(result, 'status_code'):
                    return result
            return redirect('wagtailusers_users:index')
        else:
            messages.error(request, _("The user could not be saved due to errors."))
    else:
        form = get_user_edit_form()(instance=user, editing_self=editing_self)

    return render(request, 'wagtailusers/users/edit.html', {
        'user': user,
        'form': form,
        'can_delete': can_delete,
    })

@permission_required(delete_user_perm)
def delete(request, user_id):
    user = get_object_or_404(User, pk=user_id)

    if not user_can_delete_user(request.user, user):
        return permission_denied(request)

    for fn in hooks.get_hooks('before_delete_user'):
        result = fn(request, user)
        if hasattr(result, 'status_code'):
            return result
    if request.method == 'POST':
        user.delete()
        messages.success(request, _("User '{0}' deleted.").format(user))
        for fn in hooks.get_hooks('after_delete_user'):
            result = fn(request, user)
            if hasattr(result, 'status_code'):
                return result
        return redirect('wagtailusers_users:index')

    return render(request, "wagtailusers/users/confirm_delete.html", {
        'user': user,
    })


text:
from tsdb import TSDBServer, DictDB
import timeseries as ts

identity = lambda x: x

schema = {
  'pk': {'convert': identity, 'index': None},  #will be indexed anyways
  'ts': {'convert': identity, 'index': None},
  'order': {'convert': int, 'index': 1},
  'blarg': {'convert': int, 'index': 1},
  'useless': {'convert': identity, 'index': None},
  'mean': {'convert': float, 'index': 1},
  'std': {'convert': float, 'index': 1},
  'vp': {'convert': bool, 'index': 1}
}

NUMVPS = 5

#TEST this out by running
#curl http://localhost:9999/ -X POST -d "pk=four&op=insert_ts&ts=[[0.0, 1.0, 4.0], [0.0, 0.0, 4.0]]"

def main():
    # we augment the schema by adding columns for 5 vantage points
    for i in range(NUMVPS):
        schema["d_vp-{}".format(i)] = {'convert': float, 'index': 1}
    db = DictDB(schema, 'pk')
    server = TSDBServer(db)
    server.rest_run()

if __name__=='__main__':
    main()


text:
DuoScripts
==========

Userscripts for Duolingo.com

duolingo-strength-overview.user.js
----------------------------------

A user script allows to overview strength of all skills and lessons of the currently selected language tree.


text:
'use strict';

var React = require('react');
var ReactDOM = require('react-dom');

var PropTypes = React.PropTypes;

var POSITIONS = {
  above: 'above',
  inside: 'inside',
  below: 'below'
};

/**
 * Calls a function when you scroll to the element.
 */
var Waypoint = React.createClass({
  displayName: 'Waypoint',

  propTypes: {
    onEnter: PropTypes.func,
    onLeave: PropTypes.func,
    // threshold is percentage of the height of the visible part of the
    // scrollable ancestor (e.g. 0.1)
    threshold: PropTypes.number
  },

  /**
   * @return {Object}
   */
  getDefaultProps: function getDefaultProps() {
    return {
      threshold: 0,
      onEnter: function onEnter() {},
      onLeave: function onLeave() {}
    };
  },

  componentDidMount: function componentDidMount() {
    this.scrollableAncestor = this._findScrollableAncestor();
    this.scrollableAncestor.addEventListener('scroll', this._handleScroll);
    window.addEventListener('resize', this._handleScroll);
    this._handleScroll();
  },

  componentDidUpdate: function componentDidUpdate() {
    // The element may have moved.
    this._handleScroll();
  },

  componentWillUnmount: function componentWillUnmount() {
    if (this.scrollableAncestor) {
      // At the time of unmounting, the scrollable ancestor might no longer
      // exist. Guarding against this prevents the following error:
      //
      //   Cannot read property 'removeEventListener' of undefined
      this.scrollableAncestor.removeEventListener('scroll', this._handleScroll);
    }
    window.removeEventListener('resize', this._handleScroll);
  },

  /**
   * Traverses up the DOM to find an ancestor container which has an overflow
   * style that allows for scrolling.
   *
   * @return {Object} the closest ancestor element with an overflow style that
   *   allows for scrolling. If none is found, the `window` object is returned
   *   as a fallback.
   */
  _findScrollableAncestor: function _findScrollableAncestor() {
    var node = ReactDOM.findDOMNode(this);

    while (node.parentNode) {
      node = node.parentNode;

      if (node === document) {
        // This particular node does not have a computed style.
        continue;
      }

      var style = window.getComputedStyle(node);
      var overflowY = style.getPropertyValue('overflow-y') || style.getPropertyValue('overflow');

      if (overflowY === 'auto' || overflowY === 'scroll') {
        return node;
      }
    }

    // A scrollable ancestor element was not found, which means that we need to
    // do stuff on window.
    return window;
  },

  /**
   * @param {Object} event the native scroll event coming from the scrollable
   *   ancestor, or resize event coming from the window. Will be undefined if
   *   called by a React lifecyle method
   */
  _handleScroll: function _handleScroll(event) {
    var currentPosition = this._currentPosition();

    if (this._previousPosition === currentPosition) {
      // No change since last trigger
      return;
    }

    if (currentPosition === POSITIONS.inside) {
      this.props.onEnter.call(this, event);
    } else if (this._previousPosition === POSITIONS.inside) {
      this.props.onLeave.call(this, event);
    }

    var isRapidScrollDown = this._previousPosition === POSITIONS.below && currentPosition === POSITIONS.above;
    var isRapidScrollUp = this._previousPosition === POSITIONS.above && currentPosition === POSITIONS.below;
    if (isRapidScrollDown || isRapidScrollUp) {
      // If the scroll event isn't fired often enough to occur while the
      // waypoint was visible, we trigger both callbacks anyway.
      this.props.onEnter.call(this, event);
      this.props.onLeave.call(this, event);
    }

    this._previousPosition = currentPosition;
  },

  /**
   * @param {Object} node
   * @return {Number}
   */
  _distanceToTopOfScrollableAncestor: function _distanceToTopOfScrollableAncestor(node) {
    if (this.scrollableAncestor !== window && !node.offsetParent) {
      throw new Error('The scrollable ancestor of Waypoint needs to have positioning to ' + 'properly determine position of Waypoint (e.g. `position: relative;`)');
    }

    if (node.offsetParent === this.scrollableAncestor || !node.offsetParent) {
      return node.offsetTop;
    } else {
      return node.offsetTop + this._distanceToTopOfScrollableAncestor(node.offsetParent);
    }
  },

  /**
   * @return {boolean} true if scrolled down almost to the end of the scrollable
   *   ancestor element.
   */
  _currentPosition: function _currentPosition() {
    var waypointTop = this._distanceToTopOfScrollableAncestor(ReactDOM.findDOMNode(this));
    var contextHeight = undefined;
    var contextScrollTop = undefined;

    if (this.scrollableAncestor === window) {
      contextHeight = window.innerHeight;
      contextScrollTop = window.pageYOffset;
    } else {
      contextHeight = this.scrollableAncestor.offsetHeight;
      contextScrollTop = this.scrollableAncestor.scrollTop;
    }

    var thresholdPx = contextHeight * this.props.threshold;

    var isBelowTop = contextScrollTop <= waypointTop + thresholdPx;
    if (!isBelowTop) {
      return POSITIONS.above;
    }

    var contextBottom = contextScrollTop + contextHeight;
    var isAboveBottom = contextBottom >= waypointTop - thresholdPx;
    if (!isAboveBottom) {
      return POSITIONS.below;
    }

    return POSITIONS.inside;
  },

  /**
   * @return {Object}
   */
  render: function render() {
    // We need an element that we can locate in the DOM to determine where it is
    // rendered relative to the top of its context.
    return React.createElement('span', { style: { fontSize: 0 } });
  }
});

module.exports = Waypoint;


text:
var TransformStack = _class("TransformStack", {
  props: {
    stack: [],
    pairs: {},
    endOfFirst: 0,
    beginningOfLast: 0
  },

  methods: {
    init: function () {
    },

    add: function (disposition, key, matrix) {
      var pair = this.pairs[key];
      if (pair) {
        pair[1] = matrix;
        return false;
      }
      switch (disposition.toLowerCase()) {
      case 'first':
        pair = [key, matrix];
        this.pairs[key] = pair;
        this.stack.unshift(pair);
        this.endOfFirst++;
        this.beginningOfLast++;
        break;
      case 'afterfirst':
        pair = [key, matrix];
        this.pairs[key] = pair;
        this.stack.splice(this.endOfFirst, 0, pair);
        this.beginningOfLast++;
        break;
      case 'beforelast':
        pair = [key, matrix];
        this.pairs[key] = pair;
        this.stack.splice(this.beginningOfLast, 0, pair);
        this.beginningOfLast++;
        break;
      case 'last':
        pair = [key, matrix];
        this.pairs[key] = pair;
        this.stack.push(pair);
        break;
      default:
        throw new Fashion.ArgumentError("Invalid disposition: " + disposition);
      }
      return true;
    },

    remove: function (key) {

      if (!(key in this.pairs)) return;

      var i = 0;
      for (;;) {
        if (i >= this.stack.length)
          throw new Fashion.NotFound("???"); // should not happen
        if (this.stack[i][0] == key)
          break;
        i++;
      }
      this.stack.splice(i, 1);
      if (i < this.endOfFirst)
        this.endOfFirst--;
      if (i < this.beginningOfLast)
        this.beginningOfLast--;
      delete this.pairs[key];
    },

    get: function () {
      if (this.stack.length == 0)
        return null;
      var matrix = this.stack[0][1];
      for (var i = 1; i < this.stack.length; i++)
        matrix = matrix.multiply(this.stack[i][1]);
      return matrix;
    }
  }
});
/*
 * vim: sts=2 sw=2 ts=2 et
 */


text:
//============================================================================
// Copyright 5AM Solutions, Inc
// Copyright Ekagra Software Technologies Ltd.
// Copyright Guidewire Architecture
// Copyright The Ohio State University Research Foundation
// Copyright SAIC
//
// Distributed under the OSI-approved BSD 3-Clause License.
// See http://ncip.github.com/iso21090/LICENSE.txt for details.
//============================================================================

package gov.nih.nci.iso21090.grid.dto.transform.iso;

import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertNull;
import static junit.framework.Assert.assertTrue;
import gov.nih.nci.iso21090.Int;
import gov.nih.nci.iso21090.Ivl;
import gov.nih.nci.iso21090.grid.dto.transform.AbstractTransformerTestBase;
import gov.nih.nci.iso21090.grid.dto.transform.DtoTransformException;

import org.iso._21090.INT;
import org.iso._21090.IVLINT;
import org.junit.Test;

/**
 * Tests for integer interval transformer.
 */
public class IVLINTTransformerTest extends AbstractTransformerTestBase<IVLINTTransformer, IVLINT, Ivl<Int>> {

    @Override
    public Ivl<Int> makeDtoSimple() {
        Ivl<Int> result = new Ivl<Int>();
        result.setAny(getInt(1));
        result.setHigh(getInt(2));
        result.setHighClosed(Boolean.TRUE);
        result.setLow(getInt(-1));
        result.setLowClosed(Boolean.FALSE);
        result.setWidth(getInt(3));

        return result;
    }

    @Override
    public IVLINT makeXmlSimple() {
        IVLINT result = new IVLINT();
        result.setHigh(getINT(2));
        result.setHighClosed(Boolean.TRUE);
        result.setLow(getINT(-1));
        result.setLowClosed(Boolean.FALSE);
        result.setWidth(getINT(3));

        return result;
    }

    @Override
    public void verifyDtoSimple(Ivl<Int> x) {
        // instead of doing expected.equals(x), we need to account for PO-1054
        Ivl<Int> expected = makeDtoSimple();
        assertNull(x.getAny()); // Proves PO-1054 is still around
        assertEquals(expected.getHigh(), x.getHigh());
        assertEquals(expected.getHighClosed(), x.getHighClosed());
        assertEquals(expected.getLow(), x.getLow());
        assertEquals(expected.getLowClosed(), x.getLowClosed());
        assertEquals(expected.getWidth(), x.getWidth());
    }

    @Override
    public void verifyXmlSimple(IVLINT x) {
        IVLINT expected = makeXmlSimple();
        assertEquals(expected.getHigh().getValue(), x.getHigh().getValue());
        assertEquals(expected.isHighClosed(), x.isHighClosed());
        assertEquals(expected.getLow().getValue(), x.getLow().getValue());
        assertEquals(expected.isLowClosed(), x.isLowClosed());
        assertEquals(((INT) expected.getWidth()).getValue(), ((INT) x.getWidth()).getValue());

    }

    private Int getInt(int value) {
        Int result = new INTTransformerTest().makeDtoSimple();
        result.setValue(value);
        return result;
    }

    private INT getINT(int value) {
        INT result = new INTTransformerTest().makeXmlSimple();
        result.setValue(value);
        return result;
    }

    @Test
    public void testAnyXmlToDto() throws DtoTransformException {
         // set Any with equal high and low
         IVLINT input = new IVLINT();
         input.setWidth(getINT(3));
         input.setHigh(getINT(4));
         input.setLow(getINT(4));
         Ivl<Int> output = IVLINTTransformer.INSTANCE.toDto(input);
         assertEquals(output.getAny(), getInt(4));
         // set Any with some high and no low
         IVLINT input2 = new IVLINT();
         input2.setWidth(getINT(3));
         input2.setHigh(getINT(5));
         Ivl<Int> output2 = IVLINTTransformer.INSTANCE.toDto(input2);
         assertEquals(output2.getAny(), getInt(5));
         // set Any with no high and some low
         IVLINT input3 = new IVLINT();
         input3.setWidth(getINT(3));
         input3.setHigh(getINT(1));
         Ivl<Int> output3 = IVLINTTransformer.INSTANCE.toDto(input3);
         assertEquals(output3.getAny(), getInt(1));
    }

    @Test
    public void testAnyDtoToXml() throws DtoTransformException {
         // set Any with equal high and low
         Ivl<Int> input = new Ivl<Int>();
         input.setAny(getInt(3));
         IVLINT output = IVLINTTransformer.INSTANCE.toXml(input);
         assertEquals(output.getHigh().getValue(), getINT(3).getValue());
         assertEquals(output.getLow().getValue(), getINT(3).getValue());
         assertTrue(output.isHighClosed());
         assertTrue(output.isLowClosed());
         // set Any with some high and low not being equal
         Ivl<Int> input2 = new Ivl<Int>();
         input2.setWidth(getInt(3));
         input2.setHigh(getInt(5));
         input2.setLow(getInt(1));
         input2.setAny(getInt(3));
         IVLINT output2 = IVLINTTransformer.INSTANCE.toXml(input2);
         assertEquals(output2.getHigh().getValue(), getINT(5).getValue());
         assertEquals(output2.getLow().getValue(), getINT(1).getValue());
    }

}


text:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Jint.Native.Object;
using Jint.Parser;
using Jint.Parser.Ast;
using Jint.Runtime;

namespace Jint.Native.Json
{
    public class JsonParser
    {
        private readonly Engine _engine;

        public JsonParser(Engine engine)
        {
            _engine = engine;
        }

        private Extra _extra;

        private int _index; // position in the stream
        private int _length; // length of the stream
        private int _lineNumber;
        private int _lineStart;
        private Location _location;
        private Token _lookahead;
        private string _source;

        private State _state;

        private static bool IsDecimalDigit(char ch)
        {
            return (ch >= '0' && ch <= '9');
        }

        private static bool IsHexDigit(char ch)
        {
            return
                ch >= '0' && ch <= '9' ||
                ch >= 'a' && ch <= 'f' ||
                ch >= 'A' && ch <= 'F'
                ;
        }

        private static bool IsOctalDigit(char ch)
        {
            return ch >= '0' && ch <= '7';
        }

        private static bool IsWhiteSpace(char ch)
        {
            return (ch == ' ')  ||
                   (ch == '\t') ||
                   (ch == '\n') ||
                   (ch == '\r');
        }

        private static bool IsLineTerminator(char ch)
        {
            return (ch == 10) || (ch == 13) || (ch == 0x2028) || (ch == 0x2029);
        }

        private static bool IsNullChar(char ch)
        {
            return ch == 'n'
                || ch == 'u'
                || ch == 'l'
                || ch == 'l'
                ;
        }

        private static bool IsTrueOrFalseChar(char ch)
        {
            return ch == 't'
                || ch == 'r'
                || ch == 'u'
                || ch == 'e'
                || ch == 'f'
                || ch == 'a'
                || ch == 'l'
                || ch == 's'
                ;
        }

        private char ScanHexEscape(char prefix)
        {
            int code = char.MinValue;

            int len = (prefix == 'u') ? 4 : 2;
            for (int i = 0; i < len; ++i)
            {
                if (_index < _length && IsHexDigit(_source.CharCodeAt(_index)))
                {
                    char ch = _source.CharCodeAt(_index++);
                    code = code * 16 + "0123456789abcdef".IndexOf(ch.ToString(), StringComparison.OrdinalIgnoreCase);
                }
                else
                {
                    throw new JavaScriptException(_engine.SyntaxError, string.Format("Expected hexadecimal digit:{0}", _source));
                }
            }
            return (char)code;
        }

        private void SkipWhiteSpace()
        {
            while (_index < _length)
            {
                char ch = _source.CharCodeAt(_index);

                if (IsWhiteSpace(ch))
                {
                    ++_index;
                }
                else
                {
                    break;
                }
            }
        }

        private Token ScanPunctuator()
        {
            int start = _index;
            char code = _source.CharCodeAt(_index);

            switch ((int) code)
            {
                    // Check for most common single-character punctuators.
                case 46: // . dot
                case 40: // ( open bracket
                case 41: // ) close bracket
                case 59: // ; semicolon
                case 44: // , comma
                case 123: // { open curly brace
                case 125: // } close curly brace
                case 91: // [
                case 93: // ]
                case 58: // :
                case 63: // ?
                case 126: // ~
                    ++_index;

                    return new Token
                        {
                            Type = Tokens.Punctuator,
                            Value = code.ToString(),
                            LineNumber = _lineNumber,
                            LineStart = _lineStart,
                            Range = new[] {start, _index}
                        };
            }
            throw new JavaScriptException(_engine.SyntaxError, string.Format(Messages.UnexpectedToken, code));
        }

        private Token ScanNumericLiteral()
        {
            char ch = _source.CharCodeAt(_index);

            int start = _index;
            string number = "";

            // Number start with a -
            if (ch == '-')
            {
                number += _source.CharCodeAt(_index++).ToString();
                ch = _source.CharCodeAt(_index);
            }

            if (ch != '.')
            {
                number += _source.CharCodeAt(_index++).ToString();
                ch = _source.CharCodeAt(_index);

                // Hex number starts with '0x'.
                // Octal number starts with '0'.
                if (number == "0")
                {
                    // decimal number starts with '0' such as '09' is illegal.
                    if (ch > 0 && IsDecimalDigit(ch))
                    {
                        throw new Exception(Messages.UnexpectedToken);
                    }
                }

                while (IsDecimalDigit(_source.CharCodeAt(_index)))
                {
                    number += _source.CharCodeAt(_index++).ToString();
                }
                ch = _source.CharCodeAt(_index);
            }

            if (ch == '.')
            {
                number += _source.CharCodeAt(_index++).ToString();
                while (IsDecimalDigit(_source.CharCodeAt(_index)))
                {
                    number += _source.CharCodeAt(_index++).ToString();
                }
                ch = _source.CharCodeAt(_index);
            }

            if (ch == 'e' || ch == 'E')
            {
                number += _source.CharCodeAt(_index++).ToString();

                ch = _source.CharCodeAt(_index);
                if (ch == '+' || ch == '-')
                {
                    number += _source.CharCodeAt(_index++).ToString();
                }
                if (IsDecimalDigit(_source.CharCodeAt(_index)))
                {
                    while (IsDecimalDigit(_source.CharCodeAt(_index)))
                    {
                        number += _source.CharCodeAt(_index++).ToString();
                    }
                }
                else
                {
                    throw new Exception(Messages.UnexpectedToken);
                }
            }

            return new Token
                {
                    Type = Tokens.Number,
                    Value = Double.Parse(number, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowExponent, CultureInfo.InvariantCulture),
                    LineNumber = _lineNumber,
                    LineStart = _lineStart,
                    Range = new[] {start, _index}
                };
        }

        private Token ScanBooleanLiteral()
        {
            int start = _index;
            string s = "";

            while (IsTrueOrFalseChar(_source.CharCodeAt(_index)))
            {
                s += _source.CharCodeAt(_index++).ToString();
            }

            if (s == "true" || s == "false")
            {
                return new Token
                {
                    Type = Tokens.BooleanLiteral,
                    Value = s == "true",
                    LineNumber = _lineNumber,
                    LineStart = _lineStart,
                    Range = new[] { start, _index }
                };
            }
            else
            {
                throw new JavaScriptException(_engine.SyntaxError, string.Format(Messages.UnexpectedToken, s));
            }
        }

        private Token ScanNullLiteral()
        {
            int start = _index;
            string s = "";

            while (IsNullChar(_source.CharCodeAt(_index)))
            {
                s += _source.CharCodeAt(_index++).ToString();
            }

            if (s == Null.Text)
            {
                return new Token
                {
                    Type = Tokens.NullLiteral,
                    Value = Null.Instance,
                    LineNumber = _lineNumber,
                    LineStart = _lineStart,
                    Range = new[] { start, _index }
                };
            }
            else
            {
                throw new JavaScriptException(_engine.SyntaxError, string.Format(Messages.UnexpectedToken, s));
            }
        }

        private Token ScanStringLiteral()
        {
            string str = "";

            char quote = _source.CharCodeAt(_index);

            int start = _index;
            ++_index;

            while (_index < _length)
            {
                char ch = _source.CharCodeAt(_index++);

                if (ch == quote)
                {
                    quote = char.MinValue;
                    break;
                }

                if (ch <= 31)
                {
                    throw new JavaScriptException(_engine.SyntaxError, string.Format("Invalid character '{0}', position:{1}, string:{2}", ch, _index, _source));
                }

                if (ch == '\\')
                {
                    ch = _source.CharCodeAt(_index++);

                    if (ch > 0 || !IsLineTerminator(ch))
                    {
                        switch (ch)
                        {
                            case 'n':
                                str += '\n';
                                break;
                            case 'r':
                                str += '\r';
                                break;
                            case 't':
                                str += '\t';
                                break;
                            case 'u':
                            case 'x':
                                int restore = _index;
                                char unescaped = ScanHexEscape(ch);
                                if (unescaped > 0)
                                {
                                    str += unescaped.ToString();
                                }
                                else
                                {
                                    _index = restore;
                                    str += ch.ToString();
                                }
                                break;
                            case 'b':
                                str += "\b";
                                break;
                            case 'f':
                                str += "\f";
                                break;
                            case 'v':
                                str += "\x0B";
                                break;

                            default:
                                if (IsOctalDigit(ch))
                                {
                                    int code = "01234567".IndexOf(ch);

                                    if (_index < _length && IsOctalDigit(_source.CharCodeAt(_index)))
                                    {
                                        code = code * 8 + "01234567".IndexOf(_source.CharCodeAt(_index++));

                                        // 3 digits are only allowed when string starts
                                        // with 0, 1, 2, 3
                                        if ("0123".IndexOf(ch) >= 0 &&
                                            _index < _length &&
                                            IsOctalDigit(_source.CharCodeAt(_index)))
                                        {
                                            code = code * 8 + "01234567".IndexOf(_source.CharCodeAt(_index++));
                                        }
                                    }
                                    str += ((char)code).ToString();
                                }
                                else
                                {
                                    str += ch.ToString();
                                }
                                break;
                        }
                    }
                    else
                    {
                        ++_lineNumber;
                        if (ch == '\r' && _source.CharCodeAt(_index) == '\n')
                        {
                            ++_index;
                        }
                    }
                }
                else if (IsLineTerminator(ch))
                {
                    break;
                }
                else
                {
                    str += ch.ToString();
                }
            }

            if (quote != 0)
            {
                throw new JavaScriptException(_engine.SyntaxError, string.Format(Messages.UnexpectedToken, _source));
            }

            return new Token
                {
                    Type = Tokens.String,
                    Value = str,
                    LineNumber = _lineNumber,
                    LineStart = _lineStart,
                    Range = new[] {start, _index}
                };
        }

        private Token Advance()
        {
            SkipWhiteSpace();

            if (_index >= _length)
            {
                return new Token
                    {
                        Type = Tokens.EOF,
                        LineNumber = _lineNumber,
                        LineStart = _lineStart,
                        Range = new[] {_index, _index}
                    };
            }

            char ch = _source.CharCodeAt(_index);

            // Very common: ( and ) and ;
            if (ch == 40 || ch == 41 || ch == 58)
            {
                return ScanPunctuator();
            }

            // String literal starts with double quote (#34).
            // Single quote (#39) are not allowed in JSON.
            if (ch == 34)
            {
                return ScanStringLiteral();
            }

            // Dot (.) char #46 can also start a floating-point number, hence the need
            // to check the next character.
            if (ch == 46)
            {
                if (IsDecimalDigit(_source.CharCodeAt(_index + 1)))
                {
                    return ScanNumericLiteral();
                }
                return ScanPunctuator();
            }

            if (ch == '-') // Negative Number
            {
                if (IsDecimalDigit(_source.CharCodeAt(_index + 1)))
                {
                    return ScanNumericLiteral();
                }
                return ScanPunctuator();
            }

            if (IsDecimalDigit(ch))
            {
                return ScanNumericLiteral();
            }

            if (ch == 't' || ch == 'f')
            {
                return ScanBooleanLiteral();
            }

            if (ch == 'n')
            {
                return ScanNullLiteral();
            }

            return ScanPunctuator();
        }

        private Token CollectToken()
        {
            _location = new Location
                {
                    Start = new Position
                        {
                            Line = _lineNumber,
                            Column = _index - _lineStart
                        }
                };

            Token token = Advance();
            _location.End = new Position
                {
                    Line = _lineNumber,
                    Column = _index - _lineStart
                };

            if (token.Type != Tokens.EOF)
            {
                var range = new[] {token.Range[0], token.Range[1]};
                string value = _source.Slice(token.Range[0], token.Range[1]);
                _extra.Tokens.Add(new Token
                    {
                        Type = token.Type,
                        Value = value,
                        Range = range,
                    });
            }

            return token;
        }

        private Token Lex()
        {
            Token token = _lookahead;
            _index = token.Range[1];
            _lineNumber = token.LineNumber.HasValue ? token.LineNumber.Value : 0;
            _lineStart = token.LineStart;

            _lookahead = (_extra.Tokens != null) ? CollectToken() : Advance();

            _index = token.Range[1];
            _lineNumber = token.LineNumber.HasValue ? token.LineNumber.Value : 0;
            _lineStart = token.LineStart;

            return token;
        }

        private void Peek()
        {
            int pos = _index;
            int line = _lineNumber;
            int start = _lineStart;
            _lookahead = (_extra.Tokens != null) ? CollectToken() : Advance();
            _index = pos;
            _lineNumber = line;
            _lineStart = start;
        }

        private void MarkStart()
        {
            if (_extra.Loc.HasValue)
            {
                _state.MarkerStack.Push(_index - _lineStart);
                _state.MarkerStack.Push(_lineNumber);
            }
            if (_extra.Range != null)
            {
                _state.MarkerStack.Push(_index);
            }
        }

        private T MarkEnd<T>(T node) where T : SyntaxNode
        {
            if (_extra.Range != null)
            {
                node.Range = new[] {_state.MarkerStack.Pop(), _index};
            }
            if (_extra.Loc.HasValue)
            {
                node.Location = new Location
                    {
                        Start = new Position
                            {
                                Line = _state.MarkerStack.Pop(),
                                Column = _state.MarkerStack.Pop()
                            },
                        End = new Position
                            {
                                Line = _lineNumber,
                                Column = _index - _lineStart
                            }
                    };
                PostProcess(node);
            }
            return node;
        }

        public T MarkEndIf<T>(T node) where T : SyntaxNode
        {
            if (node.Range != null || node.Location != null)
            {
                if (_extra.Loc.HasValue)
                {
                    _state.MarkerStack.Pop();
                    _state.MarkerStack.Pop();
                }
                if (_extra.Range != null)
                {
                    _state.MarkerStack.Pop();
                }
            }
            else
            {
                MarkEnd(node);
            }
            return node;
        }

        public SyntaxNode PostProcess(SyntaxNode node)
        {
            if (_extra.Source != null)
            {
                node.Location.Source = _extra.Source;
            }
            return node;
        }

        public ObjectInstance CreateArrayInstance(IEnumerable<JsValue> values)
        {
            var jsArray = _engine.Array.Construct(Arguments.Empty);
            _engine.Array.PrototypeObject.Push(jsArray, values.ToArray());
            return jsArray;
        }

        // Throw an exception

        private void ThrowError(Token token, string messageFormat, params object[] arguments)
        {
            ParserException exception;
            string msg = System.String.Format(messageFormat, arguments);

            if (token.LineNumber.HasValue)
            {
                exception = new ParserException("Line " + token.LineNumber + ": " + msg)
                    {
                        Index = token.Range[0],
                        LineNumber = token.LineNumber.Value,
                        Column = token.Range[0] - _lineStart + 1
                    };
            }
            else
            {
                exception = new ParserException("Line " + _lineNumber + ": " + msg)
                    {
                        Index = _index,
                        LineNumber = _lineNumber,
                        Column = _index - _lineStart + 1
                    };
            }

            exception.Description = msg;
            throw exception;
        }

        // Throw an exception because of the token.

        private void ThrowUnexpected(Token token)
        {
            if (token.Type == Tokens.EOF)
            {
                ThrowError(token, Messages.UnexpectedEOS);
            }

            if (token.Type == Tokens.Number)
            {
                ThrowError(token, Messages.UnexpectedNumber);
            }

            if (token.Type == Tokens.String)
            {
                ThrowError(token, Messages.UnexpectedString);
            }

            // BooleanLiteral, NullLiteral, or Punctuator.
            ThrowError(token, Messages.UnexpectedToken, token.Value as string);
        }

        // Expect the next token to match the specified punctuator.
        // If not, an exception will be thrown.

        private void Expect(string value)
        {
            Token token = Lex();
            if (token.Type != Tokens.Punctuator || !value.Equals(token.Value))
            {
                ThrowUnexpected(token);
            }
        }

        // Return true if the next token matches the specified punctuator.

        private bool Match(string value)
        {
            return _lookahead.Type == Tokens.Punctuator && value.Equals(_lookahead.Value);
        }

        private ObjectInstance ParseJsonArray()
        {
            var elements = new List<JsValue>();

            Expect("[");

            while (!Match("]"))
            {
                if (Match(","))
                {
                    Lex();
                    elements.Add(Null.Instance);
                }
                else
                {
                    elements.Add(ParseJsonValue());

                    if (!Match("]"))
                    {
                        Expect(",");
                    }
                }
            }

            Expect("]");

            return CreateArrayInstance(elements);
        }

        public ObjectInstance ParseJsonObject()
        {
            Expect("{");

            var obj = _engine.Object.Construct(Arguments.Empty);

            while (!Match("}"))
            {
                Tokens type = _lookahead.Type;
                if (type != Tokens.String)
                {
                    ThrowUnexpected(Lex());
                }

                var name = Lex().Value.ToString();
                if (PropertyNameContainsInvalidChar0To31(name))
                {
                    throw new JavaScriptException(_engine.SyntaxError, string.Format("Invalid character in property name '{0}'", name));
                }

                Expect(":");
                var value = ParseJsonValue();

                obj.FastAddProperty(name, value, true, true, true);

                if (!Match("}"))
                {
                    Expect(",");
                }
            }

            Expect("}");

            return obj;
        }

        private bool PropertyNameContainsInvalidChar0To31(string s)
        {
            const int max = 31;

            for (var i = 0; i < s.Length; i++)
            {
                var val = (int)s[i];
                if (val <= max)
                    return true;
            }
            return false;
        }

        /// <summary>
        /// Optimization.
        /// By calling Lex().Value for each type, we parse the token twice.
        /// It was already parsed by the peek() method.
        /// _lookahead.Value already contain the value.
        /// </summary>
        /// <returns></returns>
        private JsValue ParseJsonValue()
        {
            Tokens type = _lookahead.Type;
            MarkStart();

            switch (type)
            {
                case Tokens.NullLiteral:
                    var v = Lex().Value;
                    return Null.Instance;
                case Tokens.BooleanLiteral:
                    return new JsValue((bool)Lex().Value);
                case Tokens.String:
                    return new JsValue((string)Lex().Value);
                case Tokens.Number:
                    return new JsValue((double)Lex().Value);
            }

            if (Match("["))
            {
                return ParseJsonArray();
            }

            if (Match("{"))
            {
                return ParseJsonObject();
            }

            ThrowUnexpected(Lex());

            // can't be reached
            return Null.Instance;
        }

        public JsValue Parse(string code)
        {
            return Parse(code, null);
        }

        public JsValue Parse(string code, ParserOptions options)
        {
            _source = code;
            _index = 0;
            _lineNumber = (_source.Length > 0) ? 1 : 0;
            _lineStart = 0;
            _length = _source.Length;
            _lookahead = null;
            _state = new State
                {
                    AllowIn = true,
                    LabelSet = new HashSet<string>(),
                    InFunctionBody = false,
                    InIteration = false,
                    InSwitch = false,
                    LastCommentStart = -1,
                    MarkerStack = new Stack<int>()
                };

            _extra = new Extra
                {
                    Range = new int[0],
                    Loc = 0,

                };

            if (options != null)
            {
                if (!System.String.IsNullOrEmpty(options.Source))
                {
                    _extra.Source = options.Source;
                }

                if (options.Tokens)
                {
                    _extra.Tokens = new List<Token>();
                }

            }

            try
            {
                MarkStart();
                Peek();
                JsValue jsv = ParseJsonValue();

                Peek();
                Tokens type = _lookahead.Type;
                object value = _lookahead.Value;
                if(_lookahead.Type != Tokens.EOF)
                {
                    throw new JavaScriptException(_engine.SyntaxError, string.Format("Unexpected {0} {1}", _lookahead.Type, _lookahead.Value));
                }
                return jsv;
            }
            finally
            {
                _extra = new Extra();
            }
        }

        private class Extra
        {
            public int? Loc;
            public int[] Range;
            public string Source;

            public List<Token> Tokens;
        }

        private enum Tokens
        {
            NullLiteral,
            BooleanLiteral,
            String,
            Number,
            Punctuator,
            EOF,
        };

        class Token
        {
            public Tokens Type;
            public object Value;
            public int[] Range;
            public int? LineNumber;
            public int LineStart;
        }

        static class Messages
        {
            public const string UnexpectedToken = "Unexpected token {0}";
            public const string UnexpectedNumber = "Unexpected number";
            public const string UnexpectedString = "Unexpected string";
            public const string UnexpectedEOS = "Unexpected end of input";
        };
    }
}


text:
* Added method Response.getHeader

## 0.3.2
* Method to() does not overwrite query parameters

## 0.3.1
* Skipped due-to release troubles

## 0.3.0
* Generics cleanup. It's no longer extensible, but the code is at least understandable.

## 0.2.1
* Case sensitive header methods added

## 0.2.0
* Response headers wrapped in a special object
* Breaks backward compatibility, but since the verion 0.1.0 was not announced yet, I think it's not a problem.

## 0.1.0
* Better handling of nulls in response validation
* Generics in ResponseValidator made more generic
* Response can be accessed

## 0.0.8
* Fixed setHeaders function

## 0.0.7
* Changed behavior of RequestBuilder.withHeader and withQueryParameter. Now it overwrites previous values instead of adding.


text:
    <lx-select ng-model="vm.selectModel.selectedPeopleSections"
               lx-choices="vm.selectSections"
               lx-label="Lorem Ipsum"
               lx-multiple="true">
        <lx-select-selected>
            {{ $selectedSubheader }} - {{ $selected.name }}
        </lx-select-selected>

        <lx-select-choices>
            {{ $choice.name }}
        </lx-select-choices>
    </lx-select>


text:
package com.thoughtworks.go.server.dao;

import com.ibatis.sqlmap.client.SqlMapClient;
import com.rits.cloning.Cloner;
import com.thoughtworks.go.config.GoConfigDao;
import com.thoughtworks.go.database.Database;
import com.thoughtworks.go.domain.Pipeline;
import com.thoughtworks.go.domain.PipelineState;
import com.thoughtworks.go.domain.Stage;
import com.thoughtworks.go.domain.StageIdentifier;
import com.thoughtworks.go.server.cache.GoCache;
import com.thoughtworks.go.server.domain.StageStatusListener;
import com.thoughtworks.go.server.persistence.MaterialRepository;
import com.thoughtworks.go.server.transaction.SqlMapClientDaoSupport;
import com.thoughtworks.go.server.transaction.TransactionSynchronizationManager;
import com.thoughtworks.go.server.transaction.TransactionTemplate;
import com.thoughtworks.go.util.SystemEnvironment;
import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.PropertyProjection;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionSynchronizationAdapter;

import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

@SuppressWarnings({"ALL"})
@Component
public class PipelineStateDao extends SqlMapClientDaoSupport implements StageStatusListener {
    private static final Logger LOGGER = Logger.getLogger(PipelineStateDao.class);
    private StageDao stageDao;
    private MaterialRepository materialRepository;
    private EnvironmentVariableDao environmentVariableDao;
    private GoCache goCache;
    private TransactionTemplate transactionTemplate;
    private TransactionSynchronizationManager transactionSynchronizationManager;
    private final SystemEnvironment systemEnvironment;
    private final GoConfigDao configFileDao;
    private SessionFactory sessionFactory;
    private final Cloner cloner = new Cloner();
    private final ReadWriteLock activePipelineRWLock = new ReentrantReadWriteLock();
    private final Lock activePipelineReadLock = activePipelineRWLock.readLock();
    private final Lock activePipelineWriteLock = activePipelineRWLock.writeLock();

    @Autowired
    public PipelineStateDao(StageDao stageDao, MaterialRepository materialRepository, GoCache goCache, EnvironmentVariableDao environmentVariableDao, TransactionTemplate transactionTemplate,
                            SqlMapClient sqlMapClient, TransactionSynchronizationManager transactionSynchronizationManager, SystemEnvironment systemEnvironment,
                            GoConfigDao configFileDao, Database database, SessionFactory sessionFactory) {
        super(goCache, sqlMapClient, systemEnvironment, database);
        this.stageDao = stageDao;
        this.materialRepository = materialRepository;
        this.goCache = goCache;
        this.environmentVariableDao = environmentVariableDao;
        this.transactionTemplate = transactionTemplate;
        this.transactionSynchronizationManager = transactionSynchronizationManager;
        this.systemEnvironment = systemEnvironment;
        this.configFileDao = configFileDao;
        this.sessionFactory = sessionFactory;
    }

    public void stageStatusChanged(Stage stage) {
        clearLockedPipelineStateCache(stage.getIdentifier().getPipelineName());
    }

    public void lockPipeline(final Pipeline pipeline) {
        synchronized (pipelineLockStateCacheKey(pipeline.getName())) {
            transactionTemplate.execute(new TransactionCallbackWithoutResult() {
                @Override
                protected void doInTransactionWithoutResult(TransactionStatus status) {
                    transactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
                        @Override
                        public void afterCommit() {
                            clearLockedPipelineStateCache(pipeline.getName());
                        }
                    });
                    final String pipelineName = pipeline.getName();
                    PipelineState fromCache = pipelineStateFor(pipelineName);
                    if (fromCache != null && fromCache.isLocked() && !pipeline.getIdentifier().equals(fromCache.getLockedBy().pipelineIdentifier())) {
                        throw new RuntimeException(String.format("Pipeline '%s' is already locked (counter = %s)", pipelineName, fromCache.getLockedBy().getPipelineCounter()));
                    }
                    PipelineState toBeSaved = null;
                    if (fromCache == null) {
                        toBeSaved = new PipelineState(pipelineName);
                    } else {
                        toBeSaved = (PipelineState) sessionFactory.getCurrentSession().load(PipelineState.class, fromCache.getId());
                    }
                    toBeSaved.lock(pipeline.getId());
                    sessionFactory.getCurrentSession().saveOrUpdate(toBeSaved);
                }
            });
        }
    }

    private void clearLockedPipelineStateCache(String pipelineName) {
        goCache.remove(pipelineLockStateCacheKey(pipelineName));
    }

    public void unlockPipeline(final String pipelineName) {
        synchronized (pipelineLockStateCacheKey(pipelineName)) {
            transactionTemplate.execute(new TransactionCallbackWithoutResult() {
                @Override
                protected void doInTransactionWithoutResult(TransactionStatus status) {
                    transactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
                        @Override
                        public void afterCommit() {
                            clearLockedPipelineStateCache(pipelineName);
                        }
                    });

                    final String cacheKey = pipelineLockStateCacheKey(pipelineName);
                    PipelineState fromCache = pipelineStateFor(pipelineName);
                    PipelineState toBeSaved = null;
                    if (fromCache == null) {
                        toBeSaved = new PipelineState(pipelineName);
                    } else {
                        toBeSaved = (PipelineState) sessionFactory.getCurrentSession().load(PipelineState.class, fromCache.getId());
                    }
                    toBeSaved.unlock();
                    sessionFactory.getCurrentSession().saveOrUpdate(toBeSaved);
                }
            });
        }
    }

    public PipelineState pipelineStateFor(String pipelineName) {
        String cacheKey = pipelineLockStateCacheKey(pipelineName);
        PipelineState pipelineState = (PipelineState) goCache.get(cacheKey);
        if (pipelineState != null) {
            return pipelineState.equals(PipelineState.NOT_LOCKED) ? null : pipelineState;
        }
        synchronized (cacheKey) {
            pipelineState = (PipelineState) goCache.get(cacheKey);
            if (pipelineState != null) {
                return pipelineState.equals(PipelineState.NOT_LOCKED) ? null : pipelineState;
            }

            pipelineState = (PipelineState) transactionTemplate.execute(new TransactionCallback() {
                @Override
                public Object doInTransaction(TransactionStatus transactionStatus) {
                    return sessionFactory.getCurrentSession()
                            .createCriteria(PipelineState.class)
                            .add(Restrictions.eq("pipelineName", pipelineName))
                            .setCacheable(false).uniqueResult();
                }
            });

            if (pipelineState != null && pipelineState.isLocked()) {
                StageIdentifier lockedBy = (StageIdentifier) getSqlMapClientTemplate().queryForObject("lockedPipeline", pipelineState.getLockedByPipelineId());
                pipelineState.setLockedBy(lockedBy);
            }
            goCache.put(cacheKey, pipelineState == null ? PipelineState.NOT_LOCKED : pipelineState);
            return pipelineState;
        }
    }

    String pipelineLockStateCacheKey(String pipelineName) {
        // we intern() it because we synchronize on the returned String
        return (PipelineStateDao.class.getName() + "_lockedPipeline_" + pipelineName.toLowerCase()).intern();
    }

    public List<String> lockedPipelines() {
        return (List<String>) transactionTemplate.execute(new TransactionCallback() {
            @Override
            public Object doInTransaction(TransactionStatus status) {
                PropertyProjection pipelineName = Projections.property("pipelineName");
                Criteria criteria = sessionFactory.getCurrentSession().createCriteria(PipelineState.class).setProjection(pipelineName).add(
                        Restrictions.eq("locked", true));
                criteria.setCacheable(false);
                List<String> list = criteria.list();
                return list;
            }
        });
    }
}


text:
class MedicalhistoryBaseinfoCtrl {
    constructor($scope, $stateParams, _, medicalService,toastr,$cookies,$rootScope,$state,$uibModal) {
        var self = $scope;
        $scope.user = JSON.parse($cookies.get('user'));
        // 从父级中拿到选中的tab
        // console.log(self.$parent)
        self.parentTabList=self.$parent.parentTabList;//历史tab页
        self.activeTab = self.$parent.activeTab;
        // console.log(self.activeTab)
        self.goNextTab=false;
        // console.log($stateParams)
        // self.newMedicalRecord = $cookies.get('newCreateMedicalRecord') ? JSON.parse($cookies.get('newCreateMedicalRecord')) : null;
         	// console.log($cookies.get('newCreateMedicalRecord')) //新建病历需要更改数据
        self.baseInfo={
            "caseId": "",
            "patientName": "",
            "sex": "M",
            "dob": "",
            "nation": "",
            "patientHeight": '',
            "patientWeight": '',
            "bmi": "",
            "education": "",
            "job": "",
            "mobilePhone": "",
            "telePhone": "",
            "receptDoctor": "",
            "address": {
                "province":'',
                "city":'-1',
                "country":'-1'
            }
        };
        self.address = {
            province: [{regionCode: "-1", regionName: '---省---' }],
            city: [{ regionCode: "-1", regionName: '---市---' }],
            country: [{ regionCode: "-1", regionName: '---县---'}]
        };
        self.nationArr = [];
        self.educationArr = [];
        self.jobArr = [];
        self.baseInfoCopy=angular.copy(self.baseInfo)
        //初始化数据
        if(!(self.activeTab.params&&self.activeTab.params.pid&&self.activeTab.params.rid)){
            return false;
        }
        self.init=()=>{

            //初始化数据
        medicalService.getPatientMedicalPatientInfo(self.activeTab.params.pid,self.activeTab.params.rid).then(function (res) {
            self.baseInfo = res.data;
            // console.log(self.baseInfo)
            if(self.baseInfo){
                if(self.baseInfo.education!=''){
                     self.baseInfo.education=parseInt(self.baseInfo.education);
                     if(!self.baseInfo.education){
                       self.baseInfo.education='';
                     }
                }
              if(self.baseInfo.nation!=''){
                   self.baseInfo.nation=parseInt(self.baseInfo.nation);
                   if(!self.baseInfo.nation){
                       self.baseInfo.nation='';
                   }
              }
              if(self.baseInfo.job!=''){
                self.baseInfo.job=parseInt(self.baseInfo.job);
                if(!self.baseInfo.job){
                   self.baseInfo.job='';
               }
              }
              if(parseInt(self.baseInfo.receptDoctor)>0){
                self.baseInfo.receptDoctor=parseInt(self.baseInfo.receptDoctor);
                if(!self.baseInfo.receptDoctor){
                   self.baseInfo.receptDoctor='';
               }
              }else{
                //   console.log('zouleme')
                  let isEmployeeId=false;
                _.each(self.itemArr,function(a){
                    if(a.employeeId==$scope.user.employeeId){
                        self.baseInfo.receptDoctor=parseInt($scope.user.employeeId);
                        isEmployeeId=true;
                    }
                 })
                 if(!isEmployeeId){
                    self.baseInfo.receptDoctor=''
                 }
               }
           //    self.baseInfo.receptDoctor=parseInt(self.baseInfo.receptDoctor);
              if(self.baseInfo.patientWeight||self.baseInfo.patientHeight){
                  self.baseInfo.bmi=(parseInt(self.baseInfo.patientWeight)/parseInt(self.baseInfo.patientHeight)*2).toFixed(2);
              }else{
                  self.baseInfo.patientWeight='';
                      self.baseInfo.patientHeight=''
              }
               if(self.baseInfo.address.city&&self.baseInfo.address.city!='-1'){
                   medicalService.getRegionByParentCode(self.baseInfo.address.province).then(function (res) {
                       self.address.city = res.data;
                       if(self.baseInfo.address.country&&self.baseInfo.address.country!='-1'){
                           medicalService.getRegionByParentCode(self.baseInfo.address.city).then(function (res) {
                               self.address.country = res.data;
                           })
                       }
                   })
               }
               if(!self.baseInfo.address.city){
                   self.baseInfo.address.city='-1'
               }
               if(!self.baseInfo.address.province){
                   self.baseInfo.address.province=''
               }
               if(!self.baseInfo.address.country){
                   self.baseInfo.address.country='-1'
               }
           }
           self.baseInfoCopy=angular.copy(self.baseInfo)
       })
        }

        self.$watch('baseInfo.patientWeight',function(){
        	if(self.baseInfo&&self.baseInfo.patientWeight&&self.baseInfo.patientHeight){
        	let bmis=(parseInt(self.baseInfo.patientWeight)/(parseInt(self.baseInfo.patientHeight)*parseInt(self.baseInfo.patientHeight)/10000)).toFixed(2)
                self.baseInfo.bmi=bmis==NaN?0:bmis;
        	}else{
                self.baseInfo.bmi = '';
        	}
        })
         self.$watch('baseInfo.patientHeight',function(){
           if(self.baseInfo&&self.baseInfo.patientWeight&&self.baseInfo.patientHeight){
        	let bmis=(parseInt(self.baseInfo.patientWeight)/(parseInt(self.baseInfo.patientHeight)*parseInt(self.baseInfo.patientHeight)/10000)).toFixed(2)
                self.baseInfo.bmi=bmis==NaN?0:bmis;
        	}else{
                self.baseInfo.bmi = '';
        	}
        })
        var numbers=0;
        //路由相关变化
        $rootScope.$on('$stateChangeStart', (event, toState, toParams, fromState, fromParams) => {
            // console.log('切换路由')
            // console.log(JSON.parse($cookies.get('historytabs')))
            if(fromState.name=='dryad.medicalhistory.details.baseinfo'){
                numbers++;
                if(numbers==1){
                    _.each($scope.tabData,function(a,i){
                        if(a.route==toState.name){
                            self.baseInfoCopy2=angular.copy(self.baseInfo);
                            self.baseInfoCopy2.dob=moment(self.baseInfoCopy2.dob).format('YYYY-MM-DD');
                            self.baseInfoCopy.dob=moment(self.baseInfoCopy.dob).format('YYYY-MM-DD');
                             delete self.baseInfoCopy.bmi;delete self.baseInfoCopy2.bmi;
                           if(!(JSON.stringify(self.baseInfoCopy)==JSON.stringify(self.baseInfoCopy2))){
                                // console.log(self.goNextTab)
                                if(self.goNextTab==false){
                                event.preventDefault();
                                //删除确认弹窗
                                 $scope.deleteModal('当前病历还未保存,是否保存?',i)

                               }
                            }

                        }
                    })
                }

            }
        });
       //删除确认弹窗
       $scope.deleteModal = (patinet,index) => {
        $uibModal.open({
            animation: true,
            backdrop: 'static',
            template: require('../html/medicalhistory-delete.html'),
            controller: 'delectMedicalhistoryCtrl',
            controllerAs: 'delectMedicalhistoryCtrlVm',
            size: 'width-400',
            resolve: {
                items: function() {
                    return {
                        title: '提示',
                        patinet:patinet || null,
                        content: patinet
                    };
                },
                deleteModalCtrl: ($q, $ocLazyLoad) => {
                    const deferred = $q.defer();
                    require.ensure(['./medicalhistory-delete-controller'], (require) => {
                        const ctrl = require('./medicalhistory-delete-controller')(require('../../../common/module'));
                        $ocLazyLoad.inject({
                            name: 'dryadApp',
                            files: [ctrl]
                        });
                        deferred.resolve(ctrl);
                    }, './common/delete-modal-ctrl');
                    return deferred.promise;
                }
            }
        }).result.then(function(result) {
           if(result=='noSave'){
            $state.go($scope.tabData[index]['route'], $scope.tabData[index]['params']);
           }else if(result=='cancle'){
            $('.ng-isolate-scope .tab-container ul li:eq('+index+')').removeClass("active");
            $('.medical-base-info table tr:eq(0) td:eq(1) input').focus()
            $scope.tabData.active=0;
            numbers=0;
           }else if(result=='save'){
            self.saveData(true,index);
           }
        });
    };
        //获取民族字典列表
        medicalService.getNation().then(function (res) {
            self.nationArr = res.data;
        })
        //获取教育程度字典列表
        medicalService.getEducation().then(function (res) {
            self.educationArr = res.data;
        })
        //获取职业列表
        medicalService.getJob().then(function (res) {
            self.jobArr = res.data;
        })
        //获取省份字典列表
        medicalService.getProvinceList().then(function (res) {
            // console.log(res.data)
            self.address.province = res.data
            self.address.provinceCopy=angular.copy(self.address.province);
            // self.address.province.unshift({regionCode:"-1", regionName: '---省---' })
        })
        //省份首拼过滤
        $scope.serchProvinceForm=(value)=>{
            // console.log(value)
            var reg = /([\u4e00-\u9fa5]+)/g; //匹配中文
                if (value == '' || value == null) {
                    self.address.province = self.address.provinceCopy;
                } else {
                    self.address.province = [];
                    if (reg.test(value)) { //中文
                        self.address.provinceCopy.forEach(function(item) {
                            if (item.regionName.indexOf(value) > -1) {
                                self.address.province.push(item);
                            }
                        });
                    } else { //字母、数字、特殊字符
                        value = value.toUpperCase();
                        // console.log(value)
                        for (var i = 0, len = self.address.provinceCopy.length; i < len; i++) {
                            self.address.provinceCopy[i].regionShortnameEn=self.address.provinceCopy[i].regionShortnameEn.toUpperCase();
                            if (self.address.provinceCopy[i].regionShortnameEn.indexOf(value) > -1) {
                                self.address.province.push(self.address.provinceCopy[i]);
                            }
                        }
                        // console.log(self.address.province)
                    }
            }
        }
        //根据parentCode获取区域列表
        self.onSearchProvince = function(val) {
           medicalService.getRegionByParentCode(val.regionCode).then(function (res) {
               self.address.city = res.data
            //    self.address.city.unshift({ regionCode: "-1", regionName: '---市---' })
               self.address.country=[{ regionCode: "-1", regionName: '---县---'}];
            //    self.address.country.unshift({ regionCode: "-1", regionName: '---县---' })
               self.baseInfo.address.province =val.regionCode;
               self.baseInfo.address.city = self.address.city[0].regionCode;
               self.baseInfo.address.country =self.address.country[0].regionCode;

           })
        }
        //根据parentCode获取区域列表 region
        self.onSearchCity = function(val) {
            medicalService.getRegionByParentCode(val.regionCode).then(function (res) {
                if(res.data.length){
                    self.address.country = res.data
                }else{
                    self.address.country= [{ regionCode: "-1", regionName: '---县---'}];
                }
                self.baseInfo.address.city = val.regionCode;
                self.baseInfo.address.country = self.address.country[0].regionCode;
            })
        }
        self.onSearchRegion = function (val) {
            self.baseInfo.address.country = val.regionCode;
        }
		//获取医生列表
        self.getDoctorList = function(val) {
           medicalService.getDoctorList().then(function (res) {
               self.itemArr = res.data;
               self.init()

           })
        }
        $scope.isTrue=false
        self.getDoctorList();

        //输入框数字校验
        $scope.numCheck = (value,flag) => {
            if(flag == 1){ //身高、体重
                let reg = /^\d+.?\d*$/ig;
                if(!reg.test($scope.baseInfo[value])){
                    $scope.baseInfo[value] = '';
                }
            }else if(flag == 2){ //固定电话
                let regs = /^[\d{3,4}]-[\d{6,8}]/g;
                if(!regs.test($scope.baseInfo[value])){
                    toastr.warning('固定电话格式不正确!',null,3000);
                    $scope.baseInfo[value] = '';
                }
            }

        };

        //检查必填项
        var  checkRequired = function () {
			if($scope.baseInfo.patientName==''||$scope.baseInfo.patientName==null){
				return false
			}
			if($scope.baseInfo.mobilePhone==''||$scope.baseInfo.mobilePhone==null||($scope.baseInfo.mobilePhone+'').length!=11){
				return false
			}
			if($scope.baseInfo.receptDoctor==''||$scope.baseInfo.receptDoctor==null){
				return false
			}
			if($scope.baseInfo.address.city=='-1'){
				return false
			}
			if($scope.baseInfo.address.province=='-1'){
				return false
            }
            if(self.address.country.length>1&&$scope.baseInfo.address.country=='-1'){
				return false
            }
            if($scope.baseInfo.patientHeight==''){
				return false
			}
			if($scope.baseInfo.patientWeight==''){
				return false
            }
            return true;
        }
        $("[data-toggle='tooltip']").tooltip();
        self.saveData = function (flag,index) {
            if(!checkRequired()){
                toastr.warning('请填写完整的病历基本信息', null, 3000);
                if(flag){
                    $('.ng-isolate-scope .tab-container ul li:eq('+index+')').removeClass("active");
                    $('.medical-base-info table tr:eq(0) td:eq(1) input').focus()
                    $scope.tabData.active=0;
                    numbers=0;
                }
                return false;
        	}
            //校验手机号
            let regPhoneNo = /^1\d{10}$/;
            if(!$scope.baseInfo.mobilePhone || !regPhoneNo.test($scope.baseInfo.mobilePhone)){
                toastr.warning('请输入正确的手机号!',null,3000);
                if(flag){
                    $('.ng-isolate-scope .tab-container ul li:eq('+index+')').removeClass("active");
                    $('.medical-base-info table tr:eq(0) td:eq(1) input').focus()
                    $scope.tabData.active=0;
                    numbers=0;
                }
	           return false;
            }
            let patientHeight =/^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/;
            if(!$scope.baseInfo.patientHeight || !patientHeight.test($scope.baseInfo.patientHeight)){
                toastr.warning('请输入正确的身高!',null,3000);
                if(flag){
                    $('.ng-isolate-scope .tab-container ul li:eq('+index+')').removeClass("active");
                    $('.medical-base-info table tr:eq(0) td:eq(1) input').focus()
                    $scope.tabData.active=0;
                    numbers=0;
                }
	                return false;
            }
            let patientWeight = /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/;
            if(!$scope.baseInfo.patientWeight || !patientWeight.test($scope.baseInfo.patientWeight)){
                toastr.warning('请输入正确的体重!',null,3000);
                if(flag){
                    $('.ng-isolate-scope .tab-container ul li:eq('+index+')').removeClass("active");
                    $('.medical-base-info table tr:eq(0) td:eq(1) input').focus()
                    $scope.tabData.active=0;
                    numbers=0;
                }
	                return false;
            }
                self.baseInfo.medicalRecordId=$stateParams.rid;
        		self.baseInfo.dob=moment(self.baseInfo.dob).format("YYYY-MM-DD");
	        	self.baseInfo.doctorId=self.user.employeeId;
	        	self.baseInfo.patientId=$stateParams.pid;
                self.baseInfo.bmi=Number(self.baseInfo.bmi);
                self.baseInfo.firstVisit=self.activeTab.data.firstVisit;
	        	medicalService.savePatientMedicalPatientInfo(self.baseInfo).then(function(data){
	        		if(data.status==200){
                        self.goNextTab=true;
                        toastr.success('保存成功', null, 3000);
	        			self.$emit('index',{index:1,item:self.baseInfo});
                        //更新cookies中新建病历的标识值
                         $cookies.put('createAccount',0);
                         if(flag){
                            $state.go($scope.tabData[index]['route'], $scope.tabData[index]['params']);
                         }
	        		}else{
        				toastr.error(data.errorMessage, null, 3000);
        		}
        	})
        	}
    }
}
MedicalhistoryBaseinfoCtrl.$inject = ['$scope', '$stateParams', '_', 'medicalService','toastr','$cookies','$rootScope','$state','$uibModal']
module.exports = (ngMold) => {
    require.ensure(['../service/medical-history-service'], (require) => {
        require('../service/medical-history-service')(ngMold);
    }, './medicalHistory/medical-history-service');
    ngMold.controller('medicalhistoryBaseinfoCtrl', MedicalhistoryBaseinfoCtrl);
}


text:
using System;
using System.ComponentModel;
using System.Linq;
using System.Runtime.Serialization;
using System.Timers;
using Lithnet.Miiserver.Client;

namespace Lithnet.Miiserver.AutoSync
{
    [DataContract(Name = "interval-trigger")]
    [Description(TypeDescription)]
    public class IntervalExecutionTrigger : MAExecutionTrigger
    {
        private const string TypeDescription = "Repeating interval";

        private Timer checkTimer;

        [DataMember(Name = "interval")]
        public TimeSpan Interval { get; set; }

        [DataMember(Name = "run-profile-name")]
        public string RunProfileName { get; set; }

        [DataMember(Name = "exclusive")]
        public bool Exclusive { get; set; }

        [DataMember(Name = "run-immediate")]
        public bool RunImmediate { get; set; }

        private void CheckTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            this.Log($"Timer elapsed. Next event at {DateTime.Now.Add(this.Interval)}");
            ExecutionParameters p = new ExecutionParameters();
            p.RunProfileName = this.RunProfileName;
            p.Exclusive = this.Exclusive;
            p.RunImmediate = this.RunImmediate;
            this.Fire(p);
        }

        public override void Start(string managementAgentName)
        {
            if (this.Disabled)
            {
                this.Log("Trigger disabled");
                return;
            }

            this.ManagementAgentName = managementAgentName;

            if (this.RunProfileName == null)
            {
                this.LogError("Ignoring interval trigger with no run profile name");
                return;
            }

            this.Log($"Starting interval timer for {this.RunProfileName} at {this.Interval}. First event will occur at {DateTime.Now.Add(this.Interval)}");

            this.checkTimer = new Timer
            {
                Interval = this.Interval.TotalMilliseconds,
                AutoReset = true
            };

            this.checkTimer.Elapsed += this.CheckTimer_Elapsed;

            this.checkTimer.Start();
        }

        public override void Stop()
        {
            if (this.checkTimer == null)
            {
                return;
            }

            if (this.checkTimer.Enabled)
            {
                this.checkTimer.Stop();
            }
        }

        public override string DisplayName => $"{this.Type} - {this.Description}";

        public override string Type => TypeDescription;

        public override string Description => $"{this.DisabledText}{this.RunProfileName} every {this.Interval}";

        public override string ToString()
        {
            return $"{this.DisplayName}";
        }

        public static bool CanCreateForMA(ManagementAgent ma)
        {
            return true;
        }

        public IntervalExecutionTrigger(ManagementAgent ma)
        {
            this.RunProfileName = ma.RunProfiles?.Select(t => t.Key).FirstOrDefault();
            this.Interval = new TimeSpan(0, 15, 0);
        }
    }
}


text:
package org.openengsb.itests.exam;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openengsb.core.api.context.ContextCurrentService;
import org.openengsb.core.api.context.ContextHolder;
import org.openengsb.core.workflow.api.RuleBaseException;
import org.openengsb.core.workflow.api.RuleManager;
import org.openengsb.core.workflow.api.TaskboxService;
import org.openengsb.core.workflow.api.WorkflowService;
import org.openengsb.core.workflow.api.model.ProcessBag;
import org.openengsb.core.workflow.api.model.RuleBaseElementId;
import org.openengsb.core.workflow.api.model.RuleBaseElementType;
import org.openengsb.core.workflow.api.model.Task;
import org.openengsb.itests.util.AbstractPreConfiguredExamTestHelper;
import org.ops4j.pax.exam.junit.PaxExam;

@RunWith(PaxExam.class)
public class TaskboxIT extends AbstractPreConfiguredExamTestHelper {
    private TaskboxService taskboxService;
    private WorkflowService workflowService;
    private RuleManager ruleManager;

    @Before
    public void setUp() throws Exception {
        ContextCurrentService contextService = getOsgiService(ContextCurrentService.class);
        if (!contextService.getAvailableContexts().contains("it-taskbox")) {
            contextService.createContext("it-taskbox");
        }
        ContextHolder.get().setCurrentContextId("it-taskbox");
        ruleManager = getOsgiService(RuleManager.class);
        workflowService = getOsgiService(WorkflowService.class);
        taskboxService = getOsgiService(TaskboxService.class);
    }

    @Test
    public void testHumanTaskFlow_shouldWorkWithGivenProcessBag() throws Exception {
        addWorkflow("TaskDemoWorkflow");

        assertThat(taskboxService.getOpenTasks().size(), is(0));
        authenticateAsAdmin();

        ProcessBag processBag = new ProcessBag();
        processBag.addProperty("test", "test");
        Map<String, Object> parameterMap = new HashMap<String, Object>();
        parameterMap.put("processBag", processBag);

        assertThat(taskboxService.getOpenTasks().size(), is(0));

        workflowService.startFlowWithParameters("TaskDemoWorkflow", parameterMap);
        assertNotNull(processBag.getProcessId());
        assertThat(taskboxService.getOpenTasks().size(), is(1));

        Task task = taskboxService.getOpenTasks().get(0);
        assertEquals(task.getProcessId(), processBag.getProcessId());
        assertEquals(task.getProperty("test"), "test");
        assertEquals(task.getTaskType(), "demo");
        assertNotNull(task.getTaskId());
        taskboxService.finishTask(task);
        assertTrue(taskboxService.getOpenTasks().size() == 0);
    }

    @Test
    public void testHumanTaskFlow_shouldCreateOwnProcessBag() throws Exception {
        addWorkflow("TaskDemoWorkflow");

        assertThat(taskboxService.getOpenTasks().size(), is(0));
        authenticateAsAdmin();
        workflowService.startFlow("TaskDemoWorkflow");
        assertThat(taskboxService.getOpenTasks().size(), is(1));

        Task task = taskboxService.getOpenTasks().get(0);
        assertNotNull(task.getProcessId());
        assertNotNull(task.getTaskId());

        taskboxService.finishTask(task);
        assertThat(taskboxService.getOpenTasks().size(), is(0));
    }

    @Test
    public void testHumanTaskFlow_shouldHandleMultipleTasks() throws Exception {
        addWorkflow("TaskDemoWorkflow");

        assertThat(taskboxService.getOpenTasks().size(), is(0));
        authenticateAsAdmin();

        long id = workflowService.startFlow("TaskDemoWorkflow");
        long id2 = workflowService.startFlow("TaskDemoWorkflow");

        assertThat(taskboxService.getOpenTasks().size(), is(2));

        assertEquals(taskboxService.getTasksForProcessId(String.valueOf(id)).size(), 1);
        assertEquals(taskboxService.getTasksForProcessId(String.valueOf(id2)).size(), 1);

        Task task1 = taskboxService.getTasksForProcessId(String.valueOf(id)).get(0);
        Task task2 = taskboxService.getTasksForProcessId(String.valueOf(id2)).get(0);

        taskboxService.finishTask(task1);
        assertThat(taskboxService.getOpenTasks().size(), is(1));
        assertEquals(taskboxService.getTasksForProcessId(String.valueOf(id)).size(), 0);
        assertEquals(taskboxService.getTasksForProcessId(String.valueOf(id2)).size(), 1);

        taskboxService.finishTask(task2);
        assertThat(taskboxService.getOpenTasks().size(), is(0));
        assertEquals(taskboxService.getTasksForProcessId(String.valueOf(id2)).size(), 0);
    }

    @Test
    public void testCompleteWorkflow_humanInteractionShouldReplaceValues() throws Exception {
        addWorkflow("HIDemoWorkflow");
        authenticateAsAdmin();
        workflowService.startFlow("HIDemoWorkflow");
        Task task = taskboxService.getOpenTasks().get(0);
        Date date = new Date();
        task.addOrReplaceProperty("test", date);
        assertEquals("step1", task.getTaskType());

        task.setName("test");
        taskboxService.updateTask(task);
        task = taskboxService.getOpenTasks().get(0);
        assertEquals("test", task.getName());

        taskboxService.finishTask(task);

        task = taskboxService.getOpenTasks().get(0);
        assertEquals(date, task.getProperty("test"));
        assertEquals("step2", task.getTaskType());

        taskboxService.finishTask(task);
        assertThat(taskboxService.getOpenTasks().size(), is(0));
    }

    private void addWorkflow(String workflow) throws IOException, RuleBaseException {
        if (ruleManager.get(new RuleBaseElementId(RuleBaseElementType.Process, workflow)) == null) {
            InputStream is =
                getClass().getClassLoader().getResourceAsStream("rulebase/org/openengsb/" + workflow + ".rf");
            String testWorkflow = IOUtils.toString(is);
            RuleBaseElementId id = new RuleBaseElementId(RuleBaseElementType.Process, workflow);
            ruleManager.add(id, testWorkflow);
            IOUtils.closeQuietly(is);
        }
    }
}