text:
/*
  Include declarations.
*/
#include "magick/studio.h"
#include "magick/artifact.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/colorspace.h"
#include "magick/constitute.h"
#include "magick/enhance.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/log.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/module.h"
#include "magick/profile.h"
#include "magick/property.h"
#include "magick/quantum.h"
#include "magick/static.h"
#include "magick/string_.h"

/*
  Forward declarations.
*/
static MagickBooleanType
  WritePSDImage(const ImageInfo *,Image *);

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%   D e c o d e I m a g e                                                     %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  DecodeImage uncompresses an image via Macintosh encoding specific to
%  the Adobe Photoshop image format.
%
%  The format of the DecodeImage method is:
%
%      MagickBooleanType DecodeImage(Image *image,const long channel)
%
%  A description of each parameter follows:
%
%    o image,image: The address of a structure of type Image.
%
%    o channel:  Specifies which channel: red, green, blue, or index to
%      decode the pixel values into.
%
*/
static MagickBooleanType DecodeImage(Image *image,const long channel)
{
  MagickOffsetType
    number_pixels;

  Quantum
    pixel;

  register IndexPacket
    *indexes;

  register long
    i,
    x;

  register PixelPacket
    *q;

  ssize_t
    count;

  number_pixels=(MagickOffsetType) image->columns*image->rows;
  for (x=0; number_pixels > 0; )
  {
    count=(ssize_t) ReadBlobByte(image);
    if (count >= 128)
      count-=256;
    if (count < 0)
      {
        if (count == -128)
          continue;
        pixel=ScaleCharToQuantum((unsigned char) ReadBlobByte(image));
        for (count=(-count+1); count > 0; count--)
        {
          q=GetImagePixels(image,(long) (x % image->columns),
            (long) (x/image->columns),1,1);
          if (q == (PixelPacket *) NULL)
            break;
          indexes=GetIndexes(image);
          switch (channel)
          {
            case -1:
            {
              q->opacity=(Quantum) (QuantumRange-pixel);
              break;
            }
            case 0:
            {
              q->red=pixel;
              if (image->storage_class == PseudoClass)
                {
                  *indexes=(IndexPacket) ScaleQuantumToChar(pixel);
                  q->red=image->colormap[(long) *indexes].red;
                  q->green=image->colormap[(long) *indexes].green;
                  q->blue=image->colormap[(long) *indexes].blue;
                }
              break;
            }
            case 1:
            {
              if (image->storage_class == PseudoClass)
                q->opacity=(Quantum) (QuantumRange-pixel);
              else
                q->green=pixel;
              break;
            }
            case 2:
            {
              q->blue=pixel;
              break;
            }
            case 3:
            {
              if (image->colorspace == CMYKColorspace)
                *indexes=(IndexPacket) pixel;
              else
                q->opacity=(Quantum) (QuantumRange-pixel);
              break;
            }
            case 4:
            {
              q->opacity=(Quantum) pixel;
              break;
            }
            default:
              break;
          }
          if (SyncImagePixels(image) == MagickFalse)
            break;
          x++;
          number_pixels--;
        }
        continue;
      }
    count++;
    for (i=(long) count; i > 0; i--)
    {
      pixel=ScaleCharToQuantum((unsigned char) ReadBlobByte(image));
      q=GetImagePixels(image,(long) (x % image->columns),
        (long) (x/image->columns),1,1);
      if (q == (PixelPacket *) NULL)
        break;
      indexes=GetIndexes(image);
      switch (channel)
      {
        case -1:
        {
          q->opacity=(Quantum) (QuantumRange-pixel);
          break;
        }
        case 0:
        {
          q->red=pixel;
          if (image->storage_class == PseudoClass)
            {
              *indexes=(IndexPacket) ScaleQuantumToChar(pixel);
              q->red=image->colormap[(long) *indexes].red;
              q->green=image->colormap[(long) *indexes].green;
              q->blue=image->colormap[(long) *indexes].blue;
            }
          break;
        }
        case 1:
        {
          if (image->storage_class == PseudoClass)
            q->opacity=(Quantum) (QuantumRange-pixel);
          else
            q->green=pixel;
          break;
        }
        case 2:
        {
          q->blue=pixel;
          break;
        }
        case 3:
        {
          if (image->colorspace == CMYKColorspace)
            *indexes=(IndexPacket) pixel;
          else
            q->opacity=(Quantum) (QuantumRange-pixel);
          break;
        }
        case 4:
        {
          q->opacity=(Quantum) pixel;
          break;
        }
        default:
          break;
      }
      if (SyncImagePixels(image) == MagickFalse)
        break;
      x++;
      number_pixels--;
    }
  }
  /*
    Guarentee the correct number of pixel packets.
  */
  if (number_pixels > 0)
    ThrowBinaryException(CorruptImageError,"InsufficientImageDataInFile",
      image->filename)
  else
    if (number_pixels < 0)
      ThrowBinaryException(CorruptImageError,"TooMuchImageDataInFile",
        image->filename);
  return(MagickTrue);
}

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%   I s P S D                                                                 %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  IsPSD()() returns MagickTrue if the image format type, identified by the
%  magick string, is PSD.
%
%  The format of the IsPSD method is:
%
%      MagickBooleanType IsPSD(const unsigned char *magick,const size_t length)
%
%  A description of each parameter follows:
%
%    o magick: This string is generally the first few bytes of an image file
%      or blob.
%
%    o length: Specifies the length of the magick string.
%
%
*/
static MagickBooleanType IsPSD(const unsigned char *magick,const size_t length)
{
  if (length < 4)
    return(MagickFalse);
  if (LocaleNCompare((char *) magick,"8BPS",4) == 0)
    return(MagickTrue);
  return(MagickFalse);
}

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%   R e a d P S D I m a g e                                                   %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  ReadPSDImage() reads an Adobe Photoshop image file and returns it.  It
%  allocates the memory necessary for the new Image structure and returns a
%  pointer to the new image.
%
%  The format of the ReadPSDImage method is:
%
%      image=ReadPSDImage(image_info)
%
%  A description of each parameter follows:
%
%    o image_info: The image info.
%
%    o exception: return any errors or warnings in this structure.
%
*/

static inline long MagickAbsoluteValue(const long x)
{
  if (x < 0)
    return(-x);
  return(x);
}

static CompositeOperator PSDBlendModeToCompositeOperator(const char *mode)
{
  if (mode == (const char *) NULL)
    return(OverCompositeOp);
  if (LocaleNCompare(mode,"norm",4) == 0)
    return(OverCompositeOp);
  if (LocaleNCompare(mode,"mul ",4) == 0)
    return(MultiplyCompositeOp);
  if (LocaleNCompare(mode,"diss",4) == 0)
    return(DissolveCompositeOp);
  if (LocaleNCompare(mode,"diff",4) == 0)
    return(DifferenceCompositeOp);
  if (LocaleNCompare(mode,"dark",4) == 0)
    return(DarkenCompositeOp);
  if (LocaleNCompare(mode,"lite",4) == 0)
    return(LightenCompositeOp);
  if (LocaleNCompare(mode,"hue ",4) == 0)
    return(HueCompositeOp);
  if (LocaleNCompare(mode,"sat ",4) == 0)
    return(SaturateCompositeOp);
  if (LocaleNCompare(mode,"colr",4) == 0)
    return(ColorizeCompositeOp);
  if (LocaleNCompare(mode,"lum ",4) == 0)
    return(LuminizeCompositeOp);
  if (LocaleNCompare(mode,"scrn",4) == 0)
    return(ScreenCompositeOp);
  if (LocaleNCompare(mode,"over",4) == 0)
    return(OverlayCompositeOp);
  if (LocaleNCompare(mode,"hLit",4) == 0)
    return(OverCompositeOp);
  if (LocaleNCompare(mode,"sLit",4) == 0)
    return(OverCompositeOp);
  if (LocaleNCompare(mode,"smud",4) == 0)
    return(OverCompositeOp);
  if (LocaleNCompare(mode,"div ",4) == 0)
    return(OverCompositeOp);
  if (LocaleNCompare(mode,"idiv",4) == 0)
    return(OverCompositeOp);
  return(OverCompositeOp);
}

static const char *CompositeOperatorToPSDBlendMode(CompositeOperator inOp)
{
  const char
    *outMode = "norm";

  switch (inOp)
  {
    case OverCompositeOp:    outMode = "norm";  break;
    case MultiplyCompositeOp:  outMode = "mul ";  break;
    case DissolveCompositeOp:  outMode = "diss";  break;
    case DifferenceCompositeOp:  outMode = "diff";  break;
    case DarkenCompositeOp:    outMode = "dark";  break;
    case LightenCompositeOp:  outMode = "lite";  break;
    case HueCompositeOp:    outMode = "hue ";  break;
    case SaturateCompositeOp:  outMode = "sat ";  break;
    case ColorizeCompositeOp:  outMode = "colr";  break;
    case LuminizeCompositeOp:  outMode = "lum ";  break;
    case ScreenCompositeOp:    outMode = "scrn";  break;
    case OverlayCompositeOp:  outMode = "over";  break;

    default:
      outMode = "norm";
/*
  if (LocaleNCompare(mode,"hLit",4) == 0)
    return(OverCompositeOp);
  if (LocaleNCompare(mode,"sLit",4) == 0)
    return(OverCompositeOp);
  if (LocaleNCompare(mode,"smud",4) == 0)
    return(OverCompositeOp);
  if (LocaleNCompare(mode,"div ",4) == 0)
    return(OverCompositeOp);
  if (LocaleNCompare(mode,"idiv",4) == 0)
    return(OverCompositeOp);
*/
  }
  return(outMode);
}

typedef enum
{
  BitmapMode = 0,
  GrayscaleMode = 1,
  IndexedMode = 2,
  RGBMode = 3,
  CMYKMode = 4,
  MultichannelMode = 7,
  DuotoneMode = 8,
  LabMode = 9
} PSDImageType;

static const char *ModeToString( PSDImageType inType )
{
  switch ( inType )
  {
    case BitmapMode: return "Bitmap";
    case GrayscaleMode: return "Grayscale";
    case IndexedMode: return "Indexed";
    case RGBMode: return "RGB";
    case CMYKMode:  return "CMYK";
    case MultichannelMode: return "Multichannel";
    case DuotoneMode: return "Duotone";
    case LabMode: return "L*A*B";
    default: return "unknown";
  }
}

static inline unsigned char PushCharPixel(const unsigned char **pixels)
{
  unsigned char
    pixel;

  pixel=(unsigned char) *(*pixels)++;
  return(pixel);
}

static inline unsigned long PushLongPixel(const unsigned char **pixels)
{
  unsigned long
    pixel;

  pixel=(unsigned long) (*(*pixels)++ << 24);
  pixel|=(unsigned long) (*(*pixels)++ << 16);
  pixel|=(unsigned long) (*(*pixels)++ << 8);
  pixel|=(unsigned long) (*(*pixels)++);
  return(pixel);
}

static inline unsigned short PushShortPixel(const unsigned char **pixels)
{
  unsigned short
    pixel;

  pixel=(unsigned short) (*(*pixels)++ << 8);
  pixel|=(unsigned short) (*(*pixels)++);
  return(pixel);
}

static MagickBooleanType ParseImageResourceBlocks(Image *image,
  const unsigned char *blocks,size_t length)
{
  const unsigned char
    *p;

  StringInfo
    *profile;

  unsigned long
    count,
    id,
    sans;

  if (length < 16)
    return(MagickFalse);
  profile=AcquireStringInfo(length);
  SetStringInfoDatum(profile,blocks);
  (void) SetImageProfile(image,"iptc",profile);
  profile=DestroyStringInfo(profile);
  for (p=blocks; (p >= blocks) && (p < (blocks+length-16)); )
  {
    if (LocaleNCompare((char *) p,"8BIM",4) != 0)
      break;
    sans=PushLongPixel(&p);
    id=PushShortPixel(&p);
    sans=PushShortPixel(&p);
    count=PushLongPixel(&p);
    switch (id)
    {
      case 0x03ed:
      {
        unsigned long
          resolution;

        /*
          Resolution info.
        */
        resolution=PushShortPixel(&p);
        image->x_resolution=(double) resolution;
        sans=PushShortPixel(&p);
        sans=PushShortPixel(&p);
        sans=PushShortPixel(&p);
        resolution=PushShortPixel(&p);
        image->y_resolution=(double) resolution;
        sans=PushShortPixel(&p);
        sans=PushShortPixel(&p);
        sans=PushShortPixel(&p);
        break;
      }
      default:
      {
        p+=count;
        break;
      }
    }
    if ((count & 0x01) != 0)
      p++;
  }
  return(MagickTrue);
}

static Image *ReadPSDImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define MaxPSDChannels  24

  typedef struct _ChannelInfo
  {
    short int
      type;

    unsigned long
      size;
  } ChannelInfo;

  typedef struct _LayerInfo
  {
    RectangleInfo
      page,
      mask;

    unsigned short
      channels;

    ChannelInfo
      channel_info[MaxPSDChannels];

    char
      blendkey[4];

    Quantum
      opacity;

    unsigned char
      clipping,
      visible,
      flags;

    unsigned long
      offset_x,
      offset_y;

    unsigned char
      name[256];

    Image
      *image;
  } LayerInfo;

  typedef struct _PSDInfo
  {
    char
      signature[4];

    unsigned short
      channels,
      version;

    unsigned char
      reserved[6];

    unsigned long
      rows,
      columns;

    unsigned short
      depth,
      mode;
  } PSDInfo;

  char
    s[MaxTextExtent],
    type[4];

  Image
    *image;

  IndexPacket
    *indexes;

  LayerInfo
    *layer_info;

  long
    j,
    number_layers,
    y;

  PSDInfo
    psd_info;

  register long
    x;

  register PixelPacket
    *q;

  register long
    i;

  size_t
    length,
    combinedlength,
    size;

  ssize_t
    count;

  MagickBooleanType
    status;

  MagickOffsetType
    offset;

  size_t
    packet_size;

  unsigned char
    *data;

  unsigned short
    compression;

  unsigned long
    mask_size,
    pixel,
    skip_first_alpha = 0;

  /*
    Open image file.
  */
  assert(image_info != (const ImageInfo *) NULL);
  assert(image_info->signature == MagickSignature);
  if (image_info->debug != MagickFalse)
    (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
      image_info->filename);
  assert(exception != (ExceptionInfo *) NULL);
  assert(exception->signature == MagickSignature);
  image=AllocateImage(image_info);
  status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
  if (status == MagickFalse)
    {
      image=DestroyImageList(image);
      return((Image *) NULL);
    }
  /*
    Read image header.
  */
  count=ReadBlob(image,4,(unsigned char *) psd_info.signature);
  psd_info.version=ReadBlobMSBShort(image);
  if ((count == 0) || (LocaleNCompare(psd_info.signature,"8BPS",4) != 0) ||
      (psd_info.version != 1))
    ThrowReaderException(CorruptImageError,"ImproperImageHeader");
  count=ReadBlob(image,6,psd_info.reserved);
  psd_info.channels=ReadBlobMSBShort(image);
  if (psd_info.channels > MaxPSDChannels)
    ThrowReaderException(CorruptImageError,"MaximumChannelsExceeded");
  psd_info.rows=ReadBlobMSBLong(image);
  psd_info.columns=ReadBlobMSBLong(image);
  psd_info.depth=ReadBlobMSBShort(image);
  psd_info.mode=ReadBlobMSBShort(image);
  if (image->debug != MagickFalse)
    (void) LogMagickEvent(CoderEvent,GetMagickModule(),
      "  Image is %ld x %ld with channels=%d, depth=%d, mode=%s",
      psd_info.columns,psd_info.rows,psd_info.channels,psd_info.depth,
      ModeToString((PSDImageType) psd_info.mode));
  /*
    Initialize image.
  */
  image->depth=psd_info.depth;
  image->columns=psd_info.columns;
  image->rows=psd_info.rows;
  (void) SetImageBackgroundColor(image);
  image->matte=psd_info.channels >= 4 ? MagickTrue : MagickFalse;
  if (psd_info.mode == LabMode)
    image->colorspace=LabColorspace;
  if (psd_info.mode == CMYKMode)
    {
      image->colorspace=CMYKColorspace;
      image->matte=psd_info.channels >= 5 ? MagickTrue : MagickFalse;
    }
  if ((psd_info.mode == BitmapMode) || (psd_info.mode == GrayscaleMode) ||
      (psd_info.mode == DuotoneMode))
    {
      if (AllocateImageColormap(image,256) == MagickFalse)
        ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
      image->matte=psd_info.channels >= 2 ? MagickTrue : MagickFalse;
      if (image->debug != MagickFalse)
        (void) LogMagickEvent(CoderEvent,GetMagickModule(),
          "  ImageColorMap allocated");
    }
  if (image->debug != MagickFalse)
    (void) LogMagickEvent(CoderEvent,GetMagickModule(),
      image->matte ? "  image has matte" : "  image has no matte");
  /*
    Read PSD raster colormap only present for indexed and duotone images.
  */
  length=ReadBlobMSBLong(image);
  if (length != 0)
    {
      if (image->debug != MagickFalse)
        (void) LogMagickEvent(CoderEvent,GetMagickModule(),
          "  reading colormap");
      if (psd_info.mode == DuotoneMode)
        {
          /*
            Duotone image data;  the format of this data is undocumented.
          */
          data=(unsigned char *) AcquireQuantumMemory(length,sizeof(*data));
          if (data == (unsigned char *) NULL)
            ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
          count=ReadBlob(image,length,data);
          data=(unsigned char *) RelinquishMagickMemory(data);
        }
      else
        {
          /*
            Read PSD raster colormap.
          */
          if (AllocateImageColormap(image,(unsigned long) (length/3)) == MagickFalse)
            ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
          for (i=0; i < (long) image->colors; i++)
            image->colormap[i].red=ScaleCharToQuantum((unsigned char)
              ReadBlobByte(image));
          for (i=0; i < (long) image->colors; i++)
            image->colormap[i].green=ScaleCharToQuantum((unsigned char)
              ReadBlobByte(image));
          for (i=0; i < (long) image->colors; i++)
            image->colormap[i].blue=ScaleCharToQuantum((unsigned char)
              ReadBlobByte(image));
          image->matte=psd_info.channels >= 2 ? MagickTrue : MagickFalse;
        }
    }
  length=ReadBlobMSBLong(image);
  if (length != 0)
    {
      unsigned char
        *blocks;

      /*
        Image resources block.
      */
      if (image->debug != MagickFalse)
        (void) LogMagickEvent(CoderEvent,GetMagickModule(),
          "  reading image resource blocks - %ld bytes",(long) length);
      blocks=(unsigned char *) AcquireQuantumMemory(length,sizeof(*blocks));
      if (blocks == (unsigned char *) NULL)
        ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
      count=ReadBlob(image,length,blocks);
      if (((size_t) count != length) ||
          (LocaleNCompare((char *) blocks,"8BIM",4) != 0))
        {
          blocks=(unsigned char *) RelinquishMagickMemory(blocks);
          ThrowReaderException(CorruptImageError,"ImproperImageHeader");
        }
      (void) ParseImageResourceBlocks(image,blocks,length);
      blocks=(unsigned char *) RelinquishMagickMemory(blocks);
    }
  /*
    If we are only "pinging" the image, then we're done - so return.
  */
  if (image_info->ping != MagickFalse)
    {
      CloseBlob(image);
      return(GetFirstImageInList(image));
    }
  if (SetImageExtent(image,0,0) == MagickFalse)
    {
      InheritException(exception,&image->exception);
      return(DestroyImageList(image));
    }
  /*
    Layer and mask block.
  */
  layer_info=(LayerInfo *) NULL;
  number_layers=0;
  length=ReadBlobMSBLong(image);
  if (length == 8)
    {
      length=ReadBlobMSBLong(image);
      length=ReadBlobMSBLong(image);
    }
  if (length == 0)
    {
      if (image->debug != MagickFalse)
        (void) LogMagickEvent(CoderEvent,GetMagickModule(),
          "  image has no layers");
    }
  else
    {
      offset=TellBlob(image);
      size=ReadBlobMSBLong(image);
      if (size == 0)
        {
          /*
            Skip layers & masks.
          */
          for (j=0; j < (long) (length-4); j++)
            (void) ReadBlobByte(image);
        }
      else
        {
          MagickOffsetType
            layer_offset;

          layer_offset=offset+length;
          number_layers=(short) ReadBlobMSBShort(image);
          if (image->debug != MagickFalse)
            (void) LogMagickEvent(CoderEvent,GetMagickModule(),
              "  image contains %ld layers", number_layers);
          if (number_layers < 0)
            {
              /*
                Weird hack in PSD format to ignore first alpha channel.
              */
              skip_first_alpha=1;
              number_layers=MagickAbsoluteValue(number_layers);
              if (image->debug != MagickFalse)
                (void) LogMagickEvent(CoderEvent,GetMagickModule(),
                  "  negative layer count corrected for");
            }
          layer_info=(LayerInfo *) AcquireQuantumMemory((size_t) number_layers,
            sizeof(*layer_info));
          if (layer_info == (LayerInfo *) NULL)
            {
              if (image->debug != MagickFalse)
                (void) LogMagickEvent(CoderEvent,GetMagickModule(),
                  "  allocation of LayerInfo failed");
              ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
            }
          (void) ResetMagickMemory(layer_info,0,(size_t) number_layers*
            sizeof(*layer_info));
          for (i=0; i < number_layers; i++)
          {
            if (image->debug != MagickFalse)
              (void) LogMagickEvent(CoderEvent,GetMagickModule(),
                "  reading layer #%ld",i+1);
            layer_info[i].page.y=(long) ReadBlobMSBLong(image);
            layer_info[i].page.x=(long) ReadBlobMSBLong(image);
            layer_info[i].page.height=ReadBlobMSBLong(image)-layer_info[i].page.y;
            layer_info[i].page.width=ReadBlobMSBLong(image)-layer_info[i].page.x;
            layer_info[i].channels=ReadBlobMSBShort(image);
            if (layer_info[i].channels > MaxPSDChannels)
              ThrowReaderException(CorruptImageError,"MaximumChannelsExceeded");
            if (image->debug != MagickFalse)
              (void) LogMagickEvent(CoderEvent,GetMagickModule(),
                "    offset(%ld,%ld), size(%ld,%ld), channels=%d",
                layer_info[i].page.x, layer_info[i].page.y,
                layer_info[i].page.height,layer_info[i].page.width,
                layer_info[i].channels);
            for (j=0; j < (long) layer_info[i].channels; j++)
            {
              layer_info[i].channel_info[j].type=(short) ReadBlobMSBShort(image);
              layer_info[i].channel_info[j].size=ReadBlobMSBLong(image);
              if (image->debug != MagickFalse)
                (void) LogMagickEvent(CoderEvent,GetMagickModule(),
                  "    channel[%ld]: type=%d, size=%ld",j,
                  layer_info[i].channel_info[j].type,
              (long) layer_info[i].channel_info[j].size);
            }
            count=ReadBlob(image,4,(unsigned char *) type);
            if ((count == 0) || (LocaleNCompare(type,"8BIM",4) != 0))
              {
                if (image->debug != MagickFalse)
                  (void) LogMagickEvent(CoderEvent,GetMagickModule(),
                    "  layer type was %.4s instead of 8BIM", type);
                 ThrowReaderException(CorruptImageError,"ImproperImageHeader");
              }
            count=ReadBlob(image,4,(unsigned char *) layer_info[i].blendkey);
            layer_info[i].opacity=(Quantum) (QuantumRange-ScaleCharToQuantum(
              (unsigned char) ReadBlobByte(image)));
            layer_info[i].clipping=(unsigned char) ReadBlobByte(image);
            layer_info[i].flags=(unsigned char) ReadBlobByte(image);
            layer_info[i].visible=!(layer_info[i].flags & 0x02);
            if (image->debug != MagickFalse)
              (void) LogMagickEvent(CoderEvent,GetMagickModule(),
                "   blend=%.4s, opacity=%lu, clipping=%s, flags=%d, visible=%s",
                layer_info[i].blendkey,(unsigned long) layer_info[i].opacity,
                layer_info[i].clipping ? "true" : "false",layer_info[i].flags,
                layer_info[i].visible ? "true" : "false");
            (void) ReadBlobByte(image);  /* filler */
            combinedlength=0;
            size=ReadBlobMSBLong(image);
            if (size != 0)
              {
                if (image->debug != MagickFalse)
                  (void) LogMagickEvent(CoderEvent,GetMagickModule(),
                    "    layer contains additional info");
                length=ReadBlobMSBLong(image);
                if (length != 0)
                  {
                    /*
                      Layer mask info.
                    */
                    layer_info[i].mask.y=(long) ReadBlobMSBLong(image);
                    layer_info[i].mask.x=(long) ReadBlobMSBLong(image);
                    layer_info[i].mask.height=
                      (ReadBlobMSBLong(image)-layer_info[i].mask.y);
                    layer_info[i].mask.width=
                      (ReadBlobMSBLong(image)-layer_info[i].mask.x);
                    if (image->debug != MagickFalse)
                      (void) LogMagickEvent(CoderEvent,GetMagickModule(),
                        "      layer mask: offset(%ld,%ld), size(%ld,%ld), length=%ld",
                        layer_info[i].mask.x,layer_info[i].mask.y,
                        layer_info[i].mask.width, layer_info[i].mask.height,
                        (long) length-16);
                    /*
                      Skip over the rest of the layer mask information.
                    */
                    for (j=0; j < (long) (length-16); j++)
                      (void) ReadBlobByte(image);
                  }
                combinedlength+=length+4;  /* +4 for length */
                length=ReadBlobMSBLong(image);
                if (length != 0)
                  {
                    /*
                      Layer blending ranges info.
                    */
                    if (image->debug != MagickFalse)
                      (void) LogMagickEvent(CoderEvent,GetMagickModule(),
                        "      layer blending ranges: length=%ld",(long) length);
                    /*
                      We read it, but don't use it...
                    */
                    for (j=0; j < (long) (length); j+=8)
                    {
                      size_t blend_source=ReadBlobMSBLong(image);
                      size_t blend_dest=ReadBlobMSBLong(image);
                      if (image->debug != MagickFalse)
                        (void) LogMagickEvent(CoderEvent,GetMagickModule(),
                          "        source(%x), dest(%x)",(unsigned int)
                          blend_source,(unsigned int) blend_dest);
                    }
                  }
                combinedlength+=length + 4;  /* +4 for length */
                length=(size_t) ReadBlobByte(image);
                if (length != 0)
                  {
                    /*
                      Layer name.
                    */
                    for (j=0; j < (long) (length); j++)
                      layer_info[i].name[j]=(unsigned char) ReadBlobByte(image);
                    layer_info[i].name[j]='\0';
                    if (image->debug != MagickFalse)
                      (void) LogMagickEvent(CoderEvent,GetMagickModule(),
                        "      layer name: %s",layer_info[i].name);
                 }
#if     0
          if ( length == 0 )
            padBytes = 3;
          else
            padBytes = (4 - (length % 4));
          if ( padBytes != 0 ) { /* we need to pad */
            for ( i=0; i < padBytes; i++)
              (void) ReadBlobByte(image);
          }
                combinedlength += length + padBytes + 1;  /* +1 for length */
#else
               combinedlength+=length + 1;  /* +1 for length */
#endif

#if     0  /* still in development */
          /*
            Adjustment layers and other stuff...
          */
          {
            char  alsig[4],
                alkey[4];

            count=ReadBlob(image,4,alsig);
            if ((count == 0) || (LocaleNCompare(alsig,"8BIM",4) != 0)) {
              if (debug != MagickFalse)
              {
      if (image->debug != MagickFalse)
                  (void) LogMagickEvent(CoderEvent,GetMagickModule(),"  adjustment layer type was %.4s instead of 8BIM", alsig);
              }
              ThrowReaderException(CorruptImageError,"ImproperImageHeader");
            }
            count=ReadBlob(image,4,alkey);
            length=ReadBlobMSBLong(image);
              if (debug != MagickFalse)
              {
      if (image->debug != MagickFalse)
                  (void) LogMagickEvent(CoderEvent,GetMagickModule(),
                            "      adjustment layer key: %.4s, data length=%ld",
                            alkey, length);
              }

              if ( length ) {
              for (j=0; j < (long) (length); j++)
                (void) ReadBlobByte(image);
              }

          }
          combinedlength += 12 + length;  /* sig, key, length + the actual length*/
#endif

               /*
                  Skip the rest of the variable data until we support it.
                */
                if (image->debug != MagickFalse)
                  (void) LogMagickEvent(CoderEvent,GetMagickModule(),
                    "      unsupported data: length=%ld",(long)
                    size-combinedlength);
                for (j=0; j < (long) (size-combinedlength); j++)
                  (void) ReadBlobByte(image);
              }
            /*
              Allocate layered image.
            */
            layer_info[i].image=CloneImage(image,layer_info[i].page.width,
              layer_info[i].page.height,MagickTrue,&image->exception);
            if (layer_info[i].image == (Image *) NULL)
              {
                for (j=0; j < i; j++)
                  layer_info[j].image=DestroyImage(layer_info[j].image);
                if (image->debug != MagickFalse)
                  (void) LogMagickEvent(CoderEvent,GetMagickModule(),
                    "  allocation of image for layer %ld failed", i);
                ThrowReaderException(ResourceLimitError,
                  "MemoryAllocationFailed");
              }
            if (image->debug != MagickFalse)
              (void) LogMagickEvent(CoderEvent,GetMagickModule(),
                "    setting up new layer image");
            (void) SetImageBackgroundColor(layer_info[i].image);
            layer_info[i].image->compose=
              PSDBlendModeToCompositeOperator(layer_info[i].blendkey);
            if (layer_info[i].visible == MagickFalse)
              layer_info[i].image->compose=NoCompositeOp;
            if (psd_info.mode == CMYKMode)
              layer_info[i].image->colorspace=CMYKColorspace;
            for (j=0; j < (long) layer_info[i].channels; j++)
              if (layer_info[i].channel_info[j].type == -1)
                layer_info[i].image->matte=MagickTrue;
            /*
              Set up some hidden attributes for folks that need them.
            */
            (void) FormatMagickString(s,MaxTextExtent,"%ld",
              layer_info[i].page.x );
            (void) SetImageArtifact(layer_info[i].image,"layer-xpos",s);
            (void) FormatMagickString(s,MaxTextExtent,"%ld",
              layer_info[i].page.y);
            (void) SetImageArtifact(layer_info[i].image,"layer-ypos",s);
            (void) FormatMagickString(s,MaxTextExtent,"%lu",(unsigned long)
              layer_info[i].opacity );
            (void) SetImageArtifact(layer_info[i].image,"layer-opacity",s);
            (void) SetImageProperty(layer_info[i].image,"label",(char *)
              layer_info[i].name);
          }
        if (image->debug != MagickFalse)
          (void) LogMagickEvent(CoderEvent,GetMagickModule(),
            "  reading image data for layers");
        /*
          Read pixel data for each layer.
        */
        for (i=0; i < number_layers; i++)
        {
          if (image->debug != MagickFalse)
            (void) LogMagickEvent(CoderEvent,GetMagickModule(),
              "  reading data for layer %ld",i);
            for (j=0; j < (long) layer_info[i].channels; j++)
            {
              if (image->debug != MagickFalse)
                (void) LogMagickEvent(CoderEvent,GetMagickModule(),
                  "    reading data for channel %ld", j);
#if     1
              if (layer_info[i].channel_info[j].size <= (2*layer_info[i].image->rows))
                {
                  long
                    k;

                  if (image->debug != MagickFalse)
                    (void) LogMagickEvent(CoderEvent,GetMagickModule(),
                      "      layer data is empty");
                  /*
                    A layer without data.
                  */
                  for (k=0; k < (long) layer_info[i].channel_info[j].size; k++)
                    (void) ReadBlobByte(layer_info[i].image);
                  continue;
                }
#endif
              compression=ReadBlobMSBShort(layer_info[i].image);
              if (compression == 1)
                {
                  /*
                    Read RLE compressed data.
                  */
                  if (image->debug != MagickFalse)
                    (void) LogMagickEvent(CoderEvent,GetMagickModule(),
                      "      layer data is RLE compressed");
                  for (y=0; y < (long) layer_info[i].image->rows; y++)
                    (void) ReadBlobMSBShort(layer_info[i].image);
                  (void) DecodeImage(layer_info[i].image,
                     layer_info[i].channel_info[j].type);
                  continue;
                }
              /*
                Read uncompressed pixel data as separate planes.
              */
              if (image->debug != MagickFalse)
                (void) LogMagickEvent(CoderEvent,GetMagickModule(),
                  "      layer data is uncompressed");
              packet_size=1;
              if (layer_info[i].image->storage_class == PseudoClass)
                {
                  if (layer_info[i].image->colors > 256)
                    packet_size++;
                }
              else
                if (layer_info[i].image->depth > 8)
                  packet_size++;
              for (y=0; y < (long) layer_info[i].image->rows; y++)
              {
                q=GetImagePixels(layer_info[i].image,0,y,
                  layer_info[i].image->columns,1);
                if (q == (PixelPacket *) NULL)
                  break;
                indexes=GetIndexes(layer_info[i].image);
                for (x=0; x < (long) layer_info[i].image->columns; x++)
                {
                  if (packet_size == 1)
                    pixel=(unsigned long) ScaleCharToQuantum((unsigned char)
                      ReadBlobByte(layer_info[i].image));
                  else
                    pixel=(unsigned long) ScaleShortToQuantum(ReadBlobMSBShort(
                      layer_info[i].image));
                  switch (layer_info[i].channel_info[j].type)
                  {
                    case -1:  /* transparency mask */
                    {
                      q->opacity=(Quantum) (QuantumRange-pixel);
                      break;
                    }
                    case 0:  /* first component (Red, Cyan, Gray or Index) */
                    {
                      q->red=(Quantum) pixel;
                      if (layer_info[i].image->storage_class == PseudoClass)
                        {
                          if (packet_size == 1)
                            indexes[x]=(IndexPacket) ScaleQuantumToChar(
                              (Quantum) pixel);
                          else
                            indexes[x]=(IndexPacket) ScaleQuantumToShort(
                              (Quantum) pixel);
                          q->red=layer_info[i].image->colormap[(long) *indexes].red;
                          q->green=layer_info[i].image->colormap[(long) *indexes].green;
                          q->blue=layer_info[i].image->colormap[(long) *indexes].blue;
                        }
                      break;
                    }
                    case 1:  /* second component (Green, Magenta, or opacity) */
                    {
                      if (layer_info[i].image->storage_class == PseudoClass)
                        q->opacity=(Quantum) (QuantumRange-pixel);
                      else
                        q->green=(Quantum) pixel;
                      break;
                    }
                    case 2:  /* third component (Blue or Yellow) */
                    {
                      q->blue=(Quantum) pixel;
                      break;
                    }
                    case 3:  /* fourth component (Opacity or Black) */
                    {
                      if (image->colorspace == CMYKColorspace)
                        indexes[x]=(Quantum) pixel;
                      else
                        q->opacity=(Quantum) (QuantumRange-pixel);
                      break;
                    }
                    case 4:  /* fifth component (opacity) */
                    {
                      q->opacity=(Quantum) (QuantumRange-pixel);
                      break;
                    }
                    default:
                      break;
                  }
                  q++;
                }
                if (SyncImagePixels(layer_info[i].image) == MagickFalse)
                  break;
              }
            }
            if (layer_info[i].opacity != OpaqueOpacity)
              {
                /*
                  Correct for opacity level.
                */
                for (y=0; y < (long) layer_info[i].image->rows; y++)
                {
                  q=GetImagePixels(layer_info[i].image,0,y,
                    layer_info[i].image->columns,1);
                  if (q == (PixelPacket *) NULL)
                    break;
                  indexes=GetIndexes(layer_info[i].image);
                  for (x=0; x < (long) layer_info[i].image->columns; x++)
                  {
                    q->opacity=QuantumRange-(Quantum)
                      (QuantumScale*(q->opacity*layer_info[i].opacity));
                    q++;
                  }
                  if (SyncImagePixels(layer_info[i].image) == MagickFalse)
                    break;
                }
              }
            if (layer_info[i].image->colorspace == CMYKColorspace)
              (void) NegateImage(layer_info[i].image,MagickFalse);
          }
        /* added by palf -> invisible group layer make layer of this group
           invisible I consider that all layer with width and height null are
           layer for group layer */
       {
         short inside_layer = 0;
         short layer_visible = 0;
         for (i=number_layers-1; i >=0; i--)
         {
           if ((layer_info[i].page.width == 0) ||
               (layer_info[i].page.height == 0))
             {
               if (inside_layer == 0)
                 {
                   inside_layer=1;
                   layer_visible=(short int) layer_info[i].visible;
                 }
               else
                 {
                   inside_layer = 0;
                 }
             }
           else
             if ((inside_layer == 1) && (layer_visible == 0))
               {
                 layer_info[i].visible=(unsigned char) layer_visible;
                 layer_info[i].image->compose=NoCompositeOp;
               }
         }
       }
       /* added by palf -> suppression of empty layer */
       /* I consider that all layer with width and height null are layer for group layer */
       for (i=0; i < number_layers; i++)
       {
         if ((layer_info[i].page.width == 0) ||
             (layer_info[i].page.height == 0))
           {
             if (layer_info[i].image != (Image *) NULL)
               layer_info[i].image=DestroyImage(layer_info[i].image);
             for (j=i; j < number_layers - 1; j++)
               layer_info[j] = layer_info[j+1];
             number_layers--;
             i--;
           }
         }
        mask_size = ReadBlobMSBLong(image);  /* global mask size: currently ignored */

          if (number_layers > 0)
            {

          if (image->debug != MagickFalse)
            (void) LogMagickEvent(CoderEvent,GetMagickModule(),"  putting layers into image list");
              for (i=0; i < number_layers; i++)
              {
                if (i > 0)
                  layer_info[i].image->previous=layer_info[i-1].image;
                if (i < (number_layers-1))
                  layer_info[i].image->next=layer_info[i+1].image;
                layer_info[i].image->page=layer_info[i].page;
              }
            image->next=layer_info[0].image;
            layer_info[0].image->previous=image;
            layer_info=(LayerInfo *) RelinquishMagickMemory(layer_info);

            }
          layer_offset-=TellBlob(image);
          offset=SeekBlob(image,layer_offset,SEEK_CUR);
        }
    }
  /*
    Read the precombined layer, present for PSD < 4 compatibility
  */
  if (image->debug != MagickFalse)
    (void) LogMagickEvent(CoderEvent,GetMagickModule(),
      "  reading the precombined layer");
  compression=ReadBlobMSBShort(image);
  if (compression == 1)
    {
      /*
        Read Packbit encoded pixel data as separate planes.
      */
      for (i=0; i < (long) (image->rows*psd_info.channels); i++)
        (void) ReadBlobMSBShort(image);
      for (i=0; i < (long) psd_info.channels; i++)
        (void) DecodeImage(image,(int) i);
    }
  else
    {
      /*
        Read uncompressed pixel data as separate planes.
      */
      packet_size=1;
      if (image->storage_class == PseudoClass)
        {
          if (image->colors > 256)
            packet_size++;
        }
      else
        if (image->depth > 8)
          packet_size++;
      for (i=0; i < (long) psd_info.channels; i++)
      {
        for (y=0; y < (long) image->rows; y++)
        {
          q=GetImagePixels(image,0,y,image->columns,1);
          if (q == (PixelPacket *) NULL)
            break;
          indexes=GetIndexes(image);
          for (x=0; x < (long) image->columns; x++)
          {
            if (packet_size == 1)
              pixel=(unsigned long) ScaleCharToQuantum((unsigned char)
                ReadBlobByte(image));
            else
              pixel=(unsigned long) ScaleShortToQuantum(
                ReadBlobMSBShort(image));
            switch (image->matte ? i-1 : i)
            {
              case -1:
              {
                q->opacity=(Quantum) (QuantumRange-pixel);
                break;
              }
              case 0:
              {
                q->red=(Quantum) pixel;
                if (image->storage_class == PseudoClass)
                  {
                    if (packet_size == 1)
                      indexes[x]=(IndexPacket) ScaleQuantumToChar((Quantum)
                        pixel);
                    else
                      indexes[x]=(IndexPacket) ScaleQuantumToShort((Quantum)
                        pixel);
                    *q=image->colormap[(long) indexes[x]];
                    q->red=image->colormap[(long) indexes[x]].red;
                    q->green=image->colormap[(long) indexes[x]].green;
                    q->blue=image->colormap[(long) indexes[x]].blue;
                  }
                break;
              }
              case 1:
              {
                if (image->storage_class == PseudoClass)
                  q->opacity=(Quantum) (QuantumRange-pixel);
                else
                  q->green=(Quantum) pixel;
                break;
              }
              case 2:
              {
                q->blue=(Quantum) pixel;
                break;
              }
              case 3:
              {
                if (image->colorspace == CMYKColorspace)
                  indexes[x]=(IndexPacket) pixel;
                else
                  q->opacity=(Quantum) (QuantumRange-pixel);
                break;
              }
              case 4:
              {
                q->opacity=(Quantum) (QuantumRange-pixel);
                break;
              }
              default:
                break;
            }
            q++;
          }
          if (SyncImagePixels(image) == MagickFalse)
            break;
        }
      }
    }
  if (image->colorspace == CMYKColorspace)
    (void) NegateImage(image,MagickFalse);
  CloseBlob(image);
  return(GetFirstImageInList(image));
}

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%   R e g i s t e r P S D I m a g e                                           %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  RegisterPSDImage() adds properties for the PSD image format to
%  the list of supported formats.  The properties include the image format
%  tag, a method to read and/or write the format, whether the format
%  supports the saving of more than one frame to the same file or blob,
%  whether the format supports native in-memory I/O, and a brief
%  description of the format.
%
%  The format of the RegisterPSDImage method is:
%
%      unsigned long RegisterPSDImage(void)
%
*/
ModuleExport unsigned long RegisterPSDImage(void)
{
  MagickInfo
    *entry;

  entry=SetMagickInfo("PSD");
  entry->decoder=(DecodeImageHandler *) ReadPSDImage;
  entry->encoder=(EncodeImageHandler *) WritePSDImage;
  entry->magick=(IsImageFormatHandler *) IsPSD;
  entry->description=ConstantString("Adobe Photoshop bitmap");
  entry->module=ConstantString("PSD");
  (void) RegisterMagickInfo(entry);
  return(MagickImageCoderSignature);
}

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%   U n r e g i s t e r P S D I m a g e                                       %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  UnregisterPSDImage() removes format registrations made by the
%  PSD module from the list of supported formats.
%
%  The format of the UnregisterPSDImage method is:
%
%      UnregisterPSDImage(void)
%
*/
ModuleExport void UnregisterPSDImage(void)
{
  (void) UnregisterMagickInfo("PSD");
}

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%   W r i t e P S D I m a g e                                                 %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  WritePSDImage() writes an image in the Adobe Photoshop encoded image
%  format.
%
%  The format of the WritePSDImage method is:
%
%      MagickBooleanType WritePSDImage(const ImageInfo *image_info,Image *image)
%
%  A description of each parameter follows.
%
%    o image_info: The image info.
%
%    o image:  The image.
%
%
*/

static void WriteOneChannel(const ImageInfo *image_info,Image *image,
  Image *tmp_image,unsigned char *pixels,QuantumType quantum_type)
{
  int
    y;

  QuantumInfo
    quantum_info;

  register const PixelPacket
    *p;

  size_t
    packet_size;

  if (tmp_image->depth > 8)
    tmp_image->depth=16;
  GetQuantumInfo(image_info,&quantum_info);
  packet_size=tmp_image->depth > 8UL ? 2UL : 1UL;
  for (y=0; y < (long) tmp_image->rows; y++)
  {
    p=AcquireImagePixels(tmp_image,0,y,tmp_image->columns,1,&image->exception);
    if (p == (const PixelPacket *) NULL)
    break;
    (void) ImportQuantumPixels(tmp_image,&quantum_info,quantum_type,pixels);
    (void) WriteBlob(image,packet_size*tmp_image->columns,pixels);
  }
}

static MagickBooleanType WriteImageChannels(const ImageInfo *image_info,
  Image *image,Image *tmp_image)
{
  size_t
    channels,
    packet_size;

  unsigned char
    *pixels;

  /*
    Write uncompressed pixel data as separate planes.
  */
  channels=1;
  if ((tmp_image->storage_class == PseudoClass) &&
      (tmp_image->matte == MagickFalse))
    channels++;
  packet_size=tmp_image->depth > 8UL ? 2UL : 1UL;
  pixels=(unsigned char *) AcquireQuantumMemory(channels*tmp_image->columns,
    packet_size*sizeof(*pixels));
  if (pixels == (unsigned char *) NULL)
    ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
  (void) WriteBlobMSBShort(image,0);  /* compression */
  if (tmp_image->storage_class == PseudoClass)
    {
      if (tmp_image->matte == MagickFalse)
        WriteOneChannel(image_info,image,tmp_image,pixels,IndexQuantum);
      else
        WriteOneChannel(image_info,image,tmp_image,pixels,IndexAlphaQuantum);
    }
  else
    {
      if (tmp_image->colorspace == CMYKColorspace)
        (void) NegateImage(image,MagickFalse);
      if (tmp_image->matte)
        WriteOneChannel(image_info,image,tmp_image,pixels,AlphaQuantum);
      WriteOneChannel(image_info,image,tmp_image,pixels,RedQuantum);
      WriteOneChannel(image_info,image,tmp_image,pixels,GreenQuantum);
      WriteOneChannel(image_info,image,tmp_image,pixels,BlueQuantum);
      if (tmp_image->colorspace == CMYKColorspace)
        {
          WriteOneChannel(image_info,image,tmp_image,pixels,BlackQuantum);
          (void) NegateImage(image,MagickFalse);
        }
    }
  pixels=(unsigned char *) RelinquishMagickMemory(pixels);
  return(MagickTrue);
}

/* Write white background, RLE-compressed */

static void WriteWhiteBackground( Image* image )
{
  long       w8, w;
  char       *d, scanline[256];

  int numChannels = 3, dim = (int) (image->rows*numChannels);

  register long
    i;

  size_t
    length;

  unsigned short
    bytecount;

  (void) WriteBlobMSBShort(image,1); /* RLE compressed */
  w8 = (long) image->columns;
  d = scanline;
  /* Set up scanline */
  for (w=w8; w > 128; w-=128)
  {
    *d++=(-127);
    *d++=(char) 255;
  }
  switch (w)
  {
    case 0:
      break;
    case 1:
      *d++=0;
      *d++=(char) 255;
      break;
    default:
      *d++=(char) (1-w);
      *d++=(char) 255;
      break;
  }
  bytecount = d - scanline;

  /* Scanline counts (rows*channels) */
  for (i=0; i < dim; i++)
  {
    (void) WriteBlobMSBShort(image,bytecount);
  }

  /* RLE compressed data  */
  length = bytecount;
  for (i=0; i < dim; i++)
  {
    (void) WriteBlob( image, length, (unsigned char *) scanline );
  }

}

static void WritePascalString (Image* inImage, const char *inString, int inPad)
{
  size_t
    strLength;
  int i;

  /* max length is 255 */

  strLength = (strlen(inString) > 255UL ) ? 255UL : strlen(inString);

  if ( strLength !=  0 )
  {
  (void) WriteBlobByte(inImage,(unsigned char) strLength);
  (void) WriteBlob(inImage, strLength, (unsigned char *) inString);
  }
  else
  (void) WriteBlobByte(inImage, 0);

  strLength ++;

  if ( (strLength % inPad) == 0 )
    return;
  for (i=0; i < (long) (inPad-(strLength % inPad)); i++)
    (void) WriteBlobByte(inImage,0);
}

static MagickBooleanType WritePSDImage(const ImageInfo *image_info,Image *image)
{
  const char
    *theAttr;

  const StringInfo
    *profile;

  MagickBooleanType
    force_white_background = image->matte,
    invert_layer_count = MagickFalse,
    status;

  register long
    i;

  size_t
    num_channels,
    packet_size;

  unsigned char
    layer_name[4];

  unsigned long
    channel_size,
    channelLength,
    layer_count,
    layer_info_size,
    rounded_layer_info_size;

  Image
    * tmp_image = (Image *) NULL,
    * base_image = force_white_background ? image : GetNextImageInList(image);

  /*
    Open output image file.
  */
  assert(image_info != (const ImageInfo *) NULL);
  assert(image_info->signature == MagickSignature);
  assert(image != (Image *) NULL);
  assert(image->signature == MagickSignature);
  if (image->debug != MagickFalse)
    (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
  status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
  if (status == MagickFalse)
    return(status);
  packet_size=(size_t) (image->depth > 8 ? 6 : 3);
  if (image->matte != MagickFalse)
    packet_size+=image->depth > 8 ? 2 : 1;
  (void) WriteBlob(image,4,(unsigned char *) "8BPS");
  (void) WriteBlobMSBShort(image,1);  /* version */
  for ( i=1; i<=6; i++)
  (void) WriteBlobByte(image, 0);  /* 6 bytes of reserved */
  if ( force_white_background )
    num_channels = 3;
  else
  {
    if (image->storage_class == PseudoClass)
     num_channels=(image->matte ? 2UL : 1UL);
    else
    {
    if (image->colorspace != CMYKColorspace)
      num_channels=(image->matte ? 4UL : 3UL);
    else
      num_channels=(image->matte ? 5UL : 4UL);
    }
  }
  (void) WriteBlobMSBShort(image,(unsigned short) num_channels);
  (void) WriteBlobMSBLong(image,image->rows);
  (void) WriteBlobMSBLong(image,image->columns);
  (void) WriteBlobMSBShort(image,(unsigned short)
    (image->storage_class == PseudoClass ? 8 : image->depth > 8 ? 16 : 8));
  if (((image_info->colorspace != UndefinedColorspace) ||
       (image->colorspace != CMYKColorspace)) &&
       (image_info->colorspace != CMYKColorspace))
    {
      if (image_info->colorspace == UndefinedColorspace)
        (void) SetImageColorspace(image,RGBColorspace);
      (void) WriteBlobMSBShort(image,(unsigned short)
        (image->storage_class == PseudoClass ? 2 : 3));
    }
  else
    {
      if (image_info->colorspace == UndefinedColorspace)
        (void) SetImageColorspace(image,CMYKColorspace);
      (void) WriteBlobMSBShort(image,4);
    }
  if ((image->storage_class == DirectClass) || (image->colors > 256))
    (void) WriteBlobMSBLong(image,0);
  else
    {
      /*
        Write PSD raster colormap.
      */
      (void) WriteBlobMSBLong(image,768);
      for (i=0; i < (long) image->colors; i++)
        (void) WriteBlobByte(image,ScaleQuantumToChar(image->colormap[i].red));
      for ( ; i < 256; i++)
        (void) WriteBlobByte(image,0);
      for (i=0; i < (long) image->colors; i++)
        (void) WriteBlobByte(image,ScaleQuantumToChar(image->colormap[i].green));
      for ( ; i < 256; i++)
        (void) WriteBlobByte(image,0);
      for (i=0; i < (long) image->colors; i++)
        (void) WriteBlobByte(image,ScaleQuantumToChar(image->colormap[i].blue));
      for ( ; i < 256; i++)
        (void) WriteBlobByte(image,0);
    }

  /* image resource block */
  profile=GetImageProfile(image,"iptc");
  if (profile == (StringInfo *) NULL)
    (void) WriteBlobMSBLong(image,0);
  else
    {
      (void) WriteBlobMSBLong(image,(unsigned long) GetStringInfoLength(profile));
      (void) WriteBlob( image, GetStringInfoLength(profile), GetStringInfoDatum(profile) );
    }

compute_layer_info:
  layer_count = 0;
  layer_info_size = 2;
  tmp_image = base_image;
  while ( tmp_image != NULL ) {
    packet_size=tmp_image->depth > 8 ? 2UL : 1UL;

    if (tmp_image->storage_class == PseudoClass)
     num_channels = (tmp_image->matte != MagickFalse ? 2UL : 1UL);
    else
    if (tmp_image->colorspace != CMYKColorspace)
      num_channels = (tmp_image->matte != MagickFalse ? 4UL : 3UL);
    else
      num_channels = (tmp_image->matte != MagickFalse ? 5UL : 4UL);

  channelLength=(unsigned long) (tmp_image->columns * tmp_image->rows * packet_size + 2);
  layer_info_size += (unsigned long) (4*4 + 2 + num_channels * 6 + 4 + 4 + 4 * 1 + 4 + 12 + num_channels * channelLength);

  layer_count++;
  tmp_image = GetNextImageInList(tmp_image);
  }

  /* if the image has a matte, then we need to use layers */
  if ( layer_count == 0 && image->matte == MagickTrue )
  {
  invert_layer_count = MagickTrue;
  base_image = image;
  goto compute_layer_info;  /* yes, goto's suck, but it keeps the code cleaner! */
  }

  if ( layer_count == 0 )
    (void) WriteBlobMSBLong(image, 0);
  else
  {
    (void) WriteBlobMSBLong(image,layer_info_size+4+4);
    if ( layer_info_size/2 != (layer_info_size+1)/2 ) /* odd */
      rounded_layer_info_size = layer_info_size + 1;
    else
      rounded_layer_info_size = layer_info_size;
    (void) WriteBlobMSBLong(image,rounded_layer_info_size);

    if ( invert_layer_count )
      layer_count *= -1;  /* if we have a matte, then use negative count! */
    (void) WriteBlobMSBShort(image,(unsigned short) layer_count);

    layer_count = 1;
    tmp_image = base_image;
    while ( tmp_image != NULL ) {
      (void) WriteBlobMSBLong(image,0);
      (void) WriteBlobMSBLong(image,0);
      (void) WriteBlobMSBLong(image,tmp_image->rows);
      (void) WriteBlobMSBLong(image,tmp_image->columns);

      packet_size=tmp_image->depth > 8 ? 2UL : 1UL;
      channel_size=(unsigned long) ((packet_size*tmp_image->rows*tmp_image->columns)+2);
      if (tmp_image->storage_class == PseudoClass) {
       (void) WriteBlobMSBShort(image,(unsigned short)
         (tmp_image->matte ? 2 : 1));
       if (tmp_image->matte) {
         (void) WriteBlobMSBShort(image,(unsigned short) -1);
         (void) WriteBlobMSBLong(image,channel_size);
       }
       (void) WriteBlobMSBShort(image, 0);
       (void) WriteBlobMSBLong(image, channel_size);
      } else
      if (tmp_image->colorspace != CMYKColorspace)
      {
        (void) WriteBlobMSBShort(image,(unsigned short)
          (tmp_image->matte ? 4 : 3));
       if (tmp_image->matte) {
         (void) WriteBlobMSBShort(image,(unsigned short) -1);
         (void) WriteBlobMSBLong(image,channel_size);
       }
       (void) WriteBlobMSBShort(image, 0);
       (void) WriteBlobMSBLong(image, channel_size);
       (void) WriteBlobMSBShort(image, 1);
       (void) WriteBlobMSBLong(image, channel_size);
       (void) WriteBlobMSBShort(image, 2);
       (void) WriteBlobMSBLong(image, channel_size);
      }
      else
      {
        (void) WriteBlobMSBShort(image,(unsigned short)
          (tmp_image->matte ? 5 : 4));
       if (tmp_image->matte) {
         (void) WriteBlobMSBShort(image,(unsigned short) -1);
         (void) WriteBlobMSBLong(image,channel_size);
       }
       (void) WriteBlobMSBShort(image, 0);
       (void) WriteBlobMSBLong(image, channel_size);
       (void) WriteBlobMSBShort(image, 1);
       (void) WriteBlobMSBLong(image, channel_size);
       (void) WriteBlobMSBShort(image, 2);
       (void) WriteBlobMSBLong(image, channel_size);
       (void) WriteBlobMSBShort(image, 3);
       (void) WriteBlobMSBLong(image, channel_size);
      }

      (void) WriteBlob(image, 4, (unsigned char *) "8BIM");
      (void) WriteBlob(image, 4, (unsigned char *) CompositeOperatorToPSDBlendMode(tmp_image->compose));
      (void) WriteBlobByte(image, 255);    /* BOGUS: layer opacity */
      (void) WriteBlobByte(image, 0);
      (void) WriteBlobByte(image, 1);    /* BOGUS: layer attributes - visible, etc. */
      (void) WriteBlobByte(image, 0);

      (void) WriteBlobMSBLong(image, 12);
      (void) WriteBlobMSBLong(image, 0);
      (void) WriteBlobMSBLong(image, 0);

      theAttr=(const char *) GetImageProperty(tmp_image,"label");
      if (theAttr) {
        WritePascalString( image, theAttr, 4 );
        /*
        sprintf((char *) &(layer_name[1]), "%4s", theAttr->value );
        (void) WriteBlobByte(image, 3);
        (void) WriteBlob(image, 3, &layer_name[1]);
        */
      } else {
        (void) FormatMagickString((char *) layer_name,MaxTextExtent,"L%02ld",
          layer_count++ );
        WritePascalString( image, (char*)layer_name, 4 );
      }
      tmp_image = GetNextImageInList(tmp_image);
    };

     /* now the image data! */
    tmp_image = base_image;
    while ( tmp_image != NULL ) {
      status=WriteImageChannels(image_info,image,tmp_image);

      /* add in the pad! */
       if ( rounded_layer_info_size != layer_info_size )
         (void) WriteBlobByte(image,'\0');

      tmp_image = GetNextImageInList(tmp_image);
    };

    /* user mask data */
     (void) WriteBlobMSBLong(image, 0);

  }

   /* now the background image data! */
   if (force_white_background  != MagickFalse)
     WriteWhiteBackground(image);
   else
  status=WriteImageChannels(image_info,image,image);

  CloseBlob(image);
  return(status);
}


text:
function animatedTopNav(paddingSmall, paddingLarge){
    // anitmatedTopNav-helper
    // absolute distance to prevent hiding of content

    $('.animatedTopNav').after('

');
    $('.animatedTopNav-helper').css('background-color', '#2f2f2f').css('width','inherit');

    var fontSize = $('.animatedTopNav').children().css('font-size');
    var paddingTopNavHelper = parseInt(paddingLarge)*2 + parseInt(fontSize) + 7; //FAULT: Fix "7"!

    $('.animatedTopNav-helper').css('padding-top', paddingTopNavHelper+"px");

    // Scroll Animation

    //calculate reduceAtDistance
    var reduceAtDistance = paddingTopNavHelper-parseInt(paddingSmall)*2; //theoretical you can subtract the font size

    // Init size at page reload so it is overwrites the CSS propertys
    var pageAtTop;

    if(document.body.scrollTop >= reduceAtDistance){
        $('.animatedTopNav').children().css({
            'paddingTop': paddingSmall,
            'paddingBottom': paddingSmall
        });

        pageAtTop = false;

    } else {
        $('.animatedTopNav').children().css({
            'paddingTop': paddingLarge,
            'paddingBottom': paddingLarge
        });

        pageAtTop = true;
    }

    // Set event listener
    $( window ).scroll(function() {
        if (document.body.scrollTop >= reduceAtDistance && pageAtTop === true) {
            pageAtTop = false;

            $('.animatedTopNav').children().animate({
                'paddingTop': paddingSmall,
                'paddingBottom': paddingSmall
            },'fast');

        } else if (document.body.scrollTop <= reduceAtDistance && pageAtTop === false){
            pageAtTop = true;

            $('.animatedTopNav').children().animate({
                'paddingTop': paddingLarge,
                'paddingBottom': paddingLarge
            },'fast');
        }
    });
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
    ">

    <context:property-placeholder location="classpath:db-dev.properties" />

    <import resource="webMvcContext.xml"/>
    <import resource="servicesContext.xml"/>
    <import resource="persistenceContext.xml"/>
</beans>


text:
import cleanup from 'js-cleanup'
import createFilter from './create-filter'
import parseOptions from './parse-options'

/**
 * Returns the rollup-plugin-cleanup instance.
 * @param   {Object} options - Plugin's user options
 * @returns {Object} Plugin instance.
 */
const rollupCleanup = function (options) {
  options = options || {}

  // merge include, exclude, and extensions
  const filter = createFilter(options)

  // validate and clone the plugin options
  options = parseOptions(options)

  // the plugin instance
  return {

    name: 'cleanup',

    transform(code, id) {

      if (filter(id)) {
        return new Promise((resolve) => {
          try {
            resolve(cleanup(code, id, options))
          } catch (err) {
            // istanbul ignore else
            if ('position' in err && this.error) {
              this.error(err.message, err.position)
            } else {
              throw err
            }
          }
        })
      }

      return null
    },
  }
}

export default rollupCleanup


text:
function HIGH_FIVE () { return 5; };
console.log( 'header:', HIGH_FIVE(), HIGH_FIVE );

window.onload = onLoad;

function onLoad() {
	console.log( 'onLoad:', HIGH_FIVE ); //  HIGH_FIVE() - number not a function error
};


text:
"use strict";

module.exports = function(options, imports, register) {
    imports.connect.useSetup(remoteAddress);
    register(null, {
        "connect.remote-address": {}
    });
};

function remoteAddress(req, res, next) {
    req.remoteAddress =
        req.headers['x-forwarded-for'] ||
        req.socket.remoteAddress ||
        req.connection.remoteAddress ||
        req.connection.socket.remoteAddress;

    req.proto =
        req.headers["x-forwarded-proto"] ||
        (req.socket.encrypted ? "https" : "http");

    next();
}


text:
"""Create documentation for generate API surfaces.

Command-line tool that creates documentation for all APIs listed in discovery.
The documentation is generated from a combination of the discovery document and
the generated API surface itself.
"""
from __future__ import print_function

__author__ = "jcgregorio@google.com (Joe Gregorio)"

import argparse
import collections
import json
import pathlib
import re
import string
import sys

import uritemplate

from googleapiclient.discovery import DISCOVERY_URI, build_from_document
from googleapiclient.http import build_http

DISCOVERY_DOC_DIR = (
    pathlib.Path(__file__).parent.resolve()
    / "googleapiclient"
    / "discovery_cache"
    / "documents"
)

CSS = """
"""

METHOD_TEMPLATE = """

    $name($params)

$doc

"""

COLLECTION_LINK = """

  $name()

Returns the $name Resource.

"""

METHOD_LINK = """

  $name($params)

$firstline
"""

BASE = pathlib.Path(__file__).parent.resolve() / "docs" / "dyn"

DIRECTORY_URI = "https://www.googleapis.com/discovery/v1/apis"

parser = argparse.ArgumentParser(description=__doc__)

parser.add_argument(
    "--discovery_uri_template",
    default=DISCOVERY_URI,
    help="URI Template for discovery.",
)

parser.add_argument(
    "--discovery_uri",
    default="",
    help=(
        "URI of discovery document. If supplied then only "
        "this API will be documented."
    ),
)

parser.add_argument(
    "--directory_uri",
    default=DIRECTORY_URI,
    help=("URI of directory document. Unused if --discovery_uri" " is supplied."),
)

parser.add_argument(
    "--dest", default=BASE, help="Directory name to write documents into."
)

def safe_version(version):
    """Create a safe version of the verion string.

    Needed so that we can distinguish between versions
    and sub-collections in URIs. I.e. we don't want
    adsense_v1.1 to refer to the '1' collection in the v1
    version of the adsense api.

    Args:
      version: string, The version string.
    Returns:
      The string with '.' replaced with '_'.
    """

    return version.replace(".", "_")

def unsafe_version(version):
    """Undoes what safe_version() does.

    See safe_version() for the details.

    Args:
      version: string, The safe version string.
    Returns:
      The string with '_' replaced with '.'.
    """

    return version.replace("_", ".")

def method_params(doc):
    """Document the parameters of a method.

    Args:
      doc: string, The method's docstring.

    Returns:
      The method signature as a string.
    """
    doclines = doc.splitlines()
    if "Args:" in doclines:
        begin = doclines.index("Args:")
        if "Returns:" in doclines[begin + 1 :]:
            end = doclines.index("Returns:", begin)
            args = doclines[begin + 1 : end]
        else:
            args = doclines[begin + 1 :]

        parameters = []
        sorted_parameters = []
        pname = None
        desc = ""

        def add_param(pname, desc):
            if pname is None:
                return
            if "(required)" not in desc:
                pname = pname + "=None"
                parameters.append(pname)
            else:
                # required params should be put straight into sorted_parameters
                # to maintain order for positional args
                sorted_parameters.append(pname)

        for line in args:
            m = re.search(r"^\s+([a-zA-Z0-9_]+): (.*)", line)
            if m is None:
                desc += line
                continue
            add_param(pname, desc)
            pname = m.group(1)
            desc = m.group(2)
        add_param(pname, desc)
        sorted_parameters.extend(sorted(parameters))
        sorted_parameters = ", ".join(sorted_parameters)
    else:
        sorted_parameters = ""
    return sorted_parameters

def method(name, doc):
    """Documents an individual method.

    Args:
      name: string, Name of the method.
      doc: string, The methods docstring.
    """
    import html

    params = method_params(doc)
    doc = html.escape(doc)
    return string.Template(METHOD_TEMPLATE).substitute(
        name=name, params=params, doc=doc
    )

def breadcrumbs(path, root_discovery):
    """Create the breadcrumb trail to this page of documentation.

    Args:
      path: string, Dot separated name of the resource.
      root_discovery: Deserialized discovery document.

    Returns:
      HTML with links to each of the parent resources of this resource.
    """
    parts = path.split(".")

    crumbs = []
    accumulated = []

    for i, p in enumerate(parts):
        prefix = ".".join(accumulated)
        # The first time through prefix will be [], so we avoid adding in a
        # superfluous '.' to prefix.
        if prefix:
            prefix += "."
        display = p
        if i == 0:
            display = root_discovery.get("title", display)
        crumbs.append('{}'.format(prefix + p, display))
        accumulated.append(p)

    return " . ".join(crumbs)

def document_collection(resource, path, root_discovery, discovery, css=CSS):
    """Document a single collection in an API.

    Args:
      resource: Collection or service being documented.
      path: string, Dot separated name of the resource.
      root_discovery: Deserialized discovery document.
      discovery: Deserialized discovery document, but just the portion that
        describes the resource.
      css: string, The CSS to include in the generated file.
    """
    collections = []
    methods = []
    resource_name = path.split(".")[-2]
    html = [
        "",
        css,
        "
%s
" % breadcrumbs(path[:-1], root_discovery),
        "
Instance Methods
",
    ]

    # Which methods are for collections.
    for name in dir(resource):
        if not name.startswith("_") and callable(getattr(resource, name)):
            if hasattr(getattr(resource, name), "__is_resource__"):
                collections.append(name)
            else:
                methods.append(name)

    # TOC
    if collections:
        for name in collections:
            if not name.startswith("_") and callable(getattr(resource, name)):
                href = path + name + ".html"
                html.append(
                    string.Template(COLLECTION_LINK).substitute(href=href, name=name)
                )

    if methods:
        for name in methods:
            if not name.startswith("_") and callable(getattr(resource, name)):
                doc = getattr(resource, name).__doc__
                params = method_params(doc)
                firstline = doc.splitlines()[0]
                html.append(
                    string.Template(METHOD_LINK).substitute(
                        name=name, params=params, firstline=firstline
                    )
                )

    if methods:
        html.append("
Method Details
")
        for name in methods:
            dname = name.rsplit("_")[0]
            html.append(method(name, getattr(resource, name).__doc__))

    html.append("")

    return "\n".join(html)

def document_collection_recursive(
    resource, path, root_discovery, discovery, doc_destination_dir
):
    html = document_collection(resource, path, root_discovery, discovery)

    f = open(pathlib.Path(doc_destination_dir).joinpath(path + "html"), "w")

    f.write(html)
    f.close()

    for name in dir(resource):
        if (
            not name.startswith("_")
            and callable(getattr(resource, name))
            and hasattr(getattr(resource, name), "__is_resource__")
            and discovery != {}
        ):
            dname = name.rsplit("_")[0]
            collection = getattr(resource, name)()
            document_collection_recursive(
                collection,
                path + name + ".",
                root_discovery,
                discovery["resources"].get(dname, {}),
                doc_destination_dir,
            )

def document_api(name, version, uri, doc_destination_dir):
    """Document the given API.

    Args:
        name (str): Name of the API.
        version (str): Version of the API.
        uri (str): URI of the API's discovery document
        doc_destination_dir (str): relative path where the reference
            documentation should be saved.
    """
    http = build_http()
    resp, content = http.request(
        uri
        or uritemplate.expand(
            FLAGS.discovery_uri_template, {"api": name, "apiVersion": version}
        )
    )

    if resp.status == 200:
        discovery = json.loads(content)
        service = build_from_document(discovery)
        doc_name = "{}.{}.json".format(name, version)
        discovery_file_path = DISCOVERY_DOC_DIR / doc_name
        revision = None

        pathlib.Path(discovery_file_path).touch(exist_ok=True)

        # Write discovery artifact to disk if revision equal or newer
        with open(discovery_file_path, "r+") as f:
            try:
                json_data = json.load(f)
                revision = json_data["revision"]
            except json.JSONDecodeError:
                revision = None

            if revision is None or discovery["revision"] >= revision:
                # Reset position to the beginning
                f.seek(0)
                # Write the changes to disk
                json.dump(discovery, f, indent=2, sort_keys=True)
                # Truncate anything left as it's not needed
                f.truncate()

    elif resp.status == 404:
        print(
            "Warning: {} {} not found. HTTP Code: {}".format(name, version, resp.status)
        )
        return
    else:
        print(
            "Warning: {} {} could not be built. HTTP Code: {}".format(
                name, version, resp.status
            )
        )
        return

    document_collection_recursive(
        service,
        "{}_{}.".format(name, safe_version(version)),
        discovery,
        discovery,
        doc_destination_dir,
    )

def document_api_from_discovery_document(discovery_url, doc_destination_dir):
    """Document the given API.

    Args:
      discovery_url (str): URI of discovery document.
      doc_destination_dir (str): relative path where the reference
          documentation should be saved.
    """
    http = build_http()
    response, content = http.request(discovery_url)
    discovery = json.loads(content)

    service = build_from_document(discovery)

    name = discovery["version"]
    version = safe_version(discovery["version"])

    document_collection_recursive(
        service,
        "{}_{}.".format(name, version),
        discovery,
        discovery,
        doc_destination_dir,
    )

def generate_all_api_documents(directory_uri=DIRECTORY_URI, doc_destination_dir=BASE):
    """Retrieve discovery artifacts and fetch reference documentations
    for all apis listed in the public discovery directory.
    args:
        directory_uri (str): uri of the public discovery directory.
        doc_destination_dir (str): relative path where the reference
            documentation should be saved.
    """
    api_directory = collections.defaultdict(list)
    http = build_http()
    resp, content = http.request(directory_uri)
    if resp.status == 200:
        directory = json.loads(content)["items"]
        for api in directory:
            document_api(
                api["name"],
                api["version"],
                api["discoveryRestUrl"],
                doc_destination_dir,
            )
            api_directory[api["name"]].append(api["version"])

        # sort by api name and version number
        for api in api_directory:
            api_directory[api] = sorted(api_directory[api])
        api_directory = collections.OrderedDict(
            sorted(api_directory.items(), key=lambda x: x[0])
        )

        markdown = []
        for api, versions in api_directory.items():
            markdown.append("## %s" % api)
            for version in versions:
                markdown.append(
                    "* [%s](http://googleapis.github.io/google-api-python-client/docs/dyn/%s_%s.html)"
                    % (version, api, safe_version(version))
                )
            markdown.append("\n")

        with open(BASE / "index.md", "w") as f:
            markdown = "\n".join(markdown)
            f.write(markdown)

    else:
        sys.exit("Failed to load the discovery document.")

if __name__ == "__main__":
    FLAGS = parser.parse_args(sys.argv[1:])
    if FLAGS.discovery_uri:
        document_api_from_discovery_document(
            discovery_url=FLAGS.discovery_uri, doc_destination_dir=FLAGS.dest
        )
    else:
        generate_all_api_documents(
            directory_uri=FLAGS.directory_uri, doc_destination_dir=FLAGS.dest
        )


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>com.redhat.consulting.fusequickstarts.karaf</groupId>
		<artifactId>karaf-parent</artifactId>
		<version>7.6</version>
		<relativePath>../parent/pom.xml</relativePath>
	</parent>

	<artifactId>soap_client</artifactId>
	<name>Fuse Quick Start :: Karaf :: Blueprint :: Camel-CXF SOAP Client</name>

	<packaging>bundle</packaging>

	<!-- Any dependencies needed by your project -->
	<dependencies>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
		</dependency>

		<dependency>
			<groupId>org.apache.camel</groupId>
			<artifactId>camel-core</artifactId>
		</dependency>
		<dependency>
			<groupId>org.apache.camel</groupId>
			<artifactId>camel-cxf</artifactId>
		</dependency>
		<dependency>
			<groupId>org.apache.cxf</groupId>
			<artifactId>cxf-rt-transports-http-jetty</artifactId>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
			</plugin>

			<!-- Bundle plugin which builds the bundle to install on karaf -->
			<plugin>
				<groupId>org.apache.felix</groupId>
				<artifactId>maven-bundle-plugin</artifactId>
				<extensions>true</extensions>
				<configuration>
					<manifestLocation>target/META-INF</manifestLocation>
					<instructions>
						<Bundle-SymbolicName>${project.groupId}.${project.artifactId}</Bundle-SymbolicName>
						<!-- Any packages to be exported for use by another bundle -->
						<Export-Package />
						<!-- Any packages needed by your bundle -->
						<Import-Package>
							org.apache.camel.*,
							org.osgi.service.*,
							org.xmlsoap.schemas.soap.envelope,
							javax.xml.*,
							javax.jws
						</Import-Package>
						<DynamicImport-Package>
							javax.xml.namespace
						</DynamicImport-Package>
					</instructions>
				</configuration>
			</plugin>

			<!-- Generate POJO Classes for WSDL -->
			<plugin>
				<groupId>org.apache.cxf</groupId>
				<artifactId>cxf-codegen-plugin</artifactId>
				<executions>
					<execution>
						<id>generate-sources</id>
						<phase>generate-sources</phase>
						<goals>
							<goal>wsdl2java</goal>
						</goals>
						<configuration>
							<sourceRoot>${basedir}/target/generated/src/main/java</sourceRoot>
							<wsdlOptions>
								<wsdlOption>
									<wsdl>${basedir}/src/main/resources/wsdl/currencyConvertor.wsdl</wsdl>
								</wsdlOption>
							</wsdlOptions>
						</configuration>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>
</project>


text:
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN  *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.

using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Web.Script.Serialization;
using Microsoft.PythonTools.Analysis;
using Microsoft.PythonTools.Infrastructure;
using Microsoft.PythonTools.Interpreter;
using Microsoft.PythonTools.Interpreter.Ast;
using Microsoft.PythonTools.Projects;

namespace Microsoft.PythonTools.TestAdapter {
    [Export(typeof(IAnalysisExtension))]
    [AnalysisExtensionName(Name)]
    partial class TestAnalyzer : IAnalysisExtension {
        internal const string Name = "ptvs_unittest";
        internal const string GetTestCasesCommand = "testcases";

        private PythonAnalyzer _analyzer;

        public string HandleCommand(string commandId, string body) {
            var serializer = new JavaScriptSerializer();
            switch (commandId) {
                case GetTestCasesCommand:
                    IProjectEntry projEntry;
                    IEnumerable<TestCaseInfo> testCases;
                    if (_analyzer.TryGetProjectEntryByPath(body, out projEntry)) {
                        testCases = GetTestCasesFromAnalysis(projEntry);
                    } else {
                        testCases = GetTestCasesFromAst(body);
                    }

                    return serializer.Serialize(testCases.Select(tc => tc.AsDictionary()).ToArray());
            }

            return "";
        }

        public void Register(PythonAnalyzer analyzer) {
            _analyzer = analyzer;
        }

        public static TestCaseInfo[] GetTestCases(string data) {
            var serializer = new JavaScriptSerializer();
            List<TestCaseInfo> tests = new List<TestCaseInfo>();
            foreach (var item in serializer.Deserialize<object[]>(data)) {
                var dict = item as Dictionary<string, object>;
                if (dict == null) {
                    continue;
                }

                object filename, className, methodName, startLine, startColumn, endLine, kind;
                if (dict.TryGetValue(Serialize.Filename, out filename) &&
                    dict.TryGetValue(Serialize.ClassName, out className) &&
                    dict.TryGetValue(Serialize.MethodName, out methodName) &&
                    dict.TryGetValue(Serialize.StartLine, out startLine) &&
                    dict.TryGetValue(Serialize.StartColumn, out startColumn) &&
                    dict.TryGetValue(Serialize.EndLine, out endLine) &&
                    dict.TryGetValue(Serialize.Kind, out kind)) {
                    tests.Add(
                        new TestCaseInfo(
                            filename.ToString(),
                            className.ToString(),
                            methodName.ToString(),
                            ToInt(startLine),
                            ToInt(startColumn),
                            ToInt(endLine)
                        )
                    );
                }
            }
            return tests.ToArray();
        }

        private static int ToInt(object value) {
            if (value is int) {
                return (int)value;
            }
            return 0;
        }

        public class Serialize {
            public const string Filename = "filename";
            public const string ClassName = "className";
            public const string MethodName = "methodName";
            public const string StartLine = "startLine";
            public const string StartColumn = "startColumn";
            public const string EndLine = "endLine";
            public const string Kind = "kind";
        }

        public static IEnumerable<TestCaseInfo> GetTestCasesFromAnalysis(IProjectEntry projEntry) {
            var entry = projEntry as IPythonProjectEntry;
            if (entry == null) {
                yield break;
            }
            var analysis = entry.Analysis;
            if (analysis == null || !entry.IsAnalyzed) {
                yield break;
            }

            foreach (var classValue in GetTestCaseClasses(analysis)) {
                // Check the name of all functions on the class using the
                // analyzer. This will return functions defined on this
                // class and base classes
                foreach (var member in GetTestCaseMembers(analysis, classValue)) {
                    // Find the definition to get the real location of the
                    // member. Otherwise decorators will confuse us.
                    var definition = entry.Analysis
                        .GetVariablesByIndex(classValue.Name + "." + member.Key, 0)
                        .FirstOrDefault(v => v.Type == VariableType.Definition);

                    var location = (definition != null) ?
                        definition.Location :
                        member.Value.SelectMany(m => m.Locations).FirstOrDefault(loc => loc != null);

                    int endLine = location?.EndLine ?? location?.StartLine ?? 0;

                    yield return new TestCaseInfo(
                        classValue.DeclaringModule?.FilePath,
                        classValue.Name,
                        member.Key,
                        location?.StartLine ?? 0,
                        location?.StartColumn ?? 1,
                        endLine
                    );
                }
            }
        }

        private static bool IsTestCaseClass(AnalysisValue cls) {
            return IsTestCaseClass(cls?.PythonType);
        }

        private static bool IsTestCaseClass(IPythonType cls) {
            if (cls == null ||
                cls.DeclaringModule == null) {
                return false;
            }
            var mod = cls.DeclaringModule.Name;
            return (mod == "unittest" || mod.StartsWith("unittest.")) && cls.Name == "TestCase";
        }
        /// <summary>
        /// Get Test Case Members for a class.  If the class has 'test*' tests
        /// return those.  If there aren't any 'test*' tests return (if one at
        /// all) the runTest overridden method
        /// </summary>
        private static IEnumerable<KeyValuePair<string, IAnalysisSet>> GetTestCaseMembers(
            ModuleAnalysis analysis,
            AnalysisValue classValue
        ) {
            var methodFunctions = classValue.GetAllMembers(analysis.InterpreterContext)
                .Where(v => v.Value.Any(m => m.MemberType == PythonMemberType.Function || m.MemberType == PythonMemberType.Method));

            var tests = methodFunctions.Where(v => v.Key.StartsWith("test"));
            var runTest = methodFunctions.Where(v => v.Key.Equals("runTest"));

            if (tests.Any()) {
                return tests;
            } else {
                return runTest;
            }
        }

        private static IEnumerable<AnalysisValue> GetTestCaseClasses(ModuleAnalysis analysis) {
            return analysis.GetAllAvailableMembersByIndex(0, GetMemberOptions.ExcludeBuiltins)
                .SelectMany(m => analysis.GetValuesByIndex(m.Name, 0))
                .Where(v => v.MemberType == PythonMemberType.Class)
                .Where(v => v.Mro.SelectMany(v2 => v2).Any(IsTestCaseClass));
        }

        private static IEnumerable<IPythonType> GetTestCaseClasses(IPythonModule module, IModuleContext context) {
            foreach (var name in module.GetMemberNames(context)) {
                var cls = module.GetMember(context, name) as IPythonType;
                if (cls != null) {
                    foreach (var baseCls in cls.Mro.MaybeEnumerate()) {
                        if (baseCls.Name == "TestCase" ||
                            baseCls.Name.StartsWith("unittest.") && baseCls.Name.EndsWith(".TestCase")) {
                            yield return cls;
                        }
                    }
                }
            }
        }

        private static IEnumerable<IPythonFunction> GetTestCaseMembers(IPythonType cls, IModuleContext context) {
            var methodFunctions = cls.GetMemberNames(context).Select(n => cls.GetMember(context, n))
                .OfType<IPythonFunction>()
                .ToArray();

            var tests = methodFunctions.Where(v => v.Name.StartsWith("test"));
            var runTest = methodFunctions.Where(v => v.Name.Equals("runTest"));

            if (tests.Any()) {
                return tests;
            } else {
                return runTest;
            }
        }

        public IEnumerable<TestCaseInfo> GetTestCasesFromAst(string path) {
            IPythonModule module;
            try {
                module = AstPythonModule.FromFile(_analyzer.Interpreter, path, _analyzer.LanguageVersion);
            } catch (Exception ex) when (!ex.IsCriticalException()) {
                return Enumerable.Empty<TestCaseInfo>();
            }

            var ctxt = _analyzer.Interpreter.CreateModuleContext();
            return GetTestCasesFromAst(module, ctxt);
        }

        internal static IEnumerable<TestCaseInfo> GetTestCasesFromAst(IPythonModule module, IModuleContext ctxt) {
            if (module == null) {
                throw new ArgumentNullException(nameof(module));
            }

            foreach (var classValue in GetTestCaseClasses(module, ctxt)) {
                // Check the name of all functions on the class using the
                // analyzer. This will return functions defined on this
                // class and base classes
                foreach (var member in GetTestCaseMembers(classValue, ctxt)) {
                    // Find the definition to get the real location of the
                    // member. Otherwise decorators will confuse us.
                    var location = (member as ILocatedMember)?.Locations?.FirstOrDefault(loc => loc != null);

                    int endLine = location?.EndLine ?? location?.StartLine ?? 0;

                    yield return new TestCaseInfo(
                        (classValue as ILocatedMember)?.Locations.FirstOrDefault()?.FilePath,
                        classValue.Name,
                        member.Name,
                        location?.StartLine ?? 0,
                        location?.StartColumn ?? 1,
                        endLine
                    );
                }
            }
        }
    }
}


text:
steroids.layers.push
=================

Adds a `steroids.views.WebView` to the layer stack.

    var googleView = new steroids.views.WebView("http://www.google.com");

    steroids.layers.push(googleView);

Description
-----------

In the default configuration, the new view slides onto the screen from the right edge of the device.  On iOS, steroids.view.navigationBar appears automatically in the next view with the back button on the left. Please note: steroids.layers.push does not show the navigation bar by default on Android. In order to show the navigation bar on Android, you need to call steroids.view.navigationBar.show on the webview.

Full Example
-------------

    var googleView = new steroids.views.WebView( { location: "http://www.google.com" } );

    var myAnimation = new steroids.Animation({
      transition: "curlUp",
      duration: 0.2,
      curve: "easeInOut",
      reversedTransition: "curlDown",
      reversedDuration: 0.4
    });

    steroids.layers.push( {
      view: googleView,
      keepLoading: true,
      navigationBar: false,
      tabBar: false,
      animation: myAnimation
    }, {
      onSuccess: function() {
        alert("The view has been pushed to the layer stack.");
      },
      onFailure: function(error) {
        alert("Could not push the view: " + error.errorDescription);
      }
    });

Parameters
----------

`steroids.layers.push` accepts a single `steroids.views.WebView` object as the parameter.

Alternatively you can provide an options object, which can have the following properties:

- __view__: View to be added. Required.
- __keepLoading__: If set to `true`, then the target view will need to remove [loading.html](http://guides.appgyver.com/steroids/guides/ios/loading-html/)/[loading.png](http://guides.appgyver.com/steroids/guides/android/loading-png/) with steroids.view.removeLoading.
- __navigationBar__: If set to `false`, then steroids.view.navigationBar does not appear automatically (iOS only).
- __tabBar__: If set to `false`, then the native tab bar (if enabled in config/application.coffee), does not appear (iOS only).
- __animation__: A `steroids.Animation` object used for the animation that brings the target view onto the screen (as well as animates it away after it is popped from the layer stack).

Callbacks
---------
- __onSuccess__: Called once the view is about to be pushed.
- __onFailure__: Called if the view could not be pushed.

Supported Platforms
-------------------

- iOS
- Android (Only fade animation supported with duration 1.0 or 0.0 (appear))


text:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>Filibuster</title> <link rel="stylesheet" href="styles.css">
<link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro" rel="stylesheet">

Results for "sports_football_match"

Index

The Johnstown Dolphins vs. the Connecticut Slaves

The Miami Jets vs. the Los Angeles Dolphins

The Philadelphia Cowboys vs. the Minneapolis Cowboys

The Los Angeles Wildcats vs. the Atlanta Dogs

The Baltimore Indians vs. the Houston Soldiers

The Houston Jets vs. the Boston Doctors

The Chesterville Sharks vs. the Nebraska Ducks

The Johnstown Jets vs. the Philadelphia Bears

The San Francisco Magicians vs. the Nashville Wildcats

The Nashville Cowboys vs. the Nashville Magicians

The San Jose Dogs vs. the South Dakota Wildcats

The Oregon Jets vs. the Nevada Cowboys

The Los Angeles Ducks vs. the New Hampshire Raiders

The Houston Jets vs. the Philadelphia Buffalo

The Dallas Geese vs. the Maine Slaves

The Dallas Geese vs. the Seattle Geese

The Bryant, Fairfax County Sharks vs. the Atlanta Tigers

The Texas Tigers vs. the Houston Geese

The Philadelphia Dolphins vs. the Houston Ducks

The Iowa Raiders vs. the Detroit Indians


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.dinglicom.frame.sys.domain;

/**
 *
 * @author panzhen
 */
public class CityAddReq extends AdminReqBase{
    private long pid;
    private long cid;
    private String city;

    /**
     * @return the pid
     */
    public long getPid() {
        return pid;
    }

    /**
     * @param pid the pid to set
     */
    public void setPid(long pid) {
        this.pid = pid;
    }
    /**
     * @return the cid
     */
    public long getCid() {
        return cid;
    }

    /**
     * @param cid the cid to set
     */
    public void setCid(long cid) {
        this.cid = cid;
    }

    /**
     * @return the city
     */
    public String getCity() {
        return city;
    }

    /**
     * @param city the city to set
     */
    public void setCity(String city) {
        this.city = city;
    }
}