text:
#include "../precompiled/stdafx.h"
#include "../engine/base.h"
#include "../../common/utility/ext_util.h"

//////////////////////////////////////////////////////////////////////////
// Global debug options
//////////////////////////////////////////////////////////////////////////

#define FULLSCREEN_FLAG true
CTexture *mm = new CTexture();

//////////////////////////////////////////////////////////////////////////
// Global engine and modules variables
//////////////////////////////////////////////////////////////////////////

CEngine					*g_Engine = NULL;
COpenGL					*g_OpenGL = NULL;
CInputSystem			*g_Input = NULL;
CWindowSystem			*g_Winsys = NULL;
CNetworkSystem			*g_Network = NULL;
CFrustum				*g_Frustum = NULL;
CMap					*g_Map = NULL;
CPlayer					*g_Player = NULL;
CConsole				*g_Console = NULL;
CLanguagePack			*g_Language = NULL;

ext::manager<CTexture>	*g_TextureMgr = NULL;
ext::manager<CFontBase>	*g_FontMgr = NULL;
ext::manager<COption>	*g_Options = NULL;

//////////////////////////////////////////////////////////////////////////
// CEngine default constructor & destructor
//////////////////////////////////////////////////////////////////////////

CEngine::CEngine()
{
	// set global variables
	g_Engine = this;

	// state
	m_bRunning = false;

	// screen variables
	m_uiScreenWidth = 0;
	m_uiScreenHeight = 0;
	m_uiScreenDepth = 0;

	// modules
	m_OpenGL = NULL;
	m_Console = NULL;
	m_Input = NULL;
	m_Frustum = NULL;
	m_Map = NULL;
	m_Network = NULL;
	m_Winsys = NULL;
	m_Player = NULL;
	m_Language = NULL;

	// managers
	m_TextureMgr = NULL;
	m_FontMgr = NULL;
	m_Options = NULL;
}

CEngine::~CEngine()
{
	// free
	Close();
}

//////////////////////////////////////////////////////////////////////////
// Startup() : Prepares the engine to run
//////////////////////////////////////////////////////////////////////////

int CEngine::Startup(const std::string & strTitle)
{
	// sets up the texture manager
	m_TextureMgr = new ext::manager<CTexture>;
	if(!m_TextureMgr) return ERR_OUTOFMEM;
	g_TextureMgr = m_TextureMgr;

	// sets up the font manager
	m_FontMgr = new ext::manager<CFontBase>;
	if(!m_FontMgr) return ERR_OUTOFMEM;
	g_FontMgr = m_FontMgr;

	// sets up the options manager
	m_Options = new ext::manager<COption>;
	if(!m_Options) return ERR_OUTOFMEM;
	g_Options = m_Options;

	// sets up the language manager
	m_Language = new CLanguagePack();
	if(!m_Language) return ERR_OUTOFMEM;
	g_Language = m_Language;

	// create opengl object
	m_OpenGL = new COpenGL();
	if(!m_OpenGL) return ERR_OUTOFMEM;
	g_OpenGL = m_OpenGL;

	// create input object
	m_Input = new CInputSystem();
	if(!m_Input) return ERR_OUTOFMEM;
	g_Input = m_Input;

	// create network
	//m_Network = new CNetworkSystem();
	//if(!m_Network) return ERR_OUTOFMEM;
	//g_Network = m_Network;

	// create window system
	m_Winsys = new CWindowSystem();
	if(!m_Winsys) return ERR_OUTOFMEM;
	g_Winsys = m_Winsys;

	// create frustum object
	m_Frustum = new CFrustum();
	if(!m_Frustum) return ERR_OUTOFMEM;
	g_Frustum = m_Frustum;

	// create console object
	m_Console = new CConsole();
	if(!m_Console) return ERR_OUTOFMEM;
	g_Console = m_Console;

	// create player object
	m_Player = new CHumanPlayer();
	if(!m_Player) return ERR_OUTOFMEM;
	g_Player = m_Player;

	// create map object
	m_Map = new CMap();
	if(!m_Map) return ERR_OUTOFMEM;
	g_Map = m_Map;

	// set window title
	m_strWindowTitle = strTitle;

	// initialize sdl
	SDL_Init(SDL_INIT_TIMER);

	// initialize random number generator
	srand(SDL_GetTicks());

	// no errors
	return ERR_OK;
}

//////////////////////////////////////////////////////////////////////////
// Close() : Closes and frees the engine
//////////////////////////////////////////////////////////////////////////

int CEngine::Close()
{
	// destroy map object
	delete m_Map;
	m_Map = NULL;
	g_Map = NULL;

	// destroy player object
	delete m_Player;
	m_Player = NULL;
	g_Player = NULL;

	// destroy console object
	delete m_Console;
	m_Console = NULL;
	g_Console = NULL;

	// destroy window system object
	delete m_Winsys;
	m_Winsys = NULL;
	g_Winsys = NULL;

	// destroy frustum object
	delete m_Frustum;
	m_Frustum = NULL;
	g_Frustum = NULL;

	// destroy network object
	//delete m_Network;
	//m_Network = NULL;
	//g_Network = NULL;

	// shuts down sound system
	//alutExit();

	// destroy input object
	delete m_Input;
	m_Input = NULL;
	g_Input = NULL;

	// destroy opengl object
	delete m_OpenGL;
	m_OpenGL = NULL;
	g_OpenGL = NULL;

	// destroy language object
	delete m_Language;
	m_Language = NULL;
	g_Language = NULL;

	// destroys the options manager
	delete m_Options;
	m_Options = NULL;
	g_Options = NULL;

	// destroys the font manager
	delete m_FontMgr;
	m_FontMgr = NULL;
	g_FontMgr = NULL;

	// destroys the texture manager
	delete m_TextureMgr;
	m_TextureMgr = NULL;
	g_TextureMgr = NULL;

	// shut down sdl
	SDL_Quit();

	// screen variables
	m_uiScreenWidth = 0;
	m_uiScreenHeight = 0;
	m_uiScreenDepth = 0;

	// state
	m_bRunning = false;

	// no errors
	return ERR_OK;
}

//////////////////////////////////////////////////////////////////////////
// SetupModules() : Initializes the modules
//////////////////////////////////////////////////////////////////////////

int CEngine::Setup()
{
	bool bRet;

	// load options
	if(!LoadOptions()) return ERR_SETUP;

	// get screen info
	m_uiScreenWidth = ext::get_option_int("screen_width");
	m_uiScreenHeight = ext::get_option_int("screen_height");
	m_uiScreenDepth = ext::get_option_int("screen_depth");

	// load language pack
	bRet = m_Language->Load("language/español.xml");
	if(!bRet) return ERR_SETUP;

	// create window
	bRet = m_OpenGL->InitWindow(m_strWindowTitle, m_uiScreenWidth,
		m_uiScreenHeight, m_uiScreenDepth, FULLSCREEN_FLAG);
	if(!bRet) return ERR_SETUP;

	// startup input
	bRet = m_Input->Init();
	if(!bRet) return ERR_SETUP;

	// startup sound system
	bool bSfx = ext::get_option_int("sfx") ? true : false;
	bool bMusic = ext::get_option_int("music") ? true : false;
/*	if(bSfx || bMusic)
	{
		alutInit(NULL, 0);
		bRet = alGetError() ? true : false;
		if(bRet) return ERR_SETUP;
	}
*/
	// startup network system
	//bRet = m_Network->Startup();
	//if(!bRet) return ERR_SETUP;

	// startup window system
	bRet = m_Winsys->Startup();
	if(!bRet) return ERR_SETUP;

	// startup console
	bRet = m_Console->Initialize(0, m_uiScreenHeight - 150, 350, 150, "arial");
	if(!bRet) return ERR_SETUP;

	// setup console colors
	m_Console->SetBackColor(0.0f, 0.0f, 0.0f, 0.0f);
	m_Console->SetTextColor(1.0f, 1.0f, 1.0f, 0.7f);

	// setup window system
	m_Winsys->Enable(true);
	m_Winsys->EnableMouse(true);

	// no errors here
	return ERR_OK;
}

//////////////////////////////////////////////////////////////////////////
// Run() : Starts the engine core
//////////////////////////////////////////////////////////////////////////

int CEngine::Run()
{
	int iRet;
	SDL_Event event;

	// setup modules
	iRet = Setup();
	if(iRet != ERR_OK) return iRet;

	// load stuff
	InitialLoad();

	// start running
	m_bRunning = true;

	// main loop
	while(m_bRunning)
	{
		// poll sdl events
		while(SDL_PollEvent(&event))
		{
			switch(event.type)
			{
			case SDL_QUIT:
				m_bRunning = false;
				break;
			}
		}

		// Process Engine Tick
		Tick();
	}

	// no errors
	return ERR_OK;
}

//////////////////////////////////////////////////////////////////////////
// Tick() : Main engine loop function
//////////////////////////////////////////////////////////////////////////

void CEngine::Tick()
{
	/////////////////////////////////////////////////////
	// Update
	/////////////////////////////////////////////////////

	// Keyboard & Mouse
	m_Input->Update();

	// Networking System
	//m_Network->Control();

	// Window system
	if(m_Winsys->IsEnabled()) m_Winsys->Update();

	// Player
	if(m_Player->IsAlive()) m_Player->Update();

	// Console (Activation)
	if(m_Input->GetKeyHit(SDLK_RETURN))
	{
		char c = m_Input->GetQueuedKey();
		m_Console->PassKey(c);
		m_Console->Switch();
	}

	// Console (Pass Keys)
	if(m_Console->IsActive())
	{
		// queue key
		char c = m_Input->GetQueuedKey();

		// exhaust queue
		while(c != 0)
		{
			m_Console->PassKey(c);
			c = m_Input->GetQueuedKey();
		}
	}

	/////////////////////////////////////////////////////
	// Handle
	/////////////////////////////////////////////////////

	// screenshot handler
	if(m_Input->GetKey(SDLK_F12)) m_OpenGL->SaveScreenshot();
	if(m_Input->GetKey(SDLK_ESCAPE)) Stop();

	// Player
	if(m_Player->IsAlive())
	{
		// move
		if(m_Input->GetKey(SDLK_w)) m_Player->Move(40);
		if(m_Input->GetKey(SDLK_s)) m_Player->Move(-40);
		if(m_Input->GetKey(SDLK_a)) m_Player->Strafe(-40);
		if(m_Input->GetKey(SDLK_d)) m_Player->Strafe(40);

		// update player
		m_Player->Update();
	}

	/////////////////////////////////////////////////////
	// Clear
	/////////////////////////////////////////////////////

	// Clear color buffer
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	// Clear matrix
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();

	// Clear color & buffers
	glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
	glClearDepth(1.0f);

	/////////////////////////////////////////////////////
	// Render
	/////////////////////////////////////////////////////

	// Map
	if(!m_Winsys->IsEnabled())
	{
		// map
		if(m_Map) m_Map->Render();

		// Player model
		if(m_Player) m_Player->Render();

		// Console
		if(m_Console->IsEnabled())
		{
			// Overlay
			m_OpenGL->OverlayBegin(m_uiScreenWidth, m_uiScreenHeight, true);

			// Render Console
			m_Console->Render();

			// Set 3D
			m_OpenGL->OverlayEnd();
		}
	}
	else
	{
		// Set 2D
		m_OpenGL->OverlayBegin(m_uiScreenWidth, m_uiScreenHeight, true);

		// Window system
		if(m_Winsys->IsEnabled()) m_Winsys->Render();

		// Set 3D
		m_OpenGL->OverlayEnd();
	}

	// swap buffers
	m_OpenGL->SwapBuffers();
}

//////////////////////////////////////////////////////////////////////////
// InitialLoad() : Shows loading screen and loads primary stuff
//////////////////////////////////////////////////////////////////////////

void CEngine::InitialLoad()
{
	//////////////////////////
	// Draw loading text

	// Clear color buffer
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	// Clear color & buffers
	glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
	glClearDepth(1.0f);

	// Set 2D
	m_OpenGL->OverlayBegin(m_uiScreenWidth, m_uiScreenHeight, true);

	// Texture
	//glEnable(GL_TEXTURE_2D);
	glDisable(GL_TEXTURE_2D);
	//texLoading->Use();

	glBegin(GL_TRIANGLE_STRIP);
			glTexCoord2i(0, 1);
			glVertex2i(110, 200);

			glTexCoord2i(0, 0);
			glVertex2i(110, 400);

			glTexCoord2i(1, 1);
			glVertex2i(690, 200);

			glTexCoord2i(1, 0);
			glVertex2i(690, 400);
	glEnd();

	glDisable(GL_TEXTURE_2D);

	// Set 3D
	m_OpenGL->OverlayEnd();

	// Swap buffers
	m_OpenGL->SwapBuffers();

	//////////////////////////
	// Load...

	mm->Create("gfx/gui.pak/main_menu.jpg", FIF_UNKNOWN, false);

	// Fade
	g_OpenGL->FadeToBlack(60);

	//////////////////////////
	// Change mode

	to_MainMenu();
}

//////////////////////////////////////////////////////////////////////////
// MainMenu() : MENU
//////////////////////////////////////////////////////////////////////////

void CEngine::to_MainMenu()
{
	static CButton winConnect;
	static CButton winCreatePlayer;
	static CButton winDeletePlayer;
	static CButton winOptions;
	static CButton winCredits;
	static CButton winQuit;

	// clear window system's windows
	g_Winsys->ClearWindows();

	// boton : "conectar"
	//if(g_Network->IsConnected())
	if(0)
	{
		winConnect.SetCaption("Desconectar");
		winConnect.SetOnClick(menu_Disconnect);
	}
	else
	{
		//winConnect.SetCaption("Conectar al servidor");
		winConnect.SetCaption(g_Language->GetString(STR_CONNECT_TO_SERVER).c_str());
		winConnect.SetOnClick(to_ConnectMenu);
	}
	winConnect.SetPos(550, 150);
	winConnect.SetSize(200, 30);
	g_Winsys->AddWindow(&winConnect);

	// boton : "crear personaje"
	winCreatePlayer.SetPos(550, 200);
	winCreatePlayer.SetSize(200, 30);
	winCreatePlayer.SetCaption("Crear personaje");
	winCreatePlayer.SetOnClick(to_CreatePlayerMenu);
	g_Winsys->AddWindow(&winCreatePlayer);

	// boton : "borrar personaje"
	winDeletePlayer.SetPos(550, 250);
	winDeletePlayer.SetSize(200, 30);
	winDeletePlayer.SetCaption("Borrar personaje");
	winDeletePlayer.SetOnClick(to_DeletePlayerMenu);
	g_Winsys->AddWindow(&winDeletePlayer);

	// boton : "opciones"
	winOptions.SetPos(550, 300);
	winOptions.SetSize(200, 30);
	winOptions.SetCaption("Opciones");
	winOptions.SetOnClick(to_OptionsMenu);
	g_Winsys->AddWindow(&winOptions);

	// boton : "creditos"
	winCredits.SetPos(550, 350);
	winCredits.SetSize(200, 30);
	winCredits.SetCaption("Creditos");
	winCredits.SetOnClick(to_CreditsMenu);
	g_Winsys->AddWindow(&winCredits);

	// boton : "salir"
	winQuit.SetPos(550, 400);
	winQuit.SetSize(200, 30);
	winQuit.SetCaption("Salir");
	g_Winsys->AddWindow(&winQuit);

	// set background
	g_Winsys->SetBackground(mm);
}

//////////////////////////////////////////////////////////////////////////
// Connect() : MENU
//////////////////////////////////////////////////////////////////////////

void CEngine::to_ConnectMenu()
{
	static CButton		winConnect;
	static CButton		winBack;

	static CStatic		sUserName;
	static CTextBox		winUserName;

	static CStatic		sPassWord;
	static CTextBox		winPassWord;

	// clear windows
	g_Winsys->ClearWindows();

	// boton : "conectar"
	winConnect.SetPos(550, 150);
	winConnect.SetSize(200, 30);
	winConnect.SetCaption("Conectar!");
	winConnect.SetOnClick(menu_Connect);
	g_Winsys->AddWindow(&winConnect);

	// boton : "volver"
	winBack.SetPos(550, 200);
	winBack.SetSize(200, 30);
	winBack.SetCaption("Volver");
	winBack.SetOnClick(to_MainMenu);
	g_Winsys->AddWindow(&winBack);

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

	sUserName.SetPos(50, 140);
	sUserName.SetCaption("Nombre de usuario:");
	g_Winsys->AddWindow(&sUserName);

	winUserName.SetPos(50, 150);
	winUserName.SetSize(300, 20);
	winUserName.SetCaption("BetaTester");
	winUserName.SetMaxLength(25);
	winUserName.SetID(ID_CONNECT_USERNAME);
	g_Winsys->AddWindow(&winUserName);

	sPassWord.SetPos(50, 190);
	sPassWord.SetCaption("Password:");
	g_Winsys->AddWindow(&sPassWord);

	winPassWord.SetPos(50, 200);
	winPassWord.SetSize(300, 20);
	winPassWord.SetPassword(true);
	winPassWord.SetMaxLength(25);
	winPassWord.SetID(ID_CONNECT_PASSWORD);
	g_Winsys->AddWindow(&winPassWord);

	// set background
	//g_Winsys->SetBackground(texGetObject("gui_main_menu.jpg"));

	// default button : connect
	winConnect.BringToTop();

}

void CEngine::menu_Connect()
{
	// get username & password
	CWindow *winUserName = g_Winsys->FindWindow(ID_CONNECT_USERNAME);
	CWindow *winPassWord = g_Winsys->FindWindow(ID_CONNECT_PASSWORD);

	// create player
	TQualities t;
	g_Player->Create(winUserName->GetText(), &t);

	// load map
	DWORD tt = GetTickCount();
	g_Map->Load(11, FROM_NORTH);
	g_Player->SetPosition(0, 0, 0);
	std::ostringstream o;
	o << "Map loading time: " << GetTickCount() - tt << " ms.";
	g_Console->Print("Genesis: The Book of Firsts");
	g_Console->Print("Engine Version: 0.1 Alpha");
	g_Console->Print(o.str());

	// set modules state
	g_Winsys->ClearWindows();
	g_Winsys->FreeBackground();
	g_Winsys->Enable(false);
	g_Winsys->EnableMouse(false);
	g_Console->Enable(true);
}

void CEngine::menu_Disconnect()
{
	//g_Network->Disconnect();
}

//////////////////////////////////////////////////////////////////////////
// CreatePlayerMenu() : MENU
//////////////////////////////////////////////////////////////////////////

void CEngine::to_CreatePlayerMenu()
{
	static CButton		winCreate;
	static CButton		winBack;

	static CStatic		sUserName;
	static CTextBox		winUserName;

	static CStatic		sPassWord;
	static CTextBox		winPassWord;

	static CStatic		sMail;
	static CTextBox		winMail;

	static CStatic		sRace;

	static CStatic		sHuman;
	static CCheckBox	winHuman;

	static CStatic		sElf;
	static CCheckBox	winElf;

	static CStatic		sOrc;
	static CCheckBox	winOrc;

	static CImageBox	winRaceImage;

	// clear windows
	g_Winsys->ClearWindows();

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

	// boton : "crear"
	winCreate.SetPos(550, 150);
	winCreate.SetSize(200, 30);
	winCreate.SetCaption("Crear!");
	winCreate.SetOnClick(menu_Create);
	g_Winsys->AddWindow(&winCreate);

	// boton : "volver"
	winBack.SetPos(550, 200);
	winBack.SetSize(200, 30);
	winBack.SetCaption("Volver");
	winBack.SetOnClick(to_MainMenu);
	g_Winsys->AddWindow(&winBack);

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

	sUserName.SetPos(50, 140);
	sUserName.SetCaption("Nombre de usuario:");
	g_Winsys->AddWindow(&sUserName);

	winUserName.SetPos(50, 150);
	winUserName.SetSize(200, 20);
	winUserName.SetCaption("BetaTester");
	winUserName.SetMaxLength(25);
	winUserName.SetID(ID_CREATE_USERNAME);
	g_Winsys->AddWindow(&winUserName);

	sPassWord.SetPos(50, 190);
	sPassWord.SetCaption("Contraseña:");
	g_Winsys->AddWindow(&sPassWord);

	winPassWord.SetPos(50, 200);
	winPassWord.SetSize(200, 20);
	winPassWord.SetMaxLength(25);
	winPassWord.SetPassword(true);
	winPassWord.SetID(ID_CREATE_PASSWORD);
	g_Winsys->AddWindow(&winPassWord);

	sMail.SetPos(50, 240);
	sMail.SetCaption("E-Mail:");
	g_Winsys->AddWindow(&sMail);

	winMail.SetPos(50, 250);
	winMail.SetSize(200, 20);
	winMail.SetMaxLength(60);
	winMail.SetID(ID_CREATE_MAIL);
	g_Winsys->AddWindow(&winMail);

	sRace.SetPos(50, 290);
	sRace.SetCaption("Selecciona una raza:");
	g_Winsys->AddWindow(&sRace);

	sHuman.SetPos(70, 310);
	sHuman.SetCaption("Humano");
	g_Winsys->AddWindow(&sHuman);

	winHuman.SetPos(130, 300);
	winHuman.SetSize(10, 10);
	g_Winsys->AddWindow(&winHuman);

	sElf.SetPos(70, 330);
	sElf.SetCaption("Elfo");
	g_Winsys->AddWindow(&sElf);

	winElf.SetPos(130, 320);
	winElf.SetSize(10, 10);
	g_Winsys->AddWindow(&winElf);

	sOrc.SetPos(70, 350);
	sOrc.SetCaption("Orco");
	g_Winsys->AddWindow(&sOrc);

	winOrc.SetPos(130, 340);
	winOrc.SetSize(10, 10);
	g_Winsys->AddWindow(&winOrc);

	winRaceImage.SetPos(290, 130);
	winRaceImage.SetSize(200, 440);
	//winRaceImage.SetTexture(texGetObject("gui_human.jpg"));
	g_Winsys->AddWindow(&winRaceImage);

	// set background
	//g_Winsys->SetBackground(texGetObject("gui_main_menu.jpg"));

	// default button : connect
	winCreate.BringToTop();
}

void CEngine::menu_Create()
{
}

//////////////////////////////////////////////////////////////////////////
// DeletePlayerMenu() : MENU
//////////////////////////////////////////////////////////////////////////

void CEngine::to_DeletePlayerMenu()
{
}

//////////////////////////////////////////////////////////////////////////
// Options() : MENU
//////////////////////////////////////////////////////////////////////////

void CEngine::to_OptionsMenu()
{
}

//////////////////////////////////////////////////////////////////////////
// Credits() : MENU
//////////////////////////////////////////////////////////////////////////

void CEngine::to_CreditsMenu()
{
	static CStatic sCredits;
	static CButton winBack;

	// clear windows
	g_Winsys->ClearWindows();

	// boton : "volver"
	winBack.SetPos(550, 150);
	winBack.SetSize(200, 30);
	winBack.SetCaption("Volver");
	winBack.SetOnClick(to_MainMenu);
	g_Winsys->AddWindow(&winBack);

	// creditos
	sCredits.SetPos(50, 140);
	sCredits.SetColor(255, 255, 255);
	sCredits.SetCaption("== Lords of Genesis == Copyright (c) 2003 F.M.C.");
	g_Winsys->AddWindow(&sCredits);

	// set background
	//g_Winsys->SetBackground(texGetObject("gui_main_menu.jpg"));

	// default button : connect
	winBack.BringToTop();
}

//////////////////////////////////////////////////////////////////////////
// LoadOptions() : Loads all the options in "options.xml" to a database
//////////////////////////////////////////////////////////////////////////

bool CEngine::LoadOptions()
{
	xmlDocPtr	doc;
	xmlNodePtr	node;
	xmlChar		*type;

	// open and parse options file
	doc = xmlParseFile("options.xml");
	if(!doc) return false;

	// get root node
	node = xmlDocGetRootElement(doc);
	if(!node)
	{
		xmlFreeDoc(doc);
		return false;
	}

	// check for options file
	if(xmlStrcmp(node->name, (const xmlChar *) "options") != 0)
	{
		xmlFreeDoc(doc);
		return false;
	}

	// set to first sub-node
	node = node->children->next;

	// start reading options
	while(node != NULL)
	{
		// we dont want the text inside
		if(xmlStrcmp(node->name, (const xmlChar *) "text") != 0)
		{
			// get option type
			type = xmlGetProp(node, (const xmlChar *) "type");

			// string option
			if(xmlStrcmp(type, (const xmlChar *) "string") == 0)
			{
				xmlChar *key = xmlNodeListGetString(doc, node->children, 1);

				COption *opt = new COption(std::string((const char *) key));
				g_Options->Add(std::string((const char *) node->name), opt);

				xmlFree(key);
			}
			// int option
			else if(xmlStrcmp(type, (const xmlChar *) "int") == 0)
			{
				xmlChar *key = xmlNodeListGetString(doc, node->children, 1);
				int number = (int) xmlXPathCastStringToNumber(key);

				COption *opt = new COption(number);
				g_Options->Add(std::string((const char *) node->name), opt);

				xmlFree(key);
			}
			// float option
			else if(xmlStrcmp(type, (const xmlChar *) "float") == 0)
			{
				xmlChar *key = xmlNodeListGetString(doc, node->children, 1);
				float number = (float) xmlXPathCastStringToNumber(key);

				COption *opt = new COption(number);
				g_Options->Add(std::string((const char *) node->name), opt);

				xmlFree(key);
			}

			// free type
			xmlFree(type);
		}

		// go to the next node
		node = node->next;
	}

	// close options file
	xmlFreeDoc(doc);

	// no errors
	return true;
}

//////////////////////////////////////////////////////////////////////////
// SaveOptions() : Saves the options database to "options.xml"
//////////////////////////////////////////////////////////////////////////

bool CEngine::SaveOptions()
{
	// no errors
	return true;
}

//////////////////////////////////////////////////////////////////////////
// End
//////////////////////////////////////////////////////////////////////////


text:
package org.apache.hadoop.hbase.client;

import java.io.IOException;
import java.util.Random;

import org.apache.commons.logging.Log;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.ServerName;
import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.AdminService;
import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.ClientService;

/**
 * Utility used by client connections.
 */
@InterfaceAudience.Private
public class ConnectionUtils {

  private static final Random RANDOM = new Random();
  /**
   * Calculate pause time.
   * Built on {@link HConstants#RETRY_BACKOFF}.
   * @param pause
   * @param tries
   * @return How long to wait after tries retries
   */
  public static long getPauseTime(final long pause, final int tries) {
    int ntries = tries;
    if (ntries >= HConstants.RETRY_BACKOFF.length) {
      ntries = HConstants.RETRY_BACKOFF.length - 1;
    }

    long normalPause = pause * HConstants.RETRY_BACKOFF[ntries];
    long jitter =  (long)(normalPause * RANDOM.nextFloat() * 0.01f); // 1% possible jitter
    return normalPause + jitter;
  }

  /**
   * Adds / subs a 10% jitter to a pause time. Minimum is 1.
   * @param pause the expected pause.
   * @param jitter the jitter ratio, between 0 and 1, exclusive.
   */
  public static long addJitter(final long pause, final float jitter) {
    float lag = pause * (RANDOM.nextFloat() - 0.5f) * jitter;
    long newPause = pause + (long) lag;
    if (newPause <= 0) {
      return 1;
    }
    return newPause;
  }

  /**
   * @param conn The connection for which to replace the generator.
   * @param cnm Replaces the nonce generator used, for testing.
   * @return old nonce generator.
   */
  public static NonceGenerator injectNonceGeneratorForTesting(
      HConnection conn, NonceGenerator cnm) {
    return ConnectionManager.injectNonceGeneratorForTesting(conn, cnm);
  }

  /**
   * Changes the configuration to set the number of retries needed when using HConnection
   * internally, e.g. for  updating catalog tables, etc.
   * Call this method before we create any Connections.
   * @param c The Configuration instance to set the retries into.
   * @param log Used to log what we set in here.
   */
  public static void setServerSideHConnectionRetriesConfig(
      final Configuration c, final String sn, final Log log) {
    int hcRetries = c.getInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER,
      HConstants.DEFAULT_HBASE_CLIENT_RETRIES_NUMBER);
    // Go big.  Multiply by 10.  If we can't get to meta after this many retries
    // then something seriously wrong.
    int serversideMultiplier = c.getInt("hbase.client.serverside.retries.multiplier", 10);
    int retries = hcRetries * serversideMultiplier;
    c.setInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER, retries);
    log.info(sn + " server-side HConnection retries=" + retries);
  }

  /**
   * Adapt a HConnection so that it can bypass the RPC layer (serialization,
   * deserialization, networking, etc..) when it talks to a local server.
   * @param conn the connection to adapt
   * @param serverName the local server name
   * @param admin the admin interface of the local server
   * @param client the client interface of the local server
   * @return an adapted/decorated HConnection
   */
  public static HConnection createShortCircuitHConnection(final HConnection conn,
      final ServerName serverName, final AdminService.BlockingInterface admin,
      final ClientService.BlockingInterface client) {
    return new ConnectionAdapter(conn) {
      @Override
      public AdminService.BlockingInterface getAdmin(
          ServerName sn, boolean getMaster) throws IOException {
        return serverName.equals(sn) ? admin : super.getAdmin(sn, getMaster);
      }

      @Override
      public ClientService.BlockingInterface getClient(
          ServerName sn) throws IOException {
        return serverName.equals(sn) ? client : super.getClient(sn);
      }
    };
  }
}

redpajama_set_name: RedPajamaGithub


text:
import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';

moduleForComponent('bc-radio-button', 'Integration | Component | bc radio button', {
  integration: true
});

test('it renders', function(assert) {
  // Set any properties with this.set('myProperty', 'value');
  // Handle any actions with this.on('myAction', function(val) { ... });

  this.render(hbs`{{bc-radio-button}}`);

  assert.equal(this.$().text().trim(), '');

  // Template block usage:
  this.render(hbs`
	{{#bc-radio-button}}
	  template block text
	{{/bc-radio-button}}
  `);

  assert.equal(this.$().text().trim(), '');
});

test('click returns true', function(assert)
{
	this.render(hbs`
		{{bc-radio-button }}
	`);

	this.$('input').click();

	assert.throws('true');
});


text:
import { BaseImageResource } from './BaseImageResource';

/**
 * Resource type for ImageBitmap.
 * @class
 * @extends PIXI.BaseImageResource
 * @memberof PIXI
 */
export class ImageBitmapResource extends BaseImageResource
{
    /**
     * @param {ImageBitmap} source - Image element to use
     */
    // eslint-disable-next-line @typescript-eslint/no-useless-constructor
    constructor(source: ImageBitmap)
    {
        super(source);
    }

    /**
     * Used to auto-detect the type of resource.
     *
     * @static
     * @param {ImageBitmap} source - The source object
     * @return {boolean} `true` if source is an ImageBitmap
     */
    static test(source: unknown): source is ImageBitmap
    {
        return !!self.createImageBitmap && source instanceof ImageBitmap;
    }
}


text:
use strict;
use warnings;
use File::Slurp ;

my $datain = 'data/preprocessed';
my $dataout = 'data/parsed';
my $failcount = 0;
my $goodcount = 0;
my $bar = "----------------\n";
my $exename = "ptrans" ;

if (! -d $dataout) {
    unless(mkdir $dataout) {
        die "Unable to create $dataout\n";
    }
}

print "Making Clean\n";
my $compileResult = `make clean` ;
print "Testing Compile\n";
print $bar ;
$compileResult = `make` ;
print $bar ;
print "Compilation Results:\n" ;
print "$compileResult\n" ;

print "Changing Permissions on executable\n";
if ( $^O eq "darwin" || $^O eq "linux" ) {
  my $chresult = `chmod a+x $exename` ;
} else {
  print "On windows you have to give executable permissions on the compiled $exename manually!\n\n" ;
}

print "\n" ;

if ( ! -x "ptrans" ) {
  print "ERROR! no ptrans executable can be run, check permissions or compilation results above\n" ;
  exit( 1 ) ;
}

opendir(DIR, $datain) or die $!;

print "Running ptrans on data directory $datain and output to $dataout\n";
print "$bar";
while (my $infile = readdir(DIR)) {

  # We only want files
  next unless (-f "$datain/$infile");

  # Use a regular expression to find input files
  next unless ($infile =~ m/(.*)\.in$/);

  # Output file has same name, different extension
  my $outfile = $1 . ".out" ;

  print "Generating output file $outfile for input file $infile\n" ;

  my $transformOutput = `./ptrans $datain/$infile > $dataout/$outfile` ;
}

print "$bar";
print "Finished generating data output files!\n" ;

closedir(DIR);
exit 0;


text:
<!DOCTYPE html>

Artists

        <button id='create'>Create</button>


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

namespace HashTable
{
    [Serializable]
    public class HashTable<T, U> : IDictionary<T, U>
    {

        private LinkedList<T, U>[] data;
        private int cap;
        private int count = 0;

        public HashTable() : this(10) { }
        public HashTable(int size)
        {
            data = new LinkedList<T, U>[10];
            cap = 10;
        }
        public void Add(T key, U value)
        {
            if (key == null)
            {
                throw new ArgumentNullException("key");
            }
            var hash = key.GetHashCode() % cap;
            var cell = data[(uint)key.GetHashCode() % cap];
            if (cell == null)
            {
                cell = new LinkedList<T, U>();
                data[(uint)key.GetHashCode() % cap] = cell;
            }
            try
            {
                var test = cell.Search(key);
                throw new ArgumentException();
            }
            catch (KeyNotFoundException)
            {

            }

            cell.Insert(key, value);
            count++;
        }

        public bool Remove(T key)
        {
            var cell = data[(uint)key.GetHashCode() % cap];
            if (cell == null)
            {
                return false;
            }

            if (data[(uint)key.GetHashCode() % cap].Delete(key))
            {
                count--;
                return true;
            }
            return false;
        }

        private U Search (T key) {
            if (key == null)
            {
                throw new ArgumentNullException("key");
            }
            var hash = key.GetHashCode() % cap;
            var cell = data[(uint)key.GetHashCode() % cap];
            if (cell == null)
            {
                throw new KeyNotFoundException();
            }
            return data[(uint)key.GetHashCode() % cap].Search(key);
        }

        public U this[T key]
        {
            get
            {
                return Search(key);
            }
            set
            {
                if (ContainsKey(key)) {
                    var cell = data[(uint)key.GetHashCode() % cap];
                    cell.Set(key, value);
                } else {
                    Add(key, value);
                }
            }
        }

        public bool ContainsKey(T key)
        {
            if (key == null)
            {
                throw new ArgumentNullException("key");
            }
            var cell = data[(uint)key.GetHashCode() % cap];
            if (cell == null)
            {
                return false;
            }

            try
            {
                var test = cell.Search(key);
            }
            catch (KeyNotFoundException)
            {
                return false;
            }

            return true;
        }

        public ICollection<T> Keys
        {
            get { return this.Select(x => x.Key).ToList(); }
        }

        public bool TryGetValue(T key, out U value)
        {
            if (ContainsKey(key))
            {
                value = this[key];
                return true;
            }
            value = default(U);
            return false;
        }

        public ICollection<U> Values
        {
            get { return this.Select(x => x.Value).ToList(); }
        }

        public void Add(KeyValuePair<T, U> item)
        {
            throw new NotImplementedException();
        }

        public void Clear()
        {
            count = 0;
            data = new LinkedList<T, U>[10];
            cap = 10;
        }

        public bool Contains(KeyValuePair<T, U> item)
        {
            try
            {
                return Search(item.Key).Equals(item.Value);

            }
            catch (Exception)
            {
                return false;
            }
        }

        public void CopyTo(KeyValuePair<T, U>[] array, int arrayIndex)
        {
            throw new NotImplementedException();
        }

        public int Count
        {
            get { return count; }
        }

        public bool IsReadOnly
        {
            get { throw new NotImplementedException(); }
        }

        public bool Remove(KeyValuePair<T, U> item)
        {
            try
            {
                if (Search(item.Key).Equals(item.Value))
                {
                    return Remove(item.Key);
                }
                return false;
            }
            catch (Exception)
            {
                return false;
            }

        }

        public IEnumerator<KeyValuePair<T, U>> GetEnumerator()
        {
            var size = count;
            for (int i = 0; i < cap; i++)
            {
                if (data[i] != null)
	            {
                    foreach (var item in data[i])
                    {
                        if (count != size)
                        {
                            throw new InvalidOperationException();
                        }
                        yield return item;
                    }
	            }

            }
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }
    [Serializable]
    public class LinkedList<T, U>
    {
        private Link<T, U> head;

        public LinkedList()
        {
            head = null;
        }

        public U Search(T k)
        {
            var x = head;
            while (x != null)
            {
                if (x.Pair.Key.Equals(k))
                {
                    return x.Pair.Value;
                }
                x = x.Next;
            }

            throw new KeyNotFoundException();
        }

        public void Insert(T key, U value)
        {
            var x = new Link<T, U>(key, value);
            x.Next = head;
            head = x;
        }

        public bool Delete(T k)
        {
            if (head != null && head.Pair.Key.Equals(k))
            {
                head = head.Next;
                return true;
            }
            var curr = head;
            while(curr.Next != null) {
                if (curr.Next.Pair.Key.Equals(k))
	            {
                    curr.Next = curr.Next.Next;
                    return true;
	            }
                curr = curr.Next;
            }

            return false;
        }

        public IEnumerator<KeyValuePair<T, U>> GetEnumerator()
        {
            var x = head;
            while (x != null)
            {
                yield return x.Pair;
                x = x.Next;
            }
        }

        public bool Set(T key, U value)
        {
            var x = head;
            while (x != null)
            {
                if (x.Pair.Key.Equals(key))
                {
                    var old = x.Pair.Key;
                    x.Pair = new KeyValuePair<T, U>(old, value);
                    return true;
                }
            }
            return false;
        }
    }
    [Serializable]
    public class Link<T, U>
    {
        public Link(T key, U value)
        {
            Pair = new KeyValuePair<T, U>(key, value);
        }
        public Link<T, U> Next;
        public KeyValuePair<T, U> Pair;
    }
}


text:
var chalk = require('chalk')
var browserSync = require('browser-sync')
var modRewrite = require('connect-modrewrite')

module.exports = function(options) {

	let loginDomain = options.loginDomain

	//Allow any SSL certificate
	process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"

	if (!loginDomain) {
		loginDomain = 'https://login.mediafly.com'
	}

	browserSync.create().init({
		https: true,
		port: 8188,
		ui: false,
		open: false,
		server: {
			baseDir: '.',
			middleware: [
				modRewrite([
					`^/(.*)$ ${loginDomain}/$1 [P]`
				])
			]
		}
	}, function(err) {

		if (err) {
			console.log(chalk.red('WARNING: Unable to start the login proxy server on port 8188.'))
		}
	})
}


text:
<?php declare(strict_types = 1);
/**
 * @author hollodotme
 */

namespace hollodotme\StateMachineGenerator\Generator;

use hollodotme\StateMachineGenerator\Generator\Contants\Config;
use hollodotme\StateMachineGenerator\Generator\Contants\Template;
use hollodotme\StateMachineGenerator\Generator\Types\OutputFile;
use hollodotme\StateMachineGenerator\Generator\Types\TemplateFile;

/**
 * Class MainClassGenerator
 * @package hollodotme\StateMachineGenerator\Generator
 */
final class MainClassGenerator extends AbstractGenerator
{
	public function generate() : OutputFile
	{
		$spec = $this->getSpecification();

		$operationsContent                = '';
		$queriesContent                   = '';
		$authorsContent                   = join( ', ', $spec->getAuthors() );
		$mainClassConfig                  = $spec->getConfiguration( Config::MAIN_CLASS );
		$stateInterfaceConfig             = $spec->getConfiguration( Config::STATE_INTERFACE );
		$abstractStateClassConfig         = $spec->getConfiguration( Config::ABSTRACT_STATE_CLASS );
		$illegalTransitionExceptionConfig = $spec->getConfiguration( Config::ILLEGAL_TRANSITION_EXCEPTION );

		$outputDir      = $spec->getOutputSetting( 'mainClass' )->getDir();
		$outputFilePath = sprintf( '%s/%s.php', $outputDir, $mainClassConfig->getClassName() );

		$operationTemplate = file_get_contents( (new TemplateFile( Template::MAIN_CLASS_OPERATION ))->toString() );

		foreach ( $spec->getOperations() as $operation )
		{
			$operationsContent .= str_replace(
				[
					'___ILLEGAL_TRANSITION_EXCEPTION___',
					'___METHOD___',
				],
				[
					$illegalTransitionExceptionConfig->getClassName(),
					$operation->getName(),
				],
				$operationTemplate . "\n"
			);
		}

		$queryTemplate   = file_get_contents( (new TemplateFile( Template::MAIN_CLASS_QUERY ))->toString() );
		$useStateClasses = [];

		foreach ( $spec->getStates() as $state )
		{
			$useStateClasses[] = sprintf( 'use %s\\%s;', $abstractStateClassConfig->getNamespace(), $state->getName() );

			$queriesContent .= str_replace(
				[
					'___QUERY___',
					'___STATE___',
				],
				[
					$state->getQuery(),
					$state->getName(),
				],
				$queryTemplate . "\n"
			);
		}

		$content = str_replace(
			[
				'___AUTHORS___',
				'___NAMESPACE___',
				'___CLASS_NAME___',
				'___STATE_INTERFACE___',
				'___USE_STATE_INTERFACE___',
				'___USE_STATE_CLASSES___',
				'___USE_ILLEGAL_TRANSITION_EXCEPTION___',
				'___OPERATIONS___',
				'___QUERIES___',
			],
			[
				$authorsContent,
				$mainClassConfig->getNamespace(),
				$mainClassConfig->getClassName(),
				$stateInterfaceConfig->getClassName(),
				$stateInterfaceConfig->getFullQualifiedClassName(),
				join( "\n", $useStateClasses ),
				$illegalTransitionExceptionConfig->getFullQualifiedClassName(),
				rtrim( $operationsContent, "\n" ),
				rtrim( $queriesContent, "\n" ),
			],
			file_get_contents( (new TemplateFile( Template::MAIN_CLASS ))->toString() )
		);

		return new OutputFile( $outputFilePath, $content );
	}
}


text:
from django.conf.urls import *
from django.conf import settings
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.views.generic import TemplateView

from django.contrib import admin

admin.autodiscover()

urlpatterns = patterns('',

	#Admin
	url(r'^admin42/', include(admin.site.urls)),

	#Static
	url(r'^about/$', TemplateView.as_view(template_name="static/about.html")),
	url(r'^terms/$', TemplateView.as_view(template_name="static/terms.html")),
	url(r'^privacy/$', TemplateView.as_view(template_name="static/privacy.html")),
	url(r'^faq/$', TemplateView.as_view(template_name="static/faq.html")),
	url(r'^guidelines/$', TemplateView.as_view(template_name="static/guidelines.html")),

	#Profile
	url(r'user/', include('gamernews.apps.profile.urls', namespace="Profile",)),
	url(r'^', include('gamernews.apps.threadedcomments.urls')),
	url(r'^comments/', include('gamernews.vendor.django_comments.urls')),
	url(r'^', include('gamernews.apps.core.urls', namespace="Core",)),
	url(r'^', include('gamernews.apps.news.urls')),
)

if settings.DEBUG:
	#Static Media
	urlpatterns += patterns('',
	    url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {
	        'document_root': settings.STATIC_ROOT,
	    }),
	)


text: Rails.application.config.session_store :cookie_store, key: '_infrastructure_projects_session'


text:
package com.jobxhub.server.dto;

import com.google.common.base.Function;
import com.jobxhub.server.domain.LogBean;
import org.springframework.beans.BeanUtils;

import java.io.Serializable;
import java.util.Date;

/**
 * Created by ChenHui on 2016/3/31.
 */
public class Log implements Serializable {

    private Long logId;

    private Long agentId;

    private Long userId;

    private Integer type;

    private String receiver;

    private String message;

    private String result;

    private Date sendTime;

    private String agentName;

    private Boolean isread;

    public Log() {

    }

    public static Function<? super LogBean, ? extends Log> transfer = new Function<LogBean, Log>() {
        @Override
        public Log apply(LogBean input) {
            return new Log(input);
        }
    };

    public Log(LogBean logBean){
        BeanUtils.copyProperties(logBean,this);
    }

    public Long getLogId() {
        return logId;
    }

    public void setLogId(Long logId) {
        this.logId = logId;
    }

    public Long getAgentId() {
        return agentId;
    }

    public void setAgentId(Long agentId) {
        this.agentId = agentId;
    }

    public Long getUserId() {
        return userId;
    }

    public void setUserId(Long userId) {
        this.userId = userId;
    }

    public Integer getType() {
        return type;
    }

    public void setType(Integer type) {
        this.type = type;
    }

    public String getReceiver() {
        return receiver;
    }

    public void setReceiver(String receiver) {
        this.receiver = receiver;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getResult() {
        return result;
    }

    public void setResult(String result) {
        this.result = result;
    }

    public Date getSendTime() {
        return sendTime;
    }

    public void setSendTime(Date sendTime) {
        this.sendTime = sendTime;
    }

    public String getAgentName() {
        return agentName;
    }

    public void setAgentName(String agentName) {
        this.agentName = agentName;
    }

    public Boolean getIsread() {
        return isread;
    }

    public void setIsread(Boolean isread) {
        this.isread = isread;
    }
}


text:
<?php

namespace Helmich\MongoMock\Tests;

use Helmich\MongoMock\TypeMapper;
use MongoDB\Model\BSONArray;
use MongoDB\Model\BSONDocument;
use PHPUnit\Framework\TestCase;

class TypeMapperTest extends TestCase
{
    function testMapWithDefaultOptions()
    {
        $typeMapper = TypeMapper::createWithDefault();
        $mapped     = $typeMapper->map(new BSONDocument(['foo' => 'bar', 'list' => [1, 2, 3]]));

        $this->assertInstanceOf(BSONDocument::class, $mapped);
        $this->assertArrayHasKey('foo', $mapped);
        $this->assertSame('bar', $mapped['foo']);
        $this->assertInstanceOf(BSONArray::class, $mapped['list']);
        $this->assertCount(3, $mapped['list']);
    }

    function testMapWithDocumentAndArraysAsArrayOption()
    {
        $typeMapper = TypeMapper::createWithDefault(['document' => 'array', 'array' => 'array']);
        $mapped     = $typeMapper->map(new BSONDocument(['foo' => 'bar', 'list' => [1, 2, 3]]));

        $this->assertArrayHasKey('foo', $mapped);
        $this->assertSame('bar', $mapped['foo']);

        // workaround for missing assertIsArray() in phpunit6 and deprecated assertInternalType in phpunit8
        $this->assertTrue(is_array($mapped['list']));
        $this->assertCount(3, $mapped['list']);
    }

    function testMapWithDocumentAsCustomTypeOption()
    {
        $typeMapper = TypeMapper::createWithDefault(['document' => BSONArray::class]);
        $mapped     = $typeMapper->map(new BSONDocument(['foo' => 'bar', 'list' => [1, 2, 3]]));

        $this->assertInstanceOf(BSONArray::class, $mapped);
        $this->assertArrayHasKey('foo', $mapped);
        $this->assertSame('bar', $mapped['foo']);
        $this->assertInstanceOf(BSONArray::class, $mapped['list']);
        $this->assertCount(3, $mapped['list']);
    }

    function testMapWithSubObjectAsArray()
    {
        $typeMapper = TypeMapper::createWithDefault();
        $mapped     = $typeMapper->map(new BSONDocument(['foo' => ['bar' => 1, 'baz' => 2]]));

        $this->assertInstanceOf(BSONDocument::class, $mapped);
        $this->assertArrayHasKey('foo', $mapped);
        $this->assertInstanceOf(BSONDocument::class, $mapped['foo']);
        $this->assertSame(1, $mapped['foo']['bar']);
        $this->assertSame(2, $mapped['foo']['baz']);
    }

}


text:
Firstly, I come up with the idea that using a stack to save the value of each character,
however, I face several problems:

1. if I ignore the charactor that is not alphanumric, the stack will totally different from
the original string.
2. the problem need to ignore the case of letter, which means we need to do double operation
for charactor in string and in stack.
3. we need O(n) space to store the characters.

Then, I found there is an much easier way to solve that:
just using two pointers, one for the start of the string and one for the end of the string.
we just need to compare the character pointed by the two pointer.
But we still face two problem:

1. how to judge whether a character is alphanumric or not.
2. how to change cases in c++.

Then I found two functions: `isalnum()` and `tolower()`, the isalnum is in `ctype.h`, which function
is to judge whether the input is the alphanumric. The other is to change the cases.


text:
// Copyright 2011-2016 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.security.zynamics.binnavi.debug.connection.packets.replies;

/**
 * Reply type that is dispatched whenever BinNavi could not authenticate the connected debug client.
 */
public final class AuthenticationFailedReply extends DebuggerReply {
  /**
   * Creates a new debugger closed unexpectedly reply.
   */
  public AuthenticationFailedReply() {
    super(0, 0);
  }
}


text:
// Copyright 2016, EMC, Inc.
/* jshint node:true */

'use strict';

describe('Redfish TaskService', function () {
    var tv4;
    var validator;
    var redfish;
    var waterline;
    var Promise;
    var Constants;
    var view;
    var fs;
    var graph;
    var Errors;

    // Skip reading the entry from Mongo and return the entry directly
    function redirectGet(entry) {
        return fs.readFileAsync(__dirname + '/../../../../data/views/redfish-1.0/' + entry, 'utf-8')
            .then(function(contents) {
                return { contents: contents };
            });
    }

    helper.httpServerBefore();

    before(function () {
        Constants = helper.injector.get('Constants');
        view = helper.injector.get('Views');
        validator = helper.injector.get('Http.Api.Services.Schema');
        redfish = helper.injector.get('Http.Api.Services.Redfish');
        waterline = helper.injector.get('Services.Waterline');

        Promise = helper.injector.get('Promise');
        Errors = helper.injector.get('Errors');

        var nodeFs = helper.injector.get('fs');
        fs = Promise.promisifyAll(nodeFs);
        tv4 = require('tv4');
        graph = {
            id: '566afe8a7e7b8f3751b951a5',
            instanceId: '566afe8a7e7b8f3751b951a5',
            _status: Constants.Task.States.Pending,
            createdAt: '2016-01-21T17:51:23.395Z',
            updatedAt: '2016-01-21T17:52:23.395Z',
            name: 'isc-dhcp leases poller',
            node: 'abcdefg'
        };
    });

    beforeEach('set up mocks', function () {
        this.sandbox.spy(tv4, "validate");
        this.sandbox.stub(view, "get", redirectGet);
        this.sandbox.spy(validator, 'validate');
        this.sandbox.spy(redfish, 'render');
        this.sandbox.stub(waterline.graphobjects);
        this.sandbox.stub(waterline.nodes);
    });

    helper.httpServerAfter();

    it('should return a valid task service root', function () {
        waterline.graphobjects.find.resolves([graph]);
        waterline.nodes.findByIdentifier.resolves({ id: 'abcdefg'});

        return helper.request().get('/redfish/v1/TaskService')
            .expect('Content-Type', /^application\/json/)
            .expect(200)
            .expect(function() {
                expect(tv4.validate.called).to.be.true;
                expect(validator.validate.called).to.be.true;
                expect(redfish.render.called).to.be.true;
            });
    });

    it('should return a valid task collection', function () {
        waterline.graphobjects.find.resolves([graph]);
        return helper.request().get('/redfish/v1/TaskService/Tasks')
            .expect('Content-Type', /^application\/json/)
            .expect(200)
            .expect(function() {
                expect(tv4.validate.called).to.be.true;
                expect(validator.validate.called).to.be.true;
                expect(redfish.render.called).to.be.true;
            });
    });

    it('should return a valid task from a collection', function () {
        waterline.graphobjects.find.resolves([graph]);
        return helper.request().get('/redfish/v1/TaskService/Tasks/' + graph.id)
            .expect('Content-Type', /^application\/json/)
            .expect(200)
            .expect(function() {
                expect(tv4.validate.called).to.be.true;
                expect(validator.validate.called).to.be.true;
                expect(redfish.render.called).to.be.true;
            });
    });

    it('should 404 an invalid task', function () {
        waterline.graphobjects.find.resolves([graph]);
        return helper.request().get('/redfish/v1/TaskService/Tasks/' + graph.id + 'invalid')
            .expect(404);
    });

    it('should return a valid task from a system', function () {
        waterline.graphobjects.find.resolves([graph]);
        waterline.nodes.needByIdentifier.resolves();
        return helper.request().get('/redfish/v1/TaskService/Oem/Tasks/' + graph.node)
            .expect('Content-Type', /^application\/json/)
            .expect(200)
            .expect(function() {
                expect(tv4.validate.called).to.be.true;
                expect(validator.validate.called).to.be.true;
                expect(redfish.render.called).to.be.true;
            });
    });

    it('should 404 an invalid system', function () {
        waterline.graphobjects.find.resolves([graph]);
        waterline.nodes.needByIdentifier.rejects(new Errors.NotFoundError());
        return helper.request().get('/redfish/v1/TaskService/Oem/Tasks/' + graph.node + 'invalid')
            .expect(404);
    });
});


text:
---
uid: SolidEdgeAssembly.Occurrence.IsFastenerSystemItem
summary:
remarks:
---


text:
form.oktavia_form {
    position: relative;
    display: block;
    width: 240px;
    height: 25px;
}

input.oktavia_search {
    -webkit-appearance: searchfield;
    -webkit-user-select: text;
    cursor: auto;
    background-color: white;
    color: black;
    line-height: normal;
    display: inline-block;
    padding: 1px;
    text-align: start;
    margin: 2px 0px 2px 0px;
    padding: 1px;
}

div.oktavia_searchresult_box {
    display: none;
    position: absolute;
    width: 500px;
    padding: 10px;
    right: 10px;
    background-color: #ffffff;
    -moz-border-radius: 8px;
    border-radius: 8px;
    -moz-box-shadow: 3px 3px 5px 5px #b5b2b2;
    box-shadow: 3px 3px 5px 5px #b5b2b2;
    opacity: 0.95;
    z-index: 100000;
}

div.oktavia_close_search_box {
    position: absolute;
    top: 10px;
    right: 10px;
    width: 20px;
    height: 20px;
    text-align: center;
    vertical-align: middle;
    color: #666;
}

div.oktavia_close_search_box:hover {
    background-color: #d1e8ff;
    border: 1px solid gray;
}

div.oktavia_close_search_box:active {
    background-color: #b4c8db;
    border: 1px solid gray;
}

div.oktavia_searchresult_summary {
    color: #444;
}

div.oktavia_searchresult .entry {
    margin: 10px 10px 10px 10px;
    color: black;
}

div.oktavia_searchresult .entry .title {
    font-size: normal;
}

div.oktavia_searchresult .entry .title a:link {
    color: #0000EE;
    text-decoration: underline;
}

div.oktavia_searchresult .entry .title a:visited {
    color: #551A8B;
    text-decoration: underline;
}

div.oktavia_searchresult .entry .title a:hover {
}

div.oktavia_searchresult .entry .title a:active {
    color: #FF0000;
    text-decoration: underline;
}

div.oktavia_searchresult .entry .url {
    font-size: 14px!important;
    color: #093;
    font-style: normal;
    font-family: arial,sans-serif;
}

div.oktavia_searchresult .entry .resultcontent {
    font-size: small;
    font-family: arial,sans-serif;
    color: #222;
}

div.oktavia_searchresult .entry .resultcontent .hit {
    font-weight: bolder;
    text-decoration: underline;
}

div.oktavia_searchresult .proposal {
    margin: 10px 10px 10px 10px;
    color: #222;
    font-size: small;
    font-family: arial,sans-serif;
}

div.oktavia_searchresult .proposal .option {
    background-color: #e8f4ff;
    border-bottom: 1px solid blue;
}

div.oktavia_searchresult .proposal .option:hover {
    background-color: #d1e8ff;
}

div.oktavia_searchresult .proposal .option:active {
    background-color: #b4c8db;
}

div.oktavia_searchresult_nav span.leader {
    color: #228;
}

div.oktavia_searchresult_nav span.page {
    background-color: #ffffff;
    border: 1px solid #888888;
    padding: 5px;
    margin: 5px;
    color: #222;
}

div.oktavia_searchresult_nav span.page:hover {
    background-color: #d1e8ff;
    border: 1px solid #7d98ff;
}

div.oktavia_searchresult_nav span.page:active {
    background-color: #b4c8db;
    border: 1px solid #6c83db;
}

div.oktavia_searchresult_nav span.selected {
    background-color: #b4c8db;
    border: 1px solid #6c83db;
}

div.oktavia_searchresult_nav span.selected:hover {
    background-color: #b4c8db;
    border: 1px solid #6c83db;
}

div.oktavia_searchresult_nav span.selected:active {
    background-color: #b4c8db;
    border: 1px solid #6c83db;
}

div.oktavia_searchresult_box span.pr {
    position: absolute;
    right: 10px;
    bottom: 10px;
    color: #555;
}

.highlighted {
    background-color: #fbe54e;
}


text:
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""

import os.path
import posixpath
from urllib.parse import urlparse

import pathvalidate
import typepy

from ._constant import Default
from .error import InvalidFilePathError

try:
    import simplejson as json
except ImportError:
    import json  # type: ignore # noqa

def get_file_encoding(file_path, encoding):
    from mbstrdecoder import detect_file_encoding

    if encoding:
        return encoding

    encoding = detect_file_encoding(file_path)
    if not encoding:
        return Default.ENCODING

    return encoding

def get_extension(file_path):
    if typepy.is_null_string(file_path):
        raise InvalidFilePathError("file path is empty")

    return os.path.splitext(file_path)[1].lstrip(".")

def make_temp_file_path_from_url(temp_dir_path, url):
    try:
        url_path = urlparse(url).path
    except AttributeError:
        raise InvalidFilePathError("url must be a string")

    if typepy.is_null_string(url_path):
        raise InvalidFilePathError(f"invalid URL path: {url_path}")

    temp_name = os.path.basename(url_path.rstrip("/"))
    if typepy.is_null_string(temp_name):
        temp_name = pathvalidate.replace_symbol(temp_name, replacement_text="_")

    if typepy.is_null_string(temp_name):
        raise InvalidFilePathError(f"invalid URL: {url}")

    try:
        return posixpath.join(temp_dir_path, temp_name)
    except (TypeError, AttributeError):
        raise InvalidFilePathError("temp_dir_path must be a string")


text:
const fsPromise = require('../util/fs-promise');
module.exports = function addPolicy(iam, policyName, roleName, fileName) {
	'use strict';
	return fsPromise.readFileAsync(fileName, 'utf8')
		.then(policyContents => iam.putRolePolicy({
			RoleName: roleName,
			PolicyName: policyName,
			PolicyDocument: policyContents
		}).promise());
};


text:
import {Component} from '@angular/core';
import {RouteSegment} from '@angular/router';

@Component({
  selector: 'demo-about-user',
  template: `

About User

  `,
  directives: []
})

export class AboutUserComponent {
  constructor(private segment: RouteSegment) {
    console.log('about user init');
    console.log(segment.parameters, segment, segment.getParam('id'));
  }
}


text:
//
//  RMErrorCodeDefinition.h
//  RideMarketplace
//
//  Created by Johan Ride on 8/24/15.
//  Copyright (c) 2015 Ride. All rights reserved.
//

@import Foundation;
#import "RMErrorCodeBoundary.h"
#import "RMErrorDescription.h"

/**
 Describes how the app sees error code for a Domain.
 */
@interface RMErrorCodeDefinition : NSObject

/**
 Initializes the Error Code definition with a boundary, friendly message and transient indicator
 @param boundary Boundary to Match the error code
 @param friendlyMessage (optional) a text message to show in UI when error is matched
 @param transient indicates whether the error is transient or not
 */
- (instancetype)initWithBoundary:(id<RMErrorCodeBoundary>)boundary
                 friendlyMessage:(NSString *)friendlyMessage transient:(BOOL)transient NS_DESIGNATED_INITIALIZER;

/**
 Initializes the Error Code definition with boundary and attributes dictionary(RMErrors.plist)
 @param boundary Boundary to Match the error code
 @param attributes NSDictionary with attributes (See RMErrors.plist)
 */
- (instancetype)initWithBoundary:(id<RMErrorCodeBoundary>)boundary andAttributes:(NSDictionary *)attributes;

/**
 Boundary of this error code.
 See RMErrorCodeRangeBoundary.
 */
@property (nonatomic, readonly) id<RMErrorCodeBoundary> boundary;

/**
 User-Friendly message associated with the matched code boundary.
 */
@property (nonatomic, readonly) NSString *friendlyMessage;

/**
 Indicates whether the matched error code is transient. Transient errors should be retried with our without user intervention after a certain amount of time.
 */
@property (nonatomic, readonly) BOOL transient;

/**
 Indicates whether it can describe the error or not
 */
- (BOOL)canDescribe:(NSInteger)code;

/**
 Describes the given error code with a default message
 @param code error code to describe
 @param defaultMessage default known message for the error code
 */
- (RMErrorDescription *)describe:(NSInteger)code withDefaultMessage:(NSString *)defaultMessage;

@end