示例#1
0
  Solution(){
     srand(time(NULL));
 }
示例#2
0
文件: lfile.cpp 项目: kenjreno/lora3
VOID UpdateFilebase (USHORT KeepDate)
{
   FILE *fp;
   DIR *dir;
   ULONG Total, Added;
   CHAR *p, Path[128], Temp[128];
   time_t today;
   struct stat statbuf;
   struct tm *ltm;
   struct dirent *ent;
   class TFileData *Data;
   class TFileBase *File;
   class TPacker *Packer;

   printf (" * Updating filebase\r\n");

   unlink ("file_id.diz");
   Packer = new TPacker (Cfg->SystemPath);

   if ((Data = new TFileData (Cfg->SystemPath)) != NULL) {
      if (Data->First () == TRUE)
         do {
            Total = 0L;
            Added = 0L;
            cprintf (" +-- %-15.15s %-32.32s ", Data->Key, Data->Display);
            if ((File = new TFileBase (Cfg->SystemPath, Data->Key)) != NULL) {
               strcpy (Temp, Data->Download);
               if (Temp[strlen (Temp) - 1] == '\\' || Temp[strlen (Temp) - 1] == '/')
                  Temp[strlen (Temp) - 1] = '\0';

               if (File->First () == TRUE)
                  do {
                     sprintf (Path, "%s%s", Data->Download, File->Name);
                     if (stat (AdjustPath (Path), &statbuf))
                        File->Delete ();
                  } while (File->Next () == TRUE);

               File->SortByName ();
               if ((dir = opendir (AdjustPath (Temp))) != NULL) {
                  while ((ent = readdir (dir)) != NULL) {
                     if (!strcmp (ent->d_name, ".") || !strcmp (ent->d_name, ".."))
                        continue;
                     if (!stricmp (ent->d_name, "files.bbs") || !stricmp (ent->d_name, "descript.ion"))
                        continue;
                     if (File->Read (ent->d_name) == FALSE) {
                        sprintf (Path, "%s%s", Data->Download, ent->d_name);
                        if (!stat (AdjustPath (Path), &statbuf)) {
                           File->Clear ();
                           strcpy (File->Area, Data->Key);
                           strcpy (File->Name, ent->d_name);
                           strcpy (File->Complete, Path);
                           File->Size = statbuf.st_size;
                           ltm = localtime ((time_t *)&statbuf.st_mtime);
                           File->Date.Day = (UCHAR)ltm->tm_mday;
                           File->Date.Month = (UCHAR)(ltm->tm_mon + 1);
                           File->Date.Year = (USHORT)(ltm->tm_year + 1900);
                           File->Date.Hour = (UCHAR)ltm->tm_hour;
                           File->Date.Minute = (UCHAR)ltm->tm_min;
                           if (KeepDate == FALSE) {
                              today = time (NULL);
                              ltm = localtime (&today);
                              File->UplDate.Day = (UCHAR)ltm->tm_mday;
                              File->UplDate.Month = (UCHAR)(ltm->tm_mon + 1);
                              File->UplDate.Year = (USHORT)(ltm->tm_year + 1900);
                              File->UplDate.Hour = (UCHAR)ltm->tm_hour;
                              File->UplDate.Minute = (UCHAR)ltm->tm_min;
                           }
                           else {
                              File->UplDate.Day = File->Date.Day;
                              File->UplDate.Month = File->Date.Month;
                              File->UplDate.Year = File->Date.Year;
                              File->UplDate.Hour = File->Date.Hour;
                              File->UplDate.Minute = File->Date.Minute;
                           }
                           File->Uploader = "Sysop";
                           File->CdRom = Data->CdRom;
                           File->Description->Add ("Description missing");
                           if (Packer != NULL) {
                              if (Packer->CheckArc (Path) == TRUE) {
#if defined(__LINUX__)
                                 mkdir ("lfiletmp", 0666);
#else
                                 mkdir ("lfiletmp");
#endif
                                 if (strstr (Packer->UnpackCmd, "%3") == NULL && strstr (Packer->UnpackCmd, "%f") == NULL)
                                    strcat (Packer->UnpackCmd, " %3");
                                 Packer->DoUnpack (Path, "lfiletmp", "file_id.diz");
                                 strcpy (Temp, "lfiletmp\\file_id.diz");
                                 if (!stat (AdjustPath (Temp), &statbuf)) {
                                    if ((fp = fopen (Temp, "rt")) != NULL) {
                                       File->Description->Clear ();
                                       while (fgets (Temp, sizeof (Temp) - 1, fp) != NULL) {
                                          if ((p = strchr (Temp, '\n')) != NULL)
                                             *p = '\0';
                                          if ((p = strchr (Temp, '\r')) != NULL)
                                             *p = '\0';
                                          File->Description->Add (Temp);
                                       }
                                       fclose (fp);
                                    }
                                    strcpy (Temp, "lfiletmp\\file_id.diz");
                                    unlink (AdjustPath (Temp));
                                 }
                                 rmdir ("lfiletmp");
                              }
                           }
                           File->Add ();
                           Added++;
                        }
                     }
                     Total++;
                  }
                  closedir (dir);
               }
               delete File;
            }
            cprintf ("Total: %5lu Added: %5lu\r\n", Total, Added);
         } while (Data->Next () == TRUE);
      delete Data;
   }

   if (Packer != NULL)
      delete Packer;
}
示例#3
0
/* returns:
 *   0 on success
 *   1 if compact was not needed
 *   negative on error
 */
EXPORTED int backup_compact(const char *name,
                            enum backup_open_nonblock nonblock,
                            int force, int verbose, FILE *out)
{
    struct backup *original = NULL;
    struct backup *compact = NULL;
    struct backup_chunk_list *all_chunks = NULL;
    struct backup_chunk_list *keep_chunks = NULL;
    struct backup_chunk *chunk = NULL;
    struct sync_msgid_list *keep_message_guids = NULL;
    struct gzuncat *gzuc = NULL;
    struct protstream *in = NULL;
    time_t since, chunk_start_time, ts;
    int r;

    compact_readconfig();

    r = compact_open(name, &original, &compact, nonblock);
    if (r) return r;

    /* calculate current time after obtaining locks, in case of a wait */
    const time_t now = time(NULL);

    const int retention_days = config_getint(IMAPOPT_BACKUP_RETENTION_DAYS);
    if (retention_days > 0) {
        since = now - (retention_days * 24 * 60 * 60);
    }
    else {
        /* zero or negative retention days means "keep forever" */
        since = -1;
    }

    all_chunks = backup_get_chunks(original);
    if (!all_chunks) goto error;

    keep_chunks = backup_get_live_chunks(original, since);
    if (!keep_chunks) goto error;

    if (!force && !compact_required(all_chunks, keep_chunks)) {
        /* nothing to do */
        backup_chunk_list_free(&all_chunks);
        backup_chunk_list_free(&keep_chunks);
        backup_unlink(&compact);
        backup_close(&original);
        return 1;
    }

    if (verbose) {
        fprintf(out, "keeping " SIZE_T_FMT " chunks:\n", keep_chunks->count);

        for (chunk = keep_chunks->head; chunk; chunk = chunk->next) {
            fprintf(out, " %d", chunk->id);
        }

        fprintf(out, "\n");
    }

    gzuc = gzuc_new(original->fd);
    if (!gzuc) goto error;

    chunk_start_time = -1;
    ts = 0;
    struct buf cmd = BUF_INITIALIZER;
    for (chunk = keep_chunks->head; chunk; chunk = chunk->next) {
        keep_message_guids = sync_msgid_list_create(0);
        r = backup_message_foreach(original, chunk->id, &since,
                                   _keep_message_guids_cb, keep_message_guids);
        if (r) goto error;

        gzuc_member_start_from(gzuc, chunk->offset);

        in = prot_readcb(_prot_fill_cb, gzuc);

        while (1) {
            struct dlist *dl = NULL;

            int c = parse_backup_line(in, &ts, &cmd, &dl);

            if (c == EOF) {
                const char *error = prot_error(in);
                if (error && 0 != strcmp(error, PROT_EOF_STRING)) {
                    syslog(LOG_ERR,
                           "IOERROR: %s: error reading chunk at offset %jd, byte %i: %s\n",
                           name, chunk->offset, prot_bytes_in(in), error);

                    if (out)
                        fprintf(out, "error reading chunk at offset %jd, byte %i: %s\n",
                                chunk->offset, prot_bytes_in(in), error);

                    r = IMAP_IOERROR;
                    goto error;
                }

                break;
            }

            if (chunk_start_time == -1) {
                r = backup_append_start(compact, &ts, BACKUP_APPEND_NOFLUSH);
                if (r) goto error;
                chunk_start_time = ts;
            }

            // XXX if this line is worth keeping
            if (want_append(original, chunk->id, dl, keep_message_guids)) {
                // FIXME if message is removed due to unneeded chunk,
                // subsequent mailbox lines for it will fail here
                // so we need to be able to tell which lines apply to messages we don't want anymore
                r = backup_append(compact, dl, &ts, BACKUP_APPEND_NOFLUSH);
                if (r) goto error;
            }

            dlist_unlink_files(dl);
            dlist_free(&dl);

            // if this line put us over compact_maxsize
            if (want_split(chunk, &compact->append_state->wrote)) {
                r = backup_append_end(compact, &ts);
                chunk_start_time = -1;

                if (verbose) {
                    fprintf(out, "splitting chunk %d\n", chunk->id);
                }
            }
        }

        // if we're due to start a new chunk
        if (compact->append_state && compact->append_state->mode) {
            if (!want_combine(compact->append_state->wrote, chunk->next)) {
                r = backup_append_end(compact, &ts);
                chunk_start_time = -1;
            }
            else if (verbose) {
                fprintf(out, "combining chunks %d and %d\n",
                             chunk->id, chunk->next->id);
            }
        }

        prot_free(in);
        in = NULL;
        gzuc_member_end(gzuc, NULL);

        sync_msgid_list_free(&keep_message_guids);
    }
    buf_free(&cmd);

    if (compact->append_state && compact->append_state->mode)
        backup_append_end(compact, &ts);

    gzuc_free(&gzuc);

    backup_chunk_list_free(&keep_chunks);

    /* if we get here okay, then the compact succeeded */
    r = compact_closerename(&original, &compact, now);
    if (r) goto error;

    return 0;

error:
    if (in) prot_free(in);
    if (gzuc) gzuc_free(&gzuc);
    if (keep_message_guids) sync_msgid_list_free(&keep_message_guids);
    if (all_chunks) backup_chunk_list_free(&all_chunks);
    if (keep_chunks) backup_chunk_list_free(&keep_chunks);
    if (compact) backup_unlink(&compact);
    if (original) backup_close(&original);

    return r ? r : -1;
}
示例#4
0
文件: timer.c 项目: jasonblog/note
static void oneshot_cb (EV_P_ ev_timer *w, int revents)
{
    printf("oneshot at %ju\n", (uintmax_t)time(NULL));
    ev_timer_stop(EV_A_ w);
}
示例#5
0
int main(int argc, char** argv) {
	int i = 0, j = 0;
	ull gen_size = 0, code_size = 0, data_size = 0;
	ull blocks = 0, wordsize = 0, dim = 0;
	unsigned char *G = NULL, *D = NULL, *DD = NULL, *C = NULL, *NC = NULL;
	unsigned short *masks = NULL;
	unsigned char *code_tmp = NULL, *data_block_tmp = NULL;
	double accumulator = 0;
	char buffer[100];

	FILE *fout = NULL;
	
	srand (time(NULL));

	ull r = 0, m = 16, k = 50, max_iter = 700;
	data_size = 4096;

	char **ptr = NULL;
	
	if (argc == 3) {
		r = strtol(argv[1], ptr, 10);
		m = strtol(argv[2], ptr, 10);
	}

	//rm_test_0(r, m, k, max_iter, stdout);

	for (i = r; i < m; ++i) {
		sprintf(buffer, "output_%2d", i);
		fout = fopen(buffer, "w");
		fprintf(fout, "%d\n", i);
		for (j = 0; j <= i; ++j) {
			printf("%d %d\n", i, j);
			fprintf(fout, "%d %d\n", i, j);
			rm_test_0(j, i, k, max_iter, fout);
			fprintf(fout, "\n");
		}
		fclose(fout);
	}

	//rm_test_0(r, m, k, max_iter);
	// //for (m = 12; m < 16; ++m) 
	// {
	// 	gen_size = generation_mem_size(m, m);
	// 	G = (unsigned char *) malloc(gen_size);
	// 	generate_matrix(m, m, G);

	// 	masks = (unsigned short *) malloc((1 << m) * sizeof(unsigned short));
	// 	generate_masks(m, masks);

	// 	// for (r = 0; r <= m; ++r) 
	// 	{
				
	// 		D =	(unsigned char *) malloc(data_size);
	// 		DD = (unsigned char *) malloc(data_size);

	// 		for (int i = 0; i < data_size; ++i)
	// 			D[i] = (unsigned char) rand();
		     			

	// 		code_size = encode_mem_size(data_size, r, m);
	// 		C = (unsigned char *) malloc(code_size);
	// 		NC = (unsigned char *) malloc(code_size);


	// 		encode(r, m, G, data_size, D, C, masks);
			
	// 		blocks = rm_blocks(data_size, r, m);
	// 		wordsize = rm_wordsize(r, m);
	// 		dim = rm_dim(r, m);


	// 		code_tmp = (unsigned char *) malloc(wordsize / 8 + (wordsize % 8 == 0 ? 0 : 1));
	// 		data_block_tmp = (unsigned char *) malloc(dim / 8 + (dim % 8 == 0 ? 0 : 1));

	// 		decode(r, m, G, data_size, DD, C, masks, code_tmp, data_block_tmp);

	// 		// print(1, 8 * data_size, D);//printf("\n");
	// 		// print(1, 8 * data_size, DD);printf("\n\n");


	// 		//printf("r = %d, m = %d\n", r, m);
	// 		//printf("\nAccuracy %1.9lf:\n\n", accuracy(data_size, D, DD));


	// 		for (ull i = 0; i <= k; i++) {
	// 			accumulator = 0;
	// 			printf("%1.9lf ", (double) i / (double) k);

	// 			for (ull j = 0; j < max_iter; ++j) {
	// 				memcpy(NC, C, code_size);
	// 				add_noise(NC, code_size, (double) i / (double) k);	
	// 				decode(r, m, G, data_size, DD, NC, masks, code_tmp, data_block_tmp);
	// 				accumulator += accuracy(data_size, dim, D, DD);
	// 			}

	// 			printf("%1.9lf \n", accumulator / max_iter);
	// 		}

	// 		FREE_IF_ALLOCATED(C);
	// 		FREE_IF_ALLOCATED(D);
	// 		FREE_IF_ALLOCATED(DD);
			
	// 		FREE_IF_ALLOCATED(NC);

	// 		FREE_IF_ALLOCATED(code_tmp);
	// 		FREE_IF_ALLOCATED(data_block_tmp);
	// 	}

	// 	FREE_IF_ALLOCATED(masks);
	// 	FREE_IF_ALLOCATED(G);
	// }
	return 0;
}
示例#6
0
static void rearm(time_t *timer, int seconds)
{
	time(timer);
	*timer += seconds;
}
示例#7
0
文件: timer.c 项目: jasonblog/note
// another callback, this time for a time-out
static void timeout_cb (EV_P_ ev_timer *w, int revents)
{
    printf("timeout at %ju\n", (uintmax_t)time(NULL));
    // this causes the innermost ev_run to stop iterating
    ev_break (EV_A_ EVBREAK_ONE);
}
示例#8
0
/* internal log handler function */
static int default_log_handler(log_level_t level,const char *fmt, va_list args) {
    time_t epoch;
    time(&epoch);
    return _log_vfprintf(log_out, &epoch, LEVEL_EVENTS[level], fmt, args);
}
示例#9
0
 static int getEpochTime()
 {
     return (unsigned int)time(NULL);
 }
示例#10
0
int main(int argc, char **argv)
{
  float *Hydrograph = NULL;
  float ***MM5Input = NULL;
  float **PrecipLapseMap = NULL;
  float **PrismMap = NULL;
  unsigned char ***ShadowMap = NULL;
  float **SkyViewMap = NULL;
  float ***WindModel = NULL;
  int MaxStreamID, MaxRoadID;
  float SedDiams[NSEDSIZES];     /* Sediment particle diameters (mm) */
  clock_t start, finish1;
  double runtime = 0.0;
  int t = 0;
  float roadarea;
  time_t tloc;
  int flag;
  int i;
  int j;
  int x;						/* row counter */
  int y;						/* column counter */
  int shade_offset;				/* a fast way of handling arraay position given the number of mm5 input options */
  int NStats;					/* Number of meteorological stations */
  uchar ***MetWeights = NULL;	/* 3D array with weights for interpolating meteorological variables between the stations */

  int NGraphics;				/* number of graphics for X11 */
  int *which_graphics;			/* which graphics for X11 */
  char buffer[32];

  AGGREGATED Total = {			/* Total or average value of a  variable over the entire basin */
    {0.0, NULL, NULL, NULL, NULL, 0.0},												/* EVAPPIX */
    {0.0, 0.0, 0.0, 0.0, 0.0, NULL, NULL, 0.0, 0, 0.0},								/* PRECIPPIX */
    {{0.0, 0.0}, {0.0, 0.0}, {0.0, 0.0}, 0.0, 0.0, 0.0},							/* PIXRAD */
    {0.0, 0.0},																		/* RADCLASSPIX */
    {0.0, 0.0, 0, NULL, NULL, 0.0, 0, 0.0, 0.0, 0.0, 0.0, NULL, 
	NULL, NULL, NULL, NULL, NULL, 0.0},												/* ROADSTRUCT*/
    {0, 0, 0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0},		/* SNOWPIX */
    {0, 0.0, NULL, NULL, NULL, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
     0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0},			/*SOILPIX */
    { 0.0, 0.0, 0.0, 0.0, 0.0},														/*SEDPIX */
    { 0.0, 0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0},							/*FINEPIX */
    0.0, 0.0, 0.0, 0.0, 0.0, 0l, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0
  };
  CHANNEL ChannelData = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, 
  NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  NULL, NULL, NULL, NULL};
  DUMPSTRUCT Dump;
  EVAPPIX **EvapMap = NULL;
  INPUTFILES InFiles;
  LAYER Soil;
  LAYER Veg;
  LISTPTR Input = NULL;			/* Linked list with input strings */
  MAPSIZE Map;					/* Size and location of model area */
  MAPSIZE Radar;				/* Size and location of area covered by precipitation radar */
  MAPSIZE MM5Map;				/* Size and location of area covered by MM5 input files */
  METLOCATION *Stat = NULL;
  OPTIONSTRUCT Options;			/* Structure with information which program options to follow */
  PIXMET LocalMet;				/* Meteorological conditions for current pixel */
  FINEPIX ***FineMap	= NULL;
  PRECIPPIX **PrecipMap = NULL;
  RADARPIX **RadarMap	= NULL;
  RADCLASSPIX **RadMap	= NULL;
  PIXRAD **RadiationMap = NULL;
  ROADSTRUCT **Network	= NULL;	/* 2D Array with channel information for each pixel */
  SNOWPIX **SnowMap		= NULL;
  MET_MAP_PIX **MetMap	= NULL;
  SNOWTABLE *SnowAlbedo = NULL;
  SOILPIX **SoilMap		= NULL;
  SEDPIX **SedMap		= NULL;
  SOILTABLE *SType	    = NULL;
  SEDTABLE *SedType		= NULL;
  SOLARGEOMETRY SolarGeo;		/* Geometry of Sun-Earth system (needed for INLINE radiation calculations */
  TIMESTRUCT Time;
  TOPOPIX **TopoMap = NULL;
  UNITHYDR **UnitHydrograph = NULL;
  UNITHYDRINFO HydrographInfo;	/* Information about unit hydrograph */
  VEGPIX **VegMap = NULL;
  VEGTABLE *VType = NULL;
  WATERBALANCE Mass =			/* parameter for mass balance calculations */
    { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,  
      0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };

/*****************************************************************************
  Initialization Procedures 
*****************************************************************************/
  if (argc != 2) {
    fprintf(stderr, "\nUsage: %s inputfile\n\n", argv[0]);
    fprintf(stderr, "DHSVM uses two output streams: \n");
    fprintf(stderr, "Standard Out, for the majority of output \n");
    fprintf(stderr, "Standard Error, for the final mass balance \n");
    fprintf(stderr, "\nTo pipe output correctly to files: \n");
    fprintf(stderr, "(cmd > f1) >& f2 \n");
    fprintf(stderr, "where f1 is stdout_file and f2 is stderror_file\n");
    exit(EXIT_FAILURE);
  }

  sprintf(commandline, "%s %s", argv[0], argv[1]);
  printf("%s \n", commandline);
  fprintf(stderr, "%s \n", commandline);
  strcpy(InFiles.Const, argv[1]);

  printf("\nRunning DHSVM %s\n", version);
  printf("\nSTARTING INITIALIZATION PROCEDURES\n\n");

  /* Start recording time */
  start = clock();

  ReadInitFile(InFiles.Const, &Input);
  InitConstants(Input, &Options, &Map, &SolarGeo, &Time);

  InitFileIO(Options.FileFormat);
  InitTables(Time.NDaySteps, Input, &Options, &SType, &Soil, &VType, &Veg,
	     &SnowAlbedo);

  InitTerrainMaps(Input, &Options, &Map, &Soil, &TopoMap, &SoilMap, &VegMap);

  CheckOut(Options.CanopyRadAtt, Veg, Soil, VType, SType, &Map, TopoMap, 
	   VegMap, SoilMap);

  if (Options.HasNetwork)
    InitChannel(Input, &Map, Time.Dt, &ChannelData, SoilMap, &MaxStreamID, &MaxRoadID, &Options);
  else if (Options.Extent != POINT)
    InitUnitHydrograph(Input, &Map, TopoMap, &UnitHydrograph,
		       &Hydrograph, &HydrographInfo);
 
  InitNetwork(Map.NY, Map.NX, Map.DX, Map.DY, TopoMap, SoilMap, 
	      VegMap, VType, &Network, &ChannelData, Veg, &Options);

  InitMetSources(Input, &Options, &Map, Soil.MaxLayers, &Time,
		 &InFiles, &NStats, &Stat, &Radar, &MM5Map);

  /* the following piece of code is for the UW PRISM project */
  /* for real-time verification of SWE at Snotel sites */
  /* Other users, set OPTION.SNOTEL to FALSE, or use TRUE with caution */

  if (Options.Snotel == TRUE && Options.Outside == FALSE) {
    printf
      ("Warning: All met stations locations are being set to the vegetation class GLACIER\n");
    printf
      ("Warning: This requires that you have such a vegetation class in your vegetation table\n");
    printf("To disable this feature set Snotel OPTION to FALSE\n");
    for (i = 0; i < NStats; i++) {
      printf("veg type for station %d is %d ", i,
	     VegMap[Stat[i].Loc.N][Stat[i].Loc.E].Veg);
      for (j = 0; j < Veg.NTypes; j++) {
	    if (VType[j].Index == GLACIER) {
	      VegMap[Stat[i].Loc.N][Stat[i].Loc.E].Veg = j;
		  break;
		}
      }
      if (j == Veg.NTypes) {	/* glacier class not found */
	    ReportError("MainDHSVM", 62);
	  }
      printf("setting to glacier type (assumed bare class): %d\n", j);
    }
  }

  InitMetMaps(Time.NDaySteps, &Map, &Radar, &Options, InFiles.WindMapPath,
	      InFiles.PrecipLapseFile, &PrecipLapseMap, &PrismMap,
	      &ShadowMap, &SkyViewMap, &EvapMap, &PrecipMap,
	      &RadarMap, &RadMap, SoilMap, &Soil, VegMap, &Veg, TopoMap,
	      &MM5Input, &WindModel);

  InitInterpolationWeights(&Map, &Options, TopoMap, &MetWeights, Stat, NStats);

  InitDump(Input, &Options, &Map, Soil.MaxLayers, Veg.MaxLayers, Time.Dt,
	   TopoMap, &Dump, &NGraphics, &which_graphics);

  if (Options.HasNetwork == TRUE) {
    InitChannelDump(&Options, &ChannelData, Dump.Path);
    ReadChannelState(Dump.InitStatePath, &(Time.Start), ChannelData.streams);
	if (Options.StreamTemp && Options.CanopyShading)
	  InitChannelRVeg(&Time, ChannelData.streams);
  }

  InitSnowMap(&Map, &SnowMap);
  InitAggregated(Veg.MaxLayers, Soil.MaxLayers, &Total);

  InitModelState(&(Time.Start), &Map, &Options, PrecipMap, SnowMap, SoilMap,
		 Soil, SType, VegMap, Veg, VType, Dump.InitStatePath,
		 SnowAlbedo, TopoMap, Network, &HydrographInfo, Hydrograph);

  InitNewMonth(&Time, &Options, &Map, TopoMap, PrismMap, ShadowMap,
	       RadMap, &InFiles, Veg.NTypes, VType, NStats, Stat, 
	       Dump.InitStatePath);

  InitNewDay(Time.Current.JDay, &SolarGeo);

  if (NGraphics > 0) {
    printf("Initialzing X11 display and graphics \n");
    InitXGraphics(argc, argv, Map.NY, Map.NX, NGraphics, &MetMap);
  }

  shade_offset = FALSE;
  if (Options.Shading == TRUE)
    shade_offset = TRUE;

  /* Done with initialization, delete the list with input strings */
  DeleteList(Input);

  /*****************************************************************************
  Sediment Initialization Procedures 
  *****************************************************************************/
  if(Options.Sediment) {
     time (&tloc);
     srand (tloc);
  /* Randomize Random Generator */
 
  /* Commenting the line above and uncommenting the line below 
     allows for the comparison of scenarios. */
  /*  srand48 (0);  */
    printf("\nSTARTING SEDIMENT INITIALIZATION PROCEDURES\n\n");

    ReadInitFile(Options.SedFile, &Input);

    InitParameters(Input, &Options, &Map, &Network, &ChannelData, TopoMap,
		   &Time, SedDiams);

    InitSedimentTables(Time.NDaySteps, Input, &SedType, &SType, &VType, &Soil, &Veg);

    InitFineMaps(Input, &Options, &Map, &Soil, &TopoMap, &SoilMap, 
		  &FineMap);

    if (Options.HasNetwork){ 
      printf("Initializing channel sediment\n\n");
      InitChannelSedimentDump(&ChannelData, Dump.Path, Options.ChannelRouting); 
      InitChannelSediment(ChannelData.streams, &Total);
      InitChannelSediment(ChannelData.roads, &Total);
    }

    InitSedMap( &Map, &SedMap);

    /* Done with initialization, delete the list with input strings */
    DeleteList(Input);
  }

  /* setup for mass balance calculations */
  Aggregate(&Map, &Options, TopoMap, &Soil, &Veg, VegMap, EvapMap, PrecipMap,
	      RadMap, SnowMap, SoilMap, &Total, VType, Network, SedMap, FineMap,
	      &ChannelData, &roadarea);

  Mass.StartWaterStorage =
    Total.Soil.IExcess + Total.CanopyWater + Total.SoilWater + Total.Snow.Swq +
    Total.Soil.SatFlow;
  Mass.OldWaterStorage = Mass.StartWaterStorage;

  if (Options.Sediment) {
    Mass.StartChannelSedimentStorage = Total.ChannelSedimentStorage;
    Mass.LastChannelSedimentStorage = Mass.StartChannelSedimentStorage;
  }

  /* computes the number of grid cell contributing to one segment */
  if (Options.StreamTemp) 
	Init_segment_ncell(TopoMap, ChannelData.stream_map, Map.NY, Map.NX, ChannelData.streams);

/*****************************************************************************
  Perform Calculations 
*****************************************************************************/
  while (Before(&(Time.Current), &(Time.End)) ||
	 IsEqualTime(&(Time.Current), &(Time.End))) {
    ResetAggregate(&Soil, &Veg, &Total, &Options);

    if (IsNewMonth(&(Time.Current), Time.Dt))
      InitNewMonth(&Time, &Options, &Map, TopoMap, PrismMap, ShadowMap,
		   RadMap, &InFiles, Veg.NTypes, VType, NStats, Stat, 
		   Dump.InitStatePath);

    if (IsNewDay(Time.DayStep)) {
      InitNewDay(Time.Current.JDay, &SolarGeo);
      PrintDate(&(Time.Current), stdout);
      printf("\n");
    }

    /* determine surface erosion and routing scheme */
    SedimentFlag(&Options, &Time); 

    InitNewStep(&InFiles, &Map, &Time, Soil.MaxLayers, &Options, NStats, Stat,
		InFiles.RadarFile, &Radar, RadarMap, &SolarGeo, TopoMap, RadMap,
        SoilMap, MM5Input, WindModel, &MM5Map);

    /* initialize channel/road networks for time step */
    if (Options.HasNetwork) {
      channel_step_initialize_network(ChannelData.streams);
      channel_step_initialize_network(ChannelData.roads);
    }

    for (y = 0; y < Map.NY; y++) {
      for (x = 0; x < Map.NX; x++) {
	    if (INBASIN(TopoMap[y][x].Mask)) {
		  if (Options.Shading)
	        LocalMet =
	        MakeLocalMetData(y, x, &Map, Time.DayStep, &Options, NStats,
			       Stat, MetWeights[y][x], TopoMap[y][x].Dem,
			       &(RadMap[y][x]), &(PrecipMap[y][x]), &Radar,
			       RadarMap, PrismMap, &(SnowMap[y][x]),
			       SnowAlbedo, MM5Input, WindModel, PrecipLapseMap,
			       &MetMap, NGraphics, Time.Current.Month,
			       SkyViewMap[y][x], ShadowMap[Time.DayStep][y][x],
			       SolarGeo.SunMax, SolarGeo.SineSolarAltitude);
		  else
	        LocalMet =
	        MakeLocalMetData(y, x, &Map, Time.DayStep, &Options, NStats,
			       Stat, MetWeights[y][x], TopoMap[y][x].Dem,
			       &(RadMap[y][x]), &(PrecipMap[y][x]), &Radar,
			       RadarMap, PrismMap, &(SnowMap[y][x]),
			       SnowAlbedo, MM5Input, WindModel, PrecipLapseMap,
			       &MetMap, NGraphics, Time.Current.Month, 0.0,
			       0.0, SolarGeo.SunMax,
			       SolarGeo.SineSolarAltitude);
		  
		  for (i = 0; i < Soil.MaxLayers; i++) {
	        if (Options.HeatFlux == TRUE) {
	          if (Options.MM5 == TRUE)
		        SoilMap[y][x].Temp[i] =
				MM5Input[shade_offset + i + N_MM5_MAPS][y][x];
			  else
		        SoilMap[y][x].Temp[i] = Stat[0].Data.Tsoil[i];
			}
	        else
	          SoilMap[y][x].Temp[i] = LocalMet.Tair;
		  }
		  
		  MassEnergyBalance(&Options, y, x, SolarGeo.SineSolarAltitude, Map.DX, Map.DY, 
			    Time.Dt, Options.HeatFlux, Options.CanopyRadAtt, Options.RoadRouting, 
			    Options.Infiltration, Veg.MaxLayers, &LocalMet, &(Network[y][x]), 
			    &(PrecipMap[y][x]), &(VType[VegMap[y][x].Veg-1]), &(VegMap[y][x]),
			    &(SType[SoilMap[y][x].Soil-1]), &(SoilMap[y][x]), &(SnowMap[y][x]), 
				&(EvapMap[y][x]), &(Total.Rad), &ChannelData, SkyViewMap);
		 
		  PrecipMap[y][x].SumPrecip += PrecipMap[y][x].Precip;
		}
	  }
    }

	/* Average all RBM inputs over each segment */
	if (Options.StreamTemp) {
	  channel_grid_avg(ChannelData.streams);
      if (Options.CanopyShading)
	    CalcCanopyShading(&Time, ChannelData.streams, &SolarGeo);
	}

 #ifndef SNOW_ONLY

    /* set sediment inflows to zero - they are incremented elsewhere */
    if ((Options.HasNetwork) && (Options.Sediment)){ 
      InitChannelSedInflow(ChannelData.streams);
      InitChannelSedInflow(ChannelData.roads);
	}
    
    RouteSubSurface(Time.Dt, &Map, TopoMap, VType, VegMap, Network,
		    SType, SoilMap, &ChannelData, &Time, &Options, Dump.Path,
		    SedMap, FineMap, SedType, MaxStreamID, SnowMap);

    if (Options.HasNetwork)
      RouteChannel(&ChannelData, &Time, &Map, TopoMap, SoilMap, &Total, 
		   &Options, Network, SType, PrecipMap, SedMap,
		   LocalMet.Tair, LocalMet.Rh, SedDiams);

    /* Sediment Routing in Channel and output to sediment files */
    if ((Options.HasNetwork) && (Options.Sediment)){
      SPrintDate(&(Time.Current), buffer);
      flag = IsEqualTime(&(Time.Current), &(Time.Start));

      if (Options.ChannelRouting){
	    if (ChannelData.roads != NULL) {
	      RouteChannelSediment(ChannelData.roads, Time, &Dump, &Total, SedDiams);
	      channel_save_sed_outflow_text(buffer, ChannelData.roads,
					ChannelData.sedroadout,
					ChannelData.sedroadflowout, flag);
		  RouteCulvertSediment(&ChannelData, &Map, TopoMap, SedMap, 
			       &Total, SedDiams);
		}
	    RouteChannelSediment(ChannelData.streams, Time, &Dump, &Total, SedDiams);
 	    channel_save_sed_outflow_text(buffer, ChannelData.streams,
				      ChannelData.sedstreamout,
				      ChannelData.sedstreamflowout, flag);
	  }
      else {
	    if (ChannelData.roads != NULL) {
			channel_save_sed_inflow_text(buffer, ChannelData.roads,
			ChannelData.sedroadinflow, SedDiams,flag);
		}
	    channel_save_sed_inflow_text(buffer, ChannelData.streams,
			ChannelData.sedstreaminflow, SedDiams,flag);
      }
      SaveChannelSedInflow(ChannelData.roads, &Total);
      SaveChannelSedInflow(ChannelData.streams, &Total);
    }
    
    if (Options.Extent == BASIN)
      RouteSurface(&Map, &Time, TopoMap, SoilMap, &Options,
		   UnitHydrograph, &HydrographInfo, Hydrograph,
		   &Dump, VegMap, VType, SType, &ChannelData, SedMap,
		   PrecipMap, SedType, LocalMet.Tair, LocalMet.Rh, SedDiams);

#endif

    if (NGraphics > 0)
      draw(&(Time.Current), IsEqualTime(&(Time.Current), &(Time.Start)),
	   Time.DayStep, &Map, NGraphics, which_graphics, VType,
	   SType, SnowMap, SoilMap, SedMap, FineMap, VegMap, TopoMap, PrecipMap,
	   PrismMap, SkyViewMap, ShadowMap, EvapMap, RadMap, MetMap, Network,
	   &Options);
    
    Aggregate(&Map, &Options, TopoMap, &Soil, &Veg, VegMap, EvapMap, PrecipMap,
	      RadMap, SnowMap, SoilMap, &Total, VType, Network, SedMap, FineMap,
	      &ChannelData, &roadarea);
    
    MassBalance(&(Time.Current), &(Dump.Balance), &(Dump.SedBalance), &Total, 
		&Mass, &Options);

    ExecDump(&Map, &(Time.Current), &(Time.Start), &Options, &Dump, TopoMap,
	     EvapMap, RadiationMap, PrecipMap, RadMap, SnowMap, MetMap, VegMap, &Veg, 
		 SoilMap, SedMap, Network, &ChannelData, FineMap, &Soil, &Total, 
		 &HydrographInfo,Hydrograph);
	
    IncreaseTime(&Time);
	t += 1;
  }

  ExecDump(&Map, &(Time.Current), &(Time.Start), &Options, &Dump, TopoMap,
	   EvapMap, RadiationMap, PrecipMap, RadMap, SnowMap, MetMap, VegMap, &Veg, SoilMap,
	   SedMap, Network, &ChannelData, FineMap, &Soil, &Total, &HydrographInfo, Hydrograph);

  FinalMassBalance(&(Dump.FinalBalance), &Total, &Mass, &Options, roadarea);

  /*printf("\nSTARTING CLEANUP\n\n");
  cleanup(&Dump, &ChannelData, &Options);*/
  printf("\nEND OF MODEL RUN\n\n");

  /* record the run time at the end of each time loop */
  finish1 = clock ();
  runtime = (finish1-start)/CLOCKS_PER_SEC;
  printf("***********************************************************************************");
  printf("\nRuntime Summary:\n");
  printf("%6.2f hours elapsed for the simulation period of %d hours (%.1f days) \n", 
	  runtime/3600, t*Time.Dt/3600, (float)t*Time.Dt/3600/24);

  return EXIT_SUCCESS;
}
示例#11
0
static int
auth (void) {
    lfm_update_auth ();
    if (lfm_sess[0]) {
        return 0;
    }
    if (!lfm_user[0] || !lfm_pass[0]) {
        return -1;
    }
    char req[4096];
    time_t timestamp = time(NULL);
    uint8_t sig[16];
    char passmd5[33];
    char token[100];
    deadbeef->md5 (sig, lfm_pass, strlen (lfm_pass));
    deadbeef->md5_to_str (passmd5, sig);
    snprintf (token, sizeof (token), "%s%d", passmd5, (int)timestamp);
    deadbeef->md5 (sig, token, strlen (token));
    deadbeef->md5_to_str (token, sig);

    deadbeef->conf_lock ();
    const char *scrobbler_url = deadbeef->conf_get_str_fast ("lastfm.scrobbler_url", SCROBBLER_URL_LFM);
#if LFM_TESTMODE
    snprintf (req, sizeof (req), "%s/?hs=true&p=1.2.1&c=tst&v=1.0&u=%s&t=%d&a=%s", scrobbler_url, lfm_user, (int)timestamp, token);
#else
    snprintf (req, sizeof (req), "%s/?hs=true&p=1.2.1&c=%s&v=%d.%d&u=%s&t=%d&a=%s", scrobbler_url, LFM_CLIENTID, plugin.plugin.version_major, plugin.plugin.version_minor, lfm_user, (int)timestamp, token);
#endif
    deadbeef->conf_unlock ();
    // handshake
    int status = curl_req_send (req, NULL);
    if (!status) {
        // check status and extract session id, nowplaying url, submission url
        if (strncmp (lfm_reply, "OK", 2)) {
            uint8_t *p = lfm_reply;
            while (*p && *p >= 0x20) {
                p++;
            }
            *p = 0;
            trace ("scrobbler auth failed, response: %s\n", lfm_reply);
            goto fail;
        }
        uint8_t *p = lfm_reply + 2;
        // skip whitespace
        while (*p && *p < 0x20) {
            p++;
        }
        // get session
        if (!*p) {
            trace ("unrecognized scrobbler reply:\n%s\n", lfm_reply);
            goto fail;
        }
        uint8_t *end = p+1;
        while (*end && *end >= 0x20) {
            end++;
        }
        if (end-p > 32) {
            trace ("scrobbler session id is invalid length. probably plugin needs fixing.\n");
            goto fail;
        }
        strncpy (lfm_sess, p, 32);
        lfm_sess[32] = 0;
        trace ("obtained scrobbler session: %s\n", lfm_sess);
        p = end;
        // skip whitespace
        while (*p && *p < 0x20) {
            p++;
        }
        // get nowplaying url
        if (!*p) {
            trace ("unrecognized scrobbler reply:\n%s\n", lfm_reply);
            goto fail;
        }
        end = p+1;
        while (*end && *end >= 0x20) {
            end++;
        }
        if (end - p > sizeof (lfm_nowplaying_url)-1) {
            trace ("scrobbler nowplaying url is too long %d:\n", (int)(end-p));
            goto fail;
        }
        strncpy (lfm_nowplaying_url, p, end-p);
        lfm_nowplaying_url[end-p] = 0;
        trace ("obtained scrobbler nowplaying url: %s\n", lfm_nowplaying_url);
        p = end;
        // skip whitespace
        while (*p && *p < 0x20) {
            p++;
        }
        // get submission url
        if (!*p) {
            trace ("unrecognized scrobbler reply:\n%s\n", lfm_reply);
            goto fail;
        }
        end = p+1;
        while (*end && *end >= 0x20) {
            end++;
        }
        if (end - p > sizeof (lfm_submission_url)-1) {
            trace ("scrobbler submission url is too long: %d\n", (int)(end-p));
            goto fail;
        }
        strncpy (lfm_submission_url, p, end-p);
        lfm_submission_url[end-p] = 0;
        trace ("obtained scrobbler submission url: %s\n", lfm_submission_url);
        p = end;
    }
    else {
        // send failed, but that doesn't mean session is invalid
        curl_req_cleanup ();
        return -1;
    }

    curl_req_cleanup ();
    return 0;
fail:
    lfm_sess[0] = 0;
    curl_req_cleanup ();
    return -1;
}
void go(SGLVData *data, int nbiter){
	int i;
	mpz_t  k_rd, ZZ, tmp;
	mpz_inits (k_rd, ZZ, tmp, NULL);
	
	gmp_randstate_t rand_gen;
	unsigned long seed = time(NULL); 
	gmp_randinit_default(rand_gen);
	gmp_randseed_ui(rand_gen, seed);
	
	
	SGLVScalar k;
	JacPoint jp;
	
	struct timespec start1,start2;
    struct timespec end1,end2;
    uint64_t diff1,diff2, diff3;
	
	
	printf("\nSGLV 256 bits benchmark, running...\n\n");
	
	
	diff1 = 0;
	diff2 = 0;
	
	init_jacPoint(&jp);
	
	
	
	for (i = 0; i < nbiter; i++) {
		
		mpz_urandomb (k_rd, rand_gen, BIT_SIZE);
		mpz_mod (k_rd, k_rd,  data->efp);
		
		
		apply_endo(((data->PP)+1), (data->PP), beta); /* Point PHI_P */
		add_aff_aff(((data->PP)+1), (data->PP));      /* Point P+PHI_P */
		
		
		clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start1);
		
		init_glvScalar(&k);
		build_glvScalar(&k, k_rd, data->aa, data->bb, data->Na);
		
		clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &end1);
		diff1 += BILLION * (end1.tv_sec - start1.tv_sec) + end1.tv_nsec - start1.tv_nsec; 
		
		clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start1);
		
		point_from_SGLVScalar(&jp, &k, data->PP);
		
		clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &end1);
		diff2 += BILLION * (end1.tv_sec - start1.tv_sec) + end1.tv_nsec - start1.tv_nsec; 
		
		mpz_invert (ZZ, jp.Z, p);
		mpz_mul (tmp, ZZ, ZZ); // tmp = ZZ^2
		//~ P is transformed in affine coordinates for next iteration
		mpz_mul (data->PP[0].X, jp.X, tmp);
		mpz_mod (data->PP[0].X, data->PP[0].X, p);
		
		mpz_mul (data->PP[0].Y, jp.Y, tmp);
		mpz_mul (data->PP[0].Y, data->PP[0].Y, ZZ);
		mpz_mod (data->PP[0].Y, data->PP[0].Y, p);
	}
	diff3 = diff1 + diff2;
	
	
	if (is_on_curve_jac(&jp, ca, cb)){ 
		printf("\nMULT: kP OK\n");
		print_jacPoint(&jp);
		printf("Elapsed time = %llu %llu %llu nanoseconds\n", (long long unsigned int) diff1, (long long unsigned int) diff2, (long long unsigned int) diff3);
	}
	else
		printf("MULT: kP non OK\n");
	
	
	mpz_clears (k_rd, ZZ, tmp, NULL);
	free_jacPoint(&jp);
	gmp_randclear(rand_gen);
}
示例#13
0
/**
 * Does a source file.
 *
 * @param filename_in  the file to read
 * @param filename_out NULL (stdout) or the file to write
 * @param parsed_file  NULL or the filename for the parsed debug info
 * @param no_backup    don't create a backup, if filename_out == filename_in
 * @param keep_mtime   don't change the mtime (dangerous)
 */
static void do_source_file(const char *filename_in,
                           const char *filename_out,
                           const char *parsed_file,
                           bool       no_backup,
                           bool       keep_mtime)
{
   FILE     *pfout;
   bool     did_open    = false;
   bool     need_backup = false;
   file_mem fm;
   string   filename_tmp;

   /* Do some simple language detection based on the filename extension */
   if (!cpd.lang_forced || (cpd.lang_flags == 0))
   {
      cpd.lang_flags = language_from_filename(filename_in);
   }

   /* Try to read in the source file */
   if (load_mem_file(filename_in, fm) < 0)
   {
      LOG_FMT(LERR, "Failed to load (%s)\n", filename_in);
      cpd.error_count++;
      return;
   }

   LOG_FMT(LSYS, "Parsing: %s as language %s\n",
           filename_in, language_to_string(cpd.lang_flags));

   if (filename_out == NULL)
   {
      pfout = stdout;
   }
   else
   {
      /* If the out file is the same as the in file, then use a temp file */
      filename_tmp = filename_out;
      if (strcmp(filename_in, filename_out) == 0)
      {
         /* Create 'outfile.uncrustify' */
         filename_tmp = fix_filename(filename_out);

         if (!no_backup)
         {
            if (backup_copy_file(filename_in, fm.raw) != SUCCESS)
            {
               LOG_FMT(LERR, "%s: Failed to create backup file for %s\n",
                       __func__, filename_in);
               cpd.error_count++;
               return;
            }
            need_backup = true;
         }
      }
      make_folders(filename_tmp);

      pfout = fopen(filename_tmp.c_str(), "wb");
      if (pfout == NULL)
      {
         LOG_FMT(LERR, "%s: Unable to create %s: %s (%d)\n",
                 __func__, filename_tmp.c_str(), strerror(errno), errno);
         cpd.error_count++;
         return;
      }
      did_open = true;
      //LOG_FMT(LSYS, "Output file %s\n", filename_out);
   }

   cpd.filename = filename_in;
   uncrustify_file(fm, pfout, parsed_file);

   if (did_open)
   {
      fclose(pfout);

      if (need_backup)
      {
         backup_create_md5_file(filename_in);
      }

      if (filename_tmp != filename_out)
      {
         /* We need to compare and then do a rename */
         if (file_content_matches(filename_tmp, filename_out))
         {
            /* No change - remove tmp file */
            (void)unlink(filename_tmp.c_str());
         }
         else
         {
#ifdef WIN32

            /* windows can't rename a file if the target exists, so delete it
             * first. This may cause data loss if the tmp file gets deleted
             * or can't be renamed.
             */
            (void)unlink(filename_out);
#endif
            /* Change - rename filename_tmp to filename_out */
            if (rename(filename_tmp.c_str(), filename_out) != 0)
            {
               LOG_FMT(LERR, "%s: Unable to rename '%s' to '%s'\n",
                       __func__, filename_tmp.c_str(), filename_out);
               cpd.error_count++;
            }
         }
      }

#ifdef HAVE_UTIME_H
      if (keep_mtime)
      {
         /* update mtime -- don't care if it fails */
         fm.utb.actime = time(NULL);
         (void)utime(filename_in, &fm.utb);
      }
#endif
   }
}
int
main_program(int num_messages, int num_channels, int num_connections, const char *server_hostname, int server_port, int timeout)
{
    struct sockaddr_in server_address;
    int main_sd = -1, num_events = 0, i, event_mask, channels_per_connection, num, start_time = 0, iters_to_next_summary = 0;
    Connection *connections = NULL, *connection;
    Statistics stats = {0,0,0,0,0};
    int exitcode = EXIT_SUCCESS;
    struct epoll_event events[MAX_EVENTS];
    char buffer[BIG_BUFFER_SIZE];

    info("Publisher starting up\n");
    info("Publish: %d messages to %d channels on server: %s:%d\n", num_messages, num_channels, server_hostname, server_port);

    if ((fill_server_address(server_hostname, server_port, &server_address)) != 0) {
        error2("ERROR host name not found\n");
    }

    if ((main_sd = epoll_create(200 /* this size is not used on Linux kernel 2.6.8+ */)) < 0) {
        error3("Failed %d creating main epoll socket\n", errno);
    }

    if ((connections = init_connections(num_connections, &server_address, main_sd)) == NULL) {
        error2("Failed to create to connections\n");
    }

    stats.requested_connections = num_connections;

    channels_per_connection = num_channels / num_connections;
    for (i = 0; i < num_connections; i++) {
        num = i * channels_per_connection;
        connections[i].channel_start = num;
        num += channels_per_connection - 1;
        connections[i].channel_end = ((num > num_channels) || (i == (num_connections - 1))) ? num_channels - 1 : num;
    }

    // infinite loop
    debug("Entering Infinite Loop\n");

    iters_to_next_summary = ITERATIONS_TILL_SUMMARY_PER_TIMEOUT/timeout;

    for(;;) {
        if ((num_events = epoll_wait(main_sd, events, MAX_EVENTS, timeout)) < 0) {
            error3("epoll_wait failed\n");
        }

        for (i = 0; i < num_events; i++) {
            event_mask = events[i].events;
            connection = (Connection *)(events[i].data.ptr);

            if ((connection->message_count >= num_messages) && (connection->channel_id > connection->channel_end)) {
                // remove write flag from event
                if (change_connection(connection, EPOLLIN | EPOLLHUP) < 0) {
                    error2("Failed creating socket for connection = %d\n", connection->index);
                }

                if (event_mask & EPOLLOUT) { // WRITE
                    continue;
                }
            }

            if (event_mask & EPOLLHUP) { // SERVER HUNG UP
                debug("EPOLLHUP\n");
                info("Server hung up on conncetion %d. Reconecting...\n", connection->index);
                sleep(1);
                reopen_connection(connection);

                continue;
            }

            if (event_mask & EPOLLERR) {
                debug("EPOLLERR\n");
                info("Server returned an error on connection %d. Reconecting...\n", connection->index);
                reopen_connection(connection);

                continue;
            }

            if (event_mask & EPOLLIN) { // READ
                debug("----------READ AVAILABLE-------\n");

                if (connection->state == CONNECTED) {
                    read_response(connection, &stats, buffer, BIG_BUFFER_SIZE);
                }
            }

            if (event_mask & EPOLLOUT) { // WRITE
                debug("----------WRITE AVAILABLE-------\n");

                if (start_time == 0) {
                    start_time = time(NULL);
                }

                if (connection->state == CONNECTING) {
                    connection->state = CONNECTED;
                    stats.connections++;
                    debug("Connection opened for index=%d\n", connection->index);
                }

                write_message(connection, &stats);
            }
        }

        if (iters_to_next_summary-- <= 0) {
            iters_to_next_summary = ITERATIONS_TILL_SUMMARY_PER_TIMEOUT/timeout;
            summary("Connections=%ld, Messages=%ld BytesWritten=%ld Msg/Sec=%0.2f\n", stats.connections, stats.messages, stats.bytes_written, calc_message_per_second(stats.messages, start_time));
        }

        if (stats.messages >= (num_channels * num_messages)) {
            summary("Connections=%ld, Messages=%ld BytesWritten=%ld Msg/Sec=%0.2f\n", stats.connections, stats.messages, stats.bytes_written, calc_message_per_second(stats.messages, start_time));
            for (i = 0; i < num_connections; i++) {
                close_connection(&connections[i]);
                stats.connections--;
            }
            exitcode = EXIT_SUCCESS;
            goto exit;
        }
    }


exit:
    if (connections != NULL) free(connections);

    return exitcode;
}
示例#15
0
static void feedAppendOnlyFile(struct redisCommand *cmd, int dictid, robj **argv, int argc) {
    sds buf = sdsempty();
    int j;
    ssize_t nwritten;
    time_t now;
    robj *tmpargv[3];

    /* The DB this command was targetting is not the same as the last command
     * we appendend. To issue a SELECT command is needed. */
    if (dictid != server.appendseldb) {
        char seldb[64];

        snprintf(seldb,sizeof(seldb),"%d",dictid);
        buf = sdscatprintf(buf,"*2\r\n$6\r\nSELECT\r\n$%lu\r\n%s\r\n",
            (unsigned long)strlen(seldb), seldb);
        server.appendseldb = dictid;
    }

    /* "Fix" the argv vector if the command is EXPIRE. We want to translate
     * EXPIREs into EXPIREATs calls */
    if (cmd->proc == expireCommand) {
        long when;

        tmpargv[0] = createStringObject("EXPIREAT",8);
        tmpargv[1] = argv[1];
        incrRefCount(argv[1]);
        when = time(NULL)+strtol(argv[2]->ptr,NULL,10);
        tmpargv[2] = createObject(REDIS_STRING,
            sdscatprintf(sdsempty(),"%ld",when));
        argv = tmpargv;
    }

    /* Append the actual command */
    buf = sdscatprintf(buf,"*%d\r\n",argc);
    for (j = 0; j < argc; j++) {
        robj *o = argv[j];

        o = getDecodedObject(o);
        buf = sdscatprintf(buf,"$%lu\r\n",(unsigned long)sdslen(o->ptr));
        buf = sdscatlen(buf,o->ptr,sdslen(o->ptr));
        buf = sdscatlen(buf,"\r\n",2);
        decrRefCount(o);
    }

    /* Free the objects from the modified argv for EXPIREAT */
    if (cmd->proc == expireCommand) {
        for (j = 0; j < 3; j++)
            decrRefCount(argv[j]);
    }

    /* We want to perform a single write. This should be guaranteed atomic
     * at least if the filesystem we are writing is a real physical one.
     * While this will save us against the server being killed I don't think
     * there is much to do about the whole server stopping for power problems
     * or alike */
     nwritten = write(server.appendfd,buf,sdslen(buf));

    /* If a background append only file rewriting is in progress we want to
     * accumulate the differences between the child DB and the current one
     * in a buffer, so that when the child process will do its work we
     * can append the differences to the new append only file. */
    if (server.bgrewritechildpid != -1)
        server.bgrewritebuf = sdscatlen(server.bgrewritebuf,buf,sdslen(buf));

    sdsfree(buf);
    now = time(NULL);
    if (server.appendfsync == APPENDFSYNC_ALWAYS ||
        (server.appendfsync == APPENDFSYNC_EVERYSEC &&
         now-server.lastfsync > 1))
    {
        fsync(server.appendfd); /* Let's try to get this data on the disk */
        server.lastfsync = now;
    }
}
示例#16
0
void perform_http(char *request, char *response, char *directory){
	/* variable declaration: */
	char http_code[4]; // holds the http code as a char array
	FILE *fp; // file pointer for the requested file
	char status[100]; // status of the http code
	char method[20]; // the method in the http request
	char location[200]; // the location of the file requested
	char temp_directory[MAX_STR_LEN] = {0}; //to hold the full directory of the desired file
	char http_version[10]; // the version of http being used
	char *token; // a pointer to tokenize the request
	char time_str[100]; // a char array to hold the current time in a specific format
	char *file_buf; // a char array to hold the contents of the requested file
	time_t cur_time; // gets and holds the current time
	
	/* tokenize the request to get "method", "location" and "http_version" */
	token = strtok(request, " ");
	strncpy(method, token, 20);
	
	token = strtok(NULL, " ");
	strncpy(location, token, 200);
	
	token = strtok(NULL, " ");
	strncpy(http_version, strtok(token, "\r"), 10);
	
	/* the location parsed is actually the full uri sent by the client,
	*  must get the actual location of the requested file from the end of the uri
	*/
	token = strtok(location, "/");
	// check if the first part of the uri is "http:" 
	if(strncmp(token, "http:", 5)==0){
		token = strtok(NULL, "/");
	}
	// get the next part of the uri (hostname)
	token = strtok(NULL, "\0");
	/* append a forward slash to "temp_directory"
	*  and then append the location of the requested file */
	strncpy(temp_directory, directory, strlen(directory));
	strncat(temp_directory, "/", 2);
	strncat(temp_directory, token, 200);
	
	//attempt to topen the requested file in the specified location
	fp = fopen(temp_directory, "r");

	// if the porgram fails to open the file, assing http code "404"
	if(fp == NULL)
	{
		strncpy(http_code, "404", 4);
		strncpy(status, "File not found", 15);
	}else
	{//otherwise assign code "200"
		strncpy(http_code, "200", 4);
		strncpy(status, "OK", 3);
	}
	if(strncmp(method, "GET", 4) != 0)
	{//check if the method in the request is implemented in this program
		// if it is not, assign http code "501"
		strncpy(http_code, "501", 4);
		strncpy(status, "Not implemented", 16);
		fp = NULL;
	}
	
	// if the file was successfully opened, read it
	if(fp != NULL)
	{
		if((file_buf = read_file(fp, file_buf)) == NULL)
		{
			// if the file is unreadable, assign http code 404
			strncpy(http_code, "404", 4);
			strncpy(status, "File not found", 15);
		}
		// close the file after reading
		fclose(fp);
	}
	
	// get the current time
	cur_time = time(0);
	// format it for ease of reading
	strftime(time_str, 100, "%a %d, %b %Y %T PST", localtime(&cur_time));
	
	/* start to construct the response with 
	*  information about the request,
	*  the date, and the server being used
	*/
	strncat(response, "---Response Header---\n", 22);
	strncat(response, http_version, strlen(http_version));
	strncat(response, " ", 2);
	strncat(response, http_code, 4);
	strncat(response, " ", 2);
	strncat(response, status, strlen(status));
	strncat(response, "\nDate: ", 8);
	strncat(response, time_str, strlen(time_str));
	strncat(response, "\nServer: Apache/2.2.31 (Unix) mod_jk/1.2.40\n\n", 45);
	
	// if the file was successfully read, concatenate it to the response
	strncat(response, "---Response Body---\n", 21);
	if(fp != NULL)
	{
		strncat(response, file_buf, strlen(file_buf));
	}
	
}
示例#17
0
/* Initialization of neurons parameters */
int initialization(neuron **nrn, int numNeurons, int simTime)
{
    int i, j, idj, size=0;
    char *fname;
    double tmp;
    FILE *fp, *fq;

    srand (time(NULL));
        
    for(i = 0; i < numNeurons; ++i){
        (*nrn)[i].numPreSyn = 0;
        (*nrn)[i].E = 0.0;
        for(j = 0; j < simTime; ++j){
            (*nrn)[i].V[j] = randm(0.01, 0.1);
            (*nrn)[i].Z[j] = randm(0.01, 0.05);
            (*nrn)[i].S[j] = randm(0.01, 0.05);
            (*nrn)[i].N[j] = randm(0.01, 0.05);
        }
    }

    if(!(fp = fopen("stimuli.dat", "r"))){
        fname = "stimuli.dat";
        goto fail;
    }

    for(i = 0; i < numNeurons; ++i){
        for(j = 0; j < simTime; ++j){
            fscanf(fp, "%lf", &(*nrn)[i].Iext[j]);
        }
    }
    
    fclose(fp);

    if(!(fq = fopen("synapses.dat", "r"))){
        fname = "synapses.dat";
        goto fail;
    }

    for(i = 0; i < numNeurons; ++i){
        idj = 0;
        for(j = 0; j < numNeurons; ++j){
            fscanf(fp, "%lf", &tmp);
            if (tmp != 0){
                if (j == 0){
                    (*nrn)[i].W[0] = tmp;
                    (*nrn)[i].pre_id[0] = j;
                }else{
                    size++;
                    (*nrn)[i].W = (double *)realloc((*nrn)[i].W, size*sizeof(double));
                    (*nrn)[i].W[idj] = tmp;

                    (*nrn)[i].pre_id = (int *)realloc((*nrn)[i].pre_id,
                                size*sizeof(int));
                    (*nrn)[i].pre_id[idj] = j;
                    idj++;
                }
                (*nrn)[i].numPreSyn++;
            }
        }
    }

    fclose(fp);

    return 0;

fail:
    printf("File %s cannot be opened!\n", fname);
    exit(-1);
}
示例#18
0
int main( int argc, char** argv )
{
	unsigned int tickDelta;
	unsigned int currTicks;
	unsigned int physicsTickAcc;
	int numPhysicsProcesses;
	float renderDelta;

#ifdef _DEBUG
	SDL_LogSetAllPriority( SDL_LOG_PRIORITY_VERBOSE );
#else
	SDL_LogSetAllPriority( SDL_LOG_PRIORITY_WARN );
#endif

	SDL_LogSetAllPriority( SDL_LOG_PRIORITY_VERBOSE );

	if( initEverything( ) < 0 ) {
		return 1;
	}

	srand( (unsigned int)time( NULL ) );

	/* main loop */
	running = 1;
	lastTicks = SDL_GetTicks( );
	physicsTickAcc = 0;

	gsmEnterState( &globalFSM, &titleScreenState );

	while( running ) {

		if( !focused ) {
			processEvents( 1 );
			continue;
		}

		currTicks = SDL_GetTicks( );
		tickDelta = currTicks - lastTicks;
		lastTicks = currTicks;

		physicsTickAcc += tickDelta;

		/* process input */
		processEvents( 0 );
		sys_Process( );
		gsmProcess( &globalFSM );

		/* process movement and collision */
		numPhysicsProcesses = 0;
		while( physicsTickAcc > PHYSICS_TICK ) {
			sys_PhysicsTick( PHYSICS_DELTA );
			gsmPhysicsTick( &globalFSM, PHYSICS_DELTA );
			physicsTickAcc -= PHYSICS_TICK;
			++numPhysicsProcesses;
		}

		/* rendering */
		if( numPhysicsProcesses > 0 ) {
			/* set the new render positions */
			renderDelta = PHYSICS_DELTA * (float)numPhysicsProcesses;
			gfx_ClearDrawCommands( renderDelta );
			cam_FinalizeStates( renderDelta );

			/* render all the things */
			sys_Draw( );
			gsmDraw( &globalFSM );
		}

		float dt = (float)tickDelta / 1000.0f;
		cam_Update( dt );
		gfx_Render( dt );
		// flip here so we don't have to store the window anywhere else
		SDL_GL_SwapWindow( window );
	}

	return 0;
}
示例#19
0
int32
yahoo_io_thread( void * _data )
{
	YahooConnection * conn = (YahooConnection*)_data;
	
/*	conn->fID = yahoo_init_with_attributes(
		conn->fYahooID, conn->fPassword,
		//"local_host", local_host,
		"pager_port", 23,
		NULL
	);
*/	
	conn->fID = yahoo_init(
		conn->fYahooID, conn->fPassword
	);
	
	LOG(kProtocolName, liDebug, "yahoo_io_thread: id: %s, pass: %s", conn->fYahooID, conn->fPassword );
	
	gYahooConnections[conn->fID] = conn;
	
	yahoo_login( conn->fID, YAHOO_STATUS_AVAILABLE );

	int lfd=0;
	
	fd_set inp, outp;
	struct timeval tv;
	
	LOG(kProtocolName, liDebug, "yahoo_io_thread: Starting loop");
	
	while( conn->IsAlive() ) {
		FD_ZERO(&inp);
		FD_ZERO(&outp);
		tv.tv_sec=1;
		tv.tv_usec=0;
		lfd=0;
		
		for(int i=0; i<conn->CountConnections(); i++) {
			struct fd_conn *c = conn->ConnectionAt(i);
			
			if(c->remove) {
//				LOG(kProtocolName, liDebug, "yahoo_io_thread: Removing id:%d fd:%d", c->id, c->fd);
				conn->RemoveConnection(c);
				free(c);
			} else {
				if(c->cond & YAHOO_INPUT_READ) {
					FD_SET(c->fd, &inp);
				}
				if(c->cond & YAHOO_INPUT_WRITE) {
					FD_SET(c->fd, &outp);
				}
				if(lfd < c->fd)
					lfd = c->fd;
			}
		}
		
		select(lfd + 1, &inp, &outp, NULL, &tv);
		time(&curTime);
		
		for(int i=0; i<conn->CountConnections(); i++) {
			struct fd_conn *c = conn->ConnectionAt(i);
			if(c->remove)
				continue;
			if(FD_ISSET(c->fd, &inp)) {
//				LOG(kProtocolName, liDebug, "yahoo_io_thread: data to read");
				yahoo_callback(c, YAHOO_INPUT_READ);
				FD_CLR(c->fd, &inp);
			}
			if(FD_ISSET(c->fd, &outp)) {
				//LOG(kProtocolName, liDebug, "yahoo_io_thread: data to write");
				yahoo_callback(c, YAHOO_INPUT_WRITE);
				FD_CLR(c->fd, &outp);
			}
		}
		
		if(expired(pingTimer))
			yahoo_ping_timeout_callback(conn->fID, pingTimer);
	}
	LOG(kProtocolName, liDebug, "yahoo_io_thread: Exited loop");
	
	while( conn->CountConnections() > 0 ) {
		struct fd_conn * c = conn->ConnectionAt(0);
		conn->RemoveConnection(c);
		close(c->fd);
		FREE(c);
	}
	
	return 0;
}
示例#20
0
		Packet(Ip::Endpoint e, udp::Header h): header(h), parts(h.totalParts), created(time(0)), validParts(0), endpoint(e) {}
示例#21
0
文件: timer.c 项目: jasonblog/note
static void repeate_cb (EV_P_ ev_timer *w, int revents)
{
    printf("repeate at %ju\n", (uintmax_t)time(NULL));
}
示例#22
0
void TinMan::Run()
{
	FMOD::Sound * primarySound = GetRandomSound();
	FMOD::Channel * primaryChannel;
	result = system->playSound(FMOD_CHANNEL_FREE, primarySound, true, &primaryChannel);
	ERRCHECK();
	primaryChannel->setVolume(0.f);
	primaryChannel->setPaused(false);

	FMOD::Sound * secondarySound = 0;
	FMOD::Channel * secondaryChannel = 0;

	const unsigned int crossfadeTime = 2500;

	time_t voiceStartTime = time(0) + 10 + (rand() % 20);

	while(true)
	{
		system->update();

		bool isPlaying = false;
		result = primaryChannel->isPlaying(&isPlaying);
		if ((result != FMOD_OK) && (result != FMOD_ERR_INVALID_HANDLE) && (result != FMOD_ERR_CHANNEL_STOLEN))
		{
				ERRCHECK();
		}

		if(isPlaying)
		{
			unsigned int primaryPos = 0;
			unsigned int primaryLen = 0;

			result = primaryChannel->getPosition(&primaryPos, FMOD_TIMEUNIT_MS);
			if ((result != FMOD_OK) && (result != FMOD_ERR_INVALID_HANDLE) && (result != FMOD_ERR_CHANNEL_STOLEN))
			{
					ERRCHECK();
			}

			result = primarySound->getLength(&primaryLen, FMOD_TIMEUNIT_MS);
			ERRCHECK();

			float volume = 1.f;
			if(primaryPos < crossfadeTime)
			{
				volume = std::max(0.f, std::min((float)(primaryPos)/(float)crossfadeTime, 1.f));
			}
			else if(primaryPos > primaryLen - crossfadeTime)
			{
				volume = std::max(0.f, std::min((float)(primaryLen - primaryPos)/(float)crossfadeTime, 1.f));
			}

			//std::cout<<std::time(0)<<" "<<voiceStartTime<<" "<<primaryPos<<"/"<<primaryLen<<" "<<volume<<"\n";

			result = primaryChannel->setVolume(volume);
			if ((result != FMOD_OK) && (result != FMOD_ERR_INVALID_HANDLE) && (result != FMOD_ERR_CHANNEL_STOLEN))
			{
					ERRCHECK();
			}

			if(primaryPos > primaryLen - crossfadeTime)
			{
				if(!secondaryChannel)
				{
					secondarySound = GetRandomSound();
					result = system->playSound(FMOD_CHANNEL_FREE, secondarySound, true, &secondaryChannel);
					ERRCHECK();
					result = secondaryChannel->setVolume(1.f - volume);
					ERRCHECK();
					result = secondaryChannel->setPaused(false);
					ERRCHECK();
				}
				else
				{
					secondaryChannel->setVolume(1.f - volume);
					if ((result != FMOD_OK) && (result != FMOD_ERR_INVALID_HANDLE) && (result != FMOD_ERR_CHANNEL_STOLEN))
					{
							ERRCHECK();
					}
				}
			}
		}
		else
		{
			if(secondaryChannel && secondarySound)
			{
				primaryChannel = secondaryChannel;
				primarySound = secondarySound;
				secondaryChannel = 0;
			}
			else
			{
				// for some reason all channels are stopped
				primarySound = GetRandomSound();
				result = system->playSound(FMOD_CHANNEL_FREE, primarySound, 0, &primaryChannel);
				ERRCHECK();
			}
		}

		if(time(0) >= voiceStartTime)
		{
			voiceStartTime = time(0) + 15 + (rand() % 25);
			PlayVoice();
		}

		boost::this_thread::sleep(boost::posix_time::milliseconds(10));
	}
}
示例#23
0
void rm_test_0(ull r, ull m, int k, int max_iter, FILE *fout) {
	ull wordsize = 0, dim = 0, gen_size = 0;
	unsigned char *G = NULL, *D = NULL, *DD = NULL, *C = NULL, *NC = NULL;
	unsigned short *masks = NULL, width = 0;
	ull accumulator = 0, n = 0;

	ull data_block_size_bytes = 0;
	ull code_block_size_bytes = 0;

	dim = rm_dim(r, m);
	wordsize = rm_wordsize(r, m);
	width = rm_codeword_size_in_bytes(r, m);

	gen_size = gen_matrix_mem_size(m, m);
	G = (unsigned char *) malloc(gen_size);
	generate_matrix(m, m, G);
	
	//print(dim, 8 * width, G);printf("\n");

	masks = (unsigned short *) malloc(wordsize * sizeof(unsigned short));
	generate_masks(m, masks);

	data_block_size_bytes = rm_dataword_size_in_bytes(r, m);
	code_block_size_bytes = rm_codeword_size_in_bytes(r, m);

	D =	(unsigned char *) malloc(data_block_size_bytes);
	DD = (unsigned char *) malloc(data_block_size_bytes);

	for (int i = 0; i < data_block_size_bytes; ++i)
		D[i] = (unsigned char) rand();

	C = (unsigned char *) malloc(code_block_size_bytes);
	NC = (unsigned char *) malloc(code_block_size_bytes);

	encode_block(r, m, dim, wordsize, C, D, masks, G);
	//printf("Data:\n");print(1, dim, D);printf("\n");
	
	memcpy(NC, C, width);
	// print(1, wordsize, C);printf("\n");
	// decode_block(r, m, dim, wordsize, NC, DD, masks, G, width);
	// print(1, dim, DD);
	srand (time(NULL));
	
	n = 2 * k / 3 + 1;
	fprintf(fout, "%lld\n", n);
	for (ull i = 0; i < n; i++) {
		accumulator = 0;
		fprintf(fout, "%1.9lf ", (double) i / (double) k);

		for (ull j = 0; j < max_iter; ++j) {
			memcpy(NC, C, code_block_size_bytes);
	
			add_noise(NC, code_block_size_bytes, (double) i / (double) k);				
			decode_block(r, m, dim, wordsize, NC, DD, masks, G, width);
			accumulator += match(data_block_size_bytes, 0, dim, D, DD);
		}

		fprintf(fout, "%1.9lf\n", (double) accumulator / (double) max_iter);
	}
	FREE_IF_ALLOCATED(C);
	FREE_IF_ALLOCATED(NC);
	FREE_IF_ALLOCATED(D);
	FREE_IF_ALLOCATED(DD);
	FREE_IF_ALLOCATED(masks);
	FREE_IF_ALLOCATED(G);
}
示例#24
0
文件: emu.cpp 项目: ryban/DCPPU16
int main(int argc, char *argv[])
{
    if(argc < 2)
    {
        cerr << "usage: dcpu <flags> <filename>\n";
        return 1;
    }

    bool debug = false;
    int time_to_kill_ms = 0;

    // -d runs in debug mode, prints out memory dump at end

    for(int a = 1; a < argc - 1; a++)
    {
        if(!strcmp(argv[a], "-d"))
        {
            debug = true;
        }else
        {
            cerr << "invalid command <" << argv[a] << ">. ignoring\n";
        }
    }

    ifstream inFile(argv[argc - 1], ios::in);
    if(!inFile.good())
    {
        cerr << "Could not open <" << argv[argc - 1] << ">\n";
        return 1;
    }

    Dcpu cpu(inFile, debug);

    sf::Thread cpu_thread(&start, &cpu);

    sf::RenderWindow app(sf::VideoMode(TERMINAL_WIDTH * 4 * 4, TERMINAL_HEIGHT * 8 * 4), "DCPPU: DCPU-16 Emulator");

    app.SetFramerateLimit(30); // Getting 1500 fps on somthing this simple seems wasteful

    sf::Image font;
    if(!font.LoadFromFile("font.png"))
    {
        cerr << "Could not load font\n";
        return 1;
    }

    unsigned short *buf = cpu.GetScreenBuffer();
    buf += TERMINAL_WIDTH * TERMINAL_HEIGHT;

    // load and encode character set into RAM
    for(int char_off = 0; char_off < 128; char_off++)
    {
        int font_off_x = (char_off * 4) % 128;
        int font_off_y = ((char_off * 4) / 128) * 8;

        unsigned int font_char = 0;
        int x_ = 0;
        int y_ = 0;
        for(int x = font_off_x; x < font_off_x + 4; x++)
        {
            for(int y = font_off_y; y < font_off_y + 8; y++)
            {
                sf::Color pix = font.GetPixel(x, y); 
                if(pix != sf::Color(2, 1, 2))
                    font_char |= 1 << (31-((y_ * 4) + x_));
                y_++;
            }
            x_++;
        }
        unsigned short lowerword = font_char & 0xffff;
        unsigned short upperword = (font_char >> 16) & 0xffff;
        buf[char_off * 2] = upperword;
        buf[char_off * 2 + 1] = lowerword;
    }


    sf::Image screen;
    screen.Create(128, 96); // create black image
    screen.SetSmooth(false);
    sf::Sprite screen_sprite(screen);
    screen_sprite.SetScale(4.0, 4.0);

    cpu_thread.Launch();

    bool running = true;
    while(running)
    {
        sf::Event Event;
        while(app.GetEvent(Event))
        {
            if(Event.Type == sf::Event::Closed)
            {
                cpu.kill();
                running = false;
                app.Close();
            }
            if (Event.Type == sf::Event::TextEntered)
            {
                if (Event.Text.Unicode < 128)
                {
                    char c = static_cast<char>(Event.Text.Unicode);
                    cpu.PushInBuff(c);
                }
            }

        }
        app.Clear();

        unsigned short *buffer = cpu.GetScreenBuffer();

        for(int y = 0; y < TERMINAL_HEIGHT; y++)
        {
            for(int x = 0; x < TERMINAL_WIDTH; x++)
            {
                unsigned short sc = buffer[y * 32 + x];
                int fg_off = (sc >> 12) & 0xf;
                int bg_off = (sc >> 8) & 0xf;
                sf::Color fg = color_table[fg_off];
                sf::Color bg = color_table[bg_off];
                char c = sc & 0x7f;
                bool blink = (sc & 0x80) == 0x80 && (time(0) % 2 == 0); // if bit 15 set, blink on for 1 sec, off for 1 sec

                DrawCharacter(screen, buffer + (TERMINAL_WIDTH*TERMINAL_HEIGHT), c, fg, bg, blink, x, y);
            }
        }

        app.Draw(screen_sprite);
        app.Display();
    }
    
    return 0;
}
示例#25
0
/*
	* autoPlay()
	*
	* Simulates a game of Red Rover and notifies the user of the winning team.
	*
	* Selects a random player from one team to attempt to break through a random player from the other team until one team has won.
	*
	* Starting with Team A, teams take turns attempting to break through.
	*
	* When the function ends, both teams should be emptied.
	*
	* this function returns nothing, but it MUST print out
	* 		the name of the runner
	* 		the name of the defender and
	* 		the players on each team
	* after each attempt to break through.
	*
	* At the end of the game, print out the name of the winning team and the players on both teams.
	*/
void RedRover::autoPlay()
{
    srand(time(0));
    int rand_index_runner = 0, rand_index_defender = 0, i = 0;
    
    PlayerInterface* runner = NULL;
    PlayerInterface* defender = NULL;
    
    bool playing = true;
    if (roster.size() < 4)
    {
        cout << "INSUFFICIENT PLAYERS\n\n";
        return;
    }
    
    createTeams();
    
    //cout << "TEAM A: " << getTeamA() << endl;
    //cout << "TEAM B: " << getTeamB() << endl << endl;
    
    while (playing)
    {
        if (i % 2 == 0)
        {   //cout << "I: " << i << "rand: " << rand() % 6 << endl;
            //team a turn

            rand_index_runner = rand() % getTeamASize(); // grab random player from A as runner
            runner = teamA.at(rand_index_runner);
            
            rand_index_defender = rand() % getTeamBSize(); // grab random player from B As Defender
            defender = teamB.at(rand_index_defender);
            
        }
        else if (i % 2 == 1)
        {
            //team b turn
            rand_index_runner = rand() % getTeamBSize(); // grab random player from B as runner
            runner = teamB.at(rand_index_runner);
            
            rand_index_defender = rand() % getTeamASize(); // grab random player from A As Defender
            defender = teamA.at(rand_index_defender);
        }
        
        cout << "RUNNER: " << runner->getName() << endl;
        cout << "DEFENDER: " << defender->getName() << endl << endl;
        
        sendSomeoneOver(runner, defender);
        
        if (teamA.size() > 1 && teamB.size() > 1)
        {
            cout << "TEAM A: " << getTeamA() << endl;
            cout << "TEAM B: " << getTeamB() << endl << endl;
        }
        else if (teamA.size() == 1 || teamB.size() == 1)
        {
            if (teamA.size() == 1)
            {
                cout << "Team A lost! " << getTeamA() << endl << endl;
            }
            else if (teamB.size() == 1)
            {
                cout << "Team B lost! " << getTeamB() << endl << endl;
            }
            playing = false;
        }
        i++;
    }
    
    teamReset();

}
/*
 * Called when a packet with the opcode XPT_OPC_S_WORKDATA1 is received
 * This is the first version of xpt 'getwork'
 */
bool xptClient_processPacket_blockData1(xptClient_t* xptClient)
{
	// parse block data
	bool recvError = false;
	xptPacketbuffer_beginReadPacket(xptClient->recvBuffer);
	// update work info, GBT style (sha256 & scrypt)
	xptClient->blockWorkInfo.version = xptPacketbuffer_readU32(xptClient->recvBuffer, &recvError);				// version
	xptClient->blockWorkInfo.height = xptPacketbuffer_readU32(xptClient->recvBuffer, &recvError);				// block height
	xptClient->blockWorkInfo.nBits = xptPacketbuffer_readU32(xptClient->recvBuffer, &recvError);				// nBits
	// New in xpt version 6 - Targets are send in compact format (4 bytes instead of 32)
	uint32 targetCompact = xptPacketbuffer_readU32(xptClient->recvBuffer, &recvError);
	uint32 targetShareCompact = xptPacketbuffer_readU32(xptClient->recvBuffer, &recvError);
	xptClient_getDifficultyTargetFromCompact(targetCompact, (uint32*)xptClient->blockWorkInfo.target);
	xptClient_getDifficultyTargetFromCompact(targetShareCompact, (uint32*)xptClient->blockWorkInfo.targetShare);
	xptClient->blockWorkInfo.nTime = xptPacketbuffer_readU32(xptClient->recvBuffer, &recvError);				// nTimestamp
	xptPacketbuffer_readData(xptClient->recvBuffer, xptClient->blockWorkInfo.prevBlockHash, 32, &recvError);	// prevBlockHash
	xptPacketbuffer_readData(xptClient->recvBuffer, xptClient->blockWorkInfo.merkleRoot, 32, &recvError);		// merkleroot
	// coinbase part1 (16bit length + data)
	xptClient->blockWorkInfo.coinBase1Size = xptPacketbuffer_readU16(xptClient->recvBuffer, &recvError);
	xptPacketbuffer_readData(xptClient->recvBuffer, xptClient->blockWorkInfo.coinBase1, xptClient->blockWorkInfo.coinBase1Size, &recvError);
	// coinbase part2 (16bit length + data)
	xptClient->blockWorkInfo.coinBase2Size = xptPacketbuffer_readU16(xptClient->recvBuffer, &recvError);
	xptPacketbuffer_readData(xptClient->recvBuffer, xptClient->blockWorkInfo.coinBase2, xptClient->blockWorkInfo.coinBase2Size, &recvError);
	// information about remaining tx hashes
	xptClient->blockWorkInfo.txHashCount = xptPacketbuffer_readU16(xptClient->recvBuffer, &recvError);
	printf("New block data - height: %d tx count: %d\n", xptClient->blockWorkInfo.height, xptClient->blockWorkInfo.txHashCount);
	for(uint32 i=0; i<xptClient->blockWorkInfo.txHashCount; i++)
	{
		xptPacketbuffer_readData(xptClient->recvBuffer, xptClient->blockWorkInfo.txHashes+(32*i), 32, &recvError);
		// The first hash in xptClient->blockWorkInfo.txHashes is reserved for the coinbase transaction
	}
	xptClient->blockWorkInfo.timeWork = time(NULL);
	xptClient->blockWorkInfo.timeBias = xptClient->blockWorkInfo.nTime - (uint32)time(NULL);
	xptClient->hasWorkData = true;
	// add general block info (primecoin new pow for xpt v4, removed in xpt v5)
	//EnterCriticalSection(&xptClient->cs_workAccess);
	//float earnedShareValue = xptPacketbuffer_readFloat(xptClient->recvBuffer, &recvError);
	//xptClient->earnedShareValue += earnedShareValue;
	//uint32 numWorkBundle = xptPacketbuffer_readU32(xptClient->recvBuffer, &recvError); // how many workBundle blocks we have
	//for(uint32 b=0; b<numWorkBundle; b++)
	//{
	//	// general block info
	//	uint32 blockVersion = xptPacketbuffer_readU32(xptClient->recvBuffer, &recvError);
	//	uint32 blockHeight = xptPacketbuffer_readU32(xptClient->recvBuffer, &recvError);
	//	uint32 blockBits = xptPacketbuffer_readU32(xptClient->recvBuffer, &recvError);
	//	uint32 blockBitsForShare = xptPacketbuffer_readU32(xptClient->recvBuffer, &recvError);
	//	uint32 blockTimestamp = xptPacketbuffer_readU32(xptClient->recvBuffer, &recvError);
	//	uint32 workBundleFlags = xptPacketbuffer_readU8(xptClient->recvBuffer, &recvError);
	//	uint8 prevBlockHash[32];
	//	xptPacketbuffer_readData(xptClient->recvBuffer, prevBlockHash, 32, &recvError);
	//	// server constraints
	//	uint32 fixedPrimorial = xptPacketbuffer_readU32(xptClient->recvBuffer, &recvError);
	//	uint32 fixedHashFactor = xptPacketbuffer_readU32(xptClient->recvBuffer, &recvError);
	//	uint32 sievesizeMin = xptPacketbuffer_readU32(xptClient->recvBuffer, &recvError);
	//	uint32 sievesizeMax = xptPacketbuffer_readU32(xptClient->recvBuffer, &recvError);
	//	uint32 primesToSieveMin = xptPacketbuffer_readU32(xptClient->recvBuffer, &recvError);
	//	uint32 primesToSieveMax = xptPacketbuffer_readU32(xptClient->recvBuffer, &recvError);
	//	uint32 sieveChainLength = xptPacketbuffer_readU8(xptClient->recvBuffer, &recvError);
	//	uint32 nonceMin = xptPacketbuffer_readU32(xptClient->recvBuffer, &recvError);
	//	uint32 nonceMax = xptPacketbuffer_readU32(xptClient->recvBuffer, &recvError);
	//	uint32 numPayload =  xptPacketbuffer_readU32(xptClient->recvBuffer, &recvError);
	//	for(uint32 p=0; p<numPayload; p++)
	//	{
	//		xptBlockWorkInfo_t* blockData = xptClient->blockWorkInfo + xptClient->blockWorkSize;
	//		if( xptClient->blockWorkSize >= 400 )
	//			break;
	//		blockData->version = blockVersion;
	//		blockData->height = blockHeight;
	//		blockData->nBits = blockBits;
	//		blockData->nBitsShare = blockBitsForShare;
	//		blockData->nTime = blockTimestamp;
	//		memcpy(blockData->prevBlockHash, prevBlockHash, 32);
	//		blockData->flags = workBundleFlags;
	//		blockData->fixedPrimorial = fixedPrimorial;
	//		blockData->fixedHashFactor = fixedHashFactor;
	//		blockData->sievesizeMin = sievesizeMin;
	//		blockData->sievesizeMax = sievesizeMax;
	//		blockData->primesToSieveMin = primesToSieveMin;
	//		blockData->primesToSieveMax = primesToSieveMax;
	//		blockData->sieveChainLength = sieveChainLength;
	//		blockData->nonceMin = nonceMin;
	//		blockData->nonceMax = nonceMax;
	//		blockData->flags = workBundleFlags;
	//		xptPacketbuffer_readData(xptClient->recvBuffer, blockData->merkleRoot, 32, &recvError);
	//		xptClient->blockWorkSize++;
	//	}
	//}
	//LeaveCriticalSection(&xptClient->cs_workAccess);
	return true;
}
示例#27
0
void CSendFileDlg::onFileStart()
{	
	start_time = time(NULL);	
}
示例#28
0
/* Write a sequence of commands able to fully rebuild the dataset into
 * "filename". Used both by REWRITEAOF and BGREWRITEAOF. */
static int rewriteAppendOnlyFile(char *filename) {
    dictIterator *di = NULL;
    dictEntry *de;
    FILE *fp;
    char tmpfile[256];
    int j;
    time_t now = time(NULL);

    /* Note that we have to use a different temp name here compared to the
     * one used by rewriteAppendOnlyFileBackground() function. */
    snprintf(tmpfile,256,"temp-rewriteaof-%d.aof", (int) getpid());
    fp = fopen(tmpfile,"w");

    for (j = 0; j < server.dbnum; j++) {
        char selectcmd[] = "*2\r\n$6\r\nSELECT\r\n";
        redisDb *db = server.db+j;
        dict *d = db->dict;

        if (dictSize(d) == 0) continue;
        di = dictGetIterator(d);


        /* SELECT the new DB */
        fwrite(selectcmd,sizeof(selectcmd)-1,1,fp);
        fwriteBulkLong(fp,j);

        /* Iterate this DB writing every entry */
        while((de = dictNext(di)) != NULL) {
            robj *key, *o;
            time_t expiretime;
            int swapped;

            key = dictGetEntryKey(de);
            /* If the value for this key is swapped, load a preview in memory.
             * We use a "swapped" flag to remember if we need to free the
             * value object instead to just increment the ref count anyway
             * in order to avoid copy-on-write of pages if we are forked() */
            if (!server.vm_enabled || key->storage == REDIS_VM_MEMORY ||
                key->storage == REDIS_VM_SWAPPING) {
                o = dictGetEntryVal(de);
                swapped = 0;
            } else {
                o = vmPreviewObject(key);
                swapped = 1;
            }
            expiretime = getExpire(db,key);

            /* Save the key and associated value */
            if (o->type == REDIS_STRING) {
                /* Emit a SET command */
                char cmd[]="*3\r\n$3\r\nSET\r\n";
                fwrite(cmd, sizeof(cmd)-1,1,fp);
                /* Key and value */
                fwriteBulkObject(fp,key);
                fwriteBulkObject(fp,o);
            } 
            else if (o->type == REDIS_LIST) {
                /* Emit the RPUSHes needed to rebuild the list */
                list *list = o->ptr;
                listNode *ln;
                listIter li;

                listRewind(list,&li);
                while((ln = listNext(&li))) {
                    char cmd[]="*3\r\n$5\r\nRPUSH\r\n";
                    robj *eleobj = listNodeValue(ln);

                    fwrite(cmd, sizeof(cmd)-1, 1, fp);
                    fwriteBulkObject(fp,key);
                    fwriteBulkObject(fp,eleobj);
                }
            } 
            else if (o->type == REDIS_SET) {
                /* Emit the SADDs needed to rebuild the set */
                dict *set = o->ptr;
                dictIterator *di = dictGetIterator(set);
                dictEntry *de;

                while((de = dictNext(di)) != NULL) {
                    char cmd[]="*3\r\n$4\r\nSADD\r\n";
                    robj *eleobj = dictGetEntryKey(de);

                    fwrite(cmd,sizeof(cmd)-1,1,fp) ;
                    fwriteBulkObject(fp,key) ;
                    fwriteBulkObject(fp,eleobj);
                }
                dictReleaseIterator(di);
            } 
            else if (o->type == REDIS_ZSET) {
                /* Emit the ZADDs needed to rebuild the sorted set */
                zset *zs = o->ptr;
                dictIterator *di = dictGetIterator(zs->dict);
                dictEntry *de;

                while((de = dictNext(di)) != NULL) {
                    char cmd[]="*4\r\n$4\r\nZADD\r\n";
                    robj *eleobj = dictGetEntryKey(de);
                    double *score = dictGetEntryVal(de);

                    if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
                    if (fwriteBulkObject(fp,key) == 0) goto werr;
                    if (fwriteBulkDouble(fp,*score) == 0) goto werr;
                    if (fwriteBulkObject(fp,eleobj) == 0) goto werr;
                }
                dictReleaseIterator(di);
            } else if (o->type == REDIS_HASH) {
                char cmd[]="*4\r\n$4\r\nHSET\r\n";

                /* Emit the HSETs needed to rebuild the hash */
                if (o->encoding == REDIS_ENCODING_ZIPMAP) {
                    unsigned char *p = zipmapRewind(o->ptr);
                    unsigned char *field, *val;
                    unsigned int flen, vlen;

                    while((p = zipmapNext(p,&field,&flen,&val,&vlen)) != NULL) {
                        if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
                        if (fwriteBulkObject(fp,key) == 0) goto werr;
                        if (fwriteBulkString(fp,(char*)field,flen) == -1)
                            return -1;
                        if (fwriteBulkString(fp,(char*)val,vlen) == -1)
                            return -1;
                    }
                } else {
                    dictIterator *di = dictGetIterator(o->ptr);
                    dictEntry *de;

                    while((de = dictNext(di)) != NULL) {
                        robj *field = dictGetEntryKey(de);
                        robj *val = dictGetEntryVal(de);

                        if (fwrite(cmd,sizeof(cmd)-1,1,fp) == 0) goto werr;
                        if (fwriteBulkObject(fp,key) == 0) goto werr;
                        if (fwriteBulkObject(fp,field) == -1) return -1;
                        if (fwriteBulkObject(fp,val) == -1) return -1;
                    }
                    dictReleaseIterator(di);
                }
            } else {
                redisAssert(0);
            }
            /* Save the expire time */
            if (expiretime != -1) {
                char cmd[]="*3\r\n$8\r\nEXPIREAT\r\n";
                /* If this key is already expired skip it */
                if (expiretime < now) continue;
                fwrite(cmd,sizeof(cmd)-1,1,fp) ;
                fwriteBulkObject(fp,key) ;
                fwriteBulkLong(fp,expiretime) ;
            }
            if (swapped) decrRefCount(o);
        }
        dictReleaseIterator(di);
    }

    /* Make sure data will not remain on the OS's output buffers */
    fflush(fp);
    fsync(fileno(fp));
    fclose(fp);
    
    /* Use RENAME to make sure the DB file is changed atomically only
     * if the generate DB file is ok. */
    rename(tmpfile,filename) ;
    
    redisLog(REDIS_NOTICE,"SYNC append only file rewrite performed");
    return REDIS_OK;
}
示例#29
0
/* Attempt to schedule a specific job on specific available nodes
 * IN job_ptr - job to schedule
 * IN/OUT avail_bitmap - nodes available/selected to use
 * IN exc_core_bitmap - cores which can not be used
 * RET SLURM_SUCCESS on success, otherwise an error code
 */
static int  _try_sched(struct job_record *job_ptr, bitstr_t **avail_bitmap,
                       uint32_t min_nodes, uint32_t max_nodes,
                       uint32_t req_nodes, bitstr_t *exc_core_bitmap)
{
    bitstr_t *tmp_bitmap;
    int rc = SLURM_SUCCESS;
    int feat_cnt = _num_feature_count(job_ptr);
    List preemptee_candidates = NULL;
    List preemptee_job_list = NULL;

    if (feat_cnt) {
        /* Ideally schedule the job feature by feature,
         * but I don't want to add that complexity here
         * right now, so clear the feature counts and try
         * to schedule. This will work if there is only
         * one feature count. It should work fairly well
         * in cases where there are multiple feature
         * counts. */
        struct job_details *detail_ptr = job_ptr->details;
        ListIterator feat_iter;
        struct feature_record *feat_ptr;
        int i = 0, list_size;
        uint16_t *feat_cnt_orig = NULL, high_cnt = 0;

        /* Clear the feature counts */
        list_size = list_count(detail_ptr->feature_list);
        feat_cnt_orig = xmalloc(sizeof(uint16_t) * list_size);
        feat_iter = list_iterator_create(detail_ptr->feature_list);
        while ((feat_ptr =
                    (struct feature_record *) list_next(feat_iter))) {
            high_cnt = MAX(high_cnt, feat_ptr->count);
            feat_cnt_orig[i++] = feat_ptr->count;
            feat_ptr->count = 0;
        }
        list_iterator_destroy(feat_iter);

        if ((job_req_node_filter(job_ptr, *avail_bitmap) !=
                SLURM_SUCCESS) ||
                (bit_set_count(*avail_bitmap) < high_cnt)) {
            rc = ESLURM_NODES_BUSY;
        } else {
            preemptee_candidates =
                slurm_find_preemptable_jobs(job_ptr);
            rc = select_g_job_test(job_ptr, *avail_bitmap,
                                   high_cnt, max_nodes, req_nodes,
                                   SELECT_MODE_WILL_RUN,
                                   preemptee_candidates,
                                   &preemptee_job_list,
                                   exc_core_bitmap);
            if (preemptee_job_list) {
                list_destroy(preemptee_job_list);
                preemptee_job_list = NULL;
            }
        }

        /* Restore the feature counts */
        i = 0;
        feat_iter = list_iterator_create(detail_ptr->feature_list);
        while ((feat_ptr =
                    (struct feature_record *) list_next(feat_iter))) {
            feat_ptr->count = feat_cnt_orig[i++];
        }
        list_iterator_destroy(feat_iter);
        xfree(feat_cnt_orig);
    } else {
        /* Try to schedule the job. First on dedicated nodes
         * then on shared nodes (if so configured). */
        uint16_t orig_shared;
        time_t now = time(NULL);
        char str[100];

        preemptee_candidates = slurm_find_preemptable_jobs(job_ptr);
        orig_shared = job_ptr->details->shared;
        job_ptr->details->shared = 0;
        tmp_bitmap = bit_copy(*avail_bitmap);

        if (exc_core_bitmap) {
            bit_fmt(str, (sizeof(str) - 1), exc_core_bitmap);
            debug2(" _try_sched with exclude core bitmap: %s",str);
        }

        rc = select_g_job_test(job_ptr, *avail_bitmap, min_nodes,
                               max_nodes, req_nodes,
                               SELECT_MODE_WILL_RUN,
                               preemptee_candidates,
                               &preemptee_job_list,
                               exc_core_bitmap);
        if (preemptee_job_list) {
            list_destroy(preemptee_job_list);
            preemptee_job_list = NULL;
        }

        job_ptr->details->shared = orig_shared;

        if (((rc != SLURM_SUCCESS) || (job_ptr->start_time > now)) &&
                (orig_shared != 0)) {
            FREE_NULL_BITMAP(*avail_bitmap);
            *avail_bitmap= tmp_bitmap;
            rc = select_g_job_test(job_ptr, *avail_bitmap,
                                   min_nodes, max_nodes, req_nodes,
                                   SELECT_MODE_WILL_RUN,
                                   preemptee_candidates,
                                   &preemptee_job_list,
                                   exc_core_bitmap);
            if (preemptee_job_list) {
                list_destroy(preemptee_job_list);
                preemptee_job_list = NULL;
            }
        } else
            FREE_NULL_BITMAP(tmp_bitmap);
    }

    if (preemptee_candidates)
        list_destroy(preemptee_candidates);
    return rc;

}
	/**
	 * \brief add a point
	 */
	void	addPoint(const FocusPoint& point,
			const Ice::Current& /* current */) {
		std::cout << timeformat("%H:%M:%S ", time(NULL));
		std::cout << point.position << ": " << point.value;
		std::cout << std::endl;
	}