text:
//===-- include/flang/Parser/message.h --------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#ifndef FORTRAN_PARSER_MESSAGE_H_
#define FORTRAN_PARSER_MESSAGE_H_

// Defines a representation for sequences of compiler messages.
// Supports nested contextualization.

#include "char-block.h"
#include "char-set.h"
#include "provenance.h"
#include "flang/Common/idioms.h"
#include "flang/Common/reference-counted.h"
#include "flang/Common/restorer.h"
#include <cstddef>
#include <cstring>
#include <forward_list>
#include <optional>
#include <string>
#include <utility>
#include <variant>

namespace Fortran::parser {

// Use "..."_err_en_US and "..."_en_US literals to define the static
// text and fatality of a message.
class MessageFixedText {
public:
  constexpr MessageFixedText(
      const char str[], std::size_t n, bool isFatal = false)
      : text_{str, n}, isFatal_{isFatal} {}
  constexpr MessageFixedText(const MessageFixedText &) = default;
  constexpr MessageFixedText(MessageFixedText &&) = default;
  constexpr MessageFixedText &operator=(const MessageFixedText &) = default;
  constexpr MessageFixedText &operator=(MessageFixedText &&) = default;

  CharBlock text() const { return text_; }
  bool isFatal() const { return isFatal_; }

private:
  CharBlock text_;
  bool isFatal_{false};
};

inline namespace literals {
constexpr MessageFixedText operator""_en_US(const char str[], std::size_t n) {
  return MessageFixedText{str, n, false /* not fatal */};
}

constexpr MessageFixedText operator""_err_en_US(
    const char str[], std::size_t n) {
  return MessageFixedText{str, n, true /* fatal */};
}
} // namespace literals

// The construction of a MessageFormattedText uses a MessageFixedText
// as a vsnprintf() formatting string that is applied to the
// following arguments.  CharBlock and std::string argument
// values are also supported; they are automatically converted into
// char pointers that are suitable for '%s' formatting.
class MessageFormattedText {
public:
  template <typename... A>
  MessageFormattedText(const MessageFixedText &text, A &&... x)
      : isFatal_{text.isFatal()} {
    Format(&text, Convert(std::forward<A>(x))...);
  }
  MessageFormattedText(const MessageFormattedText &) = default;
  MessageFormattedText(MessageFormattedText &&) = default;
  MessageFormattedText &operator=(const MessageFormattedText &) = default;
  MessageFormattedText &operator=(MessageFormattedText &&) = default;
  const std::string &string() const { return string_; }
  bool isFatal() const { return isFatal_; }
  std::string MoveString() { return std::move(string_); }

private:
  void Format(const MessageFixedText *, ...);

  template <typename A> A Convert(const A &x) {
    static_assert(!std::is_class_v<std::decay_t<A>>);
    return x;
  }
  template <typename A> A Convert(A &x) {
    static_assert(!std::is_class_v<std::decay_t<A>>);
    return x;
  }
  template <typename A> common::IfNoLvalue<A, A> Convert(A &&x) {
    static_assert(!std::is_class_v<std::decay_t<A>>);
    return std::move(x);
  }
  const char *Convert(const char *s) { return s; }
  const char *Convert(char *s) { return s; }
  const char *Convert(const std::string &);
  const char *Convert(std::string &);
  const char *Convert(std::string &&);
  const char *Convert(CharBlock);
  std::intmax_t Convert(std::int64_t x) { return x; }
  std::uintmax_t Convert(std::uint64_t x) { return x; }

  bool isFatal_{false};
  std::string string_;
  std::forward_list<std::string> conversions_; // preserves created strings
};

// Represents a formatted rendition of "expected '%s'"_err_en_US
// on a constant text or a set of characters.
class MessageExpectedText {
public:
  MessageExpectedText(const char *s, std::size_t n) {
    if (n == std::string::npos) {
      n = std::strlen(s);
    }
    if (n == 1) {
      // Treat a one-character string as a singleton set for better merging.
      u_ = SetOfChars{*s};
    } else {
      u_ = CharBlock{s, n};
    }
  }
  constexpr explicit MessageExpectedText(CharBlock cb) : u_{cb} {}
  constexpr explicit MessageExpectedText(char ch) : u_{SetOfChars{ch}} {}
  constexpr explicit MessageExpectedText(SetOfChars set) : u_{set} {}
  MessageExpectedText(const MessageExpectedText &) = default;
  MessageExpectedText(MessageExpectedText &&) = default;
  MessageExpectedText &operator=(const MessageExpectedText &) = default;
  MessageExpectedText &operator=(MessageExpectedText &&) = default;

  std::string ToString() const;
  bool Merge(const MessageExpectedText &);

private:
  std::variant<CharBlock, SetOfChars> u_;
};

class Message : public common::ReferenceCounted<Message> {
public:
  using Reference = common::CountedReference<Message>;

  Message(const Message &) = default;
  Message(Message &&) = default;
  Message &operator=(const Message &) = default;
  Message &operator=(Message &&) = default;

  Message(ProvenanceRange pr, const MessageFixedText &t)
      : location_{pr}, text_{t} {}
  Message(ProvenanceRange pr, const MessageFormattedText &s)
      : location_{pr}, text_{s} {}
  Message(ProvenanceRange pr, MessageFormattedText &&s)
      : location_{pr}, text_{std::move(s)} {}
  Message(ProvenanceRange pr, const MessageExpectedText &t)
      : location_{pr}, text_{t} {}

  Message(CharBlock csr, const MessageFixedText &t)
      : location_{csr}, text_{t} {}
  Message(CharBlock csr, const MessageFormattedText &s)
      : location_{csr}, text_{s} {}
  Message(CharBlock csr, MessageFormattedText &&s)
      : location_{csr}, text_{std::move(s)} {}
  Message(CharBlock csr, const MessageExpectedText &t)
      : location_{csr}, text_{t} {}

  template <typename RANGE, typename A, typename... As>
  Message(RANGE r, const MessageFixedText &t, A &&x, As &&... xs)
      : location_{r}, text_{MessageFormattedText{
                          t, std::forward<A>(x), std::forward<As>(xs)...}} {}

  bool attachmentIsContext() const { return attachmentIsContext_; }
  Reference attachment() const { return attachment_; }

  void SetContext(Message *c) {
    attachment_ = c;
    attachmentIsContext_ = true;
  }
  Message &Attach(Message *);
  Message &Attach(std::unique_ptr<Message> &&);
  template <typename... A> Message &Attach(A &&... args) {
    return Attach(new Message{std::forward<A>(args)...}); // reference-counted
  }

  bool SortBefore(const Message &that) const;
  bool IsFatal() const;
  std::string ToString() const;
  std::optional<ProvenanceRange> GetProvenanceRange(const CookedSource &) const;
  void Emit(llvm::raw_ostream &, const CookedSource &,
      bool echoSourceLine = true) const;

  // If this Message or any of its attachments locates itself via a CharBlock
  // within a particular CookedSource, replace its location with the
  // corresponding ProvenanceRange.
  void ResolveProvenances(const CookedSource &);

  bool IsMergeable() const {
    return std::holds_alternative<MessageExpectedText>(text_);
  }
  bool Merge(const Message &);

private:
  bool AtSameLocation(const Message &) const;

  std::variant<ProvenanceRange, CharBlock> location_;
  std::variant<MessageFixedText, MessageFormattedText, MessageExpectedText>
      text_;
  bool attachmentIsContext_{false};
  Reference attachment_;
};

class Messages {
public:
  Messages() {}
  Messages(Messages &&that) : messages_{std::move(that.messages_)} {
    if (!messages_.empty()) {
      last_ = that.last_;
      that.ResetLastPointer();
    }
  }
  Messages &operator=(Messages &&that) {
    messages_ = std::move(that.messages_);
    if (messages_.empty()) {
      ResetLastPointer();
    } else {
      last_ = that.last_;
      that.ResetLastPointer();
    }
    return *this;
  }

  std::forward_list<Message> &messages() { return messages_; }
  bool empty() const { return messages_.empty(); }
  void clear();

  template <typename... A> Message &Say(A &&... args) {
    last_ = messages_.emplace_after(last_, std::forward<A>(args)...);
    return *last_;
  }

  void Annex(Messages &&that) {
    if (!that.messages_.empty()) {
      messages_.splice_after(last_, that.messages_);
      last_ = that.last_;
      that.ResetLastPointer();
    }
  }

  void Restore(Messages &&that) {
    that.Annex(std::move(*this));
    *this = std::move(that);
  }

  bool Merge(const Message &);
  void Merge(Messages &&);
  void Copy(const Messages &);
  void ResolveProvenances(const CookedSource &);
  void Emit(llvm::raw_ostream &, const CookedSource &cooked,
      bool echoSourceLines = true) const;
  void AttachTo(Message &);
  bool AnyFatalError() const;

private:
  void ResetLastPointer() { last_ = messages_.before_begin(); }

  std::forward_list<Message> messages_;
  std::forward_list<Message>::iterator last_{messages_.before_begin()};
};

class ContextualMessages {
public:
  ContextualMessages() = default;
  ContextualMessages(CharBlock at, Messages *m) : at_{at}, messages_{m} {}
  explicit ContextualMessages(Messages *m) : messages_{m} {}
  ContextualMessages(const ContextualMessages &that)
      : at_{that.at_}, messages_{that.messages_} {}

  CharBlock at() const { return at_; }
  Messages *messages() const { return messages_; }
  bool empty() const { return !messages_ || messages_->empty(); }

  // Set CharBlock for messages; restore when the returned value is deleted
  common::Restorer<CharBlock> SetLocation(CharBlock at) {
    if (at.empty()) {
      at = at_;
    }
    return common::ScopedSet(at_, std::move(at));
  }

  // Diverts messages to another buffer; restored when the returned
  // value is deleted.
  common::Restorer<Messages *> SetMessages(Messages &buffer) {
    return common::ScopedSet(messages_, &buffer);
  }
  // Discard messages; destination restored when the returned value is deleted.
  common::Restorer<Messages *> DiscardMessages() {
    return common::ScopedSet(messages_, nullptr);
  }

  template <typename... A> Message *Say(CharBlock at, A &&... args) {
    if (messages_ != nullptr) {
      return &messages_->Say(at, std::forward<A>(args)...);
    } else {
      return nullptr;
    }
  }

  template <typename... A> Message *Say(A &&... args) {
    return Say(at_, std::forward<A>(args)...);
  }

private:
  CharBlock at_;
  Messages *messages_{nullptr};
};
} // namespace Fortran::parser
#endif // FORTRAN_PARSER_MESSAGE_H_


text:
//#include <iostream>
#include <fstream>
#include <sstream>
#include <strstream>
#include <iterator>
#include <algorithm>
#include <db_cxx.h>
#include <vector>

#include "ROSManager.h"

ROSManager::ROSManager( string table_, int numColumns )
{
  _table = CatalogInstance::stripOffDirectory( table_ );
  cout << "Creating ROSManager from " << table_ << endl;

  _numColumns = numColumns;
  /*
  _db_ros = new Db( NULL, 0 );
  _db_wos = new Db( NULL, 0 );

  _db_ros->set_bt_compare( ROSAM::compare_int );
  _db_wos->set_bt_compare( ROSAM::compare_int );

  _db_ros->set_error_stream( &cout );
  _db_wos->set_error_stream( &cout );

  _db_ros->set_cachesize( 0, SMALL_CACHE_SIZE/5, 1 ); // 5Mb cache
  _db_ros->set_pagesize( 4096 );

  _db_wos->set_cachesize( 0, SMALL_CACHE_SIZE/5, 1 ); // 5Mb cache
  _db_wos->set_pagesize( 4096 );
  */
  //initCursors();
}

ROSManager::~ROSManager()
{
  // What goes here?
}

ROSAM* ROSManager::getROSAM( int colNum )
{
  cout << " Getting a ROSAM from ROSManager " << _fName << endl;
  //WOSAM* wm = new WOSAM( table, _numindicies, _numColumns, colNum, rwseg );
  cerr << "ROSManager: getROSAM not implemented" << endl;
  throw AccessException( "Not implemented" );

  return NULL;
}

string ROSManager::toString()
{
	return string("This is a ROSManager reporting ") +
	  string( " name? " );
}

int ROSManager::getLastStorageKey()
{
  cerr << "Throw AccessException, NOT IMPLEMENTED " <<endl;
  throw UnimplementedException(" NOT IMPLEMENTED ");
}

/*int ROSManager::getLastPosition( bool ros )
{
  if (!ros) {
    return rwseg->getLastPosition();
  } else {
    //throw UnimplementedException(" NOT IMPLEMENTED ");
    CatalogInstance* pCI = new CatalogInstance();
    ROSAM* pROS = pCI->getROSAM(table, pCI->getPrimaryColumnName(table));
    int lastPosition = pROS->getLastIndexValuePrimary();
    delete pROS;
    delete pCI;
    return lastPosition;
  }
}*/

/*int ROSManager::getLastValue( bool ros )
{
  if (!ros) {
    return rwseg->getLastValue();
  } else {
    //throw UnimplementedException(" NOT IMPLEMENTED ");
    CatalogInstance* pCI = new CatalogInstance();
    ROSAM* pROS = pCI->getROSAM(_fName, pCI->getPrimaryColumnName(_fName));
    int lastValue = pROS->getLastIndexValueSecondary();
    delete pROS;
    delete pCI;
    return lastValue;
  }
}*/

redpajama_set_name: RedPajamaGithub


text: The main repository for the source code and issue tracker of the Starlight Engine.


text:
<!DOCTYPE html>

		<meta charset="utf-8" />
		<base href="../../../" />

		<link type="text/css" rel="stylesheet" href="page.css" />

Custom Blending Equation Constants

			These work with all material types. First set the material's blending mode to THREE.CustomBlending, then set the desired Blending Equation, Source Factor and Destination Factor.

Code Example

		var material = new THREE.MeshBasicMaterial( {color: 0x00ff00} );
		material.blending = THREE.CustomBlending;
		material.blendEquation = THREE.AddEquation; //default
		material.blendSrc = THREE.SrcAlphaFactor; //default
		material.blendDst = THREE.OneMinusSrcAlphaFactor; //default

Examples

[example:webgl_materials_blending_custom materials / blending / custom ]

Blending Equations

		THREE.AddEquation
		THREE.SubtractEquation
		THREE.ReverseSubtractEquation
		THREE.MinEquation
		THREE.MaxEquation

Source Factors

		THREE.ZeroFactor
		THREE.OneFactor
		THREE.SrcColorFactor
		THREE.OneMinusSrcColorFactor
		THREE.SrcAlphaFactor
		THREE.OneMinusSrcAlphaFactor
		THREE.DstAlphaFactor
		THREE.OneMinusDstAlphaFactor
		THREE.DstColorFactor
		THREE.OneMinusDstColorFactor
		THREE.SrcAlphaSaturateFactor

Destination Factors

			All of the Source Factors are valid as Destination Factors, except for THREE.SrcAlphaSaturateFactor

Source

			[link:https://github.com/mrdoob/three.js/blob/master/src/constants.js src/constants.js]


text:
package com.thinkbiganalytics.metadata.jpa.sla;

import com.thinkbiganalytics.common.velocity.model.VelocityTemplate;
import com.thinkbiganalytics.metadata.api.MetadataAccess;
import com.thinkbiganalytics.metadata.api.event.MetadataChange;
import com.thinkbiganalytics.metadata.api.event.MetadataEventListener;
import com.thinkbiganalytics.metadata.api.event.MetadataEventService;
import com.thinkbiganalytics.metadata.api.event.sla.ServiceLevelAgreementEvent;
import com.thinkbiganalytics.metadata.api.feed.Feed;
import com.thinkbiganalytics.metadata.api.feed.OpsManagerFeed;
import com.thinkbiganalytics.metadata.api.feed.OpsManagerFeedProvider;
import com.thinkbiganalytics.metadata.api.sla.ServiceLevelAgreementActionTemplate;
import com.thinkbiganalytics.metadata.api.sla.ServiceLevelAgreementActionTemplateProvider;
import com.thinkbiganalytics.metadata.api.sla.ServiceLevelAgreementDescriptionProvider;
import com.thinkbiganalytics.metadata.sla.api.ServiceLevelAgreement;
import com.thinkbiganalytics.metadata.sla.api.ServiceLevelAgreementDescription;
import com.thinkbiganalytics.metadata.sla.spi.ServiceLevelAgreementProvider;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import javax.annotation.PostConstruct;
import javax.inject.Inject;

@Service
public class JpaServiceLevelAgreementDescriptionProvider implements ServiceLevelAgreementDescriptionProvider {

    private static final Logger log = LoggerFactory.getLogger(JpaServiceLevelAgreementDescriptionProvider.class);
    private JpaServiceLevelAgreementDescriptionRepository serviceLevelAgreementDescriptionRepository;

    @Inject
    private ServiceLevelAgreementProvider slaProvider;

    @Inject
    private OpsManagerFeedProvider feedProvider;

    @Inject
    private ServiceLevelAgreementActionTemplateProvider serviceLevelAgreementActionTemplateProvider;

    @Inject
    MetadataAccess metadataAccess;

    @Inject
    private MetadataEventService metadataEventService;

    @Inject
    private ServiceLevelAgreementDescriptionCache serviceLevelAgreementDescriptionCache;

    private SlaDeletedListener slaDeletedListener = new SlaDeletedListener();

    @Autowired
    public JpaServiceLevelAgreementDescriptionProvider(JpaServiceLevelAgreementDescriptionRepository serviceLevelAgreementDescriptionRepository) {
        this.serviceLevelAgreementDescriptionRepository = serviceLevelAgreementDescriptionRepository;
    }

    @PostConstruct
    private void init() {
        serviceLevelAgreementDescriptionCache.populateCache();
        metadataEventService.addListener(slaDeletedListener);
    }

    @Override
    public ServiceLevelAgreementDescription findOne(ServiceLevelAgreement.ID id) {
        return serviceLevelAgreementDescriptionRepository.findByIdFetchFeeds((ServiceLevelAgreementDescriptionId) resolveId(id.toString()));
    }

    @Override
    public List<ServiceLevelAgreementDescription> findAll() {
        return new ArrayList<>(serviceLevelAgreementDescriptionRepository.findAll());
    }

    /**
     * Updates the Service Level Agreement (SLA) JPA mapping and its relationship to Feeds
     * Called from ModeShape when an SLA is saved/updated
     *
     * @param slaId       the SLA id
     * @param name        the SLA Name
     * @param description the SLA Description
     * @param feeds       a set of Feed Ids related to this SLA
     */
    @Override
    public void updateServiceLevelAgreement(ServiceLevelAgreement.ID slaId, String name, String description, Set<Feed.ID> feeds, Set<VelocityTemplate.ID> velocityTemplates) {
        ServiceLevelAgreementDescriptionId id = null;
        if (!(slaId instanceof ServiceLevelAgreementDescriptionId)) {
            id = new ServiceLevelAgreementDescriptionId(slaId.toString());
        } else {
            id = (ServiceLevelAgreementDescriptionId) slaId;
        }
        JpaServiceLevelAgreementDescription serviceLevelAgreementDescription = serviceLevelAgreementDescriptionRepository.findOne(id);
        if (serviceLevelAgreementDescription == null) {
            serviceLevelAgreementDescription = new JpaServiceLevelAgreementDescription();
            serviceLevelAgreementDescription.setSlaId(id);
        }
        serviceLevelAgreementDescription.setName(name);
        serviceLevelAgreementDescription.setDescription(description);
        List<OpsManagerFeed> jpaFeeds = null;
        if (feeds != null) {
            List<OpsManagerFeed.ID> feedIds = feeds.stream().map(f -> feedProvider.resolveId(f.toString())).collect(Collectors.toList());
            jpaFeeds = (List<OpsManagerFeed>) feedProvider.findByFeedIds(feedIds);
        }
        if (jpaFeeds != null) {
            serviceLevelAgreementDescription.setFeeds(new HashSet<>(jpaFeeds));
        } else {
            serviceLevelAgreementDescription.setFeeds(null);
        }
        serviceLevelAgreementDescriptionRepository.save(serviceLevelAgreementDescription);
        //update the cache
        serviceLevelAgreementDescriptionCache.save(serviceLevelAgreementDescription);
        //save the velocity template relationships
        serviceLevelAgreementActionTemplateProvider.assignTemplateByIds(serviceLevelAgreementDescription, velocityTemplates);
    }

    public ServiceLevelAgreement.ID resolveId(Serializable ser) {
        if (ser instanceof ServiceLevelAgreementDescriptionId) {
            return (ServiceLevelAgreementDescriptionId) ser;
        } else {
            return new ServiceLevelAgreementDescriptionId(ser);
        }
    }

    public List<? extends ServiceLevelAgreementDescription> findForFeed(OpsManagerFeed.ID feedId) {
        return serviceLevelAgreementDescriptionRepository.findForFeed(feedId);
    }

    /**
     * Listen for when SLAs are deleted from ModeShape
     */
    private class SlaDeletedListener implements MetadataEventListener<ServiceLevelAgreementEvent> {

        @Override
        public void notify(ServiceLevelAgreementEvent event) {
            if (event.getData().getChange() == MetadataChange.ChangeType.DELETE) {
                serviceLevelAgreementDescriptionCache.deleteByDtoId(event.getData().getId().toString());
                try {
                    ServiceLevelAgreementDescriptionId serviceLevelAgreementDescriptionId = (ServiceLevelAgreementDescriptionId) resolveId(event.getData().getId().toString());
                    ServiceLevelAgreementDescription serviceLevelAgreementDescription = serviceLevelAgreementDescriptionRepository.findOne(serviceLevelAgreementDescriptionId);

                    List<? extends ServiceLevelAgreementActionTemplate> slaTemplates = serviceLevelAgreementActionTemplateProvider.deleteForSlaId(serviceLevelAgreementDescriptionId);

                    if (serviceLevelAgreementDescription != null) {
                        serviceLevelAgreementDescriptionRepository.delete((JpaServiceLevelAgreementDescription) serviceLevelAgreementDescription);
                    }
                } catch (Exception e) {
                    log.error("Unable to delete the Service Level Description for " + event.getData().getName() + " ( " + event.getData().getId());
                }
            }
        }
    }

}


text:
        <leaftlet-map></leaftlet-map>

Echa un vistazo a tus tareas

            <button class="accordion" ng-click="showCommentary = !showCommentary" ng-class="{active: showCommentary}">
              {{report.title}}
            </button>

Localización: {{report.location}}

Descripción: {{report.description}}

                <button ng-click="done(report.id)" class="btn-success">Hecha</button>
                <button ng-click="trouble(report.id)" class="btn-danger">Problema</button>


text:
<?php

declare(strict_types=1);

namespace Talesweaver\Application\Controller\Chapter;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Talesweaver\Application\Bus\CommandBus;
use Talesweaver\Application\Command\Chapter\Publish\DTO;
use Talesweaver\Application\Form\FormHandlerFactoryInterface;
use Talesweaver\Application\Form\FormHandlerInterface;
use Talesweaver\Application\Form\Type\Chapter\Publish;
use Talesweaver\Application\Http\ApiResponseFactoryInterface;
use Talesweaver\Application\Http\Entity\ChapterResolver;
use Talesweaver\Application\Http\UrlGenerator;

final class PublishController
{
    /**
     * @var ApiResponseFactoryInterface
     */
    private $apiRresponseFactory;

    /**
     * @var ChapterResolver
     */
    private $chapterResolver;

    /**
     * @var FormHandlerFactoryInterface
     */
    private $formHandlerFactory;

    /**
     * @var UrlGenerator
     */
    private $urlGenerator;

    /**
     * @var CommandBus
     */
    private $commandBus;

    public function __construct(
        ApiResponseFactoryInterface $apiResponseFactory,
        ChapterResolver $chapterResolver,
        FormHandlerFactoryInterface $formHandlerFactory,
        UrlGenerator $urlGenerator,
        CommandBus $commandBus
    ) {
        $this->apiRresponseFactory = $apiResponseFactory;
        $this->chapterResolver = $chapterResolver;
        $this->formHandlerFactory = $formHandlerFactory;
        $this->urlGenerator = $urlGenerator;
        $this->commandBus = $commandBus;
    }

    public function __invoke(ServerRequestInterface $request): ResponseInterface
    {
        $formHandler = $this->createFormHandler($request);
        if (true === $formHandler->isSubmissionValid()) {
            $this->handleFormSubmission($formHandler->getData());
            return $this->apiRresponseFactory->success();
        }

        return $this->apiRresponseFactory->form(
            'form\modalContent.html.twig',
            ['form' => $formHandler->createView()],
            $formHandler->displayErrors(),
            'publication.header'
        );
    }

    private function createFormHandler(ServerRequestInterface $request): FormHandlerInterface
    {
        $chapter = $this->chapterResolver->fromRequest($request);
        return $this->formHandlerFactory->createWithRequest(
            $request,
            Publish::class,
            DTO::fromEntity($chapter),
            ['action' => $this->urlGenerator->generate('chapter_publish', ['id' => $chapter->getId()])]
        );
    }

    private function handleFormSubmission(DTO $data): void
    {
        $this->commandBus->dispatch($data->toCommand());
    }
}


text:
import Datasource from 'services/datasource';
import {apiCreator} from 'services/resource-helper';

let dataSrc = new Datasource();
const basepath = '/namespaces/:namespace/data/datasets';

export const MyDatasetApi = {
  list: apiCreator(dataSrc, 'GET', 'REQUEST', basepath),
  get: apiCreator(dataSrc, 'GET', 'REQUEST', `${basepath}/:datasetId`),
  getPrograms: apiCreator(dataSrc, 'GET', 'REQUEST', `${basepath}/:datasetId/programs`),
  delete: apiCreator(dataSrc, 'DELETE', 'REQUEST', `${basepath}/:datasetId`),
  truncate: apiCreator(dataSrc, 'POST', 'REQUEST', `${basepath}/:datasetId/admin/truncate`)
};


text:
import {value} from "dep1";

export const val = value;

module.hot.accept("dep1");


text:
CREATE TABLE IF NOT EXISTS `[prefix]plupload_files` (
	`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
	`user` int(10) unsigned NOT NULL,
	`uploaded` bigint(20) unsigned NOT NULL,
	`source` varchar(255) NOT NULL COMMENT 'Path locally on storage',
	`url` varchar(255) NOT NULL,
	PRIMARY KEY (`id`),
	UNIQUE KEY `url` (`url`),
	KEY `user` (`user`),
	KEY `uploaded` (`uploaded`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `[prefix]plupload_files_tags` (
	`id` bigint(20) unsigned NOT NULL,
	`tag` varchar(255) NOT NULL,
	PRIMARY KEY (`id`,`tag`),
	KEY `tag` (`tag`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


text:
System.register(["angular2/src/facade/lang", "angular2/src/dom/dom_adapter", "angular2/change_detection", "./compile_step", "./compile_element", "./compile_control"], function($__export) {
  "use strict";
  var RegExpWrapper,
      StringWrapper,
      isPresent,
      DOM,
      Parser,
      CompileStep,
      CompileElement,
      CompileControl,
      TextInterpolationParser;
  return {
    setters: [function($__m) {
      RegExpWrapper = $__m.RegExpWrapper;
      StringWrapper = $__m.StringWrapper;
      isPresent = $__m.isPresent;
    }, function($__m) {
      DOM = $__m.DOM;
    }, function($__m) {
      Parser = $__m.Parser;
    }, function($__m) {
      CompileStep = $__m.CompileStep;
    }, function($__m) {
      CompileElement = $__m.CompileElement;
    }, function($__m) {
      CompileControl = $__m.CompileControl;
    }],
    execute: function() {
      TextInterpolationParser = $__export("TextInterpolationParser", (function($__super) {
        var TextInterpolationParser = function TextInterpolationParser(parser) {
          $traceurRuntime.superConstructor(TextInterpolationParser).call(this);
          this._parser = parser;
        };
        return ($traceurRuntime.createClass)(TextInterpolationParser, {
          process: function(parent, current, control) {
            if (!current.compileChildren || current.ignoreBindings) {
              return ;
            }
            var element = current.element;
            var childNodes = DOM.childNodes(DOM.templateAwareRoot(element));
            for (var i = 0; i < childNodes.length; i++) {
              var node = childNodes[i];
              if (DOM.isTextNode(node)) {
                this._parseTextNode(current, node, i);
              }
            }
          },
          _parseTextNode: function(pipelineElement, node, nodeIndex) {
            var ast = this._parser.parseInterpolation(DOM.nodeValue(node), pipelineElement.elementDescription);
            if (isPresent(ast)) {
              DOM.setText(node, ' ');
              pipelineElement.addTextNodeBinding(nodeIndex, ast);
            }
          }
        }, {}, $__super);
      }(CompileStep)));
      Object.defineProperty(TextInterpolationParser, "parameters", {get: function() {
          return [[Parser]];
        }});
      Object.defineProperty(TextInterpolationParser.prototype.process, "parameters", {get: function() {
          return [[CompileElement], [CompileElement], [CompileControl]];
        }});
    }
  };
});

//# sourceMappingURL=src/core/compiler/pipeline/text_interpolation_parser.map

//# sourceMappingURL=../../../../src/core/compiler/pipeline/text_interpolation_parser.js.map


text:
@implementation HMEmoticon

#pragma mark - 计算型属性
- (NSString *)imagePath {

    if (_type == 1) {
        return nil;
    }

    return [NSString stringWithFormat:@"%@/%@", _directory, _png];
}

- (void)setCode:(NSString *)code {
    _emoji = code.hm_emoji;
}

- (BOOL)isEmoji {
    return _emoji != nil;
}

#pragma mark - 构造函数
+ (instancetype)emoticonWithDict:(NSDictionary *)dict {
    id obj = [[self alloc] init];

    [obj setValuesForKeysWithDictionary:dict];

    return obj;
}

- (void)setValue:(id)value forUndefinedKey:(NSString *)key {}

- (NSString *)description {
    NSArray *keys = @[@"type", @"chs", @"png", @"code", @"times"];

    return [self dictionaryWithValuesForKeys:keys].description;
}

#pragma mark - 公共方法
- (NSDictionary *)dictionary {
    NSArray *keys = @[@"type", @"chs", @"directory", @"png", @"code", @"times"];

    return [self dictionaryWithValuesForKeys:keys];
}

@end


text:
 $(document).ready(function () {
    $('.forgot-pass').click(function(event) {
      $(".pr-wrap").toggleClass("show-pass-reset");
    });

    $('.pass-reset-submit').click(function(event) {
      $(".pr-wrap").removeClass("show-pass-reset");
    });
});


text:
<?php

import('lib.pkp.classes.form.Form');

class DOISettingsForm extends Form {

	//
	// Private properties
	//
	/** @var integer */
	var $_journalId;

	/**
	 * Get the journal ID.
	 * @return integer
	 */
	function _getJournalId() {
		return $this->_journalId;
	}

	/** @var DOIPubIdPlugin */
	var $_plugin;

	/**
	 * Get the plugin.
	 * @return DOIPubIdPlugin
	 */
	function &_getPlugin() {
		return $this->_plugin;
	}

	//
	// Constructor
	//
	/**
	 * Constructor
	 * @param $plugin DOIPubIdPlugin
	 * @param $journalId integer
	 */
	function DOISettingsForm(&$plugin, $journalId) {
		$this->_journalId = $journalId;
		$this->_plugin =& $plugin;

		parent::Form($plugin->getTemplatePath() . 'settingsForm.tpl');

		$this->addCheck(new FormValidatorCustom($this, 'doiObjects', 'required', 'plugins.pubIds.doi.manager.settings.doiObjectsRequired', create_function('$enableIssueDoi,$form', 'return $form->getData(\'enableIssueDoi\') || $form->getData(\'enableArticleDoi\') || $form->getData(\'enableGalleyDoi\') || $form->getData(\'enableSuppFileDoi\');'), array($this)));
		$this->addCheck(new FormValidatorRegExp($this, 'doiPrefix', 'required', 'plugins.pubIds.doi.manager.settings.doiPrefixPattern', '/^10\.[0-9]{4,7}$/'));
		$this->addCheck(new FormValidatorCustom($this, 'doiIssueSuffixPattern', 'required', 'plugins.pubIds.doi.manager.settings.doiIssueSuffixPatternRequired', create_function('$doiIssueSuffixPattern,$form', 'if ($form->getData(\'doiSuffix\') == \'pattern\' && $form->getData(\'enableIssueDoi\')) return $doiIssueSuffixPattern != \'\';return true;'), array($this)));
		$this->addCheck(new FormValidatorCustom($this, 'doiArticleSuffixPattern', 'required', 'plugins.pubIds.doi.manager.settings.doiArticleSuffixPatternRequired', create_function('$doiArticleSuffixPattern,$form', 'if ($form->getData(\'doiSuffix\') == \'pattern\' && $form->getData(\'enableArticleDoi\')) return $doiArticleSuffixPattern != \'\';return true;'), array($this)));
		$this->addCheck(new FormValidatorCustom($this, 'doiGalleySuffixPattern', 'required', 'plugins.pubIds.doi.manager.settings.doiGalleySuffixPatternRequired', create_function('$doiGalleySuffixPattern,$form', 'if ($form->getData(\'doiSuffix\') == \'pattern\' && $form->getData(\'enableGalleyDoi\')) return $doiGalleySuffixPattern != \'\';return true;'), array($this)));
		$this->addCheck(new FormValidatorCustom($this, 'doiSuppFileSuffixPattern', 'required', 'plugins.pubIds.doi.manager.settings.doiSuppFileSuffixPatternRequired', create_function('$doiSuppFileSuffixPattern,$form', 'if ($form->getData(\'doiSuffix\') == \'pattern\' && $form->getData(\'enableSuppFileDoi\')) return $doiSuppFileSuffixPattern != \'\';return true;'), array($this)));
		$this->addCheck(new FormValidatorPost($this));

		// for DOI reset requests
		import('lib.pkp.classes.linkAction.request.RemoteActionConfirmationModal');
		$application = PKPApplication::getApplication();
		$request = $application->getRequest();
		$clearPubIdsLinkAction =
		new LinkAction(
			'reassignDOIs',
			new RemoteActionConfirmationModal(
				__('plugins.pubIds.doi.manager.settings.doiReassign.confirm'),
				__('common.delete'),
				$request->url(null, null, 'plugin', null, array('verb' => 'settings', 'clearPubIds' => true, 'plugin' => $plugin->getName(), 'category' => 'pubIds')),
				'modal_delete'
			),
			__('plugins.pubIds.doi.manager.settings.doiReassign'),
			'delete'
		);
		$this->setData('clearPubIdsLinkAction', $clearPubIdsLinkAction);
		$this->setData('pluginName', $plugin->getName());
		$this->setData('doiSettingsHandlerJsUrl', $plugin->getJSFileUrl($request));
	}

	//
	// Implement template methods from Form
	//
	/**
	 * @see Form::initData()
	 */
	function initData() {
		$journalId = $this->_getJournalId();
		$plugin =& $this->_getPlugin();
		foreach($this->_getFormFields() as $fieldName => $fieldType) {
			$this->setData($fieldName, $plugin->getSetting($journalId, $fieldName));
		}
	}

	/**
	 * @see Form::readInputData()
	 */
	function readInputData() {
		$this->readUserVars(array_keys($this->_getFormFields()));
	}

	/**
	 * @see Form::execute()
	 */
	function execute() {
		$plugin =& $this->_getPlugin();
		$journalId = $this->_getJournalId();
		foreach($this->_getFormFields() as $fieldName => $fieldType) {
			$plugin->updateSetting($journalId, $fieldName, $this->getData($fieldName), $fieldType);
		}
	}

	//
	// Private helper methods
	//
	function _getFormFields() {
		return array(
			'enableIssueDoi' => 'bool',
			'enableArticleDoi' => 'bool',
			'enableGalleyDoi' => 'bool',
			'enableSuppFileDoi' => 'bool',
			'doiPrefix' => 'string',
			'doiSuffix' => 'string',
			'doiIssueSuffixPattern' => 'string',
			'doiArticleSuffixPattern' => 'string',
			'doiGalleySuffixPattern' => 'string',
			'doiSuppFileSuffixPattern' => 'string'
		);
	}
}

?>


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using Azure.AI.TextAnalytics.Models;

namespace Azure.AI.TextAnalytics
{
    /// <summary>
    /// Text Analytics Warning.
    /// </summary>
    public readonly struct TextAnalyticsWarning
    {
        internal TextAnalyticsWarning(TextAnalyticsWarningInternal warning)
            : this(warning.Code, warning.Message)
        {
        }

        internal TextAnalyticsWarning(DocumentWarning warning)
            : this(warning.Code.ToString(), warning.Message)
        {
        }

        internal TextAnalyticsWarning(string warningCode, string message)
        {
            WarningCode = warningCode;
            Message = message;
        }

        /// <summary>
        /// Code indicating the type of warning.
        /// </summary>
        public TextAnalyticsWarningCode WarningCode { get; }

        /// <summary>
        /// Message that contains more information about the reason of the warning.
        /// </summary>
        public string Message { get; }
    }
}


text:
(function() {
  var app;

  app = angular.module("MeApp");

  app.controller("savedCtrl", [
    "$scope", "PostResource", "Page", function($scope, PostResource, Page) {
      return $scope.page = Page;
    }
  ]);

}).call(this);


text:
<%
	var headContent = {
%>
	<% include("/template/blog/includes/header.html"){} %>

	<% include("/template/includes/ueditor_hightlighter.html"){} %>
	<% include("/template/includes/autojs.html"){} %>

<%
};

var bodyContent = {
%>
<%  include("/template/blog/includes/header_menu.html"){} %>

	<input type="hidden" name="article_id" value="${item.id}">
	<input type="hidden" name="create_id" value="${item.create_id}">
	<input type="hidden" name="count_comment" value="${item.count_comment!'0'}">

						${WEBSITE_TITLE! }

						${item.publish_time!''}

						${flyfox.suojin(item.publish_user!'',6)}

								${item.title}

								<% if(item.is_comment==1){ %>
								评论(${item.count_comment!'0'})
								<% } %>
								浏览量(${item.count_view!'0'})

${item.content!'' }

									<%
										if(taglist != null && taglist.~size > 0) {
									%>

										<%
											for(tagitem in taglist){
										%>

											${tagitem.tagname}

										<%
											}
										%>

									<%
									}
									%>

分享到:

				<% if(item.is_comment==1){ %>

					<% if(!isEmpty(session.session_user)){ %>

评论

						<textarea class="comment-textarea" name="comment"></textarea>

							<input id="comment-btn" type="button" value="发  布"  class="btn" style="background-color: #FF9933;"/>

					<% } else { %>

没有登录不能评论

					<% } %>

						<% for(comment in page.list){ %>

								<%
									var user = flyfox.getUser(comment.create_id);
									var userPic = user.title_url;
									if(isEmpty(userPic)){
										userPic = BASE_PATH + 'static/images/user/user.png';
									} else if(!strutil.startWith(userPic , 'http')) {
										userPic = ASE_PATH + userPic;
									}
								 %>

								${flyfox.getUserName(comment.create_id)}
								<% if(comment.status > 20) { %>
								回复
								${flyfox.getUserName(comment.reply_userid)}
								<% } %>

								${comment.content}

								${comment.create_time}
								<% if(!isEmpty(session.session_user) && comment.create_id==session.session_user.userid){ %>
									删除
								<% } %>
								<% if(!isEmpty(session.session_user) && comment.create_id!=session.session_user.userid){ %>
									回复
								<% } %>

						<%  } %>

					<%include("/template/blog/includes/paginator.html",{suffix:'#article_comment'}){} %>

				<% } %>

	<%  include("/template/blog/includes/footer.html"){} %>

<%}; %>

<% layout("/pages/template/_layout.html",{head:headContent,body:bodyContent}){ %>
<%} %>


text:
package httl.spi.loaders.resources;

import httl.Engine;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Locale;
import java.util.jar.JarFile;

/**
 * JarResource. (SPI, Prototype, ThreadSafe)
 *
 * @see httl.spi.loaders.JarLoader#load(String, Locale, String)
 *
 * @author Liang Fei (liangfei0201 AT gmail DOT com)
 */
public class JarResource extends InputStreamResource {

	private static final long serialVersionUID = 1L;

	private final File file;

	public JarResource(Engine engine, String name, Locale locale, String encoding, File file) {
		super(engine, name, locale, encoding);
		this.file = file;
	}

	public InputStream openStream() throws IOException {
		// ×¢£ºJarFileÓëFileµÄÉè¼ÆÊDz»Ò»ÑùµÄ£¬FileÏ൱ÓÚC#µÄFileInfo£¬Ö»³ÖÓÐÐÅÏ¢£¬
		// ¶øJarFile¹¹Ôìʱ¼´´ò¿ªÁ÷£¬ËùÒÔÿ´Î¶ÁÈ¡Êý¾Ýʱ£¬ÖØÐÂnewеÄʵÀý£¬¶ø²»×÷ΪÊôÐÔ×ֶγÖÓС£
		JarFile jarFile = new JarFile(file);
		return jarFile.getInputStream(jarFile.getEntry(getName()));
	}

	public long getLastModified() {
		return file.lastModified();
	}

	public long getLength() {
		try {
			JarFile jarFile = new JarFile(file);
			try {
				return jarFile.getEntry(getName()).getSize();
			} finally {
				jarFile.close();
			}
		} catch (IOException e) {
			return super.getLength();
		}
	}

}


text:
package com.ppmessage.ppcomdemo;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class GuideActivity extends AppCompatActivity {

    private Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_guide);

        button = (Button) findViewById(R.id.button2);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(GuideActivity.this, MainActivity.class);
                startActivity(intent);
            }
        });
    }
}


text:
//Problem 4. Multiplication Sign

//Write a program that shows the sign (+, - or 0) of the product of three real numbers, without calculating it.
//Use a sequence of if operators.

using System;
using System.Threading;
using System.Globalization;

class MultiplicationSignApp
{
    static void Main()
    {
        Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;

        Console.WriteLine("Enter three real numbers:");
        Console.Write("a = ");
        float firstNumber = float.Parse(Console.ReadLine());
        Console.Write("b = ");
        float secondNumber = float.Parse(Console.ReadLine());
        Console.Write("c = ");
        float thirdNumber = float.Parse(Console.ReadLine());

        if (firstNumber == 0 || secondNumber == 0 || thirdNumber == 0)
        {
            Console.WriteLine("The sign is: 0");
        }
        else if (firstNumber < 0 && secondNumber < 0 && thirdNumber < 0)
        {
            Console.WriteLine("The sign is: -");
        }
        else if (firstNumber > 0 && secondNumber > 0 && thirdNumber  > 0)
        {
            Console.WriteLine("The sign is: +");
        }
        else if (firstNumber < 0 && secondNumber > 0 && thirdNumber > 0)
        {
            Console.WriteLine("The sign is: -");
        }
        else if (firstNumber < 0 && secondNumber < 0 && thirdNumber > 0)
        {
            Console.WriteLine("The sign is: +");
        }
        else if (firstNumber > 0 && secondNumber < 0 && thirdNumber > 0)
        {
            Console.WriteLine("The sign is: +");
        }
        else if (firstNumber > 0 && secondNumber < 0 && thirdNumber < 0)
        {
            Console.WriteLine("The sign is: +");
        }
        else if (firstNumber > 0 && secondNumber > 0 && thirdNumber < 0)
        {
            Console.WriteLine("The sign is: +");
        }
    }
}


text:
=begin
> can run it directly using ruby/irb

## Methods

```
=end

printf "1.next : %s\n", 1.next
printf "1.positive? : %s\n", 1.positive?
printf "1.between?(0,5) : %s\n", 1.between?(0,5)

printf "1.method(\"even?\").call : %s\n", 1.method("even?").call

=begin
```

* now a custom defined method, default returns, default value parameters

```
=end

def return10
  return 10
end

def returnTimes5(some_number)
  5 * some_number
end

printf "return10 == returnTimes5(2) : %s\n", (return10 == returnTimes5(2))

def nothing; end
printf "class of return from blank method: %s\n", nothing.class
printf "class of return : %s\n", return10.class

def greet(name, msg="hello!")
  msg + " " + name
end

printf "greet('jon doe') : %s\n", greet('jon doe')
printf "greet('jane doe', 'hya!') : %s\n", greet('jane doe', 'hya!')

=begin
```

* arraying args

```
=end

def sum(*numbers)
  numbers.reduce(0) {|sum, num| sum + num } # 'inject' is an alias of 'reduce'
end

printf "sum(1,10,100,1000,10000): %s\n", sum(1,10,100,1000,10000)

def dimsum(one, two, three)
    one + two + three
end

dimsum_numbers = [1, 2, 3] # Without a splat, this is just one parameter
printf "dimsum(*dimsum_numbers) : %s\n", dimsum(*dimsum_numbers)

def greet_all(msg, *names)
  for name in names
    printf "%s %s\n", msg, name
  end
end

p "greet_all 'hoye!', 'jack', 'jill', 'jane' :"
greet_all "hoye!", "jack", "jill", "jane"

def introduction(age, gender, *names)
  names.reduce('') {|msg, name| msg + ' ' + name}
  msg + ', who\'s ' + age + ' and ' + gender
end

=begin
```

* can skip braces on last parameter if its a hash

```
=end

def account(uuid, id, options)
  printf "login to '%s' with '%s' identifier; ", id, uuid
  if options.has_key? :password
    printf "use password to login, "
  else
    printf "you are a guest here, "
  end
  p options[:config]
end

account '0x0000', 'jack', password: 'passwd', config: {'sync': true}
account '0x0000', 'jill', guest: 'foo', config: {'sync': false}

=begin
```

---
---
=end


text:
"""
The :mod:`sklearn.hmm` module implements hidden Markov models.

**Warning:** :mod:`sklearn.hmm` is orphaned, undocumented and has known
numerical stability issues. If nobody volunteers to write documentation and
make it more stable, this module will be removed in version 0.11.
"""

import string

import numpy as np

from .utils import check_random_state
from .utils.extmath import logsumexp
from .base import BaseEstimator
from .mixture import (
    GMM, log_multivariate_normal_density, sample_gaussian,
    distribute_covar_matrix_to_match_covariance_type, _validate_covars)
from . import cluster
import warnings
warnings.warn('sklearn.hmm is orphaned, undocumented and has known numerical'
              ' stability issues. If nobody volunteers to write documentation'
              ' and make it more stable, this module will be removed in'
              ' version 0.11.')

ZEROLOGPROB = -1e200
EPS = np.finfo(float).eps
NEGINF = - np.inf

def normalize(A, axis=None):
    """ Normalize the input array so that it sums to 1.

    Parameters
    ----------
    A: array, shape (n_samples, n_features)
       Non-normalized input data
    axis: int
          dimension along which normalization is performed

    Returns
    -------
    normalized_A: array, shape (n_samples, n_features)
        A with values normalized (summing to 1) along the prescribed axis

    WARNING: Modifies inplace the array
    """
    A += EPS
    Asum = A.sum(axis)
    if axis and A.ndim > 1:
        # Make sure we don't divide by zero.
        Asum[Asum == 0] = 1
        shape = list(A.shape)
        shape[axis] = 1
        Asum.shape = shape
    return A / Asum

class _BaseHMM(BaseEstimator):
    """Hidden Markov Model base class.

    Representation of a hidden Markov model probability distribution.
    This class allows for easy evaluation of, sampling from, and
    maximum-likelihood estimation of the parameters of a HMM.

    See the instance documentation for details specific to a
    particular object.

    Attributes
    ----------
    n_components : int (read-only)
        Number of states in the model.

    See Also
    --------
    GMM : Gaussian mixture model
    """

    # This class implements the public interface to all HMMs that
    # derive from it, including all of the machinery for the
    # forward-backward and Viterbi algorithms.  Subclasses need only
    # implement _generate_sample_from_state(), _compute_log_likelihood(),
    # _init(), _initialize_sufficient_statistics(),
    # _accumulate_sufficient_statistics(), and _do_mstep(), all of
    # which depend on the specific emission distribution.
    #
    # Subclasses will probably also want to implement properties for
    # the emission distribution parameters to expose them publically.

    def __init__(self, n_components=1, startprob=None, transmat=None,
                 startprob_prior=None, transmat_prior=None):
        self.n_components = n_components

        if startprob is None:
            startprob = np.tile(1.0 / n_components, n_components)
        self._set_startprob(startprob)

        if startprob_prior is None:
            startprob_prior = 1.0
        self.startprob_prior = startprob_prior

        if transmat is None:
            transmat = np.tile(1.0 / n_components,
                    (n_components, n_components))
        self._set_transmat(transmat)

        if transmat_prior is None:
            transmat_prior = 1.0
        self.transmat_prior = transmat_prior

    def eval(self, obs, maxrank=None, beamlogprob=NEGINF):
        """Compute the log probability under the model and compute posteriors

        Implements rank and beam pruning in the forward-backward
        algorithm to speed up inference in large models.

        Parameters
        ----------
        obs : array_like, shape (n, n_features)
            Sequence of n_features-dimensional data points.  Each row
            corresponds to a single point in the sequence.
        maxrank : int
            Maximum rank to evaluate for rank pruning.  If not None,
            only consider the top `maxrank` states in the inner
            sum of the forward algorithm recursion.  Defaults to None
            (no rank pruning).  See The HTK Book for more details.
        beamlogprob : float
            Width of the beam-pruning beam in log-probability units.
            Defaults to -numpy.Inf (no beam pruning).  See The HTK
            Book for more details.

        Returns
        -------
        logprob : array_like, shape (n,)
            Log probabilities of the sequence `obs`
        posteriors: array_like, shape (n, n_components)
            Posterior probabilities of each state for each
            observation

        See Also
        --------
        score : Compute the log probability under the model
        decode : Find most likely state sequence corresponding to a `obs`
        """
        obs = np.asarray(obs)
        framelogprob = self._compute_log_likelihood(obs)
        logprob, fwdlattice = self._do_forward_pass(framelogprob, maxrank,
                                                    beamlogprob)
        bwdlattice = self._do_backward_pass(framelogprob, fwdlattice, maxrank,
                                            beamlogprob)
        gamma = fwdlattice + bwdlattice
        # gamma is guaranteed to be correctly normalized by logprob at
        # all frames, unless we do approximate inference using pruning.
        # So, we will normalize each frame explicitly in case we
        # pruned too aggressively.
        posteriors = np.exp(gamma.T - logsumexp(gamma, axis=1)).T
        posteriors += np.finfo(np.float32).eps
        posteriors /= np.sum(posteriors, axis=1).reshape((-1, 1))
        return logprob, posteriors

    def score(self, obs, maxrank=None, beamlogprob=NEGINF):
        """Compute the log probability under the model.

        Parameters
        ----------
        obs : array_like, shape (n, n_features)
            Sequence of n_features-dimensional data points.  Each row
            corresponds to a single data point.
        maxrank : int
            Maximum rank to evaluate for rank pruning.  If not None,
            only consider the top `maxrank` states in the inner
            sum of the forward algorithm recursion.  Defaults to None
            (no rank pruning).  See The HTK Book for more details.
        beamlogprob : float
            Width of the beam-pruning beam in log-probability units.
            Defaults to -numpy.Inf (no beam pruning).  See The HTK
            Book for more details.

        Returns
        -------
        logprob : array_like, shape (n,)
            Log probabilities of each data point in `obs`

        See Also
        --------
        eval : Compute the log probability under the model and posteriors
        decode : Find most likely state sequence corresponding to a `obs`
        """
        obs = np.asarray(obs)
        framelogprob = self._compute_log_likelihood(obs)
        logprob, fwdlattice = self._do_forward_pass(framelogprob, maxrank,
                                                    beamlogprob)
        return logprob

    def decode(self, obs, maxrank=None, beamlogprob=NEGINF):
        """Find most likely state sequence corresponding to `obs`.

        Uses the Viterbi algorithm.

        Parameters
        ----------
        obs : array_like, shape (n, n_features)
            List of n_features-dimensional data points.  Each row
            corresponds to a single data point.
        maxrank : int
            Maximum rank to evaluate for rank pruning.  If not None,
            only consider the top `maxrank` states in the inner
            sum of the forward algorithm recursion.  Defaults to None
            (no rank pruning).  See The HTK Book for more details.
        beamlogprob : float
            Width of the beam-pruning beam in log-probability units.
            Defaults to -numpy.Inf (no beam pruning).  See The HTK
            Book for more details.

        Returns
        -------
        viterbi_logprob : float
            Log probability of the maximum likelihood path through the HMM
        states : array_like, shape (n,)
            Index of the most likely states for each observation

        See Also
        --------
        eval : Compute the log probability under the model and posteriors
        score : Compute the log probability under the model
        """
        obs = np.asarray(obs)
        framelogprob = self._compute_log_likelihood(obs)
        logprob, state_sequence = self._do_viterbi_pass(framelogprob, maxrank,
                                                        beamlogprob)
        return logprob, state_sequence

    def predict(self, obs, **kwargs):
        """Find most likely state sequence corresponding to `obs`.

        Parameters
        ----------
        obs : array_like, shape (n, n_features)
            List of n_features-dimensional data points.  Each row
            corresponds to a single data point.
        maxrank : int
            Maximum rank to evaluate for rank pruning.  If not None,
            only consider the top `maxrank` states in the inner
            sum of the forward algorithm recursion.  Defaults to None
            (no rank pruning).  See The HTK Book for more details.
        beamlogprob : float
            Width of the beam-pruning beam in log-probability units.
            Defaults to -numpy.Inf (no beam pruning).  See The HTK
            Book for more details.

        Returns
        -------
        states : array_like, shape (n,)
            Index of the most likely states for each observation
        """
        logprob, state_sequence = self.decode(obs, **kwargs)
        return state_sequence

    def predict_proba(self, obs, **kwargs):
        """Compute the posterior probability for each state in the model

        Parameters
        ----------
        obs : array_like, shape (n, n_features)
            List of n_features-dimensional data points.  Each row
            corresponds to a single data point.

        See eval() for a list of accepted keyword arguments.

        Returns
        -------
        T : array-like, shape (n, n_components)
            Returns the probability of the sample for each state in the model.
        """
        logprob, posteriors = self.eval(obs, **kwargs)
        return posteriors

    def rvs(self, n=1, random_state=None):
        """Generate random samples from the model.

        Parameters
        ----------
        n : int
            Number of samples to generate.

        Returns
        -------
        obs : array_like, length `n`
            List of samples
        """
        random_state = check_random_state(random_state)

        startprob_pdf = self._get_startprob()
        startprob_cdf = np.cumsum(startprob_pdf)
        transmat_pdf = self._get_transmat()
        transmat_cdf = np.cumsum(transmat_pdf, 1)

        # Initial state.
        rand = random_state.rand()
        currstate = (startprob_cdf > rand).argmax()
        obs = [self._generate_sample_from_state(
            currstate, random_state=random_state)]

        for x in xrange(n - 1):
            rand = random_state.rand()
            currstate = (transmat_cdf[currstate] > rand).argmax()
            obs.append(self._generate_sample_from_state(
                currstate, random_state=random_state))

        return np.array(obs)

    def fit(self, obs, n_iter=10, thresh=1e-2, params=string.ascii_letters,
            init_params=string.ascii_letters, maxrank=None,
            beamlogprob=NEGINF, **kwargs):
        """Estimate model parameters.

        An initialization step is performed before entering the EM
        algorithm. If you want to avoid this step, set the keyword
        argument init_params to the empty string ''. Likewise, if you
        would like just to do an initialization, call this method with
        n_iter=0.

        Parameters
        ----------
        obs : list
            List of array-like observation sequences (shape (n_i, n_features)).

        n_iter : int, optional
            Number of iterations to perform.

        thresh : float, optional
            Convergence threshold.

        params : string, optional
            Controls which parameters are updated in the training
            process.  Can contain any combination of 's' for startprob,
            't' for transmat, 'm' for means, and 'c' for covars, etc.
            Defaults to all parameters.

        init_params : string, optional
            Controls which parameters are initialized prior to
            training.  Can contain any combination of 's' for
            startprob, 't' for transmat, 'm' for means, and 'c' for
            covars, etc.  Defaults to all parameters.

        maxrank : int, optional
            Maximum rank to evaluate for rank pruning.  If not None,
            only consider the top `maxrank` states in the inner
            sum of the forward algorithm recursion.  Defaults to None
            (no rank pruning).  See "The HTK Book" for more details.

        beamlogprob : float, optional
            Width of the beam-pruning beam in log-probability units.
            Defaults to -numpy.Inf (no beam pruning).  See "The HTK
            Book" for more details.

        Notes
        -----
        In general, `logprob` should be non-decreasing unless
        aggressive pruning is used.  Decreasing `logprob` is generally
        a sign of overfitting (e.g. a covariance parameter getting too
        small).  You can fix this by getting more training data, or
        decreasing `covars_prior`.
        """
        self._init(obs, init_params)

        logprob = []
        for i in xrange(n_iter):
            # Expectation step
            stats = self._initialize_sufficient_statistics()
            curr_logprob = 0
            for seq in obs:
                framelogprob = self._compute_log_likelihood(seq)
                lpr, fwdlattice = self._do_forward_pass(framelogprob, maxrank,
                                                       beamlogprob)
                bwdlattice = self._do_backward_pass(framelogprob, fwdlattice,
                                                   maxrank, beamlogprob)
                gamma = fwdlattice + bwdlattice
                posteriors = np.exp(gamma.T - logsumexp(gamma, axis=1)).T
                curr_logprob += lpr
                self._accumulate_sufficient_statistics(
                    stats, seq, framelogprob, posteriors, fwdlattice,
                    bwdlattice, params)
            logprob.append(curr_logprob)

            # Check for convergence.
            if i > 0 and abs(logprob[-1] - logprob[-2]) < thresh:
                break

            # Maximization step
            self._do_mstep(stats, params, **kwargs)

        return self

    def _get_startprob(self):
        """Mixing startprob for each state."""
        return np.exp(self._log_startprob)

    def _set_startprob(self, startprob):
        if len(startprob) != self.n_components:
            raise ValueError('startprob must have length n_components')
        if not np.allclose(np.sum(startprob), 1.0):
            raise ValueError('startprob must sum to 1.0')

        self._log_startprob = np.log(np.asarray(startprob).copy())

    def _get_transmat(self):
        """Matrix of transition probabilities."""
        return np.exp(self._log_transmat)

    def _set_transmat(self, transmat):
        if (np.asarray(transmat).shape
                != (self.n_components, self.n_components)):
            raise ValueError('transmat must have shape ' +
                    '(n_components, n_components)')
        if not np.all(np.allclose(np.sum(transmat, axis=1), 1.0)):
            raise ValueError('Rows of transmat must sum to 1.0')

        self._log_transmat = np.log(np.asarray(transmat).copy())
        underflow_idx = np.isnan(self._log_transmat)
        self._log_transmat[underflow_idx] = NEGINF

    def _do_viterbi_pass(self, framelogprob, maxrank=None,
                         beamlogprob=NEGINF):
        nobs = len(framelogprob)
        lattice = np.zeros((nobs, self.n_components))
        traceback = np.zeros((nobs, self.n_components), dtype=np.int)

        lattice[0] = self._log_startprob + framelogprob[0]
        for n in xrange(1, nobs):
            idx = self._prune_states(lattice[n - 1], maxrank, beamlogprob)
            pr = self._log_transmat[idx].T + lattice[n - 1, idx]
            lattice[n] = np.max(pr, axis=1) + framelogprob[n]
            traceback[n] = np.argmax(pr, axis=1)
        lattice[lattice <= ZEROLOGPROB] = NEGINF

        # Do traceback.
        reverse_state_sequence = []
        s = lattice[-1].argmax()
        logprob = lattice[-1, s]
        for frame in reversed(traceback):
            reverse_state_sequence.append(s)
            s = frame[s]

        reverse_state_sequence.reverse()
        return logprob, np.array(reverse_state_sequence)

    def _do_forward_pass(self, framelogprob, maxrank=None,
                         beamlogprob=NEGINF):
        nobs = len(framelogprob)
        fwdlattice = np.zeros((nobs, self.n_components))

        fwdlattice[0] = self._log_startprob + framelogprob[0]
        for n in xrange(1, nobs):
            idx = self._prune_states(fwdlattice[n - 1], maxrank, beamlogprob)
            fwdlattice[n] = (logsumexp(self._log_transmat[idx].T
                                    + fwdlattice[n - 1, idx], axis=1)
                             + framelogprob[n])
        fwdlattice[fwdlattice <= ZEROLOGPROB] = NEGINF

        return logsumexp(fwdlattice[-1]), fwdlattice

    def _do_backward_pass(self, framelogprob, fwdlattice, maxrank=None,
                          beamlogprob=NEGINF):
        nobs = len(framelogprob)
        bwdlattice = np.zeros((nobs, self.n_components))

        for n in xrange(nobs - 1, 0, -1):
            # Do HTK style pruning (p. 137 of HTK Book version 3.4).
            # Don't bother computing backward probability if
            # fwdlattice * bwdlattice is more than a certain distance
            # from the total log likelihood.
            idx = self._prune_states(bwdlattice[n] + fwdlattice[n], None,
                                     -50)
            bwdlattice[n - 1] = logsumexp(self._log_transmat[:, idx] +
                                       bwdlattice[n, idx] +
                                       framelogprob[n, idx],
                                       axis=1)
        bwdlattice[bwdlattice <= ZEROLOGPROB] = NEGINF

        return bwdlattice

    def _prune_states(self, lattice_frame, maxrank, beamlogprob):
        """ Returns indices of the active states in `lattice_frame`
        after rank and beam pruning.
        """
        # Beam pruning
        threshlogprob = logsumexp(lattice_frame) + beamlogprob
        # Rank pruning
        if maxrank:
            # How big should our rank pruning histogram be?
            nbins = 3 * len(lattice_frame)

            lattice_min = lattice_frame[lattice_frame > ZEROLOGPROB].min() - 1
            hst, bin_edges = np.histogram(lattice_frame, bins=nbins,
                                    range=(lattice_min, lattice_frame.max()))

            # Want to look at the high ranks.
            hst = hst[::-1].cumsum()
            bin_edges = .5 * (bin_edges[:-1] + bin_edges[1:])
            bin_edges = bin_edges[::-1]

            rankthresh = bin_edges[hst >= min(maxrank,
                                              self.n_components)].max()

            # Only change the threshold if it is stricter than the beam
            # threshold.
            threshlogprob = max(threshlogprob, rankthresh)

        # Which states are active?
        state_idx, = np.nonzero(lattice_frame >= threshlogprob)
        return state_idx

    def _compute_log_likelihood(self, obs):
        pass

    def _generate_sample_from_state(self, state, random_state=None):
        pass

    def _init(self, obs, params):
        if 's' in params:
            self._set_startprob((1.0 / self.n_components) *
                                np.ones(self.n_components))
        if 't' in params:
            self._set_transmat(1.0 / self.n_components *
                               np.ones((self.n_components, self.n_components)))

    # Methods used by self.fit()

    def _initialize_sufficient_statistics(self):
        stats = {'nobs': 0,
                 'start': np.zeros(self.n_components),
                 'trans': np.zeros((self.n_components, self.n_components))}
        return stats

    def _accumulate_sufficient_statistics(self, stats, seq, framelogprob,
                                          posteriors, fwdlattice, bwdlattice,
                                          params):
        stats['nobs'] += 1
        if 's' in params:
            stats['start'] += posteriors[0]
        if 't' in params:
            for t in xrange(len(framelogprob)):
                zeta = (fwdlattice[t - 1][:, np.newaxis] + self._log_transmat
                        + framelogprob[t] + bwdlattice[t])
                stats['trans'] += np.exp(zeta - logsumexp(zeta))

    def _do_mstep(self, stats, params, **kwargs):
        # Based on Huang, Acero, Hon, "Spoken Language Processing",
        # p. 443 - 445
        if 's' in params:
            self._set_startprob(normalize(
                np.maximum(self.startprob_prior - 1.0 + stats['start'],
                           EPS)))
        if 't' in params:
            self._set_transmat(normalize(
                np.maximum(self.transmat_prior - 1.0 + stats['trans'],
                           EPS), axis=1))

class GaussianHMM(_BaseHMM):
    """Hidden Markov Model with Gaussian emissions

    Representation of a hidden Markov model probability distribution.
    This class allows for easy evaluation of, sampling from, and
    maximum-likelihood estimation of the parameters of a HMM.

    Parameters
    ----------
    n_components : int
        Number of states.

    _covariance_type : string
        String describing the type of covariance parameters to
        use.  Must be one of 'spherical', 'tied', 'diag', 'full'.
        Defaults to 'diag'.

    Attributes
    ----------
    covariance_type : string
        String describing the type of covariance parameters used by
        the model.  Must be one of 'spherical', 'tied', 'diag', 'full'.

    n_features : int
        Dimensionality of the Gaussian emissions.

    n_components : int
        Number of states in the model.

    transmat : array, shape (`n_components`, `n_components`)
        Matrix of transition probabilities between states.

    startprob : array, shape ('n_components`,)
        Initial state occupation distribution.

    means : array, shape (`n_components`, `n_features`)
        Mean parameters for each state.

    covars : array
        Covariance parameters for each state.  The shape depends on
        `_covariance_type`::

            (`n_components`,)                   if 'spherical',
            (`n_features`, `n_features`)              if 'tied',
            (`n_components`, `n_features`)           if 'diag',
            (`n_components`, `n_features`, `n_features`)  if 'full'

    Examples
    --------
    >>> from sklearn.hmm import GaussianHMM
    >>> GaussianHMM(n_components=2)
    ...                             #doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
    GaussianHMM(covariance_type=None, covars_prior=0.01, covars_weight=1,
    means_prior=None, means_weight=0, n_components=2, startprob=None,
    startprob_prior=1.0, transmat=None, transmat_prior=1.0)

    See Also
    --------
    GMM : Gaussian mixture model
    """

    def __init__(self, n_components=1, covariance_type='diag', startprob=None,
                 transmat=None, startprob_prior=None, transmat_prior=None,
                 means_prior=None, means_weight=0,
                 covars_prior=1e-2, covars_weight=1):
        super(GaussianHMM, self).__init__(n_components, startprob, transmat,
                                          startprob_prior=startprob_prior,
                                          transmat_prior=transmat_prior)

        self._covariance_type = covariance_type
        if not covariance_type in ['spherical', 'tied', 'diag', 'full']:
            raise ValueError('bad covariance_type')

        self.means_prior = means_prior
        self.means_weight = means_weight

        self.covars_prior = covars_prior
        self.covars_weight = covars_weight

    def _get_covars(self):
        """Return covars as a full matrix."""
        if self._covariance_type == 'full':
            return self._covars
        elif self._covariance_type == 'diag':
            return [np.diag(cov) for cov in self._covars]
        elif self._covariance_type == 'tied':
            return [self._covars] * self.n_components
        elif self._covariance_type == 'spherical':
            return [np.eye(self.n_features) * f for f in self._covars]

    def _set_covars(self, covars):
        covars = np.asarray(covars)
        _validate_covars(covars, self._covariance_type, self.n_components)
        self._covars = covars.copy()

    def _compute_log_likelihood(self, obs):
        return log_multivariate_normal_density(
            obs, self._means, self._covars, self._covariance_type)

    def _generate_sample_from_state(self, state, random_state=None):
        if self._covariance_type == 'tied':
            cv = self._covars
        else:
            cv = self._covars[state]
        return sample_gaussian(self._means[state], cv, self._covariance_type,
                               random_state=random_state)

    def _init(self, obs, params='stmc'):
        super(GaussianHMM, self)._init(obs, params=params)

        if (hasattr(self, 'n_features')
            and self.n_features != obs[0].shape[1]):
            raise ValueError('Unexpected number of dimensions, got %s but '
                             'expected %s' % (obs[0].shape[1],
                                              self.n_features))

        self.n_features = obs[0].shape[1]

        if 'm' in params:
            self._means = cluster.KMeans(
                k=self.n_components).fit(obs[0]).cluster_centers_
        if 'c' in params:
            cv = np.cov(obs[0].T)
            if not cv.shape:
                cv.shape = (1, 1)
            self._covars = distribute_covar_matrix_to_match_covariance_type(
                cv, self._covariance_type, self.n_components)

    def _initialize_sufficient_statistics(self):
        stats = super(GaussianHMM, self)._initialize_sufficient_statistics()
        stats['post'] = np.zeros(self.n_components)
        stats['obs'] = np.zeros((self.n_components, self.n_features))
        stats['obs**2'] = np.zeros((self.n_components, self.n_features))
        stats['obs*obs.T'] = np.zeros((self.n_components, self.n_features,
                                       self.n_features))
        return stats

    def _accumulate_sufficient_statistics(self, stats, obs, framelogprob,
                                          posteriors, fwdlattice, bwdlattice,
                                          params):
        super(GaussianHMM, self)._accumulate_sufficient_statistics(
            stats, obs, framelogprob, posteriors, fwdlattice, bwdlattice,
            params)

        if 'm' in params or 'c' in params:
            stats['post'] += posteriors.sum(axis=0)
            stats['obs'] += np.dot(posteriors.T, obs)

        if 'c' in params:
            if self._covariance_type in ('spherical', 'diag'):
                stats['obs**2'] += np.dot(posteriors.T, obs ** 2)
            elif self._covariance_type in ('tied', 'full'):
                for t, o in enumerate(obs):
                    obsobsT = np.outer(o, o)
                    for c in xrange(self.n_components):
                        stats['obs*obs.T'][c] += posteriors[t, c] * obsobsT

    def _do_mstep(self, stats, params, **kwargs):
        super(GaussianHMM, self)._do_mstep(stats, params)

        # Based on Huang, Acero, Hon, "Spoken Language Processing",
        # p. 443 - 445
        denom = stats['post'][:, np.newaxis]
        if 'm' in params:
            prior = self.means_prior
            weight = self.means_weight
            if prior is None:
                weight = 0
                prior = 0
            self._means = (weight * prior + stats['obs']) / (weight + denom)

        if 'c' in params:
            covars_prior = self.covars_prior
            covars_weight = self.covars_weight
            if covars_prior is None:
                covars_weight = 0
                covars_prior = 0

            means_prior = self.means_prior
            means_weight = self.means_weight
            if means_prior is None:
                means_weight = 0
                means_prior = 0
            meandiff = self._means - means_prior

            if self._covariance_type in ('spherical', 'diag'):
                cv_num = (means_weight * (meandiff) ** 2
                          + stats['obs**2']
                          - 2 * self._means * stats['obs']
                          + self._means ** 2 * denom)
                cv_den = max(covars_weight - 1, 0) + denom
                self._covars = (covars_prior + cv_num) / cv_den
                if self._covariance_type == 'spherical':
                    self._covars = np.tile(self._covars.mean(1)[:, np.newaxis],
                                           (1, self._covars.shape[1]))
            elif self._covariance_type in ('tied', 'full'):
                cvnum = np.empty((self.n_components, self.n_features,
                                  self.n_features))
                for c in xrange(self.n_components):
                    obsmean = np.outer(stats['obs'][c], self._means[c])

                    cvnum[c] = (means_weight * np.outer(meandiff[c],
                                                        meandiff[c])
                                + stats['obs*obs.T'][c]
                                - obsmean - obsmean.T
                                + np.outer(self._means[c], self._means[c])
                                * stats['post'][c])
                cvweight = max(covars_weight - self.n_features, 0)
                if self._covariance_type == 'tied':
                    self._covars = ((covars_prior + cvnum.sum(axis=0))
                                    / (cvweight + stats['post'].sum()))
                elif self._covariance_type == 'full':
                    self._covars = ((covars_prior + cvnum)
                                   / (cvweight + stats['post'][:, None, None]))

class MultinomialHMM(_BaseHMM):
    """Hidden Markov Model with multinomial (discrete) emissions

    Attributes
    ----------
    n_components : int
        Number of states in the model.

    n_symbols : int
        Number of possible symbols emitted by the model (in the observations).

    transmat : array, shape (`n_components`, `n_components`)
        Matrix of transition probabilities between states.

    startprob : array, shape ('n_components`,)
        Initial state occupation distribution.

    emissionprob : array, shape ('n_components`, 'n_symbols`)
        Probability of emitting a given symbol when in each state.

    Examples
    --------
    >>> from sklearn.hmm import MultinomialHMM
    >>> MultinomialHMM(n_components=2)
    ...                             #doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
    MultinomialHMM(n_components=2, startprob=None, startprob_prior=1.0,
             transmat=None, transmat_prior=1.0)

    See Also
    --------
    GaussianHMM : HMM with Gaussian emissions
    """

    def __init__(self, n_components=1, startprob=None, transmat=None,
                 startprob_prior=None, transmat_prior=None):
        """Create a hidden Markov model with multinomial emissions.

        Parameters
        ----------
        n_components : int
            Number of states.
        """
        super(MultinomialHMM, self).__init__(n_components, startprob, transmat,
                                             startprob_prior=startprob_prior,
                                             transmat_prior=transmat_prior)

    def _get_emissionprob(self):
        """Emission probability distribution for each state."""
        return np.exp(self._log_emissionprob)

    def _set_emissionprob(self, emissionprob):
        emissionprob = np.asarray(emissionprob)
        if hasattr(self, 'n_symbols') and \
               emissionprob.shape != (self.n_components, self.n_symbols):
            raise ValueError('emissionprob must have shape '
                             '(n_components, n_symbols)')

        self._log_emissionprob = np.log(emissionprob)
        underflow_idx = np.isnan(self._log_emissionprob)
        self._log_emissionprob[underflow_idx] = NEGINF
        self.n_symbols = self._log_emissionprob.shape[1]

    def _compute_log_likelihood(self, obs):
        return self._log_emissionprob[:, obs].T

    def _generate_sample_from_state(self, state, random_state=None):
        cdf = np.cumsum(self._get_emissionprob()[state])
        random_state = check_random_state(random_state)
        rand = random_state.rand()
        symbol = (cdf > rand).argmax()
        return symbol

    def _init(self, obs, params='ste'):
        super(MultinomialHMM, self)._init(obs, params=params)

        if 'e' in params:
            emissionprob = normalize(np.random.rand(self.n_components,
                                                    self.n_symbols), 1)
            self._set_emissionprob(emissionprob)

    def _initialize_sufficient_statistics(self):
        stats = super(MultinomialHMM, self)._initialize_sufficient_statistics()
        stats['obs'] = np.zeros((self.n_components, self.n_symbols))
        return stats

    def _accumulate_sufficient_statistics(self, stats, obs, framelogprob,
                                          posteriors, fwdlattice, bwdlattice,
                                          params):
        super(MultinomialHMM, self)._accumulate_sufficient_statistics(
            stats, obs, framelogprob, posteriors, fwdlattice, bwdlattice,
            params)
        if 'e' in params:
            for t, symbol in enumerate(obs):
                stats['obs'][:, symbol] += posteriors[t]

    def _do_mstep(self, stats, params, **kwargs):
        super(MultinomialHMM, self)._do_mstep(stats, params)
        if 'e' in params:
            self._set_emissionprob((stats['obs']
                                    / stats['obs'].sum(1)[:, np.newaxis]))

class GMMHMM(_BaseHMM):
    """Hidden Markov Model with Gaussin mixture emissions

    Attributes
    ----------
    n_components : int
        Number of states in the model.

    transmat : array, shape (`n_components`, `n_components`)
        Matrix of transition probabilities between states.

    startprob : array, shape ('n_components`,)
        Initial state occupation distribution.

    gmms : array of GMM objects, length `n_components`
        GMM emission distributions for each state.

    Examples
    --------
    >>> from sklearn.hmm import GMMHMM
    >>> GMMHMM(n_components=2, n_mix=10, covariance_type='diag')
    ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
    GMMHMM(covariance_type=None,
        gmms=[GMM(covariance_type=None, min_covar=0.001, n_components=10,
            random_state=None, thresh=0.01), GMM(covariance_type=None,
                min_covar=0.001, n_components=10, random_state=None,
                thresh=0.01)],
        n_components=2, n_mix=10, startprob=None, startprob_prior=1.0,
        transmat=None, transmat_prior=1.0)

    See Also
    --------
    GaussianHMM : HMM with Gaussian emissions
    """

    def __init__(self, n_components=1, n_mix=1, startprob=None,
                 transmat=None, startprob_prior=None, transmat_prior=None,
                 gmms=None, covariance_type=None):
        """Create a hidden Markov model with GMM emissions.

        Parameters
        ----------
        n_components : int
            Number of states.
        """
        super(GMMHMM, self).__init__(n_components, startprob, transmat,
                                     startprob_prior=startprob_prior,
                                     transmat_prior=transmat_prior)

        # XXX: Hotfit for n_mix that is incompatible with the scikit's
        # BaseEstimator API
        self.n_mix = n_mix
        self._covariance_type = covariance_type
        if gmms is None:
            gmms = []
            for x in xrange(self.n_components):
                if covariance_type is None:
                    g = GMM(n_mix)
                else:
                    g = GMM(n_mix, covariance_type=covariance_type)
                gmms.append(g)
        self.gmms = gmms

    def _compute_log_likelihood(self, obs):
        return np.array([g.score(obs) for g in self.gmms]).T

    def _generate_sample_from_state(self, state, random_state=None):
        return self.gmms[state].sample(1, random_state=random_state).flatten()

    def _init(self, obs, params='stwmc'):
        super(GMMHMM, self)._init(obs, params=params)

        allobs = np.concatenate(obs, 0)
        for g in self.gmms:
            g.fit(allobs, n_iter=0, init_params=params)

    def _initialize_sufficient_statistics(self):
        stats = super(GMMHMM, self)._initialize_sufficient_statistics()
        stats['norm'] = [np.zeros(g.weights_.shape) for g in self.gmms]
        stats['means'] = [np.zeros(np.shape(g.means_)) for g in self.gmms]
        stats['covars'] = [np.zeros(np.shape(g.covars_)) for g in self.gmms]
        return stats

    def _accumulate_sufficient_statistics(self, stats, obs, framelogprob,
                                          posteriors, fwdlattice, bwdlattice,
                                          params):
        super(GMMHMM, self)._accumulate_sufficient_statistics(
            stats, obs, framelogprob, posteriors, fwdlattice, bwdlattice,
            params)

        for state, g in enumerate(self.gmms):
            _, lgmm_posteriors = g.eval(obs)
            lgmm_posteriors += np.log(posteriors[:, state][:, np.newaxis]
                                      + np.finfo(np.float).eps)
            gmm_posteriors = np.exp(lgmm_posteriors)
            tmp_gmm = GMM(g.n_components, covariance_type=g._covariance_type)
            n_features = g.means_.shape[1]
            tmp_gmm._set_covars(
                distribute_covar_matrix_to_match_covariance_type(
                    np.eye(n_features), g._covariance_type,
                    g.n_components))
            norm = tmp_gmm._do_mstep(obs, gmm_posteriors, params)

            if np.any(np.isnan(tmp_gmm.covars_)):
                raise ValueError

            stats['norm'][state] += norm
            if 'm' in params:
                stats['means'][state] += tmp_gmm.means_ * norm[:, np.newaxis]
            if 'c' in params:
                if tmp_gmm._covariance_type == 'tied':
                    stats['covars'][state] += tmp_gmm.covars_ * norm.sum()
                else:
                    cvnorm = np.copy(norm)
                    shape = np.ones(tmp_gmm.covars_.ndim)
                    shape[0] = np.shape(tmp_gmm.covars_)[0]
                    cvnorm.shape = shape
                    stats['covars'][state] += tmp_gmm.covars_ * cvnorm

    def _do_mstep(self, stats, params, covars_prior=1e-2, **kwargs):
        super(GMMHMM, self)._do_mstep(stats, params)
        # All that is left to do is to apply covars_prior to the
        # parameters updated in _accumulate_sufficient_statistics.
        for state, g in enumerate(self.gmms):
            n_features = g.means_.shape[1]
            norm = stats['norm'][state]
            if 'w' in params:
                g.weights_ = normalize(norm)
            if 'm' in params:
                g.means_ = stats['means'][state] / norm[:, np.newaxis]
            if 'c' in params:
                if g._covariance_type == 'tied':
                    g.covars_ = ((stats['covars'][state]
                                 + covars_prior * np.eye(n_features))
                                / norm.sum())
                else:
                    cvnorm = np.copy(norm)
                    shape = np.ones(g.covars_.ndim)
                    shape[0] = np.shape(g.covars_)[0]
                    cvnorm.shape = shape
                    if (g._covariance_type in ['spherical', 'diag']):
                        g.covars_ = (stats['covars'][state]
                                    + covars_prior) / cvnorm
                    elif g._covariance_type == 'full':
                        eye = np.eye(n_features)
                        g.covars_ = ((stats['covars'][state]
                                     + covars_prior * eye[np.newaxis])
                                    / cvnorm)


text:
package bingo.odata.producer.servlets;

import java.io.IOException;
import java.io.OutputStream;
import java.io.Writer;

import javax.servlet.http.HttpServletResponse;

import bingo.lang.Exceptions;
import bingo.odata.ODataResponse;

public class ODataServletResponse implements ODataResponse {

	private final HttpServletResponse	response;

	public ODataServletResponse(HttpServletResponse response){
		this.response = response;
	}

	public void setStatus(int status) {
		response.setStatus(status);
    }

	public void setHeader(String name, String value) {
		response.setHeader(name, value);
    }

	public String getContentType() {
		return response.getContentType();
	}

	public void setContentType(String contentType){
		response.setContentType(contentType);
	}

	public Writer getWriter() {
		try {
	        return response.getWriter();
        } catch (IOException e) {
        	throw Exceptions.uncheck(e);
        }
	}

	public OutputStream getOutputStream() {
		try {
			return response.getOutputStream();
        } catch (IOException e) {
        	throw Exceptions.uncheck(e);
        }
	}
}


text:
package org.jasig.cas.ticket.proxy.support;

import org.jasig.cas.authentication.Credential;
import org.jasig.cas.authentication.HttpBasedServiceCredential;
import org.jasig.cas.ticket.TicketGrantingTicket;
import org.jasig.cas.ticket.proxy.ProxyHandler;
import org.jasig.cas.util.DefaultUniqueTicketIdGenerator;
import org.jasig.cas.util.UniqueTicketIdGenerator;
import org.jasig.cas.util.http.HttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.validation.constraints.NotNull;
import java.net.URL;

/**
 * Proxy Handler to handle the default callback functionality of CAS 2.0.
 * <p>
 * The default behavior as defined in the CAS 2 Specification is to callback the
 * URL provided and give it a pgtIou and a pgtId.
 * </p>
 *
 * @author Scott Battaglia
 * @since 3.0.0
 */
public final class Cas20ProxyHandler implements ProxyHandler {
    private static final int BUFFER_LENGTH_ADDITIONAL_CHARGE = 15;

    /** The proxy granting ticket identifier parameter. */
    private static final String PARAMETER_PROXY_GRANTING_TICKET_IOU = "pgtIou";

    /** The Constant proxy granting ticket parameter. */
    private static final String PARAMETER_PROXY_GRANTING_TICKET_ID = "pgtId";

    /** The Commons Logging instance. */
    private final Logger logger = LoggerFactory.getLogger(getClass());

    /** Generate unique ids. */
    @NotNull
    private UniqueTicketIdGenerator uniqueTicketIdGenerator = new DefaultUniqueTicketIdGenerator();

    /** Instance of Apache Commons HttpClient. */
    @NotNull
    private HttpClient httpClient;

    @Override
    public String handle(final Credential credential, final TicketGrantingTicket proxyGrantingTicketId) {
        final HttpBasedServiceCredential serviceCredentials = (HttpBasedServiceCredential) credential;
        final String proxyIou = this.uniqueTicketIdGenerator.getNewTicketId(TicketGrantingTicket.PROXY_GRANTING_TICKET_IOU_PREFIX);

        final URL callbackUrl = serviceCredentials.getCallbackUrl();
        final String serviceCredentialsAsString = callbackUrl.toExternalForm();
        final int bufferLength = serviceCredentialsAsString.length() + proxyIou.length()
                + proxyGrantingTicketId.getId().length() + BUFFER_LENGTH_ADDITIONAL_CHARGE;
        final StringBuilder stringBuffer = new StringBuilder(bufferLength);

        stringBuffer.append(serviceCredentialsAsString);

        if (callbackUrl.getQuery() != null) {
            stringBuffer.append("&");
        } else {
            stringBuffer.append("?");
        }

        stringBuffer.append(PARAMETER_PROXY_GRANTING_TICKET_IOU);
        stringBuffer.append("=");
        stringBuffer.append(proxyIou);
        stringBuffer.append("&");
        stringBuffer.append(PARAMETER_PROXY_GRANTING_TICKET_ID);
        stringBuffer.append("=");
        stringBuffer.append(proxyGrantingTicketId);

        if (this.httpClient.isValidEndPoint(stringBuffer.toString())) {
            logger.debug("Sent ProxyIou of {} for service: {}", proxyIou, serviceCredentials);
            return proxyIou;
        }

        logger.debug("Failed to send ProxyIou of {} for service: {}", proxyIou, serviceCredentials);
        return null;
    }

    /**
     * @param uniqueTicketIdGenerator The uniqueTicketIdGenerator to set.
     */
    public void setUniqueTicketIdGenerator(final UniqueTicketIdGenerator uniqueTicketIdGenerator) {
        this.uniqueTicketIdGenerator = uniqueTicketIdGenerator;
    }

    public void setHttpClient(final HttpClient httpClient) {
        this.httpClient = httpClient;
    }

    @Override
    public boolean canHandle(final Credential credential) {
        return true;
    }
}


text:
// Copyright (c) 1999-2004 Brian Wellington (bwelling@xbill.org)

package org.xbill.DNS;

import java.util.Arrays;
import java.util.Iterator;

/**
 * Constants and functions relating to DNSSEC (algorithm constants).
 * DNSSEC provides authentication for DNS information.  RRsets are
 * signed by an appropriate key, and a SIG record is added to the set.
 * A KEY record is obtained from DNS and used to validate the signature,
 * The KEY record must also be validated or implicitly trusted - to
 * validate a key requires a series of validations leading to a trusted
 * key.  The key must also be authorized to sign the data.
 * @see SIGRecord
 * @see KEYRecord
 * @see RRset
 *
 * @author Brian Wellington
 */

public class DNSSEC {

public static class Algorithm {
	private Algorithm() {}

	/** RSA/MD5 public key (deprecated) */
	public static final int RSAMD5 = 1;

	/** Diffie Hellman key */
	public static final int DH = 2;

	/** DSA public key */
	public static final int DSA = 3;

	/** Elliptic Curve key */
	public static final int ECC = 4;

	/** RSA/SHA1 public key */
	public static final int RSASHA1 = 5;

	/** DSA/SHA1, NSEC3-aware public key */
	public static final int DSA_NSEC3_SHA1 = 6;

	/** RSA/SHA1, NSEC3-aware public key */
	public static final int RSA_NSEC3_SHA1 = 7;

	/** Indirect keys; the actual key is elsewhere. */
	public static final int INDIRECT = 252;

	/** Private algorithm, specified by domain name */
	public static final int PRIVATEDNS = 253;

	/** Private algorithm, specified by OID */
	public static final int PRIVATEOID = 254;

	private static Mnemonic algs = new Mnemonic("DNSSEC algorithm",
						    Mnemonic.CASE_UPPER);

	static {
		algs.setMaximum(0xFF);
		algs.setNumericAllowed(true);

		algs.add(RSAMD5, "RSAMD5");
		algs.add(DH, "DH");
		algs.add(DSA, "DSA");
		algs.add(ECC, "ECC");
		algs.add(RSASHA1, "RSASHA1");
		algs.add(DSA_NSEC3_SHA1, "DSA-NSEC3-SHA1");
		algs.add(RSA_NSEC3_SHA1, "RSA-NSEC3-SHA1");
		algs.add(INDIRECT, "INDIRECT");
		algs.add(PRIVATEDNS, "PRIVATEDNS");
		algs.add(PRIVATEOID, "PRIVATEOID");
	}

	/**
	 * Converts an algorithm into its textual representation
	 */
	public static String
	string(int alg) {
		return algs.getText(alg);
	}

	/**
	 * Converts a textual representation of an algorithm into its numeric
	 * code.  Integers in the range 0..255 are also accepted.
	 * @param s The textual representation of the algorithm
	 * @return The algorithm code, or -1 on error.
	 */
	public static int
	value(String s) {
		return algs.getValue(s);
	}
}

public static final int RSAMD5 = Algorithm.RSAMD5;
public static final int RSA = Algorithm.RSAMD5;
public static final int DH = Algorithm.DH;
public static final int DSA = Algorithm.DSA;
public static final int RSASHA1 = Algorithm.RSASHA1;
public static final int DSA_NSEC3_SHA1 = Algorithm.DSA_NSEC3_SHA1;
public static final int RSA_NSEC3_SHA1 = Algorithm.RSA_NSEC3_SHA1;

public static final int Failed = -1;
public static final int Insecure = 0;
public static final int Secure = 1;

private
DNSSEC() { }

private static void
digestSIG(DNSOutput out, SIGBase sig) {
	out.writeU16(sig.getTypeCovered());
	out.writeU8(sig.getAlgorithm());
	out.writeU8(sig.getLabels());
	out.writeU32(sig.getOrigTTL());
	out.writeU32(sig.getExpire().getTime() / 1000);
	out.writeU32(sig.getTimeSigned().getTime() / 1000);
	out.writeU16(sig.getFootprint());
	sig.getSigner().toWireCanonical(out);
}

/**
 * Creates a byte array containing the concatenation of the fields of the
 * SIG record and the RRsets to be signed/verified.  This does not perform
 * a cryptographic digest.
 * @param sig The SIG record used to sign/verify the rrset.
 * @param rrset The data to be signed/verified.
 * @return The data to be cryptographically signed or verified.
 */
public static byte []
digestRRset(RRSIGRecord sig, RRset rrset) {
	DNSOutput out = new DNSOutput();
	digestSIG(out, sig);

	int size = rrset.size();
	Record [] records = new Record[size];

	Iterator it = rrset.rrs();
	Name name = rrset.getName();
	Name wild = null;
	int sigLabels = sig.getLabels() + 1; // Add the root label back.
	if (name.labels() > sigLabels)
		wild = name.wild(name.labels() - sigLabels);
	while (it.hasNext())
		records[--size] = (Record) it.next();
	Arrays.sort(records);

	DNSOutput header = new DNSOutput();
	if (wild != null)
		wild.toWireCanonical(header);
	else
		name.toWireCanonical(header);
	header.writeU16(rrset.getType());
	header.writeU16(rrset.getDClass());
	header.writeU32(sig.getOrigTTL());
	for (int i = 0; i < records.length; i++) {
		out.writeByteArray(header.toByteArray());
		int lengthPosition = out.current();
		out.writeU16(0);
		out.writeByteArray(records[i].rdataToWireCanonical());
		int rrlength = out.current() - lengthPosition - 2;
		out.save();
		out.jump(lengthPosition);
		out.writeU16(rrlength);
		out.restore();
	}
	return out.toByteArray();
}

/**
 * Creates a byte array containing the concatenation of the fields of the
 * SIG record and the message to be signed/verified.  This does not perform
 * a cryptographic digest.
 * @param sig The SIG record used to sign/verify the rrset.
 * @param msg The message to be signed/verified.
 * @param previous If this is a response, the signature from the query.
 * @return The data to be cryptographically signed or verified.
 */
public static byte []
digestMessage(SIGRecord sig, Message msg, byte [] previous) {
	DNSOutput out = new DNSOutput();
	digestSIG(out, sig);

	if (previous != null)
		out.writeByteArray(previous);

	msg.toWire(out);
	return out.toByteArray();
}

}


text:
/**
 *
 */
package org.openntf.domino.ext;

import org.openntf.domino.DxlExporter.MIMEOption;
import org.openntf.domino.DxlExporter.RichTextOption;

/**
 * OpenNTF extension to DxlExporter class
 *
 * @author withersp
 *
 *
 */
public interface DxlExporter {

	/**
	 * Sets how MIME should be exported, either as DXL or as raw content, using {@link org.openntf.domino.DxlExporter.MIMEOption}
	 *
	 * @param option
	 *            MIMEOption to apply
	 * @since org.openntf.domino 4.5.0
	 */
	public void setMIMEOption(MIMEOption option);

	// PW TODO: Add getters to return MIME options

	/**
	 * Sets how Rich Text should be exported, either as DXL or as raw content, using {@link org.openntf.domino.DxlExporter.RichTextOption}
	 *
	 * @param option
	 *            RichTextOption to apply
	 * @since org.openntf.domino 4.5.0
	 */
	public void setRichTextOption(RichTextOption option);

}


text:
This is based on https://github.com/hwasungmars/kafka-broker-docker

The main changes are:

   - use Kafka 0.8.0 instead of 0.8.1.1.
   - set `host.name` instead of `advertised.host.name`.
   - build on our own Spark base image.


text:
{% extends "site_base.html" %}

{% load bootstrap_tags %}
{% load i18n %}

{% block head_title %}{% trans "Receipt Upload "%}{% endblock %}

{% block body_id %}{% trans "receipt_upload" %}{% endblock %}

{% block page_title %}{% trans "Receipt Upload" %}{% endblock %}

{% block extra_head %}

{% endblock %}

{% block body %}

    <form method="POST" action="" enctype="multipart/form-data" class="form-horizontal">
        {% csrf_token %}
        {% if form.errors %}

                    {% trans "There were errors in your form, please correct them and submit again." %}

        {% endif %}
        {% if form.errors and not form.non_field_errors %}

            {% blocktrans count counter=form.errors.items|length %}Please correct the error below.{% plural %}Please correct the errors below.{% endblocktrans %}

        {% elif form.non_field_errors %}

              {{ form.non_field_errors }}

        {% endif %}

        <fieldset>
        {{ form|as_bootstrap }}
        </fieldset>

            <input class="btn btn-primary" type="submit" value="Submit" />

    </form>

{% trans "Your previously uploaded receipts:" %}

          {% trans "Type" %}
          {% trans "Date" %}
          {% trans "Description " %}
          {% trans "Amount " %}

          {% for receipt in receipts %}

              {{ receipt.receipt_type }}
              {{ receipt.date }}
              {{ receipt.description }}
              {{ receipt.amount }}
              Receipt Image

          {% endfor %}

{% endblock %}