Example #1
0
File: sos.c Project: andlt/MC658
void sos (int *sol, int cur_sum, int k, int sum_left, int *w, int W, int n)
{
/* Função limitante do Backtracking. Recebe a solução em contrução (sol), o somatório de itens atualmente inseridos no conjunto (cur_sum), a próxima dimensão da tupla a ser fixada (k) e o somatório de itens que ainda podem ser adicionados (sum_left) */

	int i = 0;

	/* Considera as soluções com o k-ésimo item */

	//printf("\n\nRecursão: k: %d\n", k);

	sol[k] = 1;
	//printf("cur_sum: %d, w[%d]: %d, W: %d\n", cur_sum, k, w[k], W);

	if (cur_sum + w[k] == W)
	{
		printf("\nSolução econtrada:\n");
		for (i = 0; i < n; i++)
		{
			if(sol[i] == 1)
				printf("%d ", w[i]);
		}
		printf("\n\n");
	}
	else
	{
		//printf("\nk: %d, n-1: %d\n", k, n-1);
		if(k < n-1)
		{
			//printf("cur_sum: %d + w[%d]: %d + w[%d]: %d <= W: %d\n?", cur_sum, k, w[k], k+1, w[k+1], W);
			if (cur_sum + w[k] + w[k+1] <= W)
			{
				sos(sol, cur_sum + w[k], k+1, sum_left - w[k], w, W, n);
			}
		}
	}

	/* Considera as soluções sem o k-ésimo item */

	sol[k] = 0;

	if(k < n-1)
	{
		if ((cur_sum + sum_left - w[k] >= W) && (cur_sum + w[k+1] <= W))
		{
			sos(sol, cur_sum, k+1, sum_left - w[k], w, W, n);
		}
	}
}
Example #2
0
wxArrayString KissMangaCom::GetPageLinks(wxString ChapterLink)
{
    wxArrayString pageLinks;

    CurlRequest cr;
    cr.SetUrl(ChapterLink);
    cr.SetAgent(agent);
    cr.SetCookies(cookies);
    cr.SetCompression(wxT("gzip"));
    wxString content;
    wxStringOutputStream sos(&content);
    cr.SetOutputStream(&sos);
    cr.ExecuteRequest();

    int indexStart = content.find(wxT("var lstImages")) + 13;
    int indexEnd = content.find(wxT("var lstImagesLoaded"), indexStart);

    if(indexStart > 12 && indexEnd > -1)
    {
        content = content.Mid(indexStart, indexEnd-indexStart);
        indexEnd = 0;

        // Example Entry: lstImages.push("http://2.bp.blogspot.com/-m2wUve_VBR8/VsFJRUDLJiI/AAAAAAAFMGc/7HfBG-sFqVA/s16000-Ic42/000.png");
        while((indexStart = content.find(wxT("lstImages.push(\""), indexEnd)) > -1)
        {
            indexStart += 16;
            indexEnd = content.find(wxT("\""), indexStart); // "\""
            pageLinks.Add(content.Mid(indexStart, indexEnd-indexStart));

            //wxYield();
        }
    }

    return pageLinks;
}
Example #3
0
wxUint32 KissMangaCom::GetMangaListPageCount()
{
    unsigned long result = 500;

    CurlRequest cr;
    cr.SetUrl(baseURL + wxT("/MangaList"));
    cr.SetAgent(agent);
    cr.SetCookies(cookies);
    cr.SetCompression(wxT("gzip"));
    wxString content;
    wxStringOutputStream sos(&content);
    cr.SetOutputStream(&sos);
    cr.ExecuteRequest();

    int indexStart = content.find(wxT("class=\"pager\"")) + 13;
    indexStart = content.find(wxT("</ul>"), indexStart);
    indexStart = content.rfind(wxT("page="), indexStart) + 6;
    int indexEnd = content.find(wxT("\""), indexStart);
    if(indexStart > 5 && indexEnd > -1) {
        content = content.Mid(indexStart, indexEnd-indexStart);
        if(content.IsNumber() && content.ToULong(&result)){
            return (wxUint32)result;
        }
    }

    Logger::Log(wxT("ERROR +++ KissMangaCom::GetMangaListPageCount() -> Cannot find last page of manga list"));
    return (wxUint32)result;
}
Example #4
0
File: sos.c Project: andlt/MC658
int main ()
{
	int n = 0;
	int W = 0;
	int *w = NULL;
	int *sol = NULL;
	int i = 0;
	int total_sum = 0;

	printf("\nEntre com o tamanho n do conjunto:\n");
	scanf("%d", &n);

	printf("\nEntre com os %d valores:\n", n);
	w = malloc(sizeof(int) * n);
	for (i = 0; i < n; i++)
	{
		scanf("%d", &w[i]);
	}

	printf("\nEntre com o valor W alvo:\n");
	scanf("%d", &W);

	sol = malloc(sizeof(int) * n);
	for (i = 0; i < n; i++)
	{
		sol[i] = 0;
		total_sum = total_sum + w[i];
	}	

	//ordenar w do menor para o maior

	sos(sol, 0, 0, total_sum, w, W, n);

	return 0;
}
Example #5
0
wxArrayMCEntry KissMangaCom::GetChapterList(MCEntry* MangaEntry)
{
    wxArrayMCEntry chapterList;

    wxString volumePrefix;
    wxString chNumber;
    wxString chEntry;
    wxString chTitle;
    wxString chLink;

    CurlRequest cr;
    cr.SetUrl(MangaEntry->Link);
    cr.SetAgent(agent);
    cr.SetCookies(cookies);
    cr.SetCompression(wxT("gzip"));
    wxString content;
    wxStringOutputStream sos(&content);
    cr.SetOutputStream(&sos);
    cr.ExecuteRequest();

    int indexStart = content.find(wxT("class=\"listing\"")) + 15;
    int indexEnd = content.find(wxT("</table>"), indexStart);

    if(indexStart > 14 && indexEnd > -1)
    {
        content = content.Mid(indexStart, indexEnd-indexStart);
        indexEnd = 0;

        //Example Entry:
        /*
        <a href="/Manga/–-and-–/Vol-003-Ch-014-Read-Online?id=209953" title="Read &amp; – and – Vol.003 Ch.014 Read Online online">& – and – Vol.003 Ch.014 Read Online</a>
        <a href="/Manga/One-Piece/823---A-World-Abuzz?id=270460" title="Read One Piece 823 - A World Abuzz online">One Piece 823 - A World Abuzz</a>
        */
        while((indexStart = content.find(wxT("<a href=\""), indexEnd)) > -1)
        {
            indexStart += 9;
            indexEnd = content.find(wxT("\""), indexStart); // "\">"
            chLink = baseURL + content.Mid(indexStart, indexEnd-indexStart);

            indexStart = indexEnd;
            indexStart = content.find(wxT(">"), indexStart) + 1; // ">"
            indexEnd = content.find(wxT("<"), indexStart); // "<"
            chEntry = content.Mid(indexStart, indexEnd-indexStart);

            // parse chEntry for: volumePrefix, chNumber, chTitle is impossible,
            // because KissManga naming is inconsistent
            // volumePrefix = ...
            // chNumber = ...
            // chTitle = ...
            chapterList.Add(new MCEntry(HtmlUnescapeString(chEntry), chLink));
        }
    }

    return chapterList;
}
void ThrusterControl::initialize()
{
	// set up environment for first time (pwm, spi, i2c)
	err = system("echo am33xx_pwm > /sys/devices/bone_capemgr.9/slots;");
	sleep(1);

	std::ostringstream sos("");
	// create gpio pins
	if(!BinaryUtils::exists("/sys/class/gpio/gpio30/value"))
	{
		sos << "echo 30 > /sys/class/gpio/export;";
		sos << "echo low > /sys/class/gpio/gpio30/direction;";
	}

	if(!BinaryUtils::exists("/sys/class/gpio/gpio31/value"))
	{
		sos << "echo 31 > /sys/class/gpio/export;";
		sos << "echo low > /sys/class/gpio/gpio31/direction;";
	}

	if(!BinaryUtils::exists("/sys/class/gpio/gpio48/value"))
	{
		sos << "echo 48 > /sys/class/gpio/export;";
		sos << "echo low > /sys/class/gpio/gpio48/direction;";
	}

	if(!BinaryUtils::exists("/sys/class/gpio/gpio60/value"))
	{
		sos << "echo 60 > /sys/class/gpio/export;";
		sos << "echo low > /sys/class/gpio/gpio60/direction;";
	}
	err = system(sos.str().c_str());
	sos.flush();



	// create pwm pins
	if(!BinaryUtils::exists("/sys/devices/ocp.3/pwm_test_P8_13.15/period"))
	{
		err = system("echo bone_pwm_P8_13 > /sys/devices/bone_capemgr.9/slots;");
		// set pwm period and default duty cycle (2ms)
		sos << "echo " << PERIOD << " > /sys/devices/ocp.3/pwm_test_P8_13.15/period;";
		sos << "echo " << PERIOD << " > /sys/devices/ocp.3/pwm_test_P8_13.15/duty;";
		err = system(sos.str().c_str());
		sos.flush();
	}
	if(!BinaryUtils::exists("/sys/devices/ocp.3/pwm_test_P9_14.16/period"))
	{
		err = system("echo bone_pwm_P9_14 > /sys/devices/bone_capemgr.9/slots;");
		sos << "echo " << PERIOD << " > /sys/devices/ocp.3/pwm_test_P9_14.16/period;";
		sos << "echo " << PERIOD << " > /sys/devices/ocp.3/pwm_test_P9_14.16/duty;";
		err = system(sos.str().c_str());
	}

}
Example #7
0
wxString KissMangaCom::JSRiddle(wxString Script)
{
    CurlRequest cr(false);
    cr.SetUrl(wxT("http://jsapp.us/ajax"));
    cr.SetPostData(wxT("{\"actions\":[{\"action\":\"test\",\"code\":\"") + Script + wxT("\"}]}"));
    wxString response;
    wxStringOutputStream sos(&response);
    cr.SetOutputStream(&sos);
    cr.ExecuteRequest();

    // open url from response
    cr.SetUrl(response.BeforeLast('"').AfterLast('"'));
    response = wxEmptyString;
    cr.ExecuteRequest();

    return response;
}
Example #8
0
// Fill the list of starships on sale. Ships that
// can't fit atmo shields are only available in
// atmosphereless environments
void SpaceStation::UpdateShipyard()
{
	bool atmospheric = false;
	if (IsGroundStation()) {
		Body *planet = GetFrame()->GetBody();
		atmospheric = planet->GetSystemBody()->HasAtmosphere();
	}

	const std::vector<ShipType::Id> &ships = atmospheric ? ShipType::playable_atmospheric_ships : ShipType::player_ships;

	unsigned int toAdd = 0, toRemove = 0;

	if (m_shipsOnSale.size() == 0)
		// fill shipyard
		toAdd = Pi::rng.Int32(20);

	else if (Pi::rng.Int32(2))
		// add one
		toAdd = 1;

	else if(m_shipsOnSale.size() > 0)
		// remove one
		toRemove = 1;

	else
		// nothing happens
		return;

	for (; toAdd > 0; toAdd--) {
		ShipType::Id id = ships[Pi::rng.Int32(ships.size())];
		std::string regId = Ship::MakeRandomLabel();
		SceneGraph::ModelSkin skin;
		skin.SetRandomColors(Pi::rng);
		skin.SetPattern(Pi::rng.Int32(0, Pi::FindModel(id)->GetNumPatterns()));
		skin.SetLabel(regId);
		ShipOnSale sos(id, regId, skin);
		m_shipsOnSale.push_back(sos);
	}

	for (; toRemove > 0; toRemove--) {
		int pos = Pi::rng.Int32(m_shipsOnSale.size());
		m_shipsOnSale.erase(m_shipsOnSale.begin() + pos);
	}

	onShipsForSaleChanged.emit();
}
Example #9
0
void watch_dog(void)
{
    /* if watch dog reset */
    if(MCUCSR & (1<<WDRF))
    {
        /* delete watch dog reset flag */
        MCUCSR &= ~(1<<WDRF);
        
        /* communicate error state */
        PORTC &= ~(1<<CONF_LED_PIN); /* err LED on */
       
        while(1)
        {
            sos();
        }
    }
    
    wdt_enable(WDTO_1S);
}
Example #10
0
void KissMangaCom::Activate(wxString Link)
{
    wxString tmp = Link + wxT("0xb"); // TODO: get offset from online source in case it changes periodically
    wxString hash = wxEmptyString;
    unsigned char sum[32];
    SHA256((const unsigned char*)tmp.ToAscii().data(), tmp.Len(), sum); // Scripts/google.js (= CryptoJS)
    for(int i = 0; i < 32; i++)
    {
        hash.Append(wxString::Format(wxT("%02x"), sum[i]));
    }
    CurlRequest cr;
    cr.SetUrl(baseURL + wxT("/0xba93?key=") + hash);
    cr.SetReferer(Link);
    cr.SetPostData(wxT("key=") + hash);
    wxString response;
    wxStringOutputStream sos(&response);
    cr.SetOutputStream(&sos);
    cr.ExecuteRequest();
}
Example #11
0
bool Project::SaveXmlFile()
{
    wxString projectXml;
    wxStringOutputStream sos( &projectXml );
    bool ok = m_doc.Save( sos );
    
    wxFFile file(m_fileName.GetFullPath(), wxT("w+b"));
    if ( !file.IsOpened() ) {
        ok = false;
        
    } else {
        file.Write( projectXml );
        file.Close();
        
    }

    SetProjectLastModifiedTime(GetFileLastModifiedTime());
    EventNotifier::Get()->PostFileSavedEvent( m_fileName.GetFullPath() );
    return ok;
}
Example #12
0
bool SceneIO::processSceneObjectSet(rapidxml::xml_node<char>* sceneXMLNode, ScenePtr scene )
{
	THROW_VR_EXCEPTION_IF(!sceneXMLNode, "NULL data in processSceneObjectSet");

	// get name
	std::string sosName = processNameAttribute(sceneXMLNode,true);
	if (sosName.empty())
	{
		THROW_VR_EXCEPTION("Please specify the name of the scene object set...");
		return false;
	}
	SceneObjectSetPtr sos(new SceneObjectSet(sosName));

	rapidxml::xml_node<>* node = sceneXMLNode->first_node();

	while (node)
	{
		std::string nodeName = getLowerCase(node->name());
		if (nodeName == "sceneobject")
		{
			std::string oname = processNameAttribute(node);
			
			THROW_VR_EXCEPTION_IF(!(scene->hasObstacle(oname) || scene->hasManipulationObject(oname)), " Object with name '" << oname << "' not known in scene '" << scene->getName() << "'." << endl);
			if (scene->hasObstacle(oname))
			{
				sos->addSceneObject(scene->getObstacle(oname));
			} else
				sos->addSceneObject(scene->getManipulationObject(oname));
		} else
		{
			THROW_VR_EXCEPTION("XML definition <" << nodeName << "> not supported in scene's SceneObjectSet definition <" << sosName << ">." << endl);
		}

		node = node->next_sibling();
	}

	scene->registerSceneObjectSet(sos);
	return true;
}
Example #13
0
void SpaceStation::Load(Serializer::Reader &rd, Space *space)
{
	ModelBody::Load(rd, space);
	MarketAgent::Load(rd);
	int num = rd.Int32();
	if (num > Equip::TYPE_MAX) throw SavedGameCorruptException();
	for (int i=0; i<Equip::TYPE_MAX; i++) {
		m_equipmentStock[i] = 0;
	}
	for (int i=0; i<num; i++) {
		m_equipmentStock[i] = static_cast<Equip::Type>(rd.Int32());
	}
	// load shityard
	int numShipsForSale = rd.Int32();
	for (int i=0; i<numShipsForSale; i++) {
		ShipType::Id id(rd.String());
		std::string regId(rd.String());
		SceneGraph::ModelSkin skin;
		skin.Load(rd);
		ShipOnSale sos(id, regId, skin);
		m_shipsOnSale.push_back(sos);
	}
	for (int i=0; i<MAX_DOCKING_PORTS; i++) {
		m_shipDocking[i].shipIndex = rd.Int32();
		m_shipDocking[i].stage = rd.Int32();
		m_shipDocking[i].stagePos = rd.Float();
		m_shipDocking[i].fromPos = rd.Vector3d();
		m_shipDocking[i].fromRot = rd.RdQuaternionf();
	}
	m_dockingLock = rd.Bool();

	m_bbCreated = rd.Bool();
	m_lastUpdatedShipyard = rd.Double();
	m_sbody = space->GetSystemBodyByIndex(rd.Int32());
	m_numPoliceDocked = rd.Int32();
	InitStation();

	m_navLights->Load(rd);
}
void DistributedJobRunner::populateChunks_() {
  unsigned int successCounter = 0;
  int mode = saga::advert::Create | saga::advert::ReadWrite;
  // Instantiate input format.
  const std::string& format_name = job_.get_input_format();
  input_format_ = InputFormatFactory::get_by_key(format_name);
  if (input_format_ == NULL) {
    throw saga::exception("Invalid input format specified");
  }
  chunks_ = input_format_->GetChunks(job_);
  std::vector<InputChunk*>::const_iterator chunk_it = chunks_.begin();
  std::string chunk_string;
  // Advertise chunks.
  while (chunk_it != chunks_.end()) {
    std::string message("Adding new chunk of length " +
      boost::lexical_cast<std::string>((*chunk_it)->GetLength()) + "...");
    try {
      saga::advert::entry adv = chunksDir_.open(saga::url("chunk-" + boost::lexical_cast<std::string>(successCounter)), mode);
      // Serialize chunk.
      chunk_string.clear();
      StringOutputStream sos(&chunk_string);
      input_format_->SerializeInputChunk(*chunk_it, &sos);
      adv.store_object<std::string>(chunk_string);
      message += "SUCCESS";
      log->write(message, MR_LOGLEVEL_INFO);
      successCounter++;
    }
    catch(saga::exception const & e) {
      message += e.what();
      log->write(message, MR_LOGLEVEL_ERROR);
    }
    ++chunk_it;
  }
  if (successCounter == 0) {
    log->write("No chunks made for this session. Aborting", MR_LOGLEVEL_FATAL);
    APPLICATION_ABORT;
  }
}
      void ProcessUnitServiceImpl::getProcessUnit(google::protobuf::RpcController* controller,
              const org::esb::rpc::ProcessUnitRequest* request,
              org::esb::rpc::ProcessUnitResponse* response,
              google::protobuf::Closure* done) {
        assert(mServer);
        LOGDEBUG("getProcessUnit");
        LOGDEBUG(request->node().DebugString());

        org::esb::signal::Message msg;
        msg.setProperty("processunitcontroller", std::string("GET_PROCESS_UNIT"));
        org::esb::signal::Messenger::getInstance().sendRequest(msg);
        boost::shared_ptr<org::esb::hive::job::ProcessUnit >un = msg.getProperty<boost::shared_ptr<org::esb::hive::job::ProcessUnit > >("processunit");
        if (!un) {
          controller->SetFailed("could not get the ProcessUnit from the ProcessUnitController");
          return;
        }
        std::string data;
        org::esb::io::StringOutputStream sos(data);
        org::esb::io::ObjectOutputStream oos(&sos);
        oos.writeObject(*un.get());
        response->mutable_unit_data()->set_serialized_data(data.c_str(), data.length());
        response->set_status("OK");
        LOGDEBUG("sended data length=" << data.length());
      }
Example #16
0
void SpaceStation::Load(Serializer::Reader &rd, Space *space)
{
	ModelBody::Load(rd, space);
	MarketAgent::Load(rd);
	int num = rd.Int32();
	if (num > Equip::TYPE_MAX) throw SavedGameCorruptException();
	for (int i=0; i<Equip::TYPE_MAX; i++) {
		m_equipmentStock[i] = 0;
	}
	for (int i=0; i<num; i++) {
		m_equipmentStock[i] = static_cast<Equip::Type>(rd.Int32());
	}
	// load shityard
	int numShipsForSale = rd.Int32();
	for (int i=0; i<numShipsForSale; i++) {
		ShipType::Id id(rd.String());
		std::string regId(rd.String());
		SceneGraph::ModelSkin skin;
		skin.Load(rd);
		ShipOnSale sos(id, regId, skin);
		m_shipsOnSale.push_back(sos);
	}
	const int32_t numShipDocking = rd.Int32();
	m_shipDocking.reserve(numShipDocking);
	for (int i=0; i<numShipDocking; i++) {
		m_shipDocking.push_back(shipDocking_t());
		shipDocking_t &sd = m_shipDocking.back();
		sd.shipIndex = rd.Int32();
		sd.stage = rd.Int32();
		sd.stagePos = rd.Float();
		sd.fromPos = rd.Vector3d();
		sd.fromRot = rd.RdQuaternionf();
	}
	// retrieve each of the bay groupings
	const int32_t numBays = rd.Int32();
	mBayGroups.reserve(numBays);
	for (int32_t i=0; i<numBays; i++) {
		mBayGroups.push_back(SpaceStationType::SBayGroup());
		SpaceStationType::SBayGroup &bay = mBayGroups.back();
		bay.minShipSize = rd.Int32();
		bay.maxShipSize = rd.Int32();
		bay.inUse = rd.Bool();
		const int32_t numBayIds = rd.Int32();
		bay.bayIDs.reserve(numBayIds);
		for (int32_t j=0; j<numBayIds; j++) {
			const int32_t ID = rd.Int32();
			bay.bayIDs.push_back(ID);
		}
	}

	m_bbCreated = rd.Bool();
	m_lastUpdatedShipyard = rd.Double();
	m_sbody = space->GetSystemBodyByIndex(rd.Int32());
	m_numPoliceDocked = rd.Int32();

	m_doorAnimationStep = rd.Double();
	m_doorAnimationState = rd.Double();

	InitStation();

	m_navLights->Load(rd);
}
void HandleMaps::issue_command_() {
    bool assigned = false; //Describes status of current chunk (file)
    while(assigned == false) {
       try {
          saga::stream::stream worker = service_->serve();
          std::string message("Established connection to ");
          message += worker.get_url().get_string();
          log_->write(message, MR_LOGLEVEL_INFO);

          // Ask worker for state.
          worker.write(saga::buffer(MASTER_QUESTION_STATE, 6));
          if (!SagaStreamUtils::TimedWaitForRead(
                   worker, job_.get_attribute("protocol.read_timeout", 10))) {
            log_->write("Worker didn't respond -- retrying.", MR_LOGLEVEL_DEBUG);
            delete service_;
            service_ = new saga::stream::server(serverURL_);
            continue;
          }

          char buff[MSG_BUFFER_SIZE];
          saga::ssize_t read_bytes = worker.read(saga::buffer(buff));
          std::string state(buff, read_bytes);

          message.clear();
          message = "Worker: " + worker.get_url().get_string() + " has state " + state;
          log_->write(message, MR_LOGLEVEL_INFO);

          if(state == WORKER_STATE_IDLE)
          {
             if(finished_.size() == totalChunks_ || unassigned_.size() == 0)
             {
                //Prevent unneccessary work assignments
                worker.write(saga::buffer(MASTER_REQUEST_IDLE, 5));
                saga::ssize_t read_bytes = worker.read(saga::buffer(buff));
                if(std::string(buff, read_bytes) != WORKER_RESPONSE_ACKNOWLEDGE)
                {
                   log_->write(std::string("Misbehaving worker!"), MR_LOGLEVEL_WARNING);
                }
                return;
             }
             std::string chunk_id(getCandidate_(worker));
             //Worker is idle
             message.clear();
             message = "Attempting to issue worker ";
             message += worker.get_url().get_string();
             message += " to map " + chunk_id;
             message += " ...";
             log_->write(message, MR_LOGLEVEL_INFO);

             //ask where their advert is
             worker.write(saga::buffer(MASTER_QUESTION_ADVERT, 7));
             memset(buff, 0, MSG_BUFFER_SIZE);
             read_bytes = worker.read(saga::buffer(buff));
             saga::url advert = saga::url(std::string(buff, read_bytes));
             // Store URL->advert mapping.
             worker_adverts_[worker.get_url().get_string()] = advert;

             message.clear();
             message += worker.get_url().get_string();
             message += " <==> " + std::string(buff);
             message += " ... ";
             log_->write(message, MR_LOGLEVEL_INFO); 

             //Tell worker about data
             worker.write(saga::buffer(WORKER_COMMAND_MAP, 3));
             memset(buff, 0, MSG_BUFFER_SIZE);
             read_bytes = worker.read(saga::buffer(buff));
             if(std::string(buff, read_bytes) == WORKER_RESPONSE_ACKNOWLEDGE)
             {
                worker.write(saga::buffer(WORKER_CHUNK, 5));
                memset(buff, 0, MSG_BUFFER_SIZE);
                read_bytes = worker.read(saga::buffer(buff));
                if(std::string(buff, read_bytes) == WORKER_RESPONSE_ACKNOWLEDGE)
                {
                  // Get chunk pointer for ID.
                  InputChunk* chunk = chunk_assignments_[chunk_id];
                  // Give serialized JobDescription, chunk_id and chunk to worker.
                  // FIXME: shouldn't we store chunk ID with the chunk/jobdesc?
                  std::string command;
                  {
                    StringOutputStream sos(&command);
                    SerializationHandler<JobDescription>::Serialize(
                      const_cast<JobDescription*>(&job_), &sos);
                    SerializationHandler<std::string>::Serialize(&chunk_id, &sos);
                    input_format_->SerializeInputChunk(chunk, &sos);
                  }
                   worker.write(saga::buffer(command, command.size()));
                   memset(buff, 0, MSG_BUFFER_SIZE);
                   read_bytes = worker.read(saga::buffer(buff));
                   if (std::string(buff, read_bytes) == WORKER_RESPONSE_ACKNOWLEDGE)
                   {
                      // Add to assigned set.
                      assigned_.insert(chunk_id);
                      //Remove from unassigned.
                      unassigned_.erase(chunk_id);
                   }
                }
             }
             else
             {
                message = std::string("Worker did not accept chunk!");
                log_->write(message, MR_LOGLEVEL_WARNING);
                break;
             }

             message.clear();
             message += "Success: ";
             message += advert.get_string() + " is comparing chunk ";
             message += chunk_id;
             log_->write(message, MR_LOGLEVEL_INFO);

             assigned = true;
          }
          else if(state == WORKER_STATE_DONE_MAP)
          {
             worker.write(saga::buffer(MASTER_QUESTION_RESULT, 7));
             memset(buff, 0, MSG_BUFFER_SIZE);
             read_bytes = worker.read(saga::buffer(buff));
             std::string result_message(buff, read_bytes);
             worker.write(saga::buffer(MASTER_REQUEST_IDLE, 5));
             // Parse result message.
             size_t split_point = result_message.find_first_of(' ');
             std::string chunk_id = result_message.substr(0, split_point);
             std::string worker_advert = result_message.substr(split_point+1);
             message.clear();
             message += "Worker ";
             message += worker.get_url().get_string() + " finished chunk ";
             message += chunk_id;
             log_->write(message, MR_LOGLEVEL_INFO);

             // Note which worker completed this chunk.
             message.clear();
             message += "Noted " + worker_advert + " for " + chunk_id;
             committed_chunks_[chunk_id] = worker_advert;
             // If in assigned, remove it.
             assigned_.erase(chunk_id);
             // Put into finished set.
             finished_.insert(chunk_id);
          }
       }
       catch(saga::exception const & e) {
          std::string message(e.what());
          log_->write(message, MR_LOGLEVEL_ERROR);
       }
    }
}
Example #18
0
void KissMangaCom::CFCookie(wxInt32 RetryCount)
{
    if(RetryCount < 0) {
        //wxMessageBox::Show(wxT("Initialization of KissManga failed!"));
        return;
    }

    int indexStart;
    int indexEnd;

    CurlRequest cr(false);
    cr.SetUrl(baseURL);
    cr.SetHeader(true);
    cr.SetAgent(agent);
    wxString response;
    wxStringOutputStream sos(&response);
    cr.SetOutputStream(&sos);
    cr.ExecuteRequest();

    // get initial cookies
    indexStart = response.find(wxT("__cfduid="));
    indexEnd = response.find(wxT(";"), indexStart);
    cookies = response.Mid(indexStart, indexEnd-indexStart);

    // get jschl_answer equation script
    indexStart = response.find(wxT("setTimeout(function(){"), indexEnd) + 22;
    indexStart = response.find(wxT("={"), indexStart);
    indexStart = response.rfind(wxT(","), indexStart) + 1;
    indexEnd = response.find(wxT(".submit();"), indexStart) + 10;
    wxString temp = response.Mid(indexStart, indexEnd-indexStart).Trim(false);
    wxString key = temp.BeforeFirst('=');
    wxString jschl_script = wxT("require('http').createServer(function(req,res){");
    while(temp.Contains(wxT(";")))
    {
        if(temp.StartsWith(key) || temp.StartsWith(wxT("a.value"))) {
            jschl_script += temp.BeforeFirst(';').Trim(false) + wxT(";");
        }
        temp = temp.AfterFirst(';').Trim(false);
    }
    jschl_script.Replace(wxT("a.value = "), wxT("res.writeHead(200);res.end(("));
    jschl_script.Replace(wxT("t.length"), wxString::Format(wxT("%lu)+'');}).listen()"), (unsigned long)baseURL.AfterLast('/').Len()));
    jschl_script.Replace(wxT("\""), wxT("'"));
    jschl_script.Replace(wxT(" "), wxT(""));
    wxString jschl_answer = JSRiddle(jschl_script);

    // get chk_jschl url
    indexStart = response.find(wxT("challenge-form"), indexEnd) + 14;
    indexStart = response.find(wxT("action=\""), indexStart) + 8;
    indexEnd = response.find(wxT("\""), indexStart);
    wxString jschl_chk = baseURL + response.Mid(indexStart, indexEnd-indexStart);

    // get jschl_vc
    indexStart = response.find(wxT("name=\"jschl_vc\""), indexEnd) + 23;
    indexEnd = response.find(wxT("\""), indexStart);
    wxString jschl_vc = response.Mid(indexStart, indexEnd-indexStart);

    // get pass
    indexStart = response.find(wxT("name=\"pass\"")) + 19;
    indexEnd = response.find(wxT("\""), indexStart);
    wxString pass = response.Mid(indexStart, indexEnd-indexStart);

    // wait a bit before sending solution of jsriddle (bypass cloudflare's "to fast solved" protection)
    wxSleep(4);
    cr.SetUrl(jschl_chk + wxT("?jschl_vc=") + jschl_vc + wxT("&pass="******"&jschl_answer=") + jschl_answer);
    cr.SetCookies(cookies);
    response = wxEmptyString;
    cr.ExecuteRequest();

    // get cf_clearance cookie
    // FIXME: it happens regulary that the cookie is not returned by the server,
    // the reason is unknown since the riddle always seems to be solved correctly
    indexStart = response.find(wxT("cf_clearance="));
    indexEnd = response.find(wxT(";"), indexStart);
    cookies = response.Mid(indexStart, indexEnd-indexStart) + wxT(";vns_readType1=1");
    if(cookies.StartsWith(wxT("cf_clearance"))) {
        Logger::Log(wxT("NOTE +++ KissMangaCom::CFCookie() -> cookie = ") + cookies);
    } else {
        Logger::Log(wxT("ERROR +++ KissMangaCom::CFCookie() -> Missing cf_clearance cookie"));
        // retry
        CFCookie(RetryCount-1);
    }
}
Example #19
0
File: lma.c Project: shimniok/lma
int main()
{
	cli();
	disableWatchdog();

	slowClock();
	initBuzzer();
	initSwitch();
	initADC();
	
#ifdef DEBUG
	uint16_t v = getVoltage();
	uint16_t i;

	for (i = 0x8000; i != 0; i >>= 1) {
		if (v & i) {
			dit();
		} else {
			dah();
		}
		_delay_ms(1000);
	}
#endif
	
	// Retrieve the current warning timeout from eeprom
	uint8_t warn_min = eeprom_read_byte(&cfg_warn_min);
	if (switchPressed()) {
		number(warn_min);
		// pause between increments
		_delay_ms(3000);
	}

	// If switch is depressed (at power up), begin increasing
	// warning time, in 5-minute increments, max 30 minutes
	// SOS time is 2 x warning time.
	//
	while (switchPressed()) {	
	
		if (switchPressed()) {
			// Increment warning time by 5 minutes
			warn_min += 5;

			// Maximum warning time is 30 minutes
			if (warn_min > 30) warn_min = 5;

			// Save the new warning time
			eeprom_update_byte(&cfg_warn_min, warn_min);
		}
		number(warn_min);

		// pause between increments
		_delay_ms(3000);		
	}

	// Compute the number of seconds for warning and SOS
	warn_sec = warn_min * 60;
	sos_sec = warn_sec * 2;

	if (checkVoltage()) {
		ok();
	} else {
		sos();
	}

	enableWatchdog();
 	sei();

	while (1) {
		set_sleep_mode(SLEEP_MODE_PWR_DOWN);
		sleep_mode();
	}
}
Example #20
0
 static std::string get_usage(const char *real_program_name) {
   std::string result;
   io::string_output_stream sos(result);
   help::markdown::usage(sos);
   return result;
 }
Example #21
0
void KissMangaCom::UpdateMangaList()
{
    wxTextFile f;
/*
    if(!mangaListFile.IsDirWritable())
    {
        wxMessageBox(wxT("Access denied!\nConfiguration directory: ") + mangaListFile.GetPath());
        return;
    }
*/
    mangaListFile.Mkdir(0755, wxPATH_MKDIR_FULL);

    // create file, or open if already exists
    if(!f.Create(mangaListFile.GetFullPath()))
    {
        f.Open(mangaListFile.GetFullPath());
        f.Clear();
    }

    wxString mangaLink;
    wxString mangaLabel;

    CurlRequest cr;
    cr.SetAgent(agent);
    cr.SetCookies(cookies);
    cr.SetCompression(wxT("gzip"));
    wxString content;
    wxStringOutputStream sos(&content);
    cr.SetOutputStream(&sos);

    wxUint32 pageMax = GetMangaListPageCount() + 1;

    for(wxUint32 i=1; i<pageMax; i++)
    {
        cr.SetUrl(wxString::Format(baseURL + wxT("/MangaList?page=%u"), i));
        content = wxEmptyString;

        if(cr.ExecuteRequest() && !content.IsEmpty())
        {
            int indexStart = content.find(wxT("class=\"listing\"")) + 15;
            int indexEnd = indexStart;//content.rfind(wxT("</table>"));

            if(indexStart > 14 && indexEnd > 14)
            {
                // Example Entry: <a class="bigChar" href="/Manga/–-and-–">& – and –</a>
                while((indexStart = content.find(wxT("class=\"bigChar\""), indexEnd)) > -1)
                {
                    indexStart += 15;
                    indexStart = content.find(wxT("=\""), indexStart) + 2; // "<a href='"
                    indexEnd = content.find(wxT("\""), indexStart); // "\">"
                    mangaLink = baseURL + content.Mid(indexStart, indexEnd-indexStart);

                    indexStart = indexEnd + 2;
                    indexEnd = content.find(wxT("<"), indexStart); // "</a>"
                    mangaLabel = content.Mid(indexStart, indexEnd-indexStart);

                    if(!mangaLabel.IsEmpty())
                    {
                        f.AddLine(HtmlUnescapeString(mangaLabel) + wxT("\t") + mangaLink);
                    }

                    //wxYield();
                }
            }
        }
        sos.Close();
    }

    f.Write();
    f.Close();
    LoadLocalMangaList();
}
Example #22
0
void GitEntry::WriteGitProperties(const wxString& localRepoPath, const GitEntry::GitProperties& props)
{
    // Read the global name/email
    // ~/.gitconfig | %USERPROFILE%\.gitconfig
    {
        wxFileName globalConfig(::wxGetHomeDir(), ".gitconfig");
        if(globalConfig.Exists()) {
            wxFFile fp(globalConfig.GetFullPath(), "rb");
            if(fp.IsOpened()) {
                wxString content;
                fp.ReadAll(&content, wxConvUTF8);
                fp.Close();
                wxStringInputStream sis(content);
                wxFileConfig conf(sis);
                conf.Write("user/email", props.global_email);
                conf.Write("user/name", props.global_username);

                // Write the content
                content.Clear();
                wxStringOutputStream sos(&content);
                if(conf.Save(sos, wxConvUTF8)) {
                    wxFFile fpo(globalConfig.GetFullPath(), "w+b");
                    if(fpo.IsOpened()) {
                        fpo.Write(content, wxConvUTF8);
                        fpo.Close();
                    }
                } else {
                    ::wxMessageBox("Could not save GIT global configuration. Configuration is unmodified",
                                   "git",
                                   wxICON_WARNING | wxOK | wxCENTER);
                }
            }
        }
    }

    // Read the repo config file
    if(!localRepoPath.IsEmpty()) {
        wxFileName localConfig(localRepoPath, "config");
        localConfig.AppendDir(".git");
        wxFFile fp(localConfig.GetFullPath(), "rb");
        if(fp.IsOpened()) {
            wxString content;
            fp.ReadAll(&content, wxConvUTF8);
            fp.Close();
            wxStringInputStream sis(content);
            wxFileConfig conf(sis);
            conf.Write("user/email", props.local_email);
            conf.Write("user/name", props.local_username);

            content.Clear();
            wxStringOutputStream sos(&content);
            if(conf.Save(sos, wxConvUTF8)) {
                wxFFile fpo(localConfig.GetFullPath(), "w+b");
                if(fpo.IsOpened()) {
                    fpo.Write(content, wxConvUTF8);
                    fpo.Close();
                }
            } else {
                ::wxMessageBox("Could not save GIT local configuration. Configuration is unmodified",
                               "git",
                               wxICON_WARNING | wxOK | wxCENTER);
            }
        }
    }
}
Example #23
0
MemoryInputStream* ShareManager::generatePartialList(const string& dir, bool recurse, bool isSharedHub) const {
	if(dir[0] != '/' || dir[dir.size()-1] != '/')
		return 0;
		
	if(!isSharedHub) {
		string xml = SimpleXML::utf8Header;
        string tmp;
        xml += "<FileListing Version=\"1\" CID=\"" + ClientManager::getInstance()->getMe()->getCID().toBase32() + "\" Base=\"" + SimpleXML::escape(dir, tmp, false) + "\" Generator=\"" APPNAME " " VERSIONSTRING "\">\r\n";
        xml += "</FileListing>";
        return new MemoryInputStream(xml);
	}	

	string xml = SimpleXML::utf8Header;
	string tmp;
	xml += "<FileListing Version=\"1\" CID=\"" + ClientManager::getInstance()->getMe()->getCID().toBase32() + "\" Base=\"" + SimpleXML::escape(dir, tmp, true) + "\" Generator=\"" APPNAME " " VERSIONSTRING "\">\r\n";
	StringRefOutputStream sos(xml);
	string indent = "\t";

	Lock l(cs);
	if(dir == "/") {
		for(auto& i: directories) {
			tmp.clear();
			i.second->toXml(sos, indent, tmp, recurse ? -1 : 0);
		}
	} else {
		string::size_type i = 1, j = 1;

		Directory::Ptr root= nullptr;

		bool first = true;
		while( (i = dir.find('/', j)) != string::npos) {
			if(i == j) {
				j++;
				continue;
			}

			if(first) {
				first = false;
				auto it = directories.find(dir.substr(j, i-j));
				if(it == directories.end())
					return 0;
				root = it->second;

			} else {
				auto it2 = root->directories.find(dir.substr(j, i-j));
				if(it2 == root->directories.end()) {
					return 0;
				}
				root = it2->second;
			}
			j = i + 1;
		}

		if(!root)
			return 0;

		for(auto& it2: root->directories) {
			it2.second->toXml(sos, indent, tmp, recurse ? -1 : 0);
		}
		root->filesToXml(sos, indent, tmp);
	}

	xml += "</FileListing>";
	return new MemoryInputStream(xml);
}
Example #24
0
void notmain(void)
{
    pinMode(pin,OUTPUT);
    while(1) 
        sos();
}