text:
import copy

from mongoengine import ValidationError
import six

from st2api.controllers import resource
from st2common import log as logging
from st2common.models.api.trigger import TriggerTypeAPI, TriggerAPI, TriggerInstanceAPI
from st2common.models.system.common import ResourceReference
from st2common.persistence.trigger import TriggerType, Trigger, TriggerInstance
from st2common.router import abort
from st2common.router import Response
from st2common.services import triggers as TriggerService
from st2common.exceptions.apivalidation import ValueValidationException
from st2common.exceptions.db import StackStormDBObjectConflictError
from st2common.transport.reactor import TriggerDispatcher
from st2common.util import isotime
from st2common.validators.api.misc import validate_not_part_of_system_pack

http_client = six.moves.http_client

LOG = logging.getLogger(__name__)

class TriggerTypeController(resource.ContentPackResourceController):
    """
        Implements the RESTful web endpoint that handles
        the lifecycle of TriggerTypes in the system.
    """
    model = TriggerTypeAPI
    access = TriggerType
    supported_filters = {
        'name': 'name',
        'pack': 'pack'
    }

    options = {
        'sort': ['pack', 'name']
    }

    include_reference = True

    def get_all(self, sort=None, offset=0, limit=None, **raw_filters):
        return self._get_all(sort=sort,
                             offset=offset,
                             limit=limit,
                             raw_filters=raw_filters)

    def get_one(self, triggertype_ref_or_id):
        return self._get_one(triggertype_ref_or_id, permission_type=None, requester_user=None)

    def post(self, triggertype):
        """
            Create a new triggertype.

            Handles requests:
                POST /triggertypes/
        """

        try:
            triggertype_db = TriggerTypeAPI.to_model(triggertype)
            triggertype_db = TriggerType.add_or_update(triggertype_db)
        except (ValidationError, ValueError) as e:
            LOG.exception('Validation failed for triggertype data=%s.', triggertype)
            abort(http_client.BAD_REQUEST, str(e))
            return
        else:
            extra = {'triggertype_db': triggertype_db}
            LOG.audit('TriggerType created. TriggerType.id=%s' % (triggertype_db.id), extra=extra)
            if not triggertype_db.parameters_schema:
                TriggerTypeController._create_shadow_trigger(triggertype_db)

        triggertype_api = TriggerTypeAPI.from_model(triggertype_db)

        return Response(json=triggertype_api, status=http_client.CREATED)

    def put(self, triggertype, triggertype_ref_or_id):
        triggertype_db = self._get_by_ref_or_id(ref_or_id=triggertype_ref_or_id)
        triggertype_id = triggertype_db.id

        try:
            validate_not_part_of_system_pack(triggertype_db)
        except ValueValidationException as e:
            abort(http_client.BAD_REQUEST, str(e))

        try:
            triggertype_db = TriggerTypeAPI.to_model(triggertype)
            if triggertype.id is not None and len(triggertype.id) > 0 and \
               triggertype.id != triggertype_id:
                LOG.warning('Discarding mismatched id=%s found in payload and using uri_id=%s.',
                            triggertype.id, triggertype_id)
            triggertype_db.id = triggertype_id
            old_triggertype_db = triggertype_db
            triggertype_db = TriggerType.add_or_update(triggertype_db)
        except (ValidationError, ValueError) as e:
            LOG.exception('Validation failed for triggertype data=%s', triggertype)
            abort(http_client.BAD_REQUEST, str(e))
            return

        extra = {'old_triggertype_db': old_triggertype_db, 'new_triggertype_db': triggertype_db}
        LOG.audit('TriggerType updated. TriggerType.id=%s' % (triggertype_db.id), extra=extra)

        triggertype_api = TriggerTypeAPI.from_model(triggertype_db)
        return triggertype_api

    def delete(self, triggertype_ref_or_id):
        """
            Delete a triggertype.

            Handles requests:
                DELETE /triggertypes/1
                DELETE /triggertypes/pack.name
        """
        LOG.info('DELETE /triggertypes/ with ref_or_id=%s',
                 triggertype_ref_or_id)

        triggertype_db = self._get_by_ref_or_id(ref_or_id=triggertype_ref_or_id)
        triggertype_id = triggertype_db.id

        try:
            validate_not_part_of_system_pack(triggertype_db)
        except ValueValidationException as e:
            abort(http_client.BAD_REQUEST, str(e))

        try:
            TriggerType.delete(triggertype_db)
        except Exception as e:
            LOG.exception('Database delete encountered exception during delete of id="%s". ',
                          triggertype_id)
            abort(http_client.INTERNAL_SERVER_ERROR, str(e))
            return
        else:
            extra = {'triggertype': triggertype_db}
            LOG.audit('TriggerType deleted. TriggerType.id=%s' % (triggertype_db.id), extra=extra)
            if not triggertype_db.parameters_schema:
                TriggerTypeController._delete_shadow_trigger(triggertype_db)

        return Response(status=http_client.NO_CONTENT)

    @staticmethod
    def _create_shadow_trigger(triggertype_db):
        try:
            trigger_type_ref = triggertype_db.get_reference().ref
            trigger = {'name': triggertype_db.name,
                       'pack': triggertype_db.pack,
                       'type': trigger_type_ref,
                       'parameters': {}}
            trigger_db = TriggerService.create_or_update_trigger_db(trigger)

            extra = {'trigger_db': trigger_db}
            LOG.audit('Trigger created for parameter-less TriggerType. Trigger.id=%s' %
                      (trigger_db.id), extra=extra)
        except (ValidationError, ValueError) as e:
            LOG.exception('Validation failed for trigger data=%s.', trigger)
            # Not aborting as this is convenience.
            return
        except StackStormDBObjectConflictError as e:
            LOG.warn('Trigger creation of "%s" failed with uniqueness conflict. Exception: %s',
                     trigger, str(e))
            # Not aborting as this is convenience.
            return

    @staticmethod
    def _delete_shadow_trigger(triggertype_db):
        # shadow Trigger's have the same name as the shadowed TriggerType.
        triggertype_ref = ResourceReference(name=triggertype_db.name, pack=triggertype_db.pack)
        trigger_db = TriggerService.get_trigger_db_by_ref(triggertype_ref.ref)
        if not trigger_db:
            LOG.warn('No shadow trigger found for %s. Will skip delete.', triggertype_db)
            return
        try:
            Trigger.delete(trigger_db)
        except Exception:
            LOG.exception('Database delete encountered exception during delete of id="%s". ',
                          trigger_db.id)

        extra = {'trigger_db': trigger_db}
        LOG.audit('Trigger deleted. Trigger.id=%s' % (trigger_db.id), extra=extra)

class TriggerController(object):
    """
        Implements the RESTful web endpoint that handles
        the lifecycle of Triggers in the system.
    """
    def get_one(self, trigger_id):

        """
            List trigger by id.

            Handle:
                GET /triggers/1
        """
        trigger_db = TriggerController.__get_by_id(trigger_id)
        trigger_api = TriggerAPI.from_model(trigger_db)
        return trigger_api

    def get_all(self):
        """
            List all triggers.

            Handles requests:
                GET /triggers/
        """
        trigger_dbs = Trigger.get_all()
        trigger_apis = [TriggerAPI.from_model(trigger_db) for trigger_db in trigger_dbs]
        return trigger_apis

    def post(self, trigger):
        """
            Create a new trigger.

            Handles requests:
                POST /triggers/
        """
        try:
            trigger_db = TriggerService.create_trigger_db(trigger)
        except (ValidationError, ValueError) as e:
            LOG.exception('Validation failed for trigger data=%s.', trigger)
            abort(http_client.BAD_REQUEST, str(e))
            return

        extra = {'trigger': trigger_db}
        LOG.audit('Trigger created. Trigger.id=%s' % (trigger_db.id), extra=extra)
        trigger_api = TriggerAPI.from_model(trigger_db)

        return Response(json=trigger_api, status=http_client.CREATED)

    def put(self, trigger, trigger_id):
        trigger_db = TriggerController.__get_by_id(trigger_id)
        try:
            if trigger.id is not None and trigger.id is not '' and trigger.id != trigger_id:
                LOG.warning('Discarding mismatched id=%s found in payload and using uri_id=%s.',
                            trigger.id, trigger_id)
            trigger_db = TriggerAPI.to_model(trigger)
            trigger_db.id = trigger_id
            trigger_db = Trigger.add_or_update(trigger_db)
        except (ValidationError, ValueError) as e:
            LOG.exception('Validation failed for trigger data=%s', trigger)
            abort(http_client.BAD_REQUEST, str(e))
            return

        extra = {'old_trigger_db': trigger, 'new_trigger_db': trigger_db}
        LOG.audit('Trigger updated. Trigger.id=%s' % (trigger.id), extra=extra)
        trigger_api = TriggerAPI.from_model(trigger_db)

        return trigger_api

    def delete(self, trigger_id):
        """
            Delete a trigger.

            Handles requests:
                DELETE /triggers/1
        """
        LOG.info('DELETE /triggers/ with id=%s', trigger_id)
        trigger_db = TriggerController.__get_by_id(trigger_id)
        try:
            Trigger.delete(trigger_db)
        except Exception as e:
            LOG.exception('Database delete encountered exception during delete of id="%s". ',
                          trigger_id)
            abort(http_client.INTERNAL_SERVER_ERROR, str(e))
            return

        extra = {'trigger_db': trigger_db}
        LOG.audit('Trigger deleted. Trigger.id=%s' % (trigger_db.id), extra=extra)

        return Response(status=http_client.NO_CONTENT)

    @staticmethod
    def __get_by_id(trigger_id):
        try:
            return Trigger.get_by_id(trigger_id)
        except (ValueError, ValidationError):
            LOG.exception('Database lookup for id="%s" resulted in exception.', trigger_id)
            abort(http_client.NOT_FOUND)

    @staticmethod
    def __get_by_name(trigger_name):
        try:
            return [Trigger.get_by_name(trigger_name)]
        except ValueError as e:
            LOG.debug('Database lookup for name="%s" resulted in exception : %s.', trigger_name, e)
            return []

class TriggerInstanceControllerMixin(object):
    model = TriggerInstanceAPI
    access = TriggerInstance

class TriggerInstanceResendController(TriggerInstanceControllerMixin, resource.ResourceController):
    supported_filters = {}

    def __init__(self, *args, **kwargs):
        super(TriggerInstanceResendController, self).__init__(*args, **kwargs)
        self.trigger_dispatcher = TriggerDispatcher(LOG)

    class TriggerInstancePayload(object):
        def __init__(self, payload=None):
            self.payload = payload or {}

        def validate(self):
            if self.payload:
                assert isinstance(self.payload, dict)

            return True

    def post(self, trigger_instance_id):
        """
        Re-send the provided trigger instance optionally specifying override parameters.

        Handles requests:

            POST /triggerinstance/<id>/re_emit
            POST /triggerinstance/<id>/re_send
        """
        # Note: We only really need parameters here
        existing_trigger_instance = self._get_one_by_id(id=trigger_instance_id,
                                                        permission_type=None,
                                                        requester_user=None)

        new_payload = copy.deepcopy(existing_trigger_instance.payload)
        new_payload['__context'] = {
            'original_id': trigger_instance_id
        }

        try:
            self.trigger_dispatcher.dispatch(existing_trigger_instance.trigger,
                                             new_payload)
            return {
                'message': 'Trigger instance %s succesfully re-sent.' % trigger_instance_id,
                'payload': new_payload
            }
        except Exception as e:
            abort(http_client.INTERNAL_SERVER_ERROR, str(e))

class TriggerInstanceController(TriggerInstanceControllerMixin, resource.ResourceController):
    """
        Implements the RESTful web endpoint that handles
        the lifecycle of TriggerInstances in the system.
    """
    supported_filters = {
        'trigger': 'trigger',
        'timestamp_gt': 'occurrence_time.gt',
        'timestamp_lt': 'occurrence_time.lt',
        'status': 'status'
    }

    filter_transform_functions = {
        'timestamp_gt': lambda value: isotime.parse(value=value),
        'timestamp_lt': lambda value: isotime.parse(value=value)
    }

    query_options = {
        'sort': ['-occurrence_time', 'trigger']
    }

    def __init__(self):
        super(TriggerInstanceController, self).__init__()

    def get_one(self, instance_id):
        """
            List triggerinstance by instance_id.

            Handle:
                GET /triggerinstances/1
        """
        return self._get_one_by_id(instance_id, permission_type=None, requester_user=None)

    def get_all(self, sort=None, offset=0, limit=None, **raw_filters):
        """
            List all triggerinstances.

            Handles requests:
                GET /triggerinstances/
        """
        trigger_instances = self._get_trigger_instances(sort=sort,
                                                        offset=offset,
                                                        limit=limit,
                                                        raw_filters=raw_filters)
        return trigger_instances

    def _get_trigger_instances(self, sort=None, offset=0, limit=None, raw_filters=None):
        if limit is None:
            limit = self.default_limit

        limit = int(limit)

        LOG.debug('Retrieving all trigger instances with filters=%s', raw_filters)
        return super(TriggerInstanceController, self)._get_all(sort=sort,
                                                               offset=offset,
                                                               limit=limit,
                                                               raw_filters=raw_filters)

triggertype_controller = TriggerTypeController()
trigger_controller = TriggerController()
triggerinstance_controller = TriggerInstanceController()
triggerinstance_resend_controller = TriggerInstanceResendController()


text:
package com.inbravo.jdk8.funcinterf;

/**
 *
 * @author amit.dixit
 *
 */
public final class ClassWithDefaultMethodUsage implements SubInterfaceWithMethod {

  @Override
  public double calculate(int a) {
    System.out.println("ClassWithDefaultMethodUsage.sqrt");
    return a * a;
  }

  public static final void main(final String... args) {

    /* Create all possible instances */
    final InterfaceWithMethod interfaceWithMethod = new ClassWithDefaultMethodUsage();
    final SubInterfaceWithMethod subInterfaceWithMethod = new ClassWithDefaultMethodUsage();
    final ClassWithDefaultMethodUsage classWithDefaultMethodUsage = new ClassWithDefaultMethodUsage();

    /* Call same method from all objects */
    interfaceWithMethod.sqrt(1);
    subInterfaceWithMethod.sqrt(1);
    classWithDefaultMethodUsage.sqrt(1);
  }
}

/**
 *
 * @author amit.dixit
 *
 */
interface SubInterfaceWithMethod extends InterfaceWithMethod {

  /**
   * This method will replace the super interface method
   */
  default double sqrt(final int a) {
    System.out.println("SubInterfaceWithMethod.sqrt");
    return Math.sqrt(a);
  }
}

/**
 *
 * @author amit.dixit
 *
 */
interface InterfaceWithMethod {

  double calculate(int a);

  default double sqrt(final int a) {
    System.out.println("InterfaceWithMethod.sqrt");
    return Math.sqrt(a);
  }
}

redpajama_set_name: RedPajamaGithub


text:
# react-rich-text-template
[![Travic CI](https://travis-ci.org/anmi/react-rich-text-template.svg?branch=master)](https://travis-ci.org/anmi/react-rich-text-template)

Text templates parameterized with react components

## Why?

Sometimes you need to insert components into strings comes from i18n module.

For example: "Hey, {username}, checkout your <profileLink>profile<profileLink>"

## Usage

```js
var rrtt = require('react-rich-text-template');

var template = rrtt.compile(
  "Hey, {username}, checkout your <profileLink>profile<profileLink>"
);

template({
  username: "anmi",
  profileLink: text => <profileLink>{text}</profileLink>
});
/*
["Hey, anmi, checkout your ", <profileLink>profile</profileLink>]
*/
```

You can redefine string wrapper and set key prop to speedup react elements merge
```jsx
var rrtt = require('react-rich-text-template');

var opts = Object.create(rrtt.defaultConfig);

opts.stringWrapper = (string, index) =>
  <span key={index}>{string}</span>

var template = rrtt.compile('template with<foo>multiple</foo>elems', opts)

template({
  foo: (children, index) =>
    <Foo key={index}>{children[0]}</Foo>
});
/* =>
[
  <span key=0>template with</span>,
  <Foo key=1>
    <span key=0>multiple</span>
  </Foo>
  <span key=2>elems</span>
]
*/
```

Define processMissingParam to handle missing params.
```jsx
var rrtt = require('react-rich-text-template');

var opts = Object.create(rrtt.defaultConfig);

opts.processMissingParam =
  function(paramName, children, index) {
    return <MissingTag>Missing tag: paramName</MissingTag>
  };

var template = rrtt.compile('Tag is <em>missing</em>');

template({});
/* =>
[
  'Tag is ',
  <MissingTag>Missing tag: em</MissingTag>
]
*/
```


text:
<!DOCTYPE html>

    <title>Chapter 12: "How They Matched the Fuddles" | The Emerald City of Oz | L. Frank Baum | Lit2Go ETC</title>
    <link rel="stylesheet" href="http://etc.usf.edu/lit2go/css/screenless.css" type="text/css" media="screen" title="no title" charset="utf-8">
    <link rel="stylesheet" href="http://etc.usf.edu/lit2go/css/printless.css" type="text/css" media="print" title="no title" charset="utf-8">

          Lit2Go

<form action="http://etc.usf.edu/lit2go/search/"><input type="text" name="q" placeholder="Search" value=""></form>

Authors

Books

Genres

Collections

Readability

      The Emerald City of Oz

      by L. Frank Baum

      Chapter 12: "How They Matched the Fuddles"

        Additional Information

            Year Published:
            1910

            Language:
            English

            Country of Origin:
            United States of America

            Source:
            Baum, L. F. (1910). The Emerald City of Oz. Chicago, IL: Reilly and Britton.

            Readability:

                Flesch–Kincaid Level:
                6.0

            Word Count:
            3,054

            Genre:
            Fantasy

            ✎ Cite This

  Share
  |

Downloads

          Audio

          Passage PDF

Student Activity

            APA

            MLA

            Chicago

            Baum, L. (1910). Chapter 12: "How They Matched the Fuddles". The Emerald City of Oz (Lit2Go Edition). Retrieved February 15, 2016, from http://etc.usf.edu/lit2go/123/the-emerald-city-of-oz/2149/chapter-12-how-they-matched-the-fuddles/

            Baum, L. Frank. "Chapter 12: "How They Matched the Fuddles"." The Emerald City of Oz. Lit2Go Edition. 1910. Web. <http://etc.usf.edu/lit2go/123/the-emerald-city-of-oz/2149/chapter-12-how-they-matched-the-fuddles/>. February 15, 2016.

            L. Frank Baum, "Chapter 12: "How They Matched the Fuddles"," The Emerald City of Oz, Lit2Go Edition, (1910), accessed February 15, 2016, http://etc.usf.edu/lit2go/123/the-emerald-city-of-oz/2149/chapter-12-how-they-matched-the-fuddles/.

Back

Next

                  <audio controls style="width:99%;">
            <source src="http://etc.usf.edu/lit2go/audio/mp3/the-emerald-city-of-oz-013-chapter-12-how-they-matched-the-fuddles.2149.mp3" type="audio/mpeg" />
                          <source src="http://etc.usf.edu/lit2go/audio/ogg/the-emerald-city-of-oz-013-chapter-12-how-they-matched-the-fuddles.2149.ogg" type="audio/ogg" />
                        The embedded audio player requires a modern internet browser. You should visit Browse Happy and update your internet browser today!
          </audio>

	Dorothy and her fellow travelers rode away from the Cuttenclip village and followed the indistinct path as far as the sign-post. Here they took the main road again and proceeded pleasantly through the pretty farming country. When evening came they stopped at a dwelling and were joyfully welcomed and given plenty to eat and good beds for the night.

	Early next morning, however, they were up and eager to start, and after a good breakfast they bade their host good-bye and climbed into the red wagon, to which the Sawhorse had been hitched all night. Being made of wood, this horse never got tired nor cared to lie down. Dorothy was not quite sure whether he ever slept or not, but it was certain that he never did when anybody was around.

	The weather is always beautiful in Oz, and this morning the air was cool and refreshing and the sunshine brilliant and delightful.

	In about an hour they came to a place where another road branched off. There was a sign-post here which read:

	THIS WAY TO FUDDLECUMJIG

	“Oh, here is where we turn,” said Dorothy, observing the sign.

	“What! Are we going to Fuddlecumjig?” asked the Captain General.

	“Yes; Ozma thought we might enjoy the Fuddles. They are said to be very interesting,” she replied.

	“No one would suspect it from their name,” said Aunt Em. “Who are they, anyhow? More paper things?”

	“I think not,” answered Dorothy, laughing; “but I can’t say ‘zactly, Aunt Em, what they are. We’ll find out when we get there.”

	“Perhaps the Wizard knows,” suggested Uncle Henry.

	“No; I’ve never been there before,” said the Wizard. “But I’ve often heard of Fuddlecumjig and the Fuddles, who are said to be the most peculiar people in all the Land of Oz.”

	“In what way?” asked the Shaggy Man.

	“I don’t know, I’m sure,” said the Wizard.

	Just then, as they rode along the pretty green lane toward Fuddlecumjig, they espied a kangaroo sitting by the roadside. The poor animal had its face covered with both its front paws and was crying so bitterly that the tears coursed down its cheeks in two tiny streams and trickled across the road, where they formed a pool in a small hollow.

	The Sawhorse stopped short at this pitiful sight, and Dorothy cried out, with ready sympathy:

	“What’s the matter, Kangaroo?”

	“Boo-hoo! Boo-hoo!” wailed the Kangaroo; “I’ve lost my mi—mi—mi—Oh, boo-hoo! Boo-hoo!”—

	“Poor thing,” said the Wizard, “she’s lost her mister. It’s probably her husband, and he’s dead.”

	“No, no, no!” sobbed the kangaroo. “It—it isn’t that. I’ve lost my mi—mi—Oh, boo, boo-hoo!”

	“I know,” said the Shaggy Man; “she’s lost her mirror.”

	“No; it’s my mi—mi—mi—Boo-hoo! My mi—Oh, Boo-hoo!” and the kangaroo cried harder than ever.

	“It must be her mince-pie,” suggested Aunt Em.

	“Or her milk-toast,” proposed Uncle Henry.

	“I’ve lost my mi—mi—mittens!” said the kangaroo, getting it out at last.

	“Oh!” cried the Yellow Hen, with a cackle of relief. “Why didn’t you say so before?”

	“Boo-hoo! I—I—couldn’t,” answered the kangaroo.

	“But, see here,” said Dorothy, “you don’t need mittens in this warm weather.”

	“Yes, indeed I do,” replied the animal, stopping her sobs and removing her paws from her face to look at the little girl reproachfully. “My hands will get all sunburned and tanned without my mittens, and I’ve worn them so long that I’ll probably catch cold without them.”

	“Nonsense!” said Dorothy. “I never heard of any kangaroo wearing mittens.”

	“Didn’t you?” asked the animal, as if surprised.

	“Never!” repeated the girl. “And you’ll probably make yourself sick if you don’t stop crying. Where do you live?”

	“About two miles beyond Fuddlecumjig,” was the answer. “Grandmother Gnit made me the mittens, and she’s one of the Fuddles.”

	“Well, you’d better go home now, and perhaps the old lady will make you another pair,” suggested Dorothy. “We’re on our way to Fuddlecumjig, and you may hop along beside us.”

	So they rode on, and the kangaroo hopped beside the red wagon and seemed quickly to have forgotten her loss. By and by the Wizard said to the animal:

	“Are the Fuddles nice people?”

	“Oh, very nice,” answered the kangaroo; “that is, when they’re properly put together. But they get dreadfully scattered and mixed up, at times, and then you can’t do anything with them.”

	“What do you mean by their getting scattered?” inquired Dorothy.

	“Why, they’re made in a good many small pieces,” explained the kangaroo; “and whenever any stranger comes near them they have a habit of falling apart and scattering themselves around. That’s when they get so dreadfully mixed, and it’s a hard puzzle to put them together again.”

	“Who usually puts them together?” asked Omby Amby.

	“Any one who is able to match the pieces. I sometimes put Grandmother Gnit together myself, because I know her so well I can tell every piece that belongs to her. Then, when she’s all matched, she knits for me, and that’s how she made my mittens. But it took a good many days hard knitting, and I had to put Grandmother together a good many times, because every time I came near, she’d scatter herself.”

	“I should think she would get used to your coming, and not be afraid,” said Dorothy.

	“It isn’t that,” replied the kangaroo. “They’re not a bit afraid, when they’re put together, and usually they’re very jolly and pleasant. It’s just a habit they have, to scatter themselves, and if they didn’t do it they wouldn’t be Fuddles.”

	The travelers thought upon this quite seriously for a time, while the Sawhorse continued to carry them rapidly forward. Then Aunt Em remarked:

	“I don’t see much use our visitin’ these Fuddles. If we find them scattered, all we can do is to sweep ‘em up, and then go about our business.”

	“Oh, I b’lieve we’d better go on,” replied Dorothy. “I’m getting hungry, and we must try to get some luncheon at Fuddlecumjig. Perhaps the food won’t be scattered as badly as the people.”

	“You’ll find plenty to eat there,” declared the kangaroo, hopping along in big bounds because the Sawhorse was going so fast; “and they have a fine cook, too, if you can manage to put him together. There’s the town now—just ahead of us!”

	They looked ahead and saw a group of very pretty houses standing in a green field a little apart from the main road.

	“Some Munchkins came here a few days ago and matched a lot of people together,” said the kangaroo. “I think they are together yet, and if you go softly, without making any noise, perhaps they won’t scatter.”

	“Let’s try it,” suggested the Wizard.

	So they stopped the Sawhorse and got out of the wagon, and, after bidding good bye to the kangaroo, who hopped away home, they entered the field and very cautiously approached the group of houses.

	So silently did they move that soon they saw through the windows of the houses, people moving around, while others were passing to and fro in the yards between the buildings. They seemed much like other people from a distance, and apparently they did not notice the little party so quietly approaching.

	They had almost reached the nearest house when Toto saw a large beetle crossing the path and barked loudly at it. Instantly a wild clatter was heard from the houses and yards. Dorothy thought it sounded like a sudden hailstorm, and the visitors, knowing that caution was no longer necessary, hurried forward to see what had happened.

	After the clatter an intense stillness reigned in the town. The strangers entered the first house they came to, which was also the largest, and found the floor strewn with pieces of the people who lived there. They looked much like fragments of wood neatly painted, and were of all sorts of curious and fantastic shapes, no two pieces being in any way alike.

	They picked up some of these pieces and looked at them carefully. On one which Dorothy held was an eye, which looked at her pleasantly but with an interested expression, as if it wondered what she was going to do with it. Quite near by she discovered and picked up a nose, and by matching the two pieces together found that they were part of a face.

	“If I could find the mouth,” she said, “this Fuddle might be able to talk, and tell us what to do next.”

	“Then let us find it,” replied the Wizard, and so all got down on their hands and knees and began examining the scattered pieces.

	“I’ve found it!” cried the Shaggy Man, and ran to Dorothy with an odd-shaped piece that had a mouth on it. But when they tried to fit it to the eye and nose they found the parts wouldn’t match together.

	“That mouth belongs to some other person,” said Dorothy. “You see we need a curve here and a point there, to make it fit the face.”

	“Well, it must be here some place,” declared the Wizard; “so if we search long enough we shall find it.”

	Dorothy fitted an ear on next, and the ear had a little patch of red hair above it. So while the others were searching for the mouth she hunted for pieces with red hair, and found several of them which, when matched to the other pieces, formed the top of a man’s head. She had also found the other eye and the ear by the time Omby Amby in a far corner discovered the mouth. When the face was thus completed, all the parts joined together with a nicety that was astonishing.

	“Why, it’s like a picture puzzle!” exclaimed the little girl. “Let’s find the rest of him, and get him all together.”

	“What’s the rest of him like?” asked the Wizard. “Here are some pieces of blue legs and green arms, but I don’t know whether they are his or not.”

	“Look for a white shirt and a white apron,” said the head which had been put together, speaking in a rather faint voice. “I’m the cook.”

	“Oh, thank you,” said Dorothy. “It’s lucky we started you first, for I’m hungry, and you can be cooking something for us to eat while we match the other folks together.”

	It was not so very difficult, now that they had a hint as to how the man was dressed, to find the other pieces belonging to him, and as all of them now worked on the cook, trying piece after piece to see if it would fit, they finally had the cook set up complete.

	When he was finished he made them a low bow and said:

	“I will go at once to the kitchen to prepare your dinner. You will find it something of a job to get all the Fuddles together, so I advise you to begin on the Lord High Chigglewitz, whose first name is Larry. He’s a bald-headed fat man and is dressed in a blue coat with brass buttons, a pink vest and drab breeches. A piece of his left knee is missing, having been lost years ago when he scattered himself too carelessly. That makes him limp a little, but he gets along very well with half a knee. As he is the chief personage in this town of Fuddlecumjig, he will be able to welcome you and assist you with the others. So it will be best to work on him while I’m getting your dinner.”

	“We will,” said the Wizard; “and thank you very much, Cook, for the suggestion.”

	Aunt Em was the first to discover a piece of the Lord High Chigglewitz.

	“It seems to me like a fool business, this matching folks together,” she remarked; “but as we haven’t anything to do till dinner’s ready, we may as well get rid of some of this rubbish. Here, Henry, get busy and look for Larry’s bald head. I’ve got his pink vest, all right.”

	They worked with eager interest, and Billina proved a great help to them. The Yellow Hen had sharp eyes and could put her head close to the various pieces that lay scattered around. She would examine the Lord High Chigglewitz and see which piece of him was next needed, and then hunt around until she found it. So before an hour had passed old Larry was standing complete before them.

	“I congratulate you, my friends,” he said, speaking in a cheerful voice. “You are certainly the cleverest people who ever visited us. I was never matched together so quickly in my life. I’m considered a great puzzle, usually.”

	“Well,” said Dorothy, “there used to be a picture puzzle craze in Kansas, and so I’ve had some ‘sperience matching puzzles. But the pictures were flat, while you are round, and that makes you harder to figure out.”

	“Thank you, my dear,” replied old Larry, greatly pleased. “I feel highly complimented. Were I not a really good puzzle, there would be no object in my scattering myself.”

	“Why do you do it?” asked Aunt Em, severely. “Why don’t you behave yourself, and stay put together?”

	The Lord High Chigglewitz seemed annoyed by this speech; but he replied, politely:

	“Madam, you have perhaps noticed that every person has some peculiarity. Mine is to scatter myself. What your own peculiarity is I will not venture to say; but I shall never find fault with you, whatever you do.”

	“Now you’ve got your diploma, Em,” said Uncle Henry, with a laugh, “and I’m glad of it. This is a strange country, and we may as well take people as we find them.”

	“If we did, we’d leave these folks scattered,” she returned, and this retort made everybody laugh good-naturedly.

	Just then Omby Amby found a hand with a knitting needle in it, and they decided to put Grandmother Gnit together. She proved an easier puzzle than old Larry, and when she was completed they found her a pleasant old lady who welcomed them cordially. Dorothy told her how the kangaroo had lost her mittens, and Grandmother Gnit promised to set to work at once and make the poor animal another pair.

	Then the cook came to call them to dinner, and they found an inviting meal prepared for them. The Lord High Chigglewitz sat at the head of the table and Grandmother Gnit at the foot, and the guests had a merry time and thoroughly enjoyed themselves.

	After dinner they went out into the yard and matched several other people together, and this work was so interesting that they might have spent the entire day at Fuddlecumjig had not the Wizard suggested that they resume their journey.

	“But I don’t like to leave all these poor people scattered,” said Dorothy, undecided what to do.

	“Oh, don’t mind us, my dear,” returned old Larry. “Every day or so some of the Gillikins, or Munchkins, or Winkies come here to amuse themselves by matching us together, so there will be no harm in leaving these pieces where they are for a time. But I hope you will visit us again, and if you do you will always be welcome, I assure you.”

	“Don’t you ever match each other?” she inquired.

	“Never; for we are no puzzles to ourselves, and so there wouldn’t be any fun in it.”

	They now said goodbye to the strange Fuddles and got into their wagon to continue their journey.

	“Those are certainly strange people,” remarked Aunt Em, thoughtfully, as they drove away from Fuddlecumjig, “but I really can’t see what use they are, at all.”

	“Why, they amused us all for several hours,” replied the Wizard. “That is being of use to us, I’m sure.”

	“I think they’re more fun than playing solitaire or mumbletypeg,” declared Uncle Henry, soberly. “For my part, I’m glad we visited the Fuddles.”

Back

Next

            This collection of children's literature is a part of the Educational Technology Clearinghouse and is funded by various grants.

            Copyright © 2006—2016 by the Florida Center for Instructional Technology, College of Education, University of South Florida.

License

Credits

FAQ

Giving

This document was downloaded from Lit2Go, a free online collection of stories and poems in Mp3 (audiobook) format published by the Florida Center for Instructional Technology. For more information, including classroom activities, readability data, and original sources, please visit http://etc.usf.edu/lit2go/123/the-emerald-city-of-oz/2149/chapter-12-how-they-matched-the-fuddles/.

Lit2Go: The Emerald City of Oz

Chapter 12: "How They Matched the Fuddles"


text:
require 'wongi-engine/beta/beta_node'
require 'wongi-engine/beta/root_node'
require 'wongi-engine/beta/filter_node'
require 'wongi-engine/beta/assignment_node'
require 'wongi-engine/beta/join_node'
require 'wongi-engine/beta/aggregate_node'
require 'wongi-engine/beta/ncc_partner'
require 'wongi-engine/beta/ncc_node'
require 'wongi-engine/beta/neg_node'
require 'wongi-engine/beta/optional_node'
require 'wongi-engine/beta/or_node'
require 'wongi-engine/beta/production_node'


text:
package webrtc

// DataChannelMessage represents a message received from the
// data channel. IsString will be set to true if the incoming
// message is of the string type. Otherwise the message is of
// a binary type.
type DataChannelMessage struct {
	IsString bool
	Data     []byte
}


text:
// Copyright (C) 2008  Davis E. King (davis@dlib.net), Steve Taylor
// License: Boost Software License   See LICENSE.txt for the full license.
#ifndef DLIB_STATISTICs_
#define DLIB_STATISTICs_

#include "statistics_abstract.h"
#include <limits>
#include <cmath>
#include "../algs.h"
#include "../matrix.h"
#include "../sparse_vector.h"

namespace dlib
{

// ----------------------------------------------------------------------------------------

    template <
        typename T
        >
    class running_stats
    {
    public:

        running_stats()
        {
            clear();

            COMPILE_TIME_ASSERT ((
                    is_same_type<float,T>::value ||
                    is_same_type<double,T>::value ||
                    is_same_type<long double,T>::value
            ));
        }

        void clear()
        {
            sum = 0;
            sum_sqr  = 0;
            sum_cub  = 0;
            sum_four = 0;

            n = 0;
            min_value = std::numeric_limits<T>::infinity();
            max_value = -std::numeric_limits<T>::infinity();
        }

        void add (
            const T& val
        )
        {
            sum      += val;
            sum_sqr  += val*val;
            sum_cub  += cubed(val);
            sum_four += quaded(val);

            if (val < min_value)
                min_value = val;
            if (val > max_value)
                max_value = val;

            ++n;
        }

        T current_n (
        ) const
        {
            return n;
        }

        T mean (
        ) const
        {
            if (n != 0)
                return sum/n;
            else
                return 0;
        }

        T max (
        ) const
        {
            // make sure requires clause is not broken
            DLIB_ASSERT(current_n() > 0,
                "\tT running_stats::max"
                << "\n\tyou have to add some numbers to this object first"
                << "\n\tthis: " << this
                );

            return max_value;
        }

        T min (
        ) const
        {
            // make sure requires clause is not broken
            DLIB_ASSERT(current_n() > 0,
                "\tT running_stats::min"
                << "\n\tyou have to add some numbers to this object first"
                << "\n\tthis: " << this
                );

            return min_value;
        }

        T variance (
        ) const
        {
            // make sure requires clause is not broken
            DLIB_ASSERT(current_n() > 1,
                "\tT running_stats::variance"
                << "\n\tyou have to add some numbers to this object first"
                << "\n\tthis: " << this
                );

            T temp = 1/(n-1);
            temp = temp*(sum_sqr - sum*sum/n);
            // make sure the variance is never negative.  This might
            // happen due to numerical errors.
            if (temp >= 0)
                return temp;
            else
                return 0;
        }

        T stddev (
        ) const
        {
            // make sure requires clause is not broken
            DLIB_ASSERT(current_n() > 1,
                "\tT running_stats::stddev"
                << "\n\tyou have to add some numbers to this object first"
                << "\n\tthis: " << this
                );

            return std::sqrt(variance());
        }

        T skewness (
        ) const
        {
            // make sure requires clause is not broken
            DLIB_ASSERT(current_n() > 2,
                "\tT running_stats::skewness"
                << "\n\tyou have to add some numbers to this object first"
                << "\n\tthis: " << this
            );

            T temp  = 1/n;
            T temp1 = std::sqrt(n*(n-1))/(n-2);
            temp    = temp1*temp*(sum_cub - 3*sum_sqr*sum*temp + 2*cubed(sum)*temp*temp)/
                      (std::sqrt(std::pow(temp*(sum_sqr-sum*sum*temp),3)));

            return temp;
        }

        T ex_kurtosis (
        ) const
        {
            // make sure requires clause is not broken
            DLIB_ASSERT(current_n() > 3,
                "\tT running_stats::kurtosis"
                << "\n\tyou have to add some numbers to this object first"
                << "\n\tthis: " << this
            );

            T temp = 1/n;
            T m4   = temp*(sum_four - 4*sum_cub*sum*temp+6*sum_sqr*sum*sum*temp*temp
                     -3*quaded(sum)*cubed(temp));
            T m2   = temp*(sum_sqr-sum*sum*temp);
            temp   = (n-1)*((n+1)*m4/(m2*m2)-3*(n-1))/((n-2)*(n-3));

            return temp;
        }

        T scale (
            const T& val
        ) const
        {
            // make sure requires clause is not broken
            DLIB_ASSERT(current_n() > 1,
                "\tT running_stats::variance"
                << "\n\tyou have to add some numbers to this object first"
                << "\n\tthis: " << this
                );
            return (val-mean())/std::sqrt(variance());
        }

        running_stats operator+ (
            const running_stats& rhs
        ) const
        {
            running_stats temp(*this);

            temp.sum += rhs.sum;
            temp.sum_sqr += rhs.sum_sqr;
            temp.sum_cub += rhs.sum_cub;
            temp.sum_four += rhs.sum_four;
            temp.n += rhs.n;
            temp.min_value = std::min(rhs.min_value, min_value);
            temp.max_value = std::max(rhs.max_value, max_value);
            return temp;
        }

        template <typename U>
        friend void serialize (
            const running_stats<U>& item,
            std::ostream& out
        );

        template <typename U>
        friend void deserialize (
            running_stats<U>& item,
            std::istream& in
        );

    private:
        T sum;
        T sum_sqr;
        T sum_cub;
        T sum_four;
        T n;
        T min_value;
        T max_value;

        T cubed  (const T& val) const {return val*val*val; }
        T quaded (const T& val) const {return val*val*val*val; }
    };

    template <typename T>
    void serialize (
        const running_stats<T>& item,
        std::ostream& out
    )
    {
        int version = 2;
        serialize(version, out);

        serialize(item.sum, out);
        serialize(item.sum_sqr, out);
        serialize(item.sum_cub, out);
        serialize(item.sum_four, out);
        serialize(item.n, out);
        serialize(item.min_value, out);
        serialize(item.max_value, out);
    }

    template <typename T>
    void deserialize (
        running_stats<T>& item,
        std::istream& in
    )
    {
        int version = 0;
        deserialize(version, in);
        if (version != 2)
            throw dlib::serialization_error("Unexpected version number found while deserializing dlib::running_stats object.");

        deserialize(item.sum, in);
        deserialize(item.sum_sqr, in);
        deserialize(item.sum_cub, in);
        deserialize(item.sum_four, in);
        deserialize(item.n, in);
        deserialize(item.min_value, in);
        deserialize(item.max_value, in);
    }

// ----------------------------------------------------------------------------------------

    template <
        typename T
        >
    class running_scalar_covariance
    {
    public:

        running_scalar_covariance()
        {
            clear();

            COMPILE_TIME_ASSERT ((
                    is_same_type<float,T>::value ||
                    is_same_type<double,T>::value ||
                    is_same_type<long double,T>::value
            ));
        }

        void clear()
        {
            sum_xy = 0;
            sum_x = 0;
            sum_y = 0;
            sum_xx = 0;
            sum_yy = 0;
            n = 0;
        }

        void add (
            const T& x,
            const T& y
        )
        {
            sum_xy += x*y;

            sum_xx += x*x;
            sum_yy += y*y;

            sum_x  += x;
            sum_y  += y;

            n += 1;
        }

        T current_n (
        ) const
        {
            return n;
        }

        T mean_x (
        ) const
        {
            if (n != 0)
                return sum_x/n;
            else
                return 0;
        }

        T mean_y (
        ) const
        {
            if (n != 0)
                return sum_y/n;
            else
                return 0;
        }

        T covariance (
        ) const
        {
            // make sure requires clause is not broken
            DLIB_ASSERT(current_n() > 1,
                "\tT running_scalar_covariance::covariance()"
                << "\n\tyou have to add some numbers to this object first"
                << "\n\tthis: " << this
                );

            return 1/(n-1) * (sum_xy - sum_y*sum_x/n);
        }

        T correlation (
        ) const
        {
            // make sure requires clause is not broken
            DLIB_ASSERT(current_n() > 1,
                "\tT running_scalar_covariance::correlation()"
                << "\n\tyou have to add some numbers to this object first"
                << "\n\tthis: " << this
                );

            return covariance() / std::sqrt(variance_x()*variance_y());
        }

        T variance_x (
        ) const
        {
            // make sure requires clause is not broken
            DLIB_ASSERT(current_n() > 1,
                "\tT running_scalar_covariance::variance_x()"
                << "\n\tyou have to add some numbers to this object first"
                << "\n\tthis: " << this
                );

            T temp = 1/(n-1) * (sum_xx - sum_x*sum_x/n);
            // make sure the variance is never negative.  This might
            // happen due to numerical errors.
            if (temp >= 0)
                return temp;
            else
                return 0;
        }

        T variance_y (
        ) const
        {
            // make sure requires clause is not broken
            DLIB_ASSERT(current_n() > 1,
                "\tT running_scalar_covariance::variance_y()"
                << "\n\tyou have to add some numbers to this object first"
                << "\n\tthis: " << this
                );

            T temp = 1/(n-1) * (sum_yy - sum_y*sum_y/n);
            // make sure the variance is never negative.  This might
            // happen due to numerical errors.
            if (temp >= 0)
                return temp;
            else
                return 0;
        }

        T stddev_x (
        ) const
        {
            // make sure requires clause is not broken
            DLIB_ASSERT(current_n() > 1,
                "\tT running_scalar_covariance::stddev_x()"
                << "\n\tyou have to add some numbers to this object first"
                << "\n\tthis: " << this
                );

            return std::sqrt(variance_x());
        }

        T stddev_y (
        ) const
        {
            // make sure requires clause is not broken
            DLIB_ASSERT(current_n() > 1,
                "\tT running_scalar_covariance::stddev_y()"
                << "\n\tyou have to add some numbers to this object first"
                << "\n\tthis: " << this
                );

            return std::sqrt(variance_y());
        }

        running_scalar_covariance operator+ (
            const running_scalar_covariance& rhs
        ) const
        {
            running_scalar_covariance temp(rhs);

            temp.sum_xy += sum_xy;
            temp.sum_x  += sum_x;
            temp.sum_y  += sum_y;
            temp.sum_xx += sum_xx;
            temp.sum_yy += sum_yy;
            temp.n      += n;
            return temp;
        }

    private:

        T sum_xy;
        T sum_x;
        T sum_y;
        T sum_xx;
        T sum_yy;
        T n;
    };

// ----------------------------------------------------------------------------------------

    template <
        typename T,
        typename alloc
        >
    double mean_sign_agreement (
        const std::vector<T,alloc>& a,
        const std::vector<T,alloc>& b
    )
    {
        // make sure requires clause is not broken
        DLIB_ASSERT(a.size() == b.size(),
                    "\t double mean_sign_agreement(a,b)"
                    << "\n\t a and b must be the same length."
                    << "\n\t a.size(): " << a.size()
                    << "\n\t b.size(): " << b.size()
        );

        double temp = 0;
        for (unsigned long i = 0; i < a.size(); ++i)
        {
            if ((a[i] >= 0 && b[i] >= 0) ||
                (a[i] < 0  && b[i] <  0))
            {
                temp += 1;
            }
        }

        return temp/a.size();
    }

// ----------------------------------------------------------------------------------------

    template <
        typename T,
        typename alloc
        >
    double correlation (
        const std::vector<T,alloc>& a,
        const std::vector<T,alloc>& b
    )
    {
        // make sure requires clause is not broken
        DLIB_ASSERT(a.size() == b.size() && a.size() > 1,
                    "\t double correlation(a,b)"
                    << "\n\t a and b must be the same length and have more than one element."
                    << "\n\t a.size(): " << a.size()
                    << "\n\t b.size(): " << b.size()
        );

        running_scalar_covariance<double> rs;
        for (unsigned long i = 0; i < a.size(); ++i)
        {
            rs.add(a[i], b[i]);
        }
        return rs.correlation();
    }

// ----------------------------------------------------------------------------------------

    template <
        typename T,
        typename alloc
        >
    double covariance (
        const std::vector<T,alloc>& a,
        const std::vector<T,alloc>& b
    )
    {
        // make sure requires clause is not broken
        DLIB_ASSERT(a.size() == b.size() && a.size() > 1,
                    "\t double covariance(a,b)"
                    << "\n\t a and b must be the same length and have more than one element."
                    << "\n\t a.size(): " << a.size()
                    << "\n\t b.size(): " << b.size()
        );

        running_scalar_covariance<double> rs;
        for (unsigned long i = 0; i < a.size(); ++i)
        {
            rs.add(a[i], b[i]);
        }
        return rs.covariance();
    }

// ----------------------------------------------------------------------------------------

    template <
        typename T,
        typename alloc
        >
    double r_squared (
        const std::vector<T,alloc>& a,
        const std::vector<T,alloc>& b
    )
    {
        // make sure requires clause is not broken
        DLIB_ASSERT(a.size() == b.size() && a.size() > 1,
                    "\t double r_squared(a,b)"
                    << "\n\t a and b must be the same length and have more than one element."
                    << "\n\t a.size(): " << a.size()
                    << "\n\t b.size(): " << b.size()
        );

        return std::pow(correlation(a,b),2.0);
    }

// ----------------------------------------------------------------------------------------

    template <
        typename T,
        typename alloc
        >
    double mean_squared_error (
        const std::vector<T,alloc>& a,
        const std::vector<T,alloc>& b
    )
    {
        // make sure requires clause is not broken
        DLIB_ASSERT(a.size() == b.size(),
                    "\t double mean_squared_error(a,b)"
                    << "\n\t a and b must be the same length."
                    << "\n\t a.size(): " << a.size()
                    << "\n\t b.size(): " << b.size()
        );

        return mean(squared(matrix_cast<double>(mat(a))-matrix_cast<double>(mat(b))));
    }

// ----------------------------------------------------------------------------------------

    template <
        typename matrix_type
        >
    class running_covariance
    {
        /*!
            INITIAL VALUE
                - vect_size == 0
                - total_count == 0

            CONVENTION
                - vect_size == in_vector_size()
                - total_count == current_n()

                - if (total_count != 0)
                    - total_sum == the sum of all vectors given to add()
                    - the covariance of all the elements given to add() is given
                      by:
                        - let avg == total_sum/total_count
                        - covariance == total_cov/total_count - avg*trans(avg)
        !*/
    public:

        typedef typename matrix_type::mem_manager_type mem_manager_type;
        typedef typename matrix_type::type scalar_type;
        typedef typename matrix_type::layout_type layout_type;
        typedef matrix<scalar_type,0,0,mem_manager_type,layout_type> general_matrix;
        typedef matrix<scalar_type,0,1,mem_manager_type,layout_type> column_matrix;

        running_covariance(
        )
        {
            clear();
        }

        void clear(
        )
        {
            total_count = 0;

            vect_size = 0;

            total_sum.set_size(0);
            total_cov.set_size(0,0);
        }

        long in_vector_size (
        ) const
        {
            return vect_size;
        }

        long current_n (
        ) const
        {
            return static_cast<long>(total_count);
        }

        void set_dimension (
            long size
        )
        {
            // make sure requires clause is not broken
            DLIB_ASSERT( size > 0,
                "\t void running_covariance::set_dimension()"
                << "\n\t Invalid inputs were given to this function"
                << "\n\t size: " << size
                << "\n\t this: " << this
                );

            clear();
            vect_size = size;
            total_sum.set_size(size);
            total_cov.set_size(size,size);
            total_sum = 0;
            total_cov = 0;
        }

        template <typename T>
        typename disable_if<is_matrix<T> >::type add (
            const T& val
        )
        {
            // make sure requires clause is not broken
            DLIB_ASSERT(((long)max_index_plus_one(val) <= in_vector_size() && in_vector_size() > 0),
                "\t void running_covariance::add()"
                << "\n\t Invalid inputs were given to this function"
                << "\n\t max_index_plus_one(val): " << max_index_plus_one(val)
                << "\n\t in_vector_size():        " << in_vector_size()
                << "\n\t this:                    " << this
                );

            for (typename T::const_iterator i = val.begin(); i != val.end(); ++i)
            {
                total_sum(i->first) += i->second;
                for (typename T::const_iterator j = val.begin(); j != val.end(); ++j)
                {
                    total_cov(i->first, j->first) += i->second*j->second;
                }
            }

            ++total_count;
        }

        template <typename T>
        typename enable_if<is_matrix<T> >::type add (
            const T& val
        )
        {
            // make sure requires clause is not broken
            DLIB_ASSERT(is_col_vector(val) && (in_vector_size() == 0 || val.size() == in_vector_size()),
                "\t void running_covariance::add()"
                << "\n\t Invalid inputs were given to this function"
                << "\n\t is_col_vector(val): " << is_col_vector(val)
                << "\n\t in_vector_size():   " << in_vector_size()
                << "\n\t val.size():         " << val.size()
                << "\n\t this:               " << this
                );

            vect_size = val.size();
            if (total_count == 0)
            {
                total_cov = val*trans(val);
                total_sum = val;
            }
            else
            {
                total_cov += val*trans(val);
                total_sum += val;
            }
            ++total_count;
        }

        const column_matrix mean (
        ) const
        {
            // make sure requires clause is not broken
            DLIB_ASSERT( in_vector_size() != 0,
                "\t running_covariance::mean()"
                << "\n\t This object can not execute this function in its current state."
                << "\n\t in_vector_size(): " << in_vector_size()
                << "\n\t current_n():      " << current_n()
                << "\n\t this:             " << this
                );

            return total_sum/total_count;
        }

        const general_matrix covariance (
        ) const
        {
            // make sure requires clause is not broken
            DLIB_ASSERT( in_vector_size() != 0 && current_n() > 1,
                "\t running_covariance::covariance()"
                << "\n\t This object can not execute this function in its current state."
                << "\n\t in_vector_size(): " << in_vector_size()
                << "\n\t current_n():      " << current_n()
                << "\n\t this:             " << this
                );

            return (total_cov - total_sum*trans(total_sum)/total_count)/(total_count-1);
        }

        const running_covariance operator+ (
            const running_covariance& item
        ) const
        {
            // make sure requires clause is not broken
            DLIB_ASSERT((in_vector_size() == 0 || item.in_vector_size() == 0 || in_vector_size() == item.in_vector_size()),
                "\t running_covariance running_covariance::operator+()"
                << "\n\t The two running_covariance objects being added must have compatible parameters"
                << "\n\t in_vector_size():            " << in_vector_size()
                << "\n\t item.in_vector_size():       " << item.in_vector_size()
                << "\n\t this:                        " << this
                );

            running_covariance temp(item);

            // make sure we ignore empty matrices
            if (total_count != 0 && temp.total_count != 0)
            {
                temp.total_cov += total_cov;
                temp.total_sum += total_sum;
                temp.total_count += total_count;
            }
            else if (total_count != 0)
            {
                temp.total_cov = total_cov;
                temp.total_sum = total_sum;
                temp.total_count = total_count;
            }

            return temp;
        }

    private:

        general_matrix total_cov;
        column_matrix total_sum;
        scalar_type total_count;

        long vect_size;
    };

// ----------------------------------------------------------------------------------------

    template <
        typename matrix_type
        >
    class running_cross_covariance
    {
        /*!
            INITIAL VALUE
                - x_vect_size == 0
                - y_vect_size == 0
                - total_count == 0

            CONVENTION
                - x_vect_size == x_vector_size()
                - y_vect_size == y_vector_size()
                - total_count == current_n()

                - if (total_count != 0)
                    - sum_x == the sum of all x vectors given to add()
                    - sum_y == the sum of all y vectors given to add()
                    - total_cov == sum of all x*trans(y) given to add()
        !*/

    public:

        typedef typename matrix_type::mem_manager_type mem_manager_type;
        typedef typename matrix_type::type scalar_type;
        typedef typename matrix_type::layout_type layout_type;
        typedef matrix<scalar_type,0,0,mem_manager_type,layout_type> general_matrix;
        typedef matrix<scalar_type,0,1,mem_manager_type,layout_type> column_matrix;

        running_cross_covariance(
        )
        {
            clear();
        }

        void clear(
        )
        {
            total_count = 0;

            x_vect_size = 0;
            y_vect_size = 0;

            sum_x.set_size(0);
            sum_y.set_size(0);
            total_cov.set_size(0,0);
        }

        long x_vector_size (
        ) const
        {
            return x_vect_size;
        }

        long y_vector_size (
        ) const
        {
            return y_vect_size;
        }

        void set_dimensions (
            long x_size,
            long y_size
        )
        {
            // make sure requires clause is not broken
            DLIB_ASSERT( x_size > 0 && y_size > 0,
                "\t void running_cross_covariance::set_dimensions()"
                << "\n\t Invalid inputs were given to this function"
                << "\n\t x_size: " << x_size
                << "\n\t y_size: " << y_size
                << "\n\t this:   " << this
                );

            clear();
            x_vect_size = x_size;
            y_vect_size = y_size;
            sum_x.set_size(x_size);
            sum_y.set_size(y_size);
            total_cov.set_size(x_size,y_size);

            sum_x = 0;
            sum_y = 0;
            total_cov = 0;
        }

        long current_n (
        ) const
        {
            return static_cast<long>(total_count);
        }

        template <typename T, typename U>
        typename enable_if_c<!is_matrix<T>::value && !is_matrix<U>::value>::type add (
            const T& x,
            const U& y
        )
        {
            // make sure requires clause is not broken
            DLIB_ASSERT( ((long)max_index_plus_one(x) <= x_vector_size() && x_vector_size() > 0) &&
                         ((long)max_index_plus_one(y) <= y_vector_size() && y_vector_size() > 0) ,
                "\t void running_cross_covariance::add()"
                << "\n\t Invalid inputs were given to this function"
                << "\n\t max_index_plus_one(x): " << max_index_plus_one(x)
                << "\n\t max_index_plus_one(y): " << max_index_plus_one(y)
                << "\n\t x_vector_size():       " << x_vector_size()
                << "\n\t y_vector_size():       " << y_vector_size()
                << "\n\t this:                  " << this
                );

            for (typename T::const_iterator i = x.begin(); i != x.end(); ++i)
            {
                sum_x(i->first) += i->second;
                for (typename U::const_iterator j = y.begin(); j != y.end(); ++j)
                {
                    total_cov(i->first, j->first) += i->second*j->second;
                }
            }

            // do sum_y += y
            for (typename U::const_iterator j = y.begin(); j != y.end(); ++j)
            {
                sum_y(j->first) += j->second;
            }

            ++total_count;
        }

        template <typename T, typename U>
        typename enable_if_c<is_matrix<T>::value && !is_matrix<U>::value>::type add (
            const T& x,
            const U& y
        )
        {
            // make sure requires clause is not broken
            DLIB_ASSERT( (is_col_vector(x) && x.size() == x_vector_size() && x_vector_size() > 0) &&
                         ((long)max_index_plus_one(y) <= y_vector_size() && y_vector_size() > 0) ,
                "\t void running_cross_covariance::add()"
                << "\n\t Invalid inputs were given to this function"
                << "\n\t is_col_vector(x):      " << is_col_vector(x)
                << "\n\t x.size():              " << x.size()
                << "\n\t max_index_plus_one(y): " << max_index_plus_one(y)
                << "\n\t x_vector_size():       " << x_vector_size()
                << "\n\t y_vector_size():       " << y_vector_size()
                << "\n\t this:                  " << this
                );

            sum_x += x;

            for (long i = 0; i < x.size(); ++i)
            {
                for (typename U::const_iterator j = y.begin(); j != y.end(); ++j)
                {
                    total_cov(i, j->first) += x(i)*j->second;
                }
            }

            // do sum_y += y
            for (typename U::const_iterator j = y.begin(); j != y.end(); ++j)
            {
                sum_y(j->first) += j->second;
            }

            ++total_count;
        }

        template <typename T, typename U>
        typename enable_if_c<!is_matrix<T>::value && is_matrix<U>::value>::type add (
            const T& x,
            const U& y
        )
        {
            // make sure requires clause is not broken
            DLIB_ASSERT( ((long)max_index_plus_one(x) <= x_vector_size() && x_vector_size() > 0) &&
                         (is_col_vector(y) && y.size() == (long)y_vector_size() && y_vector_size() > 0) ,
                "\t void running_cross_covariance::add()"
                << "\n\t Invalid inputs were given to this function"
                << "\n\t max_index_plus_one(x): " << max_index_plus_one(x)
                << "\n\t is_col_vector(y):      " << is_col_vector(y)
                << "\n\t y.size():              " << y.size()
                << "\n\t x_vector_size():       " << x_vector_size()
                << "\n\t y_vector_size():       " << y_vector_size()
                << "\n\t this:                  " << this
                );

            for (typename T::const_iterator i = x.begin(); i != x.end(); ++i)
            {
                sum_x(i->first) += i->second;
                for (long j = 0; j < y.size(); ++j)
                {
                    total_cov(i->first, j) += i->second*y(j);
                }
            }

            sum_y += y;

            ++total_count;
        }

        template <typename T, typename U>
        typename enable_if_c<is_matrix<T>::value && is_matrix<U>::value>::type add (
            const T& x,
            const U& y
        )
        {
            // make sure requires clause is not broken
            DLIB_ASSERT(is_col_vector(x) && (x_vector_size() == 0 || x.size() == x_vector_size()) &&
                        is_col_vector(y) && (y_vector_size() == 0 || y.size() == y_vector_size()) &&
                        x.size() != 0 &&
                        y.size() != 0,
                "\t void running_cross_covariance::add()"
                << "\n\t Invalid inputs were given to this function"
                << "\n\t is_col_vector(x): " << is_col_vector(x)
                << "\n\t x_vector_size():  " << x_vector_size()
                << "\n\t x.size():         " << x.size()
                << "\n\t is_col_vector(y): " << is_col_vector(y)
                << "\n\t y_vector_size():  " << y_vector_size()
                << "\n\t y.size():         " << y.size()
                << "\n\t this:             " << this
                );

            x_vect_size = x.size();
            y_vect_size = y.size();
            if (total_count == 0)
            {
                total_cov = x*trans(y);
                sum_x = x;
                sum_y = y;
            }
            else
            {
                total_cov += x*trans(y);
                sum_x += x;
                sum_y += y;
            }
            ++total_count;
        }

        const column_matrix mean_x (
        ) const
        {
            // make sure requires clause is not broken
            DLIB_ASSERT( current_n() != 0,
                "\t running_cross_covariance::mean()"
                << "\n\t This object can not execute this function in its current state."
                << "\n\t current_n():      " << current_n()
                << "\n\t this:             " << this
                );

            return sum_x/total_count;
        }

        const column_matrix mean_y (
        ) const
        {
            // make sure requires clause is not broken
            DLIB_ASSERT( current_n() != 0,
                "\t running_cross_covariance::mean()"
                << "\n\t This object can not execute this function in its current state."
                << "\n\t current_n():      " << current_n()
                << "\n\t this:             " << this
                );

            return sum_y/total_count;
        }

        const general_matrix covariance_xy (
        ) const
        {
            // make sure requires clause is not broken
            DLIB_ASSERT( current_n() > 1,
                "\t running_cross_covariance::covariance()"
                << "\n\t This object can not execute this function in its current state."
                << "\n\t x_vector_size(): " << x_vector_size()
                << "\n\t y_vector_size(): " << y_vector_size()
                << "\n\t current_n():     " << current_n()
                << "\n\t this:            " << this
                );

            return (total_cov - sum_x*trans(sum_y)/total_count)/(total_count-1);
        }

        const running_cross_covariance operator+ (
            const running_cross_covariance& item
        ) const
        {
            // make sure requires clause is not broken
            DLIB_ASSERT((x_vector_size() == 0 || item.x_vector_size() == 0 || x_vector_size() == item.x_vector_size()) &&
                        (y_vector_size() == 0 || item.y_vector_size() == 0 || y_vector_size() == item.y_vector_size()),
                "\t running_cross_covariance running_cross_covariance::operator+()"
                << "\n\t The two running_cross_covariance objects being added must have compatible parameters"
                << "\n\t x_vector_size():            " << x_vector_size()
                << "\n\t item.x_vector_size():       " << item.x_vector_size()
                << "\n\t y_vector_size():            " << y_vector_size()
                << "\n\t item.y_vector_size():       " << item.y_vector_size()
                << "\n\t this:                       " << this
                );

            running_cross_covariance temp(item);

            // make sure we ignore empty matrices
            if (total_count != 0 && temp.total_count != 0)
            {
                temp.total_cov += total_cov;
                temp.sum_x += sum_x;
                temp.sum_y += sum_y;
                temp.total_count += total_count;
            }
            else if (total_count != 0)
            {
                temp.total_cov = total_cov;
                temp.sum_x = sum_x;
                temp.sum_y = sum_y;
                temp.total_count = total_count;
            }

            return temp;
        }

    private:

        general_matrix total_cov;
        column_matrix sum_x;
        column_matrix sum_y;
        scalar_type total_count;

        long x_vect_size;
        long y_vect_size;
    };

// ----------------------------------------------------------------------------------------

    template <
        typename matrix_type
        >
    class vector_normalizer
    {
    public:
        typedef typename matrix_type::mem_manager_type mem_manager_type;
        typedef typename matrix_type::type scalar_type;
        typedef matrix_type result_type;

        template <typename vector_type>
        void train (
            const vector_type& samples
        )
        {
            // make sure requires clause is not broken
            DLIB_ASSERT(samples.size() > 0,
                "\tvoid vector_normalizer::train()"
                << "\n\tyou have to give a nonempty set of samples to this function"
                << "\n\tthis: " << this
                );

            m = mean(mat(samples));
            sd = reciprocal(sqrt(variance(mat(samples))));

            DLIB_ASSERT(is_finite(m), "Some of the input vectors to vector_normalizer::train() have infinite or NaN values");
        }

        long in_vector_size (
        ) const
        {
            return m.nr();
        }

        long out_vector_size (
        ) const
        {
            return m.nr();
        }

        const matrix_type& means (
        ) const
        {
            return m;
        }

        const matrix_type& std_devs (
        ) const
        {
            return sd;
        }

        const result_type& operator() (
            const matrix_type& x
        ) const
        {
            // make sure requires clause is not broken
            DLIB_ASSERT(x.nr() == in_vector_size() && x.nc() == 1,
                "\tmatrix vector_normalizer::operator()"
                << "\n\t you have given invalid arguments to this function"
                << "\n\t x.nr():           " << x.nr()
                << "\n\t in_vector_size(): " << in_vector_size()
                << "\n\t x.nc():           " << x.nc()
                << "\n\t this:             " << this
                );

            temp_out = pointwise_multiply(x-m, sd);
            return temp_out;
        }

        void swap (
            vector_normalizer& item
        )
        {
            m.swap(item.m);
            sd.swap(item.sd);
            temp_out.swap(item.temp_out);
        }

        template <typename mt>
        friend void deserialize (
            vector_normalizer<mt>& item,
            std::istream& in
        );

        template <typename mt>
        friend void serialize (
            const vector_normalizer<mt>& item,
            std::ostream& out
        );

    private:

        // ------------------- private data members -------------------

        matrix_type m, sd;

        // This is just a temporary variable that doesn't contribute to the
        // state of this object.
        mutable matrix_type temp_out;
    };

// ----------------------------------------------------------------------------------------

    template <
        typename matrix_type
        >
    inline void swap (
        vector_normalizer<matrix_type>& a,
        vector_normalizer<matrix_type>& b
    ) { a.swap(b); }

// ----------------------------------------------------------------------------------------

    template <
        typename matrix_type
        >
    void deserialize (
        vector_normalizer<matrix_type>& item,
        std::istream& in
    )
    {
        deserialize(item.m, in);
        deserialize(item.sd, in);
        // Keep deserializing the pca matrix for backwards compatibility.
        matrix<double> pca;
        deserialize(pca, in);

        if (pca.size() != 0)
            throw serialization_error("Error deserializing object of type vector_normalizer\n"
                                        "It looks like a serialized vector_normalizer_pca was accidentally deserialized into \n"
                                        "a vector_normalizer object.");
    }

// ----------------------------------------------------------------------------------------

    template <
        typename matrix_type
        >
    void serialize (
        const vector_normalizer<matrix_type>& item,
        std::ostream& out
    )
    {
        serialize(item.m, out);
        serialize(item.sd, out);
        // Keep serializing the pca matrix for backwards compatibility.
        matrix<double> pca;
        serialize(pca, out);
    }

// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------

    template <
        typename matrix_type
        >
    class vector_normalizer_pca
    {
    public:
        typedef typename matrix_type::mem_manager_type mem_manager_type;
        typedef typename matrix_type::type scalar_type;
        typedef matrix<scalar_type,0,1,mem_manager_type> result_type;

        template <typename vector_type>
        void train (
            const vector_type& samples,
            const double eps = 0.99
        )
        {
            // You are getting an error here because you are trying to apply PCA
            // to a vector of fixed length.  But PCA is going to try and do
            // dimensionality reduction so you can't use a vector with a fixed dimension.
            COMPILE_TIME_ASSERT(matrix_type::NR == 0);

            // make sure requires clause is not broken
            DLIB_ASSERT(samples.size() > 0,
                "\tvoid vector_normalizer_pca::train_pca()"
                << "\n\tyou have to give a nonempty set of samples to this function"
                << "\n\tthis: " << this
                );
            DLIB_ASSERT(0 < eps && eps <= 1,
                "\tvoid vector_normalizer_pca::train_pca()"
                << "\n\tyou have to give a nonempty set of samples to this function"
                << "\n\tthis: " << this
                );
            train_pca_impl(mat(samples),eps);

            DLIB_ASSERT(is_finite(m), "Some of the input vectors to vector_normalizer_pca::train() have infinite or NaN values");
        }

        long in_vector_size (
        ) const
        {
            return m.nr();
        }

        long out_vector_size (
        ) const
        {
            return pca.nr();
        }

        const matrix<scalar_type,0,1,mem_manager_type>& means (
        ) const
        {
            return m;
        }

        const matrix<scalar_type,0,1,mem_manager_type>& std_devs (
        ) const
        {
            return sd;
        }

        const matrix<scalar_type,0,0,mem_manager_type>& pca_matrix (
        ) const
        {
            return pca;
        }

        const result_type& operator() (
            const matrix_type& x
        ) const
        {
            // make sure requires clause is not broken
            DLIB_ASSERT(x.nr() == in_vector_size() && x.nc() == 1,
                "\tmatrix vector_normalizer_pca::operator()"
                << "\n\t you have given invalid arguments to this function"
                << "\n\t x.nr():           " << x.nr()
                << "\n\t in_vector_size(): " << in_vector_size()
                << "\n\t x.nc():           " << x.nc()
                << "\n\t this:             " << this
                );

            // If we have a pca transform matrix on hand then
            // also apply that.
            temp_out = pca*pointwise_multiply(x-m, sd);

            return temp_out;
        }

        void swap (
            vector_normalizer_pca& item
        )
        {
            m.swap(item.m);
            sd.swap(item.sd);
            pca.swap(item.pca);
            temp_out.swap(item.temp_out);
        }

        template <typename T>
        friend void deserialize (
            vector_normalizer_pca<T>& item,
            std::istream& in
        );

        template <typename T>
        friend void serialize (
            const vector_normalizer_pca<T>& item,
            std::ostream& out
        );

    private:

        template <typename mat_type>
        void train_pca_impl (
            const mat_type& samples,
            const double eps
        )
        {
            m = mean(samples);
            sd = reciprocal(sqrt(variance(samples)));

            // fill x with the normalized version of the input samples
            matrix<typename mat_type::type,0,1,mem_manager_type> x(samples);
            for (long r = 0; r < x.size(); ++r)
                x(r) = pointwise_multiply(x(r)-m, sd);

            matrix<scalar_type,0,0,mem_manager_type> temp, eigen;
            matrix<scalar_type,0,1,mem_manager_type> eigenvalues;

            // Compute the svd of the covariance matrix of the normalized inputs
            svd(covariance(x), temp, eigen, pca);
            eigenvalues = diag(eigen);

            rsort_columns(pca, eigenvalues);

            // figure out how many eigenvectors we want in our pca matrix
            const double thresh = sum(eigenvalues)*eps;
            long num_vectors = 0;
            double total = 0;
            for (long r = 0; r < eigenvalues.size() && total < thresh; ++r)
            {
                ++num_vectors;
                total += eigenvalues(r);
            }

            // So now we know we want to use num_vectors of the first eigenvectors.  So
            // pull those out and discard the rest.
            pca = trans(colm(pca,range(0,num_vectors-1)));

            // Apply the pca transform to the data in x.  Then we will normalize the
            // pca matrix below.
            for (long r = 0; r < x.nr(); ++r)
            {
                x(r) = pca*x(r);
            }

            // Here we just scale the output features from the pca transform so
            // that the variance of each feature is 1.  So this doesn't really change
            // what the pca is doing, it just makes sure the output features are
            // normalized.
            pca = trans(scale_columns(trans(pca), reciprocal(sqrt(variance(x)))));
        }

        // ------------------- private data members -------------------

        matrix<scalar_type,0,1,mem_manager_type> m, sd;
        matrix<scalar_type,0,0,mem_manager_type> pca;

        // This is just a temporary variable that doesn't contribute to the
        // state of this object.
        mutable result_type temp_out;
    };

    template <
        typename matrix_type
        >
    inline void swap (
        vector_normalizer_pca<matrix_type>& a,
        vector_normalizer_pca<matrix_type>& b
    ) { a.swap(b); }

// ----------------------------------------------------------------------------------------

    template <
        typename matrix_type
        >
    void deserialize (
        vector_normalizer_pca<matrix_type>& item,
        std::istream& in
    )
    {
        deserialize(item.m, in);
        deserialize(item.sd, in);
        deserialize(item.pca, in);
        if (item.pca.nc() != item.m.nr())
            throw serialization_error("Error deserializing object of type vector_normalizer_pca\n"
                                        "It looks like a serialized vector_normalizer was accidentally deserialized into \n"
                                        "a vector_normalizer_pca object.");
    }

    template <
        typename matrix_type
        >
    void serialize (
        const vector_normalizer_pca<matrix_type>& item,
        std::ostream& out
    )
    {
        serialize(item.m, out);
        serialize(item.sd, out);
        serialize(item.pca, out);
    }

// ----------------------------------------------------------------------------------------

}

#endif // DLIB_STATISTICs_


text:
using System;
using System.Threading.Tasks;

using Autumn.Common.Async;

using Common.Logging;

namespace Autumn.Server.Async
{
    public abstract class AsyncRequestHandler<TRequest, TResponse> : IAsyncRequestHandler<TRequest, TResponse>
        where TRequest : IAsyncRequest
        where TResponse : IAsyncResponse
    {
        private readonly ILog _log;

        protected AsyncRequestHandler(ILog log)
        {
            _log = log;
        }

        public async Task<IAsyncResponse> ExecuteAsync(IAsyncRequest request)
        {
            var typedRequest = (TRequest)request;

            _log.DebugFormat("Executing BeforeExecuteAsync on sync request : {0}, Id - {1} @ {2}", request.GetType().Name, request.Id, DateTime.Now);

            typedRequest = await BeforeExecuteAsync(typedRequest);

            _log.DebugFormat("Executing HandleAsync on sync request : {0}, Id - {1} @ {2}", request.GetType().Name, request.Id, DateTime.Now);

            var response = await HandleAsync(typedRequest);

            _log.DebugFormat("Executing AfterExecuteAsync on sync request : {0}, Id - {1} @ {2}", request.GetType().Name, request.Id, DateTime.Now);

            response = await AfterExecuteAsync(response);

            return response;
        }

        protected abstract Task<TResponse> HandleAsync(TRequest request);

        protected virtual Task<TRequest> BeforeExecuteAsync(TRequest request)
        {
            return Task.FromResult(request);
        }

        protected virtual Task<TResponse> AfterExecuteAsync(TResponse response)
        {
            return Task.FromResult(response);
        }
    }
}


text:
Clear Sort

Title

Type

Author

Date Added

Id

                  <input type="checkbox" ng-change="$ctrl.getAllFiles();" ng-model-options="{debounce: 200}" ng-model="$ctrl.types.person" ng-checked="$ctrl.types.person">Person

                  <input type="checkbox" ng-change="$ctrl.getAllFiles();" ng-model-options="{debounce: 200}" ng-model="$ctrl.types.place" ng-checked="$ctrl.types.place">Place

                  <input type="checkbox" ng-change="$ctrl.getAllFiles();" ng-model-options="{debounce: 200}" ng-model="$ctrl.types.collection" ng-checked="$ctrl.types.collection">Collection

                  <input type="checkbox" ng-change="$ctrl.getAllFiles();" ng-model-options="{debounce: 200}" ng-model="$ctrl.types.other" ng-checked="$ctrl.types.other">Other Metadata

      <input class="form-control" type="text" ng-model="$ctrl.typeahead" ng-model-options="{debounce: 200}" ng-change="$ctrl.getAllFiles()" placeholder="Quick Search">

      <file-preview file="item" hide-other="true" thumbnails="true"></file-preview>
      {{item[$ctrl.label]}}  ({{item.submitterName}})


text:
      <button class="navbar-toggle" type="button" data-toggle="collapse" data-target=".bs-navbar-collapse">

      </button>

          分类


text:
/* Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.camunda.bpm.engine.impl.scripting.engine;

import static org.camunda.bpm.engine.impl.util.EnsureUtil.ensureNotNull;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;

import javax.script.Bindings;
import javax.script.Compilable;
import javax.script.CompiledScript;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

import org.camunda.bpm.application.AbstractProcessApplication;
import org.camunda.bpm.application.ProcessApplicationInterface;
import org.camunda.bpm.application.ProcessApplicationReference;
import org.camunda.bpm.application.ProcessApplicationUnavailableException;
import org.camunda.bpm.dmn.engine.ScriptEngineResolver;
import org.camunda.bpm.dmn.scriptengine.DmnScriptEngineFactory;
import org.camunda.bpm.engine.ProcessEngineException;
import org.camunda.bpm.engine.ScriptCompilationException;
import org.camunda.bpm.engine.delegate.VariableScope;
import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.camunda.bpm.engine.impl.context.Context;

/**
 *
Manager for JSR-223 {@link ScriptEngine} handling.

 *
 *
Resolving a script engine:
 * This class supports resolving a script engine for a given 'language name' (eg. 'groovy').
 * If the configuration option {@link #enableScriptEngineCaching} is set to true,
 * the class will attempt to cache 'cachable' script engines. We assume a {@link ScriptEngine} is
 * 'cachable' if it declares to be threadsafe (see {@link #isCachable(ScriptEngine)})

 *
 *
Custom Bindings: this class supports custom {@link Bindings}
 * implementations through the {@link #scriptBindingsFactory}. See {@link ScriptBindingsFactory}.

 *

 *
 * @author Tom Baeyens
 * @author Daniel Meyer
 */
public class ScriptingEngines implements ScriptEngineResolver {

  private static Logger LOG = Logger.getLogger(ScriptingEngines.class.getName());

  public static final String DEFAULT_SCRIPTING_LANGUAGE = "juel";
  public static final String GROOVY_SCRIPTING_LANGUAGE = "groovy";

  private final ScriptEngineManager scriptEngineManager;
  protected ScriptBindingsFactory scriptBindingsFactory;

  protected Map<String, ScriptEngine> cachedEngines = new HashMap<String, ScriptEngine>();

  protected boolean enableScriptEngineCaching = true;

  public ScriptingEngines(ScriptBindingsFactory scriptBindingsFactory) {
    this(new ScriptEngineManager());
    this.scriptBindingsFactory = scriptBindingsFactory;
  }

  public ScriptingEngines(ScriptEngineManager scriptEngineManager) {
    this.scriptEngineManager = scriptEngineManager;
  }

  public void setEnableScriptEngineCaching(boolean cacheScriptEngines) {
    this.enableScriptEngineCaching = cacheScriptEngines;
  }

  public boolean isEnableScriptEngineCaching() {
    return enableScriptEngineCaching;
  }

  public ScriptEngineManager getScriptEngineManager() {
    return scriptEngineManager;
  }

  public ScriptingEngines addScriptEngineFactory(ScriptEngineFactory scriptEngineFactory) {
    scriptEngineManager.registerEngineName(scriptEngineFactory.getEngineName(), scriptEngineFactory);
    return this;
  }

  public void setScriptEngineFactories(List


text:
'use strict';

var should = require('chai').should();
var bitcore = require('bitcore');
var Networks = bitcore.Networks;

describe('Simple Payment Channel usage', function() {

  describe('a simple consumer', function() {

    it('correctly gets created', function() {
      var consumer = getConsumer().consumer;
      should.exist(consumer.fundingKey.toString());
      // No assertions...? Just checking that no compile errors occur
    });

    it('Commitment toObject', function() {
      var consumer = getFundedConsumer().consumer;
      var obj = consumer.commitmentTx.toObject();
      var expected = {
        'transaction': {
          'hash': '591ad922bfab0d8d4bd359dbfb6d8006efd1082029af1d3d8bdc690f1908fb37',
          'version': 1,
          'inputs': [{
            'prevTxId': '787ef38932601aa6d22b844770121f713b0afb6c13fdd52e512c6165508f47cd',
            'outputIndex': 1,
            'sequenceNumber': 4294967295,
            'script': '483045022100e5e9a5660ed650b377d1063c57ba210d2f8e36f350489a5b0ca9b46eb8fb659a02205a6d336c2252b39fcb7534fdfc3a593a87b5c34c0d3ad27e25bd5edea027308a012103bca86b6a422d1ffec9fd0a1e8d37feaef4e41f76bbdde68852251b7ae8ca6fab',
            'scriptString': '72 0x3045022100e5e9a5660ed650b377d1063c57ba210d2f8e36f350489a5b0ca9b46eb8fb659a02205a6d336c2252b39fcb7534fdfc3a593a87b5c34c0d3ad27e25bd5edea027308a01 33 0x03bca86b6a422d1ffec9fd0a1e8d37feaef4e41f76bbdde68852251b7ae8ca6fab',
            'output': {
              'satoshis': 50000000,
              'script': '76a91469b678f36c91bf635ff6e9479edd3253a5dfd41a88ac'
            }
          }, {
            'prevTxId': 'c1003b5e2c9f5eca65bde73463035e5dffcfbd3c234e55e069cfeebb513293e4',
            'outputIndex': 0,
            'sequenceNumber': 4294967295,
            'script': '47304402205d5c5ae33804c2842311bedca88474ee47d49efba2a3aece49e7039551cc98b00220338b5aed644a810b0d92c9717029a1dfe3808f8a5ce74ec4f5cc03c6a7af2148012103bca86b6a422d1ffec9fd0a1e8d37feaef4e41f76bbdde68852251b7ae8ca6fab',
            'scriptString': '71 0x304402205d5c5ae33804c2842311bedca88474ee47d49efba2a3aece49e7039551cc98b00220338b5aed644a810b0d92c9717029a1dfe3808f8a5ce74ec4f5cc03c6a7af214801 33 0x03bca86b6a422d1ffec9fd0a1e8d37feaef4e41f76bbdde68852251b7ae8ca6fab',
            'output': {
              'satoshis': 10000000,
              'script': '76a91469b678f36c91bf635ff6e9479edd3253a5dfd41a88ac'
            }
          }],
          'outputs': [{
            'satoshis': 59990000,
            'script': 'a914fdeaa734587dfed0090c98fbf1bf8730009ddda887'
          }],
          'nLockTime': 0,
          'changeScript': 'OP_HASH160 20 0xfdeaa734587dfed0090c98fbf1bf8730009ddda8 OP_EQUAL',
          'changeIndex': 0
        },
        'publicKeys': ['027f10e67bea70f847b3ab92c18776c6a97a78f84def158afc31fd98513d42912e', '023bc028f67697712efeb0216ef1bc7208e2c9156bf0731204d79328f4c8ef643a'],
        'network': 'testnet'
      };
      obj.should.deep.equal(expected);
    });

    it('processes an output', function() {
      var consumer = getFundedConsumer().consumer;
      consumer.commitmentTx.amount.should.equal(60000000);
    });

    it('validates a refund correctly', function() {
      var consumer = getValidatedConsumer().consumer;
      consumer.refundTx.isFullySigned().should.equal(true);
    });

    it('has no false positive on refund validation', function() {
      var consumer = getFundedConsumer().consumer;
      consumer.setupRefund();

      var failed = false;
      try {
        consumer.validateRefund({
          refund: consumer.refundTx.toObject(),
          paymentAddress: 'mgeLZRkELTysge5dvpo2ixGNgG2biWwRXC'
        });
      } catch (e) {
        failed = true;
      } finally {
        failed.should.equal(true);
      }
    });

    it('can increment a payment', function() {
      var consumer = getValidatedConsumer().consumer;
      consumer.incrementPaymentBy(1000);
      consumer.paymentTx.paid.should.equal(1000);
      consumer.incrementPaymentBy(1000);
      consumer.paymentTx.paid.should.equal(2000);
    });
  });

  describe('a simple provider', function() {

    it('gets created correctly', function() {
      // TODO: no assertions?
      return getProvider();
    });

    it('signs a refund', function() {
      var consumer = getValidatedConsumer().consumer;
      consumer.refundTx.isFullySigned().should.equal(true);
    });

    it('validates a payment', function() {
      var provider = getProvider();
      var consumer = getValidatedConsumer().consumer;
      provider.validPayment(consumer.incrementPaymentBy(1000));
      provider.currentAmount.should.equal(1000);
      provider.validPayment(consumer.incrementPaymentBy(1000));
      provider.validPayment(consumer.incrementPaymentBy(1000));
      provider.validPayment(consumer.incrementPaymentBy(1000));
      provider.currentAmount.should.equal(4000);
    });

    it('calculates fees normally', function() {
      var provider = getProvider();
      var consumer = getValidatedConsumer().consumer;
      provider.validPayment(consumer.incrementPaymentBy(1000));
      provider.currentAmount.should.equal(1000);
      provider.paymentTx.getFee().should.equal(10000);
      provider.validPayment(consumer.incrementPaymentBy(1000));
      provider.validPayment(consumer.incrementPaymentBy(1000));
      provider.validPayment(consumer.incrementPaymentBy(1000));
      provider.currentAmount.should.equal(4000);
      provider.paymentTx.getFee().should.equal(10000);
    });
  });
});

var providerKey = new bitcore.PrivateKey('58e78db594be551a8f4c7070fd8695363992bd1eb37d01cd4a4da608f3dc5c2d', bitcore.Networks.testnet);
var fundingKey = new bitcore.PrivateKey('79b0630419ad72397d211db4988c98ffcb5955b14f6ec5c5651eec5c98d7e557', bitcore.Networks.testnet);
var commitmentKey = new bitcore.PrivateKey('17bc93ac93f4a26599d3af49e59206e8276259febba503434eacb871f9bbad75', bitcore.Networks.testnet);
var providerAddress = providerKey.toAddress(Networks.testnet);

var getConsumer = function() {

  var Consumer = require('../').Consumer;
  var refundAddress = 'mzCXqcsLBerwyoRZzBFQELHaJ1ZtBSxxe6';

  var consumer = new Consumer({
    network: 'testnet',
    fundingKey: fundingKey,
    commitmentKey: commitmentKey,
    providerPublicKey: providerKey.publicKey,
    providerAddress: providerKey.toAddress(),
    refundAddress: refundAddress
  });

  return {
    consumer: consumer,
    serverPublicKey: providerKey.publicKey,
    refundAddress: refundAddress
  };
};

var getFundedConsumer = function() {
  var result = getConsumer();
  result.consumer.processFunding([{
    'address': 'mq9uqc4W8phHXRPt3ZWUdRpoZ9rkR67Dw1',
    'txid': '787ef38932601aa6d22b844770121f713b0afb6c13fdd52e512c6165508f47cd',
    'vout': 1,
    'ts': 1416205164,
    'scriptPubKey': '76a91469b678f36c91bf635ff6e9479edd3253a5dfd41a88ac',
    'amount': 0.5,
    'confirmationsFromCache': false
  }, {
    'address': 'mq9uqc4W8phHXRPt3ZWUdRpoZ9rkR67Dw1',
    'txid': 'c1003b5e2c9f5eca65bde73463035e5dffcfbd3c234e55e069cfeebb513293e4',
    'vout': 0,
    'ts': 1416196853,
    'scriptPubKey': '76a91469b678f36c91bf635ff6e9479edd3253a5dfd41a88ac',
    'amount': 0.1,
    'confirmations': 18,
    'confirmationsFromCache': false
  }]);
  result.consumer.commitmentTx.sign(fundingKey);
  return result;
};

var getValidatedConsumer = function() {
  var funded = getFundedConsumer().consumer;
  funded.setupRefund();
  funded.refundTx.sign(providerKey);
  var refund = funded.refundTx.toObject();
  funded.validateRefund(refund);
  return {
    consumer: funded
  };
};

var getProvider = function() {
  var Provider = require('../').Provider;
  return new Provider({
    key: providerKey,
    paymentAddress: providerAddress,
    network: 'testnet'
  });
};


text:
<!-- Copyright 2021 DeepMind Technologies Limited
     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at
         http://www.apache.org/licenses/LICENSE-2.0
     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->

<mujoco>
  <!--
  body2 is held by body1 through the weld constraint, so the force sensor on body1
  should register 20 (for the weight of both bodies).
  -->
  <option gravity="0 0 -1"/>

  <default>
    <!-- A cube of size 0.1^3 with density of 1000 has mass of 1. -->
    <geom size="0.05 0.05 0.05" type="box"/>
  </default>

  <worldbody>
    <body name="body1">
      <geom/>
      <site name="sensor"/>
    </body>
    <body name="body2" pos="0 0 -0.1">
      <joint type="slide" axis="0 0 1"/>
      <geom/>
    </body>
  </worldbody>

  <equality>
    <weld body1="body1" body2="body2" anchor="0 0 0" torquescale="0"/>
  </equality>

  <sensor>
    <force site="sensor" user="0 0 2"/>
  </sensor>
</mujoco>