text:
Getting Started
===============

(If you haven't yet, make sure you :doc:`install Channels <installation>`)

Now, let's get to writing some consumers. If you've not read it already,
you should read :doc:`concepts`, as it covers the basic description of what
channels and groups are, and lays out some of the important implementation
patterns and caveats.

First Consumers
---------------

Now, by default, Django will run things through Channels but it will also
tie in the URL router and view subsystem to the default ``http.request``
channel if you don't provide another consumer that listens to it - remember,
only one consumer can listen to any given channel.

As a very basic example, let's write a consumer that overrides the built-in
handling and handles every HTTP request directly. This isn't something you'd
usually do in a project, but it's a good illustration of how channels
now underlie every part of Django.

Make a new project, a new app, and put this in a ``consumers.py`` file in the app::

    from django.http import HttpResponse

    def http_consumer(message):
        response = HttpResponse("Hello world! You asked for %s" % message.content['path'])
        message.reply_channel.send(response.channel_encode())

The most important thing to note here is that, because things we send in
messages must be JSON-serialisable, the request and response messages
are in a key-value format. There are ``channel_decode()`` and
``channel_encode()`` methods on both Django's request and response classes,
but here we just use the message's ``content`` attribute directly for simplicity
(message content is always a dict).

Now, go into your ``settings.py`` file, and set up a channel backend; by default,
Django will just use a local backend and route HTTP requests to the normal
URL resolver (we'll come back to backends in a minute).

For now, we want to override the *channel routing* so that, rather than going
to the URL resolver and our normal view stack, all HTTP requests go to our
custom consumer we wrote above. Here's what that looks like::

    # In settings.py
    CHANNEL_BACKENDS = {
        "default": {
            "BACKEND": "channels.backends.database.DatabaseChannelBackend",
            "ROUTING": "myproject.routing.channel_routing",
        },
    }

    # In routing.py
    channel_routing = {
        "http.request": "myproject.myapp.consumers.http_consumer",
    }

As you can see, this is a little like Django's ``DATABASES`` setting; there are
named channel backends, with a default one called ``default``. Each backend
needs a class specified which powers it - we'll come to the options there later -
and a routing scheme, which points to a dict containing the routing settings.
It's recommended you call this ``routing.py`` and put it alongside ``urls.py``
in your project.

If you start up ``python manage.py runserver`` and go to
``http://localhost:8000``, you'll see that, rather than a default Django page,
you get the Hello World response, so things are working. If you don't see
a response, check you :doc:`installed Channels correctly <installation>`.

Now, that's not very exciting - raw HTTP responses are something Django can
do any time. Let's try some WebSockets, and make a basic chat server!

Delete that consumer and its routing - we'll want the normal Django view layer to
serve HTTP requests from now on - and make this WebSocket consumer instead::

    from channels import Group

    def ws_add(message):
        Group("chat").add(message.reply_channel)

Hook it up to the ``websocket.connect`` channel like this::

    channel_routing = {
        "websocket.connect": "myproject.myapp.consumers.ws_add",
    }

Now, let's look at what this is doing. It's tied to the
``websocket.connect`` channel, which means that it'll get a message
whenever a new WebSocket connection is opened by a client.

When it gets that message, it takes the ``reply_channel`` attribute from it, which
is the unique response channel for that client, and adds it to the ``chat``
group, which means we can send messages to all connected chat clients.

Of course, if you've read through :doc:`concepts`, you'll know that channels
added to groups expire out after a while unless you keep renewing their
membership. This is because Channels is stateless; the worker processes
don't keep track of the open/close states of the potentially thousands of
connections you have open at any one time.

The solution to this is that the WebSocket interface servers will send
periodic "keepalive" messages on the ``websocket.keepalive`` channel,
so we can hook that up to re-add the channel (it's safe to add the channel to
a group it's already in - similarly, it's safe to discard a channel from a
group it's not in)::

    from channels import Group

    # Connected to websocket.keepalive
    def ws_keepalive(message):
        Group("chat").add(message.reply_channel)

Of course, this is exactly the same code as the ``connect`` handler, so let's
just route both channels to the same consumer::

    channel_routing = {
        "websocket.connect": "myproject.myapp.consumers.ws_add",
        "websocket.keepalive": "myproject.myapp.consumers.ws_add",
    }

And, even though channels will expire out, let's add an explicit ``disconnect``
handler to clean up as people disconnect (most channels will cleanly disconnect
and get this called)::

    from channels import Group

    # Connected to websocket.disconnect
    def ws_disconnect(message):
        Group("chat").discard(message.reply_channel)

Now, that's taken care of adding and removing WebSocket send channels for the
``chat`` group; all we need to do now is take care of message sending. For now,
we're not going to store a history of messages or anything and just replay
any message sent in to all connected clients. Here's all the code::

    from channels import Group

    # Connected to websocket.connect and websocket.keepalive
    def ws_add(message):
        Group("chat").add(message.reply_channel)

    # Connected to websocket.receive
    def ws_message(message):
        Group("chat").send(message.content)

    # Connected to websocket.disconnect
    def ws_disconnect(message):
        Group("chat").discard(message.reply_channel)

And what our routing should look like in ``routing.py``::

    channel_routing = {
        "websocket.connect": "myproject.myapp.consumers.ws_add",
        "websocket.keepalive": "myproject.myapp.consumers.ws_add",
        "websocket.receive": "myproject.myapp.consumers.ws_message",
        "websocket.disconnect": "myproject.myapp.consumers.ws_disconnect",
    }

With all that code in your ``consumers.py`` file, you now have a working
set of a logic for a chat server. All you need to do now is get it deployed,
and as we'll see, that's not too hard.

Running with Channels
---------------------

Because Channels takes Django into a multi-process model, you can no longer
just run one process if you want to serve more than one protocol type.

There are multiple kinds of "interface server", and each one will service a
different type of request - one might do WSGI requests, one might handle
WebSockets, or you might have one that handles both.

These are separate from the "worker servers" where Django will run actual logic,
though, and so you'll need to configure a channel backend to allow the
channels to run over the network. By default, when you're using Django out of
the box, the channel backend is set to an in-memory one that only works in
process; this is enough to serve normal WSGI style requests (``runserver`` is
just running a WSGI interface and a worker in two separate threads), but now we want
WebSocket support we'll need a separate process to keep things clean.

If you notice, in the example above we switched our default backend to the
database channel backend. This uses two tables
in the database to do message handling, and isn't particularly fast but
requires no extra dependencies. When you deploy to production, you'll want to
use a backend like the Redis backend that has much better throughput.

The second thing, once we have a networked channel backend set up, is to make
sure we're running the WebSocket interface server. Even in development, we need
to do this; ``runserver`` will take care of normal Web requests and running
a worker for us, but WebSockets isn't compatible with WSGI and needs to run
separately.

The easiest way to do this is to use the ``runwsserver`` management command
that ships with Django; just make sure you've installed the latest release
of ``autobahn`` first::

    pip install -U autobahn
    python manage.py runwsserver

Run that alongside ``runserver`` and you'll have two interface servers, a
worker thread, and the channel backend all connected and running. You can
even launch separate worker processes with ``runworker`` if you like (you'll
need at least one of those if you're not also running ``runserver``).

Now, just open a browser and put the following into the JavaScript console
to test your new code::

    socket = new WebSocket("ws://127.0.0.1:9000");
    socket.onmessage = function(e) {
        alert(e.data);
    }
    socket.onopen = function() {
        socket.send("hello world");
    }

You should see an alert come back immediately saying "hello world" - your
message has round-tripped through the server and come back to trigger the alert.
You can open another tab and do the same there if you like, and both tabs will
receive the message and show an alert, as any incoming message is sent to the
``chat`` group by the ``ws_message`` consumer, and both your tabs will have
been put into the ``chat`` group when they connected.

Feel free to put some calls to ``print`` in your handler functions too, if you
like, so you can understand when they're called. If you run three or four
copies of ``runworker`` you'll probably be able to see the tasks running
on different workers.

Persisting Data
---------------

Echoing messages is a nice simple example, but it's
skirting around the real design pattern - persistent state for connections.
Let's consider a basic chat site where a user requests a chat room upon initial
connection, as part of the query string (e.g. ``http://host/websocket?room=abc``).

The ``reply_channel`` attribute you've seen before is our unique pointer to the
open WebSocket - because it varies between different clients, it's how we can
keep track of "who" a message is from. Remember, Channels is network-trasparent
and can run on multiple workers, so you can't just store things locally in
global variables or similar.

Instead, the solution is to persist information keyed by the ``reply_channel`` in
some other data store - sound familiar? This is what Django's session framework
does for HTTP requests, only there it uses cookies as the lookup key rather
than the ``reply_channel``.

Channels provides a ``channel_session`` decorator for this purpose - it
provides you with an attribute called ``message.channel_session`` that acts
just like a normal Django session.

Let's use it now to build a chat server that expects you to pass a chatroom
name in the path of your WebSocket request (we'll ignore auth for now - that's next)::

    from channels import Group
    from channels.decorators import channel_session

    # Connected to websocket.connect
    @channel_session
    def ws_connect(message):
        # Work out room name from path (ignore slashes)
        room = message.content['path'].strip("/")
        # Save room in session and add us to the group
        message.channel_session['room'] = room
        Group("chat-%s" % room).add(message.reply_channel)

    # Connected to websocket.keepalive
    @channel_session
    def ws_keepalive(message):
        Group("chat-%s" % message.channel_session['room']).add(message.reply_channel)

    # Connected to websocket.receive
    @channel_session
    def ws_message(message):
        Group("chat-%s" % message.channel_session['room']).send(message.content)

    # Connected to websocket.disconnect
    @channel_session
    def ws_disconnect(message):
        Group("chat-%s" % message.channel_session['room']).discard(message.reply_channel)

If you play around with it from the console (or start building a simple
JavaScript chat client that appends received messages to a div), you'll see
that you can now request which chat room you want in the initial request.

Authentication
--------------

Now, of course, a WebSocket solution is somewhat limited in scope without the
ability to live with the rest of your website - in particular, we want to make
sure we know what user we're talking to, in case we have things like private
chat channels (we don't want a solution where clients just ask for the right
channels, as anyone could change the code and just put in private channel names)

It can also save you having to manually make clients ask for what they want to
see; if I see you open a WebSocket to my "updates" endpoint, and I know which
user you are, I can just auto-add that channel to all the relevant groups (mentions
of that user, for example).

Handily, as WebSockets start off using the HTTP protocol, they have a lot of
familiar features, including a path, GET parameters, and cookies. We'd like to
use these to hook into the familiar Django session and authentication systems;
after all, WebSockets are no good unless we can identify who they belong to
and do things securely.

In addition, we don't want the interface servers storing data or trying to run
authentication; they're meant to be simple, lean, fast processes without much
state, and so we'll need to do our authentication inside our consumer functions.

Fortunately, because Channels has standardised WebSocket event
:doc:`message-standards`, it ships with decorators that help you with
both authentication and getting the underlying Django session (which is what
Django authentication relies on).

Channels can use Django sessions either from cookies (if you're running your websocket
server on the same port as your main site, which requires a reverse proxy that
understands WebSockets), or from a ``session_key`` GET parameter, which
is much more portable, and works in development where you need to run a separate
WebSocket server (by default, on port 9000).

You get access to a user's normal Django session using the ``http_session``
decorator - that gives you a ``message.http_session`` attribute that behaves
just like ``request.session``. You can go one further and use ``http_session_user``
which will provide a ``message.user`` attribute as well as the session attribute.

Now, one thing to note is that you only get the detailed HTTP information
during the ``connect`` message of a WebSocket connection (you can read more
about what you get when in :doc:`message-standards`) - this means we're not
wasting bandwidth sending the same information over the wire needlessly.

This also means we'll have to grab the user in the connection handler and then
store it in the session; thankfully, Channels ships with both a ``channel_session_user``
decorator that works like the ``http_session_user`` decorator you saw above but
loads the user from the *channel* session rather than the *HTTP* session,
and a function called ``transfer_user`` which replicates a user from one session
to another.

Bringing that all together, let's make a chat server one where users can only
chat to people with the same first letter of their username::

    from channels import Channel, Group
    from channels.decorators import channel_session
    from channels.auth import http_session_user, channel_session_user, transfer_user

    # Connected to websocket.connect
    @channel_session
    @http_session_user
    def ws_add(message):
        # Copy user from HTTP to channel session
        transfer_user(message.http_session, message.channel_session)
        # Add them to the right group
        Group("chat-%s" % message.user.username[0]).add(message.reply_channel)

    # Connected to websocket.keepalive
    @channel_session_user
    def ws_keepalive(message):
        # Keep them in the right group
        Group("chat-%s" % message.user.username[0]).add(message.reply_channel)

    # Connected to websocket.receive
    @channel_session_user
    def ws_message(message):
        Group("chat-%s" % message.user.username[0]).send(message.content)

    # Connected to websocket.disconnect
    @channel_session_user
    def ws_disconnect(message):
        Group("chat-%s" % message.user.username[0]).discard(message.reply_channel)

Now, when we connect to the WebSocket we'll have to remember to provide the
Django session ID as part of the URL, like this::

    socket = new WebSocket("ws://127.0.0.1:9000/?session_key=abcdefg");

You can get the current session key in a template with ``{{ request.session.session_key }}``.
Note that Channels can't work with signed cookie sessions - since only HTTP
responses can set cookies, it needs a backend it can write to separately to
store state.

Models
------

So far, we've just been taking incoming messages and rebroadcasting them to
other clients connected to the same group, but this isn't that great; really,
we want to persist messages to a datastore, and we'd probably like to be
able to inject messages into chatrooms from things other than WebSocket client
connections (perhaps a built-in bot, or server status messages).

Thankfully, we can just use Django's ORM to handle persistence of messages and
easily integrate the send into the save flow of the model, rather than the
message receive - that way, any new message saved will be broadcast to all
the appropriate clients, no matter where it's saved from.

We'll even take some performance considerations into account - We'll make our
own custom channel for new chat messages and move the model save and the chat
broadcast into that, meaning the sending process/consumer can move on
immediately and not spend time waiting for the database save and the
(slow on some backends) ``Group.send()`` call.

Let's see what that looks like, assuming we
have a ChatMessage model with ``message`` and ``room`` fields::

    from channels import Channel
    from channels.decorators import channel_session
    from .models import ChatMessage

    def msg_consumer(message):
        # Save to model
        ChatMessage.objects.create(
            room=message.content['room'],
            message=message.content['message'],
        )
        # Broadcast to listening sockets
        Group("chat-%s" % room).send({
            "content": message.content['message'],
        })

    # Connected to websocket.connect
    @channel_session
    def ws_connect(message):
        # Work out room name from path (ignore slashes)
        room = message.content['path'].strip("/")
        # Save room in session and add us to the group
        message.channel_session['room'] = room
        Group("chat-%s" % room).add(message.reply_channel)

    # Connected to websocket.keepalive
    @channel_session
    def ws_add(message):
        Group("chat-%s" % message.channel_session['room']).add(message.reply_channel)

    # Connected to websocket.receive
    @channel_session
    def ws_message(message):
        # Stick the message onto the processing queue
        Channel("chat-messages").send({
            "room": channel_session['room'],
            "message": content,
        })

    # Connected to websocket.disconnect
    @channel_session
    def ws_disconnect(message):
        Group("chat-%s" % message.channel_session['room']).discard(message.reply_channel)

Note that we could add messages onto the ``chat-messages`` channel from anywhere;
inside a View, inside another model's ``post_save`` signal, inside a management
command run via ``cron``. If we wanted to write a bot, too, we could put its
listening logic inside the ``chat-messages`` consumer, as every message would
pass through it.

Linearization
-------------

There's one final concept we want to introduce you to before you go on to build
sites with Channels - linearizing consumers.

Because Channels is a distributed system that can have many workers, by default
it's entirely feasible for a WebSocket interface server to send out a ``connect``
and a ``receive`` message close enough together that a second worker will pick
up and start processing the ``receive`` message before the first worker has
finished processing the ``connect`` worker.

This is particularly annoying if you're storing things in the session in the
``connect`` consumer and trying to get them in the ``receive`` consumer - because
the ``connect`` consumer hasn't exited, its session hasn't saved. You'd get the
same effect if someone tried to request a view before the login view had finished
processing, but there you're not expecting that page to run after the login,
whereas you'd naturally expect ``receive`` to run after ``connect``.

But, of course, Channels has a solution - the ``linearize`` decorator. Any
handler decorated with this will use locking to ensure it does not run at the
same time as any other view with ``linearize`` **on messages with the same reply channel**.
That means your site will happily mutitask with lots of different people's messages,
but if two happen to try to run at the same time for the same client, they'll
be deconflicted.

There's a small cost to using ``linearize``, which is why it's an optional
decorator, but generally you'll want to use it for most session-based WebSocket
and other "continuous protocol" things. Here's an example, improving our
first-letter-of-username chat from earlier::

    from channels import Channel, Group
    from channels.decorators import channel_session, linearize
    from channels.auth import http_session_user, channel_session_user, transfer_user

    # Connected to websocket.connect
    @linearize
    @channel_session
    @http_session_user
    def ws_add(message):
        # Copy user from HTTP to channel session
        transfer_user(message.http_session, message.channel_session)
        # Add them to the right group
        Group("chat-%s" % message.user.username[0]).add(message.reply_channel)

    # Connected to websocket.keepalive
    # We don't linearize as we know this will happen a decent time after add
    @channel_session_user
    def ws_keepalive(message):
        # Keep them in the right group
        Group("chat-%s" % message.user.username[0]).add(message.reply_channel)

    # Connected to websocket.receive
    @linearize
    @channel_session_user
    def ws_message(message):
        Group("chat-%s" % message.user.username[0]).send(message.content)

    # Connected to websocket.disconnect
    # We don't linearize as even if this gets an empty session, the group
    # will auto-discard after the expiry anyway.
    @channel_session_user
    def ws_disconnect(message):
        Group("chat-%s" % message.user.username[0]).discard(message.reply_channel)

Next Steps
----------

That covers the basics of using Channels; you've seen not only how to use basic
channels, but also seen how they integrate with WebSockets, how to use groups
to manage logical sets of channels, and how Django's session and authentication
systems easily integrate with WebSockets.

We recommend you read through the rest of the reference documentation to see
all of what Channels has to offer; in particular, you may want to look at
our :doc:`deploying` and :doc:`scaling` resources to get an idea of how to
design and run apps in production environments.


text:
using NEventStore.Persistence.Sql.Tests;

namespace NEventStore.Persistence.AcceptanceTests
{
    using global::MySql.Data.MySqlClient;
    using NEventStore.Persistence.Sql;
    using NEventStore.Persistence.Sql.SqlDialects;
    using NEventStore.Serialization;

    public partial class PersistenceEngineFixture
    {
        public PersistenceEngineFixture()
        {
#if NET461
            _createPersistence = pageSize =>
                    new SqlPersistenceFactory(
                        new EnviromentConnectionFactory("MySql", "MySql.Data.MySqlClient"),
                        new BinarySerializer(),
                        new MySqlDialect(),
                        pageSize: pageSize).Build();

            // Wireup.Init().UsingSqlPersistence("test");
#else
            _createPersistence = pageSize =>
                new SqlPersistenceFactory(
                    new EnviromentConnectionFactory("MySql", MySqlClientFactory.Instance),
                    new BinarySerializer(),
                    new MySqlDialect(),
                    pageSize: pageSize).Build();

            // Wireup.Init().UsingSqlPersistence("test");
#endif
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
#include "HMC5883.hpp"

HMC5883::HMC5883(device::Device *interface, enum Rotation rotation, I2CSPIBusOption bus_option, int bus) :
	I2CSPIDriver(MODULE_NAME, px4::device_bus_to_wq(interface->get_device_id()), bus_option, bus),
	_px4_mag(interface->get_device_id(), rotation),
	_interface(interface),
	_range_ga(1.9f),
	_collect_phase(false),
	_sample_perf(perf_alloc(PC_ELAPSED, MODULE_NAME": read")),
	_comms_errors(perf_alloc(PC_COUNT, MODULE_NAME": com_err")),
	_range_errors(perf_alloc(PC_COUNT, MODULE_NAME": rng_err")),
	_conf_errors(perf_alloc(PC_COUNT, MODULE_NAME": conf_err")),
	_range_bits(0),
	_conf_reg(0),
	_temperature_counter(0),
	_temperature_error_count(0)
{
	_px4_mag.set_external(_interface->external());
}

HMC5883::~HMC5883()
{
	// free perf counters
	perf_free(_sample_perf);
	perf_free(_comms_errors);
	perf_free(_range_errors);
	perf_free(_conf_errors);

	delete _interface;
}

int HMC5883::init()
{
	/* reset the device configuration */
	reset();

	_measure_interval = HMC5883_CONVERSION_INTERVAL;
	start();

	return PX4_OK;
}

int HMC5883::set_range(unsigned range)
{
	if (range < 0.88f) {
		_range_bits = 0x00;
		_px4_mag.set_scale(1.0f / 1370.0f);
		_range_ga = 0.88f;

	} else if (range <= 1.3f) {
		_range_bits = 0x01;
		_px4_mag.set_scale(1.0f / 1090.0f);
		_range_ga = 1.3f;

	} else if (range <= 2) {
		_range_bits = 0x02;
		_px4_mag.set_scale(1.0f / 820.0f);
		_range_ga = 1.9f;

	} else if (range <= 3) {
		_range_bits = 0x03;
		_px4_mag.set_scale(1.0f / 660.0f);
		_range_ga = 2.5f;

	} else if (range <= 4) {
		_range_bits = 0x04;
		_px4_mag.set_scale(1.0f / 440.0f);
		_range_ga = 4.0f;

	} else if (range <= 4.7f) {
		_range_bits = 0x05;
		_px4_mag.set_scale(1.0f / 390.0f);
		_range_ga = 4.7f;

	} else if (range <= 5.6f) {
		_range_bits = 0x06;
		_px4_mag.set_scale(1.0f / 330.0f);
		_range_ga = 5.6f;

	} else {
		_range_bits = 0x07;
		_px4_mag.set_scale(1.0f / 230.0f);
		_range_ga = 8.1f;
	}

	/*
	 * Send the command to set the range
	 */
	int ret = write_reg(ADDR_CONF_B, (_range_bits << 5));

	if (OK != ret) {
		perf_count(_comms_errors);
	}

	uint8_t range_bits_in = 0;
	ret = read_reg(ADDR_CONF_B, range_bits_in);

	if (OK != ret) {
		perf_count(_comms_errors);
	}

	return !(range_bits_in == (_range_bits << 5));
}

/**
   check that the range register has the right value. This is done
   periodically to cope with I2C bus noise causing the range of the
   compass changing.
 */
void HMC5883::check_range()
{
	int ret;

	uint8_t range_bits_in = 0;
	ret = read_reg(ADDR_CONF_B, range_bits_in);

	if (OK != ret) {
		perf_count(_comms_errors);
		return;
	}

	if (range_bits_in != (_range_bits << 5)) {
		perf_count(_range_errors);
		ret = write_reg(ADDR_CONF_B, (_range_bits << 5));

		if (OK != ret) {
			perf_count(_comms_errors);
		}
	}
}

/**
   check that the configuration register has the right value. This is
   done periodically to cope with I2C bus noise causing the
   configuration of the compass to change.
 */
void HMC5883::check_conf()
{
	int ret;

	uint8_t conf_reg_in = 0;
	ret = read_reg(ADDR_CONF_A, conf_reg_in);

	if (OK != ret) {
		perf_count(_comms_errors);
		return;
	}

	if (conf_reg_in != _conf_reg) {
		perf_count(_conf_errors);
		ret = write_reg(ADDR_CONF_A, _conf_reg);

		if (OK != ret) {
			perf_count(_comms_errors);
		}
	}
}

void
HMC5883::start()
{
	/* reset the report ring and state machine */
	_collect_phase = false;

	/* schedule a cycle to start things */
	ScheduleNow();
}

int
HMC5883::reset()
{
	/* set range, ceil floating point number */
	return set_range(_range_ga + 0.5f);
}

void
HMC5883::RunImpl()
{
	if (_measure_interval == 0) {
		return;
	}

	/* collection phase? */
	if (_collect_phase) {

		/* perform collection */
		if (OK != collect()) {
			PX4_DEBUG("collection error");
			/* restart the measurement state machine */
			start();
			return;
		}

		/* next phase is measurement */
		_collect_phase = false;

		/*
		 * Is there a collect->measure gap?
		 */
		if (_measure_interval > HMC5883_CONVERSION_INTERVAL) {

			/* schedule a fresh cycle call when we are ready to measure again */
			ScheduleDelayed(_measure_interval - HMC5883_CONVERSION_INTERVAL);

			return;
		}
	}

	/* measurement phase */
	if (OK != measure()) {
		PX4_DEBUG("measure error");
	}

	/* next phase is collection */
	_collect_phase = true;

	if (_measure_interval > 0) {
		/* schedule a fresh cycle call when the measurement is done */
		ScheduleDelayed(HMC5883_CONVERSION_INTERVAL);
	}
}

int HMC5883::measure()
{
	/*
	 * Send the command to begin a measurement.
	 */
	int ret = write_reg(ADDR_MODE, MODE_REG_SINGLE_MODE);

	if (OK != ret) {
		perf_count(_comms_errors);
	}

	return ret;
}

int HMC5883::collect()
{
	struct { /* status register and data as read back from the device */
		uint8_t		x[2];
		uint8_t		z[2];
		uint8_t		y[2];
	} hmc_report{};

	struct {
		int16_t	x, y, z;
	} report{};

	uint8_t check_counter;

	float xraw_f;
	float yraw_f;
	float zraw_f;

	_px4_mag.set_error_count(perf_event_count(_comms_errors));

	perf_begin(_sample_perf);

	/*
	 * @note  We could read the status register here, which could tell us that
	 *        we were too early and that the output registers are still being
	 *        written.  In the common case that would just slow us down, and
	 *        we're better off just never being early.
	 */

	/* get measurements from the device */
	const hrt_abstime timestamp_sample = hrt_absolute_time();
	int ret = _interface->read(ADDR_DATA_OUT_X_MSB, (uint8_t *)&hmc_report, sizeof(hmc_report));

	if (ret != OK) {
		perf_count(_comms_errors);
		PX4_DEBUG("data/status read error");
		goto out;
	}

	/* swap the data we just received */
	report.x = (((int16_t)hmc_report.x[0]) << 8) + hmc_report.x[1];
	report.y = (((int16_t)hmc_report.y[0]) << 8) + hmc_report.y[1];
	report.z = (((int16_t)hmc_report.z[0]) << 8) + hmc_report.z[1];

	/*
	 * If any of the values are -4096, there was an internal math error in the sensor.
	 * Generalise this to a simple range check that will also catch some bit errors.
	 */
	if ((abs(report.x) > 2048) ||
	    (abs(report.y) > 2048) ||
	    (abs(report.z) > 2048)) {
		perf_count(_comms_errors);
		goto out;
	}

	if (_conf_reg & HMC5983_TEMP_SENSOR_ENABLE) {
		/*
		  if temperature compensation is enabled read the
		  temperature too.

		  We read the temperature every 10 samples to avoid
		  excessive I2C traffic
		 */
		if (_temperature_counter++ == 10) {
			uint8_t raw_temperature[2];

			_temperature_counter = 0;

			ret = _interface->read(ADDR_TEMP_OUT_MSB,
					       raw_temperature, sizeof(raw_temperature));

			if (ret == OK) {
				int16_t temp16 = (((int16_t)raw_temperature[0]) << 8) +
						 raw_temperature[1];
				float temperature = 25 + (temp16 / (16 * 8.0f));
				_px4_mag.set_temperature(temperature);
				_temperature_error_count = 0;

			} else {
				_temperature_error_count++;

				if (_temperature_error_count == 10) {
					/*
					  it probably really is an old HMC5883,
					  and can't do temperature. Disable it
					*/
					_temperature_error_count = 0;
					PX4_DEBUG("disabling temperature compensation");
					set_temperature_compensation(0);
				}
			}
		}
	}

	/*
	 * RAW outputs
	 *
	 * to align the sensor axes with the board, x and y need to be flipped
	 * and y needs to be negated
	 */
	if (!_px4_mag.external()) {
		// convert onboard so it matches offboard for the
		// scaling below
		report.y = -report.y;
		report.x = -report.x;
	}

	/* the standard external mag by 3DR has x pointing to the
	 * right, y pointing backwards, and z down, therefore switch x
	 * and y and invert y */
	xraw_f = -report.y;
	yraw_f = report.x;
	zraw_f = report.z;

	_px4_mag.update(timestamp_sample, xraw_f, yraw_f, zraw_f);

	/*
	  periodically check the range register and configuration
	  registers. With a bad I2C cable it is possible for the
	  registers to become corrupt, leading to bad readings. It
	  doesn't happen often, but given the poor cables some
	  vehicles have it is worth checking for.
	 */
	check_counter = perf_event_count(_sample_perf) % 256;

	if (check_counter == 0) {
		check_range();
	}

	if (check_counter == 128) {
		check_conf();
	}

	ret = OK;

out:
	perf_end(_sample_perf);
	return ret;
}

/*
  enable/disable temperature compensation on the HMC5983

  Unfortunately we don't yet know of a way to auto-detect the
  difference between the HMC5883 and HMC5983. Both of them do
  temperature sensing, but only the 5983 does temperature
  compensation. We have noy yet found a behaviour that can be reliably
  distinguished by reading registers to know which type a particular
  sensor is

  update: Current best guess is that many sensors marked HMC5883L on
  the package are actually 5983 but without temperature compensation
  tables. Reading the temperature works, but the mag field is not
  automatically adjusted for temperature. We suspect that there may be
  some early 5883L parts that don't have the temperature sensor at
  all, although we haven't found one yet. The code that reads the
  temperature looks for 10 failed transfers in a row and disables the
  temperature sensor if that happens. It is hoped that this copes with
  the genuine 5883L parts.
 */
int HMC5883::set_temperature_compensation(unsigned enable)
{
	int ret;
	/* get current config */
	ret = read_reg(ADDR_CONF_A, _conf_reg);

	if (OK != ret) {
		perf_count(_comms_errors);
		return -EIO;
	}

	if (enable != 0) {
		_conf_reg |= HMC5983_TEMP_SENSOR_ENABLE;

	} else {
		_conf_reg &= ~HMC5983_TEMP_SENSOR_ENABLE;
	}

	ret = write_reg(ADDR_CONF_A, _conf_reg);

	if (OK != ret) {
		perf_count(_comms_errors);
		return -EIO;
	}

	uint8_t conf_reg_ret = 0;

	if (read_reg(ADDR_CONF_A, conf_reg_ret) != OK) {
		perf_count(_comms_errors);
		return -EIO;
	}

	return conf_reg_ret == _conf_reg;
}

int HMC5883::write_reg(uint8_t reg, uint8_t val)
{
	uint8_t buf = val;
	return _interface->write(reg, &buf, 1);
}

int HMC5883::read_reg(uint8_t reg, uint8_t &val)
{
	uint8_t buf = val;
	int ret = _interface->read(reg, &buf, 1);
	val = buf;
	return ret;
}

void HMC5883::print_status()
{
	I2CSPIDriverBase::print_status();
	perf_print_counter(_sample_perf);
	perf_print_counter(_comms_errors);
	printf("interval:  %u us\n", _measure_interval);
}


text:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Empty</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <!-- include helper library for matrix computation -->
    <script src="../libs/gl-matrix.js"></script>
    <!-- include our framework with utilities -->
    <script src="../libs/framework.js"></script>
    <!-- include rendering logic for scenes -->
    <script src="scene1.js"></script>
    <script src="scene2.js"></script>
    <script src="scene3.js"></script>
    <!-- include the main script -->
    <script src="main.js"></script>
</body>
</html>


text:
echo "`date`: Restarting elastic" >> /tmp/mitigate.log

exit -1


text:
Guice `@Provides` methods annotate methods that are used as a means of declaring
bindings. However, this is only helpful inside of a module. Methods outside of
these modules are not used for binding declaration.


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="SEND MESSAGE"
        android:id="@+id/btn_send_message"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="STOP"
        android:id="@+id/btn_stop_session"/>

    <android.support.v7.widget.RecyclerView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/list_messages"/>

</LinearLayout>


text:
<?php

namespace Devtools;

require '../lib/Devtools/Autoload.php';

Autoload::register();


text:
@implementation JGProgressHUDFadeAnimation

#pragma mark - Initializers

- (instancetype)init {
    self = [super init];
    if (self) {
        self.duration = 0.4;
        self.animationOptions = UIViewAnimationOptionCurveEaseInOut;
    }
    return self;
}

- (void)setAnimationOptions:(UIViewAnimationOptions)animationOptions {
    _animationOptions = (animationOptions | UIViewAnimationOptionBeginFromCurrentState);
}

#pragma mark - Showing

- (void)show {
    [super show];

    //Prepare animation
    self.progressHUD.alpha = 0.0f;

    //Now unhide HUD
    self.progressHUD.hidden = NO;

    //Perform the presentation animation
    [UIView animateWithDuration:self.duration delay:0.0 options:self.animationOptions animations:^{
        self.progressHUD.alpha = 1.0f;
    } completion:^(BOOL __unused finished) {
        [self animationFinished];
    }];
}

#pragma mark - Hiding

- (void)hide {
    [super hide];

    //Perform the dismissal animation
    [UIView animateWithDuration:self.duration delay:0.0 options:self.animationOptions animations:^{
        self.progressHUD.alpha = 0.0f;
    } completion:^(BOOL __unused finished) {
        [self animationFinished];
    }];
}

@end


text:
<?php
namespace Vks\Asserts;
use Vks\Core\Assert;

class FlotGraphAssert extends Assert
{

    public $css = [
    ];
    public $js = [
        'flot/jquery.flot.min.js',
        'flot/jquery.flot.time.js',
        'flot/jquery.flot.selection.js',
        'flot/jquery.flot.threshold.js',
        'flot/jquery.flot.crosshair.js',
        'flot/jquery.flot.pie.js'

    ];
}


text:
namespace blink {

PassOwnPtr<ResourceTimingInfo> ResourceTimingInfo::adopt(PassOwnPtr<CrossThreadResourceTimingInfoData> data)
{
    OwnPtr<ResourceTimingInfo> info = ResourceTimingInfo::create(AtomicString(data->m_type), data->m_initialTime, data->m_isMainResource);
    info->m_originalTimingAllowOrigin = AtomicString(data->m_originalTimingAllowOrigin);
    info->m_loadFinishTime = data->m_loadFinishTime;
    info->m_initialRequest = *ResourceRequest::adopt(data->m_initialRequest.release());
    info->m_finalResponse = *ResourceResponse::adopt(data->m_finalResponse.release());
    for (auto& responseData : data->m_redirectChain)
        info->m_redirectChain.append(*ResourceResponse::adopt(responseData.release()));
    return info.release();
}

PassOwnPtr<CrossThreadResourceTimingInfoData> ResourceTimingInfo::copyData() const
{
    OwnPtr<CrossThreadResourceTimingInfoData> data = adoptPtr(new CrossThreadResourceTimingInfoData);
    data->m_type = m_type.string().isolatedCopy();
    data->m_originalTimingAllowOrigin = m_originalTimingAllowOrigin.string().isolatedCopy();
    data->m_initialTime = m_initialTime;
    data->m_loadFinishTime = m_loadFinishTime;
    data->m_initialRequest = m_initialRequest.copyData();
    data->m_finalResponse = m_finalResponse.copyData();
    for (const auto& response : m_redirectChain)
        data->m_redirectChain.append(response.copyData());
    data->m_isMainResource = m_isMainResource;
    return data.release();
}

} // namespace blink


text:
package org.nnsoft.t2t.slicers;

/**
 * @author Davide Palmisano ( dpalmisano@gmail.com )
 */
public class SlicerException
    extends Exception
{

    private static final long serialVersionUID = 1L;

    public SlicerException()
    {
        super();
    }

    public SlicerException( String message )
    {
        super( message );
    }

}


text:
/** @file main.js
 *  @fileOverview Program driver. Configures path aliases and calls app.initialize()
 *  @author cs_brandt
 *  @date 10/19/2012
 */

require.config(
{
   paths:
   {
      order: '../vendor/libs/requirejs-plugins/order',
      text: '../vendor/libs/requirejs-plugins/text',
      jquery: '../vendor/libs/jquery/jquery-min',
      jqueryui: '../vendor/libs/jquery-ui/jquery-ui-1.9.0.custom.min',
      jquerylayout: '../vendor/libs/jquery-layout/jquery.layout-latest',
      jqueryTree: '../vendor/libs/jqTree/tree.jquery',
      jqueryuiPosition: '../vendor/libs/jquery-contextMenu/jquery.ui.position',
      jqueryContextMenu: '../vendor/libs/jquery-contextMenu/jquery.contextMenu',
      underscore: '../vendor/libs/underscore/underscore-min',
      backbone: '../vendor/libs/backbone/backbone',
      three: '../vendor/libs/three/three.min',
      ColladaLoader: '../vendor/libs/three/loaders/ColladaLoader',
      TrackballControls: '../vendor/libs/three/controls/TrackballControls'
   },
   shim:
   {
      backbone:
      {
         deps: ['underscore', 'jquery'],
         exports: 'Backbone'
      },
      underscore:
      {
         exports: "_"
      },
      ColladaLoader:
      {
         deps: ['three']
      },
      TrackballControls:
      {
         deps: ['three']
      }

   }

});

require(["app"], function(app)
{
   app.initialize();

});


text:
#ifndef ___USERVARS___H_____
#define ___USERVARS___H_____

#include "lang.h"

struct uservarstring {
  int name;
  int index;
  int pos;
  int reference;
};

class UserVarsStringList : public SortedStringListND<struct uservarstring>
{
  public:
    UserVarsStringList()
    {
      index = 0;
    }
    ~UserVarsStringList() { }

    int add(const char *name, int ref_count = 0 )
    {
      int pos=SortedStringListND<struct uservarstring>::add(name);
      if (pos == -1) return -1;

      ((struct uservarstring*)gr.get())[pos].index = index;
      ((struct uservarstring*)gr.get())[pos].pos = pos;
      ((struct uservarstring*)gr.get())[pos].reference = ref_count;

      int temp = index;
      index++;

      return temp;
    }

    int get(const char *name, int n_chars = -1)
    {
      int v=SortedStringListND<struct uservarstring>::find(name, n_chars);
      if (v==-1) return -1;
      return (((struct uservarstring*)gr.get())[v].index);
    }

    int getnum()
    {
      return index;
    }

    int get_reference(int idx)
    {
      int pos=get_internal_idx(idx);
      if (pos==-1) return -1;
      return (((struct uservarstring*)gr.get())[pos].reference);
    }

    int inc_reference(int idx)
    {
      int pos=get_internal_idx(idx);
      ((struct uservarstring*)gr.get())[pos].reference++;
      return (((struct uservarstring*)gr.get())[pos].reference)-1;
    }

    char *idx2name(int idx)
    {
      int pos=get_internal_idx(idx);
      if (pos==-1) return NULL;
      struct uservarstring *data=(struct uservarstring *)gr.get();
      return ((char*)strings.get() + data[pos].name);
    }

  private:
    int index;
    int get_internal_idx(int idx)
    {
      struct uservarstring *data=(struct uservarstring *)gr.get();
      for (int i = 0; i < index; i++)
      {
        if (data[i].index == idx)
        {
          return i;
        }
      }
      return -1;
    }
};

#endif


text:
#include <mitkGIFCooccurenceMatrix2.h>

// MITK
#include <mitkITKImageImport.h>
#include <mitkImageCast.h>
#include <mitkImageAccessByItk.h>

// ITK
#include <itkEnhancedScalarImageToTextureFeaturesFilter.h>
#include <itkShapedNeighborhoodIterator.h>
#include <itkImageRegionConstIterator.h>

// STL
#include <sstream>
#include <cmath>

namespace mitk
{
  struct GIFCooccurenceMatrix2Configuration
  {
    double range;
    unsigned int direction;

    double MinimumIntensity;
    double MaximumIntensity;
    int Bins;
    FeatureID id;
  };

  struct CoocurenceMatrixHolder
  {
  public:
    CoocurenceMatrixHolder(double min, double max, int number);

    int IntensityToIndex(double intensity);
    double IndexToMinIntensity(int index);
    double IndexToMeanIntensity(int index);
    double IndexToMaxIntensity(int index);

    double m_MinimumRange;
    double m_MaximumRange;
    double m_Stepsize;
    int m_NumberOfBins;
    Eigen::MatrixXd m_Matrix;

  };

  struct CoocurenceMatrixFeatures
  {
    CoocurenceMatrixFeatures() :
      JointMaximum(0),
      JointAverage(0),
      JointVariance(0),
      JointEntropy(0),
      RowMaximum(0),
      RowAverage(0),
      RowVariance(0),
      RowEntropy(0),
      FirstRowColumnEntropy(0),
      SecondRowColumnEntropy(0),
      DifferenceAverage(0),
      DifferenceVariance(0),
      DifferenceEntropy(0),
      SumAverage(0),
      SumVariance(0),
      SumEntropy(0),
      AngularSecondMoment(0),
      Contrast(0),
      Dissimilarity(0),
      InverseDifference(0),
      InverseDifferenceNormalised(0),
      InverseDifferenceMoment(0),
      InverseDifferenceMomentNormalised(0),
      InverseVariance(0),
      Correlation(0),
      Autocorrelation(0),
      ClusterTendency(0),
      ClusterShade(0),
      ClusterProminence(0),
      FirstMeasureOfInformationCorrelation(0),
      SecondMeasureOfInformationCorrelation(0)
    {
    }

  public:
    double JointMaximum;
    double JointAverage;
    double JointVariance;
    double JointEntropy;
    double RowMaximum;
    double RowAverage;
    double RowVariance;
    double RowEntropy;
    double FirstRowColumnEntropy;
    double SecondRowColumnEntropy;
    double DifferenceAverage;
    double DifferenceVariance;
    double DifferenceEntropy;
    double SumAverage;
    double SumVariance;
    double SumEntropy;
    double AngularSecondMoment;
    double Contrast;
    double Dissimilarity;
    double InverseDifference;
    double InverseDifferenceNormalised;
    double InverseDifferenceMoment;
    double InverseDifferenceMomentNormalised;
    double InverseVariance;
    double Correlation;
    double Autocorrelation;
    double ClusterTendency;
    double ClusterShade;
    double ClusterProminence;
    double FirstMeasureOfInformationCorrelation;
    double SecondMeasureOfInformationCorrelation;
  };

}

static
void MatrixFeaturesTo(const mitk::CoocurenceMatrixFeatures& features,
  const std::string& prefix,
  const mitk::GIFCooccurenceMatrix2Configuration& config,
  mitk::GIFCooccurenceMatrix2::FeatureListType& featureList)
{
  featureList.push_back(std::make_pair(mitk::CreateFeatureID(config.id, prefix + "Joint Maximum"), features.JointMaximum));
  featureList.push_back(std::make_pair(mitk::CreateFeatureID(config.id, prefix + "Joint Average"), features.JointAverage));
  featureList.push_back(std::make_pair(mitk::CreateFeatureID(config.id, prefix + "Joint Variance"), features.JointVariance));
  featureList.push_back(std::make_pair(mitk::CreateFeatureID(config.id, prefix + "Joint Entropy"), features.JointEntropy));
  featureList.push_back(std::make_pair(mitk::CreateFeatureID(config.id, prefix + "Difference Average"), features.DifferenceAverage));
  featureList.push_back(std::make_pair(mitk::CreateFeatureID(config.id, prefix + "Difference Variance"), features.DifferenceVariance));
  featureList.push_back(std::make_pair(mitk::CreateFeatureID(config.id, prefix + "Difference Entropy"), features.DifferenceEntropy));
  featureList.push_back(std::make_pair(mitk::CreateFeatureID(config.id, prefix + "Sum Average"), features.SumAverage));
  featureList.push_back(std::make_pair(mitk::CreateFeatureID(config.id, prefix + "Sum Variance"), features.SumVariance));
  featureList.push_back(std::make_pair(mitk::CreateFeatureID(config.id, prefix + "Sum Entropy"), features.SumEntropy));
  featureList.push_back(std::make_pair(mitk::CreateFeatureID(config.id, prefix + "Angular Second Moment"), features.AngularSecondMoment));
  featureList.push_back(std::make_pair(mitk::CreateFeatureID(config.id, prefix + "Contrast"), features.Contrast));
  featureList.push_back(std::make_pair(mitk::CreateFeatureID(config.id, prefix + "Dissimilarity"), features.Dissimilarity));
  featureList.push_back(std::make_pair(mitk::CreateFeatureID(config.id, prefix + "Inverse Difference"), features.InverseDifference));
  featureList.push_back(std::make_pair(mitk::CreateFeatureID(config.id, prefix + "Inverse Difference Normalized"), features.InverseDifferenceNormalised));
  featureList.push_back(std::make_pair(mitk::CreateFeatureID(config.id, prefix + "Inverse Difference Moment"), features.InverseDifferenceMoment));
  featureList.push_back(std::make_pair(mitk::CreateFeatureID(config.id, prefix + "Inverse Difference Moment Normalized"), features.InverseDifferenceMomentNormalised));
  featureList.push_back(std::make_pair(mitk::CreateFeatureID(config.id, prefix + "Inverse Variance"), features.InverseVariance));
  featureList.push_back(std::make_pair(mitk::CreateFeatureID(config.id, prefix + "Correlation"), features.Correlation));
  featureList.push_back(std::make_pair(mitk::CreateFeatureID(config.id, prefix + "Autocorrelation"), features.Autocorrelation));
  featureList.push_back(std::make_pair(mitk::CreateFeatureID(config.id, prefix + "Cluster Tendency"), features.ClusterTendency));
  featureList.push_back(std::make_pair(mitk::CreateFeatureID(config.id, prefix + "Cluster Shade"), features.ClusterShade));
  featureList.push_back(std::make_pair(mitk::CreateFeatureID(config.id, prefix + "Cluster Prominence"), features.ClusterProminence));
  featureList.push_back(std::make_pair(mitk::CreateFeatureID(config.id, prefix + "First Measure of Information Correlation"), features.FirstMeasureOfInformationCorrelation));
  featureList.push_back(std::make_pair(mitk::CreateFeatureID(config.id, prefix + "Second Measure of Information Correlation"), features.SecondMeasureOfInformationCorrelation));
  featureList.push_back(std::make_pair(mitk::CreateFeatureID(config.id, prefix + "Row Maximum"), features.RowMaximum));
  featureList.push_back(std::make_pair(mitk::CreateFeatureID(config.id, prefix + "Row Average"), features.RowAverage));
  featureList.push_back(std::make_pair(mitk::CreateFeatureID(config.id, prefix + "Row Variance"), features.RowVariance));
  featureList.push_back(std::make_pair(mitk::CreateFeatureID(config.id, prefix + "Row Entropy"), features.RowEntropy));
  featureList.push_back(std::make_pair(mitk::CreateFeatureID(config.id, prefix + "First Row-Column Entropy"), features.FirstRowColumnEntropy));
  featureList.push_back(std::make_pair(mitk::CreateFeatureID(config.id, prefix + "Second Row-Column Entropy"), features.SecondRowColumnEntropy));
}

static
void CalculateMeanAndStdDevFeatures(std::vector<mitk::CoocurenceMatrixFeatures> featureList,
                                    mitk::CoocurenceMatrixFeatures &meanFeature,
                                    mitk::CoocurenceMatrixFeatures  &stdFeature);
static
void NormalizeMatrixFeature(mitk::CoocurenceMatrixFeatures &features,
                            std::size_t number);

mitk::CoocurenceMatrixHolder::CoocurenceMatrixHolder(double min, double max, int number) :
m_MinimumRange(min),
m_MaximumRange(max),
m_NumberOfBins(number)
{
  m_Matrix.resize(number, number);
  m_Matrix.fill(0);
  m_Stepsize = (max - min) / (number);
}

int mitk::CoocurenceMatrixHolder::IntensityToIndex(double intensity)
{
  int index = std::floor((intensity - m_MinimumRange) / m_Stepsize);
  return std::max(0, std::min(index, m_NumberOfBins - 1));
}

double mitk::CoocurenceMatrixHolder::IndexToMinIntensity(int index)
{
  return m_MinimumRange + index * m_Stepsize;
}
double mitk::CoocurenceMatrixHolder::IndexToMeanIntensity(int index)
{
  return m_MinimumRange + (index+0.5) * m_Stepsize;
}
double mitk::CoocurenceMatrixHolder::IndexToMaxIntensity(int index)
{
  return m_MinimumRange + (index + 1) * m_Stepsize;
}

template<typename TPixel, unsigned int VImageDimension>
void
CalculateCoOcMatrix(const itk::Image<TPixel, VImageDimension>* itkImage,
                    const itk::Image<unsigned short, VImageDimension>* mask,
                    itk::Offset<VImageDimension> offset,
                    int range,
                    mitk::CoocurenceMatrixHolder &holder)
{
  typedef itk::Image<TPixel, VImageDimension> ImageType;
  typedef itk::Image<unsigned short, VImageDimension> MaskImageType;
  typedef itk::ShapedNeighborhoodIterator<ImageType> ShapeIterType;
  typedef itk::ShapedNeighborhoodIterator<MaskImageType> ShapeMaskIterType;
  typedef itk::ImageRegionConstIterator<ImageType> ConstIterType;
  typedef itk::ImageRegionConstIterator<MaskImageType> ConstMaskIterType;

  itk::Size<VImageDimension> radius;
  radius.Fill(range+1);
  ShapeIterType imageOffsetIter(radius, itkImage, itkImage->GetLargestPossibleRegion());
  ShapeMaskIterType maskOffsetIter(radius, mask, mask->GetLargestPossibleRegion());
  imageOffsetIter.ActivateOffset(offset);
  maskOffsetIter.ActivateOffset(offset);
  ConstIterType imageIter(itkImage, itkImage->GetLargestPossibleRegion());
  ConstMaskIterType maskIter(mask, mask->GetLargestPossibleRegion());
  //  iterator.GetIndex() + ci.GetNeighborhoodOffset()
  auto region = mask->GetLargestPossibleRegion();

  while (!maskIter.IsAtEnd())
  {
    auto ciMask = maskOffsetIter.Begin();
    auto ciValue = imageOffsetIter.Begin();
    if (maskIter.Value() > 0 &&
      ciMask.Get() > 0 &&
      imageIter.Get() == imageIter.Get() &&
      ciValue.Get() == ciValue.Get() &&
      region.IsInside(maskOffsetIter.GetIndex() + ciMask.GetNeighborhoodOffset()))
    {
      int i = holder.IntensityToIndex(imageIter.Get());
      int j = holder.IntensityToIndex(ciValue.Get());
      holder.m_Matrix(i, j) += 1;
      holder.m_Matrix(j, i) += 1;
    }
    ++imageOffsetIter;
    ++maskOffsetIter;
    ++imageIter;
    ++maskIter;
  }
}

void CalculateFeatures(
  mitk::CoocurenceMatrixHolder &holder,
  mitk::CoocurenceMatrixFeatures & results
  )
{
  auto pijMatrix = holder.m_Matrix;
  auto piMatrix = holder.m_Matrix;
  auto pjMatrix = holder.m_Matrix;
  double Ng = holder.m_NumberOfBins;
  int NgSize = holder.m_NumberOfBins;
  pijMatrix /= pijMatrix.sum();
  piMatrix.rowwise().normalize();
  pjMatrix.colwise().normalize();

  for (int i = 0; i < holder.m_NumberOfBins; ++i)
    for (int j = 0; j < holder.m_NumberOfBins; ++j)
    {
      if (pijMatrix(i, j) != pijMatrix(i, j))
        pijMatrix(i, j) = 0;
      if (piMatrix(i, j) != piMatrix(i, j))
        piMatrix(i, j) = 0;
      if (pjMatrix(i, j) != pjMatrix(i, j))
        pjMatrix(i, j) = 0;
    }

  Eigen::VectorXd piVector = pijMatrix.colwise().sum();
  Eigen::VectorXd pjVector = pijMatrix.rowwise().sum();
  double sigmai = 0;;
  for (int i = 0; i < holder.m_NumberOfBins; ++i)
  {
    double iInt = i + 1;// holder.IndexToMeanIntensity(i);
    results.RowAverage += iInt * piVector(i);
    if (piVector(i) > 0)
    {
      results.RowEntropy -= piVector(i) * std::log(piVector(i)) / std::log(2);
    }
  }
  for (int i = 0; i < holder.m_NumberOfBins; ++i)
  {
    double iInt = i + 1; // holder.IndexToMeanIntensity(i);
    results.RowVariance += (iInt - results.RowAverage)*(iInt - results.RowAverage) * piVector(i);
  }
  results.RowMaximum = piVector.maxCoeff();
  sigmai = std::sqrt(results.RowVariance);

  Eigen::VectorXd pimj(NgSize);
  pimj.fill(0);
  Eigen::VectorXd pipj(2*NgSize);
  pipj.fill(0);

  results.JointMaximum += pijMatrix.maxCoeff();

  for (int i = 0; i < holder.m_NumberOfBins; ++i)
  {
    for (int j = 0; j < holder.m_NumberOfBins; ++j)
    {
      //double iInt = holder.IndexToMeanIntensity(i);
      //double jInt = holder.IndexToMeanIntensity(j);
      double iInt = i + 1;// holder.IndexToMeanIntensity(i);
      double jInt = j + 1;// holder.IndexToMeanIntensity(j);
      double pij = pijMatrix(i, j);

      int deltaK = (i - j)>0?(i-j) : (j-i);
      pimj(deltaK) += pij;
      pipj(i + j) += pij;

      results.JointAverage += iInt * pij;
      if (pij > 0)
      {
        results.JointEntropy -= pij * std::log(pij) / std::log(2);
        results.FirstRowColumnEntropy -= pij * std::log(piVector(i)*pjVector(j)) / std::log(2);
      }
      if (piVector(i) > 0 && pjVector(j) > 0 )
      {
        results.SecondRowColumnEntropy -= piVector(i)*pjVector(j) * std::log(piVector(i)*pjVector(j)) / std::log(2);
      }
      results.AngularSecondMoment += pij*pij;
      results.Contrast += (iInt - jInt)* (iInt - jInt) * pij;
      results.Dissimilarity += std::abs<double>(iInt - jInt) * pij;
      results.InverseDifference += pij / (1 + (std::abs<double>(iInt - jInt)));
      results.InverseDifferenceNormalised += pij / (1 + (std::abs<double>(iInt - jInt) / Ng));
      results.InverseDifferenceMoment += pij / (1 + (iInt - jInt)*(iInt - jInt));
      results.InverseDifferenceMomentNormalised += pij / (1 + (iInt - jInt)*(iInt - jInt)/Ng/Ng);
      results.Autocorrelation += iInt*jInt * pij;
      double cluster = (iInt + jInt - 2 * results.RowAverage);
      results.ClusterTendency += cluster*cluster * pij;
      results.ClusterShade += cluster*cluster*cluster * pij;
      results.ClusterProminence += cluster*cluster*cluster*cluster * pij;
      if (iInt != jInt)
      {
        results.InverseVariance += pij / (iInt - jInt) / (iInt - jInt);
      }
    }
  }
  results.Correlation = 1 / sigmai / sigmai * (-results.RowAverage*results.RowAverage+ results.Autocorrelation);
  results.FirstMeasureOfInformationCorrelation = (results.JointEntropy - results.FirstRowColumnEntropy) / results.RowEntropy;
  if (results.JointEntropy < results.SecondRowColumnEntropy)
  {
    results.SecondMeasureOfInformationCorrelation = sqrt(1 - exp(-2 * (results.SecondRowColumnEntropy - results.JointEntropy)));
  }
  else
  {
    results.SecondMeasureOfInformationCorrelation = 0;
  }

  for (int i = 0; i < holder.m_NumberOfBins; ++i)
  {
    for (int j = 0; j < holder.m_NumberOfBins; ++j)
    {
      //double iInt = holder.IndexToMeanIntensity(i);
      //double jInt = holder.IndexToMeanIntensity(j);
      double iInt = i + 1;
      double pij = pijMatrix(i, j);

      results.JointVariance += (iInt - results.JointAverage)* (iInt - results.JointAverage)*pij;
    }
  }

  for (int k = 0; k < NgSize; ++k)
  {
    results.DifferenceAverage += k* pimj(k);
    if (pimj(k) > 0)
    {
      results.DifferenceEntropy -= pimj(k) * log(pimj(k)) / std::log(2);
    }
  }
  for (int k = 0; k < NgSize; ++k)
  {
    results.DifferenceVariance += (results.DifferenceAverage-k)* (results.DifferenceAverage-k)*pimj(k);
  }

  for (int k = 0; k <2* NgSize ; ++k)
  {
    results.SumAverage += (2+k)* pipj(k);
    if (pipj(k) > 0)
    {
      results.SumEntropy -= pipj(k) * log(pipj(k)) / std::log(2);
    }
  }
  for (int k = 0; k < 2*NgSize; ++k)
  {
    results.SumVariance += (2+k - results.SumAverage)* (2+k - results.SumAverage)*pipj(k);
  }

  //MITK_INFO << std::endl << holder.m_Matrix;
  //MITK_INFO << std::endl << pijMatrix;
  //MITK_INFO << std::endl << piMatrix;
  //MITK_INFO << std::endl << pjMatrix;

  //for (int i = 0; i < holder.m_NumberOfBins; ++i)
  //{
  //  MITK_INFO << "Bin " << i << " Min: " << holder.IndexToMinIntensity(i) << " Max: " << holder.IndexToMaxIntensity(i);
  //}
  //MITK_INFO << pimj;
  //MITK_INFO << pipj;

}

template<typename TPixel, unsigned int VImageDimension>
void
CalculateCoocurenceFeatures(const itk::Image<TPixel, VImageDimension>* itkImage, const mitk::Image* mask, mitk::GIFCooccurenceMatrix2::FeatureListType & featureList, mitk::GIFCooccurenceMatrix2Configuration config)
{
  typedef itk::Image<unsigned short, VImageDimension> MaskType;
  typedef itk::Neighborhood<TPixel, VImageDimension > NeighborhoodType;
  typedef itk::Offset<VImageDimension> OffsetType;

  ///////////////////////////////////////////////////////////////////////////////////////////////
  double rangeMin = config.MinimumIntensity;
  double rangeMax = config.MaximumIntensity;
  int numberOfBins = config.Bins;

  typename MaskType::Pointer maskImage = MaskType::New();
  mitk::CastToItkImage(mask, maskImage);

  //Find possible directions
  std::vector < itk::Offset<VImageDimension> > offsetVector;
  NeighborhoodType hood;
  hood.SetRadius(1);
  unsigned int        centerIndex = hood.GetCenterNeighborhoodIndex();
  OffsetType          offset;
  for (unsigned int d = 0; d < centerIndex; d++)
  {
    offset = hood.GetOffset(d);
    bool useOffset = true;
    for (unsigned int i = 0; i < VImageDimension; ++i)
    {
      offset[i] *= config.range;
      if (config.direction == i + 2 && offset[i] != 0)
      {
        useOffset = false;
      }
    }
    if (useOffset)
    {
      offsetVector.push_back(offset);
    }
  }
  if (config.direction == 1)
  {
    offsetVector.clear();
    offset[0] = 0;
    offset[1] = 0;
    offset[2] = 1;
  }

  std::vector<mitk::CoocurenceMatrixFeatures> resultVector;
  mitk::CoocurenceMatrixHolder holderOverall(rangeMin, rangeMax, numberOfBins);
  mitk::CoocurenceMatrixFeatures overallFeature;
  for (std::size_t i = 0; i < offsetVector.size(); ++i)
  {
    if (config.direction > 1)
    {
      if (offsetVector[i][config.direction - 2] != 0)
      {
        continue;
      }
    }

    offset = offsetVector[i];
    mitk::CoocurenceMatrixHolder holder(rangeMin, rangeMax, numberOfBins);
    mitk::CoocurenceMatrixFeatures coocResults;
    CalculateCoOcMatrix<TPixel, VImageDimension>(itkImage, maskImage, offset, config.range, holder);
    holderOverall.m_Matrix += holder.m_Matrix;
    CalculateFeatures(holder, coocResults);
    resultVector.push_back(coocResults);
  }
  CalculateFeatures(holderOverall, overallFeature);
  //NormalizeMatrixFeature(overallFeature, offsetVector.size());

  mitk::CoocurenceMatrixFeatures featureMean;
  mitk::CoocurenceMatrixFeatures featureStd;
  CalculateMeanAndStdDevFeatures(resultVector, featureMean, featureStd);

  std::ostringstream  ss;
  ss << config.range;
  std::string strRange = ss.str();

  MatrixFeaturesTo(overallFeature, "Overall ", config, featureList);
  MatrixFeaturesTo(featureMean, "Mean ", config, featureList);
  MatrixFeaturesTo(featureStd, "Std.Dev. ", config, featureList);
}

static
void CalculateMeanAndStdDevFeatures(std::vector<mitk::CoocurenceMatrixFeatures> featureList,
  mitk::CoocurenceMatrixFeatures &meanFeature,
  mitk::CoocurenceMatrixFeatures  &stdFeature)
{
#define ADDFEATURE(a)                                                                         \
  if ( ! (featureList[i].a == featureList[i].a)) featureList[i].a = 0;                        \
   meanFeature.a += featureList[i].a;stdFeature.a += featureList[i].a*featureList[i].a
#define CALCVARIANCE(a) stdFeature.a =sqrt(stdFeature.a - meanFeature.a*meanFeature.a)

  for (std::size_t i = 0; i < featureList.size(); ++i)
  {
    ADDFEATURE(JointMaximum);
    ADDFEATURE(JointAverage);
    ADDFEATURE(JointVariance);
    ADDFEATURE(JointEntropy);
    ADDFEATURE(RowMaximum);
    ADDFEATURE(RowAverage);
    ADDFEATURE(RowVariance);
    ADDFEATURE(RowEntropy);
    ADDFEATURE(FirstRowColumnEntropy);
    ADDFEATURE(SecondRowColumnEntropy);
    ADDFEATURE(DifferenceAverage);
    ADDFEATURE(DifferenceVariance);
    ADDFEATURE(DifferenceEntropy);
    ADDFEATURE(SumAverage);
    ADDFEATURE(SumVariance);
    ADDFEATURE(SumEntropy);
    ADDFEATURE(AngularSecondMoment);
    ADDFEATURE(Contrast);
    ADDFEATURE(Dissimilarity);
    ADDFEATURE(InverseDifference);
    ADDFEATURE(InverseDifferenceNormalised);
    ADDFEATURE(InverseDifferenceMoment);
    ADDFEATURE(InverseDifferenceMomentNormalised);
    ADDFEATURE(InverseVariance);
    ADDFEATURE(Correlation);
    ADDFEATURE(Autocorrelation);
    ADDFEATURE(ClusterShade);
    ADDFEATURE(ClusterTendency);
    ADDFEATURE(ClusterProminence);
    ADDFEATURE(FirstMeasureOfInformationCorrelation);
    ADDFEATURE(SecondMeasureOfInformationCorrelation);
  }
  NormalizeMatrixFeature(meanFeature, featureList.size());
  NormalizeMatrixFeature(stdFeature, featureList.size());

  CALCVARIANCE(JointMaximum);
  CALCVARIANCE(JointAverage);
  CALCVARIANCE(JointVariance);
  CALCVARIANCE(JointEntropy);
  CALCVARIANCE(RowMaximum);
  CALCVARIANCE(RowAverage);
  CALCVARIANCE(RowVariance);
  CALCVARIANCE(RowEntropy);
  CALCVARIANCE(FirstRowColumnEntropy);
  CALCVARIANCE(SecondRowColumnEntropy);
  CALCVARIANCE(DifferenceAverage);
  CALCVARIANCE(DifferenceVariance);
  CALCVARIANCE(DifferenceEntropy);
  CALCVARIANCE(SumAverage);
  CALCVARIANCE(SumVariance);
  CALCVARIANCE(SumEntropy);
  CALCVARIANCE(AngularSecondMoment);
  CALCVARIANCE(Contrast);
  CALCVARIANCE(Dissimilarity);
  CALCVARIANCE(InverseDifference);
  CALCVARIANCE(InverseDifferenceNormalised);
  CALCVARIANCE(InverseDifferenceMoment);
  CALCVARIANCE(InverseDifferenceMomentNormalised);
  CALCVARIANCE(InverseVariance);
  CALCVARIANCE(Correlation);
  CALCVARIANCE(Autocorrelation);
  CALCVARIANCE(ClusterShade);
  CALCVARIANCE(ClusterTendency);
  CALCVARIANCE(ClusterProminence);
  CALCVARIANCE(FirstMeasureOfInformationCorrelation);
  CALCVARIANCE(SecondMeasureOfInformationCorrelation);

#undef ADDFEATURE
#undef CALCVARIANCE
}

static
void NormalizeMatrixFeature(mitk::CoocurenceMatrixFeatures &features,
                            std::size_t number)
{
  features.JointMaximum = features.JointMaximum / number;
  features.JointAverage = features.JointAverage / number;
  features.JointVariance = features.JointVariance / number;
  features.JointEntropy = features.JointEntropy / number;
  features.RowMaximum = features.RowMaximum / number;
  features.RowAverage = features.RowAverage / number;
  features.RowVariance = features.RowVariance / number;
  features.RowEntropy = features.RowEntropy / number;
  features.FirstRowColumnEntropy = features.FirstRowColumnEntropy / number;
  features.SecondRowColumnEntropy = features.SecondRowColumnEntropy / number;
  features.DifferenceAverage = features.DifferenceAverage / number;
  features.DifferenceVariance = features.DifferenceVariance / number;
  features.DifferenceEntropy = features.DifferenceEntropy / number;
  features.SumAverage = features.SumAverage / number;
  features.SumVariance = features.SumVariance / number;
  features.SumEntropy = features.SumEntropy / number;
  features.AngularSecondMoment = features.AngularSecondMoment / number;
  features.Contrast = features.Contrast / number;
  features.Dissimilarity = features.Dissimilarity / number;
  features.InverseDifference = features.InverseDifference / number;
  features.InverseDifferenceNormalised = features.InverseDifferenceNormalised / number;
  features.InverseDifferenceMoment = features.InverseDifferenceMoment / number;
  features.InverseDifferenceMomentNormalised = features.InverseDifferenceMomentNormalised / number;
  features.InverseVariance = features.InverseVariance / number;
  features.Correlation = features.Correlation / number;
  features.Autocorrelation = features.Autocorrelation / number;
  features.ClusterShade = features.ClusterShade / number;
  features.ClusterTendency = features.ClusterTendency / number;
  features.ClusterProminence = features.ClusterProminence / number;
  features.FirstMeasureOfInformationCorrelation = features.FirstMeasureOfInformationCorrelation / number;
  features.SecondMeasureOfInformationCorrelation = features.SecondMeasureOfInformationCorrelation / number;
}

mitk::GIFCooccurenceMatrix2::GIFCooccurenceMatrix2():
  m_Ranges({ 1.0 })
{
  SetShortName("cooc2");
  SetLongName("cooccurence2");
  SetFeatureClassName("Co-occurenced Based Features");
}

void mitk::GIFCooccurenceMatrix2::SetRanges(std::vector<double> ranges)
{
  m_Ranges = ranges;
  this->Modified();
}

void mitk::GIFCooccurenceMatrix2::SetRange(double range)
{
  m_Ranges.resize(1);
  m_Ranges[0] = range;
  this->Modified();
}

mitk::AbstractGlobalImageFeature::FeatureListType mitk::GIFCooccurenceMatrix2::DoCalculateFeatures(const Image* image, const Image* mask)
{
  FeatureListType featureList;

  InitializeQuantifier(image, mask);

  for (const auto& range: m_Ranges)
  {
    MITK_INFO << "Start calculating coocurence with range " << range << "....";

    GIFCooccurenceMatrix2Configuration config;
    config.direction = GetDirection();
    config.range = range;
    config.MinimumIntensity = GetQuantifier()->GetMinimum();
    config.MaximumIntensity = GetQuantifier()->GetMaximum();
    config.Bins = GetQuantifier()->GetBins();
    config.id = this->CreateTemplateFeatureID(std::to_string(range), { {GetOptionPrefix() + "::range", range} });

    AccessByItk_3(image, CalculateCoocurenceFeatures, mask, featureList, config);

    MITK_INFO << "Finished calculating coocurence with range " << range << "....";
  }

  return featureList;
}

mitk::AbstractGlobalImageFeature::FeatureListType mitk::GIFCooccurenceMatrix2::CalculateFeatures(const Image* image, const Image*, const Image* maskNoNAN)
{
  return Superclass::CalculateFeatures(image, maskNoNAN);
}

void mitk::GIFCooccurenceMatrix2::AddArguments(mitkCommandLineParser &parser) const
{
  this->AddQuantifierArguments(parser);

  std::string name = this->GetOptionPrefix();

  parser.addArgument(this->GetLongName(), name, mitkCommandLineParser::Bool, "Use Co-occurence matrix", "calculates Co-occurence based features (new implementation)", us::Any());
  parser.addArgument(name+"::range", name+"::range", mitkCommandLineParser::String, "Cooc 2 Range", "Define the range that is used (Semicolon-separated)", us::Any());
}

std::string mitk::GIFCooccurenceMatrix2::GenerateLegacyFeatureEncoding(const FeatureID& id) const
{
  return QuantifierParameterString() + "_Range-" + id.parameters.at(this->GetOptionPrefix()+"::range").ToString();
}

void mitk::GIFCooccurenceMatrix2::ConfigureSettingsByParameters(const ParametersType& parameters)
{
  auto name = GetOptionPrefix()+"::range";
  if (parameters.count(name))
  {
    m_Ranges = SplitDouble(parameters.at(name).ToString(), ';');
  }
}


text:
package org.example;

import griffon.core.artifact.GriffonView;
import griffon.javafx.support.JavaFXAction;
import griffon.javafx.support.JavaFXUtils;
import griffon.javafx.support.fontawesome.FontAwesomeIcon;
import griffon.metadata.ArtifactProviderFor;
import griffon.plugins.fontawesome.FontAwesome;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.Tab;
import javafx.scene.control.TextField;
import javafx.scene.layout.AnchorPane;
import org.codehaus.griffon.runtime.javafx.artifact.AbstractJavaFXGriffonView;

import static javafx.scene.layout.AnchorPane.setLeftAnchor;
import static javafx.scene.layout.AnchorPane.setTopAnchor;

@ArtifactProviderFor(GriffonView.class)
public class Tab1View extends AbstractJavaFXGriffonView {
    private SampleController controller;
    private SampleModel model;
    private AppView parentView;

    @Override
    public void initUI() {
        AnchorPane anchorPane = new AnchorPane();
        anchorPane.setPrefHeight(90.0);
        anchorPane.setPrefWidth(384.0);

        Label label = new Label(getApplication().getMessageSource().getMessage("name.label"));
        TextField input = new TextField();
        input.setPrefWidth(200.0);

        Button button = new Button();
        button.setPrefWidth(200.0);
        JavaFXUtils.configure(button, (JavaFXAction) actionFor(controller, "sayHello").getToolkitAction());

        Label output = new Label();
        label.setPrefWidth(360.0);

        model.inputProperty().bindBidirectional(input.textProperty());
        model.outputProperty().bindBidirectional(output.textProperty());

        anchorPane.getChildren().addAll(label, input, button, output);

        setLeftAnchor(label, 14.0);
        setTopAnchor(label, 14.0);
        setLeftAnchor(input, 172.0);
        setTopAnchor(input, 11.0);
        setLeftAnchor(button, 172.0);
        setTopAnchor(button, 45.0);
        setLeftAnchor(output, 14.0);
        setTopAnchor(output, 80.0);

        Tab tab = new Tab("Java");
        tab.setGraphic(new FontAwesomeIcon(FontAwesome.FA_COFFEE));
        tab.setClosable(false);
        tab.setContent(anchorPane);
        parentView.getTabPane().getTabs().add(tab);
    }
}


text:
Please follow the instructions bellow before attending to the workshop.

## Install TensorFlow

https://www.tensorflow.org/install/

## Install other Dependencies

* Run: `$ sudo install_dependencies.sh` you can pass --python-version (2 or 3) as a parameter,
if you don't pass it it will install the dependencies for both versions of Python.

* Install dependencies manyally:
	* `python2 -m pip install jupyter numpy pandas matplotlib pillow`
  * `python3 -m pip install jupyter numpy pandas matplotlib pillow`

**If you are not familiar with [Jupyter notebooks](http://jupyter.readthedocs.io/en/latest/index.html) please visit the website and play with it**

## Test if everything is working properly

1. Clone this repo or download it
2. cd tensorflow-workshop
3. jupyter notebook
4. run test_install.ipynb

# Want to report a bug?

Thanks! Can you please file an issue? We'll be doing this samples for a couple times, and future developers will appreciate your help.

- - -

General disclaimer, this is my personal repo and not an official Google product. If you'd like to use this code, say, to build a mission critical component of your giant space laser, you should know there's no warranty, etc.


text:
import { Observable } from "rxjs/Observable";
import "rxjs/add/observable/of";
import "rxjs/add/operator/do";
import "rxjs/add/operator/first";
import "rxjs/add/operator/filter";
import "rxjs/add/operator/map";
import "rxjs/add/operator/observeOn";
import "rxjs/add/operator/publishReplay";
import "rxjs/add/operator/scan";
import "rxjs/add/operator/startWith";
import "rxjs/add/operator/withLatestFrom";
import "rxjs/add/operator/switchMap";
import "rxjs/add/operator/takeUntil";
import { queue } from "rxjs/scheduler/queue";
import {
  Store, Action, Reducer, StateUpdate,
  Dispatcher, StoreMiddleware, EmptyActionDescription,
} from "./interfaces";

const scheduler = queue;

export const startEffectsOn =
  (dispatch: Dispatcher | Observable<Dispatcher>) =>
    (...effects: Observable<Action>[]) => {
      const dispatch$ = typeof dispatch === "function"
        ? Observable.of(dispatch)
        : dispatch;
      effects.forEach(effect => {
        effect
          .observeOn(scheduler)
          .withLatestFrom(dispatch$/*.observeOn(scheduler)*/, (a, d) => [a, d] as ([Action, Dispatcher]))
          // .do<[Action, Dispatcher]>(([a, d]) => d(a))
          .subscribe(([a, d]) => d(a));
      });
    };

export const startEffects = (
  dispatch: Dispatcher | Observable<Dispatcher>,
  ...effects: Observable<Action>[]
) => startEffectsOn(dispatch)(...effects);


text:
package com.thinkbiganalytics.integration;

/**
 * Configuration required to connect to running Kylo instance
 */
public class KyloConfig {

    private String host;
    private int port;
    private String basePath;
    private String username;
    private String password;

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public String getBasePath() {
        return basePath;
    }

    public void setBasePath(String basePath) {
        this.basePath = basePath;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}


text:
$(document).on('ready page:load', function () {
	$('#navbarToggle').on('click', function(e) {
		if( $('#navbar').hasClass('hide') ) {
			$('#navbar').removeClass('hide');
		} else {
			$('#navbar').addClass('hide');
		}
	});
});


text:
Technical Information

What server platform are you using?

Just Journal is hosted on a MidnightBSD server using Apache 2.4, Apache Tomcat
        7.0, and Java 1.6 (native). I use MySQL 5.6.x for the data store.

Isn't Java slow?

This is a common misconception. Java used at the server level is quite fast.
        Most people are thinking of Java Applications that use AWT or Swing when
        they say Java is slow. The Java GUI libraries are slow, but server side
        technologies power huge Internet sites including BestBuy.com, CircuitCity.com,
        and sun.com.

Do you think this site will scale?

The current version needs work in this area, but I think that I can handle
        the load for some time. In reality, the weakest link is MySQL. I will work
        on Caching systems, and generating dynamic content into static form. I
        may end up moving away from mysql if performance becomes an issue.

Isn't this site like LiveJournal? Why didn't you just use their code?

LiveJournal was a great website when I first started using it.
        Unfortunetely,
        it didn't scale well. I suggested some changes to Live Journal including
        changing the styling system and switching to CSS for many of the "template
        tasks." It appeared that my comments were not going to be considered
        since the creator based it on a "language" he created called BML.

BML is an HTML template system written in Perl 5. It was designed help reuse
        blocks of html similar to objects. The idea was nice at the time, but it
        was implemented in Perl making it slow and Cascading Style Sheets solve
        most of the same problems. (presentation code reuse)

I did download
        the LiveJournal code to see if I could alter it and import my own style
        system, but LiveJournal is implemented as mod perl modules tightly integrated
        with the BML code. The use of mod perl for a legacy version of apache (1.3)
        showed me that the project was not salvagable without a lot of work. I
        finally decided to write a site from scratch in a language more suited
        to me.

LiveJournal has since implemented a caching system using a C server program
        (hash, storing "objects" in ram), and upgraded the style system.
        Recently, LiveJournal started storing practically everything in RAM.

There are several other limitations LiveJournal has because they must be
        backward compatible. Since I am writing JustJournal from scratch, I may
        avoid some of their mistakes making this site better than LJ.

Is this site open source?

Yes. I released the code under the BSD license. The windows client
        is under the GPL license due to code that I based it on. (LJ.NET client)


text:
module.exports = function(grunt) {

  require('fatjs')(grunt, {
    name: 'angular-mask',
    full: true, //include bower deps in build
    filename: 'angular-mask', //no ext
    fullFilename: 'angular-mask.full' //no ext
  });

};


text:
if(not BtUtils)then VFS.Include(LUAUI_DIRNAME .. "Widgets/BtUtils/root.lua", nil, VFS.RAW_FIRST) end

local Utils = BtUtils

return Utils:Assign("ProjectDialog", function()

	local ProjectDialog = {}

	local Debug = Utils.Debug;
	local Logger = Debug.Logger
	local dump = Debug.dump
	local Chili = Utils.Chili

	local ProjectManager = Utils.ProjectManager
	local Sanitizer = Utils.Sanitizer
	local Debug = Utils.Debug
	local Logger = Debug.Logger

	local NEW_ITEM_STRING = "--NEW ITEM--"
	local NEW_PROJECT_STRING = "--NEW PROJECT--"

	ProjectDialog.LOAD_DIALOG = "LOAD"
	ProjectDialog.SAVE_DIALOG = "SAVE"
	ProjectDialog.NEW_DIALOG = "NEW"

	local PATH = LUAUI_DIRNAME.."Widgets/BtUtils/"
	local BACKGROUND_IMAGE_NAME = "black.png"

	local dialogWindow

	local function sortItems(items)
		table.sort(items, function(x,y) return x.name:lower() < y.name:lower() end)
	end

	local function onSelectItem(self)
		if(self.items[self.selected] == self.newItemString) then
			if(not self.newItemEditBox.visible ) then
				self.newItemEditBox:Show()
			end
		else
			if(self.newItemEditBox.visible)then
				self.newItemEditBox:Hide()
			end
		end
	end

	local function onSelectProject(self)
		local selected = self.items[self.selected]
		self.itemComboBox:Show()
		if( selected == self.newProjectString) then
			if(not self.newProjectEditBox.visible ) then
				self.newProjectEditBox:Show()
			end
			-- add possible new item
			self.itemComboBox.items = {self.newItemString}
			self.itemComboBox:Select(1)
		else
			if( self.newProjectEditBox.visible ) then
				self.newProjectEditBox:Hide()
			end
			-- i should update item combo box:
			-- new items:
			local listProject = self.projectManager.listProject(selected, self.contentType)
			sortItems(listProject)
			local newItems = {}
			for i,data in ipairs(listProject)do
				newItems[i] = data.name
			end
			-- add possible new item
			if self.creatingEnabled then
				newItems[#newItems+1] = self.newItemString
			end
			self.itemComboBox.items = newItems
			self.itemComboBox:Select(1)
			if(#newItems == 0)then
				self.itemComboBox:Hide()
			end
		end
	end

	local function doneButtonListener(self)
		local selectedProject = self.projectSelection.items[self.projectSelection.selected]
		if(selectedProject == self.newProjectString) then
			selectedProject = self.newProjectEditBox.text
		end

		local selectedItem
		if(self.itemSelection) then
			-- the new button
			selectedItem = self.itemSelection.items[self.itemSelection.selected]
			if(selectedItem == self.newItemString) then
				selectedItem = self.newItemEditBox.text
			end
		else
			selectedItem = self.newItemEditBox.text
		end

		if(selectedProject and string.len(selectedProject ) > 0 and selectedItem and string.len(selectedItem)> 0 ) then
			-- selected project and item are not empty strings
			self.callback(self.callbackObject, selectedProject, selectedItem)
			self.showDialogHandler(false)
		end
		-- else do nothing
	end

	local function cancelButtonListener(self)
		self.callback(self.callbackObject)
		self.showDialogHandler(false)
	end

	local function hideWindowAndCall(window, ...)
		if window.visible then
			window:Hide()
		end
		window.callback(...)
		window:Dispose()
	end

	-- This will attach corresponding chili components of save/load dialog to a given parent.
	function ProjectDialog.setUpDialog(parent, contentType, creatingEnabled, callbackObject, callbackFunction, showDialogHandler, defaultProject, defaultName)
		callbackFunction = Sanitizer.sanitize(callbackFunction)

		local sanitizer = Utils.Sanitizer.forCurrentWidget()

		local selectedProject = nil
		local projects = ProjectManager.getProjects()
		sortItems(projects)
		local projectNames = {}
		for i,data in ipairs(projects) do
			projectNames[i] = data.name
			if(data.name == defaultProject)then
				selectedProject = i
				defaultProject = nil
			end
		end
		if creatingEnabled then
			if(not selectedProject and defaultProject)then
				selectedProject = #projectNames+1
			end
			projectNames[#projectNames+1] = NEW_PROJECT_STRING
		end

		local newProjectEditBox = Chili.EditBox:New{
			parent = parent,
			text = defaultProject or "Unknown",
			x = 15,
			y = 60,
			width = 120,
			height = 20,

		}

		local newItemEditBox = Chili.EditBox:New{
			parent = parent,
			text = defaultName or "untitled",
			x = 150,
			y = 60,
			width = 140,
			height = 20,

		}

		local itemSelection = Chili.ComboBox:New{
			parent = parent,
			x = 135,
			y = 20,
			width = 200,
			height = 35,
			items = {"noItem"},
			OnSelect = {sanitizer:AsHandler(onSelectItem)},
			newItemEditBox = newItemEditBox,
			newItemString = NEW_ITEM_STRING,
			newItemLabel = newLabel,
		}

		local projectSelection = Chili.ComboBox:New{
			parent = parent,
			x = 15,
			y = 20,
			width = 120,
			height = 35,
			items = projectNames,
			selected = selectedProject,
			OnSelect = {sanitizer:AsHandler(onSelectProject)},
			newProjectEditBox = newProjectEditBox,
			newProjectString = NEW_PROJECT_STRING,
			newItemString = NEW_ITEM_STRING,
			itemComboBox = itemSelection,
			projectManager = ProjectManager,
			contentType = contentType,
			creatingEnabled = creatingEnabled
		}

		for i, name in ipairs(itemSelection.items) do
			if(name == defaultName)then
				itemSelection:Select(i)
				newItemEditBox:SetText("untitled")
				break
			end
		end

		local doneButton = Chili.Button:New{
			parent = parent,
			x = 50,
			y = 80,
			width = 100,
			height = 30,
			caption = "DONE",
			OnClick = {sanitizer:AsHandler(doneButtonListener)},
			skinName = 'DarkGlass',
			focusColor = {1,0.5,0,0.5},
		}
		doneButton.callback = callbackFunction
		doneButton.callbackObject = callbackObject
		doneButton.projectSelection = projectSelection
		doneButton.itemSelection = itemSelection
		doneButton.newItemEditBox = newItemEditBox
		doneButton.newItemString = NEW_ITEM_STRING
		doneButton.newProjectEditBox = newProjectEditBox
		doneButton.newProjectString = NEW_PROJECT_STRING
		doneButton.showDialogHandler = showDialogHandler

		local cancelButton = Chili.Button:New{
			parent = parent,
			x = 150,
			y = 80,
			width = 100,
			height = 30,
			caption = "CANCEL",
			OnClick = {sanitizer:AsHandler(cancelButtonListener)},
			skinName = 'DarkGlass',
			focusColor = {1,0.5,0,0.5},
		}
		cancelButton.callback = callbackFunction
		cancelButton.callbackObject = callbackObject
		cancelButton.showDialogHandler = showDialogHandler
	end

	local function onSelectProjectNew(self)
		local selected = self.items[self.selected]
		if( selected == self.newProjectString) then
			if(not self.newProjectEditBox.visible ) then
				self.newProjectEditBox:Show()
			end
		else
			if( self.newProjectEditBox.visible ) then
				self.newProjectEditBox:Hide()
			end
		end
	end

	-- This will attach corresponding chili components of new item dialog to a given parent.
	function ProjectDialog.setUpDialogNewItem(parent, contentType, callbackObject, callbackFunction, showDialogHandler, defaultProject, defaultName)
		callbackFunction = Sanitizer.sanitize(callbackFunction)

		local sanitizer = Utils.Sanitizer.forCurrentWidget()
		local firstLineY = 20
		local secondLineY = 60
		local thirdLineY = 80

		local selectedProject = nil
		local projects = ProjectManager.getProjects()
		sortItems(projects)
		local projectNames = {}
		for i,data in ipairs(projects) do
			projectNames[i] = data.name
			if(data.name == defaultProject)then
				selectedProject = i
				defaultProject = nil
			end
		end
		if(not selectedProject)then
			selectedProject = #projectNames+1
		end
		projectNames[#projectNames+1] = NEW_PROJECT_STRING

		local newProjectEditBox = Chili.EditBox:New{
			parent = parent,
			text = defaultProject or "Untitled",
			x = 15,
			y = secondLineY,
			width = 120,
			height = 20,

		}

		local newItemEditBox = Chili.EditBox:New{
			parent = parent,
			text = defaultName or "unknown",
			x = 150,
			y = firstLineY,
			width = 140,
			height = 20,

		}

		local projectSelection = Chili.ComboBox:New{
			parent = parent,
			x = 15,
			y = 20,
			width = 120,
			height = 35,
			items = projectNames,
			selected = selectedProject,
			OnSelect = {sanitizer:AsHandler(onSelectProjectNew)},
			newProjectEditBox = newProjectEditBox,
			newProjectString = NEW_PROJECT_STRING,
			projectManager = ProjectManager,
			contentType = contentType,
		}

		local doneButton = Chili.Button:New{
			parent = parent,
			x = 50,
			y = thirdLineY,
			width = 100,
			height = 30,
			caption = "DONE",
			OnClick = {sanitizer:AsHandler(doneButtonListener)},
			skinName = 'DarkGlass',
		}
		doneButton.callback = callbackFunction
		doneButton.callbackObject = callbackObject
		doneButton.projectSelection = projectSelection
		doneButton.newItemEditBox = newItemEditBox
		doneButton.newProjectEditBox = newProjectEditBox
		doneButton.newProjectString = NEW_PROJECT_STRING
		doneButton.showDialogHandler = showDialogHandler

		local cancelButton = Chili.Button:New{
			parent = parent,
			x = 150,
			y = 80,
			width = 100,
			height = 30,
			caption = "CANCEL",
			OnClick = {sanitizer:AsHandler(cancelButtonListener)},
			skinName = 'DarkGlass',
		}
		cancelButton.callback = callbackFunction
		cancelButton.callbackObject = callbackObject
		cancelButton.showDialogHandler = showDialogHandler
	end

	local function showDialogWindow(visibilityHandler, contentType, dialogFlag, callbackFunction, title, xIn, yIn, defaultProject, defaultName)
		visibilityHandler = visibilityHandler and Sanitizer.sanitize(visibilityHandler) or function() end
		callbackFunction = callbackFunction and Sanitizer.sanitize(callbackFunction) or function() end
		local sanitizer = Utils.Sanitizer.forCurrentWidget()

		local winWidth = 400
		local winHeight = 185

		local dialogWindow = Chili.Window:New{
			parent = Chili.Screen0,
			x = xIn or 300,
			y = yIn or 500,
			width =  winWidth,
			height = winHeight,
			padding = {10,10,10,10},
			draggable = true,
			resizable = true,
			skinName = 'DarkGlass',
		}
		dialogWindow.backgroundColor = {1,1,1,1}
		dialogWindow.TileImage = PATH .. BACKGROUND_IMAGE_NAME
		dialogWindow:Invalidate()

		dialogWindow.callback = callbackFunction

		local label = Chili.Label:New{
			parent = dialogWindow,
			x = 5,
			y = 5,
			height = 30,
			width = '90%',
			caption = title,
			skinName = 'DarkGlass',
		}
		local panel = Chili.Control:New{
			parent = dialogWindow,
			x = 0,
			y = 30,
			height = 150,
			width = 400,
			skinName = 'DarkGlass',
		}

		local sanitizedHideWindowAndCall = sanitizer:Sanitize(hideWindowAndCall)

		if(dialogFlag == ProjectDialog.LOAD_DIALOG) then
			ProjectDialog.setUpDialog(panel, contentType, false, dialogWindow, sanitizedHideWindowAndCall, visibilityHandler, defaultProject, defaultName)
		end
		if(dialogFlag == ProjectDialog.SAVE_DIALOG) then
			ProjectDialog.setUpDialog(panel, contentType, true, dialogWindow, sanitizedHideWindowAndCall, visibilityHandler, defaultProject, defaultName)
		end
		if(dialogFlag == ProjectDialog.NEW_DIALOG) then
			ProjectDialog.setUpDialogNewItem(panel, contentType, dialogWindow, sanitizedHideWindowAndCall, visibilityHandler, defaultProject, defaultName)
		end

		visibilityHandler(true)
	end

	--- Shows a dialog that allows the user to select a project and a name of a content.
	-- @tab params Table of parameters tha can contain the following slots.
	--
	-- - `visibilityHandler` - function that is called with `true` when dialog is shown and with `false` when it is hidden, can be used to disable other components while the dialog is shown
	-- - `contentType` - @{ProjectManager.ContentType} that the dialog handles
	-- - `dialogType` - one of the following
	--     - `ProjectDialog.LOAD_DIALOG`
	--     - `ProjectDialog.SAVE_DIALOG`
	--     - `ProjectDialog.NEW_DIALOG`
	-- - `title` - title of the dialog
	-- - `x`, `y` - position where to show the dialog
	-- - `project`, `name` - initial selected items in the dialog
	-- @func callbackFunction Function that gets called after the dialog concludes.
	function ProjectDialog.showDialog(params, callbackFunction)
		showDialogWindow(params.visibilityHandler, params.contentType, params.dialogType, callbackFunction, params.title, params.x, params.y, params.project, params.name)
	end

	return ProjectDialog
end)


text:
#ifndef GrAAConvexPathRenderer_DEFINED
#  define GrAAConvexPathRenderer_DEFINED
#  include "src/gpu/GrPathRenderer.h"
class GrAAConvexPathRenderer : public GrPathRenderer
{
public:
  GrAAConvexPathRenderer();
private:
  CanDrawPath onCanDrawPath(const CanDrawPathArgs&) const override;
  bool onDrawPath(const DrawPathArgs&) override;
};
#endif


text:
/**
 * @module expression
 */
import { ComparatorOperator } from './comparator-operator.type'
import { FunctionOperator } from './function-operator.type'

/**
 *
 * http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.OperatorsAndFunctions.html#Expressions.OperatorsAndFunctions.Syntax
 *
 * condition-expression ::=
 *  operand comparator operand
 *    | operand BETWEEN operand AND operand
 *    | operand IN ( operand (',' operand (, ...) ))
 *    | function
 *    | condition AND condition
 *    | condition OR condition
 *    | NOT condition
 *    | ( condition )
 *
 * comparator ::=
 *    =
 *   | <>
 *   | <
 *   | <=
 *   | >
 *   | >=
 *
 * function ::=
 *    attribute_exists (path)
 *    | attribute_not_exists (path)
 *    | attribute_type (path, type)
 *    | begins_with (path, substr)
 *    | contains (path, operand)
 *    | size (path)
 * @hidden
 */
export type ConditionOperator = FunctionOperator | ComparatorOperator


text:
/*
 * This file was originally distributed by Qualcomm Atheros, Inc.
 * under proprietary terms before Copyright ownership was assigned
 * to the Linux Foundation.
 */

/*
 *
 * This file limStaHashApi.h contains the
 * function prototypes for accessing station hash entry fields.
 *
 * Author:      Sunit Bhatia
 * Date:        09/19/2006
 * History:-
 * Date            Modified by    Modification Information
 * --------------------------------------------------------------------
 *
 */

#ifndef __LIM_STA_HASH_API_H__
#define __LIM_STA_HASH_API_H__

#include "aniGlobal.h"
#include "limTypes.h"

tSirRetStatus limGetStaHashBssidx(tpAniSirGlobal pMac, tANI_U16 assocId, tANI_U8 *bssidx,tpPESession psessionEntry);

#endif