text:
package org.apache.lucene.util;

import java.io.IOException;
import java.util.Arrays;

import org.apache.lucene.search.DocIdSet;
import org.apache.lucene.search.DocIdSetIterator;
import org.apache.lucene.util.packed.PackedInts;
import org.apache.lucene.util.packed.PackedLongValues;

/**
 * {@link DocIdSet} implementation based on pfor-delta encoding.
 *
This implementation is inspired from LinkedIn's Kamikaze
 * (http://data.linkedin.com/opensource/kamikaze) and Daniel Lemire's JavaFastPFOR
 * (https://github.com/lemire/JavaFastPFOR).

 *
On the contrary to the original PFOR paper, exceptions are encoded with
 * FOR instead of Simple16.

 */
public final class PForDeltaDocIdSet extends DocIdSet implements Accountable {

  private static final long BASE_RAM_BYTES_USED = RamUsageEstimator.shallowSizeOfInstance(PForDeltaDocIdSet.class);

  static final int BLOCK_SIZE = 128;
  static final int MAX_EXCEPTIONS = 24; // no more than 24 exceptions per block
  static final PackedInts.Decoder[] DECODERS = new PackedInts.Decoder[32];
  static final int[] ITERATIONS = new int[32];
  static final int[] BYTE_BLOCK_COUNTS = new int[32];
  static final int MAX_BYTE_BLOCK_COUNT;
  static final PackedLongValues SINGLE_ZERO = PackedLongValues.packedBuilder(PackedInts.COMPACT).add(0L).build();
  static final PForDeltaDocIdSet EMPTY = new PForDeltaDocIdSet(null, 0, Integer.MAX_VALUE, SINGLE_ZERO, SINGLE_ZERO);
  static final int LAST_BLOCK = 1 << 5; // flag to indicate the last block
  static final int HAS_EXCEPTIONS = 1 << 6;
  static final int UNARY = 1 << 7;
  static {
    int maxByteBLockCount = 0;
    for (int i = 1; i < ITERATIONS.length; ++i) {
      DECODERS[i] = PackedInts.getDecoder(PackedInts.Format.PACKED, PackedInts.VERSION_CURRENT, i);
      assert BLOCK_SIZE % DECODERS[i].byteValueCount() == 0;
      ITERATIONS[i] = BLOCK_SIZE / DECODERS[i].byteValueCount();
      BYTE_BLOCK_COUNTS[i] = ITERATIONS[i] * DECODERS[i].byteBlockCount();
      maxByteBLockCount = Math.max(maxByteBLockCount, DECODERS[i].byteBlockCount());
    }
    MAX_BYTE_BLOCK_COUNT = maxByteBLockCount;
  }

  /** A builder for {@link PForDeltaDocIdSet}. */
  public static class Builder {

    final GrowableByteArrayDataOutput data;
    final int[] buffer = new int[BLOCK_SIZE];
    final int[] exceptionIndices = new int[BLOCK_SIZE];
    final int[] exceptions = new int[BLOCK_SIZE];
    int bufferSize;
    int previousDoc;
    int cardinality;
    int indexInterval;
    int numBlocks;

    // temporary variables used when compressing blocks
    final int[] freqs = new int[32];
    int bitsPerValue;
    int numExceptions;
    int bitsPerException;

    /** Sole constructor. */
    public Builder() {
      data = new GrowableByteArrayDataOutput(128);
      bufferSize = 0;
      previousDoc = -1;
      indexInterval = 2;
      cardinality = 0;
      numBlocks = 0;
    }

    /** Set the index interval. Every indexInterval-th block will
     * be stored in the index. Set to {@link Integer#MAX_VALUE} to disable indexing. */
    public Builder setIndexInterval(int indexInterval) {
      if (indexInterval < 1) {
        throw new IllegalArgumentException("indexInterval must be >= 1");
      }
      this.indexInterval = indexInterval;
      return this;
    }

    /** Add a document to this builder. Documents must be added in order. */
    public Builder add(int doc) {
      if (doc <= previousDoc) {
        throw new IllegalArgumentException("Doc IDs must be provided in order, but previousDoc=" + previousDoc + " and doc=" + doc);
      }
      buffer[bufferSize++] = doc - previousDoc - 1;
      if (bufferSize == BLOCK_SIZE) {
        encodeBlock();
        bufferSize = 0;
      }
      previousDoc = doc;
      ++cardinality;
      return this;
    }

    /** Convenience method to add the content of a {@link DocIdSetIterator} to this builder. */
    public Builder add(DocIdSetIterator it) throws IOException {
      for (int doc = it.nextDoc(); doc != DocIdSetIterator.NO_MORE_DOCS; doc = it.nextDoc()) {
        add(doc);
      }
      return this;
    }

    void computeFreqs() {
      Arrays.fill(freqs, 0);
      for (int i = 0; i < bufferSize; ++i) {
        ++freqs[32 - Integer.numberOfLeadingZeros(buffer[i])];
      }
    }

    int pforBlockSize(int bitsPerValue, int numExceptions, int bitsPerException) {
      final PackedInts.Format format = PackedInts.Format.PACKED;
      long blockSize = 1 // header: number of bits per value
          + format.byteCount(PackedInts.VERSION_CURRENT, BLOCK_SIZE, bitsPerValue);
      if (numExceptions > 0) {
        blockSize += 2 // 2 additional bytes in case of exceptions: numExceptions and bitsPerException
            + numExceptions // indices of the exceptions
            + format.byteCount(PackedInts.VERSION_CURRENT, numExceptions, bitsPerException);
      }
      if (bufferSize < BLOCK_SIZE) {
        blockSize += 1; // length of the block
      }
      return (int) blockSize;
    }

    int unaryBlockSize() {
      int deltaSum = 0;
      for (int i = 0; i < BLOCK_SIZE; ++i) {
        deltaSum += 1 + buffer[i];
      }
      int blockSize = (deltaSum + 0x07) >>> 3; // round to the next byte
      ++blockSize; // header
      if (bufferSize < BLOCK_SIZE) {
        blockSize += 1; // length of the block
      }
      return blockSize;
    }

    int computeOptimalNumberOfBits() {
      computeFreqs();
      bitsPerValue = 31;
      numExceptions = 0;
      while (bitsPerValue > 0 && freqs[bitsPerValue] == 0) {
        --bitsPerValue;
      }
      final int actualBitsPerValue = bitsPerValue;
      int blockSize = pforBlockSize(bitsPerValue, numExceptions, bitsPerException);

      // Now try different values for bitsPerValue and pick the best one
      for (int bitsPerValue = this.bitsPerValue - 1, numExceptions = freqs[this.bitsPerValue]; bitsPerValue >= 0 && numExceptions <= MAX_EXCEPTIONS; numExceptions += freqs[bitsPerValue--]) {
        final int newBlockSize = pforBlockSize(bitsPerValue, numExceptions, actualBitsPerValue - bitsPerValue);
        if (newBlockSize < blockSize) {
          this.bitsPerValue = bitsPerValue;
          this.numExceptions = numExceptions;
          blockSize = newBlockSize;
        }
      }
      this.bitsPerException = actualBitsPerValue - bitsPerValue;
      assert bufferSize < BLOCK_SIZE || numExceptions < bufferSize;
      return blockSize;
    }

    void pforEncode() {
      if (numExceptions > 0) {
        final int mask = (1 << bitsPerValue) - 1;
        int ex = 0;
        for (int i = 0; i < bufferSize; ++i) {
          if (buffer[i] > mask) {
            exceptionIndices[ex] = i;
            exceptions[ex++] = buffer[i] >>> bitsPerValue;
            buffer[i] &= mask;
          }
        }
        assert ex == numExceptions;
        Arrays.fill(exceptions, numExceptions, BLOCK_SIZE, 0);
      }

      if (bitsPerValue > 0) {
        final PackedInts.Encoder encoder = PackedInts.getEncoder(PackedInts.Format.PACKED, PackedInts.VERSION_CURRENT, bitsPerValue);
        final int numIterations = ITERATIONS[bitsPerValue];
        encoder.encode(buffer, 0, data.bytes, data.length, numIterations);
        data.length += encoder.byteBlockCount() * numIterations;
      }

      if (numExceptions > 0) {
        assert bitsPerException > 0;
        data.writeByte((byte) numExceptions);
        data.writeByte((byte) bitsPerException);
        final PackedInts.Encoder encoder = PackedInts.getEncoder(PackedInts.Format.PACKED, PackedInts.VERSION_CURRENT, bitsPerException);
        final int numIterations = (numExceptions + encoder.byteValueCount() - 1) / encoder.byteValueCount();
        encoder.encode(exceptions, 0, data.bytes, data.length, numIterations);
        data.length += PackedInts.Format.PACKED.byteCount(PackedInts.VERSION_CURRENT, numExceptions, bitsPerException);
        for (int i = 0; i < numExceptions; ++i) {
          data.writeByte((byte) exceptionIndices[i]);
        }
      }
    }

    void unaryEncode() {
      int current = 0;
      for (int i = 0, doc = -1; i < BLOCK_SIZE; ++i) {
        doc += 1 + buffer[i];
        while (doc >= 8) {
          data.writeByte((byte) current);
          current = 0;
          doc -= 8;
        }
        current |= 1 << doc;
      }
      if (current != 0) {
        data.writeByte((byte) current);
      }
    }

    void encodeBlock() {
      final int originalLength = data.length;
      Arrays.fill(buffer, bufferSize, BLOCK_SIZE, 0);
      final int unaryBlockSize = unaryBlockSize();
      final int pforBlockSize = computeOptimalNumberOfBits();
      final int blockSize;
      if (pforBlockSize <= unaryBlockSize) {
        // use pfor
        blockSize = pforBlockSize;
        data.bytes = ArrayUtil.grow(data.bytes, data.length + blockSize + MAX_BYTE_BLOCK_COUNT);
        int token = bufferSize < BLOCK_SIZE ? LAST_BLOCK : 0;
        token |= bitsPerValue;
        if (numExceptions > 0) {
          token |= HAS_EXCEPTIONS;
        }
        data.writeByte((byte) token);
        pforEncode();
      } else {
        // use unary
        blockSize = unaryBlockSize;
        final int token = UNARY | (bufferSize < BLOCK_SIZE ? LAST_BLOCK : 0);
        data.writeByte((byte) token);
        unaryEncode();
      }

      if (bufferSize < BLOCK_SIZE) {
        data.writeByte((byte) bufferSize);
      }

      ++numBlocks;

      assert data.length - originalLength == blockSize : (data.length - originalLength) + " <> " + blockSize;
    }

    /** Build the {@link PForDeltaDocIdSet} instance. */
    public PForDeltaDocIdSet build() {
      assert bufferSize < BLOCK_SIZE;

      if (cardinality == 0) {
        assert previousDoc == -1;
        return EMPTY;
      }

      encodeBlock();
      final byte[] dataArr = Arrays.copyOf(data.bytes, data.length + MAX_BYTE_BLOCK_COUNT);

      final int indexSize = (numBlocks - 1) / indexInterval + 1;
      final PackedLongValues docIDs, offsets;
      if (indexSize <= 1) {
        docIDs = offsets = SINGLE_ZERO;
      } else {
        final int pageSize = 128;
        final PackedLongValues.Builder docIDsBuilder = PackedLongValues.monotonicBuilder(pageSize, PackedInts.COMPACT);
        final PackedLongValues.Builder offsetsBuilder = PackedLongValues.monotonicBuilder(pageSize, PackedInts.COMPACT);
        // Now build the index
        final Iterator it = new Iterator(dataArr, cardinality, Integer.MAX_VALUE, SINGLE_ZERO, SINGLE_ZERO);
        index:
        for (int k = 0; k < indexSize; ++k) {
          docIDsBuilder.add(it.docID() + 1);
          offsetsBuilder.add(it.offset);
          for (int i = 0; i < indexInterval; ++i) {
            it.skipBlock();
            if (it.docID() == DocIdSetIterator.NO_MORE_DOCS) {
              break index;
            }
          }
        }
        docIDs = docIDsBuilder.build();
        offsets = offsetsBuilder.build();
      }

      return new PForDeltaDocIdSet(dataArr, cardinality, indexInterval, docIDs, offsets);
    }

  }

  final byte[] data;
  final PackedLongValues docIDs, offsets; // for the index
  final int cardinality, indexInterval;

  PForDeltaDocIdSet(byte[] data, int cardinality, int indexInterval, PackedLongValues docIDs, PackedLongValues offsets) {
    this.data = data;
    this.cardinality = cardinality;
    this.indexInterval = indexInterval;
    this.docIDs = docIDs;
    this.offsets = offsets;
  }

  @Override
  public boolean isCacheable() {
    return true;
  }

  @Override
  public DocIdSetIterator iterator() {
    if (data == null) {
      return null;
    } else {
      return new Iterator(data, cardinality, indexInterval, docIDs, offsets);
    }
  }

  static class Iterator extends DocIdSetIterator {

    // index
    final int indexInterval;
    final PackedLongValues docIDs, offsets;

    final int cardinality;
    final byte[] data;
    int offset; // offset in data

    final int[] nextDocs;
    int i; // index in nextDeltas

    final int[] nextExceptions;

    int blockIdx;
    int docID;

    Iterator(byte[] data, int cardinality, int indexInterval, PackedLongValues docIDs, PackedLongValues offsets) {
      this.data = data;
      this.cardinality = cardinality;
      this.indexInterval = indexInterval;
      this.docIDs = docIDs;
      this.offsets = offsets;
      offset = 0;
      nextDocs = new int[BLOCK_SIZE];
      Arrays.fill(nextDocs, -1);
      i = BLOCK_SIZE;
      nextExceptions = new int[BLOCK_SIZE];
      blockIdx = -1;
      docID = -1;
    }

    @Override
    public int docID() {
      return docID;
    }

    void pforDecompress(byte token) {
      final int bitsPerValue = token & 0x1F;
      if (bitsPerValue == 0) {
        Arrays.fill(nextDocs, 0);
      } else {
        DECODERS[bitsPerValue].decode(data, offset, nextDocs, 0, ITERATIONS[bitsPerValue]);
        offset += BYTE_BLOCK_COUNTS[bitsPerValue];
      }
      if ((token & HAS_EXCEPTIONS) != 0) {
        // there are exceptions
        final int numExceptions = data[offset++];
        final int bitsPerException = data[offset++];
        final int numIterations = (numExceptions + DECODERS[bitsPerException].byteValueCount() - 1) / DECODERS[bitsPerException].byteValueCount();
        DECODERS[bitsPerException].decode(data, offset, nextExceptions, 0, numIterations);
        offset += PackedInts.Format.PACKED.byteCount(PackedInts.VERSION_CURRENT, numExceptions, bitsPerException);
        for (int i = 0; i < numExceptions; ++i) {
          nextDocs[data[offset++]] |= nextExceptions[i] << bitsPerValue;
        }
      }
      for (int previousDoc = docID, i = 0; i < BLOCK_SIZE; ++i) {
        final int doc = previousDoc + 1 + nextDocs[i];
        previousDoc = nextDocs[i] = doc;
      }
    }

    void unaryDecompress(byte token) {
      assert (token & HAS_EXCEPTIONS) == 0;
      int docID = this.docID;
      for (int i = 0; i < BLOCK_SIZE; ) {
        final byte b = data[offset++];
        for (int bitList = BitUtil.bitList(b); bitList != 0; ++i, bitList >>>= 4) {
          nextDocs[i] = docID + (bitList & 0x0F);
        }
        docID += 8;
      }
    }

    void decompressBlock() {
      final byte token = data[offset++];

      if ((token & UNARY) != 0) {
        unaryDecompress(token);
      } else {
        pforDecompress(token);
      }

      if ((token & LAST_BLOCK) != 0) {
        final int blockSize = data[offset++];
        Arrays.fill(nextDocs, blockSize, BLOCK_SIZE, NO_MORE_DOCS);
      }
      ++blockIdx;
    }

    void skipBlock() {
      assert i == BLOCK_SIZE;
      decompressBlock();
      docID = nextDocs[BLOCK_SIZE - 1];
    }

    @Override
    public int nextDoc() {
      if (i == BLOCK_SIZE) {
        decompressBlock();
        i = 0;
      }
      return docID = nextDocs[i++];
    }

    int forwardBinarySearch(int target) {
      // advance forward and double the window at each step
      final int indexSize = (int) docIDs.size();
      int lo = Math.max(blockIdx / indexInterval, 0), hi = lo + 1;
      assert blockIdx == -1 || docIDs.get(lo) <= docID;
      assert lo + 1 == docIDs.size() || docIDs.get(lo + 1) > docID;
      while (true) {
        if (hi >= indexSize) {
          hi = indexSize - 1;
          break;
        } else if (docIDs.get(hi) >= target) {
          break;
        }
        final int newLo = hi;
        hi += (hi - lo) << 1;
        lo = newLo;
      }

      // we found a window containing our target, let's binary search now
      while (lo <= hi) {
        final int mid = (lo + hi) >>> 1;
        final int midDocID = (int) docIDs.get(mid);
        if (midDocID <= target) {
          lo = mid + 1;
        } else {
          hi = mid - 1;
        }
      }
      assert docIDs.get(hi) <= target;
      assert hi + 1 == docIDs.size() || docIDs.get(hi + 1) > target;
      return hi;
    }

    @Override
    public int advance(int target) throws IOException {
      assert target > docID;
      if (nextDocs[BLOCK_SIZE - 1] < target) {
        // not in the next block, now use the index
        final int index = forwardBinarySearch(target);
        final int offset = (int) offsets.get(index);
        if (offset > this.offset) {
          this.offset = offset;
          docID = (int) docIDs.get(index) - 1;
          blockIdx = index * indexInterval - 1;
          while (true) {
            decompressBlock();
            if (nextDocs[BLOCK_SIZE - 1] >= target) {
              break;
            }
            docID = nextDocs[BLOCK_SIZE - 1];
          }
          i = 0;
        }
      }
      return slowAdvance(target);
    }

    @Override
    public long cost() {
      return cardinality;
    }

  }

  /** Return the number of documents in this {@link DocIdSet} in constant time. */
  public int cardinality() {
    return cardinality;
  }

  @Override
  public long ramBytesUsed() {
    if (this == EMPTY) {
      return 0L;
    }
    long ramBytesUsed = BASE_RAM_BYTES_USED + RamUsageEstimator.sizeOf(data);
    if (docIDs != SINGLE_ZERO) {
      ramBytesUsed += docIDs.ramBytesUsed();
    }
    if (offsets != SINGLE_ZERO) {
      ramBytesUsed += offsets.ramBytesUsed();
    }
    return ramBytesUsed;
  }

}


text:
// Generated by xsd compiler for android/java
// DO NOT CHANGE!
package com.ebay.trading.api;

import java.io.Serializable;
import com.leansoft.nano.annotation.*;
import java.util.List;

/**
 *
 * Contains information about a user as a buyer.
 *
 */
public class BuyerType implements Serializable {

    private static final long serialVersionUID = -1L;

	@Element(name = "ShippingAddress")
	@Order(value=0)
	public AddressType shippingAddress;

	@AnyElement
	@Order(value=1)
	public List<Object> any;

}

redpajama_set_name: RedPajamaGithub


text:
const emojioneOptions = {
  styles: {
    backgroundImage: 'url(images/emojione.sprites.png)'
  }
};

export default emojioneOptions;


text:
/**
 * @file return_val.h
 *
 * @brief Return values of APIs
 *
 * This header file has enumeration of return values.
 *
 * $Id: return_val.h 26685 2011-05-16 11:38:33Z sschneid $
 *
 * @author    Atmel Corporation: http://www.atmel.com
 * @author    Support: http://www.atmel.com/design-support/
 */
/*
 * Copyright (c) 2009-2014, Atmel Corporation All rights reserved.
 *
 *
 */

/* Prevent double inclusion */
 /**
 * Support and FAQ: visit Atmel Support
 */
#ifndef RETURN_VAL_H
#define RETURN_VAL_H

/* === Includes ============================================================ */

/* === Externals =========================================================== */

/* === Types =============================================================== */

/**
 * These are the return values of the PAL API.
 */
typedef enum
#if !defined(DOXYGEN)
retval_tag
#endif
{
    MAC_SUCCESS                 = 0x00, /**< Success defined by 802.15.4 */

#ifdef ENABLE_RTB
    RTB_SUCCESS                 = 0x10, /**< Success of ranging procedure */
    RTB_RANGING_IN_PROGRESS     = 0x11, /**< Ranging procedure is already in progress */
    RTB_REJECT                  = 0x12, /**< Ranging procedure is rejected */
    RTB_UNSUPPORTED_ATTRIBUTE   = 0x13, /**< Unsupported attribute for RTB */
    RTB_INVALID_PARAMETER       = 0x14, /**< Unsupported parameter for RTB */
    RTB_OUT_OF_BUFFERS          = 0x15, /**< No further buffers available for RTB ranging measurement */
    RTB_UNSUPPORTED_RANGING     = 0x16, /**< Ranging is currently not supported */
    RTB_UNSUPPORTED_METHOD      = 0x17, /**< Requested Ranging method is currently not supported at reflector */
    RTB_TIMEOUT                 = 0x18, /**< Timeout since requested Ranging response frame is not received */
#endif

    TAL_TRX_ASLEEP              = 0x81, /**< Transceiver is currently sleeping */
    TAL_TRX_AWAKE               = 0x82, /**< Transceiver is currently awake */
    FAILURE                     = 0x85, /**< General failure condition */
    TAL_BUSY                    = 0x86, /**< TAL busy condition */
    TAL_FRAME_PENDING           = 0x87, /**< Frame pending at TAL */
    PAL_TMR_ALREADY_RUNNING     = 0x88, /**< Timer is already running */
    PAL_TMR_NOT_RUNNING         = 0x89, /**< Timer is not running */
    PAL_TMR_INVALID_ID          = 0x8A, /**< Invalid timer ID*/
    PAL_TMR_INVALID_TIMEOUT     = 0x8B, /**< Requested Timeout is out of range or too short */
    QUEUE_FULL                  = 0x8C, /**< Requested queue is full */

    MAC_COUNTER_ERROR           = 0xDB, /**< Invalid Frame counter value defined by 802.15.4 */
    MAC_IMPROPER_KEY_TYPE       = 0xDC, /**< Unallowed key in received frame defined by 802.15.4 */
    MAC_IMPROPER_SECURITY_LEVEL = 0xDD, /**< Required security level not applied within received frame defined by 802.15.4 */
    MAC_UNSUPPORTED_LEGACY      = 0xDE, /**< Received frame was secured using 802.15.4-2003 security */
    MAC_UNSUPPORTED_SECURITY    = 0xDF, /**< Not supported applied security defined by 802.15.4 */
    MAC_BEACON_LOSS             = 0xE0, /**< Loss of beacons defined by 802.15.4 */
    MAC_CHANNEL_ACCESS_FAILURE  = 0xE1, /**< Channel access failure defined by 802.15.4 */
    MAC_DISABLE_TRX_FAILURE     = 0xE3, /**< Disabling of TRX failed defined by 802.15.4 */
    MAC_SECURITY_ERROR          = 0xE4, /**< Failed cryptographic processing of the received secured frame defined by 802.15.4 */
    MAC_FRAME_TOO_LONG          = 0xE5, /**< Current frame is too long defined by 802.15.4 */
    MAC_INVALID_GTS             = 0xE6, /**< Invalid GTS defined by 802.15.4 */
    MAC_INVALID_HANDLE          = 0xE7, /**< Invalid handle defined by 802.15.4 */
    MAC_INVALID_PARAMETER       = 0xE8, /**< Invalid Parameter defined by 802.15.4 */
    MAC_NO_ACK                  = 0xE9, /**< No ACK defined by 802.15.4 */
    MAC_NO_BEACON               = 0xEA, /**< No beacon defined by 802.15.4 */
    MAC_NO_DATA                 = 0xEB, /**< NO data defined by 802.15.4 */
    MAC_NO_SHORT_ADDRESS        = 0xEC, /**< No valid short address defined by 802.15.4 */
    MAC_OUT_OF_CAP              = 0xED, /**< Out of CA defined by 802.15.4-2003, deprecated in 802.15.4-2006 */
    MAC_PAN_ID_CONFLICT         = 0xEE, /**< PAN ID conflict defined by 802.15.4 */
    MAC_REALIGNMENT             = 0xEF, /**< Realignment defined by 802.15.4 */
    MAC_TRANSACTION_EXPIRED     = 0xF0, /**< Transaction expired defined by 802.15.4 */
    MAC_TRANSACTION_OVERFLOW    = 0xF1, /**< Transaction overflow defined by 802.15.4 */
    MAC_TX_ACTIVE               = 0xF2, /**< Tx active defined by 802.15.4 */
    MAC_UNAVAILABLE_KEY         = 0xF3, /**< Unavailable key or blacklisted device defined by 802.15.4 */
    MAC_UNSUPPORTED_ATTRIBUTE   = 0xF4, /**< Unsupported attribute defined by 802.15.4 */
    MAC_INVALID_ADDRESS         = 0xF5, /**< Invalid address defined by 802.15.4 */
    MAC_PAST_TIME               = 0xF7, /**< Receiver could not be enabled as defined by 802.15.4 */
    MAC_INVALID_INDEX           = 0xF9, /**< Invalid index in table of MAC PIB attribute defined by 802.15.4 */
    MAC_LIMIT_REACHED           = 0xFA, /**< Scan operation terminated prematurely defined by 802.15.4 */
    MAC_READ_ONLY               = 0xFB, /**< SET request issued for read only attribute defined by 802.15.4 */
    MAC_SCAN_IN_PROGRESS        = 0xFC  /**< Scan operation failed because of ongoing scan defined by 802.15.4 */
} SHORTENUM retval_t;

/* === Macros ============================================================== */

/* === Prototypes ========================================================== */
#ifdef __cplusplus
extern "C" {
#endif

#ifdef __cplusplus
} /* extern "C" */
#endif

#endif /* RETURN_VAL_H */
/* EOF */


text:
require 'dfp_api'

def update_custom_fields(dfp, custom_field_id)
  # Get the CustomFieldService.
  custom_field_service = dfp.service(:CustomFieldService, API_VERSION)

  # Create a statement to only select a single custom field.
  statement = dfp.new_statement_builder do |sb|
    sb.where = 'id = :custom_field_id'
    sb.with_bind_variable('custom_field_id', custom_field_id)
    sb.limit = 1
  end

  # Get custom fields by statement.
  response = custom_field_service.get_custom_fields_by_statement(
      statement.to_statement()
  )
  raise 'No custom fields found to update.' if response[:results].to_a.empty?
  custom_field = response[:results].first

  # Update custom field object.
  custom_field[:description] ||= ''
  custom_field[:description] += ' Updated.'

  # Update the custom field on the server.
  updated_custom_fields =
      custom_field_service.update_custom_fields([custom_field])

  if updated_custom_fields.to_a.size > 0
    updated_custom_fields.each do |custom_field|
      puts 'Custom field ID %d, name "%s", and description "%s" was updated.' %
          [custom_field[:id], custom_field[:name], custom_field[:description]]
    end
  else
    puts 'No custom fields were updated.'
  end
end

if __FILE__ == $0
  API_VERSION = :v201711

  # Get DfpApi instance and load configuration from ~/dfp_api.yml.
  dfp = DfpApi::Api.new

  # To enable logging of SOAP requests, set the log_level value to 'DEBUG' in
  # the configuration file or provide your own logger:
  # dfp.logger = Logger.new('dfp_xml.log')

  begin
    custom_field_id = 'INSERT_CUSTOM_FIELD_ID_HERE'.to_i
    update_custom_fields(dfp, custom_field_id)

  # HTTP errors.
  rescue AdsCommon::Errors::HttpError => e
    puts "HTTP Error: %s" % e

  # API errors.
  rescue DfpApi::Errors::ApiException => e
    puts "Message: %s" % e.message
    puts 'Errors:'
    e.errors.each_with_index do |error, index|
      puts "\tError [%d]:" % (index + 1)
      error.each do |field, value|
        puts "\t\t%s: %s" % [field, value]
      end
    end
  end
end


text:
<?php

App::uses('AppController', 'Controller');

class ProvidersController extends AppController {
	public function add() {
		if ($this->request->isPost()) {
			$this->Provider->create();
			if ($this->Provider->save($this->request->data)) {
				$this->Session->setFlash(__('fornecedor salvo com sucesso'));
				$this->redirect(array('controller' => 'years', 'action' => 'index'));
				return;
			} else {
				$this->Session->setFlash(__('houve um erro ao cadastrar um fornecedor'));
			}
		}
	}

}


text:
#include "watchman.h"
using watchman::CaseSensitivity;

class NameExpr : public QueryExpr {
  w_string name;
  std::unordered_set<w_string> set;
  CaseSensitivity caseSensitive;
  bool wholename;
  explicit NameExpr(
      std::unordered_set<w_string>&& set,
      CaseSensitivity caseSensitive,
      bool wholename)
      : set(std::move(set)), caseSensitive(caseSensitive), wholename(wholename) {}

 public:
  bool evaluate(struct w_query_ctx* ctx, const FileResult* file) override {
    if (!set.empty()) {
      bool matched;
      w_string str;

      if (wholename) {
        str = w_query_ctx_get_wholename(ctx);
        if (caseSensitive == CaseSensitivity::CaseInSensitive) {
          str = str.piece().asLowerCase();
        }
      } else {
        str = caseSensitive == CaseSensitivity::CaseInSensitive
                  ? file->baseName().asLowerCase()
                  : file->baseName().asWString();
      }

      matched = set.find(str) != set.end();

      return matched;
    }

    w_string_piece str;

    if (wholename) {
      str = w_query_ctx_get_wholename(ctx);
    } else {
      str = file->baseName();
    }

    if (caseSensitive == CaseSensitivity::CaseInSensitive) {
      return w_string_equal_caseless(str, name);
    }
    return str == name;
  }

  static std::unique_ptr<QueryExpr>
  parse(w_query*, const json_ref& term, CaseSensitivity caseSensitive) {
    const char *pattern = nullptr, *scope = "basename";
    const char *which =
        caseSensitive == CaseSensitivity::CaseInSensitive ? "iname" : "name";
    std::unordered_set<w_string> set;

    if (!json_is_array(term)) {
      throw QueryParseError("Expected array for '", which, "' term");
    }

    if (json_array_size(term) > 3) {
      throw QueryParseError(
          "Invalid number of arguments for '", which, "' term");
    }

    if (json_array_size(term) == 3) {
      const auto& jscope = term.at(2);
      if (!json_is_string(jscope)) {
        throw QueryParseError("Argument 3 to '", which, "' must be a string");
      }

      scope = json_string_value(jscope);

      if (strcmp(scope, "basename") && strcmp(scope, "wholename")) {
        throw QueryParseError(
            "Invalid scope '", scope, "' for ", which, " expression");
      }
    }

    const auto& name = term.at(1);

    if (json_is_array(name)) {
      uint32_t i;

      for (i = 0; i < json_array_size(name); i++) {
        if (!json_is_string(json_array_get(name, i))) {
          throw QueryParseError(
              "Argument 2 to '",
              which,
              "' must be either a string or an array of string");
        }
      }

      set.reserve(json_array_size(name));
      for (i = 0; i < json_array_size(name); i++) {
        w_string_t* element;
        const char* ele;
        const auto& jele = name.at(i);
        ele = json_string_value(jele);
        // We need to make a copy of the string since we do in-place separator
        // normalization on the paths.
        if (caseSensitive == CaseSensitivity::CaseInSensitive) {
          element =
              w_string_new_lower_typed(ele, json_to_w_string(jele).type());
        } else {
          element = w_string_new_typed(ele, json_to_w_string(jele).type());
        }

        w_string_in_place_normalize_separators(&element);

        set.insert(element);
        w_string_delref(element);
      }

    } else if (json_is_string(name)) {
      pattern = json_string_value(name);
    } else {
      throw QueryParseError(
          "Argument 2 to '",
          which,
          "' must be either a string or an array of string");
    }

    auto data = new NameExpr(std::move(set), caseSensitive,
                             !strcmp(scope, "wholename"));

    if (pattern) {
      // We need to make a copy of the string since we do in-place separator
      // normalization on the paths.
      w_string pat(pattern, json_to_w_string(name).type());
      data->name = w_string_normalize_separators(pat);
    }

    return std::unique_ptr<QueryExpr>(data);
  }

  static std::unique_ptr<QueryExpr> parseName(
      w_query* query,
      const json_ref& term) {
    return parse(query, term, query->case_sensitive);
  }
  static std::unique_ptr<QueryExpr> parseIName(
      w_query* query,
      const json_ref& term) {
    return parse(query, term, CaseSensitivity::CaseInSensitive);
  }
};

W_TERM_PARSER("name", NameExpr::parseName)
W_TERM_PARSER("iname", NameExpr::parseIName)

/* vim:ts=2:sw=2:et:
 */


text:
ROOTDIR=$(dir $(abspath $(lastword $(MAKEFILE_LIST))))

# Used to populate version variable in main package.
VERSION ?= $(shell git describe --match 'v[0-9]*' --dirty='.m' --always)
REVISION ?= $(shell git rev-parse HEAD)$(shell if ! git diff --no-ext-diff --quiet --exit-code; then echo .m; fi)

PKG=github.com/distribution/distribution/v3

# Project packages.
PACKAGES=$(shell go list -tags "${BUILDTAGS}" ./... | grep -v /vendor/)
INTEGRATION_PACKAGE=${PKG}
COVERAGE_PACKAGES=$(filter-out ${PKG}/registry/storage/driver/%,${PACKAGES})

# Project binaries.
COMMANDS=registry digest registry-api-descriptor-template

# Allow turning off function inlining and variable registerization
ifeq (${DISABLE_OPTIMIZATION},true)
	GO_GCFLAGS=-gcflags "-N -l"
	VERSION:="$(VERSION)-noopt"
endif

WHALE = "+"

# Go files
#
TESTFLAGS_RACE=
GOFILES=$(shell find . -type f -name '*.go')
GO_TAGS=$(if $(BUILDTAGS),-tags "$(BUILDTAGS)",)
GO_LDFLAGS=-ldflags '-s -w -X $(PKG)/version.Version=$(VERSION) -X $(PKG)/version.Revision=$(REVISION) -X $(PKG)/version.Package=$(PKG) $(EXTRA_LDFLAGS)'

BINARIES=$(addprefix bin/,$(COMMANDS))

# Flags passed to `go test`
TESTFLAGS ?= -v $(TESTFLAGS_RACE)
TESTFLAGS_PARALLEL ?= 8

.PHONY: all build binaries check clean test test-race test-full integration coverage
.DEFAULT: all

all: binaries

# This only needs to be generated by hand when cutting full releases.
version/version.go:
	@echo "$(WHALE) $@"
	./version/version.sh > $@

check: ## run all linters (TODO: enable "unused", "varcheck", "ineffassign", "unconvert", "staticheck", "goimports", "structcheck")
	@echo "$(WHALE) $@"
	@golangci-lint run

test: ## run tests, except integration test with test.short
	@echo "$(WHALE) $@"
	@go test ${GO_TAGS} -test.short ${TESTFLAGS} $(filter-out ${INTEGRATION_PACKAGE},${PACKAGES})

test-race: ## run tests, except integration test with test.short and race
	@echo "$(WHALE) $@"
	@go test ${GO_TAGS} -race -test.short ${TESTFLAGS} $(filter-out ${INTEGRATION_PACKAGE},${PACKAGES})

test-full: ## run tests, except integration tests
	@echo "$(WHALE) $@"
	@go test ${GO_TAGS} ${TESTFLAGS} $(filter-out ${INTEGRATION_PACKAGE},${PACKAGES})

integration: ## run integration tests
	@echo "$(WHALE) $@"
	@go test ${TESTFLAGS} -parallel ${TESTFLAGS_PARALLEL} ${INTEGRATION_PACKAGE}

coverage: ## generate coverprofiles from the unit tests
	@echo "$(WHALE) $@"
	@rm -f coverage.txt
	@go test ${GO_TAGS} -i ${TESTFLAGS} $(filter-out ${INTEGRATION_PACKAGE},${COVERAGE_PACKAGES}) 2> /dev/null
	@( for pkg in $(filter-out ${INTEGRATION_PACKAGE},${COVERAGE_PACKAGES}); do \
		go test ${GO_TAGS} ${TESTFLAGS} \
			-cover \
			-coverprofile=profile.out \
			-covermode=atomic $$pkg || exit; \
		if [ -f profile.out ]; then \
			cat profile.out >> coverage.txt; \
			rm profile.out; \
		fi; \
	done )

FORCE:

# Build a binary from a cmd.
bin/%: cmd/% FORCE
	@echo "$(WHALE) $@${BINARY_SUFFIX}"
	@go build ${GO_GCFLAGS} ${GO_BUILD_FLAGS} -o $@${BINARY_SUFFIX} ${GO_LDFLAGS} ${GO_TAGS}  ./$<

binaries: $(BINARIES) ## build binaries
	@echo "$(WHALE) $@"

build:
	@echo "$(WHALE) $@"
	@go build ${GO_GCFLAGS} ${GO_BUILD_FLAGS} ${GO_LDFLAGS} ${GO_TAGS} $(PACKAGES)

clean: ## clean up binaries
	@echo "$(WHALE) $@"
	@rm -f $(BINARIES)


text:
package jadx.core.dex.info;

import jadx.api.IJadxArgs;
import jadx.core.dex.attributes.AType;
import jadx.core.dex.instructions.args.LiteralArg;
import jadx.core.dex.instructions.args.PrimitiveType;
import jadx.core.dex.nodes.ClassNode;
import jadx.core.dex.nodes.DexNode;
import jadx.core.dex.nodes.FieldNode;
import jadx.core.dex.nodes.ResRefField;
import jadx.core.dex.nodes.parser.FieldInitAttr;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.jetbrains.annotations.Nullable;

public class ConstStorage {

	private static final class Values {
		private final Map<Object, FieldNode> values = new HashMap<Object, FieldNode>();
		private final Set<Object> duplicates = new HashSet<Object>();

		public Map<Object, FieldNode> getValues() {
			return values;
		}

		public FieldNode get(Object key) {
			return values.get(key);
		}

		/**
		 * @return true if this value is duplicated
		 */
		public boolean put(Object value, FieldNode fld) {
			FieldNode prev = values.put(value, fld);
			if (prev != null) {
				values.remove(value);
				duplicates.add(value);
				return true;
			}
			if (duplicates.contains(value)) {
				values.remove(value);
				return true;
			}
			return false;
		}

		public boolean contains(Object value) {
			return duplicates.contains(value) || values.containsKey(value);
		}
	}

	private final boolean replaceEnabled;
	private final Values globalValues = new Values();
	private final Map<ClassNode, Values> classes = new HashMap<ClassNode, Values>();

	private Map<Integer, String> resourcesNames = new HashMap<Integer, String>();

	public ConstStorage(IJadxArgs args) {
		this.replaceEnabled = args.isReplaceConsts();
	}

	public void processConstFields(ClassNode cls, List<FieldNode> staticFields) {
		if (!replaceEnabled || staticFields.isEmpty()) {
			return;
		}
		for (FieldNode f : staticFields) {
			AccessInfo accFlags = f.getAccessFlags();
			if (accFlags.isStatic() && accFlags.isFinal()) {
				FieldInitAttr fv = f.get(AType.FIELD_INIT);
				if (fv != null
						&& fv.getValue() != null
						&& fv.getValueType() == FieldInitAttr.InitType.CONST
						&& fv != FieldInitAttr.NULL_VALUE) {
					addConstField(cls, f, fv.getValue(), accFlags.isPublic());
				}
			}
		}
	}

	private void addConstField(ClassNode cls, FieldNode fld, Object value, boolean isPublic) {
		if (isPublic) {
			globalValues.put(value, fld);
		} else {
			getClsValues(cls).put(value, fld);
		}
	}

	private Values getClsValues(ClassNode cls) {
		Values classValues = classes.get(cls);
		if (classValues == null) {
			classValues = new Values();
			classes.put(cls, classValues);
		}
		return classValues;
	}

	@Nullable
	public FieldNode getConstField(ClassNode cls, Object value, boolean searchGlobal) {
		DexNode dex = cls.dex();
		if (value instanceof Integer) {
			String str = resourcesNames.get(value);
			if (str != null) {
				return new ResRefField(dex, str.replace('/', '.'));
			}
		}
		if (!replaceEnabled) {
			return null;
		}
		boolean foundInGlobal = globalValues.contains(value);
		if (foundInGlobal && !searchGlobal) {
			return null;
		}
		ClassNode current = cls;
		while (current != null) {
			Values classValues = classes.get(current);
			if (classValues != null) {
				FieldNode field = classValues.get(value);
				if (field != null) {
					if (foundInGlobal) {
						return null;
					}
					return field;
				}
			}
			ClassInfo parentClass = current.getClassInfo().getParentClass();
			if (parentClass == null) {
				break;
			}
			current = dex.resolveClass(parentClass);
		}
		if (searchGlobal) {
			return globalValues.get(value);
		}
		return null;
	}

	@Nullable
	public FieldNode getConstFieldByLiteralArg(ClassNode cls, LiteralArg arg) {
		PrimitiveType type = arg.getType().getPrimitiveType();
		if (type == null) {
			return null;
		}
		long literal = arg.getLiteral();
		switch (type) {
			case BOOLEAN:
				return getConstField(cls, literal == 1, false);
			case CHAR:
				return getConstField(cls, (char) literal, Math.abs(literal) > 10);
			case BYTE:
				return getConstField(cls, (byte) literal, Math.abs(literal) > 10);
			case SHORT:
				return getConstField(cls, (short) literal, Math.abs(literal) > 100);
			case INT:
				return getConstField(cls, (int) literal, Math.abs(literal) > 100);
			case LONG:
				return getConstField(cls, literal, Math.abs(literal) > 1000);
			case FLOAT:
				float f = Float.intBitsToFloat((int) literal);
				return getConstField(cls, f, f != 0.0);
			case DOUBLE:
				double d = Double.longBitsToDouble(literal);
				return getConstField(cls, d, d != 0);
		}
		return null;
	}

	public void setResourcesNames(Map<Integer, String> resourcesNames) {
		this.resourcesNames = resourcesNames;
	}

	public Map<Integer, String> getResourcesNames() {
		return resourcesNames;
	}

	public Map<Object, FieldNode> getGlobalConstFields() {
		return globalValues.getValues();
	}

	public boolean isReplaceEnabled() {
		return replaceEnabled;
	}
}


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var Promise = require("bluebird");
var gutil = require("gulp-util");
var path = require("path");
var util = require("util");
var defer_1 = require("./defer");
var fileHelper = require("./fileHelper");
var fileHlp = new fileHelper.FileHelper();
var processedLibs = [];
var FolderCreator = (function () {
    function FolderCreator(options, crntSpr, crntDigest, crntFileInfo) {
        this.digest = crntDigest;
        this.config = options;
        this.spr = crntSpr;
        this.fileInfo = crntFileInfo;
    }
    FolderCreator.prototype.checkFoldersAndCreateIfNotExist = function () {
        var _this = this;
        return new Promise(function (resolve, reject) {
            var library = _this.fileInfo.library;
            if (path.sep == "\\") {
                library = library.replace(/\\/g, "/");
            }
            if (_this.config.cache) {
                if (_this.checkCachedLocation(library)) {
                    if (_this.config.verbose) {
                        gutil.log('INFO: Library already processed', library);
                    }
                    resolve(null);
                    return;
                }
            }
            var foldersArray = fileHlp.getFolderPathsArray(library);
            var proms = [];
            foldersArray.forEach(function (val) {
                proms.push(_this.checkFolderExists(val));
            });
            Promise.all(proms).then(function (data) {
                var erroredIndexes = data.map(function (val, index) {
                    if (val.error) {
                        return index;
                    }
                }).filter(function (x) {
                    return x != undefined;
                });
                var pathArray = [];
                erroredIndexes.map(function (index) {
                    pathArray.push(foldersArray[index]);
                });
                if (pathArray.length > 0) {
                    return _this.createPathRecursive(pathArray).then(function () {
                        resolve(null);
                    }).catch(function (err) {
                        reject(err);
                    });
                }
                else {
                    resolve(null);
                }
            });
        });
    };
    FolderCreator.prototype.cacheLocation = function (folderLocation) {
        if (this.config.cache) {
            if (processedLibs.indexOf(folderLocation) === -1) {
                processedLibs.push(folderLocation);
            }
        }
    };
    FolderCreator.prototype.checkCachedLocation = function (folderLocation) {
        if (processedLibs.indexOf(folderLocation) !== -1) {
            return true;
        }
        return false;
    };
    FolderCreator.prototype.checkFolderExists = function (folderName) {
        var _this = this;
        var getFolderUrl = util.format("/_api/web/GetFolderByServerRelativeUrl(@FolderName)?@FolderName='%s'", encodeURIComponent(folderName));
        var header = {
            headers: {
                "Accept": "application/json;odata=verbose",
                "content-type": "application/json;odata=verbose",
                "X-RequestDigest": this.digest
            },
            json: true
        };
        var endPoint = this.config.site + getFolderUrl;
        if (this.config.verbose) {
            gutil.log("INFO: Checking folder exists " + endPoint);
        }
        return new Promise(function (resolve, reject) {
            _this.spr.get(endPoint, header)
                .then(function (success) {
                if (_this.config.verbose) {
                    gutil.log('INFO: Folder ' + folderName + ' exists');
                }
                _this.cacheLocation(folderName);
                resolve(success);
            })
                .catch(function (err) {
                gutil.log("INFO: Folder '" + folderName + "' doesn't exist and will be created");
                resolve(err);
            });
        });
    };
    FolderCreator.prototype.createPathRecursive = function (pathArray, deferred) {
        var _this = this;
        if (!deferred) {
            deferred = defer_1.defer();
        }
        if (pathArray.length > 0) {
            if (this.config.verbose) {
                gutil.log("INFO: Creating path " + pathArray[0]);
            }
            var setFolder = util.format("/_api/web/folders");
            var opts = {
                headers: {
                    "X-RequestDigest": this.digest
                },
                body: {
                    '__metadata': {
                        'type': 'SP.Folder'
                    },
                    'ServerRelativeUrl': "" + pathArray[0]
                }
            };
            this.spr.post(this.config.site + setFolder, opts)
                .then(function (res) {
                _this.cacheLocation(pathArray[0]);
                if (_this.config.verbose) {
                    gutil.log('INFO: Folder created:', pathArray[0]);
                }
                return _this.createPathRecursive(pathArray.slice(1, pathArray.length), deferred);
            })
                .catch(function (err) {
                gutil.log(gutil.colors.red("ERROR: " + err));
                deferred.reject(err);
            });
        }
        else {
            deferred.resolve(null);
        }
        return deferred.promise;
    };
    return FolderCreator;
}());
exports.FolderCreator = FolderCreator;


text:
package middleware

import (
	"net/http"
	"strings"
)

// SetHeader is a convenience handler to set a response header key/value
func SetHeader(key, value string) func(next http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		fn := func(w http.ResponseWriter, r *http.Request) {
			w.Header().Set(key, value)
			next.ServeHTTP(w, r)
		}
		return http.HandlerFunc(fn)
	}
}

// AllowContentType enforces a whitelist of request Content-Types otherwise responds
// with a 415 Unsupported Media Type status.
func AllowContentType(contentTypes ...string) func(next http.Handler) http.Handler {
	cT := []string{}
	for _, t := range contentTypes {
		cT = append(cT, strings.ToLower(t))
	}

	return func(next http.Handler) http.Handler {
		fn := func(w http.ResponseWriter, r *http.Request) {
			if r.ContentLength == 0 {
				// skip check for empty content body
				next.ServeHTTP(w, r)
				return
			}

			s := strings.ToLower(strings.TrimSpace(r.Header.Get("Content-Type")))
			if i := strings.Index(s, ";"); i > -1 {
				s = s[0:i]
			}

			for _, t := range cT {
				if t == s {
					next.ServeHTTP(w, r)
					return
				}
			}

			w.WriteHeader(http.StatusUnsupportedMediaType)
		}
		return http.HandlerFunc(fn)
	}
}


text:
package Interviews;

public class PrintAllSizeKSubsets42 {
	public static void main(String[] args) {
		//now, let's create a test case
		int[] array = {1,2,3,4};
		int K = 2;
		boolean[] used = new boolean[array.length];
		PrintAllSizeKSubset(array, used, 0, 0, 2);
		//expect, 12,13,14,23,24,34!
	}

	public static void PrintAllSizeKSubset(int[] a, boolean[] used, int startIndex, int currentSize, int k) {
		if (currentSize == k) {
			for (int i = 0; i < used.length; i++) {
				if (used[i]) {
					System.out.print(a[i] + " ");

				}
			}
			System.out.println();
			return;
		}

		if (startIndex == a.length) {
			return;
		}
		used[startIndex] = true;
		PrintAllSizeKSubset(a, used, startIndex + 1, currentSize + 1, k);
		used[startIndex] = false;
		PrintAllSizeKSubset(a, used, startIndex + 1, currentSize, k);
	}

}


text:
const char * PROVIDE_FUNC()
{
	return NAME;
}

char **REQUIRE_FUNC()
{
	char *items[] = REQUIRE;
	char **arr = items;
	char **results = (char**)malloc(sizeof(char*) * sizeof(items));
	int i = 0;
	while (*arr)
	{
		results[i] = (char*)malloc(sizeof(char) * strlen(*arr));
		strcpy(results[i++], *arr);
		arr++;
	}
	return results;
}

char **BEFORE_FUNC()
{
	char *items[] = BEFORE;
	char **arr = items;
	char **results = (char**)malloc(sizeof(char*) * sizeof(items));
	int i = 0;
	while (*arr)
	{
		results[i] = (char*)malloc(sizeof(char) * strlen(*arr));
		strcpy(results[i++], *arr);
		arr++;
	}
	return results;
}

char **KEYWORD_FUNC()
{
	char *items[] = KEYWORD;
	char **arr = items;
	char **results = (char**)malloc(sizeof(char*) * sizeof(items));
	int i = 0;
	while (*arr)
	{
		results[i] = (char*)malloc(sizeof(char) * strlen(*arr));
		strcpy(results[i++], *arr);
		arr++;
	}
	return results;
}

#ifndef __canstart
int CANSTART_FUNC()
{
#if ALWAYS_START
	return 0;
#else
#ifndef START_VARIABLE
#define START_VARIABLE NAME "_enable"
#endif
	return is_enabled(START_VARIABLE);
#endif
}
#endif

#ifndef __prestart
int PRESTART_FUNC()
{
	return 0;
}
#endif

#if !defined(__stop)
int STOP_FUNC()
{
	return 0;
}
#endif

#ifndef __status
int STATUS_FUNC()
{
	printf("No status to report");
	return 0;
}
#endif

#ifndef __sanity
int SANITY_FUNC()
{
#ifdef REQUIRED_FILES
	char *files_[] = REQUIRED_FILES;
	char **files = files_;
	while(*files)
	{
		if (file_readable(*files) == -1) return (-1);
		files++;
	}
#endif
	return 0;
}
#endif

#ifndef __listcmd
int LISTCMD_FUNC()
{
#if defined(EXTRA_COMMANDS) && defined(EXTERA_COMMANDS_DESC)
	printf("\n\tsanity: Reports sanity of the service\n");
	printf("\tstart: Starts the service\n");
	printf("\tstop: Stop the service\n");
	printf("\tstatus: Reports the current service status\n");
	char *extra_cmds_ = EXTRA_COMMANDS;
	char *extra_cmds_desc_ = EXTRA_COMMANDS;
	char **extra_cmds = extra_cmds_;
	char **extra_cmds_desc = extra_cmds_desc_;
	while (*extra_cmds)
	{
		printf("\t%s: %s\n", *extra_cmds, *extra_cmds_desc);
		extra_cmds++;
		extra_cmds_desc++;
	}
#endif
	return 0;
}

#ifndef FLAGS_VARIABLE
#define FLAGS_VARIABLE NAME "_flags"
#endif

#if defined(PID_FILE) && defined(COMMAND)
#ifndef __start
int START_FUNC()
{
	char *cmd[] = { COMMAND, getvar(FLAGS_VARIABLE) };
	return rundaemon(cmd, PID_FILE);
}
#endif
#endif
#endif


text:
Solution was inspired by https://github.com/g00glen00b/ng-spring-boot project

## Installation
Installation is quite easy, first you will have to install some front-end dependencies using Bower:
```
bower install
```

Then you can run Maven to package the application:
```
mvn clean package
```

Now you can run the Java application quite easily:
```
cd target
java -jar ng-spring-boot-1.0.0.jar
```


text:
package cn.cdu.edu.TQC.bems.service;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.core.Response.ResponseBuilder;

import cn.cdu.edu.TQC.bems.DownLoadUtil;
import cn.cdu.edu.TQC.bems.db.bean.Template;
import cn.cdu.edu.TQC.bems.db.dao.TemplateDao;
import cn.cdu.edu.TQC.bems.db.dao.impl.TemplateDaoImpl;

import com.sun.jersey.api.client.ClientResponse.Status;
import com.sun.jersey.spi.resource.Singleton;

/**
 * @ClassName: StaffService
 * 说明:
 * TODO(Tell the reader such role.)
 * @Author LPM	【email:shouli1990@gmail.com 】
 * @Version V1.0	2012-7-5 下午8:39:55
 *
 */

@Path("/templates")
@Singleton
public class TemplateService {

    private TemplateDao dao = null;

    public TemplateService(){
	dao = new TemplateDaoImpl();
    }

    @Context
    UriInfo uriInfo;
    @Context
    Request request;

    @GET
    @Produces("application/xml")
    public List<Template> getStaffs(){
	List<Template> templates = null;
	try {
	    String sql = "select * from TEMPLATE";
	    templates = dao.getTemplates(sql);
	} catch (Exception e) {
	    // TODO: handle exception
	}
	return templates;
    }

    @GET
    @Path("/{uid}")
    @Produces("application/xml")
    public Template getTemplate(@PathParam("templateid") Integer tid){
	Template template = null;
	try {
	    String sql = "select * from TEMPLATE WHERE templateid = "+ tid;
	    template = dao.getTemplate(sql);
	} catch (Exception e) {
	    // TODO: handle exception
	}
	return template;
    }

    @POST
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    @Produces("application/xml")
    public Response createTemplate(
	    @FormParam("a") Integer a,
	    @FormParam("b") String b,
	    @FormParam("c") Long c){
	String sql = "";
	dao.upDate(sql);
	Response res = null;
	res = Response.ok().type("application/xml").build();
	return res;
    }

    @DELETE
    @Path("/{id}")
    public String deleteTemplate(@PathParam("id") Integer tid){
	try {
	    String sql = "";
	    dao.upDate(sql);
	} catch (Exception e) {
	    // TODO: handle exception
	}
	return "succes";
    }

    @GET
    @Path("/ammeter")
    @Produces("application/xml")
    public Response dowloadTest(
	    		@QueryParam("type") String type,
	    		@QueryParam("id") Integer id,
			@Context HttpServletResponse servletResponse,
			@Context HttpServletRequest servletRequest) throws Exception{

	new DownLoadUtil().exportAmmeterDataList(servletResponse, "xls",type, id);

	Response res;
        ResponseBuilder builder = Response.status(Status.CREATED);
        builder.type("application/xml");
        builder.entity("ok");
        res = builder.build();
        return res;
    }
    @GET
    @Path("/phone")
    @Produces("application/xml")
    public Response dowloadTest(
	    		@QueryParam("year") Integer year,
	    		@QueryParam("month") Integer month,
			@Context HttpServletResponse servletResponse,
			@Context HttpServletRequest servletRequest) throws Exception{

	new DownLoadUtil().exportPhoneFeeList(servletResponse, "xls", year, month);
	Response res;
        ResponseBuilder builder = Response.status(Status.CREATED);
        builder.type("application/xml");
        builder.entity("ok");
        res = builder.build();
        return res;
    }

    @GET
    @Path("/meter")
    @Produces("application/xml")
    public Response dowloadTest(
	    		@QueryParam("id") Integer id,
			@Context HttpServletResponse servletResponse,
			@Context HttpServletRequest servletRequest) throws Exception{

	new DownLoadUtil().exportMeterDataList(servletResponse, "xls", id);
	Response res;
        ResponseBuilder builder = Response.status(Status.CREATED);
        builder.type("application/xml");
        builder.entity("ok");
        res = builder.build();
        return res;
    }

}


text:
from flask import request, jsonify, Flask, render_template, url_for
import time
from flask.ext.sqlalchemy import SQLAlchemy
import os
from block_io import BlockIo
from flask import Response
import math

app = Flask(__name__)
basedir = os.path.abspath(os.path.dirname(__file__))

##db setup##
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
db = SQLAlchemy(app)
app = Flask(__name__)
app.config['SECRET_KEY'] = 'hard to guess string'
app.config['SQLALCHEMY_DATABASE_URI'] =\
        'sqlite:///' + os.path.join(basedir, 'data.sqlite')
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
db = SQLAlchemy(app)

##Model##
class Shake(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    user_id = db.Column(db.Integer)
    lat = db.Column(db.Float)
    long = db.Column(db.Float)
    timestamp = db.Column(db.Integer)
    amount = db.Column(db.Float)
    done = db.Column(db.Boolean)
    def __init__(self, user_id, lat, long, timestamp, amount):
            self.user_id = user_id
            self.lat = lat
            self.long = long
            self.timestamp = timestamp
            self.amount = amount
            self.done = False

    def __str__(self):
        return "user_id %d lat %f long %f timestamp %d amount %f " % (self.user_id, self.lat, self.long, self.timestamp, self.amount)

class User(db.Model):
    user_id = db.Column(db.Integer, primary_key=True)
    api_key = db.Column(db.String(200))
    secret = db.Column(db.String(200))
    def __init__(self, user_id, api_key, secret):
        self.user_id = user_id
        self.api_key = api_key
        self.secret = secret

def get_time_in_sec():
    return int(round(time.time()))

def db_insert(obj):
    db.session.add(obj)
    db.session.commit()

time_threshold = 7
distance_threshold = 10 #in meters

##adapted from http://stackoverflow.com/questions/1502590/calculate-distance-between-two-points-in-google-maps-v3
def rad(x):
    return (x*math.pi)/180

def get_distance(lat1, long1, lat2, long2):
    R = 6378137
    dLat = rad(lat2 - lat1)
    dLong = rad(long2 - long1)
    a = math.sin(dLat / 2) * math.sin(dLat / 2) + math.cos(rad(lat1)) * math.cos(rad(lat2)) * math.sin(dLong / 2) * math.sin(dLong / 2)
    c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
    d = R * c
    print "%f %f %f %f - %f\n" % (lat1, long1, lat2, long2, d)
    return d

def is_matching_shake(shake1, shake2): ##TODO
    if shake1.amount * shake2.amount >= 0:  ##have same sign
        return False
    if shake1.id == shake2.id:
        return False
    time_diff = abs(shake1.timestamp - shake2.timestamp)
    distance = get_distance(shake1.lat, shake1.long, shake2.lat, shake2.long)
    return time_diff <= time_threshold and distance <= distance_threshold

def get_matching_shake(shake1):
    shakes = Shake.query.all()
    for shake2 in shakes: ##TODO handle multiple shakes
        if is_matching_shake(shake1, shake2):
            print "matching\n" + str(shake1) +"\n" + str(shake2) +"\n"
            return shake2
    return None

#Note only one the shakes should call the api
def start_transaction(shake1, shake2): ##TODO
    giver = shake1
    receiver = shake2
    if shake2.amount >= 0:
        receiver, giver = giver, receiver
    ##TODO check balance etc.
    sender_block_io = get_user_block_io(giver.user_id)
    receiver_block_io = get_user_block_io(receiver.user_id)
    receiver_address = get_bitcoin_address(receiver_block_io)
    amount = giver.amount
    return send_bitcoins(sender_block_io, amount, receiver_address)

# /shake params-user_id, location, amount
#
@app.route('/shake', methods=['GET'])
def shake_func():
    user_id = request.args.get('user_id')
    lat = request.args.get('lat')
    long = request.args.get('long')
    timestamp = initial_time_sec = get_time_in_sec()
    amount = request.args.get('amount') ##This will be none for one of the shakes
    if not amount:
        amount = -1.0
    shake = Shake(user_id, lat, long, timestamp, amount)
    db_insert(shake)
    #transaction is only done by giver
    num_seconds_retry = 8
    response = None
    if amount < 0:  #receiver
        time.sleep(num_seconds_retry)
        matching_shake = get_matching_shake(shake)
        if matching_shake:
            if matching_shake.done:
                response = {'success' : True, 'message' : 'Received bitcoins'}
            else:
                response = {'success' : False, 'message' : 'Matching request found but transaction failed'}
        else:
            response = {'success' : False, 'message' : 'No opposite device found'}
    else :
        while get_time_in_sec() - initial_time_sec < num_seconds_retry:
            matching_shake = get_matching_shake(shake)
            if matching_shake:
                response = start_transaction(shake, matching_shake)
                #persist the fact that transaction was a success
                shake.done = matching_shake.done = True
                db.session.commit()
                break
        else:
            response = {'success' : False, 'message' : 'No opposite device found'}
    return jsonify(**response)

@app.route('/users/create')
def create_user():
    user_id = request.args.get('user_id')
    api_key = request.args.get('api_key')
    secret = request.args.get('secret')
    user = User(user_id, api_key, secret)
    db.insert(user)

@app.route('/db/refresh')
def refresh_db():
    db.engine.execute("drop table user;")
    db.engine.execute("drop table shake;")
    db.create_all()
    db.engine.execute("insert into user values(1, '47d3-6b6f-2c49-69c9', 'hooli123');");
    db.engine.execute("insert into user values(2, 'c142-800f-049c-5c49', 'hooli123');");
    return "done"

###bitcoin
def get_user_block_io(user_id):
    user = User.query.filter_by(user_id=user_id).first()
    return BlockIo(user.api_key, user.secret, 2)

#returns created bitcoin address
def get_bitcoin_address(block_io):
    return block_io.get_new_address()['data']['address']

def get_total_balance(block_io):
    return block_io.get_balance()

def send_bitcoins(block_io, amount, to_address): #check format
    print "sending bitcoins amount-%f to-%s\n" % (amount, to_address)
    return block_io.withdraw(amounts=amount, to_addresses=to_address)

@app.route('/user/<int:user_id>', methods=['GET'])
def api_balance(user_id):
    response = {'balance' : get_total_balance(get_user_block_io(user_id))}
    return jsonify(**response)

@app.route('/db/create')
def create_db():
    db.create_all()
    return "done"

@app.route('/')
def shaker():
    return render_template('a.html')

def main():
    app.run(host='0.0.0.0', debug=True, port=5000, use_reloader=True, threaded=True)

if __name__ == '__main__':
    main()


text:
#ifndef REPLACE_TOOL_H_DEFINED_
#define REPLACE_TOOL_H_DEFINED_

#include "../recc-implementation/binary_exponential_buffer.h"

struct replacement_rule{
	struct binary_exponential_buffer search;
	struct binary_exponential_buffer replace;
};

struct replacement_context{
	struct binary_exponential_buffer rules;
	struct binary_exponential_buffer in_characters;
	struct binary_exponential_buffer out_characters;
};

void replacement_context_associate_replacement(struct replacement_context *, struct replacement_rule *);
struct replacement_context * replacement_context_create(void);
void replacement_context_destroy(struct replacement_context *);
void reset_candidates(struct binary_exponential_buffer *);
unsigned int count_candidates(struct binary_exponential_buffer *);
unsigned int get_length(unsigned char *);
void do_string_replacements(struct replacement_context *);
struct replacement_rule * replacement_rule_create(void);
void replacement_rule_destroy(struct replacement_rule *);
#endif


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

    Licensed to the Austrian Association for Software Tool Integration (AASTI)
    under one or more contributor license agreements. See the NOTICE file
    distributed with this work for additional information regarding copyright
    ownership. The AASTI licenses this file to you under the Apache License,
    Version 2.0 (the "License"); you may not use this file except in compliance
    with the License. You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

-->

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

  <parent>
    <groupId>org.openengsb</groupId>
    <artifactId>openengsb-root</artifactId>
    <version>34-SNAPSHOT</version>
  </parent>

  <properties>
    <openengsb.api.version>3.0.0-SNAPSHOT</openengsb.api.version>
    <openengsb.test.version>3.0.0-SNAPSHOT</openengsb.test.version>
  </properties>

  <modelVersion>4.0.0</modelVersion>
  <groupId>org.openengsb.framework.workflow</groupId>
  <artifactId>org.openengsb.framework.workflow.api</artifactId>
  <version>3.0.0-SNAPSHOT</version>

  <name>OpenEngSB :: Framework :: Workflow :: API</name>

  <packaging>bundle</packaging>

  <description>
    Interfaces for the Workflow Engine
  </description>

  <url>http://www.openengsb.org</url>

  <licenses>
    <license>
      <name>Apache 2</name>
      <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
      <distribution>repo</distribution>
    </license>
  </licenses>

  <scm>
    <connection>scm:git:git://github.com/openengsb/openengsb-framework.git</connection>
    <developerConnection>scm:git:git@github.com:openengsb/openengsb-framework.git</developerConnection>
    <url>http://github.com/openengsb/openengsb-framework</url>
  </scm>

  <build>
    <resources>
      <resource>
        <directory>${project.basedir}/src/main/resources</directory>
        <includes>
          <include>**/*</include>
        </includes>
      </resource>
      <resource>
        <directory>${project.basedir}/src/main/resources</directory>
        <filtering>true</filtering>
        <includes>
          <include>**/*.info</include>
        </includes>
      </resource>
    </resources>
    <plugins>
      <plugin>
        <groupId>org.apache.felix</groupId>
        <artifactId>maven-bundle-plugin</artifactId>
        <extensions>true</extensions>
        <configuration>
          <instructions>
            <Provide-Models>true</Provide-Models>
          </instructions>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.axis2</groupId>
        <artifactId>axis2-java2wsdl-maven-plugin</artifactId>
        <executions>
          <execution>
            <id>EventRegistrationService</id>
            <phase>process-classes</phase>
            <configuration>
              <className>org.openengsb.core.workflow.api.EventRegistrationService</className>
              <outputFileName>${project.basedir}/target/generated/wsdl/EventRegistrationService.wsdl</outputFileName>
            </configuration>
            <goals>
              <goal>java2wsdl</goal>
            </goals>
          </execution>
          <execution>
            <id>RuleManager</id>
            <phase>process-classes</phase>
            <configuration>
              <className>org.openengsb.core.workflow.api.RuleManager</className>
              <outputFileName>${project.basedir}/target/generated/wsdl/RuleManager.wsdl</outputFileName>
            </configuration>
            <goals>
              <goal>java2wsdl</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>build-helper-maven-plugin</artifactId>
        <executions>
          <execution>
            <id>attach-artifacts</id>
            <phase>package</phase>
            <goals>
              <goal>attach-artifact</goal>
            </goals>
            <configuration>
              <artifacts>
                <artifact>
                  <file>target/generated/wsdl/EventRegistrationService.wsdl</file>
                  <type>wsdl</type>
                  <classifier>EventRegistrationService</classifier>
                </artifact>
                <artifact>
                  <file>target/generated/wsdl/RuleManager.wsdl</file>
                  <type>wsdl</type>
                  <classifier>RuleManager</classifier>
                </artifact>
              </artifacts>
            </configuration>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <groupId>org.jasig.maven</groupId>
        <artifactId>maven-notice-plugin</artifactId>
        <configuration>
          <licenseMapping>
            <param>etc/notice/license-mapping.xml</param>
          </licenseMapping>
        </configuration>
      </plugin>
    </plugins>
  </build>

  <dependencies>
    <dependency>
      <groupId>org.openengsb.labs.delegation</groupId>
      <artifactId>org.openengsb.labs.delegation.service</artifactId>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.openengsb.framework</groupId>
      <artifactId>org.openengsb.framework.api</artifactId>
      <version>${openengsb.api.version}</version>
    </dependency>
    <dependency>
      <groupId>commons-lang</groupId>
      <artifactId>commons-lang</artifactId>
    </dependency>
    <dependency>
      <groupId>com.google.guava</groupId>
      <artifactId>guava</artifactId>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <repositories>
    <repository> <!-- OEB snapshots are deployed here -->
      <id>sonatype-snapshots</id>
      <name>Sonaype Snapsht Repository</name>
      <url>https://oss.sonatype.org/content/repositories/snapshots/</url>
      <releases>
        <enabled>false</enabled>
      </releases>
      <snapshots>
        <enabled>true</enabled>
      </snapshots>
    </repository>
  </repositories>
</project>


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="generator" content="rustdoc">
    <meta name="description" content="API documentation for the Rust `MarkdownWriter` struct in crate `clog`.">
    <meta name="keywords" content="rust, rustlang, rust-lang, MarkdownWriter">

    <title>clog::fmt::MarkdownWriter - Rust</title>

    <link rel="stylesheet" type="text/css" href="../../main.css">

clog::<wbr>fmt

        <form class="search-form js-only">

                <input class="search-input" name="search"
                       autocomplete="off"
                       placeholder="Click or press 'S' to search, '?' for more options..."
                       type="search">

        </form>

Struct clog::<wbr>fmt::<wbr>MarkdownWriter

                [−]

        [src]

pub struct MarkdownWriter<'a>(_);

Wraps a std::io::Write object to write clog output in a Markdown format

Example

let clog = Clog::new().unwrap_or_else(|e| {
    e.exit();
});

// Get the commits we're interested in...
let sm = SectionMap::from_commits(clog.get_commits());

// Create a file to hold our results, which the MardownWriter will wrap (note, .unwrap() is only
// used to keep the example short and concise)
let mut file = File::create("my_changelog.md").ok().unwrap();

// Create the MarkdownWriter
let mut writer = MarkdownWriter::new(&mut file);

// Use the MarkdownWriter to write the changelog
clog.write_changelog_with(&mut writer).unwrap_or_else(|e| {
    e.exit();
});

Methods

impl<'a> MarkdownWriter<'a>

fn new<T: Write + 'a>(writer: &'a mut T) -> MarkdownWriter<'a>

Creates a new instance of the MarkdownWriter struct using a std::io::Write object.

Example

let clog = Clog::new().unwrap_or_else(|e| {
    e.exit();
});

// Create a MarkdownWriter to wrap stdout
let out = stdout();
let mut out_buf = BufWriter::new(out.lock());
let mut writer = MarkdownWriter::new(&mut out_buf);

Trait Implementations

impl<'a> FormatWriter for MarkdownWriter<'a>

fn write_changelog(&mut self, options: &Clog, sm: &SectionMap) -> WriterResult

Keyboard shortcuts

?

Show this help dialog

S

Focus the search field

⇤

Move up in search results

⇥

Move down in search results

⏎

Go to active search result

Search tricks

                Prefix searches with a type followed by a colon (e.g.
                fn:) to restrict the search to a given type.

                Accepted types are: fn, mod,
                struct, enum,
                trait, typedef (or
                tdef).

                Search functions by type signature (e.g.
                vec -> usize)


text:
'use strict';
require('../common');
const assert = require('assert');
const http = require('http');
const net = require('net');

const COUNT = 10;

let received = 0;

const server = http.createServer(function(req, res) {
  // Close the server, we have only one TCP connection anyway
  if (received++ === 0)
    server.close();

  res.writeHead(200);
  res.write('data');

  setTimeout(function() {
    res.end();
  }, (Math.random() * 100) | 0);
}).listen(0, function() {
  const s = net.connect(this.address().port);

  const big = 'GET / HTTP/1.0\r\n\r\n'.repeat(COUNT);

  s.write(big);
  s.resume();
});

process.on('exit', function() {
  assert.strictEqual(received, COUNT);
});


text:
<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="description" content="A front-end template that helps you build fast, modern mobile web apps.">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Web Starter Kit</title>

    <link rel="manifest" href="../app/manifest.json">

    <meta name="mobile-web-app-capable" content="yes">
    <meta name="application-name" content="Web Starter Kit">
    <link rel="icon" sizes="192x192" href="../app/images/touch/chrome-touch-icon-192x192.png">

    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="apple-mobile-web-app-title" content="Web Starter Kit">
    <link rel="apple-touch-icon" href="../app/images/touch/apple-touch-icon.png">

    <meta name="msapplication-TileImage" content="images/touch/ms-touch-icon-144x144-precomposed.png">
    <meta name="msapplication-TileColor" content="#3372DF">

    <meta name="theme-color" content="#3372DF">

    <link rel="stylesheet" href="../app/styles/main.css">

        <button class="menu"></button>

Undergraduate Research of Math & CS at QCC

Navigation

Home

Members

Projects

Funds

Links

        222-05 56th Avenue Bayside, NY 11364 (718) 631-6262 ·
        Contact Us

        Emergency/School Closing Info ·
        CUNY ·
        Text Only Version ·
        Make
          This Website Talk


text:
import { CommonModule } from '@angular/common';
import {
  AfterContentInit,
  Component,
  ContentChild,
  NgModule,
  ViewChild,
} from '@angular/core';
import {
  FormControl,
  ReactiveFormsModule,
  Validators,
} from '@angular/forms';
import { TsFormFieldComponent } from '@terminus/ui/form-field';
import {
  TsInputAutocompleteTypes,
  TsInputComponent,
  TsInputModule,
  TsInputTypes,
  TsMaskShortcutOptions,
} from '@terminus/ui/input';
import { TsStyleThemeTypes } from '@terminus/ui/utilities';

@Component({
  template: `
    <ts-input [formControl]="control"></ts-input>
  `,
})
export class SimpleFormControl {
  public control: FormControl | undefined = new FormControl();

  @ViewChild(TsInputComponent, { static: true })
  inputComponent!: TsInputComponent;
}

@Component({ template: `<ts-input [datepicker]="true"></ts-input>` })
export class Autocomplete implements AfterContentInit {
  public control: FormControl | undefined = new FormControl();
  public firstDate = new Date(2018, 1, 1);
  public secondDate = new Date(2017, 3, 3);

  @ViewChild(TsInputComponent, { static: true })
  inputComponent!: TsInputComponent;

  ngAfterContentInit() {
    this.inputComponent.value = this.firstDate;
  }

  updateDate() {
    this.inputComponent.value = this.secondDate;
  }
}

@Component({ template: `<ts-input [readOnly]="readOnly"></ts-input>` })
export class AttrReadonly {
  public readOnly = false;

  @ViewChild(TsInputComponent, { static: true })
  inputComponent!: TsInputComponent;
}

@Component({ template: `<ts-input [spellcheck]="spellcheck"></ts-input>` })
export class AttrSpellcheck {
  public spellcheck = false;

  @ViewChild(TsInputComponent, { static: true })
  inputComponent!: TsInputComponent;
}

@Component({ template: `<ts-input [autocapitalize]="autocapitalize"></ts-input>` })
export class AttrAutocapitalize {
  public autocapitalize = false;

  @ViewChild(TsInputComponent, { static: true })
  inputComponent!: TsInputComponent;
}

@Component({ template: `<ts-input [autocomplete]="autocomplete"></ts-input>` })
export class AttrAutocomplete {
  public autocomplete: TsInputAutocompleteTypes = 'on';
}

@Component({ template: `<ts-input [id]="id"></ts-input>` })
export class AttrId {
  public id: string | undefined = undefined;
}

@Component({ template: `<ts-input [isDisabled]="disabled"></ts-input>` })
export class AttrDisabled {
  public disabled = false;
}

@Component({ template: `<ts-input [isFocused]="focused"></ts-input>` })
export class AttrAutofocus {
  public focused = false;
}

@Component({
  template: `
    <ts-input [theme]="theme"></ts-input>
  `,
})
export class Theme {
  public theme: TsStyleThemeTypes | undefined;

  @ViewChild(TsInputComponent, { static: true })
  inputComponent!: TsInputComponent;
}

@Component({ template: `<ts-input [tabIndex]="index"></ts-input>` })
export class TabIndex {
  public index = 4;

  @ViewChild(TsInputComponent, { static: true })
  inputComponent!: TsInputComponent;
}

@Component({
  template: `
    <ts-input
      [mask]="mask"
      [formControl]="formControl"
    ></ts-input>
  `,
})
export class Mask {
  public mask: TsMaskShortcutOptions | undefined = undefined;
  public formControl = new FormControl();

  @ViewChild(TsInputComponent, { static: true })
  inputComponent!: TsInputComponent;
}

@Component({
  template: `
    <ts-input
      [mask]="mask"
      [formControl]="formControl"
      [maskSanitizeValue]="maskSanitizeValue"
    ></ts-input>
  `,
})
export class MaskSanitize {
  public mask: TsMaskShortcutOptions | undefined;
  public formControl = new FormControl();
  public maskSanitizeValue = true;

  @ViewChild(TsInputComponent, { static: true })
  inputComponent!: TsInputComponent;
}

@Component({
  template: `
    <ts-input
      [mask]="mask"
      [formControl]="formControl"
      [maskAllowDecimal]="maskAllowDecimal"
    ></ts-input>
  `,
})
export class MaskDecimal {
  public mask: TsMaskShortcutOptions | undefined;
  public formControl = new FormControl();
  public maskAllowDecimal = true;

  @ViewChild(TsInputComponent, { static: true })
  inputComponent!: TsInputComponent;
}

@Component({
  template: `
    <ts-input
      [mask]="mask"
      [formControl]="formControl"
    ></ts-input>
  `,
})
export class MaskDateFormat {
  public mask: TsMaskShortcutOptions = 'date';
  public formControl = new FormControl();

  @ViewChild(TsInputComponent, { static: true })
  inputComponent!: TsInputComponent;
}

@Component({
  template: `
    <ts-input
      [formControl]="formControl"
      [mask]="mask"
    ></ts-input>
  `,
})
export class PostalMask {
  public formControl = new FormControl();
  public mask: TsMaskShortcutOptions = 'postal';

  @ViewChild(TsInputComponent, { static: true })
  inputComponent!: TsInputComponent;
}

@Component({ template: `<ts-input></ts-input>` })
export class MissingFormControl {
  @ViewChild(TsInputComponent, { static: true })
  inputComponent!: TsInputComponent;
}

@Component({
  template: `
    <ts-input
      [datepicker]="true"
      [startingView]="startingView"
    ></ts-input>
  `,
})
export class StartingView {
  public startingView: 'month' | 'year' = 'month';

  @ViewChild(TsInputComponent, { static: true })
  inputComponent!: TsInputComponent;
}

@Component({
  template: `
    <ts-input
      [datepicker]="true"
      [openTo]="openTo"
    ></ts-input>
  `,
})
export class OpenTo {
  public openTo: undefined | Date = new Date(2018, 1, 1);

  @ViewChild(TsInputComponent, { static: true })
  inputComponent!: TsInputComponent;
}

@Component({
  template: `
    <ts-input
      [datepicker]="true"
      [minDate]="minDate"
      [maxDate]="maxDate"
    ></ts-input>
  `,
})
export class MinMaxDate {
  public minDate: undefined | Date = undefined;
  public maxDate: undefined | Date = undefined;

  @ViewChild(TsInputComponent, { static: true })
  inputComponent!: TsInputComponent;
}

@Component({
  template: `
    <ts-input
      [formControl]="formControl"
      [hideRequiredMarker]="hideRequiredMarker"
    ></ts-input>
  `,
})
export class AttrRequiredHidden {
  public formControl: FormControl = new FormControl(null, Validators.required);
  public hideRequiredMarker: boolean | undefined = false;
}

@Component({
  template: `
    <ts-input
      [mask]="mask"
      [formControl]="formControl"
      [type]="type"
    ></ts-input>
  `,
})
export class InputType {
  public mask: TsMaskShortcutOptions | undefined = 'number';
  public formControl = new FormControl();
  public type: TsInputTypes | undefined;

  @ViewChild(TsInputComponent, { static: true })
  inputComponent!: TsInputComponent;
}

@Component({
  template: `
    <ts-input
      [formControl]="formControl"
      [isClearable]="clearable"
      (cleared)="cleared($event)"
    ></ts-input>
  `,
})
export class Clearable {
  public clearable: boolean | undefined = undefined;
  public formControl = new FormControl();

  @ViewChild(TsInputComponent, { static: true })
  inputComponent!: TsInputComponent;
  // Must be overwritten with a spy in the test
  cleared = v => {};
}

@Component({
  template: `
    <ts-input
      [formControl]="formControl"
      [hasExternalFormField]="hasFormField"
    ></ts-input>
  `,
})
export class NoExternalFormField {
  public formControl = new FormControl();
  public hasFormField = true;

  @ViewChild(TsInputComponent, { static: true })
  inputComponent!: TsInputComponent;
}

@Component({ template: `<ts-input [formControl]="formControl" [hint]="hint"></ts-input>` })
export class Hint {
  public formControl = new FormControl();
  public hint: string | undefined = undefined;
}

@Component({ template: `<ts-input [formControl]="formControl"></ts-input>` })
export class AttrNotRequired {
  public formControl: FormControl = new FormControl(null);
}

@Component({ template: `<ts-input [formControl]="formControl"></ts-input>` })
export class FormControlAttrRequired {
  public formControl: FormControl = new FormControl(null, Validators.required);
}

@Component({ template: `<ts-input [formControl]="formControl" [isRequired]="required"></ts-input>` })
export class AttrInputRequired {
  public formControl: FormControl = new FormControl(null);
  public required = false;
}

@Component({ template: `<ts-input label="test label"></ts-input>` })
export class Label {
  @ViewChild(TsInputComponent, { static: true })
  inputComponent!: TsInputComponent;

  @ContentChild(TsFormFieldComponent)
  formFieldComponent!: TsFormFieldComponent;
}

@Component({
  template: `
    <ts-input
      [datepicker]="true"
      [dateFilter]="dateFilter"
    ></ts-input>
  `,
})
export class DateFilter {
  public dateFilter = undefined;

  @ViewChild(TsInputComponent, { static: true })
  inputComponent!: TsInputComponent;
}

@Component({
  template: `
    <ts-input
      [dateLocale]="myLocale"
      [openTo]="myDate"
      [datepicker]="true"
    ></ts-input>
  `,
})
export class DateLocale {
  myDate = new Date(2020, 3, 1);
  myLocale = 'en-US';
}

@Component({
  template: `
    <ts-input
      dateLocale="fa"
      [openTo]="myDate"
      [datepicker]="true"
    ></ts-input>
  `,
})
export class DateLocaleForeign {
  myDate = new Date(2020, 3, 1);
}
@Component({ template: `<ts-input [formControl]="formControl"></ts-input>` })
export class Autofill {
  public formControl = new FormControl();

  @ViewChild(TsInputComponent, { static: true })
  inputComponent!: TsInputComponent;
}

@Component({
  template: `
    <ts-input
      [formControl]="formControl"
      [mask]="mask"
      [maskSanitizeValue]="maskSanitizeValue"
      [maskAllowDecimal]="maskAllowDecimal"
      [label]="label"
    ></ts-input>
  `,
})
export class OnChanges {
  public formControl = new FormControl('foo');
  public mask: TsMaskShortcutOptions = 'number';
  public maskSanitizeValue = true;
  public maskAllowDecimal = true;
  public label = 'my first label';

  @ViewChild(TsInputComponent, { static: true })
  inputComponent!: TsInputComponent;
}

@Component({
  template: `
    <ts-input
      [formControl]="formControl"
      [isTextarea]="true"
      [textareaRows]="rows"
    ></ts-input>
  `,
})
export class Textarea {
  public formControl = new FormControl();
  public rows: undefined | number;

  @ViewChild(TsInputComponent, { static: true })
  inputComponent!: TsInputComponent;
}

@Component({ template: `<div *ngIf="show"><ts-input></ts-input></div>` })
export class ToggleInputComponent {
  @ViewChild(TsInputComponent)
  inputComponent!: TsInputComponent;
  public show = true;
}

@Component({
  template: `
    <ts-input
        [formControl]="formControl"
        [noValidationOrHint]="true"
    ></ts-input>
  `,
})
export class NoValidationOrHint {
  public formControl = new FormControl();
}

/**
 * NOTE: Currently all exported Components must belong to a module. So this is our useless module to avoid the build error.
 */
@NgModule({
  imports: [
    CommonModule,
    ReactiveFormsModule,
    TsInputModule,
  ],
  declarations: [
    AttrAutocapitalize,
    AttrAutocomplete,
    AttrAutofocus,
    AttrDisabled,
    AttrId,
    AttrInputRequired,
    AttrNotRequired,
    AttrReadonly,
    AttrRequiredHidden,
    AttrSpellcheck,
    Autocomplete,
    Autofill,
    Clearable,
    DateFilter,
    DateLocale,
    DateLocaleForeign,
    FormControlAttrRequired,
    Hint,
    InputType,
    Label,
    Mask,
    MaskDateFormat,
    MaskDecimal,
    MaskSanitize,
    MinMaxDate,
    MissingFormControl,
    NoExternalFormField,
    NoValidationOrHint,
    OnChanges,
    OpenTo,
    PostalMask,
    SimpleFormControl,
    StartingView,
    TabIndex,
    Textarea,
    Theme,
    ToggleInputComponent,
  ],
})
export class TsInputTestComponentsModule {}


text:
package com.mpush.api.service;

import java.util.concurrent.Future;

/**
 * Created by yxx on 2016/5/17.
 *
 * @author ohun@live.cn
 */
public interface Service {

    void start(Listener listener);

    void stop(Listener listener);

    Future<Boolean> start();

    Future<Boolean> stop();

    void init();

    boolean isRunning();

}


text:
{% load tagging_tags comments i18n %}

	  {{ object.title }}

{% trans "Written by" %}

{% for author in object.authors.all %}

			{{ author }}
		  {% if not forloop.last %}, {% endif %}

{% endfor %}

{% trans "Created on" %}

<time datetime="{{ object.creation_date|date:"c" }}" pubdate="pubdate" class="entry-date" title="{{ object.creation_date|date:"c" }}Z">{{ object.creation_date|date:"D d F Y"|capfirst }}</time>

{% trans "Category" %}

{% for category in object.categories.all %}

			{{ category }}
		  {% if not forloop.last %}, {% endif %}

{% endfor %}

{% if object.image %}

{{ object.title }}

{% endif %}

{{ object_content }}

{% trans "Tags" %}

{% tags_for_object object as tag_list %}{% for tag in tag_list %}

			{{ tag }}
		  {% if not forloop.last %}, {% endif %}

		  {% empty %}

{% trans "No tags" %}

		{% endfor %}

{% trans "Short url" %}

	  {% if object.short_url %}

		{{ object.short_url }}

	  {% else %}
	  {% trans "Unavailable" %}
	  {% endif %}

{% trans "Discussions" %}

	  {% with object.comments.count as comment_count %}
	  {% if comment_count %}

		{% blocktrans count comment_count as comment_count %}{{ comment_count }} comment{% plural %}{{ comment_count }} comments{% endblocktrans %}

	  {% else %}
		{% if object.comment_enabled %}
		{% trans "No comments yet." %}

		{% trans "Be first to comment!" %}

		{% else %}
		{% trans "Comments are closed." %}
		{% endif %}
	  {% endif %}
	  {% endwith %}
	  {% with object.pingbacks.count as pingback_count %}
	  {% if pingback_count %}
	  ,
		{% blocktrans count pingback_count as pingback_count %}{{ pingback_count }} pingback{% plural %}{{ pingback_count }} pingbacks{% endblocktrans %}

	  {% endif %}
	  {% endwith %}
	  {% with object.trackbacks.count as trackback_count %}
	  {% if trackback_count %}
	  ,
		{% blocktrans count trackback_count as trackback_count %}{{ trackback_count }} trackback{% plural %}{{ trackback_count }} trackbacks{% endblocktrans %}

	  {% endif %}
	  {% endwith %}


text:
namespace DotSee.AutoNode
{
    /// <summary>
    /// Holds rules for automatically creating nodes.
    /// </summary>
    public class Rule
    {
        public string CreatedDocTypeAlias { get; set; }
        public string DocTypeAliasToCreate { get; set; }
        public string NodeName { get; set; }
        public bool? BringNewNodeFirst { get; set; }
        public bool? OnlyCreateIfNoChildren { get; set; }
        public bool? CreateIfExistsWithDifferentName { get; set; }
        public string DictionaryItemForName { get; set; }
        public bool? KeepNewNodeUnpublished { get; set; }
        public string Blueprint { get; set; }

        /// <summary>
        /// Creates a new rule for automatically creating nodes.
        /// </summary>
        /// <param name="createdDocTypealias">The document type Alias to look for. The rule will be applied when a document of this type is published.</param>
        /// <param name="docTypeAliasToCreate">The document type to automatically create</param>
        /// <param name="nodeName">The name of the newly created document</param>
        /// <param name="bringNodeFirst">If this is set, then the node will be sorted in order to be first (as opposed to the default last position)</param>
        /// <param name="onlyCreateIfNoChildren">If this is set to true, then the new node will only be created if the node published hasn't already got any child nodes.</param>
        /// <param name="createIfExistsWithDifferentName">By default the rule does not create a node automatically only if another node of the same type with the same name already exists. By setting this parameter to false you can allow the creation of a node when one of the same type (but with a different name) already exists.</param>
        /// <param name="dictionaryItemForName">Applies the node's name based on the given dictionary entry (default entry: AutoNode.Name)</param>
        /// <param name="keepNewNodeUnpublished">Unpublishes the new node after creation</param>
        /// <param name="blueprint">The name of a content template (blueprint) to apply to the newly created document</param>
        public Rule(
            string createdDocTypealias,
            string docTypeAliasToCreate,
            string nodeName,
            bool? bringNodeFirst = false,
            bool? onlyCreateIfNoChildren = false,
            bool? createIfExistsWithDifferentName = true,
            string dictionaryItemForName = "AutoNode.Name",
            bool? keepNewNodeUnpublished = false,
            string blueprint = ""
            )
        {
            CreatedDocTypeAlias = createdDocTypealias;
            DocTypeAliasToCreate = docTypeAliasToCreate;
            NodeName = nodeName;
            BringNewNodeFirst = bringNodeFirst;
            OnlyCreateIfNoChildren = onlyCreateIfNoChildren;
            CreateIfExistsWithDifferentName = createIfExistsWithDifferentName;
            DictionaryItemForName = dictionaryItemForName;
            KeepNewNodeUnpublished = keepNewNodeUnpublished;
            Blueprint = blueprint;
        }
    }
}


text:
namespace theia {
namespace {

using Eigen::Vector3d;

// An estimator for computing a dominant plane from a set of 3D points.
class DominantPlaneEstimator : public Estimator<Vector3d, Plane> {
 public:
  DominantPlaneEstimator() {}

  // 3 non-collinear points are needed to determine a plane.
  double SampleSize() const { return 3; }

  // Estimates candidate dominant planes from three 3D points.
  bool EstimateModel(const std::vector<Vector3d>& points,
                     std::vector<Plane>* planes) const {
    // If the points are collinear, there are no possible solutions.
    static const double kTolerance = 1e-6;
    const Vector3d a = points[1] - points[0];
    const Vector3d b = points[2] - points[0];
    const Vector3d cross = a.cross(b);
    if (cross.squaredNorm() < kTolerance) {
      LOG(WARNING)
          << "The 3 world points are collinear! No solution for a plane "
             "exists.";
      return false;
    }
    Plane plane;
    plane.point = points[0];
    plane.unit_normal = cross.normalized();

    planes->emplace_back(plane);
    return true;
  }

  // The error for a point given a plane model is the point-to-plane distance.
  double Error(const Vector3d& point, const Plane& plane) const {
    return std::abs(plane.unit_normal.dot(point - plane.point));
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(DominantPlaneEstimator);
};

}  // namespace

bool EstimateDominantPlaneFromPoints(
    const RansacParameters& ransac_params,
    const RansacType& ransac_type,
    const std::vector<Vector3d>& points,
    Plane* plane,
    RansacSummary* ransac_summary) {
  DominantPlaneEstimator dominant_plane_estimator;
  std::unique_ptr<SampleConsensusEstimator<DominantPlaneEstimator> > ransac =
      CreateAndInitializeRansacVariant(ransac_type,
                                       ransac_params,
                                       dominant_plane_estimator);
  // Estimate the dominant plane.
  return ransac->Estimate(points, plane, ransac_summary);
}

}  // namespace theia


text:
'use strict';

var AppDispatcher = require('../dispatcher/AppDispatcher');
var VotesConstants = require('../constants/VotesConstants');
var api = require('../utils/api');

var VotesActions = {
  fetch: function () {
    api.votes.get(function (err, votes) {
      if (err) return console.error(err);
      VotesActions.set(votes);
    }.bind(this));
  },
  set: function (votes) {
    AppDispatcher.handleViewAction({
      actionType: VotesConstants.VOTES_SET,
      data: votes
    });
  },
  doVote: function() {
    api.votes.post(function (err) {
      if (err) console.error(err);
    });
  }
};

module.exports = VotesActions;


text:
package org.kuali.kra.irb.auth;

import org.kuali.coeus.sys.framework.workflow.KcWorkflowService;
import org.kuali.kra.infrastructure.PermissionConstants;
import org.kuali.kra.irb.actions.ProtocolAction;
import org.kuali.kra.irb.actions.ProtocolActionType;

/**
 * Is the user allowed to record committee decisions for a protocol?
 */
public class RecordCommitteeDecisionProtocolAuthorizer extends ProtocolAuthorizer {

    private KcWorkflowService kraWorkflowService;

    @Override
    public boolean isAuthorized(String userId, ProtocolTask task) {
        return kraWorkflowService.isInWorkflow(task.getProtocol().getProtocolDocument()) &&
                canExecuteAction(task.getProtocol(), ProtocolActionType.RECORD_COMMITTEE_DECISION) &&
               hasPermission(userId, task.getProtocol(), PermissionConstants.PERFORM_IRB_ACTIONS_ON_PROTO) &&
               canRecordCommitteeDecision(task.getProtocol().getLastProtocolAction());
    }

    /**
     *
     * record committee decision doesn't change the protocol status, after one record committee decision as approve, then
     * the approve screen comes up, this function prevents the record committee decision from remianing open after the action
     * has been done.
     * @param lastAction
     * @return
     */
    private boolean canRecordCommitteeDecision(ProtocolAction lastAction) {
        if(lastAction != null && !ProtocolActionType.RECORD_COMMITTEE_DECISION.equals(lastAction.getProtocolActionTypeCode())) {
            return true;
        }

        return false;
    }

    public KcWorkflowService getKraWorkflowService() {
        return kraWorkflowService;
    }

    public void setKraWorkflowService(KcWorkflowService kraWorkflowService) {
        this.kraWorkflowService = kraWorkflowService;
    }
}


text:
package main.java.de.c4.model.messages;

import java.io.Serializable;

public class SecondClientStarted implements Serializable {
	private static final long serialVersionUID = 1L;
	public int damnBufferUnderflow = 0;
}


text:
import { inject, delay, injectable } from "tsyringe";
import Operator from "../Operator";
import OperatorFactory from "../OperatorFactory";
import OperatorFactoryChain from "../OperatorFactoryChain";
import CommandOperatorFactoryChain from "./CommandOperatorFactoryChain";
import InternalOperatorFactoryChain from "./InternalOperatorFactoryChain";
import NavigateOperatorFactoryChain from "./NavigateOperatorFactoryChain";
import RepeatOperatorFactoryChain from "./RepeatOperatorFactoryChain";
import TabOperatorFactoryChain from "./TabOperatorFactoryChain";
import ZoomOperatorFactoryChain from "./ZoomOperatorFactoryChain";
import FindOperatorFactoryChain from "./FindOperatorFactoryChain";
import * as operations from "../../../shared/operations";

@injectable()
export class OperatorFactoryImpl implements OperatorFactory {
  private readonly factoryChains: OperatorFactoryChain[];

  constructor(
    commandOperatorFactoryChain: CommandOperatorFactoryChain,
    internalOperatorFactoryChain: InternalOperatorFactoryChain,
    navigateOperatorFactoryChain: NavigateOperatorFactoryChain,
    tabOperatorFactoryChain: TabOperatorFactoryChain,
    zoomOperatorFactoryChain: ZoomOperatorFactoryChain,
    findOperatorFactoryChain: FindOperatorFactoryChain,
    @inject(delay(() => RepeatOperatorFactoryChain))
    repeatOperatorFactoryChain: RepeatOperatorFactoryChain
  ) {
    this.factoryChains = [
      commandOperatorFactoryChain,
      internalOperatorFactoryChain,
      navigateOperatorFactoryChain,
      repeatOperatorFactoryChain,
      tabOperatorFactoryChain,
      zoomOperatorFactoryChain,
      findOperatorFactoryChain,
    ];
  }

  create(op: operations.Operation): Operator {
    for (const chain of this.factoryChains) {
      const operator = chain.create(op);
      if (operator !== null) {
        return operator;
      }
    }
    throw new Error("unknown operation: " + op.type);
  }
}


text:
title: Wie du mit Grav beginnst!
date: 09:55 07-07-2015
headline: Grav ist sehr einfach zu installieren, folge einfach …
taxonomy:
    category: blog
    tag: [grav]
---

Grav ist sehr einfach zu installieren. Weil es keine Datenbank benötigt – die Installation erfolgt durch das entpacken des Grav Basis-System (oder Basis-System mit einem Template) und das ablegen in das Server Verzeichnis – schon ist Grav installiert.

Das einzige was Grav benötigt ist das der Server mit einer PHP-Version von 5.4 oder höher läuft. Du kannst Grav mit Apache, Nginx, LiteSpeed, IIS, etc. nutzen.

---

## Option 1: Installieren mit dem Download der ZIP-Datei

Der einfachste Weg um Grav zu installieren ist die ZIP-Datei herunter zu laden und zu installieren::

1. Lade dir einfach die letzte Version von Grav unter [Downloads](http://getgrav.org/downloads) herunter.
2. Entpacke die ZIP-Datei und lege Sie in deinem Root Verzeichnis auf dem Server ab `~/webroot/grav`.

Wenn du die die ZIP-Datei herunter geladen hast und in dein Web-Verzeichnis kopieren möchtest, kopiere bitte den **gesamten Ordner**, das heisst mit allen versteckten Dateien (wie z.B. '.htaccess'). Diese wird beim normalen kopieren von Dateien nicht kopiert. Ohne diese versteckten Dateien kann es aber zu Fehler der Installation kommen.

---

## Option 2: Das installieren über GitHub

Die alternative zum Download der ZIP-Datei ist die Installation über Github – ein ausführendes Script erledigt die Installation:

Kopiert wird die aktulle Version Version von Github in ein Web-Verzeichnis Eurer Wahl – wie z.B. `~/webroot/grav`. Öffnet das `Terminal` or `Befehlszeile`

```text
$ cd ~/webroot
$ git clone https://github.com/getgrav/grav.git
```

Installiere **plugins** und Templates **dependencies** mit der Funktion [Grav CLI application](http://learn.getgrav.org/advanced/grav-cli) `bin/grav`:

```text
$ cd ~/webroot/grav
$ bin/grav install
This will automatically clone the required dependencies from GitHub directly into this Grav installation.
```

Du findest mehr Informationen über das installieren und aktualisieren in der Grav Dokumentaion [official documentation](http://learn.getgrav.org/basics/installation).