text:
package workflow

import (
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/suite"
	"github.com/venicegeo/pz-gocommon/elasticsearch"
	"github.com/venicegeo/pz-gocommon/gocommon"
)

type ClientTester struct {
	suite.Suite
	client *Client
	sys    *piazza.SystemConfig
}

func (suite *ClientTester) SetupSuite() {
	assertNoData(suite.T(), suite.client)
}

func (suite *ClientTester) TearDownSuite() {
	assertNoData(suite.T(), suite.client)
}

//---------------------------------------------------------------------------

func (suite *ClientTester) Test11Admin() {
	t := suite.T()
	assert := assert.New(t)

	client := suite.client

	_, err := client.GetStats()
	assert.NoError(err)
}

func (suite *ClientTester) Test12AlertResource() {
	t := suite.T()
	assert := assert.New(t)
	client := suite.client

	assertNoData(suite.T(), client)
	defer assertNoData(suite.T(), client)

	var err error

	a1 := Alert{TriggerID: "dummyT1", EventID: "dummyE1"}
	respAlert, err := client.PostAlert(&a1)
	id := respAlert.AlertID
	assert.NoError(err)

	alerts, err := client.GetAllAlerts(100, 0)
	assert.NoError(err)
	assert.Len(*alerts, 1)
	assert.EqualValues(id, (*alerts)[0].AlertID)
	assert.EqualValues("dummyT1", (*alerts)[0].TriggerID)
	assert.EqualValues("dummyE1", (*alerts)[0].EventID)

	alert, err := client.GetAlert(id)
	assert.NoError(err)
	assert.EqualValues(id, alert.AlertID)

	alert, err = client.GetAlert("nosuchalert1")
	assert.Error(err)

	err = client.DeleteAlert("nosuchalert2")
	assert.Error(err)

	err = client.DeleteAlert(id)
	assert.NoError(err)

	alert, err = client.GetAlert(id)
	assert.Error(err)

	alerts, err = client.GetAllAlerts(100, 0)
	assert.NoError(err)
	assert.Len(*alerts, 0)
}

func (suite *ClientTester) Test13EventResource() {
	t := suite.T()
	assert := assert.New(t)
	client := suite.client

	assertNoData(suite.T(), client)
	defer assertNoData(suite.T(), client)

	var err error

	mapping := map[string]interface{}{
		"myint": elasticsearch.MappingElementTypeString,
		"mystr": elasticsearch.MappingElementTypeString,
	}
	eventTypeName := "mytype"
	eventType := &EventType{Name: eventTypeName, Mapping: mapping}
	respEventType, err := client.PostEventType(eventType)
	etID := respEventType.EventTypeID
	assert.NoError(err)
	defer func() {
		err = client.DeleteEventType(etID)
		assert.NoError(err)
	}()

	event := &Event{
		EventTypeID: etID,
		CreatedOn:   piazza.NewTimeStamp(),
		Data: map[string]interface{}{
			"myint": 17,
			"mystr": "quick",
		},
	}
	respEvent, err := client.PostEvent(event)
	eID := respEvent.EventID
	assert.NoError(err)

	defer func() {
		err = client.DeleteEvent(eID)
		assert.NoError(err)
	}()

	//events, err := workflow.GetAllEvents("")
	//assert.NoError(err)
	//assert.Len(*events, 1)
	//assert.EqualValues(eID, (*events)[0].ID)

	tmp, err := client.GetEvent(eID)
	assert.NoError(err)
	assert.EqualValues(eID, tmp.EventID)
}

func (suite *ClientTester) Test14EventTypeResource() {
	t := suite.T()
	assert := assert.New(t)
	client := suite.client

	assertNoData(suite.T(), client)
	defer assertNoData(suite.T(), client)

	var err error

	mapping := map[string]interface{}{
		"myint": elasticsearch.MappingElementTypeString,
		"mystr": elasticsearch.MappingElementTypeString,
	}
	eventType := &EventType{Name: "typnam", Mapping: mapping}
	respEventType, err := client.PostEventType(eventType)
	id := respEventType.EventTypeID
	defer func() {
		err = client.DeleteEventType(id)
		assert.NoError(err)
	}()
	_, _ = client.GetEventTypeByName("typnam")

	eventTypes, err := client.GetAllEventTypes(100, 0)
	assert.NoError(err)
	assert.Len(*eventTypes, 3)

	// Find the right event type and assert
	var theType EventType
	for _, eventtyp := range *eventTypes {
		if eventtyp.EventTypeID == id {
			theType = eventtyp
		}
	}
	assert.EqualValues(id, theType.EventTypeID)

	tmp, err := client.GetEventType(id)
	assert.NoError(err)
	assert.EqualValues(id, tmp.EventTypeID)
}

func (suite *ClientTester) Test15One() {

	t := suite.T()
	assert := assert.New(t)
	client := suite.client

	assertNoData(suite.T(), client)
	defer assertNoData(suite.T(), client)

	var eventTypeName = "EventTypeA"

	var etID piazza.Ident
	{
		mapping := map[string]interface{}{
			"num": elasticsearch.MappingElementTypeInteger,
			"str": elasticsearch.MappingElementTypeString,
		}

		eventType := &EventType{Name: eventTypeName, Mapping: mapping}

		respEventType, err := client.PostEventType(eventType)
		etID = respEventType.EventTypeID
		assert.NoError(err)

		defer func() {
			err := client.DeleteEventType(etID)
			assert.NoError(err)
		}()
	}

	var tID piazza.Ident
	{
		x1 := &Trigger{
			Name:        "the x1 trigger",
			EventTypeID: etID,
			Condition: map[string]interface{}{
				"query": map[string]interface{}{
					"match": map[string]interface{}{
						"num": 17,
					},
				},
			},
			Job: JobRequest{
				CreatedBy: "test",
				JobType: JobType{
					Type: "execute-service",
					Data: map[string]interface{}{
						// "dataInputs": map[string]interface{},
						// "dataOutput": map[string]interface{},
						"serviceId": "ddd5134",
					},
				},
			},
		}

		respTrigger, err := client.PostTrigger(x1)
		tID = respTrigger.TriggerID
		assert.NoError(err)

		defer func() {
			err := client.DeleteTrigger(tID)
			assert.NoError(err)
		}()
	}

	var e1ID piazza.Ident
	{
		// will cause trigger t1ID
		e1 := &Event{
			EventTypeID: etID,
			CreatedOn:   piazza.NewTimeStamp(),
			Data: map[string]interface{}{
				"num": 17,
				"str": "quick",
			},
		}

		respEvent1, err := client.PostEvent(e1)
		e1ID = respEvent1.EventID
		assert.NoError(err)

		defer func() {
			err := client.DeleteEvent(e1ID)
			assert.NoError(err)
		}()
	}

	var e2ID piazza.Ident
	{
		// will cause no triggers
		e2 := &Event{
			EventTypeID: etID,
			CreatedOn:   piazza.NewTimeStamp(),
			Data: map[string]interface{}{
				"num": 18,
				"str": "brown",
			},
		}

		respEvent2, err := client.PostEvent(e2)
		e2ID = respEvent2.EventID
		assert.NoError(err)

		defer func() {
			err := client.DeleteEvent(e2ID)
			assert.NoError(err)
		}()
	}
}

func (suite *ClientTester) Test16TriggerResource() {
	t := suite.T()
	assert := assert.New(t)
	client := suite.client

	assertNoData(suite.T(), client)
	defer assertNoData(suite.T(), client)

	var err error

	mapping := map[string]interface{}{
		"myint": elasticsearch.MappingElementTypeString,
		"mystr": elasticsearch.MappingElementTypeString,
	}
	eventType := &EventType{Name: "typnam2", Mapping: mapping}
	respEventType, err := client.PostEventType(eventType)
	etID := respEventType.EventTypeID

	defer func() {
		err = client.DeleteEventType(etID)
		assert.NoError(err)
	}()

	t1 := Trigger{
		Name:        "the x1 trigger",
		EventTypeID: etID,
		Condition: map[string]interface{}{
			"match": map[string]interface{}{
				"myint": 17,
			},
		},
		Job: JobRequest{
			CreatedBy: "test",
			JobType: JobType{
				Type: "execute-service",
				Data: map[string]interface{}{
					// "dataInputs": map[string]interface{},
					// "dataOutput": map[string]interface{},
					"serviceId": "ddd5134",
				},
			},
		},
	}
	respTrigger, err := client.PostTrigger(&t1)
	t1ID := respTrigger.TriggerID
	assert.NoError(err)

	defer func() {
		err = client.DeleteTrigger(t1ID)
		assert.NoError(err)
	}()

	tmp, err := client.GetTrigger(t1ID)
	assert.NoError(err)
	assert.EqualValues(t1ID, tmp.TriggerID)

	triggers, err := client.GetAllTriggers(100, 0)
	assert.NoError(err)
	assert.Len(*triggers, 1)
	assert.EqualValues(t1ID, (*triggers)[0].TriggerID)
}

func (suite *ClientTester) Test17Triggering() {

	t := suite.T()
	assert := assert.New(t)
	client := suite.client

	assertNoData(suite.T(), client)
	defer assertNoData(suite.T(), client)

	//-----------------------------------------------------

	var etC, etD, etE piazza.Ident
	{
		mapping := map[string]interface{}{
			"num": elasticsearch.MappingElementTypeInteger,
			"str": elasticsearch.MappingElementTypeString,
		}
		eventTypeC := &EventType{Name: "EventType C", Mapping: mapping}
		eventTypeD := &EventType{Name: "EventType D", Mapping: mapping}
		eventTypeE := &EventType{Name: "EventType E", Mapping: mapping}
		respEventTypeC, err := client.PostEventType(eventTypeC)
		etC = respEventTypeC.EventTypeID
		assert.NoError(err)
		respEventTypeD, err := client.PostEventType(eventTypeD)
		etD = respEventTypeD.EventTypeID
		assert.NoError(err)
		respEventTypeE, err := client.PostEventType(eventTypeE)
		etE = respEventTypeE.EventTypeID
		assert.NoError(err)

		eventTypes, err := client.GetAllEventTypes(100, 0)
		assert.NoError(err)
		assert.Len(*eventTypes, 5)
	}

	defer func() {
		err := client.DeleteEventType(etC)
		assert.NoError(err)
		err = client.DeleteEventType(etD)
		assert.NoError(err)
		err = client.DeleteEventType(etE)
		assert.NoError(err)
	}()

	////////////////

	var tB piazza.Ident
	{
		t1 := &Trigger{
			Name:        "Trigger A",
			EventTypeID: etC,
			Condition: map[string]interface{}{
				"query": map[string]interface{}{
					"match": map[string]interface{}{
						"str": "quick",
					},
				},
			},
			Job: JobRequest{
				CreatedBy: "test",
				JobType: JobType{
					Type: "execute-service",
					Data: map[string]interface{}{
						// "dataInputs": map[string]interface{},
						// "dataOutput": map[string]interface{},
						"serviceId": "ddd5134",
					},
				},
			},
		}
		respTriggerA, err := client.PostTrigger(t1)
		tA := respTriggerA.TriggerID
		assert.NoError(err)
		defer func() {
			err = client.DeleteTrigger(tA)
			assert.NoError(err)
		}()

		t2 := &Trigger{
			Name:        "Trigger B",
			EventTypeID: etD,
			Condition: map[string]interface{}{
				"query": map[string]interface{}{
					"match": map[string]interface{}{
						"num": 18,
					},
				},
			},
			Job: JobRequest{
				CreatedBy: "test",
				JobType: JobType{
					Type: "execute-service",
					Data: map[string]interface{}{
						// "dataInputs": map[string]interface{},
						// "dataOutput": map[string]interface{},
						"serviceId": "ddd5134",
					},
				},
			},
		}
		respTriggerB, err := client.PostTrigger(t2)
		tB = respTriggerB.TriggerID
		assert.NoError(err)
		defer func() {
			err = client.DeleteTrigger(tB)
			assert.NoError(err)
		}()

		triggers, err := client.GetAllTriggers(100, 0)
		assert.NoError(err)
		assert.Len(*triggers, 2)
	}

	var eF, eG, eH piazza.Ident
	{
		// will cause trigger TA
		e1 := Event{
			EventTypeID: etC,
			CreatedOn:   piazza.NewTimeStamp(),
			Data: map[string]interface{}{
				"num": 17,
				"str": "quick",
			},
		}
		respEventF, err := client.PostEvent(&e1)
		eF = respEventF.EventID
		assert.NoError(err)
		defer func() {
			err = client.DeleteEvent(eF)
			assert.NoError(err)
		}()

		// will cause trigger TB
		e2 := Event{
			EventTypeID: etD,
			CreatedOn:   piazza.NewTimeStamp(),
			Data: map[string]interface{}{
				"num": 18,
				"str": "brown",
			},
		}
		respEventG, err := client.PostEvent(&e2)
		eG = respEventG.EventID
		assert.NoError(err)
		defer func() {
			err = client.DeleteEvent(eG)
			assert.NoError(err)
		}()

		// will cause no triggers
		e3 := Event{
			EventTypeID: etE,
			CreatedOn:   piazza.NewTimeStamp(),
			Data: map[string]interface{}{
				"num": 19,
				"str": "fox",
			},
		}
		respEventH, err := client.PostEvent(&e3)
		eH = respEventH.EventID
		assert.NoError(err)
		defer func() {
			err = client.DeleteEvent(eH)
			assert.NoError(err)
		}()
	}
}


text:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html" charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />

    <title>Yann's blog</title>
    <meta name="description" content="" />

    <meta name="HandheldFriendly" content="True" />
    <meta name="MobileOptimized" content="320" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <link rel="stylesheet" type="text/css" href="//YannDanthu.github.io/themes/the-shell/assets/highlighter/prettify.css?v=1589891896936" />
    <link rel="stylesheet" type="text/css" href="//YannDanthu.github.io/themes/the-shell/assets/css/screen.css?v=1589891896936" />

    <link rel="canonical" href="https://YannDanthu.github.io/" />
    <meta name="referrer" content="origin" />

    <meta property="og:site_name" content="Yann's blog" />
    <meta property="og:type" content="website" />
    <meta property="og:title" content="Yann's blog" />
    <meta property="og:url" content="https://YannDanthu.github.io/" />
    <meta name="twitter:card" content="summary" />
    <meta name="twitter:title" content="Yann's blog" />
    <meta name="twitter:url" content="https://YannDanthu.github.io/" />

    <meta name="generator" content="HubPress" />
    <link rel="alternate" type="application/rss+xml" title="Yann's blog" href="https://YannDanthu.github.io/rss/" />
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/prism/1.14.0/themes/prism-okaidia.min.css">

Yann's blog

This blog is mainly used as an FAQ and Tips reminder for myself ;)

            <time datetime="2020-05-19">19 May 2020</time> on ffmpeg, mp3, wav

ffmpeg convert mp3 to wav

ffmpeg -i file.mp3 -acodec pcm_u8 -ar 22050 file.wav…

            <time datetime="2020-05-17">17 May 2020</time> on dev, shell, rsync

How To Use Rsync to Sync with a Remote System

rsync -aP localPath user@remoteTarget:remotePath The -P option combines –progress and –partial The -a (--archive) option combines -rlptgoD Add -z to compress data if it’s worth it.…

            <time datetime="2020-05-12">12 May 2020</time> on dev, git

My git cheatsheet

Some pretty usefull git command I never remember :) Remove all local branches already merged in master git branch --merged master | xargs -L1 git branch -d and to keep master out of the result a grep will do git branch --merged master | grep -v "master" | xargs -L1 git branch -d update…

            <time datetime="2019-07-04">04 Jul 2019</time> on Stripe, NestJS, How-To, javascript

Checking Stripe Webhook Signatures from NestJS

The short story You are using NestJS and want to verify Stripe Webhook signature but your  are facing the following error Error: No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe? https://github.com/stripe/stripe-node#webhook-signing Stripe needs…

            <time datetime="2017-12-01">01 Dec 2017</time> on osx

.mov to gifanim

As simple as that: ffmpeg -i input.mov -pix_fmt rgb24 -r 10 outpout.gif…

            <time datetime="2016-11-24">24 Nov 2016</time> on RemoteWork, nomad, CoWorking, CoLiving

Co-working, co-living, remote, nomad

Remote working is great, doing it since 2005 and love it for many many reasons. I already worked from home, local co-working spaces, coffee shops, car, train, plane. I don’t want to limit myself to home or local co-working spaces, this is why I want to go abroad…

            <time datetime="2015-11-20">20 Nov 2015</time> on meteorjs, talk

MeteorJS introduction at Meetup14 of nantesjs.org

Here are my slides and demo of my talk on MeteorJS given at the NantesJS Meetup14 on 2015.11.19 Slides: http://yanndanthu.github.io/slides/meteorjs-nantesjs2015/ Demo: https://github.com/YannDanthu/chat-app…

            <time datetime="2015-10-02">02 Oct 2015</time> on meteorjs, publish, error

Meteor: data not correctly published after collection updated on server side.

I have experienced a strange behavior with Meteor publish lately. This was due to package vue:vue (https://atmospherejs.com/vue/vue) Problem: why my data disappeared ? Collection on client side was correct, with the expected data, until it was updated on server side. Updating the collection from client side…

            <time datetime="2015-08-25">25 Aug 2015</time> on Angular.js

Some Angular.js resource for best practice

http://trochette.github.io/Angular-Design-Patterns-Best-Practices/#/business_logic…

            <time datetime="2015-05-16">16 May 2015</time>

First post after hubpress.io install

Next step is to move my current wordpress blog to hubpress :) nice.…

    Page 1 of 3
        Older Posts →

All content copyright Yann's blog © 2020 • All rights reserved.

Proudly published with HubPress in The Shell theme.

redpajama_set_name: RedPajamaGithub


text:
require 'spec_helper'
require Rails.root.join('db', 'post_migrate', '20171013104327_migrate_gcp_clusters_to_new_clusters_architectures.rb')

describe MigrateGcpClustersToNewClustersArchitectures, :migration do
  let(:projects) { table(:projects) }
  let(:project) { projects.create }
  let(:users) { table(:users) }
  let(:user) { users.create! }
  let(:service) { GcpMigrationSpec::KubernetesService.create!(project_id: project.id) }

  module GcpMigrationSpec
    class KubernetesService < ActiveRecord::Base
      self.table_name = 'services'

      serialize :properties, JSON

      default_value_for :active, true
      default_value_for :type, 'KubernetesService'
      default_value_for :properties, {
        api_url: 'https://kubernetes.example.com',
        token: 'a' * 40
      }
    end
  end

  context 'when cluster is being created' do
    let(:project_id) { project.id }
    let(:user_id) { user.id }
    let(:service_id) { service.id }
    let(:status) { 2 } # creating
    let(:gcp_cluster_size) { 1 }
    let(:created_at) { "'2017-10-17 20:24:02'" }
    let(:updated_at) { "'2017-10-17 20:28:44'" }
    let(:enabled) { true }
    let(:status_reason) { "''" }
    let(:project_namespace) { "'sample-app'" }
    let(:endpoint) { 'NULL' }
    let(:ca_cert) { 'NULL' }
    let(:encrypted_kubernetes_token) { 'NULL' }
    let(:encrypted_kubernetes_token_iv) { 'NULL' }
    let(:username) { 'NULL' }
    let(:encrypted_password) { 'NULL' }
    let(:encrypted_password_iv) { 'NULL' }
    let(:gcp_project_id) { "'gcp_project_id'" }
    let(:gcp_cluster_zone) { "'gcp_cluster_zone'" }
    let(:gcp_cluster_name) { "'gcp_cluster_name'" }
    let(:gcp_machine_type) { "'gcp_machine_type'" }
    let(:gcp_operation_id) { 'NULL' }
    let(:encrypted_gcp_token) { "'encrypted_gcp_token'" }
    let(:encrypted_gcp_token_iv) { "'encrypted_gcp_token_iv'" }

    let(:cluster) { described_class::Cluster.last }
    let(:cluster_id) { cluster.id }

    before do
      ActiveRecord::Base.connection.execute <<-SQL
        INSERT INTO gcp_clusters (project_id, user_id, service_id, status, gcp_cluster_size, created_at, updated_at, enabled, status_reason, project_namespace, endpoint, ca_cert, encrypted_kubernetes_token, encrypted_kubernetes_token_iv, username, encrypted_password, encrypted_password_iv, gcp_project_id, gcp_cluster_zone, gcp_cluster_name, gcp_machine_type, gcp_operation_id, encrypted_gcp_token, encrypted_gcp_token_iv)
        VALUES (#{project_id}, #{user_id}, #{service_id}, #{status}, #{gcp_cluster_size}, #{created_at}, #{updated_at}, #{enabled}, #{status_reason}, #{project_namespace}, #{endpoint}, #{ca_cert}, #{encrypted_kubernetes_token}, #{encrypted_kubernetes_token_iv}, #{username}, #{encrypted_password}, #{encrypted_password_iv}, #{gcp_project_id}, #{gcp_cluster_zone}, #{gcp_cluster_name}, #{gcp_machine_type}, #{gcp_operation_id}, #{encrypted_gcp_token}, #{encrypted_gcp_token_iv});
      SQL
    end

    it 'correctly migrate to new clusters architectures' do
      migrate!

      expect(described_class::Cluster.count).to eq(1)
      expect(described_class::ClustersProject.count).to eq(1)
      expect(described_class::ProvidersGcp.count).to eq(1)
      expect(described_class::PlatformsKubernetes.count).to eq(1)

      expect(cluster.user_id).to eq(user.id)
      expect(cluster.enabled).to be_truthy
      expect(cluster.name).to eq(gcp_cluster_name.delete!("'"))
      expect(cluster.provider_type).to eq('gcp')
      expect(cluster.platform_type).to eq('kubernetes')

      expect(cluster.project_ids).to include(project.id)

      expect(cluster.provider_gcp.cluster_id).to eq(cluster.id)
      expect(cluster.provider_gcp.status).to eq(status)
      expect(cluster.provider_gcp.status_reason).to eq(tr(status_reason))
      expect(cluster.provider_gcp.gcp_project_id).to eq(tr(gcp_project_id))
      expect(cluster.provider_gcp.zone).to eq(tr(gcp_cluster_zone))
      expect(cluster.provider_gcp.num_nodes).to eq(gcp_cluster_size)
      expect(cluster.provider_gcp.machine_type).to eq(tr(gcp_machine_type))
      expect(cluster.provider_gcp.operation_id).to be_nil
      expect(cluster.provider_gcp.endpoint).to be_nil
      expect(cluster.provider_gcp.encrypted_access_token).to eq(tr(encrypted_gcp_token))
      expect(cluster.provider_gcp.encrypted_access_token_iv).to eq(tr(encrypted_gcp_token_iv))

      expect(cluster.platform_kubernetes.cluster_id).to eq(cluster.id)
      expect(cluster.platform_kubernetes.api_url).to be_nil
      expect(cluster.platform_kubernetes.ca_cert).to be_nil
      expect(cluster.platform_kubernetes.namespace).to eq(tr(project_namespace))
      expect(cluster.platform_kubernetes.username).to be_nil
      expect(cluster.platform_kubernetes.encrypted_password).to be_nil
      expect(cluster.platform_kubernetes.encrypted_password_iv).to be_nil
      expect(cluster.platform_kubernetes.encrypted_token).to be_nil
      expect(cluster.platform_kubernetes.encrypted_token_iv).to be_nil
    end
  end

  context 'when cluster has been created' do
    let(:project_id) { project.id }
    let(:user_id) { user.id }
    let(:service_id) { service.id }
    let(:status) { 3 } # created
    let(:gcp_cluster_size) { 1 }
    let(:created_at) { "'2017-10-17 20:24:02'" }
    let(:updated_at) { "'2017-10-17 20:28:44'" }
    let(:enabled) { true }
    let(:status_reason) { "'general error'" }
    let(:project_namespace) { "'sample-app'" }
    let(:endpoint) { "'111.111.111.111'" }
    let(:ca_cert) { "'ca_cert'" }
    let(:encrypted_kubernetes_token) { "'encrypted_kubernetes_token'" }
    let(:encrypted_kubernetes_token_iv) { "'encrypted_kubernetes_token_iv'" }
    let(:username) { "'username'" }
    let(:encrypted_password) { "'encrypted_password'" }
    let(:encrypted_password_iv) { "'encrypted_password_iv'" }
    let(:gcp_project_id) { "'gcp_project_id'" }
    let(:gcp_cluster_zone) { "'gcp_cluster_zone'" }
    let(:gcp_cluster_name) { "'gcp_cluster_name'" }
    let(:gcp_machine_type) { "'gcp_machine_type'" }
    let(:gcp_operation_id) { "'gcp_operation_id'" }
    let(:encrypted_gcp_token) { "'encrypted_gcp_token'" }
    let(:encrypted_gcp_token_iv) { "'encrypted_gcp_token_iv'" }

    let(:cluster) { described_class::Cluster.last }
    let(:cluster_id) { cluster.id }

    before do
      ActiveRecord::Base.connection.execute <<-SQL
        INSERT INTO gcp_clusters (project_id, user_id, service_id, status, gcp_cluster_size, created_at, updated_at, enabled, status_reason, project_namespace, endpoint, ca_cert, encrypted_kubernetes_token, encrypted_kubernetes_token_iv, username, encrypted_password, encrypted_password_iv, gcp_project_id, gcp_cluster_zone, gcp_cluster_name, gcp_machine_type, gcp_operation_id, encrypted_gcp_token, encrypted_gcp_token_iv)
        VALUES (#{project_id}, #{user_id}, #{service_id}, #{status}, #{gcp_cluster_size}, #{created_at}, #{updated_at}, #{enabled}, #{status_reason}, #{project_namespace}, #{endpoint}, #{ca_cert}, #{encrypted_kubernetes_token}, #{encrypted_kubernetes_token_iv}, #{username}, #{encrypted_password}, #{encrypted_password_iv}, #{gcp_project_id}, #{gcp_cluster_zone}, #{gcp_cluster_name}, #{gcp_machine_type}, #{gcp_operation_id}, #{encrypted_gcp_token}, #{encrypted_gcp_token_iv});
      SQL
    end

    it 'correctly migrate to new clusters architectures' do
      migrate!

      expect(described_class::Cluster.count).to eq(1)
      expect(described_class::ClustersProject.count).to eq(1)
      expect(described_class::ProvidersGcp.count).to eq(1)
      expect(described_class::PlatformsKubernetes.count).to eq(1)

      expect(cluster.user_id).to eq(user.id)
      expect(cluster.enabled).to be_truthy
      expect(cluster.name).to eq(tr(gcp_cluster_name))
      expect(cluster.provider_type).to eq('gcp')
      expect(cluster.platform_type).to eq('kubernetes')

      expect(cluster.project_ids).to include(project.id)

      expect(cluster.provider_gcp.cluster_id).to eq(cluster.id)
      expect(cluster.provider_gcp.status).to eq(status)
      expect(cluster.provider_gcp.status_reason).to eq(tr(status_reason))
      expect(cluster.provider_gcp.gcp_project_id).to eq(tr(gcp_project_id))
      expect(cluster.provider_gcp.zone).to eq(tr(gcp_cluster_zone))
      expect(cluster.provider_gcp.num_nodes).to eq(gcp_cluster_size)
      expect(cluster.provider_gcp.machine_type).to eq(tr(gcp_machine_type))
      expect(cluster.provider_gcp.operation_id).to eq(tr(gcp_operation_id))
      expect(cluster.provider_gcp.endpoint).to eq(tr(endpoint))
      expect(cluster.provider_gcp.encrypted_access_token).to eq(tr(encrypted_gcp_token))
      expect(cluster.provider_gcp.encrypted_access_token_iv).to eq(tr(encrypted_gcp_token_iv))

      expect(cluster.platform_kubernetes.cluster_id).to eq(cluster.id)
      expect(cluster.platform_kubernetes.api_url).to eq('https://' + tr(endpoint))
      expect(cluster.platform_kubernetes.ca_cert).to eq(tr(ca_cert))
      expect(cluster.platform_kubernetes.namespace).to eq(tr(project_namespace))
      expect(cluster.platform_kubernetes.username).to eq(tr(username))
      expect(cluster.platform_kubernetes.encrypted_password).to eq(tr(encrypted_password))
      expect(cluster.platform_kubernetes.encrypted_password_iv).to eq(tr(encrypted_password_iv))
      expect(cluster.platform_kubernetes.encrypted_token).to eq(tr(encrypted_kubernetes_token))
      expect(cluster.platform_kubernetes.encrypted_token_iv).to eq(tr(encrypted_kubernetes_token_iv))
    end
  end

  def tr(str)
    str.delete("'")
  end
end


text:
import React from 'react';
import { Motion, spring } from 'react-motion';
import { Map as makeMap } from 'immutable';
import { line, curveBasis } from 'd3-shape';
import { each, omit, times, constant } from 'lodash';

import { NODES_SPRING_ANIMATION_CONFIG } from '../constants/animation';
import { uniformSelect } from '../utils/array-utils';
import Edge from './edge';

// Tweak this value for the number of control
// points along the edge curve, e.g. values:
//   * 2 -> edges are simply straight lines
//   * 4 -> minimal value for loops to look ok
const WAYPOINTS_COUNT = 8;

const spline = line()
  .curve(curveBasis)
  .x(d => d.x)
  .y(d => d.y);

const transformedEdge = (props, path) => (
  <Edge {...props} path={spline(path)} />
);

// Converts a waypoints map of the format {x0: 11, y0: 22, x1: 33, y1: 44}
// that is used by Motion to an array of waypoints in the format
// [{x: 11, y: 22}, {x: 33, y: 44}] that can be used by D3.
const waypointsMapToArray = (waypointsMap) => {
  const waypointsArray = times(WAYPOINTS_COUNT, () => ({ x: 0, y: 0}));
  each(waypointsMap, (value, key) => {
    const [axis, index] = [key[0], key.slice(1)];
    waypointsArray[index][axis] = value;
  });
  return waypointsArray;
};

export default class EdgeContainer extends React.PureComponent {
  constructor(props, context) {
    super(props, context);
    this.state = { waypointsMap: makeMap() };
  }

  componentWillMount() {
    if (this.props.isAnimated) {
      this.prepareWaypointsForMotion(this.props.waypoints);
    }
  }

  componentWillReceiveProps(nextProps) {
    // immutablejs allows us to `===`! \o/
    if (this.props.isAnimated && nextProps.waypoints !== this.props.waypoints) {
      this.prepareWaypointsForMotion(nextProps.waypoints);
    }
  }

  render() {
    const { isAnimated, waypoints } = this.props;
    const forwardedProps = omit(this.props, 'isAnimated', 'waypoints');

    if (!isAnimated) {
      return transformedEdge(forwardedProps, waypoints.toJS());
    }

    return (
      // For the Motion interpolation to work, the waypoints need to be in a map format like
      // {x0: 11, y0: 22, x1: 33, y1: 44} that we convert to the array format when rendering.
      <Motion style={this.state.waypointsMap.toJS()}>
        {interpolated => transformedEdge(forwardedProps, waypointsMapToArray(interpolated))}
      </Motion>
    );
  }

  prepareWaypointsForMotion(nextWaypoints) {
    nextWaypoints = nextWaypoints.toJS();

    // Motion requires a constant number of waypoints along the path of each edge
    // for the animation to work correctly, but dagre might be changing their number
    // depending on the dynamic topology reconfiguration. Here we are transforming
    // the waypoints array given by dagre to the fixed size of `WAYPOINTS_COUNT` that
    // Motion could take over.
    const waypointsMissing = WAYPOINTS_COUNT - nextWaypoints.length;
    if (waypointsMissing > 0) {
      // Whenever there are some waypoints missing, we simply populate the beginning of the
      // array with the first element, as this leaves the curve interpolation unchanged.
      nextWaypoints = times(waypointsMissing, constant(nextWaypoints[0])).concat(nextWaypoints);
    } else if (waypointsMissing < 0) {
      // If there are 'too many' waypoints given by dagre, we select a sub-array of
      // uniformly distributed indices. Note that it is very important to keep the first
      // and the last endpoints in the array as they are the ones connecting the nodes.
      nextWaypoints = uniformSelect(nextWaypoints, WAYPOINTS_COUNT);
    }

    let { waypointsMap } = this.state;
    nextWaypoints.forEach((point, index) => {
      waypointsMap = waypointsMap.set(`x${index}`, spring(point.x, NODES_SPRING_ANIMATION_CONFIG));
      waypointsMap = waypointsMap.set(`y${index}`, spring(point.y, NODES_SPRING_ANIMATION_CONFIG));
    });

    this.setState({ waypointsMap });
  }
}


text:
package com.thefinestartist.movingbutton.sample;

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.crashlytics.android.Crashlytics;
import com.thefinestartist.movingbutton.MovingButton;
import com.thefinestartist.movingbutton.enums.ButtonPosition;
import com.thefinestartist.movingbutton.enums.MoveDirection;

import butterknife.Bind;
import butterknife.ButterKnife;

public class MainActivity extends ActionBarActivity {

    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.moving_button)
    MovingButton movingButton;
    @Bind(R.id.current_position_info)
    TextView currentPositionInfo;
    @Bind(R.id.move_direction_bt)
    View moveDirectionBt;
    @Bind(R.id.move_direction_tv)
    TextView moveDirectionTv;
    @Bind(R.id.movement_left_bt)
    View movementLeftBt;
    @Bind(R.id.movement_left_tv)
    TextView movementLeftTv;
    @Bind(R.id.movement_right_bt)
    View movementRightBt;
    @Bind(R.id.movement_right_tv)
    TextView movementRightTv;
    @Bind(R.id.movement_top_bt)
    View movementTopBt;
    @Bind(R.id.movement_top_tv)
    TextView movementTopTv;
    @Bind(R.id.movement_bottom_bt)
    View movementBottomBt;
    @Bind(R.id.movement_bottom_tv)
    TextView movementBottomTv;
    @Bind(R.id.movement_inner_offset_bt)
    View innerOffsetBt;
    @Bind(R.id.movement_inner_offset_tv)
    TextView innerOffsetTv;
    @Bind(R.id.movement_outer_offset_bt)
    View outerOffsetBt;
    @Bind(R.id.movement_outer_offset_tv)
    TextView outerOffsetTv;
    @Bind(R.id.volume_bt)
    View volumeBt;
    @Bind(R.id.volume_tv)
    TextView volumeTv;
    @Bind(R.id.vibration_duration_bt)
    View vibrationDurationBt;
    @Bind(R.id.vibration_duration_tv)
    TextView vibrationDurationTv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Crashlytics.start(this);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        setSupportActionBar(toolbar);

        movingButton.setOnPositionChangedListener(new MovingButton.OnPositionChangedListener() {
            @Override
            public void onPositionChanged(int action, ButtonPosition position) {
                currentPositionInfo.setText(position.name());
            }
        });

        moveDirectionBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new MaterialDialog.Builder(MainActivity.this)
                        .title(getString(R.string.move_direction))
                        .items(getMoveDirectionNames())
                        .itemsCallbackSingleChoice(movingButton.getMoveDirection().ordinal(), new MaterialDialog.ListCallbackSingleChoice() {
                            @Override
                            public boolean onSelection(MaterialDialog dialog, View view, int which, CharSequence text) {
                                MoveDirection moveDirection = MoveDirection.values()[which];
                                movingButton.setMoveDirection(moveDirection);
                                moveDirectionTv.setText(moveDirection.name());
                                return true;
                            }
                        })
                        .positiveText(getString(R.string.choose))
                        .show();
            }
        });

        movementLeftBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new MaterialDialog.Builder(MainActivity.this)
                        .title(getString(R.string.movement_left))
                        .items(getDPLists())
                        .itemsCallbackSingleChoice(dpFromPx(movingButton.getMovementLeft()) + 10, new MaterialDialog.ListCallbackSingleChoice() {
                            @Override
                            public boolean onSelection(MaterialDialog materialDialog, View view, int which, CharSequence text) {
                                movingButton.setMovementLeft(pxFromDp(which - 10));
                                movementLeftTv.setText("" + (which - 10) + "dp");
                                return true;
                            }
                        })
                        .positiveText(getString(R.string.choose))
                        .show();
            }
        });

        movementRightBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new MaterialDialog.Builder(MainActivity.this)
                        .title(getString(R.string.movement_right))
                        .items(getDPLists())
                        .itemsCallbackSingleChoice(dpFromPx(movingButton.getMovementRight()) + 10, new MaterialDialog.ListCallbackSingleChoice() {
                            @Override
                            public boolean onSelection(MaterialDialog materialDialog, View view, int which, CharSequence text) {
                                movingButton.setMovementRight(pxFromDp(which - 10));
                                movementRightTv.setText("" + (which - 10) + "dp");
                                return true;
                            }
                        })
                        .positiveText(getString(R.string.choose))
                        .show();
            }
        });

        movementTopBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new MaterialDialog.Builder(MainActivity.this)
                        .title(getString(R.string.movement_top))
                        .items(getDPLists())
                        .itemsCallbackSingleChoice(dpFromPx(movingButton.getMovementTop()) + 10, new MaterialDialog.ListCallbackSingleChoice() {
                            @Override
                            public boolean onSelection(MaterialDialog materialDialog, View view, int which, CharSequence text) {
                                movingButton.setMovementTop(pxFromDp(which - 10));
                                movementTopTv.setText("" + (which - 10) + "dp");
                                return true;
                            }
                        })
                        .positiveText(getString(R.string.choose))
                        .show();
            }
        });

        movementBottomBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new MaterialDialog.Builder(MainActivity.this)
                        .title(getString(R.string.movement_bottom))
                        .items(getDPLists())
                        .itemsCallbackSingleChoice(dpFromPx(movingButton.getMovementBottom()) + 10, new MaterialDialog.ListCallbackSingleChoice() {
                            @Override
                            public boolean onSelection(MaterialDialog materialDialog, View view, int which, CharSequence text) {
                                movingButton.setMovementBottom(pxFromDp(which - 10));
                                movementBottomTv.setText("" + (which - 10) + "dp");
                                return true;
                            }
                        })
                        .positiveText(getString(R.string.choose))
                        .show();
            }
        });

        innerOffsetBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new MaterialDialog.Builder(MainActivity.this)
                        .title(getString(R.string.inner_offset))
                        .items(getDPLists2())
                        .itemsCallbackSingleChoice(dpFromPx(movingButton.getOffSetInner()), new MaterialDialog.ListCallbackSingleChoice() {
                            @Override
                            public boolean onSelection(MaterialDialog materialDialog, View view, int which, CharSequence text) {
                                movingButton.setOffSetInner(pxFromDp(which));
                                innerOffsetTv.setText("" + which + "dp");
                                return true;
                            }
                        })
                        .positiveText(getString(R.string.choose))
                        .show();
            }
        });

        outerOffsetBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new MaterialDialog.Builder(MainActivity.this)
                        .title(getString(R.string.outer_offset))
                        .items(getDPLists2())
                        .itemsCallbackSingleChoice(dpFromPx(movingButton.getOffSetOuter()), new MaterialDialog.ListCallbackSingleChoice() {
                            @Override
                            public boolean onSelection(MaterialDialog materialDialog, View view, int which, CharSequence text) {
                                movingButton.setOffSetOuter(pxFromDp(which));
                                outerOffsetTv.setText("" + which + "dp");
                                return true;
                            }
                        })
                        .positiveText(getString(R.string.choose))
                        .show();
            }
        });

        volumeBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new MaterialDialog.Builder(MainActivity.this)
                        .title(getString(R.string.volume))
                        .items(getVolumeLists())
                        .itemsCallbackSingleChoice(movingButton.getEventVolume(), new MaterialDialog.ListCallbackSingleChoice() {
                            @Override
                            public boolean onSelection(MaterialDialog materialDialog, View view, int which, CharSequence text) {
                                movingButton.setEventVolume(which);
                                volumeTv.setText("" + which);
                                return true;
                            }
                        })
                        .positiveText(getString(R.string.choose))
                        .show();
            }
        });

        vibrationDurationBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new MaterialDialog.Builder(MainActivity.this)
                        .title(getString(R.string.vibration_duration))
                        .items(getVibrationLists())
                        .itemsCallbackSingleChoice(movingButton.getVibrationDuration(), new MaterialDialog.ListCallbackSingleChoice() {
                            @Override
                            public boolean onSelection(MaterialDialog materialDialog, View view, int which, CharSequence text) {
                                movingButton.setVibrationDuration(which);
                                vibrationDurationTv.setText(which + " Milliseconds");
                                return true;
                            }
                        })
                        .positiveText(getString(R.string.choose))
                        .show();
            }
        });
    }

    private String[] getMoveDirectionNames() {
        MoveDirection[] states = MoveDirection.values();
        String[] names = new String[states.length];
        for (int i = 0; i < states.length; i++)
            names[i] = states[i].name();
        return names;
    }

    private String[] getVibrationLists() {
        String[] names = new String[101];
        for (int i = 0; i < names.length; i++)
            names[i] = "" + i + " Milliseconds";
        return names;
    }

    private String[] getDPLists() {
        String[] names = new String[41];
        for (int i = 0; i < names.length; i++)
            names[i] = "" + (i - 10) + "dp";
        return names;
    }

    private String[] getDPLists2() {
        String[] names = new String[51];
        for (int i = 0; i < names.length; i++)
            names[i] = "" + i + "dp";
        return names;
    }

    private String[] getVolumeLists() {
        String[] names = new String[101];
        for (int i = 0; i < names.length; i++)
            names[i] = "" + i;
        return names;
    }

    private int dpFromPx(int px) {
        return (int) (px / getResources().getDisplayMetrics().density);
    }

    private int pxFromDp(int dp) {
        return (int) (dp * getResources().getDisplayMetrics().density);
    }
}


text:
// MIT License
// Copyright (c) 2011-2016 Elisée Maurer, Sparklin Labs, Creative Patterns
// Copyright (c) 2016 Thomas Morgner, Rabbit-StewDio Ltd.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
using System;
using System.Collections.Generic;
using System.Linq;

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;

namespace Steropes.UI.Input.GamePadInput
{
  public class GamePadComponent : BasicGameComponent
  {
    static readonly List<Buttons> AllGamePadButtons = Enum.GetValues(typeof(Buttons)).Cast<Buttons>().ToList();

    static readonly List<Buttons> ExcludedButtons = new List<Buttons>
                                                      {
                                                        Buttons.LeftTrigger,
                                                        Buttons.RightTrigger,
                                                        Buttons.LeftThumbstickDown,
                                                        Buttons.LeftThumbstickUp,
                                                        Buttons.LeftThumbstickRight,
                                                        Buttons.LeftThumbstickLeft,
                                                        Buttons.RightThumbstickLeft,
                                                        Buttons.RightThumbstickRight,
                                                        Buttons.RightThumbstickUp,
                                                        Buttons.RightThumbstickDown
                                                      };

    static readonly List<Buttons> NonTriggerButtons = AllGamePadButtons.Where(b => !ExcludedButtons.Contains(b)).ToList();

    readonly GamePadState[] currentStates;

    readonly IEventSink<GamePadEventData> eventSink;

    readonly GamePadState[] previousStates;

    TimeSpan currentTime;

    int frame;

    bool initialized;

    InputFlags inputFlags;

    public GamePadComponent(IEventSink<GamePadEventData> eventSink)
    {
      this.eventSink = eventSink;
      TriggerDownTreshold = 0.15f;
      ThumbstickDownTreshold = 0.5f;
      TriggerDeltaTreshold = 0.1f;
      ThumbStickDeltaTreshold = 0.1f;

      currentStates = new GamePadState[GamePad.MaximumGamePadCount];
      previousStates = new GamePadState[GamePad.MaximumGamePadCount];
    }

    /// <summary>
    ///   The treshold of movement that has to be met in order
    ///   for the listener to fire an event with the thumbstick's
    ///   updated position.
    ///   <para>
    ///     In essence this defines the event's
    ///     resolution.
    ///   </para>
    ///   At a value of 0 this will fire every time
    ///   the thumbstick's position is not {x:0, y:0}.
    /// </summary>
    public float ThumbStickDeltaTreshold { get; }

    /// <summary>
    ///   How deep the triggers have to be depressed in order to
    ///   register as a ButtonDown event.
    /// </summary>
    public float ThumbstickDownTreshold { get; }

    /// <summary>
    ///   The treshold of movement that has to be met in order
    ///   for the listener to fire an event with the trigger's
    ///   updated position.
    ///   <para>
    ///     In essence this defines the event's
    ///     resolution.
    ///   </para>
    ///   At a value of 0 this will fire every time
    ///   the trigger's position is not 0f.
    /// </summary>
    public float TriggerDeltaTreshold { get; }

    /// <summary>
    ///   How deep the triggers have to be depressed in order to
    ///   register as a ButtonDown event.
    /// </summary>
    public float TriggerDownTreshold { get; }

    public override void Update(GameTime gameTime)
    {
      frame += 1;
      currentTime = gameTime.TotalGameTime;
      inputFlags = InputFlagsHelper.Create();

      for (var p = 0; p < currentStates.Length; p += 1)
      {
        previousStates[p] = currentStates[p];
        currentStates[p] = GamePad.GetState(p);

        // collect some valid state, so on the _next_ update call we can detect changes and process events.
        if (!initialized)
        {
          initialized = true;
          return;
        }

        CheckAllButtons(p);
      }
    }

    void CheckAllButtons(int player)
    {
      var currentState = currentStates[player];
      var previousState = previousStates[player];

      for (var i = 0; i < NonTriggerButtons.Count; i++)
      {
        var button = NonTriggerButtons[i];
        if (currentState.IsButtonDown(button) && previousState.IsButtonUp(button))
        {
          eventSink.PushEvent(new GamePadEventData(GamePadEventType.ButtonDown, currentTime, frame, inputFlags, button));
        }

        if (currentState.IsButtonUp(button) && previousState.IsButtonDown(button))
        {
          eventSink.PushEvent(new GamePadEventData(GamePadEventType.ButtonUp, currentTime, frame, inputFlags, button));
        }
      }

      // Checks triggers as buttons and floats
      CheckTriggers(currentState.Triggers.Left, previousState.Triggers.Left, Buttons.LeftTrigger);
      CheckTriggers(currentState.Triggers.Right, previousState.Triggers.Right, Buttons.RightTrigger);

      // Checks thumbsticks as vector2s
      CheckThumbSticks(currentState.ThumbSticks.Right, previousState.ThumbSticks.Right, Buttons.RightStick);
      CheckThumbSticks(currentState.ThumbSticks.Left, previousState.ThumbSticks.Left, Buttons.LeftStick);
    }

    void CheckThumbSticks(Vector2 curVector, Vector2 prevVector, Buttons button)
    {
      const float Debounce = 0.15f;
      var curdown = curVector.Length() > ThumbstickDownTreshold;
      var prevdown = prevVector.Length() > ThumbstickDownTreshold;

      var curdir = ComputeThumbStickDirection(curVector, button);
      var prevdir = ComputeThumbStickDirection(prevVector, button);

      if (!prevdown && curdown)
      {
        eventSink.PushEvent(new GamePadEventData(GamePadEventType.ButtonDown, currentTime, frame, inputFlags, curdir));
      }
      else if (prevdown && curVector.Length() < Debounce)
      {
        eventSink.PushEvent(new GamePadEventData(GamePadEventType.ButtonUp, currentTime, frame, inputFlags, prevdir));
      }
      else if (prevdown && curdown && curdir != prevdir)
      {
        eventSink.PushEvent(new GamePadEventData(GamePadEventType.ButtonUp, currentTime, frame, inputFlags, prevdir));
        eventSink.PushEvent(new GamePadEventData(GamePadEventType.ButtonDown, currentTime, frame, inputFlags, curdir));
      }

      if (curVector.Length() > ThumbStickDeltaTreshold)
      {
        if (Vector2.Distance(curVector, prevVector) >= ThumbStickDeltaTreshold)
        {
          eventSink.PushEvent(new GamePadEventData(GamePadEventType.ThumbStickMoved, currentTime, frame, inputFlags, button, curVector));
        }
      }
      else if (prevVector.Length() > ThumbStickDeltaTreshold)
      {
        eventSink.PushEvent(new GamePadEventData(GamePadEventType.ThumbStickMoved, currentTime, frame, inputFlags, button, curVector));
      }
    }

    void CheckTriggers(float curstate, float prevstate, Buttons button)
    {
      var debounce = 0.05f; // Value used to qualify a trigger as coming Up from a Down state
      var curdown = curstate > TriggerDownTreshold;
      var prevdown = prevstate > TriggerDownTreshold;

      if (!prevdown && curdown)
      {
        eventSink.PushEvent(new GamePadEventData(GamePadEventType.ButtonDown, currentTime, frame, inputFlags, button));
      }
      else if (prevdown && curstate < debounce)
      {
        eventSink.PushEvent(new GamePadEventData(GamePadEventType.ButtonUp, currentTime, frame, inputFlags, button));
      }

      if (curstate > TriggerDeltaTreshold)
      {
        if (Math.Abs(prevstate - curstate) >= TriggerDeltaTreshold)
        {
          eventSink.PushEvent(new GamePadEventData(GamePadEventType.TriggerMoved, currentTime, frame, inputFlags, button, curstate));
        }
      }
      else if (prevstate > TriggerDeltaTreshold)
      {
        eventSink.PushEvent(new GamePadEventData(GamePadEventType.TriggerMoved, currentTime, frame, inputFlags, button, curstate));
      }
    }

    Buttons ComputeThumbStickDirection(Vector2 curVector, Buttons baseButton)
    {
      var right = baseButton == Buttons.RightStick;

      if (curVector.Y > curVector.X)
      {
        if (curVector.Y > -curVector.X)
        {
          return right ? Buttons.RightThumbstickUp : Buttons.LeftThumbstickUp;
        }
        return right ? Buttons.RightThumbstickLeft : Buttons.LeftThumbstickLeft;
      }

      if (curVector.Y < -curVector.X)
      {
        return right ? Buttons.RightThumbstickDown : Buttons.LeftThumbstickDown;
      }
      return right ? Buttons.RightThumbstickRight : Buttons.LeftThumbstickRight;
    }
  }
}


text:
      NOW

      BROWSE
      MY HOPS
      CREATE HOP
      RECORD HOP
      MY PLACE
      ACCOUNT
      TRAVEL BUDDIES
      LOGOUT


text:
from .async_handler import AsyncHandler
from .sync_handler import SyncHandler


text:
(function() {
  define(function(require, exports, module) {
    var AppInit, ExtensionUtils;
    ExtensionUtils = brackets.getModule('utils/ExtensionUtils');
    AppInit = brackets.getModule('utils/AppInit');
    return AppInit.appReady(function() {
      return ExtensionUtils.loadStyleSheet(module, 'main.less');
    });
  });

}).call(this);


text:
import re

class ReadSAM:
    '''
        Support queries for SAM file
    '''

    filename = None
    chromosomes = None

    def __init__(self, filename, chromosomes):
        '''
            Assumes SAM file is sorted
        '''
        self.filename = filename
        self.chromosomes = chromosomes

    def getCoverage(self, chrom, start=None, end=None):
        if start == None:
            start = 0
        else:
            start = max(start, 0)
        if end == None:
            end = self.chromosomes[chrom]
        else:
            end = min(end, self.chromosomes[chrom])

        with open(self.filename, 'r') as f:
            coverage = [0.0] * (end-start)

            for line in f:
                row = line.rstrip().split('\t')

                if len(row) < 10:
                    continue

                if row[2] == chrom:
                    readStart = int(row[3])
                    cigar = row[5]

                    if readStart < end:
                        exons = self.parseCigar(cigar, readStart)

                        if exons[-1][1] > start:
                            NH = 1.0
                            for s in row:
                                if s[:5] == 'NH:i:':
                                    NH = 1.0 / float(s[5:])

                            for e in exons:
                                if e[0] < end and e[1] >= start:
                                    for i in range(max(start,e[0]), min(end,e[1])):
                                        coverage[i-start] += NH
                    else:
                        return coverage

            return coverage

    def getReads(self, chrom, start=None, end=None):
        '''
        Assumes the SAM file is sorted
        :param chrom:
        :param start:
        :param end:
        :return:
        '''
        if start == None or end == None:
            start = 0
            end = self.chromosomes[chrom]

        offset = 0
        for k in sorted(self.chromosomes.keys()):
                if not k == chrom:
                    offset += self.chromosomes[k]
                    start += self.chromosomes[k]
                    end += self.chromosomes[k]
                else:
                    break

        unmatched = dict()

        unpaired = []
        paired = []
        sawChrom = False # Set this flag to true after we've seen the first read from chrom
        with open(self.filename, 'r') as f:
            for line in f:
                row = line.rstrip().split('\t')

                if len(row) < 10:
                    continue

                if row[2] == chrom:
                    sawChrom = True
                    readStart = int(row[3])
                    cigar = row[5]

                    if row[6] == '=':
                        pairStart = int(row[7])

                        fragmentStart = min(readStart, pairStart) + offset
                        fragmentEnd = fragmentStart + abs(int(row[8])) + offset
                        if fragmentStart >= end or fragmentEnd <= start:
                            continue

                        #if readStart >= end and pairStart >= end:
                        #    continue

                        NH = 1
                        for r in row[11 : len(row)]:
                            if r[0:5] == 'XS:A:' or r[0:5] == 'XS:a:':
                                xs = r[5]
                            elif r[0:3] == 'NH:':
                                NH = int(r[5:])

                        if row[0] in unmatched:
                            found = False
                            m = unmatched[row[0]]
                            for i in range(len(m)):
                                if m[i][0] == pairStart and m[i][2] == readStart and m[i][3] == NH:
                                    r1 = self.parseCigar(m[i][1], m[i][0]+offset)
                                    r2 = self.parseCigar(cigar, readStart+offset)

                                    if self.readOverlapsRegion(r1, start, end) or self.readOverlapsRegion(r2, start, end):
                                        paired.append([r1, r2])

                                    del unmatched[row[0]][i]
                                    break

                            if not found:
                                unmatched[row[0]].append((readStart, cigar, pairStart, NH))
                        else:
                            unmatched[row[0]] = [(readStart, cigar, pairStart, NH)]
                    else:
                        exons = self.parseCigar(cigar, readStart+offset)

                        if readStart < end and exons[-1][1] > start:
                            if self.readOverlapsRegion(exons, start, end):
                                NH = 1
                                for r in row[11 : len(row)]:
                                    if r[0:5] == 'XS:A:' or r[0:5] == 'XS:a:':
                                        xs = r[5]
                                    elif r[0:3] == 'NH:':
                                        NH = int(r[5:])
                                unpaired.append(exons)
                else:
                    if sawChrom:
                        return unpaired, paired

        return unpaired, paired

    def readOverlapsRegion(self, exons, start, end):
        '''

        :param exons: List of exon bounds
        :param start: Start of region of interest
        :param end: End of region of interest
        :return: True if any of the exons overlap the region of interest
        '''

        for e in exons:
            if e[0] >= end:
                # Passed region
                return False
            elif e[1] > start:
                return True
        return False

    def getGenes(self, chrom, start=None, end=None, overlapRadius=50):
        if start == None or end == None:
            start = 0
            end = self.chromosomes[chrom]

        genes = []
        with open(self.filename, 'r') as f:
            for line in f:
                row = line.rstrip().split('\t')

                if len(row) < 10:
                    continue

                if row[2] == chrom:
                    readStart = int(row[3])

                    if readStart >= end:
                        break

                    if row[6] == '=' and int(row[7]) > readStart:
                        genes.append((readStart, int(row[7])))
                    else:
                        cigar = row[5]
                        if readStart >= start and readStart < end:
                            exons = self.parseCigar(cigar, readStart)

                            if exons[-1][1] <= end:
                                genes.append((exons[0][0], exons[-1][1]))

            genes.sort()

            i = 0
            while i < (len(genes)-1):
                while i < (len(genes)-1) and genes[i+1][0] - genes[i][1] <= overlapRadius:
                    genes[i] = (genes[i][0], max(genes[i][1], genes[i+1][1]))
                    del genes[i+1]
                i += 1

        return genes

    def parseCigar(self, cigar, offset):
        ''' Parse the cigar string starting at the given index of the genome
            Returns a list of offsets for each exonic region of the read [(start1, end1), (start2, end2), ...]
        '''
        exons = []
        newExon = True

        # Parse cigar string
        match = re.search("\D", cigar)
        while match:
            index = match.start()
            length = int(''.join(cigar[:index]))

            if cigar[index] == 'N':
                # Separates contiguous exons, so set boolean to start a new one
                newExon = True
            elif cigar[index] == 'M':
                # If in the middle of a contiguous exon, append the length to it, otherwise start a new exon
                if newExon:
                    exons.append([offset, offset+length])
                    newExon = False
                else:
                    exons[-1][1] += length
            elif cigar[index] == 'D':
                # If in the middle of a contiguous exon, append the deleted length to it
                if not newExon:
                    exons[-1][1] += length

            if not cigar[index] == 'S':
                offset += length
            cigar = cigar[index+1:]
            match = re.search("\D", cigar)

        return exons


text:
package flags

import (
	"flag"
	"fmt"
	"os"

	"golang.org/x/net/context"

	"github.com/vmware/govmomi/object"
)

type StoragePodFlag struct {
	common

	*DatacenterFlag

	Name string

	sp *object.StoragePod
}

var storagePodFlagKey = flagKey("storagePod")

func NewStoragePodFlag(ctx context.Context) (*StoragePodFlag, context.Context) {
	if v := ctx.Value(storagePodFlagKey); v != nil {
		return v.(*StoragePodFlag), ctx
	}

	v := &StoragePodFlag{}
	v.DatacenterFlag, ctx = NewDatacenterFlag(ctx)
	ctx = context.WithValue(ctx, storagePodFlagKey, v)
	return v, ctx
}

func (f *StoragePodFlag) Register(ctx context.Context, fs *flag.FlagSet) {
	f.RegisterOnce(func() {
		f.DatacenterFlag.Register(ctx, fs)

		env := "GOVC_DATASTORE_CLUSTER"
		value := os.Getenv(env)
		usage := fmt.Sprintf("Datastore cluster [%s]", env)
		fs.StringVar(&f.Name, "datastore-cluster", value, usage)
	})
}

func (f *StoragePodFlag) Process(ctx context.Context) error {
	return f.DatacenterFlag.Process(ctx)
}

func (f *StoragePodFlag) Isset() bool {
	return f.Name != ""
}

func (f *StoragePodFlag) StoragePod() (*object.StoragePod, error) {
	if f.sp != nil {
		return f.sp, nil
	}

	finder, err := f.Finder()
	if err != nil {
		return nil, err
	}

	if f.Isset() {
		f.sp, err = finder.DatastoreCluster(context.TODO(), f.Name)
		if err != nil {
			return nil, err
		}
	} else {
		f.sp, err = finder.DefaultDatastoreCluster(context.TODO())
		if err != nil {
			return nil, err
		}
	}

	return f.sp, nil
}


text:
// ==========================================================================
//                 SeqAn - The Library for Sequence Analysis
// ==========================================================================
// Copyright (c) 2006-2015, Knut Reinert, FU Berlin
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * 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.
//     * Neither the name of Knut Reinert or the FU Berlin 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 KNUT REINERT OR THE FU BERLIN 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.
//
// ==========================================================================
// Author: Manuel Holtgrewe <manuel.holtgrewe@fu-berlin.de>
// Author: David Weese <david.weese@fu-berlin.de>
// ==========================================================================
// Code for loading and writing FAI FASTA index files.
// ==========================================================================

#include <iostream>

#include <seqan/sequence.h>
#include <seqan/store.h>
#include <seqan/file.h>
#include <seqan/stream.h>

#ifndef SEQAN_APPS_RABEMA_FAI_INDEX_H_
#define SEQAN_APPS_RABEMA_FAI_INDEX_H_

namespace seqan {

// ============================================================================
// Forwards
// ============================================================================

// ============================================================================
// Tags, Classes, Enums
// ============================================================================

// ----------------------------------------------------------------------------
// Class FaiIndexEntry_
// ----------------------------------------------------------------------------

// Stores one entry in the FAI file.

class FaiIndexEntry_
{
public:
    // Name of the sequences.
    CharString name;
    // Length of the sequence.
    __uint64 sequenceLength;
    // Offset in the file.
    __uint64 offset;
    // Number of sequence characters per line.
    unsigned lineLength;
    // Number of bytes per line, including newline character(s).
    unsigned overallLineLength;

    FaiIndexEntry_() :
        sequenceLength(0), offset(0), lineLength(0), overallLineLength(0)
    {}
};

inline void
clear(FaiIndexEntry_ &entry)
{
    clear(entry.name);
    entry.sequenceLength = 0;
    entry.offset = 0;
    entry.lineLength = 0;
    entry.overallLineLength = 0;
}

// ----------------------------------------------------------------------------
// Class FaiIndex
// ----------------------------------------------------------------------------

/*!
 * @class FaiIndex
 * @headerfile <seqan/seq_io.h>
 * @brief Data structure for access to FAI indices.
 *
 * @signature class FaiIndex;
 *
 * FAI indices allow the rast random access to sequences or parts of sequences in a FASTA file.  Originally, they were
 * introduced in the samtools program.
 *
 * Also see the Indexed FASTA I/O
 * Tutorial.
 *
 * @section Example
 *
 * The following example demonstrates the usage of the FaiIndex class.
 *
 * @include demos/seq_io/fai_index_example.cpp
 *
 * The output is as follows:
 *
 * @include demos/seq_io/fai_index_example.cpp.stdout
 *
 * @fn FaiIndex::FaiIndex
 * @brief Constructor.
 *
 * @signature FaiIndex::FaiIndex();
 */

class FaiIndex
{
public:
    // The name of the FASTA file.
    CharString fastaFilename;
    // The name of the FAI file.
    CharString faiFilename;

    // The index entries.
    String<FaiIndexEntry_> indexEntryStore;
    // A store for the sequence names.
    StringSet<CharString> seqNameStore;
    // A cache for fast access to the sequence name store.
    NameStoreCache<StringSet<CharString> > seqNameStoreCache;

    // We use this memory mapped string (opened read-only) to read from the file.
    String<char, MMap<> > mmapString;

    FaiIndex() :
        seqNameStoreCache(seqNameStore)
    {}
};

// ============================================================================
// Metafunctions
// ============================================================================

// ============================================================================
// Functions
// ============================================================================

// ----------------------------------------------------------------------------
// Function clear()
// ----------------------------------------------------------------------------

/*!
 * @fn FaiIndex#clear
 * @brief Reset a FaiIndex object to the state after default construction.
 *
 * @signature void clear(faiIndex);
 *
 * @param[in,out] faiIndex The FaiIndex to clear.
 */

inline void clear(FaiIndex & index)
{
    clear(index.fastaFilename);
    clear(index.faiFilename);
    clear(index.indexEntryStore);
    clear(index.seqNameStore);
    clear(index.seqNameStoreCache);
}

// ----------------------------------------------------------------------------
// Function getIdByName()
// ----------------------------------------------------------------------------

/*!
 * @fn FaiIndex#getIdByName
 * @brief Return reference ID (numeric index in the file) of a sequence in a FAI file.
 *
 * @signature bool getIdByName(rID, faiIndex, name);
 *
 * @param[in]  faiIndex The FaiIndex to query.
 * @param[in]  name     The name of the sequence to look the id up for.  Type: @link ContainerConcept @endlink.
 * @param[out] rID      The id of the sequence is written here.
 *
 * @return bool <tt>true</tt> if a sequence with the given name is known in the index, <tt>false</tt> otherwise.
 */

template <typename TName, typename TId>
inline bool getIdByName(TId & rID, FaiIndex const & index, TName const & name)
{
    return getIdByName(rID, index.seqNameStoreCache, name);
}

// ----------------------------------------------------------------------------
// Function sequenceLength()
// ----------------------------------------------------------------------------

/*!
 * @fn FaiIndex#sequenceLength
 * @brief Return length of the sequence with the given id in the FaiIndex.
 *
 * @signature __uint64 sequenceLength(faiIndex, rID);
 *
 * @param[in] faiIndex The FaiIndex to query.
 * @param[in] rID    The id of the sequence to get the length of.
 *
 * @return __uint64 The length of the sequence with index rID in faiIndex.
 */

template <typename TSeqId>
inline __uint64 sequenceLength(FaiIndex const & index, TSeqId rID)
{
    return index.indexEntryStore[rID].sequenceLength;
}

// TODO(holtgrew): Wrapper and template only here because sequenceLength in string_set_base.h is weird.

template <typename TSeqId>
inline __uint64 sequenceLength(FaiIndex & index, TSeqId rID)
{
    return index.indexEntryStore[rID].sequenceLength;
}

// ----------------------------------------------------------------------------
// Function sequenceName()
// ----------------------------------------------------------------------------

/*!
 * @fn FaiIndex#sequenceName
 * @brief Return the name of the sequence with the given id in the FaiIndex.
 *
 * @signature CharString sequenceName(faiIndex, rID);
 *
 * @param[in] faiIndex The FaiIndex to query.
 * @param[in] rID    The index of the sequence.
 *
 * @return CharString The name of the sequence with the given id.
 */

inline CharString const & sequenceName(FaiIndex const & index, unsigned rID)
{
    return index.indexEntryStore[rID].name;
}

// ----------------------------------------------------------------------------
// Function numSeqs()
// ----------------------------------------------------------------------------

/*!
 * @fn FaiIndex#numSeqs
 * @brief Return the number of sequences known to a FaiIndex.
 *
 * @signature __uint64 numSeqs(faiIndex);
 *
 * @param[in] faiIndex The FaiIndex to query.
 *
 * @return __uint64 The number of sequences in the index.
 */

inline __uint64 numSeqs(FaiIndex const & index)
{
    return length(index.indexEntryStore);
}

// ----------------------------------------------------------------------------
// Function readRegion()
// ----------------------------------------------------------------------------

/*!
 * @fn FaiIndex#readRegion
 * @brief Read a region through an FaiIndex.
 *
 * @signature void readRegion(str, faiIndex, rID, beginPos, endPos);
 * @signature void readRegion(str, faiIndex, region);
 *
 * @param[out] str      The @link String @endlink to read the sequence into.
 * @param[in]  faiIndex The FaiIndex to read from.
 * @param[in]  rID    The id of the sequence to read (Type: <tt>unsigned).
 * @param[in]  beginPos The begin position of the region to read (Type: <tt>unsigned).
 * @param[in]  endPos   The end position of the region to read  (Type: <tt>unsigned).
 * @param[in]  region   The @link GenomicRegion @endlink to read.
 */

template <typename TValue, typename TSpec, typename TSeqId, typename TBeginPos, typename TEndPos>
inline void readRegion(String<TValue, TSpec> & str,
                       FaiIndex const & index,
                       TSeqId rID,
                       TBeginPos beginPos,
                       TEndPos endPos)
{
    typedef String<char, MMap<> > const TFastaFile;

    FaiIndexEntry_ const & entry = index.indexEntryStore[rID];

    // Limit region to the infix, make sure that beginPos < endPos, compute character to read.
    TEndPos seqLen = entry.sequenceLength;;
    beginPos = std::min((TEndPos)beginPos, seqLen);
    endPos = std::min(std::max((TEndPos)beginPos, endPos), seqLen);
    TEndPos toRead = endPos - beginPos;

    // seek to start position
    DirectionIterator<TFastaFile, Input>::Type reader = directionIterator(index.mmapString, Input());
    setPosition(
        reader,
        index.indexEntryStore[rID].offset +
        (beginPos / entry.lineLength) * entry.overallLineLength);

    // set up countdowns
    CountDownFunctor<NotFunctor<IsWhitespace> > countDownIgnore(beginPos % entry.lineLength);
    CountDownFunctor<NotFunctor<IsWhitespace> > countDownData(toRead);
    IsWhitespace ignWhiteSpace;

    // read characters
    clear(str);
    skipUntil(reader, countDownIgnore);
    readUntil(str, reader, countDownData, ignWhiteSpace);
    if (!countDownData)
        SEQAN_THROW(UnexpectedEnd());
//
//
//    typedef typename Iterator<String<char, MMap<> > const, Standard>::Type TSourceIter;
//    typedef typename Iterator<String<TValue, TSpec>, Standard>::Type TTargetIter;
//    TSourceIter itSource = begin(index.mmapString, Standard());
//    __uint64 offset = index.indexEntryStore[rID].offset;
//    // First, compute offset of the completely filled lines.
//    unsigned numLines = beginPos / index.indexEntryStore[rID].lineLength;
//    unsigned numBytes = numLines * index.indexEntryStore[rID].overallLineLength;
//    // Then, compute overall offset by adding remaining bytes, too.
//    numBytes += beginPos % index.indexEntryStore[rID].lineLength;
//    offset += numBytes;
//    // Advance iterator in MMap file.
//    itSource += offset;
//
//    // Copy out the characters from FASTA file and convert via iterator assignment to target string's type.
//    resize(str, toRead, TValue());
//    TTargetIter itTarget = begin(str, Standard());
//    for (TEndPos i = 0; i < toRead; )
//    {
//        if (isspace(*itSource))
//        {
//            ++itSource;
//            continue;  // Skip spaces.
//        }
//        *itTarget = *itSource;
//        ++itTarget;
//        ++itSource;
//        ++i;
//    }
//
//    return true;
}

template <typename TValue, typename TSpec>
inline bool readRegion(String<TValue, TSpec> & str,
                       FaiIndex const & index,
                       GenomicRegion const & region)
{
    int rID = region.rID;
    if (rID == GenomicRegion::INVALID_ID)
        if (!getIdByName(rID, index, region.seqName))
            return false;  // Sequence with this name could not be found.

    int beginPos = (region.beginPos != GenomicRegion::INVALID_POS)? region.beginPos : 0;
    int endPos = (region.endPos != GenomicRegion::INVALID_POS)? region.endPos : sequenceLength(index, rID);
    readRegion(str, index, rID, beginPos, endPos);
    return true;
}

// ----------------------------------------------------------------------------
// Function readSequence()
// ----------------------------------------------------------------------------

/*!
 * @fn FaiIndex#readSequence
 * @brief Load a whole sequence from a FaiIndex.
 *
 * @signature void readSequence(str, faiIndex, rID);
 *
 * @param[out] str      The @link String @endlink to read into.
 * @param[in]  faiIndex The FaiIndex to read from.
 * @param[in]  seqID    The index of the sequence in the file.
 */

template <typename TValue, typename TSpec>
inline void readSequence(String<TValue, TSpec> & str, FaiIndex const & index, unsigned rID)
{
    readRegion(str, index, rID, 0u, sequenceLength(index, rID));
}

// ----------------------------------------------------------------------------
// Function readRecord()
// ----------------------------------------------------------------------------

/*!
 * @fn FaiIndex#readRecord
 * @brief Read a FAI index from file.
 *
 * @signature void readRecord(faiIndex, fastaFileName[, faiFileName]);
 *
 * @param[out] faiIndex      The FaiIndex to read into.
 * @param[in]  fastaFileName Path to the FASTA file to read.  Type: <tt>char const *</tt>.
 * @param[in]  faiFileName   Path to the FAI file to read.  Type: <tt>char const *</tt>.  Defaults to
 *                           <tt>"${fastaFileName}.fai"</tt>.
 */

template <typename TFwdIterator>
inline void
readRecord(FaiIndexEntry_ & entry, TFwdIterator & reader, CharString & buffer)
{
    clear(entry);

    // Read REF_NAME.
    readUntil(entry.name, reader, IsTab());

    skipOne(reader, IsTab());   // Must have been on tab

    // Read SEQ_LENGTH.
    clear(buffer);
    readUntil(buffer, reader, IsTab());
    lexicalCast(entry.sequenceLength, buffer);

    skipOne(reader, IsTab());   // Must have been on tab

    // Read OFFSET.
    clear(buffer);
    readUntil(buffer, reader, IsTab());
    lexicalCast(entry.offset, buffer);

    skipOne(reader, IsTab());   // Must have been on tab

    // Read LINE_LENGTH.
    clear(buffer);
    readUntil(buffer, reader, IsTab());
    lexicalCast(entry.lineLength, buffer);

    skipOne(reader, IsTab());   // Must have been on tab

    // Read OVERALL_LINE_LENGTH.
    clear(buffer);
    readUntil(buffer, reader, OrFunctor<IsTab, IsNewline>());
    lexicalCast(entry.overallLineLength, buffer);

    skipLine(reader);           // Skip over line ending.
}

// ---------------------------------------------------------------------------
// Function open()
// ---------------------------------------------------------------------------

/*!
 * @fn FaiIndex#open
 * @brief Open a FaiIndex object.
 *
 * @signature bool open(faiIndex, fastaFilename [, faiFileName]);
 *
 * @param[in] faiIndex      The FaiIndex to write out.
 * @param[in] fastaFilename Path to the FASTA file to build an index for.  Type: <tt>char const *</tt>.
 * @param[in] faiFileName The name of the FAI file to open.  This parameter is optional.  By default, the FAI
 *                        file name is derived from the FASTA file name.  Type: <tt>char
 *                        const *</tt>.
 *
 * @return bool <tt>true</tt> on success, <tt>false</tt> otherwise.
 */

inline bool open(FaiIndex & index, char const * fastaFilename, char const * faiFilename)
{
    clear(index);  // Also clears filename, thus backup above and restore below.
    index.fastaFilename = fastaFilename;
    index.faiFilename = faiFilename;

    if (!open(index.mmapString, toCString(fastaFilename), OPEN_RDONLY))
        return false;  // Could not open file.

    // Open file.
    std::ifstream faiStream(toCString(index.faiFilename));
    if (!faiStream.good())
        return false;  // problem opening
    DirectionIterator<std::ifstream, Input>::Type reader = directionIterator(faiStream, Input());

    // Read FAI file.
    CharString buffer;
    FaiIndexEntry_ entry;
    while (!atEnd(reader))
    {
        readRecord(entry, reader, buffer);
        appendValue(index.seqNameStore, entry.name);
        appendValue(index.indexEntryStore, entry);
    }

    // Recreate name store cache.
    refresh(index.seqNameStoreCache);
    return true;
}

inline bool open(FaiIndex & index, char const * fastaFilename)
{
    std::string faiFilename = fastaFilename;
    faiFilename += ".fai";
    return open(index, fastaFilename, toCString(faiFilename));
}

// ---------------------------------------------------------------------------
// Function save()
// ---------------------------------------------------------------------------

/*!
 * @fn FaiIndex#save
 * @brief Save a FaiIndex object.
 *
 * @signature bool save(faiIndex[, faiFileName]);
 *
 * @param[in] faiIndex    The FaiIndex to write out.
 * @param[in] faiFileName The name of the FAI file to write to.  This parameter is optional only if the FAI index knows
 *                        the FAI file name from a previous @link FaiIndex#build @endlink call.  By default, the FAI
 *                        file name from the previous call to @link FaiIndex#build @endlink is used.  Type: <tt>char
 *                        const *</tt>.
 *
 * @return bool <tt>true</tt> on success, <tt>false</tt> otherwise.
 */

inline bool save(FaiIndex const & index, char const * faiFilename)
{
    // Open index files.
    std::ofstream file(faiFilename);
    if (!file.good())
        return false;

    file.exceptions(std::ios_base::badbit);
    for (unsigned i = 0; i < length(index.indexEntryStore); ++i)
    {
        FaiIndexEntry_ const & entry = index.indexEntryStore[i];
        file << entry.name << '\t' << entry.sequenceLength << '\t' << entry.offset << '\t'
             << entry.lineLength << '\t' << entry.overallLineLength << '\n';
    }
    return true;
}

inline bool save(FaiIndex const & index)
{
    if (empty(index.faiFilename))
        return false;  // Cannot write out if faiFilename member is empty.
    return save(index, toCString(index.faiFilename));
}

// ----------------------------------------------------------------------------
// Function getRecordInfo(Fastq);
// ----------------------------------------------------------------------------

template <typename TFwdIterator>
inline void getRecordInfo(FaiIndexEntry_ & entry, TFwdIterator & iter, Fasta)
{
    typedef EqualsChar<'>'> TFastaBegin;

    clear(entry);

    skipUntil(iter, TFastaBegin());     // forward to the next '>'
    entry.offset = position(iter);      // store file position
    skipOne(iter);                      // skip '>'

    readUntil(entry.name, iter, IsWhitespace());    // read Fasta id (up to first whitespace)
    skipLine(iter);
    entry.offset = position(iter);      // store offset

    FaiIndexEntry_ temp;
    FaiIndexEntry_ *entryPtr = &entry;
    FaiIndexEntry_ *cmpPtr = &entry;
    OrFunctor<IsNewline, CountFunctor<NotFunctor<IsWhitespace> > > countCharsPerLine;

    while (!atEnd(iter) && !TFastaBegin()(value(iter)))
    {
        // check for consistency
        if (cmpPtr->lineLength != entry.lineLength ||
            cmpPtr->overallLineLength != entry.overallLineLength)
        {
            SEQAN_THROW(ParseError("FastaIndex: Record has inconsistent line lengths or line endings"));
        }

        __uint64 start = position(iter);

        // skip to the end of line and count non-whitespace characters
        clear(countCharsPerLine.func2);
        skipUntil(iter, countCharsPerLine);
        entry.sequenceLength += value(countCharsPerLine.func2);

        // determine line length in bases
        entryPtr->lineLength = value(countCharsPerLine.func2);

        // skip linebreak
        skipLine(iter);

        // determine line length in bytes
        entryPtr->overallLineLength = (__uint64)position(iter) - start;
        cmpPtr = entryPtr;
        entryPtr = &temp;
    }
}

// ---------------------------------------------------------------------------
// Function build()
// ---------------------------------------------------------------------------

/*!
 * @fn FaiIndex#build
 * @brief Create a FaiIndex from FASTA file.
 *
 * @signature bool build(faiIndex, seqFileName[, faiFileName]);
 *
 * @param[out] faiIndex    The FaiIndex to build into.
 * @param[in]  seqFileName Path to the FASTA file to build an index for.  Type: <tt>char const *</tt>.
 * @param[in]  faiFileName Path to the FAI file to use as the index file.  Type: <tt>char const *</tt>.
 *                         Default: <tt>"${seqFileName}.fai"</tt>.
 *
 * @return bool <tt>true</tt> on success, <tt>false</tt> otherwise.
 */

inline bool build(FaiIndex & index, char const * seqFilename, char const * faiFilename)
{
    index.fastaFilename = seqFilename;
    index.faiFilename = faiFilename;

    SeqFileIn seqFile(seqFilename);
    DirectionIterator<SeqFileIn, Input>::Type iter = directionIterator(seqFile, Input());

    if (!isEqual(format(seqFile), seqan::Fasta()))
        return false;  // Invalid format, not FASTA.

    // Clear everything.
    clear(index.seqNameStore);
    clear(index.seqNameStoreCache);
    clear(index.indexEntryStore);

    // Create FastaIndex
    FaiIndexEntry_ entry;
    while (!atEnd(iter))
    {
        getRecordInfo(entry, iter, Fasta());
        appendValue(index.seqNameStore, entry.name);
        appendValue(index.indexEntryStore, entry);
    }

    // Recreate name store cache.
    refresh(index.seqNameStoreCache);

    return true;
}

inline bool build(FaiIndex & index, char const * seqFilename)
{
    CharString faiFilename(seqFilename);
    append(faiFilename, ".fai");
    return build(index, seqFilename, toCString(faiFilename));
}

}  // namespace seqan

#endif  // #ifndef SEQAN_APPS_RABEMA_FAI_INDEX_H_


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  Copyright 2015 herd contributors

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>

   <parent>
      <groupId>org.finra.herd</groupId>
      <artifactId>herd-code</artifactId>
      <version>${revision}</version>
   </parent>

   <name>herd tools</name>
   <packaging>pom</packaging>

   <artifactId>herd-tools</artifactId>

   <description>This is the base pom for the various tools.</description>
   <url>http://finraos.github.io/herd/</url>

   <profiles>
      <profile>
         <id>tools-main</id>
         <modules>
            <module>herd-tools-common</module>
            <module>herd-uploader</module>
            <module>herd-downloader</module>
            <module>herd-retention-expiration-exporter</module>
            <module>herd-retention-expiration-destroyer</module>
            <module>herd-pandas</module>
            <module>herd-access-validator</module>
            <module>herd-content-loader</module>
         </modules>
      </profile>
      <profile>
         <id>tools-spark</id>
         <modules>
            <module>herd-spark-data-source</module>
            <module>herd-spark-data-catalog</module>
            <module>herd-spark-2.2-data-source</module>
            <module>herd-spark-3.0-data-source</module>
            <module>herd-spark-3.0-data-catalog</module>
            <module>herd-spark-3.2-data-source</module>
            <module>herd-spark-3.2-data-catalog</module>
         </modules>
      </profile>
      <profile>
         <id>tools-python</id>
         <modules>
            <module>herd-pandas</module>
            <module>herd-content-loader</module>
         </modules>
      </profile>
      <profile>
         <id>default</id>
         <activation>
            <activeByDefault>true</activeByDefault>
         </activation>
         <modules>
            <module>herd-tools-common</module>
            <module>herd-uploader</module>
            <module>herd-downloader</module>
            <module>herd-retention-expiration-exporter</module>
            <module>herd-retention-expiration-destroyer</module>
            <module>herd-pandas</module>
            <module>herd-access-validator</module>
            <module>herd-content-loader</module>
         </modules>
      </profile>
   </profiles>

</project>


text:
/**
 * Query provider based on Apache Geode (Gemfire) In Memory Data Grid
 */
package org.apache.calcite.adapter.geode.rel;


text:
class RemoveCssClassDefaultFromEssencePictures < ActiveRecord::Migration

  def self.up
    change_column_default :essence_pictures, :css_class, nil
  end

  def self.down
    change_column_default :essence_pictures, :css_class, "no_float"
  end

end


text:
package org.asassecreations.voxelgame.world.block;

public final class BlockModeled {

	public boolean visible = true;

	public boolean left = true;
	public boolean right = true;
	public boolean top = true;
	public boolean bottom = true;
	public boolean front = true;
	public boolean back = true;

	public float brightnessLeft = 0;
	public float brightnessRight = 0;
	public float brightnessTop = 0;
	public float brightnessBottom = 0;
	public float brightnessFront = 0;
	public float brightnessBack = 0;

	public final Block preset;

	public BlockModeled(final Block preset) {

		this.preset = preset;

	}

}


text:
"""
ERP+
"""
__author__ = ['António Anacleto', 'Jair Medina', 'Abner Oliveira']
__credits__ = []
__version__ = "1.0"
__maintainer__ =  ['António Anacleto', 'Jair Medina', 'Jair Medina', 'Abner Oliveira']
__status__ = "Development"
__model_name__= 'mapa_gestao.MapaGestao'
#import base_models#auth,
from orm import *
from form import *

class MapaGestao(Model, View):
    def __init__(self, **kargs):
        Model.__init__(self, **kargs)

        self.__name__ = 'mapa_gestao'
        self.__title__= 'Mapa Gestão'
        self.__model_name__ = __model_name__
        self.__list_edit_mode__ = 'edit'
        self.__workflow__ = (
            'estado', {'Rascunho':['Imprimir', 'Valores0', 'Imp.Excel', 'Imp.Primavera', 'Imp.PHC'], 'Confirmado':['Imprimir']}
            )
        self.__workflow_auth__ = {
            'Imprimir':['All'],
            'Valores0':['All'],
            'Imp.Excel':['All'],
            'Imp.PHC':['All'],
            'Imp.Primavera':['All'],
            'Rascunho':['Gestor'],
           }

        self.nif = string_field(view_order=1, name='Nif', size=80)
        self.ano_fiscal = string_field(view_order=2, name='Ano Fiscal', size=5)
        self.estado = info_field(view_order=3, name ='Estado', default='Rascunho', onlist=False, hidden=True, nolabel=True,)
        self.mapa = combo_field(view_order=4, name ='Mapa', options=[('balancete','Balancete'), ('balanco','Balanço'), ('demonst_resul','Demonstração de Resultado'), ('fluxoCaixa','Fluxo de Caixa')], onlist=False, default='Praia')
        self.linha_mapa_gestao = list_field(view_order = 5, name = 'Valores', model_name = 'linha_mapa_gestao.LinhaMapaGestao', condition = "factura_cli='{id}'", list_edit_mode = 'inline', onlist = False)