nsEventStatus
InputQueue::ReceiveInputEvent(const RefPtr<AsyncPanZoomController>& aTarget,
                              bool aTargetConfirmed,
                              const InputData& aEvent,
                              uint64_t* aOutInputBlockId) {
  APZThreadUtils::AssertOnControllerThread();

  switch (aEvent.mInputType) {
    case MULTITOUCH_INPUT: {
      const MultiTouchInput& event = aEvent.AsMultiTouchInput();
      return ReceiveTouchInput(aTarget, aTargetConfirmed, event, aOutInputBlockId);
    }

    case SCROLLWHEEL_INPUT: {
      const ScrollWheelInput& event = aEvent.AsScrollWheelInput();
      return ReceiveScrollWheelInput(aTarget, aTargetConfirmed, event, aOutInputBlockId);
    }

    case PANGESTURE_INPUT: {
      const PanGestureInput& event = aEvent.AsPanGestureInput();
      return ReceivePanGestureInput(aTarget, aTargetConfirmed, event, aOutInputBlockId);
    }

    default:
      // The return value for non-touch input is only used by tests, so just pass
      // through the return value for now. This can be changed later if needed.
      // TODO (bug 1098430): we will eventually need to have smarter handling for
      // non-touch events as well.
      return aTarget->HandleInputEvent(aEvent, aTarget->GetTransformToThis());
  }
}
Exemple #2
0
InputData* Parser::getAsInputData() {
    InputData* inputData = new InputData();
    for (int i = 0; i < this->container->size(); i++) {
        inputData->pushVector(this->container->getVectorAt(i));
    }
    return inputData; 
}
Exemple #3
0
InputData resample(InputData data, std::vector<int> indxs){
    InputData res;
    int max_sample_per_set = sqrt(data.size());
    for(int i = 0; i < max_sample_per_set; i++)
        res.push_back(data[indxs[i]]);
    return res;
}
  bool
  StreamReaderUnix::ProcessCSI(InputData& in) {
    static ExtKeyMap gExtKeyMap;
    if (gExtKeyMap.empty()) {
      // Gnome xterm
      gExtKeyMap['[']['A'] = InputData::kEIUp;
      gExtKeyMap['[']['B'] = InputData::kEIDown;
      gExtKeyMap['[']['C'] = InputData::kEIRight;
      gExtKeyMap['[']['D'] = InputData::kEILeft;
      gExtKeyMap['[']['F'] = InputData::kEIEnd; // Savannah 83478
      gExtKeyMap['[']['H'] = InputData::kEIHome;
      gExtKeyMap['[']['O']['F'] = InputData::kEIEnd;
      gExtKeyMap['[']['O']['H'] = InputData::kEIHome;
      gExtKeyMap['[']['1']['~'] = InputData::kEIHome;
      gExtKeyMap['[']['2']['~'] = InputData::kEIIns;
      gExtKeyMap['[']['3']['~'] = InputData::kEIDel;
      gExtKeyMap['[']['4']['~'] = InputData::kEIEnd;
      gExtKeyMap['[']['5']['~'] = InputData::kEIPgUp;
      gExtKeyMap['[']['6']['~'] = InputData::kEIPgDown;
      gExtKeyMap['[']['1'][';']['5']['A'].Set(InputData::kEIUp,
                                         InputData::kModCtrl);
      gExtKeyMap['[']['1'][';']['5']['B'].Set(InputData::kEIDown,
                                         InputData::kModCtrl);
      gExtKeyMap['[']['1'][';']['5']['C'].Set(InputData::kEIRight,
                                         InputData::kModCtrl);
      gExtKeyMap['[']['1'][';']['5']['D'].Set(InputData::kEILeft,
                                         InputData::kModCtrl);

      // MacOS
      gExtKeyMap['O']['A'] = InputData::kEIUp;
      gExtKeyMap['O']['B'] = InputData::kEIDown;
      gExtKeyMap['O']['C'] = InputData::kEIRight;
      gExtKeyMap['O']['D'] = InputData::kEILeft;
      gExtKeyMap['O']['F'] = InputData::kEIEnd;
      gExtKeyMap['O']['H'] = InputData::kEIHome;
      gExtKeyMap['[']['5']['C'].Set(InputData::kEIRight, InputData::kModCtrl);
      gExtKeyMap['[']['5']['D'].Set(InputData::kEILeft, InputData::kModCtrl);
    }

    InputData::EExtendedInput ret = InputData::kEIUninitialized;
    char mod = 0;
    Rewind rwd(fReadAheadBuffer, ret);
    ExtKeyMap* EKM = &gExtKeyMap;
    while (EKM) {
      if (EKM->haveExtInp()) {
        ret = EKM->getExtInp();
        mod = EKM->getMod();
        EKM = 0;
      } else {
        char c1 = ReadRawCharacter();
        rwd.push(c1);
        EKM = EKM->find(c1);
      }
    }
    in.SetExtended(ret);
    in.SetModifier(mod);
    return ret != InputData::kEIUninitialized;
  }
Exemple #5
0
    bool operator () (Location* l1, Location* l2) {
        InputData* input = InputData::getInstance();
        double* locationDistances = input->getDistancesFrom(location->getIndex());

        double dist1 = locationDistances[l1->getIndex()];
        double dist2 = locationDistances[l2->getIndex()];

        return (dist1 < dist2);
    }
void
StreamReaderWin::HandleKeyEvent(unsigned char C, InputData& in) {
    if (isprint(C)) {
        in.SetRaw(C);
    } else if (C < 32) {
        in.SetRaw(C);
        in.SetModifier(InputData::kModCtrl);
    } else {
        // woohoo, what's that?!
        in.SetRaw(C);
    }
}
 bool
 StreamReaderUnix::ReadInput(size_t& nRead, InputData& in) {
   int c = ReadRawCharacter();
   in.SetModifier(InputData::kModNone);
   if (c == -1) {
     in.SetExtended(InputData::kEIEOF);
   } else if (c == 0x1b) {
     // Only try to process CSI if Esc does not have a meaning
     // by itself.
     if (GetContext()->GetKeyBinding()->IsEscCommandEnabled()
         || !ProcessCSI(in)) {
       in.SetExtended(InputData::kEIEsc);
     }
   } else if (isprint(c)) {
     in.SetRaw(c);
   } else if (c < 32 || c == (char)127 /* ^?, DEL on MacOS */) {
     if (c == 13) {
       in.SetExtended(InputData::kEIEnter);
     } else {
       in.SetRaw(c);
       in.SetModifier(InputData::kModCtrl);
     }
   } else {
     // woohoo, what's that?!
     in.SetRaw(c);
   }
   ++nRead;
   return true;
 }
nsEventStatus AsyncPanZoomController::HandleInputEvent(const InputData& aEvent) {
  nsEventStatus rv = nsEventStatus_eIgnore;

  if (mGestureEventListener) {
    nsEventStatus rv = mGestureEventListener->HandleInputEvent(aEvent);
    if (rv == nsEventStatus_eConsumeNoDefault)
      return rv;
  }

  switch (aEvent.mInputType) {
  case MULTITOUCH_INPUT: {
    const MultiTouchInput& multiTouchInput = aEvent.AsMultiTouchInput();
    switch (multiTouchInput.mType) {
      case MultiTouchInput::MULTITOUCH_START: rv = OnTouchStart(multiTouchInput); break;
      case MultiTouchInput::MULTITOUCH_MOVE: rv = OnTouchMove(multiTouchInput); break;
      case MultiTouchInput::MULTITOUCH_END: rv = OnTouchEnd(multiTouchInput); break;
      case MultiTouchInput::MULTITOUCH_CANCEL: rv = OnTouchCancel(multiTouchInput); break;
      default: NS_WARNING("Unhandled multitouch"); break;
    }
    break;
  }
  case PINCHGESTURE_INPUT: {
    const PinchGestureInput& pinchGestureInput = aEvent.AsPinchGestureInput();
    switch (pinchGestureInput.mType) {
      case PinchGestureInput::PINCHGESTURE_START: rv = OnScaleBegin(pinchGestureInput); break;
      case PinchGestureInput::PINCHGESTURE_SCALE: rv = OnScale(pinchGestureInput); break;
      case PinchGestureInput::PINCHGESTURE_END: rv = OnScaleEnd(pinchGestureInput); break;
      default: NS_WARNING("Unhandled pinch gesture"); break;
    }
    break;
  }
  case TAPGESTURE_INPUT: {
    const TapGestureInput& tapGestureInput = aEvent.AsTapGestureInput();
    switch (tapGestureInput.mType) {
      case TapGestureInput::TAPGESTURE_LONG: rv = OnLongPress(tapGestureInput); break;
      case TapGestureInput::TAPGESTURE_UP: rv = OnSingleTapUp(tapGestureInput); break;
      case TapGestureInput::TAPGESTURE_CONFIRMED: rv = OnSingleTapConfirmed(tapGestureInput); break;
      case TapGestureInput::TAPGESTURE_DOUBLE: rv = OnDoubleTap(tapGestureInput); break;
      case TapGestureInput::TAPGESTURE_CANCEL: rv = OnCancelTap(tapGestureInput); break;
      default: NS_WARNING("Unhandled tap gesture"); break;
    }
    break;
  }
  default: NS_WARNING("Unhandled input event"); break;
  }

  mLastEventTime = aEvent.mTime;
  return rv;
}
int main() {
    InputData* data = new InputData();

    while (fgets(data->buffer, data->capacity, stdin))
        if (strncmp(data->buffer, ">THREE", 6) == 0)
            break;

    int cpus = numCPUS();
    WorkerThread threads[cpus];
    for (int i = 0; i<cpus-1; i++) {
        pthread_create(&(threads[i].pthread), NULL, (void *(*)(void *))doWork, &threads[i]);
    }

    size_t totalBytesRead = 0;
    while (fgets(&data->buffer[data->length], (data->capacity + 1) - data->length, stdin)) {
        data->length += strlen(&data->buffer[data->length]);
        if (data->buffer[data->length-1] == '\n') {
            data->buffer[--(data->length)] == 0;
        }

        if (data->length == data->capacity) {
            data->addToWorkList();
            totalBytesRead += data->length;
            data = new InputData(*data);
        }
    }

    if (data->length) {
        totalBytesRead += data->length;
        data->addToWorkList();
    }

    moreWorkIsPossible = 0;
    doWork(&threads[cpus-1]);
    for (int i=0; i<cpus-1; i++) {
        pthread_join(threads[i].pthread, NULL);
    }

    printFreq<1>(threads, cpus, (float)totalBytesRead);
    printFreq<2>(threads, cpus, (float)(totalBytesRead - 1));

    printCount<3>(threads, cpus, fragments[2]);
    printCount<4>(threads, cpus, fragments[3]);
    printCount<6>(threads, cpus, fragments[4]);
    printCount<12>(threads, cpus, fragments[5]);
    printCount<18>(threads, cpus, fragments[6]);

    return 0;
}
void CCharacterMotionControlAppTask::HandleInput( InputData& input )
{
	int action_code = m_pKeyBind ? m_pKeyBind->GetActionCode( input.iGICode ) : ACTION_NOT_ASSIGNED;

	switch( input.iGICode )
	{
	case '1':
		if( input.iType == ITYPE_KEY_PRESSED )
		{
			// toggle camera control
			bool enabled = IsCameraControllerEnabled();
			EnableCameraController( !enabled );
		}
		break;

//	case GIC_MOUSE_BUTTON_R:
//		if( input.iType == ITYPE_KEY_PRESSED )
//		{
//			if( m_pCharacterItems.empty() )
//				return;
//
//			shared_ptr<ItemEntity> pEntity = m_pCharacterItems[0]->GetItemEntity().Get();
//			if( !pEntity )
//				return;
//
//			m_CameraOrientation.target.FromRotationMatrix( pEntity->GetWorldPose().matOrient );
//		}
//		break;

	default:
		break;
	}

	switch( action_code )
	{
	case ACTION_MOV_LOOK_UP:
		if( input.IsMouseInput() && input.iType == ITYPE_VALUE_CHANGED )
		{
			if( m_pThirdPersonCameraController )
			{
				const bool invert_mouse = true;
				const float s = invert_mouse ? -1 : 1;
				const float angle
					= m_pThirdPersonCameraController->GetTargetVerticalAngle()
					+ input.fParam1 * 0.005f * s;
				m_pThirdPersonCameraController->SetTargetVerticalAngle( angle );
			}
		}
		break;

	default:
		break;
	}

	if( m_pThirdPersonMotionController )
	{
		m_pThirdPersonMotionController->HandleInput( action_code, input );
	}

}
void
TouchBlockState::DispatchEvent(const InputData& aEvent) const
{
  MOZ_ASSERT(aEvent.mInputType == MULTITOUCH_INPUT);
  mTouchCounter.Update(aEvent.AsMultiTouchInput());
  CancelableBlockState::DispatchEvent(aEvent);
}
Exemple #12
0
InputData* MDDAGClassifier::loadInputData(const string& dataFileName, const string& shypFileName)
{
    // open file
    ifstream inFile(shypFileName.c_str());
    if (!inFile.is_open())
    {
        cerr << "ERROR: Cannot open strong hypothesis file <" << shypFileName << ">!" << endl;
        exit(1);
    }

    // Declares the stream tokenizer
    nor_utils::StreamTokenizer st(inFile, "<>\n\r\t");

    // Move until it finds the multiboost tag
    if ( !UnSerialization::seekSimpleTag(st, "multiboost") )
    {
        // no multiboost tag found: this is not the correct file!
        cerr << "ERROR: Not a valid MultiBoost Strong Hypothesis file!!" << endl;
        exit(1);
    }

    // Move until it finds the algo tag
    string basicLearnerName = UnSerialization::seekAndParseEnclosedValue<string>(st, "algo");

    // Check if the weak learner exists
    if ( !BaseLearner::RegisteredLearners().hasLearner(basicLearnerName) )
    {
        cerr << "ERROR: Weak learner <" << basicLearnerName << "> not registered!!" << endl;
        exit(1);
    }

    // get the training input data, and load it
    BaseLearner* baseLearner = BaseLearner::RegisteredLearners().getLearner(basicLearnerName);
    baseLearner->initLearningOptions(_args);
    InputData* pData = baseLearner->createInputData();

    // set the non-default arguments of the input data
    pData->initOptions(_args);
    // load the data
    pData->load(dataFileName, IT_TEST, _verbose);

    return pData;
}
void
DragBlockState::DispatchEvent(const InputData& aEvent) const
{
  MouseInput mouseInput = aEvent.AsMouseInput();
  if (!mouseInput.TransformToLocal(mTransformToApzc)) {
    return;
  }

  GetTargetApzc()->HandleDragEvent(mouseInput, mDragMetrics);
}
Exemple #14
0
void InternalPortModel::updateOutputPortColor(void)
{
    if(type == OUTPUTD)
    {
        strColor = COLOR_NOMAL;
        std::vector<ArrowModel*>::iterator itr;
        for(itr=sourceArrows.begin(); itr<sourceArrows.end(); itr++)
            if((*itr)->getDestination() &&
                Glib::RefPtr<InternalPortModel>::cast_dynamic((*itr)->getDestination()))
            {
                InputData* inp = Glib::RefPtr<InternalPortModel>::cast_dynamic((*itr)->getDestination())->getInput();
                if(inp && (string(inp->getName()) != "*") &&
                   !compareString(output->getName(), inp->getName()))
                {
                    strColor = COLOR_MISMATCH;
                    break;
                }
            }
        poly->property_fill_color().set_value(strColor.c_str());
    }
}
void Newton::compute_DzMat(InputData& inputData,
			   Residuals& currentRes,
			   Phase& phase,
			   ComputeTime& com)
{
  TimeStart(START_SUMDZ);
  inputData.multi_plusToA(DyVec, DzMat);
  Lal::let(DzMat,'=',DzMat,'*',&DMONE);
  if (phase.value == SolveInfo:: pFEAS
      || phase.value == SolveInfo::noINFO) {
    Lal::let(DzMat,'=',DzMat,'+',currentRes.dualMat);
  }
  TimeEnd(END_SUMDZ);
  com.sumDz += TimeCal(START_SUMDZ,END_SUMDZ);
}
Exemple #16
0
// Sends text over the input mailslot to the server
void sendInput(char* szText, short nType)
{
   InputData idMessage;
   char szBuffer[250];
   static bool bAlreadyWarned = false;
   
   if ( szText != NULL )
      {
      if ( strlen(szText) > 198 )
         szText[198] = '\0';
      strcpy(idMessage.szMessage, szText);
      }
   else
      idMessage.szMessage[0] = '\0';
      
   idMessage.nFrom = getNode();
   idMessage.nType = nType;
   
   sendToSlot(hInputSlot, idMessage.toString(szBuffer));

   nPending++;
   if ( nPending == 2 )
      Sleep(200);
   if ( nPending == 3 || nPending == 4 )
      Sleep( nPending * 300);
   if ( nPending >= 5 && !bAlreadyWarned )
      {
      local("\r\nA door process has locked up.  Please wait a minute and then re-enter the door.");
      local("If the door still doesn't run, have your sysop use CTRL-ALT-DELETE to kill the");
      sprintf(szBuffer, "instance of %s that is running.", DOOR_SERVER_EXE);
      local(szBuffer);
      bAlreadyWarned = true;
      Sleep(3000);
      exitDoor(0);
      }
}
extern "C" __declspec(dllexport) wchar_t * __stdcall process(const wchar_t* inputFileName, const wchar_t * inputFileContent, int * hasErrors)
{
	hostLang = &hostLangCSharp;
	wstringstream out;
	wstringstream errors;

	pErrorStream = &errors;
	gblErrorCount = 0;

	InputData id;

	id.inputFileName = inputFileName;
	id.outputFileName = inputFileName;
	id.inStream = new wstringstream(inputFileContent);
	id.outStream = &out;

	InputItem *firstInputItem = new InputItem;
	firstInputItem->type = InputItem::HostData;
	firstInputItem->loc.fileName = id.inputFileName;
	firstInputItem->loc.line = 1;
	firstInputItem->loc.col = 1;
	id.inputItems.append(firstInputItem);

	Scanner scanner(id, id.inputFileName, *id.inStream, 0, 0, 0, false);
	scanner.do_scan();

	id.terminateAllParsers();
	id.prepareMachineGen();
	id.generateReduced();
	id.verifyWritesHaveData();
	id.writeOutput();

	wchar_t * result = NULL;

	if (gblErrorCount > 0)
	{
		*hasErrors = true;
		int length = (errors.str().length() + 1) * sizeof(wchar_t);
		result = (wchar_t*)::CoTaskMemAlloc(length);
		wcscpy_s(result, errors.str().length() + 1, errors.str().c_str());
	}
	else
	{
		*hasErrors = false;
		int length = (out.str().length() + 1) * sizeof(wchar_t);
		result = (wchar_t*)::CoTaskMemAlloc(length);
		wcscpy_s(result, out.str().length() + 1, out.str().c_str());
	}

	return result;
}
Exemple #18
0
bool PicParams::extractProfile(InputData &ifile, PyObject *mypy, ProfileStructure &P)
{
    double val;
    // If the profile is only a double, then convert to a constant function
    if( PyTools::convert(mypy, val) ) {
        // Extract the function "constant"
        PyObject* constantFunction = ifile.extract_py("constant");
        // Create the argument which has the value of the profile
        PyObject* arg = PyTuple_New(1);
        PyTuple_SET_ITEM(arg, 0, PyFloat_FromDouble(val));
        // Create the constant anonymous function
        PyObject * tmp = PyObject_Call(constantFunction, arg, NULL);
        P.py_profile = tmp;
        return true;
    } else if (mypy && PyCallable_Check(mypy)) {
        P.py_profile=mypy;
        return true;
    }
    return false;
}
Exemple #19
0
void PicParams::extractVectorOfProfiles(InputData &ifile, string varname, vector<ProfileStructure*> &Pvec, int ispec)
{
    Pvec.resize(3);
    vector<PyObject*> pvec = ifile.extract_pyVec(varname, "Species", ispec);
    int len = pvec.size();
    if( len==3 ) {
        for(int i=0; i<len; i++) {
            Pvec[i] = new ProfileStructure();
            if( !extractProfile(ifile, pvec[i], *(Pvec[i])) )
                ERROR("For species #" << ispec << ", "<<varname<<"["<<i<<"] not understood");
        }
    } else if ( len==1 ) {
        Pvec[0] = new ProfileStructure();
        if( !extractProfile(ifile, pvec[0], *(Pvec[0])) )
            ERROR("For species #" << ispec << ", "<<varname<<" not understood");
        Pvec[1] = Pvec[0];
        Pvec[2] = Pvec[0];
    } else {
        ERROR("For species #" << ispec << ", "<<varname<<" needs 1 or 3 components.");
    }
}
Exemple #20
0
  Editor::Command KeyBinding::ToCommand(InputData In) {
    // Convert InputData into a Command
    typedef Editor::Command C;
    bool HadEscPending = fEscPending;
    fEscPending = false;
    if (In.IsRaw()) {
      if (In.GetModifier() & InputData::kModCtrl) {
        return ToCommandCtrl(In.GetRaw(), HadEscPending);
      }

      if (HadEscPending) {
        return ToCommandEsc(In.GetRaw());
      }

      return C(In.GetRaw());
    }
    // else
    return ToCommandExtended(In.GetExtendedInput(), HadEscPending);
  }
Exemple #21
0
void MDDAGClassifier::saveConfusionMatrix(const string& dataFileName, const string& shypFileName,
        const string& outFileName)
{
    InputData* pData = loadInputData(dataFileName, shypFileName);

    if (_verbose > 0)
        cout << "Loading strong hypothesis..." << flush;

    // The class that loads the weak hypotheses
    UnSerialization us;

    // Where to put the weak hypotheses
    vector<BaseLearner*> weakHypotheses;

    // loads them
    us.loadHypotheses(shypFileName, weakHypotheses, pData);

    // where the results go
    vector< ExampleResults* > results;

    if (_verbose > 0)
        cout << "Classifying..." << flush;

    // get the results
    computeResults( pData, weakHypotheses, results, (int)weakHypotheses.size() );

    const int numClasses = pData->getNumClasses();
    const int numExamples = pData->getNumExamples();

    ofstream outFile(outFileName.c_str());

    //////////////////////////////////////////////////////////////////////////

    for (int l = 0; l < numClasses; ++l)
        outFile << '\t' << pData->getClassMap().getNameFromIdx(l);
    outFile << endl;

    for (int l = 0; l < numClasses; ++l)
    {
        vector<int> winnerCount(numClasses, 0);
        for (int i = 0; i < numExamples; ++i)
        {
            if ( pData->hasPositiveLabel(i,l) )
                ++winnerCount[ results[i]->getWinner().first ];
        }

        // class name
        outFile << pData->getClassMap().getNameFromIdx(l);

        for (int j = 0; j < numClasses; ++j)
            outFile << '\t' << winnerCount[j];

        outFile << endl;
    }

    //////////////////////////////////////////////////////////////////////////

    if (_verbose > 0)
        cout << "Done!" << endl;

    // delete the input data file
    if (pData)
        delete pData;

    vector<ExampleResults*>::iterator it;
    for (it = results.begin(); it != results.end(); ++it)
        delete (*it);
}
ArrowModel::ArrowModel(ApplicationWindow* parentWnd,
                       Glib::RefPtr<PortModel> src, Glib::RefPtr<PortModel> dest,
                       Connection* con, ApplicationModel* appModel, bool nullArw): PolylineModel(0,0,0,0), connection(NULL, NULL) 
{
    parentWindow = parentWnd;
    source = src;
    destination = dest;
    selected = false;
    bExist = false;
    bNullArrow = nullArw;
    applicationModel = appModel; 
    bNested = (applicationModel != NULL);
    if(appModel)
        application = appModel->getApplication();
    else        
        application = parentWindow->manager.getKnowledgeBase()->getApplication();

    if(con)
    {
        strLabel = con->carrier();
        connection = *con;
    }
        
    this->property_close_path().set_value(false);
    this->property_line_width().set_value(ARROW_LINEWIDTH);
    this->property_arrow_width().set_value(5.0);
    if(!bNullArrow)
        this->property_end_arrow().set_value(true);
    if(bNested)
    {
        defaultColor = "#555555";
        //GooCanvasLineDash *dash = goo_canvas_line_dash_new (ARROW_LINEWIDTH, 3.0, 3.0);
        //g_object_set(this->gobj(), "line-dash", dash, NULL);
    }
    else
        defaultColor = "black";

    source->addSourceArrow(this);
    destination->addDestinationArrow(this);
    if(!bNullArrow)
    {
        string strCarrier = strLabel;
        string dummyLabel;
        //Adding connection 
        if(application)
        {
            string strFrom, strTo;
            Glib::RefPtr<InternalPortModel> intPort;
            Glib::RefPtr<ExternalPortModel> extPort;
            Glib::RefPtr<PortArbitratorModel> arbPort;
            Module* module;
            InputData* input = NULL;
            OutputData* output = NULL;
            bool bExternFrom = false;
            bool bExternTo = false;

            // port arbitrator at the destination
            arbPort = Glib::RefPtr<PortArbitratorModel>::cast_dynamic(destination);

            // source 
            intPort = Glib::RefPtr<InternalPortModel>::cast_dynamic(source);
            if(intPort)
            {
                output = intPort->getOutput();
                module = (Module*) output->owner();
                strFrom = string(module->getPrefix()) + string(intPort->getOutput()->getPort()); 
                dummyLabel = string(intPort->getOutput()->getPort());
                if(!strCarrier.size())
                {
                    strCarrier = intPort->getOutput()->getCarrier();
                    if(arbPort)
                        strCarrier += "+recv.priority";
                }                    
            }
            else
            {
                extPort = Glib::RefPtr<ExternalPortModel>::cast_dynamic(source);
                strFrom = extPort->getPort();
                dummyLabel = string(extPort->getPort());
                if(!strCarrier.size() && arbPort)
                    strCarrier = "udp+recv.priority";
                bExternFrom = true;
            }
          
            // destination
            intPort = Glib::RefPtr<InternalPortModel>::cast_dynamic(destination);
            if(intPort)
            {
                input = intPort->getInput();
                module = (Module*) input->owner();
                strTo = string(module->getPrefix()) + string(intPort->getInput()->getPort()); 
                dummyLabel += string(" -> ") + string(intPort->getInput()->getPort()) + string(" "); 
                if(!strCarrier.size())   
                {
                    strCarrier = intPort->getInput()->getCarrier();
                    if(arbPort)
                        strCarrier += "+recv.priority";
                }                    
            }
            else if(arbPort)
            {
                intPort = Glib::RefPtr<InternalPortModel>::cast_dynamic(arbPort->getPortModel());
                extPort = Glib::RefPtr<ExternalPortModel>::cast_dynamic(arbPort->getPortModel());
                if(intPort)
                {
                    input = intPort->getInput();
                    module = (Module*) input->owner();
                    strTo = string(module->getPrefix()) + string(intPort->getInput()->getPort()); 
                    dummyLabel += string(" -> ") + string(intPort->getInput()->getPort()) + string(" "); 
                    if(!strCarrier.size())
                    {
                        strCarrier = intPort->getInput()->getCarrier();
                        strCarrier += "+recv.priority";
                    }                        
                }
                else
                {
                    strTo = extPort->getPort();
                    dummyLabel += string(" -> ") + string(extPort->getPort()) + string(" "); 
                    bExternTo = true;
                    if(!strCarrier.size())
                        strCarrier = "udp+recv.priority";
                }
            }
            else
            {
                extPort = Glib::RefPtr<ExternalPortModel>::cast_dynamic(destination);
                strTo = extPort->getPort();
                dummyLabel += string(" -> ") + string(extPort->getPort()) + string(" "); 
                bExternTo = true;
                if(!strCarrier.size())
                        strCarrier = "udp";
            }
            
            connection.setFrom(strFrom.c_str());
            connection.setTo(strTo.c_str());
            connection.setCarrier(strCarrier.c_str());
            connection.setFromExternal(bExternFrom);
            connection.setToExternal(bExternTo);
            connection.setCorOutputData(output);
            connection.setCorInputData(input);
            connection.setModel(this);
            connection = parentWindow->manager.getKnowledgeBase()->addConnectionToApplication(application, connection);
            tool = TooltipModel::create(parentWindow, dummyLabel.c_str());
        }

        strLabel = strCarrier;
        this->property_stroke_color().set_value(defaultColor.c_str());
        if(strLabel.size())
            label = LabelModel::create(parentWindow, this, strLabel.c_str());
        else
            label = LabelModel::create(parentWindow, this, strCarrier.c_str());

        // if it is an auxilary connections
        /*
        if((strLabel.find("virtual") != std::string::npos) || 
           (strLabel.find("auxiliary") != std::string::npos) )
        {
            GooCanvasLineDash *dash = goo_canvas_line_dash_new (ARROW_LINEWIDTH, 3.0, 3.0);
            g_object_set(this->gobj(), "line-dash", dash, NULL);      
        }
        */

        if(bNested)
        {
            applicationModel->add_child(label);
            label->property_visibility().set_value(Goocanvas::ITEM_HIDDEN);
        }
        else
            parentWindow->getRootModel()->add_child(label);
        label->raise();

        showLabel(parentWindow->m_showLabel);
    }

    
    Gdk::Point pt1 = source->getContactPoint(this);
    Gdk::Point pt2 = destination->getContactPoint(this);
    setPoint(0, pt1.get_x(), pt1.get_y()-ARROW_LINEWIDTH/2.0);
    Goocanvas::Points points = this->property_points().get_value();
    setPoint(points.get_num_points()-1, pt2.get_x(), pt2.get_y()-ARROW_LINEWIDTH/2.0);
    setLabel(strLabel.c_str());
    updatCoordiantes();
    //printf("%s : %d\n", __FILE__, __LINE__); 
}
Exemple #23
0
Module* XmlModLoader::parsXml(const char* szFile)
{
    module.clear();
    ErrorLogger* logger  = ErrorLogger::Instance();

    TiXmlDocument doc(szFile);
    if(!doc.LoadFile())
    {
        OSTRINGSTREAM err;
        err<<"Syntax error while loading "<<szFile<<" at line "\
           <<doc.ErrorRow()<<": ";
        err<<doc.ErrorDesc();
        logger->addError(err);
        return nullptr;
    }

    /* retrieving root module */
    TiXmlElement *root = doc.RootElement();
    if(!root)
    {
        OSTRINGSTREAM err;
        err<<"Syntax error while loading "<<szFile<<" . ";
        err<<"No root element.";
        logger->addError(err);
        return nullptr;
    }

    if(!compareString(root->Value(), "module"))
    {
        /*
        OSTRINGSTREAM msg;
        msg<<szFile<<" is not a module descriptor file.";
        logger->addWarning(msg);
        */
        return nullptr;
    }

    /* retrieving name */
    auto* name = (TiXmlElement*) root->FirstChild("name");
    if(!name || !name->GetText())
    {
        OSTRINGSTREAM err;
        err<<"Module from "<<szFile<<" has no name.";
        logger->addError(err);
        //return NULL;
    }

    for(TiXmlElement* var = root->FirstChildElement("var"); var; var = var->NextSiblingElement())
    {
        if(var->Attribute("name") && var->GetText())
        {
            parser->addVariable(var->Attribute("name"), var->GetText());
        }
    }

    module.setXmlFile(szFile);

    if(name)
        module.setName(parser->parseText(name->GetText()).c_str());

    /* retrieving description */
    TiXmlElement* desc;
    if((desc = (TiXmlElement*) root->FirstChild("description")))
        module.setDescription(parser->parseText(desc->GetText()).c_str());

    /* retrieving version */
    TiXmlElement* ver;
    if((ver = (TiXmlElement*) root->FirstChild("version")))
        module.setVersion(parser->parseText(ver->GetText()).c_str());


    /* retrieving parameter */
    TiXmlElement* arguments;
    if((arguments = (TiXmlElement*) root->FirstChild("arguments")))
        for(TiXmlElement* param = arguments->FirstChildElement(); param;
                param = param->NextSiblingElement())
        {
            if(compareString(param->Value(), "param"))
            {
                if(param->GetText())
                {
                    bool brequired = false;
                    if(compareString(param->Attribute("required"), "yes"))
                        brequired = true;
                    Argument arg(parser->parseText(param->GetText()).c_str(),
                                 brequired,
                                 param->Attribute("desc"));
                    arg.setDefault(param->Attribute("default"));
                    module.addArgument(arg);
                }
            }
            else
            if(compareString(param->Value(), "switch"))
            {
                if(param->GetText())
                {
                    bool brequired = false;
                    if(compareString(param->Attribute("required"), "yes"))
                        brequired = true;
                    Argument arg(parser->parseText(param->GetText()).c_str(),
                                 brequired,
                                 param->Attribute("desc"), true);
                    arg.setDefault(param->Attribute("default"));
                    module.addArgument(arg);
                }
            }
            else
            {
                OSTRINGSTREAM war;
                war<<"Unrecognized tag from "<<szFile<<" at line "\
                   <<param->Row()<<".";
                logger->addWarning(war);
            }

        }


    /* retrieving rank */
    TiXmlElement* rank;
    if((rank = (TiXmlElement*) root->FirstChild("rank")) &&
        rank->GetText())
        module.setRank(atoi(parser->parseText(rank->GetText()).c_str()));


    /* retrieving authors information*/
    TiXmlElement* authors;
    if((authors = (TiXmlElement*) root->FirstChild("authors")))
        for(TiXmlElement* ath = authors->FirstChildElement(); ath;
                ath = ath->NextSiblingElement())
        {
            if(compareString(ath->Value(), "author"))
            {
                Author author;
                if(ath->GetText())
                    author.setName(parser->parseText(ath->GetText()).c_str());
                if(ath->Attribute("email"))
                    author.setEmail(ath->Attribute("email"));
                module.addAuthor(author);
            }
            else
            {
                OSTRINGSTREAM war;
                war<<"Unrecognized tag from "<<szFile<<" at line "\
                   <<ath->Row()<<".";
                logger->addWarning(war);
            }

        }


   /* retrieving data */
    if(root->FirstChild("data"))
        for(TiXmlElement* data = root->FirstChild("data")->FirstChildElement();
            data; data = data->NextSiblingElement())
        {
            /* output data */
            if(compareString(data->Value(), "output"))
            {
                OutputData output;

                if(compareString(data->Attribute("port_type"), "stream") || !data->Attribute("port_type"))
                    output.setPortType(STREAM_PORT);
                else if(compareString(data->Attribute("port_type"), "event"))
                    output.setPortType(EVENT_PORT);
                else if(compareString(data->Attribute("port_type"), "service"))
                    output.setPortType(SERVICE_PORT);
                else
                {
                    OSTRINGSTREAM war;
                    war<<"Unknown port type \'"<<data->Attribute("port_type")<<"\' from "<<szFile<<" at line "\
                       <<data->Row()<<". Available types : stream, event, service";
                    logger->addWarning(war);
                }


                TiXmlElement* element;
                if(output.getPortType() != SERVICE_PORT )
                {
                    if((element = (TiXmlElement*) data->FirstChild("type")))
                        output.setName(parser->parseText(element->GetText()).c_str());
                    else
                    {
                        OSTRINGSTREAM war;
                        war<<"Output data from "<<szFile<<" at line "\
                           <<data->Row()<<" has no type.";
                        logger->addWarning(war);
                    }
                }
                else
                    output.setName("*");

                if((element = (TiXmlElement*) data->FirstChild("port")))
                {
                    output.setPort(parser->parseText(element->GetText()).c_str());
                    output.setCarrier(element->Attribute("carrier"));
                }
                else
                {
                    OSTRINGSTREAM war;
                    war<<"Output data from "<<szFile<<" at line "\
                       <<data->Row()<<" has no port.";
                    logger->addWarning(war);
                }

                if((element = (TiXmlElement*) data->FirstChild("description")))
                    output.setDescription(parser->parseText(element->GetText()).c_str());

                module.addOutput(output);
            } // end of output data

            /* input data */
            if(compareString(data->Value(), "input"))
            {
                InputData input;

                if(compareString(data->Attribute("port_type"), "stream") || !data->Attribute("port_type"))
                    input.setPortType(STREAM_PORT);
                else if(compareString(data->Attribute("port_type"), "event"))
                    input.setPortType(EVENT_PORT);
                else if(compareString(data->Attribute("port_type"), "service"))
                    input.setPortType(SERVICE_PORT);
                else
                {
                    OSTRINGSTREAM war;
                    war<<"Unknown port type \'"<<data->Attribute("port_type")<<"\' from "<<szFile<<" at line "\
                       <<data->Row()<<". Available types : stream, event, service";
                    logger->addWarning(war);
                }

                TiXmlElement* element;
                if(input.getPortType() != SERVICE_PORT )
                {

                    if((element = (TiXmlElement*) data->FirstChild("type")))
                        input.setName(parser->parseText(element->GetText()).c_str());
                    else
                    {
                        OSTRINGSTREAM war;
                        war<<"Input data from "<<szFile<<" at line "\
                           <<data->Row()<<" has no type.";
                        logger->addWarning(war);
                    }
                }
                else
                    input.setName("rpc");

                if((element = (TiXmlElement*) data->FirstChild("port")))
                {
                    input.setPort(parser->parseText(element->GetText()).c_str());
                    input.setCarrier(element->Attribute("carrier"));
                }
                else
                {
                    OSTRINGSTREAM war;
                    war<<"Input data from "<<szFile<<" at line "\
                       <<data->Row()<<" has no port.";
                    logger->addWarning(war);
                }

                if((element = (TiXmlElement*) data->FirstChild("description")))
                    input.setDescription(parser->parseText(element->GetText()).c_str());

                if((element = (TiXmlElement*) data->FirstChild("required")))
                    if(compareString(parser->parseText(element->GetText()).c_str(), "yes"))
                        input.setRequired(true);

                if((element = (TiXmlElement*) data->FirstChild("priority")))
                    if(compareString(parser->parseText(element->GetText()).c_str(), "yes"))
                        input.setPriority(true);

                module.addInput(input);
            } // end of input data

        }

    if(root->FirstChild("services")) {
        for(TiXmlElement* services = root->FirstChild("services")->FirstChildElement();
            services; services = services->NextSiblingElement())
        {
            /* server */
            if(compareString(services->Value(), "server"))
            {
                InputData input;
                input.setPortType(SERVICE_PORT);
                TiXmlElement* element;
                if((element = (TiXmlElement*) services->FirstChild("port"))) {
                    input.setPort(parser->parseText(element->GetText()).c_str());
                    input.setCarrier("tcp");
                }
                if((element = (TiXmlElement*) services->FirstChild("description")))
                    input.setDescription(parser->parseText(element->GetText()).c_str());
                if((element = (TiXmlElement*) services->FirstChild("type")))
                    input.setName(parser->parseText(element->GetText()).c_str());
                else
                    input.setName("rpc");
                module.addInput(input);
            }
            /* client */
            if(compareString(services->Value(), "client"))
            {
                OutputData output;
                output.setPortType(SERVICE_PORT);
                TiXmlElement* element;
                if((element = (TiXmlElement*) services->FirstChild("port"))) {
                    output.setPort(parser->parseText(element->GetText()).c_str());
                    output.setCarrier("tcp");
                }
                if((element = (TiXmlElement*) services->FirstChild("description")))
                    output.setDescription(parser->parseText(element->GetText()).c_str());
                if((element = (TiXmlElement*) services->FirstChild("type")))
                    output.setName(parser->parseText(element->GetText()).c_str());
                else
                    output.setName("rpc");
                module.addOutput(output);
            }
        }

    }

    /* retrieving broker*/
    TiXmlElement* element;
    if((element = (TiXmlElement*) root->FirstChild("deployer")))
    {
        module.setBroker(parser->parseText(element->GetText()).c_str());
        module.setNeedDeployer(true);
    }

    /* retrieving dependencies*/
    if(root->FirstChild("dependencies"))
        for(TiXmlElement* restag = root->FirstChild("dependencies")->FirstChildElement();
            restag; restag = restag->NextSiblingElement())
        {
            Computer computer;
            if(compareString(restag->Value(), "computer"))
            {
                Computer computer;
                computer.setXmlFile(szFile);
                for(TiXmlElement* comptag = restag->FirstChildElement();
                    comptag; comptag = comptag->NextSiblingElement())
                {
                     /* retrieving name */
                    if(compareString(comptag->Value(), "name"))
                        computer.setName(parser->parseText(comptag->GetText()).c_str());

                    /* retrieving description */
                     if(compareString(comptag->Value(), "description"))
                        computer.setDescription(parser->parseText(comptag->GetText()).c_str());

                    // platform
                    if(compareString(comptag->Value(), "platform"))
                    {
                        Platform os;
                        TiXmlElement* element;
                        if((element = (TiXmlElement*) comptag->FirstChild("name")))
                            os.setName(parser->parseText(element->GetText()).c_str());
                        if((element = (TiXmlElement*) comptag->FirstChild("distribution")))
                            os.setDistribution(parser->parseText(element->GetText()).c_str());
                        if((element = (TiXmlElement*) comptag->FirstChild("release")))
                            os.setRelease(parser->parseText(element->GetText()).c_str());
                        computer.setPlatform(os);
                    } // end of platform tag

                    /*
                    //multiplatform
                    if(compareString(comptag->Value(), "multiplatform"))
                    {
                        MultiPlatform mltPlatform;
                        for(TiXmlElement* mptag = comptag->FirstChild("multiplatform")->FirstChildElement();
                            mptag; mptag = mptag->NextSiblingElement())
                        {
                            // platform
                            if(compareString(mptag->Value(), "platform"))
                            {
                                Platform os;
                                TiXmlElement* element;
                                if((element = (TiXmlElement*) mptag->FirstChild("name")))
                                    os.setName(element->GetText());
                                if((element = (TiXmlElement*) mptag->FirstChild("distribution")))
                                    os.setDistribution(element->GetText());
                                if((element = (TiXmlElement*) mptag->FirstChild("release")))
                                    os.setDistribution(element->GetText());
                                mltPlatform.addPlatform(os);
                            }
                        }
                        module.addResource(mltPlatform);
                    }
                    // end of multiplatform tag
                    */
                    // memory
                    if(compareString(comptag->Value(), "memory"))
                    {
                        Memory mem;
                        TiXmlElement* element;
                        if((element = (TiXmlElement*) comptag->FirstChild("total_space")))
                            mem.setTotalSpace((Capacity)atol(parser->parseText(element->GetText()).c_str()));
                        if((element = (TiXmlElement*) comptag->FirstChild("free_space")))
                            mem.setFreeSpace((Capacity)atol(parser->parseText(element->GetText()).c_str()));
                        computer.setMemory(mem);
                    } // end of memory tag

                    // storage
                    if(compareString(comptag->Value(), "storage"))
                    {
                        Storage stg;
                        TiXmlElement* element;
                        if((element = (TiXmlElement*) comptag->FirstChild("total_space")))
                            stg.setTotalSpace((Capacity)atol(parser->parseText(element->GetText()).c_str()));
                        if((element = (TiXmlElement*) comptag->FirstChild("free_space")))
                            stg.setFreeSpace((Capacity)atol(parser->parseText(element->GetText()).c_str()));
                        computer.setStorage(stg);
                    } // end of storage tag

                    // processor
                    if(compareString(comptag->Value(), "processor"))
                    {
                        Processor proc;
                        TiXmlElement* element;
                        if((element = (TiXmlElement*) comptag->FirstChild("architecture")))
                            proc.setArchitecture(parser->parseText(element->GetText()).c_str());
                        if((element = (TiXmlElement*) comptag->FirstChild("model")))
                            proc.setModel(parser->parseText(element->GetText()).c_str());
                        if((element = (TiXmlElement*) comptag->FirstChild("cores")))
                            proc.setCores((size_t)atoi(parser->parseText(element->GetText()).c_str()));
                        if((element = (TiXmlElement*) comptag->FirstChild("siblings")))
                            proc.setSiblings((size_t)atoi(parser->parseText(element->GetText()).c_str()));
                        if((element = (TiXmlElement*) comptag->FirstChild("frequency")))
                            proc.setFrequency(atof(parser->parseText(element->GetText()).c_str()));
                        computer.setProcessor(proc);
                    } // end of processor tag

                    // network
                    if(compareString(comptag->Value(), "network"))
                    {
                        Network net;
                        TiXmlElement* element;
                        if((element = (TiXmlElement*) comptag->FirstChild("ip4")))
                            net.setIP4(parser->parseText(element->GetText()).c_str());
                        if((element = (TiXmlElement*) comptag->FirstChild("ip6")))
                            net.setIP6(parser->parseText(element->GetText()).c_str());
                        if((element = (TiXmlElement*) comptag->FirstChild("mac")))
                            net.setMAC(parser->parseText(element->GetText()).c_str());
                        module.addResource(net);
                        computer.setNetwork(net);
                    } // end of network tag

                    // yarp_port
                    if(compareString(comptag->Value(), "yarp_port"))
                    {
                        ResYarpPort yport;
                        auto* element = (TiXmlElement*) comptag->FirstChild("name");
                        if(element && element->GetText())
                        {
                            yport.setName(parser->parseText(element->GetText()).c_str());
                            yport.setPort(parser->parseText(element->GetText()).c_str());
                            computer.addPeripheral(yport);
                        }
                        else
                        {
                            OSTRINGSTREAM war;
                            war<<"yarp_port from "<<szFile<<" at line " <<comptag->Row()<<" has no name.";
                            logger->addWarning(war);
                        }
                    }

                    // gpu
                    if(compareString(comptag->Value(), "gpu"))
                    {
                        GPU gpu;
                        TiXmlElement* element;
                        if((element = (TiXmlElement*) comptag->FirstChild("name")))
                            gpu.setName(parser->parseText(element->GetText()).c_str());
                        if((element = (TiXmlElement*) comptag->FirstChild("capability")))
                            gpu.setCompCompatibility(parser->parseText(element->GetText()).c_str());
                        if((element = (TiXmlElement*) comptag->FirstChild("cores")))
                            gpu.setCores((size_t)atoi(parser->parseText(element->GetText()).c_str()));
                        if((element = (TiXmlElement*) comptag->FirstChild("frequency")))
                            gpu.setFrequency(atof(parser->parseText(element->GetText()).c_str()));
                        if((element = (TiXmlElement*) comptag->FirstChild("register_block")))
                            gpu.setResgisterPerBlock((size_t)atoi(parser->parseText(element->GetText()).c_str()));
                        if((element = (TiXmlElement*) comptag->FirstChild("thread_block")))
                            gpu.setThreadPerBlock((size_t)atoi(parser->parseText(element->GetText()).c_str()));
                        if((element = (TiXmlElement*) comptag->FirstChild("overlap")))
                        {
                            if(compareString(parser->parseText(element->GetText()).c_str(), "yes"))
                                gpu.setOverlap(true);
                            else
                                gpu.setOverlap(false);
                        }


                        // global memory
                        if(comptag->FirstChild("global_memory"))
                        {
                            TiXmlElement* element;
                            element = (TiXmlElement*) comptag->FirstChild("global_memory");
                            if((element = (TiXmlElement*) element->FirstChild("total_space")))
                                gpu.setGlobalMemory((Capacity)atol(parser->parseText(element->GetText()).c_str()));
                        } // end of global memory tag

                        // shared memory
                        if(comptag->FirstChild("shared_memory"))
                        {
                            TiXmlElement* element;
                            element = (TiXmlElement*) comptag->FirstChild("shared_memory");
                            if((element = (TiXmlElement*) element->FirstChild("total_space")))
                                gpu.setSharedMemory((Capacity)atol(parser->parseText(element->GetText()).c_str()));
                        } // end of shared memory tag

                        // constant memory
                        if(comptag->FirstChild("constant_memory"))
                        {
                            TiXmlElement* element;
                            element = (TiXmlElement*) comptag->FirstChild("constant_memory");
                            if((element = (TiXmlElement*) element->FirstChild("total_space")))
                                gpu.setConstantMemory((Capacity)atol(parser->parseText(element->GetText()).c_str()));
                        } // end of shared memory tag
                        computer.addPeripheral(gpu);
                    } // end of gpu tag
                } // end of computer tag loop
                module.addResource(computer);
            } //end of if computer tag
        }// end of dependecnies tag

    return &module;
}
Exemple #24
0
void ModuleWindow::updateWidget()
{
    Module* m_pModule = ModuleWindow::m_pModule;
    m_refTreeModel->clear();

    Gtk::TreeModel::Row row;
    Gtk::TreeModel::Row childrow;
    Gtk::TreeModel::Row cchildrow;

    row = *(m_refTreeModel->append());
    row[m_Columns.m_col_name] = "Name";
    row[m_Columns.m_col_value] = m_pModule->getName();

    row = *(m_refTreeModel->append());
    row[m_Columns.m_col_name] = "Version";
    row[m_Columns.m_col_value] = m_pModule->getVersion();

    row = *(m_refTreeModel->append());
    row[m_Columns.m_col_name] = "Description";
    row[m_Columns.m_col_value] = m_pModule->getDescription();

    row = *(m_refTreeModel->append());
    row[m_Columns.m_col_name] = "Parameters";
    row[m_Columns.m_col_value] = "";
    for(int i=0; i<m_pModule->argumentCount(); i++)
    {
        childrow = *(m_refTreeModel->append(row.children()));
        childrow[m_Columns.m_col_name] = m_pModule->getArgumentAt(i).getParam();
        childrow[m_Columns.m_col_value] = m_pModule->getArgumentAt(i).getDescription();
    }

    row = *(m_refTreeModel->append());
    row[m_Columns.m_col_name] = "Authors";
    row[m_Columns.m_col_value] = "";
    for(int i=0; i<m_pModule->authorCount(); i++)
    {
        childrow = *(m_refTreeModel->append(row.children()));
        childrow[m_Columns.m_col_name] = m_pModule->getAuthorAt(i).getName();
        childrow[m_Columns.m_col_value] = m_pModule->getAuthorAt(i).getEmail();
    }

    row = *(m_refTreeModel->append());
    row[m_Columns.m_col_name] = "Inputs";
    row[m_Columns.m_col_value] = "";
    for(int i=0; i<m_pModule->inputCount(); i++)
    {
        InputData in = m_pModule->getInputAt(i);

        childrow = *(m_refTreeModel->append(row.children()));
        childrow[m_Columns.m_col_name] = "Type";
        childrow[m_Columns.m_col_value] = in.getName();

        cchildrow = *(m_refTreeModel->append(childrow.children()));
        cchildrow[m_Columns.m_col_name] = "Port";
        cchildrow[m_Columns.m_col_value] = in.getPort();

        cchildrow = *(m_refTreeModel->append(childrow.children()));
        cchildrow[m_Columns.m_col_name] = "Description";
        cchildrow[m_Columns.m_col_value] = in.getDescription();

        childrow = *(m_refTreeModel->append(childrow.children()));
        childrow[m_Columns.m_col_name] = "Required";
        childrow[m_Columns.m_col_value] = (in.isRequired())?"Yes":"No";
    }

    row = *(m_refTreeModel->append());
    row[m_Columns.m_col_name] = "Outputs";
    row[m_Columns.m_col_value] = "";
    for(int i=0; i<m_pModule->outputCount(); i++)
    {
        OutputData out = m_pModule->getOutputAt(i);

        childrow = *(m_refTreeModel->append(row.children()));
        childrow[m_Columns.m_col_name] = "Type";
        childrow[m_Columns.m_col_value] = out.getName();

        cchildrow = *(m_refTreeModel->append(childrow.children()));
        cchildrow[m_Columns.m_col_name] = "Port";
        cchildrow[m_Columns.m_col_value] = out.getPort();

        cchildrow = *(m_refTreeModel->append(childrow.children()));
        cchildrow[m_Columns.m_col_name] = "Description";
        cchildrow[m_Columns.m_col_value] = out.getDescription();
    }

}
void ApplicationPropertyWindow::updateApplication(const char* item, const char* value)
{
    if(strcmp(item, "Prefix") == 0)
    {
        m_pManager->getKnowledgeBase()->setApplicationPrefix(m_pApplication, value);

        Application* mainApplication = m_pManager->getKnowledgeBase()->getApplication();
        for(int i=0; i<m_pApplication->sucCount(); i++)
        {
             Module* module = dynamic_cast<Module*>(m_pApplication->getLinkAt(i).to());
             if(module)
             {
                for(int j=0; j<module->outputCount(); j++)
                {
                    OutputData *output = &module->getOutputAt(j);

                    for(int i=0; i<mainApplication->connectionCount(); i++)
                    {
                        Connection con = mainApplication->getConnectionAt(i);
                        string strOldFrom = con.from();
                        Connection updatedCon = con;
                        if(con.getCorOutputData() && (con.getCorOutputData() == output))
                        {
                            string strFrom = string(module->getPrefix()) + string(output->getPort());
                            updatedCon.setFrom(strFrom.c_str());
                            m_pManager->getKnowledgeBase()->updateConnectionOfApplication(mainApplication,
                                                        con, updatedCon);
                            // updating arrow's connection
                            ArrowModel* arrow = dynamic_cast<ArrowModel*>(con.getModel());
                            if(arrow)
                            {
                                arrow->setConnection(updatedCon);
                                // updating excitatory links from other connections
                                Glib::RefPtr<PortArbitratorModel> arbPort = Glib::RefPtr<PortArbitratorModel>::cast_dynamic(arrow->getDestination());
                                if(arbPort)
                                    arbPort->updateExcitation(arrow, strOldFrom.c_str(), strFrom.c_str());
                            }
                        }
                    }
                }

                for(int j=0; j<module->inputCount(); j++)
                {
                    InputData *input = &module->getInputAt(j);

                    for(int i=0; i<mainApplication->connectionCount(); i++)
                    {
                        Connection con = mainApplication->getConnectionAt(i);
                        Connection updatedCon = con;
                        if(con.getCorInputData() && (con.getCorInputData() == input))
                        {
                            string strTo = string(module->getPrefix()) + string(input->getPort());
                            updatedCon.setTo(strTo.c_str());
                            m_pManager->getKnowledgeBase()->updateConnectionOfApplication(mainApplication,
                                                        con, updatedCon);
                            // updating arrow's connection
                            if(dynamic_cast<ArrowModel*>(con.getModel()))
                                dynamic_cast<ArrowModel*>(con.getModel())->setConnection(updatedCon);
                        }
                    }
                }
            } // end of if(module)
        } // end of for
    }
}
nsEventStatus
APZCTreeManagerChild::ReceiveInputEvent(
    InputData& aEvent,
    ScrollableLayerGuid* aOutTargetGuid,
    uint64_t* aOutInputBlockId)
{
  switch (aEvent.mInputType) {
  case MULTITOUCH_INPUT: {
    MultiTouchInput& event = aEvent.AsMultiTouchInput();
    MultiTouchInput processedEvent;

    nsEventStatus res;
    SendReceiveMultiTouchInputEvent(event,
                                    &res,
                                    &processedEvent,
                                    aOutTargetGuid,
                                    aOutInputBlockId);

    event = processedEvent;
    return res;
  }
  case MOUSE_INPUT: {
    MouseInput& event = aEvent.AsMouseInput();
    MouseInput processedEvent;

    nsEventStatus res;
    SendReceiveMouseInputEvent(event,
                               &res,
                               &processedEvent,
                               aOutTargetGuid,
                               aOutInputBlockId);

    event = processedEvent;
    return res;
  }
  case PANGESTURE_INPUT: {
    PanGestureInput& event = aEvent.AsPanGestureInput();
    PanGestureInput processedEvent;

    nsEventStatus res;
    SendReceivePanGestureInputEvent(event,
                                    &res,
                                    &processedEvent,
                                    aOutTargetGuid,
                                    aOutInputBlockId);

    event = processedEvent;
    return res;
  }
  case PINCHGESTURE_INPUT: {
    PinchGestureInput& event = aEvent.AsPinchGestureInput();
    PinchGestureInput processedEvent;

    nsEventStatus res;
    SendReceivePinchGestureInputEvent(event,
                                      &res,
                                      &processedEvent,
                                      aOutTargetGuid,
                                      aOutInputBlockId);

    event = processedEvent;
    return res;
  }
  case TAPGESTURE_INPUT: {
    TapGestureInput& event = aEvent.AsTapGestureInput();
    TapGestureInput processedEvent;

    nsEventStatus res;
    SendReceiveTapGestureInputEvent(event,
                                    &res,
                                    &processedEvent,
                                    aOutTargetGuid,
                                    aOutInputBlockId);

    event = processedEvent;
    return res;
  }
  case SCROLLWHEEL_INPUT: {
    ScrollWheelInput& event = aEvent.AsScrollWheelInput();
    ScrollWheelInput processedEvent;

    nsEventStatus res;
    SendReceiveScrollWheelInputEvent(event,
                                     &res,
                                     &processedEvent,
                                     aOutTargetGuid,
                                     aOutInputBlockId);

    event = processedEvent;
    return res;
  }
  default: {
    MOZ_ASSERT_UNREACHABLE("Invalid InputData type.");
    return nsEventStatus_eConsumeNoDefault;
  }
  }
}
Exemple #27
0
void MDDAGClassifier::printConfusionMatrix(const string& dataFileName, const string& shypFileName)
{
    InputData* pData = loadInputData(dataFileName, shypFileName);

    if (_verbose > 0)
        cout << "Loading strong hypothesis..." << flush;

    // The class that loads the weak hypotheses
    UnSerialization us;

    // Where to put the weak hypotheses
    vector<BaseLearner*> weakHypotheses;

    // loads them
    us.loadHypotheses(shypFileName, weakHypotheses, pData);

    // where the results go
    vector< ExampleResults* > results;

    if (_verbose > 0)
        cout << "Classifying..." << flush;

    // get the results
    computeResults( pData, weakHypotheses, results, (int)weakHypotheses.size());

    const int numClasses = pData->getNumClasses();
    const int numExamples = pData->getNumExamples();

    if (_verbose > 0)
        cout << "Done!" << endl;

    const int colSize = 7;

    if (_verbose > 0)
    {
        cout << "Raw Confusion Matrix:\n";
        cout << setw(colSize) << "Truth       ";

        for (int l = 0; l < numClasses; ++l)
            cout << setw(colSize) << nor_utils::getAlphanumeric(l);

        cout << "\nClassification\n";

        for (int l = 0; l < numClasses; ++l)
        {
            vector<int> winnerCount(numClasses, 0);
            for (int i = 0; i < numExamples; ++i)
            {
                if ( pData->hasPositiveLabel(i, l) )
                    ++winnerCount[ results[i]->getWinner().first ];
            }

            // class
            cout << setw(colSize) << "           " << nor_utils::getAlphanumeric(l);

            for (int j = 0; j < numClasses; ++j)
                cout << setw(colSize) << winnerCount[j];

            cout << endl;
        }

    }

    cout << "\nMatrix Key:\n";

    // Print the legend
    for (int l = 0; l < numClasses; ++l)
        cout << setw(5) << nor_utils::getAlphanumeric(l) << ": " <<
             pData->getClassMap().getNameFromIdx(l) << "\n";

    // delete the input data file
    if (pData)
        delete pData;

    vector<ExampleResults*>::iterator it;
    for (it = results.begin(); it != results.end(); ++it)
        delete (*it);
}
Exemple #28
0
void MDDAGClassifier::run(const string& dataFileName, const string& shypFileName,
                          int numIterations, const string& outResFileName, int numRanksEnclosed)
{
    InputData* pData = loadInputData(dataFileName, shypFileName);

    if (_verbose > 0)
        cout << "Loading strong hypothesis..." << flush;

    // The class that loads the weak hypotheses
    UnSerialization us;

    // Where to put the weak hypotheses
    vector<BaseLearner*> weakHypotheses;

    // loads them
    us.loadHypotheses(shypFileName, weakHypotheses, pData);

    // where the results go
    vector< ExampleResults* > results;

    if (_verbose > 0)
        cout << "Classifying..." << flush;

    // get the results
    computeResults( pData, weakHypotheses, results, numIterations );

    const int numClasses = pData->getNumClasses();

    if (_verbose > 0)
    {
        // well.. if verbose = 0 no results are displayed! :)
        cout << "Done!" << endl;

        vector< vector<float> > rankedError(numRanksEnclosed);

        // Get the per-class error for the numRanksEnclosed-th ranks
        for (int i = 0; i < numRanksEnclosed; ++i)
            getClassError( pData, results, rankedError[i], i );

        // output it
        cout << endl;
        cout << "Error Summary" << endl;
        cout << "=============" << endl;

        for ( int l = 0; l < numClasses; ++l )
        {
            // first rank (winner): rankedError[0]
            cout << "Class '" << pData->getClassMap().getNameFromIdx(l) << "': "
                 << setprecision(4) << rankedError[0][l] * 100 << "%";

            // output the others on its side
            if (numRanksEnclosed > 1 && _verbose > 1)
            {
                cout << " (";
                for (int i = 1; i < numRanksEnclosed; ++i)
                    cout << " " << i+1 << ":[" << setprecision(4) << rankedError[i][l] * 100 << "%]";
                cout << " )";
            }

            cout << endl;
        }

        // the overall error
        cout << "\n--> Overall Error: "
             << setprecision(4) << getOverallError(pData, results, 0) * 100 << "%";

        // output the others on its side
        if (numRanksEnclosed > 1 && _verbose > 1)
        {
            cout << " (";
            for (int i = 1; i < numRanksEnclosed; ++i)
                cout << " " << i+1 << ":[" << setprecision(4) << getOverallError(pData, results, i) * 100 << "%]";
            cout << " )";
        }

        cout << endl;

    } // verbose


    // If asked output the results
    if ( !outResFileName.empty() )
    {
        const int numExamples = pData->getNumExamples();
        ofstream outRes(outResFileName.c_str());

        outRes << "Instance" << '\t' << "Forecast" << '\t' << "Labels" << '\n';

        string exampleName;

        for (int i = 0; i < numExamples; ++i)
        {
            // output the name if it exists, otherwise the number
            // of the example
            exampleName = pData->getExampleName(i);
            if ( exampleName.empty() )
                outRes << i << '\t';
            else
                outRes << exampleName << '\t';

            // output the predicted class
            outRes << pData->getClassMap().getNameFromIdx( results[i]->getWinner().first ) << '\t';

            outRes << '|';

            vector<Label>& labels = pData->getLabels(i);
            for (vector<Label>::iterator lIt=labels.begin(); lIt != labels.end(); ++lIt) {
                if (lIt->y>0)
                {
                    outRes << ' ' << pData->getClassMap().getNameFromIdx(lIt->idx);
                }
            }

            outRes << endl;
        }

        if (_verbose > 0)
            cout << "\nPredictions written on file <" << outResFileName << ">!" << endl;

    }


    // delete the input data file
    if (pData)
        delete pData;

    vector<ExampleResults*>::iterator it;
    for (it = results.begin(); it != results.end(); ++it)
        delete (*it);
}
Exemple #29
0
void MDDAGClassifier::saveLikelihoods(const string& dataFileName, const string& shypFileName,
                                      const string& outFileName, int numIterations)
{
    InputData* pData = loadInputData(dataFileName, shypFileName);

    if (_verbose > 0)
        cout << "Loading strong hypothesis..." << flush;

    // The class that loads the weak hypotheses
    UnSerialization us;

    // Where to put the weak hypotheses
    vector<BaseLearner*> weakHypotheses;

    // loads them
    us.loadHypotheses(shypFileName, weakHypotheses, pData);

    // where the results go
    vector< ExampleResults* > results;

    if (_verbose > 0)
        cout << "Classifying..." << flush;

    const int numClasses = pData->getNumClasses();
    const int numExamples = pData->getNumExamples();


    ofstream outFile(outFileName.c_str());
    string exampleName;

    if (_verbose > 0)
        cout << "Output likelihoods..." << flush;

    // get the results
    /////////////////////////////////////////////////////////////////////
    // computeResults( pData, weakHypotheses, results, numIterations );
    assert( !weakHypotheses.empty() );

    // Initialize the output info
    OutputInfo* pOutInfo = NULL;

    if ( !_outputInfoFile.empty() )
        pOutInfo = new OutputInfo(_outputInfoFile, "err");

    // Creating the results structures. See file Structures.h for the
    // PointResults structure
    results.clear();
    results.reserve(numExamples);
    for (int i = 0; i < numExamples; ++i)
        results.push_back( new ExampleResults(i, numClasses) );

    // sum votes for classes
    vector< AlphaReal > votesForExamples( numClasses );
    vector< AlphaReal > expVotesForExamples( numClasses );

    // iterator over all the weak hypotheses
    vector<BaseLearner*>::const_iterator whyIt;
    int t;

    pOutInfo->initialize( pData );

    // for every feature: 1..T
    for (whyIt = weakHypotheses.begin(), t = 0;
            whyIt != weakHypotheses.end() && t < numIterations; ++whyIt, ++t)
    {
        BaseLearner* currWeakHyp = *whyIt;
        AlphaReal alpha = currWeakHyp->getAlpha();

        // for every point
        for (int i = 0; i < numExamples; ++i)
        {
            // a reference for clarity and speed
            vector<AlphaReal>& currVotesVector = results[i]->getVotesVector();

            // for every class
            for (int l = 0; l < numClasses; ++l)
                currVotesVector[l] += alpha * currWeakHyp->classify(pData, i, l);
        }

        // if needed output the step-by-step information
        if ( pOutInfo )
        {
            pOutInfo->outputIteration(t);
            pOutInfo->outputCustom(pData, currWeakHyp);

            // Margins and edge requires an update of the weight,
            // therefore I keep them out for the moment
            //outInfo.outputMargins(pData, currWeakHyp);
            //outInfo.outputEdge(pData, currWeakHyp);

            pOutInfo->endLine();

        } // for (int i = 0; i < numExamples; ++i)
        // calculate likelihoods from votes

        fill( votesForExamples.begin(), votesForExamples.end(), 0.0 );
        AlphaReal lLambda = 0.0;
        for (int i = 0; i < numExamples; ++i)
        {
            // a reference for clarity and speed
            vector<AlphaReal>& currVotesVector = results[i]->getVotesVector();
            AlphaReal sumExp = 0.0;
            // for every class
            for (int l = 0; l < numClasses; ++l)
            {
                expVotesForExamples[l] =  exp( currVotesVector[l] ) ;
                sumExp += expVotesForExamples[l];
            }

            if ( sumExp > numeric_limits<AlphaReal>::epsilon() )
            {
                for (int l = 0; l < numClasses; ++l)
                {
                    expVotesForExamples[l] /= sumExp;
                }
            }

            Example ex = pData->getExample( results[i]->getIdx() );
            vector<Label> labs = ex.getLabels();
            AlphaReal m = numeric_limits<AlphaReal>::infinity();
            for (int l = 0; l < numClasses; ++l)
            {
                if ( labs[l].y > 0 )
                {
                    if ( expVotesForExamples[l] > numeric_limits<AlphaReal>::epsilon() )
                    {
                        AlphaReal logVal = log( expVotesForExamples[l] );

                        if ( logVal != m ) {
                            lLambda += ( ( 1.0/(AlphaReal)numExamples ) * logVal );
                        }
                    }
                }
            }


        }


        outFile << t << "\t" << lLambda ;
        outFile << '\n';

        outFile.flush();
    }

    if (pOutInfo)
        delete pOutInfo;

    // computeResults( pData, weakHypotheses, results, numIterations );
    ///////////////////////////////////////////////////////////////////////////////////


    /*
     for (int i = 0; i < numExamples; ++i)
     {
     // output the name if it exists, otherwise the number
     // of the example
     exampleName = pData->getExampleName(i);
     if ( !exampleName.empty() )
     outFile << exampleName << ',';

     // output the posteriors
     outFile << results[i]->getVotesVector()[0];
     for (int l = 1; l < numClasses; ++l)
     outFile << ',' << results[i]->getVotesVector()[l];
     outFile << '\n';
     }
     */

    if (_verbose > 0)
        cout << "Done!" << endl;

    if (_verbose > 1)
    {
        cout << "\nClass order (You can change it in the header of the data file):" << endl;
        for (int l = 0; l < numClasses; ++l)
            cout << "- " << pData->getClassMap().getNameFromIdx(l) << endl;
    }

    // delete the input data file
    if (pData)
        delete pData;

    vector<ExampleResults*>::iterator it;
    for (it = results.begin(); it != results.end(); ++it)
        delete (*it);
}
Exemple #30
0
void MDDAGClassifier::saveCalibratedPosteriors(const string& dataFileName, const string& shypFileName,
        const string& outFileName, int numIterations)
{
    InputData* pData = loadInputData(dataFileName, shypFileName);

    if (_verbose > 0)
        cout << "Loading strong hypothesis..." << flush;

    // The class that loads the weak hypotheses
    UnSerialization us;

    // Where to put the weak hypotheses
    vector<BaseLearner*> weakHypotheses;

    // loads them
    us.loadHypotheses(shypFileName, weakHypotheses, pData);

    // where the results go
    vector< ExampleResults* > results;

    if (_verbose > 0)
        cout << "Classifying..." << flush;

    // get the results
    computeResults( pData, weakHypotheses, results, numIterations );

    const int numClasses = pData->getNumClasses();
    const int numExamples = pData->getNumExamples();

    ofstream outFile(outFileName.c_str());
    string exampleName;

    if (_verbose > 0)
        cout << "Output posteriors..." << flush;

    for (int i = 0; i < numExamples; ++i)
    {
        // output the name if it exists, otherwise the number
        // of the example
        exampleName = pData->getExampleName(i);
        if ( !exampleName.empty() )
            outFile << exampleName << ',';

        // output the posteriors
        outFile << results[i]->getVotesVector()[0];
        for (int l = 1; l < numClasses; ++l)
            outFile << ',' << results[i]->getVotesVector()[l];
        outFile << '\n';
    }

    if (_verbose > 0)
        cout << "Done!" << endl;

    if (_verbose > 1)
    {
        cout << "\nClass order (You can change it in the header of the data file):" << endl;
        for (int l = 0; l < numClasses; ++l)
            cout << "- " << pData->getClassMap().getNameFromIdx(l) << endl;
    }

    // delete the input data file
    if (pData)
        delete pData;

    vector<ExampleResults*>::iterator it;
    for (it = results.begin(); it != results.end(); ++it)
        delete (*it);
}