text:
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/autofill_assistant/browser/android/ui_controller_android_utils.h"

#include <utility>
#include <vector>

#include "base/android/jni_array.h"
#include "base/android/jni_string.h"
#include "base/base64.h"
#include "base/containers/flat_map.h"
#include "base/notreached.h"
#include "components/autofill/core/browser/autofill_data_util.h"
#include "components/autofill_assistant/android/jni_headers/AssistantChip_jni.h"
#include "components/autofill_assistant/android/jni_headers/AssistantColor_jni.h"
#include "components/autofill_assistant/android/jni_headers/AssistantDateTime_jni.h"
#include "components/autofill_assistant/android/jni_headers/AssistantDeviceConfig_jni.h"
#include "components/autofill_assistant/android/jni_headers/AssistantDialogButton_jni.h"
#include "components/autofill_assistant/android/jni_headers/AssistantDimension_jni.h"
#include "components/autofill_assistant/android/jni_headers/AssistantDrawable_jni.h"
#include "components/autofill_assistant/android/jni_headers/AssistantInfoPopup_jni.h"
#include "components/autofill_assistant/android/jni_headers/AssistantValue_jni.h"
#include "components/autofill_assistant/android/jni_headers/AutofillAssistantDependencyInjector_jni.h"
#include "components/autofill_assistant/android/jni_headers_public/AssistantAutofillCreditCard_jni.h"
#include "components/autofill_assistant/android/jni_headers_public/AssistantAutofillProfile_jni.h"
#include "components/autofill_assistant/browser/android/client_android.h"
#include "components/autofill_assistant/browser/android/dependencies_android.h"
#include "components/autofill_assistant/browser/generic_ui_java_generated_enums.h"
#include "components/autofill_assistant/browser/service/service.h"
#include "components/autofill_assistant/browser/service/service_request_sender.h"
#include "components/strings/grit/components_strings.h"
#include "ui/base/l10n/l10n_util.h"
#include "url/android/gurl_android.h"

namespace autofill_assistant {
namespace ui_controller_android_utils {
namespace {

using ::base::android::ConvertJavaStringToUTF16;
using ::base::android::ConvertJavaStringToUTF8;
using ::base::android::ConvertUTF16ToJavaString;
using ::base::android::ConvertUTF8ToJavaString;
using ::base::android::JavaRef;

constexpr char kNightModePrefix[] = "night-";

DrawableIcon MapDrawableIcon(DrawableProto::Icon icon) {
  switch (icon) {
    case DrawableProto::DRAWABLE_ICON_UNDEFINED:
      return DrawableIcon::DRAWABLE_ICON_UNDEFINED;
    case DrawableProto::PROGRESSBAR_DEFAULT_INITIAL_STEP:
      return DrawableIcon::PROGRESSBAR_DEFAULT_INITIAL_STEP;
    case DrawableProto::PROGRESSBAR_DEFAULT_DATA_COLLECTION:
      return DrawableIcon::PROGRESSBAR_DEFAULT_DATA_COLLECTION;
    case DrawableProto::PROGRESSBAR_DEFAULT_PAYMENT:
      return DrawableIcon::PROGRESSBAR_DEFAULT_PAYMENT;
    case DrawableProto::PROGRESSBAR_DEFAULT_FINAL_STEP:
      return DrawableIcon::PROGRESSBAR_DEFAULT_FINAL_STEP;
    case DrawableProto::SITTING_PERSON:
      return DrawableIcon::SITTING_PERSON;
    case DrawableProto::TICKET_STUB:
      return DrawableIcon::TICKET_STUB;
    case DrawableProto::SHOPPING_BASKET:
      return DrawableIcon::SHOPPING_BASKET;
    case DrawableProto::FAST_FOOD:
      return DrawableIcon::FAST_FOOD;
    case DrawableProto::LOCAL_DINING:
      return DrawableIcon::LOCAL_DINING;
    case DrawableProto::COGWHEEL:
      return DrawableIcon::COGWHEEL;
    case DrawableProto::KEY:
      return DrawableIcon::KEY;
    case DrawableProto::CAR:
      return DrawableIcon::CAR;
    case DrawableProto::GROCERY:
      return DrawableIcon::GROCERY;
    case DrawableProto::VISIBILITY_ON:
      return DrawableIcon::VISIBILITY_ON;
    case DrawableProto::VISIBILITY_OFF:
      return DrawableIcon::VISIBILITY_OFF;
    case DrawableProto::INFO:
      return DrawableIcon::INFO;
  }
}

void MaybeSetInfo(autofill::AutofillProfile* profile,
                  autofill::ServerFieldType type,
                  const JavaRef<jstring>& value,
                  const std::string& locale) {
  if (value) {
    profile->SetInfo(type, ConvertJavaStringToUTF16(value), locale);
  }
}

void MaybeSetRawInfo(autofill::AutofillProfile* profile,
                     autofill::ServerFieldType type,
                     const JavaRef<jstring>& value) {
  if (value) {
    profile->SetRawInfo(type, ConvertJavaStringToUTF16(value));
  }
}

const std::pair<std::string, std::string> RemoveDarkQualifier(
    std::string resource_qualifier,
    std::string url) {
  if (resource_qualifier.rfind(kNightModePrefix, 0) == 0) {
    resource_qualifier =
        resource_qualifier.substr(std::string(kNightModePrefix).length());
  }
  return {resource_qualifier, url};
}

std::map<std::string, std::string> FilterConfigBasedOnDayNightSetting(
    bool is_dark_mode_enabled,
    const ConfigBasedUrlProto& url_config) {
  std::map<std::string, std::string> daynight_specific_config;
  for (auto config_entry : url_config.url()) {
    std::string resource_qualifier = config_entry.first;
    std::string url = config_entry.second;
    bool dark_mode_qualified =
        resource_qualifier.rfind(kNightModePrefix, 0) == 0;
    if (is_dark_mode_enabled == dark_mode_qualified) {
      daynight_specific_config.insert(
          RemoveDarkQualifier(resource_qualifier, url));
    }
  }
  std::map<std::string, std::string> dpi_url_config;
  if (daynight_specific_config.empty()) {
    for (auto config_entry : url_config.url()) {
      daynight_specific_config.insert(
          RemoveDarkQualifier(config_entry.first, config_entry.second));
    }
  }
  return daynight_specific_config;
}

const std::string GetBitmapImageUrlBasedOnDeviceConfig(
    JNIEnv* env,
    const JavaRef<jobject>& jcontext,
    const ConfigBasedUrlProto& url_config) {
  bool is_dark_mode_enabled =
      Java_AssistantDeviceConfig_isDarkModeEnabled(env, jcontext);
  std::map<std::string, std::string> daynight_specific_config =
      FilterConfigBasedOnDayNightSetting(is_dark_mode_enabled, url_config);

  // Return image for the device pixel density. If not available, fallback to
  // mdpi. Caller has to specify mdpi image.
  std::string device_density = ConvertJavaStringToUTF8(
      Java_AssistantDeviceConfig_getDevicePixelDensity(env, jcontext));
  auto pos_it = daynight_specific_config.find(device_density);
  if (pos_it != daynight_specific_config.end()) {
    return pos_it->second;
  }
  if (daynight_specific_config.find("mdpi") == daynight_specific_config.end()) {
    return "";
  }
  return daynight_specific_config.find("mdpi")->second;
}

const std::string GetBitmapImageUrl(JNIEnv* env,
                                    const JavaRef<jobject>& jcontext,
                                    const BitmapDrawableProto& bitmap) {
  switch (bitmap.image_url_case()) {
    case BitmapDrawableProto::ImageUrlCase::kUrl: {
      return bitmap.url();
    }
    case BitmapDrawableProto::ImageUrlCase::kConfigBasedUrl: {
      return GetBitmapImageUrlBasedOnDeviceConfig(env, jcontext,
                                                  bitmap.config_based_url());
    }
    case BitmapDrawableProto::ImageUrlCase::IMAGE_URL_NOT_SET: {
      VLOG(1) << "Image url not set in bitmap image request.";
      return "";
    }
  }
}

}  // namespace

base::android::ScopedJavaLocalRef<jobject> GetJavaColor(
    JNIEnv* env,
    const std::string& color_string) {
  if (!Java_AssistantColor_isValidColorString(
          env, base::android::ConvertUTF8ToJavaString(env, color_string))) {
    if (!color_string.empty()) {
      VLOG(1) << "Encountered invalid color string: " << color_string;
    }
    return nullptr;
  }

  return Java_AssistantColor_createFromString(
      env, base::android::ConvertUTF8ToJavaString(env, color_string));
}

base::android::ScopedJavaLocalRef<jobject> GetJavaColor(
    JNIEnv* env,
    const JavaRef<jobject>& jcontext,
    const ColorProto& proto) {
  switch (proto.color_case()) {
    case ColorProto::kResourceIdentifier:
      if (!Java_AssistantColor_isValidResourceIdentifier(
              env, jcontext,
              base::android::ConvertUTF8ToJavaString(
                  env, proto.resource_identifier()))) {
        VLOG(1) << "Encountered invalid color resource identifier: "
                << proto.resource_identifier();
        return nullptr;
      }
      return Java_AssistantColor_createFromResource(
          env, jcontext,
          base::android::ConvertUTF8ToJavaString(env,
                                                 proto.resource_identifier()));
    case ColorProto::kParseableColor:
      return GetJavaColor(env, proto.parseable_color());
    case ColorProto::COLOR_NOT_SET:
      return nullptr;
  }
}

absl::optional<int> GetPixelSize(JNIEnv* env,
                                 const JavaRef<jobject>& jcontext,
                                 const ClientDimensionProto& proto) {
  switch (proto.size_case()) {
    case ClientDimensionProto::kDp:
      return Java_AssistantDimension_getPixelSizeDp(env, jcontext, proto.dp());
    case ClientDimensionProto::kWidthFactor:
      return Java_AssistantDimension_getPixelSizeWidthFactor(
          env, jcontext, proto.width_factor());
    case ClientDimensionProto::kHeightFactor:
      return Java_AssistantDimension_getPixelSizeHeightFactor(
          env, jcontext, proto.height_factor());
    case ClientDimensionProto::kSizeInPixel:
      return proto.size_in_pixel();
    case ClientDimensionProto::SIZE_NOT_SET:
      return absl::nullopt;
  }
}

int GetPixelSizeOrDefault(JNIEnv* env,
                          const JavaRef<jobject>& jcontext,
                          const ClientDimensionProto& proto,
                          int default_value) {
  auto size = GetPixelSize(env, jcontext, proto);
  if (size) {
    return *size;
  }
  return default_value;
}

base::android::ScopedJavaLocalRef<jobject> CreateJavaDrawable(
    JNIEnv* env,
    const JavaRef<jobject>& jcontext,
    const DependenciesAndroid& dependencies,
    const DrawableProto& proto,
    const UserModel* user_model) {
  switch (proto.drawable_case()) {
    case DrawableProto::kResourceIdentifier:
      if (!Java_AssistantDrawable_isValidDrawableResource(
              env, jcontext,
              base::android::ConvertUTF8ToJavaString(
                  env, proto.resource_identifier()))) {
        VLOG(1) << "Encountered invalid drawable resource identifier: "
                << proto.resource_identifier();
        return nullptr;
      }
      return Java_AssistantDrawable_createFromResource(
          env, base::android::ConvertUTF8ToJavaString(
                   env, proto.resource_identifier()));
    case DrawableProto::kBitmap: {
      std::string url = GetBitmapImageUrl(env, jcontext, proto.bitmap());
      if (proto.bitmap().use_instrinsic_dimensions()) {
        return Java_AssistantDrawable_createFromUrlWithIntrinsicDimensions(
            env, dependencies.CreateImageFetcher(),
            base::android::ConvertUTF8ToJavaString(env, url));
      } else {
        int width_pixels = ui_controller_android_utils::GetPixelSizeOrDefault(
            env, jcontext, proto.bitmap().width(), 0);
        int height_pixels = ui_controller_android_utils::GetPixelSizeOrDefault(
            env, jcontext, proto.bitmap().height(), 0);
        return Java_AssistantDrawable_createFromUrl(
            env, dependencies.CreateImageFetcher(),
            base::android::ConvertUTF8ToJavaString(env, url), width_pixels,
            height_pixels);
      }
    }
    case DrawableProto::kShape: {
      switch (proto.shape().shape_case()) {
        case ShapeDrawableProto::kRectangle: {
          auto jbackground_color = ui_controller_android_utils::GetJavaColor(
              env, jcontext, proto.shape().background_color());
          auto jstroke_color = ui_controller_android_utils::GetJavaColor(
              env, jcontext, proto.shape().stroke_color());
          int stroke_width_pixels =
              ui_controller_android_utils::GetPixelSizeOrDefault(
                  env, jcontext, proto.shape().stroke_width(), 0);
          int corner_radius_pixels =
              ui_controller_android_utils::GetPixelSizeOrDefault(
                  env, jcontext, proto.shape().rectangle().corner_radius(), 0);
          return Java_AssistantDrawable_createRectangleShape(
              env, jbackground_color, jstroke_color, stroke_width_pixels,
              corner_radius_pixels);
        }
        case ShapeDrawableProto::SHAPE_NOT_SET:
          return nullptr;
      }
    }
    case DrawableProto::kIcon: {
      return Java_AssistantDrawable_createFromIcon(
          env, static_cast<int>(MapDrawableIcon(proto.icon())));
    }
    case DrawableProto::kImageData: {
      return Java_AssistantDrawable_createFromBase64(
          env, base::android::ToJavaByteArray(env, proto.image_data()));
    }
    case DrawableProto::kImageDataBase64: {
      std::string image_data;
      if (!base::Base64Decode(proto.image_data_base64(), &image_data)) {
        VLOG(1) << "Invalid Base64 image data.";
        return nullptr;
      }
      return Java_AssistantDrawable_createFromBase64(
          env, base::android::ToJavaByteArray(env, image_data));
    }
    case DrawableProto::kFavicon: {
      if (!user_model) {
        VLOG(1) << "User model missing while trying to create a favicon.";
        return nullptr;
      }
      int diameter_size_in_pixel =
          ui_controller_android_utils::GetPixelSizeOrDefault(
              env, jcontext, proto.favicon().diameter_size(), 0);
      GURL url = proto.favicon().has_website_url()
                     ? GURL(proto.favicon().website_url())
                     : user_model->GetCurrentURL();
      return Java_AssistantDrawable_createFromFavicon(
          env, dependencies.CreateIconBridge(),
          url::GURLAndroid::FromNativeGURL(env, url), diameter_size_in_pixel,
          proto.favicon().force_monogram());
    }
    case DrawableProto::DRAWABLE_NOT_SET:
      return nullptr;
  }
}

base::android::ScopedJavaLocalRef<jobject> ToJavaValue(
    JNIEnv* env,
    const ValueProto& proto) {
  switch (proto.kind_case()) {
    case ValueProto::kStrings: {
      std::vector<std::string> strings;
      strings.reserve(proto.strings().values_size());
      for (const auto& string : proto.strings().values()) {
        strings.push_back(string);
      }
      return Java_AssistantValue_createForStrings(
          env, base::android::ToJavaArrayOfStrings(env, strings));
    }
    case ValueProto::kBooleans: {
      auto booleans = std::make_unique<bool[]>(proto.booleans().values_size());
      for (int i = 0; i < proto.booleans().values_size(); ++i) {
        booleans[i] = proto.booleans().values()[i];
      }
      return Java_AssistantValue_createForBooleans(
          env, base::android::ToJavaBooleanArray(
                   env, booleans.get(), proto.booleans().values_size()));
    }
    case ValueProto::kInts: {
      auto ints = std::make_unique<int[]>(proto.ints().values_size());
      for (int i = 0; i < proto.ints().values_size(); ++i) {
        ints[i] = proto.ints().values()[i];
      }
      return Java_AssistantValue_createForIntegers(
          env, base::android::ToJavaIntArray(env, ints.get(),
                                             proto.ints().values_size()));
    }
    case ValueProto::kCreditCards:
    case ValueProto::kProfiles:
    case ValueProto::kLoginOptions:
    case ValueProto::kCreditCardResponse:
    case ValueProto::kServerPayload:
    case ValueProto::kUserActions:
      // Unused.
      NOTREACHED();
      return nullptr;
    case ValueProto::kDates: {
      auto jlist = Java_AssistantValue_createDateTimeList(env);
      for (const auto& value : proto.dates().values()) {
        Java_AssistantValue_addDateTimeToList(
            env, jlist,
            Java_AssistantDateTime_Constructor(
                env, static_cast<int>(value.year()), value.month(), value.day(),
                0, 0, 0));
      }
      return Java_AssistantValue_createForDateTimes(env, jlist);
    }
    case ValueProto::KIND_NOT_SET:
      return Java_AssistantValue_create(env);
  }
}

ValueProto ToNativeValue(JNIEnv* env,
                         const base::android::JavaParamRef<jobject>& jvalue) {
  ValueProto proto;
  if (!jvalue) {
    return proto;
  }
  auto jints = Java_AssistantValue_getIntegers(env, jvalue);
  if (jints) {
    auto* mutable_ints = proto.mutable_ints();
    std::vector<int> ints;
    base::android::JavaIntArrayToIntVector(env, jints, &ints);
    for (int i : ints) {
      mutable_ints->add_values(i);
    }
    return proto;
  }

  auto jbooleans = Java_AssistantValue_getBooleans(env, jvalue);
  if (jbooleans) {
    auto* mutable_booleans = proto.mutable_booleans();
    std::vector<bool> booleans;
    base::android::JavaBooleanArrayToBoolVector(env, jbooleans, &booleans);
    for (auto b : booleans) {
      mutable_booleans->add_values(b);
    }
    return proto;
  }

  auto jstrings = Java_AssistantValue_getStrings(env, jvalue);
  if (jstrings) {
    auto* mutable_strings = proto.mutable_strings();
    std::vector<std::string> strings;
    base::android::AppendJavaStringArrayToStringVector(env, jstrings, &strings);
    for (const auto& string : strings) {
      mutable_strings->add_values(string);
    }
    return proto;
  }

  auto jdatetimes = Java_AssistantValue_getDateTimes(env, jvalue);
  if (jdatetimes) {
    auto* mutable_dates = proto.mutable_dates();
    for (int i = 0; i < Java_AssistantValue_getListSize(env, jdatetimes); ++i) {
      auto jdatetimes_value = Java_AssistantValue_getListAt(env, jdatetimes, i);
      DateProto date;
      date.set_year(Java_AssistantDateTime_getYear(env, jdatetimes_value));
      date.set_month(Java_AssistantDateTime_getMonth(env, jdatetimes_value));
      date.set_day(Java_AssistantDateTime_getDay(env, jdatetimes_value));
      *mutable_dates->add_values() = date;
    }
    return proto;
  }

  return proto;
}

base::android::ScopedJavaLocalRef<jobject> CreateJavaDialogButton(
    JNIEnv* env,
    const InfoPopupProto_DialogButton& button_proto,
    const JavaRef<jobject>& jinfo_page_util) {
  base::android::ScopedJavaLocalRef<jstring> jurl = nullptr;

  switch (button_proto.click_action_case()) {
    case InfoPopupProto::DialogButton::kOpenUrlInCct:
      jurl = base::android::ConvertUTF8ToJavaString(
          env, button_proto.open_url_in_cct().url());
      break;
    case InfoPopupProto::DialogButton::kCloseDialog:
      break;
    case InfoPopupProto::DialogButton::CLICK_ACTION_NOT_SET:
      NOTREACHED();
      break;
  }
  return Java_AssistantDialogButton_Constructor(
      env, jinfo_page_util,
      base::android::ConvertUTF8ToJavaString(env, button_proto.label()), jurl);
}

base::android::ScopedJavaLocalRef<jobject> CreateJavaInfoPopup(
    JNIEnv* env,
    const InfoPopupProto& info_popup_proto,
    const JavaRef<jobject>& jinfo_page_util,
    const std::string& close_display_str,
    const JavaRef<jobject>& jdelegate) {
  base::android::ScopedJavaLocalRef<jobject> jpositive_button = nullptr;
  base::android::ScopedJavaLocalRef<jobject> jnegative_button = nullptr;
  base::android::ScopedJavaLocalRef<jobject> jneutral_button = nullptr;

  if (info_popup_proto.has_positive_button() ||
      info_popup_proto.has_negative_button() ||
      info_popup_proto.has_neutral_button()) {
    if (info_popup_proto.has_positive_button()) {
      jpositive_button = CreateJavaDialogButton(
          env, info_popup_proto.positive_button(), jinfo_page_util);
    }
    if (info_popup_proto.has_negative_button()) {
      jnegative_button = CreateJavaDialogButton(
          env, info_popup_proto.negative_button(), jinfo_page_util);
    }
    if (info_popup_proto.has_neutral_button()) {
      jneutral_button = CreateJavaDialogButton(
          env, info_popup_proto.neutral_button(), jinfo_page_util);
    }
  } else {
    // If no button is set in the proto, we add a Close button
    jpositive_button = Java_AssistantDialogButton_Constructor(
        env, jinfo_page_util,
        base::android::ConvertUTF8ToJavaString(env, close_display_str),
        nullptr);
  }

  return Java_AssistantInfoPopup_Constructor(
      env,
      base::android::ConvertUTF8ToJavaString(env, info_popup_proto.title()),
      base::android::ConvertUTF8ToJavaString(env, info_popup_proto.text()),
      jpositive_button, jnegative_button, jneutral_button, jdelegate);
}

void ShowJavaInfoPopup(JNIEnv* env,
                       const JavaRef<jobject>& jinfo_popup,
                       const JavaRef<jobject>& jcontext) {
  Java_AssistantInfoPopup_show(env, jinfo_popup, jcontext);
}

std::string SafeConvertJavaStringToNative(
    JNIEnv* env,
    const base::android::JavaRef<jstring>& jstring) {
  std::string native_string;
  if (jstring) {
    native_string = base::android::ConvertJavaStringToUTF8(env, jstring);
  }
  return native_string;
}

base::android::ScopedJavaLocalRef<jstring> ConvertNativeOptionalStringToJava(
    JNIEnv* env,
    const absl::optional<std::string> optional_string) {
  if (!optional_string.has_value()) {
    return nullptr;
  }
  return base::android::ConvertUTF8ToJavaString(env, *optional_string);
}

BottomSheetState ToNativeBottomSheetState(int state) {
  switch (state) {
    case 1:
      return BottomSheetState::COLLAPSED;
    case 2:
    case 3:
      return BottomSheetState::EXPANDED;
    default:
      return BottomSheetState::UNDEFINED;
  }
}

int ToJavaBottomSheetState(BottomSheetState state) {
  switch (state) {
    case BottomSheetState::COLLAPSED:
      return 1;
    case BottomSheetState::UNDEFINED:
      // The current assumption is that AutofillAssistant always starts with the
      // bottom sheet expanded.
    case BottomSheetState::EXPANDED:
      return 2;
    default:
      return -1;
  }
}

base::android::ScopedJavaLocalRef<jobject> CreateJavaAssistantChip(
    JNIEnv* env,
    const ChipProto& chip) {
  switch (chip.type()) {
    default:  // Other chip types are not supported.
      return nullptr;

    case HIGHLIGHTED_ACTION:
    case DONE_ACTION:
      return Java_AssistantChip_createHighlightedAssistantChip(
          env, static_cast<int>(chip.type()), chip.icon(),
          base::android::ConvertUTF8ToJavaString(env, chip.text()),
          /* disabled = */ false, chip.sticky(), /* visible = */ true,
          chip.has_content_description()
              ? base::android::ConvertUTF8ToJavaString(
                    env, chip.content_description())
              : nullptr);

    case NORMAL_ACTION:
    case CANCEL_ACTION:
    case CLOSE_ACTION:
    case FEEDBACK_ACTION:
      return Java_AssistantChip_createHairlineAssistantChip(
          env, static_cast<int>(chip.type()), chip.icon(),
          base::android::ConvertUTF8ToJavaString(env, chip.text()),
          /* disabled = */ false, chip.sticky(), /* visible = */ true,
          chip.has_content_description()
              ? base::android::ConvertUTF8ToJavaString(
                    env, chip.content_description())
              : nullptr);
  }
}

base::android::ScopedJavaLocalRef<jobject> CreateJavaAssistantChipList(
    JNIEnv* env,
    const std::vector<ChipProto>& chips) {
  auto jlist = Java_AssistantChip_createChipList(env);
  for (const auto& chip : chips) {
    auto jchip = CreateJavaAssistantChip(env, chip);
    if (!jchip) {
      return nullptr;
    }
    Java_AssistantChip_addChipToList(env, jlist, jchip);
  }
  return jlist;
}

base::flat_map<std::string, std::string> CreateStringMapFromJava(
    JNIEnv* env,
    const JavaRef<jobjectArray>& names,
    const JavaRef<jobjectArray>& values) {
  std::vector<std::string> names_vector;
  base::android::AppendJavaStringArrayToStringVector(env, names, &names_vector);
  std::vector<std::string> values_vector;
  base::android::AppendJavaStringArrayToStringVector(env, values,
                                                     &values_vector);
  std::vector<std::pair<std::string, std::string>> result;
  DCHECK_EQ(names_vector.size(), values_vector.size());
  for (size_t i = 0; i < names_vector.size(); ++i) {
    result.emplace_back(names_vector[i], values_vector[i]);
  }
  return base::flat_map<std::string, std::string>(std::move(result));
}

std::unique_ptr<TriggerContext> CreateTriggerContext(
    JNIEnv* env,
    content::WebContents* web_contents,
    const JavaRef<jstring>& jexperiment_ids,
    const JavaRef<jobjectArray>& jparameter_names,
    const JavaRef<jobjectArray>& jparameter_values,
    const JavaRef<jobjectArray>& jdevice_only_parameter_names,
    const JavaRef<jobjectArray>& jdevice_only_parameter_values,
    jboolean onboarding_shown,
    jboolean is_direct_action,
    const JavaRef<jstring>& jinitial_url,
    const bool is_custom_tab) {
  auto script_parameters = std::make_unique<ScriptParameters>(
      CreateStringMapFromJava(env, jparameter_names, jparameter_values));
  script_parameters->UpdateDeviceOnlyParameters(CreateStringMapFromJava(
      env, jdevice_only_parameter_names, jdevice_only_parameter_values));
  return std::make_unique<TriggerContext>(
      std::move(script_parameters),
      TriggerContext::Options(
          SafeConvertJavaStringToNative(env, jexperiment_ids), is_custom_tab,
          onboarding_shown, is_direct_action,
          SafeConvertJavaStringToNative(env, jinitial_url),
          /* is_in_chrome_triggered = */ false,
          /* is_externally_triggered = */ false,
          /* skip_autofill_assistant_onboarding = */ false,
          /* suppress_browsing_features = */ true));
}

std::unique_ptr<Service> GetServiceToInject(JNIEnv* env,
                                            ClientAndroid* client_android) {
  jlong jtest_service_to_inject =
      Java_AutofillAssistantDependencyInjector_getServiceToInject(
          env, reinterpret_cast<intptr_t>(client_android));
  std::unique_ptr<Service> test_service = nullptr;
  if (jtest_service_to_inject) {
    test_service.reset(static_cast<Service*>(
        reinterpret_cast<void*>(jtest_service_to_inject)));
  }
  return test_service;
}

std::unique_ptr<ServiceRequestSender> GetServiceRequestSenderToInject(
    JNIEnv* env) {
  jlong jtest_service_request_sender_to_inject =
      Java_AutofillAssistantDependencyInjector_getServiceRequestSenderToInject(
          env);
  std::unique_ptr<ServiceRequestSender> test_service_request_sender;
  if (jtest_service_request_sender_to_inject) {
    test_service_request_sender.reset(static_cast<ServiceRequestSender*>(
        reinterpret_cast<void*>(jtest_service_request_sender_to_inject)));
  }
  return test_service_request_sender;
}

std::unique_ptr<AutofillAssistantTtsController> GetTtsControllerToInject(
    JNIEnv* env) {
  jlong jtest_tts_controller_to_inject =
      Java_AutofillAssistantDependencyInjector_getTtsControllerToInject(env);
  std::unique_ptr<AutofillAssistantTtsController> test_tts_controller;
  if (jtest_tts_controller_to_inject) {
    test_tts_controller.reset(static_cast<AutofillAssistantTtsController*>(
        reinterpret_cast<void*>(jtest_tts_controller_to_inject)));
  }
  return test_tts_controller;
}

base::android::ScopedJavaLocalRef<jobject> CreateAssistantAutofillProfile(
    JNIEnv* env,
    const autofill::AutofillProfile& profile,
    const std::string& locale) {
  return Java_AssistantAutofillProfile_Constructor(
      env, ConvertUTF8ToJavaString(env, profile.guid()),
      ConvertUTF8ToJavaString(env, profile.origin()),
      profile.record_type() == autofill::AutofillProfile::LOCAL_PROFILE,
      ConvertUTF16ToJavaString(
          env, profile.GetInfo(autofill::NAME_HONORIFIC_PREFIX, locale)),
      ConvertUTF16ToJavaString(env,
                               profile.GetInfo(autofill::NAME_FULL, locale)),
      ConvertUTF16ToJavaString(env, profile.GetRawInfo(autofill::COMPANY_NAME)),
      ConvertUTF16ToJavaString(
          env, profile.GetRawInfo(autofill::ADDRESS_HOME_STREET_ADDRESS)),
      ConvertUTF16ToJavaString(
          env, profile.GetRawInfo(autofill::ADDRESS_HOME_STATE)),
      ConvertUTF16ToJavaString(env,
                               profile.GetRawInfo(autofill::ADDRESS_HOME_CITY)),
      ConvertUTF16ToJavaString(
          env, profile.GetRawInfo(autofill::ADDRESS_HOME_DEPENDENT_LOCALITY)),
      ConvertUTF16ToJavaString(env,
                               profile.GetRawInfo(autofill::ADDRESS_HOME_ZIP)),
      ConvertUTF16ToJavaString(
          env, profile.GetRawInfo(autofill::ADDRESS_HOME_SORTING_CODE)),
      ConvertUTF16ToJavaString(
          env, profile.GetRawInfo(autofill::ADDRESS_HOME_COUNTRY)),
      ConvertUTF16ToJavaString(
          env, profile.GetRawInfo(autofill::PHONE_HOME_WHOLE_NUMBER)),
      ConvertUTF16ToJavaString(env,
                               profile.GetRawInfo(autofill::EMAIL_ADDRESS)),
      ConvertUTF8ToJavaString(env, profile.language_code()));
}

void PopulateAutofillProfileFromJava(
    const base::android::JavaParamRef<jobject>& jprofile,
    JNIEnv* env,
    autofill::AutofillProfile* profile,
    const std::string& locale) {
  // Only set the guid if it is an existing profile (Java guid not empty).
  // Otherwise, keep the generated one.
  std::string guid = ConvertJavaStringToUTF8(
      Java_AssistantAutofillProfile_getGUID(env, jprofile));
  if (!guid.empty()) {
    profile->set_guid(guid);
  }

  profile->set_origin(ConvertJavaStringToUTF8(
      Java_AssistantAutofillProfile_getOrigin(env, jprofile)));
  MaybeSetInfo(profile, autofill::NAME_FULL,
               Java_AssistantAutofillProfile_getFullName(env, jprofile),
               locale);
  MaybeSetRawInfo(
      profile, autofill::NAME_HONORIFIC_PREFIX,
      Java_AssistantAutofillProfile_getHonorificPrefix(env, jprofile));
  MaybeSetRawInfo(profile, autofill::COMPANY_NAME,
                  Java_AssistantAutofillProfile_getCompanyName(env, jprofile));
  MaybeSetRawInfo(
      profile, autofill::ADDRESS_HOME_STREET_ADDRESS,
      Java_AssistantAutofillProfile_getStreetAddress(env, jprofile));
  MaybeSetRawInfo(profile, autofill::ADDRESS_HOME_STATE,
                  Java_AssistantAutofillProfile_getRegion(env, jprofile));
  MaybeSetRawInfo(profile, autofill::ADDRESS_HOME_CITY,
                  Java_AssistantAutofillProfile_getLocality(env, jprofile));
  MaybeSetRawInfo(
      profile, autofill::ADDRESS_HOME_DEPENDENT_LOCALITY,
      Java_AssistantAutofillProfile_getDependentLocality(env, jprofile));
  MaybeSetRawInfo(profile, autofill::ADDRESS_HOME_ZIP,
                  Java_AssistantAutofillProfile_getPostalCode(env, jprofile));
  MaybeSetRawInfo(profile, autofill::ADDRESS_HOME_SORTING_CODE,
                  Java_AssistantAutofillProfile_getSortingCode(env, jprofile));
  MaybeSetInfo(profile, autofill::ADDRESS_HOME_COUNTRY,
               Java_AssistantAutofillProfile_getCountryCode(env, jprofile),
               locale);
  MaybeSetRawInfo(profile, autofill::PHONE_HOME_WHOLE_NUMBER,
                  Java_AssistantAutofillProfile_getPhoneNumber(env, jprofile));
  MaybeSetRawInfo(profile, autofill::EMAIL_ADDRESS,
                  Java_AssistantAutofillProfile_getEmailAddress(env, jprofile));
  profile->set_language_code(ConvertJavaStringToUTF8(
      Java_AssistantAutofillProfile_getLanguageCode(env, jprofile)));
  profile->FinalizeAfterImport();
}

base::android::ScopedJavaLocalRef<jobject> CreateAssistantAutofillCreditCard(
    JNIEnv* env,
    const autofill::CreditCard& credit_card,
    const std::string& locale) {
  const autofill::data_util::PaymentRequestData& payment_request_data =
      autofill::data_util::GetPaymentRequestData(credit_card.network());
  return Java_AssistantAutofillCreditCard_Constructor(
      env, ConvertUTF8ToJavaString(env, credit_card.guid()),
      ConvertUTF8ToJavaString(env, credit_card.origin()),
      credit_card.record_type() == autofill::CreditCard::LOCAL_CARD,
      credit_card.record_type() == autofill::CreditCard::FULL_SERVER_CARD,
      ConvertUTF16ToJavaString(
          env, credit_card.GetRawInfo(autofill::CREDIT_CARD_NAME_FULL)),
      ConvertUTF16ToJavaString(
          env, credit_card.GetRawInfo(autofill::CREDIT_CARD_NUMBER)),
      ConvertUTF16ToJavaString(env, credit_card.NetworkAndLastFourDigits()),
      ConvertUTF16ToJavaString(
          env, credit_card.GetRawInfo(autofill::CREDIT_CARD_EXP_MONTH)),
      ConvertUTF16ToJavaString(
          env, credit_card.GetRawInfo(autofill::CREDIT_CARD_EXP_4_DIGIT_YEAR)),
      ConvertUTF8ToJavaString(env,
                              payment_request_data.basic_card_issuer_network),
      Java_AssistantAutofillCreditCard_getIssuerIconDrawableId(
          env, ConvertUTF8ToJavaString(
                   env, credit_card.CardIconStringForAutofillSuggestion())),
      ConvertUTF8ToJavaString(env, credit_card.billing_address_id()),
      ConvertUTF8ToJavaString(env, credit_card.server_id()),
      credit_card.instrument_id(),
      ConvertUTF16ToJavaString(env, credit_card.nickname()),
      url::GURLAndroid::FromNativeGURL(env, credit_card.card_art_url()),
      static_cast<jint>(credit_card.virtual_card_enrollment_state()),
      ConvertUTF16ToJavaString(env, credit_card.product_description()),
      ConvertUTF16ToJavaString(env, credit_card.CardNameForAutofillDisplay()),
      ConvertUTF16ToJavaString(env, credit_card.ObfuscatedLastFourDigits()));
}

void PopulateAutofillCreditCardFromJava(
    const base::android::JavaParamRef<jobject>& jcredit_card,
    JNIEnv* env,
    autofill::CreditCard* credit_card,
    const std::string& locale) {
  // Only set the guid if it is an existing card (java guid not empty).
  // Otherwise, keep the generated one.
  std::string guid = ConvertJavaStringToUTF8(
      Java_AssistantAutofillCreditCard_getGUID(env, jcredit_card));
  if (!guid.empty()) {
    credit_card->set_guid(guid);
  }

  if (Java_AssistantAutofillCreditCard_getIsLocal(env, jcredit_card)) {
    credit_card->set_record_type(autofill::CreditCard::LOCAL_CARD);
  } else {
    if (Java_AssistantAutofillCreditCard_getIsCached(env, jcredit_card)) {
      credit_card->set_record_type(autofill::CreditCard::FULL_SERVER_CARD);
    } else {
      credit_card->set_record_type(autofill::CreditCard::MASKED_SERVER_CARD);
      credit_card->SetNetworkForMaskedCard(
          autofill::data_util::GetIssuerNetworkForBasicCardIssuerNetwork(
              ConvertJavaStringToUTF8(
                  env,
                  Java_AssistantAutofillCreditCard_getBasicCardIssuerNetwork(
                      env, jcredit_card))));
    }
  }

  credit_card->set_origin(ConvertJavaStringToUTF8(
      Java_AssistantAutofillCreditCard_getOrigin(env, jcredit_card)));
  credit_card->SetRawInfo(
      autofill::CREDIT_CARD_NAME_FULL,
      ConvertJavaStringToUTF16(
          Java_AssistantAutofillCreditCard_getName(env, jcredit_card)));
  credit_card->SetRawInfo(
      autofill::CREDIT_CARD_NUMBER,
      ConvertJavaStringToUTF16(
          Java_AssistantAutofillCreditCard_getNumber(env, jcredit_card)));
  credit_card->SetRawInfo(
      autofill::CREDIT_CARD_EXP_MONTH,
      ConvertJavaStringToUTF16(
          Java_AssistantAutofillCreditCard_getMonth(env, jcredit_card)));
  credit_card->SetRawInfo(
      autofill::CREDIT_CARD_EXP_4_DIGIT_YEAR,
      ConvertJavaStringToUTF16(
          Java_AssistantAutofillCreditCard_getYear(env, jcredit_card)));
  credit_card->set_billing_address_id(ConvertJavaStringToUTF8(
      Java_AssistantAutofillCreditCard_getBillingAddressId(env, jcredit_card)));
  credit_card->set_server_id(ConvertJavaStringToUTF8(
      Java_AssistantAutofillCreditCard_getServerId(env, jcredit_card)));
  credit_card->set_instrument_id(
      Java_AssistantAutofillCreditCard_getInstrumentId(env, jcredit_card));
  credit_card->SetNickname(ConvertJavaStringToUTF16(
      Java_AssistantAutofillCreditCard_getNickname(env, jcredit_card)));
  base::android::ScopedJavaLocalRef<jobject> jcard_art_url =
      Java_AssistantAutofillCreditCard_getCardArtUrl(env, jcredit_card);
  if (!jcard_art_url.is_null()) {
    credit_card->set_card_art_url(
        *url::GURLAndroid::ToNativeGURL(env, jcard_art_url));
  }
  credit_card->set_virtual_card_enrollment_state(
      static_cast<autofill::CreditCard::VirtualCardEnrollmentState>(
          Java_AssistantAutofillCreditCard_getVirtualCardEnrollmentState(
              env, jcredit_card)));
  credit_card->set_product_description(ConvertJavaStringToUTF16(
      Java_AssistantAutofillCreditCard_getProductDescription(env,
                                                             jcredit_card)));
}

}  // namespace ui_controller_android_utils
}  // namespace autofill_assistant


text:
package bio.terra.workspace.service.resource.controlled.cloud.azure.storageContainer.resourcemanager.data;

import bio.terra.cloudres.common.CloudOperation;
import bio.terra.workspace.service.resource.controlled.cloud.azure.storage.resourcemanager.StorageManagerOperation;
import com.google.auto.value.AutoValue;
import com.google.gson.JsonObject;
import java.util.UUID;

@AutoValue
public abstract class CreateStorageContainerRequestData extends BaseStorageContainerRequestData {

  @Override
  public CloudOperation cloudOperation() {
    return StorageManagerOperation.AZURE_CREATE_STORAGE_CONTAINER;
  }

  @Override
  public JsonObject serialize() {
    JsonObject requestData = super.serializeCommon();
    return requestData;
  }

  public static Builder builder() {
    return new AutoValue_CreateStorageContainerRequestData.Builder();
  }

  @AutoValue.Builder
  public abstract static class Builder {

    public abstract CreateStorageContainerRequestData.Builder setStorageAccountId(UUID value);

    public abstract CreateStorageContainerRequestData.Builder setStorageContainerName(String value);

    public abstract CreateStorageContainerRequestData.Builder setResourceGroupName(String value);

    public abstract CreateStorageContainerRequestData build();
  }
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.cassandra.config;

import javax.net.ssl.SSLSocketFactory;

public abstract class EncryptionOptions
{
    public String keystore = "conf/.keystore";
    public String keystore_password = "cassandra";
    public String truststore = "conf/.truststore";
    public String truststore_password = "cassandra";
    public String[] cipher_suites = ((SSLSocketFactory)SSLSocketFactory.getDefault()).getDefaultCipherSuites();
    public String protocol = "TLS";
    public String algorithm = "SunX509";
    public String store_type = "JKS";
    public boolean require_client_auth = false;
    public boolean require_endpoint_verification = false;

    public static class ClientEncryptionOptions extends EncryptionOptions
    {
        public boolean enabled = false;
        public boolean optional = false;
    }

    public static class ServerEncryptionOptions extends EncryptionOptions
    {
        public static enum InternodeEncryption
        {
            all, none, dc, rack
        }
        public InternodeEncryption internode_encryption = InternodeEncryption.none;
    }
}


text:
using System.Text;

namespace FilesAndFolders
{
    public class Startup
    {
        static void Main()
        {
            var entryPoint = new Folder("Help", @"C:\Windows\Help");
            GetSubFolders(entryPoint);
            StringBuilder sb = new StringBuilder();
            GetFileSystemString(entryPoint, sb, 0);
            System.Console.WriteLine(sb);
        }

        private static void GetFileSystemString(Folder folder, StringBuilder sb, int depth)
        {
            string indent = new string('*', depth * 3);

            sb.AppendLine(string.Format("{0}{1} size: {2}", indent, folder.Name, folder.GetSize()));

            foreach (var file in folder.Files)
            {
                sb.AppendLine(string.Format("{0}-{1} size: {2}", indent, file.Name, file.Size));
            }

            foreach (var subFolder in folder.Folders)
            {
                GetFileSystemString(subFolder, sb, depth + 1);
            }
        }

        private static void GetSubFolders(Folder folder)
        {
            foreach (var file in folder.Directory.GetFiles())
            {
                folder.Files.Add(new File(file.Name, file.Length));
            }

            foreach (var subDir in folder.Directory.GetDirectories())
            {
                var subFolder = new Folder(subDir.Name, subDir.FullName);
                folder.Folders.Add(subFolder);
                GetSubFolders(subFolder);
            }
        }
    }
}


text:
module Axiom

  # Abstract class for aggregate functions
  class Aggregate < Function
    include Operation::Unary
    include Equalizer.new(:operand)

    # Return the default accumulator
    #
    # @example
    #   default = Aggregate.default
    #
    # @return [Object]
    #
    # @api public
    def self.default
      self::DEFAULT
    end

    # Returns the value extracted from the accumulator
    #
    # Default behaviour is to pass-through the accumulator
    #
    # @example
    #   value = Aggregate.finalize(accumulator)
    #
    # @return [Object]
    #
    # @api public
    def self.finalize(accumulator)
      accumulator
    end

    # Return the default for this aggregate
    #
    # @example
    #   default = aggregate.default
    #
    # @return [Object]
    #
    # @api public
    def default
      self.class.default
    end

    # Evaluate the aggregate using the provided Tuple
    #
    # @example
    #   accumulator = aggregate.call(accumulator, tuple)
    #
    # @param [Object] accumulator
    #
    # @param [Tuple] tuple
    #
    # @return [Object]
    #
    # @api public
    def call(accumulator, tuple)
      self.class.call(accumulator, value(tuple))
    end

    # Finalize the accumulator value
    #
    # @example
    #   value = aggregate.finalize(accumulator)
    #
    # @return [Object]
    #
    # @api public
    def finalize(accumulator)
      self.class.finalize(accumulator)
    end

  private

    # Extract the value from the operand or tuple
    #
    # @param [Tuple] tuple
    #   the tuple to pass in to the operand if it responds to #call
    #
    # @return [Object]
    #
    # @api private
    def value(tuple)
      Function.extract_value(operand, tuple)
    end

  end # class Aggregate
end # module Axiom


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Newtonsoft.Json;

namespace Quest
{
	[Activity(Label = "ViewQuestActivity")]
	public class ViewQuestActivity : Activity
	{
		private List<QuestModel> mItems;
		protected override void OnCreate(Bundle savedInstanceState)
		{
			base.OnCreate(savedInstanceState);

			// Set our view from the "main" layout resource
			SetContentView(Resource.Layout.ViewQuest);

			int id = Intent.GetIntExtra("id", 6);

			string url = "http://104.199.155.15/api/v2/db/_table/quest/"+id.ToString();
			HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
			request.Method = "GET";
			request.Headers.Add("X-DreamFactory-Api-Key", "be8387a7b036ea65deb04d1a20d85e619b7e1634aa55b1cf6cc3988f130a2e81");
			request.Headers.Add("X-DreamFactory-Session-Token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjIsInVzZXJfaWQiOjIsImVtYWlsIjoicHVibGljQHB1YmxpYy5jb20iLCJmb3JldmVyIjp0cnVlLCJpc3MiOiJodHRwOlwvXC8xMDQuMTk5LjE1NS4xNVwvYXBpXC92MlwvdXNlclwvc2Vzc2lvbiIsImlhdCI6MTQ3MDM4MzczMCwiZXhwIjoxNTAxOTE5NzMwLCJuYmYiOjE0NzAzODM3MzAsImp0aSI6ImFlZWQ3YWRhYmI4N2I0ODBhNmIyYWRlYWM0YzQzZTU0In0.J35hKt384v25G3ylb547w0OAlJ4yYGWRxhknwm5sYhg");
			request.ContentType = "application/json";
			//HttpWebResponse myResp = (HttpWebResponse)request.GetResponse();
			string JSONString;
			using (var response = request.GetResponse())
			{
				using (var reader = new StreamReader(response.GetResponseStream()))
				{
					JSONString = "["+reader.ReadToEnd()+"]";
					Console.WriteLine("response: "+JSONString);
				}
			}
			mItems = JsonConvert.DeserializeObject<List<QuestModel>>(JSONString);

			TextView questName = (TextView)FindViewById<TextView>(Resource.Id.questName);
			questName.Text = mItems[0].questName;

			TextView questReward = (TextView)FindViewById<TextView>(Resource.Id.questReward);
			questReward.Text = mItems[0].questReward;

			TextView questDescription = (TextView)FindViewById<TextView>(Resource.Id.questDescription);
			questDescription.Text = mItems[0].questDescription;

			TextView questContact= (TextView)FindViewById<TextView>(Resource.Id.questContact);
			questContact.Text = mItems[0].questContact;
		}
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">SimpleCamApp</string>
    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>

    <string name="start_camera_button">Initialize Camera</string>

    <!-- Error messages -->
    <string name="error_message_no_camera_detected">It seems your device does not have camera. Could you check it?</string>

</resources>


text:
package server

import (
	"time"

	"github.com/m3db/m3/src/x/instrument"
	"github.com/m3db/m3/src/x/retry"
)

// Configuration configs a server.
type Configuration struct {
	// Server listening address.
	ListenAddress string `yaml:"listenAddress" validate:"nonzero"`

	// Retry mechanism configuration.
	Retry retry.Configuration `yaml:"retry"`

	// Whether keep alives are enabled on connections.
	KeepAliveEnabled *bool `yaml:"keepAliveEnabled"`

	// KeepAlive period.
	KeepAlivePeriod *time.Duration `yaml:"keepAlivePeriod"`
}

// NewOptions creates server options.
func (c Configuration) NewOptions(iOpts instrument.Options) Options {
	opts := NewOptions().
		SetRetryOptions(c.Retry.NewOptions(iOpts.MetricsScope())).
		SetInstrumentOptions(iOpts)
	if c.KeepAliveEnabled != nil {
		opts = opts.SetTCPConnectionKeepAlive(*c.KeepAliveEnabled)
	}
	if c.KeepAlivePeriod != nil {
		opts = opts.SetTCPConnectionKeepAlivePeriod(*c.KeepAlivePeriod)
	}
	return opts
}

// NewServer creates a new server.
func (c Configuration) NewServer(handler Handler, iOpts instrument.Options) Server {
	return NewServer(c.ListenAddress, handler, c.NewOptions(iOpts))
}


text:
<?xml version="1.0"?>
<project name="Impact Ant Build" basedir="." default="full-build">

    <!-- Change these properties based on your project -->

    <!-- Project meta data -->
    <property name="project.name" value="Alone"/>
    <property name="company.name" value="GameCook"/>
    <property name="company.site" value="http://gamecook.com"/>
    <property name="project.version" value="1.0.0"/>
    <property name="project.description" value="This is a game"/>
    <property name="project.url" value="http://gamecook.com/games/"/>

    <!-- Deployment directories -->
    <property name="deploy.dir" value="deploy"/>
    <property name="web.dir" value="${deploy.dir}/web"/>
    <property name="chrome.dir" value="${deploy.dir}/chrome"/>
    <property name="mozilla.dir" value="${deploy.dir}/mozilla"/>
    <property name="ios.dir" value="${deploy.dir}/ios"/>
    <property name="win8.dir" value="${deploy.dir}/win8"/>

    <!-- Path to Impact directory -->
    <property name="impact.dir" value="${basedir}/impact"/>

    <target name="full-build">
        <!-- Clean -->
        <antcall target="pre-build-cleanup"/>
        <antcall target="bake"/>
        <antcall target="web-build"/>
       <!-- <antcall target="ios-build"/>
        <antcall target="win8-build"/>
        <antcall target="chrome-build"/>
        <antcall target="mozilla-build"/>
        <antcall target="post-build-cleanup"/>-->
        <!-- Bake -->
    </target>

    <!-- Delete deploy directory and create a new one -->
    <target name="pre-build-cleanup">
        <delete dir="${deploy.dir}"/>
        <mkdir dir="${deploy.dir}"/>
    </target>

    <!-- Removes the minified game from the impact directory-->
    <target name="post-build-cleanup">
        <delete file="${impact.dir}/game.min.js"/>
    </target>

    <!-- Run the bake script - you need PHP to be runnable from the command line. -->
    <target name="bake">

        <exec dir="${impact.dir}" executable="php">
            <arg value="${impact.dir}/tools/bake.php"/>
            <arg value="lib/impact/impact.js"/>
            <arg value="lib/game/main.js"/>
            <arg value="game.min.js"/>
        </exec>

    </target>

    <target name="web-build">
        <!-- Copy over the impact directory to the deploy folder and ignore what is not needed. -->
        <sync todir="${web.dir}">
            <fileset dir="${impact.dir}">
                <exclude name="weltmeister.html"/>
                <exclude name="**/tools/*"/>
                <exclude name="**/lib/**"/>
            </fileset>
        </sync>

        <!-- replace js source paths in HTML with minified game js. Make sure code is surrounded by "source script" comments so the regex can find it. -->
        <replaceregexp file="${web.dir}/index.html"
                       match="\<!--source scripts--\>(.*?)\<!--end source scripts--\>"
                       replace="\<script src='game.min.js'\>\</script\>" flags="gs">
        </replaceregexp>
        <!-- This will copy over debug CSS if game is running in debug mode. -->

        <copy file="${impact.dir}/lib/impact/debug/debug.css"
              tofile="${web.dir}/lib/impact/debug/debug.css"/>
    </target>

    <target name="ios-build">
        <!-- copy over files for iOS -->
        <sync todir="${ios.dir}">
            <fileset dir="${web.dir}">

            </fileset>
        </sync>
    </target>

    <target name="win8-build">
        <!-- copy over files for Win8 -->
        <sync todir="${win8.dir}">
            <fileset dir="${web.dir}">

            </fileset>
        </sync>
    </target>

    <target name="chrome-build">

        <!-- Create chrome market app -->
        <sync todir="${chrome.dir}/tmp">
            <fileset dir="${web.dir}">

            </fileset>
        </sync>

        <echo file="${chrome.dir}/tmp/manifest.json" append="false">
            {
            "name": "${project.name}",
            "description": "${project.description}",
            "version": "${project.version}",
            "icons": {
            "16": "images/icons/icon-16x16.png",
            "48": "images/icons/icon-48x48.png",
            "128": "images/icons/icon-128x128.png"
            },
            "app": {"launch": {
            "local_path": "index.html"
            }},
            "homepage_url": "${project.url}"
            }
        </echo>

        <zip destfile="${chrome.dir}/${project.name}-${project.version}.zip" basedir="${chrome.dir}"/>
        <delete dir="${chrome.dir}/tmp/"/>
    </target>

    <target name="mozilla-build">
        <!-- Create Mozilla App -->
        <sync todir="${mozilla.dir}">
            <fileset dir="${web.dir}">

            </fileset>
        </sync>

        <echo file="${mozilla.dir}/manifest.json" append="false">
            {
            "name":"${project.name}",
            "developer": {
            "name":"${company.name}",
            "url":"${company.site}"
            },
            "description":"${project.description}",
            "icons":{
            "16": "/images/icons/icon-16x16.png",
            "48": "/images/icons/icon-48x48.png",
            "128": "/images/icons/icon-128x128.png"
            }
            }
        </echo>
    </target>

</project>


text:
extern crate getopts;
extern crate time;
extern crate regex;
extern crate rustc_serialize;

use getopts::Options;

use std::env;
use std::io::Write;
use std::fs;

#[macro_use]
mod utils;
mod lib;

const VERSION: &'static str = "0.1.1";

fn print_version() {
	println!("Using version {}", VERSION);
}

fn print_usage(program: &str, opts: Options) {
    let brief = format!("Usage: {} FILE [options]", program);
    print!("{}", opts.usage(&brief));
}

fn main() {
	let args: Vec<String> = env::args().collect();
    let program = args[0].clone();

    let mut opts = Options::new();
    opts.optopt("o", "", "set output file name", "FILE");
    opts.optflag("h", "help", "print this help menu");
	opts.optflag("v", "version", "print the version and exit");

    let matches = match opts.parse(&args[1..]) {
        Ok(m) => m,
        Err(f) => panic!(f.to_string()),
    };
    if matches.opt_present("h") {
        print_usage(&program, opts);
        return;
    }
	if matches.opt_present("v") {
		print_version();
		return;
	}
    let output = matches.opt_str("o");
    let input = if !matches.free.is_empty() {
        matches.free[0].clone()
    } else {
        print_usage(&program, opts);
        return;
    };

    {
        let start = time::now();
        lib::preprocess(&input).ok();
        printerrln!("It took {} milliseconds for the preprocess to run", (time::now() - start).num_milliseconds()).unwrap();
    }
    {
        let start = time::now();
        lib::analyse("tmp", output).ok();
        fs::remove_file("tmp").ok();
        printerrln!("It took {} milliseconds for the analysis to run", (time::now() - start).num_milliseconds()).unwrap();
    }
}


text:
//
//  WSQueryFormat.m
//  HMHealth
//
//  Created by 李林刚 on 2016/12/6.
//  Copyright © 2016年 HM iOS. All rights reserved.
//

/**
 @see more AFURLRequestSerialization
 */

#import "WSQueryFormat.h"
#import <AFNetworking/AFURLRequestSerialization.h>

@interface HMQueryStringPair : NSObject

@property (readwrite, nonatomic, strong) id field;
@property (readwrite, nonatomic, strong) id value;

- (instancetype)initWithField:(id)field value:(id)value;

@end

@implementation HMQueryStringPair

- (instancetype)initWithField:(id)field value:(id)value {
    self = [super init];
    if (!self) {
        return nil;
    }
    self.field = field;
    self.value = value;
    return self;
}

- (NSString *)URLEncodedStringValue {
    if (!self.value || [self.value isEqual:[NSNull null]]) {
        return AFPercentEscapedStringFromString([self.field description]);
    } else {
        return [NSString stringWithFormat:@"%@=%@", AFPercentEscapedStringFromString([self.field description]), AFPercentEscapedStringFromString([self.value description])];
    }
}

@end

@implementation WSQueryFormat

+ (NSString *)queryStringFromParameters:(NSDictionary *)parameters{
    NSMutableArray *mutablePairs = [NSMutableArray array];
    NSArray <HMQueryStringPair *> *queryStringPairs = [self queryStringPairsWithKey:nil value:parameters];
    for (HMQueryStringPair *pair in queryStringPairs) {
        [mutablePairs addObject:[pair URLEncodedStringValue]];
    }
    return [mutablePairs componentsJoinedByString:@"&"];
}

#pragma mark -  Private Methods

+ (NSArray *)queryStringPairsWithKey:(NSString *)key value:(id)value{
    NSMutableArray *mutableQueryStringComponents = [NSMutableArray array];

    NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"description" ascending:YES selector:@selector(compare:)];

    if ([value isKindOfClass:[NSDictionary class]]) {
        NSDictionary *dictionary = value;
        // Sort dictionary keys to ensure consistent ordering in query string, which is important when deserializing potentially ambiguous sequences, such as an array of dictionaries
        for (id nestedKey in [dictionary.allKeys sortedArrayUsingDescriptors:@[ sortDescriptor ]]) {
            id nestedValue = dictionary[nestedKey];
            if (nestedValue) {
                [mutableQueryStringComponents addObjectsFromArray:[self queryStringPairsWithKey:(key ? [NSString stringWithFormat:@"%@[%@]", key, nestedKey] : nestedKey) value:nestedValue]];
            }
        }
    } else if ([value isKindOfClass:[NSArray class]]) {
        NSArray *array = value;
        for (id nestedValue in array) {
            //去掉key后面的[]
            [mutableQueryStringComponents addObjectsFromArray:[self queryStringPairsWithKey:[NSString stringWithFormat:@"%@", key] value:nestedValue]];
        }
    } else if ([value isKindOfClass:[NSSet class]]) {
        NSSet *set = value;
        for (id obj in [set sortedArrayUsingDescriptors:@[ sortDescriptor ]]) {
            [mutableQueryStringComponents addObjectsFromArray:[self queryStringPairsWithKey:key value:obj]];
        }
    } else {
        [mutableQueryStringComponents addObject:[[HMQueryStringPair alloc] initWithField:key value:value]];
    }
    return mutableQueryStringComponents;
}
@end


text:
module Intrigue
class SearchCorpwatchTask < BaseTask

  def metadata
    {
      :name => "search_edgar",
      :pretty_name => "Search EDGAR",
      :authors => ["jcran"],
      :description => "EDGAR Corporation Search",
      :references => [],
      :allowed_types => ["String", "Organization"],
      :example_entities => [{:type => "String", :attributes => {:name => "intrigue"}}],
      :allowed_options => [],
      :created_types => ["*"]
    }
  end

  ## Default method, subclasses must override this
  def run
    super

    # Get the API Key
    api_key = _get_global_config "corpwatch_api_key"

    # Attach to the corpwatch service & search
    x = Client::Search::Corpwatch::ApiClient.new(api_key)
    corps = x.search(_get_entity_attribute "name")

    corps.each do |corp|

      # Create a new organization entity & attach a record
      _create_entity "Organization", {
        :name => corp.name,
        :data => corp.to_s
      }

      _create_entity "PhysicalLocation", {
        :name => corp.address,
        :address => corp.address,
        :state => corp.state,
        :country => corp.country
      }

    end
  end
end
end


text:
package org.apache.drill;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.Semaphore;

import org.apache.drill.QueryTestUtil;
import org.apache.drill.common.exceptions.UserException;
import org.apache.drill.common.util.TestTools;
import org.apache.drill.exec.proto.UserBitShared;
import org.apache.drill.exec.proto.UserBitShared.QueryResult.QueryState;
import org.apache.drill.exec.rpc.user.UserResultsListener;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestRule;

import com.google.common.collect.Sets;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;

/*
 * Note that the real interest here is that the drillbit doesn't become
 * unstable from running a lot of queries concurrently -- it's not about
 * any particular order of execution. We ignore the results.
 */
public class TestTpchDistributedConcurrent extends BaseTestQuery {
  @Rule public final TestRule TIMEOUT = TestTools.getTimeoutRule(120000); // Longer timeout than usual.

  /*
   * Valid test names taken from TestTpchDistributed. Fuller path prefixes are
   * used so that tests may also be taken from other locations -- more variety
   * is better as far as this test goes.
   */
  private final static String queryFile[] = {
    "queries/tpch/01.sql",
    "queries/tpch/03.sql",
    "queries/tpch/04.sql",
    "queries/tpch/05.sql",
    "queries/tpch/06.sql",
    "queries/tpch/07.sql",
    "queries/tpch/08.sql",
    "queries/tpch/09.sql",
    "queries/tpch/10.sql",
    "queries/tpch/11.sql",
    "queries/tpch/12.sql",
    "queries/tpch/13.sql",
    "queries/tpch/14.sql",
    // "queries/tpch/15.sql", this creates a view
    "queries/tpch/16.sql",
    "queries/tpch/18.sql",
    "queries/tpch/19_1.sql",
    "queries/tpch/20.sql",
  };

  private final static int TOTAL_QUERIES = 115;
  private final static int CONCURRENT_QUERIES = 15;

  private final static Random random = new Random(0xdeadbeef);
  private final static String alterSession = "alter session set `planner.slice_target` = 10";

  private int remainingQueries = TOTAL_QUERIES - CONCURRENT_QUERIES;
  private final Semaphore completionSemaphore = new Semaphore(0);
  private final Semaphore submissionSemaphore = new Semaphore(0);
  private final Set<UserResultsListener> listeners = Sets.newIdentityHashSet();
  private Thread testThread = null; // used to interrupt semaphore wait in case of error

  private static class FailedQuery {
    final String queryFile;
    final UserException userEx;

    public FailedQuery(final String queryFile, final UserException userEx) {
      this.queryFile = queryFile;
      this.userEx = userEx;
    }
  }

  private final List<FailedQuery> failedQueries = new LinkedList<>();

  private void submitRandomQuery() {
    final String filename = queryFile[random.nextInt(queryFile.length)];
    final String query;
    try {
      query = QueryTestUtil.normalizeQuery(getFile(filename)).replace(';', ' ');
    } catch(IOException e) {
      throw new RuntimeException("Caught exception", e);
    }
    final UserResultsListener listener = new ChainingSilentListener(query);
    client.runQuery(UserBitShared.QueryType.SQL, query, listener);
    synchronized(this) {
      listeners.add(listener);
    }
  }

  private class ChainingSilentListener extends SilentListener {
    private final String query;

    public ChainingSilentListener(final String query) {
      this.query = query;
    }

    @Override
    public void queryCompleted(QueryState state) {
      super.queryCompleted(state);

      completionSemaphore.release();
      synchronized(TestTpchDistributedConcurrent.this) {
        final Object object = listeners.remove(this);
        assertNotNull("listener not found", object);

        /* Only submit more queries if there hasn't been an error. */
        if ((failedQueries.size() == 0) && (remainingQueries > 0)) {
          /*
           * We can't directly submit the query from here, because we're on the RPC
           * thread, and it throws an exception if we try to send from here. So we
           * allow the QuerySubmitter thread to advance.
           */
          submissionSemaphore.release();
          --remainingQueries;
        }
      }
    }

    @Override
    public void submissionFailed(UserException uex) {
      super.submissionFailed(uex);

      completionSemaphore.release();
      System.out.println("submissionFailed for " + query + "\nwith " + uex);
      synchronized(TestTpchDistributedConcurrent.this) {
        final Object object = listeners.remove(this);
        assertNotNull("listener not found", object);
        failedQueries.add(new FailedQuery(query, uex));
        testThread.interrupt();
      }
    }
  }

  private class QuerySubmitter extends Thread {
    @Override
    public void run() {
      while(true) {
        try {
          submissionSemaphore.acquire();
        } catch(InterruptedException e) {
          System.out.println("QuerySubmitter quitting.");
          return;
        }

        submitRandomQuery();
      }
    }
  }

  @Test
  public void testConcurrentQueries() throws Exception {
    QueryTestUtil.testRunAndPrint(client, UserBitShared.QueryType.SQL, alterSession);

    testThread = Thread.currentThread();
    final QuerySubmitter querySubmitter = new QuerySubmitter();
    querySubmitter.start();

    // Kick off the initial queries. As they complete, they will submit more.
    submissionSemaphore.release(CONCURRENT_QUERIES);

    // Wait for all the queries to complete.
    InterruptedException interruptedException = null;
    try {
      completionSemaphore.acquire(TOTAL_QUERIES);
    } catch(InterruptedException e) {
      interruptedException = e;

      // List the failed queries.
      for(final FailedQuery fq : failedQueries) {
        System.err.println(String.format(
            "%s failed with %s", fq.queryFile, fq.userEx));
      }
    }

    // Stop the querySubmitter thread.
    querySubmitter.interrupt();

    assertNull("Query error caused interruption", interruptedException);

    final int nListeners = listeners.size();
    assertEquals(nListeners + " listeners still exist", 0, nListeners);

    assertEquals("Didn't submit all queries", 0, remainingQueries);
    assertEquals("Queries failed", 0, failedQueries.size());
  }
}


text: <!-- Other partial -->


text:
    <form ng-submit="register(registrationForm)" role="form" ng-init="registrationForm = {}">

            email
            <input type="email" name="email" ng-model="registrationForm.email" required="required" class="form-control"/>

            password
            <input type="password" name="password" ng-model="registrationForm.password" required="required" class="form-control"/>

            password confirmation
            <input type="password" name="password_confirmation" ng-model="registrationForm.password_confirmation" required="required" class="form-control"/>

        <button type="submit" class="btn btn-primary btn-lg">Register</button>
    </form>


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace CollectionUpdateSample {

    public partial class _Default {

        /// <summary>
        /// SampleMultiView control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.MultiView SampleMultiView;

        /// <summary>
        /// AuthView control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.View AuthView;

        /// <summary>
        /// ClientIdTxt control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.TextBox ClientIdTxt;

        /// <summary>
        /// ClientSecretTxt control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.TextBox ClientSecretTxt;

        /// <summary>
        /// ContinueButton control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Button ContinueButton;

        /// <summary>
        /// SearchCollectionsView control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.View SearchCollectionsView;

        /// <summary>
        /// GoToChangeExtRefButton control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Button GoToChangeExtRefButton;

        /// <summary>
        /// GoToCancelCollectionButton control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Button GoToCancelCollectionButton;

        /// <summary>
        /// CollectionsGridView control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.GridView CollectionsGridView;

        /// <summary>
        /// PagerPanel control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Panel PagerPanel;

        /// <summary>
        /// PagerFrom control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label PagerFrom;

        /// <summary>
        /// PagerTo control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label PagerTo;

        /// <summary>
        /// PagerTotal control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label PagerTotal;

        /// <summary>
        /// FirstPageButton control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Button FirstPageButton;

        /// <summary>
        /// PageDownButton control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Button PageDownButton;

        /// <summary>
        /// PageUpButton control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Button PageUpButton;

        /// <summary>
        /// LastPageButton control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Button LastPageButton;

        /// <summary>
        /// RefreshPageButton control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Button RefreshPageButton;

        /// <summary>
        /// ChangeExtRefView control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.View ChangeExtRefView;

        /// <summary>
        /// ColIdChangeExtRefText control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.TextBox ColIdChangeExtRefText;

        /// <summary>
        /// NewExternalReferenceText control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.TextBox NewExternalReferenceText;

        /// <summary>
        /// Button1 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Button Button1;

        /// <summary>
        /// ChangeExternalReferenceResult control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label ChangeExternalReferenceResult;

        /// <summary>
        /// ReturnButton1 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Button ReturnButton1;

        /// <summary>
        /// CancelCollectionView control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.View CancelCollectionView;

        /// <summary>
        /// ColIdCancelColText control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.TextBox ColIdCancelColText;

        /// <summary>
        /// CancelCollectionButton control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Button CancelCollectionButton;

        /// <summary>
        /// CancelCollectionResult control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label CancelCollectionResult;

        /// <summary>
        /// ReturnButton2 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Button ReturnButton2;
    }
}


text:
using rainbow::Data;
using rainbow::File;
using rainbow::FileType;
using rainbow::Image;
using rainbow::Passkey;
using rainbow::graphics::Filter;
using rainbow::graphics::ITextureAllocator;
using rainbow::graphics::Texture;
using rainbow::graphics::TextureData;
using rainbow::graphics::TextureProvider;

TextureProvider::TextureProvider(ITextureAllocator& allocator)
    : allocator_(allocator)
{
    R_ASSERT(Texture::s_texture_provider == nullptr,  //
             "An instance already exists");

    Texture::s_texture_provider = this;
}

TextureProvider::~TextureProvider()
{
    R_ASSERT(Texture::s_texture_provider == this, "This shouldn't happen.");

    Texture::s_texture_provider = nullptr;

    for (auto&& texture : texture_map_)
        allocator_.destroy(texture.second.data);
}

template <typename T>
auto TextureProvider::get(std::string_view path,
                          [[maybe_unused]] T data,
                          [[maybe_unused]] float scale,
                          Filter mag_filter,
                          Filter min_filter) -> Texture
{
    auto [iter, inserted] = texture_map_.emplace(path, TextureData{});
    if (inserted)
    {
        if constexpr (std::is_same_v<T, std::nullptr_t>)
        {
            auto file = File::read(path.data(), FileType::Asset);
            load(iter, Image::decode(file, scale), mag_filter, min_filter);
        }
        else if constexpr (std::is_same_v<T, const Data&>)
        {
            load(iter, Image::decode(data, scale), mag_filter, min_filter);
        }
        else if constexpr (std::is_same_v<T, const Image&>)
        {
            load(iter, data, mag_filter, min_filter);
        }
    }
    ++iter->second.use_count;
    return Texture{path, Passkey<TextureProvider>{}};
}

auto TextureProvider::get(std::string_view path,
                          float scale,
                          Filter mag_filter,
                          Filter min_filter) -> Texture
{
    return get(path, nullptr, scale, mag_filter, min_filter);
}

auto TextureProvider::get(std::string_view path,
                          const Data& data,
                          float scale,
                          Filter mag_filter,
                          Filter min_filter) -> Texture
{
    return get<const Data&>(path, data, scale, mag_filter, min_filter);
}

auto TextureProvider::get(std::string_view path,
                          const Image& image,
                          Filter mag_filter,
                          Filter min_filter) -> Texture
{
    return get<const Image&>(path, image, 1.0F, mag_filter, min_filter);
}

auto TextureProvider::raw_get(const Texture& texture) const -> TextureData
{
    auto iter = texture_map_.find(texture.key());
    return iter->second;
}

void TextureProvider::release(const Texture& texture)
{
    auto iter = texture_map_.find(texture.key());
    if (iter == texture_map_.end())
        return;

    auto& texture_data = iter->second;
    if (--texture_data.use_count == 0)
    {
        IF_DEVMODE(mem_used_ -= texture_data.size);
        allocator_.destroy(texture_data.data);
        texture_map_.erase(iter);
    }
}

auto TextureProvider::try_get(const Texture& texture)
    -> std::optional<TextureData>
{
    auto iter = texture_map_.find(texture.key());
    if (iter == texture_map_.end())
        return std::nullopt;

    ++iter->second.use_count;
    return std::make_optional(iter->second);
}

void TextureProvider::update(const Texture& texture,
                             const Image& image,
                             Filter mag_filter,
                             Filter min_filter)
{
    allocator_.update(raw_get(texture).data, image, mag_filter, min_filter);
}

void TextureProvider::load(TextureMap::iterator i,
                           const Image& image,
                           Filter mag_filter,
                           Filter min_filter)
{
    R_ASSERT(allocator_.max_size() <= sizeof(TextureData::data),
             "Texture data size is too small for the current graphics API.");

    auto& texture = i->second;
    allocator_.construct(texture.data, image, mag_filter, min_filter);
    texture.width = image.width;
    texture.height = image.height;

    IF_DEVMODE(texture.size = image.size);
    IF_DEVMODE(record_usage(image.size));
}

TextureProvider* Texture::s_texture_provider = nullptr;

Texture::~Texture()
{
    if (key_.empty())
        return;

    s_texture_provider->release(*this);
}

auto Texture::operator=(const Texture& texture) -> Texture&
{
    if (&texture == this)
        return *this;

    if (!key_.empty())
        s_texture_provider->release(*this);

    auto handle = s_texture_provider->get(texture.key());
    key_ = std::move(handle.key_);
    return *this;
}

auto Texture::operator=(Texture&& texture) noexcept -> Texture&
{
    if (!key_.empty())
        s_texture_provider->release(*this);

    key_ = std::move(texture.key_);
    return *this;
}


text:
Vixen JS JSONP Library <https://jdrich@github.com/jdrich/vixen_js.git>

## About

The Vixen JS JSONP Library is an open source (MIT licensed) library for use in
applications which require poll and signal type functionality within JavaScript
applications. The library is simple, short, and concise, and aims to stay that
way.

## Uses

Polling

    // The URL we want to poll
    var polled_location = 'poll_location.php';

    // The JSONP callback
    var poll_callback = function (data) {
        console.log(data);
    }

    // How often to poll the resource
    var interval = 500;

    Vixen.init(polled_location, poll_callback, interval);

Clearing

    Vixen.destroy(polled_location);

Signalling

    // The URL we want to signal
    var signalled_location = 'signal_location.php';

    // The message we want to send
    var message = JSON.stringify('example');

    Vixen.signal(signalled_location, message);

## Purpose

Vixen is a small library that duplicates JSONP functionality in a minimal way.
Its purpose is to facilitate the implementation of JSONP APIs. The purpose of
Vixen is not to replace Ajax calls, and it should not be abused for that purpose.

## Author

Jonathan Rich <jdrich@gmail.com>

## Feedback

Submit bugs to https://github.com/jdrich/vixen_js/issues.

## License

Please see the file called LICENSE.