void main(void) { int i; #ifdef DYNAMIC /* If we use dynamic array, allocate RAM for it */ Data = (struct Record *)calloc(9,sizeof(struct Record)); if (Data == NULL) { fputs("ERROR! couldn't allocate enough RAM!\n",stderr); exit(1); } #endif /* Handy shorthand for initializing the array */ #define INITIALIZE(y,z) strcpy(Data[i].Name,y);Data[i].Ext=z; i++ /*** Set up the data in the array ***/ i=0; INITIALIZE("Marco C. Mason", 566); INITIALIZE("Mark W. Crane", 531); INITIALIZE("Jody Gilbert", 507); INITIALIZE("Duane Spurlock", 528); INITIALIZE("Tara Billinger", 539); INITIALIZE("Tim Landgrave", 556); INITIALIZE("Douglas Cobb", 523); INITIALIZE("Maureen Pawley", 508); INITIALIZE("Karl Feige", 559); /*** Sort the list by telephone extension ***/ qsort(Data, 9, sizeof(struct Record),RecordCompare); /*** Print the resulting phone list ***/ #ifdef DYNAMIC puts("Phone list output (using DYNAMIC array)"); #else puts("Phone list output (using STATIC array)"); #endif puts("\nRecord Telephone\nNumber Extension Name"); for (i=0; i<9; i++) printf(" %02d %03d %s\n", i+1, Data[i].Ext, Data[i].Name); }
int main() { int i; string r, t; INITIALIZE("%d \t %s \t %s\n", i, t.c_str(), r.c_str()); set(r, "a"); i = len(r); while(unknown()) { PRINT_VARS(); t = unknown_s(1); set(r, cat(r, t)); } PRINT_VARS(); assert(eql(sub(r, 0, i), "a")); return 0; }
int main() { int i; string r; INITIALIZE("%d \t %s\n", i, r.c_str()); i = 0; set(r, "a"); while(unknown()) { PRINT_VARS(); set(r, rep(r, "a", "aa")); ++i; } PRINT_VARS(); assert(len(r) > i); return 0; }
int main() { SETUP_WORKSPACE(); CHOSE_LANGUAGE(); DESCRIPTION(); CHOSE_DEVICE(); YOUR_CHOICE(); MIUI_ROM_CHECK(); INITIALIZE(); DELETE_DHD_FILES(); COPY_CM7_FILES(); CUSTOMIZATION(); SIGN_ROM(); OUTPUT_CHECK(); CLEAN_WORKSPACE(); AUTO_FLASH_FUNCTION(); CLEAN_WORKSPACE(); return 0; }
int main(int argc, char *argv[]) { /* These are static so that they're initially zero. */ static char * abbrev; static size_t abbrevsize; int i; bool vflag; bool Vflag; char * cutarg; char * cuttimes; time_t cutlotime; time_t cuthitime; time_t now; bool iflag = false; cutlotime = absolute_min_time; cuthitime = absolute_max_time; #if HAVE_GETTEXT (void) setlocale(LC_ALL, ""); #ifdef TZ_DOMAINDIR (void) bindtextdomain(TZ_DOMAIN, TZ_DOMAINDIR); #endif /* defined TEXTDOMAINDIR */ (void) textdomain(TZ_DOMAIN); #endif /* HAVE_GETTEXT */ progname = argv[0]; for (i = 1; i < argc; ++i) if (strcmp(argv[i], "--version") == 0) { (void) printf("zdump %s%s\n", PKGVERSION, TZVERSION); return EXIT_SUCCESS; } else if (strcmp(argv[i], "--help") == 0) { usage(stdout, EXIT_SUCCESS); } vflag = Vflag = false; cutarg = cuttimes = NULL; for (;;) switch (getopt(argc, argv, "c:it:vV")) { case 'c': cutarg = optarg; break; case 't': cuttimes = optarg; break; case 'i': iflag = true; break; case 'v': vflag = true; break; case 'V': Vflag = true; break; case -1: if (! (optind == argc - 1 && strcmp(argv[optind], "=") == 0)) goto arg_processing_done; /* Fall through. */ default: usage(stderr, EXIT_FAILURE); } arg_processing_done:; if (iflag | vflag | Vflag) { intmax_t lo; intmax_t hi; char *loend, *hiend; intmax_t cutloyear = ZDUMP_LO_YEAR; intmax_t cuthiyear = ZDUMP_HI_YEAR; if (cutarg != NULL) { lo = strtoimax(cutarg, &loend, 10); if (cutarg != loend && !*loend) { hi = lo; cuthiyear = hi; } else if (cutarg != loend && *loend == ',' && (hi = strtoimax(loend + 1, &hiend, 10), loend + 1 != hiend && !*hiend)) { cutloyear = lo; cuthiyear = hi; } else { fprintf(stderr, _("%s: wild -c argument %s\n"), progname, cutarg); return EXIT_FAILURE; } } if (cutarg != NULL || cuttimes == NULL) { cutlotime = yeartot(cutloyear); cuthitime = yeartot(cuthiyear); } if (cuttimes != NULL) { lo = strtoimax(cuttimes, &loend, 10); if (cuttimes != loend && !*loend) { hi = lo; if (hi < cuthitime) { if (hi < absolute_min_time) hi = absolute_min_time; cuthitime = hi; } } else if (cuttimes != loend && *loend == ',' && (hi = strtoimax(loend + 1, &hiend, 10), loend + 1 != hiend && !*hiend)) { if (cutlotime < lo) { if (absolute_max_time < lo) lo = absolute_max_time; cutlotime = lo; } if (hi < cuthitime) { if (hi < absolute_min_time) hi = absolute_min_time; cuthitime = hi; } } else { (void) fprintf(stderr, _("%s: wild -t argument %s\n"), progname, cuttimes); return EXIT_FAILURE; } } } gmtzinit(); INITIALIZE (now); if (! (iflag | vflag | Vflag)) now = time(NULL); longest = 0; for (i = optind; i < argc; i++) { size_t arglen = strlen(argv[i]); if (longest < arglen) longest = arglen < INT_MAX ? arglen : INT_MAX; } for (i = optind; i < argc; ++i) { timezone_t tz = tzalloc(argv[i]); char const *ab; time_t t; struct tm tm, newtm; bool tm_ok; if (!tz) { errx(EXIT_FAILURE, "%s", argv[i]); } if (! (iflag | vflag | Vflag)) { show(tz, argv[i], now, false); tzfree(tz); continue; } warned = false; t = absolute_min_time; if (! (iflag | Vflag)) { show(tz, argv[i], t, true); t += SECSPERDAY; show(tz, argv[i], t, true); } if (t < cutlotime) t = cutlotime; tm_ok = my_localtime_rz(tz, &t, &tm) != NULL; if (tm_ok) { ab = saveabbr(&abbrev, &abbrevsize, &tm); if (iflag) { showtrans("\nTZ=%f", &tm, t, ab, argv[i]); showtrans("-\t-\t%Q", &tm, t, ab, argv[i]); } } else ab = NULL; while (t < cuthitime) { time_t newt = ((t < absolute_max_time - SECSPERDAY / 2 && t + SECSPERDAY / 2 < cuthitime) ? t + SECSPERDAY / 2 : cuthitime); struct tm *newtmp = localtime_rz(tz, &newt, &newtm); bool newtm_ok = newtmp != NULL; if (! (tm_ok & newtm_ok ? (delta(&newtm, &tm) == newt - t && newtm.tm_isdst == tm.tm_isdst && strcmp(abbr(&newtm), ab) == 0) : tm_ok == newtm_ok)) { newt = hunt(tz, argv[i], t, newt); newtmp = localtime_rz(tz, &newt, &newtm); newtm_ok = newtmp != NULL; if (iflag) showtrans("%Y-%m-%d\t%L\t%Q", newtmp, newt, newtm_ok ? abbr(&newtm) : NULL, argv[i]); else { show(tz, argv[i], newt - 1, true); show(tz, argv[i], newt, true); } } t = newt; tm_ok = newtm_ok; if (newtm_ok) { ab = saveabbr(&abbrev, &abbrevsize, &newtm); tm = newtm; } } if (! (iflag | Vflag)) { t = absolute_max_time; t -= SECSPERDAY; show(tz, argv[i], t, true); t += SECSPERDAY; show(tz, argv[i], t, true); } tzfree(tz); } close_file(stdout); if (errout && (ferror(stderr) || fclose(stderr) != 0)) return EXIT_FAILURE; return EXIT_SUCCESS; }
int main(const int argc, char *argv[]) { register const char * format; register const char * value; register const char * cp; register int ch; register int dousg; register int aflag = 0; register int dflag = 0; register int nflag = 0; register int tflag = 0; register int minuteswest; register int dsttime; register double adjust; time_t now; time_t t; INITIALIZE(dousg); INITIALIZE(minuteswest); INITIALIZE(dsttime); INITIALIZE(adjust); INITIALIZE(t); #ifdef LC_ALL (void) setlocale(LC_ALL, ""); #endif /* defined(LC_ALL) */ #if HAVE_GETTEXT #ifdef TZ_DOMAINDIR (void) bindtextdomain(TZ_DOMAIN, TZ_DOMAINDIR); #endif /* defined(TEXTDOMAINDIR) */ (void) textdomain(TZ_DOMAIN); #endif /* HAVE_GETTEXT */ (void) time(&now); format = value = NULL; while ((ch = getopt(argc, argv, "ucnd:t:a:")) != EOF && ch != -1) { switch (ch) { default: usage(); case 'u': /* do it in UTC */ case 'c': dogmt(); break; case 'n': /* don't set network */ nflag = 1; break; case 'd': /* daylight saving time */ if (dflag) { (void) fprintf(stderr, _("date: error: multiple -d's used")); usage(); } dflag = 1; cp = optarg; dsttime = atoi(cp); if (*cp == '\0' || *nondigit(cp) != '\0') wildinput(_("-t value"), optarg, _("must be a non-negative number")); break; case 't': /* minutes west of UTC */ if (tflag) { (void) fprintf(stderr, _("date: error: multiple -t's used")); usage(); } tflag = 1; cp = optarg; minuteswest = atoi(cp); if (*cp == '+' || *cp == '-') ++cp; if (*cp == '\0' || *nondigit(cp) != '\0') wildinput(_("-d value"), optarg, _("must be a number")); break; case 'a': /* adjustment */ if (aflag) { (void) fprintf(stderr, _("date: error: multiple -a's used")); usage(); } aflag = 1; cp = optarg; adjust = atof(cp); if (*cp == '+' || *cp == '-') ++cp; if (*cp == '\0' || strcmp(cp, ".") == 0) wildinput(_("-a value"), optarg, _("must be a number")); cp = nondigit(cp); if (*cp == '.') ++cp; if (*nondigit(cp) != '\0') wildinput(_("-a value"), optarg, _("must be a number")); break; } } while (optind < argc) { cp = argv[optind++]; if (*cp == '+') if (format == NULL) format = cp + 1; else { (void) fprintf(stderr, _("date: error: multiple formats in command line\n")); usage(); } else if (value == NULL) value = cp; else { (void) fprintf(stderr, _("date: error: multiple values in command line\n")); usage(); } } if (value != NULL) { /* ** This order ensures that "reasonable" twelve-digit inputs ** (such as 120203042006) won't be misinterpreted ** even if time_t's range all the way back to the thirteenth ** century. Do not change the order. */ t = convert(value, (dousg = TRUE), now); if (t == -1) t = convert(value, (dousg = FALSE), now); if (t == -1) { /* ** Out of range values, ** or time that falls in a DST transition hole? */ if ((cp = strchr(value, '.')) != NULL) { /* ** Ensure that the failure of ** TZ=America/New_York date 8712312359.60 ** doesn't get misdiagnosed. (It was ** TZ=America/New_York date 8712311859.60 ** when the leap second was inserted.) ** The normal check won't work since ** the given time is valid in UTC. */ if (atoi(cp + 1) >= SECSPERMIN) wildinput(_("time"), value, _("out of range seconds given")); } dogmt(); t = convert(value, FALSE, now); if (t == -1) t = convert(value, TRUE, now); wildinput(_("time"), value, (t == -1) ? _("out of range value given") : _("time skipped when clock springs forward")); } } /* ** Entire command line has now been checked. */ if (aflag) { #if HAVE_ADJTIME struct timeval tv; tv.tv_sec = (int) adjust; tv.tv_usec = (int) ((adjust - tv.tv_sec) * 1000000L); if (adjtime(&tv, NULL) != 0) oops("adjtime"); #endif /* HAVE_ADJTIME */ #if !HAVE_ADJTIME reset(now + adjust, nflag); #endif /* !HAVE_ADJTIME */ /* ** Sun silently ignores everything else; we follow suit. */ exit(retval); } if (dflag || tflag) { #if HAVE_SETTIMEOFDAY == 2 struct timezone tz; if (!dflag || !tflag) if (gettimeofday(NULL, &tz) != 0) oops("gettimeofday"); if (dflag) tz.tz_dsttime = dsttime; if (tflag) tz.tz_minuteswest = minuteswest; if (settimeofday(NULL, &tz) != 0) oops("settimeofday"); #endif /* HAVE_SETTIMEOFDAY == 2 */ #if HAVE_SETTIMEOFDAY != 2 (void) fprintf(stderr, _("date: warning: kernel doesn't keep -d/-t information, option ignored\n")); #endif /* HAVE_SETTIMEOFDAY != 2 */ } if (value == NULL) display(format); reset(t, nflag); checkfinal(value, dousg, t, now); #ifdef EBUG { struct tm tm; tm = *localtime(&t); timeout(stdout, "%c\n", &tm); exit(retval); } #endif /* defined EBUG */ display(format); /* gcc -Wall pacifier */ for ( ; ; ) continue; }
int main(int argc, char *argv[]) { register int i; register int c; register int vflag; register char * cutarg; register long cutloyear = ZDUMP_LO_YEAR; register long cuthiyear = ZDUMP_HI_YEAR; register time_t cutlotime; register time_t cuthitime; register char ** fakeenv; time_t now; time_t t; time_t newt; struct tm tm; struct tm newtm; register struct tm * tmp; register struct tm * newtmp; INITIALIZE(cutlotime); INITIALIZE(cuthitime); #if HAVE_GETTEXT (void) setlocale(LC_ALL, ""); #ifdef TZ_DOMAINDIR (void) bindtextdomain(TZ_DOMAIN, TZ_DOMAINDIR); #endif /* defined TEXTDOMAINDIR */ (void) textdomain(TZ_DOMAIN); #endif /* HAVE_GETTEXT */ progname = argv[0]; for (i = 1; i < argc; ++i) if (strcmp(argv[i], "--version") == 0) { (void) printf("zdump %s%s\n", PKGVERSION, TZVERSION); exit(EXIT_SUCCESS); } else if (strcmp(argv[i], "--help") == 0) { usage(stdout, EXIT_SUCCESS); } vflag = 0; cutarg = NULL; while ((c = getopt(argc, argv, "c:v")) == 'c' || c == 'v') if (c == 'v') vflag = 1; else cutarg = optarg; if ((c != EOF && c != -1) || (optind == argc - 1 && strcmp(argv[optind], "=") == 0)) { usage(stderr, EXIT_FAILURE); } if (vflag) { if (cutarg != NULL) { long lo; long hi; char dummy; if (sscanf(cutarg, "%ld%c", &hi, &dummy) == 1) { cuthiyear = hi; } else if (sscanf(cutarg, "%ld,%ld%c", &lo, &hi, &dummy) == 2) { cutloyear = lo; cuthiyear = hi; } else { (void) fprintf(stderr, _("%s: wild -c argument %s\n"), progname, cutarg); exit(EXIT_FAILURE); } } checkabsolutes(); cutlotime = yeartot(cutloyear); cuthitime = yeartot(cuthiyear); } (void) time(&now); longest = 0; for (i = optind; i < argc; ++i) if (strlen(argv[i]) > longest) longest = strlen(argv[i]); { register int from; register int to; for (i = 0; environ[i] != NULL; ++i) continue; fakeenv = malloc((i + 2) * sizeof *fakeenv); if (fakeenv == NULL || (fakeenv[0] = malloc(longest + 4)) == NULL) { (void) perror(progname); exit(EXIT_FAILURE); } to = 0; (void) strcpy(fakeenv[to++], "TZ="); for (from = 0; environ[from] != NULL; ++from) if (strncmp(environ[from], "TZ=", 3) != 0) fakeenv[to++] = environ[from]; fakeenv[to] = NULL; environ = fakeenv; } for (i = optind; i < argc; ++i) { static char buf[MAX_STRING_LENGTH]; (void) strcpy(&fakeenv[0][3], argv[i]); if (!vflag) { show(argv[i], now, FALSE); continue; } warned = FALSE; t = absolute_min_time; show(argv[i], t, TRUE); t += SECSPERHOUR * HOURSPERDAY; show(argv[i], t, TRUE); if (t < cutlotime) t = cutlotime; tmp = my_localtime(&t); if (tmp != NULL) { tm = *tmp; (void) strncpy(buf, abbr(&tm), (sizeof buf) - 1); } for ( ; ; ) { if (t >= cuthitime || t >= cuthitime - SECSPERHOUR * 12) break; newt = t + SECSPERHOUR * 12; newtmp = localtime(&newt); if (newtmp != NULL) newtm = *newtmp; if ((tmp == NULL || newtmp == NULL) ? (tmp != newtmp) : (delta(&newtm, &tm) != (newt - t) || newtm.tm_isdst != tm.tm_isdst || strcmp(abbr(&newtm), buf) != 0)) { newt = hunt(argv[i], t, newt); newtmp = localtime(&newt); if (newtmp != NULL) { newtm = *newtmp; (void) strncpy(buf, abbr(&newtm), (sizeof buf) - 1); } } t = newt; tm = newtm; tmp = newtmp; } t = absolute_max_time; t -= SECSPERHOUR * HOURSPERDAY; show(argv[i], t, TRUE); t += SECSPERHOUR * HOURSPERDAY; show(argv[i], t, TRUE); } if (fflush(stdout) || ferror(stdout)) { (void) fprintf(stderr, "%s: ", progname); (void) perror(_("Error writing to standard output")); exit(EXIT_FAILURE); } exit(EXIT_SUCCESS); /* If exit fails to exit... */ return EXIT_FAILURE; }
int main(int argc, char *argv[]) { /* DRIVER_01 is a FLOW-MOTION LIMITED flow scheme! The flow will end when all vents have no more lava to effuse AND when the flow is no longer innundating new grid cells. */ /*DRIVER for a lava flow code ALGORITHM: Read in a Configuration File with INITIALIZE Load a DEM Raster with DEM_LOADER and assign parameters to a data grid Create Cellular Automata lists and assign source vents with INIT_FLOW Main Flow Loop: If there is more volume to erupt at source vents, call PULSE Move lava from cells to neighbors with DISTRIBUTE If flow is still moving, keep looping to call DISTRIBUTE After flow is completely erupted: Check for Conservation of Mass Write out requested Model Output to user-defined file paths */ /*VARIABLES******************************************************************/ /*Files*/ char *configFilename = argv[1]; /*configuration file path */ char **Filenames; /*A list of file paths for model output */ char tempFilename[15]; /*A temporary file path for whatever use*/ /*Main Arrays*/ DataCell **dataGrid; /*Global Data Grid */ Automata **CAList; /*Cellular Automata Lists (Active Cells)*/ VentArr *Vents; /*Source Vent List */ unsigned *ActiveCounter; /*Number of Active Cells in CA List */ /*Model Parameters*/ int i,j, ret; /*loop variables, function return value */ unsigned CAListCount = 0; /*Number of CA Lists, def in INIT_FLOW */ unsigned CAListSize = 0; /*Size of each CA List, def in INIT_FLOW*/ unsigned ventCount = 0; /*Number of Src Vents, def in INITIALIZE*/ int pulseCount = 0; /*Current number of Main PULSE loops */ /*Physical Parameters*/ double residualThickness; /*Residual Flow Thickness */ double *DEMmetadata; /*Geographic Coordinates of DEM Raster */ double elevationUncertainty; /*DEM Raster Elevation Uncertainty */ double volumeToErupt; /*Total Volume to deliver to vent cells */ double volumeErupted = 0; /*Total Volume in All Active Cells */ double volumeRemaining; /*Volume Remaining to be Erupted */ int volumeRemainingBool = 0; /*0 if volume left to erupt, otherwise 1*/ /*Post Flow Motion Detection Variables*/ double TotalMotion = 0; /*Summed thickness change in all cells */ double MinTotalMotion = 1e-11; /*Threshold: below it flow is "stagnant"*/ unsigned lastmotionCounter = 0; /*Number of loops since last motion */ unsigned maxLastMotionCount = 10; /*Max loops allowed since last motion */ unsigned lastActiveCounter = 0; /*Number of active cells in prev. loop */ time_t LastInundationTime; /*Timestamp of last active cell creation*/ double maxLastInundationTime=10.0;/*Max time allowed since last cell cretn*/ /*TIME AND RANDOM NUMBER GEN*************************************************/ startTime = time(NULL); /*Define Start Time*/ srand(time(NULL)); /*Seed random number generator*/ /*WELCOME USER TO SIMULATION AND CHECK FOR CORRECT USAGE*********************/ printf("\n\n MOLASSES is a lava flow simulator.\n\n"); /*User must supply the name of the executable and a configuration file*/ if(argc<2) { printf("Usage: %s config-filename\n",argv[0]); return(-1); } printf("Beginning flow simulation...\n"); /*MODULE: INITIALIZE*********************************************************/ /* Assigns several empty variables based on a user-defined configuration file. */ /* File Name List output in this order: [0] - DEM [1] - Residual Flow Thickness [2] - Elevation Uncertainty [3] - Output file: ASCII X,Y,Thickness [4] - Output file: Hit Map [5] - Output file: Raster Thickness [6] - Output file: Raster Elevation [7] - Output file: Raster Elevation + Flow Thickness */ ret = INITIALIZE(configFilename, /*chr Configuration File Name */ &Filenames, /*chr File Name List */ &residualThickness, /*dbl Global Residual Flow Thickness*/ &elevationUncertainty, /*dbl Global Elevation Uncertainty */ &Vents, /*ventarr Vent Structure Array */ &ventCount /*unsignd Number of Vents */ ); /*Check for Error flag (INITIALIZE returns <0 value)*/ if(ret<0){ printf("\nERROR [MAIN]: Error flag returned from [INITIALIZE].\n"); printf("Exiting.\n"); return(-1); } /*MODULE: DEM_LOADER*********************************************************/ /* Loads Raster into Global Data Grid based on code: TOPOG - Loads a DEM raster into the data grid's dem_elev value RESID - Loads a raster into the data grid's residual value T_UNC - Loads a raster into the data grid's elev_uncert value Returns a metadata list of geographic coordinates of the raster */ /* DEMmetadata format: [0] lower left x [1] w-e pixel resolution [2] number of cols, assigned manually [3] lower left y [4] number of lines, assigned manually [5] n-s pixel resolution (negative value) */ /*Assign Topography to Data Grid Locations*/ DEMmetadata = DEM_LOADER(Filenames[0], /*char DEM file name */ &dataGrid, /*DataCell Global Data Grid*/ "TOPOG" /*DEM_LOADER Code Topography */ ); /*Check for Error flag (DEM_LOADER returns a null metadata list)*/ if(DEMmetadata==NULL){ printf("\nError [MAIN]: Error flag returned from DEM_LOADER[TOPOG].\n"); printf("Exiting.\n"); return(-1); } /*Assign Residual Thickness to Data Grid Locations*/ /*If residualThickness is -1, user input a Residual Thickness Map*/ if(residualThickness==-1) { DEMmetadata = DEM_LOADER(Filenames[1], /*char Residual filename*/ &dataGrid, /*DataCell Global Data Grid */ "RESID" /*DEM_LOADER Code Resid Thickness */ ); /*Check for Error flag (DEM_LOADER returns a null metadata list)*/ if(DEMmetadata==NULL){ printf("\nError [MAIN]: Error flag returned from DEM_LOADER[RESID].\n"); printf("Exiting.\n"); return(-1); } } /*If residualThickness is not -1, it is constant globally.*/ else { /*Write residual flow thickness into 2D Global Data Array*/ for(i=0;i<DEMmetadata[4];i++) { for(j=0;j<DEMmetadata[2];j++) { dataGrid[i][j].residual = residualThickness; } } } /*Assign Elevation Uncertainty to Data Grid Locations*/ /*If elevationUncertainty is -1, user input an elevation uncertainty map*/ if(elevationUncertainty==-1) { DEMmetadata = DEM_LOADER(Filenames[2], /*char uncertny filename*/ &dataGrid, /*DataCell Global Data Grid */ "T_UNC" /*DEM_LOADER Code elev uncertainty */ ); /*Check for Error flag (DEM_LOADER returns a null metadata list)*/ if(DEMmetadata==NULL){ printf("\nError [MAIN]: Error flag returned from DEM_LOADER[T_UNC].\n"); printf("Exiting.\n"); return(-1); } } /*If elevationUncertainty is not -1, it is constant globally.*/ else { /*Write elevation uncertainty values into 2D Global Data Array*/ for(i=0;i<DEMmetadata[4];i++) { for(j=0;j<DEMmetadata[2];j++) { dataGrid[i][j].elev_uncert = elevationUncertainty; } } } /*MODULE: INIT_FLOW**********************************************************/ /* Creates Active Cellular Automata lists and activates vents in them. Also creates bookkeeper variables: total size of CA lists total number of CA lists total number of active automata in the CA list total volume to erupt (combined volumes to erupt at vents) */ ret = INIT_FLOW(dataGrid, /*DataCell Global Data Grid */ &CAList, /*Automaton Active Cells List */ Vents, /*VentArr Vent Data Array */ &CAListCount, /*unsigned Number of CA Lists created */ &CAListSize, /*unsigned Size of each empty CA List */ ventCount, /*unsigned Number of Vents */ &ActiveCounter, /*unsigned Number of active cells in CA List*/ DEMmetadata, /*double Geographic Metadata */ &volumeToErupt /*double Volume that the model will expel */ ); /*Check for Error flag (INIT_FLOW returns <0 value)*/ if(ret<0) { printf("\nError [MAIN]: Error flag returned from [INIT_FLOW].\n"); printf("Exiting.\n"); return(-1); } /****************************************************************************/ /*MAIN FLOW LOOP: PULSE LAVA AND DISTRIBUTE TO CELLS*************************/ /****************************************************************************/ volumeRemaining = volumeToErupt; /*set countdown bookkeeper volumeRemaining*/ printf("\n Running Flow\n"); /*Loop to call PULSE and DISTRIBUTE only if volume remains to be erupted OR if flow has not stopped moving*/ while((volumeRemaining > 0)||(lastmotionCounter<maxLastMotionCount)) { if(volumeRemaining > 0) { /*If there is more lava to erupt, call PULSE*/ /*MODULE: PULSE************************************************************/ /* Delivers lava to vents based on information in Vent Data Array. Returns total volume remaining to be erupted. */ ret = PULSE(CAList[1], /*Automaton Active Cells List */ &Vents, /*VentArr Vent Data Array */ ActiveCounter[1], /*unsigned Number of activ cells in CA List*/ &volumeRemaining, /*double Countdown Lava Volume bookkeeper*/ ventCount, /*unsigned Number of vents */ DEMmetadata /*double Geographic Metadata */ ); /*Check for Error flags (PULSE returns <0 or 0 value)*/ if(ret<0) { printf("\nERROR [MAIN]: Error flag returned from [PULSE].\n"); printf("Exiting.\n"); return(-1); } else if (ret==0) { if (volumeRemaining) { /*This return should not be possible, Pulse should return 0 if no volume remains*/ printf("\nERROR [MAIN]: Error between [PULSE] return and lava vol.\n"); printf("Exiting.\n"); return(-1); } /*If ret==0, PULSE was called even though there was no lava to distribute. Do not call Pulse or Distribute anymore! Break out of While loop. */ break; } /*if Pulse module successfully updated vents, ret will > 0. Continue, call Distribute module.*/ /*Update status message on screen*/ printf("\rInundated Cells: %-7d; Volume Remaining: %10.2f",ActiveCounter[1], volumeRemaining); } else { /*if no more volume to erupt, but flow still moving*/ /*Update status message on screen to show flow motion*/ printf("\rInundated Cells: %-7d; total dZ in flow: %10.2e",ActiveCounter[1], TotalMotion); } /*MODULE: DISTRIBUTE*******************************************************/ /* Distributes lava from cells to neighboring cells depending on module specific algorithm (e.g. slope-proportional sharing). Updates a Cellular Automata List and the active cell counter.*/ ret = DISTRIBUTE(dataGrid, /*DataCell Global Data Grid */ CAList[1], /*Automaton Active Cells List */ &ActiveCounter[1], /*unsigned Number of active cells */ DEMmetadata /*double Geographic Metadata */ ); /*Check for Error flag (DISTRIBUTE returns <0 value)*/ if(ret<0) { printf("\nERROR [MAIN]: Error flag returned from [DISTRIBUTE].\n"); printf("Exiting.\n"); return(-1); } /*If you want to output the flow at EVERY Pulse, here is a good place to do it. A temporary file name variable is declared using the number of times this Pulse loop has been completed, then the OUTPUT module is called. Uncomment the lines below if you want this. Commenting out the file name declaration creates warnings since the variables won't later be used, so I've left it uncommented out. (It only runs once per pulse, so it doesn't slow the code down).*/ /*increment pulse count, then rename the temporary file path.*/ snprintf(tempFilename,15,"pulse_%04d.xyz",(++pulseCount)); /*MODULE: OUTPUT**************************************/ /* writes out a file. Arguments: DataCell Global Data Grid Automaton Active Cells List unsigned Number of active cells string Output Filename OUTPUT Code: 0 = ASCII X,Y,Thickness File double Geographic Metadata string Original Raster Projection */ /* ret = OUTPUT(dataGrid, CAList[1], ActiveCounter[1], tempFilename, 0, DEMmetadata, "" ); */ /*Check for Error flag (OUTPUT returns <0 value)*/ /* if(ret<0){ printf("\nERROR [MAIN]: Error flag returned from [OUTPUT].\n"); printf("Exiting.\n"); return(-1); } */ /*TEST TO SEE IF FLOW IS STILL PROGRESSING, IF VOLUME HAS RUN OUT*/ /*This Driver Module continues to call the DISTRIBUTE Module if there is significant flow within the lava flow, even after all lava has been delivered to the vents via the PULSE Module. Flow will continue to distribute if: 1) There is still volume to deliver to vent 2) The summed change in flow thickness across all cells is > than a pre-defined MinTotalMotion variable. 3) The time elapsed in seconds since the last active cell was created is < than a pre-defined maxLastInundationTime. If the summed change in flow thickness (dz) is negligable, lastmotionCounter is incremented. If lastmotionCounter==pre-defined maxLastMotionCount, flow will stop. If the time elapsed since the last cell creation is significant, lastmotionCounter will be set at maxLastMotionCount, flow will stop. */ /*Only test for remaining flow IF eruption volume has run out*/ if(volumeRemaining<=0) { /*If this is the first time volume is 0, start new screen output line*/ if((volumeRemainingBool++)==0) printf("\n"); /*MOTION TEST - If movement has stopped, end the flow*/ TotalMotion=0.0; /*Reset TotalMotion to 0*/ for(i=1;i<=ActiveCounter[1];i++) { /*Add change in volume of all active cells CA List[2] is a copy of the Active CA List of the last Pulse Loop*/ TotalMotion += fabs(CAList[1][i].elev - CAList[2][i].elev); } /*If flow has not changed, increment lastmotionCounter*/ if(TotalMotion <= MinTotalMotion) ++lastmotionCounter; /*If flow has changed, reset lastmotionCounter and store flow values in spare CA List.*/ else{ lastmotionCounter=0; /*reset*/ for(i=1;i<=ActiveCounter[1];i++) { /*For all Active Cells*/ CAList[2][i].elev = CAList[1][i].elev; /*Copy CA List[1] to List[2]*/ } } /*POPCORN RULE - If a new cell hasn't been created in X secs, end flow*/ if(lastActiveCounter!=ActiveCounter[1]) { /*If there's a new cell*/ LastInundationTime = time(NULL); /*Reset Last inundation time*/ lastActiveCounter=ActiveCounter[1]; /*Reset lastActiveCounter*/ } /*If there are no new cells, check that X secs have not gone by.*/ else { /*If max time to wait for a new cell HAS been reached, end the flow*/ if(((unsigned) (time(NULL)-LastInundationTime))>=maxLastInundationTime) { printf("\n Ending Flow because last cell to be inundated was "); printf(">%u secs ago.", (unsigned) (time(NULL)-LastInundationTime)); lastmotionCounter=maxLastMotionCount; } } } /*End of Remaining Detectable Flow Check*/ } /*End while main flow loop: (while(volumeRemaining>0)and Flow Motion)*/ /*POST FLOW WRAP UP**********************************************************/ printf("\n\n Single Flow Complete!\n"); /*Print out final number of inundated cells*/ printf("Final Count: %d cells inundated.\n\n", ActiveCounter[1]); /*POST FLOW WRAP UP: CONSERVATION OF MASS CHECK******************************/ /*ALL DRIVER MODULES MUST HAVE THIS. In order to do unit testing during code compilation, makefile searches for the string "SUCCESS: MASS CONSERVED" to conclude that the code is Verified (though not validated).*/ volumeErupted = 0; /*For each Active Flow Cell, add cell lava volume to volumeErupted*/ for(i=1;i<=ActiveCounter[1];i++) volumeErupted += (CAList[1][i].thickness + dataGrid[CAList[1][i].row][CAList[1][i].col].residual) * DEMmetadata[1] * DEMmetadata[5]; /*print out volume delivered to vents and total volume now in cells*/ printf("Conservation of mass check\n"); printf(" Total (IN) volume pulsed from vents: %0.3f\n",volumeToErupt); printf(" Total (OUT) volume found in cells: %0.3f\n",volumeErupted); /*Double data types are precise to 1e-8, so make sure that volume IN and volume OUT are within this precision.*/ if(abs(volumeErupted-volumeToErupt)<=1e-8) printf(" SUCCESS: MASS CONSERVED\n"); /*If volumes are significantly different (are more than Double Precision diff. then mass is NOT conserved!!*/ else /*Print the mass excess*/ printf(" ERROR: MASS NOT CONSERVED! Excess: %0.2e m^3", volumeErupted-volumeToErupt); /*MODULE: OUTPUT*************************************************************/ /* Writes out model output to a file path. File Output types available, and their codes: 0: X,Y,Thickness ascii flow list 1: Hit Raster (1 = Hit, 0 = Not Hit) 2: Thickness Raster 3: Elevation Raster 4: Elevation + Lava Raster (code 2 + code 3) Filename Index output from INITIALIZE: Filenames[3] - Output file: ASCII X,Y,Thickness Filenames[4] - Output file: Hit Map Filenames[5] - Output file: Raster Thickness Filenames[6] - Output file: Raster Elevation Filenames[7] - Output file: Raster Elevation + Flow Thickness */ /*Check Filenames Array to see if a filename was given (so model output is requested).*/ for(i=0;i<4;i++){ /*Check to see if the File Path is not empty (the following test will !=0)*/ if(strlen(Filenames[i+3]) > 1) { /*If there's a file path given, write model output to it.*/ ret = OUTPUT(dataGrid, /*DataCell Global Data Grid */ CAList[1], /*Automaton Active Cells List */ ActiveCounter[1], /*unsigned Number of active cells */ Filenames[i+3], /*string Output File Path */ i, /*OUTPUT Code, see above */ DEMmetadata,"" /*string Original Raster Projection */ ); /*Check for Error flag (OUTPUT returns <0 value)*/ if(ret<0){ printf("\nERROR [MAIN]: Error flag returned from [OUTPUT].\n"); printf("Exiting.\n"); return(-1); } } } /*Calculate simulation time elapsed, and print it.*/ endTime = time(NULL); printf("\nElapsed Time of simulation approximately %u seconds.\n\n", (unsigned)(endTime - startTime)); return(0); }
//Obtine mutarea urmatoare, pornind de la tabla primita ca parametru; char* Book::getNextMove (ChessBoard tabla, COLOR culoare) { int i,j,poz; // DEMONSTRATION INITIALIZE(); // Initialize (one time call) if (ERROR) { fprintf(debug_file,"Missing obliged file(s) RANDOM1.BIN and/or RANDOM2.BIN"); exit(1); } //Construim EPD; char EPDTemp[200]; memset(EPDTemp,' ',64); memset(EPD,0,200); BITBOARD temp_board[2][6]; for(i=0;i<=1;i++) for(j=0;j<6;j++) temp_board[i][j]=tabla.board[i][j]; //punem piesele; for(i=0;i<=1;i++) for(j=0;j<6;j++) for(poz=0;poz<64;poz++) { int L=poz/8; int C=poz%8; if(temp_board[i][j]%2==1){ //daca e impar => bitul e 1; if(i==BLACK) //piese albe switch(j){ case PAWN: EPDTemp[(7-L)*8+C]='p'; break; case KNIGHT: EPDTemp[(7-L)*8+C]='n'; break; case KING: EPDTemp[(7-L)*8+C]='k'; break; case BISHOP: EPDTemp[(7-L)*8+C]='b'; break; case ROOK: EPDTemp[(7-L)*8+C]='r'; break; case QUEEN: EPDTemp[(7-L)*8+C]='q'; break; } else switch(j){ case PAWN: EPDTemp[(7-L)*8+C]='P'; break; case KNIGHT: EPDTemp[(7-L)*8+C]='N'; break; case KING: EPDTemp[(7-L)*8+C]='K'; break; case BISHOP: EPDTemp[(7-L)*8+C]='B'; break; case ROOK: EPDTemp[(7-L)*8+C]='R'; break; case QUEEN: EPDTemp[(7-L)*8+C]='Q'; break; } } temp_board[i][j]>>=1; } //Scurtam textul int abs=0; char k; for(i=0;i<8;i++) { k=0; for(j=0;j<8;j++) { if(EPDTemp[8*i+j]==' ') k++; else { if(k>0) EPD[abs++]=k+'0'; EPD[abs++]=EPDTemp[8*i+j]; k=0; } } if(k>0) EPD[abs++]=k+'0'; if(i!=7) EPD[abs++]='/'; } EPD[abs++]=' '; if(culoare==WHITE) EPD[abs++]='w'; else EPD[abs++]='b'; strcat(EPD," KQkq -"); EPD[strlen(EPD)]=0; fprintf(debug_file,"%s\n",EPD); //EPD[14]='1'; //Obtinem mutarea in FROM si TO FIND_OPENING(); if (ERROR) fprintf(debug_file,"Something went wrong, error-code %d",ERROR); else fprintf(debug_file,"Move: %s-%s\nList:",FROM,TO); //Toate posibilitatile: for (i=0; i<AZ; i++) fprintf(debug_file,"%c%c-%c%c ",FROM1[i],FROM2[i],TO1[i],TO2[i]); fprintf(debug_file,"\n\n"); //Nu exista deschidere; if(FROM[0]==0) return 0; //Obtinem tipul de piesa PIECE piesa; fprintf(debug_file,"Poz:%d-%d\n",(FROM[1]-'1')*8,FROM[0]-'A'); switch(EPDTemp[(FROM[1]-'1')*8+FROM[0]-'A']) { case 'p': piesa=PAWN; break; case 'r': piesa=ROOK; break; case 'b': piesa=BISHOP; break; case 'k': piesa=KING; break; case 'n': piesa=KNIGHT; break; case 'q': piesa=QUEEN; break; case 'P': piesa=PAWN; break; case 'R': piesa=ROOK; break; case 'B': piesa=BISHOP; break; case 'K': piesa=KING; break; case 'N': piesa=KNIGHT; break; case 'Q': piesa=QUEEN; break; } //fprintf(debug_file,"-- %lld --\n",(tabla.board[culoare][piesa] & ((U64)1<<((FROM[1]-'1')*8+FROM[0]-'A')))); fprintf(debug_file,"Piesa:%d\n",piesa); if((tabla.board[culoare][piesa] & ((U64)1<<((FROM[1]-'1')*8+FROM[0]-'A'))) == (U64) 0) return 0; //Analizam rocadele if(!strcmp(FROM,"E8") && !strcmp(TO,"G8")) { fprintf(debug_file,"SAN: O-O"); return strdup("O-O"); } if(!strcmp(FROM,"E8") && !strcmp(TO,"A8")) { fprintf(debug_file,"SAN: O-O-O"); return strdup("O-O-O"); } if(!strcmp(FROM,"E1") && !strcmp(TO,"G1")) { fprintf(debug_file,"SAN: O-O"); return strdup("O-O"); } if(!strcmp(FROM,"E1") && !strcmp(TO,"A1")) { fprintf(debug_file,"SAN: O-O-O"); return strdup("O-O-O"); } fprintf(debug_file,"SAN:%s\n",tabla.getSANofMove(culoare,(FROM[1]-'1')*8+FROM[0]-'A',(TO[1]-'1')*8+TO[0]-'A',piesa)); //Intoarcem SAN-ul return tabla.getSANofMove(culoare,(FROM[1]-'1')*8+FROM[0]-'A',(TO[1]-'1')*8+TO[0]-'A',piesa); }
GeneralConfiguration::GeneralConfiguration(bool save_on_destroy) /* This version of the general configuration uses a fast, in-memory system for storing and retrieving the data. It loads the values from file only when needed. Once the values have been loaded in memory, they remain there, and the next times the values are queried, they are taken from memory, instead of loading them from disk again. This speeds the system up greatly. It has "getters" and "setters" to facilitate this system. On object destruction, it saves the values if they were modified. */ { // Save parameters. my_save_on_destroy = save_on_destroy; // Function definition for initializing variables. #define INITIALIZE(parameter) parameter##_loaded = false // Initialize variables. INITIALIZE(screen_width); INITIALIZE(screen_height); INITIALIZE(window_width); INITIALIZE(window_height); INITIALIZE(window_x_position); INITIALIZE(window_y_position); INITIALIZE(window_maximized); INITIALIZE(window_widths); INITIALIZE(window_heights); INITIALIZE(window_x_positions); INITIALIZE(window_y_positions); INITIALIZE(window_ids); INITIALIZE(window_titles); INITIALIZE(window_shows); INITIALIZE(project); INITIALIZE(book); INITIALIZE(chapter); INITIALIZE(verse); INITIALIZE(stylesheet); INITIALIZE(references_file); INITIALIZE(export_to_bibleworks_filename); INITIALIZE(export_to_sword_module_path); INITIALIZE(export_to_sword_install_path); INITIALIZE(paper_format); INITIALIZE(paper_width); INITIALIZE(paper_height); INITIALIZE(paper_inside_margin); INITIALIZE(paper_outside_margin); INITIALIZE(paper_top_margin); INITIALIZE(paper_bottom_margin); INITIALIZE(column_spacing); INITIALIZE(printdate); INITIALIZE(printdraft); INITIALIZE(header_font_size); INITIALIZE(print_engine_use_intermediate_text); INITIALIZE(print_changes_only); INITIALIZE(project_to_compare_with); INITIALIZE(notes_selection_reference); INITIALIZE(notes_selection_edited); INITIALIZE(notes_selection_date_from); INITIALIZE(notes_selection_date_to); INITIALIZE(notes_selection_category); INITIALIZE(notes_selection_current_project); INITIALIZE(notes_display_project); INITIALIZE(notes_display_category); INITIALIZE(notes_display_date_created); INITIALIZE(notes_display_created_by); INITIALIZE(notes_display_summary); INITIALIZE(notes_display_reference_text); INITIALIZE(check_markers_compare_project); INITIALIZE(check_markers_compare_all_markers); INITIALIZE(check_markers_compare_include_only); INITIALIZE(check_markers_compare_ignore); INITIALIZE(check_markers_compare_ignore_verse_zero); INITIALIZE(check_capitalization_punctuation); INITIALIZE(check_capitalization_ignore); INITIALIZE(check_capitalization_allow_any_prefixes); INITIALIZE(check_repetition_ignore_case); INITIALIZE(check_repetition_show_only_these); INITIALIZE(check_repetition_ignore_these); INITIALIZE(check_matching_pairs_ignore); INITIALIZE(check_words_inventory_not_include_words_count); INITIALIZE(check_words_inventory_word_forming_characters); INITIALIZE(check_markers_spacing_include); INITIALIZE(styles_category_expanded); INITIALIZE(insert_footnote_template); INITIALIZE(insert_endnote_template); INITIALIZE(insert_xref_template); INITIALIZE(parallel_bible_keep_verses_together); INITIALIZE(parallel_bible_chapters_verses); INITIALIZE(parallel_bible_include_verse_zero); INITIALIZE(printing_fonts); INITIALIZE(parallel_bible_projects); INITIALIZE(parallel_bible_enabled); INITIALIZE(use_outpost); INITIALIZE(mychecks); INITIALIZE(tidy_translate); INITIALIZE(tidy_books); INITIALIZE(tidy_texts); INITIALIZE(tidy_normalize_hyphens); INITIALIZE(tidy_space_between_chapter_verse); INITIALIZE(tidy_space_series_verses); INITIALIZE(tidy_full_stop_ends_text); INITIALIZE(tidy_ampersand_semicolon); INITIALIZE(tidy_space_before_punctuation); INITIALIZE(wordlist_process_general); INITIALIZE(wordlist_general_asterisk); INITIALIZE(wordlist_general_asterisk_first); INITIALIZE(wordlist_process_hebrew); INITIALIZE(wordlist_hebrew_asterisk); INITIALIZE(wordlist_hebrew_asterisk_first); INITIALIZE(wordlist_process_greek); INITIALIZE(wordlist_greek_asterisk); INITIALIZE(wordlist_greek_asterisk_first); INITIALIZE(wordlist_process_index); INITIALIZE(wordlist_index_asterisk); INITIALIZE(wordlist_index_asterisk_first); INITIALIZE(text_editor_font_default); INITIALIZE(text_editor_font_name); INITIALIZE(text_editor_default_color); INITIALIZE(text_editor_normal_text_color); INITIALIZE(text_editor_background_color); INITIALIZE(text_editor_selected_text_color); INITIALIZE(text_editor_selection_color); INITIALIZE(encoding); INITIALIZE(features_mode); INITIALIZE(features_list); INITIALIZE(remember_verse_per_chapter); INITIALIZE(start_program_maximized); INITIALIZE(administration_password); INITIALIZE(print_references_projects); INITIALIZE(dialogpositions_x); INITIALIZE(dialogpositions_y); INITIALIZE(text_replacement); INITIALIZE(text_replacement_originals); INITIALIZE(text_replacement_replacements); INITIALIZE(pdf_viewer_automatic); INITIALIZE(pdf_viewer_path); INITIALIZE(pdf_viewer_arguments); INITIALIZE(project_tasks_names); INITIALIZE(project_tasks_durations); INITIALIZE(print_job); INITIALIZE(projects_displaying_verses); INITIALIZE(compare_disregard_notes); INITIALIZE(source_language_names); INITIALIZE(reference_window_show_verse_text); INITIALIZE(reference_window_show_relevant_bits); INITIALIZE(consultation_notes_git_use_remote_repository); INITIALIZE(consultation_notes_git_remote_repository_url); INITIALIZE(bibledit_web_url); INITIALIZE(bibledit_web_user); }
int main(int argc, char *argv[]) { int i; int c; int vflag; char *cutarg; long cutloyear = ZDUMP_LO_YEAR; long cuthiyear = ZDUMP_HI_YEAR; time_t cutlotime; time_t cuthitime; char **fakeenv; time_t now; time_t t; time_t newt; struct tm tm; struct tm newtm; struct tm *tmp; struct tm *newtmp; INITIALIZE(cutlotime); INITIALIZE(cuthitime); vflag = 0; cutarg = NULL; while ((c = getopt(argc, argv, "c:v")) == 'c' || c == 'v') if (c == 'v') vflag = 1; else cutarg = optarg; if ((c != EOF && c != -1) || (optind == argc - 1 && strcmp(argv[optind], "=") == 0)) { usage(); } if (vflag) { if (cutarg != NULL) { long lo; long hi; char dummy; if (sscanf(cutarg, "%ld%c", &hi, &dummy) == 1) { cuthiyear = hi; } else if (sscanf(cutarg, "%ld,%ld%c", &lo, &hi, &dummy) == 2) { cutloyear = lo; cuthiyear = hi; } else { errx(EXIT_FAILURE, _("wild -c argument %s\n"), cutarg); } } setabsolutes(); cutlotime = yeartot(cutloyear); cuthitime = yeartot(cuthiyear); } time(&now); longest = 0; for (i = optind; i < argc; ++i) if (strlen(argv[i]) > longest) longest = strlen(argv[i]); { int from; int to; for (i = 0; environ[i] != NULL; ++i) continue; fakeenv = (char **) malloc((size_t) ((i + 2) * sizeof *fakeenv)); if (fakeenv == NULL || (fakeenv[0] = (char *) malloc((size_t) (longest + 4))) == NULL) errx(EXIT_FAILURE, _("malloc() failed")); to = 0; strcpy(fakeenv[to++], "TZ="); for (from = 0; environ[from] != NULL; ++from) if (strncmp(environ[from], "TZ=", 3) != 0) fakeenv[to++] = environ[from]; fakeenv[to] = NULL; environ = fakeenv; } for (i = optind; i < argc; ++i) { static char buf[MAX_STRING_LENGTH]; strcpy(&fakeenv[0][3], argv[i]); if (!vflag) { show(argv[i], now, FALSE); continue; } warned = FALSE; t = absolute_min_time; show(argv[i], t, TRUE); t += SECSPERHOUR * HOURSPERDAY; show(argv[i], t, TRUE); if (t < cutlotime) t = cutlotime; tmp = my_localtime(&t); if (tmp != NULL) { tm = *tmp; strncpy(buf, abbr(&tm), (sizeof buf) - 1); } for ( ; ; ) { if (t >= cuthitime || t >= cuthitime - SECSPERHOUR * 12) break; newt = t + SECSPERHOUR * 12; newtmp = localtime(&newt); if (newtmp != NULL) newtm = *newtmp; if ((tmp == NULL || newtmp == NULL) ? (tmp != newtmp) : (delta(&newtm, &tm) != (newt - t) || newtm.tm_isdst != tm.tm_isdst || strcmp(abbr(&newtm), buf) != 0)) { newt = hunt(argv[i], t, newt); newtmp = localtime(&newt); if (newtmp != NULL) { newtm = *newtmp; strncpy(buf, abbr(&newtm), (sizeof buf) - 1); } } t = newt; tm = newtm; tmp = newtmp; } t = absolute_max_time; t -= SECSPERHOUR * HOURSPERDAY; show(argv[i], t, TRUE); t += SECSPERHOUR * HOURSPERDAY; show(argv[i], t, TRUE); } if (fflush(stdout) || ferror(stdout)) errx(EXIT_FAILURE, _("error writing standard output")); exit(EXIT_SUCCESS); /* If exit fails to exit... */ return EXIT_FAILURE; }
static int tzparse(const char *name, struct state * const sp, const int lastditch) { const char * stdname; const char * dstname; size_t stdlen; size_t dstlen; long stdoffset; long dstoffset; time_t * atp; unsigned char * typep; char * cp; int load_result; static struct ttinfo zttinfo; INITIALIZE(dstname); stdname = name; if (lastditch) { stdlen = strlen(name); /* length of standard zone name */ name += stdlen; if (stdlen >= sizeof sp->chars) stdlen = (sizeof sp->chars) - 1; stdoffset = 0; } else { if (*name == '<') { name++; stdname = name; name = getqzname(name, '>'); if (*name != '>') return (-1); stdlen = name - stdname; name++; } else { name = getzname(name); stdlen = name - stdname; } if (*name == '\0') return -1; name = getoffset(name, &stdoffset); if (name == NULL) return -1; } load_result = tzload(TZDEFRULES, sp, FALSE); if (load_result != 0) sp->leapcnt = 0; /* so, we're off a little */ if (*name != '\0') { if (*name == '<') { dstname = ++name; name = getqzname(name, '>'); if (*name != '>') return -1; dstlen = name - dstname; name++; } else { dstname = name; name = getzname(name); dstlen = name - dstname; /* length of DST zone name */ } if (*name != '\0' && *name != ',' && *name != ';') { name = getoffset(name, &dstoffset); if (name == NULL) return -1; } else dstoffset = stdoffset - SECSPERHOUR; if (*name == '\0' && load_result != 0) name = TZDEFRULESTRING; if (*name == ',' || *name == ';') { struct rule start; struct rule end; int year; time_t janfirst; time_t starttime; time_t endtime; ++name; if ((name = getrule(name, &start)) == NULL) return -1; if (*name++ != ',') return -1; if ((name = getrule(name, &end)) == NULL) return -1; if (*name != '\0') return -1; sp->typecnt = 2; /* standard time and DST */ /* ** Two transitions per year, from EPOCH_YEAR forward. */ sp->ttis[0] = sp->ttis[1] = zttinfo; sp->ttis[0].tt_gmtoff = -dstoffset; sp->ttis[0].tt_isdst = 1; sp->ttis[0].tt_abbrind = stdlen + 1; sp->ttis[1].tt_gmtoff = -stdoffset; sp->ttis[1].tt_isdst = 0; sp->ttis[1].tt_abbrind = 0; atp = sp->ats; typep = sp->types; janfirst = 0; sp->timecnt = 0; for (year = EPOCH_YEAR; sp->timecnt + 2 <= TZ_MAX_TIMES; ++year) { time_t newfirst; starttime = transtime(janfirst, year, &start, stdoffset); endtime = transtime(janfirst, year, &end, dstoffset); if (starttime > endtime) { *atp++ = endtime; *typep++ = 1; /* DST ends */ *atp++ = starttime; *typep++ = 0; /* DST begins */ } else { *atp++ = starttime; *typep++ = 0; /* DST begins */ *atp++ = endtime; *typep++ = 1; /* DST ends */ } sp->timecnt += 2; newfirst = janfirst; newfirst += year_lengths[isleap(year)] * SECSPERDAY; if (newfirst <= janfirst) break; janfirst = newfirst; } } else { long theirstdoffset; long theirdstoffset; long theiroffset; int isdst; int i; int j; if (*name != '\0') return -1; /* ** Initial values of theirstdoffset and theirdstoffset. */ theirstdoffset = 0; for (i = 0; i < sp->timecnt; ++i) { j = sp->types[i]; if (!sp->ttis[j].tt_isdst) { theirstdoffset = -sp->ttis[j].tt_gmtoff; break; } } theirdstoffset = 0; for (i = 0; i < sp->timecnt; ++i) { j = sp->types[i]; if (sp->ttis[j].tt_isdst) { theirdstoffset = -sp->ttis[j].tt_gmtoff; break; } } /* ** Initially we're assumed to be in standard time. */ isdst = FALSE; theiroffset = theirstdoffset; /* ** Now juggle transition times and types ** tracking offsets as you do. */ for (i = 0; i < sp->timecnt; ++i) { j = sp->types[i]; sp->types[i] = sp->ttis[j].tt_isdst; if (sp->ttis[j].tt_ttisgmt) { /* No adjustment to transition time */ } else { /* ** If summer time is in effect, and the ** transition time was not specified as ** standard time, add the summer time ** offset to the transition time; ** otherwise, add the standard time ** offset to the transition time. */ /* ** Transitions from DST to DDST ** will effectively disappear since ** POSIX provides for only one DST ** offset. */ if (isdst && !sp->ttis[j].tt_ttisstd) { sp->ats[i] += dstoffset - theirdstoffset; } else { sp->ats[i] += stdoffset - theirstdoffset; } } theiroffset = -sp->ttis[j].tt_gmtoff; if (sp->ttis[j].tt_isdst) theirdstoffset = theiroffset; else theirstdoffset = theiroffset; } /* ** Finally, fill in ttis. */ sp->ttis[0] = sp->ttis[1] = zttinfo; sp->ttis[0].tt_gmtoff = -stdoffset; sp->ttis[0].tt_isdst = FALSE; sp->ttis[0].tt_abbrind = 0; sp->ttis[1].tt_gmtoff = -dstoffset; sp->ttis[1].tt_isdst = TRUE; sp->ttis[1].tt_abbrind = stdlen + 1; sp->typecnt = 2; } } else { dstlen = 0; sp->typecnt = 1; /* only standard time */ sp->timecnt = 0; sp->ttis[0] = zttinfo; sp->ttis[0].tt_gmtoff = -stdoffset; sp->ttis[0].tt_isdst = 0; sp->ttis[0].tt_abbrind = 0; } sp->charcnt = stdlen + 1; if (dstlen != 0) sp->charcnt += dstlen + 1; if ((size_t) sp->charcnt > sizeof sp->chars) return -1; cp = sp->chars; strncpy(cp, stdname, stdlen); cp += stdlen; *cp++ = '\0'; if (dstlen != 0) { strncpy(cp, dstname, dstlen); *(cp + dstlen) = '\0'; } return 0; }
ProjectConfiguration::ProjectConfiguration(ustring project_in, bool save_on_destroy) { // If no project given, take one currently opened. if (project.empty()) { extern Settings *settings; project = settings->genconfig.project_get(); } // Save parameters. project = project_in; my_save_on_destroy = save_on_destroy; // Function definition for initializing variables. #define INITIALIZE(parameter) parameter##_loaded = false // Initialize variables. INITIALIZE(versification); INITIALIZE(printing_fonts); INITIALIZE(text_line_height); INITIALIZE(xetex_font_mapping_file); INITIALIZE(xetex_shaping_engine); INITIALIZE(sword_name); INITIALIZE(sword_description); INITIALIZE(sword_about); INITIALIZE(sword_license); INITIALIZE(sword_version); INITIALIZE(sword_language); INITIALIZE(reordered_books); INITIALIZE(reordered_includes); INITIALIZE(reordered_portions); INITIALIZE(language); INITIALIZE(book_order); INITIALIZE(editable); INITIALIZE(backup_incremental_last_time); INITIALIZE(backup_comment); INITIALIZE(git_use_remote_repository); INITIALIZE(git_remote_repository_url); INITIALIZE(changes_last_review); INITIALIZE(changes_since); INITIALIZE(changes_till); INITIALIZE(editor_font_default); INITIALIZE(editor_font_name); INITIALIZE(editor_default_color); INITIALIZE(editor_normal_text_color); INITIALIZE(editor_background_color); INITIALIZE(editor_selected_text_color); INITIALIZE(editor_selection_color); INITIALIZE(right_to_left); INITIALIZE(planning_project_start); INITIALIZE(planning_tasks); INITIALIZE(depending_on_switch); INITIALIZE(depending_on_project); INITIALIZE(depending_on_script); INITIALIZE(spelling_check); INITIALIZE(spelling_dictionaries); }
static time_t transtime(const time_t janfirst, const int year, register const struct rule *const rulep, const long offset) { register int leapyear; register time_t value; register int i; int d, m1, yy0, yy1, yy2, dow; INITIALIZE(value); leapyear = isleap(year); switch (rulep->r_type) { case JULIAN_DAY: /* ** Jn - Julian day, 1 == January 1, 60 == March 1 even in leap ** years. ** In non-leap years, or if the day number is 59 or less, just ** add SECSPERDAY times the day number-1 to the time of ** January 1, midnight, to get the day. */ value = janfirst + (rulep->r_day - 1) * SECSPERDAY; if (leapyear && rulep->r_day >= 60) value += SECSPERDAY; break; case DAY_OF_YEAR: /* ** n - day of year. ** Just add SECSPERDAY times the day number to the time of ** January 1, midnight, to get the day. */ value = janfirst + rulep->r_day * SECSPERDAY; break; case MONTH_NTH_DAY_OF_WEEK: /* ** Mm.n.d - nth "dth day" of month m. */ value = janfirst; for (i = 0; i < rulep->r_mon - 1; ++i) value += mon_lengths[leapyear][i] * SECSPERDAY; /* ** Use Zeller's Congruence to get day-of-week of first day of ** month. */ m1 = (rulep->r_mon + 9) % 12 + 1; yy0 = (rulep->r_mon <= 2) ? (year - 1) : year; yy1 = yy0 / 100; yy2 = yy0 % 100; dow = ((26 * m1 - 2) / 10 + 1 + yy2 + yy2 / 4 + yy1 / 4 - 2 * yy1) % 7; if (dow < 0) dow += DAYSPERWEEK; /* ** "dow" is the day-of-week of the first day of the month. Get ** the day-of-month (zero-origin) of the first "dow" day of the ** month. */ d = rulep->r_day - dow; if (d < 0) d += DAYSPERWEEK; for (i = 1; i < rulep->r_week; ++i) { if (d + DAYSPERWEEK >= mon_lengths[leapyear][rulep->r_mon - 1]) break; d += DAYSPERWEEK; } /* ** "d" is the day-of-month (zero-origin) of the day we want. */ value += d * SECSPERDAY; break; } /* ** "value" is the Epoch-relative time of 00:00:00 UTC on the day in ** question. To get the Epoch-relative time of the specified local ** time on that day, add the transition time and the current offset ** from UTC. */ return value + rulep->r_time + offset; }
int main(int argc, char *argv[]) { /*VARIABLES******************************************************************/ /*Files*/ char *configFilename = argv[1]; /*configuration file path */ char **Filenames; /*A list of file paths for model output */ point *DEMvals; point *RDRvals; point *shftRDRvals; point *cropDEMvals; point origin; point translate; point rotate; double scale; point dist; double hypotenuse; double curangle; point *RDRinterp; point RDRUL; point RDRLR; point DEMUL; point DEMLR; point expandedDEMUL; point expandedDEMLR; unsigned RDRinboundsct=0; unsigned DEMinboundsct=0; double NNdist[4]; double NNelev[4]; double NNwt[4]; double curdistance; double DEMnoDATA; double RDRnoDATA; unsigned demmax; unsigned rdrmax; double *DEMmetadata; double *RDRmetadata; FILE *DEMfile; FILE *RDRfile; int ret, i, j; /*TIME **********************************************************************/ startTime = time(NULL); /*Define Start Time*/ /*WELCOME USER AND CHECK FOR CORRECT USAGE***********************************/ printf("\n\n This will shift ur data.\n\n"); /*User must supply the name of the executable and a configuration file*/ if(argc<2) { printf("Usage: %s config-filename\n",argv[0]); return(-1); } printf("Reading Configuration File...\n"); /*MODULE: INITIALIZE*********************************************************/ /* Assigns several empty variables based on a user-defined configuration file. */ /* File Name List output in this order: [0] - DEM [1] - Residual Flow Thickness [2] - Elevation Uncertainty [3] - Output file: ASCII X,Y,Thickness [4] - Output file: Hit Map [5] - Output file: Raster Thickness [6] - Output file: Raster Elevation [7] - Output file: Raster Elevation + Flow Thickness */ ret = INITIALIZE(configFilename, /*chr Configuration File Name */ &Filenames, /*chr File Name List */ &origin.easting, /*point origin location */ &origin.northing, /*point origin location */ &origin.elevation, /*point origin location */ &translate.easting, /*point origin location */ &translate.northing, /*point origin location */ &translate.elevation, /*point origin location */ &rotate.easting, /*point origin location */ &rotate.northing, /*point origin location */ &rotate.elevation, /*point origin location */ &scale, /*double scale */ &DEMnoDATA, /*DEM raster No Data */ &RDRnoDATA /*RDR raster No Data */ ); /*Check for Error flag (INITIALIZE returns <0 value)*/ if(ret<0){ printf("\nERROR [MAIN]: Error flag returned from [INITIALIZE].\n"); printf("Exiting.\n"); return(-1); } printf("Loading Digital Elevation Model..."); /*MODULE: DEM_LOADER*********************************************************/ /* Loads Raster into a list and reports range values*/ /*Load topography from "Expected" DEM*/ DEMmetadata = DEM_LOADER(Filenames[0], /*char DEM file name */ &DEMvals /*point DEM x,y,z list*/ ); /*Check for Error flag (DEM_LOADER returns a null metadata list)*/ if(DEMmetadata==NULL){ printf("\nError [MAIN]: Error flag returned from DEM_LOADER [DEM].\n"); printf("Exiting.\n"); return(-1); } demmax = DEMmetadata[2]*DEMmetadata[4]; /*DEMGeoTransform[0] lower left x DEMGeoTransform[1] w-e pixel resolution DEMGeoTransform[2] number of cols, assigned manually in this module DEMGeoTransform[3] lower left y DEMGeoTransform[4] number of lines, assigned manually in this module DEMGeoTransform[5] n-s pixel resolution (negative value) */ DEMUL.easting = DEMmetadata[0]; DEMUL.northing =DEMmetadata[3] + (DEMmetadata[4]*DEMmetadata[5]); DEMLR.easting = DEMmetadata[0] + (DEMmetadata[2]*DEMmetadata[1]); DEMLR.northing = DEMmetadata[3]; expandedDEMUL.easting = DEMUL.easting - (2*DEMmetadata[1]); expandedDEMUL.northing = DEMUL.northing + (2*DEMmetadata[5]); expandedDEMLR.easting = DEMLR.easting + (2*DEMmetadata[1]); expandedDEMLR.northing = DEMLR.northing - (2*DEMmetadata[5]); printf("Loading Radar Elevation Model..."); /*Load topography from "observed" Radar DEM*/ RDRmetadata = DEM_LOADER(Filenames[1], /*char RDR file name */ &RDRvals /*point RDR x,y,z list*/ ); /*Check for Error flag (DEM_LOADER returns a null metadata list)*/ if(RDRmetadata==NULL){ printf("\nError [MAIN]: Error flag returned from DEM_LOADER [RDR].\n"); printf("Exiting.\n"); return(-1); } rdrmax = RDRmetadata[2]*RDRmetadata[4]; RDRUL.easting = RDRmetadata[0]; RDRUL.northing =RDRmetadata[3] + (RDRmetadata[4]*RDRmetadata[5]); RDRLR.easting = RDRmetadata[0] + (RDRmetadata[2]*RDRmetadata[1]); RDRLR.northing = RDRmetadata[3]; /*Print range of DEM and RADAR coordinates, pre-shift.*/ printf("DEM (Lab) Range is: %0.3f\n", DEMUL.northing); printf(" %0.3f %0.3f\n", DEMUL.easting, DEMLR.easting); printf(" %0.3f\n\n", DEMLR.northing); printf("Radar (Body) Range is: %0.3f\n", RDRUL.northing); printf(" %0.3f %0.3f\n", RDRUL.easting, RDRLR.easting); printf(" %0.3f\n\n", RDRLR.northing); /*****DOF-SHIFT******/ printf("\n\nAPPLYING ROTATIONS AND TRANSFORMATIONS TO THE LAB DATA SET\n\n"); printf("Origin Location:\n"); printf(" easting: %0.3f\n" , rotate.easting); printf(" northing: %0.3f\n" , rotate.northing); printf(" elevation: %0.3f\n" , rotate.elevation); /*Change Rotation from degrees to radians*/ printf("\nRotating (CCW)...\n"); printf(" about the Z-axis, %0.3f° " , rotate.elevation); rotate.elevation *= M_PI / 180.0; printf("(%0.3f radians)\n", rotate.elevation); printf(" about the NS-axis, %0.3f° " , rotate.northing); rotate.northing *= M_PI / 180.0; printf("(%0.3f radians)\n", rotate.northing); printf(" about the EW-axis, %0.3f° " , rotate.easting); rotate.easting *= M_PI / 180.0; printf("(%0.3f radians)\n", rotate.easting); printf("\nTranslating...\n"); printf(" %0.3f m to the East\n",translate.easting); printf(" %0.3f m to the North\n",translate.northing); printf(" %0.3f m Up\n",translate.elevation); printf("\nScaling...\n"); printf(" %0.3f%% of original size\n\n",(scale*100.0)); for(i=0;i<rdrmax;i++){ if (RDRvals[i].elevation != RDRnoDATA) { /*only shift if this location has a value*/ /*Remove origin from locations*/ RDRvals[i].easting -= origin.easting; RDRvals[i].northing -= origin.northing; RDRvals[i].elevation -= origin.elevation; if(i==0) { printf("pre-rot: %0.3fE\t%0.3fN\t%0.3fElev\n",RDRvals[i].easting,RDRvals[i].northing,RDRvals[i].elevation); } /*ROTATE RDR locations**********************/ /*ABOUT Z AXIS*/ hypotenuse = pow((pow(RDRvals[i].easting,2.0) + pow(RDRvals[i].northing,2.0)),0.5); if(RDRvals[i].easting == 0.0) { curangle = M_PI/2.0; if(RDRvals[i].northing < 0.0) curangle *= -1.0; } else { curangle = atan(RDRvals[i].northing / RDRvals[i].easting); if(RDRvals[i].easting < 0.0) curangle += M_PI; } /*apply rotation*/ RDRvals[i].easting = cos(rotate.elevation + curangle) * hypotenuse; RDRvals[i].northing = sin(rotate.elevation + curangle) * hypotenuse; if(i==0) { printf("postrotZ: %0.3fE\t%0.3fN\t%0.3fElev\n",RDRvals[i].easting,RDRvals[i].northing,RDRvals[i].elevation); } /*ABOUT Y AXIS*/ hypotenuse = pow((pow(RDRvals[i].easting,2.0) + pow(RDRvals[i].elevation,2.0)),0.5); if(RDRvals[i].elevation == 0.0) { curangle = M_PI/2.0; if(RDRvals[i].easting < 0.0) curangle *= -1.0; } else { curangle = atan(RDRvals[i].easting / RDRvals[i].elevation); if(RDRvals[i].elevation < 0.0) curangle += M_PI; } /*apply rotation*/ RDRvals[i].elevation = cos(rotate.northing + curangle) * hypotenuse; RDRvals[i].easting = sin(rotate.northing + curangle) * hypotenuse; if(i==0) { printf("postrotY: %0.3fE\t%0.3fN\t%0.3fElev\n",RDRvals[i].easting,RDRvals[i].northing,RDRvals[i].elevation); } /*ABOUT X AXIS*/ hypotenuse = pow((pow(RDRvals[i].elevation,2.0) + pow(RDRvals[i].northing,2.0)),0.5); if(RDRvals[i].northing == 0.0) { curangle = M_PI/2.0; if(RDRvals[i].elevation < 0.0) curangle *= -1.0; } else { curangle = atan(RDRvals[i].elevation / RDRvals[i].northing); if(RDRvals[i].northing < 0.0) curangle += M_PI; } /*apply rotation*/ RDRvals[i].northing = cos(rotate.easting + curangle) * hypotenuse; RDRvals[i].elevation = sin(rotate.easting + curangle) * hypotenuse; if(i==0) { printf("postrotX: %0.3fE\t%0.3fN\t%0.3fElev\n",RDRvals[i].easting,RDRvals[i].northing,RDRvals[i].elevation); } /*find distance from origin (0,0)*/ dist.easting = RDRvals[i].easting; dist.northing = RDRvals[i].northing; dist.elevation = RDRvals[i].elevation; /*scale RDR locations (scale before translation)*/ dist.easting *= scale - 1.0; /*This is the scale shift*/ dist.northing *= scale - 1.0; dist.elevation *= scale - 1.0; /*Add translation, scale, and readd origin at same time*/ RDRvals[i].easting += translate.easting + dist.easting + origin.easting; RDRvals[i].northing += translate.northing + dist.northing + origin.northing; RDRvals[i].elevation += translate.elevation + dist.elevation + origin.elevation; if(i==0) { printf("post-trn: %0.3fE\t%0.3fN\t%0.3fElev\n",RDRvals[i].easting,RDRvals[i].northing,RDRvals[i].elevation); } } } j=0; for(i=0;i<rdrmax;i++) { if (RDRvals[i].elevation != RDRnoDATA) { /*only count if this location has a value*/ /*Find New Range*/ if((j++)==0) { RDRUL.easting = RDRvals[i].easting; RDRUL.northing = RDRvals[i].northing; RDRLR.easting = RDRvals[i].easting; RDRLR.northing = RDRvals[i].northing; } else { if (RDRUL.easting > RDRvals[i].easting) RDRUL.easting = RDRvals[i].easting; else if (RDRLR.easting < RDRvals[i].easting) RDRLR.easting = RDRvals[i].easting; if (RDRUL.northing < RDRvals[i].northing) RDRUL.northing = RDRvals[i].northing; else if (RDRLR.northing > RDRvals[i].northing) RDRLR.northing = RDRvals[i].northing; } /*Count number of RADAR points now in or near DEM*/ if ((RDRvals[i].easting >= expandedDEMUL.easting) && (RDRvals[i].easting <= expandedDEMLR.easting)){ if ((RDRvals[i].northing <= expandedDEMUL.northing) && (RDRvals[i].northing >= expandedDEMLR.northing)) { ++RDRinboundsct; /*Increment count of points within the expanded DEM boundaries*/ } } } } /*Print new range of RADAR coordinates, post shift.*/ printf("\nNew Radar Range is: %0.3f\n", RDRUL.northing); printf(" %0.3f %0.3f\n", RDRUL.easting, RDRLR.easting); printf(" %0.3f\n", RDRLR.northing); printf("%u radar locations with data are within 2 pixels of the DEM\n\n", RDRinboundsct); if(RDRinboundsct==0){ printf("NO shifted radar points lie within the DEM region!! unable to fit.\nexiting.\n"); return(-1); } /*CROP ALL THE DATA*************************************************************************/ printf("Cropping the BODY data to the LAB data extent\n"); /*move Radar values to new, potentially smaller list, for speed*/ if((shftRDRvals = malloc (sizeof (point) * (RDRinboundsct)))==NULL) { printf("ERROR [MAIN]: Out of Memory creating Shifted RADAR Values List!\n"); return(-1); } j=0; for(i=0;i<rdrmax;i++){ if((RDRvals[i].easting >= expandedDEMUL.easting) && (RDRvals[i].easting <= expandedDEMLR.easting)){ if((RDRvals[i].northing <= expandedDEMUL.northing) && (RDRvals[i].northing >= expandedDEMLR.northing)) { if (RDRvals[i].elevation != RDRnoDATA) { /*only copy if there's data*/ shftRDRvals[j] = RDRvals[i]; j++; } } } } free(RDRvals); /*free memory of old array*/ printf(" copied %u values to cropped BODY array\n",(j+1)); printf("Cropping the LAB data to the BODY data extent\n"); /*Now find new range of DEM and scrap values outside of the Radar range*/ if(DEMUL.easting < RDRUL.easting) DEMUL.easting = RDRUL.easting; if(DEMLR.easting > RDRLR.easting) DEMLR.easting = RDRLR.easting; if(DEMUL.northing > RDRUL.northing) DEMUL.northing = RDRUL.northing; if(DEMLR.northing < RDRLR.northing) DEMLR.northing = RDRLR.northing; DEMinboundsct=0; for(i=0;i<demmax;i++){ if (DEMvals[i].easting >= DEMUL.easting && DEMvals[i].easting <= DEMLR.easting){ if (DEMvals[i].northing <= DEMUL.northing && DEMvals[i].northing >= DEMLR.northing) { DEMinboundsct++; } } } /*DEMGeoTransform[0] lower left x DEMGeoTransform[1] w-e pixel resolution DEMGeoTransform[2] number of cols, assigned manually in this module DEMGeoTransform[3] lower left y DEMGeoTransform[4] number of lines, assigned manually in this module DEMGeoTransform[5] n-s pixel resolution (negative value) */ /*move DEM values to new, potentially smaller list, for speed*/ if((cropDEMvals = malloc (sizeof (point) * (DEMinboundsct)))==NULL) { printf("ERROR [MAIN]: Out of Memory creating Cropped DEM Values List!\n"); return(-1); } j=0; for(i=0;i<demmax;i++){ if (DEMvals[i].easting >= DEMUL.easting && DEMvals[i].easting <= DEMLR.easting){ if (DEMvals[i].northing <= DEMUL.northing && DEMvals[i].northing >= DEMLR.northing) { cropDEMvals[j] = DEMvals[i]; j++; } } } free(DEMvals); /*free memory of old array*/ printf(" copied %u values to cropped LAB array\n",(j+1)); if((RDRinterp = malloc (sizeof (point) * (DEMinboundsct)))==NULL) { printf("ERROR [MAIN]: Out of Memory creating Interpolated RADAR Array!\n"); return(-1); } /*Interpolate RDR onto SRTM***************************************************/ printf("\n\nInterpolating shifted points at DEM locations\n"); /*initialize NNelevs to avoid make warning.*/ NNelev[0] = NNelev[1] = NNelev[2] = NNelev[3] = 0.0; for(i=0;i<DEMinboundsct;i++){ /*printf("\r%u/%u",i,DEMinboundsct);*/ RDRinterp[i].easting = cropDEMvals[i].easting; RDRinterp[i].northing = cropDEMvals[i].northing; RDRinterp[i].elevation = -9999; /*starting elevation in case no value can be assigned*/ /*if DEM is not NoDATA*/ if (cropDEMvals[i].elevation != DEMnoDATA) { /*use near neighbor to find elevation loop through all, if in a quadrant, check if it's the closest point. after loop, closest 4 points get averaged, weighted by distance. must have all 4 points. All that is needed is to preserve a distance and an elevation for 4 quadrants. double[4] distance, double[4] elev*/ for(j=0;j<=3;j++) { /*reset distance*/ NNdist[j] = DBL_MAX; } for(j=0;j<RDRinboundsct;j++){ if (abs(shftRDRvals[j].easting-RDRinterp[i].easting) < (2.0*DEMmetadata[1])) { if (abs(shftRDRvals[j].northing-RDRinterp[i].northing) < (2.0*DEMmetadata[1])) { curdistance = pow(pow((shftRDRvals[j].easting - RDRinterp[i].easting ),2.0) + pow((shftRDRvals[j].northing - RDRinterp[i].northing),2.0),0.5); /*First quadrant*/ if((shftRDRvals[j].easting >= RDRinterp[i].easting) && (shftRDRvals[j].northing >= RDRinterp[i].northing)) { /*is distance smallest?*/ if (curdistance < NNdist[0]) { NNdist[0] = curdistance; NNelev[0] = shftRDRvals[j].elevation; } } /*Second quadrant*/ else if((shftRDRvals[j].easting < RDRinterp[i].easting) && (shftRDRvals[j].northing >= RDRinterp[i].northing)) { if (curdistance < NNdist[1]) { NNdist[1] = curdistance; NNelev[1] = shftRDRvals[j].elevation; } } /*Third quadrant*/ else if((shftRDRvals[j].easting < RDRinterp[i].easting) && (shftRDRvals[j].northing < RDRinterp[i].northing)) { if (curdistance < NNdist[2]) { NNdist[2] = curdistance; NNelev[2] = shftRDRvals[j].elevation; } } /*Fourth quadrant*/ else { if (curdistance < NNdist[3]) { NNdist[3] = curdistance; NNelev[3] = shftRDRvals[j].elevation; } } }} /*If the point is within 2 pixels of the point*/ } /*For all radar values*/ /*if all distances are assigned*/ if (((NNdist[0]<DBL_MAX)&&(NNdist[1]<DBL_MAX))&& ((NNdist[2]<DBL_MAX)&&(NNdist[3]<DBL_MAX))) { /*interpolate elevation*/ if (NNdist[0]==0) RDRinterp[i].elevation = NNelev[0]; else if (NNdist[1]==0) RDRinterp[i].elevation = NNelev[1]; else if (NNdist[2]==0) RDRinterp[i].elevation = NNelev[2]; else if (NNdist[3]==0) RDRinterp[i].elevation = NNelev[3]; else { NNwt[0] = pow((1.0/NNdist[0]),2.0); NNwt[1] = pow((1.0/NNdist[1]),2.0); NNwt[2] = pow((1.0/NNdist[2]),2.0); NNwt[3] = pow((1.0/NNdist[3]),2.0); RDRinterp[i].elevation = (NNwt[0]*NNelev[0] + NNwt[1]*NNelev[1] + NNwt[2]*NNelev[2] + NNwt[3]*NNelev[3]) / (NNwt[0] + NNwt[1] + NNwt[2] + NNwt[3]); } } /*end interpolate this point*/ } /*end only do this point if there's a DEM value*/ } /*end for all points to be interpolated*/ printf(" Done!\n\n"); /*WRITE DEM and RDR elevations to output, if both have values!*/ /*X,Y,Z ASCII Lists**********************************************/ DEMfile = fopen(Filenames[2], "w"); RDRfile = fopen(Filenames[3], "w"); if (DEMfile == NULL) { printf("Cannot open DEM output file=[%s]:[%s]! Exiting.\n", Filenames[2], strerror(errno)); return(-1); } if (RDRfile == NULL) { printf("Cannot open Radar output file=[%s]:[%s]! Exiting.\n", Filenames[3], strerror(errno)); return(-1); } j=0; for (i=0;i<DEMinboundsct;i++){ if (RDRinterp[i].elevation!=-9999) { j++; fprintf(DEMfile, "%0.3f\t%0.3f\t%0.6f\n", cropDEMvals[i].easting, cropDEMvals[i].northing, cropDEMvals[i].elevation); fprintf(RDRfile, "%0.3f\t%0.3f\t%0.6f\n", RDRinterp[i].easting, RDRinterp[i].northing, RDRinterp[i].elevation); } } fclose(RDRfile); fclose(DEMfile); printf("%u points written to ASCII Output files:\n %s (DEM)\n %s (RDR)\n", j, Filenames[2],Filenames[3]); /*Calculate simulation time elapsed, and print it.*/ endTime = time(NULL); printf("\nElapsed Time approximately %u seconds.\n\n", (unsigned)(endTime - startTime)); return(0); }
static int tzparse(const char *name, register struct state *const sp, const int lastditch) { const char *stdname; const char *dstname; size_t stdlen; size_t dstlen; long stdoffset; long dstoffset; register time_t *atp; register unsigned char *typep; register char *cp; INITIALIZE(dstname); stdname = name; if (lastditch) { stdlen = strlen(name); /* length of standard zone name */ name += stdlen; if (stdlen >= sizeof sp->chars) stdlen = (sizeof sp->chars) - 1; stdoffset = 0; } else { name = getzname(name); stdlen = name - stdname; if (stdlen < 3) return -1; if (*name == '\0') return -1; name = getoffset(name, &stdoffset); if (name == NULL) return -1; } sp->leapcnt = 0; /* so, we're off a little */ if (*name != '\0') { dstname = name; name = getzname(name); dstlen = name - dstname; /* length of DST zone name */ if (dstlen < 3) return -1; if (*name != '\0' && *name != ',' && *name != ';') { name = getoffset(name, &dstoffset); if (name == NULL) return -1; } else dstoffset = stdoffset - SECSPERHOUR; /* Go parsing the daylight saving stuff */ if (*name == ',' || *name == ';') { struct rule start; struct rule end; register int year; register time_t janfirst; time_t starttime; time_t endtime; ++name; if ((name = getrule(name, &start)) == NULL) return -1; if (*name++ != ',') return -1; if ((name = getrule(name, &end)) == NULL) return -1; if (*name != '\0') return -1; sp->typecnt = 2; /* standard time and DST */ /* ** Two transitions per year, from EPOCH_YEAR to 2037. */ sp->timecnt = 2 * (2037 - EPOCH_YEAR + 1); if (sp->timecnt > TZ_MAX_TIMES) return -1; sp->ttis[0].tt_gmtoff = -dstoffset; sp->ttis[0].tt_isdst = 1; sp->ttis[0].tt_abbrind = (int) (stdlen + 1); sp->ttis[1].tt_gmtoff = -stdoffset; sp->ttis[1].tt_isdst = 0; sp->ttis[1].tt_abbrind = 0; atp = sp->ats; typep = sp->types; janfirst = 0; for (year = EPOCH_YEAR; year <= 2037; ++year) { starttime = transtime(janfirst, year, &start, stdoffset); endtime = transtime(janfirst, year, &end, dstoffset); if (starttime > endtime) { *atp++ = endtime; *typep++ = 1; /* DST ends */ *atp++ = starttime; *typep++ = 0; /* DST begins */ } else { *atp++ = starttime; *typep++ = 0; /* DST begins */ *atp++ = endtime; *typep++ = 1; /* DST ends */ } janfirst += year_lengths[isleap(year)] * SECSPERDAY; } } else { register long theirstdoffset; register long theirdstoffset; register long theiroffset; register int isdst; register int i; register int j; if (*name != '\0') return -1; /* Initial values of theirstdoffset and theirdstoffset. */ theirstdoffset = 0; for (i = 0; i < sp->timecnt; ++i) { j = sp->types[i]; if (!sp->ttis[j].tt_isdst) { theirstdoffset = -sp->ttis[j].tt_gmtoff; break; } } theirdstoffset = 0; for (i = 0; i < sp->timecnt; ++i) { j = sp->types[i]; if (sp->ttis[j].tt_isdst) { theirdstoffset = -sp->ttis[j].tt_gmtoff; break; } } /* ** Initially we're assumed to be in standard time. */ isdst = FALSE; theiroffset = theirstdoffset; /* ** Now juggle transition times and types ** tracking offsets as you do. */ for (i = 0; i < sp->timecnt; ++i) { j = sp->types[i]; sp->types[i] = (unsigned char) sp->ttis[j].tt_isdst; if (sp->ttis[j].tt_ttisgmt) { /* No adjustment to transition time */ } else { /* ** If summer time is in effect, and the ** transition time was not specified as ** standard time, add the summer time ** offset to the transition time; ** otherwise, add the standard time ** offset to the transition time. */ /* ** Transitions from DST to DDST ** will effectively disappear since ** POSIX provides for only one DST ** offset. */ if (isdst && !sp->ttis[j].tt_ttisstd) { sp->ats[i] += dstoffset - theirdstoffset; } else { sp->ats[i] += stdoffset - theirstdoffset; } } theiroffset = -sp->ttis[j].tt_gmtoff; if (sp->ttis[j].tt_isdst) theirdstoffset = theiroffset; else theirstdoffset = theiroffset; } /* ** Finally, fill in ttis. ** ttisstd and ttisgmt need not be handled. */ sp->ttis[0].tt_gmtoff = -stdoffset; sp->ttis[0].tt_isdst = FALSE; sp->ttis[0].tt_abbrind = 0; sp->ttis[1].tt_gmtoff = -dstoffset; sp->ttis[1].tt_isdst = TRUE; sp->ttis[1].tt_abbrind = (int) (stdlen + 1); sp->typecnt = 2; } } else { dstlen = 0; sp->typecnt = 1; /* only standard time */ sp->timecnt = 0; sp->ttis[0].tt_gmtoff = -stdoffset; sp->ttis[0].tt_isdst = 0; sp->ttis[0].tt_abbrind = 0; } sp->charcnt = (int) (stdlen + 1); if (dstlen != 0) sp->charcnt += (int) (dstlen + 1); if ((size_t) sp->charcnt > sizeof sp->chars) return -1; cp = sp->chars; (void) strncpy(cp, stdname, stdlen); cp += stdlen; *cp++ = '\0'; if (dstlen != 0) { (void) strncpy(cp, dstname, dstlen); *(cp + dstlen) = '\0'; } return 0; }
extern "C" int PyType_Ready(PyTypeObject* cls) { gc::registerNonheapRootObject(cls); // unhandled fields: RELEASE_ASSERT(cls->tp_print == NULL, ""); RELEASE_ASSERT(cls->tp_getattr == NULL, ""); RELEASE_ASSERT(cls->tp_setattr == NULL, ""); RELEASE_ASSERT(cls->tp_compare == NULL, ""); RELEASE_ASSERT(cls->tp_repr == NULL, ""); RELEASE_ASSERT(cls->tp_as_number == NULL, ""); RELEASE_ASSERT(cls->tp_as_sequence == NULL, ""); RELEASE_ASSERT(cls->tp_as_mapping == NULL, ""); RELEASE_ASSERT(cls->tp_hash == NULL, ""); RELEASE_ASSERT(cls->tp_str == NULL, ""); RELEASE_ASSERT(cls->tp_getattro == NULL || cls->tp_getattro == PyObject_GenericGetAttr, ""); RELEASE_ASSERT(cls->tp_setattro == NULL, ""); RELEASE_ASSERT(cls->tp_as_buffer == NULL, ""); int ALLOWABLE_FLAGS = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC; RELEASE_ASSERT((cls->tp_flags & ~ALLOWABLE_FLAGS) == 0, ""); // RELEASE_ASSERT(cls->tp_traverse == NULL, ""); // RELEASE_ASSERT(cls->tp_clear == NULL, ""); RELEASE_ASSERT(cls->tp_richcompare == NULL, ""); RELEASE_ASSERT(cls->tp_iter == NULL, ""); RELEASE_ASSERT(cls->tp_iternext == NULL, ""); RELEASE_ASSERT(cls->tp_base == NULL, ""); RELEASE_ASSERT(cls->tp_dict == NULL, ""); RELEASE_ASSERT(cls->tp_descr_get == NULL, ""); RELEASE_ASSERT(cls->tp_descr_set == NULL, ""); RELEASE_ASSERT(cls->tp_init == NULL, ""); RELEASE_ASSERT(cls->tp_alloc == NULL, ""); RELEASE_ASSERT(cls->tp_free == NULL || cls->tp_free == PyObject_Del, ""); RELEASE_ASSERT(cls->tp_is_gc == NULL, ""); RELEASE_ASSERT(cls->tp_base == NULL, ""); RELEASE_ASSERT(cls->tp_mro == NULL, ""); RELEASE_ASSERT(cls->tp_cache == NULL, ""); RELEASE_ASSERT(cls->tp_subclasses == NULL, ""); RELEASE_ASSERT(cls->tp_weaklist == NULL, ""); RELEASE_ASSERT(cls->tp_del == NULL, ""); RELEASE_ASSERT(cls->tp_version_tag == 0, ""); // I think it is safe to ignore tp_weaklistoffset for now: // RELEASE_ASSERT(cls->tp_weaklistoffset == 0, ""); #define INITIALIZE(a) new (&(a)) decltype(a) INITIALIZE(cls->attrs); INITIALIZE(cls->dependent_icgetattrs); #undef INITIALIZE BoxedClass* base = cls->base = object_cls; if (!cls->cls) cls->cls = cls->base->cls; assert(cls->tp_name); cls->giveAttr("__name__", boxStrConstant(cls->tp_name)); // tp_name // tp_basicsize, tp_itemsize // tp_doc if (!cls->tp_new && base != object_cls) cls->tp_new = base->tp_new; if (cls->tp_new) { cls->giveAttr("__new__", new BoxedCApiFunction(METH_VARARGS | METH_KEYWORDS, cls, "__new__", (PyCFunction)tp_new_wrapper)); } if (cls->tp_call) { cls->giveAttr("__call__", new BoxedWrapperDescriptor(&call_wrapper, cls)); } if (!cls->tp_alloc) { cls->tp_alloc = reinterpret_cast<decltype(cls->tp_alloc)>(PyType_GenericAlloc); } for (PyMethodDef* method = cls->tp_methods; method && method->ml_name; ++method) { cls->giveAttr(method->ml_name, new BoxedMethodDescriptor(method, cls)); } for (PyMemberDef* member = cls->tp_members; member && member->name; ++member) { cls->giveAttr(member->name, new BoxedMemberDescriptor(member)); } if (cls->tp_getset) { if (VERBOSITY()) printf("warning: ignoring tp_getset for now\n"); } cls->gc_visit = &conservativeGCHandler; // TODO not sure how we can handle extension types that manually // specify a dict... RELEASE_ASSERT(cls->tp_dictoffset == 0, ""); // this should get automatically initialized to 0 on this path: assert(cls->attrs_offset == 0); return 0; }