text:
<?xml version="1.0" encoding="latin1" ?>
<!DOCTYPE chapter SYSTEM "chapter.dtd">

<chapter>

    <copyright>
      <year>2001</year><year>2011</year>
      <holder>Ericsson AB. All Rights Reserved.</holder>
    </copyright>
    <legalnotice>
      The contents of this file are subject to the Erlang Public License,
      Version 1.1, (the "License"); you may not use this file except in
      compliance with the License. You should have received a copy of the
      Erlang Public License along with this software. If not, it can be
      retrieved online at http://www.erlang.org/.

      Software distributed under the License is distributed on an "AS IS"
      basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
      the License for the specific language governing rights and limitations
      under the License.

    </legalnotice>

    <title>Common Caveats</title>
    <prepared>Bjorn Gustavsson</prepared>
    <docno></docno>
    <date>2001-08-08</date>
    <rev></rev>
    <file>commoncaveats.xml</file>

Here we list a few modules and BIFs to watch out for, and not only
  from a performance point of view.

     <title>The timer module</title>

Creating timers using <seealso
     marker="erts:erlang#erlang:send_after/3">erlang:send_after/3</seealso>
     and <seealso marker="erts:erlang#erlang:start_timer/3">erlang:start_timer/3</seealso>
     is much more efficient than using the timers provided by the
     <seealso marker="stdlib:timer">timer</seealso> module. The
     <c>timer</c> module uses a separate process to manage the timers,
     and that process can easily become overloaded if many processes
     create and cancel timers frequently (especially when using the
     SMP emulator).

The functions in the <c>timer</c> module that do not manage timers (such as
     <c>timer:tc/3</c> or <c>timer:sleep/1</c>), do not call the timer-server process
     and are therefore harmless.

    <title>list_to_atom/1</title>

Atoms are not garbage-collected. Once an atom is created, it will never
    be removed. The emulator will terminate if the limit for the number
    of atoms (1048576 by default) is reached.

Therefore, converting arbitrary input strings to atoms could be
    dangerous in a system that will run continuously.
    If only certain well-defined atoms are allowed as input, you can use
    <seealso marker="erts:erlang#list_to_existing_atom/1">list_to_existing_atom/1</seealso>
    to guard against a denial-of-service attack. (All atoms that are allowed
    must have been created earlier, for instance by simply using all of them
    in a module and loading that module.)

Using <c>list_to_atom/1</c> to construct an atom that is passed to
    <c>apply/3</c> like this

apply(list_to_atom("some_prefix"++Var), foo, Args)

is quite expensive and is not recommended in time-critical code.

    <title>length/1</title>

The time for calculating the length of a list is proportional to the
    length of the list, as opposed to <c>tuple_size/1</c>, <c>byte_size/1</c>,
    and <c>bit_size/1</c>, which all execute in constant time.

Normally you don't have to worry about the speed of <c>length/1</c>,
    because it is efficiently implemented in C. In time critical-code, though,
    you might want to avoid it if the input list could potentially be very long.

Some uses of <c>length/1</c> can be replaced by matching.
    For instance, this code

foo(L) when length(L) >= 3 ->
    ...

can be rewritten to

foo([_,_,_|_]=L) ->
   ...

(One slight difference is that <c>length(L)</c> will fail if the <c>L</c>
   is an improper list, while the pattern in the second code fragment will
   accept an improper list.)

    <title>setelement/3</title>

<seealso marker="erts:erlang#setelement/3">setelement/3</seealso>
    copies the tuple it modifies. Therefore, updating a tuple in a loop
    using <c>setelement/3</c> will create a new copy of the tuple every time.

There is one exception to the rule that the tuple is copied.
    If the compiler clearly can see that destructively updating the tuple would
    give exactly the same result as if the tuple was copied, the call to
    <c>setelement/3</c> will be replaced with a special destructive setelement
    instruction. In the following code sequence

multiple_setelement(T0) ->
    T1 = setelement(9, T0, bar),
    T2 = setelement(7, T1, foobar),
    setelement(5, T2, new_value).

the first <c>setelement/3</c> call will copy the tuple and modify the
    ninth element. The two following <c>setelement/3</c> calls will modify
    the tuple in place.

For the optimization to be applied, all of the followings conditions
    must be true:

    <list type="bulleted">
    <item>The indices must be integer literals, not variables or expressions.</item>
    <item>The indices must be given in descending order.</item>
    <item>There must be no calls to other function in between the calls to
    <c>setelement/3</c>.</item>
    <item>The tuple returned from one <c>setelement/3</c> call must only be used
    in the subsequent call to <c>setelement/3</c>.</item>
    </list>

If it is not possible to structure the code as in the <c>multiple_setelement/1</c>
    example, the best way to modify multiple elements in a large tuple is to
    convert the tuple to a list, modify the list, and convert the list back to
    a tuple.

    <title>size/1</title>

<c>size/1</c> returns the size for both tuples and binary.

Using the new BIFs <c>tuple_size/1</c> and <c>byte_size/1</c> introduced
    in R12B gives the compiler and run-time system more opportunities for
    optimization. A further advantage is that the new BIFs could help Dialyzer
    find more bugs in your program.

    <title>split_binary/2</title>

It is usually more efficient to split a binary using matching
      instead of calling the <c>split_binary/2</c> function.
      Furthermore, mixing bit syntax matching and <c>split_binary/2</c>
      may prevent some optimizations of bit syntax matching.

DO

        <![CDATA[
        <<Bin1:Num/binary,Bin2/binary>> = Bin,]]>

DO NOT

        {Bin1,Bin2} = split_binary(Bin, Num)

    <title>The '--' operator</title>

Note that the '<c>--</c>' operator has a complexity
     proportional to the product of the length of its operands,
     meaning that it will be very slow if both of its operands
     are long lists:

DO NOT

        <![CDATA[
        HugeList1 -- HugeList2]]>

Instead use the <seealso marker="stdlib:ordsets">ordsets</seealso>
     module:

DO

        HugeSet1 = ordsets:from_list(HugeList1),
        HugeSet2 = ordsets:from_list(HugeList2),
        ordsets:subtract(HugeSet1, HugeSet2)

Obviously, that code will not work if the original order
     of the list is important. If the order of the list must be
     preserved, do like this:

DO

        <![CDATA[
        Set = gb_sets:from_list(HugeList2),
        [E || E <- HugeList1, not gb_sets:is_element(E, Set)]]]>

Subtle note 1: This code behaves differently from '<c>--</c>'
     if the lists contain duplicate elements. (One occurrence
     of an element in HugeList2 will remove all
     occurrences in HugeList1.)

Subtle note 2: This code compares lists elements using the
     '<c>==</c>' operator, while '<c>--</c>' uses the '<c>=:=</c>'. If
     that difference is important, <c>sets</c> can be used instead of
     <c>gb_sets</c>, but note that <c>sets:from_list/1</c> is much
     slower than <c>gb_sets:from_list/1</c> for long lists.

Using the '<c>--</c>' operator to delete an element
     from a list is not a performance problem:

OK

        HugeList1 -- [Element]

</chapter>


text:
module SagepayServer
	class Payment < Interface

		attr_accessor :amount, :currency, :description, :notification_url, :profile,
									:billing_address, :delivery_address, :customer_email,
									:basket, :allow_gift_aid, :apply_avs_cv2, :apply_3d_secure, :billing_agreement

		validates :amount, :currency, :description, :notification_url, :billing_address, :delivery_address, :presence => true

		def run_payment!
			handle_response(run_post)
		end

		def url
      case mode
      when :simulator
        "https://test.sagepay.com/simulator/VSPServerGateway.asp?Service=VendorRegisterTx"
      when :test
        "https://test.sagepay.com/gateway/service/vspserver-register.vsp"
      when :live
        "https://live.sagepay.com/gateway/service/vspserver-register.vsp"
      end
    end

		def post_params
			params = super.merge({
				"Amount" => ("%.2f" % amount),
	      "Currency" => currency,
	      "Description" => description,
	      "NotificationURL" => notification_url,
	      "BillingSurname" => billing_address.surname,
	      "BillingFirstnames" => billing_address.first_names,
	      "BillingAddress1" => billing_address.address_1,
	      "BillingCity" => billing_address.city,
	      "BillingPostCode" => billing_address.postcode,
	      "BillingCountry" => billing_address.country,
	      "DeliverySurname" => delivery_address.surname,
	      "DeliveryFirstnames" => delivery_address.first_names,
	      "DeliveryAddress1" => delivery_address.address_1,
	      "DeliveryCity" => delivery_address.city,
	      "DeliveryPostCode" => delivery_address.postcode,
	      "DeliveryCountry" => delivery_address.country
			})

			# Optional parameters
	    params['BillingAddress2'] = billing_address.address_2 if billing_address.address_2.present?
	    params['BillingState'] = billing_address.state if billing_address.state.present?
	    params['BillingPhone'] = billing_address.phone if billing_address.phone.present?

	    params['DeliveryAddress2'] = delivery_address.address_2 if delivery_address.address_2.present?
	    params['DeliveryState'] = delivery_address.state if delivery_address.state.present?
	    params['DeliveryPhone'] = delivery_address.phone if delivery_address.phone.present?

	    params['CustomerEmail'] = customer_email if customer_email.present?

	    params['Basket'] = basket if basket.present?
	    params['AllowGiftAid'] = allow_gift_aid ? "1" : "0" if allow_gift_aid.present? || allow_gift_aid == false
	    params['ApplyAVSCV2'] = apply_avs_cv2.to_s if apply_avs_cv2.present?
	    params['Apply3DSecure'] = apply_3d_secure.to_s if apply_3d_secure.present?
	    params['Profile'] = profile.to_s.upcase if profile.present?
	    params['BillingAgreement'] = billing_agreement ? "1" : "0" if billing_agreement.present? || billing_agreement == false
	    #params['AccountType'] = account_type_param if account_type.present?

	    params
		end

private

		# Thanks to Mathie's SagePay gem for the help with this bit!
		# https://github.com/mathie/sage_pay/blob/master/lib/sage_pay/server/command.rb#L79
		def run_post
			parsed_uri = URI.parse(url)
      request = Net::HTTP::Post.new(parsed_uri.request_uri)
      request.form_data = post_params

      http = Net::HTTP.new(parsed_uri.host, parsed_uri.port)

      if parsed_uri.scheme == "https"
        http.use_ssl = true
        http.verify_mode = OpenSSL::SSL::VERIFY_PEER
        http.ca_file = '/etc/ssl/certs/ca-certificates.crt' if File.exists?('/etc/ssl/certs/ca-certificates.crt')
      end

      http.start { |http|
        http.request(request)
      }
		end

		def handle_response(response)
			case response.code.to_i
      when 200
        #response_from_response_body(response.body)
        Response.from_response_body(response.body)
      else
        raise RuntimeError, "Payment provider appears to be down. Please try again later."
      end
		end

	end
end

redpajama_set_name: RedPajamaGithub


text:
namespace grpc_core {

const char* kHierarchicalPathAttributeKey = "hierarchical_path";

namespace {

class HierarchicalPathAttribute : public ServerAddress::AttributeInterface {
 public:
  explicit HierarchicalPathAttribute(std::vector<std::string> path)
      : path_(std::move(path)) {}

  std::unique_ptr<AttributeInterface> Copy() const override {
    return std::make_unique<HierarchicalPathAttribute>(path_);
  }

  int Cmp(const AttributeInterface* other) const override {
    const std::vector<std::string>& other_path =
        static_cast<const HierarchicalPathAttribute*>(other)->path_;
    for (size_t i = 0; i < path_.size(); ++i) {
      if (other_path.size() == i) return 1;
      int r = path_[i].compare(other_path[i]);
      if (r != 0) return r;
    }
    if (other_path.size() > path_.size()) return -1;
    return 0;
  }

  std::string ToString() const override {
    return absl::StrCat("[", absl::StrJoin(path_, ", "), "]");
  }

  const std::vector<std::string>& path() const { return path_; }

 private:
  std::vector<std::string> path_;
};

}  // namespace

std::unique_ptr<ServerAddress::AttributeInterface>
MakeHierarchicalPathAttribute(std::vector<std::string> path) {
  return std::make_unique<HierarchicalPathAttribute>(std::move(path));
}

absl::StatusOr<HierarchicalAddressMap> MakeHierarchicalAddressMap(
    const absl::StatusOr<ServerAddressList>& addresses) {
  if (!addresses.ok()) return addresses.status();
  HierarchicalAddressMap result;
  for (const ServerAddress& address : *addresses) {
    const HierarchicalPathAttribute* path_attribute =
        static_cast<const HierarchicalPathAttribute*>(
            address.GetAttribute(kHierarchicalPathAttributeKey));
    if (path_attribute == nullptr) continue;
    const std::vector<std::string>& path = path_attribute->path();
    auto it = path.begin();
    ServerAddressList& target_list = result[*it];
    std::unique_ptr<HierarchicalPathAttribute> new_attribute;
    ++it;
    if (it != path.end()) {
      std::vector<std::string> remaining_path(it, path.end());
      new_attribute = std::make_unique<HierarchicalPathAttribute>(
          std::move(remaining_path));
    }
    target_list.emplace_back(address.WithAttribute(
        kHierarchicalPathAttributeKey, std::move(new_attribute)));
  }
  return result;
}

}  // namespace grpc_core


text:
@implementation LoadingCancelButton

- (id)init {
    self = [super init];
    if (self) {
        self.layer.cornerRadius = IWCancelButtonSize / 2.0f;
        self.layer.shadowColor = [UIColor redColor].CGColor;
        self.layer.shadowOpacity = 0.7f;
        self.layer.shadowRadius = 10.0f;
        self.backgroundColor = [UIColor redColor];

        [self setTitle:@"STOP" forState:UIControlStateNormal];
        [self setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [self setTitleColor:[UIColor redColor] forState:UIControlStateHighlighted];

        self.titleLabel.textAlignment = NSTextAlignmentCenter;
        self.titleLabel.font = [UIFont fontWithName:IWItalicFontName size:17];

    }
    return self;
}

- (void)setHighlighted:(BOOL)highlighted {
    [super setHighlighted:highlighted];
    if (highlighted) {
        [self setBackgroundColor:[UIColor whiteColor]];
    } else {
        [self setBackgroundColor:[UIColor redColor]];
    }
}

@end


text:
package com.google.android.accessibility.utils.traversal;

import androidx.core.view.accessibility.AccessibilityNodeInfoCompat;
import com.google.android.libraries.accessibility.utils.log.LogUtils;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.checkerframework.checker.nullness.qual.Nullable;

/** Tree that represents Accessibility node hierarchy. It lets reorder the structure of the tree. */
public class WorkingTree {

  private static final String TAG = "WorkingTree";

  private AccessibilityNodeInfoCompat mNode;
  private @Nullable WorkingTree mParent;
  private final List<WorkingTree> mChildren = new ArrayList<>();

  public WorkingTree(AccessibilityNodeInfoCompat node, @Nullable WorkingTree parent) {
    mNode = node;
    mParent = parent;
  }

  public AccessibilityNodeInfoCompat getNode() {
    return mNode;
  }

  public @Nullable WorkingTree getParent() {
    return mParent;
  }

  public void setParent(@Nullable WorkingTree parent) {
    mParent = parent;
  }

  public void addChild(WorkingTree node) {
    mChildren.add(node);
  }

  public boolean removeChild(WorkingTree child) {
    return mChildren.remove(child);
  }

  /** Checks whether subTree is a descendant of this WorkingTree node. */
  public boolean hasDescendant(@Nullable WorkingTree tree) {

    if (ancestorsHaveLoop()) {
      LogUtils.w(TAG, "Looped ancestors line");
      return false;
    }

    // For each ancestor of target descendant node...
    WorkingTree subTree = tree;
    while (subTree != null) {
      AccessibilityNodeInfoCompat node = subTree.getNode();

      // If ancestor is this working tree node... target is descendant of this node.
      if (mNode.equals(node)) {
        return true;
      }

      subTree = subTree.getParent();
    }

    return false;
  }

  /** Checks whether subTree is a descendant of this WorkingTree node. */
  public boolean ancestorsHaveLoop() {
    Set<AccessibilityNodeInfoCompat> visitedNodes = new HashSet<>();

    // For each ancestor node...
    for (WorkingTree workNode = this; workNode != null; workNode = workNode.getParent()) {
      AccessibilityNodeInfoCompat accessNode = workNode.getNode();
      if (visitedNodes.contains(accessNode)) {
        return true;
      }
      visitedNodes.add(accessNode);
    }
    return false;
  }

  public void swapChild(WorkingTree swappedChild, WorkingTree newChild) {
    int position = mChildren.indexOf(swappedChild);
    if (position < 0) {
      LogUtils.e(TAG, "WorkingTree IllegalStateException: swap child not found");
      return;
    }

    mChildren.set(position, newChild);
  }

  public @Nullable WorkingTree getNext() {
    if (!mChildren.isEmpty()) {
      return mChildren.get(0);
    }

    WorkingTree startNode = this;
    while (startNode != null) {
      WorkingTree nextSibling = startNode.getNextSibling();
      if (nextSibling != null) {
        return nextSibling;
      }

      startNode = startNode.getParent();
    }

    return null;
  }

  public @Nullable WorkingTree getNextSibling() {
    WorkingTree parent = getParent();
    if (parent == null) {
      return null;
    }

    int currentIndex = parent.mChildren.indexOf(this);
    if (currentIndex < 0) {
      LogUtils.e(TAG, "WorkingTree IllegalStateException: swap child not found");
      return null;
    }

    currentIndex++;

    if (currentIndex >= parent.mChildren.size()) {
      // it was last child
      return null;
    }

    return parent.mChildren.get(currentIndex);
  }

  public @Nullable WorkingTree getPrevious() {
    WorkingTree previousSibling = getPreviousSibling();
    if (previousSibling != null) {
      return previousSibling.getLastNode();
    }

    return getParent();
  }

  public @Nullable WorkingTree getPreviousSibling() {
    WorkingTree parent = getParent();
    if (parent == null) {
      return null;
    }

    int currentIndex = parent.mChildren.indexOf(this);
    if (currentIndex < 0) {
      LogUtils.e(TAG, "WorkingTree IllegalStateException: swap child not found");
      return null;
    }

    currentIndex--;

    if (currentIndex < 0) {
      // it was first child
      return null;
    }

    return parent.mChildren.get(currentIndex);
  }

  public WorkingTree getLastNode() {
    WorkingTree node = this;
    while (!node.mChildren.isEmpty()) {
      node = node.mChildren.get(node.mChildren.size() - 1);
    }

    return node;
  }

  public WorkingTree getRoot() {
    WorkingTree root = this;
    WorkingTree parent;
    while ((parent = root.getParent()) != null) {
      root = parent;
    }

    return root;
  }
}


text:
package me.vilsol.nmswrapper.wraps.unparsed;

import me.vilsol.nmswrapper.*;
import me.vilsol.nmswrapper.reflections.*;
import me.vilsol.nmswrapper.wraps.*;

@ReflectiveClass(name = "EntityArmorStand")
public class NMSEntityArmorStand extends NMSEntityLiving {

    public NMSEntityArmorStand(Object nmsObject){
        super(nmsObject);
    }

    public NMSEntityArmorStand(NMSWorld world){
        super("EntityArmorStand", new Object[]{NMSWorld.class}, new Object[]{world});
    }

    public NMSEntityArmorStand(NMSWorld world, double d, double d1, double d2){
        super("EntityArmorStand", new Object[]{NMSWorld.class, double.class, double.class, double.class}, new Object[]{world, d, d1, d2});
    }

    /**
     * TODO Find correct name
     * @see net.minecraft.server.v1_9_R1.EntityArmorStand#B()
     */
    @ReflectiveMethod(name = "B", types = {})
    public void B(){
        NMSWrapper.getInstance().exec(nmsObject);
    }

    /**
     * TODO Find correct name
     * @see net.minecraft.server.v1_9_R1.EntityArmorStand#G()
     */
    @ReflectiveMethod(name = "G", types = {})
    public void G(){
        NMSWrapper.getInstance().exec(nmsObject);
    }

    /**
     * TODO Find correct name
     * @see net.minecraft.server.v1_9_R1.EntityArmorStand#a(net.minecraft.server.v1_9_R1.EntityHuman, net.minecraft.server.v1_9_R1.Vec3D)
     */
    @ReflectiveMethod(name = "a", types = {NMSEntityHuman.class, NMSVec3D.class})
    public boolean a(NMSEntityHuman entityHuman, NMSVec3D vec3D){
        return (boolean) NMSWrapper.getInstance().exec(nmsObject, entityHuman, vec3D);
    }

    /**
     * TODO Find correct name
     * @see net.minecraft.server.v1_9_R1.EntityArmorStand#aW()
     */
    @ReflectiveMethod(name = "aW", types = {})
    public boolean aW(){
        return (boolean) NMSWrapper.getInstance().exec(nmsObject);
    }

    /**
     * TODO Find correct name
     * @see net.minecraft.server.v1_9_R1.EntityArmorStand#ad()
     */
    @ReflectiveMethod(name = "ad", types = {})
    public boolean ad(){
        return (boolean) NMSWrapper.getInstance().exec(nmsObject);
    }

    /**
     * TODO Find correct name
     * @see net.minecraft.server.v1_9_R1.EntityArmorStand#ae()
     */
    @ReflectiveMethod(name = "ae", types = {})
    public boolean ae(){
        return (boolean) NMSWrapper.getInstance().exec(nmsObject);
    }

    /**
     * TODO Find correct name
     * @see net.minecraft.server.v1_9_R1.EntityArmorStand#b(net.minecraft.server.v1_9_R1.NBTTagCompound)
     */
    @ReflectiveMethod(name = "b", types = {NMSNBTTagCompound.class})
    public void b(NMSNBTTagCompound nBTTagCompound){
        NMSWrapper.getInstance().exec(nmsObject, nBTTagCompound);
    }

    /**
     * TODO Find correct name
     * @see net.minecraft.server.v1_9_R1.EntityArmorStand#bA()
     */
    @ReflectiveMethod(name = "bA", types = {})
    public NMSItemStack bA(){
        return new NMSItemStack(NMSWrapper.getInstance().exec(nmsObject));
    }

    /**
     * TODO Find correct name
     * @see net.minecraft.server.v1_9_R1.EntityArmorStand#bL()
     */
    @ReflectiveMethod(name = "bL", types = {})
    public void bL(){
        NMSWrapper.getInstance().exec(nmsObject);
    }

    /**
     * TODO Find correct name
     * @see net.minecraft.server.v1_9_R1.EntityArmorStand#bM()
     */
    @ReflectiveMethod(name = "bM", types = {})
    public boolean bM(){
        return (boolean) NMSWrapper.getInstance().exec(nmsObject);
    }

    /**
     * TODO Find correct name
     * @see net.minecraft.server.v1_9_R1.EntityArmorStand#d(int, net.minecraft.server.v1_9_R1.ItemStack)
     */
    @ReflectiveMethod(name = "d", types = {int.class, NMSItemStack.class})
    public boolean d(int i, NMSItemStack itemStack){
        return (boolean) NMSWrapper.getInstance().exec(nmsObject, i, itemStack);
    }

    /**
     * @see net.minecraft.server.v1_9_R1.EntityArmorStand#damageEntity(net.minecraft.server.v1_9_R1.DamageSource, float)
     */
    @ReflectiveMethod(name = "damageEntity", types = {NMSDamageSource.class, float.class})
    public boolean damageEntity(NMSDamageSource damageSource, float f){
        return (boolean) NMSWrapper.getInstance().exec(nmsObject, damageSource, f);
    }

    /**
     * TODO Find correct name
     * @see net.minecraft.server.v1_9_R1.EntityArmorStand#g(float, float)
     */
    @ReflectiveMethod(name = "g", types = {float.class, float.class})
    public void g(float f, float f1){
        NMSWrapper.getInstance().exec(nmsObject, f, f1);
    }

    /**
     * @see net.minecraft.server.v1_9_R1.EntityArmorStand#getEquipment(int)
     */
    @ReflectiveMethod(name = "getEquipment", types = {int.class})
    public NMSItemStack getEquipment(int i){
        return new NMSItemStack(NMSWrapper.getInstance().exec(nmsObject, i));
    }

    /**
     * @see net.minecraft.server.v1_9_R1.EntityArmorStand#getHeadHeight()
     */
    @ReflectiveMethod(name = "getHeadHeight", types = {})
    public float getHeadHeight(){
        return (float) NMSWrapper.getInstance().exec(nmsObject);
    }

    /**
     * TODO Find correct name
     * @see net.minecraft.server.v1_9_R1.EntityArmorStand#h(float, float)
     */
    @ReflectiveMethod(name = "h", types = {float.class, float.class})
    public float h(float f, float f1){
        return (float) NMSWrapper.getInstance().exec(nmsObject, f, f1);
    }

    /**
     * @see net.minecraft.server.v1_9_R1.EntityArmorStand#hasArms()
     */
    @ReflectiveMethod(name = "hasArms", types = {})
    public boolean hasArms(){
        return (boolean) NMSWrapper.getInstance().exec(nmsObject);
    }

    /**
     * @see net.minecraft.server.v1_9_R1.EntityArmorStand#hasBasePlate()
     */
    @ReflectiveMethod(name = "hasBasePlate", types = {})
    public boolean hasBasePlate(){
        return (boolean) NMSWrapper.getInstance().exec(nmsObject);
    }

    /**
     * @see net.minecraft.server.v1_9_R1.EntityArmorStand#hasGravity()
     */
    @ReflectiveMethod(name = "hasGravity", types = {})
    public boolean hasGravity(){
        return (boolean) NMSWrapper.getInstance().exec(nmsObject);
    }

    /**
     * @see net.minecraft.server.v1_9_R1.EntityArmorStand#isBaby()
     */
    @ReflectiveMethod(name = "isBaby", types = {})
    public boolean isBaby(){
        return (boolean) NMSWrapper.getInstance().exec(nmsObject);
    }

    /**
     * @see net.minecraft.server.v1_9_R1.EntityArmorStand#isSmall()
     */
    @ReflectiveMethod(name = "isSmall", types = {})
    public boolean isSmall(){
        return (boolean) NMSWrapper.getInstance().exec(nmsObject);
    }

    /**
     * TODO Find correct name
     * @see net.minecraft.server.v1_9_R1.EntityArmorStand#n(boolean)
     */
    @ReflectiveMethod(name = "n", types = {boolean.class})
    public void n(boolean b){
        NMSWrapper.getInstance().exec(nmsObject, b);
    }

    /**
     * TODO Find correct name
     * @see net.minecraft.server.v1_9_R1.EntityArmorStand#s()
     */
    @ReflectiveMethod(name = "s", types = {})
    public boolean s(){
        return (boolean) NMSWrapper.getInstance().exec(nmsObject);
    }

    /**
     * @see net.minecraft.server.v1_9_R1.EntityArmorStand#setArms(boolean)
     */
    @ReflectiveMethod(name = "setArms", types = {boolean.class})
    public void setArms(boolean b){
        NMSWrapper.getInstance().exec(nmsObject, b);
    }

    /**
     * @see net.minecraft.server.v1_9_R1.EntityArmorStand#setBasePlate(boolean)
     */
    @ReflectiveMethod(name = "setBasePlate", types = {boolean.class})
    public void setBasePlate(boolean b){
        NMSWrapper.getInstance().exec(nmsObject, b);
    }

    /**
     * @see net.minecraft.server.v1_9_R1.EntityArmorStand#setBodyPose(net.minecraft.server.v1_9_R1.Vector3f)
     */
    @ReflectiveMethod(name = "setBodyPose", types = {NMSVector3f.class})
    public void setBodyPose(NMSVector3f vector3f){
        NMSWrapper.getInstance().exec(nmsObject, vector3f);
    }

    /**
     * @see net.minecraft.server.v1_9_R1.EntityArmorStand#setEquipment(int, net.minecraft.server.v1_9_R1.ItemStack)
     */
    @ReflectiveMethod(name = "setEquipment", types = {int.class, NMSItemStack.class})
    public void setEquipment(int i, NMSItemStack itemStack){
        NMSWrapper.getInstance().exec(nmsObject, i, itemStack);
    }

    /**
     * @see net.minecraft.server.v1_9_R1.EntityArmorStand#setGravity(boolean)
     */
    @ReflectiveMethod(name = "setGravity", types = {boolean.class})
    public void setGravity(boolean b){
        NMSWrapper.getInstance().exec(nmsObject, b);
    }

    /**
     * @see net.minecraft.server.v1_9_R1.EntityArmorStand#setHeadPose(net.minecraft.server.v1_9_R1.Vector3f)
     */
    @ReflectiveMethod(name = "setHeadPose", types = {NMSVector3f.class})
    public void setHeadPose(NMSVector3f vector3f){
        NMSWrapper.getInstance().exec(nmsObject, vector3f);
    }

    /**
     * @see net.minecraft.server.v1_9_R1.EntityArmorStand#setInvisible(boolean)
     */
    @ReflectiveMethod(name = "setInvisible", types = {boolean.class})
    public void setInvisible(boolean b){
        NMSWrapper.getInstance().exec(nmsObject, b);
    }

    /**
     * @see net.minecraft.server.v1_9_R1.EntityArmorStand#setLeftArmPose(net.minecraft.server.v1_9_R1.Vector3f)
     */
    @ReflectiveMethod(name = "setLeftArmPose", types = {NMSVector3f.class})
    public void setLeftArmPose(NMSVector3f vector3f){
        NMSWrapper.getInstance().exec(nmsObject, vector3f);
    }

    /**
     * @see net.minecraft.server.v1_9_R1.EntityArmorStand#setLeftLegPose(net.minecraft.server.v1_9_R1.Vector3f)
     */
    @ReflectiveMethod(name = "setLeftLegPose", types = {NMSVector3f.class})
    public void setLeftLegPose(NMSVector3f vector3f){
        NMSWrapper.getInstance().exec(nmsObject, vector3f);
    }

    /**
     * @see net.minecraft.server.v1_9_R1.EntityArmorStand#setRightArmPose(net.minecraft.server.v1_9_R1.Vector3f)
     */
    @ReflectiveMethod(name = "setRightArmPose", types = {NMSVector3f.class})
    public void setRightArmPose(NMSVector3f vector3f){
        NMSWrapper.getInstance().exec(nmsObject, vector3f);
    }

    /**
     * @see net.minecraft.server.v1_9_R1.EntityArmorStand#setRightLegPose(net.minecraft.server.v1_9_R1.Vector3f)
     */
    @ReflectiveMethod(name = "setRightLegPose", types = {NMSVector3f.class})
    public void setRightLegPose(NMSVector3f vector3f){
        NMSWrapper.getInstance().exec(nmsObject, vector3f);
    }

    /**
     * @see net.minecraft.server.v1_9_R1.EntityArmorStand#setSmall(boolean)
     */
    @ReflectiveMethod(name = "setSmall", types = {boolean.class})
    public void setSmall(boolean b){
        NMSWrapper.getInstance().exec(nmsObject, b);
    }

    /**
     * TODO Find correct name
     * @see net.minecraft.server.v1_9_R1.EntityArmorStand#t()
     */
    @ReflectiveMethod(name = "t", types = {})
    public NMSVector3f t(){
        return new NMSVector3f(NMSWrapper.getInstance().exec(nmsObject));
    }

    /**
     * TODO Find correct name
     * @see net.minecraft.server.v1_9_R1.EntityArmorStand#t_()
     */
    @ReflectiveMethod(name = "t_", types = {})
    public void t_(){
        NMSWrapper.getInstance().exec(nmsObject);
    }

    /**
     * TODO Find correct name
     * @see net.minecraft.server.v1_9_R1.EntityArmorStand#u()
     */
    @ReflectiveMethod(name = "u", types = {})
    public NMSVector3f u(){
        return new NMSVector3f(NMSWrapper.getInstance().exec(nmsObject));
    }

}


text:
(function() {
  var App, InfoView, Model, PdfView, State, View, log;

  log = console.log.bind(console);

  Model = Backbone.Model, View = Backbone.View;

  PdfView = View.extend({
    shortcuts: {
      'f': 'zoomIn',
      'shift+f': 'zoomOut',
      'alt+f': 'zoomFit',
      'r': 'rotateClockwise',
      'shift+r': 'rotateCounter',
      'home, g': 'home',
      'end, shift+g': 'end',
      'shift+space, b': 'prev',
      'space': 'next',
      'shift+k, shift+w': 'pageHome',
      'shift+j, shift+s': 'pageEnd',
      'k, w': 'up',
      'j, s': 'down'
    },
    initialize: function() {
      var method, shortcut, _fn, _ref,
        _this = this;
      _ref = this.shortcuts;
      _fn = function(shortcut, method) {
        return key(shortcut, function(e) {
          e.preventDefault();
          return _this[method]();
        });
      };
      for (shortcut in _ref) {
        method = _ref[shortcut];
        _fn(shortcut, method);
      }
      App.state.on('change:index', this.index, this);
      App.state.on('change:rotate change:scale', this.render, this);
      _.bindAll(this, 'render');
      return this.canvasContext = this.el.getContext('2d');
    },
    index: function(state, index) {
      var _this = this;
      return App.pdf.getPage(index).then(function(page) {
        state.set({
          page: page
        });
        return _this.render();
      });
    },
    render: function() {
      var height, page, rotate, scale, viewport, width, _ref;
      _ref = App.state.attributes, scale = _ref.scale, rotate = _ref.rotate, page = _ref.page;
      viewport = page.getViewport(scale, rotate);
      height = viewport.height, width = viewport.width;
      this.$el.attr({
        height: height,
        width: width
      });
      return page.render({
        canvasContext: this.canvasContext,
        viewport: viewport
      });
    },
    zoomFit: function() {
      var clientHeight, clientWidth, pageHeight, pageWidth, scale, _, _ref, _ref1;
      _ref = App.state.get('page').pageInfo.view, _ = _ref[0], _ = _ref[1], pageWidth = _ref[2], pageHeight = _ref[3];
      _ref1 = document.documentElement, clientHeight = _ref1.clientHeight, clientWidth = _ref1.clientWidth;
      scale = Math.min(clientWidth / pageWidth, clientHeight / pageHeight);
      return App.state.set({
        scale: scale,
        exponent: 0
      });
    },
    zoomIn: function() {
      return App.state.scale(+1);
    },
    zoomOut: function() {
      return App.state.scale(-1);
    },
    rotateClockwise: function() {
      return App.state.rotate(90);
    },
    rotateCounter: function() {
      return App.state.rotate(-90);
    },
    home: function() {
      return App.state.go(1);
    },
    end: function() {
      var length;
      length = App.state.attributes.length;
      return App.state.go(length);
    },
    next: function() {
      return App.state.goRel(+1);
    },
    prev: function() {
      return App.state.goRel(-1);
    },
    up: function() {
      return window.scrollBy(0, -40);
    },
    down: function() {
      return window.scrollBy(0, 40);
    },
    pageHome: function() {
      return window.scrollTo(0, 0);
    },
    pageEnd: function() {
      return window.scrollTo(0, document.body.offsetHeight);
    }
  });

  InfoView = View.extend({
    template: JST.info,
    initialize: function() {
      return App.state.on('change:index', this.change, this);
    },
    change: function(state, index) {
      return this.$el.html(this.template(state.attributes));
    }
  });

  State = Model.extend({
    defaults: {
      exponent: 0,
      rotate: 0,
      scale: 1
    },
    goRel: function(delta) {
      var index, length, _ref;
      _ref = this.attributes, index = _ref.index, length = _ref.length;
      index += delta;
      if ((0 < index && index <= length)) {
        return this.go(index);
      }
    },
    go: function(index) {
      this.set({
        index: index
      });
      return App.set('index', index);
    },
    rotate: function(delta) {
      var rotate;
      rotate = this.attributes.rotate;
      rotate += delta;
      rotate = (rotate + 360) % 360;
      return this.set({
        rotate: rotate
      });
    },
    scale: function(delta) {
      var exponent, scale;
      exponent = this.attributes.exponent;
      exponent += delta;
      scale = Math.pow(2, exponent);
      return this.set({
        scale: scale,
        exponent: exponent
      });
    }
  });

  App = {
    init: function() {
      var path, url;
      this.state = new State;
      new PdfView({
        el: '#canvas'
      });
      new InfoView({
        el: '#info'
      });
      path = location.hash.slice(1);
      App.ns = "pdf." + path + ".";
      url = '/raw' + path;
      PDFJS.disableWorker = true;
      return PDFJS.getDocument(url).then(function(pdf) {
        App.pdf = pdf;
        return App.state.set({
          length: pdf.pdfInfo.numPages,
          index: App.get('index', 1)
        });
      });
    },
    set: function(key, val) {
      return localStorage[App.ns + key] = JSON.stringify(val);
    },
    get: function(key, def) {
      var val;
      if (val = localStorage[App.ns + key]) {
        return JSON.parse(val);
      } else {
        return def;
      }
    }
  };

  App.init();

}).call(this);


text:
require 'lyracyst/wordnik/define'
require 'lyracyst/wordnik/example'
require 'lyracyst/wordnik/hyphen'
require 'lyracyst/wordnik/origin'
require 'lyracyst/wordnik/phrase'
require 'lyracyst/wordnik/pronounce'
require 'lyracyst/wordnik/relate'
require 'lyracyst/wordnik/word'


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Nop.Core;
using Nop.Core.Caching;
using Nop.Core.Domain.Customers;
using Nop.Core.Domain.Polls;
using Nop.Services.Localization;
using Nop.Services.Polls;
using Nop.Web.Infrastructure.Cache;
using Nop.Web.Models.Polls;

namespace Nop.Web.Controllers
{
    public partial class PollController : BasePublicController
    {
        #region Fields

        private readonly ILocalizationService _localizationService;
        private readonly IWorkContext _workContext;
        private readonly IPollService _pollService;
        private readonly IWebHelper _webHelper;
        private readonly ICacheManager _cacheManager;

        #endregion

        #region Constructors

        public PollController(ILocalizationService localizationService,
            IWorkContext workContext, IPollService pollService,
            IWebHelper webHelper, ICacheManager cacheManager)
        {
            this._localizationService = localizationService;
            this._workContext = workContext;
            this._pollService = pollService;
            this._webHelper = webHelper;
            this._cacheManager = cacheManager;
        }

        #endregion

        #region Utilities

        [NonAction]
        protected virtual PollModel PreparePollModel(Poll poll, bool setAlreadyVotedProperty)
        {
            var model = new PollModel()
            {
                Id = poll.Id,
                AlreadyVoted = setAlreadyVotedProperty && _pollService.AlreadyVoted(poll.Id, _workContext.CurrentCustomer.Id),
                Name = poll.Name
            };
            var answers = poll.PollAnswers.OrderBy(x => x.DisplayOrder);
            foreach (var answer in answers)
                model.TotalVotes += answer.NumberOfVotes;
            foreach (var pa in answers)
            {
                model.Answers.Add(new PollAnswerModel()
                {
                    Id = pa.Id,
                    Name = pa.Name,
                    NumberOfVotes = pa.NumberOfVotes,
                    PercentOfTotalVotes = model.TotalVotes > 0 ? ((Convert.ToDouble(pa.NumberOfVotes) / Convert.ToDouble(model.TotalVotes)) * Convert.ToDouble(100)) : 0,
                });
            }

            return model;
        }

        #endregion

        #region Methods

        [ChildActionOnly]
        public ActionResult PollBlock(string systemKeyword)
        {
            if (String.IsNullOrWhiteSpace(systemKeyword))
                return Content("");

            var cacheKey = string.Format(ModelCacheEventConsumer.POLL_BY_SYSTEMNAME__MODEL_KEY, systemKeyword, _workContext.WorkingLanguage.Id);
            var cachedModel = _cacheManager.Get(cacheKey, () =>
            {
                Poll poll = _pollService.GetPollBySystemKeyword(systemKeyword, _workContext.WorkingLanguage.Id);
                if (poll == null ||
                    !poll.Published ||
                    (poll.StartDateUtc.HasValue && poll.StartDateUtc.Value > DateTime.UtcNow) ||
                    (poll.EndDateUtc.HasValue && poll.EndDateUtc.Value < DateTime.UtcNow))
                    //we do not cache nulls. that's why let's return an empty record (ID = 0)
                    return new PollModel() { Id = 0};

                return PreparePollModel(poll, false);
            });
            if (cachedModel == null || cachedModel.Id == 0)
                return Content("");

            //"AlreadyVoted" property of "PollModel" object depends on the current customer. Let's update it.
            //But first we need to clone the cached model (the updated one should not be cached)
            var model = (PollModel)cachedModel.Clone();
            model.AlreadyVoted = _pollService.AlreadyVoted(model.Id, _workContext.CurrentCustomer.Id);

            return PartialView(model);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Vote(int pollAnswerId)
        {
            var pollAnswer = _pollService.GetPollAnswerById(pollAnswerId);
            if (pollAnswer == null)
                return Json(new
                {
                    error = "No poll answer found with the specified id",
                });

            var poll = pollAnswer.Poll;
            if (!poll.Published)
                return Json(new
                {
                    error = "Poll is not available",
                });

            if (_workContext.CurrentCustomer.IsGuest() && !poll.AllowGuestsToVote)
                return Json(new
                {
                    error = _localizationService.GetResource("Polls.OnlyRegisteredUsersVote"),
                });

            bool alreadyVoted = _pollService.AlreadyVoted(poll.Id, _workContext.CurrentCustomer.Id);
            if (!alreadyVoted)
            {
                //vote
                pollAnswer.PollVotingRecords.Add(new PollVotingRecord()
                {
                    PollAnswerId = pollAnswer.Id,
                    CustomerId = _workContext.CurrentCustomer.Id,
                    CreatedOnUtc = DateTime.UtcNow
                });
                //update totals
                pollAnswer.NumberOfVotes = pollAnswer.PollVotingRecords.Count;
                _pollService.UpdatePoll(poll);
            }

            return Json(new
            {
                html = this.RenderPartialViewToString("_Poll", PreparePollModel(poll, true)),
            });
        }

        [ChildActionOnly]
        public ActionResult HomePagePolls()
        {
            var cacheKey = string.Format(ModelCacheEventConsumer.HOMEPAGE_POLLS_MODEL_KEY, _workContext.WorkingLanguage.Id);
            var cachedModel = _cacheManager.Get(cacheKey, () =>
            {
                return _pollService.GetPolls(_workContext.WorkingLanguage.Id, true, 0, int.MaxValue)
                    .Select(x => PreparePollModel(x, false))
                    .ToList();
            });
            //"AlreadyVoted" property of "PollModel" object depends on the current customer. Let's update it.
            //But first we need to clone the cached model (the updated one should not be cached)
            var model = new List<PollModel>();
            foreach (var p in cachedModel)
            {
                var pollModel = (PollModel) p.Clone();
                pollModel.AlreadyVoted = _pollService.AlreadyVoted(pollModel.Id, _workContext.CurrentCustomer.Id);
                model.Add(pollModel);
            }

            if (model.Count == 0)
                Content("");

            return PartialView(model);
        }

        #endregion

    }
}


text:
import histopy
import datetime
import json
import calendar
import re
import collections
import os
import argparse

def _to_int(input):
    if len(input)==0:
        return False
    bc = re.compile(' BC\Z')
    bce = re.compile(' BCE\Z')
    slash = re.compile('/')
    if bc.search(input):
        return int(input[0:-3])
    if bce.search(input):
        return int(input[0:-4])
    if slash.search(input):
        return int(input.split('/')[0])
    return int(input)

def _filter(input):
    return {k:v for (k,v) in input.items() if _to_int(k) % 5 == 0 or _to_int(k) % 10 == 0}

def _map(input, month, day):
    return {'{num:02d}'.format(num=day) + ' ' + calendar.month_name[month] + ' ' + key: value for key, value in input.items()}

parser = argparse.ArgumentParser(description='Fetch events from Wikipedia for years ending in 0 and 5 for the given month.')
parser.add_argument('--month', dest='month', type=int, default=1)

args = vars(parser.parse_args())
month = args['month']

year = 2015
all_events = {}
all_deaths = {}
all_births = {}
days_in_month = calendar.monthrange(year, month)[1] + 1

for day in range(1, days_in_month):
    today = datetime.datetime(year, month, day)
    today_in_history = histopy.load_history(today)

    events = histopy.load_events(today_in_history)
    all_events.update(_map(_filter(events), month, day))

    deaths = histopy.load_deaths(today_in_history)
    all_deaths.update(_map(_filter(deaths), month, day))

    births = histopy.load_births(today_in_history)
    all_births.update(_map(_filter(births), month, day))

if not os.path.exists('./output'):
    os.makedirs('./output')

f = open('output/' + calendar.month_name[month] + '_events.json', 'w')
json.dump(collections.OrderedDict(sorted(all_events.items())), f)
print ('Found {} events for month of {}'.format(len(all_events), calendar.month_name[month]))

f = open('output/' + calendar.month_name[month] + '_deaths.json', 'w')
json.dump(collections.OrderedDict(sorted(all_deaths.items())), f)
print ('Found {} deaths for month of {}'.format(len(all_deaths), calendar.month_name[month]))

f = open('output/' + calendar.month_name[month] + '_births.json', 'w')
json.dump(collections.OrderedDict(sorted(all_births.items())), f)
print ('Found {} births for month of {}'.format(len(all_births), calendar.month_name[month]))


text:
- Updated packages

### Changed

- Using GitHub Actions instead of Travis

## [1.2.4] - 2020-09-02

### Fixed

- Updated packages

## [1.2.3] - 2020-01-02

### Fixed

- Added npm i to deploy script

## [1.2.2] - 2020-01-02

### Fixed

- Updated open version to 6.4

## [1.2.1] - 2020-01-02

### Fixed

- Updated unit tests

## [1.2] - 2020-01-02

### Added

- Search local documentation. NOTE: THIS IS UNTESTED ON MAC AND LINUX! Thanks [@rostok](https://github.com/rostok) for the help.
- Set documentation version for online documentation. Thanks [@mccorkle](https://github.com/mccorkle)

## [1.1.1] - 2019-06-05

### Fixed

- Updated NPM packages

## [1.1.0] - 2019-02-06

### Removed

- Removed the opn requirement, using new internal open external API

### Fixed

- Updated package.json requirements

## [1.0.5] - 2018-08-15

### Fixed

- Updated extensionDependencies to extensionPack as per new feature in VSCode.

## [1.0.3] - 2018-05-09

### Added

- Made project multi root folder ready

### Fixed

- Made so only the linux builds from travis get published.
- Updated Node version
- removed redundant default setting value

## [1.0.2] - 2018-05-08

### Added

- Added Node back to .travis.yml

### Fixed

- Fixed typo in deploy script

## [1.0.1] - 2018-05-08

### Fixed

- Added deploy back to travis file

## [1.0.0] - 2018-05-08

### Changed

- Updated project based on latest template. Including tests, config files, linting, etc.
- Fixed misc. errors caused by above

## [0.2.1] - 2018-05-07

### Removed

- Removed dotBunny's VSCode extension feature as it is no longer needed to use VSCode with Unity

## [0.2.0] - 2018-05-07

### Added

- Turned extension into extension pack for "Unity.unity-debug" and "YclepticStudios.unity-snippets"

## [0.1.17] - 2018-05-06

### Changed

- Updated dependencies

## [0.1.16] - 2018-05-06

### Added

- Added setting to disable right click menu. Made right click menu only appear in c# files.

## [0.1.15] - 2018-04-30

### Fixed

- Organization folder setting should no longer give "Unknown configuration setting" error

## [0.1.14] - 2018-04-30

### Fixed

- Travis publishing was not working.

## [0.1.13] - 2018-04-30

### Changed

- Updated Node version for Travis.

## [0.1.12] - 2018-04-30

### Fixed

- Organization folder settings should now load correctly from "unity-tools.defaultOrganizationFolders"

## [0.1.11] - 2018-04-30

### Changed

- Updated dependencies

## [0.1.10] - 2018-04-30

### Added

- Merged in PR from @ilgarmehmetali adding Open Docs feature to right-click menu

## [0.1.2] - 2016-01-29

### Added

- Added CHANGELOG.md

### Changed

- Changed command name to fit standard format "Unity: < Command >"


text:
'use strict';

var GetIntrinsic = require('get-intrinsic');

var $TypeError = GetIntrinsic('%TypeError%');
var $SyntaxError = GetIntrinsic('%SyntaxError%');

var has = require('has');

var predicates = {
	// https://ecma-international.org/ecma-262/6.0/#sec-property-descriptor-specification-type
	'Property Descriptor': function isPropertyDescriptor(Type, Desc) {
		if (Type(Desc) !== 'Object') {
			return false;
		}
		var allowed = {
			'[[Configurable]]': true,
			'[[Enumerable]]': true,
			'[[Get]]': true,
			'[[Set]]': true,
			'[[Value]]': true,
			'[[Writable]]': true
		};

		for (var key in Desc) { // eslint-disable-line
			if (has(Desc, key) && !allowed[key]) {
				return false;
			}
		}

		var isData = has(Desc, '[[Value]]');
		var IsAccessor = has(Desc, '[[Get]]') || has(Desc, '[[Set]]');
		if (isData && IsAccessor) {
			throw new $TypeError('Property Descriptors may not be both accessor and data descriptors');
		}
		return true;
	}
};

module.exports = function assertRecord(Type, recordType, argumentName, value) {
	var predicate = predicates[recordType];
	if (typeof predicate !== 'function') {
		throw new $SyntaxError('unknown record type: ' + recordType);
	}
	if (!predicate(Type, value)) {
		throw new $TypeError(argumentName + ' must be a ' + recordType);
	}
};


text:
/**
  @module ember-data
*/
import { assert } from '@ember/debug';

/*
  This file encapsulates the various states that a record can transition
  through during its lifecycle.
*/
/**
  ### State

  Each record has a `currentState` property that explicitly tracks what
  state a record is in at any given time. For instance, if a record is
  newly created and has not yet been sent to the adapter to be saved,
  it would be in the `root.loaded.created.uncommitted` state.  If a
  record has had local modifications made to it that are in the
  process of being saved, the record would be in the
  `root.loaded.updated.inFlight` state. (This state paths will be
  explained in more detail below.)

  Events are sent by the record or its store to the record's
  `currentState` property. How the state reacts to these events is
  dependent on which state it is in. In some states, certain events
  will be invalid and will cause an exception to be raised.

  States are hierarchical and every state is a substate of the
  `RootState`. For example, a record can be in the
  `root.deleted.uncommitted` state, then transition into the
  `root.deleted.inFlight` state. If a child state does not implement
  an event handler, the state manager will attempt to invoke the event
  on all parent states until the root state is reached. The state
  hierarchy of a record is described in terms of a path string. You
  can determine a record's current state by getting the state's
  `stateName` property:

  ```javascript
  record.get('currentState.stateName');
  //=> "root.created.uncommitted"
   ```

  The hierarchy of valid states that ship with ember data looks like
  this:

  ```text
  * root
    * deleted
      * saved
      * uncommitted
      * inFlight
    * empty
    * loaded
      * created
        * uncommitted
        * inFlight
      * saved
      * updated
        * uncommitted
        * inFlight
    * loading
  ```

  The `DS.Model` states are themselves stateless. What that means is
  that, the hierarchical states that each of *those* points to is a
  shared data structure. For performance reasons, instead of each
  record getting its own copy of the hierarchy of states, each record
  points to this global, immutable shared instance. How does a state
  know which record it should be acting on? We pass the record
  instance into the state's event handlers as the first argument.

  The record passed as the first parameter is where you should stash
  state about the record if needed; you should never store data on the state
  object itself.

  ### Events and Flags

  A state may implement zero or more events and flags.

  #### Events

  Events are named functions that are invoked when sent to a record. The
  record will first look for a method with the given name on the
  current state. If no method is found, it will search the current
  state's parent, and then its grandparent, and so on until reaching
  the top of the hierarchy. If the root is reached without an event
  handler being found, an exception will be raised. This can be very
  helpful when debugging new features.

  Here's an example implementation of a state with a `myEvent` event handler:

  ```javascript
  aState: DS.State.create({
    myEvent: function(manager, param) {
      console.log("Received myEvent with", param);
    }
  })
  ```

  To trigger this event:

  ```javascript
  record.send('myEvent', 'foo');
  //=> "Received myEvent with foo"
  ```

  Note that an optional parameter can be sent to a record's `send()` method,
  which will be passed as the second parameter to the event handler.

  Events should transition to a different state if appropriate. This can be
  done by calling the record's `transitionTo()` method with a path to the
  desired state. The state manager will attempt to resolve the state path
  relative to the current state. If no state is found at that path, it will
  attempt to resolve it relative to the current state's parent, and then its
  parent, and so on until the root is reached. For example, imagine a hierarchy
  like this:

      * created
        * uncommitted <-- currentState
        * inFlight
      * updated
        * inFlight

  If we are currently in the `uncommitted` state, calling
  `transitionTo('inFlight')` would transition to the `created.inFlight` state,
  while calling `transitionTo('updated.inFlight')` would transition to
  the `updated.inFlight` state.

  Remember that *only events* should ever cause a state transition. You should
  never call `transitionTo()` from outside a state's event handler. If you are
  tempted to do so, create a new event and send that to the state manager.

  #### Flags

  Flags are Boolean values that can be used to introspect a record's current
  state in a more user-friendly way than examining its state path. For example,
  instead of doing this:

  ```javascript
  var statePath = record.get('stateManager.currentPath');
  if (statePath === 'created.inFlight') {
    doSomething();
  }
  ```

  You can say:

  ```javascript
  if (record.get('isNew') && record.get('isSaving')) {
    doSomething();
  }
  ```

  If your state does not set a value for a given flag, the value will
  be inherited from its parent (or the first place in the state hierarchy
  where it is defined).

  The current set of flags are defined below. If you want to add a new flag,
  in addition to the area below, you will also need to declare it in the
  `DS.Model` class.

   * [isEmpty](DS.Model.html#property_isEmpty)
   * [isLoading](DS.Model.html#property_isLoading)
   * [isLoaded](DS.Model.html#property_isLoaded)
   * [hasDirtyAttributes](DS.Model.html#property_hasDirtyAttributes)
   * [isSaving](DS.Model.html#property_isSaving)
   * [isDeleted](DS.Model.html#property_isDeleted)
   * [isNew](DS.Model.html#property_isNew)
   * [isValid](DS.Model.html#property_isValid)

  @namespace DS
  @class RootState
*/

function didSetProperty(internalModel, context) {
  if (context.value === context.originalValue) {
    delete internalModel._attributes[context.name];
    internalModel.send('propertyWasReset', context.name);
  } else if (context.value !== context.oldValue) {
    internalModel.send('becomeDirty');
  }

  internalModel.updateRecordArrays();
}

// Implementation notes:
//
// Each state has a boolean value for all of the following flags:
//
// * isLoaded: The record has a populated `data` property. When a
//   record is loaded via `store.find`, `isLoaded` is false
//   until the adapter sets it. When a record is created locally,
//   its `isLoaded` property is always true.
// * isDirty: The record has local changes that have not yet been
//   saved by the adapter. This includes records that have been
//   created (but not yet saved) or deleted.
// * isSaving: The record has been committed, but
//   the adapter has not yet acknowledged that the changes have
//   been persisted to the backend.
// * isDeleted: The record was marked for deletion. When `isDeleted`
//   is true and `isDirty` is true, the record is deleted locally
//   but the deletion was not yet persisted. When `isSaving` is
//   true, the change is in-flight. When both `isDirty` and
//   `isSaving` are false, the change has persisted.
// * isNew: The record was created on the client and the adapter
//   did not yet report that it was successfully saved.
// * isValid: The adapter did not report any server-side validation
//   failures.

// The dirty state is a abstract state whose functionality is
// shared between the `created` and `updated` states.
//
// The deleted state shares the `isDirty` flag with the
// subclasses of `DirtyState`, but with a very different
// implementation.
//
// Dirty states have three child states:
//
// `uncommitted`: the store has not yet handed off the record
//   to be saved.
// `inFlight`: the store has handed off the record to be saved,
//   but the adapter has not yet acknowledged success.
// `invalid`: the record has invalid information and cannot be
//   sent to the adapter yet.
const DirtyState = {
  initialState: 'uncommitted',

  // FLAGS
  isDirty: true,

  // SUBSTATES

  // When a record first becomes dirty, it is `uncommitted`.
  // This means that there are local pending changes, but they
  // have not yet begun to be saved, and are not invalid.
  uncommitted: {
    // EVENTS
    didSetProperty,

    //TODO(Igor) reloading now triggers a
    //loadingData event, though it seems fine?
    loadingData() { },

    propertyWasReset(internalModel, name) {
      if (!internalModel.hasChangedAttributes()) { internalModel.send('rolledBack'); }
    },

    pushedData(internalModel) {
      let token = heimdall.start('stats.uncommitted.pushedData');
      internalModel.updateChangedAttributes();

      if (!internalModel.hasChangedAttributes()) {
        internalModel.transitionTo('loaded.saved');
      }
      heimdall.stop(token);
    },

    becomeDirty() {},

    willCommit(internalModel) {
      internalModel.transitionTo('inFlight');
    },

    reloadRecord(internalModel, resolve) {
      resolve(internalModel.store._reloadRecord(internalModel));
    },

    rolledBack(internalModel) {
      internalModel.transitionTo('loaded.saved');
    },

    becameInvalid(internalModel) {
      internalModel.transitionTo('invalid');
    },

    rollback(internalModel) {
      internalModel.rollbackAttributes();
      internalModel.triggerLater('ready');
    }
  },

  // Once a record has been handed off to the adapter to be
  // saved, it is in the 'in flight' state. Changes to the
  // record cannot be made during this window.
  inFlight: {
    // FLAGS
    isSaving: true,

    // EVENTS
    didSetProperty,
    becomeDirty() { },
    pushedData() { },

    unloadRecord: assertAgainstUnloadRecord,

    // TODO: More robust semantics around save-while-in-flight
    willCommit() { },

    didCommit(internalModel) {
      internalModel.transitionTo('saved');
      internalModel.send('invokeLifecycleCallbacks', this.dirtyType);
    },

    becameInvalid(internalModel) {
      internalModel.transitionTo('invalid');
      internalModel.send('invokeLifecycleCallbacks');
    },

    becameError(internalModel) {
      internalModel.transitionTo('uncommitted');
      internalModel.triggerLater('becameError', internalModel);
    }
  },

  // A record is in the `invalid` if the adapter has indicated
  // the the record failed server-side invalidations.
  invalid: {
    // FLAGS
    isValid: false,

    // EVENTS
    deleteRecord(internalModel) {
      internalModel.transitionTo('deleted.uncommitted');
    },

    didSetProperty(internalModel, context) {
      internalModel.removeErrorMessageFromAttribute(context.name);

      didSetProperty(internalModel, context);

      if (!internalModel.hasErrors()) {
        this.becameValid(internalModel);
      }
    },

    becameInvalid() { },
    becomeDirty() { },
    pushedData() { },

    willCommit(internalModel) {
      internalModel.clearErrorMessages();
      internalModel.transitionTo('inFlight');
    },

    rolledBack(internalModel) {
      internalModel.clearErrorMessages();
      internalModel.transitionTo('loaded.saved');
      internalModel.triggerLater('ready');
    },

    becameValid(internalModel) {
      internalModel.transitionTo('uncommitted');
    },

    invokeLifecycleCallbacks(internalModel) {
      internalModel.triggerLater('becameInvalid', internalModel);
    }
  }
};

// The created and updated states are created outside the state
// chart so we can reopen their substates and add mixins as
// necessary.

function deepClone(object) {
  const clone = {};
  let value;

  for (let prop in object) {
    value = object[prop];
    if (value && typeof value === 'object') {
      clone[prop] = deepClone(value);
    } else {
      clone[prop] = value;
    }
  }

  return clone;
}

function mixin(original, hash) {
  for (let prop in hash) {
    original[prop] = hash[prop];
  }

  return original;
}

function dirtyState(options) {
  var newState = deepClone(DirtyState);
  return mixin(newState, options);
}

const createdState = dirtyState({
  dirtyType: 'created',
  // FLAGS
  isNew: true
});

createdState.invalid.rolledBack = function(internalModel) {
  internalModel.transitionTo('deleted.saved');
};

createdState.uncommitted.rolledBack = function(internalModel) {
  internalModel.transitionTo('deleted.saved');
};

const updatedState = dirtyState({
  dirtyType: 'updated'
});

function createdStateDeleteRecord(internalModel) {
  internalModel.transitionTo('deleted.saved');
  internalModel.send('invokeLifecycleCallbacks');
}

createdState.uncommitted.deleteRecord = createdStateDeleteRecord;

createdState.invalid.deleteRecord = createdStateDeleteRecord;

createdState.uncommitted.rollback = function(internalModel) {
  DirtyState.uncommitted.rollback.apply(this, arguments);
  internalModel.transitionTo('deleted.saved');
};

createdState.uncommitted.pushedData = function(internalModel) {
  internalModel.transitionTo('loaded.updated.uncommitted');
  internalModel.triggerLater('didLoad');
};

createdState.uncommitted.propertyWasReset = function() {};

function assertAgainstUnloadRecord(internalModel) {
  assert("You can only unload a record which is not inFlight. `" + internalModel + "`", false);
}

updatedState.inFlight.unloadRecord = assertAgainstUnloadRecord;

updatedState.uncommitted.deleteRecord = function(internalModel) {
  internalModel.transitionTo('deleted.uncommitted');
};

const RootState = {
  // FLAGS
  isEmpty: false,
  isLoading: false,
  isLoaded: false,
  isDirty: false,
  isSaving: false,
  isDeleted: false,
  isNew: false,
  isValid: true,

  // DEFAULT EVENTS

  // Trying to roll back if you're not in the dirty state
  // doesn't change your state. For example, if you're in the
  // in-flight state, rolling back the record doesn't move
  // you out of the in-flight state.
  rolledBack() { },
  unloadRecord(internalModel) {
  },

  propertyWasReset() { },

  // SUBSTATES

  // A record begins its lifecycle in the `empty` state.
  // If its data will come from the adapter, it will
  // transition into the `loading` state. Otherwise, if
  // the record is being created on the client, it will
  // transition into the `created` state.
  empty: {
    isEmpty: true,

    // EVENTS
    loadingData(internalModel, promise) {
      internalModel._loadingPromise = promise;
      internalModel.transitionTo('loading');
    },

    loadedData(internalModel) {
      internalModel.transitionTo('loaded.created.uncommitted');
      internalModel.triggerLater('ready');
    },

    pushedData(internalModel) {
      internalModel.transitionTo('loaded.saved');
      internalModel.triggerLater('didLoad');
      internalModel.triggerLater('ready');
    }
  },

  // A record enters this state when the store asks
  // the adapter for its data. It remains in this state
  // until the adapter provides the requested data.
  //
  // Usually, this process is asynchronous, using an
  // XHR to retrieve the data.
  loading: {
    // FLAGS
    isLoading: true,

    exit(internalModel) {
      internalModel._loadingPromise = null;
    },

    // EVENTS
    pushedData(internalModel) {
      internalModel.transitionTo('loaded.saved');
      internalModel.triggerLater('didLoad');
      internalModel.triggerLater('ready');
      //TODO this seems out of place here
      internalModel.didCleanError();
    },

    becameError(internalModel) {
      internalModel.triggerLater('becameError', internalModel);
    },

    notFound(internalModel) {
      internalModel.transitionTo('empty');
    }
  },

  // A record enters this state when its data is populated.
  // Most of a record's lifecycle is spent inside substates
  // of the `loaded` state.
  loaded: {
    initialState: 'saved',

    // FLAGS
    isLoaded: true,

    //TODO(Igor) Reloading now triggers a loadingData event,
    //but it should be ok?
    loadingData() { },

    // SUBSTATES

    // If there are no local changes to a record, it remains
    // in the `saved` state.
    saved: {
      setup(internalModel) {
        if (internalModel.hasChangedAttributes()) {
          internalModel.adapterDidDirty();
        }
      },

      // EVENTS
      didSetProperty,

      pushedData() { },

      becomeDirty(internalModel) {
        internalModel.transitionTo('updated.uncommitted');
      },

      willCommit(internalModel) {
        internalModel.transitionTo('updated.inFlight');
      },

      reloadRecord(internalModel, resolve) {
        resolve(internalModel.store._reloadRecord(internalModel));
      },

      deleteRecord(internalModel) {
        internalModel.transitionTo('deleted.uncommitted');
      },

      unloadRecord(internalModel) {
      },

      didCommit() {},

      // loaded.saved.notFound would be triggered by a failed
      // `reload()` on an unchanged record
      notFound() { }
    },

    // A record is in this state after it has been locally
    // created but before the adapter has indicated that
    // it has been saved.
    created: createdState,

    // A record is in this state if it has already been
    // saved to the server, but there are new local changes
    // that have not yet been saved.
    updated: updatedState
  },

  // A record is in this state if it was deleted from the store.
  deleted: {
    initialState: 'uncommitted',
    dirtyType: 'deleted',

    // FLAGS
    isDeleted: true,
    isLoaded: true,
    isDirty: true,

    // TRANSITIONS
    setup(internalModel) {
      internalModel.updateRecordArrays();
    },

    // SUBSTATES

    // When a record is deleted, it enters the `start`
    // state. It will exit this state when the record
    // starts to commit.
    uncommitted: {

      // EVENTS

      willCommit(internalModel) {
        internalModel.transitionTo('inFlight');
      },

      rollback(internalModel) {
        internalModel.rollbackAttributes();
        internalModel.triggerLater('ready');
      },

      pushedData()   { },
      becomeDirty()  { },
      deleteRecord() { },

      rolledBack(internalModel) {
        internalModel.transitionTo('loaded.saved');
        internalModel.triggerLater('ready');
      }
    },

    // After a record starts committing, but
    // before the adapter indicates that the deletion
    // has saved to the server, a record is in the
    // `inFlight` substate of `deleted`.
    inFlight: {
      // FLAGS
      isSaving: true,

      // EVENTS

      unloadRecord: assertAgainstUnloadRecord,

      // TODO: More robust semantics around save-while-in-flight
      willCommit() { },
      didCommit(internalModel) {
        internalModel.transitionTo('saved');

        internalModel.send('invokeLifecycleCallbacks');
      },

      becameError(internalModel) {
        internalModel.transitionTo('uncommitted');
        internalModel.triggerLater('becameError', internalModel);
      },

      becameInvalid(internalModel) {
        internalModel.transitionTo('invalid');
        internalModel.triggerLater('becameInvalid', internalModel);
      }
    },

    // Once the adapter indicates that the deletion has
    // been saved, the record enters the `saved` substate
    // of `deleted`.
    saved: {
      // FLAGS
      isDirty: false,

      setup(internalModel) {
        internalModel.removeFromInverseRelationships();
      },

      invokeLifecycleCallbacks(internalModel) {
        internalModel.triggerLater('didDelete', internalModel);
        internalModel.triggerLater('didCommit', internalModel);
      },

      willCommit() { },
      didCommit()  { }
    },

    invalid: {
      isValid: false,

      didSetProperty(internalModel, context) {
        internalModel.removeErrorMessageFromAttribute(context.name);

        didSetProperty(internalModel, context);

        if (!internalModel.hasErrors()) {
          this.becameValid(internalModel);
        }
      },

      becameInvalid() { },
      becomeDirty()   { },
      deleteRecord()  { },
      willCommit()    { },

      rolledBack(internalModel) {
        internalModel.clearErrorMessages();
        internalModel.transitionTo('loaded.saved');
        internalModel.triggerLater('ready');
      },

      becameValid(internalModel) {
        internalModel.transitionTo('uncommitted');
      }

    }
  },

  invokeLifecycleCallbacks(internalModel, dirtyType) {
    if (dirtyType === 'created') {
      internalModel.triggerLater('didCreate', internalModel);
    } else {
      internalModel.triggerLater('didUpdate', internalModel);
    }

    internalModel.triggerLater('didCommit', internalModel);
  }
};

function wireState(object, parent, name) {
  // TODO: Use Object.create and copy instead
  object = mixin(parent ? Object.create(parent) : {}, object);
  object.parentState = parent;
  object.stateName = name;

  for (let prop in object) {
    if (!object.hasOwnProperty(prop) || prop === 'parentState' || prop === 'stateName') { continue; }
    if (typeof object[prop] === 'object') {
      object[prop] = wireState(object[prop], object, name + '.' + prop);
    }
  }

  return object;
}

export default wireState(RootState, null, 'root');


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Field Columb. Mus. 1(3): (1896)

#### Original name
Pestalotia coccolobae Ellis & Everh.

### Remarks
null


text:
This package serves as the beating heart of Guard.

It defines data structures that meet the [v1alpha1 interface](v1alpha1.go).

## The guard/v1alpha1 API

The [v1alpha1 interface](v1alpha1.go) includes three interfaces:

- Profile: describing a sample of a data type
- Pile: accumulating multiple samples of a data type to enable learning.
- Config: the rules describing what is expected from the data type.

## Core Activity

Per Sample:

1. Profile.Profile(...sample...) - Create a profile from the sample
1. Config.Decide(profile)  - Decide if it conforms to the config rules
1. Pile.Add(profile)  - Add it to a pile.

Periodically:

1. Pile.Merge(someOtherPile) - Merge someOtherPile to Pile.
1. Config.Learn(pile) - Learn a new config rules based on a pile.
1. Config.Fuse(someOtherConfig) - Fuse configs to form a new config from an old one.

Note:

- Profiles, Piles and Configs are build to be transportable across a distributed system.

## Distributed System

Guard supports working in a distributed system by allowing many instances to collect samples and take decisions.

The instances each collect piles and send them to a central service that merge the piles and learn a new config based on the enw piles and the old config.

The config is then sent back to the instances and is kept in a persistent store.


text:
/**
 * Typescript definition tests for d3/d3-time module
 *
 * Note: These tests are intended to test the definitions only
 * in the sense of typing and call signature consistency. They
 * are not intended as functional tests.
 */

import * as d3Time from 'd3-time';

let countableI: d3Time.CountableTimeInterval;
let simpleI: d3Time.TimeInterval;
let dateArray: Date[];
const start: Date = new Date(2014, 1, 1, 6, 0, 0, 0);
const end: Date = new Date(2016, 6, 13, 1, 25, 15, 500);
const inBetween: Date = new Date(2015, 6, 13, 1, 30, 5, 700);
let resultDate: Date;
let count: number;

// Test custom factories' definitions ------------------------------------------

simpleI = d3Time.timeInterval(
    // floor function
    (d: Date) => { d.setUTCMinutes(0, 0, 0); },
    // offset function
    (d: Date, step: number) => { d.setUTCHours(d.getUTCHours() + step); }
);

// Below test fails, as generating countable interval requires count function argument
// countableI = d3Time.timeInterval(
//     // floor function
//     (d: Date) => { d.setUTCMinutes(0, 0, 0); },
//     // offset function
//     (d: Date, step: number) => { d.setUTCHours(d.getUTCHours() + step); }
// );

countableI = d3Time.timeInterval(
    // floor function
    (d: Date) => { d.setUTCMinutes(0, 0, 0); },
    // offset function
    (d: Date, step: number) => { d.setUTCHours(d.getUTCHours() + step); },
    // count function
    (start: Date, end: Date) => (end.valueOf() - start.valueOf()) / 36e5
);

countableI = d3Time.timeInterval(
    // floor function
    (d: Date) => { d.setUTCMinutes(0, 0, 0); },
    // offset function
    (d: Date, step: number) => { d.setUTCHours(d.getUTCHours() + step); },
    // count function
    (start: Date, end: Date) => (end.valueOf() - start.valueOf()) / 36e5,
    // field function
    (d: Date) => d.valueOf() / 36e5
);

// Test signatures of (Countable)Interval methods ------------------------------

countableI = d3Time.timeMonday;

resultDate = countableI(inBetween);
resultDate = countableI.floor(inBetween);
resultDate = countableI.round(inBetween);
resultDate = countableI.ceil(inBetween);
resultDate = countableI.ceil(inBetween);
resultDate = countableI.offset(inBetween);
resultDate = countableI.offset(inBetween, 3);

dateArray = countableI.range(new Date(), new Date()); // TODO: specify dates
dateArray = countableI.range(new Date(), new Date(), 2); // TODO: specify dates

// countableI = countableI.filter((d: Date)=>{ return d.getMonth() === 2;}); // Test fails, since .filter(...) return Interval and not CountableInterval
simpleI = countableI.filter((d: Date) => d.getMonth() === 2);

count = countableI.count(start, end);

// let countableIOrNull: d3Time.CountableTimeInterval | null = countableI.every(10); // Test fails, since .every(...) return Interval and not CountableInterval
const simpleIOrNull: d3Time.TimeInterval | null = countableI.every(10);

resultDate = simpleI.floor(inBetween);
resultDate = simpleI.round(inBetween);
resultDate = simpleI.ceil(inBetween);
resultDate = simpleI.ceil(inBetween);
resultDate = simpleI.offset(inBetween);
resultDate = simpleI.offset(inBetween, 3);
simpleI = simpleI.filter((d: Date) => d.getMonth() === 2);

// count = simpleI.count(start, end); // Test fails, since .count(...) is not defined on Interval
// simpleI = simpleI.every(10); // Test fails, since .every(...) is not defined on Interval

// Test built-in factories and date array creator definitions ------------------

countableI = d3Time.timeMillisecond;
dateArray = d3Time.timeMilliseconds(start, end);
dateArray = d3Time.timeMilliseconds(start, end, 60000);

countableI = d3Time.timeSecond;
dateArray = d3Time.timeSeconds(start, end);
dateArray = d3Time.timeSeconds(start, end, 120);

countableI = d3Time.timeMinute;
dateArray = d3Time.timeMinutes(start, end);
dateArray = d3Time.timeMinutes(start, end, 5);

countableI = d3Time.timeHour;
dateArray = d3Time.timeHours(start, end);
dateArray = d3Time.timeHours(start, end, 2);

countableI = d3Time.timeDay;
dateArray = d3Time.timeDays(start, end);
dateArray = d3Time.timeDays(start, end, 2);

countableI = d3Time.timeWeek;
dateArray = d3Time.timeWeeks(start, end);
dateArray = d3Time.timeWeeks(start, end, 2);

countableI = d3Time.timeSunday;
dateArray = d3Time.timeSundays(start, end);
dateArray = d3Time.timeSundays(start, end, 2);

countableI = d3Time.timeMonday;
dateArray = d3Time.timeMondays(start, end);
dateArray = d3Time.timeMondays(start, end, 2);

countableI = d3Time.timeTuesday;
dateArray = d3Time.timeTuesdays(start, end);
dateArray = d3Time.timeTuesdays(start, end, 2);

countableI = d3Time.timeWednesday;
dateArray = d3Time.timeWednesdays(start, end);
dateArray = d3Time.timeWednesdays(start, end, 2);

countableI = d3Time.timeThursday;
dateArray = d3Time.timeThursdays(start, end);
dateArray = d3Time.timeThursdays(start, end, 2);

countableI = d3Time.timeFriday;
dateArray = d3Time.timeFridays(start, end);
dateArray = d3Time.timeFridays(start, end, 2);

countableI = d3Time.timeSaturday;
dateArray = d3Time.timeSaturdays(start, end);
dateArray = d3Time.timeSaturdays(start, end, 2);

countableI = d3Time.timeMonth;
dateArray = d3Time.timeMonths(start, end);
dateArray = d3Time.timeMonths(start, end, 3);

countableI = d3Time.timeYear;
dateArray = d3Time.timeYears(start, end);
dateArray = d3Time.timeYears(start, end, 2);

countableI = d3Time.utcMillisecond;
dateArray = d3Time.utcMilliseconds(start, end);
dateArray = d3Time.utcMilliseconds(start, end, 60000);

countableI = d3Time.utcSecond;
dateArray = d3Time.utcSeconds(start, end);
dateArray = d3Time.utcSeconds(start, end, 120);

countableI = d3Time.utcMinute;
dateArray = d3Time.utcMinutes(start, end);
dateArray = d3Time.utcMinutes(start, end, 5);

countableI = d3Time.utcHour;
dateArray = d3Time.utcHours(start, end);
dateArray = d3Time.utcHours(start, end, 2);

countableI = d3Time.utcDay;
dateArray = d3Time.utcDays(start, end);
dateArray = d3Time.utcDays(start, end, 2);

countableI = d3Time.utcWeek;
dateArray = d3Time.utcWeeks(start, end);
dateArray = d3Time.utcWeeks(start, end, 2);

countableI = d3Time.utcSunday;
dateArray = d3Time.utcSundays(start, end);
dateArray = d3Time.utcSundays(start, end, 2);

countableI = d3Time.utcMonday;
dateArray = d3Time.utcMondays(start, end);
dateArray = d3Time.utcMondays(start, end, 2);

countableI = d3Time.utcTuesday;
dateArray = d3Time.utcTuesdays(start, end);
dateArray = d3Time.utcTuesdays(start, end, 2);

countableI = d3Time.utcWednesday;
dateArray = d3Time.utcWednesdays(start, end);
dateArray = d3Time.utcWednesdays(start, end, 2);

countableI = d3Time.utcThursday;
dateArray = d3Time.utcThursdays(start, end);
dateArray = d3Time.utcThursdays(start, end, 2);

countableI = d3Time.utcFriday;
dateArray = d3Time.utcFridays(start, end);
dateArray = d3Time.utcFridays(start, end, 2);

countableI = d3Time.utcSaturday;
dateArray = d3Time.utcSaturdays(start, end);
dateArray = d3Time.utcSaturdays(start, end, 2);

countableI = d3Time.utcMonth;
dateArray = d3Time.utcMonths(start, end);
dateArray = d3Time.utcMonths(start, end, 3);

countableI = d3Time.utcYear;
dateArray = d3Time.utcYears(start, end);
dateArray = d3Time.utcYears(start, end, 2);


text:
<?php
class Kwc_Errors_AccessDenied_Component extends Kwc_Errors_Abstract_Component
{
    public static function getSettings($param = null)
    {
        $ret = parent::getSettings($param);
        $ret['rootElementClass'] = 'kwfUp-webStandard';
        $ret['flags']['noIndex'] = true;
        return $ret;
    }
}


text:
var express = require('express'),
    http = require('http'),
    app = express(),
    server = http.createServer(app),
    path = require('path'),
    io = require('socket.io').listen(server),
    googleapis = require("googleapis")
    OAuth2Client = googleapis.OAuth2Client,
    MongoClient = require("mongodb").MongoClient;

io.set("log level", 2);

app.configure("all", function(){
    app.set('port', process.env.PORT || 1337);
    // app.set('views', __dirname + '/views');
    // app.set('view engine', 'jade');
    app.use(require('less-middleware')({ src: __dirname + '/public' }));
    app.use(express.favicon());
    app.use(express.logger('dev'));
    app.use(express.bodyParser());
    app.use(express.methodOverride());
    app.use(app.router);
    app.use(express.static(path.join(__dirname, 'public')));
});

app.configure('development', function(){
    app.use(express.errorHandler());
});

server.listen(app.get('port'), function(){
    console.log("Express server listening on port " + app.get('port'));
});

// App
var AlarmClock = function() {
    this.init.apply(this, arguments);
};

AlarmClock.prototype = {
    // Variables
    OAuth2Config: {
        clientId: "789571319516-ch3j8s80nt0gmddnmeg5p6dijc50120k.apps.googleusercontent.com",
        clientSecret: "bfc3X3xKlikW-W5Ja2CgF7VZ",
        redirectUrl: "http://localhost:1337/oauth2callback"
    },
    OAuth2Credentials: false,
    calendarId: false,
    nextEvent: false,
    // Methods
    init: function() {
        this.appSetupDone = false;
        this.initRoutes(app);
        this.initSockets(io.sockets);
        this.initDatabase();
    },
    initSockets: function (sockets) {
        sockets = sockets || this.sockets || io.sockets;
        sockets.on("connection", function(socket) {
            socket.on("get calendar list", this.fetchCalendarList.bind(this));
            socket.on("calendar select", this.calendarSelect.bind(this));
            socket.on("setup done", this.setupDone.bind(this));
            socket.on("update", this.update.bind(this));
            socket.on("reset config", this.resetConfig.bind(this, socket));
            socket.on("request log", this.requestLog.bind(this));
            this.emitStatus(socket);
        }.bind(this));
    },
    initRoutes: function(application) {
        application
            .get("/", function(req, res) {
                res.render("index");
                res.end();
            }).get("/authorize", function(req, res) {
                var url = this.generateAuthURL();
                res.setHeader('Content-Type', 'text/plain');
                res.redirect(url);
                res.end("Redirecting...");
            }.bind(this)).get("/oauth2callback", function(req, res) {
                res.setHeader('Content-Type', 'text/plain');
                res.end("Redirecting to the app...");
                this.getOAuth2Client().getToken(req.query.code, function(err, tokens) {
                    this.OAuth2Credentials = tokens;
                    this.emitStatus(io.sockets);
                }.bind(this));
            }.bind(this));
    },
    initDatabase: function() {
        MongoClient.connect("mongodb://127.0.0.1:27017/test", function(err, db) {
            if(err) throw err;

            this.db = db;
            this.loadConfig();
        }.bind(this));
    },
    loadConfig: function() {
        var collection = this.db.collection("config");
        collection.find().toArray(function(err, result) {
            if(err) throw err;

            for(var i = 0; i < result.length; i++) {
                if(result[i].key == "credentials") {
                    this.OAuth2Credentials = result[i].value;
                }
                else if(result[i].key == "calendarId") {
                    this.calendarId = result[i].value;
                }
            }

            if(this.getOAuth2Client()) {
                this.setupDone();
            }
        }.bind(this));
    },
    resetConfig: function(socket) {
        this.calendarId = null;
        this.OAuth2Credentials = undefined;
        this.OAuth2Client = undefined;
        this.appSetupDone = false;

        this.saveConfig();

        if(socket) {
            this.emitStatus(socket);
        }
    },
    requestLog: function() {
        console.log({
            credentials: this.OAuth2Credentials,
            calendarId: this.calendarId
        });
    },
    getOAuth2Client: function() {
        if(this.OAuth2Client == undefined) {
            this.OAuth2Client = new OAuth2Client(this.OAuth2Config.clientId, this.OAuth2Config.clientSecret, this.OAuth2Config.redirectUrl);
        }

        if(this.OAuth2Credentials) {
            this.OAuth2Client.credentials = this.OAuth2Credentials;
        }

        return this.OAuth2Client
    },
    generateAuthURL: function() {
        return this.getOAuth2Client().generateAuthUrl({
            access_type: 'offline',
            scope: 'https://www.googleapis.com/auth/calendar'
        });
    },
    emitStatus: function(socket) {
        if(!this.appSetupDone) {
            var step;
            if(this.OAuth2Credentials && this.calendarId) {
                step = 3;
            }
            else if(this.OAuth2Credentials) {
                step = 2;
            }
            else {
                step = 1;
            }

            socket.emit("status", {
                status: "setup",
                setupStep: step,
                calendarId: this.calendarId,
                calendarList: this.calendarList
            });
        }
        else {
            socket.emit("status", {
                status: "running",
                nextEvent: this.nextEvent
            });
        }
    },
    getNextEvent: function(/** */) {
        var d = new Date(),
            callback;
        for(var i in arguments) {
            if(typeof arguments[i] == "function") {
                callback = arguments[i];
            }
            else {
                d = new Date(arguments[i]);
            }
        }
        if(d.getHours() > 12) {
            d.setDate(d.getDate() + 1);
        }

        d.setHours(1);
        d.setMinutes(0);
        d.setSeconds(0);
        var dMax = new Date(d);
        dMax.setHours(12);
        dMax.setMinutes(0);
        dMax.setSeconds(0);

        var id = this.calendarId;
        var auth = this.getOAuth2Client();
        googleapis.discover("calendar", "v3").execute(function(err, client) {
            client.calendar.events.list({
                calendarId: id,
                timeMin: ISODateString(d),
                singleEvents: true,
                orderBy: "startTime",
                timeMax: ISODateString(dMax)
            })
                .withAuthClient(auth)
                .execute(function(err, result) {
                    if(!err) {
                        callback && callback({
                            status: "success",
                            data: result
                        });
                    }
                    else {
                        callback && callback({
                            status: "failed",
                            data: err
                        });
                    }
                });
        });
    },
    fetchCalendarList: function(arg, callback) {
        var auth = this.getOAuth2Client();
        var done = function(data) {
            this.calendarList = data;
            callback && callback(data);
        }.bind(this);

        googleapis.discover("calendar", "v3").execute(function(err, client) {
            client.calendar.calendarList.list()
                .withAuthClient(auth)
                .execute(function(err, result) {
                    if(err) return;
                    var outData = [];
                    for(var i = 0; i < result.items.length; i++) {
                        var item = result.items[i];
                        outData.push({
                            id: item.id,
                            name: item.summary
                        });
                    }
                    done(outData);
                });
        });
    },
    fetchCalendar: function(id, callback) {
        var auth = this.getOAuth2Client();
        googleapis.discover("calendar", "v3").execute(function(err, client) {
            client.calendar.calendars.get({calendarId: id})
                .withAuthClient(auth)
                .execute(function(err, result) {
                    if(!err) {
                        callback && callback({
                            status: "success",
                            data: result
                        });
                    }
                    else {
                        callback && callback({
                            status: "failed",
                            data: err
                        });
                    }
                });
        });
    },
    calendarSelect: function(id, fn) {
        this.fetchCalendar(id, function(result) {
            if(result.status == "success") {
                this.calendarId = result.data.id;
            }

            this.emitStatus(io.sockets);

            fn && fn(result);
        }.bind(this));
    },
    setupDone: function() {
        if(this.OAuth2Credentials && this.calendarId) {
            this.appSetupDone = true;
            this.update(this.emitStatus.bind(this, io.sockets));
            this.saveConfig();
            return true;
        }
        else return false;
    },
    saveConfig: function() {
        this.db.collection("config").update({
            key: "calendarId"
        }, {
            $set: {
                value: this.calendarId
            }
        }, {
            upsert: true,
            w: 0
        });
        this.db.collection("config").update({
            key: "credentials"
        }, {
            $set: {
                value: this.OAuth2Credentials
            }
        }, {
            upsert: true,
            w: 0
        });
    },
    update: function(callback) {
        var updated = {};
        var updateCallback = function(element) {
            updated[element] = true;
            for(var i in updated) {
                if(!updated[element]) return false;
            }
            callback && callback();
        }.bind(this);

        if(this.OAuth2Credentials && this.calendarId) {
            updated = {
                nextEvent: false
            };

            this.getNextEvent(function(result) {
                if(result.status == "success") {
                    this.nextEvent = result.data.items[0];
                }
                updateCallback("nextEvent");
            }.bind(this));
        }
    }
};

// Utility function: date to iso format
function ISODateString(d){
    function pad(n){return n<10 ? '0'+n : n}
    return d.getUTCFullYear()+'-'
        + pad(d.getUTCMonth()+1)+'-'
        + pad(d.getUTCDate())+'T'
        + pad(d.getUTCHours())+':'
        + pad(d.getUTCMinutes())+':'
        + pad(d.getUTCSeconds())+'Z'}

var theApp = new AlarmClock();


text:
// Black-box Testing
package iris_test

/*
Contains tests for plugin, no end-to-end, just local-object tests, these are enoguh for now.

CONTRIBUTE & DISCUSSION ABOUT TESTS TO: https://github.com/iris-contrib/tests
*/

import (
	"fmt"
	"github.com/kataras/iris"
	"testing"
)

const (
	testPluginExDescription = "Description for My test plugin"
	testPluginExName        = "My test plugin"
)

type testPluginEx struct {
	named, activated, descriptioned          bool
	prelistenran, postlistenran, precloseran bool
}

func (t *testPluginEx) GetName() string {
	fmt.Println("GetName Struct")
	t.named = true
	return testPluginExName
}

func (t *testPluginEx) GetDescription() string {
	fmt.Println("GetDescription Struct")
	t.descriptioned = true
	return testPluginExDescription
}

func (t *testPluginEx) Activate(p iris.PluginContainer) error {
	fmt.Println("Activate Struct")
	t.activated = true
	return nil
}

func (t *testPluginEx) PreListen(*iris.Framework) {
	fmt.Println("PreListen Struct")
	t.prelistenran = true
}

func (t *testPluginEx) PostListen(*iris.Framework) {
	fmt.Println("PostListen Struct")
	t.postlistenran = true
}

func (t *testPluginEx) PreClose(*iris.Framework) {
	fmt.Println("PreClose Struct")
	t.precloseran = true
}

func ExamplePlugins_Add() {
	iris.ResetDefault()
	iris.Default.Set(iris.OptionDisableBanner(true))
	iris.Plugins.Add(iris.PreListenFunc(func(*iris.Framework) {
		fmt.Println("PreListen Func")
	}))

	iris.Plugins.Add(iris.PostListenFunc(func(*iris.Framework) {
		fmt.Println("PostListen Func")
	}))

	iris.Plugins.Add(iris.PreCloseFunc(func(*iris.Framework) {
		fmt.Println("PreClose Func")
	}))

	myplugin := &testPluginEx{}
	iris.Plugins.Add(myplugin)
	desc := iris.Plugins.GetDescription(myplugin)
	fmt.Println(desc)

	// travis have problems if I do that using
	// Listen(":8080") and Close()
	iris.Plugins.DoPreListen(iris.Default)
	iris.Plugins.DoPostListen(iris.Default)
	iris.Plugins.DoPreClose(iris.Default)

	// Output:
	// GetName Struct
	// Activate Struct
	// GetDescription Struct
	// Description for My test plugin
	// PreListen Func
	// PreListen Struct
	// PostListen Func
	// PostListen Struct
	// PreClose Func
	// PreClose Struct
}

// if a plugin has GetName, then it should be registered only one time, the name exists for that reason, it's like unique  ID
func TestPluginDublicateName(t *testing.T) {
	iris.ResetDefault()
	var plugins = iris.Default.Plugins
	firstNamedPlugin := &testPluginEx{}
	sameNamedPlugin := &testPluginEx{}
	// err := plugins.Add(firstNamedPlugin, sameNamedPlugin) or
	err := plugins.Add(firstNamedPlugin)
	if err != nil {
		t.Fatalf("Unexpected error when adding a plugin with name: %s", testPluginExName)
	}
	err = plugins.Add(sameNamedPlugin)
	if err == nil {
		t.Fatalf("Expected an error because of dublicate named plugin!")
	}
	if plugins.Len() != 1 {
		t.Fatalf("Expected: %d activated plugin but we got: %d", 1, plugins.Len())
	}
}

type testPluginActivationType struct {
	shouldError bool
}

func (t testPluginActivationType) Activate(p iris.PluginContainer) error {
	p.Add(&testPluginEx{})
	if t.shouldError {
		return fmt.Errorf("An error happens, this plugin and the added plugins by this plugin should not be registered")
	}
	return nil
}

func TestPluginActivate(t *testing.T) {
	iris.ResetDefault()
	var plugins = iris.Default.Plugins
	myplugin := testPluginActivationType{shouldError: false}
	plugins.Add(myplugin)

	if plugins.Len() != 2 { // 2 because it registeres a second plugin also
		t.Fatalf("Expected activated plugins to be: %d but we got: %d", 0, plugins.Len())
	}
}

// if any error returned from the Activate plugin's method, then this plugin and the plugins it registers should not be registered at all
func TestPluginActivationError(t *testing.T) {
	iris.ResetDefault()
	var plugins = iris.Default.Plugins
	myplugin := testPluginActivationType{shouldError: true}
	plugins.Add(myplugin)

	if plugins.Len() > 0 {
		t.Fatalf("Expected activated plugins to be: %d but we got: %d", 0, plugins.Len())
	}
}

func TestPluginEvents(t *testing.T) {
	iris.ResetDefault()
	var plugins = iris.Default.Plugins
	var prelistenran, postlistenran, precloseran bool

	plugins.Add(iris.PreListenFunc(func(*iris.Framework) {
		prelistenran = true
	}))

	plugins.Add(iris.PostListenFunc(func(*iris.Framework) {
		postlistenran = true
	}))

	plugins.Add(iris.PreCloseFunc(func(*iris.Framework) {
		precloseran = true
	}))

	myplugin := &testPluginEx{}
	plugins.Add(myplugin)
	if plugins.Len() != 4 {
		t.Fatalf("Expected: %d plugins to be registed but we got: %d", 4, plugins.Len())
	}
	desc := plugins.GetDescription(myplugin)
	if desc != testPluginExDescription {
		t.Fatalf("Expected: %s as Description of the plugin but got: %s", testPluginExDescription, desc)
	}

	plugins.DoPreListen(nil)
	plugins.DoPostListen(nil)
	plugins.DoPreClose(nil)

	if !prelistenran {
		t.Fatalf("Expected to run PreListen Func but it doesn't!")
	}
	if !postlistenran {
		t.Fatalf("Expected to run PostListen Func but it doesn't!")
	}
	if !precloseran {
		t.Fatalf("Expected to run PostListen Func but it doesn't!")
	}

	if !myplugin.named {
		t.Fatalf("Plugin should be named with: %s!", testPluginExName)
	}
	if !myplugin.activated {
		t.Fatalf("Plugin should be activated but it's not!")
	}
	if !myplugin.prelistenran {
		t.Fatalf("Expected to run PreListen Struct but it doesn't!")
	}
	if !myplugin.postlistenran {
		t.Fatalf("Expected to run PostListen Struct but it doesn't!")
	}
	if !myplugin.precloseran {
		t.Fatalf("Expected to run PostListen Struct but it doesn't!")
	}

}