text:
using namespace std::literals;

namespace arangodb::iresearch {
namespace {

// Ensures that all referenced analyzer features are consistent.
[[maybe_unused]] void checkAnalyzerFeatures(IResearchLinkMeta const& meta) {
  auto assertAnalyzerFeatures =
      [version = LinkVersion{meta._version}](auto const& analyzers) {
        for (auto& analyzer : analyzers) {
          irs::type_info::type_id invalidNorm;
          if (version < LinkVersion::MAX) {
            invalidNorm = irs::type<irs::Norm2>::id();
          } else {
            invalidNorm = irs::type<irs::Norm>::id();
          }

          const auto features = analyzer->fieldFeatures();

          TRI_ASSERT(std::end(features) == std::find(std::begin(features),
                                                     std::end(features),
                                                     invalidNorm));
        }
      };

  auto checkFieldFeatures = [&assertAnalyzerFeatures](auto const& fieldMeta,
                                                      auto&& self) -> void {
    assertAnalyzerFeatures(fieldMeta._analyzers);
    for (auto const& entry : fieldMeta._fields) {
      self(*entry.value(), self);
    }
  };
  assertAnalyzerFeatures(meta._analyzerDefinitions);
  checkFieldFeatures(meta, checkFieldFeatures);
}

template<typename T>
T getMetric(IResearchLink const& link) {
  T metric;
  metric.addLabel("db", link.getDbName());
  metric.addLabel("view", link.getViewId());
  metric.addLabel("collection", link.getCollectionName());
  metric.addLabel("shard", link.getShardName());
  return metric;
}

std::string getLabels(IResearchLink const& link) {
  return "db=\"" + link.getDbName() +                     //
         "\",view=\"" + link.getViewId() +                //
         "\",collection=\"" + link.getCollectionName() +  //
         "\",shard=\"" + link.getShardName() + "\"";
}

Result linkWideCluster(LogicalCollection const& logical, IResearchView* view) {
  if (!view) {
    return {};
  }
  auto shardIds = logical.shardIds();
  // go through all shard IDs of the collection and
  // try to link any links missing links will be populated
  // when they are created in the per-shard collection
  if (!shardIds) {
    return {};
  }
  for (auto& entry : *shardIds) {  // per-shard collection is always in vocbase
    auto collection = logical.vocbase().lookupCollection(entry.first);
    if (!collection) {
      // missing collection should be created after Plan becomes Current
      continue;
    }
    if (auto link = IResearchLinkHelper::find(*collection, *view); link) {
      if (auto r = view->link(link->self()); !r.ok()) {
        return r;
      }
    }
  }
  return {};
}

}  // namespace

template<typename T>
Result IResearchLink::toView(std::shared_ptr<LogicalView> const& logical,
                             std::shared_ptr<T>& view) {
  if (!logical) {
    return {};
  }
  if (logical->type() != ViewType::kArangoSearch) {
    return {TRI_ERROR_ARANGO_DATA_SOURCE_NOT_FOUND,
            "error finding view: '" + _viewGuid + "' for link '" +
                std::to_string(_id.id()) + "' : no such view"};
  }
  view = basics::downCast<T>(logical);
  // TODO(MBkkt) Now its workaround for unit tests that expected this behavior
  _viewGuid = view->guid();  // TRI_ASSERT(_viewGuid == view->guid());
  return {};
}

Result IResearchLink::initAndLink(bool& pathExists, InitCallback const& init,
                                  IResearchView* view) {
  irs::index_reader_options readerOptions;
#ifdef USE_ENTERPRISE
  setupReaderEntepriseOptions(readerOptions, _collection.vocbase().server(),
                              _meta);
#endif
  auto r = initDataStore(pathExists, init, _meta._version, !_meta._sort.empty(),
#ifdef USE_ENTERPRISE
                         _meta._hasNested,
#else
                         false,
#endif
                         _meta._storedValues.columns(), _meta._sortCompression,
                         readerOptions);
  if (r.ok() && view) {
    r = view->link(_asyncSelf);
  }
  return r;
}

Result IResearchLink::initSingleServer(bool& pathExists,
                                       InitCallback const& init) {
  std::shared_ptr<IResearchView> view;
  auto r = toView(_collection.vocbase().lookupView(_viewGuid), view);
  if (!r.ok()) {
    return r;
  }
  return initAndLink(pathExists, init, view.get());
}

Result IResearchLink::initCoordinator(InitCallback const& init) {
  auto& vocbase = _collection.vocbase();
  auto& ci = vocbase.server().getFeature<ClusterFeature>().clusterInfo();
  std::shared_ptr<IResearchViewCoordinator> view;
  if (auto r = toView(ci.getView(vocbase.name(), _viewGuid), view); !view) {
    return r;
  }
  return view->link(*this);
}

Result IResearchLink::initDBServer(bool& pathExists, InitCallback const& init) {
  auto& vocbase = _collection.vocbase();
  auto& server = vocbase.server();
  bool const clusterEnabled = server.getFeature<ClusterFeature>().isEnabled();
  bool wide = _collection.id() == _collection.planId() && _collection.isAStub();
  std::shared_ptr<IResearchView> view;
  if (clusterEnabled) {
    auto& ci = server.getFeature<ClusterFeature>().clusterInfo();
    clusterCollectionName(_collection, wide ? nullptr : &ci, id().id(),
                          _meta.willIndexIdAttribute(), _meta._collectionName);
    if (auto r = toView(ci.getView(vocbase.name(), _viewGuid), view); !r.ok()) {
      return r;
    }
  } else {
    LOG_TOPIC("67dd6", DEBUG, TOPIC)
        << "Skipped link '" << id().id()
        << "' maybe due to disabled cluster features.";
  }
  if (wide) {
    return linkWideCluster(_collection, view.get());
  }
  if (_meta._collectionName.empty() && !clusterEnabled &&
      server.getFeature<EngineSelectorFeature>().engine().inRecovery() &&
      _meta.willIndexIdAttribute()) {
    LOG_TOPIC("f25ce", FATAL, TOPIC)
        << "Upgrade conflicts with recovering ArangoSearch link '" << id().id()
        << "' Please rollback the updated arangodb binary and"
           " finish the recovery first.";
    THROW_ARANGO_EXCEPTION_MESSAGE(
        TRI_ERROR_INTERNAL,
        "Upgrade conflicts with recovering ArangoSearch link."
        " Please rollback the updated arangodb binary and"
        " finish the recovery first.");
  }
  return initAndLink(pathExists, init, view.get());
}

IResearchLink::IResearchLink(IndexId iid, LogicalCollection& collection)
    : IResearchDataStore(iid, collection) {}

IResearchLink::~IResearchLink() {
  // disassociate from view if it has not been done yet
  auto r = unload();
  if (!r.ok()) {
    try {
      LOG_TOPIC("2b41f", ERR, TOPIC)
          << "failed to unload arangodb_search link in link destructor: "
          << r.errorNumber() << " " << r.errorMessage();
    } catch (...) {
    }
  }
}

bool IResearchLink::operator==(LogicalView const& view) const noexcept {
  return _viewGuid == view.guid();
}

bool IResearchLink::operator==(IResearchLinkMeta const& meta) const noexcept {
  return _meta == meta;
}

Result IResearchLink::drop() {
  // the lookup and unlink is valid for single-server only (that is the only
  // scenario where links are persisted) on coordinator and db-server the
  // IResearchView is immutable and lives in ClusterInfo therefore on
  // coordinator and db-server a new plan will already have an IResearchView
  // without the link this avoids deadlocks with ClusterInfo::loadPlan() during
  // lookup in ClusterInfo
  if (ServerState::instance()->isSingleServer()) {
    auto view = basics::downCast<IResearchView>(
        collection().vocbase().lookupView(_viewGuid));

    // may occur if the link was already unlinked from the view via another
    // instance this behavior was seen
    // user-access-right-drop-view-arangosearch-spec.js where the collection
    // drop was called through REST, the link was dropped as a result of the
    // collection drop call then the view was dropped via a separate REST call
    // then the vocbase was destroyed calling
    // collection close()-> link unload() -> link drop() due to collection
    // marked as dropped thus returning an error here will cause
    // ~TRI_vocbase_t() on RocksDB to receive an exception which is not handled
    // in the destructor the reverse happens during drop of a collection with
    // MMFiles i.e. collection drop() -> collection close()-> link unload(),
    // then link drop()
    if (!view) {
      LOG_TOPIC("f4e2c", WARN, iresearch::TOPIC)
          << "unable to find arangosearch view '" << _viewGuid
          << "' while dropping arangosearch link '" << _id.id() << "'";
    } else {
      // unlink before reset() to release lock in view (if any)
      view->unlink(collection().id());
    }
  }

  return deleteDataStore();
}

Result IResearchLink::init(velocypack::Slice definition, bool& pathExists,
                           InitCallback const& init) {
  auto& vocbase = _collection.vocbase();
  auto& server = vocbase.server();
  bool const isSingleServer = ServerState::instance()->isSingleServer();
  if (!isSingleServer && !server.hasFeature<ClusterFeature>()) {
    return {
        TRI_ERROR_INTERNAL,
        "failure to get cluster info while initializing arangosearch link '" +
            std::to_string(_id.id()) + "'"};
  }
  std::string error;
  // definition should already be normalized and analyzers created if required
  if (!_meta.init(server, definition, error, vocbase.name())) {
    return {TRI_ERROR_BAD_PARAMETER,
            "error parsing view link parameters from json: " + error};
  }
#ifdef ARANGODB_ENABLE_MAINTAINER_MODE
  checkAnalyzerFeatures(_meta);
#endif
  if (!definition.isObject() ||
      !definition.get(StaticStrings::ViewIdField).isString()) {
    return {TRI_ERROR_ARANGO_DATA_SOURCE_NOT_FOUND,
            "error finding view for link '" + std::to_string(_id.id()) + "'"};
  }
  TRI_ASSERT(_meta._sortCompression);
  _viewGuid = definition.get(StaticStrings::ViewIdField).stringView();

  if (auto s = definition.get(StaticStrings::LinkError); s.isString()) {
    if (s.stringView() == StaticStrings::LinkErrorOutOfSync) {
      // mark index as out of sync
      setOutOfSync();
    } else if (s.stringView() == StaticStrings::LinkErrorFailed) {
      // TODO: not implemented yet
    }
  }

  Result r;
  if (isSingleServer) {
    r = initSingleServer(pathExists, init);
  } else if (ServerState::instance()->isCoordinator()) {
    r = initCoordinator(init);
  } else if (ServerState::instance()->isDBServer()) {
    r = initDBServer(pathExists, init);
  } else {
    TRI_ASSERT(false);
    return r;
  }
  if (r.ok()) {  // TODO(MBkkt) Do we really need this check?
    _comparer.reset(_meta._sort);
  }
  return r;
}

bool IResearchLink::isHidden() {
  // hide links unless we are on a DBServer
  return !ServerState::instance()->isDBServer();
}

bool IResearchLink::isSorted() {
  return false;  // IResearch does not provide a fixed default sort order
}

void IResearchLink::load() {
  // Note: this function is only used by RocksDB
}

bool IResearchLink::matchesDefinition(velocypack::Slice slice) const {
  if (!slice.isObject() || !slice.hasKey(StaticStrings::ViewIdField)) {
    return false;  // slice has no view identifier field
  }
  auto viewId = slice.get(StaticStrings::ViewIdField);
  // NOTE: below will not match if 'viewId' is 'id' or 'name',
  //       but ViewIdField should always contain GUID
  if (!viewId.isString() || !viewId.isEqualString(_viewGuid)) {
    // IResearch View identifiers of current object and slice do not match
    return false;
  }
  IResearchLinkMeta other;
  std::string errorField;
  // for db-server analyzer validation should have already passed on coordinator
  // (missing analyzer == no match)
  auto& vocbase = _collection.vocbase();
  return other.init(vocbase.server(), slice, errorField, vocbase.name()) &&
         _meta == other;
}

Result IResearchLink::properties(velocypack::Builder& builder,
                                 bool forPersistence) const {
  if (!builder.isOpenObject()  // not an open object
      || !_meta.json(_collection.vocbase().server(), builder, forPersistence,
                     nullptr, &(_collection.vocbase()))) {
    return {TRI_ERROR_BAD_PARAMETER};
  }

  builder.add(arangodb::StaticStrings::IndexId,
              velocypack::Value(std::to_string(_id.id())));
  builder.add(arangodb::StaticStrings::IndexType,
              velocypack::Value(
                  arangodb::iresearch::StaticStrings::ViewArangoSearchType));
  builder.add(StaticStrings::ViewIdField, velocypack::Value(_viewGuid));

  if (isOutOfSync()) {
    // link is out of sync - we need to report that
    builder.add(StaticStrings::LinkError,
                VPackValue(StaticStrings::LinkErrorOutOfSync));
  }

  return {};
}

Index::IndexType IResearchLink::type() {
  // TODO: don't use enum
  return Index::TRI_IDX_TYPE_IRESEARCH_LINK;
}

char const* IResearchLink::typeName() {
  return StaticStrings::ViewArangoSearchType.data();
}

bool IResearchLink::setCollectionName(std::string_view name) noexcept {
  TRI_ASSERT(!name.empty());
  if (_meta._collectionName.empty()) {
    _meta._collectionName = name;
    return true;
  }
  LOG_TOPIC_IF("5573c", ERR, TOPIC, name != _meta._collectionName)
      << "Collection name mismatch for arangosearch link '" << id() << "'."
      << " Meta name '" << _meta._collectionName << "' setting name '" << name
      << "'";
  TRI_ASSERT(name == _meta._collectionName);
  return false;
}

Result IResearchLink::unload() noexcept {
  // TODO(MBkkt) It's true? Now it's just a guess.
  // This is necessary because the removal of the collection can be parallel
  // with the removal of the link: when we decided whether to drop the link,
  // the collection was still there. But when we did an unload link,
  // the collection was already lazily deleted.
  if (_collection.deleted()  // collection deleted
      || _collection.status() == TRI_VOC_COL_STATUS_DELETED) {
    return basics::catchToResult([&] { return drop(); });
  }
  shutdownDataStore();
  return {};
}

////////////////////////////////////////////////////////////////////////////////
/// @brief lookup referenced analyzer
////////////////////////////////////////////////////////////////////////////////
AnalyzerPool::ptr IResearchLink::findAnalyzer(
    AnalyzerPool const& analyzer) const {
  auto const it =
      _meta._analyzerDefinitions.find(std::string_view(analyzer.name()));

  if (it == _meta._analyzerDefinitions.end()) {
    return nullptr;
  }

  auto pool = *it;

  if (pool && analyzer == *pool) {
    return pool;
  }

  return nullptr;
}

std::string_view IResearchLink::format() const noexcept {
  return getFormat(LinkVersion{_meta._version});
}

IResearchViewStoredValues const& IResearchLink::storedValues() const noexcept {
  return _meta._storedValues;
}

std::string const& IResearchLink::getDbName() const noexcept {
  return _collection.vocbase().name();
}

std::string const& IResearchLink::getViewId() const noexcept {
  return _viewGuid;
}

std::string IResearchLink::getCollectionName() const {
  if (ServerState::instance()->isSingleServer()) {
    return std::to_string(_collection.id().id());
  }
  if (ServerState::instance()->isDBServer()) {
    return _meta._collectionName;
  }
  return _collection.name();
}

std::string const& IResearchLink::getShardName() const noexcept {
  if (ServerState::instance()->isDBServer()) {
    return _collection.name();
  }
  return arangodb::StaticStrings::Empty;
}

void IResearchLink::insertMetrics() {
  auto& metric =
      _collection.vocbase().server().getFeature<metrics::MetricsFeature>();
  _numFailedCommits =
      &metric.add(getMetric<arangodb_search_num_failed_commits>(*this));
  _numFailedCleanups =
      &metric.add(getMetric<arangodb_search_num_failed_cleanups>(*this));
  _numFailedConsolidations =
      &metric.add(getMetric<arangodb_search_num_failed_consolidations>(*this));
  _avgCommitTimeMs = &metric.add(getMetric<arangodb_search_commit_time>(*this));
  _avgCleanupTimeMs =
      &metric.add(getMetric<arangodb_search_cleanup_time>(*this));
  _avgConsolidationTimeMs =
      &metric.add(getMetric<arangodb_search_consolidation_time>(*this));
  _metricStats = &metric.batchAdd<MetricStats>(kSearchStats, getLabels(*this));
}

void IResearchLink::removeMetrics() {
  auto& metric =
      _collection.vocbase().server().getFeature<metrics::MetricsFeature>();
  if (_numFailedCommits) {
    _numFailedCommits = nullptr;
    metric.remove(getMetric<arangodb_search_num_failed_commits>(*this));
  }
  if (_numFailedCleanups) {
    _numFailedCleanups = nullptr;
    metric.remove(getMetric<arangodb_search_num_failed_cleanups>(*this));
  }
  if (_numFailedConsolidations) {
    _numFailedConsolidations = nullptr;
    metric.remove(getMetric<arangodb_search_num_failed_consolidations>(*this));
  }
  if (_avgCommitTimeMs) {
    _avgCommitTimeMs = nullptr;
    metric.remove(getMetric<arangodb_search_commit_time>(*this));
  }
  if (_avgCleanupTimeMs) {
    _avgCleanupTimeMs = nullptr;
    metric.remove(getMetric<arangodb_search_cleanup_time>(*this));
  }
  if (_avgConsolidationTimeMs) {
    _avgConsolidationTimeMs = nullptr;
    metric.remove(getMetric<arangodb_search_consolidation_time>(*this));
  }
  if (_metricStats) {
    _metricStats = nullptr;
    metric.batchRemove(kSearchStats, getLabels(*this));
  }
}

void IResearchLink::invalidateQueryCache(TRI_vocbase_t* vocbase) {
  aql::QueryCache::instance()->invalidate(vocbase, _viewGuid);
}

}  // namespace arangodb::iresearch


text:
#include <sstmac/replacements/mpi.h>
#include <stdio.h>

namespace finalized {
/** FIXME: This test program assumes that MPI_Error_string will work even
   if MPI is not initialized.  That is not guaranteed.  */

/** Normally, when checking for error returns from MPI calls, you must ensure
   that the error handler on the relevant object (communicator, file, or
   window) has been set to MPI_ERRORS_RETURN.  The tests in this
   program are a special case, as either a failure or an abort will
   indicate a problem */

int finalized( int argc, char *argv[] )
{
    int error;
    int flag;
    char err_string[1024];
    int length = 1024;
    int rank;

    flag = 0;
    error = MPI_Finalized(&flag);
    if (error != MPI_SUCCESS)
    {
	MPI_Error_string(error, err_string, &length);
	printf("MPI_Finalized failed: %s\n", err_string);
	fflush(stdout);
	return error;
    }
    if (flag)
    {
	printf("MPI_Finalized returned true before MPI_Init.\n");
	return -1;
    }

    error = MPI_Init(&argc, &argv);
    if (error != MPI_SUCCESS)
    {
	MPI_Error_string(error, err_string, &length);
	printf("MPI_Init failed: %s\n", err_string);
	fflush(stdout);
	return error;
    }

    error = MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    if (error != MPI_SUCCESS)
    {
	MPI_Error_string(error, err_string, &length);
	printf("MPI_Comm_rank failed: %s\n", err_string);
	fflush(stdout);
	MPI_Abort(MPI_COMM_WORLD, error);
	return error;
    }

    flag = 0;
    error = MPI_Finalized(&flag);
    if (error != MPI_SUCCESS)
    {
	MPI_Error_string(error, err_string, &length);
	printf("MPI_Finalized failed: %s\n", err_string);
	fflush(stdout);
	MPI_Abort(MPI_COMM_WORLD, error);
	return error;
    }
    if (flag)
    {
	printf("MPI_Finalized returned true before MPI_Finalize.\n");
	fflush(stdout);
	MPI_Abort(MPI_COMM_WORLD, error);
	return -1;
    }

    error = MPI_Barrier(MPI_COMM_WORLD);
    if (error != MPI_SUCCESS)
    {
	MPI_Error_string(error, err_string, &length);
	printf("MPI_Barrier failed: %s\n", err_string);
	fflush(stdout);
	MPI_Abort(MPI_COMM_WORLD, error);
	return error;
    }

    error = MPI_Finalize();
    if (error != MPI_SUCCESS)
    {
	MPI_Error_string(error, err_string, &length);
	printf("MPI_Finalize failed: %s\n", err_string);
	fflush(stdout);
	return error;
    }

    flag = 0;
    error = MPI_Finalized(&flag);
    if (error != MPI_SUCCESS)
    {
	MPI_Error_string(error, err_string, &length);
	printf("MPI_Finalized failed: %s\n", err_string);
	fflush(stdout);
	return error;
    }
    if (!flag)
    {
	printf("MPI_Finalized returned false after MPI_Finalize.\n");
	return -1;
    }
    if (rank == 0)
    {
	printf(" No Errors\n");
    }
    return 0;
}

}

redpajama_set_name: RedPajamaGithub


text:
package org.devcloud.snippets.app;

// The class has to extend the BroadcastReceiver to get the notification from the system

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class WritePostAlarm extends BroadcastReceiver {

  private static final String TAG = "WritePostAlarm";
  public static String NOTIFICATION_ID = "notification-id";

  /**
   * This method is called when the BroadcastReceiver is receiving an Intent
   * broadcast.  During this time you can use the other methods on
   * BroadcastReceiver to view/modify the current result values.  This method
   * is always called within the main thread of its process, unless you
   * explicitly asked for it to be scheduled on a different thread using
   * {@link android.content.Context#registerReceiver(android.content.BroadcastReceiver,
   * IntentFilter, String, android.os.Handler)}. When it runs on the main
   * thread you should
   * never perform long-running operations in it (there is a timeout of
   * 10 seconds that the system allows before considering the receiver to
   * be blocked and a candidate to be killed). You cannot launch a popup dialog
   * in your implementation of onReceive().
   *

   *
If this BroadcastReceiver was launched through a <receiver> tag,
   * then the object is no longer alive after returning from this
   * function.  This means you should not perform any operations that
   * return a result to you asynchronously -- in particular, for interacting
   * with services, you should use
   * {@link android.content.Context#startService(android.content.Intent)} instead of
   * {@link android.content.Context#bindService(android.content.Intent, ServiceConnection, int)}.  If you wish
   * to interact with a service that is already running, you can use
   * {@link #peekService}.
   *

   *
The Intent filters used in {@link android.content.Context#registerReceiver}
   * and in application manifests are not guaranteed to be exclusive. They
   * are hints to the operating system about how to find suitable recipients. It is
   * possible for senders to force delivery to specific recipients, bypassing filter
   * resolution.  For this reason, {@link #onReceive(android.content.Context, android.content.Intent) onReceive()}
   * implementations should respond only to known actions, ignoring any unexpected
   * Intents that they may receive.
   *
   * @param context The Context in which the receiver is running.
   * @param intent  The Intent being received.
   */
  @Override
  public void onReceive(Context context, Intent intent) {
    Log.d(TAG, "Recurring alarm; popping up notification.");

    // Create PendingIntent (what happens when we click notification).
    Intent notificationIntent = new Intent(context, MainActivity.class);
    PendingIntent pInt = PendingIntent.getActivity(context, 0, notificationIntent, 0);

    // Request the notification manager
    NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification = getNotification(context, context.getString(R.string.write_post_notify), pInt);
    int id = intent.getIntExtra(NOTIFICATION_ID, 0);

    // Fire the notification
    notificationManager.notify(id, notification);
  }

  private Notification getNotification(Context context, String content, PendingIntent pi) {
    Notification.Builder builder = new Notification.Builder(context);
    builder.setContentIntent(pi);
    builder.setContentTitle("Scheduled Notification");
    builder.setContentText(content);
    // TODO(nat@natwelch.com): Get better icon.
    builder.setSmallIcon(R.drawable.ic_plusone_small_off_client);
    builder.setAutoCancel(true);
    builder.setPriority(Notification.PRIORITY_LOW);
    return builder.build();
  }
}


text:
Object.defineProperty (module.exports, "__esModule", { value: true });
module.exports.Context3DMipFilter = module.exports.default = {
	MIPLINEAR: "miplinear",
	MIPNEAREST: "mipnearest",
	MIPNONE: "mipnone"
};


text:
package org.terasology.rendering.dag.nodes;

import org.terasology.config.RenderingConfig;
import org.terasology.monitoring.PerformanceMonitor;
import org.terasology.registry.In;
import org.terasology.rendering.assets.material.Material;
import org.terasology.rendering.cameras.Camera;
import org.terasology.rendering.dag.WireframeCapableNode;
import org.terasology.rendering.opengl.FBO;
import org.terasology.rendering.opengl.FrameBuffersManager;
import org.terasology.rendering.world.WorldRenderer;
import static org.lwjgl.opengl.GL11.GL_COLOR_BUFFER_BIT;
import static org.lwjgl.opengl.GL11.GL_DEPTH_BUFFER_BIT;
import static org.lwjgl.opengl.GL11.glClear;
import static org.terasology.rendering.opengl.OpenGLUtils.bindDisplay;
import static org.terasology.rendering.opengl.OpenGLUtils.setViewportToSizeOf;
import static org.terasology.rendering.opengl.OpenGLUtils.renderFullscreenQuad;
import static org.terasology.rendering.opengl.OpenGLUtils.setRenderBufferMask;

/**
 * TODO: Diagram of this node
 * TODO: Separate this node into multiple SkyBandNode's
 */
public class SkyBandsNode extends WireframeCapableNode {

    @In
    private WorldRenderer worldRenderer;

    @In
    private FrameBuffersManager frameBuffersManager;

    private RenderingConfig renderingConfig;
    private Material blurShader;
    private FBO sceneOpaque;
    private FBO sceneSkyBand0;
    private Camera playerCamera;

    @Override
    public void initialise() {
        super.initialise();
        renderingConfig = config.getRendering();
        blurShader = worldRenderer.getMaterial("engine:prog.blur");
        playerCamera = worldRenderer.getActiveCamera();
    }

    @Override
    public void process() {
        PerformanceMonitor.startActivity("rendering/skyBands");

        sceneOpaque = frameBuffersManager.getFBO("sceneOpaque");

        setRenderBufferMask(sceneOpaque, true, true, true);
        if (renderingConfig.isInscattering()) {
            sceneSkyBand0 = frameBuffersManager.getFBO("sceneSkyBand0");
            FBO sceneSkyBand1 = frameBuffersManager.getFBO("sceneSkyBand1");

            generateSkyBand(sceneSkyBand0);
            generateSkyBand(sceneSkyBand1);
        }

        sceneOpaque.bind();

        playerCamera.lookThrough();

        PerformanceMonitor.endActivity();
    }

    private void generateSkyBand(FBO skyBand) {
        blurShader.enable();
        blurShader.setFloat("radius", 8.0f, true);
        blurShader.setFloat2("texelSize", 1.0f / skyBand.width(), 1.0f / skyBand.height(), true);

        if (skyBand == sceneSkyBand0) {
            sceneOpaque.bindTexture();
        } else {
            sceneSkyBand0.bindTexture();
        }

        skyBand.bind();
        setRenderBufferMask(skyBand, true, false, false);

        setViewportToSizeOf(skyBand);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // TODO: verify this is necessary

        renderFullscreenQuad();

        bindDisplay();     // TODO: verify this is necessary
        setViewportToSizeOf(sceneOpaque);    // TODO: verify this is necessary
    }
}


text:
+++
Title = "Leena S N"
Twitter = "leenasn"
image = "Leena_S_N.jpg"
type = "speaker"
linktitle = "leena-s-n"
+++

Pragmatic & Passionate Programmer, Lean Thinker, XP Evangelist who hooked into Continuous Delivery. Mother of 2 Lovely Angels.


text:
package org.jbpm.console.ng.ht.client.i18n;

import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.Messages;

/**
 * This uses GWT to provide client side compile time resolving of locales. See:
 * http://code.google.com/docreader/#p=google-web-toolkit-doc-1-5&s=google-web- toolkit-doc-1-5&t=DevGuideInternationalization
 * (for more information).
 *

 * Each method name matches up with a key in Constants.properties (the properties file can still be used on the server). To use
 * this, use GWT.create(Constants.class).
 */
public interface Constants extends Messages {

    Constants INSTANCE = GWT.create(Constants.class);

    String Tasks_List();

    String Grid();

    String New_Task();

    String Personal();

    String Group();

    String Active();

    String All();

    String No_Tasks_Found();

    String Priority();

    String Task();

    String Id();

    String Status();

    String Due_On();

    String Parent();

    String Complete();

    String Release();

    String Claim();

    String Work();

    String Start();

    String Details();

    String Actions();

    String No_Parent();

    String User();

    String Process_Id();

    String Process_Instance_Id();

    String Process_Name();

    String Process_Definition_Id();

    String Process_Instance_Details();

    String No_Comments_For_This_Task();

    String Comment();

    String At();

    String Added_By();

    String Add_Comment();

    String Task_Must_Have_A_Name();

    String Create();

    String Task_Name();

    String Quick_Task();

    String Description();

    String Comments();

    String Filters();

    String Process_Context();

    String Update();

    String Form();

    String Advanced();

    String Basic();

    String Refresh();

    String Tasks_Refreshed();

    String Add_User();

    String Add_Group();

    String Remove_User();

    String Remove_Group();

    String Assignments();

    String Auto_Assign_To_Me();

    String Created_On();

    String Text_Require();

    String UserOrGroup();

    String Forward();

    String Delegate();

    String Potential_Owners();

    String No_Potential_Owners();

    String Add_TypeRole();

    String Type_Role();

    String Parent_Group();

    String Save();

    String Delete();

    String Calendar();

    String Logs();

    String Task_Log();

    String Provide_User_Or_Group();

    String Show_Details();

    String Hide_Details();

    String Task_Admin();

    String Delegate_User();

    String Reminder();

    String Actual_Owner();

    String Reminder_Details();

    String No_Actual_Owner();

    String Loading();

    String DelegationUserInputRequired();

    String DelegationUnable();

    String DelegationSuccessfully();

    String TaskCreatedWithId(String id);

    String High();

    String Medium();

    String Low();

    String Close();

    String Created();

    String Ready();

    String Reserved();

    String InProgress();

    String Suspended();

    String Failed();

    String Error();

    String Exited();

    String Obsolete();

    String Completed();

    String TaskRole();

    String Initiator();

    String Stakeholder();

    String Potential_Owner();

    String Administrator();

    String Task_Form();

    String Task_Form_Name();

    String Task_Form_DeploymentId();

    String New_FilteredList();

    String Administrators();

}


text:
/*
  One night you go for a ride on your motorcycle. At 00:00 you start your engine, and the built-in timer automatically
  begins counting the length of your ride, in minutes. Off you go to explore the neighborhood.

  When you finally decide to head back, you realize there's a chance the bridges on your route home are up, leaving you
  stranded! Unfortunately, you don't have your watch on you and don't know what time it is. All you know thanks to the
  bike's timer is that n minutes have passed since 00:00.

  Using the bike's timer, calculate the current time. Return an answer as the sum of digits that the digital timer in
  the format hh:mm would show.

  Example
    For n = 240, the output should be
      lateRide(n) = 4.
    Since 240 minutes have passed, the current time is 04:00. The digits sum up to 0 + 4 + 0 + 0 = 4, which is the answer.

    For n = 808, the output should be
      lateRide(n) = 14.
    808 minutes mean that it's 13:28 now, so the answer should be 1 + 3 + 2 + 8 = 14.
*/

int lateRide(int n) {
    int h = n / 60;
    int m = n % 60;
    int sum = 0;
    while(h > 0) {
        sum += h % 10;
        h /= 10;
    }
    while(m > 0) {
        sum += m % 10;
        m /= 10;
    }
    return sum;
}


text:
require 'spec_helper'

module PaginationSearch
  describe BaseRelation do
    let(:relation) { Query.select(:id) }
    let(:title_attribute) do
      instance_double(
        'PaginationSearch::AttributeSet::Attribute',
        association_name: :query,
        name: :title,
        column: Arel::Table.new('queries')[:title]
      )
    end
    let(:tags_attribute) do
      instance_double(
        'PaginationSearch::AttributeSet::Attribute',
        association_name: :tags,
        name: :tags,
        column: Arel::Table.new('tags')[:name]
      )
    end
    let(:attribute_set) do
      instance_double(
        'PaginationSearch::AttributeSet',
        foreign_attributes: [tags_attribute],
        text_attributes: [tags_attribute, title_attribute]
      )
    end
    let(:params) { {} }
    let(:base_relation) { PaginationSearch::BaseRelation.new(relation, params, attribute_set) }

    before do
      allow(title_attribute).to receive(:matching_condition).with('test').and_return(
        Arel::Table.new('queries')[:title].matches('test')
      )
      allow(title_attribute).to receive(:matching_condition).with('weee').and_return(
        Arel::Table.new('queries')[:title].matches('weee')
      )
      allow(tags_attribute).to receive(:matching_condition).with('weee').and_return(
        Arel::Table.new('tags')[:name].matches('weee')
      )
      allow(tags_attribute).to receive(:matching_condition).with('test').and_return(
        Arel::Table.new('tags')[:name].matches('test')
      )
      allow(attribute_set).to receive(:[]).with(:title).and_return(title_attribute)
      allow(attribute_set).to receive(:[]).with(:tags).and_return(tags_attribute)
    end

    describe '#process' do
      subject { base_relation.process }

      context 'when the params are empty' do
        it 'produces an ActiveRecord relation which includes ordering by created_at of the base, ascending' do
          expect(subject.arel.orders.length).to eq(1)
          expect(subject.arel.orders.first.class).to eq(Arel::Nodes::Ascending)
          expect(subject.arel.orders.first.expr.name).to eq(:created_at)
        end
      end

      context 'when the params include sort_descending' do
        let(:params) { { sort_descending: true } }

        it 'produces an ActiveRecord relation which includes ordering by created_at of the base, descending' do
          expect(subject.arel.orders.length).to eq(1)
          expect(subject.arel.orders.first.class).to eq(Arel::Nodes::Descending)
          expect(subject.arel.orders.first.expr.name).to eq(:created_at)
        end
      end

      context 'when the params include another sort_by attribute' do
        let(:params) { { sort_by: 'tags' } }

        it 'produces an ActiveRecord relation which selects that attribute as well as the base ids' do
          expect(subject.arel.projections.length).to eq(2)
          select_columns = subject.arel.projections.map(&:name)
          select_tables = subject.arel.projections.map do |projection|
            projection.relation.name
          end
          expect(select_columns).to include(:name, :id)
          expect(select_tables).to include('queries', 'tags')
        end

        it 'produces an ActiveRecord relation which includes ordering by created_at of that attribute, ascending' do
          expect(subject.arel.orders.length).to eq(1)
          expect(subject.arel.orders.first.class).to eq(Arel::Nodes::Ascending)
          expect(subject.arel.orders.first.expr.relation.name).to eq('tags')
          expect(subject.arel.orders.first.expr.name).to eq(:name)
        end
      end

      context 'when the params include a search atribute on a single trait of the base object' do
        let(:params) { { search: 'title:test' } }

        it 'produces an ActiveRecord relation which includes a condition constraining that trait to that term' do
          expect(subject.to_sql).to include("queries\".\"title\" ILIKE 'test'")
        end
      end

      context 'when the params include a search atribute on a single trait of a foreign attribute' do
        let(:params) { { search: 'tags:test' } }

        it 'produces an ActiveRecord relation which includes a condition constraining that trait to that term' do
          expect(subject.to_sql).to include("tags\".\"name\" ILIKE 'test'")
        end

        it 'produces an ActiveRecord relation which left outer joins the foreign table' do
          expect(subject.to_sql).to include("LEFT OUTER JOIN \"tags\"")
        end
      end

      context 'when the params include a search atribute on any trait' do
        let(:params) { { search: 'weee' } }

        it 'produces an ActiveRecord relation which includes a condition constraining any trait to that term' do
          expect(subject.to_sql).to include("tags\".\"name\" ILIKE 'weee'")
          expect(subject.to_sql).to include("queries\".\"title\" ILIKE 'weee'")
        end

        it 'produces an ActiveRecord relation which left outer joins all foreign tables' do
          expect(subject.to_sql).to include("LEFT OUTER JOIN \"tags\"")
        end
      end
    end
  end
end


text:
package shim

import (
	"errors"
	"fmt"
	"sync"

	"github.com/golang/protobuf/proto"
	pb "github.com/hyperledger/fabric/protos/peer"
	"github.com/looplab/fsm"
)

// PeerChaincodeStream interface for stream between Peer and chaincode instance.
type PeerChaincodeStream interface {
	Send(*pb.ChaincodeMessage) error
	Recv() (*pb.ChaincodeMessage, error)
	CloseSend() error
}

type nextStateInfo struct {
	msg      *pb.ChaincodeMessage
	sendToCC bool
}

func (handler *Handler) triggerNextState(msg *pb.ChaincodeMessage, send bool) {
	handler.nextState <- &nextStateInfo{msg, send}
}

// Handler handler implementation for shim side of chaincode.
type Handler struct {
	sync.RWMutex
	//shim to peer grpc serializer. User only in serialSend
	serialLock sync.Mutex
	To         string
	ChatStream PeerChaincodeStream
	FSM        *fsm.FSM
	cc         Chaincode
	// Multiple queries (and one transaction) with different txids can be executing in parallel for this chaincode
	// responseChannel is the channel on which responses are communicated by the shim to the chaincodeStub.
	responseChannel map[string]chan pb.ChaincodeMessage
	nextState       chan *nextStateInfo
}

func shorttxid(txid string) string {
	if len(txid) < 8 {
		return txid
	}
	return txid[0:8]
}

//serialSend serializes msgs so gRPC will be happy
func (handler *Handler) serialSend(msg *pb.ChaincodeMessage) error {
	handler.serialLock.Lock()
	defer handler.serialLock.Unlock()

	err := handler.ChatStream.Send(msg)

	return err
}

//serialSendAsync serves the same purpose as serialSend (serialize msgs so gRPC will
//be happy). In addition, it is also asynchronous so send-remoterecv--localrecv loop
//can be nonblocking. Only errors need to be handled and these are handled by
//communication on supplied error channel. A typical use will be a non-blocking or
//nil channel
func (handler *Handler) serialSendAsync(msg *pb.ChaincodeMessage, errc chan error) {
	go func() {
		err := handler.serialSend(msg)
		if errc != nil {
			errc <- err
		}
	}()
}

func (handler *Handler) createChannel(txid string) (chan pb.ChaincodeMessage, error) {
	handler.Lock()
	defer handler.Unlock()
	if handler.responseChannel == nil {
		return nil, fmt.Errorf("[%s]Cannot create response channel", shorttxid(txid))
	}
	if handler.responseChannel[txid] != nil {
		return nil, fmt.Errorf("[%s]Channel exists", shorttxid(txid))
	}
	c := make(chan pb.ChaincodeMessage)
	handler.responseChannel[txid] = c
	return c, nil
}

func (handler *Handler) sendChannel(msg *pb.ChaincodeMessage) error {
	handler.Lock()
	defer handler.Unlock()
	if handler.responseChannel == nil {
		return fmt.Errorf("[%s]Cannot send message response channel", shorttxid(msg.Txid))
	}
	if handler.responseChannel[msg.Txid] == nil {
		return fmt.Errorf("[%s]sendChannel does not exist", shorttxid(msg.Txid))
	}

	chaincodeLogger.Debugf("[%s]before send", shorttxid(msg.Txid))
	handler.responseChannel[msg.Txid] <- *msg
	chaincodeLogger.Debugf("[%s]after send", shorttxid(msg.Txid))

	return nil
}

//sends a message and selects
func (handler *Handler) sendReceive(msg *pb.ChaincodeMessage, c chan pb.ChaincodeMessage) (pb.ChaincodeMessage, error) {
	errc := make(chan error, 1)
	handler.serialSendAsync(msg, errc)

	//the serialsend above will send an err or nil
	//the select filters that first error(or nil)
	//and continues to wait for the response
	//it is possible that the response triggers first
	//in which case the errc obviously worked and is
	//ignored
	for {
		select {
		case err := <-errc:
			if err == nil {
				continue
			}
			//would have been logged, return false
			return pb.ChaincodeMessage{}, err
		case outmsg, val := <-c:
			if !val {
				return pb.ChaincodeMessage{}, fmt.Errorf("unexpected failure on receive")
			}
			return outmsg, nil
		}
	}
}

func (handler *Handler) deleteChannel(txid string) {
	handler.Lock()
	defer handler.Unlock()
	if handler.responseChannel != nil {
		delete(handler.responseChannel, txid)
	}
}

// NewChaincodeHandler returns a new instance of the shim side handler.
func newChaincodeHandler(peerChatStream PeerChaincodeStream, chaincode Chaincode) *Handler {
	v := &Handler{
		ChatStream: peerChatStream,
		cc:         chaincode,
	}
	v.responseChannel = make(map[string]chan pb.ChaincodeMessage)
	v.nextState = make(chan *nextStateInfo)

	// Create the shim side FSM
	v.FSM = fsm.NewFSM(
		"created",
		fsm.Events{
			{Name: pb.ChaincodeMessage_REGISTERED.String(), Src: []string{"created"}, Dst: "established"},
			{Name: pb.ChaincodeMessage_READY.String(), Src: []string{"established"}, Dst: "ready"},
			{Name: pb.ChaincodeMessage_ERROR.String(), Src: []string{"init"}, Dst: "established"},
			{Name: pb.ChaincodeMessage_RESPONSE.String(), Src: []string{"init"}, Dst: "init"},
			{Name: pb.ChaincodeMessage_INIT.String(), Src: []string{"ready"}, Dst: "ready"},
			{Name: pb.ChaincodeMessage_TRANSACTION.String(), Src: []string{"ready"}, Dst: "ready"},
			{Name: pb.ChaincodeMessage_RESPONSE.String(), Src: []string{"ready"}, Dst: "ready"},
			{Name: pb.ChaincodeMessage_ERROR.String(), Src: []string{"ready"}, Dst: "ready"},
			{Name: pb.ChaincodeMessage_COMPLETED.String(), Src: []string{"init"}, Dst: "ready"},
			{Name: pb.ChaincodeMessage_COMPLETED.String(), Src: []string{"ready"}, Dst: "ready"},
		},
		fsm.Callbacks{
			"before_" + pb.ChaincodeMessage_REGISTERED.String():  func(e *fsm.Event) { v.beforeRegistered(e) },
			"after_" + pb.ChaincodeMessage_RESPONSE.String():     func(e *fsm.Event) { v.afterResponse(e) },
			"after_" + pb.ChaincodeMessage_ERROR.String():        func(e *fsm.Event) { v.afterError(e) },
			"before_" + pb.ChaincodeMessage_INIT.String():        func(e *fsm.Event) { v.beforeInit(e) },
			"before_" + pb.ChaincodeMessage_TRANSACTION.String(): func(e *fsm.Event) { v.beforeTransaction(e) },
		},
	)
	return v
}

// beforeRegistered is called to handle the REGISTERED message.
func (handler *Handler) beforeRegistered(e *fsm.Event) {
	if _, ok := e.Args[0].(*pb.ChaincodeMessage); !ok {
		e.Cancel(fmt.Errorf("Received unexpected message type"))
		return
	}
	chaincodeLogger.Debugf("Received %s, ready for invocations", pb.ChaincodeMessage_REGISTERED)
}

// handleInit handles request to initialize chaincode.
func (handler *Handler) handleInit(msg *pb.ChaincodeMessage) {
	// The defer followed by triggering a go routine dance is needed to ensure that the previous state transition
	// is completed before the next one is triggered. The previous state transition is deemed complete only when
	// the beforeInit function is exited. Interesting bug fix!!
	go func() {
		var nextStateMsg *pb.ChaincodeMessage

		send := true

		defer func() {
			handler.triggerNextState(nextStateMsg, send)
		}()

		errFunc := func(err error, payload []byte, ce *pb.ChaincodeEvent, errFmt string, args ...string) *pb.ChaincodeMessage {
			if err != nil {
				// Send ERROR message to chaincode support and change state
				if payload == nil {
					payload = []byte(err.Error())
				}
				chaincodeLogger.Errorf(errFmt, args)
				return &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: payload, Txid: msg.Txid, ChaincodeEvent: ce}
			}
			return nil
		}
		// Get the function and args from Payload
		input := &pb.ChaincodeInput{}
		unmarshalErr := proto.Unmarshal(msg.Payload, input)
		if nextStateMsg = errFunc(unmarshalErr, nil, nil, "[%s]Incorrect payload format. Sending %s", shorttxid(msg.Txid), pb.ChaincodeMessage_ERROR.String()); nextStateMsg != nil {
			return
		}

		// Call chaincode's Run
		// Create the ChaincodeStub which the chaincode can use to callback
		stub := new(ChaincodeStub)
		err := stub.init(handler, msg.Txid, input, msg.Proposal)
		if nextStateMsg = errFunc(err, nil, stub.chaincodeEvent, "[%s]Init get error response [%s]. Sending %s", shorttxid(msg.Txid), pb.ChaincodeMessage_ERROR.String()); nextStateMsg != nil {
			return
		}

		res := handler.cc.Init(stub)
		chaincodeLogger.Debugf("[%s]Init get response status: %d", shorttxid(msg.Txid), res.Status)

		if res.Status >= ERROR {
			err = fmt.Errorf("%s", res.Message)
			if nextStateMsg = errFunc(err, []byte(res.Message), stub.chaincodeEvent, "[%s]Init get error response [%s]. Sending %s", shorttxid(msg.Txid), pb.ChaincodeMessage_ERROR.String()); nextStateMsg != nil {
				return
			}
		}

		resBytes, err := proto.Marshal(&res)
		if nextStateMsg = errFunc(err, nil, stub.chaincodeEvent, "[%s]Init marshal response error [%s]. Sending %s", shorttxid(msg.Txid), pb.ChaincodeMessage_ERROR.String()); nextStateMsg != nil {
			return
		}

		// Send COMPLETED message to chaincode support and change state
		nextStateMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_COMPLETED, Payload: resBytes, Txid: msg.Txid, ChaincodeEvent: stub.chaincodeEvent}
		chaincodeLogger.Debugf("[%s]Init succeeded. Sending %s", shorttxid(msg.Txid), pb.ChaincodeMessage_COMPLETED)
	}()
}

// beforeInit will initialize the chaincode if entering init from established.
func (handler *Handler) beforeInit(e *fsm.Event) {
	chaincodeLogger.Debugf("Entered state %s", handler.FSM.Current())
	msg, ok := e.Args[0].(*pb.ChaincodeMessage)
	if !ok {
		e.Cancel(fmt.Errorf("Received unexpected message type"))
		return
	}
	chaincodeLogger.Debugf("[%s]Received %s, initializing chaincode", shorttxid(msg.Txid), msg.Type.String())
	if msg.Type.String() == pb.ChaincodeMessage_INIT.String() {
		// Call the chaincode's Run function to initialize
		handler.handleInit(msg)
	}
}

// handleTransaction Handles request to execute a transaction.
func (handler *Handler) handleTransaction(msg *pb.ChaincodeMessage) {
	// The defer followed by triggering a go routine dance is needed to ensure that the previous state transition
	// is completed before the next one is triggered. The previous state transition is deemed complete only when
	// the beforeInit function is exited. Interesting bug fix!!
	go func() {
		//better not be nil
		var nextStateMsg *pb.ChaincodeMessage

		send := true

		defer func() {
			handler.triggerNextState(nextStateMsg, send)
		}()

		errFunc := func(err error, ce *pb.ChaincodeEvent, errStr string, args ...string) *pb.ChaincodeMessage {
			if err != nil {
				payload := []byte(err.Error())
				chaincodeLogger.Errorf(errStr, args)
				return &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: payload, Txid: msg.Txid, ChaincodeEvent: ce}
			}
			return nil
		}

		// Get the function and args from Payload
		input := &pb.ChaincodeInput{}
		unmarshalErr := proto.Unmarshal(msg.Payload, input)
		if nextStateMsg = errFunc(unmarshalErr, nil, "[%s]Incorrect payload format. Sending %s", shorttxid(msg.Txid), pb.ChaincodeMessage_ERROR.String()); nextStateMsg != nil {
			return
		}

		// Call chaincode's Run
		// Create the ChaincodeStub which the chaincode can use to callback
		stub := new(ChaincodeStub)
		err := stub.init(handler, msg.Txid, input, msg.Proposal)
		if nextStateMsg = errFunc(err, stub.chaincodeEvent, "[%s]Transaction execution failed. Sending %s", shorttxid(msg.Txid), pb.ChaincodeMessage_ERROR.String()); nextStateMsg != nil {
			return
		}

		res := handler.cc.Invoke(stub)

		// Endorser will handle error contained in Response.
		resBytes, err := proto.Marshal(&res)
		if nextStateMsg = errFunc(err, stub.chaincodeEvent, "[%s]Transaction execution failed. Sending %s", shorttxid(msg.Txid), pb.ChaincodeMessage_ERROR.String()); nextStateMsg != nil {
			return
		}

		// Send COMPLETED message to chaincode support and change state
		chaincodeLogger.Debugf("[%s]Transaction completed. Sending %s", shorttxid(msg.Txid), pb.ChaincodeMessage_COMPLETED)
		nextStateMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_COMPLETED, Payload: resBytes, Txid: msg.Txid, ChaincodeEvent: stub.chaincodeEvent}
	}()
}

// beforeTransaction will execute chaincode's Run if coming from a TRANSACTION event.
func (handler *Handler) beforeTransaction(e *fsm.Event) {
	msg, ok := e.Args[0].(*pb.ChaincodeMessage)
	if !ok {
		e.Cancel(fmt.Errorf("Received unexpected message type"))
		return
	}
	chaincodeLogger.Debugf("[%s]Received %s, invoking transaction on chaincode(Src:%s, Dst:%s)", shorttxid(msg.Txid), msg.Type.String(), e.Src, e.Dst)
	if msg.Type.String() == pb.ChaincodeMessage_TRANSACTION.String() {
		// Call the chaincode's Run function to invoke transaction
		handler.handleTransaction(msg)
	}
}

// afterResponse is called to deliver a response or error to the chaincode stub.
func (handler *Handler) afterResponse(e *fsm.Event) {
	msg, ok := e.Args[0].(*pb.ChaincodeMessage)
	if !ok {
		e.Cancel(fmt.Errorf("Received unexpected message type"))
		return
	}

	if err := handler.sendChannel(msg); err != nil {
		chaincodeLogger.Errorf("[%s]error sending %s (state:%s): %s", shorttxid(msg.Txid), msg.Type, handler.FSM.Current(), err)
	} else {
		chaincodeLogger.Debugf("[%s]Received %s, communicated (state:%s)", shorttxid(msg.Txid), msg.Type, handler.FSM.Current())
	}
}

func (handler *Handler) afterError(e *fsm.Event) {
	msg, ok := e.Args[0].(*pb.ChaincodeMessage)
	if !ok {
		e.Cancel(fmt.Errorf("Received unexpected message type"))
		return
	}

	/* TODO- revisit. This may no longer be needed with the serialized/streamlined messaging model
	 * There are two situations in which the ERROR event can be triggered:
	 * 1. When an error is encountered within handleInit or handleTransaction - some issue at the chaincode side; In this case there will be no responseChannel and the message has been sent to the validator.
	 * 2. The chaincode has initiated a request (get/put/del state) to the validator and is expecting a response on the responseChannel; If ERROR is received from validator, this needs to be notified on the responseChannel.
	 */
	if err := handler.sendChannel(msg); err == nil {
		chaincodeLogger.Debugf("[%s]Error received from validator %s, communicated(state:%s)", shorttxid(msg.Txid), msg.Type, handler.FSM.Current())
	}
}

// TODO: Implement method to get and put entire state map and not one key at a time?
// handleGetState communicates with the validator to fetch the requested state information from the ledger.
func (handler *Handler) handleGetState(key string, txid string) ([]byte, error) {
	// Create the channel on which to communicate the response from validating peer
	var respChan chan pb.ChaincodeMessage
	var err error
	if respChan, err = handler.createChannel(txid); err != nil {
		return nil, err
	}

	defer handler.deleteChannel(txid)

	// Send GET_STATE message to validator chaincode support
	payload := []byte(key)
	msg := &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_GET_STATE, Payload: payload, Txid: txid}
	chaincodeLogger.Debugf("[%s]Sending %s", shorttxid(msg.Txid), pb.ChaincodeMessage_GET_STATE)

	var responseMsg pb.ChaincodeMessage

	if responseMsg, err = handler.sendReceive(msg, respChan); err != nil {
		return nil, errors.New(fmt.Sprintf("[%s]error sending GET_STATE %s", shorttxid(txid), err))
	}

	if responseMsg.Type.String() == pb.ChaincodeMessage_RESPONSE.String() {
		// Success response
		chaincodeLogger.Debugf("[%s]GetState received payload %s", shorttxid(responseMsg.Txid), pb.ChaincodeMessage_RESPONSE)
		return responseMsg.Payload, nil
	}
	if responseMsg.Type.String() == pb.ChaincodeMessage_ERROR.String() {
		// Error response
		chaincodeLogger.Errorf("[%s]GetState received error %s", shorttxid(responseMsg.Txid), pb.ChaincodeMessage_ERROR)
		return nil, errors.New(string(responseMsg.Payload[:]))
	}

	// Incorrect chaincode message received
	return nil, errors.New(fmt.Sprintf("[%s]Incorrect chaincode message %s received. Expecting %s or %s", shorttxid(responseMsg.Txid), responseMsg.Type, pb.ChaincodeMessage_RESPONSE, pb.ChaincodeMessage_ERROR))
}

// handlePutState communicates with the validator to put state information into the ledger.
func (handler *Handler) handlePutState(key string, value []byte, txid string) error {
	// Check if this is a transaction
	chaincodeLogger.Debugf("[%s]Inside putstate", shorttxid(txid))

	//we constructed a valid object. No need to check for error
	payloadBytes, _ := proto.Marshal(&pb.PutStateInfo{Key: key, Value: value})

	// Create the channel on which to communicate the response from validating peer
	var respChan chan pb.ChaincodeMessage
	var err error
	if respChan, err = handler.createChannel(txid); err != nil {
		return err
	}

	defer handler.deleteChannel(txid)

	// Send PUT_STATE message to validator chaincode support
	msg := &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_PUT_STATE, Payload: payloadBytes, Txid: txid}
	chaincodeLogger.Debugf("[%s]Sending %s", shorttxid(msg.Txid), pb.ChaincodeMessage_PUT_STATE)

	var responseMsg pb.ChaincodeMessage

	if responseMsg, err = handler.sendReceive(msg, respChan); err != nil {
		return errors.New(fmt.Sprintf("[%s]error sending PUT_STATE %s", msg.Txid, err))
	}

	if responseMsg.Type.String() == pb.ChaincodeMessage_RESPONSE.String() {
		// Success response
		chaincodeLogger.Debugf("[%s]Received %s. Successfully updated state", shorttxid(responseMsg.Txid), pb.ChaincodeMessage_RESPONSE)
		return nil
	}

	if responseMsg.Type.String() == pb.ChaincodeMessage_ERROR.String() {
		// Error response
		chaincodeLogger.Errorf("[%s]Received %s. Payload: %s", shorttxid(responseMsg.Txid), pb.ChaincodeMessage_ERROR, responseMsg.Payload)
		return errors.New(string(responseMsg.Payload[:]))
	}

	// Incorrect chaincode message received
	return errors.New(fmt.Sprintf("[%s]Incorrect chaincode message %s received. Expecting %s or %s", shorttxid(responseMsg.Txid), responseMsg.Type, pb.ChaincodeMessage_RESPONSE, pb.ChaincodeMessage_ERROR))
}

// handleDelState communicates with the validator to delete a key from the state in the ledger.
func (handler *Handler) handleDelState(key string, txid string) error {
	// Create the channel on which to communicate the response from validating peer
	var respChan chan pb.ChaincodeMessage
	var err error
	if respChan, err = handler.createChannel(txid); err != nil {
		return err
	}

	defer handler.deleteChannel(txid)

	// Send DEL_STATE message to validator chaincode support
	payload := []byte(key)
	msg := &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_DEL_STATE, Payload: payload, Txid: txid}
	chaincodeLogger.Debugf("[%s]Sending %s", shorttxid(msg.Txid), pb.ChaincodeMessage_DEL_STATE)

	var responseMsg pb.ChaincodeMessage

	if responseMsg, err = handler.sendReceive(msg, respChan); err != nil {
		return errors.New(fmt.Sprintf("[%s]error sending DEL_STATE %s", shorttxid(msg.Txid), pb.ChaincodeMessage_DEL_STATE))
	}

	if responseMsg.Type.String() == pb.ChaincodeMessage_RESPONSE.String() {
		// Success response
		chaincodeLogger.Debugf("[%s]Received %s. Successfully deleted state", msg.Txid, pb.ChaincodeMessage_RESPONSE)
		return nil
	}
	if responseMsg.Type.String() == pb.ChaincodeMessage_ERROR.String() {
		// Error response
		chaincodeLogger.Errorf("[%s]Received %s. Payload: %s", msg.Txid, pb.ChaincodeMessage_ERROR, responseMsg.Payload)
		return errors.New(string(responseMsg.Payload[:]))
	}

	// Incorrect chaincode message received
	return errors.New(fmt.Sprintf("[%s]Incorrect chaincode message %s received. Expecting %s or %s", shorttxid(responseMsg.Txid), responseMsg.Type, pb.ChaincodeMessage_RESPONSE, pb.ChaincodeMessage_ERROR))
}

func (handler *Handler) handleGetStateByRange(startKey, endKey string, txid string) (*pb.QueryResponse, error) {
	// Create the channel on which to communicate the response from validating peer
	var respChan chan pb.ChaincodeMessage
	var err error
	if respChan, err = handler.createChannel(txid); err != nil {
		return nil, err
	}

	defer handler.deleteChannel(txid)

	// Send GET_STATE_BY_RANGE message to validator chaincode support
	//we constructed a valid object. No need to check for error
	payloadBytes, _ := proto.Marshal(&pb.GetStateByRange{StartKey: startKey, EndKey: endKey})

	msg := &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_GET_STATE_BY_RANGE, Payload: payloadBytes, Txid: txid}
	chaincodeLogger.Debugf("[%s]Sending %s", shorttxid(msg.Txid), pb.ChaincodeMessage_GET_STATE_BY_RANGE)

	var responseMsg pb.ChaincodeMessage
	if responseMsg, err = handler.sendReceive(msg, respChan); err != nil {
		return nil, errors.New(fmt.Sprintf("[%s]error sending %s", shorttxid(msg.Txid), pb.ChaincodeMessage_GET_STATE_BY_RANGE))
	}

	if responseMsg.Type.String() == pb.ChaincodeMessage_RESPONSE.String() {
		// Success response
		chaincodeLogger.Debugf("[%s]Received %s. Successfully got range", shorttxid(responseMsg.Txid), pb.ChaincodeMessage_RESPONSE)

		rangeQueryResponse := &pb.QueryResponse{}
		if err = proto.Unmarshal(responseMsg.Payload, rangeQueryResponse); err != nil {
			return nil, errors.New(fmt.Sprintf("[%s]GetStateByRangeResponse unmarshall error", shorttxid(responseMsg.Txid)))
		}

		return rangeQueryResponse, nil
	}
	if responseMsg.Type.String() == pb.ChaincodeMessage_ERROR.String() {
		// Error response
		chaincodeLogger.Errorf("[%s]Received %s", shorttxid(responseMsg.Txid), pb.ChaincodeMessage_ERROR)
		return nil, errors.New(string(responseMsg.Payload[:]))
	}

	// Incorrect chaincode message received
	return nil, errors.New(fmt.Sprintf("Incorrect chaincode message %s received. Expecting %s or %s", responseMsg.Type, pb.ChaincodeMessage_RESPONSE, pb.ChaincodeMessage_ERROR))
}

func (handler *Handler) handleQueryStateNext(id, txid string) (*pb.QueryResponse, error) {
	// Create the channel on which to communicate the response from validating peer
	var respChan chan pb.ChaincodeMessage
	var err error
	if respChan, err = handler.createChannel(txid); err != nil {
		return nil, err
	}

	defer handler.deleteChannel(txid)

	// Send QUERY_STATE_NEXT message to validator chaincode support
	//we constructed a valid object. No need to check for error
	payloadBytes, _ := proto.Marshal(&pb.QueryStateNext{Id: id})

	msg := &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_QUERY_STATE_NEXT, Payload: payloadBytes, Txid: txid}
	chaincodeLogger.Debugf("[%s]Sending %s", shorttxid(msg.Txid), pb.ChaincodeMessage_QUERY_STATE_NEXT)

	var responseMsg pb.ChaincodeMessage

	if responseMsg, err = handler.sendReceive(msg, respChan); err != nil {
		return nil, errors.New(fmt.Sprintf("[%s]error sending %s", shorttxid(msg.Txid), pb.ChaincodeMessage_QUERY_STATE_NEXT))
	}

	if responseMsg.Type.String() == pb.ChaincodeMessage_RESPONSE.String() {
		// Success response
		chaincodeLogger.Debugf("[%s]Received %s. Successfully got range", shorttxid(responseMsg.Txid), pb.ChaincodeMessage_RESPONSE)

		queryResponse := &pb.QueryResponse{}
		if err = proto.Unmarshal(responseMsg.Payload, queryResponse); err != nil {
			return nil, errors.New(fmt.Sprintf("[%s]unmarshall error", shorttxid(responseMsg.Txid)))
		}

		return queryResponse, nil
	}
	if responseMsg.Type.String() == pb.ChaincodeMessage_ERROR.String() {
		// Error response
		chaincodeLogger.Errorf("[%s]Received %s", shorttxid(responseMsg.Txid), pb.ChaincodeMessage_ERROR)
		return nil, errors.New(string(responseMsg.Payload[:]))
	}

	// Incorrect chaincode message received
	return nil, errors.New(fmt.Sprintf("Incorrect chaincode message %s received. Expecting %s or %s", responseMsg.Type, pb.ChaincodeMessage_RESPONSE, pb.ChaincodeMessage_ERROR))
}

func (handler *Handler) handleQueryStateClose(id, txid string) (*pb.QueryResponse, error) {
	// Create the channel on which to communicate the response from validating peer
	var respChan chan pb.ChaincodeMessage
	var err error
	if respChan, err = handler.createChannel(txid); err != nil {
		return nil, err
	}

	defer handler.deleteChannel(txid)

	// Send QUERY_STATE_CLOSE message to validator chaincode support
	//we constructed a valid object. No need to check for error
	payloadBytes, _ := proto.Marshal(&pb.QueryStateClose{Id: id})

	msg := &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_QUERY_STATE_CLOSE, Payload: payloadBytes, Txid: txid}
	chaincodeLogger.Debugf("[%s]Sending %s", shorttxid(msg.Txid), pb.ChaincodeMessage_QUERY_STATE_CLOSE)

	var responseMsg pb.ChaincodeMessage

	if responseMsg, err = handler.sendReceive(msg, respChan); err != nil {
		return nil, errors.New(fmt.Sprintf("[%s]error sending %s", shorttxid(msg.Txid), pb.ChaincodeMessage_QUERY_STATE_CLOSE))
	}

	if responseMsg.Type.String() == pb.ChaincodeMessage_RESPONSE.String() {
		// Success response
		chaincodeLogger.Debugf("[%s]Received %s. Successfully got range", shorttxid(responseMsg.Txid), pb.ChaincodeMessage_RESPONSE)

		queryResponse := &pb.QueryResponse{}
		if err = proto.Unmarshal(responseMsg.Payload, queryResponse); err != nil {
			return nil, errors.New(fmt.Sprintf("[%s]unmarshall error", shorttxid(responseMsg.Txid)))
		}

		return queryResponse, nil
	}
	if responseMsg.Type.String() == pb.ChaincodeMessage_ERROR.String() {
		// Error response
		chaincodeLogger.Errorf("[%s]Received %s", shorttxid(responseMsg.Txid), pb.ChaincodeMessage_ERROR)
		return nil, errors.New(string(responseMsg.Payload[:]))
	}

	// Incorrect chaincode message received
	return nil, errors.New(fmt.Sprintf("Incorrect chaincode message %s received. Expecting %s or %s", responseMsg.Type, pb.ChaincodeMessage_RESPONSE, pb.ChaincodeMessage_ERROR))
}

func (handler *Handler) handleGetQueryResult(query string, txid string) (*pb.QueryResponse, error) {
	// Create the channel on which to communicate the response from validating peer
	var respChan chan pb.ChaincodeMessage
	var err error
	if respChan, err = handler.createChannel(txid); err != nil {
		return nil, err
	}

	defer handler.deleteChannel(txid)

	// Send GET_QUERY_RESULT message to validator chaincode support
	//we constructed a valid object. No need to check for error
	payloadBytes, _ := proto.Marshal(&pb.GetQueryResult{Query: query})

	msg := &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_GET_QUERY_RESULT, Payload: payloadBytes, Txid: txid}
	chaincodeLogger.Debugf("[%s]Sending %s", shorttxid(msg.Txid), pb.ChaincodeMessage_GET_QUERY_RESULT)

	var responseMsg pb.ChaincodeMessage

	if responseMsg, err = handler.sendReceive(msg, respChan); err != nil {
		return nil, errors.New(fmt.Sprintf("[%s]error sending %s", shorttxid(msg.Txid), pb.ChaincodeMessage_GET_QUERY_RESULT))
	}

	if responseMsg.Type.String() == pb.ChaincodeMessage_RESPONSE.String() {
		// Success response
		chaincodeLogger.Debugf("[%s]Received %s. Successfully got range", shorttxid(responseMsg.Txid), pb.ChaincodeMessage_RESPONSE)

		executeQueryResponse := &pb.QueryResponse{}
		if err = proto.Unmarshal(responseMsg.Payload, executeQueryResponse); err != nil {
			return nil, errors.New(fmt.Sprintf("[%s]unmarshall error", shorttxid(responseMsg.Txid)))
		}

		return executeQueryResponse, nil
	}
	if responseMsg.Type.String() == pb.ChaincodeMessage_ERROR.String() {
		// Error response
		chaincodeLogger.Errorf("[%s]Received %s", shorttxid(responseMsg.Txid), pb.ChaincodeMessage_ERROR)
		return nil, errors.New(string(responseMsg.Payload[:]))
	}

	// Incorrect chaincode message received
	return nil, errors.New(fmt.Sprintf("Incorrect chaincode message %s received. Expecting %s or %s", responseMsg.Type, pb.ChaincodeMessage_RESPONSE, pb.ChaincodeMessage_ERROR))
}

func (handler *Handler) handleGetHistoryForKey(key string, txid string) (*pb.QueryResponse, error) {
	// Create the channel on which to communicate the response from validating peer
	var respChan chan pb.ChaincodeMessage
	var err error
	if respChan, err = handler.createChannel(txid); err != nil {
		return nil, err
	}

	defer handler.deleteChannel(txid)

	// Send GET_HISTORY_FOR_KEY message to validator chaincode support
	//we constructed a valid object. No need to check for error
	payloadBytes, _ := proto.Marshal(&pb.GetHistoryForKey{Key: key})

	msg := &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_GET_HISTORY_FOR_KEY, Payload: payloadBytes, Txid: txid}
	chaincodeLogger.Debugf("[%s]Sending %s", shorttxid(msg.Txid), pb.ChaincodeMessage_GET_HISTORY_FOR_KEY)

	var responseMsg pb.ChaincodeMessage

	if responseMsg, err = handler.sendReceive(msg, respChan); err != nil {
		return nil, errors.New(fmt.Sprintf("[%s]error sending %s", shorttxid(msg.Txid), pb.ChaincodeMessage_GET_HISTORY_FOR_KEY))
	}

	if responseMsg.Type.String() == pb.ChaincodeMessage_RESPONSE.String() {
		// Success response
		chaincodeLogger.Debugf("[%s]Received %s. Successfully got range", shorttxid(responseMsg.Txid), pb.ChaincodeMessage_RESPONSE)

		getHistoryForKeyResponse := &pb.QueryResponse{}
		if err = proto.Unmarshal(responseMsg.Payload, getHistoryForKeyResponse); err != nil {
			return nil, errors.New(fmt.Sprintf("[%s]unmarshall error", shorttxid(responseMsg.Txid)))
		}

		return getHistoryForKeyResponse, nil
	}
	if responseMsg.Type.String() == pb.ChaincodeMessage_ERROR.String() {
		// Error response
		chaincodeLogger.Errorf("[%s]Received %s", shorttxid(responseMsg.Txid), pb.ChaincodeMessage_ERROR)
		return nil, errors.New(string(responseMsg.Payload[:]))
	}

	// Incorrect chaincode message received
	return nil, errors.New(fmt.Sprintf("Incorrect chaincode message %s received. Expecting %s or %s", responseMsg.Type, pb.ChaincodeMessage_RESPONSE, pb.ChaincodeMessage_ERROR))
}

func (handler *Handler) createResponse(status int32, payload []byte) pb.Response {
	return pb.Response{Status: status, Payload: payload}
}

// handleInvokeChaincode communicates with the validator to invoke another chaincode.
func (handler *Handler) handleInvokeChaincode(chaincodeName string, args [][]byte, txid string) pb.Response {
	//we constructed a valid object. No need to check for error
	payloadBytes, _ := proto.Marshal(&pb.ChaincodeSpec{ChaincodeId: &pb.ChaincodeID{Name: chaincodeName}, Input: &pb.ChaincodeInput{Args: args}})

	// Create the channel on which to communicate the response from validating peer
	var respChan chan pb.ChaincodeMessage
	var err error
	if respChan, err = handler.createChannel(txid); err != nil {
		return handler.createResponse(ERROR, []byte(err.Error()))
	}

	defer handler.deleteChannel(txid)

	// Send INVOKE_CHAINCODE message to validator chaincode support
	msg := &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_INVOKE_CHAINCODE, Payload: payloadBytes, Txid: txid}
	chaincodeLogger.Debugf("[%s]Sending %s", shorttxid(msg.Txid), pb.ChaincodeMessage_INVOKE_CHAINCODE)

	var responseMsg pb.ChaincodeMessage

	if responseMsg, err = handler.sendReceive(msg, respChan); err != nil {
		return handler.createResponse(ERROR, []byte(fmt.Sprintf("[%s]error sending %s", shorttxid(msg.Txid), pb.ChaincodeMessage_INVOKE_CHAINCODE)))
	}

	if responseMsg.Type.String() == pb.ChaincodeMessage_RESPONSE.String() {
		// Success response
		chaincodeLogger.Debugf("[%s]Received %s. Successfully invoked chaincode", shorttxid(responseMsg.Txid), pb.ChaincodeMessage_RESPONSE)
		respMsg := &pb.ChaincodeMessage{}
		if err = proto.Unmarshal(responseMsg.Payload, respMsg); err != nil {
			return handler.createResponse(ERROR, []byte(err.Error()))
		}
		if respMsg.Type == pb.ChaincodeMessage_COMPLETED {
			// Success response
			chaincodeLogger.Debugf("[%s]Received %s. Successfully invoked chaincode", shorttxid(responseMsg.Txid), pb.ChaincodeMessage_RESPONSE)
			res := &pb.Response{}
			if err = proto.Unmarshal(respMsg.Payload, res); err != nil {
				return handler.createResponse(ERROR, []byte(err.Error()))
			}
			return *res
		}
		chaincodeLogger.Errorf("[%s]Received %s. Error from chaincode", shorttxid(responseMsg.Txid), respMsg.Type.String())
		return handler.createResponse(ERROR, responseMsg.Payload)
	}
	if responseMsg.Type.String() == pb.ChaincodeMessage_ERROR.String() {
		// Error response
		chaincodeLogger.Errorf("[%s]Received %s.", shorttxid(responseMsg.Txid), pb.ChaincodeMessage_ERROR)
		return handler.createResponse(ERROR, responseMsg.Payload)
	}

	// Incorrect chaincode message received
	return handler.createResponse(ERROR, []byte(fmt.Sprintf("[%s]Incorrect chaincode message %s received. Expecting %s or %s", shorttxid(responseMsg.Txid), responseMsg.Type, pb.ChaincodeMessage_RESPONSE, pb.ChaincodeMessage_ERROR)))
}

// handleMessage message handles loop for shim side of chaincode/validator stream.
func (handler *Handler) handleMessage(msg *pb.ChaincodeMessage) error {
	if msg.Type == pb.ChaincodeMessage_KEEPALIVE {
		// Received a keep alive message, we don't do anything with it for now
		// and it does not touch the state machine
		return nil
	}
	chaincodeLogger.Debugf("[%s]Handling ChaincodeMessage of type: %s(state:%s)", shorttxid(msg.Txid), msg.Type, handler.FSM.Current())
	if handler.FSM.Cannot(msg.Type.String()) {
		err := errors.New(fmt.Sprintf("[%s]Chaincode handler FSM cannot handle message (%s) with payload size (%d) while in state: %s", msg.Txid, msg.Type.String(), len(msg.Payload), handler.FSM.Current()))
		handler.serialSend(&pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: []byte(err.Error()), Txid: msg.Txid})
		return err
	}
	err := handler.FSM.Event(msg.Type.String(), msg)
	return filterError(err)
}

// filterError filters the errors to allow NoTransitionError and CanceledError to not propagate for cases where embedded Err == nil.
func filterError(errFromFSMEvent error) error {
	if errFromFSMEvent != nil {
		if noTransitionErr, ok := errFromFSMEvent.(*fsm.NoTransitionError); ok {
			if noTransitionErr.Err != nil {
				// Only allow NoTransitionError's, all others are considered true error.
				return errFromFSMEvent
			}
		}
		if canceledErr, ok := errFromFSMEvent.(*fsm.CanceledError); ok {
			if canceledErr.Err != nil {
				// Only allow NoTransitionError's, all others are considered true error.
				return canceledErr
				//t.Error("expected only 'NoTransitionError'")
			}
			chaincodeLogger.Debugf("Ignoring CanceledError: %s", canceledErr)
		}
	}
	return nil
}


text:
<?php

namespace org\codeangel\security\passwords;

class DefaultPasswordGenerator extends BlowFishCryptPasswordGenerator {}


text:
@call make_jar.bat
@call run.bat


text:
package com.azure.communication.callautomation;

import com.azure.communication.callautomation.models.CallingServerErrorException;
import com.azure.communication.callautomation.models.RecordingChannel;
import com.azure.communication.callautomation.models.RecordingContent;
import com.azure.communication.callautomation.models.RecordingFormat;
import com.azure.communication.callautomation.models.RecordingState;
import com.azure.communication.callautomation.models.RecordingStateResult;
import com.azure.communication.callautomation.models.ServerCallLocator;
import com.azure.communication.callautomation.models.StartRecordingOptions;
import com.azure.communication.common.CommunicationIdentifier;
import com.azure.communication.common.CommunicationUserIdentifier;
import com.azure.core.util.Context;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.security.InvalidParameterException;
import java.util.ArrayList;
import java.util.Arrays;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

public class CallRecordingUnitTests extends CallRecordingUnitTestBase {
    private CallRecording callRecording;

    @BeforeEach
    public void setup() {
        CallAutomationClient callAutomationClient = CallAutomationUnitTestBase.getCallAutomationClient(new ArrayList<>());
        callRecording = callAutomationClient.getCallRecording();
    }
    @Test
    public void startRecordingRelativeUriFails() {
        assertThrows(
            InvalidParameterException.class,
            () -> callRecording.startRecording(new StartRecordingOptions(new ServerCallLocator(SERVER_CALL_ID))
                    .setRecordingStateCallbackUrl("/not/absolute/uri")
            ));
    }

    @Test
    public void startRecordingWithFullParamsFails() {
        StartRecordingOptions startRecordingOptions = new StartRecordingOptions(new ServerCallLocator(SERVER_CALL_ID))
            .setRecordingContent(RecordingContent.AUDIO_VIDEO)
            .setRecordingChannel(RecordingChannel.MIXED)
            .setRecordingFormat(RecordingFormat.MP4)
            .setRecordingStateCallbackUrl("/not/absolute/uri")
            .setAudioChannelParticipantOrdering(new ArrayList<CommunicationIdentifier>(Arrays.asList(
                new CommunicationUserIdentifier("rawId1"),
                new CommunicationUserIdentifier("rawId2"))));

        assertThrows(
            InvalidParameterException.class,
            () -> callRecording.startRecordingWithResponse(startRecordingOptions, Context.NONE)
        );
    }

    @Test
    public void recordingOperationsTest() {

        CallAutomationClient callAutomationClient = CallAutomationUnitTestBase.getCallAutomationClient(
            recordingOperationsResponses
        );
        callRecording = callAutomationClient.getCallRecording();

        validateRecording(
            callRecording.startRecording(new StartRecordingOptions(new ServerCallLocator(SERVER_CALL_ID))
                .setRecordingStateCallbackUrl("https://localhost/")),
            RecordingState.ACTIVE
        );

        verifyOperationWithRecordingState(
            () -> callRecording.pauseRecording(RECORDING_ID),
            RecordingState.INACTIVE
        );

        verifyOperationWithRecordingState(
            () -> callRecording.resumeRecording(RECORDING_ID),
            RecordingState.ACTIVE
        );

        callRecording.stopRecording(RECORDING_ID);
        assertThrows(CallingServerErrorException.class, () -> callRecording.getRecordingState(RECORDING_ID));
    }

    private void verifyOperationWithRecordingState(Runnable operation, RecordingState expectedStatus) {
        operation.run();
        RecordingStateResult recordingState = callRecording.getRecordingState(RECORDING_ID);
        validateRecording(recordingState, expectedStatus);
    }

    private void validateRecording(RecordingStateResult recordingState, RecordingState expectedStatus) {
        assertEquals(RECORDING_ID, recordingState.getRecordingId());
        assertEquals(expectedStatus, recordingState.getRecordingState());
    }
}


text:
<?php namespace Wireshell\Helpers;

use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Helper\Table;
use Wireshell\Helpers\WsTools as Tools;

/**
 * Class WsTables
 *
 * Contains table methods that could be used in every command
 *
 * @package Wireshell
 * @author Tabea David
 */
class WsTables {

  protected $output;
  protected $tools;

  /**
   * Construct WsTables
   *
   * @param OutputInterface $output
   */
  public function __construct(OutputInterface $output) {
    $this->output = $output;
    $this->tools = new Tools($output);
  }

  /**
   * Build borderless table
   *
   * @param array $content
   * @param array $headers
   */
  public function buildTable($content, $headers) {
    if (!is_array($headers)) $headers = array($headers);
    foreach ($headers as $k => $header) {
      $headers[$k] = $this->tools->writeHeader($header, false);
    }

    $tablePW = new Table($this->output);
    $tablePW
      ->setStyle('borderless')
      ->setHeaders($headers)
      ->setRows($content);

    return $tablePW;
  }

  /**
   * Render Tables
   *
   * @param array $tables
   * @param boolean $nlBefore, default true
   */
  public function renderTables($tables) {
    foreach ($tables as $table) {
      $table->render();
      $this->output->writeln('');
    }
  }

  /**
   * Write Table
   *
   * @param string $text
   */
  public function writeTable($text) {
    $table = new Table($this->output);
    $table->setHeaders(array($text));
    $table->render();
  }
}


text:
package sample.model.asset;

import static org.junit.jupiter.api.Assertions.*;

import java.math.BigDecimal;
import java.time.LocalDate;

import org.junit.jupiter.api.Test;

import sample.EntityTestSupport;
import sample.model.account.Account;

// low: 簡易な検証が中心
public class AssetTest extends EntityTestSupport {

    @Override
    protected void setupPreset() {
        targetEntities(Account.class, CashBalance.class, Cashflow.class, CashInOut.class);
    }

    @Test
    public void 振込出金可能か判定する() {
        // 残高 + 未実現キャッシュフロー - 出金依頼拘束額 = 出金可能額
        // 10000 + (1000 - 2000) - 8000 = 1000
        tx(() -> {
            fixtures.acc("test").save(rep);
            fixtures.cb("test", LocalDate.of(2014, 11, 18), "JPY", "10000").save(rep);
            fixtures.cf("test", "1000", LocalDate.of(2014, 11, 18), LocalDate.of(2014, 11, 20)).save(rep);
            fixtures.cf("test", "-2000", LocalDate.of(2014, 11, 19), LocalDate.of(2014, 11, 21)).save(rep);
            fixtures.cio("test", "8000", true).save(rep);

            assertTrue(
                    Asset.by("test").canWithdraw(rep, "JPY", new BigDecimal("1000"), LocalDate.of(2014, 11, 21)));
            assertFalse(
                    Asset.by("test").canWithdraw(rep, "JPY", new BigDecimal("1001"), LocalDate.of(2014, 11, 21)));
        });
    }

}


text:
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}

-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-partition-partitioninput.html

module Stratosphere.ResourceProperties.GluePartitionPartitionInput where

import Stratosphere.ResourceImports
import Stratosphere.ResourceProperties.GluePartitionStorageDescriptor

-- | Full data type definition for GluePartitionPartitionInput. See
-- 'gluePartitionPartitionInput' for a more convenient constructor.
data GluePartitionPartitionInput =
  GluePartitionPartitionInput
  { _gluePartitionPartitionInputParameters :: Maybe Object
  , _gluePartitionPartitionInputStorageDescriptor :: Maybe GluePartitionStorageDescriptor
  , _gluePartitionPartitionInputValues :: ValList Text
  } deriving (Show, Eq)

instance ToJSON GluePartitionPartitionInput where
  toJSON GluePartitionPartitionInput{..} =
    object $
    catMaybes
    [ fmap (("Parameters",) . toJSON) _gluePartitionPartitionInputParameters
    , fmap (("StorageDescriptor",) . toJSON) _gluePartitionPartitionInputStorageDescriptor
    , (Just . ("Values",) . toJSON) _gluePartitionPartitionInputValues
    ]

-- | Constructor for 'GluePartitionPartitionInput' containing required fields
-- as arguments.
gluePartitionPartitionInput
  :: ValList Text -- ^ 'gppiValues'
  -> GluePartitionPartitionInput
gluePartitionPartitionInput valuesarg =
  GluePartitionPartitionInput
  { _gluePartitionPartitionInputParameters = Nothing
  , _gluePartitionPartitionInputStorageDescriptor = Nothing
  , _gluePartitionPartitionInputValues = valuesarg
  }

-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-partition-partitioninput.html#cfn-glue-partition-partitioninput-parameters
gppiParameters :: Lens' GluePartitionPartitionInput (Maybe Object)
gppiParameters = lens _gluePartitionPartitionInputParameters (\s a -> s { _gluePartitionPartitionInputParameters = a })

-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-partition-partitioninput.html#cfn-glue-partition-partitioninput-storagedescriptor
gppiStorageDescriptor :: Lens' GluePartitionPartitionInput (Maybe GluePartitionStorageDescriptor)
gppiStorageDescriptor = lens _gluePartitionPartitionInputStorageDescriptor (\s a -> s { _gluePartitionPartitionInputStorageDescriptor = a })

-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-partition-partitioninput.html#cfn-glue-partition-partitioninput-values
gppiValues :: Lens' GluePartitionPartitionInput (ValList Text)
gppiValues = lens _gluePartitionPartitionInputValues (\s a -> s { _gluePartitionPartitionInputValues = a })


text:
'use strict';
/////////////////////////////////////
/* Problem 1 (this is your demo that we'll solve in class)
Write a function called sum() that takes in two numbers as arguments and then returns an array where the first element is the sum of those numbers, and the second element is a concatenated string that EXACTLY follows this example and uses the values that were input into the function:

"The sum of 4 and 7 is 11."

Test this function by hand in the console to get it working, and when you think it is finished, uncomment the call for the testSum() function below and check the console to see if the test passes.*/

// Write your code here
function sum(a,b){ //eslint-disable-line
  var result = a + b;
  return [result, 'The sum of ' + a + ' and ' + b + ' is ' + result + '.'];
}

sum(4,7);

// Here is the test for sum(); uncomment it to run it
testSum(4, 7);

// Once you get the test passing, do an a-c-p cycle and synchronize the code between GitHub and your laptop. Don't forget to create a new branch for your work on the next question!

/////////////////////////////////////
/* Problem 2
Write a function called multiply() that takes in two numbers as arguments and returns an array where the first element is the product of those numbers, and the second element is a string that EXACTLY follows this example and uses the values that were input into the function:

"The product of 5 and 9 is 45."

Test this function by hand in the console to get it working, and when you think it is finished, uncomment the call for the testMultiply() function and see if the test passes.*/

// Write your code here
function multiply(a,b){ //eslint-disable-line
  var result = a * b;
  return [result, 'The product of ' + a + ' and ' + b + ' is ' + result + '.'];
}

multiply(5,9);

// Here is the test for multiply(); uncomment it to run it
testMultiply(5,9);

// Once you get the test passing, do an a-c-p cycle and synchronize the code between GitHub and your laptop. Don't forget to create a new branch for your work on the next question!

/////////////////////////////////////
/* Problem 3
Write a function called sumAndMultiply() that takes in three numbers as separate arguments and returns an array where the first element is the sum of those three numbers, the second element is the product of those three numbers,  and the third and fourth elements are strings that EXACTLY follow this example and use the values that were input into the function:

Third element: "4 and 7 and 5 sum to 16."
Fourth element: "The product of 4 and 7 and 5 is 140."

IMPORTANT DETAIL: You may not use the arithmetic operators + and * in this function. To do addition, use your sum() function, and to do multiplication, use your multiply() function that you've already created. You're going to have to be resourceful to figure out how to do this.

Test this function by hand in the console to get it working, and when you think it is finished, uncomment the call for the testSumAndMultiply() function and see if the test passes.*/

// Write your code here
function sumAndMultiply(a,b,c){ //eslint-disable-line
  var addResult = sum(sum(a,b)[0],c)[0];
  var multResult = multiply(multiply(a,b)[0],c)[0];
  return [addResult, multResult, a + ' and ' + b + ' and ' + c + ' sum to ' + addResult + '.', 'The product of ' + a + ' and ' + b + ' and ' + c + ' is ' + multResult + '.'];
}

sumAndMultiply(4,7,5);
// sumAndMultiply(1, 2, 3);
// Here is the test for sumAndMultiply(); uncomment it to run it
testSumAndMultiply(4,7,5);

// Once you get the test passing, do an a-c-p cycle and synchronize the code between GitHub and your laptop. Don't forget to create a new branch for your work on the next question!

/////////////////////////////////////
/* Problem 4
Write a function called sumArray() that takes in an array of numbers as its single argument and then returns an array where the first element is the sum of the numbers in the array, and the second element is a string that EXACTLY follows this example and uses the values that were input into the function:

"2,3,4 was passed in as an array of numbers, and 9 is their sum."

IMPORTANT DETAIL: You may not use the arithmetic operator + in this function. To do addition, use your sum() function that you've already created. You're going to have to be resourceful to figure out how to do this.

Test this function by hand in the console to get it working, and when you think it is finished, uncomment the call for the testSumArray() function and see if the test passes.*/

// Write your code here
var testArray = [2,3,4]; //eslint-disable-line

function sumArray(testArray){ //eslint-disable-line
  var sumResult = sum(sum(testArray[0],testArray[1])[0], testArray[2])[0];
  return [sumResult, testArray[0] + ',' + testArray[1] + ',' + testArray[2] + ' was passed in as an array of numbers, and ' + sumResult + ' is their sum.'];
}

sumArray(testArray);
//sumArray(testArray);

// Here is the test for sumArray(); uncomment it to run it

testSumArray(testArray);

// Once you get the test passing, do an a-c-p cycle and synchronize the code between GitHub and your laptop. Don't forget to create a new branch for your work on the next question!

/////////////////////////////////////
/* Problem 5
Write a function called multiplyArray() that takes an array of numbers as its argument and returns an array whose first element is the product of those numbers, and the second element is a string that EXACTLY follows this example and uses the values that were input into the function:

"The numbers 2,3,4 have a product of 24."

IMPORTANT DETAIL: You may not use the arithmetic operator * in this function. To do multiplication, use your multiply() function that you've already created. You're going to have to be resourceful to figure out how to do this.

Test this function by hand in the console to get it working, and when you think it is finished, uncomment the call for the testMultiplyArray() function and see if the test passes.*/
// Write your code here
function multiplyArray(testArray){ //eslint-disable-line
  var multResult = multiply(multiply(testArray[0],testArray[1])[0], testArray[2])[0];
  return [multResult, 'The numbers ' + testArray[0] + ',' + testArray[1] + ',' + testArray[2] + ' have a product of ' + multResult + '.'];
}
multiplyArray(testArray);
// Here is the test for multiplyArray(); uncomment it to run it
testMultiplyArray(2,3,4);

// Once you get the test passing, do an a-c-p cycle and synchronize the code between GitHub and your laptop. You're done! Submit the link to the repo following the instructions in Canvas.


text: docker-compose up --abort-on-container-exit