text:
/*******************************************************************************
* Author: Richard Brundritt
* Website: http://rbrundritt.wordpress.com
* Date: December 4th, 2011
*
* Description:
* A point based Client Side Clustering Algorithm. This algorithm takes the first
* pushpin in the collection and groups all nearby locations in it. It then takes
* the next, ungrouped location and does the same.
********************************************************************************/

/* ClusteredEntityCollection object */
var PointBasedClusteredEntityCollection = function (map, options) {
    /* Private Properties */
    var _map = map,
        _layer,
        _zoomLevel = 1,
        _tileZoomRatio = 0,
        _data = [],
        _clusters = [21],
        _maxClusterZoom = 21; //Maximium zoom level to cluster at. Clustering will not occur past this zoom level

    /* Constants used to speed up calculations*/
    var PiBy180 = (Math.PI / 180),
        OneBy4PI = 1 / (4 * Math.PI);

    var _options = {
        //The size of the grid cells for clustering in pixels
        clusterRadius: 30,

        //Default functionality to create a single pushpin
        singlePinCallback: function (data, clusterInfo) {
            return new Microsoft.Maps.Pushpin(clusterInfo.center);
        },

        //Default function to generate clustered pushpin
        clusteredPinCallback: function (clusterInfo) {
            var pin = new Microsoft.Maps.Pushpin(clusterInfo.center, { text: '+' });
            pin.description = clusterInfo.dataIndices.length + " locations<br/>Zoom in for more details.";
            return pin;
        },

        //Callback function that gets fired after clustering has been completed.
        callback: null
    };

    /* Private Methods */

    function _init() {
        //Create an instance of an EntityCollection
        _layer = new Microsoft.Maps.EntityCollection();
        _map.entities.push(_layer);

        //Reset stored cluster information
        for (var i = 0; i < 21; i++) {
            _clusters[i] = null;
        }

        setOptions(options);
        Microsoft.Maps.Events.addThrottledHandler(_map, 'viewchangeend', function () {
            var z = _map.getZoom();
            _tileZoomRatio = 256 * Math.pow(2, z);

            if (z != _zoomLevel) {
                _zoomLevel = z;

                if(_zoomLevel <= _maxClusterZoom)
                {
                    //Recluster
                    cluster();
                }
            }

            //Rerender
            render();
        }, 500);
    }

    // Clusters the data for the current zoom level
    function cluster() {
        //remove all pins from the layer
        _layer.clear();

        var c = _clusters[_zoomLevel];

        if (c == null || c.length == 0) {

            //Initialize cluster array for current zoom level
            c = [], clusterCount = 0;

            if (_data != null) {
                var i = _data.length - 1, j, pixel, cData;

                //Itirate through the data
                if (i >= 0) {
                    do {
                        pixel = globalPixel(_data[i]._LatLong);

                        j = clusterCount - 1;

                        if (j >= 0) {
                            //See if pixel fits into any existing clusters
                            do {
                                if (pixel.y >= c[j].top && pixel.y <= c[j].bottom &&
                                    ((c[j].left <= c[j].right && pixel.x >= c[j].left && pixel.x <= c[j].right) ||
                                    (c[j].left >= c[j].right && (pixel.x >= c[j].left || pixel.x <= c[j].right)))) {

                                    c[j].dataIndices.push(i);
                                    _data[i]._clusterIndex = j;
                                    break;
                                }
                            }
                            while (j--);

                            //If j = 0 then pixel does not fit in existing cluster
                            if (j == -1) {
                                //Create new cluster
                                cData = {
                                    index: clusterCount,
                                    dataIndices: [],
                                    center: _data[i]._LatLong,
                                    left: pixel.x - _options.clusterRadius,
                                    right: pixel.x + _options.clusterRadius,
                                    top: pixel.y - _options.clusterRadius,
                                    bottom: pixel.y + _options.clusterRadius,
                                    zoom: _zoomLevel
                                };

                                cData.dataIndices.push(i);

                                if (cData.left < 0) {
                                    cData.left += _tileZoomRatio;
                                }

                                if (cData.right > _tileZoomRatio) {
                                    cData.right -= _tileZoomRatio;
                                }

                                _data[i]._clusterIndex = clusterCount;

                                c.push(cData);
                                clusterCount++;
                            }

                        } else {
                            //Create new cluster
                            cData = {
                                index: clusterCount,
                                dataIndices: [],
                                center: _data[i]._LatLong,
                                left: pixel.x - _options.clusterRadius,
                                right: pixel.x + _options.clusterRadius,
                                top: pixel.y - _options.clusterRadius,
                                bottom: pixel.y + _options.clusterRadius,
                                zoom: _zoomLevel
                            };

                            cData.dataIndices.push(i);

                            if (cData.left < 0) {
                                cData.left += _tileZoomRatio;
                            }

                            if (cData.right > _tileZoomRatio) {
                                cData.right -= _tileZoomRatio;
                            }

                            _data[i]._clusterIndex = clusterCount;

                            c.push(cData);
                            clusterCount++;
                        }
                    }
                    while (i--);
                }
            }
        }

        _clusters[_zoomLevel] = c;
    }

    function render() {
        //remove all pins from the layer
        _layer.clear();

        var bounds = _map.getBounds();

        if (_zoomLevel <= _maxClusterZoom) {
            var clusters = _clusters[_zoomLevel];

            if (clusters != null && clusters.length > 0) {
                var i = clusters.length - 1,
                pin, c;

                //Iteriates through the clusters and render those in view
                if (i >= 0) {
                    do {
                        c = clusters[i];

                        //Check that cluster is in map view
                        if (bounds.contains(clusters[i].center)) {
                            //Check to see if cluster has only one data point in it
                            if (c.dataIndices.length == 1) {
                                pin = _options.singlePinCallback(_data[c.dataIndices[0]], c);
                            }
                            else {  //generate clustered pushpin
                                pin = _options.clusteredPinCallback(c);
                            }

                            pin._clusterInfo = c;
                            _layer.push(pin);
                        }
                    }
                    while (i--);
                }
            }
        } else {
            var i = _data.length - 1,
                cData, pin;

            //Iteriates through the data and render the pushpins in view
            if (i >= 0) {
                do {
                    cData = {
                        index: i,
                        dataIndices: [],
                        center: _data[i]._LatLong,
                        left: null,
                        right: null,
                        top: null,
                        bottom: null,
                        zoom: _zoomLevel
                    };

                    cData.dataIndices.push(i);

                    //Check that data is in map view
                    if (bounds.contains(_data[i]._LatLong)) {
                        pin = _options.singlePinCallback(_data[i], cData);
                        pin._clusterInfo = cData;
                        _layer.push(pin);
                    }
                }
                while (i--);
            }
        }

        //Call users callback
        if (_options.callback) {
            _options.callback();
        }
    }

    /*
    * Calculates the global pixel coordinate for a latlong value, where a latlong value of
    * (-90, 180) will have a global pixel value of (512, 512) at zoom level 1
    */
    function globalPixel(latlong) {
        //Formulas based on following article:
        //http://msdn.microsoft.com/en-us/library/bb259689.aspx
        var sinLatitude = Math.sin(latlong.latitude * PiBy180);

        //If Latitude == 90 or -90 then Y will become infinity when Math.log is calculated
        if (sinLatitude == 1 || sinLatitude == -1) {
            sinLatitude += 0.0000000001;
        }

        var x = ((latlong.longitude + 180) / 360) * _tileZoomRatio;
        var y = (0.5 - Math.log((1 + sinLatitude) / (1 - sinLatitude)) * OneBy4PI) * _tileZoomRatio;

        return { x: Math.round(x), y: Math.round(y) };
    }

    //Updates the default options with new options
    function setOptions(options) {
        //Reset stored cluster information
        for (var i = 0; i < 21; i++) {
            _clusters[i] = null;
        }

        for (attrname in options) {
            _options[attrname] = options[attrname];
        }

        cluster();
        render();
    }

    /* Public Methods */

    //Layer Methods

    /**
    * @returns A reference to the layer being used.
    */
    this.GetLayer = function () {
        return _layer;
    };

    /**
    * @returns The clustering options.
    */
    this.GetOptions = function () {
        return _options;
    };

    /**
    * Sets the clustering options.
    * Example: clusterLayer.SetOptions({ gridSize : 30});
    */
    this.SetOptions = function (options) {
        setOptions(options);
    };

    /**
    * Sets all layer's z-index to 0 and increases the z-index of the current layer to 1.
    */
    this.BringLayerToFront = function () {
        var i = _map.entities.getLength() - 1,
            entity;

        if (i >= 0) {
            do {
                entity = _map.entities.get(i);
                if (entity.clear != null) {//Only entity collections have the clear function
                    entity.setOptions({ zIndex: 0 });
                }
            }
            while (i--);

            i = _map.entities.indexOf(_layer);
            entity = _map.entities.get(i);
            entity.setOptions({ zIndex: 1 });
        }
    };

    //Data Handlers

    /**
    * Sets the data that is to be clustered and displayed on the map. All objects
    * must at minimium have a latitude and longitude properties.
    * The algorithm will convert them to a Location object when loading in data.
    * @param {[object]} data - An array of objects that are to be mapped.
    */
    this.SetData = function (data) {
        if (data != null && data.length > 0) {
            _data = data;

            var i = _data.length - 1;

            if (i >= 0) {
                do {
                    //convert the data coordinate into a Location object and store it.
                    _data[i]._LatLong = new Microsoft.Maps.Location(_data[i].latitude, _data[i].longitude);
                } while (i--)
            }

            cluster();
            render();
        } else {
            _data = [];
            _layer.clear();
        }
    };

    /**
    * @returns The data array and returns it to the user.
    */
    this.GetData = function () {
        return _data;
    };

    /**
    * @returns All the data that is currently displayed.
    */
    this.GetDisplayedData = function () {
        var result = [];

        var i = _layer.getLength() - 1;
        if (i >= 0) {
            do {
                var pin = _layer.get(i);

                if (pin._clusterInfo != null && pin._clusterInfo.dataIndices.length > 0) {
                    for (var j = 0; j < pin._clusterInfo.dataIndices.length; j++) {
                        result.push(_data[pin._clusterInfo.dataIndices[j]]);
                    }
                }
            }
            while (i--);
        }

        return result;
    };

    /**
    * Gets data from by index
    */
    this.GetDataByIndex = function (index) {
        if (index < _data.length) {
            return _data[index];
        }

        return null;
    };

    /**
    * Gets data by Cluster Index
    */
    this.GetDataByClusterIndex = function (index) {
        var result = [], c = _clusters[_zoomLevel];

        if (c != null
            && c.length > index
            && c[index] != null
            && c[index].dataIndices != null
            && c[index].dataIndices.length > 0) {

            for (var j = 0; j < c[index].dataIndices.length; j++) {
                result.push(_data[c[index].dataIndices[j]]);
            }
        }

        return result;
    };

    /**
    * Gets the Pin by cluster Index
    */
    this.GetPinByClusterIndex = function (index) {
        var i = _layer.getLength() - 1;
        if (i >= 0) {
            do {
                var pin = _layer.get(i);

                if (pin._clusterInfo.index == index) {
                    return pin;
                }
            }
            while (i--);
        }

        return null;
    };

    //Initialize class
    _init();
};

//Call the Module Loaded method
Microsoft.Maps.moduleLoaded('PointBasedClusteringModule');


text:
from __future__ import print_function
import json
import os
import subprocess
import sys

if len(sys.argv) != 3:
    print(sys.argv[0], ' <compiler> <folder>')
    sys.exit(1)

compiler = sys.argv[1]
folder = sys.argv[2]

stats = {}

for filename in os.listdir(folder):
    basename, ext = os.path.splitext(filename)
    if ext not in ['.frag', '.spv']:
        continue
    cmdline = [compiler]
    if ext == '.spv':
        cmdline.extend(['-f', '-p'])
    cmdline.append(os.path.join(folder, filename))
    try:
        output = subprocess.check_output(cmdline)
    except subprocess.CalledProcessError:
        continue
    stats.setdefault(basename, {})
    for line in output.splitlines():
        if line.startswith('Instructions Emitted'):
            inst = line.split(':')[1].split()
            stats[basename][ext] = inst

for k, v in stats.iteritems():
    gl = v.get('.frag', ['', '', ''])
    vk = v.get('.spv', ['', '', ''])
    print('{0},{1},{2},{3},{4},{5},{6}'.format(
        k, gl[0], gl[1], gl[2], vk[0], vk[1], vk[2]))

redpajama_set_name: RedPajamaGithub


text:
%% Visualise Greenwood frequency function
s = load('spiralSplineNewgreenwoodF100.mat');
% 20 Hz to 20 kHz in numFreqLabels-1 steps
fMap = s.fMap;
% Spline for the scala media
scMediaSpline = s.scMediaSpline;

freqIndices = s.freqIndices;
% Currently 40 fibres 20 nodes. 30 frequency points is good for A_ labels.
% freqIndices = round(linspace(1,numFreqLabels,30));

for freqIndex = freqIndices
    coords = scMediaSpline(freqIndex,:);
    x = coords(1);y = coords(2); z = coords(3);
    freq = round(fMap(freqIndex));
    % Cater for the A_s to add special labels.
    As = 27.5*2.^(0:7);
    comp = abs((freq-As)./As);
    if any(comp<0.1)
        % We've got an A
        match = As(comp == min(comp));
        octave = find(comp == min(comp)) - 1;
        textStr = ['$ \bf' num2str(freq) ' Hz \left( \approx A_{' num2str(octave) '} \right) $'];
%         textStr = ['\bf \fontsize{18} '  num2str(match) ' Hz ($\approx$ A' num2str(octave) ')'];
    else
        textStr = ['\it ' num2str(freq) ' Hz'];
    end
    text(x,y,z,textStr,'Interpreter','latex')
end
plot3(scMediaSpline(:,1),scMediaSpline(:,2),scMediaSpline(:,3))


text:
CREATE TABLE movies (
  id text NOT NULL,
  title text NOT NULL,
  release_year text NOT NULL,
  directors text NOT NULL,
  rating text NOT NULL,
  votes text NOT NULL,
  genre text NOT NULL,
  runtime text NOT NULL,
  actors text NOT NULL,
  plot text NOT NULL,
  awards text,
  poster text NOT NULL,
  updated timestamp NULL DEFAULT NULL,
  added timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1


text:
<?php

namespace StingerSoft\GaugePresentationBundle\Entity;

use StingerSoft\GaugePresentationBundle\Model\Session\UserSessionInterface;
use StingerSoft\GaugePresentationBundle\Model\Session\UserSessionTrait;

abstract class UserSession implements UserSessionInterface {

	use UserSessionTrait;
}


text:
using System;
using System.Runtime;
using System.Runtime.InteropServices;

internal static partial class Interop
{
    internal unsafe partial class Sys
    {
        [RuntimeImport("SystemNative_Abort")]
        internal static extern void Abort();
    }
}


text:
extern "C"
{
#endif

#include <stddef.h>

#include "rcutils/allocator.h"

typedef struct __failing_allocator_state
{
  bool is_failing;
} __failing_allocator_state;

void *
failing_malloc(size_t size, void * state)
{
  if (((__failing_allocator_state *)state)->is_failing) {
    return nullptr;
  }
  return rcutils_get_default_allocator().allocate(size, rcutils_get_default_allocator().state);
}

void *
failing_realloc(void * pointer, size_t size, void * state)
{
  if (((__failing_allocator_state *)state)->is_failing) {
    return nullptr;
  }
  return rcutils_get_default_allocator().reallocate(
    pointer, size, rcutils_get_default_allocator().state);
}

void
failing_free(void * pointer, void * state)
{
  if (((__failing_allocator_state *)state)->is_failing) {
    return;
  }
  rcutils_get_default_allocator().deallocate(pointer, rcutils_get_default_allocator().state);
}

void *
failing_calloc(size_t number_of_elements, size_t size_of_element, void * state)
{
  if (((__failing_allocator_state *)state)->is_failing) {
    return nullptr;
  }
  return rcutils_get_default_allocator().zero_allocate(
    number_of_elements, size_of_element, rcutils_get_default_allocator().state);
}

static inline rcutils_allocator_t
get_failing_allocator(void)
{
  static __failing_allocator_state state;
  state.is_failing = true;
  auto failing_allocator = rcutils_get_default_allocator();
  failing_allocator.allocate = failing_malloc;
  failing_allocator.deallocate = failing_free;
  failing_allocator.reallocate = failing_realloc;
  failing_allocator.zero_allocate = failing_calloc;
  failing_allocator.state = &state;
  return failing_allocator;
}

static inline void
set_failing_allocator_is_failing(rcutils_allocator_t & failing_allocator, bool state)
{
  ((__failing_allocator_state *)failing_allocator.state)->is_failing = state;
}

typedef struct time_bomb_allocator_state
{
  int count_until_failure;
} time_bomb_allocator_state;

static void * time_bomb_malloc(size_t size, void * state)
{
  time_bomb_allocator_state * time_bomb_state = (time_bomb_allocator_state *)state;
  if (time_bomb_state->count_until_failure >= 0 &&
    time_bomb_state->count_until_failure-- == 0)
  {
    return nullptr;
  }
  return rcutils_get_default_allocator().allocate(size, rcutils_get_default_allocator().state);
}

static void *
time_bomb_realloc(void * pointer, size_t size, void * state)
{
  time_bomb_allocator_state * time_bomb_state = (time_bomb_allocator_state *)state;
  if (time_bomb_state->count_until_failure >= 0 &&
    time_bomb_state->count_until_failure-- == 0)
  {
    return nullptr;
  }
  return rcutils_get_default_allocator().reallocate(
    pointer, size, rcutils_get_default_allocator().state);
}

static void
time_bomb_free(void * pointer, void * state)
{
  time_bomb_allocator_state * time_bomb_state = (time_bomb_allocator_state *)state;
  if (time_bomb_state->count_until_failure >= 0 &&
    time_bomb_state->count_until_failure-- == 0)
  {
    return;
  }
  rcutils_get_default_allocator().deallocate(pointer, rcutils_get_default_allocator().state);
}

static void *
time_bomb_calloc(size_t number_of_elements, size_t size_of_element, void * state)
{
  time_bomb_allocator_state * time_bomb_state = (time_bomb_allocator_state *)state;
  if (time_bomb_state->count_until_failure >= 0 &&
    time_bomb_state->count_until_failure-- == 0)
  {
    return nullptr;
  }
  return rcutils_get_default_allocator().zero_allocate(
    number_of_elements, size_of_element, rcutils_get_default_allocator().state);
}

static inline rcutils_allocator_t
get_time_bombed_allocator(void)
{
  static time_bomb_allocator_state state;
  state.count_until_failure = 1;
  auto time_bombed_allocator = rcutils_get_default_allocator();
  time_bombed_allocator.allocate = time_bomb_malloc;
  time_bombed_allocator.deallocate = time_bomb_free;
  time_bombed_allocator.reallocate = time_bomb_realloc;
  time_bombed_allocator.zero_allocate = time_bomb_calloc;
  time_bombed_allocator.state = &state;
  return time_bombed_allocator;
}

static inline void
set_time_bombed_allocator_count(rcutils_allocator_t & time_bombed_allocator, int count)
{
  ((time_bomb_allocator_state *)time_bombed_allocator.state)->count_until_failure = count;
}

#ifdef __cplusplus
}
#endif

#endif  // RCL__ALLOCATOR_TESTING_UTILS_H_


text:
#include <fdk-aac/aacenc_lib.h>

#include "libavutil/channel_layout.h"
#include "libavutil/common.h"
#include "libavutil/opt.h"
#include "avcodec.h"
#include "audio_frame_queue.h"
#include "internal.h"

#ifdef AACENCODER_LIB_VL0
#define FDKENC_VER_AT_LEAST(vl0, vl1) \
    ((AACENCODER_LIB_VL0 > vl0) || \
     (AACENCODER_LIB_VL0 == vl0 && AACENCODER_LIB_VL1 >= vl1))
#else
#define FDKENC_VER_AT_LEAST(vl0, vl1) 0
#endif

typedef struct AACContext {
    const AVClass *class;
    HANDLE_AACENCODER handle;
    int afterburner;
    int eld_sbr;
    int eld_v2;
    int signaling;
    int latm;
    int header_period;
    int vbr;

    AudioFrameQueue afq;
} AACContext;

static const AVOption aac_enc_options[] = {
    { "afterburner", "Afterburner (improved quality)", offsetof(AACContext, afterburner), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM },
    { "eld_sbr", "Enable SBR for ELD (for SBR in other configurations, use the -profile parameter)", offsetof(AACContext, eld_sbr), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM },
#if FDKENC_VER_AT_LEAST(4, 0) // 4.0.0
    { "eld_v2", "Enable ELDv2 (LD-MPS extension for ELD stereo signals)", offsetof(AACContext, eld_v2), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM },
#endif
    { "signaling", "SBR/PS signaling style", offsetof(AACContext, signaling), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 2, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM, "signaling" },
    { "default", "Choose signaling implicitly (explicit hierarchical by default, implicit if global header is disabled)", 0, AV_OPT_TYPE_CONST, { .i64 = -1 }, 0, 0, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM, "signaling" },
    { "implicit", "Implicit backwards compatible signaling", 0, AV_OPT_TYPE_CONST, { .i64 = 0 }, 0, 0, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM, "signaling" },
    { "explicit_sbr", "Explicit SBR, implicit PS signaling", 0, AV_OPT_TYPE_CONST, { .i64 = 1 }, 0, 0, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM, "signaling" },
    { "explicit_hierarchical", "Explicit hierarchical signaling", 0, AV_OPT_TYPE_CONST, { .i64 = 2 }, 0, 0, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM, "signaling" },
    { "latm", "Output LATM/LOAS encapsulated data", offsetof(AACContext, latm), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM },
    { "header_period", "StreamMuxConfig and PCE repetition period (in frames)", offsetof(AACContext, header_period), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 0xffff, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM },
    { "vbr", "VBR mode (1-5)", offsetof(AACContext, vbr), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 5, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM },
    { NULL }
};

static const AVClass aac_enc_class = {
    .class_name = "libfdk_aac",
    .item_name  = av_default_item_name,
    .option     = aac_enc_options,
    .version    = LIBAVUTIL_VERSION_INT,
};

static const char *aac_get_error(AACENC_ERROR err)
{
    switch (err) {
    case AACENC_OK:
        return "No error";
    case AACENC_INVALID_HANDLE:
        return "Invalid handle";
    case AACENC_MEMORY_ERROR:
        return "Memory allocation error";
    case AACENC_UNSUPPORTED_PARAMETER:
        return "Unsupported parameter";
    case AACENC_INVALID_CONFIG:
        return "Invalid config";
    case AACENC_INIT_ERROR:
        return "Initialization error";
    case AACENC_INIT_AAC_ERROR:
        return "AAC library initialization error";
    case AACENC_INIT_SBR_ERROR:
        return "SBR library initialization error";
    case AACENC_INIT_TP_ERROR:
        return "Transport library initialization error";
    case AACENC_INIT_META_ERROR:
        return "Metadata library initialization error";
    case AACENC_ENCODE_ERROR:
        return "Encoding error";
    case AACENC_ENCODE_EOF:
        return "End of file";
    default:
        return "Unknown error";
    }
}

static int aac_encode_close(AVCodecContext *avctx)
{
    AACContext *s = avctx->priv_data;

    if (s->handle)
        aacEncClose(&s->handle);
    av_freep(&avctx->extradata);
    ff_af_queue_close(&s->afq);

    return 0;
}

static av_cold int aac_encode_init(AVCodecContext *avctx)
{
    AACContext *s = avctx->priv_data;
    int ret = AVERROR(EINVAL);
    AACENC_InfoStruct info = { 0 };
    CHANNEL_MODE mode;
    AACENC_ERROR err;
    int aot = FF_PROFILE_AAC_LOW + 1;
    int sce = 0, cpe = 0;

    if ((err = aacEncOpen(&s->handle, 0, avctx->channels)) != AACENC_OK) {
        av_log(avctx, AV_LOG_ERROR, "Unable to open the encoder: %s\n",
               aac_get_error(err));
        goto error;
    }

    if (avctx->profile != FF_PROFILE_UNKNOWN)
        aot = avctx->profile + 1;

    if ((err = aacEncoder_SetParam(s->handle, AACENC_AOT, aot)) != AACENC_OK) {
        av_log(avctx, AV_LOG_ERROR, "Unable to set the AOT %d: %s\n",
               aot, aac_get_error(err));
        goto error;
    }

    if (aot == FF_PROFILE_AAC_ELD + 1 && s->eld_sbr) {
        if ((err = aacEncoder_SetParam(s->handle, AACENC_SBR_MODE,
                                       1)) != AACENC_OK) {
            av_log(avctx, AV_LOG_ERROR, "Unable to enable SBR for ELD: %s\n",
                   aac_get_error(err));
            goto error;
        }
    }

    if ((err = aacEncoder_SetParam(s->handle, AACENC_SAMPLERATE,
                                   avctx->sample_rate)) != AACENC_OK) {
        av_log(avctx, AV_LOG_ERROR, "Unable to set the sample rate %d: %s\n",
               avctx->sample_rate, aac_get_error(err));
        goto error;
    }

    switch (avctx->channels) {
    case 1: mode = MODE_1;       sce = 1; cpe = 0; break;
    case 2:
#if FDKENC_VER_AT_LEAST(4, 0) // 4.0.0
      // (profile + 1) to map from profile range to AOT range
      if (aot == FF_PROFILE_AAC_ELD + 1 && s->eld_v2) {
          if ((err = aacEncoder_SetParam(s->handle, AACENC_CHANNELMODE,
                                         128)) != AACENC_OK) {
              av_log(avctx, AV_LOG_ERROR, "Unable to enable ELDv2: %s\n",
                     aac_get_error(err));
              goto error;
          } else {
            mode = MODE_212;
            sce = 1;
            cpe = 0;
          }
      } else
#endif
      {
        mode = MODE_2;
        sce = 0;
        cpe = 1;
      }
      break;
    case 3: mode = MODE_1_2;     sce = 1; cpe = 1; break;
    case 4: mode = MODE_1_2_1;   sce = 2; cpe = 1; break;
    case 5: mode = MODE_1_2_2;   sce = 1; cpe = 2; break;
    case 6: mode = MODE_1_2_2_1; sce = 2; cpe = 2; break;
/* The version macro is introduced the same time as the 7.1 support, so this
   should suffice. */
#if FDKENC_VER_AT_LEAST(3, 4) // 3.4.12
    case 8:
        sce = 2;
        cpe = 3;
        if (avctx->channel_layout == AV_CH_LAYOUT_7POINT1) {
            mode = MODE_7_1_REAR_SURROUND;
        } else {
            // MODE_1_2_2_2_1 and MODE_7_1_FRONT_CENTER use the same channel layout
            mode = MODE_7_1_FRONT_CENTER;
        }
        break;
#endif
    default:
        av_log(avctx, AV_LOG_ERROR,
               "Unsupported number of channels %d\n", avctx->channels);
        goto error;
    }

    if ((err = aacEncoder_SetParam(s->handle, AACENC_CHANNELMODE,
                                   mode)) != AACENC_OK) {
        av_log(avctx, AV_LOG_ERROR,
               "Unable to set channel mode %d: %s\n", mode, aac_get_error(err));
        goto error;
    }

    if ((err = aacEncoder_SetParam(s->handle, AACENC_CHANNELORDER,
                                   1)) != AACENC_OK) {
        av_log(avctx, AV_LOG_ERROR,
               "Unable to set wav channel order %d: %s\n",
               mode, aac_get_error(err));
        goto error;
    }

    if (avctx->flags & AV_CODEC_FLAG_QSCALE || s->vbr) {
        int mode = s->vbr ? s->vbr : avctx->global_quality;
        if (mode <  1 || mode > 5) {
            av_log(avctx, AV_LOG_WARNING,
                   "VBR quality %d out of range, should be 1-5\n", mode);
            mode = av_clip(mode, 1, 5);
        }
        av_log(avctx, AV_LOG_WARNING,
               "Note, the VBR setting is unsupported and only works with "
               "some parameter combinations\n");
        if ((err = aacEncoder_SetParam(s->handle, AACENC_BITRATEMODE,
                                       mode)) != AACENC_OK) {
            av_log(avctx, AV_LOG_ERROR, "Unable to set the VBR bitrate mode %d: %s\n",
                   mode, aac_get_error(err));
            goto error;
        }
    } else {
        if (avctx->bit_rate <= 0) {
            if (avctx->profile == FF_PROFILE_AAC_HE_V2) {
                sce = 1;
                cpe = 0;
            }
            avctx->bit_rate = (96*sce + 128*cpe) * avctx->sample_rate / 44;
            if (avctx->profile == FF_PROFILE_AAC_HE ||
                avctx->profile == FF_PROFILE_AAC_HE_V2 ||
                avctx->profile == FF_PROFILE_MPEG2_AAC_HE ||
                s->eld_sbr)
                avctx->bit_rate /= 2;
        }
        if ((err = aacEncoder_SetParam(s->handle, AACENC_BITRATE,
                                       avctx->bit_rate)) != AACENC_OK) {
            av_log(avctx, AV_LOG_ERROR, "Unable to set the bitrate %"PRId64": %s\n",
                   avctx->bit_rate, aac_get_error(err));
            goto error;
        }
    }

    /* Choose bitstream format - if global header is requested, use
     * raw access units, otherwise use ADTS. */
    if ((err = aacEncoder_SetParam(s->handle, AACENC_TRANSMUX,
                                   avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER ? TT_MP4_RAW :
                                   s->latm ? TT_MP4_LOAS : TT_MP4_ADTS)) != AACENC_OK) {
        av_log(avctx, AV_LOG_ERROR, "Unable to set the transmux format: %s\n",
               aac_get_error(err));
        goto error;
    }

    if (s->latm && s->header_period) {
        if ((err = aacEncoder_SetParam(s->handle, AACENC_HEADER_PERIOD,
                                       s->header_period)) != AACENC_OK) {
             av_log(avctx, AV_LOG_ERROR, "Unable to set header period: %s\n",
                    aac_get_error(err));
             goto error;
        }
    }

    /* If no signaling mode is chosen, use explicit hierarchical signaling
     * if using mp4 mode (raw access units, with global header) and
     * implicit signaling if using ADTS. */
    if (s->signaling < 0)
        s->signaling = avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER ? 2 : 0;

    if ((err = aacEncoder_SetParam(s->handle, AACENC_SIGNALING_MODE,
                                   s->signaling)) != AACENC_OK) {
        av_log(avctx, AV_LOG_ERROR, "Unable to set signaling mode %d: %s\n",
               s->signaling, aac_get_error(err));
        goto error;
    }

    if ((err = aacEncoder_SetParam(s->handle, AACENC_AFTERBURNER,
                                   s->afterburner)) != AACENC_OK) {
        av_log(avctx, AV_LOG_ERROR, "Unable to set afterburner to %d: %s\n",
               s->afterburner, aac_get_error(err));
        goto error;
    }

    if (avctx->cutoff > 0) {
        if (avctx->cutoff < (avctx->sample_rate + 255) >> 8 || avctx->cutoff > 20000) {
            av_log(avctx, AV_LOG_ERROR, "cutoff valid range is %d-20000\n",
                   (avctx->sample_rate + 255) >> 8);
            goto error;
        }
        if ((err = aacEncoder_SetParam(s->handle, AACENC_BANDWIDTH,
                                       avctx->cutoff)) != AACENC_OK) {
            av_log(avctx, AV_LOG_ERROR, "Unable to set the encoder bandwidth to %d: %s\n",
                   avctx->cutoff, aac_get_error(err));
            goto error;
        }
    }

    if ((err = aacEncEncode(s->handle, NULL, NULL, NULL, NULL)) != AACENC_OK) {
        av_log(avctx, AV_LOG_ERROR, "Unable to initialize the encoder: %s\n",
               aac_get_error(err));
        return AVERROR(EINVAL);
    }

    if ((err = aacEncInfo(s->handle, &info)) != AACENC_OK) {
        av_log(avctx, AV_LOG_ERROR, "Unable to get encoder info: %s\n",
               aac_get_error(err));
        goto error;
    }

    avctx->frame_size = info.frameLength;
#if FDKENC_VER_AT_LEAST(4, 0) // 4.0.0
    avctx->initial_padding = info.nDelay;
#else
    avctx->initial_padding = info.encoderDelay;
#endif
    ff_af_queue_init(avctx, &s->afq);

    if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
        avctx->extradata_size = info.confSize;
        avctx->extradata      = av_mallocz(avctx->extradata_size +
                                           AV_INPUT_BUFFER_PADDING_SIZE);
        if (!avctx->extradata) {
            ret = AVERROR(ENOMEM);
            goto error;
        }

        memcpy(avctx->extradata, info.confBuf, info.confSize);
    }
    return 0;
error:
    aac_encode_close(avctx);
    return ret;
}

static int aac_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
                            const AVFrame *frame, int *got_packet_ptr)
{
    AACContext    *s        = avctx->priv_data;
    AACENC_BufDesc in_buf   = { 0 }, out_buf = { 0 };
    AACENC_InArgs  in_args  = { 0 };
    AACENC_OutArgs out_args = { 0 };
    int in_buffer_identifier = IN_AUDIO_DATA;
    int in_buffer_size, in_buffer_element_size;
    int out_buffer_identifier = OUT_BITSTREAM_DATA;
    int out_buffer_size, out_buffer_element_size;
    void *in_ptr, *out_ptr;
    int ret;
    uint8_t dummy_buf[1];
    AACENC_ERROR err;

    /* handle end-of-stream small frame and flushing */
    if (!frame) {
        /* Must be a non-null pointer, even if it's a dummy. We could use
         * the address of anything else on the stack as well. */
        in_ptr               = dummy_buf;
        in_buffer_size       = 0;

        in_args.numInSamples = -1;
    } else {
        in_ptr               = frame->data[0];
        in_buffer_size       = 2 * avctx->channels * frame->nb_samples;

        in_args.numInSamples = avctx->channels * frame->nb_samples;

        /* add current frame to the queue */
        if ((ret = ff_af_queue_add(&s->afq, frame)) < 0)
            return ret;
    }

    in_buffer_element_size   = 2;
    in_buf.numBufs           = 1;
    in_buf.bufs              = &in_ptr;
    in_buf.bufferIdentifiers = &in_buffer_identifier;
    in_buf.bufSizes          = &in_buffer_size;
    in_buf.bufElSizes        = &in_buffer_element_size;

    /* The maximum packet size is 6144 bits aka 768 bytes per channel. */
    if ((ret = ff_alloc_packet2(avctx, avpkt, FFMAX(8192, 768 * avctx->channels), 0)) < 0)
        return ret;

    out_ptr                   = avpkt->data;
    out_buffer_size           = avpkt->size;
    out_buffer_element_size   = 1;
    out_buf.numBufs           = 1;
    out_buf.bufs              = &out_ptr;
    out_buf.bufferIdentifiers = &out_buffer_identifier;
    out_buf.bufSizes          = &out_buffer_size;
    out_buf.bufElSizes        = &out_buffer_element_size;

    if ((err = aacEncEncode(s->handle, &in_buf, &out_buf, &in_args,
                            &out_args)) != AACENC_OK) {
        if (!frame && err == AACENC_ENCODE_EOF)
            return 0;
        av_log(avctx, AV_LOG_ERROR, "Unable to encode frame: %s\n",
               aac_get_error(err));
        return AVERROR(EINVAL);
    }

    if (!out_args.numOutBytes)
        return 0;

    /* Get the next frame pts & duration */
    ff_af_queue_remove(&s->afq, avctx->frame_size, &avpkt->pts,
                       &avpkt->duration);

    avpkt->size     = out_args.numOutBytes;
    *got_packet_ptr = 1;
    return 0;
}

static const AVProfile profiles[] = {
    { FF_PROFILE_AAC_LOW,   "LC"       },
    { FF_PROFILE_AAC_HE,    "HE-AAC"   },
    { FF_PROFILE_AAC_HE_V2, "HE-AACv2" },
    { FF_PROFILE_AAC_LD,    "LD"       },
    { FF_PROFILE_AAC_ELD,   "ELD"      },
    { FF_PROFILE_UNKNOWN },
};

static const AVCodecDefault aac_encode_defaults[] = {
    { "b", "0" },
    { NULL }
};

static const uint64_t aac_channel_layout[] = {
    AV_CH_LAYOUT_MONO,
    AV_CH_LAYOUT_STEREO,
    AV_CH_LAYOUT_SURROUND,
    AV_CH_LAYOUT_4POINT0,
    AV_CH_LAYOUT_5POINT0_BACK,
    AV_CH_LAYOUT_5POINT1_BACK,
#if FDKENC_VER_AT_LEAST(3, 4) // 3.4.12
    AV_CH_LAYOUT_7POINT1_WIDE_BACK,
    AV_CH_LAYOUT_7POINT1,
#endif
    0,
};

static const int aac_sample_rates[] = {
    96000, 88200, 64000, 48000, 44100, 32000,
    24000, 22050, 16000, 12000, 11025, 8000, 0
};

AVCodec ff_libfdk_aac_encoder = {
    .name                  = "libfdk_aac",
    .long_name             = NULL_IF_CONFIG_SMALL("Fraunhofer FDK AAC"),
    .type                  = AVMEDIA_TYPE_AUDIO,
    .id                    = AV_CODEC_ID_AAC,
    .priv_data_size        = sizeof(AACContext),
    .init                  = aac_encode_init,
    .encode2               = aac_encode_frame,
    .close                 = aac_encode_close,
    .capabilities          = AV_CODEC_CAP_SMALL_LAST_FRAME | AV_CODEC_CAP_DELAY,
    .sample_fmts           = (const enum AVSampleFormat[]){ AV_SAMPLE_FMT_S16,
                                                            AV_SAMPLE_FMT_NONE },
    .priv_class            = &aac_enc_class,
    .defaults              = aac_encode_defaults,
    .profiles              = profiles,
    .supported_samplerates = aac_sample_rates,
    .channel_layouts       = aac_channel_layout,
    .wrapper_name          = "libfdk",
};


text:
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Diagnostics.Tracing;
using System.Linq;
using System.Net.Test.Common;
using System.Reflection;
using System.Threading;

using Xunit;

namespace System.Net.Http.Functional.Tests
{
    public class DiagnosticsTest : RemoteExecutorTestBase
    {
        // Diagnostic tests are each invoked in their own process as they enable/disable
        // process-wide EventSource-based tracing, and other tests in the same process
        // could interfere with the tests, as well as the enabling of tracing interfering
        // with those tests.

        /// <remarks>
        /// This test must be in the same test collection as any others testing HttpClient/WinHttpHandler
        /// DiagnosticSources, since the global logging mechanism makes them conflict inherently.
        /// </remarks>
        [Fact]
        public void SendAsync_ExpectedDiagnosticSourceLogging()
        {
            RemoteInvoke(() =>
            {
                bool requestLogged = false;
                Guid requestGuid = Guid.Empty;
                bool responseLogged = false;
                Guid responseGuid = Guid.Empty;

                var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
                {
                    if (kvp.Key.Equals("System.Net.Http.Request"))
                    {
                        Assert.NotNull(kvp.Value);
                        GetPropertyValueFromAnonymousTypeInstance<HttpRequestMessage>(kvp.Value, "Request");
                        requestGuid = GetPropertyValueFromAnonymousTypeInstance<Guid>(kvp.Value, "LoggingRequestId");

                        requestLogged = true;
                    }
                    else if (kvp.Key.Equals("System.Net.Http.Response"))
                    {
                        Assert.NotNull(kvp.Value);

                        GetPropertyValueFromAnonymousTypeInstance<HttpResponseMessage>(kvp.Value, "Response");
                        responseGuid = GetPropertyValueFromAnonymousTypeInstance<Guid>(kvp.Value, "LoggingRequestId");

                        responseLogged = true;
                    }
                });

                using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
                {
                    diagnosticListenerObserver.Enable();
                    using (var client = new HttpClient())
                    {
                        var response = client.GetAsync(Configuration.Http.RemoteEchoServer).Result;
                    }

                    Assert.True(requestLogged, "Request was not logged.");
                    // Poll with a timeout since logging response is not synchronized with returning a response.
                    WaitForTrue(() => responseLogged, TimeSpan.FromSeconds(1), "Response was not logged within 1 second timeout.");
                    Assert.Equal(requestGuid, responseGuid);
                    diagnosticListenerObserver.Disable();
                }

                return SuccessExitCode;
            }).Dispose();
        }

        /// <remarks>
        /// This test must be in the same test collection as any others testing HttpClient/WinHttpHandler
        /// DiagnosticSources, since the global logging mechanism makes them conflict inherently.
        /// </remarks>
        [Fact]
        public void SendAsync_ExpectedDiagnosticSourceNoLogging()
        {
            RemoteInvoke(() =>
            {
                bool requestLogged = false;
                bool responseLogged = false;

                var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
                {
                    if (kvp.Key.Equals("System.Net.Http.Request"))
                    {
                        requestLogged = true;
                    }
                    else if (kvp.Key.Equals("System.Net.Http.Response"))
                    {
                        responseLogged = true;
                    }
                });

                using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
                {
                    using (var client = new HttpClient())
                    {
                        var response = client.GetAsync(Configuration.Http.RemoteEchoServer).Result;
                    }

                    Assert.False(requestLogged, "Request was logged while logging disabled.");
                    WaitForFalse(() => responseLogged, TimeSpan.FromSeconds(1), "Response was logged while logging disabled.");
                }
                return SuccessExitCode;
            }).Dispose();
        }

        [Fact]
        public void SendAsync_HttpTracingEnabled_Succeeds()
        {
            RemoteInvoke(async () =>
            {
                using (var listener = new TestEventListener("Microsoft-System-Net-Http", EventLevel.Verbose))
                {
                    var events = new ConcurrentQueue<EventWrittenEventArgs>();
                    await listener.RunWithCallbackAsync(events.Enqueue, async () =>
                    {
                        // Exercise various code paths to get coverage of tracing
                        using (var client = new HttpClient())
                        {
                            // Do a get to a loopback server
                            await LoopbackServer.CreateServerAsync(async (server, url) =>
                            {
                                await TestHelper.WhenAllCompletedOrAnyFailed(
                                    LoopbackServer.ReadRequestAndSendResponseAsync(server),
                                    client.GetAsync(url));
                            });

                            // Do a post to a remote server
                            byte[] expectedData = Enumerable.Range(0, 20000).Select(i => (byte)i).ToArray();
                            HttpContent content = new ByteArrayContent(expectedData);
                            content.Headers.ContentMD5 = TestHelper.ComputeMD5Hash(expectedData);
                            using (HttpResponseMessage response = await client.PostAsync(Configuration.Http.RemoteEchoServer, content))
                            {
                                Assert.Equal(HttpStatusCode.OK, response.StatusCode);
                            }
                        }
                    });

                    // We don't validate receiving specific events, but rather that we do at least
                    // receive some events, and that enabling tracing doesn't cause other failures
                    // in processing.
                    Assert.InRange(events.Count, 1, int.MaxValue);
                }

                return SuccessExitCode;
            }).Dispose();
        }

        private static T GetPropertyValueFromAnonymousTypeInstance<T>(object obj, string propertyName)
        {
            Type t = obj.GetType();

            PropertyInfo p = t.GetRuntimeProperty(propertyName);

            object propertyValue = p.GetValue(obj);
            Assert.NotNull(propertyValue);
            Assert.IsAssignableFrom<T>(propertyValue);

            return (T)propertyValue;
        }

        private static void WaitForTrue(Func<bool> p, TimeSpan timeout, string message)
        {
            // Assert that spin doesn't time out.
            Assert.True(SpinWait.SpinUntil(p, timeout), message);
        }

        private static void WaitForFalse(Func<bool> p, TimeSpan timeout, string message)
        {
            // Assert that spin times out.
            Assert.False(SpinWait.SpinUntil(p, timeout), message);
        }
    }
}


text:
package org.apache.hyracks.control.cc.web;

import java.net.URI;
import java.net.URISyntaxException;

import org.apache.hyracks.control.cc.ClusterControllerService;
import org.apache.hyracks.control.cc.web.util.IJSONOutputFunction;
import org.apache.hyracks.control.cc.web.util.JSONOutputRequestUtil;
import org.apache.hyracks.control.cc.work.GetNodeDetailsJSONWork;
import org.apache.hyracks.control.cc.work.GetNodeSummariesJSONWork;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

public class NodesRESTAPIFunction implements IJSONOutputFunction {
    private ClusterControllerService ccs;

    public NodesRESTAPIFunction(ClusterControllerService ccs) {
        this.ccs = ccs;
    }

    @Override
    public ObjectNode invoke(String host, String servletPath, String[] arguments) throws Exception {
        ObjectMapper om = new ObjectMapper();
        ObjectNode result = om.createObjectNode();
        switch (arguments.length) {
            case 1: {
                if ("".equals(arguments[0])) {
                    GetNodeSummariesJSONWork gnse = new GetNodeSummariesJSONWork(ccs.getNodeManager());
                    ccs.getWorkQueue().scheduleAndSync(gnse);
                    result.set("result", enhanceSummaries(gnse.getSummaries(), host, servletPath));
                } else {
                    String nodeId = arguments[0];
                    GetNodeDetailsJSONWork gnde =
                            new GetNodeDetailsJSONWork(ccs.getNodeManager(), ccs.getCCConfig(), nodeId, true, true);
                    ccs.getWorkQueue().scheduleAndSync(gnde);
                    result.set("result", gnde.getDetail());
                }
            }
        }
        return result;
    }

    private static ArrayNode enhanceSummaries(final ArrayNode summaries, String host, String servletPath)
            throws URISyntaxException {
        for (int i = 0; i < summaries.size(); ++i) {
            ObjectNode node = (ObjectNode) summaries.get(i);
            URI detailsUri = JSONOutputRequestUtil.uri(host, servletPath, node.get("node-id").asText());
            node.put("details", detailsUri.toString());
        }
        return summaries;
    }
}


text:
This Docker image is using the base `tobilg/mesos` image, which is a build of the lastest Mesos version available in the [Mesos Git repository](https://github.com/apache/mesos).
Currently, the latest version is 0.25.0.

## Configuration

Mesos allows you to set all [configuration
options](http://mesos.apache.org/documentation/latest/configuration/) via
environment variables.  That means that you don't need any additional scripts to
start up a Mesos master node using this Docker image; just pass in `-e` options
to set each configuration option:

    $ docker run -d \
        --name mesos_master \
        -e MESOS_LOG_DIR=/var/log/mesos/master \
        -e MESOS_WORK_DIR=/var/lib/mesos/master \
        -e MESOS_ZK=[zookeeper URL] \
        -p 5050:5050 \
        tobilg/mesos-master

Also note the `-p` option, which exposes the default Mesos master TCP port
(5050) on the container host.

### Clustering

If you want to run multiple Mesos masters, then you have to additionally specify the quorum size. The size can be calculated as `quorum > (number of masters)/2`, e.g.

    -e MESOS_QUORUM=2

if you have 3 master nodes. Also, you should add a cluster name:

    -e MESOS_CLUSTER=[Your cluster name]

### Networking

If you want your Mesos master to be accessible via the Docker host ip, then you should run it with the following options (on Debian/Ubuntu etc. based hosts):

    $ docker run -d \
        --name mesos_master \
        --net=host \
        -e MESOS_IP=$(/usr/bin/ip -o -4 addr list eth0 | grep global | awk '{print $4}' | cut -d -f1) \
        -e MESOS_LOG_DIR=/var/log \
        -e MESOS_WORK_DIR=/var/lib/mesos/master \
        -e MESOS_ZK=[zookeeper URL] \
        -p 5050:5050 \
        tobilg/mesos-master

Be sure to replace `eth0` with the actual interface your host is using for external access. For RedHat/CentOS/Fedora-based hosts' the `MESOS_IP` line needs to replaced with

    -e MESOS_IP=$(/sbin/ifconfig eth0 | grep 'inet ' | awk '{print $2}') \


text:
import React, { PureComponent } from "react";
import PropTypes from "prop-types";
import { graphql, compose, withApollo } from "react-apollo";
//Components
import {
  SubTitle,
  Input,
  Button,
  Text,
  Link,
  Header
} from "../../../components/atoms";
import { Confirmation, Card } from "../../../components/molecules";
import { Layout } from "../../../components/organisms";
//hocs
import { withUser } from "../../../hocs";
//Utils
import { _logout } from "../../../services/utilities";
import { formatUsername } from "@vacom/vantage";
import LogRocket from "logrocket";
import { withAlert } from "react-alert";
//API
import { USERNAME_VALIDATION_QUERY } from "../../../api/Queries";
import { UPDATE_USER_MUTATION } from "../../../api/Mutations";
//locales
import { FormattedMessage, injectIntl } from "react-intl";
import { globals as messages } from "../../../locales/api";
export class Profile extends PureComponent {
  static propTypes = {
    updateUser: PropTypes.func.isRequired,
    client: PropTypes.object.isRequired,
    intl: PropTypes.object.isRequired,
    user: PropTypes.object.isRequired
  };
  state = {
    username: "",
    error: false,
    errorMsg: "",
    timeoutUserName: 0,
    onConfirmation: false
  };
  _showConfirmation = () => {
    this.setState(prevState => ({
      onConfirmation: !prevState.onConfirmation
    }));
    LogRocket.track("Opened  modal on change username");
  };
  _updateProfile = async () => {
    const { intl, user, updateUser, alert } = this.props;
    const { error } = this.state;
    let username = formatUsername(this.state.username);
    //hides the confirmation modal
    this.setState(prevState => ({
      onConfirmation: !prevState.onConfirmation
    }));
    //checks is the username is the same as the previous one
    if (this._isTheSameUsername(username)) return;
    //Verifies if the inputs are empty or not
    if (username) {
      if (error) {
        return;
      }
      const userId = user.state.profile.id;
      //updates the user username and some else info in the DB
      try {
        await updateUser({
          variables: {
            userId,
            username
          }
        });
        //Shows feedback and updates the localStorage
        this.setState({ username });
        user.changeUsername(username);
        alert.success("Change made successfully");
        LogRocket.info("Change made successfully");
        LogRocket.track("Updated username");
      } catch (e) {
        LogRocket.error({ _updateProfile: e });
        alert.error(intl.formatMessage(messages.GraphicErrorDescription));
      }
    } else {
      LogRocket.warn(
        "This form is feeling lonely, needs affection, needs data."
      );
      this.setState({
        error: true,
        errorMsg: intl.formatMessage(messages.ErrorFormEmpty)
      });
    }
  };
  _onUsernameValidation(getUsername) {
    clearTimeout(this.state.timeoutUserName);
    const { intl } = this.props;
    this.setState({
      timeoutUserName: setTimeout(() => {
        //checks is the username is the same as the previous one
        let username = formatUsername(getUsername);
        if (this._isTheSameUsername(username)) return;
        this.props.client
          .query({
            query: USERNAME_VALIDATION_QUERY,
            variables: { username }
          })
          .then(res => {
            if (Object.keys(res.data.allUsers).length !== 0) {
              LogRocket.warn(
                "With so much name in this world, you had to choose this one. Try another."
              );
              this.setState({
                error: true,
                errorMsg: intl.formatMessage(
                  messages.UserCreateFormUsernameError
                )
              });
            } else {
              this.setState({ error: false });
            }
          })
          .catch(e => {
            LogRocket.error({ _onUsernameValidation: e });
          });
      }, 500)
    });
  }
  _isTheSameUsername(username) {
    const { user, intl } = this.props;
    if (user.state.userName === username) {
      LogRocket.warn(
        "If it's the same as before, what's the point of changing?"
      );
      this.setState({
        error: true,
        errorMsg: intl.formatMessage(messages.ErrorFormSame)
      });
      return true;
    }
  }
  render() {
    const { error, errorMsg, onConfirmation } = this.state;
    const { intl, user } = this.props;
    const { userName, formsesMeta } = user.state;
    return (
      <Layout>
        <Confirmation
          title={intl.formatMessage(messages.ModalProfileChangeTitle)}
          description={intl.formatMessage(
            messages.ModalProfileChangeDescription
          )}
          show={onConfirmation}
          onConfirmationText={intl.formatMessage(
            messages.ModalProfileChangeActionTextPrimary
          )}
          onCancelText={intl.formatMessage(
            messages.ModalProfileChangeActionTextCancel
          )}
          onCancel={this._showConfirmation}
          onConfirmation={this._updateProfile}
          actionProps={{ primary: true }}
        />

            {`Hey, ${this.state.username || userName}`}

            <form>
              <div className={`form-group ${error ? "has-danger" : ""}`}>
                <Text highlight>
                  <FormattedMessage
                    id="user.account.create.text.username"
                    defaultMessage={"Username"}
                  />
                </Text>
                <Input
                  placeholder={intl.formatMessage(
                    messages.UserCreateTextUsername
                  )}
                  defaultValue={userName}
                  onKeyUp={e => this._onUsernameValidation(e.target.value)}
                  onChange={e =>
                    this.setState({ username: e.target.value, error: false })
                  }
                  className={`form-control ${error && "is-invalid"}`}
                />
                {error ? <Text color="red">{errorMsg}</Text> : ""}

              <Button
                onClick={this._showConfirmation}
                className="btn btn-lg btn-primary btn-block"
                primary
              >
                <FormattedMessage
                  id="app.page.profile.action.update"
                  defaultMessage={"Update profile"}
                />
              </Button>
            </form>

            <Card style={{ marginTop: 10 }}>

                <Text highlight>
                  <FormattedMessage
                    id="app.page.profile.text.statistics"
                    defaultMessage={"Statistics"}
                  />
                </Text>
                <Text>
                  <FormattedMessage
                    id="app.page.profile.text.statistics.description"
                    defaultMessage={
                      "We are great analysts, here you have your statistics of your forms."
                    }
                  />
                </Text>
                <SubTitle>
                  {`${formsesMeta} `}
                  <FormattedMessage
                    id="app.page.profile.text.statistics.forms.count"
                    defaultMessage={"forms created"}
                  />
                </SubTitle>

            </Card>
            <Card style={{ marginTop: 10 }}>

                <Text highlight>
                  <FormattedMessage
                    id="app.page.profile.text.plan"
                    defaultMessage={"Current Plan"}
                  />
                </Text>
                <Text>
                  <FormattedMessage
                    id="app.page.profile.text.plan.description"
                    defaultMessage={
                      "More plans soon, as the platform is in beta you have access to all features."
                    }
                  />
                </Text>
                <SubTitle>

                    <FormattedMessage
                      id="app.page.profile.text.plan.type"
                      defaultMessage={"All the features"}
                    />

                </SubTitle>

            </Card>
            <Card style={{ marginTop: 10, marginBottom: 10 }}>

                <Text highlight>
                  <FormattedMessage
                    id="app.page.profile.text.settings"
                    defaultMessage={"Settings"}
                  />
                </Text>
                <Text>
                  <FormattedMessage
                    id="app.page.profile.text.settings.description"
                    defaultMessage={
                      "This is a dangerous zone, so be careful, here you will find your settings."
                    }
                  />
                </Text>

                    <Link onClick={_logout}>
                      <FormattedMessage
                        id="app.page.profile.text.settings.action.logout"
                        defaultMessage={"Log Out"}
                      />
                    </Link>

                    <Link href="http://www.formette.com/docs" target="_blank">
                      <FormattedMessage
                        id="app.page.profile.text.settings.action.help"
                        defaultMessage={"Help"}
                      />
                    </Link>

            </Card>

      </Layout>
    );
  }
}

const profileWithData = compose(
  withUser,
  injectIntl,
  withAlert,
  graphql(UPDATE_USER_MUTATION, { name: "updateUser" })
)(Profile);

export default withApollo(profileWithData);


text:
AWS Lambda function to scan a subreddit for new submissions and notify via AWS SNS

You will need to supply the following prior to deployment:
- Reddit API client_id
- Reddit API secret_secret
- AWS region
- Tel number (support for SNS topics coming soon)
- subreddits to search through
- search string


text:
package org.sleuthkit.autopsy.keywordsearch;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.MissingResourceException;
import java.util.logging.Level;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.openide.util.NbBundle;
import org.openide.util.lookup.ServiceProvider;
import org.openide.util.lookup.ServiceProviders;
import org.sleuthkit.autopsy.casemodule.Case;
import org.sleuthkit.autopsy.casemodule.CaseMetadata;
import org.sleuthkit.autopsy.core.RuntimeProperties;
import org.sleuthkit.autopsy.coreutils.FileUtil;
import org.sleuthkit.autopsy.coreutils.Logger;
import org.sleuthkit.autopsy.appservices.AutopsyService;
import org.sleuthkit.autopsy.progress.ProgressIndicator;
import org.sleuthkit.autopsy.keywordsearchservice.KeywordSearchService;
import org.sleuthkit.autopsy.keywordsearchservice.KeywordSearchServiceException;
import org.sleuthkit.datamodel.BlackboardArtifact;
import org.sleuthkit.datamodel.TskCoreException;

/**
 * An implementation of the KeywordSearchService interface that uses Solr for
 * text indexing and search.
 */
@ServiceProviders(value = {
    @ServiceProvider(service = KeywordSearchService.class)
    ,
    @ServiceProvider(service = AutopsyService.class)}
)
public class SolrSearchService implements KeywordSearchService, AutopsyService {

    private static final String BAD_IP_ADDRESS_FORMAT = "ioexception occurred when talking to server"; //NON-NLS
    private static final String SERVER_REFUSED_CONNECTION = "server refused connection"; //NON-NLS
    private static final int IS_REACHABLE_TIMEOUT_MS = 1000;
    private static final Logger logger = Logger.getLogger(SolrSearchService.class.getName());

    /**
     * Adds an artifact to the keyword search text index as a concantenation of
     * all of its attributes.
     *
     * @param artifact The artifact to index.
     *
     * @throws org.sleuthkit.datamodel.TskCoreException
     */
    @Override
    public void indexArtifact(BlackboardArtifact artifact) throws TskCoreException {
        if (artifact == null) {
            return;
        }

        // We only support artifact indexing for Autopsy versions that use
        // the negative range for artifact ids.
        if (artifact.getArtifactID() > 0) {
            return;
        }
        final Ingester ingester = Ingester.getDefault();

        try {
            ingester.indexMetaDataOnly(artifact);
            ingester.indexText(new ArtifactTextExtractor(), artifact, null);
        } catch (Ingester.IngesterException ex) {
            throw new TskCoreException(ex.getCause().getMessage(), ex);
        }
    }

    /**
     * Tries to connect to the keyword search service.
     *
     * @param host The hostname or IP address of the service.
     * @param port The port used by the service.
     *
     * @throws KeywordSearchServiceException if cannot connect.
     */
    @Override
    public void tryConnect(String host, int port) throws KeywordSearchServiceException {
        HttpSolrServer solrServer = null;
        if (host == null || host.isEmpty()) {
            throw new KeywordSearchServiceException(NbBundle.getMessage(SolrSearchService.class, "SolrConnectionCheck.MissingHostname")); //NON-NLS
        }
        try {
            solrServer = new HttpSolrServer("http://" + host + ":" + Integer.toString(port) + "/solr"); //NON-NLS
            KeywordSearch.getServer().connectToSolrServer(solrServer);
        } catch (SolrServerException ex) {
            throw new KeywordSearchServiceException(NbBundle.getMessage(SolrSearchService.class, "SolrConnectionCheck.HostnameOrPort")); //NON-NLS
        } catch (IOException ex) {
            String result = NbBundle.getMessage(SolrSearchService.class, "SolrConnectionCheck.HostnameOrPort"); //NON-NLS
            String message = ex.getCause().getMessage().toLowerCase();
            if (message.startsWith(SERVER_REFUSED_CONNECTION)) {
                try {
                    if (InetAddress.getByName(host).isReachable(IS_REACHABLE_TIMEOUT_MS)) {
                        // if we can reach the host, then it's probably port problem
                        result = Bundle.SolrConnectionCheck_Port();
                    } else {
                        result = NbBundle.getMessage(SolrSearchService.class, "SolrConnectionCheck.HostnameOrPort"); //NON-NLS
                    }
                } catch (IOException | MissingResourceException any) {
                    // it may be anything
                    result = NbBundle.getMessage(SolrSearchService.class, "SolrConnectionCheck.HostnameOrPort"); //NON-NLS
                }
            } else if (message.startsWith(BAD_IP_ADDRESS_FORMAT)) {
                result = NbBundle.getMessage(SolrSearchService.class, "SolrConnectionCheck.Hostname"); //NON-NLS
            }
            throw new KeywordSearchServiceException(result);
        } catch (NumberFormatException ex) {
            throw new KeywordSearchServiceException(Bundle.SolrConnectionCheck_Port());
        } catch (IllegalArgumentException ex) {
            throw new KeywordSearchServiceException(ex.getMessage());
        } finally {
            if (null != solrServer) {
                solrServer.shutdown();
            }
        }
    }

    /**
     * Deletes Solr core for a case.
     *
     * @param metadata The CaseMetadata which will have its core deleted.
     */
    @NbBundle.Messages({
        "# {0} - case directory", "SolrSearchService.exceptionMessage.noIndexMetadata=Unable to create IndexMetaData from case directory: {0}",
        "SolrSearchService.exceptionMessage.noCurrentSolrCore=IndexMetadata did not contain a current Solr core so could not delete the case",
        "# {0} - index folder path", "SolrSearchService.exceptionMessage.failedToDeleteIndexFiles=Failed to delete text index files at {0}"
    })
    @Override
    public void deleteTextIndex(CaseMetadata metadata) throws KeywordSearchServiceException {
        String caseDirectory = metadata.getCaseDirectory();
        IndexMetadata indexMetadata;
        try {
            indexMetadata = new IndexMetadata(caseDirectory);
        } catch (IndexMetadata.TextIndexMetadataException ex) {
            logger.log(Level.WARNING, NbBundle.getMessage(SolrSearchService.class, "SolrSearchService.exceptionMessage.noIndexMetadata", caseDirectory), ex);
            throw new KeywordSearchServiceException(NbBundle.getMessage(SolrSearchService.class, "SolrSearchService.exceptionMessage.noIndexMetadata", caseDirectory), ex);
        }
        //find the index for the current version of solr (the one we are connected to) and delete its core using the index name
        String currentSchema = IndexFinder.getCurrentSchemaVersion();
        String currentSolr = IndexFinder.getCurrentSolrVersion();
        for (Index index : indexMetadata.getIndexes()) {
            if (index.getSolrVersion().equals(currentSolr) && index.getSchemaVersion().equals(currentSchema)) {
                /*
                 * Unload/delete the core on the server and then delete the text
                 * index files.
                 */
                KeywordSearch.getServer().deleteCore(index.getIndexName(), metadata.getCaseType());
                if (!FileUtil.deleteDir(new File(index.getIndexPath()).getParentFile())) {
                    throw new KeywordSearchServiceException(Bundle.SolrSearchService_exceptionMessage_failedToDeleteIndexFiles(index.getIndexPath()));
                }
            }
            return; //only one core exists for each combination of solr and schema version
        }

        //this code this code will only execute if an index for the current core was not found
        logger.log(Level.WARNING, NbBundle.getMessage(SolrSearchService.class,
                 "SolrSearchService.exceptionMessage.noCurrentSolrCore"));
        throw new KeywordSearchServiceException(NbBundle.getMessage(SolrSearchService.class,
                 "SolrSearchService.exceptionMessage.noCurrentSolrCore"));
    }

    @Override
    public void close() throws IOException {
    }

    @Override
    public String getServiceName() {
        return NbBundle.getMessage(this.getClass(), "SolrSearchService.ServiceName");
    }

    /**
     * Creates/opens the Solr core/text index for a case
     *
     * @param context The case context.
     *
     * @throws
     * org.sleuthkit.autopsy.framework.AutopsyService.AutopsyServiceException
     */
    @Override
    @NbBundle.Messages({
        "SolrSearch.lookingForMetadata.msg=Looking for text index metadata file",
        "SolrSearch.readingIndexes.msg=Reading text index metadata file",
        "SolrSearch.findingIndexes.msg=Looking for existing text index directories",
        "SolrSearch.creatingNewIndex.msg=Creating new text index",
        "SolrSearch.checkingForLatestIndex.msg=Looking for text index with latest Solr and schema version",
        "SolrSearch.indentifyingIndex.msg=Identifying text index to use",
        "SolrSearch.openCore.msg=Opening text index",
        "SolrSearch.complete.msg=Text index successfully opened"})
    public void openCaseResources(CaseContext context) throws AutopsyServiceException {
        if (context.cancelRequested()) {
            return;
        }

        ProgressIndicator progress = context.getProgressIndicator();
        int totalNumProgressUnits = 7;
        int progressUnitsCompleted = 0;

        String caseDirPath = context.getCase().getCaseDirectory();
        Case theCase = context.getCase();
        List<Index> indexes = new ArrayList<>();
        progress.start(Bundle.SolrSearch_lookingForMetadata_msg(), totalNumProgressUnits);
        if (IndexMetadata.isMetadataFilePresent(caseDirPath)) {
            try {
                // metadata file exists, get list of existing Solr cores for this case
                progressUnitsCompleted++;
                progress.progress(Bundle.SolrSearch_findingIndexes_msg(), progressUnitsCompleted);
                IndexMetadata indexMetadata = new IndexMetadata(caseDirPath);
                indexes = indexMetadata.getIndexes();
            } catch (IndexMetadata.TextIndexMetadataException ex) {
                logger.log(Level.SEVERE, String.format("Unable to read text index metadata file"), ex);
                throw new AutopsyServiceException("Unable to read text index metadata file", ex);
            }
        } else {
            // metadata file doesn't exist.
            // do case subdirectory search to look for Solr 4 Schema 1.8 indexes
            progressUnitsCompleted++;
            progress.progress(Bundle.SolrSearch_findingIndexes_msg(), progressUnitsCompleted);
            Index oldIndex = IndexFinder.findOldIndexDir(theCase);
            if (oldIndex != null) {
                // add index to the list of indexes that exist for this case
                indexes.add(oldIndex);
            }
        }

        if (context.cancelRequested()) {
            return;
        }

        // check if we found any existing indexes
        Index currentVersionIndex = null;
        if (indexes.isEmpty()) {
            // new case that doesn't have an existing index. create new index folder
            progressUnitsCompleted++;
            progress.progress(Bundle.SolrSearch_creatingNewIndex_msg(), progressUnitsCompleted);
            currentVersionIndex = IndexFinder.createLatestVersionIndexDir(theCase);
            // add current index to the list of indexes that exist for this case
            indexes.add(currentVersionIndex);
        } else {
            // check if one of the existing indexes is for latest Solr version and schema
            progressUnitsCompleted++;
            progress.progress(Bundle.SolrSearch_checkingForLatestIndex_msg(), progressUnitsCompleted);
            currentVersionIndex = IndexFinder.findLatestVersionIndexDir(indexes);
            if (currentVersionIndex == null) {
                // found existing index(es) but none were for latest Solr version and schema version
                progressUnitsCompleted++;
                progress.progress(Bundle.SolrSearch_indentifyingIndex_msg(), progressUnitsCompleted);
                Index indexToUse = IndexFinder.identifyIndexToUse(indexes);
                if (indexToUse == null) {
                    // unable to find index that can be used
                    throw new AutopsyServiceException("Unable to find index that can be used for this case");
                }

                if (context.cancelRequested()) {
                    return;
                }

                double currentSolrVersion = NumberUtils.toDouble(IndexFinder.getCurrentSolrVersion());
                double indexSolrVersion = NumberUtils.toDouble(indexToUse.getSolrVersion());
                if (indexSolrVersion == currentSolrVersion) {
                    // latest Solr version but not latest schema. index should be used in read-only mode
                    if (RuntimeProperties.runningWithGUI()) {
                        // pop up a message box to indicate the read-only restrictions.
                        JOptionPane optionPane = new JOptionPane(
                                NbBundle.getMessage(this.getClass(), "SolrSearchService.IndexReadOnlyDialog.msg"),
                                JOptionPane.WARNING_MESSAGE,
                                JOptionPane.DEFAULT_OPTION);
                        try {
                            SwingUtilities.invokeAndWait(() -> {
                                JDialog dialog = optionPane.createDialog(NbBundle.getMessage(this.getClass(), "SolrSearchService.IndexReadOnlyDialog.title"));
                                dialog.setVisible(true);
                            });
                        } catch (InterruptedException ex) {
                            // Cancelled
                            return;
                        } catch (InvocationTargetException ex) {
                            throw new AutopsyServiceException("Error displaying limited search features warning dialog", ex);
                        }
                    }
                    // proceed with case open
                    currentVersionIndex = indexToUse;
                } else {
                    // index needs to be upgraded to latest supported version of Solr
                    throw new AutopsyServiceException("Unable to find index to use for Case open");
                }
            }
        }

        try {
            // update text index metadata file
            if (!indexes.isEmpty()) {
                IndexMetadata indexMetadata = new IndexMetadata(caseDirPath, indexes);
            }
        } catch (IndexMetadata.TextIndexMetadataException ex) {
            throw new AutopsyServiceException("Failed to save Solr core info in text index metadata file", ex);
        }

        // open core
        try {
            progress.progress(Bundle.SolrSearch_openCore_msg(), totalNumProgressUnits - 1);
            KeywordSearch.getServer().openCoreForCase(theCase, currentVersionIndex);
        } catch (KeywordSearchModuleException ex) {
            throw new AutopsyServiceException(String.format("Failed to open or create core for %s", caseDirPath), ex);
        }

        progress.progress(Bundle.SolrSearch_complete_msg(), totalNumProgressUnits);
    }

    /**
     *
     * @param context
     *
     * @throws
     * org.sleuthkit.autopsy.framework.AutopsyService.AutopsyServiceException
     */
    @Override
    public void closeCaseResources(CaseContext context) throws AutopsyServiceException {
        /*
         * TODO (JIRA 2525): The following code KeywordSearch.CaseChangeListener
         * gambles that any BlackboardResultWriters (SwingWorkers) will complete
         * in less than roughly two seconds. This stuff should be reworked using
         * an ExecutorService and tasks with Futures.
         */
        KeywordSearchResultFactory.BlackboardResultWriter.stopAllWriters();
        try {
            Thread.sleep(2000);
        } catch (InterruptedException ex) {
            logger.log(Level.SEVERE, "Unexpected interrupt while waiting for BlackboardResultWriters to terminate", ex);
        }

        try {
            KeywordSearch.getServer().closeCore();
        } catch (KeywordSearchModuleException ex) {
            throw new AutopsyServiceException(String.format("Failed to close core for %s", context.getCase().getCaseDirectory()), ex);
        }
    }
}


text:
from django.db import models

class CompanyManager(models.Manager):

    def get_for_index(self, index):
        return self.get(index=index)

class Company(models.Model):
    """
    A Paranuaran company.
    """

    # The index of the company record in the JSON source data
    index = models.PositiveIntegerField(unique=True)

    # Referred to as 'company' in the JSON source data
    company_name = models.CharField(unique=True, max_length=100)

    objects = CompanyManager()

    # A current employee isn't dead yet! ;-)
    @property
    def current_employees(self):
        return self.employees.is_alive()

    def __str__(self):
        return self.company_name

    class Meta:
        ordering = ['company_name']
        verbose_name_plural = 'Companies'

class FoodstuffQuerySet(models.QuerySet):

    def fruit(self):
        return self.filter(type=Foodstuff.FRUIT)

    def vegetables(self):
        return self.filter(type=Foodstuff.VEGETABLE)

class Foodstuff(models.Model):
    """
    A kind of food - initially either a fruit or a vegetable
    """
    FRUIT = 'f'
    VEGETABLE = 'v'

    TYPE_CHOICES = (
        (FRUIT, 'Fruit'),
        (VEGETABLE, 'Vegetable'),
    )

    name = models.CharField(unique=True, max_length=100)
    type = models.CharField(max_length=1, choices=TYPE_CHOICES)

    objects = FoodstuffQuerySet.as_manager()

    def __str__(self):
        return self.name

    class Meta:
        ordering = ['name']
        verbose_name_plural = 'Foodstuffs'

class Tag(models.Model):
    """
    A tag which can be linked to a Person
    """
    label = models.CharField(unique=True, max_length=100)

    def __str__(self):
        return self.label

    class Meta:
        ordering = ['label']
        verbose_name_plural = 'Tags'

class PersonQuerySet(models.QuerySet):

    def is_alive(self):
        return self.filter(has_died=False)

    def has_brown_eyes(self):
        return self.filter(eyecolor=Person.EYE_COLOR_BROWN)

    def has_friend(self, friend):
        return self.filter(friends=friend)

    def friend_of(self, friend):
        return self.filter(friend_of=friend)

class PersonManager(models.Manager):

    def get_for_index(self, index):
        return self.get(index=index)

    # TODO: Determine what 'friendship' actually means in this context!
    # Is a friendship define just by the 'has friend' (forward) relationship,
    # or also by the 'friend of' (reverse) relationship.
    #
    # Consider:
    #   Jack:
    #       friends: Jill, Simon
    #
    #   Jill:
    #       friends: Jack, Simon
    #
    #   Simon:
    #       friends: (none)
    #
    #   Susan:
    #       friends: Jack
    #
    # There are a range of reasonable answers to the question "who are Jack's
    # friends":
    #   1) Just the friends Jack lists: Jill & Simon
    #   2) (1) plus the people who list Jack as a friend: Jill, Simon, & Susan
    #   3) Only those who also consider Jack a friend: Jill (only)
    #
    # For the purposes of this exercise, we'll choose the easy option - 1!

    def mutual_friends_alive_with_brown_eyes(self, person, friend):
        # Select people who:
        #   'person' considers a friend and
        #   'friend' considers a friend and
        #   are still alive and
        #   have brown eyes
        return (self.friend_of(person).friend_of(friend).
                is_alive().has_brown_eyes())

class Person(models.Model):
    """
    A Paranuaran Person
    """
    EYE_COLOR_BLUE = 'bl'
    EYE_COLOR_BROWN = 'br'
    EYE_COLOR_CHOICES = (
        (EYE_COLOR_BLUE, 'Blue'),
        (EYE_COLOR_BROWN, 'Brown'),
    )

    GENDER_MALE = 'm'
    GENDER_FEMALE = 'f'
    GENDER_CHOICES = (
        (GENDER_MALE, 'Male'),
        (GENDER_FEMALE, 'Female'),
    )

    # The _id field from the JSON source file
    json_id = models.CharField(unique=True, max_length=24)

    # The index of of the Person record in the JSON file
    index = models.PositiveIntegerField(unique=True)

    guid = models.CharField(unique=True, max_length=36)

    has_died = models.BooleanField()

    balance = models.DecimalField(max_digits=8, decimal_places=2)

    picture = models.URLField()

    age = models.PositiveIntegerField()

    eyecolor = models.CharField(max_length=2, choices=EYE_COLOR_CHOICES)

    name = models.CharField(max_length=100)

    gender = models.CharField(max_length=1, choices=GENDER_CHOICES)

    company = models.ForeignKey(Company, null=True, blank=True,
                                related_name='employees')

    email = models.EmailField(unique=True)

    phone = models.CharField(max_length=30)

    address = models.CharField(max_length=200)

    about = models.TextField()

    registered = models.DateTimeField()

    tags = models.ManyToManyField(Tag, blank=True)

    friends = models.ManyToManyField('Person', blank=True,
                                     related_name='friend_of')

    greeting = models.CharField(max_length=100)

    favourite_food = models.ManyToManyField(Foodstuff)

    objects = PersonManager.from_queryset(PersonQuerySet)()

    @property
    def favourite_fruit(self):
        return self.favourite_food.fruit()

    @property
    def favourite_vegetables(self):
        return self.favourite_food.vegetables()

    def __str__(self):
        return self.name

    class Meta:
        ordering = ['name']
        verbose_name_plural = 'People'


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

  <android.support.v7.widget.RecyclerView
      android:id="@+id/rv_photos"
      android:layout_width="match_parent"
      android:gravity="center"
      android:layout_height="match_parent"
      />

  <RelativeLayout
      android:layout_alignParentBottom="true"
      android:layout_width="match_parent"
      android:background="#e54d4f4c"
      android:layout_height="wrap_content"
      >
        <Button
            android:layout_centerVertical="true"
            android:id="@+id/button"
            android:text="@string/__picker_all_image"
            android:layout_width="wrap_content"
            android:gravity="center"
            android:textColor="@android:color/white"
            android:layout_height="wrap_content"
            style="@style/Widget.AppCompat.ActionButton"
            android:drawablePadding="5dp"
            android:drawableRight="@drawable/icon_test_list_start"
            />

      <Button
          android:layout_alignParentRight="true"
          android:layout_centerVertical="true"
          style="@style/Widget.AppCompat.ActionButton"
          android:textColor="@android:color/white"
          android:id="@+id/btn_preview"
          android:textSize="14sp"
          android:text="@string/__picker_preview"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content" />

  </RelativeLayout>

</RelativeLayout>


text:
package ch.qos.logback.classic.sift;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.sift.AbstractDiscriminator;
import ch.qos.logback.core.util.OptionHelper;

import java.util.Map;

/**
 * MDCBasedDiscriminator essentially returns the value mapped to an MDC key. If
 * the said value is null, then a default value is returned.
 *

 *
Both Key and the DefaultValue are user specified properties.
 *
 * @author Ceki Gülcü
 */
public class MDCBasedDiscriminator extends AbstractDiscriminator<ILoggingEvent> {

    private String key;
    private String defaultValue;

    /**
     * Return the value associated with an MDC entry designated by the Key
     * property. If that value is null, then return the value assigned to the
     * DefaultValue property.
     */
    public String getDiscriminatingValue(ILoggingEvent event) {
        // http://jira.qos.ch/browse/LBCLASSIC-213
        Map<String, String> mdcMap = event.getMDCPropertyMap();
        if (mdcMap == null) {
            return defaultValue;
        }
        String mdcValue = mdcMap.get(key);
        if (mdcValue == null) {
            return defaultValue;
        } else {
            return mdcValue;
        }
    }

    @Override
    public void start() {
        int errors = 0;
        if (OptionHelper.isEmpty(key)) {
            errors++;
            addError("The \"Key\" property must be set");
        }
        if (OptionHelper.isEmpty(defaultValue)) {
            errors++;
            addError("The \"DefaultValue\" property must be set");
        }
        if (errors == 0) {
            started = true;
        }
    }

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    /**
     * @return
     * @see #setDefaultValue(String)
     */
    public String getDefaultValue() {
        return defaultValue;
    }

    /**
     * The default MDC value in case the MDC is not set for
     * {@link #setKey(String) mdcKey}.
     *

     *
 For example, if {@link #setKey(String) Key} is set to the value
     * "someKey", and the MDC is not set for "someKey", then this appender will
     * use the default value, which you can set with the help of this method.
     *
     * @param defaultValue
     */
    public void setDefaultValue(String defaultValue) {
        this.defaultValue = defaultValue;
    }
}


text:
var CoreView = require('backbone/core-view');
var CodeMirrorView = require('builder/components/code-mirror/code-mirror-view');
var ErrorTemplate = require('./code-mirror-error.tpl');
var checkAndBuildOpts = require('builder/helpers/required-opts');

var REQUIRED_OPTS = [
  'codemirrorModel',
  'onApplyEvent'
];

module.exports = CoreView.extend({
  module: 'editor:layers:layer-content-views:infowindow:infowindow-html-view',

  className: 'Editor-content',

  initialize: function (opts) {
    checkAndBuildOpts(opts, REQUIRED_OPTS, this);
  },

  render: function () {
    this.clearSubViews();
    this.$el.empty();
    this._initViews();
    return this;
  },

  _initViews: function () {
    this.codeMirrorView = new CodeMirrorView({
      model: this._codemirrorModel,
      tips: [
        _t('editor.infowindow.code-mirror.save'),
        _t('editor.infowindow.code-mirror.sanitize')
      ],
      errorTemplate: ErrorTemplate
    });

    this.codeMirrorView.bind('codeSaved', this._triggerCodeSaved, this);
    this.addView(this.codeMirrorView);
    this.$el.append(this.codeMirrorView.render().el);
  },

  _triggerCodeSaved: function (code, view) {
    this._onApplyEvent && this._onApplyEvent();
  }
});


text:
require "googleauth"

module Google
  module Cloud
    module Workflows
      module Executions
        module V1beta
          module Executions
            # Credentials for the Executions API.
            class Credentials < ::Google::Auth::Credentials
              self.scope = [
                "https://www.googleapis.com/auth/cloud-platform"
              ]
              self.env_vars = [
                "WORKFLOWS_CREDENTIALS",
                "WORKFLOWS_KEYFILE",
                "GOOGLE_CLOUD_CREDENTIALS",
                "GOOGLE_CLOUD_KEYFILE",
                "GCLOUD_KEYFILE",
                "WORKFLOWS_CREDENTIALS_JSON",
                "WORKFLOWS_KEYFILE_JSON",
                "GOOGLE_CLOUD_CREDENTIALS_JSON",
                "GOOGLE_CLOUD_KEYFILE_JSON",
                "GCLOUD_KEYFILE_JSON"
              ]
              self.paths = [
                "~/.config/google_cloud/application_default_credentials.json"
              ]
            end
          end
        end
      end
    end
  end
end


text:
/*****************************************************************************
 * name: be_ai_weight.h
 *
 * desc: fuzzy weights
 *
 * $Archive: /source/code/botlib/be_ai_weight.h $
 *
 *****************************************************************************/

#define WT_BALANCE 1
#define MAX_WEIGHTS 128

//fuzzy seperator
typedef struct fuzzyseperator_s {
    int index;
    int value;
    int type;
    float weight;
    float minweight;
    float maxweight;
    struct fuzzyseperator_s* child;
    struct fuzzyseperator_s* next;
} fuzzyseperator_t;

//fuzzy weight
typedef struct weight_s {
    char* name;
    struct fuzzyseperator_s* firstseperator;
} weight_t;

//weight configuration
typedef struct weightconfig_s {
    int numweights;
    weight_t weights[MAX_WEIGHTS];
    char filename[MAX_QPATH];
} weightconfig_t;

//reads a weight configuration
weightconfig_t* ReadWeightConfig(char* filename);
//free a weight configuration
void FreeWeightConfig(weightconfig_t* config);
//writes a weight configuration, returns true if successfull
qboolean WriteWeightConfig(char* filename, weightconfig_t* config);
//find the fuzzy weight with the given name
int FindFuzzyWeight(weightconfig_t* wc, char* name);
//returns the fuzzy weight for the given inventory and weight
float FuzzyWeight(int* inventory, weightconfig_t* wc, int weightnum);
float FuzzyWeightUndecided(int* inventory, weightconfig_t* wc, int weightnum);
//scales the weight with the given name
void ScaleWeight(weightconfig_t* config, char* name, float scale);
//scale the balance range
void ScaleBalanceRange(weightconfig_t* config, float scale);
//evolves the weight configuration
void EvolveWeightConfig(weightconfig_t* config);
//interbreed the weight configurations and stores the interbreeded one in configout
void InterbreedWeightConfigs(weightconfig_t* config1, weightconfig_t* config2, weightconfig_t* configout);
//frees cached weight configurations
void BotShutdownWeights(void);


text:
package in.srain.cube.views.ptr;

import android.view.View;

public interface PtrHandler {

    /**
     * Check can do refresh or not. For example the content is empty or the first child is in view.
     * <p/>
     * {@link PtrDefaultHandler#checkContentCanBePulledDown}
     *
     * @param frame   PtrFrameLayout
     * @param content View
     * @param header  View
     */
    boolean checkCanDoRefresh(final PtrFrameLayout frame, final View content, final View header);

    /**
     * When refresh begin
     *
     * @param frame PtrFrameLayout
     */
    void onRefreshBegin(final PtrFrameLayout frame);
}


text:
//
//  NSGestureRecognizer+MultipleActions.h
//  HLSpriteKit
//
//  Created by Brent Traut on 10/3/16.
//  Copyright © 2016 Hilo Games. All rights reserved.
//

#import <TargetConditionals.h>

#if ! TARGET_OS_IPHONE

#import <Cocoa/Cocoa.h>

/**
 Out of the box, NSGestureRecognizer only allows for one target+action unlike its
 UIGestureRecognizer counterpart which allows for multiple.
 NSGestureRecognizer_MultipleActions adds the ability to add multiple targets+actions.

 After registering all targets+actions with addTarget:action:, the NSGestureRecognizer
 must set its main target+action to this category's own handleGesture:.
*/
@interface NSGestureRecognizer (NSGestureRecognizer_MultipleActions)

/**
 Categories aren't typically allowed to add properties to a class, but a common
 workaround using objc_getAssociatedObject and objc_setAssociatedObject is used:
 http://stackoverflow.com/questions/4146183/instance-variables-for-objective-c-categories
*/
@property (nonatomic, strong) NSMutableArray *targetActionPairs;

/**
 Save a target+action pair for later.

 action must follow one of the signatures as NSGestureRecognizer's main action property:
 - (void)handleGesture;
 - (void)handleGesture:(NSGestureRecognizer *)gestureRecognizer;
*/
- (void)addTarget:(id)target action:(SEL)action;

/**
 Remove a target+action pair.
*/
- (void)removeTarget:(id)target action:(SEL)action;

/**
 Automatically propogate the gesture recognizer handler call to all of the
 targets+actions registered in addTarget:action:.
*/
- (void)handleGesture:(NSGestureRecognizer *)gestureRecognizer;

@end

#endif


text:
#ifndef _ASM_POWERPC_QE_IC_H
#define _ASM_POWERPC_QE_IC_H

#include <linux/irq.h>

struct device_node;
struct qe_ic;

#define NUM_OF_QE_IC_GROUPS	6

/* Flags when we init the QE IC */
#define QE_IC_SPREADMODE_GRP_W			0x00000001
#define QE_IC_SPREADMODE_GRP_X			0x00000002
#define QE_IC_SPREADMODE_GRP_Y			0x00000004
#define QE_IC_SPREADMODE_GRP_Z			0x00000008
#define QE_IC_SPREADMODE_GRP_RISCA		0x00000010
#define QE_IC_SPREADMODE_GRP_RISCB		0x00000020

#define QE_IC_LOW_SIGNAL			0x00000100
#define QE_IC_HIGH_SIGNAL			0x00000200

#define QE_IC_GRP_W_PRI0_DEST_SIGNAL_HIGH	0x00001000
#define QE_IC_GRP_W_PRI1_DEST_SIGNAL_HIGH	0x00002000
#define QE_IC_GRP_X_PRI0_DEST_SIGNAL_HIGH	0x00004000
#define QE_IC_GRP_X_PRI1_DEST_SIGNAL_HIGH	0x00008000
#define QE_IC_GRP_Y_PRI0_DEST_SIGNAL_HIGH	0x00010000
#define QE_IC_GRP_Y_PRI1_DEST_SIGNAL_HIGH	0x00020000
#define QE_IC_GRP_Z_PRI0_DEST_SIGNAL_HIGH	0x00040000
#define QE_IC_GRP_Z_PRI1_DEST_SIGNAL_HIGH	0x00080000
#define QE_IC_GRP_RISCA_PRI0_DEST_SIGNAL_HIGH	0x00100000
#define QE_IC_GRP_RISCA_PRI1_DEST_SIGNAL_HIGH	0x00200000
#define QE_IC_GRP_RISCB_PRI0_DEST_SIGNAL_HIGH	0x00400000
#define QE_IC_GRP_RISCB_PRI1_DEST_SIGNAL_HIGH	0x00800000
#define QE_IC_GRP_W_DEST_SIGNAL_SHIFT		(12)

/* QE interrupt sources groups */
enum qe_ic_grp_id {
	QE_IC_GRP_W = 0,	/* QE interrupt controller group W */
	QE_IC_GRP_X,		/* QE interrupt controller group X */
	QE_IC_GRP_Y,		/* QE interrupt controller group Y */
	QE_IC_GRP_Z,		/* QE interrupt controller group Z */
	QE_IC_GRP_RISCA,	/* QE interrupt controller RISC group A */
	QE_IC_GRP_RISCB		/* QE interrupt controller RISC group B */
};

#ifdef CONFIG_QUICC_ENGINE
void qe_ic_init(struct device_node *node, unsigned int flags,
		void (*low_handler)(unsigned int irq, struct irq_desc *desc),
		void (*high_handler)(unsigned int irq, struct irq_desc *desc));
unsigned int qe_ic_get_low_irq(struct qe_ic *qe_ic);
unsigned int qe_ic_get_high_irq(struct qe_ic *qe_ic);
#else
static inline void qe_ic_init(struct device_node *node, unsigned int flags,
		void (*low_handler)(unsigned int irq, struct irq_desc *desc),
		void (*high_handler)(unsigned int irq, struct irq_desc *desc))
{}
static inline unsigned int qe_ic_get_low_irq(struct qe_ic *qe_ic)
{ return 0; }
static inline unsigned int qe_ic_get_high_irq(struct qe_ic *qe_ic)
{ return 0; }
#endif /* CONFIG_QUICC_ENGINE */

void qe_ic_set_highest_priority(unsigned int virq, int high);
int qe_ic_set_priority(unsigned int virq, unsigned int priority);
int qe_ic_set_high_priority(unsigned int virq, unsigned int priority, int high);

static inline void qe_ic_cascade_low_ipic(unsigned int irq,
					  struct irq_desc *desc)
{
	struct qe_ic *qe_ic = desc->handler_data;
	unsigned int cascade_irq = qe_ic_get_low_irq(qe_ic);

	if (cascade_irq != NO_IRQ)
		generic_handle_irq(cascade_irq);
}

static inline void qe_ic_cascade_high_ipic(unsigned int irq,
					   struct irq_desc *desc)
{
	struct qe_ic *qe_ic = desc->handler_data;
	unsigned int cascade_irq = qe_ic_get_high_irq(qe_ic);

	if (cascade_irq != NO_IRQ)
		generic_handle_irq(cascade_irq);
}

static inline void qe_ic_cascade_low_mpic(unsigned int irq,
					  struct irq_desc *desc)
{
	struct qe_ic *qe_ic = desc->handler_data;
	unsigned int cascade_irq = qe_ic_get_low_irq(qe_ic);

	if (cascade_irq != NO_IRQ)
		generic_handle_irq(cascade_irq);

	desc->chip->eoi(irq);
}

static inline void qe_ic_cascade_high_mpic(unsigned int irq,
					   struct irq_desc *desc)
{
	struct qe_ic *qe_ic = desc->handler_data;
	unsigned int cascade_irq = qe_ic_get_high_irq(qe_ic);

	if (cascade_irq != NO_IRQ)
		generic_handle_irq(cascade_irq);

	desc->chip->eoi(irq);
}

static inline void qe_ic_cascade_muxed_mpic(unsigned int irq,
					    struct irq_desc *desc)
{
	struct qe_ic *qe_ic = desc->handler_data;
	unsigned int cascade_irq;

	cascade_irq = qe_ic_get_high_irq(qe_ic);
	if (cascade_irq == NO_IRQ)
		cascade_irq = qe_ic_get_low_irq(qe_ic);

	if (cascade_irq != NO_IRQ)
		generic_handle_irq(cascade_irq);

	desc->chip->eoi(irq);
}

#endif /* _ASM_POWERPC_QE_IC_H */