text:
extern void barfOutStackPointer();

uint16_t PanelComponent::flasherCounter = 0;
uint16_t PanelComponent::fastFlasherCounter = 0;
uint16_t PanelComponent::flasherCounterMax = 333;
uint16_t PanelComponent::fastFlasherCounterMax = 100;
uint8_t PanelComponent::flasherState = 1;
uint8_t PanelComponent::fastFlasherState = 1;

void PanelComponent::freshenStatic( uint16_t msTickDelta ){
	flasherCounter += msTickDelta;
	if( flasherCounter > flasherCounterMax )
	{
		flasherCounter -= flasherCounterMax;
		flasherState ^= 0x01;
	}
	fastFlasherCounter += msTickDelta;
	if( fastFlasherCounter > fastFlasherCounterMax )
	{
		fastFlasherCounter -= fastFlasherCounterMax;
		fastFlasherState ^= 0x01;
	}
};

//---Button------------------------------------------------------
void Button::setHardware( GenericHardwareDescription * input, bool invertInput )
{
	hardwareInterface = input;
	invert = invertInput;

	freshen( 1 );

	state = BUTTONOFF;

	risingEdgeFlag = 0;
	fallingEdgeFlag = 0;
	holdRisingEdgeFlag = 0;
	holdFallingEdgeFlag = 0;
	beingHeld = 0;

}

bool Button::hasFreshData( void )
{
	uint8_t returnVar = 0;
	if( risingEdgeFlag || fallingEdgeFlag || holdRisingEdgeFlag || holdFallingEdgeFlag )
	{
		returnVar = 1;
	}
	return returnVar;
}

void Button::freshen( uint16_t msTickDelta )
{
	//Cause the interface to get the data
	hardwareInterface->readHardware();

	//Collect the data
	ButtonDataObject tempObject;
	hardwareInterface->getData(&tempObject);
	//if( tempObject.size <= 0 )
	//{
	//	return;
	//}
	//else
	//{
	//	return *tempObject.data;
	//}
	*tempObject.data ^= (uint8_t)invert;  //Do the inversion here

	//Update any time related things
	buttonDebounceTimeKeeper.mIncrement( msTickDelta );

	//Process state machine
	buttonState_t nextState = state;
	switch( state )
	{
	case BUTTONOFF: //Last state was BUTTONOFF
		if(( *tempObject.data == 1 ) && ( buttonDebounceTimeKeeper.mGet() > 50 ))
		{
			//Start the timer
			buttonDebounceTimeKeeper.mClear();
			nextState = BUTTONON;
			risingEdgeFlag = 1;
		}
		else
		{
			nextState = BUTTONOFF;
		}
		break;
	case BUTTONON: //Last state was BUTTONON
		if( *tempObject.data == 1 )
		{
			if( buttonDebounceTimeKeeper.mGet() > 1000 )
			{
				nextState = BUTTONHOLD;
				holdRisingEdgeFlag = 1;
			}
		}
		//No break;, do buttonhold's state too
	case BUTTONHOLD: //In the process of holding
		if( *tempObject.data == 0 )
		{
			buttonDebounceTimeKeeper.mClear();
			nextState = BUTTONOFF;
			fallingEdgeFlag = 1;
		}
		break;
	default:
		break;
	}
	state = nextState;
}

buttonState_t Button::getState( void )
{
	return state;
}

uint8_t Button::serviceRisingEdge( void )
{
	uint8_t returnVar = 0;
	if( risingEdgeFlag == 1 )
	{
		risingEdgeFlag = 0;
		returnVar = 1;
	}

	return returnVar;
}

uint8_t Button::serviceFallingEdge( void )
{
	uint8_t returnVar = 0;
	if( fallingEdgeFlag == 1 )
	{
		fallingEdgeFlag = 0;
		returnVar = 1;
	}

	return returnVar;
}

uint8_t Button::serviceHoldRisingEdge( void )
{
	uint8_t returnVar = 0;
	if( holdRisingEdgeFlag == 1 )
	{
		holdRisingEdgeFlag = 0;
		returnVar = 1;
	}

	return returnVar;
}

uint8_t Button::serviceHoldFallingEdge( void )
{
	uint8_t returnVar = 0;
	if( holdFallingEdgeFlag == 1 )
	{
		holdFallingEdgeFlag = 0;
		returnVar = 1;
	}

	return returnVar;
}

//---Led---------------------------------------------------------
void Led::setHardware( GenericHardwareDescription * input, bool invertInput )
{
	//flasherState = flasherAddress;
	//fastFlasherState = fastFlasherAddress;
	//flasherState = 1;
	//fastFlasherState = 1;
	hardwareInterface = input;
	invert = invertInput;
}

void Led::freshen( uint16_t msTickDelta )
{
	uint8_t outputValue = 0;
	switch(state)
	{
	case LEDON:
		outputValue = 1;
		break;
	case LEDFLASHING:
		outputValue = flasherState;
		break;
	case LEDFLASHINGFAST:
		outputValue = fastFlasherState;
		break;
	default:
	case LEDOFF:
		outputValue = 0;
		break;
	}

	//Give the output
	LedDataObject outputData;
	*outputData.data = outputValue ^ invert;
	hardwareInterface->setData(&outputData);
	//Cause the interface to send the data
	hardwareInterface->writeHardware();

}

ledState_t Led::getState( void )
{
	return state;

}

void Led::setState( ledState_t inputValue )
{
	state = inputValue;

}

void Led::toggle( void )
{
	switch(state)
	{
	case LEDON:
		state = LEDOFF;
		break;
	case LEDOFF:
		state = LEDON;
		break;
	default:
		break;
	}
}

//---KnobParentClass--------------------------------------------------------
KnobParentClass::KnobParentClass( void )
{
	newData = 0;
}

void KnobParentClass::setHardware( GenericHardwareDescription * input )
{
	hardwareInterface = input;
}

bool KnobParentClass::hasFreshData( void )
{
	if( newData )
	{
		return 1;
	}
	else
	{
		return 0;
	}

}

bool KnobParentClass::serviceChanged( void )
{
	if( newData )
	{
		newData = false;
		return true;
	}
	else
	{
		return false;
	}

}

//---Simple8BitKnob---------------------------------------------------------
void Simple8BitKnob::freshen( uint16_t msTickDelta )
{
	//Throw away input
	//Cause the interface to get the data
	hardwareInterface->readHardware();
	//Collect the data
	KnobDataObject tempObject;
	hardwareInterface->getData(&tempObject);

	state = *(uint16_t *)tempObject.data >> 2;
	if( state != lastState )
	{
		newData = 1;
		lastState = state;
	}

}

uint8_t Simple8BitKnob::getState( void )
{
   return state;
}

//---Simple10BitKnob--------------------------------------------------------
void Simple10BitKnob::freshen( uint16_t msTickDelta )
{
	//Throw away input
	hardwareInterface->readHardware();
	//Collect the data
	KnobDataObject tempObject;
//	KnobDataObject * tempObject = new KnobDataObject;
//		Serial.println("knobFreshen");
//		Serial.print("Temp ");
//		dumpObject(&tempObject);
//Serial.print((uint32_t)&(*tempObject), HEX);
//Serial.println("Created");
	hardwareInterface->getData(&tempObject);

	int16_t tempState = *(uint16_t *)tempObject.data;
	int8_t tempSlope = 0;
	state = tempState;
	int8_t histDirTemp = 0;
	if( state > lastState )
	{
		tempSlope = 1;
		if( lastSlope == 1 ) histDirTemp = 1;
	}
	else if( state < lastState )
	{
		tempSlope = -1;
		if( lastSlope == -1 ) histDirTemp = -1;
	}
	if( tempSlope != 0 )
	{
		if( state > (uint32_t)lastState + hysteresis || histDirTemp == 1)
		{
			newData = 1;
			lastState = state;
			lastSlope = tempSlope;
		}
		if( state < (uint32_t)lastState - hysteresis || histDirTemp == -1 )
		{
			newData = 1;
			lastState = state;
			lastSlope = tempSlope;
		}

	}
//Serial.print("Temp ");
//dumpObject(tempObject);
//Serial.print((uint32_t)&(*tempObject), HEX);
//Serial.println("Destroyed");
//	delete tempObject;

}

void Simple10BitKnob::setHysteresis( uint8_t input )
{
	hysteresis = input;
}

uint16_t Simple10BitKnob::getState( void )
{
  return state;
}

//---Complex10BitKnob--------------------------------------------
void Complex10BitKnob::freshen( uint16_t msTickDelta )
{
	//Throw away input
	//Cause the interface to get the data
	hardwareInterface->readHardware();
	//Collect the data
	KnobDataObject tempObject;
	hardwareInterface->getData(&tempObject);

//		Serial.println("knobFreshen");
//		Serial.print("Temp ");
//		dumpObject(&tempObject);

	uint16_t tempState = *(uint16_t *)tempObject.data;
	//Read the knob value into the buffer
	//Serial.println(tempState);

	currentValue = tempState;
}

uint16_t Complex10BitKnob::getState( void )
{
  return (uint16_t)currentValue;
}

uint8_t Complex10BitKnob::getAsUInt8( void )
{
	newData = 0;
	return currentValue >> 2;
}
int16_t Complex10BitKnob::getAsInt16( void )
{
	uint32_t tempValue = currentValue;
	if( tempValue < lowerKnobVal ) tempValue = lowerKnobVal;
	if( tempValue > upperKnobVal ) tempValue = upperKnobVal;
	// now find scalar from 0 to 1
	float inputPercent = ((float)(tempValue - lowerKnobVal))/(float)(upperKnobVal - lowerKnobVal);
	float outputRange = upperIntVal - lowerIntVal;
	newData = 0;
	return lowerIntVal + (inputPercent * outputRange);
}
uint16_t Complex10BitKnob::getAsUInt16( void )
{
	uint32_t tempValue = currentValue;
	if( tempValue < lowerKnobVal ) tempValue = lowerKnobVal;
	if( tempValue > upperKnobVal ) tempValue = upperKnobVal;
	// now find scalar from 0 to 1
	float inputPercent = ((float)(tempValue - lowerKnobVal))/(float)(upperKnobVal - lowerKnobVal);
	float outputRange = upperUIntVal - lowerUIntVal;
	newData = 0;
	return lowerUIntVal + (inputPercent * outputRange);
}
float Complex10BitKnob::getAsFloat( void )
{
	uint32_t tempValue = currentValue;
	if( tempValue < lowerKnobVal ) tempValue = lowerKnobVal;
	if( tempValue > upperKnobVal ) tempValue = upperKnobVal;
	// now find scalar from 0 to 1
	float inputPercent = ((float)(tempValue - lowerKnobVal))/(float)(upperKnobVal - lowerKnobVal);
	float outputRange = upperFloatVal - lowerFloatVal;
	newData = 0;
	return lowerFloatVal + (inputPercent * outputRange);
}

void Complex10BitKnob::setLowerKnobVal( uint16_t input )
{
	if( input < 0 )input = 0;
	if( input > 1023 )input = 1023;
	lowerKnobVal = input;
}

void Complex10BitKnob::setUpperKnobVal( uint16_t input )
{
	if( input < 0 )input = 0;
	if( input > 1023 )input = 1023;
	upperKnobVal = input;
}

void Complex10BitKnob::setLowerFloatVal( float input )
{
	lowerFloatVal = input;
}

void Complex10BitKnob::setUpperFloatVal( float input )
{
	upperFloatVal = input;
}

void Complex10BitKnob::setLowerIntVal( int16_t input )
{
	lowerIntVal = input;
}

void Complex10BitKnob::setUpperIntVal( int16_t input )
{
	upperIntVal = input;
}

void Complex10BitKnob::setLowerUIntVal( uint16_t input )
{
	lowerUIntVal = input;
}

void Complex10BitKnob::setUpperUIntVal( uint16_t input )
{
	upperUIntVal = input;
}

//---Hysteresis10BitKnob--------------------------------------------------------
Hysteresis10BitKnob::Hysteresis10BitKnob( void ) : values(16), averages(16)
{
}
void Hysteresis10BitKnob::freshen( uint16_t msTickDelta )
{
	//Throw away input
	//Cause the interface to get the data
	hardwareInterface->readHardware();
	//Collect the data
	KnobDataObject tempObject;
	hardwareInterface->getData(&tempObject);

//		Serial.println("knobFreshen");
//		Serial.print("Temp ");
//		dumpObject(&tempObject);

	uint16_t tempState = *(uint16_t *)tempObject.data;
	//Read the knob value into the buffer
	//Serial.println(tempState);
	values.write(tempState);
	int32_t accumulator = 0;
	for( int i = 0; i < samplesAveraged; i++ )
	{
		accumulator += values.read(i);
	}
	averages.write(accumulator/samplesAveraged);
	if(hystState == 0)
	{
		if( averages.read(0) > currentValue )
		{
			//Allow current to go up only
			currentValue = averages.read(0);
			newData = 1;
		}
		if( averages.read(0) < currentValue - hysteresis )
		{
			//toggle behavior
			hystState = 1;
			currentValue = averages.read(0);
			newData = 1;
		}
	}
	else
	{
		if( averages.read(0) < currentValue )
		{
			//Allow current to go up only
			currentValue = averages.read(0);
			newData = 1;
		}
		if( averages.read(0) > currentValue + hysteresis )
		{
			//toggle behavior
			hystState = 0;
			currentValue = averages.read(0);
			newData = 1;
		}
	}

}

void Hysteresis10BitKnob::setHysteresis( uint8_t input )
{
	hysteresis = input;
}

void Hysteresis10BitKnob::setSamplesAveraged( uint8_t input )
{
	samplesAveraged = input;
}

//---Windowed10BitKnob--------------------------------------------------------
Windowed10BitKnob::Windowed10BitKnob( void ) : values(16), averages(16)
{
}

void Windowed10BitKnob::freshen( uint16_t msTickDelta )
{
	//Throw away input
	//Cause the interface to get the data
	hardwareInterface->readHardware();
	//Collect the data
	KnobDataObject tempObject;
	hardwareInterface->getData(&tempObject);

//		Serial.println("knobFreshen");
//		Serial.print("Temp ");
//		dumpObject(&tempObject);

	uint16_t tempState = *(uint16_t *)tempObject.data;
	//Read the knob value into the buffer
	//Serial.println(tempState);
	values.write(tempState);
	int32_t accumulator = 0;
	for( int i = 0; i < samplesAveraged; i++ )
	{
		accumulator += values.read(i);
	}
	averages.write(accumulator/samplesAveraged);
	if( averages.read(0) > windowUpper )
	{
		moveWindowUpper( averages.read(0) );
		newData = 1;
	}
	if( averages.read(0) < windowLower )
	{
		moveWindowLower( averages.read(0) );
		newData = 1;
	}
	uint32_t temp = windowLower + (window >> 1);
	//scale it
	currentValue = ((temp - (window >> 1)) << 10 ) / (1024 - window );
}

void Windowed10BitKnob::setSamplesAveraged( uint8_t input )
{
	samplesAveraged = input;
}

void Windowed10BitKnob::setWindow( int16_t input )
{
	window = input;
}

void Windowed10BitKnob::moveWindowUpper( uint16_t input )
{
	windowUpper = input;
	windowLower = input - window;
}

void Windowed10BitKnob::moveWindowLower( uint16_t input )
{
	windowLower = input;
	windowUpper = input + window;

}


text:
package org.apache.flink.sql.parser.hive.ddl;

import org.apache.calcite.sql.SqlIdentifier;
import org.apache.calcite.sql.SqlNodeList;
import org.apache.calcite.sql.SqlWriter;
import org.apache.calcite.sql.parser.SqlParserPos;

import static org.apache.flink.sql.parser.hive.ddl.SqlAlterHiveTable.AlterTableOp.CHANGE_FILE_FORMAT;

/** ALTER TABLE DDL to change a Hive table/partition's file format. */
public class SqlAlterHiveTableFileFormat extends SqlAlterHiveTable {

    private final SqlIdentifier format;

    public SqlAlterHiveTableFileFormat(
            SqlParserPos pos, SqlIdentifier tableName, SqlNodeList partSpec, SqlIdentifier format) {
        super(CHANGE_FILE_FORMAT, pos, tableName, partSpec, createPropList(format));
        this.format = format;
    }

    @Override
    public void unparse(SqlWriter writer, int leftPrec, int rightPrec) {
        super.unparse(writer, leftPrec, rightPrec);
        writer.keyword("SET FILEFORMAT");
        format.unparse(writer, leftPrec, rightPrec);
    }

    private static SqlNodeList createPropList(SqlIdentifier format) {
        SqlNodeList res = new SqlNodeList(format.getParserPosition());
        res.add(
                HiveDDLUtils.toTableOption(
                        SqlCreateHiveTable.HiveTableStoredAs.STORED_AS_FILE_FORMAT,
                        format.getSimple(),
                        format.getParserPosition()));
        return res;
    }
}

redpajama_set_name: RedPajamaGithub


text:
/**
 * @license Angular v4.0.1
 * (c) 2010-2017 Google, Inc. https://angular.io/
 * License: MIT
 */
 export * from './browser/index'


text:
package aya.exceptions.runtime;

import aya.obj.symbol.Symbol;
import aya.obj.symbol.SymbolConstants;

/**
 * A special runtime exception with a basic message. The exception is
 * caught by the interpreter and its message is printed.
 * @author Nick
 *
 */
@SuppressWarnings("serial")
public class UndefVarException extends InternalAyaRuntimeException {

	public UndefVarException(Symbol var) {
		super(SymbolConstants.UNDEF_VAR, "Undefined variable '" + var.name() +"'");
	}

}


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

using DotMaysWind.Data.Command.Condition;
using DotMaysWind.Data.Command.Join;

namespace DotMaysWind.Data.Command
{
    /// <summary>
    /// SQL语句创建类
    /// </summary>
    internal class SqlCommandBuilder
    {
        #region 字段
        private StringBuilder _stringBuilder;
        private DatabaseType _dbType;
        #endregion

        #region 构造方法
        /// <summary>
        /// 初始化SQL语句创建类
        /// </summary>
        /// <param name="dbType">数据库类型</param>
        internal SqlCommandBuilder(DatabaseType dbType)
        {
            this._stringBuilder = new StringBuilder();
            this._dbType = dbType;
        }
        #endregion

        #region 方法
        #region 添加固定字符串
        /*/// <summary>
        /// 添加SQL左括号并返回当前SQL语句创建类
        /// </summary>
        /// <returns>当前SQL语句创建类</returns>
        internal SqlCommandBuilder AppendLeftParentheses()
        {
            this._stringBuilder.Append("( ");
            return this;
        }

        /// <summary>
        /// 添加SQL右括号并返回当前SQL语句创建类
        /// </summary>
        /// <returns>当前SQL语句创建类</returns>
        internal SqlCommandBuilder AppendRightParentheses()
        {
            this._stringBuilder.Append(") ");
            return this;
        }*/

        /// <summary>
        /// 添加SQL添加语句前缀并返回当前SQL语句创建类
        /// </summary>
        /// <returns>当前SQL语句创建类</returns>
        internal SqlCommandBuilder AppendInsertPrefix()
        {
            this._stringBuilder.Append(" INSERT INTO ");
            return this;
        }

        /// <summary>
        /// 添加SQL更新语句前缀并返回当前SQL语句创建类
        /// </summary>
        /// <returns>当前SQL语句创建类</returns>
        internal SqlCommandBuilder AppendUpdatePrefix()
        {
            this._stringBuilder.Append(" UPDATE ");
            return this;
        }

        /// <summary>
        /// 添加SQL删除语句前缀并返回当前SQL语句创建类
        /// </summary>
        /// <returns>当前SQL语句创建类</returns>
        internal SqlCommandBuilder AppendDeletePrefix()
        {
            this._stringBuilder.Append(" DELETE FROM ");
            return this;
        }

        /// <summary>
        /// 添加SQL选择语句前缀并返回当前SQL语句创建类
        /// </summary>
        /// <returns>当前SQL语句创建类</returns>
        internal SqlCommandBuilder AppendSelectPrefix()
        {
            this._stringBuilder.Append(" SELECT ");
            return this;
        }

        /// <summary>
        /// 添加SQL插入语句结果并返回当前SQL语句创建类
        /// </summary>
        /// <returns>当前SQL语句创建类</returns>
        internal SqlCommandBuilder AppendInsertValues()
        {
            this._stringBuilder.Append("VALUES ");
            return this;
        }

        /// <summary>
        /// 添加SQL更新语句设置并返回当前SQL语句创建类
        /// </summary>
        /// <returns>当前SQL语句创建类</returns>
        internal SqlCommandBuilder AppendUpdateSet()
        {
            this._stringBuilder.Append("SET ");
            return this;
        }
        #endregion

        #region 添加数据字段名或参数名
        /// <summary>
        /// 添加所有数据字段名并返回当前SQL语句创建类
        /// </summary>
        /// <param name="queryFields">数据字段名</param>
        /// <returns>当前SQL语句创建类</returns>
        internal SqlCommandBuilder AppendAllColumnNames(List<SqlQueryField> queryFields)
        {
            if (queryFields != null && queryFields.Count > 0)
            {
                StringBuilder names = new StringBuilder();

                for (Int32 i = 0; i < queryFields.Count; i++)
                {
                    if (i > 0) names.Append(",");

                    SqlQueryField queryField = queryFields[i];

                    if (queryField.UseFunction)
                    {
                        names.Append(queryField.Function);
                    }

                    if (!String.IsNullOrEmpty(queryField.FieldName))
                    {
                        if (queryField.UseFunction)
                        {
                            names.Append('(');
                        }

                        if (!String.IsNullOrEmpty(queryField.TableName))
                        {
                            names.Append(queryField.TableName).Append('.');
                        }

                        names.Append(queryField.FieldName);

                        if (queryField.UseFunction)
                        {
                            names.Append(')');
                        }
                    }

                    if (!String.IsNullOrEmpty(queryField.AliasesName))
                    {
                        names.Append(" AS ").Append(queryField.AliasesName);
                    }
                }

                this._stringBuilder.Append(names.ToString()).Append(' ');
            }
            else
            {
                this._stringBuilder.Append("* ");
            }

            return this;
        }

        /// <summary>
        /// 添加所有参数组中数据字段名并返回当前SQL语句创建类
        /// </summary>
        /// <param name="dbParams">参数组列表</param>
        /// <returns>当前SQL语句创建类</returns>
        internal SqlCommandBuilder AppendAllColumnNames(List<SqlParameter> dbParams)
        {
            if (dbParams != null && dbParams.Count > 0)
            {
                StringBuilder names = new StringBuilder();

                for (Int32 i = 0; i < dbParams.Count; i++)
                {
                    if (i > 0) names.Append(",");
                    names.Append(dbParams[i].ColumnName);
                }

                this._stringBuilder.Append(names.ToString()).Append(' ');
            }

            return this;
        }

        /// <summary>
        /// 添加所有参数组中数据字段名及小括号并返回当前SQL语句创建类
        /// </summary>
        /// <param name="dbParams">参数组列表</param>
        /// <returns>当前SQL语句创建类</returns>
        internal SqlCommandBuilder AppendAllColumnNamesWithParentheses(List<SqlParameter> dbParams)
        {
            if (dbParams != null && dbParams.Count > 0)
            {
                this._stringBuilder.Append("( ");
                this.AppendAllColumnNames(dbParams);
                this._stringBuilder.Append(") ");
            }

            return this;
        }

        /// <summary>
        /// 添加所有参数组中参数名并返回当前SQL语句创建类
        /// </summary>
        /// <param name="dbParams">参数组列表</param>
        /// <returns>当前SQL语句创建类</returns>
        internal SqlCommandBuilder AppendAllParameterNames(List<SqlParameter> dbParams)
        {
            if (dbParams != null && dbParams.Count > 0)
            {
                StringBuilder names = new StringBuilder();

                for (Int32 i = 0; i < dbParams.Count; i++)
                {
                    if (i > 0) names.Append(",");
                    names.Append(dbParams[i].ParameterName);
                }

                this._stringBuilder.Append(names.ToString()).Append(' ');
            }

            return this;
        }

        /// <summary>
        /// 添加所有参数组中参数名及小括号并返回当前SQL语句创建类
        /// </summary>
        /// <param name="dbParams">参数组列表</param>
        /// <returns>当前SQL语句创建类</returns>
        internal SqlCommandBuilder AppendAllParameterNamesWithParentheses(List<SqlParameter> dbParams)
        {
            if (dbParams != null && dbParams.Count > 0)
            {
                this._stringBuilder.Append("( ");
                this.AppendAllParameterNames(dbParams);
                this._stringBuilder.Append(") ");
            }

            return this;
        }

        /// <summary>
        /// 添加所有参数组等式并返回当前SQL语句创建类
        /// </summary>
        /// <param name="dbParams">参数组列表</param>
        /// <returns>当前SQL语句创建类</returns>
        internal SqlCommandBuilder AppendAllParameterEquations(List<SqlParameter> dbParams)
        {
            if (dbParams != null && dbParams.Count > 0)
            {
                StringBuilder names = new StringBuilder();

                for (Int32 i = 0; i < dbParams.Count; i++)
                {
                    if (i > 0) names.Append(",");

                    names.Append(dbParams[i].ColumnName).Append('=');

                    if (dbParams[i].IsUseParameter)
                    {
                        names.Append(dbParams[i].ParameterName);
                    }
                    else
                    {
                        names.Append(dbParams[i].Value.ToString());
                    }
                }

                this._stringBuilder.Append(names.ToString()).Append(' ');
            }

            return this;
        }
        #endregion

        #region 添加数据表名
        /// <summary>
        /// 添加SQL数据表名并返回当前SQL语句创建类
        /// </summary>
        /// <param name="tableName">数据表名</param>
        /// <returns>当前SQL语句创建类</returns>
        internal SqlCommandBuilder AppendTableName(String tableName)
        {
            this._stringBuilder.Append(tableName).Append(' ');
            return this;
        }

        /// <summary>
        /// 添加SQL选择语句来自并返回当前SQL语句创建类
        /// </summary>
        /// <param name="from">数据表名或SQL语句</param>
        /// <param name="isFromSql">是否从SQL语句中选择</param>
        /// <param name="joins">Sql连接语句列表</param>
        /// <returns>当前SQL语句创建类</returns>
        internal SqlCommandBuilder AppendSelectFromAndJoins(String from, Boolean isFromSql, List<ISqlJoin> joins)
        {
            Boolean hasJoins = (joins != null && joins.Count > 0);

            this._stringBuilder.Append("FROM ");

            if (!hasJoins)
            {
                this._stringBuilder.Append(from).Append(' ');
            }
            else
            {
                StringBuilder sb = new StringBuilder();

                sb.Append(from).Append(' ').Append(joins[0].ToString());

                if (joins.Count > 1)
                {
                    sb.Insert(0, '(').Append(')');

                    for (Int32 i = 1; i < joins.Count; i++)
                    {
                        sb.Append(' ');
                        sb.Append(joins[i].ToString());
                        sb.Insert(0, '(').Append(')');
                    }
                }

                this._stringBuilder.Append(sb.ToString()).Append(' ');
            }

            return this;
        }

        /// <summary>
        /// 添加SQL选择语句来自并返回当前SQL语句创建类
        /// </summary>
        /// <param name="from">数据表名或SQL语句</param>
        /// <param name="isFromSql">是否从SQL语句中选择</param>
        /// <returns>当前SQL语句创建类</returns>
        internal SqlCommandBuilder AppendSelectFrom(String from, Boolean isFromSql)
        {
            return this.AppendSelectFromAndJoins(from, isFromSql, null);
        }
        #endregion

        #region 添加查询语句
        /// <summary>
        /// 添加SQL Where查询语句并返回当前SQL语句创建类
        /// </summary>
        /// <param name="condition">Where条件语句</param>
        /// <returns>当前SQL语句创建类</returns>
        internal SqlCommandBuilder AppendWhere(ISqlCondition condition)
        {
            if (condition != null)
            {
                this._stringBuilder.Append("WHERE ").Append(condition.ToString()).Append(' ');
            }

            return this;
        }

        /// <summary>
        /// 添加SQL Having查询语句并返回当前SQL语句创建类
        /// </summary>
        /// <param name="condition">Having条件语句</param>
        /// <returns>当前SQL语句创建类</returns>
        internal SqlCommandBuilder AppendHaving(ISqlCondition condition)
        {
            if (condition != null)
            {
                this._stringBuilder.Append("HAVING ").Append(condition.ToString()).Append(' ');
            }

            return this;
        }
        #endregion

        #region 添加选择语句
        /// <summary>
        /// 添加SQL选择页面大小并返回当前SQL语句创建类
        /// </summary>
        /// <param name="pageSize">页面大小</param>
        /// <returns>当前SQL语句创建类</returns>
        internal SqlCommandBuilder AppendSelectTop(Int32 pageSize)
        {
            if (pageSize > 0)
            {
                this._stringBuilder.Append("TOP ").Append(pageSize.ToString()).Append(' ');
            }

            return this;
        }

        /// <summary>
        /// 添加SQL选择页面大小并返回当前SQL语句创建类
        /// </summary>
        /// <param name="recordStart">开始记录索引</param>
        /// <param name="pageSize">页面大小</param>
        /// <returns>当前SQL语句创建类</returns>
        internal SqlCommandBuilder AppendSelectLimit(Int32 recordStart, Int32 pageSize)
        {
            if (pageSize > 0)
            {
                this._stringBuilder.Append("LIMIT ");

                if (recordStart > 0)
                {
                    this._stringBuilder.Append(recordStart.ToString()).Append(',');
                }

                this._stringBuilder.Append(pageSize.ToString()).Append(' ');
            }

            return this;
        }

        /// <summary>
        /// 添加SQL选择页面大小并返回当前SQL语句创建类
        /// </summary>
        /// <param name="pageSize">页面大小</param>
        /// <returns>当前SQL语句创建类</returns>
        internal SqlCommandBuilder AppendSelectLimit(Int32 pageSize)
        {
            return this.AppendSelectLimit(0, pageSize);
        }

        /// <summary>
        /// 添加SQL选择语句唯一并返回当前SQL语句创建类
        /// </summary>
        /// <param name="isDistinct">是否选择语句唯一</param>
        /// <returns>当前SQL语句创建类</returns>
        internal SqlCommandBuilder AppendSelectDistinct(Boolean isDistinct)
        {
            if (isDistinct)
            {
                this._stringBuilder.Append("DISTINCT ");
            }

            return this;
        }

        /// <summary>
        /// 添加SQL分组语句并返回当前SQL语句创建类
        /// </summary>
        /// <param name="groupBys">Group By语句集合</param>
        /// <returns>当前SQL语句创建类</returns>
        internal SqlCommandBuilder AppendSelectGroupBys(List<String> groupBys)
        {
            if (groupBys != null && groupBys.Count > 0)
            {
                this._stringBuilder.Append("GROUP BY ");

                StringBuilder names = new StringBuilder();

                for (Int32 i = 0; i < groupBys.Count; i++)
                {
                    if (i > 0) names.Append(",");
                    names.Append(groupBys[i]);
                }

                this._stringBuilder.Append(names.ToString()).Append(' ');
            }

            return this;
        }

        /// <summary>
        /// 添加所有排序并返回当前SQL语句创建类
        /// </summary>
        /// <param name="orders">查询字段名数组</param>
        /// <param name="orderReverse">是否取反</param>
        /// <returns>当前SQL语句创建类</returns>
        internal SqlCommandBuilder AppendSelectOrderBys(List<SqlOrder> orders, Boolean orderReverse)
        {
            if (orders != null && orders.Count > 0)
            {
                this._stringBuilder.Append("ORDER BY ");

                StringBuilder names = new StringBuilder();

                for (Int32 i = 0; i < orders.Count; i++)
                {
                    if (i > 0) names.Append(",");
                    names.Append(orders[i].FieldName);
                    names.Append(orders[i].GetOrderType(orderReverse) == SqlOrderType.Desc ? " DESC" : " ASC");
                }

                this._stringBuilder.Append(names.ToString()).Append(' ');
            }

            return this;
        }
        #endregion

        #region 输出SQL语句结果
        /// <summary>
        /// 输出SQL语句结果
        /// </summary>
        /// <returns>SQL语句结果</returns>
        public override String ToString()
        {
            return this._stringBuilder.ToString();
        }
        #endregion
        #endregion
    }
}


text:
package com.jiwhiz.rest.site;

import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn;

import javax.inject.Inject;

import org.springframework.data.web.PagedResourcesAssembler;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.ResourceAssembler;
import org.springframework.stereotype.Component;

import com.jiwhiz.domain.post.BlogPost;
import com.jiwhiz.domain.post.CommentPost;
import com.jiwhiz.domain.post.CommentPostRepository;
import com.jiwhiz.domain.post.CommentStatusType;
import com.jiwhiz.rest.ResourceNotFoundException;

/**
 * @author Yuan Ji
 */
@Component
public class PublicBlogResourceAssembler implements ResourceAssembler<BlogPost, PublicBlogResource> {
    private final CommentPostRepository commentPostRepository;
    private final PagedResourcesAssembler<CommentPost> assembler;

    @Inject
    public PublicBlogResourceAssembler(
            CommentPostRepository commentPostRepository,
            PagedResourcesAssembler<CommentPost> assembler) {
        this.commentPostRepository = commentPostRepository;
        this.assembler = assembler;
    }

    @Override
    public PublicBlogResource toResource(BlogPost entity) {
        PublicBlogResource resource = new PublicBlogResource(entity);
        resource.setApprovedCommentCount(commentPostRepository.countByBlogPostIdAndStatus(entity.getId(), CommentStatusType.APPROVED));
        try {
            resource.add(linkTo(methodOn(PublicBlogRestController.class).getPublicBlogPostById(entity.getId()))
                    .withSelfRel());

            Link commentsLink = linkTo(methodOn(PublicBlogRestController.class)
                    .getBlogApprovedCommentPosts(entity.getId(), null, null))
                    .withRel(PublicBlogResource.LINK_NAME_COMMENTS);
            resource.add(assembler.appendPaginationParameterTemplates(commentsLink));

            resource.add(linkTo(methodOn(WebsiteRestController.class).getUserProfile(entity.getAuthorId()))
                    .withRel(PublicBlogResource.LINK_NAME_AUTHOR));
        } catch (ResourceNotFoundException ex) {
            //do nothing
        }
        return resource;
    }

}


text: Broca Classifier


text:
<?php

/* @Framework/Form/button_label.html.php */
class __TwigTemplate_4e64828ef32c44ca5d7f93ddec1d0bfb3776795e11844c715ed2037a74770366 extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = false;

        $this->blocks = array(
        );
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $__internal_69c592b820b3d1f21a6e89649ca37291ddd46787affb12583dc104e059959b7b = $this->env->getExtension("Symfony\\Bridge\\Twig\\Extension\\ProfilerExtension");
        $__internal_69c592b820b3d1f21a6e89649ca37291ddd46787affb12583dc104e059959b7b->enter($__internal_69c592b820b3d1f21a6e89649ca37291ddd46787affb12583dc104e059959b7b_prof = new Twig_Profiler_Profile($this->getTemplateName(), "template", "@Framework/Form/button_label.html.php"));

        $__internal_69c592b820b3d1f21a6e89649ca37291ddd46787affb12583dc104e059959b7b->leave($__internal_69c592b820b3d1f21a6e89649ca37291ddd46787affb12583dc104e059959b7b_prof);

    }

    public function getTemplateName()
    {
        return "@Framework/Form/button_label.html.php";
    }

    public function getDebugInfo()
    {
        return array ();
    }

    /** @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead */
    public function getSource()
    {
        @trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED);

        return $this->getSourceContext()->getCode();
    }

    public function getSourceContext()
    {
        return new Twig_Source("", "@Framework/Form/button_label.html.php", "D:\\wamp64\\www\\serveurDeVoeux\\vendor\\symfony\\symfony\\src\\Symfony\\Bundle\\FrameworkBundle\\Resources\\views\\Form\\button_label.html.php");
    }
}


text:
'use strict';

// Gets project name from print styles
// They're included on any page as of 2019-12-02 with following structure:
//

//   {workspace_name}
//   projectName
//

function getProjectName () {
  const printHeaderElem = document.querySelector('#header_print');

  return printHeaderElem && printHeaderElem.lastChild && printHeaderElem.lastChild.nodeValue
    ? printHeaderElem.lastChild.nodeValue.trim()
    : '';
}

// Task view
togglbutton.render('.task:not(.toggl)', { observe: true }, function (elem) {
  function getDescription () {
    // Task details view
    const descriptionElem = elem.querySelector('h1 > a');
    if (descriptionElem) return descriptionElem.textContent.trim();

    // Task modal view
    const descriptionModalElem = document.querySelector('#TB_title .name a');
    return descriptionModalElem ? descriptionModalElem.textContent.trim() : '';
  }

  const link = togglbutton.createTimerLink({
    className: 'worksection-taskview',
    description: getDescription,
    projectName: getProjectName
  });

  const root = document.querySelector('.buts_menu');
  if (root) {
    root.appendChild(link);
  }
});

// Tasks list
togglbutton.render('#tasks_images .item:not(.toggl)', { observe: true }, function (elem) {
  function getDescription () {
    const descriptionElem = elem.querySelector('.name > a');
    return descriptionElem ? descriptionElem.textContent.trim() : '';
  }

  const link = togglbutton.createTimerLink({
    buttonType: 'minimal',
    className: 'worksection-listview',
    description: getDescription,
    projectName: getProjectName
  });

  const root = elem.querySelector('.td_actions > span');
  if (root) {
    root.appendChild(link);
  }
});


text:
///
///	@file 	httpEnv.h
/// @brief 	HTTP Server environment variable header
//
////////////////////////////////// Copyright ///////////////////////////////////
//
//	@copy	default
//
//	Copyright (c) Mbedthis Software LLC, 2003-2007. All Rights Reserved.
//
//	This software is distributed under commercial and open source licenses.
//	You may use the GPL open source license described below or you may acquire
//	a commercial license from Mbedthis Software. You agree to be fully bound
//	by the terms of either license. Consult the LICENSE.TXT distributed with
//	this software for full details.
//
//	This software is open source; 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 2 of the License, or (at your
//	option) any later version. See the GNU General Public License for more
//	details at: http://www.mbedthis.com/downloads/gplLicense.html
//
//	This program is distributed WITHOUT ANY WARRANTY; without even the
//	implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
//
//	This GPL license does NOT permit incorporating this software into
//	proprietary programs. If you are unable to comply with the GPL, you must
//	acquire a commercial license to use this software. Commercial licenses
//	for this software and support services are available from Mbedthis
//	Software at http://www.mbedthis.com
//
//	@end
//
////////////////////////////////// Includes ////////////////////////////////////
#ifndef _h_HTTP_ENV
#define _h_HTTP_ENV 1

#include	"buildConfig.h"

////////////////////////////////////////////////////////////////////////////////
#if BLD_FEATURE_ESP_MODULE
#include	"espEnv.h"
//
//	If we are using the ESP module, we map the http environment variables
//	indexes onto the ESP espEnv.h definitions so we match the ESP index
//	numbers.
//
typedef EspEnvType MaEnvType;

#define MA_UNDEFINED_OBJ ESP_UNDEFINED_OBJ
#define MA_SERVER_OBJ ESP_SERVER_OBJ
#define MA_SESSION_OBJ ESP_SESSION_OBJ
#define MA_REQUEST_OBJ ESP_REQUEST_OBJ
#define MA_HEADERS_OBJ ESP_HEADERS_OBJ
#define MA_COOKIES_OBJ ESP_COOKIES_OBJ
#define MA_FILES_OBJ ESP_FILES_OBJ
#define MA_FORM_OBJ ESP_FORM_OBJ
#define MA_APPLICATION_OBJ ESP_APPLICATION_OBJ
#define MA_GLOBAL_OBJ ESP_GLOBAL_OBJ
#define MA_LOCAL_OBJ ESP_LOCAL_OBJ
#define MA_HTTP_OBJ_MAX ESP_OBJ_MAX
#define MA_HTTP_HASH_SIZE ESP_HASH_SIZE

#else

typedef enum MaEnvType {
	MA_UNDEFINED_OBJ = -1,

	/**
	 *	Elements for server[]:
	 *		DOCUMENT_ROOT GATEWAY_INTERFACE SERVER_ADDR SERVER_PORT SERVER_NAME
	 *		SERVER_PROTOCOL SERVER_SOFTWARE SERVER_URL UPLOAD_DIR
	 *		FUTURE: SERVER_ADMIN
 	 *		FUTURE: this could be shared across all hosts and be made read-only.
	 */
	MA_SERVER_OBJ = 0,						/*! server[] data */

	/**
	 *	Elements for session[]: are user defined
	 */
	MA_SESSION_OBJ = 1,					/*! session[] data */

	/**
 	 *	Elements for request[]:
	 *		AUTH_TYPE CONTENT_LENGTH CONTENT_TYPE QUERY_STRING PATH_INFO
	 *		PATH_TRANSLATED REMOTE_ADDR REMOTE_HOST REMOTE_USER REQUEST_METHOD
	 *		REQUEST_URI SCRIPT_FILENAME SCRIPT_NAME
	 *		FUTURE: FILEPATH_INFO REDIRECT_URL SELF REMOTE_PORT AUTH_USER
	 *		AUTH_GROUP AUTH_ACL
	 */
	MA_REQUEST_OBJ = 2,					/*! request[] data */

	/**
	 *	Elements for headers[]:
	 *		HTTP_ACCEPT HTTP_ACCEPT_CHARSET HTTP_CONNECTION HTTP_HOST
 	 *		HTTP_REFERER HTTP_USER_AGENT and any other custom headers
	 */
	MA_HEADERS_OBJ = 3,					/*! header [] data */

	/**
 	 *	Elements for cookies[]: are defined by the HTTP request
	 */
	MA_COOKIES_OBJ = 4,					/*! cookies[] data */

	/**
 	 *	Elements for files[]: are defined by the HTTP request
 	 *		CLIENT_FILENAME CONTENT_TYPE FILENAME SIZE
 	 */
	MA_FILES_OBJ = 5,						/*! files[] data */

	/**
 	 *	Elements for form[]: are defined by the HTTP request
 	 */
	MA_FORM_OBJ = 6,						/*! form[] data */

	/**
 	 *	Elements for application[]: are user defined
 	 */
	MA_APPLICATION_OBJ = 7,				/*! application[] data */

	/**
 	 *	Elements for global[]: are defined by MA/EJS
 	 */
	MA_GLOBAL_OBJ = 8,						/*! global [] data */

	/*
 	 *	Elements for local[]: are defined by MA/EJS
 	 */
	MA_LOCAL_OBJ = 9,						/*! local [] data */
} MaEnvType;

#define MA_HTTP_OBJ_MAX 10

#if BLD_SQUEEZE
#define MA_HTTP_HASH_SIZE	19					/* Size of hash tables */
#else
#define MA_HTTP_HASH_SIZE	37
#endif

#endif // BLD_FEATURE_ESP

#endif // _h_HTTP_ENV

//
// Local variables:
// tab-width: 4
// c-basic-offset: 4
// End:
// vim: sw=4 ts=4
//


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package edu.wpi.first.wpilibj.image;

/**
 *
 * @author joe
 */
public class FancyBinaryImage extends BinaryImage {
    private int numParticles;
    public FancyBinaryImage() throws NIVisionException {
        super();
    }

    public int getNumberParticles () throws NIVisionException{
        numParticles = NIVision.countParticles(image);
        return numParticles;
    }

    public ParticleAnalysisReport getParticleAnalysisReport(int index) throws NIVisionException{
        if(index >= numParticles) throw new IndexOutOfBoundsException("Invalid particle index");
        return new ParticleAnalysisReport(this, index);
    }
}


text:
import { Mongo }                         from 'meteor/mongo';
import SimpleSchema                      from 'simpl-schema';
import { ChangeTracker }                 from 'meteor/austinsand:roba-change-tracker';
import { SchemaHelpers }                 from '../schema_helpers.js';
import { Contributors }                  from '../contributors/contributors';
import { ContributorProjectAssignments } from '../contributors/contributor_project_assignments';
import { ContributorTeamRoles }          from '../contributors/contributor_team_roles';
import { Integrations }                  from '../integrations/integrations';
import { Teams }                         from '../teams/teams';

/**
 * ============================================================================
 * Projects
 * ============================================================================
 */
export const Project = new SimpleSchema({
  // Project Title
  title              : {
    type: String
  },
  // Project Description
  description        : {
    type    : String,
    optional: true
  },
  backgroundColor    : {
    type        : String,
    defaultValue: '#298cff'
  },
  foregroundColor    : {
    type        : String,
    defaultValue: '#ffffff'
  },
  showOnDashboard    : {
    type    : Boolean,
    optional: true
  },
  dashboardCategory  : {
    type    : String,
    optional: true
  },
  sortOrder          : {
    type    : Number,
    optional: true
  },
  // Banner Template
  bannerTemplate     : {
    type    : String,
    optional: true
  },
  // Home page template
  homeTemplate       : {
    type    : String,
    optional: true
  },
  // The content to show to on the dashboard
  cardTemplate       : {
    type    : String,
    optional: true
  },
  // The list of reports to show for this project
  reports            : {
    type    : Array, // String
    optional: true
  },
  'reports.$'        : {
    type: String
  },
  integrationProjects: {
    type    : Object,
    blackbox: true,
    optional: true
  },
  // Contributor that is the primary owner of this project
  owner              : {
    type    : String,
    optional: true
  },
  // Standard tracking fields
  dateCreated        : {
    type     : Date,
    autoValue: SchemaHelpers.autoValueDateCreated
  },
  createdBy          : {
    type     : String,
    autoValue: SchemaHelpers.autoValueCreatedBy
  },
  dateModified       : {
    type     : Date,
    autoValue: SchemaHelpers.autoValueDateModified
  },
  modifiedBy         : {
    type     : String,
    autoValue: SchemaHelpers.autoValueModifiedBy
  }
});

export const Projects = new Mongo.Collection('projects');
Projects.attachSchema(Project);
ChangeTracker.trackChanges(Projects, 'Projects');

// These are server side only
Projects.deny({
  remove () {
    return true;
  },
  insert () {
    return true;
  },
  update () {
    return true;
  }
});

/**
 * Helpers
 */
Projects.helpers({
  /**
   * Fetch the list of ContributorTeamRoles for this project
   * @param query
   * @return {Array}
   */
  teamRoleIds (query) {
    let project     = this,
        teamRoleIds = [];

    // built up the query
    query           = query || {};
    query.projectId = project._id;

    // Gather all of the teamIds from assignments to this team
    ContributorProjectAssignments.find(query).forEach((assignment) => {
      teamRoleIds.push(assignment.teamRoleId);
    });

    // Filter for uniqueness
    return _.uniq(teamRoleIds);
  },

  /**
   * Fetch a list of teams that work on this project
   * @param sortBy
   * @return {cursor}
   */
  teams (sortBy) {
    let project = this,
        teamIds = [];

    // Default sort, check for sortBy.hash because that is what is passed in by Spacebars if sortBy is not passed
    sortBy = _.isObject(sortBy) && sortBy.hash === null ? sortBy : { title: 1 };

    // Gather all of the teamIds from assignments to this team
    ContributorTeamRoles.find({ _id: { $in: project.teamRoleIds() } }).forEach((teamRole) => {
      teamIds.push(teamRole.teamId);
    });

    // Filter for uniqueness
    teamIds = _.uniq(teamIds);

    return Teams.find({ _id: { $in: teamIds } }, { sort: sortBy })
  },

  /**
   * Get all of the contributors in a given role on a given team for this project
   * @param roleId
   * @param teamId
   * @param sortBy
   */
  contributorsInRoleOnTeam (roleId, teamId, sortBy) {
    let project        = this,
        contributorIds = [];

    // Default sort, check for sortBy.hash because that is what is passed in by Spacebars if sortBy is not passed
    sortBy = _.isObject(sortBy) && sortBy.hash === null ? sortBy : { name: 1 };

    // Gather all of the teamIds from assignments to this team
    ContributorTeamRoles.find({ _id: { $in: project.teamRoleIds() }, roleId: roleId, teamId: teamId }).forEach((teamRole) => {
      contributorIds.push(teamRole.contributorId);
    });

    // Filter for uniqueness
    contributorIds = _.uniq(contributorIds);

    return Contributors.find({ _id: { $in: contributorIds } }, { sort: sortBy })
  },

  /**
   * Get all of the integrations for this project
   */
  integrations () {
    return Integrations.find({ projectId: this._id }, { sort: { itemType: 1, integrationType: 1 } })
  }
});


text:
package org.reclipse.metrics.gast;

import org.eclipse.emf.ecore.EObject;
import org.reclipse.metrics.AbstractGASTMetricCalculator;

import de.fzi.gast.core.Package;
import de.fzi.gast.core.Root;
import de.fzi.gast.types.GASTClass;

/**
 * This metric calculates the number of methods inherited (NMI) for different elements. Supported
 * elements are elements or sub types of the following:
 *
 *

 *
{@link Root Project}

 *
The total NMI of all packages inside the project.

 *
{@link Package Package}

 *
The total NMI of all classes inside the package.

 *
{@link GASTClass Class}

 *
The NMI inside the class.

 *

 *
 * @version $Revision$ $Date$
 * @author Last editor: $Author$
 * @author harka
 */
public class NMICalculator extends
      AbstractGASTMetricCalculator
{

   private boolean ignoreInnerClasses;

   public NMICalculator()
   {
      super();

      // TODO: move to preference store
      ignoreInnerClasses = true;

      addClass(getCore().getRoot());
      addClass(getCore().getPackage());
      addClass(getTypes().getGASTClass());
   }

   @Override
   public double calculate(EObject object)
   {
      if (object != null)
      {
         if (object instanceof Root)
         {
            // prepare summarizing
            double sum = 0;

            // summarize for contained packages
            for (Package p : ((Root) object).getPackages())
            {
               sum += calculate(p);
            }

            return sum;
         }

         if (object instanceof Package)
         {
            // prepare average building
            double sum = 0;

            // summarize for of all classes
            for (GASTClass c : ((Package) object).getClasses())
            {
               // ignore inner classes when necessary
               if ((c.isInner() && !ignoreInnerClasses) || !c.isInner())
               {
                  sum += calculate(c);
               }
            }

            return sum;
         }

         if (object instanceof GASTClass)
         {
            // FIXME: calculate NMI
         }
      }

      return -1;
   }
}


text:
const net = require('net');
const fs = require('fs');
const WorkerPool = require('./../common/WorkerPool');
const PhantomWorker = require('./PhantomWorker');
const JobQueue = require('./JobQueue');
const Redis = require('redis');
const API = require('./API');

var PORT_SEARCH_BEGIN; //Number of port to start looking for free ports
var LISTEN_PORT;
var NUMBER_WORKERS;

// Globals
global.redis = null;
global.workerPool = null;
global.jobQueue = null;

var start = function() {

    var dotenv = require('dotenv');
    // Load environment variables, either from .env files (development)
    dotenv.load();

    PORT_SEARCH_BEGIN = parseInt(process.env.PHANTOM_START_PORT);
    LISTEN_PORT = parseInt(process.env.PORT);
    NUMBER_WORKERS = parseInt(process.env.PHANTOM_WORKERS);

    redis = Redis.createClient(parseInt(process.env.REDIS_PORT), process.env.REDIS_HOST);

    redis.on('connect', function() {

        workerPool = new WorkerPool();

        // Create a job queue using the worker pool that has been created
        jobQueue = new JobQueue(workerPool);

        // First spawn the phantom processes that will serve the requests
        startPhantomWorkers( function() {

            // Once all the workers are ready start the API service
            API.start(LISTEN_PORT);

        } );

    });

    redis.on("error", function (err){
        console.log("Error " + err);
    });

};

var startPhantomWorkers = function(callback) {

    var workersReady = 0;

    var launchWorker = function(oneLaunchedCb) {

        // Find a free port and spawn a phantom service in that port
        getPort(function(port) {

            // If a worker dies, launch another one and try to process pending jobs
            var onKill = function(worker) {

                console.log("Worker " + worker.port + " killed!");

                launchWorker(function() {
                    jobQueue.processJobs();
                });
            };

            new PhantomWorker(port, workerPool, function(worker) {

                if(typeof oneLaunchedCb === 'function') oneLaunchedCb();

                if(++workersReady === NUMBER_WORKERS) {
                    callback();
                }

            }, onKill);

        });
    };

    console.log('Spawning ' + NUMBER_WORKERS + ' workers...');

    for(var i = 0; i < NUMBER_WORKERS; i++) {
        launchWorker();
    }

};

function getPort (cb) {
    var port = PORT_SEARCH_BEGIN;
    PORT_SEARCH_BEGIN += 1;

    var server = net.createServer();
    server.listen(port, function (err) {
        server.once('close', function () {
            cb(port)
        });
        server.close()
    });
    server.on('error', function (err) {
        getPort(cb)
    })
}

start();


text:
<pre>
    BAIP: 001
      Title: BAIP Purpose and Guidelines
      Status: Active
      Type: Process
      Author: Aleksey Karpov admin@bitcoinasset.org
      Created: 2017-09-22
</pre>

What is an BAIP?
--------------
BAIP stands for Bitcoin Improvement Proposal.A BAIP is a design document providing information to the Bitcoin community, or describing a new feature for Bitcoin Asset or its processes or environment. The BAIP should provide a concise technical specification of the feature and a rationale for the feature. The BAIP author is responsible for building consensus within the community and documenting dissenting opinions.

BAIP Types
----------
There are three kinds of BAIP:

* A Standards Track BAIP describes any change that affects most or all Bitcoin Asset implementations, such as a change to the network protocol, a change in block or transaction validity rules, or any change or addition that affects the interoperability of applications using Bitcoin Asset.
* An Informational BAIP describes a Bitcoin Asset design issue, or provides general guidelines or information to the Bitcoin Asset community, but does not propose a new feature. Informational BAIPs do not necessarily represent a Bitcoin Asset community consensus or recommendation, so users and implementors are free to ignore Informational BAIPs or follow their advice.
* A Process BAIP describes a process surrounding Bitcoin Asset, or proposes a change to (or an event in) a process. Process BAIPs are like Standards Track BAIPs but apply to areas other than the Bitcoin Asset protocol itself. They may propose an implementation, but not to Bitcoin Asset codebase; they often require community consensus; unlike Informational BAIPs, they are more than recommendations, and users are typically not free to ignore them. Examples include procedures, guidelines, changes to the decision-making process, and changes to the tools or environment used in Bitcoin Asset development. Any meta-BAIP is also considered a Process BAIP.

BAIP Work Flow
-------------

The BAIP process begins with a new idea for Bitcoin Asset. Each potential BAIP must have a champion -- someone who writes the BAIP using the style and format described below, shepherds the discussions in the appropriate forums, and attempts to build community consensus around the idea. The BAIP champion (a.k.a. Author) should first attempt to ascertain whether the idea is BAIP-able.

Once the champion has asked the Bitcoin Asset community as to whether an idea has any chance of acceptance, a draft BAIP should be presented as a [pull request]. This draft must be written in BAIP style as described below.

It is highly recommended that a single BAIP contain a single key proposal or new idea. The more focused the BAIP, the more successful it tends to be. If in doubt, split your BAIP into several well-focused ones.

Authors MUST NOT self assign BAIP numbers, but should use an alias such as "baip-johndoe-infinitebitcoins" which includes the author's name/nick and the BAIP subject.

If the BAIP collaborators approve, the BAIP editor will assign the BAIP a number (generally the issue or PR number related to the BAIP), label it as Standards Track, Informational, or Process, give it status "Draft", and add it to the git repository. The BAIP editor will not unreasonably deny an BAIP. Reasons for denying BAIP status include duplication of effort, being technically unsound, not providing proper motivation or addressing backwards compatibility, or not in keeping with the Bitcoin philosophy.

The BAIP author may update the Draft as necessary in the git repository. Updates to drafts may also be submitted by the author as pull requests.

Standards Track BAIPs consist of two parts, a design document and a reference implementation. The BAIP should be reviewed and accepted before a reference implementation is begun, unless a reference implementation will aid people in studying the BAIP. Standards Track BAIPs must include an implementation -- in the form of code, a patch, or a URL to same -- before it can be considered Final.

Once a BAIP has been accepted, the reference implementation must be completed. When the reference implementation is complete and accepted by the community, the status will be changed to "Final".

A BAIP can also be assigned status "Deferred". The BAIP author or editor can assign the BAIP this status when no progress is being made on the BAIP. Once a BAIP is deferred, the BAIP editor can re-assign it to draft status.

A BAIP can also be "Rejected". Perhaps after all is said and done it was not a good idea. It is still important to have a record of this fact.

BAIPs can also be superseded by a different BAIP, rendering the original obsolete. This is intended for Informational BAIPs, where version 2 of an API can replace version 1.

Some Informational and Process BAIPs may also have a status of "Active" if they are never meant to be completed. E.g. BAIP 001 (this BAIP).

What belongs in a successful BAIP?
---------------------------------

Each BAIP should have the following parts:

* Preamble -- RFC 822 style headers containing meta-data about the BAIP, including the BAIP number, a short descriptive title (limited to a maximum of 44 characters), the names, and optionally the contact info for each author, etc.

* Abstract -- a short (~200 word) description of the technical issue being addressed.

* Copyright/public domain -- Each BAIP must either be explicitly labelled as placed in the public domain (see this BAIP as an example) or licensed under the Open Publication License.

* Specification -- The technical specification should describe the syntax and semantics of any new feature.

* Motivation -- The motivation is critical for BAIPs that want to change the Bitcoin Asset protocol. It should clearly explain why the existing protocol specification is inadequate to address the problem that the BAIP solves. BAIP submissions without sufficient motivation may be rejected outright.

* Rationale -- The rationale fleshes out the specification by describing what motivated the design and why particular design decisions were made. It should describe alternate designs that were considered and related work, e.g. how the feature is supported in other languages.

* The rationale should provide evidence of consensus within the community and discuss important objections or concerns raised during discussion.

* Backwards Compatibility -- All BAIPs that introduce backwards incompatibilities must include a section describing these incompatibilities and their severity. The BAIP must explain how the author proposes to deal with these incompatibilities. BAIP submissions without a sufficient backwards compatibility treatise may be rejected outright.

* Reference Implementation -- The reference implementation must be completed before any BAIP is given status "Final", but it need not be completed before the BAIP is accepted. It is better to finish the specification and rationale first and reach consensus on it before writing code.

* The final implementation must include test code and documentation appropriate for the Bitcoin Asset protocol.

BAIP Formats and Templates
-------------------------

BAIPs should be written in mediawiki or markdown format.

BAIP Header Preamble
--------------------

Each BAIP must begin with an RFC 822 style header preamble. The headers must appear in the following order. Headers marked with "*" are optional and are described below. All other headers are required.

 `BIP: <BAIP number>`
  `Title: <BAIP title>`
  `Author: <list of authors' real names and optionally, email addrs>`
  `* Discussions-To: <email address>`
  `Status: <Draft | Active | Accepted | Deferred | Rejected |
           Withdrawn | Final | Superseded>`
  `Type: <Standards Track | Informational | Process>`
  `Created: <date created on, in ISO 8601 (yyyy-mm-dd) format>`
  `* Post-History: <dates of postings to bitcoin mailing list>`
  `* Replaces: <BAIP number>`
  `* Superseded-By: <BAIP number>`
  `* Resolution: <url>`

Transferring BAIP Ownership
--------------------------

It occasionally becomes necessary to transfer ownership of BAIPs to a new champion. In general, we'd like to retain the original author as a co-author of the transferred BAIP, but that's really up to the original author. A good reason to transfer ownership is because the original author no longer has the time or interest in updating it or following through with the BAIP process, or has fallen off the face of the 'net (i.e. is unreachable or not responding to email). A bad reason to transfer ownership is because you don't agree with the direction of the BAIP. We try to build consensus around a BAIP, but if that's not possible, you can always submit a competing BAIP.

If you are interested in assuming ownership of a BAIP, send a message asking to take over, addressed to both the original author and the BAIP editor. If the original author doesn't respond to email in a timely manner, the BAIP editor will make a unilateral decision (it's not like such decisions can't be reversed).

BAIP Editors
-----------

The current BAIP editor is Aleksey Karpov who can be contacted at [[mailto:admin@bitcoinasset.org]].

BAIP Editor Responsibilities & Workflow
--------------------------------------

For each new BAIP that comes in an editor does the following:

* Read the BAIP to check if it is ready: sound and complete. The ideas must make technical sense, even if they don't seem likely to be accepted.
* The title should accurately describe the content.
* Edit the BAIP for language (spelling, grammar, sentence structure, etc.), markup (for reST BAIPs), code style.

Once the BAIP is ready for the repository it should be submitted as a "pull request" to the [https://github.com/bitcoinasset/baip bitcoinasset/baip] repository on GitHub where it may get further feedback.

The BAIP editor will:

* Assign a BAIP number (almost always just the next available number, but sometimes it's a special/joke number, like 666 or 3141) in the pull request comments.

* Merge the pull request when the author is ready (allowing some time for further peer review).

* List the BAIP in [[README.md]]

The BAIP editors are intended to fulfill administrative and editorial responsibilities. The BAIP editors monitor BAIP changes, and correct any structure, grammar, spelling, or markup mistakes we see.

History
-------

This document was derived heavily from [Bitcoin's BIP-0001] written by Amir Taaki which in turn was derived from [Python's PEP-0001]. Although the PEP-0001 text was written by Barry Warsaw, Jeremy Hylton, and David Goodger, they are not responsible for its use in the Bitcoin Asset Improvement Process, and should not be bothered with technical questions specific to Bitcoin Asset or the BAIP process. Please direct all comments to the BAIP editors.

Changelog
---------

22 September 2017 - Initial commit.

[markdown]: https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet
[README.md]: README.md "wikilink"
[Bitcoin's BIP-0001]: https://github.com/bitcoin/bips
[Python's PEP-0001]: https://www.python.org/dev/peps/


text: This is the initial release of Mangaeden.


text:
import os
import zipfile

from rally.common import fileutils
from rally.common.i18n import _
from rally.common.i18n import _LE
from rally.common import log as logging
from rally.common import utils
from rally import consts
from rally import exceptions
from rally import osclients
from rally.plugins.openstack.context.cleanup import manager as resource_manager
from rally.task import context

LOG = logging.getLogger(__name__)

@context.configure(name="murano_packages", order=401)
class PackageGenerator(context.Context):
    """Context class for uploading applications for murano."""

    CONFIG_SCHEMA = {
        "type": "object",
        "$schema": consts.JSON_SCHEMA,
        "properties": {
            "app_package": {
                "type": "string",
            }
        },
        "required": ["app_package"],
        "additionalProperties": False
    }

    @utils.log_task_wrapper(LOG.info, _("Enter context: `Murano packages`"))
    def setup(self):
        is_config_app_dir = False
        if zipfile.is_zipfile(self.config["app_package"]):
            zip_name = self.config["app_package"]
        elif os.path.isdir(self.config["app_package"]):
            is_config_app_dir = True
            zip_name = fileutils.pack_dir(self.config["app_package"])
        else:
            msg = (_LE("There is no zip archive or directory by this path:"
                       " %s") % self.config["app_package"])
            raise exceptions.ContextSetupFailure(msg=msg,
                                                 ctx="murano_packages")

        for user, tenant_id in utils.iterate_per_tenants(
                self.context["users"]):
            clients = osclients.Clients(user["endpoint"])
            self.context["tenants"][tenant_id]["packages"] = []
            if is_config_app_dir:
                self.context["tenants"][tenant_id]["murano_ctx"] = zip_name
            package = clients.murano().packages.create(
                {"categories": ["Web"], "tags": ["tag"]},
                {"file": open(zip_name)})

            self.context["tenants"][tenant_id]["packages"].append(package)

    @utils.log_task_wrapper(LOG.info, _("Exit context: `Murano packages`"))
    def cleanup(self):
        resource_manager.cleanup(names=["murano.packages"],
                                 users=self.context.get("users", []))


text:
require 'redcarpet'
require 'json'

module Jekyll
  class ApiBluePrint < Converter
    safe true
    priority :low

    def matches(ext)
      ext =~ /apiblueprint/i
    end

    def output_ext(ext)
      ".html"
    end

    def convert(content)
      content
      renderer = BluePrintHTML.new()
      thismarkdown = Redcarpet::Markdown.new(renderer, no_intra_emphasis: true)
      newcontent = thismarkdown.render(content)
      return Liquid::Template.parse(newcontent).render {}
    end
  end
end

class BluePrintHTML < Redcarpet::Render::HTML

  #turns command line output on, does not work within Jekyll
  @@debug = false

  ####
  # vars for setting the params in the templates
  # could we replace this with a hash, that we reset on each header-## loop?
  ####
  @@body_block = ""
  @@group_identifier = ""
  @@http_response = "200"
  @@params = ""
  @@param_list = ""
  @@attr_list = ""
  @@attr_string = ""
  @@param_string = ""
  @@method = ""
  @@path = ""
  @@request_body = ""
  @@response_body = ""
  @@request_headers = ""

  ####
  # set the root url of the API calls
  ####
  @@root_url = "https://api.sendgrid.com/v3/"

  ####
  # Do we want to show the headers?
  ####
  # you would enable h1 and disable h2, to show group headers but not the path headers
  @@show_h1 = TRUE
  @@show_h2 = FALSE

  ####
  # Allow overriding the level of an h1 to something else, default 2
  ####
  @@change_h1_to = 2

  ####
  # Find and replace in these instances
  ####

  @@find_replace = {
      # removes the word "Group" from the h1 header
      "h1" => [["Group" , "" ]]
  }

  # =============
  #
  # Override Methods
  #
  # =============

  # handles the instances where spaces indicate a code block
  def block_code(code, language)
    debug "~~BLOCK CODE~~"
    code.chomp
  end

  # Handles the instance of `something` in API Blueprint
  def codespan(code)
    debug("~~CODESPAN~~")
    code.chomp
  end

  # def emphasis(text)
  #   text
  # end

  # Builds the header tags, according to what we expect from APIBlueprint
  # third param = nil for backwards compatibility with older redcarpet gems
  def header(text, level, somethingelse = nil)
    debug "~~HEADER~~"
    debug "\t level = " + level.to_s

    # get the path and create the group ID for the API requests
    if 2 == level

      # reset for each endpoint path, bc params are the same for all HTTP methods within this path group
      @@param_list, @@attr_list, @@param_string = "", "", ""

      #create a unique HTML ID for the group

      debug " TESTING MATCH: " +  /(?<=\[).+?(?=\])/.match(text).to_s

      path = /(?<=\[).+?(?=\])/.match(text).to_s

      if path.include? "?"
        path = path.split("?")
        @@path = path[0]
        @@params = "?" + path[1].gsub("&","&")
      else
        @@path = path
      end

      debug "\tPATH SET: " + @@path
      debug "\tPARAMS SET " + @@params

      #reset the identifier for each grouping of params/responses
      @@group_identifier = "group_" + rand(1000000000).to_s

      debug "\tGROUP SET: " + @@group_identifier

      unless @@show_h2

        return ""

      end

    end

    # get the request method
    if 3 == level
      debug "\t--RESET VARS--"

      # attrs get reset by HTTP METHOD
      @@attr_list, @@param_string = "", ""

      if text.include? "]"
        # get the response method from the header
        @@method = text.split("[")[1].gsub("]","")
      else
        debug "HEADER parse error - no HTTP method on " + text
        exit
      end

      debug "\tMETHOD SET: " + @@method
    end

    if 1 == level

      #if we don't want to show the h1 tag, don't
      unless @@show_h1
        return ""
      end

      #allows user to override the h1 level to something else
      level = @@change_h1_to
      text = do_find_replace(text, "h1")

    end
    debug "\t --header text--: " + text
    "\n\n\n" + '{% anchor h' + level.to_s + ' %}' + text + '{% endanchor %}'

  end

  # The first thing that happens to to text before any other methods are called
  # get rid of double new lines to cleanup the output
  def preprocess(full_document)
    debug "~~PRE PROCESS~~"

    # removes the FORMAT string off the top of the blueprint file
    remove = /FORMAT:\ [0-9a-zA-Z]*/.match(full_document)
    full_document.slice!(remove.to_s)

    return full_document
  end

  # Builds the list elements, by aggregating the content of the list
  def list(content, list_type)
    debug "~~LIST~~"
    debug "\t list type = " + list_type.to_s

    return "\t#{content}"
  end

  # Builds list items
  # We are adding logic to handle specific types of lists in the blueprint
  # since parameters are defined before we need them output, we store and append to the apiv3 liquid block
  def list_item(text, list_type)
    debug "~~LIST ITEM~~"
    debug "\t list type = " + list_type.to_s
    debug "\t" + text

    # individual parameters are accessed first in the processing
    if text.include? ") ... "
      return docs_liquid_individual_params(text)
    end

    # individual parameters are accessed first in the processing
    if text.include? ") - "
      return docs_liquid_individual_attrs(text)
    end

    # Build the Parameters Liquid Block
    if text.include? "Parameters"
      return docs_liquid_params_block(text, "parameters")
    end

    if text.include? "Attributes"
      return docs_liquid_params_block(text, "attributes")
    end

    #handle the request and response headers
    # When we have headers that tag along, we need to indicate this
    if text.include? "Headers"

      debug "HEADERS!! " + text

      return docs_header(text)

    end
    # next up is an element with Body - we don't know whether it's a request or a response
    if text.include? "Body"

      return docs_body(text)

    end

    debug "\t body_block = " + @@body_block

    if text.include? "Response"

      debug "\t text includes http response = " + @@http_response

      if 0 == @@http_response.length
        paragraph(text)
      end

    end

    # Build the Response Liquid block, only if we're ready to do so
    # this is in list_item rather than list, because each endpoint might have multiple responses, sometimes we don't want to
    # show responses with specific response codes.
    if "response" == @@body_block

      # if we don't have one of the 200 responses, don't bother printing it
      # originally done inside of docs_liquid_output
      unless @@http_response[0].to_s == "2"

        # call the instance var reset
        reset_vars()

        # return nothing because we don't want any output here
        return ""
      end

      return docs_liquid_output(text)
    end

    "\t" + text
  end

  # overrides the default paragraph functionality, by setting a variable to indicate what block we're working on.
  #  otherwise, it just returns the text. We don't want p tags, anywhere.
  def paragraph(text)
    debug "~~PARAGRAPH~~"
    if text.include? "Request"
      @@body_block = "request"
      debug "\t Set Body Block: request"
      debug "\t " + text
      # we don't need this text anymore, so return nothing
      return
    end

    if text.include? "Response"
      @@body_block = "response"

      @@http_response = text.split(" ")[1]

      debug "\t http response = " + @@http_response

      debug "\t Set Body Block: response"
      # we don't need this text anymore, so return nothing
      return
    end
    #let's just avoid wrapping things in p tags, mmmkay?
    text
  end

  # =============
  #
  # Custom Methods
  #
  # =============

  # outputs whatever is passed to the terminal
  def debug(text)
    if TRUE == @@debug
      puts text
    end
  end

  # takes values from the find_replace hash and applies the find_replace to the text string
  def do_find_replace(text, index)

    @@find_replace[index].each { |arr|
      text = text.gsub(arr[0], arr[1])
    }

    return text.to_s
  end

  def docs_header(text)

    text = text.gsub("Headers","")

    debug "In docs_header body_block = " + @@body_block

    if "request" == @@body_block
      debug "Found a header! " + text

      @@request_headers = text.gsub("\n","").gsub(""",'"')

    end

    if "response" == @@body_block
      #@todo build this out
    end

  end

  # handle the body of the request or response
  def docs_body(text)
    debug "\t --docs_body--"
    text = text.gsub("Body","")

    debug "Body Block: " + @@body_block

    if "request" == @@body_block

      @@request_body = text.gsub("\n", "").gsub(""",'"').strip

      debug "\t REQUEST BODY SET " + text.gsub("\n", "").gsub(""",'"').strip

      # we don't want this to be put out to the page yet
      return
    end

    if "response" == @@body_block
      # @todo get the JSON code out and pretty it up - leaving the text

      @@response_body += text.gsub(""",'"').strip
      debug "\t RESPONSE BODY SET " + text.strip

      # we don't want this to be put out to the page yet
      return
    end
    debug "\t remaining text = " + text
    # output anything that gets through, just in case
    text
  end

  # Rules:
  #   Attributes has "(required, type) - "
  #   the first word is the param name
  #   everything between the first word and the open paren is the example
  #   between the params are required, type data
  #   everything after the " - " is the description
  def docs_liquid_individual_attrs(text)
    debug "\t --Individual Attributes--"
    # BluePrint example --- :identifier :example (:optional, :type) - :description

    debug "\t\tAttr String: " + text

    position = text.index(" ")
    #the identifier is everything before the first space.
    identifier = text[0..position].strip

    debug "\t\tidentifier: " + identifier

    text = text[position..text.length].strip

    debug "\t\tnew text: " + text

    # find the open paren
    position = text.index(" (")

    #the example is everything from the first space to the open paren
    example = text[0..position]

    if example.length > 0
      example = docs_example_text(example)
    end

    debug "\t\texample: " + example

    text = text[position..text.length].strip

    debug "\t\tnew text: " + text

    position = text.index(" - ")

    #get the description, add example no matter what
    description = text[position..text.length].gsub(" - ", "").strip

    debug "\t\tdescription: " + description

    if description.rindex(".") != (description.length - 1)
      throw "Description should have a period at the end. Given: " + description + " For identifier: " + identifier
    end

    description +=  example

    text = text[0..position].strip.gsub("("," ").gsub(")", " ").split(",")

    debug "\t\t new text: "

    optional = text[0].strip

    debug "\t\t optional: " + optional

    unless optional.include? "required"
      unless optional.include? "optional"
        throw "String must be 'optional' or 'required' in parens. example: (optional, number, example string) \n String was: " + optional
      end
    end

    parameter_req = "Yes"

    if "optional" == optional.downcase
      parameter_req = "No"
    end

    requirements = text[1].strip

    debug "\t\t requirements: " + requirements

    @@attr_string += "\t{% parameter #{identifier} #{parameter_req} \"#{requirements}\" \"#{description}\" %}\n"

    debug "\t\t " + @@attr_string

  end

  def docs_default_text(text)
    return "
Default: `" + text + "`"
  end

  def docs_example_text(text)
    return "
Example: `" + text + "`"
  end

  # handles the specifics of the liquid "parameters" items for the redcarpet:list_item method
  def docs_liquid_individual_params(text)
    debug "\t --Individual Parameter--"
    # BluePrint example --- :identifier (:optional, :type, :example) … :description

    # split by ...
    #       [1] = description
    # regex between parens
    #       then split on comma
    #       [0] optional
    #       [1] requirements
    # delete everything between parens
    #   category is left
    #   if = then we have a default
    #   if no = then we have just name

    debug "Param String: " + text

    parameters = text.split(" ... ")

    description = parameters[1].chop

    # get the data in parens
    optional_requirements = /\(([^)]+)\)/.match(parameters[0])

    # remove the data in parens
    identifier_default = parameters[0].gsub(optional_requirements.to_s,"").strip

    # get the individual items
    optional_requirements = optional_requirements.to_s.gsub("(", "").gsub(")", "").split(",")

    # get the optional/required information from the 1st item in the parenthesis
    optional = optional_requirements[0].strip

    unless optional.include? "required"
      unless optional.include? "optional"
        throw "String must be 'optional' or 'required' in parens. example: (optional, number, example string) \n String was: " + parameters[0]
      end
    end

    # get the requirements information from the 2nd item in the parenthesis
    requirements = ""

    if optional_requirements[1]
      requirements = optional_requirements[1].strip
    end

    example = ""

    # Create the example from the 3rd item in the parenthesis
    if optional_requirements.length > 2
      optional_requirements[2] = optional_requirements[2].strip

      example = docs_example_text(optional_requirements[2])

      debug "\t " + example
    end

    parameter_req = "Yes"

    if "optional" == optional.downcase
      parameter_req = "No"
    end

    identifier = ""

    # add the identifier and the default string to the description.
    if identifier_default.include? "="
      identifier_default = identifier_default.split("=")
      identifier = identifier_default[0].strip
      description += docs_default_text(identifier_default[1].strip)
      debug "\t Description: " + description
    else
      identifier = identifier_default
    end

    # lets see if this description has members?
    if description.include? "Members"
      debug "Has Members!!"

      descriptors = description.split("Members")

      description = descriptors[0].strip + " Possible Values: "

      members = descriptors[1].strip.split("\n").compact.collect{|x| x.strip}
      description += members.join(", ")

      debug "New Description: " + description
    end

    # add the example to the end of the description
    if example.length > 0
      description += example
      debug "\t Desc+Example: " + description
    end

    # liquidexample --- {% parameter :identifer :required :requirements :description %}
    debug "\t{% parameter #{identifier} #{parameter_req} \"#{requirements}\" \"#{description}\" %}\n"
    debug "\t TEST "
    debug @@param_string
    @@param_string += "\t{% parameter #{identifier} #{parameter_req} \"#{requirements}\" \"#{description}\" %}\n"
    debug "\t added to param_list['temp']"
  end

  # builds the final output of all the liquid tags, using all the vars we've set
  # we do this during the response, because we finally have all the parts we need
  def docs_liquid_output(text)
    # {% apiv3example :endpoint_identifier :requestType :url?:parameters %}
    #   {% apiv3requestbody %}
    #      json here
    #   {% endapiv3requestbody %}
    #   {% apiv3requestheader %}
    #      json here
    #   {% endapiv3requestheader %}
    #   {% v3response %}
    #   :expectedResponse
    #   [
    #     {
    #         :exampleResults
    #     },
    #     {
    #         :exampleResults
    #     }
    #   ]
    #   {% endv3response %}
    # {% endapiv3example %}

    text = "HTTP/1.1 " + @@http_response

    debug "\t Path: " + @@path.to_s

    if 0 == @@path.index("/")
      @@path[0] = ''
    end

    debug "\t Path: " + @@path.to_s

    url = @@root_url + @@path.strip

    debug "\t URL: " + url

    # remove trailing slash
    url = url.chomp("/").strip

    unless @@params.nil?
      url += @@params
    end

    # output all the tags at once for this endpoint
    # if/when we want to put params on the URL in the Request area, we can do this append - @@params.gsub("\n","")+ - to the Url
    # we will need to probably grab params for the URL from the params list, rather than the request body

    output = ""

    #sometimes we have no params, that's OK
    unless @@param_list.nil?
      debug "\t PARAMS LIST IS NOT NIL"
      output += @@param_list + "\n\n"
    end

    unless @@attr_list.nil?
      debug "\t attr_list is not NIL"
      output += @@attr_list + "\n\n"
    end

    output += "{% apiv3example endpoint#{@@group_identifier} #{@@method} #{url} %}\n"

    if @@request_body.length > 1
      output +=     "\t {% apiv3requestbody %} #{@@request_body.strip} \t {% endapiv3requestbody %}"
    end

    if @@request_headers.length > 1
      output +=     "\t {% apiv3requestheader %}" +
                      @@request_headers.strip +
                    "\t {% endapiv3requestheader %}"
    end

    output +=   "\t{% v3response %}\n" +
        "\t\t" + text + "\n"

    #sometimes, we don't have a response body. That's ok.
    unless @@params.nil?
      if @@response_body.length > 1
        output += JSON.pretty_generate(JSON.parse(@@response_body)) + "\n"
      end

    end

    output += "\t{% endv3response %}\n" +
        "{% endapiv3example %}"

    # call the instance var reset
    reset_vars()
    debug "\n\n" + output + "\n\n"
    return "\n\n" + output + "\n\n"
  end

  # builds the parameter block using the parameters text that is passed in and the group identifier
  def docs_liquid_params_block(text, type)
    debug "\t --" + type + " Block --"

    debug "\t " + type + ": " + text
    # This should be building the following, using the other variables that have been set already

    # {% parameters categoriesget %}
    #   {% parameter category No 'String' 'Prefix search on the category name' %}
    #   {% parameter limit No 'Number' 'The number of results to return' %}
    #   {% parameter offset No 'Number' 'the beginning point in the list where to retrieve results from' %}
    # {% endparameters %}

    # create the params list when we have a list element that says "Params"
    if type == "parameters"
      @@param_list = "{% parameters endpoint#{@@group_identifier} %}\n" + @@param_string + "{% endparameters %}"
      debug "\t param LIST SET: " + @@param_list
    end

    # create the attr list when we have a list element that says "Params"
    if type == "attributes"
      @@attr_list = "{% attributes endpoint#{@@group_identifier} %}\n" + @@attr_string + "{% endattributes %}"
      debug "\t attr LIST SET: " + @@attr_list
    end

    @@param_string = ""
    @@attr_string = ""
    # we don't want any output from this method
    return ""
  end

  def reset_vars()
    debug "## RESET EVERYTHING ##"
    # reset everything, just in case we're about to do another endpoint - path doesn't get reset until another h2, bc we reuse the path
    @@body_block, @@group_identifier, @@http_response, @@params, @@request_body, @@response_body, @@request_headers = "","","","","","","",""
  end

end


text:
"use strict";

var stockmarket = require('../stockmarket'),
	stockmarketController = {};

stockmarketController.render = function(req, res, callback) {
	stockmarket.view(req.user.uid, function(err, data) {
		if (err) {
			return require.main.require('./src/controllers/helpers').redirect(res, '/rpg/character');
		}

		res.render('rpg/stock', data);
	});
};

module.exports = stockmarketController;


text:
from flask import request, jsonify
from flask.views import MethodView
from flask.ext.login import current_user, login_user
from sqlalchemy import and_, update
import logger

from backend.api.mail import sendEmail

from backend import db, app
from backend.database.models import User, Presence, UserStatistics, Settings, ChatMessages, UserPrivileges
from backend.api.sessionauth import current_user_props, hash_password, check_password
import validation

## Creates a new User record
def create_new_user(username, password, email, first_name, last_name):
    new_user = User(username = username,
        #password =      hash_password(password),
        password = password,
        email =         email,
        first_name =    first_name,
        last_name =     last_name,
    )

    db.session.add(new_user)
    db.session.commit()

    return new_user
## changes the user data in the database, changing only the named parameters
def change_user_data(username, password=None, email=None, first_name=None, last_name=None):
    user = User.query.filter_by(username=username).first()

    if user is None:
        return jsonify(**{'success': False, 'error': 'no username specified'}), 401

    if password is not None and not validation.valid_password(password):
        return jsonify(**{'success': False, 'error': 'Invalid password','offending_attribute': 'password'}), 401

    # update user obj with the data passed to the function
    if first_name is not None:
        user.first_name = first_name
    if last_name is not None:
        user.last_name = last_name
    if email is not None:
	    user.email= email
    if password is not None:
	   #user.password = hash_password(password)
       user.password = password

    # add the current user to the data to be committed to the database
    db.session.add(user)
    db.session.commit()
    return jsonify(**{'success': True, 'first_name': user.first_name, 'last_name': user.last_name, 'email': user.email})

## Changes the email notification settings
def change_emailSettings(username, n_hour=None):
    user = User.query.filter_by(username=username).first()

    if user is None:
        return jsonify(**{'success': False, 'error': 'no username specified'}), 401

    setting = Settings.query.filter_by(user_id=user.id).first()
    #print "user_id" + str(Settings.user_id)

    setting.n_hour = n_hour
    #Settings.update().values(n_hour=n_hour).where(Settings.user_id == user.id);
    db.session.add(setting)
    db.session.commit()

    return jsonify(**{'success': True}), 200

## Changes the details of a user
class ChangeDetailsAPI(MethodView):
    def post(self):
        request_data = request.get_json(force=True, silent=True)
        if request_data is None:
            request_data = {}

        if ('username' in request_data) and ('oldpassword' in request_data) and len(request_data['oldpassword']) != 0:
            user = User.query.filter_by(username=request_data['username']).first()
            #if (not user) or (not check_password(request_data['oldPassword'],user.password)):
            if (not user) or (request_data['oldpassword'] != user.password):
                return jsonify(**{'success': False, 'error': 'Old password not valid', 'offending_attribute': 'oldpassword'}), 401

        if('username' in request_data and ('password' in request_data
                                    or 'first_name' in request_data
                                    or 'last_name' in request_data
                                    or 'email' in request_data)):
            # at least one entry is changed
            username = request_data['username']
            password = None
            first_name = None
            last_name = None
            email = None

            if 'password' in request_data and len(request_data['password']) != 0:
                password = request_data['password']
            if 'first_name' in request_data and len(request_data['first_name']) != 0:
                first_name = request_data['first_name']
            if 'last_name' in request_data and len(request_data['last_name']) != 0:
                last_name = request_data['last_name']
            if 'email' in request_data and len(request_data['email']) != 0:
                email = request_data['email']
            # pass parsed parameters to the database method
            return change_user_data(username, password, email, first_name, last_name);
        return jsonify(**{'success': False}), 401

## Updates the settings of a specific user
class SettingsAPI(MethodView):
    def post(self):
        request_data = request.get_json(force=True, silent=True)
        if request_data is None:
            request_data = {}

        if ('username' in request_data):
            username=request_data['username']

            if 'n_hour' in request_data:
                n_hour = request_data['n_hour'].strip()
                if ((n_hour == 'immediate') or
                    (n_hour == '1-hour') or
                    (n_hour == '2-hour') or
                    (n_hour == '4-hour') or
                    (n_hour == '12-hour') or
                    (n_hour == '24-hour')):
                    # pass parsed parameters to the database method
                    return change_emailSettings(username, n_hour)
                    #return sendEmail(0, '2-hour', 60)
                else:    return jsonify(**{'success': False, 'message': "Error: settings api, n_hour wrong format."}), 422
                #else:    return jsonify(**{'success': False, 'message': username + " " + n_hour}), 422
            else:        return jsonify(**{'success': False, 'message': "Error: settings api, missing n_hour"}), 422
        else:            return jsonify(**{'success': False, 'message': "Error: settings api, missing username."}), 422

## Used when creating a new user
class RegisterAPI(MethodView):
    def post(self):
        request_data = request.get_json(force=True, silent=True)
        if request_data is None:
            request_data = {}

        errors, cleaned_data = self.validate_data(request_data)

        if errors:
            return jsonify(**{'success': False, 'errors': errors}), 422

        user = create_new_user(**cleaned_data)
        new_user_statistics = UserStatistics(user_id = user.id)
        new_presence = Presence(user_id = user.id)
        new_setting = Settings(user_id = user.id)
        new_userprivilege = UserPrivileges(user_id = user.id)
        db.session.add(new_setting)
        db.session.add(new_user_statistics)
        db.session.add(new_presence)
        db.session.add(new_userprivilege)
        db.session.commit()

        login_user(user)

        return jsonify(**{'success': True, 'authenticated': current_user.is_authenticated(), 'user': current_user_props()})

    def validate_data(self, request_data):
        errors = {}
        cleaned_data = {}

        props = ['username', 'password', 'email', 'first_name', 'last_name']

        # Check missing arguments
        missing = validation.missing_props(props, request_data)
        if missing:
            errors['missing'] = {prop: prop + ' is missing' for prop in missing}

        # Check type of arugments
        bad_types = validation.bad_types({prop: str for prop in props}, request_data)
        if bad_types:
            errors['invalid_types'] = {prop: prop + ' has an invalid type' for prop in bad_types}

        # Check for valid lengths
        bad_lengths = validation.bad_lengths({
            'username':     (5, 20),
            'password':     (6, 40),
            'email':        (None, 60),
            'first_name':   (1, 40),
            'last_name':    (1, 40)
        }, request_data)
        if bad_lengths:
            errors['invalid_lengths'] = {prop: prop + ' has an invalid length' for prop in bad_lengths}

        # Check if valid email
        if ('email' in request_data) and (not validation.valid_email(request_data['email'])):
            errors['invalid_email'] = 'email is not valid'

        # Check if valid password
        if ('password' in request_data) and (not validation.valid_password(request_data['password'])):
            errors['weak_password'] = 'Need an upper/lowercase and a number'

        # Check uniqueness
        if User.query.filter_by(username=request_data['username']).first():
            errors['username_taken'] = request_data['username']

        if User.query.filter_by(email=request_data['email']).first():
            errors['email_taken'] = request_data['email']

		#check if valid user name
        if ('username' in request_data) and (not validation.valid_username(request_data['username'])):
		    errors['invalid_username'] = 'username contained restricted symbol'

        # Quick and easy dict comprehension to convert all data to strings
        cleaned_data = {prop: str(request_data[prop]) for prop in props if prop in request_data}

        return errors, cleaned_data

## Used to change the passwords
class PasswordChangeApi(MethodView):
    def post(self):
        request_data = request.get_json(force=True, silent=True)
        if request_data is None:
            return jsonify(**{'success': "none" }), 401
        if('user' in request_data and 'password' in request_data and 'tok' in request_data):
            data = {'username': request_data['user'], 'verification': request_data['tok']}
            user = User.query.filter_by(**data).first()

            if user is None:
                return jsonify(**{'success': False}), 401
            #user.password = hash_password(request_data['password'])
            user.password = request_data['password']
            db.session.add(user)
            db.session.commit()
            return jsonify(**{'success': True})

        return jsonify(**{'success': False}), 401

## Updates the verify flag in the database
class VerifyUserAPi(MethodView):
    def post(self):
        request_data = request.get_json(force=True, silent=True)
        if request_data is None:
            return jsonify(**{'success': "none" }), 401
        if('user' in request_data and 'tok' in request_data):
            data = {'username': request_data['user'], 'verification': request_data['tok']}
            user = User.query.filter_by(**data).first()

            if user is None:
                return jsonify(**{'success': False, 'user': request_data['user'],'key': request_data['tok']}), 401
            user.new_user = 0
            db.session.add(user)
            db.session.commit()
            return jsonify(**{'success': True})

        return jsonify(**{'success': False}), 401

## Routing and View bindings
settings_view = SettingsAPI.as_view('settings')
app.add_url_rule('/api/users/settings/', view_func=settings_view, methods=['POST'])

change_details_view = ChangeDetailsAPI.as_view('change_details')
app.add_url_rule('/api/users/change_details/', view_func=change_details_view, methods=['POST'])

register_view = RegisterAPI.as_view('register_api')
app.add_url_rule('/api/users/register/', view_func=register_view, methods=['POST'])

password_change_view = PasswordChangeApi.as_view('password_change_api')
app.add_url_rule('/api/users/changepass/', view_func=password_change_view, methods=['POST'])

verify_user_view = VerifyUserAPi.as_view('verify_user_api')
app.add_url_rule('/api/users/verifyuser/', view_func=verify_user_view, methods=['POST'])