text:
#include <iostream>

#include <pcl/io/pcd_io.h>
#include <pcl/io/ply_io.h>
#include <pcl/point_cloud.h>
#include <pcl/console/parse.h>
#include <pcl/common/transforms.h>
#include <pcl/visualization/pcl_visualizer.h>
#include <pcl/point_types.h>
#include <pcl/features/normal_3d.h>

// This function displays the help
void
showHelp(char * program_name)
{
  std::cout << std::endl;
  std::cout << "Usage: " << program_name << " cloud_filename.[pcd|ply]" << std::endl;
  std::cout << "-h:  Show this help." << std::endl;
}

// This is the main function
int
main (int argc, char** argv)
{

  // Show help
  if (pcl::console::find_switch (argc, argv, "-h") || pcl::console::find_switch (argc, argv, "--help")) {
    showHelp (argv[0]);
    return 0;
  }

  // Fetch point cloud filename in arguments | Works with PCD and PLY files
  std::vector<int> filenames;
  bool file_is_pcd = false;

  filenames = pcl::console::parse_file_extension_argument (argc, argv, ".ply");

  if (filenames.size () != 1)  {
    filenames = pcl::console::parse_file_extension_argument (argc, argv, ".pcd");

    if (filenames.size () != 1) {
      showHelp (argv[0]);
      return -1;
    } else {
      file_is_pcd = true;
    }
  }

  // Load file | Works with PCD and PLY files
  pcl::PointCloud<pcl::PointXYZ>::Ptr source_cloud (new pcl::PointCloud<pcl::PointXYZ> ());

  if (file_is_pcd) {
    if (pcl::io::loadPCDFile (argv[filenames[0]], *source_cloud) < 0)  {
      std::cout << "Error loading point cloud " << argv[filenames[0]] << std::endl << std::endl;
      showHelp (argv[0]);
      return -1;
    }
  } else {
    if (pcl::io::loadPLYFile (argv[filenames[0]], *source_cloud) < 0)  {
      std::cout << "Error loading point cloud " << argv[filenames[0]] << std::endl << std::endl;
      showHelp (argv[0]);
      return -1;
    }
  }

  // Create the normal estimation class, and pass the input dataset to it
  pcl::NormalEstimation<pcl::PointXYZ, pcl::Normal> ne;
  ne.setInputCloud(source_cloud);

  // Create an empty kdtree representation, and pass it to the normal estimation object.
  // Its content will be filled inside the object, based on the given input dataset (as no other search surface is given).
  pcl::search::KdTree<pcl::PointXYZ>::Ptr tree(new pcl::search::KdTree<pcl::PointXYZ>());
  ne.setSearchMethod(tree);

  // Output datasets
  pcl::PointCloud<pcl::Normal>::Ptr cloud_normals(new pcl::PointCloud<pcl::Normal>);

  // Use all neighbors in a sphere of radius 3cm
  ne.setRadiusSearch(0.03);

  // Compute the features
  ne.compute(*cloud_normals);

  // cloud_normals->points.size () should have the same size as the input cloud->points.size ()*

  /* Reminder: how transformation matrices work :

           |-------> This column is the translation
    | 1 0 0 x |  \
    | 0 1 0 y |   }-> The identity 3x3 matrix (no rotation) on the left
    | 0 0 1 z |  /
    | 0 0 0 1 |    -> We do not use this line (and it has to stay 0,0,0,1)

    METHOD #1: Using a Matrix4f
    This is the "manual" method, perfect to understand but error prone !
  */
  Eigen::Matrix4f transform_1 = Eigen::Matrix4f::Identity();

  // Define a rotation matrix (see https://en.wikipedia.org/wiki/Rotation_matrix)
  float theta = M_PI/4; // The angle of rotation in radians
  transform_1 (0,0) = cos (theta);
  transform_1 (0,1) = -sin(theta);
  transform_1 (1,0) = sin (theta);
  transform_1 (1,1) = cos (theta);
  //    (row, column)

  // Define a translation of 2.5 meters on the x axis.
  transform_1 (0,3) = 0.025;

  // Print the transformation
  printf ("Method #1: using a Matrix4f\n");
  std::cout << transform_1 << std::endl;

  /*  METHOD #2: Using a Affine3f
    This method is easier and less error prone
  */
  Eigen::Affine3f transform_2 = Eigen::Affine3f::Identity();

  // Define a translation of 2.5 meters on the x axis.
  transform_2.translation() << 0.025, 0.0, 0.0;

  // The same rotation matrix as before; theta radians arround Z axis
  transform_2.rotate (Eigen::AngleAxisf (theta, Eigen::Vector3f::UnitZ()));

  // Print the transformation
  printf ("\nMethod #2: using an Affine3f\n");
  std::cout << transform_2.matrix() << std::endl;

  // Executing the transformation
  pcl::PointCloud<pcl::PointXYZ>::Ptr transformed_cloud (new pcl::PointCloud<pcl::PointXYZ> ());
  // You can either apply transform_1 or transform_2; they are the same
  pcl::transformPointCloud (*source_cloud, *transformed_cloud, transform_2);

  // Visualization
  printf(  "\nPoint cloud colors :  white  = original point cloud\n"
      "                        red  = transformed point cloud\n");
  pcl::visualization::PCLVisualizer viewer ("Matrix transformation example");

   // Define R,G,B colors for the point cloud
  pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> source_cloud_color_handler (source_cloud, 255, 255, 255);
  // We add the point cloud to the viewer and pass the color handler
  viewer.addPointCloud (source_cloud, source_cloud_color_handler, "original_cloud");

  pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> transformed_cloud_color_handler (transformed_cloud, 230, 20, 20); // Red
  viewer.addPointCloud (transformed_cloud, transformed_cloud_color_handler, "transformed_cloud");

  viewer.addCoordinateSystem (0.1, "cloud", 0);
  viewer.setBackgroundColor(0.05, 0.05, 0.05, 0); // Setting background to a dark grey
  viewer.setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 2, "original_cloud");
  viewer.setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 2, "transformed_cloud");
  viewer.setPosition(0, 0); // Setting visualiser window position

  while (!viewer.wasStopped ()) { // Display the visualiser until 'q' key is pressed
    viewer.spinOnce ();
  }

  return 0;
}


text:
require 'spec_helper'

RSpec.describe 'Aspector options access' do
  subject { klass.new }
  let(:interception_options) { { rand => rand } }

  context 'accessing interception options' do
    let(:klass) do
      ClassBuilder.build do
        attr_accessor :interception_options
      end
    end

    before do
      aspect.apply klass, interception_options.merge(method: :exec)
    end

    context 'before aspect' do
      let(:aspect) do
        ClassBuilder.inherit(Aspector::Base) do
          default aspect_field: 60

          before interception_arg: true do |interception|
            self.interception_options = interception.options
          end
        end
      end

      it 'should be able to reach interception options that were merged with aspect options' do
        subject.exec
        expected = interception_options.merge(method: :exec).merge(aspect_field: 60)
        expect(subject.interception_options).to eq expected
      end

      it 'still should exec original method' do
        subject.exec
        expect(subject.values).to eq %w( exec-result )
      end
    end

    context 'before_filter aspect' do
      let(:aspect) do
        ClassBuilder.inherit(Aspector::Base) do
          default aspect_field: 60

          before_filter interception_arg: true do |interception|
            self.interception_options = interception.options
          end
        end
      end

      it 'should be able to reach interception options that were merged with aspect options' do
        subject.exec
        expected = interception_options.merge(method: :exec).merge(aspect_field: 60)
        expect(subject.interception_options).to eq expected
      end

      it 'still should exec original method' do
        subject.exec
        expect(subject.values).to eq %w( exec-result )
      end
    end

    context 'around aspect' do
      let(:aspect) do
        ClassBuilder.inherit(Aspector::Base) do
          default aspect_field: 60

          around interception_arg: true do |interception, proxy, &block|
            self.interception_options = interception.options
            proxy.call(&block)
          end
        end
      end

      it 'should be able to reach interception options that were merged with aspect options' do
        subject.exec
        expected = interception_options.merge(method: :exec).merge(aspect_field: 60)
        expect(subject.interception_options).to eq expected
      end

      it 'still should exec original method' do
        subject.exec
        expect(subject.values).to eq %w( exec-result )
      end
    end

    context 'after aspect' do
      let(:aspect) do
        ClassBuilder.inherit(Aspector::Base) do
          default aspect_field: 60

          after interception_arg: true do |interception, result|
            self.interception_options = interception.options
            result
          end
        end
      end

      it 'should be able to reach interception options that were merged with aspect options' do
        subject.exec
        expected = interception_options.merge(method: :exec).merge(aspect_field: 60)
        expect(subject.interception_options).to eq expected
      end

      it 'still should exec original method' do
        subject.exec
        expect(subject.values).to eq %w( exec-result )
      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
// This file is automatically generated.

package adila.db;

/*
 * Samsung Galaxy Note 10.1
 *
 * DEVICE: p4notewifi43241any
 * MODEL: SHW-M486W
 */
final class p4notewifi43241any {
    public static final String DATA = "Samsung|Galaxy Note 10.1|Galaxy Note";
}


text:
namespace tmb {
namespace internal {

// Header for all log records written by LogWriter and read by LogReader.
struct LogRecordHeader {
  std::size_t length;
  std::uint32_t crc32;
};

}  // namespace internal
}  // namespace tmb

#endif  // TMB_INTERNAL_LOG_RECORD_HEADER_H_


text:
using System;
using DSoft.Messaging;

namespace MessageBoxAndroid.Events
{
	/// <summary>
	/// Custom MessageBusEvent class with extra data
	/// </summary>
	public class CustomMessageBusEvent : MessageBusEvent
	{
		public const string kCustEventId = "445566";

		#region Properties

		/// <summary>
		/// Gets or sets the event identifier.
		/// </summary>
		/// <value>The event identifier.</value>
		public override string EventId {
			get
			{
				//return a constant eventId
				return kCustEventId;
			}
		}

		/// <summary>
		/// Custom property on the event that Gets or sets the timestamp
		/// </summary>
		/// <value>The time stamp.</value>
		public DateTime TimeStamp { get; set; }

		#endregion

		#region Constructores

		/// <summary>
		/// Initializes a new instance of the <see cref="MessageBus_iOS.CustomMessageBusEvent"/> class.
		/// </summary>
		public CustomMessageBusEvent ()
		{
			//
			TimeStamp = DateTime.Now;
		}

		#endregion
	}
}


text:
namespace content_settings {

// The class MockProvider is a mock for a non default content settings provider.
class MockProvider : public ObservableProvider {
 public:
  MockProvider();
  explicit MockProvider(bool read_only);

  MockProvider(const MockProvider&) = delete;
  MockProvider& operator=(const MockProvider&) = delete;

  ~MockProvider() override;

  std::unique_ptr<RuleIterator> GetRuleIterator(
      ContentSettingsType content_type,
      bool incognito) const override;

  bool SetWebsiteSetting(
      const ContentSettingsPattern& requesting_url_pattern,
      const ContentSettingsPattern& embedding_url_pattern,
      ContentSettingsType content_type,
      base::Value&& value,
      const ContentSettingConstraints& constraint = {}) override;

  void ClearAllContentSettingsRules(ContentSettingsType content_type) override {
  }

  void ShutdownOnUIThread() override;

  void set_read_only(bool read_only) { read_only_ = read_only; }

  bool read_only() const { return read_only_; }

 private:
  OriginIdentifierValueMap value_map_;
  bool read_only_;
};

}  // namespace content_settings

#endif  // COMPONENTS_CONTENT_SETTINGS_CORE_TEST_CONTENT_SETTINGS_MOCK_PROVIDER_H_


text:
class AssetManager : public IModule, public Singleton<AssetManager>
{
public:
	AssetManager() {};
	~AssetManager() {};

	virtual int Init() override;
	virtual int Shutdown() override;

	Model* LoadModel(std::string fileName);
	void UnloadModel(Model* model);

	ID3D11Texture2D* LoadTexture(std::string fileName);
	void UnloadTexture();

	SimpleVertexShader* LoadVertexShader(std::string fileName);
	SimplePixelShader* LoadPixelShader(std::string fileName);
	SimpleGeometryShader* LoadGeometryShader(std::string fileName);

private:
	std::map<std::string, Model*>* m_models;
	std::map<std::string, ID3D11Texture2D*>* m_textures;
	std::map<std::string, int>* m_assetRefCount;
	std::map<std::string, SimpleVertexShader*>* m_vertexShaders;
	std::map<std::string, SimplePixelShader*>* m_pixelShaders;
	std::map<std::string, SimpleGeometryShader*>* m_geometryShaders;

protected:
	std::string m_ModelDir;
	std::string m_ShaderDir;
	std::string m_TextureDir;
};


text:
start = AskAddr(0xFFFFFFFF, "Enter start address.")
end = AskAddr(0xFFFFFFFF, "Enter end address.")
incr = AskLong(4, "What is the offset from one table entry to the next?")

def transform_to_code(start, end):
  while start < end:
	l = MakeCode(start)
	if l:
	  print "Converted 0x%08x to code."%start
	  start += l
	elif GetOpType(start, 0) == -1:
	  start+=1
	else:
	  break
  return start

if start >= end:
  print "Please enter a valid start and end address start: 0x%08x end: 0x%08x."%(start,end)

while  start < end:
  if Dfirst(start) != 0xFFFFFFFF:
	transform_to_code(Dfirst(start), Dfirst(start)+1)
  start += 4

print "Finished cleaning up the jump table code."


text:
class RockDoc
  module Configuration
    class Global < Struct.new *%i(title toc global_block namespaces app_name renderer interrogators excluded_klasses)
    end

    class Serializer < Struct.new *%i(resource_name resource_class json_representation
                                      notes attributes_for_json serializer nodoc configuration_name)
    end

    class Controller < Struct.new *%i(path resource_name resource_class controller_class
                                      serializer_configuration routes json_representation
                                      permitted_params notes attributes_for_json
                                      attributes_for_permitted_params action_configurations nodoc)
      def action name, &block
        self.action_blocks[name] = block
      end

      def action_blocks
        @action_blocks ||= {}.with_indifferent_access
      end
    end

    class Action < Struct.new *%i(action description verb pathspec controller_configuration notes
                                  scopes nodoc)
    end

    class AppControllerConfiguration < Struct.new *%i(namespace block)
    end

    class Route < Struct.new *%i(controller_path action verb path)
    end

    class Resource < Struct.new *%i(resource_class serializer configuration_name)
    end
  end
end


text:
<?php

namespace App\Backend\Submodules\Member\Models;

class BehaviorLog extends \App\Common\Models\Member\BehaviorLog
{

    use \App\Backend\Models\Base;
}


text:
/**
 * @implements {Common.ContentProvider}
 * @unrestricted
 */
SDK.Resource = class extends SDK.SDKObject {
  /**
   * @param {!SDK.Target} target
   * @param {?SDK.NetworkRequest} request
   * @param {string} url
   * @param {string} documentURL
   * @param {!Protocol.Page.FrameId} frameId
   * @param {!Protocol.Network.LoaderId} loaderId
   * @param {!Common.ResourceType} type
   * @param {string} mimeType
   * @param {?Date} lastModified
   * @param {?number} contentSize
   */
  constructor(target, request, url, documentURL, frameId, loaderId, type, mimeType, lastModified, contentSize) {
    super(target);
    this._request = request;
    this.url = url;
    this._documentURL = documentURL;
    this._frameId = frameId;
    this._loaderId = loaderId;
    this._type = type || Common.resourceTypes.Other;
    this._mimeType = mimeType;

    this._lastModified = lastModified && lastModified.isValid() ? lastModified : null;
    this._contentSize = contentSize;

    /** @type {?string} */ this._content;
    /** @type {boolean} */ this._contentEncoded;
    this._pendingContentCallbacks = [];
    if (this._request && !this._request.finished)
      this._request.addEventListener(SDK.NetworkRequest.Events.FinishedLoading, this._requestFinished, this);
  }

  /**
   * @return {?Date}
   */
  lastModified() {
    if (this._lastModified || !this._request)
      return this._lastModified;
    var lastModifiedHeader = this._request.responseLastModified();
    var date = lastModifiedHeader ? new Date(lastModifiedHeader) : null;
    this._lastModified = date && date.isValid() ? date : null;
    return this._lastModified;
  }

  /**
   * @return {?number}
   */
  contentSize() {
    if (typeof this._contentSize === 'number' || !this._request)
      return this._contentSize;
    return this._request.resourceSize;
  }

  /**
   * @return {?SDK.NetworkRequest}
   */
  get request() {
    return this._request;
  }

  /**
   * @return {string}
   */
  get url() {
    return this._url;
  }

  /**
   * @param {string} x
   */
  set url(x) {
    this._url = x;
    this._parsedURL = new Common.ParsedURL(x);
  }

  get parsedURL() {
    return this._parsedURL;
  }

  /**
   * @return {string}
   */
  get documentURL() {
    return this._documentURL;
  }

  /**
   * @return {!Protocol.Page.FrameId}
   */
  get frameId() {
    return this._frameId;
  }

  /**
   * @return {!Protocol.Network.LoaderId}
   */
  get loaderId() {
    return this._loaderId;
  }

  /**
   * @return {string}
   */
  get displayName() {
    return this._parsedURL.displayName;
  }

  /**
   * @return {!Common.ResourceType}
   */
  resourceType() {
    return this._request ? this._request.resourceType() : this._type;
  }

  /**
   * @return {string}
   */
  get mimeType() {
    return this._request ? this._request.mimeType : this._mimeType;
  }

  /**
   * @return {?string}
   */
  get content() {
    return this._content;
  }

  /**
   * @return {boolean}
   */
  get contentEncoded() {
    return this._contentEncoded;
  }

  /**
   * @override
   * @return {string}
   */
  contentURL() {
    return this._url;
  }

  /**
   * @override
   * @return {!Common.ResourceType}
   */
  contentType() {
    if (this.resourceType() === Common.resourceTypes.Document && this.mimeType.indexOf('javascript') !== -1)
      return Common.resourceTypes.Script;
    return this.resourceType();
  }

  /**
   * @override
   * @return {!Promise<?string>}
   */
  requestContent() {
    if (typeof this._content !== 'undefined')
      return Promise.resolve(this._content);

    var callback;
    var promise = new Promise(fulfill => callback = fulfill);
    this._pendingContentCallbacks.push(callback);
    if (!this._request || this._request.finished)
      this._innerRequestContent();
    return promise;
  }

  /**
   * @return {string}
   */
  canonicalMimeType() {
    return this.contentType().canonicalMimeType() || this.mimeType;
  }

  /**
   * @override
   * @param {string} query
   * @param {boolean} caseSensitive
   * @param {boolean} isRegex
   * @param {function(!Array.<!Common.ContentProvider.SearchMatch>)} callback
   */
  searchInContent(query, caseSensitive, isRegex, callback) {
    /**
     * @param {?Protocol.Error} error
     * @param {!Array.<!Protocol.Debugger.SearchMatch>} searchMatches
     */
    function callbackWrapper(error, searchMatches) {
      callback(searchMatches || []);
    }

    if (this.frameId) {
      this.target().pageAgent().searchInResource(
          this.frameId, this.url, query, caseSensitive, isRegex, callbackWrapper);
    } else {
      callback([]);
    }
  }

  /**
   * @param {!Element} image
   */
  populateImageSource(image) {
    /**
     * @param {?string} content
     * @this {SDK.Resource}
     */
    function onResourceContent(content) {
      var imageSrc = Common.ContentProvider.contentAsDataURL(content, this._mimeType, true);
      if (imageSrc === null)
        imageSrc = this._url;
      image.src = imageSrc;
    }

    this.requestContent().then(onResourceContent.bind(this));
  }

  _requestFinished() {
    this._request.removeEventListener(SDK.NetworkRequest.Events.FinishedLoading, this._requestFinished, this);
    if (this._pendingContentCallbacks.length)
      this._innerRequestContent();
  }

  _innerRequestContent() {
    if (this._contentRequested)
      return;
    this._contentRequested = true;

    /**
     * @param {?Protocol.Error} error
     * @param {?string} content
     * @param {boolean} contentEncoded
     * @this {SDK.Resource}
     */
    function contentLoaded(error, content, contentEncoded) {
      if (error || content === null) {
        replyWithContent.call(this, null, false);
        return;
      }
      replyWithContent.call(this, content, contentEncoded);
    }

    /**
     * @param {?string} content
     * @param {boolean} contentEncoded
     * @this {SDK.Resource}
     */
    function replyWithContent(content, contentEncoded) {
      this._content = content;
      this._contentEncoded = contentEncoded;
      var callbacks = this._pendingContentCallbacks.slice();
      for (var i = 0; i < callbacks.length; ++i)
        callbacks[i](this._content);
      this._pendingContentCallbacks.length = 0;
      delete this._contentRequested;
    }

    /**
     * @param {?Protocol.Error} error
     * @param {string} content
     * @param {boolean} contentEncoded
     * @this {SDK.Resource}
     */
    function resourceContentLoaded(error, content, contentEncoded) {
      contentLoaded.call(this, error, content, contentEncoded);
    }

    if (this.request) {
      this.request.requestContent().then(requestContentLoaded.bind(this));
      return;
    }

    /**
     * @param {?string} content
     * @this {SDK.Resource}
     */
    function requestContentLoaded(content) {
      contentLoaded.call(this, null, content, this.request.contentEncoded);
    }

    this.target().pageAgent().getResourceContent(this.frameId, this.url, resourceContentLoaded.bind(this));
  }

  /**
   * @return {boolean}
   */
  hasTextContent() {
    if (this._type.isTextType())
      return true;
    if (this._type === Common.resourceTypes.Other)
      return !!this._content && !this._contentEncoded;
    return false;
  }
};


text:
package org.killbill.billing.plugin.adyen.client.recurring;

import org.killbill.adyen.recurring.Recurring;
import org.killbill.adyen.recurring.RecurringPortType;
import org.killbill.billing.plugin.adyen.client.AdyenConfigProperties;
import org.killbill.billing.plugin.adyen.client.AdyenPaymentPortRegistry;
import org.killbill.billing.plugin.adyen.client.jaxws.HttpHeaderInterceptor;
import org.killbill.billing.plugin.adyen.client.jaxws.LoggingInInterceptor;
import org.killbill.billing.plugin.adyen.client.jaxws.LoggingOutInterceptor;

public class AdyenRecurringPortRegistry extends AdyenPaymentPortRegistry implements RecurringPortRegistry {

    private static final String RECURRING_SERVICE_SUFFIX = "-recurringService";

    public AdyenRecurringPortRegistry(final AdyenConfigProperties config,
                                      final LoggingInInterceptor loggingInInterceptor,
                                      final LoggingOutInterceptor loggingOutInterceptor,
                                      final HttpHeaderInterceptor httpHeaderInterceptor) {
        super(config, loggingInInterceptor, loggingOutInterceptor, httpHeaderInterceptor);
    }

    @Override
    public RecurringPortType getRecurringPort(final String merchantAccount) {
        return createService(merchantAccount,
                             RECURRING_SERVICE_SUFFIX,
                             RecurringPortType.class,
                             Recurring.SERVICE,
                             Recurring.RecurringHttpPort,
                             config.getRecurringUrl(),
                             config.getRecurringConnectionTimeout(),
                             config.getRecurringReadTimeout());
    }
}


text:
package com.lorne.tx.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lorne.core.framework.utils.task.ConditionUtils;
import com.lorne.core.framework.utils.task.IBack;
import com.lorne.core.framework.utils.task.Task;
import com.lorne.tx.Constants;
import com.lorne.tx.service.DiscoveryService;
import com.lorne.tx.service.TxManagerService;
import com.lorne.tx.service.TxService;
import com.lorne.tx.service.model.TxServer;
import com.lorne.tx.service.model.TxState;
import com.lorne.tx.utils.SocketManager;
import com.lorne.tx.utils.SocketUtils;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.eureka.EurekaServerContextHolder;
import io.netty.channel.Channel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by lorne on 2017/7/1.
 */
@Service
public class TxServiceImpl implements TxService {

    @Value("${redis_save_max_time}")
    private int redis_save_max_time;

    @Value("${transaction_netty_heart_time}")
    private int transaction_netty_heart_time;

    @Value("${transaction_netty_delay_time}")
    private int transaction_netty_delay_time;

    @Autowired
    private TxManagerService managerService;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryService discoveryService;

    @Autowired
    private TxManagerService txManagerService;

    @Override
    public TxServer getServer() {
        List<String> urls= getServices();
        List<TxState> states = new ArrayList<>();
        for(String url:urls){
            TxState state = restTemplate.getForObject(url+"/tx/manager/state",TxState.class);
            states.add(state);
        }
        if(states.size()<=1) {
            TxState state = getState();
            if (state.getMaxConnection() > state.getNowConnection()) {
                return TxServer.format(state);
            } else {
                return null;
            }
        }else{
            //找默认数据
            TxState state = getDefault(states,0);
            if (state == null) {
                //没有满足的默认数据
                return null;
            }
            return TxServer.format(state);
        }
    }

    private TxState getDefault(List<TxState> states, int index) {
        TxState state = states.get(index);
        if (state.getMaxConnection() == state.getNowConnection()) {
            index++;
            if (states.size() - 1 >= index) {
                return getDefault(states, index);
            } else {
                return null;
            }
        } else {
            return state;
        }
    }

    @Override
    public TxState getState() {
        TxState state = new TxState();
        String ipAddress = EurekaServerContextHolder.getInstance().getServerContext().getApplicationInfoManager().getEurekaInstanceConfig().getIpAddress();
        if(!isIp(ipAddress)){
            ipAddress = "127.0.0.1";
        }
        state.setIp(ipAddress);
        state.setPort(Constants.socketPort);
        state.setMaxConnection(SocketManager.getInstance().getMaxConnection());
        state.setNowConnection(SocketManager.getInstance().getNowConnection());
        state.setRedisSaveMaxTime(redis_save_max_time);
        state.setTransactionNettyDelayTime(transaction_netty_delay_time);
        state.setTransactionNettyHeartTime(transaction_netty_heart_time);
        state.setSlbList(getServices());
        return state;
    }

    public static boolean isIp(String ipAddress) {
        String ip = "([1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}";
        Pattern pattern = Pattern.compile(ip);
        Matcher matcher = pattern.matcher(ipAddress);
        return matcher.matches();
    }

    private List<String> getServices(){
        List<String> urls = new ArrayList<>();
        List<InstanceInfo> instanceInfos =discoveryService.getConfigServiceInstances();
        for (InstanceInfo instanceInfo : instanceInfos) {
            String url = instanceInfo.getHomePageUrl();
            String address = instanceInfo.getIPAddr();
            if (isIp(address)) {
                urls.add(url);
            }else{
                url = url.replace(address,"127.0.0.1");
                urls.add(url);
            }
        }
        return urls;
    }

    @Override
    public boolean checkClearGroup(String groupId, String taskId, int isGroup) {
        return managerService.checkClearGroup(groupId,taskId,isGroup);
    }

    @Override
    public int checkGroup(String groupId, String taskId) {
        return managerService.checkTransactionGroup(groupId, taskId);
    }

    @Override
    public String sendMsg(String model,String msg) {
        JSONObject jsonObject = JSON.parseObject(msg);
        String key = jsonObject.getString("k");

        //创建Task
        final Task task = ConditionUtils.getInstance().createTask(key);

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (!task.isAwait() && !Thread.currentThread().interrupted()) {
                    try {
                        Thread.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                Channel channel = SocketManager.getInstance().getChannelByModelName(model);
                if (channel != null &&channel.isActive()) {
                    SocketUtils.sendMsg(channel,msg);
                }
            }
        }).start();

        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                Task task = ConditionUtils.getInstance().getTask(key);
                if(task!=null&&!task.isNotify()) {
                    task.setBack(new IBack() {
                        @Override
                        public Object doing(Object... objs) throws Throwable {
                            return "-2";
                        }
                    });
                    task.signalTask();
                }
            }
        }, txManagerService.getDelayTime() * 1000);

        task.awaitTask();
        timer.cancel();

        try {
            return  (String)task.getBack().doing();
        } catch (Throwable throwable) {
            return "-1";
        }finally {
            task.remove();
        }
    }
}


text:
@implementation YACLogEvent (Mustache)

- (NSString *)m_timestamp
{
    return [[self timestampFormatter] stringFromDate:self.timestamp];
}

- (NSDateFormatter *)timestampFormatter
{
    static NSDateFormatter *timestampFormatter = nil;
    if (timestampFormatter == nil) {
        timestampFormatter = [[NSDateFormatter alloc] init];
        [timestampFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSS"];
    }
    return timestampFormatter;
}

@end


text:
module Omnibus
  class Error < RuntimeError
  end

  class AbstractMethod < Error
    def initialize(signature)
      @signature = signature
    end

    def to_s
      "'#{@signature}' is an abstract method and must be overridden!"
    end
  end

  class ProjectNotFound < Error
    def initialize(name)
      @name = name
    end

    def to_s
      out = "I could not find an Omnibus project named '#{@name}'! "
      out << "Valid projects are:\n"

      Omnibus.project_names.sort.each do |project_name|
        out << "  * #{project_name}\n"
      end

      out.strip
    end
  end

  class MissingAsset < Error
    def initialize(path)
      @path = path
    end

    def to_s
      "Missing asset! '#{@path}' is not present on disk."
    end
  end

  class InvalidS3Configuration < Error
    def initialize(s3_bucket, s3_access_key, s3_secret_key)
      @s3_bucket, @s3_access_key, @s3_secret_key = s3_bucket, s3_access_key, s3_secret_key
    end

    def to_s
      <<-EOH
One or more required S3 configuration values is missing.

Your effective configuration was the following:

    s3_bucket     #{@s3_bucket.inspect}
    s3_access_key #{@s3_access_key.inspect}
    s3_secret_key #{@s3_secret_key.inspect}

If you truly do want S3 caching, you should add values similar to the following
in your Omnibus config file:

    s3_bucket     ENV['S3_BUCKET_NAME']
    s3_access_key ENV['S3_ACCESS_KEY']
    s3_secret_key ENV['S3_SECRET_KEY']

Note that you are not required to use environment variables as illustrated (and
the ones listed have no special significance in Omnibus), but it is encouraged
to prevent spread of sensitive information and inadvertent check-in of same to
version control systems.
      EOH
    end
  end

  class BadReplacesLine < Error
    def to_s
      <<-EOH
The `replaces` project DSL statement should never equal the `package_name` or
`name` of a project. The `replaces` option should only be used when you have
published an artifact under one name and then later renamed the packages that
you are publishing and you must obsolete the old package name. For example this
is used, correctly, in chef-client builds:

    name 'chef'
    replaces 'chef-full'

The RPMs and debs which were originally published were named "chef-full" and
this was later renamed, and in order to upgrade the (very old) "chef-full"
packages the new "chef" packages needed to know to uninstall any "chef-full"
packages that were found. Projects which have never been renamed, however,
should never use the replaces line.
      EOH
    end
  end

  class NoPackageFile < Error
    def initialize(package_path)
      @package_path = package_path
    end

    def to_s
      """
      Cannot locate or access the package at the given path:

        #{@package_path}
      """
    end
  end

  class NoPackageMetadataFile < Error
    def initialize(package_metadata_path)
      @package_metadata_path = package_metadata_path
    end

    def to_s
      """
      Cannot locate or access the package metadata file at the given path:

        #{@package_metadata_path}
      """
    end
  end

  class InvalidS3ReleaseConfiguration < Error
    def to_s
      """
      One or more required S3 configuration values is missing.

      Your effective configuration was the following:

          release_s3_bucket     => #{Config.release_s3_bucket.inspect}
          release_s3_access_key => #{Config.release_s3_access_key.inspect}
          release_s3_secret_key => #{Config.release_s3_secret_key.inspect}

      To release a package to S3, add the following values to your
      config file:

          release_s3_bucket      ENV['S3_BUCKET_NAME']
          release_s3_access_key  ENV['S3_ACCESS_KEY']
          release_s3_secret_key  ENV['S3_SECRET_KEY']

      Note that you are not required to use environment variables as
      illustrated (and the ones listed have no special significance in
      Omnibus), but it is encouraged to prevent spread of sensitive
      information and inadvertent check-in of same to version control
      systems.

      """
    end
  end

  # Raise this error if a needed Project configuration value has not
  # been set.
  class MissingProjectConfiguration < Error
    def initialize(parameter_name, sample_value)
      @parameter_name, @sample_value = parameter_name, sample_value
    end

    def to_s
      """
      You are attempting to build a project, but have not specified
      a value for '#{@parameter_name}'!

      Please add code similar to the following to your project DSL file:

         #{@parameter_name} '#{@sample_value}'

      """
    end
  end

  # Raise this error if a needed Software configuration value has not
  # been set.
  class MissingSoftwareConfiguration < Error
    def initialize(software_name, parameter_name, sample_value)
      @software_name, @parameter_name, @sample_value = software_name, parameter_name, sample_value
    end

    def to_s
      """
      You are attempting to build software #{@sofware_name}, but have not specified
      a value for '#{@parameter_name}'!

      Please add code similar to the following to your software DSL file:

         #{@parameter_name} '#{@sample_value}'

      """
    end
  end

  class MissingPatch < Error
    def initialize(patch_name, search_paths)
      @patch_name, @search_paths = patch_name, search_paths
    end

    def to_s
      """
      Attempting to apply the patch #{@patch_name}, but it was not
      found at any of the following locations:

      #{@search_paths.join("\n      ")}
      """
    end
  end

  class MissingTemplate < Error
    def initialize(template_name, search_paths)
      @template_name, @search_paths = template_name, search_paths
    end

    def to_s
      """
      Attempting to evaluate the template #{@template_name}, but it was not
      found at any of the following locations:

      #{@search_paths.join("\n      ")}
      """
    end
  end

  class MissingProjectDependency < Error
    def initialize(dep_name, search_paths)
      @dep_name, @search_paths = dep_name, search_paths
    end

    def to_s
      """
      Attempting to load the project dependency '#{@dep_name}', but it was
      not found at any of the following locations:

      #{@search_paths.join("\n      ")}
      """
    end
  end

  class UnresolvableGitReference < Error
  end

  class UnknownPublisher < Error
    def initialize(backend)
      @backend  = backend
      @backends = Omnibus.constants
                    .map(&:to_s)
                    .select { |const| const.to_s =~ /^(.+)Publisher$/ }
                    .sort
    end

    def to_s
      <<-EOH
I could not find a publisher named #{@backend}. Valid publishers are:

    #{@backends.join("\n    ")}

Please make sure you have spelled everything correctly and try again. If this
error persists, please open an issue on GitHub.
EOH
    end
  end

  class GemNotInstalled < Error
    def initialize(name)
      @name = name
    end

    def to_s
      <<-EOH
I could not load the '#{@name}' gem. Please make sure the gem is installed on
your local system by running `gem install #{@name}`, or by adding the following
to your Gemfile:

    gem '#{@name}'

EOH
    end
  end
end


text:
package org.ado.biblio.encode;

import org.apache.commons.codec.digest.DigestUtils;

import java.security.SecureRandom;

/**
 * @author Andoni del Olmo
 * @since 16.02.16
 */
public class PasswordEncoder {

    public static PasswordHashed encode(final String password) {
        final byte[] saltBytes = new byte[32];
        new SecureRandom().nextBytes(saltBytes);
        final String salt = DigestUtils.sha256Hex(saltBytes);
        return new PasswordHashed(salt, DigestUtils.sha256Hex(salt + password));
    }
}


text:
(function() {
  var mongoose, txnSchema;

  mongoose = require("mongoose");

  txnSchema = new mongoose.Schema({
    customerId: String,
    plan: String,
    status: String,
    billingType: String,
    data: String,
    xeroId: String,
    amount: String
  });

  module.exports = mongoose.model("Txn", txnSchema);

}).call(this);


text:
// stdafx.cpp : source file that includes just the standard includes
// Gallio.MbUnitCppAdapter.TestResources.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information

#include "stdafx.h"


text:
title: "Link-o-rama #2"
author: arnehass
date: 2012-01-15
template: article.pug
tags: data, framsia, grunnlov, javascript, meetup, node.js, open, personlighetsvern, pipa, rekruttering as, sopa, uio
original: https://megoth.wordpress.com/2012/01/15/link-o-rama-2/
---

I dag har jeg lest mye – veldig mye syns jeg. Jeg har gått gjennom listen av tweets som ble favorisert i uken som var. Noe av det hadde jeg lest tidligere, og var mer en formalitet at jeg skumleste gjennom dem for å legge dem til i delicious.

Jeg innser at mesteparten av lesingen min foregår mens jeg sitter på trikken eller banen, på vei til noe og trenger å slå av tid. Konsumeringen ellers foregår ved at jeg oppdaterer meg på twitter-tidslinjen min, og favoriserer de tweetene som lenker til sider jeg har lyst å lese. Mtp tiden jeg har brukt på å lese meg opp på de sidene i dag, så innser jeg at jeg må begrense favoriseringen min. Så får vi se hvordan uken som kommer blir.

Personlighetsvern VS utlevering av åpne data

Men resultatet av lesingen er at jeg har en liste med sider jeg gjerne vil dele. Det viktigste temaet i uken som var er saken rundt Rekruttering AS, som Lars Storjord gjorde meg var på. Naturlig nok er det mest negativ kritikk jeg har lest.

Ber om innsyn hos flere

Bygger opp database med alle landets studenter

Boikott studentdatabase (Oppfordrer til boikott av database)

UiO avslår begjæring om innsyn i kandidatlister (Universitetet i Oslo nekter å gi fra seg studentregister, UiO stopper utlevering av studentdata)

Sammen mot Kunnskapsdepartementet

I sammenheng med dette temaet er også Lønna til 800.000 personer fritt tilgjengelig interessant å lese.

SOPA/PIPA/OPEN

Også aktuelt for tiden er arbeidet mot SOPA, i det den snart skal tas opp i kongressen.

The White House's SOPA response: Fight online piracy, but don't undermine the Internet

Why SOPA-Supporting News Networks Don't Mention SOPA At All: virker litt konspiratorisk, men god lesing uansett

Editorial: If SOPA passes in its current form, it will be a disaster for gamers and the games media worldwide

Endringer i grunnloven

Det har oppstått en del oppmerksomhet rundt arbeidet med de endringene som har blitt foreslått til grunnloven.

Fra rettsstat til menneskerettsstat – menneskerettighetene inn i Grunnloven

Politikere frykter ny grunnlov kan flytte makten fra dem til jurister

JavaScript

Har selvfølgelig lest litt fag-relevant (for meg) og.

Simplicity and JavaScript modules

Getting Started With RequireJS

Framsia

Var på en meetup med Framsia, og så noen interessante foredrag. Har tatt frem to her.

Difficult is OK

Step away from the for-loop!

Node.js

Jeg skal innrømme at jeg ikke har satt meg så veldig inn i node.js, men uansett interessant å lese flamewars.

Node.js is Cancer: Innlegget som startet diskusjonen

Node.js Cures Cancer: Godt svar #1

Diagnosis: No Cancer: Godt svar #2

Annen god lesing

My Guantánamo Nightmare

Jonas Gahr Støre: In defense of dialogue


text:
package es.moki.ratelimitj.hazelcast;

import com.hazelcast.config.Config;
import com.hazelcast.config.NetworkConfig;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;

class HazelcastTestFactory {

    static HazelcastInstance newStandaloneHazelcastInstance() {
        Config config = new Config();
        config.setProperty("hazelcast.logging.type", "slf4j");
        config.setProperty("hazelcast.shutdownhook.enabled", "false");
        NetworkConfig network = config.getNetworkConfig();
        network.getJoin().getTcpIpConfig().setEnabled(false);
        network.getJoin().getMulticastConfig().setEnabled(false);
        return Hazelcast.newHazelcastInstance(config);
    }
}


text:
<?php
/**
 * Contains \jamesiarmes\PhpEws\ArrayType\ArrayOfRuleOperationErrorsType.
 */

namespace jamesiarmes\PhpEws\ArrayType;

use \jamesiarmes\PhpEws\ArrayType;

/**
 * Represents an array of rule validation errors on each rule field that has an
 * error.
 *
 * @package php-ews\Array
 */
class ArrayOfRuleOperationErrorsType extends ArrayType
{
    /**
     * Represents a rule operation error.
     *
     * @since Exchange 2010
     *
     * @var \jamesiarmes\PhpEws\Type\RuleOperationErrorType[]
     */
    public $RuleOperationError;
}


text:
from pilot.util.container import execute

import logging
logger = logging.getLogger(__name__)

def get_core_count(job):
    """
    Return the core count.

    :param job: job object.
    :return: core count (int).
    """

    return 0

def add_core_count(corecount, core_counts=[]):
    """
    Add a core count measurement to the list of core counts.

    :param corecount: current actual core count (int).
    :param core_counts: list of core counts (list).
    :return: updated list of core counts (list).
    """

    return core_counts.append(corecount)

def set_core_counts(job):
    """
    Set the number of used cores.

    :param job: job object.
    :return:
    """

    if job.pgrp:
        cmd = "ps axo pgid,psr | sort | grep %d | uniq | awk '{print $1}' | grep -x %d | wc -l" % (job.pgrp, job.pgrp)
        exit_code, stdout, stderr = execute(cmd, mute=True)
        logger.debug('%s: %s' % (cmd, stdout))
        try:
            job.actualcorecount = int(stdout)
        except Exception as e:
            logger.warning('failed to convert number of actual cores to int: %s' % e)
        else:
            logger.debug('set number of actual cores to: %d' % job.actualcorecount)

            # overwrite the original core count and add it to the list
            job.corecount = job.actualcorecount
            job.corecounts = add_core_count(job.actualcorecount)
            logger.debug('current core counts list: %s' % str(job.corecounts))

    else:
        logger.debug('payload process group not set - cannot check number of cores used by payload')


text:
const path = require('path');
const axios = require('axios');
const fs = require('fs-extra');

const routes = ['A1', 'A2', 'B1', 'B2', 'C', 'BTC1', 'BTC2', 'D1', 'D2'];
const getBusStop = 'https://nextbus.comfortdelgro.com.sg/eventservice.svc/busstops';
const getBusRoute = 'https://nextbus.comfortdelgro.com.sg/eventservice.svc/pickuppoint';

const dataPath = path.join(__dirname, '../src/data/bus-stops.json');

/**
 * Download bus stop location information from ComfortDelGro's
 * NUS NextBus API
 */
async function downloadBusStops() {
  const busStopResponse = await axios.get(getBusStop);
  const data = busStopResponse.data.BusStopsResult.busstops;

  // Map bus stops to the correct shape
  const busStops = {};
  data.forEach((stop) => {
    // Check that all expected keys are here
    if (!stop.caption || !stop.latitude || !stop.longitude || !stop.name) {
      console.log(data);
      throw new Error('Incomplete data - key not found');
    }

    busStops[stop.name] = {
      // Human readable name for the stop
      name: stop.caption,
      // Location as a latlng tuple
      location: [stop.latitude, stop.longitude],
      // Used for accessing the next bus API
      code: stop.name,
      // Array to hold bus routes in the next step
      routes: [],
    };
  });

  // Insert the bus stops for each route into their bus stops
  await Promise.all(
    routes.map(async (routeCode) => {
      const response = await axios.get(getBusRoute, { params: { route_code: routeCode } });
      response.data.PickupPointResult.pickuppoint.forEach((point) => {
        if (!point) return;

        if (!busStops[point.busstopcode]) {
          console.warn(point);
          console.warn(`For route ${routeCode}`);
          return;
        }

        busStops[point.busstopcode].routes.push(routeCode);
      });
    }),
  );

  return fs.outputJSON(dataPath, Object.values(busStops), { spaces: 2 });
}

if (require.main === module) {
  downloadBusStops();
}


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

<title>NUnit - Samples</title>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<meta http-equiv="Content-Language" content="en-US">
<meta name="norton-safeweb-site-verification" content="tb6xj01p4hgo5x-8wscsmq633y11-e6nhk-bnb5d987bseanyp6p0uew-pec8j963qlzj32k5x9h3r2q7wh-vmy8bbhek5lnpp5w4p8hocouuq39e09jrkihdtaeknua" />
<link rel="stylesheet" type="text/css" href="nunit.css">
<link rel="shortcut icon" href="favicon.ico">

    NUnit
    Documentation

Samples

The samples installed with NUnit continue to be organized by language, with an additional
folder for Extensibility examples

C# Samples

Failures

This sample written in C# demonstrates 4 failing unit tests and one test
		that is not run.

Money

This is a C# version of the money example which is found in most xUnit
		implementations. Thanks to Kent Beck.

Syntax

Illustrates use of most Assert methods using both the classic and
	  constraint-based syntax in C#.

F# Samples

Failures

This sample written in F# demonstrates 4 failing unit tests and one test
		that is not run.

Money

This is a F# version of the money example which is found in most xUnit
		implementations. Thanks to Kent Beck.

Syntax

Illustrates use of most Assert methods using both the classic and
	  constraint-based syntax in F#.

VB.NET Samples

Failures

This sample written in VB.NET demonstrates 4 failing unit tests and
		one test that is not run.

Money

This is a VB.NET version of the money example which is found in most xUnit
		implementations. Thanks to Kent Beck.

Syntax

Illustrates use of most Assert methods using both the classic and
	  constraint-based syntax in VB.NET.

C++ Samples

Failures

This is the same example as the others with four failing unit
		tests and one ignored test.

Syntax

Illustrates use of most Assert methods using both the classic and
	  constraint-based syntax in C++.

Extensibility Examples

Minimal

The smallest possible Addin: it does nothing but is
		recognized by NUnit and listed in the Addins dialog.

SampleSuiteExtension

A "toy" SuiteBuilder. It recognizes a special attribute
	and identifies tests right in the suite extension. This example
	uses separate objects for the addin and the suite builder.

SampleFixtureExtension

A slightly more involved SuiteBuilder. It recognizes
	a special attribute and registers a test case builder to
	identify its tests. It inherits from NUnitTestFixture and
	so gets all the features of that class as well for free.
	This example uses the same object to implement both the
	addin and the suite builder.

NUnit 2.6.3

Getting Started

Writing Tests

Running Tests

Extensibility

Release Notes

Samples

License

NUnit Test Adapter

License

Release Notes

  Copyright © 2012 Charlie Poole. All Rights Reserved.


text:
;(function () {
  "use strict";

  angular.module('app')

    //
    // This service provides a set of convenience/utility methods that you can use throughout your app.
    //
    .factory('Application', function (StorageService, UserService, APP, Stopwatch, $log, $ionicPlatform, $ionicHistory,
                                      $ionicLoading, $ionicContentBanner, $translate, $timeout, $ionicScrollDelegate,
                                      $rootScope, $ionicPopup, $cordovaToast) {

      var deviceReady = false;
      var ionicPlatformReady = false;

      var appMessage = null;
      var appState = {};

      var init = function () {
        var w = logStarted('Application#init');

        UserService.init();

        logFinished(w);
      };

      var getStartPage = function () {
        var state = null;

        //
        // "initial page" logic - this determines the first page to be shown by the app.
        //
        // This way, we can guide the user through the onboarding process.
        //

        if (isInitialRun()) {
          state = 'app.intro';
        } else if (!isUserLoggedIn()) {
          state = 'login';
        } else {
          state = APP.routerDefaultState;
        }

        $log.info("Application#getStartPage - state = " + state);

        return {state: state, stateParams: null};
      };

      var gotoPage = function ($state, page, params, disableBackbutton, clearHistory) {

        // workaround for undesirable behavior when Ionic is showing the back button when we don't want it to
        if (disableBackbutton) {
          $ionicHistory.nextViewOptions({
            disableBack: true
          });
        }

        if (clearHistory) {
          $ionicHistory.clearHistory();
        }

        $state.go(page, params || {});
      };

      var gotoIntroPage = function ($state) {
        gotoPage($state, "app.intro", null, true);
      };

      var gotoUserProfilePage = function ($state, onboarding) {
        gotoPage($state, 'app.auth.userProfile', onboarding ? {mode: 'onboarding'} : {}, true, true);
      };

      var gotoStartPage = function ($state, clearHistory) {
        var page = getStartPage();

        // After redirecting the user to the start page we want to make sure we don't show a back-button.
        // This is why we preemptively clear the Ionic view history.
        gotoPage($state, page.state, page.stateParams, true, clearHistory);
      };

      var isInitialRun = function () {
        return StorageService.get("initialRun", "true") == "true";
      };

      var setInitialRun = function (initial) {
        StorageService.set("initialRun", initial ? "true" : "false");
      };

      var isUserLoggedIn = function () {
        return UserService.currentUser() !== null;
      };

      var showLoading = function (showBackdrop) {
        $ionicLoading.show({
          content: '',
          animation: 'fade-in',
          showBackdrop: showBackdrop,
          maxWidth: 200,
          showDelay: 0
        });
      };

      var hideLoading = function () {
        $ionicLoading.hide();
      };

      var resetForm = function (vm) {
        vm.form.$setPristine();
        vm.form.parent = vm;
        vm.error = {};
      };

      var getLogger = function (context) {
        return $log.getLogger(context);
      };

      var setMessage = function (message) {
        appMessage = message;
      };

      var getMessage = function () {
        var message = appMessage;
        appMessage = null;

        return message;
      };

      var setState = function (key, value) {
        appState[key] = value;
      };

      var getState = function (key) {
        var value = appState[key];

        return value;
      };

      var getAndClearState = function (key) {
        var value = appState[key];
        delete appState[key];

        return value;
      };

      var isObjectEmpty = function (object) {
        if (!object) {
          return true;
        }

        for (var key in object) {
          if (object.hasOwnProperty(key)) {
            return false;
          }
        }
        return true;
      };

      var isObjectNotEmpty = function (object) {
        return !isObjectEmpty(object);
      };

      var contentBannerInit = function (vm, controllerScope) {
        vm.closeContentBanner = null;

        // before we leave the view then close/destroy the ionic-content-banner, if any
        controllerScope.$on('$ionicView.beforeLeave', function () {
          if (vm.closeContentBanner) {
            vm.closeContentBanner();
            vm.closeContentBanner = null;
          }
        });
      };

      var contentBannerShow = function (vm, keys, intervalMs, autoCloseMs, type, param) {
        var messageKeys;
        var messageParam;

        if (typeof keys === 'object' && !Array.isArray(keys)) {
          messageKeys = keys.keys;
          messageParam = keys.param;
        } else {
          messageKeys = Array.isArray(keys) ? keys : [keys];
          messageParam = param;
        }

        if (!type) {
          type = 'info';
        }

        // SCROLL TO THE TOP OF THE SCREEN, OTHERWISE THE CONTENT BANNER MIGHT NOT BE VISIBLE ! (because it gets shown
        // at the top of the Ionic View). Wrap it in a 'timeout' as per Stackoverflow:
        // stackoverflow.com/questions/29247556/ionic-scrolltop-cannot-read-property-scrollto-of-null-still-exists-in-1-0-0

        $timeout(function() {
          $ionicScrollDelegate.scrollTop();
        }, 0);

        if (!intervalMs) {
          intervalMs = 3000;
        }

        if (autoCloseMs === undefined) {
          autoCloseMs = intervalMs * messageKeys.length;
        }

        $translate(messageKeys, messageParam).then(function (translations) {

          var texts = [];

          Object.keys(translations).forEach(function (key) {
            texts.push(translations[key]);
          });

          vm.closeContentBanner = $ionicContentBanner.show({
            text: texts,
            autoClose: autoCloseMs,
            interval: intervalMs,
            type: type
          });
        });
      };

      var errorMessage = function (vm, key, vars) {
        $translate(key, vars || {}).then(function (translation) {
          vm.error.message = translation;
        });
      };

      var clearErrorMessage = function (vm) {
        vm.error.message = null;
      };

      var logStarted = function (context, message) {
        var stopwatch = new Stopwatch(context);
        stopwatch.start();

        var msg = context ? context + ' - ' : '';
        msg = msg + (message || 'STARTED');

        $log.info(msg);

        return stopwatch;
      };

      var logFinished = function (stopwatch, message) {
        logEnded($log.info, stopwatch, message);
      };

      var logError = function (stopwatch, message) {
        logEnded($log.error, stopwatch, message);
      };

      function logEnded(fn, stopwatch, message) {
        stopwatch.stop();

        var context = stopwatch.context;
        var msg = context ? context + ' - ' : '';
        msg = msg + (message || 'FINISHED');

        fn(msg + ' - DURATION: ' + stopwatch.fmtTime());
      }

      var getEmail = function () {
        return StorageService.get("email", null);
      };

      var setEmail = function (value) {
        StorageService.set("email", value);
      };

      var isDeviceReady = function () {
        return deviceReady;
      };

      var setDeviceReady = function (ready) {
        deviceReady = ready;
      };

      var isIonicPlatformReady = function () {
        return ionicPlatformReady;
      };

      var setIonicPlatformReady = function (ready) {
        ionicPlatformReady = ready;
      };

      var deregisterBackbuttonHandler = null;

      var registerBackbuttonHandler = function () {

        unregisterBackbuttonHandler();

        // Prevent the Android hardware back button from exiting the app 'unvoluntarily' - ask the user to confirm; see:
        //
        // http://www.gajotres.net/ionic-framework-handling-android-back-button-like-a-pro/
        // http://forum.ionicframework.com/t/handling-the-hardware-back-buttons/1505/23
        //
        // If more flexibility is needed then one can implement something along these lines:
        //
        // https://gist.github.com/kyletns/93a510465e433c1981e1
        //
        deregisterBackbuttonHandler = $ionicPlatform.registerBackButtonAction(function (event) {

          if ($ionicHistory.backView() === null) {  // no more previous screen in the history stack, so "back" would exit
            var key = 'exit-popup.';

            $translate(key + 'text', {you: $rootScope._y}).then(function (translation) {

              $translate([key + 'title', key + 'ok-button', key + 'cancel-button']).then(function (translations) {

                $ionicPopup.confirm({
                  title: translations[key + 'title'],
                  template: translation,
                  cssClass: 'info-popup',
                  cancelText: translations[key + 'cancel-button'],
                  okText: translations[key + 'ok-button']
                }).then(function (res) {
                  if (res) {
                    ionic.Platform.exitApp();
                  }
                });

              });
            });

          } else {
            $ionicHistory.goBack();
          }
        }, 100);  // 100 = previous view

        return deregisterBackbuttonHandler;
      };

      var unregisterBackbuttonHandler = function () {
        if (deregisterBackbuttonHandler) {
          deregisterBackbuttonHandler();
          deregisterBackbuttonHandler = null;
        }
      };

      function doShowToast(message, displayLongOrShort) {
        if (window.cordova) {
          if (displayLongOrShort === 'short') {
            $cordovaToast.showShortCenter(message).then(function (success) {
              $log.debug("Success: showToastShort('" + message + "')");
            }, function (error) {
              $log.error("Error: showToastShort('" + message + "'), error: " + JSON.stringify(error));
            });
          } else {
            $cordovaToast.showLongCenter(message).then(function (success) {
              $log.debug("Success: showToastLong('" + message + "')");
            }, function (error) {
              $log.error("Error: showToastLong('" + message + "'), error: " + JSON.stringify(error));
            });
          }
        } else {
          $log.warn("NOTE - not running on device: showToast('" + message + "')");
        }
      }

      var showToast = function (messageOrKey, translateMessage, displayLongOrShort) {

        if (translateMessage) {

          $translate(messageOrKey).then(function (translation) {
            doShowToast(translation, displayLongOrShort);
          });

        } else {
          doShowToast(messageOrKey, displayLongOrShort);
        }
      };

      return {
        init: init,
        isInitialRun: isInitialRun,
        setInitialRun: setInitialRun,
        isUserLoggedIn: isUserLoggedIn,
        isDeviceReady: isDeviceReady,
        setDeviceReady: setDeviceReady,
        isIonicPlatformReady: isIonicPlatformReady,
        setIonicPlatformReady: setIonicPlatformReady,
        registerBackbuttonHandler: registerBackbuttonHandler,
        unregisterBackbuttonHandler: unregisterBackbuttonHandler,
        gotoPage: gotoPage,
        gotoStartPage: gotoStartPage,
        gotoIntroPage: gotoIntroPage,
        gotoUserProfilePage: gotoUserProfilePage,
        showLoading: showLoading,
        hideLoading: hideLoading,
        resetForm: resetForm,
        getLogger: getLogger,
        setMessage: setMessage,
        getMessage: getMessage,
        setState: setState,
        getState: getState,
        getAndClearState: getAndClearState,
        isObjectEmpty: isObjectEmpty,
        isObjectNotEmpty: isObjectNotEmpty,
        contentBannerInit: contentBannerInit,
        contentBannerShow: contentBannerShow,
        errorMessage: errorMessage,
        clearErrorMessage: clearErrorMessage,
        logStarted: logStarted,
        logFinished: logFinished,
        logError: logError,
        getEmail: getEmail,
        setEmail: setEmail,
        showToast: showToast
      };
    });
}());


text:
package com.sap.cloud.lm.sl.cf.persistence.query;

import java.sql.Connection;
import java.sql.SQLException;

@FunctionalInterface
public interface SqlQuery<R> {

    public R execute(Connection connection) throws SQLException;
}


text:
package com.sksamuel.elastic4s.requests.searches.queries.matches

case class FieldWithOptionalBoost(field: String, boost: Option[Double])


text:
#include "stdafx.h"
#include "CdapException.h"

Cask::CdapOdbc::CdapException::CdapException()
  : std::logic_error(nullptr)
  , sqlStatusCode(L"HY000")
  , errorCode(SQL_ERROR) {
}

Cask::CdapOdbc::CdapException::CdapException(const std::wstring& message)
  : std::logic_error(nullptr)
  , sqlStatusCode(L"HY000")
  , message(message)
  , errorCode(SQL_ERROR) {
}

Cask::CdapOdbc::CdapException::CdapException(const std::wstring& sqlStatusCode, const std::wstring& message)
  : std::logic_error(nullptr)
  , sqlStatusCode(sqlStatusCode)
  , message(message)
  , errorCode(SQL_ERROR) {
}

Cask::CdapOdbc::CdapException::CdapException(SQLRETURN errorCode, const std::wstring& sqlStatusCode, const std::wstring& message)
  : std::logic_error(nullptr)
  , sqlStatusCode(L"HY000")
  , message(message)
  , errorCode(errorCode) {
}

Cask::CdapOdbc::CdapException::CdapException(SQLRETURN errorCode, const std::wstring& message)
  : std::logic_error(nullptr)
  , sqlStatusCode(sqlStatusCode)
  , message(message)
  , errorCode(errorCode) {
}

Cask::CdapOdbc::CdapException::CdapException(const CdapException& other)
  : std::logic_error(nullptr)
  , sqlStatusCode(other.sqlStatusCode)
  , message(other.message)
  , errorCode(other.errorCode) {
}

Cask::CdapOdbc::CdapException::CdapException(CdapException&& other)
  : std::logic_error(nullptr)
  , sqlStatusCode(std::move(other.sqlStatusCode))
  , message(std::move(other.message))
  , errorCode(other.errorCode) {
  other.errorCode = SQL_ERROR;
}

void Cask::CdapOdbc::CdapException::operator=(const CdapException& other) {
  this->sqlStatusCode = other.sqlStatusCode;
  this->message = other.message;
  this->errorCode = other.errorCode;
}

void Cask::CdapOdbc::CdapException::operator=(CdapException&& other) {
  this->sqlStatusCode = std::move(other.sqlStatusCode);
  this->message = std::move(other.message);
  this->errorCode = other.errorCode;
  other.errorCode = SQL_ERROR;
}


text:
package com.mongodb.connection;

import org.bson.BsonBinaryWriter;
import org.bson.BsonBinaryWriterSettings;
import org.bson.BsonDocument;
import org.bson.BsonWriterSettings;
import org.bson.FieldNameValidator;
import org.bson.codecs.BsonValueCodecProvider;
import org.bson.codecs.Codec;
import org.bson.codecs.Encoder;
import org.bson.codecs.EncoderContext;
import org.bson.codecs.configuration.CodecRegistry;
import org.bson.io.BsonOutput;

import java.util.concurrent.atomic.AtomicInteger;

import static org.bson.codecs.configuration.CodecRegistries.fromProviders;

/**
 * Abstract base class for all MongoDB Wire Protocol request messages.
 */
abstract class RequestMessage {

    static final AtomicInteger REQUEST_ID = new AtomicInteger(1);

    // Allow an extra 16K to the maximum allowed size of a query or command document, so that, for example,
    // a 16M document can be upserted via findAndModify
    private static final int QUERY_DOCUMENT_HEADROOM = 16 * 1024;

    private static final CodecRegistry REGISTRY = fromProviders(new BsonValueCodecProvider());

    private final String collectionName;
    private final MessageSettings settings;
    private final int id;
    private final OpCode opCode;

    /**
     * Gets the next available unique message identifier.
     *
     * @return the message identifier
     */
    public static int getCurrentGlobalId() {
        return REQUEST_ID.get();
    }

    /**
     * Construct an instance without a collection name
     *
     * @param opCode   the op code of the message
     * @param settings the message settings
     */
    public RequestMessage(final OpCode opCode, final MessageSettings settings) {
        this(null, opCode, settings);
    }

    /**
     * Construct an instance.
     *
     * @param collectionName the collection name
     * @param opCode         the op code of the message
     * @param settings       the message settings
     */
    public RequestMessage(final String collectionName, final OpCode opCode, final MessageSettings settings) {
        this.collectionName = collectionName;
        this.settings = settings;
        id = REQUEST_ID.getAndIncrement();
        this.opCode = opCode;
    }

    /**
     * Gets the message id.
     *
     * @return the message id
     */
    public int getId() {
        return id;
    }

    /**
     * Gets the op code of the message.
     *
     * @return the op code
     */
    public OpCode getOpCode() {
        return opCode;
    }

    /**
     * Gets the collection namespace to send the message to.
     *
     * @return the namespace, which may be null for some message types
     */
    public String getNamespace() {
        return getCollectionName() != null ? getCollectionName() : null;
    }

    /**
     * Gets the message settings.
     *
     * @return the message settings
     */
    public MessageSettings getSettings() {
        return settings;
    }

    /**
     * Encoded the message to the given output.
     *
     * @param bsonOutput the output
     * @return the next message to encode, if the current message is unable to fit all of its contents in a single message due to limits
     * being exceeded
     */
    public RequestMessage encode(final BsonOutput bsonOutput) {
        int messageStartPosition = bsonOutput.getPosition();
        writeMessagePrologue(bsonOutput);
        RequestMessage nextMessage = encodeMessageBody(bsonOutput, messageStartPosition);
        backpatchMessageLength(messageStartPosition, bsonOutput);
        return nextMessage;
    }

    /**
     * Writes the message prologue to the given output.
     *
     * @param bsonOutput the output
     */
    protected void writeMessagePrologue(final BsonOutput bsonOutput) {
        bsonOutput.writeInt32(0); // length: will set this later
        bsonOutput.writeInt32(id);
        bsonOutput.writeInt32(0); // response to
        bsonOutput.writeInt32(opCode.getValue());
    }

    /**
     * Encode the message body to the given output.
     *
     * @param bsonOutput the output
     * @param messageStartPosition the start position of the message
     * @return the next message to encode, if the contents of this message need to overflow into the next
     */
    protected abstract RequestMessage encodeMessageBody(final BsonOutput bsonOutput, final int messageStartPosition);

    /**
     * Appends a document to the message.
     *
     * @param document the document
     * @param bsonOutput the output
     * @param validator the field name validator
     * @param <T> the document type
     */
    protected <T> void addDocument(final BsonDocument document, final BsonOutput bsonOutput,
                                   final FieldNameValidator validator) {
        addDocument(document, getCodec(document), EncoderContext.builder().build(), bsonOutput, validator,
                    settings.getMaxDocumentSize() + QUERY_DOCUMENT_HEADROOM);
    }

    /**
     * Appends a document to the message that is intended for storage in a collection.
     *
     * @param document the document
     * @param bsonOutput the output
     * @param validator the field name validator
     */
    protected void addCollectibleDocument(final BsonDocument document, final BsonOutput bsonOutput,
                                          final FieldNameValidator validator) {
        addDocument(document, getCodec(document), EncoderContext.builder().isEncodingCollectibleDocument(true).build(), bsonOutput,
                    validator, settings.getMaxDocumentSize());
    }

    /**
     * Backpatches the message length into the beginning of the message.
     *
     * @param startPosition the start position of the message
     * @param bsonOutput the output
     */
    protected void backpatchMessageLength(final int startPosition, final BsonOutput bsonOutput) {
        int messageLength = bsonOutput.getPosition() - startPosition;
        bsonOutput.writeInt32(bsonOutput.getPosition() - messageLength, messageLength);
    }

    /**
     * Gets the collection name, which may be null for some message types
     *
     * @return the collection name
     */
    protected String getCollectionName() {
        return collectionName;
    }

    @SuppressWarnings("unchecked")
    Codec<BsonDocument> getCodec(final BsonDocument document) {
        return (Codec<BsonDocument>) REGISTRY.get(document.getClass());
    }

    private <T> void addDocument(final T obj, final Encoder<T> encoder, final EncoderContext encoderContext,
                                 final BsonOutput bsonOutput, final FieldNameValidator validator, final int maxDocumentSize) {
        BsonBinaryWriter writer = new BsonBinaryWriter(new BsonWriterSettings(),
                                                       new BsonBinaryWriterSettings(maxDocumentSize), bsonOutput, validator);
        try {
            encoder.encode(writer, obj, encoderContext);
        } finally {
            writer.close();
        }
    }

    enum OpCode {
        OP_REPLY(1),
        OP_MSG(1000),
        OP_UPDATE(2001),
        OP_INSERT(2002),
        OP_QUERY(2004),
        OP_GETMORE(2005),
        OP_DELETE(2006),
        OP_KILL_CURSORS(2007);

        OpCode(final int value) {
            this.value = value;
        }

        private final int value;

        public int getValue() {
            return value;
        }
    }
}


text:
typedef enum
{
	DomNodeType_Unknown = 0,
	DomNodeType_Document,
	DomNodeType_Comment,
	DomNodeType_Element,
	DomNodeType_Text,
	DomNodeType_Data
} DomNodeType;

#pragma mark -

@class SamuraiDocument;
@class SamuraiStyleSheet;

@interface SamuraiDomNode : SamuraiTreeNode<NSDictionaryProtocol, NSMutableDictionaryProtocol>

@prop_strong( NSNumber *,				id );
@prop_strong( NSString *,				tag );
@prop_strong( NSString *,				text );
@prop_assign( DomNodeType,				type );
@prop_strong( NSMutableDictionary *,	attr );

@prop_unsafe( SamuraiDocument *,		document );
@prop_unsafe( SamuraiDomNode *,			parent );
@prop_unsafe( SamuraiDomNode *,			prev );
@prop_unsafe( SamuraiDomNode *,			next );

+ (instancetype)domNode;

- (void)attach:(SamuraiDocument *)document;
- (void)detach;

@end

#endif	// #if (TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR)


text:
NSString * const PEGKitErrorDomain = @"PEGKitErrorDomain";
NSString * const PEGKitErrorRangeKey = @"range";
NSString * const PEGKitErrorLineNumberKey = @"lineNumber";

NSInteger PEGKitRecognitionErrorCode = 1;
NSString * const PEGKitRecognitionTokenMatchFailed = @"Failed to match next input token";
NSString * const PEGKitRecognitionPredicateFailed = @"Predicate failed";

@interface NSObject ()
- (void)parser:(PKParser *)p didFailToMatch:(PKAssembly *)a;
@end

@interface PKAssembly ()
- (void)consume:(PKToken *)tok;
@property (nonatomic, readwrite, retain) NSMutableArray *stack;
@end

@interface PKParser ()
@property (nonatomic, assign, readwrite) id delegate; // weak ref
@property (nonatomic, retain) PKRecognitionException *exception;
@property (nonatomic, retain) NSMutableArray *lookahead;
@property (nonatomic, retain) NSMutableArray *markers;
@property (nonatomic, assign) NSInteger p;
@property (nonatomic, assign, readonly) BOOL isSpeculating;
@property (nonatomic, retain) NSCountedSet *resyncSet;
@property (nonatomic, retain) NSMutableArray *tokenSource;
@property (nonatomic, assign) NSUInteger tokenSourceIndex;
@property (nonatomic, assign) NSUInteger tokenSourceCount;

- (NSInteger)tokenKindForString:(NSString *)str;
- (NSString *)stringForTokenKind:(NSInteger)tokenKind;
- (BOOL)lookahead:(NSInteger)x predicts:(NSInteger)tokenKind;

- (void)discard;

// error recovery
- (void)pushFollow:(NSInteger)tokenKind;
- (void)popFollow:(NSInteger)tokenKind;
- (BOOL)resync;

// backtracking
- (NSInteger)mark;
- (void)unmark;
- (void)seek:(NSInteger)index;
- (void)sync:(NSInteger)i;
- (void)fill:(NSInteger)n;

// memoization
- (BOOL)alreadyParsedRule:(NSMutableDictionary *)memoization;
- (void)memoize:(NSMutableDictionary *)memoization atIndex:(NSInteger)startTokenIndex failed:(BOOL)failed;
- (void)clearMemo;
@end

@implementation PKParser

- (instancetype)init {
    self = [self initWithDelegate:nil];
    return self;
}

- (instancetype)initWithDelegate:(id)d {
    self = [super init];
    if (self) {
        self.delegate = d;
        self.enableActions = YES;

        // create a single exception for reuse in control flow
        self.exception = [[[PKRecognitionException alloc] init] autorelease];

        self.tokenKindTab = [NSMutableDictionary dictionary];

        self.tokenKindNameTab = [NSMutableArray array];
        _tokenKindNameTab[TOKEN_KIND_BUILTIN_INVALID] = @"Invalid";
        _tokenKindNameTab[TOKEN_KIND_BUILTIN_NUMBER] = @"Number";
        _tokenKindNameTab[TOKEN_KIND_BUILTIN_QUOTEDSTRING] = @"Quoted String";
        _tokenKindNameTab[TOKEN_KIND_BUILTIN_SYMBOL] = @"Symbol";
        _tokenKindNameTab[TOKEN_KIND_BUILTIN_WORD] = @"Word";
        _tokenKindNameTab[TOKEN_KIND_BUILTIN_WHITESPACE] = @"Whitespace";
        _tokenKindNameTab[TOKEN_KIND_BUILTIN_COMMENT] = @"Comment";
        _tokenKindNameTab[TOKEN_KIND_BUILTIN_DELIMITEDSTRING] = @"Delimited String";
        _tokenKindNameTab[TOKEN_KIND_BUILTIN_URL] = @"URL";
        _tokenKindNameTab[TOKEN_KIND_BUILTIN_EMAIL] = @"Email";
        _tokenKindNameTab[TOKEN_KIND_BUILTIN_TWITTER] = @"Twitter";
        _tokenKindNameTab[TOKEN_KIND_BUILTIN_HASHTAG] = @"Hashtag";
        _tokenKindNameTab[TOKEN_KIND_BUILTIN_EMPTY] = @"Empty";
        _tokenKindNameTab[TOKEN_KIND_BUILTIN_ANY] = @"Any";
    }
    return self;
}

- (void)dealloc {
    self.delegate = nil;
    self.tokenizer = nil;
    self.assembly = nil;
    self.exception = nil;
    self.lookahead = nil;
    self.markers = nil;
    self.tokenKindTab = nil;
    self.tokenKindNameTab = nil;
    self.resyncSet = nil;
    self.startRuleName = nil;
    self.statementTerminator = nil;
    self.singleLineCommentMarker = nil;
    self.multiLineCommentStartMarker = nil;
    self.multiLineCommentEndMarker = nil;
    self.blockStartMarker = nil;
    self.blockEndMarker = nil;
    self.braces = nil;
    [super dealloc];
}

#pragma mark -
#pragma mark PKTokenizerDelegate

- (NSInteger)tokenizer:(PKTokenizer *)t tokenKindForStringValue:(NSString *)str {
    NSParameterAssert([str length]);
    return [self tokenKindForString:str];
}

- (NSInteger)tokenKindForString:(NSString *)str {
    NSInteger tokenKind = TOKEN_KIND_BUILTIN_INVALID;

    id obj = self.tokenKindTab[str];
    if (obj) {
        tokenKind = [obj integerValue];
    }

    return tokenKind;
}

- (NSString *)stringForTokenKind:(NSInteger)tokenKind {
    NSString *str = nil;

    if (TOKEN_KIND_BUILTIN_EOF == tokenKind) {
        str = [[PKToken EOFToken] stringValue];
    } else {
        str = self.tokenKindNameTab[tokenKind];
    }

    return str;
}

- (id)parseStream:(NSInputStream *)input error:(NSError **)outError {
    NSParameterAssert(input);

    [input scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [input open];

    PKTokenizer *t = _tokenizer;

    if (t) {
        t.stream = input;
    } else {
        t = [PKTokenizer tokenizerWithStream:input];
    }

    id result = [self parseWithTokenizer:t error:outError];

    [input close];
    [input removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];

    return result;
}

- (id)parseString:(NSString *)input error:(NSError **)outError {
    NSParameterAssert(input);

    PKTokenizer *t = _tokenizer;

    if (t) {
        t.string = input;
    } else {
        t = [PKTokenizer tokenizerWithString:input];
    }

    id result = [self parseWithTokenizer:t error:outError];
    return result;
}

- (id)parseTokens:(NSArray *)input error:(NSError **)outError {

    self.tokenSource = [[input mutableCopy] autorelease];
    self.tokenSourceIndex = 0;
    self.tokenSourceCount = [_tokenSource count];

    id result = [self parse:outError];
    return result;
}

- (id)parseWithTokenizer:(PKTokenizer *)t error:(NSError **)outError {

    // setup tokenizer
    self.tokenizer = t;
    self.tokenizer.delegate = self;

    id result = [self parse:outError];
    return result;
}

- (id)parse:(NSError **)outError {
    id result = nil;

    self.assembly = [PKAssembly assembly];

    if (_silentlyConsumesWhitespace) {
        _tokenizer.whitespaceState.reportsWhitespaceTokens = YES;
        _assembly.preservesWhitespaceTokens = YES;
    }

    // setup speculation
    self.p = 0;
    self.lookahead = [NSMutableArray array];
    self.markers = [NSMutableArray array];

    if (_enableAutomaticErrorRecovery) {
        self.resyncSet = [NSCountedSet set];
    }

    [self clearMemo];

    @try {

        @autoreleasepool {
            // parse
            [self start];

            //NSLog(@"%@", _assembly);

            // get result
            if (_assembly.target) {
                result = _assembly.target;
            } else {
                result = _assembly;
            }

            [result retain]; // +1
        }
        [result autorelease]; // -1

    }
    @catch (PKRecognitionException *rex) {
        NSString *domain = PEGKitErrorDomain;
        NSString *name = rex.currentName;
        NSString *reason = rex.currentReason;
        NSLog(@"%@: %@", name, reason);

        if (outError) {
            *outError = [self errorWithDomain:domain name:name reason:reason range:rex.range lineNumber:rex.lineNumber];
        } else {
            [rex raise];
        }
    }
    @catch (NSException *ex) {
        NSString *domain = PEGKitErrorDomain;
        NSString *name = [ex name];
        NSString *reason = [ex reason];
        NSLog(@"%@", reason);

        if (outError) {
            *outError = [self errorWithDomain:domain name:name reason:reason range:NSMakeRange(NSNotFound, 0) lineNumber:0];
        } else {
            [ex raise];
        }
    }
    @finally {
        self.tokenSource = nil;
        self.tokenSourceIndex = 0;
        self.tokenSourceCount = 0;
        self.tokenizer.string = nil;
        self.assembly = nil;
        self.lookahead = nil;
        self.markers = nil;
        self.resyncSet = nil;
    }

    return result;
}

- (NSError *)errorWithDomain:(NSString *)domain name:(NSString *)name reason:(NSString *)reason range:(NSRange)r lineNumber:(NSUInteger)lineNum {
    NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];

    // get description
    name = name ? name : NSLocalizedString(@"A parsing recognition exception occured.", @"");
    [userInfo setObject:name forKey:NSLocalizedDescriptionKey];

    // get reason
    reason = reason ? reason : @"";
    userInfo[NSLocalizedFailureReasonErrorKey] = reason;
    userInfo[PEGKitErrorRangeKey] = [NSValue valueWithRange:r];

    id lineNumVal = nil;
    if (NSNotFound == lineNum) {
        lineNumVal = NSLocalizedString(@"Unknown", @"");
    } else {
        lineNumVal = @(lineNum);
    }
    userInfo[PEGKitErrorLineNumberKey] = lineNumVal;

    // convert to NSError
    NSError *err = [NSError errorWithDomain:PEGKitErrorDomain code:PEGKitRecognitionErrorCode userInfo:[[userInfo copy] autorelease]];
    return err;
}

- (void)match:(NSInteger)tokenKind discard:(BOOL)discard {
    NSParameterAssert(tokenKind != TOKEN_KIND_BUILTIN_INVALID);
    NSAssert(_lookahead, @"");

    // always match empty without consuming
    if (TOKEN_KIND_BUILTIN_EMPTY == tokenKind) return;

    PKToken *lt = LT(1); // NSLog(@"%@", lt);

    BOOL matches = lt.tokenKind == tokenKind || (TOKEN_KIND_BUILTIN_ANY == tokenKind && PKTokenTypeEOF != lt.tokenType);

    if (matches) {
        if (TOKEN_KIND_BUILTIN_EOF != tokenKind) {
            [self consume:lt];
            if (discard) [self discard];
        }
    } else {
        NSString *msg = [NSString stringWithFormat:@"Expected : %@\n", [self stringForTokenKind:tokenKind]];
        [self raise:msg];
    }
}

- (void)consume:(PKToken *)tok {
    if (!self.isSpeculating) {
        [_assembly consume:tok];
        //NSLog(@"%@", _assembly);
    }

    self.p++;

    // have we hit end of buffer when not backtracking?
    if (_p == [_lookahead count] && !self.isSpeculating) {
        // if so, it's an opp to start filling at index 0 again
        self.p = 0;
        [_lookahead removeAllObjects]; // size goes to 0, but retains memory on heap
        [self clearMemo]; // clear all rule_memo dictionaries
    }

    [self sync:1];
}

- (void)discard {
    if (self.isSpeculating) return;

    NSAssert(![_assembly isStackEmpty], @"");
    [_assembly pop];
}

- (void)fireDelegateSelector:(SEL)sel {
    if (self.isSpeculating) return;

    if (_delegate && [_delegate respondsToSelector:sel]) {
        [_delegate performSelector:sel withObject:self withObject:_assembly];
    }
}

- (void)fireSyntaxSelector:(SEL)sel withRuleName:(NSString *)ruleName {
    if (self.isSpeculating) return;

    if (_delegate && [_delegate respondsToSelector:sel]) {
        [_delegate performSelector:sel withObject:self withObject:ruleName];
    }
}

- (PKToken *)LT:(NSInteger)i {
    PKToken *tok = nil;

    for (;;) {
        [self sync:i];

        NSUInteger idx = _p + i - 1;
        NSAssert(idx < [_lookahead count], @"");

        tok = _lookahead[idx];
        if (_silentlyConsumesWhitespace && tok.isWhitespace) {
            [self consume:tok];
        } else {
            break;
        }
    }

    return tok;
}

- (NSInteger)LA:(NSInteger)i {
    return [LT(i) tokenKind];
}

- (double)LD:(NSInteger)i {
    return [LT(i) doubleValue];
}

- (NSString *)LS:(NSInteger)i {
    return [LT(i) stringValue];
}

- (NSInteger)mark {
    [_markers addObject:@(_p)];
    return _p;
}

- (void)unmark {
    NSInteger marker = [[_markers lastObject] integerValue];
    [_markers removeLastObject];

    [self seek:marker];
}

- (void)seek:(NSInteger)index {
    self.p = index;
}

- (BOOL)isSpeculating {
    return [_markers count] > 0;
}

- (void)sync:(NSInteger)i {
    NSInteger lastNeededIndex = _p + i - 1;
    NSInteger lastFullIndex = [_lookahead count] - 1;

    if (lastNeededIndex > lastFullIndex) { // out of tokens ?
        NSInteger n = lastNeededIndex - lastFullIndex; // get n tokens
        [self fill:n];
    }
}

- (void)fill:(NSInteger)n {
    for (NSInteger i = 0; i <= n; ++i) { // <= ?? fetches an extra lookahead tok
        PKToken *tok = [self nextToken];
        [_lookahead addObject:tok];
    }
}

- (PKToken *)nextToken {
    PKToken *tok = nil;

    if (_tokenSource) {
        NSAssert(_tokenSource, @"");
        if (_tokenSourceIndex < _tokenSourceCount) {
            tok = [_tokenSource objectAtIndex:_tokenSourceIndex];
            ++self.tokenSourceIndex;
        } else {
            tok = [PKToken EOFToken];
        }
    } else {
        NSAssert(_tokenizer, @"");
        tok = [_tokenizer nextToken];
    }

    NSAssert(tok, @"");

    // set token kind
    if (TOKEN_KIND_BUILTIN_INVALID == tok.tokenKind) {
        tok.tokenKind = [self tokenKindForToken:tok];
    }

    //NSLog(@"-nextToken: %@", [tok debugDescription]);
    return tok;
}

- (NSInteger)tokenKindForToken:(PKToken *)tok {
    NSString *key = tok.stringValue;

    NSInteger x = tok.tokenKind;

    if (TOKEN_KIND_BUILTIN_INVALID == x) {
        x = [self tokenKindForString:key];

        if (TOKEN_KIND_BUILTIN_INVALID == x) {
            x = tok.tokenType;
        }
    }

    return x;
}

- (void)raiseFormat:(NSString *)fmt, ... {
    va_list vargs;
    va_start(vargs, fmt);

    NSString *str = [[[NSString alloc] initWithFormat:fmt arguments:vargs] autorelease];

    va_end(vargs);

    //PKToken *lt = LT(1);
    //NSUInteger lineNum = lt.lineNumber;
    //NSRange r = NSMakeRange(lt.offset, [lt.stringValue length]);

    //_exception.currentName = PEGKitRecognitionSpeculationFailed;
    _exception.currentReason = str;
    //_exception.lineNumber = lineNum;
    //_exception.range = r;

    //NSLog(@"%@", str);

    // reuse
    @throw _exception;
}

- (void)raiseInRange:(NSRange)r lineNumber:(NSUInteger)lineNum name:(NSString *)name format:(NSString *)fmt, ... {
    va_list vargs;
    va_start(vargs, fmt);

    NSString *str = [[[NSString alloc] initWithFormat:fmt arguments:vargs] autorelease];

    va_end(vargs);

    _exception.currentName = name;
    _exception.currentReason = str;
    _exception.lineNumber = lineNum;
    _exception.range = r;

    //NSLog(@"%@", str);

    // reuse
    @throw _exception;
}

- (void)raise:(NSString *)msg {
    [self raiseWithName:PEGKitRecognitionTokenMatchFailed message:msg];
}

- (void)raiseWithName:(NSString *)name message:(NSString *)msg {
    PKToken *lt = LT(1);

    NSUInteger lineNum = lt.lineNumber;
    //NSAssert(NSNotFound != lineNum, @"");

    NSRange r = NSMakeRange(lt.offset, [lt.stringValue length]);

    id after = @"";
    id found = @"";
    NSString *fmt = @"%@\nLine : %@\n%@%@";

    if (_enableVerboseErrorReporting) {
        fmt = @"%@\nLine : %@\nNear : %@\nFound : %@";
        after = [NSMutableString string];
        NSString *delim = _silentlyConsumesWhitespace ? @"" : @" ";

        for (PKToken *tok in [_lookahead reverseObjectEnumerator]) {
            if (tok.lineNumber < lineNum - 1) break;
            if (tok.lineNumber == lineNum) {
                [after insertString:[NSString stringWithFormat:@"%@%@", tok.stringValue, delim] atIndex:0];
            }
        }

        found = lt ? lt.stringValue : @"-nothing-";
    }

    id lineNumVal = NSNotFound == lineNum ? @"Unknown" : @(lineNum);
    [self raiseInRange:r lineNumber:lineNum name:PEGKitRecognitionTokenMatchFailed format:fmt, msg, lineNumVal, after, found];
}

- (void)pushFollow:(NSInteger)tokenKind {
    NSParameterAssert(TOKEN_KIND_BUILTIN_INVALID != tokenKind);
    if (!_enableAutomaticErrorRecovery) return;

    NSAssert(_resyncSet, @"");
    [_resyncSet addObject:@(tokenKind)];
}

- (void)popFollow:(NSInteger)tokenKind {
    NSParameterAssert(TOKEN_KIND_BUILTIN_INVALID != tokenKind);
    if (!_enableAutomaticErrorRecovery) return;

    NSAssert(_resyncSet, @"");
    [_resyncSet removeObject:@(tokenKind)];
}

- (BOOL)resync {
    BOOL result = NO;

    if (_enableAutomaticErrorRecovery) {
        for (;;) {
            //NSLog(@"\n\nLT 1: '%@'\n%@\nla: %@\nresyncSet: %@", LT(1), _assembly, _lookahead, _resyncSet);

            PKToken *lt = LT(1);

            NSAssert([_resyncSet count], @"");
            result = [_resyncSet containsObject:@(lt.tokenKind)];

            if (result) {
                [self fireDelegateSelector:@selector(parser:didFailToMatch:)];
                break;
            }

            if (lt.isEOF) break;

            [self consume:lt];
        }
    }

    return result;
}

- (BOOL)predicts:(NSInteger)firstTokenKind, ... {
    NSParameterAssert(firstTokenKind != TOKEN_KIND_BUILTIN_INVALID);

    NSInteger la = LA(1);

    if ([self lookahead:la predicts:firstTokenKind]) {
        return YES;
    }

    BOOL result = NO;

    va_list vargs;
    va_start(vargs, firstTokenKind);

    int nextTokenKind;
    while ((nextTokenKind = va_arg(vargs, int))) {
        if ([self lookahead:la predicts:nextTokenKind]) {
            result = YES;
            break;
        }
    }

    va_end(vargs);

    return result;
}

- (BOOL)lookahead:(NSInteger)la predicts:(NSInteger)tokenKind {
    BOOL result = NO;

    if (TOKEN_KIND_BUILTIN_ANY == tokenKind && la != TOKEN_KIND_BUILTIN_EOF) {
        result = YES;
    } else if (la == tokenKind) {
        result = YES;
    }

    return result;
}

- (BOOL)speculate:(PKSSpeculateBlock)block {
    NSParameterAssert(block);

    BOOL success = YES;
    [self mark];

    @try {
        if (block) block();
    }
    @catch (PKRecognitionException *ex) {
        success = NO;
    }

    [self unmark];
    return success;
}

- (void)execute:(PKSActionBlock)block {
    NSParameterAssert(block);
    if (self.isSpeculating || !_enableActions) return;

    if (block) block();
}

- (void)tryAndRecover:(NSInteger)tokenKind block:(PKSRecoverBlock)block completion:(PKSRecoverBlock)completion {
    NSParameterAssert(block);
    NSParameterAssert(completion);

    [self pushFollow:tokenKind];
    @try {
        block();
    }
    @catch (PKRecognitionException *ex) {
        if ([self resync]) {
            completion();
        } else {
            @throw ex;
        }
    }
    @finally {
        [self popFollow:tokenKind];
    }
}

- (BOOL)test:(PKSPredicateBlock)block {
    NSParameterAssert(block);

    BOOL result = YES;
    if (block) result = block();
    return result;
}

- (void)testAndThrow:(PKSPredicateBlock)block {
    NSParameterAssert(block);

    if (![self test:block]) {
        [self raiseWithName:PEGKitRecognitionPredicateFailed message:@""];
    }
}

- (void)parseRule:(SEL)ruleSelector withMemo:(NSMutableDictionary *)memoization {
    BOOL failed = NO;
    NSInteger startTokenIndex = self.p;
    if (self.isSpeculating && [self alreadyParsedRule:memoization]) return;

    @try { [self performSelector:ruleSelector]; }
    @catch (PKRecognitionException *ex) { failed = YES; @throw ex; }
    @finally {
        if (self.isSpeculating) [self memoize:memoization atIndex:startTokenIndex failed:failed];
    }
}

- (BOOL)alreadyParsedRule:(NSMutableDictionary *)memoization {

    id idxKey = @(self.p);
    NSNumber *memoObj = memoization[idxKey];
    if (!memoObj) return NO;

    NSInteger memo = [memoObj integerValue];
    if (FAILED == memo) {
        [self raiseFormat:@"already failed prior attempt at start token index %@", idxKey];
    }

    [self seek:memo];
    return YES;
}

- (void)memoize:(NSMutableDictionary *)memoization atIndex:(NSInteger)startTokenIndex failed:(BOOL)failed {
    id idxKey = @(startTokenIndex);

    NSInteger stopTokenIdex = failed ? FAILED : self.p;
    id idxVal = @(stopTokenIdex);

    memoization[idxKey] = idxVal;
}

- (void)clearMemo {

}

- (BOOL)popBool {
    id obj = [_assembly pop];
    return [obj boolValue];
}

- (NSInteger)popInteger {
    id obj = [_assembly pop];
    return [obj integerValue];
}

- (NSUInteger)popUnsignedInteger {
    id obj = [_assembly pop];
    return [obj unsignedIntegerValue];
}

- (float)popFloat {
    id obj = [_assembly pop];
    if ([obj respondsToSelector:@selector(floatValue)]) {
        return [obj floatValue];
    } else {
        return [(PKToken *)obj doubleValue];
    }
}

- (double)popDouble {
    id obj = [_assembly pop];
    if ([obj respondsToSelector:@selector(doubleValue)]) {
        return [obj doubleValue];
    } else {
        return [(PKToken *)obj doubleValue];
    }
}

- (PKToken *)popToken {
    PKToken *tok = [_assembly pop];
    NSAssert([tok isKindOfClass:[PKToken class]], @"");
    return tok;
}

- (NSString *)popString {
    id obj = [_assembly pop];
    if ([obj respondsToSelector:@selector(stringValue)]) {
        return [obj stringValue];
    } else {
        return [obj description];
    }
}

- (NSString *)popQuotedString {
    NSString *str = [self popString];
    return [str stringByTrimmingQuotes];
}

- (void)pushBool:(BOOL)yn {
    [_assembly push:(id)(yn ? kCFBooleanTrue : kCFBooleanFalse)];
}

- (void)pushInteger:(NSInteger)i {
    [_assembly push:[NSNumber numberWithInteger:i]];
}

- (void)pushUnsignedInteger:(NSUInteger)u {
    [_assembly push:[NSNumber numberWithUnsignedInteger:u]];
}

- (void)pushFloat:(float)f {
    [_assembly push:[NSNumber numberWithFloat:f]];
}

- (void)pushDouble:(double)d {
    [_assembly push:[NSNumber numberWithDouble:d]];
}

- (void)pushAll:(NSArray *)a {
    for (id obj in a) {
        [_assembly push:obj];
    }
}

- (NSArray *)reversedArray:(NSArray *)inArray {
    return [inArray reversedMutableArray];
}

- (void)start {
    NSAssert2(0, @"%s is an abstract method and must be implemented in %@", __PRETTY_FUNCTION__, [self class]);
}

- (void)matchEOF:(BOOL)discard {
    [self match:TOKEN_KIND_BUILTIN_EOF discard:discard];
}

- (void)matchAny:(BOOL)discard {
    [self match:TOKEN_KIND_BUILTIN_ANY discard:discard];
}

- (void)matchEmpty:(BOOL)discard {
    NSParameterAssert(!discard);
}

- (void)matchWord:(BOOL)discard {
    [self match:TOKEN_KIND_BUILTIN_WORD discard:discard];
}

- (void)matchNumber:(BOOL)discard {
    [self match:TOKEN_KIND_BUILTIN_NUMBER discard:discard];
}

- (void)matchSymbol:(BOOL)discard {
    [self match:TOKEN_KIND_BUILTIN_SYMBOL discard:discard];
}

- (void)matchComment:(BOOL)discard {
    [self match:TOKEN_KIND_BUILTIN_COMMENT discard:discard];
}

- (void)matchWhitespace:(BOOL)discard {
    [self match:TOKEN_KIND_BUILTIN_WHITESPACE discard:discard];
}

- (void)matchQuotedString:(BOOL)discard {
    [self match:TOKEN_KIND_BUILTIN_QUOTEDSTRING discard:discard];
}

- (void)matchDelimitedString:(BOOL)discard {
    [self match:TOKEN_KIND_BUILTIN_DELIMITEDSTRING discard:discard];
}

- (void)matchURL:(BOOL)discard {
    [self match:TOKEN_KIND_BUILTIN_URL discard:discard];
}

- (void)matchEmail:(BOOL)discard {
    [self match:TOKEN_KIND_BUILTIN_EMAIL discard:discard];
}

@end


text:
require 'nmea_plus/message/ais/vdm_payload/vdm_msg_cnb'

module NMEAPlus
  module Message
    module AIS
      module VDMPayload
        # AIS Type 3: Position report class A, which is really {VDMMsgCNB}
        class VDMMsg3 < VDMMsgCNB; end
      end
    end
  end
end


text:
Note - this site has been revamped to v2

Site for Picture Perfect Artistry by Ivon

For reference:

http://www.facebook.com/ivonhernandezgarcia1?ref=br_tf

Completed Tasks:

Release 1:

Add skeleton

Removed extra readme

Release 2: 2/3/15

Add boostrap styling

Create Images folder

Upload Images

Release 3: 2/4/15

Add Pony to allow clients to email client from page

In progress:

Release 4: 2/9/15

ENV problems fixed

Emails now go to Picture Perfect

Glyphicon problems fixed

Create google+ account and hyperlinked it

Create Twitter account and hyperlinked it

Create Pinterest account and hyperlinked it

Create google voice number and hyperlinked it

Added Google voice contact me widget

Todo:

Get original images from client

Get contact details for client

Allow email to be sent w/o page refresh


text:
using System.IO;
using Pulse.Core;

namespace Pulse.FS
{
    public sealed class YkdHeader : IStreamingContent
    {
        public const int Size = 16;
        public const int MagicNumber = 0x5F444B59;

        public int Magic;
        public int Unknown1;
        public byte Unknown2, Unknown3, Unknown4, Unknown5;
        public int Dummy; // Always 0

        public void ReadFromStream(Stream stream)
        {
            BinaryReader br = new BinaryReader(stream);
            Magic = br.Check(reader => reader.ReadInt32(), MagicNumber);
            Unknown1 = br.ReadInt32();
            Unknown2 = br.ReadByte();
            Unknown3 = br.ReadByte();
            Unknown4 = br.ReadByte();
            Unknown5 = br.ReadByte();
            Dummy = br.Check(reader => reader.ReadInt32(), 0);
        }

        public void WriteToStream(Stream stream)
        {
            BinaryWriter bw = new BinaryWriter(stream);
            bw.Write(Magic);
            bw.Write(Unknown1);
            bw.Write(Unknown2);
            bw.Write(Unknown3);
            bw.Write(Unknown4);
            bw.Write(Unknown5);
            bw.Write(Dummy);
        }
    }
}


text:
package uk.gov.hmrc.ct.accounts.frs102.boxes

import uk.gov.hmrc.ct.accounts.{MockFrs102AccountsRetriever, AccountsPreviousPeriodValidationFixture, AccountsMoneyValidationFixture}
import uk.gov.hmrc.ct.accounts.frs102.retriever.Frs102AccountsBoxRetriever

class AC23Spec extends AccountsMoneyValidationFixture[Frs102AccountsBoxRetriever] with AccountsPreviousPeriodValidationFixture[Frs102AccountsBoxRetriever] with MockFrs102AccountsRetriever {

  testAccountsMoneyValidation("AC23", AC23.apply)

  testAccountsPreviousPoAValidation("AC23", AC23.apply)
}