Exemplo n.º 1
0
//=========================================================================================
/*virtual*/ bool MultivectorNumber::Print( char* buffer, int bufferSize, bool printLatex, Environment& environment ) const
{
	ScalarAlgebra::PrintPurpose printPurpose = ScalarAlgebra::PRINT_FOR_READING;
	if( printLatex )
		printPurpose = ScalarAlgebra::PRINT_FOR_LATEX;

	if( !environment.IsTypeOf( GeometricAlgebraEnvironment::ClassName() ) )
	{
		environment.AddError( "Multivector numbers can't be printed in a non-geometric-algebra environment." );
		return false;
	}

	GeometricAlgebraEnvironment* geometricAlgebraEnvironment = ( GeometricAlgebraEnvironment* )&environment;

	if( geometricAlgebraEnvironment->displayMode == GeometricAlgebraEnvironment::DISPLAY_AS_SUM_OF_BLADES )
	{
		if( !multivector.Print( buffer, bufferSize, printPurpose ) )
		{
			environment.AddError( "Failed to print multivector!" );
			return false;
		}
	}
	else if( geometricAlgebraEnvironment->displayMode == GeometricAlgebraEnvironment::DISPLAY_AS_SUM_OF_VERSORS )
	{
		GeometricAlgebra::SumOfPseudoVersors sumOfPseudoVersors;
		if( !sumOfPseudoVersors.AssignSumOfBlades( multivector ) )
			return false;

		if( !sumOfPseudoVersors.Print( buffer, bufferSize, printPurpose ) )
		{
			environment.AddError( "Failed to print sum of versors!" );
			return false;
		}
	}
	else
	{
		environment.AddError( "Multivector number display mode is unknown." );
		return false;
	}

	return true;
}
Exemplo n.º 2
0
bool State::firstBinding(Environment & bs,const func_term * fe)
{
	int x = 0;
	for(parameter_symbol_list::const_iterator i = fe->getArgs()->begin();
				i != fe->getArgs()->end();++i,++x)
	{
		const var_symbol * ps = dynamic_cast<const var_symbol *>(*i);
		if(bs.find(ps)==bs.end())
		{
			if(records[fe->getFunction()][x].empty()) return false;
			bs[ps] = *(records[fe->getFunction()][x].begin());
		};
	};
	while(!safeBinding(bs,fe))
	{
		if(!nextBinding(bs,fe)) return false;
	};
	cout << "Got first binding\n";
	return true;
};
Exemplo n.º 3
0
//! @remark This small limits expressions to integers
bool Binop::execute(Environment& env)
{
  switch (this->type) {
    case Equal:
      env.write(VAL_LEFT, RIGHT);
      return true;

  default:
    throw Error("Tried to execute invalid binary operation");
  }
}
Exemplo n.º 4
0
real TimesExpression::execute(Environment &env) const {
	SaveOldValue<real> it  (env.iteration_value());
	SaveOldValue<real> last(env.last_value     ());

	try {
		for (real n = exec<0>(env), i = 0; i < n; i += 1.0) {
			it = i;
			last = exec<1>(env);
		}

		return exec<2>(env);
	}
	catch (BreakException &e) {
		if (e.end()) {
			return e.getValue();
		} else {
			throw;
		}
	}
}
/**
Esta funcion devuelve la siguiente mejor accion guiada por la heuristica usando el algoritmo minimax.
Devuelve: La siguiente accion a realizar.
Parametros:
    "actual" contiene el estado del tablero.
    "jug" indica que jugador esta pidiendo el valor heuristico.
    "limite_profundidad" establece el limite de exploracion del grafo.
OBSERVACION: esta parametrizacion es solo indicativa, y el alumno podra modificarla segun sus necesidades
*/
Environment::ActionType MiniMax(const Environment & actual, int jug, int limite_profundidad){
  Environment::ActionType accion;

  int mayor = -INFINITO, mayor_actual, profundidad = 0;

  Environment sigact[4];
  int n_act = actual.GenerateNextMove(sigact, jug);

  for (int i = 0; i < n_act; i++) {
        mayor_actual = valorMin(sigact[i], jug, profundidad+1, limite_profundidad, actual.Marcador(jug));
        if (mayor_actual > mayor) {
            mayor = mayor_actual;
            accion = static_cast<Environment::ActionType> (sigact[i].Last_Action(jug));
        }
  }
  cout << "Jugador: " << jug;
  cout << "     mayor " << mayor;
  cout << endl;
  return accion;
}
Exemplo n.º 6
0
	//--------------------------------------------------------------------------------------
	void ModelPrePixelLight::_SetParameters ()
	{
		Engine& engine = Engine::Instance();
		Device* device = engine.GetDevice();
		Environment* env = engine.GetEnvironment();
		ICamera* camera = engine.GetCamera();

		device->SetShaderParameter(m_hTransform, *(Matrix44f*)(m_pMaterial->Attribute( IAttributeNode::ATT_WORLDTRANSFORM )) );
		device->SetShaderParameter(m_hNormalTransform, *(Matrix33f*)(m_pMaterial->Attribute( IAttributeNode::ATT_NORMALTRANSFORM )) );
		device->SetShaderParameter(m_hViewProjMatrixLoc, camera->GetViewProj());
		device->SetShaderParameter(m_hLightDirectionLoc, -env->GetCurrentLight().GetWorldDirection() );//phong光是像素到光源的方向,所以这里反向
		device->SetShaderParameter(m_hCameraPositionLoc, camera->GetPosition() );

		device->SetShaderParameter( m_hTextureBase, *((Texture*)m_pMaterial->Attribute(Material::ATT_TEX_DIFFUSE)) );

		device->SetShaderParameter(m_hAmbient_AmbientLight, env->GetAmbient() * m_pMaterial->Ambient() );
		device->SetShaderParameter(m_hSpecular_Light, env->GetCurrentLight().GetColor() * m_pMaterial->Specular() * m_pMaterial->SpeLevel() );
		device->SetShaderParameter(m_hLight, m_pMaterial->Diffuse() * env->GetCurrentLight().GetColor() );
		device->SetShaderParameter(m_hShininess, m_pMaterial->Shininess() );
	}
Exemplo n.º 7
0
int read_file(Environment &e, const std::string &file, const fdmask &fds) {
	std::error_code ec;
	const mapped_file mf(file, mapped_file::readonly, ec);
	if (ec) {
		fprintf(stderr, "# Error reading %s: %s\n", file.c_str(), ec.message().c_str());
		return e.status(-1, false);
	}


	mpw_parser p(e, fds);
	e.status(0, false);

	try {
		p.parse(mf.begin(), mf.end());
		p.finish();
	} catch(const execution_of_input_terminated &ex) {
		return ex.status();
	}
	return e.status();
}
Exemplo n.º 8
0
static TIpAddress NetworkIf(Environment& aEnv, TUint aIndex)
{
    const std::vector<NetworkAdapter*>& ifs = aEnv.NetworkAdapterList().List();
    ASSERT(ifs.size() > 0 && aIndex < ifs.size());
    TIpAddress addr = ifs[aIndex]->Address();
    Endpoint endpt(0, addr);
    Endpoint::AddressBuf buf;
    endpt.AppendAddress(buf);
    Print("Using network interface %s\n\n", buf.Ptr());
    return ifs[aIndex]->Address();
}
Exemplo n.º 9
0
void PlayConfigWindow::loadLocationTab() {
	_environmentSelection->clear();
	_environment->clear();
	_environment->setRowCount(0);
	_environment->setColumnCount(0);

	QVector<Environment*> environments = _project->getEnvironments()->getEnvironments();
	StartEvent *start = _project->getStartEvent();
	int index = 0;

	for (int i = 0; i < environments.size(); i++) {
		Environment *it = environments.at(i);
		_environmentSelection->addItem(it->getName());

		if (!!start->getLocation().first && (start->getLocation().first->getName() == it->getName()))
			index = i;
	}

	_environmentSelection->setCurrentIndex(index);
}
bool EffectShieldBoostingInterpreter::removeEffect(const Environment& environment)
{
	const char* key = isProjected_ ? "Target" : "Ship";
	
	Environment::const_iterator Target = environment.find(key);
	Environment::const_iterator Self = environment.find("Self");
	Environment::const_iterator Char = environment.find("Char");
	Environment::const_iterator end = environment.end();
	if (Target != end && Self != end && Char != end) {
		Modifier* modifier = new Modifier(SHIELD_CHARGE_ATTRIBUTE_ID,
										  Modifier::ASSOCIATION_ADD_RATE,
										  Self->second->getAttribute(SHIELD_BONUS_ATTRIBUTE_ID),
										  isAssistance_,
										  isOffensive_,
										  dynamic_cast<Character*>(Char->second));
		Target->second->removeItemModifier(modifier);
		delete modifier;
	}
	return 1;
}
Exemplo n.º 11
0
bool Iterator::Consume(Environment &env)
{
	Signal &sig = env.GetSignal();
	if (IsInfinite()) {
		SetError_InfiniteNotAllowed(sig);
		return false;
	}
	Value value;
	while (Next(env, value)) ;
	return !sig.IsSignalled();
}
Exemplo n.º 12
0
Value Iterator::StandardDeviation(Environment &env, size_t &cnt, bool populationFlag)
{
	Signal &sig = env.GetSignal();
	if (IsInfinite()) {
		SetError_InfiniteNotAllowed(sig);
		return Value::Nil;
	}
	Value valueVar = Clone()->Variance(env, cnt, populationFlag);
	if (!valueVar.Is_number()) return Value::Nil;
	return Value(::sqrt(valueVar.GetNumber()));
}
Exemplo n.º 13
0
 std::string SSH::getPublicKey()
 {
     Environment env;
     auto var = env.getVar("HOME", "~");
     var.append("/.ssh/id_rsa.pub");
     try {
         Poco::FileInputStream fs(var);
         std::string buffer;
         Poco::StreamCopier::copyToString(fs, buffer);
         return buffer;
     }
     catch (Poco::FileNotFoundException e) {
         Poco::Logger::get("subutai").error("id_rsa.pub not found");
         return "";
     }
     catch (std::exception e) {
         Poco::Logger::get("subutai").error("Exception: %s", e.what());
         return "";
     }
 }
Exemplo n.º 14
0
/**
 * Initialise the engine (must be called AFTER gtk_init())
 *
 * @param config - the config container in use
 */
void GeckoEmbed::init(ConfigContainer config) {
	// Set the environment
	Environment env;
	string configProfilePath = env.getUserGeckoProfilePath();
	string configProfileName = "medes-gecko";
	gtk_moz_embed_set_profile_path(configProfilePath.c_str(),configProfileName.c_str());
	GtkMozEmbed *mozEmbed = GTK_MOZ_EMBED(gtk_moz_embed_new());
	gtk_moz_embed_set_chrome_mask(mozEmbed, GTK_MOZ_EMBED_FLAG_ALLCHROME);
	// Attach to functors
	gtk_signal_connect(GTK_OBJECT(mozEmbed), "open_uri", GTK_SIGNAL_FUNC(&GeckoEmbed::open_uri_cb), this);
	gtk_signal_connect(GTK_OBJECT(mozEmbed), "progress", GTK_SIGNAL_FUNC(&GeckoEmbed::progress_change_cb), this);
	gtk_signal_connect(GTK_OBJECT(mozEmbed), "net_start", GTK_SIGNAL_FUNC(&GeckoEmbed::load_started_cb), this);
	gtk_signal_connect(GTK_OBJECT(mozEmbed), "net_stop", GTK_SIGNAL_FUNC(&GeckoEmbed::load_finished_cb), this);
	// Initial object configuration
	setMozEmbed(mozEmbed);
	setConfig(config);
	setUrl(config.getAppUrl());
	dataSize = 0;
	status = NULL;
}
Exemplo n.º 15
0
void Person::HandleBeeping(Environment &env, const Event &e) {

	Elevator *ele = static_cast<Elevator*>(e.GetSender());

	if (elevator_ == ele && elevator_) {

		beeping_ = true;
		env.CancelEvent(action_); // Cancel Interface::Interact
		Exit(env);
	}
}
Exemplo n.º 16
0
//Регистрация статических переменных
void bind_static_media_player_library (Environment& environment)
{
  InvokerRegistry player_state_lib       = environment.CreateLibrary (MEDIA_STATIC_PLAYER_STATE_LIBRARY);
  InvokerRegistry player_repeat_mode_lib = environment.CreateLibrary (MEDIA_STATIC_PLAYER_REPEAT_MODE_LIBRARY);
  InvokerRegistry player_event_lib       = environment.CreateLibrary (MEDIA_STATIC_PLAYER_EVENT_LIBRARY);

  player_state_lib.Register       ("get_Stopped",            make_const (MediaPlayerState_Stopped));
  player_state_lib.Register       ("get_Playing",            make_const (MediaPlayerState_Playing));
  player_state_lib.Register       ("get_Paused",             make_const (MediaPlayerState_Paused));
  player_repeat_mode_lib.Register ("get_Off",                make_const (MediaPlayerRepeatMode_Off));
  player_repeat_mode_lib.Register ("get_Last",               make_const (MediaPlayerRepeatMode_Last));
  player_repeat_mode_lib.Register ("get_All",                make_const (MediaPlayerRepeatMode_All));
  player_event_lib.Register       ("get_OnChangeName",       make_const (MediaPlayerEvent_OnChangeName));
  player_event_lib.Register       ("get_OnChangeTarget",     make_const (MediaPlayerEvent_OnChangeTarget));
  player_event_lib.Register       ("get_OnChangePlaylist",   make_const (MediaPlayerEvent_OnChangePlaylist));
  player_event_lib.Register       ("get_OnChangeTrack",      make_const (MediaPlayerEvent_OnChangeTrack));
  player_event_lib.Register       ("get_OnChangePlayback",   make_const (MediaPlayerEvent_OnChangePlayback));
  player_event_lib.Register       ("get_OnChangeVolume",     make_const (MediaPlayerEvent_OnChangeVolume));
  player_event_lib.Register       ("get_OnChangeRepeatMode", make_const (MediaPlayerEvent_OnChangeRepeatMode));
}
Exemplo n.º 17
0
int builtin_alias(Environment &env, const std::vector<std::string> &tokens, const fdmask &fds) {

	// alias -> lists all aliases
	// alias name -> list single alias
	// alias name parms... -> add a new alias.

	if (tokens.size() == 1) {
		for (const auto &p : env.aliases()) {
			fdprintf(stdout, "Alias %s %s\n", quote(p.first).c_str(), quote(p.second).c_str());
		}
		return 0;
	}

	std::string name = tokens[1];
	if (tokens.size() == 2) {
		const auto as = env.find_alias(name);
		if (as.empty()) {
			fdprintf(stderr, "### Alias - No alias exists for %s\n", quote(name).c_str());
			return 1;
		}
		fdprintf(stdout, "Alias %s %s\n", quote(name).c_str(), quote(as).c_str());
		return 0;
	}		

	std::string as;
	for (const auto &s : make_offset_range(tokens, 2)) {
		as += s;
		as.push_back(' ');
	}
	as.pop_back();

	// add/remove it to the alias table...

	if (as.empty()) {
		env.remove_alias(name);
	}	
	else {
		env.add_alias(std::move(name), std::move(as));
	}
	return 0;
}
Exemplo n.º 18
0
//=========================================================================================
bool BinaryOperationEvaluator::EvaluateOperands( Number*& leftNumber, Number*& rightNumber, Environment& environment )
{
	bool success = false;

	leftNumber = 0;
	rightNumber = 0;

	do
	{
		if( !leftOperand )
		{
			environment.AddError( "Binary operator has no left operand." );
			break;
		}

		if( !rightOperand )
		{
			environment.AddError( "Binary operator has no right operand." );
			break;
		}

		// Call upon the environment to create the types of numbers we'll be working with.
		leftNumber = environment.CreateNumber( this );
		rightNumber = environment.CreateNumber( this );
		if( !( leftNumber && rightNumber ) )
		{
			environment.AddError( "Failed to create numbers from environment for binary operation." );
			break;
		}
		
		// Evaluate our left and right operands.
		if( !leftOperand->EvaluateResult( *leftNumber, environment ) )
		{
			environment.AddError( "Failed to evaluate left operand of binary operator." );
			break;
		}
		if( !rightOperand->EvaluateResult( *rightNumber, environment ) )
		{
			environment.AddError( "Failed to evaluate right operand of binary operator." );
			break;
		}

		success = true;
	}
	while( false );

	if( !success )
	{
		delete leftNumber;
		delete rightNumber;
		leftNumber = 0;
		rightNumber = 0;
	}

	return success;
}
Exemplo n.º 19
0
// FIXME: try to remove again
QString PathChooser::expandedDirectory(const QString &input, const Environment &env,
                                       const QString &baseDir)
{
    if (input.isEmpty())
        return input;
    const QString path = QDir::cleanPath(env.expandVariables(input));
    if (path.isEmpty())
        return path;
    if (!baseDir.isEmpty() && QFileInfo(path).isRelative())
        return QFileInfo(baseDir + QLatin1Char('/') + path).absoluteFilePath();
    return path;
}
Exemplo n.º 20
0
GLenum GetImageFormat(Environment &env, const Image *pImage)
{
	GLenum format = 0;
	Image::Format fmt = pImage->GetFormat();
	format =
		(fmt == Image::FORMAT_RGB)? GL_BGR_EXT :
		(fmt == Image::FORMAT_RGBA)? GL_BGRA_EXT : 0;
	if (format == 0) {
		env.SetError(ERR_ValueError, "unsupported image type");
	}
	return format;
}
Exemplo n.º 21
0
occi_datasource::~occi_datasource()
{
    {
        Environment* env = occi_environment::get_environment();

        if (use_connection_pool_)
        {
            if (pool_ != 0)
            {
                env->terminateStatelessConnectionPool(pool_, StatelessConnectionPool::SPD_FORCE);
            }
        }
        else
        {
            if (conn_ != 0)
            {
                env->terminateConnection(conn_);
            }
        }
    }
}
Exemplo n.º 22
0
Environment *
ClosureValue::bindArguments( std::vector<Handle_ptr> &argValues)
{
  MCAssertValidInstance();
  if (argValues.size() != m_argumentNames.size())
    throw ArgumentCountException( m_argumentNames.size(), __FILE__, __LINE__);

  else {
    // number of actual parameters matches closure's arity
    Environment *newEnv = m_env->makeChildEnvironment();
    std::vector<std::string>::iterator namePos = m_argumentNames.begin();
    std::vector<Handle_ptr>::iterator valPos = argValues.begin();
    while ((namePos != m_argumentNames.end()) && (valPos != argValues.end())) {
      newEnv->put( *namePos, *valPos);
      ++namePos, ++valPos;
    }
    return newEnv;
  }

  MCAssertNotReached( 0);
}
Exemplo n.º 23
0
size_t Iterator::FindTrue(Environment &env, Value &value)
{
	Signal &sig = env.GetSignal();
	if (IsInfinite()) {
		SetError_InfiniteNotAllowed(sig);
		return 0;
	}
	while (Next(env, value)) {
		if (value.GetBoolean()) return GetIndexCur();
	}
	return InvalidSize;
}
Result<Environment> Environment::CreateForUser(const Handle& token, bool inherit, Trace& trace)
{
	trace < L"Environment::CreateForUser";
	Environment newEnvironment;
	LPVOID environment;
	if (!CreateEnvironmentBlock(&environment, token, inherit))
	{
		return Result<Environment>(ErrorUtilities::GetErrorCode(), ErrorUtilities::GetLastErrorMessage(L"CreateEnvironmentBlock"));
	}

	try
	{
		newEnvironment.CreateVariableMap(environment, trace);
	}
	catch (...)
	{
	}

	DestroyEnvironmentBlock(environment);
	return newEnvironment;
}
Exemplo n.º 25
0
// [[Rcpp::export]]
void WriteCapInfo_cpp (CharacterVector fname, SEXP args_env) {
  Environment testr = Environment::namespace_env("testr");
  Environment cache = testr.get("cache");
  string traceFile = as<string>(cache.get("trace.folder.path"));
  traceFile += "/";
  traceFile += as<string>(testr.get("kCaptureFile"));
  traceFile += "."; 
  char numstr[21];
  sprintf(numstr, "%d", captureFileNumber);
  traceFile += numstr;
  tracefile.open(traceFile.c_str(), std::ios::app);
  printCapture(fname, kFuncPrefix);
  printCapture(deparse(GetArgs(args_env)), kArgsPrefix);
  tracefile << std::endl;
  tracefile.close();
  // get file size
  struct stat stat_buf;
  stat(traceFile.c_str(), &stat_buf);
  if (stat_buf.st_size > MAX_FILE_SIZE)
  captureFileNumber++;
}
Exemplo n.º 26
0
Result<Environment> Environment::CreateForUser(const Handle& token, bool inherit, Trace& trace)
{
	trace < L"Environment::CreateForUser";
	Environment newEnvironment;
	LPVOID environment;
	if (!CreateEnvironmentBlock(&environment, token, inherit))
	{
		return Error(L"CreateEnvironmentBlock");
	}

	try
	{
		newEnvironment.CreateVariableMap(environment, trace);
	}
	catch (...)
	{
	}

	DestroyEnvironmentBlock(environment);
	return newEnvironment;
}
Exemplo n.º 27
0
void ReturnTypeCommand::execute(Args &args, Environment &env)
{
	if(args.size() != 2) {
		throw CommandException("Wrong number of arguments");
	}

	string type;
	XmlQueryContext::ReturnType t = (XmlQueryContext::ReturnType)-1;

	if(args[1] == "lv") {
		t = XmlQueryContext::LiveValues;
		type = "LiveValues";
	}

	if(t == (XmlQueryContext::ReturnType)-1) {
		throw CommandException("Unknown return type: " + args[1]);
	}

	if(env.verbose()) cout << "Setting return type to: " << type << endl;
	env.context().setReturnType(t);
}
Exemplo n.º 28
0
void ElevatorLogic::HandleNotify(Environment &env, const Event &e) {

	Interface *interf = static_cast<Interface*>(e.GetSender());
	Loadable *loadable = interf->GetLoadable(0);

	if (loadable->GetType() == "Elevator") {

		Elevator *ele = static_cast<Elevator*>(loadable);

		env.SendEvent("Elevator::Open", 0, this, ele);
	}
}
Exemplo n.º 29
0
int LuaVoxelManip::l_update_liquids(lua_State *L)
{
	LuaVoxelManip *o = checkobject(L, 1);

	Environment *env = getEnv(L);
	if (!env)
		return 0;

	Map *map = &(env->getMap());
	INodeDefManager *ndef = getServer(L)->getNodeDefManager();
	ManualMapVoxelManipulator *vm = o->vm;

	Mapgen mg;
	mg.vm   = vm;
	mg.ndef = ndef;

	mg.updateLiquid(&map->m_transforming_liquid,
			vm->m_area.MinEdge, vm->m_area.MaxEdge);

	return 0;
}
Exemplo n.º 30
0
void EnvironmentTestCase::testEvaluateCallRegObject() {
    Environment engine;

    QString script;
    script = "var obj = new QtScriptObject();"
             "obj.name = \"Navn\";"
             "obj.toString();";

    engine.registerClass<QtScriptObject>( "QtScriptObject" );
    ASSERT_EQUAL( engine.evaluate( script ).toString(), "Navn" );

    script = "var obj = new QtScriptObject( 5 );";
    ASSERT_EXCEPTION( engine.evaluate( script ), ScriptException );

    script = "var obj = QtScriptObject();";
    ASSERT_EXCEPTION( engine.evaluate( script ), ScriptException );

    script = "var a = new QtScriptObject();"
             "a.name = \"A\";"
             "var b = a;"
             "b.name = \"B\";"
             "b.name";
    ASSERT_EQUAL( engine.evaluate( script ).toString(), "B" );

    script = "var a = new QtScriptObject();"
             "a.name = \"A\";"
             "var b = a;"
             "b.name = \"B\";"
             "a.name";
    ASSERT_EQUAL( engine.evaluate( script ).toString(), "B" );
};