text:
namespace kaldi {

template <typename Real>
void CompressedMatrix::CopyFromMat(const MatrixBase<Real> &mat) {
  if (data_ != NULL) {
    delete[] static_cast<float *>(
        data_);  // call delete [] because was allocated with new float[]
    data_ = NULL;
  }
  if (mat.NumRows() == 0) {
    return;
  }  // Zero-size matrix stored as zero pointer.

  GlobalHeader global_header;
  KALDI_COMPILE_TIME_ASSERT(sizeof(global_header) == 16);  // otherwise
  // something weird is happening and our code probably won't work or
  // won't be robust across platforms.

  // Below, the point of the "safety_margin" is that the minimum
  // and maximum values in the matrix shouldn't coincide with
  // the minimum and maximum ranges of the 16-bit range, because
  // this could cause certain problems in ComputeColHeader, where
  // we need to ensure that the percentile_0 through percentile_100
  // are in strictly increasing order.
  float min_value = mat.Min(), max_value = mat.Max();
  if (max_value == min_value)
    max_value = min_value + (1.0 + fabs(min_value));  // ensure it's strictly
                                                      // greater than min_value,
                                                      // even if matrix is
                                                      // constant.

  global_header.min_value = min_value;
  global_header.range = max_value - min_value;
  // We can't compress the matrix if there are inf's or nan's.
  // The caller should check for this first.
  KALDI_ASSERT(KALDI_ISFINITE(global_header.min_value) &&
               KALDI_ISFINITE(global_header.range));

  // Avoid division by zero if the matrix is just a constant:
  // make sure max_value > min_value.
  if (global_header.range <= 0.0) global_header.range = 1.0e-05;
  global_header.num_rows = mat.NumRows();
  global_header.num_cols = mat.NumCols();

  int32 data_size = DataSize(global_header);

  data_ = AllocateData(data_size);

  *(reinterpret_cast<GlobalHeader *>(data_)) = global_header;

  PerColHeader *header_data = reinterpret_cast<PerColHeader *>(
      static_cast<char *>(data_) + sizeof(GlobalHeader));
  unsigned char *byte_data =
      reinterpret_cast<unsigned char *>(header_data + global_header.num_cols);

  const Real *matrix_data = mat.Data();

  for (int32 col = 0; col < global_header.num_cols; col++) {
    CompressColumn(global_header, matrix_data + col, mat.Stride(),
                   global_header.num_rows, header_data, byte_data);
    header_data++;
    byte_data += global_header.num_rows;
  }
}

// Instantiate the template for float and double.
template void CompressedMatrix::CopyFromMat(const MatrixBase<float> &mat);

template void CompressedMatrix::CopyFromMat(const MatrixBase<double> &mat);

template <typename Real>
CompressedMatrix &CompressedMatrix::operator=(const MatrixBase<Real> &mat) {
  this->CopyFromMat(mat);
  return *this;
}

// Instantiate the template for float and double.
template CompressedMatrix &CompressedMatrix::operator=(
    const MatrixBase<float> &mat);

template CompressedMatrix &CompressedMatrix::operator=(
    const MatrixBase<double> &mat);

inline uint16 CompressedMatrix::FloatToUint16(const GlobalHeader &global_header,
                                              float value) {
  float f = (value - global_header.min_value) / global_header.range;
  if (f > 1.0) f = 1.0;                        // Note: this should not happen.
  if (f < 0.0) f = 0.0;                        // Note: this should not happen.
  return static_cast<int>(f * 65535 + 0.499);  // + 0.499 is to
  // round to closest int; avoids bias.
}

inline float CompressedMatrix::Uint16ToFloat(const GlobalHeader &global_header,
                                             uint16 value) {
  // the constant 1.52590218966964e-05 is 1/65535.
  return global_header.min_value +
         global_header.range * 1.52590218966964e-05 * value;
}

template <typename Real>  // static
void CompressedMatrix::ComputeColHeader(
    const GlobalHeader &global_header, const Real *data, MatrixIndexT stride,
    int32 num_rows, CompressedMatrix::PerColHeader *header) {
  KALDI_ASSERT(num_rows > 0);
  std::vector<Real> sdata(num_rows);  // the sorted data.
  for (size_t i = 0, size = sdata.size(); i < size; i++)
    sdata[i] = data[i * stride];

  if (num_rows >= 5) {
    int quarter_nr = num_rows / 4;
    // std::sort(sdata.begin(), sdata.end());
    // The elements at positions 0, quarter_nr,
    // 3*quarter_nr, and num_rows-1 need to be in sorted order.
    std::nth_element(sdata.begin(), sdata.begin() + quarter_nr, sdata.end());
    // Now, sdata.begin() + quarter_nr contains the element that would appear
    // in sorted order, in that position.
    std::nth_element(sdata.begin(), sdata.begin(), sdata.begin() + quarter_nr);
    // Now, sdata.begin() and sdata.begin() + quarter_nr contain the elements
    // that would appear at those positions in sorted order.
    std::nth_element(sdata.begin() + quarter_nr + 1,
                     sdata.begin() + (3 * quarter_nr), sdata.end());
    // Now, sdata.begin(), sdata.begin() + quarter_nr, and sdata.begin() +
    // 3*quarter_nr, contain the elements that would appear at those positions
    // in sorted order.
    std::nth_element(sdata.begin() + (3 * quarter_nr) + 1, sdata.end() - 1,
                     sdata.end());
    // Now, sdata.begin(), sdata.begin() + quarter_nr, and sdata.begin() +
    // 3*quarter_nr, and sdata.end() - 1, contain the elements that would appear
    // at those positions in sorted order.

    header->percentile_0 = FloatToUint16(global_header, sdata[0]);
    header->percentile_25 =
        std::max<uint16>(FloatToUint16(global_header, sdata[quarter_nr]),
                         header->percentile_0 + static_cast<uint16>(1));
    header->percentile_75 =
        std::max<uint16>(FloatToUint16(global_header, sdata[3 * quarter_nr]),
                         header->percentile_25 + static_cast<uint16>(1));
    header->percentile_100 =
        std::max<uint16>(FloatToUint16(global_header, sdata[num_rows - 1]),
                         header->percentile_75 + static_cast<uint16>(1));

  } else {  // handle this pathological case.
    std::sort(sdata.begin(), sdata.end());
    // Note: we know num_rows is at least 1.
    header->percentile_0 = FloatToUint16(global_header, sdata[0]);
    if (num_rows > 1)
      header->percentile_25 = std::max<uint16>(
          FloatToUint16(global_header, sdata[1]), header->percentile_0 + 1);
    else
      header->percentile_25 = header->percentile_0 + 1;
    if (num_rows > 2)
      header->percentile_75 = std::max<uint16>(
          FloatToUint16(global_header, sdata[2]), header->percentile_25 + 1);
    else
      header->percentile_75 = header->percentile_25 + 1;
    if (num_rows > 3)
      header->percentile_100 = std::max<uint16>(
          FloatToUint16(global_header, sdata[3]), header->percentile_75 + 1);
    else
      header->percentile_100 = header->percentile_75 + 1;
  }
}

// static
inline unsigned char CompressedMatrix::FloatToChar(float p0, float p25,
                                                   float p75, float p100,
                                                   float value) {
  int ans;
  if (value < p25) {  // range [ p0, p25 ) covered by
    // characters 0 .. 64.  We round to the closest int.
    float f = (value - p0) / (p25 - p0);
    ans = static_cast<int>(f * 64 + 0.5);
    // Note: the checks on the next two lines
    // are necessary in pathological cases when all the elements in a row
    // are the same and the percentile_* values are separated by one.
    if (ans < 0) ans = 0;
    if (ans > 64) ans = 64;
  } else if (value < p75) {  // range [ p25, p75 )covered
    // by characters 64 .. 192.  We round to the closest int.
    float f = (value - p25) / (p75 - p25);
    ans = 64 + static_cast<int>(f * 128 + 0.5);
    if (ans < 64) ans = 64;
    if (ans > 192) ans = 192;
  } else {  // range [ p75, p100 ] covered by
    // characters 192 .. 255.  Note: this last range
    // has fewer characters than the left range, because
    // we go up to 255, not 256.
    float f = (value - p75) / (p100 - p75);
    ans = 192 + static_cast<int>(f * 63 + 0.5);
    if (ans < 192) ans = 192;
    if (ans > 255) ans = 255;
  }
  return static_cast<unsigned char>(ans);
}

// static
inline float CompressedMatrix::CharToFloat(float p0, float p25, float p75,
                                           float p100, unsigned char value) {
  if (value <= 64) {
    return p0 + (p25 - p0) * value * (1 / 64.0);
  } else if (value <= 192) {
    return p25 + (p75 - p25) * (value - 64) * (1 / 128.0);
  } else {
    return p75 + (p100 - p75) * (value - 192) * (1 / 63.0);
  }
}

template <typename Real>  // static
void CompressedMatrix::CompressColumn(const GlobalHeader &global_header,
                                      const Real *data, MatrixIndexT stride,
                                      int32 num_rows,
                                      CompressedMatrix::PerColHeader *header,
                                      unsigned char *byte_data) {
  ComputeColHeader(global_header, data, stride, num_rows, header);

  float p0 = Uint16ToFloat(global_header, header->percentile_0),
        p25 = Uint16ToFloat(global_header, header->percentile_25),
        p75 = Uint16ToFloat(global_header, header->percentile_75),
        p100 = Uint16ToFloat(global_header, header->percentile_100);

  for (int32 i = 0; i < num_rows; i++) {
    Real this_data = data[i * stride];
    byte_data[i] = FloatToChar(p0, p25, p75, p100, this_data);
  }
}

// static
void *CompressedMatrix::AllocateData(int32 num_bytes) {
  KALDI_ASSERT(num_bytes > 0);
  KALDI_COMPILE_TIME_ASSERT(sizeof(float) == 4);
  // round size up to nearest number of floats.
  return reinterpret_cast<void *>(new float[(num_bytes / 3) + 4]);
}

#define DEBUG_COMPRESSED_MATRIX 0  // Must be zero for Kaldi to work; use 1 only
                                   // for debugging.

void CompressedMatrix::Write(std::ostream &os, bool binary) const {
  if (binary) {  // Binary-mode write:
    WriteToken(os, binary, "CM");
    if (data_ != NULL) {
      GlobalHeader &h = *reinterpret_cast<GlobalHeader *>(data_);
      MatrixIndexT size = DataSize(h);  // total size of data in data_
      os.write(reinterpret_cast<const char *>(data_), size);
    } else {  // special case: where data_ == NULL, we treat it as an empty
      // matrix.
      GlobalHeader h;
      h.range = h.min_value = 0.0;
      h.num_rows = h.num_cols = 0;
      os.write(reinterpret_cast<const char *>(&h), sizeof(h));
    }
  } else {
// In text mode, just use the same format as a regular matrix.
// This is not compressed.
#if DEBUG_COMPRESSED_MATRIX == 0
    Matrix<BaseFloat> temp_mat(this->NumRows(), this->NumCols(), kUndefined);
    this->CopyToMat(&temp_mat);
    temp_mat.Write(os, binary);
#else
    // Text-mode writing out of the raw data.  Only really useful for debug, but
    // we'll implement it.
    if (data_ == NULL) {
      os << 0.0 << ' ' << 0.0 << ' ' << 0 << ' ' << 0 << '\n';
    } else {
      GlobalHeader &h = *reinterpret_cast<GlobalHeader *>(data_);
      KALDI_ASSERT(h.num_cols != 0);
      os << h.min_value << ' ' << h.range << ' ' << h.num_rows << ' '
         << h.num_cols << '\n';

      PerColHeader *per_col_header = reinterpret_cast<PerColHeader *>(&h + 1);
      unsigned char *c =
          reinterpret_cast<unsigned char *>(per_col_header + h.num_cols);

      for (int32 i = 0; i < h.num_cols; i++, per_col_header++) {
        os << per_col_header->percentile_0 << ' '
           << per_col_header->percentile_25 << ' '
           << per_col_header->percentile_75 << ' '
           << per_col_header->percentile_100 << '\n';
        for (int32 j = 0; j < h.num_rows; j++, c++)
          os << static_cast<int>(*c) << ' ';
        os << '\n';
      }
    }
#endif
  }
  if (os.fail()) KALDI_ERR << "Error writing compressed matrix to stream.";
}

void CompressedMatrix::Read(std::istream &is, bool binary) {
  if (data_ != NULL) {
    delete[](static_cast<float *>(data_));
    data_ = NULL;
  }
  if (binary) {  // Binary-mode read.
    // Caution: the following is not back compatible, if you were using
    // CompressedMatrix before, the old format will not be readable.

    int peekval = Peek(is, binary);
    if (peekval == 'C') {
      ExpectToken(is, binary, "CM");
      GlobalHeader h;
      is.read(reinterpret_cast<char *>(&h), sizeof(h));
      if (is.fail()) KALDI_ERR << "Failed to read header";
      if (h.num_cols == 0) {  // empty matrix.
        return;
      }
      int32 size = DataSize(h), remaining_size = size - sizeof(GlobalHeader);
      data_ = AllocateData(size);
      *(reinterpret_cast<GlobalHeader *>(data_)) = h;
      is.read(reinterpret_cast<char *>(data_) + sizeof(GlobalHeader),
              remaining_size);
    } else {
      // Assume that what we're reading is a regular Matrix.  This might be the
      // case if you changed your code, making a Matrix into a CompressedMatrix,
      // and you want back-compatibility for reading.
      Matrix<BaseFloat> M;
      M.Read(is, binary);  // This will crash if it was not a Matrix.  This
                           // might happen,
      // for instance, if the CompressedMatrix was written using the
      // older code where we didn't write the token "CM", we just
      // wrote the binary data directly.
      this->CopyFromMat(M);
    }
  } else {  // Text-mode read.
#if DEBUG_COMPRESSED_MATRIX == 0
    Matrix<BaseFloat> temp;
    temp.Read(is, binary);
    this->CopyFromMat(temp);
#else
    // The old reading code...
    GlobalHeader h;
    is >> h.min_value >> h.range >> h.num_rows >> h.num_cols;
    if (is.fail()) KALDI_ERR << "Failed to read header.";
    if (h.num_cols == 0) {  // Empty matrix; null data_ pointer.
      return;
    }
    int32 size = DataSize(h);
    data_ = AllocateData(size);
    *(reinterpret_cast<GlobalHeader *>(data_)) = h;

    PerColHeader *per_col_header = reinterpret_cast<PerColHeader *>(
        static_cast<char *>(data_) + sizeof(GlobalHeader));
    unsigned char *c =
        reinterpret_cast<unsigned char *>(per_col_header + h.num_cols);
    for (int32 i = 0; i < h.num_cols; i++, per_col_header++) {
      is >> per_col_header->percentile_0 >> per_col_header->percentile_25 >>
          per_col_header->percentile_75 >> per_col_header->percentile_100;
      for (int32 j = 0; j < h.num_rows; j++, c++) {
        int i;
        is >> i;
        KALDI_ASSERT(i >= 0 && i <= 255);
        *c = static_cast<unsigned char>(i);
      }
    }
#endif
  }
  if (is.fail()) KALDI_ERR << "Failed to read data.";
}

template <typename Real>
void CompressedMatrix::CopyToMat(MatrixBase<Real> *mat) const {
  if (data_ == NULL) {
    KALDI_ASSERT(mat->NumRows() == 0);
    KALDI_ASSERT(mat->NumCols() == 0);
  } else {
    GlobalHeader *h = reinterpret_cast<GlobalHeader *>(data_);
    PerColHeader *per_col_header = reinterpret_cast<PerColHeader *>(h + 1);
    unsigned char *byte_data =
        reinterpret_cast<unsigned char *>(per_col_header + h->num_cols);
    int32 num_cols = h->num_cols, num_rows = h->num_rows;
    KALDI_ASSERT(mat->NumRows() == num_rows);
    KALDI_ASSERT(mat->NumCols() == num_cols);
    for (int32 i = 0; i < num_cols; i++, per_col_header++) {
      float p0 = Uint16ToFloat(*h, per_col_header->percentile_0),
            p25 = Uint16ToFloat(*h, per_col_header->percentile_25),
            p75 = Uint16ToFloat(*h, per_col_header->percentile_75),
            p100 = Uint16ToFloat(*h, per_col_header->percentile_100);
      for (int32 j = 0; j < num_rows; j++, byte_data++) {
        float f = CharToFloat(p0, p25, p75, p100, *byte_data);
        (*mat)(j, i) = f;
      }
    }
  }
}

// Instantiate the template for float and double.
template void CompressedMatrix::CopyToMat(MatrixBase<float> *mat) const;
template void CompressedMatrix::CopyToMat(MatrixBase<double> *mat) const;

template <typename Real>
void CompressedMatrix::CopyRowToVec(MatrixIndexT row,
                                    VectorBase<Real> *v) const {
  KALDI_ASSERT(row < this->NumRows());
  KALDI_ASSERT(row >= 0);
  KALDI_ASSERT(v->Dim() == this->NumCols());

  GlobalHeader *h = reinterpret_cast<GlobalHeader *>(data_);
  PerColHeader *per_col_header = reinterpret_cast<PerColHeader *>(h + 1);
  unsigned char *byte_data =
      reinterpret_cast<unsigned char *>(per_col_header + h->num_cols);
  byte_data += row;  // point to first value we are interested in
  for (int32 i = 0; i < h->num_cols;
       i++, per_col_header++, byte_data += h->num_rows) {
    float p0 = Uint16ToFloat(*h, per_col_header->percentile_0),
          p25 = Uint16ToFloat(*h, per_col_header->percentile_25),
          p75 = Uint16ToFloat(*h, per_col_header->percentile_75),
          p100 = Uint16ToFloat(*h, per_col_header->percentile_100);
    float f = CharToFloat(p0, p25, p75, p100, *byte_data);
    (*v)(i) = f;
  }
}
template <typename Real>
void CompressedMatrix::CopyColToVec(MatrixIndexT col,
                                    VectorBase<Real> *v) const {
  KALDI_ASSERT(col < this->NumCols());
  KALDI_ASSERT(col >= 0);
  KALDI_ASSERT(v->Dim() == this->NumRows());

  GlobalHeader *h = reinterpret_cast<GlobalHeader *>(data_);
  PerColHeader *per_col_header = reinterpret_cast<PerColHeader *>(h + 1);
  unsigned char *byte_data =
      reinterpret_cast<unsigned char *>(per_col_header + h->num_cols);
  byte_data += col * h->num_rows;  // point to first value in the column we want
  per_col_header += col;
  float p0 = Uint16ToFloat(*h, per_col_header->percentile_0),
        p25 = Uint16ToFloat(*h, per_col_header->percentile_25),
        p75 = Uint16ToFloat(*h, per_col_header->percentile_75),
        p100 = Uint16ToFloat(*h, per_col_header->percentile_100);
  for (int32 i = 0; i < h->num_rows; i++, byte_data++) {
    float f = CharToFloat(p0, p25, p75, p100, *byte_data);
    (*v)(i) = f;
  }
}

// instantiate the templates.
template void CompressedMatrix::CopyColToVec(MatrixIndexT,
                                             VectorBase<double> *) const;
template void CompressedMatrix::CopyColToVec(MatrixIndexT,
                                             VectorBase<float> *) const;
template void CompressedMatrix::CopyRowToVec(MatrixIndexT,
                                             VectorBase<double> *) const;
template void CompressedMatrix::CopyRowToVec(MatrixIndexT,
                                             VectorBase<float> *) const;

template <typename Real>
void CompressedMatrix::CopyToMat(int32 row_offset, int32 column_offset,
                                 MatrixBase<Real> *dest) const {
  KALDI_PARANOID_ASSERT(row_offset < this->NumRows());
  KALDI_PARANOID_ASSERT(column_offset < this->NumCols());
  KALDI_PARANOID_ASSERT(row_offset >= 0);
  KALDI_PARANOID_ASSERT(column_offset >= 0);
  KALDI_ASSERT(row_offset + dest->NumRows() < this->NumRows());
  KALDI_ASSERT(column_offset + dest->NumCols() < this->NumCols());
  // everything is OK
  GlobalHeader *h = reinterpret_cast<GlobalHeader *>(data_);
  PerColHeader *per_col_header = reinterpret_cast<PerColHeader *>(h + 1);
  unsigned char *byte_data =
      reinterpret_cast<unsigned char *>(per_col_header + h->num_cols);
  int32 num_rows = h->num_rows;
  int32 tgt_cols = dest->NumCols(), tgt_rows = dest->NumRows();

  unsigned char *start_of_subcol = byte_data + row_offset;  // skip appropriate
  // number of columns
  start_of_subcol +=
      column_offset * num_rows;  // skip appropriate number of rows

  per_col_header += column_offset;  // skip the appropriate number of headers

  for (int32 i = 0; i < tgt_cols;
       i++, per_col_header++, start_of_subcol += num_rows) {
    byte_data = start_of_subcol;
    float p0 = Uint16ToFloat(*h, per_col_header->percentile_0),
          p25 = Uint16ToFloat(*h, per_col_header->percentile_25),
          p75 = Uint16ToFloat(*h, per_col_header->percentile_75),
          p100 = Uint16ToFloat(*h, per_col_header->percentile_100);
    for (int32 j = 0; j < tgt_rows; j++, byte_data++) {
      float f = CharToFloat(p0, p25, p75, p100, *byte_data);
      (*dest)(j, i) = f;
    }
  }
}

// instantiate the templates.
template void CompressedMatrix::CopyToMat(int32, int32,
                                          MatrixBase<float> *dest) const;
template void CompressedMatrix::CopyToMat(int32, int32,
                                          MatrixBase<double> *dest) const;

void CompressedMatrix::Destroy() {
  if (data_ != NULL) {
    delete[] static_cast<float *>(data_);
    data_ = NULL;
  }
}

CompressedMatrix::CompressedMatrix(const CompressedMatrix &mat) : data_(NULL) {
  *this = mat;  // use assignment operator.
}

CompressedMatrix &CompressedMatrix::operator=(const CompressedMatrix &mat) {
  Destroy();  // now this->data_ == NULL.
  if (mat.data_ != NULL) {
    MatrixIndexT data_size = DataSize(*static_cast<GlobalHeader *>(mat.data_));
    data_ = AllocateData(data_size);
    memcpy(static_cast<void *>(data_), static_cast<void *>(mat.data_),
           data_size);
  }
  return *this;
}

}  // namespace kaldi


text:
class Camera
{
  private:
    double height_angle;
    double aspect_ratio;
    Vector3 position;
    Vector3 direction;
    Vector3 up;
    Vector3 right;
  public:
    void rotate_forward(double angle);
    void rotate_up(double angle);
    void rotate_right(double angle);
    void move_forward(double distance);
    void move_up(double distance);
    void move_right(double distance);

    void draw(void);
};

redpajama_set_name: RedPajamaGithub


text:
import { Reactor, Store } from 'nuclear-js'
import expect from 'expect'
import React from 'react'
import ReactDOM from 'react-dom'
import { Provider, nuclearMixin } from '../src/index'
import setup from './setup'

function mountTestComponent(reactor, children) {
  class TestComponent extends React.Component {
    constructor(props, context) {
      super(props, context)
    }

    render() {
      return <Provider reactor={reactor}>{children}</Provider>
    }
  }
  ReactDOM.render(<TestComponent />, document.getElementById('test-root'))

}

describe('nuclearMixin', () => {
  setup()

  let reactor
  beforeEach(() => {
    reactor = new Reactor()
    reactor.registerStores({
      store1: Store({
        getInitialState: () => 1,
        initialize() {
          this.on('increment1', state => state + 1)
        },
      }),
      store2: Store({
        getInitialState: () => 2,
        initialize() {
          this.on('increment1', state => state + 1)
        },
      }),
    })
  })

  describe('when no getDataBindings function is passed', () => {
    it('it should provide reactor as context', () => {
      let TestComponent = React.createClass({
        mixins: [nuclearMixin],

        componentDidMount() {
          expect(this.context.reactor).toEqual(reactor)
        },

        render() {
          return

        },
      })

      mountTestComponent(reactor, <TestComponent />)
    })
  })

  describe('when a getDataBindings function is passed', () => {
    it('should provide initial values based on the state', () => {
      let TestComponent = React.createClass({
        mixins: [nuclearMixin],

        getDataBindings() {
          return {
            value1: ['store1'],
            value2: ['store2'],
          }
        },

        componentDidMount() {
          expect(this.state.value1).toEqual(1)
          expect(this.state.value2).toEqual(2)
        },

        render() {
          return

        },
      })

      mountTestComponent(reactor, <TestComponent />)
    })

    it('should subscribe to updates', () => {
      let renderedValues = []
      let TestComponent = React.createClass({
        mixins: [nuclearMixin],

        getDataBindings() {
          return {
            value1: ['store1'],
          }
        },

        render() {
          renderedValues.push(this.state.value1)
          return

        },
      })

      mountTestComponent(reactor, <TestComponent />)

      expect(renderedValues).toEqual([1])
      reactor.dispatch('increment1')
      expect(renderedValues).toEqual([1, 2])
      reactor.dispatch('otherAction')
      expect(renderedValues).toEqual([1, 2])
    })
  })
})


text:
package kawa.lang;
import gnu.expr.*;
import java.util.Vector;

/** Bindings from a syntax-case/syntax-rules pattern. */

public class PatternScope extends LetExp
{
  PatternScope previousSyntax;

  /** Currently visible macro pattern names.
   * For the i'th pattern variable, pattern_names.elementAt(i)
   * is the name of the variable,  */
  public Vector pattern_names;

  /** Nesting of currently visible macro pattern names.
   * For the i'th pattern variable,
   * (int) patternNesting.charAt(i)/2 is the nesting (in terms of
   * number of ellipsis that indicate the variable is repeated).
   * The low-order bit indicates that if matched value is the car
   * of the value saved in the vars array. */
  public StringBuffer patternNesting;

  // FIXME - move to Translator?
  public Declaration matchArray;

  public PatternScope ()
  {
  }

  public static PatternScope push (Translator tr)
  {
    PatternScope newScope = new PatternScope();
    // The actual declarations of newScope will be added later,
    // in SyntaxPattern#translate.
    PatternScope oldScope = tr.patternScope;
    newScope.previousSyntax = oldScope;
    tr.patternScope = newScope;
    if (oldScope == null)
      {
	newScope.pattern_names = new Vector();
	newScope.patternNesting = new StringBuffer();
      }
    else
      {
	newScope.pattern_names = (Vector) oldScope.pattern_names.clone();
	newScope.patternNesting
	  = new StringBuffer(oldScope.patternNesting.toString());
      }
    newScope.outer = tr.currentScope();
    return newScope;
  }

  public static void pop (Translator tr)
  {
    tr.patternScope = tr.patternScope.previousSyntax;
  }

  /*
  public void compile (Compilation comp, Target target)
  {
    throw new RuntimeException ("internal error - PatternScope.compile called");
  }
  */

}


text:
FreePBX dials and speaks aloud a custom 4 digit pin used in 3rd party applications or other.

I used this is for new registrations on one of my sites where users had to enter the 4 digit pin given to them. It has many use cases.


text:
#include "base/macros.h"
#include "jni.h"
#include "thread-inl.h"

namespace art {

extern "C" JNIEXPORT jint JNICALL Java_Main_getNativePriority(JNIEnv* env,
                                                              jclass clazz ATTRIBUTE_UNUSED) {
  return ThreadForEnv(env)->GetNativePriority();
}

extern "C" JNIEXPORT jboolean JNICALL Java_Main_supportsThreadPriorities(
    JNIEnv* env ATTRIBUTE_UNUSED,
    jclass clazz ATTRIBUTE_UNUSED) {
#if defined(__ANDROID__)
  return JNI_TRUE;
#else
  return JNI_FALSE;
#endif
}

}  // namespace art


text:
require "ubiquity/model"
require "ubiquity/model/auditable/version"
require "ubiquity/model/auditable/audit_entry"
require "ubiquity/model/auditable/property"

module Ubiquity::Model::Auditable

  extend ActiveSupport::Concern

  included do
    include Ubiquity::Model::Auditable::Property
  end

  class << self

    ##
    #
    ##
    def auditable_user
      @auditable_user
    end

    ##
    #
    ##
    def set_auditable_user(user)
      @auditable_user = user
    end

  end

end


text:
<?php

namespace ChinthakaGodawita;

/**
 * Custom middleware that executes on each request and verifies user
 * authentication. Inspired by Slim-Extras (which is now deprecated).
 *
 * @see https://github.com/codeguy/Slim-Extras
 */
class BasicAuthMiddleware extends \Slim\Middleware
{
    /**
     * @var string
     */
    protected $realm;

    /**
     * @var string
     */
    protected $username;

    /**
     * @var string
     */
    protected $password;

    /**
     * @var int
     */
    protected $timeout;

    /**
     * Construct middleware.
     *
     * @param string $username
     *   Username to accept.
     * @param string $password
     *   Password to accept.
     * @param string $realm
     *   HTTP authentication realm.
     */
    public function __construct($username, $password, $timeout = 3600, $realm = 'Secure API') {
        $this->username = $username;
        $this->password = $password;
        $this->realm = $realm;
        $this->timeout = $timeout;
    }

    /**
    * {@inheritdoc}
    */
    public function call()
    {
        // Get reference to application
        $app = $this->app;

        $log = $app->log;

        // Get request and response headers.
        $req = $app->request();
        $res = $app->response();

        if ($this->authenticateUser($req)) {
            // Start session if required.
            if (session_id() == '') {
                session_start();
            }

            $_SESSION['user'] = true;
            $_SESSION['start'] = time();

            // Let the client know what the session id is so that they can
            // reuse it later.
            $res->header('X-Session-Id', session_id());

            // Let Slim handle the rest.
            $this->next->call();
        }
        else {
            // Attempt to re-authenticate.
            $res->status(401);
            $res->header('WWW-Authenticate', "Basic realm=\"{$this->realm}\"");
            $res->header("Content-Type", "application/json");
            $res->body(json_encode(array(
                'status' => 401,
                'message' => "Invalid username or password.",
            )));
        }
    }

    /**
     * Attempt to authenticate a request.
     *
     * @param \Slim\Http\Request $req
     *   The current request object.
     *
     * @return boolean
     *   Whether or not the user is authenticated.
     */
    private function authenticateUser($req) {
        // Check if a session was sent by the client first.
        $session_header = $req->headers('X-Session-Id');
        if ($session_header) {
            // Load their previous session.
            session_id($session_header);
            session_start();

            // Make sure the user was previously authenticated and that the
            // session has not expired.
            if (isset($_SESSION['user']) && $_SESSION['user'] && isset($_SESSION['start']) && ($_SESSION['start'] + $this->timeout) > time()) {
                return true;
            }
            else {
                // Reset authentication status.
                $_SESSION['user'] = false;
            }
        }

        // Now attempt to authenticate via HTTP Basic.
        if (isset($_SERVER['HTTP_AUTHORIZATION'])) {
            // Allows us to use HTTP Basic easily under FastCGI.
            // Thanks to http://stackoverflow.com/a/7792912/356237.
            $auth_header = $_SERVER['HTTP_AUTHORIZATION'];
        }
        elseif (isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION'])) {
            // This header is sometimes used under FPM.
            $auth_header = $_SERVER['REDIRECT_HTTP_AUTHORIZATION'];
        }

        if (!empty($auth_header)) {
            list($auth_user, $auth_pass) =  explode(':', base64_decode(substr($auth_header, 6)));
        }
        else {
            // Assume this is mod_php.
            $auth_user = $req->headers('PHP_AUTH_USER');
            $auth_pass = $req->headers('PHP_AUTH_PW');
        }

        // Attempt to authenticate.
        if ($auth_user && $auth_pass && $auth_user === $this->username && $auth_pass === $this->password) {
            return true;
        }

        // If we've gotten this far, authentication was not successful.
        return false;
    }
}


text:
Title: Quick Introduction to Git/GitHub
Author: Enes Kemal Ergin
Date: 12/20/2016
---

# Quick Introduction to Git/GitHub

## Content
1. [Version Control System](#version-control-system)
  - [Local Version Control System](#local-version-control-system)
  - [Centralized Version Control System](#centralized-version-control-system)
  - [Distributed Version Control System](#distributed-version-control-system)
2. [Git](#git)
  - [Installing Git](#installing-git)
    - [Linux](#linux)
    - [Mac OSX](#mac-osx)
    - [Windows](#windows)
3. [GitHub](#github)
4. [Demonstration](#demonstration)
5. [Bibliography](#bibliography)

## Version Control System
A _version control system_ (sometimes just referred to as a VCS) is a system that tracks changes to files (or groups of files) over time.

It allows you to revert files back to a previous state, revert the entire project back to a previous state, compare changes over time, see who last modified something that might be causing a problem, who introduced an issue and when, and more.

Using a VCS also generally means that if you screw things up or lose files, you can easily recover._[1]_

There are 3 main types of VCSs developed over time; local, centralized, and distributed version control systems

### Local Version Control System
Copying an extra copy manually before making any changes is very common because of its simplicity. It's ancient way of version control by user itself, however it's incredibly error prone.

- Easy to forget where did you put the file
- Accidentally write in the wrong file
- Copy over files you don't mean to.

To overcome this problem developers came up with a solution called local version control systems, a long time ago. This system has a simple database which keeps all the changes to files under revision control._[1]_

![Local VCS](https://git-scm.com/book/en/v2/book/01-introduction/images/local.png)

### Centralized Version Control System
Local VCS solved a major issue but there is another issue people encounter is that they need to collaborate with developers on other systems. Central VCS is developed to solve this problem.

- Single server which contains all the versioned files
- It also containes number of clients that check out files from that central place.
- Administrator have fine-grained control over who can do what.

![Centralized VCS ](https://git-scm.com/book/en/v2/book/01-introduction/images/centralized.png)

However this setup also has some serious downsides.

- single point of failure that the centralized server represents
- If server goes down, nobody can save their work on server
- It may cause some serious difference errors on files
- If hard disk of central database becomes corrupted, you will lose absolutely everything._[1]_

### Distributed Version Control System

To solve problems with Centralized VCS Distributed VCSs developed such as Git. In these systems clients don't just check out the latest snapshot of the files: they fully mirror the repository.(Having the same copy) If any server dies, any of the client who has the copy can copy it back up the server to restore it._[1]_

![Distributed VCS ](https://git-scm.com/book/en/v2/book/01-introduction/images/distributed.png)

## Git
Git is a distributed version control system that we will use to integrate our local computer with GitHub.

![Git Version Control System ](http://www.chalkward.com/wp-content/uploads/2013/11/git-and-the-importnace-of-version-control.gif)

### Installing Git

#### Linux

``` Bash
sudo apt-get install git-all
```

#### Mac OSX
In Mac OSX the easiest way to install is installing Xcode Command Line Tools. If it is installed you can simply run ```git``` command in Terminal.

If you want to install it from the binary installer, install [here](https://git-scm.com/download/mac)

#### Windows
For windows go to [git-for-windows.github.io](https://git-for-windows.github.io/) website and download the installer. After the installation is done, you will have a Git BASH which gives you an ability to follow up the practices at the end of the article.

## GitHub

![Social Coding ](http://smashinghub.com/wp-content/uploads/2014/11/pros-and-cons-of-using-Github.png)

[GitHub](https://github.com) is a web platform, which hosts code repositories along with distributed version control system.

- You can have a repository public or private
- Unlimited private repository free for students
- Easy way to use version control system
- Having a backup of your code online
- Sharing and contributing others code
- Group work without limitations
- Nice way of publishing packages and libraries

You should create a GitHub account before completing this article with demonstration. It's easy and straightforward. You just need to go to the main page and sign-up there.

## Demonstration

Now we know about version control system, Git and GitHub, we can learn the essential commands for involving into this amazing world.

__Steps__

- To be able to interact with GitHub we should configure our Git accordingly.

> Careful: username and email should match with your github credentials.

```BASH
$ git config --global user.name "John Doe"
$ git config --global user.email johndoe@example.com
```

-  Open your newly created Github Account and click New Repository.

![creating new repo ](https://github.com/NAU-ACM/IntroductionToPython/blob/master/images/newRepo.png?raw=true)

- In the Create a new repository page, we will name our repository, write a description, decide if it will be public or private, and adding pre-defined files like ```.gitignore``` and ```license```.

> You can name it something like: "Learning Python", "Python Programming Tutorial" or similar. _You will use this repository to store our class materials assignments and small projects._

![create new repo ](https://github.com/NAU-ACM/IntroductionToPython/blob/master/images/createNewRepo.png?raw=true)

Now we have the online version of our repository, we will copy this repository to our local.

- Go to clone or download button and copy the link given

![Clone Link ](https://github.com/NAU-ACM/IntroductionToPython/blob/master/images/clone_download.png?raw=true)

- Open your terminal or Git BASH and go to desktop.

```BASH
$ cd Desktop
$ git clone <link_from_github_repo>
```
![Cloning the repo ](https://github.com/NAU-ACM/IntroductionToPython/blob/master/images/cloning.png?raw=true)

Now we have the clone of our online repository in our local. We can add, delete, modify files and we have to add changes to our local track.

- Create a python file called ```first_test.py``` add the following code into file and put the file in cloned folder in your local.

```Python
print("My name is ...")
print(2+8)
print("These are my first steps to Python")
```

Now you have added a file in your local but it is not tracked yet

- You can check the repository's status by ```git status``` while you are inside the repository.

![repo status ](https://github.com/NAU-ACM/IntroductionToPython/blob/master/images/git_status.png?raw=true)

- To track untracked files we use ```git add first_test.py``` command.

Now we are added untracked file to tracked file but before establishing a version we have to commit the changes. Commit is basically writing comments on the version and writing the version into database

- To commit ```git commit -am "Your comment"``` command is used

![add and commit changes ](https://github.com/NAU-ACM/IntroductionToPython/blob/master/images/git_commit.png?raw=true)

Now we added our second version which is commented with ```"Your comment"``` the changes are tracked, but only in local. If you want to send the changes you did in local to online version, and you should want :), we will use the following

- Push command is used for sending changes from local to online ``` git push origin master```

- If you have changed something in the online or your collaborator changed stuff in the repository. You get the changes with ```git pull origin master``` command for your local copy.

---
## Bibliography

- [1: Getting Started About Version Control ](https://git-scm.com/book/en/v2/Getting-Started-About-Version-Control)
- [2: Git Installation](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)


text:
Home assignment for the "OS" course in SPb AU (bachelor's degree, term 3).

Assignments are available here
as well as initial code.


text:
static int dateRecognitionAttemptsCount = 0;

bool IRecognitionCore::GetInstance(shared_ptr<IRecognitionCore> &recognitionCore,
                                   const shared_ptr<IRecognitionCoreDelegate>& recognitionDelegate,
                                   const shared_ptr<ITorchDelegate>& torchDelegate)
{
    recognitionCore = make_shared<CRecognitionCore>(recognitionDelegate, torchDelegate);
    return recognitionCore != 0;
}

CRecognitionCore::CRecognitionCore(const shared_ptr<IRecognitionCoreDelegate>& delegate, const shared_ptr<ITorchDelegate>& torchDelegate) : _delegate(delegate), _orientation(PayCardsRecognizerOrientationPortrait), _mode(PayCardsRecognizerModeNone), _deployed(false)
{
    _isIdle.store(false);
    _isBusy.store(false);

	_weak_delegate = delegate;

    IServiceContainerFactory::CreateServiceContainer(_serviceContainerPtr);

    _serviceContainerPtr->Initialize();
    _frameStorage = _serviceContainerPtr->resolve<IFrameStorage>();
    _edgesDetector = _serviceContainerPtr->resolve<IEdgesDetector>();
    _recognitionResult = _serviceContainerPtr->resolve<IRecognitionResult>();
    _torchManager = _serviceContainerPtr->resolve<ITorchManager>();

    if(auto torchManager = _torchManager.lock()) {
        torchManager->SetDelegate(torchDelegate);
    }
}

CRecognitionCore::~CRecognitionCore()
{
	Finish();
    _isIdle.store(false);
    _edges.clear();
    _currentFrame.release();
}

void CRecognitionCore::SetRecognitionMode(PayCardsRecognizerMode flag)
{
    _mode = flag;

    if (_mode&PayCardsRecognizerModeNumber) {
        _numberRecognizer = _serviceContainerPtr->resolve<INumberRecognizer>();
        if(auto numberRecognizer = _numberRecognizer.lock()) {
            numberRecognizer->SetRecognitionMode(flag);
        }
    }
    if (_mode&PayCardsRecognizerModeDate) {
        _dateRecognizer = _serviceContainerPtr->resolve<IDateRecognizer>();
        if(auto dateRecognizer = _dateRecognizer.lock()) {
            dateRecognizer->SetRecognitionMode(flag);
        }
    }
    if (_mode&PayCardsRecognizerModeName) {
        _nameRecognizer = _serviceContainerPtr->resolve<INameRecognizer>();
        if(auto nameRecognizer = _nameRecognizer.lock()) {
            nameRecognizer->SetRecognitionMode(flag);
        }
    }
}

void CRecognitionCore::Deploy()
{
    if (_mode == PayCardsRecognizerModeNone) return;

    if (auto numberRecognizer = _numberRecognizer.lock()) {
		if(!_weak_delegate.expired()){
			numberRecognizer->SetDelegate(_weak_delegate.lock());
		}
        if(!numberRecognizer->Deploy()) return;
    }

    if (auto dateRecognizer = _dateRecognizer.lock()) {
		if(!_weak_delegate.expired()){
			dateRecognizer->SetDelegate(_weak_delegate.lock());
		}
        if(!dateRecognizer->Deploy()) return;
    }

    if (auto nameRecognizer = _nameRecognizer.lock()) {
		if(!_weak_delegate.expired()){
			nameRecognizer->SetDelegate(_weak_delegate.lock());
		}
        if(!nameRecognizer->Deploy()) return;
    }

    _deployed = true;
}

void CRecognitionCore::SetOrientation(PayCardsRecognizerOrientation orientation)
{
    _orientation = orientation;
}

cv::Rect CRecognitionCore::CalcWorkingArea(cv::Size frameSize, int captureAreaWidth)
{
    if(auto edgesDetector = _edgesDetector.lock()) {
        return edgesDetector->CalcWorkingArea(frameSize, captureAreaWidth, _orientation);
    }

    return Rect(0,0,0,0);
}

void CRecognitionCore::SetIdle(bool isIdle)
{
    if (!isIdle) {
        if(auto recognitionResult = _recognitionResult.lock()) {
            recognitionResult->Reset();
        }
    }

    _isIdle.store(isIdle);
}

bool CRecognitionCore::IsIdle() const
{
    return _isIdle.load();
}

void CRecognitionCore::ResetResult()
{
    if(auto recognitionResult = _recognitionResult.lock()) {
        recognitionResult->Reset();
    }
}

void CRecognitionCore::SetPathNumberRecognitionModel(const string& path)
{
    if (auto numberRecognizer = _numberRecognizer.lock()) {
        numberRecognizer->SetPathNumberRecognitionModel(path);
    }
}

void CRecognitionCore::SetPathNumberRecognitionStruct(const string& path)
{
    if (auto numberRecognizer = _numberRecognizer.lock()) {
        numberRecognizer->SetPathNumberRecognitionStruct(path);
    }
}

void CRecognitionCore::SetPathNumberLocalizationXModel(const string& path)
{
    if (auto numberRecognizer = _numberRecognizer.lock()) {
        numberRecognizer->SetPathNumberLocalizationXModel(path);
    }
}

void CRecognitionCore::SetPathNumberLocalizationXStruct(const string& path)
{
    if (auto numberRecognizer = _numberRecognizer.lock()) {
        numberRecognizer->SetPathNumberLocalizationXStruct(path);
    }
}

void CRecognitionCore::SetPathNumberLocalizationYModel(const string& path)
{
    if (auto numberRecognizer = _numberRecognizer.lock()) {
        numberRecognizer->SetPathNumberLocalizationYModel(path);
    }
}

void CRecognitionCore::SetPathNumberLocalizationYStruct(const string& path)
{
    if (auto numberRecognizer = _numberRecognizer.lock()) {
        numberRecognizer->SetPathNumberLocalizationYStruct(path);
    }
}

void CRecognitionCore::SetPathDateRecognitionModel(const string& path)
{
    if (auto dateRecognizer = _dateRecognizer.lock()) {
        dateRecognizer->SetPathDateRecognitionModel(path);
    }
}

void CRecognitionCore::SetPathDateRecognitionStruct(const string& path)
{
    if (auto dateRecognizer = _dateRecognizer.lock()) {
        dateRecognizer->SetPathDateRecognitionStruct(path);
    }
}

void CRecognitionCore::SetPathDateLocalization0Model(const string& path)
{
    if (auto dateRecognizer = _dateRecognizer.lock()) {
        dateRecognizer->SetPathDateLocalization0Model(path);
    }
}

void CRecognitionCore::SetPathDateLocalization0Struct(const string& path)
{
    if (auto dateRecognizer = _dateRecognizer.lock()) {
        dateRecognizer->SetPathDateLocalization0Struct(path);
    }
}

void CRecognitionCore::SetPathDateLocalization1Model(const string& path)
{
    if (auto dateRecognizer = _dateRecognizer.lock()) {
        dateRecognizer->SetPathDateLocalization1Model(path);
    }
}

void CRecognitionCore::SetPathDateLocalization1Struct(const string& path)
{
    if (auto dateRecognizer = _dateRecognizer.lock()) {
        dateRecognizer->SetPathDateLocalization1Struct(path);
    }
}

void CRecognitionCore::SetPathDateLocalizationViola(const string& path)
{
    if (auto dateRecognizer = _dateRecognizer.lock()) {
        dateRecognizer->SetPathDateLocalizationViola(path);
    }
}

void CRecognitionCore::SetPathNameYLocalizationViola(const string& path)
{
    if (auto nameRecognizer = _nameRecognizer.lock()) {
        nameRecognizer->SetPathNameYLocalizationViola(path);
    }
}

void CRecognitionCore::SetPathNameLocalizationXModel(const string& path)
{
    if (auto nameRecognizer = _nameRecognizer.lock()) {
        nameRecognizer->SetPathNameLocalizationXModel(path);
    }
}

void CRecognitionCore::SetPathNameLocalizationXStruct(const string& path)
{
    if (auto nameRecognizer = _nameRecognizer.lock()) {
        nameRecognizer->SetPathNameLocalizationXStruct(path);
    }
}

void CRecognitionCore::SetPathNameSpaceCharModel(const string& path)
{
    if (auto nameRecognizer = _nameRecognizer.lock()) {
        nameRecognizer->SetPathNameSpaceCharModel(path);
    }
}

void CRecognitionCore::SetPathNameSpaceCharStruct(const string& path)
{
    if (auto nameRecognizer = _nameRecognizer.lock()) {
        nameRecognizer->SetPathNameSpaceCharStruct(path);
    }
}

void CRecognitionCore::SetPathNameListTxt(const string& path)
{
    if (auto nameRecognizer = _nameRecognizer.lock()) {
        nameRecognizer->SetPathNameListTxt(path);
    }
}

void CRecognitionCore::ProcessFrame(DetectedLineFlags& edgeFlags, void* bufferY,
                                    void* bufferUV, size_t bufferSizeY, size_t bufferSizeUV)
{
    if (!IsIdle() && _deployed) {

        Mat frameMatY = cv::Mat(1280, 720, CV_8UC1, bufferY); //put buffer in open cv, no memory copied

        if(auto edgesDetector = _edgesDetector.lock()) {
            if(auto recognitionResult = _recognitionResult.lock()) {
                if(auto frameStorage = _frameStorage.lock()) {
                    edgeFlags = edgesDetector->DetectEdges(frameMatY, _edges, _currentFrame);
                    if (edgeFlags&DetectedLineTopFlag &&  edgeFlags&DetectedLineBottomFlag
                        && edgeFlags&DetectedLineLeftFlag && edgeFlags&DetectedLineRightFlag) {
                        if (!_isBusy.load()) {
                            _isBusy.store(true);

                            _bufferSizeY = bufferSizeY;
                            if (!(recognitionResult->GetRecognitionStatus() & RecognitionStatusNumber)) {
                                frameStorage->SetRawY(frameMatY.data, bufferUV, _edges, _orientation);
                            }

                            std::thread thread;
                            thread = std::thread( [this] { this->ProcessFrameThreaded(); } );

                            sched_param sch;
                            int policy;
                            pthread_getschedparam(thread.native_handle(), &policy, &sch);
                            sch.sched_priority = 99;
                            pthread_setschedparam(thread.native_handle(), SCHED_FIFO, &sch);

                            thread.detach();
                        }
                    }
                }
            }
        }
    }
}

void CRecognitionCore::Finish()
{
	_delegate.reset();
	_weak_delegate.reset();
}

void CRecognitionCore::FinishRecognition()
{
    if(auto frameStorage = _frameStorage.lock()) {
        frameStorage->PopFrame();
        _isBusy.store(false);
    }
}

void CRecognitionCore::ProcessFrameThreaded()
{
    if(auto frameStorage = _frameStorage.lock()) {
        if(frameStorage->SetRawFrame(_currentFrame, _edges, _orientation)) {
			if(!_weak_delegate.expired()){
				Recognize();
			}
        }
        else {
            _isBusy.store(false);
        }
    }
}

void CRecognitionCore::Recognize()
{
    if (auto recognitionResult = _recognitionResult.lock()) {

        // number
        if (_mode&PayCardsRecognizerModeNumber &&
            !(recognitionResult->GetRecognitionStatus()&RecognitionStatusNumber)) {
            if (!RecognizeNumber()) {
                FinishRecognition();
                return;
            }
        }

        // date
        if (_mode&PayCardsRecognizerModeDate &&
            !(recognitionResult->GetRecognitionStatus() & RecognitionStatusDate) &&
            dateRecognitionAttemptsCount < kDateRecognitionAttempts && !_weak_delegate.expired()) {
            if (!RecognizeDate()) {
                FinishRecognition();
                return;
            }
        }

        if ((_mode&PayCardsRecognizerModeDate || _mode&PayCardsRecognizerModeNumber)) {
			if(!_weak_delegate.expired()) {
				_weak_delegate.lock()->RecognitionDidFinish(recognitionResult, (PayCardsRecognizerMode)(PayCardsRecognizerModeNumber|PayCardsRecognizerModeDate));
				if(_mode&PayCardsRecognizerModeGrabCardImage) {
					auto cardMat = CaptureView();
					if(!cardMat.empty()) {
						if(!_weak_delegate.expired()) {
							_weak_delegate.lock()->CardImageDidExtract(cardMat);
						}
					}
				}
			}
        }

        // name
        if (_mode&PayCardsRecognizerModeName &&
            !(recognitionResult->GetRecognitionStatus() & RecognitionStatusName) && !_weak_delegate.expired()) {
            RecognizeName();
        }
        if(!_weak_delegate.expired()) {
			_weak_delegate.lock()->RecognitionDidFinish(recognitionResult, PayCardsRecognizerModeName);
		} else {
			return;
		}

        _isIdle.store(true);
        FinishRecognition();
        dateRecognitionAttemptsCount = 0;
        SetTorchStatus(false);
    }
}

bool CRecognitionCore::RecognizeName()
{
    shared_ptr<INeuralNetworkResultList> result;

    if(auto frameStorage = _frameStorage.lock()) {
        if(auto nameRecognizer = _nameRecognizer.lock()) {
            if(auto recognitionResult = _recognitionResult.lock()) {
                Mat frame;
                frameStorage->GetCurrentFrame(frame);

                vector<cv::Mat> samples;
                std::string postprocessedName = "";
                result = nameRecognizer->Process(frame, samples, postprocessedName);

                if (result) {
                    recognitionResult->SetNameResult(result);
                    recognitionResult->SetPostprocessedName(postprocessedName);
                }
            }
        }
    }

    return result != nullptr;
}

bool CRecognitionCore::RecognizeNumber()
{
    cv::Rect boundingRect;
    shared_ptr<INeuralNetworkResultList> result;

    if(auto frameStorage = _frameStorage.lock()) {
        if(auto numberRecognizer = _numberRecognizer.lock()) {
            if(auto recognitionResult = _recognitionResult.lock()) {
                Mat frame;
                frameStorage->GetCurrentFrame(frame);
                result = numberRecognizer->Process(frame, boundingRect);
                if(result) {
                    recognitionResult->SetNumberResult(result);
                    recognitionResult->SetNumberRect(boundingRect);
                    recognitionResult->SetCardImage(frame.clone());
                }
                if(auto torchManager = _torchManager.lock()) {
                    torchManager->IncrementCounter();
                }
            }
        }
    }

    return result != nullptr;
}

bool CRecognitionCore::RecognizeDate()
{
    cv::Rect boundingRect;
    shared_ptr<INeuralNetworkResultList> result;
    if(auto frameStorage = _frameStorage.lock()) {
        if(auto dateRecognizer = _dateRecognizer.lock()) {
            if(auto recognitionResult = _recognitionResult.lock()) {
                Mat frame;
                frameStorage->GetCurrentFrame(frame);

                vector<cv::Mat> samples;
                result = dateRecognizer->Process(frame, samples, boundingRect);

                dateRecognitionAttemptsCount++;
                if (result) {
                    _isIdle.store(true);
                    recognitionResult->SetDateResult(result);
                    recognitionResult->SetDateRect(boundingRect);
                }
            }
        }
    }

    return result != nullptr;
}

void CRecognitionCore::SetTorchStatus(bool status)
{
    if(auto torchManager = _torchManager.lock()) {
        torchManager->SetStatus(status);
    }
}

cv::Mat CRecognitionCore::CaptureView()
{
    Mat normalizedMat;

    if(auto frameStorage = _frameStorage.lock()) {
        if(auto edgesDetector = _edgesDetector.lock()) {
            const size_t bufferLen = 720 * 1280 * 3 / 2 ;
            uint8_t *uPlane, *vPlane;
            void* imgBuffer = malloc(bufferLen);

            memcpy(imgBuffer, frameStorage->GetYMat(), _bufferSizeY);

            const size_t planeWidth = 360;
            const size_t planeHeight = 640;
            uint8_t *planeBaseAddress = (uint8_t *)frameStorage->GetUVMat();
            size_t planeSize = planeWidth * planeHeight;
#ifdef __APPLE__
            // Convert Y'UV420sp to Y'UV420p
            uPlane = (uint8_t *)malloc(planeSize);
            vPlane = (uint8_t *)malloc(planeSize);

            for (uint32_t i = 0; i < (planeWidth * planeHeight / 4); i++) {
                uint8_t *uvSrc = &planeBaseAddress[i * 8];
                uint8_t *uDest = &uPlane[i * 4];
                uint8_t *vDest = &vPlane[i * 4];
                uint8x8x2_t loaded = vld2_u8(uvSrc);
                vst1_u8(uDest, loaded.val[0]);
                vst1_u8(vDest, loaded.val[1]);
            }
#else
            // Convert YV12 to Y'UV420p
            uPlane = planeBaseAddress;
            vPlane = &planeBaseAddress[planeSize];
#endif

            memcpy(((unsigned char *)imgBuffer) + _bufferSizeY, uPlane, planeSize);
            memcpy(((unsigned char *)imgBuffer) + _bufferSizeY + planeSize, vPlane, planeSize);

            Mat yuv = Mat(1280 + 1280/2, 720, CV_8UC1, imgBuffer);

            Mat rgb;
            cvtColor(yuv, rgb, CV_YUV2RGB_I420);

            Mat refinedMat = rgb(edgesDetector->GetInternalWindowRect());

            vector<ParametricLine> lines = frameStorage->GetEdges();
            frameStorage->NormalizeMatrix(refinedMat, lines, normalizedMat);

#ifdef __APPLE__
            free(uPlane);
            free(vPlane);
#endif
            free(imgBuffer);

            PayCardsRecognizerOrientation orientation = frameStorage->GetYUVOrientation();

            if (orientation != PayCardsRecognizerOrientationPortraitUpsideDown &&
                orientation != PayCardsRecognizerOrientationPortrait) {

                CUtils::RotateMatrix90n(normalizedMat, normalizedMat, 90);
            }

            cv::resize(normalizedMat, normalizedMat, cv::Size(660,416));
        }
    }

    return normalizedMat;
}


text:
const contactform = document.getElementById('contactForm');
contactform.setAttribute('action', 'https://formspree.io/' + 'leo' + 'j' + 'reeves' + '+' + 'portfolio' + '@' + 'gmail' + '.' + 'com');

// Hide/show scroll to top button
const scrollTopBtn = document.querySelector('.scroll-top');
document.addEventListener('scroll', () => {
  if (window.scrollY > 100) {
    scrollTopBtn.classList.remove('hidden-xs');
  } else {
    scrollTopBtn.classList.add('hidden-xs');
  }
});


text:
#include "Path.h"

namespace NativeTask {

bool Path::IsAbsolute(const string & path) {
  if (path.length()>0 && path[0]=='/') {
    return true;
  }
  return false;
}

string Path::GetParent(const string & path) {
  size_t lastSlash = path.rfind('/');
  if (lastSlash == path.npos) {
    return ".";
  }
  if (lastSlash == 0 && path.length()==1) {
    return "";
  }
  if (lastSlash == 0) {
    return path;
  }
  return path.substr(0, lastSlash);
}

string Path::GetName(const string & path) {
  size_t lastSlash = path.rfind('/');
  if (lastSlash == path.npos) {
    return path;
  }
  return path.substr(lastSlash+1);
}

} // namespace NativeTask


text:
package org.wso2.carbon.caching.impl;

import javax.cache.Cache;
import java.io.Serializable;

/**
 * TODO: class description
 */
public class CacheEntry<K, V> implements Cache.Entry<K, V>, Serializable {

    private static final long serialVersionUID = 1996179870860085427L;

    private K key;
    private V value;
    private long lastAccessed;
    private long lastModified;

    public CacheEntry(K key, V value) {
        this.key = key;
        this.value = value;
        long now = System.currentTimeMillis();
        this.lastAccessed = now;
        this.lastModified = now;
    }

    public K getKey() {
        return key;
    }

    public void setValue(V value) {
        lastModified = System.currentTimeMillis();
        this.value = value;
    }

    public V getValue() {
        lastAccessed = System.currentTimeMillis();
        return value;
    }

    public long getLastAccessed() {
        return lastAccessed;
    }

    public long getLastModified() {
        return lastModified;
    }

    public void setLastAccessed(Long lastAccessed) {
        this.lastAccessed = lastAccessed;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        CacheEntry that = (CacheEntry) o;
        return key.equals(that.key) && value.equals(that.value);
    }

    @Override
    public int hashCode() {
        int result = key.hashCode();
        result = 31 * result + value.hashCode();
        return result;
    }
}


text:
title: "{{ replace .TranslationBaseName "-" " " | title }}"
date: {{ .Date }}
draft: false
author: "Victor Mendonça"
description: ""
tags: ""
---


text:
namespace Anycmd.Ac.ViewModels.PrivilegeViewModels
{
    using Engine.Ac.Privileges;
    using Engine.InOuts;
    using Engine.Messages;
    using System;

    /// <summary>
    /// 创建权限二元组时的输入或输出参数类型。
    /// </summary>
    public class PrivilegeCreateIo : EntityCreateInput, IPrivilegeCreateIo
    {
        public PrivilegeCreateIo()
        {
            HecpOntology = "Privilege";
            HecpVerb = "Create";
        }

        public string SubjectType { get; set; }

        public Guid SubjectInstanceId { get; set; }

        public string ObjectType { get; set; }

        public Guid ObjectInstanceId { get; set; }

        public string AcContent { get; set; }

        public string AcContentType { get; set; }

        public override IAnycmdCommand ToCommand(IAcSession acSession)
        {
            return new AddPrivilegeCommand(acSession, this);
        }
    }
}


text:
<?php

namespace PayPal\StructType;

use \WsdlToPhp\PackageBase\AbstractStructBase;

/**
 * This class stands for CreateBillingAgreementRequestType StructType
 * @subpackage Structs
 * @author WsdlToPhp <contact@wsdltophp.com>
 */
class CreateBillingAgreementRequestType extends AbstractRequestType
{
    /**
     * The Token
     * Meta information extracted from the WSDL
     * - base: xs:string
     * - maxOccurs: 1
     * - minOccurs: 1
     * @var string
     */
    public $Token;
    /**
     * Constructor method for CreateBillingAgreementRequestType
     * @uses CreateBillingAgreementRequestType::setToken()
     * @param string $token
     */
    public function __construct($token = null)
    {
        $this
            ->setToken($token);
    }
    /**
     * Get Token value
     * @return string
     */
    public function getToken()
    {
        return $this->Token;
    }
    /**
     * Set Token value
     * @param string $token
     * @return \PayPal\StructType\CreateBillingAgreementRequestType
     */
    public function setToken($token = null)
    {
        // validation for constraint: string
        if (!is_null($token) && !is_string($token)) {
            throw new \InvalidArgumentException(sprintf('Invalid value %s, please provide a string, %s given', var_export($token, true), gettype($token)), __LINE__);
        }
        $this->Token = $token;
        return $this;
    }
}


text:
#include <aws/ec2/model/DescribeSecurityGroupsRequest.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>

using namespace Aws::EC2::Model;
using namespace Aws::Utils;

DescribeSecurityGroupsRequest::DescribeSecurityGroupsRequest() :
    m_dryRun(false),
    m_dryRunHasBeenSet(false),
    m_groupNamesHasBeenSet(false),
    m_groupIdsHasBeenSet(false),
    m_filtersHasBeenSet(false)
{
}

Aws::String DescribeSecurityGroupsRequest::SerializePayload() const
{
  Aws::StringStream ss;
  ss << "Action=DescribeSecurityGroups&";
  if(m_dryRunHasBeenSet)
  {
    ss << "DryRun=" << std::boolalpha << m_dryRun << "&";
  }

  if(m_groupNamesHasBeenSet)
  {
    unsigned groupNamesCount = 1;
    for(auto& item : m_groupNames)
    {
      ss << "GroupName." << groupNamesCount << "="
          << StringUtils::URLEncode(item.c_str()) << "&";
      groupNamesCount++;
    }
  }

  if(m_groupIdsHasBeenSet)
  {
    unsigned groupIdsCount = 1;
    for(auto& item : m_groupIds)
    {
      ss << "GroupId." << groupIdsCount << "="
          << StringUtils::URLEncode(item.c_str()) << "&";
      groupIdsCount++;
    }
  }

  if(m_filtersHasBeenSet)
  {
    unsigned filtersCount = 1;
    for(auto& item : m_filters)
    {
      item.OutputToStream(ss, "Filter.", filtersCount, "");
      filtersCount++;
    }
  }

  ss << "Version=2016-11-15";
  return ss.str();
}

void  DescribeSecurityGroupsRequest::DumpBodyToUrl(Aws::Http::URI& uri ) const
{
  uri.SetQueryString(SerializePayload());
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>Welcome to Django Stories's documentation! — Django Stories 1.0.4 documentation</title>

    <link rel="stylesheet" href="_static/default.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />

    <link rel="top" title="Django Stories 1.0.4 documentation" href="#" />
    <link rel="next" title="Installation" href="install.html" />

Django Stories 1.0.4 documentation

Welcome to Django Stories's documentation!

Table of Contents

index

modules

next

Main Page

Installation

Upgrading to 1.0

Custom Author Model Guide

Settings

Pagination

Integration with Other Django Applications

Reference Manual

This Page

Show Source

        <form class="search" action="search.html" method="get">

			<input class="prettysearch" type="text" name="q" size="18" />

          <input type="submit" value="Search" class="searchbutton" />
          <input type="hidden" name="check_keywords" value="yes" />
          <input type="hidden" name="area" value="default" />
        </form>

        Enter search terms or a module, class or function name.

Welcome to Django Stories’s documentation!¶

This app is designed to be flexible to configure, but still simple to
the writers and editors.

Design Goals¶

Reduced dependencies: Checks for optional packages and only creates the
fields if they are there.

Rich content embedding from GUI: For embedded content, the markup language’s
GUI can do everything it needs.

Flexible dependencies: Can pick from several applications that provide
similar service, for example django-staff vs. User, massmedia vs. photologue

Features¶

Revision tracking: Keeps track of saved versions and allows a user to
revert to a previous version.

Related items: Can set any configured item to be related to the story.
These are for Photos, Videos, other stories, etc.

Quick Edit: Several fields can be changed in the list view including
Headline, Subheadline, Teaser, Kicker and Published Status. A form is used
and can be overridden by your project to include what ever fields you want.

Optional 404 supressing: Sometimes you may have to take down content.
You can now return a page with an explanation instead of returning a 404 error.

Contents:¶

Installation

Using PIP

Download

Install

Requirements

Run syncdb

Upgrading to 1.0

Ensureing story models are correctly configured

Ensuring functionality

Custom Author Model Guide

Settings

STATUS_CHOICES

DEFAULT_STATUS

PUBLISHED_STATUS

ORIGIN_CHOICES

DEFAULT_ORIGIN

INCLUDE_PRINT

RELATION_MODELS

PAGINATION

THROW_404

AUTHOR_MODEL

AUTHOR_MODEL_LIMIT_CHOICES

USE_REVERSION

ORDERING

WIDGET

WIDGET_ATTRS

ADMIN_EXTRAS

Pagination

PAGINATION settings

Using pagination in templates

Integration with Other Django Applications

Integrating with Django Categories

Integrating with Django Reversion

Integrating with Django TinyMCE

Reference Manual

Models

Views

Paginator

Template Tags

Urls

Helping Out¶

Source

Issues

Indices and tables¶

Index

Module Index

Search Page

      © Copyright 2012, The Calloway Project.
      Created using Sphinx 1.2b1.

		Welcome to Django Stories’s documentation!


text:
@protocol Layout <NSObject>
- (void)positionView:(UIView *)subview;
- (void)reset;
@end


text:
<?php
namespace com\selfcoders\phputils\placeholders\exception;

class UndefinedPlaceholderException extends PlaceholderException
{
    /**
     * @var string
     */
    private $placeholder;

    /**
     * @param string $placeholder
     */
    public function __construct($placeholder)
    {
        $this->placeholder = $placeholder;

        parent::__construct("Placeholder '" . $placeholder . "' is not defined");
    }

    /**
     * @return string
     */
    public function getPlaceholder()
    {
        return $this->placeholder;
    }
}


text: Asserts that the left-hand-side is **always** equal to the right-hand-side.


text:
var should = require('should');
var assert = require('assert');
var request = require('supertest');

var app = require("../server.js");

describe('Test cubieboard-monitor', function() {
    var server;
    var port;
    var url;

    // within before() you can run all the operations that are needed to setup your tests. In this case
    before(function(done) {
        server = app.boot();
        port = app.port;
        url = 'http://localhost:' + port;
        done();
    });

    // use describe to give a title to your test suite, in this case the tile is "Monitor"
    // and then specify a function in which we are going to declare all the tests
    // we want to run. Each test starts with the function it() and as a first argument
    // we have to provide a meaningful title for it, whereas as the second argument we
    // specify a function that takes a single parameter, "done", that we will use
    // to specify when our test is completed, and that's what makes easy
    // to perform async test!
    describe('Monitor:', function() {
        it('debería de devolver el hostname', function(done) {

            // once we have specified the info we want to send to the server via POST verb,
            // we need to actually perform the action on the resource, in this case we want to
            // POST on /api/profiles and we want to send some info
            // We do this using the request object, requiring supertest!
            request(url)
                .post('/SYS_hostname')
                // end handles the response
                .end(function(err, res) {
                    if (err) {
                        throw err;
                    }
                    // this is should.js syntax, very clear
                    //res.should.have.status(400);
                    res.body.should.not.equal(null);
                    done();
                });
        });
    });
    describe('Visión General', function() {
        describe('CPU', function(done) {

            it('debería de devolver la temperatura de la CPU', function(done) {
                // once we have specified the info we want to send to the server via POST verb,
                // we need to actually perform the action on the resource, in this case we want to
                // POST on /api/profiles and we want to send some info
                // We do this using the request object, requiring supertest!
                request(url)
                    .post('/CPU_Temp')
                    // end handles the response
                    .end(function(err, res) {
                        if (err) {
                            throw err;
                        }
                        // this is should.js syntax, very clear
                        //res.should.have.status(400);
                        res.body.should.not.equal(null);
                        done();
                    });

            });
            it('debería de devolver el uso de la CPU', function(done) {
                // once we have specified the info we want to send to the server via POST verb,
                // we need to actually perform the action on the resource, in this case we want to
                // POST on /api/profiles and we want to send some info
                // We do this using the request object, requiring supertest!
                request(url)
                    .post('/CPU_Uso')
                    // end handles the response
                    .end(function(err, res) {
                        if (err) {
                            throw err;
                        }
                        // this is should.js syntax, very clear
                        //res.should.have.status(400);
                        res.body.should.not.equal(null);
                        done();
                    });

            });
        });

        describe('HDD', function(done) {

            it('debería de devolver la temperatura del disco', function(done) {
                // once we have specified the info we want to send to the server via POST verb,
                // we need to actually perform the action on the resource, in this case we want to
                // POST on /api/profiles and we want to send some info
                // We do this using the request object, requiring supertest!
                request(url)
                    .post('/HDD_Temp')
                    // end handles the response
                    .end(function(err, res) {
                        if (err) {
                            throw err;
                        }
                        // this is should.js syntax, very clear
                        //res.should.have.status(400);
                        res.body.should.not.equal(null);
                        done();
                    });

            });
            it('debería de devolver el uso del disco', function(done) {
                // once we have specified the info we want to send to the server via POST verb,
                // we need to actually perform the action on the resource, in this case we want to
                // POST on /api/profiles and we want to send some info
                // We do this using the request object, requiring supertest!
                request(url)
                    .post('/HDD_Uso')
                    // end handles the response
                    .end(function(err, res) {
                        if (err) {
                            throw err;
                        }
                        // this is should.js syntax, very clear
                        //res.should.have.status(400);
                        res.body.should.not.equal(null);
                        done();
                    });

            });
        });

    });

    after(function() {
        app.shutdown();
    });

});


text:
- [A beginner's guide to Big O notation](https://rob-bell.net/2009/06/a-beginners-guide-to-big-o-notation/)
- [Big O Notation](http://www.growingwiththeweb.com/2012/11/big-o-notation.html)

## Search
- [Binary search](http://www.growingwiththeweb.com/2012/11/algorithm-binary-search.html)
- [Binary search tree](http://www.growingwiththeweb.com/2012/10/data-structures-binary-search-tree.html)

## Sorting
- [Sorting Algorithms](http://www.growingwiththeweb.com/2014/06/sorting-algorithms.html)
- [Bubble sort](http://www.growingwiththeweb.com/2014/02/bubble-sort.html)
- [Quicksort](http://www.growingwiththeweb.com/2012/12/algorithm-quicksort.html)
- [Heapsort](http://www.growingwiththeweb.com/2012/11/algorithm-heapsort.html)
- [Merge sort](http://www.growingwiththeweb.com/2012/11/algorithm-merge-sort.html)
- [Insertion sort](http://www.growingwiththeweb.com/2012/11/algorithm-insertion-sort.html)
- [Bucket sort](http://www.growingwiththeweb.com/2015/06/bucket-sort.html)
- [Comb sort](http://www.growingwiththeweb.com/2016/09/comb-sort.html)
- [Odd-even sort](http://www.growingwiththeweb.com/2016/10/odd-even-sort.html)
- [Selection sort](http://www.growingwiththeweb.com/2013/12/selection-sort.html)
- [Cocktail sort](http://www.growingwiththeweb.com/2016/04/cocktail-sort.html)

## Utilities
- [Data Structure Visualizations](https://www.cs.usfca.edu/~galles/visualization/Algorithms.html)
- [Sorting Visualiser](http://www.growingwiththeweb.com/projects/sorting-visualiser/)
- [VisuAlgo](https://visualgo.net)
- [Big-O Cheat Sheet](http://bigocheatsheet.com/)

## Interest
- [Check if a binary tree is balanced](http://www.growingwiththeweb.com/2015/11/check-if-a-binary-tree-is-balanced.html)


text:
package io.android_tech.myexample.AdapterView;

import android.Manifest;
import android.app.Activity;
import android.app.ListActivity;
import android.app.LoaderManager;
import android.content.CursorLoader;
import android.content.Loader;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.widget.GridView;
import android.widget.Toast;

import java.util.ArrayList;

import io.android_tech.myexample.R;

public class AdapterView_GridView_01_Activity extends Activity implements
        LoaderManager.LoaderCallbacks<Cursor> {
    private static final int PERMISSIONS_REQUEST_READ_CONTACTS = 100;
    private static final int viewList[] = {R.id.custom_list_title_main, R.id.custom_list_title_sub, R.id.custom_list_image};

    private static final String[] CONTACT_PROJECTION = new String[]{ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone.CONTACT_ID};
    AdapterView_ListView_CursorAdapter_02_Adapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_adapterview_gridview_01);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, PERMISSIONS_REQUEST_READ_CONTACTS);
        } else {
            startQuery();
        }
    }

    private void startQuery() {
        mAdapter = new AdapterView_ListView_CursorAdapter_02_Adapter(this,
                R.layout.activity_adapterview_gridview_01_row, null,
                new String[]{ContactsContract.Contacts.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone.CONTACT_ID},
                viewList, 0);
        GridView gridView = (GridView) findViewById(io.android_tech.myexample.R.id.gridView1);
        gridView.setAdapter(mAdapter);

        LoaderManager.LoaderCallbacks<Cursor> loaderCallbacks = this;
        LoaderManager loaderManager = getLoaderManager();
        loaderManager.initLoader(0, null, loaderCallbacks);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                           int[] grantResults) {
        if (requestCode == PERMISSIONS_REQUEST_READ_CONTACTS) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                startQuery();
            } else {
                Toast.makeText(this, "연락처에 대한 권한이 없어 실행할수 없습니다.", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        return new CursorLoader(this, ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                CONTACT_PROJECTION, null, null, null);
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        mAdapter.swapCursor(data);

    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
        mAdapter.swapCursor(null);

    }
}


text:
package com.parse.buzzbox;

import java.util.LinkedList;
import java.util.List;

import phone_numbers.To_international;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Window;
import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseQuery;
import com.parse.ParseUser;

public class DispatchActivity extends SherlockActivity{

	public DispatchActivity() {
	  }

	private Context con;
	//numbers and corresponding names validated by phone number library
	private LinkedList<String> valid_name = new LinkedList<String>();
	private LinkedList<String> valid_number = new LinkedList<String>();

	//names numbers object_ids saved in databases already
	private String names[], numbers[], object_ids[];

	// the current valid number that is currently getting checked through server
	private int index;

	private AlertDialog alertDialog;

	// used to check all contacts are checked or not
	private int flag;

	//shared preferences
	private SharedPreferences sp_parse;
	private SharedPreferences.Editor prefEdit;

	//no. of request failed
	private int no_of_errors = 0;
	  @Override
	  protected void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);

	    //set visible at starting if activity
	    requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
	    con = this;
	    sp_parse = getSharedPreferences("App_data", Activity.MODE_PRIVATE);
		prefEdit = sp_parse.edit();

		//retrieve all contacts already in db
		Contacts_database db = new Contacts_database(con);
		List<Contact> already_present = db.getAllContacts();

		names = new String[already_present.size()];
		numbers = new String[already_present.size()];
		object_ids = new String[already_present.size()];

		for(int i=0;i<already_present.size();i++)
		{
			names[i] = already_present.get(i).getName();
			numbers[i] = already_present.get(i).getPhoneNumber();
			object_ids[i] = already_present.get(i).getObjectID();
		}

	    if (ParseUser.getCurrentUser() != null) {

	    	String str = sp_parse.getString("first_time","shubham");
	    	//check if it is the first time launch of app
			  if(str.equals("shubham"))
			  {
				  //if it is first time check all contacts
				  setContentView(R.layout.looking_for_friends);
				  setSupportProgressBarIndeterminateVisibility(true);
				  chekcAllPhoneNumbers();

			  }
			  else
			  {
				// Start an intent for the logged in activity
			      startActivity(new Intent(this, MainActivity.class));
			      finish();
			  }

	    } else {
	      // Start and intent for the logged out activity
	      startActivity(new Intent(this, SignupOrLogin.class));
	      finish();
	    }

	  }
	//this method checks all phone numbers
		//and add new users who are registered on app to database
		public void chekcAllPhoneNumbers() {

				Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
				String[] projection    = new String[] {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
				                ContactsContract.CommonDataKinds.Phone.NUMBER};

				Cursor people = getContentResolver().query(uri, projection, null, null, null);

				int indexName = people.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
				int indexNumber = people.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);

				int total_size = people.getCount();
				if(total_size<=0)
				{
					//if the total contacts are 0
						Toast.makeText(con, "Friends checking complete.", Toast.LENGTH_SHORT).show();
						prefEdit.putString("first_time", "blah");
						prefEdit.commit();
						startActivity(new Intent(con, DispatchActivity.class));
					      finish();
				}
				else
				{

					people.moveToFirst();
					do {
						    String name   = people.getString(indexName);
						    String number = people.getString(indexNumber);
						    //to check phone number is valid or not
						    number = (new To_international(con)).change_to_international(number);
						    if(number!=null)
						    {
						    	valid_name.add(name);
						    	valid_number.add(number);
						    }
					} while (people.moveToNext());

					if(valid_name.size()<=0)
					{
						//if the total contacts are 0
						Toast.makeText(con, "Friends checking complete.", Toast.LENGTH_SHORT).show();
						prefEdit.putString("first_time", "blah");
						prefEdit.commit();
						startActivity(new Intent(con, DispatchActivity.class));
					      finish();
					}
					else
					{
						//check each contact
						if(valid_name.size()>10)
						{
							flag = valid_name.size();
							index = -1;
							for(int i=0;i<valid_name.size();i++)
							{
								parse_phone_number_query();
							}
						}
						else
						{
							flag = valid_name.size();
							index = -1;
							for(int i=0;i<valid_name.size();i++)
							{
								parse_phone_number_query();
							}
						}
					}

				}

		}

		//makes query for each phone number
		public void parse_phone_number_query()
		{
			ParseQuery<ParseUser> query = ParseUser.getQuery();
			index++;
			query.whereEqualTo("phone_number", valid_number.get(index));
			query.findInBackground(new FindCallback<ParseUser>() {
			@Override
			public void done(List<ParseUser> objects, ParseException e) {
				// TODO Auto-generated method stub

				flag--;
				if(flag==0)
				{
					//if all requests are complete
					Contacts_database db = new Contacts_database(con);
					List<Contact> already_present = db.getAllContacts();

					names = new String[already_present.size()];
					numbers = new String[already_present.size()];
					object_ids = new String[already_present.size()];

					for(int i=0;i<already_present.size();i++)
					{
						names[i] = already_present.get(i).getName();
						numbers[i] = already_present.get(i).getPhoneNumber();
						object_ids[i] = already_present.get(i).getObjectID();
					}
						//to save all friends in list in parse user
						for(int i=0;i<object_ids.length;i++)
						ParseUser.getCurrentUser().addUnique("friends", object_ids[i]);
						ParseUser.getCurrentUser().saveEventually();

					setSupportProgressBarIndeterminateVisibility(false);
					// if no of errors are less than 10 percent we can let user move in main activity
					if(no_of_errors<=valid_name.size()*10/100)
					{
						Toast.makeText(con, "Friends checking complete.", Toast.LENGTH_SHORT).show();
						prefEdit.putString("first_time", "blah");
						prefEdit.commit();
						startActivity(new Intent(con, DispatchActivity.class));
					      finish();
					}
					else
					{
						Toast.makeText(con, "Error while checking. Please check your internet connection.", Toast.LENGTH_SHORT).show();
						AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
								con);

								// create alert dialog
					  			alertDialog = alertDialogBuilder.setTitle("Error while checking.")
									.setMessage("Do you want to retry?")
									.setCancelable(false)
									.setPositiveButton("Ok",new DialogInterface.OnClickListener() {
										public void onClick(DialogInterface dialog,int id) {
											alertDialog.dismiss();
											startActivity(new Intent(con, DispatchActivity.class));
										      finish();
										}
									  })
									  .setNegativeButton("Cancel", new OnClickListener() {

										@Override
										public void onClick(DialogInterface dialog, int which) {
											// TODO Auto-generated method stub
											finish();
										}
									}).create();

								// show it or
								alertDialog.show();
					}
				}
				if (e == null) {
			        // The query was successful.
					//new user found

					if(objects.size()!=0)
					{
						//if there is user with same phone number
						if(objects.get(0).getList("friends")!=null)
						{
							ParseUser.getCurrentUser().addAllUnique("friends_of_friends", objects.get(0).getList("friends"));
							ParseUser.getCurrentUser().saveEventually();
						}
						int flag=0;
						//got the number using buzzbox
						String phone_number = objects.get(0).getString("phone_number");
						String object_id = objects.get(0).getObjectId();
						for(int temp = 0;temp <numbers.length;temp++)
						{
							if(numbers[temp].equals(phone_number))
								{
									flag=1;
									Log.d("User", "Already Present");
								}
						}
						if(flag==0)
						{
							Contacts_database db = new Contacts_database(con);
							int index = valid_number.indexOf(phone_number);
							Contact contact = new Contact(valid_number.get(index), valid_name.get(index),object_id);
							db.addContact(contact);
						}

					}
					else
					{
						Log.d("user not present","asdsa");
					}
			    } else {
			        Log.d("error", e.getMessage());
			        no_of_errors++;
			    }
			}
		  });
		}
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Meet Benjamin Tran</title>

    <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

    <link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Merriweather:400,300,300italic,400italic,700,700italic,900,900italic' rel='stylesheet' type='text/css'>

    <link href="vendor/magnific-popup/magnific-popup.css" rel="stylesheet">

    <link href="css/creative.min.css" rel="stylesheet">
    <link rel='icon' type='image/ico' href='favicon.ico' />

                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation Menu
                </button>
                Benjamin Bao Tran

                        About

                        Portfolio

                        Experience

                        Contact

Benjamin Bao Tran

Front-End Software Engineer

                Find Out More About Me!

ABOUT BENJAMIN

 I am a data-driven, product-focused software engineer specializing in JavaScript, HTML, CSS, and jQuery. I have experience developing with various modern JavaScript frameworks including React.js and Angular.js. Building scalable, highly-functional, and well designed full-stack applications is my passion.

Fun Fact: I am a huge coffee enthusiast and have an unwavering devotion to basketball and snowboarding.

                    See My Recent Projects

PORTFOLIO

                            FilmFinder

                            Regexcellence

                            EventSpot

FilmFinder

FilmFinder is an easy-to-use movie engine that allows users to find and research new movies, answering the life long question of what to watch next. Simply search for a title, review the plot summary, and star it! Your saved favorites are caches locally on your browser storage and will always be available for your viewing. FilmFinder allows you to easily keep track of your "to watch next" movies as well as the ones that you want to remember forever.

Repo:
                            Github

                        <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>

Regexcellence

Regexcellence is a community-driven application for learning and practicing regular expressions through tutorials and user-submitted challenges.

                        Our philosophy is simple: Learn to help others learn. Regex can be daunting and confusing but with our simple 12 steps tutorial, users can directly interact with our lessons and test their regex patterns every step of the way. Our pattern matching algorithm parses and dynamically checks user inputs as they type! Once users have completed the tutorial they are open to submit their own challenges, providing additional practice problems to the rest of the RegExers!

URL:
                            Regexcellence

Repo:
                            Github

                        <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>

EventSpot

Event spot is a snazzy event aggregator that plays music! Finding concerts to attend should be easy. At EventSpot we redefine the way users discover their next favorite artists. Our applications provides immediate access to artists' spotify playlists allowing users to preview the types of music before deciding to attend the event! It's simple! Amplify your night out!

URL:
                            EventSpotApp

Repo:
                            Github

                      <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>

EXPERIENCE

Aiva Health | Front-end Engineer

Spearhead development of AdminUI for organizing client infrastructure, managing staff, and configuring workflows

Constructed a Relay Modern based front end architecture using React.js and GraphQL queries to seamlessly render data

Build reusable Material-UI forms to and components to expedite the CRUD setup of Amazon Echo Dots and Google Home Minis

Work directly with backend leads to facilitate the development of internal tools for product integration and testing

Fishermen Labs | Front-end Engineer

Implemented front end solutions using HTML5, CSS3, and Javascript, especially in React.js and Redux

Managed technical relationships with clients to ensure understanding of code and features prior to onboarding and handover

Developed mobile responsive web pages and components addressing cross-browser compatibility and multi-platform use

Collaborated with design team to convert wireframes into fully functional views with polished UI/UX flows for various clients

Comprehended and assisted in development of back end features, specifically with the development of REST APIs

Hack Reactor | Software Engineering Resident

Mentored students on React, Angular, Backbone, Node, Express often assisting with code debugging and best practices

Conducted 3 technical interviews per week, assessing applicants on problem solving and javascript fundamentals

Presented to 40+ students on Model, View, Controller architecture, complexity analysis, and coding algorithms

Led weekly Javascript meetups covering computer science basics and intermediate javascript concepts

Connexity Inc. | Search Engine Marketing Analyst

Managed 11 Google, Bing, and Yahoo PLA/SEM campaigns and generated 3,000+ search keywords and listings

Optimized advertising spend to insure internet sales revenue growth of up to 23% MoM

Utilized SQL and Oracle Business Intelligence to compose ad hoc analyses for clients to determine resource allocations

ISA Inc. | International Student Teacher

Mentored 160 students in High School Empowerment Programs with forming post high school goals

Guided ESL students in preparing and executing English spoken speeches and presentations

Coordinated activities that promoted critical thinking and positive self-awareness

Morgan Stanley Wealth Management | Finance Program Coordinator

Led interns in financial training workshops on fundamental and technical analysis

Analyzed 10-Ks and 10-Qs, to create research reports that include SWOT diagrams, call options, and forecasted growth

Composed 2 diversified mock portfolios that resulted in 13% and 11% returns

Let's Get In Touch!

Let's grab coffee! Send me an email and I will get back to you as soon as possible.

benjamin.tran25@gmail.com

                      Copyright © Benjamin Bao Tran 2016


text:
#pragma once

#include <memory>
#include <unordered_map>

#include <Common.hpp>
#include <ShaderProgram.hpp>
#include <Camera.hpp>
#include <Renderer.hpp>
#include <Scene.hpp>

class Viewport {
 public:
  Viewport(float width, float height);

  void Init();
  void Resize(float width, float height);
  void Draw(float dt);

  void SetActiveRenderer(RendererType type);

 private:
  void InitBigScene();
  void InitSmallScene();

  float m_width;
  float m_height;

  std::shared_ptr<Scene> m_scene; //current scene

  std::shared_ptr<Scene> m_smallScene;
  std::shared_ptr<Scene> m_bigScene;

  std::shared_ptr<Camera> m_camera;

  std::shared_ptr<Renderer> m_renderer; //current renderer

  std::shared_ptr<DeferredRenderer> m_deferredRenderer;
  std::shared_ptr<ForwardRenderer> m_forwardRenderer;
};


text:
class RuleCacheClearEvent < ActiveRecord::Base
  belongs_to :event
end


text:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="10dp">

            <ImageView
                android:id="@+id/detail_note_date_default_image"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginEnd="12dp"
                android:layout_marginRight="12dp"
                android:contentDescription="@string/contentDescription"
                android:src="@drawable/ic_calendar_grey600_24dp" />

            <TextView
                android:id="@+id/detail_note_date_default"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignBottom="@+id/detail_note_date_default_image"
                android:layout_margin="2dp"
                android:layout_toEndOf="@+id/detail_note_date_default_image"
                android:layout_toRightOf="@+id/detail_note_date_default_image"
                android:text="@string/detail_incident_date_default"
                android:textColor="@color/cardview_dark_background"
                android:textSize="16sp"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/detail_note_date"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@id/detail_note_date_default"
                android:layout_margin="2dp"
                android:textColor="@color/colorPrimaryDark"
                android:textSize="14sp" />

            <ImageView
                android:id="@+id/detail_note_description_default_image"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@id/detail_note_date"
                android:layout_marginEnd="12dp"
                android:layout_marginRight="12dp"
                android:layout_marginTop="12dp"
                android:contentDescription="@string/contentDescription"
                android:src="@drawable/ic_clipboard_text_grey600_24dp" />

            <TextView
                android:id="@+id/detail_note_description_default"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignBottom="@+id/detail_note_description_default_image"
                android:layout_margin="2dp"
                android:layout_toEndOf="@+id/detail_note_description_default_image"
                android:layout_toRightOf="@+id/detail_note_description_default_image"
                android:text="@string/detail_incident_description_default"
                android:textColor="@color/cardview_dark_background"
                android:textSize="16sp"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/detail_note_description"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@id/detail_note_description_default"
                android:layout_margin="2dp"
                android:textColor="@color/colorPrimaryDark"
                android:textSize="14sp" />
        </RelativeLayout>
    </android.support.v7.widget.CardView>
</ScrollView>


text:
define("directives/stylesheet", ["app","services/urls"], function (app) {
    "use strict";
	return app.directive('stylesheet', ["urls",function (urls) {
		return {
			restrict: "E",
			template:'',
			replace: true,
			scope: {
				path: "@"
			},
			link: function (scope, elm, attrs) {
				var e=$('<link rel="stylesheet" type="text/css" href="'+urls.resourceUrl('stylesheets/'+scope.path)+'"/>');
				$(elm).replaceWith(e);
			}
		};
	}]);
});