text:
import sys
from Bio.Blast import NCBIXML
#Usage, opens an outfile and then parses any number of .xml files into that outfile, printing all hits
#parse_blastn.py outfile.txt anynumberofinfiles.xml
OUT = open(sys.argv[1], 'w')

OUT.write("Query Name\tQuery Length\tSubject Name\tSubject Length\tAlignment Length\tQuery Start\tQuery End\tSubject Start\tSubject End\tQuery Sequence\tSubject Sequence\tHsp Score\tHsp Expect\tHsp Identities\tPercent Match\tNumber_of_gaps")
for xml_file in sys.argv[2:]:
	result_handle = open(xml_file)
	blast_records = NCBIXML.parse(result_handle)
	for rec in blast_records:
		for alignment in rec.alignments:
				for hsp in alignment.hsps:
					OUT.write('\n'+ str(rec.query) + '\t' + str(rec.query_length) + '\t' + str(alignment.title) + '\t' + str(alignment.length) + '\t' + str(hsp.align_length) + '\t' + str(hsp.query_start) + '\t' + str(hsp.query_end) + '\t' + str(hsp.sbjct_start) + '\t' + str(hsp.sbjct_end) + '\t' + str(hsp.query) + '\t' + str(hsp.sbjct) + '\t' + str(hsp.score) + '\t' + str(hsp.expect) + '\t' + str(hsp.identities) + '\t' + str(float(hsp.identities)/int(hsp.align_length)) + '\t' + str(hsp.gaps))


text:
<?php

final class DiffusionRepositorySubversionManagementPanel
  extends DiffusionRepositoryManagementPanel {

  const PANELKEY = 'subversion';

  public function getManagementPanelLabel() {
    return pht('Subversion');
  }

  public function getManagementPanelOrder() {
    return 1000;
  }

  public function shouldEnableForRepository(
    PhabricatorRepository $repository) {
    return $repository->isSVN();
  }

  public function getManagementPanelIcon() {
    $repository = $this->getRepository();

    $has_any =
      $repository->getDetail('svn-subpath') ||
      $repository->getDetail('svn-layout') != PhabricatorRepository::LAYOUT_NONE ||
      $repository->getDetail('svn-trunk-folder') ||
      $repository->getDetail('svn-branches-folder') ||
      $repository->getDetail('svn-tags-folder');

    if ($has_any) {
      return 'fa-folder';
    } else {
      return 'fa-folder grey';
    }
  }

  protected function getEditEngineFieldKeys() {
    return array(
      'importOnly', 'layout', 'trunk_folder', 'branches_folder', 'tags_folder',
    );
  }

  public function buildManagementPanelCurtain() {
    $repository = $this->getRepository();
    $viewer = $this->getViewer();
    $action_list = $this->newActionList();

    $can_edit = PhabricatorPolicyFilter::hasCapability(
      $viewer,
      $repository,
      PhabricatorPolicyCapability::CAN_EDIT);

    $subversion_uri = $this->getEditPageURI();

    $action_list->addAction(
      id(new PhabricatorActionView())
        ->setIcon('fa-pencil')
        ->setName(pht('Edit Properties'))
        ->setHref($subversion_uri)
        ->setDisabled(!$can_edit)
        ->setWorkflow(!$can_edit));

    return $this->newCurtainView($action_list)
      ->setActionList($action_list);
  }

  public function buildManagementPanelContent() {
    $repository = $this->getRepository();
    $viewer = $this->getViewer();

    $view = id(new PHUIPropertyListView())
      ->setViewer($viewer);

    $default_branch = nonempty(
      $repository->getDetail('svn-subpath'),
      phutil_tag('em', array(), pht('Import Entire Repository')));
    $view->addProperty(pht('Import Only'), $default_branch);

    $layout_folders = array(
      $repository->getSubversionTrunkFolder(),
      $repository->getSubversionBranchesFolder(),
      $repository->getSubversionTagsFolder(),);

    switch ($repository->getSubversionLayout()) {
      case PhabricatorRepository::LAYOUT_NONE:
        $svn_layout = pht('None');
        break;

      case PhabricatorRepository::LAYOUT_STANDARD:
        $svn_layout = 'Standard ('.implode(', ', $layout_folders).')';
        break;

      case PhabricatorRepository::LAYOUT_CUSTOM:
        $svn_layout = 'Custom ('.implode(', ', $layout_folders).')';
        break;

      default:
        throw new Exception('Unknown repository layout: '.
          $repository->getSubversionLayout());
    }

    $svn_layout = phutil_tag('em', array(), $svn_layout);
    $view->addProperty(pht('Layout'), $svn_layout);

    return $this->newBox(pht('Subversion'), $view);
  }

}

redpajama_set_name: RedPajamaGithub


text:
{% extends "horizon/common/_modal_form.html" %}
{% load i18n %}

{% block modal-header %}{% trans "Filter Alarms" %}{% endblock %}

{% block modal-body %}

  <form></form>

  <form method="GET" class="form-group" style="width:400px" onsubmit="sendID()" name="form0">

{% trans 'Alarm ID' %}

      {% trans 'Value' %}: <input class="form-control" name="filterID" placeholder="54fdec2f-ae34-4dba-9c85-7b4ad67eea03">
      <button type="submit" class="btn btn-default">{% trans 'Submit' %}</button>
  </form>

  <form method="GET" class="form-group" style="width:400px" onsubmit="sendDimensions()" name="form1">

{% trans 'Dimension(s)' %}

      {% trans 'Key' %}[={% trans 'Value' %}]
      <input class="form-control" name="dimension" placeholder="hostname=devstack, service=mysql" data-toggle="tooltip" data-placement="right" title="Example: hostname=devstack, service=mysql">

      {% trans 'Metric Name' %}: <input class="form-control" name="metric" placeholder="http_status">
      <button type="submit" class="btn btn-default">{% trans 'Submit' %}</button>
  </form>

{% endblock %}

{% block modal-footer %}
{% endblock %}


text:
import { ADD_TODO, COMPLETE_TODO, DEL_TODO } from '../actions';

function getId(todos) {
    return todos.reduce((maxId, todo) => {
        return Math.max(todo.id, maxId);
    }, -1) + 1;
}

// reducers 的功能就是針對這個唯一的 Store 內的 State 的部分內容進行更新
// Reducer 接收舊 state 與 action 並回傳一個新的 state
const todoReducer = function todoReducer(todos = [], action) {
    switch (action.type) {
    case ADD_TODO:
        // console.log(todos)
        return [{
            text: action.text,
            completed: false,
            id: getId(todos)
        }, ...todos];

    case COMPLETE_TODO:
        return todos.map((todo) => {
            return todo.id === action.id ?
                Object.assign({}, todo, { completed: !todo.completed }) : todo;
        });

    case DEL_TODO:
        return todos.filter((todo) => {
            return todo.id !== action.id;
        });
    default:
        return todos;
    }
};

export default todoReducer;


text:
namespace Tx
{
    namespace Gui
    {
        template<class T = RectangleShape>
        class Button : public Widget<T>,
                       public TextComponent
        {
            public:
                Button( Uint32 width,
                        Uint32 height,
                        const std::string& text = "Button",
                        Int32 x = 0,
                        Int32 y = 0,
                        const std::string& font = "Arial",
                        Int32 fontSize = 16 );
                ~Button();

                bool isTextCentered() const;

                void setPositionX( Int32 x );
                void setPositionY( Int32 y );
                void setPosition( Int32 x,
                                  Int32 y );

                void setSize( Uint32 size );
                void setFont( const std::string& fontName );
                void setText( const std::string& text );

                void setTextCentered( bool centered = true );

            protected:
                virtual void setState( WidgetState state ) override;
                virtual void draw( sf::RenderTarget& target,
                                   sf::RenderStates states ) const override;

           private:
               void updateTextPosition();

           private:
               bool m_isTextCentered;
        };
    } // namespace Gui
} // namespace Tx

#include <Gui/Button.inl>

#endif // HEADER_BUTTON_HPP


text:
title: Community Demo May 22, 2019
author: Dana Walker
tags:
  - demo
---
The Community Demo is available on the [Pulp YouTube Channel](https://www.youtube.com/channel/UCI43Ffs4VPDv7awXvvBJfRQ). See the agenda below.

<iframe width="560" height="315" src="https://www.youtube.com/embed/EuDgLX8G_wg" frameborder="0" allowfullscreen></iframe>

[Community Update (dawalker)](http://www.youtube.com/watch?v=EuDgLX8G_wg&t=0m45s)

[Syncing Debian content lazily (bmbouter) (3.0)](http://www.youtube.com/watch?v=EuDgLX8G_wg&t=2m26s)

[Docker lazy sync (dkliban) (3.0)](http://www.youtube.com/watch?v=EuDgLX8G_wg&t=5m55s)

[Booting a Debian VM headlessly from Debian content synced lazily from pulp_deb (bmbouter) (3.0)](http://www.youtube.com/watch?v=EuDgLX8G_wg&t=12m54s)


text:
/***
This file is going to contain all the main code to build levels for the game.
-Garrett
***/
var utils = require("./utils.js");
//Prototype for a new map.  Will contain all the data that a map for a level will need.
function MapProto(){
	//A container to drop all of the map in
    this.container = new createjs.Container();
    //Number of pixels in the map based on height and width
    this.width = 3000;
    this.height = 3000;
    //arbitrary starting x/y location
    this.container.x = this.container.y = 0;
    //The height and width of tiles.
    this.tileSize = 30;
    //A 2d array that will contain all of the actual map tiles
    this.tiles = new Array(this.width / this.tileSize); //currently 100
    for (var i = 0; i <= this.width / this.tileSize; i++)
        this.tiles[i] = new Array(this.height / this.tileSize); //currently 50
    this.rooms = [];
    this.openTiles = [];
    //A function that will tell what tile the given X,Y are in.
    this.getLocation = function(x, y) {
    	var tileX = Math.floor(x / this.tileSize);
        var tileY = Math.floor(y / this.tileSize);

        return  this.tiles[tileX][tileY];
	};
    this.randomOpenTile = function(){
        return this.openTiles[utils.getRandomInt(0,this.openTiles.length)];
    };
}
//Prototype for a new room.  Will contain all the data for an individual room.
function RoomProto(map){
	//pick a random x,y coordinate for the room's top left corner that's not too close to the edge.
    this.roomTLCornerX = utils.getRandomInt(0,(map.tiles.length-7));
    this.roomTLCornerY = utils.getRandomInt(0,(map.tiles[0].length-7));
    //stuff
    var maxWidth, maxHeight;
    this.width;
    this.height;
    //Set maximum width and height for the room
    if(this.roomTLCornerX > map.tiles.length - 25){
        maxWidth = map.tiles.length - this.roomTLCornerX+1;
    } else maxWidth = 25;
    if(this.roomTLCornerY > map.tiles[0].length - 25){
        maxHeight = map.tiles[0].length - this.roomTLCornerY+1;
    } else maxHeight = 25;
    //Randomly select a width and height for the room within the given bounds
    this.roomWidth = utils.getRandomInt(5,maxWidth);
    this.roomHeight = utils.getRandomInt(5,maxHeight);
    //Iterate through all the maximum values and create walls, and fill in the rest with floor.
    for(var x = 0; x < map.tiles.length; x++){
        for (var y = 0; y < map.tiles[x].length; y++){
            if (x >= this.roomTLCornerX && x <= this.roomTLCornerX + this.roomWidth && y >= this.roomTLCornerY && y <= this.roomTLCornerY + this.roomHeight ){
                if ( x == this.roomTLCornerX || x == this.roomTLCornerX + this.roomWidth || y == this.roomTLCornerY || y == this.roomTLCornerY + this.roomHeight ){
                    map.tiles[x][y] = new TileProtos.Wall();
                }else map.tiles[x][y] = new TileProtos.Floor();
            }
        }
    }

}
//An associative array that contains all of the prototypes for the tile types.
var TileProtos = {
	Generic: function(){
		this.name = "none";
		this.isPassable = false;
		this.blocksVision = false;
		this.image = null;
		this.mapX;
		this.mapY;
		this.neighborTiles = {};
        this.viewableTiles = [];
        this.f = 0;
        this.g = 0;
        this.h = 0;
        this.parentTile;
	},
	Floor: function(){
		this.name = "floor";
        this.isPassable = true;
        this.blocksVision = false;
        this.image = new createjs.Bitmap("sprite_sheets/floor.png");
	},
	Wall: function(){
		this.name = "wall";
        this.isPassable = false;
        this.blocksVision = true;
        this.image = new createjs.Bitmap("sprite_sheets/wall.png");
	}
};
TileProtos.Floor.prototype = new TileProtos.Generic();
TileProtos.Wall.prototype = new TileProtos.Generic();
//This is used to connect two points with hallways
function makeCorridor(map,startx,starty,endx,endy){
	var r;

    if(startx < endx){
        for(r = startx; r <= endx; r++){
            map.tiles[r][starty] = new TileProtos.Floor();
            if(map.tiles[r+1][starty+1] === undefined)
                map.tiles[r+1][starty+1] = new TileProtos.Wall();
            if(map.tiles[r+1][starty-1] === undefined)
                map.tiles[r+1][starty-1] = new TileProtos.Wall();
        }
    }else {
       for(r = endx; r <= startx; r++){
            map.tiles[r][starty] = new TileProtos.Floor();
            if(map.tiles[r-1][starty+1] === undefined)
                map.tiles[r-1][starty+1] = new TileProtos.Wall();
            if(map.tiles[r-1][starty-1] === undefined)
                map.tiles[r-1][starty-1] = new TileProtos.Wall();
        }
    }
    if(starty < endy){
        for(r = starty; r <= endy; r++){
            map.tiles[endx][r] = new TileProtos.Floor();
            if(map.tiles[endx+1][r-1] === undefined)
                map.tiles[endx+1][r-1] = new TileProtos.Wall();
            if(map.tiles[endx-1][r-1] === undefined)
                map.tiles[endx-1][r-1] = new TileProtos.Wall();
        }
    }else {
       for(r = endy; r <= starty; r++){
            map.tiles[endx][r] = new TileProtos.Floor();
            if(map.tiles[endx+1][r+1] === undefined)
                map.tiles[endx+1][r+1] = new TileProtos.Wall();
            if(map.tiles[endx-1][r+1] === undefined)
                map.tiles[endx-1][r+1] = new TileProtos.Wall();
        }
    }

}
//Add all of the tiles to a container to be rendered.
function renderMap(map){
	for (var r = 0; r <= map.tiles.length; r++) {
        if (map.tiles[r] !== undefined) {
            for (var b = 0; b <= map.tiles[r].length; b++) {
                if (map.tiles[r][b] !== undefined) {
                    map.tiles[r][b].image.x = r * map.tileSize;
                    map.tiles[r][b].image.y = b * map.tileSize;
                    map.container.addChild(map.tiles[r][b].image);
                }
            }
        }
    }
}
//This function will fine all of the tile's x & y Coordinates
function findTileMapCoord(map){
	var r,b; //iterators

	for(r = 0; r < map.tiles.length; r++){
		for(b=0; b < map.tiles[r].length; b++){
			if(map.tiles[r][b] !== undefined){
				map.tiles[r][b].mapX = r;
				map.tiles[r][b].mapY = b;
                map.tiles[r][b].image.alpha = 0;

				if(map.tiles[r][b].isPassable){
                    map.openTiles.push(map.tiles[r][b]);
                    findNeighborTiles(map,r,b);
                    //Potentially can calculate this ahead of time, instead of on the fly
                    //findViewableTiles(map.tiles[r][b],map);
                }

			}
		}
	}
}
//This function will find every valid tile's adjacent tiles to help with AI pathfinding eventually
function findNeighborTiles(map,xCoOrd, yCoOrd){
    var north = yCoOrd - 1;
    var south = yCoOrd + 1;
    var east = xCoOrd + 1;
    var west = xCoOrd - 1;

    if(isValidNeighbor(map.tiles[xCoOrd][south]))
        map.tiles[xCoOrd][yCoOrd].neighborTiles["south"] = map.tiles[xCoOrd][south];
    if(isValidNeighbor(map.tiles[xCoOrd][north]))
        map.tiles[xCoOrd][yCoOrd].neighborTiles["north"] = map.tiles[xCoOrd][north];
    if(isValidNeighbor(map.tiles[east][yCoOrd]))
        map.tiles[xCoOrd][yCoOrd].neighborTiles["east"] = map.tiles[east][yCoOrd];
    if(isValidNeighbor(map.tiles[west][yCoOrd]))
        map.tiles[xCoOrd][yCoOrd].neighborTiles["west"] = map.tiles[west][yCoOrd];
    if(isValidNeighbor(map.tiles[east][south]))
        map.tiles[xCoOrd][yCoOrd].neighborTiles["southeast"] = map.tiles[east][south];
    if(isValidNeighbor(map.tiles[west][south]))
        map.tiles[xCoOrd][yCoOrd].neighborTiles["southwest"] = map.tiles[west][south];
    if(isValidNeighbor(map.tiles[east][north]))
        map.tiles[xCoOrd][yCoOrd].neighborTiles["northeast"] = map.tiles[east][north];
    if(isValidNeighbor(map.tiles[west][north]))
        map.tiles[xCoOrd][yCoOrd].neighborTiles["northwest"] = map.tiles[west][north];
    //return whether current tile is a valid neighbor
    function isValidNeighbor(currentTile){
        if(currentTile !== undefined){
            if(currentTile.isPassable){
                return true;
            } else return false;
        }else return false;
    }
}
//This function is of stuff I haven't figured out a good way to do yet
//Was going to use to calculate viewable area from each tile on map load rather than on the fly
function findViewableTiles(povTile,map){
    /*
    var viewDistTiles = 10;
    var viewDist = viewDistTiles*10;
    var viewPolygonTiles = [];
    var viewPolygonPoints = [];

    var viewTLCornerX = povTile.mapX - viewDistTiles;
    viewTLCornerX = (viewTLCornerX < 0)? 0 : viewTLCornerX;
    var viewTLCornerY = povTile.mapY - viewDistTiles;
    viewTLCornerY = (viewTLCornerY < 0)? 0 : viewTLCornerY;

    var lineOfSight = function(povTile,map,degree,viewDist){
        var nextX = Math.cos(degree * (Math.PI / 180));
        var nextY = Math.sin(degree * (Math.PI / 180));
        var currentX = povTile.image.x;
        var currentY = povTile.image.y;
        var currentTile = map.getLocation(currentX,currentY);
        //var counter = 0;
        //var viewDist = 260;
        var currentDist = 0;
        var done = false;

        while(!done){

            //povTile.viewableTiles.push(currentTile);
            if(currentTile.blocksVision)
                return currentTile;
            currentX += nextX;
            currentY += nextY;
            if(map.getLocation(currentX,currentY) === undefined){
                return currentTile;
            }else{
               currentTile = map.getLocation(currentX,currentY);
            }
            currentDist = Math.sqrt(Math.pow(currentX-povTile.image.x,2)+Math.pow(currentY-povTile.image.y,2));
            if(currentDist > viewDist)
                return currentTile;

        }
    };

    //update it with the newly seen tiles
    for (var r = 0; r < 360; r++){
        var endTile = lineOfSight(povTile,map, r,viewDist);
        if (r == 0 || endTile !== viewPolygonTiles[viewPolygonTiles.length-1])
            viewPolygonTiles.push(endTile);
    }
    for (var b = 0; b < viewPolygonTiles.length; b++){
        viewPolygonPoints.push({x:viewPolygonTiles[b].mapX, y:viewPolygonTiles[b].mapY});
    }
    for (var testX = viewTLCornerX; testX < viewTLCornerX+viewDistTiles*2; testX++){
        for (var testY = viewTLCornerY; testY < viewTLCornerY+viewDistTiles*2; testY++){
            if(map.tiles[testX][testY] !== undefined){
               var testPoint = {
                    x : testX,
                    y : testY
                }
                if(utils.pointInPolygon(viewPolygonPoints, testPoint)){
                    povTile.viewableTiles.push(map.tiles[testX][testY]);
                }
            }

        }
    }

*/

}
//This function will take care of all the map generating.
module.exports.generateMap = function() {
	var map = new MapProto();
	//Randomly decide the number of rooms
    var numRooms = utils.getRandomInt(10,20);
    //Make the rooms
    for (var r=0; r < numRooms; r++)
        map.rooms.push(new RoomProto(map));
    //Connect the rooms
    var corridorStartX,corridorStartY,corridorEndX,corridorEndY;
    for (var b=1; b < numRooms; b++){
    	corridorStartX = Math.floor(map.rooms[b-1].roomTLCornerX+map.rooms[b-1].roomWidth/2);
    	corridorStartY = Math.floor(map.rooms[b-1].roomTLCornerY+map.rooms[b-1].roomHeight/2);
    	corridorEndX = Math.floor(map.rooms[b].roomTLCornerX+map.rooms[b].roomWidth/2);
    	corridorEndY = Math.floor(map.rooms[b].roomTLCornerY+map.rooms[b].roomHeight/2);

        makeCorridor(map, corridorStartX, corridorStartY, corridorEndX, corridorEndY);
    }
    //Add all these shnazzy new tiles to the map container
    renderMap(map);
    //Now we find all of the tile's meta data.
    findTileMapCoord(map);
    //Cache the map, once I figure out a way to do that with line of sight
    //map.container.cache(0,0,map.width,map.height);
    //Send back the shiny new map
    return map;
};


text:
#include "config.h"

#if ENABLE(WML)
#include "WMLPElement.h"

#include "Attribute.h"
#include "CSSPropertyNames.h"
#include "CSSValueKeywords.h"
#include "Document.h"
#include "HTMLNames.h"
#include "NodeList.h"
#include "WMLNames.h"

namespace WebCore {

using namespace WMLNames;

WMLPElement::WMLPElement(const QualifiedName& tagName, Document* doc)
    : WMLElement(tagName, doc)
{
}

PassRefPtr<WMLPElement> WMLPElement::create(const QualifiedName& tagName, Document* document)
{
    return adoptRef(new WMLPElement(tagName, document));
}

bool WMLPElement::mapToEntry(const QualifiedName& attrName, MappedAttributeEntry& result) const
{
    if (attrName == HTMLNames::alignAttr) {
        result = eBlock; // We can share with DIV here.
        return false;
    }

    return WMLElement::mapToEntry(attrName, result);
}

void WMLPElement::parseMappedAttribute(Attribute* attr)
{
    if (attr->name() == HTMLNames::alignAttr) {
        const AtomicString& value = attr->value();
        if (equalIgnoringCase(value, "middle") || equalIgnoringCase(value, "center"))
            addCSSProperty(attr, CSSPropertyTextAlign, CSSValueWebkitCenter);
        else if (equalIgnoringCase(value, "left"))
            addCSSProperty(attr, CSSPropertyTextAlign, CSSValueWebkitLeft);
        else if (equalIgnoringCase(value, "right"))
            addCSSProperty(attr, CSSPropertyTextAlign, CSSValueWebkitRight);
        else
            addCSSProperty(attr, CSSPropertyTextAlign, value);
    } else if (attr->name() == modeAttr) {
        m_mode = attr->value();
        if (m_mode == "wrap")
            addCSSProperty(attr, CSSPropertyWordWrap, CSSValueBreakWord);
        else if (m_mode == "nowrap")
            addCSSProperty(attr, CSSPropertyWhiteSpace, CSSValueNowrap);
    } else
        WMLElement::parseMappedAttribute(attr);
}

void WMLPElement::insertedIntoDocument()
{
    WMLElement::insertedIntoDocument();

    // If not explicitly specified, the linewrap mode is identical to
    // the line-wrap mode of the previous paragraph in the text flow of
    // a card. The default mode for the first paragraph in a card is wrap.
    if (!m_mode.isEmpty())
        return;

    RefPtr<NodeList> nodeList = document()->getElementsByTagName("p");
    if (!nodeList)
        return;

    unsigned length = nodeList->length();
    if (length < 2)
        return;

    // Assure we're the last inserted paragraph element
    // This only works while parsing, otherwhise this statement is never true.
    if (nodeList->item(length - 1) != this)
        return;

    WMLPElement* lastParagraph = static_cast<WMLPElement*>(nodeList->item(length - 2));
    ASSERT(lastParagraph);

    String lastMode = lastParagraph->getAttribute(modeAttr);
    if (lastMode.isEmpty() || lastMode == "wrap") // Default value, do nothing.
        return;

    setAttribute(modeAttr, lastMode);
}

}

#endif


text:
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')

describe OpenGraph do
  describe "#initialize" do
    context "with invalid src" do
      it "should set the url to the same as src" do
        og = OpenGraph.new("invalid")
        og.src.should == "invalid"
        og.title.should == nil
        og.url.should == "invalid"
      end
    end

    context "with redirect_limit in options hash" do
      it "should pass redirect_limit to RedirectFollower" do
        RedirectFollower.should_receive(:new).with("http://test.host", redirect_limit: 20)

        og = OpenGraph.new("http://test.host", redirect_limit: 20)
      end
    end

    context "with no fallback" do
      it "should get values from opengraph metadata" do
        response = double(body: File.open("#{File.dirname(__FILE__)}/../view/opengraph.html", 'r') { |f| f.read })
        RedirectFollower.stub(:new) { double(resolve: response) }

        og = OpenGraph.new("http://test.host", false)
        og.src.should == "http://test.host"
        og.title.should == "OpenGraph Title"
        og.type.should == "article"
        og.url.should == "http://test.host"
        og.description.should == "My OpenGraph sample site for Rspec"
        og.images.should == ["http://test.host/images/rock1.jpg", "http://test.host/images/rock2.jpg"]
        og.original_images.should == ["http://test.host/images/rock1.jpg", "/images/rock2.jpg"]
        og.metadata.should == {
          title: [{_value: "OpenGraph Title"}],
          type: [{_value: "article"}],
          url: [{_value: "http://test.host"}],
          description: [{_value: "My OpenGraph sample site for Rspec"}],
          image: [
            {
              _value: "http://test.host/images/rock1.jpg",
              width: [{ _value: "300" }],
              height: [{ _value: "300" }]
            },
            {
              _value: "/images/rock2.jpg",
              height: [{ _value: "1000" }]
            }
          ],
          locale: [
            {
              _value: "en_GB",
              alternate: [
                { _value: "fr_FR" },
                { _value: "es_ES" }
              ]
            }
          ]
        }
      end
    end

    context "with fallback" do
      context "when website has opengraph metadata" do
        it "should get values from opengraph metadata" do
          response = double(body: File.open("#{File.dirname(__FILE__)}/../view/opengraph.html", 'r') { |f| f.read })
          RedirectFollower.stub(:new) { double(resolve: response) }

          og = OpenGraph.new("http://test.host")
          og.src.should == "http://test.host"
          og.title.should == "OpenGraph Title"
          og.type.should == "article"
          og.url.should == "http://test.host"
          og.description.should == "My OpenGraph sample site for Rspec"
          og.images.should == ["http://test.host/images/rock1.jpg", "http://test.host/images/rock2.jpg"]
        end
      end

      context "when website has no opengraph metadata" do
        it "should lookup for other data from website" do
          response = double(body: File.open("#{File.dirname(__FILE__)}/../view/opengraph_no_metadata.html", 'r') { |f| f.read })
          RedirectFollower.stub(:new) { double(resolve: response) }

          og = OpenGraph.new("http://test.host/child_page")
          og.src.should == "http://test.host/child_page"
          og.title.should == "OpenGraph Title Fallback"
          og.type.should be_nil
          og.url.should == "http://test.host/child_page"
          og.description.should == "Short Description Fallback"
          og.images.should == ["http://test.host/images/wall1.jpg", "http://test.host/images/wall2.jpg"]
        end
      end

      context "when the website has bad og tags" do
        it "should not throw an exception parsing images" do
          response = double(body: File.open("#{File.dirname(__FILE__)}/../view/opengraph_bad_url.html", 'r') { |f| f.read })
          RedirectFollower.stub(:new) { double(resolve: response) }

          og = OpenGraph.new("http://www.sutd.edu.sg/")
          og.src.should == "http://www.sutd.edu.sg/"
          og.title.should == "Home | SUTD Singapore University of Technology and Design"
          og.type.should be_nil
          og.url.should == "http://www.sutd.edu.sg/"
          og.description.should == "The Singapore University of Technology and Design is established in collaboration with MIT to advance knowledge and nurture technically grounded leaders and innovators to serve societal needs."
          og.images.should == ["http://www.sutd.edu.sg/images/logo_white.png", "http://www.sutd.edu.sg/images/topsecnav-dropdown.png", "http://www.sutd.edu.sg/images/social-media-facebook.png", "http://www.sutd.edu.sg/images/social-media-twitter.png", "http://www.sutd.edu.sg/images/social-media-youtube.png", "http://www.sutd.edu.sg/images/social-media-instagram.png", "http://www.sutd.edu.sg/cmsresource/Navigation_pic/iStock_000015771017XSmall.jpg", "http://www.sutd.edu.sg/cmsresource/Navigation_pic/DSC_0442.jpg", "http://www.sutd.edu.sg/cmsresource/Energy Innovation Challenge 2015_small.jpg", "http://www.sutd.edu.sg/cmsresource/yeo_kiat_seng71x71.jpg", "http://www.sutd.edu.sg/cmsresource/banner3.png", "http://www.sutd.edu.sg/cmsresource/banner2.png", "http://www.sutd.edu.sg/cmsresource/banner_homepage-20150811.png", "http://www.sutd.edu.sg/cmsresource/ad03.jpg", "//googleads.g.doubleclick.net/pagead/viewthroughconversion/1021803272/?value=0&guid=ON&script=0"]
        end
      end

      context "when website has no opengraph metadata nor description" do
        it "should lookup for other data from website" do
          response = double(body: File.open("#{File.dirname(__FILE__)}/../view/opengraph_no_meta_nor_description.html", 'r') { |f| f.read })
          RedirectFollower.stub(:new) { double(resolve: response) }

          og = OpenGraph.new("http://test.host/child_page")
          og.src.should == "http://test.host/child_page"
          og.title.should == "OpenGraph Title Fallback"
          og.type.should be_nil
          og.url.should == "http://test.host/child_page"
          og.description.should == "No description meta here."
          og.images.should == ["http://test.host/images/wall1.jpg", "http://test.host/images/wall2.jpg"]
        end

        context "when website has paragraphs shorter than 20 characters" do
          it "should have an empty description" do
            response = double(body: File.open("#{File.dirname(__FILE__)}/../view/opengraph_no_meta_nor_description_short_p.html", 'r') { |f| f.read })
            RedirectFollower.stub(:new) { double(resolve: response) }
            og = OpenGraph.new("http://test.host/child_page")
            og.description.should == ""
          end
        end
      end
    end

    context "with body" do
      context "with comment on html" do
        it "should parse body instead of downloading it" do
          content = File.read("#{File.dirname(__FILE__)}/../view/opengraph_comment_on_html.html")

          RedirectFollower.should_not_receive(:new)

          og = OpenGraph.new(content)
          og.src.should == content
          og.title.should == "OpenGraph Title"
          og.type.should == "article"
          og.url.should == "http://test.host"
          og.description.should == "My OpenGraph sample site for Rspec"
          og.images.should == ["http://test.host/images/rock1.jpg", "http://test.host/images/rock2.jpg"]
        end

      end

      it "should parse body instead of downloading it" do
        content = File.read("#{File.dirname(__FILE__)}/../view/opengraph.html")
        RedirectFollower.should_not_receive(:new)

        og = OpenGraph.new(content)
        og.src.should == content
        og.title.should == "OpenGraph Title"
        og.type.should == "article"
        og.url.should == "http://test.host"
        og.description.should == "My OpenGraph sample site for Rspec"
        og.images.should == ["http://test.host/images/rock1.jpg", "http://test.host/images/rock2.jpg"]
      end

      context 'the given src has no closing <html> tag' do
        it 'assigns @body to @src and gets values from og metadata anyway' do
          source = File.read("#{File.dirname(__FILE__)}/../view/opengraph_bad_html.html")
          og = OpenGraph.new(source)
          og.src.should == source
          og.title.should == "OpenGraph Title"
          og.type.should == "article"
          og.url.should == "http://test.host"
          og.description.should == "My bad OpenGraph sample site for Rspec"
          og.images.should == ["http://test.host/images/bad_rock1.jpg"]
        end
      end
    end
  end
end


text:
<?php

if (!function_exists('link_to')) {
    /**
     * Generate a HTML link.
     *
     * @param string $url
     * @param string $title
     * @param array  $attributes
     * @param bool   $secure
     *
     * @return string
     */
    function link_to($url, $title = null, $attributes = [], $secure = null)
    {
        return app('html')->link($url, $title, $attributes, $secure);
    }
}

if (!function_exists('link_to_asset')) {
    /**
     * Generate a HTML link to an asset.
     *
     * @param string $url
     * @param string $title
     * @param array  $attributes
     * @param bool   $secure
     *
     * @return string
     */
    function link_to_asset($url, $title = null, $attributes = [], $secure = null)
    {
        return app('html')->linkAsset($url, $title, $attributes, $secure);
    }
}

if (!function_exists('link_to_route')) {
    /**
     * Generate a HTML link to a named route.
     *
     * @param string $name
     * @param string $title
     * @param array  $parameters
     * @param array  $attributes
     *
     * @return string
     */
    function link_to_route($name, $title = null, $parameters = [], $attributes = [])
    {
        return app('html')->linkRoute($name, $title, $parameters, $attributes);
    }
}

if (!function_exists('link_to_action')) {
    /**
     * Generate a HTML link to a controller action.
     *
     * @param string $action
     * @param string $title
     * @param array  $parameters
     * @param array  $attributes
     *
     * @return string
     */
    function link_to_action($action, $title = null, $parameters = [], $attributes = [])
    {
        return app('html')->linkAction($action, $title, $parameters, $attributes);
    }
}


text:
package com.github.pgasync;

import com.pgasync.Connection;
import com.pgasync.NettyConnectibleBuilder;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.function.Function;

public class PgDatabase extends PgConnectible {

    public PgDatabase(NettyConnectibleBuilder.ConnectibleProperties properties, Function<Executor, ProtocolStream> toStream, Executor futuresExecutor) {
        super(properties, toStream, futuresExecutor);
    }

    @Override
    public CompletableFuture<Connection> getConnection() {
        return new PgConnection(toStream.apply(futuresExecutor), dataConverter, encoding)
                .connect(username, password, database)
                .thenApply(connection -> {
                    if (validationQuery != null && !validationQuery.isBlank()) {
                        return connection.completeScript(validationQuery)
                                .handle((rss, th) -> {
                                    if (th != null) {
                                        return connection.close()
                                                .thenApply(v -> CompletableFuture.<Connection>failedFuture(th))
                                                .thenCompose(Function.identity());
                                    } else {
                                        return CompletableFuture.completedFuture(connection);
                                    }
                                })
                                .thenCompose(Function.identity());
                    } else {
                        return CompletableFuture.completedFuture(connection);
                    }
                })
                .thenCompose(Function.identity());
    }

    @Override
    public CompletableFuture<Void> close() {
        return CompletableFuture.completedFuture(null);
    }

}


text:
package runconfig

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"runtime"
	"strings"
	"testing"

	"github.com/docker/engine-api/types/container"
	networktypes "github.com/docker/engine-api/types/network"
	"github.com/docker/engine-api/types/strslice"
)

type f struct {
	file       string
	entrypoint *strslice.StrSlice
}

func TestDecodeContainerConfig(t *testing.T) {

	var (
		fixtures []f
		image    string
	)

	if runtime.GOOS != "windows" {
		image = "ubuntu"
		fixtures = []f{
			{"fixtures/unix/container_config_1_14.json", strslice.New()},
			{"fixtures/unix/container_config_1_17.json", strslice.New("bash")},
			{"fixtures/unix/container_config_1_19.json", strslice.New("bash")},
		}
	} else {
		image = "windows"
		fixtures = []f{
			{"fixtures/windows/container_config_1_19.json", strslice.New("cmd")},
		}
	}

	for _, f := range fixtures {
		b, err := ioutil.ReadFile(f.file)
		if err != nil {
			t.Fatal(err)
		}

		c, h, _, err := DecodeContainerConfig(bytes.NewReader(b))
		if err != nil {
			t.Fatal(fmt.Errorf("Error parsing %s: %v", f, err))
		}

		if c.Image != image {
			t.Fatalf("Expected %s image, found %s\n", image, c.Image)
		}

		if c.Entrypoint.Len() != f.entrypoint.Len() {
			t.Fatalf("Expected %v, found %v\n", f.entrypoint, c.Entrypoint)
		}

		if h != nil && h.Memory != 1000 {
			t.Fatalf("Expected memory to be 1000, found %d\n", h.Memory)
		}
	}
}

// TestDecodeContainerConfigIsolation validates isolation passed
// to the daemon in the hostConfig structure. Note this is platform specific
// as to what level of container isolation is supported.
func TestDecodeContainerConfigIsolation(t *testing.T) {

	// An invalid isolation level
	if _, _, _, err := callDecodeContainerConfigIsolation("invalid"); err != nil {
		if !strings.Contains(err.Error(), `invalid --isolation: "invalid"`) {
			t.Fatal(err)
		}
	}

	// Blank isolation (== default)
	if _, _, _, err := callDecodeContainerConfigIsolation(""); err != nil {
		t.Fatal("Blank isolation should have succeeded")
	}

	// Default isolation
	if _, _, _, err := callDecodeContainerConfigIsolation("default"); err != nil {
		t.Fatal("default isolation should have succeeded")
	}

	// Process isolation (Valid on Windows only)
	if runtime.GOOS == "windows" {
		if _, _, _, err := callDecodeContainerConfigIsolation("process"); err != nil {
			t.Fatal("process isolation should have succeeded")
		}
	} else {
		if _, _, _, err := callDecodeContainerConfigIsolation("process"); err != nil {
			if !strings.Contains(err.Error(), `invalid --isolation: "process"`) {
				t.Fatal(err)
			}
		}
	}

	// Hyper-V Containers isolation (Valid on Windows only)
	if runtime.GOOS == "windows" {
		if _, _, _, err := callDecodeContainerConfigIsolation("hyperv"); err != nil {
			t.Fatal("hyperv isolation should have succeeded")
		}
	} else {
		if _, _, _, err := callDecodeContainerConfigIsolation("hyperv"); err != nil {
			if !strings.Contains(err.Error(), `invalid --isolation: "hyperv"`) {
				t.Fatal(err)
			}
		}
	}
}

// callDecodeContainerConfigIsolation is a utility function to call
// DecodeContainerConfig for validating isolation
func callDecodeContainerConfigIsolation(isolation string) (*container.Config, *container.HostConfig, *networktypes.NetworkingConfig, error) {
	var (
		b   []byte
		err error
	)
	w := ContainerConfigWrapper{
		Config: &container.Config{},
		HostConfig: &container.HostConfig{
			NetworkMode: "none",
			Isolation:   container.Isolation(isolation)},
	}
	if b, err = json.Marshal(w); err != nil {
		return nil, nil, nil, fmt.Errorf("Error on marshal %s", err.Error())
	}
	return DecodeContainerConfig(bytes.NewReader(b))
}


text:
"""Denon HEOS Media Player."""
from __future__ import annotations

from functools import reduce, wraps
import logging
from operator import ior

from pyheos import HeosError, const as heos_const

from homeassistant.components.media_player import MediaPlayerEntity
from homeassistant.components.media_player.const import (
    ATTR_MEDIA_ENQUEUE,
    DOMAIN,
    MEDIA_TYPE_MUSIC,
    MEDIA_TYPE_PLAYLIST,
    MEDIA_TYPE_URL,
    SUPPORT_CLEAR_PLAYLIST,
    SUPPORT_NEXT_TRACK,
    SUPPORT_PAUSE,
    SUPPORT_PLAY,
    SUPPORT_PLAY_MEDIA,
    SUPPORT_PREVIOUS_TRACK,
    SUPPORT_SELECT_SOURCE,
    SUPPORT_SHUFFLE_SET,
    SUPPORT_STOP,
    SUPPORT_VOLUME_MUTE,
    SUPPORT_VOLUME_SET,
    SUPPORT_VOLUME_STEP,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import STATE_IDLE, STATE_PAUSED, STATE_PLAYING
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity import DeviceInfo
from homeassistant.util.dt import utcnow

from .const import DATA_SOURCE_MANAGER, DOMAIN as HEOS_DOMAIN, SIGNAL_HEOS_UPDATED

BASE_SUPPORTED_FEATURES = (
    SUPPORT_VOLUME_MUTE
    | SUPPORT_VOLUME_SET
    | SUPPORT_VOLUME_STEP
    | SUPPORT_CLEAR_PLAYLIST
    | SUPPORT_SHUFFLE_SET
    | SUPPORT_SELECT_SOURCE
    | SUPPORT_PLAY_MEDIA
)

PLAY_STATE_TO_STATE = {
    heos_const.PLAY_STATE_PLAY: STATE_PLAYING,
    heos_const.PLAY_STATE_STOP: STATE_IDLE,
    heos_const.PLAY_STATE_PAUSE: STATE_PAUSED,
}

CONTROL_TO_SUPPORT = {
    heos_const.CONTROL_PLAY: SUPPORT_PLAY,
    heos_const.CONTROL_PAUSE: SUPPORT_PAUSE,
    heos_const.CONTROL_STOP: SUPPORT_STOP,
    heos_const.CONTROL_PLAY_PREVIOUS: SUPPORT_PREVIOUS_TRACK,
    heos_const.CONTROL_PLAY_NEXT: SUPPORT_NEXT_TRACK,
}

_LOGGER = logging.getLogger(__name__)

async def async_setup_entry(
    hass: HomeAssistant, entry: ConfigEntry, async_add_entities
):
    """Add media players for a config entry."""
    players = hass.data[HEOS_DOMAIN][DOMAIN]
    devices = [HeosMediaPlayer(player) for player in players.values()]
    async_add_entities(devices, True)

def log_command_error(command: str):
    """Return decorator that logs command failure."""

    def decorator(func):
        @wraps(func)
        async def wrapper(*args, **kwargs):
            try:
                await func(*args, **kwargs)
            except (HeosError, ValueError) as ex:
                _LOGGER.error("Unable to %s: %s", command, ex)

        return wrapper

    return decorator

class HeosMediaPlayer(MediaPlayerEntity):
    """The HEOS player."""

    def __init__(self, player):
        """Initialize."""
        self._media_position_updated_at = None
        self._player = player
        self._signals = []
        self._supported_features = BASE_SUPPORTED_FEATURES
        self._source_manager = None

    async def _player_update(self, player_id, event):
        """Handle player attribute updated."""
        if self._player.player_id != player_id:
            return
        if event == heos_const.EVENT_PLAYER_NOW_PLAYING_PROGRESS:
            self._media_position_updated_at = utcnow()
        await self.async_update_ha_state(True)

    async def _heos_updated(self):
        """Handle sources changed."""
        await self.async_update_ha_state(True)

    async def async_added_to_hass(self):
        """Device added to hass."""
        # Update state when attributes of the player change
        self._signals.append(
            self._player.heos.dispatcher.connect(
                heos_const.SIGNAL_PLAYER_EVENT, self._player_update
            )
        )
        # Update state when heos changes
        self._signals.append(
            self.hass.helpers.dispatcher.async_dispatcher_connect(
                SIGNAL_HEOS_UPDATED, self._heos_updated
            )
        )

    @log_command_error("clear playlist")
    async def async_clear_playlist(self):
        """Clear players playlist."""
        await self._player.clear_queue()

    @log_command_error("pause")
    async def async_media_pause(self):
        """Send pause command."""
        await self._player.pause()

    @log_command_error("play")
    async def async_media_play(self):
        """Send play command."""
        await self._player.play()

    @log_command_error("move to previous track")
    async def async_media_previous_track(self):
        """Send previous track command."""
        await self._player.play_previous()

    @log_command_error("move to next track")
    async def async_media_next_track(self):
        """Send next track command."""
        await self._player.play_next()

    @log_command_error("stop")
    async def async_media_stop(self):
        """Send stop command."""
        await self._player.stop()

    @log_command_error("set mute")
    async def async_mute_volume(self, mute):
        """Mute the volume."""
        await self._player.set_mute(mute)

    @log_command_error("play media")
    async def async_play_media(self, media_type, media_id, **kwargs):
        """Play a piece of media."""
        if media_type in (MEDIA_TYPE_URL, MEDIA_TYPE_MUSIC):
            await self._player.play_url(media_id)
            return

        if media_type == "quick_select":
            # media_id may be an int or a str
            selects = await self._player.get_quick_selects()
            try:
                index = int(media_id)
            except ValueError:
                # Try finding index by name
                index = next(
                    (index for index, select in selects.items() if select == media_id),
                    None,
                )
            if index is None:
                raise ValueError(f"Invalid quick select '{media_id}'")
            await self._player.play_quick_select(index)
            return

        if media_type == MEDIA_TYPE_PLAYLIST:
            playlists = await self._player.heos.get_playlists()
            playlist = next((p for p in playlists if p.name == media_id), None)
            if not playlist:
                raise ValueError(f"Invalid playlist '{media_id}'")
            add_queue_option = (
                heos_const.ADD_QUEUE_ADD_TO_END
                if kwargs.get(ATTR_MEDIA_ENQUEUE)
                else heos_const.ADD_QUEUE_REPLACE_AND_PLAY
            )
            await self._player.add_to_queue(playlist, add_queue_option)
            return

        if media_type == "favorite":
            # media_id may be an int or str
            try:
                index = int(media_id)
            except ValueError:
                # Try finding index by name
                index = next(
                    (
                        index
                        for index, favorite in self._source_manager.favorites.items()
                        if favorite.name == media_id
                    ),
                    None,
                )
            if index is None:
                raise ValueError(f"Invalid favorite '{media_id}'")
            await self._player.play_favorite(index)
            return

        raise ValueError(f"Unsupported media type '{media_type}'")

    @log_command_error("select source")
    async def async_select_source(self, source):
        """Select input source."""
        await self._source_manager.play_source(source, self._player)

    @log_command_error("set shuffle")
    async def async_set_shuffle(self, shuffle):
        """Enable/disable shuffle mode."""
        await self._player.set_play_mode(self._player.repeat, shuffle)

    @log_command_error("set volume level")
    async def async_set_volume_level(self, volume):
        """Set volume level, range 0..1."""
        await self._player.set_volume(int(volume * 100))

    async def async_update(self):
        """Update supported features of the player."""
        controls = self._player.now_playing_media.supported_controls
        current_support = [CONTROL_TO_SUPPORT[control] for control in controls]
        self._supported_features = reduce(ior, current_support, BASE_SUPPORTED_FEATURES)

        if self._source_manager is None:
            self._source_manager = self.hass.data[HEOS_DOMAIN][DATA_SOURCE_MANAGER]

    async def async_will_remove_from_hass(self):
        """Disconnect the device when removed."""
        for signal_remove in self._signals:
            signal_remove()
        self._signals.clear()

    @property
    def available(self) -> bool:
        """Return True if the device is available."""
        return self._player.available

    @property
    def device_info(self) -> DeviceInfo:
        """Get attributes about the device."""
        return DeviceInfo(
            identifiers={(HEOS_DOMAIN, self._player.player_id)},
            manufacturer="HEOS",
            model=self._player.model,
            name=self._player.name,
            sw_version=self._player.version,
        )

    @property
    def extra_state_attributes(self) -> dict:
        """Get additional attribute about the state."""
        return {
            "media_album_id": self._player.now_playing_media.album_id,
            "media_queue_id": self._player.now_playing_media.queue_id,
            "media_source_id": self._player.now_playing_media.source_id,
            "media_station": self._player.now_playing_media.station,
            "media_type": self._player.now_playing_media.type,
        }

    @property
    def is_volume_muted(self) -> bool:
        """Boolean if volume is currently muted."""
        return self._player.is_muted

    @property
    def media_album_name(self) -> str:
        """Album name of current playing media, music track only."""
        return self._player.now_playing_media.album

    @property
    def media_artist(self) -> str:
        """Artist of current playing media, music track only."""
        return self._player.now_playing_media.artist

    @property
    def media_content_id(self) -> str:
        """Content ID of current playing media."""
        return self._player.now_playing_media.media_id

    @property
    def media_content_type(self) -> str:
        """Content type of current playing media."""
        return MEDIA_TYPE_MUSIC

    @property
    def media_duration(self):
        """Duration of current playing media in seconds."""
        duration = self._player.now_playing_media.duration
        if isinstance(duration, int):
            return duration / 1000
        return None

    @property
    def media_position(self):
        """Position of current playing media in seconds."""
        # Some media doesn't have duration but reports position, return None
        if not self._player.now_playing_media.duration:
            return None
        return self._player.now_playing_media.current_position / 1000

    @property
    def media_position_updated_at(self):
        """When was the position of the current playing media valid."""
        # Some media doesn't have duration but reports position, return None
        if not self._player.now_playing_media.duration:
            return None
        return self._media_position_updated_at

    @property
    def media_image_remotely_accessible(self) -> bool:
        """If the image url is remotely accessible."""
        return True

    @property
    def media_image_url(self) -> str:
        """Image url of current playing media."""
        # May be an empty string, if so, return None
        image_url = self._player.now_playing_media.image_url
        return image_url if image_url else None

    @property
    def media_title(self) -> str:
        """Title of current playing media."""
        return self._player.now_playing_media.song

    @property
    def name(self) -> str:
        """Return the name of the device."""
        return self._player.name

    @property
    def should_poll(self) -> bool:
        """No polling needed for this device."""
        return False

    @property
    def shuffle(self) -> bool:
        """Boolean if shuffle is enabled."""
        return self._player.shuffle

    @property
    def source(self) -> str:
        """Name of the current input source."""
        return self._source_manager.get_current_source(self._player.now_playing_media)

    @property
    def source_list(self) -> list[str]:
        """List of available input sources."""
        return self._source_manager.source_list

    @property
    def state(self) -> str:
        """State of the player."""
        return PLAY_STATE_TO_STATE[self._player.state]

    @property
    def supported_features(self) -> int:
        """Flag media player features that are supported."""
        return self._supported_features

    @property
    def unique_id(self) -> str:
        """Return a unique ID."""
        return str(self._player.player_id)

    @property
    def volume_level(self) -> float:
        """Volume level of the media player (0..1)."""
        return self._player.volume / 100


text:
package akka.util

import java.nio.{ ByteBuffer, ByteOrder }

import scala.annotation.tailrec
import scala.collection.LinearSeq
import scala.collection.mutable.ListBuffer
import scala.reflect.ClassTag

object ByteIterator {
  object ByteArrayIterator {
    private val emptyArray: Array[Byte] = Array.ofDim[Byte](0)

    protected[akka] def apply(array: Array[Byte]): ByteArrayIterator =
      new ByteArrayIterator(array, 0, array.length)

    protected[akka] def apply(array: Array[Byte], from: Int, until: Int): ByteArrayIterator =
      new ByteArrayIterator(array, from, until)

    val empty: ByteArrayIterator = apply(emptyArray)
  }

  class ByteArrayIterator private (private var array: Array[Byte], private var from: Int, private var until: Int) extends ByteIterator {
    iterator ⇒

    @inline final def len: Int = until - from

    @inline final def hasNext: Boolean = from < until

    @inline final def head: Byte = array(from)

    final def next(): Byte = {
      if (!hasNext) Iterator.empty.next
      else { val i = from; from = from + 1; array(i) }
    }

    def clear(): Unit = { this.array = ByteArrayIterator.emptyArray; from = 0; until = from }

    final override def length: Int = { val l = len; clear(); l }

    final override def ++(that: TraversableOnce[Byte]): ByteIterator = that match {
      case that: ByteIterator ⇒
        if (that.isEmpty) this
        else if (this.isEmpty) that
        else that match {
          case that: ByteArrayIterator ⇒
            if ((this.array eq that.array) && (this.until == that.from)) {
              this.until = that.until
              that.clear()
              this
            } else {
              val result = MultiByteArrayIterator(List(this, that))
              this.clear()
              result
            }
          case that: MultiByteArrayIterator ⇒ this ++: that
        }
      case _ ⇒ super.++(that)
    }

    final override def clone: ByteArrayIterator = new ByteArrayIterator(array, from, until)

    final override def take(n: Int): this.type = {
      if (n < len) until = { if (n > 0) (from + n) else from }
      this
    }

    final override def drop(n: Int): this.type = {
      if (n > 0) from = { if (n < len) (from + n) else until }
      this
    }

    final override def takeWhile(p: Byte ⇒ Boolean): this.type = {
      val prev = from
      dropWhile(p)
      until = from; from = prev
      this
    }

    final override def dropWhile(p: Byte ⇒ Boolean): this.type = {
      var stop = false
      while (!stop && hasNext) {
        if (p(array(from))) { from = from + 1 } else { stop = true }
      }
      this
    }

    final override def copyToArray[B >: Byte](xs: Array[B], start: Int, len: Int): Unit = {
      val n = 0 max ((xs.length - start) min this.len min len)
      Array.copy(this.array, from, xs, start, n)
      this.drop(n)
    }

    final override def toByteString: ByteString = {
      val result =
        if ((from == 0) && (until == array.length)) ByteString.ByteString1C(array)
        else ByteString.ByteString1(array, from, len)
      clear()
      result
    }

    def getBytes(xs: Array[Byte], offset: Int, n: Int): this.type = {
      if (n <= this.len) {
        Array.copy(this.array, this.from, xs, offset, n)
        this.drop(n)
      } else Iterator.empty.next
    }

    private def wrappedByteBuffer: ByteBuffer = ByteBuffer.wrap(array, from, len).asReadOnlyBuffer

    def getShorts(xs: Array[Short], offset: Int, n: Int)(implicit byteOrder: ByteOrder): this.type =
      { wrappedByteBuffer.order(byteOrder).asShortBuffer.get(xs, offset, n); drop(2 * n) }

    def getInts(xs: Array[Int], offset: Int, n: Int)(implicit byteOrder: ByteOrder): this.type =
      { wrappedByteBuffer.order(byteOrder).asIntBuffer.get(xs, offset, n); drop(4 * n) }

    def getLongs(xs: Array[Long], offset: Int, n: Int)(implicit byteOrder: ByteOrder): this.type =
      { wrappedByteBuffer.order(byteOrder).asLongBuffer.get(xs, offset, n); drop(8 * n) }

    def getFloats(xs: Array[Float], offset: Int, n: Int)(implicit byteOrder: ByteOrder): this.type =
      { wrappedByteBuffer.order(byteOrder).asFloatBuffer.get(xs, offset, n); drop(4 * n) }

    def getDoubles(xs: Array[Double], offset: Int, n: Int)(implicit byteOrder: ByteOrder): this.type =
      { wrappedByteBuffer.order(byteOrder).asDoubleBuffer.get(xs, offset, n); drop(8 * n) }

    def copyToBuffer(buffer: ByteBuffer): Int = {
      val copyLength = math.min(buffer.remaining, len)
      if (copyLength > 0) {
        buffer.put(array, from, copyLength)
        drop(copyLength)
      }
      copyLength
    }

    def asInputStream: java.io.InputStream = new java.io.InputStream {
      override def available: Int = iterator.len

      def read: Int = if (hasNext) (next().toInt & 0xff) else -1

      override def read(b: Array[Byte], off: Int, len: Int): Int = {
        if ((off < 0) || (len < 0) || (off + len > b.length)) throw new IndexOutOfBoundsException
        if (len == 0) 0
        else if (!isEmpty) {
          val nRead = math.min(available, len)
          copyToArray(b, off, nRead)
          nRead
        } else -1
      }

      override def skip(n: Long): Long = {
        val nSkip = math.min(iterator.len, n.toInt)
        iterator.drop(nSkip)
        nSkip
      }
    }
  }

  object MultiByteArrayIterator {
    protected val clearedList: List[ByteArrayIterator] = List(ByteArrayIterator.empty)

    val empty: MultiByteArrayIterator = new MultiByteArrayIterator(Nil)

    protected[akka] def apply(iterators: LinearSeq[ByteArrayIterator]): MultiByteArrayIterator =
      new MultiByteArrayIterator(iterators)
  }

  class MultiByteArrayIterator private (private var iterators: LinearSeq[ByteArrayIterator]) extends ByteIterator {
    // After normalization:
    // * iterators.isEmpty == false
    // * (!iterator.head.isEmpty || iterators.tail.isEmpty) == true
    private def normalize(): this.type = {
      @tailrec def norm(xs: LinearSeq[ByteArrayIterator]): LinearSeq[ByteArrayIterator] = {
        if (xs.isEmpty) MultiByteArrayIterator.clearedList
        else if (xs.head.isEmpty) norm(xs.tail)
        else xs
      }
      iterators = norm(iterators)
      this
    }
    normalize()

    @inline private def current: ByteArrayIterator = iterators.head
    @inline private def dropCurrent(): Unit = { iterators = iterators.tail }
    @inline def clear(): Unit = { iterators = MultiByteArrayIterator.empty.iterators }

    @inline final def hasNext: Boolean = current.hasNext

    @inline final def head: Byte = current.head

    final def next(): Byte = {
      val result = current.next()
      normalize()
      result
    }

    final override def len: Int = iterators.foldLeft(0) { _ + _.len }

    final override def length: Int = {
      val result = len
      clear()
      result
    }

    private[akka] def ++:(that: ByteArrayIterator): this.type = {
      iterators = that +: iterators
      this
    }

    final override def ++(that: TraversableOnce[Byte]): ByteIterator = that match {
      case that: ByteIterator ⇒
        if (that.isEmpty) this
        else if (this.isEmpty) that
        else {
          that match {
            case that: ByteArrayIterator ⇒
              iterators = this.iterators :+ that
              that.clear()
              this
            case that: MultiByteArrayIterator ⇒
              iterators = this.iterators ++ that.iterators
              that.clear()
              this
          }
        }
      case _ ⇒ super.++(that)
    }

    final override def clone: MultiByteArrayIterator = {
      val clonedIterators: List[ByteArrayIterator] = iterators.map(_.clone)(collection.breakOut)
      new MultiByteArrayIterator(clonedIterators)
    }

    final override def take(n: Int): this.type = {
      var rest = n
      val builder = new ListBuffer[ByteArrayIterator]
      while ((rest > 0) && !iterators.isEmpty) {
        current.take(rest)
        if (current.hasNext) {
          rest -= current.len
          builder += current
        }
        iterators = iterators.tail
      }
      iterators = builder.result
      normalize()
    }

    @tailrec final override def drop(n: Int): this.type =
      if ((n > 0) && !isEmpty) {
        val nCurrent = math.min(n, current.len)
        current.drop(n)
        val rest = n - nCurrent
        assert(current.isEmpty || (rest == 0))
        normalize()
        drop(rest)
      } else this

    final override def takeWhile(p: Byte ⇒ Boolean): this.type = {
      var stop = false
      var builder = new ListBuffer[ByteArrayIterator]
      while (!stop && !iterators.isEmpty) {
        val lastLen = current.len
        current.takeWhile(p)
        if (current.hasNext) builder += current
        if (current.len < lastLen) stop = true
        dropCurrent()
      }
      iterators = builder.result
      normalize()
    }

    @tailrec final override def dropWhile(p: Byte ⇒ Boolean): this.type =
      if (!isEmpty) {
        current.dropWhile(p)
        val dropMore = current.isEmpty
        normalize()
        if (dropMore) dropWhile(p) else this
      } else this

    final override def copyToArray[B >: Byte](xs: Array[B], start: Int, len: Int): Unit = {
      var pos = start
      var rest = len
      while ((rest > 0) && !iterators.isEmpty) {
        val n = 0 max ((xs.length - pos) min current.len min rest)
        current.copyToArray(xs, pos, n)
        pos += n
        rest -= n
        dropCurrent()
      }
      normalize()
    }

    override def foreach[@specialized U](f: Byte ⇒ U): Unit = {
      iterators foreach { _ foreach f }
      clear()
    }

    final override def toByteString: ByteString = {
      if (iterators.tail.isEmpty) iterators.head.toByteString
      else {
        val result = iterators.foldLeft(ByteString.empty) { _ ++ _.toByteString }
        clear()
        result
      }
    }

    @tailrec protected final def getToArray[A](xs: Array[A], offset: Int, n: Int, elemSize: Int)(getSingle: ⇒ A)(getMult: (Array[A], Int, Int) ⇒ Unit): this.type =
      if (n <= 0) this else {
        if (isEmpty) Iterator.empty.next
        val nDone = if (current.len >= elemSize) {
          val nCurrent = math.min(n, current.len / elemSize)
          getMult(xs, offset, nCurrent)
          nCurrent
        } else {
          xs(offset) = getSingle
          1
        }
        normalize()
        getToArray(xs, offset + nDone, n - nDone, elemSize)(getSingle)(getMult)
      }

    def getBytes(xs: Array[Byte], offset: Int, n: Int): this.type =
      getToArray(xs, offset, n, 1) { getByte } { current.getBytes(_, _, _) }

    def getShorts(xs: Array[Short], offset: Int, n: Int)(implicit byteOrder: ByteOrder): this.type =
      getToArray(xs, offset, n, 2) { getShort(byteOrder) } { current.getShorts(_, _, _)(byteOrder) }

    def getInts(xs: Array[Int], offset: Int, n: Int)(implicit byteOrder: ByteOrder): this.type =
      getToArray(xs, offset, n, 4) { getInt(byteOrder) } { current.getInts(_, _, _)(byteOrder) }

    def getLongs(xs: Array[Long], offset: Int, n: Int)(implicit byteOrder: ByteOrder): this.type =
      getToArray(xs, offset, n, 8) { getLong(byteOrder) } { current.getLongs(_, _, _)(byteOrder) }

    def getFloats(xs: Array[Float], offset: Int, n: Int)(implicit byteOrder: ByteOrder): this.type =
      getToArray(xs, offset, n, 8) { getFloat(byteOrder) } { current.getFloats(_, _, _)(byteOrder) }

    def getDoubles(xs: Array[Double], offset: Int, n: Int)(implicit byteOrder: ByteOrder): this.type =
      getToArray(xs, offset, n, 8) { getDouble(byteOrder) } { current.getDoubles(_, _, _)(byteOrder) }

    def copyToBuffer(buffer: ByteBuffer): Int = {
      val n = iterators.foldLeft(0) { _ + _.copyToBuffer(buffer) }
      normalize()
      n
    }

    def asInputStream: java.io.InputStream = new java.io.InputStream {
      override def available: Int = current.len

      def read: Int = if (hasNext) (next().toInt & 0xff) else -1

      override def read(b: Array[Byte], off: Int, len: Int): Int = {
        val nRead = current.asInputStream.read(b, off, len)
        normalize()
        nRead
      }

      override def skip(n: Long): Long = {
        @tailrec def skipImpl(n: Long, skipped: Long): Long =
          if (n > 0) {
            if (!isEmpty) {
              val m = current.asInputStream.skip(n)
              normalize()
              val newN = n - m
              val newSkipped = skipped + m
              if (newN > 0) skipImpl(newN, newSkipped)
              else newSkipped
            } else 0
          } else 0

        skipImpl(n, 0)
      }
    }
  }
}

/**
 * An iterator over a ByteString.
 */

abstract class ByteIterator extends BufferedIterator[Byte] {
  def len: Int

  def head: Byte

  def next(): Byte

  protected def clear(): Unit

  def ++(that: TraversableOnce[Byte]): ByteIterator = if (that.isEmpty) this else ByteIterator.ByteArrayIterator(that.toArray)

  // *must* be overridden by derived classes. This construction is necessary
  // to specialize the return type, as the method is already implemented in
  // the parent class.
  override def clone: ByteIterator = throw new UnsupportedOperationException("Method clone is not implemented in ByteIterator")

  override def duplicate: (ByteIterator, ByteIterator) = (this, clone)

  // *must* be overridden by derived classes. This construction is necessary
  // to specialize the return type, as the method is already implemented in
  // the parent class.
  override def take(n: Int): this.type = throw new UnsupportedOperationException("Method take is not implemented in ByteIterator")

  // *must* be overridden by derived classes. This construction is necessary
  // to specialize the return type, as the method is already implemented in
  // the parent class.
  override def drop(n: Int): this.type = throw new UnsupportedOperationException("Method drop is not implemented in ByteIterator")

  override def slice(from: Int, until: Int): this.type = {
    if (from > 0) drop(from).take(until - from)
    else take(until)
  }

  // *must* be overridden by derived classes. This construction is necessary
  // to specialize the return type, as the method is already implemented in
  // the parent class.
  override def takeWhile(p: Byte ⇒ Boolean): this.type = throw new UnsupportedOperationException("Method takeWhile is not implemented in ByteIterator")

  // *must* be overridden by derived classes. This construction is necessary
  // to specialize the return type, as the method is already implemented in
  // the parent class.
  override def dropWhile(p: Byte ⇒ Boolean): this.type = throw new UnsupportedOperationException("Method dropWhile is not implemented in ByteIterator")

  override def span(p: Byte ⇒ Boolean): (ByteIterator, ByteIterator) = {
    val that = clone
    this.takeWhile(p)
    that.drop(this.len)
    (this, that)
  }

  override def indexWhere(p: Byte ⇒ Boolean): Int = {
    var index = 0
    var found = false
    while (!found && hasNext) if (p(next())) { found = true } else { index += 1 }
    if (found) index else -1
  }

  def indexOf(elem: Byte): Int = indexWhere { _ == elem }

  override def indexOf[B >: Byte](elem: B): Int = indexWhere { _ == elem }

  def toByteString: ByteString

  override def toSeq: ByteString = toByteString

  override def foreach[@specialized U](f: Byte ⇒ U): Unit =
    while (hasNext) f(next())

  override def foldLeft[@specialized B](z: B)(op: (B, Byte) ⇒ B): B = {
    var acc = z
    foreach { byte ⇒ acc = op(acc, byte) }
    acc
  }

  override def toArray[B >: Byte](implicit arg0: ClassTag[B]): Array[B] = {
    val target = Array.ofDim[B](len)
    copyToArray(target)
    target
  }

  /**
   * Get a single Byte from this iterator. Identical to next().
   */
  def getByte: Byte = next()

  /**
   * Get a single Short from this iterator.
   */
  def getShort(implicit byteOrder: ByteOrder): Short = {
    if (byteOrder == ByteOrder.BIG_ENDIAN)
      ((next() & 0xff) << 8 | (next() & 0xff) << 0).toShort
    else if (byteOrder == ByteOrder.LITTLE_ENDIAN)
      ((next() & 0xff) << 0 | (next() & 0xff) << 8).toShort
    else throw new IllegalArgumentException("Unknown byte order " + byteOrder)
  }

  /**
   * Get a single Int from this iterator.
   */
  def getInt(implicit byteOrder: ByteOrder): Int = {
    if (byteOrder == ByteOrder.BIG_ENDIAN)
      ((next() & 0xff) << 24
        | (next() & 0xff) << 16
        | (next() & 0xff) << 8
        | (next() & 0xff) << 0)
    else if (byteOrder == ByteOrder.LITTLE_ENDIAN)
      ((next() & 0xff) << 0
        | (next() & 0xff) << 8
        | (next() & 0xff) << 16
        | (next() & 0xff) << 24)
    else throw new IllegalArgumentException("Unknown byte order " + byteOrder)
  }

  /**
   * Get a single Long from this iterator.
   */
  def getLong(implicit byteOrder: ByteOrder): Long = {
    if (byteOrder == ByteOrder.BIG_ENDIAN)
      ((next().toLong & 0xff) << 56
        | (next().toLong & 0xff) << 48
        | (next().toLong & 0xff) << 40
        | (next().toLong & 0xff) << 32
        | (next().toLong & 0xff) << 24
        | (next().toLong & 0xff) << 16
        | (next().toLong & 0xff) << 8
        | (next().toLong & 0xff) << 0)
    else if (byteOrder == ByteOrder.LITTLE_ENDIAN)
      ((next().toLong & 0xff) << 0
        | (next().toLong & 0xff) << 8
        | (next().toLong & 0xff) << 16
        | (next().toLong & 0xff) << 24
        | (next().toLong & 0xff) << 32
        | (next().toLong & 0xff) << 40
        | (next().toLong & 0xff) << 48
        | (next().toLong & 0xff) << 56)
    else throw new IllegalArgumentException("Unknown byte order " + byteOrder)
  }

  /**
   * Get a Long from this iterator where only the least significant `n`
   * bytes were encoded.
   */
  def getLongPart(n: Int)(implicit byteOrder: ByteOrder): Long = {
    if (byteOrder == ByteOrder.BIG_ENDIAN) {
      var x = 0L
      (1 to n) foreach (_ ⇒ x = (x << 8) | (next() & 0xff))
      x
    } else if (byteOrder == ByteOrder.LITTLE_ENDIAN) {
      var x = 0L
      (0 until n) foreach (i ⇒ x |= (next() & 0xff) << 8 * i)
      x
    } else throw new IllegalArgumentException("Unknown byte order " + byteOrder)
  }

  def getFloat(implicit byteOrder: ByteOrder): Float =
    java.lang.Float.intBitsToFloat(getInt(byteOrder))

  def getDouble(implicit byteOrder: ByteOrder): Double =
    java.lang.Double.longBitsToDouble(getLong(byteOrder))

  /**
   * Get a specific number of Bytes from this iterator. In contrast to
   * copyToArray, this method will fail if this.len < xs.length.
   */
  def getBytes(xs: Array[Byte]): this.type = getBytes(xs, 0, xs.length)

  /**
   * Get a specific number of Bytes from this iterator. In contrast to
   * copyToArray, this method will fail if length < n or if (xs.length - offset) < n.
   */
  def getBytes(xs: Array[Byte], offset: Int, n: Int): this.type

  /**
   * Get a specific number of Bytes from this iterator. In contrast to
   * copyToArray, this method will fail if this.len < n.
   */
  def getBytes(n: Int): Array[Byte] = {
    val bytes = new Array[Byte](n)
    getBytes(bytes, 0, n)
    bytes
  }

  /**
   * Get a ByteString with specific number of Bytes from this iterator. In contrast to
   * copyToArray, this method will fail if this.len < n.
   */
  def getByteString(n: Int): ByteString = {
    val bs = clone.take(n).toByteString
    drop(n)
    bs
  }

  /**
   * Get a number of Shorts from this iterator.
   */
  def getShorts(xs: Array[Short])(implicit byteOrder: ByteOrder): this.type =
    getShorts(xs, 0, xs.length)(byteOrder)

  /**
   * Get a number of Shorts from this iterator.
   */
  def getShorts(xs: Array[Short], offset: Int, n: Int)(implicit byteOrder: ByteOrder): this.type

  /**
   * Get a number of Ints from this iterator.
   */
  def getInts(xs: Array[Int])(implicit byteOrder: ByteOrder): this.type =
    getInts(xs, 0, xs.length)(byteOrder)

  /**
   * Get a number of Ints from this iterator.
   */
  def getInts(xs: Array[Int], offset: Int, n: Int)(implicit byteOrder: ByteOrder): this.type

  /**
   * Get a number of Longs from this iterator.
   */
  def getLongs(xs: Array[Long])(implicit byteOrder: ByteOrder): this.type =
    getLongs(xs, 0, xs.length)(byteOrder)

  /**
   * Get a number of Longs from this iterator.
   */
  def getLongs(xs: Array[Long], offset: Int, n: Int)(implicit byteOrder: ByteOrder): this.type

  /**
   * Get a number of Floats from this iterator.
   */
  def getFloats(xs: Array[Float])(implicit byteOrder: ByteOrder): this.type =
    getFloats(xs, 0, xs.length)(byteOrder)

  /**
   * Get a number of Floats from this iterator.
   */
  def getFloats(xs: Array[Float], offset: Int, n: Int)(implicit byteOrder: ByteOrder): this.type

  /**
   * Get a number of Doubles from this iterator.
   */
  def getDoubles(xs: Array[Double])(implicit byteOrder: ByteOrder): this.type =
    getDoubles(xs, 0, xs.length)(byteOrder)

  /**
   * Get a number of Doubles from this iterator.
   */
  def getDoubles(xs: Array[Double], offset: Int, n: Int)(implicit byteOrder: ByteOrder): this.type

  /**
   * Copy as many bytes as possible to a ByteBuffer, starting from it's
   * current position. This method will not overflow the buffer.
   *
   * @param buffer a ByteBuffer to copy bytes to
   * @return the number of bytes actually copied
   */
  def copyToBuffer(buffer: ByteBuffer): Int

  /**
   * Directly wraps this ByteIterator in an InputStream without copying.
   * Read and skip operations on the stream will advance the iterator
   * accordingly.
   */
  def asInputStream: java.io.InputStream
}


text:
module.exports = {
  beforeEach: browser => browser.init(),

  'test app container': browser => {
    const homepage = browser.page.homepage();
    homepage.waitForElementVisible('@appContainer');

    const app = homepage.section.app;
    app.expect.section('@appInfo').to.be.visible;
    app.expect.section('@navigation').to.be.visible;

    browser.end();
  },

  'test app info': browser => {
    const homepage = browser.page.homepage();
    const appInfoSection = homepage.section.app.section.appInfo;

    appInfoSection.assert.elementCount('@logo', 1);
    appInfoSection.expect.section('@headline').text.to.match(/^NEST Desktop$/);
  },
};


text:
app.factory('alert', function($uibModal) {

	function show(action, event) {
		return $uibModal.open({
			templateUrl: 'modalContent.html',
			controller: function() {
				var vm = this;
				vm.action = action;
				vm.event = event;
			},
			controllerAs: 'vm'
		});
	}

	return {
		show: show
	};

});


text:
export { FormlyMatTextAreaModule } from './textarea.module';
export { FormlyFieldTextArea } from './textarea.type';


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/handel_trade_icon"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:src="@mipmap/beer"
        android:layout_marginBottom="2dp"
        android:layout_alignParentTop="true" />

    <TextView
        android:id="@+id/handel_inventory_amount"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/handel_trade_icon"
        android:layout_alignParentTop="true"
        android:layout_toEndOf="@+id/handel_trade_icon"
        android:textSize="18sp"
        android:gravity="center"
        android:layout_marginLeft="5dp"/>

    <TextView
        android:id="@+id/x"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/handel_inventory_amount"
        android:layout_alignParentTop="true"
        android:layout_toEndOf="@+id/handel_inventory_amount"
        android:gravity="center"
        android:textSize="20sp"
        android:text="x " />

    <TextView
        android:id="@+id/handel_inventory_prouct_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/x"
        android:layout_toEndOf="@+id/x"
        android:gravity="center"
        android:textSize="20sp"
        android:layout_alignTop="@+id/handel_trade_icon" />

    <Button
        android:id="@+id/increaseTradeItem"
        android:layout_width="60dp"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/handel_inventory_prouct_name"
        android:layout_alignParentEnd="true"
        android:layout_alignParentTop="true"
        android:gravity="center"
        android:text="+"
        android:textSize="20sp"
        android:textStyle="bold"/>

    <TextView
        android:id="@+id/amountOfTradeItems"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:layout_toStartOf="@id/increaseTradeItem"
        android:layout_alignBottom="@id/increaseTradeItem"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:textSize="20sp"/>

    <Button
        android:id="@+id/decreaseTradeItem"
        android:layout_width="60dp"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/increaseTradeItem"
        android:layout_alignParentTop="true"
        android:layout_toStartOf="@id/amountOfTradeItems"
        android:gravity="center"
        android:text="-"
        android:textSize="20sp"
        android:textStyle="bold" />

</RelativeLayout>


text:
package io.brooklyn.ambari.rest.domain;

import com.google.common.base.Preconditions;
import com.google.gson.annotations.SerializedName;

import java.util.List;
import java.util.Map;

public class AlertTargets {

    @SerializedName("href")
    private String href;

    @SerializedName("items")
    private List<Map> items;

    public List<Map> getItems() {
        return items;
    }

    public static class Builder {

        private String href;

        private List<Map> items;

        public Builder setHref(String href) {
            this.href = href;
            return this;
        }

        public Builder setItems(List<Map> items) {
            this.items = items;
            return this;
        }

        public AlertTargets build() {
            Preconditions.checkNotNull(this.href);
            Preconditions.checkNotNull(this.items);

            AlertTargets alertTargets = new AlertTargets();
            alertTargets.href = this.href;
            alertTargets.items = this.items;

            return alertTargets;
        }
    }
}


text:
package org.firebears.commands;

import edu.wpi.first.wpilibj.command.Command;
import org.firebears.Robot;

public class TriggerRapidFire extends Command {

    static final int PUSHING_STATE = 1;
    static final int RETRACTING_STATE = 2;
    int state = PUSHING_STATE;

    protected void initialize() {
        state = PUSHING_STATE;
        setTimeout(TriggerPush.PUSH_TIME);
    }

    protected void execute() {
        switch (state) {

            case PUSHING_STATE:
                Robot.trigger.TriggerMove(TriggerPush.PUSH_SPEED);
                if (isTimedOut()) {
                    state = RETRACTING_STATE;
                    setTimeout(0.5);
                }
                break;

            case RETRACTING_STATE:
                Robot.trigger.TriggerMove(TriggerRetract.RETRACT_SPEED);
                if (isTimedOut()) {
                    state = PUSHING_STATE;
                    setTimeout(TriggerPush.PUSH_TIME);
                }
                break;

        }
    }

    protected boolean isFinished() {
        return false;
    }

    protected void end() {
        Robot.trigger.TriggerMove(TriggerRetract.RETRACT_SPEED);
    }

    protected void interrupted() {
        end();
    }
}


text:
class ComponentManager {
  constructor(service) {
    this.service = service;
    this.loadedPackages = {};
    this.pendingPackages = {};
  }

  get(packageName, forceFetch) {
    return new Promise((resolve, reject) => {
      if (!this.loadedPackages[packageName]) {
        forceFetch = true;
      }
      if (forceFetch) {
        this._doFetch(packageName, resolve, reject);
        return;
      }
      this.service.dbService.open().then(() => {
        this.service.dbService.getComponent(packageName).then((response) => {
          if (response) {
            resolve(response);
          } else {
            this._doFetch(packageName, resolve, reject);
          }
        });
      }).catch(() => {
        this._doFetch(packageName, resolve, reject);
      });
    });
  }

  _doFetch(packageName, resolve, reject) {
    if (!this.pendingPackages[packageName]) {
      this.pendingPackages[packageName] = [];
    }
    const cb = { resolve: resolve, reject: reject };
    if (this.pendingPackages[packageName].length) {
      this.pendingPackages[packageName].push(cb);
    } else {
      this.pendingPackages[packageName].push(cb);
      this._fetchComponent(packageName).then((response) => {
        this.loadedPackages[packageName] = true;
        this.service.dbService.saveComponent(response).then(() => { });
        try {
          const list = this.pendingPackages[packageName] || [];
          for (const cb of list) {
            cb.resolve(response);
          }
        } finally {
          this.pendingPackages[packageName] = [];
        }
      }).catch((err) => {
        try {
          const list = this.pendingPackages[packageName] || [];
          for (const cb of list) {
            cb.reject(err);
          }
        } finally {
          this.pendingPackages[packageName] = [];
        }
      });
    }
  }

  _fetchComponent(packageName) {
    return this.service.fetchComponent(packageName);
  }

  list() {
    return this.service.dbService.getAllComponents();
  }
}


text:
<?php

namespace Dataphant\Tests\Properties;

use Dataphant\Tests\BaseTestCase;

class IntegerPropertyTest # extends BaseTestCase
{

}


text:
package ua.com.fielden.platform.security.exceptions;

import ua.com.fielden.platform.exceptions.AbstractPlatformRuntimeException;

/**
 * A runtime exception that indicates erroneous situation pertaining to user security.
 *
 * @author TG Team
 *
 */
public class SecurityException extends AbstractPlatformRuntimeException {
    private static final long serialVersionUID = 1L;

    public SecurityException(final String msg) {
        super(msg);
    }

    public SecurityException(final String msg, final Throwable cause) {
        super(msg, cause);
    }
}


text:
'use strict';

require('colors');
const diff = require('diff');

module.exports = (attempt, solution) => {
  // Compare solution and attempt results
  const parts = diff.diffWordsWithSpace(attempt, solution);
  // return diff
  return parts.map(part =>
    part.added   ? part.value.red.inverse :
    part.removed ? part.value.green.inverse : part.value
  ).join('');
};


text:
<?php

// autoload_files.php @generated by Composer

$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);

return array(
    $vendorDir . '/illuminate/support/Illuminate/Support/helpers.php',
    $vendorDir . '/vrana/notorm/NotORM.php',
);


text:
package jodd.bean.data;

public class EnumBean {

	private int id;
	private Color color;
	private Status status;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public Color getColor() {
		return color;
	}

	public void setColor(Color color) {
		this.color = color;
	}

	public Status getStatus() {
		return status;
	}

	public void setStatus(Status status) {
		this.status = status;
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<sem:triples uri="http://www.lds.org/vrl/objects/agriculture-and-farming/agriculture" xmlns:sem="http://marklogic.com/semantics">
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/objects/agriculture-and-farming/agriculture</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#prefLabel</sem:predicate>
    <sem:object datatype="xsd:string" xml:lang="eng">Agriculture</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/objects/agriculture-and-farming/agriculture</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#inScheme</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/concept-scheme/vrl</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/objects/agriculture-and-farming/agriculture</sem:subject>
    <sem:predicate>http://www.lds.org/core#entityType</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/Topic</sem:object>
  </sem:triple>
</sem:triples>


text:
<?xml version="1.0"?>
<!DOCTYPE module PUBLIC
        "-//Puppy Crawl//DTD Check Configuration 1.2//EN"
        "http://www.puppycrawl.com/dtds/configuration_1_2.dtd">

<!--

  Checkstyle configuration that checks the sun coding conventions from:

    - the Java Language Specification at
      http://java.sun.com/docs/books/jls/second_edition/html/index.html

    - the Sun Code Conventions at http://java.sun.com/docs/codeconv/

    - the Javadoc guidelines at
      http://java.sun.com/j2se/javadoc/writingdoccomments/index.html

    - the JDK Api documentation http://java.sun.com/j2se/docs/api/index.html

    - some best practices

  Checkstyle is very configurable. Be sure to read the documentation at
  http://checkstyle.sf.net (or in your downloaded distribution).

  Most Checks are configurable, be sure to consult the documentation.

  To completely disable a check, just comment it out or delete it from the file.

  Finally, it is worth reading the documentation.

-->

<module name="Checker">
    <!--
        If you set the basedir property below, then all reported file
        names will be relative to the specified directory. See
        http://checkstyle.sourceforge.net/5.x/config.html#Checker

        <property name="basedir" value="${basedir}"/>
    -->

    <!-- Checks that a package-info.java file exists for each package.     -->
    <!-- See http://checkstyle.sf.net/config_javadoc.html#JavadocPackage -->
    <!--<module name="JavadocPackage"/>-->

    <!-- Checks whether files end with a new line.                        -->
    <!-- See http://checkstyle.sf.net/config_misc.html#NewlineAtEndOfFile -->
    <module name="NewlineAtEndOfFile">
        <property name="lineSeparator" value="lf"/>
    </module>

    <!-- Checks that property files contain the same keys.         -->
    <!-- See http://checkstyle.sf.net/config_misc.html#Translation -->
    <!--<module name="Translation"/>-->

    <!-- Checks for Size Violations.                    -->
    <!-- See http://checkstyle.sf.net/config_sizes.html -->
    <module name="FileLength"/>

    <!-- Checks for whitespace                               -->
    <!-- See http://checkstyle.sf.net/config_whitespace.html -->
    <!--<module name="FileTabCharacter"/>-->

    <!-- Miscellaneous other checks.                   -->
    <!-- See http://checkstyle.sf.net/config_misc.html -->
    <module name="RegexpSingleline">
        <property name="format" value="\s+$"/>
        <property name="minimum" value="0"/>
        <property name="maximum" value="0"/>
        <property name="message" value="Line has trailing spaces."/>
    </module>

    <module name="TreeWalker">

        <!-- Checks for Javadoc comments.                     -->
        <!-- See http://checkstyle.sf.net/config_javadoc.html -->
        <module name="JavadocMethod">
            <property name="scope" value="protected"/>
            <property name="severity" value="warning"/>
            <property name="allowMissingJavadoc" value="true"/>
            <property name="allowMissingParamTags" value="true"/>
            <property name="allowMissingReturnTag" value="true"/>
            <property name="allowMissingThrowsTags" value="true"/>
            <property name="allowThrowsTagsForSubclasses" value="true"/>
            <property name="allowUndeclaredRTE" value="true"/>
            <property name="allowMissingPropertyJavadoc" value="true"/>
        </module>
        <!--<module name="JavadocType"/>-->
        <!--<module name="JavadocVariable"/>-->
        <module name="JavadocStyle"/>

        <!-- Checks for Naming Conventions.                  -->
        <!-- See http://checkstyle.sf.net/config_naming.html -->
        <module name="ConstantName">
            <property name="format" value="^[a-z][a-zA-Z0-9]*_?$"/>
            <property name="severity" value="warning"/>
        </module>
        <module name="LocalFinalVariableName">
            <property name="format" value="^[a-z][a-zA-Z0-9]*_?$"/>
            <property name="severity" value="warning"/>
        </module>
        <module name="LocalVariableName">
            <property name="format" value="^[a-z][a-zA-Z0-9]*_?$"/>
            <property name="severity" value="warning"/>
        </module>
        <module name="MemberName">
            <property name="format" value="^[a-z][a-zA-Z0-9]*_?$"/>
            <property name="severity" value="warning"/>
        </module>
        <module name="MethodName"/>
        <module name="PackageName"/>
        <module name="ParameterName"/>
        <module name="StaticVariableNameCheck">
            <!-- Validates static, non-final fields against the supplied
            expression "^[a-z][a-zA-Z0-9]*_?$". -->
            <metadata name="altname" value="StaticVariableName"/>
            <property name="applyToPublic" value="true"/>
            <property name="applyToProtected" value="true"/>
            <property name="applyToPackage" value="true"/>
            <property name="applyToPrivate" value="true"/>
            <property name="format" value="^[a-z][a-zA-Z0-9]*_?$"/>
            <property name="severity" value="warning"/>
        </module>
        <module name="TypeName"/>

        <!-- Checks for Headers                                -->
        <!-- See http://checkstyle.sf.net/config_header.html   -->
        <!-- <module name="Header">                            -->
        <!-- The follow property value demonstrates the ability     -->
        <!-- to have access to ANT properties. In this case it uses -->
        <!-- the ${basedir} property to allow Checkstyle to be run  -->
        <!-- from any directory within a project. See property      -->
        <!-- expansion,                                             -->
        <!-- http://checkstyle.sf.net/config.html#properties        -->
        <!-- <property                                              -->
        <!--     name="headerFile"                                  -->
        <!--     value="${basedir}/java.header"/>                   -->
        <!-- </module> -->

        <!-- Following interprets the header file as regular expressions. -->
        <!-- <module name="RegexpHeader"/>                                -->

        <!-- Checks for imports                              -->
        <!-- See http://checkstyle.sf.net/config_import.html -->
        <!--<module name="AvoidStarImport"/>-->
        <module name="IllegalImport"/> <!-- defaults to sun.* packages -->
        <module name="RedundantImport"/>
        <module name="UnusedImports"/>

        <!-- Checks for Size Violations.                    -->
        <!-- See http://checkstyle.sf.net/config_sizes.html -->
        <module name="LineLength">
            <property name="max" value="${com.puppycrawl.tools.checkstyle.checks.sizes.LineLength.max}" default="120"/>
            <property name="ignorePattern"
                      value="${com.puppycrawl.tools.checkstyle.checks.sizes.LineLength.ignorePattern}"
                      default="^(package .*;\s*)|(import .*;\s*)|( *\* *https?://.*)$"/>
        </module>
        <module name="MethodLength"/>
        <module name="ParameterNumber">
            <property name="severity" value="warning"/>
        </module>

        <!-- Checks for whitespace                               -->
        <!-- See http://checkstyle.sf.net/config_whitespace.html -->
        <!--<module name="EmptyForIteratorPad"/>-->
        <module name="GenericWhitespace"/>
        <module name="MethodParamPad"/>
        <!--<module name="NoWhitespaceAfter"/>-->
        <!--<module name="NoWhitespaceBefore"/>-->
        <module name="OperatorWrap"/>
        <module name="ParenPad"/>
        <module name="TypecastParenPad"/>
        <module name="WhitespaceAfter"/>
        <module name="WhitespaceAround"/>

        <!-- Modifier Checks                                    -->
        <!-- See http://checkstyle.sf.net/config_modifiers.html -->
        <module name="ModifierOrder"/>
        <module name="RedundantModifier">
            <property name="severity" value="warning"/>
        </module>

        <!-- Checks for blocks. You know, those {}'s         -->
        <!-- See http://checkstyle.sf.net/config_blocks.html -->
        <module name="AvoidNestedBlocks"/>
        <!--<module name="EmptyBlock"/>-->
        <module name="LeftCurly"/>
        <!--<module name="NeedBraces"/>-->
        <module name="RightCurly"/>

        <!-- Checks for common coding problems               -->
        <!-- See http://checkstyle.sf.net/config_coding.html -->
        <!--<module name="AvoidInlineConditionals"/>-->
        <!--<module name="EmptyStatement"/>-->
        <module name="EqualsHashCode"/>
        <!--<module name="HiddenField"/>-->
        <module name="IllegalInstantiation"/>
        <!--<module name="InnerAssignment"/>-->
        <module name="MagicNumber">
            <property name="severity" value="warning"/>
        </module>
        <module name="MissingSwitchDefault"/>
        <module name="SimplifyBooleanExpression"/>
        <module name="SimplifyBooleanReturn"/>

        <!-- Checks for class design                         -->
        <!-- See http://checkstyle.sf.net/config_design.html -->
        <!--<module name="DesignForExtension"/>-->
        <module name="FinalClass"/>
        <module name="HideUtilityClassConstructor">
            <property name="severity" value="warning"/>
        </module>
        <module name="InterfaceIsType"/>
        <!--<module name="VisibilityModifier"/>-->

        <!-- Miscellaneous other checks.                   -->
        <!-- See http://checkstyle.sf.net/config_misc.html -->
        <module name="ArrayTypeStyle"/>
        <!--<module name="FinalParameters"/>-->
        <module name="TodoComment"/>
        <module name="UpperEll"/>

    </module>

</module>