text:
#ifndef DrawingAreaImpl_h
#define DrawingAreaImpl_h

#include "DrawingArea.h"
#include "LayerTreeHost.h"
#include "Region.h"
#include "RunLoop.h"

namespace WebKit {

class UpdateInfo;

class DrawingAreaImpl : public DrawingArea {
public:
    static PassOwnPtr<DrawingAreaImpl> create(WebPage*, const WebPageCreationParameters&);
    virtual ~DrawingAreaImpl();

    void setLayerHostNeedsDisplay();
    void layerHostDidFlushLayers();

private:
    DrawingAreaImpl(WebPage*, const WebPageCreationParameters&);

    // DrawingArea
    virtual void setNeedsDisplay(const WebCore::IntRect&);
    virtual void scroll(const WebCore::IntRect& scrollRect, const WebCore::IntSize& scrollOffset);
    virtual void forceRepaint();

    virtual void didInstallPageOverlay();
    virtual void didUninstallPageOverlay();
    virtual void setPageOverlayNeedsDisplay(const WebCore::IntRect&);

    virtual void setRootCompositingLayer(WebCore::GraphicsLayer*);
    virtual void scheduleCompositingLayerSync();
    virtual void syncCompositingLayers();
    virtual void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::ArgumentDecoder*);

    // CoreIPC message handlers.
    virtual void updateBackingStoreState(uint64_t backingStoreStateID, bool respondImmediately, const WebCore::IntSize&, const WebCore::IntSize& scrollOffset);
    virtual void didUpdate();
    virtual void suspendPainting();
    virtual void resumePainting();

    void sendDidUpdateBackingStoreState();

    void enterAcceleratedCompositingMode(WebCore::GraphicsLayer*);
    void exitAcceleratedCompositingModeSoon();
    bool exitAcceleratedCompositingModePending() const { return m_exitCompositingTimer.isActive(); }
    void exitAcceleratedCompositingMode();

    void scheduleDisplay();
    void displayTimerFired();
    void display();
    void display(UpdateInfo&);

    uint64_t m_backingStoreStateID;

    Region m_dirtyRegion;
    WebCore::IntRect m_scrollRect;
    WebCore::IntSize m_scrollOffset;

    // Whether we're currently processing an UpdateBackingStoreState message.
    bool m_inUpdateBackingStoreState;

    // When true, we should send an UpdateBackingStoreState message instead of any other messages
    // we normally send to the UI process.
    bool m_shouldSendDidUpdateBackingStoreState;

    // Whether we're waiting for a DidUpdate message. Used for throttling paints so that the
    // web process won't paint more frequent than the UI process can handle.
    bool m_isWaitingForDidUpdate;

    // True between sending the 'enter compositing' messages, and the 'exit compositing' message.
    bool m_compositingAccordingToProxyMessages;

    // Whether painting is suspended. We'll still keep track of the dirty region but we
    // won't paint until painting has resumed again.
    bool m_isPaintingSuspended;
    bool m_alwaysUseCompositing;

    double m_lastDisplayTime;

    RunLoop::Timer<DrawingAreaImpl> m_displayTimer;
    RunLoop::Timer<DrawingAreaImpl> m_exitCompositingTimer;

    // The layer tree host that handles accelerated compositing.
    RefPtr<LayerTreeHost> m_layerTreeHost;
};

} // namespace WebKit

#endif // DrawingAreaImpl_h


text:
package net.mcft.copy.betterstorage.utils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.mcft.copy.betterstorage.api.IContainerItem;
import net.mcft.copy.betterstorage.api.lock.IKey;
import net.mcft.copy.betterstorage.api.lock.ILock;
import net.minecraft.enchantment.Enchantment;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraftforge.common.util.Constants.NBT;

public final class StackUtils {

	private StackUtils() {  }

	// NBT utility functions

	/** Gets the actual NBT tag from the ItemStack's custom NBT data. */
	public static NBTBase getTag(ItemStack stack, String... tags) {
		if (!stack.hasTagCompound()) return null;
		String tag = null;
		NBTTagCompound compound = stack.getTagCompound();
		for (int i = 0; i < tags.length; i++) {
			tag = tags[i];
			if (!compound.hasKey(tag)) return null;
			if (i == tags.length - 1) break;
			compound = compound.getCompoundTag(tag);
		}
		return compound.getTag(tag);
	}
	/** Gets the type of a tag from the ItemStack's custom NBT data.

	 *  See {@link NBTBase#NBTTypes} for possible return values.

	 *  Returns null if the tag doesn't exist. */
	public static String getType(ItemStack stack, String... tags) {
		NBTBase tag = getTag(stack, tags);
		return ((tag != null) ? NBTBase.NBTTypes[tag.getId()] : null);
	}
	/** Gets a value from the ItemStack's custom NBT data. Example:

	 *   int color = ItemUtils.get(stack, -1, "display", "color");

	 *  Returns defaultValue if any parent compounds or the value tag don't exist. */
	public static <T> T get(ItemStack stack, T defaultValue, String... tags) {
		NBTBase tag = getTag(stack, tags);
		return (T)((tag != null) ? NbtUtils.getTagValue(tag) : defaultValue);
	}

	/** Sets a tag in the ItemStack's custom NBT data.

	 *  Creates parent compounds if they don't exist. */
	public static void set(ItemStack stack, NBTBase nbtTag, String... tags) {
		String tag = null;
		NBTTagCompound compound;
		if (!stack.hasTagCompound()) {
			compound = new NBTTagCompound();
			stack.setTagCompound(compound);
		} else compound = stack.getTagCompound();
		for (int i = 0; i < tags.length; i++) {
			tag = tags[i];
			if (i == tags.length - 1) break;
			if (!compound.hasKey(tag)) {
				NBTTagCompound newCompound = new NBTTagCompound();
				compound.setTag(tag, newCompound);
				compound = newCompound;
			} else compound = compound.getCompoundTag(tag);
		}
		compound.setTag(tag, nbtTag);
	}
	/** Sets a value in the ItemStack's custom NBT data. Example:

	 *   ItemUtils.set(stack, 0xFF0000, "display", "color");

	 *  Creates parent compounds if they don't exist. */
	public static <T> void set(ItemStack stack, T value, String... tags) {
		set(stack, NbtUtils.createTag(value), tags);
	}

	/** Returns if the tag exists in the ItemStack's custom NBT data. Example:

	 *   if (ItemUtils.has(stack, "display", "color")) ...  */
	public static boolean has(ItemStack stack, String... tags) {
		if (!stack.hasTagCompound()) return false;
		String tag = null;
		NBTTagCompound compound = stack.getTagCompound();
		for (int i = 0; i < tags.length; i++) {
			tag = tags[i];
			if (!compound.hasKey(tag)) return false;
			if (i == tags.length - 1) break;
			compound = compound.getCompoundTag(tag);
		}
		return compound.hasKey(tag);
	}

	/** Removes a value from the ItemStack's custom NBT data.

	 *  Gets rid of any empty parent compounds. Example:

	 *   ItemUtils.remove(stack, "display", "color");  */
	public static void remove(ItemStack stack, String... tags) {
		if (!stack.hasTagCompound()) return;
		String tag = null;
		NBTTagCompound compound = stack.getTagCompound();
		for (int i = 0; i < tags.length; i++) {
			tag = tags[i];
			if (!compound.hasKey(tag)) return;
			if (i == tags.length - 1) break;
			compound = compound.getCompoundTag(tag);
		}
		compound.removeTag(tag);
	}

	// Stack copying

	/** Creates a copy of an item stack with a specific stack size.

	 *  Returns null if the stack is null or stackSize is <= 0. */
	public static ItemStack copyStack(ItemStack stack, int stackSize) {
		return copyStack(stack, stackSize, true);
	}
	/** Creates a copy of an item stack with a specific stack size.
	 *  Returns null if the stack is null or stackSize is <= 0 and checkSize is true. */
	public static ItemStack copyStack(ItemStack stack, int stackSize, boolean checkSize) {
		if ((stack == null) || (checkSize && (stackSize <= 0))) return null;
		ItemStack copy = new ItemStack(stack.getItem(), stackSize, getRealItemDamage(stack));
		if (stack.stackTagCompound != null)
			copy.stackTagCompound = (NBTTagCompound)stack.stackTagCompound.copy();
		return copy;
	}

	// Stack matching

	public static boolean matches(Item item1, int damage1, NBTTagCompound data1,
	                              Item item2, int damage2, NBTTagCompound data2) {
		return ((item1 == item2) && (damage1 == damage2) && nbtEquals(data1, data2));
	}
	/** Returns if the two NBT compounds are equal.
	 *  Used instead of default comparison because this function
	 *  makes sure the names of the main NBT tags match before comparing. */
	public static boolean nbtEquals(NBTTagCompound nbt1, NBTTagCompound nbt2) {
		return ((nbt1 == nbt2) || (!((nbt1 == null) || (nbt2 == null)) && nbt1.equals(nbt2)));
	}
	/** Returns if the two item stacks match.

	 *  True when they're both null or their ID, damage and optionally NBT data match. */
	public static boolean matches(ItemStack stack1, ItemStack stack2, boolean matchNBT) {
		return ((stack1 == null) ? (stack2 == null) : ((stack2 != null) && matches(
				stack1.getItem(), StackUtils.getRealItemDamage(stack1), (matchNBT ? stack1.getTagCompound() : null),
				stack2.getItem(), StackUtils.getRealItemDamage(stack2), (matchNBT ? stack2.getTagCompound() : null))));
	}
	/** Returns if the two item stacks match.

	 *  True when they're both null or their ID, damage and NBT data match. */
	public static boolean matches(ItemStack stack1, ItemStack stack2) {
		return matches(stack1, stack2, true);
	}

	// Enchantment functions

	/** Returns the enchantments on the item stack. */
	public static Map<Integer, StackEnchantment> getEnchantments(ItemStack stack) {
		Map<Integer, StackEnchantment> enchantments = new HashMap<Integer, StackEnchantment>();
		NBTTagList list = ((stack.getItem() == Items.enchanted_book)
				? Items.enchanted_book.func_92110_g(stack)
				: stack.getEnchantmentTagList());
		if (list != null)
			for (int i = 0; i < list.tagCount(); i++) {
				StackEnchantment ench = new StackEnchantment(stack, list.getCompoundTagAt(i));
				enchantments.put(ench.ench.effectId, ench);
			}
		return enchantments;
	}

	/** Returns if the enchantment can go on this item stack. */
	public static boolean isEnchantmentCompatible(ItemStack stack,
	                                              Collection<StackEnchantment> stackEnchants,
	                                              StackEnchantment newEnchant) {
		if (!newEnchant.ench.canApply(stack)) return false;
		for (StackEnchantment stackEnch : stackEnchants)
			if ((newEnchant.ench == stackEnch.ench)
					? (newEnchant.getLevel() <= stackEnch.getLevel())
					: (!newEnchant.ench.canApplyTogether(stackEnch.ench) ||
					   !stackEnch.ench.canApplyTogether(newEnchant.ench))) return false;
		return true;
	}
	/** Returns if the enchantment can go on this item stack. */
	public static boolean isEnchantmentCompatible(ItemStack stack, StackEnchantment newEnchant) {
		return isEnchantmentCompatible(stack, getEnchantments(stack).values(), newEnchant);
	}

	/** Represents an enchantment entry on an item stack. */
	public static class StackEnchantment {
		public final ItemStack stack;
		public final Enchantment ench;
		private final NBTTagCompound entry;

		public int getLevel() { return entry.getShort("lvl"); }
		public void setLevel(int level) { entry.setShort("lvl", (short)level); }

		public StackEnchantment(ItemStack stack, NBTTagCompound entry) {
			this.stack = stack;
			this.entry = entry;
			this.ench = Enchantment.enchantmentsList[entry.getShort("id")];
		}
	}

	// Other functions, mostly BetterStorage related

	/** Returns the actual itemDamage value of an ItemStack. */
	public static int getRealItemDamage(ItemStack stack) {
		// Uses a vanilla item to return the actual value.
		return Items.emerald.getDamage(stack);
	}

	/** Gets the number of stacks the item would
	 *  split into under normal circumstances. */
	public static int calcNumStacks(ItemStack stack, int count) {
		int maxStackSize = stack.getMaxStackSize();
		return (count + maxStackSize - 1) / maxStackSize;
	}
	/** Gets the number of stacks the item would
	 *  split into under normal circumstances. */
	public static int calcNumStacks(ItemStack stack) {
		return calcNumStacks(stack, stack.stackSize);
	}

	/** Stacks items from the ItemStack array into the list.

	 *  Returns the number of stacks processed. */
	public static int stackItems(ItemStack[] contents, List<ItemStack> items) {
		int numStacks = 0;
		outerLoop:
		for (int i = 0; i < contents.length; i++) {
			ItemStack contentStack = contents[i];
			if (contentStack == null) continue;
			numStacks++;
			for (ItemStack itemsStack : items)
				if (StackUtils.matches(contentStack, itemsStack)) {
					itemsStack.stackSize += contentStack.stackSize;
					continue outerLoop;
				}
			items.add(contentStack);
		}
		return numStacks;
	}
	/** Returns items from the ItemStack array stacked into a list. */
	public static List<ItemStack> stackItems(ItemStack[] contents) {
		List<ItemStack> items = new ArrayList<ItemStack>();
		stackItems(contents, items);
		return items;
	}

	public static ItemStack[] getStackContents(ItemStack stack, int size) {
		ItemStack[] contents = new ItemStack[size];
		NBTTagCompound compound = stack.getTagCompound();
		if (compound != null && compound.hasKey("Items"))
			NbtUtils.readItems(contents, compound.getTagList("Items", NBT.TAG_COMPOUND));
		return contents;
	}

	public static void setStackContents(ItemStack stack, ItemStack[] contents) {
		set(stack, NbtUtils.writeItems(contents), "Items");
	}

	public static boolean isEmpty(ItemStack[] items) {
		for (int i = 0; i < items.length; i++)
			if (items[i] != null) return false;
		return true;
	}

	public static boolean isKey(ItemStack stack) {
		return (stack != null && stack.getItem() instanceof IKey);
	}
	public static boolean isLock(ItemStack stack) {
		return (stack != null && stack.getItem() instanceof ILock);
	}

	public static boolean canBeStoredInContainerItem(ItemStack item) {
		return (((item != null) && (item.getItem() instanceof IContainerItem))
				? ((IContainerItem)item.getItem()).canBeStoredInContainerItem(item)
				: true);
	}

}

redpajama_set_name: RedPajamaGithub


text:
import {Component, OnInit, Input} from "@angular/core"
import { ActivatedRoute, Params } from '@angular/router';

import {ViewModelService} from './viewmodel.service';
@Component({
    selector: 'very-simple',
    templateUrl: 'app/very-simple.component.html',
    providers:[
        ViewModelService
    ]
})
export class VerySimpleComponent implements OnInit {
    private idView: string = 'very-simple';
    private id:string;
    @Input()
    data: any;

    get a(){return this.data.a;}
    set a(value:any){
        this.viewModelService.setProp(this.idView, this.id, 'a', value)
    }

    get b(){return this.data.b;}
    set b(value:any){
        this.viewModelService.setProp(this.idView, this.id, 'b', value)
    }
    constructor(
        private viewModelService: ViewModelService,
        private route: ActivatedRoute) {    }

    ngOnInit(): void {
        this.route.params.forEach((params: Params)=>{
           this.id = params['id'];
        });
        this.viewModelService
            .getViewModel(this.idView, this.id)
            .then(data => this.data = data);
    }

    goBack(): void {
        window.history.back();
    }
}


text: Thanks for https://github.com/choumx/amp-pwa for content, design and resources!


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="440" android:versionName="4.4.0" package="com.actionbarsherlock">
  <uses-sdk android:minSdkVersion="7" android:targetSdkVersion="19"/>
  <application/>
</manifest>


text:
package com.github.rd.life

import scala.swing.Panel
import scala.swing.event.{MouseDragged, MousePressed, MouseReleased, MouseEvent}
import scala.actors.Actor
import scala.actors.Actor._
import scala.concurrent.Future
import scala.concurrent.future
import scala.concurrent.ExecutionContext.Implicits._

import java.awt.{Color, Dimension, Graphics2D}

class LifePanel(lifeActor: Actor) extends Panel {

  private val cellSize = 6
  private val cellGap = 1

  private val liveCellColor = new Color(0x505050)
  private val emptyCellColor = new Color(0xFFFFFF)

  private var rightBtnPressed = false
  private var leftBtnPressed = false

  private var simulation = false

  override def background = Color.BLACK

  val helper = actor {
    loop {
      react {
          case "ON" =>
            repaint
      }
    }
  }

  def isSimulation() = simulation

  listenTo(mouse.clicks, mouse.moves)

  reactions += {
    case e: MouseDragged => processCell(e)
    case e: MousePressed =>
      if (e.peer.getButton == java.awt.event.MouseEvent.BUTTON1) {
        leftBtnPressed = true
        rightBtnPressed = false
        processCell(e)
      } else if (e.peer.getButton == java.awt.event.MouseEvent.BUTTON3) {
        leftBtnPressed = false
        rightBtnPressed = true
        processCell(e)
      }
    case e: MouseReleased =>
      if (e.peer.getButton == java.awt.event.MouseEvent.BUTTON1) {
        leftBtnPressed = false
      } else if (e.peer.getButton == java.awt.event.MouseEvent.BUTTON3) {
        rightBtnPressed = false
      }
  }

  override def preferredSize: Dimension = {
    val (height, width) = getDimension()
    new Dimension(
      (cellSize + cellGap) * width + cellGap,
      (cellSize + cellGap) * height + cellGap
    )
  }

  override def paint(g: Graphics2D) {
    super.paint(g)
    val (height, width) = getDimension()

    for (x <- 0 until height) {
      for (y <- 0 until width) {
        val live = getCell(x, y)
        g.setColor(
          if (live == 1) liveCellColor else emptyCellColor
        )
        g.fillRect(
          (cellSize + cellGap) * x + cellGap,
          (cellSize + cellGap) * y + cellGap,
          cellSize,
          cellSize
        )
      }
    }
  }

  def clear() {
    lifeActor ! Cmd("CLEAR", helper)
    repaint
  }

  def startSimulation() {
    simulation = true
    lifeActor ! Cmd("START", helper)
  }

  def stopSimulation() {
    simulation = false
    lifeActor ! Cmd("STOP", helper)
  }

  def updateDelay(time: Int) {
    lifeActor ! DelayTime(time)
  }

  private def getDimension(): (Int, Int) = {
    lifeActor ! FieldDimension(Actor.self)
    val dimension = Actor.self.receive {
      case FieldDimensionRes(height, width) => FieldDimensionRes(height, width)
    }
    dimension match {
      case FieldDimensionRes(height, width) => (height, width)
      case _ => (100, 70)
    }
  }

  private def setCell(x: Int, y: Int, value: Byte) {
    lifeActor ! CellSetter(x, y, value)
  }

  private def getCell(x: Int, y: Int): Byte = {
    lifeActor ! CellGetter(x, y, Actor.self)
    val value = Actor.self.receive {
      case receivedValue: Byte => receivedValue
    }
    value
  }

  private def processCell(e: MouseEvent) {
    val x = e.point.x / (cellSize + cellGap)
    val y = e.point.y / (cellSize + cellGap)
    val (height, width) = getDimension()

    if (x >= 0 && x < height && y >= 0 && y < width) {
      if (rightBtnPressed) {
        setCell(x, y, 0)
        repaint
      }
      if (leftBtnPressed) {
        setCell(x, y, 1)
        repaint
      }
    }
  }
}


text:
This project is intended to give a Java wrapper for Watson Work Services REST and GraphQL APIs. For more information on the endpoints available, see https://workspace.ibm.com/developer. For a GraphQL tester site, see https://workspace.ibm.com/graphql.

**OpenCode4Workspace**

    This project is an OpenNTF project, and is available under the Apache License V2.0.
    All other aspects of the project, including contributions, defect reports, discussions,
    feature requests and reviews are subject to the OpenNTF Terms of Use - available at
    http://openntf.org/Internal/home.nsf/dx/Terms_of_Use.

## Issues Tracking ##
Report Issues here: [JIRA](https://jira.openntf.org/secure/RapidBoard.jspa?rapidView=22&projectKey=WWAPI&view=planning.nodetail "Report Issues")

## Full Documentation ##
See [OpenNTF Wiki](https://wiki.openntf.org/display/WWSJava/)

## Release Notes ##
### 0.8.0 ###
WWAPI-9 Added Focus endpoint to pass text to Watson Work Services for analysis against focus lenses
WWAPI-11 Re-authenticating requests
WWAPI-14 Added updatedSince as filter for Spaces query
WWAPI-15, WWAPI-16, WWAPI-17, WWAPI-18, WWAPI-19, WWAPI-23, WWAPI-24 Added "mentioned" to GraphQL queries
WWAPI-30, WWAPI-32, WWAPI-36 Added addSpaceMembers mutation
WWAPI-31 Added ibmUniqueID property to Person
WWAPI-34, WWAPI-36 Added removeSpaceMembers mutation
WWAPI-37 **CHANGE** membersUpdated property in space should be a date not a string
WWAPI-38 Changed TokenScope extraction to be an array
WWAPI-39 **CHANGE** Added methods to be able to access PageInfo objects in queries

### 0.7.0 ###
WWAPI-12 Ability to pass multiple query objects in a single request, supporting aliases
WWAPI-10 Support for Photo REST endpoint
WWAPI-13 Support for Files endpoint

### 0.6.0 ###
Mutations have been added for the following GraphQL mutations:
- createSpace
- deleteSpace
- updateSpace


text:
from struct import pack, unpack
import os, sys, time, io
import traceback

from electrum.bip32 import BIP32Node, InvalidMasterKeyVersionBytes
from electrum.i18n import _
from electrum.plugin import Device
from electrum.keystore import Hardware_KeyStore, xpubkey_to_pubkey, Xpub
from electrum.transaction import Transaction
from electrum.wallet import Standard_Wallet
from electrum.crypto import hash_160
from electrum.util import bfh, bh2u, versiontuple, UserFacingException
from electrum.base_wizard import ScriptTypeNotSupported
from electrum.logging import get_logger

from ..hw_wallet import HW_PluginBase
from ..hw_wallet.plugin import LibraryFoundButUnusable

_logger = get_logger(__name__)

try:
    import hid
    from ckcc.protocol import CCProtocolPacker, CCProtocolUnpacker
    from ckcc.protocol import CCProtoError, CCUserRefused, CCBusyError
    from ckcc.constants import (MAX_MSG_LEN, MAX_BLK_LEN, MSG_SIGNING_MAX_LENGTH, MAX_TXN_LEN,
        AF_CLASSIC, AF_P2SH, AF_P2WPKH, AF_P2WSH, AF_P2WPKH_P2SH, AF_P2WSH_P2SH)
    from ckcc.constants import (
        PSBT_GLOBAL_UNSIGNED_TX, PSBT_IN_NON_WITNESS_UTXO, PSBT_IN_WITNESS_UTXO,
        PSBT_IN_SIGHASH_TYPE, PSBT_IN_REDEEM_SCRIPT, PSBT_IN_WITNESS_SCRIPT,
        PSBT_IN_BIP32_DERIVATION, PSBT_OUT_BIP32_DERIVATION, PSBT_OUT_REDEEM_SCRIPT)

    from ckcc.client import ColdcardDevice, COINKITE_VID, CKCC_PID, CKCC_SIMULATOR_PATH

    requirements_ok = True

    class ElectrumColdcardDevice(ColdcardDevice):
        # avoid use of pycoin for MiTM message signature test
        def mitm_verify(self, sig, expect_xpub):
            # verify a signature (65 bytes) over the session key, using the master bip32 node
            # - customized to use specific EC library of Electrum.
            pubkey = BIP32Node.from_xkey(expect_xpub).eckey
            try:
                pubkey.verify_message_hash(sig[1:65], self.session_key)
                return True
            except:
                return False

except ImportError:
    requirements_ok = False

    COINKITE_VID = 0xd13e
    CKCC_PID     = 0xcc10

CKCC_SIMULATED_PID = CKCC_PID ^ 0x55aa

def my_var_int(l):
    # Bitcoin serialization of integers... directly into binary!
    if l < 253:
        return pack("B", l)
    elif l < 0x10000:
        return pack("<BH", 253, l)
    elif l < 0x100000000:
        return pack("<BI", 254, l)
    else:
        return pack("<BQ", 255, l)

def xfp_from_xpub(xpub):
    # sometime we need to BIP32 fingerprint value: 4 bytes of ripemd(sha256(pubkey))
    # UNTESTED
    kk = bfh(Xpub.get_pubkey_from_xpub(xpub, []))
    assert len(kk) == 33
    xfp, = unpack('<I', hash_160(kk)[0:4])
    return xfp

class CKCCClient:
    # Challenge: I haven't found anywhere that defines a base class for this 'client',
    # nor an API (interface) to be met. Winging it. Gets called from lib/plugins.py mostly?

    def __init__(self, plugin, handler, dev_path, is_simulator=False):
        self.device = plugin.device
        self.handler = handler

        # if we know what the (xfp, xpub) "should be" then track it here
        self._expected_device = None

        if is_simulator:
            self.dev = ElectrumColdcardDevice(dev_path, encrypt=True)
        else:
            # open the real HID device
            import hid
            hd = hid.device(path=dev_path)
            hd.open_path(dev_path)

            self.dev = ElectrumColdcardDevice(dev=hd, encrypt=True)

        # NOTE: MiTM test is delayed until we have a hint as to what XPUB we
        # should expect. It's also kinda slow.

    def __repr__(self):
        return '<CKCCClient: xfp=%08x label=%r>' % (self.dev.master_fingerprint,
                                                        self.label())

    def verify_connection(self, expected_xfp, expected_xpub):
        ex = (expected_xfp, expected_xpub)

        if self._expected_device == ex:
            # all is as expected
            return

        if ( (self._expected_device is not None)
                or (self.dev.master_fingerprint != expected_xfp)
                or (self.dev.master_xpub != expected_xpub)):
            # probably indicating programing error, not hacking
            _logger.info(f"xpubs. reported by device: {self.dev.master_xpub}. "
                         f"stored in file: {expected_xpub}")
            raise RuntimeError("Expecting 0x%08x but that's not what's connected?!" %
                               expected_xfp)

        # check signature over session key
        # - mitm might have lied about xfp and xpub up to here
        # - important that we use value capture at wallet creation time, not some value
        #   we read over USB today
        self.dev.check_mitm(expected_xpub=expected_xpub)

        self._expected_device = ex

        _logger.info("Successfully verified against MiTM")

    def is_pairable(self):
        # can't do anything w/ devices that aren't setup (but not normally reachable)
        return bool(self.dev.master_xpub)

    def timeout(self, cutoff):
        # nothing to do?
        pass

    def close(self):
        # close the HID device (so can be reused)
        self.dev.close()
        self.dev = None

    def is_initialized(self):
        return bool(self.dev.master_xpub)

    def label(self):
        # 'label' of this Coldcard. Warning: gets saved into wallet file, which might
        # not be encrypted, so better for privacy if based on xpub/fingerprint rather than
        # USB serial number.
        if self.dev.is_simulator:
            lab = 'Coldcard Simulator 0x%08x' % self.dev.master_fingerprint
        elif not self.dev.master_fingerprint:
            # failback; not expected
            lab = 'Coldcard #' + self.dev.serial
        else:
            lab = 'Coldcard 0x%08x' % self.dev.master_fingerprint

        # Hack zone: during initial setup I need the xfp and master xpub but
        # very few objects are passed between the various steps of base_wizard.
        # Solution: return a string with some hidden metadata
        # - see <https://stackoverflow.com/questions/7172772/abc-for-string>
        # - needs to work w/ deepcopy
        class LabelStr(str):
            def __new__(cls, s, xfp=None, xpub=None):
                self = super().__new__(cls, str(s))
                self.xfp = getattr(s, 'xfp', xfp)
                self.xpub = getattr(s, 'xpub', xpub)
                return self

        return LabelStr(lab, self.dev.master_fingerprint, self.dev.master_xpub)

    def has_usable_connection_with_device(self):
        # Do end-to-end ping test
        try:
            self.ping_check()
            return True
        except:
            return False

    def get_xpub(self, bip32_path, xtype):
        assert xtype in ColdcardPlugin.SUPPORTED_XTYPES
        _logger.info('Derive xtype = %r' % xtype)
        xpub = self.dev.send_recv(CCProtocolPacker.get_xpub(bip32_path), timeout=5000)
        # TODO handle timeout?
        # change type of xpub to the requested type
        try:
            node = BIP32Node.from_xkey(xpub)
        except InvalidMasterKeyVersionBytes:
            raise UserFacingException(_('Invalid xpub magic. Make sure your {} device is set to the correct chain.')
                                      .format(self.device)) from None
        if xtype != 'standard':
            xpub = node._replace(xtype=xtype).to_xpub()
        return xpub

    def ping_check(self):
        # check connection is working
        assert self.dev.session_key, 'not encrypted?'
        req = b'1234 Electrum Plugin 4321'      # free up to 59 bytes
        try:
            echo = self.dev.send_recv(CCProtocolPacker.ping(req))
            assert echo == req
        except:
            raise RuntimeError("Communication trouble with Coldcard")

    def show_address(self, path, addr_fmt):
        # prompt user w/ addres, also returns it immediately.
        return self.dev.send_recv(CCProtocolPacker.show_address(path, addr_fmt), timeout=None)

    def get_version(self):
        # gives list of strings
        return self.dev.send_recv(CCProtocolPacker.version(), timeout=1000).split('\n')

    def sign_message_start(self, path, msg):
        # this starts the UX experience.
        self.dev.send_recv(CCProtocolPacker.sign_message(msg, path), timeout=None)

    def sign_message_poll(self):
        # poll device... if user has approved, will get tuple: (addr, sig) else None
        return self.dev.send_recv(CCProtocolPacker.get_signed_msg(), timeout=None)

    def sign_transaction_start(self, raw_psbt, finalize=True):
        # Multiple steps to sign:
        # - upload binary
        # - start signing UX
        # - wait for coldcard to complete process, or have it refused.
        # - download resulting txn
        assert 20 <= len(raw_psbt) < MAX_TXN_LEN, 'PSBT is too big'
        dlen, chk = self.dev.upload_file(raw_psbt)

        resp = self.dev.send_recv(CCProtocolPacker.sign_transaction(dlen, chk, finalize=finalize),
                                    timeout=None)

        if resp != None:
            raise ValueError(resp)

    def sign_transaction_poll(self):
        # poll device... if user has approved, will get tuple: (legnth, checksum) else None
        return self.dev.send_recv(CCProtocolPacker.get_signed_txn(), timeout=None)

    def download_file(self, length, checksum, file_number=1):
        # get a file
        return self.dev.download_file(length, checksum, file_number=file_number)

class Coldcard_KeyStore(Hardware_KeyStore):
    hw_type = 'coldcard'
    device = 'Coldcard'

    def __init__(self, d):
        Hardware_KeyStore.__init__(self, d)
        # Errors and other user interaction is done through the wallet's
        # handler.  The handler is per-window and preserved across
        # device reconnects
        self.force_watching_only = False
        self.ux_busy = False

        # Seems like only the derivation path and resulting **derived** xpub is stored in
        # the wallet file... however, we need to know at least the fingerprint of the master
        # xpub to verify against MiTM, and also so we can put the right value into the subkey paths
        # of PSBT files that might be generated offline.
        # - save the fingerprint of the master xpub, as "xfp"
        # - it's a LE32 int, but hex more natural way to see it
        # - device reports these value during encryption setup process
        lab = d['label']
        if hasattr(lab, 'xfp'):
            # initial setup
            self.ckcc_xfp = lab.xfp
            self.ckcc_xpub = lab.xpub
        else:
            # wallet load: fatal if missing, we need them!
            self.ckcc_xfp = d['ckcc_xfp']
            self.ckcc_xpub = d['ckcc_xpub']

    def dump(self):
        # our additions to the stored data about keystore -- only during creation?
        d = Hardware_KeyStore.dump(self)

        d['ckcc_xfp'] = self.ckcc_xfp
        d['ckcc_xpub'] = self.ckcc_xpub

        return d

    def get_derivation(self):
        return self.derivation

    def get_client(self):
        # called when user tries to do something like view address, sign somthing.
        # - not called during probing/setup
        rv = self.plugin.get_client(self)
        if rv:
            rv.verify_connection(self.ckcc_xfp, self.ckcc_xpub)

        return rv

    def give_error(self, message, clear_client=False):
        self.logger.info(message)
        if not self.ux_busy:
            self.handler.show_error(message)
        else:
            self.ux_busy = False
        if clear_client:
            self.client = None
        raise UserFacingException(message)

    def wrap_busy(func):
        # decorator: function takes over the UX on the device.
        def wrapper(self, *args, **kwargs):
            try:
                self.ux_busy = True
                return func(self, *args, **kwargs)
            finally:
                self.ux_busy = False
        return wrapper

    def decrypt_message(self, pubkey, message, password):
        raise UserFacingException(_('Encryption and decryption are currently not supported for {}').format(self.device))

    @wrap_busy
    def sign_message(self, sequence, message, password):
        # Sign a message on device. Since we have big screen, of course we
        # have to show the message unabiguously there first!
        try:
            msg = message.encode('ascii', errors='strict')
            assert 1 <= len(msg) <= MSG_SIGNING_MAX_LENGTH
        except (UnicodeError, AssertionError):
            # there are other restrictions on message content,
            # but let the device enforce and report those
            self.handler.show_error('Only short (%d max) ASCII messages can be signed.'
                                            % MSG_SIGNING_MAX_LENGTH)
            return b''

        client = self.get_client()
        path = self.get_derivation() + ("/%d/%d" % sequence)
        try:
            cl = self.get_client()
            try:
                self.handler.show_message("Signing message (using %s)..." % path)

                cl.sign_message_start(path, msg)

                while 1:
                    # How to kill some time, without locking UI?
                    time.sleep(0.250)

                    resp = cl.sign_message_poll()
                    if resp is not None:
                        break

            finally:
                self.handler.finished()

            assert len(resp) == 2
            addr, raw_sig = resp

            # already encoded in Bitcoin fashion, binary.
            assert 40 < len(raw_sig) <= 65

            return raw_sig

        except (CCUserRefused, CCBusyError) as exc:
            self.handler.show_error(str(exc))
        except CCProtoError as exc:
            self.logger.exception('Error showing address')
            self.handler.show_error('{}\n\n{}'.format(
                _('Error showing address') + ':', str(exc)))
        except Exception as e:
            self.give_error(e, True)

        # give empty bytes for error cases; it seems to clear the old signature box
        return b''

    def build_psbt(self, tx: Transaction, wallet=None, xfp=None):
        # Render a PSBT file, for upload to Coldcard.
        #
        if xfp is None:
            # need fingerprint of MASTER xpub, not the derived key
            xfp = self.ckcc_xfp

        inputs = tx.inputs()

        if 'prev_tx' not in inputs[0]:
            # fetch info about inputs, if needed?
            # - needed during export PSBT flow, not normal online signing
            assert wallet, 'need wallet reference'
            wallet.add_hw_info(tx)

        # wallet.add_hw_info installs this attr
        assert tx.output_info is not None, 'need data about outputs'

        # Build map of pubkey needed as derivation from master, in PSBT binary format
        # 1) binary version of the common subpath for all keys
        #       m/ => fingerprint LE32
        #       a/b/c => ints
        base_path = pack('<I', xfp)
        for x in self.get_derivation()[2:].split('/'):
            if x.endswith("'"):
                x = int(x[:-1]) | 0x80000000
            else:
                x = int(x)
            base_path += pack('<I', x)

        # 2) all used keys in transaction
        subkeys = {}
        derivations = self.get_tx_derivations(tx)
        for xpubkey in derivations:
            pubkey = xpubkey_to_pubkey(xpubkey)

            # assuming depth two, non-harded: change + index
            aa, bb = derivations[xpubkey]
            assert 0 <= aa < 0x80000000
            assert 0 <= bb < 0x80000000

            subkeys[bfh(pubkey)] = base_path + pack('<II', aa, bb)

        for txin in inputs:
            if txin['type'] == 'coinbase':
                self.give_error("Coinbase not supported")

            if txin['type'] in ['p2sh', 'p2wsh-p2sh', 'p2wsh']:
                self.give_error('No support yet for inputs of type: ' + txin['type'])

        # Construct PSBT from start to finish.
        out_fd = io.BytesIO()
        out_fd.write(b'psbt\xff')

        def write_kv(ktype, val, key=b''):
            # serialize helper: write w/ size and key byte
            out_fd.write(my_var_int(1 + len(key)))
            out_fd.write(bytes([ktype]) + key)

            if isinstance(val, str):
                val = bfh(val)

            out_fd.write(my_var_int(len(val)))
            out_fd.write(val)

        # global section: just the unsigned txn
        class CustomTXSerialization(Transaction):
            @classmethod
            def input_script(cls, txin, estimate_size=False):
                return ''

        unsigned = bfh(CustomTXSerialization(tx.serialize()).serialize_to_network(witness=False))
        write_kv(PSBT_GLOBAL_UNSIGNED_TX, unsigned)

        # end globals section
        out_fd.write(b'\x00')

        # inputs section
        for txin in inputs:
            if Transaction.is_segwit_input(txin):
                utxo = txin['prev_tx'].outputs()[txin['prevout_n']]
                spendable = txin['prev_tx'].serialize_output(utxo)
                write_kv(PSBT_IN_WITNESS_UTXO, spendable)
            else:
                write_kv(PSBT_IN_NON_WITNESS_UTXO, str(txin['prev_tx']))

            pubkeys, x_pubkeys = tx.get_sorted_pubkeys(txin)

            pubkeys = [bfh(k) for k in pubkeys]

            for k in pubkeys:
                write_kv(PSBT_IN_BIP32_DERIVATION, subkeys[k], k)

                if txin['type'] == 'p2wpkh-p2sh':
                    assert len(pubkeys) == 1, 'can be only one redeem script per input'
                    pa = hash_160(k)
                    assert len(pa) == 20
                    write_kv(PSBT_IN_REDEEM_SCRIPT, b'\x00\x14'+pa)

            out_fd.write(b'\x00')

        # outputs section
        for o in tx.outputs():
            # can be empty, but must be present, and helpful to show change inputs
            # wallet.add_hw_info() adds some data about change outputs into tx.output_info
            if o.address in tx.output_info:
                # this address "is_mine" but might not be change (I like to sent to myself)
                output_info = tx.output_info.get(o.address)
                index, xpubs = output_info.address_index, output_info.sorted_xpubs

                if index[0] == 1 and len(index) == 2:
                    # it is a change output (based on our standard derivation path)
                    assert len(xpubs) == 1      # not expecting multisig
                    xpubkey = xpubs[0]

                    # document its bip32 derivation in output section
                    aa, bb = index
                    assert 0 <= aa < 0x80000000
                    assert 0 <= bb < 0x80000000

                    deriv = base_path + pack('<II', aa, bb)
                    pubkey = bfh(self.get_pubkey_from_xpub(xpubkey, index))

                    write_kv(PSBT_OUT_BIP32_DERIVATION, deriv, pubkey)

                    if output_info.script_type == 'p2wpkh-p2sh':
                        pa = hash_160(pubkey)
                        assert len(pa) == 20
                        write_kv(PSBT_OUT_REDEEM_SCRIPT, b'\x00\x14' + pa)

            out_fd.write(b'\x00')

        return out_fd.getvalue()

    @wrap_busy
    def sign_transaction(self, tx, password):
        # Build a PSBT in memory, upload it for signing.
        # - we can also work offline (without paired device present)
        if tx.is_complete():
            return

        client = self.get_client()

        assert client.dev.master_fingerprint == self.ckcc_xfp

        raw_psbt = self.build_psbt(tx)

        #open('debug.psbt', 'wb').write(out_fd.getvalue())

        try:
            try:
                self.handler.show_message("Authorize Transaction...")

                client.sign_transaction_start(raw_psbt, True)

                while 1:
                    # How to kill some time, without locking UI?
                    time.sleep(0.250)

                    resp = client.sign_transaction_poll()
                    if resp is not None:
                        break

                rlen, rsha = resp

                # download the resulting txn.
                new_raw = client.download_file(rlen, rsha)

            finally:
                self.handler.finished()

        except (CCUserRefused, CCBusyError) as exc:
            self.logger.info(f'Did not sign: {exc}')
            self.handler.show_error(str(exc))
            return
        except BaseException as e:
            self.logger.exception('')
            self.give_error(e, True)
            return

        # trust the coldcard to re-searilize final product right?
        tx.update(bh2u(new_raw))

    @staticmethod
    def _encode_txin_type(txin_type):
        # Map from Electrum code names to our code numbers.
        return {'standard': AF_CLASSIC, 'p2pkh': AF_CLASSIC,
                'p2sh': AF_P2SH,
                'p2wpkh-p2sh': AF_P2WPKH_P2SH,
                'p2wpkh': AF_P2WPKH,
                'p2wsh-p2sh': AF_P2WSH_P2SH,
                'p2wsh': AF_P2WSH,
                }[txin_type]

    @wrap_busy
    def show_address(self, sequence, txin_type):
        client = self.get_client()
        address_path = self.get_derivation()[2:] + "/%d/%d"%sequence
        addr_fmt = self._encode_txin_type(txin_type)
        try:
            try:
                self.handler.show_message(_("Showing address ..."))
                dev_addr = client.show_address(address_path, addr_fmt)
                # we could double check address here
            finally:
                self.handler.finished()
        except CCProtoError as exc:
            self.logger.exception('Error showing address')
            self.handler.show_error('{}\n\n{}'.format(
                _('Error showing address') + ':', str(exc)))
        except BaseException as exc:
            self.logger.exception('')
            self.handler.show_error(exc)

class ColdcardPlugin(HW_PluginBase):
    keystore_class = Coldcard_KeyStore
    minimum_library = (0, 7, 2)
    client = None

    DEVICE_IDS = [
        (COINKITE_VID, CKCC_PID),
        (COINKITE_VID, CKCC_SIMULATED_PID)
    ]

    #SUPPORTED_XTYPES = ('standard', 'p2wpkh-p2sh', 'p2wpkh', 'p2wsh-p2sh', 'p2wsh')
    SUPPORTED_XTYPES = ('standard', 'p2wpkh', 'p2wpkh-p2sh')

    def __init__(self, parent, config, name):
        HW_PluginBase.__init__(self, parent, config, name)

        self.libraries_available = self.check_libraries_available()
        if not self.libraries_available:
            return

        self.device_manager().register_devices(self.DEVICE_IDS)
        self.device_manager().register_enumerate_func(self.detect_simulator)

    def get_library_version(self):
        import ckcc
        try:
            version = ckcc.__version__
        except AttributeError:
            version = 'unknown'
        if requirements_ok:
            return version
        else:
            raise LibraryFoundButUnusable(library_version=version)

    def detect_simulator(self):
        # if there is a simulator running on this machine,
        # return details about it so it's offered as a pairing choice
        fn = CKCC_SIMULATOR_PATH

        if os.path.exists(fn):
            return [Device(path=fn,
                           interface_number=-1,
                           id_=fn,
                           product_key=(COINKITE_VID, CKCC_SIMULATED_PID),
                           usage_page=0,
                           transport_ui_string='simulator')]

        return []

    def create_client(self, device, handler):
        if handler:
            self.handler = handler

        # We are given a HID device, or at least some details about it.
        # Not sure why not we aren't just given a HID library handle, but
        # the 'path' is unabiguous, so we'll use that.
        try:
            rv = CKCCClient(self, handler, device.path,
                    is_simulator=(device.product_key[1] == CKCC_SIMULATED_PID))
            return rv
        except:
            self.logger.info('late failure connecting to device?')
            return None

    def setup_device(self, device_info, wizard, purpose):
        devmgr = self.device_manager()
        device_id = device_info.device.id_
        client = devmgr.client_by_id(device_id)
        if client is None:
            raise UserFacingException(_('Failed to create a client for this device.') + '\n' +
                                      _('Make sure it is in the correct state.'))
        client.handler = self.create_handler(wizard)

    def get_xpub(self, device_id, derivation, xtype, wizard):
        # this seems to be part of the pairing process only, not during normal ops?
        # base_wizard:on_hw_derivation
        if xtype not in self.SUPPORTED_XTYPES:
            raise ScriptTypeNotSupported(_('This type of script is not supported with {}.').format(self.device))
        devmgr = self.device_manager()
        client = devmgr.client_by_id(device_id)
        client.handler = self.create_handler(wizard)
        client.ping_check()

        xpub = client.get_xpub(derivation, xtype)
        return xpub

    def get_client(self, keystore, force_pair=True):
        # All client interaction should not be in the main GUI thread
        devmgr = self.device_manager()
        handler = keystore.handler
        with devmgr.hid_lock:
            client = devmgr.client_for_keystore(self, handler, keystore, force_pair)
        # returns the client for a given keystore. can use xpub
        #if client:
        #    client.used()
        if client is not None:
            client.ping_check()
        return client

    def show_address(self, wallet, address, keystore=None):
        if keystore is None:
            keystore = wallet.get_keystore()
        if not self.show_address_helper(wallet, address, keystore):
            return

        # Standard_Wallet => not multisig, must be bip32
        if type(wallet) is not Standard_Wallet:
            keystore.handler.show_error(_('This function is only available for standard wallets when using {}.').format(self.device))
            return

        sequence = wallet.get_address_index(address)
        txin_type = wallet.get_txin_type(address)
        keystore.show_address(sequence, txin_type)

# EOF


text:
"""Tests for pw_cli.envparse."""

import math
import unittest

from pw_cli import envparse

# pylint: disable=no-member

class ErrorError(Exception):
    pass

def error(value: str):
    raise ErrorError('error!')

class TestEnvironmentParser(unittest.TestCase):
    """Tests for envparse.EnvironmentParser."""
    def setUp(self):
        self.raw_env = {
            'PATH': '/bin:/usr/bin:/usr/local/bin',
            'FOO': '2020',
            'ReVeRsE': 'pigweed',
        }

        self.parser = envparse.EnvironmentParser(error_on_unrecognized=True)
        self.parser.add_var('PATH')
        self.parser.add_var('FOO', type=int)
        self.parser.add_var('BAR', type=bool)
        self.parser.add_var('BAZ', type=float, default=math.pi)
        self.parser.add_var('ReVeRsE', type=lambda s: s[::-1])
        self.parser.add_var('INT', type=int)
        self.parser.add_var('ERROR', type=error)

    def test_string_value(self):
        env = self.parser.parse_env(env=self.raw_env)
        self.assertEqual(env.PATH, self.raw_env['PATH'])

    def test_int_value(self):
        env = self.parser.parse_env(env=self.raw_env)
        self.assertEqual(env.FOO, 2020)

    def test_custom_value(self):
        env = self.parser.parse_env(env=self.raw_env)
        self.assertEqual(env.ReVeRsE, 'deewgip')

    def test_empty_value(self):
        env = self.parser.parse_env(env=self.raw_env)
        self.assertEqual(env.BAR, None)

    def test_default_value(self):
        env = self.parser.parse_env(env=self.raw_env)
        self.assertEqual(env.BAZ, math.pi)

    def test_unknown_key(self):
        env = self.parser.parse_env(env=self.raw_env)
        with self.assertRaises(AttributeError):
            env.BBBBB  # pylint: disable=pointless-statement

    def test_bad_value(self):
        raw_env = {**self.raw_env, 'INT': 'not an int'}
        with self.assertRaises(envparse.EnvironmentValueError) as ctx:
            self.parser.parse_env(env=raw_env)

        self.assertEqual(ctx.exception.variable, 'INT')
        self.assertIsInstance(ctx.exception.__cause__, ValueError)

    def test_custom_exception(self):
        raw_env = {**self.raw_env, 'ERROR': 'error'}
        with self.assertRaises(envparse.EnvironmentValueError) as ctx:
            self.parser.parse_env(env=raw_env)

        self.assertEqual(ctx.exception.variable, 'ERROR')
        self.assertIsInstance(ctx.exception.__cause__, ErrorError)

class TestEnvironmentParserWithPrefix(unittest.TestCase):
    """Tests for envparse.EnvironmentParser using a prefix."""
    def setUp(self):
        self.raw_env = {
            'PW_FOO': '001',
            'PW_BAR': '010',
            'PW_BAZ': '100',
            'IGNORED': '011',
        }

    def test_parse_unrecognized_variable(self):
        parser = envparse.EnvironmentParser(prefix='PW_',
                                            error_on_unrecognized=True)
        parser.add_var('PW_FOO')
        parser.add_var('PW_BAR')

        with self.assertRaises(ValueError):
            parser.parse_env(env=self.raw_env)

    def test_parse_unrecognized_but_allowed_suffix(self):
        parser = envparse.EnvironmentParser(prefix='PW_',
                                            error_on_unrecognized=True)
        parser.add_allowed_suffix('_ALLOWED_SUFFIX')

        env = parser.parse_env(env={'PW_FOO_ALLOWED_SUFFIX': '001'})
        self.assertEqual(env.PW_FOO_ALLOWED_SUFFIX, '001')

    def test_parse_allowed_suffix_but_not_suffix(self):
        parser = envparse.EnvironmentParser(prefix='PW_',
                                            error_on_unrecognized=True)
        parser.add_allowed_suffix('_ALLOWED_SUFFIX')

        with self.assertRaises(ValueError):
            parser.parse_env(env={'PW_FOO_ALLOWED_SUFFIX_FOO': '001'})

    def test_parse_ignore_unrecognized(self):
        parser = envparse.EnvironmentParser(prefix='PW_',
                                            error_on_unrecognized=False)
        parser.add_var('PW_FOO')
        parser.add_var('PW_BAR')

        env = parser.parse_env(env=self.raw_env)
        self.assertEqual(env.PW_FOO, self.raw_env['PW_FOO'])
        self.assertEqual(env.PW_BAR, self.raw_env['PW_BAR'])

    def test_add_var_without_prefix(self):
        parser = envparse.EnvironmentParser(prefix='PW_',
                                            error_on_unrecognized=True)
        with self.assertRaises(ValueError):
            parser.add_var('FOO')

class TestStrictBool(unittest.TestCase):
    """Tests for envparse.strict_bool."""
    def setUp(self):
        self.good_bools = ['true', '1', 'TRUE', 'tRuE']
        self.bad_bools = [
            '', 'false', '0', 'foo', '2', '999', 'ok', 'yes', 'no'
        ]

    def test_good_bools(self):
        self.assertTrue(
            all(envparse.strict_bool(val) for val in self.good_bools))

    def test_bad_bools(self):
        self.assertFalse(
            any(envparse.strict_bool(val) for val in self.bad_bools))

if __name__ == '__main__':
    unittest.main()


text:
'use strict';

import { isArray } from './types';

export const empty: IDisposable = Object.freeze({
	dispose() { }
});

export interface IDisposable {
	dispose(): void;
}

export function dispose<T extends IDisposable>(...disposables: T[]): T;
export function dispose<T extends IDisposable>(disposables: T[]): T[];
export function dispose<T extends IDisposable>(...disposables: T[]): T[] {
	const first = disposables[0];

	if (isArray(first)) {
		disposables = first as any as T[];
	}

	disposables.forEach(d => d && d.dispose());
	return [];
}

export function combinedDisposable(disposables: IDisposable[]): IDisposable;
export function combinedDisposable(...disposables: IDisposable[]): IDisposable;
export function combinedDisposable(disposables: any): IDisposable {
	return { dispose: () => dispose(disposables) };
}

export function toDisposable(...fns: (() => void)[]): IDisposable {
	return combinedDisposable(fns.map(fn => ({ dispose: fn })));
}

export abstract class Disposable implements IDisposable {

	private _toDispose: IDisposable[];

	constructor() {
		this._toDispose = [];
	}

	public dispose(): void {
		this._toDispose = dispose(this._toDispose);
	}

	protected _register<T extends IDisposable>(t:T): T {
		this._toDispose.push(t);
		return t;
	}
}

export class Disposables extends Disposable {

	public add<T extends IDisposable>(e: T): T;
	public add(...elements: IDisposable[]): void;
	public add<T extends IDisposable>(arg: T | T[]): T {
		if (!Array.isArray(arg)) {
			return this._register(arg);
		} else {
			for (let element of arg) {
				return this._register(element);
			}
		}
	}
}


text:
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class AddTitleToWidgets extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        //
        Schema::table("widgets", function ($table) {

            $table -> string("title");

        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        //
        Schema::table("widgets", function ($table) {

            $table -> dropColumn("title");

        });
    }
}


text:
#pragma once

#include "arch/IArchNetwork.h"
#include "common/IInterface.h"

//! Socket multiplexer job
/*!
A socket multiplexer job handles events on a socket.
*/
class ISocketMultiplexerJob : public IInterface {
public:
	//! @name manipulators
	//@{

	//! Handle socket event
	/*!
	Called by a socket multiplexer when the socket becomes readable,
	writable, or has an error.  It should return itself if the same
	job can continue to service events, a new job if the socket must
	be serviced differently, or NULL if the socket should no longer
	be serviced.  The socket is readable if \p readable is true,
	writable if \p writable is true, and in error if \p error is
	true.

	This call must not attempt to directly change the job for this
	socket by calling \c addSocket() or \c removeSocket() on the
	multiplexer.  It must instead return the new job.  It can,
	however, add or remove jobs for other sockets.
	*/
	virtual ISocketMultiplexerJob*
						run(bool readable, bool writable, bool error) = 0;

	//@}
	//! @name accessors
	//@{

	//! Get the socket
	/*!
	Return the socket to multiplex
	*/
	virtual ArchSocket	getSocket() const = 0;

	//! Check for interest in readability
	/*!
	Return true if the job is interested in being run if the socket
	becomes readable.
	*/
	virtual bool		isReadable() const = 0;

	//! Check for interest in writability
	/*!
	Return true if the job is interested in being run if the socket
	becomes writable.
	*/
	virtual bool		isWritable() const = 0;

	//@}
};


text:
namespace {

const char kBackground[] = "background";
const char kPersistent[] = "persistent";

}  // namespace

const WindowContainerType WINDOW_CONTAINER_TYPE_NORMAL =
    content::mojom::WindowContainerType::NORMAL;
const WindowContainerType WINDOW_CONTAINER_TYPE_BACKGROUND =
    content::mojom::WindowContainerType::BACKGROUND;
const WindowContainerType WINDOW_CONTAINER_TYPE_PERSISTENT =
    content::mojom::WindowContainerType::PERSISTENT;

WindowContainerType WindowFeaturesToContainerType(
    const blink::WebWindowFeatures& window_features) {
  bool background = false;
  bool persistent = false;

  for (size_t i = 0; i < window_features.additionalFeatures.size(); ++i) {
    base::string16 feature = window_features.additionalFeatures[i];
    if (base::LowerCaseEqualsASCII(feature, kBackground))
      background = true;
    else if (base::LowerCaseEqualsASCII(feature, kPersistent))
      persistent = true;
  }

  if (background) {
    if (persistent)
      return WINDOW_CONTAINER_TYPE_PERSISTENT;
    else
      return WINDOW_CONTAINER_TYPE_BACKGROUND;
  } else {
    return WINDOW_CONTAINER_TYPE_NORMAL;
  }
}


text:
package org.hdiv.session;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * It is composed by a data structure limited by a maximun size (maxSize). Map data
 * structure is composed by elements of type IPage (all the possible requests
 * generated in the request processing).
 *
 * @author Roberto Velasco
 */
public class StateCache implements IStateCache {

	/**
	 * Commons Logging instance.
	 */
	private static final Log log = LogFactory.getLog(StateCache.class);

	/**
	 * Universal version identifier. Deserialization uses this number to ensure that
	 * a loaded class corresponds exactly to a serialized object.
	 */
	private static final long serialVersionUID = -386843742684433849L;

	/**
	 * Buffer size
	 */
	private int maxSize;

	/**
	 * page's ids map
	 */
	private List pageIds;

	/**
	 * pageIds map initialization
	 */
	public void init() {
		this.pageIds = new ArrayList();
	}

	/**
	 * Adds a new page identifier to the map pageIds.
	 *
	 * @return If the map pageIds has reached its maximun size
	 *         maxSize, the oldest page identifier is deleted.
	 *         Otherwise, null will be returned.
	 */
	public synchronized String addPage(String key) {

		if(log.isDebugEnabled()){
			log.debug("Page with ["+key+"] added to the cache.");
		}
		String removedKey = this.cleanBuffer();
		this.pageIds.add(key);

		return removedKey;
	}

	/**
	 * If the map pageIds has reached its maximun size
	 * maxSize, the oldest page identifier in the map is deleted.
	 *
	 * @return Oldest page identifier in the map pageIds. Null in
	 *         otherwise.
	 */
	public String cleanBuffer() {

		if (this.pageIds.size() >= this.maxSize) {

			// delete first element
			String key = (String) this.pageIds.remove(0);

			if(log.isDebugEnabled()){
				log.debug("Full Cache, deleted page with id ["+key+"].");
			}

			return key;
		}
		return null;
	}

	public String toString() {

		StringBuffer result = new StringBuffer();
		Iterator values = this.pageIds.iterator();

		while (values.hasNext()) {
			String pageId = (String) values.next();
			result.append(" " + pageId);
		}

		return result.toString();
	}

	/**
	 * @return Returns the maxSize.
	 */
	public int getMaxSize() {
		return maxSize;
	}

	/**
	 * @param maxSize The maxSize to set.
	 */
	public void setMaxSize(int maxSize) {
		this.maxSize = maxSize;
	}

	/**
	 * @return the pageIds
	 */
	public List getPageIds() {
		return pageIds;
	}

}


text:
<!doctype html>

  <meta charset="utf-8">
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="generator" content="Polymer Starter Kit" />
  <title>Viha POC (Client)</title>

  <meta name="theme-color" content="#027244">

  <link rel="manifest" href="manifest.json">

  <meta name="msapplication-TileColor" content="#027244">

  <meta name="mobile-web-app-capable" content="yes">
  <meta name="application-name" content="PSK">
  <link rel="icon" sizes="192x192" href="images/touch/chrome-touch-icon-192x192.png">

  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="#027244">
  <meta name="apple-mobile-web-app-title" content="Polymer Starter Kit">
  <link rel="apple-touch-icon" href="images/touch/apple-touch-icon.png">

  <meta name="msapplication-TileImage" content="images/touch/ms-touch-icon-144x144-precomposed.png">

  <link rel="shortcut icon" href="images/favicon.ico" type="image/x-icon"/>
  <link rel="icon" href="images/favicon.ico" type="image/x-icon"/>

  <link rel="stylesheet" href="styles/main.css">

  <link rel="import" href="elements/elements.html">

  <template is="dom-bind" id="app">

    <voyent-auth-provider id="authProvider" account="[[account]]" realm="viha"
      host="[[host]]" logged-in="{{isLoggedIn}}" error="{{loginError}}" timeout="120"
      scope-to-path="/demos/viha/">
    </voyent-auth-provider>
    <voyent-login-paper-card  heading="Client Login" username="{{username}}" password="{{password}}" error="{{loginError}}"
      auth-provider="authProvider" submit-label="Login" cancel-label="Cancel" hidden="{{isLoggedIn}}"
      header-image="images/vihaLogo.jpg" showrealminput showaccountinput showhostinput realm="viha" account="{{account}}" host="{{host}}">
    </voyent-login-paper-card>
    <demo-view id="demoView" visible="{{isLoggedIn}}" username="[[username]]" host="[[host]]"
      base-url="[[baseUrl]]" route="{{route}}" account="{{account}}"></demo-view>

  </template>


text:
namespace MoviesLibrary.Services.Web.Helpers
{
    using System;

    public class MovieVideo
    {
        public string Id { get; set; }

        public string Title { get; set; }

        public string Description { get; set; }

        public DateTime PublishedDate { get; set; }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.github.conversations.sample.webapp</groupId>
    <artifactId>conversations-sample-webapp</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>conversations-sample-webapp</name>
    <description>Conversations Sample Web Application</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.5.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <conversations.spring.version>1.1-SNAPSHOT</conversations.spring.version>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongo-java-driver</artifactId>
            <version>3.2.1</version>
        </dependency>
        <dependency>
            <groupId>com.github.maximilientyc</groupId>
            <artifactId>conversations-spring</artifactId>
            <version>${conversations.spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mustache</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- Test purpose dependencies -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/libs-milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>sonatype</id>
            <name>Sonatype</name>
            <url>https://oss.sonatype.org/content/groups/public</url>
        </repository>
    </repositories>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>


text:
'''Sample module showing how to read JSON files into blaze arrays'''

from __future__ import absolute_import, division, print_function

import blaze
from blaze.datadescriptor import dd_as_py

json_buf = u"[1, 2, 3, 4, 5]"
json_schema = "var, int8"

# Create a temporary JSON file in URI and open the dataset
dname = '/tmp/test.json'
store = blaze.Storage(dname)
print "store:", store
with file(store.path, "wb") as f:
    f.write(json_buf)
arr = blaze.open(store, json_schema)

#print('Blaze array:', arr)  # XXX This does not work yet
#print('Blaze array:', nd.array(arr))  # XXX idem
# Convert the data to a native Python object
print('Blaze array:', dd_as_py(arr._data))

# Remove the temporary JSON file
blaze.drop(store)


text:
namespace media {
namespace cast {
namespace transport {

namespace {

// If there is only one referecne to the packet then copy the
// reference and return.
// Otherwise return a deep copy of the packet.
PacketRef FastCopyPacket(const PacketRef& packet) {
  if (packet->HasOneRef())
    return packet;
  return make_scoped_refptr(new base::RefCountedData<Packet>(packet->data));
}

}  // namespace

RtpSender::RtpSender(
    base::TickClock* clock,
    const scoped_refptr<base::SingleThreadTaskRunner>& transport_task_runner,
    PacedSender* const transport)
    : clock_(clock),
      transport_(transport),
      transport_task_runner_(transport_task_runner),
      weak_factory_(this) {
  // Randomly set sequence number start value.
  config_.sequence_number = base::RandInt(0, 65535);
}

RtpSender::~RtpSender() {}

bool RtpSender::InitializeAudio(const CastTransportAudioConfig& config) {
  storage_.reset(new PacketStorage(config.rtp.max_outstanding_frames));
  if (!storage_->IsValid()) {
    return false;
  }
  config_.audio = true;
  config_.ssrc = config.rtp.config.ssrc;
  config_.payload_type = config.rtp.config.payload_type;
  config_.frequency = config.frequency;
  config_.audio_codec = config.codec;
  packetizer_.reset(new RtpPacketizer(transport_, storage_.get(), config_));
  return true;
}

bool RtpSender::InitializeVideo(const CastTransportVideoConfig& config) {
  storage_.reset(new PacketStorage(config.rtp.max_outstanding_frames));
  if (!storage_->IsValid()) {
    return false;
  }
  config_.audio = false;
  config_.ssrc = config.rtp.config.ssrc;
  config_.payload_type = config.rtp.config.payload_type;
  config_.frequency = kVideoFrequency;
  config_.video_codec = config.codec;
  packetizer_.reset(new RtpPacketizer(transport_, storage_.get(), config_));
  return true;
}

void RtpSender::SendFrame(const EncodedFrame& frame) {
  DCHECK(packetizer_);
  packetizer_->SendFrameAsPackets(frame);
}

void RtpSender::ResendPackets(
    const MissingFramesAndPacketsMap& missing_frames_and_packets,
    bool cancel_rtx_if_not_in_list,
    base::TimeDelta dedupe_window) {
  DCHECK(storage_);
  // Iterate over all frames in the list.
  for (MissingFramesAndPacketsMap::const_iterator it =
           missing_frames_and_packets.begin();
       it != missing_frames_and_packets.end();
       ++it) {
    SendPacketVector packets_to_resend;
    uint8 frame_id = it->first;
    // Set of packets that the receiver wants us to re-send.
    // If empty, we need to re-send all packets for this frame.
    const PacketIdSet& missing_packet_set = it->second;

    bool resend_all = missing_packet_set.find(kRtcpCastAllPacketsLost) !=
        missing_packet_set.end();
    bool resend_last = missing_packet_set.find(kRtcpCastLastPacket) !=
        missing_packet_set.end();

    const SendPacketVector* stored_packets = storage_->GetFrame8(frame_id);
    if (!stored_packets)
      continue;

    for (SendPacketVector::const_iterator it = stored_packets->begin();
         it != stored_packets->end(); ++it) {
      const PacketKey& packet_key = it->first;
      const uint16 packet_id = packet_key.second.second;

      // Should we resend the packet?
      bool resend = resend_all;

      // Should we resend it because it's in the missing_packet_set?
      if (!resend &&
          missing_packet_set.find(packet_id) != missing_packet_set.end()) {
        resend = true;
      }

      // If we were asked to resend the last packet, check if it's the
      // last packet.
      if (!resend && resend_last && (it + 1) == stored_packets->end()) {
        resend = true;
      }

      if (resend) {
        // Resend packet to the network.
        VLOG(3) << "Resend " << static_cast<int>(frame_id) << ":"
                << packet_id;
        // Set a unique incremental sequence number for every packet.
        PacketRef packet_copy = FastCopyPacket(it->second);
        UpdateSequenceNumber(&packet_copy->data);
        packets_to_resend.push_back(std::make_pair(packet_key, packet_copy));
      } else if (cancel_rtx_if_not_in_list) {
        transport_->CancelSendingPacket(it->first);
      }
    }
    transport_->ResendPackets(packets_to_resend, dedupe_window);
  }
}

void RtpSender::UpdateSequenceNumber(Packet* packet) {
  // TODO(miu): This is an abstraction violation.  This needs to be a part of
  // the overall packet (de)serialization consolidation.
  static const int kByteOffsetToSequenceNumber = 2;
  base::BigEndianWriter big_endian_writer(
      reinterpret_cast<char*>((&packet->front()) + kByteOffsetToSequenceNumber),
      sizeof(uint16));
  big_endian_writer.WriteU16(packetizer_->NextSequenceNumber());
}

}  // namespace transport
}  //  namespace cast
}  // namespace media


text:
def have_high_cards(my_cards):
    return "A" in my_cards or "K" in my_cards

def get_hole_card_ranks(game_state):
    player_id = game_state['in_action']
    cards = game_state['players'][player_id]['hole_cards']
    return [card['rank'] for card in cards]

def get_all_cards(game_state):
    player_id = game_state['in_action']
    all_cards = game_state['players'][player_id]['hole_cards']
    all_cards += game_state['community_cards']
    return all_cards

def get_player_count(game_state):
    return len(game_state["players"])

def is_preflop(game_state):
    return len(game_state["community_cards"]) == 0

def get_myself(game_state):
    player_id = game_state['in_action']
    return game_state['players'][player_id]

def is_well_positioned(game_state):
    player_id = game_state['in_action']
    dealer = game_state['dealer']

    is_last_seat = player_id == get_player_count(game_state) - 1
    is_dealer_seat = player_id == dealer

    return is_last_seat or is_dealer_seat


text:
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
android:fromAlpha="0.0" android:toAlpha="1.0"
android:duration="300" android:startOffset="1200" />


text:
package com.sillycat.springbootapi;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringBootAPIApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringBootAPIApplication.class, args);
	}

}


text:
using namespace Storage::Tape::Oric;

int Parser::get_next_byte(const std::shared_ptr<Storage::Tape::Tape> &tape, bool use_fast_encoding) {
	detection_mode_ = use_fast_encoding ? FastZero : SlowZero;
	cycle_length_ = 0.0f;

	int result = 0;
	int bit_count = 0;
	while(bit_count < 11 && !tape->is_at_end()) {
		SymbolType symbol = get_next_symbol(tape);
		if(!bit_count && symbol != SymbolType::Zero) continue;
		detection_mode_ = use_fast_encoding ? FastData : SlowData;
		result |= ((symbol == SymbolType::One) ? 1 : 0) << bit_count;
		bit_count++;
	}
	// TODO: check parity?
	return tape->is_at_end() ? -1 : ((result >> 1)&0xff);
}

bool Parser::sync_and_get_encoding_speed(const std::shared_ptr<Storage::Tape::Tape> &tape) {
	detection_mode_ = Sync;
	while(!tape->is_at_end()) {
		const SymbolType symbol = get_next_symbol(tape);
		switch(symbol) {
			case SymbolType::FoundSlow: return false;
			case SymbolType::FoundFast: return true;
			default: break;
		}
	}
	return false;
}

void Parser::process_pulse(const Storage::Tape::Tape::Pulse &pulse) {
	constexpr float maximum_short_length = 0.000512f;
	constexpr float maximum_medium_length = 0.000728f;
	constexpr float maximum_long_length = 0.001456f;

	const bool wave_is_high = pulse.type == Storage::Tape::Tape::Pulse::High;
	if(!wave_was_high_ && wave_is_high != wave_was_high_) {
		if(cycle_length_ < maximum_short_length) push_wave(WaveType::Short);
		else if(cycle_length_ < maximum_medium_length) push_wave(WaveType::Medium);
		else if(cycle_length_ < maximum_long_length) push_wave(WaveType::Long);
		else push_wave(WaveType::Unrecognised);

		cycle_length_ = 0.0f;
	}
	wave_was_high_ = wave_is_high;
	cycle_length_ += pulse.length.get<float>();
}

void Parser::inspect_waves(const std::vector<WaveType> &waves) {
	switch(detection_mode_) {
		case FastZero:
			if(waves.empty()) return;
			if(waves[0] == WaveType::Medium) {
				push_symbol(SymbolType::Zero, 1);
				return;
			}
		break;

		case FastData:
			if(waves.empty()) return;
			if(waves[0] == WaveType::Medium) {
				push_symbol(SymbolType::Zero, 1);
				return;
			}
			if(waves[0] == WaveType::Short) {
				push_symbol(SymbolType::One, 1);
				return;
			}
		break;

		case SlowZero:
			if(waves.size() < 4) return;
			if(waves[0] == WaveType::Long && waves[1] == WaveType::Long && waves[2] == WaveType::Long && waves[3] == WaveType::Long) {
				push_symbol(SymbolType::Zero, 4);
				return;
			}
		break;

		case SlowData:
#define CHECK_RUN(length, type, symbol)	\
			if(waves.size() >= length) {\
				std::size_t c;\
				for(c = 0; c < length; c++) if(waves[c] != type) break;\
				if(c == length) {\
					push_symbol(symbol, length);\
					return;\
				}\
			}

			CHECK_RUN(4, WaveType::Long, SymbolType::Zero);
			CHECK_RUN(8, WaveType::Short, SymbolType::One);
#undef CHECK_RUN
			if(waves.size() < 16) return;	// TODO, maybe: if there are any inconsistencies in the first 8, don't return
		break;

		case Sync: {
			// Sync is 0x16, either encoded fast or slow; i.e. 0 0110 1000 1
			const Pattern slow_sync[] = {
				{WaveType::Long, 8},
				{WaveType::Short, 16},
				{WaveType::Long, 4},
				{WaveType::Short, 8},
				{WaveType::Long, 12},
				{WaveType::Short, 8},
				{WaveType::Unrecognised}
			};
			const Pattern fast_sync[] = {
				{WaveType::Medium,	2},
				{WaveType::Short,	2},
				{WaveType::Medium,	1},
				{WaveType::Short,	1},
				{WaveType::Medium,	3},
				{WaveType::Short,	1},
				{WaveType::Unrecognised}
			};

			std::size_t slow_sync_matching_depth = pattern_matching_depth(waves, slow_sync);
			std::size_t fast_sync_matching_depth = pattern_matching_depth(waves, fast_sync);

			if(slow_sync_matching_depth == 52) {
				push_symbol(SymbolType::FoundSlow, 52);
				return;
			}
			if(fast_sync_matching_depth == 10) {
				push_symbol(SymbolType::FoundFast, 10);
				return;
			}
			if(slow_sync_matching_depth < waves.size() && fast_sync_matching_depth < waves.size()) {
				int least_depth = int(std::min(slow_sync_matching_depth, fast_sync_matching_depth));
				remove_waves(least_depth ? least_depth : 1);
			}

			return;
		}
		break;
	}

	remove_waves(1);
}

std::size_t Parser::pattern_matching_depth(const std::vector<WaveType> &waves, const Pattern *pattern) {
	std::size_t depth = 0;
	int pattern_depth = 0;
	while(depth < waves.size() && pattern->type != WaveType::Unrecognised) {
		if(waves[depth] != pattern->type) break;
		depth++;
		pattern_depth++;
		if(pattern_depth == pattern->count) {
			pattern_depth = 0;
			pattern++;
		}
	}

	return depth;
}


text:
<?xml version="1.0" encoding="utf-8"?>
<language>
  <definitions>
    <definition>
      <key>shipping_table_title</key>
      <value><![CDATA[Table Rate]]></value>
      <group>modules-shipping</group>
    </definition>
    <definition>
      <key>shipping_table_description</key>
      <value><![CDATA[Table Rate]]></value>
      <group>modules-shipping</group>
    </definition>
    <definition>
      <key>shipping_table_method</key>
      <value><![CDATA[Best Way]]></value>
      <group>modules-shipping</group>
    </definition>
  </definitions>
</language>


text:
import logging; logger = logging.getLogger("morse." + __name__)

######################################################
#
#    gripper.py        Blender 2.59
#
#    Gilberto Echeverria
#    13 / 10 / 2010
#
######################################################

import bge
import math
import morse.core.actuator
from morse.core.services import service
from morse.core.exceptions import MorseRPCInvokationError

class GripperActuatorClass(morse.core.actuator.MorseActuatorClass):
    """
    Basic gripper with two moving pieces

    It is capable of picking up objects marked with a predefined Game Property,
    currently they should be 'Graspable'
    """

    def __init__(self, obj, parent=None):
        """
        Constructor method.
        Receives the reference to the Blender object.
        """
        logger.info('%s initialization' % obj.name)
        # Call the constructor of the parent class
        super(self.__class__,self).__init__(obj, parent)

        self.local_data['grab'] = False

        self._near_object = None
        self._grabbed_object = None

        # Variable to indicate whether the mesh should animate closing
        #  or opening the gripper
        self._animation = ''

        # Get references to the Logic Bricks to play animations
        self._contr = self.blender_obj.controllers[0]
        self._close_anim = self._contr.actuators['Close_anim']
        self._open_anim = self._contr.actuators['Open_anim']

        logger.info('Component initialized')
        logger.setLevel(logging.DEBUG)

    def find_object(self):
        """ Store the object that is within reach of the gripper
        Uses a Blender Radar Sensor to detect objects with the
        'Graspable' property in front of this component
        """
        # Get reference to the Radar Blender sensor
        contr = bge.logic.getCurrentController()
        radar = contr.sensors['Radar']

        self._near_object = None
        if radar.triggered and radar.positive:
            min_distance = 100
            for test_obj in radar.hitObjectList:
                # Find the closest object and its distance
                new_distance = self.blender_obj.getDistanceTo(test_obj)
                if new_distance < min_distance:
                    self._near_object = test_obj
                    min_distance = new_distance

    @service
    def grab(self):
        """ Tries to grab an object close to the gripper.

        :returns: if successful (or if an object is already in hand), the
        name of the object, else None
        """
        # Check that no other object is being carried
        if not self._grabbed_object:
            # If the object is draggable
            if self._near_object != None:
                logger.debug("Grabbing object: '%s'" % self._near_object)
                # Remove Physic simulation
                #self._near_object.suspendDynamics()
                # Parent the selected object to the gripper
                self._grabbed_object = self._near_object
                self._grabbed_object.setParent (self.blender_obj)
                logger.debug("New parent: %s" % self._grabbed_object.parent)
                self._near_object = None

                # Execute the close grip animation:
                self._animation = 'close'
                return self._grabbed_object.name

            else:
                logger.debug("No 'Graspable' object within range of gripper")
                return None
        else:
            logger.debug("Already holding object %s" % self._grabbed_object )
            return self._grabbed_object.name

    @service
    def release(self):
        """ Free the grabbed object

        Let it fall down after resetting its rotation.

        Does nothing if no object is held.

        :returns: True if an object has been released, else False (if
        no object was held).
        """
        # Clear the previously selected object, if any
        if self._grabbed_object != None:
            logger.debug("Releasing object: '%s'" % self._near_object)
            # Remove the parent
            self._grabbed_object.removeParent()
            # Place the object on the nearest surface
            #morse.helpers.place_object.do_place(previous_object)
            # Reset rotation of object
            #self._grabbed_object.worldOrientation = [0.0, 0.0, 0.0]
            # Restore Physics simulation
            #previous_object.restoreDynamics()
            #previous_object.setLinearVelocity([0, 0, 0])
            #previous_object.setAngularVelocity([0, 0, 0])
            # Clear the object from dragged status
            self._grabbed_object = None

            # Execute the open grip animation:
            self._animation = 'open'
            return True

        else:
            logger.debug("No object currently being held: nothing to release.")
            return False

    def default_action(self):
        """
        Check if an object is within reach of the hand
        """
        self.find_object()

        # Play the animations when necessary
        if self._animation == 'close':
            self._contr.activate(self._close_anim)
            self._animation = ''
            logger.debug('Playing CLOSE animation')
        if self._animation == 'open':
            self._contr.activate(self._open_anim)
            self._animation = ''
            logger.debug('Playing OPEN animation')


text:
"""The SleuthKit (TSK) partition file entry implementation."""

from dfvfs.lib import definitions
from dfvfs.lib import errors
from dfvfs.lib import tsk_partition
from dfvfs.path import tsk_partition_path_spec
from dfvfs.vfs import file_entry

class TSKPartitionDirectory(file_entry.Directory):
  """File system directory that uses pytsk3."""

  def _EntriesGenerator(self):
    """Retrieves directory entries.

    Since a directory can contain a vast number of entries using
    a generator is more memory efficient.

    Yields:
      A path specification (instance of path.TSKPartitionPathSpec).
    """
    # Only the virtual root file has directory entries.
    part_index = getattr(self.path_spec, u'part_index', None)
    start_offset = getattr(self.path_spec, u'start_offset', None)

    if part_index is not None or start_offset is not None:
      return

    location = getattr(self.path_spec, u'location', None)
    if location is None or location != self._file_system.LOCATION_ROOT:
      return

    tsk_volume = self._file_system.GetTSKVolume()
    bytes_per_sector = tsk_partition.TSKVolumeGetBytesPerSector(tsk_volume)
    part_index = 0
    partition_index = 0

    # pytsk3 does not handle the Volume_Info iterator correctly therefore
    # the explicit list is needed to prevent the iterator terminating too
    # soon or looping forever.
    for tsk_vs_part in list(tsk_volume):
      kwargs = {}

      if tsk_partition.TSKVsPartIsAllocated(tsk_vs_part):
        partition_index += 1
        kwargs[u'location'] = u'/p{0:d}'.format(partition_index)

      kwargs[u'part_index'] = part_index
      part_index += 1

      start_sector = tsk_partition.TSKVsPartGetStartSector(tsk_vs_part)

      if start_sector is not None:
        kwargs[u'start_offset'] = start_sector * bytes_per_sector

      kwargs[u'parent'] = self.path_spec.parent

      yield tsk_partition_path_spec.TSKPartitionPathSpec(**kwargs)

class TSKPartitionFileEntry(file_entry.FileEntry):
  """File system file entry that uses pytsk3."""

  TYPE_INDICATOR = definitions.TYPE_INDICATOR_TSK_PARTITION

  def __init__(
      self, resolver_context, file_system, path_spec, is_root=False,
      is_virtual=False, tsk_vs_part=None):
    """Initializes a file entry.

    Args:
      resolver_context (Context): resolver context.
      file_system (FileSystem): file system.
      path_spec (PathSpec): path specification.
      is_root (Optional[bool]): True if the file entry is the root file entry
          of the corresponding file system.
      is_virtual (Optional[bool]): True if the file entry is a virtual file
          entry emulated by the corresponding file system.
      tsk_vs_part (Optional[pytsk3.TSK_VS_PART_INFO]): TSK volume system part.

    Raises:
      BackEndError: when the TSK volume system part is missing in a non-virtual
          file entry.
    """
    tsk_volume = file_system.GetTSKVolume()
    if not is_virtual and tsk_vs_part is None:
      tsk_vs_part, _ = tsk_partition.GetTSKVsPartByPathSpec(
          tsk_volume, path_spec)
    if not is_virtual and tsk_vs_part is None:
      raise errors.BackEndError(
          u'Missing TSK volume system part in non-virtual file entry.')

    super(TSKPartitionFileEntry, self).__init__(
        resolver_context, file_system, path_spec, is_root=is_root,
        is_virtual=is_virtual)
    self._name = None
    self._tsk_volume = tsk_volume
    self._tsk_vs_part = tsk_vs_part

    if is_virtual:
      self._type = definitions.FILE_ENTRY_TYPE_DIRECTORY
    else:
      self._type = definitions.FILE_ENTRY_TYPE_FILE

  def _GetDirectory(self):
    """Retrieves a directory.

    Returns:
      TSKPartitionDirectory: a directory or None if not available.
    """
    if self._type == definitions.FILE_ENTRY_TYPE_DIRECTORY:
      return TSKPartitionDirectory(self._file_system, self.path_spec)

  def _GetStat(self):
    """Retrieves the stat object.

    Returns:
      VFSStat: stat object.
    """
    stat_object = super(TSKPartitionFileEntry, self)._GetStat()

    bytes_per_sector = tsk_partition.TSKVolumeGetBytesPerSector(
        self._tsk_volume)

    # File data stat information.
    if self._tsk_vs_part is not None:
      number_of_sectors = tsk_partition.TSKVsPartGetNumberOfSectors(
          self._tsk_vs_part)

      if number_of_sectors:
        stat_object.size = number_of_sectors * bytes_per_sector

    # Date and time stat information.

    # Ownership and permissions stat information.

    # File entry type stat information.

    # The root file entry is virtual and should have type directory.
    if not self._is_virtual:
      stat_object.is_allocated = tsk_partition.TSKVsPartIsAllocated(
          self._tsk_vs_part)

    return stat_object

  @property
  def name(self):
    """str: name of the file entry, which does not include the full path."""
    if self._name is None:
      # Directory entries without a location in the path specification
      # are not given a name for now.
      location = getattr(self.path_spec, u'location', None)
      if location is not None:
        self._name = self._file_system.BasenamePath(location)
      else:
        self._name = u''
    return self._name

  @property
  def sub_file_entries(self):
    """generator(TSKPartitionFileEntry): sub file entries."""
    if self._directory is None:
      self._directory = self._GetDirectory()

    if self._directory:
      for path_spec in self._directory.entries:
        yield TSKPartitionFileEntry(
            self._resolver_context, self._file_system, path_spec)

  def GetParentFileEntry(self):
    """Retrieves the parent file entry.

    Returns:
      TSKPartitionFileEntry: parent file entry or None if not available.
    """
    # TODO: implement https://github.com/log2timeline/dfvfs/issues/76.
    return

  def GetTSKVsPart(self):
    """Retrieves the TSK volume system part.

    Returns:
      pytsk3.TSK_VS_PART_INFO: a TSK volume system part or None if not
          available.
    """
    return self._tsk_vs_part


text:
.tsetDetails.heading thread ,th {
    color: whitesmoke;  //Test Details table header font
}
.tsetDetails.heading tbody {
    background: floralwhite;      //Test Details table rows
}
.grp.head{
    color: white;
    background: #667B95;    //header for tables
}.grp.head.browsers{
    color:white;
    background: #667B95;
}
thead{
    background: #667B95;    //Test Details table header
    font-size: 12px;
}
.tesetDetails.heading table thead tr{
    background: #667B95;
}
thead input{
    border-bottom-left-radius: 5px;
    border-top-right-radius: 5px;
    border-top-left-radius: 5px;
    border-bottom-right-radius: 5px;
}
.exe.table thead  {
    border-spacing: 1px;  font-size: 14px ;
    background: #667B95;   ;
    color: white;
}
.exe.table.step.evenx,.exe.table.step.evenx td,.exe.table.step.evenx td a,.exe.table.step.evenx td label{
    background:white; //For even steps in test case steps
}
.exe.table.ng-scope.even,.exe.table.ng-scope.even td,.exe.table.ng-scope.even td a,.exe.table.ng-scope.even td label{
    background:white;
}
.exe.table.step.oddx,.exe.table.step.oddx td{
    background:floralwhite;       //test case details steps
}
.exe.table.ng-scope.odd,.exe.table.ng-scope.odd td{
    background:floralwhite;       //test case details steps
}
.exe.table.iteration{
    background: aliceblue;
    color: black;
}
.exe.table.reusable{
    background: beige;
    font-size: medium;
}
.exe.table.time{
    background:inherit;
}


text:
package org.apache.jmeter.protocol.http.modifier;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.slf4j.LoggerFactory;
import org.slf4j.Logger;

/**
 * This module controls the Sequence in which user details are returned. This
 * module uses round robin allocation of users.
 *
 * @deprecated No replacement as not used anymore in JMeter, will be dropped in next version after 3.0
 */
@Deprecated
public class UserSequence implements Serializable {
    private static final long serialVersionUID = 233L;

	private static final Logger log = LoggerFactory.getLogger(UserSequence.class);

    // -------------------------------------------
    // Constants and Data Members
    // -------------------------------------------
    private List<Map<String, String>> allUsers;

    private transient Iterator<Map<String, String>> indexOfUsers;

    // -------------------------------------------
    // Constructors
    // -------------------------------------------

    public UserSequence() {
    }

    /**
     * Load all user and parameter data into the sequence module.
     * <P>
     * ie a Set of Mapped "parameter names and parameter values" for each user
     * to be loaded into the sequencer.
     *
     * @param allUsers users and parameter data to be used
     */
    public UserSequence(List<Map<String, String>> allUsers) {
        this.allUsers = allUsers;

        // initalise pointer to first user
        indexOfUsers = allUsers.iterator();
    }

    // -------------------------------------------
    // Methods
    // -------------------------------------------

    /**
     * Returns the parameter data for the next user in the sequence
     *
     * @return a Map object of parameter names and matching parameter values for
     *         the next user
     */
    public synchronized Map<String, String> getNextUserMods() {
        // Use round robin allocation of user details
        if (!indexOfUsers.hasNext()) {
            indexOfUsers = allUsers.iterator();
        }

        Map<String, String> user;
        if (indexOfUsers.hasNext()) {
            user = indexOfUsers.next();
            log.debug("UserSequence.getNextuserMods(): current parameters will be " + "changed to: " + user);
        } else {
            // no entries in all users, therefore create an empty Map object
            user = new HashMap<>();
        }

        return user;
    }
}