text:
#ifndef __MONADIC_EXCEPTIONAL_HPP_INCLUDED__
#define __MONADIC_EXCEPTIONAL_HPP_INCLUDED__

#include <exception>
#include <stdexcept>
#include <type_traits>
#include <utility>

namespace monadic
{

template <typename T>
class exceptional;

template <typename T>
struct is_exceptional_type
{
    using type = std::false_type;
};

template <typename T>
struct is_exceptional_type<exceptional<T>>
{
    using type = std::true_type;
};

template <typename T>
using is_exceptional = typename is_exceptional_type<T>::type;

/** A type which might represent either a value or an exception.
 *
 *  \see try_to
**/
template <typename T>
class exceptional
{
public:
    /** The type of value stored in an \c exceptional instance on success. **/
    using value_type = T;

public:
    exceptional() = default;

    /** Casting constructor for \c exceptional values. **/
    template <typename U>
    exceptional(exceptional<U> src,
                typename std::enable_if<std::is_convertible<U, T>::value>::type* = nullptr
               ) noexcept(noexcept(T(std::declval<U&&>()))) :
            ex_(std::move(src.ex_)),
            val_(std::move(src.val_))
    { }

    /** Forward the \a args to construct a value for this \c exceptional. **/
    template <typename... U>
    explicit exceptional(const std::piecewise_construct_t&, U&&... args)
                noexcept(noexcept(T(std::forward<U>(args)...))) :
            val_(std::forward<U>(args)...)
    { }

    /** Create an instance with \c is_success as \c true and a value constructed in-place with \a args. **/
    template <typename... U>
    static exceptional success(U&&... args)
    {
        return exceptional(std::piecewise_construct, std::forward<U>(args)...);
    }

    /** Create an instance with \c is_success as \c false and the provided exception value \a ex.
     *
     *  \throws std::invalid_argument if \a ex is \c nullptr.
    **/
    static exceptional failure(std::exception_ptr ex)
    {
        if (!ex)
            throw std::invalid_argument("exception_ptr must not be null");

        exceptional out;
        out.ex_ = std::move(ex);
        return out;
    }

    /** Check if this value represents success. If this returns \c true, \c get will not throw. **/
    bool is_success() const noexcept
    {
        return !ex_;
    }

    /** Check if this value represents failure. If this returns \c true, \c get will throw. **/
    bool is_failure() const noexcept
    {
        return !!ex_;
    }

    /** Get the contained value of this instance if this instance represents success (\c is_success == \c true); throws
     *  the exception if this instance represents failure (\c is_success == \c false).
    **/
    const value_type& get() const &
    {
        if (ex_)
            std::rethrow_exception(ex_);
        else
            return val_;
    }

    /** Get the contained value of this instance if this instance represents success (\c is_success == \c true); throws
     *  the exception if this instance represents failure (\c is_success == \c false).
    **/
    value_type& get() &
    {
        if (ex_)
            std::rethrow_exception(ex_);
        else
            return val_;
    }

    /** Get the contained value of this instance if this instance represents success (\c is_success == \c true); throws
     *  the exception if this instance represents failure (\c is_success == \c false).
    **/
    value_type&& get() &&
    {
        if (ex_)
            std::rethrow_exception(ex_);
        else
            return std::move(val_);
    }

    /** Invoke the provided \a action if this instance represents success and return a new instance with the result of
     *  \a action. If this instance is not successful, return a new instance with the exception. If invoking \a action
     *  throws, the result will also be a failure.
    **/
    template <typename FAction>
    auto map(FAction&& action) const & noexcept
            -> exceptional<decltype(action(std::declval<const value_type&>()))>;

    /** Invoke the provided \a action if this instance represents success and return a new instance with the result of
     *  \a action. If this instance is not successful, return a new instance with the exception. If invoking \a action
     *  throws, the result will also be a failure.
    **/
    template <typename FAction>
    auto map(FAction&& action) & noexcept
            -> exceptional<decltype(action(std::declval<value_type&>()))>;

    /** Invoke the provided \a action if this instance represents success and return a new instance with the result of
     *  \a action. If this instance is not successful, return a new instance with the exception. If invoking \a action
     *  throws, the result will also be a failure.
    **/
    template <typename FAction>
    auto map(FAction&& action) && noexcept
            -> exceptional<decltype(action(std::declval<value_type&&>()))>;

    /** Similar to \c map, but useful if your provided \a action returns an <tt>exceptional<U></tt>. In this case,
     *  the result is automatically flattened from <tt>exceptional<exceptional<U>></tt> (if you had used
     *  \c map).
    **/
    template <typename FAction>
    auto flatmap(FAction&& action) const & noexcept
            -> decltype(action(std::declval<const value_type&>()))
    {
        static_assert(is_exceptional<decltype(action(std::declval<const value_type&>()))>::value,
                      "function for flatmap must return an exceptional<U>"
                     );
        return map(std::forward<FAction>(action)).get();
    }

    /** Similar to \c map, but useful if your provided \a action returns an <tt>exceptional<U></tt>. In this case,
     *  the result is automatically flattened from <tt>exceptional<exceptional<U>></tt> (if you had used
     *  \c map).
    **/
    template <typename FAction>
    auto flatmap(FAction&& action) & noexcept
            -> decltype(action(std::declval<value_type&>()))
    {
        static_assert(is_exceptional<decltype(action(std::declval<value_type&>()))>::value,
                      "function for flatmap must return an exceptional<U>"
                     );
        return map(std::forward<FAction>(action)).get();
    }

    /** Similar to \c map, but useful if your provided \a action returns an <tt>exceptional<U></tt>. In this case,
     *  the result is automatically flattened from <tt>exceptional<exceptional<U>></tt> (if you had used
     *  \c map).
    **/
    template <typename FAction>
    auto flatmap(FAction&& action) & noexcept
            -> decltype(action(std::declval<value_type&&>()))
    {
        static_assert(is_exceptional<decltype(action(std::declval<value_type&&>()))>::value,
                      "function for flatmap must return an exceptional<U>"
                     );
        return map(std::forward<FAction>(action)).get();
    }

    /** Call some \a action if this instance is not success (the opposite of \c map).
     *
     *  \param action is some function which is given an \c std::exception_ptr and returns a value. It is only called if
     *                \c is_success is \c false.
     *  \returns An instance with a copy of the value in this one if \c is_success is \c true; an instance with the
     *           result of calling \a action if \c is_success if \c false and it returns in success; otherwise, the
     *           result will have the exception thrown from \a action.
    **/
    template <typename FAction>
    auto recover(FAction&& action) const & noexcept
            -> exceptional<typename std::common_type<T, decltype(action(std::exception_ptr()))>::type>;

    /** Call some \a action if this instance is not success (the opposite of \c map).
     *
     *  \param action is some function which is given an \c std::exception_ptr and returns a value. It is only called if
     *                \c is_success is \c false.
     *  \returns An instance with a copy of the value in this one if \c is_success is \c true; an instance with the
     *           result of calling \a action if \c is_success if \c false and it returns in success; otherwise, the
     *           result will have the exception thrown from \a action.
    **/
    template <typename FAction>
    auto recover(FAction&& action) && noexcept
            -> exceptional<typename std::common_type<T, decltype(action(std::exception_ptr()))>::type>;

private:
    template <typename U>
    friend class exceptional;

private:
    std::exception_ptr ex_;
    value_type         val_;
};

template <>
class exceptional<void>
{
public:
    exceptional() noexcept
    { }

    exceptional(const std::piecewise_construct_t&) noexcept
    { }

    /** Create an empty, successful instance. **/
    static exceptional success()
    {
        return exceptional();
    }

    /** Create an instance with \c is_success as \c false and the provided exception value \a ex.
     *
     *  \throws std::invalid_argument if \a ex is \c nullptr.
    **/
    static exceptional failure(std::exception_ptr ex)
    {
        if (!ex)
            throw std::invalid_argument("exception_ptr must not be null");
        exceptional out;
        out.ex_ = std::move(ex);
        return out;
    }

    /** Throws an exception if this instance represents failure; does nothing if this represents success. **/
    void get() const
    {
        if (ex_)
            std::rethrow_exception(ex_);
    }

    /** Check if this value represents success. If this returns \c true, \c get will not throw. **/
    bool is_success() const noexcept
    {
        return !ex_;
    }

    /** Check if this value represents failure. If this returns \c true, \c get will throw. **/
    bool is_failure() const noexcept
    {
        return !!ex_;
    }

    template <typename FAction>
    auto map(FAction&& action) const noexcept
            -> exceptional<decltype(action())>;

    template <typename FAction>
    auto flatmap(FAction&& action) const noexcept
            -> decltype(action())
    {
        static_assert(is_exceptional<decltype(action())>::value, "function for flatmap must return an exceptional<U>");
        return map(std::forward<FAction>(action)).get();
    }

    /** Call some \a action if this instance is not success.
     *
     *  \param action is some function which is given an \c std::exception_ptr and returns \c void. It is only called if
     *                \c is_success is \c false.
     *  \returns An instance that has \c is_success as \c true if \c is_success is \c true or \a action did not throw an
     *           exception; otherwise, the result will have the exception thrown from \a action.
    **/
    template <typename FAction>
    auto recover(FAction&& action) const noexcept -> exceptional<void>;

private:
    std::exception_ptr ex_;
};

namespace detail
{

template <typename T>
struct try_to
{
    template <typename FAction, typename... TArgs>
    static exceptional<T> exec(FAction&& action, TArgs&&... args) noexcept
    {
        try
        {
            return exceptional<T>::success(action(std::forward<TArgs>(args)...));
        }
        catch (...)
        {
            return exceptional<T>::failure(std::current_exception());
        }
    }
};

template <>
struct try_to<void>
{
    template <typename FAction, typename... TArgs>
    static exceptional<void> exec(FAction&& action, TArgs&&... args) noexcept
    {
        try
        {
            action(std::forward<TArgs>(args)...);
            return exceptional<void>::success();
        }
        catch (...)
        {
            return exceptional<void>::failure(std::current_exception());
        }
    }
};

}

/** Attempt to execute an \a action with the given \a args.
 *
 *  \returns On success, the \c exceptional will have the result of the function. On failure, the returned value will be
 *   filled with an exception.
**/
template <typename FAction, typename... TArgs>
auto try_to(FAction&& action, TArgs&&... args) noexcept
        -> exceptional<decltype(action(std::forward<TArgs>(args)...))>
{
    return detail::try_to<decltype(action(std::forward<TArgs>(args)...))>
                     ::exec(std::forward<FAction>(action), std::forward<TArgs>(args)...);
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Implementation                                                                                //
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

template <typename T>
template <typename FAction>
auto exceptional<T>::map(FAction&& action) const & noexcept
        -> exceptional<decltype(action(std::declval<const value_type&>()))>
{
    if (ex_)
        return exceptional<decltype(action(get()))>::failure(ex_);
    else
        return try_to(std::forward<FAction>(action), get());
}

template <typename T>
template <typename FAction>
auto exceptional<T>::map(FAction&& action) & noexcept
        -> exceptional<decltype(action(std::declval<value_type&>()))>
{
    if (ex_)
        return exceptional<decltype(action(get()))>::failure(ex_);
    else
        return try_to(std::forward<FAction>(action), get());
}

template <typename T>
template <typename FAction>
auto exceptional<T>::map(FAction&& action) && noexcept
        -> exceptional<decltype(action(std::declval<value_type&&>()))>
{
    if (ex_)
        return exceptional<decltype(action(get()))>::failure(ex_);
    else
        return try_to(std::forward<FAction>(action), std::move(val_));
}

template <typename FAction>
auto exceptional<void>::map(FAction&& action) const noexcept
        -> exceptional<decltype(action())>
{
    if (ex_)
        return exceptional<decltype(action())>::failure(ex_);
    else
        return try_to(std::forward<FAction>(action));
}

template <typename T>
template <typename FAction>
auto exceptional<T>::recover(FAction&& action) const & noexcept
        -> exceptional<typename std::common_type<T, decltype(action(std::exception_ptr()))>::type>
{
    using result_type = exceptional<typename std::common_type<T, decltype(action(std::exception_ptr()))>::type>;

    try
    {
        if (is_success())
            return *this;
        else
            return result_type::success(std::forward<FAction>(action)(ex_));
    }
    catch (...)
    {
        return result_type::failure(std::current_exception());
    }
}

template <typename T>
template <typename FAction>
auto exceptional<T>::recover(FAction&& action) && noexcept
        -> exceptional<typename std::common_type<T, decltype(action(std::exception_ptr()))>::type>
{
    using result_type = exceptional<typename std::common_type<T, decltype(action(std::exception_ptr()))>::type>;

    try
    {
        if (is_success())
            return std::move(*this);
        else
            return result_type::success(std::forward<FAction>(action)(ex_));
    }
    catch (...)
    {
        return result_type::failure(std::current_exception());
    }
}

template <typename FAction>
auto exceptional<void>::recover(FAction&& action) const noexcept -> exceptional<void>
{
    if (is_success())
        return *this;
    else
        return try_to([this, &action] { std::forward<FAction>(action)(ex_); });
}

}
#endif/*__MONADIC_EXCEPTIONAL_HPP_INCLUDED__*/


text:
using System;
using System.Text;
using ATMobile.Cells;
using ATMobile.Controls;
using ATMobile.Managers;
using ATMobile.Objects;
using Xamarin.Forms;

namespace ATMobile.Forms
{
    public class TournamentEliminationRoundForm : AbstractEntryForm
    {
        private Tournament m_Tournament;
        private Round m_Round;
        private ATDateEntry m_datDate;
        private ATTextEntry m_txtSeed;
        private ATArcherEntry m_entArcher;
        private ATEditor m_txtNote;

        public TournamentEliminationRoundForm () : base ("Edit Elimination Round")
        {
            m_datDate = new ATDateEntry ("Date", "Date");
            InsideLayout.Children.Add (m_datDate);

            m_entArcher = new ATArcherEntry ("Archer", "Select Archer");
            InsideLayout.Children.Add (m_entArcher);

            m_txtSeed = new ATTextEntry {
                Keyboard = Keyboard.Numeric,
                Title = "Seed",
                Placeholder = "Enter starting seed"
            };
            InsideLayout.Children.Add (m_txtSeed);

            m_txtNote = new ATEditor (100, 200);
            InsideLayout.Children.Add (m_txtNote);
        }

        public override void Save ()
        {
            if (m_datDate.SelectedDate.HasValue) {
                m_Round.Date = m_datDate.SelectedDate.Value;
            }

            int seed;
            if (int.TryParse (m_txtSeed.Text, out seed)) {
                m_Round.Seed = seed;
            }

            m_Round.Note = m_txtNote.Text;
            m_Round.ArcherId = m_entArcher.Archer.Id;

            ATManager.GetInstance ().Persist (m_Round);
        }

        public override void ValidateForm (StringBuilder _sb)
        {
            if (m_entArcher.Archer == null) {
                _sb.AppendLine ("An archer is required.");
            }
        }

        public void SetupForm (Tournament _tournament, Round _round)
        {
            m_Tournament = _tournament;
            m_Round = _round;

            m_datDate.SelectedDate = m_Round.Date;

            if (m_Tournament.Archers.Count == 1) {
                Archer archer = ATManager.GetInstance ().GetArcher (m_Tournament.Archers [0]);
                m_entArcher.Archer = archer;
            }

            if (m_Round.Seed.HasValue) {
                m_txtSeed.Text = Convert.ToString (m_Round.Seed);
            }

            m_txtNote.Text = m_Round.Note;

            m_entArcher.PossibleArchers = m_Tournament.Archers;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php if (!defined('BASEPATH'))
	exit('No direct script access allowed'); ?>

		<?php echo $comic->name; ?>

		<?php echo _('This series contains mature contents and is meant to be viewed by an adult audience.
	If you are of legal age, click on continue.'); ?>

		<a href="<?php echo site_url() ?>">Back to index or
		<?php
			echo form_open('','',array('adult' => 'true'));
			echo form_submit('', _('Continue'));
			echo form_close();
		?>


text:
var flotTitle = "";
var flotAxes;

$(function () {
    /* initialize local variables for tracking axis state */
    flotAxes = new Object();
    flotAxes['y1'] = new Object();
    flotAxes['y2'] = new Object();
    flotAxes['y1'].VariableName = "";
    flotAxes['y1'].data = new Object();

    flotAxes['y2'].VariableName = "";
    flotAxes['y2'].data = new Object();

    /* initalize UI controls for filtering via date/time */
    $('#vis-startdate').datepicker({ dateFormat: 'yy-mm-dd' }).val('2000-01-01'); // iso 8601
    $('#vis-enddate').datepicker({ dateFormat: 'yy-mm-dd' }).val(ISODateString(new Date));   // iso 8601

    // UNCOMMENT HERE TO CLEAR LOCAL DB ON LOAD (TESTING ONLY)
    /*
    var dataStore = $.indexedDB(appName).objectStore(values, 'readwrite');
    var iterationPromise = dataStore.each(function (item) {
        item.delete();
        return;
    });*/
    LoadSeriesToDataTable();

});

/* uses the time values in the header to determine which series should be an option for visualization, populates the data table */
function LoadSeriesToDataTable() {
    debugConsole('LoadSeriesToDataTable called');
    $('#SeriesGrid').jqGrid({
        datatype: "local",
        colNames: ['Series ID', 'Site Name', 'Variable Name', 'Value Count'],// , 'Observations'],
        colModel: [
                { name: 'SeriesID', hidden: true, index: 'SeriesID' },
                { name: 'SiteName', index: 'SiteName' },
                { name: 'VariableName', index: 'VariableName' },
                { name: 'ValueCount', index: 'ValueCount', width: 70, sorttype: 'int' }
        ],
        sortname: 'SiteName',
        rowNum: 10000,
        multiselect: true,
        deselectAfterSort: false, // http://www.trirand.com/blog/?page_id=393/help/sorting-multiselect-grid-loses-selection/
        onSelectRow: function (id) {
            SeriesDataJSONofSeriesID(id);
        }
    });
    debugConsole('grid initialized');

    var BeginTime = new Date($('#vis-startdate').val());
    var EndTime = new Date($('#vis-enddate').val());

    var dataStore = $.indexedDB(appName).objectStore(values, 'readonly');

    var countProm = dataStore.count();
    countProm.done(function (result, event) {
        RefreshMyDataCount(result);
    });
    var iterationPromise = dataStore.each(function(item) {

        if (new Date(item.value.myMetadata.StartDate) > BeginTime && new Date(item.value.myMetadata.EndDate) < EndTime) {
            var row = { SeriesID: item.key, VariableName: item.value.myMetadata.VariableName, SiteName: item.value.myMetadata.SiteName, ValueCount: item.value.myMetadata.ValueCount };
            $('#SeriesGrid').jqGrid('addRowData', item.value.SeriesID, row);
        }
        return;
    });
    $('.ui-jqgrid-bdiv').css("overflow-y", "auto").css("height", 250);
}

/* appends HTML to listview */
function RefreshMyDataCount(seriesCount) {
    $('#vis-mydatalink').remove();
    $('#vis-nav').append('
My Data (' + seriesCount + ')
');
    $('#vis-mydatalink').tooltip({ placement: 'bottom', title: 'Visualize and export time series you have already downloaded.' }); /* should work offline <- test first */
    $('#vis-hisreference').tooltip({ placement: 'bottom', title: 'Learn more about the community effort to publish and share hydrologic data.'});
    $('#vis-apireference').tooltip({ placement: 'bottom', title: 'This web site is powered by an HTTP REST API that is easy to integrate into your own applications and scripts (alpha - interfaces subject to change).'});
}

/* returns 'y1', 'y2', or 'none' depending on whether there is room in the chart for the selected series
   also updates the flotAxes parameter if appropriate */
function JSONSeriesToFlot(seriesData) {
    if (flotAxes['y1'].VariableName === seriesData.myMetadata.VariableName) {
        if (flotAxes['y1'].data[seriesData.myMetadata.SeriesID.toString()] === undefined) {
            debugConsole('my variable name matches existing y1 series and is not already plotted so plot this on y1 too, so add it')
            flotAxes['y1'].data[seriesData.myMetadata.SeriesID] = seriesData;
            return 'y1';

        } else {
            debugConsole('my variable name matches existing y1 and is already plotted so remove it from plot (uncheck case)');
            delete flotAxes['y1'].data[seriesData.myMetadata.SeriesID];
            if (Object.keys(flotAxes['y1'].data) < 1) {
                flotAxes['y1'].VariableName = '';
            }
            return 'rem';
        }
    }
    else if (flotAxes['y2'].VariableName === seriesData.myMetadata.VariableName) {

        if (flotAxes['y2'].data[seriesData.myMetadata.SeriesID.toString()] === undefined) {
            debugConsole('my variable name matches existing y2 and is not already plotted so plot this on y2 too, so add it');
            flotAxes['y2'].data[seriesData.myMetadata.SeriesID] = seriesData;
            return 'y2';
        } else {
            debugConsole('my variable name matches existing y2 and is already plotted so remove it from plot (uncheck case)')
            delete flotAxes['y2'].data[seriesData.myMetadata.SeriesID];
            if (Object.keys(flotAxes['y2'].data) < 1) {
                flotAxes['y2'].VariableName = '';
            }
            return 'rem';
        }
    }
    else if (flotAxes['y2'].VariableName.length < 1 && flotAxes['y1'].VariableName.length > 0) {
        debugConsole('i do not match y1 and there is no y2, so take y2');
        flotAxes['y2'].VariableName = seriesData.myMetadata.VariableName;
        flotAxes['y2'].data[seriesData.myMetadata.SeriesID] = seriesData;
        return 'y2';

    }
    else if (flotAxes['y1'].VariableName.length < 1) {
        debugConsole('y1 is my only option, and it is open, so use y1')
        flotAxes['y1'].VariableName = seriesData.myMetadata.VariableName;
        flotAxes['y1'].data[seriesData.myMetadata.SeriesID] = seriesData;
        return 'y1';
    }
    else /* no room on chart */
        return 'none';
}

/* takes lists of seriesdata objects to be put on different axes, plots them */
function doFlot(y1seriesdata, y2seriesdata) {
    var dataList = new Array();
    var yaxesList = new Array();
    var gotOne = false;

    $.each(y1seriesdata, function (i, seriesData) {
        var d1 = [];
        if (gotOne === false) {
            yaxesList.push({ position: 'left', axisLabel: seriesData.myMetadata.VariableName });
        }
        for (var i = 0; i < seriesData.values.length; i++) {
            var date = new Date(seriesData.values[i].TimeStamp); // asp.net MVC4 libraries do not apply JSON date conversion in serialization
            d1.push([date.getTime(), seriesData.values[i].Value]);
        }
        dataList.push({ data: d1, label: seriesData.myMetadata.VariableName + ', ' + seriesData.myMetadata.SiteName + ' [' + seriesData.unitAbbrev + ']' });

    });

    gotOne = false;
    $.each(y2seriesdata, function(i, seriesData) {
        var d1 = [];
        if (gotOne === false) {
            yaxesList.push({ position: 'right', axisLabel: seriesData.myMetadata.VariableName });
        }
        for (var i = 0; i < seriesData.values.length; i++) {
            var date = new Date(seriesData.values[i].TimeStamp); // asp.net MVC4 libraries do not apply JSON date conversion in serialization
            d1.push([date.getTime(), seriesData.values[i].Value]);
        }
        dataList.push({ data: d1, label: seriesData.myMetadata.VariableName + ', ' + seriesData.myMetadata.SiteName + ' [' + seriesData.unitAbbrev + ']', yaxis: 2 });
    });

    if (y1seriesdata.length > 0 && y2seriesdata.length > 0) {
        yaxesList = [{
            position: 'left',
            axisLabel: y1seriesdata[0]
        }, {}]
    } else if (y1seriesdata.length > 0) { }
    else if (y2seriesdata.length > 0) { }

    var plot = jQuery.plot($('#flotPlot'),
        dataList,
        {
            xaxes: [ { mode: 'time' } ],
            legend: {
                position: 'sw',
                container: $('#flotLegend')
            },
            zoom: { interactive: true },
            yaxes: [ { }, { position: "right" } ]
        });
}

/* get the SeriesData object from the local objectStore */
function SeriesDataJSONofSeriesID(SeriesID) {
    var dataStore = $.indexedDB(appName).objectStore(values, 'readonly');
    var promise = dataStore.get(parseInt(SeriesID));

    promise.done(function (result, event) {
        debugConsole(result);
        var axis = JSONSeriesToFlot(result);
        if (axis === 'y1' || axis === 'y2' || axis === 'rem') {
            var y1 = [];
            for (var key in flotAxes['y1'].data) {
                y1.push(flotAxes['y1'].data[key]);
            }
            var y2 = [];
            for (var key in flotAxes['y2'].data) {
                y2.push(flotAxes['y2'].data[key]);
            }
            doFlot(y1, y2);
            if (y1.length < 1 && y2.length < 1) {
                $('#flotLegend').html('');
            }
        }
        else if (axis === 'none') {
            $('#gbox_SeriesGrid').append(getTooManySeriesForFlotAlert());
        }
    });
    promise.fail(function (error, event) {
        debugConsole('SeriesDataJSONofSeriesID error event: ');
        debugConsole(error);
        debugConsole(event);
    });
}

function getTooManySeriesForFlotAlert() {
    return '
<button type="button" class="close" data-dismiss="alert">×</button>Notice!You can only plot two different variables at the same time on this screen.
';
}

// converts object array into csv file and downloads to your computer. courtesy: http://stackoverflow.com/questions/4130849/convert-json-format-to-csv-format-for-ms-excel
function DownloadJSON2CSV(objArray) {
    var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;

    var str = '';

    for (var i = 0; i < array.length; i++) {
        var line = '';

        for (var index in array[i]) {
            line += array[i][index] + ',';
        }

        // Here is an example where you would wrap the values in double quotes
        // for (var index in array[i]) {
        //    line += '"' + array[i][index] + '",';
        // }

        line.slice(0, line.Length - 1);

        str += line + '\r\n';
    }
    window.open("data:text/csv;charset=utf-8," + escape(str))
}


text:
#ifndef ARDUINO4TETIS_H
#define ARDUINO4TETIS_H

class Joint;
class KinematicSystem;
class User;
class CanNet;

#include <mcp_can.h>
#include <MatrixMath.h>
#include "CanNet.h"
#include "KinematicSystem.h"
#include "Doris.h"
#include "Tetis.h"
#include "MatlabSerial.h"
#include "TetisJoystick.h"

/* HELPFUL UNIT CONVERSION */
#define RADSTORPM (60/(2*PI)) // rpm /(rad/s)
#define RPMTORADS ((2*PI)/60)
#define RADTODEG (180/PI) // grad/rad
#define DEGTORAD (PI/180)

/* DORIS DATA */
// if 1 all Doris Joints are simulated
#define DORIS_SIMU true
// Joint's node id
#define DOR_J1_NODEID 1
#define DOR_J2_NODEID 2
#define DOR_J3_NODEID 3
#define DOR_J4_NODEID 4
// Joints gear reduction (i.e 100 = "1:100")
#define DOR_J1_RED 21
#define DOR_J2_RED 21
#define DOR_J3_RED 21
#define DOR_J4_RED 21
// Joints max velocity [rpm @ motor]
#define DOR_J1_VMAX 6000
#define DOR_J2_VMAX 6000
#define DOR_J3_VMAX 6000
#define DOR_J4_VMAX 6000
// Joints max acceleration [rpm/s @ motor]
#define DOR_J1_AMAX 600
#define DOR_J2_AMAX 600
#define DOR_J3_AMAX 600
#define DOR_J4_AMAX 600
// Joints calibration (initial) angle [rad]
#define DOR_J1_CALQ 0
#define DOR_J2_CALQ 0
#define DOR_J3_CALQ 0
#define DOR_J4_CALQ 0
// Joints encoder counts per revolution
#define DOR_J1_CPR 500
#define DOR_J2_CPR 500
#define DOR_J3_CPR 500
#define DOR_J4_CPR 500
// Epos polarity (1: hourly angles positive)
#define DOR_J1_POL 1
#define DOR_J2_POL -1
#define DOR_J3_POL 1
#define DOR_J4_POL -1

/* TETIS DATA */
// if 1 all Tetis Joints are simulated
#define TETIS_SIMU false
// Joint's node id
#define TET_J1_NODEID 9
#define TET_J2_NODEID 8
#define TET_J3_NODEID 7
#define TET_J4_NODEID 6
// Joints gear reduction (i.e 100 = "1:100")
#define TET_J1_RED 100
#define TET_J2_RED 100
#define TET_J3_RED 100
#define TET_J4_RED 100
// Joints max velocity [rpm @ motor]
#define TET_J1_VMAX 650
#define TET_J2_VMAX 650
#define TET_J3_VMAX 650
#define TET_J4_VMAX 650
// Joints max acceleration [rpm/s @ motor]
#define TET_J1_AMAX 200
#define TET_J2_AMAX 200
#define TET_J3_AMAX 200
#define TET_J4_AMAX 200
// Joints calibration (initial) angle [rad]
#define TET_J1_CALQ 0
#define TET_J2_CALQ -PI/2
#define TET_J3_CALQ 0
#define TET_J4_CALQ 0
// Joints encoder counts per revolution
#define TET_J1_CPR 2000
#define TET_J2_CPR 2000
#define TET_J3_CPR 2000
#define TET_J4_CPR 2000
// Epos polarity (1: hourly angles positive)
#define TET_J1_POL -1
#define TET_J2_POL 1
#define TET_J3_POL -1
#define TET_J4_POL -1

/* BLUETOOTH */
// #define BT_MODE // wether bluetooth is used
#define BT_BAUDRATE 57600

/* MATLAB PLOTTING MODE*/
#define TO_MATLAB // if defined sends data to be plotted to Matlab
#define MATLAB_PREC 3 // number of decimals to send to Matlab
#define MATLAB_PLOT_SAMPLE_T 60 //Matlab plotting sample time(ms)

/*  TEST MODE */
#define SIMU_MODE // simulation mode (overrides TWO_MOTOR_TEST)
// #define TWO_MOTOR_TEST // 2 motors simulated + 2 real

/* DEBUG MODE */
#define DEBUG_PREC 3 // number of decimals to show in debug mode

/* CONTROL PARAMETERS*/
#define FORGET_JLMITS_COLIS // define to take of joint and collision limits
#define FORGET_SATURATION // define to take off saturation limits
#define SAMP_TIME 40 // Sampling time (ms) for the control loops
#define K_JOYSTICK  50 // joystick gain
#define INIT_Q_MAX_ERROR 0.3 // max error(qd-q)[grad] allowed in initial joint control out of singular
#define Q_INIT_POSITION {0.0, -PI/4, PI/2, -PI/4} // initial pos[rad] joints in initial joint control (space of the joints)
#define TETIS_TRAJ 4

/* ARDUINO BOARD CONFIG */
#define SPI_CS_PIN  53 // Uno: 10, Mega: 53
#define USB_BAUDRATE 921600 // USB serial baudrate, used for debugging & warning (9600,115200,921600)
#define CAN_BAUDRATE CAN_1000KBPS // Can network baudrate

/* TETIS SPECIFIC DATA */
#define E2  (float)52.55
#define E3  (float)320.0
#define E4  (float)225.0
#define E5  (float)167.25
#define M3  (float)55.775
#define M4  (float)55.775
#define M5  (float)57.0

/* TRANSMIT PDO 1 SETTINGS */
#define TPDO1_IN_TIME 1000 // inhibit time =  TPDO1_IN_TIME * 10exp(-6)s
#define TPDO1_TR_TYPE 1 // 255: async, 253: async on RTR only, 1:sync
#define PDO_READ_TIMEOUT 10000 // time(ms) to send new SYNC if all PDOS nto received

/* RECEIVE PDO 1 SETTINGS */
#define RPDO1_IN_TIME 1000 // inhibit time =  TPDO1_IN_TIME * 10exp(-6)s
#define RPDO1_TR_TYPE 255 // 255: async, 1:sync

/* ERROR CONTROL PROTOCOL SETTINGS */
#define HEARBEAT_TIME 1000
#define HB_DELAY_ALWD 200 // Allowed delay[ms] in hearbeat receptions

/* GLOBAL VARIABLES */

extern HardwareSerial* serial; // ptr to serial port

extern long unsigned h; // Sampling time(ms) for the control loops
extern long unsigned tLastExec; // time(ms)loop was last executed
extern long unsigned tDelay; // delay from time iteration was supposed to start

extern Joystick* joystick;

extern CanNet canNet;
extern User user;

extern BluetoothJoystick btJoystick;
extern ShieldJoystick shJoystick;
extern Joystick* joystick;

extern MatlabSerial matlab;

class User{
  public:
    unsigned int controlType;
    bool debugMode;
    int useMode; // 0: PC, 1:BT Controller, 2: BT Terminal
    bool toMatlab;
    User(unsigned int ct = 4, bool dm = false,bool tm = false, bool um = 0) :
      controlType(ct),debugMode(dm),toMatlab(tm),useMode(um){}
};

#endif  // EPOS2CONTROL_H


text:
//
//  ZKJUserModel.h
//  百思不得姐
//
//  Created by ZKJ on 2017/2/23.
//  Copyright © 2017年 ZKJ. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface ZKJUserModel : NSObject

/** 用户头像 */
@property(nonatomic,copy) NSString *header;
/** 推荐用户的昵称 */
@property(nonatomic,copy) NSString *screen_name;
/** 推荐用户的关注量 */
@property(nonatomic,copy) NSString *fans_count;
/** 是否关注 */
@property(nonatomic,assign) int is_follow;

@end


text:
declare module Adaptive {
    /**
       @enum {Adaptive.IGeolocationListenerWarning} Adaptive.IGeolocationListenerWarning
       Enumeration IGeolocationListenerWarning
    */
    class IGeolocationListenerWarning {
        value: string;
        constructor(value: string);
        toString(): string;
        /**
           @property {Adaptive.IGeolocationListenerWarning} [HighDoP='HighDoP']
        */
        static HighDoP: IGeolocationListenerWarning;
        /**
           @property {Adaptive.IGeolocationListenerWarning} [StaleData='StaleData']
        */
        static StaleData: IGeolocationListenerWarning;
        /**
           @property {Adaptive.IGeolocationListenerWarning} [Unknown='Unknown']
        */
        static Unknown: IGeolocationListenerWarning;
        /**
           @method
           @static
           Convert JSON parsed object to enumeration.
           @return {Adaptive.IGeolocationListenerWarning}
        */
        static toObject(object: any): IGeolocationListenerWarning;
    }
}


text:
package com.google.cloud.networkconnectivity.v1alpha1.samples;

// [START networkconnectivity_v1alpha1_generated_hubserviceclient_updatespoke_lro_async]
import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.networkconnectivity.v1alpha1.HubServiceClient;
import com.google.cloud.networkconnectivity.v1alpha1.OperationMetadata;
import com.google.cloud.networkconnectivity.v1alpha1.Spoke;
import com.google.cloud.networkconnectivity.v1alpha1.UpdateSpokeRequest;
import com.google.protobuf.FieldMask;

public class AsyncUpdateSpokeLRO {

  public static void main(String[] args) throws Exception {
    asyncUpdateSpokeLRO();
  }

  public static void asyncUpdateSpokeLRO() throws Exception {
    // This snippet has been automatically generated and should be regarded as a code template only.
    // It will require modifications to work:
    // - It may require correct/in-range values for request initialization.
    // - It may require specifying regional endpoints when creating the service client as shown in
    // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
    try (HubServiceClient hubServiceClient = HubServiceClient.create()) {
      UpdateSpokeRequest request =
          UpdateSpokeRequest.newBuilder()
              .setUpdateMask(FieldMask.newBuilder().build())
              .setSpoke(Spoke.newBuilder().build())
              .setRequestId("requestId693933066")
              .build();
      OperationFuture<Spoke, OperationMetadata> future =
          hubServiceClient.updateSpokeOperationCallable().futureCall(request);
      // Do something.
      Spoke response = future.get();
    }
  }
}
// [END networkconnectivity_v1alpha1_generated_hubserviceclient_updatespoke_lro_async]


text:
@implementation UIView(Traversing)

- (UIView *)subview:(NSString *)name
{
	if ( nil == name || 0 == [name length] )
		return nil;

	NSObject * view = [self valueForKey:name];

	if ( [view isKindOfClass:[UIView class]] )
	{
		return (UIView *)view;
	}
	else
	{
		return nil;
	}
}

- (UIView *)viewAtPath:(NSString *)path
{
	if ( nil == path || 0 == path.length )
		return nil;

	NSString *	keyPath = [path stringByReplacingOccurrencesOfString:@"/" withString:@"."];
	NSRange		range = NSMakeRange( 0, 1 );

	if ( [[keyPath substringWithRange:range] isEqualToString:@"."] )
	{
		keyPath = [keyPath substringFromIndex:1];
	}

	NSObject * result = [self valueForKeyPath:keyPath];
	if ( result == [NSNull null] || NO == [result isKindOfClass:[UIView class]] )
		return nil;

	return (UIView *)result;
}

- (UIView *)prevSibling
{
	if ( nil == self.superview )
		return nil;

	if ( self.superview.subviews.count <= 1 )
		return nil;

	NSUInteger count = self.superview.subviews.count;
	NSUInteger index = [self.superview.subviews indexOfObject:self];
	if ( 0 == index )
	{
		index = count - 1;
	}
	else
	{
		index = index - 1;
	}

	return [self.superview.subviews objectAtIndex:index];
}

- (UIView *)nextSibling
{
	if ( nil == self.superview )
		return nil;

	if ( self.superview.subviews.count <= 1 )
		return nil;

	NSUInteger count = self.superview.subviews.count;
	NSUInteger index = [self.superview.subviews indexOfObject:self];

	return [self.superview.subviews objectAtIndex:(index + 1) % count];
}

@end

#endif	// #if (TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR)


text:
package de.longri.cachebox3.gui.menu.menuBtn3;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.badlogic.gdx.scenes.scene2d.utils.Drawable;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.XmlStreamParser;
import de.longri.cachebox3.CB;
import de.longri.cachebox3.callbacks.FinishCallBack;
import de.longri.cachebox3.gui.dialogs.CancelProgressDialog;
import de.longri.cachebox3.gui.dialogs.MessageBox;
import de.longri.cachebox3.gui.dialogs.MessageBoxButton;
import de.longri.cachebox3.gui.dialogs.MessageBoxIcon;
import de.longri.cachebox3.gui.menu.MenuID;
import de.longri.cachebox3.gui.stages.AbstractAction;
import de.longri.cachebox3.gui.views.MapView;
import de.longri.cachebox3.gui.widgets.menu.Menu;
import de.longri.cachebox3.gui.widgets.menu.MenuItem;
import de.longri.cachebox3.locator.Coordinate;
import de.longri.cachebox3.settings.Config;
import de.longri.cachebox3.translation.Language;
import de.longri.cachebox3.translation.Translation;
import de.longri.cachebox3.utils.CharSequenceUtil;
import de.longri.cachebox3.utils.MathUtils;
import de.longri.cachebox3.utils.http.ProgressCancelDownloader;
import de.longri.cachebox3.utils.http.Webb;
import de.longri.cachebox3.utils.http.ZipDownloader;
import org.oscim.core.BoundingBox;
import org.oscim.core.GeoPoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Comparator;

public class Action_MapDownload extends AbstractAction {
    private static Logger log = LoggerFactory.getLogger(Action_MapDownload.class);
    private Menu icm;

    public Action_MapDownload() {
        super("MapDownload", MenuID.AID_Download_FZK_Map);
    }

    public Array<MapRepositoryInfo> getMapInfoList(InputStream stream) {
        final Action_MapDownload.MapRepositoryInfo[] info = {new Action_MapDownload.MapRepositoryInfo()};
        final Array<Action_MapDownload.MapRepositoryInfo> list = new Array<>();

        final XmlStreamParser parser = new XmlStreamParser();

        parser.registerDataHandler("/Freizeitkarte/Map/Name", new XmlStreamParser.DataHandler() {
            @Override
            protected void handleData(char[] data, int offset, int length) {
                info[0].name = new String(data, offset, length).trim();
            }
        });

        if (Config.localization.getEnumValue() == Language.de) {
            parser.registerDataHandler("/Freizeitkarte/Map/DescriptionGerman", new XmlStreamParser.DataHandler() {
                @Override
                protected void handleData(char[] data, int offset, int length) {
                    info[0].description = new String(data, offset, length).trim();
                }
            });
        } else {
            parser.registerDataHandler("/Freizeitkarte/Map/DescriptionEnglish", new XmlStreamParser.DataHandler() {
                @Override
                protected void handleData(char[] data, int offset, int length) {
                    info[0].description = new String(data, offset, length).trim();
                }
            });
        }

        parser.registerDataHandler("/Freizeitkarte/Map/Url", new XmlStreamParser.DataHandler() {
            @Override
            protected void handleData(char[] data, int offset, int length) {
                info[0].url = new String(data, offset, length).trim();
            }
        });

        parser.registerDataHandler("/Freizeitkarte/Map/Size", new XmlStreamParser.DataHandler() {
            @Override
            protected void handleData(char[] data, int offset, int length) {
                info[0].size = CharSequenceUtil.parseInteger(data, offset, length);
            }
        });

        parser.registerDataHandler("/Freizeitkarte/Map/Checksum", new XmlStreamParser.DataHandler() {
            @Override
            protected void handleData(char[] data, int offset, int length) {
                info[0].md5 = new String(data, offset, length).trim();
            }
        });

        parser.registerDataHandler("/Freizeitkarte/Map/MapsforgeBoundingBoxMinLat", new XmlStreamParser.DataHandler() {
            @Override
            protected void handleData(char[] data, int offset, int length) {
                info[0].minLatE6 = CharSequenceUtil.parseInteger(data, offset, length);
            }
        });

        parser.registerDataHandler("/Freizeitkarte/Map/MapsforgeBoundingBoxMinLon", new XmlStreamParser.DataHandler() {
            @Override
            protected void handleData(char[] data, int offset, int length) {
                info[0].minLonE6 = CharSequenceUtil.parseInteger(data, offset, length);
            }
        });

        parser.registerDataHandler("/Freizeitkarte/Map/MapsforgeBoundingBoxMaxLat", new XmlStreamParser.DataHandler() {
            @Override
            protected void handleData(char[] data, int offset, int length) {
                info[0].maxLatE6 = CharSequenceUtil.parseInteger(data, offset, length);
            }
        });

        parser.registerDataHandler("/Freizeitkarte/Map/MapsforgeBoundingBoxMaxLon", new XmlStreamParser.DataHandler() {
            @Override
            protected void handleData(char[] data, int offset, int length) {
                info[0].maxLonE6 = CharSequenceUtil.parseInteger(data, offset, length);
            }
        });

        parser.registerEndTagHandler("/Freizeitkarte/Map", new XmlStreamParser.EndTagHandler() {
            @Override
            protected void handleEndTag() {
                list.add(info[0]);
                info[0] = new Action_MapDownload.MapRepositoryInfo();
            }
        });

        try {
            parser.parse(stream);
        } finally {
            try {
                stream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        info[0] = null;
        return list;
    }

    @Override
    public void execute() {
        try {
            icm = new Menu("MapDownload");
            InputStream inputStream = Webb.create()
                    .get("http://repository.freizeitkarte-osm.de/repository_freizeitkarte_android.xml")
                    .readTimeout(Config.socket_timeout.getValue())
                    .ensureSuccess()
                    .asStream()
                    .getBody();
            Array<MapRepositoryInfo> list = getMapInfoList(inputStream);

            list.sort(new MapComparer(MapView.getLastCenterPos()));

            // get and check the target directory (global value)
            String workPath = Config.MapPackFolder.getValue();
            boolean isWritable;
            if (workPath.length() > 0)
                isWritable = Gdx.files.absolute(workPath).file().canWrite();
            else
                isWritable = false;
            if (isWritable)
                log.info("Download to " + workPath);
            else {
                log.error("Download to " + workPath + " is not possible!");
                // don't use Config.MapPackFolder.getDefaultValue()
                // because it doesn't reflect own repository
                // own or global repository is writable by default, but do check again
                workPath = Config.MapPackFolderLocal.getValue();
                isWritable = Gdx.files.absolute(workPath).file().canWrite();
                log.info("Download to " + workPath + " is possible? " + isWritable);
            }
            final String targetPath = workPath;
            // todo perhaps sorting mapInfoList
            // icm.setHideWithItemClick(true);

            for (MapRepositoryInfo mapInfo : list) {
                icm.addMenuItem("", mapInfo.description.substring(14) + " (" + mapInfo.size / 1024 / 1024 + " MB)",
                        null,
                        new ClickListener() {
                            public void clicked(InputEvent event, float x, float y) {
                                if (icm.mustHandle(event)) {
                                    MenuItem mi = (MenuItem) event.getListenerActor();
                                    mi.setEnabled(false);
                                    // todo doesn't show disabled (enough animation?)
                                    int slashPos = mapInfo.url.lastIndexOf("/");
                                    String zipFile = mapInfo.url.substring(slashPos + 1);
                                    String target = targetPath + "/" + zipFile;

                                    final ProgressCancelDownloader downloader = new ProgressCancelDownloader();

                                    //add downloader object
                                    try {
                                        downloader.add(new ZipDownloader(new URL(mapInfo.url), Gdx.files.absolute(target)));
                                    } catch (MalformedURLException e) {
                                        log.error("download", e);
                                    }

                                    // show dialog and start downloaderRunable
                                    // if cancel clicked or all downloads are ready, the CancelProgressDialog is closed automatically
                                    CancelProgressDialog cancelProgressDialog = new CancelProgressDialog("name", Translation.get("MapDownload"), downloader);
                                    cancelProgressDialog.show(new FinishCallBack() {
                                        @Override
                                        public void callBack() {
                                            //delete zip file after extraction
                                            if (!Gdx.files.absolute(target).delete())
                                                log.warn("can't delete zip file from downloaded Map: {}", mapInfo.description);
                                            else
                                                log.debug("delete zip file from downloaded Map: {}", mapInfo.description);
                                        }
                                    });
                                }
                            }
                        });
            }

            icm.show();

        } catch (Exception ex) {
            ex.printStackTrace();
            MessageBox.show(ex.toString(), Translation.get("MapDownload"), MessageBoxButton.OK, MessageBoxIcon.Information, null);
        }
    }

    @Override
    public Drawable getIcon() {
        return CB.getSkin().menuIcon.baseMapFreizeitkarte;
    }

    public static class MapRepositoryInfo {
        public String name;
        public String description;
        public String url;
        public int size;
        public int minLatE6;
        public int minLonE6;
        public int maxLatE6;
        public int maxLonE6;
        String md5;
        BoundingBox bb = null;
        Coordinate center = null;
        Coordinate mi = null;
        Coordinate ma = null;

        public BoundingBox getBoundingBox() {
            if (bb == null) bb = new BoundingBox(minLatE6, minLonE6, maxLatE6, maxLonE6);
            return bb;
        }

        public Coordinate getCenter() {
            if (center == null) {
                GeoPoint cE6 = getBoundingBox().getCenterPoint();
                center = new Coordinate(cE6.getLatitude(), cE6.getLongitude());
            }
            return center;
        }

        public Coordinate getMin() {
            if (mi == null) {
                GeoPoint miE6 = new GeoPoint(minLatE6, minLonE6);
                mi = new Coordinate(miE6.getLatitude(), miE6.getLongitude());
            }
            return mi;
        }

        public Coordinate getMax() {
            if (ma == null) {
                GeoPoint maE6 = new GeoPoint(maxLatE6, maxLonE6);
                ma = new Coordinate(maE6.getLatitude(), maE6.getLongitude());
            }
            return ma;
        }
    }

    static class MapComparer implements Comparator<MapRepositoryInfo> {
        GeoPoint centreE6;
        Coordinate centre;

        public MapComparer(Coordinate centre) {
            this.centre = centre;
            centreE6 = new GeoPoint(centre.getLatitude(), centre.getLongitude());
        }

        @Override
        public int compare(MapRepositoryInfo a, MapRepositoryInfo b) {
            if ((a == null) || (b == null)) {
                return 0;
            } else {
                boolean aIsIn = a.getBoundingBox().contains(centreE6);
                boolean bIsIn = b.getBoundingBox().contains(centreE6);
                if (aIsIn && bIsIn) {
                    // vereinfachend in Relation zur BoundingBox Diagonalen vergleichen.
                    double ad = a.getCenter().distance(centre, MathUtils.CalculationType.FAST) / a.getMin().distance(a.getMax(), MathUtils.CalculationType.FAST);
                    double bd = b.getCenter().distance(centre, MathUtils.CalculationType.FAST) / b.getMin().distance(b.getMax(), MathUtils.CalculationType.FAST);
                    if (!a.description.startsWith("*")) a.description = "*" + a.description; // mark as containing mapcenter
                    if (!b.description.startsWith("*")) b.description = "*" + b.description; // mark as containing mapcenter
                    return (int) ((ad - bd) * 1000);
                } else {
                    if (aIsIn && !bIsIn) {
                        return -1;
                    } else if (!aIsIn && bIsIn) {
                        return 1;
                    }
                    // don't need this map
                    return 0;
                }
            }
        }
    }

}


text:
require 'rest_client'

module Mexbt
  module Client
    include RestClient
    SSL_VERSION = :TLSv1_2

    def url(path)
      "#{endpoint()}/v1/#{path}"
    end

    def public_key
      @public_key || Mexbt.public_key
    end

    def private_key
      @private_key || Mexbt.private_key
    end

    def user_id
      @user_id || Mexbt.user_id
    end

    def auth_params
      if public_key.nil? || private_key.nil?
        raise "You must configure your API keys!"
      end
      if user_id.nil?
        raise "You must configure your user_id!"
      end
      nonce = (Time.now.to_f*10000).to_i
      {
        apiKey: public_key,
        apiNonce: nonce,
        apiSig: OpenSSL::HMAC.hexdigest('sha256', private_key, "#{nonce}#{user_id}#{public_key}").upcase
      }
    end

    def call(path, params={})
      payload = params
      params.merge!(auth_params) if self.respond_to?(:private?)
      res = Request.execute(method: :post, url: url(path), payload: payload.to_json, ssl_version: SSL_VERSION)
      if res.length === 0
        raise "Empty response from API"
      end
      json_response = ActiveSupport::HashWithIndifferentAccess.new(JSON.parse(res))
      if json_response[:isAccepted]
        json_response
      else
        raise json_response[:rejectReason]
      end
    end

    def call_data(path)
      res = Request.execute(method: :get, url: "https://data.mexbt.com/#{path}", ssl_version: SSL_VERSION)
      ActiveSupport::HashWithIndifferentAccess.new(JSON.parse(res))
    end
  end
end


text:
package com.github.nkzawa.socketio.androidchat;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.github.nkzawa.emitter.Emitter;
import com.github.nkzawa.socketio.client.IO;
import com.github.nkzawa.socketio.client.Socket;
import org.json.JSONException;
import org.json.JSONObject;

import java.net.URISyntaxException;

/**
 * A login screen that offers login via username.
 */
public class LoginActivity extends Activity {

    private EditText mUsernameView;

    private String mUsername;

    private Socket mSocket;
    {
        try {
            mSocket = IO.socket(Constants.CHAT_SERVER_URL);
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        // Set up the login form.
        mUsernameView = (EditText) findViewById(R.id.username_input);
        mUsernameView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
                if (id == R.id.login || id == EditorInfo.IME_NULL) {
                    attemptLogin();
                    return true;
                }
                return false;
            }
        });

        Button signInButton = (Button) findViewById(R.id.sign_in_button);
        signInButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                attemptLogin();
            }
        });

        mSocket.on("login", onLogin);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        mSocket.off("login", onLogin);
    }

    /**
     * Attempts to sign in the account specified by the login form.
     * If there are form errors (invalid username, missing fields, etc.), the
     * errors are presented and no actual login attempt is made.
     */
    private void attemptLogin() {
        // Reset errors.
        mUsernameView.setError(null);

        // Store values at the time of the login attempt.
        String username = mUsernameView.getText().toString().trim();

        // Check for a valid username.
        if (TextUtils.isEmpty(username)) {
            // There was an error; don't attempt login and focus the first
            // form field with an error.
            mUsernameView.setError(getString(R.string.error_field_required));
            mUsernameView.requestFocus();
            return;
        }

        mUsername = username;

        // perform the user login attempt.
        mSocket.emit("add user", username);
    }

    private Emitter.Listener onLogin = new Emitter.Listener() {
        @Override
        public void call(Object... args) {
            JSONObject data = (JSONObject) args[0];

            int numUsers;
            try {
                numUsers = data.getInt("numUsers");
            } catch (JSONException e) {
                return;
            }

            Intent intent = new Intent();
            intent.putExtra("username", mUsername);
            intent.putExtra("numUsers", numUsers);
            setResult(RESULT_OK, intent);
            finish();
        }
    };
}


text:
package io.reactivex.netty.examples.tcp.interceptors.transformation;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.reactivex.netty.channel.AllocatingTransformer;
import io.reactivex.netty.channel.Connection;
import io.reactivex.netty.examples.ExamplesEnvironment;
import io.reactivex.netty.protocol.tcp.client.TcpClient;
import io.reactivex.netty.util.StringLineDecoder;
import org.slf4j.Logger;
import rx.Observable;
import rx.functions.Func1;

import java.net.SocketAddress;
import java.util.Collections;
import java.util.List;

/**
 * A client for {@link TransformingInterceptorsServer}, which follows a simple text based, new line delimited
 * message protocol.
 * The client expects a "Hello" as the first message and then next two integers for every integer sent by the client.
 *
 * There are three ways of running this example:
 *
 *
Default

 *
 * The default way is to just run this class with no arguments, which will start a server
 * ({@link TransformingInterceptorsServer})
 * on an ephemeral port, send a "Hello World!" message to the server and print the response.
 *
 *
After starting {@link TransformingInterceptorsServer}

 *
 * If you want to see how {@link TransformingInterceptorsServer} work, you can run
 * {@link TransformingInterceptorsServer} by yourself and then
 * pass the port on which the server started to this class as a program argument:
 *

 java io.reactivex.netty.examples.tcp.interceptors.transformation.InterceptingClient [server port]

 *
 *
Existing TCP server

 *
 * You can also use this client to connect to an already running TCP server (different than
 * {@link TransformingInterceptorsServer}) by passing the port and host of the existing server similar to the case above:
 *

 java io.reactivex.netty.examples.tcp.interceptors.transformation.InterceptingClient [server port] [server host]

 * If the server host is omitted from the above, it defaults to "127.0.0.1"
 *
 * In all the above usages, this client will print the response received from the server.
 *
 * @see TransformingInterceptorsServer Default server for this client.
 */
public final class InterceptingClient {

    public static void main(String[] args) {

        ExamplesEnvironment env = ExamplesEnvironment.newEnvironment(InterceptingClient.class);
        Logger logger = env.getLogger();

        /*
         * Retrieves the server address, using the following algorithm:
         *

If any arguments are passed, then use the first argument as the server port.

If available, use the second argument as the server host, else default to localhost

Otherwise, start the passed server class and use that address.

         */
        SocketAddress serverAddress = env.getServerAddress(TransformingInterceptorsServer.class, args);

        TcpClient.newClient(serverAddress)
                .<ByteBuf, String>addChannelHandlerLast("string-line-decoder", StringLineDecoder::new)
                .intercept()
                .next(provider -> () -> provider.newConnectionRequest().map(skipHello()))
                .nextWithReadTransform(provider -> () -> provider.newConnectionRequest().map(readIntegers()))
                .nextWithWriteTransform(provider -> () -> provider.newConnectionRequest().map(writeIntegers()))
                .finish()
                .createConnectionRequest()
                .flatMap(connection -> connection.write(Observable.just(1))
                                                 .cast(Integer.class)
                                                 .mergeWith(connection.getInput())
                )
                .take(2)
                .map(Object::toString)
                .toBlocking()
                .forEach(logger::info);
    }

    private static Func1<Connection<String, ByteBuf>, Connection<String, ByteBuf>> skipHello() {
        return c -> c.transformRead(o -> o.skip(1));
    }

    private static Func1<Connection<String, ByteBuf>, Connection<Integer, ByteBuf>> readIntegers() {
        return c -> c.transformRead(o -> o.filter(s1 -> !s1.isEmpty())
                                          .flatMap(s -> Observable.from(s.split(" ")).map(Integer::parseInt)));
    }

    private static Func1<? super Connection<Integer, ByteBuf>, Connection<Integer, Integer>> writeIntegers() {
        return c -> c.transformWrite(new AllocatingTransformer<Integer, ByteBuf>() {
            @Override
            public List<ByteBuf> transform(Integer toTransform, ByteBufAllocator allocator) {
                ByteBuf b = allocator.buffer().writeBytes((toTransform.toString() + "\n").getBytes());
                return Collections.singletonList(b);
            }
        });
    }
}


text:
// Copyright © 2010-2015 The CefSharp Project. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.

#pragma once

#include "Stdafx.h"
#include "include/cef_v8.h"
#include "JavascriptCallbackRegistry.h"

using namespace CefSharp::Internals;

namespace CefSharp
{
    private ref class JavascriptPropertyWrapper
    {
    private:
        JavascriptProperty^ _javascriptProperty;
        int64 _ownerId;
        IBrowserProcess^ _browserProcess;
        //TODO: Strongly type this variable - currently trying to include JavascriptObjectWrapper.h creates a circular reference, so won't compile
        Object^ _javascriptObjectWrapper;

    public:
        JavascriptPropertyWrapper(JavascriptProperty^ javascriptProperty, int64 ownerId, IBrowserProcess^ browserProcess)
        {
            _javascriptProperty = javascriptProperty;
            _ownerId = ownerId;
            _browserProcess = browserProcess;
        }

        ~JavascriptPropertyWrapper()
        {
            if (_javascriptObjectWrapper != nullptr)
            {
                delete _javascriptObjectWrapper;
                _javascriptObjectWrapper = nullptr;
            }
            _javascriptProperty = nullptr;
        }

        void Bind(const CefRefPtr<CefV8Value>& v8Value, JavascriptCallbackRegistry^ callbackRegistry);
    };
}


text:
namespace Microsoft.Azure.Management.DigitalTwins.Models
{

    /// <summary>
    /// Defines values for ProvisioningState.
    /// </summary>
    public static class ProvisioningState
    {
        public const string Provisioning = "Provisioning";
        public const string Deleting = "Deleting";
        public const string Succeeded = "Succeeded";
        public const string Failed = "Failed";
        public const string Canceled = "Canceled";
    }
}


text:
package org.whale.system.domain;

import org.whale.system.annotation.jdbc.Column;
import org.whale.system.annotation.jdbc.Id;
import org.whale.system.annotation.jdbc.Order;
import org.whale.system.annotation.jdbc.Table;
import org.whale.system.annotation.jdbc.Validate;
import org.whale.system.base.BaseEntry;
import org.whale.system.domain.Dept;

/**
 * 根部门 需要sql脚本初始化
 *
 * @author wjs
 * @Date 2014-9-16
 */
@Table(value="sys_dept", cnName="部门")
public class Dept extends BaseEntry {

	private static final long serialVersionUID = -1410859166676l;

	/**部门名称 */
	public static final String F_deptName = "deptName";
	/**部门编码 */
	public static final String F_deptCode = "deptCode";
	/**父部门 */
	public static final String F_pid = "pid";
	/**排序 */
	public static final String F_orderNo = "orderNo";

	@Id
	@Column(name="id", cnName="id")
	private Long id;

	@Validate(required=true)
  	@Column(name="deptName", cnName="部门名称")
	private String deptName;

	@Validate(required=true)
  	@Column(name="deptCode", cnName="部门编码", unique=true)
	private String deptCode;

  	@Order
  	@Column(name="orderNo", cnName="排序")
	private Integer orderNo;

  	@Column(name="remark", cnName="备注")
	private String remark;

  	@Column(name="pid", cnName="父部门")
	private Long pid;

  	@Column(name="deptTel", cnName="联系电话")
	private String deptTel;

  	@Column(name="deptAddr", cnName="联系地址")
	private String deptAddr;

  	@Column(cnName="部门类型")
  	private String deptType;

	/**id */
	public Long getId(){
		return id;
	}

	/**id */
	public void setId(Long id){
		this.id = id;
	}

	/**部门名称 */
	public String getDeptName(){
		return deptName;
	}

	/**部门名称 */
	public void setDeptName(String deptName){
		this.deptName = deptName;
	}

	/**部门编码 */
	public String getDeptCode(){
		return deptCode;
	}

	/**部门编码 */
	public void setDeptCode(String deptCode){
		this.deptCode = deptCode;
	}

	/**排序 */
	public Integer getOrderNo(){
		return orderNo;
	}

	/**排序 */
	public void setOrderNo(Integer orderNo){
		this.orderNo = orderNo;
	}

	/**备注 */
	public String getRemark(){
		return remark;
	}

	/**备注 */
	public void setRemark(String remark){
		this.remark = remark;
	}

	/**父id */
	public Long getPid(){
		return pid;
	}

	/**父id */
	public void setPid(Long pid){
		this.pid = pid;
	}

	/**联系电话 */
	public String getDeptTel(){
		return deptTel;
	}

	/**联系电话 */
	public void setDeptTel(String deptTel){
		this.deptTel = deptTel;
	}

	/**联系地址 */
	public String getDeptAddr(){
		return deptAddr;
	}

	/**联系地址 */
	public void setDeptAddr(String deptAddr){
		this.deptAddr = deptAddr;
	}

	public String getDeptType() {
		return deptType;
	}

	public void setDeptType(String deptType) {
		this.deptType = deptType;
	}
}


text:
package com.hunantv.fw.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 处理非法字符
 *
 * @author 单红宇(365384722)
 * @myblog http://blog.csdn.net/catoop/
 * @create 2015年9月18日
 */
public class XssShieldUtil {

    private static List<Pattern> patterns = null;

    private static List<Object[]> getXssPatternList() {
        List<Object[]> ret = new ArrayList<Object[]>();

        ret.add(new Object[] { "<(no)?script[^>]*>.*?</(no)?script>", Pattern.CASE_INSENSITIVE });
        ret.add(new Object[] { "eval\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL });
        ret.add(new Object[] { "expression\\((.*?)\\)",
                Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL });
        ret.add(new Object[] { "(javascript:|vbscript:|view-source:)*", Pattern.CASE_INSENSITIVE });
        ret.add(new Object[] { "<(\"[^\"]*\"|\'[^\']*\'|[^\'\">])*>",
                Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL });
        ret.add(new Object[] {
                "(window\\.location|window\\.|\\.location|document\\.cookie|document\\.|alert\\(.*?\\)|window\\.open\\()*",
                Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL });
        ret.add(new Object[] {
                "<+\\s*\\w*\\s*(oncontrolselect|oncopy|oncut|ondataavailable|ondatasetchanged|ondatasetcomplete|ondblclick|ondeactivate|ondrag|ondragend|ondragenter|ondragleave|ondragover|ondragstart|ondrop|onerror=|onerroupdate|onfilterchange|onfinish|onfocus|onfocusin|onfocusout|onhelp|onkeydown|onkeypress|onkeyup|onlayoutcomplete|onload|onlosecapture|onmousedown|onmouseenter|onmouseleave|onmousemove|onmousout|onmouseover|onmouseup|onmousewheel|onmove|onmoveend|onmovestart|onabort|onactivate|onafterprint|onafterupdate|onbefore|onbeforeactivate|onbeforecopy|onbeforecut|onbeforedeactivate|onbeforeeditocus|onbeforepaste|onbeforeprint|onbeforeunload|onbeforeupdate|onblur|onbounce|oncellchange|onchange|onclick|oncontextmenu|onpaste|onpropertychange|onreadystatechange|onreset|onresize|onresizend|onresizestart|onrowenter|onrowexit|onrowsdelete|onrowsinserted|onscroll|onselect|onselectionchange|onselectstart|onstart|onstop|onsubmit|onunload)+\\s*=+",
                Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL });
        return ret;
    }

    private static List<Pattern> getPatterns() {

        if (patterns == null) {

            List<Pattern> list = new ArrayList<Pattern>();

            String regex = null;
            Integer flag = null;
            int arrLength = 0;

            for (Object[] arr : getXssPatternList()) {
                arrLength = arr.length;
                for (int i = 0; i < arrLength; i++) {
                    regex = (String) arr[0];
                    flag = (Integer) arr[1];
                    list.add(Pattern.compile(regex, flag));
                }
            }

            patterns = list;
        }

        return patterns;
    }

    public static String stripXss(String value) {
        if (StringUtil.isNotBlank(value)) {

            Matcher matcher = null;

            for (Pattern pattern : getPatterns()) {
                matcher = pattern.matcher(value);
                // 匹配
                if (matcher.find()) {
                    // 删除相关字符串
                    value = matcher.replaceAll("");
                }
            }

            value = value.replaceAll("<", "<").replaceAll(">", ">");
        }

        // if (LOG.isDebugEnabled())
        // LOG.debug("strip value: " + value);

        return value;
    }

    public static void main(String[] args) {

        String value = null;
        value = XssShieldUtil.stripXss("");
        System.out.println("type-1: '" + value + "'");

        value = XssShieldUtil.stripXss("");
        System.out.println("type-2: '" + value + "'");

        value = XssShieldUtil.stripXss("</script>");
        System.out.println("type-3: '" + value + "'");

        value = XssShieldUtil.stripXss(" eval(abc);");
        System.out.println("type-4: '" + value + "'");

        value = XssShieldUtil.stripXss(" expression(abc);");
        System.out.println("type-5: '" + value + "'");

        value = XssShieldUtil.stripXss("");
        System.out.println("type-6: '" + value + "'");

        value = XssShieldUtil.stripXss("");
        System.out.println("type-7: '" + value + "'");

        value = XssShieldUtil.stripXss("");
        System.out.println("type-8: '" + value + "'");

        value = XssShieldUtil.stripXss("


text:
title: Sidebar Markdown Widget
---

#### Resumo

Vinicius Schettino é graduado em Sistemas de Informação e mestrando em Engenharia de Software na Universidade Federal de Juiz de Fora (UFJF). Atualmente é servidor público, atuando como Administrador de Sistemas na mesma instituição, além de auxiliar empresas da região com capacitação e consultoria em processos do desenvolvimento de software. Suas áreas de pesquisa incluem desenvolvimento distribuído, ecossistemas, evolução de software e banco de dados. Nas horas vagas é guitarrista e vem se recuperando (lentamente) do vício em café.

Neste Blog falo sobre tendências de mercado, novas tecnologias, comandos, snippets úteis e principalmente ferramentas que conheci e gostaria de compartilhar com o público tupiniquim.


text:
@extends('shared/_adminlayout')

@section('title')
    Categories
@endsection

@section('content')

     Create new Category

    @if($categories->count())

         @foreach($categories as $category)

                 {{ $category->name }}

                      $category->id]) }}" class="btn btn-primary">
                          Edit

                      $category->id]) }}" class="btn btn-danger" data-post="true">
                          Delete

         @endforeach

    @else

No Categories

    @endif

    <form id="anti-forgery-token">
        {!! Form::token() !!}
    </form>
@endsection


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
J. Mycol. 1(5): 63 (1885)

#### Original name
Cladosporium personatum Berk. & M.A. Curtis, 1875

### Remarks
null


text:
<?php

defined('_JEXEC') or die('Restricted access');

jimport( 'joomla.filesystem.file' );

class EasyBlogMightyTouchHelper
{
	public function __construct()
	{
		$lang		= JFactory::getLanguage();
		$lang->load( 'com_easyblog' , JPATH_ROOT );
	}

	/**
	 * Sets the karma point for the respective user when certain action is performed.
	 *
	 * @param	int $userId The user id
	 * @param	string $action This action should map with the config's action string.
	 */
	public function setKarma( $userId , $action )
	{
		$config		= EasyBlogHelper::getConfig();

		if(!$config->get( 'integrations_mighty_karma_' . $action ) )
		{
			return false;
		}

		$file		= JPATH_ROOT . DIRECTORY_SEPARATOR . 'components' . DIRECTORY_SEPARATOR . 'com_community' . DIRECTORY_SEPARATOR . 'api.php';

		if( !JFile::exists( $file ) )
		{
			return false;
		}
		require_once($file);

		$points		= $config->get( 'integrations_mighty_karma_' . $action . '_points');
		JSCommunityApi::increaseKarma( $userId , $points );
		return true;
	}

	public function getBlogLink( $blog )
	{
		return EasyBlogRouter::getRoutedURL( 'index.php?option=com_easyblog&view=entry&id=' . $blog->id . $this->getItemId() , false , true );
	}

	public function getBlogTitle( $blog )
	{
		$title		= htmlspecialchars( $blog->title );

		if (strlen($title) > 80)
		{
			$title		= JString::substr( $blog->title , 0 , 80 ) . '...';
		}

		return $title;
	}

	public function getCategoryTitle( $blog )
	{
		$category	= EasyBlogHelper::getTable( 'Category' );
		$category->load( $blog->category_id );

		return $category->title;
	}

	public function getCategoryLink( $blog )
	{
		return EasyBlogRouter::getRoutedURL( 'index.php?option=com_easyblog&view=categories&layout=listings&id=' . $blog->category_id . $this->getItemId() , false , true );
	}

	public function getItemId()
	{
		$id		= '';

		$app	= JFactory::getApplication();

		if( $app->isAdmin() )
		{
			$id		= '&Itemid=' . EasyBlogRouter::getItemId( 'latest' );
		}
		return $id;
	}

	public function getFirstImage( $content )
	{
		// Remove all html tags from the content as we want to chop it down.
		$content	= strip_tags( $content );

		$pattern		= '#]*>#i';
		preg_match( $pattern , $content , $matches );

		if( $matches )
		{
			$matches[0]		= JString::str_ireplace( 'img ' , 'img style="margin: 0 5px 5px 0;float: left; height: auto; width: 120px !important;"' , $matches[0 ] );

			return $matches[ 0 ] . '

';
		}

		return false;
	}

	public function addFeaturedActivity( $blog )
	{
		$config	= EasyBlogHelper::getConfig();
		$title	= JString::substr( $blog->title , 0 , 30 ) . '...';

		$file		= JPATH_ROOT . DIRECTORY_SEPARATOR . 'components' . DIRECTORY_SEPARATOR . 'com_community' . DIRECTORY_SEPARATOR . 'api.php';

		if( !JFile::exists( $file ) )
		{
			return false;
		}
		require_once($file);

		$blogLink	= $this->getBlogLink( $blog );
		$my			= JFactory::getUser();

		$content	= $blog->intro	. $blog->content;
		$content	= EasyBlogHelper::getHelper( 'Videos' )->strip( $content );
		$image		= $this->getFirstImage( $content );

		if( JString::strlen($content) > $config->get( 'integrations_jomsocial_blogs_length', 250 ))
		{
			$content = JString::substr($content, 0, $config->get( 'integrations_mighty_blogs_length', 250 ) ) . ' ...';
		}

		$output		= '
';

		if( $image !== false )
		{
			$output	= $image . $content;
		}
		else
		{
			$output	.= $content;
		}

		$output	.= '
getBlogLink( $blog ) . '">' . JText::_( 'COM_EASYBLOG_CONTINUE_READING' ) . '
';
		$output	.= '
';

		$title	= JText::sprintf( 'COM_EASYBLOG_MIGHTY_ACTIVITY_FEATURE_BLOG' , $this->getBlogLink( $blog ) , $this->getBlogTitle( $blog ) );

		JSCommunityApi::registerActivity( 0 , $title . $output , $my->id , null , 'user', null , 'com_easyblog' , null , JText::_( 'COM_EASYBLOG_MIGHTYTOUCH_FILTER_BLOGS' ) );

		return true;
	}

	public function addActivity( $blog , $new = false )
	{
		$config		= EasyBlogHelper::getConfig();

		// We do not want to add activities if new blog activity is disabled.
		if( $new && !$config->get( 'integrations_mighty_activity_new_blog' ) )
		{
			return false;
		}

		// We do not want to add activities if update blog activity is disabled.
		if( !$new && !$config->get( 'integrations_mighty_activity_update_blog') )
		{
			return false;
		}

		$file		= JPATH_ROOT . DIRECTORY_SEPARATOR . 'components' . DIRECTORY_SEPARATOR . 'com_community' . DIRECTORY_SEPARATOR . 'api.php';

		if( !JFile::exists( $file ) )
		{
			return false;
		}
		require_once($file);
		$date		= EasyBlogHelper::getDate();
		$priority	= 0;
		$title		= $blog->title;
		$content	= '';

		if($config->get('integrations_mighty_submit_content'))
		{
			$requireVerification = false;

			if($config->get('main_password_protect', true) && !empty($blog->blogpassword))
			{
				$row->title	= JText::sprintf('COM_EASYBLOG_PASSWORD_PROTECTED_BLOG_TITLE', $blog->title);
				$requireVerification = true;
			}

			if($requireVerification && !EasyBlogHelper::verifyBlogPassword($blog->blogpassword, $blog->id))
			{
				$theme = new CodeThemes();
				$theme->set('id', $blog->id);
				$theme->set('return', base64_encode( $this->getBlogLink( $blog ) ) );
				$output	= $theme->fetch( 'blog.protected.php' );
			}
			else
			{
				$content    = $blog->intro . $blog->content;

				$content	= EasyBlogHelper::getHelper( 'Videos' )->strip( $content );
				$pattern	= '#]*>#i';
				preg_match( $pattern , $content , $matches );

				// Remove all html tags from the content as we want to chop it down.
				$content	= strip_tags( $content );
				$content	= JString::substr($content, 0, $config->get( 'integrations_mighty_blogs_length', 250 ) ) . ' ...';

				$output		= '
';
				if( $matches )
				{
					$matches[0]		= JString::str_ireplace( 'img ' , 'img style="margin: 0 5px 5px 0;float: left; height: auto; width: 120px !important;"' , $matches[0 ] );

					$output		.= $matches[0] . $content . '

';
				}
				else
				{
					$output	.= $content;
				}
				$output	.= '
getBlogLink( $blog ) . '">' . JText::_( 'COM_EASYBLOG_CONTINUE_READING' ) . '
';
				$output	.= '
';
			}
		}

		if( $new )
		{
			$title	= JText::sprintf( 'COM_EASYBLOG_MIGHTY_ACTIVITY_BLOG' , $this->getBlogLink( $blog ) , $this->getBlogTitle( $blog ) );
		}
		else
		{
			$title	= JText::sprintf( 'COM_EASYBLOG_MIGHTY_ACTIVITY_BLOG_UPDATE' , $this->getBlogLink( $blog ) , $this->getBlogTitle( $blog ) );
		}

		if($config->get('integrations_mighty_show_category'))
		{
			$title	.= JText::sprintf( 'COM_EASYBLOG_MIGHTY_ACTIVITY_IN_CATEGORY' , $this->getCategoryLink( $blog ) , $this->getCategoryTitle( $blog ) );
		}

		JSCommunityApi::registerActivity( 0 , $title . $output , $blog->created_by , null , 'user', null , 'com_easyblog' , null , JText::_( 'COM_EASYBLOG_MIGHTYTOUCH_FILTER_BLOGS' ) );

		return true;
	}
}


text: export const DataStructureVersion = 12;


text:
@interface MWZSearchParams : NSObject

@property(nonatomic, strong) NSString* query;
@property(nonatomic, strong) NSString* venueId;
@property(nonatomic, strong) NSString* organizationId;
@property(nonatomic, strong) NSString* universeId;

- (NSDictionary*) toDictionary;

@end


text:
var x,y,a=7,b=5,t=0;
//x,y are coordinates that follow lissajous pattern
//a,b are lissajous constants that determine the shape of the pattern.
//t is the frame count
var constant1=250,constant2=250;
//constant1 and constant2 determine the size of the pattern

function setup() {
  createCanvas(600,600);
  //background(0);
}

function draw() {

  translate(width/2,height/2);
  //beginShape();
  //assigning lissajous equation to the coordinates x,y
  x=constant1*sin(a*t);
  y=constant2*cos(b*t);
  noStroke();
  fill(3*x,4*y,(x+y));
  //fill(255);
  //ellipse(x,y,(x-y)/2,(x-y)/2);
  ellipse(x,y,5,5);
  //vertex(x,y);
 // endShape();
  t+=0.1;
}


text:
require 'twilio-ruby'

response = Twilio::TwiML::VoiceResponse.new
response.pay(payment_method: 'ach-debit', charge_amount: '13.22') do |pay|
    pay.prompt(for: 'bank-account-number') do |prompt|
        prompt.say(message: 'Thanks for using our service. Please enter your bank account number.')
end
    pay.prompt(for: 'bank-account-number', require_matching_inputs: true) do |prompt2|
        prompt2.say(message: 'Thank you. Please enter your bank account number again.')
end
    pay.prompt(for: 'bank-account-number', error_type: 'input-matching-failed') do |prompt3|
        prompt3.say(message: 'Sorry, your two bank account number inputs did not match. Please enter your bank account number again. We will then ask a second time again.')
end
end

puts response


text:
import os, sys, config

# Set the help menu
def getSyntax():
    return "Usage: pyvmrun-getip <vm_name>"

# Parsing arguments
if len(sys.argv) == 1:
    print getSyntax()
    exit(1)
else:
    conf = config.Config()
    vm_start_dest = conf.getVmsPathDir() + "/" + sys.argv[1] +  ".vmwarevm/" +  sys.argv[1] + ".vmx"
    if not os.path.exists(vm_start_dest):
        print "Virtual machine not found."
        exit(1)
    cmd = "vmrun getGuestIPAddress '" + vm_start_dest + "'"
    os.system(cmd)


text:
using System.Runtime.InteropServices;

#if !READ_ONLY

namespace Mono.Cecil.Pdb {

	[Guid ("B01FAFEB-C450-3A4D-BEEC-B4CEEC01E006")]
	[InterfaceType (ComInterfaceType.InterfaceIsIUnknown)]
	[ComImport]
	interface ISymUnmanagedDocumentWriter {
	}
}

#endif


text:
module Ling.Fmt.Albert.Abs where

-- Haskell module generated by the BNF converter

newtype Name = Name String deriving (Eq, Ord, Show, Read)
newtype OpName = OpName String deriving (Eq, Ord, Show, Read)
data Program = Prg [Dec]
  deriving (Eq, Ord, Show, Read)

data Dec
    = DPrc Name [ChanDec] Proc OptDot
    | DDef Name OptSig TermProc OptDot
    | DSig Name Term OptDot
    | DDat Name [ConName] OptDot
    | DAsr Assertion
  deriving (Eq, Ord, Show, Read)

data Assertion = AEq Term Term OptSig
  deriving (Eq, Ord, Show, Read)

data ConName = CN Name
  deriving (Eq, Ord, Show, Read)

data OptDot = NoDot | SoDot
  deriving (Eq, Ord, Show, Read)

data TermProc = SoTerm Term | SoProc Proc
  deriving (Eq, Ord, Show, Read)

data OptSig = NoSig | SoSig Term
  deriving (Eq, Ord, Show, Read)

data VarDec = VD Name OptSig
  deriving (Eq, Ord, Show, Read)

data ChanDec = CD Name OptRepl OptSession
  deriving (Eq, Ord, Show, Read)

data Branch = Br ConName Term
  deriving (Eq, Ord, Show, Read)

data Literal
    = LInteger Integer | LDouble Double | LString String | LChar Char
  deriving (Eq, Ord, Show, Read)

data ATerm
    = Var Name
    | Op OpName
    | Lit Literal
    | Con ConName
    | TTyp
    | TProto [RSession]
    | Paren Term OptSig
    | End
    | Par [RSession]
    | Ten [RSession]
    | Seq [RSession]
  deriving (Eq, Ord, Show, Read)

data Term
    = RawApp ATerm [ATerm]
    | Case Term [Branch]
    | Snd Term CSession
    | Rcv Term CSession
    | Dual Term
    | TRecv Name
    | Loli Term Term
    | TFun Term Term
    | TSig Term Term
    | Let Name OptSig Term Term
    | Lam Term Term
    | TProc [ChanDec] Proc
  deriving (Eq, Ord, Show, Read)

data Proc
    = PAct Act
    | PPrll [Proc]
    | PNxt Proc Proc
    | PDot Proc Proc
    | PSem Proc Proc
    | NewSlice [ChanDec] ATerm Name Proc
  deriving (Eq, Ord, Show, Read)

data Act
    = Nu NewAlloc
    | ParSplit Name [ChanDec]
    | TenSplit Name [ChanDec]
    | SeqSplit Name [ChanDec]
    | Send Name ATerm
    | NewSend Name ATerm
    | Recv Name VarDec
    | NewRecv Name OptSig Name
    | LetRecv Name OptSig ATerm
    | Ax ASession [ChanDec]
    | SplitAx Integer ASession Name
    | At ATerm TopCPatt
    | LetA Name OptSig ATerm
  deriving (Eq, Ord, Show, Read)

data ASession = AS ATerm
  deriving (Eq, Ord, Show, Read)

data TopCPatt
    = OldTopPatt [ChanDec]
    | ParTopPatt [CPatt]
    | TenTopPatt [CPatt]
    | SeqTopPatt [CPatt]
  deriving (Eq, Ord, Show, Read)

data CPatt
    = ChaPatt ChanDec
    | ParPatt [CPatt]
    | TenPatt [CPatt]
    | SeqPatt [CPatt]
  deriving (Eq, Ord, Show, Read)

data OptSession = NoSession | SoSession RSession
  deriving (Eq, Ord, Show, Read)

data RSession = Repl Term OptRepl
  deriving (Eq, Ord, Show, Read)

data OptRepl = One | Some ATerm
  deriving (Eq, Ord, Show, Read)

data CSession = Cont Term | Done
  deriving (Eq, Ord, Show, Read)

data AllocTerm = AVar Name | ALit Literal | AParen Term OptSig
  deriving (Eq, Ord, Show, Read)

data NewPatt = TenNewPatt [ChanDec] | SeqNewPatt [ChanDec]
  deriving (Eq, Ord, Show, Read)

data NewAlloc
    = OldNew [ChanDec]
    | New NewPatt
    | NewSAnn Term OptSig NewPatt
    | NewNAnn OpName [AllocTerm] NewPatt
  deriving (Eq, Ord, Show, Read)


text:
- Creating Africa's Talking [Sandbox](https://account.sandbox.africastalking.com/login?page=/ ) account or [live](https://www.africastalking.com/) account
- Take note of your africa's talking live account username and sandbox account user name
- Get [Sandbox API_KEY](https://account.sandbox.africastalking.com/settings/apikey) / [Live API_KEY](https://account.africastalking.com/settings/apikey)
- [Download](http://docs.africastalking.com/smslibraries/csharp) the C# gateway class
- install visual studio ``preferably Microsoft Visual Studio community`` but others would work as well

- After installation Open visual studio, and create a new console project

- copy this into your .cs file

```cs

 using System;

    class MainClass
    {
        static public void Main (){

            // Create a new instance of our awesome gateway class
            AfricasTalkingGateway gateway = new AfricasTalkingGateway ("MyAfricasTalkingUsername", "MyAfricasTalkingAPIKey");

            gateway.sendMessage ("+254711XXXYYY", "Hi Stranger");
        }
    }

```

- Add the Africastalking gateway
>> ```On the solution Explore right click on the name of your project then select add ,which will give you an option to add existing item or new item, click on the existing item``` Or simply click ```Shift+Alt+A```

- On the windows Explorer select ```AfricasTalkingGateway.cs```

>>> To help decode JSON responses, you will need to add a reference to System.Web.Extensions and System.Microsoft.CSharp

##### STEPS TO ADD
---------------------
- First:- Right click your project select properties,
Change your target Framework to ```Net Framework 3.5 ``` and above. Save and close the refrence tab

- Second:-Right click on the refrence Item in your Solution explorer "usually but NOT ALWAYS found on the right hand side"
choose Add refrence
In the .Net tab scroll down to System.Web, System.Web.Extensions and System.Microsoft.CSharp and Add them


text:
package org.apache.camel.processor.aggregate.hazelcast;

import org.apache.camel.EndpointInject;
import org.apache.camel.Produce;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.junit.Test;

public class HazelcastAggregationRepositoryRoutesTest extends HazelcastAggregationRepositoryCamelTestSupport {

    private static final String REPO_NAME = "routeTestRepo";
    private static final String MOCK_GOTCHA = "mock:gotcha";
    private static final String DIRECT_ONE = "direct:one";
    private static final String DIRECT_TWO = "direct:two";

    @EndpointInject(MOCK_GOTCHA)
    private MockEndpoint mock;

    @Produce(DIRECT_ONE)
    private ProducerTemplate produceOne;

    @Produce(DIRECT_TWO)
    private ProducerTemplate produceTwo;

    @Test
    public void checkAggregationFromTwoRoutes() throws Exception {
        final HazelcastAggregationRepository repoOne =
                new HazelcastAggregationRepository(REPO_NAME, false, getFirstInstance());

        final HazelcastAggregationRepository repoTwo =
                new HazelcastAggregationRepository(REPO_NAME, false, getSecondInstance());

        final int completionSize = 4;
        final String correlator = "CORRELATOR";
        RouteBuilder rbOne = new RouteBuilder() {
            @Override
            public void configure() throws Exception {

                from(DIRECT_ONE).routeId("AggregatingRouteOne")
                        .aggregate(header(correlator))
                        .aggregationRepository(repoOne)
                        .aggregationStrategy(new SumOfIntsAggregationStrategy())
                        .completionSize(completionSize)
                        .to(MOCK_GOTCHA);
            }
        };

        RouteBuilder rbTwo = new RouteBuilder() {
            @Override
            public void configure() throws Exception {

                from(DIRECT_TWO).routeId("AggregatingRouteTwo")
                        .aggregate(header(correlator))
                        .aggregationRepository(repoTwo)
                        .aggregationStrategy(new SumOfIntsAggregationStrategy())
                        .completionSize(completionSize)
                        .to(MOCK_GOTCHA);
            }
        };

        context().addRoutes(rbOne);
        context().addRoutes(rbTwo);
        context().start();

        mock.expectedMessageCount(1);
        mock.expectedBodiesReceived(1 + 2 + 3 + 4);

        produceOne.sendBodyAndHeader(1, correlator, correlator);
        produceTwo.sendBodyAndHeader(2, correlator, correlator);
        produceOne.sendBodyAndHeader(3, correlator, correlator);
        produceOne.sendBodyAndHeader(4, correlator, correlator);

        mock.assertIsSatisfied();
    }

    @Test
    public void checkAggregationFromTwoRoutesNoRecovery() throws Exception {
        final HazelcastAggregationRepository repoOne =
                new HazelcastAggregationRepository(REPO_NAME, false, getFirstInstance());

        final HazelcastAggregationRepository repoTwo =
                new HazelcastAggregationRepository(REPO_NAME, false, getSecondInstance());

        repoOne.setUseRecovery(false);
        repoTwo.setUseRecovery(false);

        final int completionSize = 4;
        final String correlator = "CORRELATOR";
        RouteBuilder rbOne = new RouteBuilder() {
            @Override
            public void configure() throws Exception {

                from(DIRECT_ONE).routeId("AggregatingRouteOne")
                        .aggregate(header(correlator))
                        .aggregationRepository(repoOne)
                        .aggregationStrategy(new SumOfIntsAggregationStrategy())
                        .completionSize(completionSize)
                        .to(MOCK_GOTCHA);
            }
        };

        RouteBuilder rbTwo = new RouteBuilder() {
            @Override
            public void configure() throws Exception {

                from(DIRECT_TWO).routeId("AggregatingRouteTwo")
                        .aggregate(header(correlator))
                        .aggregationRepository(repoTwo)
                        .aggregationStrategy(new SumOfIntsAggregationStrategy())
                        .completionSize(completionSize)
                        .to(MOCK_GOTCHA);
            }
        };

        context().addRoutes(rbOne);
        context().addRoutes(rbTwo);
        context().start();

        mock.expectedMessageCount(1);
        mock.expectedBodiesReceived(1 + 2 + 3 + 4);

        produceOne.sendBodyAndHeader(1, correlator, correlator);
        produceTwo.sendBodyAndHeader(2, correlator, correlator);
        produceOne.sendBodyAndHeader(3, correlator, correlator);
        produceOne.sendBodyAndHeader(4, correlator, correlator);

        mock.assertIsSatisfied();
    }

}


text:
// Copyright 2009 the Sputnik authors.  All rights reserved.
/**
 * Parentheses of the form ( Disjunction ) serve both to group the components of the Disjunction pattern together and to save the result of the match.
 * The result can be used either in a backreference (\ followed by a nonzero decimal number),
 * referenced in a replace string,
 * or returned as part of an array from the regular expression matching function
 *
 * @path ch15/15.10/15.10.2/15.10.2.8/S15.10.2.8_A3_T17.js
 * @description see bug http:bugzilla.mozilla.org/show_bug.cgi?id=169497
 */

__body="";
__body += '\n';
__body += '
Kibology for all<\/p>\n';
__body += '
All for Kibology<\/p>\n';
__body += '<\/body>';

__html="";
__html += '\n';
__html += __body;
__html += '\n<\/html>';

__executed = /((.*\n?)*?)<\/body>/i.exec(__html);

__expected = [__body, '\n
Kibology for all
\n
All for Kibology
\n', '
All for Kibology
\n'];
__expected.index = 7;
__expected.input = __html;

//CHECK#1
if (__executed.length !== __expected.length) {
	$ERROR('#1: __executed = /((.*\\n?)*?)<\\/body>/i.exec(__html); __executed.length === ' + __expected.length + '. Actual: ' + __executed.length);
}

//CHECK#2
if (__executed.index !== __expected.index) {
	$ERROR('#2: __executed = /((.*\\n?)*?)<\\/body>/i.exec(__html); __executed.index === ' + __expected.index + '. Actual: ' + __executed.index);
}

//CHECK#3
if (__executed.input !== __expected.input) {
	$ERROR('#3: __executed = /((.*\\n?)*?)<\\/body>/i.exec(__html); __executed.input === ' + __expected.input + '. Actual: ' + __executed.input);
}

//CHECK#4
for(var index=0; index<__expected.length; index++) {
	if (__executed[index] !== __expected[index]) {
		$ERROR('#4: __executed = /((.*\\n?)*?)<\\/body>/i.exec(__html); __executed[' + index + '] === ' + __expected[index] + '. Actual: ' + __executed[index]);
	}
}


text:
(function() {
  'use strict';

  angular.module('taskApp.widgets', [
    'taskApp.core'
    ]);
})();


text:
/**
 * Created by joshua on 6/28/15.
 */
angular.module('BlackHoleApp.Robots', ['ngRoute'])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/Robots', {
    templateUrl: 'static/view/Robots.html',
    controller: 'RobotsController'
  });
}])
app. controller('RobotsController', ['$scope', '$log', '$http', '$timeout','Token', function($scope, $log, $http,$timeout, Token) {
$scope.getRobots = function(data){
              var urlBase = "https://winkapi.quirky.com";

               var robots = function () {
                   Token.getToken().then(
                   function(token){
                       var botTimeout = "";
                       $http({
                        method: 'GET',
                        url:urlBase+'/users/me/robots',
                        headers:{
                            Authorization : 'Bearer ' + token
                        }
                       }).success(function (results) {
                   //  $log.log(results);
                             $scope.robots = results.data;
                       }).error(function (error) {
                             $log.log(error);
                       });
                   // continue to call the poller() function every 2 seconds
                   // until the timeout is cancelled
                   botTimeout = $timeout(robots, 2000);
                   })
               }
               robots();

          }
}]);


text:
package br.com.farms.rcp.parts;

import javax.annotation.PostConstruct;

import org.eclipse.e4.ui.di.Focus;
import org.eclipse.swt.widgets.Composite;

public class DefinicaoPesquisadorPorPesquisaPart {

	@PostConstruct
	public void createComposite(Composite parent) {

	}

	@Focus
	public void setFocus() {

	}
}


text:
Luker
=====

This is a continuation of Konstantin Kudryashov's ResourceWatcher for Symfony2. It have been moved
from his fork and renamed Lurker to allow a wider adoption.

Still working on rename.

Getting Started
---------------

This should be written

Special Thanks
--------------

* [Konstantin Kudryashov](http://twitter.com/everzet) for the orignal code.


text:
require 'rubygems'
require 'sequel'
require 'bacon'

$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
$LOAD_PATH.unshift(File.dirname(__FILE__))


text:
<!doctype html>

	<meta http-equiv="Content-type" content="text/html; charset=utf-8">
	<title>Setting the event color through object properties </title>

	<link rel="stylesheet" href="../../codebase/dhtmlxscheduler.css" type="text/css" media="screen" title="no title" charset="utf-8">


text:
.. GPIO Zero: a library for controlling the Raspberry Pi's GPIO pins
.. Copyright (c) 2019 Dave Jones <dave@waveform.org.uk>
..
.. Redistribution and use in source and binary forms, with or without
.. modification, are permitted provided that the following conditions are met:
..
.. * Redistributions of source code must retain the above copyright notice,
..   this list of conditions and the following disclaimer.
..
.. * Redistributions in binary form must reproduce the above copyright notice,
..   this list of conditions and the following disclaimer in the documentation
..   and/or other materials provided with the distribution.
..
.. * Neither the name of the copyright holder nor the names of its contributors
..   may be used to endorse or promote products derived from this software
..   without specific prior written permission.
..
.. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
.. AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
.. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
.. ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
.. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
.. CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
.. SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
.. INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
.. CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
.. ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
.. POSSIBILITY OF SUCH DAMAGE.

===========
API - Tones
===========

.. module:: gpiozero.tones

GPIO Zero includes a :class:`Tone` class intended for use with the
:class:`~gpiozero.TonalBuzzer`. This class is in the ``tones`` module of GPIO
Zero and is typically imported as follows::

    from gpiozero.tones import Tone

Tone
====

.. autoclass:: Tone
    :members:


text:
<?php

namespace Tacit\Test\Controller;

use Tacit\Controller\RestfulItem;

class MockRestfulItem extends RestfulItem
{
    protected static $collectionName = 'mock_persistent';
    protected static $itemName = 'mock_persistent';
    protected static $modelClass = 'Tacit\\Test\\Model\\MockPersistent';
    protected static $name = 'MockRestfulItem';
    protected static $title = 'A Mock Restful Item';
    protected static $transformer = 'Tacit\\Transform\\PersistentTransformer';

    public static function keys()
    {
        return ['_id'];
    }
}