text:
var NAVIGATOR_IS_MOBILE = (/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(navigator.userAgent.toLowerCase()));

if (!String.prototype.endsWith) {
  String.prototype.endsWith = function(searchString, position) {
    var subjectString = this.toString();
    if (typeof position !== 'number' || !isFinite(position) || Math.floor(position) !== position || position > subjectString.length) {
      position = subjectString.length;
    }
    position -= searchString.length;
    var lastIndex = subjectString.indexOf(searchString, position);
    return lastIndex !== -1 && lastIndex === position;
  };
}

(function($){
    $.unserialize = function(serializedString)
    {
        serializedString = serializedString.split("?");
        if(serializedString.length > 1)
        {
            serializedString = serializedString[1]
        }
        else {
            serializedString = serializedString[0]
        }
        var str = decodeURI(serializedString);
        var pairs = str.split('&');
        var obj = {}, p, idx, val;
        for (var i=0, n=pairs.length; i < n; i++) {
            p = pairs[i].split('=');
            idx = p[0];

            if (idx.indexOf("[]") == (idx.length - 2)) {
                // Eh um vetor
                var ind = idx.substring(0, idx.length-2)
                if (obj[ind] === undefined) {
                    obj[ind] = [];
                }
                obj[ind].push(p[1]);
            }
            else {
                obj[idx] = p[1];
            }
        }
        return obj;
    };
})(jQuery);

$.fn.addLoading = function(text, b, c)
{
    return this.each(function(i, self)
    {
        if( self.is_loading !== true )
        {
            self.is_loading = true;
            $loading = $("");
            $(self).append($loading.hide()).addClass('loading');
            $loading.fadeIn(300);
        }
        var new_text = text;
        if(!new_text)
        {
            new_text = $(self).data('loading');
        };
        if(new_text)
        {
            $(self).find('.loading-text').text(new_text);
        }
    });
}
$.fn.removeLoading = function()
{
    return this.each(function(i, self)
    {
        $(self).removeClass('loading').find('.loading-text').fadeOut(250, function()
        {
            $(this).remove();
        });
        self.is_loading = null;
    });
}

$(document).ready(function(menuTo, select)
{

    $(document).on('mousedown', '[data-confirm]', function(e, self)
    {
        e.preventDefault();
        self = $(this);
        $.magnificPopup.open({
            type: 'inline',
            closeMarkup: '<button type="button" class="mfp-close"></button>',
            items: {
                src: '
\

'+$(this).data('confirm')+'
\

\

\

\
                                Annuler\

\

\

\
                                Confirmer\

\

\

\

\

',
                cache: true,
            },
            settings: {cache: true},
            callbacks: {
                open: function() {
                    self.trigger('model.opened', [])
                    $($.magnificPopup.instance.content).on('click', '.no', function()
                    {
                        $.magnificPopup.close();
                    }).on('click', '.yes', function()
                    {
                        $.magnificPopup.close();
                        self.click();
                    })
                },
            },
            mainClass: 'my-mfp-slide-bottom',
            removalDelay: 300
        })
        e.stopPropagation();
        return false;
    });

    $('[data-images-loading]').each(function(e, $self)
    {
        $self = $(this).addLoading();
        $self.imagesLoaded(function()
        {
            $self.removeLoading();
        })
    });

    $('[data-loading]').addLoading();

    $(document).on('mouseenter', '[data-slick]', function(self) {
        if(this.data_slick === true) return
        this.data_slick = true;
        self = $(this);
        //self.imagesLoaded(function() {
            self.slick(self.data('slick'));
        //});
    })
    $('[data-slick]').trigger('mouseenter');

    $('[data-share]').each(function(i, self)
    {
        self = $(this);
        self.tooltipster({
            trigger: 'click',
            interactive: true,
            content: self.next().find('.share')
        });
    });

    $(document).on('click', '[data-modal]', function(event, trigger, target, type)
    {
        trigger = $(this);
        target = trigger.data('modal');
        if(target[0] == '#') {
            type = 'inline';
            var cache = true;
        }
        else if(target.endsWith('.png') || target.endsWith('.jpg') || target.endsWith('.gif')) {

            type = 'image';
            var cache = true;
        }
        else {
            type = 'ajax';
            var cache = false;
        }
        $.magnificPopup.open({
            type: type,
            closeMarkup: '<button type="button" class="mfp-close"></button>',
            items: {
                src: target,
                cache: cache,
            },
            settings: {cache: cache},
            callbacks: {
                open: function() {
                    if(window.mfp) window.mfp.popupsCache = {};
                    trigger.trigger('modal.opened', [])
                    if(type == "inline" || type == "image") {
                        trigger.trigger('modal.loaded', [$.magnificPopup.instance.content])
                    }
                },
                ajaxContentAdded: function(content) {
                    //select(this.content.find('select'));
                    content = $(this.content);
                    trigger.trigger('modal.loaded', [this.content]);
                }
            },
            mainClass: 'my-mfp-slide-bottom',
            removalDelay: 300
        });
        return false;
    });

    $('[data-isotopes]').each(function(i, self)
    {
        var options = $.extend({
            itemSelector: '[data-isotope]',
            layoutMode: 'fitRows',
        }, $(self).data('isotopes'))
        if($.fn.imagesLoaded) {
            $(self).imagesLoaded(function() {
                $(self).isotope(options)
            });
        }
        else {
            $(self).isotope(options)
        }

    });

    $(document).on('mouseover', '[data-tooltip]', function(content, options)
    {

        if(!this.tooltiptized_over)
        {
            var data = $(this).data('tooltip');
            options = {
                delay: 0,
                theme : 'tooltipster-default'
            }

            if(typeof data == "object")
            {
                options = $.extend(options, data)
            }
            else if(typeof data == "string")
            {
                if(data[0] != '#')
                {
                    options.content = $('
'+data+'
');
                }
                else
                {
                    options.content = data;
                }
            }
            if(options.content && options.content[0] == '#' && $(options.content).length)
            {
                options.content = $(options.content);
            }
            $(this).tooltipster(options);
            this.tooltiptized_over = true;
            if(!options.trigger || options.trigger == "hover")
            {
                $(this).tooltipster('show')
            }

        }
    });

});

$(document).ready(function($navs, scrollFct)
{
    $navs = $('[data-navigation]').each(function(i, self, $menu)
    {
        self = $(this);
        $menu = $('
'+self.data('navigation')+'
');
        $menu.on('click', 'a', function()
        {
            $.smoothScroll({
                scrollTarget: self,
                offset: -50
            });
        });
        $('#main-scroll-nav').append($menu);
        self[0].nav_menu = $menu;
    });

    scrollFct = function(windowHeight, scrollTop, closest, closest_depth)
    {

        windowHeight = $(window).height();
        scrollTop = $(window).scrollTop();
        // var middle = scrollTop + windowHeight/2

        closest_depth = null;
        closest = null;

        // $('#fixed-nav-social').css({ top: middle - $('#fixed-nav-social').height()/2 })
        // $('#fixed-nav').css({ top: middle - $('#fixed-nav').height()/2 })

        $navs.each(function(i, self, top, bottom)
        {
            self = $(this);
            top = self.offset().top;

            var wCenter = ( windowHeight/2 + scrollTop );
            var tCenter = (top + self.height()/2);

            //var depth = Math.abs(wCenter - tCenter)
            var depth = Math.abs((scrollTop - top) + ((scrollTop+windowHeight) - (top + self.height())))

            //console.log(self[0].nav_menu.text(), depth, scrollTop >= top)

            if(!closest_depth || ( depth <= closest_depth )  ) {
                closest = self;
                closest_depth = depth;
            }

        });

        if(closest) {
            closest[0].nav_menu.find('a').addClass('active')
            closest[0].nav_menu.siblings().find('a').removeClass('active');
        }

    }
    $(window).scroll(scrollFct);
    $(window).resize(scrollFct);
    scrollFct();
});


text:
require 'spec_helper'

describe Serializer do

  describe '.new' do

    it 'should initialize a new Mechanism instance with `options`' do

    end

  end

end

redpajama_set_name: RedPajamaGithub


text:
require 'spec_helper'

describe XboxApi do

let(:token)  { ENV['XBOX_TOKEN'] }
let(:client) { XboxApi::Client.new(token) }
let(:gamer)  { VCR.use_cassette("gamer") { client.gamer("audibleblink") } }

  describe XboxApi::Client do

    context "#gamer" do

      it "returns a Gamer object" do
        expect( gamer ).to be_a_kind_of XboxApi::Gamer
      end

    end

    context "#calls_remaining" do
      it "returns a hash with the correct info" do
        VCR.use_cassette("calls_remaining") do
          response = client.calls_remaining
          expect(response).to be_a_kind_of Hash
          expect(response.keys.length).to eq 3
        end
      end
    end

    context "#game_details" do
      it "returns a hash with the correct info using title id" do
        VCR.use_cassette("game_details") do
          response = client.game_details(1708767297)
          expect(response).to be_a_kind_of Hash
          expect(response.keys.length).to eq 2
        end
      end

      it "returns a hash with the correct info using hex game id" do
        VCR.use_cassette("game_details") do
          response = client.game_details('65d9b841')
          expect(response).to be_a_kind_of Hash
          expect(response.keys.length).to eq 2
        end
      end
    end
  end

  describe XboxApi::Gamer do

    context "#presence" do

      it "returns 'Offline' for an offline player" do
        VCR.use_cassette("presence_offline") do
          response = gamer.presence
          expect(response[:state]).to eq "Offline"
        end
      end

      it "returns 'Online' for an online player" do
        VCR.use_cassette("presence_online") do
          response = gamer.presence
          expect(response[:state]).to eq "Online"
        end
      end
    end

    context "#xuid" do
      it "has an xuid" do
        expect(gamer.xuid).to_not be nil
      end
    end

    context "#friends" do
      it "returns an array of friends" do
        VCR.use_cassette("friends") do
          response = gamer.friends
          expect(response).to be_a_kind_of Array
          expect(response.first).to be_a_kind_of Hash
          expect(response.first.has_key?(:id)).to be true
        end
      end
    end

    context "#followers" do
      it "returns an array of followers" do
        VCR.use_cassette("followers") do
          response = gamer.followers
          expect(response).to be_a_kind_of Array
          expect(response.first).to be_a_kind_of Hash
        end
      end
    end

    context "#gamercard" do
      it "returns the users gamercard" do
        VCR.use_cassette("gamercard") do
          response = gamer.gamercard
          expect(response).to be_a_kind_of Hash
          expect(response[:gamertag].downcase).to eq gamer.gamertag
        end
      end
    end

    context "#activity" do
      it "returns the users activity" do
        VCR.use_cassette("activity") do
          response = gamer.activity
          expect(response).to be_a_kind_of Hash
          expect(response.keys.include?(:activityItems)).to be true
        end
      end
    end

    context "#profile" do
      it "returns the users profile" do
        VCR.use_cassette("profile") do
          response = gamer.profile
          expect(response).to be_a_kind_of Hash
          expect(response[:id]).to eq gamer.xuid
        end
      end
    end

    context "#game_clips" do
      it "returns an array of game_clips" do
        VCR.use_cassette("game_clips") do
          response = gamer.game_clips
          expect(response).to be_a_kind_of Array
          expect(response.first.keys.include? :gameClipId).to be true
        end
      end
    end

    context "#xboxonegames" do
      it "returns an array of xboxonegames" do
        VCR.use_cassette("xboxonegames") do
          response = gamer.xboxonegames
          expect(response).to be_a_kind_of Hash
          expect(response[:titles]).to be_a_kind_of Array
        end
      end
    end

    context "#xbox360games" do
      it "returns an array of xbox360games" do
        VCR.use_cassette("xbox360games") do
          response = gamer.xbox360games
          expect(response).to be_a_kind_of Hash
          expect(response[:titles]).to be_a_kind_of Array
        end
      end
    end

    context "#recent_activity" do
      it "returns an array of recent_activity" do
        VCR.use_cassette("recent_activity") do
          response = gamer.recent_activity
          expect(response).to be_a_kind_of Array
          expect(response.first.keys.include?(:startTime)).to be true
        end
      end
    end
  end

  describe XboxApi::XboxLive do
    context "#status" do
      xit "displays an status for a valid user" do
        VCR.use_cassette("thor-status-valid") do
          expect{system("xbl -s theschoolmaster")}.to output("").to_stdout
        end
      end

      xit "prompts for token when none is present" do
          XboxApi::TokenHelper.clear!
          expect{system("xbl -s theschoolmaster")}.to output("XboxAPI Token:").to_stdout
      end
    end

    context "#token" do
      let(:token){"123123"}

      it "displays a token" do
          XboxApi::TokenHelper.write_local_token!(token)
          output = `xbl token`.chomp
          expect(output).to eq token
      end

      it "clears a token" do
          XboxApi::TokenHelper.write_local_token!(token)
          warning = `xbl token --clear`.chomp
          expect(warning).to eq("Token deleted. Rerun `xbl token` to enter a new token")
      end
    end

  end

end


text:
CF_EXTERN_C_BEGIN

@class MmBpOpen_BaseResponse;

NS_ASSUME_NONNULL_BEGIN

#pragma mark - WcmmbpOpenRoot

@interface WcmmbpOpenRoot : GPBRootObject

// The base class provides:
//   + (GPBExtensionRegistry *)extensionRegistry;
// which is an GPBExtensionRegistry that includes all the extensions defined by
// this file and all files that it depends on.

@end

#pragma mark - MmBpOpen_BaseResponse

typedef GPB_ENUM(MmBpOpen_BaseResponse_FieldNumber) {
  MmBpOpen_BaseResponse_FieldNumber_Errcode = 1,
  MmBpOpen_BaseResponse_FieldNumber_Errmsg = 2,
};

@interface MmBpOpen_BaseResponse : GPBMessage

@property(nonatomic, readwrite) BOOL hasErrcode;
@property(nonatomic, readwrite) int32_t errcode;

@property(nonatomic, readwrite) BOOL hasErrmsg;
@property(nonatomic, readwrite, copy, null_resettable) NSString *errmsg;

@end

#pragma mark - MmBpOpen_WristbandRequest

typedef GPB_ENUM(MmBpOpen_WristbandRequest_FieldNumber) {
  MmBpOpen_WristbandRequest_FieldNumber_StepDataArray = 1,
  MmBpOpen_WristbandRequest_FieldNumber_ExtData = 2,
};

@interface MmBpOpen_WristbandRequest : GPBMessage

// |stepDataArray| contains |MmBpOpen_WristbandRequest_MmBpOpen_StepDataItem|
@property(nonatomic, readwrite, strong, null_resettable) NSMutableArray *stepDataArray;
@property(nonatomic, readonly) NSUInteger stepDataArray_Count;

@property(nonatomic, readwrite) BOOL hasExtData;
@property(nonatomic, readwrite, copy, null_resettable) NSData *extData;

@end

#pragma mark - MmBpOpen_WristbandRequest_MmBpOpen_StepDataItem

typedef GPB_ENUM(MmBpOpen_WristbandRequest_MmBpOpen_StepDataItem_FieldNumber) {
  MmBpOpen_WristbandRequest_MmBpOpen_StepDataItem_FieldNumber_Step = 1,
  MmBpOpen_WristbandRequest_MmBpOpen_StepDataItem_FieldNumber_Timestamp = 2,
  MmBpOpen_WristbandRequest_MmBpOpen_StepDataItem_FieldNumber_TimeStampRtcYear = 3,
  MmBpOpen_WristbandRequest_MmBpOpen_StepDataItem_FieldNumber_TimeStampRtcMonth = 4,
  MmBpOpen_WristbandRequest_MmBpOpen_StepDataItem_FieldNumber_TimeStampRtcDay = 5,
  MmBpOpen_WristbandRequest_MmBpOpen_StepDataItem_FieldNumber_TimeStampRtcHour = 6,
  MmBpOpen_WristbandRequest_MmBpOpen_StepDataItem_FieldNumber_TimeStampRtcMinute = 7,
  MmBpOpen_WristbandRequest_MmBpOpen_StepDataItem_FieldNumber_TimeStampRtcSecond = 8,
};

@interface MmBpOpen_WristbandRequest_MmBpOpen_StepDataItem : GPBMessage

@property(nonatomic, readwrite) BOOL hasStep;
@property(nonatomic, readwrite) uint32_t step;

@property(nonatomic, readwrite) BOOL hasTimestamp;
@property(nonatomic, readwrite) uint32_t timestamp;

@property(nonatomic, readwrite) BOOL hasTimeStampRtcYear;
@property(nonatomic, readwrite) uint32_t timeStampRtcYear;

@property(nonatomic, readwrite) BOOL hasTimeStampRtcMonth;
@property(nonatomic, readwrite) uint32_t timeStampRtcMonth;

@property(nonatomic, readwrite) BOOL hasTimeStampRtcDay;
@property(nonatomic, readwrite) uint32_t timeStampRtcDay;

@property(nonatomic, readwrite) BOOL hasTimeStampRtcHour;
@property(nonatomic, readwrite) uint32_t timeStampRtcHour;

@property(nonatomic, readwrite) BOOL hasTimeStampRtcMinute;
@property(nonatomic, readwrite) uint32_t timeStampRtcMinute;

@property(nonatomic, readwrite) BOOL hasTimeStampRtcSecond;
@property(nonatomic, readwrite) uint32_t timeStampRtcSecond;

@end

#pragma mark - MmBpOpen_WristBandResponse

typedef GPB_ENUM(MmBpOpen_WristBandResponse_FieldNumber) {
  MmBpOpen_WristBandResponse_FieldNumber_BaseResp = 1,
};

@interface MmBpOpen_WristBandResponse : GPBMessage

@property(nonatomic, readwrite) BOOL hasBaseResp;
@property(nonatomic, readwrite, strong, null_resettable) MmBpOpen_BaseResponse *baseResp;

@end

#pragma mark - MmBpOpen_WristBandPush

@interface MmBpOpen_WristBandPush : GPBMessage

@end

NS_ASSUME_NONNULL_END

CF_EXTERN_C_END

// @@protoc_insertion_point(global_scope)


text:
package hammer

import (
	"context"
	"fmt"
	"log"
	"strings"

	"github.com/antihax/evedata/internal/datapackages"
	"github.com/antihax/goesi"
)

func init() {
	//registerConsumer("structure", structureConsumer)
	//registerConsumer("characterStructures", characterStructuresConsumer)
}

func structureConsumer(s *Hammer, parameter interface{}) {
	structureID := parameter.(int64)

	if s.inQueue.CheckWorkExpired("evedata_structure_failure", structureID) {
		return
	}

	ctx := context.WithValue(context.Background(), goesi.ContextOAuth2, *s.token)
	structure, _, err := s.esi.ESI.UniverseApi.GetUniverseStructuresStructureId(ctx, structureID, nil)

	if err != nil {
		if strings.Contains(err.Error(), "403") {
			s.inQueue.SetWorkExpire("evedata_structure_failure", structureID, 86400)
		}
		log.Println(err)
		return
	}
	// Send out the result
	err = s.QueueResult(&datapackages.Structure{Structure: structure, StructureID: structureID}, "structure")
	if err != nil {
		log.Println(err)
		return
	}
}

// Handle character structures separately since they should remain private
func characterStructuresConsumer(s *Hammer, parameter interface{}) {
	parameters := parameter.([]interface{})
	characterID := int32(parameters[0].(int))
	tokenCharacterID := int32(parameters[1].(int))
	structureID := parameters[2].(int64)

	if s.inQueue.CheckWorkExpired("evedata_structurechar_failure",
		fmt.Sprintf("%d%d", structureID, tokenCharacterID)) {
		log.Printf("failed structure ignored %d\n", structureID)
		return
	}

	ctx, err := s.GetTokenSourceContext(context.Background(), characterID, tokenCharacterID)
	if err != nil {
		log.Println(err)
		return
	}

	// [TODO] tick failure to database
	structure, r, err := s.esi.ESI.UniverseApi.GetUniverseStructuresStructureId(ctx, structureID, nil)
	if err != nil {
		s.tokenStore.CheckSSOError(characterID, tokenCharacterID, err)
		if r != nil && r.StatusCode == 403 {
			err := s.inQueue.SetWorkExpire("evedata_structurechar_failure", fmt.Sprintf("%d%d", structureID, tokenCharacterID), 86400*3)
			if err != nil {
				log.Printf("failed setting failure: %s %d\n", err, structureID)
			}
		}
		log.Println(err)
		return
	}

	// Send out the result
	err = s.QueueResult(&datapackages.CharacterStructure{Structure: structure, StructureID: structureID, CharacterID: tokenCharacterID}, "characterStructure")
	if err != nil {
		log.Println(err)
		return
	}
}


text:
#ifndef TIME_SLICED_GRAPHALGORITHMS_H
#define TIME_SLICED_GRAPHALGORITHMS_H
#pragma warning (disable:4786)
//------------------------------------------------------------------------
//
//  Name:   TimeSlicedGraphAlgorithms.h
//
//  Desc:   classes to implement graph algorithms that can be distributed
//          over multiple update-steps
//
//          Any graphs passed to these functions must conform to the
//          same interface used by the SparseGraph
//
//  Author: Mat Buckland (fup@ai-junkie.com)
//
//------------------------------------------------------------------------
#include <vector>
#include <list>
#include <queue>
#include <stack>

#include "graph/SparseGraph.h"
#include "misc/PriorityQueue.h"
#include "Graph/AStarHeuristicPolicies.h"
#include "graph/SearchTerminationPolicies.h"
#include "graph/PathEdge.h"

//these enums are used as return values from each search update method
enum {target_found, target_not_found, search_incomplete};
enum SearchType {AStar, Dijkstra};

//------------------------ Graph_SearchTimeSliced -----------------------------
//
// base class to define a common interface for graph search algorithms
//-----------------------------------------------------------------------------
template <class edge_type>
class Graph_SearchTimeSliced
{
public:

private:

  SearchType m_SearchType;

public:

  Graph_SearchTimeSliced(SearchType type):m_SearchType(type){}

  virtual ~Graph_SearchTimeSliced(){}

  //When called, this method runs the algorithm through one search cycle. The
  //method returns an enumerated value (target_found, target_not_found,
  //search_incomplete) indicating the status of the search
  virtual int                           CycleOnce()=0;

  //returns the vector of edges that the algorithm has examined
  virtual std::vector<const edge_type*> GetSPT()const=0;

  //returns the total cost to the target
  virtual double                         GetCostToTarget()const=0;

  //returns a list of node indexes that comprise the shortest path
  //from the source to the target
  virtual std::list<int>                GetPathToTarget()const=0;
  virtual void							GetPathToTarget(std::list<int> *plist)const=0;

  //returns the path as a list of PathEdges
//  virtual std::list<PathEdge>           GetPathAsPathEdges()const=0;
  virtual void				            GetPathAsPathEdges(std::list<PathEdge> *plist)const=0;

  SearchType                            GetType()const{return m_SearchType;}
};

//-------------------------- Graph_SearchAStar_TS -----------------------------
//
//  a A* class that enables a search to be completed over multiple update-steps
//-----------------------------------------------------------------------------
template <class graph_type, class heuristic>
class Graph_SearchAStar_TS : public Graph_SearchTimeSliced<typename graph_type::EdgeType>
{
private:

  //create typedefs for the node and edge types used by the graph
  typedef typename graph_type::EdgeType Edge;
  typedef typename graph_type::NodeType Node;

private:

  const graph_type&              m_Graph;

  //indexed into my node. Contains the 'real' accumulative cost to that node
  std::vector<double>            m_GCosts;

  //indexed into by node. Contains the cost from adding m_GCosts[n] to
  //the heuristic cost from n to the target node. This is the vector the
  //iPQ indexes into.
  std::vector<double>            m_FCosts;

  std::vector<const Edge*>       m_ShortestPathTree;
  std::vector<const Edge*>       m_SearchFrontier;

  int                            m_iSource;
  int                            m_iTarget;

  //create an indexed priority queue of nodes. The nodes with the
  //lowest overall F cost (G+H) are positioned at the front.
  IndexedPriorityQLow<double>*    m_pPQ;

public:

  Graph_SearchAStar_TS(const graph_type& G,
                      int                source,
                      int                target):Graph_SearchTimeSliced<Edge>(AStar),

                                              m_Graph(G),
                                              m_ShortestPathTree(G.NumNodes()),
                                              m_SearchFrontier(G.NumNodes()),
                                              m_GCosts(G.NumNodes(), 0.0),
                                              m_FCosts(G.NumNodes(), 0.0),
                                              m_iSource(source),
                                              m_iTarget(target)
  {
     //create the PQ
     m_pPQ =new IndexedPriorityQLow<double>(m_FCosts, m_Graph.NumNodes());

    //put the source node on the queue
    m_pPQ->insert(m_iSource);
  }

   ~Graph_SearchAStar_TS(){delete m_pPQ;}

  //When called, this method pops the next node off the PQ and examines all
  //its edges. The method returns an enumerated value (target_found,
  //target_not_found, search_incomplete) indicating the status of the search
  int                      CycleOnce();

  //returns the vector of edges that the algorithm has examined
  std::vector<const Edge*> GetSPT()const{return m_ShortestPathTree;}

  //returns a vector of node indexes that comprise the shortest path
  //from the source to the target
  std::list<int>         GetPathToTarget()const;
  void					 GetPathToTarget(std::list<int> *plist)const;

  //returns the path as a list of PathEdges
//  std::list<PathEdge>    GetPathAsPathEdges()const;
  void		             GetPathAsPathEdges(std::list<PathEdge> *plist)const;

  //returns the total cost to the target
  double            GetCostToTarget()const{return m_GCosts[m_iTarget];}
};

//-----------------------------------------------------------------------------
template <class graph_type, class heuristic>
int Graph_SearchAStar_TS<graph_type, heuristic>::CycleOnce()
{
  //if the PQ is empty the target has not been found
  if (m_pPQ->empty())
  {
    return target_not_found;
  }

  //get lowest cost node from the queue
  int NextClosestNode = m_pPQ->Pop();

  //put the node on the SPT
  m_ShortestPathTree[NextClosestNode] = m_SearchFrontier[NextClosestNode];

  //if the target has been found exit
  if (NextClosestNode == m_iTarget)
  {
    return target_found;
  }

  //now to test all the edges attached to this node
  graph_type::ConstEdgeIterator ConstEdgeItr(m_Graph, NextClosestNode);
  for (const Edge* pE=ConstEdgeItr.begin();
      !ConstEdgeItr.end();
       pE=ConstEdgeItr.next())
  {
    //calculate the heuristic cost from this node to the target (H)
    double HCost = heuristic::Calculate(m_Graph, m_iTarget, pE->To());

    //calculate the 'real' cost to this node from the source (G)
//    double GCost = m_GCosts[NextClosestNode] + pE->Cost();
	//calculate the 'real' cost to this node from the source (G)
	const NavGraphNode<> &t = m_Graph.GetNode(pE->To());
	const NavGraphNode<> &f = m_Graph.GetNode(pE->From());
	const double cost = t.Pos().Distance(f.Pos());
	//	  const double cost = pE->Cost();
	const double GCost = m_GCosts[NextClosestNode] + cost;

    //if the node has not been added to the frontier, add it and update
    //the G and F costs
    if (m_SearchFrontier[pE->To()] == NULL)
    {
      m_FCosts[pE->To()] = GCost + HCost;
      m_GCosts[pE->To()] = GCost;

      m_pPQ->insert(pE->To());

      m_SearchFrontier[pE->To()] = pE;
    }

    //if this node is already on the frontier but the cost to get here
    //is cheaper than has been found previously, update the node
    //costs and frontier accordingly.
    else if ((GCost < m_GCosts[pE->To()]) && (m_ShortestPathTree[pE->To()]==NULL))
    {
      m_FCosts[pE->To()] = GCost + HCost;
      m_GCosts[pE->To()] = GCost;

      m_pPQ->ChangePriority(pE->To());

      m_SearchFrontier[pE->To()] = pE;
    }
  }

  //there are still nodes to explore
  return search_incomplete;
}

//-----------------------------------------------------------------------------
template <class graph_type, class heuristic>
std::list<int>
Graph_SearchAStar_TS<graph_type, heuristic>::GetPathToTarget()const
{
  std::list<int> path;

  //just return an empty path if no target or no path found
  if (m_iTarget < 0)  return path;

  int nd = m_iTarget;

  path.push_back(nd);

  while ((nd != m_iSource) && (m_ShortestPathTree[nd] != 0))
  {
    nd = m_ShortestPathTree[nd]->From();

    path.push_front(nd);
  }

  return path;
}

template <class graph_type, class heuristic>
void Graph_SearchAStar_TS<graph_type, heuristic>::GetPathToTarget(std::list<int> *plist)const
{
	if (m_iTarget < 0)  return;
	int nd = m_iTarget;
	plist->push_back(nd);
	while ((nd != m_iSource) && (m_ShortestPathTree[nd] != 0))
	{
		nd = m_ShortestPathTree[nd]->From();
		plist->push_front(nd);
	}
}

/*
//-------------------------- GetPathAsPathEdges -------------------------------
//
//  returns the path as a list of PathEdges
//-----------------------------------------------------------------------------
template <class graph_type, class heuristic>
std::list<PathEdge>
Graph_SearchAStar_TS<graph_type, heuristic>::GetPathAsPathEdges()const
{
  std::list<PathEdge> path;

  //just return an empty path if no target or no path found
  if (m_iTarget < 0)  return path;

  int nd = m_iTarget;

  while ((nd != m_iSource) && (m_ShortestPathTree[nd] != 0))
  {
    path.push_front(PathEdge(m_Graph.GetNode(m_ShortestPathTree[nd]->From()).Pos(),
                             m_Graph.GetNode(m_ShortestPathTree[nd]->To()).Pos(),
                             m_ShortestPathTree[nd]->Flags(),
                             m_ShortestPathTree[nd]->IDofIntersectingEntity()));

    nd = m_ShortestPathTree[nd]->From();
  }

  return path;
}
/**/

template <class graph_type, class heuristic>
void Graph_SearchAStar_TS<graph_type, heuristic>::GetPathAsPathEdges(std::list<PathEdge> *plist)const
{
	//just return an empty path if no target or no path found
	if (m_iTarget < 0)  return;
	int nd = m_iTarget;
	while ((nd != m_iSource) && (m_ShortestPathTree[nd] != 0))
	{
		plist->push_front(PathEdge(m_Graph.GetNode(m_ShortestPathTree[nd]->From()).Pos(),
			m_Graph.GetNode(m_ShortestPathTree[nd]->To()).Pos(),
			m_ShortestPathTree[nd]->Flags(),
			m_ShortestPathTree[nd]->IDofIntersectingEntity()));

		nd = m_ShortestPathTree[nd]->From();
	}

}

//-------------------------- Graph_SearchDijkstras_TS -------------------------
//
//  Dijkstra's algorithm class modified to spread a search over multiple
//  update-steps
//-----------------------------------------------------------------------------
template <class graph_type, class termination_condition>
class Graph_SearchDijkstras_TS : public Graph_SearchTimeSliced<typename graph_type::EdgeType>
{
private:

  //create typedefs for the node and edge types used by the graph
  typedef typename graph_type::EdgeType Edge;
  typedef typename graph_type::NodeType Node;

private:

  const graph_type&                   m_Graph;

  //indexed into my node. Contains the accumulative cost to that node
  std::vector<double>             m_CostToThisNode;

  std::vector<const Edge*>  m_ShortestPathTree;
  std::vector<const Edge*>  m_SearchFrontier;

  int                            m_iSource;
  int                            m_iTarget;

  //create an indexed priority queue of nodes. The nodes with the
  //lowest overall F cost (G+H) are positioned at the front.
  IndexedPriorityQLow<double>*     m_pPQ;

public:

  Graph_SearchDijkstras_TS(const graph_type&  G,
                          int                   source,
                          int                   target):Graph_SearchTimeSliced<Edge>(Dijkstra),

                                              m_Graph(G),
                                              m_ShortestPathTree(G.NumNodes()),
                                              m_SearchFrontier(G.NumNodes()),
                                              m_CostToThisNode(G.NumNodes(), 0.0),
                                              m_iSource(source),
                                              m_iTarget(target)
  {
     //create the PQ         ,
     m_pPQ =new IndexedPriorityQLow<double>(m_CostToThisNode, m_Graph.NumNodes());

    //put the source node on the queue
    m_pPQ->insert(m_iSource);
  }

  //let the search class take care of tidying up memory (the wary amongst
  //you may prefer to use std::auto_ptr or similar to replace the pointer
  //to the termination condition)
   ~Graph_SearchDijkstras_TS()
   {
     delete m_pPQ;
   }

  //When called, this method pops the next node off the PQ and examines all
  //its edges. The method returns an enumerated value (target_found,
  //target_not_found, search_incomplete) indicating the status of the search
  int              CycleOnce();

  //returns the vector of edges that the algorithm has examined
  std::vector<const Edge*> GetSPT()const{return m_ShortestPathTree;}

  //returns a vector of node indexes that comprise the shortest path
  //from the source to the target
  std::list<int> GetPathToTarget()const;
  void GetPathToTarget(std::list<int> *plist)const;

  //returns the path as a list of PathEdges
//  std::list<PathEdge>    GetPathAsPathEdges()const;
  void GetPathAsPathEdges(std::list<PathEdge> *plist)const;

  //returns the total cost to the target
  double            GetCostToTarget()const{return m_CostToThisNode[m_iTarget];}
};

//-----------------------------------------------------------------------------
template <class graph_type, class termination_condition>
int Graph_SearchDijkstras_TS<graph_type, termination_condition>::CycleOnce()
{
  //if the PQ is empty the target has not been found
  if (m_pPQ->empty())
  {
    return target_not_found;
  }

  //get lowest cost node from the queue
  int NextClosestNode = m_pPQ->Pop();

  //move this node from the frontier to the spanning tree
  m_ShortestPathTree[NextClosestNode] = m_SearchFrontier[NextClosestNode];

  //if the target has been found exit
  if (termination_condition::isSatisfied(m_Graph, m_iTarget, NextClosestNode))
  {
    //make a note of the node index that has satisfied the condition. This
    //is so we can work backwards from the index to extract the path from
    //the shortest path tree.
    m_iTarget = NextClosestNode;

    return target_found;
  }

  //now to test all the edges attached to this node
  graph_type::ConstEdgeIterator ConstEdgeItr(m_Graph, NextClosestNode);
  for (const Edge* pE=ConstEdgeItr.begin();
      !ConstEdgeItr.end();
       pE=ConstEdgeItr.next())
  {
    //the total cost to the node this edge points to is the cost to the
    //current node plus the cost of the edge connecting them.
    double NewCost = m_CostToThisNode[NextClosestNode] + pE->Cost();

    //if this edge has never been on the frontier make a note of the cost
    //to get to the node it points to, then add the edge to the frontier
    //and the destination node to the PQ.
    if (m_SearchFrontier[pE->To()] == 0)
    {
      m_CostToThisNode[pE->To()] = NewCost;

      m_pPQ->insert(pE->To());

      m_SearchFrontier[pE->To()] = pE;
    }

    //else test to see if the cost to reach the destination node via the
    //current node is cheaper than the cheapest cost found so far. If
    //this path is cheaper, we assign the new cost to the destination
    //node, update its entry in the PQ to reflect the change and add the
    //edge to the frontier
    else if ( (NewCost < m_CostToThisNode[pE->To()]) &&
              (m_ShortestPathTree[pE->To()] == 0) )
    {
      m_CostToThisNode[pE->To()] = NewCost;

      //because the cost is less than it was previously, the PQ must be
      //re-sorted to account for this.
      m_pPQ->ChangePriority(pE->To());

      m_SearchFrontier[pE->To()] = pE;
    }
  }

  //there are still nodes to explore
  return search_incomplete;
}

//-----------------------------------------------------------------------------
template <class graph_type, class termination_condition>
std::list<int>
Graph_SearchDijkstras_TS<graph_type, termination_condition>::GetPathToTarget()const
{
  std::list<int> path;

  //just return an empty path if no target or no path found
  if (m_iTarget < 0)  return path;

  int nd = m_iTarget;

  path.push_back(nd);

  while ((nd != m_iSource) && (m_ShortestPathTree[nd] != 0))
  {
    nd = m_ShortestPathTree[nd]->From();

    path.push_front(nd);
  }

  return path;
}

template <class graph_type, class termination_condition>
void Graph_SearchDijkstras_TS<graph_type, termination_condition>::GetPathToTarget(std::list<int> *plist)const
{
	//just return an empty path if no target or no path found
	if (m_iTarget < 0)  return;
	int nd = m_iTarget;
	plist->push_back(nd);
	while ((nd != m_iSource) && (m_ShortestPathTree[nd] != 0))
	{
		nd = m_ShortestPathTree[nd]->From();
		plist->push_front(nd);
	}
}

/*
//-------------------------- GetPathAsPathEdges -------------------------------
//
//  returns the path as a list of PathEdges
//-----------------------------------------------------------------------------
template <class graph_type, class termination_condition>
std::list<PathEdge>
Graph_SearchDijkstras_TS<graph_type, termination_condition>::GetPathAsPathEdges()const
{
  std::list<PathEdge> path;

  //just return an empty path if no target or no path found
  if (m_iTarget < 0)  return path;

  int nd = m_iTarget;

  while ((nd != m_iSource) && (m_ShortestPathTree[nd] != 0))
  {
    path.push_front(PathEdge(m_Graph.GetNode(m_ShortestPathTree[nd]->From()).Pos(),
                             m_Graph.GetNode(m_ShortestPathTree[nd]->To()).Pos(),
                             m_ShortestPathTree[nd]->Flags(),
                             m_ShortestPathTree[nd]->IDofIntersectingEntity()));

    nd = m_ShortestPathTree[nd]->From();
  }

  return path;
}
/**/

template <class graph_type, class termination_condition>
void Graph_SearchDijkstras_TS<graph_type, termination_condition>::GetPathAsPathEdges(std::list<PathEdge> *plist)const
{
	//just return an empty path if no target or no path found
	if (m_iTarget < 0)  return;
	int nd = m_iTarget;
	while ((nd != m_iSource) && (m_ShortestPathTree[nd] != 0))
	{
		 plist->push_front(PathEdge(m_Graph.GetNode(m_ShortestPathTree[nd]->From()).Pos(),
			m_Graph.GetNode(m_ShortestPathTree[nd]->To()).Pos(),
			m_ShortestPathTree[nd]->Flags(),
			m_ShortestPathTree[nd]->IDofIntersectingEntity()));
		nd = m_ShortestPathTree[nd]->From();
	}
}

#endif


text:
/****************************************************************************
 * netutils/netlib/netlib_listenon.c
 *
 *   Copyright (C) 2007-2009, 2011 Gregory Nutt. All rights reserved.
 *   Author: Gregory Nutt <gnutt@nuttx.org>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 3. Neither the name Gregory Nutt nor the names of its contributors may be
 *    used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 ****************************************************************************/

/****************************************************************************
 * Included Files
 ****************************************************************************/

#include <tinyara/config.h>

#include <sys/types.h>
#include <sys/socket.h>
#include <stdint.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <debug.h>
#include <netutils/netlib.h>
#include <tinyara/net/netlog.h>

#define TAG "[NETLIB]"
/****************************************************************************
 * Public Functions
 ****************************************************************************/

/****************************************************************************
 * Public Functions
 ****************************************************************************/

/****************************************************************************
 * Name: netlib_listenon
 *
 * Description:
 *   Implement basic server listening
 *
 * Parameters:
 *   portno    The port to listen on (in network byte order)
 *
 * Return:
 *   A valid listening socket or -1 on error.
 *
 ****************************************************************************/

int netlib_listenon(uint16_t portno)
{
	struct sockaddr_in myaddr;
	int listensd;
#ifdef CONFIG_NET_HAVE_REUSEADDR
	int optval;
#endif

	/* Create a new TCP socket to use to listen for connections */

	listensd = socket(PF_INET, SOCK_STREAM, 0);
	if (listensd < 0) {
		NET_LOGE(TAG, "socket failure: %d\n", errno);
		return ERROR;
	}

	/* Set socket to reuse address */

#ifdef CONFIG_NET_HAVE_REUSEADDR
	optval = 1;
	if (setsockopt(listensd, SOL_SOCKET, SO_REUSEADDR, (void *)&optval, sizeof(int)) < 0) {
		NET_LOGE(TAG, "setsockopt SO_REUSEADDR failure: %d\n", errno);
		goto errout_with_socket;
	}
#endif

	/* Bind the socket to a local address */

	myaddr.sin_family = AF_INET;
	myaddr.sin_port = portno;
	myaddr.sin_addr.s_addr = INADDR_ANY;

	if (bind(listensd, (struct sockaddr *)&myaddr, sizeof(struct sockaddr_in)) < 0) {
		NET_LOGE(TAG, "bind failure: %d\n", errno);
		goto errout_with_socket;
	}

	/* Listen for connections on the bound TCP socket */

	if (listen(listensd, 5) < 0) {
		NET_LOGE(TAG, "listen failure %d\n", errno);
		goto errout_with_socket;
	}

	/* Begin accepting connections */

	NET_LOGV(TAG, "Accepting connections on port %d\n", ntohs(portno));
	return listensd;

errout_with_socket:
	close(listensd);
	return ERROR;
}


text:
#ifndef MBED_GPIO_OBJECT_H
#define MBED_GPIO_OBJECT_H

#include "mbed_assert.h"
#include "fsl_gpio.h"

#ifdef __cplusplus
extern "C" {
#endif

typedef struct {
    PinName pin;
} gpio_t;

static inline void gpio_write(gpio_t *obj, int value) {
    MBED_ASSERT(obj->pin != (PinName)NC);
    uint32_t port = obj->pin >> GPIO_PORT_SHIFT;
    uint32_t pin = obj->pin & 0xFF;
    GPIO_Type *gpio_addrs[] = GPIO_BASE_PTRS;

    GPIO_WritePinOutput(gpio_addrs[port], pin, value);
}

static inline int gpio_read(gpio_t *obj) {
    MBED_ASSERT(obj->pin != (PinName)NC);
    uint32_t port = obj->pin >> GPIO_PORT_SHIFT;
    uint32_t pin = obj->pin & 0xFF;
    GPIO_Type *gpio_addrs[] = GPIO_BASE_PTRS;

    return (int)GPIO_ReadPinInput(gpio_addrs[port], pin);
}

static inline int gpio_is_connected(const gpio_t *obj) {
    return obj->pin != (PinName)NC;
}

#ifdef __cplusplus
}
#endif

#endif


text:
<?php

namespace Att\M2X\MQTT;

use Att\M2X\MQTT\MQTTClient;
use Att\M2X\MQTT\Device;

/**
 * Methods for interacting M2X Device Streams
 */
class Stream extends Resource {

/**
 * REST path of the resource
 *
 * @var string
 */
  public static $path = ':parent_path/streams';

/**
 * The parent resource that this stream belongs to
 *
 * @var Resource
 */
  public $parent = null;
/**
 * The Stream resource properties
 *
 * @var array
 */
  protected static $properties = array(
    'name', 'unit', 'type'
  );

/**
 * Disable the original POST factory
 *
 * @param MQTTClient $client
 * @param array $data
 * @return void
 */
  public static function create($client, $data = array()) {
    throw new \BadMethodCallException('Not implemented, use Stream::createStream() instead.');
  }

/**
 * Method for {@link https://m2x.att.com/developer/documentation/v2/device#Create-Update-Data-Stream Create/Update Data Stream} endpoint.
 *
 * @param MQTTClient $client Client API
 * @param Resource $parent Parent resource that this collection belongs to
 * @param string $name Stream name to be created
 * @param array $data Query parameters passed as keyword arguments. View M2X API Docs for listing of available parameters.
 * @return Stream The newly created stream
 */
  public static function createStream(MQTTClient $client, Resource $parent, $name, $data) {
    $path = str_replace(':parent_path', $parent->path(), static::$path) . '/' . $name;
    $response = $client->put($path, $data);

    return new self($client, $parent, $response->json());
  }

/**
 * Create object from API data
 *
 * @param MQTTClient $client
 * @param Device $device
 * @param stdClass $data
 */
  public function __construct(MQTTClient $client, Resource $parent, $data) {
    $this->parent = $parent;
    parent::__construct($client, $data);
  }

/**
 * The stream id for the REST URL
 *
 * @return string Stream ID
 */
  public function id() {
    return $this->name;
  }

/**
 * Returns the path to the resource
 *
 * @return string Stream path
 */
  public function path() {
    return str_replace(':parent_path', $this->parent->path(), self::$path) . '/' . $this->id();
  }

/**
 * Method for {@link https://m2x.att.com/developer/documentation/v2/device#Update-Data-Stream-Value Update Data Stream Value} endpoint.
 * The timestamp is optional. If ommited, the current server time will be used.
 *
 * @param string $value Value to be updated
 * @param string $timestamp Current Timestamp
 * @return void
 */
  public function updateValue($value, $timestamp = null) {
    $data = array('value' => $value);

    if ($timestamp) {
      $data['timestamp'] = $timestamp;
    }

    $this->client->put($this->path() . '/value', $data);
  }

/**
 * Method for {@link https://m2x.att.com/developer/documentation/v2/device#Post-Data-Stream-Values Post multiple values} endpoint.
 *
 * @param array $values Query parameters passed as keyword arguments. View M2X API Docs for listing of available parameters.
 * @return void
 */
  public function postValues($values) {
    $data = array('values' => $values);
    $response = $this->client->post($this->path() . '/values', $data);
  }
}


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

    /*global angular*/
    angular.module('MealCalories').factory('makeOnUpdate', factory);

    /**
     * @ngInject
     */
    function factory() {

        function makeUpdate(obj) {
            var updateListeners = Object.create(null);

            obj.onUpdate = onUpdate;
            obj.notify = notify;

            function notify(status) {
                Object.keys(updateListeners).forEach(function (id) {
                    updateListeners[id].call(null, status);
                });
            }

            /**
             * @param {function(...)} fn
             * @returns {function(...)}
             */
            function onUpdate(fn) {
                if (!angular.isFunction(fn)) {
                    return angular.noop;
                }
                var id = +Date.now();
                id = id.toString(16) + Math.random();
                updateListeners[id] = fn;
                function destroy() {
                    delete updateListeners[id];
                }
                return destroy;
            }

            return obj;
        }
        return makeUpdate;
    }

}());


text: Mr. Lockman, I'm Not at Home


text:
package org.apache.druid.testing.clients;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Predicates;
import com.google.inject.Inject;
import org.apache.druid.client.indexing.TaskStatusResponse;
import org.apache.druid.indexer.TaskState;
import org.apache.druid.indexer.TaskStatusPlus;
import org.apache.druid.indexing.overlord.supervisor.SupervisorStateManager;
import org.apache.druid.java.util.common.ISE;
import org.apache.druid.java.util.common.RetryUtils;
import org.apache.druid.java.util.common.StringUtils;
import org.apache.druid.java.util.common.jackson.JacksonUtils;
import org.apache.druid.java.util.common.logger.Logger;
import org.apache.druid.java.util.http.client.HttpClient;
import org.apache.druid.java.util.http.client.Request;
import org.apache.druid.java.util.http.client.response.StatusResponseHandler;
import org.apache.druid.java.util.http.client.response.StatusResponseHolder;
import org.apache.druid.testing.IntegrationTestingConfig;
import org.apache.druid.testing.guice.TestClient;
import org.apache.druid.testing.utils.ITRetryUtil;
import org.jboss.netty.handler.codec.http.HttpMethod;
import org.jboss.netty.handler.codec.http.HttpResponseStatus;

import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;

public class OverlordResourceTestClient
{
  private static final Logger LOG = new Logger(OverlordResourceTestClient.class);
  private final ObjectMapper jsonMapper;
  private final HttpClient httpClient;
  private final String indexer;

  @Inject
  OverlordResourceTestClient(
      ObjectMapper jsonMapper,
      @TestClient HttpClient httpClient,
      IntegrationTestingConfig config
  )
  {
    this.jsonMapper = jsonMapper;
    this.httpClient = httpClient;
    this.indexer = config.getIndexerUrl();
  }

  private String getIndexerURL()
  {
    return StringUtils.format(
        "%s/druid/indexer/v1/",
        indexer
    );
  }

  public String submitTask(final String task)
  {
    try {
      return RetryUtils.retry(
          () -> {
            StatusResponseHolder response = httpClient.go(
                new Request(HttpMethod.POST, new URL(getIndexerURL() + "task"))
                    .setContent(
                        "application/json",
                        StringUtils.toUtf8(task)
                    ),
                StatusResponseHandler.getInstance()
            ).get();
            if (!response.getStatus().equals(HttpResponseStatus.OK)) {
              throw new ISE(
                  "Error while submitting task to indexer response [%s %s]",
                  response.getStatus(),
                  response.getContent()
              );
            }
            Map<String, String> responseData = jsonMapper.readValue(
                response.getContent(), JacksonUtils.TYPE_REFERENCE_MAP_STRING_STRING
            );
            String taskID = responseData.get("task");
            LOG.info("Submitted task with TaskID[%s]", taskID);
            return taskID;
          },
          Predicates.alwaysTrue(),
          5
      );
    }
    catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  public TaskStatusPlus getTaskStatus(String taskID)
  {
    try {
      StatusResponseHolder response = makeRequest(
          HttpMethod.GET,
          StringUtils.format(
              "%stask/%s/status",
              getIndexerURL(),
              StringUtils.urlEncode(taskID)
          )
      );

      LOG.info("Index status response" + response.getContent());
      TaskStatusResponse taskStatusResponse = jsonMapper.readValue(
          response.getContent(),
          new TypeReference<TaskStatusResponse>()
          {
          }
      );
      return taskStatusResponse.getStatus();
    }
    catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  public List<TaskResponseObject> getRunningTasks()
  {
    return getTasks("runningTasks");
  }

  public List<TaskResponseObject> getWaitingTasks()
  {
    return getTasks("waitingTasks");
  }

  public List<TaskResponseObject> getPendingTasks()
  {
    return getTasks("pendingTasks");
  }

  public List<TaskResponseObject> getCompleteTasksForDataSource(final String dataSource)
  {
    return getTasks(StringUtils.format("tasks?state=complete&datasource=%s", StringUtils.urlEncode(dataSource)));
  }

  private List<TaskResponseObject> getTasks(String identifier)
  {
    try {
      StatusResponseHolder response = makeRequest(
          HttpMethod.GET,
          StringUtils.format("%s%s", getIndexerURL(), identifier)
      );
      LOG.info("Tasks %s response %s", identifier, response.getContent());
      return jsonMapper.readValue(
          response.getContent(), new TypeReference<List<TaskResponseObject>>()
          {
          }
      );
    }
    catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  public void waitUntilTaskCompletes(final String taskID)
  {
    waitUntilTaskCompletes(taskID, 10000, 60);
  }

  public void waitUntilTaskCompletes(final String taskID, final int millisEach, final int numTimes)
  {
    ITRetryUtil.retryUntil(
        new Callable<Boolean>()
        {
          @Override
          public Boolean call()
          {
            TaskState status = getTaskStatus(taskID).getStatusCode();
            if (status == TaskState.FAILED) {
              throw new ISE("Indexer task FAILED");
            }
            return status == TaskState.SUCCESS;
          }
        },
        true,
        millisEach,
        numTimes,
        taskID
    );
  }

  public void waitUntilTaskFails(final String taskID)
  {
    waitUntilTaskFails(taskID, 10000, 60);
  }

  public void waitUntilTaskFails(final String taskID, final int millisEach, final int numTimes)
  {
    ITRetryUtil.retryUntil(
        new Callable<Boolean>()
        {
          @Override
          public Boolean call()
          {
            TaskState status = getTaskStatus(taskID).getStatusCode();
            if (status == TaskState.SUCCESS) {
              throw new ISE("Indexer task SUCCEED");
            }
            return status == TaskState.FAILED;
          }
        },
        true,
        millisEach,
        numTimes,
        taskID
    );
  }

  public String submitSupervisor(String spec)
  {
    try {
      StatusResponseHolder response = httpClient.go(
          new Request(HttpMethod.POST, new URL(getIndexerURL() + "supervisor"))
              .setContent(
                  "application/json",
                  StringUtils.toUtf8(spec)
              ),
          StatusResponseHandler.getInstance()
      ).get();
      if (!response.getStatus().equals(HttpResponseStatus.OK)) {
        throw new ISE(
            "Error while submitting supervisor to overlord, response [%s %s]",
            response.getStatus(),
            response.getContent()
        );
      }
      Map<String, String> responseData = jsonMapper.readValue(
          response.getContent(), JacksonUtils.TYPE_REFERENCE_MAP_STRING_STRING
      );
      String id = responseData.get("id");
      LOG.info("Submitted supervisor with id[%s]", id);
      return id;
    }
    catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  public void shutdownSupervisor(String id)
  {
    try {
      StatusResponseHolder response = httpClient.go(
          new Request(
              HttpMethod.POST,
              new URL(StringUtils.format(
                  "%ssupervisor/%s/shutdown",
                  getIndexerURL(),
                  StringUtils.urlEncode(id)
              ))
          ),
          StatusResponseHandler.getInstance()
      ).get();
      if (!response.getStatus().equals(HttpResponseStatus.OK)) {
        throw new ISE(
            "Error while shutting down supervisor, response [%s %s]",
            response.getStatus(),
            response.getContent()
        );
      }
      LOG.info("Shutdown supervisor with id[%s]", id);
    }
    catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  public SupervisorStateManager.BasicState getSupervisorStatus(String id)
  {
    try {
      StatusResponseHolder response = httpClient.go(
          new Request(
              HttpMethod.GET,
              new URL(StringUtils.format(
                  "%ssupervisor/%s/status",
                  getIndexerURL(),
                  StringUtils.urlEncode(id)
              ))
          ),
          StatusResponseHandler.getInstance()
      ).get();
      if (!response.getStatus().equals(HttpResponseStatus.OK)) {
        throw new ISE(
            "Error while getting supervisor status, response [%s %s]",
            response.getStatus(),
            response.getContent()
        );
      }
      Map<String, Object> responseData = jsonMapper.readValue(
          response.getContent(), JacksonUtils.TYPE_REFERENCE_MAP_STRING_OBJECT
      );

      Map<String, Object> payload = jsonMapper.convertValue(
          responseData.get("payload"),
          JacksonUtils.TYPE_REFERENCE_MAP_STRING_OBJECT
      );
      String state = (String) payload.get("state");
      LOG.info("Supervisor id[%s] has state [%s]", id, state);
      return SupervisorStateManager.BasicState.valueOf(state);
    }
    catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  public void suspendSupervisor(String id)
  {
    try {
      StatusResponseHolder response = httpClient.go(
          new Request(
              HttpMethod.POST,
              new URL(StringUtils.format(
                  "%ssupervisor/%s/suspend",
                  getIndexerURL(),
                  StringUtils.urlEncode(id)
              ))
          ),
          StatusResponseHandler.getInstance()
      ).get();
      if (!response.getStatus().equals(HttpResponseStatus.OK)) {
        throw new ISE(
            "Error while suspending supervisor, response [%s %s]",
            response.getStatus(),
            response.getContent()
        );
      }
      LOG.info("Suspended supervisor with id[%s]", id);
    }
    catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  public void resumeSupervisor(String id)
  {
    try {
      StatusResponseHolder response = httpClient.go(
          new Request(
              HttpMethod.POST,
              new URL(StringUtils.format(
                  "%ssupervisor/%s/resume",
                  getIndexerURL(),
                  StringUtils.urlEncode(id)
              ))
          ),
          StatusResponseHandler.getInstance()
      ).get();
      if (!response.getStatus().equals(HttpResponseStatus.OK)) {
        throw new ISE(
            "Error while resuming supervisor, response [%s %s]",
            response.getStatus(),
            response.getContent()
        );
      }
      LOG.info("Resumed supervisor with id[%s]", id);
    }
    catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  private StatusResponseHolder makeRequest(HttpMethod method, String url)
  {
    try {
      StatusResponseHolder response = this.httpClient
          .go(new Request(method, new URL(url)), StatusResponseHandler.getInstance()).get();
      if (!response.getStatus().equals(HttpResponseStatus.OK)) {
        throw new ISE("Error while making request to indexer [%s %s]", response.getStatus(), response.getContent());
      }
      return response;
    }
    catch (Exception e) {
      LOG.error(e, "Exception while sending request");
      throw new RuntimeException(e);
    }
  }

}


text:
<?php

namespace AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpFoundation\Response;
use AppBundle\Entity\Project;
use AppBundle\Entity\UserProject;
use GitElephant\Repository;

class ProjectController extends Controller
{
    /**
     * show project info
     * @param $project_id
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function showAction($project_id)
    {

        $project = $this->getDoctrine()->getRepository('AppBundle:Project')->find($project_id);

        if (!$project) {
            throw new NotFoundHttpException('Project not found');
        }

        return $this->render('AppBundle:Project:show.html.twig', array(
            'project' => $project
        ));
    }

    /**
     * build a project
     *
     * @param $project_id
     * @return Response
     */
    public function buildAction($project_id)
    {
        $project = $this->getDoctrine()->getRepository('AppBundle:Project')->find($project_id);

        if (!$project) {
            throw new NotFoundHttpException('Project not found');
        }

        $em = $this->getDoctrine()->getManager();

        // update folder
        $projectFolder = md5(uniqid());
        $project->setFolder($projectFolder);
        $em->persist($project);
        $em->flush();

        // create project from projecter
        $projectURL = $this->get('projecter')->buildAndSetup($projectFolder, $project);

        return $this->render('AppBundle:Project:build.html.twig', array(
            'projectURL'     => $projectURL
        ));
    }

    /**
     * list user projects
     *
     * @return Response
     */
    public function listAction()
    {
        $user = $this->getUser();

        $projects = $this->getDoctrine()->getRepository('AppBundle:User')->getProjectsForUser($user);

        $host = $this->get('router')->getContext()->getHost();
        $projecterRootFolder = $this->container->getParameter('projecter_root_folder');
        $homeFileName = $this->container->getParameter('projecter_home_filename');

        return $this->render('AppBundle:Project:list.html.twig', array(
            'projects'            => $projects,
            'host'                => $host,
            'homeFileName'        => $homeFileName,
            'projecterRootFolder' => $projecterRootFolder
        ));
    }

    /**
     * start/create project for requisite
     *
     * @param $requisite_id
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function startAction($requisite_id)
    {
        $em = $this->getDoctrine()->getManager();

        $requisite = $this->getDoctrine()->getRepository('AppBundle:Requisite')->find($requisite_id);
        $project = $requisite->getProject();

        if ($project) {
            throw new NotFoundHttpException('Requisite already have project');
        }

        $project = new Project();
        $project->setRequisite($requisite);
        $project->setStatus(0);
        $projecter = $this->get('projecter');

        // heroky app create
        $herokuResponse = $projecter->buildHerokuProject(
            false,
            $requisite->getUser()->getHerokuApiToken()
        );

        // github create repository
        $loginString = $requisite->getUser()->getGitHubAccountUser() . ":".$requisite->getUser()->getGitHubAccountPassword();
        $projecter->createGitHubRepository($herokuResponse["name"], $loginString);

        // Create auhtorization token
        $gitHubToken = $projecter->createGitHubToken($loginString);
        $herokuToken = $projecter->createHerokuToken($requisite->getUser()->getHerokuApiToken());

        // create webhooks Auto-Deploy
        $projecter->createGitHubHookAutoDeployForRepository(
            $herokuResponse["name"],
            $gitHubToken,
            $loginString
        );

        // create webhooks HerokuBeta
        $projecter->createGitHubHerokuBetaForRepository(
            $herokuResponse["name"],
            $gitHubToken,
            $herokuToken,
            $loginString
        );

        // set fields entity
        $project->setHerokuIdentifier($herokuResponse["id"]);
        $project->setHerokuGit($herokuResponse["git_url"]);
        $project->setHerokuHttp($herokuResponse["web_url"]);
        $project->setName($herokuResponse["name"]);
        $project->setGitHubToken($gitHubToken);
        $project->setHerokuToken($herokuToken);
        $project->setGitHubRepositoryName($herokuResponse["name"]);

        // UserProject
        $userProject = new UserProject();
        $userProject->setProject($project);
        $userProject->setUser($this->getUser());

        $em->persist($userProject);
        $em->persist($project);

        $em->flush();

        return $this->redirectToRoute('project_list');
    }
}


text:
var _FULL_WIDTH_DIFF_CODE = 65248;
var _FULL_WIDTH_SPACE_CODE = 12288;
var _HALF_WIDTH_SPACE_CODE = 32;
var _RANGE_CODES = {
  MIN: 33,
  MAX: 126,
};

/**
 * @private
 * @param {String} strs
 * @type function
 */
var _forEachByString = function(strs, func) {
  var len = strs.length,
    result = [];

  for (var i = 0; i < len; i++) {
    result.push(func(strs[i], strs[i].charCodeAt(0)));
  }
  return result.join("");
};

/**
 * @namespace
 */
var stringFormUtils = {
  /**
   * @param {String} val
   * @type String
   */
  transformToFullwidth: function(val) {
    return _forEachByString(val, function(str, code) {
      var result = str;

      if (_HALF_WIDTH_SPACE_CODE == code)
        result = String.fromCharCode(_FULL_WIDTH_SPACE_CODE);
      else if (_RANGE_CODES.MIN <= code && code <= _RANGE_CODES.MAX)
        result = String.fromCharCode(code + _FULL_WIDTH_DIFF_CODE);

      return result;
    });
  },

  /**
   * @param {String} val
   * @type String
   */
  transformToHalfwidth: function(val) {
    return _forEachByString(val, function(str, code) {
      var result = str;

      if (_FULL_WIDTH_SPACE_CODE == code)
        result = String.fromCharCode(_HALF_WIDTH_SPACE_CODE);
      else if (
        _RANGE_CODES.MIN + _FULL_WIDTH_DIFF_CODE <= code &&
        code <= _RANGE_CODES.MAX + _FULL_WIDTH_DIFF_CODE
      )
        result = String.fromCharCode(code - _FULL_WIDTH_DIFF_CODE);

      return result;
    });
  },
};

module.exports = stringFormUtils;


text:
module Presto
  module HTTP
    class InstanceApi

      # get / set cookies
      def cookies
        @cookies__proxy ||= CookiesProxy.new @request, @response
      end

      class CookiesProxy

        def initialize request, response
          @request, @response = request, response
        end

        # instruct browser to set/update cookie
        #
        # @param [String, Symbol] key
        # @param [String] val
        # @return [Boolean]
        def []= key, val
          return if confined?
          @response.set_cookie key, val
        end

        # get cookie by key
        def [] key
          @request.cookies[key]
        end

        # instruct browser to delete a cookie
        #
        # @param [String, Symbol] key
        # @param [Hash] opts
        # @return [Boolean]
        def delete key, opts ={}
          return if confined?
          @response.delete_cookie key, opts
        end

        # prohibit further cookies writing
        #
        # @example prohibit writing for all actions
        #    http.before do
        #      http.cookies.confine
        #    end
        #
        # @example prohibit writing selectively
        #    http.before :render_page do |action|
        #      http.cookies.confine
        #    end
        def confine
          @confined = true
        end

        def confined?
          @confined
        end

      end

    end
  end
end


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.teamkrunch.ck16.hanger;

import com.teamkrunch.ck16.RobotMap;
import edu.wpi.first.wpilibj.DoubleSolenoid;
import edu.wpi.first.wpilibj.command.Subsystem;

/**
 *
 * @author sebastian
 */
public class Hanger extends Subsystem {

    private boolean isExtended;
    private DoubleSolenoid hangA, hangB;

    public Hanger(){
        isExtended = false;
        hangA = RobotMap.hangPistonA;
        hangB = RobotMap.hangPistonB;
    }

    public void set(boolean state){
        hangA.set(state ? DoubleSolenoid.Value.kForward : DoubleSolenoid.Value.kReverse);
        hangB.set(!state ? DoubleSolenoid.Value.kForward : DoubleSolenoid.Value.kReverse);
        isExtended = state;
    }

    public boolean isExtended(){
        return isExtended;
    }

    public void extend(){
        set(true);
    }

    public void retract(){
        set(false);
    }

    public void invertCurrentState(){
        set(!isExtended());
    }

    /* We don't want it to retract on its own because we're going to
     * be inverting it most of the time. */
    public void initDefaultCommand() {}
}


text:
//=======================================================================
// Copyright (c) 2014-2020 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

/*!
 * \file
 * \brief Enumeration for the bias_add implementations
 */

#pragma once

namespace etl {

/*!
 * \brief Enumeration describing the different implementations of
 * bias_add
 */
enum class bias_add_impl {
    STD,    ///< Standard implementation
    VEC,    ///< VEC implementation
    EGBLAS, ///< ETL-GPU-BLAS (GPU) implementation
    CUDNN   ///< CUDNN (GPU) implementation
};

} //end of namespace etl


text:
require_relative '../../spec_helper'
require_lib 'reek/smell_detectors/class_variable'

RSpec.describe Reek::SmellDetectors::ClassVariable do
  it 'reports the right values' do
    src = <<-RUBY
      class Alfa
        @@bravo = 5
      end
    RUBY

    expect(src).to reek_of(:ClassVariable,
                           lines:   [2],
                           context: 'Alfa',
                           message: "declares the class variable '@@bravo'",
                           source:  'string',
                           name:    '@@bravo')
  end

  it 'does count all class variables' do
    src = <<-RUBY
      class Alfa
        @@bravo = 42
        @@charlie = 99
      end
    RUBY

    expect(src).
      to reek_of(:ClassVariable, name: '@@bravo').
      and reek_of(:ClassVariable, name: '@@charlie')
  end

  it 'does not report class instance variables' do
    src = <<-RUBY
      class Alfa
        @bravo = 42
      end
    RUBY

    expect(src).not_to reek_of(:ClassVariable)
  end

  context 'with no class variables' do
    it 'records nothing in the class' do
      src = <<-RUBY
        class Alfa
          def bravo; end
        end
      RUBY

      expect(src).not_to reek_of(:ClassVariable)
    end

    it 'records nothing in the module' do
      src = <<-RUBY
        module Alfa
          def bravo; end
        end
      RUBY

      expect(src).not_to reek_of(:ClassVariable)
    end
  end

  ['class', 'module'].each do |scope|
    context "when examining a #{scope}" do
      it 'reports a class variable set in a method' do
        src = <<-RUBY
          #{scope} Alfa
            def bravo
              @@charlie = {}
            end
          end
        RUBY

        expect(src).to reek_of(:ClassVariable, name: '@@charlie')
      end

      it 'reports a class variable used in a method' do
        src = <<-RUBY
          #{scope} Alfa
            def bravo
              puts @@charlie
            end
          end
        RUBY

        expect(src).to reek_of(:ClassVariable, name: '@@charlie')
      end

      it "reports a class variable set in the #{scope} body and used in a method" do
        src = <<-RUBY
          #{scope} Alfa
            @@bravo = 42

            def charlie
              puts @@bravo
            end
          end
        RUBY

        expect(src).to reek_of(:ClassVariable, name: '@@bravo')
      end
    end
  end
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;

namespace Map27Decode
{
    class TapStreamDecoder
    {
        #region Public Enums

        public enum ProcessingResult
        {
            Ok,
            FcsError,
            FormatError,
            OutOfFrameBytesFound
        }

        #endregion Public Enums

        #region Public Delegates

        public delegate void ProcessingComplete(ProcessingResult result);

        #endregion Public Delegates

        #region Public Events

        public event ProcessingComplete OnProcessingComplete;

        #endregion Public Events

        #region Public Properties

        public ReadOnlyCollection<byte> Map27Packet
        {
            get { return new ReadOnlyCollection<byte>(m_Map27Packet); }
        }

        public ReadOnlyCollection<byte> OutOfFrameBytes
        {
            get { return new ReadOnlyCollection<byte>(m_OutOfFrameBytes); }
        }

        public double MessageEndTime
        {
            get { return m_MessageEndTime; }
        }

        public string MessageEndTimeText
        {
            get { return m_MessageEndTimeText; }
        }

        public double MessageStartTime
        {
            get { return m_MessageStartTime; }
        }
        public string MessageStartTimeText
        {
            get { return m_MessageStartTimeText; }
        }

        #endregion Public Properties

        #region Internal Methods

        internal void Decode(byte[] message, int startPos, int length, string logTime, double timeStamp)
        {
            for (int index = startPos, count = 0; count < length; index++, count++)
            {
                m_InputQueue.Enqueue(message[index]);
            }

            bool processedPayload = false;
            while (m_InputQueue.Count > 0)
            {
                switch (m_ProcessingState)
                {
                    case ProcessingState.Idle:
                        DoIdleProcess(logTime, timeStamp);
                        break;
                    case ProcessingState.Sync_Rx_SYN:
                        ProcessRxSyn();
                        break;
                    case ProcessingState.Sync_Rx_DLE:
                        ProcessRxDLE();
                        break;
                    case ProcessingState.Payload:
                        if (m_OutOfFrameBytes.Count > 0)
                        {
                            m_MessageStartTime = timeStamp;
                            m_MessageStartTimeText = logTime;
                            m_MessageEndTime = timeStamp;
                            m_MessageEndTimeText = logTime;
                            ReportOutOfFrameBytes();
                        }

                        ProcessPayload();
                        break;
                    case ProcessingState.Payload_Rx_DLE:
                        ProcessPayloadRxDLE();
                        break;
                    case ProcessingState.Tail:
                        processedPayload = true;
                        ProcessTail(logTime, timeStamp);
                        break;
                }
            }

            if (!processedPayload && m_OutOfFrameBytes.Count > 0)
            {
                m_MessageStartTime = timeStamp;
                m_MessageStartTimeText = logTime;
                m_MessageEndTime = timeStamp;
                m_MessageEndTimeText = logTime;
                ReportOutOfFrameBytes();
            }
        }

        private void ReportOutOfFrameBytes()
        {
            OnProcessingComplete(ProcessingResult.OutOfFrameBytesFound);
            m_OutOfFrameBytes.Clear();
        }

        internal void Reset()
        {
            m_ProcessingState = ProcessingState.Idle;
            m_InputQueue.Clear();
        }

        #endregion Internal Methods

        #region Private Enums

        enum ProcessingState
        {
            Idle,
            Sync_Rx_SYN,
            Sync_Rx_DLE,
            Payload,
            Payload_Rx_DLE,
            Tail
        }

        #endregion Private Enums

        #region Private Methods

        private void DoIdleProcess(string logTime, double timestamp)
        {
            m_FcsError = false;

            byte inByte = m_InputQueue.Dequeue();
            if (inByte == SYN)
            {
                m_ProcessingState = ProcessingState.Sync_Rx_SYN;
                m_MessageStartTime = timestamp;
                m_MessageStartTimeText = logTime;
            }
            else
            {
                m_OutOfFrameBytes.Add(inByte);
            }
        }

        private void ProcessPayload()
        {
            // End of payload signalled by DLE ETX
            // DTE DTE is converted to DLE in payload
            while (m_InputQueue.Count > 0 && m_ProcessingState == ProcessingState.Payload)
            {
                byte inByte = m_InputQueue.Dequeue();

                if (inByte == DLE)
                {
                    m_ProcessingState = ProcessingState.Payload_Rx_DLE;
                }
                else
                {
                    m_Map27Packet.Add(inByte);
                }
            }
        }

        private void ProcessPayloadRxDLE()
        {
            // DLE DLE in packet is converted to DLE in payload (DLE stuffing)
            // End of payload signalled by DLE ETX
            // DLE <other> is stored as-is in payload
            byte inByte = m_InputQueue.Dequeue();
            if (inByte == DLE)
            {
                m_ProcessingState = ProcessingState.Payload;
                m_Map27Packet.Add(inByte);
            }
            else if (inByte == ETX)
            {
                m_ProcessingState = ProcessingState.Tail;
                m_Fcs.Clear();
            }
            else
            {
                m_Map27Packet.Add(DLE);

                m_Map27Packet.Add(inByte);
            }
        }

        private void ProcessRxDLE()
        {
            byte inByte = m_InputQueue.Dequeue();
            if (inByte == STX)
            {
                m_ProcessingState = ProcessingState.Payload;
                m_Map27Packet.Clear();
            }
            else
            {
                m_OutOfFrameBytes.Add(inByte);
                m_ProcessingState = ProcessingState.Idle;
            }
        }

        private void ProcessRxSyn()
        {
            byte inByte = m_InputQueue.Dequeue();
            if (inByte == DLE)
            {
                m_ProcessingState = ProcessingState.Sync_Rx_DLE;
            }
            else
            {
                m_OutOfFrameBytes.Add(inByte);
                m_ProcessingState = ProcessingState.Idle;
            }
        }

        private void ProcessTail(string logTime, double timeStamp)
        {
            while (m_InputQueue.Count > 0 && m_Fcs.Count < FcsLength)
            {
                m_Fcs.Add(m_InputQueue.Dequeue());
            }

            if (m_Fcs.Count == FcsLength)
            {
                ValidateFcs();
                if (OnProcessingComplete != null)
                {
                    if (m_FcsError)
                    {
                        OnProcessingComplete(ProcessingResult.FcsError);
                    }
                    else
                    {
                        m_MessageEndTime = timeStamp;
                        m_MessageEndTimeText = logTime;
                        OnProcessingComplete(ProcessingResult.Ok);
                    }
                }

                m_ProcessingState = ProcessingState.Idle;
            }
        }

        private void ValidateFcs()
        {
            // The packet body (header and data) and DLE ETX stop flag are included in the FCS
            // calculation. The start sequence and all DLE control characters used to maintain
            // data transparency are excluded from the FCS calculation.
            byte[] fcsBuffer = new byte[m_Map27Packet.Count + 2];
            int fcsBufferIndex = 0;
            foreach (byte b in m_Map27Packet)
            {
                fcsBuffer[fcsBufferIndex++] = b;
            }
            fcsBuffer[fcsBufferIndex++] = DLE;
            fcsBuffer[fcsBufferIndex++] = ETX;

            UInt16 fcsRead = (UInt16)((m_Fcs[0] << 8) + (UInt16)m_Fcs[1]);
            UInt16 fcsCalculated = m_Crc16.CalculateCrc(fcsBuffer);

            m_FcsError = (fcsRead != fcsCalculated);
        }

        #endregion Private Methods

        #region Private Fields

        const byte DLE = 0x10;
        const byte ETX = 0x03;
        const int FcsLength = 2;
        const int L2HeaderLength = 4;
        const byte STX = 0x02;
        const byte SYN = 0x16;
        Crc16 m_Crc16 = new Crc16();
        List<byte> m_Fcs = new List<byte>();
        bool m_FcsError;
        Queue<byte> m_InputQueue = new Queue<byte>();
        List<byte> m_Map27Packet = new List<byte>();
        double m_MessageEndTime;
        string m_MessageEndTimeText;
        double m_MessageStartTime;
        string m_MessageStartTimeText;
        private List<byte> m_OutOfFrameBytes = new List<byte>();
        private ProcessingState m_ProcessingState = ProcessingState.Idle;

        #endregion Private Fields
    }
}


text:
package org.kie.workbench.common.stunner.core.rule.context.impl;

import java.util.Optional;
import java.util.Set;

import org.kie.workbench.common.stunner.core.rule.RuleEvaluationContext;
import org.kie.workbench.common.stunner.core.rule.context.ConnectionContext;

class ConnectionContextImpl implements ConnectionContext {

    private final String connectorRole;
    private final Optional<Set<String>> sourceRoles;
    private final Optional<Set<String>> targetRoles;

    ConnectionContextImpl(final String connectorRole,
                          final Optional<Set<String>> sourceRoles,
                          final Optional<Set<String>> targetRoles) {
        this.connectorRole = connectorRole;
        this.sourceRoles = sourceRoles;
        this.targetRoles = targetRoles;
    }

    @Override
    public String getConnectorRole() {
        return connectorRole;
    }

    @Override
    public Optional<Set<String>> getSourceRoles() {
        return sourceRoles;
    }

    @Override
    public Optional<Set<String>> getTargetRoles() {
        return targetRoles;
    }

    @Override
    public String getName() {
        return "Connection";
    }

    @Override
    public boolean isDefaultDeny() {
        return true;
    }

    @Override
    public Class<? extends RuleEvaluationContext> getType() {
        return ConnectionContext.class;
    }
}


text:
sudo yum install -y rpm-build rpmdevtools git

# Clone rep
git clone https://github.com/guilhemmarchand/nmon-logger.git

# Enter rep
cd nmon-logger

# Checkout testing
git checkout testing; git pull

# Go back home
cd

# Create rpm tree
rpmdev-setuptree

# Copy sources
cp -a nmon-logger/nmon-logger-rsyslog rpmbuild/SOURCES/
cp -a nmon-logger/nmon-logger-syslog-ng rpmbuild/SOURCES/
cp -a nmon-logger/nmon-logger-splunk-hec rpmbuild/SOURCES/

# Create tar archives
cd rpmbuild/SOURCES/
for i in `ls -d * | grep -v tar.gz`; do
tar -cvzf $i.tar.gz $i
done

# Go back home
cd

# Copy specs
cp nmon-logger/rpmbuild/SPECS/*.spec rpmbuild/SPECS/

# Enter build
cd rpmbuild

# Build rpms
for i in `ls SPECS/*.spec`; do
rpmbuild -ba $i
done

exit 0