text:
package action

import (
	"github.com/idealeak/goserver/core/logger"
	"github.com/idealeak/goserver/core/netlib"
	"github.com/idealeak/goserver/srvlib"
	"github.com/idealeak/goserver/srvlib/protocol"
)

type PacketRedirectPacketFactory struct {
}

type PacketRedirectHandler struct {
}

func init() {
	netlib.RegisterHandler(int(protocol.SrvlibPacketID_PACKET_SS_REDIRECT), &PacketRedirectHandler{})
	netlib.RegisterFactory(int(protocol.SrvlibPacketID_PACKET_SS_REDIRECT), &PacketRedirectPacketFactory{})
}

func (this *PacketRedirectPacketFactory) CreatePacket() interface{} {
	pack := &protocol.SSPacketRedirect{}
	return pack
}

func (this *PacketRedirectHandler) Process(s *netlib.Session, packetid int, data interface{}) error {
	logger.Logger.Trace("PacketRedirectHandler.Process")
	if pr, ok := data.(*protocol.SSPacketRedirect); ok {
		packid, pack, err := netlib.UnmarshalPacket(pr.GetData())
		if err != nil {
			return err
		}
		h := srvlib.GetHandler(packid)
		if h != nil {
			return h.Process(s, packid, pack, pr.GetClientSid(), pr.GetSrvRoutes())
		} else {
			nh := netlib.GetHandler(packid)
			if nh != nil {
				return nh.Process(s, packid, pack)
			}
		}
	}
	return nil
}


text:
<?php

class   HTMLPurifier_ChildDef_StrictBlockquoteTest
extends HTMLPurifier_ChildDefHarness
{

    public function setUp()
    {
        parent::setUp();
        $this->obj = new HTMLPurifier_ChildDef_StrictBlockquote('div | p');
    }

    public function testEmptyInput()
    {
        $this->assertResult('');
    }

    public function testPreserveValidP()
    {
        $this->assertResult('
Valid
');
    }

    public function testPreserveValidDiv()
    {
        $this->assertResult('
Still valid
');
    }

    public function testWrapTextWithP()
    {
        $this->assertResult('Needs wrap', '
Needs wrap
');
    }

    public function testNoWrapForWhitespaceOrValidElements()
    {
        $this->assertResult('
Do not wrap

Whitespace
');
    }

    public function testWrapTextNextToValidElements()
    {
        $this->assertResult(
               'Wrap'. '
Do not wrap
',
            '
Wrap

Do not wrap
'
        );
    }

    public function testWrapInlineElements()
    {
        $this->assertResult(
            '
Do not
'.'Wrap',
            '
Do not

Wrap
'
        );
    }

    public function testWrapAndRemoveInvalidTags()
    {
        $this->assertResult(
            '
Not allowed
Paragraph.
Hmm.
',
            '
Not allowedParagraph.

Hmm.
'
        );
    }

    public function testWrapComplicatedSring()
    {
        $this->assertResult(
            $var = 'He said
perhaps
we should nuke them.',
            "
$var
"
        );
    }

    public function testWrapAndRemoveInvalidTagsComplex()
    {
        $this->assertResult(
            '<foo>Bar</foo><bas />PeopleConniving.'. '
Fools!
',
              '
Bar'.          'PeopleConniving.

Fools!
'
        );
    }

    public function testAlternateWrapper()
    {
        $this->config->set('HTML.BlockWrapper', 'div');
        $this->assertResult('Needs wrap', '
Needs wrap
');

    }

    public function testError()
    {
        $this->expectError('Cannot use non-block element as block wrapper');
        $this->obj = new HTMLPurifier_ChildDef_StrictBlockquote('div | p');
        $this->config->set('HTML.BlockWrapper', 'dav');
        $this->config->set('Cache.DefinitionImpl', null);
        $this->assertResult('Needs wrap', '
Needs wrap
');
    }

}

// vim: et sw=4 sts=4

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>
<html ng-app="nimble">

<head>
    <meta charset="utf-8">
    <title>nimble</title>

    <link rel="stylesheet" href="css/main.css"/>

    <script src="lib/jquery-2.1.0.js"></script>

    <script src="lib/angular.js"></script>
    <script src="lib/angular-animate.js"></script>
    <script src="lib/promise-tracker.js"></script>
    <script src="lib/angular-busy.js"></script>
    <link rel="stylesheet" href="lib/angular-busy.css"/>

    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.css">
    <script src="lib/ui-bootstrap-tpls-0.10.0.js"></script>

    <script src="lib/jquery-ui-1.10.4.custom.js"></script>
    <script src="lib/ui-sortable.js"></script>

    <script src="dist/nimble.js"></script>
</head>

<body>
    <ng-include src="'src/alert/system-alert.html'"></ng-include>
    <ng-include src="'src/header.html'"></ng-include>

    <div ng-controller="issuesController">
        <nimble-issues></nimble-issues>
    </div>
</body>

</html>


text:
from .models import *
from django.contrib import admin

class ServerAdmin(admin.ModelAdmin):
    list_display = ('title', 'host', 'port')

admin.site.register(Server, ServerAdmin)


text:
//---------------------------------------------------------------------------
// Includes
//---------------------------------------------------------------------------
#include "XnDeviceSensorProtocol.h"
#include "XnDeviceSensorIO.h"
#include "Uncomp.h"
#include "XnHostProtocol.h"
#include <XnLog.h>
#include <XnProfiling.h>
#include "XnStreamProcessor.h"
#include "XnSensor.h"
#include <XnOS.h>

FILE* g_fUSBDump;

//---------------------------------------------------------------------------
// Code
//---------------------------------------------------------------------------
XnBool XN_CALLBACK_TYPE XnDeviceSensorProtocolUsbEpCb(XnUChar* pBuffer, XnUInt32 nBufferSize, void* pCallbackData)
{
	XN_PROFILING_START_MT_SECTION("XnDeviceSensorProtocolUsbEpCb");

	XnUInt32 nReadBytes;
	XnUInt16 nMagic;

	XnSpecificUsbDevice* pDevice = (XnSpecificUsbDevice*)pCallbackData;
	XnDevicePrivateData* pDevicePrivateData = pDevice->pDevicePrivateData;
	XnUChar* pBufEnd = pBuffer + nBufferSize;

	XnSpecificUsbDeviceState* pCurrState = &pDevice->CurrState;

	while (pBuffer < pBufEnd)
	{
		switch (pCurrState->State)
		{
		case XN_WAITING_FOR_CONFIGURATION:
			pCurrState->State = XN_IGNORING_GARBAGE;
			pCurrState->nMissingBytesInState = pDevice->nIgnoreBytes;
			break;

		case XN_IGNORING_GARBAGE:
			// ignore first bytes on this endpoint. NOTE: due to a bug in the firmware, the first data received
			// on each endpoint is corrupt, causing wrong timestamp calculation, causing future (true) timestamps
			// to be calculated wrongly. By ignoring the first data received on each endpoint we hope to get
			// only valid data.
			nReadBytes = XN_MIN((XnUInt32)(pBufEnd - pBuffer), pCurrState->nMissingBytesInState);

			if (nReadBytes > 0)
			{
				xnLogVerbose(XN_MASK_SENSOR_PROTOCOL, "ignoring %d bytes - ignore garbage phase!", nReadBytes);
				pCurrState->nMissingBytesInState -= nReadBytes;
				pBuffer += nReadBytes;
			}

			if (pCurrState->nMissingBytesInState == 0)
			{
				pCurrState->State = XN_LOOKING_FOR_MAGIC;
				pCurrState->nMissingBytesInState = sizeof(XnUInt16);
			}
			break;

		case XN_LOOKING_FOR_MAGIC:
			nMagic = XN_PREPARE_VAR16_IN_BUFFER(pDevicePrivateData->FWInfo.nFWMagic);

			if (pCurrState->nMissingBytesInState == sizeof(XnUInt8) && // first byte already found
				pBuffer[0] == ((XnUInt8*)&nMagic)[1])	// we have here second byte
			{
				// move to next byte
				pBuffer++;

				// move to next state
				pCurrState->CurrHeader.nMagic = nMagic;
				pCurrState->State = XN_PACKET_HEADER;
				pCurrState->nMissingBytesInState = sizeof(XnSensorProtocolResponseHeader);
				break;
			}

			while (pBuffer < pBufEnd)
			{
				if ((pBuffer + sizeof(XnUInt16) <= pBufEnd) &&
					nMagic == *(XnUInt16*)(pBuffer))
				{
					pCurrState->CurrHeader.nMagic = nMagic;
					pCurrState->State = XN_PACKET_HEADER;
					pCurrState->nMissingBytesInState = sizeof(XnSensorProtocolResponseHeader);
					break;
				}
				else
				{
					pBuffer++;
				}
			}

			if (pBuffer == pBufEnd &&					// magic wasn't found
				pBuffer[-1] == ((XnUInt8*)&nMagic)[0])	// last byte in buffer is first in magic
			{
				// mark that we found first one
				pCurrState->nMissingBytesInState--;
			}

			break;

		case XN_PACKET_HEADER:
			nReadBytes = XN_MIN((XnUInt32)(pBufEnd - pBuffer), pCurrState->nMissingBytesInState);
			xnOSMemCopy((XnUChar*)&pCurrState->CurrHeader + sizeof(XnSensorProtocolResponseHeader) - pCurrState->nMissingBytesInState,
				pBuffer, nReadBytes);
			pCurrState->nMissingBytesInState -= nReadBytes;
			pBuffer += nReadBytes;

			if (pCurrState->nMissingBytesInState == 0)
			{
				// we have entire header. Fix it
				pCurrState->CurrHeader.nBufSize = XN_PREPARE_VAR16_IN_BUFFER(pCurrState->CurrHeader.nBufSize);
				pCurrState->CurrHeader.nMagic = XN_PREPARE_VAR16_IN_BUFFER(pCurrState->CurrHeader.nMagic);
				XnUInt16 packetID = pDevicePrivateData->HWInfo.isKinect?(pCurrState->CurrHeader.nPacketID >> 8):pCurrState->CurrHeader.nPacketID;
				pCurrState->CurrHeader.nPacketID = XN_PREPARE_VAR16_IN_BUFFER(packetID);
				pCurrState->CurrHeader.nTimeStamp = XN_PREPARE_VAR32_IN_BUFFER(pCurrState->CurrHeader.nTimeStamp);
				pCurrState->CurrHeader.nType = XN_PREPARE_VAR16_IN_BUFFER(pCurrState->CurrHeader.nType);
				pCurrState->CurrHeader.nBufSize = xnOSEndianSwapUINT16(pCurrState->CurrHeader.nBufSize);
				pCurrState->CurrHeader.nBufSize -= sizeof(XnSensorProtocolResponseHeader);

				pCurrState->State = XN_PACKET_DATA;
				pCurrState->nMissingBytesInState = pCurrState->CurrHeader.nBufSize;
			}
			break;

		case XN_PACKET_DATA:
			nReadBytes = XN_MIN((XnUInt32)(pBufEnd - pBuffer), pCurrState->nMissingBytesInState);
			pDevicePrivateData->pSensor->GetFirmware()->GetStreams()->ProcessPacketChunk(&pCurrState->CurrHeader, pBuffer, pCurrState->CurrHeader.nBufSize - pCurrState->nMissingBytesInState, nReadBytes);
			pBuffer += nReadBytes;
			pCurrState->nMissingBytesInState -= nReadBytes;

			if (pCurrState->nMissingBytesInState == 0)
			{
				pCurrState->State = XN_LOOKING_FOR_MAGIC;
				pCurrState->nMissingBytesInState = sizeof(XnUInt16);
			}
			break;
		}
	}

	XN_PROFILING_END_SECTION;

	return TRUE;
}

XnStatus XnDeviceSensorProtocolFindStreamOfType(XnDevicePrivateData* pDevicePrivateData, const XnChar* strType, const XnChar** ppStreamName)
{
	XnStatus nRetVal = XN_STATUS_OK;

	const XnChar* strNames[100];
	XnUInt32 nCount = 100;

	nRetVal = pDevicePrivateData->pSensor->GetStreamNames(strNames, &nCount);
	XN_IS_STATUS_OK(nRetVal);

	for (XnUInt32 i = 0; i < nCount; ++i)
	{
		XnChar strCurType[XN_DEVICE_MAX_STRING_LENGTH];
		nRetVal = pDevicePrivateData->pSensor->GetProperty(strNames[i], XN_STREAM_PROPERTY_TYPE, strCurType);
		XN_IS_STATUS_OK(nRetVal);

		if (strcmp(strType, strCurType) == 0)
		{
			*ppStreamName = strNames[i];
			return (XN_STATUS_OK);
		}
	}

	*ppStreamName = NULL;
	return (XN_STATUS_NO_MATCH);
}


text:
package org.mule.example.bookstore;

import org.mule.api.lifecycle.Initialisable;
import org.mule.api.lifecycle.InitialisationException;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.jws.WebService;

/**
 * Bookstore catalog service which implements both the public interface for
 * browsing the catalog and the admin interface for adding books to the catalog.
 *
 * @see CatalogService
 * @see CatalogAdminService
 */
@WebService(serviceName="CatalogService", endpointInterface="org.mule.example.bookstore.CatalogService")
public class CatalogServiceImpl implements CatalogService, CatalogAdminService, Initialisable
{
    /** Simple hashmap used to store the catalog, in real life this would be a database */
    private Map <Long, Book> books = new HashMap <Long, Book> ();

    public void initialise() throws InitialisationException
    {
        books = new HashMap <Long, Book> ();

        // Add some initial test data
        addBook(new Book("J.R.R. Tolkien", "The Fellowship of the Ring", 8));
        addBook(new Book("J.R.R. Tolkien", "The Two Towers", 10));
        addBook(new Book("J.R.R. Tolkien", "The Return of the King", 10));
        addBook(new Book("C.S. Lewis", "The Lion, the Witch and the Wardrobe", 6));
        addBook(new Book("C.S. Lewis", "Prince Caspian", 8));
        addBook(new Book("C.S. Lewis", "The Voyage of the Dawn Treader", 6));
        addBook(new Book("Leo Tolstoy", "War and Peace", 8));
        addBook(new Book("Leo Tolstoy", "Anna Karenina", 6));
        addBook(new Book("Henry David Thoreau", "Walden", 8));
        addBook(new Book("Harriet Beecher Stowe", "Uncle Tom's Cabin", 6));
        addBook(new Book("George Orwell", "1984", 8));
        addBook(new Book("George Orwell", "Animal Farm", 8));
        addBook(new Book("Aldous Huxley", "Brave New World", 8));

    }

    public long addBook(Book book)
    {
        System.out.println("Adding book " + book.getTitle());
        long id = books.size() + 1;
        book.setId(id);
        books.put(id, book);
        return id;
    }

    public Collection <Long> addBooks(Collection<Book> booksToAdd)
    {
        List <Long> ids = new ArrayList <Long> ();
        if (booksToAdd != null)
        {
            for (Book book : booksToAdd)
            {
                ids.add(addBook(book));
            }
        }
        return ids;
    }

    public Collection <Book> getBooks()
    {
        return books.values();
    }

    public Book getBook(long bookId)
    {
        return books.get(bookId);
    }
}


text:
package com.rust.year2018.test0209;

import java.math.BigInteger;
import java.util.HashSet;
import java.util.Set;

/**
 * @author Rust
 */
public class BigIntegerTest {

    public static void main(String[] args) {
        //RADIX.toStr(123);
        char[] chars = s.toCharArray();

        BigInteger base = BigInteger.valueOf(61);
        BigInteger num = BigInteger.valueOf(1235);
        StringBuilder stringBuilder = new StringBuilder();

        for (BigInteger val=num;;){
            BigInteger i = val.mod(base);
            char c = chars[i.intValueExact()];
            stringBuilder.insert(0, c);
            if (val.compareTo(base) < 0) {
                break;
            }
            val = val.subtract(i).divide(base);
        }
        System.out.println(stringBuilder.toString());

        //BigInteger base = BigInteger.valueOf(62);
        //
        //BigInteger i = val.mod(base);
        //
        //System.out.println(i);

    }

    public static final String s = "123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    public static final BigIntegerTest RADIX = new BigIntegerTest(s);
    private BigInteger bigInteger;
    char[] radixChars;

    public BigIntegerTest(String s) {
        this(s.toCharArray());
    }

    public BigIntegerTest(char[] chars) {
        Set<Character> characterSet = new HashSet<>();
        for (char aChar : chars) {
            characterSet.add(aChar);
        }
        this.radixChars = chars;
        this.bigInteger = BigInteger.valueOf(chars.length);
    }

    public String toStr(int num) {
        return toStr(BigInteger.valueOf(num));
    }

    public String toStr(BigInteger num) {
        String ret = "";

        for (BigInteger val = num; ; ) {
            BigInteger i = val.mod(bigInteger);
            char c = getChar(i.intValue());

            ret = c + ret;

            if (val.compareTo(bigInteger) < 0) {
                break;
            }

            val = val.subtract(i).divide(bigInteger);
        }

        return ret;
    }

    private char getChar(int i) {
        return radixChars[i];
    }

}


text:
<?php

use yii\helpers\Html;

echo Html::a('<i class="fa fa-plus"></i> '. Yii::t('SpaceModule.widgets_views_inviteButton', 'Invite'), $space->createUrl('/space/membership/invite'), array('class' => 'btn btn-primary', 'data-target' => '#globalModal'));


text:
package org.apache.isis.core.metamodel.facets.properties.property.regex;

import java.util.Map;
import java.util.regex.Pattern;

import com.google.common.base.Strings;

import org.apache.isis.applib.annotation.Property;
import org.apache.isis.core.metamodel.facetapi.FacetHolder;
import org.apache.isis.core.metamodel.facets.Annotations;
import org.apache.isis.core.metamodel.facets.objectvalue.regex.RegExFacet;
import org.apache.isis.core.metamodel.facets.objectvalue.regex.RegExFacetAbstract;

public class RegExFacetForPropertyAnnotation extends RegExFacetAbstract {

    private final Pattern pattern;

    public static RegExFacet create(
            final Property annotation,
            final Class<?> returnType,
            final FacetHolder holder) {

        if (annotation == null) {
            return null;
        }

        if (!Annotations.isString(returnType)) {
            return null;
        }

        final String pattern = annotation.regexPattern();
        if(Strings.isNullOrEmpty(pattern)) {
            return null;
        }

        final String replacement = annotation.regexPatternReplacement();
        final int patternFlags = annotation.regexPatternFlags();

        return new RegExFacetForPropertyAnnotation(pattern, patternFlags, holder, replacement);
    }

    private RegExFacetForPropertyAnnotation(final String pattern, final int patternFlags, final FacetHolder holder, final String replacement) {
        super(pattern, "", (patternFlags & Pattern.CASE_INSENSITIVE) == Pattern.CASE_INSENSITIVE, holder, replacement);
        this.pattern = Pattern.compile(pattern, patternFlags);
    }

    /**
     * Unused (for the TitledFacet)
     */
    @Override
    public String format(String text) {
        return text;
    }

    @Override
    public boolean doesNotMatch(final String text) {
        if (text == null) {
            return true;
        }
        return !pattern.matcher(text).matches();
    }

    @Override public void appendAttributesTo(final Map<String, Object> attributeMap) {
        super.appendAttributesTo(attributeMap);
        attributeMap.put("pattern", pattern);
    }

}


text:
@interface ObjectCreator : NSObject

- (void)addEarth:(CC3Scene*)scene;

@end


text:
/*
This file is part of WebNES.

WebNES is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

WebNES is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with WebNES.  If not, see <http://www.gnu.org/licenses/>.
*/

this.Gui = this.Gui || {};

(function(){
	"use strict";

	var gamepad_consts = {
		top1:	0, // Top button 1 ("A" on the Xbox 360 controller; cross on the PS3 controller)
		top2:	1, // Top button 2 ("B" on the Xbox 360 controller; circle on the PS3 controller)
		bottom3: 2, // gp_face3	Top button 3 ("X" on the Xbox 360 controller; square on the PS3 controller)
		bottom4: 3, // gp_face4	Top button 4 ("Y" on the Xbox 360 controller; triangle on the PS3 controller)
		shoulderLeft:	4, // gp_shoulderlb	Left shoulder button (digital)
		shoulderRight: 5, // gp_shoulderrb	Right shoulder button (digital)
		shoulderLeftTrigger:	6, // gp_shoulderl	Left shoulder trigger (analogue)
		shoulderRightTrigger:	7, // gp_shoulderr	Right shoulder trigger (analogue)
		select: 8, // gp_select	The select button on PlayStation 3 and the back button on Xbox 360
		start: 9, // gp_start	The start button
		leftStickButton: 10, // gp_stickl	The left stick pressed (as a button)
		rightStickButton: 11, // gp_stickr	The right stick pressed (as a button)
		dpadUp: 12, // gp_padu	D-pad up (digital)
		dpadDown:	13, // gp_padd	D-pad down (digital)
		dpadLeft:	14, // gp_padl	D-pad left (digital)
		dpadRight: 15, // gp_padr	D-pad right (digital)
		leftStickHoriz: 0, // gp_axislh	Left stick horizontal axis (analogue)
		leftStickVert: 1, // gp_axislv	Left stick vertical axis (analogue)
		rightStickHoriz: 2, // gp_axisrh	Right stick horizontal axis (analogue)
		rightStickVert: 3 // gp_axisrv	Right stick vertical axis (analogue)
	};

	var GamePad = function( rawPad ) {

		this._axisThreshold = 0.5;
		this._buttonStates = new Int32Array( rawPad['buttons'].length );
		this._axesStates = new Int32Array( rawPad['axes'].length );
	};

	GamePad.prototype.getButtonCount = function() {
		return this._buttonStates.length;
	};

	// Returns 0 for not changed, 1 for pressed, 2 for not pressed
	GamePad.prototype.getButtonState = function( rawPad, buttonIndex ) {

		var isPressed = rawPad['buttons'][ buttonIndex ]['pressed'];
		var intState = ( isPressed ? 1 : 0 );
		if ( this._buttonStates[ buttonIndex ] !== intState ) {
			this._buttonStates[ buttonIndex ] = intState;
			return isPressed ? 1 : 2;
		}
		return 0;
	};

	GamePad.prototype.getAxisCount = function() {
		return this._axesStates.length;
	};

	// Returns 0 for not changed, 1 for pressed, 2 for not pressed
	GamePad.prototype.getAxisState = function( rawPad, axisIndex ) {

		var isPressed = rawPad['axes'][ axisIndex ] >= this._axisThreshold || rawPad['axes'][ axisIndex ] <= -this._axisThreshold;
		var intState = ( isPressed ? 1 : 0 );
		if ( this._axesStates[ axisIndex ] !== intState ) {
			this._axesStates[ axisIndex ] = intState;
			return isPressed ? 1 : 2;
		}
		return 0;
	};

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

	var Input = function( mainboard ) {

		this._mainboard = mainboard;
		this._pads = [];

		this._loadKeyBindingsFromLocalStorage();

		// these values are guessed - need testing
		this._gamepadButtonMap = {
			'UP': [ gamepad_consts.dpadUp ],
			'DOWN': [ gamepad_consts.dpadDown ],
			'LEFT': [ gamepad_consts.dpadLeft ],
			'RIGHT': [ gamepad_consts.dpadRight ],
			'A': [ gamepad_consts.top1, gamepad_consts.top2, gamepad_consts.shoulderLeft ],
			'B': [ gamepad_consts.bottom3, gamepad_consts.bottom4, gamepad_consts.shoulderRight ],
			'SELECT': [ gamepad_consts.select ],
			'START': [ gamepad_consts.start ]
		};

		this._gamepadAxisMap = {
			'UP': [ { axis: gamepad_consts.leftStickVert, type: 'positive' }, { axis: gamepad_consts.rightStickVert, type: 'positive' } ],
			'DOWN': [ { axis: gamepad_consts.leftStickVert, type: 'negative' }, { axis: gamepad_consts.rightStickVert, type: 'negative' } ],
			'LEFT': [ { axis: gamepad_consts.leftStickHoriz, type: 'negative' }, { axis: gamepad_consts.rightStickHoriz, type: 'negative' } ],
			'RIGHT': [ { axis: gamepad_consts.leftStickHoriz, type: 'positive' }, { axis: gamepad_consts.rightStickHoriz, type: 'positive' } ],
			'A': [ { axis: gamepad_consts.shoulderLeftTrigger, type: 'positive' } ],
			'B': [ { axis: gamepad_consts.shoulderRightTrigger, type: 'positive' } ]
		};

		var that = this;

		// keyboard support
		window.addEventListener( 'keydown', function( event ) { if ( that._doKeyboardButtonPress( Number( event.keyCode ), true ) ) { event.preventDefault(); } }, false );
		window.addEventListener( 'keyup', function( event ) { if ( that._doKeyboardButtonPress( Number( event.keyCode ), false ) ) { event.preventDefault(); } }, false );

		this._gamepadsSupported = navigator['getGamepads'] !== undefined;

		if ( this._gamepadsSupported ) {
			this._populateGamepads();

			$( window ).on( "gamepadconnected", function() { that._populateGamepads(); } );
			$( window ).on( "gamepaddisconnected", function() { that._populateGamepads(); } );
		}
	};

	Input.prototype._populateGamepads = function() {

		this._pads.length = 0;
		if ( this._gamepadsSupported ) {
			var gamepads = navigator['getGamepads']();
			for (var i = 0; i < gamepads.length; ++i) {
				if ( gamepads[i] ) {
					var pad = gamepads[i];
					this._pads.push( new GamePad( pad ) );
				}
			}
		}
	};

	Input.prototype.poll = function() {

		if ( this._gamepadsSupported ) {
			this._pollGamepads();
		}
	};

	Input.prototype._pollGamepads = function() {

		var pads = navigator['getGamepads']();
		for ( var i=0; i<this._pads.length; ++i ) {
			var pad = this._pads[i];

			// do buttons
			for ( var buttonIndex=0; buttonIndex<pad.getButtonCount(); ++buttonIndex ) {
				var buttonState = pad.getButtonState( pads[ i ], buttonIndex );
				if ( buttonState > 0 ) {
					//console.log( "Pressed button " + buttonIndex );
					this._doGamepadButton( i, buttonIndex, buttonState === 1 );
				}
			}

			// do axes
			for ( var axisIndex=0; axisIndex<pad.getAxisCount(); ++axisIndex ) {
				var axisState = pad.getAxisState( pads[ i ], axisIndex );
				if ( axisState > 0 ) {
//					this._doGamepadAxis( i, axisIndex, axisState === 1, pads[ i ].axes[ axisIndex ] > 0 ? 'positive' : 'negative' );
				}
			}
		}
	};

	Input.prototype._doGamepadAxis = function( gamepadIndex, axisIndex, isPressed, axisType ) {

		var joypad = this._mainboard.inputdevicebus.getJoypad( gamepadIndex );

		if ( joypad ) {
			for ( var buttonName in this._gamepadButtonMap ) {
				if ( this._gamepadButtonMap.hasOwnProperty( buttonName ) ) {

					var buttonArray = this._gamepadButtonMap[ buttonName ];
					for ( var i=0; i<buttonArray.length; ++i ) {

						var but = buttonArray[ i ];
						if ( but.axis === axisIndex && but.type === axisType ) {
							joypad.pressButton( Number( JOYPAD_NAME_TO_ID( buttonName ) ), isPressed );
						}
					}
				}
			}
		}
	};

	Input.prototype._doGamepadButton = function( gamepadIndex, buttonIndex, isPressed ) {

		var joypad = this._mainboard.inputdevicebus.getJoypad( gamepadIndex );

		if ( joypad ) {
			for ( var buttonName in this._gamepadButtonMap ) {
				if ( this._gamepadButtonMap.hasOwnProperty( buttonName ) ) {
					var buttonArray = this._gamepadButtonMap[ buttonName ];
					for ( var i=0; i<buttonArray.length; ++i ) {
						if ( buttonIndex === buttonArray[ i ] ) {
							joypad.pressButton( Number( JOYPAD_NAME_TO_ID( buttonName ) ), isPressed );
						}
					}
				}
			}
		}
	};

	Input.prototype._doKeyboardButtonPress = function( keyCode, pressed ) {

		var len = Math.min( 2, this._playerKeyboardMaps.length );
		var wasPressed = false;

		for ( var playerIndex = 0; playerIndex < len; ++playerIndex ) {

			var joypad = this._mainboard.inputdevicebus.getJoypad( playerIndex );
			var map = this._playerKeyboardMaps[ playerIndex ];

			if ( map && joypad ) {
				for ( var buttonIndex=0; buttonIndex<map.length; ++buttonIndex ) {
					var buttonArray = map[ buttonIndex ];
					for ( var i=0; i<buttonArray.length; ++i ) {
						if ( buttonArray[ i ] === keyCode ) {
							joypad.pressButton( buttonIndex, pressed );
							wasPressed = true;
						}
					}
				}
			}
		}
		return wasPressed;
	};

	Input.prototype.saveKeyBindings = function( playerId, key, keysAssigned ) {

		this._playerKeyboardMaps[ playerId ][ key ] = keysAssigned.slice( 0 );
		this._saveKeyBindingsToLocalStorage();
	};

	Input.prototype.getKeyBindings = function( playerId, key ) {

		return this._playerKeyboardMaps[ playerId ][ key ].slice( 0 );
	};

	Input.prototype._loadKeyBindingsFromLocalStorage = function() {
		this._playerKeyboardMaps = Gui.loadFromLocalStorage( "webnes_keybindings" );

		// Load defaults if no local storage found
		if ( !this._playerKeyboardMaps ) {
			this._playerKeyboardMaps = [
				[
					// defaults for player 1
					[ 90 ], // Z // var JOYPAD_A = 0;
					[ 88 ], // X // var JOYPAD_B = 1;
					[ 16, 160, 161, 67 ], // shift, left shift, right shift, C // var JOYPAD_SELECT = 2;
					[ 13, 32, 86 ], // enter, space, V // var JOYPAD_START = 3;
					[ 38, 87, 104 ], // up, W, numpad 8 // var JOYPAD_UP = 4;
					[ 40, 83, 101, 98 ], // down, S, numpad 5, numpad 2 // var JOYPAD_DOWN = 5;
					[ 37, 65, 100 ], // left, A, numpad 4 // var JOYPAD_LEFT = 6;
					[ 39, 68, 102 ] // right, D, numpad 6 // var JOYPAD_RIGHT = 7;
				],
				[
					[],
					[],
					[],
					[],
					[],
					[],
					[],
					[]
				],
				[
					[],
					[],
					[],
					[],
					[],
					[],
					[],
					[]
				],
				[
					[],
					[],
					[],
					[],
					[],
					[],
					[],
					[]
				]
			];
		}
	};

	Input.prototype._saveKeyBindingsToLocalStorage = function() {
		Gui.saveToLocalStorage( "webnes_keybindings", this._playerKeyboardMaps );
	};

	Gui.Input = Input;

}());


text:
using namespace nadam;

namespace {

TEST(NadamMessageInfoTest, Create) {
	MessageInfo mi{"foo", 42, true};
	ASSERT_EQ(42, mi.maxSize);
	ASSERT_TRUE(mi.isVariableSize);
}

TEST(NadamMessageInfoTest, FixedSizeIsDefault) {
	MessageInfo mi{"foo", 42};
	ASSERT_FALSE(mi.isVariableSize);
}

TEST(NadamMessageInfoTest, SizeIdentifiersAreAliases) {
	MessageInfo mi{"foo", 42};
	ASSERT_EQ(42, mi.size);
	ASSERT_EQ(42, mi.maxSize);
}

TEST(NadamMessageInfoTest, ConstructHash) {
	MessageInfo mi{"foo", 0x5a, true};

	uint8_t expectedInput[] = {'f', 'o', 'o', 1, 0x0, 0x0, 0x0, 0x5a};

	util::digest::SHA1 sha;
	ASSERT_EQ(sha.digest(expectedInput, sizeof(expectedInput)), mi.hash);
}

} // namespace


text:
/// Copyright (c) 2012 Ecma International.  All rights reserved.
/// Ecma International makes this code available under the terms and conditions set
/// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
/// "Use Terms").   Any redistribution of this code must retain the above
/// copyright and this notice and otherwise comply with the Use Terms.
/**
 * @path ch15/15.3/15.3.5/15.3.5.4/15.3.5.4_2-9gs.js
 * @description Strict mode - checking access to non-strict function caller from strict function (New'ed Function constructor defined within strict mode)
 * @onlyStrict
 * @negative TypeError
 */

"use strict";
var f = new Function("return gNonStrict();");
f();

function gNonStrict() {
    return gNonStrict.caller;
}


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

namespace _1AverageStudentGrades
{
    class AverageStudentGrades
    {
        static void Main(string[] args)
        {
            var n = int.Parse(Console.ReadLine());
            var grades = new Dictionary<string, List<double>>();

            for (int i = 0; i < n; i++)
            {
                var tokens = Console.ReadLine().Split(' ');
                var name = tokens[0];
                var grade = double.Parse(tokens[1]);

                if (!grades.ContainsKey(name))
                {
                    grades[name] = new List<double>();
                }
                grades[name].Add(grade);
            }
            foreach (var nameAndGrades in grades)
            {
                Console.WriteLine("{0} -> {1} (avg: {2:f2})",
                    nameAndGrades.Key,
                    string.Join(" ", nameAndGrades.Value.Select(p => string.Format("{0:f2}", p))), // formula sprqmo p
                    nameAndGrades.Value.Average());
            }

        }
    }
}


text:
layout: page
title: "Vivian Liao"
comments: true
description: "blanks"
keywords: "Vivian Liao,CU,Boulder"
---
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://dl.dropboxusercontent.com/s/pc42nxpaw1ea4o9/highcharts.js?dl=0"></script>
<!-- <script src="../assets/js/highcharts.js"></script> -->
<style type="text/css">@font-face {
	font-family: "Bebas Neue";
	src: url(https://www.filehosting.org/file/details/544349/BebasNeue Regular.otf) format("opentype");
	}
	h1.Bebas {
		font-family: "Bebas Neue", Verdana, Tahoma;
	}
</style>
</head>

#### TEACHING INFORMATION

**College**: College of Arts and Sciences

**Classes taught**: ENGL 2051

#### ENGL 2051: INTRO FICTION WORKSHOP

**Terms taught**: Fall 2006, Spring 2007, Fall 2007, Spring 2008

**Instructor rating**: 5.41

**Standard deviation in instructor rating**: 0.18

**Average grade** (4.0 scale): 3.41

**Standard deviation in grades** (4.0 scale): 0.07

**Average workload** (raw): 2.58

**Standard deviation in workload** (raw): 0.27


text:
Imports YamlDotNet.Serialization
Imports System.IO

Public Class YAMLplanetSchematics
    Inherits YAMLFilesBase

    Public Const planetSchematicsFile As String = "planetSchematics.yaml"

    Public Sub New(ByVal YAMLFileName As String, ByVal YAMLFilePath As String, ByRef DatabaseRef As Object, ByRef TranslationRef As YAMLTranslations)
        MyBase.New(YAMLFileName, YAMLFilePath, DatabaseRef, TranslationRef)
    End Sub

    ''' <summary>
    ''' Imports the yaml file into the database set in the constructor
    ''' </summary>
    ''' <param name="Params">What the row location is and whether to insert the data or not (for bulk import)</param>
    Public Sub ImportFile(ByVal Params As ImportParameters)
        Dim DSB = New DeserializerBuilder()
        If Not TestForSDEChanges Then
            DSB.IgnoreUnmatchedProperties()
        End If
        DSB = DSB.WithNamingConvention(NamingConventions.NullNamingConvention.instance)
        Dim DS As New Deserializer
        DS = DSB.Build

        Dim YAMLRecords As New Dictionary(Of Long, planetSchematic)
        Dim DataFields As List(Of DBField)
        Dim DataFields2 As List(Of DBField)
        Dim DataFields3 As List(Of DBField)
        Dim SQL As String = ""
        Dim Count As Long = 0
        Dim TotalRecords As Long = 0

        Dim planetSchematicsTypeMapTable As String = "planetSchematicsTypeMap"
        Dim planetSchematicsPinMapTable As String = "planetSchematicsPinMap"

        Dim NameTranslation As New ImportLanguage(Params.ImportLanguageCode)

        ' Build table - planetSchematics
        Dim Table As New List(Of DBTableField)
        Table.Add(New DBTableField("schematicID", FieldType.smallint_type, 0, False, True))
        Table.Add(New DBTableField("schematicName", FieldType.nvarchar_type, 255, True))
        Table.Add(New DBTableField("cycleTime", FieldType.int_type, 0, True))

        Call UpdateDB.CreateTable(TableName, Table)

        ' Build table - planetSchematicsPinMap
        Table = New List(Of DBTableField)
        Table.Add(New DBTableField("schematicID", FieldType.smallint_type, 0, True))
        Table.Add(New DBTableField("pinTypeID", FieldType.int_type, 0, True))

        Call UpdateDB.CreateTable(planetSchematicsPinMaptable, Table)

        ' Build table - planetSchematicsTypeMap
        Table = New List(Of DBTableField)
        Table.Add(New DBTableField("schematicID", FieldType.smallint_type, 0, True))
        Table.Add(New DBTableField("typeID", FieldType.int_type, 0, True))
        Table.Add(New DBTableField("quantity", FieldType.smallint_type, 0, True))
        Table.Add(New DBTableField("isInput", FieldType.bit_type, 0, True))

        Call UpdateDB.CreateTable(planetSchematicsTypeMapTable, Table)

        ' See if we only want to build the table and indexes
        If Not Params.InsertRecords Then
            Exit Sub
        End If

        ' Start processing
        Call InitGridRow(Params.RowLocation)

        Try
            ' Parse the input text
            YAMLRecords = DS.Deserialize(Of Dictionary(Of Long, planetSchematic))(New StringReader(File.ReadAllText(YAMLFile)))
        Catch ex As Exception
            Call ShowErrorMessage(ex)
        End Try

        TotalRecords = YAMLRecords.Count

        ' Process Data
        For Each DataField In YAMLRecords
            ' Build the insert list
            With DataField.Value
                DataFields = New List(Of DBField)
                DataFields.Add(UpdateDB.BuildDatabaseField("schematicID", DataField.Key, FieldType.smallint_type))
                DataFields.Add(UpdateDB.BuildDatabaseField("schematicName", NameTranslation.GetLanguageTranslationData(.nameID), FieldType.nvarchar_type))
                DataFields.Add(UpdateDB.BuildDatabaseField("cycleTime", .cycleTime, FieldType.int_type))

                ' insert into pin map table
                For i = 0 To .pins.Count - 1
                    DataFields2 = New List(Of DBField)
                    DataFields2.Add(UpdateDB.BuildDatabaseField("schematicID", DataField.Key, FieldType.smallint_type))
                    DataFields2.Add(UpdateDB.BuildDatabaseField("pinTypeID", .pins(i), FieldType.int_type))
                    Call UpdateDB.InsertRecord(planetSchematicsPinMapTable, DataFields2)
                Next

                ' Insert all data into type map table
                For Each pinType In .types
                    DataFields3 = New List(Of DBField)
                    DataFields3.Add(UpdateDB.BuildDatabaseField("schematicID", DataField.Key, FieldType.smallint_type))
                    DataFields3.Add(UpdateDB.BuildDatabaseField("typeID", pinType.Key, FieldType.int_type))
                    DataFields3.Add(UpdateDB.BuildDatabaseField("quantity", pinType.Value.quantity, FieldType.smallint_type))
                    DataFields3.Add(UpdateDB.BuildDatabaseField("isInput", pinType.Value.isInput, FieldType.bit_type))
                    Call UpdateDB.InsertRecord(planetSchematicsTypeMapTable, DataFields3)
                Next

                ' Insert the translated data into translation tables
                Call Translator.InsertTranslationData(DataField.Key, "schematicID", "schematicName", TableName, NameTranslation.GetAllTranslations(.nameID))

            End With

            Call UpdateDB.InsertRecord(TableName, DataFields)

            ' Update grid progress
            Call UpdateGridRowProgress(Params.RowLocation, Count, TotalRecords)
            Count += 1 ' Count after so we never get to 100 until finished

        Next

        Call FinalizeGridRow(Params.RowLocation)

    End Sub

End Class

Public Class planetSchematic
    Public Property cycleTime As Object
    Public Property nameID As Translations
    Public Property pins As List(Of Object)
    Public Property types As Dictionary(Of Long, planetSchematicTypeMapValues)
End Class

Public Class planetSchematicTypeMapValues
    Public Property quantity As Object
    Public Property isInput As Object
End Class


text:
package org.immutables.criteria;

import org.immutables.criteria.repository.Facet;
import org.immutables.criteria.repository.sync.SyncReadable;
import org.immutables.criteria.repository.sync.SyncWritable;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * An immutable class annotated with {@code @Criteria} will have Criteria class automatically generated.
 *
 * Generated criteria class is a type-safe query DSL modeled after current type.
 */
@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.CLASS) // need at least CLASS retention because of APT unit testing
public @interface Criteria {

  /**
   * Marks attribute as id (primary key) for a particular class.
   */
  @Documented
  @Target({ElementType.METHOD, ElementType.FIELD})
  @Retention(RetentionPolicy.RUNTIME)
  @interface Id {}

  /**
   *

   * Classes annotated with this annotation will have repository generated to
   * store and retrieve documents. Repository classes are generated in the same package and
   * and have same visibility as original class (public / package private). They are named
   * after annotated value type: {@code [name_of_annotated_type]Repository}.
   *

   *

   * {@code @Criteria.Repository} should only be used with value types annotated with
   * {@code @Value.Immutable}.
   *

   */
  @Documented
  @Target(ElementType.TYPE)
  @Retention(RetentionPolicy.RUNTIME)
  @interface Repository {

    /**
     * Name of destination container (can be table for RDBMS, collection for MongoDB, index for ElasticSearch).
     * If not specified, name will be derived from the class name like {@code "myDocument"} for {@code MyDocument} class.
     * @return name of the container (table, collection etc.)
     */
    String name() default "";

    /**
     * Allows defining repository properties like readable / writable / watchable etc.
     * @return list of facets the repository should support
     */
    Class<? extends Facet>[] facets() default {SyncReadable.class, SyncWritable.class};
  }

}


text:
package org.jmxtrans.agent;

import org.jmxtrans.agent.util.StringUtils2;
import org.jmxtrans.agent.util.logging.Logger;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.management.ObjectName;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;

/**
 * Build a {@linkplain org.jmxtrans.agent.QueryResult#name} from a collected metric ({@linkplain org.jmxtrans.agent.Query}).
 *

 * Build name must be escaped to be compatible with all {@linkplain org.jmxtrans.agent.OutputWriter}.
 * The approach is to escape non alpha-numeric chars.
 *

 * Expressions support '#' based keywords (e.g. #hostname#) and with '%' based variables mapped to objectname properties.
 *

 * Supported '#' based 'functions':
 *

 *

 * Function
 * Description
 * Sample
 *

 *

 * #hostname#
 * localhost - hostname {@link java.net.InetAddress#getHostName()}
 *
 *

 *

 * #reversed_hostname#
 * reversed localhost - hostname {@link java.net.InetAddress#getHostName()}
 *
 *

 *

 * #escaped_hostname#
 * localhost - hostname {@link java.net.InetAddress#getHostName()} with '.' replaced by '_'
 *
 *

 *

 * #canonical_hostname#
 * localhost - canonical hostname {@link java.net.InetAddress#getCanonicalHostName()}
 * server1.ecommerce.mycompany.com
 *

 *

 * #reversed_canonical_hostname#
 * reversed localhost - canonical hostname {@link java.net.InetAddress#getCanonicalHostName()}
 * com.mycompany.ecommerce.server1
 *

 *

 * #escaped_canonical_hostname#
 * localhost - canonical hostname {@link java.net.InetAddress#getCanonicalHostName()} with '.' replaced by '_'
 * server1_ecommerce_mycompany_com
 *

 *

 * #hostaddress#
 * localhost - hostaddress {@link java.net.InetAddress#getHostAddress()}
 *
 *

 *

 * #escaped_hostname#
 * localhost - hostaddress {@link java.net.InetAddress#getHostAddress()} with '.' replaced by '_'
 *
 *

 *

 *
 * @author Cyrille Le Clerc
 */
public class ResultNameStrategyImpl implements ResultNameStrategy {

    protected final Logger logger = Logger.getLogger(getClass().getName());

    private ExpressionLanguageEngine expressionLanguageEngine = new ExpressionLanguageEngineImpl();

    @Nonnull
    @Override
    public String getResultName(@Nonnull Query query, @Nonnull ObjectName objectName) {
        return getResultName(query, objectName, null);
    }

    @Nonnull
    @Override
    public String getResultName(@Nonnull Query query, @Nonnull ObjectName objectName, @Nullable String key) {
        String result;
        if (query.getResultAlias() == null) {
            if(key == null) {
                result = escapeObjectName(objectName) + "." + query.getAttribute();
            } else {
                result = escapeObjectName(objectName) + "." + query.getAttribute() + "." + key;
            }
        } else {
            result = expressionLanguageEngine.resolveExpression(query.getResultAlias(), objectName);
        }
        return result;
    }

    /**
     * Transforms an {@linkplain javax.management.ObjectName} into a plain {@linkplain String} only composed of (a->Z, A-Z, '_').
     *

     * '_' is the escape char for not compliant chars.
     */
    protected String escapeObjectName(@Nonnull ObjectName objectName) {
        StringBuilder result = new StringBuilder();
        StringUtils2.appendEscapedNonAlphaNumericChars(objectName.getDomain(), result);
        result.append('.');
        List<String> keys = Collections.list(objectName.getKeyPropertyList().keys());
        Collections.sort(keys);
        for (Iterator<String> it = keys.iterator(); it.hasNext(); ) {
            String key = it.next();
            StringUtils2.appendEscapedNonAlphaNumericChars(key, result);
            result.append("__");
            StringUtils2.appendEscapedNonAlphaNumericChars(objectName.getKeyProperty(key), result);
            if (it.hasNext()) {
                result.append('.');
            }
        }
        if (logger.isLoggable(Level.FINEST))
            logger.log(Level.FINEST, "escapeObjectName(" + objectName + "): " + result);
        return result.toString();
    }

    public ExpressionLanguageEngine getExpressionLanguageEngine() {
        return expressionLanguageEngine;
    }

    public void setExpressionLanguageEngine(ExpressionLanguageEngine expressionLanguageEngine) {
        this.expressionLanguageEngine = expressionLanguageEngine;
    }

    public void postConstruct(@Nonnull Map<String, String> settings) {

    }
}


text:
cofy
====
[![Build Status](https://travis-ci.org/RocksonZeta/cofy.svg?branch=master)](https://travis-ci.org/RocksonZeta/cofy)
[![Coverage Status](https://coveralls.io/repos/RocksonZeta/cofy/badge.png?branch=master)](https://coveralls.io/r/RocksonZeta/cofy?branch=master)
[![NPM version](https://badge.fury.io/js/cofy.svg)](http://badge.fury.io/js/cofy)
[![Dependency Status](https://david-dm.org/RocksonZeta/cofy.svg)](https://david-dm.org/RocksonZeta/cofy)

[![NPM](https://nodei.co/npm/cofy.png?downloads=true&downloadRank=true&stars=true)](https://nodei.co/npm/cofy/)

Cofy is a bridge connecting callback style object to sequential style in [co](https://github.com/visionmedia/co) or [koa](https://github.com/koajs/koa) environment with one punch.

##Installation
```
$ npm install cofy --save
```

### NOTE: default prefix has changed to '$'.

## Some examples

use cofy in [redis](https://github.com/mranney/node_redis).
```javascript
'use strict';
var co = require("co");
var cofy = require("cofy");
var redis = require('redis');

//enable redis to has a co ablitiy.
cofy.class(redis.RedisClient);

//now we can use mysql in co
var client = redis.createClient(6379,'localhost');
co(function * () {
	//use class.$fn
	var r1 = yield client.$set('a' ,1);
	var r2 = yield client.$get('a');
	var r3 = yield client.$hmset('h' , {k1:'v1' , k2:'v2'});
	var r4 = yield client.$hget('h' ,'k1');
	console.log(r1,r2);
	console.log(r3,r4);
})();
```

use cofy in [mysql](https://github.com/felixge/node-mysql).
```javascript
'use strict';
var co = require("co");
var cofy = require("cofy");
var mysql = require('mysql');

//(felixge/node-mysql) has no extends entrance. so we can do this.
var PoolConnection = require('mysql/lib/PoolConnection.js');
var Pool = require('mysql/lib/Pool.js');
var PoolCluster = require('mysql/lib/PoolCluster.js');

//enable mysql to has a co ablitiy.
cofy.class(PoolConnection);
cofy.class(Pool);
cofy.class(PoolCluster);

var pool = mysql.createPool({
	host: "localhost",
    database: "db",
    user: "root",
    password: "pass",
});
//now we can use mysql in co
co(function * () {
	var con = yield pool.$getConnection();
	//pay attention on precedence of operator! yield < [] .
	var result = (yield con.$query("select 1+1"))[0];
	console.log(result);
	con.release();
})();

//use it in transaction
co(function*(){
	var con ;
	try{
		con = yield pool.$getConnection();
		yield con.$beginTransaction();
		yield con.$query("select some");
		yield con.$query("insert some");
		yield con.$query("update some");
		yield con.$commit();
	}catch(e){
		yield con.$rollback();
		console.error(e);
		//to do
	}finally{
		if(con){
			con.release();
		}
	}
})();
```

use cofy in [request](https://github.com/mikeal/request).
```javascript
'use strict';
var request = require('request');
var cofy = require('cofy');
var co = require('co');

var $request = cofy.fn(request);

co(function*(){
	var r = yield $request({url:"http://www.google.com"});
	console.log(r);
})();
```

cofy `nodejs` [fs](http://nodejs.org/api/fs.html) api:
```js
'use strict';
var cofy = require('../');
var co = require('co');

var fs = require('fs');
cofy(fs);

//fs.exists callback function has no error. we call set `throwable` to false.
fs.$exists = cofy.object(fs.exists , false ,fs);

co(function*(){
	var file = '/hello.txt';
	if(!(yield fs.$exists(file))){
		return;
	}
	var r = yield fs.$readFile(file,'utf8');
	console.log('fda' , r);
	//also you can use it in old way
	fs.readFile(file , 'utf8' , function(e,r){
		if(e){
			throw e;
		}
		console.log(r);
	});
})();
```

## cofy API

### class(constructor,[throwable],[methods],[prefix])

Enable a class or a object or a function to has [co](https://github.com/visionmedia/co) ability.
- `constructor` `{function}` - cofy target.the constructor of the class;
- `throwable` `{bool}` - if `throwable` is true the first argument of callback function arguments will be deemed as a exception.if `throwable` is false,no exception will be throwed ,all arguments will be returned. default is `true`.
- `methods` `{array}` - `Array`,if exists ,cofy will only cofy the methods in the target.
- `prefix` `{string}` - cofy will add function to the target(except target is function),the function name has a prefix. default is `$`.

### object(object,[throwable],[methods],[prefix],[context])

- `object` `{function}` - cofy target.the constructor of the class;
- `throwable` `{bool}` - if `throwable` is true the first argument of callback function arguments will be deemed as a exception.if `throwable` is false,no exception will be throwed ,all arguments will be returned. default is `true`.
- `context` `{object}` - the function execute context.
- `methods` `{array}` - `Array`,if exists ,cofy will only cofy the methods in the target.
- `prefix` `{string}` - cofy will add function to the target(except target is function),the function name has a prefix. default is `$`.

### fn(fn,[throwable],[context])
- `fn` `{function}` - cofy a function; `function(args , cb)` -> `yeild function(args)`
- `throwable` `{bool}` - if `throwable` is true the first argument of callback function arguments will be deemed as a exception.if `throwable` is false,no exception will be throwed ,all arguments will be returned. default is `true`.
- `context` `{object}` - the function execute context.


text:
'use strict';

var
  classes = require( './classes' ),
  merge = require( './merge' );

module.exports = {
  Nil: classes.Nil,
  newclass: classes.newclass,

  merge: merge,
  conflict: merge.conflict,
  required: merge.required,

  clone: require( './clone' ),
  extend: require( './extend' ),
  mix: require( './mix' )
};


text:
// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com

//----------------------------------------------------------------------------------
#include "stdafx.h"
#include <SDL_timer.h>
//----------------------------------------------------------------------------------
COrionApplication g_App;
//----------------------------------------------------------------------------------
void COrionApplication::OnMainLoop()
{
    //WISPFUN_DEBUG("c193_f1");
    g_Ticks = SDL_GetTicks();

    if (NextRenderTime <= g_Ticks)
    {
        NextUpdateTime = g_Ticks + 50;
        NextRenderTime = NextUpdateTime; // g_Ticks + g_OrionWindow.RenderTimerDelay;

#if !USE_WISP
        g_Orion.Process(true);
#endif
        g_ConnectionManager.Recv();
        g_PacketManager.ProcessPluginPackets();
        g_PacketManager.SendMegaClilocRequests();
    }
    else if (NextUpdateTime <= g_Ticks)
    {
        NextUpdateTime = g_Ticks + 50;

#if !USE_WISP
        g_Orion.Process(false);
#endif
        g_ConnectionManager.Recv();
        g_PacketManager.ProcessPluginPackets();
        g_PacketManager.SendMegaClilocRequests();
    }
}
//----------------------------------------------------------------------------------


text:
<?php

namespace App\Controller;

use App\Events;
use App\MainBundle\Document\ContentType;
use App\MainBundle\Document\Filter;
use App\MainBundle\Document\User;
use App\Repository\CategoryRepository;
use App\Repository\ContentTypeRepository;
use App\Service\CatalogService;
use App\Service\SettingsService;
use App\Service\UtilsService;
use Doctrine\ODM\MongoDB\DocumentManager;
use Doctrine\Persistence\ObjectRepository;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\EventDispatcher\GenericEvent;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use App\MainBundle\Document\Category;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
use Twig\Environment as TwigEnvironment;

class CatalogController extends BaseController
{

    /** @var SettingsService */
    protected $settingsService;
    /** @var CatalogService */
    protected $catalogService;
    /** @var TwigEnvironment */
    protected $twig;

    public function __construct(
        ParameterBagInterface $params,
        DocumentManager $dm,
        TranslatorInterface $translator,
        SettingsService $settingsService,
        CatalogService $catalogService,
        TwigEnvironment $twig
    )
    {
        parent::__construct($params, $dm, $translator);
        $this->settingsService = $settingsService;
        $this->catalogService = $catalogService;
        $this->twig = $twig;
    }

    /**
     * @Route(
     *     "/api/{_locale}/user_content/{categoryId}",
     *     name="user_content_create_api",
     *     requirements={"_locale"="^[a-z]{2}$"},
     *     condition="request.headers.get('Content-Type') === 'application/json'",
     *     methods={"POST"}
     * )
     * @ParamConverter("category", class="App\MainBundle\Document\Category", options={"id" = "categoryId"})
     * @param Request $request
     * @param EventDispatcherInterface $eventDispatcher
     * @param Category $category
     * @return JsonResponse
     */
    public function createUserContentAction(
        Request $request,
        EventDispatcherInterface $eventDispatcher,
        Category $category = null
    )
    {
        if(!$category){
            return $this->setError($this->translator->trans('Category not found.', [], 'validators'));
        }
        $contentType = $category->getContentType();
        if(!$contentType){
            return $this->setError($this->translator->trans('Content type not found.', [], 'validators'));
        }
        if (!$contentType->getIsCreateByUsersAllowed()) {
            return $this->setError($this->translator->trans('You are not allowed to create this page.', [], 'validators'));
        }

        /** @var User $user */
        $user = $this->getUser();
        $data = json_decode($request->getContent(), true);

        $collection = $this->catalogService->getCollection($contentType->getCollection());
        if (!$collection) {
            return $this->setError('Item not saved.');
        }

        try {
            $document = $this->catalogService->createContentItemData($category, $data, $user->getId());
        } catch (\Exception $e) {
            $msg = $e->getMessage();
            if (is_array($msg) && isset($msg['msg'])) {
                return $this->setError($this->translator->trans($msg['msg'], $msg, 'validators'));
            } else {
                return $this->setError($this->translator->trans($e->getMessage()));
            }
        }

        try {
            $result = $collection->insertOne($document);
        } catch (\Exception $e) {
            return $this->setError($this->translator->trans('Item not saved.'));
        }

        if (!$result || !$result->getInsertedCount()) {
            return $this->setError($this->translator->trans('Item not saved.'));
        }

        $event = new GenericEvent($document, ['contentType' => $contentType]);
        $eventDispatcher->dispatch($event, Events::PRODUCT_CREATED);
        $eventDispatcher->dispatch($event, Events::PRODUCT_UPDATED);

        return $this->json([
            'success' => true,
            'result' => $document
        ]);
    }

    /**
     * @Route(
     *     "/api/{_locale}/user_content/{categoryId}/{itemId}",
     *     name="user_content_update_api",
     *     requirements={"_locale"="^[a-z]{2}$"},
     *     condition="request.headers.get('Content-Type') === 'application/json'",
     *     methods={"PUT"}
     * )
     * @ParamConverter("category", class="App\MainBundle\Document\Category", options={"id" = "categoryId"})
     * @param Request $request
     * @param EventDispatcherInterface $eventDispatcher
     * @param Category $category
     * @param int|string $itemId
     * @return JsonResponse
     */
    public function updateUserContentAction(
        Request $request,
        EventDispatcherInterface $eventDispatcher,
        Category $category = null,
        $itemId = 0
    )
    {
        if(!$category){
            return $this->setError($this->translator->trans('Category not found.', [], 'validators'));
        }

        /** @var User $user */
        $user = $this->getUser();

        try {
            $doc = $this->catalogService->getContentItem($category, [
                '_id' => (int) $itemId,
                'parentId' => $category->getId(),
                'userId' => $user->getId()
            ]);
        } catch (\Exception $e) {
            return $this->setError($this->translator->trans($e->getMessage()));
        }

        $localeDefault = $this->params->get('locale');
        $locale = $request->getLocale();
        $contentType = $category->getContentType();
        $collection = $this->catalogService->getCollection($contentType->getCollection());

        $data = json_decode($request->getContent(), true);

        if ($locale !== $localeDefault && empty($data['translations'])) {
            CatalogService::updateTranslation($contentType->getFields(), $data, $doc, $locale);
        }

        try {
            $document = $this->catalogService->createContentItemData($category, $data, $user->getId(), (int) $itemId);
        } catch (\Exception $e) {
            $msg = $e->getMessage();
            if (is_array($msg) && isset($msg['msg'])) {
                return $this->setError($this->translator->trans($msg['msg'], $msg, 'validators'));
            } else {
                return $this->setError($this->translator->trans($e->getMessage()));
            }
        }

        try {
            $result = $collection->updateOne(
                ['_id' => (int) $itemId],
                ['$set' => $document]
            );
        } catch (\Exception $e) {
            return $this->setError($this->translator->trans('Item not saved.'));
        }

        if (!$result || !$result->getModifiedCount()) {
            return $this->setError($this->translator->trans('Item not saved.'));
        }

        $event = new GenericEvent($document, ['contentType' => $contentType]);
        $eventDispatcher->dispatch($event, Events::PRODUCT_UPDATED);

        return $this->json([
            'success' => true,
            'result' => $document
        ]);
    }

    /**
     * @Route(
     *     "/api/{_locale}/user_content/{categoryId}/{itemId}",
     *     name="user_content_item_api",
     *     requirements={"_locale"="^[a-z]{2}$"},
     *     condition="request.headers.get('Content-Type') === 'application/json'",
     *     methods={"GET"}
     * )
     * @ParamConverter("category", class="App\MainBundle\Document\Category", options={"id" = "categoryId"})
     * @param Request $request
     * @param Category $category
     * @param string|int $itemId
     * @return JsonResponse
     */
    public function getUserContentAction(Request $request, Category $category = null, $itemId = 0)
    {
        if(!$category){
            return $this->setError($this->translator->trans('Category not found.', [], 'validators'));
        }

        /** @var User $user */
        $user = $this->getUser();

        if ($itemId) {

            try {
                $document = $this->catalogService->getContentItem($category, [
                    '_id' => (int) $itemId,
                    'parentId' => $category->getId(),
                    'userId' => $user->getId()
                ]);
            } catch (\Exception $e) {
                return $this->setError($this->translator->trans($e->getMessage()));
            }

            return $this->json([
                'success' => true,
                'result' => $document
            ]);

        } else {

            $contentType = $category->getContentType();
            $collection = $this->catalogService->getCollection($contentType->getCollection());

            $queryString = $request->getQueryString();
            $queryOptions = UtilsService::getQueryOptions('', $queryString, $contentType->getFields());
            $skip = ($queryOptions['page'] - 1) * $queryOptions['limit'];

            $data = $this->catalogService->getContentList($contentType, $queryOptions, [
                'parentId' => $category->getId(),
                'userId' => $user->getId()
            ], $skip);

            $total = $collection->countDocuments([
                'parentId' => $category->getId(),
                'userId' => $user->getId()
            ]);

            return $this->json([
                'items' => $data,
                'total' => $total
            ]);
        }
    }

    /**
     * @Route(
     *     "/api/{_locale}/user_content/{categoryId}/{itemId}",
     *     name="user_content_delete_item_api",
     *     requirements={"_locale"="^[a-z]{2}$"},
     *     condition="request.headers.get('Content-Type') === 'application/json'",
     *     methods={"DELETE"}
     * )
     * @ParamConverter("category", class="App\MainBundle\Document\Category", options={"id" = "categoryId"})
     * @param EventDispatcherInterface $eventDispatcher
     * @param Category $category
     * @param string|int $itemId
     * @return JsonResponse
     */
    public function deleteUserContentAction(EventDispatcherInterface $eventDispatcher, Category $category, $itemId)
    {
        if(!$category){
            return $this->setError($this->translator->trans('Category not found.', [], 'validators'));
        }

        /** @var User $user */
        $user = $this->getUser();

        try {
            $document = $this->catalogService->getContentItem($category, [
                '_id' => (int) $itemId,
                'parentId' => $category->getId(),
                'userId' => $user->getId()
            ]);
        } catch (\Exception $e) {
            return $this->setError($this->translator->trans($e->getMessage()));
        }

        $contentType = $category->getContentType();
        $collection = $this->catalogService->getCollection($contentType->getCollection());

        try {
            $result = $collection->deleteOne([
                '_id' => (int) $itemId
            ]);
        } catch (\Exception $e) {
            $result = false;
        }

        if (empty($result) || !$result->getDeletedCount()) {
            return $this->setError($this->translator->trans('Deletion error. Please try again later.'));
        }

        // Dispatch event
        $event = new GenericEvent($document, ['contentType' => $contentType]);
        $eventDispatcher->dispatch($event, Events::PRODUCT_DELETED);
        $eventDispatcher->dispatch($event, Events::PRODUCT_UPDATED);

        return $this->json([
            'success' => true
        ]);
    }

    /**
     * @Route(
     *     "/{_locale}/{uri<^[a-z0-9\/\-_\.]+\/$>}",
     *     name="catalog_category_localized",
     *     requirements={"_locale": "^[a-z]{2}$", "uri": "^[a-z0-9\/\-_\.]+\/$"},
     *     defaults={"uri": ""}
     * )
     * @Route(
     *     "/{uri<^[a-z0-9\/\-_\.]+\/$>}",
     *     name="catalog_category",
     *     requirements={"uri": "^[a-z0-9\/\-_\.]+\/$"},
     *     defaults={"uri": ""}
     * )
     * @param Request $request
     * @param string $uri
     * @return Response
     * @throws \Doctrine\ODM\MongoDB\LockException
     * @throws \Doctrine\ODM\MongoDB\Mapping\MappingException
     * @throws \Doctrine\ODM\MongoDB\MongoDBException
     */
    public function catalogCategoryAction(Request $request, $uri)
    {
        return $this->catalogAction($request, $uri, 'catalog_category');
    }

    /**
     * @Route(
     *     "/{_locale}/{uri<[a-zA-Z0-9\/\-_\.]+>}",
     *     name="catalog_page_localized",
     *     requirements={"_locale": "^[a-z]{2}$", "uri": "[a-zA-Z0-9\/\-_\.]+"},
     *     defaults={"uri": ""}
     * )
     * @Route(
     *     "/{uri<[a-zA-Z0-9\/\-_\.]+>}",
     *     name="catalog_page",
     *     requirements={"uri": "[a-zA-Z0-9\/\-_\.]+"},
     *     defaults={"uri": ""}
     * )
     * @param Request $request
     * @param string $uri
     * @return Response
     * @throws \Doctrine\ODM\MongoDB\LockException
     * @throws \Doctrine\ODM\MongoDB\Mapping\MappingException
     * @throws \Doctrine\ODM\MongoDB\MongoDBException
     */
    public function catalogPageAction(Request $request, $uri)
    {
        return $this->catalogAction($request, $uri, 'catalog_page');
    }

    /**
     * @param Request $request
     * @param string $uri
     * @param string $routeName
     * @return Response
     * @throws \Doctrine\ODM\MongoDB\LockException
     * @throws \Doctrine\ODM\MongoDB\Mapping\MappingException
     * @throws \Doctrine\ODM\MongoDB\MongoDBException
     */
    public function catalogAction(Request $request, $uri, $routeName)
    {
        if (empty($this->params->get('mongodb_database'))) {
            return $this->redirectToRoute('setup');
        }
        $localeDefault = $this->params->get('locale');
        $showAllChildren = $this->params->has('app.catalog_show_all_children')
            ? $this->params->get('app.catalog_show_all_children')
            : false;
        $locale = $request->getLocale();
        $categoriesRepository = $this->getCategoriesRepository();
        $filtersRepository = $this->dm->getRepository(Filter::class);
        list($pageAlias, $categoryUri, $levelNum) = Category::parseUri($uri);

        /** @var Category $currentCategory */
        if ($categoryUri) {
            $where = ['uri' => $categoryUri];
            $currentCategory = $categoriesRepository->findOneBy($where);
        } else {
            $currentCategory = $categoriesRepository->find(0);
        }
        if ($routeName === 'catalog_page') {
            if (is_null($currentCategory)) {
                throw $this->createNotFoundException();
            }
            return $this->pageProduct($currentCategory, $uri, $locale);
        }
        if (!$currentCategory || !$currentCategory->getIsActive()) {
            throw $this->createNotFoundException();
        }

        $listTemplate = $request->cookies->get('shkListType', 'grid');
        $catalogNavSettingsDefaults = $this->getCatalogNavSettingsDefaults();
        $currentPage = $currentCategory;
        $currentId = $currentCategory->getId();

        $breadcrumbs = $categoriesRepository->getBreadcrumbs($categoryUri, false, $locale);
        $categoriesMenu = $this->getCategoriesMenu($currentCategory, $breadcrumbs, $locale);

        $contentType = $currentCategory->getContentType();
        $priceFieldName = $contentType->getPriceFieldName();
        $headerFieldName = $contentType->getFieldByChunkName('header');
        $contentTypeFields = $contentType->getFields();
        $collection = $this->catalogService->getCollection($contentType->getCollection());
        $queryString = $request->getQueryString();
        $queryOptions = UtilsService::getQueryOptions($uri, $queryString, $contentTypeFields, $catalogNavSettingsDefaults);

        $options = [
            'currentCategoryUri' => $currentCategory->getUri(),
            'systemNameField' => $contentType->getSystemNameField(),
            'needSortFields' => true
        ];
        /** @var Filter $filters */
        $filters = $filtersRepository->findByCategory($currentCategory->getId());
        $filtersArr = !empty($filters) ? $filters->getValues() : [];
        $filtersData = !empty($filters) ? $filters->getValuesData() : [];
        list($filters, $fieldsAll) = $this->getFieldsData($contentTypeFields, $options,'page', $filtersArr, $filtersData, $queryOptions);
        $fields = array_filter($fieldsAll, function($v) {
            return $v['showInList'];
        });

        // Get child products
        $criteria = [
            'isActive' => true
        ];
        $this->applyFilters($queryOptions['filter'], $filters, $criteria);

        if ($showAllChildren && $currentCategory->getParentId()) {
            $categoriesIdsArr = $categoriesRepository->getChildrenIdsByUri($categoryUri);
        } else {
            $categoriesIdsArr = [$currentCategory->getId()];
        }
        $this->catalogService->applyCategoryFilter($categoriesIdsArr, $contentTypeFields, $criteria);
        if ($locale !== $localeDefault && $headerFieldName) {
            $this->catalogService->applyLocaleFilter($locale, $headerFieldName, $criteria);
        }

        /** @var User $user */
        $user = $this->getUser();
        if ($contentType->getIsCreateByUsersAllowed() && !$user) {
            $total = 0;
            $items = [];
            $pagesOptions = UtilsService::getPagesOptions($queryOptions, $total, $catalogNavSettingsDefaults);
        } else {
            if ($contentType->getIsCreateByUsersAllowed() && !$user->getIsAdmin()) {
                $criteria['userId'] = $user->getId();
            }
            $total = $collection->countDocuments($criteria);
            $pagesOptions = UtilsService::getPagesOptions($queryOptions, $total, $catalogNavSettingsDefaults);
            $aggregateFields = $contentType->getAggregationFields($locale, $localeDefault, true);

            $pipeline = $this->catalogService->createAggregatePipeline(
                $criteria,
                $aggregateFields,
                abs($queryOptions['limit']),
                $queryOptions['sortOptionsAggregation'],
                abs($pagesOptions['skip'])
            );
            $items = $collection->aggregate($pipeline, [
                'cursor' => []
            ])->toArray();
            $items = CatalogService::mapResults($items, $contentTypeFields);
        }

        $categoriesSiblings = [];
        if (count($categoriesMenu) === 0 && $levelNum > 1) {
            $categoriesSiblings = $this->catalogService->getChildCategories($currentCategory->getParentId(), $breadcrumbs, false, '', $locale);
        }

        $activeCategoriesIds = array_map(function($item) {
            return $item['id'];
        }, $breadcrumbs);

        $breadcrumbs = array_filter($breadcrumbs, function($entry) use ($uri) {
            return $entry['uri'] !== $uri;
        });
        $currency = $this->settingsService->getCurrency();

        return $this->render($this->getTemplateName($this->twig, 'category', $contentType->getName()), [
            'currentCategory' => $currentCategory,
            'activeCategoriesIds' => $activeCategoriesIds,
            'currentPage' => $currentPage,
            'currentId' => $currentId,
            'currentUri' => $uri,
            'currency' => $currency,
            'categoriesMenu' => $categoriesMenu,
            'listTemplate' => $listTemplate,
            'items' => $items,
            'priceFieldName' => $priceFieldName,
            'fields' => $fields,
            'fieldsAll' => $fieldsAll,
            'filters' => $filters,
            'categoriesSiblings' => $categoriesSiblings,
            'breadcrumbs' => $breadcrumbs,
            'queryOptions' => $queryOptions,
            'pagesOptions' => $pagesOptions
        ]);
    }

    /**
     * @param null|Category $category
     * @param string $uri
     * @param string $locale
     * @return Response
     * @throws \Doctrine\ODM\MongoDB\LockException
     * @throws \Doctrine\ODM\MongoDB\Mapping\MappingException
     * @throws \Doctrine\ODM\MongoDB\MongoDBException
     */
    public function pageProduct(Category $category = null, $uri = '', $locale = '')
    {
        $categoriesRepository = $this->getCategoriesRepository();
        list($pageAlias, $categoryUri) = Category::parseUri($uri);

        if (empty($category)) {
            $category = $categoriesRepository->find(0);
        }
        $contentType = $category ? $category->getContentType() : null;
        if(!$contentType){
            throw $this->createNotFoundException();
        }

        /** @var User $user */
        $user = $this->getUser();
        $localeDefault = $this->params->get('locale');
        $collectionName = $contentType->getCollection();
        $contentTypeFields = $contentType->getFields();
        $priceFieldName = $contentType->getPriceFieldName();
        $collection = $this->catalogService->getCollection($collectionName);
        $breadcrumbs = $categoriesRepository->getBreadcrumbs($categoryUri, false, $locale);

        $aggregateFields = $contentType->getAggregationFields($locale, $localeDefault, true);
        if ($contentType->getIsCreateByUsersAllowed() && !$user) {
            throw $this->createNotFoundException();
        }
        $criteria = [
            'parentId' => $category->getId(),
            'isActive' => true
        ];
        if ($contentType->getIsCreateByUsersAllowed() && !$user->getIsAdmin()) {
            $criteria['userId'] = $user->getId();
        }
        if (is_numeric($pageAlias)
            && $this->params->has('app.show_page_by_id')
            && $this->params->get('app.show_page_by_id')) {
                $criteria['_id'] = (int) $pageAlias;
        } else {
            $criteria['name'] = $pageAlias;
        }

        $pipeline = $this->catalogService->createAggregatePipeline(
            $criteria,
            $aggregateFields,
            1
        );

        $currentPage = $collection->aggregate($pipeline, [
            'cursor' => []
        ])->toArray();
        if (empty($currentPage)) {
            throw $this->createNotFoundException();
        }
        $currentPage = current($currentPage);
        $currentId = $currentPage['_id'];
        $currentPage['id'] = $currentId;

        // Get fields options
        $options = [
            'currentCategoryUri' => $category->getUri(),
            'systemNameField' => $contentType->getSystemNameField(),
            'needSortFields' => false
        ];
        list($filters, $fields) = $this->getFieldsData($contentTypeFields, $options);

        // Get categories menu
        $categoriesMenu = $this->getCategoriesMenu($category, $breadcrumbs, $locale);
        $currency = $this->settingsService->getCurrency();

        $activeCategoriesIds = array_map(function($item) {
            return $item['id'];
        }, $breadcrumbs);
        if ($category && $category->getId() === 0) {
            $activeCategoriesIds[] = 0 - $currentPage['id'];
        }

        return $this->render($this->getTemplateName($this->twig, 'content-page', $contentType->getName()), [
            'currentCategory' => $category,
            'activeCategoriesIds' => $activeCategoriesIds,
            'currentPage' => $currentPage,
            'contentType' => $contentType,
            'currentId' => $currentId,
            'currentUri' => $uri,
            'currency' => $currency,
            'categoriesMenu' => $categoriesMenu,
            'breadcrumbs' => $breadcrumbs,
            'fields' => $fields,
            'priceFieldName' => $priceFieldName
        ]);
    }

    /**
     * Get catalog default settings
     * @return array
     */
    public function getCatalogNavSettingsDefaults()
    {
        $catalogNavSettingsDefaults = [];
        $catalogNavSettingsDefaults['pageSizeArr'] = $this->params->get('app.catalog_page_size');
        $catalogNavSettingsDefaults['orderBy'] = $this->params->get('app.catalog_default_order_by');
        if (!is_array($catalogNavSettingsDefaults['pageSizeArr'])) {
            $catalogNavSettingsDefaults['pageSizeArr'] = explode(',', $catalogNavSettingsDefaults['pageSizeArr']);
            $catalogNavSettingsDefaults['pageSizeArr'] = array_map('trim', $catalogNavSettingsDefaults['pageSizeArr']);
            $catalogNavSettingsDefaults['pageSizeArr'] = array_map('intval', $catalogNavSettingsDefaults['pageSizeArr']);
        }
        return $catalogNavSettingsDefaults;
    }

    /**
     * @param $contentTypeFields
     * @param array $options
     * @param string $type
     * @param array $filtersArr
     * @param array $filtersData
     * @param array $queryOptions
     * @return array
     */
    public function getFieldsData($contentTypeFields, $options = [], $type = 'page', $filtersArr = [], $filtersData = [], $queryOptions = [])
    {
        $filters = [];
        $fields = [];
        $filterIndex = 0;
        $queryOptionsFilter = !empty($queryOptions['filter']) ? $queryOptions['filter'] : [];
        foreach ($contentTypeFields as $field) {
            if ($type != 'list' || !empty($field['showInList'])) {
                if (!isset($field['outputProperties']['chunkName'])) {
                    $field['outputProperties']['chunkName'] = '';
                }
                $fields[] = array_merge($field, [
                    'listOrder' => $field['listOrder'] ?? 0,
                    'outputProperties' => array_merge($field['outputProperties'], $options)
                ]);
            }
            if (!empty($field['isFilter'])) {
                if (!empty($filtersArr[$field['name']])) {
                    $filters[] = [
                        'name' => $field['name'],
                        'title' => $field['title'],
                        'outputType' => $field['outputType'],
                        'values' => $filtersArr[$field['name']],
                        'fieldValues' => $filtersArr[$field['name']],
                        'index' => $filterIndex,
                        'order' => !empty($field['filterOrder']) ? $field['filterOrder'] : 0,
                        'selected' => isset($queryOptionsFilter[$field['name']])
                            ? is_array($queryOptionsFilter[$field['name']])
                                ? $queryOptionsFilter[$field['name']]
                                : [$queryOptionsFilter[$field['name']]]
                            : []
                    ];
                    $filterIndex++;
                } else if (!empty($filtersData)) {
                    $fieldFilterData = array_filter($filtersData, function($item) use ($field) {
                        return $item['fieldName'] === $field['name'];
                    });
                    foreach ($fieldFilterData as $fData) {
                        $fValues = array_map(function($value) use ($fData) {
                            return $fData['name'] . '__' . $value;
                        }, $fData['values']);
                        $filters[] = [
                            'name' => $field['name'],
                            'title' => $fData['name'],
                            'outputType' => $field['outputType'],
                            'values' => $fData['values'],
                            'fieldValues' => $fValues,
                            'index' => $filterIndex,
                            'order' => !empty($field['filterOrder']) ? $field['filterOrder'] : 0,
                            'selected' => isset($queryOptionsFilter[$field['name']])
                                ? is_array($queryOptionsFilter[$field['name']])
                                    ? $queryOptionsFilter[$field['name']]
                                    : [$queryOptionsFilter[$field['name']]]
                                : []
                        ];
                        $filterIndex++;
                    }
                }
            }
        }

        usort($filters, function($a, $b) {
            if ($a['order'] == $b['order']) {
                return 0;
            }
            return ($a['order'] < $b['order']) ? -1 : 1;
        });

        if (!empty($options['needSortFields'])) {
            usort($fields, function($a, $b) {
                if ($a['listOrder'] == $b['listOrder']) {
                    return 0;
                }
                return ($a['listOrder'] < $b['listOrder']) ? -1 : 1;
            });
        }

        return [$filters, $fields];
    }

    /**
     * @param Category|null $currentCategory
     * @param array $breadcrumbs
     * @param string $locale
     * @return array
     */
    public function getCategoriesMenu(Category $currentCategory = null, $breadcrumbs = [], $locale = '')
    {
        $categoriesRepository = $this->getCategoriesRepository();
        $categories = [];
        $currentId = $currentCategory ? $currentCategory->getId() : 0;
        $topIdsArr = [];
        $breadcrumbsUriArr = array_column($breadcrumbs, 'uri');
        if (!in_array($currentCategory->getUri(), $breadcrumbsUriArr)) {
            array_unshift($breadcrumbsUriArr, $currentCategory->getUri());
        }

        // Get top categories
        $results = $categoriesRepository->findBy([
            'parentId' => $currentId,
            'isActive' => true
        ], ['menuIndex' => 'asc', 'title' => 'asc']);

        /** @var Category $category */
        foreach ($results as $category) {
            $categories[] = $category->getMenuData($breadcrumbsUriArr, $locale);
            $topIdsArr[] = $category->getId();
        }

        // Get child categories
        $results = $categoriesRepository
            ->findActiveAll('title', 'asc', null, $topIdsArr);

        /** @var Category $category */
        foreach ($results as $category) {
            $index = array_search($category->getParentId(), $topIdsArr);
            if ($index !== false) {
                $categories[$index]['children'][] = $category->getMenuData($breadcrumbsUriArr, $locale);
            }
        }

        return $categories;
    }

    /**
     * @param $filters
     * @param $filtersData
     * @param $criteria
     */
    public function applyFilters($filters, $filtersData, &$criteria)
    {
        if (empty($filters)) {
            return;
        }
        foreach ($filters as $name => $filter) {
            if ($filter === '') {
                continue;
            }
            if (!is_array($filter)) {
                $filter = [is_numeric($filter) ? floatval($filter) : $filter];
            }
            $index = array_search($name, array_column($filtersData, 'name'));
            $outputType = '';
            if ($index !== false) {
                $flt = $filtersData[$index];
                $outputType = $flt['outputType'];
                // Process color filter
                if ($outputType === 'color') {
                    foreach ($filter as &$val) {
                        $val = '#' . $val;
                    }
                }
            }
            if (isset($filter['from']) && isset($filter['to'])) {
                if ($outputType === 'date') {
                    if (!empty($filter['from']) && CatalogService::isDateString($filter['from'])) {
                        $criteria[$name] = ['$gte' => CatalogService::dateToUTCDate($filter['from'])];
                    }
                    if (!empty($filter['to']) && CatalogService::isDateString($filter['to'])) {
                        if (!isset($criteria[$name])) {
                            $criteria[$name] = [];
                        }
                        $criteria[$name]['$lte'] = CatalogService::dateToUTCDate($filter['to']);
                    }
                } else {
                    $criteria[$name] = ['$gte' => floatval($filter['from']), '$lte' => floatval($filter['to'])];
                }
            } else if ($outputType === 'parameters') {
                $fData = [];
                foreach ($filter as $fValue) {
                    $fValueArr = explode('__', $fValue);
                    if (count($fValueArr) < 2) {
                        continue;
                    }
                    $index = array_search($fValueArr[0], array_column($fData, 'name'));
                    if ($index === false) {
                        $fData[] = [
                            'name' => $fValueArr[0],
                            'values' => []
                        ];
                        $index = count($fData) - 1;
                    }
                    if (!in_array($fValueArr[1], $fData[$index]['values'])) {
                        $fData[$index]['values'][] = $fValueArr[1];
                    }
                }
                if (!empty($fData)) {
                    $criteria[$name] = ['$all' => []];
                    foreach ($fData as $k => $v) {
                        $criteria[$name]['$all'][] = [
                            '$elemMatch' => [
                                'name' => $v['name'],
                                'value' => ['$in' => $v['values']]
                            ]
                        ];
                    }
                }
            } else {
                $criteria[$name] = ['$in' => $filter];
            }
        }
    }

    /**
     * @param array $treeData
     * @param array $uriArr
     * @param array $idsArr
     * @return array
     */
    public function getCategoriesActiveIds($treeData, $uriArr, $idsArr = [])
    {
        if (empty($treeData['children'])) {
            return $idsArr;
        }
        foreach ($treeData['children'] as $category) {
            if (in_array($category['uri'], $uriArr)) {
                $idsArr[] = $category['id'];
            }
            if (!empty($category['children'])) {
                $idsArr = $this->getCategoriesActiveIds($category, $uriArr, $idsArr);
            }
        }
        return $idsArr;
    }

    /**
     * @return CategoryRepository|ObjectRepository
     */
    public function getCategoriesRepository()
    {
        return $this->dm->getRepository(Category::class);
    }

    /**
     * @return ContentTypeRepository|ObjectRepository
     */
    public function getContentTypeRepository()
    {
        return $this->dm->getRepository(ContentType::class);
    }
}


text:
<SyntaxMode name = "Razor" mimeTypes="text/x-cshtml">

		<Begin>@*</Begin>
		<End>*@</End>

		<Begin><!DOCTYPE</Begin>
		<End>></End>

		<Begin><![CDATA[</Begin>
		<End>]]></End>

	<Rule name = "InTag">

			<Begin>"</Begin>
			<End>"</End>

			<Begin>'</Begin>
			<End>'</End>

		<Match color = "Keyword(Type)" ignorecase="True">[A-Za-z0-9_]+(:[A-Za-z0-9_]+)?[\s\n\r]*=</Match>

			<Begin>@*</Begin>
			<End>*@</End>

	</Rule>

	<Rule name = "InLiteral">

			<Begin>&</Begin>
			<End>;</End>

	</Rule>

	<Rule name = "Comment">
	</Rule>
</SyntaxMode>


text:
// Licensed to eXtensoft LLC under one or more agreements.
// eXtensoft LLC licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

namespace XF.Common.Db
{
    using System;
    using System.Collections.Generic;
    using System.Xml;
    using System.Xml.Serialization;

    [Serializable]
    public class DbConfig
    {
        [XmlAttribute("appKey")]
        public string AppContextKey { get; set; }

        private List<Model> _Models = new List<Model>();
        public List<Model> Models
        {
            get { return _Models; }
            set { _Models = value; }
        }
    }
}


text:
load('../../../../audiotest.js/trunk/audiotest.js');
load('../../src/audiofile/audiofile.js');
load('../../src/audiolet/Audiolet.js');
load('../Environment.js');

function testDCFilter() {
    var audiolet = new Audiolet();
    var sine = new Sine(audiolet);
    var add = new Add(audiolet, 1); // Adds a DC offset
    var dcFilter = new DCFilter(audiolet);
    var recorder = new InputRecorder(audiolet, 1);

    sine.connect(add);
    add.connect(dcFilter);
    dcFilter.connect(recorder);

    // Give the filter time to start filtering the offset
    for (var i=0; i<81920; i++) {
        sine.tick();
        add.tick();
        dcFilter.tick();
        recorder.tick();
    }

    var buffer = recorder.buffers[0][0];
    Assert.assertContinuous(buffer);
    Assert.assertAudibleValues(buffer);
    Assert.assertValuesInRange(buffer, -1, 2);

    // Most of the DC offset should now be filtered
    recorder.reset();
    for (var i=0; i<audiolet.device.sampleRate; i++) {
        sine.tick();
        add.tick();
        dcFilter.tick();
        recorder.tick();
    }

    var buffer = recorder.buffers[0][0];
    Assert.assertContinuous(buffer);
    Assert.assertAudibleValues(buffer);
    Assert.assertValuesInRange(buffer, -1, 1);
}

test("DC Filter", testDCFilter);


text:
namespace printing {

enum PwgRasterTransformType {
  TRANSFORM_NORMAL,
  TRANSFORM_ROTATE_180,
  TRANSFORM_FLIP_HORIZONTAL,
  TRANSFORM_FLIP_VERTICAL
};

struct PwgRasterSettings {
  // How to transform odd-numbered pages.
  PwgRasterTransformType odd_page_transform;
  // Rotate all pages (on top of odd-numbered page transform).
  bool rotate_all_pages;
  // Rasterize pages in reverse order.
  bool reverse_page_order;
};

}  // namespace printing

#endif  // PRINTING_BITMAP_TRANSFORM_SETTINGS_H_


text:
namespace ml {

template<class NodeData, class EdgeData>
class UndirectedGraph
{
public:
    struct Edge
    {
        UINT getNeighbor(UINT nodeIndex) const
        {
            if (node0 == nodeIndex) return node1;
            return node0;
        }

        UINT node0, node1;
        EdgeData data;
    };

    struct Node
    {
        UINT index;
        NodeData data;
        vector<UINT> edges;
    };

    const vector<Node>& nodes() const
    {
        return _nodes;
    }

    vector<Node>& nodes()
    {
        return _nodes;
    }

    const vector<Edge>& edges() const
    {
        return _edges;
    }

    vector<Edge>& edges()
    {
        return _edges;
    }

    void addNode(const NodeData &data)
    {
        Node newNode;
        newNode.index = (UINT)_nodes.size();
        newNode.data = data;
        _nodes.push_back(newNode);
    }

    void addEdge(int node0, int node1, const EdgeData &data = EdgeData())
    {
        if (node0 > node1) std::swap(node0, node1);

        Edge newEdge;
        newEdge.node0 = node0;
        newEdge.node1 = node1;
        newEdge.data = data;

        _nodes[node0].edges.push_back((UINT)_edges.size());
        _nodes[node1].edges.push_back((UINT)_edges.size());

        _edges.push_back(newEdge);
    }

    vector< vector<const Node*> > computeConnectedComponents() const
    {
        return computeConnectedComponents([](const EdgeData &e) { return true; });
    }

    vector< vector<const Node*> > computeConnectedComponents(const std::function<bool(const EdgeData&)> &edgeTest) const
    {
        const UINT n = (UINT)_nodes.size();
        set<UINT> remainingNodes;

        for (UINT i = 0; i < n; i++)
            remainingNodes.insert(i);

        std::function<void(UINT, vector<const Node*>&)> visitNode = [&](UINT nodeIndex, vector<const Node*> &curComponent)
        {
            if (remainingNodes.count(nodeIndex) == 0) return;
            remainingNodes.erase(nodeIndex);
            curComponent.push_back(&_nodes[nodeIndex]);
            for (UINT edgeIndex : _nodes[nodeIndex].edges)
            {
                const Edge &e = _edges[edgeIndex];
                if (edgeTest(e.data))
                    visitNode(e.getNeighbor(nodeIndex), curComponent);
            }
        };

        vector< vector<const Node*> > result;

        UINT componentIndex = 0;
        while (remainingNodes.size() > 0)
        {
            result.push_back(vector<const Node*>());
            int seedNodeIndex = *remainingNodes.begin();
            visitNode(seedNodeIndex, result.back());
        }

        return result;
    }

    bool hasEdge(UINT n0, UINT n1) const
    {
        if (n0 > n1) std::swap(n0, n1);
        const Node &node0 = _nodes[n0];
        const UINT edgeCount = (UINT)node0.edges.size();
        for (UINT edgeIndex = 0; edgeIndex < edgeCount; edgeIndex++)
        {
            const Edge &edge = _edges[node0.edges[edgeIndex]];
            if (edge.node0 == n0 && edge.node1 == n1)
                return true;
        }
        return false;
    }

    Edge& getEdge(UINT n0, UINT n1)
    {
        if (n0 > n1) std::swap(n0, n1);
        const Node &node0 = _nodes[n0];
        const UINT edgeCount = (UINT)node0.edges.size();
        for (UINT edgeIndex = 0; edgeIndex < edgeCount; edgeIndex++)
        {
            Edge &edge = _edges[node0.edges[edgeIndex]];
            if (edge.node0 == n0 && edge.node1 == n1)
                return edge;
        }
        return *((Edge*)nullptr);
    }

    void writeToCSV(const std::string &filename, const std::function<std::string(const NodeData&)> &nodeWriter) const
    {
        std::ofstream file(filename);
        const UINT nodeCount = (UINT)_nodes.size();
        file << "Nodes,data,edges";
        for (UINT nodeIndex = 0; nodeIndex < _nodes.size(); nodeIndex++)
            file << "," << nodeIndex;
        file << endl;

        for (UINT nodeIndexA = 0; nodeIndexA < nodeCount; nodeIndexA++)
        {
            file << nodeIndexA << ",";
            file << nodeWriter(_nodes[nodeIndexA].data) << ",";
            file << _nodes[nodeIndexA].edges.size();
            for (UINT nodeIndexB = 0; nodeIndexB < nodeCount; nodeIndexB++)
            {
                if (hasEdge(nodeIndexA, nodeIndexB))
                    file << ",1";
                else
                    file << ",0";
            }
            file << endl;
        }
    }

private:
    vector<Node> _nodes;
    vector<Edge> _edges;
};

typedef UndirectedGraph<int, int> PlainUndirectedGraph;

}

#endif


text:
<?php
class Kwc_Directories_TopChoose_Form extends Kwc_Abstract_Form
{
    public function __construct($name, $class)
    {
        parent::__construct($name, $class);

        $showDirectoryClass = Kwc_Abstract::getSetting($class, 'showDirectoryClass');

        $directories = Kwf_Component_Data_Root::getInstance()
            ->getComponentsByClass($showDirectoryClass, array('ignoreVisible' => true));

        $values = array();
        foreach ($directories as $directory) {
            $title = $directory->getTitle();
            if (Kwc_Abstract::hasSetting($class, 'componentNameShort')) {
                $name = Kwc_Abstract::getSetting($class, 'componentNameShort');
            } else {
                $name = Kwc_Abstract::getSetting($class, 'componentName');
            }
            $name = Kwf_Trl::getInstance()->trlStaticExecute($name);
            if ($title != $name) $title .= ' - ' . $name;
            $values[$directory->dbId] = $title;
        }

        $this->fields->add(new Kwf_Form_Field_Select('directory_component_id', trlKwf('Show')), 300)
            ->setValues($values);
    }
}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * classe Usuarios.
 * Responsavel por registrar novos usuarios, logar no sistema e realizar logoff do sistema.
 *
 * @extends MY_Controller
 */
class Usuarios extends MY_Controller {
	/**
	 * __construct function.
	 *
	 * @access public
	 * @return void
	 */
	public function __construct() {
		parent::__construct();
		$this->load->model('Usuario_model');
	}

	public function index() {

	}

	/**
	 * register function.
	 *
	 * @access public
	 * @return void
	 */
	public function register() {

		$this->dadosView['pagina'] = 'usuario/register/register.php';
		$this->dadosView['template'] = 'site';
		$this->addJs(
			array('jquery.1.11.1.js', 'bootstrap.js'),
			'footer',
			$this->dadosView['template']
		);

		if ($this->Usuario_model->validacoesRegistrar() !== false) {

			$dados = array(
				'tipo_usuario_id' => 1,
				'login' => $this->input->post('login'),
				'email' => $this->input->post('email'),
				'senha' => password_hash($this->input->post('senha'), PASSWORD_BCRYPT),
				'status' => 1
			);

			if (!$this->Usuario_model->inserir($dados)) {
				$this->dadosView['erro'] = 'Houve um problema ao criar sua conta. Tente novamente mais tarde.';
			}
		}

		$this->load->view('container_externo.php',$this->dadosView);
	}

	/**
	 * login function.
	 *
	 * @access public
	 * @return void
	 */
	public function login() {

		if ($this->Usuario_model->validacoesLogar() == false) {

			// validacao falhou, envia os erros para a view
			$this->dadosView['pagina'] = 'usuario/login/login.php';
			$this->dadosView['template'] = 'site';
			$this->load->view('container_externo.php',$this->dadosView);

		} else {

			$login = $this->input->post('login');
			$senha = $this->input->post('senha');

			$usuario = $this->Usuario_model->achePor(
				"(login = '{$login}' or email = '{$login}')
				and status = 1
			");
			if (count($usuario) && password_verify($senha, $usuario[0]->senha)) {

				unset($usuario[0]->senha);

				$_SESSION['usuario'] = $usuario[0];
				$_SESSION['logged_in'] = (bool)true;

				redirect(base_url("admin"));

			} else {
				// login falhou
				$this->dadosView['erro'] = 'Login ou senha incorretos.';

				$this->dadosView['pagina'] = 'usuario/login/login.php';
				$this->dadosView['template'] = 'site';

				$this->load->view('container_externo.php',$this->dadosView);
			}
		}
	}

	/**
	 * funcao que realiza o logout do usuario.
	 *
	 * @access public
	 * @return void
	 */
	public function logout() {

		if (isset($_SESSION)) {
			// remove dados da sessao
			foreach ($_SESSION as $key => $value) {
				unset($_SESSION[$key]);
			}
		}

		redirect(base_url(), 'GET');
	}
}


text:
#ifndef _DEBUG_H
#define _DEBUG_H

/*
*   Include files
*/
#include "general.h"  /* must always come first */

#ifdef DEBUG
# include <assert.h>
#endif
#include "entry.h"

/*
*   Macros
*/

#ifdef DEBUG
# define debug(level)      ((Option.debugLevel & (long)(level)) != 0)
# define DebugStatement(x) x
# define PrintStatus(x)    if (debug(DEBUG_STATUS)) printf x;
# define Assert(c)         assert(c)
#else
# define DebugStatement(x)
# define PrintStatus(x)
# define Assert(c)
# ifndef NDEBUG
#  define NDEBUG
# endif
#endif

/*
*   Data declarations
*/

/*  Defines the debugging levels.
 */
enum eDebugLevels {
	DEBUG_READ   = 0x01,  /* echo raw (filtered) characters */
	DEBUG_PARSE  = 0x02,  /* echo parsing results */
	DEBUG_STATUS = 0x04,  /* echo file status information */
	DEBUG_OPTION = 0x08,  /* echo option parsing */
	DEBUG_CPP    = 0x10,  /* echo characters out of pre-processor */
	DEBUG_RAW    = 0x20   /* echo raw (filtered) characters */
};

/*
*   Function prototypes
*/
extern void lineBreak (void);
extern void debugPrintf (const enum eDebugLevels level, const char *const format, ...) __printf__ (2, 3);
extern void debugPutc (const int level, const int c);
extern void debugParseNest (const boolean increase, const unsigned int level);
extern void debugCppNest (const boolean begin, const unsigned int level);
extern void debugCppIgnore (const boolean ignore);
extern void debugEntry (const tagEntryInfo *const tag);

#endif  /* _DEBUG_H */

/* vi:set tabstop=4 shiftwidth=4: */


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

namespace Fcds\Ivvy\Model\Validator;

use Iterator;
use Fcds\Ivvy\Model\Company;

/**
 * Class: UpdateCompanyValidatorTest
 *
 * Contains the business rules for adding a Company.
 *
 * @see Validator
 */
class UpdateCompanyValidator implements Validator
{
    use ProcessBusinessRuleTrait;

    protected function process(Company $company): Iterator
    {
        if (! $company->id) {
            yield 'An id is needed to update a Company';
        }

        if (! $company->address || ! $company->address->countryCode ||
            ! $company->address->stateCode || ! $company->address->postalCode) {
            yield 'An address with countryCode, stateCode and postalCode is needed to add a Company';
        }

        yield;
    }
}