text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="HeatMapSeries.cs" company="OxyPlot">
//   The MIT License (MIT)
//
//   Copyright (c) 2012 Oystein Bjorke
//
//   Permission is hereby granted, free of charge, to any person obtaining a
//   copy of this software and associated documentation files (the
//   "Software"), to deal in the Software without restriction, including
//   without limitation the rights to use, copy, modify, merge, publish,
//   distribute, sublicense, and/or sell copies of the Software, and to
//   permit persons to whom the Software is furnished to do so, subject to
//   the following conditions:
//
//   The above copyright notice and this permission notice shall be included
//   in all copies or substantial portions of the Software.
//
//   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
//   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
//   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
//   IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
//   CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
//   TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
//   SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
// <summary>
//   The heat map series.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace OxyPlot.Series
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    using OxyPlot.Axes;

    /// <summary>
    /// The heat map series.
    /// </summary>
    /// <remarks>
    /// Does not work with Silverlight. Silverlight does not support bitmaps, only PNG and JPG.
    /// </remarks>
    public class HeatMapSeries : XYAxisSeries
    {
        /// <summary>
        /// The hash code of the current data.
        /// </summary>
        private int dataHash;

        /// <summary>
        /// The image
        /// </summary>
        private OxyImage image;

        /// <summary>
        /// Gets or sets the x 0.
        /// </summary>
        public double X0 { get; set; }

        /// <summary>
        /// Gets or sets the x 1.
        /// </summary>
        public double X1 { get; set; }

        /// <summary>
        /// Gets or sets the y 0.
        /// </summary>
        public double Y0 { get; set; }

        /// <summary>
        /// Gets or sets the y 1.
        /// </summary>
        public double Y1 { get; set; }

        /// <summary>
        /// Gets or sets the data.
        /// </summary>
        public double[,] Data { get; set; }

        /// <summary>
        /// Gets or sets the minimum value of the dataset.
        /// </summary>
        public double MinValue { get; protected set; }

        /// <summary>
        /// Gets or sets the maximum value of the dataset.
        /// </summary>
        public double MaxValue { get; protected set; }

        /// <summary>
        /// Gets or sets the color axis.
        /// </summary>
        /// <value>
        /// The color axis.
        /// </value>
        public ColorAxis ColorAxis { get; protected set; }

        /// <summary>
        /// Gets or sets the color axis key.
        /// </summary>
        /// <value> The color axis key. </value>
        public string ColorAxisKey { get; set; }

        /// <summary>
        /// Renders the series on the specified render context.
        /// </summary>
        /// <param name="rc">
        /// The rendering context.
        /// </param>
        /// <param name="model">
        /// The model.
        /// </param>
        public override void Render(IRenderContext rc, PlotModel model)
        {
            if (this.Data == null)
            {
                this.image = null;
                return;
            }

            int m = this.Data.GetLength(0);
            int n = this.Data.GetLength(1);
            double dx = (this.X1 - this.X0) / m;
            double left = this.X0 - (dx * 0.5);
            double right = this.X1 + (dx * 0.5);
            double dy = (this.Y1 - this.Y0) / n;
            double bottom = this.Y0 - (dy * 0.5);
            double top = this.Y1 + (dy * 0.5);
            var s00 = this.Transform(left, bottom);
            var s11 = this.Transform(right, top);
            var rect = OxyRect.Create(s00, s11);

            if (this.image == null || this.Data.GetHashCode() != this.dataHash)
            {
                this.UpdateImage();
                this.dataHash = this.Data.GetHashCode();
            }

            if (this.image != null)
            {
                var clip = this.GetClippingRect();
                rc.DrawClippedImage(clip, this.image, rect.Left, rect.Top, rect.Width, rect.Height, 1, true);
            }
        }

        /// <summary>
        /// Gets the point on the series that is nearest the specified point.
        /// </summary>
        /// <param name="point">
        /// The point.
        /// </param>
        /// <param name="interpolate">
        /// Interpolate the series if this flag is set to <c>true</c>.
        /// </param>
        /// <returns>
        /// A TrackerHitResult for the current hit.
        /// </returns>
        public override TrackerHitResult GetNearestPoint(ScreenPoint point, bool interpolate)
        {
            return null;
        }

        /// <summary>
        /// Ensures that the axes of the series is defined.
        /// </summary>
        protected internal override void EnsureAxes()
        {
            base.EnsureAxes();

            this.ColorAxis =
                this.PlotModel.GetAxisOrDefault(this.ColorAxisKey, this.PlotModel.DefaultColorAxis) as ColorAxis;
        }

        /// <summary>
        /// Updates the max/minimum values.
        /// </summary>
        protected internal override void UpdateMaxMin()
        {
            base.UpdateMaxMin();

            this.MinX = Math.Min(this.X0, this.X1);
            this.MaxX = Math.Max(this.X0, this.X1);

            this.MinY = Math.Min(this.Y0, this.Y1);
            this.MaxY = Math.Max(this.Y0, this.Y1);

            this.MinValue = this.GetData().Min();
            this.MaxValue = this.GetData().Max();

            this.XAxis.Include(this.MinX);
            this.XAxis.Include(this.MaxX);

            this.YAxis.Include(this.MinY);
            this.YAxis.Include(this.MaxY);

            this.ColorAxis.Include(this.MinValue);
            this.ColorAxis.Include(this.MaxValue);
        }

        /// <summary>
        /// Gets the data as a sequence (LINQ-friendly).
        /// </summary>
        /// <returns>The sequence of data.</returns>
        protected IEnumerable<double> GetData()
        {
            int m = this.Data.GetLength(0);
            int n = this.Data.GetLength(1);
            for (int i = 0; i < m; i++)
            {
                for (int j = 0; j < n; j++)
                {
                    yield return this.Data[i, j];
                }
            }
        }

        /// <summary>
        /// Updates the image.
        /// </summary>
        private void UpdateImage()
        {
            int m = this.Data.GetLength(0);
            int n = this.Data.GetLength(1);
            var buffer = new OxyColor[n, m];
            for (int i = 0; i < m; i++)
            {
                for (int j = 0; j < n; j++)
                {
                    buffer[j, i] = this.ColorAxis.GetColor(this.Data[i, j]);
                }
            }

            this.image = OxyImage.PngFromArgb(buffer);
        }
    }
}


text:
    charAt :: Number -> String -> String

    charCodeAt :: Number -> String -> Number

    drop :: Number -> String -> String

    fromCharCode :: Number -> String

    indexOf :: String -> String -> Number

    indexOf' :: String -> Number -> String -> Number

    joinWith :: String -> [String] -> String

    lastIndexOf :: String -> String -> Number

    lastIndexOf' :: String -> Number -> String -> Number

    length :: String -> Number

    localeCompare :: String -> String -> Number

    replace :: String -> String -> String -> String

    split :: String -> String -> [String]

    take :: Number -> String -> String

    toLower :: String -> String

    toUpper :: String -> String

    trim :: String -> String

## Module Data.String.Regex

### Types

    data Regex :: *

### Values

    match :: Regex -> String -> [String]

    regex :: String -> String -> Regex

    replace :: Regex -> String -> String -> String

    replace' :: Regex -> (String -> [String] -> String) -> String -> String

    search :: Regex -> String -> Number

    test :: Regex -> String -> Boolean

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Linq;

using Foundation;
using UIKit;

namespace Reducto.Sample.iOS
{
    [Register ("AppDelegate")]
    public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
    {
        public override bool FinishedLaunching (UIApplication app, NSDictionary options)
        {
            global::Xamarin.Forms.Forms.Init ();

            LoadApplication (new XamarinApp ());

            return base.FinishedLaunching (app, options);
        }
    }
}


text:
/

#include <algorithm>
#include <thread>
#include <unistd.h>
#include <string.h>

#include "GroupManager.h"

#define ACTION_DELIMITER "*"
#define DESC_DELIMITER "|"
#define ATTR_DELIMITER "="

using namespace OC;
using namespace OIC;

std::map< std::vector< std::string >, CandidateCallback > candidateRequest;
std::map< std::vector< std::string >, CandidateCallback > candidateRequestForTimer;
std::map< std::string, std::map< std::string, std::shared_ptr< OCResource > > > rtForResourceList;
std::vector< std::string > allFoundResourceTypes;
std::mutex callbackLock;

template< typename T >
bool IsSubset(std::vector< T > full, std::vector< T > sub)
{
    std::sort(full.begin(), full.end());
    std::sort(sub.begin(), sub.end());
    return std::includes(full.begin(), full.end(), sub.begin(), sub.end());
}
std::vector< std::string > &str_split(const std::string &s, char delim,
        std::vector< std::string > &elems)
{
    std::stringstream ss(s);
    std::string item;
    while (std::getline(ss, item, delim))
    {
        elems.push_back(item);
    }
    return elems;
}

std::vector< std::string > str_split(const std::string &s, char delim)
{
    std::vector< std::string > elems;
    str_split(s, delim, elems);
    return elems;
}

void GroupManager::onFoundResource(std::shared_ptr< OCResource > resource, int waitsec)
{

    std::string resourceURI;
    std::string hostAddress;
    try
    {
        // Do some operations with resource object.
        if (resource)
        {

            std::cout << "DISCOVERED Resource:" << std::endl;
            // Get the resource URI
            resourceURI = resource->uri();
            std::cout << "\tURI of the resource: " << resourceURI << std::endl;

            // Get the resource host address
            hostAddress = resource->host();
            std::cout << "\tHost address of the resource: " << hostAddress << std::endl;

            // Get the resource types
            std::cout << "\tList of resource types: " << std::endl;

            hostAddress.append(resourceURI);

            for (auto &resourceTypes : resource->getResourceTypes())
            {
                std::cout << "\t\t" << resourceTypes << std::endl;

                if (std::find(allFoundResourceTypes.begin(), allFoundResourceTypes.end(),
                        resourceTypes) == allFoundResourceTypes.end())
                {
                    allFoundResourceTypes.push_back(resourceTypes);
                }

                rtForResourceList[resourceTypes][hostAddress] = resource;
            }

            // Get the resource interfaces
            std::cout << "\tList of resource interfaces: " << std::endl;
            for (auto &resourceInterfaces : resource->getResourceInterfaces())
            {
                std::cout << "\t\t" << resourceInterfaces << std::endl;
            }

            if (waitsec == -1)
            {
                findPreparedRequest(candidateRequest);
            }
        }
        else
        {
            // Resource is invalid
            std::cout << "Resource is invalid" << std::endl;
        }

    }
    catch (std::exception& e)
    {
        //log(e.what());
    }
}

GroupManager::GroupManager(void)
{
    ;
}

/**
 * Virtual destructor
 */
GroupManager::~GroupManager(void)
{
    candidateRequest.clear();
    candidateRequestForTimer.clear();
    rtForResourceList.clear();
    allFoundResourceTypes.clear();
}

void GroupManager::findPreparedRequest(
        std::map< std::vector< std::string >, CandidateCallback > &request)
{
    std::lock_guard<std::mutex> lock(callbackLock);
    std::vector< std::shared_ptr< OCResource > > resources;

    for (auto it = request.begin(); it != request.end();)
    {

        if (IsSubset(allFoundResourceTypes, it->first))
        {
            for (unsigned int i = 0; i < it->first.size(); ++i)
            {

                for (auto secondIt = rtForResourceList[it->first.at(i)].begin();
                        secondIt != rtForResourceList[it->first.at(i)].end(); ++secondIt)
                {
                    //insert resource related to request
                    resources.push_back(secondIt->second);
                }
            }

            it->second(resources);

            //TODO : decide policy - callback only once
            request.erase(it++);
        }
        else
        {
            ++it;
        }

    }

}

void GroupManager::lazyCallback(int second)
{
    sleep(second);
    findPreparedRequest(candidateRequestForTimer);

}

OCStackResult GroupManager::findCandidateResources(
        std::vector< std::string > resourceTypes,
        CandidateCallback callback, int waitsec)
{
    std::cout << __func__ << std::endl;
    if (resourceTypes.size() < 1)
    {
        return OC_STACK_ERROR;
    }
    if(callback == NULL)
    {
        return OC_STACK_ERROR;
    }

    std::sort(resourceTypes.begin(), resourceTypes.end());
    resourceTypes.erase(std::unique(resourceTypes.begin(), resourceTypes.end()),
            resourceTypes.end());

    if (waitsec >= 0)
    {
        candidateRequestForTimer.insert(std::make_pair(resourceTypes, callback));
    }
    else
    {
        candidateRequest.insert(std::make_pair(resourceTypes, callback));
    }

    for (unsigned int i = 0; i < resourceTypes.size(); ++i)
    {
        // std::cout << "resourceTypes : " << resourceTypes.at(i) << std::endl;

        std::string query = OC_RSRVD_WELL_KNOWN_URI;
        query.append("?rt=");
        query.append(resourceTypes.at(i));

        OCPlatform::findResource("",
                query,
                CT_DEFAULT,
                std::function < void(std::shared_ptr < OCResource > resource)
                        > (std::bind(&GroupManager::onFoundResource, this, std::placeholders::_1,
                                waitsec)));
    }

    if (waitsec >= 0)
    {
        std::thread exec(
                std::function< void(int second) >(
                        std::bind(&GroupManager::lazyCallback, this, std::placeholders::_1)),
                waitsec);
        exec.detach();
    }

    return OC_STACK_OK;
}

OCStackResult GroupManager::bindResourceToGroup(OCResourceHandle& childHandle, std::shared_ptr< OCResource > resource, OCResourceHandle& collectionHandle)
{

    OCStackResult result = OCPlatform::registerResource(childHandle, resource);

    cout << "\tresource registed!" << endl;

    if(result == OC_STACK_OK)
    {
        OCPlatform::bindResource(collectionHandle, childHandle);
    }
    else
    {
        cout << "\tresource Error!" << endl;
    }

    return result;
 }

/*
 Presence Check
 */

std::map< std::string, CollectionPresenceCallback > presenceCallbacks;

// Callback to presence
void GroupManager::collectionPresenceHandler(OCStackResult result, const unsigned int nonce,
        const std::string& /*hostAddress*/, std::string host, std::string uri)
{
    std::cout << "uri : " << uri << std::endl;
    std::cout << "host : " << host << std::endl;
    std::cout << "result : " << result << std::endl;
    switch (result)
    {
        case OC_STACK_OK:
            std::cout << "Nonce# " << nonce << std::endl;
            break;
        case OC_STACK_PRESENCE_STOPPED:
            std::cout << "Presence Stopped\n";
            break;
        case OC_STACK_PRESENCE_DO_NOT_HANDLE:
            std::cout << "Presence do not handle\n";
            break;
        case OC_STACK_PRESENCE_TIMEOUT:
            std::cout << "Presence TIMEOUT\n";
            break;
        default:
            std::cout << "Error\n";
            break;
    }

    if (presenceCallbacks.find(uri) != presenceCallbacks.end())
    {
        (presenceCallbacks.find(uri)->second)(uri, result);
    }
}

void GroupManager::checkCollectionRepresentation(const OCRepresentation& rep,
        CollectionPresenceCallback callback)
{
    std::cout << "\tResource URI: " << rep.getUri() << std::endl;

    std::vector< OCRepresentation > children = rep.getChildren();
    if(children.size() == 0 )
    {
        callback("", OC_STACK_ERROR);
        return;
    }

    for (auto oit = children.begin(); oit != children.end(); ++oit)
    {
        if(oit->getUri().find("coap://") == std::string::npos)
        {
            std::cout << "The resource with a URI " << oit->getUri() << " is not a remote resource."
                << " Thus, we ignore to send a request for presence check to the resource.\n";

            continue;
        }

        std::vector< std::string > hostAddressVector = str_split(oit->getUri(), '/');
        std::string hostAddress = "";
        for (unsigned int i = 0; i < hostAddressVector.size(); ++i)
        {
            if (i < 3)
            {
                hostAddress.append(hostAddressVector.at(i));
                if (i != 2)
                {
                    hostAddress.append("/");
                }
            }
        }

        std::vector< std::string > resourceTypes = oit->getResourceTypes();
        // for (unsigned int i = 0; i < resourceTypes.size(); ++i)
        // {
        //     std::cout << "\t\t\tresourcetype :" << resourceTypes.at(i) << std::endl;
        // }

        // std::string resourceType = "core.";
        // resourceType.append(str_split(oit->getUri(), '/').at(4));
        // std::cout << "\t\tconvertRT : " << resourceType << std::endl;
        // std::cout << "\t\tresource type front : " << resourceTypes.front() << endl;
        // std::cout << "\t\thost : " << hostAddress << std::endl;
        OCPlatform::OCPresenceHandle presenceHandle;
        OCStackResult result = OC_STACK_ERROR;

        try
        {
            result = OCPlatform::subscribePresence(presenceHandle, hostAddress,
                    // resourceType,
                    resourceTypes.front(),
                    CT_DEFAULT,
                    std::function<
                            void(OCStackResult result, const unsigned int nonce,
                                    const std::string& hostAddress) >(
                            std::bind(&GroupManager::collectionPresenceHandler, this,
                                    std::placeholders::_1, std::placeholders::_2,
                                    std::placeholders::_3, hostAddress, oit->getUri())));
        }catch(OCException& e)
        {
            std::cout<< "Exception in subscribePresence: "<< e.what() << std::endl;
        }

        if (result == OC_STACK_OK)
        {
            presenceCallbacks.insert(std::make_pair(oit->getUri(), callback));
        }
        else
        {
            callback("", OC_STACK_ERROR);
        }
    }
}

void GroupManager::onGetForPresence(const HeaderOptions& /*headerOptions*/,
        const OCRepresentation& rep, const int eCode, CollectionPresenceCallback callback)
{
    if (eCode == OC_STACK_OK)
    {
        std::cout << "GET request was successful" << std::endl;
        std::cout << "Resource URI: " << rep.getUri() << std::endl;

        checkCollectionRepresentation(rep, callback);

    }
    else
    {
        std::cout << "onGET Response error: " << eCode << std::endl;
        callback("", OC_STACK_ERROR);
    }
}

OCStackResult GroupManager::subscribeCollectionPresence(
        std::shared_ptr< OCResource > collectionResource, CollectionPresenceCallback callback)
{
    if(callback == NULL || collectionResource == NULL)
    {
        return OC_STACK_ERROR;
    }

    OCStackResult result = OC_STACK_OK;
    //callback("core.room",OC_STACK_OK);

    QueryParamsMap queryParam;

    //parameter 1 = resourceType
    collectionResource->get("", DEFAULT_INTERFACE, queryParam,
            std::function<
                    void(const HeaderOptions& headerOptions, const OCRepresentation& rep,
                            const int eCode) >(
                    std::bind(&GroupManager::onGetForPresence, this, std::placeholders::_1,
                            std::placeholders::_2, std::placeholders::_3, callback)));

    return result;
}

/*
 Group Action
 */

std::string GroupManager::getStringFromActionSet(const ActionSet *newActionSet)
{
    std::string message = "";

    if(newActionSet == NULL)
        return message;

    message = newActionSet->actionsetName;
    message.append("*");
    message.append(newActionSet->toString());
    message.append("*");
    for (auto iterAction = newActionSet->listOfAction.begin();
            iterAction != newActionSet->listOfAction.end(); iterAction++)
    {
        message.append("uri=");
        message.append((*iterAction)->target);
        message.append("|");

        for (auto iterCapa = (*iterAction)->listOfCapability.begin();
                iterCapa != (*iterAction)->listOfCapability.end(); iterCapa++)
        {
            message.append((*iterCapa)->capability);
            message.append("=");
            message.append((*iterCapa)->status);

            if (iterCapa + 1 != (*iterAction)->listOfCapability.end())
                message.append("|");
        }

        if (iterAction + 1 != newActionSet->listOfAction.end())
        {
            message.append("*");
        }
    }

    return message;
}

#define DELETE(p) { \
    delete p; \
    p = NULL; \
}

#define DELETEARRAY(p) { \
    delete[] p; \
    p = NULL; \
}

ActionSet* GroupManager::getActionSetfromString(std::string description)
{
    char *token = NULL;
    char *plainText = NULL;
    char *plainPtr = NULL;
    char *attr = NULL, *desc = NULL;

    Action *action = NULL;
    Capability *capa = NULL;
    ActionSet *actionset = new ActionSet();

    if(actionset == NULL)
    {
        goto exit;
    }

    if(description.empty())
    {
        goto exit;
    }
    else if(description.at(0) == '*')
    {
        goto exit;
    }

    plainText = new char[(description.length() + 1)];
    strncpy(plainText, description.c_str(), description.length()+1);

    // All tokens are seperated by "*" character.
    // First token means an actionset name
    token = strtok_r(plainText, ACTION_DELIMITER, &plainPtr);

    if (token != NULL)
    {
        actionset->actionsetName = std::string(token);

        if((actionset->actionsetName).empty())
            goto exit;

        // Find the second token
        token = strtok_r(NULL, ACTION_DELIMITER, &plainPtr);
    }
    else
    {
        goto exit;
    }

    if (token != NULL)
    {
        // The second token consists of two digits: time delay and actionset Type.
        // Time delay is used as a parameter to scheduled/recursive group action feature
        // And actionset type indicates if the actionset is scheduled or recursive group action.
        char *subText = NULL;
        char *subToken = NULL;
        char *subTextPtr = NULL;

        subText = new char[strlen(token)+1];
        strncpy(subText, token, strlen(token)+1);

        subToken = strtok_r(subText, " ", &subTextPtr);
        if(subToken == NULL)
        {
            DELETEARRAY(subText);
            goto exit;
        }
        actionset->mDelay = atol(subToken);

        subToken = strtok_r(NULL, " ", &subTextPtr);
        if(subToken == NULL)
        {
            DELETEARRAY(subText);
            goto exit;
        }
        actionset->type = (OIC::ACTIONSET_TYPE)atoi(subToken);

        DELETEARRAY(subText);

        // Find the third token
        token = strtok_r(NULL, ACTION_DELIMITER, &plainPtr);
    }
    else
    {
        goto exit;
    }

    while (token)
    {
        // The third token consists of two sub-segement: host address plus URI and attribute key/value pair.
        // These two segments can be divided by "|" character.
        // The third token can be repeatively appeared.

        char *descPtr = NULL;
        desc = new char[(strlen(token) + 1)];

        if (desc != NULL)
        {
            // copy a host address plus URI string from the third token
            strncpy(desc, token, (strlen(token) + 1));

            // Find "|" character to find key/value pair
            token = strtok_r(desc, DESC_DELIMITER, &descPtr);

            while (token != NULL)
            {
                char *attrPtr = NULL;
                attr = new char[(strlen(token) + 1)];
                // copy the host address plus URI string
                strcpy(attr, token);

                // Find "=" charactor to divide attribute key and value string.
                token = strtok_r(attr, ATTR_DELIMITER, &attrPtr);
                while (token != NULL)
                {
                    if ( (action == NULL) && strcmp(token, "uri") == 0)
                    {
                        token = strtok_r(NULL, ATTR_DELIMITER, &attrPtr);
                        if(token == NULL)
                        {
                            goto exit;
                        }

                        action = new Action();
                        if (action != NULL)
                        {
                            action->target = std::string(token);
                        }
                        else
                        {
                            goto exit;
                        }
                    }
                    else
                    {
                        capa = new Capability();
                        capa->capability = std::string(token);
                        token = strtok_r(NULL, ATTR_DELIMITER, &attrPtr);

                        if( token == NULL )
                            goto exit;

                        capa->status = std::string(token);

                        if (action != NULL)
                            action->listOfCapability.push_back(capa);
                        else
                            goto exit;
                    }

                    token = strtok_r(NULL, ATTR_DELIMITER, &attrPtr);
                }
                DELETEARRAY(attr);
                token = strtok_r(NULL, DESC_DELIMITER, &descPtr);
            }

            if( action != NULL )
            {
                actionset->listOfAction.push_back(action);
                action = NULL;
            }
            else
                goto exit;
            //delete action;
        }
        else
        {
            goto exit;
        }

        DELETEARRAY(desc);

        token = strtok_r(NULL, ACTION_DELIMITER, &plainPtr);
    }

    DELETEARRAY(plainText);
    return actionset;

exit:
    DELETE(action);
    DELETE(capa)
    DELETE(actionset)
    DELETEARRAY(attr);
    DELETEARRAY(plainText);
    DELETEARRAY(desc);
    return NULL;
}

OCStackResult GroupManager::addActionSet(std::shared_ptr< OCResource > resource,
        const ActionSet* newActionSet, PutCallback cb)
{
    // BUILD message of ActionSet which it is included delimiter.
    if ((resource != NULL) && (newActionSet != NULL))
    {
        if(newActionSet->mDelay < 0)
        {
            return OC_STACK_INVALID_PARAM;
        }

        std::string message = getStringFromActionSet(newActionSet);

        OCRepresentation rep;
        rep.setValue("ActionSet", message);
        return resource->put(resource->getResourceTypes().front(), GROUP_INTERFACE, rep,
                QueryParamsMap(), cb);
    }
    else
    {
        return OC_STACK_ERROR;
    }
}

OCStackResult GroupManager::executeActionSet(std::shared_ptr< OCResource > resource,
        std::string actionsetName, PostCallback cb)
{
    if (resource != NULL)
    {
        OCRepresentation rep;

        rep.setValue("DoAction", actionsetName);
        return resource->post(resource->getResourceTypes().front(), GROUP_INTERFACE, rep,
                QueryParamsMap(), cb);
    }
    else
    {
        return OC_STACK_ERROR;
    }
}

OCStackResult GroupManager::executeActionSet(std::shared_ptr< OCResource > resource,
        std::string actionsetName, long int delay, PostCallback cb)
{
    if(delay <= 0 )
    {
        return OC_STACK_INVALID_PARAM;
    }
    if (resource != NULL)
    {
        std::string value = actionsetName;
        value.append("*");
        value.append(std::to_string(delay));

        OCRepresentation rep;
        rep.setValue("DoScheduledAction", value);
        return resource->post(resource->getResourceTypes().front(), GROUP_INTERFACE, rep,
                QueryParamsMap(), cb);
    }
    else
    {
        return OC_STACK_ERROR;
    }
}

OCStackResult GroupManager::cancelActionSet(std::shared_ptr< OCResource > resource,
        std::string actionsetName, PostCallback cb)
{
    if (resource != NULL)
    {
        OCRepresentation rep;

        rep.setValue("CancelAction", actionsetName);
        return resource->post(resource->getResourceTypes().front(), GROUP_INTERFACE, rep,
                QueryParamsMap(), cb);
    }
    else
    {
        return OC_STACK_ERROR;
    }
}

OCStackResult GroupManager::getActionSet(std::shared_ptr< OCResource > resource,
        std::string actionsetName, PostCallback cb)
{
    if (resource != NULL)
    {
        OCRepresentation rep;

        rep.setValue("GetActionSet", actionsetName);

        return resource->post(resource->getResourceTypes().front(), GROUP_INTERFACE, rep,
                QueryParamsMap(), cb);
    }
    else
    {
        return OC_STACK_ERROR;
    }
}

OCStackResult GroupManager::deleteActionSet(std::shared_ptr< OCResource > resource,
        std::string actionsetName, PutCallback cb)
{
    if (resource != NULL)
    {
        OCRepresentation rep;

        rep.setValue("DelActionSet", actionsetName);

        return resource->put(resource->getResourceTypes().front(), GROUP_INTERFACE, rep,
                QueryParamsMap(), cb);
    }
    else
    {
        return OC_STACK_ERROR;
    }
}


text:
<?php

namespace sndsgd\field\rule;

use \sndsgd\Field;
use \sndsgd\field\Collection;
use \sndsgd\field\Error;

/**
 * Ensure a value isn't empty or null
 */
class RequiredRule extends \sndsgd\field\Rule
{
    /**
     * {@inheritdoc}
     */
    protected $message = 'this is a required field';

    /**
     * {@inheritdoc}
     */
    public function validate()
    {
        return ($this->value !== null && $this->value !== '');
    }
}


text:
dojo.provide("widgets.ResetSelectors");

dojo.require("dijit._Widget");
dojo.require("dijit._Templated");
dojo.require("dojo.cache");

dojo.declare("widgets.ResetSelectors", [ dijit._Widget, dijit._Templated ], {
    "templateString": dojo.cache("widgets",
                                 "templates/ResetSelectors.html"),
    "properties": {}
});


text:
package cmdr

import (
	"flag"
	"sort"
)

type (
	// Commands is a mapping of strings (the command name) to commands.
	Commands map[string]Command
	// Command is a command that can be invoked.
	Command interface {
		// Help is the help message for a command. To be a command, all you need
		// is a help message.
		// Help messages must follow this convention:
		// The first line must be 50 characters or fewer, and describe
		// succinctly what the command does.
		// The second line must be blank.
		// The remainder of the string is free-form text.
		Help() string
	}
	// Executor is a command can itself be executed to do something.
	Executor interface {
		Execute(args []string) Result
	}
	// Subcommander means this command has subcommands.
	Subcommander interface {
		// Subcommands returns a map of command names to Commands.
		Subcommands() Commands
	}
	// AddsFlags means this command has flags to add. These flags will be
	// available not only to this command, but will still be read, and have
	// impact on this command, even if the user applies them to deeper
	// subcommands.
	AddsFlags interface {
		// AddFlags will be passed a flag.FlagSet already named correctly for
		// this command. All you need to do is add whatever flag definitions
		// apply to this command.
		AddFlags(*flag.FlagSet)
	}
)

// SortedKeys returns the names of the commands in alphabetical order.
func (cs Commands) SortedKeys() []string {
	keys := make([]string, len(cs))
	i := 0
	for k := range cs {
		keys[i] = k
		i++
	}
	sort.Strings(keys)
	return keys
}


text:
class A {
    public boolean foo(boolean a, boolean b, boolean c, boolean d) {

      if (!(a |<caret>| b) || c || d)
        return false;
      return true;
    }
}


text:
struct TRI_vocbase_t;

namespace arangodb {
// forward declarations
namespace velocypack {
class Slice;
}

namespace aql {
struct QueryResult;
}

namespace tests {

namespace aql {

/// @brief Tests if the given QueryResult matches the given expected value
///        Expected is required to be an Array (maybe empty). As AQL can only
///        return a cursor, that is transformed into an Array.
///        Ordering matters. Also asserts that query was successful.
void AssertQueryResultToSlice(arangodb::aql::QueryResult const& result,
                              arangodb::velocypack::Slice expected);

/// @brief Tests if executing the given query on the given database results in the given expected value
///        Expected is required to be an Array (maybe empty). As AQL can only
///        return a cursor, that is transformed into an Array.
///        Ordering matters. Also asserts that query was successful.
void AssertQueryHasResult(TRI_vocbase_t& database, std::string const& queryString,
                          arangodb::velocypack::Slice expected);

/// @brief Tests if executing the given query on the given database results in the given error
///        Requires the query to error. Testing of no-error (TRI_ERROR_NO_ERROR) is not possible.
void AssertQueryFailsWith(TRI_vocbase_t& database, std::string const& query,
                          ErrorCode errorNumber);

}  // namespace aql
}  // namespace tests

}  // namespace arangodb


text:
<?php
/**
 * Created by IntelliJ IDEA.
 * User: tomfun
 * Date: 17.08.14
 * Time: 18:24
 */
namespace Tommy\Pymnt\MainBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Payment
 *
 * @ORM\Table(name="payment")
 * @ORM\Entity(repositoryClass="Tommy\Pymnt\MainBundle\Repo\PaymentRepository")
 */
class Payment
{
    /**
     * @var integer $id
     *
     * @ORM\Column(name="id", type="bigint")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    protected $id;

    /**
     * If null then payment to store
     * @var Part $partTo
     *
     * @ORM\ManyToOne(targetEntity="Part", inversedBy="payments")
     * @ORM\JoinColumn(name="part_to_id", referencedColumnName="id", nullable=true)
     */
    protected $partTo;

    /**
     * @var Part $partFrom
     *
     * @ORM\ManyToOne(targetEntity="Part", inversedBy="paymentsFrom")
     * @ORM\JoinColumn(name="part_from_id", referencedColumnName="id", nullable=false)
     */
    protected $partFrom;

    /**
     * @var string $description
     *
     * @ORM\Column(name="description", type="string", length=255, nullable=false)
     */
    protected $description;

    /**
     * @var float $amount
     *
     * @ORM\Column(name="amount", type="decimal", nullable=false)
     */
    protected $amount;

    /**
     * @var \Datetime $createdAt
     *
     * @ORM\Column(name="created_at", type="datetime", nullable=false)
     */
    protected $createdAt;

    public function __construct()
    {
        $this->createdAt = new \DateTime();
    }

    /**
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @return float
     */
    public function getAmount()
    {
        return $this->amount;
    }

    /**
     * @param float $amount
     */
    public function setAmount($amount)
    {
        $this->amount = $amount;
    }

    /**
     * @return \Datetime
     */
    public function getCreatedAt()
    {
        return $this->createdAt;
    }

    /**
     * @param \Datetime $createdAt
     */
    public function setCreatedAt($createdAt)
    {
        $this->createdAt = $createdAt;
    }

    /**
     * @return string
     */
    public function getDescription()
    {
        return $this->description;
    }

    /**
     * @param string $description
     */
    public function setDescription($description)
    {
        $this->description = $description;
    }

    /**
     * @return Part
     */
    public function getPartFrom()
    {
        return $this->partFrom;
    }

    /**
     * @param Part $partFrom
     */
    public function setPartFrom($partFrom)
    {
        $this->partFrom = $partFrom;
    }

    /**
     * @return Part
     */
    public function getPartTo()
    {
        return $this->partTo;
    }

    /**
     * @param Part $partTo
     */
    public function setPartTo($partTo)
    {
        $this->partTo = $partTo;
    }

}


text:
@interface CHTTPDefaultHandler ()
@property (readwrite, nonatomic, retain) NSDictionary *defaultHeaders;
@end

#pragma mark -

@implementation CHTTPDefaultHandler

@synthesize defaultHeaders;

- (id)init
{
if ((self = [super init]) != NULL)
	{
	if (defaultHeaders == NULL)
		{
		NSDictionary *theDefaultHeaders = [NSDictionary dictionaryWithObjectsAndKeys:
			@"TouchHTTPD/0.0.1 (Unix) (Mac OS X)", @"Server",
			NULL];
		defaultHeaders = theDefaultHeaders;
		}
	}
return(self);
}

- (id)initWithDefaultHeaders:(NSDictionary *)inDefaultHeaders
{
if ((self = [self init]) != NULL)
	{
	defaultHeaders = inDefaultHeaders;
	}
return(self);
}

#pragma mark -

- (BOOL)handleRequest:(CHTTPMessage *)inRequest forConnection:(CHTTPConnection *)inConnection response:(CHTTPMessage **)ioResponse error:(NSError **)outError;
{
#pragma unused (inRequest, inConnection, outError)

CHTTPMessage *theResponse = *ioResponse;

for (NSString *theHeader in self.defaultHeaders)
	{
	if ([theResponse headerForKey:theHeader] == NULL)
		{
		NSString *theValue = [self.defaultHeaders objectForKey:theHeader];
		[theResponse setHeader:theValue forKey:theHeader];
		}
	}

if ([theResponse responseStatusCode] >= 200 && [theResponse headerForKey:@"Date"] == NULL)
	{
	[theResponse setHeader:[[NSDate date] RFC822String] forKey:@"Date"];
	}

// Tue, 15 Nov 1994 08:12:31 GMT

return(YES);
}

@end


text:
package util

import (
	"net"
	"net/http"
	"net/url"
	"time"

	log "github.com/Sirupsen/logrus"
	"github.com/rcrowley/go-metrics"
)

// The variables to hold the statistics
var parallelRequestCount int = 0
var timeOfLastNOK time.Time = time.Now()
var timeOfLastOK time.Time = time.Now()

var c metrics.Meter

// An extension of the ResponseWriter that can record the
// HTTP status codes sent out
// Design taken from Gorilla
type statLogger struct {
	w      http.ResponseWriter
	size   int
	status int
}

type statResponseWriter interface {
	http.ResponseWriter
	Status() int
	Size() int
}

func MakeLogger(w http.ResponseWriter) statResponseWriter {
	var l statResponseWriter = &statLogger{w: w}
	return l
}

func (l *statLogger) Header() http.Header {
	return l.w.Header()
}

func (l *statLogger) Write(b []byte) (int, error) {
	// 200 if nothing has been set
	if l.status == 0 {
		l.status = http.StatusOK
	}
	size, err := l.w.Write(b)
	l.size += size
	return size, err
}

func (l *statLogger) WriteHeader(s int) {
	l.w.WriteHeader(s)
	l.status = s
}

func (l *statLogger) Status() int {
	return l.status
}

func (l *statLogger) Size() int {
	return l.size
}

// HTTP logging handler
func LoggingHandler(inner http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		sw := MakeLogger(w)
		inner.ServeHTTP(sw, r)

		logHTTP(r, *r.URL, time.Now(), sw.Status(), sw.Size())
	})
}

// buildCommonLogLine builds a log entry for req in Apache Common Log Format.
// ts is the timestamp with which the entry should be logged.
// status and size are used to provide the response HTTP status and size.
// Copied from gorilla/handlers/handlers.go, converted to strings instead of byte[]
func logHTTP(req *http.Request, url url.URL, ts time.Time, status int, size int) {
	host, _, err := net.SplitHostPort(req.RemoteAddr)

	if err != nil {
		host = req.RemoteAddr
	}

	uri := req.RequestURI

	// Requests using the CONNECT method over HTTP/2.0 must use
	// the authority field (aka r.Host) to identify the target.
	// Refer: https://httpwg.github.io/specs/rfc7540.html#CONNECT
	if req.ProtoMajor == 2 && req.Method == "CONNECT" {
		uri = req.Host
	}
	if uri == "" {
		uri = url.RequestURI()
	}

	log.WithFields(log.Fields{
		"host": host,
		"method": req.Method,
		"uri": uri,
		"proto": req.Proto,
		"status": status,
		"size": size,
	}).Info(status)
}

// Stats is a handler for displaying API statistics
func StatsHandler(w http.ResponseWriter, r *http.Request) {
	SendHeaders(w)
	w.WriteHeader(http.StatusOK)
	metrics.WriteJSONOnce(metrics.DefaultRegistry, w)
}

func SendHeaders(w http.ResponseWriter) {
	w.Header().Set("Content-Type", "application/json; charset=UTF-8")
}


text:
.class Lo/xt;
.super Lo/vv;

# static fields
.field private static final ˊ:Ljava/lang/String;

# instance fields
.field private final ˋ:Landroid/content/Context;

# direct methods
.method static constructor <clinit>()V
    .locals 1

    sget-object v0, Lo/gk;->ᐝ:Lo/gk;

    invoke-virtual {v0}, Lo/gk;->toString()Ljava/lang/String;

    move-result-object v0

    sput-object v0, Lo/xt;->ˊ:Ljava/lang/String;

    return-void
.end method

.method public constructor <init>(Landroid/content/Context;)V
    .locals 2

    sget-object v0, Lo/xt;->ˊ:Ljava/lang/String;

    const/4 v1, 0x0

    new-array v1, v1, [Ljava/lang/String;

    invoke-direct {p0, v0, v1}, Lo/vv;-><init>(Ljava/lang/String;[Ljava/lang/String;)V

    iput-object p1, p0, Lo/xt;->ˋ:Landroid/content/Context;

    return-void
.end method

# virtual methods
.method public ˊ(Ljava/util/Map;)Lo/io$if;
    .locals 4
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(Ljava/util/Map<Ljava/lang/String;Lo/io$if;>;)Lo/io$if;"
        }
    .end annotation

    :try_start_0
    iget-object v0, p0, Lo/xt;->ˋ:Landroid/content/Context;

    invoke-virtual {v0}, Landroid/content/Context;->getPackageManager()Landroid/content/pm/PackageManager;

    move-result-object v0

    iget-object v1, p0, Lo/xt;->ˋ:Landroid/content/Context;

    invoke-virtual {v1}, Landroid/content/Context;->getPackageName()Ljava/lang/String;

    move-result-object v1

    const/4 v2, 0x0

    invoke-virtual {v0, v1, v2}, Landroid/content/pm/PackageManager;->getPackageInfo(Ljava/lang/String;I)Landroid/content/pm/PackageInfo;

    move-result-object v3

    iget v0, v3, Landroid/content/pm/PackageInfo;->versionCode:I

    invoke-static {v0}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer;

    move-result-object v0

    invoke-static {v0}, Lo/xl;->ʻ(Ljava/lang/Object;)Lo/io$if;
    :try_end_0
    .catch Landroid/content/pm/PackageManager$NameNotFoundException; {:try_start_0 .. :try_end_0} :catch_0

    move-result-object v0

    return-object v0

    :catch_0
    move-exception v3

    new-instance v0, Ljava/lang/StringBuilder;

    invoke-direct {v0}, Ljava/lang/StringBuilder;-><init>()V

    const-string v1, "Package name "

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    iget-object v1, p0, Lo/xt;->ˋ:Landroid/content/Context;

    invoke-virtual {v1}, Landroid/content/Context;->getPackageName()Ljava/lang/String;

    move-result-object v1

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    const-string v1, " not found. "

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    invoke-virtual {v3}, Landroid/content/pm/PackageManager$NameNotFoundException;->getMessage()Ljava/lang/String;

    move-result-object v1

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    invoke-virtual {v0}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v0

    invoke-static {v0}, Lo/vW;->ˊ(Ljava/lang/String;)V

    invoke-static {}, Lo/xl;->'()Lo/io$if;

    move-result-object v0

    return-object v0
.end method

.method public ˊ()Z
    .locals 1

    const/4 v0, 0x1

    return v0
.end method


text:
package org.snmp4j.smi;

public interface AssignableFromLong {

  void setValue(long value);

  long toLong();
}


text:
// <auto-generated> This file has been auto generated by EF Core Power Tools. </auto-generated>
#nullable disable
using System;
using System.Collections.Generic;

namespace AdefHelpDeskBase.Models.DataContext
{
    public partial class AdefHelpDeskTasks
    {
        public AdefHelpDeskTasks()
        {
            AdefHelpDeskLog = new HashSet<AdefHelpDeskLog>();
            AdefHelpDeskTaskAssociations = new HashSet<AdefHelpDeskTaskAssociations>();
            AdefHelpDeskTaskCategories = new HashSet<AdefHelpDeskTaskCategories>();
            AdefHelpDeskTaskDetails = new HashSet<AdefHelpDeskTaskDetails>();
        }

        public int TaskId { get; set; }
        public int PortalId { get; set; }
        public string Description { get; set; }
        public string Status { get; set; }
        public string Priority { get; set; }
        public DateTime CreatedDate { get; set; }
        public DateTime? EstimatedStart { get; set; }
        public DateTime? EstimatedCompletion { get; set; }
        public DateTime? DueDate { get; set; }
        public int AssignedRoleId { get; set; }
        public string TicketPassword { get; set; }
        public int RequesterUserId { get; set; }
        public string RequesterName { get; set; }
        public string RequesterEmail { get; set; }
        public string RequesterPhone { get; set; }
        public int? EstimatedHours { get; set; }

        public virtual ICollection<AdefHelpDeskLog> AdefHelpDeskLog { get; set; }
        public virtual ICollection<AdefHelpDeskTaskAssociations> AdefHelpDeskTaskAssociations { get; set; }
        public virtual ICollection<AdefHelpDeskTaskCategories> AdefHelpDeskTaskCategories { get; set; }
        public virtual ICollection<AdefHelpDeskTaskDetails> AdefHelpDeskTaskDetails { get; set; }
    }
}


text:
namespace StringBuilder.Substring
{
    using System;
    using System.Text;

     static class SubStrigBuilderExt
    {
        public static StringBuilder SubString(this StringBuilder builder, int index, int length)
        {
            StringBuilder subStr = new StringBuilder();

            for (int i = index; i <= length + index; i++)
            {
                subStr.Append(builder[i]);
            }

            return subStr;
        }
    }
}


text:
use strict;
use warnings;

use FindBin;
use lib ("$FindBin::RealBin/../../PerlLib");
use SAM_reader;
use SAM_entry;

my $usage = "\n\nusage: name_sorted_paired_reads.sam [debug]\n\n";

my $sam_file = $ARGV[0] or die $usage;
my $DEBUG = $ARGV[1] || 0;

if ($sam_file =~ /coord/i) {
    die "Your filename contains the term 'coord' which makes me nervous.  This needs to be a name-sorted SAM file. Please rename the file or use the correct version here\n.";
}

my $DEBUG_OFH;
if ($DEBUG) {
    open ($DEBUG_OFH, ">_debug.nameSorted_frag_classes") or die $!;
}

=notes

Gathers all reads having the same core read name (both left and right reads of PE frags).

Separates the left and right reads into corresponding lists.

Examines pairwise comparisons between left and right reads, check for same scaffold and that the right reads mate aligned coordinate matches up with that of the left reads aligned coordinate.

If not properly paired:
    have both left and right reads mapped anywhere:  improper pair
Otherwise, left-only or right-only counts.

=cut

main: {

    my $prev_read_name = "";
    my $prev_scaff_name = "";

    my @reads;

    my %counts = ( 'UPP' => 0, # unique proper pairs
                   'MPP' => 0, # multi-mapped proper pairs

                   'IP' => 0, # improper pairs

                   'UL' => 0, # left unique reads
                   'ML' => 0, # left multi-mapped reads

                   'UR' => 0, # right unique reads
                   'MR' => 0, # right multi-mapped reads

                   'US' => 0, # single unique-reads
                   'MS' => 0, # single multi-mapped reads
        );

    my $line_counter = 0;

    my $sam_reader = new SAM_reader($sam_file);
    while ($sam_reader->has_next()) {

        $line_counter++;

        my $read = $sam_reader->get_next();

        if ($read->is_query_unmapped()) { next; }

        my $scaff_name = $read->get_scaffold_name();
        my $core_read_name = $read->get_core_read_name();

        if ($core_read_name ne $prev_read_name) {

            if (@reads) {
                &process_pairs(\@reads, \%counts);
                @reads = ();
            }
        }

        push (@reads, $read);

        $prev_read_name = $core_read_name;
        $prev_scaff_name = $scaff_name;

        if ($line_counter % 100000 == 0) {
            my $count_print = $line_counter;
            $count_print=~ s/(\d)(?=(\d{3})+(\D|$))/$1\,/g;
            print STDERR "\r[$count_print]  lines read ";
        }

    }

    print STDERR "\n\n";

    &process_pairs(\@reads, \%counts) if @reads;

    my $sum_reads = 0;
    foreach my $count (values %counts) {
        $sum_reads += $count;
    }

=try_mirror_bowtie2_summary

30575 reads; of these:
  30575 (100.00%) were paired; of these:
    2577 (8.43%) aligned concordantly 0 times
    5766 (18.86%) aligned concordantly exactly 1 time
    22232 (72.71%) aligned concordantly >1 times
    ----
    2577 pairs aligned concordantly 0 times; of these:
      133 (5.16%) aligned discordantly 1 time
    ----
    2444 pairs aligned 0 times concordantly or discordantly; of these:
      4888 mates make up the pairs; of these:
        3588 (73.40%) aligned 0 times
        322 (6.59%) aligned exactly 1 time
        978 (20.01%) aligned >1 times
94.13% overall alignment rate

=cut

    print "Stats for aligned rna-seq fragments (note, not counting those frags where neither left/right read aligned)\n";
    print "\n\n$sum_reads aligned fragments; of these:\n";
    print "  " . ($sum_reads - $counts{US} - $counts{MS}) . " were paired; of these:\n";
    print "    " . ($counts{UL} + $counts{ML} + $counts{UR} + $counts{MR} + $counts{IP}) . " aligned concordantly 0 times\n";
    print "    " . $counts{UPP} . " aligned concordantly exactly 1 time\n";
    print "    " . $counts{MPP} . " aligned concordantly >1 times\n";
    print "    ----\n";
    print "    " . ($counts{UL} + $counts{ML} + $counts{UR} + $counts{MR} + $counts{IP}) . " pairs aligned concordantly 0 times; of these:\n";
    print "    " . $counts{IP} . " aligned as improper pairs\n";
    print "    " . ($counts{UL} + $counts{ML} + $counts{UR} + $counts{MR}) . " pairs had only one fragment end align to one or more contigs; of these:\n";
    print "       " . ($counts{UL} + $counts{ML}) . " fragments had only the left /1 read aligned; of these:\n";
    print "            " . $counts{UL} . " left reads mapped uniquely\n";
    print "            " . $counts{ML} . " left reads mapped >1 times\n";
    print "       " . ($counts{UR} + $counts{MR}) . " fragments had only the right /2 read aligned; of these:\n";
    print "            " . $counts{UR} . " right reads mapped uniquely\n";
    print "            " . $counts{MR} . " right reads mapped >1 times\n";
    print "Overall,  " . sprintf("%.2f", ($counts{UPP} + $counts{MPP})/$sum_reads * 100) . "% of aligned fragments aligned as proper pairs\n\n\n";

    if ($counts{US} + $counts{MS}) {
        print "  " . ($counts{US} + $counts{MS}) . " were single-end reads; of these:\n";
        print "      " . $counts{US} . " single-end reads mapped uniquely\n";
        print "      " . $counts{MS} . " single-end reads mapped >1 times\n";
    }

    close $DEBUG_OFH if $DEBUG;

    exit(0);

}

####
sub process_pairs {
    my ($reads_aref, $counts_href) = @_;

    my @reads = @$reads_aref;

    my @left_reads;
    my @right_reads;

    foreach my $read (@reads) {
        if ($read->is_first_in_pair()) {
            push (@left_reads, $read);
        }
        elsif ($read->is_second_in_pair()) {
            push (@right_reads, $read);
        }
    }

    my $got_left_read = (@left_reads) ? 1 : 0;
    my $got_right_read = (@right_reads) ? 1: 0;

    ## check to see if we have proper pairs:
    my @proper_pairs;

  pair_search:
    foreach my $left_read (@left_reads) {

        unless ($left_read->is_proper_pair()) { next; }

        my $aligned_pos = $left_read->get_aligned_position();

        foreach my $right_read (@right_reads) {

            unless ($right_read->is_proper_pair()) { next; }

            if ($left_read->get_scaffold_name() eq $right_read->get_scaffold_name()
                &&
                $right_read->get_mate_scaffold_position() == $aligned_pos) {

                push (@proper_pairs, [$left_read, $right_read]);

                last;
            }
        }
    }

    my $class = "";

    if (@proper_pairs) {

        if (scalar(@proper_pairs) == 1) {
            $class = "UPP";
        }
        else {
            # multi ampped proper pairs
            $class = "MPP";
        }
    }
    elsif ($got_left_read && $got_right_read) {
        $class = "IP";
    }
    elsif ($got_left_read) {

        if (scalar(@left_reads) == 1) {
            $class = "UL";
        }
        else {
            $class = "ML";
        }
    }
    elsif ($got_right_read) {

        if (scalar(@right_reads) == 1) {
            $class = "UR";
        }
        else {
            $class = "MR";
        }
    }
    else {
        if (scalar(@reads) == 1) {
            $class = "US";
        }
        else {
            $class = "MS";
        }
    }

    $counts_href->{$class}++;

    if ($DEBUG) {
        my $core_read_name = $reads[0]->get_core_read_name();

        print $DEBUG_OFH join("\t", $core_read_name, $class) . "\n";
    }

    return;
}


text:
<?php

/**
 * Locale timezone source
 *
 * @author      Magento Core Team <core@magentocommerce.com>
 */
class Mage_Adminhtml_Model_System_Config_Source_Locale_Timezone
{
    public function toOptionArray()
    {
        return Mage::app()->getLocale()->getOptionTimezones();
    }
}


text:
using namespace System.Management.Automation
using namespace System.Reflection
using namespace System.Text

class MemberExpressionGeneration {
    static [string] $Indent = '    ';

    [MemberInfo] $Member;
    [psobject] $Target;
    [bool] $BeVerbose;

    hidden [bool] $WasVerbose;
    hidden [StringBuilder] $Builder;
    hidden [string] $Flags;
    hidden [bool] $IsMethod;
    hidden [bool] $IsConstructor;

    hidden MemberExpressionGeneration([MemberInfo] $member, [psobject] $target) {
        $this.Target = $target
        $this.Member = $member
        $this.IsMethod = $this.Member -is [MethodBase]
        $this.IsConstructor = $this.Member -is [ConstructorInfo]
        $this.Flags = "[System.Reflection.BindingFlags]'{0}'" -f (
            [MemberExpressionGeneration]::GetBindingFlags(
                $this.Member))

        $this.Builder = [StringBuilder]::new()
        $this.Builder.psobject.Methods.Add(
            [PSCodeMethod]::new(
                'AppendInvocationArgs',
                [MemberExpressionGeneration].GetMethod('InvocationArgsCodeMethod')))

        $this.Builder.psobject.Methods.Add(
            [PSCodeMethod]::new(
                'AppendParameterName',
                [MemberExpressionGeneration].GetMethod('CommentCodeMethod')))

        $this.Builder.psobject.Methods.Add(
            [PSCodeMethod]::new(
                'AppendIndent',
                [MemberExpressionGeneration].GetMethod('IndentCodeMethod')))
    }

    static [string] GetReflectionExpression([psobject] $instance, [MemberInfo] $member) {
        return [MemberExpressionGeneration]::GetReflectionExpression(
            $instance,
            $member,
            $false)
    }

    static [string] GetReflectionExpression(
        [psobject] $instance,
        [MemberInfo] $member,
        [bool] $beVerbose)
    {
        $helper = [MemberExpressionGeneration]::new($member, $instance)
        $helper.BeVerbose = $beVerbose
        return $helper.GetExpression()
    }

    static [string[]] GetInvocationArgs([ParameterInfo[]] $parameters) {
        return [MemberExpressionGeneration]::GetInvocationArgs($parameters, $true)
    }

    static [string[]] GetInvocationArgs([ParameterInfo[]] $parameters, [bool] $includeNameComments) {
        $result = foreach ($parameter in $parameters) {
            $comment = ''
            if ($includeNameComments) {
                $comment = '<# {0}: #> ' -f $parameter.Name
            }

            '{0}${1}' -f $comment, $parameter.Name
        }

        return $result
    }

    hidden static [StringBuilder] InvocationArgsCodeMethod(
        [psobject] $instance,
        [int] $indent,
        [MemberInfo] $member)
    {
        $parameters = $member.GetParameters()
        if (-not $parameters.Count) {
            return $instance
        }

        $indentText = (@([MemberExpressionGeneration]::Indent) * $indent) -join ''

        if ($parameters.Count) {
            $instance.AppendLine().Append($indentText)
        }

        return $instance.Append(
            [MemberExpressionGeneration]::GetInvocationArgs($parameters) -join (
                ',' + [Environment]::NewLine + $indentText))
    }

    static hidden [StringBuilder] CommentCodeMethod([psobject] $instance, [string] $parameterName) {
        return $instance.AppendFormat('<# {0}: #> ', $parameterName)
    }

    static hidden [StringBuilder] IndentCodeMethod([psobject] $instance) {
        return $instance.Append([MemberExpressionGeneration]::Indent)
    }

    static hidden [BindingFlags] GetBindingFlags([MemberInfo] $member) {
        $scope = [BindingFlags]::Instance
        if ([MemberExpressionGeneration]::IsStatic($member)) {
            $scope = [BindingFlags]::Static
        }

        return [BindingFlags]::NonPublic -bor $scope
    }

    static hidden [bool] IsStatic([MemberInfo] $member) {
        if ($member -is [PropertyInfo]) {
            return $member.GetMethod.IsStatic
        }

        return $member.IsStatic
    }

    [string] GetExpression() {
        $this.WriteBridge()
        $this.WriteGetArgs()
        $this.WriteInvocationExpression()

        return $this.Builder.ToString()
    }

    hidden [void] WriteBridge() {
        $this.Builder.
            Append($this.GetSourceExpression()).
            AppendLine('.').
            AppendIndent().
            Append('Get').
            Append($this.Member.MemberType).
            Append('(')
    }

    hidden [void] WriteGetArgs() {
        $canBeVerbose = -not ([MemberTypes]'Property, Field').HasFlag($this.Member.MemberType)
        if ($this.BeVerbose -and $canBeVerbose ) {
            $this.WriteComplexGetArgs()
            return
        }

        $this.WriteBasicGetArgs()
    }

    hidden [void] WriteInvocationExpression() {
        $methodName = 'GetValue'
        if ($this.IsMethod) {
            $methodName = 'Invoke'
        }

        $this.Builder.AppendLine().AppendIndent().
            Append($methodName).Append('(')

        if (-not $this.IsConstructor) {
            $this.Builder.Append($this.GetTargetExpression())

            if (-not $this.IsMethod) {
                $this.Builder.Append(')')
                return
            }

            $this.Builder.Append(', ')
        }

        $this.Builder.
            Append('@(').
            AppendInvocationArgs(2, $this.Member).
            Append('))')
    }

    hidden [string] GetSourceExpression() {
        if ($this.IsConstructor) {
            if ($this.Target -isnot [type]) {
                $this.Target = $this.Member.ReflectedType
            }

            return [TypeExpressionHelper]::Create($this.Target)
        }

        if ($this.Target -is [type]) {
            return [TypeExpressionHelper]::Create($this.Target)
        }

        return $this.Target.ToString() + '.GetType()'
    }

    hidden [string] GetTargetExpression() {
        if ($this.IsConstructor) {
            return [string]::Empty
        }

        if ([MemberExpressionGeneration]::IsStatic($this.Member)) {
            return '$null'
        }

        if ($this.Target -is [type]) {
            return '$instance'
        }

        return $this.Target.ToString()
    }

    hidden [void] WriteBasicGetArgs() {
        $this.
            Builder.
            AppendFormat("'{0}', ", $this.Member.Name).
            Append($this.Flags).
            Append(").")
    }

    hidden [void] WriteComplexGetArgs() {
        if ($this.Member -isnot [ConstructorInfo]) {
            $this.Builder.AppendLine().AppendIndent().AppendIndent().
                AppendParameterName('name').
                AppendFormat("'{0}',", $this.Member.Name)
        }

        $this.Builder.AppendLine().AppendIndent().AppendIndent().
            AppendParameterName('bindingAttr').
            Append($this.Flags).
            Append(',')

        $this.Builder.AppendLine().AppendIndent().AppendIndent().
            AppendParameterName('binder').
            Append('$null,')

        $types = foreach($parameter in $this.Member.GetParameters()) {
            [TypeExpressionHelper]::Create($parameter.ParameterType)
        }
        $this.Builder.AppendLine().AppendIndent().AppendIndent().
            AppendParameterName('types').
            AppendFormat('@({0}),', $types -join ', ')

        $modifiers = [int]($this.Member.GetParameters().Count)
        if (-not $modifiers) {
            $modifiers = '@()'
        }

        $this.Builder.AppendLine().AppendIndent().AppendIndent().
            AppendParameterName('modifiers').
            Append($modifiers).
            Append(').')
    }
}


text:
/** @jsx React.DOM */

var React = require('react'),
	SetClass = require('classnames'),
	Tappable = require('react-tappable'),
	Navigation = require('touchstonejs').Navigation,
	Link = require('touchstonejs').Link,
	UI = require('touchstonejs').UI;

module.exports = React.createClass({
	mixins: [Navigation],

	componentDidMount: function() {
		setTimeout(function() {
			this.showView('transitions', 'fade');
		}.bind(this), 1000);
	},

	render: function() {

		return (
			<UI.FlexLayout className={this.props.viewClassName}>
				<UI.Headerbar label="Target View" />
				<UI.FlexBlock>
					<UI.Feedback iconKey="ion-ios7-photos" iconType="muted" text="Hold on a sec..." />
				</UI.FlexBlock>
			</UI.FlexLayout>
		);
	}
});


text:
from msrest.serialization import Model

class BgpSettings(Model):
    """BgpSettings.

    :param asn: Gets or sets this BGP speaker's ASN
    :type asn: long
    :param bgp_peering_address: Gets or sets the BGP peering address and BGP
     identifier of this BGP speaker
    :type bgp_peering_address: str
    :param peer_weight: Gets or sets the weight added to routes learned from
     this BGP speaker
    :type peer_weight: int
    """

    _attribute_map = {
        'asn': {'key': 'asn', 'type': 'long'},
        'bgp_peering_address': {'key': 'bgpPeeringAddress', 'type': 'str'},
        'peer_weight': {'key': 'peerWeight', 'type': 'int'},
    }

    def __init__(self, *, asn: int=None, bgp_peering_address: str=None, peer_weight: int=None, **kwargs) -> None:
        super(BgpSettings, self).__init__(**kwargs)
        self.asn = asn
        self.bgp_peering_address = bgp_peering_address
        self.peer_weight = peer_weight


text:
/*
 * Description:
 *     What is this file about?
 *
 * Revision history:
 *     xxxx-xx-xx, author, first version
 *     xxxx-xx-xx, author, fix bug about xxx
 */
# pragma once

//
// uncomment the following line if you want to use
// data encoding/decoding from the original tool instead of rDSN
// in this case, you need to use these tools to generate
// type files with --gen=cpp etc. options
//
// !!! WARNING: not feasible for replicated service yet!!!
//
// # define DSN_NOT_USE_DEFAULT_SERIALIZATION

# include <dsn/service_api_cpp.h>

# ifdef DSN_NOT_USE_DEFAULT_SERIALIZATION

# include <dsn/thrift_helper.h>
# include "nfs_types.h"

namespace dsn {
    namespace service {
        // ---------- copy_request -------------
        inline void marshall(::dsn::binary_writer& writer, const copy_request& val)
        {
            boost::shared_ptr< ::dsn::binary_writer_transport> transport(new ::dsn::binary_writer_transport(writer));
            ::apache::thrift::protocol::TBinaryProtocol proto(transport);
            ::dsn::marshall_rpc_args<copy_request>(&proto, val, &copy_request::write);
        };

        inline void unmarshall(::dsn::binary_reader& reader, /*out*/ copy_request& val)
        {
            boost::shared_ptr< ::dsn::binary_reader_transport> transport(new ::dsn::binary_reader_transport(reader));
            ::apache::thrift::protocol::TBinaryProtocol proto(transport);
            ::dsn::unmarshall_rpc_args<copy_request>(&proto, val, &copy_request::read);
        };

        // ---------- copy_response -------------
        inline void marshall(::dsn::binary_writer& writer, const copy_response& val)
        {
            boost::shared_ptr< ::dsn::binary_writer_transport> transport(new ::dsn::binary_writer_transport(writer));
            ::apache::thrift::protocol::TBinaryProtocol proto(transport);
            ::dsn::marshall_rpc_args<copy_response>(&proto, val, &copy_response::write);
        };

        inline void unmarshall(::dsn::binary_reader& reader, /*out*/ copy_response& val)
        {
            boost::shared_ptr< ::dsn::binary_reader_transport> transport(new ::dsn::binary_reader_transport(reader));
            ::apache::thrift::protocol::TBinaryProtocol proto(transport);
            ::dsn::unmarshall_rpc_args<copy_response>(&proto, val, &copy_response::read);
        };

        // ---------- get_file_size_request -------------
        inline void marshall(::dsn::binary_writer& writer, const get_file_size_request& val)
        {
            boost::shared_ptr< ::dsn::binary_writer_transport> transport(new ::dsn::binary_writer_transport(writer));
            ::apache::thrift::protocol::TBinaryProtocol proto(transport);
            ::dsn::marshall_rpc_args<get_file_size_request>(&proto, val, &get_file_size_request::write);
        };

        inline void unmarshall(::dsn::binary_reader& reader, /*out*/ get_file_size_request& val)
        {
            boost::shared_ptr< ::dsn::binary_reader_transport> transport(new ::dsn::binary_reader_transport(reader));
            ::apache::thrift::protocol::TBinaryProtocol proto(transport);
            ::dsn::unmarshall_rpc_args<get_file_size_request>(&proto, val, &get_file_size_request::read);
        };

        // ---------- get_file_size_response -------------
        inline void marshall(::dsn::binary_writer& writer, const get_file_size_response& val)
        {
            boost::shared_ptr< ::dsn::binary_writer_transport> transport(new ::dsn::binary_writer_transport(writer));
            ::apache::thrift::protocol::TBinaryProtocol proto(transport);
            ::dsn::marshall_rpc_args<get_file_size_response>(&proto, val, &get_file_size_response::write);
        };

        inline void unmarshall(::dsn::binary_reader& reader, /*out*/ get_file_size_response& val)
        {
            boost::shared_ptr< ::dsn::binary_reader_transport> transport(new ::dsn::binary_reader_transport(reader));
            ::apache::thrift::protocol::TBinaryProtocol proto(transport);
            ::dsn::unmarshall_rpc_args<get_file_size_response>(&proto, val, &get_file_size_response::read);
        };

    }
}

# else // use rDSN's data encoding/decoding

namespace dsn {
    namespace service {

        // ---------- copy_request -------------
        struct copy_request
        {
            ::dsn::rpc_address source;
            std::string source_dir;
            std::string dst_dir;
            std::string file_name;
            uint64_t offset;
            uint32_t size;
            bool is_last;
            bool overwrite;
        };

        inline void marshall(::dsn::binary_writer& writer, const copy_request& val)
        {
            marshall(writer, val.source);
            marshall(writer, val.source_dir);
            marshall(writer, val.dst_dir);
            marshall(writer, val.file_name);
            marshall(writer, val.offset);
            marshall(writer, val.size);
            marshall(writer, val.is_last);
            marshall(writer, val.overwrite);
        };

        inline void unmarshall(::dsn::binary_reader& reader, /*out*/ copy_request& val)
        {
            unmarshall(reader, val.source);
            unmarshall(reader, val.source_dir);
            unmarshall(reader, val.dst_dir);
            unmarshall(reader, val.file_name);
            unmarshall(reader, val.offset);
            unmarshall(reader, val.size);
            unmarshall(reader, val.is_last);
            unmarshall(reader, val.overwrite);
        };

        // ---------- copy_response -------------
        struct copy_response
        {
            error_code error;
            blob file_content;
            uint64_t offset;
            uint32_t size;
        };

        inline void marshall(::dsn::binary_writer& writer, const copy_response& val)
        {
            marshall(writer, val.error);
            marshall(writer, val.file_content);
            marshall(writer, val.offset);
            marshall(writer, val.size);
        };

        inline void unmarshall(::dsn::binary_reader& reader, /*out*/ copy_response& val)
        {
            unmarshall(reader, val.error);
            unmarshall(reader, val.file_content);
            unmarshall(reader, val.offset);
            unmarshall(reader, val.size);
        };

        // ---------- get_file_size_request -------------
        struct get_file_size_request
        {
            ::dsn::rpc_address source;
            std::string dst_dir;
            std::vector< std::string> file_list;
            std::string source_dir;
            bool overwrite;
        };

        inline void marshall(::dsn::binary_writer& writer, const get_file_size_request& val)
        {
            marshall(writer, val.source);
            marshall(writer, val.dst_dir);
            marshall(writer, val.file_list);
            marshall(writer, val.source_dir);
            marshall(writer, val.overwrite);
        };

        inline void unmarshall(::dsn::binary_reader& reader, /*out*/ get_file_size_request& val)
        {
            unmarshall(reader, val.source);
            unmarshall(reader, val.dst_dir);
            unmarshall(reader, val.file_list);
            unmarshall(reader, val.source_dir);
            unmarshall(reader, val.overwrite);
        };

        // ---------- get_file_size_response -------------
        struct get_file_size_response
        {
            int32_t error;
            std::vector< std::string> file_list;
            std::vector< uint64_t> size_list;
        };

        inline void marshall(::dsn::binary_writer& writer, const get_file_size_response& val)
        {
            marshall(writer, val.error);
            marshall(writer, val.file_list);
            marshall(writer, val.size_list);
        };

        inline void unmarshall(::dsn::binary_reader& reader, /*out*/ get_file_size_response& val)
        {
            unmarshall(reader, val.error);
            unmarshall(reader, val.file_list);
            unmarshall(reader, val.size_list);
        };

    }
}

#endif


text:
package ru.turbomolot.ntchart.render;

import android.graphics.Matrix;
import android.graphics.Path;
import android.graphics.RectF;

import java.util.List;

import ru.turbomolot.ntchart.data.IPoint;

/**
 * Created by TurboMolot on 04.10.17.
 */

public interface ISeriesHolder<P extends IPoint> {
    float getMaxX();
    float getMaxY();
    float getMinX();
    float getMinY();

    void setMinX(Float minX);
    void setMinY(Float minY);
    void setMaxX(Float maxX);
    void setMaxY(Float maxY);

    Matrix getMatrix();
    void setMatrix(Matrix matrix);

    void calcRender(List<? extends P> pts);
    List<? extends P> getRender();

    void setWindowSize(float left, float top, float right, float bottom);
    RectF getWindowSize();

    float toRenderX(float x);
    float toRenderY(float y);

    float toPointX(float x);
    float toPointY(float y);

    boolean isRenderFromAxisRight();
    void setRenderFromAxisRight(boolean renderFromAxisRight);
    boolean isAutoScale();
    void setAutoScale(boolean autoScale);
    boolean isAutoMoveLastX();
    void setAutoMoveLastX(boolean autoMoveLastX);

    float getMaxDistanceX();
    void setMaxDistanceX(float maxDistanceX);
    float getMaxDistanceY();
    void setMaxDistanceY(float maxDistanceY);

    List<Path> getRenderPaths();

    void setReducePointsEnabled(boolean reducePointsEnabled);
    boolean isReducePointsEnabled();

    float getScaleX();
    float getScaleY();
}


text:
{% load rest_framework %}

{{ document.title }}

    {% if document.description %}

{% render_markdown document.description %}

    {% endif %}

    {% if 'shell' in langs %}{% include "rest_framework/docs/langs/shell-intro.html" %}{% endif %}
    {% if 'python' in langs %}{% include "rest_framework/docs/langs/python-intro.html" %}{% endif %}
    {% if 'javascript' in langs %}{% include "rest_framework/docs/langs/javascript-intro.html" %}{% endif %}

{% if document.data %}
{% for section_key, section in document.data|items %}
{% if section_key %}

{{ section_key }}

{% endif %}

    {% for link_key, link in section|schema_links|items %}
        {% include "rest_framework/docs/link.html" %}
    {% endfor %}
{% endfor %}

{% for link_key, link in document.links|items %}
    {% include "rest_framework/docs/link.html" %}
{% endfor %}
{% endif %}


text:
#region License
// Copyright (c) 2013 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Glimpse.Core.Extensibility;
using Glimpse.Core.Framework.Support;

namespace Newtonsoft.Json.Glimpse
{
  internal class JsonInspector : IInspector
  {
    public void Setup(IInspectorContext context)
    {
      Func<RuntimePolicy> runtimePolicyStrategy = context.RuntimePolicyStrategy;
      Func<IExecutionTimer> timerStrategy = context.TimerStrategy;
      IMessageBroker messageBroker = context.MessageBroker;

      // because there is no static way to access runtime policy strategy
      GlimpseJson.RuntimePolicyStrategy = runtimePolicyStrategy;

      GlimpseJson.Initialize(runtimePolicyStrategy, timerStrategy, messageBroker);
    }
  }
}


text:
/*
 * UserContent store test
 *
 */

// import UserContent from '../index'

it('TODO: store test UserContent', () => {
  expect(1 + 1).toBe(2)
})


text:
using GalaSoft.MvvmLight;
using RealEstateTourNotebook.Resources;
using RealEstateTourNotebook.ViewModel.Enum;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Windows;

namespace RealEstateTourNotebook.ViewModel
{
    /// <summary>
    /// This class contains properties that a View can data bind to.
    /// <para>
    /// See http://www.galasoft.ch/mvvm
    /// </para>
    /// </summary>
    public class SettingsViewModel : ViewModelBase
    {
        private int _selectedLang;
        /// <summary>
        /// Initializes a new instance of the SettingsViewModel class.
        /// </summary>
        public SettingsViewModel()
        {
            SetLanguageList();
            SetCurrencyList();
            SetDistanceList();
            SetDimensionList();
        }

        public Version Version
        {
            get
            {
                return Assembly.GetExecutingAssembly().GetName().Version;
            }
        }

        public ObservableCollection<Language> LanguageList
        {
            get;
            set;
        }

        public ObservableCollection<string> DimensionList
        {
            get;
            set;
        }

        public ObservableCollection<string> DistanceList
        {
            get;
            set;
        }

        public ObservableCollection<string> CurrencyList
        {
            get;
            set;
        }

        public int SelectedLang
        {
            get
            {
                return _selectedLang;
            }
            set
            {
                _selectedLang = value;
                IsolatedStorageSettings.ApplicationSettings["Language"] = LanguageList[value];
                IsolatedStorageSettings.ApplicationSettings.Save();
                MessageBox.Show(AppResources.RestartApp, "Information", MessageBoxButton.OK);
                Application.Current.Terminate();
            }
        }

        public void SetLanguageList()
        {
            LanguageList = new ObservableCollection<Language>();
            foreach (Language item in System.Enum.GetValues(typeof(Language)))
            {
                LanguageList.Add(item);
            }

            _selectedLang = LanguageList.IndexOf(LanguageList.First(x => Thread.CurrentThread.CurrentCulture.Name.Contains(x.ToString())));
        }

        public void SetCurrencyList()
        {
            CurrencyList = new ObservableCollection<string>();
        }

        public void SetDimensionList()
        {
            DimensionList = new ObservableCollection<string>();
        }

        public void SetDistanceList()
        {
            DistanceList = new ObservableCollection<string>();
        }

    }
}


text:
import jax
import jax.numpy as jnp
import matplotlib.pyplot as plt
import numpy as np

from pgmax import fgraph, fgroup, infer, vgroup

# %% [markdown]
# ### Construct variable grid, initialize factor graph, and add factors

# %%
variables = vgroup.NDVarArray(num_states=2, shape=(50, 50))
fg = fgraph.FactorGraph(variable_groups=variables)

variables_for_factors = []
for ii in range(50):
    for jj in range(50):
        kk = (ii + 1) % 50
        ll = (jj + 1) % 50
        variables_for_factors.append([variables[ii, jj], variables[kk, jj]])
        variables_for_factors.append([variables[ii, jj], variables[ii, ll]])

factor_group = fgroup.PairwiseFactorGroup(
    variables_for_factors=variables_for_factors,
    log_potential_matrix=0.8 * np.array([[1.0, -1.0], [-1.0, 1.0]]),
)
fg.add_factors(factor_group)

# %% [markdown]
# ### Run inference and visualize results

# %%
bp = infer.BP(fg.bp_state, temperature=0)

# %%
bp_arrays = bp.init(
    evidence_updates={variables: jax.device_put(np.random.gumbel(size=(50, 50, 2)))}
)
bp_arrays = bp.run_bp(bp_arrays, num_iters=3000)
beliefs = bp.get_beliefs(bp_arrays)

# %%
img = infer.decode_map_states(beliefs)[variables]
fig, ax = plt.subplots(1, 1, figsize=(10, 10))
ax.imshow(img)

# %% [markdown]
# ### Gradients and batching

# %%
def loss(log_potentials_updates, evidence_updates):
    bp_arrays = bp.init(
        log_potentials_updates=log_potentials_updates, evidence_updates=evidence_updates
    )
    bp_arrays = bp.run_bp(bp_arrays, num_iters=3000)
    beliefs = bp.get_beliefs(bp_arrays)
    loss = -jnp.sum(beliefs[variables])
    return loss

batch_loss = jax.jit(jax.vmap(loss, in_axes=(None, {variables: 0}), out_axes=0))
log_potentials_grads = jax.jit(jax.grad(loss, argnums=0))

# %%
batch_loss(None, {variables: jax.device_put(np.random.gumbel(size=(10, 50, 50, 2)))})

# %%
grads = log_potentials_grads(
    {factor_group: jnp.eye(2)},
    {variables: jax.device_put(np.random.gumbel(size=(50, 50, 2)))},
)

# %% [markdown]
# ### Message and evidence manipulation

# %%
bp_state = bp.to_bp_state(bp_arrays)

# Query evidence for variable (0, 0)
bp_state.evidence[variables[0, 0]]

# %%
# Set evidence for variable (0, 0)
bp_state.evidence[variables[0, 0]] = np.array([1.0, 1.0])
bp_state.evidence[variables[0, 0]]

# %%
# Set evidence for all variables using an array
evidence = np.random.randn(50, 50, 2)
bp_state.evidence[variables] = evidence
np.allclose(bp_state.evidence[variables[10, 10]], evidence[10, 10])