text:
#ifndef TENSORFLOW_CORE_KERNELS_QUANTIZE_AND_DEQUANTIZE_OP_H_
#define TENSORFLOW_CORE_KERNELS_QUANTIZE_AND_DEQUANTIZE_OP_H_

#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_types.h"
#include "tensorflow/core/kernels/cwise_ops.h"
#include "tensorflow/core/platform/types.h"

namespace tensorflow {

enum QuantizerRoundMode {
  // Round half up: if the fraction of y is exactly 0.5, then
  // round(y) = y + 0.5
  // E.g., -5.5 gets rounded to -5, -5.4 goes to -5,
  // 5.4 goes to 5, and 5.5 goes to 6.
  ROUND_HALF_UP,
  // Round half to even: if the fraction of y is exactly 0.5, then round(y) is
  // the nearest even integer to y.
  // E.g., 23.5 gets rounded to 24, 24.5 gets rounded to 24, while -23.5 becomes
  // -24, and -24.5 gets rounded to 24.
  ROUND_HALF_TO_EVEN,
};

namespace functor {

// TODO(pauldonnelly): 'signed_input' should really be called 'signed_output'.

template <typename Device, typename T>
struct QuantizeAndDequantizeOneScaleFunctor {
  void operator()(const Device& d, typename TTypes<T>::ConstVec input,
                  bool signed_input, int num_bits, bool range_given,
                  Tensor* input_min_tensor, Tensor* input_max_tensor,
                  QuantizerRoundMode round_mode, bool narrow_range,
                  typename TTypes<T>::Vec output);
};

template <typename Device, typename T>
struct QuantizeAndDequantizePerChannelFunctor {
  void operator()(const Device& d, typename TTypes<T, 3>::ConstTensor input,
                  bool signed_input, int num_bits, bool range_given,
                  Tensor* input_min_tensor, Tensor* input_max_tensor,
                  QuantizerRoundMode round_mode, bool narrow_range,
                  typename TTypes<T, 3>::Tensor output);
};

template <typename Device, typename T>
struct QuantizeAndDequantizeOneScaleGradientFunctor {
  void operator()(const Device& d, typename TTypes<T>::ConstFlat gradient,
                  typename TTypes<T>::ConstFlat input,
                  typename TTypes<T>::ConstScalar input_min,
                  typename TTypes<T>::ConstScalar input_max,
                  typename TTypes<T>::Flat input_backprop,
                  typename TTypes<T>::Scalar input_min_backprop,
                  typename TTypes<T>::Scalar input_max_backprop);
};

template <typename Device, typename T>
struct QuantizeAndDequantizePerChannelGradientFunctor {
  void operator()(const Device& d, typename TTypes<T, 3>::ConstTensor gradient,
                  typename TTypes<T, 3>::ConstTensor input,
                  const Tensor* input_min_tensor,
                  const Tensor* input_max_tensor,
                  typename TTypes<T, 3>::Tensor input_backprop,
                  typename TTypes<T>::Flat input_min_backprop,
                  typename TTypes<T>::Flat input_max_backprop);
};

// The implementation below runs on both CPU and GPU.
template <typename Device, typename T, typename Func,
          typename Vec = typename TTypes<T>::Vec,
          typename ConstVec = typename TTypes<T>::ConstVec>
void ClampScaleAndRound(const Device& d, ConstVec input, T min_range,
                        T max_range, T scale, T inverse_scale, Func round_func,
                        Vec output) {
  output.device(d) = (input.cwiseMin(max_range).cwiseMax(min_range) * scale)
                         .unaryExpr(round_func) *
                     inverse_scale;
}

// The implementation below runs on both CPU and GPU.
template <typename Device, typename T, typename Vec = typename TTypes<T>::Vec,
          typename ConstVec = typename TTypes<T>::ConstVec>
void ClampScaleAndRound(const Device& d, ConstVec input, T min_range,
                        T max_range, T scale, T inverse_scale,
                        QuantizerRoundMode round_mode, Vec output) {
  switch (round_mode) {
    case ROUND_HALF_TO_EVEN:
      ClampScaleAndRound(d, input, min_range, max_range, scale, inverse_scale,
                         Eigen::internal::scalar_round_half_to_even_op<T>(),
                         output);
      break;
    case ROUND_HALF_UP:
      ClampScaleAndRound(d, input, min_range, max_range, scale, inverse_scale,
                         Eigen::internal::scalar_round_up_op<T>(), output);
      break;
  }
}

// The implementation below runs on both CPU and GPU.
template <typename Device, typename T, typename Func,
          typename Vec = typename TTypes<T>::Vec,
          typename ConstVec = typename TTypes<T>::ConstVec>
void ScaleAndRound(const Device& d, ConstVec input, T scale, T inverse_scale,
                   Func round_func, Vec output) {
  output.device(d) = (input * scale).unaryExpr(round_func) * inverse_scale;
}

// The implementation below runs on both CPU and GPU.
template <typename Device, typename T, typename Vec = typename TTypes<T>::Vec,
          typename ConstVec = typename TTypes<T>::ConstVec>
void ScaleAndRound(const Device& d, ConstVec input, T scale, T inverse_scale,
                   QuantizerRoundMode round_mode, Vec output) {
  switch (round_mode) {
    case ROUND_HALF_TO_EVEN:
      ScaleAndRound(d, input, scale, inverse_scale,
                    Eigen::internal::scalar_round_half_to_even_op<T>(), output);
      break;
    case ROUND_HALF_UP:
      ScaleAndRound(d, input, scale, inverse_scale,
                    Eigen::internal::scalar_round_up_op<T>(), output);
      break;
  }
}

template <typename T>
void ComputeQuantizationRange(bool signed_input, int num_bits,
                              QuantizerRoundMode round_mode, bool narrow_range,
                              T* min_range, T* max_range, T* scale,
                              T* inverse_scale) {
  // Calculate the range for the simulated integer quantization:
  // e.g. [-127,127] for signed = true, narrow_range = true, num_bits = 8,
  // or [-128,127] for signed = true, narrow_range = false, num_bits = 8,
  // or [0, 255] for signed = false, num_bits = 8.
  const int64_t min_quantized =
      signed_input ? narrow_range ? -(1ULL << (num_bits - 1)) + 1
                                  : -(1ULL << (num_bits - 1))
                   : 0;
  const int64_t max_quantized =
      signed_input ? (1ULL << (num_bits - 1)) - 1 : (1ULL << num_bits) - 1;
  // Determine the maximum scaling factor that would scale
  // [min_range, max_range] to not exceed [min_quantized, max_quantized],
  // while keeping 0 unchanged.
  const T scale_from_min_side = (min_quantized * *min_range > 0)
                                    ? min_quantized / *min_range
                                    : std::numeric_limits<T>::max();
  const T scale_from_max_side = (max_quantized * *max_range > 0)
                                    ? max_quantized / *max_range
                                    : std::numeric_limits<T>::max();

  // Note: Avoids changing the side of the range that determines scale.
  if (scale_from_min_side < scale_from_max_side) {
    *scale = scale_from_min_side;
    *inverse_scale = *min_range / min_quantized;
    *max_range = max_quantized * *inverse_scale;
  } else {
    *scale = scale_from_max_side;
    *inverse_scale = *max_range / max_quantized;
    *min_range = min_quantized * *inverse_scale;
  }
}

// The implementation below runs on both CPU and GPU.
template <typename Device, typename T>
struct QuantizeAndDequantizeOneScaleImpl {
  static void Compute(const Device& d, typename TTypes<T>::ConstVec input,
                      bool signed_input, int num_bits, bool range_given,
                      Tensor* input_min_tensor, Tensor* input_max_tensor,
                      QuantizerRoundMode round_mode, bool narrow_range,
                      typename TTypes<T>::Vec output) {
    T min_range;
    T max_range;
    auto input_min = input_min_tensor->scalar<T>();
    auto input_max = input_max_tensor->scalar<T>();
    if (!range_given) {
      input_min.device(d) = input.minimum();
      input_max.device(d) = input.maximum();
      d.memcpyDeviceToHost(&min_range, input_min.data(), sizeof(T));
      d.memcpyDeviceToHost(&max_range, input_max.data(), sizeof(T));
    } else {
      // Copy the range values from their respective tensors on the host.
      min_range = input_min_tensor->scalar<T>()();
      max_range = input_max_tensor->scalar<T>()();
    }

    T scale, inverse_scale;
    ComputeQuantizationRange(signed_input, num_bits, round_mode, narrow_range,
                             &min_range, &max_range, &scale, &inverse_scale);

    if (range_given) {
      // Note: The clamping here is to avoid overflow in the quantized type.
      // The semantics of the op does not guarantee to clamp to the specified
      // min_range and max_range - because we may have changed either min_range
      // or max_range.
      ClampScaleAndRound(d, input, min_range, max_range, scale, inverse_scale,
                         round_mode, output);
    } else {
      ScaleAndRound(d, input, scale, inverse_scale, round_mode, output);
    }
  }
};

// The implementation below runs on both CPU and GPU.

template <typename Device, typename T>
struct QuantizeAndDequantizePerChannelImpl {
  static void Compute(const Device& d, typename TTypes<T, 3>::ConstTensor input,
                      bool signed_input, int num_bits, bool range_given,
                      Tensor* input_min_tensor, Tensor* input_max_tensor,
                      QuantizerRoundMode round_mode, bool narrow_range,
                      typename TTypes<T, 3>::Tensor output) {
    using Index = typename tensorflow::TTypes<T>::ConstTensor::Index;
    int num_channels = input.dimension(1);
    auto input_min = input_min_tensor->vec<T>();
    auto input_max = input_max_tensor->vec<T>();
    std::vector<T> min_range(num_channels);
    std::vector<T> max_range(num_channels);

    if (!range_given) {
      Eigen::IndexList<Eigen::type2index<0>, Eigen::type2index<2> > reduce_dims;
      input_min.device(d) = input.minimum(reduce_dims);
      input_max.device(d) = input.maximum(reduce_dims);
      d.memcpyDeviceToHost(min_range.data(), input_min.data(),
                           num_channels * sizeof(T));
      d.memcpyDeviceToHost(max_range.data(), input_max.data(),
                           num_channels * sizeof(T));
    } else {
      // Copy the range values from their respective tensors on the host.
      std::memcpy(min_range.data(), input_min_tensor->vec<T>().data(),
                  num_channels * sizeof(T));
      std::memcpy(max_range.data(), input_max_tensor->vec<T>().data(),
                  num_channels * sizeof(T));
    }

    for (Index i = 0; i < num_channels; ++i) {
      const auto input_chip = input.template chip<1>(i);
      auto output_chip = output.template chip<1>(i);

      T scale, inverse_scale;
      ComputeQuantizationRange(signed_input, num_bits, round_mode, narrow_range,
                               &min_range[i], &max_range[i], &scale,
                               &inverse_scale);
      if (range_given) {
        ClampScaleAndRound(d, input_chip, min_range[i], max_range[i], scale,
                           inverse_scale, round_mode, output_chip);
      } else {
        ScaleAndRound(d, input_chip, scale, inverse_scale, round_mode,
                      output_chip);
      }
    }
  }
};

template <typename Device, typename T>
struct QuantizeAndDequantizeOneScaleGradientImpl {
  static void Compute(const Device& d, typename TTypes<T>::ConstFlat gradient,
                      typename TTypes<T>::ConstFlat input,
                      typename TTypes<T>::ConstScalar input_min,
                      typename TTypes<T>::ConstScalar input_max,
                      typename TTypes<T>::Flat input_backprop,
                      typename TTypes<T>::Scalar input_min_backprop,
                      typename TTypes<T>::Scalar input_max_backprop) {
    const T min_val = input_min();
    const T max_val = input_max();
    const auto in_range =
        (input >= min_val && input <= max_val)
            .select(input.constant(1.0f), input.constant(0.0f));
    input_backprop.device(d) = gradient * in_range;
    input_min_backprop.device(d) = input_min_backprop.constant(0.0f);
    input_max_backprop.device(d) = input_max_backprop.constant(0.0f);
  }
};

template <typename Device, typename T>
struct QuantizeAndDequantizePerChannelGradientImpl {
  static void Compute(const Device& d,
                      typename TTypes<T, 3>::ConstTensor gradient,
                      typename TTypes<T, 3>::ConstTensor input,
                      const Tensor* input_min_tensor,
                      const Tensor* input_max_tensor,
                      typename TTypes<T, 3>::Tensor input_backprop,
                      typename TTypes<T>::Flat input_min_backprop,
                      typename TTypes<T>::Flat input_max_backprop) {
    using Index = typename tensorflow::TTypes<T>::ConstTensor::Index;
    auto input_min = input_min_tensor->vec<T>();
    auto input_max = input_max_tensor->vec<T>();
    int num_channels = input.dimension(1);
    for (Index i = 0; i < num_channels; ++i) {
      const auto gradient_chip = gradient.template chip<1>(i);
      const auto input_chip = input.template chip<1>(i);
      const T min_val = input_min(i);
      const T max_val = input_max(i);
      const auto in_range =
          (input_chip >= min_val && input_chip <= max_val)
              .select(input_chip.constant(1.0f), input_chip.constant(0.0f));
      input_backprop.template chip<1>(i).device(d) = gradient_chip * in_range;
    }
    input_min_backprop.device(d) = input_min_backprop.constant(0.0f);
    input_max_backprop.device(d) = input_max_backprop.constant(0.0f);
  }
};

}  // end of namespace functor
}  // end of namespace tensorflow

#endif  // TENSORFLOW_CORE_KERNELS_QUANTIZE_AND_DEQUANTIZE_OP_H_


text:
AbuseTest = TestCase("AbuseTest");

(function() {
    var parse = ZWOBBLE.abuse.parse;
    var generate = ZWOBBLE.abuse.generate;
    var generateAll = ZWOBBLE.abuse.generateAll;
    var terminal = ZWOBBLE.abuse.terminal;
    var nonTerminal = ZWOBBLE.abuse.nonTerminal;

    var assertNonTerminal = function(actual, name) {
        assertTrue(actual.isNonTerminal);
        assertEquals(name, actual.name);
    };

    var assertTerminal = function(actual, text) {
        assertTrue(actual.isTerminal);
        assertEquals(text, actual.text);
    };

    var assertRule = function(actual, nonTerminalName, right) {
        var i;
        assertNonTerminal(actual.left, nonTerminalName);
        assertEquals(right.length, actual.right.length);
        for (i = 0; i < right.length; i += 1) {
            if (right[i].isTerminal) {
                assertTerminal(actual.right[i], right[i].text);
            } else {
                assertNonTerminal(actual.right[i], right[i].name);
            }
        }
    };

    // Parsing

    AbuseTest.prototype.testCanParseSourceWithOnlyWhitespace = function() {
        var rules = parse("\n\n\n\n\n\r\t\t \n\n     \r\n\n").rules;
        assertEquals(0, rules.length);
    };

    AbuseTest.prototype.testCanReadRuleForTerminalToNonTerminal = function() {
        var rules = parse("$SENTENCE -> I hate you!").rules;
        assertEquals(1, rules.length);
        assertRule(rules[0], "SENTENCE", [terminal("I hate you!")]);
    };

    AbuseTest.prototype.testCanReadMultipleRulesSeparatedByNewLines = function() {
        var rules = parse("$SENTENCE -> I hate you!\n$SENTENCE -> You smell!").rules;
        assertEquals(2, rules.length);
        assertRule(rules[0], "SENTENCE", [terminal("I hate you!")]);
        assertRule(rules[1], "SENTENCE", [terminal("You smell!")]);
    };

    AbuseTest.prototype.testWhitespaceIsTrimmedFromRight = function() {
        var rules = parse("$SENTENCE -> I hate you!   \t\t  ").rules;
        assertEquals(1, rules.length);
        assertRule(rules[0], "SENTENCE", [terminal("I hate you!")]);
    };

    AbuseTest.prototype.testFinalTerminalIsOnlyTrimmedOnTheRight = function() {
        var rules = parse("$VERY -> $VERY very").rules;
        assertRule(rules[0], "VERY", [nonTerminal("VERY"), terminal(" very")]);
    };

    AbuseTest.prototype.testEmptyTerminalsAreNotProducedByRules = function() {
        var rules = parse("$SENTENCE -> $INSULT").rules;
        assertRule(rules[0], "SENTENCE", [nonTerminal("INSULT")]);
    };

    AbuseTest.prototype.testIgnoresBlankLines = function() {
        var rules = parse("\n    \t\n\n$SENTENCE -> I hate you!\n     \n\n$SENTENCE -> You smell!\n\n\n").rules;
        assertEquals(2, rules.length);
        assertRule(rules[0], "SENTENCE", [terminal("I hate you!")]);
        assertRule(rules[1], "SENTENCE", [terminal("You smell!")]);
    };

    AbuseTest.prototype.testCanReadNonTerminalsOnRight = function() {
        var rules = parse("$SENTENCE -> You're as $ADJ as a $ANIMAL").rules;
        assertEquals(1, rules.length);
        assertRule(rules[0], "SENTENCE",
                   [terminal("You're as "), nonTerminal("ADJ"),
                    terminal(" as a "), nonTerminal("ANIMAL")]);
    };

    AbuseTest.prototype.testNonTerminalsAreAlphanumericAndUnderscoresOnly = function() {
        var rules = parse("$SENTENCE -> You smell of $Smell2.").rules;
        assertEquals(1, rules.length);
        assertRule(rules[0], "SENTENCE", [terminal("You smell of "), nonTerminal("Smell2"), terminal(".")]);
    };

    AbuseTest.prototype.testCanUseBracesToIndicateNonTerminals = function() {
        var rules = parse("$SENTENCE -> You're ${RUDE_ADJ}er than I thought").rules;
        assertEquals(1, rules.length);
        assertRule(rules[0], "SENTENCE", [terminal("You're "), nonTerminal("RUDE_ADJ"), terminal("er than I thought")]);
    };

    AbuseTest.prototype.testAddsErrorWithLineNumberIfArrowIsMissing = function() {
        var errors = parse("\n\n$SENTENCE - You're ${RUDE_ADJ}er than I thought\n" +
                           "$RUDE_ADJ ->\n" +
                           "$SENTENCE -> $RUDE_ADJ").errors;
        assertEquals(1, errors.length);
        assertEquals("Missing symbol on line 3: ->", errors[0].str);
        assertEquals(ZWOBBLE.abuse.errors.missingArrow, errors[0].type);
        assertEquals(3, errors[0].lineNumber);
    };

    AbuseTest.prototype.testAddsErrorWithLineNumberIfClosingBraceIsMissing = function() {
        var errors = parse("\n\n$SENTENCE -> You're ${RUDE_ADJer than I thought\n" +
                           "$SENTENCE ->\n").errors;
        assertEquals(1, errors.length);
        assertEquals("Missing closing brace on line 3 (opening brace at character 22)", errors[0].str);
        assertEquals(ZWOBBLE.abuse.errors.missingClosingBrace, errors[0].type);
        assertEquals(3, errors[0].lineNumber);
        assertEquals(22, errors[0].openingBraceCharacterNumber);
    };

    AbuseTest.prototype.testAddsErrorWithLineNumberIfClosingBraceForSecondVariableIsMissing = function() {
        var errors = parse("\n\n$SENTENCE -> You're ${RUDE_ADJ}er than ${OBJ\n" +
                           "$SENTENCE ->\n\n").errors;
        assertEquals(1, errors.length);
        assertEquals("Missing closing brace on line 3 (opening brace at character 41)", errors[0].str);
    };

    AbuseTest.prototype.testAddsErrorIfNonTerminalIsUsedWithNoMatchingProductionRule = function() {
        var errors = parse("\n\n$SENTENCE -> $INSULT\n\n").errors;
        assertEquals(1, errors.length);
        assertEquals("No production rule for non-terminal $INSULT (line 3, character 14)", errors[0].str);
        assertEquals(ZWOBBLE.abuse.errors.noProductionRule, errors[0].type);
        assertEquals("INSULT", errors[0].nonTerminal);
        assertEquals(3, errors[0].lineNumber);
        assertEquals(14, errors[0].characterNumber);
    };

    AbuseTest.prototype.testAddsErrorIfSentenceHasNoProductionRule = function() {
        var errors = parse("").errors;
        assertEquals(1, errors.length);
        assertEquals("No production rule for non-terminal $SENTENCE", errors[0].str);
        assertEquals(ZWOBBLE.abuse.errors.noProductionRule, errors[0].type);
        assertEquals("SENTENCE", errors[0].nonTerminal);
    };

    AbuseTest.prototype.testAddsErrorIfProductionRuleIsNeverUsed = function() {
        var errors = parse("$SENTENCE -> \n$RUDE_ADJ -> ugly").errors;
        assertEquals(1, errors.length);
        assertEquals("Production rule with start symbol $RUDE_ADJ is never used (line 2)", errors[0].str);
        assertEquals(ZWOBBLE.abuse.errors.ruleNeverUsed, errors[0].type);
        assertEquals(2, errors[0].lineNumber);
        assertEquals("RUDE_ADJ", errors[0].start);
    };

    // Generation

    var staticSelector = function(choices) {
        return function(length) {
            return choices.shift();
        };
    };

    AbuseTest.prototype.testCanGenerateSentenceFromSimpleRule = function() {
        var rules = parse("$SENTENCE -> I hate you!").rules;
        assertEquals("I hate you!", generate(rules, staticSelector([0])).str);
    };

    AbuseTest.prototype.testUsesSelectorToPickRuleWhenThereAreManyPossibleRules = function() {
        var rules = parse("$SENTENCE -> I hate you!\n$SENTENCE -> Go away!").rules;
        assertEquals("I hate you!", generate(rules, staticSelector([0])).str);
        assertEquals("Go away!", generate(rules, staticSelector([1])).str);
    };

    AbuseTest.prototype.testCanUseIntermediateRules = function() {
        var rules = parse("$SENTENCE -> You smell of $SMELL\n" +
                          "$SMELL -> elderberries\n" +
                          "$SMELL -> dogfood").rules;
        assertEquals("You smell of elderberries", generate(rules, staticSelector([0, 0])).str);
        assertEquals("You smell of dogfood", generate(rules, staticSelector([0, 1])).str);
    };

    AbuseTest.prototype.testGenerationSequenceIsIncludedInGeneratedSentence = function() {
        var rules = parse("$SENTENCE -> You're as $RUDE_ADJ as $ANIMAL\n" +
                          "$RUDE_ADJ -> smelly\n" +
                          "$RUDE_ADJ -> stupid\n" +
                          "$ANIMAL -> a dog\n" +
                          "$ANIMAL -> a donkey").rules,
            generationSequence = generate(rules, staticSelector([0, 1, 0])).sequence;

        assertEquals(0, generationSequence[0]);
        assertEquals(1, generationSequence[1]);
        assertEquals(0, generationSequence[2]);
        assertEquals(3, generationSequence.length);
    };

    AbuseTest.prototype.testSentenceGenerationResortsToPickingSentenceRandomlyFromAllSentencesIfMaximumDepthIsReached = function() {
        var rules = parse("$SENTENCE -> B\n" +
                          "$SENTENCE -> A $SENTENCE").rules;
        assertEquals("A A B", generate(rules, staticSelector([1, 1, 1, 2]), 3).str);
    };

    AbuseTest.prototype.testSentenceGenerationResortsToPickingSentenceRandomlyFromAllSentencesIfNonTerminalCannotBeExpanded = function() {
        var rules = parse("$SENTENCE -> $RUDE_WORD\n" +
                          "$SENTENCE -> Go away!").rules;
        assertEquals("Go away!", generate(rules, staticSelector([0, 0])).str);
    };

    AbuseTest.prototype.testSentenceGenerationReturnsUndefinedIfTheSelectorReturnsUndefined = function() {
        var rules = parse("$SENTENCE -> Go away\n$SENTENCE -> Shut your face$").rules;
        assertEquals(undefined, generate(rules, staticSelector([undefined])));
    };

    AbuseTest.prototype.testSentenceGenerationReturnsUndefinedIfTheSelectorReturnsAnOutOfRangeIndex = function() {
        var rules = parse("$SENTENCE -> Go away\n$SENTENCE -> Shut your face$").rules;
        assertEquals(undefined, generate(rules, staticSelector([-1])));
        assertEquals(undefined, generate(rules, staticSelector([2])));
    };

    AbuseTest.prototype.testCanGenerateEmptySentence = function() {
        var rules = parse("$SENTENCE -> ").rules;
        assertEquals("", generate(rules, staticSelector([0])).str);
    };

    AbuseTest.prototype.testCanGenerateAllSentences = function() {
        var rules = parse("$SENTENCE -> I hate you!\n" +
                          "$SENTENCE -> You smell of $SMELL\n" +
                          "$SMELL -> elderberries\n" +
                          "$SMELL -> dogfood\n" +
                          "$SENTENCE -> You're as $RUDE_ADJ as my $PET\n" +
                          "$RUDE_ADJ -> ugly\n" +
                          "$RUDE_ADJ -> stupid\n" +
                          "$PET -> rat\n" +
                          "$PET -> dog\n").rules;
        var results = generateAll(rules);
        assertEquals(7, results.length);
        assertEquals("I hate you!", results[0].str);
        assertEquals("You smell of elderberries", results[1].str);
        assertEquals("You smell of dogfood", results[2].str);
        assertEquals("You're as ugly as my rat", results[3].str);
        assertEquals("You're as ugly as my dog", results[4].str);
        assertEquals("You're as stupid as my rat", results[5].str);
        assertEquals("You're as stupid as my dog", results[6].str);
    };

    AbuseTest.prototype.testGenerationSequenceIsRecordedWhenGeneratingAllSentences = function() {
        var rules = parse("$SENTENCE -> I hate you!\n" +
                          "$SENTENCE -> You smell of $SMELL\n" +
                          "$SMELL -> elderberries\n" +
                          "$SMELL -> dogfood\n" +
                          "$SENTENCE -> You're as $RUDE_ADJ as my $PET\n" +
                          "$RUDE_ADJ -> ugly\n" +
                          "$RUDE_ADJ -> stupid\n" +
                          "$PET -> rat\n" +
                          "$PET -> dog\n").rules;
        var results = generateAll(rules);
        assertEquals(7, results.length);
        var generationSequence = results[4].sequence;
        assertEquals(2, generationSequence[0]);
        assertEquals(0, generationSequence[1]);
        assertEquals(1, generationSequence[2]);

        assertEquals(3, generationSequence.length);
    };

    AbuseTest.prototype.testSettingDepthOnGenerateAllLimitsRecursionDepth = function() {
        var rules = parse("$SENTENCE -> B\n" +
                          "$SENTENCE -> A $SENTENCE").rules;
        var results = generateAll(rules, 3);

        assertEquals("B", results[0].str);
        assertEquals("A B", results[1].str);
        assertEquals("A A B", results[2].str);
        assertEquals(3, results.length);
    };

    AbuseTest.prototype.testEmptyRuleSetGeneratesNoSentences = function() {
        var rules = parse("").rules;
        var results = generateAll(rules);
        assertEquals(0, results.length);
    };
})();

redpajama_set_name: RedPajamaGithub


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

Imports Google.Api.Ads.AdWords.Lib
Imports Google.Api.Ads.AdWords.v201809

Imports DayOfWeek = Google.Api.Ads.AdWords.v201809.DayOfWeek

Namespace Google.Api.Ads.AdWords.Examples.VB.v201809
    ''' <summary>
    ''' This code example adds sitelinks to a campaign. To create a campaign,
    ''' run AddCampaign.vb.
    ''' </summary>
    Public Class AddSitelinks
        Inherits ExampleBase

        ''' <summary>
        ''' Main method, to run this code example as a standalone application.
        ''' </summary>
        ''' <param name="args">The command line arguments.</param>
        Public Shared Sub Main(ByVal args As String())
            Dim codeExample As New AddSitelinks
            Console.WriteLine(codeExample.Description)
            Try
                Dim campaignId As Long = Long.Parse("INSERT_CAMPAIGN_ID_HERE")
                codeExample.Run(New AdWordsUser, campaignId)
            Catch e As Exception
                Console.WriteLine("An exception occurred while running this code example. {0}",
                                  ExampleUtilities.FormatException(e))
            End Try
        End Sub

        ''' <summary>
        ''' Returns a description about the code example.
        ''' </summary>
        Public Overrides ReadOnly Property Description() As String
            Get
                Return _
                    "This code example adds sitelinks to a campaign. To create a campaign, run " &
                    "AddCampaign.vb."
            End Get
        End Property

        ''' <summary>
        ''' Runs the code example.
        ''' </summary>
        ''' <param name="user">The AdWords user.</param>
        ''' <param name="campaignId">Id of the campaign with which sitelinks are associated.
        ''' </param>
        Public Sub Run(ByVal user As AdWordsUser, ByVal campaignId As Long)
            Using campaignExtensionSettingService As CampaignExtensionSettingService =
                DirectCast(user.GetService(AdWordsService.v201809.CampaignExtensionSettingService),
                           CampaignExtensionSettingService)

                Dim customerService As CustomerService =
                        DirectCast(user.GetService(AdWordsService.v201809.CustomerService),
                                   CustomerService)

                ' Find the matching customer and its time zone. The getCustomers method
                ' will return a single Customer object corresponding to the session's
                ' clientCustomerId.
                Dim customer As Customer = customerService.getCustomers()(0)
                Console.WriteLine("Found customer ID {0:###-###-####} with time zone '{1}'.",
                                  customer.customerId, customer.dateTimeZone)

                Dim extensions As New List(Of ExtensionFeedItem)

                ' Create your sitelinks.
                Dim sitelink1 As New SitelinkFeedItem()
                sitelink1.sitelinkText = "Store Hours"
                sitelink1.sitelinkFinalUrls = New UrlList()
                sitelink1.sitelinkFinalUrls.urls = New String() _
                    {"http://www.example.com/storehours"}
                extensions.Add(sitelink1)

                Dim startOfThanksGiving As New DateTime(DateTime.Now.Year, 11, 20, 0, 0, 0)
                Dim endOfThanksGiving As New DateTime(DateTime.Now.Year, 11, 27, 23, 59, 59)

                ' Add check to make sure we don't create a sitelink with end date in the
                ' past.
                If DateTime.Now < endOfThanksGiving Then
                    ' Show the Thanksgiving specials link only from 20 - 27 Nov.
                    Dim sitelink2 As New SitelinkFeedItem()
                    sitelink2.sitelinkText = "Thanksgiving Specials"
                    sitelink2.sitelinkFinalUrls = New UrlList()
                    sitelink2.sitelinkFinalUrls.urls = New String() _
                        {"http://www.example.com/thanksgiving"}

                    sitelink2.startTime = String.Format("{0}1120 000000 {1}", DateTime.Now.Year,
                                                        customer.dateTimeZone)
                    sitelink2.endTime = String.Format("{0}1127 235959 {1}", DateTime.Now.Year,
                                                      customer.dateTimeZone)

                    ' Target this sitelink for United States only. See
                    ' https://developers.google.com/adwords/api/docs/appendix/geotargeting
                    ' for valid geolocation codes.
                    sitelink2.geoTargeting = New Location()
                    sitelink2.geoTargeting.id = 2840

                    ' Restrict targeting only to people physically within the United States.
                    ' Otherwise, this could also show to people interested in the United States
                    ' but not physically located there.
                    Dim geoTargetingRestriction As New FeedItemGeoRestriction()
                    geoTargetingRestriction.geoRestriction = GeoRestriction.LOCATION_OF_PRESENCE
                    sitelink2.geoTargetingRestriction = geoTargetingRestriction

                    extensions.Add(sitelink2)
                End If

                ' Show the wifi details primarily for high end mobile users.
                Dim sitelink3 As New SitelinkFeedItem()
                sitelink3.sitelinkText = "Wifi available"
                sitelink3.sitelinkFinalUrls = New UrlList()
                sitelink3.sitelinkFinalUrls.urls = New String() _
                    {"http://www.example.com/mobile/wifi"}
                sitelink3.devicePreference = New FeedItemDevicePreference()
                sitelink3.devicePreference.devicePreference = 30001
                extensions.Add(sitelink3)

                ' Show the happy hours link only during Mon - Fri 6PM to 9PM.
                Dim sitelink4 As New SitelinkFeedItem()
                sitelink4.sitelinkText = "Happy hours"
                sitelink4.sitelinkFinalUrls = New UrlList()
                sitelink4.sitelinkFinalUrls.urls = New String() _
                    {"http://www.example.com/happyhours"}
                extensions.Add(sitelink4)

                Dim schedule1 As New FeedItemSchedule()
                schedule1.dayOfWeek = DayOfWeek.MONDAY
                schedule1.startHour = 18
                schedule1.startMinute = MinuteOfHour.ZERO
                schedule1.endHour = 21
                schedule1.endMinute = MinuteOfHour.ZERO

                Dim schedule2 As New FeedItemSchedule()
                schedule2.dayOfWeek = DayOfWeek.TUESDAY
                schedule2.startHour = 18
                schedule2.startMinute = MinuteOfHour.ZERO
                schedule2.endHour = 21
                schedule2.endMinute = MinuteOfHour.ZERO

                Dim schedule3 As New FeedItemSchedule()
                schedule3.dayOfWeek = DayOfWeek.WEDNESDAY
                schedule3.startHour = 18
                schedule3.startMinute = MinuteOfHour.ZERO
                schedule3.endHour = 21
                schedule3.endMinute = MinuteOfHour.ZERO

                Dim schedule4 As New FeedItemSchedule()
                schedule4.dayOfWeek = DayOfWeek.THURSDAY
                schedule4.startHour = 18
                schedule4.startMinute = MinuteOfHour.ZERO
                schedule4.endHour = 21
                schedule4.endMinute = MinuteOfHour.ZERO

                Dim schedule5 As New FeedItemSchedule()
                schedule5.dayOfWeek = DayOfWeek.FRIDAY
                schedule5.startHour = 18
                schedule5.startMinute = MinuteOfHour.ZERO
                schedule5.endHour = 21
                schedule5.endMinute = MinuteOfHour.ZERO

                sitelink4.scheduling = New FeedItemSchedule() { _
                                                                  schedule1, schedule2, schedule3,
                                                                  schedule4, schedule5
                                                              }

                ' Create your campaign extension settings. This associates the sitelinks
                ' to your campaign.
                Dim campaignExtensionSetting As New CampaignExtensionSetting()
                campaignExtensionSetting.campaignId = campaignId
                campaignExtensionSetting.extensionType = FeedType.SITELINK
                campaignExtensionSetting.extensionSetting = New ExtensionSetting()
                campaignExtensionSetting.extensionSetting.extensions = extensions.ToArray

                Dim extensionOperation As New CampaignExtensionSettingOperation()
                extensionOperation.operand = campaignExtensionSetting
                extensionOperation.operator = [Operator].ADD

                Try
                    ' Add the extensions.
                    Dim retVal As CampaignExtensionSettingReturnValue =
                            campaignExtensionSettingService.mutate(
                                New CampaignExtensionSettingOperation() _
                                                                      {extensionOperation})

                    ' Display the results.
                    If Not (retVal.value Is Nothing) AndAlso retVal.value.Length > 0 Then
                        Dim newExtensionSetting As CampaignExtensionSetting = retVal.value(0)
                        Console.WriteLine(
                            "Extension setting with type = {0} was added to campaign ID {1}.",
                            newExtensionSetting.extensionType, newExtensionSetting.campaignId)
                    Else
                        Console.WriteLine("No extension settings were created.")
                    End If
                Catch e As Exception
                    Throw New System.ApplicationException("Failed to create extension settings.", e)
                End Try
            End Using
        End Sub
    End Class
End Namespace


text:
using System;
using System.Threading.Tasks;
using Discord;

namespace VKDiscordBot.Services
{
    public abstract class BotServiceBase
    {
        public event Func<LogMessage, Task> Log;

        protected void RaiseLog(LogSeverity severity, string message, Exception exception = null)
        {
            Log?.Invoke(new LogMessage(severity, GetType().Name, message, exception));
        }
    }
}


text:
package org.wso2.extension.siddhi.device;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONArray;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.extension.siddhi.device.utils.DeviceUtils;
import org.wso2.siddhi.core.config.ExecutionPlanContext;
import org.wso2.siddhi.core.exception.ExecutionPlanRuntimeException;
import org.wso2.siddhi.core.executor.ExpressionExecutor;
import org.wso2.siddhi.core.executor.function.FunctionExecutor;
import org.wso2.siddhi.query.api.definition.Attribute;
import org.wso2.siddhi.query.api.exception.ExecutionPlanValidationException;

import java.util.List;

/**
 * hasDevicesOfUser(user , deviceType [, status])
 * Returns true if there are devices belonging to user
 * Accept Type(s): (STRING, STRING, STRING)
 * Return Type(s): (BOOL)
 */
public class HasDevicesOfUserFunctionExecutor extends FunctionExecutor {

    private static Log log = LogFactory.getLog(HasDevicesOfUserFunctionExecutor.class);
    private Attribute.Type returnType = Attribute.Type.BOOL;

    @Override
    protected void init(ExpressionExecutor[] attributeExpressionExecutors,
                        ExecutionPlanContext executionPlanContext) {
        if (attributeExpressionExecutors.length != 2 && attributeExpressionExecutors.length != 3) {
            throw new ExecutionPlanValidationException(
                    "Invalid no of arguments passed to device:getDevicesOfUser() function, minimum 2, or 3 with " +
                    "optional. but found " + attributeExpressionExecutors.length);
        }
        if (attributeExpressionExecutors[0].getReturnType() != Attribute.Type.STRING) {
            throw new ExecutionPlanValidationException(
                    "Invalid parameter type found for the first argument (user) of device:getDevicesOfUser() " +
                    "function, required " + Attribute.Type.STRING + " as user, but found " +
                    attributeExpressionExecutors[0].getReturnType().toString());
        }
        if (attributeExpressionExecutors[1].getReturnType() != Attribute.Type.STRING) {
            throw new ExecutionPlanValidationException(
                    "Invalid parameter type found for the second argument (device type) of device:getDevicesOfUser() " +
                    "function, required " + Attribute.Type.STRING + " as device type, but found " +
                    attributeExpressionExecutors[1].getReturnType().toString());
        }
        if (attributeExpressionExecutors.length == 3
            && attributeExpressionExecutors[2].getReturnType() != Attribute.Type.STRING) {
            throw new ExecutionPlanValidationException(
                    "Invalid optional parameter type found for the third argument (status) of " +
                    "device:getDevicesOfUser() function, required " + Attribute.Type.STRING + " as status, but found " +
                    attributeExpressionExecutors[2].getReturnType().toString());
        }
    }

    @Override
    protected Object execute(Object[] data) {
        if (data[0] == null) {
            throw new ExecutionPlanRuntimeException("Invalid input given to device:getDevicesOfUser() function. " +
                                                    "First argument cannot be null");
        }
        if (data[1] == null) {
            throw new ExecutionPlanRuntimeException("Invalid input given to device:getDevicesOfUser() function. " +
                                                    "Second argument cannot be null");
        }
        if (data.length == 3 && data[2] == null) {
            throw new ExecutionPlanRuntimeException("Invalid input given to device:getDevicesOfUser() function. " +
                                                    "Third argument cannot be null");
        }
        String user = (String) data[0];
        String deviceType = (String) data[1];
        String status = null;
        if (data.length == 3) {
            status = (String) data[2];
        }

        try {
            DeviceManagementProviderService deviceManagementProviderService = DeviceUtils.getDeviceManagementProviderService();
            List<Device> devices = deviceManagementProviderService.getDevicesOfUser(user, deviceType, false);
            if (status == null) {
                return !devices.isEmpty();
            } else {
                for (Device device : devices) {
                    if (status.equalsIgnoreCase(device.getEnrolmentInfo().getStatus().toString())) {
                        return true;
                    }
                }
                return false;
            }
        } catch (DeviceManagementException e) {
            log.error("Error occurred while getting " + deviceType + " devices of user " + user +
                      ", with status " + status, e);
        }
        return false;
    }

    @Override
    protected Object execute(Object data) {
        return null;  //Since the getDevicesOfUser function takes in 2 or 3 parameters, this method does not get called. Hence,not implemented.
    }

    @Override
    public void start() {
        //Nothing to start
    }

    @Override
    public void stop() {
        //Nothing to stop
    }

    @Override
    public Attribute.Type getReturnType() {
        return returnType;
    }

    @Override
    public Object[] currentState() {
        return null;    //No need to maintain a state.
    }

    @Override
    public void restoreState(Object[] state) {
        //Since there's no need to maintain a state, nothing needs to be done here.
    }
}


text:
exports.create = function(_args) {
	var self = require('ui/win').create('Autoren und andere Infos zum Bestimmungsbaum');
	self.setModal(true);
		self.backgroundColor = 'white';
	self.addEventListener('android:back', function(_e) {
		self.close();
	});
	self.addEventListener('longpress', function(_e) {
		self.close();
	});
	if (Ti.Platform.name !== 'android') {
		var leftButton = Ti.UI.createButton({
			title : 'Zurück'
		});
		self.setLeftNavButton(leftButton);
		leftButton.addEventListener('click', function() {
			self.close({
				animated : true
			});
		});
	};
	var autorenimg = {
		'Paul Bachhausen' : 'http://www.salamanderseiten.de/Paul.jpg',
		'Gregor Hagedorn' : 'http://www.naturkundemuseum-berlin.de/uploads/pics/nrodegah-gregor-re00.jpg',
		'G. Hagedorn' : 'http://www.naturkundemuseum-berlin.de/uploads/pics/nrodegah-gregor-re00.jpg',
		'Pier Luigi Nimis' : 'http://www.wumingfoundation.com/giap/wp-content/uploads/2012/04/Pierluiginimis.jpeg',
		'Stefano Martellos' : '/assets/creators/stefano.jpg',
		'Walter Gams' : 'http://dpg.phytomedizin.org/uploads/pics/WalterGams1.jpg',
		'Andrea Moro' : '',
		'Werner Nezadal' : 'http://www.herbarium-erlangense.nat.uni-erlangen.de/mitarbeiter/Werner_neu_4.jpg',
		'Philipp Meinecke' : '',
		'Rolf Wißkirchen' : 'http://www.ikg.uni-bonn.de/typo3temp/pics/84a909e2bf.jpg',
		'Tomi Trilar' : 'http://boa.czp-vecer.si/VECER2000/20100120/01480903-300.jpg',
		'Sven Gemballa' : 'http://www.uni-tuebingen.de/uploads/RTEmagicC_Gemballa_Sven.jpg.jpg',
		'Sabine von Mering' : 'http://www.bgbm.fu-berlin.de/bgbm/STAFF/wiss/Mering/images/Foto_SvM_hoch_klein.jpg',
		'Ekkehard Foerster' : '',
		'Andreas Plank' : 'http://www.jki.bund.de/typo3temp/pics/bf16f5f2c8.jpg',
		'A.Plank' : 'http://www.jki.bund.de/typo3temp/pics/bf16f5f2c8.jpg',
		'N.Poelloth' : ''
	};
	var tv = Ti.UI.createTableView();
	self.add(tv);
	if (_args.meta.creator) {
		var autoren = _args.meta.creator.split(', ');
		var rows = [];
		for (var i = 0; i < autoren.length; i++) {
			var autor = autoren[i];
			var row = Ti.UI.createTableViewRow({
				backgroundColor : 'white',
				height : Ti.UI.SIZE,
			});
			row.add(Ti.UI.createImageView({
				top : 10,
				left : 10,
				width : 80,
				height : 'auto',
				defaultImage : '/assets/user.png',
				image : (autorenimg[autor]) ? autorenimg[autor] : '/assets/user.png',
			}));
			console.log(autor);
			row.add(Ti.UI.createLabel({
				top : 10,
				left : 100,
				height : Ti.UI.SIZE,
				text : autor,
				color : '#444',
				font : {
					fontSize : Ti.App.CONF.fontsize_title,
					fontFamily : 'OpenBaskerville-0.0.75'
				},
			}));
			tv.appendRow(row);
		}
	}
	if (_args.meta.created)
		tv.appendRow(require('ui/commonrow').create('Erstellung', require('vendor/moment')(_args.meta.created).format('DD.MM.YYYY')));
	if (_args.meta.modified)
		tv.appendRow(require('ui/commonrow').create('letzte Änderung', require('vendor/moment')(_args.meta.modified).format('DD.MM.YYYY')));
	if (_args.meta.audience)
		tv.appendRow(require('ui/commonrow').create('Zielgruppe', _args.meta.audience));
	if (_args.meta.source)
		tv.appendRow(require('ui/commonrow').create('Quelle', _args.meta.source));
	if (_args.meta.geoscope)
		tv.appendRow(require('ui/commonrow').create('Verbreitung', _args.meta.geoscope));
	return self;
};


text:
class EventTimesController < ApplicationController
  before_action :authenticate_user!

  def show
    @event = Event.find(params[:event_id])
    @event_time = EventTime.find(params[:id])
    @tickets = @event_time.tickets.includes(:attendee)
    unless current_user == @event.manager
      flash[:danger] = "Something went wrong."
      redirect_to dashboard_path
    end
  end

  def new
    @event = Event.find(params[:event_id])
    @event_time = @event.event_times.build
    unless current_user == @event.manager
      flash[:danger] = "Something went wrong."
      redirect_to dashboard_path
    end
  end

  def create
    @event = Event.find(params[:event_id])
    @event_time = @event.event_times.build(event_time_params)
    if @event_time.save
      flash[:success] = "Your event was created!"
      redirect_to event_path(@event)
    else
      render 'new'
    end
  end

  def edit
    @event = Event.find(params[:event_id])
    @event_time = EventTime.find(params[:id])
    unless current_user == @event.manager
      flash[:danger] = "Something went wrong."
      redirect_to dashboard_path
    end
  end

  def update
    @event = Event.find(params[:event_id])
    @event_time = EventTime.find(params[:id])
    if @event_time.update(event_time_params)
      flash[:success] = "Your event was updated!"
      redirect_to event_path(@event)
    else
      render 'edit'
    end
  end

  def destroy
    @event = Event.find(params[:event_id])
    @event_time = EventTime.find(params[:id])
    @event_time.destroy
    flash[:success] = "Your showtime was cancelled!"
    redirect_to event_path(@event)
  end

  private

    def event_time_params
      params.require(:event_time).permit(:start_time, :end_time)
    end
end


text:
package com.fordprog.matrix.interpreter.error.semantic;

import com.fordprog.matrix.interpreter.CodePoint;

public class AssignmentToFunctionSemanticError extends SemanticError {

  public AssignmentToFunctionSemanticError(CodePoint codePoint) {
    super(codePoint);
  }

  @Override
  public String getMessage() {
    return "Assignment to function is not possible at " + getCodePoint();
  }

}


text:
/**
 * Test inherit
 */
package com.ciaoshen.thinkinjava.newchapter17;

final class TestInherit {
    private static class BaseClass {
        private String privateField = "I am privateField in BaseClass!";
        public String getPrivateField() {
            return privateField;
        }
        public static void staticMethod() {
            System.out.println("I am static method in BaseClass!");
        }
        private static void privateStaticMethod() {
            System.out.println("I am private static method in BaseClass!");
        }
    }
    private static class DerivedClass extends BaseClass {
        public void visitPrivateFieldInBaseClass() {
            System.out.println("DerivedClass Visit private field in BaseClass: " + getPrivateField());
        }
    }
    public static void main(String[] args) {
        DerivedClass dc = new DerivedClass();
        dc.visitPrivateFieldInBaseClass();
        DerivedClass.staticMethod();
        // DerivedClass.privateStaticMethod(); // ERROR: can not inherit private method from BaseClass!
    }
}


text:
using System;
using System.Collections.Generic;
using System.CodeDom.Compiler;
using Drumble.DomainDrivenArchitecture.Infrastructure.EntityFramework;
using System.ComponentModel.DataAnnotations.Schema;

namespace AppCampus.Infrastructure.Models
{
    [Table("SignboardRequest")]
	[GeneratedCode("EntityFrameworkCodeGeneration", "6.1.1")]
    public partial class SignboardRequestTable : IDataEntity<Guid>
    {

        [Column("SignboardRequestId")]
		public System.Guid Id { get; set; }

        [Column("SignboardId")]
		public System.Guid SignboardId { get; set; }

        [Column("RequestType")]
		public string RequestType { get; set; }

        [Column("IsSent")]
		public bool IsSent { get; set; }

        [Column("IsProcessed")]
		public bool IsProcessed { get; set; }

        [Column("IsCancelled")]
		public bool IsCancelled { get; set; }

        [Column("Value")]
		public string Value { get; set; }

        [Column("CreatedDate")]
		public System.DateTime CreatedDate { get; set; }
        public virtual SignboardTable Signboard { get; set; }

    }
}


text:
namespace Bike_Share.Migrations
{
    using System.CodeDom.Compiler;
    using System.Data.Entity.Migrations;
    using System.Data.Entity.Migrations.Infrastructure;
    using System.Resources;

    [GeneratedCode("EntityFramework.Migrations", "6.1.2-31219")]
    public sealed partial class add_lastRun_to_inspection : IMigrationMetadata
    {
        private readonly ResourceManager Resources = new ResourceManager(typeof(add_lastRun_to_inspection));

        string IMigrationMetadata.Id
        {
            get { return "201506260207274_add_lastRun_to_inspection"; }
        }

        string IMigrationMetadata.Source
        {
            get { return null; }
        }

        string IMigrationMetadata.Target
        {
            get { return Resources.GetString("Target"); }
        }
    }
}


text:
#include "IOT_GetDevice.h"
#include "IOT_defines.h"
#include <stdio.h>

IOT_GetDevice::IOT_GetDevice(): IOT_RegDevice(), m_deviceID(""), m_href(""), m_createdAt("") {}

IOT_GetDevice::~IOT_GetDevice() {}

bool IOT_GetDevice::SetDeviceID(const std::string& devID)
{
    if(devID.length() != IOTAPI::IOTAPI_DEVID_LEN) {
        return false;
    }

    m_deviceID = devID;
    return true;
}

std::string IOT_GetDevice::GetDeviceID() const
{
    return m_deviceID;
}

bool IOT_GetDevice::SetHref(const std::string& href)
{
    if(href.empty() || href.length() > IOTAPI::IOTAPI_MAX_HREF_LEN) {
        return false;
    }

    m_href = href;
    return true;
}

std::string IOT_GetDevice::GetHref() const
{
    return m_href;
}

bool IOT_GetDevice::SetCreated(const std::string& created)
{
    if(created.empty() || created.length() > IOTAPI::IOTAPI_MAX_CREATED_LEN) {
        return false;
    }

    m_createdAt = created;
    return true;
}

std::string IOT_GetDevice::GetCreated() const
{
    return m_createdAt;
}

bool IOT_GetDevice::ToJSON(std::string &json) const
{
    Json::Value device;
    Json::FastWriter fastWriter;

    if(!IOT_GetDevice::ToJSON(device)) {
        return false;
    }

    json = fastWriter.write(device);
    return true;
}

bool IOT_GetDevice::ToJSON(Json::Value &json) const
{
    if(m_deviceID.empty() || m_href.empty() || m_createdAt.empty()) {
        return false;
    }

    json["deviceId"] = m_deviceID;
    json["href"] = m_href;
    json["createdAt"] = m_createdAt;

    if(!IOT_RegDevice::ToJSON(json)) {
        json.clear();
        return false;
    }

    return true;
}

bool IOT_GetDevice::FromJSON(const std::string &json)
{
    Json::Value answer;
    Json::Reader json_reader;

    if(json_reader.parse(json, answer, false))
    {
        if(IOT_GetDevice::FromJSON(answer)) {
            return true;
        }
    }

    return false;
}

bool IOT_GetDevice::FromJSON(const Json::Value &json)
{
    IOT_GetDevice old(*this);

    if(json.isMember("deviceId") && json["deviceId"].isString())
    {
        if(!SetDeviceID(json["deviceId"].asString())) {
            return false;
        }
    } else {
        return false;
    }

    if(json.isMember("href") && json["href"].isString())
    {
        if(!SetHref(json["href"].asString())) {
            IOT_GetDevice(old);
            return false;
        }
    } else {
        IOT_GetDevice(old);
        return false;
    }

    if(json.isMember("createdAt") && json["createdAt"].isString())
    {
        if(!SetCreated(json["createdAt"].asString())) {
            IOT_GetDevice(old);
            return false;
        }
    } else {
        IOT_GetDevice(old);
        return false;
    }

    if(!IOT_RegDevice::FromJSON(json)) {
        IOT_GetDevice(old);
        return false;
    }

    return true;
}


text:
"""Tests for custom landing pages."""

from __future__ import absolute_import  # pylint: disable=import-only-modules
from __future__ import unicode_literals  # pylint: disable=import-only-modules

from core.tests import test_utils
import feconf

class FractionLandingRedirectPageTest(test_utils.GenericTestBase):
    """Test for redirecting landing page for fractions."""

    def test_old_fractions_landing_url_without_viewer_type(self):
        """Test to validate the old Fractions landing url without viewerType
        redirects to the new Fractions landing url.
        """
        response = self.get_html_response(
            feconf.FRACTIONS_LANDING_PAGE_URL, expected_status_int=302)
        self.assertEqual(
            'http://localhost/math/fractions',
            response.headers['location'])

    def test_old_fraction_landing_url_with_viewer_type(self):
        """Test to validate the old Fractions landing url with viewerType
        redirects to the new Fractions landing url.
        """
        response = self.get_html_response(
            '%s?viewerType=student' % feconf.FRACTIONS_LANDING_PAGE_URL,
            expected_status_int=302)
        self.assertEqual(
            'http://localhost/math/fractions',
            response.headers['location'])

class TopicLandingRedirectPageTest(test_utils.GenericTestBase):
    """Test for redirecting the old landing page URL to the new one."""

    def test_old_topic_url_redirect(self):
        response = self.get_html_response(
            '/learn/maths/fractions', expected_status_int=302)
        self.assertEqual(
            'http://localhost/math/fractions', response.headers['location'])

class TopicLandingPageTest(test_utils.GenericTestBase):
    """Test for showing landing pages."""

    def test_valid_subject_and_topic_loads_correctly(self):
        response = self.get_html_response('/math/fractions')
        response.mustcontain('<topic-landing-page></topic-landing-page>')

class StewardsLandingPageTest(test_utils.GenericTestBase):
    """Test for showing the landing page for stewards (parents, teachers,
    volunteers, or NGOs).
    """

    def test_nonprofits_landing_page(self):
        response = self.get_html_response(
            feconf.CUSTOM_NONPROFITS_LANDING_PAGE_URL)
        response.mustcontain(
            '<stewards-landing-page></stewards-landing-page>')

    def test_parents_landing_page(self):
        response = self.get_html_response(
            feconf.CUSTOM_PARENTS_LANDING_PAGE_URL)
        response.mustcontain(
            '<stewards-landing-page></stewards-landing-page>')

    def test_teachers_landing_page(self):
        response = self.get_html_response(
            feconf.CUSTOM_TEACHERS_LANDING_PAGE_URL)
        response.mustcontain('<stewards-landing-page></stewards-landing-page>')

    def test_volunteers_landing_page(self):
        response = self.get_html_response(
            feconf.CUSTOM_VOLUNTEERS_LANDING_PAGE_URL)
        response.mustcontain('<stewards-landing-page></stewards-landing-page>')


text:
//----------------------------------------------------------------
// <copyright company="Microsoft Corporation">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//----------------------------------------------------------------

namespace System.Activities.Presentation.View
{
    using System.Windows.Controls;

    internal class NoContextMenuGrid : Grid
    {
        protected override void OnContextMenuOpening(ContextMenuEventArgs e)
        {
            e.Handled = true;
        }
    }
}


text:
<?php

/** Generic DAO base class. */
class MIDAS_GlobalDao
{
    /** @var string */
    protected $key;

    /** Constructor. */
    public function __construct()
    {
        if ($this->getModel()->getKey() !== '') {
            $this->_key = $this->getModel()->getKey();
        } else {
            $this->_key = false;
        }
        $this->saved = false;
        $this->loadElements();
    }

    /** Load the components. */
    public function loadElements()
    {
        Zend_Registry::set('components', array());
        if (isset($this->_components)) {
            foreach ($this->_components as $component) {
                $nameComponent = $component.'Component';
                Zend_Loader::loadClass($nameComponent, BASE_PATH.'/core/controllers/components');
                if (!isset($this->Component)) {
                    $this->Component = new stdClass();
                }
                $this->Component->$component = new $nameComponent();
            }
        }
    }

    /**
     * Initialize the DAO from the primary key.
     *
     * @param string $key primary key with which to initialize the DAO
     * @return bool true if the DAO is successfully initialized
     * @throws Zend_Exception
     */
    public function initValues($key)
    {
        if (!isset($key)) {
            throw new Zend_Exception('Model '.$this->getModel()->_name.': key is not defined here.');
        }
        $values = $this->getModel()->getValues($key);
        if ($values == null) {
            return false;
        }

        $maindata = $this->getModel()->getMainData();
        foreach ($maindata as $name => $type) {
            if (isset($values->$name) && $type['type'] == MIDAS_DATA) {
                $this->$name = $values->$name;
            }
        }

        return true;
    }

    /**
     * Return the names and values of the fields of the DAO as an associative array.
     *
     * @return array
     */
    public function toArray()
    {
        $return = array();
        $maindata = $this->getModel()->getMainData();
        foreach ($maindata as $name => $type) {
            if (isset($this->$name) && $type['type'] == MIDAS_DATA) {
                $return[$name] = $this->$name;
            } elseif ($type['type'] == MIDAS_DATA) {
                $return[$name] = null;
            }
        }

        return $return;
    }

    /**
     * Return the value of the key field of the DAO.
     *
     * @return mixed
     * @throws Zend_Exception
     */
    public function getKey()
    {
        if ($this->_key == false) {
            throw new Zend_Exception('Model  '.$this->getModel()->getName().': key is not defined here.');
        }
        $key = $this->getModel()->getKey();

        return $this->get($key);
    }

    /**
     * Return the value of a field of the DAO.
     *
     * @param string $var name of the field of which to return the value
     * @return mixed
     * @throws Zend_Exception
     */
    public function get($var)
    {
        $maindata = $this->getModel()->getMainData();
        if (!isset($maindata[$var])) {
            throw new Zend_Exception(
                'Model '.$this->getModel()->getName().': var '.$var.' is not defined here.'
            );
        }
        if (method_exists($this, 'get'.ucfirst($var))) {
            $name = 'get'.ucfirst($var);

            return $this->$name($var);
        } elseif (isset($this->$var)) {
            return $this->$var;
        } else {
            $key = $this->_key;
            if (!isset($this->$key)) {
                return $this->getModel()->getValue($var, null, $this);
            }

            return $this->getModel()->getValue($var, $this->$key, $this);
        }
    }

    /**
     * Set the value of a field of the DAO.
     *
     * @param string $var name of the field of which to set the value
     * @param mixed $value value of the field
     * @return void|mixed
     * @throws Zend_Exception
     */
    public function set($var, $value)
    {
        $maindata = $this->getModel()->getMainData();
        if (!isset($maindata[$var])) {
            throw new Zend_Exception(
                'Model '.$this->getModel()->getName().': var '.$var.' is not defined here.'
            );
        }
        if (method_exists($this, 'set'.ucfirst($var))) {
            return call_user_func('set'.ucfirst($var), $var, $value);
        }
        $this->$var = $value;
    }

    /**
     * Return a model.
     *
     * @param string|null $name name of the model
     * @return mixed|MIDASModel
     */
    public function getModel($name = null)
    {
        if ($name != null) {
            if (isset($this->_module)) {
                return MidasLoader::loadModel($name, $this->_module);
            }

            return MidasLoader::loadModel($name);
        }
        if (isset($this->_module)) {
            return MidasLoader::loadModel($this->_model, $this->_module);
        }

        return MidasLoader::loadModel($this->_model);
    }

    /**
     * Fetch the logger from the Zend registry.
     *
     * @return Zend_Log
     */
    public function getLogger()
    {
        return Zend_Registry::get('logger');
    }

    /**
     * Invoke inaccessible methods.
     *
     * @param string $method name of the method
     * @param array $params parameters of the method
     * @return mixed
     * @throws Zend_Exception
     */
    public function __call($method, $params)
    {
        if (substr($method, 0, 3) == 'get') {
            $var = $this->_getRealName(substr($method, 3));
            $maindata = $this->getModel()->getMainData();
            if (isset($maindata[$var])) {
                return $this->get($var);
            } else {
                throw new Zend_Exception(
                    'Dao:  '.__CLASS__.': method '.$method." doesn't exist (".strtolower(
                        substr($method, 3)
                    ).' is not defined.'
                );
            }
        } elseif (substr($method, 0, 3) == 'set') {
            $var = $this->_getRealName(substr($method, 3));
            $maindata = $this->getModel()->getMainData();
            if (isset($maindata[$var])) {
                return $this->set($var, $params[0]);
            } else {
                throw new Zend_Exception(
                    'Dao:  '.__CLASS__.': method '.$method." doesn't exist (".strtolower(
                        substr($method, 3)
                    ).' is not defined.'
                );
            }
        } else {
            throw new Zend_Exception('Dao:  '.__CLASS__.': method '.$method." doesn't exist.");
        }
    }

    /**
     * Return a method name given the name of an item of data in a model.
     *
     * @param string $var name of an item of data
     * @return string
     */
    private function _getRealName($var)
    {
        $return = '';
        preg_match_all('/[A-Z][^A-Z]*/', $var, $results);

        foreach ($results[0] as $key => $r) {
            if ($key == 0) {
                $return .= strtolower($r);
            } else {
                $return .= '_'.strtolower($r);
            }
        }

        return $return;
    }
}


text:
/* A simple server in the internet domain using TCP
   The port number is passed as an argument */
#include <arpa/inet.h>
#include <time.h>
#include <errno.h>
#include <fcntl.h>
#include <netinet/in.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <syslog.h>
#include <sys/types.h>
#include <sys/sendfile.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <unistd.h>

/**
    CONSTANTS
*/
enum {DEBUG=0};

/**
    Declares an array struct
*/
typedef struct {
    char* array;
    size_t used;
    size_t size;
}CharArr;
/**
    Declares a client info struct
*/
typedef struct {
    int socket;
    int bytesWritten;
    int simple;
    CharArr method;
    CharArr url;
    CharArr protocol;
    CharArr address;
    CharArr statusCode;
    CharArr logFile;
}ClientInfo;

/**
    Declares the function headers
*/
void initArr(CharArr* arr, size_t startSize);
void addArr(CharArr* arr, char item);
void catArr(CharArr* arr, char* items, int arrLen);
void freeArr(CharArr* arr);
void resetArr(CharArr* arr);

void error(const char *msg);

void handleRequest(ClientInfo* client, CharArr* url);
void handleResponse(ClientInfo* client, CharArr* url);

int sendOkHeaders(ClientInfo* client, char* ext, int fileSize);
int sendNotFound(ClientInfo* client);
int sendBadRequest(ClientInfo* client);
int sendNotImplemented(ClientInfo* client);
int sendInternalError(ClientInfo* client);
int sendForbidden(ClientInfo* client);

int loadDefaultVariables(char* configFile, CharArr* defaultPath);
int getHeaderInfo(ClientInfo* client, CharArr* buffer);

void getFormatedTime(char* buffer);
/**
    Main file
*/
int main(int argc, char *argv[])
{

    /**
        Declare variables
    */
    int serverSock, clientSock, portNr, rval, optval, i, isDaemon;
    socklen_t clilen, addressLength;
    pid_t childPid;
    struct sockaddr_in serverAddr, clientAddr;
    char* configFile = ".lab3-config";
    CharArr defaultPath;
    ClientInfo client;
    client.socket = 0;
    client.bytesWritten = 0;
    client.simple = 0;
    initArr(&client.method, 16);
    initArr(&client.url, 32);
    initArr(&client.protocol, 16);
    initArr(&client.address, 32);
    initArr(&client.statusCode, 4);
    initArr(&client.logFile, 64);
    initArr(&defaultPath, 32);
    portNr = loadDefaultVariables(configFile, &defaultPath);
    syslog(LOG_INFO, "%s", "Webserver has started");
    mkdir("/home/jails", ACCESSPERMS);
    mkdir("/home/jails/webserver", ACCESSPERMS);
    if (chroot("/home/jails/webserver") != 0) {
        perror("/home/jails/webserver");
        return 1;
    } else {
        printf("Set /home/jails/webserver as root folder\n");
    }
    /* Change the current working directory */
    if ((chdir("/")) < 0) {
        /* Log the failure */
        exit(EXIT_FAILURE);
    }
    syslog(LOG_INFO, "%s", "Successfully Jailed webserver to /home/jails/webserver");

    /**
        Init variables
    */
    isDaemon = 0;
    // Parse argv
    for(i = 0; i < argc; i++) {
        // Set port if defined
        if(!strcmp(argv[i], "-p")) {
            portNr = strtol(argv[++i], (char **)NULL, 10);
        }
        //Enable daemon mode if defined
        if(!strcmp(argv[i], "-d")) {
            isDaemon = 1;
            printf("Daemonmode activated\n", portNr);
        }
        //Enable log file if defined
        if(!strcmp(argv[i], "-l")) {
            i++;
            catArr(&client.logFile, argv[i], strlen(argv[i]));
            printf("LogFile set to: %s\n", client.logFile.array);
        }
    }
    if(isDaemon) {
        printf("Listening on port: %d\n", portNr);
        /* Our process ID and Session ID */
        pid_t pid, sid;
        /* Fork off the parent process */
        pid = fork();
        if (pid < 0) {
            exit(EXIT_FAILURE);
        }
        /* If we got a good PID, then
           we can exit the parent process. */
        if (pid > 0) {
            printf("Process id: %d\n", pid);
            exit(EXIT_SUCCESS);
        }
        /* Change the file mode mask */
        umask(0);
        /* Create a new SID for the child process */
        sid = setsid();
        if (sid < 0) {
            /* Log the failure */
            exit(EXIT_FAILURE);
        }

        /* Close out the standard file descriptors */
        close(STDIN_FILENO);
        close(STDOUT_FILENO);
        close(STDERR_FILENO);
    }

    serverSock = socket(AF_INET, SOCK_STREAM, 0);
    if (serverSock < 0) {error("ERROR opening socket");}
    // Clear the server address
    bzero((char *) &serverAddr, sizeof(serverAddr));
    serverAddr.sin_family = AF_INET; // Set the socket family to tcp/ip
    serverAddr.sin_addr.s_addr = INADDR_ANY; // Allow any connection addresses
    serverAddr.sin_port = htons(portNr); // Sets the port number
    clilen = sizeof(clientAddr);
    rval = 0;
    optval = 1;
    //Make sure that binds reuse server address so we don't get bind errors on restarts
    setsockopt(serverSock, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval));
    // Binds the socket to the server and checks that it worked
    if (bind(serverSock, (struct sockaddr *) &serverAddr, sizeof(serverAddr)) < 0) {
        error("ERROR on binding");
    }

    /**
        Start Server thingies
    */
    // Listen to the socket
    listen(serverSock,20);
    printf("Listening on port: %d\n\n", portNr);
    while(1) {
        /* accepts the client */
        client.socket = accept(serverSock, (struct sockaddr *) &clientAddr, &clilen);
        if (client.socket < 0) {error("ERROR on accept");}

        /* Get the remote address of the connection. */
        addressLength = sizeof(serverAddr);
        rval = getpeername(client.socket, (struct sockaddr *)&serverAddr, &addressLength);
        resetArr(&client.address);
        catArr(&client.address, inet_ntoa(serverAddr.sin_addr), strlen(inet_ntoa(serverAddr.sin_addr)));

        //Ignore the dying children
        signal(SIGCHLD, SIG_IGN);

        /* Fork a child process to handle the connection.  */
        childPid = fork();
        if (childPid == 0) {
            /* This child process shouldn't do anything with the listening socket. */
            close(serverSock);

            /* Handle request with a client.socket copy */
            handleRequest(&client, &defaultPath);
            /* All done; close the connection socket, and end the child
            process.  */
            close(client.socket);
            exit(0);
        }
        else if (childPid > 0) {
            /* This is the parent process.  The child process handles the
            connection, so we don't need our copy of the connected socket
            descriptor.  Close it.  Then continue with the loop and
            accept another connection.  */
            close (client.socket);
        }
        else {
            /* Call to fork failed.  */
            error("fork");
        }
    }
}

/**
    Handle the request and respond to the client
*/
void handleRequest(ClientInfo* client, CharArr* url) {
    /**
        Define variables
    */
    FILE *fd;
    //Char buffer for reading client sock
    char bc;
    //Helping variables
    char timeBuffer[64];
    //String buffers
    CharArr buffer;

    //Init buffer array
    initArr(&buffer, 128);

    /* Read the client request to buffer */
    while (strstr (buffer.array, "\r\n\r\n") == NULL && buffer.array[0] != '\n' && buffer.used <= 3000) {
        read(client->socket, &bc, 1);
        addArr(&buffer, bc);
    }
    if(DEBUG) {printf("CLIENT REQUEST: %s\n", buffer.array);}
    //extracts the method, url and protocoll from the buffer
    if(getHeaderInfo(client, &buffer)) {
        catArr(url, client->url.array, client->url.used);
        handleResponse(client, url);
    }

    getFormatedTime(timeBuffer);
    if(client->logFile.used != 0) {
        fd = fopen(client->logFile.array, "a");
        fprintf(fd, "%s - - [%s] \"%s %s %s\" %s %d\n", client->address.array, timeBuffer, client->method.array, client->url.array, client->protocol.array, client->statusCode.array, client->bytesWritten);
        fclose(fd);
    }else {
        syslog(LOG_INFO, "%s - - [%s] \"%s %s %s\" %s %d", client->address.array, timeBuffer, client->method.array, client->url.array, client->protocol.array, client->statusCode.array, client->bytesWritten);
    }
    //printf("%s - - [%s] \"%s %s %s\" %s %d\n", client->address.array, timeBuffer, client->method.array, client->url.array, client->protocol.array, client->statusCode.array, client->bytesWritten);
    freeArr(&client->method);
    freeArr(&client->url);
    freeArr(&client->protocol);
    freeArr(&client->address);
    freeArr(&client->statusCode);
    freeArr(&client->logFile);
    freeArr(&buffer);
    freeArr(url);
}
void handleResponse(ClientInfo* client, CharArr* url) {
    int rval, fd, fileSize;
    char* ext;
    struct stat file_stat;
    //If url is now empty change url to index.html
    if(!strcmp(&url->array[url->used-1], "/")) {
        catArr(url, "index.html", strlen("index.html"));
    }
    /* Try to deliver the requested file */
    fd = open(url->array, O_RDONLY);
    if(fd != -1) {
        ext = strrchr(url->array, '.');
        if (!ext) {
            addArr(url, '/');
            handleResponse(client, url);
            return;
            //File has no extension... 400?
        } else {
            ext++;
        }
        /* Get file stats */
        fstat(fd, &file_stat);
        fileSize = file_stat.st_size;
        if(DEBUG) {printf("    Method: %s\n", client->method.array);}
        if(!strcmp(client->method.array, "GET")) {
            if(!client->simple) {
                rval = sendOkHeaders(client, ext, fileSize);
            }
            rval += sendfile (client->socket, fd, NULL, fileSize);
        } else if (!strcmp(client->method.array, "HEAD")){
            if(!client->simple) {
                rval = sendOkHeaders(client, ext, fileSize);
            }
        } else {
            rval = sendNotImplemented(client);
        }
    } else {
        if(errno == 17 || errno == 21 ) {
            //Read error, file exists or is directory? :S
            rval = sendInternalError(client);
        } else {
            rval = sendNotFound(client);
        }
    }
    if(rval > 0) {
        client->bytesWritten += rval;
    } else {
        rval = sendInternalError(client);
        client->bytesWritten += rval;
    }
}

int getHeaderInfo(ClientInfo* client, CharArr* buffer) {
    char bc;
    int counter = 0;
    int bytesWritten;

    //parse http method (GET, HEAD, etc)
    bc = buffer->array[counter++];
    while(bc != ' ' && counter < buffer->used) {
        addArr(&client->method, bc);
        bc = buffer->array[counter++];
    }

    //Parse requested url
    bc = buffer->array[counter++];
    while(bc != ' ' && bc != '\r' && client->url.used != 2000 && counter < buffer->used) {
        addArr(&client->url, bc);
        bc = buffer->array[counter++];
    }
    if(bc == '\r') {
        client->simple = 1;
        return 1;
    }
    if(client->url.used == 2000 && counter < buffer->used) {
        while(bc != ' ' && counter < buffer->used) {
            bc = buffer->array[counter++];
        }
    }

    bc = buffer->array[counter++];
    while(bc != '\r' && counter < buffer->used) {
        addArr(&client->protocol, bc);
        bc = buffer->array[counter++];
    }

    if(strstr(client->url.array, "..") != NULL) {
        bytesWritten = sendForbidden(client);
        if(bytesWritten > 0) {
            client->bytesWritten += bytesWritten;
        }
        return 0;
    }

    if(strcasecmp(client->method.array, "GET") && strcasecmp(client->method.array, "HEAD")) {
        bytesWritten = sendNotImplemented(client);
        if(bytesWritten > 0) {
            client->bytesWritten += bytesWritten;
        }
        return 0;
    }

    if(client->url.used == 2000 || counter >= buffer->used) {
        bytesWritten = sendBadRequest(client);
        if(bytesWritten > 0) {
            client->bytesWritten += bytesWritten;
        }
        return 0;
    }
    return 1;
}

int sendOkHeaders(ClientInfo* client, char* ext, int fileSize) {
    catArr(&client->statusCode, "200", strlen("200"));
    /**
        HTTP response, header for valid requests dokument body should be appended on GET requests
    */
    CharArr response;
    initArr(&response, 50);
    char* jpgExt = "jpg";
    char* pngExt = "png";
    char* gifExt = "gif";
    char* icoExt = "ico";
    char* cssExt = "css";
    char* jsExt = "js";
    char responseString[200];
    const char* ok_html_response ="HTTP/1.0 200 OK\ncontent-type: text/html; charset=UTF-8\ncontent-length: %d\n\n";
    const char* ok_jpg_response =
        "HTTP/1.0 200 OK\n"
        "Content-type: image/jpeg\n"
        "content-length: %d\n"
        "\n";
    const char* ok_png_response =
        "HTTP/1.0 200 OK\n"
        "Content-type: image/png\n"
        "content-length: %d\n"
        "\n";
    const char* ok_gif_response =
        "HTTP/1.0 200 OK\n"
        "Content-type: image/gif\n"
        "content-length: %d\n"
        "\n";
    const char* ok_ico_response =
        "HTTP/1.0 200 OK\n"
        "Content-type: image/x-icon\n"
        "content-length: %d\n"
        "\n";
    const char* ok_css_response =
        "HTTP/1.0 200 OK\n"
        "Content-type: text/css\n"
        "content-length: %d\n"
        "\n";
    const char* ok_js_response =
        "HTTP/1.0 200 OK\n"
        "Content-type: text/javascript\n"
        "content-length: %d\n"
        "\n";
    if(!strcmp(jpgExt, ext)) {
        sprintf(responseString, ok_jpg_response, fileSize);
        catArr(&response, responseString, strlen(responseString));
    }else if(!strcmp(pngExt, ext)){
        sprintf(responseString, ok_png_response, fileSize);
        catArr(&response, responseString, strlen(responseString));
    }else if(!strcmp(gifExt, ext)){
        sprintf(responseString, ok_gif_response, fileSize);
        catArr(&response, responseString, strlen(responseString));
    }else if(!strcmp(icoExt, ext)){
        sprintf(responseString, ok_ico_response, fileSize);
        catArr(&response, responseString, strlen(responseString));
    }else if(!strcmp(cssExt, ext)){
        sprintf(responseString, ok_css_response, fileSize);
        catArr(&response, responseString, strlen(responseString));
    }else if(!strcmp(jsExt, ext)){
        sprintf(responseString, ok_js_response, fileSize);
        catArr(&response, responseString, strlen(responseString));
    }else{
        sprintf(responseString, ok_html_response, fileSize);
        catArr(&response, responseString, strlen(responseString));
    }

    int rval = write(client->socket, response.array, response.used);
    freeArr(&response);
    return rval;
}
int sendNotFound(ClientInfo* client) {
    catArr(&client->statusCode, "404", strlen("404"));
    /*
        HTTP response, header, and body template indicating that the
        requested document was not found.
    */
    static char* not_found_response =
        "HTTP/1.0 404 Not Found\n"
        "Content-type: text/html\n"
        "\n"
        "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n"
        "\n"
        " \n"
        "  <meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\">\n"
        "  <title>404 Not Found</title>\n"
        " \n"
        " \n"
        "
404 Not Found
\n"
        "
The requested URL was not found on this server.
\n"
        " \n"
        "\n";
    return write(client->socket, not_found_response, strlen(not_found_response));
}
int sendBadRequest(ClientInfo* client) {
    catArr(&client->statusCode, "400", strlen("400"));
    /*
        HTTP response, header, and body indicating that the we didn't
        understand the request.
    */
    static char* bad_request_response =
        "HTTP/1.0 400 Bad Request\n"
        "Content-type: text/html\n"
        "\n"
        "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n"
        "\n"
        " \n"
        "  <meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\">\n"
        "  <title>400 Bad Request</title>\n"
        " \n"
        " \n"
        "
400 Bad Request
\n"
        "
This server did not understand your request.
\n"
        " \n"
        "\n";
    return write(client->socket, bad_request_response, strlen(bad_request_response));
}
int sendNotImplemented(ClientInfo* client) {
    catArr(&client->statusCode, "501", strlen("501"));
    /*
        HTTP response, header, and body template indicating that the
        method was not understood.
    */
    static char* bad_method_response =
        "HTTP/1.0 501 Method Not Implemented\n"
        "Content-type: text/html\n"
        "\n"
        "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n"
        "\n"
        " \n"
        "  <meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\">\n"
        "  <title>501 Method Not Implemented</title>\n"
        " \n"
        " \n"
        "
501 Method Not Implemented
\n"
        "
The requested method is not implemented by this server.
\n"
        " \n"
        "\n";
    return write(client->socket, bad_method_response, strlen(bad_method_response));
}
int sendInternalError(ClientInfo* client) {
    catArr(&client->statusCode, "500", strlen("500"));
    /*
        HTTP response, header, and body template indicating that the
        method was not understood.
    */
    static char* internal_server_error_response =
        "HTTP/1.0 500 Internal server error\n"
        "Content-type: text/html\n"
        "\n"
        "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n"
        "\n"
        " \n"
        "  <meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\">\n"
        "  <title>500 Internal Server Error</title>\n"
        " \n"
        " \n"
        "
500 Internal Server Error
\n"
        "
Something went wrong.
\n"
        " \n"
        "\n";
    return write(client->socket, internal_server_error_response, strlen(internal_server_error_response));
}
int sendForbidden(ClientInfo* client) {
    catArr(&client->statusCode, "403", strlen("403"));
    /*
        HTTP response, header, and body template indicating that the
        requested document was not found.
    */
    static char* forbidden_response =
        "HTTP/1.0 403 Forbidden\n"
        "Content-type: text/html\n"
        "\n"
        "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n"
        "\n"
        " \n"
        "  <meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\">\n"
        "  <title>403 Forbidden</title>\n"
        " \n"
        " \n"
        "
403 Forbidden
\n"
        "
Permission denied.
\n"
        " \n"
        "\n";
    return write(client->socket, forbidden_response, strlen(forbidden_response));
}

/**
    logs an error and exits the program with error code 1
*/
void error(const char *msg) {
    perror(msg);
    exit(1);
}

/**
    Initialize a new array
*/
void initArr(CharArr* arr, size_t startSize) {
    arr->array = (char *)malloc(startSize * sizeof(char));
    arr->used = 0;
    arr->size = startSize;
}

/**
    Add item to array
*/
void addArr(CharArr* arr, char item) {
    if (arr->used-1 == arr->size) {
        arr->size *= 2;
        arr->array = (char *)realloc(arr->array, arr->size * sizeof(char));
    }
    arr->array[arr->used++] = item;
    arr->array[arr->used] = '\0';
}

void catArr(CharArr* arr, char* items, int arrLen) {
    int i;
    for(i = 0; i < arrLen; i++) {
        addArr(arr, items[i]);
    }
}

/**
    Free allocated memory of arr
*/
void freeArr(CharArr* arr) {
    int i;
    for(i = 0; i < arr->used; i++) {
        arr->array[i] = 0;
    }
    free(arr->array);
    arr->array = NULL;
    arr->used = arr->size = 0;
}
void resetArr(CharArr* arr) {
    size_t originalSize = arr->size;
    freeArr(arr);
    initArr(arr, originalSize);
}

int loadDefaultVariables(char* configFile, CharArr* defaultPath) {
    CharArr fileBuffer;
    int fd, portBuffer;
    char bc;
    char* rval;
    char* baseUrl = "/home/pi/shellScripting/Lab2/C/CWebserver/www/";
    int basePort = 8888;
    initArr(&fileBuffer, 10);
    /* Read the defaultPath */
    fd = open(configFile, O_RDONLY);
    while (fileBuffer.array[fileBuffer.used-1] != '\n' ) {
        read(fd, &bc, 1);
        addArr(&fileBuffer, bc);
    }
    rval = strrchr(fileBuffer.array, ':');
    if(!rval) {
        printf("No default url found\n");
        //No default path found... use default default...
        rval = baseUrl;
    } else {
        rval++;
    }
    catArr(defaultPath, rval, strlen(rval)-1);
    resetArr(&fileBuffer);
    /* Read the defaultPort */
    while (fileBuffer.array[fileBuffer.used-1] != '\n' ) {
        read(fd, &bc, 1);
        addArr(&fileBuffer, bc);
    }
    rval = strrchr(fileBuffer.array, ':');
    if(!rval) {
        printf("no default port found\n");
        //No default path found... use default default...
        portBuffer = basePort;
    } else {
        rval++;
        portBuffer = strtol(rval, (char **)NULL, 10);
    }
    freeArr(&fileBuffer);
    return portBuffer;
}

void getFormatedTime(char* buffer) {
    time_t rawtime;
    struct tm * timeinfo;

    time (&rawtime);
    timeinfo = localtime (&rawtime);

    strftime (buffer,80,"%d/%b/%Y:%H:%M:%S %z",timeinfo);
}


text:
"""
remote bash-script installation of selected package

Usage: python install_pathos_server.py [package] [version] [hostname]
    [package] - name of the package to install
    [version] - version of the package to install
    [hostname] - name of the host on which to install the package
"""

from pathos.core import copy,execute
from pathos.hosts import get_profile, register_profiles

if __name__ == '__main__':

##### CONFIGURATION & INPUT ########################
  # set the default remote host
  rhost = 'localhost'
 #rhost = 'foobar.danse.us'
 #rhost = 'computer.cacr.caltech.edu'

  # set any 'special' profiles (those which don't use default_profie)
  profiles = {'foobar.danse.us':'.profile',
              'computer.cacr.caltech.edu':'.cshrc'}

  from time import sleep
  delay = 0.0
  big_delay = 5.0

  # set the default package & version
  package = 'pp'    #XXX: package name MUST correspond to X in installer-X.sh
  version = '1.5.7' #XXX: also hardwired in installer-X.sh

  print """Usage: python install_pathos_server.py [package] [version] [hostname]
    [package] - name of the package to install
    [version] - version of the package to install
    [hostname] - name of the host on which to install the package
    defaults are: "%s" "%s" "%s".""" % (package, version, rhost)

  # get package to install from user
  import sys
  if '--help' in sys.argv:
    sys.exit(0)
  try:
    myinp = sys.argv[1],sys.argv[2]
  except: myinp = None
  if myinp:
    package,version = myinp #XXX: should test validity here... (filename)
  else: pass # use default
  del myinp

  # get remote hostname from user
  import sys
  try:
    myinp = sys.argv[3]
  except: myinp = None
  if myinp:
    rhost = myinp #XXX: should test rhost validity here... (how ?)
  else: pass # use default
  del myinp

  # get remote profile (this should go away soon)
  import sys
  try:
    myinp = sys.argv[4]
  except: myinp = None
  if myinp:
    rprof = myinp #XXX: should test validity here... (filename)
    profiles = {rhost:rprof}
  else: pass # use default
  del myinp

  # my remote environment (should be auto-detected)
  register_profiles(profiles)
  profile = get_profile(rhost)

##### CONFIGURATION & INPUT ########################

  file = 'install-%s-%s.sh' % (package,version)
  # XXX: should use easy_install, if is installed...

  import tempfile
# tempfile.tempdir = "~" #XXX: uncomment if cannot install to '/tmp'
  dest = tempfile.mktemp()+"_install" #XXX: checks local (not remote)

  # check for existing installation
  command = "source %s; python -c 'import %s'" % (profile,package)
  error = execute(command,rhost).response()
  if error in ['', None]:
    print '%s is already installed on %s' % (package,rhost)
# elif error[:39] == 'This system is available for legitimate use'[:39] \
#      and rhost[:3] == 'shc-b.cacr.caltech.edu'[:3]:
##     and error[-35:-1] == 'an authorized user of this system.'[-35:] \
#   print '%s is already installed on %s' % (package,rhost)
    #XXX: could parse 'error' for "ImportError" ==> not installed
    #XXX: could use command="python -c 'import X; X.__version__'"
    #XXX  ...returns version# or "AttributeError" ==> non-standard version tag
  else:
    print error
    sleep(delay)

    # create install directory
    command = 'mkdir -p %s' % dest #FIXME: *nix only
    report = execute(command,rhost).response()
    #XXX: could check for clean install by parsing for "Error" (?)
    sleep(delay)

    # copy over the installer to remote host
    copy(file,rhost,dest)
    sleep(delay)

    # run the installer
    command = 'cd %s; ./%s' % (dest,file) #FIXME: *nix only
    report = execute(command,rhost).response()
    #XXX: could check for clean install by parsing for "Error" (?)
    sleep(big_delay)

    # remove remote install file
#   killme = dest+'/'+file  #FIXME: *nix only
#   command = 'rm -f %s' % killme #FIXME: *nix only
#   execute(command,rhost).response()

    # remove remote package unpacking directory
#   killme = dest+'/'+package+'-'+version #FIXME: dies for NON-STANDARD naming
#   command = 'rm -rf %s' % killme #FIXME: *nix only
#   execute(command,rhost).response()

    # remove remote install directory
    killme = dest
    command = 'rm -rf %s' % killme #FIXME: *nix only
    execute(command,rhost).response()

    # check installation
    command = "source %s; python -c 'import %s'" % (profile,package)
    error = execute(command,rhost).response()
    if error in ['', None]:
      pass # is installed
    else:
      print error
#     raise ImportError, "failure to install package"


text:
add old-style parent ctor by adoptting
--SKIPIF--
<?php if(!extension_loaded("runkit") || !RUNKIT_FEATURE_MANIPULATION) print "skip"; ?>
--FILE--
<?php

class Father {
	function teSt() {
		var_dump('new constructor');
	}
}

class Test {
}

class FOO_test extends test {
}

class FOO_test_Child extends FOO_test {
}

runkit_class_adopt("Test", "Father");
$a = new test;
$a = new foo_test;
$a = new FOO_test_Child;

runkit_class_emancipate("Test");
echo "after emancipation\n";
$a = new test;
$a = new foo_test;
$a = new FOO_test_Child;

?>
--EXPECT--
string(15) "new constructor"
string(15) "new constructor"
string(15) "new constructor"
after emancipation


text:
<?php

use Exolnet\Addressing\CountyTranslation;

class CountyTranslationTest extends \PHPUnit_Framework_TestCase
{
	/**
	 * @var \Exolnet\Addressing\CountyTranslation
	 */
	protected $model;

	public function setUp()
	{
		$this->model = new CountyTranslation();
	}

	public function testItIsInitializable()
	{
		$this->assertInstanceOf(CountyTranslation::class, $this->model);
	}
}