text:
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const experimental_utils_1 = require("@typescript-eslint/experimental-utils");
const typescript_1 = __importDefault(require("typescript"));
const tsutils = __importStar(require("tsutils"));
const util = __importStar(require("../util"));
exports.default = util.createRule({
    name: 'strict-boolean-expressions',
    meta: {
        type: 'suggestion',
        docs: {
            description: 'Restricts the types allowed in boolean expressions',
            category: 'Best Practices',
            recommended: false,
        },
        schema: [],
        messages: {
            strictBooleanExpression: 'Unexpected non-boolean in conditional.',
        },
    },
    defaultOptions: [],
    create(context) {
        const service = util.getParserServices(context);
        const checker = service.program.getTypeChecker();
        /**
         * Determines if the node has a boolean type.
         */
        function isBooleanType(node) {
            const tsNode = service.esTreeNodeToTSNodeMap.get(node);
            const type = util.getConstrainedTypeAtLocation(checker, tsNode);
            return tsutils.isTypeFlagSet(type, typescript_1.default.TypeFlags.BooleanLike);
        }
        /**
         * Asserts that a testable expression contains a boolean, reports otherwise.
         * Filters all LogicalExpressions to prevent some duplicate reports.
         */
        function assertTestExpressionContainsBoolean(node) {
            if (node.test !== null &&
                node.test.type !== experimental_utils_1.AST_NODE_TYPES.LogicalExpression &&
                !isBooleanType(node.test)) {
                reportNode(node.test);
            }
        }
        /**
         * Asserts that a logical expression contains a boolean, reports otherwise.
         */
        function assertLocalExpressionContainsBoolean(node) {
            if (!isBooleanType(node.left) || !isBooleanType(node.right)) {
                reportNode(node);
            }
        }
        /**
         * Asserts that a unary expression contains a boolean, reports otherwise.
         */
        function assertUnaryExpressionContainsBoolean(node) {
            if (!isBooleanType(node.argument)) {
                reportNode(node.argument);
            }
        }
        /**
         * Reports an offending node in context.
         */
        function reportNode(node) {
            context.report({ node, messageId: 'strictBooleanExpression' });
        }
        return {
            ConditionalExpression: assertTestExpressionContainsBoolean,
            DoWhileStatement: assertTestExpressionContainsBoolean,
            ForStatement: assertTestExpressionContainsBoolean,
            IfStatement: assertTestExpressionContainsBoolean,
            WhileStatement: assertTestExpressionContainsBoolean,
            LogicalExpression: assertLocalExpressionContainsBoolean,
            'UnaryExpression[operator="!"]': assertUnaryExpressionContainsBoolean,
        };
    },
});
//# sourceMappingURL=strict-boolean-expressions.js.map


text:
<?xml version="1.0" encoding="UTF-8"?>

<phpunit colors="true" stopOnFailure="false" bootstrap="../core/bootstrap_phpunit.php">
	<php>
		<server name="doc_root" value="../../"/>
		<server name="app_path" value="fuel/app"/>
		<server name="core_path" value="fuel/core"/>
		<server name="package_path" value="fuel/packages"/>
	</php>
	<testsuites>
		<testsuite name="core">
			<directory suffix=".php">../core/tests</directory>
		</testsuite>
		<testsuite name="packages">
			<directory suffix=".php">../packages/*/tests</directory>
		</testsuite>
		<testsuite name="app">
			<directory suffix=".php">../app/tests</directory>
		</testsuite>
	</testsuites>
</phpunit>

redpajama_set_name: RedPajamaGithub


text:
from django import forms

from core.forms import SaveHelper

from .models import Um

class UmForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(UmForm, self).__init__(*args, **kwargs)
        self.helper = SaveHelper(self)

    class Meta:
        model = Um
        fields = [
            'texto',
            'versao'
        ]


text:
import utmpl = require('uri-templates');
import URITemplate = utmpl.URITemplate;

var str: string;
var u: URITemplate;
var obj: Object;

u = utmpl(str);

str = u.fillFromObject(obj);
str = u.fill((key) => {
	return str;
});
obj = u.fromUri(str);


text:
<form ng-submit="$event.preventDefault()" class="advert-form" layout="row" layout-align="center center">
    <md-autocomplete flex="75" class="advert-form-input"
        ng-disabled="$ctrl.isDisabled"
        md-no-cache="$ctrl.noCache"
        md-search-text-change="$ctrl.searchTextChange($ctrl.searchText)"
        md-selected-item-change="$ctrl.selectedItemChange(item)"
        md-items="item in $ctrl.searchQuery($ctrl.searchText)"
        md-selected-item="$ctrl.selectedItem"
        md-search-text="$ctrl.searchText"
        md-item-text="item.display"
        md-min-length="2"
        placeholder="{{'ADVERT_FORM_SEARCH_INPUT' | translate | unsafe}}">
        <md-item-template>
            {{item.display}}
        </md-item-template>
        <md-not-found>
            No states matching "{{$ctrl.searchText}}" were found.
            Create a new one!
        </md-not-found>
    </md-autocomplete>
    <md-input-container ng-if="false" class="md-block" flex-gt-sm>
        <md-checkbox ng-model="$ctrl.simulateQuery">Simulate query for results?</md-checkbox>
        <md-checkbox ng-model="$ctrl.noCache">Disable caching of queries?</md-checkbox>
        <md-checkbox ng-model="$ctrl.isDisabled">Disable the input?</md-checkbox>
    </md-input-container>
</form>


text:
package rmq

import (
	"fmt"
	"log"
	"strings"
	"time"

	"github.com/adjust/redis"
	"github.com/adjust/uniuri"
)

const heartbeatDuration = time.Minute

// Connection is an interface that can be used to test publishing
type Connection interface {
	OpenQueue(name string) Queue
	CollectStats(queueList []string) Stats
	GetOpenQueues() []string
}

// Connection is the entry point. Use a connection to access queues, consumers and deliveries
// Each connection has a single heartbeat shared among all consumers
type redisConnection struct {
	Name             string
	heartbeatKey     string // key to keep alive
	queuesKey        string // key to list of queues consumed by this connection
	redisClient      *redis.Client
	heartbeatStopped bool
}

// OpenConnectionWithRedisClient opens and returns a new connection
func OpenConnectionWithRedisClient(tag string, redisClient *redis.Client) *redisConnection {
	name := fmt.Sprintf("%s-%s", tag, uniuri.NewLen(6))

	connection := &redisConnection{
		Name:         name,
		heartbeatKey: strings.Replace(connectionHeartbeatTemplate, phConnection, name, 1),
		queuesKey:    strings.Replace(connectionQueuesTemplate, phConnection, name, 1),
		redisClient:  redisClient,
	}

	if !connection.updateHeartbeat() { // checks the connection
		log.Panicf("rmq connection failed to update heartbeat %s", connection)
	}

	// add to connection set after setting heartbeat to avoid race with cleaner
	redisErrIsNil(redisClient.SAdd(connectionsKey, name))

	go connection.heartbeat()
	// log.Printf("rmq connection connected to %s %s:%s %d", name, network, address, db)
	return connection
}

// OpenConnection opens and returns a new connection
func OpenConnection(tag, network, address string, db int) *redisConnection {
	redisClient := redis.NewClient(&redis.Options{
		Network: network,
		Addr:    address,
		DB:      int64(db),
	})
	return OpenConnectionWithRedisClient(tag, redisClient)
}

// OpenQueue opens and returns the queue with a given name
func (connection *redisConnection) OpenQueue(name string) Queue {
	redisErrIsNil(connection.redisClient.SAdd(queuesKey, name))
	queue := newQueue(name, connection.Name, connection.queuesKey, connection.redisClient)
	return queue
}

func (connection *redisConnection) CollectStats(queueList []string) Stats {
	return CollectStats(queueList, connection)
}

func (connection *redisConnection) String() string {
	return connection.Name
}

// GetConnections returns a list of all open connections
func (connection *redisConnection) GetConnections() []string {
	result := connection.redisClient.SMembers(connectionsKey)
	if redisErrIsNil(result) {
		return []string{}
	}
	return result.Val()
}

// Check retuns true if the connection is currently active in terms of heartbeat
func (connection *redisConnection) Check() bool {
	heartbeatKey := strings.Replace(connectionHeartbeatTemplate, phConnection, connection.Name, 1)
	result := connection.redisClient.TTL(heartbeatKey)
	if redisErrIsNil(result) {
		return false
	}
	return result.Val() > 0
}

// StopHeartbeat stops the heartbeat of the connection
// it does not remove it from the list of connections so it can later be found by the cleaner
func (connection *redisConnection) StopHeartbeat() bool {
	connection.heartbeatStopped = true
	return !redisErrIsNil(connection.redisClient.Del(connection.heartbeatKey))
}

func (connection *redisConnection) Close() bool {
	return !redisErrIsNil(connection.redisClient.SRem(connectionsKey, connection.Name))
}

// GetOpenQueues returns a list of all open queues
func (connection *redisConnection) GetOpenQueues() []string {
	result := connection.redisClient.SMembers(queuesKey)
	if redisErrIsNil(result) {
		return []string{}
	}
	return result.Val()
}

// CloseAllQueues closes all queues by removing them from the global list
func (connection *redisConnection) CloseAllQueues() int {
	result := connection.redisClient.Del(queuesKey)
	if redisErrIsNil(result) {
		return 0
	}
	return int(result.Val())
}

// CloseAllQueuesInConnection closes all queues in the associated connection by removing all related keys
func (connection *redisConnection) CloseAllQueuesInConnection() error {
	redisErrIsNil(connection.redisClient.Del(connection.queuesKey))
	// debug(fmt.Sprintf("connection closed all queues %s %d", connection, connection.queuesKey)) // COMMENTOUT
	return nil
}

// GetConsumingQueues returns a list of all queues consumed by this connection
func (connection *redisConnection) GetConsumingQueues() []string {
	result := connection.redisClient.SMembers(connection.queuesKey)
	if redisErrIsNil(result) {
		return []string{}
	}
	return result.Val()
}

// heartbeat keeps the heartbeat key alive
func (connection *redisConnection) heartbeat() {
	for {
		if !connection.updateHeartbeat() {
			// log.Printf("rmq connection failed to update heartbeat %s", connection)
		}

		time.Sleep(time.Second)

		if connection.heartbeatStopped {
			// log.Printf("rmq connection stopped heartbeat %s", connection)
			return
		}
	}
}

func (connection *redisConnection) updateHeartbeat() bool {
	return !redisErrIsNil(connection.redisClient.SetEx(connection.heartbeatKey, heartbeatDuration, "1"))
}

// hijackConnection reopens an existing connection for inspection purposes without starting a heartbeat
func (connection *redisConnection) hijackConnection(name string) *redisConnection {
	return &redisConnection{
		Name:         name,
		heartbeatKey: strings.Replace(connectionHeartbeatTemplate, phConnection, name, 1),
		queuesKey:    strings.Replace(connectionQueuesTemplate, phConnection, name, 1),
		redisClient:  connection.redisClient,
	}
}

// openQueue opens a queue without adding it to the set of queues
func (connection *redisConnection) openQueue(name string) *redisQueue {
	return newQueue(name, connection.Name, connection.queuesKey, connection.redisClient)
}

// flushDb flushes the redis database to reset everything, used in tests
func (connection *redisConnection) flushDb() {
	connection.redisClient.FlushDb()
}


text:
(function() {
  var Serie, Torrent, calendarContent, isSerieStarred, month, monthNames, parseCalendar, today;

  calendarContent = '';

  today = new Date();

  month = today.getMonth();

  monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

  angular.module('home', []).config(function($compileProvider) {
    return $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|chrome-extension|magnet):/);
  }).controller('HomeController', function($scope, $http) {
    var getSeriesDate, searchSeries;
    searchSeries = function(dateToSeach) {
      getSeriesDate(dateToSeach, $http, function(response) {
        $scope.seriesList = response;
        return $('#today').text(dateToSeach.getDate() + ' ' + monthNames[dateToSeach.getMonth()]);
      });
      return false;
    };
    getSeriesDate = function(dateToSearch, $http, success) {
      var monthCorrected, todayFormat;
      monthCorrected = dateToSearch.getMonth() + 1;
      todayFormat = '#d_' + dateToSearch.getDate() + '_' + monthCorrected + '_' + dateToSearch.getFullYear();
      if (calendarContent === '') {
        return $http.get('http://www.pogdesign.co.uk/cat/').success(function(data, status, headers, config) {
          if (status = 200) {
            calendarContent = data;
            return parseCalendar(todayFormat, success);
          } else {
            alert('something went wrong with the calendar connection: ' + response.statusCode);
            return calendarContent = '';
          }
        }).error(function() {
          return $scope.errorOnCall = true;
        });
      } else {
        return parseCalendar(todayFormat, success);
      }
    };
    $scope.getTorrents = function(serie) {
      var episode, urlRequest;
      $scope.serieSelected = serie;
      $scope.torrentList = [];
      episode = serie.serie.concat(' ').concat(serie.episode);
      episode = episode.replace(/\s/g, '%20');
      urlRequest = 'https://thepiratebay.se/search/' + episode + '/0/99/0';
      return $http.get(urlRequest).success(function(data, status, headers, config) {
        var desc, detLink, jresult, leeds, length, link, name, result, searchResult, seeds, torrent, torrentList, _i;
        searchResult = $(data).find('#searchResult').find('tr');
        torrentList = [];
        if (searchResult.length === 0) {
          if (typeof success === "function") {
            success(torrentList);
          }
        } else {
          length = searchResult.length > 3 ? 4 : searchResult.length;
          for (result = _i = 1; 1 <= length ? _i <= length : _i >= length; result = 1 <= length ? ++_i : --_i) {
            jresult = $(searchResult[result]);
            detLink = $(jresult.find(".detName")[0]).find(".detLink")[0];
            if (detLink !== void 0) {
              name = detLink.innerText;
              link = $(jresult.find("a[href^=magnet]")[0]).attr("href");
              desc = $(jresult.find("td")[1]).find(".detDesc").eq(0).text();
              seeds = jresult.find("td").eq(2).text();
              leeds = jresult.find("td").eq(3).text();
              torrent = new Torrent(name, leeds, seeds, link, desc);
              torrentList.push(torrent);
            }
          }
        }
        return $scope.torrentList = torrentList;
      });
    };
    searchSeries(new Date());
    $scope.goBack = function() {
      return $scope.torrentList = null;
    };
    $scope.previousDay = function() {
      today.setDate(today.getDate() - 1);
      if (month === today.getMonth()) {
        return searchSeries(today);
      } else {
        return today.setDate(today.getDate() + 1);
      }
    };
    $scope.nextDay = function() {
      today.setDate(today.getDate() + 1);
      if (month === today.getMonth()) {
        return searchSeries(today);
      } else {
        return today.setDate(today.getDate() - 1);
      }
    };
    return $scope.starShow = (function(_this) {
      return function(serie, e) {
        e.stopPropagation();
        if (localStorage.getItem(serie.serie) === null) {
          localStorage.setItem(serie.serie, "star");
          return serie.starred = true;
        } else {
          localStorage.removeItem(serie.serie);
          return serie.starred = false;
        }
      };
    })(this);
  });

  parseCalendar = function(todayFormat, success) {
    var as, className, div, divs, jdiv, serie, serieEpisodeString, serieId, serieList, serieTitleString, _i, _len;
    divs = $(calendarContent).find(todayFormat).find('div');
    serieList = [];
    serieId = 0;
    for (_i = 0, _len = divs.length; _i < _len; _i++) {
      div = divs[_i];
      jdiv = $(div);
      className = jdiv.find('p')[0].className;
      as = jdiv.find('a');
      serieTitleString = as[0].text;
      serieEpisodeString = as[1].text;
      serie = new Serie(serieTitleString.trim(), serieEpisodeString, className, serieId, isSerieStarred(serieTitleString.trim()));
      serieList.push(serie);
      serieId++;
    }
    return typeof success === "function" ? success(serieList) : void 0;
  };

  isSerieStarred = function(serieName) {
    return localStorage.getItem(serieName) != null;
  };

  Serie = (function() {
    function Serie(serie, episode, className, serieId, starred) {
      this.serie = serie;
      this.episode = episode;
      this.className = className;
      this.serieId = serieId;
      this.starred = starred;
    }

    return Serie;

  })();

  Torrent = (function() {
    function Torrent(name, leeds, seeds, link, desc) {
      this.name = name;
      this.leeds = leeds;
      this.seeds = seeds;
      this.link = link;
      this.desc = desc;
    }

    return Torrent;

  })();

}).call(this);


text:
package org.openmrs.module.sana.api;

import com.google.gson.Gson;

/**
 * A response returned from an entity of the Sana dispatch layer.
 *
 * @author Sana Development Team
 *
 */
public class MDSResponse {
	public static final String FAILURE = "FAIL";
	public static final String SUCCESS = "OK";

	public MDSResponse() {}

	/** A status string */
	public String status;
	/** A status code string for providing more granular response */
	public String code;
	/** A message body */
	public String message;

	/**
	 * Returns the JSON String representation of the object
	 */
	public String toJSON(){
    	Gson g = new Gson();
    	return g.toJson(this);
	}

    /**
     * Called when a transaction is successful. The response code is set to
     * unspecified.
     * @param message The message body of the response
     * @return
     */
    public static MDSResponse succeed(String message){
    	return succeed(message, "unspecified");
    }

    /**
     * Call when a transaction is successful to generate a response message.
     *
     * @param message The message body of the response
     * @param code A response code.
     * @return
     */
    public static MDSResponse succeed(String message, String code){
    	MDSResponse mdsresponse = new MDSResponse();
    	mdsresponse.status = MDSResponse.SUCCESS;
    	mdsresponse.code = code;
    	mdsresponse.message = message;
    	return mdsresponse;
    }

    /**
     * Called when a transaction fails. The response code is set to
     * unspecified.
     * @param message The message body of the response
     * @return
     */
    public static MDSResponse fail(String message){
    	return fail(message, "unspecified");
    }

    /**
     * Called when a transaction fails.
     * @param message The message body of the response
     * @param code
     * @return
     */
    public static MDSResponse fail(String message, String code){
    	MDSResponse mdsresponse = new MDSResponse();
    	mdsresponse.status = MDSResponse.FAILURE;
    	mdsresponse.code = "unspecified";
    	mdsresponse.message = message;
    	return mdsresponse;
    }
}


text:
  <title>Allow an empty resource.</title>

The test passes if the zero-byte resource is allowed.


text:
package com.nortal.jroad.client.rr;

import java.util.Date;
import java.util.List;

import com.nortal.jroad.client.exception.XRoadServiceConsumptionException;
import com.nortal.jroad.client.rr.types.ee.riik.xtee.rr.producers.producer.rr.DokumendiTyyp;
import com.nortal.jroad.client.rr.types.ee.riik.xtee.rr.producers.producer.rr.IsikuStaatus;
import com.nortal.jroad.client.rr.types.ee.riik.xtee.rr.producers.producer.rr.RR40Response;
import com.nortal.jroad.client.rr.types.ee.riik.xtee.rr.producers.producer.rr.RR41ResponseV1;
import com.nortal.jroad.client.rr.types.ee.riik.xtee.rr.producers.producer.rr.RR42Request;
import com.nortal.jroad.client.rr.types.ee.riik.xtee.rr.producers.producer.rr.RR42Response;
import com.nortal.jroad.client.rr.types.ee.riik.xtee.rr.producers.producer.rr.RR43Response;
import com.nortal.jroad.client.rr.types.ee.riik.xtee.rr.producers.producer.rr.RR52Response;
import com.nortal.jroad.client.rr.types.ee.riik.xtee.rr.producers.producer.rr.RR63ResponseV1;
import com.nortal.jroad.client.rr.types.ee.riik.xtee.rr.producers.producer.rr.RR81Response;
import com.nortal.jroad.client.rr.types.ee.riik.xtee.rr.producers.producer.rr.RR81ResponseV1;
import com.nortal.jroad.client.rr.types.ee.riik.xtee.rr.producers.producer.rr.RR84Request;
import com.nortal.jroad.client.rr.types.ee.riik.xtee.rr.producers.producer.rr.RR84Response;
import com.nortal.jroad.client.rr.types.ee.riik.xtee.rr.producers.producer.rr.RR96ResponseV1;
import com.nortal.jroad.client.rr.types.ee.riik.xtee.rr.producers.producer.rr.RRExtDocumentDataRequest;
import com.nortal.jroad.client.rr.types.ee.riik.xtee.rr.producers.producer.rr.RRExtDocumentDataResponse;
import com.nortal.jroad.client.rr.types.ee.riik.xtee.rr.producers.producer.rr.RRPORTTEOVOIMEResponse;
import com.nortal.jroad.client.rr.types.ee.riik.xtee.rr.producers.producer.rr.RR67Response.TtKoodid;
import com.nortal.jroad.client.rr.types.ee.riik.xtee.rr.producers.producer.rr.RR72Response.TtIsikud;

/**
 * rr (Rahvastikuregister) database X-tee service.
 *
 * @author Roman Tekhov
 */
public interface RrXTeeService {

	/**
	 * rr.RR72_isik.v1 service.
	 */
	List<TtIsikud.Item> findRR72Isik(String... idCodes)
			throws XRoadServiceConsumptionException;

	/**
	 * rr.RR63isikAadrDok.v1 service.
	 */
	RR63ResponseV1 findRR63IsikAadrDok(String surname, String firstName,
			String idCode, String birthDate)
			throws XRoadServiceConsumptionException;

	/**
	 * rr.RR81KMAisikkontroll.v1 service.
	 */
	RR81Response getRR81KMAisikkontroll(String idCode)
			throws XRoadServiceConsumptionException;

	/**
	 * rr.RR81KMAisikkontroll_V1.v1 service.
	 */
	RR81ResponseV1 getRR81KMAisikkontrollv1(String idCode)
			throws XRoadServiceConsumptionException;

	/**
	 * rr.RR40isikTaielikIsikukood.v1 service.
	 */
	RR40Response findRR40isikTaielikIsikukood(String isikukood)
			throws XRoadServiceConsumptionException;

	/**
	 * rr.RR42isikAadressKood.v1 service.
	 */
	RR42Response findRR42isikAadressKood(RR42RequestCallback cb)
			throws XRoadServiceConsumptionException;

	interface RR42RequestCallback {
		void populate(RR42Request paring);
	}

	/**
	 * rr.RR52.v1 service.
	 */
	RR52Response getRR52(String idCode, String forename, String surname)
			throws XRoadServiceConsumptionException;

	/**
	 * rr.RR43dokument.v1 service.
	 */
	RR43Response getRR43dokument(String dokumendiKood, String dokumendiSeeria,
			DokumendiTyyp.Enum dokumendiTyyp)
			throws XRoadServiceConsumptionException;

	/**
	 * rr.RR96IsikDokElukSuhe_v1.v1 service.
	 */
	RR96ResponseV1 getRR96isikDokElukSuhe(String isikueesnimi,
			String isikuperenimi, String isikukood, Long vastusteArv)
			throws XRoadServiceConsumptionException;

	/**
	 * rr.RRExtDocumentDataArkLuba.v1 service.
	 */
	RRExtDocumentDataResponse sendRRExtDocumentDataArkLuba(
			RRExtDocumentDataRequest request)
			throws XRoadServiceConsumptionException;

	/**
	 * rr.RR67MuutusV1.v1 service.
	 */
	List<TtKoodid.Item> findRR67MuutusV1(Date algus, Date lopp,
			String... koodid) throws XRoadServiceConsumptionException;

	 /**
   * rr.RR84IsikuSeosed.v1 service.
   */
  RR84Response findRR84IsikuSeosed(String isikukood) throws XRoadServiceConsumptionException;

	/**
	 * rr.RR41isikPohiandmedV1.v1 service.
	 */
  RR41ResponseV1 findRR41isikPohiandmedV1(String perenimi, String eesnimi, String isikukood,
			String vald, IsikuStaatus staatus, Long vastusteArv)
			throws XRoadServiceConsumptionException;

  /**
   * rr.RRPORTTEOVOIME.v1 service.
   */
  RRPORTTEOVOIMEResponse getRRPortTeovoimeV1(String isikukood)
			throws XRoadServiceConsumptionException;
}


text:
class CloudTenantDashboardController < ApplicationController
  extend ActiveSupport::Concern

  before_action :check_privileges
  before_action :get_session_data
  before_action :get_tenant, :only => %i[data recent_instances_data recent_images_data aggregate_status_data]
  after_action :cleanup_action
  after_action :set_session_data

  def data
    assert_privileges('ems_cloud_view')
    render :json => {:data => collect_data}
  end

  def recent_instances_data
    assert_privileges('ems_cloud_view')
    render :json => {:data => recent_instances}
  end

  def recent_images_data
    assert_privileges('ems_cloud_view')
    render :json => {:data => recent_images}
  end

  def aggregate_status_data
    assert_privileges('ems_cloud_view')
    render :json => {:data => aggregate_status}
  end

  private

  def collect_data
    CloudTenantDashboardService.new(@tenant, self, CloudTenant).all_data
  end

  def recent_instances
    CloudTenantDashboardService.new(@tenant, self, CloudTenant).recent_instances_data
  end

  def recent_images
    CloudTenantDashboardService.new(@tenant, self, CloudTenant).recent_images_data
  end

  def aggregate_status
    CloudTenantDashboardService.new(@tenant, self, CloudTenant).aggregate_status_data
  end

  def get_session_data
    @layout = "cloud_tenant_dashboard"
  end

  def set_session_data
    session[:layout] = @layout
  end

  def get_tenant
    @tenant = find_record_with_rbac(CloudTenant, params[:id])
  end
end


text:
Cap'n Proto is a project of Sandstorm.io

Maintained by kentonv ∙ Design by sailorhg

Follow Cap'n Proto on Twitter


text:
export const RESOURCE_TYPE = 'RESOURCE_TYPE'
export const DIFFICULTY = 'DIFFICULTY'
export const RATING = 'RATING'
export const TAGS = 'TAGS'


text:
namespace System.ServiceModel.Configuration
{
    using System;
    using System.ComponentModel;
    using System.Configuration;
    using System.Runtime;
    using System.ServiceModel;
    using System.ServiceModel.Channels;

    public sealed partial class NamedPipeConnectionPoolSettingsElement : ServiceModelConfigurationElement
    {
        public NamedPipeConnectionPoolSettingsElement()
        {
        }

        [ConfigurationProperty(ConfigurationStrings.GroupName, DefaultValue = ConnectionOrientedTransportDefaults.ConnectionPoolGroupName)]
        [StringValidator(MinLength = 0)]
        public string GroupName
        {
            get { return (string)base[ConfigurationStrings.GroupName]; }
            set
            {
                if (String.IsNullOrEmpty(value))
                {
                    value = String.Empty;
                }
                base[ConfigurationStrings.GroupName] = value;
            }
        }

        [ConfigurationProperty(ConfigurationStrings.IdleTimeout, DefaultValue = ConnectionOrientedTransportDefaults.IdleTimeoutString)]
        [TypeConverter(typeof(TimeSpanOrInfiniteConverter))]
        [ServiceModelTimeSpanValidator(MinValueString = ConfigurationStrings.TimeSpanZero)]
        public TimeSpan IdleTimeout
        {
            get { return (TimeSpan)base[ConfigurationStrings.IdleTimeout]; }
            set { base[ConfigurationStrings.IdleTimeout] = value; }
        }

        [ConfigurationProperty(ConfigurationStrings.MaxOutboundConnectionsPerEndpoint, DefaultValue = ConnectionOrientedTransportDefaults.MaxOutboundConnectionsPerEndpoint)]
        [IntegerValidator(MinValue = 0)]
        public int MaxOutboundConnectionsPerEndpoint
        {
            get { return (int)base[ConfigurationStrings.MaxOutboundConnectionsPerEndpoint]; }
            set { base[ConfigurationStrings.MaxOutboundConnectionsPerEndpoint] = value; }
        }

        internal void ApplyConfiguration(NamedPipeConnectionPoolSettings settings)
        {
            if (null == settings)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("settings");
            }

            settings.GroupName = this.GroupName;
            settings.IdleTimeout = this.IdleTimeout;
            settings.MaxOutboundConnectionsPerEndpoint = this.MaxOutboundConnectionsPerEndpoint;
        }

        internal void InitializeFrom(NamedPipeConnectionPoolSettings settings)
        {
            if (null == settings)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("settings");
            }

            SetPropertyValueIfNotDefaultValue(ConfigurationStrings.GroupName, settings.GroupName);
            SetPropertyValueIfNotDefaultValue(ConfigurationStrings.IdleTimeout, settings.IdleTimeout);
            SetPropertyValueIfNotDefaultValue(ConfigurationStrings.MaxOutboundConnectionsPerEndpoint, settings.MaxOutboundConnectionsPerEndpoint);
        }

        internal void CopyFrom(NamedPipeConnectionPoolSettingsElement source)
        {
            if (source == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("source");
            }

            this.GroupName = source.GroupName;
            this.IdleTimeout = source.IdleTimeout;
            this.MaxOutboundConnectionsPerEndpoint = source.MaxOutboundConnectionsPerEndpoint;
        }
    }
}


text:
<!--
Description: xml:base is an IRI
-->
<feed xmlns="http://www.w3.org/2005/Atom" xml:base="http://www.example.com/feed">
  <link rel="self" type="application/atom+xml" href=""/>
</feed>


text:
.PHONY: clean

all: windower

clean:
	rm -f windower

windower: $(shell find . -iname '*.go')
	GOOS=linux go build


text:
Useful Links

Stackalytics @ OpenStack Wiki

Stackalytics @ Launchpad


text:
<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "news_view".
 *
 * @property integer $ID
 * @property string $Slug
 * @property string $Name
 * @property string $About
 * @property string $Text
 * @property string $Photo
 * @property integer $CategorynewsID
 * @property string $Date
 * @property integer $Views
 * @property integer $Grey
 */
class NewsView extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'news_view';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['Name', 'About', 'Text', 'Photo', 'CategorynewsID'], 'required'],
            [['Text', 'Photo'], 'string'],
            [['CategorynewsID', 'Views', 'Grey'], 'integer'],
            [['Date'], 'safe'],
            [['Name', 'About'], 'string', 'max' => 200],
            [['Slug'], 'string', 'max' => 1024],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'ID' => 'ID',
            'Slug' => 'Slug',
            'Name' => 'Name',
            'About' => 'About',
            'Text' => 'Text',
            'Photo' => 'Photo',
            'CategorynewsID' => 'Categorynews ID',
            'Date' => 'Date',
            'Views' => 'Views',
            'Grey' => 'Grey',
        ];
    }
}


text:
<?php

/**
 * The "environments" collection of methods.
 * Typical usage is:
 *  <code>
 *   $cloudshellService = new Google_Service_CloudShell(...);
 *   $environments = $cloudshellService->environments;
 *  </code>
 */
class Google_Service_CloudShell_Resource_UsersEnvironments extends Google_Service_Resource
{
  /**
   * Adds a public SSH key to an environment, allowing clients with the
   * corresponding private key to connect to that environment via SSH. If a key
   * with the same content already exists, this will error with ALREADY_EXISTS.
   * (environments.addPublicKey)
   *
   * @param string $environment Environment this key should be added to, e.g.
   * `users/me/environments/default`.
   * @param Google_Service_CloudShell_AddPublicKeyRequest $postBody
   * @param array $optParams Optional parameters.
   * @return Google_Service_CloudShell_Operation
   */
  public function addPublicKey($environment, Google_Service_CloudShell_AddPublicKeyRequest $postBody, $optParams = array())
  {
    $params = array('environment' => $environment, 'postBody' => $postBody);
    $params = array_merge($params, $optParams);
    return $this->call('addPublicKey', array($params), "Google_Service_CloudShell_Operation");
  }
  /**
   * Sends OAuth credentials to a running environment on behalf of a user. When
   * this completes, the environment will be authorized to run various Google
   * Cloud command line tools without requiring the user to manually authenticate.
   * (environments.authorize)
   *
   * @param string $name Name of the resource that should receive the credentials,
   * for example `users/me/environments/default` or
   * `users/someone@example.com/environments/default`.
   * @param Google_Service_CloudShell_AuthorizeEnvironmentRequest $postBody
   * @param array $optParams Optional parameters.
   * @return Google_Service_CloudShell_Operation
   */
  public function authorize($name, Google_Service_CloudShell_AuthorizeEnvironmentRequest $postBody, $optParams = array())
  {
    $params = array('name' => $name, 'postBody' => $postBody);
    $params = array_merge($params, $optParams);
    return $this->call('authorize', array($params), "Google_Service_CloudShell_Operation");
  }
  /**
   * Gets an environment. Returns NOT_FOUND if the environment does not exist.
   * (environments.get)
   *
   * @param string $name Required. Name of the requested resource, for example
   * `users/me/environments/default` or
   * `users/someone@example.com/environments/default`.
   * @param array $optParams Optional parameters.
   * @return Google_Service_CloudShell_Environment
   */
  public function get($name, $optParams = array())
  {
    $params = array('name' => $name);
    $params = array_merge($params, $optParams);
    return $this->call('get', array($params), "Google_Service_CloudShell_Environment");
  }
  /**
   * Removes a public SSH key from an environment. Clients will no longer be able
   * to connect to the environment using the corresponding private key. If a key
   * with the same content is not present, this will error with NOT_FOUND.
   * (environments.removePublicKey)
   *
   * @param string $environment Environment this key should be removed from, e.g.
   * `users/me/environments/default`.
   * @param Google_Service_CloudShell_RemovePublicKeyRequest $postBody
   * @param array $optParams Optional parameters.
   * @return Google_Service_CloudShell_Operation
   */
  public function removePublicKey($environment, Google_Service_CloudShell_RemovePublicKeyRequest $postBody, $optParams = array())
  {
    $params = array('environment' => $environment, 'postBody' => $postBody);
    $params = array_merge($params, $optParams);
    return $this->call('removePublicKey', array($params), "Google_Service_CloudShell_Operation");
  }
  /**
   * Starts an existing environment, allowing clients to connect to it. The
   * returned operation will contain an instance of StartEnvironmentMetadata in
   * its metadata field. Users can wait for the environment to start by polling
   * this operation via GetOperation. Once the environment has finished starting
   * and is ready to accept connections, the operation will contain a
   * StartEnvironmentResponse in its response field. (environments.start)
   *
   * @param string $name Name of the resource that should be started, for example
   * `users/me/environments/default` or
   * `users/someone@example.com/environments/default`.
   * @param Google_Service_CloudShell_StartEnvironmentRequest $postBody
   * @param array $optParams Optional parameters.
   * @return Google_Service_CloudShell_Operation
   */
  public function start($name, Google_Service_CloudShell_StartEnvironmentRequest $postBody, $optParams = array())
  {
    $params = array('name' => $name, 'postBody' => $postBody);
    $params = array_merge($params, $optParams);
    return $this->call('start', array($params), "Google_Service_CloudShell_Operation");
  }
}


text:
/**
 * An enum represents the different content types of a step and their loading mechanisms.
 *
 * @class contentMode
 * @for steps
 **/
var contentMode = $.fn.steps.contentMode = {
    /**
     * HTML embedded content
     *
     * @readOnly
     * @property html
     * @type Integer
     * @for contentMode
     **/
    html: 0,

    /**
     * IFrame embedded content
     *
     * @readOnly
     * @property iframe
     * @type Integer
     * @for contentMode
     **/
    iframe: 1,

    /**
     * Async embedded content
     *
     * @readOnly
     * @property async
     * @type Integer
     * @for contentMode
     **/
    async: 2
};

/**
 * An enum represents the orientation of the steps navigation.
 *
 * @class stepsOrientation
 * @for steps
 **/
var stepsOrientation = $.fn.steps.stepsOrientation = {
    /**
     * Horizontal orientation
     *
     * @readOnly
     * @property horizontal
     * @type Integer
     * @for stepsOrientation
     **/
    horizontal: 0,

    /**
     * Vertical orientation
     *
     * @readOnly
     * @property vertical
     * @type Integer
     * @for stepsOrientation
     **/
    vertical: 1
};

/**
 * An enum that represents the various transition animations.
 *
 * @class transitionEffect
 * @for steps
 **/
var transitionEffect = $.fn.steps.transitionEffect = {
    /**
     * No transition animation
     *
     * @readOnly
     * @property none
     * @type Integer
     * @for transitionEffect
     **/
    none: 0,

    /**
     * Fade in transition
     *
     * @readOnly
     * @property fade
     * @type Integer
     * @for transitionEffect
     **/
    fade: 1,

    /**
     * Slide up transition
     *
     * @readOnly
     * @property slide
     * @type Integer
     * @for transitionEffect
     **/
    slide: 2,

    /**
     * Slide left transition
     *
     * @readOnly
     * @property slideLeft
     * @type Integer
     * @for transitionEffect
     **/
    slideLeft: 3
};


text:
    </div>
     <script src="/static/lib/jquery.min.js"></script>
     <script src="/static/lib/bootstrap/js/bootstrap.min.js"></script>
     <script src="/static/lib/bootstrap-select/bootstrap-select.min.js"></script>
     <script src="/static/js/pagination.js"></script>
     <script>
     var checkMembership = function(selected) {
       var value = $(selected).val();
       if(value == 1) {
          $(selected).val(0);
       } else {
         $(selected).val(1);
       }
     }

     var searchOn = function(event) {
       if(event.target.value === "") {
         var code = event.keyCode;
         if ((code >= 48 && code <= 57) || (code >= 96 && code <= 105)) {
           $(".name-select", event.target.parentNode).val("phone_number");
         } else {
           $(".name-select", event.target.parentNode).val("name");
         }
       }
     }

     var searchOnInPage = function(event) {
       if(event.target.value === "") {
         var phone_radio = document.getElementById("search-select-phone");
         var name_radio = document.getElementById("search-select-name");
         var etc_radio = document.getElementById("search-select-etc");
         var code = event.keyCode;
         if ((code >= 48 && code <= 57) || (code >= 96 && code <= 105)) {
           phone_radio.checked = true;
           name_radio.checked = false;
           etc_radio.checked = false;
         } else {
           phone_radio.checked = false;
           name_radio.checked = true;
           etc_radio.checked = false;
         }
         console.log(code);
     }
   }

     var phoneFormatter = function(rawString) {
       var number = rawString.replace(/[^\d]/g, '');
       if (number.length == 7) {
         number = number.replace(/(\d{3})(\d{4})/, "$1-$2");
       } else if (number.length == 10) {
         number = number.replace(/(\d{3})(\d{3})(\d{4})/, "$1-$2-$3");
       } else if (number.length == 11) {
         number = number.replace(/(\d{3})(\d{4})(\d{4})/, "$1-$2-$3");
       }
       return number;
     }

     var formatPhone = function() {
       var phoneNumbers = document.getElementsByClassName("phone_number");
       for(var i = 0; i < phoneNumbers.length; i++) {
         var original = phoneNumbers[i].innerText;
         phoneNumbers[i].innerText = phoneFormatter(original);
       }
     }
     formatPhone();

     //customer functions
       var registerCustomer = function() {
         document.forms["register-customer-form"].action = "/index.php/work";
         document.forms["register-customer-form"].submit();
       }

       var selectCustomer = function(customer_id) {
         document.forms["modify-customer-form" + customer_id].submit();
       }

       var modifyCustomer = function(postclass) {
         document.getElementById('customer-modify-postclass-input').value = postclass;
         document.forms["register-customer-form"].submit();
       }

       // design2 functions
        var selectDesign1 = function(design1_id) {
          document.getElementById('design1-class-input').value = "select-design1";
          document.getElementById('design1-id-input').value = design1_id;
          document.forms["register-design1-form"].submit();
        }

        var deleteDesign1 = function(design1_id) {
          document.getElementById('design1-class-input').value = "delete-design1";
          document.getElementById('design1-id-input').value = design1_id;
          document.forms["register-design1-form"].submit();
        }

        var updateDesign1 = function(design1_id) {
          document.getElementById('design1-class-input').value = "update-design1";
          document.getElementById('design1-id-input').value = design1_id;
          document.forms["register-design1-form"].submit();
        }

        // design2 functions
        var selectDesign2 = function(design2_id) {
          document.getElementById('design2-class-input').value = "select-design2";
          document.getElementById('design2-id-input').value = design2_id;
          document.forms["register-design2-form"].submit();
        }

        var deleteDesign2 = function(design2_id) {
          document.getElementById('design2-class-input').value = "delete-design2";
          document.getElementById('design2-id-input').value = design2_id;
          document.forms["register-design2-form"].submit();
        }

        var updateDesign2 = function(design2_id) {
          document.getElementById('design2-class-input').value = "update-design2";
          document.getElementById('design2-id-input').value = design2_id;
          document.forms["register-design2-form"].submit();
        }

        //staff functions
        var selectStaff = function(staff_id) {
          document.getElementById('staff-id-input').value = staff_id;
          document.forms["staff-form"].submit();
        }

        var modifyStaff = function(staff_id) {
          document.getElementById('register-staff-id-input').value = staff_id;
          document.getElementById('staff-type-input').value = "modify";
          document.forms["register-staff-form"].submit();
        }

        var deleteStaff = function(staff_id) {
          document.getElementById('register-staff-id-input').value = staff_id;
          document.getElementById('staff-type-input').value = "delete";
          document.forms["register-staff-form"].submit();
        }
     </script>
   </body>
</html>


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
org.apache.hadoop.mapreduce.v2.app.local (hadoop-mapreduce-client-app 2.3.0 API)
</TITLE>

<META NAME="date" CONTENT="2015-03-06">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../stylesheet.css" TITLE="Style">

org.apache.hadoop.mapreduce.v2.app.local

Classes

LocalContainerAllocator


text:
var tester = tester || {};
tester.html5validation = tester.html5validation || {};

tester.html5validation.patternSpec = function() {
    beforeEach( function() {
        this.tester = new LiveValidator.Tester();
        this.param = { regex: '^[a-z]+$', title: 'Should be lowercase letter' };
    } );

    it( 'matches', function() {
        expect( this.tester.pattern( 'abc', this.param ) ).toEqual( true );
        expect( this.tester.errors ).toEqual( [] );
    } );

    it( 'does not match', function() {
        expect( this.tester.pattern( 'Ab2c', this.param ) ).toEqual( false );
        expect( this.tester.errors ).toEqual( [ this.param.title ] );
    } );
};


text:
function repeat(str, num) {
  // repeat after me
  var repeatedString = '';
  if (num > 0) {
    for (var i = 0; i < num; i++) {
      repeatedString += str;
    }
    return repeatedString;
  } else if (num < 0) {
    return repeatedString;
  }
}

repeat('abc', 3);


text:
@interface {CLASS} : NSObject
{
} // End of {CLASS}

- ({CLASS}*) initWithResultSet: (FMResultSet*) resultSet;
{METHOD_HEADERS}

{PROPERTIES}

@end


text:
/* Linked with ar.o to flag that this program is 'ranlib' (not 'ar').  */

int is_ranlib = 1;


text:
title: Index
---

# Welcome to the ATC Documentation.

## Pages

* [Airport format](airport-format.html)
* [Airline format](airline-format.html)
* [Aircraft separation](aircraft-separation.html)
* [Scoring](scoring.html)
* [Documentation format](README.html)

## Background

ATC stands for Air Traffic Controller, which is the role you take in this simulator.

> Air traffic control (ATC) is a service provided by ground-based
controllers who direct aircraft on the ground and through controlled
airspace, and can provide advisory services to aircraft in non-controlled
airspace. The primary purpose of ATC worldwide is to prevent collisions,
organize and expedite the flow of traffic, and provide information and
other support for pilots. - [Wikipedia](https://en.wikipedia.org/wiki/Air_traffic_control)

---

## Command Reference

Although the tutorial gives a large amount of information, if you find
remembering the commands too complicated, here's a reference. Remember
that you can type out multiple commands in one go; for example:
`BAW231 fh090 d 30 sp 180` will work as well as all three commands run
separately. Additionally, some have "shortKeys", where you can skip the
space that is normally included, like in `BAW231 fh090` (heading).

### Taxi
_Aliases -_ `taxi` / `wait` / `w`

_Information -_ This command tells the specified plane to taxi to a
runway; if a runway is not included they will continue to the runway
with the largest headwind.

_Syntax -_ `AAL123 taxi [Runway]`

### SID
_Aliases -_ `sid`

_Information -_ This command tells the specified plane a standard
instrument departure route (SID) it should follow. Each SID is a list of
fixes to be flown in sequence. Having a standardized route often helps
organize departing traffic, and maintain separation from arriving aircraft.

_Syntax -_ `AAL123 sid [SID name]`

### STAR
_Aliases -_ `star`

_Information -_ This command tells the plane to add or change their filed
Standard Terminal Arrival Route to match the route you specify. This must be
entered in dotted format, and include the point where the STAR is joined, as
well as the destination airport, for example: `MLP.GLASR9.KSEA`. See the section
on rerouting for further detail.

_Syntax -_ `AAL123 star [transition].[STAR name].[airport]`

### "Cleared As Filed"
_Aliases -_ `caf`

_Information -_ This command tells the airplane that they are cleared to follow
the flight plan that they requested when spawning. Therefore, when a departure
spawns on the ground, and his strip shows that he filed for a particular SID,
there is no need to use the `sid` command. Just clear him "as filed" with the
`caf` command, and the airplane will take care of the rest.

_Syntax -_ `AAL123 caf`

### "Climb Via SID"
_Aliases -_ `cvs`

_Information -_ Authorizes the aircraft to climb in accordance with the
SID that is currently in their flightplan. They will climb to their filed
cruise altitude, whilst complying with all altitude and speed restrictions
posted in the procedure.

_Syntax -_ `AAL123 cvs`

### "Descend via STAR"
_Aliases -_ `dvs`

_Information -_ Authorizes the aircraft to descend in accordance with the
SID that is currently in their flightplan. They will descend to the lowest
altitude required by the STAR, and after no further altitude and/or speed
restrictions are listed, will maintain their altitude and speed until
receiving further instructions from ATC.

_Syntax -_ `AAL123 dvs`

### Altitude
_Aliases -_ `climb` / `c` / `descend` / `d` / `altitude` / `a`

_Hotkey -_ `up arrow` / `down arrow` (if "Control Method" setting = "Arrow Keys")

_Information -_ This command tells the specified plane the altitude, in
hundreds of feet (flight levels), it should travel to. This means that when
writing altitudes you would drop the last two zeros. For example, 3,000ft =
"30", 8,300ft = "83", 10,000ft = "100", and FL180 (18,000ft) = "180".
Airplanes will not descend below 1000 feet (unless locked on ILS).

_Syntax -_ `AAL123 c [alt]`

### Takeoff
_Aliases -_ `takeoff`, `to`, `cto`

_Hotkey -_ `numpad /`

_Information -_ This command clears the specified plane for takeoff. They
will climb to the altitude specified, or in accordance with a SID if told
previously to "climb via the SID". If neither has happened, they will ask
for an altitude assignment before they agree to take off.

_Syntax -_ `AAL123 cto`

### Heading
_Aliases -_ `heading` / `h` / `turn` / `t`

_Shortkeys -_ `fh` / `left arrow` / `right arrow` (if "Control Method" setting = "Arrow Keys")

_Information -_ This command sets the target heading; up (north) is 360,
right (east) is 090, down (south) is 180, and left (west) is 270. Of course
you can use any angle in between these as well. If the heading is set
before takeoff, the aircraft will turn to that heading after takeoff. You
can force the aircraft to reach the heading by turning left or right by
inserting `l` or `r` before the new heading, as demonstrated below.

_Syntax -_ `AAL123 fh[hdg]` or `AAL123 (rightarrow)[hdg]` or `AAL123 t r [hdg]`

### Speed
_Aliases -_ `speed` / `slow` / `sp`

_ShortKey -_ `numpad +` / `numpad -`

_Information -_ This command sets the target speed; aircraft will stay within
their safe speeds if you tell them to fly faster or slower than they are able
to. It takes some time to increase and reduce speed. Remember that speed is
always expressed in knots.

_Syntax -_ `AAL123 -[spd]` or `AAL123 +[spd]`

### Land
_Aliases -_ `ils` / `i` / `land` / `l`

_Shortkey -_ `numpad *`

_Information -_ This command clears the aircraft to land on a runway. The
aircraft's strip on the right will show either "intercept" if it's still
trying to intercept the localizer. Once established, it will show "on ILS"
and the aircraft will automatically fly down the runway centerline, descend,
and land.

_Syntax -_ `AAL123 i [rwy]`

### Reroute
_Aliases -_ `reroute`, `rr`

_Information -_ This command allows you to wipe out the aircraft's current
route, and assign a new route of your choosing. This is similar to the `route`
command, but this command will allow you to *change the entire route*, while the
other is meant for specifying a route to follow to join a later point in the
aircraft's flight plan. Note that the route uses dot format:

>Note: Input data needs to be provided with single dots connecting all procedurally-
linked points (eg KSFO.OFFSH9.SXC or SGD.V87.MOVER), and all other points that will
be simply a fix direct to another fix need to be connected with double-dots
(eg HLI..SQS..BERRA..JAN..KJAN).

Full Route Example: `KSEA.HAROB5.ERAVE.Q1.ETCHY..MLBEC.BDEGA2.KSFO`

_Syntax -_ `AAL123 rr [route]`

### Route
_Aliases -_ `route`

_Information -_ This command instructs aircraft to follow a user-provided "route", typically
one that is along an airway, approach, SID, STAR, other published procedure,
or a series of fixes. This is similar to the `reroute`/`rr` command, but this
command will allow you to "insert" a route that connects with the route
they're currently flying. Note that the route uses dot format:

>Note: Input data needs to be provided with single dots connecting all
procedurally-linked points (eg KSFO.OFFSH9.SXC or SGD.V87.MOVER), and all
other points that will be simply a fix direct to another fix need to be
connected with double-dots (eg HLI..SQS..BERRA..JAN..KJAN).

An example would be if an aircraft filed to take a particular airway, and
you needed them to take a different one. Additionally, if the current route
*and* the user-provided route share a common point, the routes are considered
to have "continuity", and the FMS will remove the intermediate fixes. This
is demonstrated below:
Current Route: `BAM..CUTVA..LLC..FMG..BINNZ..HETUX..CHOIR..NEWPI..LKV.HAWKZ4.KSEA`
Command run: `AAL123 route FESKO..RUFUS..CHOIR`
Resulting route: `FESKO..RUFUS..CHOIR..NEWPI..LKV.HAWKZ4.KSEA`

Thus, since the routes have continuity at CHOIR, we are able to give shortcuts and/or
route extensions without needing to restate the whole route, as with the `rr` command.
In the case of the above example, the aircraft would immediately turn direct to `FESKO`,
join the specified route to `CHOIR`, and continue via last routing cleared.

Partial Route Example: `WHITE.J209.ORF` or `FESKO..RUFUS..CHOIR` or `KSEA.MTN7.ELN..HAMUR.J12.DNJ`

_Syntax -_ `AAL123 route [route]`

### Say Route
_Aliases -_ `sr`

_Information -_ With the capability to edit the route, you obviously will
need a way to know what their current route is. Typically, this is displayed
in the flight progress strip. However, to preserve screen space, you will
instead have to check the route by running this command, and the route will
print out above the command bar.

_Syntax -_ `AAL123 sr`

### Fix
_Aliases -_ `f` / `fix` / `track`

_Information -_ This command instructs the aircraft to fly direct to a fix
or list of fixes before proceeding to the next point on their currently
assigned route. This method is neither realistic nor preferred, thus, you
should probably use the more powerful `route` or `rr` commands.

_Syntax -_ `AAL123 f [fixname]`

### "Proceed Direct"
_Aliases -_ `direct` / `pd` / `dct`

_Information -_ This command instructs the aircraft to go direct to a
navigational fix, taking a shortcut. For example, if an aircraft is flying
to fixes [A, B, C], issuing the command "pd B" will cause the aircraft
to go to B, then C. After flying past the last fix, the aircraft will
continue flying straight.

_Syntax -_ `AAL123 pd [fixname]`

### Abort
_Aliases -_ `abort`

_Information -_ Instructs the aircraft to abort the current operation.
Currently, only landings, taxiing, and fix navigation can be aborted.

_Syntax -_ `AAL123 abort`

### Hold
_Aliases -_ `hold`

_Information -_ This command instructs the aircraft to enter a holding
pattern until further notice. The direction (left/right) may be specified,
as well as the leg length (in minutes), as well as the fix to hold over.
But you may also omit those specifications, in which case, the aircraft
will enter a standard holding pattern over their present position (right
turns, 1 minute legs). To escape a hold, just set a new heading.

_Parameters -_ Specify the direction of turns during the hold with `right`
or `left`, the leg length, with `[time]min`, and the fix to hold over
with simply `[fixname]`. Any combination of these arguments provided in
any order is acceptable, as long as the command `hold` comes first.

_Syntax -_ `AAL123 hold [fixname] [left|right] [leg_time]min` or `AAL123 hold`

### Move Data Block
_Aliases -_ `` ` (backtick) ``

_Information -_ If aircraft data blocks are overlapping, it can be tough to
tell which aircraft is which. And on real ATC systems, moving the data block
is sometimes used by controllers to indicate the status of the aircraft, in
reference to whether or not they have been told to do something yet (for
instance, approach might move all the blocks down for a/c that have been
switched to tower frequency). In this sim, you can shift it in any of the 8
subcardinal directions, in reference to their relative position on the numpad:
`(8:N, 9:NE, 6:E, 3:SE, 2:S, 1:SW, 4:W, 7:NW)`. Additionally, position `5` can
be used to "shortstem" the aircraft, which puts the data block right on top of
the aircraft's position symbol.

_Syntax -_ ``AAL123 `2``


text:
ActiveRecord::Schema.define(version: 20150928042743) do

  create_table "movies", force: :cascade do |t|
    t.string   "title"
    t.text     "description"
    t.datetime "watched_at"
    t.integer  "scheduled_for"
    t.integer  "thing_id"
    t.integer  "rt_id"
    t.string   "rt_poster_profile",  default: "http://d3biamo577v4eu.cloudfront.net/static/images/redesign/poster_default.gif"
    t.string   "rt_poster_thumb",    default: "http://d3biamo577v4eu.cloudfront.net/static/images/redesign/poster_default.gif"
    t.datetime "watched_in"
    t.integer  "user_id"
    t.integer  "release_year"
    t.integer  "critics_score"
    t.string   "mpaa_rating"
    t.string   "rt_poster_detailed"
    t.string   "rt_poster_original"
    t.text     "rt_synopsis"
    t.string   "imdb_id"
    t.string   "rt_link"
    t.integer  "runtime"
    t.string   "director",           default: "--- []\n"
    t.string   "cast",               default: "--- []\n"
  end

  create_table "things", force: :cascade do |t|
    t.string   "name"
    t.datetime "date"
    t.string   "location"
    t.integer  "movie_limit"
  end

end


text:
title: 'NBC New York: Bill''s Books—Top 5 Books of 2017'
date: 2017-12-31 12:00:00
categories: ["Media"]
tags:
  - Reviews
  - News
  - Video
attribution: NBC New York
link_to_original: >-
  https://www.nbcnewyork.com/news/local/Here-Are-Bill-Goldsteins-Book-Choices-for-Dec-29-467398533.html
description:
---

Bill Goldstein selects Pachinko in his Top 5 Books of 2017 in NBC New York's Bill's Books. To see the video, please click the link.


text:
includeFile("modernizr.js");
includeFile("ie8/html5shiv-printshiv.js");
includeFile("ie8/respond.js");
includeFile("ie8/jquery-1.11.1.js");
includeFile("twibs-base.js");
Modernizr.load({
    test: Modernizr.input.placeholder,
    nope: [
        '/inc/polyfills/jquery.placeholder.js'
    ]
});


text:
package software.amazon.awssdk.core.internal.interceptor;

import static software.amazon.awssdk.core.HttpChecksumConstant.AWS_CHUNKED_HEADER;
import static software.amazon.awssdk.core.HttpChecksumConstant.CONTENT_SHA_256_FOR_UNSIGNED_TRAILER;
import static software.amazon.awssdk.http.Header.CONTENT_LENGTH;

import java.io.InputStream;
import java.util.Optional;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.ClientType;
import software.amazon.awssdk.core.HttpChecksumConstant;
import software.amazon.awssdk.core.checksums.ChecksumSpecs;
import software.amazon.awssdk.core.checksums.SdkChecksum;
import software.amazon.awssdk.core.interceptor.Context;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.interceptor.ExecutionInterceptor;
import software.amazon.awssdk.core.internal.io.AwsChunkedEncodingInputStream;
import software.amazon.awssdk.core.internal.io.AwsUnsignedChunkedEncodingInputStream;
import software.amazon.awssdk.core.internal.util.HttpChecksumResolver;
import software.amazon.awssdk.core.internal.util.HttpChecksumUtils;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.http.ContentStreamProvider;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.utils.IoUtils;

/**
 * Interceptor that will add Flexible Checksum to the Content Trailer for Sync Clients.
 * The Flexible checksum is added  only if following conditions are met
 *

 * 1. Checksum is not already calculated.
 * 2. Unsigned payload.
 * 3. Request has streaming payload.
 * 4. If Request has Algorithm checksum mentioned.
 *

 *
 */
@SdkInternalApi
public final class SyncHttpChecksumInTrailerInterceptor implements ExecutionInterceptor {

    @Override
    public Optional<RequestBody> modifyHttpContent(Context.ModifyHttpRequest context,
                                                   ExecutionAttributes executionAttributes) {
        ChecksumSpecs checksumSpecs =
            HttpChecksumUtils.checksumSpecWithRequestAlgorithm(executionAttributes).orElse(null);

        if (!shouldAddTrailerBasedChecksumInRequest(context, executionAttributes, checksumSpecs)) {
            return context.requestBody();
        }

        RequestBody requestBody = context.requestBody().get();
        ChecksumCalculatingStreamProvider streamProvider =
            new ChecksumCalculatingStreamProvider(requestBody.contentStreamProvider(), checksumSpecs);

        long checksumContentLength = AwsUnsignedChunkedEncodingInputStream.calculateChecksumContentLength(
            checksumSpecs.algorithm(), checksumSpecs.headerName());

        return Optional.of(
            RequestBody.fromContentProvider(
                streamProvider,
                AwsUnsignedChunkedEncodingInputStream.calculateStreamContentLength(
                    requestBody.optionalContentLength().orElse(0L), AwsChunkedEncodingInputStream.DEFAULT_CHUNK_SIZE)
                + checksumContentLength,
                requestBody.contentType()));
    }

    private static boolean shouldAddTrailerBasedChecksumInRequest(Context.ModifyHttpRequest context,
                                                                  ExecutionAttributes executionAttributes,
                                                                  ChecksumSpecs checksumSpecs) {
        return checksumSpecs != null
               && context.requestBody().isPresent()
               && HttpChecksumUtils.isTrailerBasedChecksumForClientType(
                   executionAttributes,
                   context.httpRequest(),
                   ClientType.SYNC, checksumSpecs,
                   context.requestBody().isPresent(),
                   context.requestBody().map(requestBody -> requestBody.contentStreamProvider() != null).orElse(false));
    }

    @Override
    public SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) {

        ChecksumSpecs checksumSpecs =
            HttpChecksumUtils.checksumSpecWithRequestAlgorithm(executionAttributes).orElse(null);

        if (!shouldAddTrailerBasedChecksumInRequest(context, executionAttributes, checksumSpecs)) {
            return context.httpRequest();
        }

        ChecksumSpecs checksum = HttpChecksumResolver.getResolvedChecksumSpecs(executionAttributes);
        long checksumContentLength = AwsUnsignedChunkedEncodingInputStream.calculateChecksumContentLength(
            checksum.algorithm(), checksum.headerName());
        long originalContentLength = context.requestBody().get().optionalContentLength().orElse(0L);
        return context.httpRequest().copy(
            r -> r.putHeader(HttpChecksumConstant.HEADER_FOR_TRAILER_REFERENCE, checksum.headerName())
                  .putHeader("Content-encoding", AWS_CHUNKED_HEADER)
                  .putHeader("x-amz-content-sha256", CONTENT_SHA_256_FOR_UNSIGNED_TRAILER)
                  .putHeader("x-amz-decoded-content-length", Long.toString(originalContentLength))
                  .putHeader(CONTENT_LENGTH,
                             Long.toString(AwsUnsignedChunkedEncodingInputStream.calculateStreamContentLength(
                                 originalContentLength, AwsChunkedEncodingInputStream.DEFAULT_CHUNK_SIZE)
                                           + checksumContentLength)));
    }

    static final class ChecksumCalculatingStreamProvider implements ContentStreamProvider {
        private final ContentStreamProvider underlyingInputStreamProvider;
        private final String checksumHeaderForTrailer;
        private final ChecksumSpecs checksumSpecs;
        private InputStream currentStream;
        private SdkChecksum sdkChecksum;

        ChecksumCalculatingStreamProvider(ContentStreamProvider underlyingInputStreamProvider,
                                          ChecksumSpecs checksumSpecs) {
            this.underlyingInputStreamProvider = underlyingInputStreamProvider;
            this.sdkChecksum = SdkChecksum.forAlgorithm(checksumSpecs.algorithm());
            this.checksumHeaderForTrailer = checksumSpecs.headerName();
            this.checksumSpecs = checksumSpecs;
        }

        @Override
        public InputStream newStream() {
            closeCurrentStream();
            currentStream = AwsUnsignedChunkedEncodingInputStream.builder()
                                                                 .inputStream(underlyingInputStreamProvider.newStream())
                                                                 .sdkChecksum(sdkChecksum)
                                                                 .checksumHeaderForTrailer(checksumHeaderForTrailer)
                                                                 .build();
            return currentStream;
        }

        private void closeCurrentStream() {
            sdkChecksum = SdkChecksum.forAlgorithm(checksumSpecs.algorithm());
            if (currentStream != null) {
                IoUtils.closeQuietly(currentStream, null);
                currentStream = null;
            }
        }
    }
}


text:
module YandexKassa
  class RequestSigner
    def initialize(params = {})
      @cert_file = params.fetch(:cert_file)
      @key_file = params.fetch(:key_file)
    end

    def sign(raw_xml_body)
      OpenSSL::PKCS7.sign(cert_file, key_file, raw_xml_body, [], OpenSSL::PKCS7::NOCERTS).to_pem
    end

    private

    attr_reader :cert_file, :key_file
  end
end


text:
package ru.r2cloud.jradio.detection;

import java.io.EOFException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.jtransforms.fft.FloatFFT_1D;

import ru.r2cloud.jradio.FloatInput;
import ru.r2cloud.jradio.blocks.FIRFilter;
import ru.r2cloud.jradio.blocks.Firdes;
import ru.r2cloud.jradio.blocks.Window;
import ru.r2cloud.jradio.util.CircularArray;

public class PeakDetection {

	private final int numHertzPerPixel;
	private final Float noiseFloorDb;
	private final Integer maxPeaks;
	private final float[] taps = Firdes.lowPass(1.0, 2000, 1000, 100, Window.WIN_HAMMING, 6.76);
	private final FIRFilter filter = new FIRFilter(taps);

	public PeakDetection(int numHertzPerPixel, Float noiseFloorDb, Integer maxPeaks) {
		if (numHertzPerPixel <= 0) {
			throw new IllegalArgumentException("numPixelsPer100Hz should be positive: " + numHertzPerPixel);
		}
		this.numHertzPerPixel = numHertzPerPixel;
		this.noiseFloorDb = noiseFloorDb;
		this.maxPeaks = maxPeaks;
	}

	public List<PeakInterval> process(FloatInput source) throws IOException {
		List<PeakInterval> result = new ArrayList<>();
		int width = (int) (source.getContext().getSampleRate() / numHertzPerPixel);
		FloatFFT_1D fft = new FloatFFT_1D(width);

		float iNormalizationFactor = (float) 1 / width;

		float[] complexBuf = new float[width * 2];
		float[] fftResult = new float[width];
		for (int i = 0; i < fftResult.length; i++) {
			fftResult[i] = Float.NEGATIVE_INFINITY;
		}
		long currentSample = 0;
		float[] temp = new float[fftResult.length - taps.length / 2];
		CircularArray arr = new CircularArray(taps.length);

		while (true) {
			try {
				PeakInterval curInterval = new PeakInterval();
				for (int i = 0; i < complexBuf.length; i += 2) {
					complexBuf[i] = source.readFloat();
					if (source.getContext().getChannels() == 2) {
						complexBuf[i + 1] = source.readFloat();
					} else {
						complexBuf[i + 1] = 0.0f;
					}
				}
				currentSample += width;
				curInterval.setSampleEnd(currentSample);

				fft.complexForward(complexBuf);
				for (int i = 0, j = 0; i < complexBuf.length; i += 2, j++) {
					float real = complexBuf[i] * iNormalizationFactor;
					float img = complexBuf[i + 1] * iNormalizationFactor;
					fftResult[j] = (float) (10.0 * Math.log10((real * real) + (img * img) + 1e-20));
				}

				int length = width / 2;
				int half = taps.length / 2;
				for (int i = 0; i < fftResult.length; i++) {
					// original algorithm swapped 2 halfs of result using array
					// copy and third array.
					// replaced it with juggling with index below
					int index;
					if (i < length) {
						index = length + i;
					} else {
						index = i - length;
					}
					arr.add(fftResult[index]);
					if (i >= half) {
						temp[i - half] = filter.filter(arr);
					}
					fftResult[index] = Float.NEGATIVE_INFINITY;
				}
				temp[0] = temp[1];

				List<Peak> peaksP = PeakDetectionUtil.getPersistentHomology(temp);
				List<Peak> filtered = new ArrayList<>();
				for (Peak cur : peaksP) {
					cur.setValue(temp[cur.getIndex()]);
					cur.setFrequency(numHertzPerPixel * (cur.getIndex() - length));
					boolean valueIsOk = noiseFloorDb == null || cur.getValue() > noiseFloorDb;
					boolean sizeIsOk = maxPeaks == null || filtered.size() < maxPeaks;
					if (valueIsOk && sizeIsOk) {
						filtered.add(cur);
					}
				}
				curInterval.setPeaks(filtered);
				result.add(curInterval);
			} catch (EOFException e) {
				break;
			}
		}
		return result;
	}

}


text:
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
# pragma once
#endif

/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
// is_abstract_class.hpp:
//
//  (C) Copyright 2002 Rani Sharoni (rani_sharoni@hotmail.com) and Robert Ramey
//  Use, modification and distribution is subject to the Boost Software
//  License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//
//  See http://www.boost.org for updates, documentation, and revision history.
//

// Compile type discovery whether given type is abstract class or not.
//
//   Requires DR 337 to be supported by compiler
//   (http://anubis.dkuug.dk/jtc1/sc22/wg21/docs/cwg_active.html#337).
//
//
// Believed (Jan 2004) to work on:
//  - GCC 3.4
//  - VC++ 7.1
//  - compilers with new EDG frontend (Intel C++ 7, Comeau 4.3.2)
//
// Doesn't work on:
//  - VC++6, VC++7.0 and less
//  - GCC 3.3.X and less
//  - Borland C++ 6 and less
//
//
// History:
//  - Originally written by Rani Sharoni, see
//    http://groups.google.com/groups?selm=df893da6.0207110613.75b2fe90%40posting.google.com
//    At this time supported by EDG (Intel C++ 7, Comeau 4.3.2) and VC7.1.
//  - Adapted and added into Boost.Serialization library by Robert Ramey
//    (starting with submission #10).
//  - Jan 2004: GCC 3.4 fixed to support DR337 (Giovanni Bajo).
//  - Jan 2004: modified to be part of Boost.TypeTraits (Pavel Vozenilek).
//  - Nov 2004: Christoph Ludwig found that the implementation did not work with
//              template types and gcc-3.4 or VC7.1, fix due to Christoph Ludwig
//              and John Maddock.
//  - Dec 2004: Added new config macro BOOST_NO_IS_ABSTRACT which causes the template
//              to degrade gracefully, rather than trash the compiler (John Maddock).
//

#include <boost/type_traits/intrinsics.hpp>
#ifndef BOOST_IS_ABSTRACT
#include <boost/static_assert.hpp>
#include <boost/type_traits/detail/yes_no_type.hpp>
#include <boost/type_traits/is_class.hpp>
#include <boost/type_traits/detail/ice_and.hpp>
#ifdef BOOST_NO_IS_ABSTRACT
#include <boost/type_traits/is_polymorphic.hpp>
#endif
#endif
// should be the last #include
#include <boost/type_traits/detail/bool_trait_def.hpp>

namespace boost {
namespace detail{

#ifdef BOOST_IS_ABSTRACT
template <class T>
struct is_abstract_imp
{
   BOOST_STATIC_CONSTANT(bool, value = BOOST_IS_ABSTRACT(T));
};
#elif !defined(BOOST_NO_IS_ABSTRACT)
template<class T>
struct is_abstract_imp2
{
   // Deduction fails if T is void, function type,
   // reference type (14.8.2/2)or an abstract class type
   // according to review status issue #337
   //
   template<class U>
   static type_traits::no_type check_sig(U (*)[1]);
   template<class U>
   static type_traits::yes_type check_sig(...);
   //
   // T must be a complete type, further if T is a template then
   // it must be instantiated in order for us to get the right answer:
   //
   BOOST_STATIC_ASSERT(sizeof(T) != 0);

   // GCC2 won't even parse this template if we embed the computation
   // of s1 in the computation of value.
#ifdef __GNUC__
   BOOST_STATIC_CONSTANT(std::size_t, s1 = sizeof(is_abstract_imp2<T>::template check_sig<T>(0)));
#else
#if BOOST_WORKAROUND(BOOST_MSVC_FULL_VER, >= 140050000)
#pragma warning(push)
#pragma warning(disable:6334)
#endif
   BOOST_STATIC_CONSTANT(std::size_t, s1 = sizeof(check_sig<T>(0)));
#if BOOST_WORKAROUND(BOOST_MSVC_FULL_VER, >= 140050000)
#pragma warning(pop)
#endif
#endif

   BOOST_STATIC_CONSTANT(bool, value =
      (s1 == sizeof(type_traits::yes_type)));
};

template <bool v>
struct is_abstract_select
{
   template <class T>
   struct rebind
   {
      typedef is_abstract_imp2<T> type;
   };
};
template <>
struct is_abstract_select<false>
{
   template <class T>
   struct rebind
   {
      typedef false_type type;
   };
};

template <class T>
struct is_abstract_imp
{
   typedef is_abstract_select< ::boost::is_class<T>::value> selector;
   typedef typename selector::template rebind<T> binder;
   typedef typename binder::type type;

   BOOST_STATIC_CONSTANT(bool, value = type::value);
};

#endif
}

#ifndef BOOST_NO_IS_ABSTRACT
BOOST_TT_AUX_BOOL_TRAIT_DEF1(is_abstract,T,::boost::detail::is_abstract_imp<T>::value)
#else
BOOST_TT_AUX_BOOL_TRAIT_DEF1(is_abstract,T,::boost::detail::is_polymorphic_imp<T>::value)
#endif

} // namespace boost

#include <boost/type_traits/detail/bool_trait_undef.hpp>

#endif //BOOST_TT_IS_ABSTRACT_CLASS_HPP


text:
=head1 LICENSE

Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Copyright [2016-2018] EMBL-European Bioinformatics Institute

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.

=cut

package EnsEMBL::Web::JSONServer::Tools::Blast;

use strict;
use warnings;

use JSON;
use EnsEMBL::Web::BlastConstants qw(MAX_SEQUENCE_LENGTH MAX_NUM_SEQUENCES);
use Bio::EnsEMBL::Registry;
use EnsEMBL::Web::ExtIndex;

use parent qw(EnsEMBL::Web::JSONServer::Tools EnsEMBL::Web::JSONServer::SpeciesSelector);

sub object_type { 'Blast' }

sub json_fetch_sequence {
  my ($self, $on_update) = @_;
  my $hub = $self->hub;
  my $id  = $hub->param('id') or return;
  my @seqs;

  for ($self->_possible_dbs($id)) {
    $on_update->([ $_ ]) if $on_update;
    @seqs = $hub->get_ext_seq($_, {'id' => $id});
    last if @seqs && $seqs[0]{'sequence'};
  }

  return $self->call_js_panel_method($seqs[0]{'sequence'}
    ? ('addSequences', [ join "\n\n", map $_->{'sequence'}, @seqs ])
    : ('showError', [ $seqs[0]{'error'} || "Could not find any sequence for $id." ])
  );
}

sub json_read_file {
  my $self        = shift;
  my $hub         = $self->hub;
  my $cgi         = $hub->input;
  my $max_size    = int(MAX_SEQUENCE_LENGTH() * MAX_NUM_SEQUENCES() * 1.1);
  my $filename    = $cgi->param('query_file');

  if ($filename =~ /\.(fa|txt)$/ && $cgi->uploadInfo($filename)->{'Content-Type'} =~ /^(application|text)/) {

    my $filehandle  = $cgi->upload('query_file');
    my $filecontent = '';

    for ($filehandle->getlines) {
      $filecontent .= $_;
      if (length($filecontent) > $max_size) { # FIXME - find an alternative!
        my $limit = $max_size / 1024;
        my $unit  = 'KB';
        if ($limit > 1024) {
          $limit  = $limit / 1024;
          $unit   = 'MB';
        }
        return {'file_error' => sprintf 'Uploaded file should not be more than %s %s.', int($limit), $unit};
      }
    }

    return {'file' => $filecontent};
  }

  return {'file_error' => sprintf 'Uploaded file should be of type plain text or FASTA.'};
}

sub json_fetch_species {
  my $self = shift;
  my $hub = $self->hub;
  my $sd = $hub->species_defs;
  my $division_json = $sd->ENSEMBL_TAXONOMY_DIVISION;
  my $json = {};
  my $species_info  = $hub->get_species_info;
  my $sp_assembly_map = $sd->SPECIES_ASSEMBLY_MAP;
  my $available_species_map = {};
  map { $available_species_map->{$_} = 1 } keys %$species_info;

  $self->{species_selector_data} = {
    division_json => $division_json,
    available_species => $available_species_map,
    internal_node_select => 1,
    sp_assembly_map => $sp_assembly_map
  };

  my @dyna_tree = $self->create_tree();
  return { json => \@dyna_tree };
}

sub _possible_dbs {
  ## @private
  my ($self, $id) = @_;
  my $hub       = $self->hub;
  my $ext_dbs   = $hub->species_defs->ENSEMBL_EXTERNAL_DATABASES;

  return qw(ENSEMBL)  if $id =~ /^ENS/;
  return qw(CCDS)     if $id =~ /^CCDS/ && exists $ext_dbs->{'CCDS'};

  return qw(REST ENSEMBL PUBLIC);
}

1;