text:
__dir = File.dirname(File.expand_path(__FILE__))
require File.join(__dir, "example_helper")

amq_client_example "Channel-level exception handling" do |client|
  channel = AMQ::Client::Channel.new(client, 1)
  channel.open do
    puts "Channel #{channel.id} is now open"

    show_stopper = Proc.new {
      client.disconnect do
        puts
        puts "AMQP connection is now properly closed"
        EM.stop
      end
    }

    channel.on_error do |ch, close|
      puts "Oops, there is a channel-level exception: #{close.inspect}"

      EM.add_timer(1.2) { show_stopper.call }
    end

    # amq.* names are reserevd so this causes a channel-level exception. MK.
    x = AMQ::Client::Exchange.new(client, channel, "amq.client.examples.extensions.x1", :direct)
    x.declare(false, false, false, true, false)

    EM.add_timer(1) do
      if channel.closed?
        puts "1 second later channel #{channel.id} is closed"
      end
    end

    Signal.trap "INT",  show_stopper
    Signal.trap "TERM", show_stopper

    EM.add_timer(2, show_stopper)
  end
end


text:
from flask.ext.sqlalchemy import SQLAlchemy
from sqlalchemy.ext.declarative import declared_attr

db = SQLAlchemy()
DB_STRING_TYPE = db.Unicode(256)
DB_TEXT_TYPE = db.TEXT(length=1 << 20, convert_unicode=True)

def init_db(app):
    db.init_app(app)
    db.app = app
    db.create_all()

class Base(db.Model):
    __abstract__ = True
    __table_args__ = {'mysql_charset': 'utf8'}

    @declared_attr
    def id(cls):
        return db.Column('id', db.Integer, primary_key=True,
                         autoincrement=True)

redpajama_set_name: RedPajamaGithub


text:
module NetSuite
  module Records
    class Estimate
      include Support::Fields
      include Support::RecordRefs
      include Support::Records
      include Support::Actions
      include Namespaces::TranSales

      actions :get, :get_list, :add, :initialize, :delete, :update, :upsert, :search

      fields :alt_handling_cost, :alt_sales_total, :alt_shipping_cost, :balance,
        :bill_address, :billing_address, :billing_schedule, :bill_is_residential,
        :created_date, :currency_name, :discount_rate, :email, :end_date,
        :est_gross_profit, :exchange_rate, :handling_cost, :handling_tax1_rate, :is_taxable,
        :last_modified_date, :memo, :message, :other_ref_num, :ship_date, :shipping_cost,
        :shipping_tax1_rate, :source, :start_date, :status, :sync_partner_teams, :sync_sales_teams,
        :to_be_emailed, :to_be_faxed, :to_be_printed, :total_cost_estimate, :tran_date, :tran_id,
        :linked_tracking_numbers, :is_multi_ship_to

      field :shipping_address, Address
      field :billing_address, Address

      field :item_list,                   EstimateItemList
      field :custom_field_list,           CustomFieldList

      record_refs :bill_address_list, :created_from, :currency, :custom_form, :department, :discount_item, :entity,
        :handling_tax_code, :job, :klass, :lead_source, :location, :message_sel, :opportunity, :partner,
        :promo_code, :sales_group, :sales_rep, :ship_method, :shipping_tax_code, :subsidiary, :terms

      attr_reader :internal_id
      attr_accessor :external_id
      attr_accessor :search_joins

      def initialize(attributes = {})
        @internal_id = attributes.delete(:internal_id) || attributes.delete(:@internal_id)
        @external_id = attributes.delete(:external_id) || attributes.delete(:@external_id)
        initialize_from_attributes_hash(attributes)
      end
    end
  end
end


text:
package ClusterSchedulingSimulation

import java.io.File

/**
 * Set up workloads based on measurements from a real cluster.
 * In the Eurosys paper, we used measurements from Google clusters here.
 */
object Workloads {
  /**
   * Set up CellStateDescs that will go into WorkloadDescs. Fabricated
   * numbers are provided as an example. Enter numbers based on your
   * own clusters instead.
   */
  val exampleCellStateDesc = new CellStateDesc(numMachines = 10000,
                                          cpusPerMachine = 4,
                                          memPerMachine = 16)

  /**
   * Set up WorkloadDescs, containing generators of workloads and
   * pre-fill workloads based on measurements of cells/workloads.
   */
  val exampleWorkloadGeneratorBatch =
      new ExpExpExpWorkloadGenerator(workloadName = "Batch".intern(),
                                     initAvgJobInterarrivalTime = 10.0,
                                     avgTasksPerJob = 100.0,
                                     avgJobDuration = (100.0),
                                     avgCpusPerTask = 1.0,
                                     avgMemPerTask = 2.0)
  val exampleWorkloadGeneratorService =
      new ExpExpExpWorkloadGenerator(workloadName = "Service".intern(),
                                     initAvgJobInterarrivalTime = 20.0,
                                     avgTasksPerJob = 10.0,
                                     avgJobDuration = (500.0),
                                     avgCpusPerTask = 1.0,
                                     avgMemPerTask = 2.0)
  val exampleWorkloadDesc = WorkloadDesc(cell = "example",
                                      assignmentPolicy = "CMB_PBB",
                                      workloadGenerators =
                                          exampleWorkloadGeneratorBatch ::
                                          exampleWorkloadGeneratorService :: Nil,
                                      cellStateDesc = exampleCellStateDesc)

  // example pre-fill workload generators.
  val examplePrefillTraceFileName = "traces/example-init-cluster-state.log"
  assert((new File(examplePrefillTraceFileName)).exists())
  val exampleBatchPrefillTraceWLGenerator =
      new PrefillPbbTraceWorkloadGenerator("PrefillBatch",
                                           examplePrefillTraceFileName)
  val exampleServicePrefillTraceWLGenerator =
      new PrefillPbbTraceWorkloadGenerator("PrefillService",
                                          examplePrefillTraceFileName)
  val exampleBatchServicePrefillTraceWLGenerator =
      new PrefillPbbTraceWorkloadGenerator("PrefillBatchService",
                                          examplePrefillTraceFileName)

  val exampleWorkloadPrefillDesc =
      WorkloadDesc(cell = "example",
                   assignmentPolicy = "CMB_PBB",
                   workloadGenerators =
                       exampleWorkloadGeneratorBatch ::
                       exampleWorkloadGeneratorService ::
                       Nil,
                   cellStateDesc = exampleCellStateDesc,
                   prefillWorkloadGenerators =
                       List(exampleBatchServicePrefillTraceWLGenerator))

  // Set up example workload with jobs that have interarrival times
  // from trace-based interarrival times.
  val exampleInterarrivalTraceFileName = "traces/job-distribution-traces/" +
      "example_interarrival_cmb.log"
  val exampleNumTasksTraceFileName = "traces/job-distribution-traces/" +
      "example_csizes_cmb.log"
  val exampleJobDurationTraceFileName = "traces/job-distribution-traces/" +
      "example_runtimes_cmb.log"
  assert((new File(exampleInterarrivalTraceFileName)).exists())
  assert((new File(exampleNumTasksTraceFileName)).exists())
  assert((new File(exampleJobDurationTraceFileName)).exists())

  // A workload based on traces of interarrival times, tasks-per-job,
  // and job duration. Task shapes now based on pre-fill traces.
  val exampleWorkloadGeneratorTraceAllBatch =
      new TraceAllWLGenerator(
          "Batch".intern(),
          exampleInterarrivalTraceFileName,
          exampleNumTasksTraceFileName,
          exampleJobDurationTraceFileName,
          examplePrefillTraceFileName,
          maxCpusPerTask = 3.9, // Machines in example cluster have 4 CPUs.
          maxMemPerTask = 15.9) // Machines in example cluster have 16GB mem.

  val exampleWorkloadGeneratorTraceAllService =
      new TraceAllWLGenerator(
          "Service".intern(),
          exampleInterarrivalTraceFileName,
          exampleNumTasksTraceFileName,
          exampleJobDurationTraceFileName,
          examplePrefillTraceFileName,
          maxCpusPerTask = 3.9,
          maxMemPerTask = 15.9)

  val exampleTraceAllWorkloadPrefillDesc =
      WorkloadDesc(cell = "example",
                   assignmentPolicy = "CMB_PBB",
                   workloadGenerators =
                       exampleWorkloadGeneratorTraceAllBatch ::
                       exampleWorkloadGeneratorTraceAllService ::
                       Nil,
                   cellStateDesc = exampleCellStateDesc,
                   prefillWorkloadGenerators =
                      List(exampleBatchServicePrefillTraceWLGenerator))
}


text:
package com.saucelabs.appium.page_object.widgets.combined.simple;

import com.saucelabs.appium.page_object.widgets.Movie;
import com.saucelabs.appium.page_object.widgets.Movies;
import io.appium.java_client.pagefactory.AndroidFindBy;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;

import java.util.List;

public class CombinedMovies extends Movies {

    @AndroidFindBy(className = "android.widget.RelativeLayout")
    @FindBy(className = "mb-movie")
    List<CombinedMovie> movieList;

    /*
    There could be additional behavior.
    But for test it is enough.
     */

    protected CombinedMovies(WebElement element) {
        super(element);
    }

    @Override
    public int getMovieCount() {
        return movieList.size();
    }

    @Override
    public Movie getMovie(int index) {
        return movieList.get(index);
    }
}


text:
'use strict';

// MODULES //

var partial = require( './partial.js' );

// QUANTILE //

/**
* FUNCTION: quantile( out, arr, x0, gamma )
*	Evaluates the quantile function for a Cauchy distribution with location parameter `x0` and scale parameter `gamma` for each array element.
*
* @param {Array|Int8Array|Uint8Array|Uint8ClampedArray|Int16Array|Uint16Array|Int32Array|Uint32Array|Float32Array|Float64Array} out - output array
* @param {Int8Array|Uint8Array|Uint8ClampedArray|Int16Array|Uint16Array|Int32Array|Uint32Array|Float32Array|Float64Array} arr - input array
* @param {Number} x0 - location parameter
* @param {Number} gamma - scale parameter
* @returns {Number[]|Int8Array|Uint8Array|Uint8ClampedArray|Int16Array|Uint16Array|Int32Array|Uint32Array|Float32Array|Float64Array} output array
*/
function quantile( y, x, x0, gamma ) {
	var len = x.length,
		fcn,
		i;

	fcn = partial ( x0, gamma );
	for ( i = 0; i < len; i++ ) {
		y[ i ] = fcn( x[ i ] );
	}
	return y;
} // end FUNCTION quantile()

// EXPORTS //

module.exports = quantile;


text:
package cashier.resource;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;

public class UserTest {

  public UserTest() {
  }

  @BeforeClass
  public static void setUpClass() throws Exception {
  }

  @AfterClass
  public static void tearDownClass() throws Exception {
  }

  @Before
  public void setUp() {
  }

  @After
  public void tearDown() {
  }

  @Test
  public void testSomeMethod() {
    // TODO review the generated test code and remove the default call to fail.
    fail("The test case is a prototype.");
  }
}


text:
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CWinACPIDoc

IMPLEMENT_DYNCREATE(CWinACPIDoc, CDocument)

BEGIN_MESSAGE_MAP(CWinACPIDoc, CDocument)
	//{{AFX_MSG_MAP(CWinACPIDoc)
		// NOTE - the ClassWizard will add and remove mapping macros here.
		//    DO NOT EDIT what you see in these blocks of generated code!
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CWinACPIDoc construction/destruction

CWinACPIDoc::CWinACPIDoc()
{
	// TODO: add one-time construction code here

}

CWinACPIDoc::~CWinACPIDoc()
{
}

BOOL CWinACPIDoc::OnNewDocument()
{
	if (!CDocument::OnNewDocument())
		return FALSE;

	// TODO: add reinitialization code here
	// (SDI documents will reuse this document)

	return TRUE;
}

/////////////////////////////////////////////////////////////////////////////
// CWinACPIDoc serialization

void CWinACPIDoc::Serialize(CArchive& ar)
{
	if (ar.IsStoring())
	{
		// TODO: add storing code here
	}
	else
	{
		// TODO: add loading code here
	}
}

/////////////////////////////////////////////////////////////////////////////
// CWinACPIDoc diagnostics

#ifdef _DEBUG
void CWinACPIDoc::AssertValid() const
{
	CDocument::AssertValid();
}

void CWinACPIDoc::Dump(CDumpContext& dc) const
{
	CDocument::Dump(dc);
}
#endif //_DEBUG

/////////////////////////////////////////////////////////////////////////////
// CWinACPIDoc commands


text:
package captcha

import (
	"bytes"
	"net/http"
	"path"
	"strings"
	"time"
)

type captchaHandler struct {
	imgWidth  int
	imgHeight int
}

// Server returns a handler that serves HTTP requests with image or
// audio representations of captchas. Image dimensions are accepted as
// arguments. The server decides which captcha to serve based on the last URL
// path component: file name part must contain a captcha id, file extension —
// its format (PNG or WAV).
//
// For example, for file name "LBm5vMjHDtdUfaWYXiQX.png" it serves an image captcha
// with id "LBm5vMjHDtdUfaWYXiQX", and for "LBm5vMjHDtdUfaWYXiQX.wav" it serves the
// same captcha in audio format.
//
// To serve a captcha as a downloadable file, the URL must be constructed in
// such a way as if the file to serve is in the "download" subdirectory:
// "/download/LBm5vMjHDtdUfaWYXiQX.wav".
//
// To reload captcha (get a different solution for the same captcha id), append
// "?reload=x" to URL, where x may be anything (for example, current time or a
// random number to make browsers refetch an image instead of loading it from
// cache).
//
// By default, the Server serves audio in English language. To serve audio
// captcha in one of the other supported languages, append "lang" value, for
// example, "?lang=ru".
func Server(imgWidth, imgHeight int) http.Handler {
	return &captchaHandler{imgWidth, imgHeight}
}

func (h *captchaHandler) serve(w http.ResponseWriter, r *http.Request, id, ext, lang string, download bool) error {
	w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
	w.Header().Set("Pragma", "no-cache")
	w.Header().Set("Expires", "0")

	var content bytes.Buffer
	switch ext {
	case ".png":
		w.Header().Set("Content-Type", "image/png")
		WriteImage(&content, id, h.imgWidth, h.imgHeight)
	case ".wav":
		w.Header().Set("Content-Type", "audio/x-wav")
		WriteAudio(&content, id, lang)
	default:
		return ErrNotFound
	}

	if download {
		w.Header().Set("Content-Type", "application/octet-stream")
	}
	http.ServeContent(w, r, id+ext, time.Time{}, bytes.NewReader(content.Bytes()))
	return nil
}

func (h *captchaHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	dir, file := path.Split(r.URL.Path)
	ext := path.Ext(file)
	id := file[:len(file)-len(ext)]
	if ext == "" || id == "" {
		http.NotFound(w, r)
		return
	}
	if r.FormValue("reload") != "" {

		Reload(id)
	}
	lang := strings.ToLower(r.FormValue("lang"))
	download := path.Base(dir) == "download"

	if h.serve(w, r, id, ext, lang, download) == ErrNotFound {
		http.NotFound(w, r)
	}
	// Ignore other errors.
}


text:
var Code = require('code');
var Hawk = require('../lib');
var Lab = require('lab');
var Package = require('../package.json');

// Declare internals

var internals = {};

// Test shortcuts

var lab = exports.lab = Lab.script();
var describe = lab.experiment;
var it = lab.test;
var expect = Code.expect;

describe('Hawk', function () {

    describe('Utils', function () {

        describe('#parseHost', function () {

            it('returns port 80 for non tls node request', function (done) {

                var req = {
                    method: 'POST',
                    url: '/resource/4?filter=a',
                    headers: {
                        host: 'example.com',
                        'content-type': 'text/plain;x=y'
                    }
                };

                expect(Hawk.utils.parseHost(req, 'Host').port).to.equal(80);
                done();
            });

            it('returns port 443 for non tls node request', function (done) {

                var req = {
                    method: 'POST',
                    url: '/resource/4?filter=a',
                    headers: {
                        host: 'example.com',
                        'content-type': 'text/plain;x=y'
                    },
                    connection: {
                        encrypted: true
                    }
                };

                expect(Hawk.utils.parseHost(req, 'Host').port).to.equal(443);
                done();
            });

            it('returns port 443 for non tls node request (IPv6)', function (done) {

                var req = {
                    method: 'POST',
                    url: '/resource/4?filter=a',
                    headers: {
                        host: '[123:123:123]',
                        'content-type': 'text/plain;x=y'
                    },
                    connection: {
                        encrypted: true
                    }
                };

                expect(Hawk.utils.parseHost(req, 'Host').port).to.equal(443);
                done();
            });

            it('parses IPv6 headers', function (done) {

                var req = {
                    method: 'POST',
                    url: '/resource/4?filter=a',
                    headers: {
                        host: '[123:123:123]:8000',
                        'content-type': 'text/plain;x=y'
                    },
                    connection: {
                        encrypted: true
                    }
                };

                var host = Hawk.utils.parseHost(req, 'Host');
                expect(host.port).to.equal('8000');
                expect(host.name).to.equal('[123:123:123]');
                done();
            });
        });

        describe('#version', function () {

            it('returns the correct package version number', function (done) {

                expect(Hawk.utils.version()).to.equal(Package.version);
                done();
            });
        });

        describe('#unauthorized', function () {

            it('returns a hawk 401', function (done) {

                expect(Hawk.utils.unauthorized('kaboom').output.headers['WWW-Authenticate']).to.equal('Hawk error="kaboom"');
                done();
            });
        });
    });
});


text:
from ruamel.yaml import YAML

from paradrop.core.auth.user import User
from paradrop.core.chute.chute import Chute
from paradrop.core.chute.service import Service

yaml = YAML(typ='safe')

yaml.default_flow_style = False

yaml.register_class(User)
yaml.register_class(Chute)
yaml.register_class(Service)


text:
<html>
<head>
<script>
function handleLoad() {
  console.log("Console message (C) %d with element", 2010, document.documentElement);

  setTimeout(function() {
    // Note that localhost is different from the 127.0.0.1 that tests are runnung against. So this navigation
    // is in fact cross-domain.
    document.location = "http://localhost:8000/inspector-enabled/resources/console-log-frame-after-navigation.html";
  }, 0);
}
</script>
</head>
<body onload="handleLoad()">
</body>
</html>


text:
<script>
$(function() {
    var TOC = $("ul.toc");

    $(".toc-expander").click(function() {
        if (TOC.hasClass('open')) {
            TOC.removeClass('open');
        } else {
            TOC.addClass('open');
        }
    })

    var fixed = false;
    $(window).on("scroll", function(e) {
        if ($(window).scrollTop() > 140) {
            if (!fixed) {
                TOC.addClass("fixed-toc");
                TOC.width(TOC.parent().width());
                fixed = true;
            }
        } else {
            if (fixed) {
                TOC.removeClass("fixed-toc");
                TOC.width(TOC.parent().width());
                fixed = false;
            }
        }

    });

    var positions = [];
    var windowHeight;
    var currentItem;

    function resizeWindow() {
        TOC.width(TOC.parent().width());
        calculatePositions();
        windowHeight = $(window).height();
    }
    function calculatePositions() {
        positions = [];
        $(".docs-content h3,.docs-content h4").each(function() {
            positions.push({
                el: $("#toc-item-"+$(this).attr('id')),
                pos: $(this).position().top+$(this).height()+parseInt($(this).css("marginTop"))
            });
        });
    }

    function getCurrentItem() {
        var top = $(window).scrollTop();
        var previous = positions[0].el;
        for (var i=0;i<positions.length;i++) {
            if (positions[i].pos > top) {
                if (positions[i].pos-top < windowHeight/2 ) {
                    return positions[i].el;
                } else {
                    return previous;
                }
            }
            previous = positions[i].el;
        }
    }
    function scrollWindow() {
        var targetItem = getCurrentItem();
        if (targetItem !== currentItem) {
            if (currentItem) {
                currentItem.removeClass("active");
            }
            currentItem = targetItem;
            currentItem.addClass("active");
        }
    }
    $(window).resize(resizeWindow);
    $(window).on("scroll",scrollWindow);

    resizeWindow();
    scrollWindow();

});
</script>


text:
Jytkytin2015
=======

Code run on Jytkytys.fi

A lot of the code from ng-drum (https://github.com/RoryDH/ng-drum).


text:
/* Licensed under BSD 3-Clause - see LICENSE.txt or git.io/sfdc-license */

/* eslint-disable import/no-mutable-exports */

// This function will deliver an error message to the browser console about the removal of a property.
import warning from 'warning';

import {
	BUTTON,
	BUTTON_STATEFUL,
	BUTTON_GROUP,
	CHECKBOX,
	DATE_PICKER,
	INPUT,
	LOOKUP,
	MENU_DROPDOWN,
	TIME_PICKER,
} from '../../utilities/constants';

/* eslint-disable import/no-mutable-exports */

let isTriggerTabbable = function isTriggerTabbableFunction() {};

if (process.env.NODE_ENV !== 'production') {
	const hasWarned = {};

	isTriggerTabbable = function isTriggerTabbableFunction(
		COMPONENT,
		trigger,
		comment,
		silenceTriggerTabbableWarning
	) {
		const additionalComment = comment ? ` ${comment}` : '';
		const childTabIndex = trigger.props.tabIndex;
		let elementIsTabbable = true;

		if (
			// Silencing prop for special cases
			!silenceTriggerTabbableWarning &&
			// List of "native" HTML elements that are tabbable by default
			trigger.type !== 'button' &&
			trigger.type !== 'input' &&
			trigger.type !== 'select' &&
			trigger.type !== 'textarea' &&
			trigger.type !== 'a' &&
			// List of components that are tabbable by default
			trigger.type.displayName !== BUTTON &&
			trigger.type.displayName !== BUTTON_STATEFUL &&
			trigger.type.displayName !== BUTTON_GROUP &&
			trigger.type.displayName !== CHECKBOX &&
			trigger.type.displayName !== DATE_PICKER &&
			trigger.type.displayName !== INPUT &&
			trigger.type.displayName !== LOOKUP &&
			trigger.type.displayName !== MENU_DROPDOWN &&
			trigger.type.displayName !== TIME_PICKER
		) {
			// if it's not one of the above, then check to see if it has a tabIndex
			if (childTabIndex === '-1' || childTabIndex === undefined) {
				elementIsTabbable = false;
				if (!hasWarned[COMPONENT]) {
					/* eslint-disable max-len */
					warning(
						elementIsTabbable,
						`[Design System React] The element that triggers ${COMPONENT} must be tabbable for keyboard users. Elements such as anchor, button, input or a DOM element with tabIndex="0" specified are tabbable. ${additionalComment}`
					);
					/* eslint-enable max-len */
					hasWarned[COMPONENT] = !!elementIsTabbable;
				}
			}
		}
	};
}

export default isTriggerTabbable;


text:
<?php
namespace Kir\CanonicalAddresses\Common;

class Culture {
	/** @var string */
	private $languageCode;
	/** @var string */
	private $countryCode;
	/** @var array */
	private $defaultLanguageCodeForCountryCode = array(
		'DE' => 'de',
	);

	/**
	 * @param string $languageCode
	 * @param string $countryCode
	 */
	public function __construct($countryCode, $languageCode = null) {
		$this->countryCode = $countryCode;
		if($languageCode === null && array_key_exists($languageCode, $this->defaultLanguageCodeForCountryCode)) {
			$languageCode = $this->defaultLanguageCodeForCountryCode[$languageCode];
		}
		$this->languageCode = $languageCode;
	}

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

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

	/**
	 * @return string
	 */
	function __toString() {
		return sprintf('%s_%s', $this->languageCode, $this->countryCode);
	}
}


text:
import angular from 'angular';
import uiRouter from 'angular-ui-router';
import volunteerFormComponent from './volunteerForm.component';

let volunteerFormModule = angular.module('volunteerForm', [
  uiRouter
])

.config(['$stateProvider', ($stateProvider) => {
  $stateProvider
    .state('volunteerApplication', {
      url: '/apply',
      template: '<volunteer-form></volunteer-form>'
    });
}])

.component('volunteerForm', volunteerFormComponent);

export default volunteerFormModule;


text:
#include "../stdafx.h"

#include "ReferencedCalculation.h"

using std::string;
using namespace aim_lib;

ReferencedCalculation::ReferencedCalculation(){

}

ReferencedCalculation::ReferencedCalculation(const ReferencedCalculation& referencedCalculation){
	*this = referencedCalculation;
}

ReferencedCalculation& ReferencedCalculation::operator=(const ReferencedCalculation& referencedCalculation){
	if (this != &referencedCalculation)
	{
		_cagridId			= referencedCalculation._cagridId;
		_uniqueIdentifier	= referencedCalculation._uniqueIdentifier;
	}

	return *this;
}

ReferencedCalculation::~ReferencedCalculation(){

}

const string& ReferencedCalculation::GetUniqueIdentifier() const{

	return _uniqueIdentifier;
}

void ReferencedCalculation::SetUniqueIdentifier(const string& newVal){

	_uniqueIdentifier = newVal;
}


text:
Template['setupCubs'].helpers({
});

Template['setupCubs'].events({
});


text:
<?php

namespace Magento\DesignEditor\Model\Editor\Tools\QuickStyles\Renderer;

/**
 * Background image renderer
 */
class BackgroundImage extends \Magento\DesignEditor\Model\Editor\Tools\QuickStyles\Renderer\AbstractRenderer
{
    /**
     * Render color picker attribute
     *
     * Return format:
     * .content { background-image: url(path/image.png); }
     *
     * @param array $data
     * @return string
     */
    protected function _render($data)
    {
        $override = "none";

        if (!empty($data['value'])) {
            $override = "url('{$data['value']}')";
        }

        return "{$data['selector']} { {$data['attribute']}: " . $override . "; }";
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<server description="OpenLiberty Server">

    <featureManager>
        <feature>javaee-8.0</feature>
        <feature>microProfile-2.1</feature>
        <feature>usr:opentracingZipkin-0.31</feature>
    </featureManager>

    <httpEndpoint id="defaultHttpEndpoint" host="*" httpPort="9080" httpsPort="9443"/>

    <keyStore id="defaultKeyStore" password="Liberty"/>

    <applicationManager autoExpand="true"/>

    <opentracingZipkin />
</server>


text:
package main

import (
	"bytes"
	"crypto/aes"
	"crypto/cipher"
	"encoding/base64"
	"errors"
	"github.com/smtc/glog"
	"fmt"
)

func main() {
	aesMob,err:=AesEncrypt("gloomysw_sw")
	if err != nil {
		fmt.Printf("aes err! err: %s \n",err.Error())
		return
	}
	fmt.Println(aesMob)
	enMob:="FrUW5i7w3CeMkqePA3OMIw=="
	mob,err:=AesDecrypt(enMob)
	if err != nil {
		fmt.Printf("unAes err! err: %s \n",err.Error())
		return
	}
	fmt.Println(mob)
}

var AESKEY = []byte("sfe023f_9fd&fwfl")

/**
字符串加密
创建人:邵炜
创建时间:2016年3月18日09:50:36
输入参数: 需要加密的字符串
输出参数: 加密后字符串 错误对象
*/
func AesEncrypt(origData string) (string, error) {
	origDataByte := []byte(origData)
	block, err := aes.NewCipher([]byte(AESKEY))
	if err != nil {
		glog.Error("aes newcipher is error, err: %s \n", err.Error())
		return "", err
	}
	blockSize := block.BlockSize()
	origDataByte = PKCS5Padding(origDataByte, blockSize)
	blockMode := cipher.NewCBCEncrypter(block, AESKEY[:blockSize])
	crypted := make([]byte, len(origDataByte))
	blockMode.CryptBlocks(crypted, origDataByte)
	return base64.StdEncoding.EncodeToString(crypted), nil
}

/**
字符串解密
创建人:邵炜
创建时间:2016年3月18日09:56:20
输入参数: 需要解密的字符串  解密后字符串长度
输出参数: 解密后字符串  错误对象
*/
func AesDecrypt(crypted string) (string, error) {
	cryptedByte, _ := base64.StdEncoding.DecodeString(crypted)
	block, err := aes.NewCipher(AESKEY)
	if err != nil {
		glog.Error("aes newcipher is error, err: %s \n", err.Error())
		return "", err
	}
	blockSize := block.BlockSize()

	if len(cryptedByte)%blockSize != 0 {
		glog.Error("crypto/cipher: input not full blocks , crypted: %s  \n", crypted)
		return "", errors.New("crypto/cipher: input not full blocks")
	}

	blockMode := cipher.NewCBCDecrypter(block, AESKEY[:blockSize])
	origData := make([]byte, len(cryptedByte))
	blockMode.CryptBlocks(origData, cryptedByte)
	origData = PKCS5UnPadding(origData)

	return string(origData), nil
}

func PKCS5Padding(ciphertext []byte, blockSize int) []byte {
	padding := blockSize - len(ciphertext)%blockSize
	padtext := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(ciphertext, padtext...)
}

func PKCS5UnPadding(origData []byte) []byte {
	length := len(origData)
	unpadding := int(origData[length-1])
	return origData[:(length - unpadding)]
}


text:
<?php
/*
* @version 0.2 (auto-set)
*/
 chdir('../');

 include_once("./config.php");
 include_once("./lib/loader.php");

 $db=new mysql(DB_HOST, '', DB_USER, DB_PASSWORD, DB_NAME); // connecting to database
 include_once("./load_settings.php");

 // OPTIMIZATION RULES

 $rules=array(
  'tempSensors.temp'=>array('optimize'=>'avg'),
  'humSensors.humidity'=>array('optimize'=>'avg'),
  'lumSensors.value'=>array('optimize'=>'avg'),
  'humiditySensors.humidity'=>array('optimize'=>'avg'),
  'uptime'=>array('keep'=>30, 'optimize'=>'max'),
  'PowerMeters.power'=>array('optimize'=>'avg'),
  'PowerMeters.electric'=>array('optimize'=>'avg'),
  'Relays.status'=>array('keep'=>0),
  'inhouseMovementSensors.status'=>array('keep'=>30),
  'WeatherStations.tempOutside'=>array('optimize'=>'avg'),
  'WeatherStations.updatedTime'=>array('keep'=>0),
  'WeatherStations.pressureRt'=>array('optimize'=>'avg'),
  'WeatherStations.pressure'=>array('optimize'=>'avg')
 );

 set_time_limit(6000);

 DebMes("Optimize history script started");

 //STEP 1 -- calculate stats
 echo "Calculating stats:
";
 $pvalues=SQLSelect("SELECT pvalues.ID, properties.TITLE as PTITLE, classes.TITLE as CTITLE, objects.TITLE as OTITLE FROM pvalues LEFT JOIN objects ON pvalues.OBJECT_ID=objects.ID LEFT JOIN classes ON objects.CLASS_ID=classes.ID LEFT JOIN properties ON pvalues.PROPERTY_ID=properties.ID HAVING PTITLE!=''");
 $total=count($pvalues);
 for($i=0;$i<$total;$i++) {
  $tmp=SQLSelectOne("SELECT COUNT(*) as TOTAL FROM phistory WHERE VALUE_ID='".$pvalues[$i]['ID']."'");
  if ($tmp['TOTAL']) {
   echo $pvalues[$i]['CTITLE'].".".$pvalues[$i]['PTITLE']." (object: ".$pvalues[$i]['OTITLE']."): ";
   $grand_total+=$tmp['TOTAL'];
   if ($tmp['TOTAL']>5000) {
    echo "";
   }
   echo $tmp['TOTAL']."";
   echo "
";

   echo str_repeat(' ', 1024);
   flush();
   flush();

  }
 }
 echo "
Grand-total: ".$grand_total."

";

   echo str_repeat(' ', 1024);
   flush();
   flush();

//   exit;
 if (!$rules) {
  echo "No rules defined.";
  exit;
 }

 //STEP 2 -- optimize values in time
 $values=SQLSelect("SELECT DISTINCT(VALUE_ID) FROM phistory");
 //print_r($values);
 $total=count($values);
 for($i=0;$i<$total;$i++) {
  $value_id=$values[$i]['VALUE_ID'];
  $pvalue=SQLSelectOne("SELECT pvalues.ID, properties.TITLE as PTITLE, objects.TITLE as OTITLE, classes.TITLE as CTITLE FROM pvalues LEFT JOIN objects ON pvalues.OBJECT_ID=objects.ID LEFT JOIN properties ON pvalues.PROPERTY_ID=properties.ID LEFT JOIN classes ON classes.ID=properties.CLASS_ID WHERE pvalues.ID='".$value_id."'");
  //print_r($pvalue);
  if ($pvalue['CTITLE']!='') {
   $key=$pvalue['CTITLE'].'.'.$pvalue['PTITLE'];
   $rule='';
   if ($rules[$key]) {
    $rule=$rules[$key];
   } elseif ($rules[$pvalue['OTITLE'].'.'.$pvalue['PTITLE']]) {
    $rule=$rules[$pvalue['OTITLE'].'.'.$pvalue['PTITLE']];
   } elseif ($rules[$pvalue['PTITLE']]) {
    $rule=$rules[$pvalue['PTITLE']];
   }
   if ($rule) {
    //processing
    echo "
".$pvalue['OTITLE']." (".$key.")
";
    $total_before=current(SQLSelectOne("SELECT COUNT(*) as TOTAL FROM phistory WHERE VALUE_ID='".$value_id."'"));
    if (isset($rule['keep'])) {
     echo " removing old (".(int)$rule['keep'].")";
     SQLExec("DELETE FROM phistory WHERE VALUE_ID='".$value_id."' AND TO_DAYS(NOW())-TO_DAYS(ADDED)>=".(int)$rule['keep']);
    }
    if ($rule['optimize']) {

   echo str_repeat(' ', 1024);
   flush();
   flush();

     echo "
Before last MONTH
";
     $end=time()-30*24*60*60; // month end older
     $start=current(SQLSelectOne("SELECT UNIX_TIMESTAMP(ADDED) FROM phistory WHERE VALUE_ID='".$value_id."' ORDER BY ADDED LIMIT 1"));
     $interval=2*60*60; // two-hours interval
     optimizeHistoryData($value_id, $rule['optimize'], $interval, $start, $end);

   echo str_repeat(' ', 1024);
   flush();
   flush();

     echo "
Before last WEEK
";
     $start=$end+1;
     $end=time()-7*24*60*60; // week and older
     $interval=1*60*60; // one-hour interval
     optimizeHistoryData($value_id, $rule['optimize'], $interval, $start, $end);

   echo str_repeat(' ', 1024);
   flush();
   flush();

     echo "
Before YESTERDAY
";
     $start=$end+1;
     $end=time()-1*24*60*60; // day and older
     $interval=20*60; // 20 minutes interval
     optimizeHistoryData($value_id, $rule['optimize'], $interval, $start, $end);

   echo str_repeat(' ', 1024);
   flush();
   flush();

     echo "
Before last HOUR
";
     $start=$end+1;
     $end=time()-1*60*60; // 1 hour and older
     $interval=3*60; // 3 minutes interval
     optimizeHistoryData($value_id, $rule['optimize'], $interval, $start, $end);

    }

    $total_after=current(SQLSelectOne("SELECT COUNT(*) as TOTAL FROM phistory WHERE VALUE_ID='".$value_id."'"));
    echo " (changed ".$total_before." -> ".$total_after.")
";
   }
  }
 }

 SQLExec("OPTIMIZE TABLE phistory;");

 echo "
DONE!!!
";

 $db->Disconnect(); // closing database connection

 DebMes("Optimize history script finished");

/**
* Title
*
* Description
*
* @access public
*/
 function optimizeHistoryData($value_id, $type, $interval, $start, $end) {

   $total_removed=0;
   if (!$interval) {
    return 0;
   }
   echo "Value ID: $value_id
";
   echo "Interval from ".date('Y-m-d H:i:s', $start)." to ".date('Y-m-d H:i:s', $end)." (every ".$interval." seconds)
";
   $total_values=(int)current(SQLSelectOne("SELECT COUNT(*) FROM phistory WHERE VALUE_ID='".$value_id."' AND ADDED>='".date('Y-m-d H:i:s', $start)."' AND ADDED<='".date('Y-m-d H:i:s', $end)."' "));
   echo "Total values: ".$total_values."
";
   if ($total_values<2) {
    return 0;
   }

   $tmp=$end-$start;
   $tmp2=round($tmp/$interval);
   if ($total_values<=$tmp2) {
    echo "... number of values ($total_values) is less than optimal (".$tmp2.") (skipping)
";
    return 0;
   }

   echo "Optimizing (should be about ".$tmp2." records)...";

   echo str_repeat(' ', 1024);
   flush();
   flush();

   $first_start=current(SQLSelectOne("SELECT UNIX_TIMESTAMP(ADDED) FROM phistory WHERE VALUE_ID='".$value_id."' AND ADDED>='".date('Y-m-d H:i:s', $start)."' ORDER BY ADDED LIMIT 1"));
   $last_start=current(SQLSelectOne("SELECT UNIX_TIMESTAMP(ADDED) FROM phistory WHERE VALUE_ID='".$value_id."' AND ADDED<='".date('Y-m-d H:i:s', $end)."' ORDER BY ADDED DESC LIMIT 1"));

   while($start<$end) {

    if ($start<($first_start-$interval)) {
     $start+=$interval;
     continue;
    }

   if ($start>($last_start+$interval)) {
     $start+=$interval;
     continue;
    }

    //echo date('Y-m-d H:i:s', $start)."
\n";
   echo ".";
   echo str_repeat(' ', 1024);
   flush();
   flush();

    $data=SQLSelect("SELECT * FROM phistory WHERE VALUE_ID='".$value_id."' AND ADDED>='".date('Y-m-d H:i:s', $start)."' AND ADDED<'".date('Y-m-d H:i:s', $start+$interval)."'");
    $total=count($data);
    if ($total>1) {
     $values=array();
     for($i=0;$i<$total;$i++) {
      $values[]=$data[$i]['VALUE'];
     }
     if ($type=='max') {
      $new_value=max($values);
     } elseif ($type=='sum') {
      $new_value=array_sum($values);
     } else {
      $new_value=array_sum($values)/$total;
     }
     SQLExec("DELETE FROM phistory WHERE VALUE_ID='".$value_id."' AND ADDED>='".date('Y-m-d H:i:s', $start)."' AND ADDED<'".date('Y-m-d H:i:s', $start+$interval)."'");
     $rec=array();
     $rec['VALUE_ID']=$value_id;
     $rec['VALUE']=$new_value;
     if ($type=='avg') {
      $rec['ADDED']=date('Y-m-d H:i:s', $start+(int)($interval/2));
     } else {
      $rec['ADDED']=date('Y-m-d H:i:s', $start+$interval-1);
     }
     SQLInsert('phistory', $rec);
     $total_removed+=$total;
     //echo "DONE ($total deleted)
";
     //print_r($rec);
     //exit;
    } else {
     //echo "skip mini interval ($total)
";
    }

    $start+=$interval;
   }

   echo "Done (removed: $total_removed)
";
   SQLExec("OPTIMIZE TABLE `phistory`");

   return $total_removed;

 }

?>


text:
var ExistenceFilter = /** @class */ (function () {
    // TODO(b/33078163): just use simplest form of existence filter for now
    function ExistenceFilter(count) {
        this.count = count;
    }
    ExistenceFilter.prototype.equals = function (other) {
        return other && other.count === this.count;
    };
    return ExistenceFilter;
}());
export { ExistenceFilter };

//# sourceMappingURL=existence_filter.js.map


text:
var assert = require('assert');

for (var k in assert) global[k] = assert[k];

var classic = require('../src');

// Using function invoked with the prototype as 'this'
var Person = classic(function() {
  this.constructor = function(firstname, lastname) {
    this.firstname = firstname;
    this.lastname = lastname;
  };

  this.name = function() {
    return this.firstname + ' ' + this.lastname;
  };
});

// Passing the prototype directly
var Actor = classic({
  constructor: function(firstname, lastname, movieCount) {
    Person.apply(this, arguments);
    this.movieCount = movieCount;
  },

  name: function() {
    return Person.prototype.name.call(this) + ', acted in ' +
      this.movieCount + ' movies';
  }
}, Person);

// Omit constructor
var Director = Actor.extend(function() {
  this.name = function() {
    return Person.prototype.name.call(this) + ', directed ' +
      this.movieCount + ' movies';
  };
});

runMocha({
  'Suite': {
    'passing function': function() {
      var p = new Person('john', 'doe');
      equal(p.name(), 'john doe');
      ok(p instanceof Person);
    },

    'passing prototype': function() {
      var a = new Actor('john', 'travolta', 42);
      equal(a.name(), 'john travolta, acted in 42 movies');
      ok(a instanceof Person);
      ok(a instanceof Actor);
    },

    'passing function inheriting constructor': function() {
      var d = new Director('quentin', 'tarantino', 42);
      equal(d.name(), 'quentin tarantino, directed 42 movies');
      ok(d instanceof Person);
      ok(d instanceof Actor);
      ok(d instanceof Director);
    }
  }
});


text:
package org.apache.activemq.artemis.tests.unit.core.server.impl.fakes;

import javax.transaction.xa.Xid;
import java.util.List;
import java.util.Map;

import org.apache.activemq.artemis.api.core.Pair;
import org.apache.activemq.artemis.api.core.SimpleString;
import org.apache.activemq.artemis.core.journal.Journal;
import org.apache.activemq.artemis.core.persistence.AddressBindingInfo;
import org.apache.activemq.artemis.core.persistence.GroupingInfo;
import org.apache.activemq.artemis.core.persistence.QueueBindingInfo;
import org.apache.activemq.artemis.core.persistence.impl.PageCountPending;
import org.apache.activemq.artemis.core.persistence.impl.journal.AddMessageRecord;
import org.apache.activemq.artemis.core.server.MessageReference;
import org.apache.activemq.artemis.core.server.ServerMessage;
import org.apache.activemq.artemis.core.server.impl.JournalLoader;
import org.apache.activemq.artemis.core.transaction.ResourceManager;
import org.apache.activemq.artemis.core.transaction.Transaction;

public class FakeJournalLoader implements JournalLoader {

   @Override
   public void handleNoMessageReferences(Map<Long, ServerMessage> messages) {
   }

   @Override
   public void handleAddMessage(Map<Long, Map<Long, AddMessageRecord>> queueMap) throws Exception {
   }

   @Override
   public void initQueues(Map<Long, QueueBindingInfo> queueBindingInfosMap,
                          List<QueueBindingInfo> queueBindingInfos) throws Exception {
   }

   @Override
   public void initAddresses(Map<Long, AddressBindingInfo> addressBindingInfosMap,
                             List<AddressBindingInfo> addressBindingInfo) throws Exception {
   }

   @Override
   public void handleGroupingBindings(List<GroupingInfo> groupingInfos) {
   }

   @Override
   public void handleDuplicateIds(Map<SimpleString, List<Pair<byte[], Long>>> duplicateIDMap) throws Exception {
   }

   @Override
   public void postLoad(Journal messageJournal,
                        ResourceManager resourceManager,
                        Map<SimpleString, List<Pair<byte[], Long>>> duplicateIDMap) {
   }

   @Override
   public void handlePreparedSendMessage(ServerMessage message, Transaction tx, long queueID) {
   }

   @Override
   public void handlePreparedAcknowledge(long messageID, List<MessageReference> referencesToAck, long queueID) {
   }

   @Override
   public void handlePreparedTransaction(Transaction tx,
                                         List<MessageReference> referencesToAck,
                                         Xid xid,
                                         ResourceManager resourceManager) {
   }

   @Override
   public void recoverPendingPageCounters(List<PageCountPending> pendingNonTXPageCounter) throws Exception {
   }

   @Override
   public void cleanUp() {

   }
}


text:
Download and install the package found here : [https://our.umbraco.org/projects/backoffice-extensions/nexu](https://our.umbraco.org/projects/backoffice-extensions/nexu)

## Nuget package ##

[https://www.nuget.org/packages/Our.Umbraco.Nexu/](https://www.nuget.org/packages/Our.Umbraco.Nexu/)

# Steps after installation #

Go to the nexu dashboard in the settings section and click the "Rebuild nexu relations" button. This will crawl all your content and rebuild the link relations. As this process happens in the background you can keep working without a problem and come back to recheck the status.


text:
package com.example.android.tv.recommendations;

import android.app.job.JobParameters;
import android.app.job.JobService;
import android.content.Context;
import android.os.AsyncTask;
import android.os.PersistableBundle;
import android.support.annotation.NonNull;
import android.support.media.tv.PreviewProgram;
import android.support.media.tv.TvContractCompat;
import android.util.Log;
import com.example.android.tv.recommendations.model.MockDatabase;
import com.example.android.tv.recommendations.model.Movie;
import com.example.android.tv.recommendations.model.Subscription;
import com.example.android.tv.recommendations.util.TvUtil;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * Syncs programs for a channel. A channel id is required to be passed via the {@link
 * JobParameters}. This service is scheduled to listen to changes to a channel. Once the job
 * completes, it will reschedule itself to listen for the next change to the channel. See {@link
 * TvUtil#scheduleSyncingProgramsForChannel(Context, long)} for more details about the scheduling.
 */
public class SyncProgramsJobService extends JobService {

    private static final String TAG = "SyncProgramsJobService";

    private SyncProgramsTask mSyncProgramsTask;

    @Override
    public boolean onStartJob(final JobParameters jobParameters) {
        Log.d(TAG, "onStartJob(): " + jobParameters);

        final long channelId = getChannelId(jobParameters);
        if (channelId == -1L) {
            return false;
        }
        Log.d(TAG, "onStartJob(): Scheduling syncing for programs for channel " + channelId);

        mSyncProgramsTask =
                new SyncProgramsTask(getApplicationContext()) {
                    @Override
                    protected void onPostExecute(Boolean finished) {
                        super.onPostExecute(finished);
                        // Daisy chain listening for the next change to the channel.
                        TvUtil.scheduleSyncingProgramsForChannel(
                                SyncProgramsJobService.this, channelId);
                        mSyncProgramsTask = null;
                        jobFinished(jobParameters, !finished);
                    }
                };
        mSyncProgramsTask.execute(channelId);

        return true;
    }

    @Override
    public boolean onStopJob(JobParameters jobParameters) {
        if (mSyncProgramsTask != null) {
            mSyncProgramsTask.cancel(true);
        }
        return true;
    }

    private long getChannelId(JobParameters jobParameters) {
        PersistableBundle extras = jobParameters.getExtras();
        if (extras == null) {
            return -1L;
        }

        return extras.getLong(TvContractCompat.EXTRA_CHANNEL_ID, -1L);
    }

    /*
     * Syncs programs by querying the given channel id.
     *
     * If the channel is not browsable, the programs will be removed to avoid showing
     * stale programs when the channel becomes browsable in the future.
     *
     * If the channel is browsable, then it will check if the channel has any programs.
     *      If the channel does not have any programs, new programs will be added.
     *      If the channel does have programs, then a fresh list of programs will be fetched and the
     *          channel's programs will be updated.
     */
    private void syncPrograms(long channelId, List<Movie> initialMovies) {
        Log.d(TAG, "Sync programs for channel: " + channelId);
        List<Movie> movies = new ArrayList<>(initialMovies);

        // TODO: step 5 check if visible.

    }

    private List<Movie> createPrograms(long channelId, List<Movie> movies) {
        // TODO: step 7 add programs.
        return Collections.emptyList();
    }

    private List<Movie> updatePrograms(long channelId, List<Movie> movies) {
        // TODO: step 8 update programs.
        return Collections.emptyList();
    }

    private void deletePrograms(long channelId, List<Movie> movies) {
        if (movies.isEmpty()) {
            return;
        }

        // TODO: step 9 delete programs.

        // Remove our local records to stay in sync with the TV Provider.
        MockDatabase.removeMovies(getApplicationContext(), channelId);
    }

    @NonNull
    private PreviewProgram buildProgram(long channelId, Movie movie) {
        // TODO: step 6 convert movie to program
        return null;
    }

    private class SyncProgramsTask extends AsyncTask<Long, Void, Boolean> {

        private final Context mContext;

        private SyncProgramsTask(Context context) {
            this.mContext = context;
        }

        @Override
        protected Boolean doInBackground(Long... channelIds) {
            List<Long> params = Arrays.asList(channelIds);
            if (!params.isEmpty()) {
                for (Long channelId : params) {
                    Subscription subscription =
                            MockDatabase.findSubscriptionByChannelId(mContext, channelId);
                    if (subscription != null) {
                        List<Movie> cachedMovies = MockDatabase.getMovies(mContext, channelId);
                        syncPrograms(channelId, cachedMovies);
                    }
                }
            }
            return true;
        }
    }
}


text:
package uk.gov.gchq.gaffer.sketches.datasketches.theta.binaryoperator;

import com.yahoo.sketches.theta.Sketches;
import com.yahoo.sketches.theta.Union;
import org.junit.jupiter.api.Test;

import uk.gov.gchq.gaffer.commonutil.JsonAssert;
import uk.gov.gchq.gaffer.exception.SerialisationException;
import uk.gov.gchq.gaffer.jsonserialisation.JSONSerialiser;
import uk.gov.gchq.koryphe.binaryoperator.BinaryOperatorTest;

import java.util.function.BinaryOperator;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;

public class UnionAggregatorTest extends BinaryOperatorTest {

    private static final double DELTA = 0.01D;

    @Test
    public void testAggregate() {
        final UnionAggregator unionAggregator = new UnionAggregator();

        Union currentUnion = Sketches.setOperationBuilder().buildUnion();
        currentUnion.update("A");
        currentUnion.update("B");

        assertEquals(2.0D, currentUnion.getResult().getEstimate(), DELTA);

        Union newUnion = Sketches.setOperationBuilder().buildUnion();
        newUnion.update("C");
        newUnion.update("D");

        currentUnion = unionAggregator.apply(currentUnion, newUnion);
        assertEquals(4.0D, currentUnion.getResult().getEstimate(), DELTA);
    }

    @Test
    public void testEquals() {
        assertEquals(new UnionAggregator(), new UnionAggregator());
    }

    @Test
    @Override
    public void shouldJsonSerialiseAndDeserialise() throws SerialisationException {
        // Given
        final UnionAggregator aggregator = new UnionAggregator();

        // When 1
        final String json = new String(JSONSerialiser.serialise(aggregator, true));
        // Then 1
        JsonAssert.assertEquals(String.format("{%n" +
                "  \"class\" : \"uk.gov.gchq.gaffer.sketches.datasketches.theta.binaryoperator.UnionAggregator\"%n" +
                "}"), json);

        // When 2
        final UnionAggregator deserialisedAggregator = JSONSerialiser
                .deserialise(json.getBytes(), UnionAggregator.class);
        // Then 2
        assertNotNull(deserialisedAggregator);
    }

    @Override
    protected Class<? extends BinaryOperator> getFunctionClass() {
        return UnionAggregator.class;
    }

    @Override
    protected UnionAggregator getInstance() {
        return new UnionAggregator();
    }

    @Override
    protected Iterable<UnionAggregator> getDifferentInstancesOrNull() {
        return null;
    }
}


text:
package nl.sense_os.commonsense.login.client.newpassword;

import nl.sense_os.commonsense.common.client.component.Resettable;

import com.google.gwt.user.client.ui.IsWidget;

public interface NewPasswordView extends IsWidget, Resettable {

	public interface Presenter {

		void cancel();

		void submit(String password);
	}

	void setPresenter(Presenter presenter);
}


text:
using System.Text.Json;
using Azure.Core;

namespace Azure.ResourceManager.Network.Models
{
    public partial class P2SVpnProfileContent : IUtf8JsonSerializable
    {
        void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
        {
            writer.WriteStartObject();
            if (Optional.IsDefined(AuthenticationMethod))
            {
                writer.WritePropertyName("authenticationMethod");
                writer.WriteStringValue(AuthenticationMethod.Value.ToString());
            }
            writer.WriteEndObject();
        }
    }
}


text:
import { krl, KrlLogger, makeKrlLogger } from "krl-stdlib";
import leveldown from "leveldown";
import * as _ from "lodash";
import * as makeDir from "make-dir";
import * as path from "path";
import { PicoEngineCore, RulesetRegistry } from "pico-engine-core";
import { PicoFramework } from "pico-framework";
import { getPicoLogs, makeRotatingFileLogWriter } from "./logging";
import { RulesetRegistryLoaderFs } from "./RulesetRegistryLoaderFs";
import { server } from "./server";
import { toFileUrl } from "./utils/toFileUrl";
import * as fs from "fs";
import { reject } from "lodash";

const homeDir = require("home-dir");
const version = require("../package.json").version;

/**
 * Configuration options that may be set by the user
 */
export interface PicoEngineConfiguration {
  /**
   * The absolute path to the folder where the engine should store the database and logs.
   *
   * Default: "~/.pico-engine/"
   */
  home?: string;

  /**
   * The port number the http server should listen on.
   *
   * If you want an available port assigned to you, set it to 0
   *
   * Default: 3000
   */
  port?: number;

  /**
   * The base url others should use when addressing your engine.
   *
   * Default: "http://localhost:3000"
   */
  base_url?: string;

  /**
   * Provide any custom krl modules
   */
  modules?: { [domain: string]: krl.Module };

  /**
   * Trust event.time input. Used for testing
   */
  useEventInputTime?: boolean;

  log?: KrlLogger;
}

export interface PicoEngine {
  version: string;

  home: string;
  port: number;
  base_url: string;

  pf: PicoFramework;
  uiECI: string;
  rsRegistry: RulesetRegistry;
}

export async function startEngine(
  configuration: PicoEngineConfiguration = {}
): Promise<PicoEngine> {
  let home = configuration.home;
  let port = configuration.port;
  let base_url = configuration.base_url;

  if (typeof home !== "string") {
    home = homeDir(".pico-engine") as string;
  }
  await makeDir(home);

  const logFilePath = path.resolve(home, "pico-engine.log");
  const log = configuration.log
    ? configuration.log
    : makeKrlLogger(makeRotatingFileLogWriter(logFilePath));

  const core = new PicoEngineCore({
    leveldown: leveldown(path.resolve(home, "db")) as any,
    rsRegLoader: RulesetRegistryLoaderFs(home),
    log,
    modules: configuration.modules,
    useEventInputTime: configuration.useEventInputTime,
    getPicoLogs(picoId) {
      return getPicoLogs(logFilePath, picoId);
    },
  });
  await core.start();
  const rsRegistry = core.rsRegistry;
  const pf = core.picoFramework;

  const krl_urls: string[] = [
    toFileUrl(
      path.resolve(__dirname, "..", "krl", "io.picolabs.pico-engine-ui.krl")
    ),
    toFileUrl(path.resolve(__dirname, "..", "krl", "io.picolabs.wrangler.krl")),
    toFileUrl(
      path.resolve(__dirname, "..", "krl", "io.picolabs.subscription.krl")
    ),
  ];
  for (const url of krl_urls) {
    const { ruleset } = await rsRegistry.flush(url);
    await pf.rootPico.install(ruleset, { url, config: {} });
  }

  let uiChannel = pf.rootPico
    .toReadOnly()
    .channels.find(
      (chann) => "engine,ui" === chann.tags.slice(0).sort().join(",")
    );
  if (!uiChannel) {
    uiChannel = (
      await pf.rootPico.newChannel({
        tags: ["engine", "ui"],
        eventPolicy: {
          allow: [{ domain: "engine_ui", name: "setup" }],
          deny: [],
        },
      })
    ).toReadOnly();
  }
  await pf.eventWait({
    eci: uiChannel.id,
    domain: "engine_ui",
    name: "setup",
    data: { attrs: {} },
    time: 0,
  });

  const uiECI = uiChannel.id;

  const app = server(core, uiECI);

  if ((!port || !_.isInteger(port) || port < 1) && port !== 0) {
    port = 3000;
  }
  await new Promise((resolve) => {
    const listener = app.listen(port, () => {
      if (listener) {
        const addr = listener.address();
        if (addr && typeof addr !== "string" && _.isInteger(addr.port)) {
          // Get the actual port i.e. if they set port to 0 nodejs will assign you an available port
          port = addr.port;
        }
      }
      resolve(undefined);
    });
  });
  if (typeof base_url !== "string") {
    base_url = `http://localhost:${port}`;
  }
  core.base_url = base_url;

  log.info(`Listening at ${base_url}`);

  pf.event({
    eci: uiECI,
    domain: "engine",
    name: "started",
    data: { attrs: {} },
    time: 0, // TODO remove this typescript requirement
  }).catch((error) => {
    log.error("Error signaling engine:started event", { error });
    // TODO signal all errors engine:error
  });

  return {
    version,

    home,
    port,
    base_url,

    pf,
    uiECI,
    rsRegistry,
  };
}


text:
Apex Google Mirror API Framework
================================

Overview
--------

An Apex framework has been created to provide functionality for Google Mirror API callouts.

This library extends the [Core](https://github.com/financialforcedev/ffhttp-core) library to provide access to Google Mirror API calls found at https://developers.google.com/glass/v1/reference/.

Samples demonstrating the use of this library can be found [here](https://github.com/financialforcedev/ffhttp-googlemirror-samples).

Key Features
------------

+ Apex Google Mirror API

Configuration
-------------

This section explains how to create a connection between Salesforce and Google Mirror using the packages described above.

Make sure that the [Core](https://githubsfdeploy.herokuapp.com?owner=financialforcedev&repo=ffhttp-core) and [Google Mirror](https://githubsfdeploy.herokuapp.com?owner=financialforcedev&repo=ffhttp-googlemirror) packages have been deployed to your Saleforce organisation.

###Create an app in Google

1. Log in to your Google account.
2. Go to https://console.developers.google.com/project and select **Create Project**.
3. Enter a project name and ok the dialog.
4. Select the hyperlink for the project name that you just created.
5. Expand the **APIs & auth** section.
6. Select **APIs**.
7. Enter **Mirror** in the **Browse APIs** section.
8. Turn the **Google Mirror API** on.
9. Select the **Consent screen**.
10. Enter a **Product Name**, make sure the **Email Address** is set and save.
11. Select **Credentials**.
12. Select **Create new Client ID**.
13. Select **Web application**.
14. Set the **Authorized Javascript Origins** url to the URL of the Salesforce organisation e.g. https://eu3.salesforce.com.
15. Set the **Authorized Redirect URIs** to the same as above with *apex/connector* appended: e.g. https://eu3.salesforce.com/apex/connector.
16. Make sure you know the **Client Id** and **Client Secret** as they will be needed later.

###Create a Connector in Salesforce

This requires the [OAuth Sample App](https://githubsfdeploy.herokuapp.com?owner=financialforcedev&repo=ffhttp-core-samples) to be deployed.

1. Log in to your Salesforce organisation.
2. Select the **OAuth** app.
3. Select **Connector Types** then **New**.
4. Enter a **Connector Type Name** e.g. Google Mirror.
5. Set the **Authorization Endpoint** to https://accounts.google.com/o/oauth2/auth.
6. Set the **Token Endpoint** to https://accounts.google.com/o/oauth2/token.
7. Set the **Client ID** to the client ID obtained earlier.
8. Set the **Client Secret** to the client secret obtained earlier.
9. Set the **Redirect URI** to the same URL as you set in step 12 in the Create an app in Google section.
10. Make sure that **Scope Required** is checked.
11. For full access to Google Mirror add 'https://www.googleapis.com/auth/glass.location https://www.googleapis.com/auth/glass.timeline' as the scope.
12. Set the **Extra Url Parameters** to **access_type=offline&approval_prompt=force**. Setting **access_type** to offline means that Google supplies a refresh token with the access token which is required if you do not wish to reautheniticate every time the access token expires.
13. **Save** the Connector Type.
14. Select **New Connector**.
15. Set the **Connector Name** and save.
16. Select the Connector and then **Activate**. You will be directed to another Salesforce page that activates your connector.
17. Select **Authorize**. This will prompt you to log in to your Google account (if you are not already logged in) and then authenticate the scope provided earlier. Select **Accept** to authorize.
18. Select **Save**. The connector is now ready for use.

Note that authorization can be revoked at any point by either deleting the connector in Salesforce or  revoking access to the app in Google (Select your profile then Account > Security > Account Permissions > Apps and website (View All), choose the app created and then select **Revoke Access**).

###Google Mirror Scopes

To limit access to the Google Mirror functionality the following [scopes](https://developers.google.com/oauthplayground/) can be used.

+ https://www.googleapis.com/auth/glass.location

+ https://www.googleapis.com/auth/glass.timeline

Reporting Issues & Enhancements
-------------------------------

Please report any issues using the github [issues](https://github.com/financialforcedev/ffhttp-googlemirror/issues) feature. Suggestions / bug reports are welcome as are extensions containing additional functionality.


text:
<?xml version="1.0"?>
<!--
  ~ Copyright (c) 2019 Evolveum and contributors
  ~
  ~ This work is dual-licensed under the Apache License 2.0
  ~ and European Union Public License. See LICENSE file for details.
  -->

<role xmlns="http://midpoint.evolveum.com/xml/ns/public/common/common-3"
      oid="b3d1cb95-526b-4162-8d65-acd8f2994644">
    <name>mmr1.1.1</name>
    <inducement>
        <focusMappings>
            <mapping>
                <source>
                    <path>extension/p111c</path>
                </source>
                <target>
                    <path>organizationalUnit</path>
                </target>
            </mapping>
            <mapping>
                <source>
                    <path>extension/p111b</path>
                </source>
                <target>
                    <path>extension/p111c</path>
                </target>
            </mapping>
            <mapping>
                <source>
                    <path>extension/p111a</path>
                </source>
                <target>
                    <path>extension/p111b</path>
                </target>
            </mapping>
            <mapping>
                <source>
                    <path>description</path>
                </source>
                <expression>
                    <script>
                        <code>
                            // source = this metarole
                            description + ':' + basic.stringify(source.name)
                        </code>
                    </script>
                </expression>
                <target>
                    <path>extension/p111a</path>
                </target>
            </mapping>
        </focusMappings>
        <order>3</order>
        <focusType>UserType</focusType>
    </inducement>
</role>


text:
let Verify = require('./Verify');

class Api {
    /**
     * Create a new API instance.
     *
     * @param {Mix} Mix
     */
    constructor(Mix) {
        this.Mix = Mix;
    }

    /**
     * Register the Webpack entry/output paths.
     *
     * @param {string|Array}  entry
     * @param {string} output
     */
    js(entry, output) {
        global.entry.addScript(entry, output);

        return this;
    };

    /**
     * Declare support for the React framework.
     */
    react(entry, output) {
        this.Mix.react = true;

        Verify.dependency(
            'babel-preset-react',
            'npm install babel-preset-react --save-dev'
        );

        this.js(entry, output);

        return this;
    };

    /**
     * Register vendor libs that should be extracted.
     * This helps drastically with long-term caching.
     *
     * @param {Array}  libs
     * @param {string} output
     */
    extract(libs, output) {
        global.entry.addVendor(libs, output);

        return this;
    };

    /**
     * Register libraries to automatically "autoload" when
     * the appropriate variable is references in js
     *
     * @param {object} libs
     */
    autoload(libs) {
        let aliases = {};

        Object.keys(libs).forEach(library => {
            [].concat(libs[library]).forEach(alias => {
                aliases[alias] = library;
            });
        });

        this.Mix.autoload = aliases;

        return this;
    };

    /**
     * Enable Browsersync support for the project.
     *
     * @param {object} config
     */
    browserSync(config = {}) {
        if (typeof config === 'string') {
            config = { proxy: config };
        }

        this.Mix.browserSync = config;

        return this;
    };

    /**
     * Register Sass compilation.
     *
     * @param {string} src
     * @param {string} output
     * @param {object} pluginOptions
     */
    sass(src, output, pluginOptions = {}) {
        return this.preprocess(
            'Sass', src, output, pluginOptions
        );
    };

    /**
     * Register standalone-Sass compilation that will not run through Webpack.
     *
     * @param {string} src
     * @param {string} output
     * @param {object} pluginOptions
     */
    standaloneSass(src, output, pluginOptions = {}) {
        let Preprocessor = require('./Preprocessors/StandaloneSass');

        this.Mix.standaloneSass = new Preprocessor(src, output, pluginOptions);

        return this;
    };

    /**
     * Register Less compilation.
     *
     * @param {string} src
     * @param {string} output
     * @param {object} pluginOptions
     */
    less(src, output, pluginOptions = {}) {
        return this.preprocess(
            'Less', src, output, pluginOptions
        );
    };

    /**
     * Register Stylus compilation.
     *
     * @param {string} src
     * @param {string} output
     * @param {object} pluginOptions
     */
    stylus(src, output, pluginOptions = {}) {
        Verify.dependency(
            'stylus-loader',
            'npm install stylus-loader stylus --save-dev'
        );

        return this.preprocess(
            'Stylus', src, output, pluginOptions
        );
    };

    /**
     * Register a generic CSS preprocessor.
     *
     * @param {string} type
     * @param {string} src
     * @param {string} output
     * @param {object} pluginOptions
     */
    preprocess(type, src, output, pluginOptions) {
        Verify.preprocessor(type, src, output);

        global.entry.addStylesheet(src, output);

        let Preprocessor = require('./Preprocessors/' + type);

        this.Mix.preprocessors = (this.Mix.preprocessors || []).concat(
            new Preprocessor(src, output, pluginOptions)
        );

        return this;
    };

    /**
     * Combine a collection of files.
     *
     * @param {string|Array} src
     * @param {string}       output
     */
    combine(src, output) {
        this.Mix.concat.add({ src, output });

        return this;
    };

    /**
     * Alias for this.Mix.combine().
     *
     * @param {string|Array} src
     * @param {string}       output
     */
    scripts(src, output) {
        return this.combine(src, output);
    };

    /**
     * Alias for this.Mix.combine().
     *
     * @param {string|Array} src
     * @param {string}       output
     */
    styles(src, output) {
        return this.combine(src, output);
    };

    /**
     * Identical to this.Mix.combine(), but includes Babel compilation.
     *
     * @param {string|Array} src
     * @param {string}       output
     */
    babel(src, output) {
        this.Mix.concat.add({ src, output, babel: true });

        return this;
    };

    /**
     * Copy one or more files to a new location.
     *
     * @param {string}  from
     * @param {string}  to
     * @param {boolean} flatten
     */
    copy(from, to, flatten = true) {
        this.Mix.copy = this.Mix.copy || [];

        [].concat(from).forEach(src => {
            this.Mix.copy.push({
                from: src,
                to: global.Paths.root(to),
                flatten: flatten
            });
        });

        return this;
    };

    /**
     * Copy an entire directory to a new location.
     *
     * @param {string} from
     * @param {string} to
     */
    copyDirectory(from, to) {
        return this.copy(from, to, false);
    };

    /**
     * Minify the provided file.
     *
     * @param {string|Array} src
     */
    minify(src) {
        let output = src.replace(/\.([a-z]{2,})$/i, '.min.$1');

        this.Mix.concat.add({ src, output });

        return this;
    };

    /**
     * Enable sourcemap support.
     */
    sourceMaps() {
        global.options.sourcemaps = (this.Mix.inProduction ? false : '#inline-source-map');

        return this;
    };

    /**
     * Enable compiled file versioning.
     *
     * @param {string|Array} files
     */
    version(files = []) {
        global.options.versioning = true;
        this.Mix.version = [].concat(files);

        return this;
    };

    /**
     * Disable all OS notifications.
     */
    disableNotifications() {
        global.options.notifications = false;

        return this;
    };

    /**
     * Set the path to your public folder.
     *
     * @param {string} path
     */
    setPublicPath(path) {
        global.options.publicPath = this.Mix.publicPath = new File(path)
            .parsePath()
            .pathWithoutExt;

        return this;
    };

    /**
     * Set prefix for generated asset paths
     *
     * @param {string} path
     */
    setResourceRoot(path) {
        global.options.resourceRoot = path;

        return this;
    };

    /**
     * Merge custom config with the provided webpack.config file.
     *
     * @param {object} config
     */
    webpackConfig(config) {
        this.Mix.webpackConfig = config;

        return this;
    }

    /**
     * Set Mix-specific options.
     *
     * @param {object} options
     */
    options(options) {
        if (options.purifyCss) {
            options.purifyCss = require('./PurifyPaths').build(options.purifyCss);

            Verify.dependency(
                'purifycss-webpack',
                'npm install purifycss-webpack --save-dev',
                true // abortOnComplete
            );
        }

        global.options.merge(options);

        return this;
    };

    /**
     * Register a Webpack build event handler.
     *
     * @param {Function} callback
     */
    then(callback) {
        global.events.listen('build', callback);

        return this;
    }
}

module.exports = Api;


text:
package org.apache.stratos.autoscaler.algorithms.networkpartition;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.stratos.autoscaler.algorithms.NetworkPartitionAlgorithm;
import org.apache.stratos.autoscaler.pojo.policy.PolicyManager;
import org.apache.stratos.autoscaler.pojo.policy.deployment.ApplicationPolicy;
import org.apache.stratos.common.constants.StratosConstants;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * One after algorithm for the network-partition or groups
 */
public class OneAfterAnotherAlgorithm implements NetworkPartitionAlgorithm {

    private static final Log log = LogFactory.getLog(NetworkPartitionAlgorithm.class);

    @Override
    public List<String> getNextNetworkPartitions(NetworkPartitionAlgorithmContext
                                                         networkPartitionAlgorithmContext) {

        if (networkPartitionAlgorithmContext == null) {
            if (log.isWarnEnabled()) {
                String msg = "Network partition algorithm context is null";
                log.warn(msg);
            }
            return null;
        }

        String applicationId = networkPartitionAlgorithmContext.getApplicationId();
        if (applicationId == null) {
            if (log.isWarnEnabled()) {
                String msg = "Application id is null in network partition algorithm context";
                log.warn(msg);
            }
            return null;
        }

        ApplicationPolicy applicationPolicy = PolicyManager.getInstance().getApplicationPolicy(
                networkPartitionAlgorithmContext.getApplicationPolicyId());
        if (applicationPolicy == null) {
            if (log.isWarnEnabled()) {
                String msg = String.format("No application policy found in network partition " +
                        "algorithm context [application-id] %s", applicationId);
                log.warn(msg);
            }
            return null;
        }

        String applicationPolicyId = applicationPolicy.getUuid();
        String[] networkPartitionGroups = applicationPolicy.getNetworkPartitionGroups();
        if (networkPartitionGroups != null && networkPartitionGroups.length != 0) {
            if (log.isDebugEnabled()) {
                String msg = String.format("Network partition groups property found in " +
                                "application policy [application-id] %s [application-policy-id] %s. "
                                + "Hence using network partition groups for app bursting",
                        applicationId, applicationPolicyId);
                log.debug(msg);
            }
            int totalNetworkPartitionGroups = networkPartitionGroups.length;
            if (log.isDebugEnabled()) {
                String msg = String.format("%s network partition groups found in application " +
                                "policy [application-id] %s [application-policy-id] %s",
                        totalNetworkPartitionGroups, applicationId, applicationPolicyId);
                log.debug(msg);
            }

            int currentPartitionIndex = networkPartitionAlgorithmContext.
                    getCurrentNetworkPartitionIndex().intValue();
            if (log.isDebugEnabled()) {
                String msg = String.format("Current network partition group index is %s " +
                                "[application-id] %s [application-policy-d] %s",
                        currentPartitionIndex, applicationId, applicationPolicyId);
                log.debug(msg);
            }

            if (currentPartitionIndex >= totalNetworkPartitionGroups) {
                if (log.isDebugEnabled()) {
                    String msg = String.format("currentPartitionIndex %s >= " +
                                    "totalNetworkPartitionGroups %s, hence no more network partition" +
                                    " groups are available [application-id] %s " +
                                    "[application-policy-id] %s", currentPartitionIndex,
                            totalNetworkPartitionGroups, applicationId, applicationPolicyId);
                    log.debug(msg);
                }
                return null;
            }

            int selectedIndex = networkPartitionAlgorithmContext.
                    getCurrentNetworkPartitionIndex().incrementAndGet();
            if (log.isDebugEnabled()) {
                String msg = String.format("Selected network partition group index is %s " +
                                "(starting from 1,2,3...) [application-id] %s " +
                                "[application-policy-d] %s", selectedIndex,
                        applicationId, applicationPolicyId);
                log.debug(msg);
            }

            if (log.isDebugEnabled()) {
                String msg = String.format("Selected network partition group is %s " +
                                "[application-id] %s [application-policy-id] %s",
                        networkPartitionGroups[selectedIndex - 1], applicationId, applicationPolicyId);
                log.debug(msg);
            }

            List<String> selectedNetworkPartitions = new ArrayList<String>();
            Collections.addAll(selectedNetworkPartitions, networkPartitionGroups[selectedIndex - 1].
                    split(StratosConstants.APPLICATION_POLICY_NETWORK_PARTITIONS_SPLITTER));

            return selectedNetworkPartitions;
        }

        String[] networkPartitions = applicationPolicy.getNetworkPartitionsUuid();
        if (networkPartitions == null || networkPartitions.length == 0) {
            if (log.isWarnEnabled()) {
                String msg = String.format("Network partitions found in application policy " +
                                "[application-id] %s [application-policy-id] %s",
                        applicationId, applicationPolicyId);
                log.warn(msg);
            }
            return null;
        }

        int totalNetworkPartitions = networkPartitions.length;
        if (log.isDebugEnabled()) {
            String msg = String.format("%s network partitions found in application policy " +
                            "[application-id] %s [application-policy-id] %s",
                    totalNetworkPartitions, applicationId, applicationPolicyId);
            log.debug(msg);
        }

        int currentPartitionIndex = networkPartitionAlgorithmContext.
                getCurrentNetworkPartitionIndex().intValue();
        if (log.isDebugEnabled()) {
            String msg = String.format("Current network partition index is %s " +
                            "[application-id] %s [application-policy-id] %s",
                    currentPartitionIndex, applicationId, applicationPolicyId);
            log.debug(msg);
        }

        if (currentPartitionIndex >= totalNetworkPartitions) {
            if (log.isDebugEnabled()) {
                String msg = String.format("currentPartitionIndex %s >= totalNetworkPartitions %s , " +
                                "hence no more network partitions are available "
                                + "[application-id] %s [application-policy-id] %s", currentPartitionIndex,
                        totalNetworkPartitions, applicationId, applicationPolicyId);
                log.debug(msg);
            }
            return null;
        }

        int selectedIndex = networkPartitionAlgorithmContext.getCurrentNetworkPartitionIndex().
                incrementAndGet();
        if (log.isDebugEnabled()) {
            String msg = String.format("Selected network partition index is %s " +
                            "(starting from 1,2,3...) [application-id] %s [application-policy-id] %s",
                    selectedIndex, applicationId, applicationPolicyId);
            log.debug(msg);
        }

        if (log.isDebugEnabled()) {
            String msg = String.format("Selected network partition is %s [application-id] %s " +
                            "[application-policy-id] %s",
                    networkPartitions[selectedIndex - 1], applicationId, applicationPolicyId);
            log.debug(msg);
        }

        List<String> nextNetworkPartitions = new ArrayList<String>();
        nextNetworkPartitions.add(networkPartitions[selectedIndex - 1]);

        return nextNetworkPartitions;
    }

    @Override
    public List<String> getDefaultNetworkPartitions(NetworkPartitionAlgorithmContext
                                                            networkPartitionAlgorithmContext) {
        if (networkPartitionAlgorithmContext == null) {
            if (log.isWarnEnabled()) {
                String msg = "Network partition algorithm context is null";
                log.warn(msg);
            }
            return null;
        }

        String applicationId = networkPartitionAlgorithmContext.getApplicationId();
        if (applicationId == null) {
            if (log.isWarnEnabled()) {
                String msg = "Application id is null in network partition algorithm context";
                log.warn(msg);
            }
            return null;
        }

        ApplicationPolicy applicationPolicy = PolicyManager.getInstance().getApplicationPolicy(
                networkPartitionAlgorithmContext.getApplicationPolicyId());
        if (applicationPolicy == null) {
            if (log.isWarnEnabled()) {
                String msg = String.format("No application policy found in network partition " +
                        "algorithm context [application-id] %s", applicationId);
                log.warn(msg);
            }
            return null;
        }

        String applicationPolicyId = applicationPolicy.getUuid();
        String[] networkPartitionGroups = applicationPolicy.getNetworkPartitionGroups();
        List<String> selectedNetworkPartitions = new ArrayList<String>();

        if (networkPartitionGroups != null && networkPartitionGroups.length != 0) {
            if (log.isDebugEnabled()) {
                String msg = String.format("Network partition groups property found in application " +
                                "policy [application-id] %s [application-policy-id] %s. "
                                + "Hence using network partition groups for app bursting",
                        applicationId, applicationPolicyId);
                log.debug(msg);
            }
            int totalNetworkPartitionGroups = networkPartitionGroups.length;
            if (log.isDebugEnabled()) {
                String msg = String.format("%s network partition groups found in application policy" +
                                " [application-id] %s [application-policy-id] %s",
                        totalNetworkPartitionGroups, applicationId, applicationPolicyId);
                log.debug(msg);
            }
            //Returning the very first network-partition group as the default one
            Collections.addAll(selectedNetworkPartitions, networkPartitionGroups[0].
                    split(StratosConstants.APPLICATION_POLICY_NETWORK_PARTITIONS_SPLITTER));

        } else {
            //Returning the very first network-partition as the default one
            String[] networkPartitions = applicationPolicy.getNetworkPartitionsUuid();
            selectedNetworkPartitions.add(networkPartitions[0]);
        }

        return selectedNetworkPartitions;

    }
}


text:
//
//  LFVideoTrimmerGridView.m
//  LFMediaEditingController
//
//  Created by LamTsanFeng on 2017/7/18.
//  Copyright © 2017年 LamTsanFeng. All rights reserved.
//

#import "LFVideoTrimmerGridView.h"
#import "LFResizeControl.h"
#import "LFVideoTrimmerGridLayer.h"
#import "LFGridMaskLayer.h"
#import "UIView+LFMEFrame.h"

@interface LFResizeImageControl : LFResizeControl

@property (nonatomic, strong) UIImage *image;
@property (strong, nonatomic, nullable) UIColor *color;
@property (nonatomic, assign) CGRect imageRect;

@end

@implementation LFResizeImageControl

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        _imageRect = self.bounds;
    }
    return self;
}

- (void)setImage:(UIImage *)image
{
    _image = image;
    [self setNeedsDisplay];
}

- (void)setColor:(UIColor *)color {
    _color = color;
    [self setNeedsDisplay];
}

- (void)drawRect:(CGRect)rect
{
    // Drawing code

    if (self.image) {
        [self.image drawInRect:self.imageRect];
    } else {
        //// Frames
        CGRect bubbleFrame = self.imageRect;

        //// Rounded Rectangle Drawing
        CGRect roundedRectangleRect = CGRectMake(CGRectGetMinX(bubbleFrame), CGRectGetMinY(bubbleFrame), CGRectGetWidth(bubbleFrame), CGRectGetHeight(bubbleFrame));
        UIBezierPath *roundedRectanglePath = [UIBezierPath bezierPathWithRoundedRect: roundedRectangleRect byRoundingCorners: UIRectCornerTopLeft | UIRectCornerBottomLeft | UIRectCornerTopRight | UIRectCornerBottomRight cornerRadii: CGSizeMake(3, 3)];

        [roundedRectanglePath closePath];
        [self.color setFill];
        [roundedRectanglePath fill];

        CGFloat lineWidth = 1.5f;
        CGRect decoratingRect = CGRectMake(CGRectGetMinX(bubbleFrame)+CGRectGetWidth(bubbleFrame)/3-lineWidth/2, (CGRectGetHeight(bubbleFrame)-15.f)/2, lineWidth, 15.f);
        UIBezierPath *decoratingPath = [UIBezierPath bezierPathWithRoundedRect:decoratingRect byRoundingCorners: UIRectCornerTopLeft | UIRectCornerBottomLeft | UIRectCornerBottomRight | UIRectCornerTopRight cornerRadii: CGSizeMake(1, 1)];
        [decoratingPath closePath];
        [[UIColor colorWithWhite:0.5 alpha:1.f] setFill];
        [decoratingPath fill];

        CGRect decoratingRect1 = decoratingRect;
        decoratingRect1.origin.x += CGRectGetWidth(bubbleFrame)/3;
        UIBezierPath *decoratingPath1 = [UIBezierPath bezierPathWithRoundedRect:decoratingRect1 byRoundingCorners: UIRectCornerTopLeft | UIRectCornerBottomLeft | UIRectCornerBottomRight | UIRectCornerTopRight cornerRadii: CGSizeMake(1, 1)];
        [decoratingPath1 closePath];
        [[UIColor colorWithWhite:0.5 alpha:1.f] setFill];
        [decoratingPath1 fill];
    }
}

@end

/** 可控范围 */
const CGFloat kVideoTrimmerGridControlWidth = 25.f;
const CGFloat kVideoTrimmerGridLayerLineWidth = 2.f;

@interface LFVideoTrimmerGridView () <lf_resizeConrolDelegate>

@property (nonatomic, weak) LFResizeImageControl *leftCornerView;
@property (nonatomic, weak) LFResizeImageControl *rightCornerView;

@property (nonatomic, weak) LFResizeControl *centerCornerView;

/** 边框 */
@property (nonatomic, weak) LFVideoTrimmerGridLayer *gridLayer;
/** 背景 */
@property (nonatomic, weak) LFVideoTrimmerGridLayer *bg_gridLayer;
/** 遮罩 */
@property (nonatomic, weak) LFGridMaskLayer *gridMaskLayer;
/** 进度 */
@property (nonatomic, weak) UIView *slider;

@property (nonatomic, assign) CGRect initialRect;

@end

@implementation LFVideoTrimmerGridView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self customInit];
    }
    return self;
}

- (void)customInit
{
    /** 进度 */
    UIView *slider = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 2, self.bounds.size.height)];
    slider.backgroundColor = [UIColor colorWithWhite:1.f alpha:0.8f];
    slider.userInteractionEnabled = NO;
    [self addSubview:slider];
    _slider = slider;

    /** 背景 */
    LFVideoTrimmerGridLayer *bg_gridLayer = [[LFVideoTrimmerGridLayer alloc] init];
    bg_gridLayer.frame = self.bounds;
    bg_gridLayer.lineWidth = kVideoTrimmerGridLayerLineWidth;
    bg_gridLayer.bgColor = [UIColor clearColor];
    bg_gridLayer.gridColor = [UIColor colorWithWhite:1.f alpha:0.5f];
    bg_gridLayer.gridRect = self.bounds;
    bg_gridLayer.hidden = YES;
    [self.layer addSublayer:bg_gridLayer];
    self.bg_gridLayer = bg_gridLayer;

    /** 遮罩 */
    LFGridMaskLayer *gridMaskLayer = [[LFGridMaskLayer alloc] init];
    gridMaskLayer.frame = self.bounds;
    gridMaskLayer.maskColor = [UIColor colorWithWhite:.0f alpha:.5f].CGColor;
    [self.layer addSublayer:gridMaskLayer];
    self.gridMaskLayer = gridMaskLayer;

    /** 边框 */
    LFVideoTrimmerGridLayer *gridLayer = [[LFVideoTrimmerGridLayer alloc] init];
    gridLayer.frame = self.bounds;
    gridLayer.lineWidth = kVideoTrimmerGridLayerLineWidth;
    gridLayer.bgColor = [UIColor clearColor];
    gridLayer.gridColor = [UIColor whiteColor];
    [self.layer addSublayer:gridLayer];
    self.gridLayer = gridLayer;

    /** 左右控制器 */
    self.leftCornerView = [self createResizeControl];
    self.rightCornerView = [self createResizeControl];
    self.centerCornerView = [self createCenterResizeControl];

    self.gridRect = self.bounds;
    self.controlMinWidth = self.frame.size.width * 0.33f;
    self.controlMaxWidth = self.frame.size.width;

}

- (void)layoutSubviews
{
    [super layoutSubviews];

    self.gridLayer.frame = self.bounds;
    self.bg_gridLayer.frame = self.bounds;
    self.gridMaskLayer.frame = self.bounds;

    CGRect rect = self.gridRect;

    self.leftCornerView.frame = (CGRect){CGRectGetMinX(rect) - CGRectGetWidth(self.leftCornerView.bounds) / 2, (CGRectGetHeight(rect) - CGRectGetHeight(self.leftCornerView.bounds)) / 2, self.leftCornerView.bounds.size};
    self.rightCornerView.frame = (CGRect){CGRectGetMaxX(rect) - CGRectGetWidth(self.rightCornerView.bounds) / 2, (CGRectGetHeight(rect) - CGRectGetHeight(self.rightCornerView.bounds)) / 2, self.rightCornerView.bounds.size};

    self.centerCornerView.frame = CGRectMake(CGRectGetMaxX(self.leftCornerView.frame), CGRectGetMinY(self.leftCornerView.frame), CGRectGetMinX(self.rightCornerView.frame)-CGRectGetMaxX(self.leftCornerView.frame), CGRectGetHeight(self.leftCornerView.frame));
}

- (BOOL)isEnabledLeftCorner
{
    return self.leftCornerView.userInteractionEnabled;
}

- (void)setEnabledLeftCorner:(BOOL)enabledLeftCorner
{
    self.leftCornerView.userInteractionEnabled = enabledLeftCorner;
}

- (BOOL)isEnabledRightCorner
{
    return self.rightCornerView.userInteractionEnabled;
}

- (void)setEnabledRightCorner:(BOOL)enabledRightCorner
{
    self.rightCornerView.userInteractionEnabled = enabledRightCorner;
}

- (void)setProgress:(double)progress
{
    if (isnan(progress) || progress < 0) {
        return;
    }
    _progress = progress;
    _slider.lfme_x = progress*self.lfme_width;
}

- (void)setHiddenProgress:(BOOL)hidden
{
    _slider.hidden = hidden;
}

#pragma mark - lf_resizeConrolDelegate

- (void)lf_resizeConrolDidBeginResizing:(LFResizeControl *)resizeConrol
{
    [self bringSubviewToFront:resizeConrol];

    self.bg_gridLayer.hidden = NO;
    self.initialRect = self.gridRect;

    if ([self.delegate respondsToSelector:@selector(lf_videoTrimmerGridViewDidBeginResizing:)]) {
        [self.delegate lf_videoTrimmerGridViewDidBeginResizing:self];
    }
}

- (void)lf_resizeConrolDidResizing:(LFResizeControl *)resizeConrol
{
    CGRect gridRect = [self cropRectMakeWithResizeControlView:resizeConrol];

    if (!CGRectEqualToRect(_gridRect, gridRect)) {
        [self setGridRect:gridRect animated:NO];
        if ([self.delegate respondsToSelector:@selector(lf_videoTrimmerGridViewDidResizing:)]) {
            [self.delegate lf_videoTrimmerGridViewDidResizing:self];
        }
    }
}

- (void)lf_resizeConrolDidEndResizing:(LFResizeControl *)resizeConrol
{
    self.bg_gridLayer.hidden = YES;
    self.leftCornerView.enabled = YES;
    self.rightCornerView.enabled = YES;
    self.centerCornerView.enabled = YES;
    if ([self.delegate respondsToSelector:@selector(lf_videoTrimmerGridViewDidEndResizing:)]) {
        [self.delegate lf_videoTrimmerGridViewDidEndResizing:self];
    }
}

- (void)setGridRect:(CGRect)gridRect
{
    [self setGridRect:gridRect animated:NO];
}

- (void)setGridRect:(CGRect)gridRect animated:(BOOL)animated
{
    if (!CGRectEqualToRect(_gridRect, gridRect)) {
        _gridRect = gridRect;
        [self.gridLayer setGridRect:gridRect animated:animated];
        self.gridMaskLayer.maskRect = self.gridRect;
        [self setNeedsLayout];
    }
}

#pragma mark - private
- (LFResizeImageControl *)createResizeControl
{
    LFResizeImageControl *control = [[LFResizeImageControl alloc] initWithFrame:(CGRect){CGPointMake(0, -kVideoTrimmerGridLayerLineWidth/2), CGSizeMake(kVideoTrimmerGridControlWidth, self.bounds.size.height+kVideoTrimmerGridLayerLineWidth)}];
    control.color = [UIColor whiteColor];
    CGFloat imageWidth = 10.f;
    control.imageRect = CGRectMake((control.frame.size.width-imageWidth)/2, 0, imageWidth, control.frame.size.height);
    control.delegate = self;
    [self addSubview:control];
    return control;
}

- (LFResizeControl *)createCenterResizeControl
{
    LFResizeControl *control = [[LFResizeControl alloc] initWithFrame:self.bounds];
    control.delegate = self;
    control.backgroundColor = [UIColor clearColor];
    [self addSubview:control];
    return control;
}

- (CGRect)cropRectMakeWithResizeControlView:(LFResizeControl *)resizeControlView
{
    CGRect rect = self.gridRect;

    if (resizeControlView == self.leftCornerView) {
        rect = CGRectMake(CGRectGetMinX(self.initialRect) + resizeControlView.translation.x,
                          CGRectGetMinY(self.initialRect),
                          CGRectGetWidth(self.initialRect) - resizeControlView.translation.x,
                          CGRectGetHeight(self.initialRect));
    } else if (resizeControlView == self.rightCornerView) {
        rect = CGRectMake(CGRectGetMinX(self.initialRect),
                          CGRectGetMinY(self.initialRect),
                          CGRectGetWidth(self.initialRect) + resizeControlView.translation.x,
                          CGRectGetHeight(self.initialRect));
    } else if (resizeControlView == self.centerCornerView) {
        rect = CGRectMake(CGRectGetMinX(self.initialRect) + resizeControlView.translation.x,
                          CGRectGetMinY(self.initialRect),
                          CGRectGetWidth(self.initialRect),
                          CGRectGetHeight(self.initialRect));
    }
    /** ps:
     此处判断 不能使用CGRectGet开头的方法,计算会有问题;
     当rect = (origin = (x = 50, y = 618), size = (width = 61, height = -488)) 时,
     CGRectGetMaxY(rect) = 618;CGRectGetHeight(rect) = 488
     */

    if (resizeControlView == self.leftCornerView) {
        /** 限制宽度 超出 最大限度 */
        if (rect.size.width > self.controlMaxWidth || rect.origin.x < 0) {
            if (rect.size.width > self.controlMaxWidth) {
                CGFloat diff = (self.controlMaxWidth - rect.size.width);
                rect.origin.x -= diff;
                rect.size.width += diff;
            } else {
                rect.origin.x = 0;
            }
        } else
        /** 限制宽度 超出 最小限度 */
        if (rect.size.width < self.controlMinWidth) {
            CGFloat diff = self.controlMinWidth - rect.size.width;
            rect.origin.x -= diff;
            rect.size.width += diff;
            /** 最小值大于自身宽度 */
            if (rect.origin.x < 0) {
                rect.size.width += rect.origin.x;
                rect.origin.x = 0;
            }
        }
    } else if (resizeControlView == self.rightCornerView) {
        /** 限制宽度 超出 最大限度 */
        if (rect.size.width > self.controlMaxWidth || rect.origin.x+rect.size.width > self.frame.size.width) {
            CGFloat diff = rect.size.width > self.controlMaxWidth ? (self.controlMaxWidth - rect.size.width) : (self.frame.size.width-(rect.origin.x+rect.size.width));
            rect.size.width += diff;
        } else
        /** 限制宽度 超出 最小限度 */
        if (rect.size.width < self.controlMinWidth) {
            CGFloat diff = self.controlMinWidth - rect.size.width;
            rect.size.width += diff;
            /** 最小值大于自身宽度 */
            if (rect.origin.x+rect.size.width > self.frame.size.width) {
                rect.size.width = self.frame.size.width - rect.origin.x;
            }
        }
    } else if (resizeControlView == self.centerCornerView) {
        if (rect.origin.x < 0.f){
            rect.origin.x = 0.f;
        } else if ((rect.origin.x+rect.size.width) > self.frame.size.width) {
            rect.origin.x = self.frame.size.width - rect.size.width;
        }
    }
    return rect;
}

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
    UIView *view = [super hitTest:point withEvent:event];
    if (self.leftCornerView == view) {
        self.rightCornerView.enabled = NO;
        self.centerCornerView.enabled = NO;
    } else if (self.rightCornerView == view) {
        self.leftCornerView.enabled = NO;
        self.centerCornerView.enabled = NO;
    } else if (self.centerCornerView == view) {
        self.leftCornerView.enabled = NO;
        self.rightCornerView.enabled = NO;
    }
    return view;
}

- (BOOL)pointInside:(CGPoint)point withEvent:(nullable UIEvent *)event
{
    BOOL isHit = [super pointInside:point withEvent:event];

    if (!isHit) {
        return (CGRectContainsPoint(self.leftCornerView.frame, point) || CGRectContainsPoint(self.rightCornerView.frame, point)) || CGRectContainsPoint(self.centerCornerView.frame, point);
    }

    return isHit;
}
@end


text:
@interface YWBusinessMemberViewController : UIViewController

@end