text:
<?php

final class NuanceGitHubEventItemType
  extends NuanceItemType {

  const ITEMTYPE = 'github.event';

  private $externalObject;
  private $externalActor;

  public function getItemTypeDisplayName() {
    return pht('GitHub Event');
  }

  public function getItemTypeDisplayIcon() {
    return 'fa-github';
  }

  public function getItemDisplayName(NuanceItem $item) {
    return $this->newRawEvent($item)->getEventFullTitle();
  }

  public function canUpdateItems() {
    return true;
  }

  protected function updateItemFromSource(NuanceItem $item) {
    $viewer = $this->getViewer();
    $is_dirty = false;

    $xobj = $this->reloadExternalObject($item);
    if ($xobj) {
      $item->setItemProperty('doorkeeper.xobj.phid', $xobj->getPHID());
      $is_dirty = true;
    }

    $actor = $this->reloadExternalActor($item);
    if ($actor) {
      $item->setRequestorPHID($actor->getPHID());
      $is_dirty = true;
    }

    if ($item->getStatus() == NuanceItem::STATUS_IMPORTING) {
      $item->setStatus(NuanceItem::STATUS_ROUTING);
      $is_dirty = true;
    }

    if ($is_dirty) {
      $item->save();
    }
  }

  private function getDoorkeeperActorRef(NuanceItem $item) {
    $raw = $this->newRawEvent($item);

    $user_id = $raw->getActorGitHubUserID();
    if (!$user_id) {
      return null;
    }

    $ref_type = DoorkeeperBridgeGitHubUser::OBJTYPE_GITHUB_USER;

    return $this->newDoorkeeperRef()
      ->setObjectType($ref_type)
      ->setObjectID($user_id);
  }

  private function getDoorkeeperRef(NuanceItem $item) {
    $raw = $this->newRawEvent($item);

    $full_repository = $raw->getRepositoryFullName();
    if (!strlen($full_repository)) {
      return null;
    }

    if ($raw->isIssueEvent()) {
      $ref_type = DoorkeeperBridgeGitHubIssue::OBJTYPE_GITHUB_ISSUE;
      $issue_number = $raw->getIssueNumber();
      $full_ref = "{$full_repository}#{$issue_number}";
    } else {
      return null;
    }

    return $this->newDoorkeeperRef()
      ->setObjectType($ref_type)
      ->setObjectID($full_ref);
  }

  private function newDoorkeeperRef() {
    return id(new DoorkeeperObjectRef())
      ->setApplicationType(DoorkeeperBridgeGitHub::APPTYPE_GITHUB)
      ->setApplicationDomain(DoorkeeperBridgeGitHub::APPDOMAIN_GITHUB);
  }

  private function reloadExternalObject(NuanceItem $item, $local = false) {
    $ref = $this->getDoorkeeperRef($item);
    if (!$ref) {
      return null;
    }

    $xobj = $this->reloadExternalRef($item, $ref, $local);

    if ($xobj) {
      $this->externalObject = $xobj;
    }

    return $xobj;
  }

  private function reloadExternalActor(NuanceItem $item, $local = false) {
    $ref = $this->getDoorkeeperActorRef($item);
    if (!$ref) {
      return null;
    }

    $xobj = $this->reloadExternalRef($item, $ref, $local);

    if ($xobj) {
      $this->externalActor = $xobj;
    }

    return $xobj;
  }

  private function reloadExternalRef(
    NuanceItem $item,
    DoorkeeperObjectRef $ref,
    $local) {

    $source = $item->getSource();
    $token = $source->getSourceProperty('github.token');
    $token = new PhutilOpaqueEnvelope($token);

    $viewer = $this->getViewer();

    $ref = id(new DoorkeeperImportEngine())
      ->setViewer($viewer)
      ->setRefs(array($ref))
      ->setThrowOnMissingLink(true)
      ->setContextProperty('github.token', $token)
      ->needLocalOnly($local)
      ->executeOne();

    if ($ref->getSyncFailed()) {
      $xobj = null;
    } else {
      $xobj = $ref->getExternalObject();
    }

    return $xobj;
  }

  private function getExternalObject(NuanceItem $item) {
    if ($this->externalObject === null) {
      $xobj = $this->reloadExternalObject($item, $local = true);
      if ($xobj) {
        $this->externalObject = $xobj;
      } else {
        $this->externalObject = false;
      }
    }

    if ($this->externalObject) {
      return $this->externalObject;
    }

    return null;
  }

  private function getExternalActor(NuanceItem $item) {
    if ($this->externalActor === null) {
      $xobj = $this->reloadExternalActor($item, $local = true);
      if ($xobj) {
        $this->externalActor = $xobj;
      } else {
        $this->externalActor = false;
      }
    }

    if ($this->externalActor) {
      return $this->externalActor;
    }

    return null;
  }

  private function newRawEvent(NuanceItem $item) {
    $type = $item->getItemProperty('api.type');
    $raw = $item->getItemProperty('api.raw', array());

    return NuanceGitHubRawEvent::newEvent($type, $raw);
  }

  public function getItemActions(NuanceItem $item) {
    $actions = array();

    $xobj = $this->getExternalObject($item);
    if ($xobj) {
      $actions[] = $this->newItemAction($item, 'reload')
        ->setName(pht('Reload from GitHub'))
        ->setIcon('fa-refresh')
        ->setWorkflow(true)
        ->setRenderAsForm(true);
    }

    $actions[] = $this->newItemAction($item, 'sync')
      ->setName(pht('Import to Maniphest'))
      ->setIcon('fa-anchor')
      ->setWorkflow(true)
      ->setRenderAsForm(true);

    $actions[] = $this->newItemAction($item, 'raw')
      ->setName(pht('View Raw Event'))
      ->setWorkflow(true)
      ->setIcon('fa-code');

    return $actions;
  }

  public function getItemCurtainPanels(NuanceItem $item) {
    $viewer = $this->getViewer();

    $panels = array();

    $xobj = $this->getExternalObject($item);
    if ($xobj) {
      $xobj_phid = $xobj->getPHID();

      $task = id(new ManiphestTaskQuery())
        ->setViewer($viewer)
        ->withBridgedObjectPHIDs(array($xobj_phid))
        ->executeOne();
      if ($task) {
        $panels[] = $this->newCurtainPanel($item)
          ->setHeaderText(pht('Imported As'))
          ->appendChild($viewer->renderHandle($task->getPHID()));
      }
    }

    $xactor = $this->getExternalActor($item);
    if ($xactor) {
      $panels[] = $this->newCurtainPanel($item)
        ->setHeaderText(pht('GitHub Actor'))
        ->appendChild($viewer->renderHandle($xactor->getPHID()));
    }

    return $panels;
  }

  protected function handleAction(NuanceItem $item, $action) {
    $viewer = $this->getViewer();
    $controller = $this->getController();

    switch ($action) {
      case 'raw':
        $raw = array(
          'api.type' => $item->getItemProperty('api.type'),
          'api.raw' => $item->getItemProperty('api.raw'),
        );

        $raw_output = id(new PhutilJSON())->encodeFormatted($raw);

        $raw_box = id(new AphrontFormTextAreaControl())
          ->setCustomClass('PhabricatorMonospaced')
          ->setLabel(pht('Raw Event'))
          ->setHeight(AphrontFormTextAreaControl::HEIGHT_VERY_TALL)
          ->setValue($raw_output);

        $form = id(new AphrontFormView())
          ->appendChild($raw_box);

        return $controller->newDialog()
          ->setWidth(AphrontDialogView::WIDTH_FULL)
          ->setTitle(pht('GitHub Raw Event'))
          ->appendForm($form)
          ->addCancelButton($item->getURI(), pht('Done'));
      case 'sync':
      case 'reload':
        $item->issueCommand($viewer->getPHID(), $action);
        return id(new AphrontRedirectResponse())->setURI($item->getURI());
    }

    return null;
  }

  protected function newItemView(NuanceItem $item) {
    $content = array();

    $content[] = $this->newGitHubEventItemPropertyBox($item);

    return $content;
  }

  private function newGitHubEventItemPropertyBox($item) {
    $viewer = $this->getViewer();

    $property_list = id(new PHUIPropertyListView())
      ->setViewer($viewer);

    $event = $this->newRawEvent($item);

    $property_list->addProperty(
      pht('GitHub Event ID'),
      $event->getID());

    $event_uri = $event->getURI();
    if ($event_uri && PhabricatorEnv::isValidRemoteURIForLink($event_uri)) {
      $event_uri = phutil_tag(
        'a',
        array(
          'href' => $event_uri,
        ),
        $event_uri);
    }

    if ($event_uri) {
      $property_list->addProperty(
        pht('GitHub Event URI'),
        $event_uri);
    }

    return id(new PHUIObjectBoxView())
      ->setHeaderText(pht('Event Properties'))
      ->setBackground(PHUIObjectBoxView::BLUE_PROPERTY)
      ->appendChild($property_list);
  }

  protected function handleCommand(
    NuanceItem $item,
    NuanceItemCommand $command) {

    $action = $command->getCommand();
    switch ($action) {
      case 'sync':
        return $this->syncItem($item, $command);
      case 'reload':
        $this->reloadExternalObject($item);
        return true;
    }

    return null;
  }

  private function syncItem(
    NuanceItem $item,
    NuanceItemCommand $command) {

    $xobj_phid = $item->getItemProperty('doorkeeper.xobj.phid');
    if (!$xobj_phid) {
      throw new Exception(
        pht(
          'Unable to sync: no external object PHID.'));
    }

    // TODO: Write some kind of marker to prevent double-synchronization.

    $viewer = $this->getViewer();

    $xobj = id(new DoorkeeperExternalObjectQuery())
      ->setViewer($viewer)
      ->withPHIDs(array($xobj_phid))
      ->executeOne();
    if (!$xobj) {
      throw new Exception(
        pht(
          'Unable to sync: failed to load object "%s".',
          $xobj_phid));
    }

    $acting_as_phid = $this->getActingAsPHID($item);

    $xactions = array();

    $task = id(new ManiphestTaskQuery())
      ->setViewer($viewer)
      ->withBridgedObjectPHIDs(array($xobj_phid))
      ->executeOne();
    if (!$task) {
      $task = ManiphestTask::initializeNewTask($viewer)
        ->setAuthorPHID($acting_as_phid)
        ->setBridgedObjectPHID($xobj_phid);

      $title = $xobj->getProperty('task.title');
      if (!strlen($title)) {
        $title = pht('Nuance Item %d Task', $item->getID());
      }

      $description = $xobj->getProperty('task.description');
      $created = $xobj->getProperty('task.created');
      $state = $xobj->getProperty('task.state');

      $xactions[] = id(new ManiphestTransaction())
        ->setTransactionType(ManiphestTransaction::TYPE_TITLE)
        ->setNewValue($title)
        ->setDateCreated($created);

      $xactions[] = id(new ManiphestTransaction())
        ->setTransactionType(ManiphestTransaction::TYPE_DESCRIPTION)
        ->setNewValue($description)
        ->setDateCreated($created);

      $task->setDateCreated($created);

      // TODO: Synchronize state.
    }

    $event = $this->newRawEvent($item);
    $comment = $event->getComment();
    if (strlen($comment)) {
      $xactions[] = id(new ManiphestTransaction())
        ->setTransactionType(PhabricatorTransactions::TYPE_COMMENT)
        ->attachComment(
          id(new ManiphestTransactionComment())
            ->setContent($comment));
    }

    $agent_phid = $command->getAuthorPHID();
    $source = $this->newContentSource($item, $agent_phid);

    $editor = id(new ManiphestTransactionEditor())
      ->setActor($viewer)
      ->setActingAsPHID($acting_as_phid)
      ->setContentSource($source)
      ->setContinueOnNoEffect(true)
      ->setContinueOnMissingFields(true);

    $xactions = $editor->applyTransactions($task, $xactions);

    return array(
      'objectPHID' => $task->getPHID(),
      'xactionPHIDs' => mpull($xactions, 'getPHID'),
    );
  }

  protected function getActingAsPHID(NuanceItem $item) {
    $actor_phid = $item->getRequestorPHID();

    if ($actor_phid) {
      return $actor_phid;
    }

    return parent::getActingAsPHID($item);
  }

}


text:
namespace Moonfish.Guerilla.Tags
{
    using Moonfish.Tags;
    using Moonfish.Model;
    using System.IO;
    using System.Collections.Generic;
    using System.Linq;

    public partial class GlobalGeometryPartBlockNew : GuerillaBlock, IWriteQueueable
    {
        public TypeEnum Type;
        public Flags GlobalGeometryPartNewFlags;
        public Moonfish.Tags.ShortBlockIndex1 Material;
        public short StripStartIndex;
        public short StripLength;
        public short FirstSubpartIndex;
        public short SubpartCount;
        public byte MaxNodesVertex;
        public byte ContributingCompoundNodeCount;
        /// <summary>
        /// EMPTY STRING
        /// </summary>
        public OpenTK.Vector3 Position;
        public NodeIndicesBlock[] NodeIndices00 = new NodeIndicesBlock[4];
        public NodeWeightsBlock[] NodeWeights00 = new NodeWeightsBlock[3];
        public float LodMipmapMagicNumber;
        private byte[] fieldskip = new byte[24];
        public override int SerializedSize
        {
            get
            {
                return 72;
            }
        }
        public override int Alignment
        {
            get
            {
                return 4;
            }
        }
        public override System.Collections.Generic.Queue<Moonfish.Tags.BlamPointer> ReadFields(System.IO.BinaryReader binaryReader)
        {
            System.Collections.Generic.Queue<Moonfish.Tags.BlamPointer> pointerQueue = new System.Collections.Generic.Queue<Moonfish.Tags.BlamPointer>(base.ReadFields(binaryReader));
            this.Type = ((TypeEnum)(binaryReader.ReadInt16()));
            this.GlobalGeometryPartNewFlags = ((Flags)(binaryReader.ReadInt16()));
            this.Material = binaryReader.ReadShortBlockIndex1();
            this.StripStartIndex = binaryReader.ReadInt16();
            this.StripLength = binaryReader.ReadInt16();
            this.FirstSubpartIndex = binaryReader.ReadInt16();
            this.SubpartCount = binaryReader.ReadInt16();
            this.MaxNodesVertex = binaryReader.ReadByte();
            this.ContributingCompoundNodeCount = binaryReader.ReadByte();
            this.Position = binaryReader.ReadVector3();
            int i;
            for (i = 0; (i < 4); i = (i + 1))
            {
                this.NodeIndices00[i] = new NodeIndicesBlock();
                pointerQueue = new System.Collections.Generic.Queue<Moonfish.Tags.BlamPointer>(pointerQueue.Concat(this.NodeIndices00[i].ReadFields(binaryReader)));
            }
            for (i = 0; (i < 3); i = (i + 1))
            {
                this.NodeWeights00[i] = new NodeWeightsBlock();
                pointerQueue = new System.Collections.Generic.Queue<Moonfish.Tags.BlamPointer>(pointerQueue.Concat(this.NodeWeights00[i].ReadFields(binaryReader)));
            }
            this.LodMipmapMagicNumber = binaryReader.ReadSingle();
            this.fieldskip = binaryReader.ReadBytes(24);
            return pointerQueue;
        }
        public override void ReadInstances(System.IO.BinaryReader binaryReader, System.Collections.Generic.Queue<Moonfish.Tags.BlamPointer> pointerQueue)
        {
            base.ReadInstances(binaryReader, pointerQueue);
            int i;
            for (i = 0; (i < 4); i = (i + 1))
            {
                this.NodeIndices00[i].ReadInstances(binaryReader, pointerQueue);
            }
            for (i = 0; (i < 3); i = (i + 1))
            {
                this.NodeWeights00[i].ReadInstances(binaryReader, pointerQueue);
            }
        }
        public override void QueueWrites(Moonfish.Guerilla.QueueableBinaryWriter queueableBinaryWriter)
        {
            base.QueueWrites(queueableBinaryWriter);
            int i;
            for (i = 0; (i < 4); i = (i + 1))
            {
                this.NodeIndices00[i].QueueWrites(queueableBinaryWriter);
            }
            for (i = 0; (i < 3); i = (i + 1))
            {
                this.NodeWeights00[i].QueueWrites(queueableBinaryWriter);
            }
        }
        public override void Write_(Moonfish.Guerilla.QueueableBinaryWriter queueableBinaryWriter)
        {
            base.Write_(queueableBinaryWriter);
            queueableBinaryWriter.Write(((short)(this.Type)));
            queueableBinaryWriter.Write(((short)(this.GlobalGeometryPartNewFlags)));
            queueableBinaryWriter.Write(this.Material);
            queueableBinaryWriter.Write(this.StripStartIndex);
            queueableBinaryWriter.Write(this.StripLength);
            queueableBinaryWriter.Write(this.FirstSubpartIndex);
            queueableBinaryWriter.Write(this.SubpartCount);
            queueableBinaryWriter.Write(this.MaxNodesVertex);
            queueableBinaryWriter.Write(this.ContributingCompoundNodeCount);
            queueableBinaryWriter.Write(this.Position);
            int i;
            for (i = 0; (i < 4); i = (i + 1))
            {
                this.NodeIndices00[i].Write_(queueableBinaryWriter);
            }
            for (i = 0; (i < 3); i = (i + 1))
            {
                this.NodeWeights00[i].Write_(queueableBinaryWriter);
            }
            queueableBinaryWriter.Write(this.LodMipmapMagicNumber);
            queueableBinaryWriter.Write(this.fieldskip);
        }
        public enum TypeEnum : short
        {
            NotDrawn = 0,
            OpaqueShadowOnly = 1,
            OpaqueShadowCasting = 2,
            OpaqueNonshadowing = 3,
            Transparent = 4,
            LightmapOnly = 5,
        }
        [System.FlagsAttribute()]
        public enum Flags : short
        {
            None = 0,
            Decalable = 1,
            NewPartTypes = 2,
            DislikesPhotons = 4,
            OverrideTriangleList = 8,
            IgnoredByLightmapper = 16,
        }
        public class NodeIndicesBlock : GuerillaBlock, IWriteQueueable
        {
            public byte NodeIndex;
            public override int SerializedSize
            {
                get
                {
                    return 1;
                }
            }
            public override int Alignment
            {
                get
                {
                    return 1;
                }
            }
            public override System.Collections.Generic.Queue<Moonfish.Tags.BlamPointer> ReadFields(System.IO.BinaryReader binaryReader)
            {
                System.Collections.Generic.Queue<Moonfish.Tags.BlamPointer> pointerQueue = new System.Collections.Generic.Queue<Moonfish.Tags.BlamPointer>(base.ReadFields(binaryReader));
                this.NodeIndex = binaryReader.ReadByte();
                return pointerQueue;
            }
            public override void ReadInstances(System.IO.BinaryReader binaryReader, System.Collections.Generic.Queue<Moonfish.Tags.BlamPointer> pointerQueue)
            {
                base.ReadInstances(binaryReader, pointerQueue);
            }
            public override void QueueWrites(Moonfish.Guerilla.QueueableBinaryWriter queueableBinaryWriter)
            {
                base.QueueWrites(queueableBinaryWriter);
            }
            public override void Write_(Moonfish.Guerilla.QueueableBinaryWriter queueableBinaryWriter)
            {
                base.Write_(queueableBinaryWriter);
                queueableBinaryWriter.Write(this.NodeIndex);
            }
        }
        public class NodeWeightsBlock : GuerillaBlock, IWriteQueueable
        {
            public float NodeWeight;
            public override int SerializedSize
            {
                get
                {
                    return 4;
                }
            }
            public override int Alignment
            {
                get
                {
                    return 1;
                }
            }
            public override System.Collections.Generic.Queue<Moonfish.Tags.BlamPointer> ReadFields(System.IO.BinaryReader binaryReader)
            {
                System.Collections.Generic.Queue<Moonfish.Tags.BlamPointer> pointerQueue = new System.Collections.Generic.Queue<Moonfish.Tags.BlamPointer>(base.ReadFields(binaryReader));
                this.NodeWeight = binaryReader.ReadSingle();
                return pointerQueue;
            }
            public override void ReadInstances(System.IO.BinaryReader binaryReader, System.Collections.Generic.Queue<Moonfish.Tags.BlamPointer> pointerQueue)
            {
                base.ReadInstances(binaryReader, pointerQueue);
            }
            public override void QueueWrites(Moonfish.Guerilla.QueueableBinaryWriter queueableBinaryWriter)
            {
                base.QueueWrites(queueableBinaryWriter);
            }
            public override void Write_(Moonfish.Guerilla.QueueableBinaryWriter queueableBinaryWriter)
            {
                base.Write_(queueableBinaryWriter);
                queueableBinaryWriter.Write(this.NodeWeight);
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
gsl_rng * RANDOM_NUMBER = NULL;

void print_usage_and_exit() {
  // print usage information

  printf("\nC++ implementation of Gibbs sampling for hierarchical Dirichlet process, a much faster version.\n");
  printf("Authors: Chong Wang, chongw@cs.princeton.edu, Computer Science Department, Princeton University.\n");

  printf("usage:\n");
  printf("      hdp               [options]\n");
  printf("      --help:           print help information.\n");
  printf("      --verbose:        print running information.\n");
  printf("\n");

  printf("      control parameters:\n");
  printf("      --directory:       the saving directory, required.\n");
  printf("      --random_seed:     the random seed, default from the current time.\n");
  printf("      --max_iter:        the max number of iterations, default 100 (-1 means infinite).\n");
  printf("      --max_time:        the max time allowed (in seconds), default 1800 (-1 means infinite).\n");
  printf("      --save_lag:        the saving point, default 5.\n");
  printf("\n");

  printf("      data parameters:\n");
  printf("      --train_data:      the training data file/pattern, in lda-c format.\n");
  printf("\n");

  printf("      model parameters:\n");
  printf("      --eta:             the topic Dirichlet parameter, default 0.05.\n");
  printf("      --gamma:           the first-level concentration parameter in hdp, default 1.0.\n");
  printf("      --alpha:           the second-level concentration parameter in hdp, default 1.0.\n");

  printf("      --gamma_a:        shape for 1st-level concentration parameter, default 1.0.\n");
  printf("      --gamma_b:        scale for 1st-level concentration parameter, default 1.0.\n");
  printf("      --alpha_a:        shape for 2nd-level concentration parameter, default 1.0.\n");
  printf("      --alpha_b:        scale for 2nd-level concentration parameter, default 1.0.\n");
  printf("      --sample_hyper:   sample 1st and 2nd-level concentration parameter, default false\n");
  printf("\n");

  printf("      test only parameters:\n");
  printf("      --test_data:       the test data file/pattern, in lda-c format.\n");
  printf("      --model_prefix:    the model_prefix.\n");

  printf("*******************************************************************************************************\n");

  exit(0);
}

int main(int argc, char* argv[]) {
  if (argc < 2) print_usage_and_exit();

  int verbose = 0;

  // Control parameters.
  char*  directory = NULL;
  time_t t; time(&t);
  long   random_seed = (long) t;
  int    max_iter = 100;
  int    max_time = 1800;
  int    save_lag = 5;

  // Data parameters.
  char* train_data = NULL;

  // Model parameters.
  double eta = 0.01;
  double gamma = 1.0;
  double alpha = 1.0;
  double gamma_a = 1.0;
  double gamma_b = 1.0;
  double alpha_a = 1.0;
  double alpha_b = 1.0;
  int sample_hyper = 0;

  // test only parameters
  char* test_data = NULL;
  char* model_prefix = NULL;

  for (int i = 1; i < argc; ++i) {
    if (!strcmp(argv[i], "--help")) print_usage_and_exit();
    else if (!strcmp(argv[i], "--verbose"))        verbose = 1;

    else if (!strcmp(argv[i], "--directory"))       directory = argv[++i];
    else if (!strcmp(argv[i], "--random_seed"))     random_seed = atoi(argv[++i]);
    else if (!strcmp(argv[i], "--max_iter"))        max_iter = atoi(argv[++i]);
    else if (!strcmp(argv[i], "--max_time"))        max_time = atoi(argv[++i]);
    else if (!strcmp(argv[i], "--save_lag"))        save_lag = atoi(argv[++i]);

    else if (!strcmp(argv[i], "--train_data"))      train_data = argv[++i];

    else if (!strcmp(argv[i], "--eta"))             eta = atof(argv[++i]);
    else if (!strcmp(argv[i], "--gamma"))           gamma = atof(argv[++i]);
    else if (!strcmp(argv[i], "--alpha"))           alpha = atof(argv[++i]);
    else if (!strcmp(argv[i], "--gamma_a"))         gamma_a = atof(argv[++i]);
    else if (!strcmp(argv[i], "--gamma_b"))         gamma_b = atof(argv[++i]);
    else if (!strcmp(argv[i], "--gamma_a"))         gamma_a = atof(argv[++i]);
    else if (!strcmp(argv[i], "--gamma_b"))         gamma_b = atof(argv[++i]);
    else if (!strcmp(argv[i], "--sample_hyper"))    sample_hyper = 1;

    else if (!strcmp(argv[i], "--test_data"))       test_data = argv[++i];
    else if (!strcmp(argv[i], "--model_prefix"))    model_prefix = argv[++i];
    else {
      printf("%s, unknown parameters, exit\n", argv[i]);
      print_usage_and_exit();
    }
  }
  /// print information
  printf("************************************************************************************************\n");

  if (directory == NULL)  {
    printf("Following information is missing: --directory\n");
    printf("Run ./hdp for help.\n");
    exit(0);
  }

  if (!dir_exists(directory)) make_directory(directory);
  printf("Working directory: %s.\n", directory);

  char name[500];
  // Init random numbe generator.
  RANDOM_NUMBER = new_random_number_generator(random_seed);

  if (test_data == NULL || model_prefix == NULL) {
    sprintf(name, "%s/settings.dat", directory);
    printf("Setting saved at %s.\n", name);
    FILE* setting_file = fopen(name, "w");

    fprintf(setting_file, "Control parameters:\n");
    fprintf(setting_file, "directory: %s\n", directory);
    fprintf(setting_file, "random_seed: %d\n", (int)random_seed);
    fprintf(setting_file, "save_lag: %d\n", save_lag);
    fprintf(setting_file, "max_iter: %d\n", max_iter);
    fprintf(setting_file, "max_time: %d\n", max_time);

    fprintf(setting_file, "\nData parameters:\n");
    fprintf(setting_file, "train_data: %s\n", train_data);

    fprintf(setting_file, "\nModel parameters:\n");
    fprintf(setting_file, "eta: %.4lf\n", eta);
    fprintf(setting_file, "gamma: %.4lf\n", gamma);
    fprintf(setting_file, "alpha: %.4lf\n", alpha);
    fprintf(setting_file, "gamma_a: %.2lf\n", gamma_a);
    fprintf(setting_file, "gamma_b: %.4lf\n", gamma_b);
    fprintf(setting_file, "gamma_a: %.2lf\n", alpha_a);
    fprintf(setting_file, "gamma_b: %.4lf\n", alpha_b);
    fprintf(setting_file, "sample_hyper: %d\n", sample_hyper);

    fclose(setting_file);

    Corpus* c_train = NULL;

    printf("Reading training data from %s.\n", train_data);
    // Reading one of the train data.
    c_train = new Corpus();
    c_train->read_data(train_data);

    // Open the log file for training data.
    sprintf(name, "%s/train.log", directory);
    FILE* train_log = fopen(name, "w");
    // Heldout columns record the documents that have not seen before.
    sprintf(name, "time\titer\tnum.topics\tgamma\talpha\t\tword.count\tlikelihood\tavg.likelihood");
    if(verbose) printf("%s\n", name);
    fprintf(train_log, "%s\n", name);

    // Start iterating.
    time_t start, current;
    int total_time = 0;
    int iter = 0;

    HDP* hdp = new HDP();
    hdp->init_hdp(eta, gamma, alpha, c_train->size_vocab_);

    // Setting up the hdp state.
    hdp->setup_doc_states(c_train->docs_);
    // first iteration
    hdp->iterate_gibbs_state(false, false);

    while ((max_iter == -1 || iter < max_iter) && (max_time == -1 || total_time < max_time)) {
      ++iter;
      time (&start);

      // Iterations.
      hdp->iterate_gibbs_state(true, true);
      // Scoring the documents.
      double likelihood = hdp->log_likelihood(NULL);
      hdp->compact_hdp_state();

      if (sample_hyper) hdp->hyper_inference(gamma_a, gamma_b, alpha_a, alpha_b);

      // Record the time.
      time(&current);
      int elapse = (int) difftime(current, start);
      total_time += elapse;

      sprintf(name, "%d\t%d\t%d\t\t%.5f\t%.5f\t\t%d\t\t%.3f\t%.5f",
              total_time, iter, hdp->hdp_state_->num_topics_, hdp->hdp_state_->gamma_,
              hdp->hdp_state_->alpha_, c_train->num_total_words_, likelihood, likelihood/c_train->num_total_words_);

      if (verbose) printf("%s\n", name);
      fprintf(train_log, "%s\n", name);
      fflush(train_log);

      if (save_lag > 0 && (iter % save_lag == 0)) {
        sprintf(name, "%s/iter@%05d", directory, iter);
        hdp->save_state(name);
      }
    }

    sprintf(name, "%s/final", directory);
    hdp->save_state(name);

    // Free training data.
    if (c_train != NULL) {
      delete c_train;
    }
    fclose(train_log);

    delete hdp;
  }

  if (test_data != NULL && model_prefix != NULL) {
    Corpus* c_test = new Corpus();
    c_test->read_data(test_data);

    HDP* hdp = new HDP();
    printf("Loading model from prefix %s...\n", model_prefix);
    hdp->load_state(model_prefix);

    // Remember the old state.
    HDPState* old_hdp_state = new HDPState();
    old_hdp_state->copy_hdp_state(*hdp->hdp_state_);

    hdp->setup_doc_states(c_test->docs_);

    if (verbose) printf("Initialization ...\n");
    hdp->iterate_gibbs_state(false, false);

    sprintf(name, "%s/%s-test.log", directory, basename(model_prefix));
    FILE* test_log = fopen(name, "w");
    sprintf(name, "time\titer\tnum.topics\tword.count\tlikelihood\tavg.likelihood");
    if(verbose) printf("%s\n", name);
    fprintf(test_log, "%s\n", name);

    time_t start, current;
    int total_time = 0;
    int iter = 0;

    // Iterations.
    while ((max_iter == -1 || iter < max_iter) && (max_time == -1 || total_time < max_time)) {
      ++iter;
      time (&start);
      hdp->iterate_gibbs_state(true, true);
      double likelihood = hdp->log_likelihood(old_hdp_state);
      hdp->compact_hdp_state();
      time(&current);
      int elapse = (int) difftime(current, start);
      total_time += elapse;

      sprintf(name, "%d\t%d\t%d\t\t%d\t\t%.3f\t%.5f",
              total_time, iter, hdp->hdp_state_->num_topics_,
              c_test->num_total_words_, likelihood,
              likelihood/c_test->num_total_words_);

      if (verbose) printf("%s\n", name);
      fprintf(test_log, "%s\n", name);
      fflush(test_log);
    }

    if (verbose) printf("Done and saving ...\n");
    sprintf(name, "%s/%s-test", directory, basename(model_prefix));
    hdp->save_state(name);
    hdp->save_doc_states(name);
    fclose(test_log);

    delete hdp;
    delete old_hdp_state;
    delete c_test;
  }

  // Free random number generator.
  free_random_number_generator(RANDOM_NUMBER);
  return 0;
}


text:
namespace android.database
{
	[global::MonoJavaBridge.JavaClass()]
	public partial class CursorIndexOutOfBoundsException : java.lang.IndexOutOfBoundsException
	{
		internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
		protected CursorIndexOutOfBoundsException(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
		{
		}
		private static global::MonoJavaBridge.MethodId _m0;
		public CursorIndexOutOfBoundsException(int arg0, int arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
		{
			global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
			if (global::android.database.CursorIndexOutOfBoundsException._m0.native == global::System.IntPtr.Zero)
				global::android.database.CursorIndexOutOfBoundsException._m0 = @__env.GetMethodIDNoThrow(global::android.database.CursorIndexOutOfBoundsException.staticClass, "<init>", "(II)V");
			global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.database.CursorIndexOutOfBoundsException.staticClass, global::android.database.CursorIndexOutOfBoundsException._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
			Init(@__env, handle);
		}
		private static global::MonoJavaBridge.MethodId _m1;
		public CursorIndexOutOfBoundsException(java.lang.String arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
		{
			global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
			if (global::android.database.CursorIndexOutOfBoundsException._m1.native == global::System.IntPtr.Zero)
				global::android.database.CursorIndexOutOfBoundsException._m1 = @__env.GetMethodIDNoThrow(global::android.database.CursorIndexOutOfBoundsException.staticClass, "<init>", "(Ljava/lang/String;)V");
			global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.database.CursorIndexOutOfBoundsException.staticClass, global::android.database.CursorIndexOutOfBoundsException._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
			Init(@__env, handle);
		}
		static CursorIndexOutOfBoundsException()
		{
			global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
			global::android.database.CursorIndexOutOfBoundsException.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/database/CursorIndexOutOfBoundsException"));
		}
	}
}


text:
"""Cement core output module."""

from ..core import backend, exc, interface, handler

Log = backend.minimal_logger(__name__)

def output_validator(klass, obj):
    """Validates an handler implementation against the IOutput interface."""

    members = [
        '_setup',
        'render',
        ]
    interface.validate(IOutput, obj, members)

class IOutput(interface.Interface):
    """
    This class defines the Output Handler Interface.  Classes that
    implement this handler must provide the methods and attributes defined
    below.

    Implementations do *not* subclass from interfaces.

    Usage:

    .. code-block:: python

        from cement.core import output

        class MyOutputHandler(object):
            class Meta:
                interface = output.IOutput
                label = 'my_output_handler'
            ...

    """
    class IMeta:
        label = 'output'
        validator = output_validator

    # Must be provided by the implementation
    Meta = interface.Attribute('Handler Meta-data')

    def _setup(app_obj):
        """
        The _setup function is called during application initialization and
        must 'setup' the handler object making it ready for the framework
        or the application to make further calls to it.

        Required Arguments:

            app_obj
                The application object.

        Returns: n/a
        """

    def render(data_dict, template=None):
        """
        Render the data_dict into output in some fashion.

        Required Arguments:

            data_dict
                The dictionary whose data we need to render into output.

        Optional Paramaters:

            template
                A template to use for rendering (in module form).  I.e.
                myapp.templates.some_command

        Returns: string or unicode string or None

        """

class CementOutputHandler(handler.CementBaseHandler):
    """
    Base class that all Output Handlers should sub-class from.

    """
    class Meta:
        interface = IOutput

    def __init__(self, *args, **kw):
        super(CementOutputHandler, self).__init__(*args, **kw)


text:
<?php

namespace Mxtb\Tests\Model\Lookup\Network;

use Mxtb\Model\Lookup\Network\Http;

class HttpTest extends \PHPUnit_Framework_TestCase
{
    public function testCanSetInfo()
    {
        // Arrange
		$response = new Http();

        // Act
        $response->setUid('test info');
        $response->setCommand('test info');
        $response->setIsTransitioned(true);
        $response->setCommandArgument('test info');
        $response->setTimeRecorded('2016-01-18T04:46:02.0961705-06:00');
        $response->setReportingNameServer('test info');
        $response->setTimeToComplete('test info');
        $response->setRelatedIP('test info');
        $response->setIsEndpoint(true);
        $response->setHasSubscriptions(true);
        $response->setIsBruteForce(true);
        $response->setMxRep(123);
        $response->setEmailServiceProvider('test info');
        $response->setRelatedLookups(['test key' => 'test info']);
        $response->setTimeouts(['test key' => 'test info']);

        $response->setTranscript(['test key' => 'test info']);

        $response->setPassed(['test key' => 'test info']);
        $response->setInformation(['test key' => 'test info']);

        // Assert
        $this->assertEquals('test info', $response->getUid());
        $this->assertEquals('test info', $response->getCommand());
        $this->assertEquals(true, $response->getIsTransitioned());
        $this->assertEquals('test info', $response->getCommandArgument());
        $this->assertInstanceOf(\DateTime::class, $response->getTimeRecorded());
        $this->assertEquals('test info', $response->getReportingNameServer());
        $this->assertEquals('test info', $response->getTimeToComplete());
        $this->assertEquals('test info', $response->getRelatedIP());
        $this->assertEquals(true, $response->getIsEndpoint());
        $this->assertEquals(true, $response->getHasSubscriptions());
        $this->assertEquals(true, $response->getIsBruteForce());
        $this->assertEquals(123, $response->getMxRep());
        $this->assertEquals('test info', $response->getEmailServiceProvider());
        $this->assertEquals('test info', $response->getRelatedLookups()['test key']);
        $this->assertEquals('test info', $response->getTimeouts()['test key']);

        $this->assertEquals('test info', $response->getTranscript()['test key']);

        $this->assertEquals('test info', $response->getPassed()['test key']);
        $this->assertEquals('test info', $response->getInformation()['test key']);
    }
}


text:
package jdepend.metadata.annotation;

public class Qualifier implements Annotation {

	private static final long serialVersionUID = -2441646634122188475L;

	private String value;

	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		this.value = value;
	}

	@Override
	public String toString() {
		if (value != null) {
			return "Qualifier [value=" + value + "]";
		} else {
			return "Qualifier";
		}
	}

	public boolean direct(Service service) {

		if (this.value == null) {
			return false;
		}

		if (service == null || service.getValue() == null) {
			return false;
		}

		return this.value.equals(service.getValue());

	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((value == null) ? 0 : value.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Qualifier other = (Qualifier) obj;
		if (value == null) {
			if (other.value != null)
				return false;
		} else if (!value.equals(other.value))
			return false;
		return true;
	}
}


text:
var gulp = require('gulp'),
	jshint = require('gulp-jshint'),
	stylish = require('jshint-stylish');

gulp.task('jsHint', function() {
	return gulp.src('app/resources/js/*.js')
		.pipe(jshint())
		.pipe(jshint.reporter(stylish))
		.pipe(jshint.reporter('fail'));
});


text:
package core

import (
	"encoding/json"
	"fmt"
	"github.com/sirupsen/logrus"
	"hash/fnv"
	"time"
)

type messageTracer struct {
	msg      *Message
	pluginID string
}

// codebeat:disable[TOO_MANY_IVARS]
type messageDump struct {
	Step            string
	PluginID        string
	Payload         string
	OriginalPayload string
	Stream          string
	PrevStream      string
	OrigStream      string
	Metadata        map[string]string
	Source          string
	Timestamp       time.Time
	FingerprintID   uint32
}

// codebeat:enable[TOO_MANY_IVARS]

type messageTracerSource struct {
}

// IsActive returns true if the source can produce messages
func (mts messageTracerSource) IsActive() bool {
	return true
}

// IsBlocked returns true if the source cannot produce messages
func (mts messageTracerSource) IsBlocked() bool {
	return false
}

// GetID returns the pluginID of the message source
func (mts messageTracerSource) GetID() string {
	return "core.MessageTracer"
}

// MessageTrace provide the MessageTrace() function. By default this function do nothing.
var MessageTrace = func(msg *Message, pluginID string, comment string) {}

// ActivateMessageTrace set a MessageTrace function to dump out the message trace
func ActivateMessageTrace() {
	MessageTrace = func(msg *Message, pluginID string, comment string) {
		mt := messageTracer{
			msg:      msg,
			pluginID: pluginID,
		}

		mt.Dump(comment)
	}
}

// DeactivateMessageTrace set a MessageTrace function to default
// This method is necessary for unit testing
func DeactivateMessageTrace() {
	MessageTrace = func(msg *Message, pluginID string, comment string) {}
}

// Dump creates a messageDump struct for the message trace
func (mt *messageTracer) Dump(comment string) {
	if mt.msg.streamID == LogInternalStreamID || mt.msg.streamID == TraceInternalStreamID {
		return
	}

	var err error
	msgDump := mt.newMessageDump(mt.msg, comment)

	if StreamRegistry.IsStreamRegistered(TraceInternalStreamID) {
		err = mt.routeToTraceStream(msgDump)

	} else {
		err = mt.printMessageTrace(msgDump)
	}

	if err != nil {
		logrus.Error(err)
	}
}

func (mt *messageTracer) printMessageTrace(dump messageDump) error {
	jsonData, err := json.MarshalIndent(dump, "", "\t")
	if err == nil {
		_, err = fmt.Println("\n", string(jsonData))
	}

	return err
}

func (mt *messageTracer) routeToTraceStream(dump messageDump) error {
	jsonData, err := json.Marshal(dump)
	if err != nil {
		return err
	}

	traceMsg := NewMessage(messageTracerSource{}, jsonData, nil, TraceInternalStreamID)
	traceRouter := StreamRegistry.GetRouterOrFallback(TraceInternalStreamID)

	return traceRouter.Enqueue(traceMsg)
}

func (mt *messageTracer) newMessageDump(msg *Message, comment string) messageDump {
	dump := messageDump{}
	// set general trace info
	dump.Step = comment
	dump.PluginID = mt.pluginID

	// prepare message payloads data
	dump.Payload = msg.String()
	if msg.orig != nil {
		dump.OriginalPayload = string(msg.orig.payload)
	}

	// prepare message streams data
	dump.Stream = mt.getStreamName(msg.streamID)
	dump.PrevStream = mt.getStreamName(msg.prevStreamID)
	dump.OrigStream = mt.getStreamName(msg.origStreamID)

	// prepare meta data
	if metadata := msg.TryGetMetadata(); metadata != nil {
		dump.Metadata = map[string]string{}
		for k, v := range metadata {
			dump.Metadata[k] = string(v)
		}
	}

	// set source data
	if msg.source != nil {
		dump.Source = msg.source.GetID()
	}

	//  set timestamp
	dump.Timestamp = msg.timestamp

	dump.FingerprintID = mt.createFingerPrintID(&dump)

	return dump
}

func (mt *messageTracer) createFingerPrintID(dump *messageDump) uint32 {
	hash := fnv.New32a()

	hash.Write([]byte(dump.Source))
	hash.Write([]byte(dump.Timestamp.String()))

	return hash.Sum32()
}

// get stream name and translate InvalidStreamID ("") to InvalidStream
func (mt *messageTracer) getStreamName(streamID MessageStreamID) string {
	if streamID == InvalidStreamID {
		return "InvalidStream"
	}

	return StreamRegistry.GetStreamName(streamID)
}


text:
import { moduleFor, test } from 'ember-qunit';

moduleFor('route:scan/results', 'Unit | Route | scan/results', {
  // Specify the other units that are required for this test.
  // needs: ['controller:foo']
  needs: ['service:imageData', 'service:scanner']
});

test('it exists', function(assert) {
  let route = this.subject();
  assert.ok(route);
});


text:
package org.wso2.msf4j.client.test.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wso2.msf4j.client.test.exception.InvoiceNotFoundException;
import org.wso2.msf4j.client.test.model.Invoice;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * CustomerService resource class.
 */
@Path("/invoice")
public class InvoiceService {

    private static final Logger log = LoggerFactory.getLogger(InvoiceService.class);
    private Map<String, Invoice> invoiceMap = new HashMap<>();

    public InvoiceService() {
        invoiceMap.put("I001", new Invoice("I001", "C001", 250.15));
    }

    /**
     * Retrieves an invoice record for a given invoice ID.
     * http://localhost:8080/invoice/I001
     *
     * @param id Invoice ID will be taken from the path parameter.
     * @return
     */
    @GET
    @Path("/{id}")
    @Produces({"application/json"})
    public Response getCustomer(@PathParam("id") String id) throws InvoiceNotFoundException {
        Invoice invoice = invoiceMap.get(id);
        if (invoice == null) {
            log.info("Request for non-existing invoice: " + id);
            throw new InvoiceNotFoundException("Invoice ID " + id + " not found");
        }
        return Response.status(Response.Status.OK).entity(invoice).build();
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

 <meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1">
 <title>TRIO</title>
 <link href="trio.css" rel="stylesheet" type="text/css">

Main Page   Modules

Static String Functions.
Replacements for the standard C string functions.
More...

Functions

TRIO_PUBLIC_STRING char * 	trio_create (size_t size)

 	Create new string.

TRIO_PUBLIC_STRING void 	trio_destroy (char *string)

 	Destroy string.

TRIO_PUBLIC_STRING size_t 	trio_length (const char *string)

 	Count the number of characters in a string.

TRIO_PUBLIC_STRING int 	trio_append (char *target, const char *source)

 	Append source at the end of target.

TRIO_PUBLIC_STRING int 	trio_append_max (char *target, size_t max, const char *source)

 	Append at most max characters from source to target.

TRIO_PUBLIC_STRING int 	trio_contains (const char *string, const char *substring)

 	Determine if a string contains a substring.

TRIO_PUBLIC_STRING int 	trio_copy (char *target, const char *source)

 	Copy source to target.

TRIO_PUBLIC_STRING int 	trio_copy_max (char *target, size_t max, const char *source)

 	Copy at most max characters from source to target.

TRIO_PUBLIC_STRING char * 	trio_duplicate (const char *source)

 	Duplicate source.

TRIO_PUBLIC_STRING char * 	trio_duplicate_max (const char *source, size_t max)

 	Duplicate at most max characters of source.

TRIO_PUBLIC_STRING int 	trio_equal (const char *first, const char *second)

 	Compare if two strings are equal.

TRIO_PUBLIC_STRING int 	trio_equal_case (const char *first, const char *second)

 	Compare if two strings are equal.

TRIO_PUBLIC_STRING int 	trio_equal_case_max (const char *first, size_t max, const char *second)

 	Compare if two strings up until the first max characters are equal.

TRIO_PUBLIC_STRING int 	trio_equal_locale (const char *first, const char *second)

 	Compare if two strings are equal.

TRIO_PUBLIC_STRING int 	trio_equal_max (const char *first, size_t max, const char *second)

 	Compare if two strings up until the first max characters are equal.

TRIO_PUBLIC_STRING const char * 	trio_error (int error_number)

 	Provide a textual description of an error code (errno).

TRIO_PUBLIC_STRING size_t 	trio_format_date_max (char *target, size_t max, const char *format, const struct tm *datetime)

 	Format the date/time according to format.

TRIO_PUBLIC_STRING unsigned

long 	trio_hash (const char *string, int type)

 	Calculate a hash value for a string.

TRIO_PUBLIC_STRING char * 	trio_index (const char *string, int character)

 	Find first occurrence of a character in a string.

TRIO_PUBLIC_STRING char * 	trio_index_last (const char *string, int character)

 	Find last occurrence of a character in a string.

TRIO_PUBLIC_STRING int 	trio_lower (char *target)

 	Convert the alphabetic letters in the string to lower-case.

TRIO_PUBLIC_STRING int 	trio_match (const char *string, const char *pattern)

 	Compare two strings using wildcards.

TRIO_PUBLIC_STRING int 	trio_match_case (const char *string, const char *pattern)

 	Compare two strings using wildcards.

TRIO_PUBLIC_STRING size_t 	trio_span_function (char *target, const char *source, int(*Function)(int))

 	Execute a function on each character in string.

TRIO_PUBLIC_STRING char * 	trio_substring (const char *string, const char *substring)

 	Search for a substring in a string.

TRIO_PUBLIC_STRING char * 	trio_substring_max (const char *string, size_t max, const char *substring)

 	Search for a substring in the first max characters of a string.

TRIO_PUBLIC_STRING char * 	trio_tokenize (char *string, const char *delimiters)

 	Tokenize string.

TRIO_PUBLIC_STRING trio_long_double_t 	trio_to_long_double (const char *source, char **endp)

 	Convert string to floating-point number.

TRIO_PUBLIC_STRING double 	trio_to_double (const char *source, char **endp)

 	Convert string to floating-point number.

TRIO_PUBLIC_STRING float 	trio_to_float (const char *source, char **endp)

 	Convert string to floating-point number.

TRIO_PUBLIC_STRING long 	trio_to_long (const char *string, char **endp, int base)

 	Convert string to signed integer.

TRIO_PUBLIC_STRING int 	trio_to_lower (int source)

 	Convert one alphabetic letter to lower-case.

TRIO_PUBLIC_STRING unsigned

long 	trio_to_unsigned_long (const char *string, char **endp, int base)

 	Convert string to unsigned integer.

TRIO_PUBLIC_STRING int 	trio_to_upper (int source)

 	Convert one alphabetic letter to upper-case.

TRIO_PUBLIC_STRING int 	trio_upper (char *target)

 	Convert the alphabetic letters in the string to upper-case.

TRIO_PUBLIC_STRING size_t 	trio_length_max (const char *string, size_t max)

 	Count at most max characters in a string.

Detailed Description

Replacements for the standard C string functions.

SYNOPSIS

cc ... -ltrio -lm

#include <triostr.h>

DESCRIPTION

This package renames, fixes, and extends the standard C string handling functions.

Naming

Renaming is done to provide more clear names, to provide a consistant naming and argument policy, and to hide portability issues.

 All functions starts with "trio_".
 Target is always the first argument, if present, except where the target is optional, such as Static String Functions..
 Functions requiring a size for target includes "_max" in its name, and the size is always the second argument.
 Functions performing case-sensitive operations includes "_case" in its name.

Fixing

Fixing is done to avoid subtle error conditions. For example, strncpy does not terminate the result with a zero if the source string is bigger than the maximal length, so technically the result is not a C string anymore. Static String Functions. makes sure that the result is zero terminated.

Extending

Extending is done to provide a richer set of fundamental functions. This includes functionality such as wildcard matching ( trio_match ) and calculation of hash values ( trio_hash ).

Function Documentation

           TRIO_PUBLIC_STRING int trio_append
          (
          char *
            target,

          const char *
            source

          )

Append source at the end of target.

Parameters:

target
Target string.

source
Source string.

Returns:

Boolean value indicating success or failure.

Precondition:

target must point to a memory chunk with sufficient room to contain the target string and source string.

No boundary checking is performed, so insufficient memory will result in a buffer overrun.

Postcondition:

target will be zero terminated.

           TRIO_PUBLIC_STRING int trio_append_max
          (
          char *
            target,

          size_t
            max,

          const char *
            source

          )

Append at most max characters from source to target.

Parameters:

target
Target string.

max
Maximum number of characters to append.

source
Source string.

Returns:

Boolean value indicating success or failure.

Precondition:

target must point to a memory chuck with sufficient room to contain the target string and the source string (at most max characters).

No boundary checking is performed, so insufficient memory will result in a buffer overrun.

Postcondition:

target will be zero terminated.

           TRIO_PUBLIC_STRING int trio_contains
          (
          const char *
            string,

          const char *
            substring

          )

Determine if a string contains a substring.

Parameters:

string
String to be searched.

substring
String to be found.

Returns:

Boolean value indicating success or failure.

           TRIO_PUBLIC_STRING int trio_copy
          (
          char *
            target,

          const char *
            source

          )

Copy source to target.

Parameters:

target
Target string.

source
Source string.

Returns:

Boolean value indicating success or failure.

Precondition:

target must point to a memory chunk with sufficient room to contain the source string.

No boundary checking is performed, so insufficient memory will result in a buffer overrun.

Postcondition:

target will be zero terminated.

           TRIO_PUBLIC_STRING int trio_copy_max
          (
          char *
            target,

          size_t
            max,

          const char *
            source

          )

Copy at most max characters from source to target.

Parameters:

target
Target string.

max
Maximum number of characters to append.

source
Source string.

Returns:

Boolean value indicating success or failure.

Precondition:

target must point to a memory chunk with sufficient room to contain the source string (at most max characters).

No boundary checking is performed, so insufficient memory will result in a buffer overrun.

Postcondition:

target will be zero terminated.

           TRIO_PUBLIC_STRING char* trio_create
          (
          size_t
            size
          )

Create new string.

Parameters:

size
Size of new string.

Returns:

Pointer to string, or NULL if allocation failed.

           TRIO_PUBLIC_STRING void trio_destroy
          (
          char *
            string
          )

Destroy string.

Parameters:

string
String to be freed.

           TRIO_PUBLIC_STRING char* trio_duplicate
          (
          const char *
            source
          )

Duplicate source.

Parameters:

source
Source string.

Returns:

A copy of the source string.

Postcondition:

target will be zero terminated.

           TRIO_PUBLIC_STRING char* trio_duplicate_max
          (
          const char *
            source,

          size_t
            max

          )

Duplicate at most max characters of source.

Parameters:

source
Source string.

max
Maximum number of characters to duplicate.

Returns:

A copy of the source string.

Postcondition:

target will be zero terminated.

           TRIO_PUBLIC_STRING int trio_equal
          (
          const char *
            first,

          const char *
            second

          )

Compare if two strings are equal.

Parameters:

first
First string.

second
Second string.

Returns:

Boolean indicating whether the two strings are equal or not.
Case-insensitive comparison.

           TRIO_PUBLIC_STRING int trio_equal_case
          (
          const char *
            first,

          const char *
            second

          )

Compare if two strings are equal.

Parameters:

first
First string.

second
Second string.

Returns:

Boolean indicating whether the two strings are equal or not.
Case-sensitive comparison.

           TRIO_PUBLIC_STRING int trio_equal_case_max
          (
          const char *
            first,

          size_t
            max,

          const char *
            second

          )

Compare if two strings up until the first max characters are equal.

Parameters:

first
First string.

max
Maximum number of characters to compare.

second
Second string.

Returns:

Boolean indicating whether the two strings are equal or not.
Case-sensitive comparison.

           TRIO_PUBLIC_STRING int trio_equal_locale
          (
          const char *
            first,

          const char *
            second

          )

Compare if two strings are equal.

Parameters:

first
First string.

second
Second string.

Returns:

Boolean indicating whether the two strings are equal or not.
Collating characters are considered equal.

           TRIO_PUBLIC_STRING int trio_equal_max
          (
          const char *
            first,

          size_t
            max,

          const char *
            second

          )

Compare if two strings up until the first max characters are equal.

Parameters:

first
First string.

max
Maximum number of characters to compare.

second
Second string.

Returns:

Boolean indicating whether the two strings are equal or not.
Case-insensitive comparison.

           TRIO_PUBLIC_STRING const char* trio_error
          (
          int
            error_number
          )

Provide a textual description of an error code (errno).

Parameters:

error_number
Error number.

Returns:

Textual description of error_number.

           TRIO_PUBLIC_STRING size_t trio_format_date_max
          (
          char *
            target,

          size_t
            max,

          const char *
            format,

          const struct tm *
            datetime

          )

Format the date/time according to format.

Parameters:

target
Target string.

max
Maximum number of characters to format.

format
Formatting string.

datetime
Date/time structure.

Returns:

Number of formatted characters.
The formatting string accepts the same specifiers as the standard C function strftime.

           TRIO_PUBLIC_STRING unsigned long trio_hash
          (
          const char *
            string,

          int
            type

          )

Calculate a hash value for a string.

Parameters:

string
String to be calculated on.

type
Hash function.

Returns:

Calculated hash value.
type can be one of the following

 TRIO_HASH_PLAIN Plain hash function.

           TRIO_PUBLIC_STRING char* trio_index
          (
          const char *
            string,

          int
            character

          )

Find first occurrence of a character in a string.

Parameters:

string
String to be searched.

character
Character to be found.

Returns:

A pointer to the found character, or NULL if character was not found.

           TRIO_PUBLIC_STRING char* trio_index_last
          (
          const char *
            string,

          int
            character

          )

Find last occurrence of a character in a string.

Parameters:

string
String to be searched.

character
Character to be found.

Returns:

A pointer to the found character, or NULL if character was not found.

           TRIO_PUBLIC_STRING size_t trio_length
          (
          const char *
            string
          )

Count the number of characters in a string.

Parameters:

string
String to measure.

Returns:

Number of characters in string.

           TRIO_PUBLIC_STRING size_t trio_length_max
          (
          const char *
            string,

          size_t
            max

          )

Count at most max characters in a string.

Parameters:

string
String to measure.

max
Maximum number of characters to count.

Returns:

The maximum value of max and number of characters in string.

           TRIO_PUBLIC_STRING int trio_lower
          (
          char *
            target
          )

Convert the alphabetic letters in the string to lower-case.

Parameters:

target
String to be converted.

Returns:

Number of processed characters (converted or not).

           TRIO_PUBLIC_STRING int trio_match
          (
          const char *
            string,

          const char *
            pattern

          )

Compare two strings using wildcards.

Parameters:

string
String to be searched.

pattern
Pattern, including wildcards, to search for.

Returns:

Boolean value indicating success or failure.
Case-insensitive comparison.

The following wildcards can be used

 * Match any number of characters.
 ? Match a single character.

           TRIO_PUBLIC_STRING int trio_match_case
          (
          const char *
            string,

          const char *
            pattern

          )

Compare two strings using wildcards.

Parameters:

string
String to be searched.

pattern
Pattern, including wildcards, to search for.

Returns:

Boolean value indicating success or failure.
Case-sensitive comparison.

The following wildcards can be used

 * Match any number of characters.
 ? Match a single character.

           TRIO_PUBLIC_STRING size_t trio_span_function
          (
          char *
            target,

          const char *
            source,

          int(*
            Function)(int)

          )

Execute a function on each character in string.

Parameters:

target
Target string.

source
Source string.

Function
Function to be executed.

Returns:

Number of processed characters.

           TRIO_PUBLIC_STRING char* trio_substring
          (
          const char *
            string,

          const char *
            substring

          )

Search for a substring in a string.

Parameters:

string
String to be searched.

substring
String to be found.

Returns:

Pointer to first occurrence of substring in string, or NULL if no match was found.

           TRIO_PUBLIC_STRING char* trio_substring_max
          (
          const char *
            string,

          size_t
            max,

          const char *
            substring

          )

Search for a substring in the first max characters of a string.

Parameters:

string
String to be searched.

max
Maximum characters to be searched.

substring
String to be found.

Returns:

Pointer to first occurrence of substring in string, or NULL if no match was found.

           TRIO_PUBLIC_STRING double trio_to_double
          (
          const char *
            source,

          char **
            endp

          )

Convert string to floating-point number.

Parameters:

source
String to be converted.

endp
Pointer to end of the converted string.

Returns:

A floating-point number.
See Static String Functions..

           TRIO_PUBLIC_STRING float trio_to_float
          (
          const char *
            source,

          char **
            endp

          )

Convert string to floating-point number.

Parameters:

source
String to be converted.

endp
Pointer to end of the converted string.

Returns:

A floating-point number.
See Static String Functions..

           TRIO_PUBLIC_STRING long trio_to_long
          (
          const char *
            string,

          char **
            endp,

          int
            base

          )

Convert string to signed integer.

Parameters:

string
String to be converted.

endp
Pointer to end of converted string.

base
Radix number of number.

           TRIO_PUBLIC_STRING trio_long_double_t trio_to_long_double
          (
          const char *
            source,

          char **
            endp

          )

Convert string to floating-point number.

Parameters:

source
String to be converted.

endp
Pointer to end of the converted string.

Returns:

A floating-point number.
The following Extended Backus-Naur form is used

   double        ::= [ <sign> ]
                     ( <number> |
                       <number> <decimal_point> <number> |
                       <decimal_point> <number> )
                     [ <exponential> [ <sign> ] <number> ]
   number        ::= 1*( <digit> )
   digit         ::= ( '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' )
   exponential   ::= ( 'e' | 'E' )
   sign          ::= ( '-' | '+' )
   decimal_point ::= '.'

           TRIO_PUBLIC_STRING int trio_to_lower
          (
          int
            source
          )

Convert one alphabetic letter to lower-case.

Parameters:

source
The letter to be converted.

Returns:

The converted letter.

           TRIO_PUBLIC_STRING unsigned long trio_to_unsigned_long
          (
          const char *
            string,

          char **
            endp,

          int
            base

          )

Convert string to unsigned integer.

Parameters:

string
String to be converted.

endp
Pointer to end of converted string.

base
Radix number of number.

           TRIO_PUBLIC_STRING int trio_to_upper
          (
          int
            source
          )

Convert one alphabetic letter to upper-case.

Parameters:

source
The letter to be converted.

Returns:

The converted letter.

           TRIO_PUBLIC_STRING char* trio_tokenize
          (
          char *
            string,

          const char *
            delimiters

          )

Tokenize string.

Parameters:

string
String to be tokenized.

delimiters
String containing list of delimiting characters.

Returns:

Start of new token.

Warning:

string will be destroyed.

           TRIO_PUBLIC_STRING int trio_upper
          (
          char *
            target
          )

Convert the alphabetic letters in the string to upper-case.

Parameters:

target
The string to be converted.

Returns:

The number of processed characters (converted or not).

Copyright (C) 2001 - 2006 Bjørn Reese and Daniel Stenberg.


text:
package org.apache.ode.axis2.service;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import javax.transaction.TransactionManager;
import javax.wsdl.Definition;
import javax.wsdl.Operation;
import javax.wsdl.PortType;
import javax.wsdl.WSDLException;
import javax.wsdl.factory.WSDLFactory;
import javax.wsdl.xml.WSDLReader;
import javax.xml.namespace.QName;

import org.apache.axiom.om.OMElement;
import org.apache.axiom.soap.SOAPEnvelope;
import org.apache.axiom.soap.SOAPFactory;
import org.apache.axiom.soap.SOAPFault;
import org.apache.axiom.soap.SOAPFaultCode;
import org.apache.axiom.soap.SOAPFaultDetail;
import org.apache.axiom.soap.SOAPFaultReason;
import org.apache.axis2.AxisFault;
import org.apache.axis2.context.MessageContext;
import org.apache.axis2.description.AxisService;
import org.apache.axis2.engine.AxisConfiguration;
import org.apache.axis2.engine.AxisEngine;
import org.apache.axis2.receivers.AbstractMessageReceiver;
import org.apache.axis2.util.MessageContextBuilder;
import org.apache.axis2.util.Utils;
import org.apache.axis2.util.XMLUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ode.axis2.OdeFault;
import org.apache.ode.axis2.hooks.ODEAxisService;
import org.apache.ode.bpel.engine.BpelEngineImpl;
import org.apache.ode.bpel.engine.BpelServerImpl;
import org.apache.ode.bpel.engine.FragmentManagementImpl;
import org.apache.ode.bpel.engine.MyRoleMessageExchangeImpl;
import org.apache.ode.bpel.engine.ProcessAndInstanceManagementImpl;
import org.apache.ode.bpel.extensions.handler.IncomingMessageHandler;
import org.apache.ode.bpel.fcapi.FragmentManagement;
import org.apache.ode.bpel.iapi.BpelServer;
import org.apache.ode.bpel.iapi.Message;
import org.apache.ode.bpel.iapi.MessageExchange.Status;
import org.apache.ode.bpel.iapi.MyRoleMessageExchange;
import org.apache.ode.bpel.iapi.ProcessStore;
import org.apache.ode.bpel.iapi.Scheduler.JobType;
import org.apache.ode.bpel.pmapi.InstanceManagement;
import org.apache.ode.bpel.pmapi.ProcessManagement;
import org.apache.ode.il.DynamicService;
import org.apache.ode.utils.GUID;
import org.apache.ode.utils.Namespaces;
import org.apache.ode.utils.fc.FCConstants;
import org.apache.xerces.dom.DocumentImpl;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

/**
 * Axis2 wrapper for process and instance management interfaces.
 */
public class ManagementService {

	private TransactionManager txManager;
	private static final Log __log = LogFactory.getLog(ManagementService.class);

	public static final QName PM_SERVICE_NAME = new QName(
			"http://www.apache.org/ode/pmapi", "ProcessManagementService");
	public static final String PM_PORT_NAME = "ProcessManagementPort";
	public static final String PM_AXIS2_NAME = "ProcessManagement";

	public static final QName IM_SERVICE_NAME = new QName(
			"http://www.apache.org/ode/pmapi", "InstanceManagementService");
	public static final String IM_PORT_NAME = "InstanceManagementPort";
	public static final String IM_AXIS2_NAME = "InstanceManagement";

	// AH:

	public static final QName FM_SERVICE_NAME = new QName(
			"http://www.apache.org/ode/fmapi/", "FragmentManagement");
	public static final String FM_PORT_NAME = "FragmentManagementHttpSoap11Endpoint";
	public static final String FM_AXIS2_NAME = "FragmentManagement";

	public static final String FC_AXIS2_NAME = "FragmentComposition";

	private FragmentManagement _fragmentMgmt;
	// AH: end

	private ProcessManagement _processMgmt;
	private InstanceManagement _instanceMgmt;

	// AH:
	private Definition fcServiceDefinition;

	public ManagementService(TransactionManager txManager) {
		this.txManager = txManager;
	}

	// AH: end

	public void enableService(AxisConfiguration axisConfig, BpelServer server,
			ProcessStore _store, String rootpath) {
		ProcessAndInstanceManagementImpl pm = new ProcessAndInstanceManagementImpl(
				server, _store);
		_processMgmt = pm;
		_instanceMgmt = pm;

		// AH:
		_fragmentMgmt = new FragmentManagementImpl(server, txManager);
		// AH: End

		Definition def;
		try {
			WSDLReader wsdlReader = WSDLFactory.newInstance().newWSDLReader();
			wsdlReader.setFeature("javax.wsdl.verbose", false);

			File wsdlFile = new File(rootpath + "/pmapi.wsdl");
			def = wsdlReader.readWSDL(wsdlFile.toURI().toString());
			AxisService processService = ODEAxisService.createService(
					axisConfig, PM_SERVICE_NAME, PM_PORT_NAME, PM_AXIS2_NAME,
					def, new DynamicMessageReceiver<ProcessManagement>(
							_processMgmt));

			/*
			 * XXX: Reparsing the WSDL is a workaround for WSCOMMONS-537 (see
			 * also ODE-853). When WSCOMMONS-537 is fixed we can safely remove
			 * the following line.
			 */
			def = wsdlReader.readWSDL(wsdlFile.toURI().toString());
			/* end XXX */

			AxisService instanceService = ODEAxisService.createService(
					axisConfig, IM_SERVICE_NAME, IM_PORT_NAME, IM_AXIS2_NAME,
					def, new DynamicMessageReceiver<InstanceManagement>(
							_instanceMgmt));

			axisConfig.addService(processService);
			axisConfig.addService(instanceService);

			// AH:
			File fcmwsdlFile = new File(rootpath + "/fcmapi.wsdl");
			Definition fcdef = wsdlReader.readWSDL(fcmwsdlFile.toURI()
					.toString());

			AxisService fmService = ODEAxisService.createService(axisConfig,
					FM_SERVICE_NAME, FM_PORT_NAME, FM_AXIS2_NAME, fcdef,
					new DynamicMessageReceiver<FragmentManagement>(
							_fragmentMgmt));

			File fcWsdlFile = new File(rootpath + "/fcapi.wsdl");
			fcServiceDefinition = wsdlReader.readWSDL(fcWsdlFile.toURI()
					.toString());

			/*
			 * AxisService fragCompService = ODEAxisService.createService(
			 * axisConfig, FC_SERVICE_NAME, FC_PORT_NAME, FC_AXIS2_NAME, fcDef,
			 * new DynamicMessageReceiver<FragmentComposition>( _fragmentComp));
			 */
			AxisService fragCompService = ODEAxisService.createService(
					axisConfig, FCConstants.FC_SERVICE_NAME,
					FCConstants.FC_PORT_NAME, FC_AXIS2_NAME,
					fcServiceDefinition,
					new FragmentCompositionAPIMessageReceiver(server,
							fcServiceDefinition));

			axisConfig.addService(fragCompService);
			axisConfig.addService(fmService);
			// AH: end

			// @stmz
			IncomingMessageHandler incMess = IncomingMessageHandler
					.getInstance();
		} catch (WSDLException e) {
			__log.error("Couldn't start-up management services!", e);
		} catch (IOException e) {
			__log.error("Couldn't start-up management services!", e);
		}
	}

	public ProcessManagement getProcessMgmt() {
		return _processMgmt;
	}

	public InstanceManagement getInstanceMgmt() {
		return _instanceMgmt;
	}

	// AH:
	public Definition getFcServiceDefinition() {
		return fcServiceDefinition;
	}

	class FragmentCompositionAPIMessageReceiver extends AbstractMessageReceiver {
		private BpelServerImpl server;
		private Definition def;
		// private SoapMessageConverter converter;
		private final Long timeout = 60000L;

		public FragmentCompositionAPIMessageReceiver(BpelServer server,
				Definition def) {
			this.server = (BpelServerImpl) server;
			this.def = def;
			// converter = new SoapMessageConverter(def, FC_SERVICE_NAME,
			// FC_PORT_NAME);
		}

		@Override
		protected void invokeBusinessLogic(MessageContext messageContext)
				throws AxisFault {

			// OMElement response;
			Future responseFuture = null;
			String operation = messageContext.getAxisOperation().getName()
					.getLocalPart();
			OMElement payload = messageContext.getEnvelope().getBody()
					.getFirstElement();
			boolean success = true;
			// ODEService::onAxisMessageExchange(...)
			MyRoleMessageExchange odeMex = null;
			try {

				// AH: route FragmentComposition message to the right process
				QName instanceField = FCConstants.FC_INSTANCE_ID_FIELD;
				Long instanceId = null;
				OMElement element = null;
				if (payload != null) {
					element = (OMElement) payload.getChildrenWithName(
							instanceField).next();
				}

				if (element != null) {
					try {
						instanceId = Long.parseLong(element.getText());
					} catch (NumberFormatException e) {
						__log.error("Routed: svcQname "
								+ FCConstants.FC_SERVICE_NAME
								+ "InstanceId couldn't be parsed!");
					}
				}

				// AH: end

				txManager.begin();

				String messageId = new GUID().toString();
				odeMex = ((BpelEngineImpl) (server.getEngine()))
						.createFragmentMessageExchange("" + messageId,
								FCConstants.FC_SERVICE_NAME, operation,
								instanceId);

				// hier ist odeMex relativ leer operation ect muss gesetzt
				// werden
				// if (odeMex.getOperation() != null) {
				// Preparing message to send to ODE
				QName portName = FCConstants.FC_PORT_TYPE_NAME;
				PortType port = def.getPortType(portName);
				Operation wsdlOperation = port.getOperation(operation, null,
						null);
				((MyRoleMessageExchangeImpl) odeMex).setPortOperation(port,
						wsdlOperation);

				Message odeRequest = null;
				if (payload != null) {
					odeRequest = odeMex.createMessage(payload.getQName());
					odeRequest.setMessage(XMLUtils.toDOM(payload));
				}
				/*
				 * _converter.parseSoapRequest(odeRequest, messageContext
				 * .getEnvelope(), odeMex.getOperation());
				 * readHeader(messageContext, odeMex);
				 */
				responseFuture = ((MyRoleMessageExchangeImpl) odeMex).invoke(
						odeRequest, JobType.INVOKE_FC, instanceId);
				// }
				__log.debug("Commiting ODE MEX " + odeMex);
				try {
					if (__log.isDebugEnabled())
						__log.debug("Commiting transaction.");
					txManager.commit();
				} catch (Exception e) {
					__log.error("Commit failed", e);
					success = false;
				}
			} catch (Exception e) {
				if (e.getMessage() != null
						&& e.getMessage().contains("NoSuchInstance")) {
					MessageContext outMsgContext = MessageContextBuilder
							.createOutMessageContext(messageContext);
					if (outMsgContext != null) {
						SOAPFactory soapFactory = getSOAPFactory(messageContext);
						SOAPEnvelope envelope = soapFactory
								.getDefaultEnvelope();
						outMsgContext.setEnvelope(envelope);
						QName type = new QName(FCConstants.FC_TARGET_NAMESPACE,
								"InstanceNotFoundException");

						Document xmldoc = new DocumentImpl();
						Element response = xmldoc.createElement("message");
						response.setTextContent(e.getMessage());

						envelope.getBody().addFault(
								buildFault(type, response,
										getSOAPFactory(messageContext)));
						AxisEngine.send(outMsgContext);
					}
				} else {
					__log.error("Exception occured while invoking ODE", e);
					String message = e.getMessage();
					if (message == null) {
						message = "An exception occured while invoking ODE.";
					}
					throw new OdeFault(message, e);
				}

				success = false;

			} finally {
				if (!success) {
					if (odeMex != null)
						odeMex.release(success);
					try {
						txManager.rollback();
					} catch (Exception e) {
						throw new OdeFault("Rollback failed", e);
					}
				}
			}

			// waiting for response
			if (odeMex != null && odeMex.getOperation().getOutput() != null) {
				// Waits for the response to arrive
				try {
					responseFuture.get(timeout, TimeUnit.MILLISECONDS);
				} catch (Exception e) {
					String errorMsg = "Timeout or execution error when waiting for response to MEX "
							+ odeMex + " " + e.toString();
					__log.error(errorMsg, e);
					throw new OdeFault(errorMsg);
				}
				MessageContext outMsgContext = MessageContextBuilder
						.createOutMessageContext(messageContext);
				if (outMsgContext != null) {
					SOAPFactory soapFactory = getSOAPFactory(messageContext);
					SOAPEnvelope envelope = soapFactory.getDefaultEnvelope();
					outMsgContext.setEnvelope(envelope);

					// Hopefully we have a response
					__log.debug("Handling response for MEX " + odeMex);
					boolean commit = false;
					try {
						if (__log.isDebugEnabled())
							__log.debug("Starting transaction.");
						txManager.begin();
					} catch (Exception ex) {
						throw new OdeFault("Error starting transaction!", ex);
					}
					try {
						// Refreshing the message exchange
						odeMex = (MyRoleMessageExchange) server.getEngine()
								.getMessageExchange(
										odeMex.getMessageExchangeId());

						if (odeMex.getStatus().equals(Status.RESPONSE)) {
							envelope.getBody().addChild(
									XMLUtils.toOM(odeMex.getResponse()
											.getMessage()));
						} else if (odeMex.getStatus().equals(Status.FAULT)) {
							Message fault = odeMex.getFaultResponse();
							envelope.getBody().addFault(
									buildFault(fault.getType(),
											fault.getMessage(),
											getSOAPFactory(messageContext)));
						}
						/*
						 * converter.createSoapResponse(outMsgContext,
						 * odeMex.getResponse(), odeMex .getOperation());
						 */
						AxisEngine.send(outMsgContext);
						commit = true;
					} catch (AxisFault af) {
						__log.warn("MEX produced a fault " + odeMex, af);
						commit = true;
						throw af;
					} catch (Exception e) {
						__log.error("Error processing response for MEX "
								+ odeMex, e);
						throw new OdeFault(
								"An exception occured when invoking ODE.", e);
					} finally {
						odeMex.release(commit);
						if (commit) {
							try {
								if (__log.isDebugEnabled())
									__log.debug("Comitting transaction.");
								txManager.commit();
							} catch (Exception e) {
								throw new OdeFault("Commit failed!", e);
							}
						} else {
							try {
								txManager.rollback();
							} catch (Exception ex) {
								throw new OdeFault("Rollback failed!", ex);
							}
						}
					}
				}
				if (!success) {
					throw new OdeFault(
							"Message was either unroutable or timed out!");
				}
			} else {
				// One ways cleanup
				if (odeMex != null)
					odeMex.release(true);
			}

			/*
			 * response = service.invoke(messageContext.getAxisOperation()
			 * .getName().getLocalPart(), );
			 */
			/*
			 * } catch (Exception e) { // Building a nicely formatted fault
			 * SOAPFactory soapFactory = getSOAPFactory(messageContext);
			 * envelope.getBody().addFault(toSoapFault(e, soapFactory)); }
			 */
			// AxisEngine.send(outMsgContext);
		}

		private SOAPFault buildFault(QName type, Element faultMessage,
				SOAPFactory soapFactory) {
			SOAPFault fault = soapFactory.createSOAPFault();
			SOAPFaultCode code = soapFactory.createSOAPFaultCode(fault);
			code.setText(new QName(Namespaces.SOAP_ENV_NS, "Server"));

			try {
				String faultString = faultMessage.getTextContent();
				SOAPFaultDetail soapDetail = soapFactory
						.createSOAPFaultDetail(fault);
				OMElement detail = soapFactory.createOMElement(type);
				detail.setText(faultString);
				soapDetail.addDetailEntry(detail);

				SOAPFaultReason reason = soapFactory
						.createSOAPFaultReason(fault);
				reason.setText(faultString);

			} catch (Exception e) {
				__log.error(e);
			}
			return fault;

		}
	}

	// AH: end

	class DynamicMessageReceiver<T> extends AbstractMessageReceiver {
		T _service;

		public DynamicMessageReceiver(T service) {
			_service = service;
		}

		public void invokeBusinessLogic(MessageContext messageContext)
				throws AxisFault {
			DynamicService<T> service = new DynamicService<T>(_service);
			MessageContext outMsgContext = Utils
					.createOutMessageContext(messageContext);
			outMsgContext.getOperationContext()
					.addMessageContext(outMsgContext);
			SOAPFactory soapFactory = getSOAPFactory(messageContext);
			SOAPEnvelope envelope = soapFactory.getDefaultEnvelope();
			outMsgContext.setEnvelope(envelope);

			OMElement response;
			try {
				response = service.invoke(messageContext.getAxisOperation()
						.getName().getLocalPart(), messageContext.getEnvelope()
						.getBody().getFirstElement());
				if (response != null) {
					envelope.getBody().addChild(response);
				}
			} catch (Exception e) {
				// Building a nicely formatted fault
				envelope.getBody().addFault(toSoapFault(e, soapFactory));
			}
			AxisEngine.send(outMsgContext);
		}

		private SOAPFault toSoapFault(Exception e, SOAPFactory soapFactory) {
			SOAPFault fault = soapFactory.createSOAPFault();
			SOAPFaultCode code = soapFactory.createSOAPFaultCode(fault);
			code.setText(new QName(Namespaces.SOAP_ENV_NS, "Server"));
			SOAPFaultReason reason = soapFactory.createSOAPFaultReason(fault);
			reason.setText(e.toString());

			OMElement detail = soapFactory.createOMElement(new QName(
					Namespaces.ODE_PMAPI_NS, e.getClass().getSimpleName()));
			StringWriter stack = new StringWriter();
			e.printStackTrace(new PrintWriter(stack));
			detail.setText(stack.toString());
			SOAPFaultDetail soapDetail = soapFactory
					.createSOAPFaultDetail(fault);
			soapDetail.addDetailEntry(detail);
			return fault;
		}
	}

}


text:
<?php namespace bzdbbb\Event\Updates;

use Schema;
use October\Rain\Database\Updates\Migration;

class CreateCategoriesTable extends Migration
{

    public function up()
    {
        Schema::create('bzdbbb_event_categories', function($table)
        {
            $table->engine = 'InnoDB';
            $table->increments('id');
            $table->string('name');
            $table->string('slug')->index();
            $table->string('code')->nullable();
            $table->text('description')->nullable();
            $table->timestamps();
        });

        Schema::create('bzdbbb_event_events_categories', function($table)
        {
            $table->engine = 'InnoDB';
            $table->integer('event_id')->unsigned();
            $table->integer('category_id')->unsigned();
            $table->primary(['event_id', 'category_id']);
        });
    }

    public function down()
    {
        Schema::drop('bzdbbb_event_categories');
        Schema::drop('bzdbbb_event_events_categories');
    }

}


text:
package javax.swing;

import java.io.Serializable;
import java.util.EventObject;

import javax.swing.event.CellEditorListener;
import javax.swing.event.ChangeEvent;
import javax.swing.event.EventListenerList;

public abstract class AbstractCellEditor implements CellEditor, Serializable {
    protected EventListenerList listenerList = new EventListenerList();
    protected transient ChangeEvent changeEvent;

    public boolean isCellEditable(final EventObject e) {
        return true;
    }

    public boolean shouldSelectCell(final EventObject event) {
        return true;
    }

    public boolean stopCellEditing() {
        fireEditingStopped();
        return true;
    }

    public void cancelCellEditing() {
        fireEditingCanceled();
    }

    public void addCellEditorListener(final CellEditorListener l) {
        listenerList.add(CellEditorListener.class, l);
    }

    public void removeCellEditorListener(final CellEditorListener l) {
        listenerList.remove(CellEditorListener.class, l);
    }

    public CellEditorListener[] getCellEditorListeners() {
        return listenerList.getListeners(CellEditorListener.class);
    }

    protected void fireEditingStopped() {
        CellEditorListener[] listeners = getCellEditorListeners();
        for (int i = 0; i < listeners.length; i++) {
            listeners[i].editingStopped(getChangeEvent());
        }
    }

    protected void fireEditingCanceled() {
        CellEditorListener[] listeners = getCellEditorListeners();
        for (int i = 0; i < listeners.length; i++) {
            listeners[i].editingCanceled(getChangeEvent());
        }
    }

    private ChangeEvent getChangeEvent() {
        if (changeEvent == null) {
            changeEvent = new ChangeEvent(this);
        }

        return changeEvent;
    }
}