text:
package net.imagej.ops.imagemoments.normalizedcentralmoments;

import net.imagej.ops.Op;
import net.imagej.ops.Ops;
import net.imagej.ops.imagemoments.AbstractImageMomentOp;
import net.imagej.ops.special.chain.RTs;
import net.imagej.ops.special.function.UnaryFunctionOp;
import net.imglib2.IterableInterval;
import net.imglib2.type.numeric.RealType;

import org.scijava.plugin.Plugin;

/**
 * {@link Op} to calculate the {@code imageMoments.normalizedCentralMoment20}.
 *
 * @author Daniel Seebacher (University of Konstanz)
 * @author Christian Dietz (University of Konstanz)
 * @param <I> input type
 * @param <O> output type
 */
@Plugin(type = Ops.ImageMoments.NormalizedCentralMoment20.class,
	label = "Image Moment: NormalizedCentralMoment20")
public class DefaultNormalizedCentralMoment20<I extends RealType<I>, O extends RealType<O>>
	extends AbstractImageMomentOp<I, O> implements Ops.ImageMoments.NormalizedCentralMoment20
{

	private UnaryFunctionOp<IterableInterval<I>, O> centralMoment00Func;

	private UnaryFunctionOp<IterableInterval<I>, O> centralMoment20Func;

	@Override
	public void initialize() {
		centralMoment00Func = RTs.function(ops(), Ops.ImageMoments.CentralMoment00.class, in());
		centralMoment20Func = RTs.function(ops(), Ops.ImageMoments.CentralMoment20.class, in());
	}

	@Override
	public void compute(final IterableInterval<I> input, final O output) {
		double centralMoment00 = centralMoment00Func.calculate(input).getRealDouble();
		double centralMoment20 = centralMoment20Func.calculate(input).getRealDouble();

		output.setReal(centralMoment20 /
			Math.pow(centralMoment00, 1 + ((2 + 0) / 2)));
	}
}


text:
/**
 * Optionally use this function as an HTML DOM onkeypress handler, and it will
 * attempt to listen for the enter key being pressed and submit the form at that
 * time.
 * @param {String} form_id
 * @return {Boolean}
 */
function drupalgap_form_onkeypress(form_id) {
  try {
    var event = window.event;
    var charCode = event.which || event.keyCode;
    if (charCode != '13') { return; }
    $('#' + form_id + ' button.dg_form_submit_button').click();
    event.preventDefault();
    return false;
  }
  catch (error) { console.log('drupalgap_form_onkeypress - ' + error); }
}

/**
 * Handles a drupalgap form's submit button click.
 * @param {String} form_id
 * @return {*}
 */
function _drupalgap_form_submit(form_id) {
  try {
    // Load the form from local storage.
    var form = drupalgap_form_local_storage_load(form_id);
    if (!form) {
      var msg = '_drupalgap_form_submit - ' + t('failed to load form') + ': ' +
        form_id;
      drupalgap_alert(msg);
      return false;
    }

    // Assemble the form state values.
    var form_state = drupalgap_form_state_values_assemble(form);

    // Clear out previous form errors.
    drupalgap.form_errors = {};

    // Build the form validation wrapper function.
    var form_validation = function() {
      try {

        // Call the form's validate function(s), if any.
        $.each(form.validate, function(index, function_name) {
            var fn = window[function_name];
            fn.apply(null, Array.prototype.slice.call([form, form_state]));
        });

        // Call drupalgap form's api validate.
        _drupalgap_form_validate(form, form_state);

        // If there were validation errors, show the form errors and stop the
        // form submission. Otherwise submit the form.
        if (!jQuery.isEmptyObject(drupalgap.form_errors)) {
          var html = '';
          $.each(drupalgap.form_errors, function(name, message) {
              html += message + '\n\n';
          });
          drupalgap_alert(html);
        }
        else { form_submission(); }
      }
      catch (error) {
        console.log('_drupalgap_form_submit - form_validation - ' + error);
      }
    };

    // Build the form submission wrapper function.
    var form_submission = function() {
      try {
        // Call the form's submit function(s), if any.
        $.each(form.submit, function(index, function_name) {
            var fn = window[function_name];
            fn.apply(null, Array.prototype.slice.call([form, form_state]));
        });
        // Remove the form from local storage.
        // @todo - we can't do this here because often times a form's submit
        // handler makes asynchronous calls (i.e. user login) and although the
        // form validated, server side may say the input was invalid, so the
        // user will still be on the form, except we already removed the form.
        //drupalgap_form_local_storage_delete(form_id);
      }
      catch (error) {
        console.log('_drupalgap_form_submit - form_submission - ' + error);
      }
    };

    // Get ready to validate and submit the form, but first...

    // If this is an entity form, and there is an image field on the form, we
    // need to asynchronously process the image field, then continue onward
    // with normal form validation and submission.
    if (form.entity_type &&
      image_fields_present_on_entity_type(form.entity_type, form.bundle)
    ) {
      _image_field_form_process(form, form_state, {
          success: form_validation
      });
    }
    else {
      // There were no image fields on the form, proceed normally with form
      // validation, which will in turn process the submission if there are no
      // validation errors.
      form_validation();
    }
  }
  catch (error) { console.log('_drupalgap_form_submit - ' + error); }
}

/**
 * An internal function used by the DrupalGap forms api to validate all the
 * elements on a form.
 * @param {Object} form
 * @param {Object} form_state
 */
function _drupalgap_form_validate(form, form_state) {
  try {
    $.each(form.elements, function(name, element) {
        if (name == 'submit') { return; }
        if (element.required) {
          var valid = true;
          var value = null;
          if (element.is_field) {
            value = form_state.values[name][language_default()][0];
          }
          else { value = form_state.values[name]; }
          // Check for empty values.
          if (empty(value)) { valid = false; }
          // Validate a required select list.
          else if (
            element.type == 'select' && element.required && value == ''
          ) { valid = false; }
          else if (element.type == 'checkboxes' && element.required) {
            var has_value = false;
            $.each(form_state.values[name], function(key, value) {
                if (value) { has_value = true; return false; }
            });
            if (!has_value) { valid = false; }
          }
          if (!valid) {
            var field_title = name;
            if (element.title) { field_title = element.title; }
            drupalgap_form_set_error(
              name,
              t('The') + ' ' + field_title + ' ' + t('field is required') + '.'
            );
          }
        }
    });
  }
  catch (error) { console.log('_drupalgap_form_validate - ' + error); }
}

/**
 * Given a form, this function iterates over the form's elements and assembles
 * each element and value and places them into the form state's values. This
 * is similar to $form_state['values'] in Drupal.
 * @param {Object} form
 * @return {Object}
 */
function drupalgap_form_state_values_assemble(form) {
  try {
    var lng = language_default();
    var form_state = {'values': {}};
    $.each(form.elements, function(name, element) {
      if (name == 'submit') { return; } // Always skip the form 'submit'.
      var id = null;
      if (element.is_field) {
        form_state.values[name] = {};
        form_state.values[name][lng] = {};
        var allowed_values = element.field_info_field.cardinality;
        if (allowed_values == -1) {
          allowed_values = 1; // Convert unlimited value field to one for now...
        }
        for (var delta = 0; delta < allowed_values; delta++) {
          id = drupalgap_form_get_element_id(name, form.id, lng, delta);
          form_state.values[name][lng][delta] =
            _drupalgap_form_state_values_assemble_get_element_value(
              id,
              element
            );
        }
      }
      else {
        id = drupalgap_form_get_element_id(name, form.id);
        form_state.values[name] =
          _drupalgap_form_state_values_assemble_get_element_value(
            id,
            element
          );
      }
    });
    // Attach the form state to drupalgap.form_states keyed by the form id.
    drupalgap.form_states[form.id] = form_state;
    return form_state;
  }
  catch (error) {
    console.log('drupalgap_form_state_values_assemble - ' + error);
  }
}

/**
 *
 * @param {String} id
 * @param {Object} element
 * @return {String|Number}
 */
function _drupalgap_form_state_values_assemble_get_element_value(id, element) {
  try {
    // If a value_callback is specified on the element, call that function to
    // retrieve the element's value. Ohterwise, we'll use the default techniques
    // implemented to extract a value for the form state.
    if (element.value_callback && function_exists(element.value_callback)) {
      var fn = window[element.value_callback];
      return fn(id, element);
    }
    // Figure out the value, depending on the element type.
    var value = null;
    var selector = '';
    if (element.type == 'radios') {
      selector = 'input:radio[name="' + id + '"]:checked';
    }
    else { selector = '#' + id; }
    switch (element.type) {
      case 'checkbox':
        var _checkbox = $(selector);
        if ($(_checkbox).is(':checked')) { value = 1; }
        else { value = 0; }
        break;
      case 'checkboxes':
        // Iterate over each option, and see if it is checked, then pop it onto
        // the value array. It's possible for values to be updated dynamically
        // by a developer (i.e. through a pageshow handler), so it isn't safe to
        // look at the options in local storage. Instead we'll directly iterate
        // over the element option(s) in the DOM.
        value = {};
        var options = $('label[for="' + id + '"]').siblings('.ui-checkbox');
        $.each(options, function(index, option) {
            var checkbox = $(option).children('input');
            var _value = $(checkbox).attr('value');
            if ($(checkbox).is(':checked')) { value[_value] = _value; }
            else { value[_value] = 0; }
        });
        break;
      case 'list_boolean':
        var _checkbox = $(selector);
        if ($(_checkbox).is(':checked')) { value = $(_checkbox).attr('on'); }
        else { value = $(_checkbox).attr('off'); }
        break;
      case 'list_text':
        // Radio buttons.
        if (
          element.field_info_instance &&
          element.field_info_instance.widget.type == 'options_buttons'
        ) {
          selector = 'input:radio[name="' + id + '"]:checked';
        }
        break;
    }
    if (value === null) { value = $(selector).val(); }
    if (typeof value === 'undefined') { value = null; }
    return value;
  }
  catch (error) {
    console.log(
      '_drupalgap_form_state_values_assemble_get_element_value - ' +
      error
    );
  }
}

/**
 * When a service call results in an error, this function is used to extract the
 * request's response form errors into a human readble string and returns it. If
 * there are no form errors, it will return false.
 * @param {Object} form
 * @param {Object} form_state
 * @param {Object} xhr
 * @param {String} status
 * @param {String} message
 * @return {String|Boolean}
 */
function _drupalgap_form_submit_response_errors(form, form_state, xhr, status,
  message) {
  try {
    var responseText = JSON.parse(xhr.responseText);
    if (typeof responseText === 'object' && responseText.form_errors) {
      var msg = '';
      $.each(responseText.form_errors, function(element_name, error_msg) {
          if (error_msg != '') {
            // The element name tends to come back weird, e.g.
            // "field_art_type][und", so let's trim anything at and after
            // the first "]".
            var pos = element_name.indexOf(']');
            if (pos != -1) {
              element_name = element_name.substr(0, pos);
            }
            var label = element_name;
            if (
              form.elements[element_name] &&
              form.elements[element_name].title
            ) { label = form.elements[element_name].title; }
            msg += $('<div>(' + label + ') - ' +
              error_msg + '</div>').text() + '\n';
          }
      });
      if (msg != '') { return msg; }
    }
    return false;
  }
  catch (error) {
    console.log('_drupalgap_form_submit_response_errors - ' + error);
  }
}

redpajama_set_name: RedPajamaGithub


text:
import { expectDayRange } from './ViewRenderUtils'

describe('validRange rendering', function() {

  describe('with hardcoded start constraint', function() {

    describe('when month view', function() {
      pushOptions({
        defaultView: 'month',
        defaultDate: '2017-06-01',
        validRange: { start: '2017-06-07' }
      })

      it('does not render days before', function() {
        initCalendar()
        expectDayRange('2017-06-07', '2017-07-09')
      })
    })

    describe('when in week view', function() {
      pushOptions({
        defaultView: 'agendaWeek',
        defaultDate: '2017-06-08',
        validRange: { start: '2017-06-06' }
      })

      it('does not render days before', function() {
        initCalendar()
        expectDayRange('2017-06-06', '2017-06-11')
      })
    })
  })

  describe('with hardcoded end constraint', function() {

    describe('when month view', function() {
      pushOptions({
        defaultView: 'month',
        defaultDate: '2017-06-01',
        validRange: { end: '2017-06-07' }
      })

      it('does not render days on or after', function() {
        initCalendar()
        expectDayRange('2017-05-28', '2017-06-07')
      })
    })

    describe('when in week view', function() {
      pushOptions({
        defaultView: 'agendaWeek',
        defaultDate: '2017-06-08',
        validRange: { end: '2017-06-06' }
      })

      it('does not render days on or after', function() {
        initCalendar()
        expectDayRange('2017-06-04', '2017-06-06')
      })
    })
  })
})


text:
<!-- Mention the issues this PR addresses -->

### Checks

- [ ] Ran `yarn test-build`
- [ ] Updated relevant documentations
- [ ] Updated matching config options in altair-static

### Changes proposed in this pull request:
<!-- Describe the changes being introduced in this PR -->


text:
layout: post
section-type: post
title: 'Church IO'
category: launch
tags: [ 'ChMS' ]
---
[Church IO](https://church.io) is a community who feels church software is expensive.  These developers write open source software for churches.  [One Body](https://github.com/churchio/onebody) is a members portal where church members get together and socialize.

Andrew Gauger is a recent addition to the team.  He writes features that have been sitting in the issues list, waiting patiently.  The most recent update to OneBody is for messages to be sent to a group subset.

To facilitate this, the existing Message model gained a new association: has and belongs to many members.  The main challenge was the current Message model had two duties, sending group mail and private mail (one member, not necessarily in a group).

{% highlight ruby %}
  has_and_belongs_to_many :members,
                          class_name: 'Person',
                          join_table: :members_messages,
                          association_foreign_key: member_id
{% endhighlight %}

With the assicaition in place, Rails knows to query the join table members_messages which will have a column for member_id and message_id.  If there are 3 records where the message_id equals 1, then message 1 has three members.

members_messages

      message_id
      member_id

       1
       5

       1
       7

       1
       10

To create the join table, the rails scaffold generator can be invoked with
`rails generate migration CreateMessagesMembersJoinTable messages members`

Since the functionality of the Message needs to handle dispatch to the entire group by default, the behavior only changes when at least one member exists.  To determine if the Message is destined for a particular member, two scopes were created:

{% highlight ruby %}
    scope(:for_user, lambda do |user|
      joins(:members).where('members_messages.member_id = ? OR messages.person_id = ?', user.id, user.id).uniq
    end)
    scope :for_whole_group, -> { includes(:members).where(members_messages: { :message_id => nil }) }
{% endhighlight %}

Join the discussion at [Github](https://github.com/churchio/onebody/pull/592 "Adds feature to send group messages to subset")


text:
namespace iroha {
namespace opt {
namespace sched {

SchedBlock::SchedBlock(BB *bb) : bb_(bb) {
}

SchedBlockSet::SchedBlockSet(BBSet *bbs) {
  for (BB *bb : bbs->bbs_) {
    fbs_.push_back(new SchedBlock(bb));
  }
}

SchedBlockSet::~SchedBlockSet() {
  STLDeleteValues(&fbs_);
}

}  // namespace sched
}  // namespace opt
}  // namespace iroha


text:
package apiserver

import (
	"testing"

	"k8s.io/kubernetes/pkg/api"
	"k8s.io/kubernetes/pkg/api/meta"
	"k8s.io/kubernetes/pkg/api/unversioned"

	"github.com/emicklei/go-restful"
)

func TestScopeNamingGenerateLink(t *testing.T) {
	selfLinker := &setTestSelfLinker{
		t:           t,
		expectedSet: "/api/v1/namespaces/other/services/foo",
		name:        "foo",
		namespace:   "other",
	}
	s := scopeNaming{
		meta.RESTScopeNamespace,
		selfLinker,
		func(name, namespace string) string {
			return "/api/v1/namespaces/" + namespace + "/services/" + name
		},
		true,
	}
	service := &api.Service{
		ObjectMeta: api.ObjectMeta{
			Name:      "foo",
			Namespace: "other",
		},
		TypeMeta: unversioned.TypeMeta{
			Kind: "Service",
		},
	}
	_, _, err := s.GenerateLink(&restful.Request{}, service)
	if err != nil {
		t.Errorf("Unexpected error %v", err)
	}
}


text:
package org.datagr4m.drawing.model.items.zones;

import java.awt.Polygon;
import java.util.ArrayList;
import java.util.Deque;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Logger;
import org.datagr4m.drawing.model.bounds.RectangleBounds;
import org.datagr4m.drawing.model.items.IBoundedItem;
import org.datagr4m.drawing.model.items.listeners.IItemListener;
import org.jzy3d.maths.Coord2d;
import org.jzy3d.maths.Coord3d;
import org.jzy3d.maths.algorithms.convexhull.GrahamScan;
import org.jzy3d.maths.algorithms.interpolation.algorithms.BernsteinInterpolator;

public class ZoneModel implements IZoneModel, IItemListener {
    protected String label;
    protected Object data;
    protected Polygon geometry;
    protected List<IBoundedItem> children;
    protected boolean geometryDirty = false;

    public ZoneModel(String label, Object data) {
        this(label, data, new ArrayList<IBoundedItem>());
    }

    public ZoneModel(String label, Object data, List<IBoundedItem> children) {
        this.label = label;
        this.data = data;
        this.children = children;
    }

    @Override
    public void itemBoundsChanged(IBoundedItem item) {

    }

    @Override
    public void itemPositionChanged(IBoundedItem item) {
        Logger.getLogger(ZoneModel.class).info(item + " changed");
        if (children.contains(item))
            geometryDirty = true;
    }

    @Override
    public void dispose() {
        for (IBoundedItem item : children)
            unregister(item);
    }

    protected void register(IBoundedItem item) {
        item.addItemListener(this);
    }

    protected void unregister(IBoundedItem item) {
        item.removeItemListener(this);
    }

    /* */

    @Override
    public void addChild(IBoundedItem child) {
        addChild(child, true);
    }

    @Override
    public void addChild(IBoundedItem child, boolean updateGeometry) {
        children.add(child);
        register(child);
        geometryDirty = true;
        if (updateGeometry)
            updateGeometry();
    }

    @Override
    public void addChildren(List<IBoundedItem> children) {
        for (IBoundedItem item : children)
            addChild(item, false);
        updateGeometry();
    }

    @Override
    public List<IBoundedItem> getChildren() {
        return children;
    }

    @Override
    public void setLabel(String label) {
        this.label = label;
    }

    @Override
    public String getLabel() {
        return label;
    }

    @Override
    public Object getData() {
        return data;
    }

    @Override
    public Polygon getGeometry() {
        if (geometryDirty)
            updateGeometry();
        return geometry;
    }

    @Override
    public Object getData(IBoundedItem item) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public IBoundedItem getItem(Object data) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public IBoundedItem getChildWithLabel(String label) {
        // TODO Auto-generated method stub
        return null;
    }

    /* */

    @Override
	public void updateGeometry() {
        Logger.getLogger(ZoneModel.class).info("update zone");
        geometry = computeGeometry();
        geometryDirty = false;
    }

    protected Polygon computeGeometry() {
        Polygon p = new Polygon();
        /*
         * if (children.size() == 0) { return p; } else if (children.size() ==
         * 1) { return p; // p.addPoint((int)children.get(0).getX(),
         * (int)pt.getY()); } else
         */{
            // GrahamScan
        	 Coord2d[] points = new Coord2d[children.size() * 4];

            int k = 0;
            for (IBoundedItem item : children) {

                RectangleBounds r = item.getAbsoluteRectangleBounds();// .enlarge(30,
                                                                      // 30);

                points[k++] = r.getBottomLeftCorner();
                points[k++] = r.getBottomRightCorner();
                points[k++] = r.getTopLeftCorner();
                points[k++] = r.getTopRightCorner();
            }

            // Compute convex hull
            GrahamScan gs = new GrahamScan();
            Deque<Coord2d> deque = gs.getConvexHull(points);

            Iterator<Coord2d> it = deque.iterator();

            if (interpolate) {
                List<Coord3d> in = new ArrayList<Coord3d>();
                while (it.hasNext()) {
                    Coord2d pt = it.next();
                    // Logger.getLogger(ZoneModel.class).info(pt);
                    in.add(new Coord3d(pt.getX(), pt.getY(), 0));
                }

                // Interpolation
                BernsteinInterpolator bi = new BernsteinInterpolator();
                List<Coord3d> pts = bi.interpolate(in, 10);
                for(Coord3d pt: pts){
                    p.addPoint((int) pt.x, (int) pt.y);
                }
            } else {

                // Logger.getLogger(ZoneModel.class).info(children.size() + " items in zone model");
                while (it.hasNext()) {
                    Coord2d pt = it.next();
                    // Logger.getLogger(ZoneModel.class).info(pt);
                    p.addPoint((int) pt.getX(), (int) pt.getY());
                }
            }
            return p;
        }
    }

    protected boolean interpolate = true;

    @Override
	public String toString() {
        return "ZoneModel " + label + " : " + children;
    }
}


text:
"""The tests for the mFi switch platform."""
import unittest
import unittest.mock as mock

import homeassistant.components.mfi.switch as mfi
import homeassistant.components.switch as switch
from homeassistant.setup import setup_component

from tests.common import get_test_home_assistant

class TestMfiSwitchSetup(unittest.TestCase):
    """Test the mFi switch."""

    PLATFORM = mfi
    COMPONENT = switch
    THING = "switch"
    GOOD_CONFIG = {
        "switch": {
            "platform": "mfi",
            "host": "foo",
            "port": 6123,
            "username": "user",
            "password": "pass",
            "ssl": True,
            "verify_ssl": True,
        }
    }

    def setup_method(self, method):
        """Set up things to be run when tests are started."""
        self.hass = get_test_home_assistant()

    def teardown_method(self, method):
        """Stop everything that was started."""
        self.hass.stop()

    @mock.patch("homeassistant.components.mfi.switch.MFiClient")
    @mock.patch("homeassistant.components.mfi.switch.MfiSwitch")
    def test_setup_adds_proper_devices(self, mock_switch, mock_client):
        """Test if setup adds devices."""
        ports = {
            i: mock.MagicMock(model=model) for i, model in enumerate(mfi.SWITCH_MODELS)
        }
        ports["bad"] = mock.MagicMock(model="notaswitch")
        print(ports["bad"].model)
        mock_client.return_value.get_devices.return_value = [
            mock.MagicMock(ports=ports)
        ]
        assert setup_component(self.hass, switch.DOMAIN, self.GOOD_CONFIG)
        for ident, port in ports.items():
            if ident != "bad":
                mock_switch.assert_any_call(port)
        assert mock.call(ports["bad"], self.hass) not in mock_switch.mock_calls

class TestMfiSwitch(unittest.TestCase):
    """Test for mFi switch platform."""

    def setup_method(self, method):
        """Set up things to be run when tests are started."""
        self.hass = get_test_home_assistant()
        self.port = mock.MagicMock()
        self.switch = mfi.MfiSwitch(self.port)

    def teardown_method(self, method):
        """Stop everything that was started."""
        self.hass.stop()

    def test_name(self):
        """Test the name."""
        assert self.port.label == self.switch.name

    def test_update(self):
        """Test update."""
        self.switch.update()
        assert self.port.refresh.call_count == 1
        assert self.port.refresh.call_args == mock.call()

    def test_update_with_target_state(self):
        """Test update with target state."""
        self.switch._target_state = True
        self.port.data = {}
        self.port.data["output"] = "stale"
        self.switch.update()
        assert 1.0 == self.port.data["output"]
        assert self.switch._target_state is None
        self.port.data["output"] = "untouched"
        self.switch.update()
        assert "untouched" == self.port.data["output"]

    def test_turn_on(self):
        """Test turn_on."""
        self.switch.turn_on()
        assert self.port.control.call_count == 1
        assert self.port.control.call_args == mock.call(True)
        assert self.switch._target_state

    def test_turn_off(self):
        """Test turn_off."""
        self.switch.turn_off()
        assert self.port.control.call_count == 1
        assert self.port.control.call_args == mock.call(False)
        assert not self.switch._target_state

    def test_current_power_w(self):
        """Test current power."""
        self.port.data = {"active_pwr": 10}
        assert 10 == self.switch.current_power_w

    def test_current_power_w_no_data(self):
        """Test current power if there is no data."""
        self.port.data = {"notpower": 123}
        assert 0 == self.switch.current_power_w

    def test_device_state_attributes(self):
        """Test the state attributes."""
        self.port.data = {"v_rms": 1.25, "i_rms": 2.75}
        assert {"volts": 1.2, "amps": 2.8} == self.switch.device_state_attributes


text:
using namespace BaseLabWin;

std::list<Msg> CMutexTest::MsgList;
int CMutexTest::messageNum(0);
HANDLE CMutexTest::mutex = ::CreateMutex(NULL, FALSE, "mutex");

BaseLabWin::CMutexTest::CMutexTest()
{
	mutex = ::CreateMutex(NULL, FALSE, "mutex");
}

BaseLabWin::CMutexTest::~CMutexTest()
{
}

DWORD WINAPI BaseLabWin::CMutexTest::producer(LPVOID pParameter)
{
	Msg msgtmp;
	int i = 0;
	srand((unsigned)time(0));
	while (TRUE)
	{
		WaitForSingleObject(mutex, INFINITE);
		if (MsgList.size() < MaxQueSize)
		{
			msgtmp.head = ++messageNum;
			MsgList.push_back(msgtmp);
			std::cout << "Mutex product message :" << msgtmp.head << std::endl;
			std::cout << "Mutex pool message num£º" << MsgList.size() << std::endl;
		}
		ReleaseMutex(mutex);
		Sleep(rand() % 1000);
	}

}

DWORD WINAPI BaseLabWin::CMutexTest::consumer(LPVOID pParameter)
{
	std::list<Msg>::iterator it;
	Msg msgtmp;
	srand((unsigned)time(0));
	while (TRUE)
	{
		if (!MsgList.empty())
		{
			WaitForSingleObject(mutex, INFINITE);
			if (!MsgList.empty())
			{
				it = MsgList.begin();
				std::cout << "Mutex consume message :" << it->head << std::endl;
				std::cout << "Mutex pool message num:" << MsgList.size() << std::endl;
				MsgList.pop_front();
			}
			ReleaseMutex(mutex);
		}
		Sleep(rand() % 1000);
	}
}


text:
package main

import (
	"strings"

	"github.com/kataras/iris/v12/_examples/mvc/vuejs-todo-mvc/src/todo"
	"github.com/kataras/iris/v12/_examples/mvc/vuejs-todo-mvc/src/web/controllers"

	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/mvc"
	"github.com/kataras/iris/v12/sessions"
	"github.com/kataras/iris/v12/websocket"
)

func main() {
	app := iris.New()

	// serve our app in public, public folder
	// contains the client-side vue.js application,
	// no need for any server-side template here,
	// actually if you're going to just use vue without any
	// back-end services, you can just stop afer this line and start the server.
	app.HandleDir("/", iris.Dir("./public"))

	// configure the http sessions.
	sess := sessions.New(sessions.Config{
		Cookie: "iris_session",
	})

	// create a sub router and register the http controllers.
	todosRouter := app.Party("/todos")

	// create our mvc application targeted to /todos relative sub path.
	todosApp := mvc.New(todosRouter)

	// any dependencies bindings here...
	todosApp.Register(
		todo.NewMemoryService(),
	)

	todosController := new(controllers.TodoController)
	// controllers registration here...
	todosApp.Handle(todosController)

	// Create a sub mvc app for websocket controller.
	// Inherit the parent's dependencies.
	todosWebsocketApp := todosApp.Party("/sync")
	todosWebsocketApp.HandleWebsocket(todosController).
		SetNamespace("todos").
		SetEventMatcher(func(methodName string) (string, bool) {
			return strings.ToLower(methodName), true
		})

	websocketServer := websocket.New(websocket.DefaultGorillaUpgrader, todosWebsocketApp)
	idGenerator := func(ctx iris.Context) string {
		id := sess.Start(ctx).ID()
		return id
	}
	todosWebsocketApp.Router.Get("/", websocket.Handler(websocketServer, idGenerator))

	// start the web server at http://localhost:8080
	app.Listen(":8080")
}


text:
stormPath=$1
topologyType=$2
zkAndPort=$3
dsName=$4
jarPath=$5
projectName=$6
alias=$7

temp=`echo ${jarPath} | grep ".jar"`
if [ -n "$temp" ]; then
    jarName=""
fi

#全量信息
splitterPullerMainClass="com.creditease.dbus.FullPullerTopology"
splitterPullerCmd="${stormPath}/bin/storm jar ${jarPath} ${splitterPullerMainClass} -zk ${zkAndPort} -tid ${dsName}"
#echo $splitterPullerCmd

#增量信息
dispatcherAppenderMainClass="com.creditease.dbus.stream.DispatcherAppenderTopology"
dispatcherAppenderCmd="${stormPath}/bin/storm jar ${jarPath} ${dispatcherAppenderMainClass} -zk ${zkAndPort} -tid ${dsName}"

#抽取进程信息
extractorMainClass="com.creditease.dbus.extractor.MysqlExtractorTopology"
extractorCmd="${stormPath}/bin/storm jar ${jarPath} ${extractorMainClass} -zk ${zkAndPort} -tid ${dsName}"
#echo $extractorCmd

#log-processor信息
logProcessorMainClass="com.creditease.dbus.log.processor.DBusLogProcessorTopology"
logProcessorCmd="${stormPath}/bin/storm jar ${jarPath} ${logProcessorMainClass} -zk ${zkAndPort} -tid ${dsName}"
#echo $logProcessorCmd

#router信息
routerMainClass="com.creditease.dbus.router.DBusRouterTopology"
routerCmd="${stormPath}/bin/storm jar ${jarPath} ${routerMainClass} -zk ${zkAndPort} -tid ${dsName} -pn ${projectName} -alias ${alias}"
#echo $routerCmd

#sinker信息
sinkerMainClass="com.creditease.dbus.SinkTopology"
sinkerCmd="${stormPath}/bin/storm jar ${jarPath} ${sinkerMainClass} -zk ${zkAndPort} -tid ${dsName} -sty hdfs"
#echo $sinkerCmd

dispatcherAppender="dispatcher-appender"
splitterPuller="splitter-puller"
extractor="mysql-extractor"
logProcessor="log-processor"
router="router"
sinker="sinker"

if test ${topologyType} = ${splitterPuller}
then
	${splitterPullerCmd}
elif test ${topologyType} = ${dispatcherAppender}
then
	${dispatcherAppenderCmd}
elif test ${topologyType} = ${logProcessor}
then
	${logProcessorCmd}
elif test ${topologyType} = ${extractor}
then
	${extractorCmd}
elif test ${topologyType} = ${router}
then
	${routerCmd}
elif test ${topologyType} = ${sinker}
then
	${sinkerCmd}
fi


text:
/**
 * react-native-swiper
 * @author leecade<leecade@163.com>
 */
import React from 'react'
import ReactNative, {
  StyleSheet,
  Text,
  View,
  ScrollView,
  Dimensions,
  TouchableOpacity,
  ViewPagerAndroid,
  Platform
} from 'react-native'

// Using bare setTimeout, setInterval, setImmediate
// and requestAnimationFrame calls is very dangerous
// because if you forget to cancel the request before
// the component is unmounted, you risk the callback
// throwing an exception.
import TimerMixin from 'react-timer-mixin'

let { width, height } = Dimensions.get('window')

/**
 * Default styles
 * @type {StyleSheetPropType}
 */
let styles = StyleSheet.create({
  container: {
    backgroundColor: 'transparent',
    position: 'relative',
  },

  wrapper: {
    backgroundColor: 'transparent',
  },

  slide: {
    backgroundColor: 'transparent',
  },

  pagination_x: {
    position: 'absolute',
    bottom: 25,
    left: 0,
    right: 0,
    flexDirection: 'row',
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor:'transparent',
  },

  pagination_y: {
    position: 'absolute',
    right: 15,
    top: 0,
    bottom: 0,
    flexDirection: 'column',
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor:'transparent',
  },

  title: {
    height: 30,
    justifyContent: 'center',
    position: 'absolute',
    paddingLeft: 10,
    bottom: -30,
    left: 0,
    flexWrap: 'nowrap',
    width: 250,
    backgroundColor: 'transparent',
  },

  buttonWrapper: {
    backgroundColor: 'transparent',
    flexDirection: 'row',
    position: 'absolute',
    top: 0,
    left: 0,
    flex: 1,
    paddingHorizontal: 10,
    paddingVertical: 10,
    justifyContent: 'space-between',
    alignItems: 'center'
  },

  buttonText: {
    fontSize: 50,
    color: '#007aff',
    fontFamily: 'Arial',
  },
})

// missing `module.exports = exports['default'];` with babel6
// export default React.createClass({
module.exports = React.createClass({

  /**
   * Props Validation
   * @type {Object}
   */
  propTypes: {
    horizontal                       : React.PropTypes.bool,
    children                         : React.PropTypes.node.isRequired,
    style                            : View.propTypes.style,
    pagingEnabled                    : React.PropTypes.bool,
    showsHorizontalScrollIndicator   : React.PropTypes.bool,
    showsVerticalScrollIndicator     : React.PropTypes.bool,
    bounces                          : React.PropTypes.bool,
    scrollsToTop                     : React.PropTypes.bool,
    removeClippedSubviews            : React.PropTypes.bool,
    automaticallyAdjustContentInsets : React.PropTypes.bool,
    showsPagination                  : React.PropTypes.bool,
    showsButtons                     : React.PropTypes.bool,
    loop                             : React.PropTypes.bool,
    autoplay                         : React.PropTypes.bool,
    autoplayTimeout                  : React.PropTypes.number,
    autoplayDirection                : React.PropTypes.bool,
    index                            : React.PropTypes.number,
    renderPagination                 : React.PropTypes.func,
  },

  mixins: [TimerMixin],

  /**
   * Default props
   * @return {object} props
   * @see http://facebook.github.io/react-native/docs/scrollview.html
   */
  getDefaultProps() {
    return {
      horizontal                       : true,
      pagingEnabled                    : true,
      showsHorizontalScrollIndicator   : false,
      showsVerticalScrollIndicator     : false,
      bounces                          : false,
      scrollsToTop                     : false,
      removeClippedSubviews            : true,
      automaticallyAdjustContentInsets : false,
      showsPagination                  : true,
      showsButtons                     : false,
      loop                             : true,
      autoplay                         : false,
      autoplayTimeout                  : 2.5,
      autoplayDirection                : true,
      index                            : 0,
    }
  },

  /**
   * Init states
   * @return {object} states
   */
  getInitialState() {
    return this.initState(this.props)
  },

  /**
   * autoplay timer
   * @type {null}
   */
  autoplayTimer: null,

  componentWillReceiveProps(props) {
    this.setState(this.initState(props))
  },

  componentDidMount() {
    this.autoplay()
  },

  initState(props) {
    // set the current state
    const state = this.state || {}

    let initState = {
      isScrolling: false,
      autoplayEnd: false,
    }

    initState.total = props.children ? props.children.length || 1 : 0

    if (state.total === initState.total) {
      // retain the index
      initState.index = state.index
    } else {
      // reset the index
      initState.index = initState.total > 1 ? Math.min(props.index, initState.total - 1) : 0
    }

    // Default: horizontal
    initState.dir = props.horizontal === false ? 'y' : 'x'
    initState.width = props.width || width
    initState.height = props.height || height
    initState.offset = {}

    if (initState.total > 1) {
      var setup = initState.index
      if ( props.loop ) {
        setup++
      }
      initState.offset[initState.dir] = initState.dir === 'y'
        ? initState.height * setup
        : initState.width * setup
    }
    return initState
  },

  /**
   * Automatic rolling
   */
  autoplay() {
    if(
      !Array.isArray(this.props.children)
      || !this.props.autoplay
      || this.state.isScrolling
      || this.state.autoplayEnd
    ) {
      return
    }

    clearTimeout(this.autoplayTimer)

    this.autoplayTimer = this.setTimeout(() => {
      if(
        !this.props.loop && (
          this.props.autoplayDirection
            ? this.state.index === this.state.total - 1
            : this.state.index === 0
        )
      ) {
        return this.setState({ autoplayEnd: true })
      }

      this.scrollBy(this.props.autoplayDirection ? 1 : -1)
    }, this.props.autoplayTimeout * 1000)
  },

  /**
   * Scroll begin handle
   * @param  {object} e native event
   */
  onScrollBegin(e) {
    // update scroll state
    this.setState({ isScrolling: true })

    this.setTimeout(() => {
      this.props.onScrollBeginDrag && this.props.onScrollBeginDrag(e, this.state, this)
    })
  },

  /**
   * Scroll end handle
   * @param  {object} e native event
   */
  onScrollEnd(e) {
    // update scroll state
    this.setState({
      isScrolling: false
    })

    // making our events coming from android compatible to updateIndex logic
    if (!e.nativeEvent.contentOffset) {
      if (this.state.dir === 'x') {
        e.nativeEvent.contentOffset = {x: e.nativeEvent.position * this.state.width}
      } else {
        e.nativeEvent.contentOffset = {y: e.nativeEvent.position * this.state.height}
      }
    }

    this.updateIndex(e.nativeEvent.contentOffset, this.state.dir)

    // Note: `this.setState` is async, so I call the `onMomentumScrollEnd`
    // in setTimeout to ensure synchronous update `index`
    this.setTimeout(() => {
      this.autoplay()

      // if `onMomentumScrollEnd` registered will be called here
      this.props.onMomentumScrollEnd && this.props.onMomentumScrollEnd(e, this.state, this)
    })
  },

  /**
   * Update index after scroll
   * @param  {object} offset content offset
   * @param  {string} dir    'x' || 'y'
   */
  updateIndex(offset, dir) {

    let state = this.state
    let index = state.index
    let diff = offset[dir] - state.offset[dir]
    let step = dir === 'x' ? state.width : state.height

    // Do nothing if offset no change.
    if(!diff) return

    // Note: if touch very very quickly and continuous,
    // the variation of `index` more than 1.
    // parseInt() ensures it's always an integer
    index = parseInt(index + diff / step)

    if(this.props.loop) {
      if(index <= -1) {
        index = state.total - 1
        offset[dir] = step * state.total
      }
      else if(index >= state.total) {
        index = 0
        offset[dir] = step
      }
    }

    this.setState({
      index: index,
      offset: offset,
    })
  },

  /**
   * Scroll by index
   * @param  {number} index offset index
   */
  scrollBy(index) {
    if (this.state.isScrolling || this.state.total < 2) return
    let state = this.state
    let diff = (this.props.loop ? 1 : 0) + index + this.state.index
    let x = 0
    let y = 0
    if(state.dir === 'x') x = diff * state.width
    if(state.dir === 'y') y = diff * state.height

    if (Platform.OS === 'android') {
      this.refs.scrollView && this.refs.scrollView.setPage(diff)
    } else {
      this.refs.scrollView && this.refs.scrollView.scrollTo({
        y: y,
        x: x
      })
    }

    // update scroll state
    this.setState({
      isScrolling: true,
      autoplayEnd: false,
    })

    // trigger onScrollEnd manually in android
    if (Platform.OS === 'android') {
      this.setTimeout(() => {
        this.onScrollEnd({
          nativeEvent: {
            position: diff,
          }
        });
      }, 50);
    }

  },

  scrollViewPropOverrides() {
    var props = this.props
    var overrides = {}

    /*
    const scrollResponders = [
      'onMomentumScrollBegin',
      'onTouchStartCapture',
      'onTouchStart',
      'onTouchEnd',
      'onResponderRelease',
    ]
    */

    for(let prop in props) {
      // if(~scrollResponders.indexOf(prop)
      if(typeof props[prop] === 'function'
        && prop !== 'onMomentumScrollEnd'
        && prop !== 'renderPagination'
        && prop !== 'onScrollBeginDrag'
      ) {
        let originResponder = props[prop]
        overrides[prop] = (e) => originResponder(e, this.state, this)
      }
    }

    return overrides
  },

  /**
   * Render pagination
   * @return {object} react-dom
   */
  renderPagination() {

    // By default, dots only show when `total` > 2
    if(this.state.total <= 1) return null

    let dots = []
    let ActiveDot = this.props.activeDot || <View style={{
            backgroundColor: '#007aff',
            width: 8,
            height: 8,
            borderRadius: 4,
            marginLeft: 3,
            marginRight: 3,
            marginTop: 3,
            marginBottom: 3,
          }} />;
    let Dot = this.props.dot || <View style={{
            backgroundColor:'rgba(0,0,0,.2)',
            width: 8,
            height: 8,
            borderRadius: 4,
            marginLeft: 3,
            marginRight: 3,
            marginTop: 3,
            marginBottom: 3,
          }} />;
    for(let i = 0; i < this.state.total; i++) {
      dots.push(i === this.state.index
        ?
        React.cloneElement(ActiveDot, {key: i})
        :
        React.cloneElement(Dot, {key: i})
      )
    }

    return (
      <View pointerEvents='none' style={[styles['pagination_' + this.state.dir], this.props.paginationStyle]}>
        {dots}
      </View>
    )
  },

  renderTitle() {
    let child = this.props.children[this.state.index]
    let title = child && child.props.title
    return title
      ? (
        <View style={styles.title}>
          {this.props.children[this.state.index].props.title}
        </View>
      )
      : null
  },

  renderNextButton() {
    let button;

    if (this.props.loop || this.state.index != this.state.total - 1) {
      button = this.props.nextButton || <Text style={styles.buttonText}>›</Text>
    }

    return (
      <TouchableOpacity onPress={() => button !== null && this.scrollBy.call(this, 1)}>
        <View>
          {button}
        </View>
      </TouchableOpacity>
    )
  },

  renderPrevButton() {
    let button = null

    if (this.props.loop || this.state.index != 0) {
       button = this.props.prevButton || <Text style={styles.buttonText}>‹</Text>
    }

    return (
      <TouchableOpacity onPress={() => button !== null && this.scrollBy.call(this, -1)}>
        <View>
          {button}
        </View>
      </TouchableOpacity>
    )
  },

  renderButtons() {
    return (
      <View pointerEvents='box-none' style={[styles.buttonWrapper, {width: this.state.width, height: this.state.height}, this.props.buttonWrapperStyle]}>
        {this.renderPrevButton()}
        {this.renderNextButton()}
      </View>
    )
  },

  renderScrollView(pages) {
     if (Platform.OS === 'ios')
         return (
            <ScrollView ref="scrollView"
             {...this.props}
             {...this.scrollViewPropOverrides()}
                       contentContainerStyle={[styles.wrapper, this.props.style]}
                       contentOffset={this.state.offset}
                       onScrollBeginDrag={this.onScrollBegin}
                       onScrollEndDrag={()=>this.setState({isScrolling:false})}
                       onMomentumScrollEnd={this.onScrollEnd}>
             {pages}
            </ScrollView>
         );
      return (
         <ViewPagerAndroid ref="scrollView"
          {...this.props}
            initialPage={this.props.loop ? this.state.index + 1 : this.state.index}
            onPageSelected={this.onScrollEnd}
            style={{flex: 1}}>
            {pages}
         </ViewPagerAndroid>
      );
  },

  /**
   * Default render
   * @return {object} react-dom
   */
  render() {
    let state = this.state
    let props = this.props
    let children = props.children
    let index = state.index
    let total = state.total
    let loop = props.loop
    let dir = state.dir
    let key = 0

    let pages = []
    let pageStyle = [{width: state.width, height: state.height}, styles.slide]

    // For make infinite at least total > 1
    if(total > 1) {

      // Re-design a loop model for avoid img flickering
      pages = Object.keys(children)
      if(loop) {
        pages.unshift(total - 1)
        pages.push(0)
      }

      pages = pages.map((page, i) =>
        <View style={pageStyle} key={i}>{children[page]}</View>
      )
    }
    else pages = <View style={pageStyle}>{children}</View>

    return (
      <View style={[styles.container, {
        width: state.width,
        height: state.height
      }]}>
        {this.renderScrollView(pages)}
        {props.showsPagination && (props.renderPagination
          ? this.props.renderPagination(state.index, state.total, this)
          : this.renderPagination())}
        {this.renderTitle()}
        {this.props.showsButtons && this.renderButtons()}
      </View>
    )
  }
})


text:
/***
 * Wololo - Main JavaScript
 *
 * @Author		Rafael Keramidas <rafael@keramid.as>
 * @Version     1.0
 * @Date        4th November 2013
 * @License     MIT <Look at licence.txt>
 ***/

$(function(){

	$('.status').tooltip();

	$('.wake').click(function(){
		var id = $(this).attr('name');
		$("#loading-" + id).removeClass('hidden');

		$.get('ajax/wake.ajax.php', { id: id }).done(function(data) {
			$("#loading-" + id).addClass('hidden');
			alert(data);
		});
	});

	$('.status').click(function() {
		var id = $(this).attr('name');
		isOnline(id);
	});

});

function isOnline(id) {
	$("#status-" + id).removeClass('btn-success btn-danger').addClass('btn-warning');
	$("#status-" + id).html('Checking');
	$("#loading-" + id).removeClass('hidden');

	$.get('ajax/check.ajax.php', { id: id }).done(function(data) {
		if(data == 'ok') {
			$("#status-" + id).removeClass('btn-warning').addClass('btn-success');
			$("#status-" + id).html('Online');
		}
		else {
			$("#status-" + id).removeClass('btn-warning').addClass('btn-danger');
			$("#status-" + id).html('Offline');
		}
		$("#loading-" + id).addClass('hidden');
	});
}


text:
package com.intellij.java.lexer;

import com.intellij.lang.java.JavaParserDefinition;
import com.intellij.lexer.LayeredLexer;
import com.intellij.lexer.Lexer;
import com.intellij.lexer.LexerBase;
import com.intellij.lexer.StringLiteralLexer;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.psi.JavaTokenType;
import com.intellij.psi.TokenType;
import com.intellij.psi.tree.IElementType;
import junit.framework.TestCase;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

public class LayeredLexerTest extends TestCase {
  public void testInTheMiddle() {
    Lexer lexer = setupLexer("s=\"abc\\ndef\";");

    assertEquals("s", nextToken(lexer));
    assertEquals("=", nextToken(lexer));
    assertEquals("\"abc", nextToken(lexer));
    assertEquals("\\n", nextToken(lexer));
    assertEquals("def\"", nextToken(lexer));
    assertEquals(";", nextToken(lexer));
    assertEquals(null, lexer.getTokenType());
  }

  public void testModification() {
    Lexer lexer = setupLexer("s=\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";");
    assertEquals("s", nextToken(lexer));
    assertEquals("=", nextToken(lexer));
    assertEquals("\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"", nextToken(lexer));
    assertEquals(";", nextToken(lexer));
    assertEquals(null, lexer.getTokenType());

    lexer.start(lexer.getBufferSequence(), 2, lexer.getBufferEnd(), (short) 1);
    assertEquals("\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"", nextToken(lexer));
    assertEquals(";", nextToken(lexer));
    assertEquals(null, lexer.getTokenType());
  }

  public void testInTheAtStartup() {
    Lexer lexer = setupLexer("s=\"\\ndef\";");

    assertEquals("s", nextToken(lexer));
    assertEquals("=", nextToken(lexer));
    assertEquals("\"", nextToken(lexer));
    assertEquals("\\n", nextToken(lexer));
    assertEquals("def\"", nextToken(lexer));
    assertEquals(";", nextToken(lexer));
    assertEquals(null, lexer.getTokenType());
  }

  public void testInTheAtEnd() {
    Lexer lexer = setupLexer("s=\"abc\\n\";");

    assertEquals("s", nextToken(lexer));
    assertEquals("=", nextToken(lexer));
    assertEquals("\"abc", nextToken(lexer));
    assertEquals("\\n", nextToken(lexer));
    assertEquals("\"", nextToken(lexer));
    assertEquals(";", nextToken(lexer));
    assertEquals(null, lexer.getTokenType());
  }

  public void testNonTerminated() {
    Lexer lexer = setupLexer("s=\"abc\\n");

    assertEquals("s", nextToken(lexer));
    assertEquals("=", nextToken(lexer));
    assertEquals("\"abc", nextToken(lexer));
    assertEquals("\\n", nextToken(lexer));
    assertEquals(null, lexer.getTokenType());
  }

  public void testNonTerminated2() {
    Lexer lexer = setupLexer("s=\"abc\\");

    assertEquals("s", nextToken(lexer));
    assertEquals("=", nextToken(lexer));
    assertEquals("\"abc", nextToken(lexer));
    assertEquals("\\", nextToken(lexer));
    assertEquals(null, lexer.getTokenType());
  }

  public void testUnicode() {
    Lexer lexer = setupLexer("s=\"\\uFFFF\";");
    assertEquals("s", nextToken(lexer));
    assertEquals("=", nextToken(lexer));
    assertEquals("\"", nextToken(lexer));
    assertEquals("\\uFFFF", nextToken(lexer));
    assertEquals("\"", nextToken(lexer));
    assertEquals(";", nextToken(lexer));
    assertEquals(null, lexer.getTokenType());
  }

  public void testDelegatesWithBigStates() {
    final LayeredLexer lexer = new LayeredLexer(new SimpleStateSteppingLexer());
    lexer.registerSelfStoppingLayer(new SimpleStateSteppingLexer(),
                                    new IElementType[]{TokenType.CODE_FRAGMENT},
                                    IElementType.EMPTY_ARRAY);

    lexer.start("1234567890123#1234567890123#1234567890123");
    assertLexerSequence(lexer,
      "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "1", "2", "3",
      "#",
      "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "1", "2", "3",
      "#",
      "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "1", "2", "3"
    );
  }

  private static Lexer setupLexer(String text) {
    LayeredLexer lexer = new LayeredLexer(JavaParserDefinition.createLexer(LanguageLevel.JDK_1_3));
    lexer.registerSelfStoppingLayer(new StringLiteralLexer('\"', JavaTokenType.STRING_LITERAL),
                                    new IElementType[]{JavaTokenType.STRING_LITERAL},
                                    IElementType.EMPTY_ARRAY);
    lexer.start(text);
    return lexer;
  }

  private static void assertLexerSequence(Lexer lexer, String... tokenTexts) {
    for (String tokenText : tokenTexts) {
      assertEquals(tokenText, nextToken(lexer));
    }
    assertEquals(null, lexer.getTokenType());
  }

  private static String nextToken(Lexer lexer) {
    assertTrue(lexer.getTokenType() != null);
    final String s = lexer.getBufferSequence().subSequence(lexer.getTokenStart(), lexer.getTokenEnd()).toString();
    lexer.advance();
    return s;
  }

  private static class SimpleStateSteppingLexer extends LexerBase {

    private static final char MARK = '#';

    private CharSequence myBuffer;
    private int myStartOffset;
    private int myEndOffset;
    private int myState;
    private int myPos;

    @Override
    public void start(@NotNull CharSequence buffer, int startOffset, int endOffset, int initialState) {
      myBuffer = buffer;
      myStartOffset = startOffset;
      myEndOffset = endOffset;
      myState = initialState;

      myPos = myStartOffset;
    }

    @Override
    public int getState() {
      return myState;
    }

    @Nullable
    @Override
    public IElementType getTokenType() {
      if (myPos >= myEndOffset) {
        return null;
      }

      if (findNextMarkIfStoppedOnMarkAndNotAtStart() != myEndOffset) {
        return TokenType.CODE_FRAGMENT;
      }

      return TokenType.BAD_CHARACTER;
    }

    @Override
    public int getTokenStart() {
      return myPos;
    }

    @Override
    public int getTokenEnd() {
      if (myPos == myEndOffset) {
        return myPos;
      }

      final int nextMark = findNextMarkIfStoppedOnMarkAndNotAtStart();
      if (nextMark != myEndOffset) {
        return nextMark + 1;
      }
      return myPos + 1;
    }

    @Override
    public void advance() {
      myPos = getTokenEnd();

      if (myState == 0) {
        myState = 1;
      }
      else {
        myState <<= 1;
      }
    }

    @NotNull
    @Override
    public CharSequence getBufferSequence() {
      return myBuffer;
    }

    @Override
    public int getBufferEnd() {
      return myEndOffset;
    }

    private int findNextMarkIfStoppedOnMarkAndNotAtStart() {
      if (myPos == myStartOffset ||
          myPos < myEndOffset && myBuffer.charAt(myPos) != MARK) {
        return myEndOffset;
      }

      int i = myPos + 1;
      while (i < myEndOffset && myBuffer.charAt(i) != MARK) {
        i++;
      }
      return i;
    }
  }
}


text:
#include "ControllerManager.h"

ControllerManager* ControllerManager::sInstance = nullptr;

ControllerManager::StaticDeviceConnectionListener::StaticDeviceConnectionListener(
        const DeviceConnectionCallback& callback) : mDeviceConnectionCallback(callback) {
}

void ControllerManager::StaticDeviceConnectionListener::onDeviceConnectionChanged(int deviceId,
        bool isConnected) {
    mDeviceConnectionCallback(deviceId, isConnected);
}

void ControllerManager::reset() {
    for (int deviceId : mControllerIds) {
        notifyDeviceConnectionChanged(deviceId, false);
    }
    mControllers.clear();
    mControllerIds.clear();
}

void ControllerManager::onControllerDisconnect(int deviceId) {
    mControllers.erase(deviceId);
    mControllerIds.erase(deviceId);
    notifyDeviceConnectionChanged(deviceId, false);
}

void ControllerManager::registerDeviceConnectionListener(DeviceConnectionListener* listener) {
    mDeviceConnectionListeners.insert(listener);
}

void ControllerManager::unregisterDeviceConnectionListener(DeviceConnectionListener* listener) {
    mDeviceConnectionListeners.erase(listener);
}

ControllerManager* ControllerManager::getInstance() {
    if (!sInstance) {
        sInstance = new ControllerManager;
    }
    return sInstance;
}

void ControllerManager::notifyDeviceConnectionChanged(int deviceId, bool isConnected) const {
    for (DeviceConnectionListener* listener : mDeviceConnectionListeners) {
        listener->onDeviceConnectionChanged(deviceId, isConnected);
    }
}

void ControllerManager::initControllerIfNeeded(int deviceId,
        std::unique_ptr<VirtualController> &controller, const ControllerFactory *factory) const {
    if (!controller.get() && factory) {
        controller.reset(factory->createNewController(deviceId));
        mControllerIds.insert(deviceId);
        notifyDeviceConnectionChanged(deviceId, true);
    }
}


text:
package org.kaaproject.examples.storm.storm.server.common;

import org.apache.flume.node.MaterializedConfiguration;

import java.util.Map;

/**
 Class for testing
 */
public class MaterializedConfigurationProvider {
    public MaterializedConfiguration get(String name, Map<String, String> properties) {
        MemoryConfigurationProvider confProvider =
                new MemoryConfigurationProvider(name, properties);
        return confProvider.getConfiguration();
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;

namespace Tatabouf
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            // Supprimez les commentaires de la ligne de code suivante pour activer la prise en charge des requêtes pour les actions ayant un type de retour IQueryable ou IQueryable<T>.
            // Pour éviter le traitement de requêtes inattendues ou malveillantes, utilisez les paramètres de validation définis sur QueryableAttribute pour valider les requêtes entrantes.
            // Pour plus d'informations, visitez http://go.microsoft.com/fwlink/?LinkId=279712.
            //config.EnableQuerySupport();

            // Pour désactiver le suivi dans votre application, supprimez le commentaire de la ligne de code suivante ou supprimez cette dernière
            //Pour plus d'informations, consultez la page : http://www.asp.net/web-api
            config.EnableSystemDiagnosticsTracing();
        }
    }
}


text:
The cookbook is a continuously growing collection of recipes that explain how to correctly solve the most recurrent problems that developers face in their day to day work with the KunstmaanBundlesCMS.

* [Going single language](going-single-language.md)
* [Managing translations](manage-translations.md)
* [Google Analytics dashboard](google-analytics-dashboard.md)
* [Administer robots.txt](administer-robots-txt.md)
* [Building a custom admin list filter that works on multiple columns](building-custom-filter-on-multiple-columns.md)
* [Using the LeadGenerationBundle](using-the-leadgenerationbundle.md)
* [Using the MenuBundle](using-the-menubundle.md)
* [Using the MultiDomainBundle](using-the-multi-domain-bundle.md)
* [Defining custom ckeditor configuration](defining-custom-ckeditor-configuration.md)
* [Structure pages](structure-pages.md)
* [Adding a custom controller](adding-a-custom-controller.md)
* [Using a custom filesystem for the media bundle](using-a-custom-filesystem-for-the-media-bundle.md)
* [Enabling google login](enabling-google-auth-login.md)
* [Using the cache bundle](using-the-cache-bundle.md)
* [Using anacrontab](using-anacrontab.md)

> Have some cool insight or thing you did with the CMS? Please share it with us and other developers by [sending a pull request](../contributing/pull-requests.md)!


text:
"""
models.pytorch.common
=====================

This module provides common functionality required to realize QRNNs in pytorch.
"""
import torch
import numpy as np
from torch import nn
from torch import optim
from torch.optim.lr_scheduler import ReduceLROnPlateau
from torch.utils.data import Dataset
from tqdm import tqdm

activations = {
    "elu": nn.ELU,
    "hardshrink": nn.Hardshrink,
    "hardtanh": nn.Hardtanh,
    "prelu": nn.PReLU,
    "relu": nn.ReLU,
    "selu": nn.SELU,
    "celu": nn.CELU,
    "sigmoid": nn.Sigmoid,
    "softplus": nn.Softplus,
    "softmin": nn.Softmin,
}

def save_model(f, model):
    """
    Save pytorch model.

    Args:
        f(:code:`str` or binary stream): Either a path or a binary stream
            to store the data to.
        model(:code:`pytorch.nn.Moduel`): The pytorch model to save
    """
    torch.save(model, f)

def load_model(f, quantiles):
    """
    Load pytorch model.

    Args:
        f(:code:`str` or binary stream): Either a path or a binary stream
            to read the model from
        quantiles(:code:`np.ndarray`): Array containing the quantiles
            that the model predicts.

    Returns:
        The loaded pytorch model.
    """
    model = torch.load(f)
    return model

def handle_input(data, device=None):
    """
    Handle input data.

    This function handles data supplied

      - as tuple of :code:`np.ndarray`
      - a single :code:`np.ndarray`
      - torch :code:`dataloader`

    If a numpy array is provided it is converted to a torch tensor
    so that it can be fed into a pytorch model.
    """
    if type(data) == tuple:
        x, y = data
        x = torch.tensor(x, dtype=torch.float)
        y = torch.tensor(y, dtype=torch.float)
        if not device is None:
            x = x.to(device)
            y = y.to(device)
        return x, y
    if type(data) == np.ndarray:
        x = torch.tensor(data, dtype=torch.float)
        if not device is None:
            x = x.to(device)
        return x
    else:
        return data

class BatchedDataset(Dataset):
    """
    Batches an un-batched dataset.
    """

    def __init__(self, training_data, batch_size):
        x, y = training_data
        self.x = torch.tensor(x, dtype=torch.float)
        self.y = torch.tensor(y, dtype=torch.float)
        self.batch_size = batch_size

    def __len__(self):
        # This is required because x and y are tensors and don't throw these
        # errors themselves.
        return self.x.shape[0] // self.batch_size

    def __getitem__(self, i):
        if i >= len(self):
            raise IndexError()
        i_start = i * self.batch_size
        i_end = (i + 1) * self.batch_size
        x = self.x[i_start:i_end]
        y = self.y[i_start:i_end]
        return (x, y)

################################################################################
# Quantile loss
################################################################################

class QuantileLoss:
    r"""
    The quantile loss function

    This function object implements the quantile loss defined as

    .. math::

        \mathcal{L}(y_\text{pred}, y_\text{true}) =
        \begin{cases}
        \tau \cdot |y_\text{pred} - y_\text{true}| & , y_\text{pred} < y_\text{true} \\
        (1 - \tau) \cdot |y_\text{pred} - y_\text{true}| & , \text{otherwise}
        \end{cases}

    as a training criterion for the training of neural networks. The loss criterion
    expects a vector :math:`\mathbf{y}_\tau` of predicted quantiles and the observed
    value :math:`y`. The loss for a single training sample is computed by summing the losses
    corresponding to each quantiles. The loss for a batch of training samples is
    computed by taking the mean over all samples in the batch.
    """

    def __init__(self, quantiles, mask=-1.0):
        """
        Create an instance of the quantile loss function with the given quantiles.

        Arguments:
            quantiles: Array or iterable containing the quantiles to be estimated.
        """
        self.quantiles = torch.tensor(quantiles).float()
        self.n_quantiles = len(quantiles)
        self.mask = np.float32(mask)

    def to(self, device):
        self.quantiles = self.quantiles.to(device)

    def __call__(self, y_pred, y_true):
        """
        Compute the mean quantile loss for given inputs.

        Arguments:
            y_pred: N-tensor containing the predicted quantiles along the last
                dimension
            y_true: (N-1)-tensor containing the true y values corresponding to
                the predictions in y_pred

        Returns:
            The mean quantile loss.
        """
        dy = y_pred - y_true
        n = self.quantiles.size()[0]
        qs = self.quantiles.reshape((n,) + (1,) * max(len(dy.size()) - 2, 0))
        l = torch.where(dy >= 0.0, (1.0 - qs) * dy, (-qs) * dy)
        if not self.mask is None:
            l = torch.where(y_true == self.mask, torch.zeros_like(l), l)
        return l.mean()

################################################################################
# QRNN
################################################################################

class PytorchModel:
    """
    Quantile regression neural network (QRNN)

    This class implements QRNNs as a fully-connected network with
    a given number of layers.
    """

    def __init__(self, input_dimension, quantiles):
        """
        Arguments:
            input_dimension(int): The number of input features.
            quantiles(array): Array of the quantiles to predict.
        """
        self.input_dimension = input_dimension
        self.quantiles = np.array(quantiles)
        self.criterion = QuantileLoss(self.quantiles)
        self.training_errors = []
        self.validation_errors = []
        self.backend = "typhon.retrieval.qrnn.models.pytorch"

    def _make_adversarial_samples(self, x, y, eps):
        self.model.zero_grad()
        x.requires_grad = True
        y_pred = self.model(x)
        c = self.criterion(y_pred, y)
        c.backward()
        x_adv = x.detach() + eps * torch.sign(x.grad.detach())
        return x_adv

    def reset(self):
        """
        Reinitializes the weights of a model.
        """

        def reset_function(module):
            if isinstance(m, nn.Conv2d) or isinstance(m, nn.Linear):
                m.reset_parameters()

        self.apply(reset_function)

    def train(self, *args, **kwargs):
        """
        Train the network.

        This trains the network for the given number of epochs using the
        provided training and validation data.

        If desired, the training can be augmented using adversarial training.
        In this case the network is additionally trained with an adversarial
        batch of examples in each step of the training.

        Arguments:
            training_data: pytorch dataloader providing the training data
            validation_data: pytorch dataloader providing the validation data
            n_epochs: the number of epochs to train the network for
            adversarial_training: whether or not to use adversarial training
            eps_adv: The scaling factor to use for adversarial training.
        """
        # Handle overload of train() method
        if len(args) < 1 or (len(args) == 1 and type(args[0]) == bool):
            return nn.Sequential.train(self, *args, **kwargs)

        #
        # Parse training arguments
        #

        training_data = args[0]
        arguments = {
            "validation_data": None,
            "batch_size": 256,
            "sigma_noise": None,
            "adversarial_training": False,
            "delta_at": 0.01,
            "initial_learning_rate": 1e-2,
            "momentum": 0.0,
            "convergence_epochs": 5,
            "learning_rate_decay": 2.0,
            "learning_rate_minimum": 1e-6,
            "maximum_epochs": 1,
            "training_split": 0.9,
            "gpu": False,
        }
        argument_names = arguments.keys()
        for a, n in zip(args[1:], argument_names):
            arguments[n] = a
        for k in kwargs:
            if k in arguments:
                arguments[k] = kwargs[k]
            else:
                raise ValueError("Unknown argument to {}.".print(k))

        validation_data = arguments["validation_data"]
        batch_size = arguments["batch_size"]
        sigma_noise = arguments["sigma_noise"]
        adversarial_training = arguments["adversarial_training"]
        delta_at = arguments["delta_at"]
        initial_learning_rate = arguments["initial_learning_rate"]
        convergence_epochs = arguments["convergence_epochs"]
        learning_rate_decay = arguments["learning_rate_decay"]
        learning_rate_minimum = arguments["learning_rate_minimum"]
        maximum_epochs = arguments["maximum_epochs"]
        training_split = arguments["training_split"]
        gpu = arguments["gpu"]
        momentum = arguments["momentum"]

        #
        # Determine device to use
        #
        if torch.cuda.is_available() and gpu:
            device = torch.device("cuda")
        else:
            device = torch.device("cpu")
        self.to(device)

        #
        # Handle input data
        #
        try:
            x, y = handle_input(training_data, device)
            training_data = BatchedDataset((x, y), batch_size)
        except:
            pass

        self.train()
        self.optimizer = optim.SGD(
            self.parameters(), lr=initial_learning_rate, momentum=momentum
        )
        self.criterion.to(device)
        scheduler = ReduceLROnPlateau(
            self.optimizer,
            factor=1.0 / learning_rate_decay,
            patience=convergence_epochs,
            min_lr=learning_rate_minimum,
        )
        training_errors = []
        validation_errors = []

        #
        # Training loop
        #

        for i in range(maximum_epochs):
            err = 0.0
            n = 0
            for j, (x, y) in enumerate(training_data):

                x = x.to(device)
                y = y.to(device)

                shape = x.size()
                shape = (shape[0], 1) + shape[2:]
                y = y.reshape(shape)

                self.optimizer.zero_grad()
                y_pred = self(x)
                c = self.criterion(y_pred, y)
                c.backward()
                self.optimizer.step()

                err += c.item() * x.size()[0]
                n += x.size()[0]

                if adversarial_training:
                    self.optimizer.zero_grad()
                    x_adv = self._make_adversarial_samples(x, y, delta_at)
                    y_pred = self(x)
                    c = self.criterion(y_pred, y)
                    c.backward()
                    self.optimizer.step()

                if j % 100:
                    print(
                        "Epoch {} / {}: Batch {} / {}, Training error: {:.3f}".format(
                            i, maximum_epochs, j, len(training_data), err / n
                        ),
                        end="\r",
                    )

            # Save training error
            training_errors.append(err / n)

            lr = [group["lr"] for group in self.optimizer.param_groups][0]

            val_err = 0.0
            if not validation_data is None:
                n = 0
                for x, y in validation_data:
                    x = x.to(device).detach()
                    y = y.to(device).detach()

                    shape = x.size()
                    shape = (shape[0], 1) + shape[2:]
                    y = y.reshape(shape)

                    y_pred = self(x)
                    c = self.criterion(y_pred, y)

                    val_err += c.item() * x.size()[0]
                    n += x.size()[0]
                validation_errors.append(val_err / n)

                print(
                    "Epoch {} / {}: Training error: {:.3f}, Validation error: {:.3f}, Learning rate: {:.5f}".format(
                        i,
                        maximum_epochs,
                        training_errors[-1],
                        validation_errors[-1],
                        lr,
                    )
                )
                scheduler.step(val_err / n)
            else:
                scheduler.step(err / n)
                print(
                    "Epoch {} / {}: Training error: {:.3f}, Learning rate: {:.5f}".format(
                        i, maximum_epochs, training_errors[-1], lr
                    )
                )

        self.training_errors += training_errors
        self.validation_errors += validation_errors
        self.eval()
        return {
            "training_errors": self.training_errors,
            "validation_errors": self.validation_errors,
        }

    def predict(self, x, gpu=False):
        ""
        if torch.cuda.is_available() and gpu:
            device = torch.device("cuda")
        else:
            device = torch.device("cpu")
        x = handle_input(x, device)
        self.to(device)
        return self(x.detach()).detach().numpy()

    def calibration(self, data, gpu=False):
        """
        Computes the calibration of the predictions from the neural network.

        Arguments:
            data: torch dataloader object providing the data for which to compute
                the calibration.

        Returns:
            (intervals, frequencies): Tuple containing the confidence intervals and
                corresponding observed frequencies.
        """

        if gpu and torch.cuda.is_available():
            dev = torch.device("cuda")
        else:
            dev = torch.device("cpu")
        self.to(dev)

        n_intervals = self.quantiles.size // 2
        qs = self.quantiles
        intervals = np.array([q_r - q_l for (q_l, q_r) in zip(qs, reversed(qs))])[
            :n_intervals
        ]
        counts = np.zeros(n_intervals)

        total = 0.0

        iterator = tqdm(data)
        for x, y in iterator:
            x = x.to(dev).detach()
            y = y.to(dev).detach()
            shape = x.size()
            shape = (shape[0], 1) + shape[2:]
            y = y.reshape(shape)

            y_pred = self(x)
            y_pred = y_pred.cpu()
            y = y.cpu()

            for i in range(n_intervals):
                l = y_pred[:, [i]]
                r = y_pred[:, [-(i + 1)]]
                counts[i] += np.logical_and(y >= l, y < r).sum()

            total += np.prod(y.size())
        return intervals[::-1], (counts / total)[::-1]

    def save(self, path):
        """
        Save QRNN to file.

        Arguments:
            The path in which to store the QRNN.
        """
        torch.save(
            {
                "input_dimension": self.input_dimension,
                "quantiles": self.quantiles,
                "width": self.width,
                "depth": self.depth,
                "activation": self.activation,
                "network_state": self.state_dict(),
                "optimizer_state": self.optimizer.state_dict(),
            },
            path,
        )

    @staticmethod
    def load(self, path):
        """
        Load QRNN from file.

        Arguments:
            path: Path of the file where the QRNN was stored.
        """
        state = torch.load(path, map_location=torch.device("cpu"))
        keys = ["input_dimension", "quantiles", "depth", "width", "activation"]
        qrnn = QRNN(*[state[k] for k in keys])
        qrnn.load_state_dict["network_state"]
        qrnn.optimizer.load_state_dict["optimizer_state"]


text: /*# sourceMappingURL=insurance.css.map */