text:
import { combineReducers } from 'redux';
import Pollable from '../Pollable';
import { Library } from '../di';
import {
  getDataFetcherReducer,
  createGetDataReducer,
  createGetTimestampReducer,
} from './getDataFetcherReducer';
import moduleStatuses from '../../enums/moduleStatuses';
import proxify from '../proxy/proxify';
import ensureExist from '../ensureExist';
import Enum from '../Enum';
import { moduleActionTypes } from '../../enums/moduleActionTypes';
import { actionTypeGenerator } from '../actionTypeGenerator';

const DEFAULT_TTL = 30 * 60 * 1000;
const DEFAULT_RETRY = 62 * 1000;

const RETRY_INTERVALS = [2 * 1000, 5 * 1000, 10 * 1000, 30 * 1000];

@Library({
  deps: [
    'Auth',
    'Client',
    'Subscription',
    { dep: 'SleepDetector', optional: true },
    { dep: 'TabManager', optional: true },
    { dep: 'Storage', optional: true },
    { dep: 'DataFetcherOptions', optional: true },
  ],
})
export default class DataFetcher extends Pollable {
  constructor({
    auth,
    client,
    storage,
    subscription,
    sleepDetector,
    tabManager,
    timeToRetry = DEFAULT_RETRY,
    ttl = DEFAULT_TTL,
    pollingInterval = ttl,
    polling = false,
    disableCache = false,
    cleanOnReset = false,
    getReducer = getDataFetcherReducer,
    getDataReducer = createGetDataReducer(cleanOnReset),
    getTimestampReducer = createGetTimestampReducer(cleanOnReset),
    fetchFunction,
    forbiddenHandler,
    subscriptionFilters,
    subscriptionHandler,
    readyCheckFn,
    ...options
  }) {
    if (typeof fetchFunction !== 'function') {
      throw new Error('fetchFunction must be a asynchronous function');
    }
    super({
      ...options,
    });
    this._auth = ensureExist.call(this, auth, 'auth');
    this._client = ensureExist.call(this, client, 'client');
    this._sleepDetector = sleepDetector;
    this._disableCache = disableCache;
    this._storage = storage;
    this._subscription = subscription;
    this._tabManager = tabManager;
    this._ttl = ttl;
    this._timeToRetry = timeToRetry;
    this._polling = polling;
    this._pollingInterval = pollingInterval;
    this._fetchFunction = fetchFunction;
    this._forbiddenHandler = forbiddenHandler;
    this._subscriptionFilters = subscriptionFilters;
    this._subscriptionHandler = subscriptionHandler;
    this._readyCheckFn = readyCheckFn;

    this._storageKey = `${this._name}-data`; // differentiate from old key

    if (!this._disableCache && this._storage) {
      this._reducer = getReducer(this.actionTypes);
      this._storage.registerReducer({
        key: this._storageKey,
        reducer: combineReducers({
          data: getDataReducer(this.actionTypes),
          timestamp: getTimestampReducer(this.actionTypes),
        }),
      });
    } else {
      this._reducer = getReducer(this.actionTypes, {
        data: getDataReducer(this.actionTypes),
        timestamp: getTimestampReducer(this.actionTypes),
      });
    }

    this._promise = null;
    this._lastMessage = null;
  }

  get _name() {
    throw new Error(`${this.constructor.name}::_name must be defined`);
  }

  get _actionTypes() {
    return new Enum(
      [
        ...Object.keys(moduleActionTypes),
        ...actionTypeGenerator('fetch'),
        'retry',
      ],
      this._name,
    );
  }

  initialize() {
    this.store.subscribe(() => this._onStateChange());
    if (this._sleepDetector) {
      this._sleepDetector.on(
        this._sleepDetector.events.detected,
        () => this._handleSleepDetected,
      );
    }
  }

  _handleSleepDetected() {
    if (this._shouldFetch()) {
      this.fetchData();
    }
  }

  async _onStateChange() {
    if (this._shouldInit()) {
      this.store.dispatch({
        type: this.actionTypes.init,
      });
      if (this._hasPermission) {
        await this._init();
      } else {
        this.store.dispatch({
          type: this.actionTypes.initSuccess,
          hasPermission: false,
        });
      }
    } else if (this._isDataReady()) {
      this.store.dispatch({
        type: this.actionTypes.initSuccess,
        hasPermission: this._hasPermission,
      });
    } else if (this._shouldReset()) {
      this._clearTimeout();
      this._promise = null;
      this.store.dispatch({
        type: this.actionTypes.resetSuccess,
      });
    } else if (this._shouldHandleSubscriptionMessage()) {
      this._processSubscription();
    }
  }

  _shouldInit() {
    return !!(
      this._auth.loggedIn &&
      (!this._storage || this._storage.ready) &&
      (!this._readyCheckFn || this._readyCheckFn()) &&
      (!this._subscription || this._subscription.ready) &&
      (!this._tabManager || this._tabManager.ready) &&
      this.pending
    );
  }

  _shouldReset() {
    return !!(
      (!this._auth.loggedIn ||
        (this._storage && !this._storage.ready) ||
        (this._readyCheckFn && !this._readyCheckFn()) ||
        (this._subscription && !this._subscription.ready) ||
        (this._tabManager && !this._tabManager.ready)) &&
      !this.pending
    );
  }

  _shouldHandleSubscriptionMessage() {
    return !!(
      this.ready &&
      this._subscription &&
      this._subscription.ready &&
      this._subscriptionHandler &&
      this._subscription.message &&
      this._subscription.message !== this._lastMessage
    );
  }

  _shouldFetch() {
    return (
      (!this._tabManager || this._tabManager.active) &&
      (this._auth.isFreshLogin ||
        !this.timestamp ||
        Date.now() - this.timestamp > this.ttl)
    );
  }

  _isDataReady() {
    // only turns ready when data has been fetched
    // (could be from other tabs)
    return (
      this.status === moduleStatuses.initializing &&
      this.data !== null &&
      this.timestamp !== null
    );
  }

  async _init() {
    if (this._subscription && this._subscriptionFilters) {
      this._subscription.subscribe(this._subscriptionFilters);
    }
    if (this._shouldFetch()) {
      try {
        await this.fetchData();
      } catch (e) {
        console.error('fetchData error:', e);
        this._retry();
      }
    } else if (this._polling) {
      this._startPolling();
    } else {
      this._retry();
    }
  }

  _processSubscription() {
    this._lastMessage = this._subscription.message;
    this._subscriptionHandler(this._lastMessage);
  }

  get data() {
    if (!this._disableCache && this._storage) {
      return (
        (this._storage.getItem(this._storageKey) &&
          this._storage.getItem(this._storageKey).data) ||
        null
      );
    }
    return this.state.data;
  }

  get timestamp() {
    if (!this._disableCache && this._storage) {
      return (
        (this._storage.getItem(this._storageKey) &&
          this._storage.getItem(this._storageKey).timestamp) ||
        null
      );
    }
    return this.state.timestamp;
  }

  get status() {
    return this.state.status;
  }

  get ready() {
    return this.state.status === moduleStatuses.ready;
  }

  get pending() {
    return this.state.status === moduleStatuses.pending;
  }

  get ttl() {
    return this._ttl;
  }

  get pollingInterval() {
    return this._pollingInterval;
  }

  get retryCount() {
    return this.state.retryCount;
  }

  get timeToRetry() {
    if (this.status === moduleStatuses.initializing) {
      return RETRY_INTERVALS[this.retryCount] || this._timeToRetry;
    }
    return this._timeToRetry;
  }

  get _hasPermission() {
    return true;
  }

  // handle 403 Forbidden error
  async _fetchWithForbiddenCheck() {
    try {
      const data = await this._fetchFunction();
      return data;
    } catch (error) {
      if (
        error &&
        error.apiResponse &&
        error.apiResponse._response &&
        error.apiResponse._response.status === 403 &&
        typeof this._forbiddenHandler === 'function'
      ) {
        const result = await this._forbiddenHandler(error);
        return result;
      }
      throw error;
    }
  }

  @proxify
  async _fetchData() {
    this.store.dispatch({
      type: this.actionTypes.fetch,
    });
    const { ownerId } = this._auth;
    try {
      const data = await this._fetchWithForbiddenCheck();
      if (this._auth.ownerId === ownerId) {
        this.store.dispatch({
          type: this.actionTypes.fetchSuccess,
          data,
          timestamp: Date.now(),
        });
        if (this._polling) {
          this._startPolling();
        }
        this._promise = null;
      }
    } catch (error) {
      if (this._auth.ownerId === ownerId) {
        this._promise = null;
        this.store.dispatch({
          type: this.actionTypes.fetchError,
          error,
        });
        if (this._polling) {
          this._startPolling(this.timeToRetry);
        } else {
          this._retry();
        }
        throw error;
      }
    }
  }

  @proxify
  async fetchData() {
    if (!this._promise) {
      this._promise = this._fetchData();
    }
    return this._promise;
  }

  _retry(t = this.timeToRetry) {
    this._clearTimeout();
    this._timeoutId = setTimeout(() => {
      if (this.status === moduleStatuses.initializing) {
        this.store.dispatch({
          type: this.actionTypes.retry,
        });
      }
      this._timeoutId = null;
      if (!this.timestamp || Date.now() - this.timestamp > this.ttl) {
        if (!this._tabManager || this._tabManager.active) {
          this.fetchData();
        } else {
          // continue retry checks in case tab becomes main tab
          this._retry();
        }
      }
    }, t);
  }
}


text:
package io.apiman.gateway.platforms.war;

import io.apiman.gateway.engine.IEngine;
import io.apiman.gateway.engine.IPolicyErrorWriter;
import io.apiman.gateway.engine.IPolicyFailureWriter;
import io.apiman.gateway.engine.impl.ConfigDrivenEngineFactory;
import io.apiman.gateway.engine.impl.DefaultPolicyErrorWriter;
import io.apiman.gateway.engine.impl.DefaultPolicyFailureWriter;

import java.util.Map;

/**
 * Top level gateway.  Used when the API Management Runtime Engine is being used
 * in a standard Web Application gateway scenario.
 *
 * @author eric.wittmann@redhat.com
 */
public class WarGateway {

    public static WarEngineConfig config;
    public static IEngine engine;
    public static IPolicyFailureWriter failureFormatter;
    public static IPolicyErrorWriter errorFormatter;

    /**
     * Initialize the gateway.
     */
    public static void init() {
        config = new WarEngineConfig();
        ConfigDrivenEngineFactory factory = new ConfigDrivenEngineFactory(config);
        engine = factory.createEngine();
        failureFormatter = loadFailureFormatter();
        errorFormatter = loadErrorFormatter();
    }

    private static IPolicyErrorWriter loadErrorFormatter() {
        Class<? extends IPolicyErrorWriter> clazz = config.getPolicyErrorWriterClass(engine.getPluginRegistry());
        if (clazz == null) {
            clazz = DefaultPolicyErrorWriter.class;
        }
        Map<String, String> conf = config.getPolicyErrorWriterConfig();
        return ConfigDrivenEngineFactory.instantiate(clazz, conf);
    }

    private static IPolicyFailureWriter loadFailureFormatter() {
        Class<? extends IPolicyFailureWriter> clazz = config.getPolicyFailureWriterClass(engine.getPluginRegistry());
        if (clazz == null) {
            clazz = DefaultPolicyFailureWriter.class;
        }
        Map<String, String> conf = config.getPolicyFailureWriterConfig();
        return ConfigDrivenEngineFactory.instantiate(clazz, conf);
    }

    /**
     * Shuts down the gateway.
     */
    public static void shutdown() {
        engine = null;
    }

}

redpajama_set_name: RedPajamaGithub


text:
[![Gem Version][gem-image]][gem-link] [![Build Status][build-image]][build-link] [![Code Climate][codeclimate-image]][codeclimate-link] [![Coverage Status][coverage-image]][coverage-link] [![MIT licensed][license-image]][license-link]

[gem-image]: https://badge.fury.io/rb/socketry.svg
[gem-link]: https://rubygems.org/gems/socketry
[build-image]: https://secure.travis-ci.org/socketry/socketry.svg?branch=master
[build-link]: https://travis-ci.org/socketry/socketry
[codeclimate-image]: https://codeclimate.com/github/socketry/socketry.svg?branch=master
[codeclimate-link]: https://codeclimate.com/github/socketry/socketry
[coverage-image]: https://coveralls.io/repos/github/socketry/socketry/badge.svg?branch=master
[coverage-link]: https://coveralls.io/github/socketry/socketry?branch=master
[license-image]: https://img.shields.io/badge/license-MIT-blue.svg
[license-link]: https://github.com/socketry/socketry/blob/master/LICENSE.txt

High-level Ruby socket library with support for TCP, UDP, and SSL sockets.

Implements thread-safe timeouts using asynchronous I/O and high-precision monotonic timers.

## Motivation

By default, Ruby sockets do not provide a built-in timeout mechanism. The only
timeout mechanism provided by the language leverages [timeout.rb], which uses
[unsafe multithreaded behaviors] to implement timeouts.

While Socketry provides a synchronous, blocking API similar to Ruby's own
`TCPSocket` and `UDPSocket` classes, behind the scenes it uses non-blocking I/O
to implement thread-safe timeouts.

[timeout.rb]: http://ruby-doc.org/stdlib-2.3.1/libdoc/timeout/rdoc/Timeout.html
[unsafe multithreaded behaviors]: http://blog.headius.com/2008/02/ruby-threadraise-threadkill-timeoutrb.html

## Installation

Add this line to your application's Gemfile:

```ruby
gem "socketry"
```

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install socketry

## Basic Usage

Below is a basic example of how to use Socketry to make an HTTPS request:

```ruby
require "socketry"

socket = Socketry::SSL::Socket.connect("github.com", 443)
socket.writepartial("GET / HTTP/1.0\r\nHost: github.com\r\n\r\n")
p socket.readpartial(1024)
```

[TCP], [SSL], and [UDP] servers and sockets also available.

[TCP]: https://github.com/socketry/socketry/wiki/TCP
[SSL]: https://github.com/socketry/socketry/wiki/SSL
[UDP]: https://github.com/socketry/socketry/wiki/UDP

## Documentation

[Please see the Socketry wiki](https://github.com/socketry/socketry/wiki)
for more detailed documentation and usage notes.

[YARD API documentation](http://www.rubydoc.info/gems/socketry/)
is also available.

## Supported Ruby Versions

This library aims to support and is [tested against][travis] the following Ruby
versions:

* Ruby 2.2.6+
* Ruby 2.3
* Ruby 2.4
* Ruby 2.5
* JRuby 9.1.6.0+

If something doesn't work on one of these versions, it's a bug.

This library may inadvertently work (or seem to work) on other Ruby versions,
however support will only be provided for the versions listed above.

If you would like this library to support another Ruby version or
implementation, you may volunteer to be a maintainer. Being a maintainer
entails making sure all tests run and pass on that implementation. When
something breaks on your implementation, you will be responsible for providing
patches in a timely fashion. If critical issues for a particular implementation
exist at the time of a major release, support for that Ruby version may be
dropped.

[travis]: http://travis-ci.org/socketry/socketry

## Contributing

* Fork this repository on github
* Make your changes and send us a pull request
* If we like them we'll merge them
* If we've accepted a patch, feel free to ask for commit access

## License

Copyright (c) 2016 Tony Arcieri. Distributed under the MIT License. See
[LICENSE.txt](https://github.com/socketry/socketry/blob/master/LICENSE.txt)
for further details.


text:
import React from 'react';
import ReactDOM from 'react-dom';
import App from '../../../../src/components/common/app/App';

it('renders without crashing', () => {
  const div = document.createElement('div');
  ReactDOM.render(<App />, div);
});


text:
int main(int argc, const char * argv[])
{

    @autoreleasepool {
        int triangularNumber, n, number;

        NSLog(@"What triangular number do you want?");

        scanf("%i", &number);

        triangularNumber = 0;

        for (n = 0; n <= number; n = n + 1) {
            triangularNumber += n;
        }

        NSLog(@"Triangular number %i is %i", number, triangularNumber);

    }
    return 0;
}


text:
var app = require('./lib');
app.start(process.env.PORT);


text:
namespace app {
namespace Uno {
namespace Threading {

// This file was generated based on 'C:\ProgramData\Uno\Packages\Uno.Threading\0.13.2\$.uno'.
// WARNING: Changes might be lost if you edit this file directly.

Future__bool__uType* Future__bool__typeof()
{
    static ::uStaticStrong<Future__bool__uType*> type;
    if (type != NULL) return type;

    type = (Future__bool__uType*)::uAllocClassType(sizeof(Future__bool__uType), "Uno.Threading.Future<bool>", false, 0, 6, 0);

    type->SetBaseType(::app::Uno::Threading::Future__typeof());
    type->__fp_Cancel = (void(*)(::app::Uno::Threading::Future*, bool))Future__bool__Cancel;
    type->__fp_Wait = (void(*)(::app::Uno::Threading::Future*))Future__bool__Wait;

    type->SetStrongRefs(
        "_catchables", offsetof(Future__bool, _catchables),
        "_chainables", offsetof(Future__bool, _chainables),
        "_dispatcher", offsetof(Future__bool, _dispatcher),
        "_mutex", offsetof(Future__bool, _mutex),
        "_thenables", offsetof(Future__bool, _thenables),
        "Reason", offsetof(Future__bool, Reason));

    type->SetFields(7,
        ::uNewField("_catchables", NULL, offsetof(Future__bool, _catchables), ::app::Uno::Collections::Queue__Uno_Action_Uno_Exception___typeof()),
        ::uNewField("_chainables", NULL, offsetof(Future__bool, _chainables), ::app::Uno::Collections::Queue__Uno_Threading_Promise_bool___typeof()),
        ::uNewField("_dispatcher", NULL, offsetof(Future__bool, _dispatcher), ::app::Uno::Threading::IDispatcher__typeof()),
        ::uNewField("_mutex", NULL, offsetof(Future__bool, _mutex), ::app::Uno::Threading::Mutex__typeof()),
        ::uNewField("_thenables", NULL, offsetof(Future__bool, _thenables), ::app::Uno::Collections::Queue__Uno_Action_bool___typeof()),
        ::uNewField("Reason", NULL, offsetof(Future__bool, Reason), ::app::Uno::Exception__typeof()),
        ::uNewField("Result", NULL, offsetof(Future__bool, Result), ::app::Uno::Bool__typeof()));

    type->SetFunctions(3,
        ::uNewFunction("Catch", Future__bool__Catch, 0, false, Future__bool__typeof(), ::app::Uno::Action__Uno_Exception__typeof()),
        ::uNewFunction("Then", Future__bool__Then, 0, false, Future__bool__typeof(), ::app::Uno::Action__bool__typeof()),
        ::uNewFunction("Then", Future__bool__Then_1, 0, false, Future__bool__typeof(), ::app::Uno::Action__bool__typeof(), ::app::Uno::Action__Uno_Exception__typeof()));

    ::uRegisterType(type);
    return type;
}

void Future__bool___ObjInit_1(Future__bool* __this)
{
    __this->_mutex = ::app::Uno::Threading::Mutex__Create(NULL);
    __this->_ObjInit_2((::uObject*)::app::Uno::Threading::SyncDispatcher__New_1(NULL));
}

void Future__bool___ObjInit_2(Future__bool* __this, ::uObject* dispatcher)
{
    __this->_mutex = ::app::Uno::Threading::Mutex__Create(NULL);
    ::app::Uno::Threading::Future___ObjInit(__this);

    if (dispatcher == NULL)
    {
        U_THROW(::app::Uno::ArgumentNullException__New_5(NULL, ::uGetConstString("dispatcher")));
    }

    __this->_dispatcher = dispatcher;
    __this->State(0);
    __this->_catchables = ::app::Uno::Collections::Queue__Uno_Action_Uno_Exception___New_1(NULL);
    __this->_chainables = ::app::Uno::Collections::Queue__Uno_Threading_Promise_bool___New_1(NULL);
    __this->_thenables = ::app::Uno::Collections::Queue__Uno_Action_bool___New_1(NULL);
}

void Future__bool__Cancel(Future__bool* __this, bool shutdownGracefully)
{
    U_THROW(::app::Uno::Exception__New_2(NULL, ::uGetConstString("Not implemented")));
}

Future__bool* Future__bool__Catch(Future__bool* __this, ::uDelegate* failure)
{
    return __this->Then_1(NULL, failure);
}

void Future__bool__InternalReject(Future__bool* __this, ::app::Uno::Exception* reason)
{
    ::uPtr< ::app::Uno::Threading::Mutex*>(__this->_mutex)->Lock();

    if (__this->State() != 0)
    {
        ::uPtr< ::app::Uno::Threading::Mutex*>(__this->_mutex)->Unlock();
        U_THROW(::app::Uno::Exception__New_2(NULL, ::uGetConstString("This promise is already resolved or rejected")));
    }

    __this->State(2);
    __this->Reason = reason;

    try
    {
        while (::uPtr< ::app::Uno::Collections::Queue__Uno_Action_Uno_Exception_*>(__this->_catchables)->Count() != 0)
        {
            __this->Invoke__Uno_Exception(::uPtr< ::app::Uno::Collections::Queue__Uno_Action_Uno_Exception_*>(__this->_catchables)->Dequeue(), reason);
        }

        while (::uPtr< ::app::Uno::Collections::Queue__Uno_Threading_Promise_bool_*>(__this->_chainables)->Count() != 0)
        {
            ::uPtr< ::app::Uno::Threading::Promise__bool*>(::uPtr< ::app::Uno::Collections::Queue__Uno_Threading_Promise_bool_*>(__this->_chainables)->Dequeue())->Reject(reason);
        }
    }
    catch (const ::uThrowable& __t)
    {
        if (::uIs(__t.Exception, ::app::Uno::Exception__typeof()))
        {
            ::app::Uno::Exception* exception = (::app::Uno::Exception*)__t.Exception;

            while (::uPtr< ::app::Uno::Collections::Queue__Uno_Threading_Promise_bool_*>(__this->_chainables)->Count() != 0)
            {
                ::uPtr< ::app::Uno::Threading::Promise__bool*>(::uPtr< ::app::Uno::Collections::Queue__Uno_Threading_Promise_bool_*>(__this->_chainables)->Dequeue())->Reject(exception);
            }
        }
        else
        {
            throw __t;
        }
    }

    ::uPtr< ::app::Uno::Threading::Mutex*>(__this->_mutex)->Unlock();
}

void Future__bool__InternalResolve(Future__bool* __this, bool result)
{
    ::uPtr< ::app::Uno::Threading::Mutex*>(__this->_mutex)->Lock();

    if (__this->State() != 0)
    {
        ::uPtr< ::app::Uno::Threading::Mutex*>(__this->_mutex)->Unlock();
        U_THROW(::app::Uno::Exception__New_2(NULL, ::uGetConstString("This promise is already resolved or rejected")));
    }

    __this->State(1);
    __this->Result = result;

    try
    {
        while (::uPtr< ::app::Uno::Collections::Queue__Uno_Action_bool_*>(__this->_thenables)->Count() != 0)
        {
            __this->Invoke__bool(::uPtr< ::app::Uno::Collections::Queue__Uno_Action_bool_*>(__this->_thenables)->Dequeue(), result);
        }

        while (::uPtr< ::app::Uno::Collections::Queue__Uno_Threading_Promise_bool_*>(__this->_chainables)->Count() != 0)
        {
            ::uPtr< ::app::Uno::Threading::Promise__bool*>(::uPtr< ::app::Uno::Collections::Queue__Uno_Threading_Promise_bool_*>(__this->_chainables)->Dequeue())->Resolve(result);
        }
    }
    catch (const ::uThrowable& __t)
    {
        if (::uIs(__t.Exception, ::app::Uno::Exception__typeof()))
        {
            ::app::Uno::Exception* exception = (::app::Uno::Exception*)__t.Exception;

            while (::uPtr< ::app::Uno::Collections::Queue__Uno_Threading_Promise_bool_*>(__this->_chainables)->Count() != 0)
            {
                ::uPtr< ::app::Uno::Threading::Promise__bool*>(::uPtr< ::app::Uno::Collections::Queue__Uno_Threading_Promise_bool_*>(__this->_chainables)->Dequeue())->Reject(exception);
            }
        }
        else
        {
            throw __t;
        }
    }

    ::uPtr< ::app::Uno::Threading::Mutex*>(__this->_mutex)->Unlock();
}

void Future__bool__Invoke__bool(Future__bool* __this, ::uDelegate* action, bool arg)
{
    ::app::Uno::Threading::IDispatcher::Invoke(::uPtr< ::uObject*>(__this->_dispatcher), ::uNewDelegateNonVirt(::app::Uno::Action__typeof(), (const void*)::app::Uno::Threading::Future1_Closure__bool__bool__Run, ::app::Uno::Threading::Future1_Closure__bool__bool__New_1(NULL, action, arg)));
}

void Future__bool__Invoke__Uno_Exception(Future__bool* __this, ::uDelegate* action, ::app::Uno::Exception* arg)
{
    ::app::Uno::Threading::IDispatcher::Invoke(::uPtr< ::uObject*>(__this->_dispatcher), ::uNewDelegateNonVirt(::app::Uno::Action__typeof(), (const void*)::app::Uno::Threading::Future1_Closure__bool__Uno_Exception__Run, ::app::Uno::Threading::Future1_Closure__bool__Uno_Exception__New_1(NULL, action, arg)));
}

Future__bool* Future__bool__Then(Future__bool* __this, ::uDelegate* action)
{
    return __this->Then_1(action, NULL);
}

Future__bool* Future__bool__Then_1(Future__bool* __this, ::uDelegate* fulfilled, ::uDelegate* rejected)
{
    ::app::Uno::Threading::Promise__bool* chainable = ::app::Uno::Threading::Promise__bool__New_1(NULL);
    ::uPtr< ::app::Uno::Threading::Mutex*>(__this->_mutex)->Lock();

    try
    {
        if (__this->State() == 1)
        {
            if (::app::Uno::Delegate__op_Inequality(NULL, (::uDelegate*)fulfilled, NULL))
            {
                __this->Invoke__bool(fulfilled, __this->Result);
            }
        }
        else if (__this->State() == 2)
        {
            if (::app::Uno::Delegate__op_Inequality(NULL, (::uDelegate*)rejected, NULL))
            {
                __this->Invoke__Uno_Exception(rejected, __this->Reason);
            }
        }
        else
        {
            ::uPtr< ::app::Uno::Collections::Queue__Uno_Threading_Promise_bool_*>(__this->_chainables)->Enqueue(chainable);

            if (::app::Uno::Delegate__op_Inequality(NULL, (::uDelegate*)fulfilled, NULL))
            {
                ::uPtr< ::app::Uno::Collections::Queue__Uno_Action_bool_*>(__this->_thenables)->Enqueue(fulfilled);
            }

            if (::app::Uno::Delegate__op_Inequality(NULL, (::uDelegate*)rejected, NULL))
            {
                ::uPtr< ::app::Uno::Collections::Queue__Uno_Action_Uno_Exception_*>(__this->_catchables)->Enqueue(rejected);
            }
        }
    }
    catch (const ::uThrowable& __t)
    {
        if (::uIs(__t.Exception, ::app::Uno::Exception__typeof()))
        {
            ::app::Uno::Exception* exception = (::app::Uno::Exception*)__t.Exception;
            ::uPtr< ::app::Uno::Threading::Promise__bool*>(chainable)->Reject(exception);
        }
        else
        {
            throw __t;
        }
    }

    ::uPtr< ::app::Uno::Threading::Mutex*>(__this->_mutex)->Unlock();
    return ::uCast< Future__bool*>((::uObject*)chainable, Future__bool__typeof());
}

void Future__bool__Wait(Future__bool* __this)
{
    U_THROW(::app::Uno::Exception__New_2(NULL, ::uGetConstString("Not implemented")));
}

// This file was generated based on 'C:\ProgramData\Uno\Packages\Uno.Threading\0.13.2\$.uno'.
// WARNING: Changes might be lost if you edit this file directly.

Future__Fuse_Camera_PictureResult__uType* Future__Fuse_Camera_PictureResult__typeof()
{
    static ::uStaticStrong<Future__Fuse_Camera_PictureResult__uType*> type;
    if (type != NULL) return type;

    type = (Future__Fuse_Camera_PictureResult__uType*)::uAllocClassType(sizeof(Future__Fuse_Camera_PictureResult__uType), "Uno.Threading.Future<Fuse.Camera.PictureResult>", false, 0, 7, 0);

    type->SetBaseType(::app::Uno::Threading::Future__typeof());
    type->__fp_Cancel = (void(*)(::app::Uno::Threading::Future*, bool))Future__Fuse_Camera_PictureResult__Cancel;
    type->__fp_Wait = (void(*)(::app::Uno::Threading::Future*))Future__Fuse_Camera_PictureResult__Wait;

    type->SetStrongRefs(
        "_catchables", offsetof(Future__Fuse_Camera_PictureResult, _catchables),
        "_chainables", offsetof(Future__Fuse_Camera_PictureResult, _chainables),
        "_dispatcher", offsetof(Future__Fuse_Camera_PictureResult, _dispatcher),
        "_mutex", offsetof(Future__Fuse_Camera_PictureResult, _mutex),
        "_thenables", offsetof(Future__Fuse_Camera_PictureResult, _thenables),
        "Reason", offsetof(Future__Fuse_Camera_PictureResult, Reason),
        "Result", offsetof(Future__Fuse_Camera_PictureResult, Result));

    type->SetFields(7,
        ::uNewField("_catchables", NULL, offsetof(Future__Fuse_Camera_PictureResult, _catchables), ::app::Uno::Collections::Queue__Uno_Action_Uno_Exception___typeof()),
        ::uNewField("_chainables", NULL, offsetof(Future__Fuse_Camera_PictureResult, _chainables), ::app::Uno::Collections::Queue__Uno_Threading_Promise_Fuse_Camera_PictureResult___typeof()),
        ::uNewField("_dispatcher", NULL, offsetof(Future__Fuse_Camera_PictureResult, _dispatcher), ::app::Uno::Threading::IDispatcher__typeof()),
        ::uNewField("_mutex", NULL, offsetof(Future__Fuse_Camera_PictureResult, _mutex), ::app::Uno::Threading::Mutex__typeof()),
        ::uNewField("_thenables", NULL, offsetof(Future__Fuse_Camera_PictureResult, _thenables), ::app::Uno::Collections::Queue__Uno_Action_Fuse_Camera_PictureResult___typeof()),
        ::uNewField("Reason", NULL, offsetof(Future__Fuse_Camera_PictureResult, Reason), ::app::Uno::Exception__typeof()),
        ::uNewField("Result", NULL, offsetof(Future__Fuse_Camera_PictureResult, Result), ::app::Fuse::Camera::PictureResult__typeof()));

    type->SetFunctions(3,
        ::uNewFunction("Catch", Future__Fuse_Camera_PictureResult__Catch, 0, false, Future__Fuse_Camera_PictureResult__typeof(), ::app::Uno::Action__Uno_Exception__typeof()),
        ::uNewFunction("Then", Future__Fuse_Camera_PictureResult__Then, 0, false, Future__Fuse_Camera_PictureResult__typeof(), ::app::Uno::Action__Fuse_Camera_PictureResult__typeof()),
        ::uNewFunction("Then", Future__Fuse_Camera_PictureResult__Then_1, 0, false, Future__Fuse_Camera_PictureResult__typeof(), ::app::Uno::Action__Fuse_Camera_PictureResult__typeof(), ::app::Uno::Action__Uno_Exception__typeof()));

    ::uRegisterType(type);
    return type;
}

void Future__Fuse_Camera_PictureResult___ObjInit_1(Future__Fuse_Camera_PictureResult* __this)
{
    __this->_mutex = ::app::Uno::Threading::Mutex__Create(NULL);
    __this->_ObjInit_2((::uObject*)::app::Uno::Threading::SyncDispatcher__New_1(NULL));
}

void Future__Fuse_Camera_PictureResult___ObjInit_2(Future__Fuse_Camera_PictureResult* __this, ::uObject* dispatcher)
{
    __this->_mutex = ::app::Uno::Threading::Mutex__Create(NULL);
    ::app::Uno::Threading::Future___ObjInit(__this);

    if (dispatcher == NULL)
    {
        U_THROW(::app::Uno::ArgumentNullException__New_5(NULL, ::uGetConstString("dispatcher")));
    }

    __this->_dispatcher = dispatcher;
    __this->State(0);
    __this->_catchables = ::app::Uno::Collections::Queue__Uno_Action_Uno_Exception___New_1(NULL);
    __this->_chainables = ::app::Uno::Collections::Queue__Uno_Threading_Promise_Fuse_Camera_PictureResult___New_1(NULL);
    __this->_thenables = ::app::Uno::Collections::Queue__Uno_Action_Fuse_Camera_PictureResult___New_1(NULL);
}

void Future__Fuse_Camera_PictureResult__Cancel(Future__Fuse_Camera_PictureResult* __this, bool shutdownGracefully)
{
    U_THROW(::app::Uno::Exception__New_2(NULL, ::uGetConstString("Not implemented")));
}

Future__Fuse_Camera_PictureResult* Future__Fuse_Camera_PictureResult__Catch(Future__Fuse_Camera_PictureResult* __this, ::uDelegate* failure)
{
    return __this->Then_1(NULL, failure);
}

void Future__Fuse_Camera_PictureResult__InternalReject(Future__Fuse_Camera_PictureResult* __this, ::app::Uno::Exception* reason)
{
    ::uPtr< ::app::Uno::Threading::Mutex*>(__this->_mutex)->Lock();

    if (__this->State() != 0)
    {
        ::uPtr< ::app::Uno::Threading::Mutex*>(__this->_mutex)->Unlock();
        U_THROW(::app::Uno::Exception__New_2(NULL, ::uGetConstString("This promise is already resolved or rejected")));
    }

    __this->State(2);
    __this->Reason = reason;

    try
    {
        while (::uPtr< ::app::Uno::Collections::Queue__Uno_Action_Uno_Exception_*>(__this->_catchables)->Count() != 0)
        {
            __this->Invoke__Uno_Exception(::uPtr< ::app::Uno::Collections::Queue__Uno_Action_Uno_Exception_*>(__this->_catchables)->Dequeue(), reason);
        }

        while (::uPtr< ::app::Uno::Collections::Queue__Uno_Threading_Promise_Fuse_Camera_PictureResult_*>(__this->_chainables)->Count() != 0)
        {
            ::uPtr< ::app::Uno::Threading::Promise__Fuse_Camera_PictureResult*>(::uPtr< ::app::Uno::Collections::Queue__Uno_Threading_Promise_Fuse_Camera_PictureResult_*>(__this->_chainables)->Dequeue())->Reject(reason);
        }
    }
    catch (const ::uThrowable& __t)
    {
        if (::uIs(__t.Exception, ::app::Uno::Exception__typeof()))
        {
            ::app::Uno::Exception* exception = (::app::Uno::Exception*)__t.Exception;

            while (::uPtr< ::app::Uno::Collections::Queue__Uno_Threading_Promise_Fuse_Camera_PictureResult_*>(__this->_chainables)->Count() != 0)
            {
                ::uPtr< ::app::Uno::Threading::Promise__Fuse_Camera_PictureResult*>(::uPtr< ::app::Uno::Collections::Queue__Uno_Threading_Promise_Fuse_Camera_PictureResult_*>(__this->_chainables)->Dequeue())->Reject(exception);
            }
        }
        else
        {
            throw __t;
        }
    }

    ::uPtr< ::app::Uno::Threading::Mutex*>(__this->_mutex)->Unlock();
}

void Future__Fuse_Camera_PictureResult__InternalResolve(Future__Fuse_Camera_PictureResult* __this, ::app::Fuse::Camera::PictureResult* result)
{
    ::uPtr< ::app::Uno::Threading::Mutex*>(__this->_mutex)->Lock();

    if (__this->State() != 0)
    {
        ::uPtr< ::app::Uno::Threading::Mutex*>(__this->_mutex)->Unlock();
        U_THROW(::app::Uno::Exception__New_2(NULL, ::uGetConstString("This promise is already resolved or rejected")));
    }

    __this->State(1);
    __this->Result = result;

    try
    {
        while (::uPtr< ::app::Uno::Collections::Queue__Uno_Action_Fuse_Camera_PictureResult_*>(__this->_thenables)->Count() != 0)
        {
            __this->Invoke__Fuse_Camera_PictureResult(::uPtr< ::app::Uno::Collections::Queue__Uno_Action_Fuse_Camera_PictureResult_*>(__this->_thenables)->Dequeue(), result);
        }

        while (::uPtr< ::app::Uno::Collections::Queue__Uno_Threading_Promise_Fuse_Camera_PictureResult_*>(__this->_chainables)->Count() != 0)
        {
            ::uPtr< ::app::Uno::Threading::Promise__Fuse_Camera_PictureResult*>(::uPtr< ::app::Uno::Collections::Queue__Uno_Threading_Promise_Fuse_Camera_PictureResult_*>(__this->_chainables)->Dequeue())->Resolve(result);
        }
    }
    catch (const ::uThrowable& __t)
    {
        if (::uIs(__t.Exception, ::app::Uno::Exception__typeof()))
        {
            ::app::Uno::Exception* exception = (::app::Uno::Exception*)__t.Exception;

            while (::uPtr< ::app::Uno::Collections::Queue__Uno_Threading_Promise_Fuse_Camera_PictureResult_*>(__this->_chainables)->Count() != 0)
            {
                ::uPtr< ::app::Uno::Threading::Promise__Fuse_Camera_PictureResult*>(::uPtr< ::app::Uno::Collections::Queue__Uno_Threading_Promise_Fuse_Camera_PictureResult_*>(__this->_chainables)->Dequeue())->Reject(exception);
            }
        }
        else
        {
            throw __t;
        }
    }

    ::uPtr< ::app::Uno::Threading::Mutex*>(__this->_mutex)->Unlock();
}

void Future__Fuse_Camera_PictureResult__Invoke__Fuse_Camera_PictureResult(Future__Fuse_Camera_PictureResult* __this, ::uDelegate* action, ::app::Fuse::Camera::PictureResult* arg)
{
    ::app::Uno::Threading::IDispatcher::Invoke(::uPtr< ::uObject*>(__this->_dispatcher), ::uNewDelegateNonVirt(::app::Uno::Action__typeof(), (const void*)::app::Uno::Threading::Future1_Closure__Fuse_Camera_PictureResult__Fuse_Camera_PictureResult__Run, ::app::Uno::Threading::Future1_Closure__Fuse_Camera_PictureResult__Fuse_Camera_PictureResult__New_1(NULL, action, arg)));
}

void Future__Fuse_Camera_PictureResult__Invoke__Uno_Exception(Future__Fuse_Camera_PictureResult* __this, ::uDelegate* action, ::app::Uno::Exception* arg)
{
    ::app::Uno::Threading::IDispatcher::Invoke(::uPtr< ::uObject*>(__this->_dispatcher), ::uNewDelegateNonVirt(::app::Uno::Action__typeof(), (const void*)::app::Uno::Threading::Future1_Closure__Fuse_Camera_PictureResult__Uno_Exception__Run, ::app::Uno::Threading::Future1_Closure__Fuse_Camera_PictureResult__Uno_Exception__New_1(NULL, action, arg)));
}

Future__Fuse_Camera_PictureResult* Future__Fuse_Camera_PictureResult__Then(Future__Fuse_Camera_PictureResult* __this, ::uDelegate* action)
{
    return __this->Then_1(action, NULL);
}

Future__Fuse_Camera_PictureResult* Future__Fuse_Camera_PictureResult__Then_1(Future__Fuse_Camera_PictureResult* __this, ::uDelegate* fulfilled, ::uDelegate* rejected)
{
    ::app::Uno::Threading::Promise__Fuse_Camera_PictureResult* chainable = ::app::Uno::Threading::Promise__Fuse_Camera_PictureResult__New_1(NULL);
    ::uPtr< ::app::Uno::Threading::Mutex*>(__this->_mutex)->Lock();

    try
    {
        if (__this->State() == 1)
        {
            if (::app::Uno::Delegate__op_Inequality(NULL, (::uDelegate*)fulfilled, NULL))
            {
                __this->Invoke__Fuse_Camera_PictureResult(fulfilled, __this->Result);
            }
        }
        else if (__this->State() == 2)
        {
            if (::app::Uno::Delegate__op_Inequality(NULL, (::uDelegate*)rejected, NULL))
            {
                __this->Invoke__Uno_Exception(rejected, __this->Reason);
            }
        }
        else
        {
            ::uPtr< ::app::Uno::Collections::Queue__Uno_Threading_Promise_Fuse_Camera_PictureResult_*>(__this->_chainables)->Enqueue(chainable);

            if (::app::Uno::Delegate__op_Inequality(NULL, (::uDelegate*)fulfilled, NULL))
            {
                ::uPtr< ::app::Uno::Collections::Queue__Uno_Action_Fuse_Camera_PictureResult_*>(__this->_thenables)->Enqueue(fulfilled);
            }

            if (::app::Uno::Delegate__op_Inequality(NULL, (::uDelegate*)rejected, NULL))
            {
                ::uPtr< ::app::Uno::Collections::Queue__Uno_Action_Uno_Exception_*>(__this->_catchables)->Enqueue(rejected);
            }
        }
    }
    catch (const ::uThrowable& __t)
    {
        if (::uIs(__t.Exception, ::app::Uno::Exception__typeof()))
        {
            ::app::Uno::Exception* exception = (::app::Uno::Exception*)__t.Exception;
            ::uPtr< ::app::Uno::Threading::Promise__Fuse_Camera_PictureResult*>(chainable)->Reject(exception);
        }
        else
        {
            throw __t;
        }
    }

    ::uPtr< ::app::Uno::Threading::Mutex*>(__this->_mutex)->Unlock();
    return ::uCast< Future__Fuse_Camera_PictureResult*>((::uObject*)chainable, Future__Fuse_Camera_PictureResult__typeof());
}

void Future__Fuse_Camera_PictureResult__Wait(Future__Fuse_Camera_PictureResult* __this)
{
    U_THROW(::app::Uno::Exception__New_2(NULL, ::uGetConstString("Not implemented")));
}

// This file was generated based on 'C:\ProgramData\Uno\Packages\Uno.Threading\0.13.2\$.uno'.
// WARNING: Changes might be lost if you edit this file directly.

Future__string__uType* Future__string__typeof()
{
    static ::uStaticStrong<Future__string__uType*> type;
    if (type != NULL) return type;

    type = (Future__string__uType*)::uAllocClassType(sizeof(Future__string__uType), "Uno.Threading.Future<string>", false, 0, 7, 0);

    type->SetBaseType(::app::Uno::Threading::Future__typeof());
    type->__fp_Cancel = (void(*)(::app::Uno::Threading::Future*, bool))Future__string__Cancel;
    type->__fp_Wait = (void(*)(::app::Uno::Threading::Future*))Future__string__Wait;

    type->SetStrongRefs(
        "_catchables", offsetof(Future__string, _catchables),
        "_chainables", offsetof(Future__string, _chainables),
        "_dispatcher", offsetof(Future__string, _dispatcher),
        "_mutex", offsetof(Future__string, _mutex),
        "_thenables", offsetof(Future__string, _thenables),
        "Reason", offsetof(Future__string, Reason),
        "Result", offsetof(Future__string, Result));

    type->SetFields(7,
        ::uNewField("_catchables", NULL, offsetof(Future__string, _catchables), ::app::Uno::Collections::Queue__Uno_Action_Uno_Exception___typeof()),
        ::uNewField("_chainables", NULL, offsetof(Future__string, _chainables), ::app::Uno::Collections::Queue__Uno_Threading_Promise_string___typeof()),
        ::uNewField("_dispatcher", NULL, offsetof(Future__string, _dispatcher), ::app::Uno::Threading::IDispatcher__typeof()),
        ::uNewField("_mutex", NULL, offsetof(Future__string, _mutex), ::app::Uno::Threading::Mutex__typeof()),
        ::uNewField("_thenables", NULL, offsetof(Future__string, _thenables), ::app::Uno::Collections::Queue__Uno_Action_string___typeof()),
        ::uNewField("Reason", NULL, offsetof(Future__string, Reason), ::app::Uno::Exception__typeof()),
        ::uNewField("Result", NULL, offsetof(Future__string, Result), ::app::Uno::String__typeof()));

    type->SetFunctions(3,
        ::uNewFunction("Catch", Future__string__Catch, 0, false, Future__string__typeof(), ::app::Uno::Action__Uno_Exception__typeof()),
        ::uNewFunction("Then", Future__string__Then, 0, false, Future__string__typeof(), ::app::Uno::Action__string__typeof()),
        ::uNewFunction("Then", Future__string__Then_1, 0, false, Future__string__typeof(), ::app::Uno::Action__string__typeof(), ::app::Uno::Action__Uno_Exception__typeof()));

    ::uRegisterType(type);
    return type;
}

void Future__string___ObjInit_1(Future__string* __this)
{
    __this->_mutex = ::app::Uno::Threading::Mutex__Create(NULL);
    __this->_ObjInit_2((::uObject*)::app::Uno::Threading::SyncDispatcher__New_1(NULL));
}

void Future__string___ObjInit_2(Future__string* __this, ::uObject* dispatcher)
{
    __this->_mutex = ::app::Uno::Threading::Mutex__Create(NULL);
    ::app::Uno::Threading::Future___ObjInit(__this);

    if (dispatcher == NULL)
    {
        U_THROW(::app::Uno::ArgumentNullException__New_5(NULL, ::uGetConstString("dispatcher")));
    }

    __this->_dispatcher = dispatcher;
    __this->State(0);
    __this->_catchables = ::app::Uno::Collections::Queue__Uno_Action_Uno_Exception___New_1(NULL);
    __this->_chainables = ::app::Uno::Collections::Queue__Uno_Threading_Promise_string___New_1(NULL);
    __this->_thenables = ::app::Uno::Collections::Queue__Uno_Action_string___New_1(NULL);
}

void Future__string__Cancel(Future__string* __this, bool shutdownGracefully)
{
    U_THROW(::app::Uno::Exception__New_2(NULL, ::uGetConstString("Not implemented")));
}

Future__string* Future__string__Catch(Future__string* __this, ::uDelegate* failure)
{
    return __this->Then_1(NULL, failure);
}

void Future__string__InternalReject(Future__string* __this, ::app::Uno::Exception* reason)
{
    ::uPtr< ::app::Uno::Threading::Mutex*>(__this->_mutex)->Lock();

    if (__this->State() != 0)
    {
        ::uPtr< ::app::Uno::Threading::Mutex*>(__this->_mutex)->Unlock();
        U_THROW(::app::Uno::Exception__New_2(NULL, ::uGetConstString("This promise is already resolved or rejected")));
    }

    __this->State(2);
    __this->Reason = reason;

    try
    {
        while (::uPtr< ::app::Uno::Collections::Queue__Uno_Action_Uno_Exception_*>(__this->_catchables)->Count() != 0)
        {
            __this->Invoke__Uno_Exception(::uPtr< ::app::Uno::Collections::Queue__Uno_Action_Uno_Exception_*>(__this->_catchables)->Dequeue(), reason);
        }

        while (::uPtr< ::app::Uno::Collections::Queue__Uno_Threading_Promise_string_*>(__this->_chainables)->Count() != 0)
        {
            ::uPtr< ::app::Uno::Threading::Promise__string*>(::uPtr< ::app::Uno::Collections::Queue__Uno_Threading_Promise_string_*>(__this->_chainables)->Dequeue())->Reject(reason);
        }
    }
    catch (const ::uThrowable& __t)
    {
        if (::uIs(__t.Exception, ::app::Uno::Exception__typeof()))
        {
            ::app::Uno::Exception* exception = (::app::Uno::Exception*)__t.Exception;

            while (::uPtr< ::app::Uno::Collections::Queue__Uno_Threading_Promise_string_*>(__this->_chainables)->Count() != 0)
            {
                ::uPtr< ::app::Uno::Threading::Promise__string*>(::uPtr< ::app::Uno::Collections::Queue__Uno_Threading_Promise_string_*>(__this->_chainables)->Dequeue())->Reject(exception);
            }
        }
        else
        {
            throw __t;
        }
    }

    ::uPtr< ::app::Uno::Threading::Mutex*>(__this->_mutex)->Unlock();
}

void Future__string__InternalResolve(Future__string* __this, ::uString* result)
{
    ::uPtr< ::app::Uno::Threading::Mutex*>(__this->_mutex)->Lock();

    if (__this->State() != 0)
    {
        ::uPtr< ::app::Uno::Threading::Mutex*>(__this->_mutex)->Unlock();
        U_THROW(::app::Uno::Exception__New_2(NULL, ::uGetConstString("This promise is already resolved or rejected")));
    }

    __this->State(1);
    __this->Result = result;

    try
    {
        while (::uPtr< ::app::Uno::Collections::Queue__Uno_Action_string_*>(__this->_thenables)->Count() != 0)
        {
            __this->Invoke__string(::uPtr< ::app::Uno::Collections::Queue__Uno_Action_string_*>(__this->_thenables)->Dequeue(), result);
        }

        while (::uPtr< ::app::Uno::Collections::Queue__Uno_Threading_Promise_string_*>(__this->_chainables)->Count() != 0)
        {
            ::uPtr< ::app::Uno::Threading::Promise__string*>(::uPtr< ::app::Uno::Collections::Queue__Uno_Threading_Promise_string_*>(__this->_chainables)->Dequeue())->Resolve(result);
        }
    }
    catch (const ::uThrowable& __t)
    {
        if (::uIs(__t.Exception, ::app::Uno::Exception__typeof()))
        {
            ::app::Uno::Exception* exception = (::app::Uno::Exception*)__t.Exception;

            while (::uPtr< ::app::Uno::Collections::Queue__Uno_Threading_Promise_string_*>(__this->_chainables)->Count() != 0)
            {
                ::uPtr< ::app::Uno::Threading::Promise__string*>(::uPtr< ::app::Uno::Collections::Queue__Uno_Threading_Promise_string_*>(__this->_chainables)->Dequeue())->Reject(exception);
            }
        }
        else
        {
            throw __t;
        }
    }

    ::uPtr< ::app::Uno::Threading::Mutex*>(__this->_mutex)->Unlock();
}

void Future__string__Invoke__string(Future__string* __this, ::uDelegate* action, ::uString* arg)
{
    ::app::Uno::Threading::IDispatcher::Invoke(::uPtr< ::uObject*>(__this->_dispatcher), ::uNewDelegateNonVirt(::app::Uno::Action__typeof(), (const void*)::app::Uno::Threading::Future1_Closure__string__string__Run, ::app::Uno::Threading::Future1_Closure__string__string__New_1(NULL, action, arg)));
}

void Future__string__Invoke__Uno_Exception(Future__string* __this, ::uDelegate* action, ::app::Uno::Exception* arg)
{
    ::app::Uno::Threading::IDispatcher::Invoke(::uPtr< ::uObject*>(__this->_dispatcher), ::uNewDelegateNonVirt(::app::Uno::Action__typeof(), (const void*)::app::Uno::Threading::Future1_Closure__string__Uno_Exception__Run, ::app::Uno::Threading::Future1_Closure__string__Uno_Exception__New_1(NULL, action, arg)));
}

Future__string* Future__string__Then(Future__string* __this, ::uDelegate* action)
{
    return __this->Then_1(action, NULL);
}

Future__string* Future__string__Then_1(Future__string* __this, ::uDelegate* fulfilled, ::uDelegate* rejected)
{
    ::app::Uno::Threading::Promise__string* chainable = ::app::Uno::Threading::Promise__string__New_1(NULL);
    ::uPtr< ::app::Uno::Threading::Mutex*>(__this->_mutex)->Lock();

    try
    {
        if (__this->State() == 1)
        {
            if (::app::Uno::Delegate__op_Inequality(NULL, (::uDelegate*)fulfilled, NULL))
            {
                __this->Invoke__string(fulfilled, __this->Result);
            }
        }
        else if (__this->State() == 2)
        {
            if (::app::Uno::Delegate__op_Inequality(NULL, (::uDelegate*)rejected, NULL))
            {
                __this->Invoke__Uno_Exception(rejected, __this->Reason);
            }
        }
        else
        {
            ::uPtr< ::app::Uno::Collections::Queue__Uno_Threading_Promise_string_*>(__this->_chainables)->Enqueue(chainable);

            if (::app::Uno::Delegate__op_Inequality(NULL, (::uDelegate*)fulfilled, NULL))
            {
                ::uPtr< ::app::Uno::Collections::Queue__Uno_Action_string_*>(__this->_thenables)->Enqueue(fulfilled);
            }

            if (::app::Uno::Delegate__op_Inequality(NULL, (::uDelegate*)rejected, NULL))
            {
                ::uPtr< ::app::Uno::Collections::Queue__Uno_Action_Uno_Exception_*>(__this->_catchables)->Enqueue(rejected);
            }
        }
    }
    catch (const ::uThrowable& __t)
    {
        if (::uIs(__t.Exception, ::app::Uno::Exception__typeof()))
        {
            ::app::Uno::Exception* exception = (::app::Uno::Exception*)__t.Exception;
            ::uPtr< ::app::Uno::Threading::Promise__string*>(chainable)->Reject(exception);
        }
        else
        {
            throw __t;
        }
    }

    ::uPtr< ::app::Uno::Threading::Mutex*>(__this->_mutex)->Unlock();
    return ::uCast< Future__string*>((::uObject*)chainable, Future__string__typeof());
}

void Future__string__Wait(Future__string* __this)
{
    U_THROW(::app::Uno::Exception__New_2(NULL, ::uGetConstString("Not implemented")));
}

}}}


text:
module MojeIDAttributes
  AVAILABLE_ATTRIBUTES = %W(
    http://axschema.org/namePerson
    http://axschema.org/namePerson/first
    http://axschema.org/namePerson/last
    http://axschema.org/namePerson/friendly
    http://axschema.org/company/name
    http://axschema.org/contact/postalAddress/home
    http://axschema.org/contact/postalAddressAdditional/home
    http://specs.nic.cz/attr/addr/main/street3
    http://axschema.org/contact/city/home
    http://axschema.org/contact/state/home
    http://axschema.org/contact/country/home
    http://axschema.org/contact/postalCode/home
    http://specs.nic.cz/attr/addr/bill/street
    http://specs.nic.cz/attr/addr/bill/street2
    http://specs.nic.cz/attr/addr/bill/street3
    http://specs.nic.cz/attr/addr/bill/city
    http://specs.nic.cz/attr/addr/bill/sp
    http://specs.nic.cz/attr/addr/bill/cc
    http://specs.nic.cz/attr/addr/bill/pc
    http://specs.nic.cz/attr/addr/ship/street
    http://specs.nic.cz/attr/addr/ship/street2
    http://specs.nic.cz/attr/addr/ship/street3
    http://specs.nic.cz/attr/addr/ship/city
    http://specs.nic.cz/attr/addr/ship/sp
    http://specs.nic.cz/attr/addr/ship/cc
    http://specs.nic.cz/attr/addr/ship/pc
    http://specs.nic.cz/attr/addr/mail/street
    http://specs.nic.cz/attr/addr/mail/street2
    http://specs.nic.cz/attr/addr/mail/street3
    http://specs.nic.cz/attr/addr/mail/city
    http://specs.nic.cz/attr/addr/mail/sp
    http://specs.nic.cz/attr/addr/mail/cc
    http://specs.nic.cz/attr/addr/mail/pc
    http://axschema.org/contact/phone/default
    http://axschema.org/contact/phone/home
    http://axschema.org/contact/phone/business
    http://axschema.org/contact/phone/cell
    http://axschema.org/contact/phone/fax
    http://axschema.org/contact/email
    http://specs.nic.cz/attr/email/notify
    http://specs.nic.cz/attr/email/next
    http://axschema.org/contact/web/default
    http://axschema.org/contact/web/blog
    http://specs.nic.cz/attr/url/personal
    http://specs.nic.cz/attr/url/work
    http://specs.nic.cz/attr/url/rss
    http://specs.nic.cz/attr/url/facebook
    http://specs.nic.cz/attr/url/twitter
    http://specs.nic.cz/attr/url/linkedin
    http://axschema.org/contact/IM/ICQ
    http://axschema.org/contact/IM/Jabber
    http://axschema.org/contact/IM/Skype
    http://specs.nic.cz/attr/im/google_talk
    http://specs.nic.cz/attr/im/windows_live
    http://specs.nic.cz/attr/contact/ident/vat_id
    http://specs.nic.cz/attr/contact/vat
    http://specs.nic.cz/attr/contact/ident/card
    http://specs.nic.cz/attr/contact/ident/pass
    http://specs.nic.cz/attr/contact/ident/ssn
    http://specs.nic.cz/attr/contact/student
    http://specs.nic.cz/attr/contact/valid
    http://specs.nic.cz/attr/contact/status
    http://specs.nic.cz/attr/contact/adult
    http://specs.nic.cz/attr/contact/image
  )
end


text:
package com.rocketfuel.sdbc.sqlserver.jdbc

import org.scalatest.BeforeAndAfterEach

import scala.collection.immutable.Seq

class RichResultSetSpec
  extends SqlServerSuite
  with BeforeAndAfterEach {

  test("seq() works on a single result") {implicit connection =>
    val results = Select[Int]("SELECT CAST(1 AS int)").iterator().toSeq
    assert(results == Seq(1))
  }

  test("seq() works on several results") {implicit connection =>
    val randoms = Seq.fill(10)(util.Random.nextInt())
    Execute("CREATE TABLE tbl (x int)").execute()

    val batch = randoms.foldLeft(Batch("INSERT INTO tbl (x) VALUES (@x)")) {
      case (batch, r) =>
        batch.addBatch("x" -> r)
    }

    val insertions = batch.iterator()

    assert(insertions.sum == randoms.size)

    val results = Select[Int]("SELECT x FROM tbl").iterator().toSeq
    assert(results == randoms)
  }

  test("using SelectForUpdate to update a value works") {implicit connection =>
    val randoms = Seq.fill(10)(util.Random.nextInt()).sorted

    Execute("CREATE TABLE tbl (id int IDENTITY(1,1) PRIMARY KEY, x int)").execute()

    val batch = randoms.foldLeft(Batch("INSERT INTO tbl (x) VALUES (@x)")) {
      case (batch, r) =>
        batch.addBatch("x" -> r)
    }

    batch.iterator()

    for (row <- connection.iteratorForUpdate("SELECT x FROM tbl")) {
      row("x") = row.get[Int]("x").map(_ + 1)
      row.updateRow()
    }

    val afterUpdate = connection.iterator[Int]("SELECT x FROM tbl ORDER BY x ASC").toSeq

    for ((afterUpdate, original) <- afterUpdate.zip(randoms)) {
      assertResult(original + 1)(afterUpdate)
    }
  }

  override protected def afterEach(): Unit = {
    withSql(_.execute("IF object_id('dbo.tbl') IS NOT NULL DROP TABLE tbl"))
  }
}


text:
<!DOCTYPE html>

        <title> Smart forms - contact form </title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

        <link rel="stylesheet" type="text/css"  href="css/smart-forms.css">
        <link rel="stylesheet" type="text/css"  href="css/smart-addons.css">
        <link rel="stylesheet" type="text/css"  href="css/font-awesome.min.css">

            Show Modal Form

Contact Form

                    ×

                                <form method="post" action="php/smartprocess.php" id="smart-form">

                                            <input type="text" name="sendername" id="sendername" class="gui-input" placeholder="Enter name">

                                            <input type="email" name="emailaddress" id="emailaddress" class="gui-input" placeholder="Email address">

                                            <input type="text" name="sendersubject" id="sendersubject" class="gui-input" placeholder="Enter subjec">

                                            <textarea class="gui-textarea" id="sendermessage" name="sendermessage" placeholder="Enter message"></textarea>

                                             Hint: Please enter between 80 - 300 characters.

                                                <input type="text" name="captcha" id="captcha" class="gui-input sfcode" maxlength="6" placeholder="Enter CAPTCHA">

                                                <img src="php/captcha/captcha.php?<?php echo time();?>" id="captchax" alt="captcha">

                                        <button type="submit" data-btntext-sending="Sending..." class="button btn-primary"> Submit Form </button>
                                        <button type="reset" class="button"> Cancel </button>

                                </form>


text:
package org.apereo.portal.groups.pags.testers;

import org.apereo.portal.groups.pags.dao.IPersonAttributesGroupTestDefinition;

/**
 * Tests if any of the possibly multiple values of the attribute are GE (greater than or equal to)
 * the test value.
 *
 * @author Dan Ellentuck
 */
public class IntegerGETester extends AbstractIntegerTester {

    /** @since 4.3 */
    public IntegerGETester(IPersonAttributesGroupTestDefinition definition) {
        super(definition);
    }

    public boolean test(int attributeValue) {
        return !(attributeValue < getTestInteger());
    }

}


text:
This is an example, how one can implement redux layer with redux-tiles. [This official reference](https://github.com/HackerNews/API) was used. Current implementation supports fetching different pages of different types of pages (e.g. top stories, news, etc), with support of caching.
Tiles code is located in [hn-tiles.js](./hn-tiles.js) file, with extensive number of commentaries.

You can run it by yourself:
```bash
yarn install
yarn test # note time for the second test – caching should work!
```


text:
<?php

declare(strict_types=1);

namespace Eloquent\Phony\Test;

use Traversable;

interface TestInterfaceC extends Traversable
{
}


text:
@interface Sequence_ThreeTrivialGreenOperations : NSObject <COSequence>
@property (assign, nonatomic) NSUInteger numberOfOperations;
@end

@interface Sequence_FirstOperationRejects : NSObject <COSequence>
@end

@interface Sequence_FirstOperationRejects_3Attempts : NSObject <COSequence>
@property (assign, nonatomic) NSUInteger numberOfOperations;
@end

@interface LinearSequence_ThreeOperations_EachReturningNSNull : COLinearSequence
@end


text:
ES5Harness.registerTest({

    id: "15.4.4.18-3-13",

    path: "TestCases/chapter15/15.4/15.4.4/15.4.4.18/15.4.4.18-3-13.js",

    description: "Array.prototype.forEach - 'length' is a string containing a decimal number",

    test: function testcase() {

        var testResult = false;

        function callbackfn(val, idx, obj) {
            testResult = (val > 10);
        }
        var obj = { 1: 11, 2: 9, length: "2.5" };

        Array.prototype.forEach.call(obj, callbackfn);

        return testResult;
    },

    precondition: function prereq() {
        return fnExists(Array.prototype.forEach);
    }

});


text:
<?php
class Prl_110 extends CI_Model
{
    function __construct()
    {
        parent::__construct();
        $this->sess_id = $this->session->userdata('userid');
    }

    function load_xls($type,$excelreader,$filename) {
        //read-file
        $objReader = $excelreader->createReader($type);
        $objPHPExcel  = $objReader ->load('./files/uploads/'.$filename);
        return $objPHPExcel;
    }

    function report1($su_id,$filename) {
        $array = explode('.', $filename);
        $extension = end($array);

        $this->load->library('excelReader');
        if ($extension == "xls") {
            $objPHPExcel = $this->load_xls('Excel5',$this->excelreader,$filename);
        } else if ($extension == "xlsx") {
            $objPHPExcel = $this->load_xls('Excel2007',$this->excelreader,$filename);
        } else {
            return "nok";
        }

        $worksheet = $objPHPExcel->getSheet(0);
		$lastRow   = $worksheet->getHighestRow();

        //cek-value-db

        /*$query  = $this->db->query('SELECT * FROM SMY_PTKP_401 ORDER BY POTENSI DESC LIMIT 1');
        $result = $query->result();

        foreach ($result as $key) {
            $this->db->where('WPP_ID',$key->WPP_ID);
            $this->db->where('KOMODITI_ID',$key->KOMODITI_ID);
            $this->db->where('POTENSI',$key->POTENSI);
            $this->db->where('JTB',$key->JTB);
            $this->db->where('PEMANFAATAN',$key->PEMANFAATAN);
        }

        $q = $this->db->get('SMY_PTKP_401');
        $cek = $q->num_rows();
        //echo $this->db->last_query();
        die();
        if ($cek > 0) {

            $this->session->set_flashdata('msg','
<button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>Data Sudah Ada!
');
            redirect('administrator/source_upload/add');
        }else{*/

        //get-value-from-excel
        //value-tahun
    /*    $query  = $this->db->query('SELECT TAHUN FROM SMY_RPL_109 ORDER BY TAHUN DESC LIMIT 1');
        $result = $query->result_array();
        $tahun  = 1; //tambah data tahun db 1
        foreach($result as $item) { $tahun += $item['TAHUN'];}*/

        //nama se
        $prov = array();
        $kab = array();
        $nkk = array();
        $dHk = array();
        for ($i=6; $i <=15 ; $i++) {
            # code...
            $prov[] = $worksheet->getCell("C".$i)->getValue();
            $kab[]  = $worksheet->getCell("D".$i)->getValue();
            $nkk[]  = $worksheet->getCell("E".$i)->getValue();
            $l[]    = $worksheet->getCell("F".$i)->getValue();
            $dHk[]  = $worksheet->getCell("G".$i)->getValue();
        }

        //input_db
        for ($i=0; $i < count($prov); $i++) {
            # code...
            $data = array(
                'PROVINSI'=>$prov[$i],
                'KABUPATEN'=>$kab[$i],
                'KAWASAN'=>$nkk[$i],
                'LUAS'=>$l[$i],
                'DASAR_HUKUM'=>$dHk[$i]
            );
            $this->db->insert('SMY_RPL_110',$data);
        }

         $this->session->set_flashdata('msg','
<button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>Data Tersimpan
');
            redirect('administrator/source_upload/add');
    //}

        die();
    }
}


text:
var path = require('path'),
	modify = require('../../');

module.exports = modify(path.resolve(__dirname+'/one'), {
	// nameDrops: false,
	'transform-es2015-typeof-symbol': false,
	'transform-react-jsx': { jsxPragma:'z' },
});


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
     PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <title>Class: Gem::Platform</title>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  <meta http-equiv="Content-Script-Type" content="text/javascript" />
  <link rel="stylesheet" href="../.././rdoc-style.css" type="text/css" media="screen" />

          Class
          Gem::Platform

            In:

                lib/bundler/rubygems_ext.rb

            Parent:

                Object

Methods

      hash

Constants

          JAVA
          =
          Gem::Platform.new('java')

          MSWIN
          =
          Gem::Platform.new('mswin32')

          MINGW
          =
          Gem::Platform.new('x86-mingw32')

External Aliases

          ==
          ->
          eql?

Public Instance methods

          hash()

[Validate]


text:
namespace gpopt
{

	using namespace gpos;
	using namespace gpmd;

	//---------------------------------------------------------------------------
	//	@class:
	//		CScalarOp
	//
	//	@doc:
	//		general scalar operation such as arithmetic and string evaluations
	//
	//---------------------------------------------------------------------------
	class CScalarOp : public CScalar
	{

		private:

			// metadata id in the catalog
			IMDId *m_pmdidOp;

			// return type id or NULL if it can be inferred from the metadata
			IMDId *m_pmdidReturnType;

			// scalar operator name
			const CWStringConst *m_pstrOp;

			// does operator return NULL on NULL input?
			BOOL m_fReturnsNullOnNullInput;

			// is operator return type BOOL?
			BOOL m_fBoolReturnType;

			// is operator commutative
			BOOL m_fCommutative;

			// private copy ctor
			CScalarOp(const CScalarOp &);

		public:

			// ctor
			CScalarOp
				(
				IMemoryPool *pmp,
				IMDId *pmdidOp,
				IMDId *pmdidReturnType,
				const CWStringConst *pstrOp
				);

			// dtor
			virtual
			~CScalarOp()
			{
				m_pmdidOp->Release();
				CRefCount::SafeRelease(m_pmdidReturnType);
				GPOS_DELETE(m_pstrOp);
			}

			// ident accessors
			virtual
			EOperatorId Eopid() const
			{
				return EopScalarOp;
			}

			// return a string for operator name
			virtual
			const CHAR *SzId() const
			{
				return "CScalarOp";
			}

			// accessor to the return type field
			IMDId *PmdidReturnType() const;

			// the type of the scalar expression
			virtual
			IMDId *PmdidType() const;

			// operator specific hash function
			ULONG UlHash() const;

			// match function
			BOOL FMatch(COperator *pop) const;

			// sensitivity to order of inputs
			BOOL FInputOrderSensitive() const;

			// return a copy of the operator with remapped columns
			virtual
			COperator *PopCopyWithRemappedColumns
						(
						IMemoryPool *, //pmp,
						HMUlCr *, //phmulcr,
						BOOL //fMustExist
						)
			{
				return PopCopyDefault();
			}

			// conversion function
			static
			CScalarOp *PopConvert
				(
				COperator *pop
				)
			{
				GPOS_ASSERT(NULL != pop);
				GPOS_ASSERT(EopScalarOp == pop->Eopid());

				return reinterpret_cast<CScalarOp*>(pop);
			}

			// helper function
			static
			BOOL FCommutative(const IMDId *pcmdidOtherOp);

			// boolean expression evaluation
			virtual
			EBoolEvalResult Eber(DrgPul *pdrgpulChildren) const;

			// name of the scalar operator
			const CWStringConst *Pstr() const;

			// metadata id
			IMDId *PmdidOp() const;

			// print
			virtual
			IOstream &OsPrint(IOstream &os) const;

	}; // class CScalarOp

}

#endif // !GPOPT_CScalarOp_H

// EOF


text:
package org.apache.camel.spring.boot;

import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.support.DefaultConversionService;

@Configuration
public class SpringConversionServiceConfiguration {

    @ConditionalOnMissingBean(ConversionService.class)
    @Bean
    ConversionService conversionService(ApplicationContext applicationContext) {
        DefaultConversionService service = new DefaultConversionService();
        for (Converter converter : applicationContext.getBeansOfType(Converter.class).values()) {
            service.addConverter(converter);
        }
        return service;
    }

    @Bean
    SpringTypeConverter springTypeConverter(ConversionService conversionService) {
        return new SpringTypeConverter(conversionService);
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<NeurologyFormTotalsModel>
  <NeurologyForm>
    <Id>0</Id>
    <ExamDate>0001-01-01T00:00:00</ExamDate>
    <AnalContraction>No</AnalContraction>
    <AnalSensation>Yes</AnalSensation>
    <RightLowestNonKeyMuscleWithMotorFunction>0</RightLowestNonKeyMuscleWithMotorFunction>
    <LeftLowestNonKeyMuscleWithMotorFunction>0</LeftLowestNonKeyMuscleWithMotorFunction>
    <Comments>
      Edge case - Bug discovered by Dr. Reeves - Feb 9th, 2012
    </Comments>
    <Dermatomes>
      <Dermatome name="C2">
        <RightTouch>2</RightTouch>
        <LeftTouch>2</LeftTouch>
        <RightPrick>2</RightPrick>
        <LeftPrick>2</LeftPrick>
      </Dermatome>
      <Dermatome name="C3">
        <RightTouch>2</RightTouch>
        <LeftTouch>2</LeftTouch>
        <RightPrick>2</RightPrick>
        <LeftPrick>2</LeftPrick>
      </Dermatome>
      <Dermatome name="C4">
        <RightTouch>2</RightTouch>
        <LeftTouch>2</LeftTouch>
        <RightPrick>1</RightPrick>
        <LeftPrick>2</LeftPrick>
      </Dermatome>
      <Dermatome name="C5">
        <RightMotor>5</RightMotor>
        <LeftMotor>3</LeftMotor>
        <RightTouch>1</RightTouch>
        <LeftTouch>1</LeftTouch>
        <RightPrick>1</RightPrick>
        <LeftPrick>1</LeftPrick>
      </Dermatome>
      <Dermatome name="C6">
        <RightMotor>4</RightMotor>
        <LeftMotor>3</LeftMotor>
        <RightTouch>1</RightTouch>
        <LeftTouch>1</LeftTouch>
        <RightPrick>0</RightPrick>
        <LeftPrick>1</LeftPrick>
      </Dermatome>
      <Dermatome name="C7">
        <RightMotor>1</RightMotor>
        <LeftMotor>1</LeftMotor>
        <RightTouch>1</RightTouch>
        <LeftTouch>1</LeftTouch>
        <RightPrick>0</RightPrick>
        <LeftPrick>0</LeftPrick>
      </Dermatome>
      <Dermatome name="C8">
        <RightMotor>0</RightMotor>
        <LeftMotor>1</LeftMotor>
        <RightTouch>0</RightTouch>
        <LeftTouch>0</LeftTouch>
        <RightPrick>0</RightPrick>
        <LeftPrick>0</LeftPrick>
      </Dermatome>
      <Dermatome name="T1">
        <RightMotor>0</RightMotor>
        <LeftMotor>0</LeftMotor>
        <RightTouch>0</RightTouch>
        <LeftTouch>0</LeftTouch>
        <RightPrick>0</RightPrick>
        <LeftPrick>0</LeftPrick>
      </Dermatome>
      <Dermatome name="T2">
        <RightTouch>0</RightTouch>
        <LeftTouch>0</LeftTouch>
        <RightPrick>0</RightPrick>
        <LeftPrick>0</LeftPrick>
      </Dermatome>
      <Dermatome name="T3">
        <RightTouch>0</RightTouch>
        <LeftTouch>0</LeftTouch>
        <RightPrick>0</RightPrick>
        <LeftPrick>0</LeftPrick>
      </Dermatome>
      <Dermatome name="T4">
        <RightTouch>0</RightTouch>
        <LeftTouch>0</LeftTouch>
        <RightPrick>0</RightPrick>
        <LeftPrick>0</LeftPrick>
      </Dermatome>
      <Dermatome name="T5">
        <RightTouch>0</RightTouch>
        <LeftTouch>0</LeftTouch>
        <RightPrick>0</RightPrick>
        <LeftPrick>0</LeftPrick>
      </Dermatome>
      <Dermatome name="T6">
        <RightTouch>0</RightTouch>
        <LeftTouch>0</LeftTouch>
        <RightPrick>0</RightPrick>
        <LeftPrick>0</LeftPrick>
      </Dermatome>
      <Dermatome name="T7">
        <RightTouch>0</RightTouch>
        <LeftTouch>0</LeftTouch>
        <RightPrick>0</RightPrick>
        <LeftPrick>0</LeftPrick>
      </Dermatome>
      <Dermatome name="T8">
        <RightTouch>0</RightTouch>
        <LeftTouch>0</LeftTouch>
        <RightPrick>0</RightPrick>
        <LeftPrick>0</LeftPrick>
      </Dermatome>
      <Dermatome name="T9">
        <RightTouch>0</RightTouch>
        <LeftTouch>0</LeftTouch>
        <RightPrick>0</RightPrick>
        <LeftPrick>0</LeftPrick>
      </Dermatome>
      <Dermatome name="T10">
        <RightTouch>0</RightTouch>
        <LeftTouch>0</LeftTouch>
        <RightPrick>0</RightPrick>
        <LeftPrick>0</LeftPrick>
      </Dermatome>
      <Dermatome name="T11">
        <RightTouch>0</RightTouch>
        <LeftTouch>0</LeftTouch>
        <RightPrick>0</RightPrick>
        <LeftPrick>0</LeftPrick>
      </Dermatome>
      <Dermatome name="T12">
        <RightTouch>0</RightTouch>
        <LeftTouch>0</LeftTouch>
        <RightPrick>0</RightPrick>
        <LeftPrick>0</LeftPrick>
      </Dermatome>
      <Dermatome name="L1">
        <RightTouch>0</RightTouch>
        <LeftTouch>0</LeftTouch>
        <RightPrick>0</RightPrick>
        <LeftPrick>0</LeftPrick>
      </Dermatome>
      <Dermatome name="L2">
        <RightMotor>0</RightMotor>
        <LeftMotor>0</LeftMotor>
        <RightTouch>0</RightTouch>
        <LeftTouch>0</LeftTouch>
        <RightPrick>0</RightPrick>
        <LeftPrick>0</LeftPrick>
      </Dermatome>
      <Dermatome name="L3">
        <RightMotor>0</RightMotor>
        <LeftMotor>0</LeftMotor>
        <RightTouch>0</RightTouch>
        <LeftTouch>0</LeftTouch>
        <RightPrick>0</RightPrick>
        <LeftPrick>0</LeftPrick>
      </Dermatome>
      <Dermatome name="L4">
        <RightMotor>0</RightMotor>
        <LeftMotor>0</LeftMotor>
        <RightTouch>0</RightTouch>
        <LeftTouch>0</LeftTouch>
        <RightPrick>0</RightPrick>
        <LeftPrick>0</LeftPrick>
      </Dermatome>
      <Dermatome name="L5">
        <RightMotor>0</RightMotor>
        <LeftMotor>0</LeftMotor>
        <RightTouch>0</RightTouch>
        <LeftTouch>0</LeftTouch>
        <RightPrick>0</RightPrick>
        <LeftPrick>0</LeftPrick>
      </Dermatome>
      <Dermatome name="S1">
        <RightMotor>0</RightMotor>
        <LeftMotor>0</LeftMotor>
        <RightTouch>0</RightTouch>
        <LeftTouch>0</LeftTouch>
        <RightPrick>0</RightPrick>
        <LeftPrick>0</LeftPrick>
      </Dermatome>
      <Dermatome name="S2">
        <RightTouch>0</RightTouch>
        <LeftTouch>0</LeftTouch>
        <RightPrick>0</RightPrick>
        <LeftPrick>0</LeftPrick>
      </Dermatome>
      <Dermatome name="S3">
        <RightTouch>0</RightTouch>
        <LeftTouch>0</LeftTouch>
        <RightPrick>0</RightPrick>
        <LeftPrick>0</LeftPrick>
      </Dermatome>
      <Dermatome name="S4_5">
        <RightTouch>0</RightTouch>
        <LeftTouch>0</LeftTouch>
        <RightPrick>0</RightPrick>
        <LeftPrick>0</LeftPrick>
      </Dermatome>
    </Dermatomes>
  </NeurologyForm>
  <NeurologyFormTotals>
    <RightUpperMotorTotal>10</RightUpperMotorTotal>
    <RightUpperMotorContainsNt>false</RightUpperMotorContainsNt>
    <LeftUpperMotorTotal>8</LeftUpperMotorTotal>
    <LeftUpperMotorContainsNt>false</LeftUpperMotorContainsNt>
    <RightLowerMotorTotal>0</RightLowerMotorTotal>
    <RightLowerMotorContainsNt>false</RightLowerMotorContainsNt>
    <LeftLowerMotorTotal>0</LeftLowerMotorTotal>
    <LeftLowerMotorContainsNt>false</LeftLowerMotorContainsNt>
    <RightTouchTotal>9</RightTouchTotal>
    <RightTouchContainsNt>false</RightTouchContainsNt>
    <LeftTouchTotal>9</LeftTouchTotal>
    <LeftTouchContainsNt>false</LeftTouchContainsNt>
    <RightPrickTotal>6</RightPrickTotal>
    <RightPrickContainsNt>false</RightPrickContainsNt>
    <LeftPrickTotal>8</LeftPrickTotal>
    <LeftPrickContainsNt>false</LeftPrickContainsNt>
    <RightMotorTotal>10</RightMotorTotal>
    <LeftMotorTotal>8</LeftMotorTotal>
    <UpperMotorTotal>18</UpperMotorTotal>
    <LowerMotorTotal>0</LowerMotorTotal>
    <TouchTotal>18</TouchTotal>
    <PrickTotal>14</PrickTotal>
    <RightSensory>C3</RightSensory>
    <LeftSensory>C4</LeftSensory>
    <RightMotor>C3</RightMotor>
    <LeftMotor>C5</LeftMotor>
    <NeurologicalLevelOfInjury>C3</NeurologicalLevelOfInjury>
    <RightSensoryZpp>C7</RightSensoryZpp>
    <LeftSensoryZpp>C7</LeftSensoryZpp>
    <RightMotorZpp>C7</RightMotorZpp>
    <LeftMotorZpp>C8</LeftMotorZpp>
    <AsiaImpairmentScale>C</AsiaImpairmentScale>
  </NeurologyFormTotals>
</NeurologyFormTotalsModel>


text:
package org.sirix.access.trx.node;

import com.google.common.base.MoreObjects;
import org.checkerframework.checker.index.qual.NonNegative;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.sirix.access.User;
import org.sirix.access.trx.node.InternalResourceSession.Abort;
import org.sirix.access.trx.node.json.InternalJsonNodeReadOnlyTrx;
import org.sirix.api.*;
import org.sirix.axis.IncludeSelf;
import org.sirix.axis.PostOrderAxis;
import org.sirix.diff.DiffTuple;
import org.sirix.exception.SirixException;
import org.sirix.exception.SirixIOException;
import org.sirix.exception.SirixThreadedException;
import org.sirix.exception.SirixUsageException;
import org.sirix.index.path.summary.PathSummaryReader;
import org.sirix.index.path.summary.PathSummaryWriter;
import org.sirix.node.SirixDeweyID;
import org.sirix.node.interfaces.Node;
import org.sirix.node.interfaces.immutable.ImmutableNode;
import org.sirix.page.UberPage;

import java.io.IOException;
import java.time.Duration;
import java.time.Instant;
import java.util.*;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.nio.file.Files.deleteIfExists;
import static java.util.concurrent.Executors.newScheduledThreadPool;

/**
 * Abstract implementation for {@link InternalNodeTrx}.
 *
 * @author Joao Sousa
 */
public abstract class AbstractNodeTrxImpl<R extends NodeReadOnlyTrx & NodeCursor, W extends NodeTrx & NodeCursor, NF extends NodeFactory, N extends ImmutableNode, IN extends InternalNodeReadOnlyTrx<N>>
    implements NodeReadOnlyTrx, InternalNodeTrx<W>, NodeCursor {

  /**
   * Maximum number of node modifications before auto commit.
   */
  private final int maxNodeCount;
  /**
   * Scheduled executor service.
   */
  private final ScheduledExecutorService commitScheduler;

  /**
   * Hash kind of Structure.
   */
  private final HashType hashType;

  /**
   * {@link InternalJsonNodeReadOnlyTrx} reference.
   */
  protected final IN nodeReadOnlyTrx;
  private final R typeSpecificTrx;

  /**
   * The resource manager.
   */
  protected final InternalResourceSession<R, W> resourceManager;

  /**
   * {@link PathSummaryWriter} instance.
   */
  protected PathSummaryWriter<R> pathSummaryWriter;

  /**
   * {@link NodeFactory} to be able to create nodes.
   */
  protected NF nodeFactory;

  /**
   * Determines if a path summary should be built and kept up-to-date or not.
   */
  protected final boolean buildPathSummary;

  /**
   * Collects update operations in pre-order, thus it must be an order-preserving sorted map.
   */
  protected final SortedMap<SirixDeweyID, DiffTuple> updateOperationsOrdered;

  /**
   * Collects update operations in no particular order (if DeweyIDs used for sorting are not stored).
   */
  protected final Map<Long, DiffTuple> updateOperationsUnordered;

  /**
   * An optional lock for all methods, if an automatic commit is issued.
   */
  @Nullable
  protected final Lock lock;

  /**
   * Transaction state.
   */
  private volatile State state;

  /**
   * After commit state: keep open or close.
   */
  private final AfterCommitState afterCommitState;

  /**
   * Modification counter.
   */
  private long modificationCount;

  /**
   * The page write trx.
   */
  protected PageTrx pageTrx;

  /**
   * The {@link IndexController} used within the resource manager this {@link NodeTrx} is bound to.
   */
  protected IndexController<R, W> indexController;

  /**
   * The node to revisions index (when a node has changed)
   */
  protected final RecordToRevisionsIndex nodeToRevisionsIndex;

  /**
   * Collection holding pre-commit hooks.
   */
  private final List<PreCommitHook> preCommitHooks = new ArrayList<>();

  /**
   * Collection holding post-commit hooks.
   */
  private final List<PostCommitHook> postCommitHooks = new ArrayList<>();

  /**
   * Hashes nodes.
   */
  protected AbstractNodeHashing<N, R> nodeHashing;

  /**
   * The transaction states.
   */
  private enum State {
    Running,

    Committing,

    Committed,

    Closed
  }

  protected AbstractNodeTrxImpl(final ThreadFactory threadFactory, final HashType hashType, final IN nodeReadOnlyTrx,
      final R typeSpecificTrx, final InternalResourceSession<R, W> resourceManager,
      final AfterCommitState afterCommitState, final AbstractNodeHashing<N, R> nodeHashing,
      final PathSummaryWriter<R> pathSummaryWriter, final NF nodeFactory,
      final RecordToRevisionsIndex nodeToRevisionsIndex, @Nullable final Lock transactionLock,
      final Duration afterCommitDelay, @NonNegative final int maxNodeCount) {
    // Do not accept negative values.
    checkArgument(maxNodeCount >= 0, "Negative argument for maxNodeCount is not accepted.");
    checkArgument(!afterCommitDelay.isNegative(), "After commit delay cannot be negative");
    this.commitScheduler = newScheduledThreadPool(1, threadFactory);
    this.hashType = hashType;
    this.nodeReadOnlyTrx = checkNotNull(nodeReadOnlyTrx);
    this.typeSpecificTrx = typeSpecificTrx;
    this.resourceManager = checkNotNull(resourceManager);
    this.lock = transactionLock;
    this.afterCommitState = checkNotNull(afterCommitState);
    this.nodeHashing = checkNotNull(nodeHashing);
    this.buildPathSummary = resourceManager.getResourceConfig().withPathSummary;
    this.nodeFactory = checkNotNull(nodeFactory);
    this.pathSummaryWriter = pathSummaryWriter;
    this.indexController = resourceManager.getWtxIndexController(nodeReadOnlyTrx.getPageTrx().getRevisionNumber());
    this.nodeToRevisionsIndex = checkNotNull(nodeToRevisionsIndex);

    this.updateOperationsOrdered = new TreeMap<>();
    this.updateOperationsUnordered = new HashMap<>();

    this.pageTrx = (PageTrx) nodeReadOnlyTrx.getPageTrx();

    // Only auto commit by node modifications if it is more then 0.
    this.maxNodeCount = maxNodeCount;
    this.modificationCount = 0L;

    this.state = State.Running;

    if (!afterCommitDelay.isZero()) {
      commitScheduler.scheduleWithFixedDelay(() -> commit("autoCommit", null),
                                             afterCommitDelay.toMillis(),
                                             afterCommitDelay.toMillis(),
                                             TimeUnit.MILLISECONDS);
    }
  }

  protected abstract W self();

  protected void assertRunning() {
    if (state != State.Running) {
      throw new IllegalStateException("Transaction state is not running: " + state);
    }
  }

  @Override
  public Optional<User> getUser() {
    return getResourceSession().getUser();
  }

  @Override
  public W setBulkInsertion(final boolean bulkInsertion) {
    nodeHashing.setBulkInsert(bulkInsertion);
    return self();
  }

  /**
   * Get the current node.
   *
   * @return {@link Node} implementation
   */
  protected N getCurrentNode() {
    return nodeReadOnlyTrx.getCurrentNode();
  }

  /**
   * Modifying hashes in a postorder-traversal.
   *
   * @throws SirixIOException if an I/O error occurs
   */
  protected void postOrderTraversalHashes() {
    new PostOrderAxis(this, IncludeSelf.YES).forEach(unused -> nodeHashing.addHashAndDescendantCount());
  }

  @Override
  public void adaptHashesInPostorderTraversal() {
    if (hashType != HashType.NONE) {
      final long nodeKey = getCurrentNode().getNodeKey();
      postOrderTraversalHashes();
      final ImmutableNode startNode = getCurrentNode();
      moveToParent();
      while (getCurrentNode().hasParent()) {
        moveToParent();
        nodeHashing.addParentHash(startNode);
      }
      moveTo(nodeKey);
    }
  }

  protected void runLocked(final Runnable runnable) {
    if (lock != null) {
      lock.lock();
    }
    try {
      runnable.run();
    } finally {
      if (lock != null) {
        lock.unlock();
      }
    }
  }

  @Override
  public W commit(@Nullable final String commitMessage, @Nullable final Instant commitTimestamp) {
    nodeReadOnlyTrx.assertNotClosed();
    if (commitTimestamp != null && !resourceManager.getResourceConfig().customCommitTimestamps()) {
      throw new IllegalStateException("Custom commit timestamps are not enabled for the resource.");
    }

    runLocked(() -> {
      state = State.Committing;

      // Execute pre-commit hooks.
      for (final PreCommitHook hook : preCommitHooks) {
        hook.preCommit(this);
      }

      // Reset modification counter.
      modificationCount = 0L;

      final var preCommitRevision = getRevisionNumber();

      final UberPage uberPage = pageTrx.commit(commitMessage, commitTimestamp);

      // Remember successfully committed uber page in resource manager.
      resourceManager.setLastCommittedUberPage(uberPage);

      if (resourceManager.getResourceConfig().storeDiffs()) {
        serializeUpdateDiffs(preCommitRevision);
      }

      // Reinstantiate everything.
      if (afterCommitState == AfterCommitState.KEEP_OPEN) {
        reInstantiate(getId(), preCommitRevision);
        state = State.Running;
      } else {
        state = State.Committed;
      }
    });

    // Execute post-commit hooks.
    for (final PostCommitHook hook : postCommitHooks) {
      hook.postCommit(this);
    }

    return self();
  }

  /**
   * Checking write access and intermediate commit.
   *
   * @throws SirixException if anything weird happens
   */
  protected void checkAccessAndCommit() {
    nodeReadOnlyTrx.assertNotClosed();
    assertRunning();
    modificationCount++;
    intermediateCommitIfRequired();
  }

  /**
   * Making an intermediate commit based on set attributes.
   *
   * @throws SirixException if commit fails
   */
  private void intermediateCommitIfRequired() {
    nodeReadOnlyTrx.assertNotClosed();
    if (maxNodeCount > 0 && modificationCount > maxNodeCount) {
      commit("autoCommit");
    }
  }

  protected abstract void serializeUpdateDiffs(int revisionNumber);

  /**
   * Create new instances.
   *
   * @param trxID     transaction ID
   * @param revNumber revision number
   */
  private void reInstantiate(final @NonNegative long trxID, final @NonNegative int revNumber) {
    // Reset page transaction to new uber page.
    resourceManager.closeNodePageWriteTransaction(getId());
    pageTrx = resourceManager.createPageTransaction(trxID, revNumber, revNumber, Abort.NO, true);
    nodeReadOnlyTrx.setPageReadTransaction(null);
    nodeReadOnlyTrx.setPageReadTransaction(pageTrx);
    resourceManager.setNodePageWriteTransaction(getId(), pageTrx);

    nodeFactory = reInstantiateNodeFactory(pageTrx);

    final boolean isBulkInsert = nodeHashing.isBulkInsert();
    nodeHashing = reInstantiateNodeHashing(hashType, pageTrx);
    nodeHashing.setBulkInsert(isBulkInsert);

    updateOperationsUnordered.clear();
    updateOperationsOrdered.clear();

    reInstantiateIndexes();
  }

  protected abstract AbstractNodeHashing<N, R> reInstantiateNodeHashing(HashType hashType, PageTrx pageTrx);

  protected abstract NF reInstantiateNodeFactory(PageTrx pageTrx);

  private void reInstantiateIndexes() {
    // Get a new path summary instance.
    if (buildPathSummary) {
      pathSummaryWriter = new PathSummaryWriter<>(pageTrx, resourceManager, nodeFactory, typeSpecificTrx);
    }

    // Recreate index listeners.
    final var indexDefs = indexController.getIndexes().getIndexDefs();
    indexController = resourceManager.getWtxIndexController(nodeReadOnlyTrx.getPageTrx().getRevisionNumber());
    indexController.createIndexListeners(indexDefs, self());

    nodeToRevisionsIndex.setPageTrx(pageTrx);
  }

  @Override
  public synchronized W rollback() {
    if (lock != null) {
      lock.lock();
    }

    nodeReadOnlyTrx.assertNotClosed();

    // Reset modification counter.
    modificationCount = 0L;

    // Close current page transaction.
    final long trxID = getId();
    final int revision = getRevisionNumber();
    final int revNumber = pageTrx.getUberPage().isBootstrap() ? 0 : revision - 1;

    final UberPage uberPage = pageTrx.rollback();

    // Remember successfully committed uber page in resource manager.
    resourceManager.setLastCommittedUberPage(uberPage);

    resourceManager.closeNodePageWriteTransaction(getId());
    nodeReadOnlyTrx.setPageReadTransaction(null);
    removeCommitFile();

    pageTrx = resourceManager.createPageTransaction(trxID, revNumber, revNumber, Abort.YES, true);
    nodeReadOnlyTrx.setPageReadTransaction(pageTrx);
    resourceManager.setNodePageWriteTransaction(getId(), pageTrx);

    nodeFactory = reInstantiateNodeFactory(pageTrx);

    reInstantiateIndexes();

    if (lock != null) {
      lock.unlock();
    }

    return self();
  }

  private void removeCommitFile() {
    try {
      deleteIfExists(resourceManager.getCommitFile());
    } catch (final IOException e) {
      throw new SirixIOException(e);
    }
  }

  @Override
  public W revertTo(final int revision) {
    if (lock != null) {
      lock.lock();
    }

    try {
      nodeReadOnlyTrx.assertNotClosed();
      resourceManager.assertAccess(revision);

      // Close current page transaction.
      final long trxID = getId();
      final int revNumber = getRevisionNumber();

      // Reset internal transaction state to new uber page.
      resourceManager.closeNodePageWriteTransaction(getId());
      pageTrx = resourceManager.createPageTransaction(trxID, revision, revNumber - 1, Abort.NO, true);
      nodeReadOnlyTrx.setPageReadTransaction(null);
      nodeReadOnlyTrx.setPageReadTransaction(pageTrx);
      resourceManager.setNodePageWriteTransaction(getId(), pageTrx);

      nodeHashing = reInstantiateNodeHashing(hashType, pageTrx);

      // Reset node factory.
      nodeFactory = reInstantiateNodeFactory(pageTrx);

      // New index instances.
      reInstantiateIndexes();

      // Reset modification counter.
      modificationCount = 0L;

      // Move to document root.
      moveToDocumentRoot();
    } finally {
      if (lock != null) {
        lock.unlock();
      }
    }

    return self();
  }

  @Override
  public W addPreCommitHook(final PreCommitHook hook) {
    if (lock != null) {
      lock.lock();
    }

    try {
      preCommitHooks.add(checkNotNull(hook));
      return self();
    } finally {
      if (lock != null) {
        lock.unlock();
      }
    }
  }

  @Override
  public W addPostCommitHook(final PostCommitHook hook) {
    if (lock != null) {
      lock.lock();
    }

    try {
      postCommitHooks.add(checkNotNull(hook));
      return self();
    } finally {
      if (lock != null) {
        lock.unlock();
      }
    }
  }

  @Override
  public W truncateTo(final int revision) {
    nodeReadOnlyTrx.assertNotClosed();

    // TODO

    return self();
  }

  @Override
  public PathSummaryReader getPathSummary() {
    if (lock != null) {
      lock.lock();
    }

    try {
      return pathSummaryWriter.getPathSummary();
    } finally {
      if (lock != null) {
        lock.unlock();
      }
    }
  }

  @Override
  public PageTrx getPageWtx() {
    nodeReadOnlyTrx.assertNotClosed();
    return (PageTrx) nodeReadOnlyTrx.getPageTrx();
  }

  @Override
  public Optional<User> getUserOfRevisionToRepresent() {
    return nodeReadOnlyTrx.getUser();
  }

  @Override
  public synchronized void close() {
    runLocked(() -> {
      if (!isClosed()) {
        // Make sure to commit all dirty data.
        if (modificationCount > 0) {
          throw new SirixUsageException("Must commit/rollback transaction first!");
        }

        // Release all state immediately.
        final long trxId = getId();
        nodeReadOnlyTrx.close();
        resourceManager.closeWriteTransaction(trxId);
        removeCommitFile();

        pathSummaryWriter = null;
        nodeFactory = null;

        // Shutdown pool.
        commitScheduler.shutdown();
        try {
          commitScheduler.awaitTermination(2, TimeUnit.SECONDS);
        } catch (final InterruptedException e) {
          throw new SirixThreadedException(e);
        }
      }
    });
  }

  @Override
  public CommitCredentials getCommitCredentials() {
    nodeReadOnlyTrx.assertNotClosed();

    return nodeReadOnlyTrx.getCommitCredentials();
  }

  @Override
  public SirixDeweyID getDeweyID() {
    nodeReadOnlyTrx.assertNotClosed();
    return getCurrentNode().getDeweyID();
  }

  @Override
  public boolean equals(final Object o) {
    if (this == o)
      return true;
    if (o == null || getClass() != o.getClass())
      return false;
    final AbstractNodeTrxImpl<?, ?, ?, ?, ?> that = (AbstractNodeTrxImpl<?, ?, ?, ?, ?>) o;
    return nodeReadOnlyTrx.equals(that.nodeReadOnlyTrx);
  }

  @Override
  public int hashCode() {
    return Objects.hash(nodeReadOnlyTrx);
  }

  @Override
  public String toString() {
    return MoreObjects.toStringHelper(this)
                      .add("super", super.toString())
                      .add("hashType", this.hashType)
                      .add("nodeReadOnlyTrx", this.nodeReadOnlyTrx)
                      .toString();
  }
}


text:
% Code written by Tao Wang (http://cs.stanford.edu/people/twangcat/)

function [matchscore real_good_idx]= getMatchScore(origscores, origword, good_idx)

% given the char recognition score and a candidate lexicon word,
% computes the matchscore using dynamic programming
% origscores: the score matrix M
% origword: one single lexicon word
% good_idx: peak positions obtained after NMS on 'confidence margin'

scores = origscores(:,good_idx);
word=double(ascii2label(origword));
w = length(word);
if w<1
    matchscore = -10;
    real_good_idx = 0;
    return;
end
s = size(scores,2);
os = size(origscores,2);

% scoreMat(i,j) contains the maximum score you can get so far by matching
% the ith character with the jth score location

% if word is longer than number of sliding windows, something's wrong
if w>s
    matchscore = -10;
    real_good_idx = 0;
    return;
end
% dynamic programming window
scoreMat = zeros(w,s);
scoreIdx = zeros(w,s);
scoreMat(1,:)  = scores(word(1),:); % initialize first row

% Viterbi dynamic programming
for i = 2:w
    for j = i:s
        [maxPrev maxPrevIdx] = max(scoreMat(i-1, i-1:j-1));
        scoreMat(i,j) = scores(word(i), j) + maxPrev;

        scoreIdx(i,j) = maxPrevIdx;
    end
end

[matchscore lastidx]= max(scoreMat(end,w:end));

real_good_idx = zeros(1,w);
real_good_idx(end) = lastidx+w-1;
i = w;
% backtrace to find correspondence between peaks and chars.
while i>1
    real_good_idx(i-1) = scoreIdx(i, real_good_idx(i))+i-2;
    i = i-1;
end
real_good_idx = good_idx(real_good_idx);

gaps = [real_good_idx s] - [1 real_good_idx];

%% penalize geometric inconsistency
global c_std c_narrow;
% inconsistent character spacing
if length(gaps)>=4
    gaps = gaps(2:end-1);
    std_loss = c_std*std(gaps);
else
    std_loss = 0;
end
% very narrow characters
narrow_loss = 0;
if ~strcmp(origword,'I') && ~strcmp(origword,'l')
if (size(origscores,2))/w<8
    narrow_loss = (8-(size(origscores,2))/w)*c_narrow;
end
end

% penalize excessive extra space on both sides
matchscore = matchscore- std_loss-narrow_loss - ((min(real_good_idx) - 1)/os + (os-max(real_good_idx))/os);


text:
<?php

/**
 * This code was generated by
 * \ / _    _  _|   _  _
 * | (_)\/(_)(_|\/| |(/_  v1.0.0
 * /       /
 */

namespace Twilio\Rest\Serverless\V1\Service\Environment;

use Twilio\Exceptions\TwilioException;
use Twilio\ListResource;
use Twilio\Options;
use Twilio\Stream;
use Twilio\Values;
use Twilio\Version;

/**
 * PLEASE NOTE that this class contains beta products that are subject to change. Use them with caution.
 */
class DeploymentList extends ListResource {
    /**
     * Construct the DeploymentList
     *
     * @param Version $version Version that contains the resource
     * @param string $serviceSid The SID of the Service that the Deployment
     *                           resource is associated with
     * @param string $environmentSid The SID of the Environment for the Deployment
     */
    public function __construct(Version $version, string $serviceSid, string $environmentSid) {
        parent::__construct($version);

        // Path Solution
        $this->solution = ['serviceSid' => $serviceSid, 'environmentSid' => $environmentSid, ];

        $this->uri = '/Services/' . \rawurlencode($serviceSid) . '/Environments/' . \rawurlencode($environmentSid) . '/Deployments';
    }

    /**
     * Streams DeploymentInstance records from the API as a generator stream.
     * This operation lazily loads records as efficiently as possible until the
     * limit
     * is reached.
     * The results are returned as a generator, so this operation is memory
     * efficient.
     *
     * @param int $limit Upper limit for the number of records to return. stream()
     *                   guarantees to never return more than limit.  Default is no
     *                   limit
     * @param mixed $pageSize Number of records to fetch per request, when not set
     *                        will use the default value of 50 records.  If no
     *                        page_size is defined but a limit is defined, stream()
     *                        will attempt to read the limit with the most
     *                        efficient page size, i.e. min(limit, 1000)
     * @return Stream stream of results
     */
    public function stream(int $limit = null, $pageSize = null): Stream {
        $limits = $this->version->readLimits($limit, $pageSize);

        $page = $this->page($limits['pageSize']);

        return $this->version->stream($page, $limits['limit'], $limits['pageLimit']);
    }

    /**
     * Reads DeploymentInstance records from the API as a list.
     * Unlike stream(), this operation is eager and will load `limit` records into
     * memory before returning.
     *
     * @param int $limit Upper limit for the number of records to return. read()
     *                   guarantees to never return more than limit.  Default is no
     *                   limit
     * @param mixed $pageSize Number of records to fetch per request, when not set
     *                        will use the default value of 50 records.  If no
     *                        page_size is defined but a limit is defined, read()
     *                        will attempt to read the limit with the most
     *                        efficient page size, i.e. min(limit, 1000)
     * @return DeploymentInstance[] Array of results
     */
    public function read(int $limit = null, $pageSize = null): array {
        return \iterator_to_array($this->stream($limit, $pageSize), false);
    }

    /**
     * Retrieve a single page of DeploymentInstance records from the API.
     * Request is executed immediately
     *
     * @param mixed $pageSize Number of records to return, defaults to 50
     * @param string $pageToken PageToken provided by the API
     * @param mixed $pageNumber Page Number, this value is simply for client state
     * @return DeploymentPage Page of DeploymentInstance
     */
    public function page($pageSize = Values::NONE, string $pageToken = Values::NONE, $pageNumber = Values::NONE): DeploymentPage {
        $params = Values::of(['PageToken' => $pageToken, 'Page' => $pageNumber, 'PageSize' => $pageSize, ]);

        $response = $this->version->page('GET', $this->uri, $params);

        return new DeploymentPage($this->version, $response, $this->solution);
    }

    /**
     * Retrieve a specific page of DeploymentInstance records from the API.
     * Request is executed immediately
     *
     * @param string $targetUrl API-generated URL for the requested results page
     * @return DeploymentPage Page of DeploymentInstance
     */
    public function getPage(string $targetUrl): DeploymentPage {
        $response = $this->version->getDomain()->getClient()->request(
            'GET',
            $targetUrl
        );

        return new DeploymentPage($this->version, $response, $this->solution);
    }

    /**
     * Create the DeploymentInstance
     *
     * @param array|Options $options Optional Arguments
     * @return DeploymentInstance Created DeploymentInstance
     * @throws TwilioException When an HTTP error occurs.
     */
    public function create(array $options = []): DeploymentInstance {
        $options = new Values($options);

        $data = Values::of(['BuildSid' => $options['buildSid'], ]);

        $payload = $this->version->create('POST', $this->uri, [], $data);

        return new DeploymentInstance(
            $this->version,
            $payload,
            $this->solution['serviceSid'],
            $this->solution['environmentSid']
        );
    }

    /**
     * Constructs a DeploymentContext
     *
     * @param string $sid The SID that identifies the Deployment resource to fetch
     */
    public function getContext(string $sid): DeploymentContext {
        return new DeploymentContext(
            $this->version,
            $this->solution['serviceSid'],
            $this->solution['environmentSid'],
            $sid
        );
    }

    /**
     * Provide a friendly representation
     *
     * @return string Machine friendly representation
     */
    public function __toString(): string {
        return '[Twilio.Serverless.V1.DeploymentList]';
    }
}