text:
import logging
import socket

import fixtures
from oslo_utils import importutils
import testtools

try:
    import zmq
except ImportError:
    zmq = None

import oslo_messaging
from oslo_messaging._drivers import common as rpc_common
from oslo_messaging.tests import utils as test_utils
from six.moves import mock

# eventlet is not yet py3 compatible, so skip if not installed
eventlet = importutils.try_import('eventlet')

impl_zmq = importutils.try_import('oslo_messaging._drivers.impl_zmq')

LOG = logging.getLogger(__name__)

def get_unused_port():
    """Returns an unused port on localhost."""
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind(('localhost', 0))
    port = s.getsockname()[1]
    s.close()
    return port

class ZmqBaseTestCase(test_utils.BaseTestCase):
    """Base test case for all ZMQ tests that make use of the ZMQ Proxy"""

    @testtools.skipIf(zmq is None, "zmq not available")
    def setUp(self):
        super(ZmqBaseTestCase, self).setUp()
        self.messaging_conf.transport_driver = 'zmq'
        # Get driver
        transport = oslo_messaging.get_transport(self.conf)
        self.driver = transport._driver

        # Set config values
        self.internal_ipc_dir = self.useFixture(fixtures.TempDir()).path
        kwargs = {'rpc_zmq_bind_address': '127.0.0.1',
                  'rpc_zmq_host': '127.0.0.1',
                  'rpc_response_timeout': 5,
                  'rpc_zmq_port': get_unused_port(),
                  'rpc_zmq_ipc_dir': self.internal_ipc_dir}
        self.config(**kwargs)

        # Start RPC
        LOG.info("Running internal zmq receiver.")
        self.reactor = impl_zmq.ZmqProxy(self.conf)
        self.reactor.consume_in_thread()

        self.matchmaker = impl_zmq._get_matchmaker(host='127.0.0.1')
        self.addCleanup(stopRpc(self.__dict__))

class TestConfZmqDriverLoad(test_utils.BaseTestCase):

    @testtools.skipIf(zmq is None, "zmq not available")
    def setUp(self):
        super(TestConfZmqDriverLoad, self).setUp()
        self.messaging_conf.transport_driver = 'zmq'

    def test_driver_load(self):
        transport = oslo_messaging.get_transport(self.conf)
        self.assertIsInstance(transport._driver, impl_zmq.ZmqDriver)

class stopRpc(object):
    def __init__(self, attrs):
        self.attrs = attrs

    def __call__(self):
        if self.attrs['reactor']:
            self.attrs['reactor'].close()
        if self.attrs['driver']:
            self.attrs['driver'].cleanup()

class TestZmqBasics(ZmqBaseTestCase):

    def test_start_stop_listener(self):
        target = oslo_messaging.Target(topic='testtopic')
        listener = self.driver.listen(target)
        result = listener.poll(0.01)
        self.assertEqual(result, None)

    def test_send_receive_raises(self):
        """Call() without method."""
        target = oslo_messaging.Target(topic='testtopic')
        self.driver.listen(target)
        self.assertRaises(
            KeyError,
            self.driver.send,
            target, {}, {'tx_id': 1}, wait_for_reply=True)

    @mock.patch('oslo_messaging._drivers.impl_zmq.ZmqIncomingMessage')
    def test_send_receive_topic(self, mock_msg):
        """Call() with method."""
        mock_msg.return_value = msg = mock.MagicMock()
        msg.received = received = mock.MagicMock()
        received.failure = False
        received.reply = True
        msg.condition = condition = mock.MagicMock()
        condition.wait.return_value = True

        target = oslo_messaging.Target(topic='testtopic')
        self.driver.listen(target)
        result = self.driver.send(
            target, {},
            {'method': 'hello-world', 'tx_id': 1},
            wait_for_reply=True)
        self.assertEqual(result, True)

    @mock.patch('oslo_messaging._drivers.impl_zmq._call', autospec=True)
    def test_send_receive_fanout(self, mock_call):
        target = oslo_messaging.Target(topic='testtopic', fanout=True)
        self.driver.listen(target)

        mock_call.__name__ = '_call'
        mock_call.return_value = [True]

        result = self.driver.send(
            target, {},
            {'method': 'hello-world', 'tx_id': 1},
            wait_for_reply=True)

        self.assertEqual(result, True)
        mock_call.assert_called_once_with(
            self.driver,
            'tcp://127.0.0.1:%s' % self.conf['rpc_zmq_port'],
            {}, 'fanout~testtopic.127.0.0.1',
            {'tx_id': 1, 'method': 'hello-world'},
            None, False, [], True)

    @mock.patch('oslo_messaging._drivers.impl_zmq._call', autospec=True)
    def test_send_receive_direct(self, mock_call):
        # Also verifies fix for bug http://pad.lv/1301723
        target = oslo_messaging.Target(topic='testtopic', server='localhost')
        self.driver.listen(target)

        mock_call.__name__ = '_call'
        mock_call.return_value = [True]

        result = self.driver.send(
            target, {},
            {'method': 'hello-world', 'tx_id': 1},
            wait_for_reply=True)

        self.assertEqual(result, True)
        mock_call.assert_called_once_with(
            self.driver,
            'tcp://localhost:%s' % self.conf['rpc_zmq_port'],
            {}, 'testtopic.localhost',
            {'tx_id': 1, 'method': 'hello-world'},
            None, False, [], True)

class TestZmqSocket(test_utils.BaseTestCase):

    @testtools.skipIf(zmq is None, "zmq not available")
    def setUp(self):
        super(TestZmqSocket, self).setUp()
        self.messaging_conf.transport_driver = 'zmq'
        # Get driver
        transport = oslo_messaging.get_transport(self.conf)
        self.driver = transport._driver

    @mock.patch('oslo_messaging._drivers.impl_zmq.ZmqSocket.subscribe')
    @mock.patch('oslo_messaging._drivers.impl_zmq.zmq.Context')
    def test_zmqsocket_init_type_pull(self, mock_context, mock_subscribe):
        mock_ctxt = mock.Mock()
        mock_context.return_value = mock_ctxt
        mock_sock = mock.Mock()
        mock_ctxt.socket = mock.Mock(return_value=mock_sock)
        mock_sock.connect = mock.Mock()
        mock_sock.bind = mock.Mock()
        addr = '127.0.0.1'

        sock = impl_zmq.ZmqSocket(addr, impl_zmq.zmq.PULL, bind=False,
                                  subscribe=None)
        self.assertTrue(sock.can_recv)
        self.assertFalse(sock.can_send)
        self.assertFalse(sock.can_sub)
        self.assertTrue(mock_sock.connect.called)
        self.assertFalse(mock_sock.bind.called)

    @mock.patch('oslo_messaging._drivers.impl_zmq.ZmqSocket.subscribe')
    @mock.patch('oslo_messaging._drivers.impl_zmq.zmq.Context')
    def test_zmqsocket_init_type_sub(self, mock_context, mock_subscribe):
        mock_ctxt = mock.Mock()
        mock_context.return_value = mock_ctxt
        mock_sock = mock.Mock()
        mock_ctxt.socket = mock.Mock(return_value=mock_sock)
        mock_sock.connect = mock.Mock()
        mock_sock.bind = mock.Mock()
        addr = '127.0.0.1'

        sock = impl_zmq.ZmqSocket(addr, impl_zmq.zmq.SUB, bind=False,
                                  subscribe=None)
        self.assertTrue(sock.can_recv)
        self.assertFalse(sock.can_send)
        self.assertTrue(sock.can_sub)
        self.assertTrue(mock_sock.connect.called)
        self.assertFalse(mock_sock.bind.called)

    @mock.patch('oslo_messaging._drivers.impl_zmq.ZmqSocket.subscribe')
    @mock.patch('oslo_messaging._drivers.impl_zmq.zmq.Context')
    def test_zmqsocket_init_type_push(self, mock_context, mock_subscribe):
        mock_ctxt = mock.Mock()
        mock_context.return_value = mock_ctxt
        mock_sock = mock.Mock()
        mock_ctxt.socket = mock.Mock(return_value=mock_sock)
        mock_sock.connect = mock.Mock()
        mock_sock.bind = mock.Mock()
        addr = '127.0.0.1'

        sock = impl_zmq.ZmqSocket(addr, impl_zmq.zmq.PUSH, bind=False,
                                  subscribe=None)
        self.assertFalse(sock.can_recv)
        self.assertTrue(sock.can_send)
        self.assertFalse(sock.can_sub)
        self.assertTrue(mock_sock.connect.called)
        self.assertFalse(mock_sock.bind.called)

    @mock.patch('oslo_messaging._drivers.impl_zmq.ZmqSocket.subscribe')
    @mock.patch('oslo_messaging._drivers.impl_zmq.zmq.Context')
    def test_zmqsocket_init_type_pub(self, mock_context, mock_subscribe):
        mock_ctxt = mock.Mock()
        mock_context.return_value = mock_ctxt
        mock_sock = mock.Mock()
        mock_ctxt.socket = mock.Mock(return_value=mock_sock)
        mock_sock.connect = mock.Mock()
        mock_sock.bind = mock.Mock()
        addr = '127.0.0.1'

        sock = impl_zmq.ZmqSocket(addr, impl_zmq.zmq.PUB, bind=False,
                                  subscribe=None)
        self.assertFalse(sock.can_recv)
        self.assertTrue(sock.can_send)
        self.assertFalse(sock.can_sub)
        self.assertTrue(mock_sock.connect.called)
        self.assertFalse(mock_sock.bind.called)

class TestZmqIncomingMessage(test_utils.BaseTestCase):

    @testtools.skipIf(zmq is None, "zmq not available")
    def setUp(self):
        super(TestZmqIncomingMessage, self).setUp()
        self.messaging_conf.transport_driver = 'zmq'
        # Get driver
        transport = oslo_messaging.get_transport(self.conf)
        self.driver = transport._driver

    def test_zmqincomingmessage(self):
        msg = impl_zmq.ZmqIncomingMessage(mock.Mock(), None, 'msg.foo')
        msg.reply("abc")
        self.assertIsInstance(
            msg.received, impl_zmq.ZmqIncomingMessage.ReceivedReply)
        self.assertIsInstance(
            msg.received, impl_zmq.ZmqIncomingMessage.ReceivedReply)
        self.assertEqual(msg.received.reply, "abc")
        msg.requeue()

class TestZmqConnection(ZmqBaseTestCase):

    @mock.patch('oslo_messaging._drivers.impl_zmq.ZmqReactor', autospec=True)
    def test_zmqconnection_create_consumer(self, mock_reactor):

        mock_reactor.register = mock.Mock()
        conn = impl_zmq.Connection(self.driver.conf, self.driver)
        topic = 'topic.foo'
        context = mock.Mock()
        inaddr = ('ipc://%s/zmq_topic_topic.127.0.0.1' %
                  (self.internal_ipc_dir))
        # No Fanout
        conn.create_consumer(topic, context)
        conn.reactor.register.assert_called_with(context, inaddr,
                                                 impl_zmq.zmq.PULL,
                                                 subscribe=None, in_bind=False)

        # Reset for next bunch of checks
        conn.reactor.register.reset_mock()

        # Fanout
        inaddr = ('ipc://%s/zmq_topic_fanout~topic' %
                  (self.internal_ipc_dir))
        conn.create_consumer(topic, context, fanout='subscriber.foo')
        conn.reactor.register.assert_called_with(context, inaddr,
                                                 impl_zmq.zmq.SUB,
                                                 subscribe='subscriber.foo',
                                                 in_bind=False)

    @mock.patch('oslo_messaging._drivers.impl_zmq.ZmqReactor', autospec=True)
    def test_zmqconnection_create_consumer_topic_exists(self, mock_reactor):
        mock_reactor.register = mock.Mock()
        conn = impl_zmq.Connection(self.driver.conf, self.driver)
        topic = 'topic.foo'
        context = mock.Mock()
        inaddr = ('ipc://%s/zmq_topic_topic.127.0.0.1' %
                  (self.internal_ipc_dir))

        conn.create_consumer(topic, context)
        conn.reactor.register.assert_called_with(
            context, inaddr, impl_zmq.zmq.PULL, subscribe=None, in_bind=False)
        conn.reactor.register.reset_mock()
        # Call again with same topic
        conn.create_consumer(topic, context)
        self.assertFalse(conn.reactor.register.called)

    @mock.patch('oslo_messaging._drivers.impl_zmq._get_matchmaker',
                autospec=True)
    @mock.patch('oslo_messaging._drivers.impl_zmq.ZmqReactor', autospec=True)
    def test_zmqconnection_close(self, mock_reactor, mock_getmatchmaker):
        conn = impl_zmq.Connection(self.driver.conf, self.driver)
        conn.reactor.close = mock.Mock()
        mock_getmatchmaker.return_value.stop_heartbeat = mock.Mock()
        conn.close()
        self.assertTrue(mock_getmatchmaker.return_value.stop_heartbeat.called)
        self.assertTrue(conn.reactor.close.called)

    @mock.patch('oslo_messaging._drivers.impl_zmq.ZmqReactor', autospec=True)
    def test_zmqconnection_wait(self, mock_reactor):
        conn = impl_zmq.Connection(self.driver, self.driver)
        conn.reactor.wait = mock.Mock()
        conn.wait()
        self.assertTrue(conn.reactor.wait.called)

    @mock.patch('oslo_messaging._drivers.impl_zmq._get_matchmaker',
                autospec=True)
    @mock.patch('oslo_messaging._drivers.impl_zmq.ZmqReactor', autospec=True)
    def test_zmqconnection_consume_in_thread(self, mock_reactor,
                                             mock_getmatchmaker):
        mock_getmatchmaker.return_value.start_heartbeat = mock.Mock()
        conn = impl_zmq.Connection(self.driver, self.driver)
        conn.reactor.consume_in_thread = mock.Mock()
        conn.consume_in_thread()
        self.assertTrue(mock_getmatchmaker.return_value.start_heartbeat.called)
        self.assertTrue(conn.reactor.consume_in_thread.called)

class TestZmqListener(ZmqBaseTestCase):

    def test_zmqlistener_no_msg(self):
        listener = impl_zmq.ZmqListener(self.driver)
        # Timeout = 0 should return straight away since the queue is empty
        listener.poll(timeout=0)

    def test_zmqlistener_w_msg(self):
        listener = impl_zmq.ZmqListener(self.driver)
        kwargs = {'a': 1, 'b': 2}
        m = mock.Mock()
        ctxt = mock.Mock(autospec=impl_zmq.RpcContext)
        message = {'namespace': 'name.space', 'method': m.fake_method,
                   'args': kwargs}
        eventlet.spawn_n(listener.dispatch, ctxt, message)
        resp = listener.poll(timeout=10)
        msg = {'method': m.fake_method, 'namespace': 'name.space',
               'args': kwargs}
        self.assertEqual(resp.message, msg)

class TestZmqDriver(ZmqBaseTestCase):

    @mock.patch('oslo_messaging._drivers.impl_zmq._cast', autospec=True)
    @mock.patch('oslo_messaging._drivers.matchmaker.MatchMakerBase.queues',
                autospec=True)
    def test_zmqdriver_multi_send_cast_with_no_queues(self,
                                                      mock_queues,
                                                      mock_cast):
        context = mock.Mock(autospec=impl_zmq.RpcContext)
        topic = 'testtopic'
        msg = 'jeronimo'

        with mock.patch.object(impl_zmq.LOG, 'warn') as flog:
            mock_queues.return_value = None
            impl_zmq._multi_send(self.driver, mock_cast,
                                 context, topic, msg)
            self.assertEqual(1, flog.call_count)
            args, kwargs = flog.call_args
            self.assertIn('No matchmaker results', args[0])

    @mock.patch('oslo_messaging._drivers.impl_zmq._call', autospec=True)
    @mock.patch('oslo_messaging._drivers.matchmaker.MatchMakerBase.queues',
                autospec=True)
    def test_zmqdriver_multi_send_call_with_no_queues(self,
                                                      mock_queues,
                                                      mock_call):
        context = mock.Mock(autospec=impl_zmq.RpcContext)
        topic = 'testtopic'
        msg = 'jeronimo'

        mock_queues.return_value = None
        self.assertRaises(rpc_common.Timeout,
                          impl_zmq._multi_send, self.driver,
                          mock_call, context, topic, msg)

    @mock.patch('oslo_messaging._drivers.impl_zmq._cast', autospec=True)
    @mock.patch('oslo_messaging._drivers.impl_zmq._multi_send', autospec=True)
    def test_zmqdriver_send(self, mock_multi_send, mock_cast):
        context = mock.Mock(autospec=impl_zmq.RpcContext)
        topic = 'testtopic'
        msg = 'jeronimo'
        self.driver.send(oslo_messaging.Target(topic=topic), context, msg,
                         False, 0, False)
        mock_multi_send.assert_called_with(self.driver, mock_cast, context,
                                           topic, msg,
                                           allowed_remote_exmods=[],
                                           envelope=False, pooled=True)

    @mock.patch('oslo_messaging._drivers.impl_zmq._cast', autospec=True)
    @mock.patch('oslo_messaging._drivers.impl_zmq._multi_send', autospec=True)
    def test_zmqdriver_send_notification(self, mock_multi_send, mock_cast):
        context = mock.Mock(autospec=impl_zmq.RpcContext)
        topic = 'testtopic.foo'
        topic_reformat = 'testtopic-foo'
        msg = 'jeronimo'
        self.driver.send_notification(oslo_messaging.Target(topic=topic),
                                      context, msg, False, False)
        mock_multi_send.assert_called_with(self.driver, mock_cast, context,
                                           topic_reformat, msg,
                                           allowed_remote_exmods=[],
                                           envelope=False, pooled=True)

    @mock.patch('oslo_messaging._drivers.impl_zmq.ZmqListener', autospec=True)
    @mock.patch('oslo_messaging._drivers.impl_zmq.Connection', autospec=True)
    def test_zmqdriver_listen(self, mock_connection, mock_listener):
        mock_listener.return_value = listener = mock.Mock()
        mock_connection.return_value = conn = mock.Mock()
        conn.create_consumer = mock.Mock()
        conn.consume_in_thread = mock.Mock()
        topic = 'testtopic.foo'
        self.driver.listen(oslo_messaging.Target(topic=topic))
        conn.create_consumer.assert_called_with(topic, listener, fanout=True)

    @mock.patch('oslo_messaging._drivers.impl_zmq.ZmqListener', autospec=True)
    @mock.patch('oslo_messaging._drivers.impl_zmq.Connection', autospec=True)
    def test_zmqdriver_listen_for_notification(self, mock_connection,
                                               mock_listener):
        mock_listener.return_value = listener = mock.Mock()
        mock_connection.return_value = conn = mock.Mock()
        conn.create_consumer = mock.Mock()
        conn.consume_in_thread = mock.Mock()
        topic = 'testtopic.foo'
        data = [(oslo_messaging.Target(topic=topic), 0)]
        # NOTE(jamespage): Pooling not supported, just pass None for now.
        self.driver.listen_for_notifications(data, None)
        conn.create_consumer.assert_called_with("%s-%s" % (topic, 0), listener)


text:
#pragma once
#ifndef GWEN_CONTROLS_PROPERTY_BASEPROPERTY_H
#define GWEN_CONTROLS_PROPERTY_BASEPROPERTY_H

#include "rose/ctl/Widget.hpp"
#include "rose/Rose.hpp"
#include "rose/Skin.hpp"
#include "rose/Utility.hpp"

namespace rose {
namespace ctl {

class GWEN_EXPORT Property : public Widget
{
public:

    GWEN_CONTROL_INLINE(Property, Widget)
    {
        SetHeight(17);
    }

    virtual String GetPropertyValue() = 0;

    virtual void SetPropertyValue(const String & v, bool bFireChangeEvents = false) = 0;

    virtual bool IsEditing() = 0;

    virtual void DoChanged()
    {
        EventInfo info;
        info.String = GetPropertyValue();
        onChange.Call(this, info);
    }

    void OnPropertyValueChanged(rose::ctl::Widget* /*control*/)
    {
        DoChanged();
    }

    EventCaller onChange;
};

} //ctl
} //rose

#endif

redpajama_set_name: RedPajamaGithub


text:
Toggle Me

About Us

Blog

Affiliates

Contact Us


text:
<?xml version="1.0" encoding="UTF-8"?>
<config xmlns="experimentconfig" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="experimentconfig experimentconfig.xsd">
 <loader name="ARFFFolderLoader" datalocation="benchmark/data/AEEEM_WCHU" relative="false"/>
 <versionfilter name="MinClassNumberFilter" param="5" />
 <resultspath path="benchmark/results-csv"/>
 <setwisetrainer name="GPTraining" param="numberRuns:1,errorType2Weight:15" /> <eval name="NormalWekaEvaluation" param="" />
 <repetitions number="10" />
 <storage name="MySQLResultStorage" param="" />
</config>


text:
<?php

use Egulias\EmailValidator\EmailValidator;
use Egulias\EmailValidator\Validation\RFCValidation;

/**
 * An ID MIME Header for something like Message-ID or Content-ID.
 *
 * @author Chris Corbyn
 */
class Swift_Mime_Headers_IdentificationHeader extends Swift_Mime_Headers_AbstractHeader
{
    /**
     * The IDs used in the value of this Header.
     *
     * This may hold multiple IDs or just a single ID.
     *
     * @var string[]
     */
    private $ids = array();

    /**
     * The strict EmailValidator.
     *
     * @var EmailValidator
     */
    private $emailValidator;

    /**
     * Creates a new IdentificationHeader with the given $name and $id.
     *
     * @param string         $name
     * @param EmailValidator $emailValidator
     */
    public function __construct($name, EmailValidator $emailValidator)
    {
        $this->setFieldName($name);
        $this->emailValidator = $emailValidator;
    }

    /**
     * Get the type of Header that this instance represents.
     *
     * @see TYPE_TEXT, TYPE_PARAMETERIZED, TYPE_MAILBOX
     * @see TYPE_DATE, TYPE_ID, TYPE_PATH
     *
     * @return int
     */
    public function getFieldType()
    {
        return self::TYPE_ID;
    }

    /**
     * Set the model for the field body.
     *
     * This method takes a string ID, or an array of IDs.
     *
     * @param mixed $model
     *
     * @throws Swift_RfcComplianceException
     */
    public function setFieldBodyModel($model)
    {
        $this->setId($model);
    }

    /**
     * Get the model for the field body.
     *
     * This method returns an array of IDs
     *
     * @return array
     */
    public function getFieldBodyModel()
    {
        return $this->getIds();
    }

    /**
     * Set the ID used in the value of this header.
     *
     * @param string|array $id
     *
     * @throws Swift_RfcComplianceException
     */
    public function setId($id)
    {
        $this->setIds(is_array($id) ? $id : array($id));
    }

    /**
     * Get the ID used in the value of this Header.
     *
     * If multiple IDs are set only the first is returned.
     *
     * @return string
     */
    public function getId()
    {
        if (count($this->ids) > 0) {
            return $this->ids[0];
        }
    }

    /**
     * Set a collection of IDs to use in the value of this Header.
     *
     * @param string[] $ids
     *
     * @throws Swift_RfcComplianceException
     */
    public function setIds(array $ids)
    {
        $actualIds = array();

        foreach ($ids as $id) {
            $this->assertValidId($id);
            $actualIds[] = $id;
        }

        $this->clearCachedValueIf($this->ids != $actualIds);
        $this->ids = $actualIds;
    }

    /**
     * Get the list of IDs used in this Header.
     *
     * @return string[]
     */
    public function getIds()
    {
        return $this->ids;
    }

    /**
     * Get the string value of the body in this Header.
     *
     * This is not necessarily RFC 2822 compliant since folding white space will
     * not be added at this stage (see {@see toString()} for that).
     *
     * @see toString()
     *
     * @throws Swift_RfcComplianceException
     *
     * @return string
     */
    public function getFieldBody()
    {
        if (!$this->getCachedValue()) {
            $angleAddrs = array();

            foreach ($this->ids as $id) {
                $angleAddrs[] = '<'.$id.'>';
            }

            $this->setCachedValue(implode(' ', $angleAddrs));
        }

        return $this->getCachedValue();
    }

    /**
     * Throws an Exception if the id passed does not comply with RFC 2822.
     *
     * @param string $id
     *
     * @throws Swift_RfcComplianceException
     */
    private function assertValidId($id)
    {
        if (!$this->emailValidator->isValid($id, new RFCValidation())) {
            throw new Swift_RfcComplianceException('Invalid ID given <'.$id.'>');
        }
    }
}


text:
#ifndef snap7_h
#define snap7_h
//---------------------------------------------------------------------------
// Platform detection
//---------------------------------------------------------------------------
#if defined (_WIN32)||defined(_WIN64)||defined(__WIN32__)||defined(__WINDOWS__)
# define OS_WINDOWS
#endif

// Visual Studio needs this to use the correct time_t size
#if defined (_WIN32) && !defined(_WIN64)
# define _USE_32BIT_TIME_T
#endif

#if defined(unix) || defined(__unix__) || defined(__unix)
# define PLATFORM_UNIX
#endif

#if defined(__SVR4) || defined(__svr4__)
# define OS_SOLARIS
#endif

#if BSD>=0
# define OS_BSD
#endif

#if defined(__APPLE__)
# define OS_OSX
#endif

#if defined(PLATFORM_UNIX) || defined(OS_OSX)
# include <unistd.h>
# if defined(_POSIX_VERSION)
#   define POSIX
# endif
#endif

//---------------------------------------------------------------------------
// C++ Library
//---------------------------------------------------------------------------
#ifdef __cplusplus
#include <string>
#include <time.h>

// Visual C++ not C99 compliant (VS2008--)
#ifdef _MSC_VER
# if _MSC_VER >= 1600
#  include <stdint.h>  // VS2010++ have it
# else
   typedef signed __int8     int8_t;
   typedef signed __int16    int16_t;
   typedef signed __int32    int32_t;
   typedef signed __int64    int64_t;
   typedef unsigned __int8   uint8_t;
   typedef unsigned __int16  uint16_t;
   typedef unsigned __int32  uint32_t;
   typedef unsigned __int64  uint64_t;
   #ifdef _WIN64
     typedef unsigned __int64  uintptr_t;
   #else
     typedef unsigned __int32  uintptr_t;
   #endif
# endif
#else
# include <stdint.h>
#endif

extern "C" {
#endif
//---------------------------------------------------------------------------
// C exact length types
//---------------------------------------------------------------------------
#ifndef __cplusplus

#ifdef OS_BSD
#  include <stdint.h>
#  include <time.h>
#endif

#ifdef OS_OSX
#  include <stdint.h>
#  include <time.h>
#endif

#ifdef OS_SOLARIS
#  include <stdint.h>
#  include <time.h>
#endif

#if defined(_UINTPTR_T_DEFINED)
#  include <stdint.h>
#  include <time.h>
#endif

#if !defined(_UINTPTR_T_DEFINED) && !defined(OS_SOLARIS) && !defined(OS_BSD) && !defined(OS_OSX)
  typedef unsigned char   uint8_t;  //  8 bit unsigned integer
  typedef unsigned short  uint16_t; // 16 bit unsigned integer
  typedef unsigned int    uint32_t; // 32 bit unsigned integer
  typedef unsigned long   uintptr_t;// 64 bit unsigned integer
#endif

#endif

#ifdef OS_WINDOWS
# define S7API __stdcall
#else
# define S7API
#endif

#pragma pack(1)
//******************************************************************************
//                                   COMMON
//******************************************************************************
// Exact length types regardless of platform/processor
typedef uint8_t    byte;
typedef uint16_t   word;
typedef uint32_t   longword;
typedef byte       *pbyte;
typedef word       *pword;
typedef uintptr_t  S7Object; // multi platform/processor object reference
                             // DON'T CONFUSE IT WITH AN OLE OBJECT, IT'S SIMPLY
                             // AN INTEGER VALUE (32 OR 64 BIT) USED AS HANDLE.

#ifndef __cplusplus
typedef struct
{
  int   tm_sec;
  int   tm_min;
  int   tm_hour;
  int   tm_mday;
  int   tm_mon;
  int   tm_year;
  int   tm_wday;
  int   tm_yday;
  int   tm_isdst;
}tm;

#endif

const int errLibInvalidParam  = -1;
const int errLibInvalidObject = -2;

// CPU status
#define S7CpuStatusUnknown  0x00
#define S7CpuStatusRun      0x08
#define S7CpuStatusStop     0x04

// ISO Errors
const longword errIsoConnect            = 0x00010000; // Connection error
const longword errIsoDisconnect         = 0x00020000; // Disconnect error
const longword errIsoInvalidPDU         = 0x00030000; // Bad format
const longword errIsoInvalidDataSize    = 0x00040000; // Bad Datasize passed to send/recv buffer is invalid
const longword errIsoNullPointer    	= 0x00050000; // Null passed as pointer
const longword errIsoShortPacket    	= 0x00060000; // A short packet received
const longword errIsoTooManyFragments   = 0x00070000; // Too many packets without EoT flag
const longword errIsoPduOverflow    	= 0x00080000; // The sum of fragments data exceded maximum packet size
const longword errIsoSendPacket         = 0x00090000; // An error occurred during send
const longword errIsoRecvPacket         = 0x000A0000; // An error occurred during recv
const longword errIsoInvalidParams    	= 0x000B0000; // Invalid TSAP params
const longword errIsoResvd_1            = 0x000C0000; // Unassigned
const longword errIsoResvd_2            = 0x000D0000; // Unassigned
const longword errIsoResvd_3            = 0x000E0000; // Unassigned
const longword errIsoResvd_4            = 0x000F0000; // Unassigned

// Tag Struct
typedef struct{
	int Area;
	int DBNumber;
	int Start;
	int Size;
	int WordLen;
}TS7Tag, *PS7Tag;

//------------------------------------------------------------------------------
//                                  PARAMS LIST
//------------------------------------------------------------------------------
const int p_u16_LocalPort  	    = 1;
const int p_u16_RemotePort 	    = 2;
const int p_i32_PingTimeout	    = 3;
const int p_i32_SendTimeout     = 4;
const int p_i32_RecvTimeout     = 5;
const int p_i32_WorkInterval    = 6;
const int p_u16_SrcRef          = 7;
const int p_u16_DstRef          = 8;
const int p_u16_SrcTSap         = 9;
const int p_i32_PDURequest      = 10;
const int p_i32_MaxClients      = 11;
const int p_i32_BSendTimeout    = 12;
const int p_i32_BRecvTimeout    = 13;
const int p_u32_RecoveryTime    = 14;
const int p_u32_KeepAliveTime   = 15;

// Client/Partner Job status
const int JobComplete           = 0;
const int JobPending            = 1;

//******************************************************************************
//                                   CLIENT
//******************************************************************************

// Error codes
const longword errNegotiatingPDU            = 0x00100000;
const longword errCliInvalidParams          = 0x00200000;
const longword errCliJobPending             = 0x00300000;
const longword errCliTooManyItems           = 0x00400000;
const longword errCliInvalidWordLen         = 0x00500000;
const longword errCliPartialDataWritten     = 0x00600000;
const longword errCliSizeOverPDU            = 0x00700000;
const longword errCliInvalidPlcAnswer       = 0x00800000;
const longword errCliAddressOutOfRange      = 0x00900000;
const longword errCliInvalidTransportSize   = 0x00A00000;
const longword errCliWriteDataSizeMismatch  = 0x00B00000;
const longword errCliItemNotAvailable       = 0x00C00000;
const longword errCliInvalidValue           = 0x00D00000;
const longword errCliCannotStartPLC         = 0x00E00000;
const longword errCliAlreadyRun             = 0x00F00000;
const longword errCliCannotStopPLC          = 0x01000000;
const longword errCliCannotCopyRamToRom     = 0x01100000;
const longword errCliCannotCompress         = 0x01200000;
const longword errCliAlreadyStop            = 0x01300000;
const longword errCliFunNotAvailable        = 0x01400000;
const longword errCliUploadSequenceFailed   = 0x01500000;
const longword errCliInvalidDataSizeRecvd   = 0x01600000;
const longword errCliInvalidBlockType       = 0x01700000;
const longword errCliInvalidBlockNumber     = 0x01800000;
const longword errCliInvalidBlockSize       = 0x01900000;
const longword errCliDownloadSequenceFailed = 0x01A00000;
const longword errCliInsertRefused          = 0x01B00000;
const longword errCliDeleteRefused          = 0x01C00000;
const longword errCliNeedPassword           = 0x01D00000;
const longword errCliInvalidPassword        = 0x01E00000;
const longword errCliNoPasswordToSetOrClear = 0x01F00000;
const longword errCliJobTimeout             = 0x02000000;
const longword errCliPartialDataRead        = 0x02100000;
const longword errCliBufferTooSmall         = 0x02200000;
const longword errCliFunctionRefused        = 0x02300000;
const longword errCliDestroying             = 0x02400000;
const longword errCliInvalidParamNumber     = 0x02500000;
const longword errCliCannotChangeParam      = 0x02600000;

const int MaxVars     = 20; // Max vars that can be transferred with MultiRead/MultiWrite

// Client Connection Type
const word CONNTYPE_PG                      = 0x0001;  // Connect to the PLC as a PG
const word CONNTYPE_OP                      = 0x0002;  // Connect to the PLC as an OP
const word CONNTYPE_BASIC                   = 0x0003;  // Basic connection

// Area ID
const byte S7AreaPE   =	0x81;
const byte S7AreaPA   =	0x82;
const byte S7AreaMK   =	0x83;
const byte S7AreaDB   =	0x84;
const byte S7AreaCT   =	0x1C;
const byte S7AreaTM   =	0x1D;

// Word Length
const int S7WLBit     = 0x01;
const int S7WLByte    = 0x02;
const int S7WLWord    = 0x04;
const int S7WLDWord   = 0x06;
const int S7WLReal    = 0x08;
const int S7WLCounter = 0x1C;
const int S7WLTimer   = 0x1D;

// Block type
const byte Block_OB   = 0x38;
const byte Block_DB   = 0x41;
const byte Block_SDB  = 0x42;
const byte Block_FC   = 0x43;
const byte Block_SFC  = 0x44;
const byte Block_FB   = 0x45;
const byte Block_SFB  = 0x46;

// Sub Block Type
const byte SubBlk_OB  = 0x08;
const byte SubBlk_DB  = 0x0A;
const byte SubBlk_SDB = 0x0B;
const byte SubBlk_FC  = 0x0C;
const byte SubBlk_SFC = 0x0D;
const byte SubBlk_FB  = 0x0E;
const byte SubBlk_SFB = 0x0F;

// Block languages
const byte BlockLangAWL       = 0x01;
const byte BlockLangKOP       = 0x02;
const byte BlockLangFUP       = 0x03;
const byte BlockLangSCL       = 0x04;
const byte BlockLangDB        = 0x05;
const byte BlockLangGRAPH     = 0x06;

// Read/Write Multivars
typedef struct{
   int   Area;
   int   WordLen;
   int   Result;
   int   DBNumber;
   int   Start;
   int   Amount;
   void  *pdata;
} TS7DataItem, *PS7DataItem;

//typedef int TS7ResultItems[MaxVars];
//typedef TS7ResultItems *PS7ResultItems;

// List Blocks
typedef struct {
   int OBCount;
   int FBCount;
   int FCCount;
   int SFBCount;
   int SFCCount;
   int DBCount;
   int SDBCount;
} TS7BlocksList, *PS7BlocksList;

// Blocks info
typedef struct {
   int BlkType;    // Block Type (OB, DB)
   int BlkNumber;  // Block number
   int BlkLang;    // Block Language
   int BlkFlags;   // Block flags
   int MC7Size;    // The real size in bytes
   int LoadSize;   // Load memory size
   int LocalData;  // Local data
   int SBBLength;  // SBB Length
   int CheckSum;   // Checksum
   int Version;    // Block version
   // Chars info
   char CodeDate[11]; // Code date
   char IntfDate[11]; // Interface date
   char Author[9];    // Author
   char Family[9];    // Family
   char Header[9];    // Header
} TS7BlockInfo, *PS7BlockInfo ;

typedef word TS7BlocksOfType[0x2000];
typedef TS7BlocksOfType *PS7BlocksOfType;

// Order code
typedef struct {
   char Code[21];
   byte V1;
   byte V2;
   byte V3;
} TS7OrderCode, *PS7OrderCode;

// CPU Info
typedef struct {
   char ModuleTypeName[33];
   char SerialNumber[25];
   char ASName[25];
   char Copyright[27];
   char ModuleName[25];
} TS7CpuInfo, *PS7CpuInfo;

// CP Info
typedef struct {
   int MaxPduLengt;
   int MaxConnections;
   int MaxMpiRate;
   int MaxBusRate;
} TS7CpInfo, *PS7CpInfo;

// See §33.1 of "System Software for S7-300/400 System and Standard Functions"
// and see SFC51 description too
typedef struct {
   word LENTHDR;
   word N_DR;
} SZL_HEADER, *PSZL_HEADER;

typedef struct {
   SZL_HEADER Header;
   byte Data[0x4000-4];
} TS7SZL, *PS7SZL;

// SZL List of available SZL IDs : same as SZL but List items are big-endian adjusted
typedef struct {
   SZL_HEADER Header;
   word List[0x2000-2];
} TS7SZLList, *PS7SZLList;

// See §33.19 of "System Software for S7-300/400 System and Standard Functions"
typedef struct {
   word  sch_schal;
   word  sch_par;
   word  sch_rel;
   word  bart_sch;
   word  anl_sch;
} TS7Protection, *PS7Protection;

// Client completion callback
typedef void (S7API *pfn_CliCompletion) (void *usrPtr, int opCode, int opResult);
//------------------------------------------------------------------------------
//  Import prototypes
//------------------------------------------------------------------------------
S7Object S7API Cli_Create();
void S7API Cli_Destroy(S7Object *Client);
int S7API Cli_ConnectTo(S7Object Client, const char *Address, int Rack, int Slot);
int S7API Cli_SetConnectionParams(S7Object Client, const char *Address, word LocalTSAP, word RemoteTSAP);
int S7API Cli_SetConnectionType(S7Object Client, word ConnectionType);
int S7API Cli_Connect(S7Object Client);
int S7API Cli_Disconnect(S7Object Client);
int S7API Cli_GetParam(S7Object Client, int ParamNumber, void *pValue);
int S7API Cli_SetParam(S7Object Client, int ParamNumber, void *pValue);
int S7API Cli_SetAsCallback(S7Object Client, pfn_CliCompletion pCompletion, void *usrPtr);
// Data I/O main functions
int S7API Cli_ReadArea(S7Object Client, int Area, int DBNumber, int Start, int Amount, int WordLen, void *pUsrData);
int S7API Cli_WriteArea(S7Object Client, int Area, int DBNumber, int Start, int Amount, int WordLen, void *pUsrData);
int S7API Cli_ReadMultiVars(S7Object Client, PS7DataItem Item, int ItemsCount);
int S7API Cli_WriteMultiVars(S7Object Client, PS7DataItem Item, int ItemsCount);
// Data I/O Lean functions
int S7API Cli_DBRead(S7Object Client, int DBNumber, int Start, int Size, void *pUsrData);
int S7API Cli_DBWrite(S7Object Client, int DBNumber, int Start, int Size, void *pUsrData);
int S7API Cli_MBRead(S7Object Client, int Start, int Size, void *pUsrData);
int S7API Cli_MBWrite(S7Object Client, int Start, int Size, void *pUsrData);
int S7API Cli_EBRead(S7Object Client, int Start, int Size, void *pUsrData);
int S7API Cli_EBWrite(S7Object Client, int Start, int Size, void *pUsrData);
int S7API Cli_ABRead(S7Object Client, int Start, int Size, void *pUsrData);
int S7API Cli_ABWrite(S7Object Client, int Start, int Size, void *pUsrData);
int S7API Cli_TMRead(S7Object Client, int Start, int Amount, void *pUsrData);
int S7API Cli_TMWrite(S7Object Client, int Start, int Amount, void *pUsrData);
int S7API Cli_CTRead(S7Object Client, int Start, int Amount, void *pUsrData);
int S7API Cli_CTWrite(S7Object Client, int Start, int Amount, void *pUsrData);
// Directory functions
int S7API Cli_ListBlocks(S7Object Client, TS7BlocksList *pUsrData);
int S7API Cli_GetAgBlockInfo(S7Object Client, int BlockType, int BlockNum, TS7BlockInfo *pUsrData);
int S7API Cli_GetPgBlockInfo(S7Object Client, void *pBlock, TS7BlockInfo *pUsrData, int Size);
int S7API Cli_ListBlocksOfType(S7Object Client, int BlockType, TS7BlocksOfType *pUsrData, int *ItemsCount);
// Blocks functions
int S7API Cli_Upload(S7Object Client, int BlockType, int BlockNum, void *pUsrData, int *Size);
int S7API Cli_FullUpload(S7Object Client, int BlockType, int BlockNum, void *pUsrData, int *Size);
int S7API Cli_Download(S7Object Client, int BlockNum, void *pUsrData, int Size);
int S7API Cli_Delete(S7Object Client, int BlockType, int BlockNum);
int S7API Cli_DBGet(S7Object Client, int DBNumber, void *pUsrData, int *Size);
int S7API Cli_DBFill(S7Object Client, int DBNumber, int FillChar);
// Date/Time functions
int S7API Cli_GetPlcDateTime(S7Object Client, tm *DateTime);
int S7API Cli_SetPlcDateTime(S7Object Client, tm *DateTime);
int S7API Cli_SetPlcSystemDateTime(S7Object Client);
// System Info functions
int S7API Cli_GetOrderCode(S7Object Client, TS7OrderCode *pUsrData);
int S7API Cli_GetCpuInfo(S7Object Client, TS7CpuInfo *pUsrData);
int S7API Cli_GetCpInfo(S7Object Client, TS7CpInfo *pUsrData);
int S7API Cli_ReadSZL(S7Object Client, int ID, int Index, TS7SZL *pUsrData, int *Size);
int S7API Cli_ReadSZLList(S7Object Client, TS7SZLList *pUsrData, int *ItemsCount);
// Control functions
int S7API Cli_PlcHotStart(S7Object Client);
int S7API Cli_PlcColdStart(S7Object Client);
int S7API Cli_PlcStop(S7Object Client);
int S7API Cli_CopyRamToRom(S7Object Client, int Timeout);
int S7API Cli_Compress(S7Object Client, int Timeout);
int S7API Cli_GetPlcStatus(S7Object Client, int *Status);
// Security functions
int S7API Cli_GetProtection(S7Object Client, TS7Protection *pUsrData);
int S7API Cli_SetSessionPassword(S7Object Client, char *Password);
int S7API Cli_ClearSessionPassword(S7Object Client);
// Low level
int S7API Cli_IsoExchangeBuffer(S7Object Client, void *pUsrData, int *Size);
// Misc
int S7API Cli_GetExecTime(S7Object Client, int *Time);
int S7API Cli_GetLastError(S7Object Client, int *LastError);
int S7API Cli_GetPduLength(S7Object Client, int *Requested, int *Negotiated);
int S7API Cli_ErrorText(int Error, char *Text, int TextLen);
// 1.1.0
int S7API Cli_GetConnected(S7Object Client, int *Connected);
//------------------------------------------------------------------------------
//  Async functions
//------------------------------------------------------------------------------
int S7API Cli_AsReadArea(S7Object Client, int Area, int DBNumber, int Start, int Amount, int WordLen, void *pUsrData);
int S7API Cli_AsWriteArea(S7Object Client, int Area, int DBNumber, int Start, int Amount, int WordLen, void *pUsrData);
int S7API Cli_AsDBRead(S7Object Client, int DBNumber, int Start, int Size, void *pUsrData);
int S7API Cli_AsDBWrite(S7Object Client, int DBNumber, int Start, int Size, void *pUsrData);
int S7API Cli_AsMBRead(S7Object Client, int Start, int Size, void *pUsrData);
int S7API Cli_AsMBWrite(S7Object Client, int Start, int Size, void *pUsrData);
int S7API Cli_AsEBRead(S7Object Client, int Start, int Size, void *pUsrData);
int S7API Cli_AsEBWrite(S7Object Client, int Start, int Size, void *pUsrData);
int S7API Cli_AsABRead(S7Object Client, int Start, int Size, void *pUsrData);
int S7API Cli_AsABWrite(S7Object Client, int Start, int Size, void *pUsrData);
int S7API Cli_AsTMRead(S7Object Client, int Start, int Amount, void *pUsrData);
int S7API Cli_AsTMWrite(S7Object Client, int Start, int Amount, void *pUsrData);
int S7API Cli_AsCTRead(S7Object Client, int Start, int Amount, void *pUsrData);
int S7API Cli_AsCTWrite(S7Object Client, int Start, int Amount, void *pUsrData);
int S7API Cli_AsListBlocksOfType(S7Object Client, int BlockType, TS7BlocksOfType *pUsrData, int *ItemsCount);
int S7API Cli_AsReadSZL(S7Object Client, int ID, int Index, TS7SZL *pUsrData, int *Size);
int S7API Cli_AsReadSZLList(S7Object Client, TS7SZLList *pUsrData, int *ItemsCount);
int S7API Cli_AsUpload(S7Object Client, int BlockType, int BlockNum, void *pUsrData, int *Size);
int S7API Cli_AsFullUpload(S7Object Client, int BlockType, int BlockNum, void *pUsrData, int *Size);
int S7API Cli_AsDownload(S7Object Client, int BlockNum, void *pUsrData, int Size);
int S7API Cli_AsCopyRamToRom(S7Object Client, int Timeout);
int S7API Cli_AsCompress(S7Object Client, int Timeout);
int S7API Cli_AsDBGet(S7Object Client, int DBNumber, void *pUsrData, int *Size);
int S7API Cli_AsDBFill(S7Object Client, int DBNumber, int FillChar);
int S7API Cli_CheckAsCompletion(S7Object Client, int *opResult);
int S7API Cli_WaitAsCompletion(S7Object Client, int Timeout);

//******************************************************************************
//                                   SERVER
//******************************************************************************
const int OperationRead  = 0;
const int OperationWrite = 1;

const int mkEvent = 0;
const int mkLog   = 1;

// Server Area ID  (use with Register/unregister - Lock/unlock Area)
const int srvAreaPE = 0;
const int srvAreaPA = 1;
const int srvAreaMK = 2;
const int srvAreaCT = 3;
const int srvAreaTM = 4;
const int srvAreaDB = 5;

// Errors
const longword errSrvCannotStart        = 0x00100000; // Server cannot start
const longword errSrvDBNullPointer      = 0x00200000; // Passed null as PData
const longword errSrvAreaAlreadyExists  = 0x00300000; // Area Re-registration
const longword errSrvUnknownArea        = 0x00400000; // Unknown area
const longword errSrvInvalidParams      = 0x00500000; // Invalid param(s) supplied
const longword errSrvTooManyDB          = 0x00600000; // Cannot register DB
const longword errSrvInvalidParamNumber = 0x00700000; // Invalid param (srv_get/set_param)
const longword errSrvCannotChangeParam  = 0x00800000; // Cannot change because running

// TCP Server Event codes
const longword evcServerStarted       = 0x00000001;
const longword evcServerStopped       = 0x00000002;
const longword evcListenerCannotStart = 0x00000004;
const longword evcClientAdded         = 0x00000008;
const longword evcClientRejected      = 0x00000010;
const longword evcClientNoRoom        = 0x00000020;
const longword evcClientException     = 0x00000040;
const longword evcClientDisconnected  = 0x00000080;
const longword evcClientTerminated    = 0x00000100;
const longword evcClientsDropped      = 0x00000200;
const longword evcReserved_00000400   = 0x00000400; // actually unused
const longword evcReserved_00000800   = 0x00000800; // actually unused
const longword evcReserved_00001000   = 0x00001000; // actually unused
const longword evcReserved_00002000   = 0x00002000; // actually unused
const longword evcReserved_00004000   = 0x00004000; // actually unused
const longword evcReserved_00008000   = 0x00008000; // actually unused
// S7 Server Event Code
const longword evcPDUincoming  	      = 0x00010000;
const longword evcDataRead            = 0x00020000;
const longword evcDataWrite    	      = 0x00040000;
const longword evcNegotiatePDU        = 0x00080000;
const longword evcReadSZL             = 0x00100000;
const longword evcClock               = 0x00200000;
const longword evcUpload              = 0x00400000;
const longword evcDownload            = 0x00800000;
const longword evcDirectory           = 0x01000000;
const longword evcSecurity            = 0x02000000;
const longword evcControl             = 0x04000000;
const longword evcReserved_08000000   = 0x08000000; // actually unused
const longword evcReserved_10000000   = 0x10000000; // actually unused
const longword evcReserved_20000000   = 0x20000000; // actually unused
const longword evcReserved_40000000   = 0x40000000; // actually unused
const longword evcReserved_80000000   = 0x80000000; // actually unused
// Masks to enable/disable all events
const longword evcAll                 = 0xFFFFFFFF;
const longword evcNone                = 0x00000000;
// Event SubCodes
const word evsUnknown                 = 0x0000;
const word evsStartUpload             = 0x0001;
const word evsStartDownload           = 0x0001;
const word evsGetBlockList            = 0x0001;
const word evsStartListBoT            = 0x0002;
const word evsListBoT                 = 0x0003;
const word evsGetBlockInfo            = 0x0004;
const word evsGetClock                = 0x0001;
const word evsSetClock                = 0x0002;
const word evsSetPassword             = 0x0001;
const word evsClrPassword             = 0x0002;
// Event Params : functions group
const word grProgrammer               = 0x0041;
const word grCyclicData               = 0x0042;
const word grBlocksInfo               = 0x0043;
const word grSZL                      = 0x0044;
const word grPassword                 = 0x0045;
const word grBSend                    = 0x0046;
const word grClock                    = 0x0047;
const word grSecurity                 = 0x0045;
// Event Params : control codes
const word CodeControlUnknown         = 0x0000;
const word CodeControlColdStart       = 0x0001;
const word CodeControlWarmStart       = 0x0002;
const word CodeControlStop            = 0x0003;
const word CodeControlCompress        = 0x0004;
const word CodeControlCpyRamRom       = 0x0005;
const word CodeControlInsDel          = 0x0006;
// Event Result
const word evrNoError                 = 0x0000;
const word evrFragmentRejected        = 0x0001;
const word evrMalformedPDU            = 0x0002;
const word evrSparseBytes             = 0x0003;
const word evrCannotHandlePDU         = 0x0004;
const word evrNotImplemented          = 0x0005;
const word evrErrException            = 0x0006;
const word evrErrAreaNotFound         = 0x0007;
const word evrErrOutOfRange           = 0x0008;
const word evrErrOverPDU              = 0x0009;
const word evrErrTransportSize        = 0x000A;
const word evrInvalidGroupUData       = 0x000B;
const word evrInvalidSZL              = 0x000C;
const word evrDataSizeMismatch        = 0x000D;
const word evrCannotUpload            = 0x000E;
const word evrCannotDownload          = 0x000F;
const word evrUploadInvalidID         = 0x0010;
const word evrResNotFound             = 0x0011;

typedef struct{
	time_t EvtTime;    // Timestamp
	int EvtSender;     // Sender
	longword EvtCode;  // Event code
	word EvtRetCode;   // Event result
	word EvtParam1;    // Param 1 (if available)
	word EvtParam2;    // Param 2 (if available)
	word EvtParam3;    // Param 3 (if available)
	word EvtParam4;    // Param 4 (if available)
}TSrvEvent, *PSrvEvent;

// Server Events callback
typedef void (S7API *pfn_SrvCallBack)(void *usrPtr, PSrvEvent PEvent, int Size);
// Server Read/Write callback
typedef int(S7API *pfn_RWAreaCallBack)(void *usrPtr, int Sender, int Operation, PS7Tag PTag, void *pUsrData);

S7Object S7API Srv_Create();
void S7API Srv_Destroy(S7Object *Server);
int S7API Srv_GetParam(S7Object Server, int ParamNumber, void *pValue);
int S7API Srv_SetParam(S7Object Server, int ParamNumber, void *pValue);
int S7API Srv_StartTo(S7Object Server, const char *Address);
int S7API Srv_Start(S7Object Server);
int S7API Srv_Stop(S7Object Server);
int S7API Srv_RegisterArea(S7Object Server, int AreaCode, word Index, void *pUsrData, int Size);
int S7API Srv_UnregisterArea(S7Object Server, int AreaCode, word Index);
int S7API Srv_LockArea(S7Object Server, int AreaCode, word Index);
int S7API Srv_UnlockArea(S7Object Server, int AreaCode, word Index);
int S7API Srv_GetStatus(S7Object Server, int *ServerStatus, int *CpuStatus, int *ClientsCount);
int S7API Srv_SetCpuStatus(S7Object Server, int CpuStatus);
int S7API Srv_ClearEvents(S7Object Server);
int S7API Srv_PickEvent(S7Object Server, TSrvEvent *pEvent, int *EvtReady);
int S7API Srv_GetMask(S7Object Server, int MaskKind, longword *Mask);
int S7API Srv_SetMask(S7Object Server, int MaskKind, longword Mask);
int S7API Srv_SetEventsCallback(S7Object Server, pfn_SrvCallBack pCallback, void *usrPtr);
int S7API Srv_SetReadEventsCallback(S7Object Server, pfn_SrvCallBack pCallback, void *usrPtr);
int S7API Srv_SetRWAreaCallback(S7Object Server, pfn_RWAreaCallBack pCallback, void *usrPtr);
int S7API Srv_EventText(TSrvEvent *Event, char *Text, int TextLen);
int S7API Srv_ErrorText(int Error, char *Text, int TextLen);

//******************************************************************************
//                                   PARTNER
//******************************************************************************

// Status
const int par_stopped         = 0;   // stopped
const int par_connecting      = 1;   // running and active connecting
const int par_waiting         = 2;   // running and waiting for a connection
const int par_linked          = 3;   // running and connected : linked
const int par_sending         = 4;   // sending data
const int par_receiving       = 5;   // receiving data
const int par_binderror       = 6;   // error starting passive server

// Errors
const longword errParAddressInUse       = 0x00200000;
const longword errParNoRoom             = 0x00300000;
const longword errServerNoRoom          = 0x00400000;
const longword errParInvalidParams      = 0x00500000;
const longword errParNotLinked          = 0x00600000;
const longword errParBusy               = 0x00700000;
const longword errParFrameTimeout       = 0x00800000;
const longword errParInvalidPDU         = 0x00900000;
const longword errParSendTimeout        = 0x00A00000;
const longword errParRecvTimeout        = 0x00B00000;
const longword errParSendRefused        = 0x00C00000;
const longword errParNegotiatingPDU     = 0x00D00000;
const longword errParSendingBlock       = 0x00E00000;
const longword errParRecvingBlock       = 0x00F00000;
const longword errParBindError          = 0x01000000;
const longword errParDestroying         = 0x01100000;
const longword errParInvalidParamNumber = 0x01200000; // Invalid param (par_get/set_param)
const longword errParCannotChangeParam  = 0x01300000; // Cannot change because running
const longword errParBufferTooSmall     = 0x01400000; // Raised by LabVIEW wrapper

// Brecv Data incoming Callback
typedef void (S7API *pfn_ParRecvCallBack)(void * usrPtr, int opResult, longword R_ID, void *pData, int Size);
// BSend Completion Callback
typedef void (S7API *pfn_ParSendCompletion)(void * usrPtr, int opResult);

S7Object S7API Par_Create(int Active);
void S7API Par_Destroy(S7Object *Partner);
int S7API Par_GetParam(S7Object Partner, int ParamNumber, void *pValue);
int S7API Par_SetParam(S7Object Partner, int ParamNumber, void *pValue);
int S7API Par_StartTo(S7Object Partner, const char *LocalAddress, const char *RemoteAddress,
    word LocTsap, word RemTsap);
int S7API Par_Start(S7Object Partner);
int S7API Par_Stop(S7Object Partner);
// BSend
int S7API Par_BSend(S7Object Partner, longword R_ID, void *pUsrData, int Size);
int S7API Par_AsBSend(S7Object Partner, longword R_ID, void *pUsrData, int Size);
int S7API Par_CheckAsBSendCompletion(S7Object Partner, int *opResult);
int S7API Par_WaitAsBSendCompletion(S7Object Partner, longword Timeout);
int S7API Par_SetSendCallback(S7Object Partner, pfn_ParSendCompletion pCompletion, void *usrPtr);
// BRecv
int S7API Par_BRecv(S7Object Partner, longword *R_ID, void *pData, int *Size, longword Timeout);
int S7API Par_CheckAsBRecvCompletion(S7Object Partner, int *opResult, longword *R_ID,
	void *pData, int *Size);
int S7API Par_SetRecvCallback(S7Object Partner, pfn_ParRecvCallBack pCompletion, void *usrPtr);
// Stat
int S7API Par_GetTimes(S7Object Partner, longword *SendTime, longword *RecvTime);
int S7API Par_GetStats(S7Object Partner, longword *BytesSent, longword *BytesRecv,
	longword *SendErrors, longword *RecvErrors);
int S7API Par_GetLastError(S7Object Partner, int *LastError);
int S7API Par_GetStatus(S7Object Partner, int *Status);
int S7API Par_ErrorText(int Error, char *Text, int TextLen);

#pragma pack()
#ifdef __cplusplus
 }
#endif // __cplusplus

#ifdef __cplusplus

//******************************************************************************
//                           CLIENT CLASS DEFINITION
//******************************************************************************
class TS7Client
{
private:
    S7Object Client;
public:
	TS7Client();
	~TS7Client();
    // Control functions
    int Connect();
    int ConnectTo(const char *RemAddress, int Rack, int Slot);
    int SetConnectionParams(const char *RemAddress, word LocalTSAP, word RemoteTSAP);
    int SetConnectionType(word ConnectionType);
    int Disconnect();
    int GetParam(int ParamNumber, void *pValue);
    int SetParam(int ParamNumber, void *pValue);
    // Data I/O Main functions
    int ReadArea(int Area, int DBNumber, int Start, int Amount, int WordLen, void *pUsrData);
    int WriteArea(int Area, int DBNumber, int Start, int Amount, int WordLen, void *pUsrData);
    int ReadMultiVars(PS7DataItem Item, int ItemsCount);
    int WriteMultiVars(PS7DataItem Item, int ItemsCount);
    // Data I/O Lean functions
    int DBRead(int DBNumber, int Start, int Size, void *pUsrData);
    int DBWrite(int DBNumber, int Start, int Size, void *pUsrData);
    int MBRead(int Start, int Size, void *pUsrData);
    int MBWrite(int Start, int Size, void *pUsrData);
    int EBRead(int Start, int Size, void *pUsrData);
    int EBWrite(int Start, int Size, void *pUsrData);
    int ABRead(int Start, int Size, void *pUsrData);
    int ABWrite(int Start, int Size, void *pUsrData);
    int TMRead(int Start, int Amount, void *pUsrData);
    int TMWrite(int Start, int Amount, void *pUsrData);
    int CTRead(int Start, int Amount, void *pUsrData);
    int CTWrite(int Start, int Amount, void *pUsrData);
    // Directory functions
    int ListBlocks(PS7BlocksList pUsrData);
    int GetAgBlockInfo(int BlockType, int BlockNum, PS7BlockInfo pUsrData);
    int GetPgBlockInfo(void *pBlock, PS7BlockInfo pUsrData, int Size);
    int ListBlocksOfType(int BlockType, TS7BlocksOfType *pUsrData, int *ItemsCount);
    // Blocks functions
    int Upload(int BlockType, int BlockNum, void *pUsrData, int *Size);
    int FullUpload(int BlockType, int BlockNum, void *pUsrData, int *Size);
    int Download(int BlockNum, void *pUsrData, int Size);
    int Delete(int BlockType, int BlockNum);
    int DBGet(int DBNumber, void *pUsrData, int *Size);
    int DBFill(int DBNumber, int FillChar);
    // Date/Time functions
    int GetPlcDateTime(tm *DateTime);
    int SetPlcDateTime(tm *DateTime);
    int SetPlcSystemDateTime();
    // System Info functions
    int GetOrderCode(PS7OrderCode pUsrData);
    int GetCpuInfo(PS7CpuInfo pUsrData);
    int GetCpInfo(PS7CpInfo pUsrData);
	int ReadSZL(int ID, int Index, PS7SZL pUsrData, int *Size);
	int ReadSZLList(PS7SZLList pUsrData, int *ItemsCount);
	// Control functions
	int PlcHotStart();
	int PlcColdStart();
	int PlcStop();
	int CopyRamToRom(int Timeout);
	int Compress(int Timeout);
	// Security functions
	int GetProtection(PS7Protection pUsrData);
	int SetSessionPassword(char *Password);
	int ClearSessionPassword();
	// Properties
	int ExecTime();
	int LastError();
	int PDURequested();
	int PDULength();
	int PlcStatus();
	bool Connected();
	// Async functions
	int SetAsCallback(pfn_CliCompletion pCompletion, void *usrPtr);
	bool CheckAsCompletion(int *opResult);
	int WaitAsCompletion(longword Timeout);
	int AsReadArea(int Area, int DBNumber, int Start, int Amount, int WordLen, void *pUsrData);
	int AsWriteArea(int Area, int DBNumber, int Start, int Amount, int WordLen, void *pUsrData);
	int AsListBlocksOfType(int BlockType, PS7BlocksOfType pUsrData, int *ItemsCount);
	int AsReadSZL(int ID, int Index, PS7SZL pUsrData, int *Size);
	int AsReadSZLList(PS7SZLList pUsrData, int *ItemsCount);
	int AsUpload(int BlockType, int BlockNum, void *pUsrData, int *Size);
	int AsFullUpload(int BlockType, int BlockNum, void *pUsrData, int *Size);
	int AsDownload(int BlockNum, void *pUsrData,  int Size);
	int AsCopyRamToRom(int Timeout);
	int AsCompress(int Timeout);
	int AsDBRead(int DBNumber, int Start, int Size, void *pUsrData);
	int AsDBWrite(int DBNumber, int Start, int Size, void *pUsrData);
	int AsMBRead(int Start, int Size, void *pUsrData);
	int AsMBWrite(int Start, int Size, void *pUsrData);
	int AsEBRead(int Start, int Size, void *pUsrData);
	int AsEBWrite(int Start, int Size, void *pUsrData);
	int AsABRead(int Start, int Size, void *pUsrData);
	int AsABWrite(int Start, int Size, void *pUsrData);
    int AsTMRead(int Start, int Amount, void *pUsrData);
    int AsTMWrite(int Start, int Amount, void *pUsrData);
    int AsCTRead(int Start, int Amount, void *pUsrData);
	int AsCTWrite(int Start, int Amount, void *pUsrData);
    int AsDBGet(int DBNumber, void *pUsrData, int *Size);
	int AsDBFill(int DBNumber, int FillChar);
};
typedef TS7Client *PS7Client;
//******************************************************************************
//                           SERVER CLASS DEFINITION
//******************************************************************************
class TS7Server
{
private:
    S7Object Server;
public:
    TS7Server();
    ~TS7Server();
    // Control
    int Start();
    int StartTo(const char *Address);
    int Stop();
    int GetParam(int ParamNumber, void *pValue);
    int SetParam(int ParamNumber, void *pValue);
    // Events
    int SetEventsCallback(pfn_SrvCallBack PCallBack, void *UsrPtr);
	int SetReadEventsCallback(pfn_SrvCallBack PCallBack, void *UsrPtr);
	int SetRWAreaCallback(pfn_RWAreaCallBack PCallBack, void *UsrPtr);
    bool PickEvent(TSrvEvent *pEvent);
    void ClearEvents();
    longword GetEventsMask();
    longword GetLogMask();
    void SetEventsMask(longword Mask);
    void SetLogMask(longword Mask);
    // Resources
    int RegisterArea(int AreaCode, word Index, void *pUsrData, word Size);
    int UnregisterArea(int AreaCode, word Index);
    int LockArea(int AreaCode, word Index);
    int UnlockArea(int AreaCode, word Index);
    // Properties
    int ServerStatus();
    int GetCpuStatus();
    int SetCpuStatus(int Status);
	int ClientsCount();
};
typedef TS7Server *PS7Server;

//******************************************************************************
//                          PARTNER CLASS DEFINITION
//******************************************************************************
class TS7Partner
{
private:
	S7Object Partner; // Partner Handle
public:
	TS7Partner(bool Active);
	~TS7Partner();
	// Control
	int GetParam(int ParamNumber, void *pValue);
	int SetParam(int ParamNumber, void *pValue);
	int Start();
	int StartTo(const char *LocalAddress,
				const char *RemoteAddress,
				int LocalTSAP,
				int RemoteTSAP);
	int Stop();
	// Data I/O functions : BSend
	int BSend(longword R_ID, void *pUsrData, int Size);
	int AsBSend(longword R_ID, void *pUsrData, int Size);
	bool CheckAsBSendCompletion(int *opResult);
	int WaitAsBSendCompletion(longword Timeout);
	int SetSendCallback(pfn_ParSendCompletion pCompletion, void *usrPtr);
	// Data I/O functions : BRecv
	int BRecv(longword *R_ID, void *pUsrData, int *Size, longword Timeout);
	bool CheckAsBRecvCompletion(int *opResult, longword *R_ID, void *pUsrData, int *Size);
	int SetRecvCallback(pfn_ParRecvCallBack pCallback, void *usrPtr);
	// Properties
	int Status();
	int LastError();
	int GetTimes(longword *SendTime, longword *RecvTime);
	int GetStats(longword *BytesSent,
				 longword *BytesRecv,
				 longword *ErrSend,
				 longword *ErrRecv);
	bool Linked();
};
typedef TS7Partner *PS7Partner;
//******************************************************************************
//                               TEXT ROUTINES
// Only for C++, for pure C use xxx_ErrorText() which uses *char
//******************************************************************************
#define TextLen 1024

// String type
// Here we define generic TextString (by default mapped onto std::string).
// So you can change it if needed (Unicodestring, Ansistring etc...)

typedef std::string TextString;

TextString CliErrorText(int Error);
TextString SrvErrorText(int Error);
TextString ParErrorText(int Error);
TextString SrvEventText(TSrvEvent *Event);

#endif // __cplusplus
#endif // snap7_h


text:
#if ! defined _Rel_map_h
#define _Rel_map_h 1

/* $Id: Rel_map.h,v 1.1.1.1 2004/09/13 21:07:48 mstrout Exp $ */

#if ! defined _pres_gen_h
#include <omega/pres_gen.h>
#endif
#if ! defined _pres_var_h
#include <omega/pres_var.h>
#endif

namespace omega {

//
// Mapping for relations
// When a relation operation needs to re-arrange the variables,
//  it describes the re-arragement with a mapping, and then calls
//  align to re-arrange them.
//
// In a mapping, map_in (map_out/map_set) gives the new type and
//  position of each of the old input (output/set) variables.
// For variables being mapped to Input, Output, or Set variables,
//  the position is the new position in the tuple.
// For variables being mapped to Exists_Var, Forall_Var, or
//  Wildcard_Var, the positions can be used to map multiple
//  variables to the same quantified variable, by providing
//  the same position.  Each variable with a negative position
//  is given a unique quantified variable that is NOT listed
//  in the seen_exists_ids list.
// I'm not sure what the positions mean for Global_Vars - perhaps
//  they are ignored?
//
// Currently, align seems to support only mapping to Set, Input,
//  Output, and Exists vars.
//

class Mapping {
public:
  inline  Mapping(int no_in, int no_out): n_input(no_in), n_output(no_out) {}
  inline  Mapping(int no_set): n_input(no_set), n_output(0){}
  inline  Mapping(const Mapping &m): n_input(m.n_input), n_output(m.n_output) {
    int i;
    for(i=1; i<=n_input; i++) map_in_kind[i] = m.map_in_kind[i];
    for(i=1; i<=n_input; i++) map_in_pos[i]  = m.map_in_pos[i];
    for(i=1; i<=n_output;i++) map_out_kind[i] = m.map_out_kind[i];
    for(i=1; i<=n_output;i++) map_out_pos[i] = m.map_out_pos[i];
  }

  inline void set_map (Var_Kind in_kind, int pos, Var_Kind type, int map) {
    if(in_kind==Input_Var)
      set_map_in(pos,type,map);
    else if(in_kind==Set_Var)
      set_map_in(pos,type,map);
    else if(in_kind==Output_Var)
      set_map_out(pos,type,map);
    else
      assert(0);
  }

  inline void set_map_in (int pos, Var_Kind type, int map) {
    assert(pos>=1 && pos<=n_input);
    map_in_kind[pos] = type;
    map_in_pos[pos] = map;
  }
  inline void set_map_set (int pos, Var_Kind type, int map) {
    assert(pos>=1 && pos<=n_input);
    map_in_kind[pos] = type;
    map_in_pos[pos] = map;
  }

  inline void set_map_out(int pos, Var_Kind type, int map) {
    assert(pos>=1 && pos<=n_output);
    map_out_kind[pos] = type;
    map_out_pos[pos] = map;
  }

  inline Var_Kind get_map_in_kind(int pos)  const {
    assert(pos>=1 && pos<=n_input);
    return map_in_kind[pos];
  }

  inline int get_map_in_pos(int pos)  const {
    assert(pos>=1 && pos<=n_input);
    return map_in_pos[pos];
  }

  inline Var_Kind get_map_out_kind(int pos)  const {
    assert(pos>=1 && pos<=n_output);
    return map_out_kind[pos];
  }

  inline int get_map_out_pos(int pos)  const {
    assert(pos>=1 && pos<=n_output);
    return map_out_pos[pos];
  }

  inline int n_in()  const { return n_input;  }
  inline int n_out() const { return n_output; }

  // If a tuple as a whole becomes the new Input or Output tuple,
  //  return the Tuple of they will become (Input, Output)
  // Return Unknown_Tuple otherwise

  inline Argument_Tuple get_tuple_fate(Argument_Tuple t, int prefix = -1) const
	{ return   t== Input_Tuple ?  get_input_fate(prefix) :
                  (t==Output_Tuple ? get_output_fate(prefix) : Unknown_Tuple); }

  inline Argument_Tuple get_set_fate(int prefix = -1)  const
        { return get_input_fate(prefix); }

  inline Argument_Tuple get_input_fate(int prefix = -1)  const
	{
	    if (prefix < 0) prefix = n_input;
	    assert(n_input >= prefix);
	    if (n_input < prefix)
		return Unknown_Tuple;
	    Var_Kind vf = map_in_kind[1];
	    for (int i = 1; i<=prefix; i++)
		if (map_in_pos[i]!=i || map_in_kind[i]!=vf)
		    return Unknown_Tuple;

	    return vf == Input_Var  ? Input_Tuple
		 : vf == Set_Var    ? Set_Tuple
	         : vf == Output_Var ? Output_Tuple
		 : Unknown_Tuple;
	}
  inline Argument_Tuple get_output_fate(int prefix = -1) const
	{
	    if (prefix < 0) prefix = n_output;
	    assert(n_output >= prefix);
	    if (n_output < 1)
		return Unknown_Tuple;
	    Var_Kind vf = map_out_kind[1];
	    for (int i = 1; i<=prefix; i++)
		if (map_out_pos[i]!=i || map_out_kind[i]!=vf)
		    return Unknown_Tuple;
	    return vf == Input_Var  ? Input_Tuple
		 : vf == Set_Var    ? Set_Tuple
	         : vf == Output_Var ? Output_Tuple
		 : Unknown_Tuple;
	}

  inline static Mapping Identity(int inp, int outp)
    {
	Mapping m(inp, outp); int i;
	for(i=1; i<=m.n_input; i++) m.set_map(Input_Var, i, Input_Var, i);
	for(i=1; i<=m.n_output;i++) m.set_map(Output_Var, i, Output_Var, i);
	return m;
    }

  inline static Mapping Identity(int setvars)
    {
	Mapping m(setvars); int i;
	for(i=1; i<=setvars; i++) m.set_map(Set_Var, i, Set_Var, i);
	return m;
    }

private:
  int  n_input;
  int  n_output;
  Var_Kind map_in_kind[maxVars];
  int      map_in_pos[maxVars];
  Var_Kind map_out_kind[maxVars];
  int      map_out_pos[maxVars];
};

} // end of namespace omega

#endif


text:
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;

/**
 * @unrestricted
 */
Bindings.TempFile = class {
  constructor() {
    this._fileEntry = null;
    this._writer = null;
  }

  /**
   * @param {string} dirPath
   * @param {string} name
   * @return {!Promise.<!Bindings.TempFile>}
   */
  static create(dirPath, name) {
    var file = new Bindings.TempFile();

    function requestTempFileSystem() {
      return new Promise(window.requestFileSystem.bind(window, window.TEMPORARY, 10));
    }

    /**
     * @param {!FileSystem} fs
     */
    function getDirectoryEntry(fs) {
      return new Promise(fs.root.getDirectory.bind(fs.root, dirPath, {create: true}));
    }

    /**
     * @param {!DirectoryEntry} dir
     */
    function getFileEntry(dir) {
      return new Promise(dir.getFile.bind(dir, name, {create: true}));
    }

    /**
     * @param {!FileEntry} fileEntry
     */
    function createFileWriter(fileEntry) {
      file._fileEntry = fileEntry;
      return new Promise(fileEntry.createWriter.bind(fileEntry));
    }

    /**
     * @param {!FileWriter} writer
     */
    function truncateFile(writer) {
      if (!writer.length) {
        file._writer = writer;
        return Promise.resolve(file);
      }

      /**
       * @param {function(?)} fulfill
       * @param {function(*)} reject
       */
      function truncate(fulfill, reject) {
        writer.onwriteend = fulfill;
        writer.onerror = reject;
        writer.truncate(0);
      }

      function didTruncate() {
        file._writer = writer;
        writer.onwriteend = null;
        writer.onerror = null;
        return Promise.resolve(file);
      }

      function onTruncateError(e) {
        writer.onwriteend = null;
        writer.onerror = null;
        throw e;
      }

      return new Promise(truncate).then(didTruncate, onTruncateError);
    }

    return Bindings.TempFile.ensureTempStorageCleared()
        .then(requestTempFileSystem)
        .then(getDirectoryEntry)
        .then(getFileEntry)
        .then(createFileWriter)
        .then(truncateFile);
  }

  /**
   * @return {!Promise.<undefined>}
   */
  static ensureTempStorageCleared() {
    if (!Bindings.TempFile._storageCleanerPromise) {
      Bindings.TempFile._storageCleanerPromise =
          Services.serviceManager.createAppService('utility_shared_worker', 'TempStorage', true).then(service => {
            if (service)
              return service.send('clear');
          });
    }
    return Bindings.TempFile._storageCleanerPromise;
  }

  /**
   * @param {!Array.<string>} strings
   * @param {function(number)} callback
   */
  write(strings, callback) {
    var blob = new Blob(strings, {type: 'text/plain'});
    this._writer.onerror = function(e) {
      Common.console.error('Failed to write into a temp file: ' + e.target.error.message);
      callback(-1);
    };
    this._writer.onwriteend = function(e) {
      callback(e.target.length);
    };
    this._writer.write(blob);
  }

  finishWriting() {
    this._writer = null;
  }

  /**
   * @param {function(?string)} callback
   */
  read(callback) {
    this.readRange(undefined, undefined, callback);
  }

  /**
   * @param {number|undefined} startOffset
   * @param {number|undefined} endOffset
   * @param {function(?string)} callback
   */
  readRange(startOffset, endOffset, callback) {
    /**
     * @param {!Blob} file
     */
    function didGetFile(file) {
      var reader = new FileReader();

      if (typeof startOffset === 'number' || typeof endOffset === 'number')
        file = file.slice(/** @type {number} */ (startOffset), /** @type {number} */ (endOffset));
      /**
       * @this {FileReader}
       */
      reader.onloadend = function(e) {
        callback(/** @type {?string} */ (this.result));
      };
      reader.onerror = function(error) {
        Common.console.error('Failed to read from temp file: ' + error.message);
      };
      reader.readAsText(file);
    }
    function didFailToGetFile(error) {
      Common.console.error('Failed to load temp file: ' + error.message);
      callback(null);
    }
    this._fileEntry.file(didGetFile, didFailToGetFile);
  }

  /**
   * @param {!Common.OutputStream} outputStream
   * @param {!Bindings.OutputStreamDelegate} delegate
   */
  copyToOutputStream(outputStream, delegate) {
    /**
     * @param {!File} file
     */
    function didGetFile(file) {
      var reader = new Bindings.ChunkedFileReader(file, 10 * 1000 * 1000, delegate);
      reader.start(outputStream);
    }

    function didFailToGetFile(error) {
      Common.console.error('Failed to load temp file: ' + error.message);
      outputStream.close();
    }

    this._fileEntry.file(didGetFile, didFailToGetFile);
  }

  remove() {
    if (this._fileEntry)
      this._fileEntry.remove(function() {});
  }
};

/**
 * @unrestricted
 */
Bindings.DeferredTempFile = class {
  /**
   * @param {string} dirPath
   * @param {string} name
   */
  constructor(dirPath, name) {
    /** @type {!Array.<!{strings: !Array.<string>, callback: ?function(number)}>} */
    this._chunks = [];
    this._tempFile = null;
    this._isWriting = false;
    this._finishCallback = null;
    this._finishedWriting = false;
    this._callsPendingOpen = [];
    this._pendingReads = [];
    Bindings.TempFile.create(dirPath, name)
        .then(this._didCreateTempFile.bind(this), this._failedToCreateTempFile.bind(this));
  }

  /**
   * @param {!Array.<string>} strings
   * @param {function(number)=} callback
   */
  write(strings, callback) {
    if (this._finishCallback)
      throw new Error('No writes are allowed after close.');
    this._chunks.push({strings: strings, callback: callback || null});
    if (this._tempFile && !this._isWriting)
      this._writeNextChunk();
  }

  /**
   * @param {function(?Bindings.TempFile)} callback
   */
  finishWriting(callback) {
    this._finishCallback = callback;
    if (this._finishedWriting)
      callback(this._tempFile);
    else if (!this._isWriting && !this._chunks.length)
      this._notifyFinished();
  }

  /**
   * @param {*} e
   */
  _failedToCreateTempFile(e) {
    Common.console.error('Failed to create temp file ' + e.code + ' : ' + e.message);
    this._notifyFinished();
  }

  /**
   * @param {!Bindings.TempFile} tempFile
   */
  _didCreateTempFile(tempFile) {
    this._tempFile = tempFile;
    var callsPendingOpen = this._callsPendingOpen;
    this._callsPendingOpen = null;
    for (var i = 0; i < callsPendingOpen.length; ++i)
      callsPendingOpen[i]();
    if (this._chunks.length)
      this._writeNextChunk();
  }

  _writeNextChunk() {
    // File was deleted while create or write was in-flight.
    if (!this._tempFile)
      return;
    var chunk = this._chunks.shift();
    this._isWriting = true;
    this._tempFile.write(
        /** @type {!Array.<string>} */ (chunk.strings), this._didWriteChunk.bind(this, chunk.callback));
  }

  /**
   * @param {?function(number)} callback
   * @param {number} size
   */
  _didWriteChunk(callback, size) {
    this._isWriting = false;
    if (size === -1) {
      this._tempFile = null;
      this._notifyFinished();
      return;
    }
    if (callback)
      callback(size);
    if (this._chunks.length)
      this._writeNextChunk();
    else if (this._finishCallback)
      this._notifyFinished();
  }

  _notifyFinished() {
    this._finishedWriting = true;
    if (this._tempFile)
      this._tempFile.finishWriting();
    var chunks = this._chunks;
    this._chunks = [];
    for (var i = 0; i < chunks.length; ++i) {
      if (chunks[i].callback)
        chunks[i].callback(-1);
    }
    if (this._finishCallback)
      this._finishCallback(this._tempFile);
    var pendingReads = this._pendingReads;
    this._pendingReads = [];
    for (var i = 0; i < pendingReads.length; ++i)
      pendingReads[i]();
  }

  /**
   * @param {number|undefined} startOffset
   * @param {number|undefined} endOffset
   * @param {function(string?)} callback
   */
  readRange(startOffset, endOffset, callback) {
    if (!this._finishedWriting) {
      this._pendingReads.push(this.readRange.bind(this, startOffset, endOffset, callback));
      return;
    }
    if (!this._tempFile) {
      callback(null);
      return;
    }
    this._tempFile.readRange(startOffset, endOffset, callback);
  }

  /**
   * @param {!Common.OutputStream} outputStream
   * @param {!Bindings.OutputStreamDelegate} delegate
   */
  copyToOutputStream(outputStream, delegate) {
    if (!this._finishedWriting) {
      this._pendingReads.push(this.copyToOutputStream.bind(this, outputStream, delegate));
      return;
    }
    if (this._tempFile)
      this._tempFile.copyToOutputStream(outputStream, delegate);
  }

  remove() {
    if (this._callsPendingOpen) {
      this._callsPendingOpen.push(this.remove.bind(this));
      return;
    }
    if (this._tempFile)
      this._tempFile.remove();
    this._tempFile = null;
  }
};

/**
 * @implements {SDK.BackingStorage}
 * @unrestricted
 */
Bindings.TempFileBackingStorage = class {
  /**
   * @param {string} dirName
   */
  constructor(dirName) {
    this._dirName = dirName;
    this.reset();
  }

  /**
   * @override
   * @param {string} string
   */
  appendString(string) {
    this._strings.push(string);
    this._stringsLength += string.length;
    var flushStringLength = 10 * 1024 * 1024;
    if (this._stringsLength > flushStringLength)
      this._flush(false);
  }

  /**
   * @override
   * @param {string} string
   * @return {function():!Promise.<?string>}
   */
  appendAccessibleString(string) {
    this._flush(false);
    this._strings.push(string);
    var chunk = /** @type {!Bindings.TempFileBackingStorage.Chunk} */ (this._flush(true));

    /**
     * @param {!Bindings.TempFileBackingStorage.Chunk} chunk
     * @param {!Bindings.DeferredTempFile} file
     * @return {!Promise.<?string>}
     */
    function readString(chunk, file) {
      if (chunk.string)
        return /** @type {!Promise.<?string>} */ (Promise.resolve(chunk.string));

      console.assert(chunk.endOffset);
      if (!chunk.endOffset)
        return Promise.reject('Nor string nor offset to the string in the file were found.');

      /**
       * @param {function(?string)} fulfill
       * @param {function(*)} reject
       */
      function readRange(fulfill, reject) {
        // FIXME: call reject for null strings.
        file.readRange(chunk.startOffset, chunk.endOffset, fulfill);
      }

      return new Promise(readRange);
    }

    return readString.bind(null, chunk, this._file);
  }

  /**
   * @param {boolean} createChunk
   * @return {?Bindings.TempFileBackingStorage.Chunk}
   */
  _flush(createChunk) {
    if (!this._strings.length)
      return null;

    var chunk = null;
    if (createChunk) {
      console.assert(this._strings.length === 1);
      chunk = {string: this._strings[0], startOffset: 0, endOffset: 0};
    }

    /**
     * @this {Bindings.TempFileBackingStorage}
     * @param {?Bindings.TempFileBackingStorage.Chunk} chunk
     * @param {number} fileSize
     */
    function didWrite(chunk, fileSize) {
      if (fileSize === -1)
        return;
      if (chunk) {
        chunk.startOffset = this._fileSize;
        chunk.endOffset = fileSize;
        chunk.string = null;
      }
      this._fileSize = fileSize;
    }

    this._file.write(this._strings, didWrite.bind(this, chunk));
    this._strings = [];
    this._stringsLength = 0;
    return chunk;
  }

  /**
   * @override
   */
  finishWriting() {
    this._flush(false);
    this._file.finishWriting(function() {});
  }

  /**
   * @override
   */
  reset() {
    if (this._file)
      this._file.remove();
    this._file = new Bindings.DeferredTempFile(this._dirName, String(Date.now()));
    /**
     * @type {!Array.<string>}
     */
    this._strings = [];
    this._stringsLength = 0;
    this._fileSize = 0;
  }

  /**
   * @param {!Common.OutputStream} outputStream
   * @param {!Bindings.OutputStreamDelegate} delegate
   */
  writeToStream(outputStream, delegate) {
    this._file.copyToOutputStream(outputStream, delegate);
  }
};

/**
 * @typedef {{
 *      string: ?string,
 *      startOffset: number,
 *      endOffset: number
 * }}
 */
Bindings.TempFileBackingStorage.Chunk;


text:
Example demonstrating how to do authentication using Facebook OAuth on
iOS and with a NodeJS Backend.

Run the server locally:

```shell
$ cd server
$ npm install
$ node app.js
```

Load your browser to http://localhost:6001/LanguageTranslation/api/v1/token?fbtoken=XXX where XXX is your Facebook token.

## Server deployment:

First, you must use the Cloud Foundary tool to create the services on your Bluemix account:

``` shell
$ cf login
$ cf create-service speech_to_text standard speech-to-text-service
$ cf create-service text_to_speech standard text-to-speech-service
$ cf create-service language_translation standard language-translation-service
$ cf create-user-provided-service facebook-authentication -p "APP_SECRET_GOES_HERE"
$ cf env
```

```
$ cd server
$ cf push
```


text:
<?xml version="1.0" encoding="utf-8"?>
 <selector xmlns:android="http://schemas.android.com/apk/res/android">
     <item android:state_pressed="true"
           android:drawable="@drawable/black_next_pressed" /> <!-- pressed -->
     <item android:drawable="@drawable/black_next_normal" /> <!-- default -->
 </selector>


text:
<?php

use yeesoft\db\PermissionsMigration;

class m150825_220620_add_page_permissions extends PermissionsMigration
{

    public function beforeUp()
    {
        $this->addPermissionsGroup('pageManagement', 'Page Management');
    }

    public function afterDown()
    {
        $this->deletePermissionsGroup('pageManagement');
    }

    public function getPermissions()
    {
        return [
            'pageManagement' => [
                'links' => [
                    '/admin/page/*',
                    '/admin/page/default/*',
                ],
                'viewPages' => [
                    'title' => 'View Pages',
                    'roles' => [self::ROLE_ADMIN],
                    'links' => [
                        '/admin/page/default/index',
                        '/admin/page/default/view',
                        '/admin/page/default/grid-sort',
                        '/admin/page/default/grid-page-size',
                    ],
                ],
                'editPages' => [
                    'title' => 'Edit Pages',
                    'roles' => [self::ROLE_ADMIN],
                    'childs' => ['viewPages'],
                    'links' => [
                        '/admin/page/default/update',
                        '/admin/page/default/bulk-activate',
                        '/admin/page/default/bulk-deactivate',
                        '/admin/page/default/toggle-attribute',
                    ],
                ],
                'createPages' => [
                    'title' => 'Create Pages',
                    'roles' => [self::ROLE_ADMIN],
                    'childs' => ['viewPages'],
                    'links' => [
                        '/admin/page/default/create',
                    ],
                ],
                'deletePages' => [
                    'title' => 'Delete Pages',
                    'roles' => [self::ROLE_ADMIN],
                    'childs' => ['viewPages'],
                    'links' => [
                        '/admin/page/default/delete',
                        '/admin/page/default/bulk-delete',
                    ],
                ],
                'fullPageAccess' => [
                    'title' => 'Full Page Access',
                    'roles' => [self::ROLE_ADMIN],
                ],
            ],
        ];
    }

}


text:
<!DOCTYPE html>

    <title>Unix Family Tree</title>

Unix Family Tree

Directed graph flow layout and shortest-path edge routing

    <link rel="stylesheet" href="../extern/hljs/styles/github.css">

    This is a cola.js rendering of the classic graphviz dot example.  We use graphlib-dot.js to parse the dot file.
    The initialization for cola here is interesting:

d3cola
    .avoidOverlaps(true)
    .flowLayout('x', 150)
    .size([width, height])
    .nodes(nodes)
    .links(edges)
    .jaccardLinkLengths(150);

    In particular, the call to flowLayout causes all edges not involved in a cycle (strongly connected component) to have a separation constraint generated between their source and sink,
    with a minimum spacing set to 150.  Specifying the 'x' axis achieves a left-to-right flow layout.  The default is top-to-bottom flow layout (i.e. 'y').
    You can also specify a function as the second argument to flowLayout that returns different separations for each edge.  Specify a different minimum as a second parameter to flowLayout.

    Another feature of this example is shortest-path edge routing.  That is, after layout stops, the edge paths are routed to avoid passing through node boundaries.
    To do this, we call the following function on the layout "end" event:

var routeEdges = function () {
    d3cola.prepareEdgeRouting(margin / 3);
    link.attr("d", function (d) { return lineFunction(d3cola.routeEdge(d)); });
    if (isIE()) link.each(function (d) { this.parentNode.insertBefore(this, this) });
}

        The function prepareEdgeRouting(padding) creates a tangent visibility graph over the polygonal boundaries of the nodes.
        The padding parameter controls how close edges can come to the node boundaries.
        Here we set it to be a third of the minimum spacing that layout allows between nodes.
        This visibility graph looks like this:

    The call to d3adaptor.routeEdge for each edge, uses the Dijkstra algorithm to find a shortest path through the visibility graph from the
    centre of the source node to the centre of the target node.

    The last bit: if (isIE()) link.each(... is an IE10/11 specific hack to force it to redraw the edges.  This is necessary because
    IE has trouble with SVG markers (in this case the arrow heads).


text:
'use strict';

var fs = require('fs');
var filePath = process.argv[2];
var file;

file = fs.readFileSync(filePath);

console.log(file.toString().split('\n').length - 1);


text:
import { AbstractPokerCommand } from "../../core/commands/AbstractPokerCommand";

export class ClGetMoneyCommand extends AbstractPokerCommand {
	public static NAME = "ClGetMoney";
	public static UID = 10263;

	constructor() {
		super();
		this.init(2, 2071, ClGetMoneyCommand.NAME);
	}
}


text:
p.css {
  color:red;
  background-color:gray;
}


text:
package tech.darkespresso.hellbinder;

import java.util.List;
import tech.darkespresso.hellbinder.annotations.ContentProviderEntity;

/**
 * An interface to obtain a {@link List} of {@link Entity Entities}. This is overridden by generated
 * code.
 *
 * @param <Entity> A class (annotated with {@link ContentProviderEntity}.
 * @param <ContentResolver> The class representing Android's content resolver.
 */
public interface QueryExecutor<Entity, ContentResolver> {
  /**
   * Returns an iterable wrapped around a closeable resource, that can be used to obtain all of the
   * elements that satisfy the constraints of the query.
   *
   * @param contentResolver an object of type {@link ContentResolver} that will be used when
   *     retrieving the entity.
   * @return an iterable of objects that satisfy the query, or {@code null}.
   */
  CloseableList<Entity> get(ContentResolver contentResolver);

  /**
   * Returns the number of entities satisfying the query.
   *
   * @param contentResolver an object of type {@link ContentResolver} that will be used when
   *     retrieving the entity.
   * @return the number of elements that satisfy the query.
   */
  int count(ContentResolver contentResolver);
}


text:
/**
 * @type {Handle}
 * @param {Code} node
 */
export function code(node: Code, _: import("../types.js").Parent | null | undefined, context: import("../types.js").Context, safeOptions: import("../types.js").SafeOptions): string;
export type Code = import('mdast').Code;
export type Handle = import('../types.js').Handle;
export type Exit = import('../types.js').Exit;
export type Map = import('../util/indent-lines.js').Map;


text:
@implementation BITSDKTextFieldCell

- (NSRect)drawingRectForBounds:(NSRect)theRect {
	// Get the parent's idea of where we should draw
	NSRect newRect = [super drawingRectForBounds:theRect];
  NSSize textSize = [self cellSizeForBounds:theRect];

  CGFloat heightDelta = newRect.size.height - textSize.height;
  if (heightDelta > 0) {
    newRect.size.height -= heightDelta;
    newRect.origin.y += heightDelta / 2;
    if (self.horizontalInset) {
#if CGFLOAT_IS_DOUBLE
      CGFloat horizontalInset = [self.horizontalInset doubleValue];
#else
      CGFloat horizontalInset = [self.horizontalInset floatValue];
#endif
      newRect.origin.x += horizontalInset;
      newRect.size.width -= (horizontalInset * 2);
    }
  }

	return newRect;
}

- (void)setBitPlaceHolderString:(NSString *)bitPlaceHolderString {
  self.placeholderString = bitPlaceHolderString;
}

@end


text:
#include "library/compiler/preprocess.h"
#include "library/compiler/nat_value.h"
#include "library/compiler/comp_irrelevant.h"
#include "library/compiler/inliner.h"
#include "library/compiler/rec_fn_macro.h"
#include "library/compiler/erase_irrelevant.h"
#include "library/compiler/simp_inductive.h"
#include "library/compiler/vm_compiler.h"

namespace lean {
void initialize_compiler_module() {
    initialize_preprocess();
    initialize_nat_value();
    initialize_comp_irrelevant();
    initialize_inliner();
    initialize_rec_fn_macro();
    initialize_erase_irrelevant();
    initialize_simp_inductive();
    initialize_vm_compiler();
}
void finalize_compiler_module() {
    finalize_vm_compiler();
    finalize_simp_inductive();
    finalize_erase_irrelevant();
    finalize_rec_fn_macro();
    finalize_inliner();
    finalize_comp_irrelevant();
    finalize_nat_value();
    finalize_preprocess();
}
}


text:
package workspace

import (
	"encoding/json"
	"fmt"
	"github.com/opslabjpl/earthkit-cli/fileset"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"path/filepath"
)

const EarthkitDir = ".earthkit"

// Starting at the given dir, traverse up to the root dir
// and generate a Workspace struct
func GetWorkspace(dir string) (workspace Workspace) {
	dir, _ = filepath.Abs(dir)
	earthkitRCPath, rootDir := findEarthkitRC(dir)

	earthkitRC, _ := ioutil.ReadFile(earthkitRCPath)
	json.Unmarshal(earthkitRC, &workspace)
	workspace.LocalRootDir = rootDir

	patternCachePath := filepath.Join(rootDir, EarthkitDir, "patterns.cache")
	var patternCache []string
	patternCacheJson, patternCacheErr := ioutil.ReadFile(patternCachePath)
	if patternCacheErr == nil {
		json.Unmarshal(patternCacheJson, &patternCache)
	}
	workspace.patternCache_ = patternCache

	return
}

func New(name, dir string) *Workspace {
	return &Workspace{name, dir, nil, []string{}}
}

// Traverse up the tree, loking for earthkitrc
func findEarthkitRC(dir string) (earthKitRC string, rootDir string) {
	earthKitRC = filepath.Join(dir, EarthkitDir, "earthkitrc")
	if _, err := os.Stat(earthKitRC); err == nil {
		return earthKitRC, dir
	} else if dir == "/" {
		return "", ""
	}

	return findEarthkitRC(filepath.Dir(dir))
}

func cp(src, dst string) error {
	s, err := os.Open(src)
	if err != nil {
		return err
	}
	// no need to check errors on read only file, we already got everything
	// we need from the filesystem, so nothing can go wrong now.
	defer s.Close()
	d, err := os.Create(dst)
	if err != nil {
		return err
	}
	if _, err := io.Copy(d, s); err != nil {
		d.Close()
		return err
	}
	return d.Close()
}

func warnUser(localRootDir string, diff fileset.EntryMapDiff) {
	need_confirmation := false
	if len(diff.Added) > 0 || len(diff.Updated) > 0 {
		fmt.Println("The following files/directories will be deleted or updated:")
		for k, _ := range diff.Added {
			toBeDeleted := filepath.Join(localRootDir, k)
			fmt.Println(toBeDeleted)
		}
		for k, _ := range diff.Updated {
			toBeUpdated := filepath.Join(localRootDir, k)
			fmt.Println(toBeUpdated)
		}
		need_confirmation = true
	}
	if need_confirmation {
		var input string
		fmt.Print("Do you want to continue (y/N)? ")
		fmt.Scanf("%s", &input)
		if input != "y" && input != "Y" {
			os.Exit(0)
		}
	}
}

func genDigest(path string) (digest string) {
	info, err := os.Stat(path)
	if err != nil {
		panic(err.Error())
	}

	if info.Size() > 0 {
		var fp *os.File
		fp, err = os.Open(path)
		if err != nil {
			log.Fatal(err)
		}
		defer fp.Close()
		digest, err = fileset.Hexdigest(fp)
		if err != nil {
			log.Fatal(err)
		}
	}
	return
}

func genEtcdDiscoveryURL(newUrl string) []byte {
	resp, err := http.Get(newUrl)
	if err != nil {
		panic(err.Error())
	}

	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		panic(err.Error())
	}
	return body
}

func (f filesDateSort) Len() int {
	return len(f)
}

func (f filesDateSort) Less(i, j int) bool {
	return f[i].ModTime().Unix() <= f[j].ModTime().Unix()
}

func (f filesDateSort) Swap(i, j int) {
	f[i], f[j] = f[j], f[i]
}


text:
define({
  "showLegend": "Jelmagyarázat megjelenítése",
  "controlPopupMenuTitle": "Válassza ki, mely műveletek jelenjenek meg a réteg helyi menüjében",
  "zoomto": "Nagyítás erre:",
  "transparency": "Átlátszóság",
  "setVisibilityRange": "Láthatósági tartomány beállítása",
  "controlPopup": "Felugró ablak engedélyezése/letiltása",
  "moveUpAndDown": "Feljebb / Lejjebb",
  "attributeTable": "Megtekintés az Attribútumtáblában",
  "url": "Leírás / Elem részleteinek megjelenítése / Letöltés",
  "showHideLabels": "Feliratok megjelenítése / elrejtése",
  "expandAllLayers": "Összes réteg kibontása",
  "expandAllLayersByDefault": "Összes réteg kibontása alapértelmezés szerint",
  "layerSelectorTitle": "Válassza ki, mely rétegek jelenjenek meg a listán",
  "showTitle": "Cím megjelenítése",
  "showBasemap": "Alaptérkép megjelenítése"
});


text:
class GearmanBacklog < Scout::Plugin
  needs 'net/telnet'
  OPTIONS=<<-EOS
    host:
      name: Host
      default: localhost
      notes: Hostname or IP address of the Gearman job server
    port:
      name Port
      default: 4730
  EOS
  def build_report
    telnet = Net::Telnet::new("Host" => option(:host), "Port" => option(:port))
    status = telnet.cmd("String" => "status", "Match" => /\n./)
    status.split("\n")[0...-1].map do |job|
      task, jobs, running, workers = job.split("\t")
      report(task => workers)
    end
  end
end


text:
<?php

namespace AppBundle\Controller\Frontend;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Response;

class DefaultController extends Controller
{

    /**
     * @Route("/", name="app_homepage")
     */
    public function indexAction()
    {
        return $this->render('AppBundle:Default:index.html.twig');
    }

    /**
     * @Route("/comment-ca-marche", name="app_comment_ca_marche")
     */
    public function commentCaMarcheAction()
    {
        return $this->render('AppBundle:Default:comment_ca_marche.html.twig');
    }
}