text:
C automata library to build, determinize, minimize, translate regexp etc

### Requirements

- GCC or Clang, yacc and lex
- PCRE is used in regression tests to compare matching with PCRE
- graphviz if you want to visualize automatons

Ubuntu/Debian: `apt-get install bison flex libpcre3-dev graphviz`
Brew (Mac OS X): `brew install bison pcre graphviz`

### Build

To build run `make`, to run tests `make test`

### Example usage

See [faexample.c](faexample.c) for full example.

```c
// create union NFA of two regexp NFAs
fa_t *a_fa = fa_regexp_fa("^aa*$", &errstr, &errpos, NULL);
// assign 0 to all accepting states for first regexp
fa_set_accepting_opaque(a_fa, (void *)0);
fa_t *b_fa = fa_regexp_fa("^a(a|b)$", &errstr, &errpos, NULL);
// assign 1 to all accepting states for second regexp
fa_set_accepting_opaque(b_fa, (void *)1);
fa_t *union_fa = fa_union(a_fa, b_fa);
fa_graphviz_output(union_fa, "union.dot", NULL);
```
![](doc/union.png)
```c
// determinize and choose lowest opaque number when more than one opaque
// value end up in same accepting state.
// this happens when two regexps are overlapping.
fa_t *dfa = fa_determinize_ex(union_fa, state_pri, NULL, NULL);
fa_graphviz_output(dfa, "dfa.dot", NULL);
```
![](doc/dfa.png)
```c
// minimize and treat states with different opaque values as distinguishable.
// this is to be able to know which original regexp has a match when using
// the minimized DFA
fa_t *mdfa = fa_minimize_ex(dfa, state_cmp, NULL);
fa_graphviz_output(mdfa, "mdfa.dot", NULL);
```
![](doc/mdfa.png)
```c
// convert minimal DFA into format suitable for running it on input
fa_sim_t *sim = fa_sim_create(mdfa);
fa_sim_run_t fsr;
fa_sim_run_init(sim, &fsr);
if (fa_sim_run(sim, &fsr, (uint8_t *)"aa", 2) == FA_SIM_RUN_ACCEPT)
  printf("matches %p\n", fsr.opaque); // outputs matches 0x0
fa_sim_run_init(sim, &fsr);
if (fa_sim_run(sim, &fsr, (uint8_t *)"ab", 2) == FA_SIM_RUN_ACCEPT)
  printf("matches %p\n", fsr.opaque); // outputs matches 0x1
```
```shell
$ ./faexample
matches 0x0
matches 0x1
```

### Using fatool

Minimal `--min` DFA `--det` that can match regular expression
`^[df]{2}a+$` and `^(dfa)*$` and know which one was matched. First `--in` has
priority.

```shell
./fatool --in 're:^[df]{2}a+$' --in 're:^(dfa)*$' --out dot:- --dfa --min | \
  dot -Gdpi=70 -Tpng -odoc/fatool.png /dev/stdin
```

![](doc/fatool.png)

### Regular expressions

Regular expression syntax tries to be compatible with PCRE with some known
exceptions:

 - No capture groups
 - No back references (not regular)
 - No greediness options (only needed with capture groups?)
 - `[a-^]` or `[^-a]` does not work, use `[a-\^]` instead
 - `(?)` options only support `i`
 - `\x{hhh...}` not supported
 - `\b \B \A \Z \z \G \C \X \p \P` not supported
 - `.` matches any byte
 - `^ab|c$` is matched as `^ab$|c$`

libfa regular expressions have support for matching at bit level using
`(?B<constant>:<bit length>[, ...])` syntax. Constants are matched big-endian
and are limited by the bit length if specified. Max bit length is 32. The sum
of bit lengths must be byte aligned.

The binary syntax support these variants:

- `^(?B32)` or `(?B0x20)` matches a byte of value 32 (bit length defaults to 8)
- `^(?B:4,0xf:4)$` first 4 bit can be anything, last must all be ones.

### Author

Mattias Wadman <mattias.wadman@gmail.com>


text:
==============
Redfish driver
==============

Overview
========

The ``redfish`` driver enables managing servers compliant with the
Redfish_ protocol.

Prerequisites
=============

* The Sushy_ library should be installed on the ironic conductor node(s).

  For example, it can be installed with ``pip``::

      sudo pip install sushy

Enabling the Redfish driver
===========================

#. Add ``redfish`` to the list of ``enabled_hardware_types``,
   ``enabled_power_interfaces`` and ``enabled_management_interfaces``
   in ``/etc/ironic/ironic.conf``. For example::

    [DEFAULT]
    ...
    enabled_hardware_types = ipmi,redfish
    enabled_power_interfaces = ipmitool,redfish
    enabled_management_interfaces = ipmitool,redfish

#. Restart the ironic conductor service::

    sudo service ironic-conductor restart

    # Or, for RDO:
    sudo systemctl restart openstack-ironic-conductor

Registering a node with the Redfish driver
===========================================

Nodes configured to use the driver should have the ``driver`` property
set to ``redfish``.

The following properties are specified in the node's ``driver_info``
field:

- ``redfish_address``: The URL address to the Redfish controller. It must
                       include the authority portion of the URL, and can
                       optionally include the scheme. If the scheme is
                       missing, https is assumed.
                       For example: https://mgmt.vendor.com. This is required.

- ``redfish_system_id``: The canonical path to the System resource that
                         the driver will interact with. It should include
                         the root service, version and the unique
                         resource path to the System. For example:
                         /redfish/v1/Systems/1. This is required.

- ``redfish_username``: User account with admin/server-profile access
                        privilege. Although not required, it is highly
                        recommended.

- ``redfish_password``: User account password. Although not required, it is
                        highly recommended.

- ``redfish_verify_ca``: If redfish_address has the **https** scheme, the
                         driver will use a secure (TLS_) connection when
                         talking to the Redfish controller. By default
                         (if this is not set or set to True), the driver
                         will try to verify the host certificates. This
                         can be set to the path of a certificate file or
                         directory with trusted certificates that the
                         driver will use for verification. To disable
                         verifying TLS_, set this to False. This is optional.

The ``openstack baremetal node create`` command can be used to enroll
a node with the ``redfish`` driver. For example:

.. code-block:: bash

  openstack baremetal node create --driver redfish --driver-info \
    redfish_address=https://example.com --driver-info \
    redfish_system_id=/redfish/v1/Systems/CX34R87 --driver-info \
    redfish_username=admin --driver-info redfish_password=password

For more information about enrolling nodes see :ref:`enrollment`
in the install guide.

.. _Redfish: http://redfish.dmtf.org/
.. _Sushy: https://git.openstack.org/cgit/openstack/sushy
.. _TLS: https://en.wikipedia.org/wiki/Transport_Layer_Security

redpajama_set_name: RedPajamaGithub


text:
/**
 * A server collection collection_decks_server handler.
 */
define([ 'framework/request/base_request_handler',
		 '../collection_decks_server_request',
		 'framework/core/deferred/deferred' ],
function(BaseRequestHandler,
		 CollectionDecksServerRequest,
		 Deferred)
{
	var CollectionDecksServerHandler = BaseRequestHandler.create(CollectionDecksServerRequest,
			[ 'deckRepository' ]);

	// @override
	CollectionDecksServerHandler.prototype.execute = function(requestContext, request, response)
	{
		var format = request.getFormat() || 'standard';

		return this._remotePromise(requestContext, this._deckRepository.getByUserIdAndFormat(requestContext.getUserId(), format)).then(function(decks)
		{
			response.setDecks(decks || []);

			return Deferred.resolvedPromise(requestContext);
		});
	};

	return CollectionDecksServerHandler;
});


text:
package org.omg.PortableInterceptor;

/**
* org/omg/PortableInterceptor/TRANSPORT_RETRY.java .
* Generated by the IDL-to-Java compiler (portable), version "3.2"
* from c:/workspace/8-2-build-windows-amd64-cygwin/jdk8u65/4987/corba/src/share/classes/org/omg/PortableInterceptor/Interceptors.idl
* Tuesday, October 6, 2015 4:40:34 PM PDT
*/

public interface TRANSPORT_RETRY
{

  /**
   * Indicates a Transport Retry reply status. One possible value for
   * RequestInfo.reply_status.
   * @see RequestInfo#reply_status
   * @see SUCCESSFUL
   * @see SYSTEM_EXCEPTION
   * @see USER_EXCEPTION
   * @see LOCATION_FORWARD
   */
  public static final short value = (short)(4);
}


text:
package edu.jhuapl.sages.mobile.lib.message;

/**
 *
 * @author sages
 * @date 05/06/13
 *
 */
public class SagesMessageHeader {

	private String header;

	/**
	 * SagesMessageHeader constructor
	 * @param header
	 */
	public SagesMessageHeader(String header) {
		super();
		this.header = header;
	}

	/**
	 * @return the header
	 */
	public String getHeader() {
		return header;
	}

	/**
	 * @param header the header to set
	 */
	public void setHeader(String header) {
		this.header = header;
	}

}


text:
package org.domeos.framework.api.biz.alarm;

import org.domeos.framework.api.biz.base.BaseBiz;
import org.domeos.framework.api.model.alarm.HostGroupInfoBasic;
import org.domeos.framework.api.model.alarm.StrategyInfo;
import org.domeos.framework.api.consolemodel.alarm.TemplateInfo;
import org.domeos.framework.api.model.alarm.falcon.portal.Action;
import org.domeos.framework.api.model.alarm.falcon.portal.GroupTemplate;

import java.util.List;

/**
 * Created by baokangwang on 2016/4/14.
 */
public interface PortalBiz extends BaseBiz {

    // host

    Integer getHostIdByHostname(String hostname);

    // group

    void insertHostGroupByHostGroupBasicInfo(HostGroupInfoBasic hostGroupInfoBasic);

    void updateHostGroupByHostGroupBasicInfo(HostGroupInfoBasic hostGroupInfoBasic);

    void deleteHostGroupById(long id);

    String getHostGroupList();

    // template

    void insertTemplateByTemplateInfo(TemplateInfo templateInfo);

    void updateTemplateByTemplateInfo(TemplateInfo templateInfo);

    void deleteTemplateByIdAndType(long templateId, String templateType);

    void updateDeployAlarmPortal(long templateId, int deployId, List<StrategyInfo> strategyInfos);

    // group host bind

    void insertGroupHostBind(long grp_id, long host_id);

    void deleteGroupHostBind(long grp_id, long host_id);

    void deleteGroupHostBindByGroupId(long grp_id);

    // group template bind

    void insertGroupTemplateBind(GroupTemplate groupTemplate);

    // action

    Action getActionById(long id);

    // mockcfg

    void updateNodataObj(String groups);
}


text:
#include "third_party/blink/renderer/core/layout/svg/layout_svg_text_path.h"

#include "third_party/blink/renderer/core/layout/svg/svg_layout_support.h"
#include "third_party/blink/renderer/core/svg/svg_animated_length.h"
#include "third_party/blink/renderer/core/svg/svg_path_element.h"
#include "third_party/blink/renderer/core/svg/svg_text_path_element.h"
#include "third_party/blink/renderer/platform/graphics/path.h"

namespace blink {

PathPositionMapper::PathPositionMapper(const Path& path,
                                       float computed_path_length,
                                       float start_offset)
    : position_calculator_(path),
      path_length_(computed_path_length),
      path_start_offset_(start_offset) {}

PathPositionMapper::PositionType PathPositionMapper::PointAndNormalAtLength(
    float length,
    PointAndTangent& point_and_tangent) {
  if (length < 0)
    return kBeforePath;
  if (length > path_length_)
    return kAfterPath;
  DCHECK_GE(length, 0);
  DCHECK_LE(length, path_length_);

  point_and_tangent = position_calculator_.PointAndNormalAtLength(length);
  return kOnPath;
}

LayoutSVGTextPath::LayoutSVGTextPath(Element* element)
    : LayoutSVGInline(element) {}

bool LayoutSVGTextPath::IsChildAllowed(LayoutObject* child,
                                       const ComputedStyle&) const {
  NOT_DESTROYED();
  if (child->IsText())
    return SVGLayoutSupport::IsLayoutableTextNode(child);

  return child->IsSVGInline() && !child->IsSVGTextPath();
}

std::unique_ptr<PathPositionMapper> LayoutSVGTextPath::LayoutPath() const {
  NOT_DESTROYED();
  const auto& text_path_element = To<SVGTextPathElement>(*GetNode());
  Element* target_element = SVGURIReference::TargetElementFromIRIString(
      text_path_element.HrefString(), text_path_element.OriginatingTreeScope());

  const auto* path_element = DynamicTo<SVGPathElement>(target_element);
  if (!path_element)
    return nullptr;

  Path path_data = path_element->AsPath();
  if (path_data.IsEmpty())
    return nullptr;

  // Spec: The 'transform' attribute on the referenced 'path' ...
  // element represents a supplemental transformation relative to the current
  // user coordinate system for the current 'text' element, including any
  // adjustments to the current user coordinate system due to a possible
  // 'transform' property on the current 'text' element.
  // https://svgwg.org/svg2-draft/text.html#TextPathElement
  path_data.Transform(
      path_element->CalculateTransform(SVGElement::kIncludeMotionTransform));

  // Determine the length to resolve any percentage 'startOffset'
  // against - either 'pathLength' (author path length) or the
  // computed length of the path.
  float computed_path_length = path_data.length();
  float author_path_length = path_element->AuthorPathLength();
  float offset_scale = 1;
  if (!std::isnan(author_path_length)) {
    offset_scale = SVGGeometryElement::PathLengthScaleFactor(
        computed_path_length, author_path_length);
  } else {
    author_path_length = computed_path_length;
  }

  const SVGLength& start_offset =
      *text_path_element.startOffset()->CurrentValue();
  float path_start_offset = start_offset.ValueAsPercentage();
  if (start_offset.IsPercentage())
    path_start_offset *= author_path_length;

  path_start_offset *= offset_scale;

  return std::make_unique<PathPositionMapper>(path_data, computed_path_length,
                                              path_start_offset);
}

}  // namespace blink


text:
package tlfhandle

import (
	"context"

	"github.com/keybase/client/go/kbfs/tlf"
)

// IDGetter is an interface for resolving TLF handles to their TLF IDs.
type IDGetter interface {
	// GetIDForHandle returns the tlf.ID associated with the given
	// handle, if the logged-in user has read permission on the
	// folder.  It may or may not create the folder if it doesn't
	// exist yet, and it may return `tlf.NullID` with a `nil` error if
	// it doesn't create a missing folder.
	GetIDForHandle(ctx context.Context, handle *Handle) (tlf.ID, error)
	// ValidateLatestHandleForTLF returns true if the TLF ID contained
	// in `h` does not currently map to a finalized TLF.
	ValidateLatestHandleNotFinal(ctx context.Context, h *Handle) (
		bool, error)
}


text:
var sira = require('../');
var s = require('./support');
var t = s.t;

describe('hidden properties', function () {

    var sapp, Product, Category;

    beforeEach(function (done) {
        sapp = sira();
        sapp.registry.define('Product', {
            crud: true,
            hidden: ['secret'],
            properties: {
                name: String,
                secret: String
            }
        });
        sapp.registry.define('Category', {
            crud: true,
            properties: {
                name: String
            },
            relations: {
                products: {
                    type: "hasMany",
                    model: "Product"
                }
            }
        });
        sapp.phase(sira.boot.database());
        sapp.boot(function (err) {
            if (err) return done(err);
            Category = sapp.model('Category');
            Product = sapp.model('Product');

            Category.create({
                name: 'my category'
            }, function (err, category) {
                category.products.create({
                    name: 'pencil',
                    secret: 'a secret'
                }, done);
            });
        });
    });

    afterEach(function (done) {
        Category.destroyAll(function () {
            Product.destroyAll(done);
        });
    });

    it('should hide a property remotely', function (done) {
        sapp.rekuest('product.all').send(function (err, result) {
            if (err) return done(err);
            var product = result[0].toJSON();
            t.equal(product.name, 'pencil');
            t.equal(product.secret, undefined);
            done();
        });
    });

    it('should hide a property of nested models', function (done) {
        sapp.rekuest('category.all', {filter: {include: 'products'}}).send(function (err, result) {
            if (err) return done(err);
            var category = result[0].toJSON();
            var product = category.products[0];
            t.equal(product.name, 'pencil');
            t.equal(product.secret, undefined);
            done();
        });
    });
});


text:
package com.eaw1805.data.model.army;

import com.eaw1805.data.model.map.CarrierInfo;

import java.io.Serializable;

/**
 * Represents a battalion.
 */
public class Battalion implements Serializable {

    /**
     * Required by Serializable interface.
     */
    static final long serialVersionUID = 42L; //NOPMD

    /**
     * The unique identifier of the battalion.
     */
    private int id; // NOPMD

    /**
     * The order of the battalion in the brigade.
     */
    private int order;

    /**
     * The type of the troops.
     */
    private com.eaw1805.data.model.army.ArmyType type;

    /**
     * The experience level of the battalion.
     */
    private int experience;

    /**
     * The headcount of the battalion.
     */
    private int headcount;

    /**
     * The brigade that this battalion belongs to.
     */
    private Brigade brigade;

    /**
     * used temporarily during battles. this field does not persist.
     * Used in the battle to check if the battalion has passed the morale check.
     */
    private boolean fleeing;

    /**
     * used temporarily during battles. this field does not persist.
     */
    private boolean attackedByCav;

    /**
     * used temporarily during battles. this field does not persist.
     * Used in the battle to check if the experience of this unit
     * is increased by the commander's skill.
     */
    private boolean expIncByComm;

    /**
     * used temporarily during battles. this field does not persist.
     * Used in the battle to check if the particular unit has participated
     * in a round of the battle.
     */
    private boolean participated;

    /**
     * used temporarily during battles. this field does not persist.
     * Used in the battle to check if the battalion was unloaded for the battle.
     */
    private boolean unloaded;

    /**
     * used to determine if a battalion has moved during the turn.
     */
    private boolean hasMoved;

    /**
     * used to determine if a battalion will engage to battle due to its movement.
     */
    private boolean hasEngagedBattle;

    /**
     * used to determine if a battalion has lost a battle during the turn.
     */
    private boolean hasLost;

    /**
     * used to determine if a battalion is not properly supplied.
     */
    private boolean notSupplied;

    /**
     * The unit that is transferring the battalion.
     */
    private CarrierInfo carrierInfo;

    /**
     * Get the unique identifier of the battalion.
     *
     * @return the unique identifier of the battalion.
     */
    public int getId() {
        return id;
    }

    /**
     * Set the unique identifier of the battalion.
     *
     * @param identity the unique identifier of the battalion.
     */
    public void setId(final int identity) {
        this.id = identity;
    }

    /**
     * The order of the battalion in the brigade.
     *
     * @return the order of the battalion in the brigade.
     */
    public int getOrder() {
        return order;
    }

    /**
     * Set the order of the battalion in the brigade.
     *
     * @param value The order of the battalion in the brigade.
     */
    public void setOrder(final int value) {
        this.order = value;
    }

    /**
     * Get the type of the troops.
     *
     * @return the type of the troops.
     */
    public com.eaw1805.data.model.army.ArmyType getType() {
        return type;
    }

    /**
     * Set the thisType of the troops.
     *
     * @param thisType the thisType of the troops.
     */
    public void setType(final com.eaw1805.data.model.army.ArmyType thisType) {
        this.type = thisType;
    }

    /**
     * Get experience level of the battalion.
     *
     * @return the experience level of the battalion.
     */
    public int getExperience() {
        return experience;
    }

    /**
     * Set the thisExperience level of the battalion.
     *
     * @param thisExperience the thisExperience level of the battalion.
     */
    public void setExperience(final int thisExperience) {
        this.experience = thisExperience;
    }

    /**
     * Get the headcount of the battalion.
     *
     * @return the headcount of the battalion.
     */
    public int getHeadcount() {
        return headcount;
    }

    /**
     * Set the thisHeadcount of the battalion.
     *
     * @param thisHeadcount the thisHeadcount of the battalion.
     */
    public void setHeadcount(final int thisHeadcount) {
        this.headcount = thisHeadcount;
    }

    /**
     * Get the brigade this battalion belongs to.
     *
     * @return the brigade this battalion belongs to.
     */
    public Brigade getBrigade() {
        return brigade;
    }

    /**
     * Set the brigade this battalion belongs to.
     *
     * @param value the brigade this battalion belongs to.
     */
    public void setBrigade(final Brigade value) {
        this.brigade = value;
    }

    /**
     * Check if the unit is fleeing.
     *
     * @return true if the unit is fleeing.
     */
    public boolean isFleeing() {
        return fleeing;
    }

    /**
     * Set if the unit is fleeing.
     *
     * @param value true if the unit is fleeing.
     */
    public void setFleeing(final boolean value) {
        fleeing = value;
    }

    /**
     * Check if the unit is being attacked by cavalry.
     *
     * @return true if the unit is being attacked by cavalry.
     */
    public boolean isAttackedByCav() {
        return attackedByCav;
    }

    /**
     * Set if the unit is being attacked by cavalry.
     *
     * @param value true if the unit is being attacked by cavalry.
     */
    public void setAttackedByCav(final boolean value) {
        this.attackedByCav = value;
    }

    /**
     * Check if the unit's experience is increased by the commander.
     *
     * @return true if the unit's experience is increased by the commander.
     */
    public boolean getExpIncByComm() {
        return expIncByComm;
    }

    /**
     * Set if the unit's experience is increased by the commander.
     *
     * @param value true if the unit's experience is increased by the commander.
     */
    public void setExpIncByComm(final boolean value) {
        this.expIncByComm = value;
    }

    /**
     * Get if the particular unit has participated in a round of the battle.
     *
     * @return true, if the particular unit has participated in a round of the battle.
     */
    public boolean isParticipated() {
        return participated;
    }

    /**
     * Set if the particular unit has participated in a round of the battle.
     *
     * @param value true, if the particular unit has participated in a round of the battle.
     */
    public void setParticipated(final boolean value) {
        participated = value;
    }

    /**
     * Used in the battle to check if the battalion was unloaded for the battle.
     * @return true if the battalion was unloaded for the battle.
     */
    public boolean getUnloaded() {
        return unloaded;
    }

    /**
     Used in the battle to check if the battalion was unloaded for the battle.
     * @param value true if the battalion was unloaded for the battle.
     */
    public void setUnloaded(final boolean value) {
        this.unloaded = value;
    }

    /**
     * Get if the battalion has moved during the turn.
     *
     * @return true, if the battalion has moved during the turn.
     */
    public boolean getHasMoved() {
        return hasMoved;
    }

    /**
     * Set if the battalion has moved during the turn.
     *
     * @param value true, if the battalion has moved during the turn.
     */
    public void setHasMoved(final boolean value) {
        this.hasMoved = value;
    }

    /**
     * Get if a battalion engaged to battle due to its movement.
     *
     * @return true, if a battalion engaged to battle due to its movement.
     */
    public boolean getHasEngagedBattle() {
        return hasEngagedBattle;
    }

    /**
     * Set if a battalion engaged to battle due to its movement.
     *
     * @param value true, if a battalion engaged to battle due to its movement.
     */
    public void setHasEngagedBattle(final boolean value) {
        this.hasEngagedBattle = value;
    }

    /**
     * Get if the battalion is not properly supplied.
     *
     * @return true, if the battalion is not properly supplied.
     */
    public boolean getNotSupplied() {
        return notSupplied;
    }

    /**
     * Get if the battalion has lost a battle during the turn.
     *
     * @return if the battalion has lost a battle during the turn.
     */
    public boolean getHasLost() {
        return hasLost;
    }

    /**
     * Set if the battalion has lost a battle during the turn.
     *
     * @param value if the battalion has lost a battle during the turn.
     */
    public void setHasLost(final boolean value) {
        this.hasLost = value;
    }

    /**
     * Set if the battalion is not properly supplied.
     *
     * @param value true, if the battalion is not properly supplied.
     */
    public void setNotSupplied(final boolean value) {
        this.notSupplied = value;
    }

    /**
     * Get the unit that is transferring the spy.
     *
     * @return the unit that is transferring the spy.
     */
    public CarrierInfo getCarrierInfo() {
        return carrierInfo;
    }

    /**
     * Set the unit that is transferring the spy.
     *
     * @param value the unit that is transferring the spy.
     */
    public void setCarrierInfo(final CarrierInfo value) {
        this.carrierInfo = value;
    }

    @Override
    public Object clone() {
        final Battalion bat = new Battalion();
        bat.setId(getId());
        bat.setOrder(getOrder());
        bat.setType(getType());
        bat.setExperience(getExperience());
        bat.setHeadcount(getHeadcount());
        bat.setBrigade(getBrigade());
        bat.setFleeing(isFleeing());
        bat.setAttackedByCav(isAttackedByCav());
        bat.setExpIncByComm(getExpIncByComm());
        bat.setParticipated(isParticipated());
        bat.setHasMoved(getHasMoved());
        bat.setHasLost(getHasLost());
        bat.setNotSupplied(getNotSupplied());
        bat.setHasEngagedBattle(getHasEngagedBattle());

        final CarrierInfo thisCarrierInfo = new CarrierInfo();
        thisCarrierInfo.setCarrierType(getCarrierInfo().getCarrierType());
        thisCarrierInfo.setCarrierId(getCarrierInfo().getCarrierId());
        bat.setCarrierInfo(thisCarrierInfo);

        return bat;
    }
}


text:
from django.conf import settings
import datetime
import urllib

from django.contrib import auth
from django.core.exceptions import ImproperlyConfigured
from django.db import models
from django.db.models.manager import EmptyManager
from django.contrib.contenttypes.models import ContentType
from django.utils.encoding import smart_str
from django.utils.hashcompat import md5_constructor, sha_constructor
from django.utils.translation import ugettext_lazy as _
from google.appengine.ext import db
from ragendja.dbutils import FakeModelListProperty, KeyListProperty
from string import ascii_letters, digits
import hashlib, random

UNUSABLE_PASSWORD = '!' # This will never be a valid hash

try:
    set
except NameError:
    from sets import Set as set   # Python 2.3 fallback

def get_hexdigest(algorithm, salt, raw_password):
    """
    Returns a string of the hexdigest of the given plaintext password and salt
    using the given algorithm ('md5', 'sha1' or 'crypt').
    """
    raw_password, salt = smart_str(raw_password), smart_str(salt)
    if algorithm == 'crypt':
        try:
            import crypt
        except ImportError:
            raise ValueError('"crypt" password algorithm not supported in this environment')
        return crypt.crypt(raw_password, salt)

    if algorithm == 'md5':
        return md5_constructor(salt + raw_password).hexdigest()
    elif algorithm == 'sha1':
        return sha_constructor(salt + raw_password).hexdigest()
    raise ValueError("Got unknown password algorithm type in password.")

def gen_hash(password, salt=None, algorithm='sha512'):
    hash = hashlib.new(algorithm)
    hash.update(smart_str(password))
    if salt is None:
        salt = ''.join([random.choice(ascii_letters + digits) for _ in range(8)])
    hash.update(salt)
    return (algorithm, salt, hash.hexdigest())

def check_password(raw_password, enc_password):
    """
    Returns a boolean of whether the raw_password was correct. Handles
    encryption formats behind the scenes.
    """
    try:
        algo, salt, hsh = enc_password.split('$')
    except:
        raise ValueError("You've mistakenly set the password directly. Please use set_password() instead.")
    if algo == 'sha512':
        return hsh == gen_hash(raw_password, salt, algo)[-1]
    return hsh == get_hexdigest(algo, salt, raw_password)

class SiteProfileNotAvailable(Exception):
    pass

class Permission(object):
    """The permissions system provides a way to assign permissions to specific users and groups of users.

    The permission system is used by the Django admin site, but may also be useful in your own code. The Django admin site uses permissions as follows:

        - The "add" permission limits the user's ability to view the "add" form and add an object.
        - The "change" permission limits a user's ability to view the change list, view the "change" form and change an object.
        - The "delete" permission limits the ability to delete an object.

    Permissions are set globally per type of object, not per specific object instance. It is possible to say "Mary may change news stories," but it's not currently possible to say "Mary may change news stories, but only the ones she created herself" or "Mary may only change news stories that have a certain status or publication date."

    Three basic permissions -- add, change and delete -- are automatically created for each Django model.
    """
    def __init__(self, name=None, content_type=None, codename=None):
        self.name, self.content_type = name, content_type
        self.codename = codename

    def __repr__(self):
        return '<%s: %s>' % (self.__class__.__name__, unicode(self))

    def __unicode__(self):
        return u"%s | %s | %s" % (
            unicode(self.content_type.app_label),
            unicode(self.content_type),
            unicode(self.name))

    @classmethod
    def all(cls):
        return cls.get_permissions()

    def get_value_for_datastore(self):
        return '%s.%s' % (self.content_type.app_label, self.codename)

    @classmethod
    def make_value_from_datastore(cls, value):
        app_label, codename = value.split('.', 1)
        perms = [perm for perm in cls.get_permissions(app_label)
                 if perm.codename == codename]
        if perms:
            return perms[0]
        return Permission(codename=codename,
            content_type=ContentType(app_label=app_label, model='Unknown',
                                     name='Unknown'),
            name=codename + ' (Unknown)')

    @classmethod
    def get_permissions(cls, app_label=None, model_name=None):
        permissions = []
        from django.db.models.loading import get_models
        for model in get_models():
            for permission in model._meta.permissions:
                if app_label and app_label != model._meta.app_label or \
                        model_name and model_name != model._meta.object_name:
                    continue
                content_type = ContentType.objects.get_for_model(model)
                permissions.append(
                    Permission(codename=permission[0], name=permission[1],
                               content_type=content_type))
        return permissions

class Group(db.Model):
    """Groups are a generic way of categorizing users to apply permissions, or some other label, to those users. A user can belong to any number of groups.

    A user in a group automatically has all the permissions granted to that group. For example, if the group Site editors has the permission can_edit_home_page, any user in that group will have that permission.

    Beyond permissions, groups are a convenient way to categorize users to apply some label, or extended functionality, to them. For example, you could create a group 'Special users', and you could write code that would do special things to those users -- such as giving them access to a members-only portion of your site, or sending them members-only e-mail messages.
    """
    name = db.StringProperty(required=True, verbose_name=_('name'))
    permissions = FakeModelListProperty(Permission,
        verbose_name=_('permissions'))

    class Meta:
        verbose_name = _('group')
        verbose_name_plural = _('groups')

    def __repr__(self):
        return '<%s: %s>' % (self.__class__.__name__, unicode(self))

    def __unicode__(self):
        return self.name

class AnonymousUser(object):
    id = None
    username = ''
    is_staff = False
    is_active = False
    is_superuser = False
    _groups = EmptyManager()
    _user_permissions = EmptyManager()

    def __init__(self):
        pass

    def __unicode__(self):
        return 'AnonymousUser'

    def __str__(self):
        return unicode(self).encode('utf-8')

    def __eq__(self, other):
        return isinstance(other, self.__class__)

    def __ne__(self, other):
        return not self.__eq__(other)

    def __hash__(self):
        return 1 # instances always return the same hash value

    def save(self):
        raise NotImplementedError

    def delete(self):
        raise NotImplementedError

    def set_password(self, raw_password):
        raise NotImplementedError

    def check_password(self, raw_password):
        raise NotImplementedError

    def _get_groups(self):
        return self._groups
    groups = property(_get_groups)

    def _get_user_permissions(self):
        return self._user_permissions
    user_permissions = property(_get_user_permissions)

    def has_perm(self, perm):
        return False

    def has_perms(self, perm_list):
        return False

    def has_module_perms(self, module):
        return False

    def get_and_delete_messages(self):
        return []

    def is_anonymous(self):
        return True

    def is_authenticated(self):
        return False

class UserManager(models.Manager):
    def create_user(self, username, email, password=None):
        "Creates and saves a User with the given username, e-mail and password."
        now = datetime.datetime.now()
        # Check if username is already taken
        count = User.all().filter('username =', username).count(1)
        if count:
            from django.db import IntegrityError
            raise IntegrityError('username already taken')
        user = User(username=username, email=email.strip().lower())
        if password:
            user.set_password(password)
        else:
            user.set_unusable_password()
        user.save()
        # Check for race condition (two users register at the same time)
        count = User.all().filter('username =', username).count(2)
        if count == 2:
            user.delete()
            from django.db import IntegrityError
            raise IntegrityError('username already taken')
        return user

    def create_superuser(self, username, email, password):
        u = self.create_user(username, email, password)
        u.is_staff = True
        u.is_active = True
        u.is_superuser = True
        u.save()
        return u

    def make_random_password(self, length=10, allowed_chars='abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789'):
        "Generates a random password with the given length and given allowed_chars"
        # Note that default value of allowed_chars does not have "I" or letters
        # that look like it -- just to avoid confusion.
        from random import choice
        return ''.join([choice(allowed_chars) for i in range(length)])

class UserTraits(db.Model):
    last_login = db.DateTimeProperty(verbose_name=_('last login'))
    date_joined = db.DateTimeProperty(auto_now_add=True,
        verbose_name=_('date joined'))
    is_active = db.BooleanProperty(default=True, verbose_name=_('active'))
    is_staff = db.BooleanProperty(default=False,
        verbose_name=_('staff status'))
    is_superuser = db.BooleanProperty(default=False,
        verbose_name=_('superuser status'))
    password = db.StringProperty(default=UNUSABLE_PASSWORD,
        verbose_name=_('password'))
    groups = KeyListProperty(Group, verbose_name=_('groups'))
    user_permissions = FakeModelListProperty(Permission,
        verbose_name=_('user permissions'))

    objects = UserManager()

    class Meta:
        abstract = True

    def is_anonymous(self):
        "Always returns False. This is a way of comparing User objects to anonymous users."
        return False

    def is_authenticated(self):
        """Always return True. This is a way to tell if the user has been authenticated in templates.
        """
        return True

    def get_full_name(self):
        "Returns the first_name plus the last_name, with a space in between."
        full_name = u'%s %s' % (self.first_name, self.last_name)
        return full_name.strip()

    def set_password(self, raw_password):
        import random
        algo = 'sha1'
        salt = get_hexdigest(algo, str(random.random()), str(random.random()))[:5]
        hsh = get_hexdigest(algo, salt, raw_password)
        self.password = '%s$%s$%s' % (algo, salt, hsh)

    def check_password(self, raw_password):
        """
        Returns a boolean of whether the raw_password was correct. Handles
        encryption formats behind the scenes.
        """
        # Backwards-compatibility check. Older passwords won't include the
        # algorithm or salt.
        if '$' not in self.password:
            is_correct = (self.password == get_hexdigest('md5', '', raw_password))
            if is_correct:
                # Convert the password to the new, more secure format.
                self.set_password(raw_password)
                self.save()
            return is_correct
        # Backwards-compatibility check for old app-engine-patch hash format
        if self.password.split('$')[0] == 'sha512':
            valid = check_password(raw_password, self.password)
            if valid:
                self.set_password(raw_password)
                self.save()
            return valid
        return check_password(raw_password, self.password)

    def set_unusable_password(self):
        # Sets a value that will never be a valid hash
        self.password = UNUSABLE_PASSWORD

    def has_usable_password(self):
        return self.password != UNUSABLE_PASSWORD

    def get_group_permissions(self):
        """
        Returns a list of permission strings that this user has through
        his/her groups. This method queries all available auth backends.
        """
        permissions = set()
        for backend in auth.get_backends():
            if hasattr(backend, "get_group_permissions"):
                permissions.update(backend.get_group_permissions(self))
        return permissions

    def get_all_permissions(self):
        permissions = set()
        for backend in auth.get_backends():
            if hasattr(backend, "get_all_permissions"):
                permissions.update(backend.get_all_permissions(self))
        return permissions

    def has_perm(self, perm):
        """
        Returns True if the user has the specified permission. This method
        queries all available auth backends, but returns immediately if any
        backend returns True. Thus, a user who has permission from a single
        auth backend is assumed to have permission in general.
        """
        # Inactive users have no permissions.
        if not self.is_active:
            return False

        # Superusers have all permissions.
        if self.is_superuser:
            return True

        # Otherwise we need to check the backends.
        for backend in auth.get_backends():
            if hasattr(backend, "has_perm"):
                if backend.has_perm(self, perm):
                    return True
        return False

    def has_perms(self, perm_list):
        """Returns True if the user has each of the specified permissions."""
        for perm in perm_list:
            if not self.has_perm(perm):
                return False
        return True

    def has_module_perms(self, app_label):
        """
        Returns True if the user has any permissions in the given app
        label. Uses pretty much the same logic as has_perm, above.
        """
        if not self.is_active:
            return False

        if self.is_superuser:
            return True

        for backend in auth.get_backends():
            if hasattr(backend, "has_module_perms"):
                if backend.has_module_perms(self, app_label):
                    return True
        return False

    def get_and_delete_messages(self):
        messages = []
        for m in self.message_set:
            messages.append(m.message)
            m.delete()
        return messages

    def get_profile(self):
        """
        Returns site-specific profile for this user. Raises
        SiteProfileNotAvailable if this site does not allow profiles.
        """
        if not hasattr(self, '_profile_cache'):
            from django.conf import settings
            if not getattr(settings, 'AUTH_PROFILE_MODULE', False):
                raise SiteProfileNotAvailable
            try:
                app_label, model_name = settings.AUTH_PROFILE_MODULE.split('.')
                model = models.get_model(app_label, model_name)
                profile = model.all().filter('user =', self).get()
                if profile:
                    self._profile_cache = profile
                    profile.user = self
                return profile
            except (ImportError, ImproperlyConfigured):
                raise SiteProfileNotAvailable
        return self._profile_cache

class EmailUserTraits(UserTraits):
    def email_user(self, subject, message, from_email=None):
        """Sends an e-mail to this user."""
        from django.core.mail import send_mail
        send_mail(subject, message, from_email, [self.email])

    class Meta:
        abstract = True

    def __unicode__(self):
        return unicode(self.email)

class EmailUser(EmailUserTraits):
    email = db.EmailProperty(required=True, verbose_name=_('e-mail address'))
    # This can be used to distinguish between banned users and unfinished
    # registrations
    is_banned = db.BooleanProperty(default=False,
        verbose_name=_('banned status'))

    class Meta:
        abstract = True

class User(EmailUserTraits):
    """Default User class that mimics Django's User class."""
    username = db.StringProperty(required=True, verbose_name=_('username'))
    email = db.EmailProperty(verbose_name=_('e-mail address'))
    first_name = db.StringProperty(verbose_name=_('first name'))
    last_name = db.StringProperty(verbose_name=_('last name'))

    class Meta:
        verbose_name = _('user')
        verbose_name_plural = _('users')

    def __unicode__(self):
        return self.get_full_name()

DjangoCompatibleUser = User

AUTH_USER_MODULE = getattr(settings, 'AUTH_USER_MODULE', None)
if AUTH_USER_MODULE and AUTH_USER_MODULE != 'ragendja.auth.models':
    from django.db.models.loading import cache
    module = __import__(AUTH_USER_MODULE, {}, {}, [''])
    User = cache.app_models['auth']['user'] = module.User
    try:
        AnonymousUser = module.AnonymousUser
    except:
        pass

class Message(db.Model):
    """
    The message system is a lightweight way to queue messages for given
    users. A message is associated with a User instance (so it is only
    applicable for registered users). There's no concept of expiration or
    timestamps. Messages are created by the Django admin after successful
    actions. For example, "The poll Foo was created successfully." is a
    message.
    """
    user = db.ReferenceProperty(User, required=True)
    message = db.TextProperty(required=True, verbose_name=_('message'))

    def __unicode__(self):
        return self.message


text:
package com.github.benmanes.caffeine.jcache.management;

import static com.google.common.truth.Truth.assertThat;

import org.testng.annotations.Test;

/**
 * @author ben.manes@gmail.com (Ben Manes)
 */
public final class JCacheStatisticsMXBeanTest {

  @Test
  public void clear() {
    JCacheStatisticsMXBean stats = new JCacheStatisticsMXBean();
    stats.recordHits(1);
    stats.recordMisses(1);
    stats.recordPuts(1);
    stats.recordRemovals(1);
    stats.recordEvictions(1);
    stats.recordGetTime(1);
    stats.recordPutTime(1);
    stats.recordRemoveTime(1);

    stats.clear();
    assertThat(stats.getCacheHits()).isEqualTo(0L);
    assertThat(stats.getCacheMisses()).isEqualTo(0L);
    assertThat(stats.getCachePuts()).isEqualTo(0L);
    assertThat(stats.getCacheRemovals()).isEqualTo(0L);
    assertThat(stats.getCacheEvictions()).isEqualTo(0L);
    assertThat(stats.getAverageGetTime()).isEqualTo(0F);
    assertThat(stats.getAveragePutTime()).isEqualTo(0F);
    assertThat(stats.getAverageRemoveTime()).isEqualTo(0F);
  }
}


text:
package cmd

import (
	"bytes"
	"encoding/json"
	"io/ioutil"
	"net/http"
	"reflect"
	"testing"
	"time"

	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/kubernetes/pkg/api"
	"k8s.io/kubernetes/pkg/api/v1"
	"k8s.io/kubernetes/pkg/client/restclient/fake"
	cmdtesting "k8s.io/kubernetes/pkg/kubectl/cmd/testing"
	cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
	"k8s.io/kubernetes/pkg/util/strategicpatch"
)

func generateNodeAndTaintedNode(oldTaints []v1.Taint, newTaints []v1.Taint) (*api.Node, *api.Node) {
	var taintedNode *api.Node

	oldTaintsData, _ := json.Marshal(oldTaints)
	// Create a node.
	node := &api.Node{
		ObjectMeta: metav1.ObjectMeta{
			Name:              "node-name",
			CreationTimestamp: metav1.Time{Time: time.Now()},
			Annotations: map[string]string{
				v1.TaintsAnnotationKey: string(oldTaintsData),
			},
		},
		Spec: api.NodeSpec{
			ExternalID: "node-name",
		},
		Status: api.NodeStatus{},
	}
	clone, _ := api.Scheme.DeepCopy(node)

	newTaintsData, _ := json.Marshal(newTaints)
	// A copy of the same node, but tainted.
	taintedNode = clone.(*api.Node)
	taintedNode.Annotations = map[string]string{
		v1.TaintsAnnotationKey: string(newTaintsData),
	}

	return node, taintedNode
}

func AnnotationsHaveEqualTaints(annotationA map[string]string, annotationB map[string]string) bool {
	taintsA, err := v1.GetTaintsFromNodeAnnotations(annotationA)
	if err != nil {
		return false
	}
	taintsB, err := v1.GetTaintsFromNodeAnnotations(annotationB)
	if err != nil {
		return false
	}

	if len(taintsA) != len(taintsB) {
		return false
	}

	for _, taintA := range taintsA {
		found := false
		for _, taintB := range taintsB {
			if reflect.DeepEqual(taintA, taintB) {
				found = true
				break
			}
		}
		if !found {
			return false
		}
	}
	return true
}

func TestTaint(t *testing.T) {
	tests := []struct {
		description string
		oldTaints   []v1.Taint
		newTaints   []v1.Taint
		args        []string
		expectFatal bool
		expectTaint bool
	}{
		// success cases
		{
			description: "taints a node with effect NoSchedule",
			newTaints: []v1.Taint{{
				Key:    "foo",
				Value:  "bar",
				Effect: "NoSchedule",
			}},
			args:        []string{"node", "node-name", "foo=bar:NoSchedule"},
			expectFatal: false,
			expectTaint: true,
		},
		{
			description: "taints a node with effect PreferNoSchedule",
			newTaints: []v1.Taint{{
				Key:    "foo",
				Value:  "bar",
				Effect: "PreferNoSchedule",
			}},
			args:        []string{"node", "node-name", "foo=bar:PreferNoSchedule"},
			expectFatal: false,
			expectTaint: true,
		},
		{
			description: "update an existing taint on the node, change the value from bar to barz",
			oldTaints: []v1.Taint{{
				Key:    "foo",
				Value:  "bar",
				Effect: "NoSchedule",
			}},
			newTaints: []v1.Taint{{
				Key:    "foo",
				Value:  "barz",
				Effect: "NoSchedule",
			}},
			args:        []string{"node", "node-name", "foo=barz:NoSchedule", "--overwrite"},
			expectFatal: false,
			expectTaint: true,
		},
		{
			description: "taints a node with two taints",
			newTaints: []v1.Taint{{
				Key:    "dedicated",
				Value:  "namespaceA",
				Effect: "NoSchedule",
			}, {
				Key:    "foo",
				Value:  "bar",
				Effect: "PreferNoSchedule",
			}},
			args:        []string{"node", "node-name", "dedicated=namespaceA:NoSchedule", "foo=bar:PreferNoSchedule"},
			expectFatal: false,
			expectTaint: true,
		},
		{
			description: "node has two taints with the same key but different effect, remove one of them by indicating exact key and effect",
			oldTaints: []v1.Taint{{
				Key:    "dedicated",
				Value:  "namespaceA",
				Effect: "NoSchedule",
			}, {
				Key:    "dedicated",
				Value:  "namespaceA",
				Effect: "PreferNoSchedule",
			}},
			newTaints: []v1.Taint{{
				Key:    "dedicated",
				Value:  "namespaceA",
				Effect: "PreferNoSchedule",
			}},
			args:        []string{"node", "node-name", "dedicated:NoSchedule-"},
			expectFatal: false,
			expectTaint: true,
		},
		{
			description: "node has two taints with the same key but different effect, remove all of them with wildcard",
			oldTaints: []v1.Taint{{
				Key:    "dedicated",
				Value:  "namespaceA",
				Effect: "NoSchedule",
			}, {
				Key:    "dedicated",
				Value:  "namespaceA",
				Effect: "PreferNoSchedule",
			}},
			newTaints:   []v1.Taint{},
			args:        []string{"node", "node-name", "dedicated-"},
			expectFatal: false,
			expectTaint: true,
		},
		{
			description: "node has two taints, update one of them and remove the other",
			oldTaints: []v1.Taint{{
				Key:    "dedicated",
				Value:  "namespaceA",
				Effect: "NoSchedule",
			}, {
				Key:    "foo",
				Value:  "bar",
				Effect: "PreferNoSchedule",
			}},
			newTaints: []v1.Taint{{
				Key:    "foo",
				Value:  "barz",
				Effect: "PreferNoSchedule",
			}},
			args:        []string{"node", "node-name", "dedicated:NoSchedule-", "foo=barz:PreferNoSchedule", "--overwrite"},
			expectFatal: false,
			expectTaint: true,
		},

		// error cases
		{
			description: "invalid taint key",
			args:        []string{"node", "node-name", "nospecialchars^@=banana:NoSchedule"},
			expectFatal: true,
			expectTaint: false,
		},
		{
			description: "invalid taint effect",
			args:        []string{"node", "node-name", "foo=bar:NoExcute"},
			expectFatal: true,
			expectTaint: false,
		},
		{
			description: "duplicated taints with the same key and effect should be rejected",
			args:        []string{"node", "node-name", "foo=bar:NoExcute", "foo=barz:NoExcute"},
			expectFatal: true,
			expectTaint: false,
		},
		{
			description: "can't update existing taint on the node, since 'overwrite' flag is not set",
			oldTaints: []v1.Taint{{
				Key:    "foo",
				Value:  "bar",
				Effect: "NoSchedule",
			}},
			newTaints: []v1.Taint{{
				Key:    "foo",
				Value:  "bar",
				Effect: "NoSchedule",
			}},
			args:        []string{"node", "node-name", "foo=bar:NoSchedule"},
			expectFatal: true,
			expectTaint: false,
		},
	}

	for _, test := range tests {
		oldNode, expectNewNode := generateNodeAndTaintedNode(test.oldTaints, test.newTaints)

		new_node := &api.Node{}
		tainted := false
		f, tf, codec, ns := cmdtesting.NewAPIFactory()

		tf.Client = &fake.RESTClient{
			NegotiatedSerializer: ns,
			Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) {
				m := &MyReq{req}
				switch {
				case m.isFor("GET", "/nodes/node-name"):
					return &http.Response{StatusCode: 200, Header: defaultHeader(), Body: objBody(codec, oldNode)}, nil
				case m.isFor("PATCH", "/nodes/node-name"):
					tainted = true
					data, err := ioutil.ReadAll(req.Body)
					if err != nil {
						t.Fatalf("%s: unexpected error: %v", test.description, err)
					}
					defer req.Body.Close()

					// apply the patch
					oldJSON, err := runtime.Encode(codec, oldNode)
					if err != nil {
						t.Fatalf("%s: unexpected error: %v", test.description, err)
					}
					appliedPatch, err := strategicpatch.StrategicMergePatch(oldJSON, data, &v1.Node{})
					if err != nil {
						t.Fatalf("%s: unexpected error: %v", test.description, err)
					}

					// decode the patch
					if err := runtime.DecodeInto(codec, appliedPatch, new_node); err != nil {
						t.Fatalf("%s: unexpected error: %v", test.description, err)
					}
					if !AnnotationsHaveEqualTaints(expectNewNode.Annotations, new_node.Annotations) {
						t.Fatalf("%s: expected:\n%v\nsaw:\n%v\n", test.description, expectNewNode.Annotations, new_node.Annotations)
					}
					return &http.Response{StatusCode: 200, Header: defaultHeader(), Body: objBody(codec, new_node)}, nil
				case m.isFor("PUT", "/nodes/node-name"):
					tainted = true
					data, err := ioutil.ReadAll(req.Body)
					if err != nil {
						t.Fatalf("%s: unexpected error: %v", test.description, err)
					}
					defer req.Body.Close()
					if err := runtime.DecodeInto(codec, data, new_node); err != nil {
						t.Fatalf("%s: unexpected error: %v", test.description, err)
					}
					if !AnnotationsHaveEqualTaints(expectNewNode.Annotations, new_node.Annotations) {
						t.Fatalf("%s: expected:\n%v\nsaw:\n%v\n", test.description, expectNewNode.Annotations, new_node.Annotations)
					}
					return &http.Response{StatusCode: 200, Header: defaultHeader(), Body: objBody(codec, new_node)}, nil
				default:
					t.Fatalf("%s: unexpected request: %v %#v\n%#v", test.description, req.Method, req.URL, req)
					return nil, nil
				}
			}),
		}
		tf.ClientConfig = defaultClientConfig()

		buf := bytes.NewBuffer([]byte{})
		cmd := NewCmdTaint(f, buf)

		saw_fatal := false
		func() {
			defer func() {
				// Recover from the panic below.
				_ = recover()
				// Restore cmdutil behavior
				cmdutil.DefaultBehaviorOnFatal()
			}()
			cmdutil.BehaviorOnFatal(func(e string, code int) { saw_fatal = true; panic(e) })
			cmd.SetArgs(test.args)
			cmd.Execute()
		}()

		if test.expectFatal {
			if !saw_fatal {
				t.Fatalf("%s: unexpected non-error", test.description)
			}
		}

		if test.expectTaint {
			if !tainted {
				t.Fatalf("%s: node not tainted", test.description)
			}
		}
		if !test.expectTaint {
			if tainted {
				t.Fatalf("%s: unexpected taint", test.description)
			}
		}
	}
}


text:
[![Build Status](https://travis-ci.org/daxingplay/kissy-xtemplate.png?branch=master)](https://travis-ci.org/daxingplay/kissy-xtemplate)

Independent XTemplate compiler for KISSY

## Usage

### NodeJS

```js
var XTemplate = require('kissy-xtemplate');
new XTemplate().compileSync('xxx.xtpl.html', 'xxx.xtpl.js');
```

or use the async version:

```js
var XTemplate = require('kissy-xtemplate');
new XTemplate().compile('xxx.xtpl.html', 'xxx.xtpl.js');
```

### shell

to use shell version, you'd better install it using `-g`

```
npm install kissy-xtemplate -g
```

then, you can compile using `xtemplate` bin.

```
xtemplate a.xtpl.html a.js
xtemplate src/ dest/
```

for more information, please refer to help.

```
xtemplate -h
```

## Options

```
var XTemplate = require('kissy-xtemplate');
var compiler = new XTemplate({
    version: '1.5.0', // config your KISSY version
    inputCharset: 'gbk', // your tpl src charset
    outputCharset: 'gbk', // compiled charset
    type: 'xtpl', // template type. default is XTemplate
});
compiler.compile('xxx.xtpl.html', 'xxx.xtpl.js');
```

## Current Supported Versions

* 1.4.0
* 1.4.1
* 1.4.2
* 1.5.0
* 5.0.0-alpha.1
* 5.0.0-alpha.2
* 5.0.0-alpha.10
* kg-4.1.4
* kg-4.2.0
* kg-4.2.1
    * static constraint when parameter is a static value


text:
<!DOCTYPE HTML>

<TITLE>Using plotWAC() and ggplotWAC()</TITLE>
<META NAME="description" CONTENT="Using plotWAC() and ggplotWAC()">
<META NAME="keywords" CONTENT="R4RAF">
<META NAME="resource-type" CONTENT="document">
<META NAME="distribution" CONTENT="global">

<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=utf-8">
<META NAME="viewport" CONTENT="width=device-width, initial-scale=1.0">
<META NAME="Generator" CONTENT="LaTeX2HTML v2018.3">

<LINK REL="STYLESHEET" HREF="R4RAF.css">

<LINK REL="previous" HREF="node6.html">
<LINK REL="next" HREF="node8.html">

 Next: Overview of Ranadu functions
 Up: Using the data.frame
 Previous: Simple Plots

Using plotWAC() and ggplotWAC()

The function Ranadu::plotWAC() calls the standard R function “plot”
with a particular set of conventions. Some reasons you may want to
consider using it include the following:

[time offset:] The convention in the NCAR/EOL/RAF netCDF files
is that the time variable represents the start of the interval over
which measurements are averaged, so a 1-Hz variable with a specified
time is actually an average where the mean time is 0.5 s later. Plots
generated by plotWAC() adjust for this offset. For this same reason,
you may want to use the routine Ranadu::lineWAC() to add lines to
the plot, instead of the standard “lines” routine provided by
R.

[plot format:] The set of conventions regarding time labels, axis
formats, and legends may be preferable to those that are standard
with “plot()” and will save you from making those tailoring adjustments.

[pipe_compatible:] The function plotWAC() can be used in a pipe
where the piped variable is a data.frame tailored to contain specified
variables to construct multiple-variable plots. A similar pipe to
“plot()” will produce a faceted plot of each variable vs. each
other variable, which may not be what you want.

Figure  shows an example.

 plotWAC(Data[, c('Time', 'GGALT')])

Figure:
Example of the same plot as the preceding figure but generated with Ranadu::plotWAC().

Another option is provided by Ranadu::ggplotWAC(), as shown in Fig. :

 ggplotWAC(Data[, c('Time', 'GGALT')])

Figure:
Example of the same plot as the preceding figure but generated with Ranadu::ggplotWAC().

Additional examples showing the advantages of constructing plots with
pipes will be presented in later chapters of this document. For more
information on the use of these plotting routines, see “?Ranadu::plotWAC”
and “?Ranadu::ggplotWAC”.

 Next: Overview of Ranadu functions
 Up: Using the data.frame
 Previous: Simple Plots


text:
var HazelcastClient = require('../.').Client;
var Controller = require('./RC');
var assert = require('chai').assert;
var sinon = require('sinon');
describe('MembershipListener', function() {
    this.timeout(10000);
    var cluster;
    var member;
    var client;
    before(function(done) {
        Controller.createCluster(null, null).then(function(res) {
            cluster = res;
            return Controller.startMember(cluster.id).then(function(res) {
                member = res;
                return HazelcastClient.newHazelcastClient();
            }).then(function(res) {
                client = res;
                done();
            }).catch(function(err) {
                done(err);
            });
        }).catch(function(err) {
            done(err);
        });
    });

    after(function() {
        client.shutdown();
        return Controller.shutdownCluster(cluster.id);
    });

    it('sees member added event', function(done) {
        var memberAddedSpy = sinon.spy();
        var newMember;
        client.clusterService.on('memberAdded', memberAddedSpy);
        Controller.startMember(cluster.id).then(function(res) {
            newMember = res;
            assert.isTrue(memberAddedSpy.calledOnce);
            assert.equal(memberAddedSpy.getCall(0).args[0].address.host, newMember.host);
            assert.equal(memberAddedSpy.getCall(0).args[0].address.port, newMember.port);
        }).catch(function(err) {
            done(err);
        }).finally(function() {
            Controller.shutdownMember(cluster.id, newMember.uuid).then(function() {
                done();
            });
        });
    });

    it('sees member removed event', function(done) {
        var memberRemovedSpy = sinon.spy();
        var newMember;
        client.clusterService.on('memberRemoved', memberRemovedSpy);
        Controller.startMember(cluster.id).then(function(res) {
            newMember = res;
            return Controller.shutdownMember(cluster.id, newMember.uuid);
        }).then(function() {
            assert.isTrue(memberRemovedSpy.calledOnce);
            assert.equal(memberRemovedSpy.getCall(0).args[0].address.host, newMember.host);
            assert.equal(memberRemovedSpy.getCall(0).args[0].address.port, newMember.port);
            done();
        }).catch(function(err) {
            done(err);
        });
    });

    it('sees member attribute change put event', function(done) {
        client.clusterService.on('memberAttributeChange', function(uuid, key, op, value) {
            if(op === 'put') {
                assert.equal(uuid, member.uuid);
                assert.equal(key, 'test');
                assert.equal(op, 'put');
                assert.equal(value, '123');
                done();
            }
        });
        var script = 'function attrs() { ' +
            'return instance_0.getCluster().getLocalMember().setIntAttribute("test", 123); }; result=attrs();';
        Controller.executeOnController(cluster.id, script, 1);
    });

    it('sees member attribute change remove event', function(done) {
        client.clusterService.on('memberAttributeChange', function(uuid, key, op, value) {
            if (op === 'remove') {
                assert.equal(uuid, member.uuid);
                assert.equal(key, 'test');
                assert.equal(op, 'remove');
                done();
            }
        });
        var addScript = 'function attrs() { ' +
            'return instance_0.getCluster().getLocalMember().setIntAttribute("test", 123); }; result=attrs();';
        var removeScript = 'function attrs() { ' +
            'return instance_0.getCluster().getLocalMember().removeAttribute("test"); }; result=attrs();';
        Controller.executeOnController(cluster.id, addScript, 1)
            .then(Controller.executeOnController.bind(this, cluster.id, removeScript, 1));
    });
});


text:
classdef BaseCrossover < fsf.ga.operators.BaseOperator
    % BASECROSSOVER: Determines how two individuals crossover in order to produce offsprings.

    methods
        function this = BaseCrossover()
            % Creates a fsf.ga.operators.BaseCrossover instance.
            %
            %  @return this: The new fsf.ga.Operators.BaseCrossover instance.

            this@fsf.ga.operators.BaseOperator();
        end
    end

    methods(Access = protected)
        function must = MustCrossover(this, crossoverRate)
            % Determines if crossover must be done according to a crossover rate.
            %
            %  @param crossoverRate: The crossover rate threshold, between [0, 1].
            %
            %  @return must: A boolean stating when to perform crossover or not.

            must = (random('Uniform', 0, 1) < crossoverRate);
        end

    end

    methods(Access = public)
        function crossedPopulation = ApplyCrossover(this, population, crossoverRate)
            % Applies the croosover operator to a population, according to the crossoverRate provided
            %
            % @param population: The population to apply the crossover to.
            % @param crossoverRate: The crossover rate used to determine when to apply crossover or not.
            %
            % @return crossedPopulation: The population result of apply crossover to the given population
            %                            (only included the offsprings result of crossover).

            populationLength = population.Length;
            crossedIndividuals = [];
            for indexIndividual = 1:2:(populationLength-1)
                if(this.MustCrossover(crossoverRate))
                    father = population.Individuals(indexIndividual);
                    mother = population.Individuals(indexIndividual + 1);
                    [offspring1, offspring2] = this.CrossoverImplementation(father.Clone(), mother.Clone());
                    crossedIndividuals = [crossedIndividuals, offspring1, offspring2];
                end
            end
            crossedPopulation = fsf.ga.Population(crossedIndividuals);
        end
    end

    methods(Access = protected, Abstract)
        % Implements the crossover of two individuals, father and mother, to generate acouple of offsprings
        %
        % @param father: The father to be crossover.
        % @param mother: The mother to be crossover.
        %
        % @return offspring_1: The first offspring result of crossover
        % @return offspring_2: The second offspring result of crossover
        [offspring_1, offspring_2] = CrossoverImplementation(this, father, mother);
    end

end


text:
if [ -f VERSION ]; then
    ORIGINAL_STRING=`cat VERSION`
    ORIGINAL_LIST=(`echo $ORIGINAL_STRING | tr '.' ' '`)
    MAJOR=${ORIGINAL_LIST[0]}
    MINOR=${ORIGINAL_LIST[1]}
    PATCH=${ORIGINAL_LIST[2]}
    echo "Current Version: $ORIGINAL_STRING"
    PATCH=$((PATCH + 1))
    SUGGESTED="$MAJOR.$MINOR.$PATCH"
    read -p "Enter a version number [$SUGGESTED]: " VERSION_INPUT
    if [ "$VERSION_INPUT" = "" ]; then
        VERSION_INPUT=$SUGGESTED
    fi
    echo "Version will be set to $VERSION_INPUT"
    echo $VERSION_INPUT > VERSION
    echo "Version $VERSION_INPUT:" > tmpfile
    git log --pretty=format:" -%s" "v$ORIGINAL_STRING"...HEAD >> tmpfile
    echo "" >> tmpfile
    echo "" >> tmpfile
    cat CHANGES >> tmpfile
    mv tmpfile CHANGES
    git add CHANGES VERSION
    git commit -m "Version change to $VERSION_INPUT"
    git tag -a -m "Tagging version $VERSION_INPUT" "v$VERSION_INPUT"
    git push origin --tags
else
    echo "Could not find the VERSION file"
fi


text:
using Aggregates;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Language
{
    public class PreviousMessages : IService<MessageState[]>
    {
    }
}


text:
// Copyright 2014 Music Glue. All rights reserved.
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
/*
Package oak is an implementation of a Trie-style data structure
implemented with mutexes around the nodes to ensure coherent and
safe data access and updating from multiple concurrent accessors.

Sample use cases would include a lookup table for routes in a web
process.
*/
package oak


text: this is my implementation for the book of "Programming Pearls"


text:
package com.microsoft.azure.management.storageimportexport.v2016_11_01;

import com.microsoft.azure.arm.model.HasInner;
import com.microsoft.azure.arm.resources.models.HasManager;
import com.microsoft.azure.management.storageimportexport.v2016_11_01.implementation.StorageImportExportManager;
import com.microsoft.azure.management.storageimportexport.v2016_11_01.implementation.DriveBitLockerKeyInner;

/**
 * Type representing DriveBitLockerKey.
 */
public interface DriveBitLockerKey extends HasInner<DriveBitLockerKeyInner>, HasManager<StorageImportExportManager> {
    /**
     * @return the bitLockerKey value.
     */
    String bitLockerKey();

    /**
     * @return the driveId value.
     */
    String driveId();

}


text:
{% extends "templates/test.html" %}

{% block script %}
<script type="text/javascript">
  sk.start()

  const resources = sk.resolve('resources')
  const stage     = sk.resolve('stage')
  const display   = sk.resolve('display')

  let t1 = null

  const options = {
    progress: 0
  }

  let ball = new PIXI.Graphics()
  ball.beginFill(sk.COLORS.WHITE).drawCircle(0, 0, 50)
  ball.tint = sk.COLORS.FLAT_POMEGRANATE
  ball.pivot.set(0, 0)
  ball.position.set(display.halfWidth, display.halfHeight)
  stage.addChild(ball)

  t1 = sk.tween.Tween.fromTo(ball, 1000, {x:0}, {x:display.width}, {
    delay: 500,
    repeat: 2,
    repeatDelay: 500,
    yoyo: true,
    yoyoDelay: 100,
    ease: sk.ease.bounceOut,
    yoyoEase: sk.ease.bounceIn,
    onStart: () => { console.log('onStart') },
    onUpdate: (tween, progress, realProgress) => {
      if (tween.active) {
        options.progress = progress
        skf.options.update()
      }

      if (progress <= 0.5) {
        ball.tint = sk.colors.blend(sk.COLORS.FLAT_POMEGRANATE, sk.COLORS.FLAT_SUNFLOWER, progress*2)
      } else if (progress > 0.5) {
        ball.tint = sk.colors.blend(sk.COLORS.FLAT_SUNFLOWER, sk.COLORS.SK_LIME, (progress - 0.5)*2)
      }
    },
    onComplete: () => { console.log('onComplete') },
    onRepeat: (_, loop, lastLoop) => { console.log('onRepeat', loop) },
    onReverse: (_, backwards) => { console.log('onReverse', backwards) },
  }).start()

  skf.options
     .add(options, 'progress', 0, 1, 0.001)
     .onChange((value) => {
       t1.stop()
       t1.seek(t1.totalDuration * value)
     })

  skf.options.add(t1, 'start')
  skf.options.add(t1, 'pause')
  skf.options.add(t1, 'resume')
  skf.options.add(t1, 'stop')
  skf.options.add(t1, '_reset')

</script>
{% endblock %}


text:
namespace OmniSharp.Services
{
    public interface ITestCommandProvider
    {
        string GetTestCommand(TestContext testContext);
    }
}


text:
<?php

class QuizController extends ApiController {
	public function getAction() {
		$action = $this->request->getUrlElement(1);

		$data = array();

		if ($action == "") {
			$data = $this->db->query("SELECT * FROM event e LEFT JOIN programYear p ON e.programYearID=p.programYearID ORDER BY programYear, name;")->fetchAll(PDO::FETCH_ASSOC);
		} else {
			$sth = $this->db->prepare("SELECT u.* FROM attendee a LEFT JOIN user u ON a.userID = u.accountno WHERE a.eventID=?;");
			if (!$sth->execute(array( $action ))) throw new Exception('Unsupported method', 405);
			$data = $sth->fetchAll(PDO::FETCH_ASSOC);
			for ($i=0; $i < sizeof($data); $i++) unset($data[$i]['pass']);
		}

		return $data;
	}
}


text:
rem Windows 64bit batch file for running GML Tool

rem setup classpath
set CLASSPATH=..\lib\GMLTool.jar
set CLASSPATH=%CLASSPATH%;..\lib\worldwind.jar
set CLASSPATH=%CLASSPATH%;..\lib\worldwindx.jar
set CLASSPATH=%CLASSPATH%;..\lib\jogl.jar
set CLASSPATH=%CLASSPATH%;..\lib\gluegen-rt.jar
set CLASSPATH=%CLASSPATH%;..\lib\jgoodies-common-1.4.0.jar
set CLASSPATH=%CLASSPATH%;..\lib\jgoodies-looks-2.5.2.jar

rem launch jvm with natives in windows folder
java -Xms128m -Dsun.java2d.noddraw=true -Djava.library.path=..\lib\windows64 -cp %CLASSPATH% gmltool.App


text:
@class Recipe;

@interface RecipeCell : UITableViewCell

@property (nonatomic, strong) Recipe* recipe;
@property (nonatomic, strong) NSIndexPath* indexPath;

@property (weak, nonatomic) IBOutlet UIImageView *imageViewRecipe;
@property (weak, nonatomic) IBOutlet UILabel *labelName;
@property (weak, nonatomic) IBOutlet UILabel *labelDifficulty;
@property (weak, nonatomic) IBOutlet UIButton *buttonFavorite;
@property (weak, nonatomic) IBOutlet UILabel *labelDateUpdate;
@property (weak, nonatomic) IBOutlet UIView *viewForStars;

- (IBAction)favoriteHandler:(UIButton*)sender;

@end