text:
namespace IPC {
class Message;
}  // namespace IPC

namespace {
// For breaking deep recursion.
int g_depth = 0;
}  // namespace

namespace ipc_fuzzer {

FuzzerFunctionVector g_function_vector;

bool Fuzzer::ShouldGenerate() {
  return false;
}

// Partially-specialized class that knows how to handle a given type.
template <class P>
struct FuzzTraits {
  static bool Fuzz(P* p, Fuzzer *fuzzer) {
    // This is the catch-all for types we don't have enough information
    // to generate.
    std::cerr << "Can't handle " << PRETTY_FUNCTION << "\n";
    return false;
  }
};

// Template function to invoke partially-specialized class method.
template <class P>
static bool FuzzParam(P* p, Fuzzer* fuzzer) {
  return FuzzTraits<P>::Fuzz(p, fuzzer);
}

template <class P>
static bool FuzzParamArray(P* p, size_t length, Fuzzer* fuzzer) {
  for (size_t i = 0; i < length; i++, p++) {
    if (!FuzzTraits<P>::Fuzz(p, fuzzer))
      return false;
  }
  return true;
}

// Specializations to generate primitive types.
template <>
struct FuzzTraits<bool> {
  static bool Fuzz(bool* p, Fuzzer* fuzzer) {
    fuzzer->FuzzBool(p);
    return true;
  }
};

template <>
struct FuzzTraits<int> {
  static bool Fuzz(int* p, Fuzzer* fuzzer) {
    fuzzer->FuzzInt(p);
    return true;
  }
};

template <>
struct FuzzTraits<unsigned int> {
  static bool Fuzz(unsigned int* p, Fuzzer* fuzzer) {
    fuzzer->FuzzInt(reinterpret_cast<int*>(p));
    return true;
  }
};

template <>
struct FuzzTraits<long> {
  static bool Fuzz(long* p, Fuzzer* fuzzer) {
    fuzzer->FuzzLong(p);
    return true;
  }
};

template <>
struct FuzzTraits<unsigned long> {
  static bool Fuzz(unsigned long* p, Fuzzer* fuzzer) {
    fuzzer->FuzzLong(reinterpret_cast<long*>(p));
    return true;
  }
};

template <>
struct FuzzTraits<long long> {
  static bool Fuzz(long long* p, Fuzzer* fuzzer) {
    fuzzer->FuzzInt64(reinterpret_cast<int64_t*>(p));
    return true;
  }
};

template <>
struct FuzzTraits<unsigned long long> {
  static bool Fuzz(unsigned long long* p, Fuzzer* fuzzer) {
    fuzzer->FuzzInt64(reinterpret_cast<int64_t*>(p));
    return true;
  }
};

template <>
struct FuzzTraits<short> {
  static bool Fuzz(short* p, Fuzzer* fuzzer) {
    fuzzer->FuzzUInt16(reinterpret_cast<uint16_t*>(p));
    return true;
  }
};

template <>
struct FuzzTraits<unsigned short> {
  static bool Fuzz(unsigned short* p, Fuzzer* fuzzer) {
    fuzzer->FuzzUInt16(reinterpret_cast<uint16_t*>(p));
    return true;
  }
};

template <>
struct FuzzTraits<char> {
  static bool Fuzz(char* p, Fuzzer* fuzzer) {
    fuzzer->FuzzUChar(reinterpret_cast<unsigned char*>(p));
    return true;
  }
};

template <>
struct FuzzTraits<signed char> {
  static bool Fuzz(signed char* p, Fuzzer* fuzzer) {
    fuzzer->FuzzUChar(reinterpret_cast<unsigned char*>(p));
    return true;
  }
};

template <>
struct FuzzTraits<unsigned char> {
  static bool Fuzz(unsigned char* p, Fuzzer* fuzzer) {
    fuzzer->FuzzUChar(p);
    return true;
  }
};

template <>
struct FuzzTraits<wchar_t> {
  static bool Fuzz(wchar_t* p, Fuzzer* fuzzer) {
    fuzzer->FuzzWChar(p);
    return true;
  }
};

template <>
struct FuzzTraits<float> {
  static bool Fuzz(float* p, Fuzzer* fuzzer) {
    fuzzer->FuzzFloat(p);
    return true;
  }
};

template <>
struct FuzzTraits<double> {
  static bool Fuzz(double* p, Fuzzer* fuzzer) {
    fuzzer->FuzzDouble(p);
    return true;
  }
};

template <>
struct FuzzTraits<std::string> {
  static bool Fuzz(std::string* p, Fuzzer* fuzzer) {
    fuzzer->FuzzString(p);
    return true;
  }
};

template <>
struct FuzzTraits<std::u16string> {
  static bool Fuzz(std::u16string* p, Fuzzer* fuzzer) {
    fuzzer->FuzzString16(p);
    return true;
  }
};

// Specializations for tuples.
template <>
struct FuzzTraits<std::tuple<>> {
  static bool Fuzz(std::tuple<>* p, Fuzzer* fuzzer) { return true; }
};

template <class A>
struct FuzzTraits<std::tuple<A>> {
  static bool Fuzz(std::tuple<A>* p, Fuzzer* fuzzer) {
    return FuzzParam(&std::get<0>(*p), fuzzer);
  }
};

template <class A, class B>
struct FuzzTraits<std::tuple<A, B>> {
  static bool Fuzz(std::tuple<A, B>* p, Fuzzer* fuzzer) {
    return FuzzParam(&std::get<0>(*p), fuzzer) &&
           FuzzParam(&std::get<1>(*p), fuzzer);
  }
};

template <class A, class B, class C>
struct FuzzTraits<std::tuple<A, B, C>> {
  static bool Fuzz(std::tuple<A, B, C>* p, Fuzzer* fuzzer) {
    return FuzzParam(&std::get<0>(*p), fuzzer) &&
           FuzzParam(&std::get<1>(*p), fuzzer) &&
           FuzzParam(&std::get<2>(*p), fuzzer);
  }
};

template <class A, class B, class C, class D>
struct FuzzTraits<std::tuple<A, B, C, D>> {
  static bool Fuzz(std::tuple<A, B, C, D>* p, Fuzzer* fuzzer) {
    return FuzzParam(&std::get<0>(*p), fuzzer) &&
           FuzzParam(&std::get<1>(*p), fuzzer) &&
           FuzzParam(&std::get<2>(*p), fuzzer) &&
           FuzzParam(&std::get<3>(*p), fuzzer);
  }
};

template <class A, class B, class C, class D, class E>
struct FuzzTraits<std::tuple<A, B, C, D, E>> {
  static bool Fuzz(std::tuple<A, B, C, D, E>* p, Fuzzer* fuzzer) {
    return FuzzParam(&std::get<0>(*p), fuzzer) &&
           FuzzParam(&std::get<1>(*p), fuzzer) &&
           FuzzParam(&std::get<2>(*p), fuzzer) &&
           FuzzParam(&std::get<3>(*p), fuzzer) &&
           FuzzParam(&std::get<4>(*p), fuzzer);
  }
};

// Specializations for containers.
template <class A>
struct FuzzTraits<std::vector<A> > {
  static bool Fuzz(std::vector<A>* p, Fuzzer* fuzzer) {
    ++g_depth;
    size_t count = p->size();
    if (fuzzer->ShouldGenerate()) {
      count = g_depth > 3 ? 0 : RandElementCount();
      p->resize(count);
    }
    for (size_t i = 0; i < count; ++i) {
      if (!FuzzParam(&p->at(i), fuzzer)) {
        --g_depth;
        return false;
      }
    }
    --g_depth;
    return true;
  }
};

template <class A>
struct FuzzTraits<std::set<A> > {
  static bool Fuzz(std::set<A>* p, Fuzzer* fuzzer) {
    if (!fuzzer->ShouldGenerate()) {
      std::set<A> result;
      typename std::set<A>::iterator it;
      for (it = p->begin(); it != p->end(); ++it) {
        A item = *it;
        if (!FuzzParam(&item, fuzzer))
          return false;
        result.insert(item);
      }
      *p = result;
      return true;
    }

    static int g_depth = 0;
    size_t count = ++g_depth > 3 ? 0 : RandElementCount();
    A a;
    for (size_t i = 0; i < count; ++i) {
      if (!FuzzParam(&a, fuzzer)) {
        --g_depth;
        return false;
      }
      p->insert(a);
    }
    --g_depth;
    return true;
  }
};

template <class A, class B>
struct FuzzTraits<std::map<A, B> > {
  static bool Fuzz(std::map<A, B>* p, Fuzzer* fuzzer) {
    if (!fuzzer->ShouldGenerate()) {
      typename std::map<A, B>::iterator it;
      for (it = p->begin(); it != p->end(); ++it) {
        if (!FuzzParam(&it->second, fuzzer))
          return false;
      }
      return true;
    }

    static int g_depth = 0;
    size_t count = ++g_depth > 3 ? 0 : RandElementCount();
    std::pair<A, B> place_holder;
    for (size_t i = 0; i < count; ++i) {
      if (!FuzzParam(&place_holder, fuzzer)) {
        --g_depth;
        return false;
      }
      p->insert(place_holder);
    }
    --g_depth;
    return true;
  }
};

template <class A, class B, class C, class D>
struct FuzzTraits<std::map<A, B, C, D>> {
  static bool Fuzz(std::map<A, B, C, D>* p, Fuzzer* fuzzer) {
    if (!fuzzer->ShouldGenerate()) {
      typename std::map<A, B, C, D>::iterator it;
      for (it = p->begin(); it != p->end(); ++it) {
        if (!FuzzParam(&it->second, fuzzer))
          return false;
      }
      return true;
    }

    static int g_depth = 0;
    size_t count = ++g_depth > 3 ? 0 : RandElementCount();
    std::pair<A, B> place_holder;
    for (size_t i = 0; i < count; ++i) {
      if (!FuzzParam(&place_holder, fuzzer)) {
        --g_depth;
        return false;
      }
      p->insert(place_holder);
    }
    --g_depth;
    return true;
  }
};

template <class A, class B>
struct FuzzTraits<std::pair<A, B> > {
  static bool Fuzz(std::pair<A, B>* p, Fuzzer* fuzzer) {
    return
        FuzzParam(&p->first, fuzzer) &&
        FuzzParam(&p->second, fuzzer);
  }
};

// Specializations for hand-coded types.

template <>
struct FuzzTraits<base::FilePath> {
  static bool Fuzz(base::FilePath* p, Fuzzer* fuzzer) {
    if (!fuzzer->ShouldGenerate()) {
      base::FilePath::StringType path = p->value();
      if(!FuzzParam(&path, fuzzer))
        return false;
      *p = base::FilePath(path);
      return true;
    }

    const char path_chars[] = "ACz0/.~:";
    size_t count = RandInRange(60);
    base::FilePath::StringType random_path;
    for (size_t i = 0; i < count; ++i)
      random_path += path_chars[RandInRange(sizeof(path_chars) - 1)];
    *p = base::FilePath(random_path);
    return true;
  }
};

template <>
struct FuzzTraits<base::File::Error> {
  static bool Fuzz(base::File::Error* p, Fuzzer* fuzzer) {
    int value = static_cast<int>(*p);
    if (!FuzzParam(&value, fuzzer))
      return false;
    *p = static_cast<base::File::Error>(value);
    return true;
  }
};

template <>
struct FuzzTraits<base::File::Info> {
  static bool Fuzz(base::File::Info* p, Fuzzer* fuzzer) {
    double last_modified = p->last_modified.ToDoubleT();
    double last_accessed = p->last_accessed.ToDoubleT();
    double creation_time = p->creation_time.ToDoubleT();
    if (!FuzzParam(&p->size, fuzzer))
      return false;
    if (!FuzzParam(&p->is_directory, fuzzer))
      return false;
    if (!FuzzParam(&last_modified, fuzzer))
      return false;
    if (!FuzzParam(&last_accessed, fuzzer))
      return false;
    if (!FuzzParam(&creation_time, fuzzer))
      return false;
    p->last_modified = base::Time::FromDoubleT(last_modified);
    p->last_accessed = base::Time::FromDoubleT(last_accessed);
    p->creation_time = base::Time::FromDoubleT(creation_time);
    return true;
  }
};

template <>
struct FuzzTraits<base::Time> {
  static bool Fuzz(base::Time* p, Fuzzer* fuzzer) {
    int64_t internal_value = p->ToInternalValue();
    if (!FuzzParam(&internal_value, fuzzer))
      return false;
    *p = base::Time::FromInternalValue(internal_value);
    return true;
  }
};

template <>
struct FuzzTraits<base::TimeDelta> {
  static bool Fuzz(base::TimeDelta* p, Fuzzer* fuzzer) {
    int64_t internal_value = p->ToInternalValue();
    if (!FuzzParam(&internal_value, fuzzer))
      return false;
    *p = base::TimeDelta::FromInternalValue(internal_value);
    return true;
  }
};

template <>
struct FuzzTraits<base::TimeTicks> {
  static bool Fuzz(base::TimeTicks* p, Fuzzer* fuzzer) {
    int64_t internal_value = p->ToInternalValue();
    if (!FuzzParam(&internal_value, fuzzer))
      return false;
    *p = base::TimeTicks::FromInternalValue(internal_value);
    return true;
  }
};

template <>
struct FuzzTraits<base::Value> {
  static bool Fuzz(base::Value* p, Fuzzer* fuzzer) {
    DCHECK(p->type() == base::Value::Type::LIST ||
           p->type() == base::Value::Type::DICTIONARY);

    // TODO(mbarbella): Support mutation.
    if (!fuzzer->ShouldGenerate())
      return true;

    if (g_depth > 2)
      return true;

    g_depth++;

    const size_t kMaxSize = 8;
    size_t random_size = RandInRange(kMaxSize);
    for (size_t i = 0; i < random_size; i++) {
      base::Value random_value;
      const size_t kNumValueTypes = 8;
      switch (static_cast<base::Value::Type>(RandInRange(kNumValueTypes))) {
        case base::Value::Type::BOOLEAN: {
          bool tmp;
          fuzzer->FuzzBool(&tmp);
          random_value = base::Value(tmp);
          break;
        }
        case base::Value::Type::INTEGER: {
          int tmp;
          fuzzer->FuzzInt(&tmp);
          random_value = base::Value(tmp);
          break;
        }
        case base::Value::Type::DOUBLE: {
          double tmp;
          fuzzer->FuzzDouble(&tmp);
          random_value = base::Value(tmp);
          break;
        }
        case base::Value::Type::BINARY: {
          char tmp[200];
          size_t bin_length = RandInRange(sizeof(tmp));
          fuzzer->FuzzData(tmp, bin_length);
          random_value =
              base::Value(base::as_bytes(base::make_span(tmp, bin_length)));
          break;
        }
        case base::Value::Type::STRING: {
          random_value = base::Value(base::Value::Type::STRING);
          fuzzer->FuzzString(&random_value.GetString());
          break;
        }
        case base::Value::Type::DICTIONARY: {
          random_value = base::Value(base::Value::Type::DICTIONARY);
          FuzzParam(&random_value, fuzzer);
          break;
        }
        case base::Value::Type::LIST: {
          random_value = base::Value(base::Value::Type::LIST);
          FuzzParam(&random_value, fuzzer);
          break;
        }
        case base::Value::Type::NONE:
          // |random_value| already has type NONE, nothing to do.
          break;
      }

      // Add |random_value| to the container.
      if (p->type() == base::Value::Type::LIST) {
        p->Append(std::move(random_value));
      } else {
        // |p| is a dictionary, a fuzzed key is also required.
        std::string key;
        fuzzer->FuzzString(&key);
        p->SetKey(key, std::move(random_value));
      }
    }

    --g_depth;
    return true;
  }
};

template <>
struct FuzzTraits<base::UnguessableToken> {
  static bool Fuzz(base::UnguessableToken* p, Fuzzer* fuzzer) {
    auto low = p->GetLowForSerialization();
    auto high = p->GetHighForSerialization();
    if (!FuzzParam(&low, fuzzer))
      return false;
    if (!FuzzParam(&high, fuzzer))
      return false;
    while (high == 0 && low == 0) {
      FuzzParam(&low, fuzzer);
      FuzzParam(&high, fuzzer);
    }
    *p = base::UnguessableToken::Deserialize(high, low);
    return true;
  }
};

template <>
struct FuzzTraits<base::UnsafeSharedMemoryRegion> {
  static bool Fuzz(base::UnsafeSharedMemoryRegion* p, Fuzzer* fuzzer) {
    size_t size = RandInRange(16 * 1024 * 1024 * sizeof(char));
    *p = base::UnsafeSharedMemoryRegion::Create(size);
    return true;
  }
};

template <>
struct FuzzTraits<blink::mojom::EmulatedScreenType> {
  static bool Fuzz(blink::mojom::EmulatedScreenType* p, Fuzzer* fuzzer) {
    int screen_type = RandInRange(
        static_cast<int>(blink::mojom::EmulatedScreenType::kMaxValue) + 1);
    *p = static_cast<blink::mojom::EmulatedScreenType>(screen_type);
    return true;
  }
};

template <>
struct FuzzTraits<viz::FrameSinkId> {
  static bool Fuzz(viz::FrameSinkId* p, Fuzzer* fuzzer) {
    uint32_t client_id;
    uint32_t sink_id;
    if (!FuzzParam(&client_id, fuzzer))
      return false;
    if (!FuzzParam(&sink_id, fuzzer))
      return false;
    *p = viz::FrameSinkId(client_id, sink_id);
    return true;
  }
};

template <>
struct FuzzTraits<viz::LocalSurfaceId> {
  static bool Fuzz(viz::LocalSurfaceId* p, Fuzzer* fuzzer) {
    uint32_t parent_sequence_number = p->parent_sequence_number();
    uint32_t child_sequence_number = p->child_sequence_number();
    base::UnguessableToken embed_token = p->embed_token();
    if (!FuzzParam(&parent_sequence_number, fuzzer))
      return false;
    if (!FuzzParam(&child_sequence_number, fuzzer))
      return false;
    if (!FuzzParam(&embed_token, fuzzer))
      return false;
    *p = viz::LocalSurfaceId(parent_sequence_number, child_sequence_number,
                             embed_token);
    return true;
  }
};

template <>
struct FuzzTraits<viz::ResourceFormat> {
  static bool Fuzz(viz::ResourceFormat* p, Fuzzer* fuzzer) {
    int format = RandInRange(viz::ResourceFormat::RESOURCE_FORMAT_MAX + 1);
    *p = static_cast<viz::ResourceFormat>(format);
    return true;
  }
};

template <>
struct FuzzTraits<blink::PageState> {
  static bool Fuzz(blink::PageState* p, Fuzzer* fuzzer) {
    std::string data = p->ToEncodedData();
    if (!FuzzParam(&data, fuzzer))
      return false;
    *p = blink::PageState::CreateFromEncodedData(data);
    return true;
  }
};

template <>
struct FuzzTraits<device::mojom::ScreenOrientationLockType> {
  static bool Fuzz(device::mojom::ScreenOrientationLockType* p,
                   Fuzzer* fuzzer) {
    int value = RandInRange(
        static_cast<int>(device::mojom::ScreenOrientationLockType::kMaxValue) +
        1);
    *p = static_cast<device::mojom::ScreenOrientationLockType>(value);
    return true;
  }
};

template <>
struct FuzzTraits<ContentSettingsPattern> {
  static bool Fuzz(ContentSettingsPattern* p, Fuzzer* fuzzer) {
    // TODO(mbarbella): This can crash if a pattern is generated from a random
    // string. We could carefully generate a pattern or fix pattern generation.
    return true;
  }
};

template <>
struct FuzzTraits<gfx::BufferFormat> {
  static bool Fuzz(gfx::BufferFormat* p, Fuzzer* fuzzer) {
    int format = RandInRange(static_cast<int>(gfx::BufferFormat::LAST) + 1);
    *p = static_cast<gfx::BufferFormat>(format);
    return true;
  }
};

template <>
struct FuzzTraits<gfx::ColorSpace> {
  static bool Fuzz(gfx::ColorSpace* p, Fuzzer* fuzzer) {
    gfx::ColorSpace::PrimaryID primaries;
    gfx::ColorSpace::TransferID transfer;
    gfx::ColorSpace::MatrixID matrix;
    gfx::ColorSpace::RangeID range;
    if (!FuzzParam(&primaries, fuzzer))
      return false;
    if (!FuzzParam(&transfer, fuzzer))
      return false;
    if (!FuzzParam(&matrix, fuzzer))
      return false;
    if (!FuzzParam(&range, fuzzer))
      return false;
    *p = gfx::ColorSpace(primaries, transfer, matrix, range);
    return true;
  }
};

template <>
struct FuzzTraits<gfx::ColorSpace::MatrixID> {
  static bool Fuzz(gfx::ColorSpace::MatrixID* p, Fuzzer* fuzzer) {
    uint8_t matrix =
        RandInRange(static_cast<int>(gfx::ColorSpace::MatrixID::kMaxValue) + 1);
    *p = static_cast<gfx::ColorSpace::MatrixID>(matrix);
    return true;
  }
};

template <>
struct FuzzTraits<gfx::ColorSpace::PrimaryID> {
  static bool Fuzz(gfx::ColorSpace::PrimaryID* p, Fuzzer* fuzzer) {
    int primaries = RandInRange(
        static_cast<int>(gfx::ColorSpace::PrimaryID::kMaxValue) + 1);
    *p = static_cast<gfx::ColorSpace::PrimaryID>(primaries);
    return true;
  }
};

template <>
struct FuzzTraits<gfx::ColorSpace::RangeID> {
  static bool Fuzz(gfx::ColorSpace::RangeID* p, Fuzzer* fuzzer) {
    uint8_t range =
        RandInRange(static_cast<int>(gfx::ColorSpace::RangeID::kMaxValue) + 1);
    *p = static_cast<gfx::ColorSpace::RangeID>(range);
    return true;
  }
};

template <>
struct FuzzTraits<gfx::ColorSpace::TransferID> {
  static bool Fuzz(gfx::ColorSpace::TransferID* p, Fuzzer* fuzzer) {
    uint8_t transfer = RandInRange(
        static_cast<int>(gfx::ColorSpace::TransferID::kMaxValue) + 1);
    *p = static_cast<gfx::ColorSpace::TransferID>(transfer);
    return true;
  }
};

template <>
struct FuzzTraits<gfx::GpuFenceHandle> {
  static bool Fuzz(gfx::GpuFenceHandle* p, Fuzzer* fuzzer) {
    return true;
  }
};

template <>
struct FuzzTraits<gfx::GpuMemoryBufferHandle> {
  static bool Fuzz(gfx::GpuMemoryBufferHandle* p, Fuzzer* fuzzer) {
    int type;
    if (!FuzzParam(&type, fuzzer))
      return false;
    if (!FuzzParam(&p->offset, fuzzer))
      return false;
    if (!FuzzParam(&p->stride, fuzzer))
      return false;
    if (!FuzzParam(&p->region, fuzzer))
      return false;
    p->type = static_cast<gfx::GpuMemoryBufferType>(type);
    return true;
  }
};

template <>
struct FuzzTraits<gfx::Point> {
  static bool Fuzz(gfx::Point* p, Fuzzer* fuzzer) {
    int x = p->x();
    int y = p->y();
    if (!FuzzParam(&x, fuzzer))
      return false;
    if (!FuzzParam(&y, fuzzer))
      return false;
    p->SetPoint(x, y);
    return true;
  }
};

template <>
struct FuzzTraits<gfx::PointF> {
  static bool Fuzz(gfx::PointF* p, Fuzzer* fuzzer) {
    float x = p->x();
    float y = p->y();
    if (!FuzzParam(&x, fuzzer))
      return false;
    if (!FuzzParam(&y, fuzzer))
      return false;
    p->SetPoint(x, y);
    return true;
  }
};

template <>
struct FuzzTraits<gfx::PresentationFeedback> {
  static bool Fuzz(gfx::PresentationFeedback* p, Fuzzer* fuzzer) {
    if (!FuzzParam(&p->timestamp, fuzzer))
      return false;
    if (!FuzzParam(&p->interval, fuzzer))
      return false;
    if (!FuzzParam(&p->flags, fuzzer))
      return false;
    return true;
  }
};

template <>
struct FuzzTraits<gfx::Rect> {
  static bool Fuzz(gfx::Rect* p, Fuzzer* fuzzer) {
    gfx::Point origin = p->origin();
    gfx::Size size = p->size();
    if (!FuzzParam(&origin, fuzzer))
      return false;
    if (!FuzzParam(&size, fuzzer))
      return false;
    p->set_origin(origin);
    p->set_size(size);
    return true;
  }
};

template <>
struct FuzzTraits<gfx::RectF> {
  static bool Fuzz(gfx::RectF* p, Fuzzer* fuzzer) {
    gfx::PointF origin = p->origin();
    gfx::SizeF size = p->size();
    if (!FuzzParam(&origin, fuzzer))
      return false;
    if (!FuzzParam(&size, fuzzer))
      return false;
    p->set_origin(origin);
    p->set_size(size);
    return true;
  }
};

template <>
struct FuzzTraits<gfx::Range> {
  static bool Fuzz(gfx::Range* p, Fuzzer* fuzzer) {
    size_t start = p->start();
    size_t end = p->end();
    if (!FuzzParam(&start, fuzzer))
      return false;
    if (!FuzzParam(&end, fuzzer))
      return false;
    *p = gfx::Range(start, end);
    return true;
  }
};

template <>
struct FuzzTraits<gfx::Size> {
  static bool Fuzz(gfx::Size* p, Fuzzer* fuzzer) {
    int width = p->width();
    int height = p->height();
    if (!FuzzParam(&width, fuzzer))
      return false;
    if (!FuzzParam(&height, fuzzer))
      return false;
    p->SetSize(width, height);
    return true;
  }
};

template <>
struct FuzzTraits<gfx::SizeF> {
  static bool Fuzz(gfx::SizeF* p, Fuzzer* fuzzer) {
    float w;
    float h;
    if (!FuzzParam(&w, fuzzer))
      return false;
    if (!FuzzParam(&h, fuzzer))
      return false;
    p->SetSize(w, h);
    return true;
  }
};

template <>
struct FuzzTraits<gfx::SwapResponse> {
  static bool Fuzz(gfx::SwapResponse* p, Fuzzer* fuzzer) {
    if (!FuzzParam(&p->swap_id, fuzzer))
      return false;
    if (!FuzzParam(&p->result, fuzzer))
      return false;
    if (!FuzzParam(&p->timings, fuzzer))
      return false;
    return true;
  }
};

template <>
struct FuzzTraits<gfx::SwapResult> {
  static bool Fuzz(gfx::SwapResult* p, Fuzzer* fuzzer) {
    int result =
        RandInRange(static_cast<int>(gfx::SwapResult::SWAP_RESULT_LAST) + 1);
    *p = static_cast<gfx::SwapResult>(result);
    return true;
  }
};

template <>
struct FuzzTraits<gfx::SwapTimings> {
  static bool Fuzz(gfx::SwapTimings* p, Fuzzer* fuzzer) {
    if (!FuzzParam(&p->swap_start, fuzzer))
      return false;
    if (!FuzzParam(&p->swap_end, fuzzer))
      return false;
    return true;
  }
};

template <>
struct FuzzTraits<gfx::Transform> {
  static bool Fuzz(gfx::Transform* p, Fuzzer* fuzzer) {
    SkScalar matrix[16];
    for (size_t i = 0; i < base::size(matrix); i++) {
      matrix[i] = p->matrix().get(i / 4, i % 4);
    }
    if (!FuzzParamArray(&matrix[0], base::size(matrix), fuzzer))
      return false;
    *p = gfx::Transform(matrix[0], matrix[1], matrix[2], matrix[3], matrix[4],
                        matrix[5], matrix[6], matrix[7], matrix[8], matrix[9],
                        matrix[10], matrix[11], matrix[12], matrix[13],
                        matrix[14], matrix[15]);
    return true;
  }
};

template <>
struct FuzzTraits<gfx::Vector2d> {
  static bool Fuzz(gfx::Vector2d* p, Fuzzer* fuzzer) {
    int x = p->x();
    int y = p->y();
    if (!FuzzParam(&x, fuzzer))
      return false;
    if (!FuzzParam(&y, fuzzer))
      return false;
    *p = gfx::Vector2d(x, y);
    return true;
  }
};

template <>
struct FuzzTraits<gfx::Vector2dF> {
  static bool Fuzz(gfx::Vector2dF* p, Fuzzer* fuzzer) {
    float x = p->x();
    float y = p->y();
    if (!FuzzParam(&x, fuzzer))
      return false;
    if (!FuzzParam(&y, fuzzer))
      return false;
    *p = gfx::Vector2dF(x, y);
    return true;
  }
};

template <typename TypeMarker, typename WrappedType, WrappedType kInvalidValue>
struct FuzzTraits<base::IdType<TypeMarker, WrappedType, kInvalidValue>> {
  using param_type = base::IdType<TypeMarker, WrappedType, kInvalidValue>;
  static bool Fuzz(param_type* id, Fuzzer* fuzzer) {
    WrappedType raw_value = id->GetUnsafeValue();
    if (!FuzzParam(&raw_value, fuzzer))
      return false;
    *id = param_type::FromUnsafeValue(raw_value);
    return true;
  }
};

template <>
struct FuzzTraits<base::StrongAlias<extensions::ActivationSequenceTag, int>> {
  static bool Fuzz(base::StrongAlias<extensions::ActivationSequenceTag, int>* p,
                   Fuzzer* fuzzer) {
    int value;
    if (!FuzzParam(&value, fuzzer))
      return false;
    *p = base::StrongAlias<extensions::ActivationSequenceTag, int>(value);
    return true;
  }
};

template <>
struct FuzzTraits<gl::GpuPreference> {
  static bool Fuzz(gl::GpuPreference* p, Fuzzer* fuzzer) {
    int preference =
        RandInRange(static_cast<int>(gl::GpuPreference::kMaxValue) + 1);
    *p = static_cast<gl::GpuPreference>(preference);
    return true;
  }
};

template <>
struct FuzzTraits<gpu::ColorSpace> {
  static bool Fuzz(gpu::ColorSpace* p, Fuzzer* fuzzer) {
    int color_space = RandInRange(gpu::ColorSpace::COLOR_SPACE_LAST + 1);
    *p = static_cast<gpu::ColorSpace>(color_space);
    return true;
  }
};

template <>
struct FuzzTraits<gpu::CommandBuffer::State> {
  static bool Fuzz(gpu::CommandBuffer::State* p, Fuzzer* fuzzer) {
    if (!FuzzParam(&p->get_offset, fuzzer))
      return false;
    if (!FuzzParam(&p->token, fuzzer))
      return false;
    if (!FuzzParam(&p->release_count, fuzzer))
      return false;
    if (!FuzzParam(&p->error, fuzzer))
      return false;
    if (!FuzzParam(&p->context_lost_reason, fuzzer))
      return false;
    if (!FuzzParam(&p->generation, fuzzer))
      return false;
    if (!FuzzParam(&p->set_get_buffer_count, fuzzer))
      return false;
    return true;
  }
};

template <>
struct FuzzTraits<gpu::CommandBufferNamespace> {
  static bool Fuzz(gpu::CommandBufferNamespace* p, Fuzzer* fuzzer) {
    int name_space =
        RandInRange(gpu::CommandBufferNamespace::NUM_COMMAND_BUFFER_NAMESPACES);
    *p = static_cast<gpu::CommandBufferNamespace>(name_space);
    return true;
  }
};

template <>
struct FuzzTraits<gpu::ContextCreationAttribs> {
  static bool Fuzz(gpu::ContextCreationAttribs* p, Fuzzer* fuzzer) {
    if (!FuzzParam(&p->offscreen_framebuffer_size, fuzzer))
      return false;
    if (!FuzzParam(&p->gpu_preference, fuzzer))
      return false;
    if (!FuzzParam(&p->context_type, fuzzer))
      return false;
    if (!FuzzParam(&p->color_space, fuzzer))
      return false;
    return true;
  }
};

template <>
struct FuzzTraits<gpu::ContextType> {
  static bool Fuzz(gpu::ContextType* p, Fuzzer* fuzzer) {
    int type = RandInRange(gpu::ContextType::CONTEXT_TYPE_LAST + 1);
    *p = static_cast<gpu::ContextType>(type);
    return true;
  }
};

template <>
struct FuzzTraits<gpu::error::ContextLostReason> {
  static bool Fuzz(gpu::error::ContextLostReason* p, Fuzzer* fuzzer) {
    int reason =
        RandInRange(gpu::error::ContextLostReason::kContextLostReasonLast + 1);
    *p = static_cast<gpu::error::ContextLostReason>(reason);
    return true;
  }
};

template <>
struct FuzzTraits<gpu::error::Error> {
  static bool Fuzz(gpu::error::Error* p, Fuzzer* fuzzer) {
    int error = RandInRange(gpu::error::Error::kErrorLast + 1);
    *p = static_cast<gpu::error::Error>(error);
    return true;
  }
};

template <>
struct FuzzTraits<gpu::Mailbox> {
  static bool Fuzz(gpu::Mailbox* p, Fuzzer* fuzzer) {
    fuzzer->FuzzBytes(p->name, sizeof(p->name));
    return true;
  }
};

template <>
struct FuzzTraits<gpu::SchedulingPriority> {
  static bool Fuzz(gpu::SchedulingPriority* p, Fuzzer* fuzzer) {
    int priority =
        RandInRange(static_cast<int>(gpu::SchedulingPriority::kLast) + 1);
    *p = static_cast<gpu::SchedulingPriority>(priority);
    return true;
  }
};

template <>
struct FuzzTraits<gpu::SwapBuffersCompleteParams> {
  static bool Fuzz(gpu::SwapBuffersCompleteParams* p, Fuzzer* fuzzer) {
    if (!FuzzParam(&p->swap_response, fuzzer))
      return false;
    return true;
  }
};

template <>
struct FuzzTraits<gpu::SyncToken> {
  static bool Fuzz(gpu::SyncToken* p, Fuzzer* fuzzer) {
    bool verified_flush = false;
    gpu::CommandBufferNamespace namespace_id =
        gpu::CommandBufferNamespace::INVALID;
    gpu::CommandBufferId command_buffer_id;
    uint64_t release_count = 0;

    if (!FuzzParam(&verified_flush, fuzzer))
      return false;
    if (!FuzzParam(&namespace_id, fuzzer))
      return false;
    if (!FuzzParam(&command_buffer_id, fuzzer))
      return false;
    if (!FuzzParam(&release_count, fuzzer))
      return false;

    p->Clear();
    p->Set(namespace_id, command_buffer_id, release_count);
    if (verified_flush)
      p->SetVerifyFlush();
    return true;
  }
};

template <>
struct FuzzTraits<gpu::MailboxHolder> {
  static bool Fuzz(gpu::MailboxHolder* p, Fuzzer* fuzzer) {
    if (!FuzzParam(&p->mailbox, fuzzer))
      return false;
    if (!FuzzParam(&p->sync_token, fuzzer))
      return false;
    if (!FuzzParam(&p->texture_target, fuzzer))
      return false;
    return true;
  }
};

template <>
struct FuzzTraits<GURL> {
  static bool Fuzz(GURL* p, Fuzzer* fuzzer) {
    if (!fuzzer->ShouldGenerate()) {
      std::string spec = p->possibly_invalid_spec();
      if (!FuzzParam(&spec, fuzzer))
        return false;
      if (spec != p->possibly_invalid_spec())
        *p = GURL(spec);
      return true;
    }

    const char url_chars[] = "Ahtp0:/.?+\\%&#";
    size_t count = RandInRange(100);
    std::string random_url;
    for (size_t i = 0; i < count; ++i)
      random_url += url_chars[RandInRange(sizeof(url_chars) - 1)];
    int selector = RandInRange(10);
    if (selector == 0)
      random_url = std::string("http://") + random_url;
    else if (selector == 1)
      random_url = std::string("file://") + random_url;
    else if (selector == 2)
      random_url = std::string("javascript:") + random_url;
    else if (selector == 2)
      random_url = std::string("data:") + random_url;
    *p = GURL(random_url);
    return true;
  }
};

#if defined(OS_WIN)
template <>
struct FuzzTraits<HWND> {
  static bool Fuzz(HWND* p, Fuzzer* fuzzer) {
    // TODO(aarya): This should actually do something.
    return true;
  }
};
#endif

template <>
struct FuzzTraits<std::unique_ptr<IPC::Message>> {
  static bool Fuzz(std::unique_ptr<IPC::Message>* p, Fuzzer* fuzzer) {
    // TODO(mbarbella): Support mutation.
    if (!fuzzer->ShouldGenerate())
      return true;

    if (g_function_vector.empty())
      return false;
    size_t index = RandInRange(g_function_vector.size());
    std::unique_ptr<IPC::Message> ipc_message =
        (*g_function_vector[index])(nullptr, fuzzer);
    if (!ipc_message)
      return false;
    *p = std::move(ipc_message);
    return true;
  }
};

template <>
struct FuzzTraits<IPC::PlatformFileForTransit> {
  static bool Fuzz(IPC::PlatformFileForTransit* p, Fuzzer* fuzzer) {
    // TODO(inferno): I don't think we can generate real ones due to check on
    // construct.
    return true;
  }
};

template <>
struct FuzzTraits<IPC::ChannelHandle> {
  static bool Fuzz(IPC::ChannelHandle* p, Fuzzer* fuzzer) {
    // TODO(mbarbella): Support mutation.
    if (!fuzzer->ShouldGenerate())
      return true;

    return FuzzParam(&p->mojo_handle, fuzzer);
  }
};

#if defined(OS_WIN)
template <>
struct FuzzTraits<LOGFONT> {
  static bool Fuzz(LOGFONT* p, Fuzzer* fuzzer) {
    // TODO(aarya): This should actually do something.
    return true;
  }
};
#endif

template <>
struct FuzzTraits<media::AudioParameters> {
  static bool Fuzz(media::AudioParameters* p, Fuzzer* fuzzer) {
    int channel_layout = p->channel_layout();
    int format = p->format();
    int sample_rate = p->sample_rate();
    int frames_per_buffer = p->frames_per_buffer();
    int channels = p->channels();
    int effects = p->effects();
    // TODO(mbarbella): Support ChannelLayout mutation and invalid values.
    if (fuzzer->ShouldGenerate()) {
      channel_layout =
          RandInRange(media::ChannelLayout::CHANNEL_LAYOUT_MAX + 1);
    }
    if (!FuzzParam(&format, fuzzer))
      return false;
    if (!FuzzParam(&sample_rate, fuzzer))
      return false;
    if (!FuzzParam(&frames_per_buffer, fuzzer))
      return false;
    if (!FuzzParam(&channels, fuzzer))
      return false;
    if (!FuzzParam(&effects, fuzzer))
      return false;
    media::AudioParameters params(
        static_cast<media::AudioParameters::Format>(format),
        static_cast<media::ChannelLayout>(channel_layout), sample_rate,
        frames_per_buffer);
    params.set_channels_for_discrete(channels);
    params.set_effects(effects);
    *p = params;
    return true;
  }
};

template <>
struct FuzzTraits<media::OverlayInfo> {
  static bool Fuzz(media::OverlayInfo* p, Fuzzer* fuzzer) {
    if (!FuzzParam(&p->is_fullscreen, fuzzer))
      return false;
    if (!FuzzParam(&p->is_persistent_video, fuzzer))
      return false;
    if (!FuzzParam(&p->routing_token, fuzzer))
      return false;
    return true;
  }
};

template <>
struct FuzzTraits<media::VideoPixelFormat> {
  static bool Fuzz(media::VideoPixelFormat* p, Fuzzer* fuzzer) {
    int format = RandInRange(media::VideoPixelFormat::PIXEL_FORMAT_MAX + 1);
    *p = static_cast<media::VideoPixelFormat>(format);
    return true;
  }
};

template <>
struct FuzzTraits<net::EffectiveConnectionType> {
  static bool Fuzz(net::EffectiveConnectionType* p, Fuzzer* fuzzer) {
    int type = RandInRange(
        net::EffectiveConnectionType::EFFECTIVE_CONNECTION_TYPE_LAST + 1);
    *p = static_cast<net::EffectiveConnectionType>(type);
    return true;
  }
};

template <>
struct FuzzTraits<net::LoadTimingInfo> {
  static bool Fuzz(net::LoadTimingInfo* p, Fuzzer* fuzzer) {
    return FuzzParam(&p->socket_log_id, fuzzer) &&
           FuzzParam(&p->socket_reused, fuzzer) &&
           FuzzParam(&p->request_start_time, fuzzer) &&
           FuzzParam(&p->request_start, fuzzer) &&
           FuzzParam(&p->proxy_resolve_start, fuzzer) &&
           FuzzParam(&p->proxy_resolve_end, fuzzer) &&
           FuzzParam(&p->connect_timing.dns_start, fuzzer) &&
           FuzzParam(&p->connect_timing.dns_end, fuzzer) &&
           FuzzParam(&p->connect_timing.connect_start, fuzzer) &&
           FuzzParam(&p->connect_timing.connect_end, fuzzer) &&
           FuzzParam(&p->connect_timing.ssl_start, fuzzer) &&
           FuzzParam(&p->connect_timing.ssl_end, fuzzer) &&
           FuzzParam(&p->send_start, fuzzer) &&
           FuzzParam(&p->send_end, fuzzer) &&
           FuzzParam(&p->receive_headers_end, fuzzer);
  }
};

template <>
struct FuzzTraits<net::HostPortPair> {
  static bool Fuzz(net::HostPortPair* p, Fuzzer* fuzzer) {
    std::string host = p->host();
    uint16_t port = p->port();
    if (!FuzzParam(&host, fuzzer))
      return false;
    if (!FuzzParam(&port, fuzzer))
      return false;
    p->set_host(host);
    p->set_port(port);
    return true;
  }
};

template <>
struct FuzzTraits<net::IPAddress> {
  static bool Fuzz(net::IPAddress* p, Fuzzer* fuzzer) {
    std::vector<uint8_t> bytes = p->CopyBytesToVector();
    if (!FuzzParam(&bytes, fuzzer))
      return false;
    net::IPAddress ip_address(bytes.data(), bytes.size());
    *p = ip_address;
    return true;
  }
};

template <>
struct FuzzTraits<net::IPEndPoint> {
  static bool Fuzz(net::IPEndPoint* p, Fuzzer* fuzzer) {
    net::IPAddress ip_address = p->address();
    int port = p->port();
    if (!FuzzParam(&ip_address, fuzzer))
      return false;
    if (!FuzzParam(&port, fuzzer))
      return false;
    net::IPEndPoint ip_endpoint(ip_address, port);
    *p = ip_endpoint;
    return true;
  }
};

// PP_ traits.
template <>
struct FuzzTraits<PP_Bool> {
  static bool Fuzz(PP_Bool* p, Fuzzer* fuzzer) {
    bool tmp = PP_ToBool(*p);
    if (!FuzzParam(&tmp, fuzzer))
      return false;
    *p = PP_FromBool(tmp);
    return true;
  }
};

template <>
struct FuzzTraits<PP_NetAddress_Private> {
  static bool Fuzz(PP_NetAddress_Private* p, Fuzzer* fuzzer) {
    p->size = RandInRange(sizeof(p->data) + 1);
    fuzzer->FuzzBytes(&p->data, p->size);
    return true;
  }
};

template <>
struct FuzzTraits<ppapi::PPB_X509Certificate_Fields> {
  static bool Fuzz(ppapi::PPB_X509Certificate_Fields* p,
                       Fuzzer* fuzzer) {
    // TODO(mbarbella): This should actually do something.
    return true;
  }
};

template <>
struct FuzzTraits<ppapi::proxy::PPBFlash_DrawGlyphs_Params> {
  static bool Fuzz(ppapi::proxy::PPBFlash_DrawGlyphs_Params* p,
                       Fuzzer* fuzzer) {
    // TODO(mbarbella): This should actually do something.
    return true;
  }
};

template <>
struct FuzzTraits<ppapi::proxy::ResourceMessageCallParams> {
  static bool Fuzz(
      ppapi::proxy::ResourceMessageCallParams* p, Fuzzer* fuzzer) {
    // TODO(mbarbella): Support mutation.
    if (!fuzzer->ShouldGenerate())
      return true;

    PP_Resource resource;
    int32_t sequence;
    bool has_callback;
    if (!FuzzParam(&resource, fuzzer))
      return false;
    if (!FuzzParam(&sequence, fuzzer))
      return false;
    if (!FuzzParam(&has_callback, fuzzer))
      return false;
    *p = ppapi::proxy::ResourceMessageCallParams(resource, sequence);
    if (has_callback)
      p->set_has_callback();
    return true;
  }
};

template <>
struct FuzzTraits<ppapi::proxy::ResourceMessageReplyParams> {
  static bool Fuzz(
      ppapi::proxy::ResourceMessageReplyParams* p, Fuzzer* fuzzer) {
    // TODO(mbarbella): Support mutation.
    if (!fuzzer->ShouldGenerate())
      return true;

    PP_Resource resource;
    int32_t sequence;
    int32_t result;
    if (!FuzzParam(&resource, fuzzer))
      return false;
    if (!FuzzParam(&sequence, fuzzer))
      return false;
    if (!FuzzParam(&result, fuzzer))
      return false;
    *p = ppapi::proxy::ResourceMessageReplyParams(resource, sequence);
    p->set_result(result);
    return true;
  }
};

template <>
struct FuzzTraits<ppapi::proxy::SerializedHandle> {
  static bool Fuzz(ppapi::proxy::SerializedHandle* p,
                       Fuzzer* fuzzer) {
    // TODO(mbarbella): This should actually do something.
    return true;
  }
};

template <>
struct FuzzTraits<ppapi::proxy::SerializedFontDescription> {
  static bool Fuzz(ppapi::proxy::SerializedFontDescription* p,
                       Fuzzer* fuzzer) {
    // TODO(mbarbella): This should actually do something.
    return true;
  }
};

template <>
struct FuzzTraits<ppapi::proxy::SerializedVar> {
  static bool Fuzz(ppapi::proxy::SerializedVar* p, Fuzzer* fuzzer) {
    // TODO(mbarbella): This should actually do something.
    return true;
  }
};

template <>
struct FuzzTraits<ppapi::HostResource> {
  static bool Fuzz(ppapi::HostResource* p, Fuzzer* fuzzer) {
    // TODO(mbarbella): Support mutation.
    if (!fuzzer->ShouldGenerate())
      return true;

    PP_Instance instance;
    PP_Resource resource;
    if (!FuzzParam(&instance, fuzzer))
      return false;
    if (!FuzzParam(&resource, fuzzer))
      return false;
    p->SetHostResource(instance, resource);
    return true;
  }
};

template <>
struct FuzzTraits<ppapi::PepperFilePath> {
  static bool Fuzz(ppapi::PepperFilePath *p, Fuzzer* fuzzer) {
    // TODO(mbarbella): Support mutation.
    if (!fuzzer->ShouldGenerate())
      return true;

    unsigned domain = RandInRange(ppapi::PepperFilePath::DOMAIN_MAX_VALID+1);
    base::FilePath path;
    if (!FuzzParam(&path, fuzzer))
      return false;
    *p = ppapi::PepperFilePath(
        static_cast<ppapi::PepperFilePath::Domain>(domain), path);
    return true;
  }
};

template <>
struct FuzzTraits<ppapi::PpapiPermissions> {
  static bool Fuzz(ppapi::PpapiPermissions* p, Fuzzer* fuzzer) {
    uint32_t bits = p->GetBits();
    if (!FuzzParam(&bits, fuzzer))
      return false;
    *p = ppapi::PpapiPermissions(bits);
    return true;
  }
};

template <>
struct FuzzTraits<ppapi::SocketOptionData> {
  static bool Fuzz(ppapi::SocketOptionData* p, Fuzzer* fuzzer) {
    // TODO(mbarbella): This can be improved.
    int32_t tmp;
    p->GetInt32(&tmp);
    if (!FuzzParam(&tmp, fuzzer))
      return false;
    p->SetInt32(tmp);
    return true;
  }
};

template <>
struct FuzzTraits<printing::mojom::MarginType> {
  static bool Fuzz(printing::mojom::MarginType* p, Fuzzer* fuzzer) {
    int type = RandInRange(
        static_cast<int>(printing::mojom::MarginType::kMaxValue) + 1);
    *p = static_cast<printing::mojom::MarginType>(type);
    return true;
  }
};

template <>
struct FuzzTraits<SkBitmap> {
  static bool Fuzz(SkBitmap* p, Fuzzer* fuzzer) {
    // TODO(mbarbella): This should actually do something.
    return true;
  }
};

template <>
struct FuzzTraits<ui::LatencyInfo> {
  static bool Fuzz(ui::LatencyInfo* p, Fuzzer* fuzzer) {
    // TODO(inferno): Add param traits for |latency_components|.
    int64_t trace_id = p->trace_id();
    bool terminated = p->terminated();
    if (!FuzzParam(&trace_id, fuzzer))
      return false;
    if (!FuzzParam(&terminated, fuzzer))
      return false;

    ui::LatencyInfo latency(trace_id, terminated);
    *p = latency;

    return true;
  }
};

template <>
struct FuzzTraits<url::Origin> {
  static bool Fuzz(url::Origin* p, Fuzzer* fuzzer) {
    bool opaque = p->opaque();
    if (!FuzzParam(&opaque, fuzzer))
      return false;
    std::string scheme = p->GetTupleOrPrecursorTupleIfOpaque().scheme();
    std::string host = p->GetTupleOrPrecursorTupleIfOpaque().host();
    uint16_t port = p->GetTupleOrPrecursorTupleIfOpaque().port();
    if (!FuzzParam(&scheme, fuzzer))
      return false;
    if (!FuzzParam(&host, fuzzer))
      return false;
    if (!FuzzParam(&port, fuzzer))
      return false;

    absl::optional<url::Origin> origin;
    if (!opaque) {
      origin = url::Origin::UnsafelyCreateTupleOriginWithoutNormalization(
          scheme, host, port);
    } else {
      absl::optional<base::UnguessableToken> token =
          p->GetNonceForSerialization();
      if (!token)
        token = base::UnguessableToken::Deserialize(RandU64(), RandU64());
      if (!FuzzParam(&(*token), fuzzer))
        return false;
      origin = url::Origin::UnsafelyCreateOpaqueOriginWithoutNormalization(
          scheme, host, port, url::Origin::Nonce(*token));
    }

    if (!origin) {
      // This means that we produced non-canonical values that were rejected by
      // UnsafelyCreate. Which is nice, except, those are arguably interesting
      // values to be sending over the wire sometimes, to make sure they're
      // rejected at the receiving end.
      //
      // We could potentially call CreateFromNormalizedTuple here to force their
      // creation, except that could lead to invariant violations within the
      // url::Origin we construct -- and potentially crash the fuzzer. What to
      // do?
      return false;
    }

    *p = std::move(origin).value();
    return true;
  }
};

// Redefine macros to generate generating from traits declarations.
// STRUCT declarations cause corresponding STRUCT_TRAITS declarations to occur.
#undef IPC_STRUCT_BEGIN
#undef IPC_STRUCT_BEGIN_WITH_PARENT
#undef IPC_STRUCT_MEMBER
#undef IPC_STRUCT_END
#define IPC_STRUCT_BEGIN_WITH_PARENT(struct_name, parent) \
  IPC_STRUCT_BEGIN(struct_name)
#define IPC_STRUCT_BEGIN(struct_name) IPC_STRUCT_TRAITS_BEGIN(struct_name)
#define IPC_STRUCT_MEMBER(type, name, ...) IPC_STRUCT_TRAITS_MEMBER(name)
#define IPC_STRUCT_END() IPC_STRUCT_TRAITS_END()

// Set up so next include will generate generate trait classes.
#undef IPC_STRUCT_TRAITS_BEGIN
#undef IPC_STRUCT_TRAITS_MEMBER
#undef IPC_STRUCT_TRAITS_PARENT
#undef IPC_STRUCT_TRAITS_END
#define IPC_STRUCT_TRAITS_BEGIN(struct_name) \
  template <> \
  struct FuzzTraits<struct_name> { \
    static bool Fuzz(struct_name *p, Fuzzer* fuzzer) {

#define IPC_STRUCT_TRAITS_MEMBER(name) \
      if (!FuzzParam(&p->name, fuzzer)) \
        return false;

#define IPC_STRUCT_TRAITS_PARENT(type) \
      if (!FuzzParam(static_cast<type*>(p), fuzzer)) \
        return false;

#define IPC_STRUCT_TRAITS_END() \
      return true; \
    } \
  };

// If |condition| isn't met, the messsge will fail to serialize. Try
// increasingly smaller ranges until we find one that happens to meet
// the condition, or fail trying.
// TODO(mbarbella): Attempt to validate even in the mutation case.
#undef IPC_ENUM_TRAITS_VALIDATE
#define IPC_ENUM_TRAITS_VALIDATE(enum_name, condition)             \
  template <>                                                      \
  struct FuzzTraits<enum_name> {                                   \
    static bool Fuzz(enum_name* p, Fuzzer* fuzzer) {               \
      if (!fuzzer->ShouldGenerate()) {                             \
        return FuzzParam(reinterpret_cast<int*>(p), fuzzer);       \
      }                                                            \
      for (int shift = 30; shift; --shift) {                       \
        for (int tries = 0; tries < 2; ++tries) {                  \
          int value = RandInRange(1 << shift);                     \
          if (condition) {                                         \
            *reinterpret_cast<int*>(p) = value;                    \
            return true;                                           \
          }                                                        \
        }                                                          \
      }                                                            \
      std::cerr << "failed to satisfy " << #condition << "\n";     \
      return false;                                                \
    }                                                              \
  };

// Bring them into existence.
#include "tools/ipc_fuzzer/message_lib/all_messages.h"
#include "tools/ipc_fuzzer/message_lib/all_message_null_macros.h"

#define MAX_FAKE_ROUTING_ID 15

// MessageFactory abstracts away constructing control/routed messages by
// providing an additional random routing ID argument when necessary.
template <typename Message, IPC::MessageKind>
class MessageFactory;

template <typename Message>
class MessageFactory<Message, IPC::MessageKind::CONTROL> {
 public:
  template <typename... Args>
  static std::unique_ptr<Message> New(const Args&... args) {
    return std::make_unique<Message>(args...);
  }
};

template <typename Message>
class MessageFactory<Message, IPC::MessageKind::ROUTED> {
 public:
  template <typename... Args>
  static std::unique_ptr<Message> New(const Args&... args) {
    return std::make_unique<Message>(RandInRange(MAX_FAKE_ROUTING_ID), args...);
  }
};

template <typename Message>
class FuzzerHelper;

template <typename Meta, typename... Ins>
class FuzzerHelper<IPC::MessageT<Meta, std::tuple<Ins...>, void>> {
 public:
  using Message = IPC::MessageT<Meta, std::tuple<Ins...>, void>;

  static std::unique_ptr<IPC::Message> Fuzz(IPC::Message* msg, Fuzzer* fuzzer) {
    return FuzzImpl(msg, fuzzer, std::index_sequence_for<Ins...>());
  }

 private:
  template <size_t... Ns>
  static std::unique_ptr<IPC::Message> FuzzImpl(IPC::Message* msg,
                                                Fuzzer* fuzzer,
                                                std::index_sequence<Ns...>) {
    typename Message::Param p;
    if (msg) {
      Message::Read(static_cast<Message*>(msg), &p);
    }
    if (FuzzParam(&p, fuzzer)) {
      return MessageFactory<Message, Meta::kKind>::New(std::get<Ns>(p)...);
    }
    std::cerr << "Don't know how to handle " << Meta::kName << "\n";
    return nullptr;
  }
};

template <typename Meta, typename... Ins, typename... Outs>
class FuzzerHelper<
    IPC::MessageT<Meta, std::tuple<Ins...>, std::tuple<Outs...>>> {
 public:
  using Message = IPC::MessageT<Meta, std::tuple<Ins...>, std::tuple<Outs...>>;

  static std::unique_ptr<IPC::Message> Fuzz(IPC::Message* msg, Fuzzer* fuzzer) {
    return FuzzImpl(msg, fuzzer, std::index_sequence_for<Ins...>());
  }

 private:
  template <size_t... Ns>
  static std::unique_ptr<IPC::Message> FuzzImpl(IPC::Message* msg,
                                                Fuzzer* fuzzer,
                                                std::index_sequence<Ns...>) {
    typename Message::SendParam p;
    Message* real_msg = static_cast<Message*>(msg);
    std::unique_ptr<Message> new_msg;
    if (real_msg) {
      Message::ReadSendParam(real_msg, &p);
    }
    if (FuzzParam(&p, fuzzer)) {
      new_msg = MessageFactory<Message, Meta::kKind>::New(
          std::get<Ns>(p)..., static_cast<Outs*>(nullptr)...);
    }
    if (real_msg && new_msg) {
      MessageCracker::CopyMessageID(new_msg.get(), real_msg);
    } else if (!new_msg) {
      std::cerr << "Don't know how to handle " << Meta::kName << "\n";
    }
    return new_msg;
  }
};

#include "tools/ipc_fuzzer/message_lib/all_message_null_macros.h"

void PopulateFuzzerFunctionVector(
    FuzzerFunctionVector* function_vector) {
#undef IPC_MESSAGE_DECL
#define IPC_MESSAGE_DECL(name, ...) \
  function_vector->push_back(FuzzerHelper<name>::Fuzz);
#include "tools/ipc_fuzzer/message_lib/all_messages.h"
}

// Redefine macros to register fuzzing functions into map.
#include "tools/ipc_fuzzer/message_lib/all_message_null_macros.h"
#undef IPC_MESSAGE_DECL
#define IPC_MESSAGE_DECL(name, ...) \
  (*map)[static_cast<uint32_t>(name::ID)] = FuzzerHelper<name>::Fuzz;

void PopulateFuzzerFunctionMap(FuzzerFunctionMap* map) {
#include "tools/ipc_fuzzer/message_lib/all_messages.h"
}

}  // namespace ipc_fuzzer


text:
from __future__ import unicode_literals
from ..preprocess import Smooth

def test_Smooth_inputs():
    input_map = dict(data_type=dict(field='dtype',
    ),
    fwhm=dict(field='fwhm',
    ),
    ignore_exception=dict(nohash=True,
    usedefault=True,
    ),
    implicit_masking=dict(field='im',
    ),
    in_files=dict(copyfile=False,
    field='data',
    mandatory=True,
    ),
    matlab_cmd=dict(),
    mfile=dict(usedefault=True,
    ),
    out_prefix=dict(field='prefix',
    usedefault=True,
    ),
    paths=dict(),
    use_mcr=dict(),
    use_v8struct=dict(min_ver='8',
    usedefault=True,
    ),
    )
    inputs = Smooth.input_spec()

    for key, metadata in list(input_map.items()):
        for metakey, value in list(metadata.items()):
            assert getattr(inputs.traits()[key], metakey) == value

def test_Smooth_outputs():
    output_map = dict(smoothed_files=dict(),
    )
    outputs = Smooth.output_spec()

    for key, metadata in list(output_map.items()):
        for metakey, value in list(metadata.items()):
            assert getattr(outputs.traits()[key], metakey) == value

redpajama_set_name: RedPajamaGithub


text:
package org.apache.hadoop.ozone.container.common.states.endpoint;

import com.google.common.base.Preconditions;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hdds.protocol.proto
    .StorageContainerDatanodeProtocolProtos.SCMVersionResponseProto;
import org.apache.hadoop.ozone.OzoneConsts;
import org.apache.hadoop.ozone.container.common.statemachine
    .EndpointStateMachine;
import org.apache.hadoop.ozone.container.common.utils.HddsVolumeUtil;
import org.apache.hadoop.ozone.container.common.volume.HddsVolume;
import org.apache.hadoop.ozone.container.common.volume.VolumeSet;
import org.apache.hadoop.ozone.container.ozoneimpl.OzoneContainer;
import org.apache.hadoop.ozone.protocol.VersionResponse;
import org.apache.hadoop.util.DiskChecker.DiskOutOfSpaceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.Callable;

/**
 * Task that returns version.
 */
public class VersionEndpointTask implements
    Callable<EndpointStateMachine.EndPointStates> {
  public static final Logger LOG = LoggerFactory.getLogger(VersionEndpointTask
      .class);
  private final EndpointStateMachine rpcEndPoint;
  private final Configuration configuration;
  private final OzoneContainer ozoneContainer;

  public VersionEndpointTask(EndpointStateMachine rpcEndPoint,
                             Configuration conf, OzoneContainer container) {
    this.rpcEndPoint = rpcEndPoint;
    this.configuration = conf;
    this.ozoneContainer = container;
  }

  /**
   * Computes a result, or throws an exception if unable to do so.
   *
   * @return computed result
   * @throws Exception if unable to compute a result
   */
  @Override
  public EndpointStateMachine.EndPointStates call() throws Exception {
    rpcEndPoint.lock();
    try{
      if (rpcEndPoint.getState().equals(
          EndpointStateMachine.EndPointStates.GETVERSION)) {
        SCMVersionResponseProto versionResponse =
            rpcEndPoint.getEndPoint().getVersion(null);
        VersionResponse response = VersionResponse.getFromProtobuf(
            versionResponse);
        rpcEndPoint.setVersion(response);

        String scmId = response.getValue(OzoneConsts.SCM_ID);
        String clusterId = response.getValue(OzoneConsts.CLUSTER_ID);

        // Check volumes
        VolumeSet volumeSet = ozoneContainer.getVolumeSet();
        volumeSet.writeLock();
        try {
          Map<String, HddsVolume> volumeMap = volumeSet.getVolumeMap();

          Preconditions.checkNotNull(scmId, "Reply from SCM: scmId cannot be " +
              "null");
          Preconditions.checkNotNull(clusterId, "Reply from SCM: clusterId " +
              "cannot be null");

          // If version file does not exist create version file and also set scmId

          for (Map.Entry<String, HddsVolume> entry : volumeMap.entrySet()) {
            HddsVolume hddsVolume = entry.getValue();
            boolean result = HddsVolumeUtil.checkVolume(hddsVolume, scmId,
                clusterId, LOG);
            if (!result) {
              volumeSet.failVolume(hddsVolume.getHddsRootDir().getPath());
            }
          }
          if (volumeSet.getVolumesList().size() == 0) {
            // All volumes are in inconsistent state
            throw new DiskOutOfSpaceException("All configured Volumes are in " +
                "Inconsistent State");
          }
        } finally {
          volumeSet.writeUnlock();
        }

        ozoneContainer.getDispatcher().setScmId(scmId);

        EndpointStateMachine.EndPointStates nextState =
            rpcEndPoint.getState().getNextState();
        rpcEndPoint.setState(nextState);
        rpcEndPoint.zeroMissedCount();
      } else {
        LOG.debug("Cannot execute GetVersion task as endpoint state machine " +
            "is in {} state", rpcEndPoint.getState());
      }
    } catch (DiskOutOfSpaceException ex) {
      rpcEndPoint.setState(EndpointStateMachine.EndPointStates.SHUTDOWN);
    } catch(IOException ex) {
      rpcEndPoint.logIfNeeded(ex);
    } finally {
      rpcEndPoint.unlock();
    }
    return rpcEndPoint.getState();
  }
}


text:
package com.clarifai.androidstarter;

import android.content.Context;
import android.util.Log;
import android.view.Display;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.hardware.Camera;
import android.view.Window;
import android.view.WindowManager;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import static android.content.Context.*;

public class CSView extends SurfaceView implements SurfaceHolder.Callback {
    private static final String TAG = RecognitionActivity.class.getSimpleName();
    private SurfaceHolder cHolder;
    public Camera camera;
    public boolean isPreviewRunning;

    public CSView(Context context, Camera mcamera){
        super(context);
        camera = mcamera;
        cHolder = getHolder();
        cHolder.addCallback(this);
    }

    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height)
    {
        if (isPreviewRunning)
        {
            camera.stopPreview();
        }

        Camera.Parameters parameters = camera.getParameters();
        List<Camera.Size> previewSizes = parameters.getSupportedPreviewSizes();
        if(previewSizes.get(0).height<previewSizes.get(0).width){
            width=previewSizes.get(0).height;
            height=previewSizes.get(0).width;
        }
        else{
            height=previewSizes.get(0).height;
            width=previewSizes.get(0).width;
        }

        Context mContext = getContext();

        WindowManager win;
        String wanted = Context.WINDOW_SERVICE;
        win = (WindowManager)mContext.getSystemService(wanted);

        Display display = win.getDefaultDisplay();
        if(display.getRotation() == Surface.ROTATION_0)
        {
            parameters.setPreviewSize(height, width);
            camera.setDisplayOrientation(90);
        }

        if(display.getRotation() == Surface.ROTATION_90)
        {
            parameters.setPreviewSize(width, height);
        }

        if(display.getRotation() == Surface.ROTATION_180)
        {
            parameters.setPreviewSize(height, width);
        }

        if(display.getRotation() == Surface.ROTATION_270)
        {
            parameters.setPreviewSize(width, height);
            camera.setDisplayOrientation(180);
        }
        if (parameters.getSupportedFocusModes().contains(                               //always autofocus if device has this mode
                Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) {
            parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
        }
        camera.setParameters(parameters);
        previewCamera();
    }

    public void previewCamera()
    {
        try
        {
            camera.setPreviewDisplay(cHolder);
            camera.startPreview();
            isPreviewRunning = true;
        }
        catch(Exception e)
        {
            Log.d(TAG, "Cannot start preview", e);
        }
    }

    public void surfaceCreated(SurfaceHolder holder){
        try{
            camera.setPreviewDisplay(cHolder);
            camera.startPreview();
        }catch(Exception e){

        }
    }

    public void surfaceDestroyed(SurfaceHolder holder){
        camera.stopPreview();
        camera = null;
    }

    public void capture(final Camera.PictureCallback bithandler) {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                camera.startPreview();
                camera.takePicture(null, null, bithandler);
            }
        }, 0, 5000);
    }
}


text:
layout: page
weight: 100
title: Overview
seo:
  title: Whitelabel Overview
  description: Whitelabeling allows you to use your own domains for sending email and click tracking.
  keywords: whitelabeling, domain whitelabel, email link, IP whitelabeling
navigation:
  show: true
---

Whitelabeling is the functionality that proves to the world that SendGrid has your permission to send emails on your behalf. This permission is given by the act of pointing very specific DNS entries from your domain registrar to SendGrid. Once these DNS entries are entered and propagated, email recipient mail servers and services will read the headers on the emails you send and check the DNS records to verify the email was initiated at a trusted source. This drastically increases your ability to deliver email and allows you to begin building a sender reputation for your domain and your IP addresses.

{% info %}
SendGrid does not host domains. Do not attempt to transfer a domain to SendGrid. If you have already registered a domain, then you have a registrar, and it is often the hosting company where your website resides.
{% endinfo %}

{% warning %}
Any changes you make to DNS can immediately affect your client's ability to reach your resources. We cannot take any responsibility for any changes you make to DNS, so please be very careful. If you have any questions, please contact our support team.
{% endwarning %}

{% anchor h2 %}
The Types of Whitelabeling
{% endanchor %}

Domain Whitelabel

This type of whitelabel allows email recipient servers and services to verify the identity of the email sender back to the domain that the sender controls. This gives a layer of email authentication that helps in email deliverability. With only the domain whitelabel, you are still subject to the reputation of your IP address.

Email Links Whitelabel

When you put a link or an image into an email and have click or open tracking turned on, the click tracking links and the images will point to your domain. This shows the recipient email server that you are not trying to hide anything behind the links and that you control the content of your emails.

Some bad actors will use 3rd party link shortening services to populate the domains they list in their email content and they do not include their own domain in those links. This practice is a red flag to spam filters.

IP Addresses Whitelabel

An IP whitelabel works in tandem with your domain whitelabel, but the real reputation for email usually lays with the IP address since many domains can point to the same IP. It is always ideal to have both a domain and an IP whitelabel. You will need to have a dedicated IP address or purchase one through [SendGrid support](https://support.sendgrid.com/hc/en-us/articles/200181948-Adding-an-additional-dedicated-IP-to-your-account) in order to whitelabel your IP address. You can send email from multiple domains from each of your dedicated IPs. Remember that each domain will positively or negatively affect the other domains when you use the same IP for multiple domains.

{% anchor h2 %}
Setting Up Whitelabels
{% endanchor %}

You can set up your whitelabels from the overview page or from the individual whitelabel type pages in the customer portal. For the purposes of the User Guide, we cover each setup process in depth on the respective whitelabel pages.

* Setting up Domain Whitelabel
* Setting up Email Link Whitelabels
* Setting up IP Whitelabels
* [All you need to know about whitelabeling](https://support.sendgrid.com/hc/en-us/articles/200548228-All-You-Need-to-Know-About-Whitelabeling)

{% anchor h2 %}
How Does Whitelabeling Work?
{% endanchor %}

{% anchor h3 %}
Recipient Servers Check Your Email Headers
{% endanchor %}

When you recipient's servers receive emails, it is their job to protect their users from unwanted mail. They assume all mail is guilty until proven innocent, so as the sender it is your responsibility to provide as much information about yourself as possible. The recipient server will check the email headers for sender identification information and originating server information.

One of the most basic things that mail servers will check is the FROM address and whether it matches the domain of the sending server. If it does not, on some email applications, your recipients will see something like "via sendgrid.net" in the header of the delivered email.

{% anchor h3 %}
SendGrid Attaches Whitelabel Information In Email Headers
{% endanchor %}

When you tell SendGrid to send emails on your behalf, whether manually or over the API, SendGrid will add headers to your emails about you and your email settings so that recipient servers know that we send the email with your permission and on your behalf.

If you don't have a domain whitelabel set up, then your emails will show as being sent by sendgrid.net regardless of your FROM address.

{% anchor h3 %}
Whitelabel Application Logic
{% endanchor %}

Assigning whitelabels in email headers takes some care and consideration. SendGrid takes care of this process so that you don't have to worry about it, but you should know how it works!

{% info %}
If SendGrid cannot match your email to a valid whitelabel, SendGrid.net will be used.
{% endinfo %}

For any account, SendGrid will attach valid whitelabel information in the following order, starting at the top of the list and applying the whitelabel when the criteria are matched:

1. Valid whitelabel that matches the domain in the FROM address
2. Valid default Whitelabel
3. SendGrid.net

For subusers, SendGrid will attach valid whitelabel information in the following order, starting at the top of the list and applying the whitelabel when the criteria are matched:

1. Valid whitelabel *for this subuser* that matches the domain in the FROM address
2. Valid default whitelabel *for this subuser*
3. Valid whitelabel assigned by the parent account to this subuser
4. SendGrid.net


text:
package com.javafiction.common.persistence.resources;

import javax.persistence.EntityManager;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * Allows EntityManager to "auto join into JTA transaction"
 * See: https://community.jboss.org/message/850194
 */
public class JtaEntityManagerProxy implements java.lang.reflect.InvocationHandler {

    private EntityManager obj;

    public static Object newInstance(EntityManager obj) {
        return Proxy.newProxyInstance(obj.getClass().getClassLoader(),new Class<?>[] {EntityManager.class}, new JtaEntityManagerProxy(obj));
    }

    private JtaEntityManagerProxy(EntityManager obj) {
        this.obj = obj;
    }

    public Object invoke(Object proxy, Method m, Object[] args) throws Throwable {
        Object result;
        try {
            obj.joinTransaction();
            result = m.invoke(obj, args);
        } catch (InvocationTargetException e) {
            throw e.getTargetException();
        } catch (Exception e) {
            throw new RuntimeException("unexpected invocation exception: " + e.getMessage(), e);
        } finally {
        }
        return result;
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<definitions id="definitions"
	xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:activiti="http://activiti.org/bpmn"
	targetNamespace="Examples">

	<process id="nonInterruptingOnConcurrentTasks">

		<startEvent id="theStart" />
		<sequenceFlow id="flow1" sourceRef="theStart" targetRef="fork" />

		<parallelGateway id="fork" />
		<sequenceFlow id="flow2" sourceRef="fork" targetRef="firstTask" />
		<sequenceFlow id="flow3" sourceRef="fork" targetRef="secondTask" />

    <userTask id="firstTask" />
    <sequenceFlow id="flow4" sourceRef="firstTask" targetRef="join" />

    <boundaryEvent id="timer" attachedToRef="firstTask" cancelActivity="false">
      <timerEventDefinition>
        <timeDuration>PT1H</timeDuration>
      </timerEventDefinition>
    </boundaryEvent>
    <sequenceFlow id="flow5" sourceRef="timer" targetRef="timerFiredTask" />
    <userTask id="timerFiredTask" />
    <sequenceFlow id="flow6" sourceRef="timerFiredTask" targetRef="nonInterruptingEnd" />
    <endEvent id="nonInterruptingEnd" />

    <userTask id="secondTask" />
    <sequenceFlow id="flow7" sourceRef="secondTask" targetRef="join" />

    <parallelGateway id="join" />
    <sequenceFlow id="flow8" sourceRef="join" targetRef="theEnd" />

		<endEvent id="theEnd" />

	</process>
</definitions>


text:
utils Package
=============

:mod:`utils` Package
--------------------

.. automodule:: ooni.utils
    :members:
    :undoc-members:
    :show-inheritance:

:mod:`config` Module
--------------------

.. automodule:: ooni.utils.config
    :members:
    :undoc-members:
    :show-inheritance:

:mod:`date` Module
------------------

.. automodule:: ooni.utils.date
    :members:
    :undoc-members:
    :show-inheritance:

:mod:`log` Module
-----------------

.. automodule:: ooni.utils.log
    :members:
    :undoc-members:
    :show-inheritance:

:mod:`logo` Module
------------------

.. automodule:: ooni.utils.logo
    :members:
    :undoc-members:
    :show-inheritance:

:mod:`net` Module
-----------------

.. automodule:: ooni.utils.net
    :members:
    :undoc-members:
    :show-inheritance:


text:
package com.intellij.tasks.context;

import com.intellij.notification.NotificationDisplayType;
import com.intellij.notification.impl.NotificationsConfigurationImpl;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.vcs.VcsConfiguration;
import com.intellij.tasks.TaskBundle;
import com.intellij.ui.components.JBCheckBox;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;

public class ConfigureBranchContextDialog extends DialogWrapper {

  private final Project myProject;
  private JPanel myPanel;
  private JBCheckBox myReloadContext;
  private JBCheckBox myShowNotification;

  protected ConfigureBranchContextDialog(Project project) {
    super(project);
    myProject = project;
    setTitle(TaskBundle.message("branch.workspace.settings"));

    myReloadContext.setSelected(VcsConfiguration.getInstance(project).RELOAD_CONTEXT);
    myReloadContext.addActionListener(e -> myShowNotification.setEnabled(myReloadContext.isSelected()));

    myShowNotification.setEnabled(myReloadContext.isSelected());
    myShowNotification.setSelected(
      NotificationsConfigurationImpl.getSettings(BranchContextTracker.NOTIFICATION.getDisplayId()).getDisplayType() !=
      NotificationDisplayType.NONE);

    init();
  }

  @Nullable
  @Override
  protected JComponent createCenterPanel() {
    return myPanel;
  }

  @Override
  protected void doOKAction() {
    VcsConfiguration.getInstance(myProject).RELOAD_CONTEXT = myReloadContext.isSelected();

    NotificationDisplayType displayType = myShowNotification.isSelected() ? NotificationDisplayType.BALLOON : NotificationDisplayType.NONE;
    NotificationsConfigurationImpl configuration = NotificationsConfigurationImpl.getInstanceImpl();
    configuration.changeSettings(BranchContextTracker.NOTIFICATION.getDisplayId(), displayType, true, false);

    super.doOKAction();
  }
}


text:
const BinaryPjax         = require('../../base/binary_pjax');
const Client             = require('../../base/client');
const BinarySocket       = require('../../base/socket');
const Currency           = require('../../common/currency');
const FormManager        = require('../../common/form_manager');
const elementTextContent = require('../../../_common/common_functions').elementTextContent;
const getElementById     = require('../../../_common/common_functions').getElementById;
const localize           = require('../../../_common/localize').localize;
const State              = require('../../../_common/storage').State;
const getPropertyValue   = require('../../../_common/utility').getPropertyValue;

const AccountTransfer = (() => {
    const form_id       = 'frm_account_transfer';
    const form_id_hash  = `#${form_id}`;

    const messages = {
        parent : 'client_message',
        error  : 'no_account',
        balance: 'not_enough_balance',
        deposit: 'no_balance',
        limit  : 'limit_reached',
    };

    let el_transfer_from,
        el_transfer_to,
        el_reset_transfer,
        el_transfer_fee,
        el_fee_amount,
        el_fee_minimum,
        el_success_form,
        client_balance,
        client_currency,
        client_loginid,
        withdrawal_limit,
        max_amount,
        transferable_amount,
        to_loginid,
        transfer_to_currency;

    /**
     * Sort Accounts
     * See : https://github.com/you-dont-need/You-Dont-Need-Lodash-Underscore#_sortby-and-_orderby
     * @param accounts
     * @returns {*}
     */
    const sortAccounts = (accounts) => {
        const sortBy = (key) => (a, b) => (a[key] > b[key]) ? 1 : ((b[key] > a[key]) ? -1 : 0);

        return accounts.concat().sort(sortBy('currency'));
    };

    const populateAccounts = (accounts) => {
        client_loginid   = Client.get('loginid');
        el_transfer_from = getElementById('lbl_transfer_from');
        el_transfer_to   = getElementById('transfer_to');

        elementTextContent(el_transfer_from, `${client_loginid} ${client_currency ? `(${client_currency})` : ''}`);

        const fragment_transfer_to = document.createElement('select');

        sortAccounts(accounts).forEach((account, index) => {
            if (Client.canTransferFunds(account)) {
                if (index === 0) {
                    to_loginid = account.loginid;
                }
                const option = document.createElement('option');
                option.setAttribute('data-currency', account.currency);
                option.setAttribute('data-loginid', account.loginid);
                option.appendChild(document.createTextNode(`${account.loginid}${account.currency ? ` (${account.currency})` : ''}`));
                fragment_transfer_to.appendChild(option);
            }
        });

        if (!fragment_transfer_to.childElementCount) {
            showError();
            return;
        } else if (fragment_transfer_to.childElementCount === 1) {
            const el_label_transfer_to = document.createElement('p');
            el_label_transfer_to.setAttribute('data-value', fragment_transfer_to.firstChild.textContent);
            el_label_transfer_to.setAttribute('id', el_transfer_to.getAttribute('id'));
            el_label_transfer_to.innerText = fragment_transfer_to.firstChild.textContent;
            to_loginid = fragment_transfer_to.firstChild.getAttribute('data-loginid');
            el_transfer_to.setVisibility(0);
            el_transfer_to.setAttribute('data-value', fragment_transfer_to.firstChild.textContent);
            el_transfer_to.setAttribute('data-loginid', to_loginid);
            el_transfer_to.parentElement.insertBefore(el_label_transfer_to, el_transfer_to);
        } else {
            el_transfer_to.innerHTML = fragment_transfer_to.innerHTML;
        }
        el_transfer_to.addEventListener('change', (e) => {
            setTransferFeeAmount();
            to_loginid = e.target.getAttribute('data-loginid');
        });

        transfer_to_currency = getElementById('amount-add-on');
        transfer_to_currency.textContent = Client.get('currency');

        if (Client.hasCurrencyType('crypto') && Client.hasCurrencyType('fiat')) {
            setTransferFeeAmount();
            elementTextContent(el_fee_minimum, Currency.getMinimumTransferFee(client_currency));
            el_transfer_fee.setVisibility(1);
        } else {
            const to_currency = el_transfer_to.getAttribute('data-currency');
            el_transfer_fee.setVisibility(client_currency !== to_currency);
        }

        // Hide Notes from MF|MLT accounts
        if (/iom|malta/.test(Client.get('landing_company_shortcode'))) {
            el_transfer_fee.setVisibility(0);
        }

        // transfer limit is calculated by USD, so for USD the amount will not vary based on exchange rates
        if (client_currency !== 'USD') {
            getElementById('exchange_rate_vary').setVisibility(1);
        }
        setLoadingVisibility(0);
    };

    const setTransferFeeAmount = () => {
        elementTextContent(el_fee_amount, Currency.getTransferFee(client_currency, (el_transfer_to.value || el_transfer_to.getAttribute('data-value') || '').match(/\((\w+)\)/)[1]));
    };

    const hasError = (response) => {
        const error = response.error;
        if (error) {
            const el_error = getElementById('error_message').getElementsByTagName('p')[0];
            elementTextContent(el_error, error.message);
            if (el_error.parentNode) {
                el_error.parentNode.setVisibility(1);
                setLoadingVisibility(0);
            }
            return true;
        }
        return false;
    };

    const showError = () => {
        setLoadingVisibility(0);
        getElementById(messages.parent).setVisibility(1);
        getElementById(messages.error).setVisibility(1);
    };

    const setLoadingVisibility = (is_loading_visible) => {
        getElementById('loading').setVisibility(is_loading_visible);
        getElementById('transfer_between_accounts').setVisibility(!is_loading_visible);
    };

    const showForm = () => {
        elementTextContent(document.querySelector(`${form_id_hash} #currency`), client_currency);

        getElementById(form_id).setVisibility(1);

        FormManager.init(form_id_hash, [
            { selector: '#amount', validations: [['req', { hide_asterisk: true }], ['number', { type: 'float', decimals: Currency.getDecimalPlaces(client_currency), min: Currency.getTransferLimits(client_currency, 'min'), max: transferable_amount, format_money: true }]] },

            { request_field: 'transfer_between_accounts', value: 1 },
            { request_field: 'account_from',              value: client_loginid },
            { request_field: 'account_to',                value: () => (el_transfer_to.value || el_transfer_to.getAttribute('data-value') || '').split(' (')[0] },
            { request_field: 'currency',                  value: client_currency },
        ]);

        FormManager.handleSubmit({
            form_selector       : form_id_hash,
            fnc_response_handler: responseHandler,
            enable_button       : true,
        });
    };

    const responseHandler = (response) => {
        if (response.error) {
            const el_error = getElementById('form_error');
            elementTextContent(el_error, response.error.message);
            el_error.setVisibility(1);
            // Auto hide error after 5 seconds.
            setTimeout(() => el_error.setVisibility(0), 5000);
        } else {
            populateReceipt(response);
        }
    };

    const populateReceipt = (response) => {
        getElementById(form_id).setVisibility(0);
        response.accounts.forEach((account) => {
            if (account.loginid === client_loginid) {
                elementTextContent(getElementById('transfer_success_from'), localize('From account: '));
                elementTextContent(getElementById('from_loginid'), `${account.loginid} (${account.currency})`);
                getElementById('from_current_balance').innerText = Currency.getTextFormat(account.balance, account.currency);
            } else if (account.loginid === response.client_to_loginid) {
                elementTextContent(getElementById('transfer_success_to'), localize('To account: '));
                elementTextContent(getElementById('to_loginid'), `${account.loginid} (${account.currency})`);
                getElementById('to_current_balance').innerText = Currency.getTextFormat(account.balance, account.currency);
            }
        });

        el_transfer_fee.setVisibility(0);
        el_success_form.setVisibility(1);
    };

    const onClickReset = () => {
        el_success_form.setVisibility(0);
        getElementById('amount').value = '';
        onLoad();
    };

    const onLoad = () => {
        if (!Client.canTransferFunds()) {
            BinaryPjax.loadPreviousUrl();
            return;
        }

        setLoadingVisibility(1);
        el_transfer_fee   = getElementById('transfer_fee');
        el_fee_amount     = getElementById('transfer_fee_amount');
        el_fee_minimum    = getElementById('transfer_fee_minimum');
        el_success_form   = getElementById('success_form');
        el_reset_transfer = getElementById('reset_transfer');
        el_reset_transfer.addEventListener('click', onClickReset);

        BinarySocket.wait('balance').then((response) => {
            client_balance   = +getPropertyValue(response, ['balance', 'balance']);
            client_currency  = Client.get('currency');
            const min_amount = Currency.getTransferLimits(client_currency, 'min');
            if (!client_balance || client_balance < +min_amount) {
                setLoadingVisibility(0);
                getElementById(messages.parent).setVisibility(1);
                if (client_currency) {
                    elementTextContent(getElementById('min_required_amount'), `${client_currency} ${min_amount}`);
                    getElementById(messages.balance).setVisibility(1);
                }
                getElementById(messages.deposit).setVisibility(1);
            } else {
                const req_transfer_between_accounts = BinarySocket.send({ transfer_between_accounts: 1 });
                const req_get_limits                = BinarySocket.send({ get_limits: 1 });
                const get_account_status            = BinarySocket.send({ get_account_status: 1 });

                Promise.all([req_transfer_between_accounts, req_get_limits, get_account_status]).then(() => {
                    const response_transfer = State.get(['response', 'transfer_between_accounts']);
                    const response_limits   = State.get(['response', 'get_limits']);
                    const is_authenticated  = State.getResponse('get_account_status.status').some(state => state === 'authenticated');

                    if (hasError(response_transfer)) {
                        return;
                    }
                    const accounts = response_transfer.accounts;
                    if (!accounts || !accounts.length) {
                        showError();
                        return;
                    }
                    if (hasError(response_limits)) {
                        return;
                    }

                    populateAccounts(accounts);
                    setLimits(response_limits, min_amount, is_authenticated).then(() => {
                        showForm({ is_authenticated });
                        populateHints();
                    }).catch(() => {
                        getElementById(messages.limit).setVisibility(1);
                        getElementById(messages.parent).setVisibility(1);
                        el_transfer_fee.setVisibility(0);
                    });

                });
            }
        });
    };

    const setLimits = (response, min_amount, is_authenticated) => new Promise((resolve, reject) => {
        withdrawal_limit = +response.get_limits.remainder;
        if (withdrawal_limit < +min_amount) {
            reject(new Error('Withdrawal limit is less than Min amount.'));
        }

        max_amount = Currency.getTransferLimits(Client.get('currency'), 'max');

        const from_currency = Client.get('currency');
        const to_currency   = Client.get('currency', to_loginid);
        if (!Currency.isCryptocurrency(from_currency) && !Currency.isCryptocurrency(to_currency) && is_authenticated) {
            transferable_amount = client_balance;
        } else {
            transferable_amount = max_amount ? Math.min(max_amount, withdrawal_limit, client_balance) : Math.min(
                withdrawal_limit,
                client_balance,
            );
        }

        getElementById('range_hint_min').textContent = min_amount;
        resolve();
    });

    const populateHints = () => {
        getElementById('limit_current_balance').innerText  = Currency.getTextFormat(client_balance, client_currency);

        getElementById('limit_max_amount').innerText = max_amount ? Currency.getTextFormat(transferable_amount, client_currency) : localize('Not announced for this currency.');

        $('#range_hint').accordion({
            heightStyle: 'content',
            collapsible: true,
            active     : true,
        });

        getElementById('range_hint').show();
    };

    const onUnload = () => {
        if (el_reset_transfer) el_reset_transfer.removeEventListener('click', onClickReset);
    };

    return {
        onLoad,
        onUnload,
    };
})();

module.exports = AccountTransfer;


text:
package org.apache.activemq.apollo.openwire.command;

/**
 * @openwire:marshaller
 * @version $Revision: 1.6 $
 */
public abstract class TransactionId implements DataStructure {

    public abstract boolean isXATransaction();
    public abstract boolean isLocalTransaction();
    public abstract String getTransactionKey();

    public boolean isMarshallAware() {
        return false;
    }
}


text:
import os
from django.core.management.base import NoArgsCommand
from optparse import make_option

class Command(NoArgsCommand):
    shells = ['ipython', 'bpython']

    option_list = NoArgsCommand.option_list + (
        make_option('--plain', action='store_true', dest='plain',
            help='Tells Django to use plain Python, not IPython or bpython.'),
        make_option('--no-startup', action='store_true', dest='no_startup',
            help='When using plain Python, ignore the PYTHONSTARTUP environment variable and ~/.pythonrc.py script.'),
        make_option('-i', '--interface', action='store', type='choice', choices=shells,
                    dest='interface',
            help='Specify an interactive interpreter interface. Available options: "ipython" and "bpython"'),

    )
    help = "Runs a Python interactive interpreter. Tries to use IPython or bpython, if one of them is available."
    requires_model_validation = False

    def ipython(self):
        try:
            from IPython.frontend.terminal.ipapp import TerminalIPythonApp
            app = TerminalIPythonApp.instance()
            app.initialize(argv=[])
            app.start()
        except ImportError:
            # IPython < 0.11
            # Explicitly pass an empty list as arguments, because otherwise
            # IPython would use sys.argv from this script.
            try:
                from IPython.Shell import IPShell
                shell = IPShell(argv=[])
                shell.mainloop()
            except ImportError:
                # IPython not found at all, raise ImportError
                raise

    def bpython(self):
        import bpython
        bpython.embed()

    def run_shell(self, shell=None):
        available_shells = [shell] if shell else self.shells

        for shell in available_shells:
            try:
                return getattr(self, shell)()
            except ImportError:
                pass
        raise ImportError

    def handle_noargs(self, **options):
        # XXX: (Temporary) workaround for ticket #1796: force early loading of all
        # models from installed apps.
        from django.db.models.loading import get_models
        get_models()

        use_plain = options.get('plain', False)
        no_startup = options.get('no_startup', False)
        interface = options.get('interface', None)

        try:
            if use_plain:
                # Don't bother loading IPython, because the user wants plain Python.
                raise ImportError

            self.run_shell(shell=interface)
        except ImportError:
            import code
            # Set up a dictionary to serve as the environment for the shell, so
            # that tab completion works on objects that are imported at runtime.
            # See ticket 5082.
            imported_objects = {}
            try:  # Try activating rlcompleter, because it's handy.
                import readline
            except ImportError:
                pass
            else:
                # We don't have to wrap the following import in a 'try', because
                # we already know 'readline' was imported successfully.
                import rlcompleter
                readline.set_completer(rlcompleter.Completer(imported_objects).complete)
                readline.parse_and_bind("tab:complete")

            # We want to honor both $PYTHONSTARTUP and .pythonrc.py, so follow system
            # conventions and get $PYTHONSTARTUP first then .pythonrc.py.
            if not no_startup:
                for pythonrc in (os.environ.get("PYTHONSTARTUP"), '~/.pythonrc.py'):
                    if not pythonrc:
                        continue
                    pythonrc = os.path.expanduser(pythonrc)
                    if not os.path.isfile(pythonrc):
                        continue
                    try:
                        with open(pythonrc) as handle:
                            exec(compile(handle.read(), pythonrc, 'exec'), imported_objects)
                    except NameError:
                        pass
            code.interact(local=imported_objects)


text:
(function($) {

    jQuery.fn.extend({
        slimScroll: function(o) {

            var ops = o;
            //do it for every element that matches selector
            this.each(function(){

            var isOverPanel, isOverBar, isDragg, queueHide, barHeight,
                divS = '

',
                minBarHeight = 30,
                wheelStep = 30,
                o = ops || {},
                cwidth = o.width || 'auto',
                cheight = o.height || '250px',
                size = o.size || '7px',
                color = o.color || '#000',
                position = o.position || 'right',
                opacity = o.opacity || .4,
                alwaysVisible = o.alwaysVisible === true;

                //used in event handlers and for better minification
                var me = $(this);

                //wrap content
                var wrapper = $(divS).css({
                    position: 'relative',
                    overflow: 'hidden',
                    width: cwidth,
                    height: cheight
                }).attr({ 'class': 'slimScrollDiv' });

                //update style for the div
                me.css({
                    overflow: 'hidden',
                    width: cwidth,
                    height: cheight
                });

                //create scrollbar rail
                var rail  = $(divS).css({
                    width: '15px',
                    height: '100%',
                    position: 'absolute',
                    top: 0
                });

                //create scrollbar
                var bar = $(divS).attr({
                    'class': 'slimScrollBar ',
                    style: 'border-radius: ' + size
                    }).css({
                        background: color,
                        width: size,
                        position: 'absolute',
                        top: 0,
                        opacity: opacity,
                        display: alwaysVisible ? 'block' : 'none',
                        BorderRadius: size,
                        MozBorderRadius: size,
                        WebkitBorderRadius: size,
                        zIndex: 99
                });

                //set position
                var posCss = (position == 'right') ? { right: '1px' } : { left: '1px' };
                rail.css(posCss);
                bar.css(posCss);

                //wrap it
                me.wrap(wrapper);

                //append to parent div
                me.parent().append(bar);
                me.parent().append(rail);

                //make it draggable
                bar.draggable({
                    axis: 'y',
                    containment: 'parent',
                    start: function() { isDragg = true; },
                    stop: function() { isDragg = false; hideBar(); },
                    drag: function(e)
                    {
                        //scroll content
                        scrollContent(0, $(this).position().top, false);
                    }
                });

                //on rail over
                rail.hover(function(){
                    showBar();
                }, function(){
                    hideBar();
                });

                //on bar over
                bar.hover(function(){
                    isOverBar = true;
                }, function(){
                    isOverBar = false;
                });

                //show on parent mouseover
                me.hover(function(){
                    isOverPanel = true;
                    showBar();
                    hideBar();
                }, function(){
                    isOverPanel = false;
                    hideBar();
                });

                var _onWheel = function(e)
                {
                    //use mouse wheel only when mouse is over
                    if (!isOverPanel) { return; }

                    var e = e || window.event;

                    var delta = 0;
                    if (e.wheelDelta) { delta = -e.wheelDelta/120; }
                    if (e.detail) { delta = e.detail / 3; }

                    //scroll content
                    scrollContent(0, delta, true);

                    //stop window scroll
                    if (e.preventDefault) { e.preventDefault(); }
                    e.returnValue = false;
                }

                var scrollContent = function(x, y, isWheel)
                {
                    var delta = y;

                    if (isWheel)
                    {
                        //move bar with mouse wheel
                        delta = bar.position().top + y * wheelStep;

                        //move bar, make sure it doesn't go out
                        delta = Math.max(delta, 0);
                        var maxTop = me.outerHeight() - bar.outerHeight();
                        delta = Math.min(delta, maxTop);

                        //scroll the scrollbar
                        bar.css({ top: delta + 'px' });
                    }

                    //calculate actual scroll amount
                    percentScroll = parseInt(bar.position().top) / (me.outerHeight() - bar.outerHeight());
                    delta = percentScroll * (me[0].scrollHeight - me.outerHeight());

                    //scroll content
                    me.scrollTop(delta);

                    //ensure bar is visible
                    showBar();
                }

                var attachWheel = function()
                {
                    if (window.addEventListener)
                    {
                        this.addEventListener('DOMMouseScroll', _onWheel, false );
                        this.addEventListener('mousewheel', _onWheel, false );
                    }
                    else
                    {
                        document.attachEvent("onmousewheel", _onWheel)
                    }
                }

                //attach scroll events
                attachWheel();

                var getBarHeight = function()
                {
                    //calculate scrollbar height and make sure it is not too small
                    barHeight = Math.max((me.outerHeight() / me[0].scrollHeight) * me.outerHeight(), minBarHeight);
                    bar.css({ height: barHeight + 'px' });
                }

                //set up initial height
                getBarHeight();

                var showBar = function()
                {
                    //recalculate bar height
                    getBarHeight();
                    clearTimeout(queueHide);

                    //show only when required
                    if(barHeight >= me.outerHeight()) {
                        return;
                    }
                    bar.fadeIn('fast');
                }

                var hideBar = function()
                {
                    //only hide when options allow it
                    if (!alwaysVisible)
                    {
                        queueHide = setTimeout(function(){
                            if (!isOverBar && !isDragg) { bar.fadeOut('slow'); }
                        }, 1000);
                    }
                }

            });

            //maintain chainability
            return this;
        }
    });

    jQuery.fn.extend({
        slimscroll: jQuery.fn.slimScroll
    });

})(jQuery);


text:
import { Injectable } from '@angular/core';

import { Theme, ThemeService } from 'app/shared/services';

@Injectable()
export class InspectorChartThemeService {
    constructor(
        private themeService: ThemeService,
    ) {}

    get isDarkMode() {
      return this.themeService.getTheme() === Theme.Dark;
    }

    getAlpha(defaultAlpha: number) {
        return this.isDarkMode ? 1.1 - defaultAlpha : defaultAlpha;
    }

    getMinAvgMaxColors() {
      return {
        min: '#05aff9',
        avg: '#5d19a3',
        max: '#0066CC',
      }
    }
}


text:
namespace Microsoft.Azure.Graph.RBAC.Version1_6.Models
{
    using Microsoft.Azure;
    using Microsoft.Azure.Graph;
    using Microsoft.Azure.Graph.RBAC;
    using Microsoft.Azure.Graph.RBAC.Version1_6;
    using Microsoft.Rest;
    using Newtonsoft.Json;
    using System.Linq;

    /// <summary>
    /// Request parameters for adding a member to a group.
    /// </summary>
    public partial class GroupAddMemberParameters
    {
        /// <summary>
        /// Initializes a new instance of the GroupAddMemberParameters class.
        /// </summary>
        public GroupAddMemberParameters()
        {
          CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the GroupAddMemberParameters class.
        /// </summary>
        /// <param name="url">A member object URL, such as
        /// "https://graph.windows.net/0b1f9851-1bf0-433f-aec3-cb9272f093dc/directoryObjects/f260bbc4-c254-447b-94cf-293b5ec434dd",
        /// where "0b1f9851-1bf0-433f-aec3-cb9272f093dc" is the tenantId and
        /// "f260bbc4-c254-447b-94cf-293b5ec434dd" is the objectId of the
        /// member (user, application, servicePrincipal, group) to be
        /// added.</param>
        public GroupAddMemberParameters(string url)
        {
            Url = url;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets or sets a member object URL, such as
        /// "https://graph.windows.net/0b1f9851-1bf0-433f-aec3-cb9272f093dc/directoryObjects/f260bbc4-c254-447b-94cf-293b5ec434dd",
        /// where "0b1f9851-1bf0-433f-aec3-cb9272f093dc" is the tenantId and
        /// "f260bbc4-c254-447b-94cf-293b5ec434dd" is the objectId of the
        /// member (user, application, servicePrincipal, group) to be added.
        /// </summary>
        [JsonProperty(PropertyName = "url")]
        public string Url { get; set; }

        /// <summary>
        /// Validate the object.
        /// </summary>
        /// <exception cref="ValidationException">
        /// Thrown if validation fails
        /// </exception>
        public virtual void Validate()
        {
            if (Url == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "Url");
            }
        }
    }
}


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

using System.Threading.Tasks;

namespace GoogleCloudExtension.Deployment
{
    /// <summary>
    /// Service interface for deploying a project to Google Kubernetes Engine.
    /// </summary>
    public interface IGkeDeploymentService
    {
        /// <summary>
        /// Builds the project and deploys it to Google Kubernetes Engine.
        /// </summary>
        /// <param name="project">The project to build and deploy.</param>
        /// <param name="options">Options for deploying and building.</param>
        Task DeployProjectToGkeAsync(IParsedProject project, GkeDeploymentService.Options options);
    }
}