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

using System;

namespace Realms.Sync.ErrorHandling
{
    /// <summary>
    /// A client reset strategy where all the not yet synchronized data is automatically discarded and a fresh copy of the synchronized Realm is obtained.
    /// </summary>
    /// <remarks>
    /// The freshly downloaded copy of the synchronized Realm triggers all change notifications as a write transaction is internally simulated.
    /// This strategy supplies three callbacks: <see cref="OnBeforeReset"/>, <see cref="OnAfterReset"/>, and <see cref="ManualResetFallback"/>.
    /// The first two are invoked just before and after the client reset has happened,
    /// while the last one will be invoked in case an error occurs during the automated process and the system needs to fallback to a manual mode.
    /// The overall recommendation for using this strategy is that using the three available callbacks should only be considered when:
    /// 1. the user needs to be notified (in <see cref="OnBeforeReset"/>) of an incoming potential data loss of unsynced data
    /// 2. the user needs to be notified (in <see cref="OnAfterReset"/>) that the reset process has completed
    /// 3. advanced use cases for data-sensitive applications where the developer wants to recover in the most appropriate way the unsynced data
    /// 4. backup the whole realm before the client reset happens (in <see cref="OnBeforeReset"/>). Such backup could, for example, be used to restore the unsynced data (see 3.)
    /// </remarks>
    /// <seealso href="https://docs.mongodb.com/realm/sdk/dotnet/advanced-guides/client-reset/">Client Resets - .NET SDK</seealso>
    public sealed class DiscardUnsyncedChangesHandler : ClientResetHandlerBase
    {
        /// <summary>
        /// Gets or sets the callback that indicates a Client Reset is about to happen.
        /// </summary>
        /// <value>Callback invoked right before a Client Reset.</value>
        public BeforeResetCallback OnBeforeReset { get; set; }

        /// <summary>
        /// Gets or sets the callback that indicates a Client Reset just happened.
        /// </summary>
        /// <value>Callback invoked right after a Client Reset.</value>
        public AfterResetCallback OnAfterReset { get; set; }

        internal override ClientResyncMode ClientResetMode => ClientResyncMode.Discard;

        /// <summary>
        /// Gets or sets the callback triggered when an error has occurred that makes the operation unable to complete, for example in the case of a destructive schema change.
        /// </summary>
        /// <value>Callback invoked if automatic Client Reset handling fails.</value>
        public ClientResetCallback ManualResetFallback
        {
            get => ManualClientReset;
            set => ManualClientReset = value;
        }
    }

#pragma warning disable SA1402 // This type is now obsolete and will be deleted in the next major version

    /// <summary>
    /// A client reset strategy where all the not yet synchronized data is automatically discarded and a fresh copy of the synchronized Realm is obtained.
    /// </summary>
    /// <remarks>
    /// The freshly downloaded copy of the synchronized Realm triggers all change notifications as a write transaction is internally simulated.
    /// This strategy supplies three callbacks: <see cref="OnBeforeReset"/>, <see cref="OnAfterReset"/>, and <see cref="ManualResetFallback"/>.
    /// The first two are invoked just before and after the client reset has happened,
    /// while the last one will be invoked in case an error occurs during the automated process and the system needs to fallback to a manual mode.
    /// The overall recommendation for using this strategy is that using the three available callbacks should only be considered when:
    /// 1. the user needs to be notified (in <see cref="OnBeforeReset"/>) of an incoming potential data loss of unsynced data
    /// 2. the user needs to be notified (in <see cref="OnAfterReset"/>) that the reset process has completed
    /// 3. advanced use cases for data-sensitive applications where the developer wants to recover in the most appropriate way the unsynced data
    /// 4. backup the whole realm before the client reset happens (in <see cref="OnBeforeReset"/>). Such backup could, for example, be used to restore the unsynced data (see 3.)
    /// </remarks>
    /// <seealso href="https://docs.mongodb.com/realm/sdk/dotnet/advanced-guides/client-reset/">Client Resets - .NET SDK</seealso>
    [Obsolete("Use DiscardUnsyncedChangesHandler instead.")]
    public sealed class DiscardLocalResetHandler : ClientResetHandlerBase
    {
        /// <summary>
        /// Gets or sets the callback that indicates a Client Reset is about to happen.
        /// </summary>
        /// <value>Callback invoked right before a Client Reset.</value>
        public BeforeResetCallback OnBeforeReset { get; set; }

        /// <summary>
        /// Gets or sets the callback that indicates a Client Reset just happened.
        /// </summary>
        /// <value>Callback invoked right after a Client Reset.</value>
        public AfterResetCallback OnAfterReset { get; set; }

        internal override ClientResyncMode ClientResetMode => ClientResyncMode.Discard;

        /// <summary>
        /// Gets or sets the callback triggered when an error has occurred that makes the operation unable to complete, for example in the case of a destructive schema change.
        /// </summary>
        /// <value>Callback invoked if automatic Client Reset handling fails.</value>
        public ClientResetCallback ManualResetFallback
        {
            get => ManualClientReset;
            set => ManualClientReset = value;
        }
    }
#pragma warning restore SA1402 // This type is now obsolete and will be deleted in the next major version

}


text:
"""
A :term:`LDAP Server Definition` resource represents a definition that contains
information about an LDAP server that may be used for HMC user authentication
purposes.
"""

from __future__ import absolute_import

import copy

from ._manager import BaseManager
from ._resource import BaseResource
from ._logging import logged_api_call
from ._utils import matches_filters, divide_filter_args, \
    RC_LDAP_SERVER_DEFINITION

__all__ = ['LdapServerDefinitionManager', 'LdapServerDefinition']

class LdapServerDefinitionManager(BaseManager):
    """
    Manager providing access to the :term:`LDAP Server Definition` resources of
    a HMC.

    Derived from :class:`~zhmcclient.BaseManager`; see there for common methods
    and attributes.

    Objects of this class are not directly created by the user; they are
    accessible via the following instance variable of a
    :class:`~zhmcclient.Console` object:

    * :attr:`zhmcclient.Console.ldap_server_definitions`
    """

    def __init__(self, console):
        # This function should not go into the docs.
        # Parameters:
        #   console (:class:`~zhmcclient.Console`):
        #      Console object representing the HMC.

        # Resource properties that are supported as filter query parameters.
        # If the support for a resource property changes within the set of HMC
        # versions that support this type of resource, this list must be set up
        # for the version of the HMC this session is connected to.
        # Because this resource has case-insensitive names, this list must
        # contain the name property.
        query_props = [
            'name',
        ]

        super(LdapServerDefinitionManager, self).__init__(
            resource_class=LdapServerDefinition,
            class_name=RC_LDAP_SERVER_DEFINITION,
            session=console.manager.session,
            parent=console,
            base_uri='/api/console/ldap-server-definitions',
            oid_prop='element-id',
            uri_prop='element-uri',
            name_prop='name',
            query_props=query_props,
            case_insensitive_names=True)

    @property
    def console(self):
        """
        :class:`~zhmcclient.Console`: :term:`Console` defining the scope for
        this manager.
        """
        return self._parent

    @logged_api_call
    def list(self, full_properties=True, filter_args=None):
        """
        List the :term:`LDAP Server Definition` resources representing the
        definitions of LDAp servers in this HMC.

        Authorization requirements:

        * User-related-access permission to the LDAP Server Definition objects
          included in the result, or task permission to the "Manage LDAP Server
          Definitions" task.

        Parameters:

          full_properties (bool):
            Controls whether the full set of resource properties should be
            retrieved, vs. only the short set as returned by the list
            operation.

          filter_args (dict):
            Filter arguments that narrow the list of returned resources to
            those that match the specified filter arguments. For details, see
            :ref:`Filtering`.

            `None` causes no filtering to happen, i.e. all resources are
            returned.

        Returns:

          : A list of :class:`~zhmcclient.LdapServerDefinition` objects.

        Raises:

          :exc:`~zhmcclient.HTTPError`
          :exc:`~zhmcclient.ParseError`
          :exc:`~zhmcclient.AuthError`
          :exc:`~zhmcclient.ConnectionError`
        """
        resource_obj_list = []
        query_parms, client_filters = divide_filter_args(
            self._query_props, filter_args)
        resources_name = 'ldap-server-definitions'
        uri = '{}/{}{}'.format(self.console.uri, resources_name, query_parms)

        result = self.session.get(uri)
        if result:
            props_list = result[resources_name]
            for props in props_list:

                resource_obj = self.resource_class(
                    manager=self,
                    uri=props[self._uri_prop],
                    name=props.get(self._name_prop, None),
                    properties=props)

                if matches_filters(resource_obj, client_filters):
                    resource_obj_list.append(resource_obj)
                    if full_properties:
                        resource_obj.pull_full_properties()

        self._name_uri_cache.update_from(resource_obj_list)
        return resource_obj_list

    @logged_api_call
    def create(self, properties):
        """
        Create a new LDAP Server Definition in this HMC.

        Authorization requirements:

        * Task permission to the "Manage LDAP Server Definitions" task.

        Parameters:

          properties (dict): Initial property values.
            Allowable properties are defined in section 'Request body contents'
            in section 'Create LDAP Server Definition' in the :term:`HMC API`
            book.

        Returns:

          LdapServerDefinition:
            The resource object for the new LDAP Server Definition.
            The object will have its 'object-uri' property set as returned by
            the HMC, and will also have the input properties set.

        Raises:

          :exc:`~zhmcclient.HTTPError`
          :exc:`~zhmcclient.ParseError`
          :exc:`~zhmcclient.AuthError`
          :exc:`~zhmcclient.ConnectionError`
        """
        result = self.session.post(
            self.console.uri + '/ldap-server-definitions', body=properties)
        # There should not be overlaps, but just in case there are, the
        # returned props should overwrite the input props:
        props = copy.deepcopy(properties)
        props.update(result)
        name = props.get(self._name_prop, None)
        uri = props[self._uri_prop]
        ldap_server_definition = LdapServerDefinition(self, uri, name, props)
        self._name_uri_cache.update(name, uri)
        return ldap_server_definition

class LdapServerDefinition(BaseResource):
    """
    Representation of a :term:`LDAP Server Definition`.

    Derived from :class:`~zhmcclient.BaseResource`; see there for common
    methods and attributes.

    Objects of this class are not directly created by the user; they are
    returned from creation or list functions on their manager object
    (in this case, :class:`~zhmcclient.LdapServerDefinitionManager`).
    """

    def __init__(self, manager, uri, name=None, properties=None):
        # This function should not go into the docs.
        #   manager (:class:`~zhmcclient.LdapServerDefinitionManager`):
        #     Manager object for this resource object.
        #   uri (string):
        #     Canonical URI path of the resource.
        #   name (string):
        #     Name of the resource.
        #   properties (dict):
        #     Properties to be set for this resource object. May be `None` or
        #     empty.
        assert isinstance(manager, LdapServerDefinitionManager), \
            "Console init: Expected manager type %s, got %s" % \
            (LdapServerDefinitionManager, type(manager))
        super(LdapServerDefinition, self).__init__(
            manager, uri, name, properties)

    @logged_api_call
    def delete(self):
        """
        Delete this LDAP Server Definition.

        Authorization requirements:

        * Task permission to the "Manage LDAP Server Definitions" task.

        Raises:

          :exc:`~zhmcclient.HTTPError`
          :exc:`~zhmcclient.ParseError`
          :exc:`~zhmcclient.AuthError`
          :exc:`~zhmcclient.ConnectionError`
        """
        # pylint: disable=protected-access
        self.manager.session.delete(self.uri)
        self.manager._name_uri_cache.delete(
            self.get_properties_local(self.manager._name_prop, None))

    @logged_api_call
    def update_properties(self, properties):
        """
        Update writeable properties of this LDAP Server Definitions.

        This method serializes with other methods that access or change
        properties on the same Python object.

        Authorization requirements:

        * Task permission to the "Manage LDAP Server Definitions" task.

        Parameters:

          properties (dict): New values for the properties to be updated.
            Properties not to be updated are omitted.
            Allowable properties are the properties with qualifier (w) in
            section 'Data model' in section 'LDAP Server Definition object' in
            the :term:`HMC API` book.

        Raises:

          :exc:`~zhmcclient.HTTPError`
          :exc:`~zhmcclient.ParseError`
          :exc:`~zhmcclient.AuthError`
          :exc:`~zhmcclient.ConnectionError`
        """
        # pylint: disable=protected-access
        self.manager.session.post(self.uri, body=properties)

        # The name of LDAP Server Definitions cannot be updated. An attempt to
        # do so should cause HTTPError to be raised in the POST above, so we
        # assert that here, because we omit the extra code for handling name
        # updates:
        assert self.manager._name_prop not in properties
        self.update_properties_local(copy.deepcopy(properties))

redpajama_set_name: RedPajamaGithub


text:
import sys
from functools import wraps

from rqalpha.const import ORDER_TYPE, SIDE, POSITION_EFFECT

from .pyctp import MdApi, TraderApi, ApiStruct
from .data_dict import TickDict, PositionDict, AccountDict, InstrumentDict, OrderDict, TradeDict, CommissionDict
from ..utils import make_order_book_id, str2bytes, bytes2str

ORDER_TYPE_MAPPING = {
    ORDER_TYPE.MARKET: ApiStruct.OPT_AnyPrice,
    ORDER_TYPE.LIMIT: ApiStruct.OPT_LimitPrice,
}

SIDE_MAPPING = {
    SIDE.BUY: ApiStruct.D_Buy,
    SIDE.SELL: ApiStruct.D_Sell,
}

POSITION_EFFECT_MAPPING = {
    POSITION_EFFECT.OPEN: ApiStruct.OF_Open,
    POSITION_EFFECT.CLOSE: ApiStruct.OF_Close,
    POSITION_EFFECT.CLOSE_TODAY: ApiStruct.OF_CloseToday,
}

def query_in_sync(func):
    @wraps(func)
    def wrapper(api, pData, pRspInfo, nRequestID, bIsLast):
        api._req_id = max(api.req_id, nRequestID)
        result = func(api, pData, pRspInfo, nRequestID, bIsLast)
        if bIsLast:
            api.gateway.on_query(api.api_name, nRequestID, result)
    return wrapper

class CtpMdApi(MdApi):
    def __init__(self, gateway, user_id, password, broker_id, address, api_name='ctp_md'):
        super(CtpMdApi, self).__init__()

        self.gateway = gateway
        self._req_id = 0

        self.connected = False
        self.logged_in = False

        self.user_id = user_id
        self.password = password
        self.broker_id = broker_id
        self.address = address

        self.api_name = api_name

    def OnFrontConnected(self):
        """服务器连接"""
        self.connected = True
        self.login()

    def OnFrontDisconnected(self, nReason):
        """服务器断开"""
        self.connected = False
        self.logged_in = False
        self.gateway.on_debug('服务器断开,将自动重连。')

    def OnHeartBeatWarning(self, nTimeLapse):
        """心跳报警"""
        pass

    def OnRspError(self, pRspInfo, nRequestID, bIsLast):
        """错误回报"""
        self.gateway.on_err(pRspInfo, sys._getframe().f_code.co_name)

    def OnRspUserLogin(self, pRspUserLogin, pRspInfo, nRequestID, bIsLast):
        """登陆回报"""
        if pRspInfo.ErrorID == 0:
            self.logged_in = True
        else:
            self.gateway.on_err(pRspInfo, sys._getframe().f_code.co_name)

    def OnRspUserLogout(self, pUserLogout, pRspInfo, nRequestID, bIsLast):
        """登出回报"""
        if pRspInfo.ErrorID == 0:
            self.logged_in = False
        else:
            self.gateway.on_err(pRspInfo, sys._getframe().f_code.co_name)

    def OnRspSubMarketData(self, pSpecificInstrument, pRspInfo, nRequestID, bIsLast):
        """订阅合约回报"""
        pass

    def OnRspUnSubForQuoteRsp(self, pSpecificInstrument, pRspInfo, nRequestID, bIsLast):
        """退订合约回报"""
        pass

    def OnRtnDepthMarketData(self, pDepthMarketData):
        """行情推送"""
        tick_dict = TickDict(pDepthMarketData)
        if tick_dict.is_valid:
            self.gateway.on_tick(tick_dict)

    def OnRspSubForQuoteRsp(self, pSpecificInstrument, pRspInfo, nRequestID, bIsLast):
        """订阅期权询价"""
        pass

    def OnRspUnSubMarketData(self, pSpecificInstrument, pRspInfo, nRequestID, bIsLast):
        """退订期权询价"""
        pass

    def OnRtnForQuoteRsp(self, pForQuoteRsp):
        """期权询价推送"""
        pass

    @property
    def req_id(self):
        self._req_id += 1
        return self._req_id

    def connect(self):
        """初始化连接"""
        if not self.connected:
            self.Create()
            self.RegisterFront(str2bytes(self.address))
            self.Init()
        else:
            self.login()

    def subscribe(self, ins_id_list):
        """订阅合约"""
        if len(ins_id_list) > 0:
            ins_id_list = [str2bytes(i) for i in ins_id_list]
            self.SubscribeMarketData(ins_id_list)

    def login(self):
        """登录"""
        if not self.logged_in:
            req = ApiStruct.ReqUserLogin(BrokerID=str2bytes(self.broker_id),
                                         UserID=str2bytes(self.user_id),
                                         Password=str2bytes(self.password))
            req_id = self.req_id
            self.ReqUserLogin(req, req_id)
            return req_id

    def close(self):
        """关闭"""
        pass
        # self.Join()

class CtpTdApi(TraderApi):
    def __init__(self, gateway, user_id, password, broker_id, address, api_name='ctp_td'):
        super(CtpTdApi, self).__init__()

        self.gateway = gateway
        self._req_id = 0

        self.connected = False
        self.logged_in = False
        self.authenticated = False

        self.user_id = user_id
        self.password = password
        self.broker_id = broker_id
        self.address = address
        self.auth_code = None
        self.user_production_info = None

        self.front_id = 0
        self.session_id = 0

        self.require_authentication = False

        self.pos_cache = {}
        self.ins_cache = {}
        self.order_cache = {}

        self.api_name = api_name

    def OnFrontConnected(self):
        self.connected = True
        if self.require_authentication:
            self.authenticate()
        else:
            self.login()

    def OnFrontDisconnected(self, nReason):
        self.connected = False
        self.logged_in = False
        self.gateway.on_debug('服务器断开,将自动重连。')

    def OnHeartBeatWarning(self, nTimeLapse):
        """心跳报警"""
        pass

    def OnRspAuthenticate(self, pRspAuthenticate, pRspInfo, nRequestID, bIsLast):
        """验证客户端回报"""
        if pRspInfo.ErrorID == 0:
            self.authenticated = True
            self.login()
        else:
            self.gateway.on_err(pRspInfo, sys._getframe().f_code.co_name)

    def OnRspUserLogin(self, pRspUserLogin, pRspInfo, nRequestID, bIsLast):
        """登陆回报"""
        if pRspInfo.ErrorID == 0:
            self.front_id = pRspUserLogin.FrontID
            self.session_id = pRspUserLogin.SessionID
            self.logged_in = True
            self.qrySettlementInfoConfirm()
        else:
            self.gateway.on_err(pRspInfo, sys._getframe().f_code.co_name)

    def OnRspUserLogout(self, pUserLogout, pRspInfo, nRequestID, bIsLast):
        """登出回报"""
        if pRspInfo.ErrorID == 0:
            self.logged_in = False
        else:
            self.gateway.on_err(pRspInfo)

    def OnRspOrderInsert(self, pInputOrder, pRspInfo, nRequestID, bIsLast):
        order_dict = OrderDict(pInputOrder, rejected=True)
        if order_dict.is_valid:
            self.gateway.on_order(order_dict)

    def OnRspOrderAction(self, pInputOrderAction, pRspInfo, nRequestID, bIsLast):
        self.gateway.on_err(pRspInfo, sys._getframe().f_code.co_name)

    @query_in_sync
    def OnRspQryOrder(self, pOrder, pRspInfo, nRequestID, bIsLast):
        """报单回报"""
        if pOrder:
            order_dict = OrderDict(pOrder)
            if order_dict.is_valid:
                self.order_cache[order_dict.order_id] = order_dict
        if bIsLast:
            return self.order_cache

    @query_in_sync
    def OnRspQryInvestorPosition(self, pInvestorPosition, pRspInfo, nRequestID, bIsLast):
        """持仓查询回报"""
        if pInvestorPosition.InstrumentID:
            order_book_id = make_order_book_id(pInvestorPosition.InstrumentID)
            if order_book_id not in self.pos_cache:
                self.pos_cache[order_book_id] = PositionDict(pInvestorPosition)
            else:
                self.pos_cache[order_book_id].update_data(pInvestorPosition)
        if bIsLast:
            return self.pos_cache

    @query_in_sync
    def OnRspQryTradingAccount(self, pTradingAccount, pRspInfo, nRequestID, bIsLast):
        """资金账户查询回报"""
        return AccountDict(pTradingAccount)

    @query_in_sync
    def OnRspQryInstrumentCommissionRate(self, pInstrumentCommissionRate, pRspInfo, nRequestID, bIsLast):
        """请求查询合约手续费率响应"""
        return CommissionDict(pInstrumentCommissionRate)

    @query_in_sync
    def OnRspQryInstrument(self, pInstrument, pRspInfo, nRequestID, bIsLast):
        """合约查询回报"""
        ins_dict = InstrumentDict(pInstrument)
        if ins_dict.is_valid:
            self.ins_cache[ins_dict.order_book_id] = ins_dict
        if bIsLast:
            return self.ins_cache

    def OnRspError(self, pRspInfo, nRequestID, bIsLast):
        """错误回报"""
        self.gateway.on_err(pRspInfo, sys._getframe().f_code.co_name)

    def OnRtnOrder(self, pOrder):
        """报单回报"""
        order_dict = OrderDict(pOrder)
        if order_dict.is_valid:
            self.gateway.on_order(order_dict)

    def OnRtnTrade(self, pTrade):
        """成交回报"""
        trade_dict = TradeDict(pTrade)
        self.gateway.on_trade(trade_dict)

    def OnErrRtnOrderInsert(self, pInputOrder, pRspInfo):
        """发单错误回报(交易所)"""
        self.gateway.on_err(pRspInfo, sys._getframe().f_code.co_name)
        order_dict = OrderDict(pInputOrder)
        if order_dict.is_valid:
            self.gateway.on_order(order_dict)

    def OnErrRtnOrderAction(self, pOrderAction, pRspInfo):
        """撤单错误回报(交易所)"""
        self.gateway.on_err(pRspInfo, sys._getframe().f_code.co_name)

    @property
    def req_id(self):
        self._req_id += 1
        return self._req_id

    def connect(self):
        if not self.connected:
            self.Create()
            self.SubscribePrivateTopic(0)
            self.SubscribePublicTopic(0)
            self.RegisterFront(str2bytes(self.address))
            self.Init()
        else:
            if self.require_authentication:
                self.authenticate()
            else:
                self.login()

    def authenticate(self):
        """申请验证"""
        if self.authenticated:
            req = ApiStruct.AuthenticationInfo(
                BrokerID=str2bytes(self.broker_id),
                UserID=str2bytes(self.user_id),
                AuthInfo=str2bytes(self.auth_code),
                UserProductInfo=str2bytes(self.user_production_info)
            )
            req_id = self.req_id
            self.ReqAuthenticate(req, req_id)
            return req_id
        else:
            self.login()

    def login(self):
        """登录"""
        if not self.logged_in:
            req = ApiStruct.ReqUserLogin(
                UserID=str2bytes(self.user_id),
                BrokerID=str2bytes(self.broker_id),
                Password=str2bytes(self.password),
            )
            req_id = self.req_id
            self.ReqUserLogin(req, req_id)
            return req_id

    def qrySettlementInfoConfirm(self):
        req = ApiStruct.SettlementInfoConfirm(BrokerID=str2bytes(self.broker_id), InvestorID=str2bytes(self.user_id))
        req_id = self.req_id
        self.ReqSettlementInfoConfirm(req, req_id)

    def qryInstrument(self):
        self.ins_cache = {}
        req = ApiStruct.QryInstrument()
        req_id = self.req_id
        self.ReqQryInstrument(req, req_id)
        return req_id

    def qryCommission(self, order_book_id):
        ins_dict = self.gateway.get_ins_dict(order_book_id)
        if ins_dict is None:
            return None
        req = ApiStruct.QryInstrumentCommissionRate(
            InstrumentID=str2bytes(ins_dict.instrument_id),
            InvestorID=str2bytes(self.user_id),
            BrokerID=str2bytes(self.broker_id),
        )
        req_id = self.req_id
        self.ReqQryInstrumentCommissionRate(req, req_id)
        return req_id

    def qryAccount(self):
        req = ApiStruct.QryTradingAccount()
        req_id = self.req_id
        self.ReqQryTradingAccount(req, req_id)
        return req_id

    def qryPosition(self):
        self.pos_cache = {}
        req = ApiStruct.QryInvestorPosition(
            BrokerID=str2bytes(self.broker_id),
            InvestorID=str2bytes(self.user_id)
        )
        req_id = self.req_id
        self.ReqQryInvestorPosition(req, req_id)
        return req_id

    def qryOrder(self):
        self.order_cache = {}
        req = ApiStruct.QryOrder(
            BrokerID=str2bytes(self.broker_id),
            InvestorID=str2bytes(self.user_id)
        )
        req_id = self.req_id
        self.ReqQryOrder(req, req_id)
        return req_id

    def sendOrder(self, order):
        ins_dict = self.gateway.get_ins_dict(order.order_book_id)
        if ins_dict is None:
            return None
        req = ApiStruct.InputOrder(
            InstrumentID=str2bytes(ins_dict.instrument_id),
            LimitPrice=str2bytes(order.price),
            VolumeTotalOriginal=str2bytes(order.quantity),
            OrderPriceType=ORDER_TYPE_MAPPING.get(order.type, ''),
            Direction=SIDE_MAPPING.get(order.side, ''),
            CombOffsetFlag=POSITION_EFFECT_MAPPING.get(order.position_effect, ''),

            OrderRef=str2bytes(str(order.order_id)),
            InvestorID=str2bytes(self.user_id),
            UserID=str2bytes(self.user_id),
            BrokerID=str2bytes(self.broker_id),

            CombHedgeFlag=ApiStruct.HF_Speculation,
            ContingentCondition=ApiStruct.CC_Immediately,
            ForceCloseReason=ApiStruct.FCC_NotForceClose,
            IsAutoSuspend=0,
            TimeCondition=ApiStruct.TC_GFD,
            VolumeCondition=ApiStruct.VC_AV,
            MinVolume=1,
        )
        req_id = self.req_id
        self.ReqOrderInsert(req, req_id)
        return self.req_id

    def cancelOrder(self, order):
        ins_dict = self.gateway.get_ins_dict(order.order_book_id)
        if ins_dict is None:
            return None

        req = ApiStruct.InputOrderAction(
            InstrumentID=str2bytes(ins_dict.instrument_id),
            ExchangeID=str2bytes(ins_dict.exchange_id),
            OrderRef=str2bytes(str(order.order_id)),
            FrontID=int(self.front_id),
            SessionID=int(self.session_id),

            ActionFlag=ApiStruct.AF_Delete,
            BrokerID=str2bytes(self.broker_id),
            InvestorID=str2bytes(self.user_id),
        )
        req_id = self.req_id
        self.ReqOrderAction(req, req_id)
        return req_id

    def close(self):
        pass
        # self.Join()


text:
package _19

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */

type ListNode struct {
	Val int
	Next *ListNode
}

func formatList2Node(list []int)*ListNode  {
	head := new(ListNode)
	current := head
	for i := range list{
		current.Next = new(ListNode)
		current.Next.Val = list[i]
		current = current.Next
	}
	return head.Next
}

func removeNthFromEnd(head *ListNode, n int) *ListNode {
	dummy := new(ListNode)
	dummy.Next = head
	left := dummy
	right := dummy
	for i := 0 ;i < n; i ++ {
		if right.Next == nil {
			return nil
		}
		right = right.Next
	}
	for right.Next != nil {
		right = right.Next
		left = left.Next
	}
	left.Next = left.Next.Next
	return dummy.Next
}


text:
//
//  main_picking.cpp
//  HCI 557 Picking example
//
//  Created by Rafael Radkowski on 5/28/15.
//  Copyright (c) 2015 -. All rights reserved.
//

// stl include
#include <iostream>
#include <string>

// GLEW include
#include <GL/glew.h>

// GLM include files
#define GLM_FORCE_INLINE
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/transform.hpp>

// glfw includes
#include <GLFW/glfw3.h>

// include local files
#include "controls.h"
#include "HCI557Common.h"
#include "CoordSystem.h"

#include "GLObjectObj.h"
#include "Bezier.h"
#include "GLSurface.h"

using namespace std;

// The handle to the window object
GLFWwindow*         window;

/* A trackball to move and rotate the camera view */
extern Trackball trackball;

int main(int argc, const char * argv[])
{
    vector< vector<float> > control_points;
    vector< vector<float> > result;

    // These are the control points for a spline
    vector<float> p0 = vector<float>(3,0);
    p0[0] = 0.0; p0[1] = 1.0; p0[2] = 0.0;

    vector<float> p1 = vector<float>(3,0);
    p1[0] = 0.0; p1[1] = 2.0; p1[2] = 1.0;

    vector<float> p2 = vector<float>(3,0);
    p2[0] = 0.0; p2[1] = 3.0; p2[2] = 3.0;

    vector<float> p3 = vector<float>(3,0);
    p3[0] = 0.0; p3[1] = 2.0; p3[2] = 4.0;

    control_points.push_back(p0);
    control_points.push_back(p1);
    control_points.push_back(p2);
    control_points.push_back(p3);

    // This computes the spline and ten points along the spline.
    ComputeCubicSplineC(10, control_points, result);

    // Next, we create a surface with 4x4 control points.
    // A different way in order to introduce different computational way.s
    static const
    float data_surface[16][3] = {{0,0,0}, {1.5, 0, 0}, {2.2,0,0}, {4.0,0,0},
                                 {0,1,0.2}, {1.5, 1, 0.4}, {2.2,1,0.6}, {4.0,1,0.2},
                                 {0.1,2,0.2}, {1.4, 2, 0.5}, {2.0,2,0.8}, {3.9,2,0.2},
                                 {0.0,3,0.2}, {1.4, 3, 0.4}, {2.0,3,0.5}, {3.9,3,0.0}
                                 };

    vector< vector<float> > control_points_surface(16,vector<float>(3,0.0) );
    for(int i=0; i<16; i++){
     control_points_surface[i][0] = data_surface[i][0];
     control_points_surface[i][1] = data_surface[i][1];
     control_points_surface[i][2] = data_surface[i][2];
    }

    vector< vector<float> > result_surface;

    // This computes the points for this surface.
    ComputeCubicPatch(10, control_points_surface, result_surface );

    // In order to render the object, we need to vertices, triangles, and normals.
    // This function generates them for us.
    // glm::vec3(0.0,0.0,1.0) <- this is the general up direction of this surface.
    // This vector is used to align all the normal vectors.
    vector< glm::vec3 > vertices;
    vector< glm::vec3 > normals;
    TriangulateCubicPatch(10, 10, result_surface, glm::vec3(0.0,0.0,1.0), vertices, normals );

    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //// Init glfw, create a window, and init glew

    // Init the GLFW Window
    window = initWindow();

    // Init the glew api
    initGlew();
    SetCameraManipulator(CameraTypes::CAMERA_MANIPULATOR);

    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //// Create some models

    // coordinate system
    CoordSystem* cs = new CoordSystem(40.0);

    // create an apperance object.
    //GLAppearance* apperance_0 = new GLAppearance("../../data/shaders/multi_vertex_lights_ext.vs", "../../data/shaders/multi_vertex_lights.fs");
    GLAppearance* apperance_0 = new GLAppearance("../../data/shaders/multi_fragment_lights.vs", "../../data/shaders/multi_fragment_lights.fs");

    GLDirectLightSource  light_source;
    light_source._lightPos = glm::vec4(2.0,0.0,10.0, 0.0);
    light_source._ambient_intensity = 1.0;
    light_source._specular_intensity = 1.5;
    light_source._diffuse_intensity = 40.0;
    light_source._attenuation_coeff = 0.0;

    // add the light to this apperance object
    apperance_0->addLightSource(light_source);

    // Create a material object
    GLMaterial material_0;
    material_0._diffuse_material = glm::vec3(1.0, 0.0, 0.0);
    material_0._ambient_material = glm::vec3(1.0, 0.0, 0.0);
    material_0._specular_material = glm::vec3(1.0, 1.0, 1.0);
    material_0._shininess = 25.0;
    material_0._transparency = 1.0;

    // Add the material to the apperance object
    apperance_0->setMaterial(material_0);
    apperance_0->finalize();

    // If you want to change appearance parameters after you init the object, call the update function
    apperance_0->updateLightSources();

    GLSurface* surface = new GLSurface(vertices, normals);
    surface->setApperance(*apperance_0);
    surface->init();

    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    // Set up our green background color
    static const GLfloat clear_color_white[] = { 1.0f, 1.0f, 1.0f, 1.0f };
    static const GLfloat clear_color_black[] = { 0.0f, 0.0f, 0.0f, 0.0f };
    static const GLfloat clear_depth[] = { 1.0f, 1.0f, 1.0f, 1.0f };

    // This sets the camera to a new location
    // the first parameter is the eye position, the second the center location, and the third the up vector.
    SetViewAsLookAt(glm::vec3(8.0f, 8.0f, 20.5f), glm::vec3(1.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f));
    SetCameraDistance(15.0);

    // Enable depth test
    // ignore this line, it allows us to keep the distance value after we proejct each object to a 2d canvas.
    glEnable(GL_DEPTH_TEST);

    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //// Blending

    // Enable blending
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //// Main render loop

    // This is our render loop. As long as our window remains open (ESC is not pressed), we'll continue to render things.
    while(!glfwWindowShouldClose(window))
    {

        // Clear the entire buffer with our green color (sets the background to be green).
        glClearBufferfv(GL_COLOR , 0, clear_color_black);
        glClearBufferfv(GL_DEPTH , 0, clear_depth);

        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //// This renders the objects

        // Set the trackball locatiom
        SetTrackballLocation(GetCurrentCameraMatrix(), GetCurrentCameraTranslation());

        // draw the objects
        cs->draw();
        surface->draw();

        //// This renders the objects
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        // Swap the buffers so that what we drew will appear on the screen.
        glfwSwapBuffers(window);
        glfwPollEvents();

    }

    delete cs;

}


text:
// ------------------------------------------------------------
//  Copyright (c) Microsoft Corporation.  All rights reserved.
//  Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------

namespace VisualObjects.Common
{
    using System;
    using System.Collections.Generic;
    using System.Runtime.Serialization;
    using System.Text;

    [DataContract]
    public class VisualObject
    {
        private const int HistoryLength = 7;

        public VisualObject(string name, Speed speed, Coordinate location, Color color, Color historyColor, double rotation = 0)
        {
            this.Name = name;
            this.Speed = speed;
            this.CurrentLocation = location;
            this.CurrentColor = color;
            this.HistoryColor = historyColor;
            this.Rotation = rotation;
            this.LocationHistory = new List<Coordinate>();
            this.HistoryStartIndex = -1;
        }

        public VisualObject(VisualObject other)
        {
            this.Name = other.Name;
            this.Speed = new Speed(other.Speed);

            this.CurrentLocation = new Coordinate(other.CurrentLocation);
            this.LocationHistory = new List<Coordinate>(other.LocationHistory.Count);
            foreach (Coordinate c in other.LocationHistory)
            {
                this.LocationHistory.Add(new Coordinate(c));
            }

            this.CurrentColor = new Color(other.CurrentColor);
            this.HistoryColor = new Color(other.HistoryColor);

            this.Rotation = other.Rotation;
        }

        [DataMember]
        public string Name { get; private set; }

        [DataMember]
        public Speed Speed { get; private set; }

        [DataMember(Name = "current")]
        public Coordinate CurrentLocation { get; set; }

        [DataMember]
        public Color CurrentColor { get; set; }

        [DataMember]
        public Color HistoryColor { get; set; }

        [DataMember]
        public int HistoryStartIndex { get; set; }

        [DataMember(Name = "history")]
        public List<Coordinate> LocationHistory { get; private set; }

        [DataMember]
        public double Rotation { get; set; }

        public static VisualObject CreateRandom(string name, Random rand = null)
        {
            if (rand == null)
            {
                rand = new Random(name.GetHashCode());
            }

            return new VisualObject(
                name,
                Speed.CreateRandom(rand),
                Coordinate.CreateRandom(rand),
                Color.CreateRandom(Color.CurrentColorsPalette, rand),
                Color.CreateRandom(Color.HistoryColorsPalette, rand));
        }

        public void Move(bool rotate)
        {
            if (this.LocationHistory.Count < HistoryLength)
            {
                this.HistoryStartIndex = (this.HistoryStartIndex + 1);
                this.LocationHistory.Add(new Coordinate(this.CurrentLocation));
            }
            else
            {
                this.HistoryStartIndex = (this.HistoryStartIndex + 1)%HistoryLength;
                this.LocationHistory[this.HistoryStartIndex] = new Coordinate(this.CurrentLocation);
            }

            double xSpeed = this.Speed.XSpeed;
            double ySpeed = this.Speed.YSpeed;
            double zSpeed = this.Speed.ZSpeed;

            double x = this.CurrentLocation.X + xSpeed;
            double y = this.CurrentLocation.Y + ySpeed;
            double z = this.CurrentLocation.Z + zSpeed;

            this.CurrentLocation = new Coordinate(this.CurrentLocation.X + xSpeed, this.CurrentLocation.Y + ySpeed, this.CurrentLocation.Z + zSpeed);

            // trim to edges
            this.Speed = new Speed(
                CheckForEdge(x, xSpeed),
                CheckForEdge(y, ySpeed),
                CheckForEdge(z, zSpeed));

            if (rotate)
            {
                this.Rotation = 5;
            }
            else
            {
                this.Rotation = 0;
            }
        }

        public string ToJson()
        {
            StringBuilder sb = new StringBuilder();
            this.ToJson(sb);

            return sb.ToString();
        }

        public void ToJson(StringBuilder builder)
        {
            builder.Append("{");

            {
                builder.Append("\"current\":");
                this.CurrentLocation.ToJson(builder);
            }

            {
                builder.Append(", \"history\":");
                builder.Append("[");
                int currentIndex = this.HistoryStartIndex;
                if (currentIndex != -1)
                {
                    bool first = true;
                    do
                    {
                        currentIndex++;
                        if (currentIndex == this.LocationHistory.Count)
                        {
                            currentIndex = 0;
                        }

                        if (first)
                        {
                            first = false;
                        }
                        else
                        {
                            builder.Append(", ");
                        }

                        this.LocationHistory[currentIndex].ToJson(builder);
                    } while (currentIndex != this.HistoryStartIndex);
                }
                builder.Append("]");
            }

            {
                builder.Append(", \"currentColor\":");
                this.CurrentColor.ToJson(builder);
            }

            {
                builder.Append(", \"historyColor\":");
                this.HistoryColor.ToJson(builder);
            }

            {
                builder.Append(", \"rotation\":");
                builder.Append(this.Rotation);
            }

            builder.Append("}");
        }

        private static double CheckForEdge(double point, double speed)
        {
            if (point < -1.0 || point > 1.0)
            {
                return speed*-1.0;
            }

            return speed;
        }
    }
}


text:
<launch>
  <param name="somestring1" />
</launch>


text:
namespace openGLDriver {

	class Logger
	{
	private:
		std::ofstream m_stream;

	public:
		Logger();
		Logger(const std::string &filename);
		~Logger();
		void init(const std::string &filename);
		void write(const std::string& line);
		void close();
	};

}


text:
ActiveRecord::Schema.define(:version => 20120518225540) do

  create_table "articles", :force => true do |t|
    t.string   "name"
    t.text     "content"
    t.datetime "created_at", :null => false
    t.datetime "updated_at", :null => false
  end

  create_table "comments", :force => true do |t|
    t.text     "content"
    t.integer  "commentable_id"
    t.string   "commentable_type"
    t.datetime "created_at",       :null => false
    t.datetime "updated_at",       :null => false
  end

  add_index "comments", ["commentable_id", "commentable_type"], :name => "index_comments_on_commentable_id_and_commentable_type"

  create_table "events", :force => true do |t|
    t.string   "name"
    t.datetime "starts_at"
    t.datetime "ends_at"
    t.text     "description"
    t.datetime "created_at",  :null => false
    t.datetime "updated_at",  :null => false
  end

  create_table "photos", :force => true do |t|
    t.string   "name"
    t.string   "filename"
    t.datetime "created_at", :null => false
    t.datetime "updated_at", :null => false
  end

end


text:
package com.morihacky.android.rxjava.retrofit;

public class User {
    public String name;
    public String email;
}


text:
package org.sakaiproject.dash.tool.panels;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Logger;
import org.apache.wicket.AttributeModifier;
import org.apache.wicket.Component;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.behavior.SimpleAttributeModifier;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.image.Image;
import org.apache.wicket.markup.html.link.ExternalLink;
import org.apache.wicket.markup.html.navigation.paging.IPagingLabelProvider;
import org.apache.wicket.markup.html.navigation.paging.PagingNavigator;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.markup.repeater.DefaultItemReuseStrategy;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.markup.repeater.data.DataView;
import org.apache.wicket.markup.repeater.data.IDataProvider;
import org.apache.wicket.model.AbstractReadOnlyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.LoadableDetachableModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.sakaiproject.dash.app.DashboardCommonLogic;
import org.sakaiproject.dash.app.DashboardConfig;
import org.sakaiproject.dash.app.SakaiProxy;
import org.sakaiproject.dash.model.CalendarItem;
import org.sakaiproject.dash.model.CalendarLink;
import org.sakaiproject.dash.tool.pages.DashboardPage;
import org.sakaiproject.dash.tool.util.JsonHelper;
import org.sakaiproject.dash.util.DateUtil;
import org.sakaiproject.util.FormattedText;
import org.sakaiproject.util.ResourceLoader;

/**
 *
 *
 */
public class CalendarLinksPanel extends Panel {

	public static final String TAB_ID_UPCOMING = "upcoming";
	public static final String TAB_ID_PAST = "past";
	public static final String TAB_ID_STARRED = "starred";
	public static final String TAB_ID_HIDDEN = "hidden";
	public static final String TAB_ID_PAST_HIDDEN = "past-hidden";

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

	protected static final String DATE_FORMAT = "dd-MMM-yyyy";
	protected static final String TIME_FORMAT = "HH:mm";
	protected static final String DATETIME_FORMAT = "dd-MMM-yyyy HH:mm";

	@SpringBean(name="org.sakaiproject.dash.app.SakaiProxy")
	protected SakaiProxy sakaiProxy;

	@SpringBean(name="org.sakaiproject.dash.app.DashboardCommonLogic")
	protected DashboardCommonLogic dashboardCommonLogic;

	@SpringBean(name="org.sakaiproject.dash.app.DashboardConfig")
	protected DashboardConfig dashboardConfig;

	protected CalendarLinksDataProvider calendarLinksProvider = null;

	protected DashboardPage dashboardPage;

	protected String selectedCalendarTab = null;
	protected String calendarLinksDivId = null;
	protected String calendarLinksCountId = null;
	protected int pageSize = dashboardConfig.getConfigValue(DashboardConfig.PROP_DEFAULT_ITEMS_IN_PANEL, 5);

	public CalendarLinksPanel(String id) {
		super(id);

		initPanel();

	}
	public CalendarLinksPanel(String id, String selectedTab) {
		super(id);
		this.selectedCalendarTab = selectedTab;

		initPanel();

	}

	/**
	 *
	 */
	protected void initPanel() {

		if(selectedCalendarTab == null) {
			selectedCalendarTab = TAB_ID_UPCOMING;
		}

		if(this.calendarLinksDivId != null) {
			this.remove(calendarLinksDivId);
		}

        ResourceLoader rl = new ResourceLoader("dash_entity");

		final WebMarkupContainer calendarLinksDiv = new WebMarkupContainer("calendarLinksDiv");
		calendarLinksDiv.setOutputMarkupId(true);
		add(calendarLinksDiv);
		this.calendarLinksDivId = calendarLinksDiv.getId();

		calendarLinksDiv.add(new Label("calendarTitle",rl.getString("dash.calendar.title")));

        AjaxLink<IModel<List<CalendarLink>>> upcomingCalendarLink = new AjaxLink<IModel<List<CalendarLink>>>("link") {

			@Override
			public void onClick(AjaxRequestTarget target) {
				logger.debug("upcomingCalendarLink onClick called");
				// set currentCalendarTab to "upcoming"
				selectedCalendarTab = TAB_ID_UPCOMING;
				// reset calendar dataview to show upcoming stuff
		        if(calendarLinksProvider == null) {
		        	calendarLinksProvider = new CalendarLinksDataProvider(selectedCalendarTab);
		        } else {
		        	calendarLinksProvider.setCalendarTab(selectedCalendarTab);
		        }

				// refresh calendarItemsDiv
		        initPanel();
				target.addComponent(CalendarLinksPanel.this);
				target.appendJavascript("resizeFrame('grow');");
				target.appendJavascript("$('#schedPanel').focus();");
				dashboardCommonLogic.recordDashboardActivity(DashboardCommonLogic.EVENT_DASH_TABBING, "/dashboard/calendar/upcoming");
			}

        };

        upcomingCalendarLink.add(new Label("label", rl.getString("dash.calendar.upcoming")));
		WebMarkupContainer upcomingCalendarTab = new WebMarkupContainer("upcomingCalendarTab");
		if(selectedCalendarTab == null || TAB_ID_UPCOMING.equalsIgnoreCase(selectedCalendarTab)) {
			upcomingCalendarTab.add(new SimpleAttributeModifier("class", "activeTab"));
		}
		upcomingCalendarTab.add(upcomingCalendarLink);
        calendarLinksDiv.add(upcomingCalendarTab);

		AjaxLink<IModel<List<CalendarLink>>> pastCalendarLink = new AjaxLink<IModel<List<CalendarLink>>>("link") {

			@Override
			public void onClick(AjaxRequestTarget target) {
				logger.debug("pastCalendarLink onClick called");
				// set currentCalendarTab to "past"
				selectedCalendarTab = TAB_ID_PAST;

				// reset calendar dataview to show past stuff
		        if(calendarLinksProvider == null) {
		        	calendarLinksProvider = new CalendarLinksDataProvider(selectedCalendarTab);
		        } else {
		        	calendarLinksProvider.setCalendarTab(selectedCalendarTab);
		        }

				// refresh calendarItemsDiv
		        initPanel();
				target.addComponent(CalendarLinksPanel.this);
				target.appendJavascript("resizeFrame('grow');");
				target.appendJavascript("$('#schedPanel').focus();");
				dashboardCommonLogic.recordDashboardActivity(DashboardCommonLogic.EVENT_DASH_TABBING, "/dashboard/calendar/past");
			}

        };
        pastCalendarLink.add(new Label("label", rl.getString("dash.calendar.past")));
		WebMarkupContainer pastCalendarTab = new WebMarkupContainer("pastCalendarTab");
		if(selectedCalendarTab != null && TAB_ID_PAST.equalsIgnoreCase(selectedCalendarTab)) {
			pastCalendarTab.add(new SimpleAttributeModifier("class", "activeTab"));
		}
		pastCalendarTab.add(pastCalendarLink);
        calendarLinksDiv.add(pastCalendarTab);

		AjaxLink<IModel<List<CalendarLink>>> starredCalendarLink = new AjaxLink<IModel<List<CalendarLink>>>("link") {

			@Override
			public void onClick(AjaxRequestTarget target) {
				logger.debug("starredCalendarLink onClick called");
				// set currentCalendarTab to "starred"
				selectedCalendarTab = TAB_ID_STARRED;

				// reset calendar dataview to show starred stuff
		        if(calendarLinksProvider == null) {
		        	calendarLinksProvider = new CalendarLinksDataProvider(selectedCalendarTab);
		        } else {
		        	calendarLinksProvider.setCalendarTab(selectedCalendarTab);
		        }

				// refresh calendarItemsDiv
		        initPanel();
				target.addComponent(CalendarLinksPanel.this);
				target.appendJavascript("resizeFrame('grow');");
				target.appendJavascript("$('#schedPanel').focus();");
				dashboardCommonLogic.recordDashboardActivity(DashboardCommonLogic.EVENT_DASH_TABBING, "/dashboard/calendar/starred");
			}

        };
        starredCalendarLink.add(new Label("label", rl.getString("dash.calendar.starred")));
		WebMarkupContainer starredCalendarTab = new WebMarkupContainer("starredCalendarTab");
		if(selectedCalendarTab != null && TAB_ID_STARRED.equalsIgnoreCase(selectedCalendarTab)) {
			starredCalendarTab.add(new SimpleAttributeModifier("class", "activeTab"));
		}
		starredCalendarTab.add(starredCalendarLink);
        calendarLinksDiv.add(starredCalendarTab);

		AjaxLink<IModel<List<CalendarLink>>> hiddenCalendarLink = new AjaxLink<IModel<List<CalendarLink>>>("link") {

			@Override
			public void onClick(AjaxRequestTarget target) {
				logger.debug("hiddenCalendarLink onClick called");
				// set currentCalendarTab to "hidden"
				selectedCalendarTab = TAB_ID_HIDDEN;

				// reset calendar dataview to show hidden stuff
		        if(calendarLinksProvider == null) {
		        	calendarLinksProvider = new CalendarLinksDataProvider(selectedCalendarTab);
		        } else {
		        	calendarLinksProvider.setCalendarTab(selectedCalendarTab);
		        }

				// refresh calendarItemsDiv
		        initPanel();
				target.addComponent(CalendarLinksPanel.this);
				target.appendJavascript("resizeFrame('grow');");
				target.appendJavascript("$('#schedPanel').focus();");
				dashboardCommonLogic.recordDashboardActivity(DashboardCommonLogic.EVENT_DASH_TABBING, "/dashboard/calendar/hidden");
			}

        };
        hiddenCalendarLink.add(new Label("label", rl.getString("dash.calendar.hidden")));
		WebMarkupContainer hiddenCalendarTab = new WebMarkupContainer("hiddenCalendarTab");
		if(selectedCalendarTab != null && TAB_ID_HIDDEN.equalsIgnoreCase(selectedCalendarTab)) {
			hiddenCalendarTab.add(new SimpleAttributeModifier("class", "activeTab"));
		}
		hiddenCalendarTab.add(hiddenCalendarLink);
        calendarLinksDiv.add(hiddenCalendarTab);

        if(calendarLinksProvider == null) {
        	calendarLinksProvider = new CalendarLinksDataProvider(selectedCalendarTab);
        } else {
        	calendarLinksProvider.setCalendarTab(selectedCalendarTab);
        }

        WebMarkupContainer haveLinks = new WebMarkupContainer("haveLinks");
        calendarLinksDiv.add(haveLinks);

		//present the calendar data in a table
		final DataView<CalendarLink> calendarDataView = new DataView<CalendarLink>("calendarItems", calendarLinksProvider) {

			@Override
			public void populateItem(final Item item) {
				if(item != null && item.getModelObject() != null) {
					item.setOutputMarkupId(true);
					ResourceLoader rl = new ResourceLoader("dash_entity");

	                final CalendarLink cLink = (CalendarLink) item.getModelObject();
	                final CalendarItem cItem = cLink.getCalendarItem();

	                if(logger.isDebugEnabled()) {
	                	logger.debug(this + "populateItem()  item: " + item);
	                }

	                String itemType = cItem.getSourceType().getIdentifier();
	                item.add(new Label("itemType", itemType));
	                item.add(new Label("itemCount", "1"));
	                item.add(new Label("entityReference", cItem.getEntityReference()));
	                Component timeLabel = new Label("calendarDate", DateUtil.getCalendarTimeString(cItem.getCalendarTime()));
	                timeLabel.add(new AttributeModifier("title", true, new AbstractReadOnlyModel(){

						@Override
						public Object getObject() {
							// TODO Auto-generated method stub
							return DateUtil.getFullDateString(cItem.getCalendarTime());
						}

	                }));
					item.add(timeLabel );
	                //item.add(new Label("calendarTime", new SimpleDateFormat(TIME_FORMAT).format(cItem.getCalendarTime())));

	                Image icon = new Image("icon");
	                icon.add(new AttributeModifier("src", true, new AbstractReadOnlyModel(){

						@Override
						public Object getObject() {
							// TODO Auto-generated method stub
							return dashboardCommonLogic.getEntityIconUrl(cItem.getSourceType().getIdentifier(), cItem.getSubtype());
						}

	                }));
	                item.add(icon);
	                StringBuilder errorMessages = new StringBuilder();
					String title = FormattedText.processFormattedText(cItem.getTitle(), errorMessages , true, true);
					if(errorMessages != null && errorMessages.length() > 0) {
						logger.warn("Error(s) encountered while cleaning calendarItem title:\n" + errorMessages);
					}
					ExternalLink itemLink = new ExternalLink("itemLink", "#itemEvent");
					itemLink.add(new Label("itemTitle",title));
					itemLink.add(new Label("itemClick",rl.getString("dash.details")));
					item.add(itemLink);

	                String calendarItemLabel = dashboardCommonLogic.getString(cItem.getCalendarTimeLabelKey(), "", itemType);
	                if(calendarItemLabel == null) {
	                	calendarItemLabel = "";
	                }
					item.add(new Label("itemLabel", calendarItemLabel ));
	                item.add(new ExternalLink("siteLink", cItem.getContext().getContextUrl(), cItem.getContext().getContextTitle()));

	                if(cLink.isSticky()) {
		                AjaxLink<CalendarLink> starringAction = new AjaxLink<CalendarLink>("starringAction") {
		                	protected long calendarItemId = cItem.getId();
		                	protected Component thisRow = item;

							@Override
							public void onClick(AjaxRequestTarget target) {
								logger.debug("starringAction onClick() called -- unstar ");
								// need to keep one item
								logger.debug(calendarItemId);
								//logger.debug(this.getModelObject());

								String sakaiUserId = sakaiProxy.getCurrentUserId();
								boolean success = dashboardCommonLogic.unkeepCalendarItem(sakaiUserId, calendarItemId);
								dashboardCommonLogic.recordDashboardActivity(DashboardCommonLogic.EVENT_DASH_UNSTAR, "/dashboard/calendar/" + selectedCalendarTab + "/" + calendarItemId);

								// if success adjust UI, else report failure?
								if(success) {
									target.addComponent(CalendarLinksPanel.this);
									if(TAB_ID_STARRED.equals(selectedCalendarTab)) {
										ResourceLoader rl = new ResourceLoader("dash_entity");

										CalendarItem changedItem = dashboardCommonLogic.getCalendarItem(calendarItemId);
										JsonHelper jsonHelper = new JsonHelper(dashboardCommonLogic, dashboardConfig);
										String jsonStr = jsonHelper.getJsonObjectFromCalendarItem(changedItem).toString();
										String javascript = "reportSuccess('" + rl.getString("dash.ajax.unstar.success") + "'," + jsonStr + ",'" + "not-sure-about-url-yet" + "');";
										target.appendJavascript(javascript);
										target.appendJavascript("resizeFrame('grow');");
										target.appendJavascript("$('#schedPanel').focus();");
									}
								}
							}

		                };

		                starringAction.setDefaultModel(item.getModel());
		                item.add(starringAction);

						Image starringActionIcon = new Image("starringActionIcon");
						starringActionIcon.add(new AttributeModifier("src", true, new AbstractReadOnlyModel(){

							@Override
							public Object getObject() {
								return dashboardConfig.getActionIcon(dashboardConfig.ACTION_UNSTAR);
							}

						}));
						starringActionIcon.add(new AttributeModifier("alt", true, new AbstractReadOnlyModel(){

							@Override
							public Object getObject() {
								ResourceLoader rl = new ResourceLoader("dash_entity");
								return rl.getString("dash.unstar");
							}

						}));
						starringAction.add(starringActionIcon);
		                //starringAction.add(new Label("starringActionLabel", "Unstar"));

		                if(cLink.isHidden()) {
		                	// this shouldn't happen, but just in case ...
		                	starringAction.setVisible(false);
		                	starringAction.setVisibilityAllowed(false);
		                }
	                } else {
		                AjaxLink<CalendarLink> starringAction = new AjaxLink<CalendarLink>("starringAction") {
		                	protected long calendarItemId = cItem.getId();
		                	protected Component thisRow = item;

							@Override
							public void onClick(AjaxRequestTarget target) {
								logger.debug("starringAction onClick() called -- star ");
								// need to keep one item
								logger.debug(calendarItemId);
								//logger.debug(this.getModelObject());

								ResourceLoader rl = new ResourceLoader("dash_entity");

								String sakaiUserId = sakaiProxy.getCurrentUserId();
								boolean success = dashboardCommonLogic.keepCalendarItem(sakaiUserId, calendarItemId);
								dashboardCommonLogic.recordDashboardActivity(DashboardCommonLogic.EVENT_DASH_STAR, "/dashboard/calendar/" + selectedCalendarTab + "/" + calendarItemId);

								// if success adjust UI, else report failure?
								if(success) {
									target.addComponent(CalendarLinksPanel.this);
									//String javascript = "alert('success. (" + thisRow.getMarkupId() + ")');";
									//target.appendJavascript(javascript );
									target.appendJavascript("resizeFrame('grow');");
									target.appendJavascript("$('#schedPanel').focus();");
								}
							}

		                };
						Image starringActionIcon = new Image("starringActionIcon");
						starringActionIcon.add(new AttributeModifier("src", true, new AbstractReadOnlyModel(){

							@Override
							public Object getObject() {
								return dashboardConfig.getActionIcon(dashboardConfig.ACTION_STAR);
							}

						}));
						starringActionIcon.add(new AttributeModifier("alt", true, new AbstractReadOnlyModel(){

							@Override
							public Object getObject() {
								ResourceLoader rl = new ResourceLoader("dash_entity");
								return rl.getString("dash.star");
							}

						}));
						starringAction.add(starringActionIcon);

		                //starringAction.add(new Label("starringActionLabel", "Star"));
		                item.add(starringAction);

		                if(cLink.isHidden()) {
		                	starringAction.setVisible(false);
		                	starringAction.setVisibilityAllowed(false);
		                }
	                }

	                if(cLink.isHidden()) {
		                AjaxLink<CalendarLink> hidingAction = new AjaxLink<CalendarLink>("hidingAction") {
		                	protected long calendarItemId = cItem.getId();
		                	protected Component thisRow = item;

							@Override
							public void onClick(AjaxRequestTarget target) {
								logger.debug("hidingAction onClick() called -- show");
								// need to trash one item
								logger.debug(calendarItemId);
								//logger.debug(this.getModelObject());
								String sakaiUserId = sakaiProxy.getCurrentUserId();
								boolean success = dashboardCommonLogic.unhideCalendarItem(sakaiUserId, calendarItemId);
								dashboardCommonLogic.recordDashboardActivity(DashboardCommonLogic.EVENT_DASH_SHOW, "/dashboard/calendar/" + selectedCalendarTab + "/" + calendarItemId);

								// if success adjust UI, else report failure?
								if(success) {
									ResourceLoader rl = new ResourceLoader("dash_entity");

									target.addComponent(CalendarLinksPanel.this);
									CalendarItem changedItem = dashboardCommonLogic.getCalendarItem(calendarItemId);
									JsonHelper jsonHelper = new JsonHelper(dashboardCommonLogic, dashboardConfig);
									String jsonStr = jsonHelper.getJsonObjectFromCalendarItem(changedItem).toString();
									String javascript = "reportSuccess('" + rl.getString("dash.ajax.show.success") + "'," + jsonStr + ",'" + "not-sure-about-url-yet" + "');";
									target.appendJavascript(javascript );
									target.appendJavascript("resizeFrame('grow');");
									target.appendJavascript("$('#schedPanel').focus();");
								}
							}

		                };
		                hidingAction.setDefaultModel(item.getModel());
		                //actionHideThisLink.setModelObject(cItem);
		                item.add(hidingAction);
						Image hidingActionIcon = new Image("hidingActionIcon");
						hidingActionIcon.add(new AttributeModifier("src", true, new AbstractReadOnlyModel(){

							@Override
							public Object getObject() {
								return dashboardConfig.getActionIcon(dashboardConfig.ACTION_SHOW);
							}

						}));
						hidingActionIcon.add(new AttributeModifier("alt", true, new AbstractReadOnlyModel(){

							@Override
							public Object getObject() {
								ResourceLoader rl = new ResourceLoader("dash_entity");
								return rl.getString("dash.show");
							}

						}));
						hidingAction.add(hidingActionIcon);
		                //hidingAction.add(new Label("hidingActionLabel", "Show"));

		                if(cLink.isSticky() || TAB_ID_PAST.equals(selectedCalendarTab)) {
		                	// this shouldn't happen, but just in case ...
		                	hidingAction.setVisible(false);
		                	hidingAction.setVisibilityAllowed(false);
		                }

	                } else {
		                AjaxLink<CalendarLink> hidingAction = new AjaxLink<CalendarLink>("hidingAction") {
		                	protected long calendarItemId = cItem.getId();
		                	protected Component thisRow = item;

							@Override
							public void onClick(AjaxRequestTarget target) {
								logger.debug("hidingAction onClick() called -- hide");
								// need to trash one item
								logger.debug(calendarItemId);
								//logger.debug(this.getModelObject());
								String sakaiUserId = sakaiProxy.getCurrentUserId();
								boolean success = dashboardCommonLogic.hideCalendarItem(sakaiUserId, calendarItemId);
								dashboardCommonLogic.recordDashboardActivity(DashboardCommonLogic.EVENT_DASH_HIDE, "/dashboard/calendar/" + selectedCalendarTab + "/" + calendarItemId);

								// if success adjust UI, else report failure?
								if(success) {
									ResourceLoader rl = new ResourceLoader("dash_entity");
									//renderItemCounter(calendarLinksDiv, calendarDataView);
									target.addComponent(CalendarLinksPanel.this);

									CalendarItem changedItem = dashboardCommonLogic.getCalendarItem(calendarItemId);
									JsonHelper jsonHelper = new JsonHelper(dashboardCommonLogic, dashboardConfig);
									String jsonStr = jsonHelper.getJsonObjectFromCalendarItem(changedItem).toString();
									String javascript = "reportSuccess('" + rl.getString("dash.ajax.hide.success") + "'," + jsonStr + ",'" + "not-sure-about-url-yet" + "');";
									target.appendJavascript(javascript );
									target.appendJavascript("resizeFrame('grow');");
									target.appendJavascript("$('#schedPanel').focus();");
								}
							}

		                };
		                hidingAction.setDefaultModel(item.getModel());

		                //actionHideThisLink.setModelObject(cItem);
		                item.add(hidingAction);
						Image hidingActionIcon = new Image("hidingActionIcon");
						hidingActionIcon.add(new AttributeModifier("src", true, new AbstractReadOnlyModel(){

							@Override
							public Object getObject() {
								return dashboardConfig.getActionIcon(dashboardConfig.ACTION_HIDE);
							}

						}));
						hidingActionIcon.add(new AttributeModifier("alt", true, new AbstractReadOnlyModel(){

							@Override
							public Object getObject() {
								ResourceLoader rl = new ResourceLoader("dash_entity");
								return rl.getString("dash.hide");
							}

						}));
						hidingAction.add(hidingActionIcon);
		                //hidingAction.add(new Label("hidingActionLabel", "Hide"));

		                if(cLink.isSticky() || TAB_ID_PAST.equals(selectedCalendarTab)) {
			                hidingAction.setVisible(false);
		                	hidingAction.setVisibilityAllowed(false);
		                }

	                }

				}
			}
        };
        calendarDataView.setItemReuseStrategy(new DefaultItemReuseStrategy());
        calendarDataView.setItemsPerPage(pageSize);
        haveLinks.add(calendarDataView);

        IPagingLabelProvider pagingLabelProvider = new IPagingLabelProvider() {

			public String getPageLabel(int page) {
		        ResourceLoader rl = new ResourceLoader("dash_entity");

				int itemCount = 0;
				String pagerStatus = "";
				if(calendarDataView != null) {
				    int first = 0;
				    int last = 0;
					itemCount = calendarDataView.getItemCount();
				    int pageSize = calendarDataView.getItemsPerPage();
					if(itemCount > pageSize) {
						//int page = calendarDataView.getCurrentPage();
						first = page * pageSize + 1;
						last = Math.min(itemCount, (page + 1) * pageSize);
						if(first == last) {
				    		pagerStatus = Integer.toString(first);
						} else {
				    		pagerStatus = rl.getFormattedMessage("dash.pager.range", new Object[]{new Integer(first), new Integer(last)});
						}
					} else if(itemCount > 1) {
						pagerStatus = rl.getFormattedMessage("dash.pager.range", new Object[]{new Integer(1), new Integer(itemCount)});
					} else if(itemCount > 0) {
						pagerStatus = "1";
					} else {
						pagerStatus = "0";
					}
				}
				if(logger.isDebugEnabled()) {
					logger.debug("getPageLabel() " + pagerStatus);
				}
				return pagerStatus;
			}
        };
		//add a pager to our table, only visible if we have more than 5 items
        calendarLinksDiv.add(new PagingNavigator("calendarNavigator", calendarDataView, pagingLabelProvider ) {

        	protected int currentPage = 1;

        	@Override
        	public boolean isVisible() {
        		if(calendarLinksProvider != null && calendarLinksProvider.size() > pageSize) {
        			return true;
        		}
        		return false;
        	}

        	@Override
        	public void onBeforeRender() {
        		super.onBeforeRender();

        		if(this.getPageable().getCurrentPage() != currentPage) {
    				dashboardCommonLogic.recordDashboardActivity(DashboardCommonLogic.EVENT_DASH_PAGING, "/dashboard/calendar/" + selectedCalendarTab);
    				currentPage = this.getPageable().getCurrentPage();
        		}

        		//renderItemCounter(calendarLinksDiv, (DataView<CalendarLink>) getPageable());

        		//clear the feedback panel messages
        		//clearFeedback(feedbackPanel);
        	}

        });

        WebMarkupContainer haveNoLinks = new WebMarkupContainer("haveNoLinks");
        calendarLinksDiv.add(haveNoLinks);

        String noCalendarLinksLabel = null;
		if(TAB_ID_UPCOMING.equals(selectedCalendarTab)) {
			noCalendarLinksLabel = rl.getString("dash.calendar.noupcoming");
		} else if(TAB_ID_PAST.equals(selectedCalendarTab)) {
			noCalendarLinksLabel = rl.getString("dash.calendar.nopast");
		} else if(TAB_ID_STARRED.equals(selectedCalendarTab)) {
			noCalendarLinksLabel = rl.getString("dash.calendar.nostarred");
		} else if(TAB_ID_HIDDEN.equals(selectedCalendarTab)) {
			noCalendarLinksLabel = rl.getString("dash.calendar.nohidden");
		}
		haveNoLinks.add(new Label("message", noCalendarLinksLabel));

		//renderItemCounter(calendarLinksDiv, calendarDataView);

        int itemCount = 0;
        if(calendarDataView != null) {
        	itemCount = calendarDataView.getItemCount();
        }

        if(itemCount > 0) {
        	// show the haveLinks
        	haveLinks.setVisible(true);
        	// hide the haveNoLinks
        	haveNoLinks.setVisible(false);
        } else {
        	// show the haveNoLinks
        	haveNoLinks.setVisible(true);
        	// hide the haveLinks
        	haveLinks.setVisible(false);
        }
	}

	/**
	 * @param rl
	 * @param calendarLinksDiv
	 * @param calendarDataView
	 */
	protected void renderItemCounter(WebMarkupContainer calendarLinksDiv,
			DataView<CalendarLink> calendarDataView) {

		ResourceLoader rl = new ResourceLoader("dash_entity");

		if(calendarLinksCountId != null) {
			Iterator itx = calendarLinksDiv.iterator();
			while(itx.hasNext()) {
				Component child = (Component) itx.next();
				if(calendarLinksCountId.equals(child.getId())) {
					calendarLinksDiv.remove(child);
					break;
				}
			}
		}

		int itemCount = 0;
		String pagerStatus = "";
		if(calendarDataView != null) {
		    int first = 0;
		    int last = 0;
			itemCount = calendarDataView.getItemCount();
		    int pageSize = calendarDataView.getItemsPerPage();
			if(itemCount > pageSize) {
				int page = calendarDataView.getCurrentPage();
				first = page * pageSize + 1;
				last = Math.min(itemCount, (page + 1) * pageSize);
				if(first == last) {
		    		pagerStatus = rl.getFormattedMessage("dash.calendar.linksCount2", new Object[]{new Integer(first), new Integer(itemCount)});
				} else {
		    		pagerStatus = rl.getFormattedMessage("dash.calendar.linksCount3", new Object[]{new Integer(first), new Integer(last), new Integer(itemCount)});
				}
			} else if(itemCount > 1) {
				pagerStatus = rl.getFormattedMessage("dash.calendar.linksCount3", new Object[]{new Integer(1), new Integer(itemCount), new Integer(itemCount)});
			} else if(itemCount > 0) {
				pagerStatus = rl.getString("dash.calendar.linksCount1");
			} else {
				pagerStatus = rl.getString("dash.calendar.linksCount0");
			}
		}
		Label calendarLinksCount = new Label("calendarLinksCount", pagerStatus);
    	// add the count to the calendarLinksDiv
        calendarLinksDiv.add(calendarLinksCount);
        calendarLinksCountId = calendarLinksCount.getId();
	}

	private class CalendarLinkListDataProvider implements IDataProvider<List<CalendarLink>> {

		public void detach() {
			// TODO Auto-generated method stub

		}

		public Iterator<? extends List<CalendarLink>> iterator(int first, int count) {
			// TODO Auto-generated method stub
			return null;
		}

		public int size() {

			return 0;
		}

		public IModel<List<CalendarLink>> model(List<CalendarLink> object) {
			// TODO Auto-generated method stub
			return null;
		}

	}

	/**
	 * DataProvider to manage our list
	 *
	 */
	private class CalendarLinksDataProvider implements IDataProvider<CalendarLink> {

		private List<CalendarLink> calendarLinks;
		private String calendarTabId;

		public CalendarLinksDataProvider() {
			super();
		}

		public CalendarLinksDataProvider(String calendarTabId) {
			super();
			this.calendarTabId = calendarTabId;
			if(this.calendarTabId == null) {
				this.calendarTabId = TAB_ID_UPCOMING;
			}
		}

		public void setCalendarTab(String calendarTabId) {
			if(this.calendarTabId == null || ! this.calendarTabId.equals(calendarTabId)) {
				// force refresh of dataProvider
				this.calendarLinks = null;
			}
			this.calendarTabId = calendarTabId;

		}

		private List<CalendarLink> getData() {

			if(calendarLinks == null) {
				String siteId = sakaiProxy.getCurrentSiteId();
				String sakaiId = sakaiProxy.getCurrentUserId();
				if(siteId == null || sakaiId == null) {
					if(logger.isDebugEnabled()) {
						logger.debug("CalendarLinkDataProvider.getData() siteId:" + siteId + "  sakaiId:" + sakaiId);
					}
					return new ArrayList<CalendarLink>();
				}
				if(TAB_ID_UPCOMING.equals(this.calendarTabId) && sakaiProxy.isWorksite(siteId)) {
					calendarLinks = dashboardCommonLogic.getFutureCalendarLinks(sakaiId, null, false);
				} else if(TAB_ID_UPCOMING.equals(this.calendarTabId)) {
					calendarLinks = dashboardCommonLogic.getFutureCalendarLinks(sakaiId, siteId, false);
				} else if(TAB_ID_STARRED.equals(this.calendarTabId) && sakaiProxy.isWorksite(siteId)) {
					calendarLinks = dashboardCommonLogic.getStarredCalendarLinks(sakaiId, null);
				} else if(TAB_ID_STARRED.equals(this.calendarTabId)) {
					calendarLinks = dashboardCommonLogic.getStarredCalendarLinks(sakaiId, siteId);
				} else if(TAB_ID_PAST.equals(this.calendarTabId) && sakaiProxy.isWorksite(siteId)) {
					calendarLinks = dashboardCommonLogic.getPastCalendarLinks(sakaiId, null, false);
				} else if(TAB_ID_PAST.equals(this.calendarTabId) ) {
					calendarLinks = dashboardCommonLogic.getPastCalendarLinks(sakaiId, siteId, false);
				} else if(TAB_ID_HIDDEN.equals(this.calendarTabId) && sakaiProxy.isWorksite(siteId)) {
					calendarLinks = dashboardCommonLogic.getFutureCalendarLinks(sakaiId, null, true);
				} else if(TAB_ID_HIDDEN.equals(this.calendarTabId)) {
					calendarLinks = dashboardCommonLogic.getFutureCalendarLinks(sakaiId, siteId, true);
				} else if(TAB_ID_PAST_HIDDEN.equals(this.calendarTabId) && sakaiProxy.isWorksite(siteId)) {
					calendarLinks = dashboardCommonLogic.getPastCalendarLinks(sakaiId, null, false);
				} else {
					calendarLinks = dashboardCommonLogic.getPastCalendarLinks(sakaiId, siteId, false);
				}
			}
			if(calendarLinks == null) {
				logger.warn("Error getting calendarLinks");
				return new ArrayList<CalendarLink>();
			}
			return calendarLinks;
		}

		public Iterator<CalendarLink> iterator(int first, int count){
			return getData().subList(first, first + count).iterator();
		}

		public int size(){
			return getData().size();
		}

		public IModel<CalendarLink> model(CalendarLink object){
			return new DetachableCalendarLinkModel(object);
		}

		public void detach(){
			calendarLinks = null;
		}
	}

	/**
	 * Detachable model to wrap a CalendarLink
	 *
	 */
	private class DetachableCalendarLinkModel extends LoadableDetachableModel<CalendarLink>{

		private Long id = null;

		/**
		 * @param m
		 */
		public DetachableCalendarLinkModel(CalendarLink t){
			this.id = t.getId();
		}

		/**
		 * @param id
		 */
		public DetachableCalendarLinkModel(long id){
			this.id = id;
		}

		/**
		 * @see java.lang.Object#hashCode()
		 */
		public int hashCode() {
			return Long.valueOf(id).hashCode();
		}

		/**
		 * used for dataview with ReuseIfModelsEqualStrategy item reuse strategy
		 *
		 * @see org.apache.wicket.markup.repeater.ReuseIfModelsEqualStrategy
		 * @see java.lang.Object#equals(java.lang.Object)
		 */
		public boolean equals(final Object obj){
			if (obj == this){
				return true;
			}
			else if (obj == null){
				return false;
			}
			else if (obj instanceof DetachableCalendarLinkModel) {
				DetachableCalendarLinkModel other = (DetachableCalendarLinkModel)obj;
				return other.id == id;
			}
			return false;
		}

		/**
		 * @see org.apache.wicket.model.LoadableDetachableModel#load()
		 */
		protected CalendarLink load(){

			// get the calendar item
			return dashboardCommonLogic.getCalendarLink(id);
		}
	}

}


text:
namespace MultipleForms
{
    partial class AdminFrm
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.menuStrip1 = new System.Windows.Forms.MenuStrip();
            this.addToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.returnToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.lblTitle = new System.Windows.Forms.Label();
            this.label1 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.txtBxShowName = new System.Windows.Forms.TextBox();
            this.txtBxShowCost = new System.Windows.Forms.TextBox();
            this.menuStrip1.SuspendLayout();
            this.SuspendLayout();
            //
            // menuStrip1
            //
            this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.addToolStripMenuItem,
            this.returnToolStripMenuItem});
            this.menuStrip1.Location = new System.Drawing.Point(0, 0);
            this.menuStrip1.Name = "menuStrip1";
            this.menuStrip1.Size = new System.Drawing.Size(627, 24);
            this.menuStrip1.TabIndex = 0;
            this.menuStrip1.Text = "menuStrip1";
            //
            // addToolStripMenuItem
            //
            this.addToolStripMenuItem.Name = "addToolStripMenuItem";
            this.addToolStripMenuItem.Size = new System.Drawing.Size(41, 20);
            this.addToolStripMenuItem.Text = "Add";
            this.addToolStripMenuItem.Click += new System.EventHandler(this.addToolStripMenuItem_Click);
            //
            // returnToolStripMenuItem
            //
            this.returnToolStripMenuItem.Name = "returnToolStripMenuItem";
            this.returnToolStripMenuItem.Size = new System.Drawing.Size(62, 20);
            this.returnToolStripMenuItem.Text = "Log Out";
            this.returnToolStripMenuItem.Click += new System.EventHandler(this.returnToolStripMenuItem_Click);
            //
            // lblTitle
            //
            this.lblTitle.AutoSize = true;
            this.lblTitle.Font = new System.Drawing.Font("Segoe UI Symbol", 20.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.lblTitle.Location = new System.Drawing.Point(157, 42);
            this.lblTitle.Name = "lblTitle";
            this.lblTitle.Size = new System.Drawing.Size(313, 37);
            this.lblTitle.TabIndex = 9;
            this.lblTitle.Text = "ISIIA BLOCK 1 PROJECT";
            //
            // label1
            //
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(67, 142);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(93, 13);
            this.label1.TabIndex = 10;
            this.label1.Text = "Enter Show Name";
            //
            // label2
            //
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(67, 184);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(86, 13);
            this.label2.TabIndex = 11;
            this.label2.Text = "Enter Show Cost";
            //
            // txtBxShowName
            //
            this.txtBxShowName.Location = new System.Drawing.Point(185, 142);
            this.txtBxShowName.Name = "txtBxShowName";
            this.txtBxShowName.Size = new System.Drawing.Size(353, 20);
            this.txtBxShowName.TabIndex = 12;
            //
            // txtBxShowCost
            //
            this.txtBxShowCost.Location = new System.Drawing.Point(185, 184);
            this.txtBxShowCost.Name = "txtBxShowCost";
            this.txtBxShowCost.Size = new System.Drawing.Size(353, 20);
            this.txtBxShowCost.TabIndex = 13;
            //
            // AdminFrm
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(627, 432);
            this.Controls.Add(this.txtBxShowCost);
            this.Controls.Add(this.txtBxShowName);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.lblTitle);
            this.Controls.Add(this.menuStrip1);
            this.MainMenuStrip = this.menuStrip1;
            this.Name = "AdminFrm";
            this.Text = "Admin";
            this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
            this.menuStrip1.ResumeLayout(false);
            this.menuStrip1.PerformLayout();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.MenuStrip menuStrip1;
        private System.Windows.Forms.ToolStripMenuItem addToolStripMenuItem;
        private System.Windows.Forms.ToolStripMenuItem returnToolStripMenuItem;
        private System.Windows.Forms.Label lblTitle;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.TextBox txtBxShowName;
        private System.Windows.Forms.TextBox txtBxShowCost;
    }
}


text:
/* Written by Sergei A. Golubchik, who has a shared copyright to this code */

/* some definitions for full-text indices */

#include "fulltext.h"
#include <m_ctype.h>
#include <my_tree.h>
#include <queues.h>
#include <mysql/plugin.h>

#define true_word_char(ctype, character) \
                      ((ctype) & (_MY_U | _MY_L | _MY_NMR) || \
                       (character) == '_')
#define misc_word_char(X)	0

#define FT_MAX_WORD_LEN_FOR_SORT 31

#define FTPARSER_MEMROOT_ALLOC_SIZE 65536

#define COMPILE_STOPWORDS_IN

/* Interested readers may consult SMART
   (ftp://ftp.cs.cornell.edu/pub/smart/smart.11.0.tar.Z)
   for an excellent implementation of vector space model we use.
   It also demonstrate the usage of different weghting techniques.
   This code, though, is completely original and is not based on the
   SMART code but was in some cases inspired by it.

   NORM_PIVOT was taken from the article
   A.Singhal, C.Buckley, M.Mitra, "Pivoted Document Length Normalization",
   ACM SIGIR'96, 21-29, 1996
 */

#define LWS_FOR_QUERY					  LWS_TF
#define LWS_IN_USE					 LWS_LOG
#define PRENORM_IN_USE				     PRENORM_AVG
#define NORM_IN_USE				      NORM_PIVOT
#define GWS_IN_USE					GWS_PROB
/*==============================================================*/
#define LWS_TF						  (count)
#define LWS_BINARY					(count>0)
#define LWS_SQUARE				    (count*count)
#define LWS_LOG				 (count?(log( (double) count)+1):0)
/*--------------------------------------------------------------*/
#define PRENORM_NONE				      (p->weight)
#define PRENORM_MAX			  (p->weight/docstat.max)
#define PRENORM_AUG		  (0.4+0.6*p->weight/docstat.max)
#define PRENORM_AVG	     (p->weight/docstat.sum*docstat.uniq)
#define PRENORM_AVGLOG ((1+log(p->weight))/(1+log(docstat.sum/docstat.uniq)))
/*--------------------------------------------------------------*/
#define NORM_NONE					      (1)
#define NORM_SUM				   (docstat.nsum)
#define NORM_COS			    (sqrt(docstat.nsum2))

#define PIVOT_VAL (0.0115)
#define NORM_PIVOT  (1+PIVOT_VAL*docstat.uniq)
/*---------------------------------------------------------------*/
#define GWS_NORM				     (1/sqrt(sum2))
#define GWS_GFIDF				      (sum/doc_cnt)
/* Mysterious, but w/o (double) GWS_IDF performs better :-o */
#define GWS_IDF		   log(aio->info->state->records/doc_cnt)
#define GWS_IDF1	   log((double)aio->info->state->records/doc_cnt)
#define GWS_PROB ((aio->info->state->records > doc_cnt) ? log(((double)(aio->info->state->records-doc_cnt))/doc_cnt) : 0 )
#define GWS_FREQ					(1.0/doc_cnt)
#define GWS_SQUARED pow(log((double)aio->info->state->records/doc_cnt),2)
#define GWS_CUBIC   pow(log((double)aio->info->state->records/doc_cnt),3)
#define GWS_ENTROPY (1-(suml/sum-log(sum))/log(aio->info->state->records))
/*=================================================================*/

/* Boolean search operators */
#define FTB_YES   (ft_boolean_syntax[0])
#define FTB_EGAL  (ft_boolean_syntax[1])
#define FTB_NO    (ft_boolean_syntax[2])
#define FTB_INC   (ft_boolean_syntax[3])
#define FTB_DEC   (ft_boolean_syntax[4])
#define FTB_LBR   (ft_boolean_syntax[5])
#define FTB_RBR   (ft_boolean_syntax[6])
#define FTB_NEG   (ft_boolean_syntax[7])
#define FTB_TRUNC (ft_boolean_syntax[8])
#define FTB_LQUOT (ft_boolean_syntax[10])
#define FTB_RQUOT (ft_boolean_syntax[11])

typedef struct st_ft_word {
  uchar * pos;
  uint	 len;
  double weight;
} FT_WORD;

int is_stopword(char *word, uint len);

uint _ft_make_key(MI_INFO *, uint , uchar *, FT_WORD *, my_off_t);

uchar ft_get_word(CHARSET_INFO *, uchar **, uchar *, FT_WORD *,
                  MYSQL_FTPARSER_BOOLEAN_INFO *);
uchar ft_simple_get_word(CHARSET_INFO *, uchar **, const uchar *,
                         FT_WORD *, my_bool);

typedef struct _st_ft_seg_iterator {
  uint        num, len;
  HA_KEYSEG  *seg;
  const uchar *rec, *pos;
} FT_SEG_ITERATOR;

void _mi_ft_segiterator_init(MI_INFO *, uint, const uchar *, FT_SEG_ITERATOR *);
void _mi_ft_segiterator_dummy_init(const uchar *, uint, FT_SEG_ITERATOR *);
uint _mi_ft_segiterator(FT_SEG_ITERATOR *);

void ft_parse_init(TREE *, CHARSET_INFO *);
int ft_parse(TREE *, uchar *, int, struct st_mysql_ftparser *parser,
             MYSQL_FTPARSER_PARAM *, MEM_ROOT *);
FT_WORD * ft_linearize(TREE *, MEM_ROOT *);
FT_WORD * _mi_ft_parserecord(MI_INFO *, uint, const uchar *, MEM_ROOT *);
uint _mi_ft_parse(TREE *, MI_INFO *, uint, const uchar *,
                  MYSQL_FTPARSER_PARAM *, MEM_ROOT *);

FT_INFO *ft_init_nlq_search(MI_INFO *, uint, uchar *, uint, uint, uchar *);
FT_INFO *ft_init_boolean_search(MI_INFO *, uint, uchar *, uint, CHARSET_INFO *);

extern const struct _ft_vft _ft_vft_nlq;
int ft_nlq_read_next(FT_INFO *, char *);
float ft_nlq_find_relevance(FT_INFO *, uchar *, uint);
void ft_nlq_close_search(FT_INFO *);
float ft_nlq_get_relevance(FT_INFO *);
my_off_t ft_nlq_get_docid(FT_INFO *);
void ft_nlq_reinit_search(FT_INFO *);

extern const struct _ft_vft _ft_vft_boolean;
int ft_boolean_read_next(FT_INFO *, char *);
float ft_boolean_find_relevance(FT_INFO *, uchar *, uint);
void ft_boolean_close_search(FT_INFO *);
float ft_boolean_get_relevance(FT_INFO *);
my_off_t ft_boolean_get_docid(FT_INFO *);
void ft_boolean_reinit_search(FT_INFO *);
MYSQL_FTPARSER_PARAM* ftparser_alloc_param(MI_INFO *info);
extern MYSQL_FTPARSER_PARAM *ftparser_call_initializer(MI_INFO *info,
                                                       uint keynr,
                                                       uint paramnr);
extern void ftparser_call_deinitializer(MI_INFO *info);


text:
var logviewerApp = angular.module("logviewerApp");

logviewerApp.controller("ChannelListController", function($rootScope, $scope, $http, $stateParams, $window){
	$scope.channels = [];
	$scope.channellimit = 80;
	$scope.channelSearch = {};

	// todo: dynamic channellimit based on window width+height. Average item width is ~ 130px, height 51px
	var calcChannellimit = function () {
		var availableWidth = 0.7 * window.innerWidth;
		var availableHeight = window.innerHeight - 450; // 450px get used on the header, footer, title, show more and search

		$scope.channellimit = Math.max(5, Math.floor(availableHeight * availableWidth / (130 * 51)));
	}

	angular.element($window).bind('resize', function(){
		$scope.$apply(function(){
			if(isFinite($scope.channellimit)) calcChannellimit();
		});
	});
	calcChannellimit();

	var updateChannels = function(){
		$http.get("/api/channels/").then(function(response) {
			$scope.channels = response.data;
		});
	}

	// update every 2 minutes
	var interval = setInterval(updateChannels,2*60000);

	$scope.$on('$destroy', function() {
		clearInterval(interval);
	});
	updateChannels();
});

logviewerApp.filter("orderChannels", function() {
	return function(channels) {
		return channels.slice().sort(function(a,b){
			if(a.live < b.live) return 1;
			if(a.live > b.live) return -1;
			if(a.ispremium < b.ispremium) return 1;
			if(a.ispremium > b.ispremium) return -1;
			if(a.name > b.name) return 1;
			if(a.name < b.name) return -1;
		});
	}
});