text:
// Copyright (C) 2011  Davis E. King (davis@dlib.net)
// License: Boost Software License   See LICENSE.txt for the full license.
#ifndef DLIB_SAVE_PnG_Hh_
#define DLIB_SAVE_PnG_Hh_

#include "save_png_abstract.h"
#include "image_saver.h"
#include "../array2d.h"
#include <vector>
#include <string>
#include "../pixel.h"
#include "../matrix/matrix_exp.h"
#include "../image_transforms/assign_image.h"

namespace dlib
{

// ----------------------------------------------------------------------------------------

    namespace impl
    {
        enum png_type
        {
            png_type_rgb,
            png_type_rgb_alpha,
            png_type_gray,
        };

        void impl_save_png (
            const std::string& file_name,
            std::vector<unsigned char*>& row_pointers,
            const long width,
            const png_type type,
            const int bit_depth
        );
    }

// ----------------------------------------------------------------------------------------

    template <
        typename image_type
        >
    typename disable_if<is_matrix<image_type> >::type save_png(
        const image_type& img_,
        const std::string& file_name
    )
    {
        const_image_view<image_type> img(img_);

        // make sure requires clause is not broken
        DLIB_CASSERT(img.size() != 0,
            "\t save_png()"
            << "\n\t You can't save an empty image as a PNG"
            );

#ifndef DLIB_PNG_SUPPORT
            /* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
                You are getting this error because you are trying to use save_png()
                but you haven't defined DLIB_PNG_SUPPORT.  You must do so to use
                this function.   You must also make sure you set your build environment
                to link against the libpng library.
            !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/
            COMPILE_TIME_ASSERT(sizeof(image_type) == 0);
#else
        std::vector<unsigned char*> row_pointers(img.nr());
        typedef typename image_traits<image_type>::pixel_type pixel_type;

        if (is_same_type<rgb_pixel,pixel_type>::value)
        {
            for (unsigned long i = 0; i < row_pointers.size(); ++i)
                row_pointers[i] = (unsigned char*)(&img[i][0]);

            impl::impl_save_png(file_name, row_pointers, img.nc(), impl::png_type_rgb, 8);
        }
        else if (is_same_type<rgb_alpha_pixel,pixel_type>::value)
        {
            for (unsigned long i = 0; i < row_pointers.size(); ++i)
                row_pointers[i] = (unsigned char*)(&img[i][0]);

            impl::impl_save_png(file_name, row_pointers, img.nc(), impl::png_type_rgb_alpha, 8);
        }
        else if (pixel_traits<pixel_type>::lab || pixel_traits<pixel_type>::hsi || pixel_traits<pixel_type>::rgb)
        {
            // convert from Lab or HSI to RGB (Or potentially RGB pixels that aren't laid out as R G B)
            array2d<rgb_pixel> temp_img;
            assign_image(temp_img, img_);
            for (unsigned long i = 0; i < row_pointers.size(); ++i)
                row_pointers[i] = (unsigned char*)(&temp_img[i][0]);

            impl::impl_save_png(file_name, row_pointers, img.nc(), impl::png_type_rgb, 8);
        }
        else if (pixel_traits<pixel_type>::rgb_alpha)
        {
            // convert from RGBA pixels that aren't laid out as R G B A
            array2d<rgb_alpha_pixel> temp_img;
            assign_image(temp_img, img_);
            for (unsigned long i = 0; i < row_pointers.size(); ++i)
                row_pointers[i] = (unsigned char*)(&temp_img[i][0]);

            impl::impl_save_png(file_name, row_pointers, img.nc(), impl::png_type_rgb_alpha, 8);
        }
        else // this is supposed to be grayscale
        {
            DLIB_CASSERT(pixel_traits<pixel_type>::grayscale, "impossible condition detected");

            if (pixel_traits<pixel_type>::is_unsigned && sizeof(pixel_type) == 1)
            {
                for (unsigned long i = 0; i < row_pointers.size(); ++i)
                    row_pointers[i] = (unsigned char*)(&img[i][0]);

                impl::impl_save_png(file_name, row_pointers, img.nc(), impl::png_type_gray, 8);
            }
            else if (pixel_traits<pixel_type>::is_unsigned && sizeof(pixel_type) == 2)
            {
                for (unsigned long i = 0; i < row_pointers.size(); ++i)
                    row_pointers[i] = (unsigned char*)(&img[i][0]);

                impl::impl_save_png(file_name, row_pointers, img.nc(), impl::png_type_gray, 16);
            }
            else
            {
                // convert from whatever this is to 16bit grayscale
                array2d<dlib::uint16> temp_img;
                assign_image(temp_img, img_);
                for (unsigned long i = 0; i < row_pointers.size(); ++i)
                    row_pointers[i] = (unsigned char*)(&temp_img[i][0]);

                impl::impl_save_png(file_name, row_pointers, img.nc(), impl::png_type_gray, 16);
            }
        }

#endif

    }

// ----------------------------------------------------------------------------------------

    template <
        typename EXP
        >
    void save_png(
        const matrix_exp<EXP>& img,
        const std::string& file_name
    )
    {
        array2d<typename EXP::type> temp;
        assign_image(temp, img);
        save_png(temp, file_name);
    }

// ----------------------------------------------------------------------------------------

}

#ifdef NO_MAKEFILE
#include "save_png.cpp"
#endif

#endif // DLIB_SAVE_PnG_Hh_


text:
package duplication;

public class Duplications {

}

redpajama_set_name: RedPajamaGithub


text:
import * as React from 'react';
import * as CSSTransitionReplace from 'react-css-transition-replace';

export class PanelItem {
  public panelId: string;
  public component: (React.ComponentClass<any> | React.StatelessComponent<any>);
}

interface Props {
  activePanelId: string;
  panelList: PanelItem[];
}

const renderSelectedComponent = ({ activePanelId, panelList }: Props) => {
  let panelItem = <div key={activePanelId} />;
  const panel = panelList.find((currentPanel) => currentPanel.panelId === activePanelId);

  if (panel) {
    const Component = panel.component;
    if (Component) {
      panelItem = <Component key={activePanelId} />;
    }
  }

  return (
    <CSSTransitionReplace transitionName="cross-fade" transitionEnterTimeout={150} transitionLeaveTimeout={150}>
      {panelItem}
    </CSSTransitionReplace>
  );
};

export const PanelComponent: React.StatelessComponent<Props> = (props) => {
  return renderSelectedComponent(props);
};

PanelComponent.displayName = 'PanelComponent';


text:
from django.shortcuts import render, redirect, get_object_or_404
from random import randint
from django.conf import settings
from forms import ContactForm
from django.core.mail import EmailMessage
from django.contrib import messages
from django.contrib.flatpages.models import FlatPage
from django.views.generic import RedirectView
from tweet_cache.models import Tweet
from commission.models import Member, FAQ, PressRelease, Partner, Supporter, \
    MediaContact, Event, Publication, Video, Feature
from .models import UrlAlias
from datetime import datetime
import pytz

def home(request, template="structure/home.html"):

    public_tweets = Tweet.objects.filter(account=settings.TWITTER_USER, hide=False).order_by("-id")[:20]

    video_number = randint(1, 3)

    main_page, created = FlatPage.objects.get_or_create(url='/main/')
    about_page, created = FlatPage.objects.get_or_create(url='/about/')
    # press_page, created = FlatPage.objects.get_or_create(url='/press/')
    # partner_page, created = FlatPage.objects.get_or_create(url='/partner/')
    commission_page, created = FlatPage.objects.get_or_create(url='/commission/')
    event_page, created = FlatPage.objects.get_or_create(url='/event/')
    footer_page, created = FlatPage.objects.get_or_create(url='/footer/')
    contact_page, created = FlatPage.objects.get_or_create(url='/contact/')
    research_advisers_page, created = FlatPage.objects.get_or_create(url='/research_advisers/')
    contact_form = ContactForm()

    faq_page, created = FlatPage.objects.get_or_create(url='/faq/')
    faq_list = FAQ.objects.all().order_by('weight')

    chair_members = list(Member.objects.filter(member_type="chair").order_by("last_name"))
    other_members = list(Member.objects.filter(member_type="general").order_by("last_name"))
    supporting_members = list(Member.objects.filter(member_type="supporting").order_by("last_name"))

    research_advisers = list(Member.objects.filter(member_type="research_adviser").order_by("last_name"))

    press_releases = PressRelease.objects.all().order_by("-release_date")
    partners = Partner.objects.all().order_by("weight")
    supporters = Supporter.objects.all().order_by("weight")
    media_contacts = MediaContact.objects.filter(display_on_contact=True).order_by("weight")

    today = datetime.now(tz=pytz.timezone(settings.SERVER_TIMEZONE)).replace(tzinfo=pytz.timezone("UTC"))
    current_events = Event.objects.filter(end_date__gte=today).order_by("start_date")
    past_events = Event.objects.filter(end_date__lt=today).order_by("-start_date")

    publications = Publication.objects.all().order_by("-publish_date", "weight")

    videos = Video.objects.all().order_by("weight")

    features = Feature.objects.filter(disable=False).order_by("weight")

    context = {'public_tweets': public_tweets,
               'video_number': video_number,
               'main_page': main_page,
               'about_page': about_page,
               # 'press_page': press_page,
               # 'partner_page': partner_page,
               'commission_page': commission_page,
               'event_page': event_page,
               'footer_page': footer_page,
               'contact_page': contact_page,
               'research_advisers_page': research_advisers_page,
               'contact_form': contact_form,
               'chair_members': chair_members,
               'other_members': other_members,
               'supporting_members': supporting_members,
               'research_advisers': research_advisers,
               'faq_list': faq_list,
               'faq_page': faq_page,
               'GA_SITE_ID': settings.GA_SITE_ID,
               'GA_SITE_URL': settings.GA_SITE_URL,
               'VIDEO_BASE_URL': settings.VIDEO_BASE_URL,
               'press_releases': press_releases,
               'partners': partners,
               'supporters': supporters,
               'media_contacts': media_contacts,
               'current_events': current_events,
               'past_events': past_events,
               'publications': publications,
               'videos': videos,
               'features': features,
               }

    return render(request, template, context)

def contact_submit(request):
    #request.is_ajax() and
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():

            subject = "[OurInternet Contact Form] %s" % form.cleaned_data['subject']
            message = form.cleaned_data['message']
            sender = form.cleaned_data['sender']
            cc_sender = form.cleaned_data['cc_myself']

            recipients = settings.CONTACT_FORM_RECIPIENT_LIST

            cc_list = []
            if cc_sender:
                cc_list = [sender]

            email = EmailMessage(subject, message, from_email=sender, to=recipients, cc=cc_list)
            email.send()

            form = ContactForm()
            messages.add_message(request, messages.SUCCESS, 'Your email has been sent.')

        else:
            messages.add_message(request, messages.ERROR,
                                 'There has been an error submitting your form.')

    else:
        form = ContactForm()

    context = {'contact_form': form,
               'media_contacts': MediaContact.objects.filter(display_on_contact=True).order_by("weight"),
               }

    if request.is_ajax():
        return render(request, 'structure/_contact.html', context)
    else:
        return redirect('contact_redirect_no_ajax')

class CustomRedirectView(RedirectView):
    permanent = False
    query_string = False

    def get_redirect_url(self, *args, **kwargs):

        url_alias = get_object_or_404(UrlAlias, source=kwargs['source'])
        self.url = url_alias.destination

        return super(CustomRedirectView, self).get_redirect_url(*args, **kwargs)


text:
/* slapcommon.h - common definitions for the slap tools */
/* $OpenLDAP: pkg/ldap/servers/slapd/slapcommon.h,v 1.14.2.12 2011/01/04 23:50:25 kurt Exp $ */
/* This work is part of OpenLDAP Software <http://www.openldap.org/>.
 *
 * Copyright 1998-2011 The OpenLDAP Foundation.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted only as authorized by the OpenLDAP
 * Public License.
 *
 * A copy of this license is available in the file LICENSE in the
 * top-level directory of the distribution or, alternatively, at
 * <http://www.OpenLDAP.org/license.html>.
 */

#ifndef SLAPCOMMON_H_
#define SLAPCOMMON_H_ 1

#define SLAPD_TOOLS 1
#include "slap.h"

enum slaptool {
	SLAPADD=1,	/* LDIF -> database tool */
	SLAPCAT,	/* database -> LDIF tool */
	SLAPDN,		/* DN check w/ syntax tool */
	SLAPINDEX,	/* database index tool */
	SLAPPASSWD,	/* password generation tool */
	SLAPSCHEMA,	/* schema checking tool */
	SLAPTEST,	/* slapd.conf test tool */
	SLAPAUTH,	/* test authz-regexp and authc/authz stuff */
	SLAPACL,	/* test acl */
	SLAPLAST
};

typedef struct tool_vars {
	Backend *tv_be;
	int tv_dbnum;
	int tv_verbose;
	int tv_quiet;
	int tv_update_ctxcsn;
	int tv_continuemode;
	int tv_nosubordinates;
	int tv_dryrun;
	int tv_jumpline;
	struct berval tv_sub_ndn;
	int tv_scope;
	Filter *tv_filter;
	struct LDIFFP	*tv_ldiffp;
	struct berval tv_baseDN;
	struct berval tv_authcDN;
	struct berval tv_authzDN;
	struct berval tv_authcID;
	struct berval tv_authzID;
	struct berval tv_mech;
	char	*tv_realm;
	struct berval tv_listener_url;
	struct berval tv_peer_domain;
	struct berval tv_peer_name;
	struct berval tv_sock_name;
	slap_ssf_t tv_ssf;
	slap_ssf_t tv_transport_ssf;
	slap_ssf_t tv_tls_ssf;
	slap_ssf_t tv_sasl_ssf;
	unsigned tv_dn_mode;
	unsigned int tv_csnsid;
	ber_len_t tv_ldif_wrap;
} tool_vars;

extern tool_vars tool_globals;

#define	be tool_globals.tv_be
#define	dbnum tool_globals.tv_dbnum
#define verbose tool_globals.tv_verbose
#define quiet tool_globals.tv_quiet
#define jumpline tool_globals.tv_jumpline
#define update_ctxcsn tool_globals.tv_update_ctxcsn
#define continuemode tool_globals.tv_continuemode
#define nosubordinates tool_globals.tv_nosubordinates
#define dryrun tool_globals.tv_dryrun
#define sub_ndn tool_globals.tv_sub_ndn
#define scope tool_globals.tv_scope
#define filter tool_globals.tv_filter
#define ldiffp tool_globals.tv_ldiffp
#define baseDN tool_globals.tv_baseDN
#define authcDN tool_globals.tv_authcDN
#define authzDN tool_globals.tv_authzDN
#define authcID tool_globals.tv_authcID
#define authzID tool_globals.tv_authzID
#define mech tool_globals.tv_mech
#define realm tool_globals.tv_realm
#define listener_url tool_globals.tv_listener_url
#define peer_domain tool_globals.tv_peer_domain
#define peer_name tool_globals.tv_peer_name
#define sock_name tool_globals.tv_sock_name
#define ssf tool_globals.tv_ssf
#define transport_ssf tool_globals.tv_transport_ssf
#define tls_ssf tool_globals.tv_tls_ssf
#define sasl_ssf tool_globals.tv_sasl_ssf
#define dn_mode tool_globals.tv_dn_mode
#define csnsid tool_globals.tv_csnsid
#define ldif_wrap tool_globals.tv_ldif_wrap

#define SLAP_TOOL_LDAPDN_PRETTY		SLAP_LDAPDN_PRETTY
#define SLAP_TOOL_LDAPDN_NORMAL		(SLAP_LDAPDN_PRETTY << 1)

void slap_tool_init LDAP_P((
	const char* name,
	int tool,
	int argc, char **argv ));

int slap_tool_destroy LDAP_P((void));

#endif /* SLAPCOMMON_H_ */


text:
package com.google.test.metric.report;

/**
 * The various options that affect the reporting of metrics. Just a big JavaBean.
 *
 * @author alexeagle@google.com (Alex Eagle)
 */
public class ReportOptions {
  private double cyclomaticMultiplier;
  private double globalMultiplier;
  private double constructorMultiplier;
  private int maxExcellentCost;
  private int maxAcceptableCost;
  private int worstOffenderCount;
  private int maxMethodCount;
  private int maxLineCount;
  private int printDepth;
  private int minCost;
  private String srcFileLineUrl;
  private String srcFileUrl;

  public ReportOptions(double cyclomaticMultiplier, double globalMultiplier,
                       double constructorMultiplier, int maxExcellentCost,
                       int maxAcceptableCost, int worstOffenderCount, int maxMethodCount,
                       int maxLineCount, int printDepth, int minCost, String srcFileLineUrl,
                       String srcFileUrl) {
    this.cyclomaticMultiplier = cyclomaticMultiplier;
    this.globalMultiplier = globalMultiplier;
    this.constructorMultiplier = constructorMultiplier;
    this.maxExcellentCost = maxExcellentCost;
    this.maxAcceptableCost = maxAcceptableCost;
    this.worstOffenderCount = worstOffenderCount;
    this.maxMethodCount = maxMethodCount;
    this.maxLineCount = maxLineCount;
    this.printDepth = printDepth;
    this.minCost = minCost;
    this.srcFileLineUrl = srcFileLineUrl;
    this.srcFileUrl = srcFileUrl;
  }

  public double getCyclomaticMultiplier() {
    return cyclomaticMultiplier;
  }

  public void setCyclomaticMultiplier(double cyclomaticMultiplier) {
    this.cyclomaticMultiplier = cyclomaticMultiplier;
  }

  public double getGlobalMultiplier() {
    return globalMultiplier;
  }

  public void setGlobalMultiplier(double globalMultiplier) {
    this.globalMultiplier = globalMultiplier;
  }

  public int getMaxExcellentCost() {
    return maxExcellentCost;
  }

  public void setMaxExcellentCost(int maxExcellentCost) {
    this.maxExcellentCost = maxExcellentCost;
  }

  public int getMaxAcceptableCost() {
    return maxAcceptableCost;
  }

  public void setMaxAcceptableCost(int maxAcceptableCost) {
    this.maxAcceptableCost = maxAcceptableCost;
  }

  public int getWorstOffenderCount() {
    return worstOffenderCount;
  }

  public void setWorstOffenderCount(int worstOffenderCount) {
    this.worstOffenderCount = worstOffenderCount;
  }

  public int getMaxMethodCount() {
    return maxMethodCount;
  }

  public void setMaxMethodCount(int maxMethodCount) {
    this.maxMethodCount = maxMethodCount;
  }

  public int getMaxLineCount() {
    return maxLineCount;
  }

  public void setMaxLineCount(int maxLineCount) {
    this.maxLineCount = maxLineCount;
  }

  public int getPrintDepth() {
    return printDepth;
  }

  public void setPrintDepth(int printDepth) {
    this.printDepth = printDepth;
  }

  public int getMinCost() {
    return minCost;
  }

  public void setMinCost(int minCost) {
    this.minCost = minCost;
  }

  public String getSrcFileLineUrl() {
    return srcFileLineUrl;
  }

  public void setSrcFileLineUrl(String srcFileLineUrl) {
    this.srcFileLineUrl = srcFileLineUrl;
  }

  public String getSrcFileUrl() {
    return srcFileUrl;
  }

  public void setSrcFileUrl(String srcFileUrl) {
    this.srcFileUrl = srcFileUrl;
  }

  public double getConstructorMultiplier() {
    return constructorMultiplier;
  }
}


text:
#include "CatalogInformation.h"
#include "PageTree.h"
#include "IndirectObjectsReferenceRegistry.h"

CatalogInformation::CatalogInformation(void)
{
	mCurrentPageTreeNode = NULL;
}

CatalogInformation::~CatalogInformation(void)
{
	Reset();
}

void CatalogInformation::Reset()
{
	if(mCurrentPageTreeNode)
	{
		// delete root
		PageTree* resultPageTree = mCurrentPageTreeNode;
		while(resultPageTree->GetParent())
			resultPageTree = resultPageTree->GetParent();
		delete resultPageTree;
	}
	mCurrentPageTreeNode = NULL;
}

ObjectIDType CatalogInformation::AddPageToPageTree(ObjectIDType inPageID,IndirectObjectsReferenceRegistry& inObjectsRegistry)
{
	if(!mCurrentPageTreeNode)
		mCurrentPageTreeNode = new PageTree(inObjectsRegistry);

	mCurrentPageTreeNode = mCurrentPageTreeNode->AddNodeToTree(inPageID,inObjectsRegistry);
	return mCurrentPageTreeNode->GetID();
}

PageTree* CatalogInformation::GetPageTreeRoot(IndirectObjectsReferenceRegistry& inObjectsRegistry)
{
	if(mCurrentPageTreeNode)
	{
		PageTree* resultPageTree = mCurrentPageTreeNode;
		while(resultPageTree->GetParent())
			resultPageTree = resultPageTree->GetParent();
		return resultPageTree;
	}
	else
	{
		mCurrentPageTreeNode = new PageTree(inObjectsRegistry);
		return mCurrentPageTreeNode;
	}
}

PageTree* CatalogInformation::GetCurrentPageTreeNode()
{
	return mCurrentPageTreeNode;
}

void CatalogInformation::SetCurrentPageTreeNode(PageTree* inCurrentPageTreeNode)
{
	mCurrentPageTreeNode = inCurrentPageTreeNode;
}


text:
#include <cstring>
#include <cstddef>

#include <sstream>
#include <algorithm>

#include <ignite/common/fixed_size_array.h>

#include <ignite/network/network.h>

#include "ignite/odbc/log.h"
#include "ignite/odbc/utility.h"
#include "ignite/odbc/environment.h"
#include "ignite/odbc/statement.h"
#include "ignite/odbc/connection.h"
#include "ignite/odbc/message.h"
#include "ignite/odbc/ssl_mode.h"
#include "ignite/odbc/dsn_config.h"
#include "ignite/odbc/config/configuration.h"
#include "ignite/odbc/config/connection_string_parser.h"

// Uncomment for per-byte debug.
//#define PER_BYTE_DEBUG

namespace
{
#pragma pack(push, 1)
    struct OdbcProtocolHeader
    {
        int32_t len;
    };
#pragma pack(pop)
}

namespace ignite
{
    namespace odbc
    {
        Connection::Connection(Environment* env) :
            env(env),
            socket(),
            timeout(0),
            loginTimeout(DEFAULT_CONNECT_TIMEOUT),
            autoCommit(true),
            parser(),
            config(),
            info(config),
            streamingContext()
        {
            streamingContext.SetConnection(*this);
        }

        Connection::~Connection()
        {
            // No-op.
        }

        const config::ConnectionInfo& Connection::GetInfo() const
        {
            return info;
        }

        void Connection::GetInfo(config::ConnectionInfo::InfoType type, void* buf, short buflen, short* reslen)
        {
            LOG_MSG("SQLGetInfo called: "
                << type << " ("
                << config::ConnectionInfo::InfoTypeToString(type) << "), "
                << std::hex << reinterpret_cast<size_t>(buf) << ", "
                << buflen << ", "
                << std::hex << reinterpret_cast<size_t>(reslen));

            IGNITE_ODBC_API_CALL(InternalGetInfo(type, buf, buflen, reslen));
        }

        SqlResult::Type Connection::InternalGetInfo(config::ConnectionInfo::InfoType type, void* buf, short buflen, short* reslen)
        {
            const config::ConnectionInfo& info = GetInfo();

            SqlResult::Type res = info.GetInfo(type, buf, buflen, reslen);

            if (res != SqlResult::AI_SUCCESS)
                AddStatusRecord(SqlState::SHYC00_OPTIONAL_FEATURE_NOT_IMPLEMENTED, "Not implemented.");

            return res;
        }

        void Connection::Establish(const std::string& connectStr)
        {
            IGNITE_ODBC_API_CALL(InternalEstablish(connectStr));
        }

        SqlResult::Type Connection::InternalEstablish(const std::string& connectStr)
        {
            config::Configuration config;

            config::ConnectionStringParser parser(config);

            parser.ParseConnectionString(connectStr, &GetDiagnosticRecords());

            if (config.IsDsnSet())
            {
                std::string dsn = config.GetDsn();

                ReadDsnConfiguration(dsn.c_str(), config);
            }

            return InternalEstablish(config);
        }

        void Connection::Establish(const config::Configuration cfg)
        {
            IGNITE_ODBC_API_CALL(InternalEstablish(cfg));
        }

        SqlResult::Type Connection::InitSocket()
        {
            ssl::SslMode::Type sslMode = config.GetSslMode();

            if (sslMode == ssl::SslMode::DISABLE)
            {
                socket.reset(network::ssl::MakeTcpSocketClient());

                return SqlResult::AI_SUCCESS;
            }

            try
            {
                network::ssl::EnsureSslLoaded();
            }
            catch (const IgniteError &err)
            {
                LOG_MSG("Can not load OpenSSL library: " << err.GetText());

                AddStatusRecord(SqlState::SHY000_GENERAL_ERROR,
                                "Can not load OpenSSL library (did you set OPENSSL_HOME environment variable?).");

                return SqlResult::AI_ERROR;
            }

            socket.reset(network::ssl::MakeSecureSocketClient(
                config.GetSslCertFile(), config.GetSslKeyFile(), config.GetSslCaFile()));

            return SqlResult::AI_SUCCESS;
        }

        SqlResult::Type Connection::InternalEstablish(const config::Configuration& cfg)
        {
            using ssl::SslMode;

            config = cfg;

            if (socket.get() != 0)
            {
                AddStatusRecord(SqlState::S08002_ALREADY_CONNECTED, "Already connected.");

                return SqlResult::AI_ERROR;
            }

            if (!config.IsHostSet() && config.IsAddressesSet() && config.GetAddresses().empty())
            {
                AddStatusRecord(SqlState::SHY000_GENERAL_ERROR, "No valid address to connect.");

                return SqlResult::AI_ERROR;
            }

            bool connected = TryRestoreConnection();

            if (!connected)
            {
                AddStatusRecord(SqlState::S08001_CANNOT_CONNECT, "Failed to establish connection with the host.");

                return SqlResult::AI_ERROR;
            }

            bool errors = GetDiagnosticRecords().GetStatusRecordsNumber() > 0;

            return errors ? SqlResult::AI_SUCCESS_WITH_INFO : SqlResult::AI_SUCCESS;
        }

        void Connection::Release()
        {
            IGNITE_ODBC_API_CALL(InternalRelease());
        }

        void Connection::Deregister()
        {
            env->DeregisterConnection(this);
        }

        SqlResult::Type Connection::InternalRelease()
        {
            if (socket.get() == 0)
            {
                AddStatusRecord(SqlState::S08003_NOT_CONNECTED, "Connection is not open.");

                return SqlResult::AI_ERROR;
            }

            Close();

            return SqlResult::AI_SUCCESS;
        }

        void Connection::Close()
        {
            if (socket.get() != 0)
            {
                socket->Close();

                socket.reset();
            }
        }

        Statement* Connection::CreateStatement()
        {
            Statement* statement;

            IGNITE_ODBC_API_CALL(InternalCreateStatement(statement));

            return statement;
        }

        SqlResult::Type Connection::InternalCreateStatement(Statement*& statement)
        {
            statement = new Statement(*this);

            if (!statement)
            {
                AddStatusRecord(SqlState::SHY001_MEMORY_ALLOCATION, "Not enough memory.");

                return SqlResult::AI_ERROR;
            }

            return SqlResult::AI_SUCCESS;
        }

        bool Connection::Send(const int8_t* data, size_t len, int32_t timeout)
        {
            if (socket.get() == 0)
                throw OdbcError(SqlState::S08003_NOT_CONNECTED, "Connection is not established");

            int32_t newLen = static_cast<int32_t>(len + sizeof(OdbcProtocolHeader));

            common::FixedSizeArray<int8_t> msg(newLen);

            OdbcProtocolHeader *hdr = reinterpret_cast<OdbcProtocolHeader*>(msg.GetData());

            hdr->len = static_cast<int32_t>(len);

            memcpy(msg.GetData() + sizeof(OdbcProtocolHeader), data, len);

            OperationResult::T res = SendAll(msg.GetData(), msg.GetSize(), timeout);

            if (res == OperationResult::TIMEOUT)
                return false;

            if (res == OperationResult::FAIL)
                throw OdbcError(SqlState::S08S01_LINK_FAILURE, "Can not send message due to connection failure");

#ifdef PER_BYTE_DEBUG
            LOG_MSG("message sent: (" <<  msg.GetSize() << " bytes)" << utility::HexDump(msg.GetData(), msg.GetSize()));
#endif //PER_BYTE_DEBUG

            return true;
        }

        Connection::OperationResult::T Connection::SendAll(const int8_t* data, size_t len, int32_t timeout)
        {
            int sent = 0;

            while (sent != static_cast<int64_t>(len))
            {
                int res = socket->Send(data + sent, len - sent, timeout);

                LOG_MSG("Sent: " << res);

                if (res < 0 || res == network::SocketClient::WaitResult::TIMEOUT)
                {
                    Close();

                    return res < 0 ? OperationResult::FAIL : OperationResult::TIMEOUT;
                }

                sent += res;
            }

            assert(static_cast<size_t>(sent) == len);

            return OperationResult::SUCCESS;
        }

        bool Connection::Receive(std::vector<int8_t>& msg, int32_t timeout)
        {
            if (socket.get() == 0)
                throw OdbcError(SqlState::S08003_NOT_CONNECTED, "Connection is not established");

            msg.clear();

            OdbcProtocolHeader hdr;

            OperationResult::T res = ReceiveAll(reinterpret_cast<int8_t*>(&hdr), sizeof(hdr), timeout);

            if (res == OperationResult::TIMEOUT)
                return false;

            if (res == OperationResult::FAIL)
                throw OdbcError(SqlState::S08S01_LINK_FAILURE, "Can not receive message header");

            if (hdr.len < 0)
            {
                Close();

                throw OdbcError(SqlState::SHY000_GENERAL_ERROR, "Protocol error: Message length is negative");
            }

            if (hdr.len == 0)
                return false;

            msg.resize(hdr.len);

            res = ReceiveAll(&msg[0], hdr.len, timeout);

            if (res == OperationResult::TIMEOUT)
                return false;

            if (res == OperationResult::FAIL)
                throw OdbcError(SqlState::S08S01_LINK_FAILURE, "Can not receive message body");

#ifdef PER_BYTE_DEBUG
            LOG_MSG("Message received: " << utility::HexDump(&msg[0], msg.size()));
#endif //PER_BYTE_DEBUG

            return true;
        }

        Connection::OperationResult::T Connection::ReceiveAll(void* dst, size_t len, int32_t timeout)
        {
            size_t remain = len;
            int8_t* buffer = reinterpret_cast<int8_t*>(dst);

            while (remain)
            {
                size_t received = len - remain;

                int res = socket->Receive(buffer + received, remain, timeout);
                LOG_MSG("Receive res: " << res << " remain: " << remain);

                if (res < 0 || res == network::SocketClient::WaitResult::TIMEOUT)
                {
                    Close();

                    return res < 0 ? OperationResult::FAIL : OperationResult::TIMEOUT;
                }

                remain -= static_cast<size_t>(res);
            }

            return OperationResult::SUCCESS;
        }

        const std::string& Connection::GetSchema() const
        {
            return config.GetSchema();
        }

        const config::Configuration& Connection::GetConfiguration() const
        {
            return config;
        }

        bool Connection::IsAutoCommit() const
        {
            return autoCommit;
        }

        diagnostic::DiagnosticRecord Connection::CreateStatusRecord(SqlState::Type sqlState,
            const std::string& message, int32_t rowNum, int32_t columnNum)
        {
            return diagnostic::DiagnosticRecord(sqlState, message, "", "", rowNum, columnNum);
        }

        void Connection::TransactionCommit()
        {
            IGNITE_ODBC_API_CALL(InternalTransactionCommit());
        }

        SqlResult::Type Connection::InternalTransactionCommit()
        {
            std::string schema = config.GetSchema();

            app::ParameterSet empty;

            QueryExecuteRequest req(schema, "COMMIT", empty, timeout, autoCommit);
            QueryExecuteResponse rsp;

            try
            {
                bool sent = SyncMessage(req, rsp, timeout);

                if (!sent)
                {
                    AddStatusRecord(SqlState::S08S01_LINK_FAILURE, "Failed to send commit request.");

                    return SqlResult::AI_ERROR;
                }
            }
            catch (const OdbcError& err)
            {
                AddStatusRecord(err);

                return SqlResult::AI_ERROR;
            }
            catch (const IgniteError& err)
            {
                AddStatusRecord(SqlState::SHY000_GENERAL_ERROR, err.GetText());

                return SqlResult::AI_ERROR;
            }

            return SqlResult::AI_SUCCESS;
        }

        void Connection::TransactionRollback()
        {
            IGNITE_ODBC_API_CALL(InternalTransactionRollback());
        }

        SqlResult::Type Connection::InternalTransactionRollback()
        {
            std::string schema = config.GetSchema();

            app::ParameterSet empty;

            QueryExecuteRequest req(schema, "ROLLBACK", empty, timeout, autoCommit);
            QueryExecuteResponse rsp;

            try
            {
                bool sent = SyncMessage(req, rsp, timeout);

                if (!sent)
                {
                    AddStatusRecord(SqlState::S08S01_LINK_FAILURE, "Failed to send rollback request.");

                    return SqlResult::AI_ERROR;
                }
            }
            catch (const OdbcError& err)
            {
                AddStatusRecord(err);

                return SqlResult::AI_ERROR;
            }
            catch (const IgniteError& err)
            {
                AddStatusRecord(SqlState::SHY000_GENERAL_ERROR, err.GetText());

                return SqlResult::AI_ERROR;
            }

            return SqlResult::AI_SUCCESS;
        }

        void Connection::GetAttribute(int attr, void* buf, SQLINTEGER bufLen, SQLINTEGER* valueLen)
        {
            IGNITE_ODBC_API_CALL(InternalGetAttribute(attr, buf, bufLen, valueLen));
        }

        SqlResult::Type Connection::InternalGetAttribute(int attr, void* buf, SQLINTEGER, SQLINTEGER* valueLen)
        {
            if (!buf)
            {
                AddStatusRecord(SqlState::SHY009_INVALID_USE_OF_NULL_POINTER, "Data buffer is null.");

                return SqlResult::AI_ERROR;
            }

            switch (attr)
            {
                case SQL_ATTR_CONNECTION_DEAD:
                {
                    SQLUINTEGER *val = reinterpret_cast<SQLUINTEGER*>(buf);

                    *val = socket.get() != 0 ? SQL_CD_FALSE : SQL_CD_TRUE;

                    if (valueLen)
                        *valueLen = SQL_IS_INTEGER;

                    break;
                }

                case SQL_ATTR_CONNECTION_TIMEOUT:
                {
                    SQLUINTEGER *val = reinterpret_cast<SQLUINTEGER*>(buf);

                    *val = static_cast<SQLUINTEGER>(timeout);

                    if (valueLen)
                        *valueLen = SQL_IS_INTEGER;

                    break;
                }

                case SQL_ATTR_LOGIN_TIMEOUT:
                {
                    SQLUINTEGER *val = reinterpret_cast<SQLUINTEGER*>(buf);

                    *val = static_cast<SQLUINTEGER>(loginTimeout);

                    if (valueLen)
                        *valueLen = SQL_IS_INTEGER;

                    break;
                }

                case SQL_ATTR_AUTOCOMMIT:
                {
                    SQLUINTEGER *val = reinterpret_cast<SQLUINTEGER*>(buf);

                    *val = autoCommit ? SQL_AUTOCOMMIT_ON : SQL_AUTOCOMMIT_OFF;

                    if (valueLen)
                        *valueLen = SQL_IS_INTEGER;

                    break;
                }

                default:
                {
                    AddStatusRecord(SqlState::SHYC00_OPTIONAL_FEATURE_NOT_IMPLEMENTED,
                        "Specified attribute is not supported.");

                    return SqlResult::AI_ERROR;
                }
            }

            return SqlResult::AI_SUCCESS;
        }

        void Connection::SetAttribute(int attr, void* value, SQLINTEGER valueLen)
        {
            IGNITE_ODBC_API_CALL(InternalSetAttribute(attr, value, valueLen));
        }

        SqlResult::Type Connection::InternalSetAttribute(int attr, void* value, SQLINTEGER)
        {
            switch (attr)
            {
                case SQL_ATTR_CONNECTION_DEAD:
                {
                    AddStatusRecord(SqlState::SHY092_OPTION_TYPE_OUT_OF_RANGE, "Attribute is read only.");

                    return SqlResult::AI_ERROR;
                }

                case SQL_ATTR_CONNECTION_TIMEOUT:
                {
                    timeout = RetrieveTimeout(value);

                    if (GetDiagnosticRecords().GetStatusRecordsNumber() != 0)
                        return SqlResult::AI_SUCCESS_WITH_INFO;

                    break;
                }

                case SQL_ATTR_LOGIN_TIMEOUT:
                {
                    loginTimeout = RetrieveTimeout(value);

                    if (GetDiagnosticRecords().GetStatusRecordsNumber() != 0)
                        return SqlResult::AI_SUCCESS_WITH_INFO;

                    break;
                }

                case SQL_ATTR_AUTOCOMMIT:
                {
                    SQLUINTEGER mode = static_cast<SQLUINTEGER>(reinterpret_cast<ptrdiff_t>(value));

                    if (mode != SQL_AUTOCOMMIT_ON && mode != SQL_AUTOCOMMIT_OFF)
                    {
                        AddStatusRecord(SqlState::SHYC00_OPTIONAL_FEATURE_NOT_IMPLEMENTED,
                            "Specified attribute is not supported.");

                        return SqlResult::AI_ERROR;
                    }

                    autoCommit = mode == SQL_AUTOCOMMIT_ON;

                    break;
                }

                default:
                {
                    AddStatusRecord(SqlState::SHYC00_OPTIONAL_FEATURE_NOT_IMPLEMENTED,
                        "Specified attribute is not supported.");

                    return SqlResult::AI_ERROR;
                }
            }

            return SqlResult::AI_SUCCESS;
        }

        SqlResult::Type Connection::MakeRequestHandshake()
        {
            ProtocolVersion protocolVersion = config.GetProtocolVersion();

            if (!protocolVersion.IsSupported())
            {
                AddStatusRecord(SqlState::S01S00_INVALID_CONNECTION_STRING_ATTRIBUTE,
                    "Protocol version is not supported: " + protocolVersion.ToString());

                return SqlResult::AI_ERROR;
            }

            if (protocolVersion < ProtocolVersion::VERSION_2_5_0 && !config.GetUser().empty())
            {
                AddStatusRecord(SqlState::S01S00_INVALID_CONNECTION_STRING_ATTRIBUTE,
                    "Authentication is not allowed for protocol version below 2.5.0");

                return SqlResult::AI_ERROR;
            }

            HandshakeRequest req(config);
            HandshakeResponse rsp;

            try
            {
                // Workaround for some Linux systems that report connection on non-blocking
                // sockets as successful but fail to establish real connection.
                bool sent = InternalSyncMessage(req, rsp, loginTimeout);

                if (!sent)
                {
                    AddStatusRecord(SqlState::S08001_CANNOT_CONNECT,
                        "Failed to get handshake response (Did you forget to enable SSL?).");

                    return SqlResult::AI_ERROR;
                }
            }
            catch (const OdbcError& err)
            {
                AddStatusRecord(err);

                return SqlResult::AI_ERROR;
            }
            catch (const IgniteError& err)
            {
                AddStatusRecord(SqlState::S08004_CONNECTION_REJECTED, err.GetText());

                return SqlResult::AI_ERROR;
            }

            if (!rsp.IsAccepted())
            {
                LOG_MSG("Handshake message has been rejected.");

                std::stringstream constructor;

                constructor << "Node rejected handshake message. ";

                if (!rsp.GetError().empty())
                    constructor << "Additional info: " << rsp.GetError() << " ";

                constructor << "Current version of the protocol, used by the server node is "
                            << rsp.GetCurrentVer().ToString() << ", "
                            << "driver protocol version introduced in version "
                            << protocolVersion.ToString() << ".";

                AddStatusRecord(SqlState::S08004_CONNECTION_REJECTED, constructor.str());

                return SqlResult::AI_ERROR;
            }

            return SqlResult::AI_SUCCESS;
        }

        void Connection::EnsureConnected()
        {
            if (socket.get() != 0)
                return;

            bool success = TryRestoreConnection();

            if (!success)
                throw OdbcError(SqlState::S08001_CANNOT_CONNECT,
                    "Failed to establish connection with any provided hosts");
        }

        bool Connection::TryRestoreConnection()
        {
            std::vector<EndPoint> addrs;

            CollectAddresses(config, addrs);

            if (socket.get() == 0)
            {
                SqlResult::Type res = InitSocket();

                if (res != SqlResult::AI_SUCCESS)
                    return false;
            }

            bool connected = false;

            while (!addrs.empty() && !connected)
            {
                const EndPoint& addr = addrs.back();

                for (uint16_t port = addr.port; port <= addr.port + addr.range; ++port)
                {
                    try
                    {
                        connected = socket->Connect(addr.host.c_str(), port, loginTimeout);
                    }
                    catch (const IgniteError& err)
                    {
                        LOG_MSG("Error while trying connect to " << addr.host << ":" << addr.port <<", " << err.GetText());
                    }

                    if (connected)
                    {
                        SqlResult::Type res = MakeRequestHandshake();

                        connected = res != SqlResult::AI_ERROR;

                        if (connected)
                            break;
                    }
                }

                addrs.pop_back();
            }

            if (!connected)
                Close();
            else
                parser.SetProtocolVersion(config.GetProtocolVersion());

            return connected;
        }

        void Connection::CollectAddresses(const config::Configuration& cfg, std::vector<EndPoint>& endPoints)
        {
            endPoints.clear();

            if (!cfg.IsAddressesSet())
            {
                LOG_MSG("'Address' is not set. Using legacy connection method.");

                endPoints.push_back(EndPoint(cfg.GetHost(), cfg.GetTcpPort()));

                return;
            }

            endPoints = cfg.GetAddresses();

            std::random_shuffle(endPoints.begin(), endPoints.end());
        }

        int32_t Connection::RetrieveTimeout(void* value)
        {
            SQLUINTEGER uTimeout = static_cast<SQLUINTEGER>(reinterpret_cast<ptrdiff_t>(value));

            if (uTimeout != 0 && socket.get() != 0 && socket->IsBlocking())
            {
                AddStatusRecord(SqlState::S01S02_OPTION_VALUE_CHANGED, "Can not set timeout, because can not "
                    "enable non-blocking mode on TCP connection. Setting to 0.");

                return 0;
            }

            if (uTimeout > INT32_MAX)
            {
                std::stringstream ss;

                ss << "Value is too big: " << uTimeout << ", changing to " << timeout << ".";

                AddStatusRecord(SqlState::S01S02_OPTION_VALUE_CHANGED, ss.str());

                return INT32_MAX;
            }

            return static_cast<int32_t>(uTimeout);
        }
    }
}


text:
package com.example.tictactoe.baseboard

import com.example.tictactoe.player.PlayerMark
import com.example.tictactoe.{InvalidMoveException,InvalidPositionException}
import com.example.tictactoe.player.{X,O,Empty}
import com.example.tictactoe.baseboard.Board.Position

/**
 * @author s.a.ramamuniappa
 */
class Board private (val squares: List[Square]) {

  override def toString = squares.toString()

  def move(position: Position, mark: PlayerMark): Board = {
    isValidMove(position) match {
      case Left(valid) if valid => Board(squares updated(position, Square(position,mark)))
      case Right(invalidMove)   => throw invalidMove
    }
  }

  def whoWon : Option[PlayerMark] = {
   val playerAndTheirMarkinPosition = squares.groupBy(_.marking).mapValues(_.map ( _.position )).par

   playerAndTheirMarkinPosition.find( squares => hasWon(squares._2)).fold[Option[PlayerMark]](None)( a => Some(a._1))
  }

  private def hasWon(finalPositions : List[Position]) = {
      Board.winCombinations.par.find{ combination => combination.par.forall(finalPositions.contains(_)) } isDefined
  }

  def markingAtPosition(position: Position): PlayerMark = {
    squares.find(_.position equals position).fold(throw new InvalidPositionException(position))(_.marking)
  }

  def isBoardEmpty = {
    squares.forall(_.marking equals Empty)
  }

  def maxOccuranceOfNonEmptyMarking : Option[PlayerMark] = {
    val occuranceOfXandY = squares.foldLeft((0,0)){
      case((x,o),Square(pos,mark)) if(mark equals X) => (x+1,o)
      case((x,o),Square(pos,mark)) if(mark equals O) => (x,o+1)
      case((x,o),Square(pos,mark)) if(mark equals Empty) => (x,o)
    }
    occuranceOfXandY match {
      case (occuranceOfX,occuranceOfO) if occuranceOfX > occuranceOfO => Some(X)
      case (occuranceOfX,occuranceOfO) if occuranceOfO > occuranceOfX => Some(O)
      case _ => None
    }
 }

  private def isValidMove(position: Position): Either[Boolean, Exception] = {
    position match {
      case pos if !isValidPosition(pos) => Right(new InvalidPositionException(pos))
      case pos if !isPositionAvailable(pos) => Right(new InvalidMoveException(pos))
      case validPos => Left(true)
    }
  }

  private def isPositionAvailable(position: Position) = {
    squares find { square => (square.position equals position) && (square.marking equals Empty) } isDefined
  }
}

object Board {

  type Position = Int

  val winCombinations = List(List(0, 1, 2),List(3, 4, 5),List(6, 7, 8),List(0, 3, 6),
                              List(1, 4, 7),List(0, 4, 8),List(0, 4, 8),List(2, 4, 6))

  def apply()= {
    val squares = List.fill(9)(Empty).zipWithIndex.map{ case (mark, position) => Square(position,mark)}
    new Board(squares)
  }

  def apply(squares: List[Square]) = {
    new Board(squares)
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Duracellko.WindowsAzureVmManager.Model
{
    public class HostedServices
    {
        public HostedServices()
        {
            this.Services = new List<HostedService>();
        }

        public IList<HostedService> Services { get; private set; }
    }
}


text:
"""Django ORM models for Social Auth"""
import base64
import six

from social.exceptions import NotAllowedToDisconnect
from social.storage.base import UserMixin, AssociationMixin, NonceMixin, \
                                BaseStorage

class DjangoUserMixin(UserMixin):
    """Social Auth association model"""
    @classmethod
    def changed(cls, user):
        user.save()

    def set_extra_data(self, extra_data=None):
        if super(DjangoUserMixin, self).set_extra_data(extra_data):
            self.save()

    @classmethod
    def allowed_to_disconnect(cls, user, backend_name, association_id=None):
        if association_id is not None:
            qs = cls.objects.exclude(id=association_id)
        else:
            qs = cls.objects.exclude(provider=backend_name)
        qs = qs.filter(user=user)

        if hasattr(user, 'has_usable_password'):
            valid_password = user.has_usable_password()
        else:
            valid_password = True
        return valid_password or qs.count() > 0

    @classmethod
    def disconnect(cls, name, user, association_id=None):
        if cls.allowed_to_disconnect(user, name, association_id):
            qs = cls.get_social_auth_for_user(user)
            if association_id:
                qs = qs.get(id=association_id)
            else:
                qs = qs.filter(provider=name)
            qs.delete()
        else:
            raise NotAllowedToDisconnect()

    @classmethod
    def user_exists(cls, username):
        """
        Return True/False if a User instance exists with the given arguments.
        Arguments are directly passed to filter() manager method.
        """
        return cls.user_model().objects.filter(username=username).count() > 0

    @classmethod
    def get_username(cls, user):
        return getattr(user, 'username', None)

    @classmethod
    def create_user(cls, username, email=None):
        return cls.user_model().objects.create_user(username=username,
                                                    email=email)

    @classmethod
    def get_user(cls, pk):
        try:
            return cls.user_model().objects.get(pk=pk)
        except cls.user_model().DoesNotExist:
            return None

    @classmethod
    def get_social_auth(cls, provider, uid):
        if not isinstance(uid, six.string_types):
            uid = str(uid)
        try:
            return cls.objects.get(provider=provider, uid=uid)
        except cls.DoesNotExist:
            return None

    @classmethod
    def get_social_auth_for_user(cls, user):
        return cls.objects.all()

    @classmethod
    def create_social_auth(cls, user, uid, provider):
        if not isinstance(uid, six.string_types):
            uid = str(uid)
        return cls.objects.create(user=user, uid=uid, provider=provider)

class DjangoNonceMixin(NonceMixin):
    @classmethod
    def use(cls, server_url, timestamp, salt):
        return cls.objects.get_or_create(server_url=server_url,
                                         timestamp=timestamp,
                                         salt=salt)[1]

class DjangoAssociationMixin(AssociationMixin):
    @classmethod
    def store(cls, server_url, association):
        # Don't use get_or_create because issued cannot be null
        try:
            assoc = cls.objects.get(server_url=server_url,
                                    handle=association.handle)
        except cls.DoesNotExist:
            assoc = cls(server_url=server_url,
                        handle=association.handle)
        assoc.secret = base64.encodestring(association.secret)
        assoc.issued = association.issued
        assoc.lifetime = association.lifetime
        assoc.assoc_type = association.assoc_type
        assoc.save()

    @classmethod
    def get(cls, *args, **kwargs):
        return cls.objects.filter(*args, **kwargs)

    @classmethod
    def remove(cls, ids_to_delete):
        cls.objects.filter(pk__in=ids_to_delete).delete()

class BaseDjangoStorage(BaseStorage):
    user = DjangoUserMixin
    nonce = DjangoNonceMixin
    association = DjangoAssociationMixin


text:
/**
 * Class constructor for Tabs WSK component.
 * Implements WSK component design pattern defined at:
 * https://github.com/jasonmayes/mdl-component-design-pattern
 * @param {HTMLElement} element The element that will be upgraded.
 */
function MaterialTabs(element) {
  'use strict';

  // Stores the HTML element.
  this.element_ = element;

  // Initialize instance.
  this.init();
}

/**
 * Store constants in one place so they can be updated easily.
 * @enum {string}
 * @private
 */
MaterialTabs.prototype.Constant_ = {
  // None at the moment.
};

/**
 * Store strings for class names defined by this component that are used in
 * JavaScript. This allows us to simply change it in one place should we
 * decide to modify at a later date.
 * @enum {string}
 * @private
 */
MaterialTabs.prototype.CssClasses_ = {
  TAB_CLASS: 'mdl-tabs__tab',
  PANEL_CLASS: 'mdl-tabs__panel',
  ACTIVE_CLASS: 'is-active',
  UPGRADED_CLASS: 'is-upgraded',

  WSK_JS_RIPPLE_EFFECT: 'mdl-js-ripple-effect',
  WSK_RIPPLE_CONTAINER: 'mdl-tabs__ripple-container',
  WSK_RIPPLE: 'mdl-ripple',
  WSK_JS_RIPPLE_EFFECT_IGNORE_EVENTS: 'mdl-js-ripple-effect--ignore-events'
};

/**
 * Handle clicks to a tabs component
 * @private
 */
MaterialTabs.prototype.initTabs_ = function(e) {
  'use strict';

  if (this.element_.classList.contains(this.CssClasses_.WSK_JS_RIPPLE_EFFECT)) {
    this.element_.classList.add(
      this.CssClasses_.WSK_JS_RIPPLE_EFFECT_IGNORE_EVENTS);
  }

  // Select element tabs, document panels
  this.tabs_ = this.element_.querySelectorAll('.' + this.CssClasses_.TAB_CLASS);
  this.panels_ =
      this.element_.querySelectorAll('.' + this.CssClasses_.PANEL_CLASS);

  // Create new tabs for each tab element
  for (var i = 0; i < this.tabs_.length; i++) {
    new MaterialTab(this.tabs_[i], this);
  }

  this.element_.classList.add(this.CssClasses_.UPGRADED_CLASS);
};

/**
 * Reset tab state, dropping active classes
 * @private
 */
MaterialTabs.prototype.resetTabState_ = function() {
  'use strict';

  for (var k = 0; k < this.tabs_.length; k++) {
    this.tabs_[k].classList.remove(this.CssClasses_.ACTIVE_CLASS);
  }
};

/**
 * Reset panel state, droping active classes
 * @private
 */
MaterialTabs.prototype.resetPanelState_ = function() {
  'use strict';

  for (var j = 0; j < this.panels_.length; j++) {
    this.panels_[j].classList.remove(this.CssClasses_.ACTIVE_CLASS);
  }
};

MaterialTabs.prototype.init = function() {
  'use strict';

  if (this.element_) {
    this.initTabs_();
  }
};

function MaterialTab(tab, ctx) {
  'use strict';

  if (tab) {
    if (ctx.element_.classList.contains(ctx.CssClasses_.WSK_JS_RIPPLE_EFFECT)) {
      var rippleContainer = document.createElement('span');
      rippleContainer.classList.add(ctx.CssClasses_.WSK_RIPPLE_CONTAINER);
      rippleContainer.classList.add(ctx.CssClasses_.WSK_JS_RIPPLE_EFFECT);
      var ripple = document.createElement('span');
      ripple.classList.add(ctx.CssClasses_.WSK_RIPPLE);
      rippleContainer.appendChild(ripple);
      tab.appendChild(rippleContainer);
    }

    tab.addEventListener('click', function(e) {
      e.preventDefault();
      var href = tab.href.split('#')[1];
      var panel = ctx.element_.querySelector('#' + href);
      ctx.resetTabState_();
      ctx.resetPanelState_();
      tab.classList.add(ctx.CssClasses_.ACTIVE_CLASS);
      panel.classList.add(ctx.CssClasses_.ACTIVE_CLASS);
    });

  }
}

// The component registers itself. It can assume componentHandler is available
// in the global scope.
componentHandler.register({
  constructor: MaterialTabs,
  classAsString: 'MaterialTabs',
  cssClass: 'mdl-js-tabs'
});


text:
package org.apache.nifi.remote.client;

import static org.apache.nifi.remote.util.EventReportUtil.error;
import static org.apache.nifi.remote.util.EventReportUtil.warn;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import javax.validation.constraints.NotNull;
import org.apache.nifi.events.EventReporter;
import org.apache.nifi.remote.Peer;
import org.apache.nifi.remote.PeerDescription;
import org.apache.nifi.remote.PeerStatus;
import org.apache.nifi.remote.TransferDirection;
import org.apache.nifi.remote.protocol.SiteToSiteTransportProtocol;
import org.apache.nifi.remote.util.PeerStatusCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Service which maintains state around peer (NiFi node(s) in a remote instance (cluster or
 * standalone)). There is an internal cache which stores identifying information about each
 * node and the current workload of each in number of flowfiles being processed. Individual
 * nodes can be penalized for an amount of time (see {@link #penalize(Peer, long)}) to avoid
 * sending/receiving data from them. Attempts are made to balance communications ("busier"
 * nodes will {@code TransferDirection.SEND} more and {@code TransferDirection.RECEIVE} fewer
 * flowfiles from this instance).
 */
public class PeerSelector {
    private static final Logger logger = LoggerFactory.getLogger(PeerSelector.class);

    // The timeout for the peer status cache
    private static final long PEER_CACHE_MILLIS = TimeUnit.MILLISECONDS.convert(1, TimeUnit.MINUTES);

    // The service which saves the peer state to persistent storage
    private final PeerPersistence peerPersistence;

    // The service which retrieves peer state
    private final PeerStatusProvider peerStatusProvider;

    // Maps the peer description to a millisecond penalty expiration
    private final ConcurrentMap<PeerDescription, Long> peerPenaltyExpirations = new ConcurrentHashMap<>();

    // The most recently fetched peer statuses
    private volatile PeerStatusCache peerStatusCache;

    private EventReporter eventReporter;

    /**
     * Returns a peer selector with the provided collaborators.
     *
     * @param peerStatusProvider the service which retrieves peer state
     * @param peerPersistence    the service which persists peer state
     */
    public PeerSelector(final PeerStatusProvider peerStatusProvider, final PeerPersistence peerPersistence) {
        this.peerStatusProvider = peerStatusProvider;
        this.peerPersistence = peerPersistence;

        // On instantiation, retrieve the peer status cache
        restoreInitialPeerStatusCache();
    }

    /**
     * Populates the peer status cache from the peer persistence provider (e.g. the file system or
     * persisted cluster state). If this fails, it will log a warning and continue, as it is not
     * required for startup. If the cached protocol differs from the currently configured protocol,
     * the cache will be cleared.
     */
    private void restoreInitialPeerStatusCache() {
        try {
            PeerStatusCache restoredPeerStatusCache = null;
            if (peerPersistence != null) {
                restoredPeerStatusCache = peerPersistence.restore();

                // If there is an existing cache, ensure that the protocol matches the current protocol
                if (restoredPeerStatusCache != null) {
                    final SiteToSiteTransportProtocol currentProtocol = peerStatusProvider.getTransportProtocol();
                    final SiteToSiteTransportProtocol cachedProtocol = restoredPeerStatusCache.getTransportProtocol();

                    // If the protocols have changed, clear the cache
                    if (!currentProtocol.equals(cachedProtocol)) {
                        logger.warn("Discard stored peer statuses in {} because transport protocol has changed from {} to {}",
                                peerPersistence.getClass().getSimpleName(), cachedProtocol, currentProtocol);
                        restoredPeerStatusCache = null;
                    }
                }
            }
            this.peerStatusCache = restoredPeerStatusCache;
        } catch (final IOException ioe) {
            logger.warn("Failed to recover peer statuses from {} due to {}; will continue without loading information from file",
                    peerPersistence.getClass().getSimpleName(), ioe);
        }
    }

    /**
     * Returns the normalized weight for this ratio of peer flowfiles to total flowfiles and the given direction. The number will be
     * a Double between 0 and 100 indicating the percent of all flowfiles the peer
     * should send/receive. The transfer direction is from the perspective of this node to the peer
     * (i.e. how many flowfiles should this node send to the peer, or how many flowfiles
     * should this node receive from the peer).
     *
     * @param direction          the transfer direction ({@code SEND} weights the destinations higher if they have fewer flowfiles, {@code RECEIVE} weights them higher if they have more)
     * @param totalFlowFileCount the total flowfile count in the remote instance (standalone or cluster)
     * @param flowFileCount      the flowfile count for the given peer
     * @param peerCount          the number of peers in the remote instance
     * @return the normalized weight of this peer
     */
    private static double calculateNormalizedWeight(TransferDirection direction, long totalFlowFileCount, int flowFileCount, int peerCount) {
        // If there is only a single remote, send/receive all data to/from it
        if (peerCount == 1) {
            return 100;
        }

        double cappedPercent;
        // If no flowfiles exist in the remote instance, evenly weight each node with 1/N
        if (totalFlowFileCount == 0) {
            cappedPercent = 1.0 / peerCount;
        } else {
            final double percentageOfFlowFiles = ((double) flowFileCount / totalFlowFileCount);
            cappedPercent = percentageOfFlowFiles;

            // If sending to the remote, allocate more flowfiles to the less-stressed peers
            if (direction == TransferDirection.SEND) {
                cappedPercent = (1 - percentageOfFlowFiles) / (peerCount - 1);
            }
        }
        return new BigDecimal(cappedPercent * 100).setScale(2, RoundingMode.FLOOR).doubleValue();
    }

    /**
     * Returns an ordered map of peers sorted in descending order by value (relative weight).
     *
     * @param unsortedMap the unordered map of peers to weights
     * @return the sorted (desc) map (by value)
     */
    private static LinkedHashMap<PeerStatus, Double> sortMapByWeight(Map<PeerStatus, Double> unsortedMap) {
        List<Map.Entry<PeerStatus, Double>> list = new ArrayList<>(unsortedMap.entrySet());
        list.sort(Map.Entry.comparingByValue());

        LinkedHashMap<PeerStatus, Double> result = new LinkedHashMap<>();
        for (int i = list.size() - 1; i >= 0; i--) {
            Map.Entry<PeerStatus, Double> entry = list.get(i);
            result.put(entry.getKey(), entry.getValue());
        }

        return result;
    }

    /**
     * Prints the distribution of the peers to the logger.
     *
     * @param sortedPeerWorkloads the peers and relative weights
     */
    private static void printDistributionStatistics(Map<PeerStatus, Double> sortedPeerWorkloads, TransferDirection direction) {
        if (logger.isDebugEnabled() && sortedPeerWorkloads != null) {
            DecimalFormat df = new DecimalFormat("##.##");
            df.setRoundingMode(RoundingMode.FLOOR);
            final StringBuilder distributionDescription = new StringBuilder();
            distributionDescription.append("New weighted distribution of nodes:");
            for (final Map.Entry<PeerStatus, Double> entry : sortedPeerWorkloads.entrySet()) {
                final double percentage = entry.getValue();
                distributionDescription.append("\n").append(entry.getKey())
                        .append(" will").append(direction == TransferDirection.RECEIVE ? " send " : " receive ")
                        .append(df.format(percentage)).append("% of data");
            }
            logger.debug(distributionDescription.toString());
        }
    }

    /**
     * Returns the total of all values in the map. This method is frequently used to calculate the total number of
     * flowfiles in the instance from the respective peer flowfile counts or the total percentage from the relative weights.
     *
     * @param peerWeightMap the map of peers to flowfile counts or relative weights
     * @return the total of the map values
     */
    private static double sumMapValues(Map<PeerStatus, Double> peerWeightMap) {
        return peerWeightMap.values().stream().mapToDouble(Double::doubleValue).sum();
    }

    /**
     * Resets all penalization states for the peers.
     */
    public void clear() {
        peerPenaltyExpirations.clear();
    }

    /**
     * Return status of a peer that will be used for the next communication.
     * The peers with lower workloads will be selected with higher probability.
     *
     * @param direction the amount of workload is calculated based on transaction direction,
     *                  for SEND, a peer with fewer flow files is preferred,
     *                  for RECEIVE, a peer with more flow files is preferred
     * @return a selected peer, if there is no available peer or all peers are penalized, then return null
     */
    public PeerStatus getNextPeerStatus(final TransferDirection direction) {
        Set<PeerStatus> peerStatuses = getPeerStatuses();
        Map<PeerStatus, Double> orderedPeerStatuses = buildWeightedPeerMap(peerStatuses, direction);

        return getAvailablePeerStatus(orderedPeerStatuses);
    }

    /**
     * Returns {@code true} if this peer is currently penalized and should not send/receive flowfiles.
     *
     * @param peerStatus the peer status identifying the peer
     * @return true if this peer is penalized
     */
    public boolean isPenalized(final PeerStatus peerStatus) {
        final Long expirationEnd = peerPenaltyExpirations.get(peerStatus.getPeerDescription());
        return (expirationEnd != null && expirationEnd > System.currentTimeMillis());
    }

    /**
     * Updates internal state map to penalize a PeerStatus that points to the
     * specified peer.
     *
     * @param peer               the peer
     * @param penalizationMillis period of time to penalize a given peer (relative time, not absolute)
     */
    public void penalize(final Peer peer, final long penalizationMillis) {
        penalize(peer.getDescription(), penalizationMillis);
    }

    /**
     * Updates internal state map to penalize a PeerStatus that points to the
     * specified peer.
     *
     * @param peerDescription    the peer description (identifies the peer)
     * @param penalizationMillis period of time to penalize a given peer (relative time, not absolute)
     */
    public void penalize(final PeerDescription peerDescription, final long penalizationMillis) {
        Long expiration = peerPenaltyExpirations.get(peerDescription);
        if (expiration == null) {
            expiration = 0L;
        }

        final long newExpiration = Math.max(expiration, System.currentTimeMillis() + penalizationMillis);
        peerPenaltyExpirations.put(peerDescription, newExpiration);
    }

    /**
     * Allows for external callers to trigger a refresh of the internal peer status cache. Performs the refresh if the cache has expired. If the cache is still valid, skips the refresh.
     */
    public void refresh() {
        long cacheAgeMs = getCacheAge();
        logger.debug("External refresh triggered. Last refresh was {} ms ago", cacheAgeMs);
        if (isPeerRefreshNeeded()) {
            logger.debug("Refreshing peer status cache");
            refreshPeerStatusCache();
        } else {
            logger.debug("Cache is still valid; skipping refresh");
        }
    }

    /**
     * Sets the event reporter instance.
     *
     * @param eventReporter the event reporter
     */
    public void setEventReporter(EventReporter eventReporter) {
        this.eventReporter = eventReporter;
    }

    /**
     * Returns a map of peers prepared for flowfile transfer in the specified direction. Each peer is a key and the value is a
     * weighted percentage of the total flowfiles in the remote instance. For example, in a cluster where the total number of flowfiles
     * is 100, distributed across three nodes 20 in A, 30 in B, and 50 in C, the resulting map for
     * {@code SEND} will be {@code [A:40.0, B:35.0, C:25.0]} (1 - .2 => .8 * 100 / (3-1)) => 40.0).
     *
     * @param statuses  the set of all peers
     * @param direction the direction of transfer ({@code SEND} weights the destinations higher if they have more flowfiles, {@code RECEIVE} weights them higher if they have fewer)
     * @return the ordered map of each peer to its relative weight
     */
    LinkedHashMap<PeerStatus, Double> buildWeightedPeerMap(final Set<PeerStatus> statuses, final TransferDirection direction) {
        // Get all the destinations with their relative weights
        final Map<PeerStatus, Double> peerWorkloads = createDestinationMap(statuses, direction);

        if (!peerWorkloads.isEmpty()) {
            // This map is sorted, but not by key, so it cannot use SortedMap
            LinkedHashMap<PeerStatus, Double> sortedPeerWorkloads = sortMapByWeight(peerWorkloads);

            // Print the expected distribution of the peers
            printDistributionStatistics(sortedPeerWorkloads, direction);

            return sortedPeerWorkloads;
        } else {
            logger.debug("No peers available");
            return new LinkedHashMap<>();
        }
    }

    /**
     * Returns a map indexed by a peer to the normalized weight (number of flowfiles currently being
     * processed by the peer as a percentage of the total). This is used to allocate flowfiles to
     * the various peers as destinations.
     *
     * @param peerStatuses the set of peers, along with their current workload (number of flowfiles)
     * @param direction    whether sending flowfiles to these peers or receiving them
     * @return the map of weighted peers
     */
    @NotNull
    private Map<PeerStatus, Double> createDestinationMap(Set<PeerStatus> peerStatuses, TransferDirection direction) {
        final Map<PeerStatus, Double> peerWorkloads = new HashMap<>();

        // Calculate the total number of flowfiles in the peers
        long totalFlowFileCount = peerStatuses.stream().mapToLong(PeerStatus::getFlowFileCount).sum();
        logger.debug("Building weighted map of peers with total remote NiFi flowfile count: {}", totalFlowFileCount);

        // For each node, calculate the relative weight and store it in the map
        for (final PeerStatus nodeInfo : peerStatuses) {
            final int flowFileCount = nodeInfo.getFlowFileCount();
            final double normalizedWeight = calculateNormalizedWeight(direction, totalFlowFileCount, flowFileCount, peerStatuses.size());
            peerWorkloads.put(nodeInfo, normalizedWeight);
        }

        return peerWorkloads;
    }

    /**
     * Returns a set of {@link PeerStatus} objects representing all remote peers for the provided
     * {@link PeerDescription}s. If a queried peer returns updated state on a peer which has already
     * been captured, the new state is used.
     *

     * Example:
     *

     * 3 node cluster with nodes A, B, C
     *

     * Node A knows about Node B and Node C, B about A and C, etc.
     *
     *

     *     Action                           |   Statuses
     *     query(A) -> B.status, C.status   |   Bs1, Cs1
     *     query(B) -> A.status, C.status   |   As1, Bs1, Cs2
     *     query(C) -> A.status, B.status   |   As2, Bs2, Cs2
     *

     *
     * @param peersToRequestClusterInfoFrom the set of peers to query
     * @return the complete set of statuses for each collection of peers
     * @throws IOException if there is a problem fetching peer statuses
     */
    private Set<PeerStatus> fetchRemotePeerStatuses(Set<PeerDescription> peersToRequestClusterInfoFrom) throws IOException {
        logger.debug("Fetching remote peer statuses from: {}", peersToRequestClusterInfoFrom);
        Exception lastFailure = null;

        final Set<PeerStatus> allPeerStatuses = new HashSet<>();

        // Iterate through all peers, getting (sometimes multiple) status(es) from each
        for (final PeerDescription peerDescription : peersToRequestClusterInfoFrom) {
            try {
                // Retrieve the peer status(es) from each peer description
                final Set<PeerStatus> statusesForPeerDescription = peerStatusProvider.fetchRemotePeerStatuses(peerDescription);

                // Filter to remove any peers which are not queryable
                final Set<PeerStatus> filteredStatuses = statusesForPeerDescription.stream()
                        .filter(PeerStatus::isQueryForPeers)
                        .collect(Collectors.toSet());

                allPeerStatuses.addAll(filteredStatuses);
            } catch (final Exception e) {
                logger.warn("Could not communicate with {}:{} to determine which node(s) exist in the remote NiFi instance, due to {}",
                        peerDescription.getHostname(), peerDescription.getPort(), e.toString());
                lastFailure = e;
            }
        }

        // If no peers were fetched and an exception was the cause, throw an exception
        if (allPeerStatuses.isEmpty() && lastFailure != null) {
            throw new IOException("Unable to retrieve nodes from remote instance", lastFailure);
        }

        return allPeerStatuses;
    }

    /**
     * Returns the {@link PeerStatus} identifying the next peer to send/receive data. This uses random
     * selection of peers, weighted by the relative desirability (i.e. for {@code SEND}, peers with more
     * flowfiles are more likely to be selected, and for {@code RECEIVE}, peers with fewer flowfiles are
     * more likely).
     *
     * @param orderedPeerStatuses the map of peers to relative weights, sorted in descending order by weight
     * @return the peer to send/receive data
     */
    private PeerStatus getAvailablePeerStatus(Map<PeerStatus, Double> orderedPeerStatuses) {
        if (orderedPeerStatuses == null || orderedPeerStatuses.isEmpty()) {
            logger.warn("Available peers collection is empty; no peer available");
            return null;
        }

        // Only distribute to unpenalized peers
        Map<PeerStatus, Double> unpenalizedPeers = orderedPeerStatuses.entrySet().stream()
                .filter(e -> !isPenalized(e.getKey()))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

        final double totalWeights = sumMapValues(unpenalizedPeers);
        logger.debug("Determining next available peer ({} peers with total weight {})", unpenalizedPeers.keySet().size(), totalWeights);

        final double random = Math.random() * Math.min(100, totalWeights);
        logger.debug("Generated random value {}", random);

        double threshold = 0.0;
        for (Map.Entry<PeerStatus, Double> e : unpenalizedPeers.entrySet()) {
            logger.debug("Initial threshold was {}; added peer value {}; total {}", threshold, e.getValue(), threshold + e.getValue());
            threshold += e.getValue();
            if (random <= threshold) {
                return e.getKey();
            }
        }

        logger.debug("Did not select a peer; r {}, t {}, w {}", random, threshold, orderedPeerStatuses.values());
        logger.debug("All peers appear to be penalized; returning null");
        return null;
    }

    /**
     * Returns the cache age in milliseconds. If the cache is null or not set, returns {@code -1}.
     *
     * @return the cache age in millis
     */
    private long getCacheAge() {
        if (peerStatusCache == null) {
            return -1;
        }
        return System.currentTimeMillis() - peerStatusCache.getTimestamp();
    }

    /**
     * Returns the set of queryable peers ({@link PeerStatus#isQueryForPeers()}) most recently fetched.
     *
     * @return the set of queryable peers (empty set if the cache is {@code null})
     */
    @NotNull
    private Set<PeerStatus> getLastFetchedQueryablePeers() {
        return peerStatusCache != null ? peerStatusCache.getStatuses() : Collections.emptySet();
    }

    /**
     * Returns the set of peer statuses. If the cache is {@code null} or empty, refreshes the cache first and then returns the new peer status set.
     *
     * @return the most recent peer statuses (empty set if the cache is {@code null})
     */
    @NotNull
    private Set<PeerStatus> getPeerStatuses() {
        if (isPeerRefreshNeeded()) {
            refreshPeerStatusCache();
        }

        return getLastFetchedQueryablePeers();
    }

    /**
     * Returns the set of {@link PeerDescription} objects uniquely identifying each NiFi node which should be queried for {@link PeerStatus}.
     *
     * @return the set of recently retrieved peers and the bootstrap peer
     * @throws IOException if there is a problem retrieving the list of peers to query
     */
    private Set<PeerDescription> getPeersToQuery() throws IOException {
        final Set<PeerDescription> peersToRequestClusterInfoFrom = new HashSet<>();

        // Use the peers fetched last time
        final Set<PeerStatus> lastFetched = getLastFetchedQueryablePeers();
        if (lastFetched != null && !lastFetched.isEmpty()) {
            for (PeerStatus peerStatus : lastFetched) {
                peersToRequestClusterInfoFrom.add(peerStatus.getPeerDescription());
            }
        }

        // Always add the configured node info to the list of peers
        peersToRequestClusterInfoFrom.add(peerStatusProvider.getBootstrapPeerDescription());

        return peersToRequestClusterInfoFrom;
    }

    /**
     * Returns {@code true} if this cache has expired.
     *
     * @param cache the peer status cache
     * @return true if the cache is expired
     */
    private boolean isCacheExpired(PeerStatusCache cache) {
        return cache == null || cache.getTimestamp() + PEER_CACHE_MILLIS < System.currentTimeMillis();
    }

    /**
     * Returns {@code true} if the internal collection of peers is empty or the refresh time has passed.
     *
     * @return true if the peer statuses should be refreshed
     */
    private boolean isPeerRefreshNeeded() {
        return (peerStatusCache == null || peerStatusCache.isEmpty() || isCacheExpired(peerStatusCache));
    }

    /**
     * Persists the provided cache instance (in memory and via the {@link PeerPersistence} (e.g. in cluster state or a local file)) for future retrieval.
     *
     * @param peerStatusCache the cache of current peer statuses to persist
     */
    private void persistPeerStatuses(PeerStatusCache peerStatusCache) {
        try {
            this.peerStatusCache = peerStatusCache;

            // The #save mechanism persists the cache to stateful or file-based storage
            peerPersistence.save(peerStatusCache);
        } catch (final IOException e) {
            error(logger, eventReporter, "Failed to persist list of peers due to {}; if restarted" +
                    " and the nodes specified at the remote instance are down," +
                    " may be unable to transfer data until communications with those nodes are restored", e.toString());
            logger.error("", e);
        }
    }

    /**
     * Refreshes the list of S2S peers that flowfiles can be sent to or received from. Uses the stateful
     * cache to reduce network overhead.
     */
    private void refreshPeerStatusCache() {
        try {
            // Splitting enumeration and querying into separate methods allows better testing and composition
            final Set<PeerDescription> peersToQuery = getPeersToQuery();
            final Set<PeerStatus> statuses = fetchRemotePeerStatuses(peersToQuery);

            if (statuses.isEmpty()) {
                logger.info("No peers were retrieved from the remote group {}", peersToQuery.stream().map(p -> p.getHostname() + ":" + p.getPort()).collect(Collectors.joining(",")));
            }

            // Persist the fetched peer statuses
            PeerStatusCache peerStatusCache = new PeerStatusCache(statuses, System.currentTimeMillis(), peerStatusProvider.getTransportProtocol());
            persistPeerStatuses(peerStatusCache);
            logger.info("Successfully refreshed peer status cache; remote group consists of {} peers", statuses.size());
        } catch (Exception e) {
            warn(logger, eventReporter, "Unable to refresh remote group peers due to: {}", e.getMessage());
            if (logger.isDebugEnabled() && e.getCause() != null) {
                logger.warn("Caused by: ", e);
            }
        }
    }
}


text:
using System;
using System.IO;
using System.IO.Compression;
using System.Text;

namespace AppPressFramework
{
    internal static class StringCompressor
    {
        internal static string CompressString(string text)
        {
            byte[] buffer = Encoding.UTF8.GetBytes(text);
            var memoryStream = new MemoryStream();
            using (var gZipStream = new GZipStream(memoryStream, CompressionMode.Compress, true))
            {
                gZipStream.Write(buffer, 0, buffer.Length);
            }

            memoryStream.Position = 0;

            var compressedData = new byte[memoryStream.Length];
            memoryStream.Read(compressedData, 0, compressedData.Length);

            var gZipBuffer = new byte[compressedData.Length + 4];
            Buffer.BlockCopy(compressedData, 0, gZipBuffer, 4, compressedData.Length);
            Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, gZipBuffer, 0, 4);
            return Convert.ToBase64String(gZipBuffer);
        }

        internal static string DecompressString(string compressedText)
        {
            byte[] gZipBuffer = Convert.FromBase64String(compressedText);
            using (var memoryStream = new MemoryStream())
            {
                int dataLength = BitConverter.ToInt32(gZipBuffer, 0);
                memoryStream.Write(gZipBuffer, 4, gZipBuffer.Length - 4);

                var buffer = new byte[dataLength];

                memoryStream.Position = 0;
                using (var gZipStream = new GZipStream(memoryStream, CompressionMode.Decompress))
                {
                    gZipStream.Read(buffer, 0, buffer.Length);
                }

                return Encoding.UTF8.GetString(buffer);
            }
        }
    }
}


text:
import baseRange from 'lodash/range';
import baseRangeRight from 'lodash/rangeRight';

export function fill<T>(array: T[], valueFn: (index: number) => any): T[] {
  for (let i = 0; i < array.length; i++) array[i] = valueFn(i);

  return array;
}

export function increaseOfPrevious(array: number[], index: number) {
  array[index] += array[index - 1];
}

/**
 * Move the item at given index to the right
 */
export function moveRight(input, index) {
  input[index + 1] = input[index];
}

/**
 * Creates an array of numbers from start to end, both included.
 */
export function range(from: number, to: number): number[] {
  return baseRange(from, to + 1);
}

/**
 * Creates an array of numbers in descending order from start to end, both included.
 */
export function reverseRange(from: number, to: number = 0): number[] {
  return baseRangeRight(to, from + 1);
}

export interface Node {
  left: Node;
  right: Node;
}

/**
 * Convert a tree to serializable Binary Tree for Jest snapshots
 */
export function toSerializableTree(root: Node, nodeConverter: (node: any) => Node): Node {
  if (!root) return;

  toSerializableTree(root.left, nodeConverter);
  Object.assign(root, nodeConverter(root));
  toSerializableTree(root.right, nodeConverter);

  return root;
}

export function setHead(input: number[], value: number): number[] {
  input[0] = value;
  return input;
}

/**
 * Swap two items in an array
 * @param array Input array, whose elements are swapped
 * @param from From index
 * @param to Destination index
 */
export function swap(input: number[], from: number, to: number): number[] {
  const temp = input[from];
  input[from] = input[to];
  input[to] = temp;

  return input;
}


text:
var should = require('chai').should(),
    activiti = require('../index'),
	fs = require('fs');

describe('engine', function() {

  it('get engine name', function() {
    engine = activiti.engine();
    engine.getNameSync().should.equal('default');
  });

  it('deploy process', function() {
	var repository = activiti.repositoryService();
	var processes = repository.createProcessDefinitionQuerySync().listSync();
	console.log("Count Processes Before Deployment: " + processes.sizeSync());
	processes.sizeSync().should.equal(0);

	var data = fs.readFileSync('./test/processes/UserTaskTest.bpmn','utf-8');
	data.should.be.a('string');

	var deployment = repository.createDeploymentSync().addStringSync("UserTaskTest.bpmn",data).deploySync();

	console.log("Deploying 'UserTaskTest': " + deployment.getIdSync());
	deployment.getIdSync().should.be.above(0);

	var processes = repository.createProcessDefinitionQuerySync().listSync();
	console.log("Count Processes After Deployment: " + processes.sizeSync());
	processes.sizeSync().should.equal(1);

	var processDef = processes.getSync(0);
	processDef.should.not.to.be.null;
	console.log("Process Definition: " + processDef.toString());

	var processDefId = processDef.getIdSync();
	console.log("Process Definition ID: " + processDefId);
	processDefId.should.not.to.be.null;
	processDefId.should.be.a('string');
  });

  it('start process', function() {
	var repository = activiti.repositoryService();
	var runtime = activiti.runtimeService();

	var processes = repository.createProcessDefinitionQuerySync().listSync();
	processes.sizeSync().should.be.above(0);

	var processDef = processes.getSync(0);
	console.log("Process Definition: " + processDef.toString());
	processDef.should.not.to.be.null;

	var processDefId = processDef.getIdSync();
	console.log("Process Definition ID: " + processDefId);
	processDefId.should.not.to.be.null;
	processDefId.should.be.a('string');

	var processInst = runtime.startProcessInstanceByIdSync(processDefId.toString());
	console.log("Start Process Instance: " + processInst.getIdSync());
	processInst.should.not.to.be.null;
	processInst.getIdSync().should.be.a('string');
  });

});