text:
<!--
    @license
    Copyright (c) 2014 The Polymer Project Authors. All rights reserved.
    This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
    The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
    The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
    Code distributed by Google as part of the polymer project is also
    subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
-->
<x-meta id="core-toolbar" label="Toolbar" group="Core" isContainer>

  <template>

    <core-toolbar style="right: 0px; left: 0px; background-color: #4F7DC9; color: #fff; fill: #fff;">
      <core-icon-button icon="menu"></core-icon-button>
      <div flex>Toolbar</div>
    </core-toolbar>

  </template>

  <template id="imports">

    <link rel="import" href="../core-icon-button/core-icon-button.html">
    <link rel="import" href="core-toolbar.html">

  </template>

</x-meta>


text:
.class Lcom/android/internal/telephony/cdma/utk/DisplayTextParams;
.super Lcom/android/internal/telephony/cdma/utk/CommandParams;
.source "CommandParams.java"

# instance fields
.field textMsg:Lcom/android/internal/telephony/cdma/utk/TextMessage;

# direct methods
.method constructor <init>(Lcom/android/internal/telephony/cdma/utk/CommandDetails;Lcom/android/internal/telephony/cdma/utk/TextMessage;)V
    .locals 0
    .param p1, "cmdDet"    # Lcom/android/internal/telephony/cdma/utk/CommandDetails;
    .param p2, "textMsg"    # Lcom/android/internal/telephony/cdma/utk/TextMessage;

    .prologue
    .line 48
    invoke-direct {p0, p1}, Lcom/android/internal/telephony/cdma/utk/CommandParams;-><init>(Lcom/android/internal/telephony/cdma/utk/CommandDetails;)V

    .line 49
    iput-object p2, p0, Lcom/android/internal/telephony/cdma/utk/DisplayTextParams;->textMsg:Lcom/android/internal/telephony/cdma/utk/TextMessage;

    .line 50
    return-void
.end method

# virtual methods
.method setIcon(Landroid/graphics/Bitmap;)Z
    .locals 1
    .param p1, "icon"    # Landroid/graphics/Bitmap;

    .prologue
    .line 53
    if-eqz p1, :cond_0

    iget-object v0, p0, Lcom/android/internal/telephony/cdma/utk/DisplayTextParams;->textMsg:Lcom/android/internal/telephony/cdma/utk/TextMessage;

    if-eqz v0, :cond_0

    .line 54
    iget-object v0, p0, Lcom/android/internal/telephony/cdma/utk/DisplayTextParams;->textMsg:Lcom/android/internal/telephony/cdma/utk/TextMessage;

    iput-object p1, v0, Lcom/android/internal/telephony/cdma/utk/TextMessage;->icon:Landroid/graphics/Bitmap;

    .line 55
    const/4 v0, 0x1

    .line 57
    :goto_0
    return v0

    :cond_0
    const/4 v0, 0x0

    goto :goto_0
.end method

redpajama_set_name: RedPajamaGithub


text:
/* (c) British Telecommunications plc, 2010, All Rights Reserved */
package com.bt.pi.ops.website.entities;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;

import com.bt.pi.app.common.entities.KeyPair;
import com.bt.pi.app.common.entities.User;

@XmlRootElement(name = "user")
public class ReadOnlyUser {
	private User user;

	public ReadOnlyUser() {
	}

	public ReadOnlyUser(User theUser) {
		user = theUser;
	}

	public void setUser(User theUser) {
		user = theUser;
	}

	@XmlElement
	public byte[] getCertificate() {
		return user.getCertificate();
	}

	@XmlElement
	public String getUsername() {
		return user.getUsername();
	}

	@XmlElement
	public String getApiAccessKey() {
		return user.getApiAccessKey();
	}

	@XmlElement
	public String getApiSecretKey() {
		return user.getApiSecretKey();
	}

	@XmlElementWrapper
	public Set<String> getInstanceIds() {
		Set<String> result = new HashSet<String>();
		result.addAll(Arrays.asList(user.getInstanceIds()));
		return result;
	}

	@XmlElementWrapper
	public Set<String> getVolumeIds() {
		return user.getVolumeIds();
	}

	@XmlElementWrapper
	public Set<String> getImageIds() {
		return user.getImageIds();
	}

	@XmlElementWrapper
	public Set<String> getBucketNames() {
		return user.getBucketNames();
	}

	@XmlElementWrapper
	public Set<String> getSecurityGroupIds() {
		return user.getSecurityGroupIds();
	}

	@XmlElementWrapper
	public Set<KeyPair> getKeyPairs() {
		return user.getKeyPairs();
	}

	@XmlElement
	public String getRealName() {
		return user.getRealName();
	}

	@XmlElement
	public String getEmailAddress() {
		return user.getEmailAddress();
	}

	@XmlElement
	public boolean isEnabled() {
		return user.isEnabled();
	}

	@XmlElement
	public String getExternalRefId() {
		return user.getExternalRefId();
	}

	User getUser() {
		return user;
	}

	@Override
	public String toString() {
		return user.toString();
	}

	@Override
	public int hashCode() {
		return user.hashCode();
	}

	@Override
	public boolean equals(Object obj) {
		Object o;
		if (obj instanceof ReadOnlyUser) {
			o = ((ReadOnlyUser) obj).getUser();
		} else {
			o = obj;
		}
		return user.equals(o);
	}

	@XmlElement
	public int getMaxInstances() {
		return user.getMaxInstances();
	}

	@XmlElement
	public int getMaxCores() {
		return user.getMaxCores();
	}
}


text:
/**
  @file     popcount_none.h
  @brief    The policiy NOT to count the number of bits.
  @author   HRYKY
  @version  $Id: popcount_none.h 325 2014-02-09 12:37:53Z hryky.private@gmail.com $
 */
#ifndef POPCOUNT_NONE_H_20130518234945659
#define POPCOUNT_NONE_H_20130518234945659
#include "hryky/with_stream_out.h"
#include "hryky/with_swap.h"
//------------------------------------------------------------------------------
// defines macros
//------------------------------------------------------------------------------
#define hryky_template_param \
	size_t Size
#define hryky_template_arg \
	Size
//------------------------------------------------------------------------------
// declares types
//------------------------------------------------------------------------------
namespace hryky
{
namespace popcount
{
	/// The policiy NOT to count the number of bits.
	template <hryky_template_param>
	class None;

} // namespace popcount
} // namespace hryky
//------------------------------------------------------------------------------
// declares classes
//------------------------------------------------------------------------------
/**
  @brief The policiy NOT to count the number of bits.
 */
template <size_t Size>
class hryky::popcount::None :
	public WithStreamOut<None<hryky_template_arg> >,
	public WithSwap<None<hryky_template_arg> >
{
public :

	typedef None<hryky_template_arg> this_type;

	typedef typename UnsignedEnoughUint<Size>::type size_type;

	/// default constructor.
	None();

	/// copy constructor.
	None(this_type const &);

	/// move constructor.
	None(this_type &&);

	/// destructor.
	~None();

	/// assignment operator.
	hryky_assign_op;

	/// move assignment operator.
	hryky_move_assign_op;

	/// releases the internal resources.
	void clear();

	/// decomposes the instance to primitive objects.
	template <typename StreamT>
	StreamT & write_to(StreamT & out) const;

	/// interchanges the each internal resources of two instances.
	void swap(this_type & src);

	/// retrieves the calculated number of bits.
	template <typename BitsetT>
	size_type count(BitsetT const & bitset) const;

	/// applies the result of assigning a new bit.
	template <typename BitsetT>
	void set(
		BitsetT const & bitset,
		typename BitsetT::index_type const index,
		typename BitsetT::bitpos_type const bitpos,
		typename BitsetT::value_type const value);

	/// applies the result of enabling a bit.
	template <typename BitsetT>
	void on(
		BitsetT const & bitset,
		typename BitsetT::index_type const index,
		typename BitsetT::bitpos_type const bitpos);

	/// applies the result of disabling a bit.
	template <typename BitsetT>
	void off(
		BitsetT const & bitset,
		typename BitsetT::index_type const index,
		typename BitsetT::bitpos_type const bitpos);

	/// applies the result of reversing a bit.
	template <typename BitsetT>
	void flip(
		BitsetT const & bitset,
		typename BitsetT::index_type const index,
		typename BitsetT::bitpos_type const bitpos);

	/// updates the number of bits.
	template <typename BitsetT>
	void update(BitsetT const & bitset);

	/// overwrites the existing value by an arbitrary value.
	template <typename ValueT>
	void assign(ValueT value);

protected :

private :

	static size_type const dummy_;

};
//------------------------------------------------------------------------------
// specializes classes
//------------------------------------------------------------------------------
namespace hryky
{
namespace popcount
{
} // namespace popcount
} // namespace hryky
//------------------------------------------------------------------------------
// defines public member functions
//------------------------------------------------------------------------------
/**
  @brief default constructor.
 */
template <hryky_template_param>
hryky::popcount::None<hryky_template_arg>::None()
{
}
/**
  @brief copy constructor.
 */
template <hryky_template_param>
hryky::popcount::None<hryky_template_arg>::None(this_type const & rhs)
{
}
/**
  @brief move constructor.
 */
template <hryky_template_param>
hryky::popcount::None<hryky_template_arg>::None(this_type && rhs)
{
}
/**
  @brief destructor.
 */
template <hryky_template_param>
hryky::popcount::None<hryky_template_arg>::~None()
{
}
/**
  @brief releases the internal resources.
 */
template <hryky_template_param>
void hryky::popcount::None<hryky_template_arg>::clear()
{
}
/**
  @brief decomposes the instance to primitive objects.
 */
template <hryky_template_param>
template <typename StreamT>
StreamT &
hryky::popcount::None<hryky_template_arg>::write_to(
	StreamT & out) const
{
	out << "N/A";
	return out;
}
/**
  @brief interchanges the each internal resources of two instances.
 */
template <hryky_template_param>
void hryky::popcount::None<hryky_template_arg>::swap(this_type & src)
{
}
/**
  @brief retrieves the calculated number of bits.
 */
template <hryky_template_param>
template <typename BitsetT>
typename hryky::popcount::None<hryky_template_arg>::size_type
hryky::popcount::None<hryky_template_arg>::count(BitsetT const &) const
{
	return dummy_;
}
/**
  @brief applies the result of assigning a new bit.
 */
template <hryky_template_param>
template <typename BitsetT>
void hryky::popcount::None<hryky_template_arg>::set(
	BitsetT const &,
	typename BitsetT::index_type const,
	typename BitsetT::bitpos_type const,
	typename BitsetT::value_type const)
{
}
/**
  @brief applies the result of enabling a bit.
 */
template <hryky_template_param>
template <typename BitsetT>
void hryky::popcount::None<hryky_template_arg>::on(
	BitsetT const &,
	typename BitsetT::index_type const,
	typename BitsetT::bitpos_type const)
{
}
/**
  @brief applies the result of disabling a bit.
 */
template <hryky_template_param>
template <typename BitsetT>
void hryky::popcount::None<hryky_template_arg>::off(
	BitsetT const &,
	typename BitsetT::index_type const,
	typename BitsetT::bitpos_type const)
{
}
/**
  @brief applies the result of reversing a bit.
 */
template <hryky_template_param>
template <typename BitsetT>
void hryky::popcount::None<hryky_template_arg>::flip(
	BitsetT const &,
	typename BitsetT::index_type const,
	typename BitsetT::bitpos_type const)
{
}
/**
  @brief updates the number of bits.
 */
template <hryky_template_param>
template <typename BitsetT>
void hryky::popcount::None<hryky_template_arg>::update(
	BitsetT const &)
{
}
/**
  @brief overwrites the existing value by an arbitrary value.
 */
template <hryky_template_param>
template <typename ValueT>
void hryky::popcount::None<hryky_template_arg>::assign(ValueT)
{
}
//------------------------------------------------------------------------------
// defines protected member functions
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// defines private member functions
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// declares global functions
//------------------------------------------------------------------------------
namespace hryky
{
namespace popcount
{

} // namespace popcount
} // namespace hryky
//------------------------------------------------------------------------------
// defines global functions
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// revokes the temporary macros
//------------------------------------------------------------------------------
#undef hryky_template_param
#undef hryky_template_arg
#endif // POPCOUNT_NONE_H_20130518234945659
// end of file


text:
using NUnit.Framework;
using Projac.SqlClient;

namespace Projac.Sql.Tests.SqlClient
{
    [TestFixture]
    public partial class SqlClientSyntaxTests
    {
        private SqlClientSyntax _syntax;

        [SetUp]
        public void SetUp()
        {
            _syntax = new SqlClientSyntax();
        }

        private SqlClientSyntax Sql { get { return _syntax; } }
    }
}


text:
use rand;
use rand::{rngs::ThreadRng, Rng};

use std::collections::hash_map::*;
use std::fmt;
use std::iter::*;

use super::map::*;
use super::paths::PathPoint;
use context::*;
use items::Item;
use resources::Image;
use utils::{chance_to_hit, distance_under};
use weapons::{Weapon, WeaponType};

// The cost for a unit to pick up / drop / use / throw an item
pub const ITEM_COST: u16 = 5;

// A list of first names to pick from
const FIRST_NAMES: &[&str] = &[
    "David",
    "Dale",
    "Robert",
    "Lucy",
    "Ashley",
    "Mia",
    "JC",
    "Paul",
    "Heisenberg",
    "John",
    "Kyle",
    "Sarah",
    "Dylan",
    "Connor",
    "Hawk",
    "Laura",
    "Bobby",
    "Jane",
];

// A list of last names to pick from
const LAST_NAMES: &[&str] = &[
    "Cooper", "Yang", "Smith", "Denton", "Simons", "Rivers", "Savage", "Connor", "Reese", "Rhodes",
    "Zhou", "Jensen", "Palmer", "Mason", "Johnson", "Briggs",
];

// Generate a new random squaddie name
fn generate_squaddie_name(rng: &mut ThreadRng) -> String {
    let first = FIRST_NAMES[rng.gen_range(0, FIRST_NAMES.len())];
    let last = LAST_NAMES[rng.gen_range(0, LAST_NAMES.len())];
    format!("{} {}", first, last)
}

// Generate a new random machine name
fn generate_machine_name(rng: &mut ThreadRng) -> String {
    format!("SK{:05}", rng.gen_range(0, 100_000))
}

#[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub enum Side {
    PlayerA,
    PlayerB,
}

impl Side {
    pub fn enemies(self) -> Side {
        match self {
            Side::PlayerA => Side::PlayerB,
            Side::PlayerB => Side::PlayerA,
        }
    }

    pub fn vs_ai_string(self) -> &'static str {
        match self {
            Side::PlayerA => "Player",
            Side::PlayerB => "AI",
        }
    }

    pub fn multiplayer_string(self) -> &'static str {
        match self {
            Side::PlayerA => "Player A",
            Side::PlayerB => "Player B",
        }
    }
}

impl fmt::Display for Side {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.multiplayer_string())
    }
}

#[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Hash, Clone, Copy)]
pub enum UnitFacing {
    Bottom,
    BottomLeft,
    Left,
    TopLeft,
    Top,
    TopRight,
    Right,
    BottomRight,
}

impl UnitFacing {
    pub fn from_points(x: usize, y: usize, target_x: usize, target_y: usize) -> Self {
        let x = target_x as f32 - x as f32;
        let y = target_y as f32 - y as f32;
        let rotation = (y.atan2(x).to_degrees() + 360.0 / 16.0 * 15.0) % 360.0;

        if rotation < 45.0 {
            UnitFacing::Bottom
        } else if rotation < 90.0 {
            UnitFacing::BottomLeft
        } else if rotation < 135.0 {
            UnitFacing::Left
        } else if rotation < 180.0 {
            UnitFacing::TopLeft
        } else if rotation < 225.0 {
            UnitFacing::Top
        } else if rotation < 270.0 {
            UnitFacing::TopRight
        } else if rotation < 315.0 {
            UnitFacing::Right
        } else {
            UnitFacing::BottomRight
        }
    }

    // Which tiles should be visible relative to the center depending on the facing
    // You can use
    // http://www.wolframalpha.com/input/?+-abs(y)+%3E=+x&i=graph+y+%3E%3D+0+%26%26+abs(x)+%3C%3D+y
    // to check that there are correct
    fn visible(self, x: isize, y: isize) -> bool {
        match self {
            UnitFacing::Bottom => x >= 0 && y >= 0,
            UnitFacing::BottomLeft => y >= 0 && x.abs() <= y,
            UnitFacing::Left => x <= 0 && y >= 0,
            UnitFacing::TopLeft => x <= 0 && -y.abs() >= x,
            UnitFacing::Top => x <= 0 && y <= 0,
            UnitFacing::TopRight => y <= 0 && -x.abs() >= y,
            UnitFacing::Right => x >= 0 && y <= 0,
            UnitFacing::BottomRight => x >= 0 && y.abs() <= x,
        }
    }

    pub fn can_see(self, x: usize, y: usize, target_x: usize, target_y: usize, sight: f32) -> bool {
        self.visible(
            target_x as isize - x as isize,
            target_y as isize - y as isize,
        ) && distance_under(x, y, target_x, target_y, sight)
    }

    pub fn rotate_cw(self) -> Self {
        match self {
            UnitFacing::Bottom => UnitFacing::BottomLeft,
            UnitFacing::BottomLeft => UnitFacing::Left,
            UnitFacing::Left => UnitFacing::TopLeft,
            UnitFacing::TopLeft => UnitFacing::Top,
            UnitFacing::Top => UnitFacing::TopRight,
            UnitFacing::TopRight => UnitFacing::Right,
            UnitFacing::Right => UnitFacing::BottomRight,
            UnitFacing::BottomRight => UnitFacing::Bottom,
        }
    }

    pub fn rotate_ccw(self) -> Self {
        match self {
            UnitFacing::Bottom => UnitFacing::BottomRight,
            UnitFacing::BottomRight => UnitFacing::Right,
            UnitFacing::Right => UnitFacing::TopRight,
            UnitFacing::TopRight => UnitFacing::Top,
            UnitFacing::Top => UnitFacing::TopLeft,
            UnitFacing::TopLeft => UnitFacing::Left,
            UnitFacing::Left => UnitFacing::BottomLeft,
            UnitFacing::BottomLeft => UnitFacing::Bottom,
        }
    }

    pub fn rotation_cost_and_direction(self, target: Self) -> (u16, bool) {
        let mut facing = self;
        let mut cw_turns = 0;
        while facing != target {
            facing = facing.rotate_cw();
            cw_turns += 1;
        }

        let mut facing = self;
        let mut ccw_turns = 0;
        while facing != target {
            facing = facing.rotate_ccw();
            ccw_turns += 1;
        }

        if ccw_turns < cw_turns {
            (ccw_turns, false)
        } else {
            (cw_turns, true)
        }
    }
}

// The type of a unit
#[derive(PartialEq, Copy, Clone, Serialize, Deserialize, Debug)]
pub enum UnitType {
    Squaddie,
    Machine,
}

impl UnitType {
    pub fn moves(self) -> u16 {
        match self {
            UnitType::Squaddie => 30,
            UnitType::Machine => 25,
        }
    }

    pub fn health(self) -> i16 {
        match self {
            UnitType::Squaddie => 100,
            UnitType::Machine => 150,
        }
    }

    pub fn capacity(self) -> f32 {
        match self {
            UnitType::Squaddie => 25.0,
            UnitType::Machine => 75.0,
        }
    }

    pub fn sight(self) -> f32 {
        Unit::SIGHT
    }

    // How far the unit can throw
    pub fn throw_distance(self) -> f32 {
        self.sight() * 1.5
    }

    fn front_image(self) -> Image {
        match self {
            UnitType::Squaddie => Image::SquaddieFront,
            UnitType::Machine => Image::MachineFront,
        }
    }

    fn left_image(self) -> Image {
        match self {
            UnitType::Squaddie => Image::SquaddieLeft,
            UnitType::Machine => Image::MachineFront,
        }
    }

    fn right_image(self) -> Image {
        match self {
            UnitType::Squaddie => Image::SquaddieRight,
            UnitType::Machine => Image::MachineFront,
        }
    }

    fn back_image(self) -> Image {
        match self {
            UnitType::Squaddie => Image::SquaddieBack,
            UnitType::Machine => Image::MachineBack,
        }
    }
}

impl fmt::Display for UnitType {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "{}",
            match *self {
                UnitType::Squaddie => "Squaddie",
                UnitType::Machine => "Machine",
            }
        )
    }
}

// A struct for a unit in the game
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct Unit {
    pub id: u8,
    pub x: usize,
    pub y: usize,
    pub tag: UnitType,
    pub side: Side,
    pub weapon: Weapon,
    pub facing: UnitFacing,
    pub moves: u16,
    health: i16,
    name: String,
    inventory: Vec<Item>,
}

impl Unit {
    // The cost for a unit to walk laterally
    pub const WALK_LATERAL_COST: u16 = 2;
    // The cost for a unit to walk diagonally
    pub const WALK_DIAGONAL_COST: u16 = 3;
    // How far a unit can see
    pub const SIGHT: f32 = 7.5;

    // Create a new unit based on unit type
    pub fn new(tag: UnitType, side: Side, x: usize, y: usize, facing: UnitFacing, id: u8) -> Unit {
        let mut rng = rand::thread_rng();

        match tag {
            UnitType::Squaddie => {
                // Randomly choose a weapon
                let weapon_type = if rng.gen() {
                    WeaponType::Rifle
                } else {
                    WeaponType::MachineGun
                };
                let capacity = weapon_type.capacity();

                Unit {
                    tag,
                    side,
                    x,
                    y,
                    facing,
                    id,
                    weapon: Weapon::new(weapon_type, capacity),
                    name: generate_squaddie_name(&mut rng),
                    moves: tag.moves(),
                    health: tag.health(),
                    inventory: if let WeaponType::Rifle = weapon_type {
                        vec![
                            Item::RifleClip(capacity),
                            Item::RifleClip(capacity),
                            Item::Bandages,
                            Item::Grenade(false),
                        ]
                    } else {
                        vec![
                            Item::MachineGunClip(capacity),
                            Item::MachineGunClip(capacity),
                            Item::Bandages,
                            Item::Grenade(false),
                        ]
                    },
                }
            }
            UnitType::Machine => Unit {
                tag,
                side,
                x,
                y,
                facing,
                id,
                weapon: Weapon::new(WeaponType::PlasmaRifle, WeaponType::PlasmaRifle.capacity()),
                name: generate_machine_name(&mut rng),
                moves: tag.moves(),
                health: tag.health(),
                inventory: Vec::new(),
            },
        }
    }

    pub fn inventory(&self) -> &[Item] {
        &self.inventory
    }

    // The weight of the items that the units is carrying
    pub fn carrying(&self) -> f32 {
        self.inventory
            .iter()
            .fold(self.weapon.tag.weight(), |total, item| {
                total + item.weight()
            })
    }

    pub fn damage(&mut self, damage: i16) -> bool {
        self.health -= damage;
        self.health <= 0
    }

    // Move the unit to a location with a specific cost
    pub fn move_to(&mut self, point: &PathPoint) {
        self.x = point.x;
        self.y = point.y;
        self.facing = point.facing;
        self.moves -= point.cost;
    }

    pub fn inventory_remove(&mut self, item: usize) -> Option<Item> {
        if item < self.inventory.len() && self.moves >= ITEM_COST {
            self.moves -= ITEM_COST;
            Some(self.inventory.remove(item))
        } else {
            None
        }
    }

    // Get the chance-to-hit of a tile from the unit
    pub fn chance_to_hit(&self, target_x: usize, target_y: usize) -> f32 {
        chance_to_hit(self.x, self.y, target_x, target_y)
    }

    pub fn can_heal_from(&self, item: Item) -> bool {
        let amount = item.heal(self.tag);
        amount > 0 && self.moves >= ITEM_COST && self.tag.health() - self.health >= amount
    }

    pub fn can_reload_from(&self, item: Item) -> bool {
        let ammo = item.ammo(self.weapon.tag);
        ammo > 0 && self.weapon.can_reload(ammo)
    }

    // Drop an item from the unit's inventory
    pub fn drop_item(&mut self, tiles: &mut Tiles, index: usize) {
        if let Some(item) = self.inventory_remove(index) {
            tiles.drop(self.x, self.y, item);
        }
    }

    pub fn pickup_item(&mut self, tiles: &mut Tiles, index: usize) {
        if self.moves < ITEM_COST {
            return;
        }

        let tile = tiles.at_mut(self.x, self.y);

        if let Some(item) = tile.items_remove(index) {
            if self.carrying() + item.weight() <= self.tag.capacity() {
                self.inventory.push(item);
                self.moves -= ITEM_COST;
                return;
            }
        }
    }

    pub fn use_item(&mut self, index: usize) {
        let mut item_consumed = false;
        let mut new_item = None;

        // Return if the unit doesn't have the moves to use the item
        if self.moves < ITEM_COST {
            return;
        }

        if let Some(item) = self.inventory.get(index) {
            item_consumed = match (*item, self.weapon.tag) {
                // Reload the corresponding weapon
                (Item::RifleClip(ammo), WeaponType::Rifle)
                | (Item::MachineGunClip(ammo), WeaponType::MachineGun)
                | (Item::PlasmaClip(ammo), WeaponType::PlasmaRifle) => self.weapon.reload(ammo),
                // Switch weapons
                (Item::Rifle(ammo), _) => {
                    new_item = Some(self.weapon.to_item());
                    self.weapon = Weapon::new(WeaponType::Rifle, ammo);
                    true
                }
                (Item::MachineGun(ammo), _) => {
                    new_item = Some(self.weapon.to_item());
                    self.weapon = Weapon::new(WeaponType::MachineGun, ammo);
                    true
                }
                (Item::PlasmaRifle(ammo), _) => {
                    new_item = Some(self.weapon.to_item());
                    self.weapon = Weapon::new(WeaponType::PlasmaRifle, ammo);
                    true
                }
                // Use other items
                (Item::Bandages, _) if self.can_heal_from(*item) => {
                    self.health += item.heal(self.tag);
                    true
                }
                (Item::Grenade(primed), _) if !primed => {
                    new_item = Some(Item::Grenade(true));
                    true
                }
                _ => false,
            }
        }

        // If the item was consumed, remove it from the inventory
        if item_consumed {
            self.inventory.remove(index);
        }

        // If a new item was created, add it to the inventory
        if let Some(item) = new_item {
            self.inventory.push(item);
        }

        if item_consumed || new_item.is_some() {
            self.moves -= ITEM_COST;
        }
    }

    pub fn fire_weapon(&mut self) -> bool {
        let can_fire = self.moves >= self.weapon.tag.cost() && self.weapon.can_fire();

        if can_fire {
            self.moves -= self.weapon.tag.cost();
            self.weapon.ammo -= 1;
        }

        can_fire
    }

    pub fn info(&self) -> String {
        format!(
            "Name: {}, Moves: {}, Health: {}, Weapon: {}",
            self.name, self.moves, self.health, self.weapon
        )
    }

    pub fn carrying_info(&self) -> String {
        format!(
            "{}\n{} - {} kg\nCarry Capacity: {}/{} kg",
            self.name,
            self.weapon,
            self.weapon.tag.weight(),
            self.carrying(),
            self.tag.capacity()
        )
    }

    pub fn render(&self, ctx: &mut Context, dest: [f32; 2], zoom: f32, overlay: [f32; 4]) {
        let image = match self.facing {
            UnitFacing::Right | UnitFacing::BottomRight => self.tag.right_image(),
            UnitFacing::Bottom | UnitFacing::BottomLeft => self.tag.front_image(),
            UnitFacing::Left | UnitFacing::TopLeft => self.tag.left_image(),
            _ => self.tag.back_image(),
        };

        ctx.render_with_overlay(image, dest, zoom, overlay);
    }
}

// A struct for containing all of the units
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct Units {
    pub max_player_a_units: u8,
    pub max_player_b_units: u8,
    index: u8,
    units: HashMap<u8, Unit>,
}

impl Units {
    // Create a new Units struct
    pub fn new() -> Units {
        Units {
            index: 0,
            max_player_a_units: 0,
            max_player_b_units: 0,
            units: HashMap::new(),
        }
    }

    // Add a unit to the struct
    pub fn add(&mut self, tag: UnitType, side: Side, x: usize, y: usize, facing: UnitFacing) {
        match side {
            Side::PlayerA => self.max_player_a_units += 1,
            Side::PlayerB => self.max_player_b_units += 1,
        }

        self.units
            .insert(self.index, Unit::new(tag, side, x, y, facing, self.index));
        self.index += 1;
    }

    // Iterate over the units
    pub fn iter(&self) -> Values<u8, Unit> {
        self.units.values()
    }

    // Iterate mutably over the units
    pub fn iter_mut(&mut self) -> ValuesMut<u8, Unit> {
        self.units.values_mut()
    }

    // Get a reference to a unit with a specific ID, if the unit exists
    pub fn get(&self, id: u8) -> Option<&Unit> {
        self.units.get(&id)
    }

    // Get a mutable reference to a unit with a specific ID, if the unit exists
    pub fn get_mut(&mut self, id: u8) -> Option<&mut Unit> {
        self.units.get_mut(&id)
    }

    // Return a reference to a unit at (x, y)
    pub fn at(&self, x: usize, y: usize) -> Option<&Unit> {
        self.iter().find(|unit| unit.x == x && unit.y == y)
    }

    // Return a mutable reference to a unit at (x, y)
    pub fn at_mut(&mut self, x: usize, y: usize) -> Option<&mut Unit> {
        self.iter_mut().find(|unit| unit.x == x && unit.y == y)
    }

    // Count the number of units on a particular side
    pub fn count(&self, side: Side) -> u8 {
        self.iter().filter(|unit| unit.side == side).count() as u8
    }

    // Is a unit on a particular side at (x, y)?
    pub fn on_side(&self, x: usize, y: usize, side: Side) -> bool {
        self.at(x, y).map(|unit| unit.side == side).unwrap_or(false)
    }

    // Kill a unit and drop a corpse
    pub fn kill(&mut self, tiles: &mut Tiles, id: u8) {
        if let Some(unit) = self.get_mut(id) {
            let corpse = match unit.tag {
                UnitType::Squaddie => Item::SquaddieCorpse,
                UnitType::Machine => Item::MachineCorpse,
            };

            // Drop the unit's items
            tiles.drop_all(unit.x, unit.y, &mut unit.inventory);
            // Drop the unit's weapon
            tiles.drop(unit.x, unit.y, unit.weapon.to_item());
            // Drop the unit's corpse
            tiles.drop(unit.x, unit.y, corpse);
        } else {
            return;
        }
        // Remove the unit
        self.units.remove(&id);
        // Update the visibility of the tiles
        tiles.update_visibility(self);
    }
}

impl FromIterator<Unit> for Units {
    fn from_iter<I: IntoIterator<Item = Unit>>(iterator: I) -> Self {
        let mut max_player_a_units = 0;
        let mut max_player_b_units = 0;

        let units = iterator
            .into_iter()
            .inspect(|unit| match unit.side {
                Side::PlayerA => max_player_a_units += 1,
                Side::PlayerB => max_player_b_units += 1,
            })
            .map(|unit| (unit.id, unit))
            .collect();

        Self {
            max_player_a_units,
            max_player_b_units,
            units,
            index: 0,
        }
    }
}

#[test]
fn unit_actions() {
    let mut units = Units::new();
    let mut tiles = Tiles::new(30, 30);

    let rifle = WeaponType::Rifle;
    let plasma_rifle = WeaponType::PlasmaRifle;

    // After adding 10 units, there should be 10 ai units into total

    for i in 0..10 {
        units.add(UnitType::Machine, Side::PlayerB, i, i, UnitFacing::Bottom);
    }

    assert_eq!(units.count(Side::PlayerB), 10);

    // Iterating over the units should work as expected

    {
        // A unit should be carrying the weight of a plasma rifle

        let unit = units.get_mut(0).unwrap();

        assert_eq!(unit.carrying(), plasma_rifle.weight());

        // Test picking up a rifle

        tiles.at_mut(0, 0).items.push(Item::Rifle(rifle.capacity()));

        assert_eq!(unit.inventory, Vec::new());
        unit.pickup_item(&mut tiles, 0);
        assert_eq!(unit.inventory, vec![Item::Rifle(rifle.capacity())]);
        assert_eq!(tiles.at(0, 0).items, Vec::new());

        assert_eq!(unit.inventory[0], Item::Rifle(rifle.capacity()));

        assert_eq!(unit.carrying(), plasma_rifle.weight() + rifle.weight());

        assert_eq!(unit.moves, unit.tag.moves() - ITEM_COST);

        // Test equpping a rifle

        unit.use_item(0);

        assert_eq!(
            unit.inventory[0],
            Item::PlasmaRifle(plasma_rifle.capacity())
        );

        assert_eq!(unit.moves, unit.tag.moves() - ITEM_COST * 2);

        // The unit is at full health and shouldn't be able to heal

        assert!(!unit.can_heal_from(Item::Bandages));

        // Or reload

        assert!(!unit.can_reload_from(Item::RifleClip(rifle.capacity())));

        // Test firing the weapon

        assert!(unit.fire_weapon());

        assert_eq!(unit.moves, unit.tag.moves() - ITEM_COST * 2 - rifle.cost());
    }

    // After killing a unit there should be 9 left

    units.kill(&mut tiles, 0);

    assert_eq!(units.count(Side::PlayerB), 9);

    // And the tile under the unit should have items on it

    assert_ne!(tiles.at(0, 0).items, Vec::new());
}

#[test]
fn test_turning() {
    let (cost, direction) = UnitFacing::Bottom.rotation_cost_and_direction(UnitFacing::Top);
    assert_eq!((cost, direction), (4, true));

    let (cost, direction) = UnitFacing::BottomRight.rotation_cost_and_direction(UnitFacing::Top);
    assert_eq!((cost, direction), (3, false));
}


text:
class Person
  def initialize(name, age)
    @name = name
    @age = age
  end

  def birthday
    @age += 1
  end

  attr_accessor 'name', 'age'
end

josh = Person.new 'Josh', 28

josh.name
josh.age

josh.name = 'Joshua'
josh.name

josh.birthday
josh.age

josh.birthday
josh.age


text:
function Neo(urlSource) {
	function txUrl() {
		var url = (urlSource() || "http://localhost:7474").replace(/\/db\/data.*/,"");
		return url + "/db/data/cypher";
	}
	function getIdFromUrl(url){
		var segments = url.split('/');
		return segments[segments.length-1];
	}
	var me = {
		executeQuery: function(query, params, cb) {
			$.ajax(txUrl(), {
				type: "POST",
				data: JSON.stringify({
					  query : query,
					  params : params || {}
				}),
				contentType: "application/json",
				error: function(err) {
					cb(err);
				},
				success: function(res) {
					if (res.exception) {
						cb(res.exception);
					} else {
						var cols = res.columns;
						var rows = res.data.map(function(row) {
							var r = {};
							cols.forEach(function(col, index) {
								r[col] = row[index];
							});
							return r;
						});
						var nodes = [];
						var rels = [];
						var labels = [];
						res.data.forEach(function(row) {

							var node = row[0]['data'];

							for (var property in node) {
							    if (Object.hasOwnProperty(property)) {
							    	var found = nodes.filter(function (m) { return m.id == node.id; }).length > 0;
									   if (!found) {
										  nodes.push(node);
										  if (labels.indexOf(node.label) == -1) labels.push(node.label);
									   }
							    }
							}

							var rel = row[1];
							if(rel){
								rels = rels.concat({ source:getIdFromUrl(rel.start), target:getIdFromUrl(rel.end), caption:rel.type});
							}
							/*row.graph.nodes.forEach(function(n) {
							   var found = nodes.filter(function (m) { return m.id == n.id; }).length > 0;
							   if (!found) {
								  var node = n.properties||{}; node.id=n.id;node.type=n.labels[0];
								  nodes.push(node);
								  if (labels.indexOf(node.type) == -1) labels.push(node.type);
							   }
							});*/

							//rels = rels.concat(row.graph.relationships.map(function(r) { return { source:r.startNode, target:r.endNode, caption:r.type} }));
						});
						cb(null,{table:rows,graph:{nodes:nodes, edges:rels},labels:labels});
					}
				}
			});
		}
	};
	return me;
}


text:
module DiaryHelper

  def diary_page(diaries,before)
    if before
      diaries = diaries.where("diaries.id < ?", before)
      sum = diaries.count
      start = sum - Settings.paginate_per_page
      has_more = start > 0
      if start > 0
        diaries = diaries.limit "#{start}, #{Settings.paginate_per_page}"
      else
        diaries = diaries.limit Settings.paginate_per_page
      end
    else
      has_more = (diaries.count - Settings.paginate_per_page) > 0
      diaries = diaries.limit(Settings.paginate_per_page)
    end

    present diaries, with: DiaryEntity
    body( { has_more: has_more, data: body() })
  end

end


text:
module WebMock

  def self.included(clazz)
    WebMock::Deprecation.warning("include WebMock is deprecated. Please include WebMock::API instead")
    if clazz.instance_methods.map(&:to_s).include?('request')
      warn "WebMock#request was not included in #{clazz} to avoid name collision"
    else
      clazz.class_eval do
        def request(method, uri)
          WebMock::Deprecation.warning("WebMock#request is deprecated. Please use WebMock::API#a_request method instead")
          WebMock.a_request(method, uri)
        end
      end
    end
  end

  include WebMock::API
  extend WebMock::API

  class << self
    alias :request :a_request
  end

  def self.version
    VERSION
  end

  def self.disable!(options = {})
    except = [options[:except]].flatten.compact
    HttpLibAdapterRegistry.instance.each_adapter do |name, adapter|
      adapter.enable!
      adapter.disable! unless except.include?(name)
    end
  end

  def self.enable!(options = {})
    except = [options[:except]].flatten.compact
    HttpLibAdapterRegistry.instance.each_adapter do |name, adapter|
      adapter.disable!
      adapter.enable! unless except.include?(name)
    end
  end

  def self.allow_net_connect!(options = {})
    Config.instance.allow_net_connect = true
    Config.instance.net_http_connect_on_start = options[:net_http_connect_on_start]
  end

  def self.disable_net_connect!(options = {})
    Config.instance.allow_net_connect = false
    Config.instance.allow_localhost = options[:allow_localhost]
    Config.instance.allow = options[:allow]
    Config.instance.net_http_connect_on_start = options[:net_http_connect_on_start]
  end

  def self.net_connect_allowed?(uri = nil)
    if uri.is_a?(String)
      uri = WebMock::Util::URI.normalize_uri(uri)
    end

    Config.instance.allow_net_connect ||
    ( Config.instance.allow_localhost && WebMock::Util::URI.is_uri_localhost?(uri) ||
      Config.instance.allow && net_connect_explicit_allowed?(Config.instance.allow, uri) )
  end

  def self.net_connect_explicit_allowed?(allowed, uri=nil)
    case allowed
    when Array
      allowed.any? { |allowed_item| net_connect_explicit_allowed?(allowed_item, uri) }
    when Regexp
      uri.to_s =~ allowed
    when String
      allowed == uri.host ||
      allowed == "#{uri.host}:#{uri.port}"
    else
      if allowed.respond_to?(:call)
        allowed.call(uri)
      end
    end
  end

  def self.show_body_diff!
    Config.instance.show_body_diff = true
  end

  def self.hide_body_diff!
    Config.instance.show_body_diff = false
  end

  def self.show_body_diff?
    Config.instance.show_body_diff
  end

  def self.hide_stubbing_instructions!
    Config.instance.show_stubbing_instructions = false
  end

  def self.show_stubbing_instructions!
    Config.instance.show_stubbing_instructions = true
  end

  def self.show_stubbing_instructions?
    Config.instance.show_stubbing_instructions
  end

  def self.reset!
    WebMock::RequestRegistry.instance.reset!
    WebMock::StubRegistry.instance.reset!
  end

  def self.reset_webmock
    WebMock::Deprecation.warning("WebMock.reset_webmock is deprecated. Please use WebMock.reset! method instead")
    reset!
  end

  def self.reset_callbacks
    WebMock::CallbackRegistry.reset
  end

  def self.after_request(options={}, &block)
    WebMock::CallbackRegistry.add_callback(options, block)
  end

  def self.registered_request?(request_signature)
    WebMock::StubRegistry.instance.registered_request?(request_signature)
  end

  def self.print_executed_requests
    puts WebMock::RequestExecutionVerifier.executed_requests_message
  end

  def self.globally_stub_request(&block)
    WebMock::StubRegistry.instance.register_global_stub(&block)
  end

  %w(
    allow_net_connect!
    disable_net_connect!
    net_connect_allowed?
    reset_webmock
    reset_callbacks
    after_request
    registered_request?
  ).each do |method|
    self.class_eval(%Q(
                      def #{method}(*args, &block)
                        WebMock::Deprecation.warning("WebMock##{method} instance method is deprecated. Please use WebMock.#{method} class method instead")
                        WebMock.#{method}(*args, &block)
                          end
    ))
  end

  self.enable!
end


text:
#include "paddle/fluid/inference/analysis/pass_manager.h"
#include "paddle/fluid/inference/analysis/fluid_to_data_flow_graph_pass.h"

namespace paddle {
namespace inference {
namespace analysis {

bool PassManager::Initialize(Argument* argument) {
  argument_ = argument;
  for (auto& pass : data_) {
    LOG(INFO) << "Initializing pass " << pass->repr();
    if (!pass->Initialize(argument)) {
      LOG(ERROR) << "Failed to initialize pass [" << pass->repr() << "]";
      return false;
    }
  }
  return true;
}

void DfgPassManager::RunAll() {
  PADDLE_ENFORCE(argument_);
  for (auto& pass : data_) {
    VLOG(4) << "Running pass [" << pass->repr() << "]";
    pass->Run(argument_->main_dfg.get());
  }
}

void NodePassManager::RunAll() {
  PADDLE_ENFORCE(argument_);
  PADDLE_ENFORCE(argument_->main_dfg.get());
  auto trait =
      GraphTraits<DataFlowGraph>(argument_->main_dfg.get()).nodes_in_DFS();
  for (auto& node : trait) {
    for (auto& pass : data_) {
      pass->Run(&node);
    }
  }
}

}  // namespace analysis
}  // namespace inference
}  // namespace paddle


text:
func mime(path string) (string, error) {

	file, err := os.Open(path)
	if err != nil {
		return "", err
	}
	defer file.Close()

	// Only the first 512 bytes are used to sniff the content type.
	buffer := make([]byte, 512)
	n, err := file.Read(buffer)
	if err != nil && err != io.EOF {
		return "", err
	}
	return http.DetectContentType(buffer[:n]), nil
}


text:
typedef NS_ENUM(NSUInteger, JLoadMoreViewState) {
    JLoadMoreViewStateNormal,
    JLoadMoreViewStateLoading,
    JLoadMoreViewStateFailed,
};

@class JLoadMoreView;

@protocol JLoadMoreViewDelegate <NSObject>

- (void)loadMoreViewDidStartLoad:(JLoadMoreView *)view;
- (BOOL)loadMoreViewIsLoading:(JLoadMoreView *)view;

@end

@interface JLoadMoreView : UIView

@property (nonatomic, assign) id<JLoadMoreViewDelegate> delegate;
@property (nonatomic, assign) JLoadMoreViewState state;

- (void)scrollViewDidScroll:(UIScrollView *)scrollView;
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView;
- (void)startLoad;

@end


text: The Great Hypertext Hairball


text:
package org.xwalk.core;

import org.chromium.base.CalledByNative;
import org.chromium.base.JNINamespace;
import org.chromium.components.web_contents_delegate_android.WebContentsDelegateAndroid;

@JNINamespace("xwalk")
abstract class XWalkWebContentsDelegate extends WebContentsDelegateAndroid {
    @CalledByNative
    public abstract boolean addNewContents(boolean isDialog, boolean isUserGesture);

    @CalledByNative
    public abstract void closeContents();

    @CalledByNative
    public abstract void activateContents();

    @CalledByNative
    public abstract void rendererUnresponsive();

    @CalledByNative
    public abstract void rendererResponsive();

    @CalledByNative
    public void updatePreferredSize(int widthCss, int heightCss) {
    }

    @CalledByNative
    public void toggleFullscreen(boolean enterFullscreen) {
    }

    @CalledByNative
    public boolean isFullscreen() {
        return false;
    }
}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Syll. fung. (Abellini) 6: 332 (1888)

#### Original name
Boletus terrestris DC., 1815

### Remarks
null


text:
.class public Landroid/support/v7/app/AppCompatDialogFragment;
.super Landroid/support/v4/app/DialogFragment;
.source "AppCompatDialogFragment.java"

# direct methods
.method public constructor <init>()V
    .registers 1

    .prologue
    .line 35
    invoke-direct {p0}, Landroid/support/v4/app/DialogFragment;-><init>()V

    return-void
.end method

# virtual methods
.method public onCreateDialog(Landroid/os/Bundle;)Landroid/app/Dialog;
    .registers 5
    .param p1, "savedInstanceState"    # Landroid/os/Bundle;

    .prologue
    .line 39
    new-instance v0, Landroid/support/v7/app/AppCompatDialog;

    invoke-virtual {p0}, Landroid/support/v7/app/AppCompatDialogFragment;->getContext()Landroid/content/Context;

    move-result-object v1

    invoke-virtual {p0}, Landroid/support/v7/app/AppCompatDialogFragment;->getTheme()I

    move-result v2

    invoke-direct {v0, v1, v2}, Landroid/support/v7/app/AppCompatDialog;-><init>(Landroid/content/Context;I)V

    return-object v0
.end method

.method public setupDialog(Landroid/app/Dialog;I)V
    .registers 6
    .param p1, "dialog"    # Landroid/app/Dialog;
    .param p2, "style"    # I
    .annotation build Landroid/support/annotation/RestrictTo;
        value = {
            .enum Landroid/support/annotation/RestrictTo$Scope;->LIBRARY_GROUP:Landroid/support/annotation/RestrictTo$Scope;
        }
    .end annotation

    .prologue
    .line 46
    instance-of v1, p1, Landroid/support/v7/app/AppCompatDialog;

    if-eqz v1, :cond_19

    move-object v0, p1

    .line 48
    check-cast v0, Landroid/support/v7/app/AppCompatDialog;

    .line 49
    .local v0, "acd":Landroid/support/v7/app/AppCompatDialog;
    packed-switch p2, :pswitch_data_1e

    .line 63
    .end local v0    # "acd":Landroid/support/v7/app/AppCompatDialog;
    :goto_a
    return-void

    .line 51
    .restart local v0    # "acd":Landroid/support/v7/app/AppCompatDialog;
    :pswitch_b
    invoke-virtual {p1}, Landroid/app/Dialog;->getWindow()Landroid/view/Window;

    move-result-object v1

    const/16 v2, 0x18

    invoke-virtual {v1, v2}, Landroid/view/Window;->addFlags(I)V

    .line 57
    :pswitch_14
    const/4 v1, 0x1

    invoke-virtual {v0, v1}, Landroid/support/v7/app/AppCompatDialog;->supportRequestWindowFeature(I)Z

    goto :goto_a

    .line 61
    .end local v0    # "acd":Landroid/support/v7/app/AppCompatDialog;
    :cond_19
    invoke-super {p0, p1, p2}, Landroid/support/v4/app/DialogFragment;->setupDialog(Landroid/app/Dialog;I)V

    goto :goto_a

    .line 49
    nop

    :pswitch_data_1e
    .packed-switch 0x1
        :pswitch_14
        :pswitch_14
        :pswitch_b
    .end packed-switch
.end method


text:
class CookiesTreeModel;
class LocalDataContainer;

namespace content {
struct StorageUsageInfo;
}

namespace net {
class CanonicalCookie;
}

// LocalDataContainer ---------------------------------------------------------
// This class is a wrapper around all the BrowsingData*Helper classes. Because
// isolated applications have separate storage, we need different helper
// instances. As such, this class contains the app name and id, along with the
// helpers for all of the data types we need. The browser-wide "app id" will be
// the empty string, as no app can have an empty id.
class LocalDataContainer {
 public:
  // Friendly typedefs for the multiple types of lists used in the model.
  using CookieList = std::list<net::CanonicalCookie>;
  using DatabaseInfoList = std::list<content::StorageUsageInfo>;
  using LocalStorageInfoList = std::list<content::StorageUsageInfo>;
  using SessionStorageInfoList = std::list<content::StorageUsageInfo>;
  using IndexedDBInfoList = std::list<content::StorageUsageInfo>;
  using FileSystemInfoList =
      std::list<browsing_data::FileSystemHelper::FileSystemInfo>;
  using QuotaInfoList = std::list<BrowsingDataQuotaHelper::QuotaInfo>;
  using ServiceWorkerUsageInfoList = std::list<content::StorageUsageInfo>;
  using SharedWorkerInfoList =
      std::list<browsing_data::SharedWorkerHelper::SharedWorkerInfo>;
  using CacheStorageUsageInfoList = std::list<content::StorageUsageInfo>;
  using MediaLicenseUsageInfoList = std::list<content::StorageUsageInfo>;

  LocalDataContainer(
      scoped_refptr<browsing_data::CookieHelper> cookie_helper,
      scoped_refptr<browsing_data::DatabaseHelper> database_helper,
      scoped_refptr<browsing_data::LocalStorageHelper> local_storage_helper,
      scoped_refptr<browsing_data::LocalStorageHelper> session_storage_helper,
      scoped_refptr<browsing_data::IndexedDBHelper> indexed_db_helper,
      scoped_refptr<browsing_data::FileSystemHelper> file_system_helper,
      scoped_refptr<BrowsingDataQuotaHelper> quota_helper,
      scoped_refptr<browsing_data::ServiceWorkerHelper> service_worker_helper,
      scoped_refptr<browsing_data::SharedWorkerHelper> shared_worker_helper,
      scoped_refptr<browsing_data::CacheStorageHelper> cache_storage_helper,
      scoped_refptr<BrowsingDataMediaLicenseHelper> media_license_helper);

  LocalDataContainer(const LocalDataContainer&) = delete;
  LocalDataContainer& operator=(const LocalDataContainer&) = delete;

  virtual ~LocalDataContainer();

  // This method must be called to start the process of fetching the resources.
  // The delegate passed in is called back to deliver the updates.
  void Init(CookiesTreeModel* delegate);

 private:
  friend class CookiesTreeModel;
  friend class CookieTreeMediaLicenseNode;
  friend class CookieTreeCookieNode;
  friend class CookieTreeDatabaseNode;
  friend class CookieTreeLocalStorageNode;
  friend class CookieTreeSessionStorageNode;
  friend class CookieTreeIndexedDBNode;
  friend class CookieTreeFileSystemNode;
  friend class CookieTreeQuotaNode;
  friend class CookieTreeServiceWorkerNode;
  friend class CookieTreeSharedWorkerNode;
  friend class CookieTreeCacheStorageNode;

  // Callback methods to be invoked when fetching the data is complete.
  void OnCookiesModelInfoLoaded(const net::CookieList& cookie_list);
  void OnDatabaseModelInfoLoaded(const DatabaseInfoList& database_info);
  void OnLocalStorageModelInfoLoaded(
      const LocalStorageInfoList& local_storage_info);
  void OnSessionStorageModelInfoLoaded(
      const LocalStorageInfoList& local_storage_info);
  void OnIndexedDBModelInfoLoaded(
      const IndexedDBInfoList& indexed_db_info);
  void OnFileSystemModelInfoLoaded(
      const FileSystemInfoList& file_system_info);
  void OnQuotaModelInfoLoaded(const QuotaInfoList& quota_info);
  void OnServiceWorkerModelInfoLoaded(
      const ServiceWorkerUsageInfoList& service_worker_info);
  void OnSharedWorkerInfoLoaded(const SharedWorkerInfoList& shared_worker_info);
  void OnCacheStorageModelInfoLoaded(
      const CacheStorageUsageInfoList& cache_storage_info);
  void OnMediaLicenseInfoLoaded(
      const MediaLicenseUsageInfoList& media_license_usage_info);

  // Pointers to the helper objects, needed to retreive all the types of locally
  // stored data.
  scoped_refptr<browsing_data::CookieHelper> cookie_helper_;
  scoped_refptr<browsing_data::DatabaseHelper> database_helper_;
  scoped_refptr<browsing_data::LocalStorageHelper> local_storage_helper_;
  scoped_refptr<browsing_data::LocalStorageHelper> session_storage_helper_;
  scoped_refptr<browsing_data::IndexedDBHelper> indexed_db_helper_;
  scoped_refptr<browsing_data::FileSystemHelper> file_system_helper_;
  scoped_refptr<BrowsingDataQuotaHelper> quota_helper_;
  scoped_refptr<browsing_data::ServiceWorkerHelper> service_worker_helper_;
  scoped_refptr<browsing_data::SharedWorkerHelper> shared_worker_helper_;
  scoped_refptr<browsing_data::CacheStorageHelper> cache_storage_helper_;
  scoped_refptr<BrowsingDataMediaLicenseHelper> media_license_helper_;

  // Storage for all the data that was retrieved through the helper objects.
  // The collected data is used for (re)creating the CookiesTreeModel.
  CookieList cookie_list_;
  DatabaseInfoList database_info_list_;
  LocalStorageInfoList local_storage_info_list_;
  LocalStorageInfoList session_storage_info_list_;
  IndexedDBInfoList indexed_db_info_list_;
  FileSystemInfoList file_system_info_list_;
  QuotaInfoList quota_info_list_;
  ServiceWorkerUsageInfoList service_worker_info_list_;
  SharedWorkerInfoList shared_worker_info_list_;
  CacheStorageUsageInfoList cache_storage_info_list_;
  MediaLicenseUsageInfoList media_license_info_list_;

  // A delegate, which must outlive this object. The update callbacks use the
  // delegate to deliver the updated data to the CookieTreeModel.
  raw_ptr<CookiesTreeModel> model_ = nullptr;

  // Keeps track of how many batches are expected to start.
  int batches_started_ = 0;

  base::WeakPtrFactory<LocalDataContainer> weak_ptr_factory_{this};
};

#endif  // CHROME_BROWSER_BROWSING_DATA_LOCAL_DATA_CONTAINER_H_


text:
OUTFILE=./jsjac.js
PACKFILE=./jsjac.packed.js
UNCOMPRESSED=./jsjac.uncompressed.js
SRC=src/jsextras.js src/crypt.js src/JSJaCJSON.js src/xmlextras.js \
src/JSJaCBuilder.js src/JSJaCConstants.js \
src/JSJaCConsoleLogger.js src/JSJaCCookie.js src/JSJaCError.js \
src/JSJaCJID.js src/JSJaCKeys.js src/JSJaCPacket.js src/JSJaCConnection.js \
src/JSJaCHttpBindingConnection.js src/JSJaCHttpPollingConnection.js \
src/JSJaC.js

all: clean utils install doc

install: build uncompressed crunch
	@echo "done."

build:
	@echo "building ...";
	@for i in ${SRC}; do \
		echo "\t$$i"; \
		cat "$$i" >> $(OUTFILE); \
	done

crunch:
	@echo "crunching ..."
	@if [ -e $(OUTFILE) ]; then \
		utils/jsmin < $(OUTFILE) > $(OUTFILE).tmp && \
		cat src/header.js > $(OUTFILE) && \
		cat src/JSJaCConfig.js >> $(OUTFILE) && \
		cat $(OUTFILE).tmp >> $(OUTFILE) && \
		rm $(OUTFILE).tmp; \
	fi

pack: clean utils build moo crunch doc

moo:
	@echo "packing..."
	@if [ -e $(OUTFILE) ]; then \
		php ./utils/packer/pack.php $(OUTFILE) $(PACKFILE).tmp && \
		cat src/header.js > $(PACKFILE) && \
		cat src/JSJaCConfig.js >> $(PACKFILE) && \
		cat $(PACKFILE).tmp >> $(PACKFILE) && \
		rm $(PACKFILE).tmp; \
	else \
		echo "$(OUTFILE) not found. build failed?"; \
	fi

doc:
	@utils/JSDoc/jsdoc.pl --project-name JSJaC -d doc src/

utils:
	@make -C utils
clean:
	@rm -f $(OUTFILE) 2>/dev/null
	@rm -f $(PACKFILE) 2>/dev/null
	@rm -f $(UNCOMPRESSED) 2>/dev/null
	@rm -rf doc/
	@make -C utils clean

uncompressed:
	@if [ -e $(OUTFILE) ]; then \
		cat src/header.js > $(UNCOMPRESSED) && \
		cat src/JSJaCConfig.js >> $(UNCOMPRESSED) && \
		cat $(OUTFILE) >> $(UNCOMPRESSED); \
	fi

.PHONY: doc utils


text:
using System.Collections.Immutable;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Analyzer.Utilities;

namespace Microsoft.ApiDesignGuidelines.Analyzers
{
    /// <summary>
    /// CA1064: Exceptions should be public
    /// </summary>
    public abstract class ExceptionsShouldBePublicAnalyzer : DiagnosticAnalyzer
    {
        internal const string RuleId = "CA1064";

        private static readonly LocalizableString s_localizableTitle = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.ExceptionsShouldBePublicTitle), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources));

        private static readonly LocalizableString s_localizableMessage = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.ExceptionsShouldBePublicMessage), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources));
        private static readonly LocalizableString s_localizableDescription = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.ExceptionsShouldBePublicDescription), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources));

        internal static DiagnosticDescriptor Rule = new DiagnosticDescriptor(RuleId,
                                                                             s_localizableTitle,
                                                                             s_localizableMessage,
                                                                             DiagnosticCategory.Design,
                                                                             DiagnosticSeverity.Warning,
                                                                             isEnabledByDefault: false,
                                                                             description: s_localizableDescription,
                                                                             helpLinkUri: null,     // TODO: add MSDN url
                                                                             customTags: WellKnownDiagnosticTags.Telemetry);

        public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule);

        public override void Initialize(AnalysisContext analysisContext)
        {

        }
    }
}


text:
package org.luaj.vm2.server;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * Class loader that can be used to launch a lua script in a Java VM that has a
 * unique set of classes for org.luaj classes.
 *

 * Note: This class is experimental and subject to change in future
 * versions.
 *

 * By using a custom class loader per script, it allows the script to have its
 * own set of globals, including static values such as shared metatables that
 * cannot access lua values from other scripts because their classes are loaded
 * from different class loaders. Thus normally unsafe libraries such as luajava
 * can be exposed to scripts in a server environment using these techniques.
 *

 * All classes in the package "org.luaj.vm2." are considered user classes, and
 * loaded into this class loader from their bytes in the class path. Other
 * classes are considered systemc classes and loaded via the system loader. This
 * class set can be extended by overriding {@link #isUserClass(String)}.
 *

 * The {@link Launcher} interface is loaded as a system class by exception so
 * that the caller may use it to launch lua scripts.
 *

 * By default {@link #NewLauncher()} creates a subclass of {@link Launcher} of
 * type {@link DefaultLauncher} which creates debug globals, runs the script,
 * and prints the return values. This behavior can be changed by supplying a
 * different implementation class to {@link #NewLauncher(Class)} which must
 * extend {@link Launcher}.
 *
 * @see Launcher
 * @see #NewLauncher()
 * @see #NewLauncher(Class)
 * @see DefaultLauncher
 * @since luaj 3.0.1
 */
public class LuajClassLoader extends ClassLoader {

	/**
	 * String describing the luaj packages to consider part of the user classes
	 */
	static final String luajPackageRoot = "org.luaj.vm2.";

	/**
	 * String describing the Launcher interface to be considered a system class
	 */
	static final String launcherInterfaceRoot = Launcher.class.getName();

	/** Local cache of classes loaded by this loader. */
	Map<String, Class<?>> classes = new HashMap<>();

	/**
	 * Construct a default {@link Launcher} instance that will load classes in
	 * its own {@link LuajClassLoader} using the default implementation class
	 * {@link DefaultLauncher}.
	 *

	 * The {@link Launcher} that is returned will be a pristine luaj vm whose
	 * classes are loaded into this loader including static variables such as
	 * shared metatables, and should not be able to directly access variables
	 * from other Launcher instances.
	 *
	 * @return {@link Launcher} instance that can be used to launch scripts.
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 * @throws ClassNotFoundException
	 */
	public static Launcher NewLauncher() throws InstantiationException, IllegalAccessException, ClassNotFoundException {
		return NewLauncher(DefaultLauncher.class);
	}

	/**
	 * Construct a {@link Launcher} instance that will load classes in its own
	 * {@link LuajClassLoader} using a user-supplied implementation class that
	 * implements {@link Launcher}.
	 *

	 * The {@link Launcher} that is returned will be a pristine luaj vm whose
	 * classes are loaded into this loader including static variables such as
	 * shared metatables, and should not be able to directly access variables
	 * from other Launcher instances.
	 *
	 * @return instance of type 'launcher_class' that can be used to launch
	 *         scripts.
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 * @throws ClassNotFoundException
	 */
	public static Launcher NewLauncher(Class<? extends Launcher> launcher_class)
		throws InstantiationException, IllegalAccessException, ClassNotFoundException {
		final LuajClassLoader loader = new LuajClassLoader();
		final Object instance = loader.loadAsUserClass(launcher_class.getName()).newInstance();
		return (Launcher) instance;
	}

	/**
	 * Test if a class name should be considered a user class and loaded by this
	 * loader, or a system class and loaded by the system loader.
	 *
	 * @param classname Class name to test.
	 * @return true if this should be loaded into this class loader.
	 */
	public static boolean isUserClass(String classname) {
		return classname.startsWith(luajPackageRoot) && !classname.startsWith(launcherInterfaceRoot);
	}

	@Override
	public Class<?> loadClass(String classname) throws ClassNotFoundException {
		if (classes.containsKey(classname))
			return classes.get(classname);
		if (!isUserClass(classname))
			return super.findSystemClass(classname);
		return loadAsUserClass(classname);
	}

	private Class<?> loadAsUserClass(String classname) throws ClassNotFoundException {
		final String path = classname.replace('.', '/').concat(".class");
		InputStream is = getResourceAsStream(path);
		if (is != null) {
			try {
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				byte[] b = new byte[1024];
				for (int n = 0; (n = is.read(b)) >= 0;)
					baos.write(b, 0, n);
				byte[] bytes = baos.toByteArray();
				Class<?> result = super.defineClass(classname, bytes, 0, bytes.length);
				classes.put(classname, result);
				return result;
			} catch (java.io.IOException e) {
				throw new ClassNotFoundException("Read failed: " + classname + ": " + e);
			}
		}
		throw new ClassNotFoundException("Not found: " + classname);
	}
}


text:
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------

using Microsoft.Azure.Commands.NotificationHubs.Models;
using System.Management.Automation;
using System.Globalization;
using System;
using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters;

namespace Microsoft.Azure.Commands.NotificationHubs.Commands.NotificationHub
{

    [Cmdlet(VerbsCommon.Set, "AzureRmNotificationHub", SupportsShouldProcess = true), OutputType(typeof(NotificationHubAttributes))]
    public class SetAzureNotificationHub : AzureNotificationHubsCmdletBase
    {
        [Parameter(Mandatory = true,
            ValueFromPipelineByPropertyName = true,
            Position = 0,
            HelpMessage = "The name of the resource group")]
        [ResourceGroupCompleter]
        [ValidateNotNullOrEmpty]
        public string ResourceGroup { get; set; }

        [Parameter(Mandatory = true,
           ValueFromPipelineByPropertyName = true,
           Position = 1,
           HelpMessage = "Namespace Name.")]
        [ValidateNotNullOrEmpty]
        public string Namespace { get; set; }

        [Parameter(Mandatory = true,
            ParameterSetName = InputFileParameterSetName,
            Position = 2,
            HelpMessage = "File name containing a single NotificationHub definition.")]
        [ValidateNotNullOrEmpty]
        public string InputFile { get; set; }

        [Parameter(Mandatory = true,
            ParameterSetName = NotificationHubParameterSetName,
            Position = 2,
            HelpMessage = "NotificationHub definition.")]
        [ValidateNotNullOrEmpty]
        public NotificationHubAttributes NotificationHubObj { get; set; }

        /// <summary>
        /// If present, do not ask for confirmation
        /// </summary>
        [Parameter(Mandatory = false,
           HelpMessage = "Do not ask for confirmation.")]
        public SwitchParameter Force { get; set; }

        public override void ExecuteCmdlet()
        {
            NotificationHubAttributes hub = null;
            if (!string.IsNullOrEmpty(InputFile))
            {
                hub = ParseInputFile<NotificationHubAttributes>(InputFile);
            }
            else
            {
                hub = NotificationHubObj;
            }

            if (!string.IsNullOrEmpty(hub.Name))
            {
                ConfirmAction(
                Force.IsPresent,
                string.Format(CultureInfo.InvariantCulture, Resources.UpdateNotificationHub_Confirm, hub.Name),
                Resources.UpdateNotificationHub_WhatIf,
                hub.Name,
                () =>
                {

                    var hubAttributes = Client.UpdateNotificationHub(ResourceGroup, Namespace, hub);
                    WriteObject(hubAttributes);
                });
            }
            else
            {
                throw new ArgumentNullException(Resources.NotificationHubNameNull);
            }
        }
    }
}


text:
// Specific protocol driver library
#include "iDatalink.h"

volatile Uint8 VSSSupported;
volatile Uint8 VehicleSpeed;


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//------------------------------------------------------------------------------
// <copyright from='1997' to='2015' company='Microsoft Corporation'>
//    Information Contained Herein is Proprietary and Confidential.
// </copyright>
//------------------------------------------------------------------------------

using System;
using System.Reflection;
using System.Globalization;
using System.Resources;
using System.Text;
using System.Threading;
using System.Security.Permissions;

using System.ComponentModel;

namespace Microsoft.Build.Tasks
{
    [AttributeUsage(AttributeTargets.All)]
    internal sealed class SRDescriptionAttribute : DescriptionAttribute
    {
        private bool _replaced = false;

        /// <summary>
        ///     Constructs a new sys description.
        /// </summary>
        /// <param name='description'>
        ///     description text.
        /// </param>
        public SRDescriptionAttribute(string description) : base(description)
        {
        }

        /// <summary>
        ///     Retrieves the description text.
        /// </summary>
        /// <returns>
        ///     description
        /// </returns>
        public override string Description
        {
            get
            {
                if (!_replaced)
                {
                    _replaced = true;
                    DescriptionValue = SR.GetString(base.Description);
                }
                return base.Description;
            }
        }
    }

    [AttributeUsage(AttributeTargets.All)]
    internal sealed class SRCategoryAttribute : CategoryAttribute
    {
        public SRCategoryAttribute(string category) : base(category)
        {
        }

        protected override string GetLocalizedString(string value)
        {
            return SR.GetString(value);
        }
    }

    /// <summary>
    ///    AutoGenerated resource class. Usage:
    ///
    ///        string s = SR.GetString(SR.MyIdenfitier);
    /// </summary>

    internal sealed class SR
    {
        internal const string ClassDocComment = "ClassDocComment";
        internal const string ClassComments1 = "ClassComments1";
        internal const string ClassComments3 = "ClassComments3";
        internal const string StringPropertyComment = "StringPropertyComment";
        internal const string StringPropertyTruncatedComment = "StringPropertyTruncatedComment";
        internal const string NonStringPropertyComment = "NonStringPropertyComment";
        internal const string NonStringPropertyDetailedComment = "NonStringPropertyDetailedComment";
        internal const string CulturePropertyComment1 = "CulturePropertyComment1";
        internal const string CulturePropertyComment2 = "CulturePropertyComment2";
        internal const string ResMgrPropertyComment = "ResMgrPropertyComment";
        internal const string MismatchedResourceName = "MismatchedResourceName";
        internal const string InvalidIdentifier = "InvalidIdentifier";

        private static SR s_loader = null;
        private MainAssemblyFallbackResourceManager _resources;

        /// <summary>
        /// The containing assembly is set to lookup resources for the neutral language in satellite assemblies, not in the main assembly.
        /// System.Design resources are not meant to be translated, so the ResourceManager should not look for satellite assemblies.
        /// This ResourceManager forces resource lookup to be constrained to the current assembly and not look for satellites.
        /// </summary>
        private class MainAssemblyFallbackResourceManager : ResourceManager
        {
            public MainAssemblyFallbackResourceManager(string baseName, Assembly assembly) : base(baseName, assembly)
            {
                this.FallbackLocation = UltimateResourceFallbackLocation.MainAssembly;
            }
        }

        internal SR()
        {
            _resources = new MainAssemblyFallbackResourceManager("System.Design", this.GetType().Assembly);
        }

        private static SR GetLoader()
        {
            if (s_loader == null)
            {
                SR sr = new SR();
                Interlocked.CompareExchange(ref s_loader, sr, null);
            }
            return s_loader;
        }

        private static CultureInfo Culture
        {
            get { return null/*use ResourceManager default, CultureInfo.CurrentUICulture*/; }
        }

        public static ResourceManager Resources
        {
            get
            {
                return GetLoader()._resources;
            }
        }

        public static string GetString(string name, params object[] args)
        {
            SR sys = GetLoader();
            if (sys == null)
                return null;
            string res = sys._resources.GetString(name, SR.Culture);

            if (args != null && args.Length > 0)
            {
                for (int i = 0; i < args.Length; i++)
                {
                    String value = args[i] as String;
                    if (value != null && value.Length > 1024)
                    {
                        args[i] = value.Substring(0, 1024 - 3) + "...";
                    }
                }
                return String.Format(CultureInfo.CurrentCulture, res, args);
            }
            else
            {
                return res;
            }
        }

        public static string GetString(string name)
        {
            SR sys = GetLoader();
            if (sys == null)
                return null;
            return sys._resources.GetString(name, SR.Culture);
        }

        public static string GetString(string name, out bool usedFallback)
        {
            // always false for this version of gensr
            usedFallback = false;
            return GetString(name);
        }

        public static object GetObject(string name)
        {
            SR sys = GetLoader();
            if (sys == null)
                return null;
            return sys._resources.GetObject(name, SR.Culture);
        }
    }
}


text:
from healthvaultlib.utils.xmlutils import XmlUtils

class UpdatedRecord:
    '''
        Attributes:
            record_id   Record id
            update_date Date in which the record was last updated
    '''

    def __init__(self, xml=None):
        self.record_id = None
        self.update_date = None

        if xml is not None:
            self.parse_xml(xml)

    def parse_xml(self, xml):
        xmlutils = XmlUtils(xml)
        self.record_id = xmlutils.get_string_by_xpath('record-id')
        self.update_date = xmlutils.get_datetime('update-date')


text:
*> \brief \b ZLA_LIN_BERR computes a component-wise relative backward error.
*
*  =========== DOCUMENTATION ===========
*
* Online html documentation available at
*            http://www.netlib.org/lapack/explore-html/
*
*> \htmlonly
*> Download ZLA_LIN_BERR + dependencies
*>
*> [TGZ]
*>
*> [ZIP]
*>
*> [TXT]
*> \endhtmlonly
*
*  Definition:
*  ===========
*
*       SUBROUTINE ZLA_LIN_BERR ( N, NZ, NRHS, RES, AYB, BERR )
*
*       .. Scalar Arguments ..
*       INTEGER            N, NZ, NRHS
*       ..
*       .. Array Arguments ..
*       DOUBLE PRECISION   AYB( N, NRHS ), BERR( NRHS )
*       COMPLEX*16         RES( N, NRHS )
*       ..
*
*
*> \par Purpose:
*  =============
*>
*> \verbatim
*>
*>    ZLA_LIN_BERR computes componentwise relative backward error from
*>    the formula
*>        max(i) ( abs(R(i)) / ( abs(op(A_s))*abs(Y) + abs(B_s) )(i) )
*>    where abs(Z) is the componentwise absolute value of the matrix
*>    or vector Z.
*> \endverbatim
*
*  Arguments:
*  ==========
*
*> \param[in] N
*> \verbatim
*>          N is INTEGER
*>     The number of linear equations, i.e., the order of the
*>     matrix A.  N >= 0.
*> \endverbatim
*>
*> \param[in] NZ
*> \verbatim
*>          NZ is INTEGER
*>     We add (NZ+1)*SLAMCH( 'Safe minimum' ) to R(i) in the numerator to
*>     guard against spuriously zero residuals. Default value is N.
*> \endverbatim
*>
*> \param[in] NRHS
*> \verbatim
*>          NRHS is INTEGER
*>     The number of right hand sides, i.e., the number of columns
*>     of the matrices AYB, RES, and BERR.  NRHS >= 0.
*> \endverbatim
*>
*> \param[in] RES
*> \verbatim
*>          RES is DOUBLE PRECISION array, dimension (N,NRHS)
*>     The residual matrix, i.e., the matrix R in the relative backward
*>     error formula above.
*> \endverbatim
*>
*> \param[in] AYB
*> \verbatim
*>          AYB is DOUBLE PRECISION array, dimension (N, NRHS)
*>     The denominator in the relative backward error formula above, i.e.,
*>     the matrix abs(op(A_s))*abs(Y) + abs(B_s). The matrices A, Y, and B
*>     are from iterative refinement (see zla_gerfsx_extended.f).
*> \endverbatim
*>
*> \param[out] BERR
*> \verbatim
*>          BERR is COMPLEX*16 array, dimension (NRHS)
*>     The componentwise relative backward error from the formula above.
*> \endverbatim
*
*  Authors:
*  ========
*
*> \author Univ. of Tennessee
*> \author Univ. of California Berkeley
*> \author Univ. of Colorado Denver
*> \author NAG Ltd.
*
*> \date September 2012
*
*> \ingroup complex16OTHERcomputational
*
*  =====================================================================
      SUBROUTINE ZLA_LIN_BERR ( N, NZ, NRHS, RES, AYB, BERR )
*
*  -- LAPACK computational routine (version 3.4.2) --
*  -- LAPACK is a software package provided by Univ. of Tennessee,    --
*  -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..--
*     September 2012
*
*     .. Scalar Arguments ..
      INTEGER            N, NZ, NRHS
*     ..
*     .. Array Arguments ..
      DOUBLE PRECISION   AYB( N, NRHS ), BERR( NRHS )
      COMPLEX*16         RES( N, NRHS )
*     ..
*
*  =====================================================================
*
*     .. Local Scalars ..
      DOUBLE PRECISION   TMP
      INTEGER            I, J
      COMPLEX*16         CDUM
*     ..
*     .. Intrinsic Functions ..
      INTRINSIC          ABS, REAL, DIMAG, MAX
*     ..
*     .. External Functions ..
      EXTERNAL           DLAMCH
      DOUBLE PRECISION   DLAMCH
      DOUBLE PRECISION   SAFE1
*     ..
*     .. Statement Functions ..
      COMPLEX*16         CABS1
*     ..
*     .. Statement Function Definitions ..
      CABS1( CDUM ) = ABS( DBLE( CDUM ) ) + ABS( DIMAG( CDUM ) )
*     ..
*     .. Executable Statements ..
*
*     Adding SAFE1 to the numerator guards against spuriously zero
*     residuals.  A similar safeguard is in the CLA_yyAMV routine used
*     to compute AYB.
*
      SAFE1 = DLAMCH( 'Safe minimum' )
      SAFE1 = (NZ+1)*SAFE1

      DO J = 1, NRHS
         BERR(J) = 0.0D+0
         DO I = 1, N
            IF (AYB(I,J) .NE. 0.0D+0) THEN
               TMP = (SAFE1 + CABS1(RES(I,J)))/AYB(I,J)
               BERR(J) = MAX( BERR(J), TMP )
            END IF
*
*     If AYB is exactly 0.0 (and if computed by CLA_yyAMV), then we know
*     the true residual also must be exactly 0.0.
*
         END DO
      END DO
      END


text:
layout: post
title: "Misty Step"
date: 2017-3-22
source: PHB.260
tags: [druid (coast), paladin (ancients), paladin (vengeance), sorcerer, warlock, wizard, level2, conjuration]
categories:
- spells
---

**2nd-level conjuration**

**Casting Time**: 1 bonus action

**Range**: Self

**Components**: V

**Duration**: Instantaneous

Briefly surrounded by silvery mist, you teleport up to 30 feet to an unoccupied space that you can see.


text:
/*
* Author: Maire Kehoe (mkehoe@ie.ibm.com)
* Date: 17 Apr 2015
* DataService.java
* Was a subpart of BluemixContext.java
* with Author: Tony McGuckin (tony.mcguckin@ie.ibm.com)
* and Date: 09 Apr 2015 (or earlier)
*
*/
package com.ibm.xsp.bluemix.util.context;

import java.util.Vector;

import com.ibm.commons.util.PathUtil;
import com.ibm.commons.util.io.json.JsonJavaObject;

public class DataService{
	private static final String _NAME_KEY = "name"; // $NON-NLS-1$
	private static final String _LABEL_KEY = "label"; // $NON-NLS-1$
	private static final String _PLAN_KEY = "plan"; // $NON-NLS-1$
	private static final String _APPPATH_KEY = "apppath"; // $NON-NLS-1$
	private static final String _USERNAME_KEY = "username"; // $NON-NLS-1$
	private static final String _PASSWORD_KEY = "password"; // $NON-NLS-1$
	private static final String _SERVERNAME_KEY = "servername"; // $NON-NLS-1$
	private static final String _HOST_KEY = "host"; // $NON-NLS-1$
	private static final String _ROOTDIR_KEY = "rootdir"; // $NON-NLS-1$

	private String _NAME;
	private String _LABEL;
	private String _PLAN;
	private String _APPPATH;
	private String _USERNAME;
	private String _PASSWORD;
	private String _SERVERNAME;
	private String _HOST;
	private String _ROOTDIR;
	private JsonJavaObject instanceData;
	private JsonJavaObject credentialsData;

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

	/*package-private*/ DataService(JsonJavaObject instanceData) {
		this.instanceData = instanceData;
		if (null != instanceData) {
			_NAME = instanceData.getAsString(_NAME_KEY);
			_LABEL = instanceData.getAsString(_LABEL_KEY);
			_PLAN = instanceData.getAsString(_PLAN_KEY);
			credentialsData = instanceData.getAsObject("credentials"); // $NON-NLS-1$
			if (null != credentialsData) {
				_APPPATH = credentialsData.getAsString(_APPPATH_KEY);
				_USERNAME = credentialsData.getAsString(_USERNAME_KEY);
				_PASSWORD = credentialsData.getAsString(_PASSWORD_KEY);
				_SERVERNAME = credentialsData.getAsString(_SERVERNAME_KEY);
				_HOST = credentialsData.getAsString(_HOST_KEY);
				_ROOTDIR = credentialsData.getAsString(_ROOTDIR_KEY);
			}
		}
	}

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

	public String getName() {
		return _NAME;
	}

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

	public String getLabel() {
		return _LABEL;
	}

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

	public String getPlan() {
		return _PLAN;
	}

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

	public String getAppPath() {
		return _APPPATH;
	}

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

	public String getUserName() {
		return _USERNAME;
	}

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

	public String getPassword() {
		return _PASSWORD;
	}

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

	public String getServerName() {
		return _SERVERNAME;
	}
	// ------------------------------------------------
	public String getHost(){
		return _HOST;
	}

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

	public String getRootDir() {
		return _ROOTDIR;
	}

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

	public String findDatabaseName(){
		return getHost()+"!!"+getAppPath();
	}
	public String findDatabaseByName(String dbPath){
		String path1 = getHost()+"!!"+getRootDir();
		String concatPath = PathUtil.concat(path1, dbPath, '/');
		return concatPath;
	}
	public Vector<String> atDbName(){
		Vector<String> v = new Vector<String>();
		v.add(getHost());
		v.add(getAppPath());
		return v;
	}
	public Vector<String> atDbByName(String dbPath){
		String path1 = getRootDir();
		String concatPath = PathUtil.concat(path1, dbPath, '/');

		Vector<String> v = new Vector<String>();
		v.add(getHost());
		v.add(concatPath);
		return v;
	}

	public String getValue(String name){
		return instanceData.getAsString(name);
	}
	public String getCredentialsValue(String name){
		// note, would throw a NPE if null credentialsData
		// but the XPagesData service doesn't return null credentials.
		return credentialsData.getAsString(name);
	}
}


text:
@interface ViewController ()

@property (weak, nonatomic) IBOutlet UICurveSlider *curveSlider;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    [self.curveSlider addTarget:self action:@selector(updateProgress:) forControlEvents:UIControlEventValueChanged];
    self.curveSlider.minimumValue = 0;
    self.curveSlider.maximumValue = 100;
    self.curveSlider.continuous = NO;
    self.curveSlider.maximumTrackTintColor = [UIColor greenColor];
    self.curveSlider.sliderCenter = CGPointMake(140, 140);
    self.curveSlider.sliderRadius = 120;
    self.curveSlider.startAngel = M_PI_4*5;
    self.curveSlider.endAngel = M_PI_4*7;
    self.curveSlider.clockwise = YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)updateProgress:(UICurveSlider *)sender
{
    NSLog(@"value:%.2f", sender.value);
}

@end


text:
#include "test.h"

/*
Execute the following command to rebuild the data for this program:
   tail -n +32 test_read_format_cpio_svr4_gzip_rpm.c | /bin/sh

F=test_read_format_cpio_svr4_gzip_rpm.rpm
NAME=rpmsample
TMPRPM=/tmp/rpm
rm -rf ${TMPRPM}
mkdir -p ${TMPRPM}/BUILD
mkdir -p ${TMPRPM}/RPMS
mkdir -p ${TMPRPM}/SOURCES
mkdir -p ${TMPRPM}/SPECS
mkdir -p ${TMPRPM}/SRPMS
echo "hello" > ${TMPRPM}/BUILD/file1
echo "hello" > ${TMPRPM}/BUILD/file2
echo "hello" > ${TMPRPM}/BUILD/file3
cat > ${TMPRPM}/SPECS/${NAME}.spec <<END
##
%define _topdir ${TMPRPM}
%define _binary_payload w9.gzdio

Summary: Sample data of RPM filter of libarchive
Name: ${NAME}
Version: 1.0.0
Release: 1
License: BSD
URL: http://code.google.com/p/libarchive
BuildArch: noarch
BuildRoot: %{_tmppath}/%{name}-%{version}-root

%install
rm -rf \$RPM_BUILD_ROOT

mkdir -p \$RPM_BUILD_ROOT%{_sysconfdir}
install -m 644 file1 \$RPM_BUILD_ROOT%{_sysconfdir}/file1
install -m 644 file2 \$RPM_BUILD_ROOT%{_sysconfdir}/file2
install -m 644 file3 \$RPM_BUILD_ROOT%{_sysconfdir}/file3
TZ=utc touch -afm -t 197001020000.01 \$RPM_BUILD_ROOT%{_sysconfdir}/file1
TZ=utc touch -afm -t 197001020000.01 \$RPM_BUILD_ROOT%{_sysconfdir}/file2
TZ=utc touch -afm -t 197001020000.01 \$RPM_BUILD_ROOT%{_sysconfdir}/file3

%files
%{_sysconfdir}/file1
%{_sysconfdir}/file2
%{_sysconfdir}/file3

%description
Sample data.
END
#
rpmbuild -bb ${TMPRPM}/SPECS/${NAME}.spec
uuencode ${F} < ${TMPRPM}/RPMS/noarch/${NAME}-1.0.0-1.noarch.rpm > ${F}.uu

rm -rf ${TMPRPM}
exit 1
*/

DEFINE_TEST(test_read_format_cpio_svr4_gzip_rpm)
{
	struct archive_entry *ae;
	struct archive *a;
	const char *name = "test_read_format_cpio_svr4_gzip_rpm.rpm";
	int r;

	assert((a = archive_read_new()) != NULL);
        r = archive_read_support_compression_gzip(a);
	if (r == ARCHIVE_WARN) {
		skipping("gzip reading not fully supported on this platform");
		assertEqualInt(ARCHIVE_OK, archive_read_finish(a));
		return;
        }
	assertEqualIntA(a, ARCHIVE_OK, r);
	assertEqualIntA(a, ARCHIVE_OK,
	    archive_read_support_compression_rpm(a));
	assertEqualIntA(a, ARCHIVE_OK, archive_read_support_format_all(a));
	extract_reference_file(name);
	assertEqualIntA(a, ARCHIVE_OK, archive_read_open_filename(a, name, 2));

	assertEqualIntA(a, ARCHIVE_OK, archive_read_next_header(a, &ae));
	assertEqualString("./etc/file1", archive_entry_pathname(ae));
	assertEqualInt(86401, archive_entry_mtime(ae));
	assertEqualIntA(a, ARCHIVE_OK, archive_read_next_header(a, &ae));
	assertEqualString("./etc/file2", archive_entry_pathname(ae));
	assertEqualInt(86401, archive_entry_mtime(ae));
	assertEqualIntA(a, ARCHIVE_OK, archive_read_next_header(a, &ae));
	assertEqualString("./etc/file3", archive_entry_pathname(ae));
	assertEqualInt(86401, archive_entry_mtime(ae));

	/* Verify the end-of-archive. */
	assertEqualIntA(a, ARCHIVE_EOF, archive_read_next_header(a, &ae));

	/* Verify that the format detection worked. */
	assertEqualInt(archive_compression(a), ARCHIVE_COMPRESSION_GZIP);
	assertEqualString(archive_compression_name(a), "gzip");
	assertEqualInt(archive_format(a), ARCHIVE_FORMAT_CPIO_SVR4_NOCRC);

	assertEqualInt(ARCHIVE_OK, archive_read_close(a));
	assertEqualInt(ARCHIVE_OK, archive_read_finish(a));
}


text:
package org.terracotta.config.data_roots.management;

import org.terracotta.management.service.monitoring.registry.provider.AliasBinding;

import java.nio.file.Path;

public class DataRootBinding extends AliasBinding {

  public DataRootBinding(String identifier, Path path) {
    super(identifier, path);
  }

  @Override
  public Path getValue() {
    return (Path) super.getValue();
  }

}


text:
import extractCanonicalDepsFromFile from './extractCanonicalDepsFromFile';
import getCanonicalIds from './getCanonicalIds';
import Rx from 'rx';
import depres from 'depres/dist/depres';

function expandNestedDeps(rootId, visitedCache, stack) {
    stack = stack || [];
    visitedCache = visitedCache || {};

    if (rootId in visitedCache) {
        var priorReference = stack.indexOf(rootId);
        if (priorReference !== -1)
            throw new Error('Circular reference detected:\n    ' + stack.slice(priorReference).concat([rootId]).map(s => '  ' + s).join('\n -->'));
        return Rx.Observable.empty();
    }

    visitedCache[rootId] = true;

    var obsDeps = extractCanonicalDepsFromFile(rootId);
    stack = stack.concat(rootId);

    var rootEntry = obsDeps
        .toArray()
        .map(deps => ({
            id: rootId,
            deps
        }));

    var depEntries = obsDeps
        .flatMap(
            depId => expandNestedDeps(depId, visitedCache, stack)
        );

    return rootEntry
        .concat(depEntries);
}

export
default

function resolveDeps(entryPointIds) {
    if (typeof entryPointIds !== 'object' || !('length' in entryPointIds))
        entryPointIds = [entryPointIds];

    var visitedCache = {};

    return Rx.Observable.create(observer => {
        var depMap = {};
        return getCanonicalIds(entryPointIds)
            .concatMap(id => expandNestedDeps(id, visitedCache))
            //.distinct(entry => entry.id)
            .forEach(entry => {
                depMap[entry.id] = entry.deps;
            }, error => observer.onError(error), () => {
                observer.onNext(depMap);
                observer.completed();
            });
        })
    .map(depres.resolveMap)
    .map(result => result.resolved)
    .flatMap(Rx.Observable.from);

    //return Promise.resolve(null);
}


text:
angular.module('app').controller('ArtistListController',
    ['$scope', '$log', 'localStorageService', 'ArtistService',
    function($scope, $log, localStorageService, ArtistService){

        $scope.deleteArtist = function(artist){
            for(i = 0; i < $scope.artists.length; i++){
                if($scope.artists[i] === artist){
                    $scope.artists.splice(i, 1);
                }
            }
        };

        $scope.resetArtists = function(){
            $scope.artists = ArtistService.GetArtists().then(function(data){
                    $scope.artists = data;
                }).reject(function(error){
                    $log.error(error);
                });
        };

        //the artists either are the ones in the store or go get them
        //from the service
        var artistsInStore = localStorageService.get('artists');
        $scope.artists = artistsInStore || ArtistService.GetArtists().then(function(data){
                $scope.artists = data;
            }).reject(function(error){
                $log.error(error);
            });

        //sets a watch on that store binding the $scope.artists to
        //the store 'artists'
        $scope.$watch('artists', function () {
            localStorageService.set('artists', $scope.artists);
        }, true);

}]);


text:
#region Imports

using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
#endregion

namespace P3Net.Kraken.Web.UI
{
	/// A <see cref="Button"/> that displays a client-side confirmation message.
	/// <preliminary/>
	/// <remarks>
	/// At this time the <see cref="Button.OnClientClick">OnClientClick</see> property is ignored.
	/// <para/>
	/// The ConfirmButton available in the AJAX Toolkit provides more advanced functionality.  Use
	/// that control instead when using AJAX in a site.
	/// </remarks>
	[CodeNotAnalyzed]
	[CodeNotTested]
	[ToolboxData("<{0}:ConfirmButton runat=\"server\"></{0}:ConfirmButton>")]
	public class ConfirmButton : Button
	{
		#region Public Members

		#region Attributes

		/// Gets or sets the confirmation message to display when the button is clicked.
		[Category("Appearance")]
		[Description("The message to display prior to posting back.")]
		[DefaultValue("Are you sure?")]
		public string ConfirmMessage
		{
			[DebuggerStepThrough]
			get
			{
				object obj = ViewState["ConfirmMessage"];
				return (obj != null) ? (string)obj : "Are you sure?";
			}

			[DebuggerStepThrough]
			set
			{
				value = (value != null) ? value.Trim() : "";
				if (value.Length > 0)
					ViewState["ConfirmMessage"] = value;
				else
					ViewState.Remove("ConfirmMessage");
			}
		}
		#endregion

		#endregion  //Public Members

		#region Protected Members

		#region Methods

		/// Prepares the control for rendering.
		/// <param name="e">The event arguments.</param>
		protected override void OnPreRender ( EventArgs e )
		{
			base.OnPreRender(e);

			//Add the confirmation attribute
			if ((ConfirmMessage.Length > 0) && (Page != null) && Visible)
				Attributes.Add("onclick", "return confirm('" + Page.Server.HtmlEncode(ConfirmMessage) + "');");
		}
		#endregion

		#endregion //Protected Members
	}
}


text:
import Ember from 'ember';

export function number(params) {
  var value, unit, decimals;

  value = params[0];
  unit = params[1] || '';
  decimals = typeof params[2] === 'number' ? params[2] : 2;

  if (!value) {
  	return '–';
  }

  return (Math.round(value * 100) / 100).toLocaleString('en', {
    minimumFractionDigits: decimals,
    maximumFractionDigits: decimals
  }) + (unit ? ' ' + unit : '');
}

export default Ember.HTMLBars.makeBoundHelper(number);


text:
package org.apache.helix;

import java.util.Map;
import java.util.concurrent.CountDownLatch;

import org.I0Itec.zkclient.IZkStateListener;
import org.I0Itec.zkclient.ZkConnection;
import org.apache.helix.InstanceType;
import org.apache.helix.ZNRecord;
import org.apache.helix.PropertyKey.Builder;
import org.apache.helix.manager.zk.ZKHelixDataAccessor;
import org.apache.helix.manager.zk.ZKHelixManager;
import org.apache.helix.manager.zk.ZkBaseDataAccessor;
import org.apache.helix.manager.zk.ZkClient;
import org.apache.helix.model.ExternalView;
import org.apache.log4j.Logger;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.ZooKeeper.States;

public class ZkTestHelper
{
  private static Logger LOG = Logger.getLogger(ZkTestHelper.class);

  static
  {
    // Logger.getRootLogger().setLevel(Level.DEBUG);
  }

  // zkClusterManager that exposes zkclient
  public static class TestZkHelixManager extends ZKHelixManager
  {

    public TestZkHelixManager(String clusterName,
                              String instanceName,
                              InstanceType instanceType,
                              String zkConnectString) throws Exception
    {
      super(clusterName, instanceName, instanceType, zkConnectString);
      // TODO Auto-generated constructor stub
    }

    public ZkClient getZkClient()
    {
      return _zkClient;
    }

  }

  public static void expireSession(final ZkClient zkClient) throws Exception
  {
    final CountDownLatch waitExpire = new CountDownLatch(1);

    IZkStateListener listener = new IZkStateListener()
    {
      @Override
      public void handleStateChanged(KeeperState state) throws Exception
      {
        // System.err.println("handleStateChanged. state: " + state);
      }

      @Override
      public void handleNewSession() throws Exception
      {
        // make sure zkclient is connected again
        zkClient.waitUntilConnected();

        ZkConnection connection = ((ZkConnection) zkClient.getConnection());
        ZooKeeper curZookeeper = connection.getZookeeper();

        LOG.info("handleNewSession. sessionId: "
            + Long.toHexString(curZookeeper.getSessionId()));
        waitExpire.countDown();
      }
    };

    zkClient.subscribeStateChanges(listener);

    ZkConnection connection = ((ZkConnection) zkClient.getConnection());
    ZooKeeper curZookeeper = connection.getZookeeper();
    LOG.info("Before expiry. sessionId: " + Long.toHexString(curZookeeper.getSessionId()));

    Watcher watcher = new Watcher()
    {
      @Override
      public void process(WatchedEvent event)
      {
        LOG.info("Process watchEvent: " + event);
      }
    };

    final ZooKeeper dupZookeeper =
        new ZooKeeper(connection.getServers(),
                      curZookeeper.getSessionTimeout(),
                      watcher,
                      curZookeeper.getSessionId(),
                      curZookeeper.getSessionPasswd());
    // wait until connected, then close
    while (dupZookeeper.getState() != States.CONNECTED)
    {
      Thread.sleep(10);
    }
    dupZookeeper.close();

    // make sure session expiry really happens
    waitExpire.await();
    zkClient.unsubscribeStateChanges(listener);

    connection = (ZkConnection) zkClient.getConnection();
    curZookeeper = connection.getZookeeper();

    // System.err.println("zk: " + oldZookeeper);
    LOG.info("After expiry. sessionId: " + Long.toHexString(curZookeeper.getSessionId()));
  }

  /*
   * stateMap: partition->instance->state
   */
  public static boolean verifyState(ZkClient zkclient,
                                    String clusterName,
                                    String resourceName,
                                    Map<String, Map<String, String>> expectStateMap,
                                    String op)
  {
    boolean result = true;
    ZkBaseDataAccessor<ZNRecord> baseAccessor =
        new ZkBaseDataAccessor<ZNRecord>(zkclient);
    ZKHelixDataAccessor accessor = new ZKHelixDataAccessor(clusterName, baseAccessor);
    Builder keyBuilder = accessor.keyBuilder();

    ExternalView extView = accessor.getProperty(keyBuilder.externalView(resourceName));
    Map<String, Map<String, String>> actualStateMap = extView.getRecord().getMapFields();
    for (String partition : actualStateMap.keySet())
    {
      for (String expectPartiton : expectStateMap.keySet())
      {
        if (!partition.matches(expectPartiton))
        {
          continue;
        }

        Map<String, String> actualInstanceStateMap = actualStateMap.get(partition);
        Map<String, String> expectInstanceStateMap = expectStateMap.get(expectPartiton);
        for (String instance : actualInstanceStateMap.keySet())
        {
          for (String expectInstance : expectStateMap.get(expectPartiton).keySet())
          {
            if (!instance.matches(expectInstance))
            {
              continue;
            }

            String actualState = actualInstanceStateMap.get(instance);
            String expectState = expectInstanceStateMap.get(expectInstance);
            boolean equals = expectState.equals(actualState);
            if (op.equals("==") && !equals || op.equals("!=") && equals)
            {
              System.out.println(partition + "/" + instance
                  + " state mismatch. actual state: " + actualState + ", but expect: "
                  + expectState + ", op: " + op);
              result = false;
            }

          }
        }

      }
    }
    return result;
  }

}