nsresult
nsOperaProfileMigrator::CopySmartKeywords(nsINavBookmarksService* aBMS, 
                                          nsIStringBundle* aBundle,
                                          PRInt64 aParentFolder)
{
  nsresult rv;

  nsCOMPtr<nsIFile> smartKeywords;
  mOperaProfile->Clone(getter_AddRefs(smartKeywords));
  smartKeywords->Append(NS_LITERAL_STRING("search.ini"));

  nsCOMPtr<nsILocalFile> lf(do_QueryInterface(smartKeywords));
  nsINIParser parser;
  if (!lf || NS_FAILED(parser.Init(lf)))
    return NS_OK;

  nsString sourceNameOpera;
  rv = aBundle->GetStringFromName(NS_LITERAL_STRING("sourceNameOpera").get(),
                                  getter_Copies(sourceNameOpera));
  NS_ENSURE_SUCCESS(rv, rv);

  const PRUnichar* sourceNameStrings[] = { sourceNameOpera.get() };
  nsString importedSearchUrlsTitle;
  rv = aBundle->FormatStringFromName(NS_LITERAL_STRING("importedSearchURLsFolder").get(),
                                     sourceNameStrings, 1, 
                                     getter_Copies(importedSearchUrlsTitle));
  NS_ENSURE_SUCCESS(rv, rv);

  PRInt64 keywordsFolder;
  rv = aBMS->CreateFolder(aParentFolder,
                          NS_ConvertUTF16toUTF8(importedSearchUrlsTitle),
                          nsINavBookmarksService::DEFAULT_INDEX,
                          &keywordsFolder);
  NS_ENSURE_SUCCESS(rv, rv);

  PRInt32 sectionIndex = 1;
  nsCAutoString name, url, keyword;
  do {
    nsCAutoString section("Search Engine ");
    section.AppendInt(sectionIndex++);

    rv = parser.GetString(section.get(), "Name", name);
    if (NS_FAILED(rv)) {
      // No more smart keywords found, stop parsing the file.
      break;
    }
    if (name.IsEmpty())
      continue;

    rv = parser.GetString(section.get(), "URL", url);
    if (NS_FAILED(rv) || url.IsEmpty())
      continue;

    rv = parser.GetString(section.get(), "Key", keyword);
    if (NS_FAILED(rv) || keyword.IsEmpty())
      continue;

    PRInt32 post;
    rv = GetInteger(parser, section.get(), "Is post", &post);
    if (NS_SUCCEEDED(rv) && post)
      continue;

    PRUint32 length = name.Length();
    PRInt32 index = 0;
    do {
      index = name.FindChar('&', index);
      if ((PRUint32)index >= length - 2)
        break;

      // Assume "&&" is an escaped ampersand in the search query title. 
      if (name.CharAt(index + 1) == '&') {
        name.Cut(index, 1);
        index += 2;
        continue;
      }

      name.Cut(index, 1);
    }
    while ((PRUint32)index < length);

    nsCOMPtr<nsIURI> uri;
    if (NS_FAILED(NS_NewURI(getter_AddRefs(uri), url.get())) || !uri)
      continue;

    nsCAutoString hostCStr;
    uri->GetHost(hostCStr);
    NS_ConvertASCIItoUTF16 host(hostCStr);

    const PRUnichar* descStrings[] = { NS_ConvertUTF8toUTF16(keyword).get(),
                                       host.get() };
    nsString keywordDesc;
    rv = aBundle->FormatStringFromName(NS_LITERAL_STRING("importedSearchUrlDesc").get(),
                                       descStrings, 2,
                                       getter_Copies(keywordDesc));
    NS_ENSURE_SUCCESS(rv, rv);

    PRInt64 newId;
    rv = aBMS->InsertBookmark(keywordsFolder, uri,
                              nsINavBookmarksService::DEFAULT_INDEX,
                              name, &newId);
    NS_ENSURE_SUCCESS(rv, rv);
    rv = aBMS->SetKeywordForBookmark(newId, NS_ConvertUTF8toUTF16(keyword));
    NS_ENSURE_SUCCESS(rv, rv);
    // TODO Bug 397771: set bookmark description to keywordDesc.
  }
  while (1);
  
  return rv;
}
 resumable::resume_result resume(execution_unit* new_host,
                                 size_t max_throughput) override {
   CAF_REQUIRE(max_throughput > 0);
   auto d = static_cast<Derived*>(this);
   CAF_LOG_TRACE("id = " << d->id());
   d->host(new_host);
   auto done_cb = [&]() -> bool {
     CAF_LOG_TRACE("");
     d->bhvr_stack().clear();
     d->bhvr_stack().cleanup();
     d->on_exit();
     if (!d->bhvr_stack().empty()) {
       CAF_LOG_DEBUG("on_exit did set a new behavior");
       d->planned_exit_reason(exit_reason::not_exited);
       return false; // on_exit did set a new behavior
     }
     auto rsn = d->planned_exit_reason();
     if (rsn == exit_reason::not_exited) {
       rsn = exit_reason::normal;
       d->planned_exit_reason(rsn);
     }
     d->cleanup(rsn);
     return true;
   };
   auto actor_done = [&]() -> bool {
     if (d->bhvr_stack().empty()
         || d->planned_exit_reason() != exit_reason::not_exited) {
       return done_cb();
     }
     return false;
   };
   // actors without behavior or that have already defined
   // an exit reason must not be resumed
   CAF_REQUIRE(!d->is_initialized()
               || (!d->bhvr_stack().empty()
                   && d->planned_exit_reason() == exit_reason::not_exited));
   std::exception_ptr eptr = nullptr;
   try {
     if (!d->is_initialized()) {
       CAF_LOG_DEBUG("initialize actor");
       d->is_initialized(true);
       auto bhvr = d->make_behavior();
       CAF_LOG_DEBUG_IF(!bhvr, "make_behavior() did not return a behavior, "
                               << "bhvr_stack().empty() = "
                               << std::boolalpha << d->bhvr_stack().empty());
       if (bhvr) {
         // make_behavior() did return a behavior instead of using become()
         CAF_LOG_DEBUG("make_behavior() did return a valid behavior");
         d->become(std::move(bhvr));
       }
       if (actor_done()) {
         CAF_LOG_DEBUG("actor_done() returned true right "
                       << "after make_behavior()");
         return resume_result::done;
       }
     }
     // max_throughput = 0 means infinite
     for (size_t i = 0; i < max_throughput; ++i) {
       auto ptr = d->next_message();
       if (ptr) {
         if (d->invoke_message(ptr)) {
           if (actor_done()) {
             CAF_LOG_DEBUG("actor exited");
             return resume_result::done;
           }
           // continue from cache if current message was
           // handled, because the actor might have changed
           // its behavior to match 'old' messages now
           while (d->invoke_message_from_cache()) {
             if (actor_done()) {
               CAF_LOG_DEBUG("actor exited");
               return resume_result::done;
             }
           }
         }
         // add ptr to cache if invoke_message
         // did not reset it (i.e. skipped, but not dropped)
         if (ptr) {
           CAF_LOG_DEBUG("add message to cache");
           d->push_to_cache(std::move(ptr));
         }
       } else {
         CAF_LOG_DEBUG("no more element in mailbox; going to block");
         if (d->mailbox().try_block()) {
           return resumable::awaiting_message;
         }
         CAF_LOG_DEBUG("try_block() interrupted by new message");
       }
     }
     if (!d->has_next_message() && d->mailbox().try_block()) {
       return resumable::awaiting_message;
     }
     // time's up
     return resumable::resume_later;
   }
   catch (actor_exited& what) {
     CAF_LOG_INFO("actor died because of exception: actor_exited, "
                  "reason = " << what.reason());
     if (d->exit_reason() == exit_reason::not_exited) {
       d->quit(what.reason());
     }
   }
   catch (std::exception& e) {
     CAF_LOG_INFO("actor died because of an exception: "
                  << detail::demangle(typeid(e))
                  << ", what() = " << e.what());
     if (d->exit_reason() == exit_reason::not_exited) {
       d->quit(exit_reason::unhandled_exception);
     }
     eptr = std::current_exception();
   }
   catch (...) {
     CAF_LOG_INFO("actor died because of an unknown exception");
     if (d->exit_reason() == exit_reason::not_exited) {
       d->quit(exit_reason::unhandled_exception);
     }
     eptr = std::current_exception();
   }
   if (eptr) {
     auto opt_reason = d->handle(eptr);
     if (opt_reason) {
       // use exit reason defined by custom handler
       d->planned_exit_reason(*opt_reason);
     }
   }
   if (!actor_done()) {
     // actor has been "revived", try running it again later
     return resumable::resume_later;
   }
   return resumable::done;
 }
Ejemplo n.º 3
0
	void Ping::start() {
		m_process->start("ping", QStringList() << host() << QString("-c %1").arg(packetCount()));
	}
Ejemplo n.º 4
0
bool HostAndPort::operator<(const HostAndPort& r) const {
    const int cmp = host().compare(r.host());
    if (cmp)
        return cmp < 0;
    return port() < r.port();
}
Ejemplo n.º 5
0
void ShadowRoot::setInnerHTML(const String& markup, ExceptionCode& ec)
{
    RefPtr<DocumentFragment> fragment = createFragmentFromSource(markup, host(), ec);
    if (fragment)
        replaceChildrenWithFragment(this, fragment.release(), ec);
}
Ejemplo n.º 6
0
void ShadowRoot::setInnerHTML(const String& markup, ExceptionState& exceptionState)
{
    if (isOrphan()) {
        exceptionState.throwDOMException(InvalidAccessError, "The ShadowRoot does not have a host.");
        return;
    }

    if (RefPtrWillBeRawPtr<DocumentFragment> fragment = createFragmentForInnerOuterHTML(markup, host(), AllowScriptingContent, "innerHTML", exceptionState))
        replaceChildrenWithFragment(this, fragment.release(), exceptionState);
}
Ejemplo n.º 7
0
	std::unique_ptr<Role> assign_roles(unsigned nprocs) {

		char* hostname = new char[MAX_HOSTNAME_LENGTH+1];
		char other_hostname[(MAX_HOSTNAME_LENGTH+1)*nprocs];

		// LOG(DEBUG) << "Detecting hostname for this process:";

		/* invoke the 'hostname' command and read the value */
		gethostname(hostname, MAX_HOSTNAME_LENGTH);
		
		std::string host(hostname); 
		// LOG(DEBUG) << "\tHostname: '" << hostname << "'";

		/* Collect all the hostnames from all the processes */
		MPI_Allgather( hostname, MAX_HOSTNAME_LENGTH+1, MPI_CHAR, other_hostname, 
					   MAX_HOSTNAME_LENGTH+1, MPI_CHAR, MPI_COMM_WORLD );

		/* free memory */
		delete[] hostname;

		std::set<std::string> hosts;
		for(size_t p=0; p<static_cast<size_t>(nprocs); ++p) {
			hosts.insert( std::string(&other_hostname[p*(MAX_HOSTNAME_LENGTH+1)]) );
		}
	
		// declare communicators
		MPI_Comm node_comm, sched_comm;

		auto fit = std::find(hosts.begin(), hosts.end(), host);
		assert(fit != hosts.end() && "Current host name not found!");

		MPI_Comm_split(MPI_COMM_WORLD, std::distance(hosts.begin(), fit), 0, &node_comm);

		int node_comm_size;
		int node_comm_rank;
		MPI_Comm_size(node_comm, &node_comm_size);
		MPI_Comm_rank(node_comm, &node_comm_rank);
		if (node_comm_rank==0) {
			LOG(DEBUG) << "Node communicator has '" << node_comm_size << "' nodes";
			LOG(DEBUG) << "Number of nodes detected is '" << hosts.size() << "'";
			LOG(DEBUG) << utils::join(hosts.begin(), hosts.end(), ",");
		}

		/* 
		 * If the rank in the new communicator is 0 then this process will act as 
		 * a node scheduler, therefore a communicator between scheduler is create
		 * to connect them 
		 */
		MPI_Comm_split(MPI_COMM_WORLD, node_comm_rank==0, 0, &sched_comm);

		LOG(DEBUG) << "\\@ Initialization completed!";

		int mypid = getpid();
		if (node_comm_rank==0) {
			std::vector<int> node_pids(node_comm_size);

			MPI_Gather(&mypid, 1, MPI_INT, 
					   &node_pids.front(), 1, MPI_INT, 
					   0, node_comm);
			
			Scheduler::Pids pids(node_comm_size);
			for(int i=1;i<node_comm_size;++i) 
				pids[i-1] = { i, node_pids[i] };

			return std::move( std::unique_ptr<Scheduler>( 
						new Scheduler(node_comm, sched_comm, std::move(pids)) ) 
					);
		}

		MPI_Gather(&mypid, 1, MPI_INT, NULL, 0, MPI_INT, 0, node_comm);
		return std::move( std::unique_ptr<Worker>( new Worker(node_comm) ) );
	}
Ejemplo n.º 8
0
//
// By default, we self-identify by asking our host to identify us.
// (This is currently only overridden in the root-of-trust (kernel) implementation.)
//
void SecCode::identify()
{
	mStaticCode.take(host()->identifyGuest(this, &mCDHash.aref()));
}
Ejemplo n.º 9
0
bool HostPortWidget::isValidHost() const {
    common::net::HostAndPort hs = host();
    return hs.isValid();
}
Ejemplo n.º 10
0
 ////////////////////////////////////////////////////////////////////////
 //  constructor
 advertdirectory_cpi_impl::advertdirectory_cpi_impl (proxy                           * p, 
                                                     cpi_info const                  & info,
                                                     saga::ini::ini const            & glob_ini, 
                                                     saga::ini::ini const            & adap_ini,
                                                     TR1::shared_ptr <saga::adaptor>   adaptor)
   : saga::adaptors::v1_0::advert_directory_cpi <advertdirectory_cpi_impl> (p, info, adaptor, cpi::Noflags) 
 {
     saga::url advert_url;
     instance_data data (this);
     advert_url = data->location_.clone();
     std::string path;
     int port;
     path = advert_url.get_path();
     if (path.empty())
         path = "/"; // root only
     std::string host(advert_url.get_host());
     if (host.empty()) {
        SAGA_OSSTREAM strm;
        strm << "advert::advert_cpi_impl::init: "
                "cannot handle advert entry name: " 
             << advert_url.get_url();
        SAGA_ADAPTOR_THROW(SAGA_OSSTREAM_GETSTRING(strm), saga::IncorrectURL);
     }
     std::string scheme(advert_url.get_scheme());
     if (!scheme.empty() && scheme != "hbase" && scheme != "any") {
        SAGA_OSSTREAM strm;
        strm << "advert::advert_cpi_impl::init: "
                "cannot handle advert entry name: " << advert_url.get_url();
        SAGA_ADAPTOR_THROW(SAGA_OSSTREAM_GETSTRING(strm), saga::IncorrectURL);
     }
     port = advert_url.get_port();
     boost::shared_ptr<TTransport> socket(new TSocket(host, port));
     transport_ = boost::shared_ptr<TTransport>(new TBufferedTransport(socket));
     boost::shared_ptr<TProtocol> protocol(new TBinaryProtocol(transport_));
     client_ = new HbaseClient(protocol);
     transport_->open();
     saga::advert::flags mode = (saga::advert::flags)data->mode_;
     if(path == "/") {
     }
     else if (((mode & saga::advert::Create) || (mode & saga::advert::CreateParents)) && 
         (mode & saga::advert::Exclusive)) {
         if(!url_exists(*client_, advert_url.get_url())) {
            SAGA_OSSTREAM strm;
            strm << "advert::advert_cpi_impl::init: "
                    "advert already exists: " << advert_url.get_url();
            SAGA_ADAPTOR_THROW(SAGA_OSSTREAM_GETSTRING(strm), saga::AlreadyExists);
         }
     }
     else if ((mode & saga::advert::Create) || (mode & saga::advert::CreateParents)) {
         if(!url_exists(*client_, advert_url.get_url())) {
            if(!create_url(*client_, advert_url.get_url(), true)) {
               // failed to create url
               SAGA_OSSTREAM strm;
               strm << "advert::advert_cpi_impl::init: "
                       "advert couldn't create url: " << advert_url.get_url();
               SAGA_ADAPTOR_THROW(SAGA_OSSTREAM_GETSTRING(strm), saga::AlreadyExists);
            }
         }
        // no need to create this entry twice
        data->mode_ &= ~(saga::advert::Create | saga::advert::CreateParents);
     }
     /*if(!url_exists(*client_, advert_url.get_url())) {
        //here is where I am
        SAGA_OSSTREAM strm;
        strm << "advert::advert_cpi_impl::init: "
                "advert does not exist: " << advert_url.get_url();
        SAGA_ADAPTOR_THROW(SAGA_OSSTREAM_GETSTRING(strm), saga::BadParameter);
     }*/
     //SAGA_ADAPTOR_THROW ("Not Implemented", saga::NotImplemented);
 }
Ejemplo n.º 11
0
 void UdpMonitor::AddPort(int port, UdpPortDataType dataType)
 {
     // Utils::HostInf host("127.0.0.1", port);
     Utils::HostInf host("0.0.0.0", port);
     m_ports.Add(new UdpLocalPoint(m_thread, *this, new UdpDataTransformer(dataType), host));
 }
Ejemplo n.º 12
0
ElementShadow* ShadowRoot::owner() const
{
    if (host())
        return host()->shadow();
    return 0;
}
Ejemplo n.º 13
0
 actor spawn_in_group(const group& grp, Ts&&... args) {
   constexpr auto os = make_unbound(Os);
   auto res = spawn_class<C, os>(host(), group_subscriber{grp},
                   std::forward<Ts>(args)...);
   return eval_opts(Os, std::move(res));
 }
Ejemplo n.º 14
0
 actor spawn(Ts&&... args) {
   constexpr auto os = make_unbound(Os);
   auto res = spawn_functor<os>(host(), empty_before_launch_callback{},
                  std::forward<Ts>(args)...);
   return eval_opts(Os, std::move(res));
 }
Ejemplo n.º 15
0
void petabricks::DistributedGC::onCreated() {
  host()->swapObjects(_objects, _gen);
  remoteNotify(FLUSH_MSGS);
}
void lvDCOMInterface::createViRef(BSTR vi_name, bool reentrant, LabVIEW::VirtualInstrumentPtr& vi)
{
	epicsThreadOnce(&onceId, initCOM, NULL);
	std::wstring ws(vi_name, SysStringLen(vi_name));
	HRESULT hr;
	if ( (m_lv != NULL) && (m_lv->CheckConnection() == S_OK) )
	{
		;
	}
	else if (m_host.size() > 0)
	{
		std::cerr << "(Re)Making connection to LabVIEW on " << m_host << std::endl;
		CComBSTR host(m_host.c_str());
		m_pidentity = createIdentity(m_username, m_host, m_password);
		COAUTHINFO* pauth = new COAUTHINFO;
		COSERVERINFO csi = { 0, NULL, NULL, 0 };
		pauth->dwAuthnSvc = RPC_C_AUTHN_WINNT;
		pauth->dwAuthnLevel = RPC_C_AUTHN_LEVEL_DEFAULT;
		pauth->dwAuthzSvc = RPC_C_AUTHZ_NONE;
		pauth->dwCapabilities = EOAC_NONE;
		pauth->dwImpersonationLevel = RPC_C_IMP_LEVEL_IMPERSONATE;
		pauth->pAuthIdentityData = m_pidentity;
		pauth->pwszServerPrincName = NULL;
		csi.pwszName = host;
		csi.pAuthInfo = pauth;
		MULTI_QI mq[ 1 ] = { 0 }; 
		mq[ 0 ].pIID = &IID_IDispatch;  // &LabVIEW::DIID__Application; // &IID_IDispatch; 
		mq[ 0 ].pItf = NULL; 
		mq[ 0 ].hr   = S_OK; 
		hr = CoCreateInstanceEx( m_clsid, NULL, CLSCTX_REMOTE_SERVER | CLSCTX_LOCAL_SERVER, &csi, 1, mq ); 
		if( FAILED( hr ) ) 
		{ 
			hr = CoCreateInstanceEx( m_clsid, NULL, CLSCTX_ALL, &csi, 1, mq );
		}
		if( FAILED( hr ) ) 
		{
			throw COMexception("CoCreateInstanceEx (LabVIEW) ", hr);
		} 
		if( S_OK != mq[ 0 ].hr || NULL == mq[ 0 ].pItf ) 
		{ 
			throw COMexception("CoCreateInstanceEx (LabVIEW)(mq) ", mq[ 0 ].hr);
		} 
		setIdentity(m_pidentity, mq[ 0 ].pItf);
		m_lv.Release();
		m_lv.Attach( reinterpret_cast< LabVIEW::_Application* >( mq[ 0 ].pItf ) ); 
		std::cerr << "Successfully connected to LabVIEW on " << m_host << std::endl;
	}
	else
	{
		std::cerr << "(Re)Making local connection to LabVIEW" << std::endl;
		m_pidentity = NULL;
		m_lv.Release();
		hr = m_lv.CoCreateInstance(m_clsid, NULL, CLSCTX_LOCAL_SERVER);
		if( FAILED( hr ) ) 
		{
			throw COMexception("CoCreateInstance (LabVIEW) ", hr);
		} 
		std::cerr << "Successfully connected to local LabVIEW" << std::endl;
	}
	if (reentrant)
	{
		vi = m_lv->GetVIReference(vi_name, "", 1, 8);
		setIdentity(m_pidentity, vi);
	}
	else
	{
		//If a VI is reentrant then always get it as reentrant
		vi = m_lv->GetVIReference(vi_name, "", 0, 0);
		setIdentity(m_pidentity, vi);
		if (vi->IsReentrant)
		{
			vi = m_lv->GetVIReference(vi_name, "", 1, 8);
			setIdentity(m_pidentity, vi);
			reentrant = true;
		}
	}
	ViRef viref(vi, reentrant, false);
	// LabVIEW::ExecStateEnum::eIdle = 1
	// LabVIEW::ExecStateEnum::eRunTopLevel = 2
	if (vi->ExecState == LabVIEW::eIdle)
	{
		if ( checkOption(viStartIfIdle) ) 
		{
			std::cerr << "Starting \"" << CW2CT(vi_name) << "\" on " << (m_host.size() > 0 ? m_host : "localhost") << std::endl;
			vi->Run(true);
			viref.started = true;
		}
		else if ( checkOption(viWarnIfIdle) )
		{
			std::cerr << "\"" << CW2CT(vi_name) << "\" is not running on " << (m_host.size() > 0 ? m_host : "localhost") << " and autostart is disabled" << std::endl;
		}
	}
	m_vimap[ws] = viref;
}
Ejemplo n.º 17
0
bool QXmppSaslClientDigestMd5::respond(const QByteArray &challenge, QByteArray &response)
{
    Q_UNUSED(challenge);
    const QByteArray digestUri = QString("%1/%2").arg(serviceType(), host()).toUtf8();

    if (m_step == 0) {
        response = QByteArray();
        m_step++;
        return true;
    } else if (m_step == 1) {
        const QMap<QByteArray, QByteArray> input = QXmppSaslDigestMd5::parseMessage(challenge);

        if (!input.contains("nonce")) {
            warning("QXmppSaslClientDigestMd5 : Invalid input on step 1");
            return false;
        }

        // determine realm
        const QByteArray realm = input.value("realm");

        // determine quality of protection
        const QList<QByteArray> qops = input.value("qop", "auth").split(',');
        if (!qops.contains("auth")) {
            warning("QXmppSaslClientDigestMd5 : Invalid quality of protection");
            return false;
        }

        m_nonce = input.value("nonce");
        m_secret = QCryptographicHash::hash(
            username().toUtf8() + ":" + realm + ":" + password().toUtf8(),
            QCryptographicHash::Md5);

        // Build response
        QMap<QByteArray, QByteArray> output;
        output["username"] = username().toUtf8();
        if (!realm.isEmpty())
            output["realm"] = realm;
        output["nonce"] = m_nonce;
        output["qop"] = "auth";
        output["cnonce"] = m_cnonce;
        output["nc"] = m_nc;
        output["digest-uri"] = digestUri;
        output["response"] = calculateDigest("AUTHENTICATE", digestUri, m_secret, m_nonce, m_cnonce, m_nc);
        output["charset"] = "utf-8";

        response = QXmppSaslDigestMd5::serializeMessage(output);
        m_step++;
        return true;
    } else if (m_step == 2) {
        const QMap<QByteArray, QByteArray> input = QXmppSaslDigestMd5::parseMessage(challenge);

        // check new challenge
        if (input.value("rspauth") != calculateDigest(QByteArray(), digestUri, m_secret, m_nonce, m_cnonce, m_nc)) {
            warning("QXmppSaslClientDigestMd5 : Invalid challenge on step 2");
            return false;
        }

        response = QByteArray();
        m_step++;
        return true;
    } else {
        warning("QXmppSaslClientDigestMd5 : Invalid step");
        return false;
    }
}
Ejemplo n.º 18
0
int main(int argc, char ** argv)
{
#ifdef WIN32
	SetUnhandledExceptionFilter( UnhandledExceptionProc );
#endif

	std::unique_ptr<SplashWindow> splashWindow;

	try{

		// start recording backtrace
		spades::reflection::Backtrace::StartBacktrace();
		SPADES_MARK_FUNCTION();

		// show splash window
		// NOTE: splash window uses image loader, which assumes backtrace is already initialized.
		splashWindow.reset(new SplashWindow());
		auto showSplashWindowTime = SDL_GetTicks();
		auto pumpEvents = [&splashWindow] { splashWindow->PumpEvents(); };

		// initialize threads
		spades::Thread::InitThreadSystem();
		spades::DispatchQueue::GetThreadQueue()->MarkSDLVideoThread();

		SPLog("Package: " PACKAGE_STRING);

		// setup user-specific default resource directories
#ifdef WIN32
		static wchar_t buf[4096];
		GetModuleFileNameW(NULL, buf, 4096);
		std::wstring appdir = buf;
		appdir = appdir.substr(0, appdir.find_last_of(L'\\')+1);

		if(SUCCEEDED(SHGetFolderPathW(NULL, CSIDL_APPDATA, NULL, 0, buf))){
			std::wstring datadir = buf;
			datadir += L"\\OpenSpades\\Resources";
			spades::FileManager::AddFileSystem(new spades::DirectoryFileSystem(Utf8FromWString(datadir.c_str()), true));
		}
		
		spades::FileManager::AddFileSystem(new spades::DirectoryFileSystem(Utf8FromWString((appdir + L"Resources").c_str()), false));
		
		//fltk has a console window on windows (can disable while building, maybe use a builtin console for a later release?)
		HWND hCon = GetConsoleWindow();
		if( NULL != hCon ) {
			setIcon( hCon );
		}

#elif defined(__APPLE__)
		std::string home = getenv("HOME");
		spades::FileManager::AddFileSystem
		(new spades::DirectoryFileSystem("./Resources", false));

		// OS X application is made of Bundle, which contains its own Resources directory.
		{
			char *baseDir = SDL_GetBasePath();
			if(baseDir) {
				spades::FileManager::AddFileSystem
				(new spades::DirectoryFileSystem(baseDir, false));
				SDL_free(baseDir);
			}
		}

		spades::FileManager::AddFileSystem
		(new spades::DirectoryFileSystem(home+"/Library/Application Support/OpenSpades/Resources", true));
#else
		std::string home = getenv("HOME");

		spades::FileManager::AddFileSystem
		(new spades::DirectoryFileSystem("./Resources", false));

		spades::FileManager::AddFileSystem
		(new spades::DirectoryFileSystem("/usr/local/share/games/openspades/Resources", false));

		spades::FileManager::AddFileSystem
		(new spades::DirectoryFileSystem("/usr/share/games/openspades/Resources", false));


		std::string xdg_data_home = home+"/.local/share";

		if (getenv("XDG_DATA_HOME") == NULL) {
			SPLog("XDG_DATA_HOME not defined. Assuming that XDG_DATA_HOME is ~/.local/share");
		}
		else {
			std::string xdg_data_home = getenv("XDG_DATA_HOME");
			SPLog("XDG_DATA_HOME is %s", xdg_data_home.c_str());
		}

		struct stat info;

		if ( stat((xdg_data_home+"/openspades").c_str(), &info ) != 0 ) {
			if ( stat((home+"/.openspades").c_str(), &info ) != 0) { }
			else if( info.st_mode & S_IFDIR ) {
				SPLog("Openspades directory in XDG_DATA_HOME not found, though old directory exists. Trying to resolve compatibility problem.");

				if (rename( (home+"/.openspades").c_str() , (xdg_data_home+"/openspades").c_str() ) != 0) {
					SPLog("Failed to move old directory to new.");
				} else {
					SPLog("Successfully moved old directory.");

					if (mkdir((home+"/.openspades").c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) == 0) {
						SDL_RWops *io = SDL_RWFromFile((home+"/.openspades/CONTENT_MOVED_TO_NEW_DIR").c_str(), "wb");
						if (io != NULL) {
							const char* text = ("Content of this directory moved to "+xdg_data_home+"/openspades").c_str();
							io->write(io, text, strlen(text), 1);
							io->close(io);
						}
					}
				}
			}
		}

		spades::FileManager::AddFileSystem
		(new spades::DirectoryFileSystem(xdg_data_home+"/openspades/Resources", true));

#endif

		// start log output to SystemMessages.log
		try{
			spades::StartLog();
		}catch(const std::exception& ex){

			SDL_InitSubSystem(SDL_INIT_VIDEO);
			auto msg = spades::Format("Failed to start recording log because of the following error:\n{0}\n\n"
									  "OpenSpades will continue to run, but any critical events are not logged.", ex.what());
			if(SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_WARNING,
										"OpenSpades Log System Failure",
										msg.c_str(), splashWindow->GetWindow())) {
				// showing dialog failed.
			}
		}
		SPLog("Log Started.");

		// load preferences.
		spades::Settings::GetInstance()->Load();
		pumpEvents();

		// dump CPU info (for debugging?)
		{
			spades::CpuID cpuid;
			SPLog("---- CPU Information ----");
			SPLog("Vendor ID: %s", cpuid.GetVendorId().c_str());
			SPLog("Brand ID: %s", cpuid.GetBrand().c_str());
			SPLog("Supports MMX: %s", cpuid.Supports(spades::CpuFeature::MMX)?"YES":"NO");
			SPLog("Supports SSE: %s", cpuid.Supports(spades::CpuFeature::SSE)?"YES":"NO");
			SPLog("Supports SSE2: %s", cpuid.Supports(spades::CpuFeature::SSE2)?"YES":"NO");
			SPLog("Supports SSE3: %s", cpuid.Supports(spades::CpuFeature::SSE3)?"YES":"NO");
			SPLog("Supports SSSE3: %s", cpuid.Supports(spades::CpuFeature::SSSE3)?"YES":"NO");
			SPLog("Supports FMA: %s", cpuid.Supports(spades::CpuFeature::FMA)?"YES":"NO");
			SPLog("Supports AVX: %s", cpuid.Supports(spades::CpuFeature::AVX)?"YES":"NO");
			SPLog("Supports AVX2: %s", cpuid.Supports(spades::CpuFeature::AVX2)?"YES":"NO");
			SPLog("Supports AVX512F: %s", cpuid.Supports(spades::CpuFeature::AVX512F)?"YES":"NO");
			SPLog("Supports AVX512CD: %s", cpuid.Supports(spades::CpuFeature::AVX512CD)?"YES":"NO");
			SPLog("Supports AVX512ER: %s", cpuid.Supports(spades::CpuFeature::AVX512ER)?"YES":"NO");
			SPLog("Supports AVX512PF: %s", cpuid.Supports(spades::CpuFeature::AVX512PF)?"YES":"NO");
			SPLog("Simultaneous Multithreading: %s", cpuid.Supports(spades::CpuFeature::SimultaneousMT)?"YES":"NO");
			SPLog("Misc:");
			SPLog("%s", cpuid.GetMiscInfo().c_str());
			SPLog("-------------------------");
		}

		// register resource directory specified by Makefile (or something)
#if defined(RESDIR_DEFINED) && !NDEBUG
		spades::FileManager::AddFileSystem(new spades::DirectoryFileSystem(RESDIR, false));
#endif

		// search current file system for .pak files
		{
			std::vector<spades::IFileSystem*> fss;
			std::vector<spades::IFileSystem*> fssImportant;

			std::vector<std::string> files = spades::FileManager::EnumFiles("");

			struct Comparator {
				static int GetPakId(const std::string& str) {
					if(str.size() >= 4 && str[0] == 'p' &&
					   str[1] == 'a' && str[2] == 'k' &&
					   (str[3] >= '0' && str[3] <= '9')){
						return atoi(str.c_str() + 3);
					}else{
						return 32767;
					}
				}
				static bool Compare(const std::string& a,
									const std::string& b) {
					int pa = GetPakId(a);
					int pb = GetPakId(b);
					if(pa == pb){
						return a < b;
					}else{
						return pa < pb;
					}
				}
			};

			std::sort(files.begin(), files.end(), Comparator::Compare);

			for(size_t i = 0; i < files.size(); i++){
				std::string name = files[i];

				// check extension
				if(name.size() < 4 ||
				   name.rfind(".pak") != name.size() - 4){
					continue;
				}

				if(spades::FileManager::FileExists(name.c_str())) {
					spades::IStream *stream = spades::FileManager::OpenForReading(name.c_str());
					spades::ZipFileSystem *fs = new spades::ZipFileSystem(stream);
					if(name[0] == '_' && false) { // last resort for #198
						SPLog("Pak Registered: %s (marked as 'important')\n", name.c_str());
						fssImportant.push_back(fs);
					}else{
						SPLog("Pak Registered: %s\n", name.c_str());
						fss.push_back(fs);
					}
				}
			}
			for(size_t i = fss.size(); i > 0; i--){
				spades::FileManager::AppendFileSystem(fss[i - 1]);
			}
			for(size_t i = 0; i < fssImportant.size(); i++){
				spades::FileManager::PrependFileSystem(fssImportant[i]);
			}
		}
		pumpEvents();

		// initialize localization system
		SPLog("Initializing localization system");
		spades::LoadCurrentLocale();
		_Tr("Main", "Localization System Loaded");
		pumpEvents();

		// parse args
		for(int i = 1; i < argc;) {
			int ret = argsHandler(argc, argv, i);
			if(!ret) {
				// ignore unknown arg
				i++;
			}
		}

		// initialize AngelScript
		SPLog("Initializing script engine");
		spades::ScriptManager::GetInstance();
		pumpEvents();

		ThreadQuantumSetter quantumSetter;
		(void)quantumSetter; // suppress "unused variable" warning

		SDL_InitSubSystem(SDL_INIT_VIDEO);

		// we want to show splash window at least for some time...
		pumpEvents();
		auto ticks = SDL_GetTicks();
		if(ticks < showSplashWindowTime + 1500) {
			SDL_Delay(showSplashWindowTime + 1500 - ticks);
		}
		pumpEvents();

		// everything is now ready!
		if( !cg_autoConnect ) {
			if(!((int)cl_showStartupWindow != 0 ||
				 splashWindow->IsStartupScreenRequested())) {
				splashWindow.reset();

				SPLog("Starting main screen");
				spades::StartMainScreen();
			}else{
				splashWindow.reset();

				SPLog("Starting startup window");
				::spades::gui::StartupScreen::Run();
			}
		} else {
			splashWindow.reset();

			spades::ServerAddress host(cg_lastQuickConnectHost.CString(), (int)cg_protocolVersion == 3 ? spades::ProtocolVersion::v075 : spades::ProtocolVersion::v076 );
			spades::StartClient(host, cg_playerName);
		}

		spades::Settings::GetInstance()->Flush();

	}catch(const ExitRequestException&){
		// user changed his mind.
	}catch(const std::exception& ex) {

		try {
			splashWindow.reset(nullptr);
		}catch(...){
		}

		std::string msg = ex.what();
		msg = _Tr("Main", "A serious error caused OpenSpades to stop working:\n\n{0}\n\nSee SystemMessages.log for more details.", msg);

		SPLog("[!] Terminating due to the fatal error: %s", ex.what());

		SDL_InitSubSystem(SDL_INIT_VIDEO);
		if(SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, _Tr("Main", "OpenSpades Fatal Error").c_str(), msg.c_str(), nullptr)) {
			// showing dialog failed.
			// TODO: do appropriate action
		}

	}

    return 0;
}
Ejemplo n.º 19
0
bool EClientSocket::eConnectImpl(int clientId, bool extraAuth, ConnState* stateOutPt)
{
	// resolve host
	struct hostent* hostEnt = gethostbyname( host().c_str());
	if ( !hostEnt) {
		getWrapper()->error( NO_VALID_ID, CONNECT_FAIL.code(), CONNECT_FAIL.msg());
		return false;
	}

	// create socket
	m_fd = socket(AF_INET, SOCK_STREAM, 0);

	// cannot create socket
	if( m_fd < 0) {
		getWrapper()->error( NO_VALID_ID, FAIL_CREATE_SOCK.code(), FAIL_CREATE_SOCK.msg());
		return false;
	}

	// starting to connect to server
	struct sockaddr_in sa;
	memset( &sa, 0, sizeof(sa));
	sa.sin_family = AF_INET;
	sa.sin_port = htons( port());
	sa.sin_addr.s_addr = ((in_addr*)hostEnt->h_addr)->s_addr;

	// try to connect
	if( (connect( m_fd, (struct sockaddr *) &sa, sizeof( sa))) < 0) {
		// error connecting
		SocketClose( m_fd);
		m_fd = -1;
		getWrapper()->error( NO_VALID_ID, CONNECT_FAIL.code(), CONNECT_FAIL.msg());
		return false;
	}

    getTransport()->fd(m_fd);

	// set client id
	setClientId( clientId);
	setExtraAuth( extraAuth);

    int res = sendConnectRequest();

    if (res < 0 && !handleSocketError())
        return false;

	if( !isConnected()) {
		if( connState() != CS_DISCONNECTED) {
			assert( connState() == CS_REDIRECT);
			if( stateOutPt) {
				*stateOutPt = connState();
			}
			eDisconnect();
		}
		return false;
	}

	// set socket to non-blocking state
	if ( !SetSocketNonBlocking(m_fd)) {
	// error setting socket to non-blocking
		eDisconnect();
		getWrapper()->error( NO_VALID_ID, CONNECT_FAIL.code(), CONNECT_FAIL.msg());
		return false;
	}

	assert( connState() == CS_CONNECTED);
	if( stateOutPt) {
		*stateOutPt = connState();
	}
            
    if (!m_asyncEConnect) {
        EReader reader(this, m_pSignal);

        while (m_pSignal && !m_serverVersion && isSocketOK()) {
            reader.checkClient();
            m_pSignal->waitForSignal();
            reader.processMsgs();
        }
    }

	// successfully connected
	return isSocketOK();
}
Ejemplo n.º 20
0
KAQueryList &
KAQuery::getFileList() const
{
  KAQueryFile *file;
  KAQueryList *filelist = new KAQueryList;
  QDate date;
  QTime time;
  //  QDateTime datetime;
  VLINK tmplink = queryresult;
  /* (from archie/procquery.c)         */
  PATTRIB     ap;
  int         size = 0;
  char        *modes = "";
  char        *gt_date = "";
  int         gt_year = 0;
  int         gt_mon = 0;
  int         gt_day = 0;
  int         gt_hour = 0;
  int         gt_min = 0;

  while (tmplink != 0) {
    /* Parse the attibutes of this link
     * (from archie/procquery.c)         */
    for (ap = tmplink->lattrib; ap; ap = ap->next) {
	if (strcmp(ap->aname,"SIZE") == 0) {
#ifdef MSDOS
	  sscanf(ap->value.ascii,"%lu",&size);
#else
	  sscanf(ap->value.ascii,"%d",&size);
#endif
	} else if(strcmp(ap->aname,"UNIX-MODES") == 0) {
	    modes = ap->value.ascii;
	} else if(strcmp(ap->aname,"LAST-MODIFIED") == 0) {
	    gt_date = ap->value.ascii;
	    sscanf(gt_date,"%4d%2d%2d%2d%2d", &gt_year,
		   &gt_mon, &gt_day, &gt_hour, &gt_min);
	    /*
	    if ((12 * (presenttime->tm_year + 1900 - gt_year) + 
					presenttime->tm_mon - gt_mon) > 6) 
		sprintf(archie_date,"%s %2d %4d",month_sname(gt_mon),
			gt_day, gt_year);
	    else
		sprintf(archie_date,"%s %2d %02d:%02d",month_sname(gt_mon),
			 gt_day, gt_hour, gt_min);
			 */
	}
    }
    
    date.setYMD(gt_year, gt_mon, gt_day);
    time.setHMS(gt_hour, gt_min, 0);
    //datetime.setTime( time );
    //datetime.setDate( date );
    QString host(tmplink->host);
    QString path(tmplink->filename);
    int slash_index = path.findRev('/');
    QString filename( path.right( path.length() - slash_index -1 ));
    path.resize( slash_index +2 );
    file = new KAQueryFile( host, path, filename, size, modes, date, time );
    filelist->append( file );
    tmplink = tmplink->next;
  }

  return *filelist;
}
Ejemplo n.º 21
0
void CapturePacketThread::HttpPacketHandler(std::ext_string httpdatastr,IpPacket *ipobj,u_int httpdatalen)
{
    vector<ext_string> linessplit = httpdatastr.split("\n");
    ext_string url("") ;
    ext_string host("");
    
    bool ispost = false;
    ext_string httppostdata("");

    ext_string hostprefix("host:");
    ext_string getprefix("get /");
    ext_string postprefix("post /");

    for (std::vector<ext_string>::iterator it = linessplit.begin() ; it != linessplit.end(); ++it)
    {
       ext_string currline = *it;
       currline.tolower();

       if(currline.substr(0, hostprefix.size()) == hostprefix)
       {
            std::vector<ext_string> tmp = currline.split(" ");
			if(tmp.size()>=2)
                host = tmp[1].trim();
       }
       else if(currline.substr(0, getprefix.size()) == getprefix)
       {
            std::vector<ext_string> tmp = currline.split(" ");
            if(tmp.size()>=2)
                url = tmp[1].trim();
       }
       else if(currline.substr(0, postprefix.size()) == postprefix)
       {
            ispost = true;
            std::vector<ext_string> tmp = currline.split(" ");
            if(tmp.size()>=2)
                url = tmp[1].trim();
	   }
    }
	//int ByVarNum = url.length() + 1;
	//byte *ByVar;
	//ByVar = (byte *)malloc(sizeof(byte)*ByVarNum);
	//memset(ByVar,0,ByVarNum);
	//byte ByVar[255] = {0};
	//for (int i=0;i<url.length();i++)
	//{
	//	ByVar[i] =(byte)url[i];
	//}
    ext_string httpurl_ext = "http://"+host+url;
	//httpurl_ext.append((char *)ByVar);
	if(httpurl_ext.length()>7)
	{
	  HttpPacket* httpobj = new HttpPacket();
	  httpobj->set_processname(ipobj->processname());
	  httpobj->set_processmd5(ipobj->processmd5());
	  httpobj->set_sip(ipobj->sip());
	  httpobj->set_dip(ipobj->dip());
	  httpobj->set_sport(ipobj->sport());
	  httpobj->set_dport(ipobj->dport());
	  httpobj->set_datetime(ipobj->datetime());
	  httpobj->set_httpurl(httpurl_ext.c_str());
	  pfthread->PostThreadMessage(PROTOBUF_HTTP_MESSAGE, 0, (LPARAM)httpobj);
	  httpobj=NULL;
	}
    //CLogMod::SharedInstance()->LogInfo(httpurl_ext.c_str());
	//#BUG print bug here
   // cout<<"httpurl_ext:"<<httpurl_ext<<endl;
}
Ejemplo n.º 22
0
int main(int argc, char **argv) {

  if (argc > 3) {
    std::cout << "test_client [server [port]]" << std::endl;
    return -1;
  }
  
  std::string server = "localhost";
  unsigned short port = 8080;

  if (argc >= 2) {
    server = argv[1];
  }

  if (argc >= 3) {
    sscanf(argv[2], "%hu", &port);
  }

  gnet::Initialize();

  try {
    /*
    std::cout << "Create socket" << std::endl;
    Nett::Socket socket(server, 8080);
    
    std::cout << "Connect to socket" << std::endl;
    gnet::Connection conn = socket.connect();
    
    std::cout << "Send data to socket" << std::endl;
    conn.write(content.c_str(), content.length());
    */
    bool end = false;
    
    std::cout << "Get Host...";
    gnet::Host host(server, port);
    std::cout << "DONE: " << host.address() << ":" << host.port() << std::endl;
    
    gnet::TCPSocket socket(host);
    
    std::cout << "Connect to server...";
    gnet::TCPConnection *conn = socket.connect();
    std::cout << "DONE" << std::endl;
    
    while (!end) {
      
      char buffer[512];
      
      if (!fgets(buffer, 512, stdin)) {
        end = true;
        continue;
      }
      
      size_t len = strlen(buffer);
      if (len > 0 && buffer[len-1] == '\n') {
        buffer[len-1] = '\0';
      }
      
      if (!strcmp(buffer, "QUIT")) {
        end = true;
        continue;
      }
      
      std::cout << "Send data: \"" << buffer << "\"...";
      conn->write(buffer, len-1);
      std::cout << "DONE" << std::endl;
      
      // to check if connection is alive
      // do a non-blocking read, and check for 0 result
      // read(fd, buffer, len, MSG_NONBLOCK) == 0
  
    }
      
    std::cout << "Close connection...";
    socket.closeConnection(conn);
    std::cout << "DONE" << std::endl;
    
  } catch (std::exception &e) {
    
    std::cout << e.what() << std::endl;
  }
  
  gnet::Uninitialize();
  
  return 0;
}
Ejemplo n.º 23
0
bool HostAndPort::operator==(const HostAndPort& r) const {
    return host() == r.host() && port() == r.port();
}
Ejemplo n.º 24
0
Address::Address(const string& address) : host(4),port(0) {
	// port
	size_t pos = address.find_last_of(':');
	if(pos!=string::npos)
		((UInt16&)port) = atoi(&address.c_str()[pos+1]);
	else
		pos = address.size();

	string host(address,0,pos);

	// host
	if(host.find_first_of(':')==string::npos) {
		// IPv4
		StringTokenizer split(host,".",StringTokenizer::TOK_TRIM);
		StringTokenizer::Iterator it;
		int i=0;
		for(it=split.begin();it!=split.end();++it) {
			if(i>=this->host.size())
				return;
			((vector<UInt8>&)this->host)[i++] = atoi(it->c_str());
		}
	} else {
		// IPv6
		((vector<UInt8>&)this->host).resize(16);
		size_t first = host.find_first_of('[');
		if(first == string::npos)
			first = 0;
		else
			++first;
		size_t size = host.find_first_of(']');
		if(size == string::npos)
			size = host.size()-first;
		else
			size -= first;
		StringTokenizer split(string(host,first,size),":",StringTokenizer::TOK_TRIM);
		StringTokenizer::Iterator it;
		int i=0;
		for(it=split.begin();it!=split.end();++it) {
			string temp(*it);
			int delta = 4-it->size();
			if(delta>0)
				temp.insert(0,string(delta,'0'));

			int c = 0;
			for(int j=0;j<4;++j) {
				int n = temp[j];
				if (n >= '0' && n <= '9')
					c |= n - '0';
				else if (n >= 'A' && n <= 'F')
					c |= n - 'A' + 10;
				else if (n >= 'a' && n <= 'f')
					c |= n - 'a' + 10;
				if(j%2==0)
					c <<= 4;
				else {
					if(i>=this->host.size())
						return;
					((vector<UInt8>&)this->host)[i++] = c;
					c = 0;
				}
			}
		}
	}
}
Ejemplo n.º 25
0
ShadowTree* ShadowRoot::tree() const
{
    if (host())
        return host()->shadowTree();
    return 0;
}
Ejemplo n.º 26
0
QString IrcUser::hostmask() const
{
    return QString("%1!%[email protected]%3").arg(nick()).arg(user()).arg(host());
}
Ejemplo n.º 27
0
std::vector<condor_sockaddr> resolve_hostname(const char* hostname)
{
	MyString host(hostname);
	return resolve_hostname(host);
}
Ejemplo n.º 28
0
int main(int argc, char** argv)
{
	const int NUM_ARGS = 3;

	if (argc != NUM_ARGS+1)
	{
	    printUsage(argc, argv);
	    return 1;
	}
	string infilename(argv[1]);
	string outfilename(argv[2]);
	int iterations = atoi(argv[3]);

	PatternBlock tblock;
	FieldReader reader;

	byte *in = new byte[(NUMBER_OF_ROWS+2)*(NUMBER_OF_COLS+2)];
#ifdef MEASUREMENTS
	byte *cpuout = new byte[(NUMBER_OF_ROWS+2)*(NUMBER_OF_COLS+2)];
#endif

	assert(reader.readFile(infilename));
	assert(reader.buildField(in,NUMBER_OF_COLS+2,NUMBER_OF_ROWS+2)); //< leave dead margin
	clearMargin(in,NUMBER_OF_COLS+2,NUMBER_OF_ROWS+2);

#ifdef MEASUREMENTS
	writeBufToFile(outfilename,"in",in,NUMBER_OF_COLS,NUMBER_OF_ROWS);
#endif

	byte *gpuout = host(in,iterations);
#ifndef MEASUREMENTS
	writeBufToFile(outfilename,gpuout,NUMBER_OF_COLS,NUMBER_OF_ROWS);
#else
	writeBufToFile(outfilename,"gpu",gpuout,NUMBER_OF_COLS,NUMBER_OF_ROWS);

	cpuSim(iterations,in,cpuout,NUMBER_OF_COLS,NUMBER_OF_ROWS);
	if (iterations % 2 == 0) {
		byte *tmp = cpuout;
		cpuout = in;
		in = tmp;
	}

	writeBufToFile(outfilename,"cpu",cpuout,NUMBER_OF_COLS,NUMBER_OF_ROWS);

	int errors = 0;
	for(int j=0;j<NUMBER_OF_ROWS;j++) {
		for(int i=0;i<NUMBER_OF_COLS;i++) {
			if (cpuout[(j+1)*(NUMBER_OF_COLS+2) + (i+1)] != gpuout[(j+1)*(NUMBER_OF_COLS+2) + (i+1)]) {
				errors +=1;
				std::cout << "fucked " << j << " " << i << " (CPU=[" << (int)(cpuout[(j+1)*(NUMBER_OF_COLS+2) + (i+1)]) << "],GPU=[" << (int)(gpuout[(j+1)*(NUMBER_OF_COLS+2) + (i+1)]) << "])\n";
				if (errors == 5)
					break;
			}
		}
		if (errors == 5)
			break;
	}

	if(errors > 0) {
		std::cout << "Errors Detected" << "\n";
	} else {
		std::cout << "all good\n";
	}

	delete[] cpuout;
#endif

	delete[] in;
	delete[] gpuout;

	return 0;
}
Ejemplo n.º 29
0
	virtual void post(
		ResponsePtr responder,
		const LLSD& context,
		const LLSD& input) const
	{
		LLHost host(input["sender"].asString());
		LLViewerRegion* region = LLWorld::getInstance()->getRegion(host);
		if( !region )
		{
			return;
		}

		S32 target_index = input["body"]["Index"][0]["Prey"].asInteger();
		S32 you_index    = input["body"]["Index"][0]["You" ].asInteger();

		LLDynamicArray<U32>* avatar_locs = &region->mMapAvatars;
		LLDynamicArray<LLUUID>* avatar_ids = &region->mMapAvatarIDs;
		avatar_locs->reset();
		avatar_ids->reset();

		//llinfos << "coarse locations agent[0] " << input["body"]["AgentData"][0]["AgentID"].asUUID() << llendl;
		//llinfos << "my agent id = " << gAgent.getID() << llendl;
		//llinfos << ll_pretty_print_sd(input) << llendl;

		LLSD 
			locs   = input["body"]["Location"],
			agents = input["body"]["AgentData"];
		LLSD::array_iterator 
			locs_it = locs.beginArray(), 
			agents_it = agents.beginArray();
		BOOL has_agent_data = input["body"].has("AgentData");

		for(int i=0; 
			locs_it != locs.endArray(); 
			i++, locs_it++)
		{
			U8 
				x = locs_it->get("X").asInteger(),
				y = locs_it->get("Y").asInteger(),
				z = locs_it->get("Z").asInteger();
			// treat the target specially for the map, and don't add you or the target
			if(i == target_index)
			{
				LLVector3d global_pos(region->getOriginGlobal());
				global_pos.mdV[VX] += (F64)x;
				global_pos.mdV[VY] += (F64)y;
				global_pos.mdV[VZ] += (F64)z * 4.0;
				LLAvatarTracker::instance().setTrackedCoarseLocation(global_pos);
			}
			else if( i != you_index)
			{
				U32 loc = x << 16 | y << 8 | z; loc = loc;
				U32 pos = 0x0;
				pos |= x;
				pos <<= 8;
				pos |= y;
				pos <<= 8;
				pos |= z;
				avatar_locs->put(pos);
				//llinfos << "next pos: " << x << "," << y << "," << z << ": " << pos << llendl;
				if(has_agent_data) // for backwards compatibility with old message format
				{
					LLUUID agent_id(agents_it->get("AgentID").asUUID());
					//llinfos << "next agent: " << agent_id.asString() << llendl;
					avatar_ids->put(agent_id);
				}
			}
			if (has_agent_data)
			{
				agents_it++;
			}
		}
	}
Ejemplo n.º 30
0
void IRC_Session::on_connected() {
    ChanList["status"]->append("CONNECTED",host(),"Connection Established..");
    emit event_connected(this);
    return;
}