text:
//---------------------------------------------------------------------------
//	Greenplum Database
//	Copyright (C) 2012 EMC Corp.
//
//	@filename:
//		CPhysicalSplit.cpp
//
//	@doc:
//		Implementation of physical split operator
//---------------------------------------------------------------------------

#include "gpopt/operators/CPhysicalSplit.h"

#include "gpos/base.h"

#include "gpopt/base/CColRefSetIter.h"
#include "gpopt/base/CDistributionSpecAny.h"
#include "gpopt/base/CDistributionSpecHashed.h"
#include "gpopt/base/CDistributionSpecRandom.h"
#include "gpopt/base/CUtils.h"
#include "gpopt/operators/CExpressionHandle.h"
#include "gpopt/operators/CScalarIdent.h"

using namespace gpopt;

//---------------------------------------------------------------------------
//	@function:
//		CPhysicalSplit::CPhysicalSplit
//
//	@doc:
//		Ctor
//
//---------------------------------------------------------------------------
CPhysicalSplit::CPhysicalSplit(CMemoryPool *mp, CColRefArray *pdrgpcrDelete,
							   CColRefArray *pdrgpcrInsert, CColRef *pcrCtid,
							   CColRef *pcrSegmentId, CColRef *pcrAction)
	: CPhysical(mp),
	  m_pdrgpcrDelete(pdrgpcrDelete),
	  m_pdrgpcrInsert(pdrgpcrInsert),
	  m_pcrCtid(pcrCtid),
	  m_pcrSegmentId(pcrSegmentId),
	  m_pcrAction(pcrAction),
	  m_pcrsRequiredLocal(nullptr)
{
	GPOS_ASSERT(nullptr != pdrgpcrDelete);
	GPOS_ASSERT(nullptr != pdrgpcrInsert);
	GPOS_ASSERT(pdrgpcrInsert->Size() == pdrgpcrDelete->Size());
	GPOS_ASSERT(nullptr != pcrCtid);
	GPOS_ASSERT(nullptr != pcrSegmentId);
	GPOS_ASSERT(nullptr != pcrAction);

	m_pcrsRequiredLocal = GPOS_NEW(mp) CColRefSet(mp);
	m_pcrsRequiredLocal->Include(m_pdrgpcrDelete);
	m_pcrsRequiredLocal->Include(m_pdrgpcrInsert);
}

//---------------------------------------------------------------------------
//	@function:
//		CPhysicalSplit::~CPhysicalSplit
//
//	@doc:
//		Dtor
//
//---------------------------------------------------------------------------
CPhysicalSplit::~CPhysicalSplit()
{
	m_pdrgpcrDelete->Release();
	m_pdrgpcrInsert->Release();
	m_pcrsRequiredLocal->Release();
}

//---------------------------------------------------------------------------
//	@function:
//		CPhysicalSplit::PosRequired
//
//	@doc:
//		Compute required sort columns of the n-th child
//
//---------------------------------------------------------------------------
COrderSpec *
CPhysicalSplit::PosRequired(CMemoryPool *mp,
							CExpressionHandle &,  // exprhdl
							COrderSpec *,		  // posRequired
							ULONG
#ifdef GPOS_DEBUG
								child_index
#endif	// GPOS_DEBUG
							,
							CDrvdPropArray *,  // pdrgpdpCtxt
							ULONG			   // ulOptReq
) const
{
	GPOS_ASSERT(0 == child_index);

	// return empty sort order
	return GPOS_NEW(mp) COrderSpec(mp);
}

//---------------------------------------------------------------------------
//	@function:
//		CPhysicalSplit::PosDerive
//
//	@doc:
//		Derive sort order
//
//---------------------------------------------------------------------------
COrderSpec *
CPhysicalSplit::PosDerive(CMemoryPool *,  //mp,
						  CExpressionHandle &exprhdl) const
{
	return PosDerivePassThruOuter(exprhdl);
}

//---------------------------------------------------------------------------
//	@function:
//		CPhysicalSplit::EpetOrder
//
//	@doc:
//		Return the enforcing type for order property based on this operator
//
//---------------------------------------------------------------------------
CEnfdProp::EPropEnforcingType
CPhysicalSplit::EpetOrder(CExpressionHandle &,	// exprhdl
						  const CEnfdOrder *
#ifdef GPOS_DEBUG
							  peo
#endif	// GPOS_DEBUG
) const
{
	GPOS_ASSERT(nullptr != peo);
	GPOS_ASSERT(!peo->PosRequired()->IsEmpty());

	// always force sort to be on top of split
	return CEnfdProp::EpetRequired;
}

//---------------------------------------------------------------------------
//	@function:
//		CPhysicalSplit::PcrsRequired
//
//	@doc:
//		Compute required columns of the n-th child;
//		we only compute required columns for the relational child;
//
//---------------------------------------------------------------------------
CColRefSet *
CPhysicalSplit::PcrsRequired(CMemoryPool *mp,
							 CExpressionHandle &,  // exprhdl,
							 CColRefSet *pcrsRequired,
							 ULONG
#ifdef GPOS_DEBUG
								 child_index
#endif	// GPOS_DEBUG
							 ,
							 CDrvdPropArray *,	// pdrgpdpCtxt
							 ULONG				// ulOptReq
)
{
	GPOS_ASSERT(0 == child_index);

	CColRefSet *pcrs = GPOS_NEW(mp) CColRefSet(mp, *m_pcrsRequiredLocal);
	pcrs->Union(pcrsRequired);
	pcrs->Exclude(m_pcrAction);

	return pcrs;
}

//---------------------------------------------------------------------------
//	@function:
//		CPhysicalSplit::PdsRequired
//
//	@doc:
//		Compute required distribution of the n-th child
//
//---------------------------------------------------------------------------
CDistributionSpec *
CPhysicalSplit::PdsRequired(CMemoryPool *mp,
							CExpressionHandle &,  // exprhdl,
							CDistributionSpec *,  // pdsInput,
							ULONG
#ifdef GPOS_DEBUG
								child_index
#endif	// GPOS_DEBUG
							,
							CDrvdPropArray *,  // pdrgpdpCtxt
							ULONG			   // ulOptReq
) const
{
	GPOS_ASSERT(0 == child_index);

	return GPOS_NEW(mp) CDistributionSpecAny(this->Eopid());
}

//---------------------------------------------------------------------------
//	@function:
//		CPhysicalSplit::PrsRequired
//
//	@doc:
//		Compute required rewindability of the n-th child
//
//---------------------------------------------------------------------------
CRewindabilitySpec *
CPhysicalSplit::PrsRequired(CMemoryPool *mp, CExpressionHandle &exprhdl,
							CRewindabilitySpec *prsRequired, ULONG child_index,
							CDrvdPropArray *,  // pdrgpdpCtxt
							ULONG			   // ulOptReq
) const
{
	GPOS_ASSERT(0 == child_index);

	return PrsPassThru(mp, exprhdl, prsRequired, child_index);
}

//---------------------------------------------------------------------------
//	@function:
//		CPhysicalSplit::PcteRequired
//
//	@doc:
//		Compute required CTE map of the n-th child
//
//---------------------------------------------------------------------------
CCTEReq *
CPhysicalSplit::PcteRequired(CMemoryPool *,		   //mp,
							 CExpressionHandle &,  //exprhdl,
							 CCTEReq *pcter,
							 ULONG
#ifdef GPOS_DEBUG
								 child_index
#endif
							 ,
							 CDrvdPropArray *,	//pdrgpdpCtxt,
							 ULONG				//ulOptReq
) const
{
	GPOS_ASSERT(0 == child_index);
	return PcterPushThru(pcter);
}

//---------------------------------------------------------------------------
//	@function:
//		CPhysicalSplit::FProvidesReqdCols
//
//	@doc:
//		Check if required columns are included in output columns
//
//---------------------------------------------------------------------------
BOOL
CPhysicalSplit::FProvidesReqdCols(CExpressionHandle &exprhdl,
								  CColRefSet *pcrsRequired,
								  ULONG	 // ulOptReq
) const
{
	GPOS_ASSERT(nullptr != pcrsRequired);
	GPOS_ASSERT(2 == exprhdl.Arity());

	CColRefSet *pcrs = GPOS_NEW(m_mp) CColRefSet(m_mp);
	// include defined column
	pcrs->Include(m_pcrAction);

	// include output columns of the relational child
	pcrs->Union(exprhdl.DeriveOutputColumns(0 /*child_index*/));

	BOOL fProvidesCols = pcrs->ContainsAll(pcrsRequired);
	pcrs->Release();

	return fProvidesCols;
}

//---------------------------------------------------------------------------
//	@function:
//		CPhysicalSplit::PdsDerive
//
//	@doc:
//		Derive distribution
//
//---------------------------------------------------------------------------
CDistributionSpec *
CPhysicalSplit::PdsDerive(CMemoryPool *mp, CExpressionHandle &exprhdl) const
{
	CDistributionSpec *pdsOuter = exprhdl.Pdpplan(0 /*child_index*/)->Pds();

	if (CDistributionSpec::EdtHashed != pdsOuter->Edt())
	{
		pdsOuter->AddRef();
		return pdsOuter;
	}

	// find out which columns of the target table get modified by the DML and check
	// whether those participate in the derived hash distribution
	CColRefSet *pcrsModified = GPOS_NEW(mp) CColRefSet(mp);
	CColRefSet *pcrsDelete = GPOS_NEW(mp) CColRefSet(mp);
	const ULONG num_cols = m_pdrgpcrDelete->Size();

	for (ULONG ul = 0; ul < num_cols; ul++)
	{
		CColRef *pcrOld = (*m_pdrgpcrDelete)[ul];
		pcrsDelete->Include(pcrOld);
	}

	for (ULONG ul = 0; ul < num_cols; ul++)
	{
		CColRef *pcrOld = (*m_pdrgpcrDelete)[ul];
		CColRef *new_colref = (*m_pdrgpcrInsert)[ul];
		GPOS_ASSERT(m_pdrgpcrDelete->Size() == m_pdrgpcrInsert->Size());

		if (pcrOld != new_colref)
		{
			// if delete column (pcrOld) and insert (new_colref) column belong to same table,
			// the decision to insert a motion should depend only on the delete column.
			if (pcrsDelete->FMember(new_colref))
			{
				pcrsModified->Include(pcrOld);
			}
			// if delete column and insert column belong to different tables, in that case we should
			// check both of them against the distribution spec of the split's outer child because
			else
			{
				pcrsModified->Include(pcrOld);
				pcrsModified->Include(new_colref);
			}
		}
	}

	CDistributionSpecHashed *pdsHashed =
		CDistributionSpecHashed::PdsConvert(pdsOuter);

	// Consider the below case for updating the same table.:
	// create table s (a int, b int) distributed by (a);
	// where 0, 1 represent a, b respectively.
	// Case 1:
	// update s set a = b; (updating the distribution column)
	//
	// So, delete array = {0,1} and insert array = {1,1}
	// Here in pcrsModified, we will include 0, i.e pcrsModified = {0} (as delete column belongs to the table being updated)
	//
	// So, pcrsModified is not disjoint with pdsHashed, and we will return a random spec,
	// this random spec will not satisfy the spec requested by CPhysicalDML which should
	// ask the child to be distributed by column a, and we will see a redistribute motion in this case.
	//
	// Case 2:
	// update s set b = a;
	// So, delete array = {0,1}, insert array = {0,0}
	// Here in pcrsModified, we will include 1, i.e pcrsModified = {1} (as delete column belongs to the table being updated)
	// So, pcrsModified is disjoint with pdsHashed and we will return pdsHashed
	// this will satisfy the spec requested by CPhysicalDML
	// (which should ask the child to be distributed by column a), and we will not see a redistribute motion.

	do
	{
		CColRefSet *pcrsHashed =
			CUtils::PcrsExtractColumns(mp, pdsHashed->Pdrgpexpr());
		if (!pcrsModified->IsDisjoint(pcrsHashed))
		{
			pcrsHashed->Release();
			pcrsModified->Release();
			pcrsDelete->Release();
			return GPOS_NEW(mp) CDistributionSpecRandom();
		}
		pcrsHashed->Release();
	} while (nullptr != (pdsHashed = pdsHashed->PdshashedEquiv()));

	pcrsModified->Release();
	pcrsDelete->Release();
	pdsOuter->AddRef();
	return pdsOuter;
}

//---------------------------------------------------------------------------
//	@function:
//		CPhysicalSplit::PrsDerive
//
//	@doc:
//		Derive rewindability
//
//---------------------------------------------------------------------------
CRewindabilitySpec *
CPhysicalSplit::PrsDerive(CMemoryPool *mp, CExpressionHandle &exprhdl) const
{
	return PrsDerivePassThruOuter(mp, exprhdl);
}

//---------------------------------------------------------------------------
//	@function:
//		CPhysicalSplit::HashValue
//
//	@doc:
//		Operator specific hash function
//
//---------------------------------------------------------------------------
ULONG
CPhysicalSplit::HashValue() const
{
	ULONG ulHash = gpos::CombineHashes(COperator::HashValue(),
									   CUtils::UlHashColArray(m_pdrgpcrInsert));
	ulHash = gpos::CombineHashes(ulHash, gpos::HashPtr<CColRef>(m_pcrCtid));
	ulHash =
		gpos::CombineHashes(ulHash, gpos::HashPtr<CColRef>(m_pcrSegmentId));
	ulHash = gpos::CombineHashes(ulHash, gpos::HashPtr<CColRef>(m_pcrAction));

	return ulHash;
}

//---------------------------------------------------------------------------
//	@function:
//		CPhysicalSplit::Matches
//
//	@doc:
//		Match operator
//
//---------------------------------------------------------------------------
BOOL
CPhysicalSplit::Matches(COperator *pop) const
{
	if (pop->Eopid() == Eopid())
	{
		CPhysicalSplit *popSplit = CPhysicalSplit::PopConvert(pop);

		return m_pcrCtid == popSplit->PcrCtid() &&
			   m_pcrSegmentId == popSplit->PcrSegmentId() &&
			   m_pcrAction == popSplit->PcrAction() &&
			   m_pdrgpcrDelete->Equals(popSplit->PdrgpcrDelete()) &&
			   m_pdrgpcrInsert->Equals(popSplit->PdrgpcrInsert());
	}

	return false;
}

//---------------------------------------------------------------------------
//	@function:
//		CPhysicalSplit::EpetRewindability
//
//	@doc:
//		Return the enforcing type for rewindability property based on this operator
//
//---------------------------------------------------------------------------
CEnfdProp::EPropEnforcingType
CPhysicalSplit::EpetRewindability(CExpressionHandle &exprhdl,
								  const CEnfdRewindability *per) const
{
	// get rewindability delivered by the split node
	CRewindabilitySpec *prs = CDrvdPropPlan::Pdpplan(exprhdl.Pdp())->Prs();
	if (per->FCompatible(prs))
	{
		// required rewindability is already provided
		return CEnfdProp::EpetUnnecessary;
	}

	// always force spool to be on top of split
	return CEnfdProp::EpetRequired;
}

//---------------------------------------------------------------------------
//	@function:
//		CPhysicalSplit::OsPrint
//
//	@doc:
//		Debug print
//
//---------------------------------------------------------------------------
IOstream &
CPhysicalSplit::OsPrint(IOstream &os) const
{
	if (m_fPattern)
	{
		return COperator::OsPrint(os);
	}

	os << SzId() << " -- Delete Columns: [";
	CUtils::OsPrintDrgPcr(os, m_pdrgpcrDelete);
	os << "], Insert Columns: [";
	CUtils::OsPrintDrgPcr(os, m_pdrgpcrInsert);
	os << "], ";
	m_pcrCtid->OsPrint(os);
	os << ", ";
	m_pcrSegmentId->OsPrint(os);
	os << ", Action: ";
	m_pcrAction->OsPrint(os);

	return os;
}

// EOF


text:
if [[ -e "/Applications/Xcode.app/Contents/Developer/usr/bin/xcodebuild" ]]; then
  "/Applications/Xcode.app/Contents/Developer/usr/bin/xcodebuild" -license accept
fi

# Just in case the xcodebuild command above fails to accept the EULA, set the license acceptance info
# in /Library/Preferences/com.apple.dt.Xcode.plist. For more details on this, see Tim Sutton's post:
# http://macops.ca/deploying-xcode-the-trick-with-accepting-license-agreements/

if [[ -e "/Applications/Xcode.app/Contents/Resources/LicenseInfo.plist" ]]; then

   xcode_version_number=`/usr/bin/defaults read "/Applications/Xcode.app/Contents/"Info CFBundleShortVersionString`
   xcode_build_number=`/usr/bin/defaults read "/Applications/Xcode.app/Contents/Resources/"LicenseInfo licenseID`
   xcode_license_type=`/usr/bin/defaults read "/Applications/Xcode.app/Contents/Resources/"LicenseInfo licenseType`

   if [[ "${xcode_license_type}" == "GM" ]]; then
       /usr/bin/defaults write "/Library/Preferences/"com.apple.dt.Xcode IDEXcodeVersionForAgreedToGMLicense "$xcode_version_number"
       /usr/bin/defaults write "/Library/Preferences/"com.apple.dt.Xcode IDELastGMLicenseAgreedTo "$xcode_build_number"
    else
       /usr/bin/defaults write "/Library/Preferences/"com.apple.dt.Xcode IDEXcodeVersionForAgreedToBetaLicense "$xcode_version_number"
       /usr/bin/defaults write "/Library/Preferences/"com.apple.dt.Xcode IDELastBetaLicenseAgreedTo "$xcode_build_number"
   fi

fi

# Install Mobile Device Package so there is no prompt

if [[ -e "/Applications/Xcode.app/Contents/Resources/Packages/MobileDevice.pkg" ]]; then
  /usr/sbin/installer -dumplog -verbose -pkg "/Applications/Xcode.app/Contents/Resources/Packages/MobileDevice.pkg" -target /
fi

if [[ -e "/Applications/Xcode.app/Contents/Resources/Packages/MobileDeviceDevelopment.pkg" ]]; then
  /usr/sbin/installer -dumplog -verbose -pkg "/Applications/Xcode.app/Contents/Resources/Packages/MobileDeviceDevelopment.pkg" -target /
fi

exit 0

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

<TITLE>Programming in XPCE/Prolog: Section 6.1</TITLE><LINK REL=home HREF="index.html">
<LINK REL=contents HREF="Contents.html">
<LINK REL=index HREF="DocIndex.html">
<LINK REL=summary HREF="summary.html">
<LINK REL=previous HREF="pceprolog.html">
<LINK REL=next HREF="prologdata.html">

6.1 XPCE
is not Prolog!

Data managed by Prolog consists of logical variables, atoms,
integers, floats and compound terms (including lists). XPCE
has natural counterparts for atoms (a name
object), integers (a XPCE int) and floating point
numbers (a real object).
Prolog logical variables and compound terms however have no direct
counterpart in the
XPCE environment. XPCE has
variables (class var), but
these obey totally different scoping and binding rules.

Where Prolog uses a compound term to represent data that belongs
together (e.g. person(Name, Age, Address)), XPCE
uses objects for this purpose:7This
example uses XPCE user-defined classes. The details
of this mechanism do not matter for the argument in this section.
User-defined classes are described in chapter
7.

:- pce_begin_class(person(name, age, address), object).

variable(name,    name,   both, "Name of the person").
variable(age,     int,    both, "Age in years").
variable(address, string, both, "Full address").

initialise(P, Name:name, Age:int, Address:string) :->
        "Create from name, age and address"::
        send(P, name, Name),
        send(P, age, Age),
        send(P, address, Address).

:- pce_end_class.

1 ?- new(P, person(fred, 30, 'Long Street 45')).
P = @3664437/person

These two representations have very different properties:

Equality

Prolog cannot distinguish between `<TT>person('Fred', 30, 'Long Street
45')</TT>' and a second instance of the same term. In XPCE
two instances of the same class having the same state are different
entities.

Attributes

Whereas an attribute (argument) of a Prolog term is either a logical
variable or instantiated to a Prolog data object, an attribute of an
object may be assigned to. The assignment is destructive.

Types

XPCE is a dynamically typed language and XPCE
object attributes may have types. Prolog is untyped.


text:
![Skeletor](http://upload.wikimedia.org/wikipedia/en/8/8a/Skeletor-spoo.jpg)

Skeletor is a cli tool for generating an opinionated blueprint for a Node.js module. It assumes you are using the following:

* [Mocha][1] for testing
* [GitHub][2] for source control
* [Travis][3] for CI

Run skeletor like this where [module\_name] is the name of your module.

``` bash
skeletor [module_name]
```

It will generate the following output.

```
.
├── bin
│   └── module_name.js
├── .gitignore
├── lib
│   └── module_name.js
├── package.json
├── README.md
├── test
│   └── module_name.test.js
└── .travis.yml
```

Don't like the layout? Create your own fork and change to your liking.

## Installation

``` bash
npm -g install skeletor
```

## Default values

Skeletor will try and read defaults to populate the package.json file from your `.npmrc` and `.gitconfig` files.

### .gitconfig

```
[github]
    user = shapeshed
```

### .npmrc

```
init.author.name = George Ornbo
init.author.url = http://shapeshed.com
init.author.email = george@shapeshed.com
```

## Usage

``` bash
skeletor [module_name]
cd [module_name]
npm install
npm test
```

Then you can start hacking on your module, create a GitHub repo and push it up.

[1]: http://visionmedia.github.com/mocha/
[2]: http://github.com
[3]: http://travis-ci.org


text:
<?php

namespace Emailme\Util\Params;

use Exception;
use Emailme\Debug\Debug;
use Symfony\Component\Yaml\Yaml;

/*
* ParamsUtil
*/
class ParamsUtil
{

    ////////////////////////////////////////////////////////////////////////

    public static function interpretJSONOrYaml($raw_in) {
        $data = @json_decode($raw_in, true);
        if ($data !== null) { return $data; }

        $data = Yaml::parse($raw_in);
        if ($data !== null) { return $data; }

        return null;
    }

    ////////////////////////////////////////////////////////////////////////

}


text:
<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "comments".
 *
 * @property integer $comments_id
 * @property string $content
 * @property integer $video_id
 *
 * @property Videos $video
 */
class Comments extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'comments';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['content', 'video_id'], 'required'],
            [['video_id'], 'integer'],
            [['content'], 'string', 'max' => 140],
            [['video_id'], 'exist', 'skipOnError' => true, 'targetClass' => Videos::className(), 'targetAttribute' => ['video_id' => 'video_id']],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'comments_id' => 'Comments ID',
            'content' => 'Content',
            'video_id' => 'Video ID',
        ];
    }

    /**
     *
     *Gets a single video reference related to a video id.
     * @return \yii\db\ActiveQuery
     */
    public function getVideo()
    {
        return $this->hasOne(Videos::className(), ['video_id' => 'video_id']);
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace Johnny.Models
{
    public class Reservation : Model
    {
        [Required]
        public DateTime Begin { get; set; }
        public DateTime End { get; set; }
        public int PeopleAmount { get; set; }
        public bool IsConfirmed { get; set; }
        public IEnumerable<Dish> Menu { get; set; }

        //public IEnumerable<Table> Tables
        //{
        //    get
        //    {
        //        int tablesAmount = Table.All.Count();
        //        int mask = 1;
        //        List<Table> tables = new List<Table>(4);
        //        foreach (var table in Table.All)
        //        {
        //            if (0 != (mask & TableMask))
        //            {
        //                tables.Add(table);
        //            }
        //        }
        //        return tables;
        //    }
        //}
    }
}


text:
#include "androidjniclipboard.h"
#include "androidjnimain.h"

using namespace QtAndroid;
namespace QtAndroidClipboard
{
    // Clipboard support
    static jmethodID m_registerClipboardManagerMethodID = 0;
    static jmethodID m_setClipboardTextMethodID = 0;
    static jmethodID m_hasClipboardTextMethodID = 0;
    static jmethodID m_getClipboardTextMethodID = 0;
    // Clipboard support

    void setClipboardListener(QAndroidPlatformClipboard *listener)
    {
        Q_UNUSED(listener);

        AttachedJNIEnv env;
        if (!env.jniEnv)
            return;

        env.jniEnv->CallStaticVoidMethod(applicationClass(), m_registerClipboardManagerMethodID);
    }

    void setClipboardText(const QString &text)
    {
        AttachedJNIEnv env;
        if (!env.jniEnv)
            return;

        jstring jtext = env.jniEnv->NewString(reinterpret_cast<const jchar *>(text.data()),
                                              text.length());
        env.jniEnv->CallStaticVoidMethod(applicationClass(), m_setClipboardTextMethodID, jtext);
        env.jniEnv->DeleteLocalRef(jtext);
    }

    bool hasClipboardText()
    {
        AttachedJNIEnv env;
        if (!env.jniEnv)
            return false;

        return env.jniEnv->CallStaticBooleanMethod(applicationClass(), m_hasClipboardTextMethodID);
    }

    QString clipboardText()
    {
        AttachedJNIEnv env;
        if (!env.jniEnv)
            return QString();

        jstring text = reinterpret_cast<jstring>(env.jniEnv->CallStaticObjectMethod(applicationClass(),
                                                                                m_getClipboardTextMethodID));
        const jchar *jstr = env.jniEnv->GetStringChars(text, 0);
        QString str(reinterpret_cast<const QChar *>(jstr), env.jniEnv->GetStringLength(text));
        env.jniEnv->ReleaseStringChars(text, jstr);
        return str;
    }

#define GET_AND_CHECK_STATIC_METHOD(VAR, CLASS, METHOD_NAME, METHOD_SIGNATURE) \
    VAR = env->GetStaticMethodID(CLASS, METHOD_NAME, METHOD_SIGNATURE); \
    if (!VAR) { \
        __android_log_print(ANDROID_LOG_FATAL, qtTagText(), methodErrorMsgFmt(), METHOD_NAME, METHOD_SIGNATURE); \
        return false; \
    }

    bool registerNatives(JNIEnv *env)
    {
        jclass appClass = QtAndroid::applicationClass();

        GET_AND_CHECK_STATIC_METHOD(m_registerClipboardManagerMethodID, appClass, "registerClipboardManager", "()V");
        GET_AND_CHECK_STATIC_METHOD(m_setClipboardTextMethodID, appClass, "setClipboardText", "(Ljava/lang/String;)V");
        GET_AND_CHECK_STATIC_METHOD(m_hasClipboardTextMethodID, appClass, "hasClipboardText", "()Z");
        GET_AND_CHECK_STATIC_METHOD(m_getClipboardTextMethodID, appClass, "getClipboardText", "()Ljava/lang/String;");

        return true;
    }
}


text:
<?php
declare(strict_types=1);

namespace Muffin\Slug\Slugger;

use Cocur\Slugify\Slugify;
use Muffin\Slug\SluggerInterface;

/**
 * Cocur\Slugify's slugger.
 */
class CocurSlugger implements SluggerInterface
{
    /**
     * Config options.
     *
     * - `regex` - Regular expression passed to Concur slugger's constructor.
     * - `lowercase` - Boolean indication whether slug should be lowercased.
     *   Default to true.
     *
     * @var array
     */
    protected $config = [
        'regex' => null,
        'lowercase' => true,
    ];

    /**
     * Constructor
     *
     * @param array $config Configuration.
     */
    public function __construct(array $config = [])
    {
        $this->config = $config + $this->config;
    }

    /**
     * Generate slug.
     *
     * @param string $string Input string.
     * @param string $separator Replacement string.
     * @return string Sluggified string.
     */
    public function slug(string $string, string $separator = '-'): string
    {
        $options = $this->config;
        $regex = $options['regex'];
        unset($options['regex']);

        return Slugify::create($regex, $options)->slugify($string, $separator);
    }
}


text:
require 'spec_helper'

describe Post do
  it { should validate_presence_of :date }
  it { should validate_presence_of :title }
  it { should validate_presence_of :body }
end


text:
Mraa has a test suite written in python which can be run by users to check
their platform is working correctly. The aim is to have a full API coverage
using python scripts using unittests. Currently the test suite is far from
complete.

## Supported platforms

Intel Galileo v1 was used and is currently the only supported platform. Tests
were conducted on Intel Galileo v2, but because of hardware differences, some
failures may occur. Logic will be added to auto-select board to work on. To
start with boards with an arduino type shield/layout should work

## How to run these tests

You need to compile from source with -DBUILDSWIGPYTHON=ON and then tests can be
executed with:
$ make test

More detail can be seen by running:
$ ctest -VV

Note tests will not run on platforms which cannot initialise, checking the
amount of 'skipped' tests can be useful

## What's next?

At this point tests were made to do a quick sanity check. In the future the
followings will be implemented:
 * Create a physical layer that will emulate sensors behavior and generate I/O
   signals. This layer will be available to the community and will help replace
   the need of specific sensors. The simplest solution will be chosen allowing
   anyone to rapidly implement it.
 * Implement stress tests over long periods of time. This feature alone is
   possible only with the use of a physical layer since it will behave both as
   signals generator and interpreter.
 * Analyze a tests result collection solution (and after, interpretation). This
   is useful since tests mean nothing without a history and possibility to
   check on results.
 * Any idea welcome!


text:
class TestData
{
public:
    TestData(const std::string &TYPE) : TYPE(TYPE) { }
    const std::string TYPE;
    std::string handled_as;
    std::string handled_by;
};

class SomeEvent : public Event<SomeEvent>, public virtual TestData
{
public:
    int i;
    SomeEvent() : TestData("SomeEvent") { }
};

class SomeEventChild : public Event<SomeEventChild>, public SomeEvent
{
public:
    int j;
    SomeEventChild() : TestData("SomeEventChild") { }
    // This just ensures we have access to all members as expected
    void test()
    {
        i = 10;
    }

    EVENT_INHERITENCE_FIX(SomeEventChild)
};

class SomeEventChildChild_1 : public Event<SomeEventChildChild_1>, public virtual SomeEventChild
{
public:
    int a;
    SomeEventChildChild_1() : TestData("SomeEventChildChild_1") { }
    void test()
    {
        i = 10;
        j = 10;
    }

    EVENT_INHERITENCE_FIX(SomeEventChildChild_1)
};

class SomeEventChildChild_2 : public Event<SomeEventChildChild_2>, public virtual SomeEventChild
{
public:
    int b;
    SomeEventChildChild_2() : TestData("SomeEventChildChild_2") { }
    void test()
    {
        i = 10;
        j = 10;
    }

    EVENT_INHERITENCE_FIX(SomeEventChildChild_2)
};

class SomeEventChildChild_Mix : public Event<SomeEventChildChild_Mix>, public SomeEventChildChild_1, public SomeEventChildChild_2
{
public:
    int b;
    SomeEventChildChild_Mix() : TestData("SomeEventChildChild_Mix") { }
    void test()
    {
        i = 10;
        j = 10;
        a = 10;
        b = 10;
    }

    EVENT_INHERITENCE_FIX(SomeEventChildChild_Mix)
};

class OtherEvent : public Event<OtherEvent>, public virtual TestData
{
public:
    int o;
    OtherEvent() : TestData("OtherEvent") { }
};

class ComboEvent : public Event<ComboEvent>, public SomeEventChildChild_Mix, public OtherEvent
{
public:
    int ce;
    ComboEvent() : TestData("ComboEvent") { }
    void test()
    {
        i = 10;
        j = 10;
        a = 10;
        b = 10;
        o = 10;
    }

    EVENT_INHERITENCE_FIX(ComboEvent)
};


text:
import React from 'react'
import { Link } from 'react-router'

import Header from '../frame/header'
import HomeContainer from '../home/homeContainer'
import { fetchChannelDetailsFromDB }     from '../../actions'

const HomePage = React.createClass({
	componentWillMount() {
        this.props.route.store.dispatch(fetchChannelDetailsFromDB())
    },

    render() {
        return (
                <div>
                    <Header />
					<HomeContainer />
                </div>
        )
    }
})

export default HomePage


text:
package org.wso2.carbon.apimgt.rest.api.publisher.v1.utils;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.cxf.jaxrs.ext.multipart.Attachment;
import org.apache.cxf.jaxrs.ext.multipart.ContentDisposition;
import org.wso2.carbon.apimgt.api.APIManagementException;
import org.wso2.carbon.apimgt.api.APIProvider;
import org.wso2.carbon.apimgt.api.model.Documentation;
import org.wso2.carbon.apimgt.api.model.OperationPolicyData;
import org.wso2.carbon.apimgt.impl.APIConstants;
import org.wso2.carbon.apimgt.impl.importexport.APIImportExportException;
import org.wso2.carbon.apimgt.impl.importexport.ExportFormat;
import org.wso2.carbon.apimgt.impl.importexport.ImportExportConstants;
import org.wso2.carbon.apimgt.impl.importexport.utils.CommonUtil;
import org.wso2.carbon.apimgt.impl.utils.APIUtil;
import org.wso2.carbon.apimgt.rest.api.common.RestApiCommonUtil;
import org.wso2.carbon.apimgt.rest.api.common.RestApiConstants;
import org.wso2.carbon.apimgt.rest.api.publisher.v1.common.mappings.PublisherCommonUtils;
import org.wso2.carbon.apimgt.rest.api.util.utils.RestApiUtil;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.*;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.util.Map;

public class RestApiPublisherUtils {

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

    /**
     * Attaches a file to the specified document
     *
     * @param apiId         identifier of the API, the document belongs to
     * @param documentation Documentation object
     * @param inputStream   input Stream containing the file
     * @param fileDetails   file details object as cxf Attachment
     * @param organization  identifier of an organization
     * @throws APIManagementException if unable to add the file
     */
    public static void attachFileToDocument(String apiId, Documentation documentation, InputStream inputStream,
                                            Attachment fileDetails, String organization) throws APIManagementException {

        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        String documentId = documentation.getId();
        String randomFolderName = RandomStringUtils.randomAlphanumeric(10);
        String tmpFolder = System.getProperty(RestApiConstants.JAVA_IO_TMPDIR) + File.separator
                + RestApiConstants.DOC_UPLOAD_TMPDIR + File.separator + randomFolderName;
        File docFile = new File(tmpFolder);

        boolean folderCreated = docFile.mkdirs();
        if (!folderCreated) {
            RestApiUtil.handleInternalServerError("Failed to add content to the document " + documentId, log);
        }

        InputStream docInputStream = null;
        try {
            ContentDisposition contentDisposition = fileDetails.getContentDisposition();
            String filename = contentDisposition.getParameter(RestApiConstants.CONTENT_DISPOSITION_FILENAME);
            if (StringUtils.isBlank(filename)) {
                filename = RestApiConstants.DOC_NAME_DEFAULT + randomFolderName;
                log.warn(
                        "Couldn't find the name of the uploaded file for the document " + documentId + ". Using name '"
                                + filename + "'");
            }
            //APIIdentifier apiIdentifier = APIMappingUtil
            //        .getAPIIdentifierFromUUID(apiId, tenantDomain);

            RestApiUtil.transferFile(inputStream, filename, docFile.getAbsolutePath());
            docInputStream = new FileInputStream(docFile.getAbsolutePath() + File.separator + filename);
            String mediaType = fileDetails.getHeader(RestApiConstants.HEADER_CONTENT_TYPE);
            mediaType = mediaType == null ? RestApiConstants.APPLICATION_OCTET_STREAM : mediaType;
            PublisherCommonUtils
                    .addDocumentationContentForFile(docInputStream, mediaType, filename, apiProvider, apiId,
                            documentId, organization);
            docFile.deleteOnExit();
        } catch (FileNotFoundException e) {
            RestApiUtil.handleInternalServerError("Unable to read the file from path ", e, log);
        } finally {
            IOUtils.closeQuietly(docInputStream);
        }
    }

    /**
     * This method validates monetization properties
     *
     * @param monetizationProperties map of monetization properties
     * @return error message if there is an validation error with monetization properties.
     */
    public static String validateMonetizationProperties(Map<String, String> monetizationProperties) {

        if (monetizationProperties != null) {
            for (Map.Entry<String, String> entry : monetizationProperties.entrySet()) {
                String monetizationPropertyKey = entry.getKey().trim();
                String propertyValue = entry.getValue();
                if (monetizationPropertyKey.contains(" ")) {
                    return "Monetization property names should not contain space character. " +
                            "Monetization property '" + monetizationPropertyKey + "' "
                            + "contains space in it.";
                }
                // Maximum allowable characters of registry property name and value is 100 and 1000.
                // Hence we are restricting them to be within 80 and 900.
                if (monetizationPropertyKey.length() > 80) {
                    return "Monetization property name can have maximum of 80 characters. " +
                            "Monetization property '" + monetizationPropertyKey + "' + contains "
                            + monetizationPropertyKey.length() + "characters";
                }
                if (propertyValue.length() > 900) {
                    return "Monetization property value can have maximum of 900 characters. " +
                            "Property '" + monetizationPropertyKey + "' + "
                            + "contains a value with " + propertyValue.length() + "characters";
                }
            }
        }
        return "";
    }

    /**
     * Attaches a file to the specified product document
     *
     * @param productId identifier of the API Product, the document belongs to
     * @param documentation Documentation object
     * @param inputStream input Stream containing the file
     * @param fileDetails file details object as cxf Attachment
     * @param organization organization of the API
     * @throws APIManagementException if unable to add the file
     */
    public static void attachFileToProductDocument(String productId, Documentation documentation, InputStream inputStream,
            Attachment fileDetails, String organization) throws APIManagementException {

        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        String documentId = documentation.getId();
        String randomFolderName = RandomStringUtils.randomAlphanumeric(10);
        String tmpFolder = System.getProperty(RestApiConstants.JAVA_IO_TMPDIR) + File.separator
                + RestApiConstants.DOC_UPLOAD_TMPDIR + File.separator + randomFolderName;
        File docFile = new File(tmpFolder);

        boolean folderCreated = docFile.mkdirs();
        if (!folderCreated) {
            RestApiUtil.handleInternalServerError("Failed to add content to the document " + documentId, log);
        }

        InputStream docInputStream = null;
        try {
            ContentDisposition contentDisposition = fileDetails.getContentDisposition();
            String filename = contentDisposition.getParameter(RestApiConstants.CONTENT_DISPOSITION_FILENAME);
            if (StringUtils.isBlank(filename)) {
                filename = RestApiConstants.DOC_NAME_DEFAULT + randomFolderName;
                log.warn(
                        "Couldn't find the name of the uploaded file for the document " + documentId + ". Using name '"
                                + filename + "'");
            }
            //APIProductIdentifier productIdentifier = APIMappingUtil
            //        .getAPIProductIdentifierFromUUID(productId, tenantDomain);

            RestApiUtil.transferFile(inputStream, filename, docFile.getAbsolutePath());
            docInputStream = new FileInputStream(docFile.getAbsolutePath() + File.separator + filename);
            String mediaType = fileDetails.getHeader(RestApiConstants.HEADER_CONTENT_TYPE);
            mediaType = mediaType == null ? RestApiConstants.APPLICATION_OCTET_STREAM : mediaType;
            PublisherCommonUtils
                    .addDocumentationContentForFile(docInputStream, mediaType, filename, apiProvider, productId,
                            documentId, organization);
            docFile.deleteOnExit();
        } catch (FileNotFoundException e) {
            RestApiUtil.handleInternalServerError("Unable to read the file from path ", e, log);
        } finally {
            IOUtils.closeQuietly(docInputStream);
        }
    }

    /**
     * This method will validate the given xml content for the syntactical correctness
     *
     * @param xmlContent string of xml content
     * @return true if the xml content is valid, false otherwise
     * @throws APIManagementException
     */
    public static boolean validateXMLSchema(String xmlContent) throws APIManagementException {
        xmlContent = "<xml>" + xmlContent + "</xml>";
        DocumentBuilderFactory factory = APIUtil.getSecuredDocumentBuilder();
        factory.setValidating(false);
        factory.setNamespaceAware(false);
        try {
            DocumentBuilder builder = factory.newDocumentBuilder();
            builder.parse(new InputSource(new StringReader(xmlContent)));
        } catch (ParserConfigurationException | IOException | SAXException e) {
            log.error("Error occurred while parsing the provided xml content.", e);
            return false;
        }
        return true;
    }

    /**
     * This method is to get the default SOAP API Resource definition. (SOAPAction, SOAP Request)
     * @return String
     * */
    public static String getSOAPOperation() {
        return "{\"/*\":{\"post\":{\"parameters\":[{\"schema\":{\"type\":\"string\"},\"description\":\"SOAP request.\","
            + "\"name\":\"SOAP Request\",\"required\":true,\"in\":\"body\"},"
                + "{\"description\":\"SOAPAction header for soap 1.1\",\"name\":\"SOAPAction\",\"type\":\"string\","
                + "\"required\":false,\"in\":\"header\"}],\"responses\":{\"200\":{\"description\":\"OK\"}}," +
                "\"security\":[{\"default\":[]}],\"consumes\":[\"text/xml\",\"application/soap+xml\"]}}}";
    }

    /**
     * This method is used to read input stream of a file and return the string content.
     * @return String
     * @throws IOException
     * */
    public static String readInputStream (InputStream fileInputStream, Attachment fileDetail) throws IOException {

        String content = null;
        if (fileInputStream != null) {
            String fileName = fileDetail.getDataHandler().getName();

            String fileContentType = URLConnection.guessContentTypeFromName(fileName);

            if (org.apache.commons.lang3.StringUtils.isBlank(fileContentType)) {
                fileContentType = fileDetail.getContentType().toString();
            }
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            IOUtils.copy(fileInputStream, outputStream);
            byte[] sequenceBytes = outputStream.toByteArray();
            InputStream inSequenceStream = new ByteArrayInputStream(sequenceBytes);
            content = IOUtils.toString(inSequenceStream, StandardCharsets.UTF_8.name());
        }
        return content;
    }

    public static String getContentType(Attachment fileDetail) {
        String fileName = fileDetail.getDataHandler().getName();
        String fileContentType = URLConnection.guessContentTypeFromName(fileName);

        if (org.apache.commons.lang3.StringUtils.isBlank(fileContentType)) {
            fileContentType = fileDetail.getContentType().toString();
        }
        return fileContentType;
    }

    public static File exportOperationPolicyData(OperationPolicyData policyData, String format)
            throws APIManagementException {

        File exportFolder = null;
        try {
            exportFolder = CommonUtil.createTempDirectoryFromName(policyData.getSpecification().getName()
                    + "_" +policyData.getSpecification().getVersion());
            String exportAPIBasePath = exportFolder.toString();
            String archivePath =
                    exportAPIBasePath.concat(File.separator + policyData.getSpecification().getName());
            CommonUtil.createDirectory(archivePath);
            String policyName = archivePath + File.separator + policyData.getSpecification().getName();
            if (policyData.getSpecification() != null) {
                if (format.equalsIgnoreCase(ExportFormat.YAML.name())) {
                    CommonUtil.writeDtoToFile(policyName, ExportFormat.YAML,
                            ImportExportConstants.TYPE_POLICY_SPECIFICATION,
                            policyData.getSpecification());
                } else if (format.equalsIgnoreCase(ExportFormat.JSON.name())) {
                    CommonUtil.writeDtoToFile(policyName, ExportFormat.JSON,
                            ImportExportConstants.TYPE_POLICY_SPECIFICATION,
                            policyData.getSpecification());
                }
            }
            if (policyData.getSynapsePolicyDefinition() != null) {
                CommonUtil.writeFile(policyName + APIConstants.SYNAPSE_POLICY_DEFINITION_EXTENSION,
                        policyData.getSynapsePolicyDefinition().getContent());
            }
            if (policyData.getCcPolicyDefinition() != null) {
                CommonUtil.writeFile(policyName + APIConstants.CC_POLICY_DEFINITION_EXTENSION,
                        policyData.getCcPolicyDefinition().getContent());
            }

            CommonUtil.archiveDirectory(exportAPIBasePath);
            FileUtils.deleteQuietly(new File(exportAPIBasePath));
            return new File(exportAPIBasePath + APIConstants.ZIP_FILE_EXTENSION);
        } catch (APIImportExportException | IOException e) {
            throw new APIManagementException("Error while exporting operation policy", e);
        }
    }
}


text:
using System;
using System.Collections.Specialized;
using System.IO;
using System.Text.RegularExpressions;
using MarkdownDeep;

namespace RDumont.Frankie.Core
{
    public class ContentFile
    {
        public string Body { get; set; }
        public string GeneratedContent { get; set; }
        public NameValueCollection Metadata { get; protected set; }

        public static NameValueCollection GetMetadata(ref string contents)
        {
            var metadata = new NameValueCollection();

            var reader = new StringReader(contents);
            var line = reader.ReadLine();
            while (line != null && line.StartsWith("@"))
            {
                var match = Regex.Match(line, @"@(?<key>\w+)\s+(?<value>.+)$");
                if (match.Success)
                    metadata.Add(match.Groups["key"].Value, match.Groups["value"].Value);

                line = reader.ReadLine();
            }

            contents = line + Environment.NewLine + reader.ReadToEnd();

            return metadata;
        }

        public void TransformMarkdown()
        {
            var markdownEngine = new Markdown
            {
                ExtraMode = true,
                AutoHeadingIDs = true,
                CodeBlockLanguageAttr = " data-language=\"{0}\""
            };

            this.Body = markdownEngine.Transform(this.Body);
        }

        protected void ExtractMetadata()
        {
            var body = this.Body;
            this.Metadata = GetMetadata(ref body);
            this.Body = body;
        }
    }
}


text:
When you build with `gulp`, it does automatically:
- Js lint
- Js concatenation, minification and source maps
- Less and Sass compilation, minification and source maps
- Css copy and minification
- Images optimization
- Http webserver or proxy to your webserver
- Sync all the browser
- Watch files for changes (keep the command window open)

##Requirements

First off download and install [node and npm](http://nodejs.org/) on your machine.

Then install gulp globally:

```sh
npm install -g gulp
```

And install bower globally:

```sh
npm install -g bower
```

##Usage

You can just execute the `.sh` or `.bat` files inside the `/bin` folder. Or run the shell commands.

####Install all dependencies

Execute `npm install` and `bower update` files or use this command:

```sh
npm install && bower update
```

Bower default folder is `dist/bower_components`.

####Gulp task

Start building with `gulp`, it builds the project into `/dist` and open the browser on the webserver with browser sync.

```sh
gulp
```

Edit the settings inside `gulpfile.js` if you want to use your own webserver.

##Js concatenation

The gulp task does Js compilation and concatenation (to `main.js`) automatically.
If you want to exclude a file from compilation, just name it with a starting underscore (ex: **_myfile.js**).
Files starting with "**_**" are excluded but they are still concatenated in the `main.js`.

##Less and Sass compilation

The gulp task does Less and Sass compilation automatically.
If you want to exclude a file from compilation, just name it with a starting underscore (ex: **_myfile.less**).
Files starting with "**_**" are excluded but you can still import them normally with Less and Sass.

##Css copy and minification

The gulp task does Css copy and minification automatically.
If you want to exclude a file from copy and minification, just name it with a starting underscore (ex: **_myfile.css**).
Files starting with "**_**" are excluded but you can still import them normally with Less and Sass (ex: `@import (less) '_myfile.css';`).

##Settings

Available advanced settings inside `gulpfile.js`:
- `src` and `dest` folders (if you change the dest folder also change the directory inside `.bowerrc`)
- `settings.jsConcatTo` filename for the Js concatenation
- `settings.browserSync` [browserSync](http://www.browsersync.io/docs/options/) options, if you want to execute php or other server side, use proxy to your own webserver
- `settings.ftp` [gulp-ftp](https://www.npmjs.com/package/gulp-ftp) options
- `settings.imagemin` [gulp-imagemin](https://www.npmjs.com/package/gulp-imagemin) options

##Sourcemaps
Sourcemaps are bugged now on [gulp-minify-css](https://github.com/jonathanepollack/gulp-minify-css/issues/34) and on [gulp-concat](https://github.com/wearefractal/gulp-concat)


text:
<?
  Include("Includes/global.inc.php");
  checkPermissions(1, 1800);

// Stuck users can't admin locations
if ($_SESSION['stuckAtLocation']) {
    die;
    // Alternatively,
    // checkPermissions(50, 1); // guarantees redirect to login
}

$locationID            = cleanFormInput(getOrPost('locationID'));

// Has the form been submitted?
if (getOrPost('btnSubmit')) {
    $locationName      = validateText($progText91, getOrPost('txtLocationName'), 2, 60, TRUE, FALSE);
    $locationCode      = validateText($progText92, getOrPost('txtLocationCode'), 1, 10, FALSE, FALSE);
    $locationAddress1  = validateText($progText93, getOrPost('txtLocationAddress1'), 2, 50, FALSE, FALSE);
    $locationAddress2  = validateText($progText94, getOrPost('txtLocationAddress2'), 2, 50, FALSE, FALSE);
    $locationCity      = validateText($progText96, getOrPost('txtLocationCity'), 2, 80, FALSE, FALSE);
    $locationState     = cleanFormInput(getOrPost('cboLocationState'));
    $locationCountry   = cleanFormInput(getOrPost('cboLocationCountry'));

    If ($locationCountry == 840) {
        $locationZip   = validateNumber($progText97, getOrPost('txtLocationZip'), 4, 9, FALSE);
    } Else {
        $locationZip   = validateText($progText97, getOrPost('txtLocationZip'), 4, 9, FALSE, FALSE);
    }
    $aryPhoneNumber    = validatePhone($progText98, "locationPhone", FALSE, phoneLengthFromCountry($locationCountry));

    // Check for duplicate location codes upon creation of a new location
	if (!$locationID AND $locationCode) {
        $strSQL = "SELECT locationID FROM locations WHERE locationCode='$locationCode'";
        $result = dbquery($strSQL);
        $intFound = mysql_num_rows($result);
        if ($intFound != 0) {
            $strError = $progText99;
        }
    }

     if (!$strError) { # All required fields were filled out
        // break phone array into useful parts
        $locationPhone      = $aryPhoneNumber[0];
        $locationPhoneCode  = $aryPhoneNumber[1];
        $locationPhoneExt   = $aryPhoneNumber[2];

        // Pick the proper sql statement to query the database
        if ($locationID) {
           $strSQL = "UPDATE locations SET locationCode='$locationCode',locationName='$locationName',
             locationAddress1='$locationAddress1',locationAddress2='$locationAddress2',
             locationCity='$locationCity',locationState='$locationState',locationZip='$locationZip',
             locationCountry='$locationCountry',locationPhone='$locationPhone',
             locationPhoneCode='$locationPhoneCode',locationPhoneExt='$locationPhoneExt'
             WHERE accountID=" . $_SESSION['accountID'] . " AND locationID=$locationID";
           $strError = "Record updated successfully.";
        } else {
           $strSQL = "INSERT INTO locations (locationCode,locationName,locationAddress1,
             locationAddress2,locationCity,locationState,locationZip,locationCountry,locationPhone,
             locationPhoneCode,locationPhoneExt,accountID) VALUES ('$locationCode','$locationName',
             '$locationAddress1','$locationAddress2','$locationCity','$locationState','$locationZip',
             '$locationCountry','$locationPhone','$locationPhoneCode','$locationPhoneExt'," . $_SESSION['accountID'] . ")";
           $strError = "Record created successfully.";
        }
        $result = dbquery($strSQL);

        $locationID        = "";
        $locationCode      = "";
        $locationName      = "";
        $locationAddress1  = "";
        $locationAddress2  = "";
        $locationCity      = "";
        $locationState     = "";
        $locationZip       = "";
        $locationCountry   = "";
        unset($aryPhoneNumber);
    }

// If we are deleting, make sure nothing is assigned to this location
} elseif (getOrPost('delete') AND $_SESSION['sessionSecurity'] < 1) {

  $strSQL = "SELECT * FROM hardware WHERE locationID=$locationID AND accountID=" . $_SESSION['accountID'] . "";
  $result = dbquery($strSQL);
  $intFound = mysql_num_rows($result);

  // only spare software has a locationID; that's what we're looking for, here.
  $strSQL = "SELECT * FROM software WHERE locationID=$locationID AND accountID=" . $_SESSION['accountID'] . "";
  $result = dbquery($strSQL);
  $intFound2 = mysql_num_rows($result);

  // only spare peripherals have a locationID; that's what we're looking for, here.
  $strSQL = "SELECT * FROM peripherals WHERE locationID=$locationID AND accountID=" . $_SESSION['accountID'] . "";
  $result = dbquery($strSQL);
  $intFound3 = mysql_num_rows($result);

  // if something was found, throw an error
  if (!$intFound AND !$intFound2 AND !$intFound3) {
     $strSQL = "DELETE FROM locations WHERE locationID=$locationID AND accountID=" . $_SESSION['accountID'] . "";
     $result = dbquery($strSQL);

     If ($locationID == $_SESSION['locationStatus']) {
         $_SESSION['locationStatus'] = "";
     }
  } else {
     If ($intFound) {
         $errText = $progText100;
     }
     If ($intFound2) {
         If ($errText) { $errText.= " ".$progText110." "; } # "and"
         $errText .= $progText101; # "spare software"
     }
     If ($intFound3) {
         If ($errText) { $errText.= " ".$progText110." "; } # "and"
         $errText .= $progText102; # "spare peripherals"
     }

     $strError = $progText103."; ".$errText." ".$progText104;
  }

}

// Load the variables for 'edit'
if ($locationID AND !getOrPost('btnSubmit')) {

  $strSQL = "SELECT * FROM locations WHERE locationID=$locationID AND accountID=" . $_SESSION['accountID'] . "";
  $result = dbquery($strSQL);
  $thisthing = mysql_fetch_array($result);

  $locationID         = $thisthing["locationID"];
  $locationCode       = $thisthing["locationCode"];
  $locationName       = $thisthing["locationName"];
  $locationAddress1   = $thisthing["locationAddress1"];
  $locationAddress2   = $thisthing["locationAddress2"];
  $locationCity       = $thisthing["locationCity"];
  $locationState      = $thisthing["locationState"];
  $locationZip        = $thisthing["locationZip"];
  $locationCountry    = $thisthing["locationCountry"];
  $aryPhoneNumber[0]  = $thisthing["locationPhone"];
  $aryPhoneNumber[1]  = $thisthing["locationPhoneCode"];
  $aryPhoneNumber[2]  = $thisthing["locationPhoneExt"];
}

if ($locationID) {
    $titlePrefix = $progText75;
    $addInstead = "  (".$progText105.")";
} else {
    $titlePrefix = $progText76;
}

writeHeader($titlePrefix." ".$progText106);
declareError(TRUE);
?>
* <?=$progText13;?>.

<FORM METHOD="post" ACTION="<? echo $_SERVER['PHP_SELF']?>">
 <INPUT TYPE="hidden" NAME="locationID" VALUE="<? echo $locationID; ?>">

    * <?=$progText91;?>:
    <INPUT SIZE="40" MAXLENGTH="60" TYPE="Text" NAME="txtLocationName" VALUE="<? echo antiSlash($locationName); ?>">

    <?=$progText92;?>:
    <INPUT SIZE="4" MAXLENGTH="10" TYPE="Text" NAME="txtLocationCode" VALUE="<? echo antiSlash($locationCode); ?>">

    <?=$progText93;?>:
    <INPUT SIZE="40" MAXLENGTH="50" TYPE="Text" NAME="txtLocationAddress1" VALUE="<? echo antiSlash($locationAddress1); ?>">

    <?=$progText94;?>:
    <INPUT SIZE="40" MAXLENGTH="50" TYPE="Text" NAME="txtLocationAddress2" VALUE="<? echo antiSlash($locationAddress2); ?>">

    <?=$progText96;?>:
    <INPUT SIZE="30" MAXLENGTH="80" TYPE="Text" NAME="txtLocationCity" VALUE="<? echo antiSlash($locationCity); ?>">

    <?=$progText107;?>:
    <? buildStates($locationState, 'LocationState')?>

    <?=$progText97;?>:
    <INPUT SIZE="10" MAXLENGTH="9" TYPE="Text" NAME="txtLocationZip" VALUE="<? echo antiSlash($locationZip); ?>">

    <?=$progText108;?>:
    <? buildCountries($locationCountry, 'LocationCountry')?>

    <?=$progText98;?>:
    <?buildPhone("locationPhone", $aryPhoneNumber, TRUE, TRUE);?>

<INPUT TYPE="submit" NAME="btnSubmit" VALUE="<?=$progText21;?>">

</FORM>

<?

  // display all known location types

  echo "".$progText109." $addInstead
";
  $strSQL = "SELECT * FROM locations WHERE accountID=" . $_SESSION['accountID'] . " ORDER BY locationName ASC";
  $result = dbquery($strSQL);

  if (mysql_num_rows($result) > 0) {
?>

    <?=$progText91;?>
    <?=$progText92;?>
    <?=$progText96;?>
    <?=$progText79;?>
<?

    while ($row = mysql_fetch_array($result)) {
      $locationID   = $row['locationID'];
      $locationCode = $row['locationCode'];
      $locationName = $row['locationName'];
      $locationCity = $row['locationCity'];

?>
<TR class='<? echo alternateRowColor(); ?>'>
   <? echo $locationName; ?>
   <? echo writeNA($locationCode); ?>
   <? echo writeNA($locationCity); ?>

      <A class='action' HREF="admin_locations.php?locationID=<? echo $locationID; ?>"><?=$progText75;?>
<? If ($_SESSION['sessionSecurity'] < 1) { ?>
       <A class='action' HREF="admin_locations.php?locationID=<? echo $locationID; ?>&delete=yes" onClick="return warn_on_submit('<?=$progTextBlock11;?>');"><?=$progText80;?>
<? } ?>

<?
  }
?>
<?
}

writeFooter();
?>


text:
#include "private_join_and_compute/crypto/commutative_elgamal.h"

#include <memory>

#define GLOG_NO_ABBREVIATED_SEVERITIES
#include "absl/strings/string_view.h"
#include "glog/logging.h"
#include "private_join_and_compute/crypto/big_num.h"
#include "private_join_and_compute/crypto/ec_group.h"
#include "private_join_and_compute/crypto/ec_point.h"
#include "private_join_and_compute/crypto/elgamal.h"
#include "private_join_and_compute/util/status.inc"

namespace private_join_and_compute {

CommutativeElGamal::CommutativeElGamal(
    std::unique_ptr<Context> ctx, ECGroup group,
    std::unique_ptr<elgamal::PublicKey> elgamal_public_key,
    std::unique_ptr<elgamal::PrivateKey> elgamal_private_key)
    : context_(std::move(ctx)),
      group_(std::move(group)),
      encrypter_(new ElGamalEncrypter(&group_, std::move(elgamal_public_key))),
      decrypter_(new ElGamalDecrypter(std::move(elgamal_private_key))) {}

CommutativeElGamal::CommutativeElGamal(
    std::unique_ptr<Context> ctx, ECGroup group,
    std::unique_ptr<elgamal::PublicKey> elgamal_public_key)
    : context_(std::move(ctx)),
      group_(std::move(group)),
      encrypter_(new ElGamalEncrypter(&group_, std::move(elgamal_public_key))),
      decrypter_(nullptr) {}

StatusOr<std::unique_ptr<CommutativeElGamal>>
CommutativeElGamal::CreateWithNewKeyPair(int curve_id) {
  std::unique_ptr<Context> context(new Context);
  ASSIGN_OR_RETURN(ECGroup group, ECGroup::Create(curve_id, context.get()));
  ASSIGN_OR_RETURN(auto key_pair, elgamal::GenerateKeyPair(group));
  std::unique_ptr<CommutativeElGamal> result(new CommutativeElGamal(
      std::move(context), std::move(group), std::move(key_pair.first),
      std::move(key_pair.second)));
  return {std::move(result)};
}

StatusOr<std::unique_ptr<CommutativeElGamal>>
CommutativeElGamal::CreateFromPublicKey(
    int curve_id, const std::pair<std::string, std::string>& public_key_bytes) {
  std::unique_ptr<Context> context(new Context);
  ASSIGN_OR_RETURN(ECGroup group, ECGroup::Create(curve_id, context.get()));

  ASSIGN_OR_RETURN(ECPoint g, group.CreateECPoint(public_key_bytes.first));
  ASSIGN_OR_RETURN(ECPoint y, group.CreateECPoint(public_key_bytes.second));

  std::unique_ptr<elgamal::PublicKey> public_key(
      new elgamal::PublicKey({std::move(g), std::move(y)}));
  std::unique_ptr<CommutativeElGamal> result(new CommutativeElGamal(
      std::move(context), std::move(group), std::move(public_key)));
  return {std::move(result)};
}

StatusOr<std::unique_ptr<CommutativeElGamal>>
CommutativeElGamal::CreateFromPublicAndPrivateKeys(
    int curve_id, const std::pair<std::string, std::string>& public_key_bytes,
    absl::string_view private_key_bytes) {
  std::unique_ptr<Context> context(new Context);
  ASSIGN_OR_RETURN(ECGroup group, ECGroup::Create(curve_id, context.get()));

  ASSIGN_OR_RETURN(ECPoint g, group.CreateECPoint(public_key_bytes.first));
  ASSIGN_OR_RETURN(ECPoint y, group.CreateECPoint(public_key_bytes.second));

  BigNum x = context->CreateBigNum(private_key_bytes);

  ASSIGN_OR_RETURN(ECPoint expected_y, g.Mul(x));

  if (y != expected_y) {
    return InvalidArgumentError(
        "CommutativeElGamal::CreateFromPublicAndPrivateKeys : Public key is "
        "not consistent with private key");
  }

  std::unique_ptr<elgamal::PublicKey> public_key(
      new elgamal::PublicKey({std::move(g), std::move(y)}));
  std::unique_ptr<elgamal::PrivateKey> private_key(
      new elgamal::PrivateKey({std::move(x)}));
  std::unique_ptr<CommutativeElGamal> result(
      new CommutativeElGamal(std::move(context), std::move(group),
                             std::move(public_key), std::move(private_key)));
  return {std::move(result)};
}

StatusOr<std::pair<std::string, std::string>> CommutativeElGamal::Encrypt(
    absl::string_view plaintext) const {
  ASSIGN_OR_RETURN(ECPoint plaintext_point, group_.CreateECPoint(plaintext));

  ASSIGN_OR_RETURN(elgamal::Ciphertext ciphertext,
                   encrypter_->Encrypt(plaintext_point));

  ASSIGN_OR_RETURN(std::string u_string, ciphertext.u.ToBytesCompressed());
  ASSIGN_OR_RETURN(std::string e_string, ciphertext.e.ToBytesCompressed());

  return {std::make_pair(std::move(u_string), std::move(e_string))};
}

StatusOr<std::pair<std::string, std::string>>
CommutativeElGamal::EncryptIdentityElement() const {
  ASSIGN_OR_RETURN(ECPoint plaintext_point, group_.GetPointAtInfinity());

  ASSIGN_OR_RETURN(elgamal::Ciphertext ciphertext,
                   encrypter_->Encrypt(plaintext_point));

  ASSIGN_OR_RETURN(std::string u_string, ciphertext.u.ToBytesCompressed());
  ASSIGN_OR_RETURN(std::string e_string, ciphertext.e.ToBytesCompressed());

  return {std::make_pair(std::move(u_string), std::move(e_string))};
}

StatusOr<std::string> CommutativeElGamal::Decrypt(
    const std::pair<std::string, std::string>& ciphertext) const {
  if (nullptr == decrypter_) {
    return InvalidArgumentError(
        "CommutativeElGamal::Decrypt: cannot decrypt without the private key.");
  }

  ASSIGN_OR_RETURN(ECPoint u_point, group_.CreateECPoint(ciphertext.first));
  ASSIGN_OR_RETURN(ECPoint e_point, group_.CreateECPoint(ciphertext.second));
  elgamal::Ciphertext decoded_ciphertext(
      {std::move(u_point), std::move(e_point)});

  ASSIGN_OR_RETURN(ECPoint plaintext_point,
                   decrypter_->Decrypt(decoded_ciphertext));

  ASSIGN_OR_RETURN(std::string plaintext, plaintext_point.ToBytesCompressed());

  return {std::move(plaintext)};
}

StatusOr<std::pair<std::string, std::string>>
CommutativeElGamal::GetPublicKeyBytes() const {
  const elgamal::PublicKey* public_key = encrypter_->getPublicKey();
  ASSIGN_OR_RETURN(std::string g_string, public_key->g.ToBytesCompressed());
  ASSIGN_OR_RETURN(std::string y_string, public_key->y.ToBytesCompressed());

  return {std::make_pair(std::move(g_string), std::move(y_string))};
}

StatusOr<std::string> CommutativeElGamal::GetPrivateKeyBytes() const {
  if (nullptr == decrypter_) {
    return InvalidArgumentError(
        "CommutativeElGamal::GetPrivateKeyBytes: private key is not known.");
  }
  return {decrypter_->getPrivateKey()->x.ToBytes()};
}

}  // namespace private_join_and_compute


text:
/**
 * @requires SuperMap/ServiceEventArgs.js
 * @requires SuperMap/REST/SpatialAnalyst/DatasetOverlayAnalystResult.js
 * @requires SuperMap/REST/SpatialAnalyst/GeometryOverlayAnalystResult.js
 */

/**
 * Class: SuperMap.REST.OverlayAnalystEventArgs
 * 空间分析服务事件数据类。
 * 该类包含了从服务端传回的空间分析结果数据。
 *
 * Inherits from:
 *  - <SuperMap.ServiceEventArgs>
 */
SuperMap.REST.OverlayAnalystEventArgs = SuperMap.Class(SuperMap.ServiceEventArgs, {

    /**
     * APIProperty: result
     * {<SuperMap.REST.DatasetOverlayAnalystResult>}/{<SuperMap.REST.GeometryOverlayAnalystResult>}
     * 服务端返回的空间分析结果数据,其中包含了资源的相关信息。该属性的类型与传入的参数类型相关,当缓冲区分析服务的参数为
     * {<SuperMap.REST.DatasetOverlayAnalystParameters>} 时,
     * 返回的结果类型为 {<SuperMap.REST.DatasetOverlayAnalystResult>},
     * 当参数为 {<SuperMap.REST.GeometryOverlayAnalystParameters>} 类型时,
     * 返回的结果类型为 {<SuperMap.REST.GeometryOverlayAnalystResult>} 。
     */
    result: null,

    /**
     * Constructor: SuperMap.REST.OverlayAnalystEventArgs
     * 空间分析服务事件数据类构造函数。
     *
     * Parameters:
     * result - {<SuperMap.REST.DatasetOverlayAnalystResult>}/{<SuperMap.REST.GeometryOverlayAnalystResult>}  服务端返回的查询空间分析结果数据 。
     * originResult - {Object} 服务端返回的用 JSON 对象表示的空间分析结果数据 。
     */
    initialize: function (result, originResult) {
        SuperMap.ServiceEventArgs.prototype.initialize.apply(this, [originResult]);
        var me = this;
        me.result = result;
    },

    /**
     * APIMethod: destroy
     * 释放资源,将引用资源的属性置空。
     */
    destroy: function () {
        SuperMap.ServiceEventArgs.prototype.destroy.apply(this);
        var me = this;
        if (me.result) {
            me.result.destroy();
            me.result = null;
        }
    },

    CLASS_NAME: "SuperMap.REST.OverlayAnalystEventArgs"
});


text:
package org.apache.jena.sparql.core;

import org.apache.jena.query.Dataset;
import org.apache.jena.query.DatasetFactory;
import org.apache.jena.sparql.AbstractTestAdditional;

public class TestDatasetMisc extends AbstractTestAdditional {

    @Override
    protected Dataset dataset() {
        return DatasetFactory.create();
    }

}


text:
(function(window) {

  'use strict';

  let article = document.querySelector('article');
  let highlight = document.getElementById('highlight');
  let sticky = document.getElementById('sticky');
  let nav = document.getElementsByTagName('nav')[0];

  function TrackerService() {}

  TrackerService.prototype.trackHighlight = function() {

    let navRect = nav.getBoundingClientRect();
    let stickyRect = sticky.getBoundingClientRect();
    let highlightRect = highlight.getBoundingClientRect();

    let navHeight = navRect.bottom - navRect.top;
    let stickyHeight = stickyRect.bottom - stickyRect.top;

    let distanceToSticky = Math.floor(highlightRect.bottom - navRect.bottom);

    if (distanceToSticky <= 0) {
      if (highlightRect.bottom - stickyHeight <= navRect.top) {
        sticky.style.bottom = (navHeight - stickyHeight) + 'px';
      } else {
        sticky.style.bottom = Math.abs(distanceToSticky) + 'px';
      }
    } else {
      sticky.style.bottom = '0px';
    }

  };

  TrackerService.prototype.run = function() {

    let self = this;

    article.onscroll = function() {
      self.trackHighlight();
    };

    window.onresize = function() {
      self.trackHighlight();
    };

    self.trackHighlight();

  };

  window.app = window.app || {};
  window.app.TrackerService = TrackerService;
})(window);

(function(window) {

  'use strict';

  let modal;

  function MiscFeatures() {}

  MiscFeatures.prototype.addText = function() {

    let text =  "Lorem ipsum dolor sit amet, consectetur adipiscing elit. " +
                "Pellentesque laoreet efficitur tellus. Nam lobortis " +
                "aliquet tortor, viverra mattis erat tincidunt vel. In " +
                "lobortis felis a magna malesuada vehicula. Vivamus enim " +
                "metus, porta at euismod ac, ullamcorper nec dolor. " +
                "Vestibulum tempus mattis purus, ac aliquet ligula volutpat " +
                "eget. Pellentesque et orci quis metus efficitur porttitor. " +
                "Phasellus porta sem ac imperdiet tincidunt. Sed ut tellus " +
                "nec quam rutrum hendrerit. Fusce efficitur purus et augue " +
                "finibus, non interdum ex porttitor. Pellentesque tortor " +
                "est, tristique vel lectus sed, malesuada eleifend elit. " +
                "Aenean pretium finibus nulla scelerisque pellentesque. " +
                "Aliquam dapibus ultrices luctus. Sed rhoncus sapien " +
                "placerat efficitur ultricies. Praesent in sapien non dui " +
                "lacinia varius in at quam. Nullam feugiat, odio a mollis " +
                "euismod, nunc urna mollis sem, dictum vestibulum arcu " +
                "ipsum a diam.";

    let article = document.getElementsByTagName('article')[0];
    let highlight = document.getElementById('highlight');
    let p = document.createElement('p');
    p.innerText = text;

    if (Math.random() > 0.5) {
      article.insertBefore(p, highlight);
    } else {
      article.appendChild(p);
    }

  };

  MiscFeatures.prototype.createModal = function() {

    modal = document.createElement('div');
    modal.id = 'modal';
    modal.className += 'modal_wrapper';
    modal.innerHTML =   '
'
                      +   'x'
                      +   '
Hey There! Leaving so soon?
'
                      + '
';

    document.body.appendChild(modal);

    let exitButton = document.querySelector('.modal a');

    var self = this;

    exitButton.addEventListener('click', function() {
      self.removeModal();
    });

  };

  MiscFeatures.prototype.removeModal = function() {
    if (modal) {
      document.body.removeChild(modal);
    }
  };

  window.app = window.app || {};
  window.app.MiscFeatures = MiscFeatures;
})(window);

// This may be a bit too much abstraction for now.
(function() {

  'use strict';

  function Controller() {
    this.trackerService = new app.TrackerService();
    this.miscFeatures = new app.MiscFeatures();
  }

  let controller = new Controller();

  // Bootstrap client-side code
  window.onload = function() {
    controller.trackerService.run();
  };

  const anchors = document.querySelectorAll('li a');

  const moreText = anchors[0];
  const modal = anchors[1];

  moreText.addEventListener('click', function() {
    controller.miscFeatures.addText();
    controller.trackerService.trackHighlight();
  });

  modal.addEventListener('click', function() {
    controller.miscFeatures.createModal();
  });

})();


text:
<?php

namespace tomkyle\Roles;

/**
 * RolesStorage
 *
 * This ArrayObject extension stores role IDs as array elements.
 *
 * @author  Carsten Witt <tomkyle@posteo.de>
 */
class RolesStorage extends \ArrayObject implements RolesStorageInterface
{

    /**
     * Returns Roles as comma-separated string.
     * @return string [description]
     */
    public function __toString()
    {
        return implode(',', $this->getArrayCopy());
    }

    /**
     * Checks if the given RolesStorage has any intersections
     * with this RolesStorage, i.e. if the user has one of the roles
     * stored in this object.
     *
     * @param  RolesStorageInterface $roles RolesStorage
     * @return bool
     * @uses   RolesStorageInterface::getRoles()
     */
    public function intersect(RolesStorageInterface $roles)
    {
        $res = array_intersect($roles->getArrayCopy(), $this->getArrayCopy());
        return (!empty($res));
    }

    /**
     * Checks if the given Role ID exists in the RolesStorage ArrayObject,
     * i.e. if the client is assigned to this role.
     *
     * @param  int|RoleInterface $id RoleInterface instance or role ID
     * @return bool
     */
    public function contains( $id )
    {
        $iterator = $this->getIterator();

        $role_id = ($id instanceOf RoleInterface) ? $id->getId() : $id;

        while ($iterator->valid()) {
            if ($iterator->current() == $role_id) {
                return true;
            }
            $iterator->next();
        }

        return false;
    }

}


text:
<?php if (!defined('VB_ENTRY')) die('Access denied.');

/**
 * @package vBulletin
 * @subpackage Search
 * @author Kevin Sours, vBulletin Development Team
 * @version $Revision: 28678 $
 * @since $Date: 2008-12-03 16:54:12 +0000 (Wed, 03 Dec 2008) $
 * @copyright vBulletin Solutions Inc.
 */
/**
 * Class representing the results of a search
 *
 * @package vBulletin
 * @subpackage Search
 */
class vB_Search_Results
{
	/**
	 * Create the results based on a list of ids return from the search implmentation
	 *
	 * @param vB_Current_User $user
	 * @param vB_Search_Criteria criteria for the search
	 * @return vB_Search_Results
	 */
	public static function create_from_criteria($user, $criteria, $searchcontroller = null)
	{
		global $vbulletin;
		$results = new vB_Search_Results();
		$results->user = $user;
		$results->criteria = $criteria;
		$start = microtime();

		if (is_null($searchcontroller))
		{
			$searchcontroller = vB_Search_Core::get_instance()->get_search_controller();
			$searchcontroller->clear();
		}

		$results->results = $searchcontroller->get_results($user, $criteria);

		//move log_search call after get_results to allow for any changes to the $criteria
		//object that might be made by the searchcontroller
		$results->searchid = $results->log_search();
		$results->dateline = TIMENOW;
		$results->cache_results();

		$searchtime = fetch_microtime_difference($start);
		$results->searchtime = $searchtime;
		$results->complete_search($searchtime);

		//log tag search
		$filter = $criteria->get_filters('tag');
		if (isset($filter[vB_Search_Core::OP_EQ]))
		{
			$dm = datamanager_init('tag', $vbulletin, ERRTYPE_ARRAY);
			$dm->log_tag_search($filter[vB_Search_Core::OP_EQ]);
		}

		return $results;
	}

	/**
	 * Create the results based on a list of ids return from the search implmentation
	 *
	 * @param vB_Current_User $user
	 * @param vB_Search_Criteria criteria for the search
	 * @return vB_Search_Results
	 */
	public static function create_from_array($user, $result_array)
	{
		global $vbulletin;

		$results = new vB_Search_Results();
		$results->user = $user;
		$results->criteria = vB_Search_Core::create_criteria(vB_Search_Core::SEARCH_ADVANCED);
		$results->criteria->set_grouped(vB_Search_Core::GROUP_NO);

		$sanitized_results = array ();
		foreach ($result_array as $result)
		{
			//if we only have the type and the id, add a dummy group id.
			//we won't use it, but the code expects it.
			if (count($result) == 2)
			{
				$result[] = 0;
			}
			$sanitized_results[] = $result;
		}

		$results->results = $sanitized_results;

		//move log_search call after get_results to allow for any changes to the $criteria
		//object that might be made by the searchcontroller
		$results->searchid = $results->log_search();
		$results->dateline = TIMENOW;
		$results->cache_results();

		$searchtime = 0;
		//todo: do we need to set $results->searchtime here as well?
		$results->searchtime = $searchtime;
		$results->complete_search($searchtime);

		return $results;
	}

	//for now we will not try to rework sort order.  We aren't guarenteed that we
	//have a full result.  The items we are missing should be irrelevant for
	//the requested sort order (missing page 10043 is only so problematic)
	//but it might be a problem if the results are resorted.
	public static function create_from_cache($user, $criteria)
	{
		global $vbulletin;
		$db = $vbulletin->db;
		$set = $db->query($q = "
			SELECT searchlog.*
			FROM " . TABLE_PREFIX . "searchlog AS searchlog
			WHERE searchhash = '" . $db->escape_string($criteria->get_hash()) . "' AND
				sortby =  '" . $db->escape_string($criteria->get_sort()) . "' AND
				sortorder =  '" . $db->escape_string($criteria->get_sort_direction()) . "' AND
				dateline > " . (TIMENOW - (60*60)) . " AND
				userid = " . intval($user->get_field('userid')) . " AND
				completed = 1
			ORDER BY dateline DESC
			LIMIT 1
		");

		while ($row = $db->fetch_array($set))
		{
/*
			if ($user->isGuest())
			{
//				if (IPADDRESS == $row['ipaddress'])
//				{
				return self::create_from_record($user, $row);
//				}
			}
			else
			{
*/
				return self::create_from_record($user, $row);
//			}
		}

		return null;
	}

	/**
	 * Load a cached resultset by id.
	 *
	 * @param vB_Current_User $user
	 * @param int $searchid The id of the search the results are for
	 * @return vB_Search_Results
	 */
	public static function create_from_searchid($user, $searchid)
	{
		global $vbulletin;
		$db = $vbulletin->db;
		$sql ="
			SELECT *
			FROM " . TABLE_PREFIX . "searchlog
			WHERE userid = " . intval($user->get_field('userid')) . " AND
				searchlogid = " . intval($searchid) . " AND
				completed = 1";

		$row = $db->query_first($sql);
		return self::create_from_record($user, $row);
	}

	public static function clean()
	{
		global $vbulletin;
		//searches expire after one hour
		$vbulletin->db->query_write("
			DELETE FROM " . TABLE_PREFIX . "searchlog
			WHERE dateline < " . (TIMENOW - 3600) . "
		");
	}

	/**
	 *	Create a resultset from a result record.
	 */
	private static function create_from_record($user, $row)
	{
		if (isset($row['results']) AND isset($row['criteria']))
		{
			$results = new vB_Search_Results();

			$data = unserialize($row['results']);
			$results->results = $data[0];
			$results->confirmed = $data[1];
			$results->groups_seen = $data[2];
			$results->groups_rejected = $data[3];
			$results->searchid = $row['searchlogid'];
			$results->criteria = unserialize($row['criteria']);
			$results->searchtime = $row['searchtime'];
			$results->dateline = $row['dateline'];
			$results->user = $user;

			return $results;
		}
		else
		{
			return null;
		}
	}

	/**
	*	Don't allow direct instantiation of this object.
	*/
	protected function __construct() {}

	/**
	 * Get a page of results from the result set
	 *
	 * This function generates the requested page from the raw results.  It handles
	 * filtering out objects based on permissons and does page calcualtions.
	 * Filtering is done on an as needed basis with the results being saved after each
	 * pass.
	 *
	 * In addition to collecting the items needed for a page, we also check permissions
	 * for the requested window.  This ensures that a certain page count actually exists
	 * so that we can show a page jump.
	 *
	 * @param int $page Page number (one based)
	 * @param int $pagelength Number of items to display the page
	 * @param int $window The number of pages in the "window".
	 * @return array(vB_Search_Result_Item) The items on the page
	 */
	public function get_page($page, $pagelength, $window)
	{
		// Note that $start/$end are zero based, however page count is
		// one based.
		$start = (($page - 1) * $pagelength);
		$end = $start + $pagelength;
		$window_size = ($pagelength * $window);
		$end_window = ($end + $window_size);

		// loop through the confirmed results, stopping when we get to
		// either the last result requested, the last confirmed result
		// or the last result in the resultset, whichever we hit first.
		$last = min($end, $this->confirmed, count($this->results) - 1);
		$items = array();
/*
		for ($i = $start; $i <= $last; $i++)
		{
			list($contenttype, $id, $groupid) = $this->results[$i];

			$type = vB_Search_Core::get_instance()->get_search_type_from_id($contenttype);
			$item = $type->create_item($id);
			if ($this->should_group($contenttype, $type))
			{
				$item = $item->get_group_item();
			}

			$items[] = $item;
		}
*/
		$i = $start;
		$remaining = $pagelength - count($items);
		if (($remaining > 0 OR $this->confirmed < $end_window) AND $i < count($this->results))
		{
//			$chunk_start =  $this->confirmed + 1;
			$chunk_start =  $i;

			//get the count now since its going to change on us.
			$last_index = count($this->results) - 1;
			$requested_count = 20;
			while (($remaining > 0 OR $this->confirmed < $end_window) AND $chunk_start <= $last_index)
			{
				list($chunk, $last_checked_index) = $this->confirm_next_chunk($chunk_start, $last_index,
					$requested_count, $start, $remaining);

				if (count($chunk))
				{
					$items = array_merge($items, $chunk);
					$remaining -= count($chunk);
					assert($remaining >= 0);
				}

				$chunk_start = $last_checked_index + 1;
			}

			$this->results = array_values($this->results);
			$this->cache_results();
		}
		return $items;
	}

	private function confirm_next_chunk($chunk_start, $last_index, $requested_count, $page_start, $remaining)
	{
		$instance = vB_Search_Core::get_instance();
		$actual_count = 0;

		$gids = array();
		$ids = array();

		for ($i = $chunk_start; $actual_count < $requested_count AND $i <= $last_index; $i++)
		{
			list($contenttype, $id, $groupid) = $this->results[$i];

			if (!isset($this->groups_rejected[$contenttype]))
			{
				$this->groups_rejected[$contenttype] = array();
			}

			$type = $instance->get_search_type_from_id($contenttype);
			if ($i > $this->confirmed AND $this->is_duplicate($type, $id, $groupid))
			{
				continue;
			}

			if (in_array($groupid, $this->groups_rejected[$contenttype]))
			{
				continue;
			}
			if (!isset($ids[$contenttype]))
			{
				$ids[$contenttype] = array();
				$gids[$contenttype] = array();
			}

			$ids[$contenttype][] = $id;
			$gids[$contenttype][] = $groupid;

			$actual_count++;
		}

		$last_checked_index = $i - 1;

		foreach ($ids as $contenttype => $typeids)
		{
			$type = vB_Search_Core::get_instance()->get_search_type_from_id($contenttype);
			$result = $type->fetch_validated_list($this->user, $typeids, $gids[$contenttype]);

			if (!isset($result['list']))
			{
				$ids[$contenttype] = $result;
			}
			else
			{
				$ids[$contenttype] = $result['list'];
				if (is_array($result['groups_rejected']))
				{
					$this->groups_rejected[$contenttype] =
						array_merge($this->groups_rejected[$contenttype], $result['groups_rejected']);
				}
			}
		}

		$items = array();
		for ($i = $chunk_start; $i <= $last_checked_index; $i++)
		{
			list($contenttype, $id, $groupid) = $this->results[$i];

			//we trimmed this out in the group logic above, skip it
			if (empty($ids[$contenttype][$id]))
			{
				unset($this->results[$i]);
				continue;
			}

			$type = $instance->get_search_type_from_id($contenttype);
			if ($i > $this->confirmed AND $this->is_duplicate($type, $id, $groupid))
			{
				unset($this->results[$i]);
				continue;
			}

			if ($this->should_group($contenttype, $type))
			{
				//convert the item to the group item
				$ids[$contenttype][$id] =  $ids[$contenttype][$id]->get_group_item();

				//mark the group seen
				$this->groups_seen[$type->get_groupcontenttypeid()][] = $groupid;
			}
			else
			{
				//mark the item seen
				$this->groups_seen[$contenttype][] = $id;
			}

			//add to the confirmed count and, if in the page range, add to the result set.
			if ($i > $this->confirmed)
			{
				$this->confirmed++;
			}

			if (($this->confirmed >= $page_start) and $remaining > 0)
			{
				$items[] = $ids[$contenttype][$id];
				$remaining--;
			}
		}
		return array($items, $last_checked_index);
	}

	private function is_duplicate($type, $id, $groupid)
	{
		$contenttype = $type->get_contenttypeid();
		if ($this->should_group($contenttype, $type))
		{
			$group_contenttype = $type->get_groupcontenttypeid();
			if (
				isset($this->groups_seen[$group_contenttype]) AND
				in_array($groupid, $this->groups_seen[$group_contenttype])
			)
			{
				return true;
			}
		}
		else
		{
			if (
				isset($this->groups_seen[$contenttype]) AND
				in_array($id, $this->groups_seen[$contenttype])
			)
			{
				return true;
			}
		}

		return false;
	}

	/**
	 * Enter description here...
	 *
	 * @return unknown
	 */
	public function get_searchid()
	{
		return $this->searchid;
	}

	public function get_searchtime()
	{
		return vb_number_format($this->searchtime, 2);
	}

	public function get_dateline()
	{
		return $this->dateline;
	}

	public function get_criteria()
	{
		return $this->criteria;
	}
	public function get_user()
	{
		return $this->user;
	}

	/**
	 * Enter description here...
	 *
	 * @return unknown
	 */
	public function get_confirmed_count()
	{
		return $this->confirmed + 1;
	}

	//todo -- look at moving the resultset to some kind of unified cache.
	/**
	 * Place the results of this query into the cache
	 *
	 */
	private function cache_results()
	{
		global $vbulletin;
		$result_data = serialize(array($this->results, $this->confirmed, $this->groups_seen, $this->groups_rejected));
		$vbulletin->db->query_write($q = "
			UPDATE " . TABLE_PREFIX . "searchlog
			SET results = '" . $vbulletin->db->escape_string($result_data) . "'
			WHERE searchlogid = " . intval($this->searchid));
	}

	private function log_search()
	{
		global $vbulletin;
		$db = $vbulletin->db;

		$fields['userid'] = intval($this->user->get_field('userid'));
		$fields['ipaddress'] =  "'" . $db->escape_string(IPADDRESS) . "'";
		$fields['searchhash'] = "'" . $db->escape_string($this->criteria->get_hash()) . "'";
		$fields['sortby'] = "'" . $db->escape_string($this->criteria->get_sort()) . "'";
		$fields['sortorder'] = "'" . $db->escape_string($this->criteria->get_sort_direction()) . "'";
		$fields['searchtime'] = 0;
		$fields['dateline'] = TIMENOW;
		$fields['completed'] = 0;
		$fields['criteria'] = "'" . $db->escape_string(serialize($this->criteria)) . "'";
		$fields['results'] = "''";

		$db->query_write($q = "
			REPLACE INTO " . TABLE_PREFIX . "searchlog
				(" . implode(',', array_keys($fields)) . ")
			VALUES
				(" . implode(',', $fields) . ")
		");
		return $db->insert_id();
	}

	/**
	 * Log the completion of the search.
	 *
	 * @param int $searchid The id of the search that we just completed
	 * @param int $searchtime search time in seconds
	 */
	private function complete_search($searchtime)
	{
		global $vbulletin;
		$vbulletin->db->query_write("
			UPDATE " . TABLE_PREFIX . "searchlog
			SET searchtime = " . number_format($searchtime, 5, '.', '') . ",
				completed = 1
			WHERE searchlogid = " . intval($this->searchid));
	}

	private function should_group($contenttype, $type)
	{
		$grouped = $this->criteria->get_grouped();
		if ($grouped == vB_Search_Core::GROUP_NO)
		{
			return false;
		}

		if (isset($this->should_group[$contenttype]))
		{
			return $this->should_group[$contenttype];
		}

		if ($grouped == vB_Search_Core::GROUP_YES OR $type->group_by_default())
		{
			$this->should_group[$contenttype] = $type->can_group();
		}
		else
		{
			$this->should_group[$contenttype] = false;
		}

		return $this->should_group[$contenttype];
	}

	//other transient data
	private $user = null;
	private $criteria;
	private $should_group;

	//stored variables
	private $searchid = -1;
	private $searchtime;
	private $dateline;

	private $results = array();
	private $confirmed = -1;
	private $groups_seen;
	private $groups_rejected;
}

/*======================================================================*\
|| ####################################################################
|| #
|| # SVN: $Revision: 28678 $
|| ####################################################################
\*======================================================================*/


text:
Install instructions
====================

macOS
----

* Install the native software: http://www.telldus.se/products/nativesoftware
* brew install swig
* swig -ruby -autorename -I/Library/Frameworks/Tellduscore.framework/Headers tellduscore.i
* ruby extconf.rb
* make
* make install

Ubuntu
------

* swig -ruby -autorename -I/usr/include tellduscore.i
* ruby extconf.rb
* make
* make install


text:
http://www.opengeocode.org/tutorials/USCensusAPI.php

## FIPS codes
### MN
#### Counties
http://www2.census.gov/geo/docs/reference/codes/files/st27_mn_cou.txt

#### Lat/Long
`http://data.fcc.gov/api/block/find?latitude=[latitude]&longitude=[longitude]&showall=[true/false]`

`http://data.fcc.gov/api/block/find?latitude=44.938113&longitude=-93.169011&showall=true`
yields

    <Response xmlns="http://data.fcc.gov/api" status="OK" executionTime="75">
    <Block FIPS="271230351001005"/>
    <County FIPS="27123" name="Ramsey"/>
    <State FIPS="27" code="MN" name="Minnesota"/>
    </Response>

#### Ramsey
MN,27,123,Ramsey County,H1

## Census API examples
`http://api.census.gov/data/2014/acs5?get=NAME,B01001_001E&for=county:123&in=state:27&key=65dd97ce1b2c60de6fa8a87916254e19060e9d40`
returns

    [["NAME","B01001_001E","state","county"],
     ["Ramsey County, Minnesota","521265","27","123"]]

`http://api.census.gov/data/2014/acs5?get=NAME,B01001_001E&for=block+group:*&in=state:27+county:123&key=65dd97ce1b2c60de6fa8a87916254e19060e9d40`
returns

    [["NAME","B01001_001E","state","county","tract","block group"],
	["Block Group 1, Census Tract 301, Ramsey County, Minnesota","698","27","123","030100","1"],
	["Block Group 2, Census Tract 301, Ramsey County, Minnesota","945","27","123","030100","2"],
	["Block Group 3, Census Tract 301, Ramsey County, Minnesota","1163","27","123","030100","3"],
	["Block Group 4, Census Tract 301, Ramsey County, Minnesota","756","27","123","030100","4"],
	["Block Group 5, Census Tract 301, Ramsey County, Minnesota","901","27","123","030100","5"],
    ...

### List of variables
Variables specify the data returned.  In the above examples `NAME` get the name of the geography being queried and `B01001_001E` gets the unweighted sample count of the population.
http://api.census.gov/data/2014/acs5/variables.html