Ejemplo n.º 1
0
/**
 * @brief Evaluates streamState at @ s[i]
 *
 * The streamState can be @a code, @2 quote1, @a quote2, or @a
 * comment. The method examines the elements just before and after to
 * determine if state should change, based upon c89 comment syntax.
 * @param[in] s Current line
 * @param[in] i Current point on line
 */
void evalStateAt(char s[], int i)
{
    int len = strLen(s);
    char iMinus4 = (i > 3) ? s[i-4] : '\0';
    char iMinus3 = (i > 2) ? s[i-3] : '\0';
    char iMinus2 = (i > 1) ? s[i-2] : '\0';
    char iMinus1 = (i > 0) ? s[i-1] : '\0';
    char iZed = s[i];
    char iPlus1 = (i+1 < len) ? s[i+1] : '\0';
    char iPlus2 = (i+2 < len) ? s[i+2] : '\0';
    char iPlus3 = (i+3 < len) ? s[i+3] : '\0';
    switch (state) {
        case code:
            if (iZed == '/' && iPlus1 == '*')
                state = comment;
            else if ((iZed == '\'' && iPlus1 == '\\' && iPlus3 == '\'') ||
                     (iZed == '\'' && iPlus2 == '\''))
                state = quote1;
            else if (iZed == '\"')
                state = quote2;
            else if (i == 0 && iZed == '#' && isInclude(s))
                state = include;
            break;
        case include:
            if (iZed == '\n')
                state = code;
            break;
        case quote1:
            if ((iMinus4 == '\'' && iMinus3 == '\\' && iMinus1 == '\'') ||
                (iMinus3 == '\'' && iMinus1 == '\''))
                state = code;
            break;
        case quote2:
            if (iMinus1 == '\"')
                state = code;
            break;
        case comment:
            if (iMinus2 == '*' && iMinus1 == '/')
                state = code;
            break;
        default:
            break;
    }
}
static void preprocess(char *srcFileName){
  char *buf;
  //fprintf(stderr, "pp \"%s\"\n", srcFileName);
  //init srcFile
  if(findProcessedFileName(srcFileName)){
    fprintf(output, "#include \"%s\"\n", srcFileName);
    return;
  }
  SrcFile *src = malloc(sizeof(SrcFile));
  if(src == NULL){
    fprintf(stderr, "error: cannot alloc structure\n");
  }
  src->filename = srcFileName;
  src->dir = getDir(srcFileName);
  src->curLine = 1;
  src->numCommentedLFs = 0;
  src->numEscapedLFs = 0;
  src->inStrLiteral = 0;
  src->file = fopen(src->filename, "r");
  if(src->file == NULL){
    fprintf(stderr, "error: cannot open \"%s\"\n", src->filename);
    exit(EXIT_FAILURE);
  }
  pushSrcFileName(srcFileName);

  while( (buf = getLine(src)) != NULL){
    int includeKind;
    if(isPragma(buf)){
      char *pragmaStr = getPragmaStr(buf);

      if( startsWithWord(pragmaStr, "omp") || startsWithWord(pragmaStr, "acc")
	  || (enableXMP && startsWithWord(pragmaStr, "xmp")) ){
	fprintf(output, "%s(%s)\n", PRAGMA_NAME1, pragmaStr);
      }else{
	fprintf(output, "%s\n", buf);
      }
    }else if( (includeKind = isInclude(buf)) ){
      char *includeFileName = getIncludeFileName(buf);
      char *includeFilePath = findIncludeFilePath(src->dir, includeFileName, includeKind);
      if(includeFilePath != NULL){
	//get pos
	fgetpos(src->file, &(src->pos));
	//close current file
	fclose(src->file);

	//output filename
	fprintf(output, "# 1 \"%s\"\n", includeFilePath);
	preprocess(includeFilePath);
	fprintf(output, "# %d \"%s\"\n", src->curLine , src->filename);

	//reopen
	src->file = fopen(src->filename, "r");
	if(src->file == NULL){
	  fprintf(stderr, "error: cannot reopen \"%s\"\n", src->filename);
	  exit(EXIT_FAILURE);
	}

	//set pos
	fsetpos(src->file, &(src->pos));
	free(includeFilePath);
      }else{
	if(includeKind == USER_INCLUDE){
	  fprintf(output, "#include \"%s\"\n", includeFileName);
	}else{
	  fprintf(output, "#include <%s>\n", includeFileName);
	}
      }
      free(includeFileName);
    }else{
      fprintf(output, "%s\n", buf);
    }
    if(buf != staticBuffer){
      free(buf);
    }
  }
  
  popSrcFileName();

  fclose(src->file);
  free(src->dir);
  free(src);
}
Ejemplo n.º 3
0
void routerFinder::advGreedySoluation(int vertexNum,int edgeNum,int (*edgeData)[4],
                        int setSizeRec,int *includeSet,
                        int& total_cost,std::vector<int>& final_path)
{
    int (*reverse_edge)[4] = new int[edgeNum][4];

    for (int i = 0; i < edgeNum; ++i) {
        reverse_edge[i][0] = edgeData[i][0];
        reverse_edge[i][1] = edgeData[i][2];
        reverse_edge[i][2] = edgeData[i][1];
        reverse_edge[i][3] = edgeData[i][3];
    }

    std::vector<vertex> verteix = loadVerterix(vertexNum);
    loadEdge(edgeData, edgeNum, verteix);

     std::vector<vertex> reverse_verteix = loadVerterix(vertexNum);
    loadEdge(reverse_edge, edgeNum, reverse_verteix);

    bool visited[600];
    bool reverse_visited[600];
    int parent[20];
    int reverse_parent[20];
    for (int i = 0; i < vertexNum; ++i) {
        visited[i] = false;
        reverse_visited[i] = false;
        parent[i] = -1;
        reverse_parent[i] = -1;
    }

    int setSize = setSizeRec;
    int sourceID = includeSet[0];
    int meetID = includeSet[setSizeRec-1];


    node* distance;
    node* reverse_dist;
    float judge[52] = {0};

    int maxIndex = 0;
    int selectIndex = 0;
    float maxRec = INF;
    float k_value = 0.6;

    std::vector<int> temp_path;

    for (;setSize > 1; --setSize) {

        distance = dijkstra(sourceID,verteix,includeSet,setSize,visited,parent);
        reverse_dist = dijkstra(meetID,reverse_verteix,includeSet,setSize,reverse_visited,reverse_parent);

        if (setSize == 2) {
            selectIndex = meetID;
        }else{
            for (int i = 1; i < setSize-1; ++i) {
                judge[i] = k_value*distance[includeSet[i]].w+(1-k_value)*reverse_dist[includeSet[i]].w;
                if (maxRec > judge[i]) {
                    maxRec = judge[i];
                    maxIndex = i;
                    selectIndex = includeSet[i];
                }
            }
        }

        //把选中的点交换到末尾去,includeSet的逆顺就是 需要通过的点的通过顺序
        int tempx = includeSet[setSize-2];
        includeSet[setSize-2] = includeSet[maxIndex];
        includeSet[maxIndex] = tempx;

        tempx = includeSet[setSize-1];
        includeSet[setSize-1] = includeSet[setSize-2];
        includeSet[setSize-2] = tempx;

        for (int i = 0; i < setSizeRec; ++i) {
             std::cout << includeSet[i] << "|";
        }
         std::cout <<  std::endl;

        int tempIndex = selectIndex;
        //update isSelected
        while (tempIndex != -1) {
            //到达某个选中的点可能回通过另外选中的点
            int pindex = isInclude(parent[tempIndex],includeSet,setSize);
            if( pindex != 0 ){

                int tempx = includeSet[setSize-3];
                includeSet[setSize-3] = includeSet[pindex];
                includeSet[pindex] = tempx;

                tempx = includeSet[setSize-2];
                includeSet[setSize-2] = includeSet[setSize-3];
                includeSet[setSize-3] = tempx;

                --setSize;
            }
            verteix[tempIndex].isSelected = true;
            reverse_verteix[tempIndex].isSelected = true;

            //纪录结果
            temp_path.push_back(tempIndex);

            tempIndex = parent[tempIndex];

        }

        int tempPathSize = temp_path.size();
        for (int i = temp_path.size()-1; i > 0; --i) {
            final_path.push_back(temp_path[i]);
        }
        if (setSize == 2) {
            final_path.push_back(temp_path[0]);
        }
        temp_path.clear();

        //重置visited parent maxRec
        for (int i = 0; i < vertexNum; ++i) {
            visited[i] = false;
            reverse_visited[i] = false;
            parent[i] = -1;
            reverse_parent[i] = -1;
        }
        total_cost += distance[selectIndex].w;

        //无解处理
        if (total_cost >= INF) {

        }
        maxRec = INF;

        //更改起点再计算
        sourceID = selectIndex;

    }

    //    for (int i = setSizeRec-1; i >= 0; --i) {
    //        cout << includeSet[i] << "|";
    //    }
    std:: cout <<  std::endl;
    for (int i = 0; i < final_path.size(); ++i) {
         std::cout << final_path[i] << "|";
    }
     std::cout <<  std::endl;
     std::cout << total_cost;
}
Ejemplo n.º 4
0
//This function may be recruse called
void plainconf::loadConfFile(const char *path)
{
    logToMem(LOG_LEVEL_INFO, "start parsing file %s", path);

    int type = checkFiletype(path);

    if (type == 0)
        return;

    else if (type == 2)
        loadDirectory(path, NULL);

    else if (type == 3)
    {
        AutoStr2 prefixPath = path;
        const char *p = strrchr(path, '/');

        if (p)
            prefixPath.setStr(path, p - path);

        struct stat sb;

        //removed the wildchar filename, should be a directory if exist
        if (stat(prefixPath.c_str(), &sb) == -1)
        {
            logToMem(LOG_LEVEL_ERR, "LoadConfFile error 1, path:%s directory:%s",
                     path, prefixPath.c_str());
            return ;
        }

        if ((sb.st_mode & S_IFMT) != S_IFDIR)
        {
            logToMem(LOG_LEVEL_ERR, "LoadConfFile error 2, path:%s directory:%s",
                     path, prefixPath.c_str());
            return ;
        }

        loadDirectory(prefixPath.c_str(), p + 1);
    }

    else //existed file
    {
        //gModuleList.push_back();
        //XmlNode *xmlNode = new XmlNode;
        FILE *fp = fopen(path, "r");

        if (fp == NULL)
        {
            logToMem(LOG_LEVEL_ERR, "Cannot open configuration file: %s", path);
            return;
        }


        const int MAX_LINE_LENGTH = 8192;
        char sLine[MAX_LINE_LENGTH];
        char *p;
        char sLines[MAX_LINE_LENGTH] = {0};
        int lineNumber = 0;
        const int MAX_MULLINE_SIGN_LENGTH = 128;
        char sMultiLineModeSign[MAX_MULLINE_SIGN_LENGTH] = {0};
        size_t  nMultiLineModeSignLen = 0;  //>0 is mulline mode

        while (fgets(sLine, MAX_LINE_LENGTH, fp), !feof(fp))
        {
            ++lineNumber;
            p = sLine;

            if (nMultiLineModeSignLen)
            {
                //Check if reach the END of the milline mode
                size_t len = 0;
                const char *pLineStart = getStrNoSpace(p, len);

                if (len == nMultiLineModeSignLen &&
                    strncasecmp(pLineStart, sMultiLineModeSign, nMultiLineModeSignLen) == 0)
                {
                    nMultiLineModeSignLen = 0;
                    removeSpace(sLines,
                                1);   //Remove the last \r\n so that if it is one line, it will still be one line
                    parseLine(path, lineNumber, sLines);
                    sLines[0] = 0x00;
                }
                else
                    strcat(sLines, p);

                continue;
            }

            removeSpace(p, 0);
            removeSpace(p, 1);

            if (!isValidline(p))
                continue;

            AutoStr2 pathInclude;

            if (isInclude(p, pathInclude))
            {
                char achBuf[512] = {0};
                getIncludeFile(pathInclude.c_str(), achBuf);
                loadConfFile(achBuf);
            }
            else
            {
                nMultiLineModeSignLen = checkMultiLineMode(p, sMultiLineModeSign,
                                        MAX_MULLINE_SIGN_LENGTH);

                if (nMultiLineModeSignLen > 0)
                    strncat(sLines, p, strlen(p) - (3 + nMultiLineModeSignLen));
                //need to continue
                else if (isChunkedLine(p))
                {
                    strncat(sLines, p, strlen(p) - 1);
                    //strcatchr(sLines, ' ', MAX_LINE_LENGTH); //add a space at the end of the line which has a '\\'
                }

                else
                {
                    strcat(sLines, p);
                    parseLine(path, lineNumber, sLines);
                    sLines[0] = 0x00;
                }
            }
        }

        fclose(fp);

        //Parsed, check in it
        checkInFile(path);
    }
}
Ejemplo n.º 5
0
void FindSeeds(int targetCount, int *candidates, int candidatesNum)
{
	int i, j, top1;
	int topk = seedNumber;
	int *seedSet = malloc(seedNumber * sizeof(int));
	bool best = true;
	double diffusionTime, time_spent;
	extern clock_t begin, end;

	double **distToTargets = malloc(targetCount * sizeof(double *));	// create a 2D array distToTargets[eachTarget][totalvertices]
	double *firstRound = malloc(candidatesNum * sizeof(double));		// store max time of each candidate to targets
	double *targets = malloc(targetCount * sizeof(double));				// the minimum time to arrive each target
	double *eachReduce = malloc(candidatesNum * sizeof(double));		// store each candidate to target causes the diffusion time less

	/*	initialize targets array, distToTargets array, firstRound array, eachReduce array and seedSet */
	for(i = 0 ; i < targetCount ; i++){
		targets[i] = DBL_MAX;
		distToTargets[i] = malloc(totalvertices * sizeof(double));
		for(j = 0 ; j < totalvertices ; j++)
			distToTargets[i][j] = -1;
	}
	for(i = 0 ; i < candidatesNum ; i++){
		firstRound[i] = -1;
		eachReduce[i] = 0;
	}
	memset(seedSet, -1, seedNumber * sizeof(int));

	FILE *f = write_file("result");
	if(f == NULL) err("Couldn't open file.\n");
	fprintf(f, "number of candidates : %d\n", candidatesNum);
	fprintf(f, "number of targets : %d\n", targetCount);

	/* Get the first seed. Then get the next seed by recording the marginal gain of each candidate. */
	int count = 0;
	while(topk > 0){
		InitializeEachReduce(eachReduce, candidatesNum);
		best = true;														// check the diffusion time has improved or not

		for(i = 0 ; i < targetCount ; i++){
			distToTargets[i] = BoundDist[i];								// the time of each node to the target
			for(j = 0 ; j < candidatesNum ; j++){
				if(count == 0){
					firstRound[j] = MAX(firstRound[j], distToTargets[i][candidates[j]]);
//					printf("node %d to node %d : %f\n", candidates[j], targetUsers[i], distToTargets[i][candidates[j]]);
					best = false;
				}
				/* check the candidate is blocked by seed or not. */
				else if(isBlock(targetUsers[i], candidates[j], seedSet)){
					continue;
				}
				/* if node has contribution of diffusion time, then store it into "eachReduce" to get the most one. */
				else if(!isInclude(candidates[j], seedSet) && distToTargets[i][candidates[j]]<targets[i]){
					eachReduce[j] += targets[i]-distToTargets[i][candidates[j]];
					best = false;
//					printf("\ncandidates %d has contribution!\n\n", candidates[j]);
				}
			}
		}

		// if there is no node has contribution , then quit the algorithm.
		if(best){
			printf("No more seeds !!\nIt's the shortest diffusion time !!\n");
			break;
		}
		if(count == 0)
			top1 = BubbleSort(firstRound, false, candidatesNum);
		else
			top1 = BubbleSort(eachReduce, true, candidatesNum);

		top1 = candidates[top1];
		seedSet[count++] = top1;											// store top1 to seed set
		diffusionTime = 0.0;
//		printf("top %d is %d\n", count, top1);
		for(i = 0 ; i < targetCount ; i++){
			if(distToTargets[i][top1] < targets[i])
				targets[i] = distToTargets[i][top1];
			diffusionTime = MAX(diffusionTime, targets[i]);
//			printf("top %d to node %d is : %f\n\n", count, targetUsers[i], targets[i]);
		}

		topk--;

		fprintf(f, "top%d", count);
		fprintf(f, "\nseed set are : \n\t");
		for(i = 0 ; i < count ; i++)
			fprintf(f, "%d ", seedSet[i]);
		fprintf(f, "\nDiffusion Time is %lf\n", diffusionTime);

		end = clock();
		time_spent = (double)(end-begin) / CLOCKS_PER_SEC;
		fprintf(f, "execution time : %f\n", time_spent);
	}

	printf("targets are : \n");
	for(i = 0 ; i < targetCount ; i++)
		printf("%d ", targetUsers[i]);
	printf("number of targets : %d\n", targetCount);
	printf("\nseed set are : \n");
	for(i = 0 ; i < count ; i++)
		printf("%d ", seedSet[i]);
	printf("\nDiffusion Time is %lf\n", diffusionTime);

	fclose(f);
}