void cargarClientes(FILE * archivo) { char res; Cliente registro; do { cargarUnCliente(registro); fwrite(®istro, sizeof(registro), 1, archivo); printf("\n Otro cliente? (S/N): "); _flushall(); scanf("%c", &res); } while (res != 'N'); }
void Application::runManager(int choice) { string tempStr; _flushall(); switch(choice) { case 1: currentManager->transaction(store); //Run transaction break; case 2: store.updateInventory(); //Update inventory break; case 3: store.printInventory(); //Display all inventory system("pause"); break; case 4: cout << "Enter category: "; getline(cin, tempStr); store.printInventory(tempStr, "category"); //Display category system("pause"); break; case 5: cout << "Enter subcategory: "; getline(cin, tempStr); store.printInventory(tempStr, "subcategory"); //Display subcategory system("pause"); break; case 6: cout << "Enter item name: "; getline(cin, tempStr); store.printInventory(tempStr, "name");//Display individual item system("pause"); break; case 7: currentManager->changeDiscount(store);//Update discounts system("pause"); break; case 8: currentManager->addEmployee();//Add employee system("pause"); break; case 9: currentManager->editEmployee();//Edit employee system("pause"); break; case 10: currentManager->terminateEmployee();//Terminate employee system("pause"); break; default: break; } }
int wmain(int argc, WCHAR* argv[]) { WCHAR CmdLine[CMDLINE_LENGTH]; /* * If the user hasn't asked for specific help, * then print out the list of available commands. */ if (argc <= 1) { PrintResourceString(IDS_HELP1); PrintResourceString(IDS_HELP2); return 0; } /* * Bad usage (too much options) or we use the /? switch. * Display help for the help command. */ if ((argc > 2) || (wcscmp(argv[1], L"/?") == 0)) { PrintResourceString(IDS_USAGE); return 0; } /* * If the command is not an internal one, * display an information message and exit. */ if (!IsInternalCommand(argv[1])) { PrintResourceString(IDS_NO_ENTRY, argv[1]); return 0; } /* * Run "<command> /?" in the current command processor. */ wcsncpy(CmdLine, argv[1], CMDLINE_LENGTH - wcslen(CmdLine)); wcsncat(CmdLine, L" /?" , CMDLINE_LENGTH - wcslen(CmdLine)); _flushall(); return _wsystem(CmdLine); }
int main(void) { int choice = 0; double amt = 0.0; Bank wsecu; while(choice != 7) { system("cls"); wsecu.displayMenu(); choice = wsecu.getMenuChoice(); switch(choice) { case 1: _flushall(); wsecu.addAccount(); break; case 2: _flushall(); wsecu.modifyAccount(); break; case 3: _flushall(); cout << "Enter amount to deposit: "; cin >> amt; wsecu.deposit(amt); break; case 4: _flushall(); cout << "Enter the amount to withdraw: "; cin >> amt; wsecu.withdrawal(amt); break; case 5: _flushall(); wsecu.displayAccount(); break; case 6: _flushall(); wsecu.deleteAccount(); break; default: break; } } wsecu.~Bank(); cout << "Thankyou for using the bank" << endl; return 0; }
void Application::login(int choice) { string name; _flushall(); if(choice == 1 || choice == 2) { cout << "Enter login name: "; getline(cin, name); } switch(choice) { case 1: for(list<Manager>::iterator iter = managers.begin(); iter != managers.end(); iter++) { if(iter->getName() == name) { currentManager = &(*iter); } } break; case 2: for(list<Employee>::iterator iterEmp = employees.begin(); iterEmp != employees.end(); iterEmp++) { if(iterEmp->getName() == name) { currentEmployee = &(*iterEmp); } } break; default: break; } if(choice == 1 && currentManager == NULL) { cout << "Manager not found" << endl; } else if(choice == 2 && currentEmployee == NULL) { cout << "Employee not found" << endl; } }
//Has no error handling. //I think that if an error occurs here there's no way to handle it anyway. LONG WINAPI MyUnhandledExceptionFilter(LPEXCEPTION_POINTERS e) { //EnterCriticalSection(&g_uefcs); File::IOFile file("exceptioninfo.txt", "a"); file.Seek(0, SEEK_END); etfprint(file.GetHandle(), "\n"); //etfprint(file, g_buildtime); //etfprint(file, "\n"); //dumpCurrentDate(file); etfprintf(file.GetHandle(), "Unhandled Exception\n Code: 0x%08X\n", e->ExceptionRecord->ExceptionCode); STACKTRACE2(file.GetHandle(), e->ContextRecord->Rip, e->ContextRecord->Rsp, e->ContextRecord->Rbp); file.Close(); _flushall(); //LeaveCriticalSection(&g_uefcs); return EXCEPTION_CONTINUE_SEARCH; }
int main(int argc, char* argv[]) { char *args[ARG_BUF_SIZE]; char base_path[PATH_BUF_SIZE + 1]; char script_path[PATH_BUF_SIZE + 1]; char shell_path[PATH_BUF_SIZE + 1]; char env_path[ENV_VAR_SIZE]; int argi; _fullpath(shell_path, argv[0], PATH_BUF_SIZE); strcpy(script_path, shell_path); strcpy(base_path, shell_path); parent(shell_path); strcat(shell_path, "\\sh.exe"); remove_extension(script_path); parent(base_path); args[0] = shell_path; args[1] = "--norc"; args[2] = script_path; /* Any parameters passed on the command line will be passed through to the shell script */ for (argi = 0; argi < MIN(argc - 1, ARG_BUF_SIZE); argi++) { printf("%s\n", argv[argi + 1]); args[argi + NUM_EXEC_ARGS] = argv[argi + 1]; } /* Signal the end of the argument list */ args[argi + NUM_EXEC_ARGS] = NULL; /* Add this executable's directory to the path */ strcpy(env_path, "PATH="); strcat(env_path, getenv("PATH")); strcat(env_path, ";"); strcat(env_path, base_path); _putenv(env_path); _spawnv(_P_WAIT, args[0], &args[1]); _flushall(); }
void PageAlert(char *subject,char *message) { char messagebuf[4000]; char FAR hostname[256]; unsigned int i; int res; char *mailServer; char *emailAddress; /* hostname of computer */ gethostname((char *)&hostname ,255-1); mailServer = ConfigStr( EMAIL_HOST ); emailAddress = ConfigStr( EMAIL_NAME ); /* don`t want spaces in either subject or message */ for(i=0;i<strlen( subject ); i++) { if(subject[ i ] == ' ' ) subject[ i ] = '_'; } for(i=0;i<strlen( message ); i++) { if(message[ i ] == ' ' ) message[ i ] = '_'; } /* build the command string , bypass the mail filter .. (its ok we`re inside 3do) */ /* until i finish the internal mail sender, i`ve ignored the subject parameter */ sprintf(messagebuf,"mailto -H %s -U %s -S Warning -M %s -D %s",mailServer,hostname,message,emailAddress); dprintf(messagebuf); /* calling system() requires a flush of all buffered streams */ _flushall(); /* handle any returns from system */ res = system(messagebuf); /* handle any returns from system */ if(res==-1) { DisplayErrnoText(); } else dprintf("system command returned %d\n",res); }
int HostExceptionFilter(int exceptionCode, _EXCEPTION_POINTERS *ep) { ChakraRTInterface::NotifyUnhandledException(ep); bool crashOnException = false; ChakraRTInterface::GetCrashOnExceptionFlag(&crashOnException); if (exceptionCode == EXCEPTION_BREAKPOINT || (crashOnException && exceptionCode != 0xE06D7363)) { return EXCEPTION_CONTINUE_SEARCH; } fwprintf(stderr, _u("FATAL ERROR: %ls failed due to exception code %x\n"), hostName, exceptionCode); _flushall(); // Exception happened, so we probably didn't clean up properly, // Don't exit normally, just terminate TerminateProcess(::GetCurrentProcess(), exceptionCode); return EXCEPTION_CONTINUE_SEARCH; }
/************************************************************************* * Date last modified: July 9th, 2013 * Description: Gets user input for SML program * Input parameters: * Returns: * Precondition: User inputs a valid program * Postcondition: Memory is updated with users program *************************************************************************/ void SimpletronSimulator::getProgram(Simpletron &program) { int instruction = 00000, counter = 000; cout << "*** Welcome to Simpletron ***" << endl; cout << "*** Please enter your program one instruction at a time ***" << endl; cout << "*** I will type the location number followed by a question mark ***" << endl; cout << "*** Then type the word for that memory location ***" << endl; cout << "*** Type -99999 to stop entering your program ***" << endl; while(instruction != -99999) { _flushall(); cout << counter<< " ? "; cin >> instruction; if(instruction != -99999) { program.memory[counter] = instruction; } counter++; } cout << "*** Program loading completed ***" << endl; }
/************************************************************************* * Date last modified: June 16th, 2013 * Description: Asks user for input to create new node * Input parameters: * Returns: pointer to new user defined node (dynamically allocated) * Precondition: Memory must be available * Postcondition: Pointer to valid node is returned *************************************************************************/ Node *createItem(void) { char *pStr; char str[100]; Node *pMem = NULL; _flushall(); pMem = (Node*)malloc(sizeof(Node)); printf("\nEnter artist: "); gets(str); pStr = (char*)malloc(sizeof(char)*(strlen(str)+1)); strcpy(pStr, str); pMem->pArtist = pStr; printf("Enter song title: "); gets(str); pStr = (char*)malloc(sizeof(char)*(strlen(str)+1)); strcpy(pStr, str); pMem->pSongTitle = pStr; printf("Enter album title: "); gets(str); pStr = (char*)malloc(sizeof(char)*(strlen(str)+1)); strcpy(pStr, str); pMem->pAlbumTitle = pStr; printf("Enter Genre: "); gets(str); pStr = (char*)malloc(sizeof(char)*(strlen(str)+1)); strcpy(pStr, str); pMem->pGenre = pStr; printf("Enter song length: "); scanf("%lf", &(pMem->songLength)); printf("Enter number of plays: "); scanf("%d", &(pMem->numTimesPlayed)); printf("Enter rating: "); scanf("%d", &(pMem->rating)); return pMem; }
int paralelkenar_ciz() { int i, j,boyut; paralelkenardonus: printf("Paralelkenar'in Boyutu : "); scanf_s("%d", &boyut); _flushall(); if (boyut > 1) { system("cls"); for (i = 1; i<(boyut); i++) // işlemi (boyut-1) kadar tekrarlar. { for (j = 0; j<boyut - (i); j++) // (boyut-1)*(boyut -i) kadar boşluk koyar. { printf(" "); } for (j = 0; j <= boyut; j++) // (boyut-1)*(boyut+1) kadar işlemi tekrarlar. { for (j = 0; j < boyut; j++) // (boyut-1)*(boyut+1)*(boyut+1) kadar * koyar printf("*"); } printf("\n"); // (boyut-1) boşluk yazdırdıktan ve boyut adet yıldız koyduktan sonra bir alt satıra iner.Bu işlemi (boyut-1) degeri kadar yapar. } for (i = 1; i <= (boyut); i++) // boyut kadar yıldız yazdırtır.Boşluk olmayan satır için yazdım. { printf("*"); } } else { goto paralelkenardonus; // paralelkenardonus noktasina geri donuyor. } printf("\nDevam etmek icin bir tusa basin!"); _getch(); system("cls"); return 0; }
void handleDiceInput() { int input = -1; do { _flushall(); scanf(" %d", &input); if (validateNumber(&input) == 0) { if (validateUINTMAX(input) == 1 && validateMin(input) == 1) { castDice(input); setState(GS_MAINMENU); #undef FLAGG manage(); //Go back to main menu. } else { printf("\nValue not in range!\n"); drawDiceMenu(); handleDiceInput(); } } else { printf("\nInput value shall be a number!\n"); drawDiceMenu(); handleDiceInput(); } } while (1); }
HRESULT ExecuteTestWithMemoryCheck(char* fileName) { HRESULT hr = E_FAIL; #ifdef CHECK_MEMORY_LEAK // Always check memory leak, unless user specified the flag already if (!ChakraRTInterface::IsEnabledCheckMemoryFlag()) { ChakraRTInterface::SetCheckMemoryLeakFlag(true); } // Disable the output in case an unhandled exception happens // We will re-enable it if there is no unhandled exceptions ChakraRTInterface::SetEnableCheckMemoryLeakOutput(false); #endif #ifdef _WIN32 __try { hr = ExecuteTest(fileName); } __except (HostExceptionFilter(GetExceptionCode(), GetExceptionInformation())) { Assert(false); } #else // REVIEW: Do we need a SEH handler here? hr = ExecuteTest(fileName); if (FAILED(hr)) exit(0); #endif // _WIN32 _flushall(); #ifdef CHECK_MEMORY_LEAK ChakraRTInterface::SetEnableCheckMemoryLeakOutput(true); #endif return hr; }
void cargarArchivo(FILE * archivo) { char seguir; Paciente regi; fseek(archivo, 0, SEEK_END); do { system("cls"); printf("NHC: "); _flushall(); scanf("%d", ®i.nhc); printf("\nNombre: "); _flushall(); gets(regi.nombre); printf("\nEdad: "); _flushall(); scanf("%d", ®i.edad); printf("\nSexo: "); _flushall(); scanf("%c", ®i.sexo); printf("\nDiagnostico: "); _flushall(); gets(regi.diagnostico); fwrite(®i, sizeof(regi), 1, archivo); printf("\n"); printf("\nIngresar otro paciente? (S/N)"); _flushall(); scanf("%c", &seguir); } while (seguir == 'S' || seguir == 's'); } // cargarArchivo
void cargarUnCliente(Cliente ®i) { int tipoDePoliza = -1; printf("\n------------- "); printf("\nNuevo Cliente "); printf("\nDNI: "); _flushall(); scanf("%d", ®i.dni); printf("\nApellido: "); _flushall(); gets(regi.apellido); printf("\nNombre: "); _flushall(); gets(regi.nombre); do { printf("\nPoliza (0 a 4): "); _flushall(); scanf("%d", &tipoDePoliza); } while ( ( tipoDePoliza < 0 ) || ( tipoDePoliza > 4) ); regi.poliza = tipoDePoliza; printf("\nMonto: "); _flushall(); scanf("%f", ®i.montoAsegurado); printf("\nCiudad: "); _flushall(); gets(regi.ciudad); printf("\n------------- "); }
/************************************************************* * Function: pa3_main () * Created: February 6th, 2012 * Last Revised: February 10th, 2012 * Description: This function runs an evaluation/conversion * Input parameters: whether the expression should be saved * Returns: N/A * Preconditions: an expression needs to be converted/evaluated * Postconditions: an expression has been converted/evaluated *************************************************************/ void pa3_main (Bool isSaving) { FILE *outFile = NULL; char infixString[128] = "", infixBackup[128], postfixString[128], postfixBackup[128]; int endValue = 0.0; Bool success = false; // flush the buffer (just in case) _flushall (); fflush(stdin); // ask/get for an infix expression printf ("Expression to evaluate (positive integers, infix format)? "); while (!isdigit (infixString[0])) { gets (infixString); } printf ("Converting.."); // make a backup copy of the inputted expression strcpy (infixBackup, infixString); printf ("."); // convert infix to postfix success = infixConvertor (infixString, postfixString); if (success) { printf ("."); // make a backup copy of the postfix expression strcpy (postfixBackup, postfixString); printf ("."); // evaluate the expression printf (".Converted...Evaluating.."); endValue = postfixEvaluation (&postfixString[0]); printf (".Evaluated!\n\n"); // print the data printf ("%s = %s = %d\n", infixBackup, postfixBackup, endValue); // perform any necessary file operations if necessary if (isSaving) { // open the save file (or create one if necessary) outFile = fopen ("expressions.txt", "a"); // print expression data fprintf (outFile, "%s = %s = %d\n", infixBackup, postfixBackup, endValue); // print that data has been saved printf ("Expression data has been saved!\n"); // close file fclose (outFile); } } else { // if something went wrong, say so printf ("Failed to evaluate expression!\n"); } // print a new line printf ("\n"); // pause the screen pause_clear (true, false); }
int start_emulator(char* emu, char *start_prog, char** argv, int start_detached) { int result; static char console_mode[] = "tty:ccc"; char* fd_type; char* title; #ifdef HARDDEBUG fprintf(stderr,"emu = %s, start_prog = %s\n",emu, start_prog); #endif fd_type = strchr(console_mode, ':'); fd_type++; _flushall(); /* * If no console, we will spawn the emulator detached. */ if (start_detached) { char *buff; close(0); close(1); close(2); set_env("ERL_CONSOLE_MODE", "detached"); set_env(DLL_ENV, emu); argv[0] = start_prog; argv = fnuttify_argv(argv); #ifdef ARGS_HARDDEBUG { char buffer[2048]; int i; sprintf(buffer,"Start detached [%s]\n",start_prog); for(i=0;argv[i] != NULL;++i) { strcat(buffer,"|"); strcat(buffer,argv[i]); strcat(buffer,"|\n"); } MessageBox(NULL, buffer,"Start detached",MB_OK); } #endif result = spawnv(_P_DETACH, start_prog, argv); free_fnuttified(argv); if (result == -1) { #ifdef ARGS_HARDDEBUG MessageBox(NULL, "_spawnv failed","Start detached",MB_OK); #endif return 1; } SetPriorityClass((HANDLE) result, GetPriorityClass(GetCurrentProcess())); } else { int argc = 0; #ifdef LOAD_BEAM_DYNAMICALLY HMODULE beam_module = load_win_beam_dll(emu); #endif /* * Start the emulator. */ title = get_env("ERL_WINDOW_TITLE"); if (title) { SetConsoleTitle(title); } free_env_val(title); set_env("ERL_CONSOLE_MODE", console_mode); while (argv[argc] != NULL) { ++argc; } if (keep_window) { atexit(do_keep_window); } #ifdef ARGS_HARDDEBUG { char sbuf[2048] = ""; int i; for (i = 0; i < argc; ++i) { strcat(sbuf,"|"); strcat(sbuf, argv[i]); strcat(sbuf,"|\n"); } MessageBox(NULL, sbuf, "erl", MB_OK); } #endif #ifdef LOAD_BEAM_DYNAMICALLY (*sys_primitive_init_p)(beam_module); (*erl_start_p)(argc,argv); #else erl_start(argc, argv); #endif } return 0; }
/* Save the state of WinAmp */ void save_state() { int ii; int eq; char eq_string[EQSIZE]; int string_pos = 0; int list_pos; char *song_title; char *song_filename; char *str_to_write; char *tmpstr; int str_to_write_len; /* Only save if configured to do so currently */ if ( SendMessage(module.hwndParent, WM_WA_IPC, 0, IPC_ISPLAYING) != 1 ) { /* WinAmp is not playing */ /* Exit this procedure if we're not supposed to save while not playing */ if ( GetPrivateProfileInt(INI_SECTNAME, KEY_SAVEWHILEPLAYING, DEFAULT_SAVEWHILEPLAYING, ini_path) == 1 ) /* We're not supposed to save while not playing */ return; } /* Write out the playlist */ SendMessage(module.hwndParent, WM_WA_IPC, 0, IPC_WRITEPLAYLIST); /* Write out the current playlist position */ list_pos = SendMessage(module.hwndParent, WM_WA_IPC, 0, IPC_GETLISTPOS); WritePrivateProfileInt(INI_SECTNAME, KEY_PLAYLISTLOC, list_pos, ini_path); /* Write out the position in the current song */ /* If we're only supposed to resume from the beginning, always write 0. */ if ( GetPrivateProfileInt(INI_SECTNAME, KEY_RESUMEATBEGINNING, DEFAULT_RESUMEATBEGINNING, ini_path) == 1 ) WritePrivateProfileInt(INI_SECTNAME, KEY_SONGLOC, 0, ini_path); else WritePrivateProfileInt(INI_SECTNAME, KEY_SONGLOC, SendMessage(module.hwndParent, WM_WA_IPC, 0, IPC_GETOUTPUTTIME), ini_path); /* Write out the current equalizer settings */ for ( ii = 0 ; ii < NUM_EQS ; ii++ ) { eq = SendMessage(module.hwndParent, WM_WA_IPC, ii, IPC_GETEQDATA); if (ii == 0) sprintf(eq_string+string_pos, "%d", eq); else sprintf(eq_string+string_pos, ",%d", eq); /* Add to the length of the string the number of digits + the comma */ string_pos += num_digits(eq) + (ii!=0); } /* Write out the EQ settings */ WritePrivateProfileString(INI_SECTNAME, KEY_EQ, eq_string, ini_path); WritePrivateProfileInt(INI_SECTNAME, KEY_EQPREAMP, SendMessage(module.hwndParent, WM_WA_IPC, PREAMP, IPC_GETEQDATA), ini_path); WritePrivateProfileInt(INI_SECTNAME, KEY_EQENABLED, SendMessage(module.hwndParent, WM_WA_IPC, EQENABLED, IPC_GETEQDATA), ini_path); /* Write out the song name */ tmpstr = (char*)SendMessage(module.hwndParent, WM_WA_IPC, list_pos, IPC_GETPLAYLISTFILE); if ( !tmpstr ) { /* Can't get filename, don't save state. This is most likely because the playlist has been cleared. */ WritePrivateProfileInt(INI_SECTNAME, KEY_SONGLOC, 0, ini_path); return; } else song_filename = strdup(tmpstr); tmpstr = (char*)SendMessage(module.hwndParent, WM_WA_IPC, list_pos, IPC_GETPLAYLISTTITLE); if ( !tmpstr ) { /* Again, playlist has probably be cleared. Don't save state. */ WritePrivateProfileInt(INI_SECTNAME, KEY_SONGLOC, 0, ini_path); return; } else song_title = strdup(tmpstr); str_to_write_len = strlen(song_title) + strlen(song_filename) + 1; str_to_write = (char*)malloc(sizeof(char)*(str_to_write_len+1)); _snprintf(str_to_write, SONG_NAME_BUF, "%s-%s", song_filename, song_title); WritePrivateProfileString(INI_SECTNAME, KEY_SONG_NAME, str_to_write, ini_path); free(song_filename); free(song_title); free(str_to_write); /* Force disk cache flush if requested */ if ( GetPrivateProfileInt(INI_SECTNAME, KEY_FORCEFLUSH, DEFAULT_FORCEFLUSH, ini_path) ) /* Note: this feature only works because I'm linking to commode.obj! */ _flushall(); }
void nandflash_sb_setup(struct nandflash_device* dev) { uint8 flag=0xFF; int len,start,needinit=0; struct stat statbuf; struct nandflash_sb_status *nf; int i; nf=(struct nandflash_sb_status *)malloc(sizeof(struct nandflash_sb_status)); if (nf==NULL) { printf("error malloc nandflash_sb_status!\n"); skyeye_exit(-1); } dev->poweron=nandflash_sb_poweron; dev->readdata=nandflash_sb_readdata; dev->readio=nandflash_sb_readio; dev->readRB=nandflash_sb_readRB; dev->reset=nandflash_sb_reset; dev->sendaddr=nandflash_sb_sendaddr; dev->sendcmd=nandflash_sb_sendcmd; dev->senddata=nandflash_sb_senddata; dev->setALE=nandflash_sb_setALE; dev->setCE=nandflash_sb_setCE; dev->setCLE=nandflash_sb_setCLE; dev->setRE=nandflash_sb_setRE; dev->setWE=nandflash_sb_setWE; dev->setWP=nandflash_sb_setWP; memset(nf,0,sizeof(struct nandflash_sb_status)); #ifdef POSIX_SHARE_MEMORY_BROKEN nf->readbuffer=(uint8*)malloc(dev->pagedumpsize); #endif nf->writebuffer=(uint8*)malloc(dev->pagedumpsize); //nf->memsize=528*32*4096; if ((nf->fdump= open(dev->dump, FILE_FLAG, S_IRUSR |S_IWUSR )) < 0) { free(nf); printf("error open nandflash dump!\n"); skyeye_exit(-1); } if (fstat(nf->fdump, &statbuf) < 0) /* need size of input file */ { free(nf); printf("error fstat function\n"); skyeye_exit(-1); } if (statbuf.st_size<dev->devicesize) { printf("\nInit nandflash dump file.\n"); needinit=1; start=statbuf.st_size; len=dev->devicesize-start; lseek(nf->fdump,dev->devicesize-1,SEEK_SET); write(nf->fdump,&flag,1); #ifndef __MINGW32__ fsync(nf->fdump); #else _flushall(); #endif } #ifndef POSIX_SHARE_MEMORY_BROKEN if (fstat(nf->fdump, &statbuf) < 0) /* need size of input file */ { free(nf); printf("error fstat function\n"); skyeye_exit(-1); } printf("file size:%d\n",statbuf.st_size); if ((nf->addrspace= mmap(0, statbuf.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, nf->fdump, 0)) == MAP_FAILED) { free(nf); printf("error mmap nandflash file\n"); skyeye_exit(-1); } if (needinit) { for(i=start;i<dev->devicesize;i++) { *(nf->addrspace+i)=flag; } if (!msync(nf->addrspace,dev->devicesize,MS_SYNC)) printf("finish init nandflash dump\n"); } #else nf->curblock=-1; if (needinit) { memset(nf->readbuffer,0xff,dev->pagedumpsize); lseek(nf->fdump,start,SEEK_SET); while((dev->devicesize-start)>=dev->pagesize) { write(nf->fdump,nf->readbuffer,dev->pagesize); start=start+dev->pagesize; } for (i=start;i<dev->devicesize;i++) write(nf->fdump,&flag,1); } #endif dev->priv=nf; nandflash_sb_poweron(dev); }
void __cdecl Phase_Info ( const int *phase, // Current phase number Type_Of_Phase *phase_type, // Type of phase (numeric, analytic) DLL_Item *phase_desc, // Phase description DLL_Unit_Item *phase_time, // Time description DLL_Item *ini_cost, // Initial cost description DLL_Item *integ_cost, // Integral cost description DLL_Item *term_cost, // Terminal cost description int *error // Error flag ) /* SYNOPSIS: * returns for the specified phase, the type of the phase, its * name and description, name and description of the * independant variable and for each cost term. */ { #ifdef DEBUG_MODE printf("Phase Info\n");_flushall(); #endif *error = 0; /* what kind of phase */ *phase_type = Numeric; Phase_Description[*phase-1].Name_len = strlen(Phase_Description[*phase-1].Name); Phase_Description[*phase-1].Desc_len = strlen(Phase_Description[*phase-1].Desc); phase_desc->Desc = Phase_Description[*phase-1].Desc; phase_desc->Name = Phase_Description[*phase-1].Name; phase_desc->Desc_len = Phase_Description[*phase-1].Desc_len; phase_desc->Name_len = Phase_Description[*phase-1].Name_len; /* time info */ Time_Description.Name_len = strlen(Time_Description.Name); Time_Description.Desc_len = strlen(Time_Description.Desc); Time_Description.Unit_len = strlen(Time_Description.Unit); phase_time->Desc = Time_Description.Desc; phase_time->Name = Time_Description.Name; phase_time->Unit = Time_Description.Unit; phase_time->Desc_len = Time_Description.Desc_len; phase_time->Name_len = Time_Description.Name_len; phase_time->Unit_len = Time_Description.Unit_len; /* ini cost info */ Initial_Cost_Item.Name_len = strlen(Initial_Cost_Item.Name); Initial_Cost_Item.Desc_len = strlen(Initial_Cost_Item.Desc); ini_cost->Desc = Initial_Cost_Item.Desc; ini_cost->Name = Initial_Cost_Item.Name; ini_cost->Desc_len = Initial_Cost_Item.Desc_len; ini_cost->Name_len = Initial_Cost_Item.Name_len; /* lagrange cost info * if there isn't any, set Integral_Cost := Unspecified. */ Integral_Cost_Item.Name_len = strlen(Integral_Cost_Item.Name); Integral_Cost_Item.Desc_len = strlen(Integral_Cost_Item.Desc); integ_cost->Desc = Integral_Cost_Item.Desc; integ_cost->Name = Integral_Cost_Item.Name; integ_cost->Desc_len = Integral_Cost_Item.Desc_len; integ_cost->Name_len = Integral_Cost_Item.Name_len; /* terminal cost info */ Terminal_Cost_Item.Name_len = strlen(Terminal_Cost_Item.Name); Terminal_Cost_Item.Desc_len = strlen(Terminal_Cost_Item.Desc); term_cost->Desc = Terminal_Cost_Item.Desc; term_cost->Name = Terminal_Cost_Item.Name; term_cost->Desc_len = Terminal_Cost_Item.Desc_len; term_cost->Name_len = Terminal_Cost_Item.Name_len; }
// IDL compiler main program. Logic as explained in comment at head of file. int driver_main(int argc, char **argv) { int ret = 0; #if defined (_WIN32) char * cmdstr = DRV_param_copy (argc, argv); #endif // Open front-end library DRV_FE_open (); // Initialize driver and global variables { DRV_init (); } // Open back-end library DRV_BE_open (); // Parse arguments DRV_parse_args (argc, argv); // If a version message is requested, print it and exit if (idl_global->compile_flags () & IDL_CF_VERSION) { DRV_version (); } else { // If a usage message is requested, give it and exit if (idl_global->compile_flags () & IDL_CF_ONLY_USAGE) { DRV_usage (); } else { // Fork off a process for each file to process. Fork only if // there is more than one file to process if (DRV_nfiles > 1) { // DRV_fork never returns #if !defined (_WIN32) DRV_fork (); #else char tmp_command[1024]; for (int tmpcounter = 0; tmpcounter < DRV_nfiles; tmpcounter++) { os_sprintf(tmp_command, "%s %s\0", cmdstr, DRV_files[tmpcounter]); _flushall (); if (system (tmp_command)) { cerr << "system() failed, errno: " << errno << endl; } } #endif } else { // Do the one file we have to parse // Check if stdin and handle file name appropriately if (DRV_nfiles == 0) { DRV_files[0] = "standard input"; } DRV_file_index = 0; ret = DRV_drive (DRV_files[DRV_file_index]); } } } return ret; }
HRESULT ExecuteTest(const char* fileName) { HRESULT hr = S_OK; LPCSTR fileContents = nullptr; JsRuntimeHandle runtime = JS_INVALID_RUNTIME_HANDLE; UINT lengthBytes = 0; if(strlen(fileName) >= 14 && strcmp(fileName + strlen(fileName) - 14, "ttdSentinal.js") == 0) { #if !ENABLE_TTD wprintf(_u("Sentinel js file is only ok when in TTDebug mode!!!\n")); return E_FAIL; #else if(!doTTDebug) { wprintf(_u("Sentinel js file is only ok when in TTDebug mode!!!\n")); return E_FAIL; } jsrtAttributes = static_cast<JsRuntimeAttributes>(jsrtAttributes | JsRuntimeAttributeEnableExperimentalFeatures); IfJsErrorFailLog(ChakraRTInterface::JsTTDCreateReplayRuntime(jsrtAttributes, ttUri, ttUriByteLength, Helpers::TTInitializeForWriteLogStreamCallback, Helpers::TTCreateStreamCallback, Helpers::TTReadBytesFromStreamCallback, Helpers::TTWriteBytesToStreamCallback, Helpers::TTFlushAndCloseStreamCallback, nullptr, &runtime)); chRuntime = runtime; JsContextRef context = JS_INVALID_REFERENCE; IfJsErrorFailLog(ChakraRTInterface::JsTTDCreateContext(runtime, true, &context)); IfJsErrorFailLog(ChakraRTInterface::JsSetCurrentContext(context)); IfFailGo(RunScript(fileName, fileContents, nullptr, nullptr)); unsigned int rcount = 0; IfJsErrorFailLog(ChakraRTInterface::JsSetCurrentContext(nullptr)); ChakraRTInterface::JsRelease(context, &rcount); AssertMsg(rcount == 0, "Should only have had 1 ref from replay code and one ref from current context??"); #endif } else { LPCOLESTR contentsRaw = nullptr; char fullPath[_MAX_PATH]; size_t len = 0; hr = Helpers::LoadScriptFromFile(fileName, fileContents, &lengthBytes); contentsRaw; lengthBytes; // Unused for now. IfFailGo(hr); if (HostConfigFlags::flags.GenerateLibraryByteCodeHeaderIsEnabled) { jsrtAttributes = (JsRuntimeAttributes)(jsrtAttributes | JsRuntimeAttributeSerializeLibraryByteCode); } #if ENABLE_TTD if (doTTRecord) { //Ensure we run with experimental features (as that is what Node does right now). jsrtAttributes = static_cast<JsRuntimeAttributes>(jsrtAttributes | JsRuntimeAttributeEnableExperimentalFeatures); IfJsErrorFailLog(ChakraRTInterface::JsTTDCreateRecordRuntime(jsrtAttributes, ttUri, ttUriByteLength, snapInterval, snapHistoryLength, Helpers::TTInitializeForWriteLogStreamCallback, Helpers::TTCreateStreamCallback, Helpers::TTReadBytesFromStreamCallback, Helpers::TTWriteBytesToStreamCallback, Helpers::TTFlushAndCloseStreamCallback, nullptr, &runtime)); chRuntime = runtime; JsContextRef context = JS_INVALID_REFERENCE; IfJsErrorFailLog(ChakraRTInterface::JsTTDCreateContext(runtime, true, &context)); #if ENABLE_TTD //We need this here since this context is created in record IfJsErrorFailLog(ChakraRTInterface::JsSetObjectBeforeCollectCallback(context, nullptr, WScriptJsrt::JsContextBeforeCollectCallback)); #endif IfJsErrorFailLog(ChakraRTInterface::JsSetCurrentContext(context)); } else { AssertMsg(!doTTDebug, "Should be handled in the else case above!!!"); IfJsErrorFailLog(ChakraRTInterface::JsCreateRuntime(jsrtAttributes, nullptr, &runtime)); chRuntime = runtime; if (HostConfigFlags::flags.DebugLaunch) { Debugger* debugger = Debugger::GetDebugger(runtime); debugger->StartDebugging(runtime); } JsContextRef context = JS_INVALID_REFERENCE; IfJsErrorFailLog(ChakraRTInterface::JsCreateContext(runtime, &context)); //Don't need collect callback since this is always in replay IfJsErrorFailLog(ChakraRTInterface::JsSetCurrentContext(context)); } #else IfJsErrorFailLog(ChakraRTInterface::JsCreateRuntime(jsrtAttributes, nullptr, &runtime)); chRuntime = runtime; if (HostConfigFlags::flags.DebugLaunch) { Debugger* debugger = Debugger::GetDebugger(runtime); debugger->StartDebugging(runtime); } JsContextRef context = JS_INVALID_REFERENCE; IfJsErrorFailLog(ChakraRTInterface::JsCreateContext(runtime, &context)); IfJsErrorFailLog(ChakraRTInterface::JsSetCurrentContext(context)); #endif #ifdef DEBUG ChakraRTInterface::SetCheckOpHelpersFlag(true); #endif #ifdef ENABLE_DEBUG_CONFIG_OPTIONS ChakraRTInterface::SetOOPCFGRegistrationFlag(false); #endif if (!WScriptJsrt::Initialize()) { IfFailGo(E_FAIL); } if (_fullpath(fullPath, fileName, _MAX_PATH) == nullptr) { IfFailGo(E_FAIL); } // canonicalize that path name to lower case for the profile storage // REVIEW: Assuming no utf8 characters here len = strlen(fullPath); for (size_t i = 0; i < len; i++) { fullPath[i] = (char)tolower(fullPath[i]); } if (HostConfigFlags::flags.GenerateLibraryByteCodeHeaderIsEnabled) { if (HostConfigFlags::flags.GenerateLibraryByteCodeHeader != nullptr && *HostConfigFlags::flags.GenerateLibraryByteCodeHeader != _u('\0')) { CHAR libraryName[_MAX_PATH]; CHAR ext[_MAX_EXT]; _splitpath_s(fullPath, NULL, 0, NULL, 0, libraryName, _countof(libraryName), ext, _countof(ext)); IfFailGo(CreateLibraryByteCodeHeader(fileContents, lengthBytes, HostConfigFlags::flags.GenerateLibraryByteCodeHeader, libraryName)); } else { fwprintf(stderr, _u("FATAL ERROR: -GenerateLibraryByteCodeHeader must provide the file name, i.e., -GenerateLibraryByteCodeHeader:<bytecode file name>, exiting\n")); IfFailGo(E_FAIL); } } else if (HostConfigFlags::flags.SerializedIsEnabled) { CreateAndRunSerializedScript(fileName, fileContents, fullPath); } else { IfFailGo(RunScript(fileName, fileContents, nullptr, fullPath)); } } Error: if (Debugger::debugger != nullptr) { Debugger::debugger->CompareOrWriteBaselineFile(fileName); Debugger::CloseDebugger(); } ChakraRTInterface::JsSetCurrentContext(nullptr); if (runtime != JS_INVALID_RUNTIME_HANDLE) { ChakraRTInterface::JsDisposeRuntime(runtime); } _flushall(); return hr; }
void __cdecl Get_Controls( const int *phase, // Current phase number const int *dimx, // Dimension of state vector X const int *dimu, // Dimension of control vector U const int *dimip, // Dimension of integer parameter vector const int *dimrp, // Dimension of real parameter vector const Phase_Info_Type *fazinf, // Record with additional phase info const double *t, // Time t of evaluation const double x[], // State vector X at time t const int ipar[], // Integer parameter vector of phase const double rpar[], // Real parameter vector of phase double *u, // Control vector U at time t double *u_lb, // Lower bounds for the control vector U double *u_ub, // Upper bounds for the control vector U int *error) // Error flag { /* compute the control and its bounds as a function * of time, states and parameters. */ double *mee_coords_LCI; double *cart_inert_coords_LCI; double *v_vec_norm; double *v_vec_norm_rotrad; double **Q_transp; double v_norm; int i,j; #ifdef DEBUG_MODE printf("Get Controls\n");_flushall(); #endif *error = 0; mee_coords_LCI = dvector(1,6); cart_inert_coords_LCI = dvector(1,6); v_vec_norm = dvector(1,3); v_vec_norm_rotrad = dvector(1,3); Q_transp = dmatrix(1,3,1,3); for (i=1; i<=3; i++){ for (j=1; j<=3; j++){ Q_transp[i][j] = 0.0; } v_vec_norm[i] = 0.0; v_vec_norm_rotrad[i] = 0.0; } for (i=1; i<=6; i++) { mee_coords_LCI[i] = x[i-1]; cart_inert_coords_LCI[i] = 0.0; } // Calculate velocity vector mee2cart(mee_coords_LCI, gmue[MOON], cart_inert_coords_LCI); v_norm = dvec_abs(&cart_inert_coords_LCI[3],3); for (i=1; i<=3; i++) { v_vec_norm[i] = cart_inert_coords_LCI[i+3] / v_norm; } ir_itheta_ih_transp(cart_inert_coords_LCI, Q_transp); //obtain Q_transp as [ir itheta ih]' dmat_times_vec(Q_transp, v_vec_norm, v_vec_norm_rotrad, 3, 3); //convert to rotating radial frame /* Initial control profile thrust tangentially to radius. */ // Future work: set this initial guess separately for each phase u[0] = -v_vec_norm_rotrad[1];//0.0; u[1] = -v_vec_norm_rotrad[2];//-1.0; u[2] = -v_vec_norm_rotrad[3];//0.0; u[3] = 1.0;//(cos(x[5])+1)/2; /* Bounds on control parameters */ u_lb[0] = LB_Control; u_ub[0] = UB_Control; u_lb[1] = LB_Control; u_ub[1] = UB_Control; u_lb[2] = LB_Control; u_ub[2] = UB_Control; u_lb[3] = 0.0; u_ub[3] = 1.0; free_dvector(mee_coords_LCI,1,6); free_dvector(cart_inert_coords_LCI,1,6); free_dvector(v_vec_norm,1,3); free_dvector(v_vec_norm_rotrad,1,3); free_dmatrix(Q_transp,1,3,1,3); }
void __cdecl Right_Hand_Side( const int *phase, // Current phase number const int *dimx, // Dimension of state vector X const int *dimu, // Dimension of control vector U const int *dimip, // Dimension of integer parameter vector const int *dimrp, // Dimension of real parameter vector const Phase_Info_Type *fazinf, // Record with additional phase info const double *t, // Time t of evaluation const double x[], // State vector X at time t const double u[], // Control vector U at time t const int ipar[], // Integer parameter vector of phase const double rpar[], // Real parameter vector of phase double *dx, // State derivative vector at time t int *error // Error flag ) { /* computes the state derivative of the dynamic system (ODE) * at the specified evaluation time of the given phase as a * function of the phase specific real parameter vector and * the state- and control vector at the evaluation time. */ // Local variables double p,f,g,h,k,L,time, mass; // renames for the state variables double pdot, fdot, gdot, hdot, kdot, Ldot, mdot; // time derivatives of state variables double *mee_coords; double *r_vec, *v_vec; double *cart_inert_coords; double **Q_transp; //contains the rotation matrix for the rotating radial frame in which //disturbing accelerations are expressed (x_rot = Q_transp * x_cart_inert) int center, target; //these are used for all calls to compute_ephemeris() double julian_date; double thrust; // [N] double ce; // [m/s] exhaust velocity double power; // [W] double solar_power; // [W] double thruster_power; // [W] double payload_power; // [W] double comms_power; // [W] double thrust_mag; // [-] Normalised thrust magnitude // thirdbody perturbations double *pertearth; // cartesian perturbing acceleration due to Earth (inertial) double *pertsun; // cartesian perturbing acceleration due to Sun (inertial) double *pertmoon; // cartesian perturbing acceleration due to Moon double *pertjupiter; // cartesian perturbing acceleration due to jupiter double *pertvenus; // cartesian perturbing acceleration due to venus double *pertmars; // cartesian perturbing acceleration due to mars double *thirdbody_acc_cart, *thirdbody_acc_rotrad; // third body perturbing accelerations in cartesian and in rotating reference frame // gravity harmonic perturbations double *pertharm_cart; // inertial cartesian perturbing acceleration due to gravity harmonic double *pertharm_rotrad; // ... in rotating reference frame // solar pressure perturbations double *pertsolp_cart; //inertial cartesian perturbing acceleration due to solar pressure double *pertsolp_rotrad; // ... in rotating reference frame double **inert2fixed; //contains the rotation matrix for the transformation from inertial //to fixed coordinates (x_fixed = inert2fixed * x_cart_inert) double ephemerides[6]; double *body2sun; double *craft2sun; // auxiliary values for right hand sides double omega,s2; // accelerations double acc_r, acc_theta, acc_h; double thrust_acc_r, thrust_acc_theta, thrust_acc_h; double g_mue; // gravitional constant depending on phase double deltaL; const double LIBR_CENTER = 0.0; int i, j; //counter variables #ifdef DEBUG_MODE printf("Right Hand Side\n");_flushall(); #endif // Initializations *error = 0; Q_transp = dmatrix(1,3,1,3); inert2fixed = dmatrix(1,3,1,3); mee_coords = dvector(1,6); cart_inert_coords = dvector(1,6); r_vec = dvector(1,3); v_vec = dvector(1,3); pertearth = dvector(1,3); pertsun = dvector(1,3); pertmoon = dvector(1,3); pertjupiter = dvector(1,3); pertvenus = dvector(1,3); pertmars = dvector(1,3); thirdbody_acc_cart = dvector(1,3); thirdbody_acc_rotrad = dvector(1,3); pertharm_cart = dvector(1,3); pertharm_rotrad = dvector(1,3); pertsolp_cart = dvector(1,3); pertsolp_rotrad = dvector(1,3); craft2sun = dvector(1,3); body2sun = dvector(1,3); for (i=1; i<=3; i++){ for (j=1; j<=3; j++){ Q_transp[i][j] = 0.0; inert2fixed[i][j] = 0.0; } pertearth[i] = 0.0; pertsun[i] = 0.0; pertmoon[i] = 0.0; pertjupiter[i] = 0.0; pertvenus[i] = 0.0; pertmars[i] = 0.0; thirdbody_acc_cart[i] = 0.0; thirdbody_acc_rotrad[i] = 0.0; pertharm_cart[i] = 0.0; pertharm_rotrad[i] = 0.0; pertsolp_cart[i] = 0.0; pertsolp_rotrad[i] = 0.0; craft2sun[i] = 0.0; body2sun[i] = 0.0; r_vec[i] = 0.0; v_vec[i] = 0.0; } acc_r = 0.0; acc_theta = 0.0; acc_h = 0.0; power = 0.0; // Retrieve state for (i=1; i<=6; i++) { mee_coords[i] = x[i-1]; cart_inert_coords[i] = 0.0; } // Rename states p = mee_coords[1]; f = mee_coords[2]; g = mee_coords[3]; h = mee_coords[4]; k = mee_coords[5]; L = mee_coords[6]; time = x[6]; mass = x[7]; // Retrieve optimised parameters deltaL = rpar[2]; // Get optimised phase length thrust_mag = u[3]; // Get optimised normalised thrust magnitude // if (x[8] < 100) // thrust_mag = 0.0; // else thrust_mag = u[3]; // Get optimised normalised thrust magnitude #ifdef DEBUG_MODE printf("---PHASE %i---\n", *phase);_flushall(); #endif if (*phase < 3) center = EARTH; else center = MOON; g_mue = gmue[center]; switch(*phase) { case 1: thrust = thrust_mag*thrust_arc; ce = ce_arc; thruster_power = thrust_mag*power_arc; payload_power = 0.0; // break; case 2: thrust = thrust_mag*thrust_ppt; ce = ce_ppt; thruster_power = thrust_mag*power_ppt; payload_power = 0.0; break; case 3: thrust = thrust_mag*thrust_arc; ce = ce_arc; thruster_power = thrust_mag*power_arc; payload_power = 0.0; break; case 4: thrust = thrust_mag*thrust_ppt; ce = ce_ppt; thruster_power = thrust_mag*power_ppt; payload_power = 0.0; break; case 5: thrust = 0.0; ce = 1.0; thruster_power = 0.0; payload_power = 1000.0; break; default: printf("Unrecognised phase number in RHS function\n"); break; } // switch comms_power = 0.0; // auxilliary values omega = 1.0 + f*cos(L) + g*sin(L); s2 = 1.0 + h*h + k*k; mee2cart(mee_coords, g_mue, cart_inert_coords); // obtain inertial cartesian coords ir_itheta_ih_transp(cart_inert_coords, Q_transp); // obtain rotating radial coordinate frame Q_transp as [ir itheta ih]' julian_date = EPOCH + rpar[0] + time; // = start time + current mission time // split cartesian coords into radius and velocity-vector for (i=1; i<=3; i++){ r_vec[i] = cart_inert_coords[i]; v_vec[i] = cart_inert_coords[i+3]; } /******** evaluate accelerations *******/ // --- thrust --- thrust_acc_r = thrust/mass * u[0]; thrust_acc_theta = thrust/mass * u[1]; thrust_acc_h = thrust/mass * u[2]; switch (PERT_MODE) { case 3: // --- minor 3rd body perturbations --- target = JUPITER; third_body_pert_cart(julian_date, center, target, r_vec, pertjupiter); target = VENUS; third_body_pert_cart(julian_date, center, target, r_vec, pertvenus); target = MARS; third_body_pert_cart(julian_date, center, target, r_vec, pertmars); case 2: // --- perturbations due to oblateness --- compute_rotation(julian_date, center, inert2fixed); if (center == EARTH) { AccelHarmonic (r_vec, inert2fixed, GM_JGM3, R_JGM3, CS_JGM3, 20, 20, pertharm_cart); } else { AccelHarmonic (r_vec, inert2fixed, GM_LP100J, R_LP100J, CS_LP100J, 20, 20, pertharm_cart); } dmat_times_vec(Q_transp, pertharm_cart, pertharm_rotrad, 3, 3); //convert to rotating radial frame // --- perturbations due to solar pressure --- solar_rad_pressure_cart(julian_date, mass, cart_inert_coords, center, pertsolp_cart); dmat_times_vec(Q_transp, pertsolp_cart, pertsolp_rotrad, 3, 3); case 1: // --- major 3rd body perturbations --- if (center == EARTH) { target = MOON; third_body_pert_cart(julian_date, center, target, r_vec, pertmoon); } else { target = EARTH; third_body_pert_cart(julian_date, center, target, r_vec, pertearth); } target = SUN; third_body_pert_cart(julian_date, center, target, cart_inert_coords, pertsun); // sum 3rd body perturbations for (i=1; i<=3; i++){ thirdbody_acc_cart[i] = pertearth[i] + pertsun[i] + pertmoon[i] + pertjupiter[i] + pertvenus[i] + pertmars[i]; } dmat_times_vec(Q_transp, thirdbody_acc_cart, thirdbody_acc_rotrad, 3, 3); //convert to rotating radial frame } //total acc_r = thrust_acc_r + thirdbody_acc_rotrad[1] + pertharm_rotrad[1] + pertsolp_rotrad[1]; acc_theta = thrust_acc_theta + thirdbody_acc_rotrad[2] + pertharm_rotrad[2] + pertsolp_rotrad[2]; acc_h = thrust_acc_h + thirdbody_acc_rotrad[3] + pertharm_rotrad[3] + pertsolp_rotrad[3]; /******** power calculations *******/ target = SUN; compute_ephemeris(julian_date, target, center, ephemerides); for(i=1;i<=3;i++) { body2sun[i] = ephemerides[i-1]*1000.0; craft2sun[i] = body2sun[i] - cart_inert_coords[i]; } // if(center == EARTH) // solar_power = SOLARINTENSITY*aref*area_efficiency*conversion_efficiency*shadowfunc(body2sun,cart_inert_coords,R_JGM3)*sin(sunangle(craft2sun,u)); // else // solar_power = SOLARINTENSITY*aref*area_efficiency*conversion_efficiency*shadowfunc(body2sun,cart_inert_coords,R_LP100J)*sin(sunangle(craft2sun,u)); // power = solar_power - thruster_power - payload_power - comms_power; // right hand sides // ----------------------------------------------------------- pdot = sqrt(p/g_mue)* 2.0*p/omega*acc_theta; // [km/s] fdot = sqrt(p/g_mue) *( sin(L)*acc_r + ((omega+1.0)*cos(L) + f)*acc_theta/omega - (h*sin(L) - k*cos(L))*g/omega*acc_h ); // [1/s] gdot = sqrt(p/g_mue) *( -cos(L)*acc_r + ((omega+1.0)*sin(L) + g)*acc_theta/omega + (h*sin(L) - k*cos(L))*f/omega*acc_h ); // [1/s] hdot = sqrt(p/g_mue) * s2*cos(L)/(2.0*omega)*acc_h; // [1/s] kdot = sqrt(p/g_mue) * s2*sin(L)/(2.0*omega)*acc_h; // [1/s] Ldot = sqrt(p/g_mue) *( h*sin(L) - k*cos(L) )*acc_h/omega + sqrt(p*g_mue)*(omega/p)*(omega/p); // [1/s] mdot = -thrust / ce; // [kg/s] if(Ldot < 0.0) printf("\n\nLDOT NEGATIVE!!!!!\n\n");_flushall(); if(p < 0.0) printf("\n\nP NEGATIVE!!!!!\n\n");_flushall(); // normalized L shall be the independent variable, so dx/dLn = dx/dt * dt/dL * dL/dLn dx[0] = pdot * deltaL / Ldot; // [km] dx[1] = fdot * deltaL / Ldot; // [-] dx[2] = gdot * deltaL / Ldot; dx[3] = hdot * deltaL / Ldot; dx[4] = kdot * deltaL / Ldot; dx[5] = deltaL; // L_phase_f - L_phase_i dx[6] = deltaL / Ldot / 86400.0; // [days] dx[7] = mdot * deltaL / Ldot; // [kg] dx[8] = 0.0;//power * deltaL / Ldot; // [J] //clean-up free_dvector(mee_coords,1,6); free_dvector(cart_inert_coords,1,6); free_dvector(pertearth,1,3); free_dvector(pertsun,1,3); free_dvector(pertmoon,1,3); free_dvector(pertjupiter,1,3); free_dvector(pertvenus,1,3); free_dvector(pertmars,1,3); free_dvector(thirdbody_acc_cart,1,3); free_dvector(thirdbody_acc_rotrad,1,3); free_dvector(pertharm_cart,1,3); free_dvector(pertharm_rotrad,1,3); free_dvector(pertsolp_cart,1,3); free_dvector(pertsolp_rotrad,1,3); free_dmatrix(Q_transp,1,3,1,3); free_dmatrix(inert2fixed,1,3,1,3); free_dvector(body2sun,1,3); free_dvector(craft2sun,1,3); }
short EXos( char oscmd[], DBshort mode) /* Proceduren OS i WIN32-version. * * In: oscmd => Kommandosträng. * mode => 0 = Asynkront (Batch) med wait * 1 = Interaktivt * 2 = Asynkront utan wait * * Ut: Inget. * * Felkoder: EX2092 = Fel från os, cmd=%s * * (C)microform ab 1996-02-21 J. Kjellander * * 1997-02-03 _flushall(), J.Kjellander * 1997-05-20 COMMAND.COM bort,mode 1, J.Kjellander * 1998-03-27 WaitForSingleObject(), J.Kjellander * ******************************************************!*/ { DWORD create,errnum; char errbuf[80]; STARTUPINFO si; PROCESS_INFORMATION pi; /* DWORD excode används ej fn.; */ /* ***Initiera startupinfo och processinfo. */ memset(&si,0,sizeof(si)); si.cb = sizeof(si); /* ***Töm alla filbuffrar. */ _flushall(); /* ***Om mode = 1 skall DOS-fönster skapas. */ if ( mode == 1 ) create = CREATE_NEW_CONSOLE; else create = DETACHED_PROCESS; /* ***Starta processen. */ if ( !CreateProcess(NULL, oscmd, NULL, NULL, FALSE, create, NULL, NULL, &si, &pi) ) { errnum = GetLastError(); sprintf(errbuf,"%d%%%s",errnum,oscmd); return(erpush("EX2092",errbuf)); } /* ***Enligt dok. bör man stänga handtagen primära ***tråden så fort som möjligt om det inte behövs. */ CloseHandle(pi.hThread); /* ***Om mode = 0 eller 1 skall vi vänta tills subprocessen är ***klar. Detta verkar funka olika i NT och 95. C:s wait funkar ***inte ! Ej heller cwait(). Bytt till WaitForSingleObject() ***1998-03-27, JK. */ if ( mode != 2 ) WaitForSingleObject(pi.hProcess,INFINITE); /* ***Nu kan vi stänga även handtaget till själva processen. */ CloseHandle(pi.hProcess); /* ***Det ska gå att få reda på Exit-status men det test ***jag gjorde mot TakCAD funkade inte. VisualBasic inblandat ! * loop: if ( GetExitCodeProcess(pi.hProcess,&excode) ) { if ( excode == STILL_ACTIVE ) { goto loop; } } else { errnum = GetLastError(); sprintf(errbuf,"%d%%%s",errnum,oscmd); return(erpush("EX2092",errbuf)); } */ return(0); }
//static void MemoryManager::DumpMemory() { static int dumpCount = 0; MemoryManager* instance = GetInstance(); DWORD64 dwDisplacement = 0; DWORD64 dwAddress; IMAGEHLP_LINE64 line; DWORD dwLineDisplacement; DWORD error; HANDLE hProcess; char buffer[sizeof(SYMBOL_INFO) + MAX_SYM_NAME * sizeof(TCHAR)]; PSYMBOL_INFO pSymbol = (PSYMBOL_INFO)buffer; SymSetOptions(SYMOPT_UNDNAME | SYMOPT_DEFERRED_LOADS | SYMOPT_LOAD_LINES); hProcess = GetCurrentProcess(); if (!SymInitialize(hProcess, NULL, TRUE)) { error = GetLastError(); LogError("SymInitialize returned error : %d\n", error); } std::stringstream filename; filename << "MemDump" << dumpCount++ << ".txt"; FILE *myFile = nullptr; errno_t openResult = fopen_s(&myFile, filename.str().c_str(), "w"); XTVERIFY(openResult == 0); if (myFile) { fprintf(myFile, "Total Memory Used:%u\n\n", (uint32)instance->m_totalAlloc); Alloc* currentAlloc = instance->m_head; while(currentAlloc != NULL) { dwAddress = (DWORD64)currentAlloc->m_stack[2]; line.SizeOfStruct = sizeof(IMAGEHLP_LINE64); fprintf(myFile, "Size: %u\n", (uint32)currentAlloc->m_size); if (currentAlloc->m_stackDepth >= 3 && SymGetLineFromAddr64(hProcess, dwAddress, &dwLineDisplacement, &line)) { fprintf(myFile, "%s:%u\n", line.FileName, line.LineNumber); } else { fprintf(myFile, "Unknown File\n"); } fprintf(myFile, "Callstack:\n"); for(int i = 0; i < currentAlloc->m_stackDepth; i++) { dwAddress = (DWORD64)currentAlloc->m_stack[i]; pSymbol->SizeOfStruct = 88; //sizeof(SYMBOL_INFO); pSymbol->MaxNameLen = MAX_SYM_NAME; if (SymFromAddr(hProcess, dwAddress, &dwDisplacement, pSymbol)) { const char* name = pSymbol->Name; fprintf(myFile, "\t%i: %s\n", i, name); } else { fprintf(myFile, "\t%i: Unknown\n", i); } } fprintf(myFile, "\n"); currentAlloc = currentAlloc->m_next; } _flushall(); CONTEXT Context; memset(&Context, 0, sizeof(Context)); RtlCaptureContext(&Context); fclose(myFile); } SymCleanup(hProcess); }
INT8 StartMultiThreadBuild ( BUILD_ITEM **BuildList, UINT32 ThreadNumber, INT8 *BuildDir ) /*++ Routine Description: Start multi-thread build for a specified build list Arguments: BuildList - build list for multi-thread build ThreadNumber - thread number for multi-thread build BuildDir - build dir Returns: 0 - Successfully finished the multi-thread build other value - Build failure --*/ { UINT32 Index; UINT32 Count; BUILD_ITEM *PreviousBuildItem; BUILD_ITEM *CurrentBuildItem; BUILD_ITEM *NextBuildItem; HANDLE *ThreadHandle; INT8 Cmd[MAX_PATH]; mError = 0; mDone = 0; mThreadNumber = ThreadNumber; mBuildDir = BuildDir; mPendingList = *BuildList; *BuildList = NULL; mWaitingList = NULL; mBuildingList = NULL; mDoneList = NULL; // // Do nothing when mPendingList is empty // if (mPendingList == NULL) { return 0; } // // Get build item count of mPendingList // Count = 0; CurrentBuildItem = mPendingList; while (CurrentBuildItem != NULL) { Count++; CurrentBuildItem = CurrentBuildItem->Next; } // // The semaphore is also used to wake up child threads for exit, // so need to make sure "maximum count" >= "thread number". // if (Count < ThreadNumber) { Count = ThreadNumber; } // // Init mSemaphoreHandle // mSemaphoreHandle = CreateSemaphore ( NULL, // default security attributes 0, // initial count Count, // maximum count NULL // unnamed semaphore ); if (mSemaphoreHandle == NULL) { Error (NULL, 0, 0, NULL, "failed to create semaphore"); RestoreBuildList (BuildList); return 1; } // // Init mEventHandle // mEventHandle = CreateEvent( NULL, // default security attributes FALSE, // auto-reset event TRUE, // initial state is signaled NULL // object not named ); if (mEventHandle == NULL) { Error (NULL, 0, 0, NULL, "failed to create event"); CloseHandle (mSemaphoreHandle); RestoreBuildList (BuildList); return 1; } // // Init mCriticalSection // InitializeCriticalSection (&mCriticalSection); // // Create build item log dir // sprintf (mLogDir, "%s\\Log", mBuildDir); _mkdir (mLogDir); // // Create child threads for muti-thread build // ThreadHandle = malloc (ThreadNumber * sizeof (HANDLE)); if (ThreadHandle == NULL) { Error (NULL, 0, 0, NULL, "failed to allocate memory"); CloseHandle (mSemaphoreHandle); CloseHandle (mEventHandle); RestoreBuildList (BuildList); return 1; } for (Index = 0; Index < ThreadNumber; Index++) { ThreadHandle[Index] = CreateThread ( NULL, // default security attributes 0, // use default stack size ThreadProc, // thread function (LPVOID)Index, // argument to thread function: use Index as thread id 0, // use default creation flags NULL // thread identifier not needed ); if (ThreadHandle[Index] == NULL) { Error (NULL, 0, 0, NULL, "failed to create Thread_%d", Index); mError = 1; ThreadNumber = Index; // // Make sure to wake up every child thread for exit // ReleaseSemaphore (mSemaphoreHandle, ThreadNumber, NULL); break; } } // // Loop until error occurred or no more build items pending for build // for (;;) { WaitForSingleObject (mEventHandle, INFINITE); if (mError) { break; } Count = 0; EnterCriticalSection (&mCriticalSection); PreviousBuildItem = NULL; CurrentBuildItem = mPendingList; while (CurrentBuildItem != NULL) { NextBuildItem = CurrentBuildItem->Next; if (CheckDependency (CurrentBuildItem->DependencyList)) { // // Move the current build item from mPendingList // if (PreviousBuildItem != NULL) { PreviousBuildItem->Next = NextBuildItem; } else { mPendingList = NextBuildItem; } // // Add the current build item to the head of mWaitingList // CurrentBuildItem->Next = mWaitingList; mWaitingList = CurrentBuildItem; Count++; } else { PreviousBuildItem = CurrentBuildItem; } CurrentBuildItem = NextBuildItem; } LeaveCriticalSection (&mCriticalSection); ReleaseSemaphore (mSemaphoreHandle, Count, NULL); if (mPendingList == NULL) { break; } } // // Wait until all threads have terminated // WaitForMultipleObjects (ThreadNumber, ThreadHandle, TRUE, INFINITE); if (mError && (mBuildingList != NULL)) { // // Dump build failure log of the first build item which doesn't finish the build // printf ("\tnmake -nologo -f %s all\n", mBuildingList->Makefile); sprintf (Cmd, "type %s\\%s_%s_%d.txt 2>NUL", mLogDir, mBuildingList->BaseName, mBuildingList->Processor, mBuildingList->Index); _flushall (); if (system (Cmd)) { Error (NULL, 0, 0, NULL, "failed to run \"%s\"", Cmd); } } DeleteCriticalSection (&mCriticalSection); for (Index = 0; Index < ThreadNumber; Index++) { CloseHandle (ThreadHandle[Index]); } free (ThreadHandle); CloseHandle (mSemaphoreHandle); CloseHandle (mEventHandle); RestoreBuildList (BuildList); return mError; }
JsValueRef WScriptJsrt::LoadScript(JsValueRef callee, LPCSTR fileName, LPCSTR fileContent, LPCSTR scriptInjectType, bool isSourceModule) { HRESULT hr = E_FAIL; JsErrorCode errorCode = JsNoError; LPCWSTR errorMessage = _u("Internal error."); JsValueRef returnValue = JS_INVALID_REFERENCE; JsErrorCode innerErrorCode = JsNoError; JsContextRef currentContext = JS_INVALID_REFERENCE; JsRuntimeHandle runtime = JS_INVALID_RUNTIME_HANDLE; char fullPathNarrow[_MAX_PATH]; size_t len = 0; IfJsrtErrorSetGo(ChakraRTInterface::JsGetCurrentContext(¤tContext)); IfJsrtErrorSetGo(ChakraRTInterface::JsGetRuntime(currentContext, &runtime)); if (fileName) { if (_fullpath(fullPathNarrow, fileName, _MAX_PATH) == nullptr) { IfFailGo(E_FAIL); } // canonicalize that path name to lower case for the profile storage // REVIEW: This doesn't work for UTF8... len = strlen(fullPathNarrow); for (size_t i = 0; i < len; i++) { fullPathNarrow[i] = (char)tolower(fullPathNarrow[i]); } } else { // No fileName provided (WScript.LoadScript()), use dummy "script.js" strcpy_s(fullPathNarrow, "script.js"); } // this is called with LoadModuleCallback method as well where caller pass in a string that should be // treated as a module source text instead of opening a new file. if (isSourceModule || (strcmp(scriptInjectType, "module") == 0)) { errorCode = LoadModuleFromString(fileName, fileContent); } else if (strcmp(scriptInjectType, "self") == 0) { JsContextRef calleeContext; IfJsrtErrorSetGo(ChakraRTInterface::JsGetContextOfObject(callee, &calleeContext)); IfJsrtErrorSetGo(ChakraRTInterface::JsSetCurrentContext(calleeContext)); errorCode = ChakraRTInterface::JsRunScriptUtf8(fileContent, GetNextSourceContext(), fullPathNarrow, &returnValue); if(errorCode == JsNoError) { errorCode = ChakraRTInterface::JsGetGlobalObject(&returnValue); } IfJsrtErrorSetGo(ChakraRTInterface::JsSetCurrentContext(currentContext)); } else if (strcmp(scriptInjectType, "samethread") == 0) { JsValueRef newContext = JS_INVALID_REFERENCE; // Create a new context and set it as the current context IfJsrtErrorSetGo(ChakraRTInterface::JsCreateContext(runtime, &newContext)); IfJsrtErrorSetGo(ChakraRTInterface::JsSetCurrentContext(newContext)); // Initialize the host objects Initialize(); errorCode = ChakraRTInterface::JsRunScriptUtf8(fileContent, GetNextSourceContext(), fullPathNarrow, &returnValue); if (errorCode == JsNoError) { errorCode = ChakraRTInterface::JsGetGlobalObject(&returnValue); } // Set the context back to the old one ChakraRTInterface::JsSetCurrentContext(currentContext); } else { errorCode = JsErrorInvalidArgument; errorMessage = _u("Unsupported argument type inject type."); } Error: JsValueRef value = returnValue; if (errorCode != JsNoError) { if (innerErrorCode != JsNoError) { // Failed to retrieve the inner error message, so set a custom error string errorMessage = ConvertErrorCodeToMessage(errorCode); } JsValueRef error = JS_INVALID_REFERENCE; JsValueRef messageProperty = JS_INVALID_REFERENCE; ERROR_MESSAGE_TO_STRING(errCode, errorMessage, messageProperty); if (errCode == JsNoError) { errCode = ChakraRTInterface::JsCreateError(messageProperty, &error); if (errCode == JsNoError) { errCode = ChakraRTInterface::JsSetException(error); } } ChakraRTInterface::JsDoubleToNumber(errorCode, &value); } _flushall(); return value; }
void __cdecl Initial_Boundary_Constraints( const int *phase, // Current phase number const int *dimx, // Dimension of state vector X const int *dimu, // Dimension of control vector U const int *dimip, // Dimension of integer parameter vector const int *dimrp, // Dimension of real parameter vector const Phase_Info_Type *fazinf, // Record with additional phase info const double *t, // Time t of evaluation const double x[], // State vector X at time t const double u[], // Control vector U at time t const int ipar[], // Integer parameter vector of phase const double rpar[], // Real parameter vector of phase const int *dimbc, // dimension of boundary constraint vector const Decision_Type evalc[], // Which constraints to evaluate double *bcon, // Vector of boundary constraints int *error // Error flag ) { /* computes the boundary constraints associated with the initial * time of the optimal control problem (t0 of *phase) * as a function of the initial time, the state- and control * vector at time t0 and the real parameter vector of *phase. */ double *mee_coords_LCI; // contains the first six elements of the state, ie the equ. elements double *kep_coords_LCI; // contains the first six elements of the state in earth centred keplerian elements int i; #ifdef DEBUG_MODE printf("Initial Boundary Constraints\n");_flushall(); #endif *error = 0; // Initialise storage mee_coords_LCI = dvector(1,6); kep_coords_LCI = dvector(1,6); for (i=1; i<=6; i++) { mee_coords_LCI[i] = x[i-1]; kep_coords_LCI[i] = 0.0; } // Calculate parameters mee2kep(mee_coords_LCI, kep_coords_LCI); /* Semimajor axis = 1,838km */ if (evalc[0] == yes) { bcon[0] = 1.0 - kep_coords_LCI[1]/1.838e6; } /* Eccentricity < 0.1 */ if (evalc[1] == yes) { bcon[1] = 0.1 - kep_coords_LCI[2]; } /* Inclination = 70° */ if (evalc[2] == yes) { bcon[2] = kep_coords_LCI[3]*R2D/70 - 1.0; } /* Time = 1000 days */ if (evalc[3] == yes) { bcon[3] = x[6]/1000 - 1.0; } /* Mass = 100.0kg */ if (evalc[4] == yes) { bcon[4] = x[7]/100.0 - 1.0; } // Free memory free_dvector(mee_coords_LCI,1,6); free_dvector(kep_coords_LCI,1,6); }