Beispiel #1
0
	sequence_in_t C_method(const unique_ptr<DFSM>& fsm, int extraStates) {
		RETURN_IF_UNREDUCED(fsm, "FSMtesting::C_method", sequence_in_t());
		auto E = getAdaptiveDistinguishingSet(fsm);
		if (E.empty()) {
			return sequence_in_t();
		}
		auto N = fsm->getNumberOfStates();
		auto P = fsm->getNumberOfInputs();
		
		/* // Example from simao2009checking
		E.clear();
		E[0].push_back(0);
		E[0].push_back(1);
		E[0].push_back(0);
		E[1].push_back(0);
		E[1].push_back(1);
		E[1].push_back(0);
		E[2].push_back(0);
		E[2].push_back(1);
		E[3].push_back(0);
		E[3].push_back(1);
		E[4].push_back(0);
		E[4].push_back(1);
		//*/
		vector<vector<bool>> verifiedTransition(N);
		vector<input_t> verifiedState(N, P);
		vector<shared_ptr<ver_seq_t>> verSeq(N);
		for (state_t i = 0; i < N; i++) {
			verifiedTransition[i].resize(P, false);
			verSeq[i] = make_shared<ver_seq_t>();
		}
		if (fsm->isOutputState()) {
			for (state_t i = 0; i < N; i++) {
				sequence_in_t seq;
				for (const auto& input : E[i]) {
					if (input == STOUT_INPUT) continue;
					seq.push_back(input);
				}
				E[i].swap(seq);
			}
		}
		output_t outputState = (fsm->isOutputState()) ? fsm->getOutput(0, STOUT_INPUT) : DEFAULT_OUTPUT;
		output_t outputTransition;
		vector<unique_ptr<TestNodeC>> cs;
		cs.emplace_back(make_unique<TestNodeC>(STOUT_INPUT, DEFAULT_OUTPUT, 0, outputState));
		state_t currState = 0;
		for (const auto& input : E[0]) {
			auto nextState = fsm->getNextState(currState, input);
			outputState = (fsm->isOutputState()) ? fsm->getOutput(nextState, STOUT_INPUT) : DEFAULT_OUTPUT;
			outputTransition = (fsm->isOutputTransition()) ? fsm->getOutput(currState, input) : DEFAULT_OUTPUT;
			cs.emplace_back(make_unique<TestNodeC>(input, outputTransition, nextState, outputState));
			currState = nextState;
		}
		vector<vector<seq_len_t>> confirmedNodes(N);
		confirmedNodes[0].push_back(0);
		queue<seq_len_t> newlyConfirmed;
		seq_len_t counter = N * fsm->getNumberOfInputs();
		seq_len_t currIdx = 1;
		seq_len_t lastConfIdx = 0;
		currState = 0;

		while (counter > 0) {
			//getCS(CS, fsm->isOutputState());
			//printf("%u/%u %u %s\n", currIdx, cs.size(), lastConfIdx, FSMmodel::getInSequenceAsString(CS).c_str());
			if (cs.back()->confirmed) {
				currIdx = seq_len_t(cs.size());
				lastConfIdx = currIdx - 1;
			}
			if (currIdx < cs.size()) {
				if (!cs[currIdx]->confirmed) {
					auto nextState = cs[currIdx]->state;
					auto nextInput = E[nextState].begin();
					if (equalSeqPart(currIdx + 1, nextInput, E[nextState].end(), cs)) {
						currState = cs.back()->state;
						for (; nextInput != E[cs[currIdx]->state].end(); nextInput++) {
							nextState = fsm->getNextState(currState, *nextInput);
							outputState = (fsm->isOutputState()) ? fsm->getOutput(nextState, STOUT_INPUT) : DEFAULT_OUTPUT;
							outputTransition = (fsm->isOutputTransition()) ? fsm->getOutput(currState, *nextInput) : DEFAULT_OUTPUT;
							cs.emplace_back(make_unique<TestNodeC>(*nextInput, outputTransition, nextState, outputState));
							currState = nextState;
						}
						cs[currIdx]->confirmed = true;
						newlyConfirmed.emplace(currIdx);
						update(lastConfIdx, cs, newlyConfirmed, verifiedTransition, verifiedState, verSeq, confirmedNodes, counter);
						processNewlyConfirmed(cs, newlyConfirmed, verifiedTransition, verifiedState, verSeq, confirmedNodes, counter,
							currIdx, lastConfIdx);
					}
				}
				else {
					lastConfIdx = currIdx;
				}
				currIdx++;
			}
			else if (verifiedState[cs.back()->state] > 0) {
				currState = cs.back()->state;
				for (input_t input = 0; input < P; input++) {
					if (!verifiedTransition[currState][input]) {
						auto nextState = fsm->getNextState(currState, input);
						outputState = (fsm->isOutputState()) ? fsm->getOutput(nextState, STOUT_INPUT) : DEFAULT_OUTPUT;
						outputTransition = (fsm->isOutputTransition()) ? fsm->getOutput(currState, input) : DEFAULT_OUTPUT;
						cs.emplace_back(make_unique<TestNodeC>(input, outputTransition, nextState, outputState));
						cs.back()->confirmed = true;
						newlyConfirmed.emplace(currIdx); //cs.size()-1

						sequence_in_t seqE(E[nextState]);
						// output-confirmed
						if (!E[currState].empty() && input == E[currState].front()) {
							sequence_in_t suf(E[currState]);
							suf.pop_front();
							auto outSuf = fsm->getOutputAlongPath(nextState, suf);
							auto outE = fsm->getOutputAlongPath(nextState, E[nextState]);
							//printf("(%d,%d,%d) %s/%s %s\n", currState, input, nextState,
							//      FSMmodel::getInSequenceAsString(suf).c_str(),
							//    FSMmodel::getOutSequenceAsString(outSuf).c_str(),
							//  FSMmodel::getOutSequenceAsString(outE).c_str());
							seq_len_t lenE = 0; //outE.size();
							for (state_t i = 0; i < N; i++) {
								if (i != nextState) {
									auto outSufI = fsm->getOutputAlongPath(i, suf);
									auto osl = equalLength(outSuf.begin(), outSufI.begin(), seq_len_t(outSuf.size()));
									if (osl != outSuf.size()) {
										bool outConfirmed = false;
										auto sufIt = suf.begin();
										osl++;
										while (osl-- > 0) sufIt++;
										for (auto& cnIdx : confirmedNodes[i]) {
											auto sufBeginIt = suf.begin();
											if (equalSeqPart(cnIdx + 1, sufBeginIt, sufIt, cs)) {
												outConfirmed = true;
												break;
											}
										}

										if (outConfirmed) {
											continue;
											/*
											outConfirmed = false;
											for (auto cnIdx : confirmedNodes[nextState]) {
											auto sufBeginIt = suf.begin();
											if (equalSeqPart(cnIdx, sufBeginIt, sufIt)) {
											outConfirmed = true;
											break;
											}
											}
											if (outConfirmed) {
											continue;
											}
											*/
										}
									}
									auto outI = fsm->getOutputAlongPath(i, E[nextState]);
									auto oel = 1 + equalLength(outE.begin(), outI.begin(), seq_len_t(outI.size()));
									//printf("%s/%s x %s %d %d-%d\n", 
									//      FSMmodel::getInSequenceAsString(E[nextState]).c_str(),
									//    FSMmodel::getOutSequenceAsString(outE).c_str(),
									//  FSMmodel::getOutSequenceAsString(outI).c_str(),
									//oel, lenE, outE.size());
									if (oel > lenE) {
										lenE = oel;
										if (lenE == outE.size()) {// entire E is needed
											break;
										}
									}
								}
							}
							// adjust E
							for (; lenE < outE.size(); lenE++) {
								seqE.pop_back();
							}
						}
						currState = nextState;
						for (const auto& input : seqE) {
							nextState = fsm->getNextState(currState, input);
							outputState = (fsm->isOutputState()) ? fsm->getOutput(nextState, STOUT_INPUT) : DEFAULT_OUTPUT;
							outputTransition = (fsm->isOutputTransition()) ? fsm->getOutput(currState, input) : DEFAULT_OUTPUT;
							cs.emplace_back(make_unique<TestNodeC>(input, outputTransition, nextState, outputState));
							currState = nextState;
						}
						update(currIdx - 1, cs, newlyConfirmed, verifiedTransition, verifiedState, verSeq, confirmedNodes, counter);
						processNewlyConfirmed(cs, newlyConfirmed, verifiedTransition, verifiedState, verSeq, confirmedNodes, counter,
							currIdx, lastConfIdx);
						break;
					}
				}
			}
			else {// find unverified transition
				vector<bool> covered(N, false);
				list<pair<state_t, sequence_in_t>> fifo;
				currState = cs.back()->state;
				covered[currState] = true;
				fifo.emplace_back(currState, sequence_in_t());
				while (!fifo.empty()) {
					auto current = move(fifo.front());
					fifo.pop_front();
					for (input_t input = 0; input < P; input++) {
						auto nextState = fsm->getNextState(current.first, input);
						if (nextState == WRONG_STATE) continue;
						if (verifiedState[nextState] > 0) {
							for (auto nextInput = current.second.begin(); nextInput != current.second.end(); nextInput++) {
								nextState = fsm->getNextState(currState, *nextInput);
								outputState = (fsm->isOutputState()) ? fsm->getOutput(nextState, STOUT_INPUT) : DEFAULT_OUTPUT;
								outputTransition = (fsm->isOutputTransition()) ? fsm->getOutput(currState, *nextInput) : DEFAULT_OUTPUT;
								cs.emplace_back(make_unique<TestNodeC>(*nextInput, outputTransition, nextState, outputState));
								cs.back()->confirmed = true;
								currState = nextState;
							}
							nextState = fsm->getNextState(currState, input);
							outputState = (fsm->isOutputState()) ? fsm->getOutput(nextState, STOUT_INPUT) : DEFAULT_OUTPUT;
							outputTransition = (fsm->isOutputTransition()) ? fsm->getOutput(currState, input) : DEFAULT_OUTPUT;
							lastConfIdx = seq_len_t(cs.size());
							cs.emplace_back(make_unique<TestNodeC>(input, outputTransition, nextState, outputState));
							cs.back()->confirmed = true;
							currIdx = seq_len_t(cs.size());
							fifo.clear();
							break;
						}
						if (!covered[nextState]) {
							covered[nextState] = true;
							sequence_in_t newPath(current.second);
							newPath.push_back(input);
							fifo.emplace_back(nextState, move(newPath));
						}
					}
				}

			}
		}
		return getCS(fsm->isOutputState(), cs);
	}
bool ompl::geometric::LightningRetrieveRepair::findBestPath(const base::State *startState, const base::State *goalState, ompl::base::PlannerDataPtr &chosenPath)
{
    OMPL_INFORM("LightningRetrieveRepair: Found %d similar paths. Filtering", nearestPaths_.size());

    // Filter down to just 1 chosen path
    ompl::base::PlannerDataPtr bestPath = nearestPaths_.front();
    std::size_t bestPathScore = std::numeric_limits<std::size_t>::max();

    // Track which path has the shortest distance
    std::vector<double> distances(nearestPaths_.size(), 0);
    std::vector<bool> isReversed(nearestPaths_.size());

    assert(isReversed.size() == nearestPaths_.size());

    for (std::size_t pathID = 0; pathID < nearestPaths_.size(); ++pathID)
    {
        const ompl::base::PlannerDataPtr &currentPath = nearestPaths_[pathID];

        // Error check
        if (currentPath->numVertices() < 2) // needs at least a start and a goal
        {
            OMPL_ERROR("A path was recalled that somehow has less than 2 vertices, which shouldn't happen");
            return false;
        }

        const ompl::base::State *pathStartState = currentPath->getVertex(0).getState();
        const ompl::base::State *pathGoalState = currentPath->getVertex(currentPath->numVertices()-1).getState();

        double regularDistance  = si_->distance(startState,pathStartState) + si_->distance(goalState,pathGoalState);
        double reversedDistance = si_->distance(startState,pathGoalState) + si_->distance(goalState,pathStartState);

        // Check if path is reversed from normal [start->goal] direction and cache the distance
        if ( regularDistance > reversedDistance )
        {
            // The distance between starts and goals is less when in reverse
            isReversed[pathID] = true;
            distances[pathID] = reversedDistance;
            // We won't actually flip it until later to save memory operations and not alter our NN tree in the LightningDB
        }
        else
        {
            isReversed[pathID] = false;
            distances[pathID] = regularDistance;
        }

        std::size_t pathScore = 0; // the score

        // Check the validity between our start location and the path's start
        // TODO: this might bias the score to be worse for the little connecting segment
        if (!isReversed[pathID])
            pathScore += checkMotionScore(startState, pathStartState);
        else
            pathScore += checkMotionScore(startState, pathGoalState);

        // Score current path for validity
        std::size_t invalidStates = 0;
        for (std::size_t vertex_id = 0; vertex_id < currentPath->numVertices(); ++vertex_id)
        {
            // Check if the sampled points are valid
            if (!si_->isValid( currentPath->getVertex(vertex_id).getState()))
            {
                invalidStates++;
            }
        }
        // Track separate for debugging
        pathScore += invalidStates;

        // Check the validity between our goal location and the path's goal
        // TODO: this might bias the score to be worse for the little connecting segment
        if (!isReversed[pathID])
            pathScore += checkMotionScore( goalState, pathGoalState );
        else
            pathScore += checkMotionScore( goalState, pathStartState );

        // Factor in the distance between start/goal and our new start/goal
        OMPL_INFORM("LightningRetrieveRepair: Path %d | %d verticies | %d invalid | score %d | reversed: %s | distance: %f",
            int(pathID), currentPath->numVertices(), invalidStates, pathScore,
            isReversed[pathID] ? "true" : "false", distances[pathID]);

        // Check if we have a perfect score (0) and this is the shortest path (the first one)
        if (pathID == 0 && pathScore == 0)
        {
            OMPL_DEBUG("LightningRetrieveRepair:  --> The shortest path (path 0) has a perfect score (0), ending filtering early.");
            bestPathScore = pathScore;
            bestPath = currentPath;
            nearestPathsChosenID_ = pathID;
            break; // end the for loop
        }

        // Check if this is the best score we've seen so far
        if (pathScore < bestPathScore)
        {
            OMPL_DEBUG("LightningRetrieveRepair:  --> This path is the best we've seen so far. Previous best: %d", bestPathScore);
            bestPathScore = pathScore;
            bestPath = currentPath;
            nearestPathsChosenID_ = pathID;
        }
        // if the best score is the same as a previous one we've seen,
        // choose the one that has the shortest connecting component
        else if (pathScore == bestPathScore && distances[nearestPathsChosenID_] > distances[pathID])
        {
            // This new path is a shorter distance
            OMPL_DEBUG("LightningRetrieveRepair:  --> This path is as good as the best we've seen so far, but its path is shorter. Previous best score: %d from index %d",
                       bestPathScore, nearestPathsChosenID_);
            bestPathScore = pathScore;
            bestPath = currentPath;
            nearestPathsChosenID_ = pathID;
        }
        else
            OMPL_DEBUG("LightningRetrieveRepair:  --> Not best. Best score: %d from index %d", bestPathScore, nearestPathsChosenID_);
    }

    // Check if we have a solution
    if (!bestPath)
    {
        OMPL_ERROR("LightningRetrieveRepair: No best path found from k filtered paths");
        return false;
    }
    else if(!bestPath->numVertices() || bestPath->numVertices() == 1)
    {
        OMPL_ERROR("LightningRetrieveRepair: Only %d verticies found in PlannerData loaded from file. This is a bug.", bestPath->numVertices());
        return false;
    }

    // Reverse the path if necessary. We allocate memory for this so that we don't alter the database
    if (isReversed[nearestPathsChosenID_])
    {
        OMPL_DEBUG("LightningRetrieveRepair: Reversing planner data verticies count %d", bestPath->numVertices());
        ompl::base::PlannerDataPtr newPath(new ompl::base::PlannerData(si_));
        for (std::size_t i = bestPath->numVertices(); i > 0; --i) // size_t can't go negative so subtract 1 instead
        {
            newPath->addVertex( bestPath->getVertex(i-1) );
        }
        // Set result
        chosenPath = newPath;
    }
    else
    {
        // Set result
        chosenPath = bestPath;
    }
    OMPL_DEBUG("LightningRetrieveRepair: Done Filtering\n");

    return true;
}
Beispiel #3
0
void SourceView::showFile(std::wstring path, int proclinenum, const std::vector<double> &linecounts)
{
	currentfile = path;

	// Don't show error messages with CPP highlighting
	setPlainMode();
	if (path == "[hint KiFastSystemCallRet]")
	{
		updateText(
			" Hint: KiFastSystemCallRet often means the thread was waiting for something else to finish.\n"
			" \n"
			" Possible causes might be disk I/O, waiting for an event, or maybe just calling Sleep().\n"
			);
		return;
	}

	if (path == "" || path == "[unknown]")
	{
		updateText("[ No source file available for this location. ]");
		return;
	}


	FILE *file = _wfopen(path.c_str(),L"r, ccs=UNICODE");
	if(!file)
	{
		wchar_t *crtSub = L"\\crt\\src\\";
		wchar_t *crt = wcsstr((wchar_t *)path.c_str(), crtSub);
		if(crt) {
			for(size_t i=0;i<msDevPaths.size();i++) {
				std::wstring newPath(msDevPaths[i]);
				newPath += crt+wcslen(crtSub);
				path = newPath;
				file = _wfopen(path.c_str(),L"r");
				if(file)
					break;
			}
		}
	}

	if(!file)
	{
		updateText(std::wstring("[ Could not open file '" + path + "'. ]").c_str());
		return;
	}

	std::wstring displaytext;
	wchar_t line[1024];
	while(fgetws(line,countof(line),file))
	{
		displaytext += line;
	}

	fclose(file);

	setCppMode();

	updateText(displaytext);

	// Show line counts in margin
	for (int line=1,lineCount=linecounts.size(); line<lineCount; ++line)
	{
		if (linecounts[line])
		{
			wchar_t currCount[32];
			swprintf(currCount, countof(currCount), L"%0.2fs ", linecounts[line]);
			MarginSetText (line-1, currCount);
			MarginSetStyle(line-1, MARGIN_TEXT_STYLE);
		}
	}

	SetYCaretPolicy(wxSTC_CARET_STRICT|wxSTC_CARET_EVEN, 0);
	GotoLine(proclinenum);
	SetYCaretPolicy(wxSTC_CARET_EVEN, 0);

	MarkerDefine(1, wxSTC_MARK_BACKGROUND, wxNullColour, *wxYELLOW);
	MarkerAdd(proclinenum-1, 1);
}
CDGPath *getTopPaths(CDGContext * ctx, CDGNode * root, int numberOfPaths) {
  CDGPath *pathHead = NULL;
  CDGNode *path;
  CDGPath *currPath;
  CDGNode *node;
  int branch;
  Stack *changedNodes = stackNew(sizeof(CDGNode *));
  Stack *changedBranches = stackNew(sizeof(int));
  while (numberOfPaths--) {
    path = getTopPath(root, changedNodes, changedBranches);
    if (NULL == path)
      break;
    if (NULL == pathHead) {
      pathHead = setPathNode(newPath(), path);
      currPath = pathHead;
    } else {
      setNextPath(currPath, setPathNode(newPath(), path));
      currPath = getNextPath(currPath);
    }
    updateCDG(root, 0);
  }
  while (!stackIsEmpty(changedNodes) && !stackIsEmpty(changedBranches)) {
    stackPop(changedNodes, &node);
    stackPop(changedBranches, &branch);
    if (isLeaf(node)) {
      setScore(node, 1);
    } else {
      if (branch)
	setBranchInfo(getID(node), 0, getBranchInfo(getID(node), 0));
      else
	setBranchInfo(getID(node), getBranchInfo(getID(node), 1), 0);
    }

  }
  updateCDG(root, 0);
  stackFree(changedNodes);
  stackFree(changedBranches);

  /* Updating context */
  (*ctx).topPaths = pathHead;

  /* Ensuring atleast one path was found */
  if (NULL == pathHead)
    return NULL;

  /* Creating list of nodes from complicated path form */
  CDGPath *outPathHead = NULL;
  currPath = NULL;
  path = NULL;
  while (NULL != pathHead) {
    path = getPathNode(pathHead);
    if (NULL == outPathHead) {
      outPathHead = setPathNode(newPath(), pathToList(path));
      currPath = outPathHead;
    } else {
      setNextPath(currPath, setPathNode(newPath(), pathToList(path)));
      currPath = getNextPath(currPath);
    }
    pathHead = getNextPath(pathHead);
  }

  return outPathHead;
}
Beispiel #5
0
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
bool POSIXFilesystemNode::getChildren(AbstractFSList& myList, ListMode mode,
                                      bool hidden) const
{
  assert(_isDirectory);

  DIR *dirp = opendir(_path.c_str());
  struct dirent *dp;

  if (dirp == NULL)
    return false;

  // loop over dir entries using readdir
  while ((dp = readdir(dirp)) != NULL)
  {
    // Skip 'invisible' files if necessary
    if (dp->d_name[0] == '.' && !hidden)
      continue;

    // Skip '.' and '..' to avoid cycles
    if ((dp->d_name[0] == '.' && dp->d_name[1] == 0) || (dp->d_name[0] == '.' && dp->d_name[1] == '.'))
      continue;

    string newPath(_path);
    if (newPath.length() > 0 && newPath[newPath.length()-1] != '/')
      newPath += '/';
    newPath += dp->d_name;

    POSIXFilesystemNode entry(newPath, false);

#if defined(SYSTEM_NOT_SUPPORTING_D_TYPE)
    /* TODO: d_type is not part of POSIX, so it might not be supported
     * on some of our targets. For those systems where it isn't supported,
     * add this #elif case, which tries to use stat() instead.
     *
     * The d_type method is used to avoid costly recurrent stat() calls in big
     * directories.
     */
    entry.setFlags();
#else
    if (dp->d_type == DT_UNKNOWN)
    {
      // Fall back to stat()
      entry.setFlags();
    }
    else
    {
      entry._isValid = (dp->d_type == DT_DIR) || (dp->d_type == DT_REG) || (dp->d_type == DT_LNK);
      if (dp->d_type == DT_LNK)
      {
        struct stat st;
        if (stat(entry._path.c_str(), &st) == 0)
          entry._isDirectory = S_ISDIR(st.st_mode);
        else
          entry._isDirectory = false;
      }
      else
        entry._isDirectory = (dp->d_type == DT_DIR);
    }
#endif

    // Skip files that are invalid for some reason (e.g. because we couldn't
    // properly stat them).
    if (!entry._isValid)
      continue;

    // Honor the chosen mode
    if ((mode == FilesystemNode::kListFilesOnly && entry._isDirectory) ||
        (mode == FilesystemNode::kListDirectoriesOnly && !entry._isDirectory))
      continue;

    if (entry._isDirectory)
      entry._path += "/";

    myList.push_back(new POSIXFilesystemNode(entry));
  }
  closedir(dirp);

  return true;
}
Beispiel #6
0
	Path Path::reverse() const
	{
		Path newPath(_end, _start);

		return newPath;
	}
static jboolean java_io_File_renameToImpl(JNIEnv* env, jobject, jbyteArray oldPathBytes, jbyteArray newPathBytes) {
    ScopedByteArray oldPath(env, oldPathBytes);
    ScopedByteArray newPath(env, newPathBytes);
    return (rename(&oldPath[0], &newPath[0]) == 0);
}
bool
VR_VoiceBoxVoiceTag::SaveVoiceTag(std::string &strAddGrammar, const std::string &deviceAddress, VoiceTagInfo voiceTagPara, const std::string tempData, bool update)
{
    VR_LOGD_FUNC();

    VR_LOG("deviceAddress : %s", deviceAddress.c_str());
    if (deviceAddress.empty()) {
        return false;
    }
    pugi::xml_document contactDoc;
    contactDoc.load_string(voiceTagPara.contactMsg.c_str());
    pugi::xml_node contactNode = contactDoc.select_node((std::string("//") + VR_VOICETAG_CONTACT_NODE).c_str()).node();
    // std::string name = contactNode.attribute("name").as_string();
    VR_LOG("pcmfile path : %s", voiceTagPara.pcmPath.c_str());

    std::string dirPath = VR_VOICETAG_REC_PATH;
    VR_ConfigureIF::Instance()->makeDir(dirPath);
    dirPath = dirPath + deviceAddress;
    VR_ConfigureIF::Instance()->makeDir(dirPath);
    VR_LOG("pcmfile path : %s", dirPath.c_str());
    std::string relativePath(dirPath + "/" + voiceTagPara.voiceTagID + ".wav");
    VR_LOG("relativePath %s", relativePath.c_str());
    VR_VoiceBoxDataStorage storage;
    std::string newPath(VR_ConfigureIF::Instance()->getUsrPath() + VR_VOICETAG_REC_PATH + deviceAddress + "/" + voiceTagPara.voiceTagID + ".wav");
    VR_LOG("pcmfile newPath path : %s", newPath.c_str());
    if ("false" == tempData) {
        if (VR_ConfigureIF::Instance()->isFileExist(relativePath)) {
            bool isRemoved = VR_ConfigureIF::Instance()->removeFile(relativePath);
            VR_LOG("Remove File: %s", isRemoved ? "true" : "false");
        }
        VR_LOG("moveFile");
        VR_ConfigureIF::Instance()->moveFile("voiceTag.wav", relativePath.c_str());
    }

    // create voicetag value
    pugi::xml_document voiceTagValueDoc;
    voiceTagValueDoc.load_string("");
    pugi::xml_node voiceTagValueNode = voiceTagValueDoc.append_child((std::string(VR_VOICETAG_ID_PREFIX) + voiceTagPara.voiceTagID).c_str());
    if ("true" == tempData) {
        newPath = voiceTagPara.pcmPath;
    }
    VR_LOG("pcmfile newPath path : %s", newPath.c_str());
    voiceTagValueNode.append_child(VR_VOICETAG_PCM_PATH_NODE).text().set(newPath.c_str());
    voiceTagValueNode.append_child(VR_VOICETAG_PHONEME_NODE).text().set(voiceTagPara.phoneme.c_str());
    voiceTagValueNode.append_child(VR_VOICETAG_TEMPDATA).text().set(tempData.c_str());
    voiceTagValueNode.append_copy(contactNode);

    std::ostringstream osss;
    voiceTagValueNode.print(osss);
    VR_LOG("voiceTag Value: %s", osss.str().c_str());

    // save voicetag
    int key = VR_VoiceTagIDManager::getInstance()->getVoiceTagStorageKey(deviceAddress);
    VR_LOG("key: %d", key);
    std::string deviceVoiceTagValueStr;

    storage.GetValue(key, deviceVoiceTagValueStr);

    pugi::xml_document deviceVoiceTagValueDoc;
    deviceVoiceTagValueDoc.load_string(deviceVoiceTagValueStr.c_str());
    if ("true" == tempData) {
        pugi::xml_node VoicetagIdNode = deviceVoiceTagValueDoc.select_node((std::string("//") + VR_VOICETAG_ID_PREFIX + voiceTagPara.voiceTagID).c_str()).node();
        if (VoicetagIdNode) {
            std::string name = VoicetagIdNode.name();
            VR_LOG("name :%s", name.c_str());
            deviceVoiceTagValueDoc.remove_child((std::string(VR_VOICETAG_ID_PREFIX) + voiceTagPara.voiceTagID).c_str());
        }
    }
    if (update) {
        VR_LOG("update");
        deviceVoiceTagValueDoc.remove_child((std::string(VR_VOICETAG_ID_PREFIX) + voiceTagPara.voiceTagID).c_str());
    }
    if ("false" == tempData) {
        VR_LOG("remove_child");
        deviceVoiceTagValueDoc.remove_child((std::string(VR_VOICETAG_ID_PREFIX) + "-2").c_str());
    }
    deviceVoiceTagValueDoc.append_copy(voiceTagValueNode);

    std::ostringstream oss;
    deviceVoiceTagValueDoc.print(oss);
    deviceVoiceTagValueStr = oss.str();
    VR_LOG("VoiceTag Value: %s", deviceVoiceTagValueStr.c_str());
    storage.PutValue(key, deviceVoiceTagValueStr);
    if ("false" == tempData) {
        VR_VoiceTagIDManager::getInstance()->saveVoiceTagID(voiceTagPara.voiceTagID);
    }
    VR_LOG("Save VoiceTag End");

    deviceVoiceTagValueStr.clear();
    storage.GetValue(key, deviceVoiceTagValueStr);
    VR_LOG("VoiceTag Value: %s", deviceVoiceTagValueStr.c_str());
    if ("false" == tempData) {
        std::string strFullName = contactNode.attribute("name").as_string();
        VR_LOG("FullName: %s", strFullName.c_str());
        strAddGrammar = "<grammar_voicetag agent=\"phone\" op=\"addGrammar\"><fullName>";
        strAddGrammar.append(strFullName);
        strAddGrammar.append("</fullName><phoneme>");
        strAddGrammar.append(voiceTagPara.phoneme);
        strAddGrammar.append("</phoneme></grammar_voicetag>");
        VR_LOG("strAddGrammar : %s", strAddGrammar.c_str());
    }
    return true;
}
std::string
ExpandUserPath(const std::string &path)
{
    std::string newPath(path);

    if(path[0] == '~')
    {
        char username[256];
        int  i;

        // Find the user name portion of the path, ie ~user
        for (i = 1; isalnum(path[i]); i++)
        {
            username[i - 1] = path[i];
        }
        username[i - 1] = '\0';

#if defined(_WIN32)
        if(i == 1)
        {
            // User just specified '~', get the current user name.
            DWORD s = 256;
            GetUserName(username, &s);
        }
        // Get 'home' directory
        char *profDir = new char[MAX_PATH];
        DWORD size = 256;
        GetProfilesDirectory(profDir, &size);
        std::string homeDir(profDir);
        delete [] profDir;    

        // Append the rest of the path to the home directory.
        std::string restOfPath(path.substr(i, path.length() - i + 1));
        newPath = homeDir + "\\" + std::string(username) + restOfPath;
#else
        // Check if the user specified '~' or '~name'.
        struct passwd *users_passwd_entry = NULL;
        if (i == 1)
        {
            // User just specified '~', get /etc/passwd entry
            users_passwd_entry = getpwuid(getuid());
        }
        else
        {
            // User specified '~name', get /etc/passwd entry
            users_passwd_entry = getpwnam(username);
        }

        // Now that we have a passwd entry, validate it.
        if (users_passwd_entry == NULL)
        {
            // Did not specify a valid user name.  Do nothing. 
            return newPath;
        }
        if (users_passwd_entry->pw_dir == NULL)
        {
            // Passwd entry is invalid.  Do nothing.
            return newPath;
        }

        // Append the rest of the path to the home directory.
        std::string restOfPath(path.substr(i, path.length() - i + 1));
        newPath = std::string(users_passwd_entry->pw_dir) + restOfPath;
#endif
    }

    return newPath;
}