Esempio n. 1
0
static void SetupRecur_Precon(Bsystem *B){
  MatPre   *M     = B->Pmat = (MatPre *)malloc(sizeof(MatPre));

  /* at present just store diagonal of whole matrix in M->ivert */
  switch(B->Precon){
  case Pre_Diag: /* diagonal preconditioner */
    {
      Rsolver    *R = B->rslv;
      int      nsolve = R->rdata[R->nrecur-1].cstart;
      double   **a    = R->A.a;
      Recur    *rdata = R->rdata + R->nrecur-1;
      int      npatch = rdata->npatch;
      int      *alen  = rdata->patchlen_a;
      int      **map  = rdata->map;
      int       i,n,pos;

      M->info.diag.ndiag = nsolve;
      M->info.diag.idiag = dvector(0,nsolve-1);
      dzero(nsolve,M->info.diag.idiag,1);

      for(n = 0; n < npatch; ++n)
  for(i = 0,pos = 0; i < alen[n]; pos +=alen[n]-i,++i)
    M->info.diag.idiag[map[n][i]] += a[n][pos];
      InvtPrecon(B);
    }
    break;
  case Pre_Block: /* block diagonal preconditioner */
    {
#if 0
      register int j,k;
      int      al, gid, gid1, pos, nvs = B->rslv->Ainfo.nv_solve;
      Blockp   Blk = B->rslv->precon->blk;

      M->nvert = nvs;
      if(nvs) {
  M->ivert = dvector(0, nvs*(nvs+1)/2-1);
  dzero(nvs*(nvs+1)/2,M->ivert,1);
      }

      M->nedge = Blk.nlgid;
      M->Ledge = ivector(0,M->nedge-1);
      M->iedge = (double **)malloc(M->nedge*sizeof(double *));

      for(i = 0; i < npatch; ++i)
  for(j = 0; j < Blk.nle[i]; ++j)
    M->Ledge[Blk.lgid[i][j]] = Blk.edglen[i][j];


      for(i = 0; i < M->nedge; ++i){
  M->iedge[i] = dvector(0,M->Ledge[i]*(M->Ledge[i]+1)/2-1);
  dzero(M->Ledge[i]*(M->Ledge[i]+1)/2,M->iedge[i],1);
      }

      /* For the iterative solver all the global vertex dof are
   listed first then the local dof and finally the local edges */
      for(i = 0; i < npatch; ++i){
  al = alen[i];

  for(j =0,pos = 0; j < Blk.ngv[i]; ++j, pos += al--){
    gid = map[i][j];
    M->ivert[(gid*(gid+1))/2 + gid*(nvs-gid)] += a[i][pos];
    for(k = j+1; k < Blk.ngv[i]; ++k){
      gid1 = map[i][k];
      if(gid < gid1)
        M->ivert[(gid*(gid+1))/2 + gid*(nvs-gid) + gid1-gid]
    += a[i][pos+k-j];
      else if(gid == gid1) /* special case of periodic element */
        M->ivert[(gid*(gid+1))/2 + gid*(nvs-gid1)]
    += 2*a[i][pos+k-j];
      else
        M->ivert[(gid1*(gid1+1))/2 + gid1*(nvs-gid1) + gid-gid1]
    += a[i][pos+k-j];
    }
  }

  /* set up local blocks - note: it is assumed that the local
     vertices are ordered in a similar fashion either side of
     the patch */
  for(j = 0; j < Blk.nle[i]; ++j){
    for(k = 0,n=0; k < Blk.edglen[i][j];pos += al--,
        n += Blk.edglen[i][j]-k, ++k)
      dvadd(Blk.edglen[i][j]-k,a[i]+pos,1,M->iedge[Blk.lgid[i][j]]+n,1,
      M->iedge[Blk.lgid[i][j]]+n,1);
  }
      }
      InvtPrecon(B, nsolve);
#endif
    fprintf(stderr,"H_MatrixR.C: iterative -r not implemented\n");
    }
    break;
  case Pre_None: /* no preconditioner */
    break;
  default:
    error_msg(Unknown value of PRECON);
    break;
  }
}
Esempio n. 2
0
static void update_groupfiles(char *filename, char* username)
{
  char *filenamesfx = NULL, *sfx = NULL, *line = NULL;
  FILE *exfp, *newfp;
  int ulen = strlen(username);
  struct flock lock;

  filenamesfx = xmprintf("%s+", filename);
  sfx = strchr(filenamesfx, '+');
  exfp = xfopen(filename, "r+");

  *sfx = '-';
  unlink(filenamesfx);
  if (link(filename, filenamesfx)) error_msg("Can't create backup file");

  *sfx = '+';
  lock.l_type = F_WRLCK;
  lock.l_whence = SEEK_SET;
  lock.l_start = lock.l_len = 0;

  if (fcntl(fileno(exfp), F_SETLK, &lock) < 0)
    perror_msg("Couldn't lock file %s",filename);

  lock.l_type = F_UNLCK; //unlocking at a later stage

  newfp = xfopen(filenamesfx, "w+");

  while ((line = get_line(fileno(exfp))) != NULL){
    sprintf(toybuf, "%s:",username);
    if (!strncmp(line, toybuf, ulen+1)) goto LOOP;
    else {
      char *n, *p = strrchr(line, ':');

      if (p && *++p && (n = strstr(p, username))) {
        do {
          if (n[ulen] == ',') {
            *n = '\0';
            n += ulen + 1;
            fprintf(newfp, "%s%s\n", line, n);
            break;
          } else if (!n[ulen]) {
            if (n[-1] == ',') n[-1] = *n = '\0';
            if (n[-1] == ':') *n = '\0';
            fprintf(newfp, "%s%s\n", line, n);
            break;
          } else n += ulen;
        } while (*n && (n=strstr(n, username)));
        if (!n) fprintf(newfp, "%s\n", line);
      } else fprintf(newfp, "%s\n", line);
    }
LOOP:
    free(line);
  }
  fcntl(fileno(exfp), F_SETLK, &lock);
  fclose(exfp);
  errno = 0;
  fflush(newfp);
  fsync(fileno(newfp));
  fclose(newfp);
  rename(filenamesfx, filename);
  if (errno){
    perror_msg("File Writing/Saving failed: ");
    unlink(filenamesfx);
  }
  free(filenamesfx);
}
Esempio n. 3
0
/*-------------------------------------------------------------------------
 * Function: parse_layout
 *
 * Purpose: read layout info
 *
 * Return: a list of names, the number of names and its chunking info for
 *  chunked. NULL, on error
 * the layout type can be:
 *  CHUNK, to apply chunking layout
 *  CONTI, to apply continuous layout
 *  COMPA, to apply compact layout
 *
 * Example:
 * "AA,B,CDE:CHUNK=10X10"
 *
 * Programmer: Pedro Vicente, [email protected]
 *
 * Date: December 30, 2003
 *
 *-------------------------------------------------------------------------
 */
obj_list_t* parse_layout(const char *str,
                         int *n_objs,
                         pack_info_t *pack,    /* info about layout needed */
                         pack_opt_t *options)
{
    obj_list_t* obj_list=NULL;
    unsigned    i;
    char        c;
    size_t      len=strlen(str);
    int         j, n, k, end_obj=-1, c_index;
    char        sobj[MAX_NC_NAME];
    char        sdim[10];
    char        slayout[10];


    memset(sdim, '\0', sizeof(sdim));
    memset(sobj, '\0', sizeof(sobj));
    memset(slayout, '\0', sizeof(slayout));

    /* check for the end of object list and number of objects */
    for ( i=0, n=0; i<len; i++)
    {
        c = str[i];
        if ( c==':' )
        {
            end_obj=i;
        }
        if ( c==',' )
        {
            n++;
        }
    }

    if (end_obj==-1) { /* missing : chunk all */
        options->all_layout=1;
    }

    n++;
    obj_list = (obj_list_t*) malloc(n*sizeof(obj_list_t));
    if (obj_list==NULL)
    {
        error_msg(progname, "could not allocate object list\n");
        return NULL;
    }
    *n_objs=n;

    /* get object list */
    for ( j=0, k=0, n=0; j<end_obj; j++,k++)
    {
        c = str[j];
        sobj[k]=c;
        if ( c==',' || j==end_obj-1)
        {
            if ( c==',') sobj[k]='\0'; else sobj[k+1]='\0';
            strcpy(obj_list[n].obj,sobj);
            memset(sobj,0,sizeof(sobj));
            n++;
            k=-1;
        }
    }

    /* nothing after : */
    if (end_obj+1==(int)len)
    {
        if (obj_list) free(obj_list);
        error_msg(progname, "in parse layout, no characters after : in <%s>\n",str);
        exit(EXIT_FAILURE);
    }

    /* get layout info */
    for ( j=end_obj+1, n=0; n<=5; j++,n++)
    {
        if (n==5)
        {
            slayout[n]='\0';  /*cut string */
            if (strcmp(slayout,"COMPA")==0)
                pack->layout=H5D_COMPACT;
            else if (strcmp(slayout,"CONTI")==0)
                pack->layout=H5D_CONTIGUOUS;
            else if (strcmp(slayout,"CHUNK")==0)
                pack->layout=H5D_CHUNKED;
            else {
                error_msg(progname, "in parse layout, not a valid layout in <%s>\n",str);
                exit(EXIT_FAILURE);
            }
        }
        else
        {
            c = str[j];
            slayout[n]=c;
        }
    } /* j */


    if ( pack->layout==H5D_CHUNKED )
    {

    /*-------------------------------------------------------------------------
    * get chunk info
    *-------------------------------------------------------------------------
        */
        k=0;

        if (j>(int)len)
        {
            if (obj_list) free(obj_list);
            error_msg(progname, "in parse layout,  <%s> Chunk dimensions missing\n",str);
            exit(EXIT_FAILURE);
        }

        for ( i=j, c_index=0; i<len; i++)
        {
            c = str[i];
            sdim[k]=c;
            k++; /*increment sdim index */

            if (!isdigit(c) && c!='x'
                && c!='N' && c!='O' && c!='N' && c!='E'
                ){
                if (obj_list) free(obj_list);
                error_msg(progname, "in parse layout, <%s> Not a valid character in <%s>\n",
                    sdim,str);
                exit(EXIT_FAILURE);
            }

            if ( c=='x' || i==len-1)
            {
                if ( c=='x') {
                    sdim[k-1]='\0';
                    k=0;
                    pack->chunk.chunk_lengths[c_index]=atoi(sdim);
                    if (pack->chunk.chunk_lengths[c_index]==0) {
                        if (obj_list) free(obj_list);
                        error_msg(progname, "in parse layout, <%s> conversion to number in <%s>\n",
                            sdim,str);
                        exit(EXIT_FAILURE);
                    }
                    c_index++;
                }
                else if (i==len-1) { /*no more parameters */
                    sdim[k]='\0';
                    k=0;
                    if (strcmp(sdim,"NONE")==0)
                    {
                        pack->chunk.rank=-2;
                    }
                    else
                    {
                        pack->chunk.chunk_lengths[c_index]=atoi(sdim);
                        if (pack->chunk.chunk_lengths[c_index]==0){
                            if (obj_list) free(obj_list);
                            error_msg(progname, "in parse layout, <%s> conversion to number in <%s>\n",
                                sdim,str);
                            exit(EXIT_FAILURE);
                        }
                        pack->chunk.rank=c_index+1;
                    }
                } /*if */
            } /*if c=='x' || i==len-1 */
        } /*i*/


    } /*H5D_CHUNKED*/


    return obj_list;
}
Esempio n. 4
0
int
main (int argc, const char *argv[])
{
  int fd;
  unsigned int size;
  char *filename;
  long res;
  char *buf;

  h5tools_setprogname(PROGRAMNAME);
  h5tools_setstatus(EXIT_SUCCESS);

  /* Initialize h5tools lib */
  h5tools_init();

  parse_command_line (argc, argv);

  if (nbytes == NULL)
    {
      /* missing arg */
      error_msg("missing size\n");
      usage (h5tools_getprogname());
      exit (EXIT_FAILURE);
    }
  if (argc <= (opt_ind))
    {
      error_msg("missing file name\n");
      usage (h5tools_getprogname());
      exit (EXIT_FAILURE);
    }
  filename = HDstrdup (argv[opt_ind]);

  size = 0;
  res = sscanf (nbytes, "%u", &size);
  if (res == EOF)
    {
      /* fail */
      error_msg("missing file name\n");
      usage (h5tools_getprogname());
      exit (EXIT_FAILURE);
    }

  fd = HDopen (filename, O_RDONLY, 0);
  if (fd < 0)
    {
      error_msg("can't open file %s\n", filename);
      exit (EXIT_FAILURE);
    }

  buf = (char *)HDmalloc ((unsigned)(size + 1));
  if (buf == NULL)
    {
      HDclose (fd);
      exit (EXIT_FAILURE);
    }

  res = HDread (fd, buf, (unsigned)size);

  if (res < (long)size)
    {
      if (buf)
  HDfree (buf);
      HDclose (fd);
      exit (EXIT_FAILURE);
    }

  HDwrite (1, buf, (unsigned)size);

  if (buf)
    HDfree (buf);
  HDclose (fd);
  return (EXIT_SUCCESS);
}
/*-------------------------------------------------------------------------
 * Function:    main
 *
 * Purpose:     HDF5 user block unjammer
 *
 * Return:      Success:    0
 *              Failure:    1
 *
 * Programmer:
 *
 * Modifications:
 *
 *-------------------------------------------------------------------------
 */
int
main(int argc, const char *argv[])
{
    void               *edata;
    H5E_auto2_t         func;
    hid_t               ifile = -1;
    hid_t               plist = -1;
    off_t               fsize;
    hsize_t             usize;
    htri_t              testval;
    herr_t              status;
    int                 res;
    h5_stat_t           sbuf;

    h5tools_setprogname(PROGRAMNAME);
    h5tools_setstatus(EXIT_SUCCESS);

    /* Disable error reporting  */
    H5Eget_auto2(H5E_DEFAULT, &func, &edata);
    H5Eset_auto2(H5E_DEFAULT, NULL, NULL);

    /* Initialize h5tools lib  */
    h5tools_init();

    if(EXIT_FAILURE == parse_command_line(argc, argv))
        goto done;

    if (input_file == NULL) {
        /* no user block  */
        error_msg("missing arguemnt for HDF5 file input.\n");
        help_ref_msg(stderr);
        h5tools_setstatus(EXIT_FAILURE);
        goto done;
    }
  
    testval = H5Fis_hdf5(input_file);

    if (testval <= 0) {
        error_msg("Input HDF5 file \"%s\" is not HDF\n", input_file);
        help_ref_msg (stderr);
        h5tools_setstatus(EXIT_FAILURE);
        goto done;
    }

    ifile = H5Fopen(input_file, H5F_ACC_RDONLY , H5P_DEFAULT);

    if (ifile < 0) {
        error_msg("Can't open input HDF5 file \"%s\"\n", input_file);
        h5tools_setstatus(EXIT_FAILURE);
        goto done;
    }

    plist = H5Fget_create_plist(ifile);
    if (plist < 0) {
        error_msg("Can't get file creation plist for file \"%s\"\n", input_file);
        h5tools_setstatus(EXIT_FAILURE);
        goto done;
    }

    status = H5Pget_userblock(plist, & usize);
    if (status < 0) {
        error_msg("Can't get user block for file \"%s\"\n", input_file);
        h5tools_setstatus(EXIT_FAILURE);
        goto done;
    }

    status = H5Pclose(plist);
    HDassert(status >= 0);
    status = H5Fclose(ifile);
    HDassert(status >= 0);

    if (usize == 0) {
  /* no user block to remove: message? */
        error_msg("\"%s\" has no user block: no change to file\n", input_file);
        h5tools_setstatus(EXIT_SUCCESS);
        goto done;
    }

    res = HDfstat(HDfileno(rawinstream), &sbuf);
    if(res < 0) {
        error_msg("Can't stat file \"%s\"\n", input_file);
        h5tools_setstatus(EXIT_FAILURE);
        goto done;
    }

    fsize = sbuf.st_size;

    if (do_delete && (ub_file != NULL)) {
        error_msg("??\"%s\"\n", ub_file);
        h5tools_setstatus(EXIT_FAILURE);
        goto done;
    }

    if (output_file == NULL) {
            error_msg("unable to open output HDF5 file \"%s\"\n", input_file);
            h5tools_setstatus(EXIT_FAILURE);
            goto done;
    } 

    /* copy from 0 to 'usize - 1' into ufid  */
    if (!do_delete) {
        if(copy_to_file(rawinstream, rawoutstream, 0, (ssize_t) usize) < 0) {
            error_msg("unable to copy user block to output file \"%s\"\n", ub_file);
            h5tools_setstatus(EXIT_FAILURE);
            goto done;
        }
    }

    /* copy from usize to end of file into h5fid,
     * starting at end of user block if present */
   if(copy_to_file(rawinstream, rawdatastream, (ssize_t) usize, (ssize_t)(fsize - (ssize_t)usize)) < 0) {
        error_msg("unable to copy hdf5 data to output file \"%s\"\n", output_file);
        h5tools_setstatus(EXIT_FAILURE);
        goto done;
    }
 
done:
    if(input_file)
        HDfree(input_file);
		
    if(output_file)
        HDfree(output_file);
		
    if(ub_file) {
        HDfree(ub_file);
    }
	   
    h5tools_close();

    return h5tools_getstatus();
}
Esempio n. 6
0
File: step.c Progetto: AkaBlood/ogs5
/* ---------------------------------------------------------------------- */
int
P_step (LDBLE step_fraction)
/* ---------------------------------------------------------------------- */
{
/*
 *   zero global solution, add solution or mixture, add exchange,
 *   add surface, add gas phase, add solid solutions,
 *   set temperature, and add reaction. 
 *   Ensure all elements
 *   included in any of these are present in small amounts.
 *   Save result as n_user -1.
 */
  LDBLE difftemp;
  int step_number;
  struct pp_assemblage *pp_assemblage_save = NULL;
  struct s_s_assemblage *s_s_assemblage_save = NULL;

  if (svnid == NULL)
    fprintf (stderr, " ");

/*
 *   Zero out global solution data
 */

  xsolution_zero ();
/*
 *   Set reaction to zero
 */
  step_x = 0.0;
  step_number = reaction_step;
/*
 *   Mixing or solution
 */
  if (use.mix_ptr != NULL)
  {
    add_mix (use.mix_ptr);
  }
  else if (use.solution_ptr != NULL)
  {
    add_solution (use.solution_ptr, 1.0, 1.0);
  }
  else
  {
    input_error++;
    error_msg ("Neither mixing nor an initial solution have "
	       "been defined in reaction step.", STOP);
  }
/*
 *   Reaction
 */
  if (use.irrev_ptr != NULL)
  {
    add_reaction (use.irrev_ptr, step_number, step_fraction);
  }
/*
 *   Kinetics
 */
  if (use.kinetics_ptr != NULL)
  {
    add_kinetics (use.kinetics_ptr);
    /*
       master_ptr =master_bsearch("S(6)");
       output_msg(OUTPUT_MESSAGE,"Added kinetics, S(6) %e\n", master_ptr->total);
       master_ptr =master_bsearch("S");
       output_msg(OUTPUT_MESSAGE,"Added kinetics, S %e\n", master_ptr->total);
     */
  }
/*
 *   Exchange
 */
  if (use.exchange_ptr != NULL)
  {
    add_exchange (use.exchange_ptr);
  }
/*
 *   Surface
 */
  if (use.surface_ptr != NULL)
  {
    add_surface (use.surface_ptr);
  }
/*
 *   Gases
 */
  if (use.gas_phase_ptr != NULL)
  {
    add_gas_phase (use.gas_phase_ptr);
  }
/*
 *   Temperature
 */
  if (use.temperature_ptr != NULL)
  {
    add_temperature (use.temperature_ptr, step_number);
  }
  if ((state == TRANSPORT) && (transport_step != 0) &&
      (cell > 0) && (cell != count_cells + 1))
  {
    difftemp = tc_x - cell_data[cell - 1].temp;
    cell_data[cell - 1].temp += difftemp / tempr;
    tc_x = cell_data[cell - 1].temp;
  }
/*
 *   Pure phases and solid solutions are added to avoid
 *   zero or negative concentrations
 */
/*
 *   Pure phases
 */
  if (use.pp_assemblage_ptr != NULL)
  {
    pp_assemblage_save =
      (struct pp_assemblage *) PHRQ_malloc (sizeof (struct pp_assemblage));
    if (pp_assemblage_save == NULL)
      malloc_error ();
    pp_assemblage_copy (use.pp_assemblage_ptr, pp_assemblage_save,
			use.pp_assemblage_ptr->n_user);
    add_pp_assemblage (use.pp_assemblage_ptr);
  }
/*
 *   Solid solutions
 */
  if (use.s_s_assemblage_ptr != NULL)
  {
    s_s_assemblage_save =
      (struct s_s_assemblage *) PHRQ_malloc (sizeof (struct s_s_assemblage));
    if (s_s_assemblage_save == NULL)
      malloc_error ();
    s_s_assemblage_copy (use.s_s_assemblage_ptr, s_s_assemblage_save,
			 use.s_s_assemblage_ptr->n_user);
    add_s_s_assemblage (use.s_s_assemblage_ptr);
  }
/*
 *   Check that elements are available for gas components,
 *   pure phases, and solid solutions
 */
  if (use.gas_phase_ptr != NULL)
  {
    gas_phase_check (use.gas_phase_ptr);
  }
  if (use.pp_assemblage_ptr != NULL)
  {
    pp_assemblage_check (use.pp_assemblage_ptr);
  }
  if (use.s_s_assemblage_ptr != NULL)
  {
    s_s_assemblage_check (use.s_s_assemblage_ptr);
  }
/*
 *   Check that element moles are >= zero
 */
  if (solution_check () == MASS_BALANCE)
  {
    /* reset moles and deltas */
    if (use.pp_assemblage_ptr != NULL)
    {
      pp_assemblage_free (use.pp_assemblage_ptr);
      pp_assemblage_copy (pp_assemblage_save, use.pp_assemblage_ptr,
			  use.pp_assemblage_ptr->n_user);
      pp_assemblage_free (pp_assemblage_save);
      pp_assemblage_save =
	(struct pp_assemblage *) free_check_null (pp_assemblage_save);
    }
    if (use.s_s_assemblage_ptr != NULL)
    {
      s_s_assemblage_free (use.s_s_assemblage_ptr);
      s_s_assemblage_copy (s_s_assemblage_save, use.s_s_assemblage_ptr,
			   use.s_s_assemblage_ptr->n_user);
      s_s_assemblage_free (s_s_assemblage_save);
      s_s_assemblage_save =
	(struct s_s_assemblage *) free_check_null (s_s_assemblage_save);
    }
    return (MASS_BALANCE);
  }
/*
 *   Copy global into solution n_user = -1
 */
  xsolution_save (-1);
  step_save_surf (-1);
  step_save_exch (-1);
/*
 *   Clean up temporary space
 */
  if (pp_assemblage_save != NULL)
  {
    pp_assemblage_free (pp_assemblage_save);
    pp_assemblage_save =
      (struct pp_assemblage *) free_check_null (pp_assemblage_save);
  }
  if (s_s_assemblage_save != NULL)
  {
    s_s_assemblage_free (s_s_assemblage_save);
    s_s_assemblage_save =
      (struct s_s_assemblage *) free_check_null (s_s_assemblage_save);
  }
  return (OK);
}
Esempio n. 7
0
int main(int argc, char *argv[])
{
	int ret;
	const char *target_device;
	const char *img_path;

	if (argv[1][0] != '-')
	{
		printf("Unknown Option\n");
		return -1;
	}

	if (argc >= 4)
	{
		target_device = get_device(argv[2][0] - '0');
		img_path = argv[3];
	}
	else
	{
		target_device = get_device(0);
		if (argc >= 3)
		{
			img_path = argv[2];
		}
		else
		{
			img_path = NULL;
		}
	}

	switch (argv[1][1])
	{
	case 'u':
	case 'U':
		if (img_path == NULL)
		{
			return cavan_dd("u-boot-no-padding.bin", target_device, 0, UBOOT_OFFSET, 0);
		}
		else if (strcmp(text_basename(img_path), "u-boot.bin") == 0)
		{
			return cavan_dd(img_path, target_device, UBOOT_PADDING_SIZE, UBOOT_OFFSET, 0);
		}
		else
		{
			return cavan_dd(img_path, target_device, 0, UBOOT_OFFSET, 0);
		}

	case 'k':
	case 'K':
		return copy_to_emmc("uImage", img_path, target_device, UIMAGE_OFFSET);

	case 'l':
	case 'L':
		return copy_to_emmc("logo.bmp", img_path, target_device, LOGO_OFFSET);

	case 'b':
	case 'B':
		return copy_to_emmc("busybox.img", img_path, target_device, BUSYBOX_OFFSET);

	case 'c':
	case 'C':
		return copy_to_emmc("charge.bmps", img_path, target_device, CARTOON_OFFSET);

	case 's':
	case 'S':
		target_device = format_text("%sp2", target_device);
		ret = copy_to_emmc("system.img", img_path, target_device, 0);
		if (ret < 0)
		{
			error_msg("copy_to_emmc");
			return ret;
		}
		break;

	case 'd':
	case 'D':
		target_device = format_text("%sp5", target_device);
		ret = copy_to_emmc("userdata.img", img_path, target_device, 0);
		if (ret < 0)
		{
			error_msg("copy_to_emmc");
			return ret;
		}
		break;

	case 'r':
	case 'R':
		switch (argv[1][2])
		{
		case 'a':
		case 'A':
			return copy_to_emmc("uramdisk.img", img_path, target_device, RAMDISK_OFFSET);

		case 'e':
		case 'E':
			target_device = format_text("%sp4", target_device);
			ret = copy_to_emmc("recovery.img", img_path, target_device, 0);
			if (ret < 0)
			{
				error_msg("copy_to_emmc");
				return ret;
			}
			break;

		default:
			printf("Unknown Option\n");
			return -1;
		}
		break;

	default:
		printf("Unknown Option\n");
		return -1;
	}

	return extend_partition(target_device);
}
Esempio n. 8
0
File: h5jam.c Progetto: ElaraFX/hdf5
/*-------------------------------------------------------------------------
 * Function:    main
 *
 * Purpose:     HDF5 user block jammer
 *
 * Return:      Success:    0
 *              Failure:    1
 *
 * Programmer:
 *
 * Modifications:
 *
 *-------------------------------------------------------------------------
 */
int
main (int argc, const char *argv[])
{
    int         ufid = -1;
    int         h5fid = -1;
    int         ofid = -1;
    void       *edata;
    H5E_auto2_t func;
    hid_t       ifile = -1;
    hid_t       plist = -1;
    herr_t      status;
    htri_t      testval;
    hsize_t     usize;
    hsize_t     h5fsize;
    hsize_t     startub;
    hsize_t     where;
    hsize_t     newubsize;
    off_t       fsize;
    h5_stat_t   sbuf;
    h5_stat_t   sbuf2;
    int         res;

    h5tools_setprogname(PROGRAMNAME);
    h5tools_setstatus(EXIT_SUCCESS);

    /* Disable error reporting */
    H5Eget_auto2(H5E_DEFAULT, &func, &edata);
    H5Eset_auto2(H5E_DEFAULT, NULL, NULL);

    /* Initialize h5tools lib */
    h5tools_init();

    parse_command_line (argc, argv);

    if (ub_file == NULL) {
        /* no user block */
        error_msg("missing arguemnt for -u <user_file>.\n");
        help_ref_msg(stderr);
        leave (EXIT_FAILURE);
    }

    testval = H5Fis_hdf5 (ub_file);

    if (testval > 0) {
        error_msg("-u <user_file> cannot be HDF5 file, but it appears to be an HDF5 file.\n");
        help_ref_msg(stderr);
        leave (EXIT_FAILURE);
    }

    if (input_file == NULL) {
        error_msg("missing arguemnt for -i <HDF5 file>.\n");
        help_ref_msg(stderr);
        leave (EXIT_FAILURE);
    }

    testval = H5Fis_hdf5 (input_file);

    if (testval <= 0) {
        error_msg("Input HDF5 file \"%s\" is not HDF5 format.\n", input_file);
        help_ref_msg(stderr);
        leave (EXIT_FAILURE);
    }

    ifile = H5Fopen (input_file, H5F_ACC_RDONLY, H5P_DEFAULT);

    if (ifile < 0) {
        error_msg("Can't open input HDF5 file \"%s\"\n", input_file);
        leave (EXIT_FAILURE);
    }

    plist = H5Fget_create_plist (ifile);
    if (plist < 0) {
        error_msg("Can't get file creation plist for file \"%s\"\n", input_file);
        H5Fclose(ifile);
        leave (EXIT_FAILURE);
    }

    status = H5Pget_userblock (plist, &usize);
    if (status < 0) {
        error_msg("Can't get user block for file \"%s\"\n", input_file);
        H5Pclose(plist);
        H5Fclose(ifile);
        leave (EXIT_FAILURE);
    }

    H5Pclose(plist);
    H5Fclose(ifile);

    ufid = HDopen(ub_file, O_RDONLY, 0);
    if(ufid < 0) {
        error_msg("unable to open user block file \"%s\"\n", ub_file);
        leave (EXIT_FAILURE);
    }

    res = HDfstat(ufid, &sbuf);
    if(res < 0) {
        error_msg("Can't stat file \"%s\"\n", ub_file);
        HDclose (ufid);
        leave (EXIT_FAILURE);
    }

    fsize = (off_t)sbuf.st_size;

    h5fid = HDopen(input_file, O_RDONLY, 0);
    if(h5fid < 0) {
        error_msg("unable to open HDF5 file for read \"%s\"\n", input_file);
        HDclose (ufid);
        leave (EXIT_FAILURE);
    }

    res = HDfstat(h5fid, &sbuf2);
    if(res < 0) {
        error_msg("Can't stat file \"%s\"\n", input_file);
        HDclose (h5fid);
        HDclose (ufid);
        leave (EXIT_FAILURE);
    }

    h5fsize = (hsize_t)sbuf2.st_size;

    if (output_file == NULL) {
        ofid = HDopen (input_file, O_WRONLY, 0);

        if (ofid < 0) {
            error_msg("unable to open output file \"%s\"\n", output_file);
            HDclose (h5fid);
            HDclose (ufid);
            leave (EXIT_FAILURE);
        }
    }
    else {
        ofid = HDopen (output_file, O_WRONLY | O_CREAT | O_TRUNC, 0644);

        if (ofid < 0) {
            error_msg("unable to create output file \"%s\"\n", output_file);
            HDclose (h5fid);
            HDclose (ufid);
            leave (EXIT_FAILURE);
        }
    }

    newubsize = compute_user_block_size ((hsize_t) fsize);

    startub = usize;

    if (usize > 0) {
        if (do_clobber == TRUE) {
            /* where is max of the current size or the new UB */
            if (usize > newubsize) {
                newubsize = usize;
            }
            startub = 0;    /*blast the old */
        }
        else {
            /* add new ub to current ublock, pad to new offset */
            newubsize += usize;
            newubsize = compute_user_block_size ((hsize_t) newubsize);
        }
    }

    /* copy the HDF5 from starting at usize to starting at newubsize:
     *  makes room at 'from' for new ub */
    /* if no current ub, usize is 0 */
    copy_some_to_file (h5fid, ofid, usize, newubsize, (ssize_t) (h5fsize - usize));

    /* copy the old ub to the beginning of the new file */
    if (!do_clobber) {
        where = copy_some_to_file (h5fid, ofid, (hsize_t) 0, (hsize_t) 0, (ssize_t) usize);
    }

    /* copy the new ub to the end of the ub */
    where = copy_some_to_file (ufid, ofid, (hsize_t) 0, startub, (ssize_t) - 1);

    /* pad the ub */
    where = write_pad (ofid, where);

    if(ub_file)
        HDfree (ub_file);
    if(input_file)
        HDfree (input_file);
    if(output_file)
        HDfree (output_file);
    
    if(ufid >= 0)
        HDclose (ufid);
    if(h5fid >= 0)
        HDclose (h5fid);
    if(ofid >= 0)
        HDclose (ofid);

    return h5tools_getstatus();
}
Esempio n. 9
0
File: h5jam.c Progetto: ElaraFX/hdf5
/*-------------------------------------------------------------------------
 * Function:    copy_some_to_file
 *
 * Purpose:     Copy part of the input file to output.
 *      infid: fd of file to read
 *      outfid: fd of file to write
 *      startin: offset of where to read from infid
 *      startout: offset of where to write to outfid
 *      limit: bytes to read/write
 *
 *    If limit is < 0, the entire input file is copied.
 *
 *    Note: this routine can be used to copy within
 *    the same file, i.e., infid and outfid can be the
 *    same file.
 *
 * Return:      Success:    last byte written in the output.
 *              Failure:    Exits program with EXIT_FAILURE value.
 *
 *-------------------------------------------------------------------------
 */
hsize_t
copy_some_to_file(int infid, int outfid, hsize_t startin, hsize_t startout,
       ssize_t limit)
{
    char buf[1024];
    h5_stat_t sbuf;
    int res;
    ssize_t tot = 0;
    ssize_t howmuch = 0;
    ssize_t nchars = -1;
    ssize_t to;
    ssize_t from;
    ssize_t toend;
    ssize_t fromend;

    if(startin > startout) {
        /* this case is prohibited */
        error_msg("copy_some_to_file: panic: startin > startout?\n");
        exit (EXIT_FAILURE);
    } /* end if */

    if(limit < 0) {
        res = HDfstat(infid, &sbuf);
        if(res < 0) {
            error_msg("Can't stat file \n");
            HDexit(EXIT_FAILURE);
        } /* end if */

        howmuch = (ssize_t)sbuf.st_size;
    } else {
        howmuch = limit;
    } /* end if */

    if(0 == howmuch)
        return 0;

    toend = (ssize_t) startout + howmuch;
    fromend = (ssize_t) startin + howmuch;

    if (howmuch > 512) {
        to = toend - 512;
        from = fromend - 512;
    } else {
        to = toend - howmuch;
        from = fromend - howmuch;
    } /* end if */

    while (howmuch > 0) {
        HDlseek(outfid, (off_t) to, SEEK_SET);
        HDlseek(infid, (off_t) from, SEEK_SET);

        if (howmuch > 512) {
            nchars = HDread(infid, buf, (unsigned) 512);
        } else {
            nchars = HDread(infid, buf, (unsigned)howmuch);
        } /* end if */

        if (nchars <= 0) {
            error_msg("Read error \n");
            HDexit(EXIT_FAILURE);
        } /* end if */

        if(HDwrite (outfid, buf, (unsigned) nchars) < 0) {
            error_msg("Write error \n");
            HDexit(EXIT_FAILURE);
        }

        tot += nchars;
        howmuch -= nchars;
        if(howmuch > 512) {
            to -= nchars;
            from -= nchars;
        } else {
            to -= howmuch;
            from -= howmuch;
        } /* end if */
    } /* end while */

    return (hsize_t)tot + (hsize_t)startout;
} /* end copy_some_to_file() */
Esempio n. 10
0
	void ScriptComponent::OnEvent( const IEvent* event )
	{
		for ( IScriptFunctionHandler::FunctionList::iterator i = m_eventHandlers.begin( ); i != m_eventHandlers.end( ); ++i )
		{
			EventType eventType = event->GetEventType( );
			
			if ( event->GetEventType( ) == ALL_EVENTS )
			{
				ScriptEvent* scriptEvent = ( ScriptEvent* ) event;

				try
				{
					switch( scriptEvent->GetParamType( ) )
					{

					case ScriptEvent::PARAMCOMBO_NONE:

						call_function< void >( ( *i )->GetFunction( ), scriptEvent->GetEventName( ) );

						break;

					case ScriptEvent::PARAMCOMBO_INT:

						call_function< void >( ( *i )->GetFunction( ), scriptEvent->GetEventName( ), scriptEvent->GetValue1AsInt( ) );

						break;

					case ScriptEvent::PARAMCOMBO_STRING:

						call_function< void >( ( *i )->GetFunction( ), scriptEvent->GetEventName( ), scriptEvent->GetValue1AsString( ) );

						break;

					case ScriptEvent::PARAMCOMBO_STRING_STRING:

						call_function< void >( ( *i )->GetFunction( ), scriptEvent->GetEventName( ), scriptEvent->GetValue1AsString( ), scriptEvent->GetValue2AsString( ) );

						break;

					case ScriptEvent::PARAMCOMBO_STRING_INT:

						call_function< void >( ( *i )->GetFunction( ), scriptEvent->GetEventName( ), scriptEvent->GetValue1AsString( ), scriptEvent->GetValue2AsInt( ) );

						break;

					case ScriptEvent::PARAMCOMBO_INT_STRING:

						call_function< void >( ( *i )->GetFunction( ), scriptEvent->GetEventName( ), scriptEvent->GetValue1AsInt( ), scriptEvent->GetValue2AsString( ) );

						break;

					case ScriptEvent::PARAMCOMBO_INT_INT:

						call_function< void >( ( *i )->GetFunction( ), scriptEvent->GetEventName( ), scriptEvent->GetValue1AsInt( ), scriptEvent->GetValue2AsInt( ) );

						break;

					}
				}
				catch( error& e )
				{
					object error_msg( from_stack( e.state( ) , -1) );
					std::stringstream logMessage;
					logMessage << error_msg;
					Logger::Get( )->Warn( logMessage.str( ) );
				}
			}
		}
	}
Esempio n. 11
0
int copy_file_recursive(const char *source, const char *dest)
{
	/* This is a recursive function, try to minimize stack usage */
	/* NB: each struct stat is ~100 bytes */
	struct stat source_stat;
	struct stat dest_stat;
	int retval = 0;
	int dest_exists = 0;

	if (strcmp(source, ".lock") == 0)
		goto skip;

	if (stat(source, &source_stat) < 0) {
		perror_msg("Can't stat '%s'", source);
		return -1;
	}

	if (lstat(dest, &dest_stat) < 0) {
		if (errno != ENOENT) {
			perror_msg("Can't stat '%s'", dest);
			return -1;
		}
	} else {
		if (source_stat.st_dev == dest_stat.st_dev
		 && source_stat.st_ino == dest_stat.st_ino
		) {
			error_msg("'%s' and '%s' are the same file", source, dest);
			return -1;
		}
		dest_exists = 1;
	}

	if (S_ISDIR(source_stat.st_mode)) {
		DIR *dp;
		struct dirent *d;

		if (dest_exists) {
			if (!S_ISDIR(dest_stat.st_mode)) {
				error_msg("Target '%s' is not a directory", dest);
				return -1;
			}
			/* race here: user can substitute a symlink between
			 * this check and actual creation of files inside dest */
		} else {
			/* Create DEST */
			mode_t mode = source_stat.st_mode;
			/* Allow owner to access new dir (at least for now) */
			mode |= S_IRWXU;
			if (mkdir(dest, mode) < 0) {
				perror_msg("Can't create directory '%s'", dest);
				return -1;
			}
		}
		/* Recursively copy files in SOURCE */
		dp = opendir(source);
		if (dp == NULL) {
			retval = -1;
			goto ret;
		}

		while (retval == 0 && (d = readdir(dp)) != NULL) {
			char *new_source, *new_dest;

			if (dot_or_dotdot(d->d_name))
				continue;
			new_source = concat_path_file(source, d->d_name);
			new_dest = concat_path_file(dest, d->d_name);
			if (copy_file_recursive(new_source, new_dest) < 0)
				retval = -1;
			free(new_source);
			free(new_dest);
		}
		closedir(dp);

		goto ret;
	}

	if (S_ISREG(source_stat.st_mode)) {
		int src_fd;
		int dst_fd;
		mode_t new_mode;

		src_fd = open(source, O_RDONLY);
		if (src_fd < 0) {
			perror_msg("Can't open '%s'", source);
			return -1;
		}

		/* Do not try to open with weird mode fields */
		new_mode = source_stat.st_mode;

		// security problem versus (sym)link attacks
		// dst_fd = open(dest, O_WRONLY|O_CREAT|O_TRUNC, new_mode);
		/* safe way: */
		dst_fd = open(dest, O_WRONLY|O_CREAT|O_EXCL, new_mode);
		if (dst_fd < 0) {
			close(src_fd);
			return -1;
		}

		if (copyfd_eof(src_fd, dst_fd, COPYFD_SPARSE) == -1)
			retval = -1;
		close(src_fd);
		/* Careful: do check that buffered writes succeeded... */
		if (close(dst_fd) < 0) {
			perror_msg("Error writing to '%s'", dest);
			retval = -1;
		} else {
			/* (Try to) copy atime and mtime */
			struct timeval atime_mtime[2];
			atime_mtime[0].tv_sec = source_stat.st_atime;
			// note: if "st_atim.tv_nsec" doesn't compile, try "st_atimensec":
			atime_mtime[0].tv_usec = source_stat.st_atim.tv_nsec / 1000;
			atime_mtime[1].tv_sec = source_stat.st_mtime;
			atime_mtime[1].tv_usec = source_stat.st_mtim.tv_nsec / 1000;
			// note: can use utimensat when it is more widely supported:
			utimes(dest, atime_mtime);
		}
		goto ret;
	}

	/* Neither dir not regular file: skip */

 skip:
	log_warning("Skipping '%s'", source);
 ret:
	return retval;
}
Esempio n. 12
0
void 
main (int argc, char *args[])
{
  int i, n, r, c, ch;
  FILE *inf;
  marklistptr library = NULL, list = NULL, step = NULL;
  marklistptr symbol_list = NULL;
  marktype d, d2;
  Pixel **bitmap, **recon, **bitmapcopy;
  char *splitfilename = NULL;
  int cols, rows, count, librarysize, lossy = 1;
  int quick = 0;
  int ticencode = 0, ticdecode = 0, external = 0;
  char *libraryname = NULL, *infile = NULL;
  char *s1 = NULL, *s2 = NULL;
  char bufferin[BUFSIZ], bufferout[BUFSIZ];

  if (argc < 2)
    usage ();

  while ((ch = getopt (argc, args, "edlLQhvXR:")) != -1)
    switch (ch)
      {
      case 'e':
	ticencode = 1;
	break;
      case 'd':
	ticdecode = 1;
	break;
      case 'l':
	lossy = 1;
	break;
      case 'L':
	lossy = 0;
	break;
      case 'Q':
	quick = 1;
	break;
      case 'v':
	V = 1;
	break;
      case 'X':
	external = 1;
	break;
      case 'R':
	splitfilename = optarg;
	break;
      case 'h':
      case '?':
	usage ();
      }

  for (i = 1; i < argc; i++)
    if (args[i][0] != '-')
      if (strcmp (args[i - 1], "-R"))
	{			/* ignore arg following -R, ie. -R <filename> */
	  if (!s1)
	    s1 = args[i];
	  else if (!s2)
	    s2 = args[i];
	  else
	    error_msg (args[0], "too many filenames", "");
	}

  if (ticencode == ticdecode)
    error_msg (args[0], "please specify either encode XOR decode", "");

  if (ticencode)
    {
	  /*****************
	    ENCODING STAGE
	  *****************/
      long PrevBits = 0;
      long BITS_header = 0, BITS_symbols = 0, BITS_offsets = 0, BITS_residue = 0,
        BITS_footer = 0, BITS_library = 0;

      libraryname = s1;
      if (!libraryname)
	error_msg (args[0], "please specify a library file", "");
      infile = s2;
      if (!infile)
	error_msg (args[0], "please specify a file name", "");

      inf = fopen (infile, "rb");
      if (inf == NULL)
	error_msg (args[0], "Trouble opening file:", infile);
      setbuf (inf, bufferin);

      count = librarysize = read_library (libraryname, &library);

      if (V)
	fprintf (stderr, "%s: processing...\n", args[0]);

      if (pbm_isapbmfile (inf))
	{
	  if (V)
	    fprintf (stderr, "reading file %s...\n", infile);
	  bitmap = pbm_readfile (inf, &cols, &rows);
	  fclose (inf);

	  bitmapcopy = pbm_copy (bitmap, cols, rows);

	  if (V)
	    fprintf (stderr, "extracting...");
	  ExtractAllMarks (bitmap, &list, cols, rows);
	  if (V)
	    fprintf (stderr, "(%d marks)\n", marklist_length (list));

	  /* sort into reading order */
	  if (V)
	    fprintf (stderr, "sorting...\n");
	  list = sortmarks (list);

	  pbm_freearray (&bitmap, rows);	/* clear old version */
	  bitmap = bitmapcopy;	/* point to the copy */
	  recon = pbm_allocarray (cols, rows);

	  if (V)
	    fprintf (stderr, "matching...");

	  match_sequence (list, library, &symbol_list, recon, quick);


	  PrevBits = 0;
	  setbuf (stdout, bufferout);
	  /* start output */
	  magic_write (stdout, MAGIC_TIC);
	  InitArithEncoding ();

	  EncodeGammaDist (1);	/* version 1 of the program */
	  EncodeGammaDist (lossy);	/* lossy=1 = no residue */
	  EncodeGammaDist (external);	/* 1== external file */

	  count = marklist_length (symbol_list);
	  if (V)
	    fprintf (stderr, "encoding cols, rows, and number of symbols=%d\n", count);

	  EncodeGammaDist (cols);
	  EncodeGammaDist (rows);
	  EncodeGammaDist (count);
	  EncodeGammaDist (librarysize);

	  BITS_header = CountOfBitsOut - PrevBits;
	  PrevBits = CountOfBitsOut;


	  /* output the library sequence */
	  if (external == 0)
	    {
	      if (V)
		fprintf (stderr, "encoding library\n");

	      bl_clearmodel ();
	      bl_writetemplate (library_template);
	      for (step = library; step; step = step->next)
		bl_compress_mark (step->data);
	      bl_freemodel ();
	      BITS_library = CountOfBitsOut - PrevBits;
	      PrevBits = CountOfBitsOut;
	    }

	  /* output the symbol sequence */
	  if (V)
	    fprintf (stderr, "encoding symbol sequence\n");
	  InitPPM ();
	  EncodeSymbols (symbol_list, count);
	  BITS_symbols = CountOfBitsOut - PrevBits;
	  PrevBits = CountOfBitsOut;


	  /* output the offset sequence */
	  if (V)
	    fprintf (stderr, "encoding offset sequence\n");
	  EncodeOffsets (symbol_list, count);
	  BITS_offsets = CountOfBitsOut - PrevBits;
	  PrevBits = CountOfBitsOut;

	  EncodeChecksum ();	/* code lossy checksum */

	  /* calculate the residue...and compress it---if need be! */
	  if (!lossy)
	    {
	      if (V)
		fprintf (stderr, "encoding residue...\n");

	      d.bitmap = bitmap;
	      d.h = rows;
	      d.w = cols;
	      d2.bitmap = recon;
	      d2.h = rows;
	      d2.w = cols;

	      if (splitfilename)
		{
		  FILE *temp;

		  CloseDownArithEncoding ();
		  fclose (stdout);
		  /* no residue result */
		  BITS_footer = CountOfBitsOut - PrevBits;

		  temp = fopen (splitfilename, "wb");
		  if (temp == NULL)
		    error_msg (args[0], "Trouble creating file:", splitfilename);

		  arith_out = temp;
		  InitArithEncoding ();
		  bl_clair_compress (d, d2);
		  CloseDownArithEncoding ();
		  BITS_residue = CountOfBitsOut;
		  fclose (temp);
		}
	      else
		{
		  bl_clair_compress (d, d2);
		  BITS_residue = CountOfBitsOut - PrevBits;
		  PrevBits = CountOfBitsOut;
		  EncodeChecksum ();	/* code lossless checksum */
		  CloseDownArithEncoding ();
		  BITS_footer = CountOfBitsOut - PrevBits;
		}
	    }
	  else
	    {
	      if (V)
		fprintf (stderr, "not encoding residue..lossy mode\n");
	      CloseDownArithEncoding ();
	      BITS_footer = CountOfBitsOut - PrevBits;
	    }

	  /* because we edit the values above */
	  CountOfBitsOut = BITS_header + BITS_library + BITS_symbols + BITS_offsets + BITS_residue + BITS_footer;

	  fprintf (stderr, "bits: header=%ld, library=%ld, "
		   "symbols=%ld, offsets=%ld, residue=%ld, footer=%ld\n",
		   BITS_header, BITS_library, BITS_symbols,
		   BITS_offsets, BITS_residue, BITS_footer);
	  fprintf (stderr, "total bits: %ld, ", CountOfBitsOut);
	  fprintf (stderr, "Lossy CR: %4.2f", (cols * rows) / (float) (CountOfBitsOut - BITS_residue));
	  if (external)
	    fprintf (stderr, " (excluding external lib)");
	  fprintf (stderr, ", Lossless CR: %4.2f\n", (!lossy) * (cols * rows) / (float) (CountOfBitsOut));
	}
      else
	error_msg (args[0], "unknown format of bitmap--expecting PBM.", "");
    }
  else
    {
	  /*****************
	    DECODING STAGE
	  *****************/
      int lastx, lasty;
      librarysize = 0;

      if (external)
	{
	  libraryname = s1;
	  infile = s2;
	  count = librarysize = read_library (libraryname, &library);
	}
      else
	{
	  infile = s1;
	  if (infile && s2)
	    error_msg (args[0], "too many filenames", "");
	}

      if (!freopen (infile, "rb", stdin))
	error_msg (args[0], "Trouble opening file:", infile);


      if (V)
	fprintf (stderr, "decompressing...\n");

      setbuf (stdin, bufferin);
      magic_check (stdin, MAGIC_TIC);

      InitArithDecoding ();

      {
	int version = DecodeGammaDist ();
	if (version != 1)
	  error_msg (args[0], "Need later version of decompressor.", "");
      }

      {
	int templossy = DecodeGammaDist ();
	if (!lossy)
	  lossy = templossy;	/* can only choose if encoded file is lossless */
	if (V)
	  {
	    if (lossy)
	      fprintf (stderr, "lossy mode\n");
	    else
	      fprintf (stderr, "lossless mode\n");
	  }
      }

      if (DecodeGammaDist ())
	{			/* if compressed file doesn't contain library */
	  if (!external)
	    error_msg (args[0], "compressed file doesn't contain library, specify externally", "");
	  external = 1;
	}
      else
	{			/* if compressed file contains library */
	  if (external)
	    fprintf (stderr, "ignoring external library file\n");
	  external = 0;
	}

      cols = DecodeGammaDist ();
      rows = DecodeGammaDist ();
      count = DecodeGammaDist ();

      i = DecodeGammaDist ();	/* librarysize */
      if (external)
	{
	  if (i > librarysize)
	    error_msg (args[0], "external library file is too small!", "");
	  else if (i < librarysize)
	    fprintf (stderr, "%s: warning, expecting a different (smaller) library.\n", args[0]);
	}
      librarysize = i;

      if (V)
	fprintf (stderr, "cols %d, rows %d, num syms %d, library size %d\n", cols, rows, count, librarysize);

      /* decode library */
      if (external == 0)
	{
	  if (V)
	    fprintf (stderr, "reading library\n");
	  bl_clearmodel ();
	  bl_readtemplate ();
	  for (n = 0; n < librarysize; n++)
	    {
	      bl_decompress_mark (&d);
	      d.symnum = n;
	      if (library == NULL)
		step = marklist_add (&library, d);
	      else
		step = marklist_add (&step, d);
	    }
	  bl_freemodel ();
	  if (V)
	    fprintf (stderr, "read %d marks from library\n", marklist_length (library));
	}

      recon = pbm_allocarray (cols, rows);

      /* decode symbols */
      InitPPM ();
      if (V)
	fprintf (stderr, "decompressing %d symbols\n", count);
      symbol_list = DecodeSymbols (count);

      /* decode offsets */
      if (V)
	fprintf (stderr, "reading offsets...\n");
      DecodeOffsets (symbol_list, count);
      lastx = lasty = 0;
      for (step = symbol_list; step; step = step->next)
	{
	  lastx = lastx + step->data.xoffset;
	  lasty = lasty + step->data.yoffset;

	  marklist_getat (library, step->data.symnum, &d2);
	  for (r = 0; r < d2.h; r++)
	    for (c = 0; c < d2.w; c++)
	      if (pbm_getpixel (d2.bitmap, c, r))
		pbm_putpixel_trunc (recon, lastx + c, lasty + r, 1, cols, rows);	/* we don't care, already warned them! */
	  lastx += d2.w;
	}

      DecodeChecksum (args[0]);

      /* decode the residue */
      if (!lossy)
	{
	  if (V)
	    fprintf (stderr, "decoding residue...\n");

	  bitmap = pbm_allocarray (cols, rows);
	  d.bitmap = bitmap;
	  d.w = d2.w = cols;
	  d.h = d2.h = rows;

	  d2.bitmap = recon;

	  /* NOTE: the 2nd argument is clairvoyantly compressed */
	  if (splitfilename)
	    {
	      FILE *temp;

	      CloseDownArithDecoding ();
	      fclose (stdin);

	      temp = fopen (splitfilename, "rb");
	      if (temp == NULL)
		error_msg (args[0], "Trouble opening file:", splitfilename);

	      arith_in = temp;
	      InitArithDecoding ();
	      bl_clair_decompress (d, d2);
	      CloseDownArithDecoding ();
	      fclose (temp);
	    }
	  else
	    {
	      bl_clair_decompress (d, d2);
	      DecodeChecksum (args[0]);
	      CloseDownArithDecoding ();
	    }
	  pbm_freearray (&recon, rows);
	  recon = bitmap;	/* point to the bitmap */
	}
      else
	{
	  CloseDownArithDecoding ();
	}

      if (V)
	fprintf (stderr, "writing pbm file...\n");
      setbuf (stdout, bufferout);
      pbm_writefile (stdout, recon, cols, rows);
      pbm_freearray (&recon, rows);
    }				/* end decoding */
}
Esempio n. 13
0
int main(int argc, char *argv[])
{
	int i;
	int ret;
	char input_file[100];
	char output_file[100];
	off_t bs = 1, seek = 0, skip = 0, count = 0;

	assert(argc >= 3);

	for (i = 1; i < argc; i++)
	{
		char c, *p;

		parse_parameter(argv[i]);

		c = para_option[0];
		p = para_option + 1;

		switch (c)
		{
		case 'i':
			if (strcmp(p, "f") == 0)
			{
				strcpy(input_file, para_value);
			}
			else
			{
				goto out_unknown_option;
			}
			break;
		case 'o':
			if (strcmp(p, "f") == 0)
			{
				strcpy(output_file, para_value);
			}
			else
			{
				goto out_unknown_option;
			}
			break;
		case 'b':
			if (strcmp(p, "s") == 0)
			{
				bs = text2size(para_value, NULL);
			}
			else
			{
				goto out_unknown_option;
			}
			break;
		case 's':
			if (strcmp(p, "kip") == 0)
			{
				skip = text2size(para_value, NULL);
			}
			else if (strcmp(p, "eek") == 0)
			{
				seek = text2size(para_value, NULL);
			}
			else
			{
				goto out_unknown_option;
			}
			break;
		case 'c':
			if (strcmp(p, "ount") == 0)
			{
				count = text2size(para_value, NULL);
			}
			else
			{
				goto out_unknown_option;
			}
			break;
		default:
			goto out_unknown_option;
		}
	}

	ret = cavan_dd(input_file, output_file, skip * bs, seek * bs, count * bs);
	if (ret < 0)
	{
		error_msg("cavan_dd");
		return ret;
	}

	return 0;

out_unknown_option:
	error_msg("unknown option \"%s\"", para_option);
	return -EINVAL;
}
Esempio n. 14
0
void Condense_Recur(Bsystem *Bsys, int lev, char trip){
  register int i,j,k;
  Recur *rdata = Bsys->rslv->rdata + lev;
  int    npatch = rdata->npatch, *bwidth_c = rdata->bwidth_c;
  int    csize,asize,bw,info, *pivot;
  double *A, *B, *C;
  double *c, **b;

  for(i = 0; i < npatch; ++i){
    bw = bwidth_c[i] = bandwidth_c(rdata->invc[i],rdata->patchlen_c[i]);

    asize = rdata->patchlen_a[i];
    csize = rdata->patchlen_c[i];

    A = Bsys->rslv->A.a[i];
    B = rdata->binvc[i];
    C = rdata->invc[i];

    /* pack and factor C */

    if(csize){
      if(2*bw < csize)
  c = dvector(0,csize*bw-1);
      else{
  c = dvector(0,csize*(csize+1)/2-1);
  if(trip != 'p')
    pivot = ivector(0,csize-1);
      }

      PackMatrixV (C,csize,c,bw,'l');
      if(trip == 'p') /* positive definite system */
  FacMatrix   (c,csize,bw);
      else{
  FacMatrixSym(c,pivot,csize,bw);
  rdata->pivotc[i] = pivot;
      }

      free(rdata->invc[i]);
      rdata->invc[i]   = C = c;

      if(asize){
  /* copy B into b for A-BCB */
  b = dmatrix(0,asize-1,0,csize-1);
  dcopy(asize*csize,B,1,*b,1);

  /* calc inv(c)*b^T */
  if(trip == 'p'){
    if(2*bw < csize)
      dpbtrs('L',csize,bw-1,asize,C, bw,B,csize,info);
    else
      dpptrs('L',csize,asize,C,B,csize,info);
  }
  else{
    if(2*bw < csize){
      error_msg(error in codense_recur);
    }
    else
      dsptrs('L',csize,asize,C,pivot,B,csize,info);
  }

  /* A - b inv(c) b^T */
  for(j = 0; j < asize; ++j)
    for(k = 0; k < asize; ++k)
      A[j*asize+k] -= ddot(csize,b[j],1,B+k*csize,1);

  free_dmatrix(b,0,0);
      }
    }
  }
}
Esempio n. 15
0
static struct ast_node*
process_matrix(void)
{	
	struct ast_node_stub *stub_node;
	struct ast_node **elem;
	struct ast_node *node;	
	int row, col, len;
	int prev_col;
	int i;

	elem = NULL;
	node = NULL;

	row = col = 1;
	len = prev_col = 0;

	while (TRUE) {
		node = or_expr();

		if (node == NULL) {
			error_msg("expr expected");
			sync_stream();
			goto err;
		}		
		
		elem = urealloc(elem, ++len*sizeof(struct ast_node *));
		elem[len - 1] = node;

		switch(current_token) {
		case TOKEN_COMMA:
			consume_token();
			col++;
			continue;
		case TOKEN_SEMICOLON:
			consume_token();
			if (prev_col == 0)
				prev_col = col;
			else if (prev_col != col) {
				error_msg("incompatible column count");
				sync_stream();
				goto err;
			}
			col = 1;
			row++;
			continue;
		case TOKEN_RBRACKET:
			consume_token();
			break;
		default:
			error_msg("syntax error");
			sync_stream();
			goto err;
		} 
		break;							
	}

	if (row == 1 || col == 1)
		node = (struct ast_node *)ast_node_vector(elem, len);
	else
		node = (struct ast_node *) ast_node_matrix(elem, row, col);

	return node;

err:
	if (node != NULL)
		ast_node_unref(node);
	
	if (elem != NULL) 
		for (i = 0; i < len; i++)
			ast_node_unref(elem[i]);

	stub_node = ast_node_stub();

	return AST_NODE(stub_node);	
}
Esempio n. 16
0
/****************************************************************
*																*
*					ouvre la fenˆtre du tampon					*
*																*
****************************************************************/
void ouvrir_tampon(void)
{
	windowptr thewin = Tampon;
	WIN *win;
	GRECT rect;
	t_win_coord *window;
	int dummy;

	/* demande la taille de la fenˆtre */
	window = get_info(1, Tampon, &rect);

	thewin -> fonction.secteur.couleur_curseur = window -> fonction.texte.curseur_c;
	thewin -> fonction.secteur.trame_curseur = window -> fonction.texte.curseur_t;
	thewin -> fonction.text.couleur_texte = window -> fonction.texte.texte_c;
	thewin -> fonction.text.taille_pt = window -> fonction.texte.texte_pt;
	thewin -> fonction.text.couleur_fond = window -> fonction.texte.background_c;
	thewin -> fonction.text.trame_fond = window -> fonction.texte.background_t;

	/* Create the information for the window.  Max size is the desktop. */
	win = open_window(thewin -> title, thewin -> title, NULL, NULL, window -> type, TRUE, 10, 10, &desk, &rect, NULL, secteurproc, NULL, 0);

	/* Check for error. */
	if (win == NULL)
	{
		error_msg(Z_NO_MORE_WINDOW);
		return;
	}

	if (!open_work(&win -> vdi_handle, work_out))
	{
		my_alert(1, FAIL, X_ICN_STOP, Messages(MAIN_9), NULL);
		close_window(win, FALSE);
		return;
	}

	thewin -> win = win;

	vst_point(win -> vdi_handle, thewin -> fonction.text.taille_pt, &dummy, &dummy, &thewin -> fonction.text.taille_w, &thewin -> fonction.text.taille_h);
	vst_color(win -> vdi_handle, thewin -> fonction.secteur.couleur_texte);
	vsf_interior(win -> vdi_handle, FIS_SOLID);
	vswr_mode(win -> vdi_handle, MD_REPLACE);
	vsf_perimeter(win -> vdi_handle, 0);

	/* Insert into windowlist. */
	{
		register windowptr winptr = (windowptr)&Firstwindow;

		while(winptr -> next)
		{
			winptr = winptr -> next;
			winptr -> place++;
		}
	
		winptr -> next = thewin;
	}

	convert_sect(thewin -> fonction.secteur.secteurBin, thewin -> fonction.text.Ligne, thewin -> fonction.secteur.ascii);

	/* initialise les ascenseurs */
	wind_set(win -> handle, WF_HSLSIZE, (int)(thewin -> win -> work.g_w *1000. / max_w), 0, 0, 0);

	wind_set(win -> handle, WF_VSLSIZE, 1000, 0, 0, 0);
	wind_set(win -> handle, WF_VSLIDE, 1000, 0, 0, 0);

	/* entr‚e dans le menu */
	get_menu_entry(thewin, thewin -> title +1);

	make_frontwin(thewin);

	menu_ienable(Menu, OUVRIR_TAMPON, 0);
	ajoute(Firstwindow, Messages(TAMPON_13));
} /* ouvrir_tampon */
Esempio n. 17
0
static struct ast_node*
function_call(char *name)
{
	struct function *func_ctx;
	struct ast_node_func_call *func_call;
	struct ast_node_stub *stub_node;	
	struct ast_node *arg;
	int nargs = 0;

	func_ctx = function_table_lookup(name);

	consume_token();
	
	if (func_ctx == NULL) {
		error_msg("unknown function");
		sync_stream();
		stub_node = ast_node_stub();
		return AST_NODE(stub_node);	
	}

	func_call = ast_node_func_call(func_ctx->name);

	while (!match(TOKEN_RPARENTH)) {
		if (match(TOKEN_EOL)) {
			error_msg("EOL in function call");
			sync_stream();
			goto free;
			
		}
		
		arg = or_expr();

		if (arg == NULL) {
			error_msg("error: function argument expected");
			sync_stream();
			goto free;
		}
			
		nargs++;

		ast_node_func_call_add_arg(func_call, arg);
		
		if (current_token != TOKEN_RPARENTH && !match(TOKEN_COMMA)) {
			error_msg("error: missed comma");
			sync_stream();
			goto free;
		}				
	}
	
	if (func_ctx->nargs != nargs) {
		error_msg("error: unmatched arguments count");
		sync_stream();
		goto free;
	}

	return AST_NODE(func_call);	
free:
	ast_node_unref(AST_NODE(func_call));	
	stub_node = ast_node_stub();
	return	AST_NODE(stub_node);
}
Esempio n. 18
0
/****************************************************************
*																*
*					cree la fenˆtre du tampon					*
*																*
****************************************************************/
void creer_tampon(void)
{
	register int k;
	register windowptr thewin;

	/* Allocate space for window record. */
	if ((Tampon = (windowptr)malloc(sizeof(windowrec))) == NULL)
		return;

	thewin = Tampon;

	/* Initialize window data structure. */
	thewin -> next = NULL;
	thewin -> kind_c = SIZER | MOVER | FULLER | CLOSER | NAME | UPARROW | DNARROW | VSLIDE | LFARROW | RTARROW | HSLIDE;
	thewin -> type = TAMPON;
	thewin -> menu_entry = FAIL;
	thewin -> place = 0;
	strcpy(thewin -> title, Messages(TAMPON_14));

	if ((thewin -> fonction.tampon.secteurBin = sector_alloc(512)) == NULL)
	{
		free(thewin);
		Tampon = NULL;
		return;
	}

	if ((thewin -> fonction.tampon.Text = malloc((size_t)SECTEURSIZE)) == NULL)
	{
		error_msg(Z_NOT_ENOUGH_MEMORY);
		free(thewin -> fonction.tampon.secteurBin);
		free(thewin);
		Tampon = NULL;
		return;
	}

	if ((thewin -> fonction.tampon.Ligne = (char **)malloc((size_t)SECTEURLINE * sizeof(char *))) == NULL)
	{
		error_msg(Z_NOT_ENOUGH_MEMORY);
		free(thewin -> fonction.tampon.secteurBin);
		free(thewin -> fonction.tampon.Text);
		free(thewin);
		Tampon = NULL;
		return;
	}

	/* le bloc contient d‚ja toutes les lignes remplies */
	thewin -> fonction.tampon.TextSize = SECTEURSIZE;
	thewin -> fonction.tampon.LineNumberMax = SECTEURLINE;
	thewin -> fonction.tampon.LineNumber = SECTEURLINE-2;
	thewin -> fonction.tampon.CurrentLine = SECTEURLINE-2;
	thewin -> fonction.tampon.taille_pt = gr_ch == 8 ? 9 : 10;
	thewin -> fonction.tampon.taille_w = gr_cw;
	thewin -> fonction.tampon.taille_h = gr_ch;
	thewin -> fonction.tampon.PrintLine = SECTEURLINE-3;
	thewin -> fonction.tampon.ligne = SECTEURLINE-3;
	thewin -> fonction.tampon.colonne = 0;

	/* chaque ligne … 0 */
	*thewin -> fonction.tampon.Text = '\0';

	for (k=1; k<SECTEURLINE; k++)	/* la premiŠre ligne est deux fois plus grande */
		thewin -> fonction.tampon.Text[(k+1) * SECTEURLINESIZE] = '\0';

	/* un pointeur sur chaque ligne */
	thewin -> fonction.tampon.Ligne[0] = thewin -> fonction.tampon.Text;

	for (k=1; k<SECTEURLINE; k++)
		thewin -> fonction.tampon.Ligne[k] = &thewin -> fonction.tampon.Text[(k+1) * SECTEURLINESIZE];

	thewin -> fonction.tampon.ascii = TRUE;
	thewin -> fonction.tampon.curseur_x = thewin -> fonction.tampon.curseur_y = FAIL;
	thewin -> fonction.tampon.page = 0;

	/* les champs suivant ne sont pas utilis‚ mais sont initialis‚s quand mˆme au cas ou... */
	thewin -> fonction.tampon.dirty = FALSE;
	thewin -> fonction.tampon.slide = NULL;
	thewin -> fonction.tampon.goto_liste = NULL;
	thewin -> fonction.tampon.max = 1;
	thewin -> fonction.tampon.secteur = 0;
	thewin -> fonction.tampon.sector_size = 1;

	/* secteur … 0 */
	memset(thewin -> fonction.tampon.secteurBin, 0, 512L);

	strncpy(thewin -> fonction.tampon.Ligne[0], "  Tampon", SECTEURLINESIZE*2);
	strncpy(thewin -> fonction.tampon.Ligne[1], "      0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1", SECTEURLINESIZE);
	strncpy(thewin -> fonction.tampon.Ligne[2], "      0 1 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 A B C D E F", SECTEURLINESIZE);
	strncpy(thewin -> fonction.tampon.Ligne[3], "                                                                    ", SECTEURLINESIZE);
	strncpy(thewin -> fonction.tampon.Ligne[4], "0000  ", SECTEURLINESIZE);
	strncpy(thewin -> fonction.tampon.Ligne[5], "0020  ", SECTEURLINESIZE);
	strncpy(thewin -> fonction.tampon.Ligne[6], "0040  ", SECTEURLINESIZE);
	strncpy(thewin -> fonction.tampon.Ligne[7], "0060  ", SECTEURLINESIZE);
	strncpy(thewin -> fonction.tampon.Ligne[8], "0080  ", SECTEURLINESIZE);
	strncpy(thewin -> fonction.tampon.Ligne[9], "00A0  ", SECTEURLINESIZE);
	strncpy(thewin -> fonction.tampon.Ligne[10], "00C0  ", SECTEURLINESIZE);
	strncpy(thewin -> fonction.tampon.Ligne[11], "00E0  ", SECTEURLINESIZE);
	strncpy(thewin -> fonction.tampon.Ligne[12], "0100  ", SECTEURLINESIZE);
	strncpy(thewin -> fonction.tampon.Ligne[13], "0120  ", SECTEURLINESIZE);
	strncpy(thewin -> fonction.tampon.Ligne[14], "0140  ", SECTEURLINESIZE);
	strncpy(thewin -> fonction.tampon.Ligne[15], "0160  ", SECTEURLINESIZE);
	strncpy(thewin -> fonction.tampon.Ligne[16], "0180  ", SECTEURLINESIZE);
	strncpy(thewin -> fonction.tampon.Ligne[17], "01A0  ", SECTEURLINESIZE);
	strncpy(thewin -> fonction.tampon.Ligne[18], "01C0  ", SECTEURLINESIZE);
	strncpy(thewin -> fonction.tampon.Ligne[19], "01E0  ", SECTEURLINESIZE);
} /* creer_tampon */
Esempio n. 19
0
File: step.c Progetto: AkaBlood/ogs5
/* ---------------------------------------------------------------------- */
int
add_surface (struct surface *surface_ptr)
/* ---------------------------------------------------------------------- */
{
/*
 *   Accumulate surface data in master->totals and _x variables.
 */
  int i, j;
  struct master *master_ptr;

  if (surface_ptr == NULL)
    return (OK);
/*
 *   Add element concentrations on surface to master species totals
 */
  dl_type_x = surface_ptr->dl_type;
  for (i = 0; i < surface_ptr->count_comps; i++)
  {
    /*if(surface_ptr->edl == FALSE) { */
    if (surface_ptr->type == NO_EDL)
    {
      cb_x += surface_ptr->comps[i].cb;
    }
#ifdef SKIP_MUSIC
    if (surface_ptr->type == CD_MUSIC)
    {
      cb_x += surface_ptr->comps[i].cb;
    }
#endif
    if (surface_ptr->new_def == FALSE)
    {
      surface_ptr->comps[i].master->s->la = surface_ptr->comps[i].la;
    }
/*
 *   Add surface and specifically sorbed elements
 */
    for (j = 0; surface_ptr->comps[i].totals[j].elt != NULL; j++)
    {
      master_ptr = surface_ptr->comps[i].totals[j].elt->primary;
      if (master_ptr == NULL)
      {
	input_error++;
	sprintf (error_string, "Element not defined in database, %s.",
		 surface_ptr->comps[i].totals[j].elt->name);
	error_msg (error_string, STOP);
      }
      if (master_ptr->s == s_hplus)
      {
	total_h_x += surface_ptr->comps[i].totals[j].coef;
      }
      else if (master_ptr->s == s_h2o)
      {
	total_o_x += surface_ptr->comps[i].totals[j].coef;
      }
      else
      {
	master_ptr->total += surface_ptr->comps[i].totals[j].coef;
      }
    }
  }
  /*if (surface_ptr->edl == FALSE) return(OK); */
  if (surface_ptr->type != DDL && surface_ptr->type != CD_MUSIC)
    return (OK);
  for (i = 0; i < surface_ptr->count_charge; i++)
  {
    /*if (surface_ptr->edl == TRUE) { */
    /*cb_x += surface_ptr->charge[i].charge_balance; */
    if (surface_ptr->type == DDL || surface_ptr->type == CD_MUSIC)
    {
      cb_x += surface_ptr->charge[i].charge_balance;
    }
    if (surface_ptr->new_def == FALSE)
    {
      master_ptr =
	surface_get_psi_master (surface_ptr->charge[i].name, SURF_PSI);
      master_ptr->s->la = surface_ptr->charge[i].la_psi;
      /*surface_ptr->charge[i].psi_master->s->la = surface_ptr->charge[i].la_psi; */
    }
/*
 *   Add diffuse layer elements (including water in Debye layer)
 */
    if (surface_ptr->dl_type != NO_DL && surface_ptr->new_def == FALSE)
    {
      for (j = 0; surface_ptr->charge[i].diffuse_layer_totals[j].elt != NULL;
	   j++)
      {
	master_ptr =
	  surface_ptr->charge[i].diffuse_layer_totals[j].elt->primary;
	if (master_ptr->s == s_hplus)
	{
	  total_h_x += surface_ptr->charge[i].diffuse_layer_totals[j].coef;
	}
	else if (master_ptr->s == s_h2o)
	{
	  total_o_x += surface_ptr->charge[i].diffuse_layer_totals[j].coef;
	}
	else
	{
	  master_ptr->total +=
	    surface_ptr->charge[i].diffuse_layer_totals[j].coef;
	}
      }
    }
  }
  return (OK);
}
Esempio n. 20
0
/****************************************************************
*																*
*				Sauvegarde dans le ClipBoard					*
*																*
****************************************************************/
void copier_clipboard(windowptr thewin, char *scrap_path)
{
	FILE *fd;
	char scrap_file[FILENAME_MAX];
	int format = FAIL;
	long best_ext;

	scrp_clear(FALSE);

	/* fichier BINAIRE */
	if (thewin -> type >= TAMPON)
	{
		/* le fichier en binaire */
		strcpy(scrap_file, scrap_path);
		strcat(scrap_file, "SCRAP.BIN");

		/* cr‚ation du fichier */
		if ((fd = fopen(scrap_file, "wb")) == NULL)
		{
			error_msg(Z_CLIPBOARD_NOT_INSTALLED);
			return;
		}

		/* ‚criture du fichier */
		fwrite(thewin -> fonction.secteur.page*512L + thewin -> fonction.secteur.secteurBin, 512L, 1L, fd);

		/* fermeture */
		fclose(fd);

		format = SCF_INDEF;
		best_ext = '.BIN';
	}

	/* fichier TEXTE */
	if (thewin -> type >= TEXT)
	{
		int current, ligne, len, i;
		char buffer[255];

		/* le fichier en binaire */
		strcpy(scrap_file, scrap_path);
		strcat(scrap_file, "SCRAP.TXT");

		/* cr‚ation du fichier */
		if ((fd = fopen(scrap_file, "w")) == NULL)
		{
			error_msg(Z_CANT_CREATE_SCRAP);
			return;
		}

		/* un petit message de bienvenue */
		fprintf(fd, "ZORG realised by Ludovic Rousseau\nCopyright 1993-95\n\n");

		/* on ‚crite d'abord le titre de la fenˆtre */
		fprintf(fd, "%s\n", thewin -> title);

		/* la ligne d'info si elle existe */
		if (thewin -> win -> gadgets & INFO)
			fprintf(fd, "%s\n", thewin -> win -> info);
		
		current = thewin -> fonction.text.CurrentLine;
		for (ligne = 0; ligne < thewin -> fonction.text.LineNumber; ligne++)
			current = current > 0 ? current-1 : thewin -> fonction.text.LineNumberMax-1;

		/* ‚criture du fichier */
		for (ligne = 0; ligne < thewin -> fonction.text.LineNumber; ligne++)
		{
			len = sprintf(buffer, "%s\n", thewin -> fonction.text.Ligne[current]);
			for (i=0; i<len-1; i++)
				if (buffer[i] == 0x0A || buffer[i] == 0x0D || buffer[i] == 0x09)
					buffer[i] = ZeroChar;

			fwrite(buffer, (long)len, 1L, fd);

			current = current < thewin -> fonction.text.LineNumberMax-1 ? current+1 : 0;
		}

		/* fermeture */
		fclose(fd);

		format = SCF_TEXT;
		best_ext = '.TXT';
	}

	if (format > FAIL)
		scrp_changed(format, best_ext);
} /* copier_clipboard */
Esempio n. 21
0
static Geometry *loadGeom (char *name){
  const int verbose = option("verbose");
  Geometry *g   = (Geometry *) calloc (1, sizeof(Geometry));
  char      buf [BUFSIZ];
  double    tmp[_MAX_NC];
  Point     p1, p2, p3, p4;
  FILE     *fp;
  register  int i;

  if (verbose > 1)
    printf ("Loading geometry file %s...", name);
  if ((fp = fopen(name, "r")) == (FILE *) NULL) {
    fprintf (stderr, "couldn't find the curved-side file %s", name);
    exit (-1);
  }

  while (fgets (buf, BUFSIZ, fp))    /* Read past the comments */
    if (*buf != '#') break;

  /* Allocate space for the coordinates */

  g -> x = (double*) calloc (_MAX_NC, sizeof(double));
  g -> y = (double*) calloc (_MAX_NC, sizeof(double));

  strcpy (g->name = (char *) malloc (strlen(name)+1), name);

  /* Read the coordinates.  The first line is already in *
   * the input buffer from the comment loop above.       */

  i = 0;
  while (i <= _MAX_NC && sscanf (buf,"%lf%lf", g->x + i, g->y + i) == 2) {
    i++;
    if (!fgets(buf, BUFSIZ, fp)) break;
  }
  g->npts = i;

  if (i < 2 ) error_msg (geometry file does not have enough points);

  if (i > _MAX_NC) error_msg (geometry file has too many points);

  if (verbose > 1) printf ("%d points", g->npts);

  /* Allocate memory for the other quantities */

  g->sx     = (double*) calloc (g->npts, sizeof(double));
  g->sy     = (double*) calloc (g->npts, sizeof(double));
  g->arclen = (double*) calloc (g->npts, sizeof(double));

  /* Compute spline information for the (x,y)-coordinates.  The vector "tmp"
     is a dummy independent variable for the function x(eta), y(eta).  */

  tmp[0] = 0.;
  tmp[1] = 1.;
  dramp  (g->npts, tmp, tmp + 1, tmp, 1);
  spline (g->npts, 1.e30, 1.e30, tmp, g->x, g->sx);
  spline (g->npts, 1.e30, 1.e30, tmp, g->y, g->sy);

  /* Compute the arclength of the curve using 4 points per segment */

  for (i = 0; i < (*g).npts-1; i++) {
    p1 = setPoint (g->x[i], g->y[i] );
    p2 = setPoint (splint (g->npts, i+.25, tmp, g->x, g->sx),
       splint (g->npts, i+.25, tmp, g->y, g->sy));
    p3 = setPoint (splint (g->npts, i+.75, tmp, g->x, g->sx),
       splint (g->npts, i+.75, tmp, g->y, g->sy));
    p4 = setPoint (g->x[i+1], g->y[i+1]);

    g->arclen [i+1] = g->arclen[i] + distance (p1, p2) + distance (p2, p3) +
                                     distance (p3, p4);
  }

  /* Now that we have the arclength, compute x(s), y(s) */

  spline (g->npts, 1.e30, 1.e30, g->arclen, g->x, g->sx);
  spline (g->npts, 1.e30, 1.e30, g->arclen, g->y, g->sy);

  if (verbose > 1)
    printf (", arclength  = %f\n", g->arclen[i]);


  /* add to the list of geometries */

  g ->next = geomlist;
  geomlist = g;

  fclose (fp);
  return g;
}
Esempio n. 22
0
/* ---------------------------------------------------------------------- */
int Phreeqc::
advection(void)
/* ---------------------------------------------------------------------- */
{
	int i;
	LDBLE kin_time;
/*
 *   Calculate advection
 */
	state = ADVECTION;
/*	mass_water_switch = TRUE; */
/*
 *   Check existence of all solutions
 */
	for (i = 0; i <= count_ad_cells; i++)
	{
		if (Utilities::Rxn_find(Rxn_solution_map, i) == NULL)
		//if (solution_bsearch(i, &n, TRUE) == NULL)
		{
			input_error++;
			error_string = sformatf(
					"Solution %d is needed for advection, but is not defined.",
					i);
			error_msg(error_string, CONTINUE);
		}
	}
/*
 *   Check kinetics logic
 */
	kin_time = advection_kin_time;
	if (kin_time <= 0.0)
	{
		for (i = 1; i <= count_ad_cells; i++)
		{
			if (Utilities::Rxn_find(Rxn_kinetics_map, i) != NULL)
			{
				input_error++;
				error_string = sformatf(
						"KINETIC reaction(s) defined, but time_step is not defined in ADVECTION keyword.");
				error_msg(error_string, CONTINUE);
				break;
			}
		}
	}
/*
 *   Quit on error
 */
	if (get_input_errors() > 0)
	{
		error_msg("Program terminating due to input errors.", STOP);
	}
/*
 *   Equilibrate solutions with phases, exchangers, surfaces
 */
	last_model.force_prep = TRUE;
	rate_sim_time_start = 0;
	for (advection_step = 1; advection_step <= count_ad_shifts;
		 advection_step++)
	{
		log_msg(sformatf(
				   "\nBeginning of advection time step %d, cumulative pore volumes %f.\n",
				   advection_step,
				   (double) (((LDBLE) advection_step) /
							 ((LDBLE) count_ad_cells))));
		if (pr.use == TRUE && pr.all == TRUE)
		{
			output_msg(sformatf(
					   "Beginning of advection time step %d, cumulative pore volumes %f.\n",
					   advection_step,
					   (double) (((LDBLE) advection_step) /
								 ((LDBLE) count_ad_cells))));
		}
/*
 *  Advect
 */
		for (i = count_ad_cells; i > 0; i--)
		{
			//solution_duplicate(i - 1, i);
			Utilities::Rxn_copy(Rxn_solution_map, i -1, i);
		}
/*
 *  Equilibrate and (or) mix
 */
		for (i = 1; i <= count_ad_cells; i++)
		{
			set_initial_moles(i);
			cell_no = i;
			set_advection(i, TRUE, TRUE, i);
			run_reactions(i, kin_time, TRUE, 1.0);
			if (advection_kin_time_defined == TRUE)
			{
				rate_sim_time = rate_sim_time_start + kin_time;
			}
			log_msg(sformatf( "\nCell %d.\n\n", i));
			if (pr.use == TRUE && pr.all == TRUE &&
				advection_step % print_ad_modulus == 0 &&
				advection_print[i - 1] == TRUE)
			{
				output_msg(sformatf( "\nCell %d.\n\n", i));
			}
			if (advection_step % punch_ad_modulus == 0 &&
				advection_punch[i - 1] == TRUE)
			{
				punch_all();
			}
			if (advection_step % print_ad_modulus == 0 &&
				advection_print[i - 1] == TRUE)
			{
				print_all();
			}
			if (i > 1)
				Utilities::Rxn_copy(Rxn_solution_map, -2, i - 1);
				//solution_duplicate(-2, i - 1);
			saver();
		}
		Utilities::Rxn_copy(Rxn_solution_map, -2, count_ad_cells);
		//solution_duplicate(-2, count_ad_cells);
		rate_sim_time_start += kin_time;
	}
	initial_total_time += rate_sim_time_start;
	/* free_model_allocs(); */
	mass_water_switch = FALSE;
	return (OK);
}
Esempio n. 23
0
int
background_and_wait_for_errors(char cmd[], int cancellable)
{
#ifndef _WIN32
	pid_t pid;
	int error_pipe[2];
	int result = 0;

	if(pipe(error_pipe) != 0)
	{
		error_msg("File pipe error", "Error creating pipe");
		return -1;
	}

	(void)set_sigchld(1);

	if((pid = fork()) == -1)
	{
		(void)set_sigchld(0);
		return -1;
	}

	if(pid == 0)
	{
		(void)set_sigchld(0);
		run_from_fork(error_pipe, 1, cmd);
	}
	else
	{
		char buf[80*10];
		char linebuf[80];
		int nread = 0;

		close(error_pipe[1]); /* Close write end of pipe. */

		if(cancellable)
		{
			ui_cancellation_enable();
		}

		wait_for_data_from(pid, NULL, error_pipe[0]);

		buf[0] = '\0';
		while((nread = read(error_pipe[0], linebuf, sizeof(linebuf) - 1)) > 0)
		{
			const int read_empty_line = nread == 1 && linebuf[0] == '\n';
			result = -1;
			linebuf[nread] = '\0';

			if(!read_empty_line)
			{
				strncat(buf, linebuf, sizeof(buf) - strlen(buf) - 1);
			}

			wait_for_data_from(pid, NULL, error_pipe[0]);
		}
		close(error_pipe[0]);

		if(cancellable)
		{
			ui_cancellation_disable();
		}

		if(result != 0)
		{
			error_msg("Background Process Error", buf);
		}
		else
		{
			/* Don't use "const int" variables with WEXITSTATUS() as they cause
			 * compilation errors in case __USE_BSD is defined.  Anonymous type with
			 * "const int" is composed via compound literal expression. */
			int status = get_proc_exit_status(pid);
			result = (status != -1 && WIFEXITED(status)) ? WEXITSTATUS(status) : -1;
		}
	}

	(void)set_sigchld(0);

	return result;
#else
	return -1;
#endif
}
Esempio n. 24
0
static
int read_info(const char *filename, pack_opt_t *options) {

	char stype[10];
	char comp_info[1024];
	FILE *fp = NULL;
	char c;
	int i, rc = 1;
	int ret_value = EXIT_SUCCESS;

	if ((fp = HDfopen(filename, "r")) == (FILE *) NULL) {
		error_msg("cannot open options file %s\n", filename);
		h5tools_setstatus(EXIT_FAILURE);
		ret_value = EXIT_FAILURE;
		goto done;
	}

	/* cycle until end of file reached */
	while (1) {
		rc = fscanf(fp, "%s", stype);
		if (rc == -1)
			break;

		/*-------------------------------------------------------------------------
		 * filter
		 *-------------------------------------------------------------------------
		 */
		if (HDstrcmp(stype,"-f") == 0) {
			/* find begining of info */
			i = 0;
			c = '0';
			while (c != ' ') {
				fscanf(fp, "%c", &c);
				if (HDfeof(fp))
					break;
			}
			c = '0';
			/* go until end */
			while (c != ' ') {
				fscanf(fp, "%c", &c);
				comp_info[i] = c;
				i++;
				if (HDfeof(fp))
					break;
				if (c == 10 /*eol*/)
					break;
			}
			comp_info[i - 1] = '\0'; /*cut the last " */

			if (h5repack_addfilter(comp_info, options) == -1) {
				error_msg("could not add compression option\n");
				h5tools_setstatus(EXIT_FAILURE);
				ret_value = EXIT_FAILURE;
				goto done;
			}
		}
		/*-------------------------------------------------------------------------
		 * layout
		 *-------------------------------------------------------------------------
		 */
		else if (HDstrcmp(stype,"-l") == 0) {

			/* find begining of info */
			i = 0;
			c = '0';
			while (c != ' ') {
				fscanf(fp, "%c", &c);
				if (HDfeof(fp))
					break;
			}
			c = '0';
			/* go until end */
			while (c != ' ') {
				fscanf(fp, "%c", &c);
				comp_info[i] = c;
				i++;
				if (HDfeof(fp))
					break;
				if (c == 10 /*eol*/)
					break;
			}
			comp_info[i - 1] = '\0'; /*cut the last " */

			if (h5repack_addlayout(comp_info, options) == -1) {
				error_msg("could not add chunck option\n");
				h5tools_setstatus(EXIT_FAILURE);
				ret_value = EXIT_FAILURE;
				goto done;
			}
		}
		/*-------------------------------------------------------------------------
		 * not valid
		 *-------------------------------------------------------------------------
		 */
		else {
			error_msg("bad file format for %s", filename);
			h5tools_setstatus(EXIT_FAILURE);
			ret_value = EXIT_FAILURE;
			goto done;
		}
	}

done:
	if (fp)
		HDfclose(fp);

	return ret_value;
}
Esempio n. 25
0
int main() {
    unsigned long T = 0L;
    int Ival;
    U8 rb, Num;

    CFG_GCR |= 1; // disable SWIM

    // Configure clocking
    CLK_CKDIVR = 0; // F_HSI = 16MHz, f_CPU = 16MHz

    // Timer 4 (8 bit) used as system tick timer
    // prescaler == 128 (2^7), Tfreq = 125kHz
    // period = 1ms, so ARR = 125
    TIM4_PSCR = 7;
    TIM4_ARR = 125;
    // interrupts: update
    TIM4_IER = TIM_IER_UIE;
    // auto-reload + interrupt on overflow + enable
    TIM4_CR1 = TIM_CR1_APRE | TIM_CR1_URS | TIM_CR1_CEN;

    // Configure pins
    // PC2 - PP output (on-board LED)
    PORT(LED_PORT, DDR) |= LED_PIN;
    PORT(LED_PORT, CR1) |= LED_PIN;
    // PD5 - UART2_TX -- pseudo open-drain output; don't forget an pullup resistor!
    PORT(UART_PORT, DDR) |= UART_TX_PIN;
    PORT(UART_PORT, ODR) |= UART_TX_PIN; // torn off N push-down ???
    //PORT(UART_PORT, CR1) |= UART_TX_PIN;

    // Configure UART
    // 9 bit, no parity, 1 stop (UART_CR3 = 0 - reset value)
    // 57600 on 16MHz: BRR1=0x11, BRR2=0x06
    UART2_BRR1 = 0x11; UART2_BRR2 = 0x06;
    UART2_CR1  = UART_CR1_M; // M = 1 -- 9bits
    UART2_CR2  = UART_CR2_REN | UART_CR2_RIEN; // Allow RX, generate ints on rx

    setup_stepper_pins();


    // enable all interrupts
    enableInterrupts();
    // Loop
    do{
        if((Global_time - T > paused_val) || (T > Global_time)){
            T = Global_time;
            PORT(LED_PORT, ODR) ^= LED_PIN; // blink on-board LED
        }
        if(UART_read_byte(&rb)){ // buffer isn't empty
            switch(rb){
                case 'h': // help
                case 'H':
                    uart_write("\nPROTO:\n"
                        "+/-\tLED period\n"
                        "Ex/ex\tset/get end-switches stored\n"
                        "p\tget HW end-switches\n"
                        "Mx\tstop on end-switch\n"
                        "Sx/sx\tset/get Mspeed\n"
                        "mx\tget steps\n"
                        "Px\tpause/resume\n"
                        "Xx\tstop\n"
                        "0..2N\tmove xth motor for N steps\n"
                        "=\tinfinity moving (after 0..2)"
                        "U/u\tset/get U-stepping\n"
                        "I\tget serial ID\n"
                        "N\tchange HW number\n"
                        "n\tshow HW number\n"
                        );
                break;
                case 'I': // get serial id
                    show_uid();
                break;
                case '+':
                    paused_val += 100;
                    if(paused_val > 10000)
                        paused_val = 500; // but not more than 10s
                break;
                case '-':
                    paused_val -= 100;
                    if(paused_val < 100)  // but not less than 0.1s
                        paused_val = 500;
                break;
                case 'E': // set end-switches value
                    if(get_motor_number(&Num)){
                        if(readInt(&Ival) && (Ival == (Ival & 0x1f))){
                            if(Num)
                                EPs[Num] = Ival & 0x0f; // 4 bits in motors 1&2
                            else
                                EPs[0] = Ival; // all 5 bits in motor 0
                        }else
                            error_msg("bad EP");
                    }
                break;
                case 'e': // get stored end-switches value
                    if(get_motor_number(&Num)){
                        printUint(&EPs[Num], 1);
                    }
                break;
                case 'p': // get hardware end-switches value
                    if(get_motor_number(&Num)){
                        Num = get_ep_value(Num);
                        printUint(&Num, 1);
                    }
                break;
                case 'S': // set stepper speed
                    if(get_motor_number(&Num)){
                        if(readInt(&Ival) && Ival > MIN_STEP_LENGTH)
                            set_stepper_speed(Num, Ival);
                        else
                            error_msg("bad speed");
                    }
                break;
                case 's': // get stepper speed
                    if(get_motor_number(&Num))
                        printUint((U8*)&Stepper_speed[Num], 2);
                break;
                case 'M': // move till EP, you can call it before starting motor
                    if(get_motor_number(&Num))
                        Stop_on_EP[Num] = 1;
                break;
                case 'm': // how much steps there is to the end of moving
                    if(get_motor_number(&Num))
                        printUint((U8*)&Nsteps[Num], 2);
                break;
                case 'X': // stop
                    if(get_motor_number(&Num))
                        stop_motor(Num);
                break;
                case 'P': // pause/resume
                    if(get_motor_number(&Num))
                        pause_resume(Num);
                break;
                case 'N':
                    if(readInt(&Ival) && Ival > 0 && Ival < 256)
                        if(!change_progmem_value(&UART_devNUM, (unsigned int) Ival))
                            error_msg("can't change val");
                break;
                case 'n': // show HW num
                    printUint(&UART_devNUM, 1);
                break;
                case 'u': // show UStepping
                    printUint(&USteps, 1);
                break;
                case 'U': // set UStepping
                    if(readInt(&Ival) && Ival > 0 && Ival < 256)
                        USteps = Ival;
                break;
                case '=': // infinity moving: just don't decrement steps
                    StepperInfty = 1;
                break;
                default:
                    if(rb >= '0' && rb <= '2'){ // run motor
                        Num = rb - '0';
                        if(readInt(&Ival) && Ival)
                            move_motor(Num, Ival);
                        else{
                            error_msg("bad Nsteps");
                        }
                    }
            }
        }
    }while(1);
}
Esempio n. 26
0
static
int parse_command_line(int argc, const char **argv, pack_opt_t* options) {

	int opt;
	int ret_value = 0;

	/* parse command line options */
	while ((opt = get_option(argc, argv, s_opts, l_opts)) != EOF) {
		switch ((char) opt) {

		/* -i for backward compability */
		case 'i':
			infile = opt_arg;
			has_i_o = 1;
			break;

			/* -o for backward compability */
		case 'o':
			outfile = opt_arg;
			has_i_o = 1;
			break;

		case 'h':
			usage(h5tools_getprogname());
			h5tools_setstatus(EXIT_SUCCESS);
			ret_value = -1;
			goto done;

		case 'V':
			print_version(h5tools_getprogname());
			h5tools_setstatus(EXIT_SUCCESS);
			ret_value = -1;
			goto done;

		case 'v':
			options->verbose = 1;
			break;

		case 'f':
			/* parse the -f filter option */
			if (h5repack_addfilter(opt_arg, options) < 0) {
				error_msg("in parsing filter\n");
				h5tools_setstatus(EXIT_FAILURE);
				ret_value = -1;
				goto done;
			}
			break;

		case 'l':
			/* parse the -l layout option */
			if (h5repack_addlayout(opt_arg, options) < 0) {
				error_msg("in parsing layout\n");
				h5tools_setstatus(EXIT_FAILURE);
				ret_value = -1;
				goto done;
			}
			break;

		case 'm':
			options->min_comp = HDatoi( opt_arg );
			if ((int) options->min_comp <= 0) {
				error_msg("invalid minimum compress size <%s>\n", opt_arg);
				h5tools_setstatus(EXIT_FAILURE);
				ret_value = -1;
				goto done;
			}
			break;

		case 'e':
			ret_value = read_info(opt_arg, options);
			if (ret_value < 0)
				goto done;
			break;

		case 'n':
			options->use_native = 1;
			break;

		case 'L':
			options->latest = 1;
			break;

		case 'c':
			options->grp_compact = HDatoi( opt_arg );
			if (options->grp_compact > 0)
				options->latest = 1; /* must use latest format */
			break;

		case 'd':
			options->grp_indexed = HDatoi( opt_arg );
			if (options->grp_indexed > 0)
				options->latest = 1; /* must use latest format */
			break;

		case 's':
			{
				int idx = 0;
				int ssize = 0;
				char *msgPtr = HDstrchr( opt_arg, ':');
				options->latest = 1; /* must use latest format */
				if (msgPtr == NULL) {
					ssize = HDatoi( opt_arg );
					for (idx = 0; idx < 5; idx++)
						options->msg_size[idx] = ssize;
				}
				else {
					char msgType[10];
					HDstrcpy(msgType, msgPtr + 1);
					msgPtr[0] = '\0';
					ssize = HDatoi( opt_arg );
					if (HDstrncmp(msgType, "dspace",6) == 0) {
						options->msg_size[0] = ssize;
					}
					else if (HDstrncmp(msgType, "dtype", 5) == 0) {
						options->msg_size[1] = ssize;
					}
					else if (HDstrncmp(msgType, "fill", 4) == 0) {
						options->msg_size[2] = ssize;
					}
					else if (HDstrncmp(msgType, "pline", 5) == 0) {
						options->msg_size[3] = ssize;
					}
					else if (HDstrncmp(msgType, "attr", 4) == 0) {
						options->msg_size[4] = ssize;
					}
				}
			}
			break;

		case 'u':
			options->ublock_filename = opt_arg;
			break;

		case 'b':
			options->ublock_size = (hsize_t) HDatol( opt_arg );
			break;

		case 'M':
			options->meta_block_size = (hsize_t) HDatol( opt_arg );
			break;

		case 't':
			options->threshold = (hsize_t) HDatol( opt_arg );
			break;

		case 'a':
			options->alignment = HDatol( opt_arg );
			if (options->alignment < 1) {
				error_msg("invalid alignment size\n", opt_arg);
				h5tools_setstatus(EXIT_FAILURE);
				ret_value = -1;
				goto done;
			}
			break;

		default:
			break;
		} /* switch */

	} /* while */

	if (has_i_o == 0) {
		/* check for file names to be processed */
		if (argc <= opt_ind || argv[opt_ind + 1] == NULL) {
			error_msg("missing file names\n");
			usage(h5tools_getprogname());
			h5tools_setstatus(EXIT_FAILURE);
			ret_value = -1;
		}
	}

done:
	return ret_value;
}
Esempio n. 27
0
int
main(int argc, char *argv[])
{
	char *conf_file = NULL;
	char *conf_dir = NULL;
	int c;

	setlocale(LC_ALL, "");
	bindtextdomain(PACKAGE, LOCALEDIR);
	textdomain(PACKAGE);

	set_program_name(&program_name, argv[0]);

	while ((c = getopt(argc, argv, "hf:d:")) != -1) {
		switch (c) {
		case 'f':
			conf_file = optarg;
			break;
		case 'd':
			conf_dir = optarg;
			break;
		case 'h':
			usage(EXIT_SUCCESS);
			break;
		default:
			fprintf(stderr, _("ERROR: no valid argument\n"));
			usage(EXIT_FAILURE);
		}
	}

	if (atexit(cleanup) != 0)
		exit(EXIT_FAILURE);

	if (conf_file == NULL)
		usage(EXIT_FAILURE);

        /*
	 * init non-gtk stuff
	 */
	git_libgit2_init();
	curl_global_init(CURL_GLOBAL_ALL);

	if (read_complete_config(conf_file, conf_dir) == 0) {
		info_msg(_("Init main sdk_config done"));
	} else {
		error_msg(_("Possible init problem: read_complete_config != 0"));
		usage(EXIT_FAILURE);
	}

	if ((is_this_a_dir(get_common_workdir()) == false) ||
	    (is_this_a_dir(get_common_workdir()) == false))
		usage(EXIT_FAILURE);

	if ((read_checksum_file()) == 0)
		info_msg(_("Read checksum file done"));
	else
		info_msg(_("%s not available or not valid"),
			 NAME_CHECKSUM_FILE);

	/*
	 * init gtk stuff
	 */
	if (!g_thread_supported())
		g_thread_init(NULL);

	gdk_threads_init();
	gdk_threads_enter();

	gtk_init(&argc, &argv);
	build_main_window();

	// lock unused buttons/menus -> not yet implemented
	lock_unused_buttons();

	/*
	 * check for some defaults to control the gui
	 */
	check_all_states();

	/*
	 * show some useful info
	 */
	show_all_infos();

	// beginn trash

	/*
	 *
	 */

	// end trash

	gtk_main();
	gdk_threads_leave();

	git_libgit2_shutdown();

	return EXIT_SUCCESS;
}
Esempio n. 28
0
static struct ast_node*
for_expr(void *opaque)
{
	struct ast_node_for *for_node;
	struct ast_node_stub *stub_node;
	struct ast_node *expr1;
	struct ast_node *expr2;
	struct ast_node *expr3;
	struct ast_node *_stmt;
	struct scope_ctx helper;

	if (!match(TOKEN_LPARENTH)) {
		error_msg("error: `(' expected after for");
		sync_stream();
		stub_node = ast_node_stub();
		return AST_NODE(stub_node);
	}
	
	expr1 = expr();
	
	if (!match(TOKEN_SEMICOLON)) {
		error_msg("error: `;' expected after for(");
		sync_stream();
		stub_node = ast_node_stub();
		return AST_NODE(stub_node);
	}
	
	expr2 = or_expr();

	if (!match(TOKEN_SEMICOLON)) {
		error_msg("error: `;' expected after for(;");
		sync_stream();
		stub_node = ast_node_stub();
		return AST_NODE(stub_node);
	}	
	
	expr3 = expr();
		
	if (!match(TOKEN_RPARENTH)) {
		error_msg("error: `)' expected after for(;;");
		sync_stream();
		stub_node = ast_node_stub();
		return AST_NODE(stub_node);
	}
	
	if (opaque) {
		helper = *(struct scope_ctx *)opaque;
		helper.is_cycle++;
	} else {	
		memset(&helper, 0, sizeof(helper));
		helper.is_cycle++;
	}

	_stmt = stmt(&helper);
	
	if (_stmt == NULL) {
		error_msg("error: stmt expected after for(;;)");
		sync_stream();
		stub_node = ast_node_stub();
		return AST_NODE(stub_node);
	}
	
	for_node = ast_node_for(expr1, expr2, expr3, _stmt);
	
	helper.is_cycle--;

	return AST_NODE(for_node);
}
Esempio n. 29
0
obj_list_t* parse_filter(const char *str,
                         int *n_objs,
                         filter_info_t *filt,
                         pack_opt_t *options,
                         int *is_glb)
{
    unsigned    i, u;
    char        c;
    size_t      len=strlen(str);
    int         j, m, n, k, l, end_obj=-1, no_param=0;
    char        sobj[MAX_NC_NAME];
    char        scomp[10];
    char        stype[5];
    char        smask[3];
    obj_list_t* obj_list=NULL;
    unsigned    pixels_per_block;


    /* initialize compression  info */
    memset(filt,0,sizeof(filter_info_t));
    *is_glb = 0;

    /* check for the end of object list and number of objects */
    for ( i = 0, n = 0; i < len; i++)
    {
        c = str[i];
        if ( c==':' )
        {
            end_obj=i;
        }
        if ( c==',' )
        {
            n++;
        }
    }

    if (end_obj==-1) /* missing : */
    {
        /* apply to all objects */
        options->all_filter=1;
        *is_glb = 1;
    }

    n++;
    obj_list = (obj_list_t*) malloc(n*sizeof(obj_list_t));
    if (obj_list==NULL)
    {
        error_msg(progname, "could not allocate object list\n");
        return NULL;
    }
    *n_objs=n;

    /* get object list */
    for ( j = 0, k = 0, n = 0; j < end_obj; j++, k++)
    {
        c = str[j];
        sobj[k] = c;
        if ( c==',' || j==end_obj-1)
        {
            if ( c==',') sobj[k]='\0'; else sobj[k+1]='\0';
            strcpy(obj_list[n].obj,sobj);
            memset(sobj,0,sizeof(sobj));
            n++;
            k=-1;
        }
    }
    /* nothing after : */
    if (end_obj+1==(int)len)
    {
        if (obj_list) free(obj_list);
        error_msg(progname, "input Error: Invalid compression type in <%s>\n",str);
        exit(EXIT_FAILURE);
    }


    /* get filter additional parameters */
    m=0;
    for ( i=end_obj+1, k=0, j=0; i<len; i++,k++)
    {
        c = str[i];
        scomp[k]=c;
        if ( c=='=' || i==len-1)
        {
            if ( c=='=') /*one more parameter */
            {
                scomp[k]='\0';     /*cut space */

               /*-------------------------------------------------------------------------
                * H5Z_FILTER_SZIP
                * szip has the format SZIP=<pixels per block,coding>
                * pixels per block is a even number in 2-32 and coding method is 'EC' or 'NN'
                * example SZIP=8,NN
                *-------------------------------------------------------------------------
                */
                if (strcmp(scomp,"SZIP")==0)
                {
                    l=-1; /* mask index check */
                    for ( m=0,u=i+1; u<len; u++,m++)
                    {
                        if (str[u]==',')
                        {
                            stype[m]='\0'; /* end digit of szip */
                            l=0;  /* start EC or NN search */
                            u++;  /* skip ',' */
                        }
                        c = str[u];
                        if (!isdigit(c) && l==-1){
                            if (obj_list) free(obj_list);
                            error_msg(progname, "compression parameter not digit in <%s>\n",str);
                            exit(EXIT_FAILURE);
                        }
                        if (l==-1)
                            stype[m]=c;
                        else
                        {
                            smask[l]=c;
                            l++;
                            if (l==2)
                            {
                                smask[l]='\0';
                                i=len-1; /* end */
                                (*n_objs)--; /* we counted an extra ',' */
                                if (strcmp(smask,"NN")==0)
                                    filt->cd_values[j++]=H5_SZIP_NN_OPTION_MASK;
                                else if (strcmp(smask,"EC")==0)
                                    filt->cd_values[j++]=H5_SZIP_EC_OPTION_MASK;
                                else
                                {
                                    error_msg(progname, "szip mask must be 'NN' or 'EC' \n");
                                    exit(EXIT_FAILURE);
                                }


                            }
                        }

                    }  /* u */
                } /*if */

                  /*-------------------------------------------------------------------------
                  * H5Z_FILTER_SCALEOFFSET
                  * scaleoffset has the format SOFF=<scale_factor,scale_type>
                  * scale_type can be
                  *   integer datatype, H5Z_SO_INT (IN)
                  *   float datatype using D-scaling method, H5Z_SO_FLOAT_DSCALE  (DS)
                  *   float datatype using E-scaling method, H5Z_SO_FLOAT_ESCALE  (ES) , not yet implemented
                  * for integer datatypes, scale_factor denotes Minimum Bits
                  * for float datatypes, scale_factor denotes decimal scale factor
                  *  examples
                  *  SOFF=31,IN
                  *  SOFF=3,DF
                  *-------------------------------------------------------------------------
                */

                else if (strcmp(scomp,"SOFF")==0)
                {
                    l=-1; /* mask index check */
                    for ( m=0,u=i+1; u<len; u++,m++)
                    {
                        if (str[u]==',')
                        {
                            stype[m]='\0'; /* end digit */
                            l=0;  /* start 'IN' , 'DS', or 'ES' search */
                            u++;  /* skip ',' */
                        }
                        c = str[u];
                        if (!isdigit(c) && l==-1){
                            if (obj_list) free(obj_list);
                            error_msg(progname, "compression parameter is not a digit in <%s>\n",str);
                            exit(EXIT_FAILURE);
                        }
                        if (l==-1)
                            stype[m]=c;
                        else
                        {
                            smask[l]=c;
                            l++;
                            if (l==2)
                            {
                                smask[l]='\0';
                                i=len-1; /* end */
                                (*n_objs)--; /* we counted an extra ',' */
                                if (strcmp(smask,"IN")==0)
                                    filt->cd_values[j++]=H5Z_SO_INT;
                                else if (strcmp(smask,"DS")==H5Z_SO_FLOAT_DSCALE)
                                    filt->cd_values[j++]=H5Z_SO_FLOAT_DSCALE;
                                else
                                {
                                    error_msg(progname, "scale type must be 'IN' or 'DS' \n");
                                    exit(EXIT_FAILURE);
                                }

                            }
                        }

                    }  /* u */
                } /*if */


               /*-------------------------------------------------------------------------
                * all other filters
                *-------------------------------------------------------------------------
                */

                else
                {
                    /* here we could have 1 or 2 digits  */
                    for ( m=0,u=i+1; u<len; u++,m++)
                    {
                        c = str[u];
                        if (!isdigit(c)){
                            if (obj_list) free(obj_list);
                            error_msg(progname, "compression parameter is not a digit in <%s>\n",str);
                            exit(EXIT_FAILURE);
                        }
                        stype[m]=c;
                    } /* u */

                    stype[m]='\0';
                } /*if */



                filt->cd_values[j++]=atoi(stype);
                i+=m; /* jump */
   }
   else if (i==len-1)
   { /*no more parameters */
       scomp[k+1]='\0';
       no_param=1;
   }

  /*-------------------------------------------------------------------------
   * translate from string to filter symbol
   *-------------------------------------------------------------------------
   */

  /*-------------------------------------------------------------------------
   * H5Z_FILTER_NONE
   *-------------------------------------------------------------------------
   */
   if (strcmp(scomp,"NONE")==0)
   {
       filt->filtn=H5Z_FILTER_NONE;
       filt->cd_nelmts = 0;
   }

  /*-------------------------------------------------------------------------
   * H5Z_FILTER_DEFLATE
   *-------------------------------------------------------------------------
   */
   else if (strcmp(scomp,"GZIP")==0)
   {
       filt->filtn=H5Z_FILTER_DEFLATE;
       filt->cd_nelmts = 1;
       if (no_param)
       { /*no more parameters, GZIP must have parameter */
           if (obj_list) free(obj_list);
           error_msg(progname, "missing compression parameter in <%s>\n",str);
           exit(EXIT_FAILURE);
       }
   }

  /*-------------------------------------------------------------------------
   * H5Z_FILTER_SZIP
   *-------------------------------------------------------------------------
   */
   else if (strcmp(scomp,"SZIP")==0)
   {
       filt->filtn=H5Z_FILTER_SZIP;
       filt->cd_nelmts = 2;
       if (no_param)
       { /*no more parameters, SZIP must have parameter */
           if (obj_list) free(obj_list);
           error_msg(progname, "missing compression parameter in <%s>\n",str);
           exit(EXIT_FAILURE);
       }
   }

   /*-------------------------------------------------------------------------
   * H5Z_FILTER_SHUFFLE
   *-------------------------------------------------------------------------
   */
   else if (strcmp(scomp,"SHUF")==0)
   {
       filt->filtn=H5Z_FILTER_SHUFFLE;
       filt->cd_nelmts = 0;
       if (m>0)
       { /*shuffle does not have parameter */
           if (obj_list) free(obj_list);
           error_msg(progname, "extra parameter in SHUF <%s>\n",str);
           exit(EXIT_FAILURE);
       }
   }
  /*-------------------------------------------------------------------------
   * H5Z_FILTER_FLETCHER32
   *-------------------------------------------------------------------------
   */
   else if (strcmp(scomp,"FLET")==0)
   {
       filt->filtn=H5Z_FILTER_FLETCHER32;
       filt->cd_nelmts = 0;
       if (m>0)
       { /*shuffle does not have parameter */
           if (obj_list) free(obj_list);
           error_msg(progname, "extra parameter in FLET <%s>\n",str);
           exit(EXIT_FAILURE);
       }
   }
  /*-------------------------------------------------------------------------
   * H5Z_FILTER_NBIT
   *-------------------------------------------------------------------------
   */
   else if (strcmp(scomp,"NBIT")==0)
   {
       filt->filtn=H5Z_FILTER_NBIT;
       filt->cd_nelmts = 0;
       if (m>0)
       { /*nbit does not have parameter */
           if (obj_list) free(obj_list);
           error_msg(progname, "extra parameter in NBIT <%s>\n",str);
           exit(EXIT_FAILURE);
       }
   }
  /*-------------------------------------------------------------------------
   * H5Z_FILTER_SCALEOFFSET
   *-------------------------------------------------------------------------
   */
   else if (strcmp(scomp,"SOFF")==0)
   {
       filt->filtn=H5Z_FILTER_SCALEOFFSET;
       filt->cd_nelmts = 2;
       if (no_param)
       { /*no more parameters, SOFF must have parameter */
           if (obj_list) free(obj_list);
           error_msg(progname, "missing compression parameter in <%s>\n",str);
           exit(EXIT_FAILURE);
       }
   }
   else {
       if (obj_list) free(obj_list);
       error_msg(progname, "invalid filter type in <%s>\n",str);
       exit(EXIT_FAILURE);
   }
  }
 } /*i*/

  /*-------------------------------------------------------------------------
   * check valid parameters
   *-------------------------------------------------------------------------
   */

   switch (filt->filtn)
   {

  /*-------------------------------------------------------------------------
   * H5Z_FILTER_DEFLATE
   *-------------------------------------------------------------------------
   */

   case H5Z_FILTER_DEFLATE:
       if (filt->cd_values[0]>9 )
       {
           if (obj_list) free(obj_list);
           error_msg(progname, "invalid compression parameter in <%s>\n",str);
           exit(EXIT_FAILURE);
       }
       break;

  /*-------------------------------------------------------------------------
   * H5Z_FILTER_SZIP
   *-------------------------------------------------------------------------
   */

   case H5Z_FILTER_SZIP:
       pixels_per_block=filt->cd_values[0];
       if ((pixels_per_block%2)==1)
       {
           if (obj_list) free(obj_list);
           error_msg(progname, "pixels_per_block is not even in <%s>\n",str);
           exit(EXIT_FAILURE);
       }
       if (pixels_per_block>H5_SZIP_MAX_PIXELS_PER_BLOCK)
       {
           if (obj_list) free(obj_list);
           error_msg(progname, "pixels_per_block is too large in <%s>\n",str);
           exit(EXIT_FAILURE);
       }
       if ( (strcmp(smask,"NN")!=0) && (strcmp(smask,"EC")!=0) )
       {
           if (obj_list) free(obj_list);
           error_msg(progname, "szip mask must be 'NN' or 'EC' \n");
           exit(EXIT_FAILURE);
       }
       break;
   default:
       break;

 
   };

   return obj_list;
}
Esempio n. 30
0
int main(int argc, char **argv)
{
    abrt_init(argv);

    /* I18n */
    setlocale(LC_ALL, "");
#if ENABLE_NLS
    bindtextdomain(PACKAGE, LOCALEDIR);
    textdomain(PACKAGE);
#endif

    /* Can't keep these strings/structs static: _() doesn't support that */
    const char *program_usage_string = _(
        "& [-v] [-d DIR] [-m MESSAGEID] [-F FMTFILE] [-p NONE|ESSENTIAL|FULL] [-s SYSLOGID]\n"
        "\n"
        "Reports problem information into systemd journal.\n"
        "\n"
        "The tool reads problem directory DIR and sends its details\n"
        "into systemd journal as a message. If MESSAGEID is defined, the tool\n"
        "creates a catalog message as well.\n"
    );
    enum {
        OPT_v = 1 << 0,
        OPT_d = 1 << 1,
        OPT_m = 1 << 2,
        OPT_F = 1 << 3,
        OPT_p = 1 << 4,
        OPT_s = 1 << 5,
        OPT_D = 1 << 6,
    };
    const char *dump_dir_name = ".";
    const char *message_id = NULL;
    const char *fmt_file = NULL;
    const char *dump = NULL;
    const char *syslog_id = NULL;
    /* Keep enum above and order of options below in sync! */
    struct options program_options[] = {
        OPT__VERBOSE(&g_verbose),
        OPT_STRING('d', NULL          , &dump_dir_name, "DIR"   , _("Problem directory")),
        OPT_STRING('m', "message-id"  , &message_id,    "STR"   , _("Catalog message id")),
        OPT_STRING('F', NULL          , &fmt_file     , "FILE"  , _("Formatting file for catalog message")),
        OPT_STRING('p', "dump"        , &dump         , "STR"   , _("Dump problem dir into systemd journal fields")),
        OPT_STRING('s', "syslog-id"   , &syslog_id    , "STR"   , _("Define SYSLOG_IDENTIFIER systemd journal field")),
        OPT_BOOL(  'D', NULL          , NULL                    , _("Debug")),
        OPT_END()
    };
    unsigned opts = parse_opts(argc, argv, program_options, program_usage_string);

    unsigned dump_opt = DUMP_NONE;
    if (opts & OPT_p)
    {
        if (dump && strcmp(dump, "NONE") == 0)
            /* PASS */;
        else if (dump && strcmp(dump, "ESSENTIAL") == 0)
            dump_opt = DUMP_ESSENTIAL;
        else if (dump && strcmp(dump, "FULL") == 0)
            dump_opt = DUMP_FULL;
        else
        {
            error_msg("Parameter --dump takes NONE|ESSENTIAL|FULL values");
            show_usage_and_die(program_usage_string, program_options);
        }
    }

    export_abrt_envvars(0);

    problem_data_t *problem_data = create_problem_data_for_reporting(dump_dir_name);
    if (!problem_data)
        xfunc_die(); /* create_problem_data_for_reporting already emitted error msg */

    problem_formatter_t *pf = problem_formatter_new();

    if (fmt_file)
    {
        if (problem_formatter_load_file(pf, fmt_file))
            error_msg_and_die("Invalid format file: %s", fmt_file);
    }
    else
    {
        if (problem_formatter_load_string(pf, PROBLEM_REPORT_DEFAULT_TEMPLATE))
            error_msg_and_die("BUG: Invalid default problem report format string");
    }

    problem_report_settings_t report_settings = problem_formatter_get_settings(pf);
    report_settings.prs_shortbt_max_frames = 5;
    report_settings.prs_shortbt_max_text_size = 0; /* always short bt */
    problem_formatter_set_settings(pf, report_settings);

    /* Modify problem_data to meet reporter's needs */
    /* We want to have only binary name in problem report assigned to executable element */
    const char *exe = problem_data_get_content_or_NULL(problem_data, FILENAME_EXECUTABLE);
    char *binary_name = NULL;
    if (exe)
        binary_name = strrchr(exe, '/') + 1;

    if (binary_name)
        problem_data_add_text_noteditable(problem_data, BINARY_NAME, binary_name);

    /* crash_function element is neeeded by systemd journal messages, save ??, if it doesn't exist */
    const char *crash_function = problem_data_get_content_or_NULL(problem_data, FILENAME_CRASH_FUNCTION);
    if (!crash_function)
        problem_data_add_text_noteditable(problem_data, "crash_function", "??");

    /* Add SYSLOG_IDENTIFIER into problem data */
    if (syslog_id || (syslog_id = getenv("REPORTER_JOURNAL_SYSLOG_ID")))
        problem_data_add_text_noteditable(problem_data, SYSLOG_ID, syslog_id);

    /* Add MESSAGE_ID into problem data */
    if (message_id)
        problem_data_add_text_noteditable(problem_data, MESSAGE_ID, message_id);

    /* Generating of problem report */
    problem_report_t *pr = NULL;
    if (problem_formatter_generate_report(pf, problem_data, &pr))
        error_msg_and_die("Failed to format bug report from problem data");

    /* Debug */
    if (opts & OPT_D)
    {
        log("Message: %s\n"
                "\n"
                "%s"
                "\n"
                , problem_report_get_summary(pr)
                , problem_report_get_description(pr)
        );

        problem_data_free(problem_data);
        problem_report_free(pr);
        problem_formatter_free(pf);
        return 0;
    }

    msg_content_t *msg_c = create_journal_message(problem_data, pr, dump_opt);

    /* post journal message */
    sd_journal_sendv(msg_content_get_data(msg_c), msg_content_get_size(msg_c));

    msg_content_free(msg_c);

    problem_data_free(problem_data);
    problem_formatter_free(pf);
    problem_report_free(pr);

    return 0;
}