text:
// ***********************************************************************
// Assembly         : paramore.brighter.restms.core
// Author           : ian
// Created          : 10-21-2014
//
// Last Modified By : ian
// Last Modified On : 10-21-2014
// ***********************************************************************
//     Copyright (c) . All rights reserved.
// </copyright>
// <summary></summary>
// ***********************************************************************

#region Licence

#endregion

using System;
using Paramore.Brighter;

namespace paramore.brighter.restms.core.Ports.Commands
{
    /// <summary>
    /// </summary>
    public class AddPipeToDomainCommand : Command
    {
        /// <summary>
        /// Gets the name of the domain.
        /// </summary>
        /// <value>The name of the domain.</value>
        public string DomainName { get; private set; }
        /// <summary>
        /// Gets the name of the pipe.
        /// </summary>
        /// <value>The name of the pipe.</value>
        public string PipeName { get; private set; }

        /// <summary>
        /// Initializes a new instance of the <see cref="AddPipeToDomainCommand"/> class.
        /// </summary>
        /// <param name="domainName">Name of the domain.</param>
        /// <param name="pipeName">Name of the pipe.</param>
        public AddPipeToDomainCommand(string domainName, string pipeName) : base(Guid.NewGuid())
        {
            DomainName = domainName;
            PipeName = pipeName;
        }
    }
}


text:
import hashlib
import logging

from django.contrib.auth import get_user_model
from django_browserid.auth import BrowserIDBackend
from django.core.cache import cache
from django.conf import settings

from mozilla_django_oidc.auth import OIDCAuthenticationBackend

from airmozilla.base.mozillians import is_vouched
from airmozilla.main.models import UserProfile

UserModel = get_user_model()

logger = logging.getLogger('auth')

def hash_email(email):
    return hashlib.md5(email).hexdigest()[:30]

class AirmozillaBrowserIDBackend(BrowserIDBackend):
    """The only difference between this backend and the default
    BrowserIDBackend backend is that this one uses the cache framework
    to remember the user.

    The cache is invalidated by a post_save signal in this app's models.py.
    """

    def get_user(self, user_id):
        if not user_id:
            return None
        cache_key = 'user:%s' % (user_id,)
        user = cache.get(cache_key)
        if user:
            return user
        try:
            user = self.User.objects.get(pk=user_id)
            cache.set(cache_key, user, 60 * 60 * 3)  # 3 hours
            return user
        except self.User.DoesNotExist:
            return None

class AirmozillaOIDCAuthenticationBackend(OIDCAuthenticationBackend):

    def filter_users_by_claims(self, claims):
        users = super(
            AirmozillaOIDCAuthenticationBackend,
            self
        ).filter_users_by_claims(claims)
        # If this returned a set of users, it means the email already
        # exists (got in at some point). If so, do nothing but just
        # return the users.
        if users:
            return users

        # Never heard of this user before!
        # Because we set settings.OIDC_CREATE_USER it won't immediately
        # be created.
        # If we that this user should not be allowed in, return an empty
        # list or empty queryset.
        email = claims.get('email')
        domain = email.split('@')[-1].lower()
        if domain in settings.ALLOWED_BID:
            # You've never signed in before but you have an awesome
            # email domain.
            user = super(
                AirmozillaOIDCAuthenticationBackend,
                self
            ).create_user(claims)
            return [user]

        # A this point, you need to be a vouced mozillian.
        # And if you are you get a "contributor" profile.
        if is_vouched(email):
            user = super(
                AirmozillaOIDCAuthenticationBackend,
                self
            ).create_user(claims)
            UserProfile.objects.create(
                user=user,
                contributor=True
            )
            return [user]

        return UserModel.objects.none()

redpajama_set_name: RedPajamaGithub


text:
package com.bird;

import org.glassfish.jersey.media.sse.EventInput;
import org.glassfish.jersey.media.sse.InboundEvent;
import org.glassfish.jersey.media.sse.SseFeature;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = SseventApplication.class)
@WebAppConfiguration
@IntegrationTest("server.port:${local.server.port}")
public class CommunicationTest {

    @Value("${local.server.port}")
    int port;

    String address;

    @Before
    public void setup() {
        address = "http://localhost:" + port + "/event";
    }

    @Test
    public void contextLoads() {
    }

    @Test
    public void oneClient() {
        Client client = ClientBuilder.newBuilder()
                .register(SseFeature.class).build();

        WebTarget target = client.target(address);

        EventInput eventInput = target.request().get(EventInput.class);
        while (!eventInput.isClosed()) {
            final InboundEvent inboundEvent = eventInput.read();
            if (inboundEvent == null) {
                // connection has been closed
                break;
            }
            System.out.println(inboundEvent.getName() + "; "
                    + inboundEvent.readData(String.class));
        }
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!-- Reviewed: no -->
<sect2 id="zend.application.available-resources.layout">
    <title>Zend_Application_Resource_Layout</title>

    <para>
        <classname>Zend_Application_Resource_Layout</classname> can be used to
        configure <classname>Zend_Layout</classname>. Configuration options are
        per <link linkend="zend.layout.options">the <classname>Zend_Layout
        </classname> options</link>.
    </para>

    <example id="zend.application.available-resources.layout.configExample">
        <title>Sample Layout configuration</title>

        <para>
            Below is a sample <acronym>INI</acronym> snippet showing how to
            configure the layout resource.
        </para>

        <programlisting language="ini"><![CDATA[
resources.layout.layout = "NameOfDefaultLayout"
resources.layout.layoutPath = "/path/to/layouts"
]]></programlisting>
    </example>
</sect2>


text:
require_relative '../spec_helper'

describe Careerbuilder::Job do
  context '.search' do
    let(:result) { Careerbuilder::Job.search({test: 'data'}) }

    it 'returns an array' do
      expect(result).to be_a(Array)
    end
  end

  context '.find' do
    let(:result) { Careerbuilder::Job.find('anything') }

    it 'returns a job if found' do
      api_call({job_count: 1, jobs: [{test: 'job'}]})
      expect(result).to be_a(Careerbuilder::Job)
    end
    it 'returns a nil if not found' do
      api_call({job_count: 0})
      expect(result).to be_nil
    end
  end
end

def api_call(result)
  allow(Careerbuilder::Utils::Request).to receive(:get).and_return(result)
end


text:
import collections
import logging
import time

from mopidy import exceptions
from mopidy.audio import tags as tags_lib
from mopidy.audio import utils
from mopidy.internal import log
from mopidy.internal.gi import Gst, GstPbutils

# GST_ELEMENT_FACTORY_LIST:
_DECODER = 1 << 0
_AUDIO = 1 << 50
_DEMUXER = 1 << 5
_DEPAYLOADER = 1 << 8
_PARSER = 1 << 6

# GST_TYPE_AUTOPLUG_SELECT_RESULT:
_SELECT_TRY = 0
_SELECT_EXPOSE = 1

_Result = collections.namedtuple(
    "Result", ("uri", "tags", "duration", "seekable", "mime", "playable")
)

logger = logging.getLogger(__name__)

def _trace(*args, **kwargs):
    logger.log(log.TRACE_LOG_LEVEL, *args, **kwargs)

# TODO: replace with a scan(uri, timeout=1000, proxy_config=None)?
class Scanner:

    """
    Helper to get tags and other relevant info from URIs.

    :param timeout: timeout for scanning a URI in ms
    :param proxy_config: dictionary containing proxy config strings.
    :type event: int
    """

    def __init__(self, timeout=1000, proxy_config=None):
        self._timeout_ms = int(timeout)
        self._proxy_config = proxy_config or {}

    def scan(self, uri, timeout=None):
        """
        Scan the given uri collecting relevant metadata.

        :param uri: URI of the resource to scan.
        :type uri: string
        :param timeout: timeout for scanning a URI in ms. Defaults to the
            ``timeout`` value used when creating the scanner.
        :type timeout: int
        :return: A named tuple containing
            ``(uri, tags, duration, seekable, mime)``.
            ``tags`` is a dictionary of lists for all the tags we found.
            ``duration`` is the length of the URI in milliseconds, or
            :class:`None` if the URI has no duration. ``seekable`` is boolean.
            indicating if a seek would succeed.
        """
        timeout = int(timeout or self._timeout_ms)
        tags, duration, seekable, mime = None, None, None, None
        pipeline, signals = _setup_pipeline(uri, self._proxy_config)

        try:
            _start_pipeline(pipeline)
            tags, mime, have_audio, duration = _process(pipeline, timeout)
            seekable = _query_seekable(pipeline)
        finally:
            signals.clear()
            pipeline.set_state(Gst.State.NULL)
            del pipeline

        return _Result(uri, tags, duration, seekable, mime, have_audio)

# Turns out it's _much_ faster to just create a new pipeline for every as
# decodebins and other elements don't seem to take well to being reused.
def _setup_pipeline(uri, proxy_config=None):
    src = Gst.Element.make_from_uri(Gst.URIType.SRC, uri)
    if not src:
        raise exceptions.ScannerError(f"GStreamer can not open: {uri}")

    if proxy_config:
        utils.setup_proxy(src, proxy_config)

    signals = utils.Signals()
    pipeline = Gst.ElementFactory.make("pipeline")
    pipeline.add(src)

    if _has_src_pads(src):
        _setup_decodebin(src, src.get_static_pad("src"), pipeline, signals)
    elif _has_dynamic_src_pad(src):
        signals.connect(src, "pad-added", _setup_decodebin, pipeline, signals)
    else:
        raise exceptions.ScannerError("No pads found in source element.")

    return pipeline, signals

def _has_src_pads(element):
    pads = []
    element.iterate_src_pads().foreach(pads.append)
    return bool(pads)

def _has_dynamic_src_pad(element):
    for template in element.get_pad_template_list():
        if template.direction == Gst.PadDirection.SRC:
            if template.presence == Gst.PadPresence.SOMETIMES:
                return True
    return False

def _setup_decodebin(element, pad, pipeline, signals):
    typefind = Gst.ElementFactory.make("typefind")
    decodebin = Gst.ElementFactory.make("decodebin")

    for element in (typefind, decodebin):
        pipeline.add(element)
        element.sync_state_with_parent()

    pad.link(typefind.get_static_pad("sink"))
    typefind.link(decodebin)

    signals.connect(typefind, "have-type", _have_type, decodebin)
    signals.connect(decodebin, "pad-added", _pad_added, pipeline)
    signals.connect(decodebin, "autoplug-select", _autoplug_select)

def _have_type(element, probability, caps, decodebin):
    decodebin.set_property("sink-caps", caps)
    struct = Gst.Structure.new_empty("have-type")
    struct.set_value("caps", caps.get_structure(0))
    element.get_bus().post(Gst.Message.new_application(element, struct))

def _pad_added(element, pad, pipeline):
    sink = Gst.ElementFactory.make("fakesink")
    sink.set_property("sync", False)

    pipeline.add(sink)
    sink.sync_state_with_parent()
    pad.link(sink.get_static_pad("sink"))

    if pad.query_caps().is_subset(Gst.Caps.from_string("audio/x-raw")):
        # Probably won't happen due to autoplug-select fix, but lets play it
        # safe until we've tested more.
        struct = Gst.Structure.new_empty("have-audio")
        element.get_bus().post(Gst.Message.new_application(element, struct))

def _autoplug_select(element, pad, caps, factory):
    if factory.list_is_type(_DECODER | _AUDIO):
        struct = Gst.Structure.new_empty("have-audio")
        element.get_bus().post(Gst.Message.new_application(element, struct))
    if not factory.list_is_type(_DEMUXER | _DEPAYLOADER | _PARSER):
        return _SELECT_EXPOSE
    return _SELECT_TRY

def _start_pipeline(pipeline):
    result = pipeline.set_state(Gst.State.PAUSED)
    if result == Gst.StateChangeReturn.NO_PREROLL:
        pipeline.set_state(Gst.State.PLAYING)

def _query_duration(pipeline):
    success, duration = pipeline.query_duration(Gst.Format.TIME)
    if not success:
        duration = None  # Make sure error case preserves None.
    elif duration < 0:
        duration = None  # Stream without duration.
    else:
        duration = int(duration // Gst.MSECOND)
    return success, duration

def _query_seekable(pipeline):
    query = Gst.Query.new_seeking(Gst.Format.TIME)
    pipeline.query(query)
    return query.parse_seeking()[1]

def _process(pipeline, timeout_ms):
    bus = pipeline.get_bus()
    tags = {}
    mime = None
    have_audio = False
    missing_message = None
    duration = None

    types = (
        Gst.MessageType.ELEMENT
        | Gst.MessageType.APPLICATION
        | Gst.MessageType.ERROR
        | Gst.MessageType.EOS
        | Gst.MessageType.ASYNC_DONE
        | Gst.MessageType.DURATION_CHANGED
        | Gst.MessageType.TAG
    )

    timeout = timeout_ms
    start = int(time.time() * 1000)
    while timeout > 0:
        msg = bus.timed_pop_filtered(timeout * Gst.MSECOND, types)
        if msg is None:
            break

        if logger.isEnabledFor(log.TRACE_LOG_LEVEL) and msg.get_structure():
            debug_text = msg.get_structure().to_string()
            if len(debug_text) > 77:
                debug_text = debug_text[:77] + "..."
            _trace("element %s: %s", msg.src.get_name(), debug_text)

        if msg.type == Gst.MessageType.ELEMENT:
            if GstPbutils.is_missing_plugin_message(msg):
                missing_message = msg
        elif msg.type == Gst.MessageType.APPLICATION:
            if msg.get_structure().get_name() == "have-type":
                mime = msg.get_structure().get_value("caps").get_name()
                if mime and (
                    mime.startswith("text/") or mime == "application/xml"
                ):
                    return tags, mime, have_audio, duration
            elif msg.get_structure().get_name() == "have-audio":
                have_audio = True
        elif msg.type == Gst.MessageType.ERROR:
            error, _debug = msg.parse_error()
            if missing_message and not mime:
                caps = missing_message.get_structure().get_value("detail")
                mime = caps.get_structure(0).get_name()
                return tags, mime, have_audio, duration
            raise exceptions.ScannerError(str(error))
        elif msg.type == Gst.MessageType.EOS:
            return tags, mime, have_audio, duration
        elif msg.type == Gst.MessageType.ASYNC_DONE:
            success, duration = _query_duration(pipeline)
            if tags and success:
                return tags, mime, have_audio, duration

            # Don't try workaround for non-seekable sources such as mmssrc:
            if not _query_seekable(pipeline):
                return tags, mime, have_audio, duration

            # Workaround for upstream bug which causes tags/duration to arrive
            # after pre-roll. We get around this by starting to play the track
            # and then waiting for a duration change.
            # https://bugzilla.gnome.org/show_bug.cgi?id=763553
            logger.debug("Using workaround for duration missing before play.")
            result = pipeline.set_state(Gst.State.PLAYING)
            if result == Gst.StateChangeReturn.FAILURE:
                return tags, mime, have_audio, duration

        elif msg.type == Gst.MessageType.DURATION_CHANGED and tags:
            # VBR formats sometimes seem to not have a duration by the time we
            # go back to paused. So just try to get it right away.
            success, duration = _query_duration(pipeline)
            pipeline.set_state(Gst.State.PAUSED)
            if success:
                return tags, mime, have_audio, duration
        elif msg.type == Gst.MessageType.TAG:
            taglist = msg.parse_tag()
            # Note that this will only keep the last tag.
            tags.update(tags_lib.convert_taglist(taglist))

        timeout = timeout_ms - (int(time.time() * 1000) - start)

    raise exceptions.ScannerError(f"Timeout after {timeout_ms:d}ms")

if __name__ == "__main__":
    import os
    import sys

    from mopidy.internal import path

    logging.basicConfig(
        format="%(asctime)-15s %(levelname)s %(message)s",
        level=log.TRACE_LOG_LEVEL,
    )

    scanner = Scanner(5000)
    for uri in sys.argv[1:]:
        if not Gst.uri_is_valid(uri):
            uri = path.path_to_uri(os.path.abspath(uri))
        try:
            result = scanner.scan(uri)
            for key in ("uri", "mime", "duration", "playable", "seekable"):
                value = getattr(result, key)
                print(f"{key:<20}   {value}")
            print("tags")
            for tag, value in result.tags.items():
                line = f"{tag:<20}   {value}"
                if len(line) > 77:
                    line = line[:77] + "..."
                print(line)
        except exceptions.ScannerError as error:
            print(f"{uri}: {error}")


text:
from __future__ import unicode_literals

import logging
import re

from streamlink.exceptions import FatalPluginError, NoStreamsError, PluginError
from streamlink.plugin import Plugin, PluginArguments, PluginArgument
from streamlink.plugin.api import useragents, validate
from streamlink.stream import HLSStream
from streamlink.utils.encoding import maybe_decode

log = logging.getLogger(__name__)

class Pixiv(Plugin):
    """Plugin for https://sketch.pixiv.net/lives"""

    _url_re = re.compile(r"https?://sketch\.pixiv\.net/@?(?P<user>[^/]+)")
    _post_key_re = re.compile(
        r"""name=["']post_key["']\svalue=["'](?P<data>[^"']+)["']""")

    _user_dict_schema = validate.Schema(
        {
            "user": {
                "unique_name": validate.text,
                "name": validate.all(validate.text,
                                     validate.transform(maybe_decode))
            },
            validate.optional("hls_movie"): {
                "url": validate.text
            }
        }
    )

    _user_schema = validate.Schema(
        {
            "owner": _user_dict_schema,
            "performers": [
                validate.any(_user_dict_schema, None)
            ]
        }
    )

    _data_lives_schema = validate.Schema(
        {
            "data": {
                "lives": [_user_schema]
            }
        },
        validate.get("data"),
        validate.get("lives")
    )

    api_lives = "https://sketch.pixiv.net/api/lives.json"
    login_url_get = "https://accounts.pixiv.net/login"
    login_url_post = "https://accounts.pixiv.net/api/login"

    arguments = PluginArguments(
        PluginArgument(
            "username",
            requires=["password"],
            metavar="USERNAME",
            help="""
        The email/username used to register with pixiv.net
        """
        ),
        PluginArgument(
            "password",
            sensitive=True,
            metavar="PASSWORD",
            help="""
        A pixiv.net account password to use with --pixiv-username
        """
        ),
        PluginArgument(
            "purge-credentials",
            action="store_true",
            help="""
        Purge cached Pixiv credentials to initiate a new session
        and reauthenticate.
        """),
        PluginArgument(
            "performer",
            metavar="USER",
            help="""
        Select a co-host stream instead of the owner stream.
        """)
    )

    def __init__(self, url):
        super(Pixiv, self).__init__(url)
        self._authed = (self.session.http.cookies.get("PHPSESSID")
                        and self.session.http.cookies.get("device_token"))
        self.session.http.headers.update({
            "User-Agent": useragents.FIREFOX,
            "Referer": self.url
        })

    @classmethod
    def can_handle_url(cls, url):
        return cls._url_re.match(url) is not None

    def _login(self, username, password):
        res = self.session.http.get(self.login_url_get)
        m = self._post_key_re.search(res.text)
        if not m:
            raise PluginError("Missing post_key, no login posible.")

        post_key = m.group("data")
        data = {
            "lang": "en",
            "source": "sketch",
            "post_key": post_key,
            "pixiv_id": username,
            "password": password,
        }

        res = self.session.http.post(self.login_url_post, data=data)
        res = self.session.http.json(res)
        log.trace("{0!r}".format(res))
        if res["body"].get("success"):
            self.save_cookies()
            log.info("Successfully logged in")
        else:
            log.error("Failed to log in.")

    def hls_stream(self, hls_url):
        log.debug("URL={0}".format(hls_url))
        for s in HLSStream.parse_variant_playlist(self.session, hls_url).items():
            yield s

    def get_streamer_data(self):
        res = self.session.http.get(self.api_lives)
        data = self.session.http.json(res, schema=self._data_lives_schema)
        log.debug("Found {0} streams".format(len(data)))

        m = self._url_re.match(self.url)
        for item in data:
            if item["owner"]["user"]["unique_name"] == m.group("user"):
                return item

        raise NoStreamsError(self.url)

    def _get_streams(self):
        login_username = self.get_option("username")
        login_password = self.get_option("password")

        if self.options.get("purge_credentials"):
            self.clear_cookies()
            self._authed = False
            log.info("All credentials were successfully removed.")

        if self._authed:
            log.debug("Attempting to authenticate using cached cookies")
        elif not self._authed and login_username and login_password:
            self._login(login_username, login_password)

        streamer_data = self.get_streamer_data()
        performers = streamer_data.get("performers")
        log.trace("{0!r}".format(streamer_data))
        if performers:
            co_hosts = []
            # create a list of all available performers
            for p in performers:
                co_hosts += [(p["user"]["unique_name"], p["user"]["name"])]

            log.info("Available hosts: {0}".format(", ".join(
                ["{0} ({1})".format(k, v) for k, v in co_hosts])))

            # control if the host from --pixiv-performer is valid,
            # if not let the User select a different host
            if (self.get_option("performer")
                    and not self.get_option("performer") in [v[0] for v in co_hosts]):

                # print the owner as 0
                log.info("0 - {0} ({1})".format(
                    streamer_data["owner"]["user"]["unique_name"],
                    streamer_data["owner"]["user"]["name"]))
                # print all other performer
                for i, item in enumerate(co_hosts, start=1):
                    log.info("{0} - {1} ({2})".format(i, item[0], item[1]))

                try:
                    number = int(self.input_ask(
                        "Enter the number you'd like to watch").split(" ")[0])
                    if number == 0:
                        # default stream
                        self.set_option("performer", None)
                    else:
                        # other co-hosts
                        self.set_option("performer", co_hosts[number - 1][0])
                except FatalPluginError:
                    raise PluginError("Selected performer is invalid.")
                except (IndexError, ValueError, TypeError):
                    raise PluginError("Input is invalid")

        # ignore the owner stream, if a performer is selected
        # or use it when there are no other performers
        if not self.get_option("performer") or not performers:
            return self.hls_stream(streamer_data["owner"]["hls_movie"]["url"])

        # play a co-host stream
        if performers and self.get_option("performer"):
            for p in performers:
                if p["user"]["unique_name"] == self.get_option("performer"):
                    # if someone goes online at the same time as Streamlink
                    # was used, the hls URL might not be in the JSON data
                    hls_movie = p.get("hls_movie")
                    if hls_movie:
                        return self.hls_stream(hls_movie["url"])

__plugin__ = Pixiv


text:
function [stOutputResAlloc] = resalloc_fsp_by_auction(stInputResAlloc)
%% interative adjust price for combinatorial item (2 resources) with multiple period problem
% History
% YYYYMMDD  Notes
% 20070602  Release ComplementarySearch
% 20070605  improve stoping criterion zzy
% 20070704  Output complete price and netDemand history, required by JongHan, done by zzy
%           Add feasible solution information package into stSolutionInfo
% 20070921  Add full combo search
% 20070927  return the best solution even in equlibrium
% 20071102  combine price adj 5 into 6
% 20080228  detection of bad cycles, TBA
% 20080304  Debug
%%%%
stAgent_Solution   = stInputResAlloc.stAgent_Solution;
stBerthJobInfo  = stInputResAlloc.stBerthJobInfo;
stJobListInfoAgent = stInputResAlloc.stJobListInfoAgent;
%%% stResourceConfigGenSch0 = stInputResAlloc.stResourceConfigGenSch0;
astResourceConfigSrchSinglePeriod = stInputResAlloc.astResourceConfigSrchSinglePeriod ;
astResourceConfigGenSch0          = stInputResAlloc.astResourceConfigGenSch0          ;

stBerthJobInfo.stPriceDetectCycle.isCycle2 = 0; %%% 20080228
nTotalMachineType = 3;

%%% Assignment for agent based structure
stInputResAllocAgent.stBerthJobInfo     = stBerthJobInfo              ;
stInputResAllocAgent.iFlagSorting       = stInputResAlloc.iFlagSorting            ;
stInputResAllocAgent.iMaxIter_BidGenOpt = stInputResAlloc.iMaxIter_BidGenOpt      ;

iFlagPriceAdjust = stBerthJobInfo.stPriceAjustment.iFlagStrategy; % 20071102

iPlotFlag = stBerthJobInfo.iPlotFlag;
% == 0: no stop, plot least figure
% >= 1: stop for prompting
% >= 4: plot all figures, only for NUS-ECE_SMU collaborated users

t0 = cputime;

%%%% Initial Price
stMachinePriceInfo.astMachinePrice(2).fPricePerFrame = stBerthJobInfo.fPricePrimeMoverDollarPerFrame;
stMachinePriceInfo.astMachinePrice(3).fPricePerFrame = stBerthJobInfo.fPriceYardCraneDollarPerFrame;

fDeltaObj = stBerthJobInfo.stAuctionStrategy.fDeltaObj;               % 20070605
fDeltaPrice = stBerthJobInfo.stAuctionStrategy.fDeltaPrice;
iMinNumFeasibleSolution = stBerthJobInfo.stAuctionStrategy.iMinNumFeasibleSolution;
iConvergingRule = stBerthJobInfo.stAuctionStrategy.iConvergingRule;
iNumIterDeOscilating = stBerthJobInfo.stAuctionStrategy.iNumIterDeOscilating;
%%% Synchonous flag for price updating
%%% 1: synchronously, trigger only after collecting bids from all the clients
%%% -1: unsynchronously, trigger each time by event of submitting bid
iSynchFlagPriceUpdating = stBerthJobInfo.stAuctionStrategy.iSynchUpdatingBid;
n_feas = 0;
%%% Initialization output
astFeasibleSolutionSet = [];

%%% Initialization a circular buffer for latest feasible solution
%iLenPriceVector = length(stBerthJobInfo.fPricePrimeMoverDollarPerFrame) + length(stBerthJobInfo.fPriceYardCraneDollarPerFrame);
%for ii = 1:1:iNumIterDeOscilating
%    stConvergingVariableSet(ii).afPriceList = zeros(iLenPriceVector, 1);
%    stConvergingVariableSet(ii).fObjValue = 0;
%end
aiCirBufIdxLastFeasiSolution = zeros(iNumIterDeOscilating, 1);
iIdxCirBufIdxLastFeasiSolution = 0;         % 20070605

%%% initialize output structure % 20070605
stConstraintVialationInfo.nTotalCaseViolation = 0;
stConstraintVialationInfo.astCaseViolation    = [];
iFlagSolution = -1;  %% initialize the solution type to be infeasible

%%% Interation, auction
iMaxIter = stBerthJobInfo.stAuctionStrategy.iMaxIteration;
iMinIteration = stBerthJobInfo.stAuctionStrategy.iMinIteration ;
iter = 1;
while iter <= iMaxIter

    %%%%% 20070602, following section should be actually implemented
    %%%%% decentrally
    if stBerthJobInfo.iAlgoChoice == 7 | ...
            stBerthJobInfo.iAlgoChoice == 18 | stBerthJobInfo.iAlgoChoice == 20  ...
            | stBerthJobInfo.iAlgoChoice == 19 | stBerthJobInfo.iAlgoChoice == 21
        %%%%%%%%%% multi-period bid generation, multi-period price adjustment
        for ii = 1:1:stBerthJobInfo.iTotalAgent

            if iter >= iMinNumFeasibleSolution % 20080304
                stInputResAllocAgent.iFlag_RunGenSch2        = 1 ;
            else
                stInputResAllocAgent.iFlag_RunGenSch2        = 0 ;
            end

            stInputResAllocAgent.iAgentId_dbg      = ii;
            stInputResAllocAgent.stResourceConfigGenSch0          = astResourceConfigGenSch0(ii)  ;
            stInputResAllocAgent.stResourceConfigSrchSinglePeriod = astResourceConfigSrchSinglePeriod(ii) ;
%            stInputResAlloc.stResourceConfigSrchSinglePeriod_ii; % only
%            for initialization
            stInputResAllocAgent.stAgentJobInfo = stBerthJobInfo.stAgentJobInfo(ii);
            stInputResAllocAgent.stJobListInfoAgent    = stBerthJobInfo.stJobListInfoAgent(ii);
            % store the history
            stInputResAllocAgent.stAgent_Solution = stAgent_Solution(ii);
                %% By GenSch3, Algo 18, 19, 20
            if stBerthJobInfo.iAlgoChoice == 18
                [stAgent_Solution_ii] = bidgen_fsp_agent_ful_combo(stInputResAllocAgent);  % 20070921
            else
                [stAgent_Solution_ii] = bidgen_fsp_port_agent(stInputResAllocAgent);  %psa_bidgen_mp_srch_gensch3(stInputResAlloc);
            end

            stAgent_Solution(ii) = stAgent_Solution_ii;

            if iSynchFlagPriceUpdating == -1
                [stMachinePriceInfo, stMachineUsageInfoBerth, stMachineUsageInfoByAgent] = resalloc_bld_res_calc_price(stBerthJobInfo, stAgent_Solution, stMachinePriceInfo);
                %%% Update price
                stInputResAllocAgent.stBerthJobInfo.fPricePrimeMoverDollarPerFrame = stMachinePriceInfo.astMachinePrice(2).fPricePerFrame;
                stInputResAllocAgent.stBerthJobInfo.fPriceYardCraneDollarPerFrame = stMachinePriceInfo.astMachinePrice(3).fPricePerFrame;
                stInputResAllocAgent.stBerthJobInfo.astResourceInitPrice(2).afMachinePriceListPerFrame = stMachinePriceInfo.astMachinePrice(2).fPricePerFrame;
                stInputResAllocAgent.stBerthJobInfo.astResourceInitPrice(3).afMachinePriceListPerFrame = stMachinePriceInfo.astMachinePrice(3).fPricePerFrame;
            end

        end
    else
        error('Only enable multi-period bid-generation');
    end

    if iSynchFlagPriceUpdating == 1 | iter == 1
        [stMachinePriceInfo, stMachineUsageInfoBerth, stMachineUsageInfoByAgent] = resalloc_bld_res_calc_price(stBerthJobInfo, stAgent_Solution, stMachinePriceInfo);
        %%% Update price
        stInputResAllocAgent.stBerthJobInfo.fPricePrimeMoverDollarPerFrame = stMachinePriceInfo.astMachinePrice(2).fPricePerFrame;
        stInputResAllocAgent.stBerthJobInfo.fPriceYardCraneDollarPerFrame = stMachinePriceInfo.astMachinePrice(3).fPricePerFrame;
        stInputResAllocAgent.stBerthJobInfo.astResourceInitPrice(2).afMachinePriceListPerFrame = stMachinePriceInfo.astMachinePrice(2).fPricePerFrame;
        stInputResAllocAgent.stBerthJobInfo.astResourceInitPrice(3).afMachinePriceListPerFrame = stMachinePriceInfo.astMachinePrice(3).fPricePerFrame;
    end
    s_r(iter) = mean(stMachinePriceInfo.s_r);
    alpha(iter) = stMachinePriceInfo.alpha;
    fStepSizePerMachCurrIter = stMachinePriceInfo.s_r;

    aPricePrimeMover_From8Clock = stInputResAllocAgent.stBerthJobInfo.fPricePrimeMoverDollarPerFrame(8:24);
    aiNetusagePrimeMover = stMachineUsageInfoBerth.astMachineUsage(2).aMachineUsageAfterTime - stMachineUsageInfoBerth.astMachineUsage(2).iMaxCapacity;
    aPriceYardCrane_From8Clock  = stInputResAllocAgent.stBerthJobInfo.fPriceYardCraneDollarPerFrame(8:24);
    aiNetusageYardCrane = stMachineUsageInfoBerth.astMachineUsage(3).aMachineUsageAfterTime - stMachineUsageInfoBerth.astMachineUsage(3).iMaxCapacity;

    aMaxNetDemandPrimeMover(iter) = max(aiNetusagePrimeMover);
    aMaxNetDemandYardCrane(iter) = max(aiNetusageYardCrane);
    [fMaxPricePrimeMover, idxMaxPricePrimeMover] = max(stMachinePriceInfo.astMachinePrice(2).fPricePerFrame);
    aMaxPricePrimeMover(iter) = fMaxPricePrimeMover;
    aidxMaxPricePrimeMover(iter) = idxMaxPricePrimeMover;
    [fMaxPriceYardCrane, idxMaxPriceYardCrane] = max(stMachinePriceInfo.astMachinePrice(3).fPricePerFrame);
    aMaxPriceYardCrane(iter)  = fMaxPriceYardCrane;
    aidxMaxPriceYardCrane(iter) = idxMaxPriceYardCrane;

    %%% 20080228
    idxMachPeriod = 0;
    idxPricePeriod = 0;
    for mm = 1:1:nTotalMachineType
        if mm ~= stBerthJobInfo.stSystemMasterConfig.iCriticalMachType
            nTotalMachUsagePeriod = length(stMachineUsageInfoBerth.astMachineUsage(mm).aMachineUsageAfterTime);
            for pp = 1:1:nTotalMachUsagePeriod
                idxMachPeriod = idxMachPeriod + 1;
                aiNetUsageGenMachine(idxMachPeriod) = ...
                    stMachineUsageInfoBerth.astMachineUsage(mm).aMachineUsageAfterTime(pp) ...
                    - stMachineUsageInfoBerth.astMachineUsage(mm).iMaxCapacity;  %% to be generalize later
            end
            nTotalPricePeriod = length(stMachinePriceInfo.astMachinePrice(mm).fPricePerFrame);
            for pp = 1:1:nTotalPricePeriod
                idxPricePeriod = idxPricePeriod + 1;
                afPriceGenMachinePeriod(idxPricePeriod) = stMachinePriceInfo.astMachinePrice(mm).fPricePerFrame(pp);
            end
            if nTotalMachUsagePeriod ~= nTotalPricePeriod
%                anPeriod_MachineUsage_Price = [nTotalMachUsagePeriod, nTotalPricePeriod]
                 strText = sprintf('mType:%d, TotalUsagePeriod-%d TotalPricingPeriod-%d', ...
                     mm, nTotalMachUsagePeriod, nTotalPricePeriod);
                 disp(strText);
            end
        end
    end
    [aiSortNetMachUsage, aiIdxSortNetMachUsage ]= sort(aiNetUsageGenMachine);
    [afSortPriceMachPeriod, aiIdxSortPriceMachPeriod] = sort(afPriceGenMachinePeriod);
    %%% 20080228
    astConvergingInfo(iter).aiSortNetMachUsage = aiSortNetMachUsage;
    astConvergingInfo(iter).aiIdxSortNetMachUsage = aiIdxSortNetMachUsage;
    astConvergingInfo(iter).afSortPriceMachPeriod = afSortPriceMachPeriod;
    astConvergingInfo(iter).aiIdxSortPriceMachPeriod = aiIdxSortPriceMachPeriod;

    astMachinePriceInfo(iter) = stMachinePriceInfo;    % 20070704
    astMachineUsageInfoGlobal(iter) = stMachineUsageInfoBerth; % 20070704
    if iPlotFlag >= 5
        input('Press any key');
    end

    %%%%% Stopping Criterion, % 20070605
    if max(aiNetUsageGenMachine) <= 0 % & max(aiNetusageYardCrane) <= 0
        iaFlagIsFeasibleSolution(iter) = 1;
        n_feas = n_feas + 1;

        %%% Machine usage confliction resolved
        if iFlagPriceAdjust == 6 & stBerthJobInfo.stPriceAjustment.iFlagStrategy == 5 ...
                & n_feas >= iMinNumFeasibleSolution %% temperility hard-coded TBA, donot return to smaller step immediately, but seek some optimality
            stBerthJobInfo.stPriceAjustment.iFlagStrategy = 6; %% for the later iterations with feasible solutions
            % 20080304
            stMachinePriceInfo.astMachinePrice(2).fPricePerFrame = ...
                astFeasibleSolutionSet(iBestSolutionIndex).astFeasiblePriceInfo.stMachinePriceInfo.astMachinePrice(2).fPricePerFrame;
            stMachinePriceInfo.astMachinePrice(3).fPricePerFrame = ...
                astFeasibleSolutionSet(iBestSolutionIndex).astFeasiblePriceInfo.stMachinePriceInfo.astMachinePrice(3).fPricePerFrame;
            % 20080304
        end  % 20071102

        for aa = 1:1:stBerthJobInfo.iTotalAgent % 20080304
            stPartialScheduleGenSch2 = stAgent_Solution(aa).stCostAtAgent.stSolutionMinCost.stSchedule;
            [stSchedule] = psa_jsp_dispatch_machine_02(stPartialScheduleGenSch2);
            stAgent_Solution(aa).stCostAtAgent.stSolutionMinCost.stSchedule = stSchedule;
        end % 20080304

        astFeasibleSolutionSet(n_feas).astAgent_Solution = stAgent_Solution;
        astFeasibleSolutionSet(n_feas).afPriceListPMandYC = ... % TBA
            [stInputResAllocAgent.stBerthJobInfo.fPricePrimeMoverDollarPerFrame, stInputResAllocAgent.stBerthJobInfo.fPriceYardCraneDollarPerFrame];
        astFeasibleSolutionSet(n_feas).astFeasiblePriceInfo.stMachinePriceInfo = stMachinePriceInfo; % 20080304
        fFeasibleObjValue = 0;
        for ii = 1:1:stBerthJobInfo.iTotalAgent
            fFeasibleObjValue = fFeasibleObjValue + stAgent_Solution(ii).stPerformReport.fCostMakespanTardiness;
        end
        astFeasibleSolutionSet(n_feas).fFeasibleObjValue = fFeasibleObjValue;
        astFeasibleSolutionSet(n_feas).iIterationInAuction = iter; % 20070704
        if n_feas == 1
            %% Initialization of the Best Feasible
            fBestFeasibleSolution = fFeasibleObjValue;
            iBestSolutionIndex = n_feas;
        else
            if fBestFeasibleSolution > fFeasibleObjValue
                fBestFeasibleSolution = fFeasibleObjValue;
                iBestSolutionIndex = n_feas;
            end
        end

        %% update the circular buffer to the index
        iIdxCirBufIdxLastFeasiSolution = iIdxCirBufIdxLastFeasiSolution + 1;
        if iIdxCirBufIdxLastFeasiSolution > iNumIterDeOscilating
            iIdxCirBufIdxLastFeasiSolution = 1;
        end
        aiCirBufIdxLastFeasiSolution(iIdxCirBufIdxLastFeasiSolution) = n_feas;
%        stConvergingVariableSet(iIdxCirBufIdxLastFeasiSolution).afPriceList = ;
    else
        iaFlagIsFeasibleSolution(iter) = 0;
        if iFlagPriceAdjust == 6 & iter >= 3 & n_feas == 0  % nIterInfeasAdjustByFunc = 10
            stBerthJobInfo.stPriceAjustment.iFlagStrategy = 5; %% for the initial iterations with unfeasible solutions
        end  % 20071102
    end
%     astConvergingInfo(iter).aiSortNetMachUsage;
%     astConvergingInfo(iter).aiIdxSortNetMachUsage;
%     astConvergingInfo(iter).afSortPriceMachPeriod;
%     astConvergingInfo(iter).aiIdxSortPriceMachPeriod;

    if iter >= 4 % detection of cyclation % 20080228
        if (abs(alpha(iter) - alpha(iter - 2)) < 0.0001 & abs(alpha(iter - 1) - alpha(iter - 3)) < 0.0001) ...
                | (abs(s_r(iter) - s_r(iter - 2)) < 0.0001 & abs(s_r(iter - 1) - s_r(iter - 3)) < 0.0001)
%           if (astConvergingInfo(iter).aiIdxSortNetMachUsage(end) ...
%                   == astConvergingInfo(iter-1).aiIdxSortNetMachUsage(end-1) ...
%                 & astConvergingInfo(iter-1).aiIdxSortNetMachUsage(end-1) ...
%                   == astConvergingInfo(iter-2).aiIdxSortNetMachUsage(end) ...
%                 & astConvergingInfo(iter-2).aiIdxSortNetMachUsage(end) ...
%                   == astConvergingInfo(iter-3).aiIdxSortNetMachUsage(end-1)) ...
%             & (astConvergingInfo(iter).aiIdxSortNetMachUsage(end-1) ...
%                   == astConvergingInfo(iter-1).aiIdxSortNetMachUsage(end) ...
%                 & astConvergingInfo(iter-1).aiIdxSortNetMachUsage(end) ...
%                   == astConvergingInfo(iter-2).aiIdxSortNetMachUsage(end-1) ...
%                 & astConvergingInfo(iter-2).aiIdxSortNetMachUsage(end-1) ...
%                   == astConvergingInfo(iter-3).aiIdxSortNetMachUsage(end)) ...
%             & (astConvergingInfo(iter).aiSortNetMachUsage(end) > 0 ...
%                 & astConvergingInfo(iter).aiSortNetMachUsage(end-1) > 0 )
            stBerthJobInfo.stPriceDetectCycle.isCycle2 = 1;
        else
            stBerthJobInfo.stPriceDetectCycle.isCycle2 = 0;
        end
    end

    %% Checking not oscilating
    if n_feas >= iMinNumFeasibleSolution & iter >= iMinIteration
        %%%
        iFlagConverging = 1;
        for ii = 2:1:iNumIterDeOscilating
            iCurrIdxInFeasibleSolutionSet = aiCirBufIdxLastFeasiSolution(ii);
            iPrevIdxInFeasibleSolutionSet = aiCirBufIdxLastFeasiSolution(ii-1);
            if iConvergingRule == 0  %%% price only
                if norm(astFeasibleSolutionSet(iCurrIdxInFeasibleSolutionSet).afPriceListPMandYC - ...
                        astFeasibleSolutionSet(iPrevIdxInFeasibleSolutionSet).afPriceListPMandYC) > fDeltaPrice
                    iFlagConverging = 0;
                end
            elseif iConvergingRule == 1  %%% obj value only
                if norm(astFeasibleSolutionSet(iCurrIdxInFeasibleSolutionSet).fFeasibleObjValue - ...
                        astFeasibleSolutionSet(iPrevIdxInFeasibleSolutionSet).fFeasibleObjValue) > fDeltaObj
                    iFlagConverging = 0;
                end
            elseif iConvergingRule == 2
                if (norm(astFeasibleSolutionSet(iCurrIdxInFeasibleSolutionSet).afPriceListPMandYC - ...
                        astFeasibleSolutionSet(iPrevIdxInFeasibleSolutionSet).afPriceListPMandYC) > fDeltaPrice)  ...
                        & ...
                        (norm(astFeasibleSolutionSet(iCurrIdxInFeasibleSolutionSet).fFeasibleObjValue - ...
                        astFeasibleSolutionSet(iPrevIdxInFeasibleSolutionSet).fFeasibleObjValue) > fDeltaObj)

                    iFlagConverging = 0;
                end
            elseif iConvergingRule == 3
                if (norm(astFeasibleSolutionSet(iCurrIdxInFeasibleSolutionSet).afPriceListPMandYC - ...
                        astFeasibleSolutionSet(iPrevIdxInFeasibleSolutionSet).afPriceListPMandYC) > fDeltaPrice)  ...
                        | ...
                        (norm(astFeasibleSolutionSet(iCurrIdxInFeasibleSolutionSet).fFeasibleObjValue - ...
                        astFeasibleSolutionSet(iPrevIdxInFeasibleSolutionSet).fFeasibleObjValue) > fDeltaObj)

                    iFlagConverging = 0;
                end

            else
                %% always think it is converging
            end
        end

        if iFlagConverging == 1
            %% Equilibrium solution has achieved. 20070927
            stAgent_Solution = astFeasibleSolutionSet(iBestSolutionIndex).astAgent_Solution;
            iFlagSolution = 2; %% Equilibrium Solution
            break;
        end
    else
    end

    if iPlotFlag >= 1
        strText = sprintf('MeanSr \t Alpha \t Itr \t Sr(1:K) \t IsFeasi \t IsCyc \t Top3PriceIdx');
        disp(strText);
        strText = sprintf('%4.2f , %4.2f , %d ;', s_r(iter), alpha(iter), iter);
        for mm = 1:1:nTotalMachineType
            strText = sprintf('%s %4.2f,', strText, fStepSizePerMachCurrIter(mm));
        end
        strText = sprintf('%s %d, %d; ', ...
            strText, iaFlagIsFeasibleSolution(iter), stBerthJobInfo.stPriceDetectCycle.isCycle2);
        for ii = 1:1:3
            strText = sprintf('%s %4.1f, %d;', ...
                strText, afSortPriceMachPeriod(end + 1 - ii), floor(aiIdxSortPriceMachPeriod(end + 1 - ii)));

        end
        disp(strText);
    end
%     MeanSr_Alpha_Itr_Sr_IsFeasi_IsCyc_Top3PriceIdx = [s_r(iter), alpha(iter), floor(iter), ...
%                           fStepSizePerMachCurrIter, floor(iaFlagIsFeasibleSolution(iter)), ...
%                           floor(stBerthJobInfo.stPriceDetectCycle.isCycle2), ...
%                           afSortPriceMachPeriod(end), floor(aiIdxSortPriceMachPeriod(end)), ...
%                           afSortPriceMachPeriod(end-1), floor(aiIdxSortPriceMachPeriod(end-1)), ...
%                           afSortPriceMachPeriod(end-2), floor(aiIdxSortPriceMachPeriod(end-2)), ...
%                           ]

    iter = iter + 1;
    if iter > iMaxIter
        %%% Still not resolve in the last iteration
        if n_feas >= 1
            stAgent_Solution = astFeasibleSolutionSet(iBestSolutionIndex).astAgent_Solution;
            iFlagSolution = 1;  %% Best in history feasible solution
        else
            % 20070605 manually adjust to feasible solution
%            save temp_resolve_conflt.mat stBerthJobInfo stAgent_Solution stJobListInfoAgent
             aPosnNameDot = strfind(stBerthJobInfo.strInputFilename, '.');
             if length(aPosnNameDot) == 0
                 strCmd_SaveMatFileResvConflt = sprintf('save %s_resolve_conflt.mat stBerthJobInfo stAgent_Solution stJobListInfoAgent', stBerthJobInfo.strInputFilename)
             else
                 strCmd_SaveMatFileResvConflt = sprintf('save %s_resolve_conflt.mat stBerthJobInfo stAgent_Solution stJobListInfoAgent', ...
                     stBerthJobInfo.strInputFilename(1:(aPosnNameDot(end)-1)));
             end
             eval(strCmd_SaveMatFileResvConflt);

            [stAgent_Solution, stDebugOutputSolveByPriority] = psa_resalloc_solve_by_priority(stBerthJobInfo, stAgent_Solution, stJobListInfoAgent);
            stConstraintVialationInfo.nTotalCaseViolation = stDebugOutputSolveByPriority.nTotalCaseViolation;
            stConstraintVialationInfo.astCaseViolation    = stDebugOutputSolveByPriority.astCaseViolation;
            iFlagSolution = 0;  %% Manually adjusted feasible solution
        end
    end
end

tSolutionTime_sec = cputime - t0;

fFeasibleObjValue = 0;
for ii = 1:1:stBerthJobInfo.iTotalAgent
    fFeasibleObjValue = fFeasibleObjValue + stAgent_Solution(ii).stPerformReport.fCostMakespanTardiness;
end

stSolutionInfo.fTotalCostMakespanTardiness = fFeasibleObjValue;
stSolutionInfo.s_r      = s_r;
stSolutionInfo.fAlphaList = alpha;
stSolutionInfo.iMaxIter = iMaxIter;
stSolutionInfo.iActualIter = iter;
stSolutionInfo.tSolutionTime_sec = tSolutionTime_sec;
stSolutionInfo.nTotalFeasibleSolution = n_feas;
stSolutionInfo.astFeasibleSolutionSet = astFeasibleSolutionSet;
stSolutionInfo.iFlagSolution = iFlagSolution;
  %% 0; Manually adjusted feasible solution
  %% 1; Best in history feasible solution
  %% 2; Equilibrium Solution
stSolutionInfo.aMaxNetDemandPrimeMover = aMaxNetDemandPrimeMover;
stSolutionInfo.aMaxNetDemandYardCrane  = aMaxNetDemandYardCrane;
stSolutionInfo.aMaxPricePrimeMover     = aMaxPricePrimeMover;
stSolutionInfo.aMaxPriceYardCrane      = aMaxPriceYardCrane;
stSolutionInfo.aidxMaxPricePrimeMover  = aidxMaxPricePrimeMover;
stSolutionInfo.aidxMaxPriceYardCrane   = aidxMaxPriceYardCrane;
stSolutionInfo.astMachineUsageInfoGlobal = astMachineUsageInfoGlobal;    % 20070704
stSolutionInfo.astMachinePriceInfo      = astMachinePriceInfo;         % 20070704

stOutputResAlloc.stMachineUsageInfoBerth = stMachineUsageInfoBerth;
stOutputResAlloc.stMachineUsageInfoByAgent  = stMachineUsageInfoByAgent;
stOutputResAlloc.stAgent_Solution           = stAgent_Solution;
stOutputResAlloc.stSolutionInfo          = stSolutionInfo;
stOutputResAlloc.stMachinePriceInfo      = stMachinePriceInfo;       % 20070704
stOutputResAlloc.astFeasibleSolutionSet  = astFeasibleSolutionSet;
stOutputResAlloc.stConstraintVialationInfo = stConstraintVialationInfo;

stAgent_Solution.stPerformReport

%%% plotting solution
% if iPlotFlag >= 1
%     stIdFigure.iAllScheGroupByMachine = 101;
%     stIdFigure.iAllScheGroupByJob = 102;
%     psa_plot_resalloc_sch_all_in_1(stAgent_Solution, stIdFigure);
% end


text:
Difficulty: Medium

https://leetcode.com/problems/rabbits-in-forest/

In a forest, each rabbit has some color. Some subset of rabbits (possibly all of them) tell you how many other rabbits have the same color as them. Those answers are placed in an array.

Return the minimum number of rabbits that could be in the forest.
```
Examples:
Input: answers = [1, 1, 2]
Output: 5
Explanation:
The two rabbits that answered "1" could both be the same color, say red.
The rabbit than answered "2" can't be red or the answers would be inconsistent.
Say the rabbit that answered "2" was blue.
Then there should be 2 other blue rabbits in the forest that didn't answer into the array.
The smallest possible number of rabbits in the forest is therefore 5: 3 that answered plus 2 that didn't.

Input: answers = [10, 10, 10]
Output: 11

Input: answers = []
Output: 0
```
**Note:**

1. answers will have length at most 1000.
2. Each answers[i] will be an integer in the range [0, 999].

Companies: Wish

Related Topics: Hash Table, Math


text:
export class Ride {
  constructor() { }
  duration = 30;
  sampleId: string;
}


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: FyChessMessage.proto

package org.okraAx.v3.chess.beans;

/**
 *

 * 响应加入棋局
 *

 *
 * Protobuf type {@code org.okraAx.v3.ResChessJoin}
 */
public  final class ResChessJoin extends
    com.google.protobuf.GeneratedMessageV3 implements
    // @@protoc_insertion_point(message_implements:org.okraAx.v3.ResChessJoin)
    ResChessJoinOrBuilder {
  // Use ResChessJoin.newBuilder() to construct.
  private ResChessJoin(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
    super(builder);
  }
  private ResChessJoin() {
    side_ = 0;
  }

  @java.lang.Override
  public final com.google.protobuf.UnknownFieldSet
  getUnknownFields() {
    return com.google.protobuf.UnknownFieldSet.getDefaultInstance();
  }
  private ResChessJoin(
      com.google.protobuf.CodedInputStream input,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws com.google.protobuf.InvalidProtocolBufferException {
    this();
    int mutable_bitField0_ = 0;
    try {
      boolean done = false;
      while (!done) {
        int tag = input.readTag();
        switch (tag) {
          case 0:
            done = true;
            break;
          default: {
            if (!input.skipField(tag)) {
              done = true;
            }
            break;
          }
          case 8: {

            side_ = input.readInt32();
            break;
          }
        }
      }
    } catch (com.google.protobuf.InvalidProtocolBufferException e) {
      throw e.setUnfinishedMessage(this);
    } catch (java.io.IOException e) {
      throw new com.google.protobuf.InvalidProtocolBufferException(
          e).setUnfinishedMessage(this);
    } finally {
      makeExtensionsImmutable();
    }
  }
  public static final com.google.protobuf.Descriptors.Descriptor
      getDescriptor() {
    return org.okraAx.v3.chess.beans.FyChessMi.internal_static_org_okraAx_v3_ResChessJoin_descriptor;
  }

  protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internalGetFieldAccessorTable() {
    return org.okraAx.v3.chess.beans.FyChessMi.internal_static_org_okraAx_v3_ResChessJoin_fieldAccessorTable
        .ensureFieldAccessorsInitialized(
            org.okraAx.v3.chess.beans.ResChessJoin.class, org.okraAx.v3.chess.beans.ResChessJoin.Builder.class);
  }

  public static final int SIDE_FIELD_NUMBER = 1;
  private int side_;
  /**
   *

   *  阵营
   *

   *
   * optional int32 side = 1;
   */
  public int getSide() {
    return side_;
  }

  private byte memoizedIsInitialized = -1;
  public final boolean isInitialized() {
    byte isInitialized = memoizedIsInitialized;
    if (isInitialized == 1) return true;
    if (isInitialized == 0) return false;

    memoizedIsInitialized = 1;
    return true;
  }

  public void writeTo(com.google.protobuf.CodedOutputStream output)
                      throws java.io.IOException {
    if (side_ != 0) {
      output.writeInt32(1, side_);
    }
  }

  public int getSerializedSize() {
    int size = memoizedSize;
    if (size != -1) return size;

    size = 0;
    if (side_ != 0) {
      size += com.google.protobuf.CodedOutputStream
        .computeInt32Size(1, side_);
    }
    memoizedSize = size;
    return size;
  }

  private static final long serialVersionUID = 0L;
  @java.lang.Override
  public boolean equals(final java.lang.Object obj) {
    if (obj == this) {
     return true;
    }
    if (!(obj instanceof org.okraAx.v3.chess.beans.ResChessJoin)) {
      return super.equals(obj);
    }
    org.okraAx.v3.chess.beans.ResChessJoin other = (org.okraAx.v3.chess.beans.ResChessJoin) obj;

    boolean result = true;
    result = result && (getSide()
        == other.getSide());
    return result;
  }

  @java.lang.Override
  public int hashCode() {
    if (memoizedHashCode != 0) {
      return memoizedHashCode;
    }
    int hash = 41;
    hash = (19 * hash) + getDescriptorForType().hashCode();
    hash = (37 * hash) + SIDE_FIELD_NUMBER;
    hash = (53 * hash) + getSide();
    hash = (29 * hash) + unknownFields.hashCode();
    memoizedHashCode = hash;
    return hash;
  }

  public static org.okraAx.v3.chess.beans.ResChessJoin parseFrom(
      com.google.protobuf.ByteString data)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data);
  }
  public static org.okraAx.v3.chess.beans.ResChessJoin parseFrom(
      com.google.protobuf.ByteString data,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data, extensionRegistry);
  }
  public static org.okraAx.v3.chess.beans.ResChessJoin parseFrom(byte[] data)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data);
  }
  public static org.okraAx.v3.chess.beans.ResChessJoin parseFrom(
      byte[] data,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data, extensionRegistry);
  }
  public static org.okraAx.v3.chess.beans.ResChessJoin parseFrom(java.io.InputStream input)
      throws java.io.IOException {
    return com.google.protobuf.GeneratedMessageV3
        .parseWithIOException(PARSER, input);
  }
  public static org.okraAx.v3.chess.beans.ResChessJoin parseFrom(
      java.io.InputStream input,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws java.io.IOException {
    return com.google.protobuf.GeneratedMessageV3
        .parseWithIOException(PARSER, input, extensionRegistry);
  }
  public static org.okraAx.v3.chess.beans.ResChessJoin parseDelimitedFrom(java.io.InputStream input)
      throws java.io.IOException {
    return com.google.protobuf.GeneratedMessageV3
        .parseDelimitedWithIOException(PARSER, input);
  }
  public static org.okraAx.v3.chess.beans.ResChessJoin parseDelimitedFrom(
      java.io.InputStream input,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws java.io.IOException {
    return com.google.protobuf.GeneratedMessageV3
        .parseDelimitedWithIOException(PARSER, input, extensionRegistry);
  }
  public static org.okraAx.v3.chess.beans.ResChessJoin parseFrom(
      com.google.protobuf.CodedInputStream input)
      throws java.io.IOException {
    return com.google.protobuf.GeneratedMessageV3
        .parseWithIOException(PARSER, input);
  }
  public static org.okraAx.v3.chess.beans.ResChessJoin parseFrom(
      com.google.protobuf.CodedInputStream input,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws java.io.IOException {
    return com.google.protobuf.GeneratedMessageV3
        .parseWithIOException(PARSER, input, extensionRegistry);
  }

  public Builder newBuilderForType() { return newBuilder(); }
  public static Builder newBuilder() {
    return DEFAULT_INSTANCE.toBuilder();
  }
  public static Builder newBuilder(org.okraAx.v3.chess.beans.ResChessJoin prototype) {
    return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
  }
  public Builder toBuilder() {
    return this == DEFAULT_INSTANCE
        ? new Builder() : new Builder().mergeFrom(this);
  }

  @java.lang.Override
  protected Builder newBuilderForType(
      com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
    Builder builder = new Builder(parent);
    return builder;
  }
  /**
   *

   * 响应加入棋局
   *

   *
   * Protobuf type {@code org.okraAx.v3.ResChessJoin}
   */
  public static final class Builder extends
      com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
      // @@protoc_insertion_point(builder_implements:org.okraAx.v3.ResChessJoin)
      org.okraAx.v3.chess.beans.ResChessJoinOrBuilder {
    public static final com.google.protobuf.Descriptors.Descriptor
        getDescriptor() {
      return org.okraAx.v3.chess.beans.FyChessMi.internal_static_org_okraAx_v3_ResChessJoin_descriptor;
    }

    protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
        internalGetFieldAccessorTable() {
      return org.okraAx.v3.chess.beans.FyChessMi.internal_static_org_okraAx_v3_ResChessJoin_fieldAccessorTable
          .ensureFieldAccessorsInitialized(
              org.okraAx.v3.chess.beans.ResChessJoin.class, org.okraAx.v3.chess.beans.ResChessJoin.Builder.class);
    }

    // Construct using org.okraAx.v3.chess.beans.ResChessJoin.newBuilder()
    private Builder() {
      maybeForceBuilderInitialization();
    }

    private Builder(
        com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
      super(parent);
      maybeForceBuilderInitialization();
    }
    private void maybeForceBuilderInitialization() {
      if (com.google.protobuf.GeneratedMessageV3
              .alwaysUseFieldBuilders) {
      }
    }
    public Builder clear() {
      super.clear();
      side_ = 0;

      return this;
    }

    public com.google.protobuf.Descriptors.Descriptor
        getDescriptorForType() {
      return org.okraAx.v3.chess.beans.FyChessMi.internal_static_org_okraAx_v3_ResChessJoin_descriptor;
    }

    public org.okraAx.v3.chess.beans.ResChessJoin getDefaultInstanceForType() {
      return org.okraAx.v3.chess.beans.ResChessJoin.getDefaultInstance();
    }

    public org.okraAx.v3.chess.beans.ResChessJoin build() {
      org.okraAx.v3.chess.beans.ResChessJoin result = buildPartial();
      if (!result.isInitialized()) {
        throw newUninitializedMessageException(result);
      }
      return result;
    }

    public org.okraAx.v3.chess.beans.ResChessJoin buildPartial() {
      org.okraAx.v3.chess.beans.ResChessJoin result = new org.okraAx.v3.chess.beans.ResChessJoin(this);
      result.side_ = side_;
      onBuilt();
      return result;
    }

    public Builder clone() {
      return (Builder) super.clone();
    }
    public Builder setField(
        com.google.protobuf.Descriptors.FieldDescriptor field,
        Object value) {
      return (Builder) super.setField(field, value);
    }
    public Builder clearField(
        com.google.protobuf.Descriptors.FieldDescriptor field) {
      return (Builder) super.clearField(field);
    }
    public Builder clearOneof(
        com.google.protobuf.Descriptors.OneofDescriptor oneof) {
      return (Builder) super.clearOneof(oneof);
    }
    public Builder setRepeatedField(
        com.google.protobuf.Descriptors.FieldDescriptor field,
        int index, Object value) {
      return (Builder) super.setRepeatedField(field, index, value);
    }
    public Builder addRepeatedField(
        com.google.protobuf.Descriptors.FieldDescriptor field,
        Object value) {
      return (Builder) super.addRepeatedField(field, value);
    }
    public Builder mergeFrom(com.google.protobuf.Message other) {
      if (other instanceof org.okraAx.v3.chess.beans.ResChessJoin) {
        return mergeFrom((org.okraAx.v3.chess.beans.ResChessJoin)other);
      } else {
        super.mergeFrom(other);
        return this;
      }
    }

    public Builder mergeFrom(org.okraAx.v3.chess.beans.ResChessJoin other) {
      if (other == org.okraAx.v3.chess.beans.ResChessJoin.getDefaultInstance()) return this;
      if (other.getSide() != 0) {
        setSide(other.getSide());
      }
      onChanged();
      return this;
    }

    public final boolean isInitialized() {
      return true;
    }

    public Builder mergeFrom(
        com.google.protobuf.CodedInputStream input,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws java.io.IOException {
      org.okraAx.v3.chess.beans.ResChessJoin parsedMessage = null;
      try {
        parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
      } catch (com.google.protobuf.InvalidProtocolBufferException e) {
        parsedMessage = (org.okraAx.v3.chess.beans.ResChessJoin) e.getUnfinishedMessage();
        throw e.unwrapIOException();
      } finally {
        if (parsedMessage != null) {
          mergeFrom(parsedMessage);
        }
      }
      return this;
    }

    private int side_ ;
    /**
     *

     *  阵营
     *

     *
     * optional int32 side = 1;
     */
    public int getSide() {
      return side_;
    }
    /**
     *

     *  阵营
     *

     *
     * optional int32 side = 1;
     */
    public Builder setSide(int value) {

      side_ = value;
      onChanged();
      return this;
    }
    /**
     *

     *  阵营
     *

     *
     * optional int32 side = 1;
     */
    public Builder clearSide() {

      side_ = 0;
      onChanged();
      return this;
    }
    public final Builder setUnknownFields(
        final com.google.protobuf.UnknownFieldSet unknownFields) {
      return this;
    }

    public final Builder mergeUnknownFields(
        final com.google.protobuf.UnknownFieldSet unknownFields) {
      return this;
    }

    // @@protoc_insertion_point(builder_scope:org.okraAx.v3.ResChessJoin)
  }

  // @@protoc_insertion_point(class_scope:org.okraAx.v3.ResChessJoin)
  private static final org.okraAx.v3.chess.beans.ResChessJoin DEFAULT_INSTANCE;
  static {
    DEFAULT_INSTANCE = new org.okraAx.v3.chess.beans.ResChessJoin();
  }

  public static org.okraAx.v3.chess.beans.ResChessJoin getDefaultInstance() {
    return DEFAULT_INSTANCE;
  }

  private static final com.google.protobuf.Parser<ResChessJoin>
      PARSER = new com.google.protobuf.AbstractParser<ResChessJoin>() {
    public ResChessJoin parsePartialFrom(
        com.google.protobuf.CodedInputStream input,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws com.google.protobuf.InvalidProtocolBufferException {
        return new ResChessJoin(input, extensionRegistry);
    }
  };

  public static com.google.protobuf.Parser<ResChessJoin> parser() {
    return PARSER;
  }

  @java.lang.Override
  public com.google.protobuf.Parser<ResChessJoin> getParserForType() {
    return PARSER;
  }

  public org.okraAx.v3.chess.beans.ResChessJoin getDefaultInstanceForType() {
    return DEFAULT_INSTANCE;
  }

}


text:
module States {
    export class Fade2D extends Engine.State2D implements Engine.GameState {
        private myManagers: Managers.ManagerSet;
        private position: number;
        private direction: number;
        private drawState: Engine.State2D;
        private back: Drawing.Sprite;
        private firstFrame: boolean;

        constructor(managers: Managers.ManagerSet, start: number, drawState: Engine.State2D, runPhysicsFirst: boolean) {
            super(managers);
            this.myManagers = managers;
            this.position = start;
            this.direction = start > 0.5 ? -1.0 : 1.0;
            this.drawState = drawState;
            this.firstFrame = runPhysicsFirst;
        }

        load(gl: WebGLRenderingContext): void {
            super.load(gl);

            var blackTex = new WGL.Texture(gl);
            var cvs = this.myManagers.Canvas.getCanvas();
            cvs.width = 32;
            cvs.height = 32;

            var ctx = cvs.getContext('2d');
            ctx.fillStyle = '#000000';
            ctx.fillRect(0, 0, cvs.width, cvs.height);

            blackTex.loadData(cvs);
            blackTex.setFilters(gl.NEAREST, gl.NEAREST);

            var blackFrag = new Drawing.TextureFragment(blackTex, 0, 0, 320, 200);
            this.back = new Drawing.Sprite(gl, this.myManagers, blackFrag);
            this.back.Alpha = 1.0 - this.position;
        }

        unload(): void {

        }

        updatePhysics(frameManager: Engine.FrameManager, frameTimeInfo: Engine.FrameTimeInfo): void {
            this.position += this.direction * frameTimeInfo.getPhysicsStep();
            if (this.position <= 0.0 || this.position >= 1.0) {
                frameManager.popState();
            } else {
                this.back.Alpha = 1.0 - this.position;
            }
            if (this.firstFrame) {
                this.drawState.updatePhysics(frameManager, frameTimeInfo);
                this.firstFrame = false;
            }
        }

        drawFrame2D(gl: WebGLRenderingContext, canvas: HTMLCanvasElement, frameManager: Engine.FrameManager, frameTimeInfo: Engine.FrameTimeInfo, cam: Engine.CameraState): void {
            this.drawState.drawFrame2D(gl, canvas, frameManager, frameTimeInfo, cam);
            this.back.draw();
        }
    }
}


text:
<!DOCTYPE html>

    <title>Angular Directive for LinkedIn Sign In</title>


text:
#ifndef _GL_DECODER_CONTEXT_DATA_H_
#define _GL_DECODER_CONTEXT_DATA_H_

#include <assert.h>
#include <string.h>
#include "FixedBuffer.h"
#include "codec_defs.h"

class  GLDecoderContextData {
public:
    typedef enum  {
        VERTEX_LOCATION = 0,
        NORMAL_LOCATION = 1,
        COLOR_LOCATION = 2,
        POINTSIZE_LOCATION = 3,
        TEXCOORD0_LOCATION = 4,
        TEXCOORD1_LOCATION = 5,
        TEXCOORD2_LOCATION = 6,
        TEXCOORD3_LOCATION = 7,
        TEXCOORD4_LOCATION = 8,
        TEXCOORD5_LOCATION = 9,
        TEXCOORD6_LOCATION = 10,
        TEXCOORD7_LOCATION = 11,
        MATRIXINDEX_LOCATION = 12,
        WEIGHT_LOCATION = 13,
        LAST_LOCATION = 14
    } PointerDataLocation;

    GLDecoderContextData(int nLocations = CODEC_MAX_VERTEX_ATTRIBUTES) :
        m_nLocations(nLocations)
    {
        m_pointerData = new FixedBuffer[m_nLocations];
    }

    ~GLDecoderContextData() {
        delete [] m_pointerData;
    }

    void storePointerData(unsigned int loc, void *data, size_t len) {

        assert(loc < m_nLocations);
        m_pointerData[loc].alloc(len);
        memcpy(m_pointerData[loc].ptr(), data, len);
    }
    void *pointerData(unsigned int loc) {
        assert(loc < m_nLocations);
        return m_pointerData[loc].ptr();
    }
private:
    FixedBuffer *m_pointerData;
    int m_nLocations;
};

#endif


text:
require 'selenium-webdriver'
require 'rspec'
require 'cucumber'

require File.dirname(__FILE__) + "/../lib/pages"


text:
package org.statefulj.fsm;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.statefulj.fsm.model.Action;
import org.statefulj.fsm.model.State;
import org.statefulj.fsm.model.StateActionPair;
import org.statefulj.fsm.model.Transition;
import org.statefulj.fsm.model.impl.DeterministicTransitionImpl;
import org.statefulj.fsm.model.impl.StateImpl;
import org.statefulj.persistence.memory.MemoryPersisterImpl;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * The FSM is responsible for the processing the event with the current State and persisting
 * the State with the composite Persister
 *
 * @author Andrew Hall
 *
 */
public class FSM<T> {

	private static final Logger logger = LoggerFactory.getLogger(FSM.class);

	private static final int DEFAULT_RETRIES = 20;
	private static final int DEFAULT_RETRY_INTERVAL = 250;  // 250 ms

	private int retryAttempts = DEFAULT_RETRIES;
	private int retryInterval = DEFAULT_RETRY_INTERVAL;

	private Persister<T> persister;
	private String name = "FSM";

	/**
	 * FSM Constructor with the name of the FSM
	 *
	 * @param name Name associated with the FSM
	 */
	public FSM(String name) {
		this.name = name;
	}

	/**
	 * FSM Constructor with the Persister responsible for setting the State on the Entity
	 *
	 * @param persister Persister responsible for setting the State on the Entity
	 */
	public FSM(Persister<T> persister) {
		this.persister = persister;
	}

	/**
	 * FSM Constructor with the name of the FSM and Persister responsible for setting the State on the Entity
	 *
	 * @param name Name associated with the FSM
	 * @param persister Persister responsible for setting the State on the Entity
	 */
	public FSM(String name, Persister<T> persister) {
		this.name = name;
		this.persister = persister;
	}

	/**
	 * FSM Constructor
	 *
	 * @param name Name associated with the FSM
	 * @param persister Persister responsible for setting the State on the Entity
	 * @param retryAttempts Number of Retry Attempts.  A value of -1 indicates unlimited Attempts
	 * @param retryInterval Time between Retry Attempts in milliseconds
	 */
	public FSM(String name, Persister<T> persister, int retryAttempts, int retryInterval) {
		this.name = name;
		this.persister = persister;
		this.retryAttempts = retryAttempts;
		this.retryInterval = retryInterval;
	}

	/**
	 * Process event.  Will handle all retry attempts.  If attempts exceed maximum retries,
	 * it will throw a TooBusyException.
	 *
	 * @param stateful The Stateful Entity
	 * @param event The Event
	 * @param args Optional parameters to pass into the Action
	 * @return The current State
	 * @throws TooBusyException Exception indicating that we've exceeded the number of RetryAttempts
	 */
	public State<T> onEvent(T stateful, String event, Object ... args) throws TooBusyException {

		int attempts = 0;

		while(this.retryAttempts == -1 || attempts < this.retryAttempts) {
			try {
				State<T> current = this.getCurrentState(stateful);

				// Fetch the transition for this event from the current state
				//
				Transition<T> transition = this.getTransition(event, current);

				// Is there one?
				//
				if (transition != null) {
					current = this.transition(stateful, current, event, transition, args);
				} else {

					if (logger.isDebugEnabled())
                        logger.debug("{}({})::{}({})->{}/noop",
                                this.name,
                                stateful.getClass().getSimpleName(),
                                current.getName(),
                                event,
                                current.getName());

					// If blocking, force a transition to the current state as
					// it's possible that another thread has moved out of the blocking state.
					// Either way, we'll retry this event
					//
					if (current.isBlocking()) {
						this.setCurrent(stateful, current, current);
						throw new WaitAndRetryException(this.retryInterval);
					}
				}

				return current;

			} catch(RetryException re) {

				logger.warn("{}({})::Retrying event", this.name, stateful);

				// Wait?
				//
				if (WaitAndRetryException.class.isInstance(re)) {
					try {
						Thread.sleep(((WaitAndRetryException)re).getWait());
					} catch(InterruptedException ie) {
						throw new RuntimeException(ie);
					}
				}
				attempts++;
			}
		}
		logger.error("{}({})::Unable to process event", this.name, stateful);
		throw new TooBusyException();
	}

	public int getRetryAttempts() {
		return retryAttempts;
	}

	public void setRetryAttempts(int retries) {
		this.retryAttempts = retries;
	}

	public int getRetryInterval() {
		return retryInterval;
	}

	public void setRetryInterval(int retryInterval) {
		this.retryInterval = retryInterval;
	}

	public Persister<T> getPersister() {
		return persister;
	}

	public void setPersister(Persister<T> persister) {
		this.persister = persister;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public State<T> getCurrentState(T obj) {
		return this.persister.getCurrent(obj);
	}

	/**
	 * Fluid FSM builder
	 *
	 * @author Andrew Hall
	 *
	 * @param <T> Type of the Stateful Entity
	 */
	public static class FSMBuilder<T> {

		/**
		 * Fluid State Builder
		 *
		 * @author Andrew Hall
		 *
		 * @param <T> Type of the Stateful Entity
		 */
		public static class StateBuilder<T> {

			/**
			 * Fluid Transition Builder
			 *
			 * @author Andrew Hall
			 *
			 * @param <T> Type of the Stateful Entity
			 */
			public static class TransitionBuilder<T> {

				private StateBuilder<T> stateBuilder;
				private String event;
				private String toStateName;
				private State<T> toState;
				private Action<T> action;

				private TransitionBuilder(String event, StateBuilder<T> stateBuilder) {
					this.event = event;
					this.stateBuilder = stateBuilder;
					this.toStateName = null;
					this.action = null;
				}

				private TransitionBuilder(String event, String toStateKey) {
					this(event, toStateKey, null);
				}

				private TransitionBuilder(String event, String toStateKey, Action<T> action) {
					if (event == null || event.trim().equals("")) {
						throw new RuntimeException("You must provide an Event");
					}
					this.event = event;
					this.toStateName = toStateKey;
					this.toState = null;
					this.action = action;
				}

				private TransitionBuilder(String event, State<T> toState, Action<T> action) {
					if (event == null || event.trim().equals("")) {
						throw new RuntimeException("You must provide an Event");
					}
					this.event = event;
					this.toState = toState;
					this.action = action;
				}

				/**
				 * Set the "To" State using the specified State Name
				 * @param toStateName Name of the State
				 * @return TransitionBuilder
				 */
				public TransitionBuilder<T> setToState(String toStateName) {
					this.toStateName = toStateName;
					return this;
				}

				/**
				 * Set the "To" State to the specified State.  If both the "To" State is
				 * set using the name of the State and the State object, the State object
				 * will take precedence
				 * @param toState To State object
				 * @return TransitionBuilder
				 */
				public TransitionBuilder<T> setToState(State<T> toState) {
					this.toState = toState;
					return this;
				}

				/**
				 * Set the Action for this Transition
				 *
				 * @param action
				 * @return TransitionBuilder
				 */
				public TransitionBuilder<T> setAction(Action<T> action) {
					this.action = action;
					return this;
				}

				/**
				 * Completes the setup for this Transition Builder
				 *
				 * @return StateBuilder
				 */
				public StateBuilder<T> done() {
					return this.stateBuilder;
				}

				private Transition<T> build(State<T> from, Map<String, State<T>> states) {
					State<T> to = (this.toState != null)
							? this.toState
							: (this.toStateName != null)
								? states.get(this.toStateName)
								: from;
					return new DeterministicTransitionImpl<T>(from, to, this.event, this.action);
				}

			}

			private String stateName;
			private Map<String, Transition<T>> transistions = new HashMap<String, Transition<T>>();
			private List<TransitionBuilder<T>> transistionBuilders = new LinkedList<TransitionBuilder<T>>();
			private boolean isEndState = false;
			private boolean isBlocking = false;
			private State<T> state;

			private FSMBuilder<T> fsmBuilder;

			private StateBuilder(FSMBuilder<T> fsmBuilder, String stateName) {
				if (stateName == null || stateName.trim().equals("")) {
					throw new RuntimeException("You must provide a State name");
				}
				this.fsmBuilder = fsmBuilder;
				this.stateName = stateName;
			}

			/**
			 * Set whether this State is the End State
			 * @param isEndState
			 * @return StateBuilder
			 */
			public StateBuilder<T> setEndState(boolean isEndState) {
				this.isEndState = isEndState;
				return this;
			}

			/**
			 * Set whether this State is a blocking State
			 * @param isBlocking
			 * @return StateBuilder
			 */
			public StateBuilder<T> setBlockingState(boolean isBlocking) {
				this.isBlocking = isBlocking;
				return this;
			}

			/**
			 * Add a Transition with no Action.
			 * @param event Event that triggers the Transition
			 * @param toState The name of the State in which to transition to
			 * @return StateBuilder
			 */
			public StateBuilder<T> addTransition(String event, String toState) {
				this.transistionBuilders.add(new TransitionBuilder<T>(event, toState));
				return this;
			}

			/**
			 * Add a Transition with no Action.
			 * @param event Event that triggers the Transition
			 * @param toState The State in which to transition to
			 * @return StateBuilder
			 */
			public StateBuilder<T> addTransition(String event, State<T> toState) {
				return this.addTransition(event, toState, null);
			}

			/**
			 * Add a Transition with an Action
			 * @param event Event that triggers the Transition
			 * @param toState The name of the State in which to transition to
			 * @param action The Action to invoke
			 * @return StateBuilder
			 */
			public StateBuilder<T> addTransition(String event, String toState, Action<T> action) {
				this.transistionBuilders.add(new TransitionBuilder<T>(event, toState, action));
				return this;
			}

			/**
			 * Add a Transition with an Action
			 * @param event Event that triggers the Transition
			 * @param toState The State in which to transition to
			 * @param action The Action to invoke
			 * @return StateBuilder
			 */
			public StateBuilder<T> addTransition(String event, State<T> toState, Action<T> action) {
				this.fsmBuilder.addState(toState);
				this.transistionBuilders.add(new TransitionBuilder<T>(event, toState, action));
				return this;
			}

			/**
			 * Add a Transition with no State change but with an Action
			 * @param event Event that triggers the Transition
			 * @param action The Action to invoke
			 * @return StateBuilder
			 */
			public StateBuilder<T> addTransition(String event, Action<T> action) {
				return this.addTransition(event, this.stateName, action);
			}

			/**
			 * Add an instantiated Transition
			 * @param event Event that triggers the Transition
			 * @return StateBuilder
			 */
			public StateBuilder<T> addTransition(String event, Transition<T> transition) {
				this.transistions.put(event, transition);
				return this;
			}

			/**
			 * Begin building a Transition
			 * @param event Event that triggers the Transition
			 * @return StateBuilder
			 */
			public TransitionBuilder<T> buildTransition(String event) {
				TransitionBuilder<T> transitionBuilder = new TransitionBuilder<T>(event, this);
				this.transistionBuilders.add(transitionBuilder);
				return transitionBuilder;
			}

			/**
			 * Completes the setup for this State Builder
			 * @return FSMBuilder
			 */
			public FSMBuilder<T> done() {
				return this.fsmBuilder;
			}

			private State<T> buildState() {
				this.state = new StateImpl<T>(this.stateName, this.transistions, this.isEndState, this.isBlocking);
				return this.state;
			}

			private void buildTransitions(Map<String, State<T>> states) {
				for(TransitionBuilder<T> transitionBuilder : this.transistionBuilders) {
					transitionBuilder.build(this.state, states);
				}
			}

		}

		private int retryAttempts = DEFAULT_RETRIES;
		private int retryInterval = DEFAULT_RETRY_INTERVAL;

		private Persister<T> persister;
		private String name = "FSM";

		private HashMap<String, State<T>> states = new HashMap<String, State<T>>();
		private List<StateBuilder<T>> stateBuilders = new LinkedList<StateBuilder<T>>();
		private String startState;

		/**
		 * Build a new FSM Builder
		 * @param clazz Parameterized Class for the FSM
		 * @return FSMBuilder
		 */
		public static <T> FSMBuilder<T> newBuilder(Class<T> clazz) {
			return new FSMBuilder<T>();
		}

		/**
		 * Set the Persister for the FSM.  If not specified, a MemoryPersister will be
		 * instantiated with persists the state only on the Stateful object
		 * @param persister The Persister
		 * @return FSMBuilder
		 */
		public FSMBuilder<T> setPerister(Persister<T> persister) {
			this.persister = persister;
			return this;
		}

		/**
		 * Sets the name of the FSM
		 * @param name Name of the FSM
		 * @return FSMBuilder
		 */
		public FSMBuilder<T> setName(String name) {
			this.name = name;
			return this;
		}

		/**
		 * Sets the number of retry attempts for the FSM
		 * @param retryAttempts
		 * @return FSMBuilder
		 */
		public FSMBuilder<T> setRetryAttempts(int retryAttempts) {
			this.retryAttempts = retryAttempts;
			return this;
		}

		/**
		 * Sets the retry interval for the FSM
		 * @param retryInterval
		 * @return FSMBuilder
		 */
		public FSMBuilder<T> setRetryInterval(int retryInterval) {
			this.retryInterval = retryInterval;
			return this;
		}

		/**
		 * Add a specified State
		 * @param state State to add
		 * @return FSMBuilder
		 */
		public FSMBuilder<T> addState(State<T> state) {
			return this.addState(state, false);
		}

		/**
		 * Add a specified State and state whether or not it's the Start State for the FSM.
		 * If no State is explicitly set as the Start State, then the first State added will
		 * be the Start State
		 *
		 * @param state State to add
		 * @param isStartState Whether or not the State is specified as the Start State
		 * @return FSMBuilder
		 */
		public FSMBuilder<T> addState(State<T> state, boolean isStartState) {
			this.startState = (this.startState == null || isStartState) ? state.getName() : this.startState;
			this.states.put(state.getName(), state);
			return this;
		}

		/**
		 * Begin building a State for the FSM
		 *
		 * @param name Name of the State
		 * @return StateBuilder
		 */
		public StateBuilder<T> buildState(String name) {
			return this.buildState(name, false);
		}

		/**
		 * Begin building a State for the FSM and state whether or not it's the Start State for the FSM.
		 * If no State is explicitly set as the Start State, then the first State added will
		 * be the Start State
		 *
		 * @param name Name of the State
		 * @param isStartState Whether or not the State is specified as the Start State
		 * @return StateBuilder
		 */
		public StateBuilder<T> buildState(String name, boolean isStartState) {
			this.startState = (this.startState == null || isStartState) ? name : this.startState;
			StateBuilder<T> stateBuilder = new StateBuilder<T>(this, name);
			this.stateBuilders.add(stateBuilder);
			return stateBuilder;
		}

		/**
		 * Build the FSM and all of it's States and Transitions
		 * @return FSM
		 */
		public FSM<T> build() {

			for(StateBuilder<T> stateBuilder : this.stateBuilders) {
				State<T> state = stateBuilder.buildState();
				this.states.put(state.getName(), state);
			}

			for(StateBuilder<T> stateBuilder : this.stateBuilders) {
				stateBuilder.buildTransitions(this.states);
			}

			State<T> startState = this.states.get(this.startState);
			if (startState == null) {
				throw new RuntimeException("No start state defined, state=" + this.startState);
			}

			if (this.persister == null) {
				this.persister = new MemoryPersisterImpl<T>();
			}
			this.persister.setStates(this.states.values());
			this.persister.setStartState(startState);

			return new FSM<T>(this.name, this.persister, this.retryAttempts, this.retryInterval);
		}
	}

	protected Transition<T> getTransition(String event, State<T> current) {
		return current.getTransition(event);
	}

	protected State<T> transition(T stateful, State<T> current, String event, Transition<T> transition, Object... args) throws RetryException {
		StateActionPair<T> pair = transition.getStateActionPair(stateful, event, args);
		setCurrent(stateful, current, pair.getState());
		executeAction(
				pair.getAction(),
				stateful,
				event,
				current.getName(),
				pair.getState().getName(),
				args);
		return getCurrentState(stateful); // Refetch as the action may have changed the state
	}

	protected void setCurrent(T stateful, State<T> current, State<T> next) throws StaleStateException {
		persister.setCurrent(stateful, current, next);
	}

	protected void executeAction(
			Action<T> action,
			T stateful,
			String event,
			String from,
			String to,
			Object... args) throws RetryException {

        if (logger.isDebugEnabled())
            logger.debug("{}({})::{}({})->{}/{}",
                    this.name,
                    stateful.getClass().getSimpleName(),
                    from,
                    event,
                    to,
                    (action == null) ? "noop" : action.toString());

		if (action != null) {
			action.execute(stateful, event, args);
		}
	}
}


text:
/**
 * Generates a browser-specific Flash tag. Create a new instance, set whatever
 * properties you need, then call either toString() to get the tag as a string, or
 * call write() to write the tag out.
 */

/**
 * Creates a new instance of the FlashTag.
 * src: The path to the SWF file.
 * width: The width of your Flash content.
 * height: the height of your Flash content.
 */
function FlashTag(src, width, height)
{
    this.src       = src;
    this.width     = width;
    this.height    = height;
    this.version   = '7,0,14,0';
    this.id        = null;
    this.bgcolor   = 'ffffff';
    this.flashVars = null;
}

/**
 * Sets the Flash version used in the Flash tag.
 */
FlashTag.prototype.setVersion = function(v)
{
    this.version = v;
}

/**
 * Sets the ID used in the Flash tag.
 */
FlashTag.prototype.setId = function(id)
{
    this.id = id;
}

/**
 * Sets the background color used in the Flash tag.
 */
FlashTag.prototype.setBgcolor = function(bgc)
{
    this.bgcolor = bgc;
}

/**
 * Sets any variables to be passed into the Flash content.
 */
FlashTag.prototype.setFlashvars = function(fv)
{
    this.flashVars = fv;
}

/**
 * Get the Flash tag as a string.
 */
FlashTag.prototype.toString = function()
{
    var ie = (navigator.appName.indexOf ("Microsoft") != -1) ? 1 : 0;
    var flashTag = new String();
    if (ie)
    {
        flashTag += '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" ';
        if (this.id != null)
        {
            flashTag += 'id="'+this.id+'" ';
        }
        flashTag += 'codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version='+this.version+'" ';
        flashTag += 'width="'+this.width+'" ';
        flashTag += 'height="'+this.height+'">';
        flashTag += '<param name="movie" value="'+this.src+'"/>';
        flashTag += '<param name="quality" value="high"/>';
        flashTag += '<param name="bgcolor" value="#'+this.bgcolor+'"/>';
        if (this.flashVars != null)
        {
            flashTag += '<param name="flashvars" value="'+this.flashVars+'"/>';
        }
        flashTag += '</object>';
    }
    else
    {
        flashTag += '<embed src="'+this.src+'" ';
        flashTag += 'quality="high" ';
        flashTag += 'bgcolor="#'+this.bgcolor+'" ';
        flashTag += 'width="'+this.width+'" ';
        flashTag += 'height="'+this.height+'" ';
        flashTag += 'type="application/x-shockwave-flash" ';
        if (this.flashVars != null)
        {
            flashTag += 'flashvars="'+this.flashVars+'" ';
        }
        if (this.id != null)
        {
            flashTag += 'name="'+this.id+'" ';
        }
        flashTag += 'pluginspage="http://www.macromedia.com/go/getflashplayer">';
        flashTag += '</embed>';
    }
    return flashTag;
}

/**
 * Write the Flash tag out. Pass in a reference to the document to write to.
 */
FlashTag.prototype.write = function(doc)
{
    doc.write(this.toString());
}


text:
<Type Name="CGDataProvider" FullName="MonoMac.CoreGraphics.CGDataProvider">
  <TypeSignature Language="C#" Value="public class CGDataProvider : IDisposable, MonoMac.ObjCRuntime.INativeObject" />
  <TypeSignature Language="ILAsm" Value=".class public auto ansi beforefieldinit CGDataProvider extends System.Object implements class MonoMac.ObjCRuntime.INativeObject, class System.IDisposable" />
  <AssemblyInfo>
    <AssemblyName>MonoMac</AssemblyName>
    <AssemblyVersion>0.0.0.0</AssemblyVersion>
  </AssemblyInfo>
  <Base>
    <BaseTypeName>System.Object</BaseTypeName>
  </Base>
  <Interfaces>
    <Interface>
      <InterfaceName>MonoMac.ObjCRuntime.INativeObject</InterfaceName>
    </Interface>
    <Interface>
      <InterfaceName>System.IDisposable</InterfaceName>
    </Interface>
  </Interfaces>
  <Docs>
    A class that wraps a data source and exposes it to the CGImage class.
    <remarks />
  </Docs>
  <Members>
    <Member MemberName=".ctor">
      <MemberSignature Language="C#" Value="public CGDataProvider (IntPtr handle);" />
      <MemberSignature Language="ILAsm" Value=".method public hidebysig specialname rtspecialname instance void .ctor(native int handle) cil managed" />
      <MemberType>Constructor</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>0.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <Parameters>
        <Parameter Name="handle" Type="System.IntPtr" />
      </Parameters>
      <Docs>
        <param name="handle">To be added.</param>
        To be added.
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName=".ctor">
      <MemberSignature Language="C#" Value="public CGDataProvider (string file);" />
      <MemberSignature Language="ILAsm" Value=".method public hidebysig specialname rtspecialname instance void .ctor(string file) cil managed" />
      <MemberType>Constructor</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>0.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <Parameters>
        <Parameter Name="file" Type="System.String" />
      </Parameters>
      <Docs>
        <param name="file">The file to load data from.</param>
        Exposes the contents of the file as a CGDataProvider.
        <remarks>
        </remarks>
      </Docs>
    </Member>
    <Member MemberName=".ctor">
      <MemberSignature Language="C#" Value="public CGDataProvider (IntPtr memoryBlock, int size);" />
      <MemberSignature Language="ILAsm" Value=".method public hidebysig specialname rtspecialname instance void .ctor(native int memoryBlock, int32 size) cil managed" />
      <MemberType>Constructor</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>0.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <Parameters>
        <Parameter Name="memoryBlock" Type="System.IntPtr" />
        <Parameter Name="size" Type="System.Int32" />
      </Parameters>
      <Docs>
        <param name="memoryBlock">Pointer to the memory block.</param>
        <param name="size">Size of the block.</param>
        Creates a CGDataProvider from an in-memory block.
        <remarks />
      </Docs>
    </Member>
    <Member MemberName=".ctor">
      <MemberSignature Language="C#" Value="public CGDataProvider (byte[] buffer, int offset, int count);" />
      <MemberSignature Language="ILAsm" Value=".method public hidebysig specialname rtspecialname instance void .ctor(unsigned int8[] buffer, int32 offset, int32 count) cil managed" />
      <MemberType>Constructor</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>0.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <Parameters>
        <Parameter Name="buffer" Type="System.Byte[]" />
        <Parameter Name="offset" Type="System.Int32" />
        <Parameter Name="count" Type="System.Int32" />
      </Parameters>
      <Docs>
        <param name="buffer">A block of bytes that contains the data to be provided.</param>
        <param name="offset">Offset into the block that is considered part of the data to be provided.</param>
        <param name="count">The number of bytes to consume from the offset start from the block.</param>
        Creates a CGDataProvider that exposes the byte array starting at the specified offset for the specified amount of bytes.   This is merely a wrapper around
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName=".ctor">
      <MemberSignature Language="C#" Value="public CGDataProvider (IntPtr memoryBlock, int size, bool ownBuffer);" />
      <MemberSignature Language="ILAsm" Value=".method public hidebysig specialname rtspecialname instance void .ctor(native int memoryBlock, int32 size, bool ownBuffer) cil managed" />
      <MemberType>Constructor</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>0.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <Parameters>
        <Parameter Name="memoryBlock" Type="System.IntPtr" />
        <Parameter Name="size" Type="System.Int32" />
        <Parameter Name="ownBuffer" Type="System.Boolean" />
      </Parameters>
      <Docs>
        <param name="memoryBlock">Pointer to the memory block.</param>
        <param name="size">Size of the block.</param>
        <param name="ownBuffer">If true this means that the CGDataProvider owns the buffer and will call FreeHGlobal when it is disposed, otherwise it is assumed that the block is owned by another object.</param>
        Creates a CGDataProvider from an in-memory block.
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="CopyData">
      <MemberSignature Language="C#" Value="public MonoMac.Foundation.NSData CopyData ();" />
      <MemberSignature Language="ILAsm" Value=".method public hidebysig instance class MonoMac.Foundation.NSData CopyData() cil managed" />
      <MemberType>Method</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>0.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>MonoMac.Foundation.NSData</ReturnType>
      </ReturnValue>
      <Parameters />
      <Docs>
        To be added.
        <returns>To be added.</returns>
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="Dispose">
      <MemberSignature Language="C#" Value="public void Dispose ();" />
      <MemberSignature Language="ILAsm" Value=".method public hidebysig newslot virtual instance void Dispose() cil managed" />
      <MemberType>Method</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>0.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>System.Void</ReturnType>
      </ReturnValue>
      <Parameters />
      <Docs>
        Releases the resources used by the CGDataProvider object.
        <remarks>
          <para>The Dispose method releases the resources used by the CGDataProvider class.</para>
          <para>Calling the Dispose method when you are finished using the CGDataProvider ensures that all external resources used by this managed object are released as soon as possible.  Once you have invoked the Dispose method, the object is no longer useful and you should no longer make any calls to it.  For more information on releasing resources see ``Cleaning up Unmananaged Resources'' at http://msdn.microsoft.com/en-us/library/498928w2.aspx</para>
        </remarks>
      </Docs>
    </Member>
    <Member MemberName="Dispose">
      <MemberSignature Language="C#" Value="protected virtual void Dispose (bool disposing);" />
      <MemberSignature Language="ILAsm" Value=".method familyhidebysig newslot virtual instance void Dispose(bool disposing) cil managed" />
      <MemberType>Method</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>0.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>System.Void</ReturnType>
      </ReturnValue>
      <Parameters>
        <Parameter Name="disposing" Type="System.Boolean" />
      </Parameters>
      <Docs>
        <param name="disposing">
          <para>If set to <see langword="true" />, the method is invoked directly and will dispose manage and unmanaged resources;   If set to <see langword="false" /> the method is being called by the garbage collector finalizer and should only release unmanaged resources.</para>
        </param>
        Releases the resources used by the CGDataProvider object.
        <remarks>
          <para>This Dispose method releases the resources used by the CGDataProvider class.</para>
          <para>This method is called by both the Dispose() method and the object finalizer (Finalize).    When invoked by the Dispose method, the parameter disposting <paramref name="disposing" /> is set to <see langword="true" /> and any managed object references that this object holds are also disposed or released;  when invoked by the object finalizer, on the finalizer thread the value is set to <see langword="false" />. </para>
          <para>Calling the Dispose method when you are finished using the CGDataProvider ensures that all external resources used by this managed object are released as soon as possible.  Once you have invoked the Dispose method, the object is no longer useful and you should no longer make any calls to it.</para>
          <para>  For more information on how to override this method and on the Dispose/IDisposable pattern, read the ``Implementing a Dispose Method'' document at http://msdn.microsoft.com/en-us/library/fs2xkftw.aspx</para>
        </remarks>
      </Docs>
    </Member>
    <Member MemberName="Finalize">
      <MemberSignature Language="C#" Value="~CGDataProvider ();" />
      <MemberSignature Language="ILAsm" Value=".method familyhidebysig virtual instance void Finalize() cil managed" />
      <MemberType>Method</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>0.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>System.Void</ReturnType>
      </ReturnValue>
      <Parameters />
      <Docs>
        Finalizer for the CGDataProvider object
        <remarks>
        </remarks>
      </Docs>
    </Member>
    <Member MemberName="FromFile">
      <MemberSignature Language="C#" Value="public static MonoMac.CoreGraphics.CGDataProvider FromFile (string file);" />
      <MemberSignature Language="ILAsm" Value=".method public static hidebysig class MonoMac.CoreGraphics.CGDataProvider FromFile(string file) cil managed" />
      <MemberType>Method</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>0.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>MonoMac.CoreGraphics.CGDataProvider</ReturnType>
      </ReturnValue>
      <Parameters>
        <Parameter Name="file" Type="System.String" />
      </Parameters>
      <Docs>
        <param name="file">File name.</param>
        Creates a CGDataProvider from an on-disk file.
        <returns>An initialized CGDataProvider.</returns>
        <remarks />
      </Docs>
    </Member>
    <Member MemberName="Handle">
      <MemberSignature Language="C#" Value="public IntPtr Handle { get; }" />
      <MemberSignature Language="ILAsm" Value=".property instance native int Handle" />
      <MemberType>Property</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>0.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>System.IntPtr</ReturnType>
      </ReturnValue>
      <Docs>
        Handle (pointer) to the unmanaged object representation.
        <value>A pointer</value>
        <remarks>This IntPtr is a handle to the underlying unmanaged representation for this object.</remarks>
      </Docs>
    </Member>
  </Members>
</Type>