示例#1
0
	//Grounds the theory with the given structure
	AbstractGroundTheory* ground() {
		Assert(_grounder==NULL);

		if (getOption(BoolType::SHAREDTSEITIN)) {
			_theory = FormulaUtils::sharedTseitinTransform(_theory, _structure);
		}

		// Calculate known definitions
		auto satdelay = getOption(SATISFIABILITYDELAY);
		setOption(SATISFIABILITYDELAY, false);
		auto tseitindelay = getOption(TSEITINDELAY);
		setOption(TSEITINDELAY, false);
		if (getOption(IntType::VERBOSE_GROUNDING) >= 1) {
			logActionAndTime("Starting definition evaluation at ");
		}
		auto defCalculatedResult = CalculateDefinitions::doCalculateDefinitions(dynamic_cast<Theory*>(_theory), _structure, satdelay);
		if(getOption(VERBOSE_GROUNDING_STATISTICS) > 1){
			cout <<"\ndefs&&max:" <<toDouble(Grounder::getFullGroundingSize()) <<"&&grounded:" <<Grounder::groundedAtoms() <<"\n";
		}
		if (not defCalculatedResult._hasModel) {
			// FIXME bugged: NULL as symstructure
			// returnUnsat has to create an entirely new grounder because it's buggy when symstructure is NULL
			// This is rather sloppy
			return returnUnsat(GroundInfo { _theory, { _structure, generateBounds(_theory, _structure, false, false, _outputvocabulary) }, _outputvocabulary, _nbmodelsequivalent, _minimizeterm }, _receiver);
		}
		Assert(defCalculatedResult._calculated_model->isConsistent());
		_structure = defCalculatedResult._calculated_model;
		if(getOption(BoolType::XSB) && getOption(BoolType::REFINE_DEFS_WITH_XSB)) {
			auto defRefinedResult = refineStructureWithDefinitions::doRefineStructureWithDefinitions(dynamic_cast<Theory*>(_theory), _structure, satdelay);
			if (not defRefinedResult._hasModel) {
				// FIXME bugged: NULL as symstructure (see above))
				return returnUnsat(GroundInfo { _theory, { _structure, generateBounds(_theory, _structure, false, false, _outputvocabulary) }, _outputvocabulary, _nbmodelsequivalent, _minimizeterm }, _receiver);
			}
			Assert(defRefinedResult._calculated_model->isConsistent());
			_structure = defRefinedResult._calculated_model;
		}
		setOption(SATISFIABILITYDELAY, satdelay);
		setOption(TSEITINDELAY, tseitindelay);

		// Approximation
		if (getOption(IntType::VERBOSE_GROUNDING) >= 1) {
			logActionAndTime("Starting approximation at ");
		}

		if (getGlobal()->getOptions()->approxDef() != ApproxDef::NONE) {
			PropagationUsingApproxDef* propagator = new PropagationUsingApproxDef();
			auto propagated_structures = propagator->propagate(_theory, _structure);
			if (propagated_structures.size() == 0 || not propagated_structures[0]->isConsistent()) {
				bool LUP = getOption(BoolType::LIFTEDUNITPROPAGATION);
				bool propagate = LUP || getOption(BoolType::GROUNDWITHBOUNDS);
				auto symstructure = generateBounds(_theory, _structure, propagate, LUP, _outputvocabulary);
				auto grounding = returnUnsat(GroundInfo { _theory, { _structure, symstructure }, _outputvocabulary, _nbmodelsequivalent, _minimizeterm }, _receiver);
				symstructure.reset();
				return grounding;
			}
			_structure = propagated_structures[0];
		}
		bool LUP = getOption(BoolType::LIFTEDUNITPROPAGATION);
		bool propagate = LUP || getOption(BoolType::GROUNDWITHBOUNDS);
		auto symstructure = generateBounds(_theory, _structure, propagate, LUP, _outputvocabulary);

		if (not _structure->isConsistent()) {
			if (getOption(IntType::VERBOSE_GROUNDING) > 0 || getOption(IntType::VERBOSE_PROPAGATING) > 0) {
				std::clog << "approximation detected UNSAT\n";
			}
			return returnUnsat(GroundInfo { _theory, { _structure, symstructure }, _outputvocabulary, _nbmodelsequivalent, _minimizeterm }, _receiver);
		}
		if (getOption(IntType::VERBOSE_GROUNDING) >= 1) {
			logActionAndTime("Creating grounders at ");
		}
		auto gi = GroundInfo(_theory, { _structure, symstructure }, _outputvocabulary, _nbmodelsequivalent, _minimizeterm);
		if (_receiver == NULL) {
			_grounder = GrounderFactory::create(gi);
		} else {
			_grounder = GrounderFactory::create(gi, _receiver);
		}

		if (getOption(BoolType::TRACE)) {
			connectTraceMonitor(_tracemonitor, _grounder, _receiver);
		}

		// Run grounder
		if (getOption(IntType::VERBOSE_GROUNDING) >= 1) {
			logActionAndTime("Starting grounding at ");
		}
		if (getOption(VERBOSE_GROUNDING_STATISTICS) >= 1) {
			logActionAndTime("grounding-start");
		}
		bool unsat = _grounder->toplevelRun();
		if(unsat){
			if(getOption(VERBOSE_GROUNDING_STATISTICS) > 0){
				std::clog <<"groundsize&&" <<_grounder->getGrounding()->getSize() <<"\n";
			}
			auto grounding = returnUnsat(GroundInfo { _theory, { _structure, symstructure }, _outputvocabulary, _nbmodelsequivalent, _minimizeterm }, _receiver);
			return grounding;
		}

		addSymmetryBreaking(_theory, _structure, _grounder->getGrounding(), _minimizeterm, _nbmodelsequivalent);

		if(getOption(VERBOSE_GROUNDING_STATISTICS) > 0){
			std::clog <<"groundsize&&" <<_grounder->getGrounding()->getSize() <<"\n";
		}

		return _grounder->getGrounding();
	}
示例#2
0
const char* COption::getFileName()
{
    return getOption('f');
}
  void LiftingLrDpleInternal::init() {

    form_ = getOptionEnumValue("form");

    // Initialize the base classes
    LrDpleInternal::init();

    casadi_assert_message(!pos_def_,
      "pos_def option set to True: Solver only handles the indefinite case.");
    casadi_assert_message(const_dim_,
      "const_dim option set to False: Solver only handles the True case.");

    // We will construct an MXFunction to facilitate the calculation of derivatives

    MX As = MX::sym("As", input(LR_DLE_A).sparsity());
    MX Vs = MX::sym("Vs", input(LR_DLE_V).sparsity());
    MX Cs = MX::sym("Cs", input(LR_DLE_C).sparsity());
    MX Hs = MX::sym("Hs", input(LR_DLE_H).sparsity());

    n_ = A_[0].size1();

    // Chop-up the arguments
    std::vector<MX> As_ = horzsplit(As, n_);
    std::vector<MX> Vs_ = horzsplit(Vs, V_[0].size2());
    std::vector<MX> Cs_ = horzsplit(Cs, V_[0].size2());
    std::vector<MX> Hs_;
    if (with_H_) {
      Hs_ = horzsplit(Hs, Hsi_);
    }

    MX A;
    if (K_==1) {
      A = As;
    } else {
      if (form_==0) {
        MX AL = diagcat(vector_slice(As_, range(As_.size()-1)));

        MX AL2 = horzcat(AL, MX(AL.size1(), As_[0].size2()));
        MX AT = horzcat(MX(As_[0].size1(), AL.size2()), As_.back());
        A = vertcat(AT, AL2);
      } else {
        MX AL = diagcat(reverse(vector_slice(As_, range(As_.size()-1))));

        MX AL2 = horzcat(MX(AL.size1(), As_[0].size2()), AL);
        MX AT = horzcat(As_.back(), MX(As_[0].size1(), AL.size2()));
        A = vertcat(AL2, AT);
      }
    }

    MX V;
    MX C;

    MX H;

    if (form_==0) {
      V = diagcat(Vs_.back(), diagcat(vector_slice(Vs_, range(Vs_.size()-1))));
      if (with_C_) {
        C = diagcat(Cs_.back(), diagcat(vector_slice(Cs_, range(Cs_.size()-1))));
      }
    } else {
      V = diagcat(diagcat(reverse(vector_slice(Vs_, range(Vs_.size()-1)))), Vs_.back());
      if (with_C_) {
        C = diagcat(diagcat(reverse(vector_slice(Cs_, range(Cs_.size()-1)))), Cs_.back());
      }
    }

    if (with_H_) {
      H = diagcat(form_==0? Hs_ : reverse(Hs_));
    }

    // QP solver options
    Dict options;
    if (hasSetOption(optionsname())) {
      options = getOption(optionsname());
    }
    options["Hs"] = Hss_;

    // Create an LrDleSolver instance
    solver_ = LrDleSolver("solver", getOption(solvername()),
                          make_map("a", A.sparsity(),
                                   "v", V.sparsity(),
                                   "c", C.sparsity(),
                                   "h", H.sparsity()), options);

    std::vector<MX> v_in(LR_DPLE_NUM_IN);
    v_in[LR_DLE_A] = As;
    v_in[LR_DLE_V] = Vs;
    if (with_C_) {
      v_in[LR_DLE_C] = Cs;
    }
    if (with_H_) {
      v_in[LR_DLE_H] = Hs;
    }

    MX Pf = solver_(make_map("a", A, "v", V, "c", C, "h", H)).at(solver_.outputName(0));

    std::vector<MX> Ps = with_H_ ? diagsplit(Pf, Hsi_) : diagsplit(Pf, n_);

    if (form_==1) {
      Ps = reverse(Ps);
    }

    f_ = MXFunction(name_, v_in, dpleOut("p", horzcat(Ps)),
                    make_dict("input_scheme", IOScheme(SCHEME_LR_DPLEInput),
                              "output_scheme", IOScheme(SCHEME_LR_DPLEOutput)));

    Wrapper<LiftingLrDpleInternal>::checkDimensions();

  }
示例#4
0
int SocketImpl::socketError()
{
    int result(0);
    getOption(SOL_SOCKET, SO_ERROR, result);
    return result;
}
示例#5
0
const char* COption::getRecordName()
{
    return getOption('r');
}
示例#6
0
bool SocketImpl::getKeepAlive()
{
    int value(0);
    getOption(SOL_SOCKET, SO_KEEPALIVE, value);
    return value != 0;
}
示例#7
0
bool SocketImpl::getOOBInline()
{
    int value(0);
    getOption(SOL_SOCKET, SO_OOBINLINE, value);
    return value != 0;
}
//----------------------------------------------------------------------------
QVariant ctkPluginFrameworkDebugOptions::getOption(const QString& option) const
{
  return getOption(option, QVariant());
}
//opts - all options list WITHOUT serverDUID including server id
TClntMsgInfRequest::TClntMsgInfRequest(TOptList ReqOpts,
				       int iface)
    :TClntMsg(iface, 0, INFORMATION_REQUEST_MSG) {
    IRT = INF_TIMEOUT;
    MRT = INF_MAX_RT;
    MRC = 0;
    MRD = 0;
    RT=0;

    Iface=iface;
    IsDone=false;
    
    SPtr<TIfaceIface> ptrIface = ClntIfaceMgr().getIfaceByID(iface);
    if (!ptrIface) {
        Log(Error) << "Unable to find interface with ifindex=" << iface 
                   << " while trying to generate INF-REQUEST." << LogEnd;
        IsDone = true;
        return;
    }
    Log(Debug) << "Creating INF-REQUEST on the " << ptrIface->getFullName()
	           << "." << LogEnd;
    
    // copy whole list from Verify ...
    Options = ReqOpts;
    
    SPtr<TOpt> opt;
    firstOption();
    while(opt=getOption())
    {
        switch (opt->getOptType())
        {       
            //These options possibly receipt from verify transaction
            //can't appear in request message and have to be deleted
            case OPTION_UNICAST:
            case OPTION_STATUS_CODE:
            case OPTION_PREFERENCE:
            case OPTION_IA_TA:
            case OPTION_RELAY_MSG:
            case OPTION_SERVERID:
            case OPTION_IA_NA:
            case OPTION_IAADDR:
            case OPTION_RAPID_COMMIT:
            case OPTION_INTERFACE_ID:
            case OPTION_RECONF_MSG:
            case OPTION_AUTH:
            case OPTION_AAAAUTH:
            case OPTION_KEYGEN:
	    case OPTION_ELAPSED_TIME:       //delete the old elapsed option,as we will append a new one
                delOption(opt->getOptType());
                break;        
        }
        //The other options can be included in Information request option
        //CLIENTID,ORO,ELAPSED_TIME,USER_CLASS,VENDOR_CLASS,
        //VENDOR_OPTS,DNS_RESOLVERS,DOMAIN_LIST,NTP_SERVERS,TIME_ZONE,
        //RECONF_ACCEPT - maybe also SERVERID if information request
        //is answer to reconfigure message
    }
    appendElapsedOption();
    appendAuthenticationOption();

    this->send();
}
示例#10
0
文件: app.c 项目: HsuJv/Note
int main(int argc, char* argv[]){
    const char* options[] = {"-u", "upload", "-d", "download", \
        "-h", "help", "-l", "list", "-r", "remove", 0};
    int op;

    if (argc != 3 && argc != 2){
        helpInfo();
        return 0;
    }
    
    op = getOption(options, argv[1]);
    switch(op){
        case 0:
        case 1:
            if (argc == 2){
                fprintf(stdout, "Please input the filename!\n");
                exit(0);
            }
            if (access(argv[2], R_OK)){
                fprintf(stdout, "File '%s' not exists,\n", argv[2]);
                fprintf(stdout, "Or permession denied.\n");
                fprintf(stdout, "Please check the filename.\n");
                exit(0);
            }
            if(!uploadFile(argv[2]))
                fprintf(stdout, "Upload %s success\n", argv[2]);
            break;
        case 2:
        case 3:
            if (argc == 2){
                fprintf(stdout, "Please input the filename!\n");
                exit(0);
            }
            if(!downloadFile(argv[2]))
               fprintf(stdout, "Downloadload %s success\n", argv[2]);
            break;
        case 4:
        case 5:
            helpInfo();
            break;
        case 6:
        case 7:
            if (argc == 2){
                fprintf(stdout, "Please input the filename!\n");
                exit(0);
            }
            dfsList(argv[2]);
            break;
        case 8:
        case 9:
            if (argc == 2){
                fprintf(stdout, "Please input the filename!\n");
                exit(0);
            }
            if (!dfsRemove(argv[2]))
                fprintf(stdout, "Delete %s success\n", argv[2]);
            break;
        default:
            exit(-1);
    }
    exit(0);
}
示例#11
0
GDALDataset *RasdamanDataset::Open( GDALOpenInfo * poOpenInfo )
{
  // buffer to communicate errors 
  char errbuffer[4096];

  // fast checks if current module should handle the request
  // check 1: the request is not on a existing file in the file system
  if (poOpenInfo->fp != NULL) {
    return NULL;
  }
  // check 2: the request contains --collection
  char* connString = poOpenInfo->pszFilename;
  if (!EQUALN(connString, "rasdaman", 8)) {
    return NULL;
  }

  // regex for parsing options
  regex_t optionRegEx;
  // regex for parsing query
  regex_t queryRegEx;
  // array to store matching subexpressions
  regmatch_t matches[10];

  #define QUERY_POSITION 2
  #define SERVER_POSITION 3
  #define PORT_POSITION 4
  #define USERNAME_POSITION 5
  #define USERPASSWORD_POSITION 6
  #define DATABASE_POSITION 7
  #define TILEXSIZE_POSITION 8
  #define TILEYSIZE_POSITION 9

  int result = regcomp(&optionRegEx, "^rasdaman:(query='([[:alnum:][:punct:] ]+)'|host='([[:alnum:]]+)'|port=([0-9]+)|user='******'|password='******'|database '([[:alnum:]]+)'|tileXSize=([0-9]+)|tileYSize=([0-9]+)| )*", REG_EXTENDED);

  // should never happen 
  if (result != 0) {
    regerror(result, &optionRegEx, errbuffer, 4096);
    CPLError(CE_Failure, CPLE_AppDefined, "Internal error at compiling option parsing regex: %s", errbuffer);
    return NULL; 
  }

  result = regcomp(&queryRegEx, "^select ([[:alnum:][:punct:] ]*) from ([[:alnum:][:punct:] ]*)$", REG_EXTENDED);
  // should never happen 
  if (result != 0) {
    regerror(result, &queryRegEx, errbuffer, 4096);
    CPLError(CE_Failure, CPLE_AppDefined, "Internal error at compiling option parsing regex: %s", errbuffer);
    return NULL; 
  }

  // executing option parsing regex on the connection string and checking if it succeeds
  result = regexec(&optionRegEx, connString, 10, matches, 0);
  if (result != 0) {
    regerror(result, &optionRegEx, errbuffer, 4096);
    CPLError(CE_Failure, CPLE_AppDefined, "Parsing opening parameters failed with error: %s", errbuffer);
    regfree(&optionRegEx);
    regfree(&queryRegEx);
    return NULL; 
  }

  regfree(&optionRegEx);
  

  // checking if the whole expressions was matches, if not give an error where 
  // the matching stopped and exit
  if (size_t(matches[0].rm_eo) < strlen(connString)) {
    CPLError(CE_Failure, CPLE_AppDefined, "Parsing opening parameters failed with error: %s", connString+matches[0].rm_eo);
    regfree(&queryRegEx);
    return NULL; 
  }

  CPLString queryParam = getOption(connString, matches[QUERY_POSITION], (const char*)NULL);
  CPLString host = getOption(connString, matches[SERVER_POSITION], "localhost");
  int port = getOption(connString, matches[PORT_POSITION], 7001);
  CPLString username = getOption(connString, matches[USERNAME_POSITION], "rasguest");
  CPLString userpassword = getOption(connString, matches[USERPASSWORD_POSITION], "rasguest");
  CPLString databasename = getOption(connString, matches[DATABASE_POSITION], "RASBASE");
  int tileXSize = getOption(connString, matches[TILEXSIZE_POSITION], 1024);
  int tileYSize = getOption(connString, matches[TILEYSIZE_POSITION], 1024);

  result = regexec(&queryRegEx, queryParam, 10, matches, 0);
  if (result != 0) {
    regerror(result, &queryRegEx, errbuffer, 4096);
    CPLError(CE_Failure, CPLE_AppDefined, "Parsing query parameter failed with error: %s", errbuffer);
    regfree(&queryRegEx);
    return NULL; 
  }

  regfree(&queryRegEx);

  CPLString osQueryString = "select sdom(";
  osQueryString += getOption(queryParam, matches[1], "");
  osQueryString += ") from ";
  osQueryString += getOption(queryParam, matches[2], "");

  CPLString queryX = getQuery(osQueryString, "*", "*", "0", "0");
  CPLString queryY = getQuery(osQueryString, "0", "0", "*", "*");
  CPLString queryUnit = getQuery(queryParam, "0", "0", "0", "0");

  stringstream queryStream;
  
  r_Transaction transaction;

  RasdamanDataset *rasDataset = new RasdamanDataset();

  r_Database database;  
  try {
    database.set_servername(host, port);
    database.set_useridentification(username, userpassword);
    database.open(databasename);
    transaction.begin();
    
    int dimX = getExtent(queryX, rasDataset->xPos);
    int dimY = getExtent(queryY, rasDataset->yPos);
    rasDataset->nRasterXSize = dimX;
    rasDataset->nRasterYSize = dimY;
    rasDataset->tileXSize = tileXSize;
    rasDataset->tileYSize = tileYSize;
    rasDataset->createBands(queryUnit);

    transaction.commit();
    database.close();
  } catch (r_Error error) {
    CPLError(CE_Failure, CPLE_AppDefined, "%s", error.what());
    delete rasDataset;
    return NULL;
  }
  rasDataset->queryParam = queryParam;
  rasDataset->host = host;
  rasDataset->port = port;
  rasDataset->username = username;
  rasDataset->userpassword = userpassword;
  rasDataset->databasename = databasename;

  return rasDataset;
}
示例#12
0
bool 
Device::addDirPorts(enum Streaming::Port::E_Direction direction) {

    const char *mode_str = direction==Streaming::Port::E_Capture?"cap":"pbk";
    Streaming::StreamProcessor *s_processor;
    std::string id;
    char name[128];
    signed int i;
    signed int n_analog, n_phones, n_adat, n_spdif;
    signed int sample_rate = getSamplingFrequency();

    /* Apply bandwidth limit if selected.  This effectively sets up the
     * number of adat and spdif channels assuming single-rate speed.
     */
    n_spdif = 2;
    switch (dev_config->settings.limit_bandwidth) {
      case FF_SWPARAM_BWLIMIT_ANALOG_ONLY:
        n_adat = n_spdif = 0;
        break;
      case FF_SWPARAM_BWLIMIT_ANALOG_SPDIF_ONLY:
        n_adat = 0;
        break;
      case FF_SWPARAM_BWLIMIT_NO_ADAT2:
        /* FF800 only */
        n_adat = 8;
        break;
      default:
        /* Send all channels */
        n_adat = (m_rme_model==RME_MODEL_FIREFACE800)?16:8;
    }

    /* Work out the number of analog channels based on the device model and
     * adjust the spdif and ADAT channels according to the current sample
     * rate.
     */
    n_analog = (m_rme_model==RME_MODEL_FIREFACE800)?10:8;
    n_phones = 0;
    if (sample_rate>=MIN_DOUBLE_SPEED && sample_rate<MIN_QUAD_SPEED) {
      n_adat /= 2;
    } else
    if (sample_rate >= MIN_QUAD_SPEED) {
      n_adat = 0;
      n_spdif = 0;
    }

    if (direction == Streaming::Port::E_Capture) {
        s_processor = m_receiveProcessor;
    } else {
        s_processor = m_transmitProcessor;
        /* Phones count as two of the analog outputs */
        n_analog -= 2;
        n_phones = 2;
    }

    id = std::string("dev?");
    if (!getOption("id", id)) {
        debugWarning("Could not retrieve id parameter, defaulting to 'dev?'\n");
    }

    for (i=0; i<n_analog; i++) {
      snprintf(name, sizeof(name), "%s_%s_analog-%d", id.c_str(), mode_str, i+1);
      addPort(s_processor, name, direction, i*4, 0);
    }
    for (i=0; i<n_phones; i++) {
      snprintf(name, sizeof(name), "%s_%s_phones-%c", id.c_str(), mode_str, 
        i==0?'L':'R');
      /* The headphone channels follow the straight analog lines */
      addPort(s_processor, name, direction, n_analog*4+i*4, 0);
    }
    for (i=0; i<n_spdif; i++) {
      snprintf(name, sizeof(name), "%s_%s_SPDIF-%d", id.c_str(), mode_str, i+1);
      /* The SPDIF channels start after all analog lines */
      addPort(s_processor, name, direction, (n_analog+n_phones)*4+i*4, 0);
    }
    for (i=0; i<n_adat; i++) {
      snprintf(name, sizeof(name), "%s_%s_adat-%d", id.c_str(), mode_str, i+1);
      /* ADAT ports follow all other ports */
      addPort(s_processor, name, direction, (n_analog+n_phones+n_spdif)*4+i*4, 0);
    }

    return true;
}
示例#13
0
bool
Device::prepare() {

    signed int mult, bandwidth;
    signed int freq, init_samplerate;
    signed int err = 0;
    unsigned int stat[4];

    debugOutput(DEBUG_LEVEL_NORMAL, "Preparing Device...\n" );

    // If there is no iso data to send in a given cycle the RMEs simply
    // don't send anything.  This is in contrast to most other interfaces
    // which at least send an empty packet.  As a result the IsoHandler
    // contains code which detects missing packets as dropped packets.
    // For RME devices we must turn this test off since missing packets
    // are in fact to be expected.
    get1394Service().getIsoHandlerManager().setMissedCyclesOK(true);

    freq = getSamplingFrequency();
    if (freq <= 0) {
        debugOutput(DEBUG_LEVEL_ERROR, "Can't continue: sampling frequency not set\n");
        return false;
    }
    mult = freq<68100?1:(freq<136200?2:4);

    frames_per_packet = getFramesPerPacket();

    // The number of active channels depends on sample rate and whether
    // bandwidth limitation is active.  First set up the number of analog
    // channels (which differs between devices), then add SPDIF channels if
    // relevant.  Finally, the number of channels available from each ADAT
    // interface depends on sample rate: 0 at 4x, 4 at 2x and 8 at 1x.
    if (m_rme_model == RME_MODEL_FIREFACE800)
        num_channels = 10;
    else
        num_channels = 8;
    if (settings->limit_bandwidth != FF_SWPARAM_BWLIMIT_ANALOG_ONLY)
        num_channels += 2;
    if (settings->limit_bandwidth==FF_SWPARAM_BWLIMIT_SEND_ALL_CHANNELS)
        num_channels += (mult==4?0:(mult==2?4:8));
    if (m_rme_model==RME_MODEL_FIREFACE800 &&
        settings->limit_bandwidth==FF_SWPARAM_BWLIMIT_SEND_ALL_CHANNELS)
        num_channels += (mult==4?0:(mult==2?4:8));

    // Bandwidth is calculated here.  For the moment we assume the device 
    // is connected at S400, so 1 allocation unit is 1 transmitted byte.
    // There is 25 allocation units of protocol overhead per packet.  Each
    // channel of audio data is sent/received as a 32 bit integer.
    bandwidth = 25 + num_channels*4*frames_per_packet;

    // Both the FF400 and FF800 require we allocate a tx iso channel and
    // then initialise the device.  Device status is then read at least once
    // regardless of which interface is in use.  The rx channel is then
    // allocated for the FF400 or acquired from the device in the case of
    // the FF800.  Even though the FF800 chooses the rx channel it does not
    // handle the bus-level channel/bandwidth allocation so we must do that 
    // here.
    if (iso_tx_channel < 0) {
        iso_tx_channel = get1394Service().allocateIsoChannelGeneric(bandwidth);
    }
    if (iso_tx_channel < 0) {
        debugFatal("Could not allocate iso tx channel\n");
        return false;
    } else {
      debugOutput(DEBUG_LEVEL_NORMAL, "iso tx channel: %d\n", iso_tx_channel);
    }

    // Call this to initialise the device's streaming system and, in the
    // case of the FF800, obtain the rx iso channel to use.  Having that
    // functionality in resetForStreaming() means it's effectively done
    // twice when FFADO is first started, but this does no harm.
    resetForStreaming();
  
    if (err) {
        if (iso_tx_channel >= 0) 
            get1394Service().freeIsoChannel(iso_tx_channel);
        if (iso_rx_channel>=0 && m_rme_model==RME_MODEL_FIREFACE400)
            // The FF800 manages this channel itself.
            get1394Service().freeIsoChannel(iso_rx_channel);
        return false;
    }

    /* We need to manage the FF400's iso rx channel */
    if (m_rme_model == RME_MODEL_FIREFACE400) {
        iso_rx_channel = get1394Service().allocateIsoChannelGeneric(bandwidth);
    }

    if ((stat[1] & SR1_CLOCK_MODE_MASTER) ||
        (stat[0] & SR0_AUTOSYNC_FREQ_MASK)==0 ||
        (stat[0] & SR0_AUTOSYNC_SRC_MASK)==SR0_AUTOSYNC_SRC_NONE) {
        init_samplerate = dev_config->hardware_freq;
    } else {
        init_samplerate = (stat[0] & SR0_STREAMING_FREQ_MASK) * 250;
    }

    debugOutput(DEBUG_LEVEL_VERBOSE, "sample rate on start: %d\n",
        init_samplerate);

    // get the device specific and/or global SP configuration
    Util::Configuration &config = getDeviceManager().getConfiguration();
    // base value is the config.h value
    float recv_sp_dll_bw = STREAMPROCESSOR_DLL_BW_HZ;
    float xmit_sp_dll_bw = STREAMPROCESSOR_DLL_BW_HZ;

    // we can override that globally
    config.getValueForSetting("streaming.spm.recv_sp_dll_bw", recv_sp_dll_bw);
    config.getValueForSetting("streaming.spm.xmit_sp_dll_bw", xmit_sp_dll_bw);

    // or override in the device section
    config.getValueForDeviceSetting(getConfigRom().getNodeVendorId(), getConfigRom().getModelId(), "recv_sp_dll_bw", recv_sp_dll_bw);
    config.getValueForDeviceSetting(getConfigRom().getNodeVendorId(), getConfigRom().getModelId(), "xmit_sp_dll_bw", xmit_sp_dll_bw);

    // Calculate the event size.  Each audio channel is allocated 4 bytes in
    // the data stream.
    /* FIXME: this will still require fine-tuning, but it's a start */
    signed int event_size = num_channels * 4;

    // Set up receive stream processor, initialise it and set DLL bw
    m_receiveProcessor = new Streaming::RmeReceiveStreamProcessor(*this, 
      m_rme_model, event_size);
    m_receiveProcessor->setVerboseLevel(getDebugLevel());
    if (!m_receiveProcessor->init()) {
        debugFatal("Could not initialize receive processor!\n");
        return false;
    }
    if (!m_receiveProcessor->setDllBandwidth(recv_sp_dll_bw)) {
        debugFatal("Could not set DLL bandwidth\n");
        delete m_receiveProcessor;
        m_receiveProcessor = NULL;
        return false;
    }

    // Add ports to the processor - TODO
    std::string id=std::string("dev?");
    if (!getOption("id", id)) {
        debugWarning("Could not retrieve id parameter, defaulting to 'dev?'\n");
    }
    addDirPorts(Streaming::Port::E_Capture);

    /* Now set up the transmit stream processor */
    m_transmitProcessor = new Streaming::RmeTransmitStreamProcessor(*this,
      m_rme_model, event_size);
    m_transmitProcessor->setVerboseLevel(getDebugLevel());
    if (!m_transmitProcessor->init()) {
        debugFatal("Could not initialise receive processor!\n");
        return false;
    }
    if (!m_transmitProcessor->setDllBandwidth(xmit_sp_dll_bw)) {
        debugFatal("Could not set DLL bandwidth\n");
        delete m_transmitProcessor;
        m_transmitProcessor = NULL;
        return false;
    }

    // Other things to be done:
    //  * add ports to transmit stream processor
    addDirPorts(Streaming::Port::E_Playback);

    return true;
}
示例#14
0
 std::string getOption(const std::string &option, const std::string &def) { return getOption(std::string(), option, def); }
示例#15
0
int SocketImpl::getReceiveBufferSize()
{
    int result;
    getOption(SOL_SOCKET, SO_RCVBUF, result);
    return result;
}
示例#16
0
/* Main function. */
int main(int argc, char *argv[]) {

    /* Local variables. */
    char option = 'x';
    int exitValue;
    char *fileName;
    FILE *employeeFile;
    employee *employees;
    float total = 0;

    // Validation: Number of arguments from console.
    if (argc != 2) {
        printf("Error: Numero de parametros invalido.\nDebe iniciar asi: ./taller.out <archivo.csv>\n");
		exit(0);
    }
    
    fileName = argv[1];
    
    employeeFile = fopen(fileName, "r");
    if(employeeFile == NULL) {
        printf("No se pudo abrir el archivo\n");
        exit(0);
    }
    
    numEmployees = getNumEmployees(employeeFile);
    
    if (numEmployees <= 0) {
        printf("Error: No hay trabajadores en el archivo\n");
		exit(0);
    }
    
    printf("Hay %d trabajadores en el archivo\n", numEmployees);
    
    employees = (employee *)malloc(sizeof(employee) * numEmployees);

    do {
        getOption(&option);
        switch (option) {
            case 'a':
                registerEmployees(employees, employeeFile);
                break;
            case 'b':
					 showEmployees(employees);
                break;
            case 'c':
					 total = getTotal(employees);
                     printf("TOTAL: %.2f", total);
                break;
            case 'q':
                printf("Saliendo del programa...\n");
                break;
            default:
                printf("La opcion '%c' no es valida. Volviendo al menu.\n", option);
                break;
        }
    } while(option != 'q');
    
    exitValue = fclose(employeeFile);
    if(exitValue == 0) {
        printf("se cerro el archivo\n");
    }
    
    /* Free memory. */
    free(employees);


    return 0;
}
示例#17
0
bool SocketImpl::getNoDelay()
{
    int value(0);
    getOption(IPPROTO_TCP, TCP_NODELAY, value);
    return value != 0;
}
示例#18
0
void AddNew::processInput(string inputString)
{
    // Holds the value entered by the user for this menu
    static int menuChoiceInt;
    static char menuChoiceChar;
    
    // Holds whether the entered value is valid
    static bool isValidInt; 
    static bool isValidChar;
    
    isValidInt = validateInt(inputString, &menuChoiceInt);
    isValidChar = validateChar(inputString, &menuChoiceChar);
    
    if(isValidInt)
    {
        if(isOption(menuChoiceInt))
        {
            // You need to find a way to associate values with menu selections
            // This more general than assuming the order that is setup in setActions()
            
            //process();
            if(menuChoiceInt == 1)
            {
                //change(MenuSystem::ENTERDIR);
                kill();
            }
            else if(menuChoiceInt == 2)
            {
                cout << "trying to switch to enter dir..." << endl;
                change(MenuSystem::ENTERDIR);
                //kill();
            }
            else if(menuChoiceInt == 3)
            {
                //change(MenuSystem::REMOVEDIR);
                kill();
            }
            else
            {
                process();
            }
        }
    }
    else if(isValidChar)
    {
        if(Menu::isOption(menuChoiceChar))
        {
            MenuSystem::MenuType menuType = getOption(menuChoiceChar)->getValue();
            if(menuType == MenuSystem::EXIT)
            {
                kill();
            }
            else if(menuType == MenuSystem::ADDREMOVE)
            {                
                // Assuming there are no more menus for now
                change(MenuSystem::ADDREMOVE);
            }
        }
        else
        {
            printInvalidAndProcess();
        }
    }
    else
    {
        printInvalidAndProcess();
    }

}
示例#19
0
bool SocketImpl::getReuseAddress()
{
    int value(0);
    getOption(SOL_SOCKET, SO_REUSEADDR, value);
    return value != 0;
}
示例#20
0
	void beginJob() throw (std::runtime_error)
	{
		// copy option to local variables to avoid map search due to
		// performance
		getOption("stats", _Stats);
	}
示例#21
0
bool SocketImpl::getBroadcast()
{
    int value(0);
    getOption(SOL_SOCKET, SO_BROADCAST, value);
    return value != 0;
}
示例#22
0
void WebWidget::updateEditActions()
{
	const bool canPaste = (QApplication::clipboard()->mimeData() && QApplication::clipboard()->mimeData()->hasText());
	const bool hasSelection = (this->hasSelection() && !getSelectedText().trimmed().isEmpty());

	if (m_actions.contains(ActionsManager::CutAction))
	{
		m_actions[ActionsManager::CutAction]->setEnabled(hasSelection && m_hitResult.flags.testFlag(IsContentEditableTest));
	}

	if (m_actions.contains(ActionsManager::CopyAction))
	{
		m_actions[ActionsManager::CopyAction]->setEnabled(hasSelection);
	}

	if (m_actions.contains(ActionsManager::CopyPlainTextAction))
	{
		m_actions[ActionsManager::CopyPlainTextAction]->setEnabled(hasSelection);
	}

	if (m_actions.contains(ActionsManager::CopyToNoteAction))
	{
		m_actions[ActionsManager::CopyToNoteAction]->setEnabled(hasSelection);
	}

	if (m_actions.contains(ActionsManager::PasteAction))
	{
		m_actions[ActionsManager::PasteAction]->setEnabled(canPaste && m_hitResult.flags.testFlag(IsContentEditableTest));
	}

	if (m_actions.contains(ActionsManager::PasteAndGoAction))
	{
		m_actions[ActionsManager::PasteAndGoAction]->setEnabled(canPaste);
	}

	if (m_actions.contains(ActionsManager::PasteNoteAction))
	{
		m_actions[ActionsManager::PasteNoteAction]->setEnabled(canPaste && m_hitResult.flags.testFlag(IsContentEditableTest) && NotesManager::getModel()->getRootItem()->hasChildren());
	}

	if (m_actions.contains(ActionsManager::DeleteAction))
	{
		m_actions[ActionsManager::DeleteAction]->setEnabled(m_hitResult.flags.testFlag(IsContentEditableTest) && !m_hitResult.flags.testFlag(IsEmptyTest));
	}

	if (m_actions.contains(ActionsManager::SelectAllAction))
	{
		m_actions[ActionsManager::SelectAllAction]->setEnabled(!m_hitResult.flags.testFlag(IsEmptyTest));
	}

	if (m_actions.contains(ActionsManager::ClearAllAction))
	{
		m_actions[ActionsManager::ClearAllAction]->setEnabled(m_hitResult.flags.testFlag(IsContentEditableTest) && !m_hitResult.flags.testFlag(IsEmptyTest));
	}

	if (m_actions.contains(ActionsManager::SearchAction))
	{
		const SearchInformation engine = SearchesManager::getSearchEngine(getOption(QLatin1String("Search/DefaultQuickSearchEngine")).toString());
		const bool isValid = !engine.identifier.isEmpty();

		m_actions[ActionsManager::SearchAction]->setEnabled(isValid);
		m_actions[ActionsManager::SearchAction]->setData(isValid ? engine.identifier : QVariant());
		m_actions[ActionsManager::SearchAction]->setIcon((!isValid || engine.icon.isNull()) ? Utils::getIcon(QLatin1String("edit-find")) : engine.icon);
		m_actions[ActionsManager::SearchAction]->setOverrideText(isValid ? engine.title : QT_TRANSLATE_NOOP("actions", "Search"));
		m_actions[ActionsManager::SearchAction]->setToolTip(isValid ? engine.description : tr("No search engines defined"));
	}

	if (m_actions.contains(ActionsManager::SearchMenuAction))
	{
		m_actions[ActionsManager::SearchMenuAction]->setEnabled(SearchesManager::getSearchEngines().count() > 1);
	}

	updateLinkActions();
	updateFrameActions();
	updateImageActions();
	updateMediaActions();
}
示例#23
0
const char* COption::getURL()
{
    return getOption('n');
}
  void CollocationIntegrator::setupFG() {

    // Interpolation order
    deg_ = getOption("interpolation_order");

    // All collocation time points
    std::vector<long double> tau_root = collocationPointsL(deg_, getOption("collocation_scheme"));

    // Coefficients of the collocation equation
    vector<vector<double> > C(deg_+1, vector<double>(deg_+1, 0));

    // Coefficients of the continuity equation
    vector<double> D(deg_+1, 0);

    // Coefficients of the quadratures
    vector<double> B(deg_+1, 0);

    // For all collocation points
    for (int j=0; j<deg_+1; ++j) {

      // Construct Lagrange polynomials to get the polynomial basis at the collocation point
      Polynomial p = 1;
      for (int r=0; r<deg_+1; ++r) {
        if (r!=j) {
          p *= Polynomial(-tau_root[r], 1)/(tau_root[j]-tau_root[r]);
        }
      }

      // Evaluate the polynomial at the final time to get the
      // coefficients of the continuity equation
      D[j] = zeroIfSmall(p(1.0L));

      // Evaluate the time derivative of the polynomial at all collocation points to
      // get the coefficients of the continuity equation
      Polynomial dp = p.derivative();
      for (int r=0; r<deg_+1; ++r) {
        C[j][r] = zeroIfSmall(dp(tau_root[r]));
      }

      // Integrate polynomial to get the coefficients of the quadratures
      Polynomial ip = p.anti_derivative();
      B[j] = zeroIfSmall(ip(1.0L));
    }

    // Symbolic inputs
    MX x0 = MX::sym("x0", f_.input(DAE_X).sparsity());
    MX p = MX::sym("p", f_.input(DAE_P).sparsity());
    MX t = MX::sym("t", f_.input(DAE_T).sparsity());

    // Implicitly defined variables (z and x)
    MX v = MX::sym("v", deg_*(nx_+nz_));
    vector<int> v_offset(1, 0);
    for (int d=0; d<deg_; ++d) {
      v_offset.push_back(v_offset.back()+nx_);
      v_offset.push_back(v_offset.back()+nz_);
    }
    vector<MX> vv = vertsplit(v, v_offset);
    vector<MX>::const_iterator vv_it = vv.begin();

    // Collocated states
    vector<MX> x(deg_+1), z(deg_+1);
    for (int d=1; d<=deg_; ++d) {
      x[d] = reshape(*vv_it++, this->x0().shape());
      z[d] = reshape(*vv_it++, this->z0().shape());
    }
    casadi_assert(vv_it==vv.end());

    // Collocation time points
    vector<MX> tt(deg_+1);
    for (int d=0; d<=deg_; ++d) {
      tt[d] = t + h_*tau_root[d];
    }

    // Equations that implicitly define v
    vector<MX> eq;

    // Quadratures
    MX qf = MX::zeros(f_.output(DAE_QUAD).sparsity());

    // End state
    MX xf = D[0]*x0;

    // For all collocation points
    for (int j=1; j<deg_+1; ++j) {
      //for (int j=deg_; j>=1; --j) {

      // Evaluate the DAE
      vector<MX> f_arg(DAE_NUM_IN);
      f_arg[DAE_T] = tt[j];
      f_arg[DAE_P] = p;
      f_arg[DAE_X] = x[j];
      f_arg[DAE_Z] = z[j];
      vector<MX> f_res = f_.call(f_arg);

      // Get an expression for the state derivative at the collocation point
      MX xp_j = C[0][j] * x0;
      for (int r=1; r<deg_+1; ++r) {
        xp_j += C[r][j] * x[r];
      }

      // Add collocation equation
      eq.push_back(vec(h_*f_res[DAE_ODE] - xp_j));

      // Add the algebraic conditions
      eq.push_back(vec(f_res[DAE_ALG]));

      // Add contribution to the final state
      xf += D[j]*x[j];

      // Add contribution to quadratures
      qf += (B[j]*h_)*f_res[DAE_QUAD];
    }

    // Form forward discrete time dynamics
    vector<MX> F_in(DAE_NUM_IN);
    F_in[DAE_T] = t;
    F_in[DAE_X] = x0;
    F_in[DAE_P] = p;
    F_in[DAE_Z] = v;
    vector<MX> F_out(DAE_NUM_OUT);
    F_out[DAE_ODE] = xf;
    F_out[DAE_ALG] = vertcat(eq);
    F_out[DAE_QUAD] = qf;
    F_ = MXFunction(F_in, F_out);
    F_.init();

    // Backwards dynamics
    // NOTE: The following is derived so that it will give the exact adjoint
    // sensitivities whenever g is the reverse mode derivative of f.
    if (!g_.isNull()) {

      // Symbolic inputs
      MX rx0 = MX::sym("x0", g_.input(RDAE_RX).sparsity());
      MX rp = MX::sym("p", g_.input(RDAE_RP).sparsity());

      // Implicitly defined variables (rz and rx)
      MX rv = MX::sym("v", deg_*(nrx_+nrz_));
      vector<int> rv_offset(1, 0);
      for (int d=0; d<deg_; ++d) {
        rv_offset.push_back(rv_offset.back()+nrx_);
        rv_offset.push_back(rv_offset.back()+nrz_);
      }
      vector<MX> rvv = vertsplit(rv, rv_offset);
      vector<MX>::const_iterator rvv_it = rvv.begin();

      // Collocated states
      vector<MX> rx(deg_+1), rz(deg_+1);
      for (int d=1; d<=deg_; ++d) {
        rx[d] = reshape(*rvv_it++, this->rx0().shape());
        rz[d] = reshape(*rvv_it++, this->rz0().shape());
      }
      casadi_assert(rvv_it==rvv.end());

      // Equations that implicitly define v
      eq.clear();

      // Quadratures
      MX rqf = MX::zeros(g_.output(RDAE_QUAD).sparsity());

      // End state
      MX rxf = D[0]*rx0;

      // For all collocation points
      for (int j=1; j<deg_+1; ++j) {

        // Evaluate the backward DAE
        vector<MX> g_arg(RDAE_NUM_IN);
        g_arg[RDAE_T] = tt[j];
        g_arg[RDAE_P] = p;
        g_arg[RDAE_X] = x[j];
        g_arg[RDAE_Z] = z[j];
        g_arg[RDAE_RX] = rx[j];
        g_arg[RDAE_RZ] = rz[j];
        g_arg[RDAE_RP] = rp;
        vector<MX> g_res = g_.call(g_arg);

        // Get an expression for the state derivative at the collocation point
        MX rxp_j = -D[j]*rx0;
        for (int r=1; r<deg_+1; ++r) {
          rxp_j += (B[r]*C[j][r]) * rx[r];
        }

        // Add collocation equation
        eq.push_back(vec(h_*B[j]*g_res[RDAE_ODE] - rxp_j));

        // Add the algebraic conditions
        eq.push_back(vec(g_res[RDAE_ALG]));

        // Add contribution to the final state
        rxf += -B[j]*C[0][j]*rx[j];

        // Add contribution to quadratures
        rqf += h_*B[j]*g_res[RDAE_QUAD];
      }

      // Form backward discrete time dynamics
      vector<MX> G_in(RDAE_NUM_IN);
      G_in[RDAE_T] = t;
      G_in[RDAE_X] = x0;
      G_in[RDAE_P] = p;
      G_in[RDAE_Z] = v;
      G_in[RDAE_RX] = rx0;
      G_in[RDAE_RP] = rp;
      G_in[RDAE_RZ] = rv;
      vector<MX> G_out(RDAE_NUM_OUT);
      G_out[RDAE_ODE] = rxf;
      G_out[RDAE_ALG] = vertcat(eq);
      G_out[RDAE_QUAD] = rqf;
      G_ = MXFunction(G_in, G_out);
      G_.init();
    }
  }
示例#25
0
const char* COption::getSimple()
{
    return getOption('s');
}
示例#26
0
文件: ci.cpp 项目: cran/lm.br
int Clmbr::ci_geo( METHOD met,  double incr, double * bds )
// Using Knowles, Siegmund and Zhang's geometric formula to calculate significance level.
// In Model=M1, treat regions before x[0] and after x[n-1] as two seperate regions.
// Conditional SL(th,mle-alpha) is not constant on end-intervals.
// 'incr' specified so as to cover same theta values as in 'cr' routine.
{
	Rcpp::Function  getOption("getOption");
	Rcpp::Function  Rflush("flush.console");

	int  numi=0, ind=0;		// ind = indicator = {0 if sl_geo was below SL, 1 if above}
	double th, sl_th =2, thold;

	if( Model==M3 )  {

		const double  sl_inf= sl(-Inf,met,false);
		th= min( -1., xs[0] );
		int it=0;
		while( fabs( sl_th - sl_inf ) > tol_sl_abs  &&  it < 18 )  
			th *= 2,  sl_th= sl(th,met,false),  it++;
		if (sl_th > SL)  bds[numi++] = -Inf,  ind= 1;
		thold= th;
		const double  thi = th,  inc = (xs[0]-thi)/(subints+0.5);


		for (th=thi;th<xs[0];th+=inc) {
			sl_th = sl(th,met,false);
			if (sl_th > SL && ind==0) {
				bds[numi++] = bisect_sl(thold,th,met,-tol_xb);
				ind=1;
			}
			if (sl_th < SL && ind==1) {
				bds[numi++] = bisect_sl(thold,th,met,-tol_xb);
				ind=0;
			}
			thold = th;
		}


	}  else  {
	
// start with point  xs[0]-1.
		th= xs[0] - 1.;
		sl_th= sl(th,met,false);
		if (sl_th > SL) {
			bds[numi++] = -Inf;
			ind= 1;
		}
		thold= th;

		if(Model==M1) {		// in M1, boundary is discontinuous at x[0]

			if(met==GEO) {
				th= xs[1]; 
				sl_th= sl(th,met,false);
				if (sl_th > SL && ind==0) {
					bds[numi++] = xs[0];
					ind=1;
				}
				if (sl_th < SL && ind==1) {
					bds[numi++] = xs[0];
					ind=0;
				}
				thold= th;
			}

			if(met==GEO2) {
				th = xs[0] + tol_xb/2;
				sl_th = sl(th,met,false);
				if (sl_th > SL && ind==0) {
					bds[numi++] = xs[0];
					ind=1;
				}
				if (sl_th < SL && ind==1) {
					bds[numi++] = xs[0];
					ind=0;
				}
				thold= th;
			}
		}

	}


// get critical points

	double* cpts= Calloc( ns+2, double );

	const double thmle = mle(false);

	double  thm = thmle;
	if(Model==M3)  thm = max( thmle, thold);

	int k= 0, ncp= 0;
	if(Model==M1) k= 1;
	if(met==GEO2 && Model==M1) cpts[ncp++]= xs[0]+tol_xb/2;
	if(met==GEO2 && Model==M2) cpts[ncp++]= xs[0]-1;
	while(xs[k]<thm) cpts[ncp++]= xs[k++];
	cpts[ncp++]= thm;
	if(thmle==xs[k]) k++;
	while( k < ns-1 ) cpts[ncp++]= xs[k++];
	if(met==GEO2) cpts[ncp++]= xs[ns-1]-tol_xb/2;

	bool msg= false;
	int  width =0,  col =33;
	double lag;
	if( met==GEO )  lag = 5;  else  lag = 10;
	double  tstart= time(NULL);

// grid search
	for (k = 0; k < ncp - 1; k++) {
		th= cpts[k];
			sl_th = sl(th,met,false);
			if (sl_th > SL && ind==0) {
				bds[numi++] = bisect_sl( thold, th, met, -tol_xb );
				ind= 1;
			}
			if (sl_th < SL && ind==1) {
				bds[numi++] = bisect_sl( thold, th, met, -tol_xb );
				ind= 0;
			}
			thold = th;

// a grid search can miss a small break in a confidence interval
// to avoid 'cr' finding a break that 'ci' misses
// setup the starting value and increments to cover the same points as in 'cr' routine
		double inc= incr;
		if(Model==M3 && k==0) inc= (cpts[k+1]-cpts[k])/(subints+0.5);
		while( (cpts[k+1]-cpts[k])/inc < subints + 1 )  inc /= 2.;
		double  fth= floor(th);
		while( fth < cpts[k] + tol_xb )  fth += inc;
		for ( th = fth; th < cpts[k+1] - tol_xb; th += inc )  { 
			sl_th = sl(th,met,false);
			if (sl_th > SL && ind==0) {
				bds[numi++] = bisect_sl( thold, th, met, -tol_xb );
				ind= 1;
			}
			if (sl_th < SL && ind==1) {
				bds[numi++] = bisect_sl( thold, th, met, -tol_xb );
				ind= 0;
			}
			thold = th;

			double  tfinish = time( NULL ),  elapsed = tfinish - tstart;
			if( elapsed > lag ) {
				if(!msg) { 
					Rcpp::IntegerVector  tw = getOption("width");
					width = tw[0];
					if(met==GEO)  { Rcout << "   " << _("progress:") << "   ";  col= 15; }
					msg=true; 
				}
				if( col > width - 6 )  { Rcout << endl;  col= 0; } 
				const double  progress = floor( 100*(th-cpts[0])/(cpts[ncp-1]-cpts[0]) );
				Rcout << progress << "%...   ";  Rflush();
				tstart= tfinish;
				col += 9;
			}
		}

	}
	if(msg && met==GEO) Rcout << endl << endl;

// check boundary of final end-interval
	th = cpts[k];
	sl_th = sl( th, met, false );
	if (sl_th > SL && ind==0) {
		bds[numi++] = bisect_sl( thold, th, met, -tol_xb );
		ind= 1;
	}
	if (sl_th < SL && ind==1) {
		bds[numi++] = bisect_sl( thold, th, met, -tol_xb );
		ind= 0;
	}


// check region after xs[ns-1]
	th = xs[ns-1]+1.;
	sl_th = sl(th,met,false);
	if (sl_th < SL && ind==1) bds[numi++] = xs[ns-1];
	if (sl_th > SL && ind==0) {
		bds[numi++] = xs[ns-1];
		bds[numi++] = Inf;
	}
	if (sl_th > SL && ind==1) bds[numi++] = Inf;


	Free( cpts );
	return numi/2;
}
void DirectMultipleShootingInternal::init(){
  // Initialize the base classes
  OCPSolverInternal::init();

  // Create an integrator instance
  integratorCreator integrator_creator = getOption("integrator");
  integrator_ = integrator_creator(ffcn_,FX());
  if(hasSetOption("integrator_options")){
    integrator_.setOption(getOption("integrator_options"));
  }

  // Set t0 and tf
  integrator_.setOption("t0",0);
  integrator_.setOption("tf",tf_/nk_);
  integrator_.init();
  
  // Path constraints present?
  bool path_constraints = nh_>0;
  
  // Count the total number of NLP variables
  int NV = np_ + // global parameters
           nx_*(nk_+1) + // local state
           nu_*nk_; // local control
           
  // Declare variable vector for the NLP
  // The structure is as follows:
  // np x 1  (parameters)
  // ------
  // nx x 1  (states at time i=0)
  // nu x 1  (controls in interval i=0)
  // ------
  // nx x 1  (states at time i=1)
  // nu x 1  (controls in interval i=1)
  // ------
  // .....
  // ------
  // nx x 1  (states at time i=nk)
  
  MX V("V",NV);

  // Global parameters
  MX P = V(Slice(0,np_));

  // offset in the variable vector
  int v_offset=np_; 
  
  // Disretized variables for each shooting node
  vector<MX> X(nk_+1), U(nk_);
  for(int k=0; k<=nk_; ++k){ // interior nodes
    // Local state
    X[k] = V[Slice(v_offset,v_offset+nx_)];
    v_offset += nx_;
    
    // Variables below do not appear at the end point
    if(k==nk_) break;
    
    // Local control
    U[k] = V[Slice(v_offset,v_offset+nu_)];
    v_offset += nu_;
  }
  
  // Make sure that the size of the variable vector is consistent with the number of variables that we have referenced
  casadi_assert(v_offset==NV);

  // Input to the parallel integrator evaluation
  vector<vector<MX> > int_in(nk_);
  for(int k=0; k<nk_; ++k){
    int_in[k].resize(INTEGRATOR_NUM_IN);
    int_in[k][INTEGRATOR_P] = vertcat(P,U[k]);
    int_in[k][INTEGRATOR_X0] = X[k];
  }

  // Input to the parallel function evaluation
  vector<vector<MX> > fcn_in(nk_);
  for(int k=0; k<nk_; ++k){
    fcn_in[k].resize(DAE_NUM_IN);
    fcn_in[k][DAE_T] = (k*tf_)/nk_;
    fcn_in[k][DAE_P] = vertcat(P,U.at(k));
    fcn_in[k][DAE_X] = X[k];
  }

  // Options for the parallelizer
  Dictionary paropt;
  
  // Transmit parallelization mode
  if(hasSetOption("parallelization"))
    paropt["parallelization"] = getOption("parallelization");
  
  // Evaluate function in parallel
  vector<vector<MX> > pI_out = integrator_.call(int_in,paropt);

  // Evaluate path constraints in parallel
  vector<vector<MX> > pC_out;
  if(path_constraints)
    pC_out = cfcn_.call(fcn_in,paropt);
  
  //Constraint function
  vector<MX> gg(2*nk_);

  // Collect the outputs
  for(int k=0; k<nk_; ++k){
    //append continuity constraints
    gg[2*k] = pI_out[k][INTEGRATOR_XF] - X[k+1];
    
    // append the path constraints
    if(path_constraints)
      gg[2*k+1] = pC_out[k][0];
  }

  // Terminal constraints
  MX g = vertcat(gg);

  // Objective function
  MX f;
  if (mfcn_.getNumInputs()==1) {
    f = mfcn_.call(X.back()).front();
  } else {
    vector<MX> mfcn_argin(MAYER_NUM_IN); 
    mfcn_argin[MAYER_X] = X.back();
    mfcn_argin[MAYER_P] = P;
    f = mfcn_.call(mfcn_argin).front();
  }

  // NLP
  nlp_ = MXFunction(nlpIn("x",V),nlpOut("f",f,"g",g));
  nlp_.setOption("ad_mode","forward");
  nlp_.init();
  
  // Get the NLP creator function
  NLPSolverCreator nlp_solver_creator = getOption("nlp_solver");
  
  // Allocate an NLP solver
  nlp_solver_ = nlp_solver_creator(nlp_);
  
  // Pass user options
  if(hasSetOption("nlp_solver_options")){
    const Dictionary& nlp_solver_options = getOption("nlp_solver_options");
    nlp_solver_.setOption(nlp_solver_options);
  }
  
  // Initialize the solver
  nlp_solver_.init();
}
示例#28
0
int SocketImpl::getSendBufferSize()
{
    int result;
    getOption(SOL_SOCKET, SO_SNDBUF, result);
    return result;
}
示例#29
0
local void Begin(Player *host, Arena *arena, const char *params)
{
    /* Set the game as started */
    Adata *adata = P_ARENA_DATA(arena, arenaKey);
    if (adata->started >= 1)
    {
        chat->SendMessage(host, "There is already a game running. Please use ?stop to end the current game.");
        return;
    }
    else
        adata->started = 1;
    
    /* Get Game Options*/
    //goals
    int goals;
    char *next, *string;
    string = getOption(params, 'g');
    
    if (string != next)
    {
        goals = atoi(string);
        if ((goals <= 15) && (goals > 0))
            adata->goals = goals;
        else
        {
            Abort(arena, host, 1);
            return;
        }
    }
    else
    {
        Abort(arena, host, 2);
        return;
    }
    
    //ships
    string = getOption(params, 's');
    
    int ii;
    for (ii = 0; ii <= 8; ii++)
    {
        allships[ii] = 0; //reset everyship
    }
    
    
    int length = strlen(string);
    
    if ((string != next) && (string) && (length >= 1))
    {
        if ((length % 2 == 0)  || (length > 15) || (!length))
        {
            Abort(arena, host, 3);
            return;
        }
        else
        {
            int i;
            for (i = 0; i < length; i++)
            {
                if (string[i] != ',');
                {
                    char first[64];
                    //strncpy(first, string + i, 60);
                    snprintf(first, sizeof(first) - 10, "%s", string + i * 2);
                    first[1] = '\0';
                    
                    //chat->SendMessage(host, "Ship %s", first);

                    int legal = atoi(first) - 1;
                    if (legal == -1)
                        break;
                    
                    if (legal < 0 || legal > 7)
                    {
                        //chat->SendMessage(host, "Legal %i", legal);
                        Abort(arena, host, 4);
                        return;
                    }
                    else
                    {
                        LegalShip(legal, arena);
                    }
                    first[0] = '\0';
                    //free(first);
                }
            }
            char first[64];
            strncpy(first, string, 4);
            first[1] = '\0';
            adata->defaultship = atoi(first) - 1;
            CheckLegalShip(arena);
            
            adata->lockships = 1;
        }
    }
    else
    {
        for (ii = 0; ii < 8; ii++)
        {
            allships[ii] = 1; //all ships are legal
        }
        adata->lockships = 0;
    }
    
    /* Close the doors */
    Player *d;
    Link *link;

    cs->ArenaOverride(arena, ok_Doors, 255);

    pd->Lock();
    FOR_EACH_PLAYER(d)
    {
        cs->SendClientSettings(d);
    }
    pd->Unlock();
    
    chat->SendArenaSoundMessage(arena, 2, "Paintball will start in 10 seconds, get ready!");
    if (adata->lockships)
        chat->SendArenaMessage(arena, "Allowed ships: %s", string);
    
    CheckLegalShip(arena);
    
    adata->started = 1;
    /* Start the timer */
    ml->SetTimer(TimeUp, 1000, 1000, host, NULL);
}
示例#30
0
/// @brief check if received message should be accepted.
///
/// The following conditions are checked:
/// - is server on the black-list?
/// - are all requested options present?
/// - is there requested IA option?
/// - is there requested TA option?
///
/// @param msg server's REPLY
///
/// @return true if REPLY is rejected
bool TClntMsgSolicit::shallRejectAnswer(SPtr<TClntMsg> msg)
{
    bool somethingAssigned = false;

    // this == solicit or request
    // msg  == reply
    SPtr<TOptDUID> srvDUID = (Ptr*) msg->getOption(OPTION_SERVERID);
    if (!srvDUID) {
        Log(Notice) << "No server identifier provided. Message ignored." << LogEnd;
        return true;
    }
    
    //is this server rejected?
    SPtr<TClntCfgIface> iface = ClntCfgMgr().getIface(this->Iface);
    if (!iface) {
        Log(Error) << "Unable to find iface=" << this->Iface << "." << LogEnd;
        return true;
    }
    if (iface->isServerRejected(msg->getAddr(), srvDUID->getDUID())) {
	Log(Notice) << "Server was rejected (duid=" << srvDUID->getDUID() << ")." << LogEnd;
        return true;
    }

    // have we asked for IA?
    bool iaOk = true;
    if (this->getOption(OPTION_IA_NA))
    {
        ///@todo Check if proper IAIDs are returned, also if all IA were answered (if requested several IAs were requested)
        ///@todo Check all IA_NAs, not just first one
        SPtr<TClntOptIA_NA> ia = (Ptr*)msg->getOption(OPTION_IA_NA);
        if (!ia)  {
            Log(Notice) << "IA_NA option requested, but not present in this message. Ignored." << LogEnd;
            iaOk = false;
        } else {
            if (!ia->getOption(OPTION_IAADDR)) {
                Log(Notice) << "IA_NA option returned, but without any addresses. Ignored." << LogEnd;
                iaOk = false;
            }
            SPtr<TClntOptStatusCode> st = (Ptr*)ia->getOption(OPTION_STATUS_CODE);
            if (st && st->getCode()!= STATUSCODE_SUCCESS) {
                Log(Notice) << "IA_NA has status code!=SUCCESS: " << st->getCode()
                            << "(" << st->getText() << "). Ignored." << LogEnd;
                iaOk = false;
            }
        }
        if (iaOk)
            somethingAssigned = true;
    }

    // have we asked for TA?
    bool taOk = true;
    if (this->getOption(OPTION_IA_TA)) {
        SPtr<TClntOptTA> ta = (Ptr*)msg->getOption(OPTION_IA_TA);
        if (!ta) {
            Log(Notice) << "TA option requested, but not present in this message. Ignored." << LogEnd;
            taOk = false;
        } else {
            if (!ta->getOption(OPTION_IAADDR)) {
                Log(Notice) << "TA option received, but without IAADDR" << LogEnd;
                taOk = false;
            }

            SPtr<TClntOptStatusCode> st = (Ptr*)ta->getOption(OPTION_STATUS_CODE);
            if (st && st->getCode()!= STATUSCODE_SUCCESS) {
                Log(Notice) << "IA_TA has status code!=SUCCESS: " << st->getCode()
                            << "(" << st->getText() << "). Ignored." << LogEnd;
                taOk = false;
            }
        }
        if (taOk)
            somethingAssigned = true;
    }

    // have we asked for PD?
    bool pdOk = true;
    if (getOption(OPTION_IA_PD)) {
        SPtr<TClntOptIA_PD> pd = (Ptr*) msg->getOption(OPTION_IA_PD);
        if (!pd) {
            Log(Notice) << "PD option requested, but not returned in this message. Ignored." << LogEnd;
            pdOk = false;
        } else {

	    if (!pd->getOption(OPTION_IAPREFIX)) {
		Log(Notice) << "Received PD without any prefixes." << LogEnd;
		pdOk = false;
	    }

	    SPtr<TClntOptStatusCode> st = (Ptr*)pd->getOption(OPTION_STATUS_CODE);
	    if (st && st->getCode()!= STATUSCODE_SUCCESS) {
		Log(Notice) << "IA_NA has status code!=SUCCESS: " << st->getCode()
			    << "(" << st->getText() << "). Ignored." << LogEnd;
		pdOk = false;
	    }
        }
        if (pdOk)
            somethingAssigned = true;
    }

    if (!somethingAssigned)
        return true; // this advertise does not offers us anything

    if (!ClntCfgMgr().insistMode())
        return false; // accept this advertise

    // insist-mode enabled. We MUST get everything we wanted or we reject this answer
    if (iaOk && taOk && pdOk)
        return false;
    else
        return true;
}