text:
import Base.==

"""

A multidimensional array together with additional axes attached to it.
Each axis is a one dimensional array, possibly a `DictArray`.
Use the function `larr` or a macro version `@larr` to create `LabeledArray`s, rather than call the constructor directly.

A `LabeledArray` consists of one main array, which we call the *base* array, and an axis array for each direction.

##### Constructors
* `LabeledArray(arr, axes)` creates a `LabeledArray` from a *base* array `arr` and a tuple `axes` of one dimensional arrays for axes.
* `LabeledArray(arr; kwargs...)` creates a `LabeledArray` from a *base* array `arr` and a keyword argument of the form `axisN=V` for some integer `N` for the axis direction and a one dimensional array `V`.

"""
immutable LabeledArray{T,N,AXES<:Tuple,TN} <: AbstractArray{T,N}
  data::TN
  axes::AXES

  LabeledArray(data::TN, axes::AXES) = begin
    if length(axes) != ndims(data)
      throw(ArgumentError("LabeledArray: the number of axes $(length(axes)) is not the same as the number of dimensions of data $(ndims(data))."))
    end
    if size(data) != map(length, axes)
      throw(ArgumentError("LabeledArray: the dimensions of data $(size(data)) do not match with the axes lengths $(map(length, axes))."))
    end
    for axis in axes
      if ndims(axis) != 1
        throw(ArgumentError("LabeledArray: axes should be 1 dimensional."))
      end
    end
    new(data, axes)
  end
end

(==)(arr1::LabeledArray, arr2::LabeledArray) = wrap_array(arr1.data)==wrap_array(arr2.data) && all(map(arr1.axes,arr2.axes) do x1,x2;wrap_array(x1)==wrap_array(x2) end)
Base.copy(arr::LabeledArray) = LabeledArray(copy(arr.data), map(copy, arr.axes))

"""

Default axis used when no axis is specified for a `LabeledArray`.
It behaves mostly as an array `[Nullable(1), Nullable(2), ...]`.
However, one notable exception is when using `@select`/`selct`/`extract`/`discard`/`getindex`/etc to choose, set or drop specific elements of a `LabeledArray`.
In this case, the result array of reduced size will again have a `DefaultAxis` of an appropriate size.

"""
immutable DefaultAxis <: AbstractArray{Nullable{Int}, 1}
  counts::Int
end
Base.size(axis::DefaultAxis) = (axis.counts,)
Base.linearindexing(::Type{DefaultAxis}) = Base.LinearFast()
Base.getindex(axis::DefaultAxis, i::Int) = Nullable(i)
Base.getindex(axis::DefaultAxis, i...) = begin
  labeledarray_mapnullable_inner((1:axis.counts)[i...])
end
labeledarray_mapnullable_inner(i::Int) = Nullable(i)
labeledarray_mapnullable_inner(i::AbstractArray) = map(Nullable, i)

Base.start(::DefaultAxis) = 1
Base.next(arr::DefaultAxis, state) = (Nullable(state), state+1)
Base.done(arr::DefaultAxis, s) = s > arr.counts
Base.eltype(::Type{DefaultAxis}) = Nullable{Int}
Base.length(axis::DefaultAxis) = axis.counts
Base.ndims(::DefaultAxis) = 1
(==)(arr1::DefaultAxis, arr2::DefaultAxis) = arr1.counts == arr2.counts

LabeledArray{T,N,AXES<:Tuple}(data::AbstractArray{T,N}, axes::AXES) = begin
  LabeledArray{T,N,AXES,typeof(data)}(data, axes)
end
# don't know why this is necessary.
LabeledArray{K,N,VS,SV,AXES<:Tuple}(data::DictArray{K,N,VS,SV}, axes::AXES) = LabeledArray{LDict{K,SV},N,AXES,typeof(data)}(data, axes)
LabeledArray{T,N}(data::AbstractArray{T,N}; kwargs...) = begin
  axes = Any[DefaultAxis(x) for x in size(data)]
  for (k, v) in kwargs
    kstr = string(k)
    if startswith(kstr, "axis")
      axisindex = parse(Int, kstr[5:endof(kstr)])
      axes[axisindex] = v
    end
  end
  axestuple = (axes...)
  LabeledArray(data, axestuple)
end

# used to calculate the appropriate number of columns/rows when showing an LabeledArray or a DictArray.
arr_width(x::DictArray) = length(x.data)
arr_width(x::AbstractArray) = 1

# some functions to set the height and width of output LabeledArrays to console.
default_showsize = () -> ((height,width) = Base.tty_size();(height-20,width-6))

@doc """

`set_default_showsize!!()`

Set the show height and width limit function to be the default one.
The default version calculates the height and width based on the current console screen size.
This is used to set the print limits when showing a `DictArray` or a `LabeledArray`.

"""
set_default_showsize!!() = (global show_size;show_size = default_showsize)
show_size = default_showsize

@doc """

`setshowsize!!(height::Integer, width::Integer)`

Set the show height and width limits to be the constant `height` and `width`, respectively.
To get to the default behavior of adjusting to the current console screen size, use `set_default_showsize!!()`.

"""
setshowsize!!(height::Integer, width::Integer) = (global show_size;show_size = () -> (height, width))

@doc """

`set_showheight!!(height::Integer)`

Set the show height limit to the constant `height`.
To get to the default behavior of adjusting to the current console screen size, use `set_default_showsize!!()`.

"""
set_showheight!!(height::Integer) = (origwidth=show_size()[2];global show_size;show_size = () -> (height, origwidth))

@doc """

`set_showwidth!!(width::Integer)`

Set the show width limit to the constant `width`.
To get to the default behavior of adjusting to the current console screen size, use `set_default_showsize!!()`.

"""
set_showwidth!!(width::Integer) = (origheight=show_size()[1];global show_size;show_size = () -> (origheight, width))
toshow_alongrow = true

@doc """

`set_showalongrow!!(alongrow::Bool)`

Determine how to show the fields of a `DictArray`.
By default (`alongrow` is `true`), the fields are shown from left to right.
If `alongrow=false`, the fields are shown from top to bottom.

##### Examples

```julia
julia> set_showalongrow!!(true)
true

julia> darr(a=[1 2 3;4 5 6], b=[:x :y :z;:u :v :w])
2 x 3 DictArray

a b |a b |a b
----+----+----
1 x |2 y |3 z
4 u |5 v |6 w

julia> set_showalongrow!!(false)
false

julia> darr(a=[1 2 3;4 5 6], b=[:x :y :z;:u :v :w])
2 x 3 DictArray

a |1 2 3
b |x y z
--+------
a |4 5 6
b |u v w
```

"""
set_showalongrow!!(alongrow::Bool) = (global toshow_alongrow; toshow_alongrow = alongrow)

# some functions to set the height and width of output LabeledArrays to html.
default_dispsize = () -> (80,30)

@doc """

`set_default_dispsize!!()`

Set the display height and width limit function to be the default one.
This is used to set the display limits when displaying a `DictArray` or a `LabeledArray`.

"""
set_default_dispsize!!() = (global show_size;show_size = default_dispsize)
dispsize = default_dispsize

@doc """

`setdispsize!!(height::Integer, width::Integer)`

Set the display height and width limits to be the constant `height` and `width`, respectively.
To get to the default behavior, use `set_default_dispsize!!()`.

"""
setdispsize!!(height::Integer, width::Integer) = (global dispsize;dispsize = () -> (height, width))

@doc """

`set_dispheight!!(height::Integer)`

Set the display height limit to the constant `height`.
To get to the default behavior, use `set_default_dispsize!!()`.

"""
set_dispheight!!(height::Integer) = (origwidth=dispsize()[2];global dispsize;dispsize = () -> (height, origwidth))

@doc """

`set_dispwidth!!(width::Integer)`

Set the display width limit to the constant `width`.
To get to the default behavior, use `set_default_dispsize!!()`.

"""
set_dispwidth!!(width::Integer) = (origheight=dispsize()[1];global dispsize;dispsize = () -> (origheight, width))
todisp_alongrow = true

@doc """

`set_dispalongrow!!(alongrow::Bool)`

Determine how to display the fields of a `DictArray`.
By default (`alongrow` is `true`), the fields are displayed from left to right.
If `alongrow=false`, the fields are displayed from top to bottom.
See `set_showalongrow!!` to see an analogous example when showing a `DictArray`.

"""
set_dispalongrow!!(alongrow::Bool) = (global todisp_alongrow; todisp_alongrow = alongrow)

"""

`show(io::IO, table::LabeledArray [, indent=0; height=..., width=...])`

Show a LabeledArray.

##### Arguments

* `height` and `width`(optional, default set by show_size()): sets the maximum height and width to draw, beyond which the table will be cut.
* `alongrow`(optional, default set by `set_dispalongrow!!`. `tru` by default): if `true`, the fields in the array will be displayed along the row in each cell. Otherwise, they will be stacked on top of each other.

"""
Base.show{N}(io::IO, table::LabeledArray{TypeVar(:T),N}, indent=0; height::Int=show_size()[1], width::Int=show_size()[2], alongrow::Bool=toshow_alongrow) = begin
  print(io, join(size(table), " x "))
  print(io, " LabeledArray")
  print(io, '\n')
  ndimstable = ndims(table)
  for index=1:last(size(table))
    axislabel = table.axes[end][index]
    coords = [fill(:,ndimstable-1);index]
    print(io, '\n')
    show_indent(io, indent)
    print(io, axislabel)
    print(io, ' ')
    print(io, '[')
    for i in 1:length(coords)-1
      print(io, ":,")
    end
    print(io, index)
    print(io, ']')
    print(io, '\n')
    show(io, getindex(table, coords...), indent+4; height=height, width=width, alongrow=alongrow)
  end
end

Base.show(io::IO, table::LabeledArray{TypeVar(:T),0}, indent=0; height::Int=show_size()[1], width::Int=show_size()[2], alongrow::Bool=toshow_alongrow) = begin
  println(io, "0 dimensional LabeledArray")
  show(io, table.data)
end

Base.show(io::IO, table::LabeledArray{TypeVar(:T),1}, indent=0; height::Int=show_size()[1], width::Int=show_size()[2], alongrow::Bool=toshow_alongrow) = begin
  print(io, join(size(table), " x "))
  print(io, " LabeledArray")
  print(io, '\n')
  (result, hlines, vlines) = if alongrow
    create_string_reprmat_alongrow(table; height=height, width=width)
  else
    create_string_reprmat_alongcol(table; height=height, width=width)
  end
  show_string_matrix(io, result, height, width, indent, hlines, vlines)
end

# create a string version of the matrix, properly truncated.
# returns a tuple of (string matrix, locations of horizontal lines, locations of vertical lines).
# location 10 of horizonal line means, e.g., there is a horizontal line to be inserted
# between the 9th and 10th rows.
create_string_reprmat_alongrow(table::LabeledArray{TypeVar(:T),1}; height::Int=show_size()[1], width::Int=show_size()[2]) = begin
  show_height,show_width = (height, width)
  tabledata = table.data
  tableaxes1 = table.axes[1]
  nrows = min(show_height, size(table,1) + 1)
  nkeys = arr_width(tableaxes1)
  ncols = max(nkeys, min(show_width, nkeys + arr_width(tabledata)))
  result = fill("", nrows, ncols)
  if isa(tabledata, DictArray)
    result[1,nkeys+1:ncols] = map(string, tabledata.data.keys[1:ncols-nkeys])
    for i in nkeys+1:ncols
      result[2:nrows,i] = map(cell_to_string, tabledata.data.values[i-nkeys][1:nrows-1])
    end
  else
    result[2:nrows,nkeys+1] = map(cell_to_string, tabledata[1:nrows-1])
  end
  if isa(tableaxes1, DictArray)
    result[1,1:nkeys] = map(string, tableaxes1.data.keys)
    for i in 1:nkeys
      result[2:nrows,i] = map(cell_to_string, tableaxes1.data.values[i][1:nrows-1])
    end
  else
    result[2:nrows,1] = map(cell_to_string, tableaxes1[1:nrows-1])
  end
  (result, [2], [nkeys+1])
end

create_string_reprmat_alongcol(table::LabeledArray{TypeVar(:T),1}; height::Int=show_size()[1], width=show_size()[2]) = begin
  show_height,show_width = (height, width)
  tabledata = table.data
  tableaxes1 = table.axes[1]
  widthtabledata = arr_width(tabledata)
  nrows = min(show_height, 1+widthtabledata*length(table))
  nkeys = arr_width(tableaxes1)
  ncols = max(nkeys, min(show_width, nkeys + 2))
  result = fill("", nrows, ncols)
  if isa(tabledata, DictArray)
    for i in 2:nrows
      result[i,nkeys+1] = string(tabledata.data.keys[1+(i-2) % widthtabledata]) #string(data.keys[i loop_key_index])
      result[i,nkeys+2] = cell_to_string(tabledata.data.values[1+(i-2) % widthtabledata][1+div(i-2,widthtabledata)])
    end
  else
    result[2:nrows,nkeys+1] = map(cell_to_string, tabledata[1:nrows-1])
  end
  # display axis 1.
  if isa(tableaxes1, DictArray)
    result[1,1:nkeys] = map(string, tableaxes1.data.keys)
    for i in 2:nrows
      for j in 1:nkeys
        if (i-2) % widthtabledata == 0
          result[i,j] = cell_to_string(tableaxes1.data.values[j][1+div(i-2,widthtabledata)])
        end
      end
    end
  else
    for i in 2:nrows
      result[i,1] = cell_to_string(tableaxes1[1+div(i-2,widthtabledata)])
    end
  end
  (result, collect(2+widthtabledata*(0:1+fld(nrows,widthtabledata))), [nkeys+1,nkeys+2])
end

Base.show(io::IO, table::LabeledArray{TypeVar(:T),2}, indent; height::Int=show_size()[1], width::Int=show_size()[2], alongrow=toshow_alongrow) = begin
  print(io, join(size(table), " x "))
  print(io, " LabeledArray")
  print(io, '\n')
  (result, hlines, vlines) = if alongrow
    create_string_reprmat_alongrow(table; height=height, width=width)
  else
    create_string_reprmat_alongcol(table; height=height, width=width)
  end
  show_string_matrix(io, result, height, width, indent, hlines, vlines)
end

# create a string version of the matrix, properly truncated.
# returns a tuple of (string matrix, locations of horizontal lines, locations of vertical lines).
# location 10 of horizonal line means, e.g., there is a horizontal line to be inserted
# between the 9th and 10th rows.
create_string_reprmat_alongrow(table::LabeledArray{TypeVar(:T),2}; height::Int=show_size()[1], width::Int=show_size()[2]) = begin
  show_height,show_width = (height, width)
  tabledata = table.data
  (tableheight,tablewidth) = size(tabledata)
  widthtabledata = arr_width(tabledata)
  tableaxes1 = table.axes[1]
  tableaxes2 = table.axes[2]
  widthtableaxes2 = arr_width(tableaxes2)
  nrows = min(show_height, tableheight + widthtableaxes2 + 1)
  nkeys = arr_width(tableaxes1)
  ncols = max(nkeys, min(show_width, nkeys + length(tableaxes2)*widthtabledata))
  result = fill("", nrows, ncols)
  # fill in axis2 above data columns.
  if isa(tableaxes2, DictArray)
    result[1:widthtableaxes2,nkeys] = map(string, tableaxes2.data.keys)
    for i in 1:min(show_height, widthtableaxes2)
      for j in 1:length(tableaxes2)
        ind = 1+nkeys+widthtabledata*(j-1)
        if ind <= ncols
          result[i,ind] = cell_to_string(tableaxes2.data.values[i][j])
        else
          break
        end
      end
    end
  else
    for i in 1:length(tableaxes2)
      ind = 1+nkeys+widthtabledata*(i-1)
      if ind <= ncols
        result[1,ind] = cell_to_string(tableaxes2[i])
      end
    end
  end
  # fill in the key columns.
  if isa(tabledata, DictArray)
    if widthtableaxes2+1 <= nrows
      for i in 1:length(tableaxes2)
        for j in 1:widthtabledata
          ind = nkeys+widthtabledata*(i-1)+j
          if ind>ncols break end
          result[widthtableaxes2+1,ind] = string(tabledata.data.keys[j])
        end
      end
      for i in widthtableaxes2+2:nrows
        for j in 1:length(tableaxes2)
          for k in 1:widthtabledata
            ind = nkeys+widthtabledata*(j-1)+k
            if ind>ncols break end
            result[i,ind] = cell_to_string(tabledata.data.values[k][i-widthtableaxes2-1,j])
          end
        end
      end
    end
  else
    result[widthtableaxes2+2:nrows,nkeys+1:ncols] = map(cell_to_string, tabledata[1:nrows-1-widthtableaxes2,1:ncols-nkeys])
  end
  if isa(tableaxes1, DictArray)
    result[widthtableaxes2+1,1:nkeys] = map(string, tableaxes1.data.keys)
    for i in 1:nkeys
      result[widthtableaxes2+2:nrows,i] = map(cell_to_string, tableaxes1.data.values[i][1:nrows-widthtableaxes2-1])
    end
  else
    result[widthtableaxes2+2:nrows,1] = map(cell_to_string, tableaxes1[1:nrows-1-widthtableaxes2])
  end
  (result, [widthtableaxes2+1,widthtableaxes2+2], map(x->nkeys+1+widthtabledata*(x-1), 1:ncols))
end

create_string_reprmat_alongcol(table::LabeledArray{TypeVar(:T),2}; height::Int=show_size()[1], width::Int=show_size()[2]) = begin
  show_height,show_width = (height, width)
  tabledata = table.data
  (tableheight,tablewidth) = size(tabledata)
  widthtabledata = arr_width(tabledata)
  tableaxes1 = table.axes[1]
  tableaxes2 = table.axes[2]
  widthtableaxes2 = arr_width(tableaxes2)
  nrows = min(show_height, widthtabledata*tableheight + widthtableaxes2)
  nkeys = arr_width(tableaxes1)
  ncols = max(nkeys, min(show_width, nkeys + length(tableaxes2)+1))
  result = fill("", nrows, ncols)
  # fill in axis2 above data columns.
  if isa(tableaxes2, DictArray)
    result[1:widthtableaxes2,nkeys+1] = map(string, tableaxes2.data.keys)
    for i in 1:min(show_height, widthtableaxes2)
      for j in 1:length(tableaxes2)
        ind = 1 + nkeys + j
        if ind <= ncols
          result[i,ind] = cell_to_string(tableaxes2.data.values[i][j])
        else
          break
        end
      end
    end
  else
    for i in 1:length(tableaxes2)
      ind = 1 + nkeys + i
      if ind <= ncols
        result[1,ind] = cell_to_string(tableaxes2[i])
      end
    end
  end
  # fill in the key columns.
  if isa(tabledata, DictArray)
    for j in widthtableaxes2+1:nrows
      result[j,nkeys+1] = string(tabledata.data.keys[1+(j-widthtableaxes2-1) % widthtabledata])
    end
    for i in widthtableaxes2+1:nrows
      for j in 1:length(tableaxes2)
        ind = nkeys + 1 + j
        if ind>ncols break end
        result[i,ind] = cell_to_string(tabledata.data.values[1+(i-widthtableaxes2-1) % widthtabledata][div(i-widthtableaxes2-1, widthtabledata)+1,j])
      end
    end
  else
    result[widthtableaxes2+1:nrows,nkeys+2:ncols] = map(cell_to_string, tabledata[1:nrows-widthtableaxes2,1:ncols-nkeys-1])
  end
  # fill in the axis 1 field names and values.
  if isa(tableaxes1, DictArray)
    result[widthtableaxes2,1:nkeys] = map(string, tableaxes1.data.keys)
    for i in 1:nkeys
      for j in widthtableaxes2+1:nrows
        if (j-widthtableaxes2-1) % widthtabledata == 0
          result[j,i] = cell_to_string(tableaxes1.data.values[i][1+div(j-1-widthtableaxes2, widthtabledata)])
        end
      end
    end
  else
    for j in widthtableaxes2+1:nrows
      if (j-widthtableaxes2-1) % widthtabledata == 0
        result[j,1] = cell_to_string(tableaxes1[1+div(j-1-widthtableaxes2, widthtabledata)])
      end
    end
  end
  (result, collect(widthtableaxes2+1+widthtabledata*(0:1+fld(nrows-1,widthtabledata))), [nkeys+1,nkeys+2])
end

show_indent(io::IO, indent) = print(io, repeat(" ", indent))

show_string_matrix(io::IO, m::Matrix, show_height, show_width, indent, hline_pos=[], vline_pos=[]) = begin
  # calculate maximum width for the displayed cells for each column.
  msize = size(m)
  max_widths = zeros(Int, msize[2])
  for j in 1:msize[1]
    for i in 1:msize[2]
      max_widths[i] = max(max_widths[i], length(m[j,i]))
    end
  end
  # calculate total width in character.
  max_i = 0
  nchar_sofar = indent
  istrunc = false
  for i in 1:length(max_widths)
    if nchar_sofar <= show_width
      nchar_sofar += max_widths[i] + (i in vline_pos ? 2 : 1)
      max_i +=1
    else
      istrunc = true
      break
    end
  end
  j_count = 0
  print(io, '\n')
  for j in 1:msize[1]
    if j in hline_pos
      show_indent(io, indent)
      running_nchars = indent
      for i in 1:max_i
        if i in vline_pos
          print(io, '+')
          running_nchars += 1
        end
        linelength = max(0, min(show_width-running_nchars, max_widths[i]+1))
        print(io, repeat("-", linelength))
        running_nchars += linelength
      end
      print(io, '\n')
      j_count += 1
    end
    show_indent(io, indent)
    running_nchars = indent
    for i in 1:max_i
      if i in vline_pos
        print(io, '|')
        running_nchars += 1
      end
      if max_widths[i] + running_nchars > show_width
        # it could be a unicode character.
        if running_nchars >= show_width-2
          print(io, "..")
          running_nchars += 2
        else
          for c in m[j,i]
            if running_nchars >= show_width-2
              print(io, "..")
              running_nchars += 2
              break
            end
            print(io, c)
            running_nchars += 1
          end
        end
        print(io, repeat(" ", max(0, show_width - running_nchars)))
        running_nchars += max(0, show_width - running_nchars)
      else
        print(io, rpad(m[j,i], max_widths[i]))
        running_nchars += max_widths[i]
      end
      print(io, ' ')
      running_nchars += 1
    end
    if istrunc print(io, "...") end
    print(io, '\n')
    j_count += 1
    if j_count > show_height
      show_indent(io, indent)
      for i in 1:max_i
        if i in vline_pos
          print(io, '|')
        end
        print(io, rpad(":", max_widths[i]))
        print(io, ' ')
      end
      print(io, '\n')
      break
    end
  end
end

Base.eachindex(arr::LabeledArray) = eachindex(arr.data)
Base.start(arr::LabeledArray) = begin
  iter = eachindex(arr.data)
  i = 1
  axes = map(arr.axes) do axis
    a = BroadcastAxis(axis, arr.data, i)
    i += 1
    a
  end
  (axes, iter, start(iter))
end
Base.next(arr::LabeledArray, state) = begin
  nextelem, nextstate = next(state[2], state[3])
  axesvalues = map(state[1]) do axis
    axis[nextelem]
  end
  nextvalue = arr[nextelem]
  (nextvalue, (state[1], state[2], nextstate))
end
Base.done(arr::LabeledArray, state) = done(state[2], state[3])
Base.linearindexing{T,N,AXES<:Tuple,TN}(::Type{LabeledArray{T,N,AXES,TN}}) = Base.LinearSlow()
Base.eltype{T,N,AXES<:Tuple,TN}(::Type{LabeledArray{T,N,AXES,TN}}) = T
Base.length(table::LabeledArray) = length(table.data)
Base.getindex(arr::LabeledArray, arg::Symbol) = selectfield(arr, arg)
Base.getindex(arr::LabeledArray, arg::Symbol, args::Symbol...) = [selectfield(arr, a) for a in [arg;args...]]
Base.getindex{N}(arr::LabeledArray, args::Tuple{N,Symbol}) = map(a->selectfield(arr, a), args)
Base.getindex(arr::LabeledArray, args::AbstractVector{Symbol}) = selectfields(arr, args...)
Base.getindex(arr::LabeledArray, indices::CartesianIndex) = getindex(arr, indices.I...)
Base.getindex(table::LabeledArray, indices...) = begin
  if is_scalar_indexing(indices)
    getindex_labeledarray_scalar_indexing(table, indices)
  else
    getindex_labeledarray_nonscalar_indexing(table, indices)
  end
end

getindex_labeledarray_scalar_indexing(table::LabeledArray, indices) = begin
  int_indices = Array(Int, ndims(table))
  loc_ind = 1
  # this is a hackish way to deal a CartesianIndex, but I don't know a better way yet...
  for index in indices
    if isa(index, Real)
      int_indices[loc_ind] = index
      loc_ind += 1
    elseif isa(index, CartesianIndex)
      for j = 1:length(index)
        int_indices[loc_ind+j-1] = index[j]
      end
      loc_ind += length(index)
    else
      error("this cannot happen. the index is ", index, " and we don't know how to handle it.")
    end
  end
  getindex(table, int_indices...)
end

getindex_labeledarray_nonscalar_indexing(table::LabeledArray, indices) = begin
  dataelem = getindex(table.data, indices...)
  zippedindices = zip(table.axes, indices)
  filtered_zippedindices = [filter(elem->!isa(elem[2], Real), zip(table.axes, indices))...]
  axeselem = [axis_index(axis,index) for (axis, index) in zippedindices]
  ndimstable = ndims(table)
  v04ndims = ndimstable
  for i in ndimstable:-1:1
    if !isa(axeselem[i], Real)
      v04ndims = i
      break
    end
  end
  if ndims(dataelem) == v04ndims
    # this is the expected behavior for v0.4:
    LabeledArray(dataelem, (axeselem[1:v04ndims]...))
  else
    # this is the expected behavior for v0.5, if one direction before the last non integer index is an integer index.
    LabeledArray(dataelem, ([axis_index(axis, index) for (axis, index) in filtered_zippedindices]...))
  end
end

axis_index(axis, index) = axis[index]
axis_sub(axis, index) = sub(axis, index)
axis_slice(axis, index) = slice(axis, index)

axis_index(axis::DefaultAxis, i::Int) = i
axis_index(axis::DefaultAxis, ::Colon) = axis
axis_index(axis::DefaultAxis, index::AbstractArray{Bool}) = DefaultAxis(length(find(index)))
axis_index(axis::DefaultAxis, index) = DefaultAxis(length(index))
axis_sub(axis::DefaultAxis, index) = axis_index(axis, index)
axis_slice(axis::DefaultAxis, index) = axis_index(axis, index)

Base.getindex(table::LabeledArray, indices::Int) =
  getindex_inner(table, ind2sub(table, indices))
Base.getindex(table::LabeledArray, indices::Int...) =
  getindex_inner(table, indices)
getindex_inner{N}(table::LabeledArray, indices::NTuple{N,Int}) = getindex(table.data, indices...)

# returns nested pairs axis1 => (axis2 => ... => (axisN => value)).
getindexpair(table::LabeledArray, indices::Int) =
  getindexpair_inner(table, ind2sub(table, indices))
getindexpair(table::LabeledArray, indices::Int...) =
  getindexpair_inner(table, indices)
getindexpair_inner{N}(table::LabeledArray{TypeVar(:T),N}, indices::NTuple{N,Int}) = begin
  tableaxes = table.axes
  foldr((x,acc)->Pair(x,acc),
        getindex(table.data, indices...),
        [x[y] for (x,y) in zip(tableaxes,indices)])
end

Base.size{N}(table::LabeledArray{TypeVar(:T),N}) = size(table.data)::NTuple{N,Int}
Base.transpose(table::LabeledArray{TypeVar(:T),2}) = LabeledArray(transpose(table.data), (table.axes[2],table.axes[1]))
Base.permutedims(table::LabeledArray, perms) = begin
  lenaxes = length(table.axes)
  if length(perms) != lenaxes
    throw(ArgumentError("LabeledArray permutedims: the number of axes is not the same as the length of the permutations."))
  end
  newdata = permutedims(table.data, perms)
  newaxes = cell(lenaxes)
  for i=1:lenaxes
    newaxes[i] = table.axes[perms[i]]
  end
  LabeledArray(newdata,(newaxes...))
end
Base.setindex!(table::LabeledArray, v, args...) = setindex!(table.data, v, args...)
Base.Multimedia.writemime(io::IO, ::MIME"text/plain", table::LabeledArray) = show(io, table)
Base.sub(table::LabeledArray, indices::Union{Colon, Int64, AbstractArray{TypeVar(:T),1}}...) = begin
  dataelem = sub(table.data, indices...)
  axeselem = [axis_sub(axis, isa(index,Int) ? (index:index) : index) for (axis, index) in zip(table.axes,indices)]
  newN = ndims(dataelem)
  LabeledArray(dataelem, (axeselem[1:newN]...))
end
Base.slice(table::LabeledArray, indices::Union{Colon, Int64, AbstractArray{TypeVar(:T),1}}...) = begin
  dataelem = slice(table.data, indices...)
  axeselem = [axis_slice(axis, index) for (axis, index) in [filter(elem->!isa(elem[2], Real), zip(table.axes, indices))...]]
  newN = ndims(dataelem)
  LabeledArray(dataelem, (axeselem[1:newN]...))
end

# select the field with name from table. If the name belongs to an axis,
# the axis array is broadcast to the full matrix shape.
selectfield(table::LabeledArray, name) = begin
  if isa(table.data, DictArray) && name in table.data.data.keys
    return selectfield(table.data, name)
  end
  counter = 1
  for axis in table.axes
    if isa(axis, DictArray) && name in axis.data.keys
      return AbstractArrayWrapper(BroadcastAxis(selectfield(axis, name), table.data, counter))
    end
    counter += 1
  end
  throw(ArgumentError(string("cannot find field ", name, " in the data or axes.")))
end
selectfields(arr::LabeledArray, fields...) = DictArray(LDict(map(n->n=>selectfield(arr,n), fields)...))

# broadcast an axis so that they can be treated as an N dimensional array for LabeledArray{T,N}.
immutable BroadcastAxis{T,N,V,W} <: AbstractArray{T,N}
  axis::V #AbstractArray{T,1}
  base::W #AbstractArray{TypeVar(:U),N}
  index::Int
end
(==)(arr1::BroadcastAxis, arr2::BroadcastAxis) =
  arr1.index==arr2.index && size(arr1.base)==size(arr2.base) && arr1.axis==arr2.axis
BroadcastAxis{T,N}(axis::AbstractArray{T,1}, base::AbstractArray{TypeVar(:U),N}, index::Int) = BroadcastAxis{T,N,typeof(axis),typeof(base)}(axis, base, index)
BroadcastAxis(axis::DictArray, base::AbstractArray, index::Int) = create_dictarray_nocheck(mapvalues(v->BroadcastAxis(v, base, index), peel(axis)))
Base.size(axis::BroadcastAxis) = size(axis.base)
Base.linearindexing(::Type{BroadcastAxis}) = Base.LinearSlow()
Base.getindex(axis::BroadcastAxis, arg::CartesianIndex) = getindex(axis.axis, arg[axis.index])
Base.getindex(axis::BroadcastAxis, args...) = begin
  newaxis = getindex(axis.axis, args[axis.index])
  if isa(newaxis, AbstractArray)
    newbase = sub(axis.base, args...)
    BroadcastAxis(newaxis, newbase, axis.index)
  else
    # this is definitely not one point. it is one coord along the axis index, but ranges along some other directions.
    # I cannot think of an alternative. Let's do a copy.
    fill(newaxis, size(sub(axis.base, args...)))
  end
end
Base.getindex(axis::BroadcastAxis, index::Int...) = getindex(axis.axis, index[axis.index])
Base.getindex(axis::BroadcastAxis, index::Int) = begin
  getindex(axis.axis, ind2sub(axis.base, index)[axis.index])
end

"""

returns all field names for LabeledArray or DictArray. Returns an empty array for other types of arrays.

"""
allfieldnames(table::LabeledArray) = simplify_array(unique(vcat(vcat(map(allfieldnames, table.axes)...),allfieldnames(table.data))))
allfieldnames(table::AbstractArray) = Array(Any, 0)
cell_to_string(cell::Nullable) = cell.isnull ? "" : string(cell.value)
cell_to_string{K,T}(cell::LDict{K,Nullable{T}}) = string(cell)
cell_to_string(cell::AbstractArray) = string(map(x->string(cell_to_string(x)," "), cell)...)

isna(arr::LabeledArray) = isna(peel(arr))
isna(arr::LabeledArray, indices...) = isna(peel(arr), indices...)

"""

`cat(catdim::Integer, arrs::LabeledArray...)`

Concatenate `LabeledArray`s `arrs` along the `catdim` direction.
The base of each element of `arrs` are concatenated and become the new base of the return `LabeledArray`.
The axes of each of `arrs` not along the `catdim` direction should be identical. Otherwise, there will be an error.
The axis along the `catdim` direction will be the concatenation of the axis of each of `arrs` along that direction.

```julia
julia> t1 = larr(a=[1 2 3;4 5 6], axis1=[:x,:y], axis2=["A","B","C"])
t2 x 3 LabeledArray

  |  |A B C
--+--+------
x |a |1 2 3
--+--+------
y |a |4 5 6

julia> t2 = larr(a=[11 12 13;14 15 16], axis1=[:x,:y], axis2=["D","E","F"])
2 x 3 LabeledArray

  |  |D  E  F
--+--+---------
x |a |11 12 13
--+--+---------
y |a |14 15 16

julia> cat(2, t1, t2)
2 x 6 LabeledArray

  |  |A B C D  E  F
--+--+---------------
x |a |1 2 3 11 12 13
--+--+---------------
y |a |4 5 6 14 15 16
```

"""
Base.cat(catdim::Integer, arr1::LabeledArray, arrs::LabeledArray...) = begin
  if isempty(arrs)
    return arr1
  end
  newdata = cat(catdim, arr1.data, map(x->x.data, arrs)...)
  arrlist = Any[arr1,arrs...]
  newaxes = cell(max(map(ndims, arrlist)...))
  for arr in arrlist
    for i in 1:length(arr.axes)
      if i != catdim && isdefined(newaxes, i) && arr.axes[i] != newaxes[i]
        throw(ArgumentError("array dimensions in the arguments for cat do not match."))
      else
        newaxes[i] = arr.axes[i]
      end
    end
  end
  newaxes[catdim] = if all(arr->ndims(arr)<catdim || isa(arr.axes[catdim], DefaultAxis), arrlist) #isa(newaxes[catdim], DefaultAxis)
    DefaultAxis(sum(map(arr->ndims(arr)<catdim ? 1 : length(arr.axes[catdim]), arrlist)))
  else
    maxsizearr = arrlist[indmax(map(ndims, arrlist))]
    null_oneelem_array = create_naelem_array(maxsizearr.axes[catdim])
    cat(1, map(arr->ndims(arr)<catdim ? null_oneelem_array : arr.axes[catdim], arrlist)...)
  end
  LabeledArray(newdata, (newaxes...))
end

create_naelem_array(arr::DictArray) = darr(mapvalues(arr.data) do v
  eltype(v)[Nullable{eltype(eltype(v))}()]
end...)
create_naelem_array(arr::AbstractArray) = eltype(arr)[Nullable{eltype(eltype(arr))}()]

Base.vcat(arr1::LabeledArray, arrs::LabeledArray...) = cat(1, arr1, arrs...)
Base.hcat(arr1::LabeledArray, arrs::LabeledArray...) = cat(2, arr1, arrs...)

Base.repeat(arr::LabeledArray; inner::Array{Int}=ones(Int,ndims(arr)), outer::Array{Int}=ones(Int,ndims(arr))) = begin
  newdata = repeat(arr.data, inner=inner, outer=outer)
  newaxes = ntuple(ndims(arr)) do d
    repeat(arr.axes[d], inner=collect(inner[d]), outer=collect(outer[d]))
  end
  additional_axes = map(n->DefaultAxis(n), size(newdata)[length(newaxes)+1:end])
  LabeledArray(newdata, (newaxes..., additional_axes...))
end

Base.Multimedia.writemime{N}(io::IO,
                             ::MIME"text/html",
                             table::LabeledArray{TypeVar(:T),N};
                             height::Int=dispsize()[1],
                             width::Int=dispsize()[2],
                             alongrow::Bool=todisp_alongrow) = begin
  ndimstable = ndims(table)
  print(io, join(size(table), " x "))
  print(io, " LabeledArray")
  print(io, '\n')
  print(io, "<ul>")
  for index=1:last(size(table))
    axislabel = table.axes[end][index]
    coords = [fill(:,ndimstable-1);index]
    print(io, "<li>")
    print(io, axislabel)
    print(io, ' ')
    print(io, '[')
    for i in 1:length(coords)-1
      print(io, ":,")
    end
    print(io, index)
    print(io, ']')
    print(io, '\n')
    Base.Multimedia.writemime(io, MIME("text/html"), getindex(table, coords...); height=height, width=width, alongrow=alongrow)
    print(io, "</li>")
  end
  print(io, "</ul>")
end

Base.Multimedia.writemime(io::IO, ::MIME"text/html", table::LabeledArray{TypeVar(:T),0}; height::Int=dispsize()[1], width::Int=dispsize()[2], alongrow::Bool=todisp_alongrow) = begin
  print(io, "0 dimensional LabeledArray")
end

Base.Multimedia.writemime(io::IO, ::MIME"text/html", table::Union{LabeledArray{TypeVar(:T),1},LabeledArray{TypeVar(:T),2}}; height::Int=dispsize()[1], width::Int=dispsize()[2], alongrow::Bool=todisp_alongrow) = begin
  print(io, join(size(table), " x "))
  print(io, " LabeledArray")
  print(io, '\n')
  (result, hlines, vlines) = if alongrow
    create_string_reprmat_alongrow(table; height=height, width=width)
  else
    create_string_reprmat_alongcol(table; height=height, width=width)
  end
  print_string_reprmat_to_html_table(io, result, height, width, hlines, vlines)
end

# an internal function to convert a string represented matrix into an html table string printed into an output io).
print_string_reprmat_to_html_table{T<:AbstractString}(io::IO, strrep::AbstractArray{T,2}, height, width, hlines=[], vlines=[]) = begin
  buffer = 1
  print(io, """<table border="0" style="border:none; width:100%; border-collapse:collapse">""")
  for row in 1:size(strrep,1)
    if row > height-buffer
      print(io, """<tr style="border:0">""")
      for col in 1:size(strrep,2)
        if col > width-buffer
          break
        end
        print(io, """<td style="border:1px solid #000; border-width:0 0 0 0">:</td>""")
      end
      print(io, "</tr>")
      break
    end
    print(io, """<tr style="border:0">""")
    for col in 1:size(strrep,2)
      if col > width-buffer
        print(io, """<td style="border:1px solid #000; border-width:0 0 0 0"></td>""")
        break
      end
      ishline = row in hlines
      isvline = col in vlines
      if ishline && isvline
        print(io, """<td style="border:1px solid #ccc;border-width:1px 0px 0px 1px">""")
      end
      if ishline && !isvline
        print(io, """<td style="border:1px solid #ccc;border-width:1px 0px 0px 0px">""")
      end
      if !ishline && isvline
        print(io, """<td style="border:1px solid #ccc;border-width:0px 0px 0px 1px">""")
      end
      if !ishline && !isvline
        print(io, """<td style="border:1px solid #ccc;border-width:0px 0px 0px 0px">""")
      end
      print(io, strrep[row, col])
      print(io, "</td>")
    end
    print(io, "</tr>")
   end
  print(io, """</table>""")
end

Base.convert(::Type{DictArray}, larr::LabeledArray) = selectfields(larr, allfieldnames(larr)...)
Base.convert(::Type{LabeledArray}, larr::LabeledArray) = larr

Base.map(f::Function, arr::LabeledArray) = mapslices(f, arr, [])
Base.reducedim(f::Function, arr::LabeledArray, dims, initial) = begin
  mapslices(arr, dims) do slice
    reduce(f, initial, slice)
  end
end
Base.mapslices(f::Function, arr::LabeledArray, dims::AbstractVector) = begin
  if length(dims) != length(unique(dims))
    throw(ArgumentError("the dims argument should be an array of distinct elements."))
  end
  dimtypes = ntuple(ndims(arr)) do d
    if d in dims
      Colon()
    else
      0
    end
  end
  result = mapslices_inner(f, arr, dimtypes)
  newdata = if ndims(result) == 0
    isa(result, DictArray) ? mapvalues(x->x[1], result) : result[1]
  else
    result
  end
  newaxes = arr.axes[filter(i->!(i in dims),1:ndims(arr))]
  if length(dims) == ndims(arr)
    newdata
  else
    LabeledArray(newdata, newaxes)
  end
end

@generated mapslices_inner{T,N,AXES,TN,D}(f::Function, arr::LabeledArray{T,N,AXES,TN}, dims::D) = begin
  dimtypes = dims.types
  slice_ndims = foldl((acc,x)->acc + (x==Int), 0, dimtypes)
  slice_indices = Int[map(it->it[1], filter(it->it[2]==Int, enumerate(dimtypes)))...]
  slice_exp = if slice_ndims == N
    :(arr.data[coords...])
  else
    :(slice(arr, coords...))
  end
  quote
    sizearr = size(arr)
    coords = Array(Any, $N)
    # assume that the types are all the same.
    fill!(coords, Colon())
    coords[$slice_indices] = 1
    testslice = $slice_exp
    testres = f(testslice)
    reseltype = typeof(testres)
    result = Array(reseltype, sizearr[$slice_indices]...)

    if reseltype <: LDict
      ldict_keys_sofar = testres.keys
      same_ldict::Bool = true
      @nloops $slice_ndims i j->1:sizearr[$slice_indices[j]] begin
        fill!(coords, Colon())
        @nexprs $slice_ndims j->(coords[$slice_indices[j]] = i_j)
        oneslice = $slice_exp
        oneres = f(oneslice)
        if same_ldict
          same_ldict &= (ldict_keys_sofar == oneres.keys)
        end
        @nref($slice_ndims, result, i) = oneres
      end
      if same_ldict
        valuetypes = [typeof(v) for v in testres.values]
        valuevects = map(valuetypes) do vtype
          similar(result, vtype)
        end
        valuevectslen = length(valuevects)
        @nloops $slice_ndims i result begin
          for j in 1:valuevectslen
            valuevectsj = valuevects[j]
            @nref($slice_ndims,valuevectsj,i) = @nref($slice_ndims,result,i).values[j]
          end
        end
        DictArray(testres.keys, map(wrap_array, valuevects))
      else
        result
      end
    else
      @nloops $slice_ndims i j->1:sizearr[$slice_indices[j]] begin
        fill!(coords, Colon())
        @nexprs $slice_ndims j->(coords[$slice_indices[j]] = i_j)
        oneslice = $slice_exp #slice(arr, coords...)
        oneres = f(oneslice)
        @nref($slice_ndims, result, i) = oneres
      end
      wrap_array(nalift(result))
    end
  end
end

recursive_pair_types{K1,K2,V}(::Type{Pair{K1,Pair{K2,V}}}) = DataType[K1, recursive_pair_types(Pair{K2,V})...]
recursive_pair_types{K,V}(::Type{Pair{K,V}}) = DataType[K, V]

"""

`create_dict(::LabeledArray)`

Create a nested `Dict` from a `LabeledArray`.

##### Examples

```julia
julia> t = larr(a=[1 2;3 4], axis1=[:x,:y], axis2=["A","B"])
2 x 2 LabeledArray

  |  |A B
--+--+----
x |a |1 2
--+--+----
y |a |3 4

julia> create_dict(t)
Dict{Nullable{Symbol},Dict{Nullable{ASCIIString},MultidimensionalTables.LDict{Symbol,Nullable{Int64}}}} with 2 entries:
  Nullable(:y) => Dict(Nullable("B")=>MultidimensionalTables.LDict(:a=>Nullable(4)),Nullable("A")=>MultidimensionalTables.LDict(:a=>Nullable(3)))
  Nullable(:x) => Dict(Nullable("B")=>MultidimensionalTables.LDict(:a=>Nullable(2)),Nullable("A")=>MultidimensionalTables.LDict(:a=>Nullable(1)))
```

"""
function create_dict end

create_dict{T,N,AXES<:Tuple,TN}(arr::LabeledArray{T,N,AXES,TN}) = begin
  kvtype = foldr((x,acc)->Pair{x,acc}, T, map(eltype, arr.axes))
  typevec = recursive_pair_types(kvtype)
  result = foldr((x,acc)->Dict{x,acc}, typevec)()
  for i in eachindex(arr)
    if !isna(arr, i)
      insert_dict!(typevec, result, getindexpair(arr, i))
    end
  end
  result
end

insert_dict!{K,KK,DV,PV}(typevec, d::Dict{K,Dict{KK,DV}}, elem::Pair{K,PV}) = begin
  k = elem.first
  v = elem.second
  if !haskey(d, k)
    d[k] = Dict{KK,DV}()
  end
  insert_dict!(typevec[2:end], d[k], v)
end
insert_dict!{K,V}(typevec, d::Dict{K,V}, elem::Pair{K,V}) = begin
  k = elem.first
  v = elem.second
  d[k] = v
end

# to avoid ambiguity with conventional use of reverse, specifically prohobit the integer argument.
Base.reverse(arr::LabeledArray, dummy::Int) = error("not yet implemented.")
Base.reverse(arr::LabeledArray) = Base.reverse(arr, [1])
# any iterable dims can be an argument.
Base.reverse(arr::LabeledArray, dims) = begin
  coords = ntuple(ndims(arr)) do d
    if d in dims
      size(arr, d):-1:1
    else
      Colon()
    end
  end
  getindex(arr, coords...)
end
Base.flipdim(arr::LabeledArray, dims::Int...) = reverse(arr, dims)

Base.reshape(arr::LabeledArray, dims::Tuple{Vararg{Int}}) = reshape(arr, dims...)

"""

`reshape(arr::LabeledArray, dims...)`

Reshape `arr` into different sizes, if there is no ambiguity.
This means you can collapse several contiguous directions into one direction,
in which case all axes belonging to collapsing direction will be concatenated.
For other case, sometimes it is possible to disambiguate the axis position.
But in general, the result is either an error or an undetermined result
as long as the axis positions are concerned.

##### Examples

```julia
julia> t = larr(a=[1 2 3;4 5 6], axis1=[:x,:y], axis2=["A","B","C"])
2 x 3 LabeledArray

  |A |B |C
--+--+--+--
  |a |a |a
--+--+--+--
x |1 |2 |3
y |4 |5 |6

1 x 6 LabeledArray

x1 |x |y |x |y |x |y
x2 |A |A |B |B |C |C
---+--+--+--+--+--+--
   |a |a |a |a |a |a
---+--+--+--+--+--+--
1  |1 |4 |2 |5 |3 |6

julia> reshape(t, 6, 1)
6 x 1 LabeledArray

      |1
------+--
x1 x2 |a
------+--
x  A  |1
y  A  |4
x  B  |2
y  B  |5
x  C  |3
y  C  |6

julia> reshape(t, 6)
6 LabeledArray

x1 x2 |a
------+--
x  A  |1
y  A  |4
x  B  |2
y  B  |5
x  C  |3
y  C  |6

julia> reshape(t, 3,2)
ERROR: ArgumentError: dims (3,2) are inconsistent.
```

"""
Base.reshape(arr::LabeledArray, dims::Int...) = begin
  newdata = reshape(arr.data, dims...)
  arraxes = arr.axes
  srcdims = [1;cumprod(collect(size(arr)))]
  tgtdims = [1;cumprod(collect(dims))]
  newaxes = Any[DefaultAxis(d) for d in dims]

  tracker = []
  for d in 1:length(arr.axes)
    if !isa(arraxes[d], DefaultAxis)
      startdims = srcdims[d]
      enddims = srcdims[d+1]
      # find where startdims, enddims lie in the tgtdims.
      for p in 1:length(dims)
        tgtdim = tgtdims[p]
        ntgtdim = tgtdims[p+1]
        if tgtdim<=startdims && ntgtdim>=enddims
          inner_dims = divrem(startdims, tgtdim)
          outer_dims = divrem(ntgtdim, enddims)
          if inner_dims[2] != 0 || outer_dims[2] != 0
            throw(ArgumentError("dims $(dims) are inconsistent."))
          end
          axistoadd = repeat(arraxes[d], inner=collect(inner_dims[1]), outer=collect(outer_dims[1]))
          if isa(newaxes[p], DefaultAxis)
            newaxes[p] = axistoadd
          else
            newaxes[p] = DictArray(merge(map(x->isa(x,DictArray) ? x.data : LDict(create_additional_fieldname(arr,tracker)=>x), (newaxes[p], axistoadd))...))
          end
        end
      end
    end
  end
  LabeledArray(newdata, (newaxes...))
end

"""

##### Description

reorders the fields such that the first field names are `names`.
The rest field names are placed sequentially after that.

"""
function reorder end

"""

##### Description

renames the fields such that the first field names are `names`.
The rest field names remain the same.

"""
function rename end

"""

`reorder(arr::LabeledArray, ks...)`

Reorder the field names of the base of `arr` so that the first few field names are `ks`.
The base of `arr` is expected to be a `DictArray`.

##### Return
A new `LabeledArray` whose base fields are shuffled from `arr` so that the first few field names are `ks`.

"""
reorder(arr::LabeledArray, ks...) = LabeledArray(reorder(arr.data, ks...), arr.axes)

"""

`rename(arr::LabeledArray, ks...)`

Rename the field names of the base of `arr` so that the first few field names are `ks`.

##### Return
A new `LabeledArray` whose first few field names of the base of `arr` are `ks`.

"""
rename(arr::LabeledArray, ks...) = LabeledArray(rename(arr.data, ks...), arr.axes)

"""

`@larr(...)`

Create a `LabeledArray`. The arguments `...` can be one of the following:

##### Arguments

* `k=>v` creates a field using array `v` with field name `k` for the base of the return `LabeledArray`. `k` can be an arbitrary type. If the element type of `v` is not `Nullable`, each element will be wrapped by `Nullable`. If `NA` is provided as an element, it is translated as `Nullable{T}()` for an appropriate type `T`.
* `k=v` creates a field using array `v` of the base with field name `:k`.
* There can be at most one non pair type argument, which will be converted into a `LabeledArray` and other pair arguments will update it.
* `axisN[...]` for some integer `N`: this creates an axis along the `N`th direction. If `...` are either keywords or pairs, those are used to create a `DictArray`. Otherwise, an array will be created using `...`.

##### Examples

```julia
julia> t = @larr(a=[1 NA;3 4;NA NA],:b=>[1.0 1.5;:sym 'a';"X" "Y"],c=1,axis1[:U,NA,:W],axis2[r=['m','n']])
3 x 2 LabeledArray

r |m       |n
--+--------+--------
  |a b   c |a b   c
--+--------+--------
U |1 1.0 1 |  1.5 1
  |3 sym 1 |4 a   1
W |  X   1 |  Y   1

julia> @larr(t, c=[NA NA;3 4;5 6], :d=>:X, axis1[k=["g","h","i"]])
3 x 2 LabeledArray

r |m         |n
--+----------+----------
k |a b   c d |a b   c d
--+----------+----------
g |1 1.0   X |  1.5   X
h |3 sym 3 X |4 a   4 X
i |  X   5 X |  Y   6 X
```

"""
macro larr(args...)
  data_pairs = Any[]
  axes_pairs = Any[]
  template = Nullable()
  for arg in args
    if :head in fieldnames(arg) && (arg.head == :kw || arg.head == :(=>))
      key = arg.head==:kw ? quote_symbol(arg.args[1]) : arg.args[1]
      value = arg.args[2]
      push!(data_pairs, quote
        $key => @nalift($(esc(value)))
      end)
    elseif :head in fieldnames(arg) && arg.head ==:ref && startswith(string(arg.args[1]), "axis") &&
           all(Bool[is_kw(a) for a in arg.args[2:end]])
      push!(axes_pairs, arg.args[1] => read_kws(arg.args[2:end]))
    elseif :head in fieldnames(arg) && arg.head == :ref && startswith(string(arg.args[1]), "axis") && length(arg.args) > 1
      if length(arg.args) != 2
        valueexpr = Expr(:vect, map(esc, arg.args[2:end])...)
        push!(axes_pairs, arg.args[1] => (verbatim_magic_symbol, quote
          @nalift($valueexpr)
        end))
        #throw(ArgumentError("if not a keyword/pair argument, the length has to be 1, consisting of an array for that axis."))
      else
        push!(axes_pairs, arg.args[1] => (verbatim_magic_symbol, quote
          @nalift($(esc(arg.args[2])))
        end))
      end
    elseif template.isnull #length(args) == 1
      template = Nullable(arg)
    else
      throw(ArgumentError("not a key=value type argument or an array argument $arg, or two or more base LabeledArrays are provided."))
    end
  end
  dataexp = if template.isnull && isempty(data_pairs)
    throw(ArgumentError("neither a base LabeledArray or a fieldname=>array pair provided."))
  elseif isempty(data_pairs)
    nothing
  else
    Expr(:call, :darr, Expr(:..., Expr(:vect, data_pairs...)))
  end
  axesexp = map(axes_pairs) do axispair
    axisname = axispair[1]
    axisvalue = axispair[2]
    axisexpr = if isa(axisvalue, Tuple) && length(axisvalue) == 2 && axisvalue[1] == verbatim_magic_symbol
      Expr(:kw, axisname, axisvalue[2])
    else
      Expr(:kw, axisname, Expr(:call, :darr, Expr(:..., Expr(:vect, axisvalue...))))
    end
  end
  if template.isnull
    Expr(:call, :larr, dataexp, axesexp...)
  else
    Expr(:call, :update_larr, quote @nalift($(esc(template.value))) end, dataexp, axesexp...)
  end
end

larr_inner(kwargs...) = begin
  data = []
  axes = []
  for (k,v) in kwargs
    if startswith(string(k), "axis")
      push!(axes, k=>nalift(v))
    else
      push!(data, k=>v)
    end
  end
  LabeledArray(darr(data...); axes...)
end

"""

`larr(...)`

Create a `LabeledArray`. The arguments `...` can be one of the following:

##### Arguments

* `k=>v` creates a field using array `v` with field name `k` for the underlying base `DictArray`. `k` can be an arbitrary type. If the element type of `v` is not `Nullable`, each element will be wrapped by `Nullable`. If you want to manually provide a `Nullable` array with `Nullable{T}()` elements in it, the macro version `@larr` may be more convenient to use. Note that this type of argument precedes the keyword type argument in the return `LabeledArray`, as shown in Examples below.
* `k=v` creates a field using an array `v` with field name `:k` for the underlying base `DictArray`.
* The keyword `axisN=v` for some integer `N` and an array `v` is treated specially. This will create the `N`th axis using the array `v`.
* There can be at most one non pair type argument, which will be converted into a `LabeledArray` and other pair arguments will update it.
Especially, if the non pair type argument is an array of `LDict`, it will be converted into a `DictArray`.

##### Examples

```julia
julia> t = larr(a=[1 2;3 4;5 6],:b=>[1.0 1.5;:sym 'a';"X" "Y"],c=1,axis1=[:U,:V,:W],axis2=darr(r=['m','n']))
3 x 2 LabeledArray

r |m       |n
--+--------+--------
  |b   a c |b   a c
--+--------+--------
U |1.0 1 1 |1.5 2 1
V |sym 3 1 |a   4 1
W |X   5 1 |Y   6 1

julia> larr(t, c=[1 2;3 4;5 6], :d=>:X, axis1=darr(k=["g","h","i"]))
3 x 2 LabeledArray

r |m         |n
--+----------+----------
k |b   a c d |b   a c d
--+----------+----------
g |1.0 1 1 X |1.5 2 2 X
h |sym 3 3 X |a   4 4 X
i |X   5 5 X |Y   6 6 X
```

"""
function larr end

larr0(arr::LabeledArray, kwargs...) = begin
  data = []
  newaxes = Any[arr.axes...]
  for (k,v) in kwargs
    kstr = string(k)
    if startswith(kstr, "axis")
      axisindex = parse(Int, kstr[5:endof(kstr)])
      newaxes[axisindex] = nalift(v)
    else
      push!(data, k=>nalift(v))
    end
  end
  LabeledArray(combine_data_inner(arr.data, LDict(data...)), (newaxes...))
end

combine_data_inner(arr1::DictArray, ldict::LDict) = darr(merge(arr1.data, ldict)...)
combine_data_inner(arr1::AbstractArray, ldict::LDict) = if isempty(ldict)
  arr1
else
  throw(ArgumentError("cannot combine an array of type $(typeof(arr1)) with a dict of type $(typeof(ldict))"))
end

larr(arr::AbstractArray) = convert(LabeledArray, nalift(arr))
larr(arr::AbstractArray, kwargs...) = larr(convert(LabeledArray, nalift(arr)), kwargs...)
larr(arr::AbstractArray, pairs...; kwargs...) = if isempty(kwargs) && isempty(pairs)
  convert(LabeledArray, nalift(arr))
else
  larr(convert(LabeledArray, nalift(arr)), pairs..., kwargs...)
end
larr(arr::LabeledArray, pairs...; kwargs...) = larr0(arr, pairs..., kwargs...)
larr(arr::LabeledArray) = arr
larr(args...; kwargs...) = larr_inner(args..., kwargs...)

Base.convert{K,V,N}(::Type{LabeledArray}, arr::LabeledArray{LDict{K,V},N}) = LabeledArray(convert_to_dictarray_if_possible(peel(arr)), arr.axes)
Base.convert{K,V,N}(::Type{LabeledArray}, arr::LabeledArray{Nullable{LDict{K,V}},N}) = LabeledArray(convert_to_dictarray_if_possible(peel(arr)), arr.axes)

# for some reason, this generic verion is gtakeed up instead of the LDict specialized versions.
Base.convert(::Type{LabeledArray}, arr::DictArray) = LabeledArray(arr)
Base.convert(::Type{LabeledArray}, arr::AbstractArray) = if eltype(arr) <: LDict
  LabeledArray(convert_to_dictarray_if_possible(arr))
elseif eltype(arr) <: Nullable && eltype(eltype(arr)) <: LDict
  LabeledArray(convert_to_dictarray_if_possible(arr))
else
  LabeledArray(arr)
end

update_larr(base, data; kwargs...) = update_larr(convert(LabeledArray, base), data;kwargs...)
update_larr(base::LabeledArray, data; kwargs...) = begin
  newdata = if data == nothing
    base.data
  else
    darr(merge(base.data.data, data.data)...)
  end
  newaxes = if isempty(kwargs)
    base.axes
  else
    axes = cell(length(base.axes))
    copy!(axes, base.axes)
    for (k,v) in kwargs
      kstr = string(k)
      if startswith(kstr, "axis")
        axisindex = parse(Int, kstr[5:endof(kstr)])
        axes[axisindex] = v
      end
    end
    axes
  end
  LabeledArray(newdata, (newaxes...))
end

"""

`merge(::LabeledArray, ::LabeledArray)`

Merge two `LabeledArrays`. The axes set of the two should be identical.
The bases are merged together and the common axes set is used.

##### Examples

```julia
julia> merge(larr(a=[1,2,3],b=[:x,:y,:z],axis1=[:a,:b,:c]),larr(c=[4,5,6],b=[:m,:n,:p],axis1=[:a,:b,:c]))
3 LabeledArray

  |a b c
--+------
a |1 m 4
b |2 n 5
c |3 p 6
```

"""
Base.merge(arr1::LabeledArray, arr2::LabeledArray) = begin
  @assert(pickaxis(arr1) == pickaxis(arr2))
  LabeledArray(merge(peel(arr1), peel(arr2)), pickaxis(arr1))
end

"""

`merge(::LabeledArray, ::DictArray...)`

Merge the base of the `LabeledArray` and the rest `DictArray`s.
Together with the axes set of the input `LabeledArray`, return a new `LabeledArray`.

##### Examples

```julia
julia> merge(larr(a=[1,2,3],b=[:x,:y,:z],axis1=[:a,:b,:c]),darr(c=[4,5,6],b=[:m,:n,:p]),darr(a=["X","Y","Z"]))
3 LabeledArray

  |a b c
--+------
a |X m 4
b |Y n 5
c |Z p 6
```

"""
Base.merge(arr1::LabeledArray, args::DictArray...) = LabeledArray(merge(peel(arr1), args...), pickaxis(arr1))


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

using System;
using System.Collections.Generic;
using Microsoft.WindowsAzure.Commands.ScenarioTest;
using Microsoft.WindowsAzure.Commands.Storage.Common;
using Xunit;

namespace Microsoft.WindowsAzure.Commands.Storage.Test.Common
{
    /// <summary>
    /// Unit test for sas token helper
    /// </summary>
    public class SasTokenHelperTest : StorageTestBase
    {
        [Fact]
        [Trait(Category.AcceptanceType, Category.CheckIn)]
        public void ValidateExistingPolicyTest()
        {
            Dictionary<string, string> policies = new Dictionary<string,string>()
                { { "test", "test" }, { "Abc", "abc" }, { "123", "123" } };
            SasTokenHelper.GetExistingPolicy<string>(policies, "ABC");
            SasTokenHelper.GetExistingPolicy<string>(policies, "test");
            SasTokenHelper.GetExistingPolicy<string>(policies, "tesT");
            SasTokenHelper.GetExistingPolicy<string>(policies, "123");
            AssertThrows<ArgumentException>(() => SasTokenHelper.GetExistingPolicy<string>(policies, "test1"));
        }

        [Fact]
        [Trait(Category.AcceptanceType, Category.CheckIn)]
        public void ValidateExistingPolicyWithEmptyPoliciesTest()
        {
            Dictionary<string, string> policies = new Dictionary<string, string>();
            AssertThrows<ArgumentException>(() => SasTokenHelper.GetExistingPolicy<string>(policies, "test1"));
        }

        [Fact]
        [Trait(Category.AcceptanceType, Category.CheckIn)]
        public void SetupAccessPolicyLifeTimeTest()
        {
            DateTime? start = DateTime.Now;
            DateTime? end = start.Value.AddHours(1.0);
            DateTimeOffset? testStart = null;
            DateTimeOffset? testEnd = null;
            SasTokenHelper.SetupAccessPolicyLifeTime(start, end, out testStart, out testEnd, true);
            Assert.Equal(testStart.Value.UtcDateTime.ToString(), start.Value.ToUniversalTime().ToString());
            Assert.Equal(testEnd.Value.UtcDateTime.ToString(), end.Value.ToUniversalTime().ToString());
            AssertThrows<ArgumentException>(() => SasTokenHelper.SetupAccessPolicyLifeTime(end, start, out testStart, out testEnd, true));
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
import React from 'react'
import * as ACTION_TYPES from '../constants/action_types'
import * as MAPPING_TYPES from '../constants/mapping_types'
import * as api from '../networking/api'
import * as StreamFilters from '../components/streams/StreamFilters'
import * as StreamRenderables from '../components/streams/StreamRenderables'
import { ZeroState } from '../components/zeros/Zeros'

export function loadNotifications(params = {}) {
  const categoryResult = params.category && params.category !== 'all' ? `/${params.category}` : ''
  return {
    type: ACTION_TYPES.LOAD_STREAM,
    payload: { endpoint: api.notifications(params) },
    meta: {
      mappingType: MAPPING_TYPES.ACTIVITIES,
      renderStream: {
        asList: StreamRenderables.notificationList,
        asGrid: StreamRenderables.notificationList,
        asZero: <ZeroState>Sorry, no notifications found.</ZeroState>,
      },
      resultFilter: StreamFilters.notificationsFromActivities,
      resultKey: `/notifications${categoryResult}`,
      updateKey: '/notifications',
    },
  }
}

export function checkForNewNotifications() {
  return {
    type: ACTION_TYPES.HEAD,
    payload: {
      endpoint: api.newNotifications(),
      method: 'HEAD',
    },
  }
}

export const loadAnnouncements = () =>
  ({
    type: ACTION_TYPES.LOAD_STREAM,
    payload: {
      endpoint: api.announcements(),
    },
    meta: {
      mappingType: MAPPING_TYPES.ANNOUNCEMENTS,
      resultKey: '/announcements',
      updateKey: '/announcements',
    },
  })

export const markAnnouncementRead = () =>
  ({
    type: ACTION_TYPES.NOTIFICATIONS.MARK_ANNOUNCEMENT_READ,
    payload: {
      endpoint: api.markAnnouncementRead(),
      method: 'PATCH',
    },
  })


text:
author: someone
layout: post_full
type: image
featimg: 5.jpg
title: Pulau Jemur
tags: [image]
category: [image]
---
Pulau Jemur (luas 250 ha) adalah sebuah pulau milik Indonesia yang terletak di Selat Malaka, dekat dengan perbatasan Malaysia. Pulau ini termasuk dalam wilayah Kecamatan Pasir Limau Kapas, Kabupaten Rokan Hilir, Provinsi Riau. Letaknya sekitar 72,4 km dari Bagansiapiapi dan 64,3 km dari Pelabuhan Klang di Malaysia. Pulau ini merupakan pulau terluas dari Kepulauan Arwah, gugusan sembilan pulau, di antaranya Pulau Jemur, Tokong Emas, Tokong Simbang dan Labuhan Bilik.

Pulau Jemur terkenal dengan panorama alam seperti pantai berpasir putih dan sebagai habitat penyu hijau. Perairan di sekitar pulau ini terkenal sebagai daerah penghasil ikan.

Pulau Jemur tidak berpenghuni dan hanya menjadi tempat persinggahan bagi nelayan yang sedang melaut. Sebuah pos TNI-AL didirikan di pulau ini untuk kepentingan pengamatan dan navigasi.

Pulau ini sempat menjadi objek sentimen anti-Malaysia di Indonesia, setelah sejumlah media Indonesia pada bulan Agustus 2009 melaporkan bahwa Malaysia bermaksud mengelola Pulau Jemur sebagai tujuan wisata.melalui situs traveljournals.net. Kepemilikan sah Pulau Jemur (dan gugusan Kepulauan Arwah) oleh Indonesia didasarkan atas sertifikat tanah yang dimiliki oleh Raja Siak. Ketegangan ini baru mereda setelah diketahui terdapat pulau bernama Pulau Jemor sebagai bagian dari Kesultanan Selangor.


text:
<?php

/**
 * Doctrine_Sequence_Informix
 *
 * @package     Doctrine
 * @subpackage  Sequence
 * @author      Konsta Vesterinen <kvesteri@cc.hut.fi>
 * @license     http://www.opensource.org/licenses/lgpl-license.php LGPL
 * @link        www.phpdoctrine.org
 * @since       1.0
 * @version     $Revision: 3884 $
 */
class Doctrine_Sequence_Informix extends Doctrine_Sequence
{ }


text:
package org.snaker.engine.handlers.impl;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import org.snaker.engine.SnakerEngine;
import org.snaker.engine.SnakerException;
import org.snaker.engine.core.Execution;
import org.snaker.engine.core.ModelContainer;
import org.snaker.engine.entity.Order;
import org.snaker.engine.entity.Process;
import org.snaker.engine.handlers.IHandler;
import org.snaker.engine.model.ProcessModel;
import org.snaker.engine.model.SubProcessModel;

/**
 * 启动子流程的处理器
 * @author yuqs
 * @version 1.0
 */
public class StartSubProcessHandler implements IHandler {
	private SubProcessModel model;
	/**
	 * 是否以future方式执行启动子流程任务
	 */
	private boolean isFutureRunning = false;
	public StartSubProcessHandler(SubProcessModel model) {
		this.model = model;
	}

	public StartSubProcessHandler(SubProcessModel model, boolean isFutureRunning) {
		this.model = model;
		this.isFutureRunning = isFutureRunning;
	}

	/**
	 * 子流程执行的处理
	 */
	@Override
	public void handle(Execution execution) {
		//获取子流程模型对象
		ProcessModel pm = model.getSubProcess();
		//根据子流程模型名称获取子流程定义对象
		Process process = ModelContainer.getEntity(pm.getName());
		SnakerEngine engine = execution.getEngine();

		Execution child = execution.createSubExecution(execution, process, model.getName());
		Order order = null;
		if(isFutureRunning) {
			//创建单个线程执行器来执行启动子流程的任务
			ExecutorService es = Executors.newSingleThreadExecutor();
			//提交执行任务,并返回future
			Future<Order> future = es.submit(new ExecuteTask(execution, process, model.getName()));
			try {
				es.shutdown();
				order = future.get();
			} catch (InterruptedException e) {
				throw new SnakerException("Future线程被强制终止执行", e.getCause());
			} catch (ExecutionException e) {
				throw new SnakerException("Future线程执行异常.", e.getCause());
			}
		} else {
			order  = engine.startInstanceByExecution(child);
		}
		if(order == null) throw new SnakerException("子流程创建失败");

		execution.addTasks(engine.query().getActiveTasks(order.getId()));
	}

	/**
	 * Future模式的任务执行。通过call返回任务结果集
	 * @author yuqs
	 * @version 1.0
	 */
	class ExecuteTask implements Callable<Order> {
		private SnakerEngine engine;
		private Execution child;
		/**
		 * 构造函数
		 * @param execution
		 * @param process
		 * @param parentNodeName
		 */
		public ExecuteTask(Execution execution, Process process,String parentNodeName) {
			this.engine = execution.getEngine();
			child = execution.createSubExecution(execution, process, parentNodeName);
		}
		@Override
		public Order call() throws Exception {
			return engine.startInstanceByExecution(child);
		}
	}
}


text:
package com.crawljax.test;

public class SimpleJsSiteCrawlTest extends SimpleCrawlTest {

	private static final int NUMBER_OF_STATES = 11;
	private static final int NUMBER_OF_EDGES = 10;

	public SimpleJsSiteCrawlTest() {
		super(NUMBER_OF_STATES, NUMBER_OF_EDGES);
	}

	@Override
	public BaseCrawler getCrawler() {
		return new SimpleJsSiteCrawl();
	}

}


text:
require 'json'
require 'puppet/util/inifile'

class Puppet::Provider::Tuskar < Puppet::Provider

  def self.conf_filename
    '/etc/tuskar/tuskar.conf'
  end

  def self.withenv(hash, &block)
    saved = ENV.to_hash
    hash.each do |name, val|
      ENV[name.to_s] = val
    end

    yield
  ensure
    ENV.clear
    saved.each do |name, val|
      ENV[name] = val
    end
  end

  def self.tuskar_credentials
    @tuskar_credentials ||= get_tuskar_credentials
  end

  def self.get_tuskar_credentials
    auth_keys = ['auth_host', 'auth_port', 'auth_protocol',
                 'admin_tenant_name', 'admin_user', 'admin_password']
    conf = tuskar_conf
    if conf and conf['keystone_authtoken'] and
        auth_keys.all?{|k| !conf['keystone_authtoken'][k].nil?}
      return Hash[ auth_keys.map \
                   { |k| [k, conf['keystone_authtoken'][k].strip] } ]
    else
      raise(Puppet::Error, "File: #{conf_filename} does not contain all \
required sections.  Tuskar types will not work if tuskar is not \
correctly configured.")
    end
  end

  def tuskar_credentials
    self.class.tuskar_credentials
  end

  def self.auth_endpoint
    @auth_endpoint ||= get_auth_endpoint
  end

  def self.get_auth_endpoint
    q = tuskar_credentials
    "#{q['auth_protocol']}://#{q['auth_host']}:#{q['auth_port']}/v2.0/"
  end

  def self.tuskar_conf
    return @tuskar_conf if @tuskar_conf
    @tuskar_conf = Puppet::Util::IniConfig::File.new
    @tuskar_conf.read(conf_filename)
    @tuskar_conf
  end

  def self.auth_tuskar(*args)
    q = tuskar_credentials
    authenv = {
      :OS_AUTH_URL    => self.auth_endpoint,
      :OS_USERNAME    => q['admin_user'],
      :OS_TENANT_NAME => q['admin_tenant_name'],
      :OS_PASSWORD    => q['admin_password']
    }
    begin
      withenv authenv do
        tuskar(args)
      end
    rescue Exception => e
      if (e.message =~ /\[Errno 111\] Connection refused/) or
          (e.message =~ /\(HTTP 400\)/)
        sleep 10
        withenv authenv do
          tuskar(args)
        end
      else
       raise(e)
      end
    end
  end

  def auth_tuskar(*args)
    self.class.auth_tuskar(args)
  end

  def tuskar_manage(*args)
    cmd = args.join(" ")
    output = `#{cmd}`
    $?.exitstatus
  end

  def self.reset
    @tuskar_conf        = nil
    @tuskar_credentials = nil
  end

  def self.list_tuskar_resources(type, *args)
    json = auth_tuskar("--json", "#{type}-list", *args)
    return JSON.parse(json)
  end

  def self.get_tuskar_resource_attrs(type, id)
    json = auth_tuskar("--json", "#{type}-show", id)
    return JSON.parse(json)
  end

end


text:
DEFINE_LOG_CATEGORY_STATIC(BaseItem, Log, All);

void ABaseItem::PlayInteractionSound(bool bIsSuccessful)
{
	USoundBase* SoundToPlay = (bIsSuccessful) ? SuccessfulSoundCue : FailedSoundCue;

	if (SoundToPlay) UGameplayStatics::PlaySoundAtLocation(GetWorld(), SoundToPlay, GetActorLocation());
}

void ABaseItem::PrintWarnings()
{
	if (bIsPickupable && (!ItemTexture || ItemName.IsEmpty()))
	{
		UE_LOG(BaseItem, Error, TEXT("The %s item is marked as pickupable yet you haven't assigned a texture or a name"), *GetNameSafe(this));
	}

	if (!SuccessfulSoundCue)
	{
		UE_LOG(BaseItem, Warning, TEXT("You haven't assigned a successful sound cue in %s"),*GetNameSafe(this));
	}
}

// Sets default values
ABaseItem::ABaseItem()
{
 	// Set this actor to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
	PrimaryActorTick.bCanEverTick = true;

	SM = CreateDefaultSubobject<UStaticMeshComponent>(FName("SM"));
}

// Called when the game starts or when spawned
void ABaseItem::BeginPlay()
{
	Super::BeginPlay();

#if !UE_BUILD_SHIPPING

	PrintWarnings();

#endif
}

bool ABaseItem::Interact(UBackpackComponent& BackpackComponent)
{
	if (!RequiredItemName.IsEmpty() && !bIsPickupable)
	{
		ABaseItem* FoundItem=nullptr;

		if (BackpackComponent.GetEquippedItem(FoundItem) && FoundItem->ItemName.Equals(RequiredItemName))
		{
			BackpackComponent.RemoveItemFromBackpack(FoundItem);
			PlayInteractionSound(true);
			return true;
		}
		else
		{
			PlayInteractionSound(false);
			return false;
		}

	}
	else if (bIsPickupable && BackpackComponent.AddItemToBackpack(this))
	{
		PlayInteractionSound(true);

		SM->SetVisibility(false, true);
		SM->SetCollisionEnabled(ECollisionEnabled::NoCollision);

		return true;
	}
	else
	{
		PlayInteractionSound(true);
		return true;
	}
}

void ABaseItem::OnBeginFocus()
{
	if(bShouldRenderOutline) SM->SetRenderCustomDepth(true);
}

void ABaseItem::OnLostFocus()
{
	SM->SetRenderCustomDepth(false);
}


text:
class PendingFeedback < ActiveRecord::Base
	belongs_to :engagement
	belongs_to :iteration
end


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
 ~ Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 ~
 ~ Licensed under the Apache License, Version 2.0 (the "License");
 ~ you may not use this file except in compliance with the License.
 ~ You may obtain a copy of the License at
 ~
 ~      http://www.apache.org/licenses/LICENSE-2.0
 ~
 ~ Unless required by applicable law or agreed to in writing, software
 ~ distributed under the License is distributed on an "AS IS" BASIS,
 ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 ~ See the License for the specific language governing permissions and
 ~ limitations under the License.
-->

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <parent>
    <groupId>org.wso2.carbon</groupId>
        <artifactId>carbon-storage-management</artifactId>
        <version>4.3.0-SNAPSHOT</version>
        <relativePath>../../pom.xml</relativePath>
    </parent>

    <modelVersion>4.0.0</modelVersion>
    <artifactId>cassandra-feature</artifactId>
    <packaging>pom</packaging>
    <name>WSO2 Carbon - Cassandra Feature Aggregator Module</name>
    <url>http://wso2.org</url>

    <modules>
        <module>server/org.wso2.carbon.cassandra.server.feature</module>
        <module>client/org.wso2.carbon.cassandra.client.feature</module>
        <module>client/org.wso2.carbon.cassandra.datareader.feature</module>
        <module>server/org.wso2.carbon.cassandra.dataaccess.feature</module>
        <module>server/org.wso2.carbon.cassandra.mgt.feature</module>
        <module>server/org.wso2.carbon.cassandra.mgt.ui.feature</module>
        <module>server/org.wso2.carbon.cassandra.feature</module>
        <module>server-monitor/org.wso2.carbon.cassandra.cluster.feature</module>
        <module>server-monitor/org.wso2.carbon.cassandra.cluster.mgt.feature</module>
        <module>server-monitor/org.wso2.carbon.cassandra.cluster.mgt.ui.feature</module>
        <module>server-monitor/org.wso2.carbon.cassandra.cluster.proxy.feature</module>
        <module>server-monitor/org.wso2.carbon.cassandra.monitor.feature</module>
        <module>common/org.wso2.carbon.cassandra.common.feature</module>

    </modules>

    <dependencyManagement>
        <dependencies>

            <!--Cassandra -->

            <dependency>
                <groupId>org.apache.cassandra.wso2</groupId>
                <artifactId>apache-cassandra</artifactId>
                <version>${wso2.cassandra.version}</version>
            </dependency>

            <!--Hector-->
            <dependency>
                <groupId>org.hectorclient</groupId>
                <artifactId>hector-core</artifactId>
                <version>${hector-core.version}</version>
            </dependency>
            <dependency>
                <groupId>libthrift.wso2</groupId>
                <artifactId>libthrift</artifactId>
                <version>${libthrift.version}</version>
            </dependency>
            <dependency>
                <groupId>org.perf4j.wso2</groupId>
                <artifactId>perf4j</artifactId>
                <version>${perf4j.version}</version>
            </dependency>
            <dependency>
                <groupId>org.cliffc.high_scale_lib.wso2</groupId>
                <artifactId>high-scale-lib</artifactId>
                <version>${highscale.version}</version>
            </dependency>
            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-api</artifactId>
                <version>${slf4j.version}</version>
            </dependency>
            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-log4j12</artifactId>
                <version>${slf4j.version}</version>
            </dependency>

            <!--Cassandra Component-->

            <dependency>
                <groupId>org.wso2.carbon</groupId>
                <artifactId>org.wso2.carbon.cassandra.dataaccess</artifactId>
                <version>${wso2carbon.version.cassandra}</version>
            </dependency>
            <dependency>
                <groupId>org.wso2.carbon</groupId>
                <artifactId>org.wso2.carbon.cassandra.server</artifactId>
                <version>${wso2carbon.version.cassandra}</version>
            </dependency>
            <dependency>
                <groupId>org.wso2.carbon</groupId>
                <artifactId>org.wso2.carbon.cassandra.sharedkey</artifactId>
                <version>${wso2carbon.version.cassandra}</version>
            </dependency>
            <dependency>
                <groupId>org.wso2.carbon</groupId>
                <artifactId>org.wso2.carbon.cassandra.mgt</artifactId>
                <version>${wso2carbon.version.cassandra}</version>
            </dependency>
            <dependency>
                <groupId>org.wso2.carbon</groupId>
                <artifactId>org.wso2.carbon.cassandra.mgt.ui</artifactId>
                <version>${wso2carbon.version.cassandra}</version>
            </dependency>
            <dependency>
                <groupId>org.wso2.carbon</groupId>
                <artifactId>org.wso2.carbon.cassandra.mgt.stub</artifactId>
                <version>${wso2carbon.version.cassandra}</version>
            </dependency>
            <dependency>
                <groupId>org.yaml.wso2</groupId>
                <artifactId>snakeyaml</artifactId>
                <version>${yaml.version}</version>
            </dependency>
            <dependency>
                <groupId>com.google.guava.wso2</groupId>
                <artifactId>guava</artifactId>
                <version>${guava.version}</version>
            </dependency>
            <dependency>
                <groupId>com.googlecode.concurrentlinkedhashmap.wso2</groupId>
                <artifactId>concurrentlinkedhashmap-lru</artifactId>
                <version>${concurrentlinkedhashmap.version}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.hadoop.wso2</groupId>
                <artifactId>avro</artifactId>
                <version>${avro.version}</version>
            </dependency>

            <!--Carbon-->
            <dependency>
                <groupId>org.wso2.carbon</groupId>
                <artifactId>org.wso2.carbon.user.api</artifactId>
                <version>${wso2carbon.version.cassandra}</version>
            </dependency>
            <dependency>
                <groupId>org.wso2.carbon</groupId>
                <artifactId>org.wso2.carbon.core.server.feature</artifactId>
                <version>${project.version}</version>
                <type>zip</type>
            </dependency>
            <dependency>
                <groupId>org.wso2.carbon</groupId>
                <artifactId>org.wso2.carbon.identity.authentication</artifactId>
                <version>${wso2carbon.version.cassandra}</version>
            </dependency>
            <dependency>
                <groupId>org.safehaus.jug.wso2</groupId>
                <artifactId>jug</artifactId>
                <version>${jug.version}</version>
            </dependency>
            <dependency>
                <groupId>com.googlecode.json-simple.wso2</groupId>
                <artifactId>json-simple</artifactId>
                <version>${simple-json.version}</version>
            </dependency>
            <!--dependency>
                <groupId>org.mortbay.jetty</groupId>
                <artifactId>jetty-util</artifactId>
                <version>${jetty.version}</version>
            </dependency-->
            <dependency>
                <groupId>org.codehaus.jackson</groupId>
                <artifactId>jackson-core-asl</artifactId>
                <version>${jackson.version}</version>
            </dependency>
            <dependency>
                <groupId>org.codehaus.jackson</groupId>
                <artifactId>jackson-mapper-asl</artifactId>
                <version>${jackson.version}</version>
            </dependency>
            <dependency>
                <groupId>org.github.wso2</groupId>
                <artifactId>jamm</artifactId>
                <version>${jamm.version}</version>
            </dependency>
            <dependency>
                <groupId>antlr.wso2</groupId>
                <artifactId>antlr</artifactId>
                <version>${antlr.version}</version>
            </dependency>
	    <dependency>
                <groupId>org.antlr.wso2</groupId>
                <artifactId>antlr-runtime</artifactId>
                <version>${antlr.version}</version>
            </dependency>
            <dependency>
                <groupId>org.xerial.snappy</groupId>
                <artifactId>snappy-java</artifactId>
                <version>${snappy-java.version}</version>
            </dependency>
            <dependency>
                <groupId>snaptree.wso2</groupId>
                <artifactId>snaptree</artifactId>
                <version>${snaptree.version}</version>
            </dependency>
            <dependency>
                <groupId>metrics-core.wso2</groupId>
                <artifactId>metrics-core</artifactId>
                <version>${metrics-core.version}</version>
            </dependency>
	    <dependency>
		<groupId>com.ning</groupId>
		<artifactId>compress-lzf</artifactId>
		<version>${compress-lzf.version}</version>
	    </dependency>
        </dependencies>
    </dependencyManagement>

    <repositories>
        <repository>
            <id>wso2-nexus</id>
            <name>WSO2 internal Repository</name>
            <url>http://maven.wso2.org/nexus/content/groups/wso2-public/</url>
            <releases>
                <enabled>true</enabled>
                <updatePolicy>daily</updatePolicy>
                <checksumPolicy>fail</checksumPolicy>
            </releases>
        </repository>
        <!--moved to nexus

        <repository>
            <id>riptano</id>
            <name>riptano</name>
            <url>http://mvn.riptano.com/content/repositories/public/</url>
        </repository>

        -->
    </repositories>

    <properties>
        <wso2carbon.version.cassandra>${wso2carbon.version}</wso2carbon.version.cassandra>
        <wso2carbon.version.cassandra.feature>${wso2carbon.version}</wso2carbon.version.cassandra.feature>
        <cassandra.version>1.1.3.wso2v5</cassandra.version>
        <hector-core.version>1.1-0</hector-core.version>
        <libthrift.version>0.7.wso2v1</libthrift.version>
        <perf4j.version>0.9.12.wso2v1</perf4j.version>
        <highscale.version>1.1.2.wso2v1</highscale.version>
        <slf4j.version>1.6.1</slf4j.version>
        <yaml.version>1.6.wso2v1</yaml.version>
        <guava.version>${google.guava.wso2.version}</guava.version>
        <concurrentlinkedhashmap.version>1.2.0.wso2v1</concurrentlinkedhashmap.version>
        <avro.version>1.4.0-fixes.wso2v1</avro.version>
        <jug.version>2.0.0.wso2v1</jug.version>
        <simple-json.version>1.1.wso2v1</simple-json.version>
        <!--jetty.version>6.1.26</jetty.version-->
        <jackson.version>1.9.2</jackson.version>
        <jamm.version>0.2.5.wso2v2</jamm.version>
        <antlr.version>3.2.0.wso2v1</antlr.version>
	<metrics-core.version>2.0.3.wso2v1</metrics-core.version>
	<snaptree.version>0.1.wso2v1</snaptree.version>
	<snappy-java.version>1.1.1.6</snappy-java.version>
	<compress-lzf.version>0.8.4</compress-lzf.version>
    </properties>

</project>


text:
"""A base class for contents managers."""

# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.

from fnmatch import fnmatch
import itertools
import json
import os
import re

from tornado.web import HTTPError

from .checkpoints import Checkpoints
from traitlets.config.configurable import LoggingConfigurable
from nbformat import sign, validate, ValidationError
from nbformat.v4 import new_notebook
from ipython_genutils.importstring import import_item
from traitlets import (
    Any,
    Dict,
    Instance,
    List,
    TraitError,
    Type,
    Unicode,
)
from ipython_genutils.py3compat import string_types

copy_pat = re.compile(r'\-Copy\d*\.')

class ContentsManager(LoggingConfigurable):
    """Base class for serving files and directories.

    This serves any text or binary file,
    as well as directories,
    with special handling for JSON notebook documents.

    Most APIs take a path argument,
    which is always an API-style unicode path,
    and always refers to a directory.

    - unicode, not url-escaped
    - '/'-separated
    - leading and trailing '/' will be stripped
    - if unspecified, path defaults to '',
      indicating the root path.

    """

    notary = Instance(sign.NotebookNotary)
    def _notary_default(self):
        return sign.NotebookNotary(parent=self)

    hide_globs = List(Unicode(), [
            u'__pycache__', '*.pyc', '*.pyo',
            '.DS_Store', '*.so', '*.dylib', '*~',
        ], config=True, help="""
        Glob patterns to hide in file and directory listings.
    """)

    untitled_notebook = Unicode("Untitled", config=True,
        help="The base name used when creating untitled notebooks."
    )

    untitled_file = Unicode("untitled", config=True,
        help="The base name used when creating untitled files."
    )

    untitled_directory = Unicode("Untitled Folder", config=True,
        help="The base name used when creating untitled directories."
    )

    pre_save_hook = Any(None, config=True, allow_none=True,
        help="""Python callable or importstring thereof

        To be called on a contents model prior to save.

        This can be used to process the structure,
        such as removing notebook outputs or other side effects that
        should not be saved.

        It will be called as (all arguments passed by keyword)::

            hook(path=path, model=model, contents_manager=self)

        - model: the model to be saved. Includes file contents.
          Modifying this dict will affect the file that is stored.
        - path: the API path of the save destination
        - contents_manager: this ContentsManager instance
        """
    )
    def _pre_save_hook_changed(self, name, old, new):
        if new and isinstance(new, string_types):
            self.pre_save_hook = import_item(self.pre_save_hook)
        elif new:
            if not callable(new):
                raise TraitError("pre_save_hook must be callable")

    def run_pre_save_hook(self, model, path, **kwargs):
        """Run the pre-save hook if defined, and log errors"""
        if self.pre_save_hook:
            try:
                self.log.debug("Running pre-save hook on %s", path)
                self.pre_save_hook(model=model, path=path, contents_manager=self, **kwargs)
            except Exception:
                self.log.error("Pre-save hook failed on %s", path, exc_info=True)

    checkpoints_class = Type(Checkpoints, config=True)
    checkpoints = Instance(Checkpoints, config=True)
    checkpoints_kwargs = Dict(config=True)

    def _checkpoints_default(self):
        return self.checkpoints_class(**self.checkpoints_kwargs)

    def _checkpoints_kwargs_default(self):
        return dict(
            parent=self,
            log=self.log,
        )

    # ContentsManager API part 1: methods that must be
    # implemented in subclasses.

    def dir_exists(self, path):
        """Does a directory exist at the given path?

        Like os.path.isdir

        Override this method in subclasses.

        Parameters
        ----------
        path : string
            The path to check

        Returns
        -------
        exists : bool
            Whether the path does indeed exist.
        """
        raise NotImplementedError

    def is_hidden(self, path):
        """Is path a hidden directory or file?

        Parameters
        ----------
        path : string
            The path to check. This is an API path (`/` separated,
            relative to root dir).

        Returns
        -------
        hidden : bool
            Whether the path is hidden.

        """
        raise NotImplementedError

    def file_exists(self, path=''):
        """Does a file exist at the given path?

        Like os.path.isfile

        Override this method in subclasses.

        Parameters
        ----------
        path : string
            The API path of a file to check for.

        Returns
        -------
        exists : bool
            Whether the file exists.
        """
        raise NotImplementedError('must be implemented in a subclass')

    def exists(self, path):
        """Does a file or directory exist at the given path?

        Like os.path.exists

        Parameters
        ----------
        path : string
            The API path of a file or directory to check for.

        Returns
        -------
        exists : bool
            Whether the target exists.
        """
        return self.file_exists(path) or self.dir_exists(path)

    def get(self, path, content=True, type=None, format=None):
        """Get a file or directory model."""
        raise NotImplementedError('must be implemented in a subclass')

    def save(self, model, path):
        """
        Save a file or directory model to path.

        Should return the saved model with no content.  Save implementations
        should call self.run_pre_save_hook(model=model, path=path) prior to
        writing any data.
        """
        raise NotImplementedError('must be implemented in a subclass')

    def delete_file(self, path):
        """Delete the file or directory at path."""
        raise NotImplementedError('must be implemented in a subclass')

    def rename_file(self, old_path, new_path):
        """Rename a file or directory."""
        raise NotImplementedError('must be implemented in a subclass')

    # ContentsManager API part 2: methods that have useable default
    # implementations, but can be overridden in subclasses.

    def delete(self, path):
        """Delete a file/directory and any associated checkpoints."""
        path = path.strip('/')
        if not path:
            raise HTTPError(400, "Can't delete root")
        self.delete_file(path)
        self.checkpoints.delete_all_checkpoints(path)

    def rename(self, old_path, new_path):
        """Rename a file and any checkpoints associated with that file."""
        self.rename_file(old_path, new_path)
        self.checkpoints.rename_all_checkpoints(old_path, new_path)

    def update(self, model, path):
        """Update the file's path

        For use in PATCH requests, to enable renaming a file without
        re-uploading its contents. Only used for renaming at the moment.
        """
        path = path.strip('/')
        new_path = model.get('path', path).strip('/')
        if path != new_path:
            self.rename(path, new_path)
        model = self.get(new_path, content=False)
        return model

    def info_string(self):
        return "Serving contents"

    def get_kernel_path(self, path, model=None):
        """Return the API path for the kernel

        KernelManagers can turn this value into a filesystem path,
        or ignore it altogether.

        The default value here will start kernels in the directory of the
        notebook server. FileContentsManager overrides this to use the
        directory containing the notebook.
        """
        return ''

    def increment_filename(self, filename, path='', insert=''):
        """Increment a filename until it is unique.

        Parameters
        ----------
        filename : unicode
            The name of a file, including extension
        path : unicode
            The API path of the target's directory

        Returns
        -------
        name : unicode
            A filename that is unique, based on the input filename.
        """
        path = path.strip('/')
        basename, ext = os.path.splitext(filename)
        for i in itertools.count():
            if i:
                insert_i = '{}{}'.format(insert, i)
            else:
                insert_i = ''
            name = u'{basename}{insert}{ext}'.format(basename=basename,
                insert=insert_i, ext=ext)
            if not self.exists(u'{}/{}'.format(path, name)):
                break
        return name

    def validate_notebook_model(self, model):
        """Add failed-validation message to model"""
        try:
            validate(model['content'])
        except ValidationError as e:
            model['message'] = u'Notebook Validation failed: {}:\n{}'.format(
                e.message, json.dumps(e.instance, indent=1, default=lambda obj: '<UNKNOWN>'),
            )
        return model

    def new_untitled(self, path='', type='', ext=''):
        """Create a new untitled file or directory in path

        path must be a directory

        File extension can be specified.

        Use `new` to create files with a fully specified path (including filename).
        """
        path = path.strip('/')
        if not self.dir_exists(path):
            raise HTTPError(404, 'No such directory: %s' % path)

        model = {}
        if type:
            model['type'] = type

        if ext == '.ipynb':
            model.setdefault('type', 'notebook')
        else:
            model.setdefault('type', 'file')

        insert = ''
        if model['type'] == 'directory':
            untitled = self.untitled_directory
            insert = ' '
        elif model['type'] == 'notebook':
            untitled = self.untitled_notebook
            ext = '.ipynb'
        elif model['type'] == 'file':
            untitled = self.untitled_file
        else:
            raise HTTPError(400, "Unexpected model type: %r" % model['type'])

        name = self.increment_filename(untitled + ext, path, insert=insert)
        path = u'{0}/{1}'.format(path, name)
        return self.new(model, path)

    def new(self, model=None, path=''):
        """Create a new file or directory and return its model with no content.

        To create a new untitled entity in a directory, use `new_untitled`.
        """
        path = path.strip('/')
        if model is None:
            model = {}

        if path.endswith('.ipynb'):
            model.setdefault('type', 'notebook')
        else:
            model.setdefault('type', 'file')

        # no content, not a directory, so fill out new-file model
        if 'content' not in model and model['type'] != 'directory':
            if model['type'] == 'notebook':
                model['content'] = new_notebook()
                model['format'] = 'json'
            else:
                model['content'] = ''
                model['type'] = 'file'
                model['format'] = 'text'

        model = self.save(model, path)
        return model

    def copy(self, from_path, to_path=None):
        """Copy an existing file and return its new model.

        If to_path not specified, it will be the parent directory of from_path.
        If to_path is a directory, filename will increment `from_path-Copy#.ext`.

        from_path must be a full path to a file.
        """
        path = from_path.strip('/')
        if to_path is not None:
            to_path = to_path.strip('/')

        if '/' in path:
            from_dir, from_name = path.rsplit('/', 1)
        else:
            from_dir = ''
            from_name = path

        model = self.get(path)
        model.pop('path', None)
        model.pop('name', None)
        if model['type'] == 'directory':
            raise HTTPError(400, "Can't copy directories")

        if to_path is None:
            to_path = from_dir
        if self.dir_exists(to_path):
            name = copy_pat.sub(u'.', from_name)
            to_name = self.increment_filename(name, to_path, insert='-Copy')
            to_path = u'{0}/{1}'.format(to_path, to_name)

        model = self.save(model, to_path)
        return model

    def log_info(self):
        self.log.info(self.info_string())

    def trust_notebook(self, path):
        """Explicitly trust a notebook

        Parameters
        ----------
        path : string
            The path of a notebook
        """
        model = self.get(path)
        nb = model['content']
        self.log.warn("Trusting notebook %s", path)
        self.notary.mark_cells(nb, True)
        self.save(model, path)

    def check_and_sign(self, nb, path=''):
        """Check for trusted cells, and sign the notebook.

        Called as a part of saving notebooks.

        Parameters
        ----------
        nb : dict
            The notebook dict
        path : string
            The notebook's path (for logging)
        """
        if self.notary.check_cells(nb):
            self.notary.sign(nb)
        else:
            self.log.warn("Saving untrusted notebook %s", path)

    def mark_trusted_cells(self, nb, path=''):
        """Mark cells as trusted if the notebook signature matches.

        Called as a part of loading notebooks.

        Parameters
        ----------
        nb : dict
            The notebook object (in current nbformat)
        path : string
            The notebook's path (for logging)
        """
        trusted = self.notary.check_signature(nb)
        if not trusted:
            self.log.warn("Notebook %s is not trusted", path)
        self.notary.mark_cells(nb, trusted)

    def should_list(self, name):
        """Should this file/directory name be displayed in a listing?"""
        return not any(fnmatch(name, glob) for glob in self.hide_globs)

    # Part 3: Checkpoints API
    def create_checkpoint(self, path):
        """Create a checkpoint."""
        return self.checkpoints.create_checkpoint(self, path)

    def restore_checkpoint(self, checkpoint_id, path):
        """
        Restore a checkpoint.
        """
        self.checkpoints.restore_checkpoint(self, checkpoint_id, path)

    def list_checkpoints(self, path):
        return self.checkpoints.list_checkpoints(path)

    def delete_checkpoint(self, checkpoint_id, path):
        return self.checkpoints.delete_checkpoint(checkpoint_id, path)


text:
module.exports = function() {
    switch (process.env.NODE_ENV) {
        case 'production':
            return {
                "databaseUrl": 'mongodb://ets:ets@ds127978.mlab.com:27978/heroku_0d43trbz'
            }
        case 'development':
            return {
                "databaseUrl": 'mongodb://localhost/meanstacktutorials'
            }
        case 'test':
            return {
                "databaseUrl": 'mongodb://localhost/node-test'
            }
        default:
            return {
                "error": "No configuration values supplied.\nTry 'NODE_ENV=development node build.js'\nOther value is 'production'."
            }
    }
};


text:
package com.doctoror.fuckoffmusicplayer.presentation.util;

import android.content.Context;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.FloatingActionButton;
import android.util.Pair;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

/**
 * {@link ViewUtils} test
 */
@Config(manifest = Config.NONE)
@RunWith(RobolectricTestRunner.class)
public final class ViewUtilsAndroidTest {

    private Pair<Integer, ViewGroup> prepareViewGroupWithValidChildHeights() {
        final Context context = RuntimeEnvironment.application;
        final int v1h = 101;
        final int v2h = 102;
        final int v3h = 103;
        final int v4h = 0;

        final ViewGroup vg = new FrameLayout(context);
        vg.setBottom(666);

        final View v1 = new View(context);
        v1.setBottom(v1h);
        vg.addView(v1);

        final View v2 = new View(context);
        v2.setBottom(v2h);
        vg.addView(v2);

        final View v3 = new View(context);
        v3.setBottom(v3h);
        vg.addView(v3);

        final View v4 = new View(context);
        v4.setBottom(v4h);
        vg.addView(v4);

        return new Pair<>(v1h + v2h + v3h + v4h, vg);
    }

    @Test(expected = NullPointerException.class)
    public void testChildHeightsNull() {
        //noinspection ConstantConditions
        ViewUtils.childHeights(null);
    }

    @Test
    public void testChildHeightsEmptyViewGroup() {
        final ViewGroup vg = new FrameLayout(RuntimeEnvironment.application);
        vg.setBottom(666);

        assertEquals(0, ViewUtils.childHeights(vg));
    }

    @Test
    public void testChildHeights() {
        final Pair<Integer, ViewGroup> result = prepareViewGroupWithValidChildHeights();
        assertEquals(result.first.intValue(), ViewUtils.childHeights(result.second));
    }

    @Test(expected = NullPointerException.class)
    public void testGetOverlayTopNull() {
        //noinspection ConstantConditions
        ViewUtils.getOverlayTop(null);
    }

    @Test
    public void testGetOverlayTopOrdinaryView() {
        final View view = new View(RuntimeEnvironment.application);
        assertEquals(0, ViewUtils.getOverlayTop(view));
    }

    @Test
    public void testGetOverlayTopNoBehavior() {
        final View view = new View(RuntimeEnvironment.application);
        view.setLayoutParams(new CoordinatorLayout.LayoutParams(0, 0));
        assertEquals(0, ViewUtils.getOverlayTop(view));
    }

    @Test
    public void testGetOverlayTopDifferentBehavior() {
        final View view = new View(RuntimeEnvironment.application);

        final CoordinatorLayout.LayoutParams p = new CoordinatorLayout.LayoutParams(0, 0);
        p.setBehavior(new FloatingActionButton.Behavior());

        view.setLayoutParams(p);
        assertEquals(0, ViewUtils.getOverlayTop(view));
    }

    @Test
    public void testGetOverlayTop() {
        final View view = new View(RuntimeEnvironment.application);

        final CoordinatorLayout.LayoutParams p = new CoordinatorLayout.LayoutParams(0, 0);
        final AppBarLayout.ScrollingViewBehavior b = new AppBarLayout.ScrollingViewBehavior();
        b.setOverlayTop(128);
        p.setBehavior(b);

        view.setLayoutParams(p);
        assertEquals(128, ViewUtils.getOverlayTop(view));
    }

    @Test
    public void testIsScrollableViewLargeEnoughToScrollWhenFalse() {
        final Context context = RuntimeEnvironment.application;
        final Pair<Integer, ViewGroup> heightsResult = prepareViewGroupWithValidChildHeights();

        final ViewGroup rootView = new FrameLayout(context);
        rootView.setBottom(heightsResult.first);

        final ViewGroup appBarLayout = new FrameLayout(context);
        final ViewGroup scrollableView = heightsResult.second;

        rootView.addView(appBarLayout);
        rootView.addView(scrollableView);

        assertFalse(ViewUtils.isScrollableViewLargeEnoughToScroll(rootView,
                appBarLayout,
                scrollableView,
                0));
    }

    @Test
    public void testIsScrollableViewLargeEnoughToScrollWhenTrue() {
        final Context context = RuntimeEnvironment.application;
        final Pair<Integer, ViewGroup> heightsResult = prepareViewGroupWithValidChildHeights();

        final ViewGroup rootView = new FrameLayout(context);
        rootView.setBottom(heightsResult.first / 2);

        final ViewGroup appBarLayout = new FrameLayout(context);
        appBarLayout.setBottom(heightsResult.first / 2);

        final ViewGroup scrollableView = heightsResult.second;

        rootView.addView(appBarLayout);
        rootView.addView(scrollableView);

        assertTrue(ViewUtils.isScrollableViewLargeEnoughToScroll(rootView,
                appBarLayout,
                scrollableView,
                0));
    }
}