Exemplo n.º 1
48
double PatchyDisc::computePairEnergy(unsigned int particle1, double position1[],
    double orientation1[], unsigned int particle2, double position2[], double orientation2[])
{
    // Separation vector.
    std::vector<double> sep(2);

    // Calculate disc separation.
    sep[0] = position1[0] - position2[0];
    sep[1] = position1[1] - position2[1];

    // Enforce minimum image.
    box.minimumImage(sep);

    // Calculate squared norm of vector.
    double normSqd = sep[0]*sep[0] + sep[1]*sep[1];

    // Discs overlap.
    if (normSqd < 1) return INF;

    // Total interaction energy sum.
    double energy = 0;

    // Test interactions between all patch pairs.
    for (unsigned int i=0;i<maxInteractions;i++)
    {
        // Compute position of patch i on first disc.
        std::vector<double> coord1(2);
        coord1[0] = position1[0] + 0.5*(orientation1[0]*cosTheta[i] - orientation1[1]*sinTheta[i]);
        coord1[1] = position1[1] + 0.5*(orientation1[0]*sinTheta[i] + orientation1[1]*cosTheta[i]);

        // Enforce periodic boundaries.
        box.periodicBoundaries(coord1);

        for (unsigned int j=0;j<maxInteractions;j++)
        {
            // Compute position of patch j on second disc.
            std::vector<double> coord2(2);
            coord2[0] = position2[0] + 0.5*(orientation2[0]*cosTheta[j] - orientation2[1]*sinTheta[j]);
            coord2[1] = position2[1] + 0.5*(orientation2[0]*sinTheta[j] + orientation2[1]*cosTheta[j]);

            // Enforce periodic boundaries.
            box.periodicBoundaries(coord2);

            // Calculate patch separation.
            sep[0] = coord1[0] - coord2[0];
            sep[1] = coord1[1] - coord2[1];

            // Enforce minimum image.
            box.minimumImage(sep);

            // Calculate squared norm of vector.
            normSqd = sep[0]*sep[0] + sep[1]*sep[1];

            // Patches interact.
            if (normSqd < squaredCutOffDistance)
                energy -= interactionEnergy;
        }
    }

    return energy;
}
Exemplo n.º 2
1
	void Execute(CommandSource &source, const std::vector<Anope::string> &params) override
	{
		const Anope::string &target = params[0];
		const Anope::string &modes = params[1];

		Reference<Channel> c = Channel::Find(target);
		if (!c)
			source.Reply(_("Channel \002{0}\002 doesn't exist."), target);
		else if (c->bouncy_modes)
			source.Reply(_("Services is unable to change modes. Are your servers' U:lines configured correctly?"));
		else if (modes.equals_ci("CLEAR"))
		{
			bool all = params.size() > 2 && params[2].equals_ci("ALL");

			const Channel::ModeList chmodes = c->GetModes();
			for (Channel::ModeList::const_iterator it = chmodes.begin(), it_end = chmodes.end(); it != it_end && c; ++it)
				c->RemoveMode(c->ci->WhoSends(), it->first, it->second, false);

			if (!c)
			{
				source.Reply(_("Modes cleared on %s and the channel destroyed."), target.c_str());
				return;
			}

			if (all)
			{
				for (Channel::ChanUserList::iterator it = c->users.begin(), it_end = c->users.end(); it != it_end; ++it)
				{
					ChanUserContainer *uc = it->second;

					if (uc->user->HasMode("OPER"))
						continue;

					for (size_t i = uc->status.Modes().length(); i > 0; --i)
						c->RemoveMode(c->ci->WhoSends(), ModeManager::FindChannelModeByChar(uc->status.Modes()[i - 1]), uc->user->GetUID(), false);
				}

				source.Reply(_("All modes cleared on \002{0}\002."), c->name);
			}
			else
				source.Reply(_("Non-status modes cleared on \002{0}\002."), c->name);
		}
		else
		{
			spacesepstream sep(modes + (params.size() > 2 ? " " + params[2] : ""));
			Anope::string mode;
			int add = 1;
			Anope::string log_modes, log_params;

			sep.GetToken(mode);
			for (unsigned i = 0; i < mode.length() && c; ++i)
			{
				char ch = mode[i];

				if (ch == '+')
				{
					add = 1;
					log_modes += "+";
					continue;
				}
				else if (ch == '-')
				{
					add = 0;
					log_modes += "-";
					continue;
				}

				ChannelMode *cm = ModeManager::FindChannelModeByChar(ch);
				if (!cm)
					continue;

				Anope::string param, param_log;
				if (cm->type != MODE_REGULAR)
				{
					if (cm->type == MODE_PARAM && !add && anope_dynamic_static_cast<ChannelModeParam *>(cm)->minus_no_arg)
						;
					else if (!sep.GetToken(param))
						continue;

					param_log = param;

					if (cm->type == MODE_STATUS)
					{
						User *targ = User::Find(param, true);
						if (targ == NULL || c->FindUser(targ) == NULL)
							continue;
						param = targ->GetUID();
					}
				}

				log_modes += cm->mchar;
				if (!param.empty())
					log_params += " " + param_log;

				if (add)
					c->SetMode(source.service, cm, param, false);
				else
					c->RemoveMode(source.service, cm, param, false);
			}

			if (!log_modes.replace_all_cs("+", "").replace_all_cs("-", "").empty())
				Log(LOG_ADMIN, source, this) << log_modes << log_params << " on " << (c ? c->name : target);
		}
	}
Exemplo n.º 3
0
int main(int argc, const char* argv[])
{
	puts("this is a file transfer client.");
	printf("usage: file_client [<port=%d> [<ip=%s> [link num=1]]]\n", ST_ASIO_SERVER_PORT, ST_ASIO_SERVER_IP);
	if (argc >= 2 && (0 == strcmp(argv[1], "--help") || 0 == strcmp(argv[1], "-h")))
		return 0;
	else
		puts("type " QUIT_COMMAND " to end.");

	st_service_pump service_pump;
	file_client client(service_pump);

	if (argc > 3)
		link_num = std::min(256, std::max(atoi(argv[3]), 1));

	for (int i = 0; i < link_num; ++i)
	{
//		argv[2] = "::1" //ipv6
//		argv[2] = "127.0.0.1" //ipv4
		if (argc > 2)
			client.add_client(atoi(argv[1]), argv[2])->set_index(i);
		else if (argc > 1)
			client.add_client(atoi(argv[1]))->set_index(i);
		else
			client.add_client()->set_index(i);
	}

	service_pump.start_service();
	while(service_pump.is_running())
	{
		std::string str;
		std::getline(std::cin, str);
		if (str == QUIT_COMMAND)
			service_pump.stop_service();
		else if (str == RESTART_COMMAND)
		{
			service_pump.stop_service();
			service_pump.start_service();
		}
		else if (str.size() > sizeof(REQUEST_FILE) && !strncmp(REQUEST_FILE, str.data(), sizeof(REQUEST_FILE) - 1) && isspace(str[sizeof(REQUEST_FILE) - 1]))
		{
			str.erase(0, sizeof(REQUEST_FILE));
			boost::char_separator<char> sep(" \t");
			boost::tokenizer<boost::char_separator<char> > tok(str, sep);
			for (BOOST_AUTO(iter, tok.begin()); iter != tok.end(); ++iter)
			{
				completed_client_num = 0;
				file_size = 0;
				boost::timer::cpu_timer begin_time;

				printf("transfer %s begin.\n", iter->data());
				if (client.find(0)->get_file(*iter))
				{
					client.do_something_to_all(boost::bind(&file_socket::get_file, _1, boost::cref(*iter)));
					client.start();

					while (completed_client_num != (unsigned short) link_num)
						boost::this_thread::sleep(boost::get_system_time() + boost::posix_time::milliseconds(50));

					client.stop(*iter);
				}
				else
					printf("transfer %s failed!\n", iter->data());
			}
		}
		else
			client.at(0)->talk(str);
	}

	return 0;
}
Exemplo n.º 4
0
/* Copy directory path with overflow checking */
static void dircpy(char *dst, char *src) {
	if (strlen(src) >= FILENAME_MAX) {
		cbFatal(cbctx, "directory path too long");
	}
	sprintf(dst, "%s%s", src, sep());
}
Exemplo n.º 5
0
Serializable* NickCore::Unserialize(Serializable *obj, Serialize::Data &data)
{
	NickCore *nc;

	Anope::string sdisplay;

	data["display"] >> sdisplay;

	if (obj)
		nc = anope_dynamic_static_cast<NickCore *>(obj);
	else
		nc = new NickCore(sdisplay);

	data["pass"] >> nc->pass;
	data["email"] >> nc->email;
	data["language"] >> nc->language;
	{
		Anope::string buf;
		data["access"] >> buf;
		spacesepstream sep(buf);
		nc->access.clear();
		while (sep.GetToken(buf))
			nc->access.push_back(buf);
	}
	data["memomax"] >> nc->memos.memomax;
	{
		Anope::string buf;
		data["memoignores"] >> buf;
		spacesepstream sep(buf);
		nc->memos.ignores.clear();
		while (sep.GetToken(buf))
			nc->memos.ignores.push_back(buf);
	}

	Extensible::ExtensibleUnserialize(nc, nc, data);

	/* compat */
	bool b;
	b = false;
	data["extensible:SECURE"] >> b;
	if (b)
		nc->Extend<bool>("NS_SECURE");
	b = false;
	data["extensible:PRIVATE"] >> b;
	if (b)
		nc->Extend<bool>("NS_PRIVATE");
	b = false;
	data["extensible:AUTOOP"] >> b;
	if (b)
		nc->Extend<bool>("AUTOOP");
	b = false;
	data["extensible:HIDE_EMAIL"] >> b;
	if (b)
		nc->Extend<bool>("HIDE_EMAIL");
	b = false;
	data["extensible:HIDE_QUIT"] >> b;
	if (b)
		nc->Extend<bool>("HIDE_QUIT");
	b = false;
	data["extensible:MEMO_RECEIVE"] >> b;
	if (b)
		nc->Extend<bool>("MEMO_RECEIVE");
	b = false;
	data["extensible:MEMO_SIGNON"] >> b;
	if (b)
		nc->Extend<bool>("MEMO_SIGNON");
	b = false;
	data["extensible:KILLPROTECT"] >> b;
	if (b)
		nc->Extend<bool>("KILLPROTECT");
	/* end compat */

	return nc;
}
Exemplo n.º 6
0
bool SpawnManager::loadSpawnsSQL(std::string identifier)
{
	std::string host = g_config.getGlobalString("map_host");
	std::string user = g_config.getGlobalString("map_user");
	std::string pass = g_config.getGlobalString("map_pass");
	std::string db   = g_config.getGlobalString("map_db");

#ifdef __DEBUG__
	std::cout "host" << host << "user" << user << "pass" << pass << "db" << db << std::endl;
#endif     
	mysqlpp::Connection con;

	try{
		con.connect(db.c_str(), host.c_str(), user.c_str(), pass.c_str()); 
	}
	catch(mysqlpp::BadQuery e){
		std::cout << "MYSQL-ERROR: " << e.error << std::endl;
		return false;
	}
	
	mysqlpp::Result res;
	
	//Monsters

	//Try & Find the Monter's	
	try{
     mysqlpp::Query query = con.query();
		query << "SELECT * FROM " << identifier << "_monsters WHERE name !=''";
	 
#ifdef __DEBUG__
	std::cout << query.preview() << std::endl;
#endif	
	
	 res = query.store();
	} //End Try
	catch(mysqlpp::BadQuery e){
		std::cout << "MYSQL-ERROR: " << e.error << std::endl;
		return false;
	}

	std::cout << ":: Found: " << res.size() << " Monsters(s)/Spawn(s)" << std::endl;
    if(res.size() < 1){//No Monsters
       std::cout << "No Monsters found" << std::endl;
       return false;
    }
		//if there are any monster spawns to load
    else{
       //Load Monsters
			try{
        mysqlpp::Result Monster;
        mysqlpp::Query query = con.query();

        for(int i=1; i <= res.size(); ++i){
          query.reset();
          query << "SELECT * FROM " << identifier << "_monsters WHERE id = '" << i <<"' and id != ''";
          Monster = query.store();
          mysqlpp::Row row = *Monster.begin();          
          //Get the Monster's Position on Map
          std::string pos = std::string(row.lookup_by_name("spawnpos"));
          boost::char_separator<char> sep(";");
          tokenizer spawnpostokens(pos, sep);
          tokenizer::iterator spawnposit = spawnpostokens.begin();
					Position spawnpos;
          spawnpos.x=atoi(spawnposit->c_str()); spawnposit++;
					spawnpos.y=atoi(spawnposit->c_str()); spawnposit++;
					spawnpos.z=atoi(spawnposit->c_str());
					std::string name;
          if(std::string(row.lookup_by_name("name")) != ""){name = std::string(row.lookup_by_name("name"));}
          int time = row.lookup_by_name("time");

          Spawn *spawn = new Spawn(game, spawnpos, 1);
					spawns.push_back(spawn);
          spawn->addMonster(name, NORTH, 0, 0, time * 1000);
        }//End For Loop
			}//End Try
			catch(mysqlpp::BadQuery e){
				std::cout << "MYSQL-ERROR: " << e.error << std::endl;
				return false;
			}//End Catch    
		}
	
	//NPC's	
	//Try & Find the NPC's	
	try{
		mysqlpp::Query query = con.query();
		query << "SELECT * FROM " << identifier << "_npcs WHERE name !=''";
	 
#ifdef __DEBUG__
		std::cout << query.preview() << std::endl;
#endif	
	
	 res = query.store();
	}//End Try
	catch(mysqlpp::BadQuery e){
		std::cout << "MYSQL-ERROR: " << e.error << std::endl;
		return false;
	}

	std::cout << ":: Found: " << res.size() << " NPC(s)" << std::endl;
    if(res.size() < 1){//No NPC's
       std::cout << "No NPC's found" << std::endl;
       return false;
		}
		//if there are any NPC's to load
    else{
       //Load Monsters
			try{
        mysqlpp::Result Monster;
        mysqlpp::Query query = con.query();

        for(int i=1; i <= res.size(); ++i){
          query.reset();
          query << "SELECT * FROM " << identifier << "_npcs WHERE id = '" << i <<"' and id != ''";
          Monster = query.store();
          mysqlpp::Row row = *Monster.begin();          
          //Get the NPC's Position on Map
          std::string pos = std::string(row.lookup_by_name("pos"));
          boost::char_separator<char> sep(";");
          tokenizer postokens(pos, sep);
          tokenizer::iterator posit = postokens.begin();
					Position npcpos;
          npcpos.x=atoi(posit->c_str()); posit++;
					npcpos.y=atoi(posit->c_str()); posit++;
					npcpos.z=atoi(posit->c_str());
					std::string name;
          if(std::string(row.lookup_by_name("name")) != ""){name = std::string(row.lookup_by_name("name"));}
          int dir = row.lookup_by_name("dir");
          Npc* npc = new Npc(name, game);
          
          npc->pos = npcpos;
          switch(dir){
             case 1:
                npc->direction=(NORTH);
                break;
             
             case 2:
                npc->direction=(SOUTH);
                break;
             
             case 3:
                npc->direction=(WEST);
                break;
             
             case 4:
                npc->direction=(EAST);
                break;
             
             default:
              //  std::cout << "Invalid direction for " << name << "  " <<x<<" "<<y<<" "<<z<<".";
                return false;
                break;
          }
					
					if(!game->placeCreature(npc->pos, npc)){
						delete npc;
					}
				}//End For Loop
        return true;
			}//End Try
			catch(mysqlpp::BadQuery e){
				std::cout << "MYSQL-ERROR: " << e.error << std::endl;
				return false;
			}//End Catch    
    
		}
    return true;
}
Exemplo n.º 7
0
// Iterates through space delimited tokens in string, triggering any gestures found.
// Generates a revised string that has the found tokens replaced by their replacement strings
// and (as a minor side effect) has multiple spaces in a row replaced by single spaces.
BOOL LLGestureManager::triggerAndReviseString(const std::string &utf8str, std::string* revised_string)
{
	std::string tokenized = utf8str;

	BOOL found_gestures = FALSE;
	BOOL first_token = TRUE;

	typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
	boost::char_separator<char> sep(" ");
	tokenizer tokens(tokenized, sep);
	tokenizer::iterator token_iter;

	for( token_iter = tokens.begin(); token_iter != tokens.end(); ++token_iter)
	{
		const char* cur_token = token_iter->c_str();
		LLMultiGesture* gesture = NULL;

		// Only pay attention to the first gesture in the string.
		if( !found_gestures )
		{
			std::string cur_token_lower = cur_token;
			LLStringUtil::toLower(cur_token_lower);

			// collect gestures that match
			std::vector <LLMultiGesture *> matching;
			item_map_t::iterator it;
			for (it = mActive.begin(); it != mActive.end(); ++it)
			{
				gesture = (*it).second;

				// Gesture asset data might not have arrived yet
				if (!gesture) continue;
				
				if (gesture->mTrigger == cur_token_lower)
				{
					matching.push_back(gesture);
				}
				
				gesture = NULL;
			}

			
			if (matching.size() > 0)
			{
				// choose one at random
				{
					S32 random = ll_rand(matching.size());

					gesture = matching[random];
					
					playGesture(gesture);

					if (!gesture->mReplaceText.empty())
					{
						if( !first_token )
						{
							if (revised_string)
								revised_string->append( " " );
						}

						// Don't muck with the user's capitalization if we don't have to.
						std::string output = gesture->mReplaceText;
						std::string output_lower = output;
						LLStringUtil::toLower(output_lower);
						if( cur_token_lower == output_lower )
						{
							if (revised_string)
								revised_string->append( cur_token );
						}
						else
						{
							if (revised_string)
								revised_string->append( output );
						}
					}
					found_gestures = TRUE;
				}
			}
		}
		
		if(!gesture)
		{
			// This token doesn't match a gesture.  Pass it through to the output.
			if( !first_token )
			{
				if (revised_string)
					revised_string->append( " " );
			}
			if (revised_string)
				revised_string->append( cur_token );
		}

		first_token = FALSE;
		gesture = NULL;
	}
	return found_gestures;
}
Exemplo n.º 8
0
  inline
  time_duration
  parse_delimited_time_duration(const std::string& s)
  {
    unsigned short min=0, sec =0;
    int hour =0; 
    bool is_neg = (s.at(0) == '-');
    boost::int64_t fs=0;
    int pos = 0;
    
    char_separator<char> sep("-:,.");
    tokenizer<char_separator<char> > tok(s,sep);
    for(tokenizer<char_separator<char> >::iterator beg=tok.begin(); beg!=tok.end();++beg){
      switch(pos) {
      case 0: {
        hour = boost::lexical_cast<int>(*beg);
        break;
      }
      case 1: {
        min = boost::lexical_cast<unsigned short>(*beg);
        break;
      }
      case 2: {
        sec = boost::lexical_cast<unsigned short>(*beg);
        break;
      };
      case 3: {
        int digits = static_cast<int>(beg->length());
        //Works around a bug in MSVC 6 library that does not support
        //operator>> thus meaning lexical_cast will fail to compile.
#if (defined(BOOST_MSVC) && (_MSC_VER <= 1200))  // 1200 == VC++ 6.0
        // msvc wouldn't compile 'time_duration::num_fractional_digits()' 
        // (required template argument list) as a workaround a temp 
        // time_duration object was used
        time_duration td(hour,min,sec,fs);
        int precision = td.num_fractional_digits();
        // _atoi64 is an MS specific function
        if(digits >= precision) {
          // drop excess digits
          fs = _atoi64(beg->substr(0, precision).c_str());
        }
        else {
          fs = _atoi64(beg->c_str());
        }
#else
        int precision = time_duration::num_fractional_digits();
        if(digits >= precision) {
          // drop excess digits
          fs = boost::lexical_cast<boost::int64_t>(beg->substr(0, precision));
        }
        else {
          fs = boost::lexical_cast<boost::int64_t>(*beg);
        }
#endif
        if(digits < precision){
          // trailing zeros get dropped from the string, 
          // "1:01:01.1" would yield .000001 instead of .100000
          // the power() compensates for the missing decimal places
          fs *= power(10, precision - digits); 
        }
        
        break;
      }
      }//switch
      pos++;
    }
    if(is_neg) {
      return -time_duration(hour, min, sec, fs);
    }
    else {
      return time_duration(hour, min, sec, fs);
    }
  }
Exemplo n.º 9
0
Set::Set(NumConstraint& ctr, double eps) : root(new SetLeaf(YES)), Rn(ctr.f.nb_var()) {
	SepFwdBwd sep(ctr);
	sep.contract(*this,eps);
}
Exemplo n.º 10
0
void PluginCallbackManager::init()
{
	DIR *dp;
	struct dirent *ep;

	dp = opendir(getPluginDirectory());
	if (dp != NULL)
	{
		while (ep = readdir(dp))
		{
			int location = strstr(ep->d_name,".") - ep->d_name;
			// We're one of ".", "..", or hidden, so let's skip
			if ( location == 0 )
				continue;

			LogDebug(VB_PLUGIN, "Found Plugin: (%s)\n", ep->d_name);

			std::string filename = std::string(getPluginDirectory()) + "/" + ep->d_name + "/callbacks";
			bool found = false;

			if ( FileExists(filename.c_str()) )
			{
				printf("Found callback with no extension");
				found = true;
			}
			else
			{
				std::vector<std::string> extensions;
				extensions.push_back(std::string(".sh"));
				extensions.push_back(std::string(".pl"));
				extensions.push_back(std::string(".php"));
				extensions.push_back(std::string(".py"));

				for ( std::vector<std::string>::iterator i = extensions.begin(); i != extensions.end(); ++i)
				{
					std::string tmpFilename = filename + *i;
					if ( FileExists( tmpFilename.c_str() ) )
					{
						filename += *i;
						found = true;
					}
				}
			}
			std::string eventScript = std::string(getFPPDirectory()) + "/scripts/eventScript";

			if ( !found )
			{
				LogExcess(VB_PLUGIN, "No callbacks supported by plugin: '%s'\n", ep->d_name);
				continue;
			}

			LogDebug(VB_PLUGIN, "Processing Callbacks (%s) for plugin: '%s'\n", filename.c_str(), ep->d_name);

			int output_pipe[2], pid, bytes_read;
			char readbuffer[128];
			std::string callback_list = "";

			if (pipe(output_pipe) == -1)
			{
				LogErr(VB_PLUGIN, "Failed to make pipe\n");
				exit(EXIT_FAILURE);
			}

			if ((pid = fork()) == -1 )
			{
				LogErr(VB_PLUGIN, "Failed to fork\n");
				exit(EXIT_FAILURE);
			}

			if ( pid == 0 )
			{
				dup2(output_pipe[1], STDOUT_FILENO);
				close(output_pipe[1]);
				execl(eventScript.c_str(), "eventScript", filename.c_str(), "--list", NULL);

				LogErr(VB_PLUGIN, "We failed to exec our callbacks query!\n");
				exit(EXIT_FAILURE);
			}
			else
			{
				close(output_pipe[1]);

				while (true)
				{
					bytes_read = read(output_pipe[0], readbuffer, sizeof(readbuffer)-1);

					if (bytes_read <= 0)
						break;

					readbuffer[bytes_read] = '\0';
					callback_list += readbuffer;
				}

				boost::trim(callback_list);

				LogExcess(VB_PLUGIN, "Callback output: (%s)\n", callback_list.c_str());

				wait(NULL);
			}

			boost::char_separator<char> sep(",");
			boost::tokenizer< boost::char_separator<char> > tokens(callback_list, sep);
		    BOOST_FOREACH (const std::string& type, tokens)
			{
				if (type == "media")
				{
					LogDebug(VB_PLUGIN, "Plugin %s supports media callback.\n", ep->d_name);
					MediaCallback *media = new MediaCallback(std::string(ep->d_name), filename);
					mCallbacks.push_back(media);
				}
				else if (type == "playlist")
				{
					LogDebug(VB_PLUGIN, "Plugin %s supports playlist callback.\n", ep->d_name);
					PlaylistCallback *playlist = new PlaylistCallback(std::string(ep->d_name), filename);
					mCallbacks.push_back(playlist);
				}
				else if (type == "nextplaylist")
				{
					LogDebug(VB_PLUGIN, "Plugin %s supports nextplaylist callback.\n", ep->d_name);
					NextPlaylistEntryCallback *nextplaylistentry = new NextPlaylistEntryCallback(std::string(ep->d_name), filename);
					mCallbacks.push_back(nextplaylistentry);
				}
				else if (type == "event")
				{
					LogDebug(VB_PLUGIN, "Plugin %s supports event callback.\n", ep->d_name);
					EventCallback *eventcallback = new EventCallback(std::string(ep->d_name), filename);
					mCallbacks.push_back(eventcallback);
				}
			}

			plugin_count += 1;
		}
		closedir(dp);
	}
	else
	{
Exemplo n.º 11
0
  /** Using the [Post]ProcessingAlgorithm and [Post]ProcessingProperties properties,
   * create and initialize an algorithm for processing.
   *
   * @param postProcessing :: true to create the PostProcessingAlgorithm.
   *        false to create the ProcessingAlgorithm
   * @return shared pointer to the algorithm, ready for execution.
   *         Returns a NULL pointer if no algorithm was chosen.
   */
  IAlgorithm_sptr LiveDataAlgorithm::makeAlgorithm(bool postProcessing)
  {
    std::string prefix = "";
    if (postProcessing)
      prefix = "Post";

    // Get the name of the algorithm to run
    std::string algoName = this->getPropertyValue(prefix+"ProcessingAlgorithm");
    algoName = Strings::strip(algoName);

    // Get the script to run. Ignored if algo is specified
    std::string script = this->getPropertyValue(prefix+"ProcessingScript");
    script = Strings::strip(script);

    if (!algoName.empty())
    {
      // Properties to pass to algo
      std::string props = this->getPropertyValue(prefix+"ProcessingProperties");

      // Create the UNMANAGED algorithm
      IAlgorithm_sptr alg = this->createChildAlgorithm(algoName);

      // ...and pass it the properties
      boost::char_separator<char> sep(";");
      typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
      tokenizer propPairs(props, sep);
      // Iterate over the properties
      for (tokenizer::iterator it = propPairs.begin(); it != propPairs.end(); ++it)
      {
        // Pair of the type "
        std::string pair = *it;

        size_t n = pair.find('=');
        if (n == std::string::npos)
        {
          // Do nothing
        }
        else
        {
          // Normal "PropertyName=value" string.
          std::string propName = "";
          std::string value = "";

          // Extract the value string
          if (n < pair.size()-1)
          {
            propName = pair.substr(0, n);
            value = pair.substr(n+1, pair.size()-n-1);
          }
          else
          {
            // String is "PropertyName="
            propName = pair.substr(0, n);
            value = "";
          }
          // Skip some of the properties when setting
          if ((propName != "InputWorkspace") && (propName != "OutputWorkspace"))
            alg->setPropertyValue(propName,value);
        }
      }

      // Warn if someone put both values.
      if (!script.empty())
        g_log.warning() << "Running algorithm " << algoName << " and ignoring the script code in " << prefix+"ProcessingScript" << std::endl;
      return alg;
    }
    else if (!script.empty())
    {
      // Run a snippet of python
      IAlgorithm_sptr alg = this->createChildAlgorithm("RunPythonScript");
      alg->setLogging(false);
      alg->setPropertyValue("Code", script);
      return alg;
    }
    else
      return IAlgorithm_sptr();
  }
Exemplo n.º 12
0
/**
   char* upload_pick(void* data)

   If applicable, brings up a file chooser in which the user selects a file
   to upload for a particular task.  If the file is valid for the given action,
   returns the string to the full path filename, else returns NULL.
   Data is the load filter for the type of file as defined in LLFilePicker.
**/
const std::string upload_pick(void* data)
{
 	if( gAgentCamera.cameraMouselook() )
	{
		gAgentCamera.changeCameraToDefault();
		// This doesn't seem necessary. JC
		// display();
	}

	LLFilePicker::ELoadFilter type;
	if(data)
	{
		type = (LLFilePicker::ELoadFilter)((intptr_t)data);
	}
	else
	{
		type = LLFilePicker::FFLOAD_ALL;
	}

	LLFilePicker& picker = LLFilePicker::instance();
	if (!picker.getOpenFile(type))
	{
		LL_INFOS() << "Couldn't import objects from file" << LL_ENDL;
		return std::string();
	}

	
	const std::string& filename = picker.getFirstFile();
	std::string ext = gDirUtilp->getExtension(filename);

	//strincmp doesn't like NULL pointers
	if (ext.empty())
	{
		std::string short_name = gDirUtilp->getBaseFileName(filename);
		
		// No extension
		LLSD args;
		args["FILE"] = short_name;
		LLNotificationsUtil::add("NoFileExtension", args);
		return std::string();
	}
	else
	{
		//so there is an extension
		//loop over the valid extensions and compare to see
		//if the extension is valid

		//now grab the set of valid file extensions
		std::string valid_extensions = build_extensions_string(type);

		BOOL ext_valid = FALSE;
		
		typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
		boost::char_separator<char> sep(" ");
		tokenizer tokens(valid_extensions, sep);
		tokenizer::iterator token_iter;

		//now loop over all valid file extensions
		//and compare them to the extension of the file
		//to be uploaded
		for( token_iter = tokens.begin();
			 token_iter != tokens.end() && ext_valid != TRUE;
			 ++token_iter)
		{
			const std::string& cur_token = *token_iter;

			if (cur_token == ext || cur_token == "*.*")
			{
				//valid extension
				//or the acceptable extension is any
				ext_valid = TRUE;
			}
		}//end for (loop over all tokens)

		if (ext_valid == FALSE)
		{
			//should only get here if the extension exists
			//but is invalid
			LLSD args;
			args["EXTENSION"] = ext;
			args["VALIDS"] = valid_extensions;
			LLNotificationsUtil::add("InvalidFileExtension", args);
			return std::string();
		}
	}//end else (non-null extension)

	//valid file extension
	
	//now we check to see
	//if the file is actually a valid image/sound/etc.
	if (type == LLFilePicker::FFLOAD_WAV)
	{
		// pre-qualify wavs to make sure the format is acceptable
		std::string error_msg;
		if (check_for_invalid_wav_formats(filename,error_msg))
		{
			LL_INFOS() << error_msg << ": " << filename << LL_ENDL;
			LLSD args;
			args["FILE"] = filename;
			LLNotificationsUtil::add( error_msg, args );
			return std::string();
		}
	}//end if a wave/sound file

	
	return filename;
}
/*
 * データベース管理実行
 */
void ManageRecordedDataOnMySQL::run()
{
	try
	{
		typedef boost::char_separator<char> BOOST_CHAR_SEP;
		typedef boost::tokenizer< BOOST_CHAR_SEP > BOOST_TOKENIZER;

		boost::regex regexSelectPnPattern       ("select pn");
		boost::regex regexSelectPnWithNumPattern("select pn +[0-9]{1,9}");
		boost::regex regexSelectImPattern       ("select im");
		boost::regex regexSelectImWithNumPattern("select im +[0-9]{1,9}");
		boost::regex regexUpdateMidPattern      ("update pn +[0-9]{1,9} +[0-9]{1,9}");
		//boost::regex regexUpdateMidPattern      ("update pn +[0-9]{1,9} +rid +[0-9]{1,9}");
		//boost::regex regexUpdateMemoPattern     ("update pn +[0-9]{1,9} +memo .+");
		boost::regex regexDeletePattern         ("delete pn +[0-9]{1,9}");
		boost::regex regexHelpPattern           ("h");
		boost::regex regexExitPattern           ("q");

		DatabaseDAO databaseDAO;

		char inputLineAry[DatabaseDAO::MAX_LINE];
		BOOST_CHAR_SEP sep(" ");

		std::string inputLine;

		// 使い方表示
		this->printHelp();

		while (true)
		{
			std::cout << std::endl;
			std::cout << "> コマンドを入力してください(h :help)" << std::endl;
			std::cout << "> "; std::cin.getline(inputLineAry, DatabaseDAO::MAX_LINE);

			std::string inputLine = inputLineAry;

			boost::algorithm::trim(inputLine);

			/*
			 * select pn
			 */
			if (regex_match(inputLine, regexSelectPnPattern))
			{
				databaseDAO.select();
			}
			/*
			 * select pn XXX
			 */
			else if (regex_match(inputLine, regexSelectPnWithNumPattern))
			{
				BOOST_TOKENIZER tokens(inputLine, sep);
				boost::tokenizer< BOOST_CHAR_SEP >::iterator it = tokens.begin();

				it++; it++;
				int printNum = stoi(*it);

				databaseDAO.select(printNum);
			}
			/*
			 * select im
			 */
			else if (regex_match(inputLine, regexSelectImPattern))
			{
				databaseDAO.selectImitation();
			}
			/*
			 * select im XXX
			 */
			else if (regex_match(inputLine, regexSelectImWithNumPattern))
			{
				BOOST_TOKENIZER tokens(inputLine, sep);
				boost::tokenizer< BOOST_CHAR_SEP >::iterator it = tokens.begin();

				it++; it++;
				int printNum = stoi(*it);

				databaseDAO.selectImitation(printNum);
			}
			/*
			 * update pn RRR NNN
			 */
			else if (regex_match(inputLine, regexUpdateMidPattern))
			{
				BOOST_TOKENIZER tokens(inputLine, sep);
				boost::tokenizer< BOOST_CHAR_SEP >::iterator it = tokens.begin();

				it++; it++;
				std::string recId = *it;
				it++; 
				std::string newRecId = *it;

				// 事前エラーチェック
				if (databaseDAO.selectCount(DatabaseDAO::SUMMARY_TBL, "rec_id", recId) == 0)
				{
					std::cout << "更新元のrec_id(" + recId + ")が存在しません。処理終了します。" << std::endl;
					continue;
				}

				if (databaseDAO.selectCount(DatabaseDAO::SUMMARY_TBL, "rec_id", newRecId) != 0)
				{
					std::cout << "更新先のrec_id(" + newRecId + ")が" + DatabaseDAO::SUMMARY_TBL + "に既に存在します。処理終了します。" << std::endl;
					continue;
				}

				std::cout << "時系列データのレコード数は、" << databaseDAO.selectCount(DatabaseDAO::DETAIL_TBL, "rec_id", recId) << "件です。" << std::endl;


				char inputYN[DatabaseDAO::MAX_LINE];
				std::string inputKey = "";

				while (inputKey.compare("y") != 0 && inputKey.compare("n") != 0)
				{
					std::cout << "> rec_id=[" << recId << "] new rec_id=[" << newRecId << "]として更新しますが宜しいですか?(y/n):";
					std::cin.getline(inputYN, DatabaseDAO::MAX_LINE);
					inputKey = inputYN;
				}

				if (inputKey.compare("y") == 0)
				{
					int cnt;

					// 真似情報テーブル更新
					cnt = databaseDAO.updateAndDelete("UPDATE " + DatabaseDAO::IMITATION_TBL + " SET rec_id=" + newRecId + " WHERE rec_id=" + recId);
					std::cout << DatabaseDAO::IMITATION_TBL+"のrec_id="+recId+"のレコードを" << cnt << "件更新しました。" << std::endl;

					cnt = databaseDAO.updateAndDelete("UPDATE " + DatabaseDAO::IMITATION_TBL + " SET original_rec_id=" + newRecId + " WHERE original_rec_id=" + recId);
					std::cout << DatabaseDAO::IMITATION_TBL+"のoriginal_rec_id="+recId+"のレコードを" << cnt << "件更新しました。" << std::endl;


					// Perception Neuron動作サマリテーブル更新
					cnt = databaseDAO.updateAndDelete("UPDATE " + DatabaseDAO::SUMMARY_TBL + " SET rec_id=" + newRecId + " WHERE rec_id=" + recId);
					std::cout << DatabaseDAO::SUMMARY_TBL+"のレコードを" << cnt << "件更新しました。" << std::endl;


					// Perception Neuron動作時系列テーブル更新
//					std::cout << DatabaseDAO::DETAIL_TBL+"を更新中です。" << std::endl;
					cnt = databaseDAO.updateAndDelete("UPDATE " + DatabaseDAO::DETAIL_TBL + " SET rec_id=" + newRecId + " WHERE rec_id=" + recId);
					std::cout << DatabaseDAO::DETAIL_TBL+"のレコードを" << cnt << "件更新しました。" << std::endl;
				}
			}
			//メモの更新に関しては、真似情報テーブルにしても、Perception Neuron動作サマリテーブルにしても1行しかないため、MySQL Workbenchで直接編集してもらっても大差ない。
			///*
			// * update RRR memo NNN
			// */
			//else if (regex_match(inputLine, regexUpdateMemoPattern))
			//{
			//	BOOST_TOKENIZER tokens(inputLine, sep);
			//	boost::tokenizer< BOOST_CHAR_SEP >::iterator it = tokens.begin();

			//	it++; 
			//	std::string recId = *it;
			//	it++; it++;
			//	std::string newMemo;

			//	while(it!=tokens.end())
			//	{
			//		newMemo += (*it) + " ";
			//		it++;
			//	}
			//	boost::trim(newMemo);

			//	if (databaseDAO.selectCount(DatabaseDAO::SUMMARY_TBL, "rec_id", recId) == 0)
			//	{
			//		std::cout << "対象のrec_id(" + recId + ")が存在しません。処理終了します。" << std::endl;
			//		continue;
			//	}

			//	char inputYN[DatabaseDAO::MAX_LINE];
			//	std::string inputKey = "";

			//	while (inputKey.compare("y") != 0 && inputKey.compare("n") != 0)
			//	{
			//		std::cout << "> rec_id=[" << recId << "] new memo=[" << newMemo << "]として" + DatabaseDAO::SUMMARY_TBL + "を更新しますが宜しいですか?(y/n):";
			//		std::cin.getline(inputYN, DatabaseDAO::MAX_LINE);
			//		inputKey = inputYN;
			//	}

			//	if (inputKey.compare("y") == 0)
			//	{
			//		databaseDAO.updateAndDelete("UPDATE " + DatabaseDAO::SUMMARY_TBL + " SET memo='" + newMemo + "' WHERE rec_id=" + recId);
			//		std::cout << DatabaseDAO::SUMMARY_TBL+"のmemoを更新しました。" << std::endl;
			//	}
			//}
			/*
			 * delete pn RRR
			 */
			else if (regex_match(inputLine, regexDeletePattern))
			{
				BOOST_TOKENIZER tokens(inputLine, sep);
				boost::tokenizer< BOOST_CHAR_SEP >::iterator it = tokens.begin();

				it++; it++;
				std::string recId = *it;

				// 事前エラーチェック
				if (databaseDAO.selectCount(DatabaseDAO::SUMMARY_TBL, "rec_id", recId) == 0)
				{
					std::cout << "削除対象のrec_id(" + recId + ")が存在しません。処理終了します。" << std::endl;
					continue;
				}
				if (databaseDAO.selectCount(DatabaseDAO::IMITATION_TBL, "rec_id", recId) != 0)
				{
					std::cout << "削除対象のrec_id(" + recId + ")は真似情報テーブルで収録IDとして使用されています。処理終了します。" << std::endl;
					continue;
				}

				if (databaseDAO.selectCount(DatabaseDAO::IMITATION_TBL, "original_rec_id", recId) != 0)
				{
					std::cout << "削除対象のrec_id(" + recId + ")は真似情報テーブルで手本動作として使用されています。処理終了します。" << std::endl;
					continue;
				}

				std::cout << "時系列データのレコード数は、" << databaseDAO.selectCount(DatabaseDAO::DETAIL_TBL, "rec_id", recId) << "件です。" << std::endl;


				char inputYN[DatabaseDAO::MAX_LINE];
				std::string inputKey = "";

				while (inputKey.compare("y") != 0 && inputKey.compare("n") != 0)
				{
					std::cout << "> rec_id=[" << recId << "]のレコードを削除しますが宜しいですか?(y/n):";
					std::cin.getline(inputYN, DatabaseDAO::MAX_LINE);
					inputKey = inputYN;
				}

				if (inputKey.compare("y") == 0)
				{
					int cnt;

					// Perception Neuron動作サマリテーブル更新
					cnt = databaseDAO.updateAndDelete("DELETE FROM " + DatabaseDAO::SUMMARY_TBL + " WHERE rec_id=" + recId);
					std::cout << DatabaseDAO::SUMMARY_TBL+"のレコードを" << cnt << "件削除しました。" << std::endl;

					// Perception Neuron動作時系列テーブル更新
//					std::cout << DatabaseDAO::DETAIL_TBL+"を削除中です。" << std::endl;
					cnt = databaseDAO.updateAndDelete("DELETE FROM " + DatabaseDAO::DETAIL_TBL + " WHERE rec_id=" + recId);
					std::cout << DatabaseDAO::DETAIL_TBL+"のレコードを" << cnt << "件削除しました。" << std::endl;
				}
			}
			/*
			 * help
			 */
			else if (regex_match(inputLine, regexHelpPattern))
			{
				this->printHelp();
			}
			/*
			 * exit
			 */
			else if (regex_match(inputLine, regexExitPattern))
			{
				std::cout << "終了します";
				break;
			}
			/*
			 * FORMAT ERROR
			 */
			else
			{
				std::cout << "書式不正です" << inputLine << std::endl;
			}
		}
	}
	catch (std::exception& ex)
	{
		std::cout << ex.what() << std::endl;
	}
}
Exemplo n.º 14
0
bool Map::loadMap(std::string file, Player *player)
{
	int i,e;
	std::string linha; // temp
	
	Console::printf("Comecar a ler o ficheiro do mapa %s",file.c_str());
	
	std::ifstream ifs (file.c_str(), std::ios::in);
	if (ifs.fail ())
		return false;
	
	// ler tamanho
	ifs >> this->tamanho_mapa;
	
	// ler textura do tecto
	ifs >> this->tex_tecto;
	
	// ler textura do chao
	ifs >> this->tex_chao;
	
	// portas para a fisica, vamos por tudo a 0, as portas tem de falar ah fisica para actualizar o seu estado
	std::vector<std::vector <bool> > to_fisica_portas(this->tamanho_mapa, std::vector<bool>(this->tamanho_mapa));
	std::vector<std::vector <bool> > to_fisica_objectos(this->tamanho_mapa, std::vector<bool>(this->tamanho_mapa));
	std::vector<std::vector <bool> > fisica_guardas(this->tamanho_mapa, std::vector<bool>(this->tamanho_mapa));
	for(int i=0; i<to_fisica_portas.size(); i++)
		for(int e=0; e<to_fisica_portas.size(); e++){
			to_fisica_portas[i][e] = true;
			to_fisica_objectos[i][e] = false;
			fisica_guardas[i][e] = false;
		}
	Fisica::setGuardas(fisica_guardas);
	
	std::getline (ifs, linha);
	boost::char_separator<char> sep(",");
    for(i=0; i<this->tamanho_mapa; i++)
	{
		std::vector<int> codigos_mapa(this->tamanho_mapa-1);
		std::vector<int> linha_para_ir(this->tamanho_mapa-1);
		std::getline (ifs, linha);
		Tokenize(linha, codigos_mapa ,sep);
		linha_para_ir.clear();
		for(e=0; e<codigos_mapa.size(); e++){
			// stuff pro mapa
			//	1000 - texturas
			//	2000 - guardas
			//  3000 - portas
			//  4000 - items
			//  5000 - objectos mapa
			bool to_go = true;
			if(codigos_mapa[e]>1000 && codigos_mapa[e]<2000){
				// paredes -> enviar para o 
				linha_para_ir.push_back(codigos_mapa[e]);
				to_go = false;
			}else
			if(codigos_mapa[e]>3000 && codigos_mapa[e]<4000){
				// portas
				switch(codigos_mapa[e]){
					case 3001:
						// porta norte-sul
						this->addPorta(i,e,0, 0);
						break;
					case 3002:
						// porta oeste-este
						this->addPorta(i,e,0, 1);
						break;	
					case 3003:
						// porta norte-sul chave amarela
						this->addPorta(i,e,1, 0);
						break;
					case 3004:
						// porta oeste-este chave amarela
						this->addPorta(i,e,1, 1);
						break;
					case 3005:
						// porta norte-sul chave vermelha
						this->addPorta(i,e,2, 0);
						break;
					case 3006:
						// porta oeste-este chave vermelha
						this->addPorta(i,e,2, 1);
						break;
					default:
						Console::printf("Nao entendo este codigo de mapa porta: %d",codigos_mapa[e]);
						break;
				}
				if(codigos_mapa[e]>=3001 && codigos_mapa[e]<=3006){
					to_fisica_portas[i][e]=false;
				}
				
			}else
			if(codigos_mapa[e]>4000 && codigos_mapa[e]<5000){
				// items
				switch(codigos_mapa[e]){
					case 4001:
						// vida 15
						this->addItems(i,e,1);
						break;
					case 4002:
						// vida 25
						this->addItems(i,e,2);
						break;	
					case 4003:
						// vida 50
						this->addItems(i,e,3);
						break;
					case 4004:
						// gun 2
						this->addItems(i,e,4);
						break;
					case 4005:
						// gun 3
						this->addItems(i,e,5);
						break;
					case 4006:
						// gun 4
						this->addItems(i,e,6);
						break;
					case 4007:
						// ammo
						this->addItems(i,e,7);
						break;
					case 4008:
						// chave 1
						this->addItems(i,e,8);
						break;
					case 4009:
						// chave 2
						this->addItems(i,e,9);
						break;
					case 4010:
						// start player
						player->setInitialPosition(i*this->cube_size*2*-1 , e*this->cube_size*2*-1);
						Console::printf("Jogador vai começar em %f %f. No mapa tem %d %d", player->x, player->z, i, e);
						break;
					case 4011:
						// finish map
						this->fim_mapa_x = i;
						this->fim_mapa_y = e;
						break;
					case 4012:
						this->addItems(i,e,10);
						break;
					default:
						Console::printf("Nao entendo este codigo de mapa item: %d",codigos_mapa[e]);
						break;
				}
			}else
				if(codigos_mapa[e]>2000 && codigos_mapa[e]<3000){
					// guardas
					// addGuard(int x, int y, int type, int direction, bool movimento)
					switch(codigos_mapa[e]){
						// guarda 1 - soldado
						case 2001:
							// Norte / parado
							this->addGuard(i, e, 1, 1, false );
							break;
						case 2002:
							// Sul / parado
							this->addGuard(i, e, 1, 2, false );
							break;
						case 2003:
							// Este / parado
							this->addGuard(i, e, 1, 3, false );
							break;
						case 2004:
							// Oeste / parado
							this->addGuard(i, e, 1, 4, false );
							break;
						case 2005:
							// Norte / mover-se
							this->addGuard(i, e, 1, 1, true );
							break;
						case 2006:
							// Sul / mover-se
							this->addGuard(i, e, 1, 2, true );
							break;
						case 2007:
							// Este / mover-se
							this->addGuard(i, e, 1, 3, true );
							break;
						case 2008:
							// Oeste / mover-se
							this->addGuard(i, e, 1, 4, true );
							break;
							
						// guarda 2 - medium
						case 2009:
							// Norte / parado
							this->addGuard(i, e, 2, 1, false );
							break;
						case 2010:
							// Sul / parado
							this->addGuard(i, e, 2, 2, false );
							break;
						case 2011:
							// Este / parado
							this->addGuard(i, e, 2, 3, false );
							break;
						case 2012:
							// Oeste / parado
							this->addGuard(i, e, 2, 4, false );
							break;
						case 2013:
							// Norte / mover-se
							this->addGuard(i, e, 2, 1, true );
							break;
						case 2014:
							// Sul / mover-se
							this->addGuard(i, e, 2, 2, true );
							break;
						case 2015:
							// Este / mover-se
							this->addGuard(i, e, 2, 3, true );
							break;
						case 2016:
							// Oeste / mover-se
							this->addGuard(i, e, 2, 4, true );
							break;	
							
						// guarda 3 - intermedio
						case 2017:
							// Norte / parado
							this->addGuard(i, e, 3, 1, false );
							break;
						case 2018:
							// Sul / parado
							this->addGuard(i, e, 3, 2, false );
							break;
						case 2019:
							// Este / parado
							this->addGuard(i, e, 3, 3, false );
							break;
						case 2020:
							// Oeste / parado
							this->addGuard(i, e, 3, 4, false );
							break;
						case 2021:
							// Norte / mover-se
							this->addGuard(i, e, 3, 1, true );
							break;
						case 2022:
							// Sul / mover-se
							this->addGuard(i, e, 3, 2, true );
							break;
						case 2023:
							// Este / mover-se
							this->addGuard(i, e, 3, 3, true );
							break;
						case 2024:
							// Oeste / mover-se
							this->addGuard(i, e, 3, 4, true );
							break;
							
						// guarda 4 - dificil
						case 2025:
							// Norte / parado
							this->addGuard(i, e, 4, 1, false );
							break;
						case 2026:
							// Sul / parado
							this->addGuard(i, e, 4, 2, false );
							break;
						case 2027:
							// Este / parado
							this->addGuard(i, e, 4, 3, false );
							break;
						case 2028:
							// Oeste / parado
							this->addGuard(i, e, 4, 4, false );
							break;
						case 2029:
							// Norte / mover-se
							this->addGuard(i, e, 4, 1, true );
							break;
						case 2030:
							// Sul / mover-se
							this->addGuard(i, e, 4, 2, true );
							break;
						case 2031:
							// Este / mover-se
							this->addGuard(i, e, 4, 3, true );
							break;
						case 2032:
							// Oeste / mover-se
							this->addGuard(i, e, 4, 4, true );
							break;	
						
						// guarda 5 - robo
						case 2041:
							// Norte / parado
							this->addGuard(i, e, 5, 1, false );
							break;
						case 2042:
							// Sul / parado
							this->addGuard(i, e, 5, 2, false );
							break;
						case 2043:
							// Este / parado
							this->addGuard(i, e, 5, 3, false );
							break;
						case 2044:
							// Oeste / parado
							this->addGuard(i, e, 5, 4, false );
							break;
						case 2045:
							// Norte / mover-se
							this->addGuard(i, e, 5, 1, true );
							break;
						case 2046:
							// Sul / mover-se
							this->addGuard(i, e, 5, 2, true );
							break;
						case 2047:
							// Este / mover-se
							this->addGuard(i, e, 5, 3, true );
							break;
						case 2048:
							// Oeste / mover-se
							this->addGuard(i, e, 5, 4, true );
							break;	
						case 2049:
							// boss1
							this->addGuard(i, e, 6, 2, false);
							break;
							
						// direccoes dos guardas -> adicionar no mapa
						case 2033:
							to_go=false;
							linha_para_ir.push_back(2033);
							break;
						case 2034:
							to_go=false;
							linha_para_ir.push_back(2034);
							break;
						case 2035:
							to_go=false;
							linha_para_ir.push_back(2035);
							break;
						case 2036:
							to_go=false;
							linha_para_ir.push_back(2036);
							break;
						case 2037:
							to_go=false;
							linha_para_ir.push_back(2037);
							break;
						case 2038:
							to_go=false;
							linha_para_ir.push_back(2038);
							break;
						case 2039:
							to_go=false;
							linha_para_ir.push_back(2039);
							break;
						case 2040:
							to_go=false;
							linha_para_ir.push_back(2040);
							break;
							
						default:
							Console::printf("Nao entendo este codigo de mapa guarda: %d",codigos_mapa[e]);
							break;
							
					}
										
			}else 
				if(codigos_mapa[e]>5000 && codigos_mapa[e]<6000){
					// objectos decorativos para o mapa
					this->addObject(i,e,codigos_mapa[e],to_fisica_objectos);
				}else if(codigos_mapa[e]==0){
					// 0 -> sem nada
					linha_para_ir.push_back(codigos_mapa[e]);	
					to_go = false;
				}
				else{
					Console::printf("Nao entendo este codigo de mapa: %d",codigos_mapa[e]);
				}
			// tem de ser 0 pelo menos
			if(to_go)
				linha_para_ir.push_back(0);
		}
		this->map.push_back(linha_para_ir);
		
	}
	// enter a separar, floorcodes a seguir
	std::getline (ifs, linha);
    for(i=0; i<this->tamanho_mapa; ++i)
	{
		std::vector<int> codigos_floor(this->tamanho_mapa-1);
		std::getline (ifs, linha);
		Tokenize(linha, codigos_floor ,sep);
		this->floormap.push_back(codigos_floor);
	}
	
	// we're done
	// necessitamos de fornecer ah fisica as posicoes onde nos nao podemos avancar ate..
	// para isso vamos criar um vector de vector de booleanos que dizem que podemos ir ou nao podemos ir
	// percorremos o mapa. objectos agora sao calculados num vector ah parte e adicionados aqui ao vector que vai pra fisica
	std::vector<std::vector <bool> > to_fisica(this->tamanho_mapa, std::vector<bool>(this->tamanho_mapa));
	for(int i=0; i<this->map.size(); i++)
	{
		//to_fisica[i] = new std::vector<std::vector<bool> >(this->tamanho_mapa);
		for(e=0; e<this->map[i].size(); e++)
		{
			if(this->map[i][e]>1000 && this->map[i][e]<2000)
				to_fisica[i][e]=true;
			else {
				if(to_fisica_objectos[i][e])
					to_fisica[i][e]=true;
				else
					to_fisica[i][e]=false;
			}
		}
	}
	Fisica::setMap(to_fisica,this->cube_size);
	Fisica::setPortas(to_fisica_portas);
	
	// eh necessario agora actualizar os floorcodes de toda a gente e coisas
	// portas eh o + importante + guardas + o nosso player
	// cada guarda vai mudar de floorcode, ptt tal como o player necessita de receber novo floorcode
	player->floorcode = this->getFloorcode(player->z, player->x); // este n eh mt necessario pq no segundo frame ja vai tar certo
	for(int i=0; i<this->guardas.size(); i++)
	{
		this->guardas[i]->floorcode = this->getFloorcode(this->guardas[i]->z, this->guardas[i]->x);
	}
	for(int i=0; i<this->portas.size();i++)
	{
		if(this->portas[i]->direction==0)
		{
			this->portas[i]->floorcode1 = this->floormap[this->portas[i]->y][this->portas[i]->x-1];
			this->portas[i]->floorcode2 = this->floormap[this->portas[i]->y][this->portas[i]->x+1];
		}else
		{
			this->portas[i]->floorcode1 = this->floormap[this->portas[i]->y-1][this->portas[i]->x];
			this->portas[i]->floorcode2 = this->floormap[this->portas[i]->y+1][this->portas[i]->x];
		}
		//std::cout << "porta posicao " << this->portas[i]->x << " " << this->portas[i]->y << " floor:" << this->portas[i]->floorcode1 << " " << this->portas[i]->floorcode2 << std::endl;
	}
	
	Console::addLine("Mapa OK!");
	return true;
}
Exemplo n.º 15
0
/* texturas */
bool Map::loadTextures()
{
	std::string line;
	boost::char_separator<char> sep(" ");
	Console::addLine("Loading textures...");
	std::ifstream ifs ("data/textures/textures.def", std::ios::in);
	if (ifs.fail ()){
		Console::addLine("Erro a ler o ficheiro de texturas");
		return false;
	}
	
	// fazer o mapa das texturas que sao necessarias
	std::set<int> needed;
	for(int i=0; i< this->map.size(); ++i)
	{
		for(int e=0; e< this->map[i].size(); ++e){
			
		if(this->map[i][e]!=0)
			needed.insert(this->map[i][e]);
		}
	}
	needed.insert(this->tex_chao);
	needed.insert(this->tex_tecto);
	needed.insert(this->tex_porta);
	needed.insert(this->tex_porta_lado);
	needed.insert(this->tex_porta_chave1);
	needed.insert(this->tex_porta_lado_chave1);
	needed.insert(this->tex_porta_chave2);
	needed.insert(this->tex_porta_lado_chave2);
	
	while(!ifs.eof())
	{
		std::vector<std::string> t;
		int num;
		// ler linha
		std::getline(ifs, line);
		if(line.size()>1){
			// partir pq o primeiro eh o numero e segundo eh a path
			Tokenize(line, t, sep);
			num = StrtoInt(t[0]);
			// iterador para encontrar no needed
			set<int>::iterator it;
			it=needed.find(num);
			if(it!=needed.end()){
				Console::addLine("Loading texture "+t[0]+" in "+t[1]);
				Texture2D *tex = this->texMgr->load (t[1]);
				this->map_textures.insert (TexMap::value_type (num, tex));
			}
		}
	}
	
	// buscar texturas de portas
	this->textura_porta = this->map_textures.find(this->tex_porta)->second;
	this->textura_porta_lado = this->map_textures.find (this->tex_porta_lado)->second;
	this->textura_porta_chave1 = this->map_textures.find (this->tex_porta_chave1)->second;
	this->textura_porta_lado_chave1 = this->map_textures.find (this->tex_porta_lado_chave1)->second;
	this->textura_porta_chave2 = this->map_textures.find(this->tex_porta_chave2)->second;
	this->textura_porta_lado_chave2 = this->map_textures.find (this->tex_porta_lado_chave2)->second;
	
	Console::addLine("Ended loading textures");
	
	Console::addLine("Generating CallLists");
	this->createCallListMap();
	Console::addLine("Generating CallLists completed");
	return true;
}
Exemplo n.º 16
0
Set::Set(Function& f, CmpOp op, double eps) : root(new SetLeaf(YES)), Rn(f.nb_var()) {
	NumConstraint ctr(f,op);
	SepFwdBwd sep(ctr);
	sep.contract(*this,eps);
}
Exemplo n.º 17
0
Stage* Translate::makeReader(Options readerOptions)
{

    if (isDebug())
    {
        readerOptions.add<bool>("debug", true);
        boost::uint32_t verbosity(getVerboseLevel());
        if (!verbosity)
            verbosity = 1;
        
        readerOptions.add<boost::uint32_t>("verbose", verbosity);
        readerOptions.add<std::string>("log", "STDERR");
    }


    Stage* reader_stage = AppSupport::makeReader(readerOptions);
    
    Stage* final_stage(0);
    if (!m_bounds.empty() || !m_wkt.empty() || !m_output_srs.empty())
    {
        Stage* next_stage = reader_stage;
        
        Stage* crop_stage(0);
        Stage* reprojection_stage(0);

        if (!m_output_srs.empty())
        {
            readerOptions.add<std::string >("out_srs", m_output_srs.getWKT());

            boost::char_separator<char> sep(SEPARATORS);
            std::vector<double> offsets;
            tokenizer off_tokens(m_offsets, sep);
            for (tokenizer::iterator t = off_tokens.begin(); t != off_tokens.end(); ++t) {
                offsets.push_back(boost::lexical_cast<double>(*t));
            }

            std::vector<double> scales;
            tokenizer scale_tokens(m_scales, sep);
            for (tokenizer::iterator t = scale_tokens.begin(); t != scale_tokens.end(); ++t) {
                scales.push_back(boost::lexical_cast<double>(*t));
            }
            
            if (scales.size())
            {
                if (scales.size() <= 1)
                {
                    readerOptions.add<double >("scale_x", scales[0]);
                    
                }
                else if (scales.size() <= 2)
                {
                    readerOptions.add<double >("scale_x", scales[0]);
                    readerOptions.add<double >("scale_y", scales[1]);
                }
                else if (scales.size() <= 3)
                {
                    readerOptions.add<double >("scale_x", scales[0]);
                    readerOptions.add<double >("scale_y", scales[1]);
                    readerOptions.add<double >("scale_z", scales[2]);
                }
            }

            if (offsets.size())
            {
                if (offsets.size() <= 1)
                {
                    readerOptions.add<double >("offset_x", offsets[0]);
                    
                }
                else if (offsets.size() <= 2)
                {
                    readerOptions.add<double >("offset_x", offsets[0]);
                    readerOptions.add<double >("offset_y", offsets[1]);
                }
                else if (offsets.size() <= 3)
                {
                    readerOptions.add<double >("offset_x", offsets[0]);
                    readerOptions.add<double >("offset_y", offsets[1]);
                    readerOptions.add<double >("offset_z", offsets[2]);
                }
            }
            reprojection_stage = new pdal::filters::InPlaceReprojection(*next_stage, readerOptions);
            next_stage = reprojection_stage;
        }
        
        if (!m_bounds.empty() && m_wkt.empty())
        {
            readerOptions.add<pdal::Bounds<double> >("bounds", m_bounds);
            crop_stage = new pdal::filters::Crop(*next_stage, readerOptions);
            next_stage = crop_stage;
        } 
        else if (m_bounds.empty() && !m_wkt.empty())
        {
            std::istream* wkt_stream;
            try
            {
                wkt_stream = FileUtils::openFile(m_wkt);
                std::stringstream buffer;
                buffer << wkt_stream->rdbuf();

                m_wkt = buffer.str();
                FileUtils::closeFile(wkt_stream);
                
            } catch (pdal::pdal_error const&)
            {
                // If we couldn't open the file given in m_wkt because it 
                // was likely actually wkt, leave it alone
            }
            readerOptions.add<std::string >("polygon", m_wkt);
            crop_stage = new pdal::filters::Crop(*next_stage, readerOptions);
            next_stage = crop_stage;
        }
        
        final_stage = next_stage;
    }

    if (final_stage == 0) 
        final_stage = reader_stage;
    
    return final_stage;    

}
Exemplo n.º 18
0
Set::Set(const System& sys, double eps) : root(new SetLeaf(YES)), Rn(sys.nb_var) {
	SepFwdBwd sep(sys);
	sep.contract(*this,eps);
}
Exemplo n.º 19
0
int main(int argc, const char* argv[])
{
	puts("usage: asio_client [link num=1]");
	if (argc > 1)
		link_num = std::min(256, std::max(atoi(argv[1]), 1));

	puts("\nthis is a file client.");
	puts("type quit to end this client.");

	std::string str;
	st_service_pump service_pump;
	file_client client(service_pump);
	for (int i = 0; i < link_num; ++i)
	{
		BOOST_AUTO(client_ptr, client.create_client());
//		client_ptr->set_server_addr(SERVER_PORT, "::1"); //ipv6
//		client_ptr->set_server_addr(SERVER_PORT, "127.0.0.1"); //ipv4
		client_ptr->set_index(i);
		client.add_client(client_ptr);
	}

	service_pump.start_service();
	while(service_pump.is_running())
	{
		std::getline(std::cin, str);
		if (str == QUIT_COMMAND)
			service_pump.stop_service();
		else if (str == RESTART_COMMAND)
		{
			service_pump.stop_service();
			service_pump.start_service();
		}
		else if (str.size() > sizeof(REQUEST_FILE) &&
			!strncmp(REQUEST_FILE, str.data(), sizeof(REQUEST_FILE) - 1) &&
			isspace(str[sizeof(REQUEST_FILE) - 1]))
		{
			str.erase(0, sizeof(REQUEST_FILE));
			boost::char_separator<char> sep(" \t");
			boost::tokenizer<boost::char_separator<char> > tok(str, sep);
			for (BOOST_AUTO(iter, tok.begin()); iter != tok.end(); ++iter)
			{
				completed_client_num.store(0);
				file_size = 0;
				int begin_time = boost::get_system_time().time_of_day().total_seconds();
				if (client.at(0)->get_file(*iter))
				{
					for (int i = 1; i < link_num; ++i)
						client.at(i)->get_file(*iter);

					printf("transfer %s begin.\n", iter->data());
					unsigned percent = -1;
					while (completed_client_num.load() != (unsigned short) link_num)
					{
						boost::this_thread::sleep(boost::get_system_time() + boost::posix_time::milliseconds(50));
						if (file_size > 0)
						{
							__off64_t total_rest_size = client.get_total_rest_size();
							if (total_rest_size > 0)
							{
								unsigned new_percent =
									(unsigned) ((file_size - total_rest_size) * 100 / file_size);
								if (percent != new_percent)
								{
									percent = new_percent;
									printf("\r%u%%", percent);
									fflush(stdout);
								}
							}
						}
					}
					int used_time = boost::get_system_time().time_of_day().total_seconds() - begin_time;
					if (used_time > 0)
						printf("\r100%%\ntransfer %s end, speed: " __off64_t_format "kB/s.\n",
							iter->data(), file_size / 1024 / used_time);
					else
						printf("\r100%%\ntransfer %s end.\n", iter->data());
				}
			}
		}
		else
			client.at(0)->talk(str);
	}

	return 0;
}
Exemplo n.º 20
0
int Observable2D::ParseObservable2D(std::string& type, 
                                     boost::tokenizer<boost::char_separator<char> >* tok, 
                                     boost::tokenizer<boost::char_separator<char> >::iterator& beg, 
                                     std::string& infilename, 
                                     std::ifstream& ifile,
                                     int lineNo,
                                     int rank)
{
    if (infilename.find("\\/") == std::string::npos) filepath = infilename.substr(0, infilename.find_last_of("\\/") + 1);
    if (std::distance(tok->begin(), tok->end()) < 12) {
        setName(*beg);
        ++beg;
        if (std::distance(tok->begin(), tok->end()) < 4) {
            if(rank == 0) throw std::runtime_error("ERROR: lack of information on " + name + " in " + infilename + " at line number" + boost::lexical_cast<std::string>(lineNo));
            else sleep (2);
        }
        std::string toMCMC = *beg;
        if (toMCMC.compare("MCMC") == 0)
            setTMCMC(true);
        else if (toMCMC.compare("noMCMC") == 0)
            setTMCMC(false);
        else {
            if (rank == 0) throw std::runtime_error("ERROR: wrong MCMC flag in Observable2D" + name + " at line number:" + boost::lexical_cast<std::string>(lineNo) + " of file " + infilename + ".\n");
            else sleep(2);
        }
        
        ++beg;
        setDistr(*beg);
        if (distr.compare("file") == 0) {
            if (std::distance(tok->begin(), tok->end()) < 6) {
                if(rank == 0) throw std::runtime_error("ERROR: lack of information on "+ *beg + " in " + infilename);
                else sleep (2);
            }
            setFilename(filepath + *(++beg));
            setHistoname(*(++beg));
        }

        std::vector<double> min(2, 0.);
        std::vector<double> max(2, 0.);
        std::vector<double> ave(2, 0.);
        std::vector<double> errg(2, 0.);
        std::vector<double> errf(2, 0.);
        std::vector<std::string> thname(2, "");
        std::vector<std::string> label(2, "");
        std::vector<std::string> type2D(2, "");
        std::string line;
        size_t pos = 0;
        boost::char_separator<char> sep(" \t");
        for (int i = 0; i < 2; i++) {
            IsEOF = getline(ifile, line).eof();
            if (line.empty() || line.at(0) == '#') {
                if (rank == 0) throw std::runtime_error("ERROR: no comments or empty lines in Observable2D please! In file " + infilename + " at line number:" + boost::lexical_cast<std::string>(lineNo) + ".\n");
                else sleep(2);
            }
            lineNo++;
            boost::tokenizer<boost::char_separator<char> > mytok(line, sep);
            beg = mytok.begin();
            type2D[i] = *beg;
            if (type2D[i].compare("Observable") != 0 && type2D[i].compare("BinnedObservable") != 0 && type2D[i].compare("FunctionObservable") != 0) {
                if (rank == 0) throw std::runtime_error("ERROR: in line no." + boost::lexical_cast<std::string>(lineNo) + " of file " + infilename + ", expecting an Observable or BinnedObservable or FunctionObservable type here...\n");
                else sleep(2);
            }
            ++beg;
            thname[i] = *beg;
            ++beg;
            label[i] = *beg;
            while ((pos = label[i].find("~", pos)) != std::string::npos)
                label[i].replace(pos++, 1, " ");
            ++beg;
            min[i] = atof((*beg).c_str());
            ++beg;
            max[i] = atof((*beg).c_str());
            if (distr.compare("weight") == 0) {
                ++beg;
                ave[i] = atof((*beg).c_str());
                ++beg;
                errg[i] = atof((*beg).c_str());
                ++beg;
                errf[i] = atof((*beg).c_str());
                if (errg[i] == 0. && errg[i] == 0.) {
                    if (rank == 0) throw std::runtime_error("ERROR: The Gaussian and flat error in weight for " + name + " cannot both be 0. in the " + infilename + " file, line number:" + boost::lexical_cast<std::string>(lineNo) + ".\n");
                    else sleep(2);
                }
            } else if (distr.compare("noweight") == 0 || distr.compare("file") == 0) {
                if (type2D[i].compare("BinnedObservable") == 0 || type2D[i].compare("FunctionObservable") == 0) {
                    ++beg;
                    ++beg;
                    ++beg;
                }
            } else {
                if (rank == 0) throw std::runtime_error("ERROR: wrong distribution flag in " + name + " in file " + infilename + ".\n");
                else sleep(2);
            }
            if (type2D[i].compare("BinnedObservable") == 0) {
                ++beg;
                bin_min[i] = atof((*beg).c_str());
                ++beg;
                bin_max[i] = atof((*beg).c_str());
            } else if (type2D[i].compare("FunctionObservable") == 0) {
                ++beg;
                bin_min[i] = atof((*beg).c_str());
                ++beg;
            }
        }
        setObsType(type2D[0]);
        obsType2 = type2D[1];
        setThname(thname[0]);
        thname2 = thname[1];
        setLabel(label[0]);
        label2 = label[1];
        setMin(min[0]);
        min2 = min[1];
        setMax(max[0]);
        max2= max[1];
        setAve(ave[0]);
        ave2 = ave[1];
        setErrg(errg[0]);
        errg2 = errg[1];
        setErrf(errf[0]);
        errf2 = errf[1];
        if (distr.compare("file") == 0) {
            setLikelihoodFromHisto(filename, histoname);
            if (rank == 0) std::cout << "added input histogram " << filename << "/" << histoname << std::endl;
        }
        return lineNo;
    } else {
        beg = ParseObservable(type, tok, beg, filepath, filename, rank);
        ++beg;
        std::string distr = *beg;
        if (distr.compare("file") == 0) {
            if (std::distance(tok->begin(), tok->end()) < 14) {
                if (rank == 0) throw std::runtime_error("ERROR: lack of information on " + *beg + " in " + infilename + ".\n");
                else sleep(2);
            }
            setFilename(filepath + *(++beg));
            setHistoname(*(++beg));
            setLikelihoodFromHisto(filename, histoname);
            if (rank == 0) std::cout << "added input histogram " << filename << "/" << histoname << std::endl;
        } else if (distr.compare("noweight") == 0) {
        } else { 
            if (rank == 0) throw std::runtime_error("ERROR: wrong distribution flag in " + name);
            else sleep(2);
        }
        setDistr(distr);
        ++beg;
        thname2 = *beg;
        ++beg;
        std::string label = *beg;
        size_t pos = 0;
        while ((pos = label.find("~", pos)) != std::string::npos)
            label.replace(pos, 1, " ");
        label2 = label;
        ++beg;
        min2 = atof((*beg).c_str());
        ++beg;
        max2 = atof((*beg).c_str());
        ++beg;
        if (beg != tok->end())
            if (rank == 0) std::cout << "WARNING: unread information in observable2D " << name << std::endl;
        return lineNo;
    }
}
Exemplo n.º 21
0
int main()
{
    std::string name = "BrickyBot";
    std::string source = ":BrickyBot!~BrickyBot@BrickHouse";
    std::string server = "irc.p2p-network.net";
    std::string port = "6667";
    std::string channel = "#MyLittleAlcoholic";
    bool auto_reconnect = false;
    
    // Load and parse the options file for configurability
    std::vector<std::pair<std::string, std::string> > options = get_pairs_from_file("data/options");
    for (std::vector<std::pair<std::string, std::string> >::iterator options_it = options.begin(); options_it != options.end(); options_it++)
    {
        if ((*options_it).first == "name") name = (*options_it).second;
        else if ((*options_it).first == "source") source = (*options_it).second;
        else if ((*options_it).first == "server") server = (*options_it).second;
        else if ((*options_it).first == "port") port = (*options_it).second;
        else if ((*options_it).first == "channel") channel = (*options_it).second;
        else if ((*options_it).first == "auto_reconnect" && (*options_it).second == "true") auto_reconnect = true;
        else if ((*options_it).first == "debug" && (*options_it).second == "true") debug = true;
    }

    // initialize vectors    
    std::vector<std::string> operators = get_vector_from_file("data/operators");
    std::vector<std::string> episodes = get_vector_from_file("data/pony_episodes");
    std::vector<boost::tuple<std::string, uint16_t, time_t> > drinks = get_counts_from_tuples(get_tuples_from_file("data/drinkcount"));
    std::vector<std::pair<std::string, std::string> > responses = get_pairs_from_file("data/responses");
    std::vector<boost::tuple<std::string, uint16_t, time_t> > hits = get_counts_from_tuples(get_tuples_from_file("data/hitcount"));
    
    // set up signal handlers
    signal(SIGABRT, handleSignal);
    signal(SIGINT, handleSignal);
    signal(SIGTERM, handleSignal);
    
    try
    {
        // networking shit
        boost::asio::io_service io_service;
        boost::asio::ip::tcp::resolver resolver(io_service);
        boost::asio::ip::tcp::resolver::query query(server, port);
        boost::asio::ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
        boost::asio::ip::tcp::socket socket(io_service);
        boost::asio::connect(socket, endpoint_iterator);

        boost::system::error_code ignored_error;
        uint64_t num_in = 0;
        bool first_ping = false;
        bool in_channel = false;
        
        while (running)
        {
            // Get a message from the server
            boost::array<char, 1024> buf;
            boost::system::error_code error;
            size_t len = socket.read_some(boost::asio::buffer(buf), error);

            // Check for an error or a closed connection
            if (error == boost::asio::error::eof)
            {
                // Connection closed cleanly by peer
                running = false;
            }
            else if (error)
            {
                // Some other dipshit error
                throw boost::system::system_error(error);
            }
            else
            {
                // No error. Parse the message.
                // First form a string from the char array
                std::string message_str(buf.begin(), buf.begin() + len);

                // Tokenize the string for multiple messages
                boost::char_separator<char> msg_sep("\r\n");
                boost::tokenizer<boost::char_separator<char> > msg_tok(message_str, msg_sep);

                // Place all the tokens into a vector
                std::vector<std::string> message_strings;
                for (boost::tokenizer<boost::char_separator<char> >::iterator it = msg_tok.begin(); it != msg_tok.end(); ++it)
                    message_strings.push_back(*it);

                // Process each message
                for (uint16_t i = 0; i < message_strings.size(); ++i)
                {
                    dbgPrint("incoming: %s\n", message_strings[i].c_str());

                    // Tokenize the message
                    boost::char_separator<char> sep(" ");
                    boost::tokenizer<boost::char_separator<char> > tok(message_strings[i], sep);
                    std::vector<std::string> tokens;
                    for (boost::tokenizer<boost::char_separator<char> >::iterator it = tok.begin(); it != tok.end(); ++it)
                        tokens.push_back(*it);

                    // Now process the message.
                    if (tokens[0] == "PING")
                    {
                        // Build a new string consisting of PONG followed by everything else
                        std::string send_str = "PONG";

                        for (uint16_t j = 1; j < tokens.size(); ++j)
                            send_str += " " + tokens[j];

                        // Add the carriage return and newline, as per IRC protocol
                        send_str += "\r\n";

                        // Send it to the server
                        boost::asio::write(socket, boost::asio::buffer(send_str), ignored_error);

                        first_ping = true;
                    }

                    num_in++;

                    
                    // Stupid IRC bullshit. Send some info after getting three messages.
                    if (num_in == 3)
                    {
                        // Send the USER/NICK message pair after 3 receives
                        // (What a w***e; receieves three times before telling its name...)
                        std::string nick_msg_str = "NICK " + name + "\r\n";
                        std::string user_msg_str = "USER " + name + " 0 * :" + name + "\r\n";
                        boost::asio::write(socket, boost::asio::buffer(nick_msg_str), ignored_error);
                        boost::asio::write(socket, boost::asio::buffer(user_msg_str), ignored_error);
                    }

                    // Join the channel when appropriate
                    if (first_ping && !in_channel)
                    {
                        // Connect after being pinged
                        std::string send_str = source + " JOIN :" + channel + "\r\n";
                        boost::asio::write(socket, boost::asio::buffer(send_str), ignored_error);

                        // wait a bit...
                        //boost::this_thread::sleep(boost::posix_time::milliseconds(1000));

                        in_channel = true;
                    }

                    // Bot is in the channel. The interesting shit is here
                    if (in_channel)
                    {
                        // Used to send messages
                        std::string send_str;

                        if (tokens[1] == "PRIVMSG") // gettin a message
                        {
                            // Get the name of the sending user
                            boost::char_separator<char> user_tok_sep(":!");
                            boost::tokenizer<boost::char_separator<char> > user_tok(tokens[0], user_tok_sep);
                            std::string sending_user = *(user_tok.begin());
                            
                            // Check whether the sending user is an operator
                            bool user_is_operator = (std::find(operators.begin(), operators.end(), sending_user) != operators.end());
                            
                            // Find the start of the text
                            uint16_t chat_start_index = 2;
                            while (tokens[chat_start_index][0] != ':') ++chat_start_index;
                            
                            // Add the first token (the start of the message) and remove the leading colon
                            std::string chat_text = tokens[chat_start_index];
                            chat_text.erase(0, 1);
                            
                            for (uint16_t chat_text_index = chat_start_index + 1; chat_text_index < tokens.size(); ++chat_text_index)
                            {
                                chat_text += " " + tokens[chat_text_index];
                            }

                            boost::char_separator<char> chat_sep(" ");
                            boost::tokenizer<boost::char_separator<char> > chat_tok(chat_text, chat_sep);
                            std::string chat_command = chat_text;
                            
                            int16_t chat_arg = -1;
                            
                            if (std::distance(chat_tok.begin(), chat_tok.end()) > 0)
                            {
                                chat_command =  *(chat_tok.begin());
                                
                                boost::tokenizer<boost::char_separator<char> >::iterator chat_tok_it = chat_tok.begin();
                                if (++chat_tok_it != chat_tok.end())
                                {
                                    try
                                    {
                                        chat_arg = boost::lexical_cast<int16_t>(*chat_tok_it);
                                    }
                                    catch (boost::bad_lexical_cast &)
                                    {
                                        BB
                                    }
                                }
                                
                                if (chat_arg < -1) chat_arg = -1;
                            }
                                
                            /*
                             *    This is where the bot actually does interesting things.
                             *    ---AT THIS INDENTATION, MOTHERFUCKERS.---
                             */
                            
                            // quit if an operator tells it to
                            if (boost::iequals(chat_text, name + ": quit") && user_is_operator)
                            {
                                send_str = source + " QUIT " + channel + " :quitting\r\n";
                                boost::asio::write(socket, boost::asio::buffer(send_str), ignored_error);
                                running = false;
                            }
                            
                            // reload operators file when ordered to by an operator
                            if (boost::iequals(chat_text, name + ": reload ops") && user_is_operator)
                            {
                                operators =  get_vector_from_file("data/operators");
                                send_str = source + " PRIVMSG " + channel + " :Reloaded operators.\r\n";
                                boost::asio::write(socket, boost::asio::buffer(send_str), ignored_error);
                            }

                            // .poni
                            if (boost::iequals(chat_command, ".poni"))
                            {
                                // pick a random episode
                                int episode = rand() % episodes.size();
                                send_str = source + " PRIVMSG " + channel + " :" + episodes[episode] + "\r\n";
                                boost::asio::write(socket, boost::asio::buffer(send_str), ignored_error);
                                
                            }
                            
                            // reload mlp episode list when ordered to by an operator
                            if (boost::iequals(chat_text, name + ": reload poni") && user_is_operator)
                            {
                                episodes =  get_vector_from_file("data/pony_episodes");
                                send_str = source + " PRIVMSG " + channel + " :Reloaded poni.\r\n";
                                boost::asio::write(socket, boost::asio::buffer(send_str), ignored_error);
                            }
                            
                            if (boost::iequals(chat_command, ".shot") || boost::iequals(chat_command, ".drink"))
                            {
                                // Find the user in the vector
                                int32_t user_index = get_user_index_in_counts(sending_user, drinks);
                                uint16_t current_drink_count;
                                
                                // If the user is already in the vector, increment the count and update the time.
                                // Otherwise, add the user and initialize them.
                                if (user_index != -1)
                                {
                                    time_t rawtime;
                                    time (&rawtime);
                                    
                                    drinks[user_index].get<1>() += chat_arg == -1? 1: chat_arg; 
                                    current_drink_count = boost::get<1>(drinks[user_index]);
                                    drinks[user_index].get<2>() = rawtime;
                                    // drinks[user_index].second += chat_arg == -1? 1: chat_arg;
                                    // current_drink_count = drinks[user_index].second;
                                }
                                else
                                {  ///////// Found a bug: if the user isn't in the array and adds more than one, it will only count as one, but
                                   ///////// it will say that it added however many it said it would. or so I think. I'm pretty drunk right now.
                                   time_t rawtime;
                                   time (&rawtime);
                                
                                   drinks.push_back(boost::make_tuple(sending_user, 1, rawtime));
                                    //drinks.push_back(std::make_pair(sending_user, 1));
                                    current_drink_count = chat_arg == -1? 1 : chat_arg;
                                }
                                
                                
                                // Write the changes to disk
                                write_counts(drinks, "data/drinkcount");
                                
                                // Convert the number of drinks into a string
                                std::ostringstream num_to_str;
                                num_to_str << current_drink_count;
                                std::string drink_count_str = num_to_str.str();
                                
                                // send the current number of drinks
                                send_str = source + " PRIVMSG " + channel + " :" + sending_user + ": you are now at " +
                                        drink_count_str + " drink(s).\r\n";
                                boost::asio::write(socket, boost::asio::buffer(send_str), ignored_error);
                            }
                            
                            if (boost::iequals(chat_command, ".weed") || boost::iequals(chat_command, ".hit") || boost::iequals(chat_command, ".toke"))
                            {
                                // Find the user in the vector
                                int32_t user_index = get_user_index_in_counts(sending_user, hits);
                                uint16_t current_hit_count;
                                
                                // If the user is already in the vector, increment the count.
                                // Otherwise, add the user and initialize them with one drink.
                                if (user_index != -1)
                                {
                                    time_t rawtime;
                                    time (&rawtime);  
                                    
                                    hits[user_index].get<1>() += chat_arg == -1? 1: chat_arg;
                                    current_hit_count = boost::get<1>(hits[user_index]);
                                    hits[user_index].get<2>() = rawtime;
                                    //hits[user_index].second += chat_arg == -1? 1: chat_arg;
                                    //current_hit_count = hits[user_index].second;
                                }
                                else
                                {  ///////// Found a bug: if the user isn't in the array and adds more than one, it will only count as one, but
                                   ///////// it will say that it added however many it said it would. or so I think. I'm pretty drunk right now.
                                   time_t rawtime;
                                   time (&rawtime);  
                                   
                                    hits.push_back(boost::make_tuple(sending_user, 1, rawtime));
                                    //hits.push_back(std::make_pair(sending_user, 1));
                                    current_hit_count = chat_arg == -1? 1: chat_arg;
                                }

                                
                                // Write the changes to disk
                                 write_counts(hits, "data/hitcount");
                                
                                // Convert the number of drinks into a string
                                std::ostringstream num_to_str;
                                num_to_str << current_hit_count;
                                std::string hit_count_str = num_to_str.str();
                                
                                // send the current number of drinks
                                send_str = source + " PRIVMSG " + channel + " :" + sending_user + ": you are now at " +
                                        hit_count_str + " hit(s).\r\n";
                                boost::asio::write(socket, boost::asio::buffer(send_str), ignored_error);                                
                            }
                            
                            if (boost::iequals(chat_command, ".reset"))
                            {
                                ////////////////// Reset Drink Count
                                
                                // Find the user in the vector
                                int32_t user_index = get_user_index_in_counts(sending_user, drinks);
                                
                                // set that user's shot/drink count to zero
                                if (user_index != -1)
                                {
                                    //drinks[user_index].second = 0;
                                    drinks[user_index].get<1>() = 0;
                                }
                                else
                                {
                                    time_t rawtime;
                                    time(&rawtime);
                                    //drinks.push_back(std::make_pair(sending_user, 0));
                                    drinks.push_back(boost::make_tuple(sending_user, 0, rawtime)); 
                                }
                                
                                // write changes to disk
                                write_counts(drinks, "data/drinkcount");
                                
                                ////////////////// Reset Hit Count
                                
                                // Find the user in the vector
                                user_index = get_user_index_in_counts(sending_user, hits);
                                
                                // set that user's hit count to zero
                                if (user_index != -1)
                                {
                                    //hits[user_index].second = 0;
                                    hits[user_index].get<1>() = 0;
                                }
                                else
                                {
                                    time_t rawtime;
                                    time(&rawtime);
                                    //hits.push_back(std::make_pair(sending_user, 0));
                                    hits.push_back(boost::make_tuple(sending_user, 0, rawtime));
                                }
                                
                                // write changes to disk
                                write_counts(hits, "data/hitcount");
                                
                                // send acknowledgement
                                send_str = source + " PRIVMSG " + channel + " :" + sending_user + ": you are now at 0 drinks and 0 hits.\r\n";
                                boost::asio::write(socket, boost::asio::buffer(send_str), ignored_error);
                            }
                            
                            
                            
                            // Print user's counts
                            if (boost::iequals(chat_command, ".count"))
                            {
                                // Find the user in the vector
                                int32_t user_index = get_user_index_in_counts(sending_user, drinks);
                                
                                send_str = source + " PRIVMSG " + channel + " :" + sending_user + ": you are now at ";
                                
                                if (user_index != -1)
                                {
                                    std::ostringstream num_to_str;
                                    //num_to_str << drinks[user_index].second;
                                    num_to_str << drinks[user_index].get<1>();
                                    send_str += num_to_str.str();
                                }
                                else
                                {
                                    send_str += "0";
                                }

                                send_str += " drinks and ";
                                
                                user_index = get_user_index_in_counts(sending_user, hits);
                                
                                if (user_index != -1)
                                {
                                    std::ostringstream num_to_str;
                                    //num_to_str << hits[user_index].second;
                                    num_to_str << hits[user_index].get<1>();
                                    send_str += num_to_str.str();
                                }
                                else
                                {
                                    send_str += "0";
                                }
                                
                                send_str += " hits.\r\n";

                                
                                boost::asio::write(socket, boost::asio::buffer(send_str), ignored_error);
                            }
                            
                            // Print the time of the user's last count update
                            if (boost::iequals(chat_command, ".lastdrink"))
                            {
                                int32_t user_index = get_user_index_in_counts(sending_user, drinks);
                                
                                send_str = source + " PRIVMSG " + channel + " :" + sending_user + ": ";
                                
                                if (user_index != -1)
                                {
                                    if (boost::get<1>(drinks[user_index]) > 0)
                                    {
                                        send_str += "Last counted drink was at " + std::string(ctime(&(boost::get<2>(drinks[user_index])))) + ".\r\n";
                                    }
                                    else
                                    {
                                        send_str += "You have no counted drinks.\r\n";
                                    }
                                }
                                else
                                {
                                    send_str += "You have no counted drinks.\r\n";
                                }
                                
                                boost::asio::write(socket, boost::asio::buffer(send_str), ignored_error);
                                
                            }
                            if (boost::iequals(chat_command, ".lasthit"))
                            {
                                int32_t user_index = get_user_index_in_counts(sending_user, drinks);
                                
                                send_str = source + " PRIVMSG " + channel + " :" + sending_user + ": ";
                                
                                if (user_index != -1)
                                {
                                    if (boost::get<1>(hits[user_index]) > 0)
                                    {
                                        send_str += "Last counted hit was at " + std::string(ctime(&(boost::get<2>(hits[user_index])))) + ".\r\n";
                                    }
                                    else
                                    {
                                        send_str += "You have no counted hits.\r\n";
                                    }
                                }
                                else
                                {
                                    send_str += "You have no counted hits.\r\n";
                                }
                                
                                boost::asio::write(socket, boost::asio::buffer(send_str), ignored_error);
                            }
                            
                            
                            // Print the channel's total number of recorded drinks
                            if (boost::iequals(chat_command, ".chtotal"))
                            {
                                uint32_t total = 0;
                                //for (std::vector<std::pair<std::string, uint16_t> >::iterator drinks_it = drinks.begin(); drinks_it != drinks.end(); drinks_it++)
                                for (std::vector<boost::tuple<std::string, uint16_t, time_t> >::iterator drinks_it = drinks.begin(); drinks_it != drinks.end(); drinks_it++)
                                {
                                    //total += (*drinks_it).second;
                                    total += boost::get<1>(*drinks_it);
                                }
                                
                                std::ostringstream num_to_str;
                                num_to_str << total;
                                send_str = source + " PRIVMSG " + channel + " :Total drinks: " + num_to_str.str() + "; ";
                                
                                total = 0;
                                //for (std::vector<std::pair<std::string, uint16_t> >::iterator hits_it = hits.begin(); hits_it != hits.end(); hits_it++)
                                for (std::vector<boost::tuple<std::string, uint16_t, time_t> >::iterator hits_it = hits.begin(); hits_it != hits.end(); hits_it++)
                                {
                                    //total += (*hits_it).second;
                                    total += boost::get<1>(*hits_it);
                                }
                                
                                std::ostringstream num_to_str2;
                                num_to_str2 << total;
                                send_str += "Total hits: " + num_to_str2.str() + "\r\n";
                                
                                boost::asio::write(socket, boost::asio::buffer(send_str), ignored_error);
                            }
                            
                            // Send all the drink info
                            if (boost::iequals(chat_command, ".chdrinks"))
                            {
                                send_str = source + " PRIVMSG " + channel + " :Channel Drinks: ";
                                
                                for (uint16_t i = 0; i < drinks.size(); i++)
                                {
                                    //if (drinks[i].second > 0)
                                    if (drinks[i].get<1>() > 0)
                                    {
                                        std::ostringstream num_to_str;
                                        //num_to_str << drinks[i].second;
                                        num_to_str <<  boost::get<1>(drinks[i]);
                                        //send_str += drinks[i].first + ": " + num_to_str.str() + ". ";
                                        send_str += boost::get<0>(drinks[i]) + ": " + num_to_str.str() + ". ";
                                    }
                                }
                                
                                send_str += "\r\n";
                                
                                boost::asio::write(socket, boost::asio::buffer(send_str), ignored_error);
                            }

                            // Send all the hits info
                            if (boost::iequals(chat_command, ".chhits"))
                            {
                                send_str = source + " PRIVMSG " + channel + " :Channel Hits: ";
                                
                                for (uint16_t i = 0; i < hits.size(); i++)
                                {
                                    //if (hits[i].second > 0)
                                    if (hits[i].get<1>() > 0)
                                    {
                                        std::ostringstream num_to_str;
                                        //num_to_str << hits[i].second;
                                        num_to_str << boost::get<1>(drinks[i]);
                                        //send_str += hits[i].first + ": " + num_to_str.str() + ". ";
                                        send_str += boost::get<0>(drinks[i]) + ": " + num_to_str.str() + ". ";
                                    }
                                }
                                
                                send_str += "\r\n";
                                
                                boost::asio::write(socket, boost::asio::buffer(send_str), ignored_error);
                            }
                             
                            // Operator command to reset all drinks
                            if (boost::iequals(chat_text, name + ": reset all drinks") && user_is_operator)
                            {
                                for (uint16_t i = 0; i < drinks.size(); i++)
                                {
                                    drinks[i].get<1>() = 0;
                                    // drinks[i].second = 0;
                                }
                                
                                write_counts(drinks, "data/drinkcount");
                                
                                send_str = source + " PRIVMSG " + channel + " :All drinks were reset.\r\n";
                                boost::asio::write(socket, boost::asio::buffer(send_str), ignored_error);
                            }
                            
                            // Operator command to reset all hits
                            if (boost::iequals(chat_text, name + ": reset all hits") && user_is_operator)
                            {
                                for (uint16_t i = 0; i < hits.size(); i++)
                                {
                                    //hits[i].second = 0;
                                    hits[i].get<1>() = 0;
                                }
                                
                                write_counts(hits, "data/hitcount");
                                
                                send_str = source + " PRIVMSG " + channel + " :All hits were reset.\r\n";
                                boost::asio::write(socket, boost::asio::buffer(send_str), ignored_error);
                            }
                            
                            // Operator command to reset both counters
                            if (boost::iequals(chat_text, name + ": reset all") && user_is_operator)
                            {
                                for (uint16_t i = 0; i < drinks.size(); i++)
                                {
                                    //drinks[i].second = 0;
                                    drinks[i].get<1>() = 0;
                                }
                                
                                write_counts(drinks, "data/drinkcount");
                                
                                
                                for (uint16_t i = 0; i < hits.size(); i++)
                                {
                                    //hits[i].second = 0;
                                    hits[i].get<1>() = 0;
                                    
                                }
                                
                                write_counts(hits, "data/hitcount");   
                                
                                send_str = source + " PRIVMSG " + channel + " :All drinks and hits were reset.\r\n";
                                boost::asio::write(socket, boost::asio::buffer(send_str), ignored_error);
                            }
                            
                            // modifying responses while running
                            if (boost::iequals(chat_text, name + ": reload responses") && user_is_operator)
                            {
                                responses = get_pairs_from_file("data/responses");
                                send_str = source + " PRIVMSG " + channel + " :Reloaded responses.\r\n";
                                boost::asio::write(socket, boost::asio::buffer(send_str), ignored_error);
                            }
                            
                            // simple response commands
                            for (std::vector<std::pair<std::string, std::string> >::iterator resp_it = responses.begin(); resp_it != responses.end(); resp_it++)
                            {
                                if (boost::iequals(chat_command, (*resp_it).first))
                                {
                                    send_str = source + " PRIVMSG " + channel + " :" + (*resp_it).second + "\r\n";
                                    boost::asio::write(socket, boost::asio::buffer(send_str), ignored_error);
                                }
                            }
                        }
                        else if (tokens[1] == "KICK" && tokens[3] == name) // The bot was kicked
                        {
                            boost::char_separator<char> user_tok_sep(":!");
                            boost::tokenizer<boost::char_separator<char> > user_tok(tokens[0], user_tok_sep);
                            std::string sending_user = *(user_tok.begin());
                            bool user_is_operator = (std::find(operators.begin(), operators.end(), sending_user) != operators.end());

                            if (auto_reconnect && !user_is_operator)
                            {
                                // rejoin the channel
                                std::string send_str = source + " JOIN :" + channel + "\r\n";
                                boost::asio::write(socket, boost::asio::buffer(send_str), ignored_error);
                            }
                            else
                            {
                                // don't rejoin; just quit
                                send_str = source + " QUIT " + channel + " :quitting\r\n";
                                boost::asio::write(socket, boost::asio::buffer(send_str), ignored_error);
                                running = false;
                            }
                        }
                    }
                }
            }
Exemplo n.º 22
0
static String generateTransitionTable (const AbnfRule & rule, bool isOrigRule, const AbnfGenContext::Options & options)
{
	String r;
	CWT_UNUSED(options);

	CWT_ASSERT(rule.elements().size() == 1);
	CWT_ASSERT(! (rule.elements())[0]->isScalar()); // one of containers

	const AbnfElement * inner = (rule.elements())[0];
	const Vector<AbnfElement * > & elements = dynamic_cast<const AbnfContainer *>(inner)->elements();
	AbnfElementType innerType = inner->type();

	String c_rulename(__c_name(rule.name()));
	String actionArgsText(String("& ACTION_ARGS[Token_") + c_rulename + "]");
	int state_next = -1;
	int state_fail = -1;
	int status = FSM_NORMAL;

	CWT_ASSERT_X(innerType == Abnf_Altern
			|| innerType == Abnf_Concat
			|| innerType == Abnf_Rpt
		, String(_Fr("ABNF rule list is corrupted or elements may be added through the bypass: %d") % innerType).c_str() );

	if (innerType == Abnf_Altern) {
		state_fail = 0;
		state_next = -1;
		status = FSM_ACCEPT;
	} else { // Abnf_Concat || Abnf_Rpt
		state_next = 0;
		state_fail = -1;
		status = FSM_NORMAL;
	}

	r << "/*" << String::EndOfLine;
	r << INDENT << rule.toString() << String::EndOfLine;
	r << "*/" << String::EndOfLine;
	r << "Transitions::Type Transitions::" << TRANSITION_TABLE_NAME(c_rulename) << "[] = {" << String::EndOfLine;
	String sep("  ");

	size_t nelements = calculateNonComments(elements);

	if (isOrigRule) {
		r << INDENT << sep
		  << generateTransition(1, -1, "FSM_MATCH_NOTHING", FSM_NORMAL, "Transitions::on_begin", actionArgsText)
		  << String::EndOfLine;

		// begin action
		if (innerType == Abnf_Altern) {
			++state_fail;
			state_next = nelements + 2;
		} else { // Abnf_Concat || Abnf_Rpt
			++state_next;
			state_fail = nelements + 2;
		}

		sep = String(", ");
	}

	Vector<AbnfElement *>::const_iterator it = elements.begin();
	Vector<AbnfElement *>::const_iterator itEnd = elements.end();

	while (it != itEnd) {
		const AbnfElement * element = *it;
		AbnfElementType t = element->type();

		if (t == Abnf_Comment) {
			++it;
			continue;
		}

		if (innerType == Abnf_Altern) {
			++state_fail;
		} else { // Abnf_Concat || Abnf_Rpt
			++state_next;
		}

/*
		if (t == Abnf_CharVal && options.compactCharValues) {
			// Compact char values
			String s = compactCharValues(it, itEnd);
			if (s.isEmpty()) {
				s = dynamic_cast<const AbnfScalar *>(element)->value();
				r << INDENT << sep
					<< generateTransition(state_next, state_fail
							, String("FSM_MATCH_STR(_u8(\"") + s + "\"))"
							, status)
					<< String::EndOfLine;
				++it;
			} else {
				r << INDENT << sep
					<< generateTransition(state_next, state_fail
							, (innerType == Abnf_Altern
									? String("FSM_MATCH_CHAR(_u8(\"") + s + "\"))"
									: String("FSM_MATCH_STR(_u8(\"") + s + "\"))")
							, status)
					<< String::EndOfLine;
			}
		} else {
*/
			r << INDENT << sep << generateTransition(state_next, state_fail, element->toFsmMatchString(), status) << String::EndOfLine;
			++it;
//		}

		sep = String(", ");
	}

	if (innerType == Abnf_Altern) {
		r << INDENT << sep
		  << generateTransition(-1, -1, "FSM_MATCH_NOTHING", FSM_REJECT
				  , (isOrigRule ? "Transitions::on_end_rejected" : "")
				  , (isOrigRule ? actionArgsText : ""))
		  << String::EndOfLine;

		if (isOrigRule) {
			r << INDENT << sep
			  << generateTransition(-1, -1, "FSM_MATCH_NOTHING", FSM_ACCEPT, "Transitions::on_end_accepted", actionArgsText)
			  << String::EndOfLine;
		}
	} else { // Abnf_Concat || Abnf_Rpt
		r << INDENT << sep
		  << generateTransition(-1, -1, "FSM_MATCH_NOTHING", FSM_ACCEPT
				  , (isOrigRule ? "Transitions::on_end_accepted" : "")
				  , (isOrigRule ? actionArgsText : ""))
		  << String::EndOfLine;

		if (isOrigRule) {
			r << INDENT << sep
			  << generateTransition(-1, -1, "FSM_MATCH_NOTHING", FSM_REJECT , "Transitions::on_end_rejected", actionArgsText)
			  << String::EndOfLine;
		}
	}


	r << "};" << String::EndOfLine;

	return r;
}
Exemplo n.º 23
0
bool zip::parse(QTreeWidget * listv, QString bf, akuRatioWidget *ratioBar )
{
  // variabile che indica la presenza di file con password (header compreso)
  bool fileswithpass = false;
  bf.remove(0, (bf.indexOf("\n") + 1)); // elimino la prima riga
  bf.remove(bf.lastIndexOf("\n"), bf.size()); // elimino l'ultima riga
  // memorizzo l'ultima riga per conservare delle informazioni utili
  QString lastline = bf.mid((bf.lastIndexOf("\n") + 1), bf.size());
  bf.remove(bf.lastIndexOf("\n"), bf.size()); 
  bool crypted = false;
  QStringList flist = bf.split ( "\n" ); //splitto basandomi sul carattere di newline
  int numeroPezziPercorso;
  QRegExp sep("(\\s+)");
  //inizio il ciclo per la visualizzazione dell'elenco
  for ( int i = 0; i < flist.size(); i++ ) {
    // estraggo prima il percorso del file a partire dal carattere 62
    QString filepath = flist[i].mid(62, flist[i].size());
    // questa funzione per quanto migliore, non prende i file che iniziano per spazio vuoto
    //QString filepath = flist[i].section(sep, 9 , -1);
    QStringList singleItem = filepath.split (QDir().separator());  //splitto i nomi delle cartelle
    //puts(singleItem.join(" ").toAscii());
    numeroPezziPercorso = singleItem.size() - 1;
    QTreeWidgetItem *fitem; //nuovo elemento da allocare in lista
    QTreeWidgetItem *tmpItem; //puntatore a elemento temporaneo
    bool foldFound = false; //se ho trovato l'elemento...
    bool itemFound = false;
    for ( int j = 0; j < singleItem.size(); j++ ) {//per ogni cartella ramifico...
      itemFound = false;
      foldFound = false;
    //-------------------queste operazioni avvengono solo ed esclusivamente al primo ciclo---------------------//
      if ( j == 0 ) {  //se e' il primo ciclo limitiamo la ricerca ai top level items
        for ( int c = 0; c < listv -> topLevelItemCount(); c++ ) { //se trovo l'elemento tra i top level setto il current
          if ( ( listv -> topLevelItem ( c ) ) -> text ( 0 ) == singleItem[j] ) {
            tmpItem = listv -> topLevelItem ( c );
            foldFound = true;
            break; //se ho trovato l'elemento è inutile continuare il ciclo
          }
        }
        if ( foldFound == false ) {  //altrimenti alloco in lista in topLevel.. Questo accade anche se non è stato eseguito nessun ciclo
          fitem = new QTreeWidgetItem ( listv );
          fitem -> setText ( 0, singleItem[j] );
          tmpItem = fitem;
        }
      }
      else {  //------------------queste operazioni avvengono per tutti gli altri cicli-------------------//
      //cerco ciò che mi interessa tra i child dell currentItem() attuale
        for ( int c=0; c < tmpItem -> childCount(); c++ ) {
            if ( tmpItem->child ( c ) -> text ( 0 ) == singleItem[j] ) {
              tmpItem = tmpItem->child ( c ); //se lo trovo setto il current item
              itemFound = true;
              break; //se ho trovato l'elemento è inutile continuare il ciclo
            }
        }
        if (( itemFound == false ) && (!singleItem[j].isEmpty())) {  //altrimenti alloco e setto il currentItem
          fitem = new QTreeWidgetItem ( tmpItem );
          fitem -> setText ( 0, singleItem[j] );
          tmpItem = fitem;
        }
      }

    }

    //flist[i].remove(62, flist[i].size());
    QStringList dlist = (flist.at(i)).split(" ", QString::SkipEmptyParts ); // generiamo una lista contenente i parametri dei file
    //puts(dlist[4].toAscii() + dlist[6].toAscii());
    //if (!((dlist[6] == "stor") && (dlist[4] == "bx"))) {  //è inutile scrivere gli attributi della cartella
    // provo a vedere se basta leggere la "d" dai permessi per individuare una cartella invece di un controllo
    // fatto nella riga precedente.
    if (dlist[0][0] != QChar('d')) { 
      fitem -> setText(4, dlist[7] + " " + dlist[8]);  // modified

      QString size = KLocale( QString() ).formatByteSize(dlist[3].toDouble());  // 3 -> dimensione originale del file
      fitem -> setText(1, size);
      size = KLocale( QString() ).formatByteSize(dlist[5].toDouble()); // 5 -> dimensione packed del file
      fitem -> setText(2, size);

      fitem -> setText(5, dlist[0]);   // attributi 
      fitem -> setText(7, dlist[4] + " " + dlist[6]); // metodo
      
      if ((dlist[4][0] == QChar('B')) || (dlist[4][0] == QChar('T'))) crypted = true; 
      else crypted = false;

      fitem -> setText(8, dlist[1] + " " + dlist[2]); // version and so
      // calcolo il ratio
      float ratio = 0;
      if (dlist[3].toInt() != 0) {
        ratio = (100.0 * dlist[5].toFloat() / dlist[3].toFloat());
        ratio = abs(ratio - 100);   
      }
      fitem -> setText(3, QString().setNum(ratio) + "%");
        
//       //  akuRatioWidget *ratioWidget = new akuRatioWidget(ratio);
//       //  listv -> setItemWidget(fitem, 3, ratioWidget); 
// 
      fitem -> setTextAlignment ( 1, Qt::AlignRight | Qt::AlignVCenter );
      fitem -> setTextAlignment ( 2, Qt::AlignRight | Qt::AlignVCenter );
      fitem -> setTextAlignment ( 3, Qt::AlignHCenter | Qt::AlignVCenter );
      fitem -> setTextAlignment ( 5, Qt::AlignHCenter | Qt::AlignVCenter );
      fitem -> setTextAlignment ( 7, Qt::AlignRight | Qt::AlignVCenter );
      fitem -> setTextAlignment ( 8, Qt::AlignCenter | Qt::AlignVCenter );     

      KMimeType::Ptr mimePtr = KMimeType::findByUrl(KUrl(singleItem[numeroPezziPercorso]));
      KIcon icon(mimePtr -> iconName());
      fitem -> setIcon (0, icon);
      fitem -> setText(9, mimePtr->name());
    }
    if (crypted == true) {
      fitem -> setIcon(10, KIcon("dialog-password"));
      fileswithpass = true;
    }
  }

  QStringList archinfo;
  archinfo = lastline.split ( " ", QString::SkipEmptyParts );
  archiveDetails << archinfo[0] << KLocale(archinfo[2] ).formatByteSize(archinfo[2].toULong()) << KLocale(archinfo[5] ).formatByteSize(archinfo[5].toULong());
  
  QString ratio = archinfo.at (8);
  ratio.remove (ratio.length() - 1, 1);
  ratioBar -> setRatio (int(ratio.toFloat() + 0.5f));
  
  return fileswithpass;
}
Exemplo n.º 24
0
void LLHTTPNode::addNode(const std::string& path, LLHTTPNode* nodeToAdd)
{
	typedef boost::tokenizer< boost::char_separator<char> > tokenizer;
	boost::char_separator<char> sep("/", "", boost::drop_empty_tokens);
	tokenizer tokens(path, sep);
	tokenizer::iterator iter = tokens.begin();
	tokenizer::iterator end = tokens.end();

	LLHTTPNode* node = this;
	for(; iter != end; ++iter)
	{
		LLHTTPNode* child = node->impl.findNamedChild(*iter);
		if (!child) { break; }
		node = child;
	}
	
	if (iter == end)
	{
		llwarns << "LLHTTPNode::addNode: already a node that handles "
			<< path << llendl;
		return;
	}
	
	while (true)
	{
		std::string pathPart = *iter;
		
		++iter;
		bool lastOne = iter == end;
		
		LLHTTPNode* nextNode = lastOne ? nodeToAdd : new LLHTTPNode();
		
		switch (pathPart[0])
		{
			case '<':
				// *NOTE: This should really validate that it is of
				// the proper form: <wildcardkey> so that the substr()
				// generates the correct key name.
				node->impl.mWildcardChild = nextNode;
				node->impl.mWildcardName = pathPart;
				if(node->impl.mWildcardKey.empty())
				{
					node->impl.mWildcardKey = pathPart.substr(
						1,
						pathPart.size() - 2);
				}
				break;
			case '*':
				node->impl.mWildcardChild = nextNode;
				if(node->impl.mWildcardName.empty())
				{
					node->impl.mWildcardName = pathPart;
				}
				break;
			
			default:
				node->impl.mNamedChildren[pathPart] = nextNode;
		}
		nextNode->impl.mParentNode = node;

		if (lastOne) break;
		node = nextNode;
	}
}
Exemplo n.º 25
0
void LLFloaterAO::onNotecardLoadComplete(LLVFS *vfs,const LLUUID& asset_uuid,LLAssetType::EType type,void* user_data, S32 status, LLExtStat ext_status)
{
	if(status == LL_ERR_NOERR)
	{
		S32 size = vfs->getSize(asset_uuid, type);
		U8* buffer = new U8[size];
		vfs->getData(asset_uuid, type, buffer, 0, size);

		if(type == LLAssetType::AT_NOTECARD)
		{
			LLViewerTextEditor* edit = new LLViewerTextEditor("",LLRect(0,0,0,0),S32_MAX,"");
			if(edit->importBuffer((char*)buffer, (S32)size))
			{
				llinfos << "ao nc decode success" << llendl;
				std::string card = edit->getText();
				edit->die();

				LUA_CALL("OnAONotecardRead") << card << LUA_END;

				mAOAllAnims.clear();
				mAOStands.clear();
				//mAODefaultAnims.clear();

				struct_stands standsloader;
				struct_all_anims all_anims_loader;

				typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
				boost::char_separator<char> sep("\n");
				tokenizer tokline(card, sep);

				for (tokenizer::iterator line = tokline.begin(); line != tokline.end(); ++line)
				{
					std::string strline(*line);

					boost::regex type("^(\\s*)(\\[ )(.*)( \\])");
					boost::smatch what; 
					if (boost::regex_search(strline, what, type)) 
					{
						boost::char_separator<char> sep("|,");
						std::string stranimnames(boost::regex_replace(strline, type, ""));
						tokenizer tokanimnames(stranimnames, sep);
						for (tokenizer::iterator anim = tokanimnames.begin(); anim != tokanimnames.end(); ++anim)
						{
							std::string strtoken(what[0]);
							std::string stranim(*anim);
							int state = GetStateFromToken(strtoken.c_str());
							LLUUID animid(getAssetIDByName(stranim));

							if (!(animid.notNull()))
							{
								cmdline_printchat(llformat("Warning: animation '%s' could not be found (Section: %s).",stranim.c_str(),strtoken.c_str()));
							}
							else
							{
								all_anims_loader.ao_id = animid; all_anims_loader.anim_name = stranim.c_str(); all_anims_loader.state = state; mAOAllAnims.push_back(all_anims_loader);

								if (state == STATE_AGENT_STAND)
								{
									standsloader.ao_id = animid; standsloader.anim_name = stranim.c_str(); mAOStands.push_back(standsloader);
									continue;
								}

								for (std::vector<struct_default_anims>::iterator iter = mAODefaultAnims.begin(); iter != mAODefaultAnims.end(); ++iter)
								{
									if (state == iter->state) iter->ao_id = animid;
								}
							}
						}
					} 
				}
				llinfos << "ao nc read sucess" << llendl;

				loadComboBoxes();

				run();
			}
			else
			{
				llinfos << "ao nc decode error" << llendl;
			}
		}
	}
	else
	{
		llinfos << "ao nc read error" << llendl;
	}
}
Exemplo n.º 26
0
inline std::vector<std::string> tokenizeLabels( const std::string &list ) {
    boost::char_separator<char> sep( "," );
    boost::tokenizer<boost::char_separator<char>> tok( list, sep );
    return std::vector<std::string>( tok.begin(), tok.end() );
}
Exemplo n.º 27
0
/**
 @brief main() Initialize user task
 @return void
*/
MEMSPACE 
void setup(void)
{
	int i;
    char time[20];
	int ret;
	uint16_t *ptr;
	double ang;
	extern web_init();
	int w,h;

	ip_msg[0] = 0;

// CPU
// 160MHZ
   REG_SET_BIT(0x3ff00014, BIT(0));
// 80MHZ
//   REG_CLR_BIT(0x3ff00014, BIT(0));

	os_delay_us(200000L);	// Power Up dalay - lets power supplies and devices settle

	// Configure the UART
	//uart_init(BIT_RATE_115200,BIT_RATE_115200);
	uart_init(BIT_RATE_74880,BIT_RATE_74880);

	os_delay_us(200000L);	// Power Up dalay - lets power supplies and devices settle
	os_delay_us(200000L);	// Power Up dalay - lets power supplies and devices settle
	printf("\n\n\n\n");
    sep();
	printf("System init...\n");
    printf("ESP8266 multidevice project\n");
    printf(" (c) 2014-2017 by Mike Gore\n");
    printf(" GNU version 3\n");
    printf("-> https://github.com/magore/esp8266_ili9341\n");
    printf("   GIT last pushed:   %s\n", GIT_VERSION);
    printf("   Last updated file: %s\n", LOCAL_MOD);


    sep();
    PrintRam();

    sep();
	printf("HSPI init...\n");
	hspi_init(1,0);

	printf("Timers init...\n");
	init_timers();

	// 1000HZ timer
	ms_init();

	test_types();

	// Functions manage user defined address pins
	chip_addr_init();

	initialize_clock(300);


#ifdef ADF4351
	#ifdef ADF4351_CS
		chip_select_init(ADF4351_CS);
	#endif
	ADF4351_Init();
	printf("ADF4351 init done\n");
#endif

// Make sure all other GPIO pins are initialized BEFORE SD card
#ifdef FATFS_SUPPORT
    sep();
	// Functions manage chip selects
	#ifdef MMC_CS
		chip_select_init(MMC_CS);
	#endif
	printf("SD Card init...\n");
	mmc_init(1);
#endif

#ifdef DISPLAY
    sep();
	#ifdef ILI9341_CS
		chip_select_init(ILI9341_CS);
	#endif

	#ifdef XPT2046_CS
		XPT2046_spi_init();
	#endif

	// Initialize TFT
	master = tft_init();

 	tft_calX = MatRead("/tft_calX");
 	tft_calY = MatRead("/tft_calY");
	if(tft_calX.data == NULL || tft_calY.data == NULL)
		tft_is_calibrated = 0;
	else
		tft_is_calibrated = 1;
	printf("TFT calibration %s\n", tft_is_calibrated ?  "YES" : "NO");

	// rotateion = 1, debug = 1
	setup_windows(1,1);
#endif

	wdt_reset();
    sep();
	printf("Setup Tasks\n");

    sep();
	setup_networking();

	#ifdef TELNET_SERIAL
		printf("Setup Network Serial Bridge\n");
		bridge_task_init(23);
	#endif

	if ( espconn_tcp_set_max_con(MAX_CONNECTIONS+1) )
		printf("espconn_tcp_set_max_con(%d) != (%d) - failed!\n", 
			MAX_CONNECTIONS+1, espconn_tcp_get_max_con());
	else
		printf("espconn_tcp_set_max_con(%d) = (%d) - success!\n", 
			MAX_CONNECTIONS+1, espconn_tcp_get_max_con());

#ifdef NETWORK_TEST
	printf("Setup Network TFT Display Client\n");
	servertest_setup(TCP_PORT);
#endif

#ifdef WEBSERVER
	printf("Setup Network WEB SERVER\n");
	web_init(80);
#endif

    sep();
    PrintRam();

	system_set_os_print(0);

} //setup()
Exemplo n.º 28
0
    /**
    *   Executes the algorithm.
    */
    void LoadSpec::exec()
    {
      std::string filename = getProperty("Filename");
      //std::string separator = " "; //separator can be 1 or more spaces
      std::ifstream file(filename.c_str());

      file.seekg (0, std::ios::end);
      Progress progress(this,0,1,static_cast<int>(file.tellg()));
      file.seekg (0, std::ios::beg);

      std::string str;

      std::vector<DataObjects::Histogram1D> spectra;


      int nBins = 0; //number of rows


      //bool numeric = true;
      std::vector<double> input;

      //determine the number of lines starting by #L
      //as there is one per set of data
      int spectra_nbr = 0;
      while(getline(file,str))
      {
        if (str[0] == '#' && str[1] == 'L')
        {
          spectra_nbr++;
        }
      }

      spectra.resize(spectra_nbr);
      file.clear(); //end of file has been reached so we need to clear file state
      file.seekg (0, std::ios::beg); //go back to beginning of file

      int working_with_spectrum_nbr = -1; //spectrum number
      while(getline(file,str))
      {
        progress.report(static_cast<int>(file.tellg()));

        //line with data, need to be parsed by white spaces
        if (!str.empty() && str[0] != '#')
        {
          typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
          boost::char_separator<char> sep(" ");
          tokenizer tok(str, sep);
          for (tokenizer::iterator beg=tok.begin(); beg!=tok.end(); ++beg)
          {
            std::stringstream ss;
            ss << *beg;
            double d;
            ss >> d;
            input.push_back(d);
          }
        }

        if (str.empty())
        {
          if (working_with_spectrum_nbr != -1)
          {
            for(int j=0; j<static_cast<int>(input.size()-1); j++)
            {
              spectra[working_with_spectrum_nbr].dataX().push_back(input[j]);
              j++;
              spectra[working_with_spectrum_nbr].dataY().push_back(input[j]);
              j++;
              spectra[working_with_spectrum_nbr].dataE().push_back(input[j]);
              nBins = j/3;
            }
          }
          working_with_spectrum_nbr++;
          input.clear();
        }

      } //end of read file

      try
      {
        if (spectra_nbr == 0)
          throw "Undefined number of spectra";

        if (working_with_spectrum_nbr == (spectra_nbr-1))
        {
          for(int j=0; j<static_cast<int>(input.size()-1); j++)
          {
            spectra[working_with_spectrum_nbr].dataX().push_back(input[j]);
            j++;
            spectra[working_with_spectrum_nbr].dataY().push_back(input[j]);
            j++;
            spectra[working_with_spectrum_nbr].dataE().push_back(input[j]);
            nBins = j/3;
          }
        }
      }
      catch (...)
      {
      }

      try
      {
        int nSpectra = spectra_nbr;
        MatrixWorkspace_sptr localWorkspace = boost::dynamic_pointer_cast<MatrixWorkspace>
          (WorkspaceFactory::Instance().create("Workspace2D",nSpectra,nBins,nBins));

        localWorkspace->getAxis(0)->unit() = UnitFactory::Instance().create(getProperty("Unit"));

        for(int i=0;i<nSpectra;i++)
        {
          localWorkspace->dataX(i) = spectra[i].dataX();
          localWorkspace->dataY(i) = spectra[i].dataY();
          localWorkspace->dataE(i) = spectra[i].dataE();
          // Just have spectrum number start at 1 and count up
          localWorkspace->getSpectrum(i)->setSpectrumNo(i+1);
        }

        setProperty("OutputWorkspace",localWorkspace);
      }
      catch (Exception::NotFoundError&)
      {
        // Asked for dimensionless workspace (obviously not in unit factory)
      }

    }
Exemplo n.º 29
0
void LLInventoryItem::unpackBinaryBucket(U8* bin_bucket, S32 bin_bucket_size)
{	
	// Early exit on an empty binary bucket.
	if (bin_bucket_size <= 1) return;

	if (NULL == bin_bucket)
	{
		llerrs << "unpackBinaryBucket failed.  bin_bucket is NULL." << llendl;
		return;
	}

	// Convert the bin_bucket into a string.
	std::vector<char> item_buffer(bin_bucket_size+1);
	memcpy(&item_buffer[0], bin_bucket, bin_bucket_size);	/* Flawfinder: ignore */
	item_buffer[bin_bucket_size] = '\0';
	std::string str(&item_buffer[0]);

	lldebugs << "item buffer: " << str << llendl;

	// Tokenize the string.
	typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
	boost::char_separator<char> sep("|", "", boost::keep_empty_tokens);
	tokenizer tokens(str, sep);
	tokenizer::iterator iter = tokens.begin();

	// Extract all values.
	LLUUID item_id;
	item_id.generate();
	setUUID(item_id);

	LLAssetType::EType type;
	type = (LLAssetType::EType)(atoi((*(iter++)).c_str()));
	setType( type );
	
	LLInventoryType::EType inv_type;
	inv_type = (LLInventoryType::EType)(atoi((*(iter++)).c_str()));
	setInventoryType( inv_type );

	std::string name((*(iter++)).c_str());
	rename( name );
	
	LLUUID creator_id((*(iter++)).c_str());
	LLUUID owner_id((*(iter++)).c_str());
	LLUUID last_owner_id((*(iter++)).c_str());
	LLUUID group_id((*(iter++)).c_str());
	PermissionMask mask_base = strtoul((*(iter++)).c_str(), NULL, 16);
	PermissionMask mask_owner = strtoul((*(iter++)).c_str(), NULL, 16);
	PermissionMask mask_group = strtoul((*(iter++)).c_str(), NULL, 16);
	PermissionMask mask_every = strtoul((*(iter++)).c_str(), NULL, 16);
	PermissionMask mask_next = strtoul((*(iter++)).c_str(), NULL, 16);
	LLPermissions perm;
	perm.init(creator_id, owner_id, last_owner_id, group_id);
	perm.initMasks(mask_base, mask_owner, mask_group, mask_every, mask_next);
	setPermissions(perm);
	//lldebugs << "perm: " << perm << llendl;

	LLUUID asset_id((*(iter++)).c_str());
	setAssetUUID(asset_id);

	std::string desc((*(iter++)).c_str());
	setDescription(desc);
	
	LLSaleInfo::EForSale sale_type;
	sale_type = (LLSaleInfo::EForSale)(atoi((*(iter++)).c_str()));
	S32 price = atoi((*(iter++)).c_str());
	LLSaleInfo sale_info(sale_type, price);
	setSaleInfo(sale_info);
	
	U32 flags = strtoul((*(iter++)).c_str(), NULL, 16);
	setFlags(flags);

	time_t now = time(NULL);
	setCreationDate(now);
}
Exemplo n.º 30
-25
int main(int argc, char * argv[]) {
	if(argc != 2) {
		std::cerr << "Usage: " << argv[0] << " csvfile.csv" << std::endl;
		exit(EXIT_FAILURE);
	}//if

	CsvParser cp(argv[1]);
	std::cout << "Parsing ..." << std::endl;

	const auto & data_ref = cp.parse();
	if(data_ref.size() == 0) {
		std::cout << "No Data Available." << std::endl;
		return 0;
	}//if

	auto row_max = data_ref.size();
	auto col_max = data_ref[0].size();
	std::string line;
	std::vector<std::string> line_param;
	boost::char_separator<char> sep("[], ");

	// INTERACTIVE MODE
	std::cout << "Interactive Mode: Ctrl-D to Exit" << std::endl;
	std::cout << "list all the data: " << std::endl;
	std::cout << ">> list" << std::endl;
	std::cout << "output to file: " << std::endl;
	std::cout << ">> [Row_Begin,Row_End][Col_Begin,Col_End] FileName"
		<< std::endl;
	std::cout << "Get Data from data[Row][Column]: " << std::endl;
	std::cout << ">> Row,Column" << std::endl;
	std::cout << "Row size: " << row_max << " Col size: " << col_max << std::endl;
	while(1) {
		line.clear();
		// OUTPUT Title
		for(auto i : data_ref[0])
			std::cout << i << ' ';
		std::cout << std::endl;
		// GET INPUT
		do {
			std::cout << ">> ";
			std::getline(std::cin, line);
		} while(line.empty() && std::cin);

		// Test Ctrl-D
		if(!std::cin) {
			std::cout << std::endl;
			break;
		}//if

		// PARSE INPUT
		line_param.clear();
		boost::tokenizer<boost::char_separator<char>> tok(line, sep);
		std::copy(tok.begin(), tok.end(), std::back_inserter(line_param));

		try {
			switch(line_param.size()) {
			case 1: {
					if(line_param[0] == "l" || line_param[0] == "list") {
						std::size_t line_counter = 0;
						auto i = data_ref.begin(), i_end = data_ref.end();
						std::advance(i, 1); // skip the title
						for(; i != i_end; ++i) {
							std::cout << ++line_counter << ": ";
							for(auto j : *i) {
								std::cout << j << ',';
							}//for
							std::cout << "\b \b" << std::endl;
						}//for
					}//if
				}
				break;
			case 2: {
					auto row = std::stoi(line_param[0]);
					auto col = std::stoi(line_param[1]);
					if(row >= row_max || col >= col_max) {
						std::cout << "Out of Range!" << std::endl;
					} else {
						std::cout << data_ref[row][col] << std::endl;
					}//if-else
				}
				break;
			case 5: {
					std::ofstream out(line_param[4]);

					for(auto row_iter = std::stoi(line_param[0])-1,
								row_end = std::stoi(line_param[1]);
							row_iter != row_end;
							++row_iter)
					{
						for(auto col_iter = std::stoi(line_param[2])-1,
									col_end = std::stoi(line_param[3]);
								col_iter != col_end;
								++col_iter)
						{
							out << data_ref[row_iter][col_iter] << ',';
						}//for
						out << std::endl;
					}//for

					out.close();
				}//case
				break;
			default:
				std::cout << "Format Error" << std::endl;
			}//switch-case
		} catch(...) {
			std::cerr << "Format Error" << std::endl;
		}//try-catch
	}//while

	return 0;
}//main