PlanProjectionCell::PlanProjectionCell():
	Cell()
{
	parameters()["name"] = "PlanProjectionCell";
	proj.setModelType (pcl::SACMODEL_PLANE);
}
Exemplo n.º 2
0
void PlayerActionJob::start()
{
    const QString operation(operationName());

    kDebug() << "Trying to perform the action" << operationName();
    if (!m_controller->isOperationEnabled(operation)) {
        setError(Denied);
        emitResult();
        return;
    }

    if (operation == QLatin1String("Quit") || operation == QLatin1String("Raise")
                                           || operation == QLatin1String("SetFullscreen")) {
        listenToCall(m_controller->rootInterface()->asyncCall(operation));
    } else if (operation == QLatin1String("Play")
               || operation == QLatin1String("Pause")
               || operation == QLatin1String("PlayPause")
               || operation == QLatin1String("Stop")
               || operation == QLatin1String("Next")
               || operation == QLatin1String("Previous")) {
        listenToCall(m_controller->playerInterface()->asyncCall(operation));
    } else if (operation == "Seek") {
        if (parameters().value("microseconds").type() == QVariant::LongLong) {
            listenToCall(m_controller->playerInterface()->asyncCall(operation, parameters()["microseconds"]));
        } else {
            setErrorText("microseconds");
            setError(MissingArgument);
            emitResult();
        }
    } else if (operation == "SetPosition") {
        if (parameters().value("microseconds").type() == QVariant::LongLong) {
            listenToCall(m_controller->playerInterface()->asyncCall(operation,
                         m_controller->trackId(),
                         parameters()["microseconds"]));
        } else {
            setErrorText("microseconds");
            setError(MissingArgument);
            emitResult();
        }
    } else if (operation == "OpenUri") {
        if (parameters().value("uri").canConvert<KUrl>()) {
            listenToCall(m_controller->playerInterface()->asyncCall(operation,
                         QString::fromLatin1(parameters()["uri"].toUrl().toEncoded())));
        } else {
            kDebug() << "uri was of type" << parameters().value("uri").userType();
            setErrorText("uri");
            setError(MissingArgument);
            emitResult();
        }
    } else if (operation == "SetLoopStatus") {
        if (parameters().value("status").type() == QVariant::String) {
            setDBusProperty(m_controller->playerInterface()->interface(),
                    "LoopStatus", QDBusVariant(parameters()["status"]));
        } else {
            setErrorText("status");
            setError(MissingArgument);
            emitResult();
        }
    } else if (operation == "SetShuffle") {
        if (parameters().value("on").type() == QVariant::Bool) {
            setDBusProperty(m_controller->playerInterface()->interface(),
                    "Shuffle", QDBusVariant(parameters()["on"]));
        } else {
            setErrorText("on");
            setError(MissingArgument);
            emitResult();
        }
    } else if (operation == "SetRate") {
        if (parameters().value("rate").type() == QVariant::Double) {
            setDBusProperty(m_controller->playerInterface()->interface(),
                    "Rate", QDBusVariant(parameters()["rate"]));
        } else {
            setErrorText("rate");
            setError(MissingArgument);
            emitResult();
        }
    } else if (operation == "SetVolume") {
        if (parameters().value("level").type() == QVariant::Double) {
            setDBusProperty(m_controller->playerInterface()->interface(),
                    "Volume", QDBusVariant(parameters()["level"]));
        } else {
            setErrorText("level");
            setError(MissingArgument);
            emitResult();
        }
    } else {
        setError(UnknownOperation);
        emitResult();
    }
}
Exemplo n.º 3
0
mitk::PropertyList::Pointer mitk::CustomTagParser::ParseDicomPropertyString(std::string dicomPropertyString)
{
  auto results = mitk::PropertyList::New();
  if ("" == dicomPropertyString)
  {
    //MITK_ERROR << "Could not parse empty custom dicom string";
    return results;
  }

  std::map<std::string, std::string> privateParameters;

  // convert hex to ascii
  // the Siemens private tag contains the information like this
  // "43\52\23\34" we jump over each \ and convert the number
  int len = dicomPropertyString.length();
  std::string asciiString;
  for (int i = 0; i < len; i += 3)
  {
    std::string byte = dicomPropertyString.substr(i, 2);
    auto chr = (char)(int)strtol(byte.c_str(), nullptr, 16);
    asciiString.push_back(chr);
  }

  // extract parameter list
  std::size_t beginning = asciiString.find("### ASCCONV BEGIN ###") + 21;
  std::size_t ending = asciiString.find("### ASCCONV END ###");
  std::string parameterListString = asciiString.substr(beginning, ending - beginning);

  boost::replace_all(parameterListString, "\r\n", "\n");
  boost::char_separator<char> newlineSeparator("\n");
  boost::tokenizer<boost::char_separator<char>> parameters(parameterListString, newlineSeparator);
  for (const auto &parameter : parameters)
  {
    std::vector<std::string> parts;
    boost::split(parts, parameter, boost::is_any_of("="));

    if (parts.size() == 2)
    {
      parts[0].erase(std::remove(parts[0].begin(), parts[0].end(), ' '), parts[0].end());
      parts[1].erase(parts[1].begin(), parts[1].begin() + 1); // first character is a space
      privateParameters[parts[0]] = parts[1];
    }
  }

  std::string revisionString = "";

  try
  {
    revisionString = ExtractRevision(privateParameters["tSequenceFileName"]);
  }
  catch (const std::exception &e)
  {
    MITK_ERROR << "Cannot deduce revision information. Reason: "<< e.what();
    return results;
  }

  results->SetProperty(m_RevisionPropertyName, mitk::StringProperty::New(revisionString));

  std::string jsonString = GetRevisionAppropriateJSONString(revisionString);

  boost::property_tree::ptree root;
  std::istringstream jsonStream(jsonString);
  try
  {
    boost::property_tree::read_json(jsonStream, root);
  }
  catch (const boost::property_tree::json_parser_error &e)
  {
    mitkThrow() << "Could not parse json file. Error was:\n" << e.what();
  }

  for (auto it : root)
  {
    if (it.second.empty())
    {
      std::string propertyName = m_CESTPropertyPrefix + it.second.data();
      if (m_JSONRevisionPropertyName == propertyName)
      {
        results->SetProperty(propertyName, mitk::StringProperty::New(it.first));
      }
      else
      {
        results->SetProperty(propertyName, mitk::StringProperty::New(privateParameters[it.first]));
      }
    }
    else
    {
      MITK_ERROR << "Currently no support for nested dicom tag descriptors in json file.";
    }
  }

  std::string offset = "";
  std::string measurements = "";
  results->GetStringProperty("CEST.Offset", offset);
  results->GetStringProperty("CEST.measurements", measurements);

  if ("" == measurements)
  {
    std::string stringRepetitions = "";
    std::string stringAverages = "";
    results->GetStringProperty("CEST.repetitions", stringRepetitions);
    results->GetStringProperty("CEST.averages", stringAverages);
    std::stringstream  measurementStream;
    try
    {
      measurementStream << std::stoi(stringRepetitions) + std::stoi(stringAverages);
      measurements = measurementStream.str();
      MITK_INFO << "Could not find measurements, assuming repetitions + averages. Which is: " << measurements;
    }
    catch (const std::invalid_argument &ia)
    {
      MITK_ERROR
        << "Could not find measurements, fallback assumption of repetitions + averages could not be determined either: "
        << ia.what();
    }
  }

  std::string preparationType = "";
  std::string recoveryMode = "";
  std::string spoilingType = "";
  results->GetStringProperty(CEST_PROPERTY_NAME_PREPERATIONTYPE().c_str(), preparationType);
  results->GetStringProperty(CEST_PROPERTY_NAME_RECOVERYMODE().c_str(), recoveryMode);
  results->GetStringProperty(CEST_PROPERTY_NAME_SPOILINGTYPE().c_str(), spoilingType);

  if (this->IsT1Sequence(preparationType, recoveryMode, spoilingType, revisionString))
  {
    MITK_INFO << "Parsed as T1 image";

    mitk::LocaleSwitch localeSwitch("C");

    std::stringstream trecStream;

    std::string trecPath = m_DicomDataPath + "/TREC.txt";
    std::ifstream list(trecPath.c_str());

    if (list.good())
    {
      std::string currentTime;
      while (std::getline(list, currentTime))
      {
        trecStream << currentTime << " ";
      }
    }
    else
    {
      MITK_WARN << "Assumed T1, but could not load TREC at " << trecPath;
    }

    results->SetStringProperty(CEST_PROPERTY_NAME_TREC().c_str(), trecStream.str().c_str());
  }
  else
  {
    MITK_INFO << "Parsed as CEST or WASABI image";
    std::string sampling = "";
    bool hasSamplingInformation = results->GetStringProperty("CEST.SamplingType", sampling);
    if (hasSamplingInformation)
    {
      std::string offsets = GetOffsetString(sampling, offset, measurements);
      results->SetStringProperty(m_OffsetsPropertyName.c_str(), offsets.c_str());
    }
    else
    {
      MITK_WARN << "Could not determine sampling type.";
    }
  }


  //persist all properties
  mitk::IPropertyPersistence *persSrv = GetPersistenceService();
  if (persSrv)
  {
    auto propertyMap = results->GetMap();
    for (auto const &prop : *propertyMap)
    {
      PropertyPersistenceInfo::Pointer info = PropertyPersistenceInfo::New();
      std::string key = prop.first;
      std::replace(key.begin(), key.end(), '.', '_');
      info->SetNameAndKey(prop.first, key);

      persSrv->AddInfo(info);
    }
  }

  return results;
}
Exemplo n.º 4
0
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Seiscomp::IO::DatabaseInterface* DatabaseProvideMessage::database() const {
	return Seiscomp::IO::DatabaseInterface::Open((service() +
	                                              std::string("://") +
	                                              parameters()).c_str());
}
Exemplo n.º 5
0
int main (int argc, char **argv)
{
   int i;
   char *cp;
   bool greeting;
   int tmo = 600;

   progname = ((cp = strrchr(argv[0], '/')) ? cp + 1 : argv[0]);

   parameters(TRUE);

   greeting = TRUE;
   while ((i = opt_get(argc, argv, "t")) > -1)
      switch (i)
      {
         case 'P': log_with_pid(); break;
         case 'd': debug++; break;
         case 'V': version(); _exit(0);
         case 'S': greeting = FALSE; break;
         case 't':
            if (!opt_arg)
               fail(1, "Need value for \"t\"");
            if ((tmo = strtoul(opt_arg, &cp, 10)) < 0 || *cp)
               fail(1, "Timeout must be positive");
            break;
         default: usage();
      }

   if (opt_ind < argc)
   {
      int pid, lg[2];

      if (-1 == (pid = pipefork(lg)))
         fail(2, "pipe/fork:%m");
      if (0 == pid)
      {
         if (-1 == dup2(lg[0], 0))
            fail(2, "dup:%m");
         dup2(1, 2);
         close(lg[1]);
         execvp(argv[opt_ind], argv + opt_ind);
         LOG("exec(%s):%m", argv[opt_ind]);
         _exit(2);
      }
      close(lg[0]);
      if (-1 == dup2(lg[1], 2))
         fail(2, "dup:%m");
   }

   if (-1 == readln_ready(0, tmo, &input))
      FAIL(2, "readln_ready:%m");

   init();
   set_path_var();
   
   if (greeting)
   {
      args[1] = "READER";
      do_mode();
   }
   
   /* Main loop */

   while (1)
   {
      int nr;

      switch ((nr = args_read(&input)))
      {
         case 0:
            args_write(1, "501 Bad command\r\n");
            continue;
         case -1:
            do_quit(); /* Does not return */
      }
      if (checkservice)
         docheckservice(); /* May not return */
      for (i = 0; i < sizeof (cmds) / sizeof (struct cmd); i++)
      {
         if (strcasecmp(args[0], cmds[i].name))
            continue;
         if (nr < cmds[i].needs_args)
            args_write(1, "501 Bad syntax\r\n");
         else if (cmds[i].needs_group && !currentgroup)
            args_write(1, "412 No group selected\r\n");
         else if (cmds[i].needs_article && -1 == currentserial)
            args_write(1, "420 No article selected\r\n");
         else if (!nr_keys && cmds[i].needs_grouplist && -1 == getallgroups())
            args_write(1, "503 No memory\r\n");
         else
            (*cmds[i].function) ();
         break;
      }
      if (i >= sizeof (cmds) / sizeof (struct cmd))
         args_write(1, "500 unimplemented\r\n");
   }
   /* Not Reached */
}
Exemplo n.º 6
0
Arquivo: snget.c Projeto: liu-chong/sn
int main (int argc, char **argv)
{
   char optdebugbuf[7];
   int n, mark;
   char *cp;

   progname = ((cp = strrchr(argv[0], '/')) ? cp + 1 : argv[0]);

   while ((n = opt_get(argc, argv, "pthcmo")) > -1)
      switch (n)
      {
         case 'd':
            if (++debug < 6)
	    {
               if (!optdebug)
                  strcpy(optdebug = optdebugbuf, "-d");
               else
                  strcat(optdebug, "d");
            }
            break;
         case 'V': version(); _exit(0);
         case 't':
            if (!opt_arg)
               usage();
            LOG("option \"-t %s\" no longer supported", opt_arg);
            break;
         case 'p':
            if (!opt_arg)
               usage();
            concurrency = strtoul(opt_arg, &cp, 10);
            if (concurrency > MAX_CONCURRENCY || concurrency <= 0 || *cp)
               fail(1, "Bad value for concurrency option -p");
            break;
         case 'h':
            if (!opt_arg)
               usage();
            throttlerate = strtoul(opt_arg, &cp, 10);
            if (throttlerate < 0)
               fail(1, "Bad value for throttle option -h");
            break;
         case 'c':
            if (!(optpipelining = opt_arg))
               usage();
            if (strtoul(optpipelining, &cp, 10) < 0 || *cp)
               fail(1, "Bad value for pipeline option -c");
            break;
         case 'm':
            if (!(optmax = opt_arg))
               usage();
            if (strtoul(optmax, &cp, 10) <= 0 || *cp)
               fail(1, "Bad value for max-prime-articles option -m");
            break;
         case 'P':
            optlogpid = TRUE;
            log_with_pid();
            break;
         default:
            usage();
      }
   close(0);
   open("/dev/null", O_RDONLY);
   /* snag 6 and 7 so we can dup onto them */
   if (-1 == dup2(2, 6) || -1 == dup2(2, 7) || -1 == dup2(2, 1))
      fail(2, "Unable to dup standard error:%m");

   parameters(TRUE);
   if (-1 == chdir(snroot))
      fail(2, "chdir(%s):%m", snroot);
   init();
   if (-1 == set_path_var())
      fail(2, "No memory");

   n = 0;
   if (opt_ind == argc)
   {
      DIR *dir;
      struct dirent *dp;
      struct stat st;
      char ch;

      if (!(dir = opendir(".")))
         fail(2, "opendir(%s):%m", snroot);
      while ((dp = readdir(dir)))
         if (is_valid_group(dp->d_name))
            if (-1 == readlink(dp->d_name, &ch, 1)) /* no symlinks */
               if (0 == statf(&st, "%s/.outgoing", dp->d_name))
                  if (S_ISDIR(st.st_mode))
                     if (add(dp->d_name) > -1)   /* NB: add() from get.c */
                        n++;
      closedir(dir);
   }
   else
   {
      debug++;
      for (; opt_ind < argc; opt_ind++)
         if (add(argv[opt_ind]) > -1)
            n++;
      debug--;
   }

   if (n == 0)
      fail(0, "No groups to fetch");

   for (mark = 0; jobs_not_done(); mark++)
   {
      struct timeval tv;
      fd_set rset;
      int max;

      while (sow() == 0)   /* Start some jobs */
         ;
      FD_ZERO(&rset);
      if (throttlerate)
      {
         max = throttle_setfds(&rset);
         if (sigusr)
         {
            sigusr = FALSE;
            LOG("throttling at %d bytes/sec", throttlerate);
         }
      }
      else
         max = -1;
      
      tv.tv_sec = 1;
      tv.tv_usec = 0;
      if (select(max + 1, &rset, NULL, NULL, &tv) > 0)
         if (throttlerate)
            throttle(&rset);
      
      if (sigchld || 1 == mark % 10)
      {
         sigchld = FALSE;
         while (reap() == 0)
            ;
      }
   }
   quit();
   _exit(0);
}
bool ArgumentCoder<WebCore::FilterOperations>::decode(ArgumentDecoder& decoder, WebCore::FilterOperations& filters)
{
    uint32_t size;
    if (!decoder.decode(size))
        return false;

    Vector<RefPtr<FilterOperation> >& operations = filters.operations();

    for (size_t i = 0; i < size; ++i) {
        FilterOperation::OperationType type;
        RefPtr<FilterOperation> filter;
        if (!decoder.decodeEnum(type))
            return false;

        switch (type) {
        case FilterOperation::GRAYSCALE:
        case FilterOperation::SEPIA:
        case FilterOperation::SATURATE:
        case FilterOperation::HUE_ROTATE: {
            double value;
            if (!decoder.decode(value))
                return false;
            filter = BasicColorMatrixFilterOperation::create(value, type);
            break;
        }
        case FilterOperation::INVERT:
        case FilterOperation::BRIGHTNESS:
        case FilterOperation::CONTRAST:
        case FilterOperation::OPACITY: {
            double value;
            if (!decoder.decode(value))
                return false;
            filter = BasicComponentTransferFilterOperation::create(value, type);
            break;
        }
        case FilterOperation::BLUR: {
            Length length;
            if (!ArgumentCoder<Length>::decode(decoder, length))
                return false;
            filter = BlurFilterOperation::create(length, type);
            break;
        }
        case FilterOperation::DROP_SHADOW: {
            IntPoint location;
            int32_t stdDeviation;
            Color color;
            if (!ArgumentCoder<IntPoint>::decode(decoder, location))
                return false;
            if (!decoder.decode(stdDeviation))
                return false;
            if (!ArgumentCoder<Color>::decode(decoder, color))
                return false;
            filter = DropShadowFilterOperation::create(location, stdDeviation, color, type);
            break;
        }
#if ENABLE(CSS_SHADERS)
        case FilterOperation::CUSTOM:
            // Custom Filters are converted to VALIDATED_CUSTOM before reaching this point.
            ASSERT_NOT_REACHED();
            break;
        case FilterOperation::VALIDATED_CUSTOM: {
            // FIXME: CustomFilterOperation should not need the meshType.
            // https://bugs.webkit.org/show_bug.cgi?id=102529
            CustomFilterMeshType meshType;
            if (!decoder.decodeEnum(meshType))
                return false;
            int programID = 0;
            if (!decoder.decode(programID))
                return false;

            uint32_t parametersSize;
            if (!decoder.decode(parametersSize))
                return false;

            CustomFilterParameterList parameters(parametersSize);
            for (size_t i = 0; i < parametersSize; ++i) {
                String name;
                CustomFilterParameter::ParameterType parameterType;
                if (!decoder.decode(name))
                    return false;
                if (!decoder.decodeEnum(parameterType))
                    return false;

                switch (parameterType) {
                case CustomFilterParameter::ARRAY: {
                    RefPtr<CustomFilterArrayParameter> arrayParameter = CustomFilterArrayParameter::create(name);
                    uint32_t arrayParameterSize;
                    if (!decoder.decode(arrayParameterSize))
                        return false;
                    double arrayParameterValue;
                    for (size_t j = 0; j < arrayParameterSize; ++j) {
                        if (!decoder.decode(arrayParameterValue))
                            return false;
                        arrayParameter->addValue(arrayParameterValue);
                    }
                    parameters[i] = arrayParameter.release();
                    break;
                }
                case CustomFilterParameter::NUMBER: {
                    RefPtr<CustomFilterNumberParameter> numberParameter = CustomFilterNumberParameter::create(name);
                    uint32_t numberParameterSize;
                    if (!decoder.decode(numberParameterSize))
                        return false;
                    double numberParameterValue;
                    for (size_t j = 0; j < numberParameterSize; ++j) {
                        if (!decoder.decode(numberParameterValue))
                            return false;
                        numberParameter->addValue(numberParameterValue);
                    }
                    parameters[i] = numberParameter.release();
                    break;
                }
                case CustomFilterParameter::TRANSFORM: {
                    RefPtr<CustomFilterTransformParameter> transformParameter = CustomFilterTransformParameter::create(name);
                    TransformOperations operations;
                    if (!ArgumentCoder<TransformOperations>::decode(decoder, operations))
                        return false;
                    transformParameter->setOperations(operations);
                    parameters[i] = transformParameter.release();
                    break;
                }
                }
            }

            unsigned meshRows;
            unsigned meshColumns;
            if (!decoder.decode(meshRows))
                return false;
            if (!decoder.decode(meshColumns))
                return false;

            // At this point the Shaders are already validated, so we just use WebCustomFilterOperation for transportation.
            filter = CoordinatedCustomFilterOperation::create(0, programID, parameters, meshRows, meshColumns, meshType);
            break;
        }
#endif
        default:
            break;
        }

        if (filter)
            operations.append(filter);
    }

    return true;
}
Exemplo n.º 8
0
const Style *StyleController::adaptObjectStyle(const StyledObject &object)
{
    Parameters parameters(this);
    return m_defaultStyleEngine->applyObjectStyle(m_defaultStyle.data(), object, &parameters);
}
Exemplo n.º 9
0
const Style *StyleController::adaptStyle(StyleEngine::ElementType elementType)
{
    Parameters parameters(this);
    return m_defaultStyleEngine->applyStyle(m_defaultStyle.data(), elementType, &parameters);
}
Exemplo n.º 10
0
const Style *StyleController::adaptObjectStyle(StyleEngine::ElementType elementType, const ObjectVisuals &objectVisuals)
{
    Parameters parameters(this);
    return m_defaultStyleEngine->applyObjectStyle(m_defaultStyle.data(), elementType, objectVisuals, &parameters);
}
Exemplo n.º 11
0
bool UffTorsionCalculation::setup()
{
    UffForceField *forceField = static_cast<UffForceField *>(this->forceField());

    const chemkit::ForceFieldAtom *b = atom(1);
    const chemkit::ForceFieldAtom *c = atom(2);

    if(b->type().length() < 3 || c->type().length() < 3){
        return false;
    }

    const UffAtomParameters *pb = parameters(b);
    const UffAtomParameters *pc = parameters(c);

    chemkit::Real V = 0;
    chemkit::Real n = 0;
    chemkit::Real phi0 = 0;

    // sp3-sp3
    if(b->type()[2] == '3' && c->type()[2] == '3'){

        // exception for two group six atoms
        if(forceField->isGroupSix(b) && forceField->isGroupSix(c)){
            if(b->atom()->is(chemkit::Atom::Oxygen) && c->atom()->is(chemkit::Atom::Oxygen)){
                V = 2; // sqrt(2*2)
            }
            else if(b->atom()->is(chemkit::Atom::Oxygen) || c->atom()->is(chemkit::Atom::Oxygen)){
                V = sqrt(2 * 6.8);
            }
            else{
                V = sqrt(6.8 * 6.8);
            }

            n = 2;
            phi0 = 90;
        }

        // general case
        else{
            // equation 16
            V = sqrt(pb->V * pc->V);

            n = 3;
            phi0 = 180 * chemkit::constants::DegreesToRadians;
        }
    }
    // sp2-sp2
    else if((b->type()[2] == '2' || b->type()[2] == 'R') && (c->type()[2] == '2' || c->type()[2] == 'R')){
        chemkit::Real bondorder = bondOrder(b, c);

        // equation 17
        V = 5 * sqrt(pb->U * pc->U) * (1 + 4.18 * log(bondorder));

        n = 2;
        phi0 = 180 * chemkit::constants::DegreesToRadians;
    }
    // group 6 sp3 - any sp2 or R
    else if((forceField->isGroupSix(b) && (c->type()[2] == '2' || c->type()[2] == 'R')) ||
            (forceField->isGroupSix(c) && (b->type()[2] == '2' || b->type()[2] == 'R'))){
        chemkit::Real bondorder = bondOrder(b, c);

        // equation 17
        V = 5 * sqrt(pb->U * pc->U) * (1 + 4.18 * log(bondorder));

        n = 2;
        phi0 = 90 * chemkit::constants::DegreesToRadians;
    }
    // sp3-sp2
    else if((b->type()[2] == '3' && (c->type()[2] == '2' || c->type()[2] == 'R')) ||
            (c->type()[2] == '3' && (b->type()[2] == '2' || b->type()[2] == 'R'))){
        V = 1;
        n = 6;
        phi0 = 0;
    }
    else{
        return false;
    }

    setParameter(0, V);
    setParameter(1, n);
    setParameter(2, phi0);

    return true;
}
Exemplo n.º 12
0
const Style *StyleController::adaptBoundaryStyle(const DBoundary *boundary)
{
    Parameters parameters(this);
    return m_defaultStyleEngine->applyBoundaryStyle(m_defaultStyle.data(), boundary, &parameters);
}
Exemplo n.º 13
0
void MoveEstimation::addMeassurement(Eigen::Matrix4f &m) {
  MoveParameters parameters(m);
  estimator.addMeassurement(parameters);
}
Exemplo n.º 14
0
void PowerManagementJob::start()
{
    const QString operation = operationName();
    //qDebug() << "starting operation  ... " << operation;

    if (operation == QLatin1String("lockScreen")) {
        if (KAuthorized::authorizeKAction(QStringLiteral("lock_screen"))) {
            const QString interface(QStringLiteral("org.freedesktop.ScreenSaver"));
            QDBusInterface screensaver(interface, QStringLiteral("/ScreenSaver"));
            screensaver.asyncCall(QStringLiteral("Lock"));
            setResult(true);
            return;
        }
        qDebug() << "operation denied " << operation;
        setResult(false);
        return;
    } else if (operation == QLatin1String("suspend") || operation == QLatin1String("suspendToRam")) {
        Solid::PowerManagement::requestSleep(Solid::PowerManagement::SuspendState, 0, 0);
        setResult(Solid::PowerManagement::supportedSleepStates().contains(Solid::PowerManagement::SuspendState));
        return;
    } else if (operation == QLatin1String("suspendToDisk")) {
        Solid::PowerManagement::requestSleep(Solid::PowerManagement::HibernateState, 0, 0);
        setResult(Solid::PowerManagement::supportedSleepStates().contains(Solid::PowerManagement::HibernateState));
        return;
    } else if (operation == QLatin1String("suspendHybrid")) {
        Solid::PowerManagement::requestSleep(Solid::PowerManagement::HybridSuspendState, 0, 0);
        setResult(Solid::PowerManagement::supportedSleepStates().contains(Solid::PowerManagement::HybridSuspendState));
        return;
    } else if (operation == QLatin1String("requestShutDown")) {
        requestShutDown();
        setResult(true);
        return;
    } else if (operation == QLatin1String("switchUser")) {
        // Taken from kickoff/core/itemhandlers.cpp
        org::kde::krunner::App krunner(QStringLiteral("org.kde.krunner"), QStringLiteral("/App"), QDBusConnection::sessionBus());
        krunner.switchUser();
        setResult(true);
        return;
    } else if (operation == QLatin1String("beginSuppressingSleep")) {
        setResult(Solid::PowerManagement::beginSuppressingSleep(parameters().value(QStringLiteral("reason")).toString()));
        return;
    } else if (operation == QLatin1String("stopSuppressingSleep")) {
        setResult(Solid::PowerManagement::stopSuppressingSleep(parameters().value(QStringLiteral("cookie")).toInt()));
        return;
    } else if (operation == QLatin1String("beginSuppressingScreenPowerManagement")) {
        setResult(Solid::PowerManagement::beginSuppressingScreenPowerManagement(parameters().value(QStringLiteral("reason")).toString()));
        return;
    } else if (operation == QLatin1String("stopSuppressingScreenPowerManagement")) {
        setResult(Solid::PowerManagement::stopSuppressingScreenPowerManagement(parameters().value(QStringLiteral("cookie")).toInt()));
        return;
    } else if (operation == QLatin1String("setBrightness")) {
        setScreenBrightness(parameters().value(QStringLiteral("brightness")).toInt(), parameters().value(QStringLiteral("silent")).toBool());
        setResult(true);
        return;
    } else if (operation == QLatin1String("setKeyboardBrightness")) {
        setKeyboardBrightness(parameters().value(QStringLiteral("brightness")).toInt(), parameters().value(QStringLiteral("silent")).toBool());
        setResult(true);
        return;
    }

    qDebug() << "don't know what to do with " << operation;
    setResult(false);
}
Exemplo n.º 15
0
#include "common.h"
#include "sysfunc.h"
#include "trec_eval.h"
#include "functions.h"
#include "trec_format.h"

static int
te_calc_num_rel_ret(const EPI *epi, const REL_INFO *rel_info,
		const RESULTS *results, const TREC_MEAS *tm, TREC_EVAL *eval);

/* See trec_eval.h for definition of TREC_MEAS */
TREC_MEAS te_meas_num_rel_ret =
		{ "num_rel_ret",
				"    Number of relevant documents retrieved for topic. \n\
    May be affected by Judged_docs_only and Max_retrieved_per_topic command\n\
    line parameters (as are most measures).\n\
    Summary figure is sum of individual topics, not average.\n",
				te_init_meas_s_long, te_calc_num_rel_ret, te_acc_meas_s,
				te_calc_avg_meas_empty, te_print_single_meas_s_long,
				te_print_final_meas_s_long,
				NULL, -1 };

static int te_calc_num_rel_ret(const EPI *epi, const REL_INFO *rel_info,
		const RESULTS *results, const TREC_MEAS *tm, TREC_EVAL *eval) {
	RES_RELS res_rels;

	/* Can't just use results, since epi->only_judged_docs may be set */
	if (UNDEF == te_form_res_rels(epi, rel_info, results, &res_rels))
		return (UNDEF);

	eval->values[tm->eval_index].value = (double) res_rels.num_rel_ret;
	return (1);
Exemplo n.º 16
0
int sc_main (int argc , char *argv[]) {

/*
	int	quantization[64] = { 8,  6,  6,  7,  6,  5,  8,  7,
								 7,  7,  9,  9,  8, 10, 12, 20,
								13, 12, 11, 11, 12, 25, 18, 19,
								15, 20, 29, 26, 31, 30, 29, 26,
								28, 28, 32, 36, 46, 39, 32, 34,
								44, 35, 28, 28, 40, 55, 41, 44,
								48, 49, 52, 52, 52, 31, 39, 57,
								61, 56, 50, 60, 46, 51, 52, 50 };
*/

	int	quantization[64] = { 16, 11, 10, 16, 24, 40, 51, 61,
								 12, 12, 14, 19, 26, 58, 60, 55,
								 14, 13, 16, 24, 40, 57, 69, 56,
								 14, 17, 22, 29, 51, 87, 80, 62,
								 18, 22, 37, 56, 68,109,103, 77,
								 24, 35, 55, 64, 81,104,113, 92,
								 49, 64, 78, 87,103,121,120,101,
								 72, 92, 95, 98,112,100,103, 99};

// definition of default files
	const char*	inputfile		= "datain.pgm";
	const char*	outputfile		= "dataout.pgm";
	const char* typefile 		= "types.txt";
	const char* costfilename;
	bool outputcost = false;

//	definition of FIFO queues
	fifo_stat<int>	stimulus("stimulus",1);
	fifo_stat<int>	parameters("parameters",3);
	fifo_stat<int>	stimulus_dup1("stimulus_dup1",1);
	fifo_stat<int>	stimulus_dup2("stimulus_dup2",MAXWIDTH8*8+64+64+64+64+64);
	fifo_stat<int>	parameters_dup1("parameters_dup1",3);
	fifo_stat<int>	parameters_dup2("parameters_dup2",3);
	fifo_stat<int>	parameters_dup3("parameters_dup3",3);
	fifo_stat<int>	jpeg_enc_out("jpeg_enc_out",1);
	fifo_stat<int>	result("result",1);
	fifo_stat<int>	result_dup1("result_dup1",1);
	fifo_stat<int>	result_dup2("result_dup2",1);


// processing of command-line arguments
	bool	detected;
	for(int i=3; i<=argc; i+=2) {
		cout << argv[i-2] << " " << argv[i-1] << endl;
		detected = 0;
		if (strcmp(argv[i-2],"-i")==0) {
			inputfile = argv[i-1];
			detected = 1;
		}
		if (strcmp(argv[i-2],"-o")==0) {
			outputfile = argv[i-1];
			detected = 1;
		}
		if (strcmp(argv[i-2],"-t")==0) {
			typefile = argv[i-1];
			detected = 1;
		}
		if (strcmp(argv[i-2],"-c")==0) {
			costfilename = argv[i-1];
			outputcost = true;
			detected = 1;
		}
		if (detected == 0) {
			cout << "option " << argv[i-2] << " not known " << endl;
		}
	}

//	definition of modules

	src src1("src1", inputfile, MAXWIDTH);
	src1.output(stimulus);
//	src1.output(stimulus_dup1);
//	src1.output(stimulus_dup2);
	src1.parameters(parameters);

	df_fork<int,2> fork1("fork1");
	fork1.in(stimulus);
	fork1.out[0](stimulus_dup1);
	fork1.out[1](stimulus_dup2);

	df_fork<int,3> fork_param("fork_param");
	fork_param.in(parameters);
	fork_param.out[0](parameters_dup1);
	fork_param.out[1](parameters_dup2);
	fork_param.out[2](parameters_dup3);

	jpeg_enc jpeg_enc_1("jpeg_enc_1", quantization, MAXWIDTH);
	jpeg_enc_1.input(stimulus_dup1);
	jpeg_enc_1.parameters(parameters_dup1);
	jpeg_enc_1.output(jpeg_enc_out);

	jpeg_dec jpeg_dec_1("jpeg_dec_1", quantization, MAXWIDTH, typefile);
	jpeg_dec_1.input(jpeg_enc_out);
	jpeg_dec_1.parameters(parameters_dup2);
	jpeg_dec_1.output(result);

	df_fork<int,2> fork2("fork2");
	fork2.in(result);
	fork2.out[0](result_dup1);
	fork2.out[1](result_dup2);

	snk snk1("snk1", outputfile);
	snk1.input(result_dup1);
	snk1.parameters(parameters_dup3);

	test test1("test1");
	test1.reference(stimulus_dup2);
	test1.data(result_dup2);

	sc_start();

	if (outputcost == true) {
		int cost = jpeg_dec_1.idct_1->hardware_cost();
		float snr = test1.snr();
		float psnr = test1.psnr();
		cout << "hardware cost IDCT 2nd " << cost << endl;
		ofstream *costfile;
		costfile = new ofstream(costfilename);
		if (!costfile->is_open()) cout << "Error opening file " << costfilename << endl;
		*costfile << cost << " " << snr << " " << psnr << endl;
		costfile->close();
	}
	return 0;
}
Exemplo n.º 17
0
 HaWpEvaluator<D,MultiIndex,N> create_evaluator(CMatrix<D,N> const& grid) const
 {
     return {eps(), &parameters(), shape().get(), grid};
 }
Exemplo n.º 18
0
memory_datasource::memory_datasource(datasource::datasource_t type, bool bbox_check)
    : datasource(parameters()),
      desc_("in-memory datasource","utf-8"),
      type_(type),
      bbox_check_(bbox_check) {}
Exemplo n.º 19
0
int main(int argc, char** argv)
{
    int my_rank, size, i;

    //char msg0[] = "Wasssssaaaaap Ich hasse mein Leif Hundin!\n";
    //char msg1[] = "Lol I hate my life\n";
    //char rcv0[100], rcv1[100];

    MPI_Init(&argc, &argv);

    MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
    MPI_Comm_size(MPI_COMM_WORLD, &size);

    printf("Started Process %d of %d\n", my_rank, (size - 1));

    if (my_rank == 0)
    {
        printf("Computing in Parallel on %d Processes\n", size);

        /* Process program parameters */
        parameters(argc, argv);

        /* Initialize A and B */
        initialize_inputs();

        /* Print input matrices */
        print_inputs();

        /* Gaussian elimination */
        for (norm = 0; norm < N - 1; norm++) /*Proceeding sequentially on each norm row because of
                          *Read-After-Write dependence between each norm variable iteration.
                          */
        {
            i = 0;
            for (row = norm + 1; row < N; row += blockSize) /*Putting values in the 'inidices' dynamic array described above.
                                 *Note that this loop increments with a step size equal to the blockSize value
                                 *which is the number of rows each thread will be handling.
                                 */
            {
                indices[3 * i] = row; /*First value storing the starting row index.*/

                if ((row + blockSize - 1) < N) /*Second value stores the ending row index.*/
                    indices[3 * i + 1] = row + blockSize - 1;
                else
                    indices[3 * i + 1] = N - 1;

                indices[3 * i + 2] = norm; /*Third value stores value of current normalization row index.*/
                i++;
            }

        numCPU = i; /*Ensures that number of threads launched is equal to the number of proceesing lbocks made.*/

            for (i = 0; i < numCPU; i++)
            {
                pthread_create(rowThreads + i, NULL, processRows, (indices + 3 * i)); /*Launching each thread to operate on different parts of the array*/
            }

            for (i = 0; i < numCPU; i++)
            {
                pthread_join(*(rowThreads + i), NULL); /*Consolidating all threads*/
            }
        }
        /* (Diagonal elements are not normalized to 1.  This is treated in back
         * substitution.)
         */

        for (i = 1; i < size; i++)
        {
            MPI_Send(A, (MAXN*MAXN), MPI_FLOAT, i, 0, MPI_COMM_WORLD);
            MPI_Send(B, MAXN, MPI_FLOAT, i, 1, MPI_COMM_WORLD);
            MPI_Send(&N, 1, MPI_INT, i, 2, MPI_COMM_WORLD);
            printf("Data sent to processor %d!\n", i);
        }
    }
    else
    {
        MPI_Recv(A, (MAXN*MAXN), MPI_FLOAT, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
        MPI_Recv(B, MAXN, MPI_FLOAT, 0, 1, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
        MPI_Recv(&N, 1, MPI_INT, 0, 2, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
        printf("Received size of data (Value of N) = %d\n", N);
        printf("Received data with tag 0 & 1\n");
        print_inputs();
    }

    MPI_Finalize();

    return 0;
}
Exemplo n.º 20
0
    setIcon(p->icon);
    setDescription(p->description);
    setDisplayName(p->displayName);
    setCategory(p->category);
    setDisplayCategory(p->displayCategory);
    setRequiredFeatures(p->requiredFeatures);
    setFlags(p->flags);
}

Core::BaseFileWizard *CustomWizard::create(QWidget *parent, const Core::WizardDialogParameters &p) const
{
    QTC_ASSERT(!d->m_parameters.isNull(), return 0);
    Core::BaseFileWizard *wizard = new Core::BaseFileWizard(parent);

    d->m_context->reset();
    CustomWizardPage *customPage = new CustomWizardPage(d->m_context, parameters());
    customPage->setPath(p.defaultPath());
    if (parameters()->firstPageId >= 0)
        wizard->setPage(parameters()->firstPageId, customPage);
    else
        wizard->addPage(customPage);
    foreach (QWizardPage *ep, p.extensionPages())
        wizard->addPage(ep);
    if (CustomWizardPrivate::verbose)
        qDebug() << "initWizardDialog" << wizard << wizard->pageIds();

    return wizard;
}

// Read out files and store contents with field contents replaced.
static inline bool createFile(CustomWizardFile cwFile,
Exemplo n.º 21
0
int ACE_TMAIN (int argc, ACE_TCHAR *argv[])
{
    try
    {
        int failed = 0;

        ACE_DEBUG((LM_DEBUG, "Start of Client\n"));
        // Initialise ORB.
        //
        CORBA::ORB_var orb = CORBA::ORB_init(argc, argv);

        // Find the Interface Repository.
        //
        ACE_DEBUG((LM_DEBUG, ". Find IFR\n"));
        CORBA::Object_var ifr_obj =
            orb->resolve_initial_references( "InterfaceRepository");

        ACE_DEBUG((LM_DEBUG, ". Narrow IFR\n"));
        CORBA::Repository_var ifr = CORBA::Repository::_narrow( ifr_obj.in());

        if( CORBA::is_nil( ifr.in() ) )
        {
            ACE_DEBUG((LM_DEBUG, "Nil IFR reference\n"));
            return 1;
        }

        ACE_DEBUG((LM_DEBUG, ". Construct interface\n"));
        // Add an interface to the repository.
        //
        CORBA::InterfaceDefSeq baseInterfaces(1) ;
        baseInterfaces.length(0) ;
        CORBA::InterfaceDef_var intface =
            ifr->create_interface( "IDL:interface865:1.0",
                                   "interface865",
                                   "1.0",
                                   baseInterfaces) ;

        // Add an operation to the interface.
        // First get some useful things.
        //
        ACE_DEBUG((LM_DEBUG, ". Get primitive (void)\n"));
        CORBA::PrimitiveDef_var voidPrimitive =
            ifr->get_primitive( CORBA::pk_void) ;
        ACE_DEBUG((LM_DEBUG, ". Get primitive (char)\n"));
        CORBA::PrimitiveDef_var charPrimitive =
            ifr->get_primitive( CORBA::pk_char) ;
        ACE_DEBUG((LM_DEBUG, ". Get primitive (long)\n"));
        CORBA::PrimitiveDef_var longPrimitive =
            ifr->get_primitive( CORBA::pk_long) ;
        ACE_DEBUG((LM_DEBUG, ". Get primitive (short)\n"));
        CORBA::PrimitiveDef_var shortPrimitive =
            ifr->get_primitive( CORBA::pk_short) ;

        ACE_DEBUG((LM_DEBUG, ". create 3 parameters\n"));
        // The operation has three parameters...
        //
        CORBA::ULong numParams = 3 ;
        CORBA::ParDescriptionSeq parameters( numParams ) ;
        parameters.length( numParams ) ;

        // ... which are: in char p1...
        //
        parameters[0].name = CORBA::string_dup("p1") ;
        parameters[0].type_def =
            CORBA::PrimitiveDef::_duplicate( charPrimitive.in() ) ;
        parameters[0].type = charPrimitive->type() ;
        parameters[0].mode = CORBA::PARAM_IN ;

        // ...out long p2...
        //
        parameters[1].name = CORBA::string_dup("p2") ;
        parameters[1].type_def =
            CORBA::PrimitiveDef::_duplicate( longPrimitive.in() ) ;
        parameters[1].type = longPrimitive->type() ;
        parameters[1].mode = CORBA::PARAM_OUT ;

        // ...and inout short p3
        //
        parameters[2].name = CORBA::string_dup("p3") ;
        parameters[2].type_def =
            CORBA::PrimitiveDef::_duplicate( shortPrimitive.in() ) ;
        parameters[2].type = shortPrimitive->type() ;
        parameters[2].mode = CORBA::PARAM_INOUT ;

        // ...and no exceptions...
        //
        ACE_DEBUG((LM_DEBUG, ". create 0 excepts\n"));
        CORBA::ExceptionDefSeq exceptions( 1 ) ;
        exceptions.length( 0 ) ;

        // ...and no context ids
        //
        ACE_DEBUG((LM_DEBUG, ". create 0 cids\n"));
        CORBA::ContextIdSeq contextIds( 1 ) ;
        contextIds.length( 0 ) ;

        // Create the operation, called "f".
        //
        ACE_DEBUG((LM_DEBUG, ". create_operation\n"));
        CORBA::OperationDef_var operation =
            intface->create_operation( "IDL:interface865/f:1.0",
                                       "f",
                                       "1.0",
                                       voidPrimitive.in(),
                                       CORBA::OP_NORMAL,
                                       parameters,
                                       exceptions,
                                       contextIds) ;



        // Create operation list.
        //
        CORBA::NVList_var opList ;

        ACE_DEBUG((LM_DEBUG, "About to call create_operation_list\n"));
        orb->create_operation_list(operation.in (),
                                   opList.out()) ;

        ACE_DEBUG((LM_DEBUG, "Call to create_operation_list succeeded\n"));
        CORBA::ULong count = opList->count() ;

        if( count != numParams )
        {
            ACE_DEBUG((LM_DEBUG, "Test failed - wrong number of elements n list\n")) ;
            failed = 1 ;
        }

        CORBA::NamedValue_ptr nv = opList->item( 0 ) ;
        if(ACE_OS::strcmp( nv->name(), "p1") != 0 )
        {
            ACE_DEBUG((LM_DEBUG, "Test failed: param 1 wrong name\n"));
            failed = 1 ;
        }

        CORBA::Boolean const eq_char =
            nv->value()->type()->equal (CORBA::_tc_char);

        if( !eq_char  )
        {
            ACE_DEBUG((LM_DEBUG, "Test failed: param 1 wrong type\n"));
            failed = 1 ;
        }
        if( nv->flags() != CORBA::ARG_IN )
        {
            ACE_DEBUG((LM_DEBUG, "Test failed: param 1 wrong mode\n"));
            failed = 1 ;
        }

        nv = opList->item( 1 ) ;
        if(ACE_OS::strcmp( nv->name(), "p2") != 0 )
        {
            ACE_DEBUG((LM_DEBUG, "Test failed: param 2 wrong name\n"));
            failed = 1 ;
        }

        CORBA::Boolean const eq_long =
            nv->value()->type()->equal (CORBA::_tc_long);

        if( !eq_long  )
        {
            ACE_DEBUG((LM_DEBUG, "Test failed: param 2 wrong type\n"));
            failed = 1 ;
        }
        if( nv->flags() != CORBA::ARG_OUT )
        {
            ACE_DEBUG((LM_DEBUG, "Test failed: param 2 wrong mode\n"));
            failed = 1 ;
        }

        nv = opList->item( 2 ) ;
        if(ACE_OS::strcmp( nv->name(), "p3") != 0 )
        {
            ACE_DEBUG((LM_DEBUG, "Test failed: param 3 wrong name\n"));
            failed = 1 ;
        }

        CORBA::Boolean const eq_short =
            nv->value()->type()->equal (CORBA::_tc_short);

        if( !eq_short  )
        {
            ACE_DEBUG((LM_DEBUG, "Test failed: param 3 wrong type\n"));
            failed = 1 ;
        }
        if( nv->flags() != CORBA::ARG_INOUT )
        {
            ACE_DEBUG((LM_DEBUG, "Test failed: param 3 wrong mode\n"));
            failed = 1 ;
        }

        // opList->free();
        //operation->destroy();

        // Finally destroy the interface.
        //
        intface->destroy() ;

        //orb->destroy();

        if( failed == 1 )
        {
            return 1 ;
        }
        ACE_DEBUG((LM_DEBUG, ". seems OK\n"));
    }
    catch (const CORBA::Exception& ex)
    {
        ex._tao_print_exception ("Exception - test failed:\n");
        return 1;
    }
    catch (...)
    {
        ACE_DEBUG((LM_DEBUG, "An unknown exception occured - test failed\n"));
        return 1;
    }


    return 0 ;
}
Exemplo n.º 22
0
const Style *StyleController::adaptRelationStyle(const StyledRelation &relation)
{
    Parameters parameters(this);
    return m_defaultStyleEngine->applyRelationStyle(m_defaultStyle.data(), relation, &parameters);
}
Exemplo n.º 23
0
Context<BasisFunctionType, ResultType>::Context(
    const ParameterList &globalParameterList) {

  ParameterList parameters(globalParameterList);
  auto defaults = GlobalParameters::parameterList();

  std::string assemblyType = parameters.get<std::string>(
      "options.assembly.boundaryOperatorAssemblyType",
      defaults.get<std::string>(
          "options.assembly.boundaryOperatorAssemblyType"));
  if (assemblyType == "hmat")
    m_assemblyOptions.switchToHMatMode();
  else if (assemblyType == "dense")
    m_assemblyOptions.switchToDenseMode();
  else
    throw std::runtime_error(
        "Context::Context(): boundaryOperatorAssemblyType has "
        "unsupported value.");

  m_assemblyOptions.setMaxThreadCount(
      parameters.get<int>("options.global.maxThreadCount",
                          defaults.get<int>("options.global.maxThreadCount")));

  int verbosityLevel =
      parameters.get<int>("options.global.verbosityLevel",
                          defaults.get<int>("options.global.verbosityLevel"));

  if (verbosityLevel == -5)
    m_assemblyOptions.setVerbosityLevel(VerbosityLevel::LOW);
  else if (verbosityLevel == 0)
    m_assemblyOptions.setVerbosityLevel(VerbosityLevel::DEFAULT);
  else if (verbosityLevel == 5)
    m_assemblyOptions.setVerbosityLevel(VerbosityLevel::HIGH);
  else
    throw std::runtime_error(
        "Context::Context(): verbosityLevel has unsupported value");

  m_assemblyOptions.enableSingularIntegralCaching(parameters.get<bool>(
      "options.assembly.enableSingularIntegralCaching",
      defaults.get<bool>("options.assembly.enableSingularIntegralCaching")));

  m_assemblyOptions.enableBlasInQuadrature(AssemblyOptions::AUTO);

  Fiber::AccuracyOptionsEx accuracyOptions;

  accuracyOptions.setSingleRegular(
      parameters.get<double>(
          "options.quadrature.near.maxRelDist",
          defaults.get<double>("options.quadrature.near.maxRelDist")),
      parameters.get<int>(
          "options.quadrature.near.singleOrder",
          defaults.get<int>("options.quadrature.near.singleOrder")),
      parameters.get<double>(
          "options.quadrature.medium.maxRelDist",
          defaults.get<double>("options.quadrature.medium.maxRelDist")),
      parameters.get<int>(
          "options.quadrature.medium.singleOrder",
          defaults.get<int>("options.quadrature.medium.singleOrder")),
      parameters.get<int>(
          "options.quadrature.far.singleOrder",
          defaults.get<int>("options.quadrature.far.singleOrder")),
      false);

  accuracyOptions.setDoubleRegular(
      parameters.get<double>(
          "options.quadrature.near.maxRelDist",
          defaults.get<double>("options.quadrature.near.maxRelDist")),
      parameters.get<int>(
          "options.quadrature.near.doubleOrder",
          defaults.get<int>("options.quadrature.near.doubleOrder")),
      parameters.get<double>(
          "options.quadrature.medium.maxRelDist",
          defaults.get<double>("options.quadrature.medium.maxRelDist")),
      parameters.get<int>(
          "options.quadrature.medium.doubleOrder",
          defaults.get<int>("options.quadrature.medium.doubleOrder")),
      parameters.get<int>(
          "options.quadrature.far.doubleOrder",
          defaults.get<int>("options.quadrature.far.doubleOrder")),
      false);

  accuracyOptions.setDoubleSingular(
      parameters.get<int>(
          "options.quadrature.doubleSingular",
          defaults.get<int>("options.quadrature.doubleSingular")),
      false);

  m_quadStrategy.reset(
      new NumericalQuadratureStrategy<BasisFunctionType, ResultType>(
          accuracyOptions));

  m_globalParameterList = parameters;
}
Exemplo n.º 24
0
int
main (int argc, char *argv[])
{
	struct pollfd pfd;
	char line[4096], *p;
	char *name, *id, *polname, *filters;
	int nfilters, res;
	time_t curtime;
	GList *items = NULL;

	GtkWidget *systracewin;
	GtkWidget *processname;
	GtkWidget *policyname;
	GtkWidget *processid;
	GtkWidget *syscallinfo;
	GtkWidget *statusline;
	GtkWidget *timeline;
	GtkWidget *reviewbutton;
	GtkWidget *detachlabel;
	GtkWidget *filterentry;

	GtkStyle *default_style, *red_style;

	/* Set up required parameters */
	parameters();

	gtk_set_locale ();
	gtk_init (&argc, &argv);

	add_pixmap_directory (PACKAGE_DATA_DIR "/pixmaps");
	add_pixmap_directory (PACKAGE_SOURCE_DIR "/pixmaps");

	/*
	 * The following code was added by Glade to create one of each component
	 * (except popup menus), just so that you see something after building
	 * the project. Delete any components that you don't want shown initially.
	 */
	systracewin = create_systracewin ();
	filterreview = create_filterreview();
	wizard = create_wizard();

	processname = lookup_widget(GTK_WIDGET(systracewin), "processname");
	processid = lookup_widget(GTK_WIDGET(systracewin), "processid");
	policyname = lookup_widget(GTK_WIDGET(systracewin), "policyname");
	syscallinfo = lookup_widget(GTK_WIDGET(systracewin), "syscallinfo");
	statusline = lookup_widget(GTK_WIDGET(systracewin), "statusline");
	timeline = lookup_widget(GTK_WIDGET(systracewin), "timeline");
	reviewbutton = lookup_widget(GTK_WIDGET(systracewin), "reviewbutton");
	wizardbutton = lookup_widget(GTK_WIDGET(systracewin), "wizardbutton");
	detachlabel = lookup_widget(GTK_WIDGET(systracewin), "detachlabel");
	filterentry = lookup_widget(GTK_WIDGET(systracewin), "filterentry");
	default_style = gtk_widget_get_style(processname);
	red_style = make_color(default_style, 0xd000, 0x1000, 0);
	red_style->private_font = gdk_font_load("-*-helvetica-bold-r-normal--*-140-*-*-*-*-iso8859-1");
	gtk_widget_set_style(processname, red_style);
	gtk_widget_set_style(processid, red_style);
	gtk_widget_set_style(policyname, red_style);
	gtk_widget_set_style(syscallinfo, red_style);

	/* Return key is not supposed to pop it up */
	gtk_combo_disable_activate(GTK_COMBO(filterentry));

	/* Connect to cradle server if requested */
	if (argc == 2 && strcmp(argv[1], "-C") == 0) {
		struct sockaddr_un sun;
		int s;
		char path[MAXPATHLEN];

		snprintf(path, sizeof(path), "/tmp/systrace-%d/%s",
		    getuid(), CRADLE_UI);

		if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1)
			err(1, "socket()");

		memset(&sun, 0, sizeof (sun));
		sun.sun_family = AF_UNIX;

		if (strlcpy(sun.sun_path, path, sizeof(sun.sun_path)) >=
		    sizeof(sun.sun_path))
			errx(1, "Path too long: %s", path);

		if (connect(s, (struct sockaddr *)&sun, sizeof(sun)) == -1)
			err(1, "connect()");

		if (dup2(s, fileno(stdin)) == -1)
			err(1, "dup2");
		if (dup2(s, fileno(stdout)) == -1)
			err(1, "dup2");
	}

	/* Make IO line buffered */
	setvbuf(stdin, NULL, _IONBF, 0);
	setvbuf(stdout, NULL, _IONBF, 0);
	while (1) {
		/* See if we can read from the file descriptor */
		memset(&pfd, 0, sizeof(pfd));
		pfd.fd = fileno(stdin);
		pfd.events = POLLIN;
		res = poll(&pfd, 1, 1000);
		if (res == -1) {
			if (errno == EINTR || errno == EAGAIN)
				break;
		} else if (res == 0) {
			while (gtk_events_pending())
				gtk_main_iteration();
			continue;
		}

		if (freadline(line, sizeof(line), stdin) == NULL)
			break;
		p = line;
		name = strsep(&p, ",");
		if (p == NULL || *p == '\0')
			errx(1, "Bad input line");
		p++;
		strsep(&p, " ");
		if (p == NULL || *p == '\0')
			errx(1, "Bad input line");
		id = strsep(&p, "(");
		if (p == NULL || *p == '\0')
			errx(1, "Bad input line");
		strsep(&p, ":");
		if (p == NULL || *p == '\0')
			errx(1, "Bad input line");
		p++;
		polname = strsep(&p, ",");
		if (p == NULL || *p == '\0')
			errx(1, "Bad input line");
		strsep(&p, ":");
		if (p == NULL || *p == '\0')
			errx(1, "Bad input line");
		p++;
		filters = strsep(&p, ",");
		if (p == NULL || *p == '\0')
			errx(1, "Bad input line");
		nfilters = atoi(filters);
		strsep(&p, ":");
		if (p == NULL || *p == '\0')
			errx(1, "Bad input line");
		p++;

		gtk_label_set_text(GTK_LABEL(processname), name);
		gtk_label_set_text(GTK_LABEL(processid), id);
		gtk_label_set_text(GTK_LABEL(policyname), polname);
		gtk_label_set_text(GTK_LABEL(syscallinfo), p);
		gtk_label_set_text(GTK_LABEL(statusline), "");

		items = make_policy_suggestion(p);

		curtime = time(NULL);
		snprintf(line, sizeof(line), "%.25s", ctime(&curtime));
		gtk_label_set_text(GTK_LABEL(timeline), line);

		if (nfilters) {
			gtk_widget_set_sensitive(wizardbutton, 0);
			gtk_widget_set_sensitive(reviewbutton, 1);
			gtk_label_set_text(GTK_LABEL(detachlabel), "Automatic");
		} else {
			gtk_widget_set_sensitive(wizardbutton, 1);
			gtk_widget_set_sensitive(reviewbutton, 0);
			gtk_label_set_text(GTK_LABEL(detachlabel), "Detach");
		}

		gtk_widget_show (systracewin);

		gtk_combo_set_popdown_strings (GTK_COMBO(filterentry), items);
		g_list_foreach(items, free_list, NULL);
		g_list_free(items);

		do {
			gtk_main ();
			while (freadline(line, sizeof(line), stdin)) {
				if (!strcmp(line, "OKAY"))
					goto done;
				if (!strcmp(line, "WRONG"))
					break;
				gtk_label_set_text(GTK_LABEL(statusline), line);
			}
		} while (1);

	done:
		gtk_widget_hide (systracewin);

		while (gtk_events_pending())
			gtk_main_iteration();
	}
	return 0;
}
Exemplo n.º 25
0
void setupMNparams(int &sampler, int &IS, int &modal, int &ceff, int &nlive, double &efr, int &sample, int &updInt, int &nClsPar, int &Nchords){


	//sampler flag chooses which sampler to use, 0 = MultiNest, 1 = PolyChord
	sampler = 1;

	//IS: flag to use importance sampling, will be supported by upcoming release of multinest, at which point it should be set to 1
	IS=0;
	
	//modal: flag to allow multinest to search for multiple modes in the data. 1 = multimodal, 0 = single mode
	modal=0;

	//ceff: flag to set multinest to constant efficiency mode.  Adjusts sampling to maintain the efficiency set by the efr parameter. This is usefull for large dimensional problems (> 20dim), however the accuracy of the evidence suffers if importance sampling isn't used.
	ceff=0;

	//nlive: the number of live points used by multinest.  THe more you have the more it explores the parameter space, but the longer it takes to sample.
	//As a guide depending on the dimensionality of the problem (this is the numer of parameters sampled after discounting those to be marginalised over): 
	//Less than 5 dimensions: 100
	//Between 5 and 10 dimensions: 200
	//Between 10 and 50: 500
	//More than 50: 1000
	nlive=500;

	//efr: The sampling efficiency.  The Lower this number the more carefully multinest explores the parameter space, so the longer it takes.
	//The value depends on the dimensionality and the goal.
	//For parameter estimation it can be set higher than if an accurate Evidence value is required.
	//As a rough guide:
	//Less than 10 dimensions: 0.8 (parameter estimation), 0.3 (Evidence evaluation)
	//Between 10 and 20 dimensions: 0.3 (parameter estimation), 0.1 (Evidence evaluation)
	//Between 20 and 50: 0.1 (parameter estimation), 0.05 (Evidence evaluation)
	//More than 50: 0.05 (parameter estimation), 0.01 (Evidence evaluation)
	//These numbers may well be adjusted with experience, for parameter estimation of a single modal "blob", these may be much lower than required.
	//Also: In constant efficiency mode this must be set lower, to 0.05 for D<50 and 0.01 D>50.
	efr=0.1;

	//do sampling? 0 = No, 1 = Yes
	sample = 1;

	//updInt: How often the output files are updated
	updInt = 2000;

	//nClsPar:  Number of parameters to cluster over when doing multi modal analysis
	nClsPar = 1;

	Nchords = 1;

    // Use a configfile, if we can, to overwrite the defaults set in this file.
         try {
                 string strBuf;
                 strBuf = string("defaultparameters.conf");
                 ConfigFile parameters(strBuf);

		parameters.readInto(sampler, "sampler", sampler);
		parameters.readInto(IS, "IS", IS);
		parameters.readInto(modal, "modal", modal);
		parameters.readInto(ceff, "ceff", ceff);
		parameters.readInto(nlive, "nlive", nlive);
		parameters.readInto(efr, "efr", efr);
 		parameters.readInto(sample, "sample", sample);
 		parameters.readInto(updInt, "updInt", updInt);
 		parameters.readInto(nClsPar, "nClsPar", nClsPar);
		parameters.readInto(Nchords, "Nchords", Nchords);
	    } catch(ConfigFile::file_not_found oError) {
		printf("WARNING: parameters file '%s' not found. Using defaults.\n", oError.filename.c_str());
	    } // try

}
Exemplo n.º 26
0
void
ContactAction::act()
{
  if (!_problem->getDisplacedProblem())
    mooseError("Contact requires updated coordinates.  Use the 'displacements = ...' line in the "
               "Mesh block.");

  std::string action_name = MooseUtils::shortName(name());

  std::vector<NonlinearVariableName> displacements;
  if (isParamValid("displacements"))
    displacements = getParam<std::vector<NonlinearVariableName>>("displacements");
  else
  {
    // Legacy parameter scheme for displacements
    if (!isParamValid("disp_x"))
      mooseError("Specify displacement variables using the `displacements` parameter.");
    displacements.push_back(getParam<NonlinearVariableName>("disp_x"));

    if (isParamValid("disp_y"))
    {
      displacements.push_back(getParam<NonlinearVariableName>("disp_y"));
      if (isParamValid("disp_z"))
        displacements.push_back(getParam<NonlinearVariableName>("disp_z"));
    }

    mooseDeprecated("use the `displacements` parameter rather than the `disp_*` parameters (those "
                    "will go away with the deprecation of the Solid Mechanics module).");
  }

  // Determine number of dimensions
  const unsigned int ndisp = displacements.size();

  // convert vector of NonlinearVariableName to vector of VariableName
  std::vector<VariableName> coupled_displacements(ndisp);
  for (unsigned int i = 0; i < ndisp; ++i)
    coupled_displacements[i] = displacements[i];

  if (_current_task == "add_dirac_kernel")
  {
    // MechanicalContactConstraint has to be added after the init_problem task, so it cannot be
    // added for the add_constraint task.
    if (_system == "Constraint")
    {
      InputParameters params = _factory.getValidParams("MechanicalContactConstraint");
      params.applyParameters(parameters(), {"displacements", "formulation"});
      params.set<std::string>("formulation") = _formulation;
      params.set<std::vector<VariableName>>("nodal_area") = {"nodal_area_" + name()};
      params.set<std::vector<VariableName>>("displacements") = coupled_displacements;
      params.set<BoundaryName>("boundary") = _master;
      params.set<bool>("use_displaced_mesh") = true;

      for (unsigned int i = 0; i < ndisp; ++i)
      {
        std::string name = action_name + "_constraint_" + Moose::stringify(i);

        params.set<unsigned int>("component") = i;
        params.set<NonlinearVariableName>("variable") = displacements[i];
        params.set<std::vector<VariableName>>("master_variable") = {coupled_displacements[i]};
        _problem->addConstraint("MechanicalContactConstraint", name, params);
      }
    }

    if (_system == "DiracKernel")
    {
      {
        InputParameters params = _factory.getValidParams("ContactMaster");
        params.applyParameters(parameters(), {"displacements", "formulation"});
        params.set<std::string>("formulation") = _formulation;
        params.set<std::vector<VariableName>>("nodal_area") = {"nodal_area_" + name()};
        params.set<std::vector<VariableName>>("displacements") = coupled_displacements;
        params.set<BoundaryName>("boundary") = _master;
        params.set<bool>("use_displaced_mesh") = true;

        for (unsigned int i = 0; i < ndisp; ++i)
        {
          std::string name = action_name + "_master_" + Moose::stringify(i);
          params.set<unsigned int>("component") = i;
          params.set<NonlinearVariableName>("variable") = displacements[i];
          _problem->addDiracKernel("ContactMaster", name, params);
        }
      }

      {
        InputParameters params = _factory.getValidParams("SlaveConstraint");
        params.applyParameters(parameters(), {"displacements", "formulation"});
        params.set<std::string>("formulation") = _formulation;
        params.set<std::vector<VariableName>>("nodal_area") = {"nodal_area_" + name()};
        params.set<std::vector<VariableName>>("displacements") = coupled_displacements;
        params.set<BoundaryName>("boundary") = _slave;
        params.set<bool>("use_displaced_mesh") = true;

        for (unsigned int i = 0; i < ndisp; ++i)
        {
          std::string name = action_name + "_slave_" + Moose::stringify(i);
          params.set<unsigned int>("component") = i;
          params.set<NonlinearVariableName>("variable") = displacements[i];
          _problem->addDiracKernel("SlaveConstraint", name, params);
        }
      }
    }
  }
}
Exemplo n.º 27
0
const Style *StyleController::adaptAnnotationStyle(const DAnnotation *annotation)
{
    Parameters parameters(this);
    return m_defaultStyleEngine->applyAnnotationStyle(m_defaultStyle.data(), annotation, &parameters);
}
Exemplo n.º 28
0
bool launcherApplication::Elevate(const StringArray& commandLineArray)
{
#if defined(JUCE_LINUX) || defined(JUCE_BSD)
    if (geteuid() == 0) {
        return true;
    }

    String parameters("--user root /usr/bin/env ");

    const char *var = getenv("DISPLAY");
    if (var) {
        String s("DISPLAY=" + String(var).quoted());
        parameters += s + " ";
    }

    var = getenv("XAUTHORITY");
    if (var) {
        String s("XAUTHORITY=" + String(var).quoted());
        parameters += s + " ";
    }

    String launcher(File::getSpecialLocation(
                File::currentExecutableFile).getFullPathName());
    if (launcher.contains(" ")) {
        launcher = launcher.quoted();
    }

    parameters += String(" ") + launcher;
    for (int i = 0; i < commandLineArray.size(); i++)
    {
        parameters += " ";
        if (commandLineArray[i].contains(" "))
            parameters += commandLineArray[i].quoted();
        else
            parameters += commandLineArray[i];
    }

    File pkexec("/usr/bin/pkexec");
    if (pkexec.exists() && pkexec.startAsProcess(parameters)) {
        quit();
    }

    pkexec = "/usr/local/bin/pkexec";
    if (pkexec.exists() && pkexec.startAsProcess(parameters)) {
        quit();
    }

#elif defined(JUCE_WINDOWS)
    BOOL fIsRunAsAdmin = FALSE;
    DWORD dwError = ERROR_SUCCESS;
    PSID pAdministratorsGroup = NULL;

    SID_IDENTIFIER_AUTHORITY NtAuthority = SECURITY_NT_AUTHORITY;
    if (!AllocateAndInitializeSid(&NtAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID,
                DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &pAdministratorsGroup)) {
        dwError = GetLastError();
        goto cleanup;
    }

    if (!CheckTokenMembership(NULL, pAdministratorsGroup, &fIsRunAsAdmin)) {
        dwError = GetLastError();
        goto cleanup;
    }

cleanup:
    if (pAdministratorsGroup) {
        FreeSid(pAdministratorsGroup);
        pAdministratorsGroup = NULL;
    }

    if (dwError != ERROR_SUCCESS) {
        throw dwError;
    }

    if (fIsRunAsAdmin) {
        return true;
    }

    TCHAR szPath[MAX_PATH];
    if (!GetModuleFileName(NULL, szPath, ARRAYSIZE(szPath))) {
        dwError = GetLastError();
        throw dwError;
    }

    String commandLine;
    for (int i = 0; i < commandLineArray.size(); i++) {
        if (commandLineArray[i].contains(" ")) {
            commandLine += String("\"") + commandLineArray[i] + String("\"");
        } else {
            commandLine += commandLineArray[i];
        }
        if (i + 1 < commandLineArray.size()) {
            commandLine += " ";
        }
    }

    SHELLEXECUTEINFO sei = { 0 };
    sei.cbSize = sizeof(SHELLEXECUTEINFO);
    sei.lpVerb = _T("runas");
    sei.lpFile = szPath;
    sei.lpParameters = commandLine.toUTF8();
    sei.nShow = SW_NORMAL;
    if (ShellExecuteEx(&sei)) {
        _exit(1);
    }

#elif defined(JUCE_MAC)
    if (geteuid() == 0) {
        return true;
    }

    String launcher(File::getSpecialLocation(
                File::currentExecutableFile).getFullPathName());

    const char * execpath = launcher.toRawUTF8();
    char * args[] = { NULL };

    OSStatus           err;
    AuthorizationRef   ref;
    AuthorizationFlags flags;

    flags = kAuthorizationFlagDefaults;
    err   = AuthorizationCreate(NULL, kAuthorizationEmptyEnvironment, flags, &ref);
    if ( err != errAuthorizationSuccess ) {
        quit();
    }

    AuthorizationItem    _temp = { kAuthorizationRightExecute, 0, NULL, 0 };
    AuthorizationRights rights = { 1, &_temp };

    flags = kAuthorizationFlagDefaults
          | kAuthorizationFlagInteractionAllowed
          | kAuthorizationFlagPreAuthorize
          | kAuthorizationFlagExtendRights;

    err  = AuthorizationCopyRights(ref, &rights, NULL, flags, NULL);
    if ( err != errAuthorizationSuccess ) {
        AuthorizationFree(ref, kAuthorizationFlagDefaults);
        quit();
    }

    flags = kAuthorizationFlagDefaults;
    err  = AuthorizationExecuteWithPrivileges(ref, execpath, flags, args, NULL);
    AuthorizationFree(ref, kAuthorizationFlagDefaults);

    // Probably overkill.
    if ( err != errAuthorizationSuccess ) {
        quit();
    }
#endif // JUCE_MAC

    return false;
}
Exemplo n.º 29
-1
double trajectoryOptimizer::eval(vector<double> &params, vector<double> &gradient) {

   cout << "IN EVAL   "<<params.size()<<endl;


   for (int i=0; i < params.size(); i++) 
      cout << "PARAMS IN: "<<i<<" "<<params.at(i)<<endl;

   int factor = evidence.getFactor();

  // cout << "FACTOR: "<<factor<<endl;
  
   FeatureArray featArray2(features);

   FeatureArray featArray(featArray2, factor);
   //cout<<"Dims featarray  "<<featArray.dims().first<<" "<<featArray.dims().second<<endl;

   Parameters parameters(params);

   //cout << "Calculating rewards"<<endl;

   RewardMap rewards(featArray, parameters); 

   pair<int, int> dims = grid.dims();

   BMPFile gridView(dims.first, dims.second);

   pair<int, int> lowDims((int)ceil((float)dims.first/factor),
         (int)ceil((float)dims.second/factor));

   //cout << "Computing prior"<<endl;
   vector<vector<double> > prior(lowDims.first, vector<double>(lowDims.second, 
            -HUGE_VAL)); 

   double obj = 0.0;
   gradient.clear();
   gradient.resize(params.size(), 0.0); 

   for (int i=0; i < evidence.size(); i++) {

      Predictor predictor(grid, rewards, engine); 

      cout << "Evidence #"<<i<<endl;
      vector<pair<int, int> > trajectory = evidence.at(i);

      double cost = 0.0;
      for (int j=0; j < trajectory.size(); j++){
		  double temp = rewards.at(trajectory.at(j).first, 
					  trajectory.at(j).second);
		  cost += temp;
	  }
	  

      pair<int, int> initial = trajectory.front();
      pair<int, int> destination = trajectory.back();

      prior.at(destination.first).at(destination.second) = 0.0;
#if 0
      cout << "Initial: "<<initial.first<<"  "<<initial.second<<endl;
      cout << "Destination: "<<destination.first<<"  "
         <<destination.second<<endl;
#endif
      predictor.setStart(initial);
      predictor.setPrior(prior);

      vector<vector<double> > occupancy;
      double norm = predictor.predict(initial, occupancy);

      gridView.addBelief(occupancy, -300.0, 0.0, white, red);


      gridView.addVector(trajectory, blue, factor);

      char buf[1024];
      sprintf(buf, "../figures/train%04d.bmp", i);
      gridView.write(buf);

      vector<double> modelFeats, pathFeats;

      //cout << "Computing feature counts"<<endl;

	  /*
      for (int i=0; i < occupancy.size(); i++)
         for (int j=0; j < occupancy.at(i).size(); j++) 
            if (occupancy.at(i).at(j) > -10)
               cout << i <<" "<<j<<"    "<<occupancy.at(i).at(j)<<endl; 
      */

      featArray.featureCounts(occupancy, modelFeats);

      featArray.featureCounts(trajectory, pathFeats);

      cout << "GRADIENT"<<endl;

      for (int k=0; k < params.size(); k++) {
         double diff = pathFeats.at(k) - modelFeats.at(k);
         gradient.at(k) -= diff;
         cout << k << ": " << gradient.at(k) << "    " << pathFeats.at(k)
            << " " << modelFeats.at(k) <<endl;
      }

      cout << "OBJ: "<<cost-norm<<endl;
      cout << "     "<<cost<<"  "<<norm<<endl;
      obj += (cost - norm);

      prior.at(destination.first).at(destination.second) = -HUGE_VAL; 
   }

   cout << "RETURN OBJ: "<<-obj<<endl;

   return -obj;
}