HRESULT CLR_RT_HeapBlock_Queue::CopyTo( CLR_RT_HeapBlock_Array* toArray, CLR_INT32 index ) { NATIVE_PROFILE_CLR_CORE(); TINYCLR_HEADER(); CLR_RT_HeapBlock_Array* array = GetArray(); CLR_INT32 size = GetSize(); CLR_INT32 head = Head(); CLR_INT32 tail = GetTail(); // if the target array is of type Object, we don't need to call the complex Array::Copy() since there will be no casting involved HRESULT (*arrayCopy)( CLR_RT_HeapBlock_Array*, int, CLR_RT_HeapBlock_Array*, int, int ) = (toArray->m_typeOfElement == DATATYPE_OBJECT) ? ObjArrayMemcpy : CLR_RT_HeapBlock_Array::Copy; if(((CLR_INT32)toArray->m_numOfElements) - index < size) TINYCLR_SET_AND_LEAVE(CLR_E_INVALID_PARAMETER); if(size > 0) { if(head < tail) { TINYCLR_SET_AND_LEAVE(arrayCopy( array, head, toArray, index, size )); } else { CLR_INT32 firstPart = array->m_numOfElements - head; TINYCLR_CHECK_HRESULT(arrayCopy( array, head, toArray, index , firstPart )); TINYCLR_SET_AND_LEAVE(arrayCopy( array, 0 , toArray, index + firstPart, tail )); } } TINYCLR_NOCLEANUP(); }
void Audio::Play(byte melody[], byte durations[], byte length) { playing = true; currentNoteStartTime = millis(); noteIndex = 0; currentTune.length = length; arrayCopy(melody, currentTune.notes, length); arrayCopy(durations, currentTune.durations, length); tone(audioPin, notes_array[currentTune.notes[noteIndex]], (currentTune.durations[noteIndex]*20)); }
static void shift(DeviceList* const list, int index, int rooms, Shift dir) { if(dir == RIGHT) { arrayCopy(list->elements, index + 1, list->elements, index, rooms, list->current, sizeof(Element)); }else //SHIFT { arrayCopy(list->elements, index, list->elements, index + 1, rooms, list->current, sizeof(Element)); } }
/**************************************************************** * * Function: arrayCopy * Input: arg *argv Pointer to Thread Struct * * Output: returns nothing * * Description: Copys the results from the temporary arrays * to their respective output arrays * *****************************************************************/ void* arrayCopy(void* argv){ int i; int *S,*P,*R, *R_temp, *P_temp; args* input = (args*)argv; S = input->S; P = input->P; R = input->R; R_temp = input->R_temp; P_temp = input->P_temp; int status; status = checkQueue(input); if(status>0){ for(i=(input->s1); i<(input->e1); i++){ R[i] = R_temp[i]; P[i] = P_temp[i]; } arrayCopy(input); } else{ /*Wait for all Threads to Finish*/ pthread_barrier_wait(&init); } }
static void wide(DeviceList* const list) { list->size += list->increment_rate; Element *newArr = (Element*) calloc(sizeof(Element), list->size); arrayCopy(newArr, 0, list->elements, 0, list->current, list->size, sizeof(Element)); free(list->elements); list->elements = newArr; }
void loadPattern ( char initBoard[] [WIDTH],char pattern[][WIDTH], int &rows, int &columns) { int patternChoice; cout << endl << "Please Select a Predefined pattern: " << endl; patternMenu(patternChoice); loadPatternArray( pattern, rows, columns, patternChoice); arrayCopy(initBoard, pattern); }
int main() { int size = 10; int source[10] = {1,2,3,4,5,6,7,8,9,10}; int destination[size]; arrayCopy(destination, source, size); return 0; }
int main (int argc, char *argv[]) { GfrEntry *currGE; int count; int countRemoved; int i, j; int foundEST; if (argc != 2) { usage ("%s <EST.interval>",argv[0]); } intervalFind_addIntervalsToSearchSpace( argv[1], 0); // beginFiltering count = 0; countRemoved = 0; gfr_init ("-"); puts (gfr_writeHeader ()); while (currGE = gfr_nextEntry ()) { // reading the gfr foundEST = 0; if( strEqual( currGE->fusionType, "cis" ) ) { if( ! strEqual( currGE->chromosomeTranscript1, currGE->chromosomeTranscript2 ) ) die("The two genes are not on the same chromosomes: %s - %s", currGE->chromosomeTranscript1, currGE->chromosomeTranscript2 ); int start1, end1, start2, end2; findCoordinates( currGE, &start1, &end1, &start2, &end2 ); Array intervals1 = arrayCopy( intervalFind_getOverlappingIntervals( currGE->chromosomeTranscript1, start1, end1 ) ); Array intervals2 = intervalFind_getOverlappingIntervals( currGE->chromosomeTranscript2, start2, end2 ); for( i=0; i<arrayMax( intervals1 ); i++ ) { Interval* currInterval1 = arru( intervals1, i, Interval* ); for( j=0; j<arrayMax ( intervals2 ); j++ ) { Interval* currInterval2 = arru( intervals2, j, Interval* ); if( currInterval1==currInterval2 ) { foundEST = 1; i = arrayMax( intervals1 ); j = arrayMax( intervals2 ); } } } arrayDestroy( intervals1 ); } if( foundEST ) countRemoved++; else { puts (gfr_writeGfrEntry (currGE)); count++; } } gfr_deInit (); warn ("%s_EST_data: %s",argv[0], argv[1]); warn ("%s_numRemoved: %d",argv[0], countRemoved); warn ("%s_numGfrEntries: %d",argv[0],count); return 0; }
void arrayReverse(unsigned int *array, unsigned int arraySize){ unsigned int i; unsigned int *reversed; if (!array) { if (gVerbose) printf("-W- arrayReverse received NULL array\n"); return; } reversed = (unsigned int*)malloc(arraySize*sizeof(unsigned int)); for (i=0;i<arraySize;i++) reversed[i] = array[arraySize-i-1]; arrayCopy(reversed,array,arraySize); free(reversed); }
ArrayList<T>& ArrayList<T>::operator=(const ArrayList<T>& a) { if (this != &a) { T** newItems = new T*[a.cap]; arrayCopy(newItems, a.items, a.cap); sz = a.sz; cap = a.cap; delete[] items; items = newItems; } return *this; }
void playGame (char currentBoard [] [WIDTH], char nextGenBoard [][WIDTH], int nrows, int ncols ) { int i, turns; do{ cout << "How Many Turns?: "; cin >> turns; if (turns <= 0) { cout << "Error: Invalid Entry. Number must be positive" << endl << endl; } }while (turns <= 0); displayCurrentBoard(currentBoard, nrows, ncols); for (i = 0; i < turns; ++i) { computeNextGeneration(currentBoard, nextGenBoard, nrows, ncols); displayCurrentBoard( nextGenBoard, nrows, ncols); arrayCopy(currentBoard, nextGenBoard); } }
void computeNextGeneration ( char currentBoard [][WIDTH], char nextGenBoard [][WIDTH], int nrows, int ncols ) { int row, columns, neighbor; arrayCopy(nextGenBoard, currentBoard); for (row = 0; row < nrows; ++row) { for (columns = 0; columns < ncols; ++columns) { neighbor = countLiveNeighbor(nextGenBoard, row, columns); if (nextGenBoard[row][columns] == '*') { if (neighbor < 2){ nextGenBoard[row][columns] = ' '; } // rule 1. underpopulation else if (neighbor > 3){ nextGenBoard [row][columns] = ' '; } // rule 2. overcrowding else if ( neighbor == 2 || neighbor == 3){ nextGenBoard[row][columns] = '*'; } // rule 3. live Cell continues on to next generation } // checks for Rules 1-3 else if (currentBoard [row][columns] == ' ') { if (neighbor == 3) nextGenBoard [row][columns] = '*'; } // checks for Rule 4 dead cell becomes live cell } } }
void bunny24_bruteForce(bit plain[block_length] , bit crypt[block_length]){ unsigned int i, end = 1024 * 1024 * 16; bit test[block_length]; bit testp[block_length]; for(i = 0; i < end; i++) { arrayCopy(plain , testp , 24); int j; for(j = 0; j < 24; j++) { if(i & (1 << j)) test[j] = 1; else test[j] = 0; } //printArray(test , 24); bunny24_encrypt(testp , test); if(arrayEqual(testp , crypt , 24) == 0) { printHex(test , 24); return; } //printf("fail key %d \n " , i); } }
void Message::SetMsg(byte func, byte length, byte* payload) { this->function = func; this->length = length; arrayCopy(payload, this->payload, length); this->length = length; }
int main() { int test; int terminal=-999;//this is for input text, so the loop knows when to stop int size=100;//Initial size int i=0; int *Data=Create(size); scanf("%d",&Data[i]);//Read in our initialize variable for our array //printf("i:%d and val:%d\n",i,Data[i]); i++; //????Even without increasing the allocated space the array was not Seg faulting while (Data[i-1]!=terminal)//This looks at the previous posi { scanf("%d",&Data[i]); //printf("i:%d and val:%d\n",i,Data[i]); i++; if (i==size)//this counter counts up size malloced for array, if true goes into function { size=size*2; Data=Inc_Cap(Data,size); } } printf("\nReading in Data Complete\n"); size=i-1;//the get rid of the -999 in the array because we dont want that sorted //printf("Test_shot\n"); int *lsearch_numComp_P;//This is for number of comparisons because we want to return to values from functions int *bsearch_numComp_P; int lsearch_numComp=0; int bsearch_numComp=0; lsearch_numComp_P=&lsearch_numComp;//Take the address of the right because we need to point to that space bsearch_numComp_P=&bsearch_numComp; int* toArray=Create(size);//We are mallocing because to we can free it later arrayCopy(Data,toArray,size);//self- explanatory sort(Data,size); i=0; int target;//This is the value that need to be found for binary and linear search scanf("%d",&target); //printf("Target Value: %d\n",target); while (target!=terminal) { //scanf("%d",&target); //printf("Target Value: %d\n",target); int Print_Lsearch=lsearch(toArray,size,target,lsearch_numComp_P);//reason for this becaue we are sending the index location if (Print_Lsearch==-1)//because of the above statement is the reason for this "if" statement {//we dont want to run the same function twice becasue it would be unneccassay printf("Value not found in Linear search\n"); } else printf("Target Value:%d found with Linear search in Array position %d with %d comparisons\n",target,Print_Lsearch,*lsearch_numComp_P); int Print_Bsearch=Bsearch(Data,size,target,bsearch_numComp_P); if (Print_Bsearch==-1) { //Same sort of logic as lsearch explaniation for "if" printf("Value not found in Binary search\n"); } else printf("Target Value:%d found with Binary search in Array position %d with %d comparisons\n",target,Print_Bsearch,*bsearch_numComp_P); lsearch_numComp=0; bsearch_numComp=0; scanf("%d",&target); } free_space(Data); free_space(toArray); return 0; }
void restart (char initBoard [] [WIDTH], char currentBoard [] [WIDTH]) { arrayCopy(currentBoard, initBoard); cout << endl << endl << endl << endl << endl; cout << "Reset Board Complete" << endl; }
int main ( ) { int introChoice, gameMenuChoice, rows, columns, restartBoard, enterNewBoard; int i; char initBoard [HEIGHT] [WIDTH]; char currentBoard [HEIGHT] [WIDTH]; char nextGenBoard [HEIGHT] [WIDTH]; char pattern [HEIGHT] [WIDTH]; char repeat; do{ enterNewBoard = 0; rows = 0; columns = 0; do{ cout << endl << "*** Spaces Between Spaces ***" << endl; introMenu(introChoice); if (introChoice == 1) { enterFromKeyboard ( initBoard, rows, columns); repeat = 'n'; } else if (introChoice == 2) { cout << endl<< "Load From Files" << endl; boardDataFile(initBoard, rows, columns); repeat = 'n'; } else if (introChoice == 3) { cout << "Load Presets" << endl; loadPattern(initBoard, pattern, rows, columns); repeat = 'n'; } else { cout << "Error: Invalid Entry" << endl << endl; repeat = 'y'; } }while (repeat == 'y'); arrayCopy(currentBoard, initBoard); displayCurrentBoard ( currentBoard, rows, columns); do{ restartBoard = 0; gameMenuDisplay(gameMenuChoice); if (gameMenuChoice == 1) { playGame(currentBoard, nextGenBoard, rows, columns); restartBoard = 1; } else if (gameMenuChoice == 2) { restart(initBoard, currentBoard); restartBoard = 1; } else if (gameMenuChoice == 3) { cout << "Displaying Current Board...." << endl; displayCurrentBoard(currentBoard, rows, columns); restartBoard = 1; } else if (gameMenuChoice == 4){ cout << "Enter a New Board" << endl; restartBoard = 0; enterNewBoard = 1; for (i = 0; i < 7;++i) { cout << endl; } } else if (gameMenuChoice == 5){ cout << endl << endl << endl; restartBoard = 0; } } while ( restartBoard == 1); }while (enterNewBoard == 1); // loop that allows User to enter new board cout << "Have A Good Day" << endl; cout << "Goodbye!" << endl << endl; return 0; } // End of int main
int main(){ int *a; char *b="Hello "; char *c= "World"; char *d; char *file1="e.bin"; char *file2="text.bin"; int size; int sizes[2]; int e[4][3]={{1,2,3},{4,5,6},{7,8,9},{10,11,12}}; int **f; int **g; //1 mark //write a function "allocate10" that allocates space for 10 integer using the parameter list //in other words the function is of VOID type, takes a parameter and allocates and assigns memory to that parameter //call the function to allocate and assign memory to a //use a loop in the function to assign a[0] to a[9] to integers 0 to 9 //print the values out one per line in the main program //To be clear - the memory is allocated and assigning values happens in the function //in the main function //free the memory in a allocate10(&a); for(int i=0;i<10;i++){ printf("%d\n",a[i]); } free(a); //1 mark //Write a function "joinStrings" takes as parameters 3 strings. It joins the first 2 together and puts the result in the third string //The function allocates memory for the third string using malloc //apply the function to strings b,c, and d. After the function is done d should have memory allocated to it and contain "Hello World" //the function should not assume the sizes of b or c - it needs to be general enough for any string //after calling the function using b,c,d as parameters print out d from the main function //free the memory in d joinStrings(b,c,&d); printf("%s\n",d); free(d); //1 mark //write a function "arrayWrite" that takes as parameters an array of the same type as e, the size of the first dimension, and a string variables, binaryFilename //the function "arrayWrite" writes the values of the the array (starting from array[0][0] and ending at array[size-1][2]) to the binaryFilename //apply the function to array e and file1 size=4; arrayWrite(e,size,file1); //1 mark //write a function "binaryIO" to take as a parameter two filenames //it opens the first file which is binary reads in sizeof(int) bytes at a time //it writes value and the value squared separated by a ',' one set of values per line i.e. //0,0 //1,1 //2,4 //etc. to a the second file // //run the function with parameters file1, file2 //so at the end of this there should be two new files binaryIO(file1,file2); //2 marks //malloc and assign memory for f as a pointer to pointers to integer style array of the same size as e //malloc and assign memory for g as a pointer to pointer to integer where you assign the pointers to a block of memory the size of e //write a function "arrayCopy" that that takes parameters of the same type as e, f, and g and a sizes array parameter //sizes is an array of the dimension sizes //use for loops to copy values of e to f and g inside the function //in main print out e, f and g 0 //in main free the memory for f //in main free the memory for g f=(int**) malloc(sizeof(int*)*4); for(int i=0;i<4;i++) f[i]=(int*) malloc(sizeof(int)*3); g=(int**) malloc(sizeof(int*)*4); g[0]=malloc(12*sizeof(int)); for(int i=1;i<4;i++) g[i]=g[i-1]+3; sizes[0]=4; sizes[1]=3; arrayCopy(e,f,g,sizes); for(int i=0;i<4;i++){ for(int j=0;j<3;j++){ printf("%d %d %d\n",e[i][j],f[i][j],g[i][j]); } } for(int i=0;i<4;i++) free(f[i]); free(f); f=0; free(g[0]); free(g); g=0; return 1; }
double factDecomp(int n, int T, double *price, double *D, double *V, double *F, double *mu, int pcNum) { /*Initialization*/ srand((unsigned)time(NULL));//Set seed for random int count =0 , count_limit = 400, retcode = 0; double *r,*Q,*w,*w0, *wOld, *eigValue, *Qcal; double *tempW = nullptr; double *tempT1 = nullptr,*tempT2 = nullptr,*tempWW = nullptr, *tempVF = nullptr, *Vtrans = nullptr, *tempVFV =nullptr; double tempSum = 0, tempQ = 0 , temp = 0 , tempNorm = 0; r = (double *)calloc(n*(T-1),sizeof(double)); Q = (double *)calloc(n*n,sizeof(double)); /*Compute return of each stock r = (P_n - P_n-1)/P_n-1 */ for (int h = 0 ; h < n; h++){ tempSum = 0; for (int k = 0 ; k < T-1 ; k++){ r[k + h * (T-1)] = (price[k + h * T +1] - price[k + h * T])/price[k + h * T]; tempSum = tempSum + r[k + h * (T-1)]; } mu[h] = tempSum/(T - 1); } /*Compute the covariance matrix Q = E[(x-Ex)(y-Ey)]*/ for (int i = 0; i < n; i++){ for (int j = 0; j < n; j++){ tempQ = 0; for ( int k = 0; k < T - 1; ++k){ tempQ = tempQ + (r[k + i * (T-1)] - mu[i])*(r[k + j * (T-1)] - mu[j]); } Q[i*n + j] = tempQ/(T-2); } } /*Use power method to get the principal component*/ //Initialization w = (double *)calloc(n,sizeof(double)); w0 = (double *)calloc(n,sizeof(double)); eigValue = (double *)calloc(pcNum,sizeof(double)); Vtrans = (double *)calloc(n*pcNum,sizeof(double)); Qcal = (double *)calloc(n*n,sizeof(double)); tempT1 = (double *)calloc(1,sizeof(double)); tempT2 = (double *)calloc(n,sizeof(double)); wOld = (double *)calloc(n,sizeof(double)); tempW = (double *)calloc(n,sizeof(double)); tempWW = (double *)calloc(n,sizeof(double)); tempVF = (double *)calloc(n*pcNum,sizeof(double)); tempVFV = (double *)calloc(n*n,sizeof(double)); //Generate a random array w0 for (int i = 0 ; i < n; i++){ w0[i] = rand()/(RAND_MAX+1.0); w[i] = w0[i]; } //Copy Q to Qcal arrayCopy(Q, n*n,&Qcal); //Compute eigenvalue, eigenvector for (int h = 0; h < pcNum ; h++){ count = 0; //Get a new vector that is orthogonal to all previous w as a start after the first iteration if (h != 0){ //Generate new random w0 //Compute wTw0w arrayMultiply(w, w0 ,1, n, 1,&tempT1); arrayMultiply(tempT1, w ,1, 1, n, &tempT2); //Subtract wTw0w for each previous w from w0 for (int ind = 0; ind < n; ind++){ w0[ind] = w0[ind] - tempT2[ind]; } arrayCopy(w0, n, &w); //Q' = Q - lambda*w*wT for (int l = 0 ; l < n ; l++ ){ for (int g = 0 ; g < n ; g++) Qcal[l*n + g] = Qcal[l*n + g] - tempW[l]*tempW[g]*eigValue[h-1]; } } //iteration begin while (count < count_limit){//we use count_limit to limit the iteration times arrayCopy(w , n, &wOld); arrayMultiply(Qcal, w ,n, n, 1, &tempW); arrayNormalize(&tempW, n); arrayCopy(tempW, n, &w); count = count + 1; ////Break if the difference between the new w and the old w is very small /* diff = diffJudge( w,wOld,n,1); if (diff == true) { printf("%d\n",count); break; } */ } //Compute eigenvalue and store the eigenvector temp = 0; for (int j = 0 ; j <n ; j++){ temp = temp + Q[j] * w[j]; V[h + j*pcNum] = w[j]; } eigValue[h] = temp/w[0]; } //Compute F for (int ind = 0 ; ind < pcNum; ind++){ F[ind*(pcNum+1)] = eigValue[ind]; } //Compute principal part of Q :VFV' arrayTranspose(V, n, pcNum,&Vtrans); arrayMultiply(V, F ,n, pcNum, pcNum, &tempVF); arrayMultiply(tempVF, Vtrans ,n, pcNum, n, &tempVFV); //Compute D and take the main diagonal of R for (int ind2 = 0 ; ind2 < n; ind2++){ D[ind2] = Q[ind2*(n+1)] - tempVFV[ind2*(n+1)]; //if (D[ind2] < 0){ // printf("warning!! %f %d \n", D[ind2], ind2); // retcode = -1000; // goto BACK; //} } ////Compute D (not take the main diagonal) //for (int ind2 = 0 ; ind2 < n*n; ind2++){ // D[ind2] = Q[ind2] - tempVFV[ind2]; //} //free the calloc space free(r); free(Q); free(w); free(w0); free(eigValue); free(Vtrans); free(Qcal); free(tempT1); free(tempT2); free(wOld); free(tempW); free(tempWW); free(tempVF); free(tempVFV); return retcode; }
void keySchedule(bit key[key_length] , bit schedule[16][key_length]){ //Step 1 bit word[88][6]; int i , j , r; for(i = 0; i < 4; i++){ getChunk(key, word[i], i); for(j = 0; j < chunk_length; j++) word[i + 4][j] = word[i][j]; } for(i = 4; i < 8; i++) { sbox(word[i], i - 4); if(i < 7) arraySum(word[i - 3] , word[i] , word[i] , chunk_length); else arraySum(word[0] , word[i] , word[i] , chunk_length); } //step 2 for(j = 9; j <= 88; j++) { i = j-1; if((j % 8) == 1) { bit buffer[chunk_length]; arrayCopy(word[i - 1] , buffer , chunk_length); rotate(buffer, -1 , chunk_length); sbox(buffer , 1); arraySum(buffer , word[i - 8], word[i], chunk_length); arraySum(word[i], keyScheduleArray , word[i], chunk_length); } else if((j % 8) == 5) { bit buffer[chunk_length]; arrayCopy(word[i - 1] , buffer , chunk_length); sbox(buffer , 2); arraySum(word[i - 8] , buffer , word[i] , chunk_length); } else if((j % 4) != 1) arraySum(word[i - 8] , word[i - 1] , word[i] , chunk_length); } //phase 3 for(r = 0; r < 3; r++) //for rect 1,2,3 { for(j = 0; j < 5; j++) //for key 1...5 { int z = (8 + 20*r) + j; int index = (r*5)+j; for(i = 0; i < 4; i++) //for each word of the key { setChunk(schedule[index] , word[z] , i); z += 5; } } } int z = 68; for(i = 0; i < 4; i++) //last key { setChunk(schedule[15] , word[z] , i); z += 5; } }
void NatureQLearner::learnFromPast() { const int availableSamples = history.size(); int batchSize = availableSamples >= maxSamples ? maxSamples : availableSamples; // batchSize = ; const int size = scenario->getPerceptionSize(); const int numActions = scenario->getNumActions(); net->setBatchSize(batchSize); // cout << "batchSize: " << batchSize << endl; // draw samples Experience **experiences = new Experience *[ batchSize ]; for(int n = 0; n < batchSize; n++) { int sampleIdx = myrand() % availableSamples; Experience *experience = history[sampleIdx]; experiences[n] = experience; } // copy in data float *afters = new float[ batchSize * planes * size * size ]; float *befores = new float[ batchSize * planes * size * size ]; for(int n = 0; n < batchSize; n++) { Experience *experience = experiences[n]; arrayCopy(afters + n * planes * size * size, experience->after, planes * size * size); arrayCopy(befores + n * planes * size * size, experience->before, planes * size * size); } // replace targetNet if(epoch % replaceTargetnetEpoch == 0) { float weights[netTotalNumWeights]; WeightsPersister::copyNetWeightsToArray(net, weights); WeightsPersister::copyArrayToNetWeights(weights, targetNet); } // get next q values, based on forward prop 'afters' targetNet->setBatchSize(batchSize); targetNet->forward(afters); float const *allOutput = targetNet->getOutput(); float *bestQ = new float[ batchSize ]; for(int n = 0; n < batchSize; n++) { float const *output = allOutput + n * numActions; float thisBestQ = output[0]; for(int action = 1; action < numActions; action++) { if(output[action] > thisBestQ) { thisBestQ = output[action]; } } bestQ[n] = thisBestQ; } // forward prop 'befores', set up expected values, and backprop // new q values net->forward(befores); allOutput = net->getOutput(); float *expectedValues = new float[ numActions * batchSize ]; arrayCopy(expectedValues, allOutput, batchSize * numActions); for(int n = 0; n < batchSize; n++) { Experience *experience = experiences[n]; if(experience->isEndState) { expectedValues[ n * numActions + experience->action ] = experience->reward; } else { expectedValues[ n * numActions + experience->action ] = experience->reward + lambda * bestQ[n]; } } // backprop... // throw runtime_error("need to implement this"); TrainingContext context(epoch, 0); trainer->train(net, &context, befores, expectedValues); // net->backward(learningRate / batchSize, expectedValues); net->setBatchSize(1); epoch++; delete[] expectedValues; delete[] bestQ; delete[] afters; delete[] befores; delete[] experiences; }
bool ResourceFileReader::read() { ifstream inputFile(myFilePath.c_str(), ios::in | ios::binary); if(!inputFile.is_open()) // make sure the file is open { return false; } // read in the first four bytes, where the magic word should be intComponents currentMagicWord; currentMagicWord.number = 0; inputFile.read(currentMagicWord.bytes, 4); convertLittleEndianToNative(currentMagicWord.bytes); if(currentMagicWord.number != magicWord) // make sure the magic word matches { return false; } // read in the header size and convert from little-endian intComponents headerSize; headerSize.number = 0; inputFile.read(headerSize.bytes, 4); convertLittleEndianToNative(headerSize.bytes); // read in the file count and convert from little-endian intComponents fileCount; fileCount.number = 0; inputFile.read(fileCount.bytes, 4); convertLittleEndianToNative(fileCount.bytes); // read the entire file table block into memory int fileTableSize = headerSize.number - 3 * sizeof(int); char * headerData = new char[fileTableSize]; inputFile.read(headerData, fileTableSize); // parse the file table int fileTableOffset = 0; unsigned int fileIndex = 0; while(true) { string name(headerData + fileTableOffset); fileTableOffset += name.size() + 1; // read in the entry's file size intComponents fileSize; fileSize.number = 0; arrayCopy(headerData + fileTableOffset, fileSize.bytes, sizeof(int)); convertLittleEndianToNative(fileSize.bytes); // read in the entry's offset intComponents offset; offset.number = 0; arrayCopy(headerData + fileTableOffset + sizeof(int), offset.bytes, sizeof(int)); convertLittleEndianToNative(offset.bytes); fileTableOffset += 2 * sizeof(int); // add the entry to the entry list ResourceFileEntry * entry = new ResourceFileEntry(name, "", fileSize.number); entry->setOffset(offset.number); myEntries[name] = entry; fileIndex++; if(fileIndex == fileCount.number || fileTableOffset >= fileTableSize) // if we've found enough files or we're at the end of the file table { break; } } delete headerData; return true; }
double Run factDecomp(int n, int T, double *price) { /*Initialization*/ srand((unsigned)time(NULL));//Set seed for random int count =0 , count_limit = 1000, pcNum = 10; double *r,*avgR,*Q,*w,*w0, *wOld, *eigValue, *V, *F, *D, *Qcal; double *tempW = nullptr; double *tempT1 = nullptr,*tempT2 = nullptr,*tempWW = nullptr, *tempVF = nullptr, *Vtrans = nullptr, *tempVFV =nullptr; double tempSum = 0, tempQ = 0 , temp = 0 , tempNorm = 0; r = (double *)calloc(n*(T-1),sizeof(double)); avgR = (double *)calloc(n,sizeof(double)); Q = (double *)calloc(n*n,sizeof(double)); //bool diff; /*Compute return of each stock r = (P_n - P_n-1)/P_n-1 */ for (int h = 0 ; h < n; h++){ tempSum = 0; for (int k = 0 ; k < T-1 ; k++){ r[k + h * (T-1)] = (price[k + h * T +1] - price[k + h * T])/price[k + h * T]; tempSum = tempSum + r[k + h * (T-1)]; } avgR[h] = tempSum/(T - 1); } /*Compute the covariance matrix Q = E[(x-Ex)(y-Ey)]*/ for (int i = 0; i < n; i++){ for (int j = 0; j < n; j++){ tempQ = 0; for ( int k = 0; k < T - 1; ++k){ tempQ = tempQ + (r[k + i * (T-1)] - avgR[i])*(r[k + j * (T-1)] - avgR[j]); } Q[i*n + j] = tempQ/(T-2); } } /*Use power method to get the principal component*/ //Initialization w = (double *)calloc(n,sizeof(double)); w0 = (double *)calloc(n,sizeof(double)); eigValue = (double *)calloc(pcNum,sizeof(double)); F = (double *)calloc(pcNum*pcNum,sizeof(double)); D = (double *)calloc(n*n,sizeof(double)); V = (double *)calloc(n*pcNum,sizeof(double)); Vtrans = (double *)calloc(n*pcNum,sizeof(double)); Qcal = (double *)calloc(n*n,sizeof(double)); tempT1 = (double *)calloc(1,sizeof(double)); tempT2 = (double *)calloc(n,sizeof(double)); wOld = (double *)calloc(n,sizeof(double)); tempW = (double *)calloc(n,sizeof(double)); tempWW = (double *)calloc(n,sizeof(double)); tempVF = (double *)calloc(n*pcNum,sizeof(double)); tempVFV = (double *)calloc(n*n,sizeof(double)); //Generate a random array w0 for (int i = 0 ; i < n; i++){ w0[i] = rand()/(RAND_MAX+1.0); w[i] = w0[i]; } //Copy Q to Qcal arrayCopy(Q, n*n,&Qcal); //Compute eigenvalue, eigenvector for (int h = 0; h < pcNum ; h++){ count = 0; //Get a new vector that is orthogonal to all previous w as a start after the first iteration if (h != 0){ //Generate new random w0 for (int i = 0 ; i < n; i++){ w0[i] = rand()/(RAND_MAX+1.0); } for (int i = 0; i <h; i ++){ //Get previous eigenvector w for (int q = 0 ; q < n; q++){ tempWW[q]= V[i + q*pcNum]; } //Compute wTw0w arrayMultiply(tempWW, w0 ,1, n, 1,&tempT1); arrayMultiply(tempT1, tempWW ,1, 1, n, &tempT2); //Subtract wTw0w for each previous w from w0 for (int ind = 0; ind < n; ind++){ w0[ind] = w0[ind] - tempT2[ind]; } } arrayCopy(w0, n, &w); //Q' = Q - lambda*w*wT for (int l = 0 ; l < n ; l++ ){ for (int g = 0 ; g < n ; g++) Qcal[l*n + g] = Qcal[l*n + g] - tempW[l]*tempW[g]*eigValue[h-1]; } } //iteration begin while (count < count_limit){ arrayCopy(w , n, &wOld); arrayMultiply(Qcal, w ,n, n, 1, &tempW); arrayNormalize(&tempW, n); arrayCopy(tempW, n, &w); count = count + 1; //Break if the difference between the new w and the old w is very small //diff = diffJudge( w,wOld,n,1); //if (diff == true) { // //printf("%d\n",count); // break; } } //Compute eigenvalue and store the eigenvector temp = 0; for (int j = 0 ; j <n ; j++){ temp = temp + Q[j] * w[j]; V[h + j*pcNum] = w[j]; } eigValue[h] = temp/w[0]; } //Compute F for (int ind = 0 ; ind < pcNum; ind++){ F[ind*(pcNum+1)] = eigValue[ind]; } //Compute principal part of Q :VFV' arrayTranspose(V, n, pcNum,&Vtrans); arrayMultiply(V, F ,n, pcNum, pcNum, &tempVF); arrayMultiply(tempVF, Vtrans ,n, pcNum, n, &tempVFV); //Compute D and take the main diagonal of R for (int ind2 = 0 ; ind2 < n; ind2++){ D[ind2*(n+1)] = Q[ind2*(n+1)] - tempVFV[ind2*(n+1)]; } //Compute D (not take the main diagonal) /*for (int ind2 = 0 ; ind2 < n*n; ind2++){ D[ind2] = Q[ind2] - tempVFV[ind2]; }*/ //Print result(for check purpose) //printf("V:\n"); //arrayPrint(V, n, pcNum); //printf("F:\n"); //arrayPrint(F ,pcNum,pcNum); //printf("D:\n"); //arrayPrint(D, n, n); //Output the result to csv file(if there doesn't exist a csv file, then create one) FILE *out; char* buffer; // Get the current working directory: if( (buffer = _getcwd( NULL, 0 )) == NULL ) perror( "_getcwd error" ); strcat(buffer,"\\result.csv"); printf( "%s\n", buffer); out=fopen(buffer,"w+"); if (out == NULL){ printf("could not open for reading\n"); return -1; } //Write the result into the csv file fprintf(out,"V:\n"); for (int i = 0 ; i < n*pcNum ; i++){ if (i != 0 && i % pcNum == 0) fprintf(out,"\n"); fprintf(out,"%g,",V[i]); } fprintf(out,"\n\n"); fprintf(out,"F:\n"); for (int i = 0 ; i < pcNum*pcNum ; i++){ if (i != 0 && i % pcNum == 0) fprintf(out,"\n"); fprintf(out,"%g,",F[i]); } fprintf(out,"\n\n"); fprintf(out,"D:\n"); for (int i = 0 ; i < n*n ; i++){ if (i != 0 && i % n == 0) fprintf(out,"\n"); fprintf(out,"%g,",D[i]); } fclose(out); return 0; }
/**************************************************************** * * Function: nodeLength * Input: int *S Pointer to Input Array S * int *R Pointer to Output Array R * int n Size of the Arrays S and R * * Output: returns nothing * * Description: Takes a linked list array S and finds the * distance of each node in S to the final node 0. The * distance is saved in the output array R. * *****************************************************************/ void* nodeLength(void* argv){ int i; int *S,*P,*R, *R_temp, *P_temp; args* input = (args*)argv; S = input->S; P = input->P; R = input->R; R_temp = input->R_temp; P_temp = input->P_temp; int status; status = checkQueue(input); if(status>0){ /*Process each node */ for(i=(input->s1); i<(input->e1); i++){ if(P[i] > 0){ R_temp[i] = R[i]+R[P[i]]; P_temp[i] = P[P[i]]; } } /*Check to see if more work is left*/ nodeLength(input); } else{ /*Wait for other threads to finish step*/ pthread_barrier_wait(&barrier); /*Reset Work Queue so we can start Copying Results Back*/ if(input->id == 0){ /*Only master touches it*/ jobs.queue1[0] = 0; jobs.queue1[1] = input->n; } /*Wait for Master to update the Queue*/ pthread_barrier_wait(&barrier); /*Start Copying array back*/ arrayCopy(input); /*Wait for other threads to finish*/ pthread_barrier_wait(&barrier); /*Finished all steps*/ if(status==-1){ if(input->id){ pthread_exit(NULL); } } else{ /*Reset the work queue*/ if(input->id == 0){ /*Only master touches it*/ jobs.m -= 1; jobs.queue1[0] = 0; jobs.queue1[1] = input->n; } /*Wait for other threads to finish step*/ pthread_barrier_wait(&barrier); nodeLength(input); } } }
int main(int argc, char* argv[]) { // Args if(argc > 1) { if(!strcmp(argv[1], "-r")) { printf("Record mode, will use default recording device.\n\n"); record = true; } else { record = false; printf("Going to play %s\n\n", argv[1]); sound_file = argv[1]; } if(argc > 2) { if(!strcmp(argv[2], "-f")) { fullscreen = true; } if(argc > 4) { WINDOW_WIDTH = atoi(argv[3]); WINDOW_HEIGHT = atoi(argv[4]); } } } else { printf("Usage: visualizer -r [-f width height]\n visualizer <filename> [-f width height]\n\n -r: record from default audio source\n filename: audio file to play\n\n -f width height: fullscreen at width*height resolution.\n", argv[0]); return 0; } // Intialize SDL, OpenGL context, etc. if (init() == false) { return -1; } printf("\nInitialization complete. Enjoy!\n"); shader_init(); // Uniform locations GLint time_loc = glGetUniformLocation(p, "time"); GLint amplitude_loc = glGetUniformLocation(p, "amplitude"); GLint high_freq_loc = glGetUniformLocation(p, "high_freq"); GLint low_freq_loc = glGetUniformLocation(p, "low_freq"); GLint texture_loc = glGetUniformLocation(p, "texture"); GLint low_freq_max_loc = glGetUniformLocation(p, "low_freq_max"); // Scene // // Sphere GLUquadric* quadric = gluNewQuadric(); gluQuadricNormals(quadric, GLU_SMOOTH); gluQuadricTexture(quadric, GL_TRUE); gluQuadricOrientation(quadric, GLU_OUTSIDE); // Lights GLfloat light_0_ambient[] = {0.2f, 0.2f, 0.2f, 1.0f}; GLfloat light_0_diffuse[] = {1.0f, 1.0f, 1.0f, 1.0f}; GLfloat light_0_position[] = {0.0f, 0.0f, 1.0f, 0.0f}; glLightfv(GL_LIGHT0, GL_AMBIENT, light_0_ambient); glLightfv(GL_LIGHT0, GL_DIFFUSE, light_0_diffuse); glLightfv(GL_LIGHT0, GL_POSITION, light_0_position); glEnable(GL_LIGHT0); glEnable(GL_LIGHTING); glEnable(GL_COLOR_MATERIAL); // Textures and FBOs glGenTextures(1, &fbo_texture_id); glBindTexture(GL_TEXTURE_2D, fbo_texture_id); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE); // automatic mipmap generation included in OpenGL v1.4 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, FBO_TEXTURE_WIDTH, FBO_TEXTURE_HEIGHT, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); glBindTexture(GL_TEXTURE_2D, 0); glGenFramebuffersEXT(1, &fbo_id); glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo_id); glGenRenderbuffersEXT(1, &rbo_id); glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, rbo_id); glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT, FBO_TEXTURE_WIDTH, FBO_TEXTURE_HEIGHT); glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, 0); glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, fbo_texture_id, 0); glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, rbo_id); glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); bool quit = false; unsigned int length; bool playing = false; bool recording = false; bool looping = true; unsigned int recordpos = 0; unsigned int playpos = 0; int i; float instant_spectrum[256]; float instant_spectrum_l[256]; float instant_spectrum_r[256]; float rot_angle; while (quit == false) { // Grab spectrums result = channel->getSpectrum(instant_spectrum_l, 256, 0, FMOD_DSP_FFT_WINDOW_RECT); if(!record) { result = channel->getSpectrum(instant_spectrum_r, 256, 1, FMOD_DSP_FFT_WINDOW_RECT); } FMODErrorCheck(result); // Merge stereo for(i = 0; i < 256; i++) { if(record) { instant_spectrum[i] = 10.0f * (float)log10(instant_spectrum_l[i]/2.0f) * 2.0f; } else { instant_spectrum[i] = 10.0f * (float)log10((instant_spectrum_l[i] + instant_spectrum_r[i])/2.0f) * 2.0f; } } //instant_spectrum[255] = 0; // Rolling spectrum average for(i = 7; i >= 1; i = i - 1) { arrayCopy(256, spectrum[i-1], spectrum[i]); } arrayCopy(256, instant_spectrum, spectrum[0]); int j; for(j = 0; j < 256; j++) { rolling_spectrum[j] = 0; for(i = 0; i < 8; i++) { rolling_spectrum[j] += spectrum[i][j]; } rolling_spectrum[j] = rolling_spectrum[j] / 8.0f; } float max = -100.0f; int max_index = 0; for(i = 0; i < 256; i++) { if(rolling_spectrum[i] > max) { max = rolling_spectrum[i]; max_index = i; } } // Normalize float low_avg = 0; float low_mid_avg = 0; float mid_avg = 0; float high_avg = 0; float low_max = 0; float low_mid_max = 0; float mid_max = 0; float high_max = 0; int low_max_index = 0; int low_mid_max_index = 0; int mid_max_index = 0; int high_max_index = 0; for(i = 0; i < 256; i++) { processed_spectrum[i] = (rolling_spectrum[i] + 100)/(100); if(i < 64) { low_avg += processed_spectrum[i]; if(processed_spectrum[i] > low_max) { low_max = processed_spectrum[i]; low_max_index = i; } } else if(i < 128 && i >= 64) { low_mid_avg += processed_spectrum[i]; if(processed_spectrum[i] > low_mid_max) { low_mid_max = processed_spectrum[i]; low_mid_max_index = i; } } else if(i < 196 && i >= 128) { mid_avg += processed_spectrum[i]; if(processed_spectrum[i] > mid_max) { mid_max = processed_spectrum[i]; mid_max_index = i; } } else if(i < 256 && i >= 196 ) { high_avg += processed_spectrum[i]; if(processed_spectrum[i] > high_max) { high_max = processed_spectrum[i]; high_max_index = i; } } } low_avg = low_avg/64.0f; low_mid_avg = low_mid_avg/64.0f; mid_avg = mid_avg/64.0f; high_avg = high_avg/64.0f; float high_freq_avg = 0; float low_freq_avg = 0; float high_freq_max = spectrum_freq*(low_mid_max_index+1); float low_freq_max = spectrum_freq*(low_max_index+1); for(i = 63; i >= 1; i = i-1) { low_freq_samples[i] = low_freq_samples[i-1]; high_freq_samples[i] = high_freq_samples[i-1]; } high_freq_samples[0] = high_freq_max; low_freq_samples[0] = low_freq_max; for(i = 0; i < 64; i++) { high_freq_avg += high_freq_samples[i]; low_freq_avg += low_freq_samples[i]; } high_freq_avg = high_freq_avg / 64.0f; low_freq_avg = low_freq_avg / 64.0f; //printf("dominant high freq: %f dominant low freq: %f\n", high_freq_avg, low_freq_avg); // OpenGL // Uniforms for shaders glUniform1f(time_loc, (GLfloat)SDL_GetTicks()*0.001); //glUniform1f(amplitude_loc, 8.0f*smoothstep(-1, 1, log(low_mid_max/low_mid_avg))); glUniform1f(amplitude_loc, 0.5/normalize(low_avg, low_max)); glUniform1f(high_freq_loc, high_freq_avg); glUniform1f(low_freq_loc, low_freq_avg); glUniform1f(low_freq_max_loc, low_freq_max); printf("low: %f high: %f midmax-mid %f\n", low_freq_avg, high_freq_avg, 1/normalize(low_avg, low_max)); // Into the FBO glViewport(0, 0, FBO_TEXTURE_WIDTH, FBO_TEXTURE_HEIGHT); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(60.0f, (float)(FBO_TEXTURE_WIDTH)/FBO_TEXTURE_HEIGHT, 1.0f, 100.0f); glMatrixMode(GL_MODELVIEW); glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo_id); glClearColor(1, 1, 1, 1); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glTranslatef(0.0f, 0.0f, -50.0f); glColor4f(0.4f, 0.2f, 1.0f, 1.0f); gluSphere(quadric, 8.0f, 64, 64); glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); glBindTexture(GL_TEXTURE_2D, fbo_texture_id); glGenerateMipmapEXT(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, 0); // Normal render glViewport(0, 0, (GLsizei) WINDOW_WIDTH, (GLsizei) WINDOW_HEIGHT); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(60.0f, (GLfloat)WINDOW_WIDTH/(GLfloat)WINDOW_HEIGHT, 0.1f, 100.0f); glMatrixMode (GL_MODELVIEW); glLoadIdentity(); glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity (); glBindTexture(GL_TEXTURE_2D, fbo_texture_id); glUniform1f(texture_loc, fbo_texture_id); rot_angle += 0.9f; glTranslatef(0.0f, 0.0f, -40.0f); glRotatef(rot_angle,0.0f,1.0f,0.0f); glRotatef(20,0.0f,0.0f,1.0f); glColor4f(0.4f, 0.2f, 1.0f, 1.0f); gluSphere(quadric, 8.0f, 64, 64); glFlush(); glFinish(); SDL_GL_SwapBuffers(); // FMOD fmod_system->update(); result = sound->getLength(&length, FMOD_TIMEUNIT_PCM); FMODErrorCheck(result); result = fmod_system->isRecording(0, &recording); FMODErrorCheck(result); result = fmod_system->getRecordPosition(0, &recordpos); FMODErrorCheck(result); if (channel) { result = channel->isPlaying(&playing); FMODErrorCheck(result); result = channel->getPosition(&playpos, FMOD_TIMEUNIT_PCM); FMODErrorCheck(result); } //printf("State: %-19s. Record pos = %6d : Play pos = %6d : Loop %-3s\r", recording ? playing ? "Recording / playing" : "Recording" : playing ? "Playing" : "Idle", recordpos, playpos, looping ? "On" : "Off"); // SDL while (SDL_PollEvent(&event)) { if(event.type == SDL_QUIT) { quit = true; } else if(event.type == SDL_KEYDOWN) { switch(event.key.keysym.sym) { case SDLK_ESCAPE: quit = true; break; case SDLK_f: break; } } } } fmod_system->release(); SDL_Quit(); return 0; }