Example #1
1
libnet_t *Libnet_init(int injection_type, char *device)
{
	char errbuf[LIBNET_ERRBUF_SIZE];
	libnet_t *l = libnet_init(injection_type, device, errbuf);
	if (l == NULL) {
		throw runtime_error("Libnet_init error: "+string(errbuf));
	}
	return l;
}
Example #2
1
string dec2rom(uint32_t value) {
	stringstream s;
	if (value < MINDEC || value > MAXDEC) throw runtime_error("Input value out of range.");
	int vals[]{1000,500,100,50,10,5,1,0};
	for (int * p = vals; *p; ++p) {
		value = print(s, value, *p);
	}
	return s.str();
}
Example #3
0
int main(int argc, char ** argv) {
	try {
		if (argc < 2) 
			throw runtime_error("USAGE: dec2rom decimal_number");
		stringstream s;
		s.str(argv[1]);
		uint32_t value = 0;
		s >> value;
		if (! s.eof()) 
			throw runtime_error("Junk input.\nUSAGE: dec2rom decimal_number");
		char buf[6]{0};
		snprintf(buf, sizeof(buf), "%-4d", value);
		std::cout << buf << "   " << dec2rom(value) << "\n";

	} catch (const std::exception& ex) {
		std::cerr << "*** Error: " << ex.what() << "\n";
	}
}
Example #4
0
shared_ptr<vector<string>> StrBlobPtr::check(size_t i, const string &msg) const
{
	auto ret = wptr.lock();
	if (!ret)
		throw runtime_error("unbound StrBlobPtr");
	if (i >= ret->size())
		throw out_of_range(msg);
	return ret;
}
Example #5
0
string Choices::LookupName(ChoiceID id) const
{
	map<string, ChoiceID>::iterator entry;

	for (entry = intern->data.begin(); entry != intern->data.end(); entry++)
		if (entry->second == id) return entry->first;

	throw runtime_error("LookupName called for bad id");
}
Example #6
0
const DrakeJoint& RigidBody::getJoint() const {
  if (joint_) {
    return (*joint_);
  } else {
    throw runtime_error("ERROR: RigidBody::getJoint(): Rigid body \"" + name_ +
                        "\" in model " + model_name_ +
                        " does not have a joint!");
  }
}
Example #7
0
void Container::find_streams() {
	if (avformat_find_stream_info(format_context_, nullptr) < 0) {
		throw runtime_error("Finding stream information");
	}

	for (size_t i = 0; i < format_context_->nb_streams; ++i) {
		size_t codec_type = format_context_->streams[i]->codec->codec_type;
		if (codec_type == AVMEDIA_TYPE_VIDEO) {
			video_stream_.push_back(i);
		} else if (codec_type == AVMEDIA_TYPE_AUDIO) {
			audio_stream_.push_back(i);
		}
	}

	if (!is_video() && !is_audio()) {
		throw runtime_error("No audio or video stream");
	}
}
const Mat FileListImageSource::getImage() const
{
	if (index < 0 || index >= static_cast<int>(files.size()))
		return Mat();
	Mat image = imread(files[index].string(), CV_LOAD_IMAGE_COLOR);
	if (image.empty())
		throw runtime_error("image '" + files[index].string() + "' could not be loaded");
	return image;
}
Example #9
0
int Libnet_write(libnet_t *l)
{
	int c = libnet_write(l);
	if (c == -1) {
		throw runtime_error("Libnet_write error: "
				+string(libnet_geterror(l)));
	}
	return c;
}
Example #10
0
void Track_shelf::msd(vector<double> & msd_vec,vector<int> & entry_count)const{
  //this exception needs to get it's own class or something
  if(msd_vec.size()!=entry_count.size())
    throw runtime_error("Vector size's don't match, change this exception");

  int max_time_step = msd_vec.size();


  double disp_sq_sum;
  int tmp_count;

  const particle_track* current = NULL;
  const particle_track* next = NULL;

  bool not_past_end = false;

  

  for(tr_list::const_iterator working_track = tracks_.begin();
      working_track!=tracks_.end(); working_track++)
    {
      
      //      cout<<"Track legnth: "<<(*working_track)->get_length()<<endl;
      for(int j = 0; j<((*working_track)->get_length()-1) && j < max_time_step;j++){
	tmp_count =0;
	disp_sq_sum = 0;
	
	not_past_end = true;

	current = (*working_track)->get_first();
	not_past_end = current->step_forwards(j+1,next);
	while(not_past_end){
	  disp_sq_sum += current->distancesq(next);
	  ++tmp_count;
	  
	  current = next;
	  not_past_end = current->step_forwards(j+1,next);
	}
	msd_vec.at(j) += disp_sq_sum/tmp_count;
	++(entry_count.at(j));
	
      }
    }


  vector<double>::iterator it = msd_vec.begin();
  vector<int>::iterator it2 = entry_count.begin();
  for(;it<msd_vec.end();it++, it2++)
    {
      if(*it2 >0)
	{
	  (*it) = (*it)/(double)(*(it2));
	}
    }
  
}
/**
 * \brief This function gives for each group a priority value
 *
 * \param s (INPUT) is the definition part of the string location
 * \param OperatorNumber (INPUT) is the number of operator
 * \param GrpPriority (OUTPUT) is a list of groups priorities
 * \param InverseDef (OUTPUT) equals to 1 or 0 for each groups; 1 means we want
 * to reverse the tag_operator meaning.
 * \param OpePriority (OUTPUT) is the list of the groups priorities
 */
void assign_grps_priority( string & s, 
                           int OperatorNumber, 
                           vector<int> & GrpPriority, 
                           vector<int> & InverseDef, 
                           vector<int> & OpePriority)
{
  int DefinitionString_size = s.size();
  int GrpNumberLive = 0;
  int Priority = 0;
    
  //Initialization of vector<int> and vector<bool>
  for (int i=0; i<OperatorNumber; i++)
    {
      GrpPriority.push_back(0);
      InverseDef.push_back(0);
      OpePriority.push_back(0);
    }
  
  //move along the definition part and look for g,A,O,!,(,and ).
  for (int j=0 ; j<DefinitionString_size; ++j)
    {
      switch (s[j])
	{
	case 'g':
          j=j+3;   //move to end of grp#
	  GrpPriority[GrpNumberLive]=Priority;
   	  ++GrpNumberLive;
     	  break;
	case '!':
	  InverseDef[GrpNumberLive]=1;
          break;
	case '(':
	  ++Priority;
          break;
	case ')':
	  --Priority;
          break;
	case 'A':
	  OpePriority[GrpNumberLive-1]=Priority;
	  break;
	case 'O':
	  OpePriority[GrpNumberLive-1]=Priority;
	  break;
	default:
          // do nothing
	  break;
	}
    }
 
  if (Priority != 0)
    {
      throw runtime_error("Format of parentheses not valid");
    }

  return;
}
Example #12
0
/**
 * Read the rest of file line by line. Convert each
 * number to an double, and populate array. It is expected that
 * the array has already been allocated with at least
 * a number of elements (returned by the ADnEDFile::getSize()
 * function).
 * @param pArray Pointer to array of epicsFloat64.
 */
void ADnEDFile::readDataIntoDoubleArray(epicsFloat64 **pArray)
{
  const char *whitespace = "# \n\t";
  char line[s_ADNEDFILE_MAX_STRING] = {0};
  char *end = NULL;
  epicsUInt32 index = 0;
  const char *functionName = "ADnEDFile::readDataIntoDoubleArray";
  
  if (p_FILE == NULL) {
    throw runtime_error("p_FILE is NULL.");
  }

  if (*pArray == NULL) {
    throw runtime_error("Array pointer is NULL.");
  }

  while (fgets(line, s_ADNEDFILE_MAX_STRING-1, p_FILE)) {
    if (index >= m_Size) {
      fprintf(stderr, "%s. More lines than expected. Stopping.\n", functionName);
      break;
    }
    //Remove newline
    line[strlen(line)-1]='\0';
    //reject any whitespace
    if (strpbrk(line, whitespace) == NULL) {
      double factor = strtod(line, &end);
      //Populate array
      if ((errno != ERANGE) && (end != line)) {
        (*pArray)[index] = static_cast<epicsFloat64>(factor);
        ++index;
      } else {
        fprintf(stderr, "%s: Stopping due to bad reading in line: %s.\n", functionName, line);
        throw runtime_error("Could not convert line to double.");
      }
    } else {
      fprintf(stderr, "%s: Stopping due to whitespace in line: %s.\n", functionName, line);
      throw runtime_error("Whitespace in file not allowed.");
    }
    memset(line, 0, sizeof(line));
  }
  printf("%s. Read %d data lines.\n", functionName, index);

}
Example #13
0
map<string, string> buildMap(ifstream &map_file) {
	map<string, string> trans_map;
	string key, value;
	while (map_file >> key && getline(map_file, value))
		if (value.size() > 1)
			trans_map[key] = value.substr(1);
		else
			throw runtime_error("No rule for " + key);
	return trans_map;
}
ImportProjectFile::ImportProjectFile ( const string& file, bool rawDataIncluded ) :
	rawDataIncluded ( rawDataIncluded )
{
	if ( !genFileExists ( file ) ) throw runtime_error ( "The project file is missing from the uploaded archive.\n" );
	info = getFileInfo ( file, '\n', 1, false, &numLines );
	centroid = XMLParser::getStringVectorValue ( info, "centroid" );
	raw = XMLParser::getStringVectorValue ( info, "raw" );
	getCentroidFiles ();
	getRawFiles ();
}
Example #15
0
Value getconnectioncount(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 0)
        throw runtime_error(
            "getconnectioncount\n"
            "Returns the number of connections to other nodes.");

    LOCK(cs_vNodes);
    return (int)vNodes.size();
}
Example #16
0
void Track_shelf::remove_track_internal_(  tr_list::iterator it)
{
  if(it == tracks_.end())
    throw runtime_error("not in list");
  delete *it;
  *it = NULL;
  tracks_.erase(it);
  --track_count_;
  
}
shared_ptr<AggregatedFeaturesDetector> DetectorTrainer::getDetector(shared_ptr<NonMaximumSuppression> nms, int octaveLayerCount) const {
	if (!classifier->isUsable())
		throw runtime_error("DetectorTrainer: must train a classifier first");
	if (!imageFilter)
		return make_shared<AggregatedFeaturesDetector>(filter, featureParams.cellSizeInPixels,
				featureParams.windowSizeInCells, octaveLayerCount, classifier->getSvm(), nms);
	else
		return make_shared<AggregatedFeaturesDetector>(imageFilter, filter, featureParams.cellSizeInPixels,
				featureParams.windowSizeInCells, octaveLayerCount, classifier->getSvm(), nms);
}
Example #18
0
void
XMLTester::run(const std::string &source)
{
    curr_file=&source;

    if ( sqlOutput )
    {
        std::cout << "CREATE TABLE \"" << normalize_filename(*curr_file) << "\"" 
                  << "( caseno integer, testno integer, " 
              << " operation varchar, description varchar, "
              << " a geometry, b geometry, expected geometry, "
              << " obtained geometry, result bool )"

              // NOTE: qgis 0.7.4 require oids for proper operations.
              //       The 'WITH OIDS' parameter is supported back to
              //       PostgreSQL 7.2, so if you run an older version
              //       rebuild with the next line commented out.
              << " WITH OIDS"

              << ";" << std::endl;
    }

    ++testFileCount;

    caseCount=0;

    if ( ! xml.LoadFile(source.c_str()) )
    {
        std::stringstream err;
        err << "Could not load " << source << ": " << xml.ErrorDesc();
        throw runtime_error(err.str());
    }

    //dump_to_stdout(&xml);

    const TiXmlNode* node = xml.FirstChild("run");

    if ( ! node )
      throw(runtime_error("Document has no childs"));

    parseRun(node);

}
/* check that if there are no entries then the hash returns no
 * results. seems pretty obvious, but worth checking.
 */
void test_zero_entry() {
   consistent_hash<string, string> h(100);

   if (h.lookup("12345")) { throw runtime_error("Unexpected item found in empty hash."); }
   if (h.lookup("12346")) { throw runtime_error("Unexpected item found in empty hash."); }
   if (h.lookup("12347")) { throw runtime_error("Unexpected item found in empty hash."); }
   if (h.lookup("12348")) { throw runtime_error("Unexpected item found in empty hash."); }
   if (h.lookup("blash")) { throw runtime_error("Unexpected item found in empty hash."); }
   if (h.lookup("")) { throw runtime_error("Unexpected item found in empty hash."); }
   if (h.lookup("!")) { throw runtime_error("Unexpected item found in empty hash."); }
   if (h.lookup("  ")) { throw runtime_error("Unexpected item found in empty hash."); }
}
Example #20
0
void text_bind(sqlite3_stmt* stmt, int indx,const string &  txt)
{
    int rc = sqlite3_bind_text(stmt,indx,txt.c_str(),-1,SQLITE_STATIC);

    if( rc!= SQLITE_OK)
        throw runtime_error(err_format("failed to bind sql_paramater error: ",rc));



}
Example #21
0
pid_t 
CScheduler::run_crawler(const CEnv &env, bool call_fork, bool debug)
{
	string hostport = CURL::hostport("http", env.host, env.port);
	string path = "./" + hostport;
	ifstream ifs(("./"+hostport+".links").c_str());
	if (ifs)
	{
		ofstream ofs((path+"/"+root_file).c_str(), ios::out|ios::app);
		ofs<<ifs.rdbuf();
		ifs.close();
		unlink(("./"+hostport+".links").c_str());
	}
	pid_t pid = 0;
	if (call_fork)
		pid = fork();
	if (pid == 0) // child process or not call_fork;
	{
		if (0 != chdir(path.c_str()))
		{
			ostringstream oss;
			oss<<"Can not chdir to dir:"<<path;
			throw runtime_error(oss.str());
		}
		if (call_fork && setpriority(PRIO_PROCESS, 0, 10) != 0)
		{
			ostringstream oss;
			oss<<"run_crawler():setpriority() error,"<<strerror(errno);
			throw runtime_error(oss.str());
		}
		exec_crawler(env, debug);
		assert(false);
		exit(-1);
	}
	else if (pid < 0)
	{
		cout<<"fork failed!"<<endl;
		return -4;
	}
	else if (pid > 0)
		return pid;
	return -1;
}
Example #22
0
void TA_msd::add_disp(const Tuplef  & displacement,unsigned step)
{
    // check that steps is less than max steps
    if(step > max_step_)
        throw runtime_error("TA_msd::add_disp step out of range");

    summed_displacement_[step-1] += displacement.magnitude_sqr();
    ++(segment_count_[step-1]);

}
Example #23
0
void Commands::exec(const std::string line) throw(std::runtime_error) {
    bool findName= true, quoteMode= false;
    string name, temp;
    vector<string> args;
    size_t i;

    history.insert(history.begin(), line);
    /** parse the command line */
    for(i= 0; i < line.size(); i++) {
        if (line[i] == '\"') {
            quoteMode= !quoteMode;
        } else if (line[i] != ' ' || quoteMode) {
            temp+= line[i];
        } else {
            if (findName) {
                name= temp;
                findName= false;
            } else {
                args.push_back(temp);
            }
            temp.clear();
        }
    }
    if (quoteMode) {
        throw runtime_error("Unmatched quotation \"");
    }
    if (!temp.empty()) {
        if (findName) {
            name= temp;
        } else {
            args.push_back(temp);
        }
    }
    if (commands.count(name) == 0) {
        stringstream msg(stringstream::out);

        msg << "Unrecognized command: " << name;
        throw runtime_error(msg.str().c_str());
    }

    commands[name](args);
}
lambda_unique_ptr<ngram_model_t> createDefaultLanguageModel(ps_decoder_t& decoder) {
	path modelPath = getSphinxModelDirectory() / "en-us.lm.bin";
	lambda_unique_ptr<ngram_model_t> result(
		ngram_model_read(decoder.config, modelPath.string().c_str(), NGRAM_AUTO, decoder.lmath),
		[](ngram_model_t* lm) { ngram_model_free(lm); });
	if (!result) {
		throw runtime_error(fmt::format("Error reading language model from {}.", modelPath));
	}

	return std::move(result);
}
Example #25
0
void Pcap_setfilter(pcap_t *p, const char *rule, int netmask)
{
	assert(p);

	/* Don't care about netmask, it won't be used for this filter */
	struct bpf_program filter;
	int ret;

	// compile the filter 
	if (pcap_compile(p, &filter, (char *) rule, 1, netmask) < 0) {
		throw runtime_error("Pcap_setfilter error: "+string(pcap_geterr(p)));
	}

	// set the filter
	ret = pcap_setfilter(p, &filter);
	pcap_freecode(&filter);
	if (ret < 0) {
		throw runtime_error("Pcap_setfilter error: "+string(pcap_geterr(p)));
	}
}
Example #26
0
static string get_xml_prop(xmlNodePtr node, const string &name)
{
  shared_ptr<xmlChar> xmlstr(xmlGetProp(node, BAD_CAST(name.c_str())),
			     xmlFree);

  if (!xmlstr)
    throw runtime_error("Exanodes protocol error: property '" + name
			+ "' not found");

  return reinterpret_cast<const char*>(xmlstr.get());
}
Example #27
0
Network::Network()
{
    if( SDLNet_Init() == -1 )
        throw runtime_error( string("Unable to init SDL_net! (") + SDLNet_GetError() + ")" );

    socket = SDLNet_UDP_Open( Config::serverPort );

    if( ! socket ) {
        stringstream ss;
        ss << "Failed to open socket on port " << Config::serverPort << "! (" << SDLNet_GetError() << " )";
        throw runtime_error( ss.str() );
    }

    packet = SDLNet_AllocPacket( 5000 );

    if( ! packet )
        throw runtime_error( "Failed to allocate packet!" );

    lastSent = 0;
}
Example #28
0
uint32_t Libnet_name2addr4(libnet_t *l, char *host_name, uint8_t use_name)
{
	assert(l);

	uint32_t ip = libnet_name2addr4(l, host_name, use_name);
	if (ip == (uint32_t) -1) {
		throw runtime_error("Libnet_name2addr4 error for"
				+string(host_name)+": "+string(libnet_geterror(l)));
	}
	return ip;
}
Example #29
0
double MathEx::op_factorial(const double &op) const
{
	int n = static_cast<int>(op), sum = n;
	if (op<0 || abs(op - n) > EPS)
		throw runtime_error(MathExError::FACTORIAL_ERROR);
	if (n == 0 || n == 1)
		return 1;
	while (--n)
		sum *= n;
	return sum;
}
Example #30
0
string AdmindCommand::get_summary() const
{
  string summary(get_name());

  assert(xml_cmd);

  xmlNodePtr cmd = xml_conf_xpath_singleton(xml_cmd.get(), "/Admind/command");

  assert(cmd);

  for (xmlNodePtr node = cmd->children;
       node;
       node = node->next)
  {
      try
      {
          /* Using a shared_ptr here provides us with exception-safety. */
          shared_ptr<xmlChar> prop;

          prop = shared_ptr<xmlChar>(xmlGetProp(node, BAD_CAST("name")), xmlFree);
          if (!prop)
              throw runtime_error("missing \"name\" property");

          string name(reinterpret_cast<const char*>(prop.get()));

          prop = shared_ptr<xmlChar>(xmlGetProp(node, BAD_CAST("value")), xmlFree);
          if (!prop)
              throw runtime_error("missing \"value\" property");

          string value(reinterpret_cast<const char*>(prop.get()));

          summary += " " + name + "=\"" + value + "\"";
      }
      catch (...)
      {
          summary += " <bad parameter>";
      }
  }

  return summary;
}