text:
namespace SurgSim
{
namespace Graphics
{

RenderPass::RenderPass(const std::string& name) :
	SceneElement(name)
{
	m_camera = std::make_shared<OsgCamera>(getName() + " camera");
	m_camera->setRenderGroupReference(name);

	m_material = std::make_shared<OsgMaterial>("material");
	m_camera->setMaterial(m_material);
}

RenderPass::~RenderPass()
{

}

bool RenderPass::doInitialize()
{
	addComponent(m_camera);
	addComponent(m_material);
	return true;
}

std::shared_ptr<Camera> RenderPass::getCamera()
{
	return m_camera;
}

bool RenderPass::setRenderTarget(std::shared_ptr<RenderTarget> target)
{
	bool result = m_camera->setRenderTarget(target);
	if (result)
	{
		m_renderTarget = target;
	}
	return result;
}

std::shared_ptr<RenderTarget> RenderPass::getRenderTarget()
{
	return m_renderTarget;
}

bool RenderPass::setMaterial(std::shared_ptr<SurgSim::Framework::Component> material)
{
	bool result = m_camera->setMaterial(material);
	if (result)
	{
		m_material = std::dynamic_pointer_cast<Material>(material);
	}
	return result;
}

std::shared_ptr<Material> RenderPass::getMaterial()
{
	return m_material;
}

void RenderPass::setRenderOrder(SurgSim::Graphics::Camera::RenderOrder order, int value)
{
	m_camera->setRenderOrder(order, value);
}

void RenderPass::showColorTarget(int x, int y, int width, int height)
{
	if (m_debugColor == nullptr && m_renderTarget->getColorTargetCount() > 0)
	{
		auto texture = m_renderTarget->getColorTarget(0);
		m_debugColor = buildDebugQuad("debug color", texture);
	}
	if (m_debugColor != nullptr)
	{
		m_debugColor->setLocation(x, y);
		m_debugColor->setSize(width, height);
		m_debugColor->setLocalActive(true);
	}
}

void RenderPass::hideColorTarget()
{
	if (m_debugColor != nullptr)
	{
		m_debugColor->setLocalActive(false);
	}
}

void RenderPass::showDepthTarget(int x, int y, int width, int height)
{
	if (m_debugDepth == nullptr && m_renderTarget->doesUseDepthTarget())
	{
		auto texture = m_renderTarget->getDepthTarget();
		m_debugDepth = buildDebugQuad("debug depth", texture);
	}
	if (m_debugDepth != nullptr)
	{
		m_debugDepth->setLocation(x, y);
		m_debugDepth->setSize(width, height);
		m_debugDepth->setLocalActive(true);
	}
}

void RenderPass::hideDepthTarget()
{
	if (m_debugDepth != nullptr)
	{
		m_debugDepth->setLocalActive(false);
	}
}

std::shared_ptr<ScreenSpaceQuadRepresentation> RenderPass::buildDebugQuad(const std::string& name,
																		  std::shared_ptr<Texture> texture)
{
	auto result = std::make_shared<OsgScreenSpaceQuadRepresentation>(name);
	result->setTexture(texture);
	addComponent(result);
	return result;
}

}; // Graphics
}; // SurgSim


text:
#include "d3d7_canvas.h"
#include "ddraw_common.h"
#include "macro.h"
#include "utils.h"

namespace maku
{
namespace render
{
namespace ddrawhooker
{
const GUID IID_IDirect3DDevice7_T = {0xf5049e79, 0x4861, 0x11d2, 0xa4, 0x7, 0x0, 0xa0, 0xc9, 0x6, 0x29, 0xa8};
D3D7Canvas::D3D7Canvas(IDirect3DDevice7 * device)
{
    device7_ = device;
    state_block_ = 0;
    texture_ = NULL;
    back_buffer_ = NULL;
    last_render_target_ = NULL;
    last_texture_ = NULL;
}

D3D7Canvas::~D3D7Canvas()
{
    device7_ = NULL;
    SAFE_RELEASE(texture_);
}

void D3D7Canvas::CreateTexture(uint32_t width, uint32_t height)
{
    DDSURFACEDESC2 surfaceDesc;
    ::ZeroMemory(&surfaceDesc, sizeof(surfaceDesc));
    surfaceDesc.dwSize = sizeof(surfaceDesc);
    surfaceDesc.dwFlags = DDSD_CAPS | DDSD_WIDTH |
        DDSD_HEIGHT | DDSD_PIXELFORMAT ;
    surfaceDesc.ddsCaps.dwCaps = DDSCAPS_VIDEOMEMORY | DDSCAPS_TEXTURE | DDSCAPS_3DDEVICE;
    surfaceDesc.dwWidth = width;
    surfaceDesc.dwHeight = height;
    surfaceDesc.ddpfPixelFormat.dwSize = sizeof(DDPIXELFORMAT);
    surfaceDesc.ddpfPixelFormat.dwFlags = DDPF_RGB | DDPF_ALPHAPIXELS;
    surfaceDesc.ddpfPixelFormat.dwRGBBitCount = 32;
    surfaceDesc.ddpfPixelFormat.dwRBitMask = 0x00ff0000;
    surfaceDesc.ddpfPixelFormat.dwGBitMask = 0x0000ff00;
    surfaceDesc.ddpfPixelFormat.dwBBitMask = 0x000000ff;
    surfaceDesc.ddpfPixelFormat.dwRGBAlphaBitMask = 0xff000000;

    HRESULT hr = GetDirectDraw()->CreateSurface(&surfaceDesc, &texture_, NULL);
    if (hr != D3D_OK)
        texture_ = NULL;
}

IDirectDraw7* D3D7Canvas::GetDirectDraw()
{
    IDirect3D7* dd7 = NULL;
    IDirectDraw7* ddraw = NULL;

    device7_->GetDirect3D(&dd7);
    dd7->QueryInterface(IID_IDirectDraw7_T, (void**)&ddraw);

    if (ddraw != NULL)
    {
        dd7->Release();
        ddraw->Release();
    }
    return ddraw;
}

void D3D7Canvas::GetTextureWH(uint32_t & width, uint32_t & height)
{
    if (texture_)
    {
        DDSURFACEDESC2 surfaceDesc;
        ::ZeroMemory(&surfaceDesc, sizeof(surfaceDesc));
        surfaceDesc.dwSize = sizeof(surfaceDesc);
        texture_->GetSurfaceDesc(&surfaceDesc);
        width = surfaceDesc.dwWidth;
        height = surfaceDesc.dwHeight;
    }
    else
    {
        width = 0;
        height = 0;
    }
}

bool D3D7Canvas::UpdateTexture(Bitmap & bmp_info)
{
    DDSURFACEDESC2 surfaceDesc;
    ::ZeroMemory(&surfaceDesc, sizeof(surfaceDesc));
    surfaceDesc.dwSize = sizeof(surfaceDesc);

    HRESULT hr = texture_->Lock(NULL, &surfaceDesc, DDLOCK_WAIT, NULL);
    char* src_buf = bmp_info.bits;

    if (SUCCEEDED(hr))
    {
        uint32_t pitch = surfaceDesc.lPitch;
        uint32_t height = surfaceDesc.dwHeight;

        char* dst_buf = reinterpret_cast<char*>(surfaceDesc.lpSurface);
        uint32_t copy_width = pitch > bmp_info.pitch ?
            bmp_info.pitch : pitch;
        uint32_t copy_height = height > bmp_info.height ?
                               bmp_info.height : height;

        for (uint32_t i = 0; i < copy_height; ++i)
        {
            memcpy_s(dst_buf + i*pitch, pitch, src_buf, copy_width);
            src_buf += copy_width;
        }
        texture_->Unlock(NULL);
    }
    else
    {
        SAFE_RELEASE(texture_);
        return false;
    }
    return true;
}

void D3D7Canvas::SetRenderTarget(LPDIRECTDRAWSURFACE7 back_buffer, const Rect & rect)
{
    back_buffer_ = back_buffer;
    rect_ = rect;
}

void D3D7Canvas::SaveStatus()
{
    device7_->CreateStateBlock(D3DSBT_ALL, &state_block_);
    device7_->CaptureStateBlock(state_block_);

    device7_->GetRenderTarget(&last_render_target_);
    device7_->GetTexture(0, &last_texture_);//sacred.exe
    //
    Prepare();
}

void D3D7Canvas::RestoreStatus()
{
    device7_->ApplyStateBlock(state_block_);
    device7_->DeleteStateBlock(state_block_);

    device7_->SetRenderTarget(last_render_target_, 0);
    SAFE_RELEASE(last_render_target_);
    SAFE_RELEASE(last_texture_);
}

void D3D7Canvas::Prepare()
{
    device7_->SetTextureStageState(0,  D3DTSS_ADDRESS,   D3DTADDRESS_WRAP);
    device7_->SetTextureStageState(0,  D3DTSS_MAGFILTER, D3DTFG_POINT);
    device7_->SetTextureStageState(0,  D3DTSS_MINFILTER, D3DTFG_POINT);
    device7_->SetTextureStageState(0,  D3DTSS_MIPFILTER, D3DTFP_NONE);
    device7_->SetRenderState(D3DRENDERSTATE_ALPHABLENDENABLE, TRUE);
    device7_->SetRenderState(D3DRENDERSTATE_SRCBLEND,  D3DBLEND_SRCALPHA);
    device7_->SetRenderState(D3DRENDERSTATE_DESTBLEND, D3DBLEND_INVSRCALPHA);
    device7_->SetRenderState(D3DRENDERSTATE_CLIPPLANEENABLE, FALSE);
    device7_->SetRenderState(D3DRENDERSTATE_ZENABLE, FALSE);
    device7_->SetRenderState(D3DRENDERSTATE_ZWRITEENABLE, TRUE);
    device7_->SetRenderState(D3DRENDERSTATE_CULLMODE, 3);
}

void D3D7Canvas::SetTextureState()
{
    device7_->SetTextureStageState(0, D3DTSS_TEXCOORDINDEX, 0);
    device7_->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
    device7_->SetTextureStageState(0, D3DTSS_COLOROP,   D3DTOP_SELECTARG1);
    device7_->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE);
    device7_->SetTextureStageState(0, D3DTSS_ALPHAOP,   D3DTOP_SELECTARG1);
}

void D3D7Canvas::SetDiffuseState()
{
    device7_->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_DIFFUSE);
    device7_->SetTextureStageState(0, D3DTSS_COLOROP,   D3DTOP_SELECTARG1);
    device7_->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_DIFFUSE);
    device7_->SetTextureStageState(0, D3DTSS_ALPHAOP,   D3DTOP_SELECTARG1);
}

void D3D7Canvas::DrawRect(const Rect & rect, const Paint & paint)
{
    SimpleVertex cv_buffer[4];
    cv_buffer[0] = SimpleVertex((float)rect.left(),
        (float)rect.top(), 0.5f, paint.color);
    cv_buffer[1] = SimpleVertex((float)rect.right(),
        (float)rect.top(), 0.5f, paint.color);
    cv_buffer[2] = SimpleVertex((float)rect.left(),
        (float)rect.bottom(), 0.5f, paint.color);
    cv_buffer[3] = SimpleVertex((float)rect.right(),
        (float)rect.bottom(), 0.5f, paint.color);

    SetDiffuseState();
    device7_->DrawPrimitive(D3DPT_TRIANGLESTRIP, SimpleVertex::GetFVF(),
        (LPVOID)cv_buffer, 4, 0);
}

void D3D7Canvas::DrawBitmap(Bitmap & bmp_info, const Rect & dest)
{
    if (NULL == back_buffer_)
        return;
    HRESULT hr = device7_->SetRenderTarget(back_buffer_, 0);
    if(FAILED(hr))
        return;
    DDSURFACEDESC2 surfaceDesc;
    ::ZeroMemory(&surfaceDesc, sizeof(surfaceDesc));
    surfaceDesc.dwSize = sizeof(surfaceDesc);
    back_buffer_->GetSurfaceDesc(&surfaceDesc);

    D3DVIEWPORT7 port = {0, 0, surfaceDesc.dwWidth,
        surfaceDesc.dwHeight,
        0.0f, 1.0f};
    hr = device7_->SetViewport(&port);
    if(FAILED(hr))
        return;

    //set state
    SetTextureState();

    uint32_t width = 0;
    uint32_t height = 0;
    GetTextureWH(width, height);
    //create or update
    if (bmp_info.width > width || bmp_info.height > height)
    {
        //delete texture
        if (texture_)
            SAFE_RELEASE(texture_);
        //recreate texture
        CreateTexture(bmp_info.width, bmp_info.height);
    }
    //
    if (!UpdateTexture(bmp_info))
        return;

    GetTextureWH(width, height);
    if(width == 0 || height == 0)
        return;
    //update vertex data
    float max_u = (float)(bmp_info.width) / width;
    float max_v = (float)(bmp_info.height) / height;

    SimpleVertex vertex_buffer[4];
    vertex_buffer[0] = SimpleVertex(-0.5f + dest.left() + rect_.left(),
        -0.5f + dest.top() + rect_.top(), 0.0f, 1.0f, 0.0f, 0.0f);
    vertex_buffer[1] = SimpleVertex(-0.5f + dest.right() + rect_.left(),
        -0.5f + dest.top() + rect_.top(), 0.0f, 1.0f, max_u, 0.0f);
    vertex_buffer[2] = SimpleVertex(-0.5f + dest.left() + rect_.left(),
        -0.5f + dest.bottom() + rect_.top(), 0.0f, 1.0f, 0.0f, max_v);
    vertex_buffer[3] = SimpleVertex(-0.5f + dest.right() + rect_.left(),
        -0.5f + dest.bottom() + rect_.top(), 0.0f, 1.0f, max_u, max_v);

    //draw
    device7_->SetTexture(0, texture_);
    device7_->DrawPrimitive(D3DPT_TRIANGLESTRIP, SimpleVertex::GetFVF(),
        (LPVOID)vertex_buffer, 4, 0);
}

void D3D7Canvas::DrawLine(const Point & p1,
                                              const Point & p2,
                                              const Paint & paint)
{
    SimpleVertex cv_buffer[2];
    cv_buffer[0] = SimpleVertex(p1, paint.color);
    cv_buffer[1] = SimpleVertex(p2, paint.color);

    SetDiffuseState();
    device7_->DrawPrimitive(D3DPT_LINELIST, SimpleVertex::GetFVF(),
        (LPVOID)cv_buffer, 2, 0);
}

void D3D7Canvas::DrawPoint(const Point & p1, const Paint & paint)
{
    SimpleVertex sv(p1, paint.color);

    SetDiffuseState();
    device7_->DrawPrimitive(D3DPT_POINTLIST, SimpleVertex::GetFVF(),
        (LPVOID)&sv, 1, 0);
}
}
}
}

redpajama_set_name: RedPajamaGithub


text:
// Copyright 2016 by Thorsten von Eicken, see LICENSE file

package sx1231

import "fmt"

// JeeLabsSync returns a byte array of sync bytes given the group number.
func JeeLabsSync(grp byte) []byte {
	return []byte{0x2d, grp}
}

// JLEncode encodes a JeeLabs packet.
//
// Jeelabs native rfm69 packet format
//
// From the radio's perspective, a packet has 5 preamble bytes, 2 sync bytes, a length byte, a
// dest address byte, up to 64 payload bytes, and 2-byte CRC. The length counts the payload plus the dest
// address.
//
// The JeeLabs format defines the 5-byte preamble (the radio allows many options) and the 2 sync
// bytes. The first sync byte is 0x2d, the second is the group ID (network number).
// The JeeLabs format also uses the first payload byte as a source address. This means that
// the application payload can hold up to 63 bytes. Finally, in newer JeeLabs usage the first payload
// byte (after the src address) is a packet type format byte.
//
// The destination address byte is calculated as the 6-bit destination node ID and two sync parity bits
// at the top. Bit 7 (MSB) is calculated as the group's b7^b5^b3^b1 and bit 6 as the group's
// b6^b4^b2^b0.
//
// The source address byte is calculated as the 6-bit source node ID and two control bits. Bit 7 is an
// ACK request bit and bit 6 is unassigned.
//
// A packet with destination ID 0 is a broadcast packet, a node ID of 62 is used for
// anonymouns tx-only nodes, and a node ID of 63 is used on the receiving end to denote a node
// that receives all packets regardless of destination (promiscuous mode).
func JLEncode(grp, src, dst byte, ack bool, payload []byte) []byte {
	p7 := ((grp >> 7) & 1) ^ ((grp >> 5) & 1) ^ ((grp >> 3) & 1) ^ ((grp >> 1) & 1)
	p6 := ((grp >> 6) & 1) ^ ((grp >> 4) & 1) ^ ((grp >> 2) & 1) ^ ((grp >> 0) & 1)
	a := byte(0)
	if ack {
		a = 0x80
	}
	p := make([]byte, len(payload)+2)
	p[0] = (dst & 0x3f) | (p7 << 7) | (p6 << 6)
	p[1] = (src & 0x3f) | a
	copy(p[2:], payload)
	return p
}

// MakeJLAck returns an ACK packet given a received payload with the ack bit set.
func MakeJLAck(grp byte, payload []byte) []byte {
	if src, dst, ack, _, err := JLDecode(grp, payload); err == nil && ack {
		return JLEncode(grp, dst, src, false, nil)
	}
	return nil
}

// JLDecode decodes a JeeLabs packet. See JLEncode for a description of the
// packet format. The outPayload it returns has the src/dst stripped.
func JLDecode(grp byte, payload []byte) (
	src, dst byte, ack bool, outPayload []byte, err error,
) {
	if len(payload) < 2 {
		err = fmt.Errorf("sx1231 JeeLabs decode: packet too short: %d bytes",
			len(payload))
		return
	}

	// check group parity bits.
	p7 := ((grp >> 7) & 1) ^ ((grp >> 5) & 1) ^ ((grp >> 3) & 1) ^ ((grp >> 1) & 1)
	p6 := ((grp >> 6) & 1) ^ ((grp >> 4) & 1) ^ ((grp >> 2) & 1) ^ ((grp >> 0) & 1)
	if payload[0]&0xc0 != (p7<<7)|(p6<<6) {
		err = fmt.Errorf(
			"sx1231 JeeLabs decode: bad group parity: got %#x want %#x for group %d",
			payload[0]&0xc0, (p7<<7)|(p6<<6), grp)
		return
	}

	dst = payload[0] & 0x3f
	src = payload[1] & 0x3f
	ack = payload[1]&0x80 != 0
	outPayload = payload[2:]
	return
}

/* deprecated in favor of mqttradio GW type of structure

// JLRxPacket holds a decoded JeeLabs packet.
type JLRxPacket struct {
	Src, Dst byte // source and destination nodes from packet header
	Ack      bool // ACK request bit from packet header
	RxPacket
}

type JLTxPacket struct {
	Src, Dst byte // source and destination nodes for packet header
	Ack      bool // ACK request bit for packet header
	Payload  []byte
}

// JLAckHandler spawns a goroutine that mediates the TX and RX channels in order to retransmit
// outgoing packets that are unacked and to reply with ACKs when incoming packets request so.
func JLAckHandler(radio *Radio, grp byte) (chan<- *JLTxPacket, <-chan *JLRxPacket) {
	txChan := make(chan *JLTxPacket, 1)
	rxChan := make(chan *JLRxPacket, 1)
	go func() {
		waitingForAck := false
		for {
			if waitingForAck {
				// Ignore txChan until we get ack or give up.
				select {
				case rxPkt := <-radio.RxChan:
					jlPkt, err := JLDecode(grp, rxPkt)
					if err != nil {
						radio.log("%s", err.Error())
						break
					}
					if jlPkt.IsAck() {
						waitingForAck = false
						break
					}
					rxChan <- jlPkt
				}
			} else {
				// Handle both txChan and rxChan.
				select {
				case txPkt := <-txChan:
					jlPkt := JLEncode(grp, txPkt.Src, txPkt.Dst, txPkt.Ack, txPkt.Payload)
					radio.txChan <- jlPkt
					waitingForAck = txPkt.Ack
				case rxPkt := <-radio.RxChan:
					jlPkt, err := JLDecode(grp, rxPkt)
					if err != nil {
						radio.log("%s", err.Error())
						break
					}
					rxChan <- jlPkt
				}
			}
		}
	}()
	return txChan, rxChan
}

*/


text:
package es.minetsii.eggwars.objects;

import java.util.Set;

import org.bukkit.Location;
import org.bukkit.entity.Villager;

public class Team {

	public Team(Location egg, Location villager, Location spawn, Location respawn, int id) {
	}

	public Set<EwPlayer> getPlayers() {
		return null;
	}

	public Set<EwPlayer> getPlayersAlive(){
		return null;
	}

	public Location getEgg() {
		return null;
	}

	public void setEgg(Location egg) {
	}

	public Villager getVillager() {
		return null;
	}

	public void setVillager(Villager villager) {
	}

	public Arena getArena() {
		return null;
	}

	public Location getSpawn() {
		return null;
	}

	public void setSpawn(Location spawn) {
	}

	public boolean canRespawn(){
		return false;
	}

	public void addPlayer(EwPlayer pl){
	}

	public Location getRespawn() {
		return null;
	}

	public void setRespawn(Location respawn) {
	}

	public Location getVillagerLoc() {
		return null;
	}

	public void setVillagerLoc(Location villagerLoc) {
	}

	public org.bukkit.scoreboard.Team getMcTeam() {
		return null;
	}

	public void setMcTeam(org.bukkit.scoreboard.Team mcTeam) {
	}

	public int getId() {
		return 0;
	}

	public void spawnVillager(){
	}

	public boolean isEliminated(){
		return false;
	}

	public void setGlass(){
	}

	public void removeGlass(){
	}

	public void spawnPlayers(){
	}

	public void setEgg(){
	}

	public void removeVillager(){
	}

	public void sendBroadcast(String s, boolean languageNode, Object... obj){
	}

    @Override
    public int hashCode() {
    	return 0;
    }

    @Override
    public boolean equals(Object obj) {
    	return false;
    }

}


text:
package json

import (
	"encoding/json"
	"math/big"
)

// DHParams can be used to store finite-field Diffie-Hellman parameters. At any
// point in time, it is unlikely that both OurPrivate and TheirPrivate will be
// non-nil.
type DHParams struct {
	Prime         *big.Int
	Generator     *big.Int
	ServerPublic  *big.Int
	ServerPrivate *big.Int
	ClientPublic  *big.Int
	ClientPrivate *big.Int
	SessionKey    *big.Int
}

type auxDHParams struct {
	Prime         *cryptoParameter `json:"prime"`
	Generator     *cryptoParameter `json:"generator"`
	ServerPublic  *cryptoParameter `json:"server_public,omitempty"`
	ServerPrivate *cryptoParameter `json:"server_private,omitempty"`
	ClientPublic  *cryptoParameter `json:"client_public,omitempty"`
	ClientPrivate *cryptoParameter `json:"client_private,omitempty"`
	SessionKey    *cryptoParameter `json:"session_key,omitempty"`
}

// MarshalJSON implements the json.Marshal interface
func (p *DHParams) MarshalJSON() ([]byte, error) {
	aux := auxDHParams{
		Prime:     &cryptoParameter{Int: p.Prime},
		Generator: &cryptoParameter{Int: p.Generator},
	}
	if p.ServerPublic != nil {
		aux.ServerPublic = &cryptoParameter{Int: p.ServerPublic}
	}
	if p.ServerPrivate != nil {
		aux.ServerPrivate = &cryptoParameter{Int: p.ServerPrivate}
	}
	if p.ClientPublic != nil {
		aux.ClientPublic = &cryptoParameter{Int: p.ClientPublic}
	}
	if p.ClientPrivate != nil {
		aux.ClientPrivate = &cryptoParameter{Int: p.ClientPrivate}
	}
	if p.SessionKey != nil {
		aux.SessionKey = &cryptoParameter{Int: p.SessionKey}
	}
	return json.Marshal(aux)
}

// UnmarshalJSON implement the json.Unmarshaler interface
func (p *DHParams) UnmarshalJSON(b []byte) error {
	var aux auxDHParams
	if err := json.Unmarshal(b, &aux); err != nil {
		return err
	}
	if aux.Prime != nil {
		p.Prime = aux.Prime.Int
	}
	if aux.Generator != nil {
		p.Generator = aux.Generator.Int
	}
	if aux.ServerPublic != nil {
		p.ServerPublic = aux.ServerPublic.Int
	}
	if aux.ServerPrivate != nil {
		p.ServerPrivate = aux.ServerPrivate.Int
	}
	if aux.ClientPublic != nil {
		p.ClientPublic = aux.ClientPublic.Int
	}
	if aux.ClientPrivate != nil {
		p.ClientPrivate = aux.ClientPrivate.Int
	}
	if aux.SessionKey != nil {
		p.SessionKey = aux.SessionKey.Int
	}
	return nil
}

// CryptoParameter represents a big.Int used a parameter in some cryptography.
// It serializes to json as a tupe of a base64-encoded number and a length in
// bits.
type cryptoParameter struct {
	*big.Int
}

type auxCryptoParameter struct {
	Raw    []byte `json:"value"`
	Length int    `json:"length"`
}

// MarshalJSON implements the json.Marshaler interface
func (p *cryptoParameter) MarshalJSON() ([]byte, error) {
	var aux auxCryptoParameter
	if p.Int != nil {
		aux.Raw = p.Bytes()
		aux.Length = 8 * len(aux.Raw)
	}
	return json.Marshal(&aux)
}

// UnmarshalJSON implements the json.Unmarshal interface
func (p *cryptoParameter) UnmarshalJSON(b []byte) error {
	var aux auxCryptoParameter
	if err := json.Unmarshal(b, &aux); err != nil {
		return err
	}
	p.Int = new(big.Int)
	p.SetBytes(aux.Raw)
	return nil
}


text:
package daemon // import "go.pedge.io/openflights/daemon"

import (
	"fmt"
	"net/http"
	"os"

	"go.pedge.io/lion"
	"go.pedge.io/lion/env"
	"go.pedge.io/openflights"
	"go.pedge.io/proto/server"
	"google.golang.org/grpc"
)

// DoOptions are options for Do.
type DoOptions struct {
	GRPCGatewayModifier func(openflights.Client, http.Handler) (http.Handler, error)
}

// Do runs the daemon.
func Do(options DoOptions) error {
	if err := envlion.Setup(); err != nil {
		return err
	}
	client, err := openflights.NewDefaultServerClientWithOptions(
		openflights.CodeStoreOptions{
			LogFunc: lion.Infof,
		},
	)
	if err != nil {
		return err
	}
	return protoserver.GetAndServeWithHTTP(
		func(grpcServer *grpc.Server) {
			openflights.RegisterAPIServer(grpcServer, openflights.NewAPIServer(client))
		},
		openflights.RegisterAPIHandler,
		protoserver.ServeWithHTTPOptions{
			HTTPHandlerModifier: func(httpHandler http.Handler) (http.Handler, error) {
				if options.GRPCGatewayModifier == nil {
					return httpHandler, nil
				}
				return options.GRPCGatewayModifier(client, httpHandler)
			},
		},
	)
}

// Main is Do but with errors handled.
func Main(options DoOptions) {
	if err := Do(options); err != nil {
		fmt.Fprintf(os.Stderr, "%s\n", err.Error())
		os.Exit(1)
	}
	os.Exit(0)
}


text: <!DOCTYPE html>


text:
const crypto    = require('crypto');
const fs        = require('fs');

//Configurations
const encryptionAlgorithm = 'aes-256-ctr';
const key = '$myvirus_sample_encryption_key!!';

//Get the target file name from the first command line parameter
const fileName = process.argv[2];

//Read file and execute callback with file content
function readFileContents(file, callback) {
    fs.readFile(file, (err, data)=>{
        if (err) throw err;
        callback(data);
    });
}

//Receive encrypted file content and a password and return the original file content
function decryptFile(fileContents, password) {
    let decipher = crypto.createDecipher(encryptionAlgorithm,password);
    return Buffer.concat([decipher.update(fileContents), decipher.final()]);
}

//Save data to a file located at fileLocation and execute the callback with fileLocation
function saveToFile(fileLocation, data, callback){
    fs.writeFile(fileLocation, data, (err)=>{
        if(err) {
            return console.log(err);
        }
        callback(fileLocation);
    });
}

//Read file content, decipher it and overwrite the encrypted file
readFileContents(fileName, (fileData)=>{
    let fileByteData = decryptFile(fileData, key);
    saveToFile(fileName, fileByteData, (fileName)=>{
        console.log(fileName+' decrypted')
    })
});


text:
`cozy-konnector-libs` also comes with some cli tools which allow to run your connector in standalone
or development mode

#### cozy-konnector-standalone

If you just want to test your connector without any cozy available. Just add the following code in
the `scripts` section of your package.json file

```javascript
  scripts: {
    standalone: "cozy-konnector-standalone"
  }
```

and run:

```sh
npm run standalone
```

The requests to the cozy-stack will be stubbed using the [./fixture.json] file as source of data
and when cozy-client-js is asked to create or update data, the data will be output to the console.
The bills (or any file) will be saved in the . directory.

#### cozy-konnector-dev

If you want to run your connector linked to a cozy-stack, even remotely. Just add the follwing code
in the `scripts` section of your package.json file:

```javascript
  scripts: {
    dev: "cozy-konnector-dev"
  }
```

and run:

```sh
npm run dev
```

This command will register your konnector as an OAuth application to the cozy-stack. By default,
the cozy-stack is supposed to be located in http://cozy.tools:8080. If this is not your case, just
update the COZY_URL field in [./konnector-dev-config.json].

After that, your konnector is running but should not work since you did not specify any credentials to
the target service. You can do this also in [./konnector-dev-config.json] in the "fields" section

The files are saved in the root directory of your cozy by default.


text:
<?xml version="1.0" encoding="UTF-8"?>
<configurationDescriptor version="89">
  <logicalFolder name="root" displayName="root" projectFiles="true" kind="ROOT">
    <df root="." name="CoMinipure">
      <df name="binary">
      </df>
      <df name="code">
        <df name="core">
          <in>Dimacs.h</in>
          <in>Main.cc</in>
          <in>Solver.cc</in>
          <in>Solver.h</in>
          <in>SolverTypes.h</in>
        </df>
        <df name="mtl">
          <in>Alg.h</in>
          <in>Alloc.h</in>
          <in>Heap.h</in>
          <in>IntTypes.h</in>
          <in>Map.h</in>
          <in>Queue.h</in>
          <in>Sort.h</in>
          <in>Vec.h</in>
          <in>XAlloc.h</in>
        </df>
        <df name="simp">
          <in>Main.cc</in>
          <in>Main.or</in>
          <in>SimpSolver.cc</in>
          <in>SimpSolver.h</in>
        </df>
        <df name="utils">
          <in>Options.cc</in>
          <in>Options.h</in>
          <in>ParseUtils.h</in>
          <in>System.cc</in>
          <in>System.h</in>
        </df>
      </df>
    </df>
  </logicalFolder>
  <projectmakefile>Makefile</projectmakefile>
  <confs>
    <conf name="Default" type="0">
      <toolsSet>
        <developmentServer>localhost</developmentServer>
        <platform>2</platform>
      </toolsSet>
      <compile>
        <compiledirpicklist>
          <compiledirpicklistitem>.</compiledirpicklistitem>
          <compiledirpicklistitem>${AUTO_FOLDER}</compiledirpicklistitem>
        </compiledirpicklist>
        <compiledir>${AUTO_FOLDER}</compiledir>
        <compilecommandpicklist>
          <compilecommandpicklistitem>${MAKE} ${ITEM_NAME}.o</compilecommandpicklistitem>
          <compilecommandpicklistitem>${AUTO_COMPILE}</compilecommandpicklistitem>
        </compilecommandpicklist>
        <compilecommand>${AUTO_COMPILE}</compilecommand>
      </compile>
      <dbx_gdbdebugger version="1">
        <gdb_pathmaps>
        </gdb_pathmaps>
        <gdb_interceptlist>
          <gdbinterceptoptions gdb_all="false" gdb_unhandled="true" gdb_unexpected="true"/>
        </gdb_interceptlist>
        <gdb_options>
          <DebugOptions>
          </DebugOptions>
        </gdb_options>
        <gdb_buildfirst gdb_buildfirst_overriden="false" gdb_buildfirst_old="false"/>
      </dbx_gdbdebugger>
      <nativedebugger version="1">
        <engine>gdb</engine>
      </nativedebugger>
      <runprofile version="9">
        <runcommandpicklist>
          <runcommandpicklistitem>"${OUTPUT_PATH}"</runcommandpicklistitem>
          <runcommandpicklistitem>"${OUTPUT_PATH}" ../../../../../Benchmarks/fiasco.dimacs</runcommandpicklistitem>
          <runcommandpicklistitem>"${OUTPUT_PATH}" ../../../../Benchmarks/fiasco.dimacs</runcommandpicklistitem>
          <runcommandpicklistitem>"${OUTPUT_PATH}" ../../../Benchmarks/fiasco.dimacs ../../../Benchmarks/fiasco.communities</runcommandpicklistitem>
          <runcommandpicklistitem>"${OUTPUT_PATH}" ../../../Benchmarks/fiasco.dimacs</runcommandpicklistitem>
        </runcommandpicklist>
        <runcommand>"${OUTPUT_PATH}" ../../../Benchmarks/fiasco.dimacs</runcommand>
        <rundir>.</rundir>
        <buildfirst>false</buildfirst>
        <terminal-type>0</terminal-type>
        <remove-instrumentation>0</remove-instrumentation>
        <environment>
        </environment>
      </runprofile>
    </conf>
  </confs>
</configurationDescriptor>


text:
var casper = require('casper').create();

casper.start('http://casperjs.org/', function() {
    this.echo(this.getTitle());
    this.echo("hiennnnnnnnnnn");
});

casper.thenOpen('http://phantomjs.org', function() {
    this.echo(this.getTitle());
});

casper.run();


text:
using System;
using System.Runtime.InteropServices;

namespace StressTest
{
   public static class NativeInterface
    {
        [DllImport("TestDLL")]
        public static extern int AddMoney();
        [DllImport("TestDLL")]
        public static extern int GetValueRef(ref int param);
        [DllImport("TestDLL")]
        public static extern int SetArray(byte[] arr, int length);
        [DllImport("TestDLL")]
        public static extern IntPtr GetArray();

        public static int[] GetIntArrayByPtr(IntPtr ptr,int len)
        {
            int[] ret = new int[len];
            Marshal.Copy(ptr, ret, 0, len);
            return ret;
        }
        public static byte[] GetByteArrayByPtr(IntPtr ptr, int len)
        {
            byte[] ret = new byte[len];
            Marshal.Copy(ptr, ret, 0, len);
            return ret;
        }
    }
}


text:
@interface XFTextView : UITextView<UITextViewDelegate>

//- (void)requireGestureRecognizerToFail:(UIGestureRecognizer*)gestureRecognizer;

@property (nonatomic) NSString *placeholder;
@property(nonatomic,strong) UILabel *lab_placeholder;

- (id)initWithFrame:(CGRect)frame placeholder:(NSString *)placeholder;

@end


text:
angular
  .module('tas')
  .config(authConfig)
  .run(privateRoutes);

function authConfig($routeProvider){
  $routeProvider
    .when('/login', {
      templateUrl: 'js/auth/login.html',
      controller: 'AuthController',
      controllerAs: 'auth',
      resolve: {
        data: function ($location, authFactory) {
          if(authFactory.isLoggedIn()) {
            $location.path('/tas');
          }
        }
      }
    })
    .when('/logout', {
      template: '',
      controller: 'LogoutController'
    });
  }

  function privateRoutes($rootScope, authFactory, $location){
    $rootScope.$on('$routeChangeStart', function (event, nextRoute) {

      $rootScope.user = authFactory.getAuth();

      if (nextRoute.$$route.private && !authFactory.isLoggedIn()) {
        $location.path('/login');
      }
    });
  }


text:
<!DOCTYPE html>

      <title></title>

LinkedIn

Home

What is LinkedIn

Join Today

Sign In

 Email: <input type="text">

 Password: <input type="text">

<input type="button" value="Sign in">

Over 175 million professional use LinkedIn to exchange information, ideas and opportunities

stay informed about your contacts and industry

Find the people and knowledge you need to achieve your goals

Control your professional identity online

Join LinkedIn Today

Sign Up

First Name:

               <input type="text" name="FirstName">

Last Name:

               <input type="text" name="LastName">

Email:

               <input type="text" name="Email">

Password

               <input type="text" name="Password">

               6 or more charachters

         <input type="button" value="Join Now">

         Already in LinkedIn? Sign in

Search for someone by name:

First Name <input type = "text" placeholder="First Name">

Last Name <input type = "text" placeholder="Last Name">

         <input type="button" value="Go">


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
        id="parent"
        layout_width="match_parent"
        layout_height="match_parent">

    <UIButton
            id="left"
            layout_gravity="left"
            text="View"
            layout_width="wrap_content"
            layout_height="wrap_content" />

    <UIButton
            id="right"
            layout_gravity="right"
            text="View"
            layout_width="wrap_content"
            layout_height="wrap_content" />

    <UIButton
            id="center_horizontal"
            layout_gravity="center_horizontal"
            text="View"
            layout_width="wrap_content"
            layout_height="wrap_content" />

    <UIButton
            id="left_center_vertical"
            layout_gravity="center_vertical|left"
            text="View"
            layout_width="wrap_content"
            layout_height="wrap_content" />

    <UIButton
            id="right_center_vertical"
            layout_gravity="center_vertical|right"
            text="View"
            layout_width="wrap_content"
            layout_height="wrap_content" />

    <UIButton
            id="center"
            layout_gravity="center"
            text="View"
            layout_width="wrap_content"
            layout_height="wrap_content" />

    <UIButton
            id="left_bottom"
            layout_gravity="bottom|left"
            text="View"
            layout_width="wrap_content"
            layout_height="wrap_content" />

    <UIButton
            id="right_bottom"
            layout_gravity="bottom|right"
            text="View"
            layout_width="wrap_content"
            layout_height="wrap_content" />

    <UIButton
            id="center_horizontal_bottom"
            layout_gravity="bottom|center_horizontal"
            text="View"
            layout_width="wrap_content"
            layout_height="wrap_content" />

</LinearLayout>


text:
package com.thaiopensource.xml.dtd.om;

public class DatatypeRef extends Datatype {

  private final String name;
  private final Datatype datatype;

  public DatatypeRef(String name, Datatype datatype) {
    this.name = name;
    this.datatype = datatype;
  }

  public int getType() {
    return DATATYPE_REF;
  }

  public Datatype getDatatype() {
    return datatype;
  }

  public String getName() {
    return name;
  }

  public void accept(DatatypeVisitor visitor) throws Exception {
    visitor.datatypeRef(name, datatype);
  }

  public Datatype deref() {
    return datatype.deref();
  }
}


text:
title: default
description: Allows setting a default value that can be returned if a first value is not set.
qref: "Returns a default value if a value is not set when checked."
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
keywords: [defaults]
categories: [functions]
menu:
  docs:
    parent: "functions"
toc:
signature: ["default DEFAULT INPUT"]
workson: []
hugoversion:
relatedfuncs: []
deprecated: false
draft: false
aliases: []
---

`default` checks whether a given value is set and returns a default value if it is not. *Set* in this context means different things depending on the data type:

* non-zero for numeric types and times
* non-zero length for strings, arrays, slices, and maps
* any boolean or struct value
* non-nil for any other types

`default` function examples reference the following content page:

{{< code file="content/posts/default-function-example.md" >}}
---
title: Sane Defaults
seo_title:
date: 2017-02-18
font:
oldparam: The default function helps make your templating DRYer.
newparam:
---
{{< /code >}}

`default` can be written in more than one way:

```
{{ index .Params "font" | default "Roboto" }}
{{ default "Roboto" (index .Params "font") }}
```

Both of the above `default` function calls return `Roboto`.

A `default` value, however, does not need to be hard coded like the previous example. The `default` value can be a variable or pulled directly from the front matter using dot notation:

{{< code file="variable-as-default-value.html" nocopy="true" >}}
{{$old := .Params.oldparam }}
<p>{{ .Params.newparam | default $old }}</p>
{{< /code >}}

Which would return:

```
<p>The default function helps make your templating DRYer.</p>
```

And then using dot notation

{{< code file="dot-notation-default-value.html" >}}
<title>{{ .Params.seo_title | default .Title }}</title>
{{< /code >}}

Which would return

{{< output file="dot-notation-default-return-value.html" >}}
<title>Sane Defaults</title>
{{< /output >}}

The following have equivalent return values but are far less terse. This demonstrates the utility of `default`:

Using `if`:

{{< code file="if-instead-of-default.html" nocopy="true" >}}
<title>{{if .Params.seo_title}}{{.Params.seo_title}}{{else}}{{.Title}}{{end}}</title>
=> Sane Defaults
{{< /code >}}

Using `with`:

{{< code file="with-instead-of-default.html" nocopy="true" >}}
<title>{{with .Params.seo_title}}{{.}}{{else}}{{.Title}}{{end}}</title>
=> Sane Defaults
{{< /code >}}


text:
<?php

namespace Coogle\Database;

use Coogle\Utils\Registry;

/**
 * Our Database driver, which is an extension of PDO
 * with it tied into our configuration system
 */
class Driver extends \PDO
{
	/**
	 * @var self
	 */
	static protected $_instance = null;

	/**
	 * @var array
	 */
	protected $_config;

	/**
	 * Singleton pattern to make sure we don't keep
	 * making DB connections.
	 * @return self
	 */
	static public function getInstance()
	{
		if(is_null(static::$_instance) || !(static::$_instance instanceof self)) {

			$config = Registry::get('Config')['database'];

			$dsn = "mysql:host={$config['host']};dbname={$config['database']}";

			static::$_instance = new static($dsn, $config['username'], $config['password'], $config['options']);
		}

		return static::$_instance;
	}

	/**
	 * @return the $_config
	 */
	public function getConfig() {
		return $this->_config;
	}

	/**
	 * @param array $_config
	 */
	public function setConfig(array $_config) {
		$this->_config = $_config;
		return $this;
	}

	/**
	 * The constructor
	 *
	 * @param string $message
	 * @param string $code
	 * @param string $previous
	 */
	public function __construct ($message = null, $code = null, $previous = null)
	{
		parent::__construct($message, $code, $previous);

		$this->setConfig(Registry::get('Config')['database']);
	}

}


text:
BOOST_AUTO_TEST_SUITE(test_puissance)

    BOOST_AUTO_TEST_CASE(test_puissance_modulaire) {
        BOOST_CHECK_EQUAL(puissance::puissance_modulaire(2u, 10u, 100u), 24u);
        BOOST_CHECK_EQUAL(puissance::puissance_modulaire<unsigned long long>(97643u, 276799u, 456753u), 368123u);
    }

    BOOST_AUTO_TEST_CASE(test_puissance) {
        BOOST_CHECK_EQUAL(puissance::puissance(2u, 10u), 1024u);
    }

BOOST_AUTO_TEST_SUITE_END()


text:
[![NPM version](https://img.shields.io/npm/v/is-bluebird.svg)](https://www.npmjs.com/package/is-bluebird)
[![Build Status](https://img.shields.io/travis/overlookmotel/is-bluebird/master.svg)](http://travis-ci.org/overlookmotel/is-bluebird)
[![Dependency Status](https://img.shields.io/david/overlookmotel/is-bluebird.svg)](https://david-dm.org/overlookmotel/is-bluebird)
[![Dev dependency Status](https://img.shields.io/david/dev/overlookmotel/is-bluebird.svg)](https://david-dm.org/overlookmotel/is-bluebird)
[![Coverage Status](https://img.shields.io/coveralls/overlookmotel/is-bluebird/master.svg)](https://coveralls.io/r/overlookmotel/is-bluebird)

## Usage

Tools to check whether some input is a [bluebird](http://bluebirdjs.com/) promise, a bluebird promise constructor, or determining the version of bluebird from a promise or constructor.

#### `isBluebird( promise )`

Returns true if is a bluebird promise, false if not.

```js
var isBluebird = require('is-bluebird');
var Bluebird = require('bluebird');

console.log( isBluebird( Bluebird.resolve() ) ); // true
console.log( isBluebird( Promise.resolve() ) ); // false (native JS promise)
```

#### `isBluebird.ctor( Promise )`

Returns true if is bluebird promise constructor, false if not.

```js
var isBluebird = require('is-bluebird');
var Bluebird = require('bluebird');

console.log( isBluebird.ctor( Bluebird ) ); // true
console.log( isBluebird.ctor( Promise ) ); // false (native JS promise)
```

#### `isBluebird.v2( promise )` / `isBluebird.v3( promise )`

Returns true if is a bluebird promise of the specified version.

```js
var isBluebird = require('is-bluebird');
var Bluebird2 = require('bluebird2');
var Bluebird3 = require('bluebird3');

console.log( isBluebird.v2( Bluebird2.resolve() ) ); // true
console.log( isBluebird.v2( Bluebird3.resolve() ) ); // false
console.log( isBluebird.v2( Promise.resolve() ) ); // false (native JS promise)
```

#### `isBluebird.v2.ctor( Promise )` / `isBluebird.v3.ctor( Promise )`

Returns true if is bluebird promise constructor of the specified version.

```js
var isBluebird = require('is-bluebird');
var Bluebird2 = require('bluebird2');
var Bluebird3 = require('bluebird3');

console.log( isBluebird.v2.ctor( Bluebird2 ) ); // true
console.log( isBluebird.v2.ctor( Bluebird3 ) ); // false
console.log( isBluebird.v2.ctor( Promise ) ); // false (native JS promise)
```

## Tests

Use `npm test` to run the tests. Use `npm run cover` to check coverage.

## Changelog

See [changelog.md](https://github.com/overlookmotel/is-bluebird/blob/master/changelog.md)

## Issues

If you discover a bug, please raise an issue on Github. https://github.com/overlookmotel/is-bluebird/issues

## Contribution

Pull requests are very welcome. Please:

* ensure all tests pass before submitting PR
* add an entry to changelog
* add tests for new features
* document new functionality/API additions in README


text:
source ../testsupport.sh

. ./clean.sh

run test.txt

grep -q "Stage hello" test.out || err "Failed to find expected stage hello"
grep -q "Stage world" test.out || err "Failed to find expected stage world"

[ ! -f test.f1.txt ] && err "Failed to find expected output test.f1.txt"
[ ! -f test.f1.f2.txt ] && err "Failed to find expected output test.f1.f2.txt"
[ ! -f test.f1.f3.txt ] && err "Failed to find expected output test.f2.f3.txt"

true


text:
package ex06.pyrmont.startup;

import org.apache.catalina.Connector;
import org.apache.catalina.Context;
import org.apache.catalina.Lifecycle;
import org.apache.catalina.LifecycleListener;
import org.apache.catalina.Loader;
import org.apache.catalina.Mapper;
import org.apache.catalina.Wrapper;
import org.apache.catalina.connector.http.HttpConnector;

import ex06.pyrmont.core.SimpleContext;
import ex06.pyrmont.core.SimpleContextLifecycleListener;
import ex06.pyrmont.core.SimpleContextMapper;
import ex06.pyrmont.core.SimpleLoader;
import ex06.pyrmont.core.SimpleWrapper;

public final class Bootstrap {
  public static void main(String[] args) {
    Connector connector = new HttpConnector();
    Wrapper wrapper1 = new SimpleWrapper();
    wrapper1.setName("Primitive");
    wrapper1.setServletClass("PrimitiveServlet");
    Wrapper wrapper2 = new SimpleWrapper();
    wrapper2.setName("Modern");
    wrapper2.setServletClass("ModernServlet");

    Context context = new SimpleContext();
    context.addChild(wrapper1);
    context.addChild(wrapper2);

    Mapper mapper = new SimpleContextMapper();
    mapper.setProtocol("http");
    LifecycleListener listener = new SimpleContextLifecycleListener();
    ((Lifecycle) context).addLifecycleListener(listener);
    context.addMapper(mapper);
    Loader loader = new SimpleLoader();
    context.setLoader(loader);
    // context.addServletMapping(pattern, name);
    context.addServletMapping("/Primitive", "Primitive");
    context.addServletMapping("/Modern", "Modern");
    connector.setContainer(context);
    try {
      connector.initialize();
      ((Lifecycle) connector).start();
      ((Lifecycle) context).start();

      // make the application wait until we press a key.
      System.in.read();
      ((Lifecycle) context).stop();
    }
    catch (Exception e) {
      e.printStackTrace();
    }
  }
}


text: This repository defines the SystemNet domain for WebGME. It is a special version of Petri-nets.


text:
import codecs
import os
import re
import sys
import textwrap
import time
from mercurial import hg, ui

PRODUCT_NAME = "rMake"
HEADINGS = [
        ('feature', 'New Features'),
        ('api', 'API Changes'),
        ('bugfix', 'Bug Fixes'),
        ('internal', 'Internal Changes'),
        ]
KINDS = set(x[0] for x in HEADINGS)
NEWSDIR = 'NEWS.src'

RE_ISSUE = re.compile('^[A-Z0-9]+-\d+')

def main():
    rootdir = os.path.realpath(__file__ + '/../..')
    os.chdir(rootdir)

    if not os.path.isdir(NEWSDIR):
        sys.exit("Can't find news directory")

    repo = hg.repository(ui.ui(), '.')

    args = sys.argv[1:]
    if args:
        command = args.pop(0)
    else:
        command = 'preview'

    if command == 'generate':
        generate(repo)
    elif command == 'preview':
        out, htmlOut, _ = preview(repo)
        print 'Text Version:\n'
        for line in out:
            print line
        print 'Html Version:\n'
        for line in htmlOut:
            print line
    else:
        sys.exit("Usage: %s <preview|generate>" % sys.argv[0])

def preview(repo, modifiedOK=True):
    mod, add, rem, del_, unk, ign, cln = repo.status(clean=True)
    ok = set(cln)
    bad = set(mod + add + rem + del_)

    kind_map = {}
    files = set()
    for filename in os.listdir(NEWSDIR):
        path = '/'.join((NEWSDIR, filename))
        if filename[0] == '.' or '.' not in filename:
            continue
        issue, kind = filename.rsplit('.', 1)
        if kind not in KINDS:
            print >> sys.stderr, "Ignoring '%s' due to unknown type '%s'" % (
                    filename, kind)
            continue

        if path in bad:
            if modifiedOK:
                print >> sys.stderr, "warning: '%s' is modified." % (path,)
                modified = time.time()
            else:
                sys.exit("File '%s' is modified and must be committed first." %
                        (path,))
        elif path not in ok:
            if modifiedOK:
                print >> sys.stderr, "warning: '%s' is not checked in." % (
                        path,)
                modified = time.time()
            else:
                sys.exit("File '%s' is not checked in and must be "
                        "committed first." % (path,))
        else:
            files.add(path)
            modified = _firstModified(repo, path)

        entries = [x.replace('\n', ' ') for x in
                   codecs.open(path, 'r', 'utf8').read().split('\n\n')]
        for n, line in enumerate(entries):
            entry = line.strip()
            if entry:
                kind_map.setdefault(kind, []).append((modified, issue, n,
                    entry))

    out = ['Changes in %s:' % _getVersion()]
    htmlOut = ['
%s %s is a maintenance release
' % (PRODUCT_NAME,
                                                           _getVersion())]
    for kind, heading in HEADINGS:
        entries = kind_map.get(kind, ())
        if not entries:
            continue
        out.append('  o %s:' % heading)
        htmlOut.append('%s:' % heading)
        htmlOut.append("
")
        for _, issue, _, entry in sorted(entries):
            htmlEntry = '
' + entry
            if RE_ISSUE.match(issue):
                entry += ' (%s)' % issue
                htmlEntry += ' (%s)' % (issue,issue)
            lines = textwrap.wrap(entry, 66)
            out.append('    * %s' % (lines.pop(0),))
            for line in lines:
                out.append('      %s' % (line,))
            htmlEntry += '
'
            htmlOut.append(htmlEntry)
        out.append('')
        htmlOut.append('
')
    return out, htmlOut, files

def generate(repo):
    version = _getVersion()
    old = codecs.open('NEWS', 'r', 'utf8').read()
    if '@NEW@' in old:
        sys.exit("error: NEWS contains a @NEW@ section")
    elif ('Changes in %s:' % version) in old:
        sys.exit("error: NEWS already contains a %s section" % version)

    lines, htmlLines, files = preview(repo, modifiedOK=False)
    new = '\n'.join(lines) + '\n'
    newHtml = '\n'.join(htmlLines) + '\n'

    doc = new + old
    codecs.open('NEWS', 'w', 'utf8').write(doc)
    codecs.open('NEWS.html', 'w', 'utf8').write(newHtml)

    sys.stdout.write(new)
    print >> sys.stderr, "Updated NEWS"
    print >> sys.stderr, "Wrote NEWS.html"

    wlock = repo.wlock()
    try:
        for name in files:
            os.unlink(name)
            repo.dirstate.remove(name)
    finally:
        wlock.release()
    print >> sys.stderr, "Deleted %s news fragments" % len(files)

def _firstModified(repo, path):
    fl = repo.file(path)
    ctx = repo[fl.linkrev(0)]
    return ctx.date()[0]

def _getVersion():
    f = os.popen("make show-version")
    return f.read().strip()

main()


text:
from __future__ import print_function
import requests
from flask import session

class AminoElasticsearch:
    '''
    pronounced 'Loo Py', not loopy:
    A Python module that makes REST API calls to Loopback apps.
    '''

    def __init__(self, **kwargs):
        # normalize url
        self.base_url = 'http://' + kwargs['hosts'][0]['host']
        if 'port' in kwargs['hosts'][0] and kwargs['hosts'][0]['port'] is not '':
            self.base_url = '{}{}{}'.format(self.base_url, ':',kwargs['hosts'][0]['port']).strip().rstrip('/') + '/'
        query_url = 'amino-api/Elasticsearches/es/'
        self.query_url = '{}{}'.format(self.base_url.strip().rstrip('/') + '/', query_url)

    @staticmethod
    def merge_two_dicts(x, y):
        """Given two dicts, merge them into a new dict as a shallow copy."""
        z = x.copy()
        z.update(y)
        return z

    def search(self, **kwargs):
        return self.verb(kwargs, '_search')

    def count(self, **kwargs):
        return self.verb(kwargs, '_count')

    def verb(self, kwargs, verb='_search', method='POST', return_result=False):
        index = ''
        merged_body = {}
        params = {}
        doc_type = ''

        if kwargs is not None:
            for key, value in kwargs.iteritems():
                if key is 'index':
                    index = value + '/'
                if key is 'id':
                    verb = value
                if key is 'body':
                    merged_body = AminoElasticsearch.merge_two_dicts(value, merged_body)
                if key is '_source_include':
                    source_dict = {
                        '_source': {
                            'includes': value
                        }
                    }
                    merged_body = AminoElasticsearch.merge_two_dicts(source_dict, merged_body)
                if key is 'from_':
                    merged_body['from'] = value
                if key is 'request_cache':
                    params['request_cache'] = value
                if key is 'fielddata_fields':
                    params['fielddata_fields'] = value
                if key is 'fields':
                    params['fields'] = value
                if key is 'completion_fields':
                    params['completion_fields'] = value
                if key is 'size':
                    merged_body[key] = value
                if key is 'doc_type':
                    doc_type = value + '/'

                params['access_token'] = self.get_token()

        url = '{}{}{}{}'.format(self.query_url, index, doc_type, verb)
        if len(merged_body) == 0:
            merged_body = None

        result = requests.request(method, url, json=merged_body, params=params)
        if result.status_code == 200 or result.status_code == 201:
            return result if return_result else result.json()
        if result.status_code == 401:
            params['access_token'] = self.get_token(True)
            print("Access token error, attempting to refresh auth token and try again.")
            result = requests.request(method, url, json=merged_body, params=params)
        if not return_result and (result.status_code != 200 or result.status_code == 201):
            print(result.content)
            raise Exception('{} to {} failed: {}'.format(method.upper(), url, result.content))
        return result if return_result else result.json()

    def stats(self, **kwargs):
        index = ''
        verb = '_stats'
        if kwargs is not None:
            for key, value in kwargs.iteritems():
                if key is 'index' and value is not '_all':
                    index = value + '/'
        method = 'GET'
        url = '{}{}{}'.format(self.query_url, index, verb)

        result = requests.request(method, url, params={'access_token': self.get_token()})
        if result.status_code == 200:
            return result.json()
        if result.status_code == 401:
            print("Access token error, attempting to refresh auth token and try again.")
            result = requests.request(method, url, params={'access_token': self.get_token(True)})
        if result.status_code != 200:
            print(result.content)
            raise Exception('{} to {} failed: {}'.format(method.upper(), url, result.content))
        return result.json()

    def get_document(self, **kwargs):
        if kwargs is not None and 'id' in kwargs and 'doc_type' in kwargs and 'index' in kwargs:
            return self.verb(kwargs, method='GET')
        raise Exception('kwargs insufficient, get requires index, doc_type and id')

    def exists(self, **kwargs):
        if kwargs is not None and 'id' in kwargs and 'doc_type' in kwargs and 'index' in kwargs:
            result = self.verb(kwargs, method='GET', return_result=True)
            return result.status_code is 200
        raise Exception('kwargs insufficient, exists requires index, doc_type and id')

    def index(self, **kwargs):
        if kwargs is not None and 'id' in kwargs and 'doc_type' in kwargs and 'index' in kwargs and 'body' in kwargs:
            return self.verb(kwargs, method='PUT')
        raise Exception('kwargs insufficient, exists requires index, doc_type, id and body')

    def get_token(self, force=False):
        if force or 'amino_token' not in session:
            payload = {'username': session['amino_user'], 'password': 'password'}
            url = '{}{}'.format(self.base_url.strip().rstrip('/') + '/', 'amino-api/AminoUsers/login')
            response = requests.post(url, payload)
            if response.status_code is not 200:
                raise Exception('{} to {} failed: {}'.format('POST', url, response.content))
            session['amino_token'] = response.json()['id']

        return session['amino_token']


text:
package com.crawljax.web.jaxrs;

import static org.junit.Assert.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

//TODO: delete the following imports
import java.io.File;
import org.openqa.selenium.firefox.FirefoxProfile;

import org.junit.*;
import org.junit.rules.TestRule;
import org.junit.rules.Timeout;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.Lists;
import com.thoughtworks.selenium.DefaultSelenium;
import com.thoughtworks.selenium.webdriven.WebDriverBackedSelenium;

public class StandardFunctionsFlowTest {

	private static final Logger LOG = LoggerFactory.getLogger(StandardFunctionsFlowTest.class);
	private static DefaultSelenium selenium;
	private static WebDriver driver;

	private static String CONFIG_NAME = "TestConfiguration";
	private static String CONFIG_URL = "http://demo.crawljax.com/";

	private static String LOCAL_PLUGIN_NAME = "Test Plugin";
	private static String LOCAL_PLUGIN_ID = "test-plugin";

	private static String REMOTE_PLUGIN_NAME = "dummy-plugin";
	private static String REMOTE_PLUGIN_URL =
	        "https://raw.github.com/crawljax/crawljax/web-ui-with-plugins/web/src/test/resources/dummy-plugin.jar";

	@Rule
	public TestRule globalTimeout = new Timeout(120 * 1000);

	@ClassRule
	public static final CrawljaxServerResource SERVER = new CrawljaxServerResource();

	@BeforeClass
	public static void setup() throws Exception {
		driver = new FirefoxDriver();
		LOG.debug("Starting selenium");
		selenium = new WebDriverBackedSelenium(driver, SERVER.getUrl());
		driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
	}

	@Test
	public void canPerformStandardFunctions() {
		createNewConfiguration();
		editConfiguration();
		copyConfiguration();

		addLocalPlugin();
		addRemotePlugin();
		addPluginToConfiguration();

		runConfigurationAndViewResults();

		deleteConfiguration();
		deletePlugins();
	}

	private void createNewConfiguration() {
		open("configurations");
		List<WebElement> newConfigurationLink =
		        driver.findElements(By.linkText("New Configuration"));
		assertFalse(newConfigurationLink.isEmpty());
		followLink(newConfigurationLink.get(0));
		List<WebElement> textBoxes = visibleElementsByTagName("input");
		assertFalse(textBoxes.isEmpty());
		textBoxes.get(0).sendKeys(CONFIG_NAME);
		textBoxes.get(1).clear();
		textBoxes.get(1).sendKeys(CONFIG_URL);
		List<WebElement> saveConfigurationLink =
		        driver.findElements(By.linkText("Save Configuration"));
		assertFalse(saveConfigurationLink.isEmpty());
		followLink(saveConfigurationLink.get(0));

		WebElement nameSpan = driver.findElements(By.xpath(
		       "//label[contains(text(),'Name:')]/following-sibling::input")).get(0);
		assertTrue(nameSpan.getAttribute("value").equals(CONFIG_NAME));

		WebElement urlInput = driver.findElements(By.xpath(
		       "//label[contains(text(),'Site:')]/following-sibling::input")).get(0);
		assertTrue(urlInput.getAttribute("value").equals(CONFIG_URL));
	}

	private void editConfiguration() {
		WebElement maxCrawlStates =
		        driver.findElements(
		                By.xpath(
		                        "//label[contains(text(),'Maximum Crawl States:')]/following-sibling::input"))
		                .get(0);
		maxCrawlStates.clear();
		maxCrawlStates.sendKeys("3");

		maxCrawlStates =
		        driver.findElements(
		                By.xpath(
		                        "//label[contains(text(),'Maximum Crawl States:')]/following-sibling::input"))
		                .get(0);
		assertTrue(maxCrawlStates.getAttribute("value").equals("3"));

		WebElement crawlRulesLink = driver.findElements(By.linkText("Crawl Rules")).get(0);
		followLink(crawlRulesLink);

		WebElement clickDefaultElements =
		        driver.findElements(By.xpath("//label[@class='checkbox']")).get(0);
		followLink(clickDefaultElements);

		WebElement addANewClickRule =
		        driver.findElements(By.linkText("Add a New Click Rule")).get(0);
		followLink(addANewClickRule);

		WebElement addANewConditionLink =
		        driver.findElements(By.linkText("Add a New Condition")).get(0);
		followLink(addANewConditionLink);

		WebElement pageConditionInput =
		        driver.findElements(
		                By.xpath(
		                        "//legend[contains(text(),'Page Conditions')]/following-sibling::table//input[@type='text']"))
		                .get(0);
		pageConditionInput.clear();
		pageConditionInput.sendKeys("ConditionInput");

		WebElement addANewFilter = driver.findElements(By.linkText("Add a New Filter")).get(0);
		followLink(addANewFilter);
		WebElement filterInput =
		        driver.findElements(
		                By.xpath(
		                        "//legend[contains(text(),'State Filters')]/following-sibling::table//input[@type='text']"))
		                .get(0);
		filterInput.clear();
		filterInput.sendKeys("FilterInput");

		WebElement addANewField = driver.findElements(By.linkText("Add a New Field")).get(0);
		followLink(addANewField);
		WebElement fieldIdInput =
		        driver.findElements(
		                By.xpath(
		                        "//legend[contains(text(),'Form Field Input Values')]/following-sibling::table//input[@type='text']"))
		                .get(0);
		fieldIdInput.clear();
		fieldIdInput.sendKeys("FieldID");
		WebElement fieldValueInput =
		        driver.findElements(
		                By.xpath(
		                        "//legend[contains(text(),'Form Field Input Values')]/following-sibling::table//input[@type='text']"))
		                .get(1);
		fieldValueInput.clear();
		fieldValueInput.sendKeys("FieldValue");

		((JavascriptExecutor) driver).executeScript("scroll(250,0);");
		WebElement assertionsLink = driver.findElements(By.partialLinkText("Assertions")).get(0);
		followLink(assertionsLink);

		addANewConditionLink = driver.findElements(By.linkText("Add a New Condition")).get(0);
		followLink(addANewConditionLink);
		WebElement newConditionInput =
		        driver.findElements(
		                By.xpath(
		                        "//legend[contains(text(),'Invariants')]/following-sibling::table//input[@type='text']"))
		                .get(0);
		newConditionInput.clear();
		newConditionInput.sendKeys("crawljax");

		List<WebElement> saveConfigurationLink =
		        driver.findElements(By.linkText("Save Configuration"));
		followLink(saveConfigurationLink.get(0));

		ExpectedCondition<Boolean> isSaved = new ExpectedCondition<Boolean>() {
			public Boolean apply(WebDriver driver) {
				WebElement notification = driver.findElements(By.id("notification")).get(0);
				return notification.getText().equals("Configuration Saved");
			}
		};
		WebDriverWait wait = new WebDriverWait(driver, 10);
		wait.until(isSaved);
	}

	private void copyConfiguration() {

		WebElement copyConfigurationLink = driver.findElements(By.linkText("New Copy")).get(0);
		followLink(copyConfigurationLink);

		List<WebElement> textBoxes = visibleElementsByTagName("input");
		WebElement nameInput = textBoxes.get(0);
		nameInput.clear();
		nameInput.sendKeys("copy");

		WebElement saveConfigurationLink =
		        driver.findElements(By.linkText("Save Configuration")).get(0);
		followLink(saveConfigurationLink);

		WebElement siteInput = driver.findElement(By.xpath(
		        "//label[contains(text(),'Site:')]/following-sibling::input"));
		String asdf = siteInput.getAttribute("value");
		assertEquals(CONFIG_URL, siteInput.getAttribute("value"));

		List<WebElement> deleteLink = driver.findElements(By.linkText("Delete Configuration"));
		followLink(deleteLink.get(0));

		Alert confirmDialog = driver.switchTo().alert();
		confirmDialog.accept();

		ExpectedCondition<Boolean> isDeleted = new ExpectedCondition<Boolean>() {
			public Boolean apply(WebDriver driver) {
				WebElement notification = driver.findElements(By.id("notification")).get(0);
				return notification.getText().equals("Configuration Deleted");
			}
		};
		WebDriverWait wait = new WebDriverWait(driver, 10);
		wait.until(isDeleted);
	}

	private void runConfigurationAndViewResults() {
		openConfiguration();

		WebElement empty =
		        driver.findElement(By
		                .xpath(
		                "//li[contains(text(),'CRAWL EXECUTION QUEUE')]/following-sibling::li[contains(i,'empty')]"));
		assertNotNull(empty);

		List<WebElement> runConfigurationLink =
		        driver.findElements(By.linkText("Run Configuration"));
		followLink(runConfigurationLink.get(0));

		ExpectedCondition<Boolean> isRunning = new ExpectedCondition<Boolean>() {
			public Boolean apply(WebDriver driver) {
				WebElement running =
				        driver.findElement(By
				                .xpath(
				                "//li[contains(text(),'CRAWL EXECUTION QUEUE')]/following-sibling::li//span[contains(i,'running')]"));
				return running != null;
			}
		};
		WebDriverWait wait = new WebDriverWait(driver, 10);
		wait.until(isRunning);

		ExpectedCondition<Boolean> isComplete = new ExpectedCondition<Boolean>() {
			public Boolean apply(WebDriver driver) {
				WebElement success =
				        driver.findElement(By
				                .xpath(
				                "//li[contains(text(),'CRAWL EXECUTION QUEUE')]/following-sibling::li//span[contains(i,'success')]"));
				return success != null;
			}
		};
		wait = new WebDriverWait(driver, 60);
		wait.until(isComplete);

		List<WebElement> crawlHistoryLink = driver.findElements(By.linkText("Crawl History"));
		followLink(crawlHistoryLink.get(0));

		WebElement crawlLink = driver.findElement(By.xpath(
		        "//td[following-sibling::td[contains(a,'" + CONFIG_NAME + "')]]/a"));
		followLink(crawlLink);

		List<WebElement> logLink = driver.findElements(By.linkText("Log"));
		assertFalse(logLink.isEmpty());

		List<WebElement> crawlOverviewLink = driver.findElements(By.linkText("Crawl Overview"));
		assertFalse(crawlOverviewLink.isEmpty());

		List<WebElement> pluginLink = driver.findElements(By.linkText(LOCAL_PLUGIN_NAME));
		assertFalse(pluginLink.isEmpty());

		followLink(logLink.get(0));
		assertFalse(driver.findElement(By.id("logPanel")).getAttribute("innerHTML").equals(""));

		List<WebElement> historyLink = driver.findElements(By.linkText("History"));
		followLink(historyLink.get(0));
		driver.navigate().refresh();

		WebElement dateContainer = driver.findElement(By.xpath(
		        "//td[preceding-sibling::td[contains(a,'" + CONFIG_NAME + "')]]"));
		assertNotNull(dateContainer);
		String displayedDate = dateContainer.getText();
		SimpleDateFormat dateParser = new SimpleDateFormat("EEE MMM d yyyy HH:mm:ss");
		Date date = null;
		try {
			date = dateParser.parse(displayedDate);
		} catch (ParseException e) {

		}
		assertNotNull(date);

		assertTrue(date.after(timeNSecondsAgo(70)));
	}

	private void addLocalPlugin() {
		open("plugins");

		List<WebElement> refreshLink = driver.findElements(By.linkText("Refresh List"));
		followLink(refreshLink.get(0));

		WebElement fileInput = driver.findElement(By.xpath("//input[@type='file']"));

		String fileName =
		        getClass().getClassLoader().getResource(LOCAL_PLUGIN_ID + ".jar")
		                .toExternalForm();
		fileInput.sendKeys(fileName);

		List<WebElement> uploadLink = driver.findElements(By.linkText("Upload Local Plugin"));
		followLink(uploadLink.get(0));

		WebElement uploaded =
		        (new WebDriverWait(driver, 10))
		                .until(ExpectedConditions.presenceOfElementLocated(By
		                        .xpath(
		                        "//legend[contains(text(),'Available Plugins')]/following-sibling::table//tbody//tr"
		                        + "//td[contains(text(),'" + LOCAL_PLUGIN_NAME + "')]")));
		assertNotNull(uploaded);

	}

	private void addRemotePlugin() {
		open("plugins");

		List<WebElement> refreshLink = driver.findElements(By.linkText("Refresh List"));
		followLink(refreshLink.get(0));

		WebElement urlInput = driver.findElement(By.xpath(
		        "//label[contains(text(),'URL:')]/following-sibling::input[@type='text']"));
		urlInput.sendKeys(REMOTE_PLUGIN_URL);

		List<WebElement> downloadLink = driver.findElements(By.linkText("Download Remote Plugin"));
		followLink(downloadLink.get(0));

		WebElement uploaded =
		        (new WebDriverWait(driver, 10))
		                .until(ExpectedConditions.presenceOfElementLocated(By
		                        .xpath(
		                        "//legend[contains(text(),'Available Plugins')]/following-sibling::table//tbody//tr"
		                        + "//td[contains(text(),'" + REMOTE_PLUGIN_NAME + "')]")));
		assertNotNull(uploaded);

	}

	private void addPluginToConfiguration() {
		openConfiguration();

		WebElement pluginsLink =
		        driver.findElement(By
		                .xpath(
		                "//li[preceding-sibling::li[contains(a,'Overview')]]/a[contains(text(),'Plugins')]"));
		assertNotNull(pluginsLink);
		followLink(pluginsLink);

		List<WebElement> addPluginLink = driver.findElements(By.linkText("Add Plugin"));
		followLink(addPluginLink.get(0));
		Select select = new Select(driver.findElement(By.xpath("//select")));

		select.selectByVisibleText(LOCAL_PLUGIN_ID);

		List<WebElement> saveLink = driver.findElements(By.linkText("Save Configuration"));
		followLink(saveLink.get(0));

		driver.navigate().refresh();

		WebElement pluginTitle =
		        driver.findElement(By.xpath("//legend[contains(text(),'" + LOCAL_PLUGIN_NAME
		                + "')]"));
		assertNotNull(pluginTitle);
	}

	private void deletePlugins() {
		open("plugins");

		List<WebElement> deleteLinks = driver.findElements(By.linkText("Delete"));

		while (deleteLinks.size() > 0) {
			followLink(deleteLinks.get(0));
			Alert confirmDialog = driver.switchTo().alert();
			confirmDialog.accept();
			ExpectedCondition<Boolean> isDeleted = new ExpectedCondition<Boolean>() {
				public Boolean apply(WebDriver driver) {
					WebElement notification = driver.findElements(By.id("notification")).get(0);
					return notification.getText().equals("Plugin Deleted");
				}
			};
			WebDriverWait wait = new WebDriverWait(driver, 10);
			wait.until(isDeleted);
			if (!isElementPresent(driver, By.linkText("Delete"))) {
				break;
			}
			deleteLinks = driver.findElements(By.linkText("Delete"));
		}

		driver.navigate().refresh();
		assertFalse(isElementPresent(driver, By.linkText("Delete")));
	}

	private void deleteConfiguration() {
		open("configurations");

		List<WebElement> existingConfigurationLinks =
		        driver.findElements(By.linkText(CONFIG_NAME));

		openConfiguration();

		WebElement deleteLink = driver.findElement(By.linkText("Delete Configuration"));
		followLink(deleteLink);

		Alert confirmDialog = driver.switchTo().alert();
		confirmDialog.accept();

		open("configurations");
		if (isElementPresent(driver, By.linkText(CONFIG_NAME))) {
			List<WebElement> configurationLinks = driver.findElements(By.linkText(CONFIG_NAME));
			assertEquals(existingConfigurationLinks.size() - 1, configurationLinks.size());
		}
		else {
			assertEquals(1, existingConfigurationLinks.size());
		}
	}

	private void open(String hashLocation) {
		selenium.open("/#/" + hashLocation);
		try {
			Thread.sleep(100);
		} catch (InterruptedException e) {
			throw new RuntimeException(e);
		}
	}

	private void followLink(WebElement link) {
		link.click();
		try {
			Thread.sleep(400);
		} catch (InterruptedException e) {
			throw new RuntimeException(e);
		}
	}

	private void openConfiguration() {
		open("configurations");
		WebElement configLink =
		        driver.findElement(By.xpath(
		                "//td[contains(a,'" + CONFIG_NAME
		                        + "') and following-sibling::td[contains(a,'" + CONFIG_URL
		                        + "')]]/a"));
		configLink.click();
	}

	private Date timeNSecondsAgo(int n) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(new Date());
		cal.add(Calendar.SECOND, -n);
		return cal.getTime();
	}

	private List<WebElement> visibleElementsByTagName(String selector) {
		List<WebElement> elements = driver.findElements(By.tagName(selector));
		List<WebElement> visible = Lists.newArrayListWithExpectedSize(elements.size());
		for (WebElement webElement : elements) {
			if (webElement.isDisplayed()) {
				visible.add(webElement);
			}
		}
		return visible;
	}

	private boolean isElementPresent(WebDriver driver, By by) {
		driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);
		try {
			driver.findElement(by);
			return true;
		} catch (Exception e) {
			return false;
		} finally {
			driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
		}
	}

	@AfterClass
	public static void tearDown() throws Exception {
		selenium.stop();
	}
}


text:
<!--
DO NOT EDIT THIS FILE!

It's auto-generated by sonata-project/dev-kit package.
-->

# Sonata project contribution

Thanks for your interest in Sonata projects!

This document is about issues and pull requests.

The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD",
"SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be
interpreted as described in [RFC 2119](https://www.ietf.org/rfc/rfc2119.txt).

## Summary

* [Issues](#issues)
* [Pull Requests](#pull-requests)
    * [Content](#content)
        * [Coding style](#coding-style)
        * [Documentation](#documentation)
        * [Tests](#tests)
    * [Writing a pull request](#writing-a-pull-request)
        * [Subject](#subject)
        * [Changelog](#changelog)
        * [Base branch](#base-branch)
        * [Commit messages](#commit-messages)

## Issues

First, check if you are up to date: is your version still supported, and are
you using the latest patch version?

GitHub Issues is for **issues**, as opposed to question on how to use Sonata.
If you are not sure this is a bug, or simply want to ask such a question,
please post your question on [Stack Overflow](http://stackoverflow.com/questions/tagged/sonata),
using the `sonata` tags.

If you happen to find a bug, we kindly request you report it. However,
before submitting it, please check the [project documentation available
online](https://sonata-project.org/bundles/).

Then, if it appears that it is indeed a real bug, you MAY report it using
Github by following these points are taken care of:

* Check if the bug is not already reported!
* The title sums up the issue with clarity.
* A description of the workflow needed to reproduce the bug. Please try to make
  sentences, dumping an error message by itself is frowned upon.
* If your issue is an error page, you MUST provide us with a stack trace. With
  recent versions of Symfony, you can even get stack traces as plain text at the
end of the page. Just look for "Stack Trace (Plain Text)", and copy/paste what
you see. **Do not** make a screenshot of the stack trace, as screenshots are
not indexed by search engines and will make it difficult for other people to
find your bug report. If you have an issue when using the Symfony CLI,
use the `-vvv` option to get a stack trace.
* Screenshots SHOULD be considered additional data, and therefore, you SHOULD
  always provide a textual description of the bug. It is strongly RECOMMENDED
to provide them when reporting UI-related bugs.
* If you need to provide code, make sure you know how to get syntactic
  coloration, in particular with [fenced code
blocks](https://help.github.com/articles/creating-and-highlighting-code-blocks/).
When you feel the code is to long, use external code pastebin like
https://gist.github.com/ or http://hastebin.com/ . If this is not sufficient,
just create a repository to show the issue.

> _NOTE:_ Don't hesitate to give as much information as you can (OS, PHP
> version, extensions...)

## Pull Requests

All the sonata team will be glad to review your code changes propositions! :smile:

But please, read the following before.

### Content

#### Coding style

Each project follows [PSR-1](http://www.php-fig.org/psr/psr-1/), [PSR-2](http://www.php-fig.org/psr/psr-2/)
and [Symfony Coding Standards](http://symfony.com/doc/current/contributing/code/standards.html) for coding style,
[PSR-4](http://www.php-fig.org/psr/psr-4/) for autoloading.

Please [install PHP Coding Standard Fixer](http://cs.sensiolabs.org/#installation)
and run this command before committing your modifications:

```bash
php-cs-fixer fix --verbose
```

Please note that we try to keep phpdoc to a minimum, so if an `@param` phpdoc
comment brings nothing more than the type hint and variable name already do,
it SHOULD be removed. Descriptions are OPTIONAL if you want to document a type.

If you want to use pseudo-types, generics, array shapes or templates for
static-analysis, prefer the usage of `@phpstan-` annotations over classic
annotations to keep IDE support, and over `@psalm-` annotations for consistency.
Keep standard annotations if necessary.

```php
/**
 * @param Bar|Baz $foo
 * @param int     $limit a crucial, highly interesting comment
 *
 * @phpstan-param class-string $class
 */
protected function bar($foo, string $class, int $limit)
{
    // ...
}
```

Please also note that multiline signatures are allowed when the line is longer than 120 characters.

#### Documentation

The documentation is mostly written with the `rst` format, and can be found in the `docs` directory.
You can test the doc rendering with the `make docs` command, but to do this, you will need [Sphinx][sphinx_install].
Just like php dependencies can be managed with Composer, python dependencies can be managed with [pip][pip_install].
To get sphinx, simply run the following command.

```bash
pip install --requirement docs/requirements.txt --user
```

Some python binaries SHOULD be downloaded to `~/.local/bin` for Linux or `~/Library/Python/2.7/bin` for Mac OS,
[modify your `$PATH` environment variable](http://www.linfo.org/path_env_var.html)
so that it contains this path and then, from the root of the project, run `make docs`

If `make docs` is successful, you SHOULD be able to see your modifications:

```bash
$YOUR_FAVORITE_BROWSER docs/_build/html/index.html
```

If your PR contains a new feature, you MUST add documentation for it.
Of course, you can also create PRs consisting only in documentation changes.

Documentation contributions SHOULD comply with [the Symfony documentation standards](https://symfony.com/doc/current/contributing/documentation/standards.html).

#### Tests

If your PR contains a fix, tests SHOULD be added to prove the bug.

If your PR contains an addition, a new feature, this one has to be fully covered by tests.

Some rules have to be respected about the test:

* Prefer [the built-in test doubles implementation](https://phpunit.de/manual/current/en/test-doubles.html) over prophecy.
* Annotations about coverage are prohibited. This concerns:
  * `@covers`
  * `@coversDefaultClass`
  * `@coversNothing`
  * `@codeCoverageIgnore`
  * `@codeCoverageIgnoreStart`
  * `@codeCoverageIgnoreEnd`
* All test methods MUST be prefixed by `test`. Example: `public function testItReturnsNull()`.
* As opposed, the `@test` annotation is prohibited.
* All test method names MUST be in camel case format.
* Most of the time, the test class SHOULD have the same name as the targeted class, suffixed by `Test`.
* The `@expectedException*` annotations are prohibited. Use `PHPUnit_Framework_TestCase::setExpectedException()`.

### Writing a Pull Request

#### Subject

Ideally, a Pull Request SHOULD concern one and **only one** subject, so that it
remains clear, and independent changes can be merged quickly.

If you want to fix a typo and improve the performance of a process, you SHOULD
try as much as possible to do it in a **separate** PR, so that we can quickly
merge one while discussing the other.

The goal is to have a clear commit history and make a possible revert easier.

If you found an issue/typo while writing your change that is not related to
your work, please do another PR for that. In some rare cases, you might be
forced to do it on the same PR. In this kind of situation, please add a comment
on your PR explaining why you feel it is the case.

#### Changelog

For each PR, a change log MUST be provided.

There are few cases where no change log is necessary:

* When you fix a bug on an unreleased feature.
* When your PR concerns only the documentation (fix or improvement).

**Do not** edit the `CHANGELOG.md` directly though, because having every
contributor write PR with changes in the same file, at roughly the same line is
a recipe for conflicts. Instead, fill in the dedicated section that SHOULD
appear in a textaread when submitting your PR.

Your note can be put on one of these sections:

* `Added` for new features.
* `Changed` for changes in existing functionality.
* `Deprecated` for deprecation of features that will be removed in next major release.
* `Removed` for deprecated features removed in this release.
* `Fixed` for any bug fixes.
* `Security` to invite users to upgrade in case of vulnerabilities.

More information about the followed changelog format: [keepachangelog.com](http://keepachangelog.com/)

#### Base branch

Before writing a PR, you have to check on which branch your changes SHOULD be based.

Each project follows [semver](http://semver.org/) convention for release management.

Here is a short table resuming on which you have to start:

Kind of modification | Backward Compatible (BC) | Type of release | Branch to target        | Label |
-------------------- | ------------------------ | --------------- | ----------------------- | ----- |
Bug fixes            | Yes                      | Patch           | `3.x`   |       |
Bug fixes            | No (Only if no choice)   | Major           | `master` |       |
Feature              | Yes                      | Minor           | `3.x`   |       |
Feature              | No (Only if no choice)   | Major           | `master` |       |
Deprecation          | Yes (Have to)            | Minor           | `3.x`   |       |
Deprecation removal  | No (Can't be)            | Major           | `master` |       |

Notes:
  * Branch `3.x` is the branch of the **latest stable** minor release and
  has to be used for Backward compatible PRs.
  * If you PR is not **Backward Compatible** but can be, it **MUST** be:
    * Changing a function/method signature? Prefer create a new one and deprecate the old one.
    * Code deletion? Don't. Please deprecate it instead.
    * If your BC PR is accepted, you can do a new one on the `master` branch which removes the deprecated code.
    * SYMFONY DOC REF (same logic)?

If you have a non-BC PR to propose, please try to create a related BC PR first.
This BC PR SHOULD mark every piece of code that needs to be removed / uncommented / reworked
in the corresponding non-BC PR with the following marker comment : `NEXT_MAJOR`.
When the BC PR is merged in the stable branch, wait for the stable branch to be
merged in the unstable branch, and then work on your non-BC PR.

For instance, assuming you want to introduce a new method to an existing interface, you SHOULD do something like this:

```php
<?php

namespace Foo;

interface BarInterface
{
  /**
   * NEXT_MAJOR: Uncomment this method
   *
   * This method does useful stuff.
   */
  // public function usefulMethod();

  // …
}
```

##### Deprecation

In some cases, you might have some code parts that might become superseded by others, but could still be used by the end user.
If the concerned code is not tagged as `internal`, it MUST be deprecated on the stable branch, then removed.

If an alternate usage solution is possible, you **MUST** provide it in the deprecation message.

The deprecated minor version **MUST NOT** be provided. Use `x` instead. It will be updated when releasing.

Any deprecation **MUST** be documented in the corresponding `UPGRADE-[0-9].x.md`.
The documentation **MUST** be filled inside the top **unreleased** section with a sub title.

The `NEXT_MAJOR` tag SHOULD also be used for deprecations, it will be searched for before releasing the next major version.

You have three ways to deprecate things.

For class definitions and properties, use the `@deprecated` tag.
For methods, use the `@deprecated` tag and trigger a deprecation with `@trigger_error('...', \E_USER_DEPRECATED)`:

```php
/**
 * NEXT_MAJOR: Remove this class.
 *
 * @deprecated since sonata-project/foo-lib 42.x, to be removed in 43.0. Use Shiny\New\ClassOfTheMonth instead.
 */
final class IAmOldAndUseless
{
}

final class StillUsedClass
{
    /**
     * NEXT_MAJOR: Remove this property.
     *
     * @deprecated since sonata-project/foo-lib 42.x, to be removed in 43.0.
     */
    public $butNotThisProperty;

    /**
     * NEXT_MAJOR: Remove this method.
     *
     * @deprecated since sonata-project/foo-lib 42.x, to be removed in 43.0.
     */
    public function iAmBatman()
    {
        @trigger_error(sprintf(
            'Method %s() is deprecated since sonata-project/foo-lib 42.x and will be removed in version 43.0.',
            __METHOD__
        ), \E_USER_DEPRECATED);

        echo "But this is not Gotham here.";
    }
}
```

If the deprecated thing is a service, you **MUST** specify it on the service definition:

```xml
<!-- NEXT_MAJOR: Remove this service -->
<service id="sonata.block.old" class="Sonata\Block\Old">
    <argument type="service" id="security.token_storage" />
    <deprecated>The "%service_id%" service is deprecated since sonata-project/bar-bundle 42.x and will be removed in 43.0.</deprecated>
 </service>
 ```

More info: http://symfony.com/blog/new-in-symfony-2-8-deprecated-service-definitions

For everything else, not managed by the `@deprecated` tag,
you **MUST** still trigger a deprecation message (and add a `NEXT_MAJOR` comment).

```php
<?php
// NEXT_MAJOR: Remove this condition.
if (/* some condition showing the user is using the legacy way */) {
    @trigger_error(
        'This is deprecated since sonata-project/bar-bundle 42.x and will not be supported in version 43.0.',
        \E_USER_DEPRECATED
    );
} else {
    // new way of doing things
}
```

In the case of a deprecation, unit tests might show your deprecation notice.
You **MUST** mark such tests with the `@group legacy` annotation and add a `NEXT_MAJOR` comment to explain
how to deal with them in the next major (with a removal or some changes).

Be aware that pull requests with BC breaks could be rejected
or postponed to next major release **only** if BC is not possible.

If you are not sure what should be done, don't hesitate to open an issue about your PR project.

##### Dependency changes

If you want to change some dependencies, here are the rules:

- Don't add support for a version lower than the current one.
- Don't change the highest supported version to a lower one.
- Lower version dropping is accepted as a Backward Compatible change according to [semver][semver_dependencies_update],
but some extra rules MUST be respected here:
  - PHP versions that are under the [orange zone][php_supported_versions] (Security Support) **MUST NOT** be dropped on the stable branch.
  - PHP versions that are under the [green zone][php_supported_versions] (Active Support) **MUST NOT** be dropped on the master branch.
  - If it's a Symfony package, at least the last LTS version **MUST** be supported, even on master.
  - Generally, don't drop dependency version if it doesn't have a big impact on the code.
  - Backward Compatible code related to the dropped version **MUST** be dropped on the same PR.
    This will allow seeing if this version drop **is really worth it** or not.
    Please note that we can refuse a version drop at any moment if the gain does not seem sufficient.

##### Legacy branches

Legacy branches are **NOT** supported at all. Any submitted Pull Request will be immediately closed.

Core team members *MAY* cherry-pick some fixes from the stable branch to the legacy one if it's really needed
and if the legacy one is not too old (~less than one month).

#### Commit messages

Sonata is a big project with many contributors, and a big part of the job is
being able to understand the code at all times, be it when submitting a PR or
looking at the history. Good commit messages are crucial to achieve this goal.

There are already a few articles (or even single purpose websites) about this,
we cannot recommend enough the following:

* http://rakeroutes.com/blog/deliberate-git
* http://stopwritingramblingcommitmessages.com
* http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html

To sum them up, the commit message has to be crystal clear and of course,
related to the PR content.

The first line of the commit message MUST be short, keep it under 50
characters. It MUST say concisely but *precisely* what you did. The other
lines, if needed, SHOULD contain a complete description of *why* you did this.

Bad commit message subject:

```
Update README.md
```

Good commit message subject :

```
Document how to install the project
```

Also, when you specify what you did avoid commit message subjects with "Fix bug
in such and such feature". Saying you are fixing something implies the previous
implementation was wrong and yours is right, which might not even be true.
Instead, state unquestionable technical facts about your changes, not opinions.
Then, in the commit description, explain why you did that and how it fixes
something.
```
call foo::bar() instead of bar::baz()

This fixes a bug that arises when doing this or that, because baz() needs a
flux capacitor object that might not be defined.
Fixes #42
```

The description is OPTIONAL but strongly RECOMMENDED. It could be asked by the
team if needed. PR will often lead to complicated, hard-to-read conversations
with many links to other web pages.

The commit description SHOULD be able to live without what is said in the PR,
and SHOULD ideally sum it up in a crystal clear way, so that people do not have
to open a web browser to understand what you did.
Links to PRs/Issues and external references are of course welcome, but SHOULD
not be considered enough. When you reference an issue, make sure to use one of
the keywords described in [the dedicated github
article](https://help.github.com/articles/closing-issues-via-commit-messages/).

Good commit message with description :

```
Change web UI background color to pink

This is a consensus made on #4242 in addition to #1337.

We agreed that blank color is boring and so deja vu. Pink is the new way to do.
```
(Obviously, this commit is fake. :wink:)


text:
from airflow.hooks.base_hook import BaseHook
from azure.mgmt.containerinstance.models import (Volume,
                                                 AzureFileVolume)

class AzureContainerVolumeHook(BaseHook):
    """
    A hook which wraps an Azure Volume.

    :param wasb_conn_id: connection id of a Azure storage account of
    which file shares should be mounted
    :type wasb_conn_id: str
    """

    def __init__(self, wasb_conn_id='wasb_default'):
        self.conn_id = wasb_conn_id

    def get_storagekey(self):
        conn = self.get_connection(self.conn_id)
        service_options = conn.extra_dejson

        if 'connection_string' in service_options:
            for keyvalue in service_options['connection_string'].split(";"):
                key, value = keyvalue.split("=", 1)
                if key == "AccountKey":
                    return value
        return conn.password

    def get_file_volume(self, mount_name, share_name,
                        storage_account_name, read_only=False):
        return Volume(name=mount_name,
                      azure_file=AzureFileVolume(share_name=share_name,
                                                 storage_account_name=storage_account_name,
                                                 read_only=read_only,
                                                 storage_account_key=self.get_storagekey()))


text:
layout: icon
title: Parking
categories: transportation
icon-24: parking-24.png
icon-18: parking-18.png
icon-12: parking-12.png
tags:
  - parking
  - transportation
---