text:
import pandas as pd

from . import dtypes, utils
from .alignment import align
from .duck_array_ops import lazy_array_equiv
from .merge import _VALID_COMPAT, merge_attrs, unique_variable
from .variable import IndexVariable, Variable, as_variable
from .variable import concat as concat_vars

def concat(
    objs,
    dim,
    data_vars="all",
    coords="different",
    compat="equals",
    positions=None,
    fill_value=dtypes.NA,
    join="outer",
    combine_attrs="override",
):
    """Concatenate xarray objects along a new or existing dimension.

    Parameters
    ----------
    objs : sequence of Dataset and DataArray objects
        xarray objects to concatenate together. Each object is expected to
        consist of variables and coordinates with matching shapes except for
        along the concatenated dimension.
    dim : str or DataArray or pandas.Index
        Name of the dimension to concatenate along. This can either be a new
        dimension name, in which case it is added along axis=0, or an existing
        dimension name, in which case the location of the dimension is
        unchanged. If dimension is provided as a DataArray or Index, its name
        is used as the dimension to concatenate along and the values are added
        as a coordinate.
    data_vars : {'minimal', 'different', 'all' or list of str}, optional
        These data variables will be concatenated together:
          * 'minimal': Only data variables in which the dimension already
            appears are included.
          * 'different': Data variables which are not equal (ignoring
            attributes) across all datasets are also concatenated (as well as
            all for which dimension already appears). Beware: this option may
            load the data payload of data variables into memory if they are not
            already loaded.
          * 'all': All data variables will be concatenated.
          * list of str: The listed data variables will be concatenated, in
            addition to the 'minimal' data variables.

        If objects are DataArrays, data_vars must be 'all'.
    coords : {'minimal', 'different', 'all' or list of str}, optional
        These coordinate variables will be concatenated together:
          * 'minimal': Only coordinates in which the dimension already appears
            are included.
          * 'different': Coordinates which are not equal (ignoring attributes)
            across all datasets are also concatenated (as well as all for which
            dimension already appears). Beware: this option may load the data
            payload of coordinate variables into memory if they are not already
            loaded.
          * 'all': All coordinate variables will be concatenated, except
            those corresponding to other dimensions.
          * list of str: The listed coordinate variables will be concatenated,
            in addition to the 'minimal' coordinates.
    compat : {'identical', 'equals', 'broadcast_equals', 'no_conflicts', 'override'}, optional
        String indicating how to compare non-concatenated variables of the same name for
        potential conflicts. This is passed down to merge.

        - 'broadcast_equals': all values must be equal when variables are
          broadcast against each other to ensure common dimensions.
        - 'equals': all values and dimensions must be the same.
        - 'identical': all values, dimensions and attributes must be the
          same.
        - 'no_conflicts': only values which are not null in both datasets
          must be equal. The returned dataset then contains the combination
          of all non-null values.
        - 'override': skip comparing and pick variable from first dataset
    positions : None or list of integer arrays, optional
        List of integer arrays which specifies the integer positions to which
        to assign each dataset along the concatenated dimension. If not
        supplied, objects are concatenated in the provided order.
    fill_value : scalar, optional
        Value to use for newly missing values
    join : {'outer', 'inner', 'left', 'right', 'exact'}, optional
        String indicating how to combine differing indexes
        (excluding dim) in objects

        - 'outer': use the union of object indexes
        - 'inner': use the intersection of object indexes
        - 'left': use indexes from the first object with each dimension
        - 'right': use indexes from the last object with each dimension
        - 'exact': instead of aligning, raise `ValueError` when indexes to be
          aligned are not equal
        - 'override': if indexes are of same size, rewrite indexes to be
          those of the first object with that dimension. Indexes for the same
          dimension must have the same size in all objects.
    combine_attrs : {'drop', 'identical', 'no_conflicts', 'override'},
                    default 'override
        String indicating how to combine attrs of the objects being merged:

        - 'drop': empty attrs on returned Dataset.
        - 'identical': all attrs must be the same on every object.
        - 'no_conflicts': attrs from all objects are combined, any that have
          the same name must also have the same value.
        - 'override': skip comparing and copy attrs from the first dataset to
          the result.

    Returns
    -------
    concatenated : type of objs

    See also
    --------
    merge
    auto_combine
    """
    # TODO: add ignore_index arguments copied from pandas.concat
    # TODO: support concatenating scalar coordinates even if the concatenated
    # dimension already exists
    from .dataset import Dataset
    from .dataarray import DataArray

    try:
        first_obj, objs = utils.peek_at(objs)
    except StopIteration:
        raise ValueError("must supply at least one object to concatenate")

    if compat not in _VALID_COMPAT:
        raise ValueError(
            "compat=%r invalid: must be 'broadcast_equals', 'equals', 'identical', 'no_conflicts' or 'override'"
            % compat
        )

    if isinstance(first_obj, DataArray):
        f = _dataarray_concat
    elif isinstance(first_obj, Dataset):
        f = _dataset_concat
    else:
        raise TypeError(
            "can only concatenate xarray Dataset and DataArray "
            "objects, got %s" % type(first_obj)
        )
    return f(
        objs, dim, data_vars, coords, compat, positions, fill_value, join, combine_attrs
    )

def _calc_concat_dim_coord(dim):
    """
    Infer the dimension name and 1d coordinate variable (if appropriate)
    for concatenating along the new dimension.
    """
    from .dataarray import DataArray

    if isinstance(dim, str):
        coord = None
    elif not isinstance(dim, (DataArray, Variable)):
        dim_name = getattr(dim, "name", None)
        if dim_name is None:
            dim_name = "concat_dim"
        coord = IndexVariable(dim_name, dim)
        dim = dim_name
    elif not isinstance(dim, DataArray):
        coord = as_variable(dim).to_index_variable()
        (dim,) = coord.dims
    else:
        coord = dim
        (dim,) = coord.dims
    return dim, coord

def _calc_concat_over(datasets, dim, dim_names, data_vars, coords, compat):
    """
    Determine which dataset variables need to be concatenated in the result,
    """
    # Return values
    concat_over = set()
    equals = {}

    if dim in dim_names:
        concat_over_existing_dim = True
        concat_over.add(dim)
    else:
        concat_over_existing_dim = False

    concat_dim_lengths = []
    for ds in datasets:
        if concat_over_existing_dim:
            if dim not in ds.dims:
                if dim in ds:
                    ds = ds.set_coords(dim)
        concat_over.update(k for k, v in ds.variables.items() if dim in v.dims)
        concat_dim_lengths.append(ds.dims.get(dim, 1))

    def process_subset_opt(opt, subset):
        if isinstance(opt, str):
            if opt == "different":
                if compat == "override":
                    raise ValueError(
                        "Cannot specify both %s='different' and compat='override'."
                        % subset
                    )
                # all nonindexes that are not the same in each dataset
                for k in getattr(datasets[0], subset):
                    if k not in concat_over:
                        equals[k] = None

                        variables = []
                        for ds in datasets:
                            if k in ds.variables:
                                variables.append(ds.variables[k])

                        if len(variables) == 1:
                            # coords="different" doesn't make sense when only one object
                            # contains a particular variable.
                            break
                        elif len(variables) != len(datasets) and opt == "different":
                            raise ValueError(
                                f"{k!r} not present in all datasets and coords='different'. "
                                f"Either add {k!r} to datasets where it is missing or "
                                "specify coords='minimal'."
                            )

                        # first check without comparing values i.e. no computes
                        for var in variables[1:]:
                            equals[k] = getattr(variables[0], compat)(
                                var, equiv=lazy_array_equiv
                            )
                            if equals[k] is not True:
                                # exit early if we know these are not equal or that
                                # equality cannot be determined i.e. one or all of
                                # the variables wraps a numpy array
                                break

                        if equals[k] is False:
                            concat_over.add(k)

                        elif equals[k] is None:
                            # Compare the variable of all datasets vs. the one
                            # of the first dataset. Perform the minimum amount of
                            # loads in order to avoid multiple loads from disk
                            # while keeping the RAM footprint low.
                            v_lhs = datasets[0].variables[k].load()
                            # We'll need to know later on if variables are equal.
                            computed = []
                            for ds_rhs in datasets[1:]:
                                v_rhs = ds_rhs.variables[k].compute()
                                computed.append(v_rhs)
                                if not getattr(v_lhs, compat)(v_rhs):
                                    concat_over.add(k)
                                    equals[k] = False
                                    # computed variables are not to be re-computed
                                    # again in the future
                                    for ds, v in zip(datasets[1:], computed):
                                        ds.variables[k].data = v.data
                                    break
                            else:
                                equals[k] = True

            elif opt == "all":
                concat_over.update(
                    set(getattr(datasets[0], subset)) - set(datasets[0].dims)
                )
            elif opt == "minimal":
                pass
            else:
                raise ValueError(f"unexpected value for {subset}: {opt}")
        else:
            invalid_vars = [k for k in opt if k not in getattr(datasets[0], subset)]
            if invalid_vars:
                if subset == "coords":
                    raise ValueError(
                        "some variables in coords are not coordinates on "
                        "the first dataset: %s" % (invalid_vars,)
                    )
                else:
                    raise ValueError(
                        "some variables in data_vars are not data variables "
                        "on the first dataset: %s" % (invalid_vars,)
                    )
            concat_over.update(opt)

    process_subset_opt(data_vars, "data_vars")
    process_subset_opt(coords, "coords")
    return concat_over, equals, concat_dim_lengths

# determine dimensional coordinate names and a dict mapping name to DataArray
def _parse_datasets(datasets):

    dims = set()
    all_coord_names = set()
    data_vars = set()  # list of data_vars
    dim_coords = {}  # maps dim name to variable
    dims_sizes = {}  # shared dimension sizes to expand variables

    for ds in datasets:
        dims_sizes.update(ds.dims)
        all_coord_names.update(ds.coords)
        data_vars.update(ds.data_vars)

        for dim in set(ds.dims) - dims:
            if dim not in dim_coords:
                dim_coords[dim] = ds.coords[dim].variable
        dims = dims | set(ds.dims)

    return dim_coords, dims_sizes, all_coord_names, data_vars

def _dataset_concat(
    datasets,
    dim,
    data_vars,
    coords,
    compat,
    positions,
    fill_value=dtypes.NA,
    join="outer",
    combine_attrs="override",
):
    """
    Concatenate a sequence of datasets along a new or existing dimension
    """
    from .dataset import Dataset

    dim, coord = _calc_concat_dim_coord(dim)
    # Make sure we're working on a copy (we'll be loading variables)
    datasets = [ds.copy() for ds in datasets]
    datasets = align(
        *datasets, join=join, copy=False, exclude=[dim], fill_value=fill_value
    )

    dim_coords, dims_sizes, coord_names, data_names = _parse_datasets(datasets)
    dim_names = set(dim_coords)
    unlabeled_dims = dim_names - coord_names

    both_data_and_coords = coord_names & data_names
    if both_data_and_coords:
        raise ValueError(
            "%r is a coordinate in some datasets but not others." % both_data_and_coords
        )
    # we don't want the concat dimension in the result dataset yet
    dim_coords.pop(dim, None)
    dims_sizes.pop(dim, None)

    # case where concat dimension is a coordinate or data_var but not a dimension
    if (dim in coord_names or dim in data_names) and dim not in dim_names:
        datasets = [ds.expand_dims(dim) for ds in datasets]

    # determine which variables to concatentate
    concat_over, equals, concat_dim_lengths = _calc_concat_over(
        datasets, dim, dim_names, data_vars, coords, compat
    )

    # determine which variables to merge, and then merge them according to compat
    variables_to_merge = (coord_names | data_names) - concat_over - dim_names

    result_vars = {}
    if variables_to_merge:
        to_merge = {var: [] for var in variables_to_merge}

        for ds in datasets:
            for var in variables_to_merge:
                if var in ds:
                    to_merge[var].append(ds.variables[var])

        for var in variables_to_merge:
            result_vars[var] = unique_variable(
                var, to_merge[var], compat=compat, equals=equals.get(var, None)
            )
    else:
        result_vars = {}
    result_vars.update(dim_coords)

    # assign attrs and encoding from first dataset
    result_attrs = merge_attrs([ds.attrs for ds in datasets], combine_attrs)
    result_encoding = datasets[0].encoding

    # check that global attributes are fixed across all datasets if necessary
    for ds in datasets[1:]:
        if compat == "identical" and not utils.dict_equiv(ds.attrs, result_attrs):
            raise ValueError("Dataset global attributes not equal.")

    # we've already verified everything is consistent; now, calculate
    # shared dimension sizes so we can expand the necessary variables
    def ensure_common_dims(vars):
        # ensure each variable with the given name shares the same
        # dimensions and the same shape for all of them except along the
        # concat dimension
        common_dims = tuple(pd.unique([d for v in vars for d in v.dims]))
        if dim not in common_dims:
            common_dims = (dim,) + common_dims
        for var, dim_len in zip(vars, concat_dim_lengths):
            if var.dims != common_dims:
                common_shape = tuple(dims_sizes.get(d, dim_len) for d in common_dims)
                var = var.set_dims(common_dims, common_shape)
            yield var

    # stack up each variable to fill-out the dataset (in order)
    # n.b. this loop preserves variable order, needed for groupby.
    for k in datasets[0].variables:
        if k in concat_over:
            try:
                vars = ensure_common_dims([ds.variables[k] for ds in datasets])
            except KeyError:
                raise ValueError("%r is not present in all datasets." % k)
            combined = concat_vars(vars, dim, positions)
            assert isinstance(combined, Variable)
            result_vars[k] = combined

    result = Dataset(result_vars, attrs=result_attrs)
    absent_coord_names = coord_names - set(result.variables)
    if absent_coord_names:
        raise ValueError(
            "Variables %r are coordinates in some datasets but not others."
            % absent_coord_names
        )
    result = result.set_coords(coord_names)
    result.encoding = result_encoding

    result = result.drop_vars(unlabeled_dims, errors="ignore")

    if coord is not None:
        # add concat dimension last to ensure that its in the final Dataset
        result[coord.name] = coord

    return result

def _dataarray_concat(
    arrays,
    dim,
    data_vars,
    coords,
    compat,
    positions,
    fill_value=dtypes.NA,
    join="outer",
    combine_attrs="override",
):
    arrays = list(arrays)

    if data_vars != "all":
        raise ValueError(
            "data_vars is not a valid argument when concatenating DataArray objects"
        )

    datasets = []
    for n, arr in enumerate(arrays):
        if n == 0:
            name = arr.name
        elif name != arr.name:
            if compat == "identical":
                raise ValueError("array names not identical")
            else:
                arr = arr.rename(name)
        datasets.append(arr._to_temp_dataset())

    ds = _dataset_concat(
        datasets,
        dim,
        data_vars,
        coords,
        compat,
        positions,
        fill_value=fill_value,
        join=join,
        combine_attrs="drop",
    )

    merged_attrs = merge_attrs([da.attrs for da in arrays], combine_attrs)

    result = arrays[0]._from_temp_dataset(ds, name)
    result.attrs = merged_attrs

    return result


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.apimanagement.generated;

import com.azure.core.util.Context;

/** Samples for UserSubscription Get. */
public final class UserSubscriptionGetSamples {
    /*
     * x-ms-original-file: specification/apimanagement/resource-manager/Microsoft.ApiManagement/stable/2021-08-01/examples/ApiManagementGetUserSubscription.json
     */
    /**
     * Sample code: ApiManagementGetUserSubscription.
     *
     * @param manager Entry point to ApiManagementManager.
     */
    public static void apiManagementGetUserSubscription(
        com.azure.resourcemanager.apimanagement.ApiManagementManager manager) {
        manager
            .userSubscriptions()
            .getWithResponse("rg1", "apimService1", "1", "5fa9b096f3df14003c070001", Context.NONE);
    }
}

redpajama_set_name: RedPajamaGithub


text:
class CreateCustomers < ActiveRecord::Migration
  def change
    create_table :customers do |t|
      t.string :name
      t.string :email
      t.string :phone
      t.string :token
      t.string :customer_id

      t.timestamps
    end
  end
end


text:
% Method for class 'FreqSignal' and subclasses
%  avgElements : average the elements of a FreqSignal object
% elements must have the same dimensions
% INPUTS
%
% OUTPUT
% avgSignal : between-elements FreqSignal average

function avgSignal = avgElements(self, varargin)

if numel(self) == 1
    avgSignal = self;
    return;
end

% check input
if ~(all(arrayfun(@isNumFreq, self)) || ~any(arrayfun(@isNumFreq, self)))
    error('Freq property of the elements of the FreqSignal must be all numeric or all discrete');
end

% args & options
if ~isempty(varargin)
    if ischar(varargin{1}) % kvPairs
        varargin = panam_args2struct(varargin);
    else % structure
        varargin = varargin{1};
    end
else
    varargin = [];
end
defaultOption.freqAxis = 'max'; % by default : freq axis will be extended for all averaged elements (fill with nans if necessary)
defaultOption.df = 'min'; % space between freq points is set at the minimum
defaultOption.freqMarkers = 'keepRange'; % saves the range of freq markers across elements via field 'window'. Other options : 'avgAll' to average values and 'keepOnlyConstant'
defaultOption.subclassFlag = 0;
option = setstructfields(defaultOption, varargin);

% modifiy freq axis if necessary
if numel(self) > 1 && all(arrayfun(@isNumFreq, self))
    if ~isequal(self.Freq)
        self = self.adjustFreq(option);
    end
else % discrete times
    if ~isequal(self.Freq)
        error('To average discrete freq FreqSignals, freq tags must be similar for all elements');
    end
end

% average
avgSignal = self.avgElements@Signal(option);
avgSignal.FreqMarkers = FreqMarkers.empty;

% unify markers
for ii =1:numel(self)
    self(ii).FreqMarkers = self(ii).FreqMarkers.unifyMarkers(0);
end
% keep only markers that are present in all Signals
listNames = arrayfun(@(x) {x.FreqMarkers.MarkerName}, self,'UniformOutput',0);
allNames = unique([listNames{:}]);
bad = [];
for ii = 1:numel(allNames)
    name = allNames{ii};
    if ~all(cellfun(@(x) ismember(name, x), listNames)) % suppress this event
        bad(end+1) = ii;
    end
end
for b = bad
    for ii = 1:numel(self)
        self(ii).FreqMarkers = self(ii).FreqMarkers.deleteMarkers(allNames{b});
    end
end
% keep a marker only if it is present the same number of times in all
% elements
allNames = {self(1).FreqMarkers.MarkerName};
bad = [];
for ii = 1:numel(allNames)
    name = allNames{ii};
    n = arrayfun(@(x) numel(x.FreqMarkers(strcmpi({x.FreqMarkers.MarkerName},name)).Freq), self);
    if length(unique(n)) > 1
        bad(end+1) = ii;
    end
end
for b = bad
    for ii = 1:numel(self)
        self(ii).FreqMarkers = self(ii).FreqMarkers.deleteMarkers(allNames{b});
    end
end
% average markers
allNames = {self(1).FreqMarkers.MarkerName};
switch option.freqMarkers
    case 'keepRange'
        for ii = 1:numel(allNames)
            name = allNames{ii};
            freq = arrayfun(@(x) x.FreqMarkers(strcmpi({x.FreqMarkers.MarkerName},name)).Freq, self, 'UniformOutput',0);
            freq = cell2mat(freq');
            avgF = min(freq,1);
            window = max(freq,1) - min(freq,1);
            avgSignal.FreqMarkers(end+1) = FreqMarkers(name, avgF, window);
        end
    case 'avgAll'
        for ii = 1:numel(allNames)
            name = allNames{ii};
            freq = arrayfun(@(x) x.FreqMarkers(strcmpi({x.FreqMarkers.MarkerName},name)).Freq, self, 'UniformOutput',0);
            freq = cell2mat(freq');
            avgF = mean(freq,1);
            avgSignal.FreqMarkers(end+1) = FreqMarkers(name, avgF);
        end
    case 'keepOnlyConstant'
        for ii = 1:numel(allNames)
            name = allNames{ii};
            freq = arrayfun(@(x) x.Events(strcmpi({x.FreqMarkers.MarkerName},name)).Freq, self, 'UniformOutput',0);
            freq = cell2mat(freq');
            if all(arrayfun(@(i) length(unique(freq(:,i))) == 1, 1:size(freq,2)))
                avgSignal.FreqMarkers(end+1) = FreqMarkers(name, mean(freq,1));
            end
        end
end

% history
if ~option.subclassFlag
    avgSignal.History{end+1,1} = datestr(clock);
    avgSignal.History{end,2} = ...
        'Average the elements of the FreqSignal object';
end

end


text:
import random
import uuid
import sys

def generate_data(lower_bound, upper_bound, number_count):
    return list(set([
        (
            random.randint(lower_bound, upper_bound),
            random.randint(lower_bound, upper_bound)
        )
        for num in range(int(number_count))
    ]))

if __name__ == "__main__":
    if len(sys.argv) < 5:
        sys.exit("python generate.py [file] [number of points] [lower bound] [higher bound]")

    lower_bound = int(sys.argv[3])
    upper_bound = int(sys.argv[4])

    points = generate_data(lower_bound, upper_bound, sys.argv[2])

    points_with_uuid = [(*point, str(uuid.uuid4())) for point in points]

    with open(sys.argv[1], "w") as points_dat:
        points_dat.write(str(points_with_uuid))


text:
namespace draco {

AttributesDecoder::AttributesDecoder()
    : point_cloud_decoder_(nullptr), point_cloud_(nullptr) {}

bool AttributesDecoder::Initialize(PointCloudDecoder *decoder, PointCloud *pc) {
  point_cloud_decoder_ = decoder;
  point_cloud_ = pc;
  return true;
}

bool AttributesDecoder::DecodeAttributesDecoderData(DecoderBuffer *in_buffer) {
  // Decode and create attributes.
  uint32_t num_attributes;
#ifdef DRACO_BACKWARDS_COMPATIBILITY_SUPPORTED
  if (point_cloud_decoder_->bitstream_version() <
      DRACO_BITSTREAM_VERSION(2, 0)) {
    if (!in_buffer->Decode(&num_attributes))
      return false;
  } else
#endif
  {
    if (!DecodeVarint(&num_attributes, in_buffer))
      return false;
  }
  if (num_attributes == 0)
    return false;
  point_attribute_ids_.resize(num_attributes);
  PointCloud *pc = point_cloud_;
  for (int i = 0; i < num_attributes; ++i) {
    // Decode attribute descriptor data.
    uint8_t att_type, data_type, num_components, normalized;
    if (!in_buffer->Decode(&att_type))
      return false;
    if (!in_buffer->Decode(&data_type))
      return false;
    if (!in_buffer->Decode(&num_components))
      return false;
    if (!in_buffer->Decode(&normalized))
      return false;
    if (data_type <= DT_INVALID || data_type >= DT_TYPES_COUNT)
      return false;
    const DataType draco_dt = static_cast<DataType>(data_type);

    // Add the attribute to the point cloud
    GeometryAttribute ga;
    ga.Init(static_cast<GeometryAttribute::Type>(att_type), nullptr,
            num_components, draco_dt, normalized > 0,
            DataTypeLength(draco_dt) * num_components, 0);
    uint32_t unique_id;
#ifdef DRACO_BACKWARDS_COMPATIBILITY_SUPPORTED
    if (point_cloud_decoder_->bitstream_version() <
        DRACO_BITSTREAM_VERSION(1, 3)) {
      uint16_t custom_id;
      if (!in_buffer->Decode(&custom_id))
        return false;
      // TODO(zhafang): Add "custom_id" to attribute metadata.
      unique_id = static_cast<uint32_t>(custom_id);
      ga.set_unique_id(unique_id);
    } else
#endif
    {
      DecodeVarint(&unique_id, in_buffer);
      ga.set_unique_id(unique_id);
    }
    const int att_id = pc->AddAttribute(
        std::unique_ptr<PointAttribute>(new PointAttribute(ga)));
    pc->attribute(att_id)->set_unique_id(unique_id);
    point_attribute_ids_[i] = att_id;

    // Update the inverse map.
    if (att_id >= static_cast<int32_t>(point_attribute_to_local_id_map_.size()))
      point_attribute_to_local_id_map_.resize(att_id + 1, -1);
    point_attribute_to_local_id_map_[att_id] = i;
  }
  return true;
}

}  // namespace draco


text:
package eu.socialedge.ddd.domain;

import com.fasterxml.jackson.annotation.JsonIgnore;
import eu.socialedge.ddd.domain.id.Identifier;
import lombok.AccessLevel;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

import javax.persistence.*;

import static org.apache.commons.lang3.Validate.notNull;

/**
 * A {@link ValueObject} fundamentally defined not by its
 * attributes, but by a thread of continuity and identity.
 *
 *
In comparison to value objects, an entity's core
 * trait is it's identity. Two customers named Michael
 * Müller might not constitue the very same instance, so
 * that usually a dedicated property is introduced to capture
 * the identity. Another core trait of entities is that they're
 * usually subject to a certain lifecycle within the problem
 * event. They get created, they undergo certain state changes
 * usually driven by event events and might reach an end state
 * (i.e. might be deleted, although this doesn't necessary mean
 * that the information is removed from the system).

 *
 *
Entities usually relate to other entities and contain
 * properties that are value objects or primitives (the former
 * preferred).

 *
 * @see
 *     Domain-Driven Design and Spring - Oliver Gierke
 *
 * @param <T> concrete {@link Identifier} type implementation
 */
@EqualsAndHashCode(of = "id")
@NoArgsConstructor(force = true, access = AccessLevel.PROTECTED) // Required by JPA
@MappedSuperclass @Access(AccessType.FIELD)
public abstract class Entity<T extends Identifier<?>> {

    @EmbeddedId
    protected final T id;

    @JsonIgnore
    @Version
    private Long version;

    protected Entity(T id) {
        this.id = notNull(id);
    }

    public T id() {
        return id;
    }
}


text:
package brooklyn.entity.messaging.qpid;

import static java.lang.String.format;

import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;

import brooklyn.entity.messaging.amqp.AmqpExchange;
import brooklyn.util.exceptions.Exceptions;

public class QpidTopicImpl extends QpidDestinationImpl implements QpidTopic {

    public QpidTopicImpl() {
    }

    @Override
    public void onManagementStarting() {
        super.onManagementStarting();
        setAttribute(TOPIC_NAME, getName());
        try {
            String virtualHost = getParent().getVirtualHost();
            exchange = new ObjectName(format("org.apache.qpid:type=VirtualHost.Exchange,VirtualHost=\"%s\",name=\"%s\",ExchangeType=topic", virtualHost, getExchangeName()));
        } catch (MalformedObjectNameException e) {
            throw Exceptions.propagate(e);
        }
    }

    // TODO sensors
    @Override
    public void connectSensors() {
    }

    @Override
    public String getExchangeName() { return AmqpExchange.TOPIC; }

    @Override
    public String getTopicName() { return getQueueName(); }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
                                             xmlns:app="http://schemas.android.com/apk/res-auto"
                                             xmlns:tools="http://schemas.android.com/tools"
                                             android:layout_width="match_parent"
                                             android:layout_height="match_parent"
                                             tools:context="org.fraunhofer.cese.madcap.PermissionsActivity">

    <include
        android:id="@+id/my_toolbar"
        layout="@layout/action_bar"/>

    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="24sp"
        android:padding="8sp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/my_toolbar">

        <TextView
            android:id="@+id/headerText"
            style="@style/headerText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/permissions_header"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"/>

        <TextView
            android:id="@+id/contactsText"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="24sp"
            android:text="@string/contacts_short_rationale"
            app:layout_constraintHorizontal_weight="1"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@id/headerText"
            app:layout_constraintEnd_toStartOf="@+id/contactsCheckBox"/>

        <CheckBox
            android:id="@+id/contactsCheckBox"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:layout_constraintBottom_toBottomOf="@id/contactsText"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toEndOf="@id/contactsText"
            app:layout_constraintTop_toTopOf="@id/contactsText"
            />

        <TextView
            android:id="@+id/smsText"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="24sp"
            android:text="@string/sms_short_rationale"
            app:layout_constraintHorizontal_weight="1"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toStartOf="@+id/smsCheckBox"
            app:layout_constraintTop_toBottomOf="@id/contactsText"/>

        <CheckBox
            android:id="@+id/smsCheckBox"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:layout_constraintBottom_toBottomOf="@id/smsText"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toEndOf="@id/smsText"
            app:layout_constraintTop_toTopOf="@id/smsText"/>

        <TextView
            android:id="@+id/locationText"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="24sp"
            android:text="@string/location_short_rationale"
            app:layout_constraintHorizontal_weight="1"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toStartOf="@+id/locationCheckBox"
            app:layout_constraintTop_toBottomOf="@id/smsText"/>

        <CheckBox
            android:id="@+id/locationCheckBox"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:layout_constraintBottom_toBottomOf="@id/locationText"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toEndOf="@id/locationText"
            app:layout_constraintTop_toTopOf="@id/locationText"
            />

        <TextView
            android:id="@+id/telephoneText"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="24sp"
            android:text="@string/telephone_short_rationale"
            app:layout_constraintHorizontal_weight="1"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toStartOf="@+id/telephoneCheckBox"
            app:layout_constraintTop_toBottomOf="@id/locationText"
            />

        <CheckBox
            android:id="@+id/telephoneCheckBox"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:layout_constraintBottom_toBottomOf="@id/telephoneText"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toEndOf="@id/telephoneText"
            app:layout_constraintTop_toTopOf="@id/telephoneText"

            />

        <TextView
            android:id="@+id/usageText"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="24sp"
            android:text="@string/access_usage_short_rationale"
            app:layout_constraintHorizontal_weight="1"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toStartOf="@+id/usageStatsCheckBox"
            app:layout_constraintTop_toBottomOf="@id/telephoneText"
            />

        <CheckBox
            android:id="@+id/usageStatsCheckBox"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:layout_constraintBottom_toBottomOf="@id/usageText"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toEndOf="@id/usageText"
            app:layout_constraintTop_toTopOf="@id/usageText"
            />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="24dp"
            android:autoLink="web"
            android:gravity="center"
            android:text="@string/permissions_more_inf"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@id/usageText"/>

    </android.support.constraint.ConstraintLayout>

    <include layout="@layout/footer"/>
</android.support.constraint.ConstraintLayout>


text:
package itunes

func (p *Playlist) Name() string {
	return p.name
}


text:
package org.emmalanguage
package lib.ml.optimization.error

import api._
import lib.linalg._
import lib.ml.LDPoint
import lib.ml.optimization.loss.squared
import lib.stats.stat

/**
 * Mean Squared Error.
 *
 * This is similar to the SSE with normalization according to dataset-size
 *
 * loss:      E(w) = 1/2m sum{ (wTx - y)**2 }
 * gradient: dE(w) = 1/m  sum{ (wTx - y) *x }
 */
@emma.lib
object mse extends Error {

  def apply[ID](
    weights: DVector, instances: DataBag[LDPoint[ID, Double]]
  ): Double = 1.0 / (2.0 * instances.size) * instances.map(squared(weights, _)).sum

  def gradient[ID](
    weights: DVector, instances: DataBag[LDPoint[ID, Double]]
  ): DVector = stat.sum(weights.size)(instances.map(squared.gradient(weights, _))) / instances.size
}


text:
<?php

namespace Skolar\Modules\Server;

/**
 * AJAX request for schoollist
 *
 * @author David
 */
class SchoollistModule extends \Skolar\Modules\BaseModule {

    public function parse($content = null) {

        list($toplat, $toplng) = explode(",", $this->getRequestParam("northeast"));
        list($bottomlat, $bottomlng) = explode(",", $this->getRequestParam("southwest"));

        $stredlat = min($toplat, $bottomlat) + (abs($toplat - $bottomlat) / 2);
        $stredlng = min($toplng, $bottomlng) + (abs($toplng - $bottomlng) / 2);

        $limit = (is_numeric($this->getRequestParam("limit")) && $this->getRequestParam("limit") <= 60 && $this->getRequestParam("limit") >= 0) ? $this->getRequestParam("limit") : 60;

        $data = \dibi::query("SELECT id, name, url, address, latitude, longitude, (6378.10 * ACOS(COS(RADIANS(stredlat)) * COS(RADIANS(latitude)) * COS(RADIANS(longitude) - RADIANS(stredlong)) + SIN(RADIANS(stredlat)) * SIN(RADIANS(latitude)))) AS distance
        FROM [schoollist]
        JOIN (SELECT %f", $stredlat, " AS stredlat, %f", $stredlng, " AS stredlong) as stred WHERE (latitude BETWEEN %f", min($toplat, $bottomlat), " AND %f", max($toplat, $bottomlat), ") AND (longitude BETWEEN %f", min($toplng, $bottomlng), " AND %f", max($toplng, $bottomlng), ")
        HAVING distance < 20
        ORDER BY distance
        LIMIT 0, %i", $limit ,";")->fetchAll();

        return $this->response->setResult(array("schoollist" => $data));
    }

    public function getParameters($request = null) {
        return $this->parameters;
    }

}

?>


text:
class Composite : public Component {
public:
  virtual void update();
  virtual void draw() const;

  void addChild(std::shared_ptr<Component> child);
  //remove

protected:
  std::vector<std::shared_ptr<Component>> _children;
};

#endif // COMPOSITE_H


text:
FROM ubuntu:14.10
MAINTAINER Stephen J. Mason <hi@stephenmason.me>

RUN apt-get update
RUN apt-get install -y wget
RUN apt-get install -y docker.io
RUN apt-get install -y git
RUN wget -O- https://www.opscode.com/chef/install.sh | bash -s -- -P chefdk

# Gen UTF-8 locale
RUN locale-gen en_US.UTF-8
ENV LANG en_US.UTF-8

WORKDIR /tmp

# Kitchen-Docker GEM
RUN chef gem install kitchen-docker -v 2.0.0

# Kitchen azure gem
RUN chef gem install kitchen-azure

# Kitchen-EC2.. custom GEM
ENV kitchenec2commit 6fb9047
RUN git clone https://github.com/stevejmason/kitchen-ec2.git
WORKDIR /tmp/kitchen-ec2
RUN git checkout ${kitchenec2commit}
RUN chef gem build kitchen-ec2.gemspec
RUN chef gem install kitchen-ec2*.gem

# Working DIR
WORKDIR /kitchen


text:
<?php

	/**
	*
	*/
	class DesaSiagaAktif extends CActiveRecord
	{
		public static function model($className=__CLASS__)
			{
				return parent::model($className);
			}

			public function tableName()
			{
				return 'kes_siagaaktif';
			}
	}

?>


text:
<title>Remote Non-Stop - Debugging with GDB</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="Debugging with GDB">
<meta name="generator" content="makeinfo 4.11">
<link title="Top" rel="start" href="index.html#Top">
<link rel="up" href="Remote-Protocol.html#Remote-Protocol" title="Remote Protocol">
<link rel="prev" href="Notification-Packets.html#Notification-Packets" title="Notification Packets">
<link rel="next" href="Packet-Acknowledgment.html#Packet-Acknowledgment" title="Packet Acknowledgment">
<link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage">

<meta http-equiv="Content-Style-Type" content="text/css">

Next: Packet Acknowledgment,
Previous: Notification Packets,
Up: Remote Protocol

E.10 Remote Protocol Support for Non-Stop Mode

gdb's remote protocol supports non-stop debugging of
multi-threaded programs, as described in Non-Stop Mode.  If the stub
supports non-stop mode, it should report that to gdb by including
‘<samp>QNonStop+</samp>’ in its ‘<samp>qSupported</samp>’ response (see qSupported).

gdb typically sends a ‘<samp>QNonStop</samp>’ packet only when
establishing a new connection with the stub.  Entering non-stop mode
does not alter the state of any currently-running threads, but targets
must stop all threads in any already-attached processes when entering
all-stop mode.  gdb uses the ‘<samp>?</samp>’ packet as necessary to
probe the target state after a mode change.

In non-stop mode, when an attached process encounters an event that
would otherwise be reported with a stop reply, it uses the
asynchronous notification mechanism (see Notification Packets) to
inform gdb.  In contrast to all-stop mode, where all threads
in all processes are stopped when a stop reply is sent, in non-stop
mode only the thread reporting the stop event is stopped.  That is,
when reporting a ‘<samp>S</samp>’ or ‘<samp>T</samp>’ response to indicate completion
of a step operation, hitting a breakpoint, or a fault, only the
affected thread is stopped; any other still-running threads continue
to run.  When reporting a ‘<samp>W</samp>’ or ‘<samp>X</samp>’ response, all running
threads belonging to other attached processes continue to run.

In non-stop mode, the target shall respond to the ‘<samp>?</samp>’ packet as
follows.  First, any incomplete stop reply notification/‘<samp>vStopped</samp>’
sequence in progress is abandoned.  The target must begin a new
sequence reporting stop events for all stopped threads, whether or not
it has previously reported those events to gdb.  The first
stop reply is sent as a synchronous reply to the ‘<samp>?</samp>’ packet, and
subsequent stop replies are sent as responses to ‘<samp>vStopped</samp>’ packets
using the mechanism described above.  The target must not send
asynchronous stop reply notifications until the sequence is complete.
If all threads are running when the target receives the ‘<samp>?</samp>’ packet,
or if the target is not attached to any process, it shall respond
‘<samp>OK</samp>’.


text:
from cupy import _util

# expose cache handles to this module
from cupy.fft._cache import get_plan_cache  # NOQA
from cupy.fft._cache import clear_plan_cache  # NOQA
from cupy.fft._cache import get_plan_cache_size  # NOQA
from cupy.fft._cache import set_plan_cache_size  # NOQA
from cupy.fft._cache import get_plan_cache_max_memsize  # NOQA
from cupy.fft._cache import set_plan_cache_max_memsize  # NOQA
from cupy.fft._cache import show_plan_cache_info  # NOQA

# on Linux, expose callback handles to this module
import sys as _sys
if _sys.platform.startswith('linux'):
    from cupy.fft._callback import get_current_callback_manager  # NOQA
    from cupy.fft._callback import set_cufft_callbacks  # NOQA
else:
    def get_current_callback_manager(*args, **kwargs):
        return None

    class set_cufft_callbacks:  # type: ignore
        def __init__(self, *args, **kwargs):
            raise RuntimeError('cuFFT callback is only available on Linux')

enable_nd_planning = True
use_multi_gpus = False
_devices = None

def set_cufft_gpus(gpus):
    '''Set the GPUs to be used in multi-GPU FFT.

    Args:
        gpus (int or list of int): The number of GPUs or a list of GPUs
            to be used. For the former case, the first ``gpus`` GPUs
            will be used.

    .. warning::
        This API is currently experimental and may be changed in the future
        version.

    .. seealso:: `Multiple GPU cuFFT Transforms`_

    .. _Multiple GPU cuFFT Transforms:
        https://docs.nvidia.com/cuda/cufft/index.html#multiple-GPU-cufft-transforms
    '''
    _util.experimental('cupy.fft.config.set_cufft_gpus')
    global _devices

    if isinstance(gpus, int):
        devs = [i for i in range(gpus)]
    elif isinstance(gpus, list):
        devs = gpus
    else:
        raise ValueError("gpus must be an int or a list of int.")
    if len(devs) <= 1:
        raise ValueError("Must use at least 2 GPUs.")

    # make it hashable
    _devices = tuple(devs)


text:
'''This module provides the object representation of a CurrencyCloud Contact'''

from currencycloud.resources.resource import Resource
from currencycloud.resources.actions import UpdateMixin

class Iban(UpdateMixin, Resource):
    '''This class represents a CurrencyCloud IBAN'''
    pass


text:
package test.searchbox.framework;

import javax.sql.DataSource;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.aspectj.EnableSpringConfigured;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.searchbox.framework.repository.CollectionRepository;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackageClasses = { CollectionRepository.class })
@EnableSpringConfigured
@PropertySource("classpath:application.properties")
@ComponentScan(basePackages = { "com.searchbox.framework.model" })
public class PersistenceTestConfig {

  @Bean
  public DataSource dataSource() {
    return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2)
        .build();
  }

  @Bean(name = "entityManagerFactory")
  public LocalContainerEntityManagerFactoryBean entityManagerFactory(
      DataSource dataSource, JpaVendorAdapter jpaVendorAdapter) {
    LocalContainerEntityManagerFactoryBean lef = new LocalContainerEntityManagerFactoryBean();
    lef.setDataSource(dataSource);
    lef.setJpaVendorAdapter(jpaVendorAdapter);
    lef.setPackagesToScan("com.searchbox.framework.model");
    return lef;
  }

  @Bean
  public JpaVendorAdapter jpaVendorAdapter() {
    HibernateJpaVendorAdapter hibernateJpaVendorAdapter = new HibernateJpaVendorAdapter();
    hibernateJpaVendorAdapter.setShowSql(true);
    hibernateJpaVendorAdapter.setGenerateDdl(true);
    hibernateJpaVendorAdapter.setDatabase(Database.H2);
    return hibernateJpaVendorAdapter;
  }

  @Bean(name = "transactionManager")
  public PlatformTransactionManager transactionManager() {
    JpaTransactionManager txManager = new JpaTransactionManager();
    return txManager;
  }
}


text:
package ca.josephroque.stayawhile.desktop;

import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
import ca.josephroque.stayawhile.StayAwhile;

public class DesktopLauncher {
	public static void main (String[] arg) {
		LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
		new LwjglApplication(new StayAwhile(), config);
	}
}


text:
import logging
logger = logging.getLogger('differ.changes')

class CHANGE_STATE():
  NONE =         0
  ADD =          1 << 0
  REMOVED =      1 << 1
  CHANGED =      1 << 2
  CHANGED_STAT = 1 << 3

class Change(object):
  def __init__(self, path):
    self.path = path
    self.state = CHANGE_STATE.NONE
    self.related = []

  def __repr__(self):
    return ("path={} state={} num_related={}".format(
      self.path,
      self.state,
      len(self.related)))

class Changes(object):
  def __init__(self):
    self.changes = {}

  def get_list_by_state(self, state):
    """Get a list of changes by state

    :param state: The state to look up
    :return: List of changes that match the state
    """
    items = []
    for item in self.changes.values():
      if (item.state & state) == state:
        items.append(item.path)
    print("Result {}".format(items))
    return items

  def get_added(self):
    return self.get_list_by_state(CHANGE_STATE.ADD)

  def get_removed(self):
    return self.get_list_by_state(CHANGE_STATE.REMOVED)

  def get_changed(self):
    return self.get_list_by_state(CHANGE_STATE.CHANGED)

  def get_changed_stat(self):
    return self.get_list_by_state(CHANGE_STATE.CHANGED_STAT)

  def get_or_add(self, path):
    """Get or add a change

    :param path: Path associated to the change
    :return: The change object which was either looked up or added
    """
    obj = self.changes.get(path)
    if obj:
      return obj
    self.changes[path] = Change(path)
    return self.changes[path]

  def set_state(self, path, state):
    """Set a state to the change associated to a path

    :param path: The path associated to the change
    :param state: The state of the change
    """
    obj = self.get_or_add(path)
    obj.state |= state
    logger.debug("path={} state={} updated state={}".format(
      path,
      state,
      obj.state))

  def mark_added(self, path):
    self.set_state(path, CHANGE_STATE.ADD)

  def mark_deleted(self, path):
    self.set_state(path, CHANGE_STATE.REMOVED)

  def mark_changed(self, path):
    self.set_state(path, CHANGE_STATE.CHANGED)

  def mark_changed_stat(self, path):
    self.set_state(path, CHANGE_STATE.CHANGED_STAT)

  def add_related(self, path, related_path):
    """Add a related path to the change

    :param path: The path associated to the change
    :param related_path: The related path to the change
    """
    obj = self.get_or_add(path)
    obj.related.append(related_path)


text:
Listen to Soundcloud tracks & playlists with your friends!

Built with Rails, React and Firebase.

Demo hosted on Heroku at [soundcloud-demo.kus.dk](http://soundcloud-demo.kus.dk)

## TODO

 - Add a list of public rooms to the homepage.
 - Add a way for owners of rooms to remove access for specific users.
 - Add a name generator for guest users that generates readable names.
 - Better error handling when the owner of a room disconnects.
 - Better testing of react components.


text:
/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/

/***
  This file is part of systemd.

  Copyright 2010-2012 Lennart Poettering

  systemd is free software; you can redistribute it and/or modify it
  under the terms of the GNU Lesser General Public License as published by
  the Free Software Foundation; either version 2.1 of the License, or
  (at your option) any later version.

  systemd is distributed in the hope that it will be useful, but
  WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  Lesser General Public License for more details.

  You should have received a copy of the GNU Lesser General Public License
  along with systemd; If not, see <http://www.gnu.org/licenses/>.
***/

#include <assert.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <stdlib.h>
#include <signal.h>
#include <stdio.h>
#include <fcntl.h>
#include <dirent.h>
#include <sys/statvfs.h>

#include "macro.h"
#include "util.h"
#include "log.h"
#include "path-util.h"
#include "missing.h"

bool path_is_absolute(const char *p) {
        return p[0] == '/';
}

char *path_kill_slashes(char *path) {
        char *f, *t;
        bool slash = false;

        /* Removes redundant inner and trailing slashes. Modifies the
         * passed string in-place.
         *
         * ///foo///bar/ becomes /foo/bar
         */

        for (f = path, t = path; *f; f++) {

                if (*f == '/') {
                        slash = true;
                        continue;
                }

                if (slash) {
                        slash = false;
                        *(t++) = '/';
                }

                *(t++) = *f;
        }

        /* Special rule, if we are talking of the root directory, a
        trailing slash is good */

        if (t == path && slash)
                *(t++) = '/';

        *t = 0;
        return path;
}

char* path_startswith(const char *path, const char *prefix) {
        assert(path);
        assert(prefix);

        if ((path[0] == '/') != (prefix[0] == '/'))
                return NULL;

        for (;;) {
                size_t a, b;

                path += strspn(path, "/");
                prefix += strspn(prefix, "/");

                if (*prefix == 0)
                        return (char*) path;

                if (*path == 0)
                        return NULL;

                a = strcspn(path, "/");
                b = strcspn(prefix, "/");

                if (a != b)
                        return NULL;

                if (memcmp(path, prefix, a) != 0)
                        return NULL;

                path += a;
                prefix += b;
        }
}

bool path_equal(const char *a, const char *b) {
        assert(a);
        assert(b);

        if ((a[0] == '/') != (b[0] == '/'))
                return false;

        for (;;) {
                size_t j, k;

                a += strspn(a, "/");
                b += strspn(b, "/");

                if (*a == 0 && *b == 0)
                        return true;

                if (*a == 0 || *b == 0)
                        return false;

                j = strcspn(a, "/");
                k = strcspn(b, "/");

                if (j != k)
                        return false;

                if (memcmp(a, b, j) != 0)
                        return false;

                a += j;
                b += k;
        }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Kiwi.HUD.HUDWidget - Kiwi.js</title>
    <link rel="stylesheet" href="http://yui.yahooapis.com/3.9.1/build/cssgrids/cssgrids-min.css">
    <link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css">
    <link rel="stylesheet" href="../assets/css/main.css" id="site_styles">
    <link rel="shortcut icon" type="image/png" href="../assets/favicon.png">

            API Docs for: 1.3.0

APIs

Classes

Modules

            <input type="search" id="api-filter" placeholder="Type to filter APIs">

Kiwi.Animations.Animation

Kiwi.Animations.Sequence

Kiwi.Animations.Tween

Kiwi.Animations.Tweens.Easing.Back

Kiwi.Animations.Tweens.Easing.Bounce

Kiwi.Animations.Tweens.Easing.Circular

Kiwi.Animations.Tweens.Easing.Cubic

Kiwi.Animations.Tweens.Easing.Elastic

Kiwi.Animations.Tweens.Easing.Exponential

Kiwi.Animations.Tweens.Easing.Linear

Kiwi.Animations.Tweens.Easing.Quadratic

Kiwi.Animations.Tweens.Easing.Quartic

Kiwi.Animations.Tweens.Easing.Quintic

Kiwi.Animations.Tweens.Easing.Sinusoidal

Kiwi.Animations.Tweens.TweenManager

Kiwi.Camera

Kiwi.CameraManager

Kiwi.Component

Kiwi.ComponentManager

Kiwi.Components.AnimationManager

Kiwi.Components.ArcadePhysics

Kiwi.Components.Box

Kiwi.Components.Input

Kiwi.Components.Sound

Kiwi.Entity

Kiwi.Files.AudioFile

Kiwi.Files.DataFile

Kiwi.Files.DataLibrary

Kiwi.Files.File

Kiwi.Files.FileStore

Kiwi.Files.Loader

Kiwi.Files.TextureFile

Kiwi.Game

Kiwi.GameManager

Kiwi.GameObjects.Sprite

Kiwi.GameObjects.StaticImage

Kiwi.GameObjects.TextField

Kiwi.GameObjects.Tilemap.TileMap

Kiwi.GameObjects.Tilemap.TileMapLayer

Kiwi.GameObjects.Tilemap.TileMapLayerIsometric

Kiwi.GameObjects.Tilemap.TileMapLayerOrthogonal

Kiwi.GameObjects.Tilemap.TileType

Kiwi.Geom.AABB

Kiwi.Geom.Circle

Kiwi.Geom.Intersect

Kiwi.Geom.IntersectResult

Kiwi.Geom.Line

Kiwi.Geom.Matrix

Kiwi.Geom.Point

Kiwi.Geom.Ray

Kiwi.Geom.Rectangle

Kiwi.Geom.Transform

Kiwi.Geom.Vector2

Kiwi.Group

Kiwi.HUD.HUDComponents.Counter

Kiwi.HUD.HUDComponents.Time

Kiwi.HUD.HUDComponents.WidgetInput

Kiwi.HUD.HUDDisplay

Kiwi.HUD.HUDManager

Kiwi.HUD.HUDWidget

Kiwi.HUD.Widget.Bar

Kiwi.HUD.Widget.BasicScore

Kiwi.HUD.Widget.Button

Kiwi.HUD.Widget.Icon

Kiwi.HUD.Widget.IconBar

Kiwi.HUD.Widget.Menu

Kiwi.HUD.Widget.MenuItem

Kiwi.HUD.Widget.TextField

Kiwi.HUD.Widget.Time

Kiwi.IChild

Kiwi.Input.Finger

Kiwi.Input.InputManager

Kiwi.Input.Key

Kiwi.Input.Keyboard

Kiwi.Input.Keycodes

Kiwi.Input.Mouse

Kiwi.Input.MouseCursor

Kiwi.Input.Pointer

Kiwi.Input.Touch

Kiwi.PluginManager

Kiwi.Renderers.CanvasRenderer

Kiwi.Renderers.GLArrayBuffer

Kiwi.Renderers.GLBlendMode

Kiwi.Renderers.GLElementArrayBuffer

Kiwi.Renderers.GLRenderManager

Kiwi.Renderers.GLTextureManager

Kiwi.Renderers.GLTextureWrapper

Kiwi.Renderers.Renderer

Kiwi.Renderers.TextureAtlasRenderer

Kiwi.Shaders.ShaderManager

Kiwi.Shaders.ShaderPair

Kiwi.Shaders.TextureAtlasShader

Kiwi.Signal

Kiwi.SignalBinding

Kiwi.Sound.Audio

Kiwi.Sound.AudioLibrary

Kiwi.Sound.AudioManager

Kiwi.Stage

Kiwi.State

Kiwi.StateConfig

Kiwi.StateManager

Kiwi.System.Bootstrap

Kiwi.System.Device

Kiwi.Textures.SingleImage

Kiwi.Textures.SpriteSheet

Kiwi.Textures.TextureAtlas

Kiwi.Textures.TextureLibrary

Kiwi.Time.Clock

Kiwi.Time.ClockManager

Kiwi.Time.MasterClock

Kiwi.Time.Timer

Kiwi.Time.TimerEvent

Kiwi.Utils.Canvas

Kiwi.Utils.Color

Kiwi.Utils.Common

Kiwi.Utils.GameMath

Kiwi.Utils.Log

Kiwi.Utils.RandomDataGenerator

Kiwi.Utils.RequestAnimationFrame

Kiwi.Utils.Version

Animations

Components

Easing

Files

GameObjects

Geom

HUD

HUDComponents

Input

Kiwi

Renderers

Shaders

Sound

System

Textures

Tilemap

Time

Tweens

Utils

Utils.

Widget

        Show:

            <input type="checkbox" id="api-show-inherited" checked>
            Inherited

            <input type="checkbox" id="api-show-protected">
            Protected

            <input type="checkbox" id="api-show-private">
            Private

            <input type="checkbox" id="api-show-deprecated">
            Deprecated

Kiwi.HUD.HUDWidget Class

            Defined in: src\hud\HUDWidget.ts:9

            Module: HUD

            Parent Module: Kiwi

The HUDWidget is an abstract class containing the fundamental properties and methods that every HUDWidget needs to have.
This class is designed to be extended from and thus objects should not directly instantiate it.

Constructor

Kiwi.HUD.HUDWidget

            (

                        game

                        name

                        x

                        y

)

            Kiwi.HUD.HUDWidget

                Defined in

        src\hud\HUDWidget.ts:9

Parameters:

                        game
                        Kiwi.Game

The game that this HUDWidget belongs to.

                        name
                        String

Name of the type of HUDWidget.

                        x
                        Number

The coordinates of this HUDWidget on the x-axis.

                        y
                        Number

The coordinates of this HUDWidget on the y-axis.

Returns:

                        Kiwi.HUD.HUDWidget:

Index

Methods

Properties

Item Index

Methods

                                destroy

                                objType

                                removeTemplate

                                setTemplate

                                update

Properties

                                _device

                                _horizontalOrigin

                                _manager

                                _tempContainer

                                _tempParent

                                _verticalOrigin

                                _x

                                _y

                                BOTTOM

                                    static

                                class

                                components

                                game

                                horizontalOrigin

                                LEFT

                                    static

                                onCoordsUpdate

                                RIGHT

                                    static

                                style

                                tempElement

                                TOP

                                    static

                                vertical

                                x

                                y

Methods

destroy

        ()

        public

                Defined in

        src\hud\HUDWidget.ts:426

objType

        ()

            String

        public

                Defined in

        src\hud\HUDWidget.ts:46

Returns the type of object that this is.

Returns:

                        String:

"HUDWidget"

removeTemplate

        ()

        public

                Defined in

        src\hud\HUDWidget.ts:251

Used to remove any the template HTML from this HUDWidget.
Currently doesn't have that great support.

setTemplate

            (

                        main

                        [element]

)

        public

                Defined in

        src\hud\HUDWidget.ts:213

This method is used to remove existing DOM elements and place them inside a HUDWidget's container element.
Useful so that when making HUD Widgets the developer can style HUDWidgets without having to create/write to much javascript.

Can be used by itself but maybe more useful if you customise it to suit your own needs.
Currently doesn't have that great support.

Parameters:

                        main
                        String

main - ID of an HTMLElement. This element should contain all of the elements you would like to place inside the HUDWidget.

                        [element]
                        String
                        optional

element - ID of an HTMLElement that resides inside of the main param. This is the element that the HUDWidget can use to populate with information. E.g. Your score, health remaining, the icon, e.t.c.

update

        ()

        public

                Defined in

        src\hud\HUDWidget.ts:287

The game update loop.

Properties

_device

    _device

        protected

                Defined in

        src\hud\HUDWidget.ts:65

The type of device that this game is being targeted at. Same as the deviceTargetOption on the game class.
Used to detirmine how the HUD is to be managed behind the scenes.
This is mainly indented for INTERNAL Kiwi use only and is public so that sub classes can have a reference to it.

_horizontalOrigin

    String

        protected

                Defined in

        src\hud\HUDWidget.ts:296

Available since 1.3.0

Contains the current CSS style that will used for the x position.
Should either be LEFT or RIGHT but these values are not checked upon assignment.

Default: 'left'

_manager

    Kiwi.HUD.HUDManager

        protected

                Defined in

        src\hud\HUDWidget.ts:56

The HUDManager that this widget 'belongs' to.
This is mainly indented for INTERNAL Kiwi use only and is public so that sub classes can have a reference to it.

_tempContainer

    HTMLElement

        private

                Defined in

        src\hud\HUDWidget.ts:204

The container element for the template
Currently doesn't have that great support.

_tempParent

    HTMLElement

        private

                Defined in

        src\hud\HUDWidget.ts:195

The parent of the template container. So that when removing a template we can place it in the right spot
Currently doesn't have that great support.

_verticalOrigin

    String

        protected

                Defined in

        src\hud\HUDWidget.ts:333

Available since 1.3.0

Contains the current CSS style that will used for the y position.
Should either be TOP or BOTTOM but these values are not checked upon assignment.

Default: 'top'

_x

    Number

        private

                Defined in

        src\hud\HUDWidget.ts:108

The x coordinate of the widget

_y

    Number

        private

                Defined in

        src\hud\HUDWidget.ts:135

The y coordinate of the widget

BOTTOM

    String

        public

        final

        static

                Defined in

        src\hud\HUDWidget.ts:384

Available since 1.3.0

Contains the CSS style used to position a HUD element from the bottom corner.

Default: 'bottom'

class

    String

        public

                Defined in

        src\hud\HUDWidget.ts:270

The class name/s that the container element that this HUDWidget current has.

components

    Kiwi.ComponentManager

        public

                Defined in

        src\hud\HUDWidget.ts:162

The list of components that the HUDWidget use's.

game

    Kiwi.Game

        public

                Defined in

        src\hud\HUDWidget.ts:75

The game that this HUDWidget belongs to.

horizontalOrigin

    String

        public

                Defined in

        src\hud\HUDWidget.ts:308

Available since 1.3.0

Contains the current CSS style that will used for the x position.
Should either be LEFT or RIGHT but these values are not checked upon assignment.

Default: 'left'

LEFT

    String

        public

        final

        static

                Defined in

        src\hud\HUDWidget.ts:398

Available since 1.3.0

Contains the CSS style used to position a HUD element from the left corner.

Default: 'left'

onCoordsUpdate

    Kiwi.Signal

        public

                Defined in

        src\hud\HUDWidget.ts:100

Called when the coordinates of the HUD Widget updates.

RIGHT

    String

        public

        final

        static

                Defined in

        src\hud\HUDWidget.ts:412

Available since 1.3.0

Contains the CSS style used to position a HUD element from the right corner.

Default: 'right'

    HTMLDivElement

        public

                Defined in

        src\hud\HUDWidget.ts:170

The HTMLDivElement that this widget is using.

    String

        public

                Defined in

        src\hud\HUDWidget.ts:178

The name of the widget which is used to identify the type of widget.

style

    Any

        public

                Defined in

        src\hud\HUDWidget.ts:83

A quick way to reference the style object that exists on the container element of this widget.

tempElement

    HTMLElement

        public

                Defined in

        src\hud\HUDWidget.ts:186

When a template has been set, this property will have a reference to the HTMLElement we can place the HUDWidget information into.
Currently doesn't have that great support.

TOP

    String

        public

        final

        static

                Defined in

        src\hud\HUDWidget.ts:370

Available since 1.3.0

Contains the CSS style used to position a HUD element from the top corner.

Default: 'top'

vertical

    String

        public

                Defined in

        src\hud\HUDWidget.ts:345

Available since 1.3.0

Contains the current CSS style that will used for the y position.
Should either be TOP or BOTTOM but these values are not checked upon assignment.

Default: 'top'

x

    Number

        public

                Defined in

        src\hud\HUDWidget.ts:116

Get the x coordinate of the widget

y

    Number

        public

                Defined in

        src\hud\HUDWidget.ts:143

Get the y coordinate of the widget


text:
SYNONYM

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

#### Published in
null

#### Original name
Amphisphaeria hypoxylon Ellis & Everh., 1886

### Remarks
null


text:
package jkind.smv.visitors;

import jkind.smv.SMVArrayType;
import jkind.smv.SMVEnumType;
import jkind.smv.SMVNamedType;
import jkind.smv.SMVSubrangeIntType;

public interface SMVTypeVisitor<T> {
	public T visit(SMVArrayType e);

	public T visit(SMVEnumType e);

	public T visit(SMVNamedType e);

	public T visit(SMVSubrangeIntType e);
}


text:
package karob.bigtrees.generators;

import java.util.List;

import karob.bigtrees.config.BlockAndMeta;
import net.minecraft.block.Block;
import net.minecraft.world.World;
import net.minecraft.world.gen.feature.WorldGenerator;

public abstract class AbstractWorldGenerator extends WorldGenerator {

	protected World worldObject;

	protected List<BlockAndMeta> baseblocks;

	protected AbstractWorldGenerator(boolean doBlockNotify) {
		super(doBlockNotify);
	}

	protected void setBlock(int x, int y, int z, Block block) {
		try {
			worldObject.setBlock(x, y, z, block, 0, 3);
		} catch (RuntimeException e) {
//			FMLLog.getLogger().error(new FormattedMessage("setBlock(%s, %s, %s)", new Object[]{ x, y, z }));
		}
	}

	protected void setBlockAndMetadata(int x, int y, int z, Block block, int meta) {
		try {
			worldObject.setBlock(x, y, z, block, meta, 3);
		} catch (RuntimeException e) {
//			FMLLog.getLogger().error(new FormattedMessage("setBlockAndMetadata(%s, %s, %s)", new Object[]{ x, y, z }));
		}
	}

	protected void setBlockAndMetadataWithNotify(int x, int y, int z, Block block, int meta) {
		try {
			worldObject.setBlock(x, y, z, block);
			worldObject.setBlockMetadataWithNotify(x, y, z, meta, 3);
		} catch (RuntimeException e) {
//			FMLLog.getLogger().error(new FormattedMessage("setBlockAndMetadataWithNotify(%s, %s, %s)", new Object[]{ x, y, z }));
		}
	}

	protected Block getBlock(int x, int y, int z) {
		try {
			return worldObject.getBlock(x, y, z);
		} catch (RuntimeException e) {
//			FMLLog.getLogger().error(new FormattedMessage("getBlock(%s, %s, %s)", new Object[]{ x, y, z }));
			return null;
		}
	}

	protected int getBlockMetadata(int x, int y, int z) {
		try {
			return worldObject.getBlockMetadata(x, y, z);
		} catch (RuntimeException e) {
//			FMLLog.getLogger().error(new FormattedMessage("getBlock(%s, %s, %s)", new Object[]{ x, y, z }));
			return 0;
		}
	}

	protected boolean isSupportedBaseBlock(int x, int y, int z) {
		Block block = getBlock(x, y, z);
		int meta = getBlockMetadata(x, y, z);

		for (BlockAndMeta possibleBaseBlock : baseblocks) {
			if (possibleBaseBlock.areEqual(block, meta)) {
				return true;
			}
		}

		return false;
	}
}


text:
/**
 * Utility classes, mostly related to classloading.
 */
package org.apache.s4.base.util;


text:
package com.framwork.arcanimator;

import android.graphics.PointF;

import java.util.Arrays;

class ArcMetric {

    PointF mStartPoint = new PointF();

    PointF mEndPoint = new PointF();

    PointF mMidPoint = new PointF();

    PointF mAxisPoint[] = new PointF[2];

    PointF mZeroPoint = new PointF();

    //SEGMENTS. This Segments create virtual triangle except mZeroStartSegment

    float mStartEndSegment;

    float mRadius;

    float mMidAxisSegment;

    float mZeroStartSegment;

    //DEGREES.

    float mAnimationDegree;

    float mSideDegree;

    float mZeroStartDegree;

    float mStartDegree;

    float mEndDegree;

    //Side of animation
    Side mSide;

    private void createAxisVariables(){
        for(int i=0; i<mAxisPoint.length; i++)
            mAxisPoint[i] = new PointF();
    }

    private void calcStartEndSeg(){
        mStartEndSegment = (float) Math.sqrt(Math.pow(mStartPoint.x - mEndPoint.x, 2) +
                Math.pow(mStartPoint.y - mEndPoint.y, 2));

    }

    private void calcRadius(){
        mSideDegree = (180 - mAnimationDegree)/2;
        mRadius = mStartEndSegment/ ArcUtils.sin(mAnimationDegree)* ArcUtils.sin(mSideDegree);
    }

    private void calcMidAxisSeg(){
        mMidAxisSegment = mRadius * ArcUtils.sin(mSideDegree);
    }

    private void calcMidPoint(){
        mMidPoint.x = mStartPoint.x + mStartEndSegment/2*(mEndPoint.x - mStartPoint.x)/mStartEndSegment;
        mMidPoint.y = mStartPoint.y + mStartEndSegment/2*(mEndPoint.y - mStartPoint.y)/mStartEndSegment;
    }

    private void calcAxisPoints(){
        if(mStartPoint.y > mEndPoint.y || mStartPoint.y == mEndPoint.y){
            mAxisPoint[0].x = mMidPoint.x + mMidAxisSegment*(mEndPoint.y-mStartPoint.y)/mStartEndSegment;
            mAxisPoint[0].y = mMidPoint.y - mMidAxisSegment*(mEndPoint.x-mStartPoint.x)/mStartEndSegment;

            mAxisPoint[1].x = mMidPoint.x - mMidAxisSegment*(mEndPoint.y-mStartPoint.y)/mStartEndSegment;
            mAxisPoint[1].y = mMidPoint.y + mMidAxisSegment*(mEndPoint.x-mStartPoint.x)/mStartEndSegment;
        }else{
            mAxisPoint[0].x = mMidPoint.x - mMidAxisSegment*(mEndPoint.y-mStartPoint.y)/mStartEndSegment;
            mAxisPoint[0].y = mMidPoint.y + mMidAxisSegment*(mEndPoint.x-mStartPoint.x)/mStartEndSegment;

            mAxisPoint[1].x = mMidPoint.x + mMidAxisSegment*(mEndPoint.y-mStartPoint.y)/mStartEndSegment;
            mAxisPoint[1].y = mMidPoint.y - mMidAxisSegment*(mEndPoint.x-mStartPoint.x)/mStartEndSegment;
        }
    }

    private void calcZeroPoint(){
        switch (mSide){
            case RIGHT:
                mZeroPoint.x = mAxisPoint[Side.RIGHT.value].x + mRadius;
                mZeroPoint.y = mAxisPoint[Side.RIGHT.value].y;
                break;
            case LEFT:
                mZeroPoint.x = mAxisPoint[Side.LEFT.value].x - mRadius;
                mZeroPoint.y = mAxisPoint[Side.LEFT.value].y;
                break;
        }
    }

    private void calcDegrees(){
        mZeroStartSegment = (float) Math.sqrt(Math.pow(mZeroPoint.x - mStartPoint.x, 2) +
                Math.pow(mZeroPoint.y - mStartPoint.y, 2));
        mZeroStartDegree = ArcUtils.acos((2 * Math.pow(mRadius, 2) - Math.pow(mZeroStartSegment, 2)) / (2 * Math.pow(mRadius, 2)));
        switch(mSide){
            case RIGHT:
                if(mStartPoint.y <= mZeroPoint.y){
                    if(mStartPoint.y > mEndPoint.y ||
                            (mStartPoint.y == mEndPoint.y && mStartPoint.x > mEndPoint.x)){
                        mStartDegree = mZeroStartDegree;
                        mEndDegree = mStartDegree + mAnimationDegree;
                    }else{
                        mStartDegree = mZeroStartDegree;
                        mEndDegree = mStartDegree - mAnimationDegree;
                    }
                }else if(mStartPoint.y >= mZeroPoint.y){
                    if(mStartPoint.y < mEndPoint.y ||
                            (mStartPoint.y == mEndPoint.y && mStartPoint.x > mEndPoint.x)){
                        mStartDegree = 0 - mZeroStartDegree;
                        mEndDegree = mStartDegree - mAnimationDegree;
                    }else {
                        mStartDegree = 0 - mZeroStartDegree;
                        mEndDegree = mStartDegree + mAnimationDegree;
                    }
                }
                break;
            case LEFT:
                if(mStartPoint.y <= mZeroPoint.y){
                    if(mStartPoint.y > mEndPoint.y ||
                            (mStartPoint.y == mEndPoint.y && mStartPoint.x < mEndPoint.x)){
                        mStartDegree = 180 - mZeroStartDegree;
                        mEndDegree = mStartDegree - mAnimationDegree;
                    }else{
                        mStartDegree = 180 - mZeroStartDegree;
                        mEndDegree = mStartDegree + mAnimationDegree;
                    }
                }else if(mStartPoint.y >= mZeroPoint.y){
                    if(mStartPoint.y < mEndPoint.y ||
                            (mStartPoint.y == mEndPoint.y && mStartPoint.x < mEndPoint.x)){
                        mStartDegree = 180 + mZeroStartDegree;
                        mEndDegree = mStartDegree + mAnimationDegree;
                    }else{
                        mStartDegree = 180 + mZeroStartDegree;
                        mEndDegree = mStartDegree - mAnimationDegree;
                    }
                }
                break;
        }
    }

    /**
     * Create new {@link ArcMetric} instance and do all calculations below
     * and finally return ready to use object
     */
    public static ArcMetric evaluate(float startX, float startY,
                                       float endX, float endY,
                                       float degree, Side side){
        //TODO return ready to use object with have done computations
        ArcMetric arcMetric = new ArcMetric();
        arcMetric.mStartPoint.set(startX, startY);
        arcMetric.mEndPoint.set(endX, endY);
        arcMetric.setDegree(degree);
        arcMetric.mSide = side;
        arcMetric.createAxisVariables();

        arcMetric.calcStartEndSeg();
        arcMetric.calcRadius();
        arcMetric.calcMidAxisSeg();
        arcMetric.calcMidPoint();
        arcMetric.calcAxisPoints();
        arcMetric.calcZeroPoint();
        arcMetric.calcDegrees();

        return arcMetric;
    }

    public void setDegree(float degree) {
        degree = Math.abs(degree);
        if(degree>180)
            setDegree(degree%180);
        else if(degree == 180)
            setDegree(degree-1);
        else if(degree<30)
            setDegree(30);
        else
            this.mAnimationDegree = degree;
    }

    PointF getAxisPoint(){
        return mAxisPoint[mSide.value];
    }

    /**
     * Return evaluated start degree
     *
     * @return the start degree
     */
    public float getStartDegree(){
        return mStartDegree;
    }

    /**
     * Return evaluated end degree
     *
     * @return the end degree
     */
    public float getEndDegree(){
        return mEndDegree;
    }

    @Override
    public String toString() {
        return "ArcMetric{" +
                "\nmStartPoint=" + mStartPoint +
                "\n mEndPoint=" + mEndPoint +
                "\n mMidPoint=" + mMidPoint +
                "\n mAxisPoint=" + Arrays.toString(mAxisPoint) +
                "\n mZeroPoint=" + mZeroPoint +
                "\n mStartEndSegment=" + mStartEndSegment +
                "\n mRadius=" + mRadius +
                "\n mMidAxisSegment=" + mMidAxisSegment +
                "\n mZeroStartSegment=" + mZeroStartSegment +
                "\n mAnimationDegree=" + mAnimationDegree +
                "\n mSideDegree=" + mSideDegree +
                "\n mZeroStartDegree=" + mZeroStartDegree +
                "\n mStartDegree=" + mStartDegree +
                "\n mEndDegree=" + mEndDegree +
                "\n mSide=" + mSide +
                '}';
    }
}


text:
OOP = OOP or {};

-- Integrates a library into a given class. This takes all
-- public (non-double-underscored functions), and adds them
-- to the specified class.
function OOP.IntegrateLibrary(library, class)
	for funcName, func in pairs(library) do
		if not string.match(funcName, "^__") then
			class[funcName] = func;
		end;
	end
end

function OOP.InstanceOf(class, instance)
	assert(OOP.IsClass(class), "class is not a class: " .. tostring(class));
	if not OOP.IsInstance(instance) then
		return false;
	end;
	local candidateClass = instance.class;
	while true do
		if candidateClass == class then
			return true;
		end;
		local super = candidateClass.super;
		if super ~= nil and super ~= candidateClass then
			candidateClass = super;
		else
			break;
		end;
	end;
	return false;
end;

function OOP.IsInstance(candidate)
	if type(candidate) ~= "table" then
		return false;
	end;
	return OOP.IsClass(rawget(candidate, "class"));
end;

function OOP.IsClass(candidate)
	if type(candidate) ~= "table" then
		return false;
	end;
	if rawget(candidate, "class") then
		return false;
	end;
	return IsCallable(rawget(candidate,"New"));
end;


text:
from __future__ import unicode_literals

from django.contrib import messages
from django.contrib.messages.middleware import MessageMiddleware
from django.contrib.sessions.middleware import SessionMiddleware
from django.core.paginator import Page, Paginator
from django.core.urlresolvers import reverse

from djet.testcases import MiddlewareType
from model_mommy import mommy

from base.utils import BaseTestCase

class CategoryListViewTest(BaseTestCase):
    from category.views import CategoryListView

    url = reverse('category:category_list')
    view_class = CategoryListView

    def test_view_with_no_category(self):
        response = self.get()

        self.assertEqual(200, response.status_code)
        self.assertTemplateUsed(response, 'category/list.html')
        self.assertIsInstance(response.context_data['paginator'], Paginator)
        self.assertIsInstance(response.context_data['page_obj'], Page)
        self.assertFalse(response.context_data['is_paginated'])
        self.assertEqual(0, response.context_data['categories'].count())

    def test_view_with_no_active_category(self):
        mommy.make('Category', is_deleted=True)
        response = self.get()

        self.assertEqual(200, response.status_code)
        self.assertTemplateUsed(response, 'category/list.html')
        self.assertIsInstance(response.context_data['paginator'], Paginator)
        self.assertIsInstance(response.context_data['page_obj'], Page)
        self.assertFalse(response.context_data['is_paginated'])
        self.assertEqual(0, response.context_data['categories'].count())

    def test_view_with_a_active_category(self):
        category = mommy.make('Category')
        response = self.get()

        self.assertEqual(200, response.status_code)
        self.assertTemplateUsed(response, 'category/list.html')
        self.assertIsInstance(response.context_data['paginator'], Paginator)
        self.assertIsInstance(response.context_data['page_obj'], Page)
        self.assertFalse(response.context_data['is_paginated'])
        self.assertEqual(1, response.context_data['categories'].count())
        self.assertIn(category, response.context_data['categories'])

    def test_view_pagination(self):
        mommy.make('Category', _quantity=10)
        category = mommy.make('Category')
        url = '%s?page=2' % self.url
        request = self.factory.get(path=url, user=self.mock_user)
        response = self.view(request)
        response.render()

        self.assertIsInstance(response.context_data['paginator'], Paginator)
        self.assertIsInstance(response.context_data['page_obj'], Page)
        self.assertTrue(response.context_data['is_paginated'])
        self.assertEqual(1, response.context_data['categories'].count())
        self.assertIn(category, response.context_data['categories'])

    def test_html_content_with_no_category(self):
        response = self.get()

        self.assertNotContains(response, 'INVALID VARIABLE:')
        self.assertContains(response, 'Category List', count=2)
        self.assertContains(response, 'New Category')
        self.assertContains(response, reverse('category:category_add'))
        self.assertContains(response, 'No categories found.')

    def test_html_content_with_a_category(self):
        category = mommy.make('Category')
        response = self.get()

        self.assertNotContains(response, 'INVALID VARIABLE:')
        self.assertContains(response, 'Category List', count=2)
        self.assertContains(response, 'New Category')
        self.assertNotContains(response, 'No categories found.')
        self.assertContains(response, category.id)
        self.assertContains(response, category.name)
        self.assertContains(response, reverse('category:category_edit', kwargs={'slug': category.slug}))
        self.assertContains(response, reverse('category:category_delete', kwargs={'slug': category.slug}))

    def test_view_redirect_if_anonymous(self):
        request = self.factory.get(path=self.url, user=self.anonymous_user)
        response = self.view(request)

        self.assertEqual(302, response.status_code)
        self.assertEqual('%s?next=%s' % (reverse('login'), self.url), response._headers['location'][1])

    def get(self):
        request = self.factory.get(path=self.url, user=self.mock_user)
        response = self.view(request)
        return response.render()

class CategoryAddViewTest(BaseTestCase):
    from category.views import CategoryCreateView

    url = reverse('category:category_add')
    view_class = CategoryCreateView

    middleware_classes = [
        SessionMiddleware,
        (MessageMiddleware, MiddlewareType.PROCESS_REQUEST),
    ]

    def test_has_form_on_context(self):
        from category.forms import CategoryForm

        response = self.get()

        self.assertEqual(200, response.status_code)
        self.assertTemplateUsed(response, 'category/add.html')
        self.assertIsInstance(response.context_data['form'], CategoryForm)

    def test_show_form_with_errors(self):
        _, response = self.post({})
        response.render()
        form = response.context_data['form']

        self.assertEqual(1, len(form.errors))
        self.assertTrue(form['name'].errors)

    def test_redirect_after_save(self):
        form_data = {'name': 'foo'}
        _, response = self.post(form_data)

        self.assertEqual(302, response.status_code)
        self.assertEqual(('Location', reverse('category:category_list')), response._headers['location'])

    def test_confirm_saved_object(self):
        from category.models import Category

        form_data = {'name': 'Foo'}
        self.post(form_data)
        category = Category.objects.get(pk=1)

        self.assertEqual(1, Category.active.count())
        self.assertEqual('Foo', category.name)
        self.assertEqual('foo', category.slug)

    def test_show_alert_message_after_save(self):
        form_data = {'name': 'Foo'}
        request, response = self.post(form_data)

        self.assert_redirect(response, reverse('category:category_list'))
        message = 'Category %s was created successfully!' % form_data['name']
        self.assert_message_exists(request, messages.SUCCESS, message)

    def test_html_content_with_a_unbound_form(self):
        response = self.get()

        self.assertNotContains(response, 'INVALID VARIABLE:')
        self.assertContains(response, 'Add A Category', count=2)
        self.assertContains(response, 'id="id_name"')
        self.assertContains(response, reverse('category:category_list'))

    def test_view_redirect_if_anonymous(self):
        request = self.factory.get(path=self.url, user=self.anonymous_user)
        response = self.view(request)

        self.assertEqual(302, response.status_code)
        self.assertEqual('%s?next=%s' % (reverse('login'), self.url), response._headers['location'][1])

    def get(self):
        request = self.factory.get(path=self.url, user=self.mock_user)
        response = self.view(request)
        return response.render()

    def post(self, form_data):
        request = self.factory.post(path=self.url, data=form_data, user=self.mock_user)
        return request, self.view(request)

class CategoryEditViewTest(BaseTestCase):
    from category.views import CategoryUpdateView

    view_class = CategoryUpdateView
    middleware_classes = [
        SessionMiddleware,
        (MessageMiddleware, MiddlewareType.PROCESS_REQUEST),
    ]

    def test_has_form_on_context(self):
        from category.forms import CategoryForm

        category = mommy.make('Category')
        response = self.get(category)

        self.assertEqual(200, response.status_code)
        self.assertTemplateUsed(response, 'category/edit.html')
        self.assertIsInstance(response.context_data['form'], CategoryForm)

    def test_should_show_form_with_errors(self):
        category = mommy.make('Category')
        _, response = self.post(category, {})
        form = response.context_data['form']

        self.assertEqual(200, response.status_code)
        self.assertTemplateUsed(response, 'category/edit.html')
        self.assertEqual(1, len(form.errors))
        self.assertTrue(form['name'].errors)

    def test_redirect_after_save(self):
        category = mommy.make('Category')
        form_data = {'name': 'foo'}
        _, response = self.post(category, form_data)

        self.assertEqual(302, response.status_code)
        self.assertEqual(('Location', reverse('category:category_list')), response._headers['location'])

    def test_confirm_saved_object(self):
        from category.models import Category

        old_category = mommy.make('Category', name='Foo')
        form_data = {'name': 'Bar'}
        self.post(old_category, form_data)
        new_category = self.refresh(old_category)

        self.assertEqual(1, Category.objects.count())
        self.assertEqual('Bar', new_category.name)
        self.assertEqual(old_category.slug, new_category.slug)

    def test_show_alert_message_after_save(self):
        old_category = mommy.make('Category', name='Foo')
        form_data = {'name': 'Bar'}
        self.post(old_category, form_data)
        new_category = self.refresh(old_category)
        request, response = self.post(old_category, form_data)

        self.assert_redirect(response, reverse('category:category_list'))
        message = 'Category %s was updated successfully!' % new_category.name
        self.assert_message_exists(request, messages.SUCCESS, message)

    def test_html_content_with_a_bound_form(self):
        category = mommy.make('Category')
        response = self.get(category)

        self.assertNotContains(response, 'INVALID VARIABLE:')
        self.assertContains(response, 'Edit Category', count=2)
        self.assertContains(response, category.name)
        self.assertContains(response, reverse('category:category_delete', kwargs={'slug': category.slug}))

    def test_view_redirect_if_anonymous(self):
        slug = 'foo'
        url = reverse('category:category_edit', kwargs={'slug': slug})
        request = self.factory.get(path=url, user=self.anonymous_user)
        response = self.view(request, slug=slug)

        self.assertEqual(302, response.status_code)
        self.assertEqual('%s?next=%s' % (reverse('login'), url), response._headers['location'][1])

    def get(self, category):
        url = reverse('category:category_edit', kwargs={'slug': category.slug})
        request = self.factory.get(path=url, user=self.mock_user)
        response = self.view(request, slug=category.slug)
        return response.render()

    def post(self, category, form_data):
        url = reverse('category:category_edit', kwargs={'slug': category.slug})
        request = self.factory.post(path=url, data=form_data, user=self.mock_user)
        return request, self.view(request, slug=category.slug)

class CategoryDeleteViewTest(BaseTestCase):
    from category.views import CategoryDeleteView

    view_class = CategoryDeleteView

    def test_view_response(self):
        category = mommy.make('Category')
        response = self.get(category)

        self.assertEqual(200, response.status_code)
        self.assertTemplateUsed(response, 'category/delete.html')
        self.assertEqual(category, response.context_data['category'])

    def test_view_redirect_after_delete(self):
        category = mommy.make('Category',)
        response = self.post(category)

        self.assertEqual(302, response.status_code)
        self.assertEqual(reverse('category:category_list'), response._headers['location'][1])

    def test_confirm_deleted_object(self):
        from category.models import Category

        old_category = mommy.make('Category',)
        self.post(old_category)
        new_category = self.refresh(old_category)

        self.assertEqual(1, Category.objects.count())
        self.assertEqual(0, Category.active.count())
        self.assertTrue(new_category.is_deleted)

    def test_html_content_on_delete_view(self):
        category = mommy.make('Category')
        response = self.get(category)

        self.assertNotContains(response, 'INVALID VARIABLE:')
        self.assertContains(response, 'Delete Category', count=2)
        self.assertContains(response, 'Are you sure you want to delete "%s"?' % category.name)
        self.assertContains(response, reverse('category:category_list'))

    def test_view_redirect_if_anonymous(self):
        slug = 'foo'
        url = reverse('category:category_delete', kwargs={'slug': slug})
        request = self.factory.get(path=url, user=self.anonymous_user)
        response = self.view(request, slug=slug)

        self.assertEqual(302, response.status_code)
        self.assertEqual('%s?next=%s' % (reverse('login'), url), response._headers['location'][1])

    def get(self, category):
        url = reverse('category:category_delete', kwargs={'slug': category.slug})
        request = self.factory.get(path=url, user=self.mock_user)
        response = self.view(request, slug=category.slug)
        return response.render()

    def post(self, category):
        url = reverse('category:category_delete', kwargs={'slug': category.slug})
        request = self.factory.post(path=url, user=self.mock_user)
        return self.view(request, slug=category.slug)