Example #1
0
Obj_ptr quoteMakeList(const ParseTree_ptr & tree)
{
	Obj_ptr obj;

	if (tree==nullptr)
	{
		obj = Obj_ptr( new PairObj(nullptr, nullptr) );
		return descend(obj);
	}

	std::string token = tree->getToken();

	if (token==".")
	{
		if (tree->getBrother() == nullptr || tree->getBrother()->getBrother() != nullptr)
			throw syntaxError("illegal use: \'.\'");
		return Quote(tree->getBrother());
	}
	else
	{
		Obj_ptr o1( Quote(tree) );
		obj = Obj_ptr( new PairObj(o1, quoteMakeList(tree->getBrother())) );
	}
	return descend(obj);
}
/*
=================
CG_CenterPrint_Delay_f
=================
*/
void CG_CenterPrint_Delay_f()
{
    char cmd[ MAX_STRING_CHARS ];

    Com_sprintf( cmd, sizeof( cmd ), "delay %s lcp %s", Quote( CG_Argv( 1 ) ), Quote( CG_Argv( 2 ) ) );
    trap_SendConsoleCommand( cmd );
}
/*
=================
CG_CenterPrintTR_Delay_f
=================
*/
void CG_CenterPrintTR_Delay_f()
{
    char cmd[ MAX_STRING_CHARS ];

    Com_sprintf( cmd, sizeof( cmd ), "delay %s lcp %s", Quote( CG_Argv( 1 ) ), Quote( TranslateText_Internal( false, 2 ) ) );
    trap_SendConsoleCommand( cmd );
}
Example #4
0
CPLString swq_expr_node::QuoteIfNecessary( const CPLString &osExpr,
                                           char chQuote )

{
    if( osExpr[0] == '_' )
        return Quote(osExpr, chQuote);
    if( osExpr == "*" )
        return osExpr;

    for( int i = 0; i < static_cast<int>(osExpr.size()); i++ )
    {
        char ch = osExpr[i];
        if( (!(isalnum(static_cast<int>(ch)) || ch == '_')) || ch == '.' )
        {
            return Quote(osExpr, chQuote);
        }
    }

    if( swq_is_reserved_keyword(osExpr) )
    {
        return Quote(osExpr, chQuote);
    }

    return osExpr;
}
Example #5
0
/*
=================================================================================

target_print

=================================================================================
*/
void target_print_act( gentity_t *self, gentity_t *other, gentity_t *activator )
{
	if ( self->spawnflags & 4 )
	{
		if ( activator && activator->client )
		{
			trap_SendServerCommand( activator - g_entities, va( "cp %s", Quote( self->message ) ) );
		}

		return;
	}

	if ( self->spawnflags & 3 )
	{
		if ( self->spawnflags & 1 )
		{
			G_TeamCommand( TEAM_HUMANS, va( "cp %s", Quote( self->message ) ) );
		}

		if ( self->spawnflags & 2 )
		{
			G_TeamCommand( TEAM_ALIENS, va( "cp %s", Quote( self->message ) ) );
		}

		return;
	}

	trap_SendServerCommand( -1, va( "cp %s", Quote( self->message ) ) );
}
Example #6
0
int main()
{
	
	Basket car;
	car.add_items(Quote("0001", 25));
	car.add_items(Bulk_quote("0002", 12, 8, 0.3));
	car.add_items(Quote("0003", 19));
	car.add_items(Bulk_quote("0004", 32, 12, 0.5));
	auto total = car.total_receipt(std::cout);

	return 0;
}
Example #7
0
/**
 *  Given the original argv stuff, the length of our target executable, and the
 *  filepath, build a suitable command line for CreateProcess.
 */
STATIC LPTSTR BuildCmdLine(int argc, TCHAR* argv[], SIZE_T szExecutable, LPTSTR lpExecutable)
{
	int i = 1;
	LPTSTR lpCmdLine = NULL;
	SIZE_T szCmdLine = szExecutable;
	TCHAR** lpNewArgs = (TCHAR**)calloc(argc, sizeof(TCHAR*));
	assert(lpNewArgs != NULL);
	
	// Quote the executable path if need be.
	XINFO(_T("Building command line.."));
	if(HasSpace(lpExecutable, szExecutable)) {
		lpNewArgs[0] = Quote(lpExecutable, &szCmdLine, FALSE);
	} else {
		lpNewArgs[0] = DupArg(lpExecutable, &szCmdLine, FALSE);
	}
	
	// Iterate through all args, quoting as necessary.
	for(; i < argc; i++) {
		SIZE_T szArg = (SIZE_T)_tcslen((const TCHAR*)argv[i]);
		if(HasSpace(argv[i], szArg)) {
			lpNewArgs[i] = Quote(argv[i], &szArg, TRUE);
		} else {
			lpNewArgs[i] = DupArg(argv[i], &szArg, TRUE);
		}
		// +1 for space + len(arg)
		szCmdLine += szArg;
	}
	
	// Allocate our cmdline buffer and begin adding the various parts.
	lpCmdLine = (LPTSTR)calloc(szCmdLine + 1, sizeof(TCHAR));
	assert(lpCmdLine != NULL);
	_tcscpy(lpCmdLine, lpNewArgs[0]);
	XINFO(_T("  [0] => \"%s\""), lpNewArgs[0]);
	
	// Cleanup allocated arg.
	xfree(lpNewArgs[0]);
	lpNewArgs[0] = NULL;
	
	for(i = 1; i < argc; i++) {
		XINFO(_T("  [%d] => \"%s\""), i, argv[i]);
		_tcscat(lpCmdLine, lpNewArgs[i]);
		xfree(lpNewArgs[i]);
		lpNewArgs[i] = NULL;
	}
	
	XINFO(_T("Finished building.."));
	XINFO(_T("CmdLine: %s"), lpCmdLine);
	xfree(lpNewArgs);
	return lpCmdLine;
}
Example #8
0
 Popup & Popup::setHTML(C Wt::WString & content)
 {
   std::stringstream stream;
   stream << jsRef() << ".popup.setHTML(" << Quote(content) << ");";
   doDelayedJavaScript(stream.str());
   return *this;
 }
Example #9
0
static void Svcmd_TeamMessage_f( void )
{
	char   teamNum[ 2 ];
	team_t team;
	char   *arg;

	if ( trap_Argc() < 3 )
	{
		G_Printf( "usage: say_team <team> <message>\n" );
		return;
	}

	trap_Argv( 1, teamNum, sizeof( teamNum ) );
	team = G_TeamFromString( teamNum );

	if ( team == NUM_TEAMS )
	{
		G_Printf( "say_team: invalid team \"%s\"\n", teamNum );
		return;
	}

	arg = ConcatArgs( 2 );
	G_TeamCommand( team, va( "chat -1 %d %s", SAY_TEAM, Quote( arg ) ) );
	G_LogPrintf( "SayTeam: -1 \"console\": %s\n", arg );
}
Example #10
0
void DMPlace::toString(CString &str)
{
	CString tmp;
	tmp.Format(_T("<place id=\"%d\" color=\"#%02X%02X%02X\">\r\n<title>"), m_id, GetRValue(m_color), GetGValue(m_color), GetBValue(m_color)); str += tmp;
	Quote(m_title, str);
	str += _T("</title>\r\n<description>");		
	m_description.toString(str);
	str += _T("</description>\r\n</place>\r\n");
}  
Example #11
0
Obj_ptr Quote(const ParseTree_ptr &root)
{
	if (root == nullptr)
		return nullptr;
	std::string token = root->getToken();
	bool numberFlag = true, rationalFlag = false, realFlag = false, idenFlag = true;

	checkToken(token, numberFlag, rationalFlag, realFlag, idenFlag);

	if ( numberFlag==true )		// numerical constant
	{
		//----integer-----
		if (!rationalFlag && !realFlag)
			return Obj_ptr( new IntegerObj( bigInteger(token) ) );
		//----rational----
		else if (rationalFlag)
			return Obj_ptr( new RationalObj( bigRational(token) ) );
		//----real--------
		else
			return Obj_ptr( new RealObj( bigReal(token) ) );
	}
	else if (token[0]=='\"')	// string constant
		return Obj_ptr( new StringObj(token.substr(1, token.size()-2)) );
	else if (token[0]=='#')
	{
		// character constant
		if (token[1]=='\\')
		{
			if (token=="#\\newline")
				return Obj_ptr( new CharObj('\n') );
			else if (token=="#\\space")
				return Obj_ptr( new CharObj(' ') );
			else if (token=="#\\tab")
				return Obj_ptr( new CharObj('\t') );
			else
				return Obj_ptr( new CharObj(token[2]) );
		}
		// boolean constant
		else
		{
			if (token[1]=='t')
				return Obj_ptr( new BoolObj(true) );
			else
				return Obj_ptr( new BoolObj(false) );
		}
	}
	else if (token=="\'")
		return Quote(root->getSon());
	else if (token=="`")
		throw syntaxError("unexpected \'`\' here");	
	else if (token=="()")
		return quoteMakeList(root->getSon());
	else if (token[0]==',')
		throw syntaxError("unexpected comma here");	
	else
		return Obj_ptr( new SymbolObj( token ) );
}
Example #12
0
static void Svcmd_CenterPrint_f( void )
{
	if ( trap_Argc() < 2 )
	{
		G_Printf( "usage: cp <message>\n" );
		return;
	}

	trap_SendServerCommand( -1, va( "cp %s", Quote( ConcatArgs( 1 ) ) ) );
}
Example #13
0
    void ParseSemicolonDelimitedUriList ( const std::string& aSemicolonDelimitedUriList , std::vector< std::pair<std::string, std::string> >& aUriList )
    {
      try
      {
        grammars::SemicolonDelimitedUriListGrammar lGrammar;
        boost::spirit::qi::phrase_parse ( aSemicolonDelimitedUriList.begin() , aSemicolonDelimitedUriList.end() , lGrammar , boost::spirit::ascii::space , aUriList );
      }
      catch ( const std::exception& aExc )
      {
        exception::UriListParsingError lExc;
        log ( lExc , "Expression " , Quote ( aSemicolonDelimitedUriList ) , " must be a semicolon delimeted list and all files must be in the form " , Quote ( "protocol://address" ) );
        throw lExc;
      }

      log ( Debug() , "Parsed " , Quote ( aSemicolonDelimitedUriList ) , " to:" );

      for ( std::vector< std::pair<std::string, std::string> >::iterator lIt = aUriList.begin() ; lIt != aUriList.end() ; ++lIt )
      {
        log ( Debug() , "    > [" , lIt->first , "] " , Quote ( lIt->second ) );
      }
    }
Example #14
0
int main(int argc, char *argv[] ) {
    //std::cout << "Enter name of input file from yahoo.com: ";
    std::string strInputFile = "/home/shiva/Downloads/s1.csv";
    //std::cin >> strInputFile;
    Quotes quotes = ReadQuotes( strInputFile );
    //std::copy( quotes.rbegin(), quotes.rend(), std::ostream_iterator< Quote >( std::cout, "\n" ) );
    Quote minVal{ "Initial", std::numeric_limits< double >::max() }, maxVal{ "Initial", std::numeric_limits< double >::min() };
    BestPrice bestPrice = std::make_pair( maxVal, minVal );
    std::for_each( quotes.begin(), quotes.end(), [ &minVal, &maxVal, &bestPrice ] ( const Quote &q ) {
        if( q.dPrice < minVal.dPrice )
            minVal = Quote( q.strDate, q.dPrice );

        std::cout << "minValue " << minVal << std::endl;

        if( abs( bestPrice.first.dPrice ) - abs( bestPrice.second.dPrice ) < abs( maxVal.dPrice ) - abs( minVal.dPrice ) )
            bestPrice = std::make_pair( maxVal, minVal );

        std::cout << "bestPrice1 " << bestPrice.first << " => " << bestPrice.second << std::endl;

        if( q.dPrice > maxVal.dPrice ) {
            maxVal = Quote( q.strDate, q.dPrice );
            minVal = Quote( q.strDate, q.dPrice );
        }

        std::cout << "minValue " << minVal << std::endl;
        std::cout << "maxValue " << maxVal << std::endl;

        if( abs( bestPrice.first.dPrice ) - abs( bestPrice.second.dPrice ) < abs( maxVal.dPrice ) - abs( minVal.dPrice ) )
            bestPrice = std::make_pair( maxVal, minVal );

        std::cout << "bestPrice2 " << bestPrice.first << " => " << bestPrice.second << std::endl;
    } );

    std::cout << "Buy at " << bestPrice.second << std::endl;
    std::cout << "Sell at " << bestPrice.first << std::endl;
    return 0;
}
Example #15
0
Quotes ReadQuotes( const std::string strInputFile ) {
    std::ifstream finputFile{ strInputFile, std::ifstream::in };
    std::string strInputLine;
    Quotes quotes;
    while( std::getline( finputFile, strInputLine ) ) {
        // Date,Open,High,Low,Close,Volume,Adj Close
        // 2016-09-12,42.279999,43.650002,42.18,43.459999,10767000,43.459999
        std::string strDate;
        double      dClosePrice, dUnused;
        std::stringstream ss( strInputLine );
        ss >> strDate >> dClosePrice;
        quotes.push_back( Quote( strDate, dClosePrice ) );
    }
    return( quotes );
}
Example #16
0
int main()
{
    Basket basket;

    for (unsigned i = 0; i != 10; ++i)
        basket.add_item(Bulk_quote("Bible",20.6,20,0.3));

    for (unsigned i = 0; i != 10; ++i)
        basket.add_item(Bulk_quote("C++Primer",30.9,5,0.4));

    for (unsigned i = 0; i != 10; ++i)
        basket.add_item(Quote("CLRS",40.1));

    std::ofstream log("log.txt",std::ios_base::app|std::ios_base::out);

    basket.total_receipt(log);
    return 0;
}
Example #17
0
    void ShellExpandFilenameExpr ( const std::string& aFilenameExpr , const boost::filesystem::path& aParentPath , std::vector< boost::filesystem::path >& aFiles )
    {
      try
      {
        //	boost::lock_guard<boost::mutex> lLock ( gUtilityMutex );
        //struct which will store the shell expansions of the expression
        wordexp_t lShellExpansion;
        wordexp ( aFilenameExpr.c_str() , &lShellExpansion , 0 );

        for ( std::size_t i = 0 ; i != lShellExpansion.we_wordc ; i++ )
        {
          boost::filesystem::path lPath ( lShellExpansion.we_wordv[i] );
          log ( Debug() , "lPath was " , Quote ( lPath.c_str() ) );
          log ( Debug() , "aParentPath is " , Quote ( aParentPath.c_str() ) );
          lPath = boost::filesystem::absolute ( lPath , aParentPath );
          log ( Debug() , "lPath now " , Quote ( lPath.c_str() ) );

          if ( boost::filesystem::exists ( lPath ) )
          {
            if ( boost::filesystem::is_regular_file ( lPath ) )
            {
              aFiles.push_back ( lPath );
            }
          }
        }

        wordfree ( &lShellExpansion );
      }
      catch ( const std::exception& aExc )
      {
        uhal::exception::ExpandingShellExpressionFailed lExc;
        log ( lExc , "Caught exception: " , Quote ( aExc.what() ) );
        throw lExc;
      }

      if ( ! aFiles.size() )
      {
        uhal::exception::FileNotFound lExc;
        log ( lExc , "No matching files for expression " , Quote ( aFilenameExpr ) , " with parent path " , Quote ( aParentPath.c_str() ) );
        throw lExc;
      }
      else
      {
        log ( Debug() , "Shell expansion of " , Quote ( aFilenameExpr.c_str() ) , " returned:" );

        for ( std::vector< boost::filesystem::path >::iterator lIt = aFiles.begin() ; lIt !=  aFiles.end() ; ++lIt )
        {
          log ( Debug() , " > [file] " , lIt->c_str() );
        }
      }
    }
Example #18
0
std::string ExecuteProcess(const std::string& file, std::vector<std::string> args)
{
	std::string execError = "";

	// "The first argument, by convention, should point to
	// the filename associated with the file being executed."
	args.insert(args.begin(), Quote(file));

	char** processArgs = new char*[args.size() + 1];

	for (size_t a = 0; a < args.size(); ++a) {
		const std::string& arg = args.at(a);
		const size_t arg_size = arg.length() + 1;
		processArgs[a] = new char[arg_size];
		STRCPY_T(processArgs[a], arg_size, arg.c_str());
	}

	// "The array of pointers must be terminated by a NULL pointer."
	processArgs[args.size()] = NULL;

	{
		// Execute
#ifdef WIN32
	#define EXECVP _execvp
#else
	#define EXECVP execvp
#endif
		const int ret = EXECVP(file.c_str(), processArgs);

		if (ret == -1) {
			execError = strerror(errno);
		}
	}

	for (size_t a = 0; a < args.size(); ++a) {
		delete[] processArgs[a];
	}
	delete[] processArgs;

	return execError;
}
Example #19
0
static void Svcmd_Pr_f( void )
{
	char targ[ 4 ];
	int  cl;

	if ( trap_Argc() < 3 )
	{
		G_Printf( "usage: <clientnum|-1> <message>\n" );
		return;
	}

	trap_Argv( 1, targ, sizeof( targ ) );
	cl = atoi( targ );

	if ( cl >= MAX_CLIENTS || cl < -1 )
	{
		G_Printf( "invalid clientnum %d\n", cl );
		return;
	}

	trap_SendServerCommand( cl, va( "print %s\\\n", Quote( ConcatArgs( 2 ) ) ) );
}
Example #20
0
void G_BotDel( int clientNum )
{
	gentity_t *bot = &g_entities[clientNum];
	char userinfo[MAX_INFO_STRING];
	const char *autoname;

	if ( !( bot->r.svFlags & SVF_BOT ) || !bot->botMind )
	{
		Log::Warn( "'^7%s^7' is not a bot", bot->client->pers.netname );
		return;
	}

	trap_GetUserinfo( clientNum, userinfo, sizeof( userinfo ) );

	autoname = Info_ValueForKey( userinfo, "autoname" );
	if ( autoname && *autoname )
	{
		G_BotNameUsed( BotGetEntityTeam( bot ), autoname, false );
	}

	trap_SendServerCommand( -1, va( "print_tr %s %s", QQ( N_( "$1$^7 disconnected" ) ),
					Quote( bot->client->pers.netname ) ) );
	trap_DropClient( clientNum, "disconnected" );
}
Example #21
0
/*
==================
player_die
==================
*/
void player_die( gentity_t *self, gentity_t *inflictor, gentity_t *attacker, int meansOfDeath )
{
	gentity_t *ent;
	int       anim;
	int       killer;
	int       i;
	const char *killerName, *obit;

	if ( self->client->ps.pm_type == PM_DEAD )
	{
		return;
	}

	if ( level.intermissiontime )
	{
		return;
	}

	self->client->ps.pm_type = PM_DEAD;
	self->suicideTime = 0;

	if ( attacker )
	{
		killer = attacker->s.number;

		if ( attacker->client )
		{
			killerName = attacker->client->pers.netname;
		}
		else
		{
			killerName = "<world>";
		}
	}
	else
	{
		killer = ENTITYNUM_WORLD;
		killerName = "<world>";
	}

	if ( meansOfDeath < 0 || meansOfDeath >= ARRAY_LEN( modNames ) )
	{
		// fall back on the number
		obit = va( "%d", meansOfDeath );
	}
	else
	{
		obit = modNames[ meansOfDeath ];
	}

	G_LogPrintf( "Die: %d %d %s: %s" S_COLOR_WHITE " killed %s\n",
	             killer,
	             ( int )( self - g_entities ),
	             obit,
	             killerName,
	             self->client->pers.netname );

	// deactivate all upgrades
	for ( i = UP_NONE + 1; i < UP_NUM_UPGRADES; i++ )
	{
		BG_DeactivateUpgrade( i, self->client->ps.stats );
	}

	// broadcast the death event to everyone
	ent = G_NewTempEntity( self->r.currentOrigin, EV_OBITUARY );
	ent->s.eventParm = meansOfDeath;
	ent->s.otherEntityNum = self->s.number;
	ent->s.otherEntityNum2 = killer;
	ent->r.svFlags = SVF_BROADCAST; // send to everyone

	if ( attacker && attacker->client )
	{
		if ( ( attacker == self || OnSameTeam( self, attacker ) ) )
		{
			//punish team kills and suicides
			if ( attacker->client->ps.stats[ STAT_TEAM ] == TEAM_ALIENS )
			{
				G_AddCreditToClient( attacker->client, -ALIEN_TK_SUICIDE_PENALTY, qtrue );
				G_AddCreditsToScore( attacker, -ALIEN_TK_SUICIDE_PENALTY );
			}
			else if ( attacker->client->ps.stats[ STAT_TEAM ] == TEAM_HUMANS )
			{
				G_AddCreditToClient( attacker->client, -HUMAN_TK_SUICIDE_PENALTY, qtrue );
				G_AddCreditsToScore( attacker, -HUMAN_TK_SUICIDE_PENALTY );
			}
		}
		else if ( g_showKillerHP.integer )
		{
			trap_SendServerCommand( self - g_entities, va( "print_tr %s %s %3i", QQ( N_("Your killer, $1$^7, had $2$ HP.\n") ),
			                        Quote( killerName ),
			                        attacker->health ) );
		}
	}
	else if ( attacker->s.eType != ET_BUILDABLE )
	{
		if ( self->client->ps.stats[ STAT_TEAM ] == TEAM_ALIENS )
		{
			G_AddCreditsToScore( self, -ALIEN_TK_SUICIDE_PENALTY );
		}
		else if ( self->client->ps.stats[ STAT_TEAM ] == TEAM_HUMANS )
		{
			G_AddCreditsToScore( self, -HUMAN_TK_SUICIDE_PENALTY );
		}
	}

	// give credits for killing this player
	G_RewardAttackers( self );

	ScoreboardMessage( self );  // show scores

	// send updated scores to any clients that are following this one,
	// or they would get stale scoreboards
	for ( i = 0; i < level.maxclients; i++ )
	{
		gclient_t *client;

		client = &level.clients[ i ];

		if ( client->pers.connected != CON_CONNECTED )
		{
			continue;
		}

		if ( client->sess.spectatorState == SPECTATOR_NOT )
		{
			continue;
		}

		if ( client->sess.spectatorClient == self->s.number )
		{
			ScoreboardMessage( g_entities + i );
		}
	}

	VectorCopy( self->s.origin, self->client->pers.lastDeathLocation );

	self->takedamage = qfalse; // can still be gibbed

	self->s.weapon = WP_NONE;
	if ( self->client->noclip )
	{
		self->client->cliprcontents = CONTENTS_CORPSE;
	}
	else
	{
		self->r.contents = CONTENTS_CORPSE;
	}

	self->s.angles[ PITCH ] = 0;
	self->s.angles[ ROLL ] = 0;
	self->s.angles[ YAW ] = self->s.apos.trBase[ YAW ];
	LookAtKiller( self, inflictor, attacker );

	VectorCopy( self->s.angles, self->client->ps.viewangles );

	self->s.loopSound = 0;

	self->r.maxs[ 2 ] = -8;

	// don't allow respawn until the death anim is done
	// g_forcerespawn may force spawning at some later time
	self->client->respawnTime = level.time + 1700;

	// clear misc
	memset( self->client->ps.misc, 0, sizeof( self->client->ps.misc ) );

	{
		static int i;

		if ( !( self->client->ps.persistant[ PERS_STATE ] & PS_NONSEGMODEL ) )
		{
			switch ( i )
			{
				case 0:
					anim = BOTH_DEATH1;
					break;

				case 1:
					anim = BOTH_DEATH2;
					break;

				case 2:
				default:
					anim = BOTH_DEATH3;
					break;
			}
		}
		else
		{
			switch ( i )
			{
				case 0:
					anim = NSPA_DEATH1;
					break;

				case 1:
					anim = NSPA_DEATH2;
					break;

				case 2:
				default:
					anim = NSPA_DEATH3;
					break;
			}
		}

		self->client->ps.legsAnim =
		  ( ( self->client->ps.legsAnim & ANIM_TOGGLEBIT ) ^ ANIM_TOGGLEBIT ) | anim;

		if ( !( self->client->ps.persistant[ PERS_STATE ] & PS_NONSEGMODEL ) )
		{
			self->client->ps.torsoAnim =
			  ( ( self->client->ps.torsoAnim & ANIM_TOGGLEBIT ) ^ ANIM_TOGGLEBIT ) | anim;
		}

		// use own entityid if killed by non-client to prevent uint8_t overflow
		G_AddEvent( self, EV_DEATH1 + i,
		            ( killer < MAX_CLIENTS ) ? killer : self - g_entities );

		// globally cycle through the different death animations
		i = ( i + 1 ) % 3;
	}

	trap_LinkEntity( self );

	self->client->pers.infoChangeTime = level.time;
}
Example #22
0
static void CG_UIMenu_f( void )
{
	trap_SendConsoleCommand( va( "menu %s\n", Quote( CG_Argv( 1 ) ) ) );
}
Example #23
0
/**
 * @brief Log deconstruct/destroy events
 * @param self
 * @param actor
 * @param mod
 */
void G_LogDestruction( gentity_t *self, gentity_t *actor, int mod )
{
	buildFate_t fate;

	switch ( mod )
	{
		case MOD_DECONSTRUCT:
			fate = BF_DECONSTRUCT;
			break;

		case MOD_REPLACE:
			fate = BF_REPLACE;
			break;

		case MOD_NOCREEP:
			fate = ( actor->client ) ? BF_UNPOWER : BF_AUTO;
			break;

		default:
			if ( actor->client )
			{
				if ( actor->client->pers.team ==
				     BG_Buildable( self->s.modelindex )->team )
				{
					fate = BF_TEAMKILL;
				}
				else
				{
					fate = BF_DESTROY;
				}
			}
			else
			{
				fate = BF_AUTO;
			}

			break;
	}

	G_BuildLogAuto( actor, self, fate );

	// don't log when marked structures are removed
	if ( mod == MOD_REPLACE )
	{
		return;
	}

	G_LogPrintf( S_COLOR_YELLOW "Deconstruct: %d %d %s %s: %s %s by %s\n",
	             ( int )( actor - g_entities ),
	             ( int )( self - g_entities ),
	             BG_Buildable( self->s.modelindex )->name,
	             modNames[ mod ],
	             BG_Buildable( self->s.modelindex )->humanName,
	             mod == MOD_DECONSTRUCT ? "deconstructed" : "destroyed",
	             actor->client ? actor->client->pers.netname : "<world>" );

	// No-power deaths for humans come after some minutes and it's confusing
	//  when the messages appear attributed to the deconner. Just don't print them.
	if ( mod == MOD_NOCREEP && actor->client &&
	     actor->client->pers.team == TEAM_HUMANS )
	{
		return;
	}

	if ( actor->client && actor->client->pers.team ==
	     BG_Buildable( self->s.modelindex )->team )
	{
		G_TeamCommand( (team_t) actor->client->pers.team,
		               va( "print_tr %s %s %s", mod == MOD_DECONSTRUCT ? QQ( N_("$1$ ^3DECONSTRUCTED^7 by $2$\n") ) :
						   QQ( N_("$1$ ^3DESTROYED^7 by $2$\n") ),
		                   Quote( BG_Buildable( self->s.modelindex )->humanName ),
		                   Quote( actor->client->pers.netname ) ) );
	}
}
Example #24
0
Obj_ptr Quasiquote(const ParseTree_ptr &root, env_ptr & env)
{
	if (root == nullptr)
		return nullptr;
	std::string token = root->getToken();
	bool numberFlag = true, rationalFlag = false, realFlag = false, idenFlag = true;

	checkToken(token, numberFlag, rationalFlag, realFlag, idenFlag);

	if ( numberFlag==true )		// numerical constant
	{
		//----integer-----
		if (!rationalFlag && !realFlag)
			return Obj_ptr( new IntegerObj( bigInteger(token) ) );
		//----rational----
		else if (rationalFlag)
			return Obj_ptr( new RationalObj( bigRational(token) ) );
		//----real--------
		else
			return Obj_ptr( new RealObj( bigReal(token) ) );
	}
	else if (token[0]=='\"')	// string constant
		return Obj_ptr( new StringObj(token.substr(1, token.size()-2)) );
	else if (token[0]=='#')
	{
		// character constant
		if (token[1]=='\\')
		{
			if (token=="#\\newline")
				return Obj_ptr( new CharObj('\n') );
			else if (token=="#\\space")
				return Obj_ptr( new CharObj(' ') );
			else if (token=="#\\tab")
				return Obj_ptr( new CharObj('\t') );
			else
				return Obj_ptr( new CharObj(token[2]) );
		}
		// boolean constant
		else
		{
			if (token[1]=='t')
				return Obj_ptr( new BoolObj(true) );
			else
				return Obj_ptr( new BoolObj(false) );
		}
	}
	else if (token=="\'")
		return Quote(root->getSon());
	else if (token=="`")
		return Quasiquote(root->getSon(), env);
	else if (token=="()")
		return quasiquoteMakeList(root->getSon(), env);
	else if (token==",")
		return evaluate(root->getSon(), env);
	else if (token==",@")
	{
		Obj_ptr obj(evaluate(root->getSon(), env));
		if (!isList(obj))
			throw syntaxError("there must be a list after \',@\'");	//W.T.F.
		throw syntaxError("sorry for no support of \',@\' now");
	}
	else
		return Obj_ptr( new SymbolObj( token ) );
}
Example #25
0
Obj_ptr evaluate(const ParseTree_ptr &root, env_ptr & env)
{
	if (root == nullptr)
		return nullptr;

	std::string token = root->getToken();
	Obj_ptr obj;
	bool numberFlag = true, rationalFlag = false, realFlag = false, idenFlag = true;

	checkToken(token, numberFlag, rationalFlag, realFlag, idenFlag);

	//----number-----
	if (numberFlag)
	{
		//----integer-----
		if (!rationalFlag && !realFlag)
			obj = Obj_ptr( new IntegerObj( bigInteger(token) ) );
		//----rational----
		else if (rationalFlag)
			obj = Obj_ptr( new RationalObj( bigRational(token) ) );
		//----real--------
		else
			obj = Obj_ptr( new RealObj( bigReal(token) ) );
		return descend(obj);
	}

	//----comma--------
	else if (token[0]==',')
		throw syntaxError("unexpected comma here");

	//----identifier----
	else if (idenFlag)
	{
		obj = findIden(env, token);
		if (obj.get() == nullptr)
		{
			if (builtInProcedure.find(token) == builtInProcedure.end())
				throw syntaxError("Undefined identifier: " + token);
			Arg_ptr nullArg(nullptr);
			ParseTree_ptr nullTree(nullptr);
			env_ptr nullEnv(nullptr);
			obj = Obj_ptr(new ProcedureObj(nullArg, nullTree, nullEnv, true, token));
		}
		return descend(obj);
	}

	//----char&bool-----
	else if (token[0]=='#')
	{
		//----char-----
		if (token[1]=='\\')
		{
			if (token=="#\\newline")
				obj = Obj_ptr( new CharObj('\n') );
			else if (token=="#\\space")
				obj = Obj_ptr( new CharObj(' ') );
			else if (token=="#\\tab")
				obj = Obj_ptr( new CharObj('\t') );
			else
				obj = Obj_ptr( new CharObj(token[2]) );

			return descend(obj);
		}
		//----bool-----
		else
		{
			
			if (token[1]=='t')
				obj = Obj_ptr( new BoolObj(true) );
			else
				obj = Obj_ptr( new BoolObj(false) );

			return descend(obj);
		}
	}

	//----string-------
	else if (token[0]=='\"')
	{
		obj = Obj_ptr( new StringObj(token.substr(1, token.size()-2)) );
		return descend(obj);
	}

	//----quote-------
	else if (token=="\'")
	{
		obj = Quote(root);
		return descend(obj);
	}

	else if (token=="`")
	{
		obj = Quasiquote(root, env);
		return descend(obj);
	}

	//----syntax&procedure----
	else if (token=="()")
	{
		ParseTree_ptr name = root->getSon();

		if (name == nullptr)
			throw syntaxError("missing expression");

		std::string iden = name->getToken();

		//--------syntax------------
		if (builtInSyntax.find(iden) != builtInSyntax.end())
		{
			return descend(evaluateSyntax(iden, name->getBrother(), env));
		}
		
		//--------procedure---------

		Obj_ptr obj = findIden(env, iden);

			//--------procedure object----
			if (iden == "()")
			{
				obj = evaluate(name, env);
				if (obj->Type != Procedure)
					throw syntaxError("not a procedure");
			}


		if (obj==nullptr)
		{
			if (builtInProcedure.find(iden) == builtInProcedure.end())
				throw syntaxError("Undefined identifier: " + iden);
		}
		else if (obj->Type != Procedure)
			throw syntaxError("\'" + iden + "\' is not a procedure");

		ParseTree_ptr para = name->getBrother();
		Para_ptr head=nullptr, tail=nullptr;

		while (para!=nullptr)
		{
			if (head==nullptr)
			{
				head = Para_ptr( new Parameters(evaluate(para, env)) );
				tail = head;
			}
			else
			{
				tail->next = Para_ptr( new Parameters(evaluate(para, env)) );
				tail = tail->next;
			}

			para = para->getBrother();
		}

		if (obj)	//define by user
		{
			return descend(evaluateUserDefined(obj, head, env));
		}
		else		// built-in
		{
			return descend(evaluateBuiltInProcedure(iden, head, env));
		}

	}

	//----else----------
	else
	{
		throw syntaxError("Illegal expression or the function you use is not available now.");
	}

}
Example #26
0
// NULL for everyone
void QDECL PRINTF_LIKE(2) PrintMsg( gentity_t *ent, const char *fmt, ... )
{
	char    msg[ 1024 ];
	va_list argptr;
	char    *p;

	va_start( argptr, fmt );

	if ( Q_vsnprintf( msg, sizeof( msg ), fmt, argptr ) >= sizeof( msg ) )
	{
		G_Error( "PrintMsg overrun" );
	}

	va_end( argptr );

	// double quotes are bad
	while ( ( p = strchr( msg, '"' ) ) != NULL )
	{
		*p = '\'';
	}

	trap_SendServerCommand( ( ( ent == NULL ) ? -1 : ent - g_entities ), va( "print %s", Quote( msg ) ) );
}
Example #27
0
void Siteop(const std::string& admin, const std::string& format, const Args&... args)
{
  extern Logger siteop;
  siteop.PushEntry("admin", Quote('\''), admin, "message", util::Format()(format, args...));
}
Example #28
0
/*
===========
ClientUserInfoChanged

Called from ClientConnect when the player first connects and
directly by the server system when the player updates a userinfo variable.

The game can override any of the settings and call trap_SetUserinfo
if desired.
============
*/
const char *ClientUserinfoChanged( int clientNum, bool forceName )
{
	gentity_t *ent;
	const char      *s;
	char      model[ MAX_QPATH ];
	char      buffer[ MAX_QPATH ];
	char      oldname[ MAX_NAME_LENGTH ];
	char      newname[ MAX_NAME_LENGTH ];
	char      err[ MAX_STRING_CHARS ];
	bool  revertName = false;
	gclient_t *client;
	char      userinfo[ MAX_INFO_STRING ];

	ent = g_entities + clientNum;
	client = ent->client;

	trap_GetUserinfo( clientNum, userinfo, sizeof( userinfo ) );

	// check for malformed or illegal info strings
	if ( !Info_Validate( userinfo ) )
	{
		trap_SendServerCommand( ent - g_entities,
		                        "disconnect \"illegal or malformed userinfo\"" );
		trap_DropClient( ent - g_entities,
		                 "dropped: illegal or malformed userinfo" );
		return "Illegal or malformed userinfo";
	}
	// If their userinfo overflowed, tremded is in the process of disconnecting them.
	// If we send our own disconnect, it won't work, so just return to prevent crashes later
	//  in this function. This check must come after the Info_Validate call.
	else if ( !userinfo[ 0 ] )
	{
		return "Empty (overflowed) userinfo";
	}

	// stickyspec toggle
	s = Info_ValueForKey( userinfo, "cg_stickySpec" );
	client->pers.stickySpec = atoi( s ) != 0;

	// set name
	Q_strncpyz( oldname, client->pers.netname, sizeof( oldname ) );
	s = Info_ValueForKey( userinfo, "name" );
	G_ClientCleanName( s, newname, sizeof( newname ), client );

	if ( strcmp( oldname, newname ) )
	{
		if ( !forceName && client->pers.namelog->nameChangeTime &&
		     level.time - client->pers.namelog->nameChangeTime <=
		     g_minNameChangePeriod.value * 1000 )
		{
			trap_SendServerCommand( ent - g_entities, va(
			                          "print_tr %s %d", QQ( N_("Name change spam protection (g_minNameChangePeriod = $1$)") ),
			                          g_minNameChangePeriod.integer ) );
			revertName = true;
		}
		else if ( !forceName && g_maxNameChanges.integer > 0 &&
		          client->pers.namelog->nameChanges >= g_maxNameChanges.integer )
		{
			trap_SendServerCommand( ent - g_entities, va(
			                          "print_tr %s %d", QQ( N_("Maximum name changes reached (g_maxNameChanges = $1$)") ),
			                          g_maxNameChanges.integer ) );
			revertName = true;
		}
		else if ( !forceName && client->pers.namelog->muted )
		{
			trap_SendServerCommand( ent - g_entities,
			                        va( "print_tr %s", QQ( N_("You cannot change your name while you are muted") ) ) );
			revertName = true;
		}
		else if ( !G_admin_name_check( ent, newname, err, sizeof( err ) ) )
		{
			trap_SendServerCommand( ent - g_entities, va( "print_tr %s %s %s", QQ( "$1t$ $2$" ), Quote( err ), Quote( newname ) ) );
			revertName = true;
		}
		else if ( Q_UTF8_Strlen( newname ) > MAX_NAME_CHARACTERS )
		{
			trap_SendServerCommand( ent - g_entities,
			                        va( "print_tr %s %d", QQ( N_("Name is too long! Must be less than $1$ characters.") ), MAX_NAME_CHARACTERS ) );
			revertName = true;

		}

		if ( revertName )
		{
			Q_strncpyz( client->pers.netname, *oldname ? oldname : G_UnnamedClientName( client ),
			            sizeof( client->pers.netname ) );
		}
		else
		{
			if( G_IsUnnamed( newname ) )
			{
				Q_strncpyz( client->pers.netname, G_UnnamedClientName( client ), sizeof( client->pers.netname ) );
			}
			else
			{
				Q_strncpyz( client->pers.netname, newname, sizeof( client->pers.netname ) );
			}

			if ( !forceName && client->pers.connected == CON_CONNECTED )
			{
				client->pers.namelog->nameChangeTime = level.time;
				client->pers.namelog->nameChanges++;
			}

			if ( *oldname )
			{
				G_LogPrintf( "ClientRename: %i [%s] (%s) \"%s^7\" -> \"%s^7\" \"%s^7\"",
				             clientNum, client->pers.ip.str, client->pers.guid,
				             oldname, client->pers.netname,
				             client->pers.netname );
			}
		}

		G_namelog_update_name( client );

		Info_SetValueForKey(userinfo, "name", client->pers.netname, false);
		trap_SetUserinfo(clientNum, userinfo);
	}

	if ( client->pers.classSelection == PCL_NONE )
	{
		//This looks hacky and frankly it is. The clientInfo string needs to hold different
		//model details to that of the spawning class or the info change will not be
		//registered and an axis appears instead of the player model. There is zero chance
		//the player can spawn with the battlesuit, hence this choice.
		Com_sprintf( buffer, MAX_QPATH, "%s/%s",  BG_ClassModelConfig( PCL_HUMAN_BSUIT )->modelName,
		             BG_ClassModelConfig( PCL_HUMAN_BSUIT )->skinName );
	}
	else
	{
		Com_sprintf( buffer, MAX_QPATH, "%s/%s",  BG_ClassModelConfig( client->pers.classSelection )->modelName,
		             BG_ClassModelConfig( client->pers.classSelection )->skinName );

		if ( BG_ClassModelConfig( client->pers.classSelection )->segmented )
		{
			client->ps.persistant[ PERS_STATE ] |= PS_NONSEGMODEL;
		}
		else
		{
			client->ps.persistant[ PERS_STATE ] &= ~PS_NONSEGMODEL;
		}
	}

	Q_strncpyz( model, buffer, sizeof( model ) );

	// wallwalk follow
	s = Info_ValueForKey( userinfo, "cg_wwFollow" );

	if ( atoi( s ) )
	{
		client->ps.persistant[ PERS_STATE ] |= PS_WALLCLIMBINGFOLLOW;
	}
	else
	{
		client->ps.persistant[ PERS_STATE ] &= ~PS_WALLCLIMBINGFOLLOW;
	}

	// wallwalk toggle
	s = Info_ValueForKey( userinfo, "cg_wwToggle" );

	if ( atoi( s ) )
	{
		client->ps.persistant[ PERS_STATE ] |= PS_WALLCLIMBINGTOGGLE;
	}
	else
	{
		client->ps.persistant[ PERS_STATE ] &= ~PS_WALLCLIMBINGTOGGLE;
	}

	// always sprint
	s = Info_ValueForKey( userinfo, "cg_sprintToggle" );

	if ( atoi( s ) )
	{
		client->ps.persistant[ PERS_STATE ] |= PS_SPRINTTOGGLE;
	}
	else
	{
		client->ps.persistant[ PERS_STATE ] &= ~PS_SPRINTTOGGLE;
	}

	// fly speed
	s = Info_ValueForKey( userinfo, "cg_flySpeed" );

	if ( *s )
	{
		client->pers.flySpeed = atoi( s );
	}
	else
	{
		client->pers.flySpeed = BG_Class( PCL_NONE )->speed;
	}

	// disable blueprint errors
	s = Info_ValueForKey( userinfo, "cg_disableBlueprintErrors" );

	if ( atoi( s ) )
	{
		client->pers.disableBlueprintErrors = true;
	}
	else
	{
		client->pers.disableBlueprintErrors = false;
	}

	// teamInfo
	s = Info_ValueForKey( userinfo, "teamoverlay" );

	if ( atoi( s ) != 0 )
	{
		// teamoverlay was enabled so we need an update
		if ( client->pers.teamInfo == 0 )
		{
			client->pers.teamInfo = 1;
		}
	}
	else
	{
		client->pers.teamInfo = 0;
	}

	s = Info_ValueForKey( userinfo, "cg_unlagged" );

	if ( !s[ 0 ] || atoi( s ) != 0 )
	{
		client->pers.useUnlagged = true;
	}
	else
	{
		client->pers.useUnlagged = false;
	}

	Q_strncpyz( client->pers.voice, Info_ValueForKey( userinfo, "voice" ),
	            sizeof( client->pers.voice ) );

	// send over a subset of the userinfo keys so other clients can
	// print scoreboards, display models, and play custom sounds

	Com_sprintf( userinfo, sizeof( userinfo ),
	             "n\\%s\\t\\%i\\model\\%s\\ig\\%16s\\v\\%s",
	             client->pers.netname, client->pers.team, model,
	             Com_ClientListString( &client->sess.ignoreList ),
	             client->pers.voice );

	trap_SetConfigstring( CS_PLAYERS + clientNum, userinfo );

	/*G_LogPrintf( "ClientUserinfoChanged: %i %s\n", clientNum, userinfo );*/

	return nullptr;
}
Example #29
0
/*
===========
ClientBegin

Called when a client has finished connecting, and is ready
to be placed into the level. This will happen on every
level load and level restart, but doesn't happen on respawns.
============
*/
void ClientBegin( int clientNum )
{
	gentity_t       *ent;
	gclient_t       *client;
	int             flags;
	char            startMsg[ MAX_STRING_CHARS ];

	ent    = g_entities + clientNum;
	client = level.clients + clientNum;

	// ignore if client already entered the game
	if ( client->pers.connected != CON_CONNECTING )
	{
		return;
	}

	if ( ent->r.linked )
	{
		trap_UnlinkEntity( ent );
	}

	G_InitGentity( ent );

	// Create a basic client entity, will be replaced by a more specific one later.
	ent->entity = new ClientEntity({ent, client});

	ent->touch = 0;
	ent->pain = 0;
	ent->client = client;

	client->pers.connected = CON_CONNECTED;
	client->pers.enterTime = level.time;

	ClientAdminChallenge( clientNum );

	// save eflags around this, because changing teams will
	// cause this to happen with a valid entity, and we
	// want to make sure the teleport bit is set right
	// so the viewpoint doesn't interpolate through the
	// world to the new position
	flags = client->ps.eFlags;
	memset( &client->ps, 0, sizeof( client->ps ) );
	memset( &client->pmext, 0, sizeof( client->pmext ) );
	client->ps.eFlags = flags;

	// locate ent at a spawn point
	ClientSpawn( ent, nullptr, nullptr, nullptr );

	trap_SendServerCommand( -1, va( "print_tr %s %s", QQ( N_("$1$^7 entered the game") ), Quote( client->pers.netname ) ) );

	trap_Cvar_VariableStringBuffer( "g_mapStartupMessage", startMsg, sizeof( startMsg ) );

	if ( *startMsg )
	{
		trap_SendServerCommand( ent - g_entities, va( "cpd %d %s", g_mapStartupMessageDelay.integer, Quote( startMsg ) ) );
	}

	G_namelog_restore( client );

	G_LogPrintf( "ClientBegin: %i", clientNum );

	// count current clients and rank for scoreboard
	CalculateRanks();

	// display the help menu, if connecting the first time
	if ( !client->sess.seenWelcome )
	{
		client->sess.seenWelcome = 1;

		// 0 - don't show
		// 1 - always show to all
		// 2 - show only to unregistered
		switch ( g_showHelpOnConnection.integer )
		{
		case 0:
			if (0)
		default:
			if ( !client->pers.admin )
		case 1:
			G_TriggerMenu( client->ps.clientNum, MN_WELCOME );
		}
	}
}
Example #30
0
/*
===========
ClientBotConnect

Cut-down version of ClientConnect.
Doesn't do things not relevant to bots (which are local GUIDless clients).
============
*/
const char *ClientBotConnect( int clientNum, bool firstTime, team_t team )
{
	const char      *userInfoError;
	gclient_t       *client;
	char            userinfo[ MAX_INFO_STRING ];
	gentity_t       *ent;

	ent = &g_entities[ clientNum ];
	client = &level.clients[ clientNum ];

	ent->client = client;
	memset( client, 0, sizeof( *client ) );

	trap_GetUserinfo( clientNum, userinfo, sizeof( userinfo ) );

	client->pers.localClient = true;
	G_AddressParse( "localhost", &client->pers.ip );

	Q_strncpyz( client->pers.guid, "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", sizeof( client->pers.guid ) );
	client->pers.admin = nullptr;
	client->pers.pubkey_authenticated = true;
	client->pers.connected = CON_CONNECTING;

	// read or initialize the session data
	if ( firstTime )
	{
		G_InitSessionData( client, userinfo );
	}

	G_ReadSessionData( client );

	// get and distribute relevant parameters
	G_namelog_connect( client );
	userInfoError = ClientUserinfoChanged( clientNum, false );

	if ( userInfoError != nullptr )
	{
		return userInfoError;
	}

	ent->r.svFlags |= SVF_BOT;

	// can happen during reconnection
	if ( !ent->botMind )
	{
		G_BotSetDefaults( clientNum, team, client->sess.botSkill, client->sess.botTree );
	}

	G_LogPrintf( "ClientConnect: %i [%s] (%s) \"%s^7\" \"%s^7\" [BOT]",
	             clientNum, client->pers.ip.str[0] ? client->pers.ip.str : "127.0.0.1", client->pers.guid,
	             client->pers.netname,
	             client->pers.netname );

	// don't do the "xxx connected" messages if they were caried over from previous level
	if ( firstTime )
	{
		trap_SendServerCommand( -1, va( "print_tr %s %s", QQ( N_("$1$^7 connected") ),
		                                Quote( client->pers.netname ) ) );
	}

	// count current clients and rank for scoreboard
	CalculateRanks();

	return nullptr;
}