/* 然后是三个UCCI指令解释器 * 其中第一个解释器"BootLine()"最简单,只用来接收引擎启动后的第一行指令 * 输入"ucci"时就返回"e_CommUcci",否则一律返回"e_CommNone" * 前两个解释器都等待是否有输入,如果没有输入则执行待机指令"Idle()" * 而第三个解释器("BusyLine()",只用在引擎思考时)则在没有输入时直接返回"e_CommNone" */ CommEnum BootLine(void) { const char *LineStr; LineStr = ReadInput(); while (LineStr == NULL) { Idle(); LineStr = ReadInput(); } if (strcmp(LineStr, "ucci") == 0) { return e_CommUcci; } else { return e_CommNone; } }
void SearchMv::statusCheck(s_searchParamas* params) { // check if time up, or interrupt from GUI if(params->timeset == true && returnMillisecs() > params->stoptime) params->stopped = true; ReadInput(params); }
void GlobalMasterFreeEnergy::user_initialize() { //----------------------------------------------------------------- // read all the input from config //----------------------------------------------------------------- iout << iINFO << " FREE ENERGY PERTURBATION CONFIG\n"; iout << iINFO << "***********************************\n"; int config_len = strlen(config); if ( config_len < 10000 ) { iout << config; } else { char *new_config = new char[10000 + 10]; strncpy(new_config,config,10000); new_config[10000] = 0; strcat(new_config,"\n...\n"); iout << new_config; delete [] new_config; } iout << iINFO << "***********************************\n" << endi; ReadInput(config, m_RestraintManager, m_LambdaManager, *this, simParams->dt); // exit if there aren't enough steps to complete all pmf & mcti blocks int Total = m_LambdaManager.GetTotalNumSteps(); if (Total > simParams->N) { iout << "FreeEnergy: Not enough steps to complete pfm & mcti blocks" << std::endl; iout << "FreeEnergy: Num Steps Needed = " << Total << std::endl; iout << "FreeEnergy: Num Steps Requested = " << simParams->N << std::endl << endi; NAMD_die("FreeEnergy: Fatal Run-Time Error"); } }
int main(int argc , char*argv[]){ My402List node ; FILE *fp = NULL; struct stat statbuf; if(argc != 2 && argc != 3 ){ fprintf(stderr, "Please enter correct command- warmup1 sort [tfile]\n"); exit(1); } if(strcmp(argv[1],"sort") != 0){ fprintf(stderr, "Please enter correct command- warmup1 sort [tfile]\n"); exit(1); } if(argc == 2){ fp = stdin; } else if(argc == 3){ fp = fopen(argv[2], "r"); if(fp == NULL){ fprintf(stderr, "File \"%s\" not found\n",argv[2]); exit(1); } stat(argv[2], &statbuf); if(S_ISDIR(statbuf.st_mode)){ fprintf(stderr, "\"%s\" is a directory\n",argv[2]); exit(1); } } memset(&node,0,sizeof(My402List)); if(!My402ListInit(&node)){ fprintf(stderr,"Error while init!!\n"); } if(!ReadInput(fp,&node)){ fprintf(stderr,"Error while reading input!\n"); } PrintStatement(&node); return 0; }
int _tmain(int argc, _TCHAR* argv[]) { JaimeChapinal me; me.SetEmail("*****@*****.**"); me.SetWeb("www.jaimechapinal.com"); me.SetTelephone("678-97-57-76"); me.SetStudies(); me.SetPublications(); me.SetJobs(); me.SetGames(); me.SetSkills(); ShowTitle(me); bool bExit = false; int iOption = -1; while (!bExit) { ShowMainMenu(); iOption = ReadInput(); switch (iOption) { case 1: //Personal data ShowPersonalData(me); break; case 2: //Studies data ShowStudiesData(me.GetStudies()); break; case 3: //Professional data ShowPublications(me.GetPublications()); break; case 4: //Professional data ShowProfessionalData(me.GetJobs()); break; case 5: //Games ShowGames(me.GetGames()); break; case 6: //Skills ShowSkills(me.GetSkills()); break; case 0: //Exit bExit = true; break; default: std::cout << "Invalid option. Please, try again. " << std::endl; std::cout << std::endl; break; } } std::cout << std::endl; std::cout << "Thanks for your time! =) " << std::endl; getch(); return 0; }
void inital() { int i; ReadInput(); OptHub(); InitalVDenisty(); for(i=1;i<=Vnum;i++) InitHubDenisty(i); std::sort(HubDensityList.begin(),HubDensityList.end(),comphd); }
void main(void) { /* Write your local variable definition here */ /*** Processor Expert internal initialization. DON'T REMOVE THIS CODE!!! ***/ PE_low_level_init(); /*** End of Processor Expert internal initialization. ***/ /* Write your code here */ /* For example: for(;;) { } */ //Flash_Erase_Page(0xE000); //Flash_Program_Byte(0xE002,0x03); //valor minimo cero, valor maximo 600 ancho del pulso 31 mode = SETPOINT; switch(mode) { case NORMAL : { PTCD_PTCD0 = 1; //Delay1s(TIMEINIT); for(;;){ ReadInput(&interm); SetDisp(interm); } } break; case SETPOINT : { PTCD_PTCD0 = 1; //Delay1s(5); ReadSetPoint(&interm); Flash_Erase_Page(0xE000); Flash_Program_Byte(0xE000, ADCRH); Flash_Program_Byte(0xE001, ADCRL); flash = u16Flash_ReadWord(0xE000); for(;;){ //ReadSetPoint(&interm); SetDisp(interm); } } break; } /*** Don't write any code pass this line, or it will be deleted during code generation. ***/ /*** Processor Expert end of main routine. DON'T MODIFY THIS CODE!!! ***/ for(;;){} /*** Processor Expert end of main routine. DON'T WRITE CODE BELOW!!! ***/ } /*** End of main routine. DO NOT MODIFY THIS TEXT!!! ***/
void Modal::Process() { Show(); while (!Done()) { ReadInput(); ProcessInput(); } GetDialogObjectsData(); }
int main(int argc, const char **argv) try { if (argc != 3) throw std::runtime_error("Invalid input. Usage: atlas_packer.exe params.json output.json"); auto jsonRoot = ReadInput(argv[1]); int width = jsonRoot["size"][0].asInt(); int height = jsonRoot["size"][1].asInt(); rbp::MaxRectsBinPack packer(width, height, false); std::vector<rbp::Rect> resultRects; for (auto it : jsonRoot["inputRects"]) { int rectWidth = it[0].asInt(); int rectHeight = it[1].asInt(); auto rect = packer.Insert(rectWidth, rectHeight, rbp::MaxRectsBinPack::FreeRectChoiceHeuristic::RectBestAreaFit); if ((rect.height > 0) && (rect.width == rectWidth) && (rect.height == rectHeight)) resultRects.push_back(rect); else throw std::runtime_error("Atlas Packer: failed to pack"); } Json::Value result; result["rects"] = Json::Value(Json::arrayValue); for (auto r : resultRects) { Json::Value jsonRect; jsonRect["x"] = r.x; jsonRect["y"] = r.y; jsonRect["w"] = r.width; jsonRect["h"] = r.height; result["rects"].append(jsonRect); } std::ofstream outf(argv[2]); Json::StreamWriterBuilder b; b["indentation"] = " "; outf << Json::writeString(b, result); return outf.bad() ? 1 : 0; } catch (std::exception &e) { std::cerr << "An error occurred:\n" << e.what() << "\n"; return 1; }
void main() { ReadInput(); path_vec shortestPath; //最短路径 int length = Dijkstra(shortestPath); paths.push_back(std::make_pair(length,shortestPath)); //找到最短路径 //PrintPath(shortestPath, length); for(unsigned int i=0; i<shortestPath.size()-1; i++) { path_vec path1; //去掉一条边以后的最短路径 memcpy(crt_map1, origin_map, sizeof(origin_map)); RemoveEdge(shortestPath[i], shortestPath[i+1]); //删除一条边以后找出最短路径 length = Dijkstra(path1); if(length==0) continue; paths.push_back(std::make_pair(length, path1)); //PrintPath(path1, length); for(unsigned int j=0; j<path1.size()-1; j++) { path_vec path2; //删除第二条边以后的最短路径 memcpy(crt_map2, crt_map1, sizeof(crt_map1)); RemoveEdge(path1[j], path1[j+1], crt_map2); length = Dijkstra(path2); if(length==0) continue; paths.push_back(std::make_pair(length, path2)); } } //将找到的路径排序,然后输出(会存在路径长度相同但是路线不同的路径) std::sort(paths.begin(), paths.end(), Compare); //删除重复的路径 RemoveDunplicated(paths); int outputCount = 0; for(paths_vec_iter iter = paths.begin(); iter != paths.end(); iter++) { if(outputCount++ > K) break; PrintPath(iter->second, iter->first); } }
// // Main Routine // int main(int argc, const char *argv[]) { if(argc < 4) FatalError("Usage: qbin2c <infile> <outfile> <symbol>"); // read input file ReadInput(argv[1]); // write output file WriteOutput(argv[1], argv[2], argv[3]); printf("%s written successfully.\n", argv[2]); return 0; }
void PS2_Guitar::ReadInputGuitar(const bool config, u8 *buffer) { if(config) ReadInput(buffer); else ReadInputPressure(buffer); buffer[3] &= 0x7F; // Switch off LEFT DPAD for some reason. // 9 - A // A - F // E - 9 // F - E u8 bitswap[4] = {0}; bitswap[0] = (buffer[4] & 0x2)? 0: 1 << 2; // 9 - A bitswap[1] = (buffer[4] & 0x4)? 0: 1 << 7; // A - F bitswap[2] = (buffer[4] & 0x40)? 0: 1 << 1; // E - 9 bitswap[3] = (buffer[4] & 0x80)? 0: 1 << 6; // F - E buffer[4] |= 0xC6; buffer[4] &= ~(bitswap[0] + bitswap[1] + bitswap[2] + bitswap[3]); }
// PROCESS SOURCE FILE local void ProcessSource( char *src_file ) // - starting file { int kw; // - current key-word ProcessMode = MODE_OUTPUT; SegStk = NULL; SourceText = NULL; Files = NULL; OpenFileNormal( src_file, "r" ); while( Files != NULL ) { kw = ReadInput(); if( kw == KW_EOF ) { CloseFile(); } else { ProcessRecord( kw, Record ); } } }
/**************************************************************************//** * @brief Performs the actual transfer of a byte * * @param[in] data actual data to be passed towards spi * * @return actual data to be received from spi *****************************************************************************/ uint8_t SPI_XferSpi(uint8_t _Data) { uint8_t l_Result; uint8_t l_Size; uint16_t delay_count; l_Result = 0; // ensure initialised to zero(0); // clock in/out data (LSB first) for (l_Size=8; l_Size; l_Size--) { // output data, NOTE: before falling edge of SCK so signals don't all change at same time if (_Data & 0x80) SetOutput(DOUT); else ClrOutput(DOUT); // falling edge of SCK and Data out ClearSCK(); #if defined(NRF52) // nrf_delay_us(1); // for(delay_count = 0; delay_count < 17; delay_count++) // { // __ASM volatile (" NOP\n"); // } #endif // prepare for next bit out/in _Data <<= 1; l_Result <<= 1; // rising edge of SCK to latch data SetSCK(); // read in data if (ReadInput(DIN)) l_Result |= 0x01; } return l_Result; }
void Game::InitGameAux() { int targetCount, speed, time; ReadInput(targetCount, speed, time); if (targetCount < 0) targetCount = 0; if (targetCount > 30) targetCount = 30; if (time < 0) time = 0; if (time > 1000) time = 1000; if (speed < 0) speed = 0; if (speed > 1000) speed = 300; _objects.clear(); for (int q = 0; q < targetCount; q++) { const char *const texArr[] = {"azure", "blue", "green", "magenta"}; Render::Texture *const tex = Core::resourceManager.getTexture(texArr[::rand() % _countof(texArr)]); const FPoint pos(Target::Size().x + ::rand() % int(Core::appInstance->GAME_CONTENT_WIDTH - 2 * Target::Size().x), Target::Size().y + ::rand() % int(Core::appInstance->GAME_CONTENT_HEIGHT - 2 * Target::Size().y)), vel(FPoint((::rand() % 100 < 50? -1: 1) * float(100 + ::rand() % 200), (::rand() % 100 < 50? -1: 1) * float(100 + ::rand() % 200)) / 2); _objects.push_back(std::tr1::shared_ptr<Object >(new Target(this, tex, pos, vel))); } _objects.push_back(std::tr1::shared_ptr<Object >(new Cannon(this, speed))); _time = float(time); }
CommEnum BusyLine(int /* bool */ Debug) { const char *LineStr; LineStr = ReadInput(); if (LineStr == NULL) { return e_CommNone; } else { if (Debug) { printf("info string %s\n", LineStr); fflush(stdout); } // "BusyLine"只能接收"isready"、"ponderhit"和"stop"这三条指令 if (strcmp(LineStr, "isready") == 0) { return e_CommIsReady; } else if (strcmp(LineStr, "ponderhit") == 0) { return e_CommPonderHit; } else if (strcmp(LineStr, "stop") == 0) { return e_CommStop; } else { return e_CommNone; } } }
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) { struct input *X,*Y; int n,N; double *vec_double; int *vec; if(nrhs != 2) mexErrMsgIdAndTxt("SpikeInfo:MultiSiteSubset:numArgs","2 input arguments required."); if(nlhs != 1) mexErrMsgIdAndTxt("SpikeInfo:MultiSiteSubset:numArgs","1 output argument required."); X = ReadInput(prhs[0]); N = mxGetNumberOfElements(prhs[1]); vec_double = mxGetPr(prhs[1]); vec = (int *)mxMalloc(N*sizeof(int)); for(n=0;n<N;n++) { vec[n] = ((int)vec_double[n])-1; if(vec[n]>=X[0].N) { mxFreeInput(X); mxFree(vec); mexErrMsgIdAndTxt("SpikeInfo:MultiSiteSubset:outOfRange","Index in vec exceeds number of sites in X."); } } Y = MultiSiteSubsetComp(X,vec,N); plhs[0]=WriteInput(Y,1); mxFreeInput(X); mxFree(vec); return; }
Boolean PipeStruct::LineInput(char *szLineStr) { if (GetBuffer(szLineStr)) { return TRUE; } if (CheckInput()) { ReadInput(); if (GetBuffer(szLineStr)) { return TRUE; } else { if (nReadEnd == LINE_INPUT_MAX_CHAR) { memcpy(szLineStr, szBuffer, LINE_INPUT_MAX_CHAR - 1); szLineStr[LINE_INPUT_MAX_CHAR - 1] = '\0'; szBuffer[0] = szBuffer[LINE_INPUT_MAX_CHAR - 1]; nReadEnd = 1; return TRUE; } else { return FALSE; } } } else { return FALSE; } }
void CVtConsoleInputController::RunL() { TInt err = iStatus.Int(); #ifdef FSHELL_PLATFORM_OPP if (err == KErrAbort) { ReadInput(); return; } #endif if (err == KErrNone) { ReadKeyPress(); } else if (iClientRequestStatus) { CompleteKeyPressRequest(err); } else { // Report the error next time the client requests a key. iInputError = err; } }
/*--------------main function---------------*/ int main(int argc, char **argv){ const CHAR *fn = __func__; InputParams XLAL_INIT_DECL(inputs); REAL8 srate = 16384.0; /*sample rate defaulted to 16384 */ /* read in command line input args */ ReadInput( &inputs, argc, argv ); LALStatus XLAL_INIT_DECL(status); EphemerisData *edat; if ( (edat = InitEphemeris ( inputs.ephemType, inputs.ephemDir)) == NULL ){ XLALPrintError ( "%s: Failed to init ephemeris data\n", fn ); XLAL_ERROR ( XLAL_EFUNC ); } /*init detector info */ LALDetector *site; if ( ( site = XLALGetSiteInfo ( inputs.det )) == NULL ){ XLALPrintError("%s: Failed to get site-info for detector '%s'\n", fn, inputs.det ); XLAL_ERROR ( XLAL_EFUNC ); } if( inputs.geocentre ){ /* set site to the geocentre */ site->location[0] = 0.0; site->location[1] = 0.0; site->location[2] = 0.0; } struct dirent **pulsars; INT4 n=scandir(inputs.pulsarDir, &pulsars, 0, alphasort); if ( n < 0){ XLALPrintError("scandir failed\n"); XLAL_ERROR(XLAL_EIO); } UINT4 numpulsars = (UINT4)n; UINT4 h=0; CHAR parname[256]; PulsarParameters *pulparams[numpulsars]; for(h=2; h<numpulsars; h++){ if(strstr(pulsars[h]->d_name,".par") == NULL){ free(pulsars[h]); continue; } else{ sprintf(parname,"%s/%s", inputs.pulsarDir, pulsars[h]->d_name); fprintf(stderr, "%s\n", parname); FILE *inject; if (( inject = fopen ( parname, "r" )) == NULL ){ fprintf(stderr,"Error opening file: %s\n", parname); XLAL_ERROR ( XLAL_EIO ); } pulparams[h] = XLALReadTEMPOParFile( parname ); fclose( inject ); } } LIGOTimeGPS epoch; UINT4 ndata; epoch.gpsSeconds = inputs.epoch; epoch.gpsNanoSeconds = 0; ndata = inputs.frDur; REAL8TimeSeries *series=NULL; CHAR out_file[256]; sprintf(out_file, "%s-%s-%d-%d.gwf", inputs.det, inputs.outStr, epoch.gpsSeconds, ndata ); LALFrameH *outFrame = NULL; if ((outFrame = XLALFrameNew( &epoch, (REAL8)ndata, inputs.channel, 1, 0, 0 )) == NULL) { LogPrintf(LOG_CRITICAL, "%s : XLALFrameNew() filed with error = %d.\n", fn, xlalErrno); XLAL_ERROR( XLAL_EFAILED); } if ((series = XLALCreateREAL8TimeSeries( inputs.channel, &epoch, 0., 1./srate,&lalSecondUnit, (int)(ndata*srate) )) == NULL) { XLAL_ERROR( XLAL_EFUNC ); } UINT4 counter=0; for (counter = 0; counter < series->data->length; counter++) series->data->data[counter] = 0; /*** Read Pulsar Data ***/ for (h=0; h < numpulsars; h++){ if(strstr(pulsars[h]->d_name,".par")==NULL){ free(pulsars[h]); continue; } else{ PulsarSignalParams XLAL_INIT_DECL(params); /* set signal generation barycenter delay look-up table step size */ params.dtDelayBy2 = 10.; /* generate table every 10 seconds */ if (( params.pulsar.spindown = XLALCreateREAL8Vector(1)) == NULL ){ XLALPrintError("Out of memory"); XLAL_ERROR ( XLAL_EFUNC ); } INT4 dtpos = 0; if ( PulsarCheckParam(pulparams[h], "POSEPOCH") ) dtpos = epoch.gpsSeconds - (INT4)PulsarGetREAL8Param(pulparams[h], "POSEPOCH"); else dtpos = epoch.gpsSeconds - (INT4)PulsarGetREAL8Param(pulparams[h], "PEPOCH"); REAL8 ra = 0., dec = 0.; if ( PulsarCheckParam( pulparams[h], "RAJ" ) ) { ra = PulsarGetREAL8Param( pulparams[h], "RAJ" ); } else if ( PulsarCheckParam( pulparams[h], "RA" ) ){ ra = PulsarGetREAL8Param( pulparams[h], "RA" ); } else{ XLALPrintError("No right ascension found"); XLAL_ERROR ( XLAL_EFUNC ); } if ( PulsarCheckParam( pulparams[h], "DECJ" ) ) { dec = PulsarGetREAL8Param( pulparams[h], "DECJ" ); } else if ( PulsarCheckParam( pulparams[h], "DEC" ) ){ dec = PulsarGetREAL8Param( pulparams[h], "DEC" ); } else{ XLALPrintError("No declination found"); XLAL_ERROR ( XLAL_EFUNC ); } params.pulsar.position.latitude = dec + (REAL8)dtpos * PulsarGetREAL8ParamOrZero(pulparams[h], "PMDEC"); params.pulsar.position.longitude = ra + (REAL8)dtpos * PulsarGetREAL8ParamOrZero(pulparams[h], "PMRA") / cos(params.pulsar.position.latitude); params.pulsar.position.system = COORDINATESYSTEM_EQUATORIAL; REAL8Vector *fs = PulsarGetREAL8VectorParam(pulparams[h], "F"); if ( fs->length == 0 ){ XLALPrintError("No frequencies found"); XLAL_ERROR ( XLAL_EFUNC ); } params.pulsar.f0 = 2.*fs->data[0]; if ( fs->length > 1 ){ params.pulsar.spindown->data[0] = 2.*fs->data[1]; } if (( XLALGPSSetREAL8(&(params.pulsar.refTime), PulsarGetREAL8Param(pulparams[h], "PEPOCH")) ) == NULL ) XLAL_ERROR ( XLAL_EFUNC ); params.pulsar.psi = PulsarGetREAL8ParamOrZero(pulparams[h], "PSI"); params.pulsar.phi0 = PulsarGetREAL8ParamOrZero(pulparams[h], "PHI0"); REAL8 cosiota = PulsarGetREAL8ParamOrZero(pulparams[h], "COSIOTA"); REAL8 h0 = PulsarGetREAL8ParamOrZero(pulparams[h], "H0"); params.pulsar.aPlus = 0.5 * h0 * (1. + cosiota * cosiota ); params.pulsar.aCross = h0 * cosiota; /*Add binary later if needed!*/ params.site = site; params.ephemerides = edat; params.startTimeGPS = epoch; params.duration = ndata; params.samplingRate = srate; params.fHeterodyne = 0.; REAL4TimeSeries *TSeries = NULL; LALGeneratePulsarSignal( &status, &TSeries, ¶ms ); if (status.statusCode){ fprintf(stderr, "LAL Routine failed!\n"); XLAL_ERROR (XLAL_EFAILED); } UINT4 i; for (i=0; i < TSeries->data->length; i++) series->data->data[i] += TSeries->data->data[i]; XLALDestroyREAL4TimeSeries(TSeries); XLALDestroyREAL8Vector(params.pulsar.spindown); } } if (XLALFrameAddREAL8TimeSeriesProcData(outFrame,series)){ LogPrintf(LOG_CRITICAL, "%s : XLALFrameAddREAL8TimeSeries() failed with error = %d.\n",fn,xlalErrno); XLAL_ERROR(XLAL_EFAILED); } CHAR OUTFILE[256]; sprintf(OUTFILE, "%s/%s", inputs.outDir, out_file); if ( XLALFrameWrite(outFrame, OUTFILE)){ LogPrintf(LOG_CRITICAL, "%s : XLALFrameWrite() failed with error = %d.\n", fn, xlalErrno); XLAL_ERROR( XLAL_EFAILED ); } XLALFrameFree(outFrame); XLALDestroyREAL8TimeSeries( series ); return 0; }
int main(int argc, char* argv[]) { ISmsProtocolGsm *pGsm = NULL; ISmsMessage *pMessage = NULL; ISmsDeliveryStatus *pDeliveryStatus = NULL; LPSTR lpszMessage = NULL; LPSTR lpszPincode = NULL; BSTR bstrMessageReference = NULL; VARIANT vtVar; HRESULT hr; LONG lLastError; char *cp; BOOL bRequestDeliveryReport = FALSE; LONG lDeliveryStatus = 0L, lDeliveryStatusCode = 0L; BSTR bstrDeliveryStatusTime = NULL, bstrStatusDescription = NULL; BOOL bDeliveryCompleted = FALSE; CoInitialize(NULL); VariantInit( &vtVar ); hr = CoCreateInstance(CLSID_SmsProtocolGsm, NULL, CLSCTX_INPROC_SERVER, IID_ISmsProtocolGsm, (void**) &pGsm); if( SUCCEEDED( hr ) ) hr = CoCreateInstance(CLSID_SmsMessage, NULL, CLSCTX_INPROC_SERVER, IID_ISmsMessage, (void**) &pMessage ); if( ! SUCCEEDED( hr ) ) { printf( "无法创建对象\n" ); goto _EndMain; } // 选择设备 pGsm->put_Device( _bstr_t( "COM1" ) ); pMessage->Clear(); // 接收者号码 pMessage->put_Recipient( _bstr_t( ReadInput( "输入接收者号码,号码必须以+86开头" ) ) ); //定义短信编码方式 pMessage->put_Format( asMESSAGEFORMAT_UNICODE_MULTIPART ); // 短信内容 lpszMessage = ReadInput( "输入短信内容" ); pMessage->put_Data( _bstr_t( lpszMessage ) ); printf( "正在发送信息...\n" ); pGsm->Send( &_variant_t ( ( IDispatch*) pMessage ), &bstrMessageReference ); pGsm->get_LastError( &lLastError ); printf( "发送结果: %ld (%s)\n\n", lLastError, GetErrorDescription( lLastError, pGsm ) ); goto _EndMain; _EndMain: if( pGsm != NULL ) pGsm->Release(); if( pMessage != NULL ) pMessage->Release(); if( bstrMessageReference != NULL ) SysFreeString( bstrMessageReference ); CoUninitialize(); printf("结束...\n"); return 0; }
int main() { int nprob, curprob, probsz, ret, index, i; if(fgets(&(inbuf[0]), 255, stdin) == NULL) { fprintf(stderr, "Read failed on problem count\n"); return -1; } if(sscanf(&(inbuf[0]), "%d", &nprob) != 1) { fprintf(stderr, "Scan failed on problem count\n"); return -2; } for(i = 0 ; i < HASH_SIZE ; i++) { scanHash[i] = NULL; } for(curprob = 1; curprob <= nprob ; curprob++) { if(fgets(&(inbuf[0]), 255, stdin) == NULL) { fprintf(stderr, "Read failed on problem %d size\n", curprob); CleanGlobal(); return -3; } if(sscanf(&(inbuf[0]), "%d %d", &index, &probsz) != 2) { fprintf(stderr, "Scan failed on problem %d size\n", curprob); CleanGlobal(); return -4; } if((probsz < 3) || (probsz > MAX_POINTS)) { fprintf(stderr, "problem size %d is < 3 or > %d in problem %d\n", probsz, MAX_POINTS, curprob); CleanGlobal(); return -5; } if(index != curprob) { fprintf(stderr, "problem index %d not = expected problem %d\n", index, curprob); CleanGlobal(); return -7; } if((ret = ReadInput(probsz, curprob)) != 0) { CleanGlobal(); return ret; } if((ret = BuildScans(probsz, curprob)) != 0) { CleanGlobal(); return ret; } if((ret = BuildHullEdges(curprob)) != 0) { CleanGlobal(); return ret; } if((ret = BuildHullVerts(curprob)) != 0) { CleanGlobal(); return ret; } PrintSolution(curprob); CleanLocal(); } CleanGlobal(); return 0; }
int main() { ofstream outFile; ifstream inFile; //IN - file used in the function string inFileName; //IN - name of file the user will enter string outFileName; MovieInfo *head; // MovieInfo *headPtr; bool validMenuChoice; int menuChoice; Menu commandMenu; bool quit; quit = false; head = NULL; commandMenu = OUTPUT; GetFileNames(inFile,outFile,"Input"); GetFileNames(inFile,outFile,"Output"); head = ReadInput(head,inFile); // PrintHeader("Searching Linked List",'A',7,cout); // PrintHeader("Searching Linked List",'A',7,outFile); while(commandMenu != EXIT) { // do // { cout << "DVD MENU OPTIONS" << endl << endl; cout << "1 - Output Entire List" << endl; cout << "2 - Title Search" << endl; cout << "3 - Genre Search" << endl; cout << "4 - Actor Search" << endl; cout << "5 - Year Search" << endl; cout << "6 - Rating Search (0-9)"<< endl; cout << "0 - EXIT" << endl; menuChoice = ErrorCheckingMenu ("Enter an option (0 to exit): ", "**** The number is an invalid entry ****", "**** Please input a number between 0 and 6 ****", 6,0 ); // }while(); if(menuChoice > 0) { commandMenu = Menu(menuChoice); } if (commandMenu == OUTPUT && menuChoice >0) { cout << endl <<"Listing all movies!" << endl << endl; ListAllMovies(head, outFile); } else if (commandMenu == TITLESEARCH || commandMenu == GENRESEARCH || commandMenu == ACTORSEARCH || commandMenu == YEARSEARCH || commandMenu == RATINGSEARCH ) { SearchLinkedList(head,commandMenu, outFile); } } cout <<"Done reading File"; cout << "Done outputting File"; inFile.close(); outFile.close(); return 0; }
int main(int argc, char* argv[]) { IMmsProtocolMm1 *pMm1Protocol = NULL; IMmsSlide *pSlide = NULL; IMmsMessage *pMessage = NULL; LPSTR lpszPincode = NULL; HRESULT hr; LONG lLastError; CoInitialize(NULL); hr = CoCreateInstance(CLSID_MmsProtocolMm1, NULL, CLSCTX_INPROC_SERVER, IID_IMmsProtocolMm1, (void**) &pMm1Protocol); if( SUCCEEDED( hr ) ) hr = CoCreateInstance(CLSID_MmsSlide, NULL, CLSCTX_INPROC_SERVER, IID_IMmsSlide, (void**) &pSlide ); if( SUCCEEDED( hr ) ) hr = CoCreateInstance(CLSID_MmsMessage, NULL, CLSCTX_INPROC_SERVER, IID_IMmsMessage, (void**) &pMessage ); if( ! SUCCEEDED( hr ) ) { printf( "无法创建对象.\n" ); goto _EndMain; } pSlide->Clear(); // 增加幻灯片中的图片和文本 pSlide->AddAttachment( _bstr_t( "test.jpg" ) ); pSlide->AddText( _bstr_t( "这里可以输入文本信息" ) ); pMessage->Clear(); // 接收者号码 pMessage->AddRecipient( _bstr_t( ReadInput( "输入接收者号码(号码必须以'+86'开头)" ) ), asMMS_RECIPIENT_TO ); // 彩信主题 pMessage->put_Subject( _bstr_t("此处为彩信主题") ); // 增加幻灯片 pMessage->AddSlide( &_variant_t ( ( IDispatch*) pSlide ) ); pMm1Protocol->Clear(); // 选择发送设备 pMm1Protocol->put_Device( _bstr_t( "标准 33600 bps 调制解调器" ) ); // 中国移动彩信发送配置 pMm1Protocol->put_ProviderMMSC( _bstr_t("http://mmsc.monternet.com") ); pMm1Protocol->put_ProviderAPN( _bstr_t( "cmwap" ) ); pMm1Protocol->put_ProviderAPNAccount( _bstr_t( "") ); pMm1Protocol->put_ProviderAPNPassword( _bstr_t( "") ); pMm1Protocol->put_ProviderWAPGateway( _bstr_t( "10.0.0.172" ) ); /* 中国移动彩信发送配置 pMm1Protocol->put_ProviderMMSC( _bstr_t( "http://mmsc.myuni.com.cn" ) ); pMm1Protocol->put_ProviderAPN( _bstr_t( "UNIWAP" ) ); pMm1Protocol->put_ProviderAPNAccount( _bstr_t( "") ); pMm1Protocol->put_ProviderAPNPassword( _bstr_t( "") ); pMm1Protocol->put_ProviderWAPGateway( _bstr_t( "10.0.0.172" ) ); */ // 连接gprs网络 printf( "正在拨号gprs网络...\n" ); pMm1Protocol->Connect(); pMm1Protocol->get_LastError( &lLastError ); printf( "结果: %ld (%s)\n\n", lLastError, GetErrorDescription( lLastError, pMm1Protocol ) ); if( lLastError != 0L ) goto _EndMain; // 发送彩信 printf( "正在发送...\n" ); pMm1Protocol->Send( &_variant_t ( ( IDispatch*) pMessage ) ); pMm1Protocol->get_LastError( &lLastError ); printf( "结果: %ld (%s)\n\n", lLastError, GetErrorDescription( lLastError, pMm1Protocol ) ); _EndMain: if( pMm1Protocol != NULL ) { pMm1Protocol->Disconnect(); pMm1Protocol->Release(); } if( pMessage != NULL ) pMessage->Release(); if( pSlide != NULL ) pSlide->Release(); CoUninitialize(); printf("结束.......\n"); return 0; }
// Strong Component Search Code struct TreeNode *AllStrongComponents(int startNode) { int i; struct TreeNode *tn = NULL; // the tree node we'd like to create static int parentTreeNode,lastDfLabel,CallLevel,*dflabels,*low,*strongcomps,*backtracked; // put in call level stuff, but make sure that unvisited nodes can get revisted... if (0 == CallLevel) { if (0 == numNodes) ReadInput(); else {free(dflabels); free(low); free(strongcomps); free(backtracked);} dflabels = (int *)malloc(numNodes*sizeof(int)); low = (int *)malloc(numNodes*sizeof(int)); strongcomps = (int *)malloc(numNodes*sizeof(int)); backtracked = (int *)malloc(numNodes*sizeof(int));} // recursion unrolling condition; only if dfLabel is unset //printf("recursion level %d\n",CallLevel); if (dflabels[startNode] == 0) { tn = (struct TreeNode *)malloc(sizeof(TreeNode)); tn->node_label = startNode; tn->parent = tn; // initialize parent as self tn->first = tn->last = tn->left = tn->right = NULL; if (0 == CallLevel) StackPush(strongcomps,startNode); CallLevel++; for (i = 0; i < nodes[startNode].degree; i++) { // only assign dflabel once, init low if (0 == dflabels[startNode]) { tn->dflabel = dflabels[startNode] = low[startNode] = ++lastDfLabel; printf("dfLabel( %d)=%d, parentNode=%d, low[%d]=%d\n",startNode,lastDfLabel,parentTreeNode,startNode,low[startNode]); printf("stack: ");StackPrintAll(strongcomps);printf("\n");} printf("processing (%d,%d): ",tn->node_label,nodes[startNode].adjNodes[i]); if (0 == dflabels[nodes[startNode].adjNodes[i]]) { printf ("tree-edge\n"); StackPush(strongcomps,nodes[startNode].adjNodes[i]); parentTreeNode = startNode; // tree node building code section struct TreeNode *child = AllStrongComponents(nodes[startNode].adjNodes[i]); if (NULL != child) { child->left = child->right = NULL; child->parent = tn; if (NULL == tn->first) tn->first = tn->last = child; else { child->left = tn->last; tn->last->right = tn->last = child; } // backtracking... backtracked[child->node_label]++; } printf("backtracking %d -> %d\n",nodes[startNode].adjNodes[i],startNode); // update parent's low with child's low if (low[nodes[startNode].adjNodes[i]] < low[startNode]) { low[startNode] = low[nodes[startNode].adjNodes[i]]; printf ("low[%d] = %d on backtrack\n",startNode,low[startNode]); } else printf("No change in low[%d] on backtrack\n",startNode); // check to see if child is entry node for the strong component if (low[nodes[startNode].adjNodes[i]] == dflabels[nodes[startNode].adjNodes[i]]) { printf ("STRONG COMPONENT "); while (StackPeek(strongcomps) != nodes[startNode].adjNodes[i]) printf("%d ",StackPop(strongcomps)); printf("%d ",StackPop(strongcomps)); printf("\n");} } else if (dflabels[nodes[startNode].adjNodes[i]] < dflabels[startNode] && backtracked[nodes[startNode].adjNodes[i]] == 0) { printf ("back-edge\n"); if ((dflabels[nodes[startNode].adjNodes[i]]) < low[startNode]) { low[startNode] = dflabels[nodes[startNode].adjNodes[i]]; printf ("low[%d] = %d on back-edge\n",startNode,low[startNode]);} } else if (backtracked[nodes[startNode].adjNodes[i]] > 0) { printf("cross-edge\n"); if ((dflabels[nodes[startNode].adjNodes[i]]) < low[startNode]) { low[startNode] = dflabels[nodes[startNode].adjNodes[i]]; printf ("low[%d] = %d on cross-edge\n",startNode,low[startNode]);} } } } CallLevel--; // pick unvisited if (0 == CallLevel) { for (i = 0; i < numNodes; i++) { if (0 == dflabels[i]) { struct TreeNode *unvisted = AllStrongComponents(i);; break; }}} return tn; }
/* Allocate memory for main structure and set initial conditions */ CELL *Init() { void ReadInput(); void InitCondEuler(REAL, REAL *); UINT i, j, k, l; REAL dx, U[NVAR], v; CELL *cell; ReadInput(); /* Coefficients for RK3 */ ark[0] = 0.0; ark[1] = 3.0 / 4.0; ark[2] = 1.0 / 3.0; brk[0] = 1.0; brk[1] = 1.0 / 4.0; brk[2] = 2.0 / 3.0; NG = PORD + 2; printf("Allocating memory and setting initial condition ...\n"); cell = (CELL *) calloc(NC, sizeof(CELL)); if(cell == NULL) { printf("Init: Could not allocate cell\n"); exit(0); } dx = (xmax - xmin) / NC; printf("No of cells = %d\n", NC); printf(" dx = %f\n", dx); for(i = 0; i < NC; i++) { cell[i].xl = xmin + i * dx; cell[i].xr = cell[i].xl + dx; cell[i].x = 0.5 * (cell[i].xl + cell[i].xr); cell[i].h = cell[i].xr - cell[i].xl; cell[i].p = PORD; cell[i].ng = NG; cell[i].xg = (REAL *) calloc(cell[i].ng, sizeof(REAL)); GaussPoints(&cell[i]); cell[i].Un = (REAL **) calloc(NVAR, sizeof(REAL *)); cell[i].Uo = (REAL **) calloc(NVAR, sizeof(REAL *)); cell[i].Re = (REAL **) calloc(NVAR, sizeof(REAL *)); for(j = 0; j < NVAR; j++) { cell[i].Un[j] = (REAL *) calloc(cell[i].p, sizeof(REAL)); cell[i].Uo[j] = (REAL *) calloc(cell[i].p, sizeof(REAL)); cell[i].Re[j] = (REAL *) calloc(cell[i].p, sizeof(REAL)); } } /* Set initial condition by L2 projection */ for(i = 0; i < NC; i++) { for(j = 0; j < NVAR; j++) for(k = 0; k < cell[i].p; k++) cell[i].Un[j][k] = 0.0; for(j = 0; j < cell[i].p; j++) for(k = 0; k < cell[i].ng; k++) { InitCondEuler(cell[i].xg[k], U); v = ShapeFun(cell[i].xg[k], &cell[i], j); for(l = 0; l < NVAR; l++) cell[i].Un[l][j] += 0.5 * U[l] * v * wg[cell[i].ng - 1][k]; } } return cell; }
/******************************************************************************************************************************* * TestReadSortAndWrite12BitNumbers * * @brief * Generic routine to provide first read, sort the input data and write the max 32 and last 32 entries using the given * pair of input and output file. * * @return * N/A * *******************************************************************************************************************************/ BOOL TestReadSortAndWrite12BitNumbers(const char* pInputFileName, const char* pOutputFileName) { UINT totalNumEntries, maxBufEntries; FILE* hInputFile = NULL; FILE* hOutputFile = NULL; CircularBuffer cReadBuf = {0}; CircularBuffer cProcessedBuf = {0}; BOOL status = TRUE; if ((pInputFileName == NULL) || (pOutputFileName == NULL)) { printf("ERROR: Invalid input or output file \r\n"); status = FALSE; } if (status == TRUE) { hInputFile = OpenFile(pInputFileName, "rb"); if (hInputFile == NULL) { printf("ERROR: Failed to open input file %s \r\n", pInputFileName); status = FALSE; } } if (status == TRUE) { hOutputFile = OpenFile(pOutputFileName, "wb"); if (hOutputFile == NULL) { printf("ERROR: Failed to open output file %s", pOutputFileName); status = FALSE; } } if (status == TRUE) { totalNumEntries = GetFileEntries(hInputFile); if (totalNumEntries < 1) { printf("Error: Insufficient data in input file \r\n"); status = FALSE; } } if (status == TRUE) { maxBufEntries = (totalNumEntries > MaxNumOfBufEntries) ? MaxNumOfBufEntries : totalNumEntries; cReadBuf.pData = (UCHAR*) malloc(CONVERT_ENTRIES_TO_BYTE(maxBufEntries) * sizeof(UCHAR)); if (cReadBuf.pData == NULL) { printf("ERROR: Unable to allocate 12 DWORDs for read circular buffer \r\n"); status = FALSE; } } if (status == TRUE) { cProcessedBuf.pData = (UCHAR*) malloc(CONVERT_ENTRIES_TO_BYTE(maxBufEntries) * sizeof(UCHAR)); if (cProcessedBuf.pData == NULL) { printf("ERROR: Unable to allocate 12 DWORDs for sorted max circular buffer \r\n"); status = FALSE; } } if (status == TRUE) { UINT entriesToBeRead = totalNumEntries; while (entriesToBeRead != 0) { // Read maximum MaxNumOfBufEntries i.e. 32 entries at a time from input into circular buffer UINT numEntries, ret; numEntries = (entriesToBeRead > MaxNumOfBufEntries) ? MaxNumOfBufEntries : entriesToBeRead; ret = ReadInput(hInputFile, numEntries, &cReadBuf); if (ret != 0) { status = FALSE; break; } ret = ProcessSensorData(&cReadBuf, &cProcessedBuf); if (ret != 0) { status = FALSE; break; } entriesToBeRead -= numEntries; } } if (status == TRUE) { WriteStringToOutput(hOutputFile, "--Sorted Max 32 Values--\r\n"); WriteCBufToOutput(hOutputFile, &cProcessedBuf); // If we have more than 32 entries then we should // all of the last 32 entries in circular buffer and // not just the most recently read entries. if (totalNumEntries > MaxNumOfBufEntries) { cReadBuf.numEntries = MaxNumOfBufEntries; } WriteStringToOutput(hOutputFile, "--Last 32 Values--\r\n"); // Write out max allowed (i.e. 32) last read entries from circular read buffer WriteCBufToOutput(hOutputFile, &cReadBuf); } // Clean up if (hOutputFile != NULL) { CloseFile(hOutputFile); } if (hInputFile != NULL) { CloseFile(hInputFile); } free(cReadBuf.pData); cReadBuf.pData = NULL; free(cProcessedBuf.pData); cProcessedBuf.pData = NULL; return status; }
void RunShell() { int running = 1; char* str; char** argv; InitBackgroundProcessing(); while (running) { CheckProcessQueue(); PrintPrompt(); str = ReadInput(); argv = ParseInput(str); if (argv[0] == NULL) { // do nothing if empty arguments } else if (CheckForIOandPipeErrors(argv)) { // do nothing if IO or pipe error } else if (CheckForBackgroundErrors(argv)) { // do nothing if background processing format error } else if (strcmp(argv[0], "exit") == 0) { BigFree(argv); printf("Exiting Shell...\n"); OnExitProcessQueueWait(); exit(0); } else if (strcmp(argv[0], "cd") == 0) { if (ArraySize(argv) <= 2) { if (ArraySize(argv) == 2) ChangeDirectory(argv[1]); else ChangeDirectory(getenv("HOME")); } else { printf("Too many arguments...\n"); } } else if (strcmp(argv[0], "limits") == 0) { if (ArraySize(argv) > 1) { argv = ArrayRemoveElement(argv, 0); Limits(argv); } } else if (strcmp(argv[0], "etime") == 0) { if (ArraySize(argv) > 1) { argv = ArrayRemoveElement(argv, 0); ETime(argv); } } else if (IsExecutable(argv[0])) { int background = VecContainsStr(argv, "&"); int I_loc = VecContainsStr(argv, "<"); int O_loc = VecContainsStr(argv, ">"); int pipe_count = ArgvCountSymbol(argv, "|"); if (I_loc != -1) { argv = ExecuteExternalWithInput(argv, I_loc, background); } else if (O_loc != -1) { argv = ExecuteExternalWithOutput(argv, O_loc, background); } else if (pipe_count > 0) { argv = ExecuteExternalWithPipe(argv, pipe_count, background); } else { char* cmd = ArgvToString(argv); if (background != -1) { argv = ArrayRemoveElement(argv, background); } ExecuteExternal(argv, background, cmd); free(cmd); } } BigFree(argv); } }
static void DrawGLScene() { ReadInput(); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); glTranslatef(-xTranslate, -yTranslate, -zTranslate); glScaled(currentScale, currentScale, currentScale); glRotatef(xRotate, 1, 0, 0); glRotatef(yRotate, 0, 1, 0); //glBegin(GL_LINE_LOOP); //glColor4f(1.0, 1.0, 1.0, 1.0); //for(double theta=0; theta<=2*M_PI; theta+=M_PI/24.) //{ // double s, c; // double r = KW_R(theta); // s = sin(theta); // c = cos(theta); // glVertex3f(s * r, c * r, 0.0); //} //glEnd(); // First we draw the clicks for( auto click = clicks.begin(); !clicks.empty() && click != clicks.end(); click++) { if (click->alpha < MIN_ALPHA) { clicks.erase(click); continue; } else { DrawPoint( click->x, click->alpha ); click->alpha -= click->dalpha; } } // Now the explosions for( auto explosion = explosions.begin() ; !explosions.empty() && explosion != explosions.end(); explosion++) { if (explosion->alpha < MIN_ALPHA) { explosions.erase(explosion); continue; } else { DrawTorus( explosion->x, explosion->r, explosion->alpha ); explosion->alpha -= explosion->dalpha; explosion->r += explosion->dr; } } // Keyword time int new_max_count = 0; for ( auto kw_pair=keywords.begin() ; !keywords.empty() && kw_pair != keywords.end(); kw_pair++ ) { auto kw = &(kw_pair->second); if (kw->alpha < MIN_ALPHA) { keywords.erase(kw_pair); continue; } else { if (kw->count >= MIN_KEYWORD_COUNT) DrawText( kw->kw, kw->x, kw->theta, kw->alpha ); //kw->dr = fmin( 1.0*log( MAX_COUNT / kw->count), 5.0 ); double max_dr = 0.0125, min_dr = 0.01; kw->dr = max_dr - (max_dr - min_dr) * kw->count / MAX_COUNT; double s, c; s = sin(kw->theta); c = cos(kw->theta); kw->x[0] += kw->dr * s * MAX_COUNT / kw->count; kw->x[1] += kw->dr * c * MAX_COUNT / kw->count; kw->alpha -= kw->dalpha; new_max_count = (new_max_count < kw->count ? kw->count : new_max_count); } } MAX_COUNT = new_max_count; // Finally, we draw the lines! for ( auto li=links.begin() ; !links.empty() && li != links.end(); li++ ) { if (li->alpha < MIN_ALPHA || li->click == NULL || li->kw == NULL) { links.erase(li); continue; } else { if (li->kw->count >= MIN_KEYWORD_COUNT) DrawLine(li->click->x, li->kw->x, li->alpha); li->alpha -= li->dalpha; } } glFlush(); glutSwapBuffers(); }
/** * @brief Interfaces C and Matlab data. * This function is the MEX-file gateway routine. Please see the Matlab * MEX-file documentation (http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_external/f43721.html) * for more information. */ void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) { /* allocate variables */ struct input *X; struct options_direct *opts; int m,p,n,z; int p_total,P_total; int W; int *P_vec; mxArray *mxbinned; int **binned,*binned_temp; int cur_P; int status; int temp_N; /* check number of inputs (nargin) and outputs (nargout) */ if((nrhs<1) | (nrhs>2)) mexErrMsgIdAndTxt("STAToolkit:directbin:numArgs","1 or 2 input arguments required."); if((nlhs<1) | (nlhs>2)) mexErrMsgIdAndTxt("STAToolkit:directbin:numArgs","1 or 2 output arguments required."); X = ReadInput(prhs[0]); /* get or set options */ if(nrhs<2) opts = ReadOptionsDirect(mxCreateEmptyStruct()); else if(mxIsEmpty(prhs[1])) opts = ReadOptionsDirect(mxCreateEmptyStruct()); else opts = ReadOptionsDirect(prhs[1]); /* Read in time range */ ReadOptionsDirectTimeRange(opts,X); /* check options */ if(opts->Delta_flag==0) { opts[0].Delta = (*opts).t_end-(*opts).t_start; opts[0].Delta_flag=1; mexWarnMsgIdAndTxt("STAToolkit:directbin:missingParameter","Missing parameter counting_bin_size. Using default value end_time-start_time=%f.\n",opts[0].Delta); } if(opts->Delta <= 0) { mxFree(opts); mxFreeInput(X); mexErrMsgIdAndTxt("STAToolkit:directbin:invalidValue","counting_bin_size must be positive. It is currently set to %f.\n",opts[0].Delta); } if(opts->words_per_train_flag==0) { opts[0].words_per_train = (int)DEFAULT_WORDS_PER_TRAIN; opts[0].words_per_train_flag=1; mexWarnMsgIdAndTxt("STAToolkit:directbin:missingParameter","Missing parameter words_per_train. Using default value %d.\n",opts[0].words_per_train); } if(opts->words_per_train <= 0) { mxFree(opts); mxFreeInput(X); mexErrMsgIdAndTxt("STAToolkit:directbin:invalidValue","words_per_train must be positive. It is currently set to %d.\n",opts[0].words_per_train); } if(opts->legacy_binning_flag==0) { opts[0].legacy_binning = (int)DEFAULT_LEGACY_BINNING; opts[0].legacy_binning_flag=1; mexWarnMsgIdAndTxt("STAToolkit:directbin:missingParameter","Missing parameter legacy_binning. Using default value %d.\n",opts[0].legacy_binning); } if((opts->legacy_binning!=0) & (opts->legacy_binning!=1)) { mxFree(opts); mxFreeInput(X); mexErrMsgIdAndTxt("STAToolkit:directbin:invalidValue","Option legacy_binning set to an invalid value. Must be 0 or 1. It is currently set to %d.\n",opts[0].legacy_binning); } if(opts->letter_cap_flag==0) { opts[0].letter_cap = (int)DEFAULT_LETTER_CAP; opts[0].letter_cap_flag=1; mexWarnMsgIdAndTxt("STAToolkit:directbin:missingParameter","Missing parameter letter_cap. Using default value %d.\n",opts[0].letter_cap); } if(opts->letter_cap<0) { mxFree(opts); mxFreeInput(X); mexErrMsgIdAndTxt("STAToolkit:directbin:invalidValue","Option letter_cap set to an invalid value. Must be a positive integer or Inf. It is currently set to %d.\n",opts[0].letter_cap); } if((*X).N>1) { if(opts->sum_spike_trains_flag==0) { opts[0].sum_spike_trains = (int)DEFAULT_SUM_SPIKE_TRAINS; opts[0].sum_spike_trains_flag=1; mexWarnMsgIdAndTxt("STAToolkit:directbin:missingParameter","Missing parameter sum_spike_trains. Using default value %d.\n",opts[0].sum_spike_trains); } if((opts->sum_spike_trains!=0) & (opts->sum_spike_trains!=1)) { mxFree(opts); mxFreeInput(X); mexErrMsgIdAndTxt("STAToolkit:directbin:invalidValue","Option sum_spike_trains set to an invalid value. Must be 0 or 1. It is currently set to %d.\n",(*opts).sum_spike_trains); } if(opts->permute_spike_trains_flag==0) { opts[0].permute_spike_trains = (int)DEFAULT_PERMUTE_SPIKE_TRAINS; opts[0].permute_spike_trains_flag=1; mexWarnMsgIdAndTxt("STAToolkit:directbin:missingParameter","Missing parameter permute_spike_trains. Using default value %d.\n",opts[0].permute_spike_trains); } if((opts->permute_spike_trains!=0) & (opts->permute_spike_trains!=1)) { mxFree(opts); mxFreeInput(X); mexErrMsgIdAndTxt("STAToolkit:directbin:invalidValue","Option permute_spike_trains set to an invalid value. Must be 0 or 1. It is currently set to %d.\n",(*opts).permute_spike_trains); } } P_total = GetNumTrials(X); /* W is the number of letters in a word */ W=GetWindowSize(opts); /* Allocate memory for pointers to pointers */ if(opts[0].sum_spike_trains) temp_N = 1; else temp_N = X[0].N; binned = mxMatrixInt((*opts).words_per_train*P_total,temp_N*W); /* Allocate memory for P_vec */ P_vec = (int *)mxMalloc((*X).M*sizeof(int)); /* Do computation */ status = DirectBinComp(X,opts,(*opts).words_per_train*P_total,W,P_vec,binned); if(status==EXIT_FAILURE) { mxFree(opts); mxFreeInput(X); mxFreeMatrixInt(binned); mxFree(P_vec); mexErrMsgIdAndTxt("STAToolkit:directbin:failure","directbin failed."); } /* Create binned cell array */ plhs[0] = mxCreateCellMatrix((*X).M,(*opts).words_per_train); p_total = 0; for(m=0;m<(*X).M;m++) { cur_P = (*X).categories[m].P; for(z=0;z<(*opts).words_per_train;z++) { /* vectorize and transpose this matrix */ binned_temp = (int *)mxMalloc(W*temp_N*cur_P*sizeof(int)); for(p=0;p<cur_P;p++) for(n=0;n<temp_N*W;n++) binned_temp[n*cur_P + p]=binned[p_total+p][n]; p_total += cur_P; mxbinned = mxCreateNumericMatrix(cur_P,temp_N*W,mxINT32_CLASS,mxREAL); memcpy(mxGetData(mxbinned),binned_temp,cur_P*temp_N*W*sizeof(int)); mxSetCell(plhs[0],z*(*X).M+m,mxbinned); mxFree(binned_temp); } } /* output options used */ if(nrhs<2) plhs[1] = WriteOptionsDirect(mxCreateEmptyStruct(),opts); else if(mxIsEmpty(prhs[1])) plhs[1] = WriteOptionsDirect(mxCreateEmptyStruct(),opts); else plhs[1] = WriteOptionsDirect(prhs[1],opts); /* free memory */ mxFreeInput(X); mxFreeMatrixInt(binned); mxFree(P_vec); return; }