Exemplo n.º 1
0
void my_printn(const char* str1, int val, const char* str2)
{
    char szT[32];
    my_print(str1);
    sprintf(szT, "%x", val);
    my_print(szT);
    my_print(str2);
}
Exemplo n.º 2
0
void FONSEModel::printHyperParameters()
{
	for (unsigned i = 0u; i < getNumSynthesisRateCategories(); i++)
	{
		my_print("stdDevSynthesisRate posterior estimate for selection category %: %\n", i, getStdDevSynthesisRate(i));
	}
	my_print("\t current stdDevSynthesisRate proposal width: %\n", getCurrentStdDevSynthesisRateProposalWidth());
}
Exemplo n.º 3
0
int main (int argc, char *argv[])
{
    char* hello="hello\n";
	my_print(hello);
	my_print("%p\n",hello);
	my_print("hello's addr is :%p\n",&hello);
	printf("main's addr is :%p\n",&main);
	printf("my_print's addr is :%p\n",&my_print);
	printf("printf's addr is :%p\n",&printf);
    return 0;
}
Exemplo n.º 4
0
void readFileByPath(FILE* file, char* name, char* originPath, char* path, int offset, RootDir* rd, BOOL* found){

	int RD_Size = sizeof(RootDir);

	long point = ftell(file);
	fseek(file, offset, SEEK_SET);
	//printf("INpath:\n");
	//puts(path);
	//printf("\n");
	if(belongTo(path,originPath)){
		//printf("belongTo\n");
		do {
			memset(rd, 0, RD_Size);
			fread(rd, RD_Size, 1, file);
			if (isDir(rd)){
					int fst_Clus = rd->DIR_FstClus[0] + rd->DIR_FstClus[1] * 0x10;
					char* newPath = (char*)malloc(MAX);
					memset(newPath, 0, strlen(newPath));
					memcpy(newPath, path, strlen(path));
					RootDir oldRd;
					memcpy(&oldRd, rd, RD_Size);
					addToPath(newPath, rd->DIR_Name);
					readFileByPath(file,name,originPath, newPath, (fst_Clus * 0x200 + DATA_START), rd,found);
					memcpy(rd, &oldRd, RD_Size);
					free(newPath);
			}else{
				if (pathEquals(path,originPath)&&fileEquals(rd->DIR_Name,name)&&isValid(rd)){
					// printf("%s%s\n",path, rd->DIR_Name);
					int fatVal=rd->DIR_FstClus[0] + rd->DIR_FstClus[1] * 0x10;
					while(fatVal<0xFF8){
						readContent(file,fatVal);
						*found=TRUE;
						fatVal=getFATValue(file,fatVal);
						//printf("FATVAL:%3X\n",fatVal);
						if(fatVal==0xFF7){
							my_print("坏",1);
							my_print("簇",1);
							break;
						}
					}

					my_print("\n",1);
					return;
				}
			}
		}while(!isEmpty(rd));
	}
	fseek(file, point, SEEK_SET);

}
Exemplo n.º 5
0
void readContent(FILE* file,int fst_Clus){
	int offset=fst_Clus * 0x200 + DATA_START;
	//printf("clus[0]:%d,clus[1]:%d\n",clus[0],clus[1]);
	//printf("fst_clu:%d\n",fst_Clus);
	//printf("DATA_START:%6X\n",DATA_START);
	//printf("offset:%6X\n",offset);
	fseek(file, offset, SEEK_SET);
	
	char* content = (char* )malloc(BytsPerSec);  //暂存从簇中读出的数据   

	fread(content,1,BytsPerSec,file);
	
	int i=0;
	//change_color();
	while(TRUE){
		if(i>=BytsPerSec||content[i]=='\0'||content[i]==-1)
			break;
		//printf("!%2X",content[i]);
		my_print(content+i,1);
		//printf("A:%2X",content[i]);
		++i;	
	}
	//ret_color();
	//my_print("\n",1);

	free(content);
}
Exemplo n.º 6
0
int main()
{
	uval.a = 10;
	printf("v.a = %d, v.b = %d\n", uval.a, uval.b);
	return 0;
	double eps = 1e-8;
	double cella2 = 0.176;
	double pixel = 0.028;
	double cella2p = cella2 / ceil((cella2 - eps) / pixel);
	TRACE(cella2p, %f);
	int cella2n = (int)rint(cella2 / cella2p);
	TRACE(cella2n, %d);

	int ia = 10;
	TRACE(ia, %d);
	printf("size of one char in c:%d\n", sizeof('a'));
	char a = -127;
	printf("%#x\n", a);
	unsigned char i = -1;
	printf("%#x\n", i);
	printf("%d\n", i%256);
	return 0;
	char my_string[] = "hello there";
	
	my_print(my_string);
	my_print2(my_string);
}
Exemplo n.º 7
0
int check_village(struct Village *top)
{
   struct Results result = get_results(top);
   int answer = BOTS_RESULT_SUCCESSFUL;

   if (res_population != result.total_patients) answer = BOTS_RESULT_UNSUCCESSFUL;
   if (res_hospitals != result.hosps_number) answer = BOTS_RESULT_UNSUCCESSFUL;
   if (res_personnel != result.hosps_personnel) answer = BOTS_RESULT_UNSUCCESSFUL;
   if (res_checkin != result.total_hosps_v) answer = BOTS_RESULT_UNSUCCESSFUL;
   if (res_village != result.total_in_village) answer = BOTS_RESULT_UNSUCCESSFUL;
   if (res_waiting != result.total_waiting) answer = BOTS_RESULT_UNSUCCESSFUL;
   if (res_assess != result.total_assess) answer = BOTS_RESULT_UNSUCCESSFUL;
   if (res_inside != result.total_inside) answer = BOTS_RESULT_UNSUCCESSFUL;

   bots_message("\n");
   bots_message("Sim. Variables      = expect / result\n");
   bots_message("Total population    = %6d / %6d people\n", (int)   res_population, (int) result.total_patients);
   bots_message("Hospitals           = %6d / %6d people\n", (int)   res_hospitals, (int) result.hosps_number);
   bots_message("Personnel           = %6d / %6d people\n", (int)   res_personnel, (int) result.hosps_personnel);
   bots_message("Check-in's          = %6d / %6d people\n", (int)   res_checkin, (int) result.total_hosps_v);
   bots_message("In Villages         = %6d / %6d people\n", (int)   res_village, (int) result.total_in_village);
   bots_message("In Waiting List     = %6d / %6d people\n", (int)   res_waiting, (int) result.total_waiting);
   bots_message("In Assess           = %6d / %6d people\n", (int)   res_assess, (int) result.total_assess);
   bots_message("Inside Hospital     = %6d / %6d people\n", (int)   res_inside, (int) result.total_inside);
   bots_message("Average Stay        = %6f / %6f u/time\n", (float) res_avg_stay,(float) result.total_time/result.total_patients);

   my_print(top);

   return answer;
}
Exemplo n.º 8
0
//输出函数
void myprint(char str[]){
        int length;
        length=strlen(str);
        
	my_print(str,length);
	printf("length: %d   %s",length,str);
}
Exemplo n.º 9
0
void printPath(char* path){
	int i = 0;
	change_color();
	char* p = "/";
	while (i < strlen(path)-1){
		if (path[i] != ' '){
			my_print(&path[i], 1);
		}
		if (i % 8 == 7){
			my_print(p, 1);
		}
		i++;
	}
	ret_color();

	my_print("\n",1);
}
Exemplo n.º 10
0
static DWORD cmd_on_receive_data( pcmd_backend_data local, HANDLE h) 
{
	DWORD nBytesRead;
	char lpszBuffer[256+1];
	char *readBuf = NULL;
	char* sendcmd = NULL;
	int readlen = 0;
	char * descmd = NULL;
	int deslen = 0;
	DWORD total = 0;
	DWORD byteleft = 0;


	if (!ReadFile(h, lpszBuffer, 256,
		&nBytesRead, NULL) || !nBytesRead)
	{
		if (GetLastError() == ERROR_BROKEN_PIPE)
			return ERROR_BROKEN_PIPE;			// pipe done - normal exit path.
	}
	// data on!
	WaitForSingleObject(local->m_hWriteEvent, INFINITE);
	do {
		if (nBytesRead)
		{
			lpszBuffer[nBytesRead] = '\0';
			my_print("[ondata]%x, %d", h, nBytesRead);
			readBuf = lpszBuffer;
			readlen = nBytesRead;
			deslen = readlen*2;
			descmd = smalloc(deslen);
			memset(descmd, 0, deslen);
			cmd_convert_to_cmd_format(readBuf, readlen, descmd, deslen);
			from_backend(local->frontend, 0, descmd, deslen);
			sfree(descmd);
		}

		if( !PeekNamedPipe(h, lpszBuffer, 256, &nBytesRead, &total, &byteleft) )
		{
			if (GetLastError() == ERROR_BROKEN_PIPE)
				return ERROR_BROKEN_PIPE;			// pipe done - normal exit path.
		}
		if( byteleft == 0 )
		{
			SetEvent(local->m_hWriteEvent);
			break;
		}

		if (!ReadFile(h, lpszBuffer, 256,
			&nBytesRead, NULL) || !nBytesRead)
		{
			if (GetLastError() == ERROR_BROKEN_PIPE)
				return ERROR_BROKEN_PIPE;			// pipe done - normal exit path.
		}
	}while(1);

	return ERROR_SUCCESS;
}
Exemplo n.º 11
0
void
heap_sort(int *a, int n) {
    int i;

    for (i=n/2-1; i>=0; i--) {
        heap_adjust(a, n, i);
    }
    my_print(a, n);

    for (i=n-1; i>0; i--) {
        a[i] = a[i]^a[0];
        a[0] = a[i]^a[0];
        a[i] = a[i]^a[0];

        heap_adjust(a, i, 0);
        my_print(a, n);
    }
}
Exemplo n.º 12
0
int main()
{

	my_print();
	printf("This is a test for include .c file\n");

	return 0;

}
Exemplo n.º 13
0
int main()
{
    freopen("out.txt","w",stdout);
    my_init();
    while(scanf("%s",op), strcmp(op,".EOP")){
        solve();
    }
    my_print();
    //system("pause");
    return 0;
}
Exemplo n.º 14
0
int main(int argc, const char *argv[])
{
    int i;
    int k;
    sscanf(argv[1],"%d",&k);
    //格式转换 还可以转换其他的形式,现在转换成int型
    for(i=0;i<k;i++){
    my_print(k,printf_1);
    printf(" %d\n",i+1);
    }
    return 0;
}
Exemplo n.º 15
0
void printFile(char* path, RootDir* rd){
	int i = 0;
	change_color();
	char* p = "/";
	while (i < strlen(path)){
		if (path[i] != ' '){
			my_print(&path[i], 1);
		}
		if (i % 8 == 7){
			my_print(p, 1);
		}
		i++;
	}
	ret_color();

	for (i = 0; i < 8; i++){
		if (rd->DIR_Name[i] == ' '){
			break;
		}
		my_print(&rd->DIR_Name[i], 1);
	}
	my_print(".", 1);
	for (i = 8; i < 11; i++){
		if (rd->DIR_Name[i] == ' '){
			break;
		}
		my_print(&rd->DIR_Name[i], 1);
	}
	my_print("\n",1);
}
Exemplo n.º 16
0
Arquivo: debug.c Projeto: 4179e1/misc
main ()

{

  char my_string[] = "hello there";



  my_print (my_string);

  my_print2 (my_string);

}
Exemplo n.º 17
0
int
main() {
    //int a[13] = {9, 4, 6, 2, 1, 7, 3, 12, 23, 5, 34, 8, 10};
    //int a[13] = {9, 4, 6, 2, 1, 7, 3, 9, 23, 5, 34, 8, 10};
    //int a[13] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};
    //int a[13] = {13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
    int a[2] = {1, 0};
    int b[13];
    int a_len = sizeof(a)/sizeof(a[0]);

    my_print(a, a_len);

    //bubble_sort(a, a_len);
    //insert_sort(a, a_len);
    //merge_sort(a, b, a_len);
    //fast_sort(a, 0, a_len-1);
    heap_sort(a, a_len);

    my_print(a, a_len);

    return 0;
}
Exemplo n.º 18
0
int main(int argc, char ** argv) {
    char buf [BUF_SIZE];
    char *delim = argv[1];
    for(int i = 0; i < argc - 2; ++i) {
        int fd;
        sscanf(argv[i + 2], "%d", &fd);
        int ret;
        while((ret = read(fd, buf, BUF_SIZE)) != 0) {
            if (ret == -1) {
                char str[] = "Error read";
                perror(str);
                return EXIT_FAILURE;
            } else {
                my_print(buf, ret);
           }
        }
        if (i < (argc - 3)) {
            my_print(delim, strlen(delim));
        }
    }

    return EXIT_FAILURE;
}
Exemplo n.º 19
0
void
bubble_sort(int *a, int n) {
    int i, j, temp;

    for (i=0; i<n; i++) {
        for (j=0; j<n-i; j++) {
            if (a[j] > a[j+1]) {
                temp = a[j];
                a[j] = a[j+1];
                a[j+1] = temp;
            }
        }
        my_print(a, n);
    }
}
Exemplo n.º 20
0
void
insert_sort(int *a, int n) {
    int i, j, temp;

    for (j=1; j<n; j++) {
        for (i=j; i>0; i--) {
            if (a[i-1] > a[i]) {
                temp = a[i-1];
                a[i-1] = a[i];
                a[i] = temp;
            }
        }
        my_print(a, n);
    }
}
Exemplo n.º 21
0
/*
 * Stupid Pico/Pilot/Pine!!!  They are assuming that the returned st_size
 * field from a stat() syscall for a directory is the actual size of the 
 * directory.  But Cygwin returns zero and they don't check for that.
 *
 * The unfortunate result is that a diretory stat() is _very_ expensive...
 */
static void get_dir_size(char *name, struct linux_stat *ls)
{
  DIR *dir;
  struct dirent *d;
  int size = 0;
    char file[MAX_PATH];
    change_path_to_relative(file, (char*)name);
  my_print("[ender]get dir size %s \n", file);
  dir = opendir(file);
  if (NULL == dir) return;
  
  while (NULL != (d = readdir(dir))) {
    size += ROUND_UP(NAME_OFFSET(d) + strlen(d->d_name)+1);
  } 
  
  ls->st_size = size;
}
Exemplo n.º 22
0
int main(int argc,char *argv[])
{
    int i;
    char *buf = NULL;
    int argcount = 0;
    char arglist[100][256];
    char *arg[20];
    int pid;
    int stat_val;

    buf = (char *)malloc(256);
    while(1)
    {
        memset(buf,0,256);
        my_print();
  //      fflush(NULL);
        //处理输入参数的部分
        get_input(buf);
        for(i = 0;i < 100;i++)
        {
            arglist[i][0] = '\0';
        }
        argcount = 0;
        explain_input(buf,&argcount,arglist);
        for(i = 0;i < argcount;i++)
            arg[i] = &arglist[i][0];
        for(i = 0;i < argcount;i++)
            printf("%s ",arg[i]);
        if((pid = fork()) < 0)
        {
            perror("fork error");
            return 0;
        }
        switch(pid)
        {
            case 0:
                execvp(arg[0],arg);
                exit(0);
                break;
            default:
                if(waitpid(0,&stat_val,0) == -1)
                    perror("error");
        }
    }
    exit(0);
}
Exemplo n.º 23
0
void my_print(struct Village *village)
{
	struct Village *vlist;
	struct Patient *plist;

	if (village == NULL) return;

	/* Traverse village hierarchy (lower level first)*/
	vlist = village->forward;
	while(vlist) {
		my_print(vlist);
		vlist = vlist->next;
	}

	plist = village->population;

	while (plist != NULL) {
		printf("[pid:%d]",plist->id);
		plist = plist->forward; 
	}
	printf("[vid:%d]\n",village->id);

}
Exemplo n.º 24
0
int main()
{
	std::string pathBegin = "/home/nax/Work/biolab/TestingIn/";

	unsigned numMixtures = 1;
	std::vector<double> sphi_init(numMixtures, 2);
	std::vector<std::vector<unsigned> > mixtureDefinitionMatrix;

	// SIMULATE GENOME: RFP
	Genome genome;
    //if(testEqualityGenome(genome, genome)){
      //  my_print("So far so good\n");
    //}
    //exit(1);
        
	genome.readRFPData(pathBegin + "rfp_file_20positions_20genes.csv", false);
    exit(0);
	/*genome.readFasta(pathBegin + "RibModelDev/data/singleMixture/genome_2000.fasta", false);
	
	std::vector<unsigned> geneAssignment(genome.getGenomeSize());
	for (unsigned i = 0u; i < genome.getGenomeSize(); i++)
	{
		geneAssignment[i] = 0u;
	}

	PAParameter parameter(sphi_init, numMixtures, geneAssignment, mixtureDefinitionMatrix, true, "allUnique");
	PAModel model;
	
    //ROCParameter parameter(sphi_init, numMixtures, geneAssignment, mixtureDefinitionMatrix, true, "allUnique");
	//ROCModel model;

	model.setParameter(parameter);

	model.simulateGenome(genome);
	genome.writeRFPData(pathBegin + "labbooks/Denizhan.Pak/Log_Files/sim_genomes/PASim.csv", true);
	genome.writeRFPData(pathBegin + "labbooks/Denizhan.Pak/Log_Files/sim_genomes/PANotSim.csv", false);
	exit(1);*/
	

	// UNIT TESTING
	//testUtility();
	//testSequenceSummary();
	//testGene();
	//testGenome(pathBegin + "RibModelFramework/tests/testthat/UnitTestingData");
	//testCovarianceMatrix();
	//testParameter();
	//testParameterWithFile(pathBegin + "HollisFile.txt");
	//testPAParameter();
	//testMCMCAlgorithm();
	//exit(0);


	std::string modelToRun = "PANSE"; //can be RFP, ROC or FONSE
	bool withPhi = false;
	bool fromRestart = false;


	my_print("Initializing MCMCAlgorithm object---------------\n");
	unsigned samples = 100;
	unsigned thinning = 100;
	int useSamples = 1000;
	my_print("\t# Samples: %\n", samples);
	my_print("\tThinning: %\n", thinning);
	my_print("\t # Samples used: %\n", useSamples);
	MCMCAlgorithm mcmc = MCMCAlgorithm(samples, thinning, 10, true, true, true);
	mcmc.setRestartFileSettings(pathBegin + "RestartFile.txt", 20, true);
	my_print("Done!-------------------------------\n\n\n");


	if (modelToRun == "ROC")
	{
		my_print("Initializing Genome object--------------------------\n");
		Genome genome;
		genome.readFasta(pathBegin + "RibModelDev/data/twoMixtures/simulatedAllUniqueR.fasta");
		if (withPhi)
		{
			genome.readObservedPhiValues(pathBegin + "RibModelFramework/ribModel/data/simulatedAllUniqueR_phi.csv", false);
		}
		my_print("Done!-------------------------------\n\n\n");


		my_print("Initializing shared parameter variables---------------\n");
		std::vector<unsigned> geneAssignment(genome.getGenomeSize());
		std::vector<double> sphi_init(numMixtures, 1);

		if (numMixtures == 1)
		{
			for (unsigned i = 0u; i < genome.getGenomeSize(); i++)
			{
				geneAssignment[i] = 0u;
			}
		}
		else if (numMixtures == 3)
		{
			for (unsigned i = 0u; i < genome.getGenomeSize(); i++)
			{
				if (i < 961) geneAssignment[i] = 0u;
				else if (i < 1418) geneAssignment[i] = 1u;
				else geneAssignment[i] = 0u;
			}
		}
		std::vector<std::vector<unsigned>> mixtureDefinitionMatrix;
		my_print("Done!------------------------\n\n\n");


		my_print("Initializing ROCParameter object--------------------\n\n");
		ROCParameter parameter;

		if (fromRestart)
		{
			ROCParameter tmp(pathBegin + "RibModelFramework/DevRscripts/10restartFile.rst");
			parameter = tmp;
		}
		else
		{
			std::string mixDef = ROCParameter::allUnique;
			ROCParameter tmp(sphi_init, numMixtures, geneAssignment, mixtureDefinitionMatrix, true, mixDef);

			for (unsigned i = 0u; i < numMixtures; i++)
			{
				unsigned selectionCategry = tmp.getSelectionCategory(i);
				my_print("Sphi_init for selection category %: %\n", selectionCategry, sphi_init[selectionCategry]);
			}
			my_print("\t# mixtures: %\n", numMixtures);
			my_print("\tmixture definition: %\n", mixDef);

			std::vector<std::string> files(2);
			files[0] = std::string(pathBegin + "RibModelDev/data/twoMixtures/simulated_mutation0.csv");
			files[1] = std::string(pathBegin + "RibModelDev/data/twoMixtures/simulated_mutation1.csv");
			tmp.initMutationCategories(files, tmp.getNumMutationCategories());
			files[0] = std::string(pathBegin + "RibModelDev/data/twoMixtures/simulated_selection0.csv");
			files[1] = std::string(pathBegin + "RibModelDev/data/twoMixtures/simulated_selection1.csv");
			tmp.initSelectionCategories(files, tmp.getNumSelectionCategories());

			tmp.InitializeSynthesisRate(genome, sphi_init[0]);
			//std::vector<double> phiVals =
			// parameter.readPhiValues(pathBegin + "RibModelDev/data/realGenomes/Skluyveri_ChrA_ChrCleft_phi_est.csv");
			//parameter.InitializeSynthesisRate(phiVals);
			parameter = tmp;
		}
		my_print("Done!--------------------------------\n\n\n");


		my_print("Initializing ROCModel object--------------------------\n");
		ROCModel model;
		model.setParameter(parameter);
		my_print("Done!----------------------------------\n\n\n");


		my_print("Running MCMC.............\n\n");
		mcmc.run(genome, model, 1, 0);
		my_print("Done!----------------------------------\n\n\n");
	} //END OF ROC
	else if (modelToRun == "PANSE")
	{
		my_print("Initializing Genome object--------------------------\n");
		Genome genome;
		//genome.readRFPData(pathBegin + "RibModelDev/data/rfp/rfp.counts.by.codon.and.gene.GSE63789.wt.csv");
		genome.readRFPData(pathBegin + "PopPAData.csv");
		my_print("Done!-------------------------------\n\n\n");


		my_print("Initializing shared parameter variables---------------\n");
		std::vector<unsigned> geneAssignment(genome.getGenomeSize());
		std::vector<double> sphi_init(numMixtures, 1);

		if (numMixtures == 1)
		{
			for (unsigned i = 0u; i < genome.getGenomeSize(); i++)
			{
				geneAssignment[i] = 0u;
			}
		}
		else if (numMixtures == 3)
		{
			for (unsigned i = 0u; i < genome.getGenomeSize(); i++)
			{
				if (i < 961) geneAssignment[i] = 0u;
				else if (i < 1418) geneAssignment[i] = 1u;
				else geneAssignment[i] = 0u;
			}
		}
		std::vector<std::vector<unsigned>> mixtureDefinitionMatrix;
		my_print("Done!------------------------\n\n\n");


		my_print("Initializing PANSEParameter object--------------------\n\n");
		PANSEParameter parameter;
		//parameter.writeBasicRestartFile("/Users/hollisbui/HollisFile.txt");

		if (fromRestart)
		{
			PANSEParameter tmp(pathBegin + "RibModelFramework/10_restartFile.rst");
			parameter = tmp;
		}
		else
		{
			std::string mixDef = Parameter::allUnique;
			PANSEParameter tmp(sphi_init, numMixtures, geneAssignment, mixtureDefinitionMatrix, true, mixDef);

			for (unsigned i = 0u; i < numMixtures; i++)
			{
				unsigned selectionCategry = tmp.getSelectionCategory(i);
				my_print("Sphi_init for selection category %: %\n", selectionCategry, sphi_init[selectionCategry]);
			}
			my_print("\t# mixtures: %\n", numMixtures);
			my_print("\tmixture definition: %\n", mixDef);

			tmp.InitializeSynthesisRate(genome, sphi_init[0]);
			parameter = tmp;
			//parameter.writeEntireRestartFile("/Users/hollisbui/HollisFile2.txt");
		}
		my_print("Done!--------------------------------\n\n\n");


		my_print("Initializing PAModel object--------------------------\n");
		PANSEModel model;
		model.setParameter(parameter);
		my_print("Done!----------------------------------\n\n\n");


		my_print("Running MCMC.............\n\n");
		mcmc.run(genome, model, 1, 0);
		my_print("Done!----------------------------------\n\n\n");

	} //END OF RFP
	else if (modelToRun == "FONSE")
	{
		my_print("initialize Genome object--------------------------\n");
		Genome genome;
		genome.readFasta(pathBegin + "RibModelDev/data/singleMixture/genome_2000.fasta");
		my_print("Done!-------------------------------\n\n\n");


		my_print("Initializing shared parameter variables---------------\n");
		std::vector<unsigned> geneAssignment(genome.getGenomeSize());
		std::vector<double> sphi_init(numMixtures, 1);

		if (numMixtures == 1)
		{
			for (unsigned i = 0u; i < genome.getGenomeSize(); i++)
			{
				geneAssignment[i] = 0u;
			}
		}
		else if (numMixtures == 3)
		{
			for (unsigned i = 0u; i < genome.getGenomeSize(); i++)
			{
				if (i < 961) geneAssignment[i] = 0u;
				else if (i < 1418) geneAssignment[i] = 1u;
				else geneAssignment[i] = 0u;
			}
		}
		std::vector<std::vector<unsigned>> mixtureDefinitionMatrix;
		my_print("Done!------------------------\n\n\n");


		FONSEParameter parameter;
		my_print("initialize Parameter object\n");
		if (fromRestart)
		{
			FONSEParameter tmp(pathBegin + "RibModelDev/DevRscripts/10restartFile.rst");
			parameter = tmp;
		}
		else
		{
			std::string mixDef = ROCParameter::allUnique;
			FONSEParameter tmp(sphi_init, numMixtures, geneAssignment, mixtureDefinitionMatrix, true, mixDef);

			for (unsigned i = 0u; i < numMixtures; i++)
			{
				unsigned selectionCategory = tmp.getSelectionCategory(i);
				my_print("Sphi_init for selection category %: %\n", selectionCategory, sphi_init[selectionCategory]);
			}
			my_print("\t# mixtures: %\n", numMixtures);
			my_print("\tmixture definition: %\n", mixDef);

			std::vector<std::string> files(1);
			files[0] = std::string(pathBegin + "RibModelDev/data/singleMixture/genome_2000.mutation.csv");
			tmp.initMutationCategories(files, tmp.getNumMutationCategories());
			tmp.InitializeSynthesisRate(genome, sphi_init[0]);
			//std::vector<double> phiVals = parameter.readPhiValues(
			// pathBegin + "RibModelDev/data/realGenomes/Skluyveri_ChrA_ChrCleft_phi_est.csv");
			//parameter.InitializeSynthesisRate(phiVals);
			parameter = tmp;
			my_print("done initialize Parameter object\n");
		}


		my_print("Initializing Model object\n");
		FONSEModel model;
		model.setParameter(parameter);
		my_print("Done!------------------------\n\n\n");


		my_print("starting MCMC for ROC\n");
		mcmc.run(genome, model, 4, 0);
		my_print("\nFinished MCMC for ROC\n");

	}
}
Exemplo n.º 25
0
int main()
{
	std::string pathBegin = "/Users/hollisbui/";

	unsigned numMixtures = 1;
	std::vector<double> sphi_init(numMixtures, 2);
	std::vector<std::vector<unsigned>> mixtureDefinitionMatrix;

	/*
	// SIMULATE GENOME: PA

	Genome genome;
	genome.readRFPData(pathBegin + "TODO");
	std::vector<unsigned> geneAssignment(genome.getGenomeSize());
	for (unsigned i = 0u; i < genome.getGenomeSize(); i++)
		geneAssignment[i] = 0u;

	PAParameter parameter(sphi_init, numMixtures, geneAssignment, mixtureDefinitionMatrix, true, "allUnique");

	std::vector<std::string> files;
	files.push_back(pathBegin + "miscGilchrist/runMe/HollisTestingData/RFPAlphaValues.csv");
	parameter.initMutationSelectionCategories(files, 1, PAParameter::alp);
	files[0] = pathBegin + "miscGilchrist/runMe/HollisTestingData/RFPLambdaPrimeValues.csv";
	parameter.initMutationSelectionCategories(files, 1, PAParameter::lmPri);

	std::vector<double> phi = parameter.readPhiValues(pathBegin + "miscGilchrist/runMe/HollisTestingData/RFPPhiValues.csv");
	//std::vector<double> phi = tmp.readPhiValues("/Users/roxasoath1/Desktop/TONEWTON/RFPPsiValues.csv");
	parameter.InitializeSynthesisRate(phi);

	PAModel model;

	model.setParameter(parameter);

	model.simulateGenome(genome);
	genome.writeRFPData(pathBegin + "miscGilchrist/runMe/HollisTestingOut/hbuiSimGenome5.30.17.csv", true);
	exit(1);
	 */

	// UNIT TESTING
	//testUtility();
	//testSequenceSummary();
	//testGene();
	//testGenome(pathBegin + "RibModelFramework/tests/testthat/UnitTestingData");
	//testCovarianceMatrix();
	//testParameter();
	//testMCMCAlgorithm();
	//exit(0);


	std::string modelToRun = "PA"; //can be PA, ROC or FONSE
	bool withPhi = false;
	bool fromRestart = false;


	my_print("Initializing MCMCAlgorithm object---------------\n");
	unsigned samples = 1000;
	unsigned thinning = 10;
	int useSamples = 100;
	my_print("\t# Samples: %\n", samples);
	my_print("\tThinning: %\n", thinning);
	my_print("\t # Samples used: %\n", useSamples);
	MCMCAlgorithm mcmc = MCMCAlgorithm(samples, thinning, 10, true, true, true);
	//mcmc.setRestartFileSettings(pathBegin + "RestartFile.txt", 20, true);
	my_print("Done!-------------------------------\n\n\n");
	my_print("Initializing Genome object--------------------------\n");
	Genome genome;

	if (modelToRun == "ROC")
	{
		genome.readFasta(pathBegin + "RibModelDev/data/twoMixtures/simulatedAllUniqueR.fasta");
		if (withPhi)
		{
			genome.readObservedPhiValues(pathBegin + "RibModelFramework/ribModel/data/simulatedAllUniqueR_phi.csv", false);
		}
		my_print("Done!-------------------------------\n\n\n");


		my_print("Initializing shared parameter variables---------------\n");
		std::vector<unsigned> geneAssignment(genome.getGenomeSize());
		std::vector<double> sphi_init(numMixtures, 1);

		if (numMixtures == 1)
		{
			for (unsigned i = 0u; i < genome.getGenomeSize(); i++)
			{
				geneAssignment[i] = 0u;
			}
		}
		else if (numMixtures == 3)
		{
			for (unsigned i = 0u; i < genome.getGenomeSize(); i++)
			{
				if (i < 961) geneAssignment[i] = 0u;
				else if (i < 1418) geneAssignment[i] = 1u;
				else geneAssignment[i] = 0u;
			}
		}
		my_print("Done!------------------------\n\n\n");


		my_print("Initializing ROCParameter object--------------------\n\n");
		ROCParameter parameter;

		if (fromRestart)
		{
			ROCParameter tmp(pathBegin + "RibModelFramework/DevRscripts/10restartFile.rst");
			parameter = tmp;
		}
		else
		{
			std::string mixDef = ROCParameter::allUnique;
			ROCParameter tmp(sphi_init, numMixtures, geneAssignment, mixtureDefinitionMatrix, true, mixDef);

			for (unsigned i = 0u; i < numMixtures; i++)
			{
				unsigned selectionCategory = tmp.getSelectionCategory(i);
				my_print("Sphi_init for selection category %: %\n", selectionCategory, sphi_init[selectionCategory]);
			}
			my_print("\t# mixtures: %\n", numMixtures);
			my_print("\tmixture definition: %\n", mixDef);

			std::vector<std::string> files(2);
			files[0] = std::string(pathBegin + "RibModelDev/data/twoMixtures/simulated_mutation0.csv");
			files[1] = std::string(pathBegin + "RibModelDev/data/twoMixtures/simulated_mutation1.csv");
			tmp.initMutationCategories(files, tmp.getNumMutationCategories());
			files[0] = std::string(pathBegin + "RibModelDev/data/twoMixtures/simulated_selection0.csv");
			files[1] = std::string(pathBegin + "RibModelDev/data/twoMixtures/simulated_selection1.csv");
			tmp.initSelectionCategories(files, tmp.getNumSelectionCategories());

			tmp.InitializeSynthesisRate(genome, sphi_init[0]);
			//std::vector<double> phiVals =
			// parameter.readPhiValues(pathBegin + "RibModelDev/data/realGenomes/Skluyveri_ChrA_ChrCleft_phi_est.csv");
			//parameter.InitializeSynthesisRate(phiVals);
			parameter = tmp;
		}
		my_print("Done!--------------------------------\n\n\n");


		my_print("Initializing ROCModel object--------------------------\n");
		ROCModel model;
		model.setParameter(parameter);
		my_print("Done!----------------------------------\n\n\n");


		my_print("Running MCMC.............\n\n");
		mcmc.run(genome, model, 1, 0);
		my_print("Done!----------------------------------\n\n\n");
	} //END OF ROC
	else if (modelToRun == "PA")
	{
		genome.readRFPData(pathBegin + "labnotebooks/Hollis.Bui/RunnableScriptsAndData/June2017PAModelPop/PopPADataOneGene.csv");
		my_print("Done!-------------------------------\n\n\n");


		my_print("Initializing shared parameter variables---------------\n");
		std::vector<unsigned> geneAssignment(genome.getGenomeSize());
		std::vector<double> sphi_init(numMixtures, 1);

		if (numMixtures == 1)
		{
			for (unsigned i = 0u; i < genome.getGenomeSize(); i++)
			{
				geneAssignment[i] = 0u;
			}
		}
		else if (numMixtures == 3)
		{
			for (unsigned i = 0u; i < genome.getGenomeSize(); i++)
			{
				if (i < 961) geneAssignment[i] = 0u;
				else if (i < 1418) geneAssignment[i] = 1u;
				else geneAssignment[i] = 0u;
			}
		}
		my_print("Done!------------------------\n\n\n");


		my_print("Initializing PAParameter object--------------------\n\n");
		PAParameter parameter;
		parameter.writeBasicRestartFile(pathBegin + "RibModelFramework/HollisRestartFile.txt");

		if (fromRestart)
		{
			PAParameter tmp(pathBegin + "RibModelFramework/10_restartFile.rst");
			parameter = tmp;
		}
		else
		{
			std::string mixDef = Parameter::allUnique;
			PAParameter tmp(sphi_init, numMixtures, geneAssignment, mixtureDefinitionMatrix, true, mixDef);

			for (unsigned i = 0u; i < numMixtures; i++)
			{
				unsigned selectionCategory = tmp.getSelectionCategory(i);
				my_print("Sphi_init for selection category %: %\n", selectionCategory, sphi_init[selectionCategory]);
			}
			my_print("\t# mixtures: %\n", numMixtures);
			my_print("\tmixture definition: %\n", mixDef);

			tmp.InitializeSynthesisRate(genome, sphi_init[0]);
			parameter = tmp;
			parameter.writeEntireRestartFile(pathBegin + "RibModelFramework/HollisRestartFile2.txt");
		}
		my_print("Done!--------------------------------\n\n\n");


		my_print("Initializing PAModel object--------------------------\n");
		PAModel model;
		model.setParameter(parameter);
		my_print("Done!----------------------------------\n\n\n");


		my_print("Running MCMC.............\n\n");
		mcmc.run(genome, model, 1, 0);
		my_print("Done!----------------------------------\n\n\n");

		std::vector<double> alphaList (61,0);
		std::vector<double> lambdaPrimeList (61,0);
		std::vector<double> waitingTimes (61,0);
		std::vector<double> waitRates (61,0);
		std::vector<std::string> codonList = SequenceSummary::codons();
		unsigned cat = 0u;

		for (unsigned i = 0u; i < 61; i++)
		{
			std::string codon = codonList[i];

			alphaList[i] = parameter.getCodonSpecificPosteriorMean(cat, samples / 2, codon, 0, false);
			//alphaTrace <- trace$getCodonSpecificParameterTraceByMixtureElementForCodon(1, codon, 0, FALSE)
			//alpha.ci[i,] <- quantile(alphaTrace[(samples * 0.5):samples], probs = c(0.025,0.975))

			lambdaPrimeList[i] = parameter.getCodonSpecificPosteriorMean(cat, samples / 2, codon, 1, false);
			//lambdaPrimeTrace <- trace$getCodonSpecificParameterTraceByMixtureElementForCodon(1, codon, 1, FALSE)
			//lambdaPrime.ci[i,] <- quantile(lambdaPrimeTrace[(samples * 0.5):samples], probs = c(0.025,0.975))

			waitingTimes[i] = alphaList[i] / lambdaPrimeList[i];
			waitRates[i] = (1.0/waitingTimes[i]);

			my_print("For codon %, alpha is %, lambda prime is %, and waitingTime is %.\n", codonList[i], alphaList[i],
					 lambdaPrimeList[i], waitingTimes[i]);
		}
	} //END OF PA
	else if (modelToRun == "FONSE")
	{
		genome.readFasta(pathBegin + "RibModelDev/data/singleMixture/genome_2000.fasta");
		my_print("Done!-------------------------------\n\n\n");


		my_print("Initializing shared parameter variables---------------\n");
		std::vector<unsigned> geneAssignment(genome.getGenomeSize());
		std::vector<double> sphi_init(numMixtures, 1);

		if (numMixtures == 1)
		{
			for (unsigned i = 0u; i < genome.getGenomeSize(); i++)
			{
				geneAssignment[i] = 0u;
			}
		}
		else if (numMixtures == 3)
		{
			for (unsigned i = 0u; i < genome.getGenomeSize(); i++)
			{
				if (i < 961) geneAssignment[i] = 0u;
				else if (i < 1418) geneAssignment[i] = 1u;
				else geneAssignment[i] = 0u;
			}
		}
		my_print("Done!------------------------\n\n\n");


		FONSEParameter parameter;
		my_print("initialize Parameter object\n");
		if (fromRestart)
		{
			FONSEParameter tmp(pathBegin + "RibModelDev/DevRscripts/10restartFile.rst");
			parameter = tmp;
		}
		else
		{
			std::string mixDef = ROCParameter::allUnique;
			FONSEParameter tmp(sphi_init, numMixtures, geneAssignment, mixtureDefinitionMatrix, true, mixDef);

			for (unsigned i = 0u; i < numMixtures; i++)
			{
				unsigned selectionCategory = tmp.getSelectionCategory(i);
				my_print("Sphi_init for selection category %: %\n", selectionCategory, sphi_init[selectionCategory]);
			}
			my_print("\t# mixtures: %\n", numMixtures);
			my_print("\tmixture definition: %\n", mixDef);

			std::vector<std::string> files(1);
			files[0] = std::string(pathBegin + "RibModelDev/data/singleMixture/genome_2000.mutation.csv");
			tmp.initMutationCategories(files, tmp.getNumMutationCategories());
			tmp.InitializeSynthesisRate(genome, sphi_init[0]);
			//std::vector<double> phiVals = parameter.readPhiValues(
			// pathBegin + "RibModelDev/data/realGenomes/Skluyveri_ChrA_ChrCleft_phi_est.csv");
			//parameter.InitializeSynthesisRate(phiVals);
			parameter = tmp;
			my_print("done initialize Parameter object\n");
		}


		my_print("Initializing Model object\n");
		FONSEModel model;
		model.setParameter(parameter);
		my_print("Done!------------------------\n\n\n");


		my_print("starting MCMC for ROC\n");
		mcmc.run(genome, model, 4, 0);
		my_print("\nFinished MCMC for ROC\n");

	}
}
Exemplo n.º 26
0
int main(int argv, char **argc)
{	
	//Setting up variables for iteration, string and file parsing, file opening and scanning. 
	FILE *fin, *fopen();
	int i;
	char fn[20],ln[20],incI[10],incLine[80],scholStatus;
	float incG,avgGPA,tempGPA;
	
	//I setup a student struct and then a pointer to the struct.
	STUDENT scholarshipStudents,*studentPointer;
	studentPointer = &scholarshipStudents;
	
	//If the file can't be opened, I let the user know and then exit the program.
	if((fin = fopen("/home/courses1/cs3352/projects/proj1/P1-DATA","r"))==NULL) {
		printf("Unable to open file /home/courses1/cs3352/projects/proj1/P1-DATA\n");
		exit(1);
	} 
	
	//I print the header for each column of data to be printed
	fprintf(stdout, "\n%-20s %-20s %9s %4s\n", "First Name","Last Name","ID","GPA");
	
	//Initializing both the iterator of the 24 records and average GPA to zero
	i = 0;
	avgGPA = 0.0;
	//loop until no more lines to read or max number of students read.
	while (1 && i < SIZE) {
		//If we reach the end of the file, exit the loop.
		if (feof(fin)) break;
		//The first character of any line designates the current scholarship status, this time we ignore it
		scholStatus = fgetc(fin);
		//Get the rest of the text and then scan the first and last names, ID number and GPA
		fgets(incLine,80,fin);
		sscanf(incLine,"%s %s %s %f",fn,ln,incI,&incG);
		//Print the line of data just read in pretty print. Also, add the newly read in GPA to the 
		//avgGPA variable and increment i
		fprintf(stdout,"%-20s %-20s %9s %1.2f\n",fn,ln,incI,incG);
		avgGPA+=incG;
		i++;
	}
	//Now we find the average GPA
	avgGPA/=SIZE;
	//Print out the average GPA
	fprintf(stdout,"\nAverage GPA is %1.2f\n",avgGPA);
	
	//We want to reopen the same file to reach in the students again to check for scholarship candidates.
	if((fin = freopen("/home/courses1/cs3352/projects/proj1/P1-DATA","r",fin))==NULL) {
		printf("Unable to reopen file /home/courses1/cs3352/projects/proj1/P1-DATA\n");
		exit(1);
	}
	
	i = 0;
	//Initial section is very similar to original loop, read until end of file or max students
	//Get scholarship status and then read and parse the rest of the line. 
	while (1 && i < SIZE) {
		if (feof(fin)) break;
		scholStatus = fgetc(fin);
		fgets(incLine,80,fin);
		sscanf(incLine,"%s %s %s %f",fn,ln,incI,&incG);
		//We check to see if this is a current scholarship student, if not and their GPA is greater than
		//the average GPA, check to see if there is a student in the first slot, if not, add this student
		//If so, parse the first slot student and compare the two student's GPA.
		if (scholStatus != '#' && incG > avgGPA) {
			if (scholarshipStudents.FIRST == NULL)
				strcpy(scholarshipStudents.FIRST,incLine);
			else {
				sscanf(scholarshipStudents.FIRST,"%s %s %s %f",fn,ln,incI,&tempGPA);
				//If the new student's GPA is higher than the First student's GPA, we copy the first to
				//the second, then copy the new student to the first.
				if (incG > tempGPA) {
					strcpy(scholarshipStudents.SECOND,scholarshipStudents.FIRST);
					strcpy(scholarshipStudents.FIRST,incLine);
				//If the second student is empty, add this student to the second slot.
				} else if (scholarshipStudents.SECOND == NULL)
					strcpy(scholarshipStudents.SECOND,incLine);
				else {
					//Otherwise, compare the students as done for the first student position and replace
					//the second position with the current student, if needed.
					sscanf(scholarshipStudents.SECOND,"%s %s %s %f",fn,ln,incI,&tempGPA);
					if (incG > tempGPA) {
						strcpy(scholarshipStudents.SECOND,incLine);
					}
				}
			}		
		i++;
		}
	}
	
	//Call the function to print the students and then close the file stream.
	my_print(studentPointer);
		
	fclose(fin);

return 0;
}
Exemplo n.º 27
0
bool SessionInfo::ProcessConfig(const string& config_json)
{
    m_upgradeVersion.clear();
    m_psk.clear();
    m_sshPort = 0;
    m_sshUsername.clear();
    m_sshPassword.clear();
    m_sshHostKey.clear();
    m_sshSessionID.clear();
    m_sshObfuscatedPort = 0;
    m_sshObfuscatedKey.clear();
    m_homepages.clear();
    m_servers.clear();
    m_pageViewRegexes.clear();
    m_httpsRequestRegexes.clear();
    m_preemptiveReconnectLifetimeMilliseconds = PREEMPTIVE_RECONNECT_LIFETIME_MILLISECONDS_DEFAULT;
    m_localHttpProxyPort = 0;
    m_localHttpsProxyPort = 0;
    m_localSocksProxyPort = 0;

    Json::Value config;
    Json::Reader reader;
    bool parsingSuccessful = reader.parse(config_json, config);
    if (!parsingSuccessful)
    {
        string fail = reader.getFormattedErrorMessages();
        my_print(NOT_SENSITIVE, false, _T("%s:%d: Page view regex parse failed: %S"), __TFUNCTION__, __LINE__, fail.c_str());
        return false;
    }

    try
    {
        // Homepages
        Json::Value homepages = config["homepages"];
        for (Json::Value::ArrayIndex i = 0; i < homepages.size(); i++)
        {
            m_homepages.push_back(UTF8ToWString(homepages[i].asString()));
        }

        // Upgrade
        m_upgradeVersion = config.get("upgrade_client_version", "").asString();

        // Servers
        Json::Value servers = config["encoded_server_list"];
        for (Json::Value::ArrayIndex i = 0; i < servers.size(); i++)
        {
            m_servers.push_back(servers[i].asString());
        }

        // SSH and OSSH values
        m_sshPort = config.get("ssh_port", 0).asInt();
        m_sshUsername = config.get("ssh_username", "").asString();
        m_sshPassword = config.get("ssh_password", "").asString();
        m_sshHostKey = config.get("ssh_host_key", "").asString();
        m_sshSessionID = config.get("ssh_session_id", "").asString();
        m_sshObfuscatedPort = config.get("ssh_obfuscated_port", 0).asInt();
        m_sshObfuscatedKey = config.get("ssh_obfuscated_key", "").asString();

        // VPN PSK
        m_psk = config.get("l2tp_ipsec_psk", "").asString();

        // Page view regexes        
        Json::Value regexes = config["page_view_regexes"];
        for (Json::Value::ArrayIndex i = 0; i < regexes.size(); i++)
        {
            RegexReplace rx_re;
            rx_re.regex = regex(
                            regexes[i].get("regex", "").asString(), 
                            regex::ECMAScript | regex::icase | regex::optimize);
            rx_re.replace = regexes[i].get("replace", "").asString();

            m_pageViewRegexes.push_back(rx_re);
        }

        // HTTPS request regexes        
        regexes = config["https_request_regexes"];
        for (Json::Value::ArrayIndex i = 0; i < regexes.size(); i++)
        {
            RegexReplace rx_re;
            rx_re.regex = regex(
                            regexes[i].get("regex", "").asString(), 
                            regex::ECMAScript | regex::icase | regex::optimize);
            rx_re.replace = regexes[i].get("replace", "").asString();

            m_httpsRequestRegexes.push_back(rx_re);
        }

        // Preemptive Reconnect Lifetime Milliseconds
        m_preemptiveReconnectLifetimeMilliseconds = (DWORD)config.get("preemptive_reconnect_lifetime_milliseconds", 0).asUInt();
        // A zero value indicates that it should be disabled.
    }
    catch (exception& e)
    {
        my_print(NOT_SENSITIVE, false, _T("%s:%d: Config parse exception: %S"), __TFUNCTION__, __LINE__, e.what());
        return false;
    }

    return true;
}
Exemplo n.º 28
0
// ================================================================================
// This program stress tests the templated MultiLL container class
int main() {


  // The test data (stored in STL lists)
  std::list<std::string> songs;
  songs.push_back("hound dog");
  songs.push_back("poker face");
  songs.push_back("brown eyed girl");
  songs.push_back("let it be");
  songs.push_back("walk like an egyptian");
  songs.push_back("man in the mirror");
  songs.push_back("stairway to heaven");
  songs.push_back("dancing in the street");
  songs.push_back("every breath you take");
  songs.push_back("hotel california");
  // the same data, sorted!
  std::list<std::string> sorted_songs(songs);
  sorted_songs.sort();


  // create an empty multi-linked list and fill it with the test data
  MultiLL<std::string> my_list;
  for (std::list<std::string>::iterator itr = songs.begin(); itr != songs.end(); itr++) {
    my_list.add(*itr);
    my_print(my_list);
  }
  assert (songs.size() == my_list.size());



  // -------------------
  // iterator tests

  // test the chronological iterator (forwards)
  std::cout << "chronological order" << std::endl;
  std::list<std::string> chrono_order;
  MultiLL<std::string>::iterator itr = my_list.begin_chronological();
  while (itr != my_list.end_chronological()) {
    std::cout << "  " << *itr << std::endl;
    chrono_order.push_back(*itr);
    itr++;
  }
  std::cout << std::endl;
  assert (same(songs,chrono_order));


  // test the sorted order iterator (forwards)
  std::cout << "sorted order" << std::endl;
  std::list<std::string> sorted_order;
  itr = my_list.begin_sorted();
  while (itr != my_list.end_sorted()) {
    std::cout << "  " << *itr << std::endl;
    sorted_order.push_back(*itr);
    itr++;
  }
  std::cout << std::endl;
  assert (same(sorted_songs,sorted_order));


  // test the random order iterator
  std::cout << "random order" << std::endl;
  std::list<std::string> random_order;
  itr = my_list.begin_random();
  for (int i = 0; i < my_list.size(); i++,itr++) {
    std::cout << "  " << *itr << std::endl;
    random_order.push_back(*itr);
  }
  std::cout << std::endl;
  // loop through the elements a second time (the order should be the same!)
  std::list<std::string>::iterator itr2 = random_order.begin();
  for (int i = 0; i < my_list.size(); i++,itr++,itr2++) {
    // verify that the elements repeat the order
    assert (*itr == *itr2);
  }
  std::list<std::string> random_order_check(random_order);
  random_order_check.sort();
  // verify that all of the elements appeared in the initial loop
  assert (same(sorted_songs,random_order_check));



  // test the re-randomization by creating a new random iterator
  std::cout << "random order 2" << std::endl;
  std::list<std::string> random_order2;
  itr = my_list.begin_random();
  for (int i = 0; i < my_list.size(); i++,itr++) {
    std::cout << "  " << *itr << std::endl;
    random_order2.push_back(*itr);
  }
  std::cout << std::endl;
  // with over 3 million different possible permutations of 10
  // elements, it is highly unlikely they will be the same!
  assert (!same(random_order,random_order2));


  
  /*
  // -------------------
  // erase tests

  // erase the first element inserted
  itr = my_list.begin_chronological();
  assert (*itr == "hound dog");
  itr = my_list.erase(itr);
  assert (*itr == "poker face");
  assert (my_list.size() == 9);
  std::cout << "erased: hound dog" << std::endl;

  // erase the second to last element in sorted order
  itr = my_list.begin_sorted();
  for (int i = 0; i < 7; i++) { itr++; }
  assert (*itr == "stairway to heaven");
  itr = my_list.erase(itr);
  assert (*itr == "walk like an egyptian");
  assert (my_list.size() == 8);  
  std::cout << "erased: stairway to heaven" << std::endl;

  // erase the third element in the random order
  itr = my_list.begin_random();
  itr++;
  itr++;
  std::string tmp = *itr;
  // note that the return value of erase with a random iterator is undefined
  my_list.erase(itr);
  std::cout << "erased: " << tmp << std::endl;
  assert (my_list.size() == 7);
  assert (!my_list.empty());

  my_list.clear();
  assert (my_list.empty());
  assert (my_list.size() == 0);
  std::cout << "cleared the whole list!" << std::endl << std::endl;
  */



  // ---------------------------
  // ADD YOUR OWN TEST CASES BELOW
  
  // be sure to test:
  //   copy constructor
  //   assignment operator
  //   destructor
  //   all corner cases of erase
  //   decrement operator for the chronological & sorted iterators
  //   pre vs. post increment & decrement operations for iterators
  //   MultiLL containing types other than std::string
  //   anything else that is necessary




  std::cout << " ***  OUTPUT FROM YOUR TEST CASES ***" << std::endl;

  // copy constructor
  MultiLL<std::string> copy_list(my_list);

  std::cout << "Old list:" << std::endl;
  my_print(my_list);
  /*
  std::cout << "Copy of old list:" << std::endl;
  my_print(copy_list);
  */




}
Exemplo n.º 29
0
static int invoker_init(void)
{
printk(KERN_ALERT " Hello world, I'm invoker module\n");
my_print(" Called by invoker module");
return 0;
}
Exemplo n.º 30
0
static int load_elf_binary(struct linux_binprm *bprm)
{
  struct pt_regs regs; 
  int interpreter_fd = -1;
   unsigned long load_addr = 0, load_bias;
  int load_addr_set = 0;
  char * elf_interpreter = NULL;
  unsigned int interpreter_type = INTERPRETER_NONE;
  unsigned long error;
  struct elf_phdr * elf_ppnt, *elf_phdata;
  unsigned long elf_bss, k, elf_brk;
  int elf_exec_fileno;
  int retval, size, i;
  unsigned long elf_entry, interp_load_addr = 0;
  unsigned long start_code, end_code, end_data;
  struct elfhdr elf_ex;
  struct elfhdr interp_elf_ex;
    struct exec interp_ex;
  char passed_fileno[6];
  
  /* Get the exec-header */
  elf_ex = *((struct elfhdr *) bprm->buf);
  my_print("[debug]here to run elf\n");
  retval = -ENOEXEC;
  /* First of all, some simple consistency checks */
  if (elf_ex.e_ident[0] != 0x7f ||
      strncmp(&elf_ex.e_ident[1], "ELF", 3) != 0)
    goto out;
  //my_print("[ender]1\n");
  if (elf_ex.e_type != ET_EXEC && elf_ex.e_type != ET_DYN)
    goto out;
  if (!elf_check_arch(elf_ex.e_machine))
    goto out;
  //my_print("[ender]2\n");

  /* Now read in all of the header information */

  if (elf_ex.e_phentsize != sizeof(struct elf_phdr) ||
      elf_ex.e_phnum < 1 ||
      elf_ex.e_phnum > 65536 / sizeof(struct elf_phdr))
    goto out;
 // my_print("[ender]3\n");
  retval = -ENOMEM;
  size = elf_ex.e_phentsize * elf_ex.e_phnum;
  elf_phdata = (struct elf_phdr *) malloc(size);
  if (!elf_phdata)
    goto out;

  retval = read_exec(bprm->fd, elf_ex.e_phoff, (char *) elf_phdata, size, 1);
  if (retval < 0)
    goto out_free_ph;
  //my_print("[ender]4\n");

  elf_exec_fileno = dup(bprm->fd);
  lseek(elf_exec_fileno, 0, SEEK_SET);

  elf_ppnt = elf_phdata;
  elf_bss = 0;
  elf_brk = 0;

  start_code = ~0UL;
  end_code = 0;
  end_data = 0;

  /* look for interpreter */
  for (i = 0; i < elf_ex.e_phnum; i++) {
    if (elf_ppnt->p_type == PT_INTERP) {
      retval = -ENOEXEC;
        if (elf_interpreter ||
          elf_ppnt->p_filesz < 2 ||
          elf_ppnt->p_filesz > PAGE_SIZE)
        goto out_free_dentry;

      /* This is the program interpreter used for
       * shared libraries - for now assume that this
       * is an a.out format binary
       */

      retval = -ENOMEM;
      elf_interpreter = (char *)malloc(elf_ppnt->p_filesz);
      if (!elf_interpreter)
        goto out_free_file;

      retval = read_exec(bprm->fd, elf_ppnt->p_offset,
             elf_interpreter, elf_ppnt->p_filesz, 1);
      if (retval < 0)
        goto out_free_interp;
      elf_interpreter[elf_ppnt->p_filesz - 1] = 0;
      
#if 0
      /* If the program interpreter is one of these two,
       * then assume an iBCS2 image. Otherwise assume
       * a native linux image.
       */
      if (strcmp(elf_interpreter,"/usr/lib/libc.so.1") == 0 ||
          strcmp(elf_interpreter,"/usr/lib/ld.so.1") == 0)
        ibcs2_interpreter = 1;
#endif

      log_debug(LOG_LINEXEC_EXEC, "Using ELF interpreter: %s", elf_interpreter);
	  if( elf_interpreter[0] == '/'){
		  char tmp [MAX_PATH];
          change_path_to_relative(tmp, elf_interpreter);
		  free(elf_interpreter);
		  //elf_interpreter = (char *)malloc(elf_ppnt->p_filesz);
          elf_interpreter = (char *)malloc(strlen(tmp)+1);
		  if (!elf_interpreter)
			  goto out_free_file;
		  strcpy(elf_interpreter, tmp);
	  }
      interpreter_fd = open(elf_interpreter, O_RDONLY);
	  my_print("[debug]open elf_interpreter %s\n", elf_interpreter);
      if (interpreter_fd < 0) {
        retval = -errno;
        goto out_free_interp;
      }

#if 0        
      retval = permission(interpreter_dentry->d_inode, MAY_EXEC);
      if (retval < 0)
        goto out_free_dentry;
#endif
        
      retval = read_exec(interpreter_fd, 0, bprm->buf, 128, 1);
      if (retval < 0)
        goto out_free_dentry;

      /* Get the exec headers */
      interp_ex = *((struct exec *) bprm->buf);
      interp_elf_ex = *((struct elfhdr *) bprm->buf);
    }
    elf_ppnt++;
	//my_print("[ender]6\n");
  }

  /* Some simple consistency checks for the interpreter */
  if (elf_interpreter) {
    interpreter_type = INTERPRETER_ELF | INTERPRETER_AOUT;

    /* Now figure out which format our binary is */
    if ((N_MAGIC(interp_ex) != OMAGIC) &&
        (N_MAGIC(interp_ex) != ZMAGIC) &&
        (N_MAGIC(interp_ex) != QMAGIC))
      interpreter_type = INTERPRETER_ELF;

    if (interp_elf_ex.e_ident[0] != 0x7f ||
        strncmp(&interp_elf_ex.e_ident[1], "ELF", 3) != 0)
      interpreter_type &= ~INTERPRETER_ELF;

    retval = -ELIBBAD;
    if (!interpreter_type)
      goto out_free_dentry;

    /* Make sure only one type was selected */
    if ((interpreter_type & INTERPRETER_ELF) &&
         interpreter_type != INTERPRETER_ELF) {
      printf("ELF: Ambiguous type, using ELF\n");
      interpreter_type = INTERPRETER_ELF;
    }
  }
  //my_print("[ender]7\n");
  /* OK, we are done with that, now set up the arg stuff,
     and then start this sucker up */
  if (!bprm->sh_bang) {
    char * passed_p;

    if (interpreter_type == INTERPRETER_AOUT) {
      sprintf(passed_fileno, "%d", elf_exec_fileno);
      passed_p = passed_fileno;

      if (elf_interpreter) {
        bprm->p = copy_strings(1,&passed_p,bprm->page,bprm->p);
        bprm->argc++;
      }
    }
    retval = -E2BIG;
    if (!bprm->p)
      goto out_free_dentry;
  }


#if 0
  /* Flush all traces of the currently running executable */
  retval = flush_old_exec(bprm);
  if (retval)
    goto out_free_dentry;
#endif  

  /* OK, This is the point of no return */
  current->end_data = 0;
  current->end_code = 0;
#if 0
  current->mm->mmap = NULL;
  current->flags &= ~PF_FORKNOEXEC;

#endif  
  elf_entry = (unsigned long) elf_ex.e_entry;
  //printf("[ender]8\n");

#if 0
  /* Do this immediately, since STACK_TOP as used in setup_arg_pages
     may depend on the personality.  */
  SET_PERSONALITY(elf_ex, ibcs2_interpreter);
#endif  

  /* Do this so that we can load the interpreter, if need be.  We will
     change some of these later */
//  current->mm->rss = 0;
  bprm->p = setup_arg_pages(bprm->p, bprm);
  
  current->start_stack = bprm->p;

  /* Try and get dynamic programs out of the way of the default mmap
     base, as well as whatever program they might try to exec.  This
     is because the brk will follow the loader, and is not movable.  */

  load_bias = ELF_PAGESTART(elf_ex.e_type==ET_DYN ? ELF_ET_DYN_BASE : 0);
#ifdef __VERBOSE__
  printf("load_bias: %08lX\n", load_bias);
#endif

  /* Now we do a little grungy work by mmaping the ELF image into
     the correct location in memory.  At this point, we assume that
     the image should be loaded at fixed address, not at a variable
     address. */

  for(i = 0, elf_ppnt = elf_phdata; i < elf_ex.e_phnum; i++, elf_ppnt++) {
    int elf_prot = 0, elf_flags;
    unsigned long vaddr;

    if (elf_ppnt->p_type != PT_LOAD)
      continue;

    if (elf_ppnt->p_flags & PF_R) elf_prot |= PROT_READ;
    if (elf_ppnt->p_flags & PF_W) elf_prot |= PROT_WRITE;
    if (elf_ppnt->p_flags & PF_X) elf_prot |= PROT_EXEC;

    elf_flags = MAP_PRIVATE; // |MAP_DENYWRITE|MAP_EXECUTABLE;

    vaddr = elf_ppnt->p_vaddr;
    if (elf_ex.e_type == ET_EXEC || load_addr_set) {
      elf_flags |= MAP_FIXED;
    }
	//my_print("[ender]9\n");
#ifdef __VERBOSE__
    printf("mapping: %08lX\n", ELF_PAGESTART(load_bias + vaddr));
#endif
    error = do_mmap(bprm->fd, ELF_PAGESTART(load_bias + vaddr),
                    (elf_ppnt->p_filesz + ELF_PAGEOFFSET(elf_ppnt->p_vaddr)),
                    elf_prot, elf_flags, 
                    (elf_ppnt->p_offset - ELF_PAGEOFFSET(elf_ppnt->p_vaddr)));

#ifdef __VERBOSE__
    printf("error: %08lX\n", error);
#endif

    if (!load_addr_set) {
      load_addr_set = 1;
      load_addr = (elf_ppnt->p_vaddr - elf_ppnt->p_offset);
#ifdef __VERBOSE__
      printf("load_addr: %08lX, vaddr: %08lX\n", load_addr, vaddr);
#endif      
      if (elf_ex.e_type == ET_DYN) {
        load_bias += error - ELF_PAGESTART(load_bias + vaddr);
        load_addr += error;
      
#ifdef __VERBOSE__
        printf("new\nload_bias: %08lX, load_addr: %08lX\n", load_bias, load_addr);
#endif        
      }
    }
    k = elf_ppnt->p_vaddr;
    if (k < start_code) start_code = k;
    k = elf_ppnt->p_vaddr + elf_ppnt->p_filesz;
    if (k > elf_bss)
      elf_bss = k;
    if ((elf_ppnt->p_flags & PF_X) && end_code <  k)
      end_code = k;
    if (end_data < k)
      end_data = k;
    k = elf_ppnt->p_vaddr + elf_ppnt->p_memsz;
    if (k > elf_brk)
      elf_brk = k;
  }
  
  close(bprm->fd);
  
  elf_entry += load_bias;
  elf_bss += load_bias;
  elf_brk += load_bias;
  start_code += load_bias;
  end_code += load_bias;
  end_data += load_bias;

  if (elf_interpreter) {
    if (interpreter_type == INTERPRETER_AOUT) {
      elf_entry = load_aout_interp(&interp_ex, interpreter_fd);
    } else {
      elf_entry = load_elf_interp(&interp_elf_ex, interpreter_fd, 
                                  &interp_load_addr);
    }                                  
    close(interpreter_fd);
    if (elf_entry == ~0UL) {
      printf("Unable to load interpreter %.128s\n", elf_interpreter);
      free(elf_interpreter);
      free(elf_phdata);
      
      //send_sig(SIGSEGV, current, 0);
      exit(1);
      return 0;
    }

    free(elf_interpreter);
  }
  
  free(elf_phdata);

  if (interpreter_type != INTERPRETER_AOUT)
    close(elf_exec_fileno);
  
#if 0
#ifndef VM_STACK_FLAGS
  current->executable = dget(bprm->dentry);
#endif
#endif
  bprm->p = (unsigned long)create_elf_tables((char *)bprm->p,
                        bprm->argc, bprm->envc,
                        (interpreter_type == INTERPRETER_ELF ? &elf_ex : NULL),
                        load_addr, load_bias, interp_load_addr,
                        (interpreter_type == INTERPRETER_AOUT ? 0 : 1));

#if 0                        
  /* N.B. passed_fileno might not be initialized? */
  if (interpreter_type == INTERPRETER_AOUT)
    current->arg_start += strlen(passed_fileno) + 1;
#endif  
    
  current->start_brk = current->brk = elf_brk;
  current->end_code = end_code;
  current->start_code = start_code;
  current->end_data = end_data;
  current->start_stack = bprm->p;

  /* Calling set_brk effectively mmaps the pages that we need
   * for the bss and break sections
   */
  set_brk(elf_bss, elf_brk);
  padzero(elf_bss);
  log_debug(LOG_LINEXEC_EXEC,"start_brk: %lx" , current->start_brk);
  log_debug(LOG_LINEXEC_EXEC,"end_code: %lx" , current->end_code);
  log_debug(LOG_LINEXEC_EXEC,"start_code: %lx" , current->start_code);
  log_debug(LOG_LINEXEC_EXEC,"end_data: %lx" , current->end_data);
  log_debug(LOG_LINEXEC_EXEC,"start_stack: %lx" , current->start_stack);
  log_debug(LOG_LINEXEC_EXEC,"brk: %lx" , current->brk);

  /*
   * The ABI may specify that certain registers be set up in special
   * ways (on i386 %edx is the address of a DT_FINI function, for
   * example.  This macro performs whatever initialization to
   * the regs structure is required.
   */
  ELF_PLAT_INIT((&regs));

  regs.eip = elf_entry;
  regs.esp = bprm->p;

#if 0
  if (current->flags & PF_PTRACED)
    send_sig(SIGTRAP, current, 0);
#endif

#ifndef __DEBUG__


//  dumpMemoryMap();
  log_verbose(LOG_LINEXEC_EXEC, "[transfering control to Linux executable]");
  //getchar();
  //printf("[ender]11\n");
  ASM_EXEC_JUMP(regs);
  
  printf("You should never see this message!\n");
 
#else

  printf("execve() finished, but in debug mode. exiting...\n");
 
#endif
    
  retval = 0;
out:
  return retval;

  /* error cleanup */
out_free_dentry:
  close(interpreter_fd);
  
out_free_interp:
  if (elf_interpreter) {
    free(elf_interpreter);
  }

out_free_file:
  close(elf_exec_fileno);
  
out_free_ph:
  free(elf_phdata);
  goto out;
}