text:
"""
@package ion.agents.instrument.test.test_vel3d
@file ion/agents.instrument/test_vel3d.py
@author Edward Hunter
@brief Test cases for vel3d instrument agent.
"""

__author__ = 'Edward Hunter'

# Import pyon first for monkey patching.

# Pyon log and config objects.
from pyon.public import log
from pyon.public import CFG

# Standard imports.
import sys
import time
import socket
import re
import json
import unittest
import os
import signal
import subprocess

# 3rd party imports.
import gevent
from gevent.event import AsyncResult
from nose.plugins.attrib import attr
from mock import patch
import numpy

# Pyon pubsub and event support.
from pyon.event.event import EventSubscriber, EventPublisher
from pyon.ion.stream import StandaloneStreamSubscriber
from ion.services.dm.utility.granule_utils import RecordDictionaryTool

# Pyon unittest support.
from pyon.util.int_test import IonIntegrationTestCase

# Pyon Object Serialization
from pyon.core.object import IonObjectSerializer

# Pyon exceptions.
from pyon.core.exception import BadRequest, Conflict, Timeout, ResourceError
from pyon.core.exception import IonException

# Agent imports.
from pyon.util.context import LocalContextMixin
from pyon.agent.agent import ResourceAgentClient
from pyon.agent.agent import ResourceAgentState
from pyon.agent.agent import ResourceAgentEvent

# Driver imports.
from ion.agents.instrument.direct_access.direct_access_server import DirectAccessTypes
from ion.agents.instrument.driver_int_test_support import DriverIntegrationTestSupport
from ion.agents.instrument.driver_process import DriverProcessType
from ion.agents.instrument.driver_process import ZMQEggDriverProcess

# Objects and clients.
from interface.objects import AgentCommand
from interface.objects import CapabilityType
from interface.objects import AgentCapability
from interface.services.icontainer_agent import ContainerAgentClient
from interface.services.dm.ipubsub_management_service import PubsubManagementServiceClient
from interface.services.dm.idataset_management_service import DatasetManagementServiceClient

"""
bin/nosetests -s -v --nologcapture ion/agents/instrument/test/test_vel3d.py:TestVel3d
bin/nosetests -s -v --nologcapture ion/agents/instrument/test/test_vel3d.py:TestVel3d.test_initialize
bin/nosetests -s -v --nologcapture ion/agents/instrument/test/test_vel3d.py:TestVel3d.test_xx
"""

###############################################################################
# Global constants.
###############################################################################

# Work dir and logger delimiter.
WORK_DIR = '/tmp/'

from ion.agents.instrument.instrument_agent import InstrumentAgent
# Agent parameters.
IA_RESOURCE_ID = '123xyz'
IA_NAME = 'Agent007'
IA_MOD = 'ion.agents.instrument.instrument_agent'
IA_CLS = 'InstrumentAgent'

# Vel3d URI, Mod, Class.
DRV_URI = 'http://sddevrepo.oceanobservatories.org/releases/nobska_mavs4_ooicore-0.0.8-py2.7.egg'
DRV_MOD = 'mi.instrument.nobska.mavs4.ooicore.driver'
DRV_CLS = 'mavs4InstrumentDriver'

# Driver config.
# DVR_CONFIG['comms_config']['port'] is set by the setup.
DVR_CONFIG = {
    'dvr_egg' : DRV_URI,
    'dvr_mod' : DRV_MOD,
    'dvr_cls' : DRV_CLS,
    'workdir' : WORK_DIR,
    'process_type' : (DriverProcessType.EGG,),
    'comms_config' : {
                      'addr' : 'rsn-port-agent-test.oceanobservatories.org',
                      'port' : 13015,
                      'cmd_port' : 12015
    }
}

class TcpClient():
    '''
    TCP client for testing DA.
    '''

    # 'will echo' command sequence to be sent from DA telnet server
    # see RFCs 854 & 857
    WILL_ECHO_CMD = '\xff\xfd\x03\xff\xfb\x03\xff\xfb\x01'
    # 'do echo' command sequence to be sent back from telnet client
    DO_ECHO_CMD   = '\xff\xfb\x03\xff\xfd\x03\xff\xfd\x01'
    BUFFER_SIZE = 1024

    buf = ""

    def __init__(self, host = None, port = None):
        '''
        Constructor - open/connect to the socket
        @param host: host address
        @param port: host port
        '''
        self.buf = ""
        s = None

        if(host and port):
            self._connect(host, port)

    def _connect(self, host, port):
        log.debug("TcpClient._connect: host = " + str(host) + " port = " + str(port))
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.s.connect((host, port))
        self.s.settimeout(0.0)

    def disconnect(self):
        log.debug("TcpClient.disconnect:")
        if(self.s):
            self.s.close()
            self.s = None

    def do_telnet_handshake(self):
        if(self.expect(self.WILL_ECHO_CMD)):
            self.send_data(self.DO_ECHO_CMD)
            return True
        return False

    def start_telnet(self, token=None, handshake=True):

        def assert_success(function_to_call, *args):
            result = function_to_call(*args)
            log.debug("TcpClient.start_telnet.assert_success: result = %s" %result)
            if result == False:
                raise Exception("call [%s] failed" %str(function_to_call))

        gevent.sleep(1)   # give DA server a chance to start handler
        try:
            assert_success(self.expect, "Username: ")
            assert_success(self.send_data, "someone\r\n")
            if token:
                assert_success(self.expect, "token: ")
                assert_success(self.send_data, token + "\r\n")
            else:
                return True
            if handshake:
                assert_success(self.do_telnet_handshake)
                assert_success(self.expect, "connected\r\n")
        except Exception as ex:
            log.debug("TcpClient.start_telnet: exception caught [%s]" %str(ex))
            return False
        return True

    def send_data(self, data):
        if self.s == None:
            return False
        log.debug("TcpClient.send_data: data to send = [" + repr(data) + "]")
        try:
            self.s.sendall(data)
            return True
        except Exception as ex:
            log.debug("TcpClient.send_data: exception caught [%s] during sending" %ex)
            return False

    def expect(self, prompt, timeout=2):

        if self.s == None:
            return False
        self.buf = ''
        found = False
        starttime = time.time()

        log.debug('TcpClient.expect: prompt = [%s]' %prompt)
        while True:
            try:
                self.buf += self.s.recv(self.BUFFER_SIZE)
                log.debug('TcpClient.expect: buf = [%s]' % self.buf)
                if prompt and self.buf.find(prompt) != -1:
                    found = True
                    break
            except:
                gevent.sleep(.1)
            delta = time.time() - starttime
            if delta > timeout:
                break
        if prompt == None:
            return found, self.buf
        else:
            return found

class FakeProcess(LocalContextMixin):
    """
    A fake process used because the test case is not an ion process.
    """
    name = ''
    id=''
    process_type = ''

@attr('HARDWARE', group='sa')
@patch.dict(CFG, {'endpoint':{'receive':{'timeout': 600}}})
@unittest.skipIf((not os.getenv('PYCC_MODE', False)) and os.getenv('CEI_LAUNCH_TEST', False), 'Skip until tests support launch port agent configurations.')
class TestVel3d(IonIntegrationTestCase):
    """
    Test cases for instrument agent class. Functions in this class provide
    instrument agent integration tests and provide a tutorial on use of
    the agent setup and interface.
    """

    def setUp(self):

        """
        Set up driver integration support.
        Start port agent, add port agent cleanup.
        Start container.
        Start deploy services.
        Define agent config, start agent.
        Start agent client.
        """
        print '#####################'
        print 'IN SETUP'

        self._ia_client = None

        # Start container.
        log.info('Staring capability container.')
        self._start_container()

        # Bring up services in a deploy file (no need to message)
        log.info('Staring deploy services.')
        self.container.start_rel_from_url('res/deploy/r2deploy.yml')

        log.info('building stream configuration')
        # Setup stream config.
        self._build_stream_config()

        #log.info('driver uri: %s', DRV_URI)
        #log.info('device address: %s', DEV_ADDR)
        #log.info('device port: %s', DEV_PORT)
        #log.info('work dir: %s', WORK_DIR)

        # Create agent config.
        agent_config = {
            'driver_config' : DVR_CONFIG,
            'stream_config' : self._stream_config,
            'agent'         : {'resource_id': IA_RESOURCE_ID},
            'test_mode' : True,
            'forget_past' : True,
            'enable_persistence' : False
        }

        #if org_governance_name is not None:
        #    agent_config['org_governance_name'] = org_governance_name

        # Start instrument agent.

        log.info("TestInstrumentAgent.setup(): starting IA.")
        container_client = ContainerAgentClient(node=self.container.node,
            name=self.container.name)

        log.info("Agent setup")
        ia_pid = container_client.spawn_process(name=IA_NAME,
            module=IA_MOD,
            cls=IA_CLS,
            config=agent_config)
        log.info('Agent pid=%s.', str(ia_pid))
        #self.addCleanup(self._verify_agent_reset)

        # Start a resource agent client to talk with the instrument agent.

        self._ia_client = ResourceAgentClient(IA_RESOURCE_ID, process=FakeProcess())
        log.info('Got ia client %s.', str(self._ia_client))

        log.info('test setup complete')

    ###############################################################################
    # Port agent helpers.
    ###############################################################################

    def _verify_agent_reset(self):
        """
        Check agent state and reset if necessary.
        This called if a test fails and reset hasn't occurred.
        """
        if self._ia_client is None:
            return

        state = self._ia_client.get_agent_state()
        if state != ResourceAgentState.UNINITIALIZED:
            cmd = AgentCommand(command=ResourceAgentEvent.RESET)
            retval = self._ia_client.execute_agent(cmd)

    ###############################################################################
    # Event helpers.
    ###############################################################################

    def _start_event_subscriber(self, type='ResourceAgentEvent', count=0):
        """
        Start a subscriber to the instrument agent events.
        @param type The type of event to catch.
        @count Trigger the async event result when events received reaches this.
        """
        def consume_event(*args, **kwargs):
            log.info('Test recieved ION event: args=%s, kwargs=%s, event=%s.',
                     str(args), str(kwargs), str(args[0]))
            self._events_received.append(args[0])
            if self._event_count > 0 and \
                self._event_count == len(self._events_received):
                self._async_event_result.set()

        # Event array and async event result.
        self._event_count = count
        self._events_received = []
        self._async_event_result = AsyncResult()

        self._event_subscriber = EventSubscriber(
            event_type=type, callback=consume_event,
            origin=IA_RESOURCE_ID)
        self._event_subscriber.start()
        self._event_subscriber._ready_event.wait(timeout=5)

    def _stop_event_subscriber(self):
        """
        Stop event subscribers on cleanup.
        """
        self._event_subscriber.stop()
        self._event_subscriber = None

    ###############################################################################
    # Data stream helpers.
    ###############################################################################

    def _build_stream_config(self):
        """
        """
        # Create a pubsub client to create streams.
        pubsub_client = PubsubManagementServiceClient(node=self.container.node)
        dataset_management = DatasetManagementServiceClient()

        encoder = IonObjectSerializer()

        # Create streams and subscriptions for each stream named in driver.
        self._stream_config = {}

        stream_name = 'parsed'
        param_dict_name = 'ctd_parsed_param_dict'
        pd_id = dataset_management.read_parameter_dictionary_by_name(param_dict_name, id_only=True)
        stream_def_id = pubsub_client.create_stream_definition(name=stream_name, parameter_dictionary_id=pd_id)
        stream_def = pubsub_client.read_stream_definition(stream_def_id)
        stream_def_dict = encoder.serialize(stream_def)
        pd = stream_def.parameter_dictionary
        stream_id, stream_route = pubsub_client.create_stream(name=stream_name,
                                                exchange_point='science_data',
                                                stream_definition_id=stream_def_id)
        stream_config = dict(routing_key=stream_route.routing_key,
                                 exchange_point=stream_route.exchange_point,
                                 stream_id=stream_id,
                                 parameter_dictionary=pd,
                                 stream_def_dict=stream_def_dict)
        self._stream_config[stream_name] = stream_config

        stream_name = 'raw'
        param_dict_name = 'ctd_raw_param_dict'
        pd_id = dataset_management.read_parameter_dictionary_by_name(param_dict_name, id_only=True)
        stream_def_id = pubsub_client.create_stream_definition(name=stream_name, parameter_dictionary_id=pd_id)
        stream_def = pubsub_client.read_stream_definition(stream_def_id)
        stream_def_dict = encoder.serialize(stream_def)
        pd = stream_def.parameter_dictionary
        stream_id, stream_route = pubsub_client.create_stream(name=stream_name,
                                                exchange_point='science_data',
                                                stream_definition_id=stream_def_id)
        stream_config = dict(routing_key=stream_route.routing_key,
                                 exchange_point=stream_route.exchange_point,
                                 stream_id=stream_id,
                                 parameter_dictionary=pd,
                                 stream_def_dict=stream_def_dict)
        self._stream_config[stream_name] = stream_config

    def _start_data_subscribers(self, count, raw_count):
        """
        """
        # Create a pubsub client to create streams.
        pubsub_client = PubsubManagementServiceClient(node=self.container.node)

        # Create streams and subscriptions for each stream named in driver.
        self._data_subscribers = []
        self._samples_received = []
        self._raw_samples_received = []
        self._async_sample_result = AsyncResult()
        self._async_raw_sample_result = AsyncResult()

        # A callback for processing subscribed-to data.
        def recv_data(message, stream_route, stream_id):
            log.info('Received parsed data on %s (%s,%s)', stream_id, stream_route.exchange_point, stream_route.routing_key)
            self._samples_received.append(message)
            if len(self._samples_received) == count:
                self._async_sample_result.set()

        def recv_raw_data(message, stream_route, stream_id):
            log.info('Received raw data on %s (%s,%s)', stream_id, stream_route.exchange_point, stream_route.routing_key)
            self._raw_samples_received.append(message)
            if len(self._raw_samples_received) == raw_count:
                self._async_raw_sample_result.set()

        from pyon.util.containers import create_unique_identifier

        stream_name = 'parsed'
        parsed_config = self._stream_config[stream_name]
        stream_id = parsed_config['stream_id']
        exchange_name = create_unique_identifier("%s_queue" %
                    stream_name)
        self._purge_queue(exchange_name)
        sub = StandaloneStreamSubscriber(exchange_name, recv_data)
        sub.start()
        self._data_subscribers.append(sub)
        sub_id = pubsub_client.create_subscription(name=exchange_name, stream_ids=[stream_id])
        pubsub_client.activate_subscription(sub_id)
        sub.subscription_id = sub_id # Bind the subscription to the standalone subscriber (easier cleanup, not good in real practice)

        stream_name = 'raw'
        parsed_config = self._stream_config[stream_name]
        stream_id = parsed_config['stream_id']
        exchange_name = create_unique_identifier("%s_queue" %
                    stream_name)
        self._purge_queue(exchange_name)
        sub = StandaloneStreamSubscriber(exchange_name, recv_raw_data)
        sub.start()
        self._data_subscribers.append(sub)
        sub_id = pubsub_client.create_subscription(name=exchange_name, stream_ids=[stream_id])
        pubsub_client.activate_subscription(sub_id)
        sub.subscription_id = sub_id # Bind the subscription to the standalone subscriber (easier cleanup, not good in real practice)

    def _purge_queue(self, queue):
        xn = self.container.ex_manager.create_xn_queue(queue)
        xn.purge()

    def _stop_data_subscribers(self):
        for subscriber in self._data_subscribers:
            pubsub_client = PubsubManagementServiceClient()
            if hasattr(subscriber,'subscription_id'):
                try:
                    pubsub_client.deactivate_subscription(subscriber.subscription_id)
                except:
                    pass
                pubsub_client.delete_subscription(subscriber.subscription_id)
            subscriber.stop()

    ###############################################################################
    # tcp helpers.
    ###############################################################################

    def _start_tcp_client(self, retval):
        host = retval.result['ip_address']
        port = retval.result['port']
        tcp_client = TcpClient(host, port)
        return tcp_client

    ###############################################################################
    # Tests.
    ###############################################################################

    @unittest.skip('Test should be run manually only.')
    def test_initialize(self):
        """
        test_initialize
        Test agent initialize command. This causes creation of
        driver process and transition to inactive.
        """

        print '#### in test'

        # We start in uninitialized state.
        # In this state there is no driver process.
        state = self._ia_client.get_agent_state()
        self.assertEqual(state, ResourceAgentState.UNINITIALIZED)

        # Ping the agent.
        retval = self._ia_client.ping_agent()
        log.info(retval)

        # Initialize the agent.
        # The agent is spawned with a driver config, but you can pass one in
        # optinally with the initialize command. This validates the driver
        # config, launches a driver process and connects to it via messaging.
        # If successful, we switch to the inactive state.
        cmd = AgentCommand(command=ResourceAgentEvent.INITIALIZE)
        retval = self._ia_client.execute_agent(cmd)
        state = self._ia_client.get_agent_state()
        self.assertEqual(state, ResourceAgentState.INACTIVE)

        # Ping the driver proc.
        retval = self._ia_client.ping_resource()
        log.info(retval)

        # Reset the agent. This causes the driver messaging to be stopped,
        # the driver process to end and switches us back to uninitialized.
        cmd = AgentCommand(command=ResourceAgentEvent.RESET)
        retval = self._ia_client.execute_agent(cmd)
        state = self._ia_client.get_agent_state()
        self.assertEqual(state, ResourceAgentState.UNINITIALIZED)

    @unittest.skip('Test should be run manually only.')
    def test_xx(self):
        """
        """

        state = self._ia_client.get_agent_state()
        self.assertEqual(state, ResourceAgentState.UNINITIALIZED)

        with self.assertRaises(Conflict):
            res_state = self._ia_client.get_resource_state()

        cmd = AgentCommand(command=ResourceAgentEvent.INITIALIZE)
        retval = self._ia_client.execute_agent(cmd)
        state = self._ia_client.get_agent_state()
        self.assertEqual(state, ResourceAgentState.INACTIVE)

        cmd = AgentCommand(command=ResourceAgentEvent.GO_ACTIVE)
        retval = self._ia_client.execute_agent(cmd)
        state = self._ia_client.get_agent_state()
        print '################################# mavs4 came up in state: ' + state

        if state == ResourceAgentState.IDLE:
            cmd = AgentCommand(command=ResourceAgentEvent.RUN)
            retval = self._ia_client.execute_agent(cmd)
            state = self._ia_client.get_agent_state()
            self.assertEqual(state, ResourceAgentState.COMMAND)

        elif state == ResourceAgentState.STREAMING:
            cmd = AgentCommand(command='DRIVER_EVENT_STOP_AUTOSAMPLE')
            retval = self._ia_client.execute_resource(cmd)
            state = self._ia_client.get_agent_state()
            self.assertEqual(state, ResourceAgentState.COMMAND)

        state = self._ia_client.get_agent_state()
        print '################################# mavs4 now in state: ' + state

        cmd = AgentCommand(command=ResourceAgentEvent.GO_DIRECT_ACCESS,
                           kwargs={'session_type': DirectAccessTypes.telnet,
                           'session_timeout':600,
                           'inactivity_timeout':600})
        retval = self._ia_client.execute_agent(cmd)
        state = self._ia_client.get_agent_state()
        self.assertEqual(state, ResourceAgentState.DIRECT_ACCESS)

        state = self._ia_client.get_agent_state()
        print '################################# mavs4 now in state: ' + state

        tcp_client = self._start_tcp_client(retval)
        self.assertTrue(tcp_client.start_telnet(token=retval.result['token']))

        self.assertTrue(tcp_client.send_data('\r\r'))

        gevent.sleep(180)

        state = self._ia_client.get_agent_state()
        self.assertEqual(state, ResourceAgentState.DIRECT_ACCESS)

        cmd = AgentCommand(command=ResourceAgentEvent.GO_COMMAND)
        retval = self._ia_client.execute_agent(cmd)
        state = self._ia_client.get_agent_state()
        self.assertEqual(state, ResourceAgentState.COMMAND)


text:
Properties

                <jhi-alert></jhi-alert>

                            <form class="form-inline" role="form">
                                Sort by

                                    <button type="button" class="btn btn-success" ng-click="vm.changeOrder('price')" data-translate="assessoriaTorrellesApp.property.sortBy.price">Price </button>
                                    <button type="button" class="btn btn-success" ng-click="vm.changeOrder('m2')" data-translate="assessoriaTorrellesApp.property.sortBy.size">Size </button>

                                    <select class="form-control" ng-model="vm.itemsPerPage" ng-change="vm.changeItemsPerPage()">
                                        <option>1</option>
                                        <option>2</option>
                                        <option>3</option>
                                        <option>5</option>
                                        <option>10</option>
                                        <option>20</option>
                                        <option>25</option>
                                        <option>50</option>
                                        <option>100</option>
                                    </select>

                            </form>

                                <input type="text" class="form-control" ng-model="vm.quickSearch" placeholder="{{ 'assessoriaTorrellesApp.property.quickSearch' | translate }}">

                            <button class="btn btn-success btn-block"  ui-sref="dashboard-property" >

                            </button>

                                        {{property.price}}€

                                        For Rent

                                     {{property.m2}} m2
                                     {{property.numberBedroom}}
                                     {{property.numberBedroom}}

{{property.buildingType}} {{property.town}}

                                <jhi-item-count page="vm.page" total="vm.queryCount" items-per-page="vm.itemsPerPage"></jhi-item-count>
                                <uib-pagination class="pagination-sm" total-items="vm.totalItems" items-per-page="vm.itemsPerPage" ng-model="vm.page" ng-change="vm.transition()"></uib-pagination>

redpajama_set_name: RedPajamaGithub


text:
using namespace metrics;
namespace storage {

CommunicationManagerMetrics::CommunicationManagerMetrics(MetricSet* owner)
    : MetricSet("communication", {}, "Metrics for the communication manager", owner),
      queueSize("messagequeue", {}, "Size of input message queue.", this),
      messageProcessTime("messageprocesstime", {}, "Time transport thread uses to process a single message", this),
      exceptionMessageProcessTime("exceptionmessageprocesstime", {},
                                  "Time transport thread uses to process a single message "
                                  "that fails with an exception thrown into communication manager", this),
      failedDueToTooLittleMemory("toolittlememory", {}, "Number of messages failed due to too little memory available", this),
      convertToStorageAPIFailures("convertfailures", {},
                                  "Number of messages that failed to get converted to storage API messages", this),
      bucketSpaceMappingFailures("bucket_space_mapping_failures", {},
                                 "Number of messages that could not be resolved to a known bucket space", this),
      sendCommandLatency("sendcommandlatency", {}, "Average ms used to send commands to MBUS", this),
      sendReplyLatency("sendreplylatency", {}, "Average ms used to send replies to MBUS", this)
{
}

CommunicationManagerMetrics::~CommunicationManagerMetrics() = default;

}


text:
package org.apache.batik.dom.svg;

import org.apache.batik.parser.NumberListHandler;
import org.apache.batik.parser.NumberListParser;
import org.apache.batik.parser.ParseException;

import org.w3c.dom.DOMException;
import org.w3c.dom.Element;
import org.w3c.dom.svg.SVGException;
import org.w3c.dom.svg.SVGNumber;
import org.w3c.dom.svg.SVGNumberList;

/**
 * This class is the implementation of {@link SVGNumberList}.
 *
 * @author Tonny Kohar
 * @version $Id: AbstractSVGNumberList.java 479349 2006-11-26 11:54:23Z cam $
 */
public abstract class AbstractSVGNumberList
        extends AbstractSVGList
        implements SVGNumberList {

    /**
     * Separator for a length list.
     */
    public static final String SVG_NUMBER_LIST_SEPARATOR
        = " ";

    /**
     * Return the separator between values in the list.
     */
    protected String getItemSeparator() {
        return SVG_NUMBER_LIST_SEPARATOR;
    }

    /**
     * Create an SVGException when the {@link #checkItemType(Object)} fails.
     */
    protected abstract SVGException createSVGException(short type,
                                                       String key,
                                                       Object[] args);

    /**
     * Returns the element associated with this SVGNumberList.
     */
    protected abstract Element getElement();

    /**
     * Creates a new SVGNumberList.
     */
    protected AbstractSVGNumberList() {
    }

    /**
     * DOM: Implements {@link SVGNumberList#initialize(SVGNumber)}.
     */
    public SVGNumber initialize(SVGNumber newItem)
        throws DOMException, SVGException {

        return (SVGNumber)initializeImpl(newItem);
    }

    /**
     * DOM: Implements {@link SVGNumberList#getItem(int)}.
     */
    public SVGNumber getItem(int index) throws DOMException {

        return (SVGNumber)getItemImpl(index);
    }

    /**
     * DOM: Implements {@link
     * SVGNumberList#insertItemBefore(SVGNumber,int)}.
     */
    public SVGNumber insertItemBefore(SVGNumber newItem, int index)
        throws DOMException, SVGException {

        return (SVGNumber)insertItemBeforeImpl(newItem,index);
    }

    /**
     * DOM: Implements {@link SVGNumberList#replaceItem(SVGNumber,int)}.
     */
    public SVGNumber replaceItem(SVGNumber newItem, int index)
        throws DOMException, SVGException {

        return (SVGNumber)replaceItemImpl(newItem,index);
    }

    /**
     * DOM: Implements {@link SVGNumberList#removeItem(int)}.
     */
    public SVGNumber removeItem(int index) throws DOMException {
        return (SVGNumber)removeItemImpl(index);
    }

    /**
     * DOM: Implements {@link SVGNumberList#appendItem(SVGNumber)}.
     */
    public SVGNumber appendItem(SVGNumber newItem)
        throws DOMException, SVGException {

        return (SVGNumber)appendItemImpl(newItem);
    }

    /**
     * Creates a new {@link SVGNumberItem} from the given {@link SVGNumber}.
     */
    protected SVGItem createSVGItem(Object newItem) {
        SVGNumber l = (SVGNumber)newItem;
        return new SVGNumberItem(l.getValue());
    }

    /**
     * Parse the attribute associated with this SVGNumberList.
     * @param value attribute value
     * @param handler list handler
     */
    protected void doParse(String value, ListHandler handler)
        throws ParseException{

        NumberListParser NumberListParser = new NumberListParser();
        NumberListBuilder builder = new NumberListBuilder(handler);

        NumberListParser.setNumberListHandler(builder);
        NumberListParser.parse(value);
    }

    /**
     * Asserts that the given item object is an {@link SVGNumber}.
     */
    protected void checkItemType(Object newItem) throws SVGException {
        if (!(newItem instanceof SVGNumber)) {
            // XXX Fix error code.
            createSVGException(SVGException.SVG_WRONG_TYPE_ERR,
                               "expected SVGNumber",
                               null);
        }
    }

    /**
     * Representation of the item SVGNumber.
     */
    protected class SVGNumberItem extends AbstractSVGNumber implements SVGItem {

        /**
         * The {@link SVGNumberList} this item belongs to.
         */
        protected AbstractSVGList parentList;

        /**
         * Creates a new SVGNumberItem.
         */
        public SVGNumberItem(float value) {
            this.value = value;
        }

        /**
         * Returns a String representation of the number.
         */
        public String getValueAsString() {
            return Float.toString(value);
        }

        /**
         * Associates this item to the given {@link SVGNumberList}.
         */
        public void setParent(AbstractSVGList list) {
            parentList = list;
        }

        /**
         * Returns the list the item belongs to.
         */
        public AbstractSVGList getParent() {
            return parentList;
        }

        /**
         * Notifies the parent {@link SVGNumberList} that this item's value
         * has changed.
         */
        protected void reset() {
            if (parentList != null) {
                parentList.itemChanged();
            }
        }
    }

    /**
     * Helper class to interface the {@link NumberListParser} and the
     * {@link NumberListHandler}.
     */
    protected class NumberListBuilder implements NumberListHandler {

        /**
         * The ListHandler to notify of parsed numbers.
         */
        protected ListHandler listHandler;

        /**
         * The number just parsed.
         */
        protected float currentValue;

        /**
         * Creates a new NumberListBuilder.
         */
        public NumberListBuilder(ListHandler listHandler) {
            this.listHandler = listHandler;
        }

        /**
         * Implements {@link NumberListHandler#startNumberList()}.
         */
        public void startNumberList() throws ParseException{
            listHandler.startList();
        }

        /**
         * Implements {@link NumberListHandler#startNumber()}.
         */
        public void startNumber() throws ParseException {
            currentValue = 0.0f;
        }

        /**
         * Implements {@link NumberListHandler#numberValue(float)}.
         */
        public void numberValue(float v) throws ParseException {
            currentValue = v;
        }

        /**
         * Implements {@link NumberListHandler#endNumber()}.
         */
        public void endNumber() throws ParseException {
            listHandler.item(new SVGNumberItem(currentValue));
        }

        /**
         * Implements {@link NumberListHandler#endNumberList()}.
         */
        public void endNumberList() throws ParseException {
            listHandler.endList();
        }
    }
}


text:
using PocketBoss.Common.Messaging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PocketBoss.Messages.Commands
{
    public class RecordStateAction: MessageBase
    {
        public string TargetObjectId { get; set; }
        public string TargetObjectType { get; set; }
        public long WorkflowInstanceId { get; set; }
        public string WorkflowTemplateName { get; set; }
        public string State { get; set; }
        public long StateId { get; set; }
        public long TaskId { get; set; }
        public string Event { get; set; }
    }
}


text:
var CommCareUsersViewModel = function (o) {
    'use strict';
    var self = this;
    self.initial_load = ko.observable(false);

    self.users_list = ko.observableArray();
    self.archive_action_users = ko.observableArray();

    self.cannot_share = o.cannot_share;
    self.show_inactive = o.show_inactive;
    self.more_columns = ko.observable(o.more_columns);

    self.list_url = o.list_url;

    self.total = ko.observable(o.total);
    self.page_limit = ko.observable(o.limit);
    self.max_page = ko.computed(function () {
        return Math.ceil(self.total()/self.page_limit());
    });
    self.current_page = ko.observable(o.start_page);
    self.next_page = ko.computed(function () {
        var page = self.current_page() + 1;
        if (page > self.max_page()) {
            return undefined;
        }
        return page;
    });
    self.previous_page = ko.computed(function () {
        var page = self.current_page() - 1;
        if (page < 1) {
            return undefined;
        }
        return page;
    });

    self.all_pages = ko.computed(function () {
        var last_ind = self.max_page()+1;
        if (self.max_page() <= 5 || self.current_page() <= 3)
            return _.range(1, Math.min(last_ind, 6));
        if (self.current_page() >= self.max_page()-2)
            return _.range(self.max_page()-4, last_ind);
        return _.range(self.current_page()-2, Math.min(last_ind, self.current_page()+3));
    });

    self.colspan = ko.computed(function () {
        if (self.more_columns())
            return 8;
        return 7;
    });

    self.search_string = ko.observable();
    self.from_search = ko.observable();
    self.currently_searching = ko.observable(false);
    self.init = function () {
        $(function () {
            self.change_page(self.current_page);
            $("#user-search-clear-btn").click(function(e) {
                self.search_string('');
            });
        });
    };

    self.update_limit = function (model, event) {
        var elem = $(event.currentTarget);
        self.page_limit(elem.val());
        self.change_page(1);
    };

    self.show_more_columns = function () {
        self.more_columns(true);
        self.change_page(self.current_page);
        return false;
    };

    self.change_page = function (page, next_or_last) {
        page = ko.utils.unwrapObservable(page);
        self.from_search(page === -1);
        page = page === -1 ? 1 : page;

        if (page) {
            self.currently_searching(true);
            $.ajax({
                url: format_url(page),
                dataType: 'json',
                error: function () {
                    self.initial_load(true);
                    $('.hide-until-load').fadeIn();
                    $('#user-list-notification').text('Sorry, there was an problem contacting the server ' +
                        'to fetch your Mobile Workers list. Please, try again in a little bit.');
                    self.currently_searching(false);
                },
                success: reloadList
            });
        }

        return false;
    };

    self.get_user_index = function (index) {
        return index() + ((self.current_page() - 1) * self.page_limit()) + 1;
    };

    self.format_phone_numbers = function (numbers) {
        if (numbers.length < 1) {
            return "";
        }
        var first_num = "+" + numbers[0];
        if (numbers.length > 1) {
            first_num = first_num + " (More Available)";
        }
        return first_num;
    };

    self.take_user_action = function (action_url, button, user_index) {
        $(button).button('loading');
        user_index = ko.utils.unwrapObservable(user_index);
        $.ajax({
            url: action_url,
            dataType: 'json',
            error: unsuccessful_archive_action(button, user_index),
            success: successful_archive_action(button, user_index)
        });
    };

    var reloadList = function(data) {
            self.currently_searching(false);
            if (data.success) {
                if (!self.initial_load()) {
                    self.initial_load(true);
                    $('.hide-until-load').fadeIn();
                }
                self.current_page(data.current_page);
                self.users_list(data.users_list);
                self.total(data.users_list_total);
                self.archive_action_users([]);
            }
        },
        format_url = function(page) {
            if (!page) {
                return "#";
            }
            var ret_url = self.list_url +'?page=' + page +
                "&limit=" + self.page_limit() +
                "&cannot_share=" + self.cannot_share +
                "&show_inactive=" + self.show_inactive +
                "&more_columns=" + self.more_columns();

            if (self.search_string()) {
                ret_url += "&query=" + self.search_string();
            }

            return ret_url
        },
        successful_archive_action = function (button, index) {
            return function (data) {
                if (data.success) {
                    var $modal = $(button).parent().parent();
                    $modal.modal('hide');
                    $modal.on('hidden', function () {
                        var users = self.users_list(),
                            actioned = self.archive_action_users();
                        actioned.push(users[index]);
                        users = _.difference(users, actioned);
                        self.total(self.total()-1);
                        self.users_list(users);
                        self.archive_action_users(actioned);
                    });
                } else {
                    unsuccessful_archive_action(button, index)(data);
                }
            }
        },
        unsuccessful_archive_action = function (button, index) {
            return function (data) {
                $(button).button('unsuccessful');
            }
        };
};

$.fn.asyncUsersList = function (options) {
    this.each(function(i, v) {
        var viewModel = new CommCareUsersViewModel(options);
        ko.applyBindings(viewModel, $(this).get(i));
        viewModel.init();
    });
};

ko.bindingHandlers.isPrevNextDisabled = {
    update: function(element, valueAccessor) {
        var value = valueAccessor()();
        if (value === undefined) {
            $(element).parent().addClass('disabled');
        } else {
            $(element).parent().removeClass('disabled');
        }
    }
};

ko.bindingHandlers.isPaginationActive = {
    update: function(element, valueAccessor, allBindingsAccessor) {
        var current_page = valueAccessor()();
        var current_item = parseInt(allBindingsAccessor()['text']);
        if (current_page === current_item) {
            $(element).parent().addClass('active');
        } else {
            $(element).parent().removeClass('active');
        }
    }
};


text:
<?php

namespace App\Http\Controllers;

use App\Http\Requests\StoreDelivery;
use App\Models\Cargo;
use App\Models\Delivery;
use App\Models\Game;
use App\Models\Location;
use Auth;

final class DeliveryController extends Controller
{
    public function index()
    {
        $deliveries = Delivery::with('cargo', 'from', 'to', 'user')
            ->orderBy('created_at', 'desc')
            ->paginate();

        return view('deliveries.index', compact('deliveries'));
    }

    public function create()
    {
        $cargos = Cargo::all();
        $games = Game::with('maps.locations')->get()->keyBy('id');

        $previousDelivery = Auth::user()
            ->deliveries()
            ->with('to.map.game')
            ->latest()
            ->first();

        return view(
            'deliveries.create',
            compact('cargos', 'games', 'previousDelivery')
        );
    }

    public function store(StoreDelivery $request)
    {
        $delivery = new Delivery($request->all());

        $delivery->user()->associate(Auth::user());
        $delivery->cargo()->associate(Cargo::find($request->get('cargo')));
        $delivery->from()->associate(Location::find($request->get('from')));
        $delivery->to()->associate(Location::find($request->get('to')));

        $delivery->save();

        return redirect()->route('deliveries.show', compact('delivery'));
    }

    public function show(Delivery $delivery)
    {
        return view('deliveries.show', compact('delivery'));
    }

    public function edit(Delivery $delivery)
    {
        $cargos = Cargo::all();
        $games = Game::all();

        return view('deliveries.edit', compact('delivery', 'cargos', 'games'));
    }

    public function update(StoreDelivery $request, Delivery $delivery)
    {
        $delivery->fill($request->all());

        $delivery->cargo()->associate(Cargo::find($request->get('cargo')));
        $delivery->from()->associate(Location::find($request->get('from')));
        $delivery->to()->associate(Location::find($request->get('to')));

        $delivery->save();

        return redirect()->route('deliveries.show', compact('delivery'));
    }

    public function destroy(Delivery $delivery)
    {
        $delivery->delete();

        return redirect('/');
    }
}


text:
using System.Web.Mvc;

namespace Microsoft.Azure.Blast.Web.Controllers
{
    [ConfigBasedMvcAuthorize]
    public class AuthorizedController : Controller
    {
    }
}


text:
"""Tests for the worker."""

import time

# pylint: disable=unused-import,g-bad-import-order
from grr.lib import server_plugins
# pylint: enable=unused-import,g-bad-import-order

from grr.lib import aff4
from grr.lib import data_store
from grr.lib import flags
from grr.lib import flow
from grr.lib import flow_runner
from grr.lib import rdfvalue
from grr.lib import scheduler
from grr.lib import test_lib
from grr.lib import worker

# A global collector for test results
RESULTS = []

class WorkerSendingTestFlow(flow.GRRFlow):
  """Tests that sent messages are correctly collected."""

  @flow.StateHandler(next_state="Incoming")
  def Start(self):
    for i in range(10):
      self.CallClient("Test",
                      rdfvalue.DataBlob(string="test%s" % i),
                      data=str(i),
                      next_state="Incoming")

  @flow.StateHandler(auth_required=False)
  def Incoming(self, responses):
    # Add a delay here to catch thread races.
    time.sleep(0.2)
    # We push the result into a global array so we can examine it
    # better.
    for response in responses:
      RESULTS.append(response.string)

class WorkerSendingTestFlow2(WorkerSendingTestFlow):
  """Only send a single request."""

  @flow.StateHandler(next_state="Incoming")
  def Start(self):
    i = 1
    self.CallClient("Test",
                    rdfvalue.DataBlob(string="test%s" % i),
                    data=str(i),
                    next_state="Incoming")

class WorkerSendingWKTestFlow(flow.WellKnownFlow):

  well_known_session_id = rdfvalue.SessionID(
      "aff4:/flows/WorkerSendingWKTestFlow")

  def ProcessMessage(self, message):
    RESULTS.append(message)

class GrrWorkerTest(test_lib.FlowTestsBaseclass):
  """Tests the GRR Worker."""

  def SendResponse(self, session_id, data, client_id=None, send_status=True):
    if not isinstance(data, rdfvalue.RDFValue):
      data = rdfvalue.DataBlob(string=data)
    with flow_runner.FlowManager(token=self.token) as flow_manager:
      flow_manager.QueueResponse(session_id, rdfvalue.GrrMessage(
          source=client_id,
          session_id=session_id,
          payload=data,
          request_id=1, response_id=1))
      if send_status:
        flow_manager.QueueResponse(session_id, rdfvalue.GrrMessage(
            source=client_id,
            session_id=session_id,
            payload=rdfvalue.GrrStatus(
                status=rdfvalue.GrrStatus.ReturnedStatus.OK),
            request_id=1, response_id=2,
            type=rdfvalue.GrrMessage.Type.STATUS))

    # Signal on the worker queue that this flow is ready.
    data_store.DB.Set(worker.DEFAULT_WORKER_QUEUE,
                      "task:%s" % session_id, "X", token=self.token)

  def testProcessMessages(self):
    """Test processing of several inbound messages."""
    worker_obj = worker.GRRWorker(worker.DEFAULT_WORKER_QUEUE,
                                  run_cron=False, token=self.token)

    # Create a couple of flows
    flow_obj = self.FlowSetup("WorkerSendingTestFlow")
    session_id_1 = flow_obj.session_id
    flow_obj.Close()

    flow_obj = self.FlowSetup("WorkerSendingTestFlow2")
    session_id_2 = flow_obj.session_id
    flow_obj.Close()

    # Check that client queue has messages
    tasks_on_client_queue = scheduler.SCHEDULER.Query(
        self.client_id, 100, token=self.token)

    # should have 10 requests from WorkerSendingTestFlow and 1 from
    # SendingTestFlow2
    self.assertEqual(len(tasks_on_client_queue), 11)

    # Send each of the flows a repeated message
    self.SendResponse(session_id_1, "Hello1")
    self.SendResponse(session_id_2, "Hello2")
    self.SendResponse(session_id_1, "Hello1")
    self.SendResponse(session_id_2, "Hello2")

    # Clear the results global
    del RESULTS[:]

    # Process all messages
    worker_obj.RunOnce()

    worker_obj.thread_pool.Join()

    # Ensure both requests ran exactly once
    RESULTS.sort()
    self.assertEqual(2, len(RESULTS))
    self.assertEqual("Hello1", RESULTS[0])
    self.assertEqual("Hello2", RESULTS[1])

    # Check that client queue is cleared - should have 2 less messages (since
    # two were completed).
    tasks_on_client_queue = scheduler.SCHEDULER.Query(
        self.client_id, 100, token=self.token)

    self.assertEqual(len(tasks_on_client_queue), 9)

    # Ensure that processed requests are removed from state subject
    self.assertEqual((None, 0), data_store.DB.Resolve(
        flow_runner.FlowManager.FLOW_STATE_TEMPLATE % session_id_1,
        flow_runner.FlowManager.FLOW_REQUEST_TEMPLATE % 1,
        token=self.token))

    flow_obj = aff4.FACTORY.Open(session_id_1, token=self.token)
    self.assertTrue(flow_obj.state.context.state !=
                    rdfvalue.Flow.State.TERMINATED)
    flow_obj = aff4.FACTORY.Open(session_id_2, token=self.token)
    self.assertTrue(flow_obj.state.context.state ==
                    rdfvalue.Flow.State.TERMINATED)

  def testProcessMessagesWellKnown(self):
    worker_obj = worker.GRRWorker(worker.DEFAULT_WORKER_QUEUE,
                                  run_cron=False, token=self.token)

    # Send a message to a WellKnownFlow - ClientStatsAuto.
    client_id = rdfvalue.ClientURN("C.1100110011001100")
    self.SendResponse(rdfvalue.SessionID("aff4:/flows/W:Stats"),
                      data=rdfvalue.ClientStats(RSS_size=1234),
                      client_id=client_id,
                      send_status=False)

    # Process all messages
    worker_obj.RunOnce()
    worker_obj.thread_pool.Join()

    client = aff4.FACTORY.Open(client_id.Add("stats"), token=self.token)
    stats = client.Get(client.Schema.STATS)
    self.assertEqual(stats.RSS_size, 1234)

    # Make sure no notifications have been sent.
    user = aff4.FACTORY.Open("aff4:/users/%s" % self.token.username,
                             token=self.token)
    notifications = user.Get(user.Schema.PENDING_NOTIFICATIONS)
    self.assertIsNone(notifications)

  def CheckNotificationsDisappear(self, session_id):
    worker_obj = worker.GRRWorker(worker.DEFAULT_WORKER_QUEUE,
                                  run_cron=False, token=self.token)
    scheduler.SCHEDULER.NotifyQueue(session_id, token=self.token)

    sessions = scheduler.SCHEDULER.GetSessionsFromQueue("aff4:/W",
                                                        token=self.token)
    # Check the notification is there.
    self.assertEqual(len(sessions), 1)
    self.assertEqual(sessions[0], session_id)

    # Process all messages
    worker_obj.RunOnce()
    worker_obj.thread_pool.Join()

    sessions = scheduler.SCHEDULER.GetSessionsFromQueue("aff4:/W",
                                                        token=self.token)
    # Check the notification is now gone.
    self.assertEqual(len(sessions), 0)

  def testWorkerDeletesNotificationsForBrokenObjects(self):
    # Test notifications for objects that don't exist.
    session_id = rdfvalue.SessionID("aff4:/flows/W:123456")

    self.CheckNotificationsDisappear(session_id)

    # Now check objects that are actually broken.
    session_id = rdfvalue.SessionID("aff4:/flows/W:testobj")
    obj = aff4.FACTORY.Create(session_id, "GRRFlow", token=self.token)
    obj.Close()
    # Overwrite the type of the object such that opening it will now fail.
    data_store.DB.Set(session_id, "aff4:type", "DeprecatedClass",
                      token=self.token)

    # Check it really does.
    with self.assertRaises(aff4.InstanciationError):
      aff4.FACTORY.Open(session_id, token=self.token)

    self.CheckNotificationsDisappear(session_id)

def main(_):
  test_lib.main()

if __name__ == "__main__":
  flags.StartMain(main)


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>CharRange.Reversible (Alternet Tools 1.0 API)</title>
<meta name="date" content="2020-01-18">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

ml.alternet.misc

Interface CharRange.Reversible

All Known Implementing Classes:

CharRange.BoundRange

Enclosing interface:

CharRange

public static interface CharRange.Reversible

Allow to specify a set of values in terms of inclusion or exclusion.

Author:

Philippe Poulard

Method Summary

All Methods Instance Methods Abstract Methods Default Methods

Modifier and Type
Method and Description

default boolean
includes()

Indicates whether a set of values is specified by inclusion or exclusion
 of the mentioned values.

CharRange
revert()

Create a char range that is the complement of this char range.

Method Detail

includes

default boolean includes()

Indicates whether a set of values is specified by inclusion or exclusion
 of the mentioned values.

Returns:

true to include values (by default),
      false to exclude values.

revert

CharRange revert()

Create a char range that is the complement of this char range.

Returns:

The revert char range.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2020 Alternet. All rights reserved.


text:
@interface ARArtworkRelatedArtworksView (Testing)
@property (nonatomic, strong) AREmbeddedModelsViewController *artworksVC;
- (void)renderWithArtworks:(NSArray *)artworks heading:(NSString *)heading;
@end

SpecBegin(ARArtworkRelatedArtworksView)

__block ARArtworkRelatedArtworksView *relatedView;

before(^{
    relatedView = [[ARArtworkRelatedArtworksView alloc] init];
    [relatedView renderWithArtworks:@[[Artwork modelFromDictionary:@{@"title": @"Title"}]] heading:@"Related Heading"];
});

describe(@"iPhone", ^{
    it(@"initializes module with correct layout", ^{
        ARArtworkMasonryLayout layout = [(ARArtworkMasonryModule *)relatedView.artworksVC.activeModule layout];
        expect(layout).to.equal(ARArtworkMasonryLayout2Column);
    });
});

describe(@"iPad", ^{
    beforeAll(^{
        [ARTestContext stubDevice:ARDeviceTypePad];
    });

    afterAll(^{
        [ARTestContext stopStubbing];
    });

    it(@"initializes the module with correct layout", ^{
        ARArtworkMasonryLayout layout = [(ARArtworkMasonryModule *)relatedView.artworksVC.activeModule layout];
        expect(layout).to.equal(ARArtworkMasonryLayout3Column);
    });

    it(@"returns correct layout for orientation", ^{
        expect([relatedView masonryLayoutForPadWithOrientation:UIInterfaceOrientationLandscapeLeft]).to.equal(ARArtworkMasonryLayout4Column);
        expect([relatedView masonryLayoutForPadWithOrientation:UIInterfaceOrientationLandscapeRight]).to.equal(ARArtworkMasonryLayout4Column);
        expect([relatedView masonryLayoutForPadWithOrientation:UIInterfaceOrientationPortrait]).to.equal(ARArtworkMasonryLayout3Column);
        expect([relatedView masonryLayoutForPadWithOrientation:UIInterfaceOrientationPortraitUpsideDown]).to.equal(ARArtworkMasonryLayout3Column);
    });
});

SpecEnd


text:
All notable changes to this project will be documented in this file, in reverse chronological order by release.

## 2.6.2 - TBD

### Added

- Nothing.

### Deprecated

- Nothing.

### Removed

- Nothing.

### Fixed

- Nothing.

## 2.6.1 - 2016-04-25

### Added

- Adds all existing documentation and publishes it at
  https://zendframework.github.io/zend-di/

### Deprecated

- Nothing.

### Removed

- Nothing.

### Fixed

- [#3](https://github.com/zendframework/zend-di/pull/3) fixes how
  `InstanceManager::sharedInstancesWithParams()` behaves when multiple calls are
  made with different sets of parameters (it should return different instances
  in that situation).

## 2.6.0 - 2016-02-23

### Added

- [#16](https://github.com/zendframework/zend-di/pull/16) adds container-interop
  as a dependency, and updates the `LocatorInterface` to extend
  `Interop\Container\ContainerInterface`. This required adding the following
  methods:
  - `Zend\Di\Di::has()`
  - `Zend\Di\ServiceLocator::has()`

### Deprecated

- Nothing.

### Removed

- [#15](https://github.com/zendframework/zend-di/pull/15) and
  [#16](https://github.com/zendframework/zend-di/pull/16) remove most
  development dependencies, as the functionality could be reproduced with
  generic test assets or PHP built-in classes. These include:
  - zend-config
  - zend-db
  - zend-filter
  - zend-log
  - zend-mvc
  - zend-view
  - zend-servicemanager

### Fixed

- [#16](https://github.com/zendframework/zend-di/pull/16) updates the try/catch
  block in `Zend\Di\Di::resolveMethodParameters()` to catch container-interop
  exceptions instead of the zend-servicemanager-specific exception class. Since
  all zend-servicemanager exceptions derive from container-interop, this
  provides more flexibility in using any container-interop implementation as a
  peering container.


text:
package net.dirtyfilthy.bitcoin.core;

import java.security.interfaces.ECPublicKey;
import java.text.ParseException;

import net.dirtyfilthy.bitcoin.protocol.ProtocolVersion;
import net.dirtyfilthy.bitcoin.util.Base58;
import net.dirtyfilthy.bitcoin.util.HashTools;
import net.dirtyfilthy.bitcoin.util.KeyTools;

public class Base58Hash160 {
	private byte[] hash160;
	private String hash;
	public Base58Hash160(ECPublicKey k){
		byte[] encoded=KeyTools.encodePublicKey(k);
		hash160=HashTools.ripemd160(HashTools.sha256(encoded));
		byte[] toEncode=new byte[hash160.length+1];
		toEncode[0]=ProtocolVersion.addressVersion();
		System.arraycopy(hash160, 0, toEncode, 1, hash160.length);
		hash=Base58.encodeCheck(toEncode);
	}

	public Base58Hash160(String address) throws ParseException{
		byte[] decoded=Base58.decodeCheck(address);
		hash=address;
		hash160=new byte[decoded.length-1];
		System.arraycopy(decoded, 1, hash160, 0, hash160.length);
	}

	public byte[] hash160(){
		return hash160;
	}

	public String toString(){
		return hash;
	}

}


text:
namespace Firestorm
{
    public class FilterInstruction
    {
        protected FilterInstruction()
        {
        }

        public FilterInstruction(string fieldName, FilterComparisonOperator comparisonOperator, string valueString)
        {
            FieldName = fieldName;
            Operator = comparisonOperator;
            ValueString = valueString;
        }

        public string FieldName { get; protected set; }

        public FilterComparisonOperator Operator { get; protected set; }

        public string ValueString { get; protected set; }
    }

    public enum FilterComparisonOperator
    {
        Equals,
        NotEquals,
        GreaterThan,
        GreaterThanOrEquals,
        LessThan,
        LessThanOrEquals,
        Contains,
        StartsWith,
        EndsWith,
        IsIn
    }
}


text:
package restaurant_pizza;

import agent_pizza.Agent;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.net.URI;
import java.net.URL;
import java.util.*;

import restaurant_pizza.gui.RestaurantPizza;
import restaurant_pizza.interfaces.Cashier;
import restaurant_pizza.interfaces.Customer;
import restaurant_pizza.interfaces.Market;
import restaurant_pizza.interfaces.Waiter;
import restaurant_pizza.test.mock.EventLog;
import restaurant_pizza.test.mock.LoggedEvent;
import restaurant_rancho.CashierAgent.MarketBill;
import simcity.RestMenu;
import simcity.PersonAgent;
import simcity.interfaces.Market_Douglass;
import simcity.interfaces.Person;

public class CashierAgent extends Agent implements Cashier {

	// ***** DATA *****

	public EventLog log = new EventLog();

	private Map<String, Double> menu =
			Collections.synchronizedMap(new HashMap<String, Double>());
	public List<MyCustomer> myCustomers =
			Collections.synchronizedList(new ArrayList<MyCustomer>()); //customers pending their checks to be approved
	public List<Check> checks =
			Collections.synchronizedList(new ArrayList<Check>());

	public enum CustomerState {NewCustomer, ValidPayment, InvalidPayment};
	public enum CheckState {NewCheck, InTransit, SentToWaiter, PaidByCustomer};
	private String name;
	Person person;
	boolean shiftDone = false;
	double wage;
	public boolean isWorking = true;

	RestaurantPizza restaurant;

	private List<FoodBill> billsToPay = Collections.synchronizedList(new ArrayList<FoodBill>());
	private List<MarketBill> bills = Collections.synchronizedList(new ArrayList<MarketBill>());
	public double totalMoney = 500.0; // keeps track of the money received
	private double totalDebt = 0.0; // keeps track of the money received

	public static class MarketBill {
		public Market_Douglass market;
		double amount;

		public MarketBill(Market_Douglass m, double am) {
			market = m;
			amount = am;
		}
	}

	public CashierAgent(String name) {
		super();
		this.name = name;
		this.restaurant = restaurant;
		//initializeMenu();
	}

	public CashierAgent(String name, RestaurantPizza restaurant) {
		super();
		this.name = name;
		this.restaurant = restaurant;
		//initializeMenu();
	}

	@Override
	public String getName() {
		return name;
	}

	public void setPerson(Person p) {
		person = p;
	}

	public double getTotalMoney() {
		return totalMoney;
	}

	public void setTotalMoney(double aMoney) {
		totalMoney = aMoney;
	}

	public void subtract(double amount) {
		totalMoney -= amount;
	}

	public void initializeMenu() {
		try {
			URL fileURL = getClass().getResource("/res/MenuTextFile.txt");
			URI fileURI = fileURL.toURI();
			BufferedReader br = new BufferedReader(new FileReader(new File(fileURI)));
			int numItems = Integer.parseInt(br.readLine());
			StringTokenizer st;
			for(int i = 0; i < numItems; i++) {
				st = new StringTokenizer(br.readLine());
				String itemName = st.nextToken();
				double price = Double.parseDouble(st.nextToken());
				st.nextToken();
				menu.put(itemName, price);
			}
			br.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// ***** MESSAGES *****

	@Override
	public void msgCustomerNeedsCheck(Waiter w, String order, Customer customer, RestMenu menu) {
		print("calling msgCustomerNeedsCheck()");
		double amountDue = menu.menuItems.get(order);
		Check newCheck = new Check(order, w, customer, amountDue);
		if(isNewCustomer(customer))
			myCustomers.add(new MyCustomer(customer));
		checks.add(newCheck);
		stateChanged();
	}

	public void msgShiftDone(double w) {
		print("got msg shift done");
		shiftDone = true;
		wage = w;
		stateChanged();
	}

	@Override
	public void msgPayingMyCheck(Customer c, Check check, double payment) {
		log.add(new LoggedEvent("Calling msgPayingMyCheck"));
		print("calling msgPayingMyCheck(), payment = " + payment);
		MyCustomer mc = null;
		synchronized(myCustomers) {
			for(MyCustomer tempMC : myCustomers)
				if(tempMC.cust.equals(c)) {
					mc = tempMC;
					break;
				}
		}
		check.state = CheckState.PaidByCustomer;
		// set state depending on whether customer has enough or not
		if(payment < check.amountDue) {
			print("invalid");
			mc.customerState = CustomerState.InvalidPayment;
		}
		else {
			print("valid");
			mc.customerState = CustomerState.ValidPayment;
		}
		stateChanged();
	}

	@Override
	public void msgHereIsBill(FoodBill fb) {
		log.add(new LoggedEvent("msgHereIsBill from " + fb.market.getName() + " for order " + fb.order
				+ " and amount " + fb.amountDue));
		billsToPay.add(fb);
		stateChanged();
	}

	public void msgHereIsMarketBill(Market_Douglass m, double amount){
		log.add(new LoggedEvent("Received Market Bill."));
		bills.add(new MarketBill(m, amount));
		stateChanged();
	}

	// ***** SCHEDULER *****
	// changed from protected to public for JUnit testing
	@Override
	public boolean pickAndExecuteAnAction() {

		// CashierMarket interaction scheduler step
		// Priority over the others
		// If there exists a bill in here, pay it, subtract from totalMoney
		// If negative number, convert to debt and set totalMoney = 0;
		// else, with whatever totalMoney you have left, make up for the debt as well.
		// send message to market containing the amount of money paid: msgHereIsBill
		// remove bill from List
		// return true;
		if(billsToPay.size() > 0) {
			FoodBill theBill = billsToPay.remove(0);
			double amountToPay = theBill.amountDue;
			boolean billIsPaid = true;
			if(totalMoney >= amountToPay) {
				totalMoney -= theBill.amountDue;
				if(totalDebt > 0) {
					// cashier will make up as much previous debt as possible
					amountToPay += Math.min(totalMoney, totalDebt);
					totalMoney -= amountToPay;
					totalDebt -= amountToPay;
					print("Repaying debts; total debt is now " + totalDebt);
				}
			}
			else {
				amountToPay = totalMoney;
				totalDebt += (theBill.amountDue - amountToPay);
				totalMoney = 0;
				billIsPaid = false;
			}
			print("Paying " + amountToPay + " in total");
			if(billIsPaid)
				print("This bill is fully paid off!");
			else {
				print("This bill is not fully paid off - will pay " + (theBill.amountDue - amountToPay) + " next time.");
				print("Total debt is now " + totalDebt);
			}
			Market theMarket = theBill.market;
			theMarket.msgHereIsBill(amountToPay, billIsPaid);
			return true;
		}

		print("pickAndExecute called");
		if(checks.isEmpty()) {
			print("no checks");
			return false;
		}

		// loop through all waiting customers and tables
		synchronized (checks) {

			for(int indBill = 0; indBill<bills.size(); indBill++) {
				MarketBill bill = bills.get(indBill);
				payBill(bill);
				return true;
			}
			for(int indCheck = 0; indCheck < checks.size(); indCheck++) {
				Check aCheck = checks.get(indCheck);
				if(aCheck.state == CheckState.NewCheck) {
					deliverCheck(aCheck.waiter, aCheck);
					aCheck.state = CheckState.InTransit;
					return true;
				}
				if(aCheck.state == CheckState.PaidByCustomer) {
					Customer customerOnCheck = aCheck.customer;
					synchronized (myCustomers) {
						for(int i = 0; i < myCustomers.size(); i++) {
							MyCustomer mc = myCustomers.get(i);
							if(mc.cust.equals(customerOnCheck)) {
								print("ready to inspect check");
								if(mc.customerState == CustomerState.ValidPayment)
									handleValidPayment(aCheck);
								else
									handleInvalidPayment(aCheck);
								return true;
							}
						}
					}
				}
			}
		}
		if (shiftDone) {leaveWork();}
		return false;
	}

	private void payBill(MarketBill bill) {
		bill.market.msgHereIsPayment(restaurant, bill.amount);
		totalMoney -= bill.amount;
		print ("Paid market, I have " + totalMoney + " dollars now");
		bills.remove(bill);
		stateChanged();
	}

	public void deliverCheck(Waiter freeWaiter, Check aCheck) {
		aCheck.waiter.msgHereIsCheck(aCheck);
	}

	private void leaveWork() {
		person.msgStopWork(wage);
		isWorking = false;
	}
	public void handleValidPayment(Check aCheck) {
		print("handle valid");
		log.add(new LoggedEvent("handleValidPayment called"));
		totalMoney += aCheck.amountDue;
		Customer theCustomer = aCheck.customer;
		print("Received " + aCheck.amountDue + " from Customer");
		print("Total money in the register: " + totalMoney);
		checks.remove(aCheck);
		theCustomer.msgLeaveRestaurant();
	}

	public void handleInvalidPayment(Check aCheck) {
		print("handle invalid");
		log.add(new LoggedEvent("handleInvalidPayment called"));
		Customer customerOnCheck = aCheck.customer;
		synchronized (myCustomers) {
			for(int i = 0; i < myCustomers.size(); i++) {
				MyCustomer mc = myCustomers.get(i);
				if(mc.cust.equals(customerOnCheck)) {
					mc.debt += aCheck.amountDue;
					print("Next time you come, pay up this debt: " + mc.debt);
					log.add(new LoggedEvent("Customer has this much debt to repay: " + mc.debt));
				}
			}
		}
		checks.remove(aCheck);
		Customer theCustomer = aCheck.customer;
		theCustomer.msgLeaveRestaurant();
	}

	//utilities

	private boolean isNewCustomer(Customer c) {
		synchronized (myCustomers) {
			for(MyCustomer tempMC : myCustomers) {
				if(tempMC.cust.equals(c)) {
					return false;
				}
			}
		}
		return true;
	}

	private class MyCustomer {
		Customer cust;
		CustomerState customerState;
		double debt = 0.0;

		public MyCustomer(Customer aCustomerAgent) {
			cust = aCustomerAgent;
			customerState = CustomerState.NewCustomer;
		}
	}
}


text:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Mappings;

namespace MappingsTests
{
    [TestClass]
    public class RepositoryTests
    {

        Repository _repo;

        [TestInitialize]
        public void startup()
        {
            _repo = new Repository(3);
        }

        [TestMethod]
        [ExpectedException(typeof(ArgumentOutOfRangeException))]
        public void NegativePositionThrows()
        {
            _repo.add_item(-1, 10, true);
        }

        [TestMethod]
        [ExpectedException(typeof(ArgumentOutOfRangeException))]
        public void PositionGreaterThanSizeThrows()
        {
            _repo.add_item(1000, 10, true);
        }

        [TestMethod]
        public void AddingValidItemReturnsTrue()
        {
            _repo.add_item(2, 10, false);
        }
        [TestMethod]
        public void AddingToOccupiedSpaceWithoutOverwriteReturnsFalse()
        {
            _repo.add_item(2, 10, false);
            _repo.add_item(2, 12, false);
        }

        [TestMethod]
        public void AddingToOccupiedSpaceWithOverwriteReturnsTrue()
        {
            _repo.add_item(2, 10, false);
            _repo.add_item(2, 12, true);
        }

    }
}


text:
package net.floodlightcontroller.prediction;

import org.json.JSONObject;
import org.restlet.resource.Get;
import org.restlet.resource.Post;
import org.restlet.resource.ServerResource;

import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;

public class MongoDBResource extends ServerResource {

    @Get("json")
    public String retrieve() throws FileNotFoundException, UnsupportedEncodingException {
        INetTopologyService service = (INetTopologyService)getContext().getAttributes().get(INetTopologyService.class.getCanonicalName());
        MongoDBInfo info = service.getMongoDBConnection();
        String out = "{\n";
        out += "\"ip\" : \"" + info.getIP() + "\",\n";
        out += "\"port\" : \"" + info.getPORT() + "\"\n";
        out += "}\n";
        return out;
    }

    @Post
    public String store(String in) {
        INetTopologyService service = (INetTopologyService)getContext().getAttributes().get(INetTopologyService.class.getCanonicalName());
        try {
            JSONObject jp = new JSONObject(in);
            String ip = jp.getString("ip");
            String port = jp.getString("port");
            service.setMongoDBConnection(ip,port);
        }
        catch(Exception e){
            System.out.println(e.getMessage());
            return "{ \"status\" : \"err\" }\n";
        }
        return "{ \"status\" : \"ok\" }\n";
    }

}


text:
/**
 * A brief explanation for "project.json":
 * Here is the content ofproject.json file, this is the global configuration for your game, you can modify it to customize some behavior.
 * The detail of each field is under it.
 {
    "debugMode"     : 1,
    // "debugMode" possible values :
    //      0 - No message will be printed.
    //      1 - cc.error, cc.assert, cc.warn, cc.log will print in console.
    //      2 - cc.error, cc.assert, cc.warn will print in console.
    //      3 - cc.error, cc.assert will print in console.
    //      4 - cc.error, cc.assert, cc.warn, cc.log will print on canvas, available only on web.
    //      5 - cc.error, cc.assert, cc.warn will print on canvas, available only on web.
    //      6 - cc.error, cc.assert will print on canvas, available only on web.

    "showFPS"       : true,
    // Left bottom corner fps information will show when "showFPS" equals true, otherwise it will be hide.

    "frameRate"     : 60,
    // "frameRate" set the wanted frame rate for your game, but the real fps depends on your game implementation and the running environment.

    "noCache"       : false,
    // "noCache" set whether your resources will be loaded with a timestamp suffix in the url.
    // In this way, your resources will be force updated even if the browser holds a cache of it.
    // It's very useful for mobile browser debuging.

    "id"            : "gameCanvas",
    // "gameCanvas" sets the id of your canvas element on the web page, it's useful only on web.

    "renderMode"    : 0,
    // "renderMode" sets the renderer type, only useful on web :
    //      0 - Automatically chosen by engine
    //      1 - Forced to use canvas renderer
    //      2 - Forced to use WebGL renderer, but this will be ignored on mobile browsers

    "engineDir"     : "../../frameworks/cocos2d-html5/",
    // In debug mode, if you use the whole engine to develop your game, you should specify its relative path with "engineDir",
    // but if you are using a single engine file, you can ignore it.

    "modules"       : ["cocos2d", "extensions", "external"],
    // "modules" defines which modules you will need in your game, it's useful only on web,
    // using this can greatly reduce your game's resource size, and the cocos console tool can package your game with only the modules you set.
    // For details about modules definitions, you can refer to "../../frameworks/cocos2d-html5/modulesConfig.json".

    "plugin": {
        "facebook": {
            "appId" : "1426774790893461",
            "xfbml" : true,
            "version" : "v2.0"
        }
    },
    // "plugin" is used by plugin-x for its settings, if you don't use it, you can ignore it.

    "jsList"        : [
    ]
    // "jsList" sets the list of js files in your game.
 }
 *
 */

if(cc.sys){
    var scene3SearchPaths = cc.sys.localStorage.getItem("Scene3SearchPaths");
    if (scene3SearchPaths)
        jsb.fileUtils.setSearchPaths(JSON.parse(scene3SearchPaths));
}

cc.game.onStart = function(){
    cc.view.enableRetina(false);
    if (cc.sys.isNative) {
        var resolutionPolicy = (cc.sys.os == cc.sys.OS_WP8 || cc.sys.os == cc.sys.OS_WINRT) ? cc.ResolutionPolicy.SHOW_ALL : cc.ResolutionPolicy.FIXED_HEIGHT;
        cc.view.setDesignResolutionSize(800, 450, resolutionPolicy);
        cc.view.resizeWithBrowserSize(true);
        var searchPaths = jsb.fileUtils.getSearchPaths();
        searchPaths.push('script');
        searchPaths.push('src');
        var paths = [
            'res/resjs',
            'res',
            'res/scenetest',
            'res/scenetest/ArmatureComponentTest',
            'res/scenetest/AttributeComponentTest',
            'res/scenetest/BackgroundComponentTest',
            'res/scenetest/EffectComponentTest',
            'res/scenetest/LoadSceneEdtiorFileTest',
            'res/scenetest/ParticleComponentTest',
            'res/scenetest/SpriteComponentTest',
            'res/scenetest/TmxMapComponentTest',
            'res/scenetest/UIComponentTest',
            'res/scenetest/TriggerTest'
        ];
        for (var i = 0; i < paths.length; i++) {
            searchPaths.push(paths[i]);
        }
        jsb.fileUtils.setSearchPaths(searchPaths);
    }
    else
    {
        cc.view.setDesignResolutionSize(800, 450, cc.ResolutionPolicy.SHOW_ALL);
        cc.view.resizeWithBrowserSize(true);
        // js-test use cpptest resource in debug mode , and in the release mode, console will copy the resource into the res dir
        // so the respath will modify to res,
        if (cc.game.config[cc.game.CONFIG_KEY.engineDir] !== "frameworks/cocos2d-html5") {
            cc.loader.resPath = '../cpp-tests/Resources';
        }
        else {
            cc.loader.resPath = 'res';
            document.getElementById("cocosbanner").src = "res/Images/cocos2dbanner.png";
        }
    }

    cc.LoaderScene.preload(g_resources, function () {
        if(window.sideIndexBar && typeof sideIndexBar.start === 'function'){
            sideIndexBar.start();
        }else{
            var scene = new cc.Scene();
            scene.addChild(new TestController());
            cc.director.runScene(scene);
        }
    }, this);
};
cc.game.run();


text:
(function () {

    "use strict";

    function watchHistory($injector, $q, watchHistoryService) {

        var self = this;

        self.onStoreUpdate = function () {

        }

        return self;

    }

    angular.module("app").service("watchHistory", ["$injector", "$q", "watchHistoryService", watchHistory]);

})();


text:
package main

import (
	"context"

	binaryauthorization "cloud.google.com/go/binaryauthorization/apiv1"
	binaryauthorizationpb "cloud.google.com/go/binaryauthorization/apiv1/binaryauthorizationpb"
)

func main() {
	ctx := context.Background()
	// This snippet has been automatically generated and should be regarded as a code template only.
	// It will require modifications to work:
	// - It may require correct/in-range values for request initialization.
	// - It may require specifying regional endpoints when creating the service client as shown in:
	//   https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options
	c, err := binaryauthorization.NewValidationHelperClient(ctx)
	if err != nil {
		// TODO: Handle error.
	}
	defer c.Close()

	req := &binaryauthorizationpb.ValidateAttestationOccurrenceRequest{
		// TODO: Fill request struct fields.
		// See https://pkg.go.dev/cloud.google.com/go/binaryauthorization/apiv1/binaryauthorizationpb#ValidateAttestationOccurrenceRequest.
	}
	resp, err := c.ValidateAttestationOccurrence(ctx, req)
	if err != nil {
		// TODO: Handle error.
	}
	// TODO: Use resp.
	_ = resp
}

// [END binaryauthorization_v1_generated_ValidationHelperV1_ValidateAttestationOccurrence_sync]