text:
namespace local_discovery {

namespace {

const char kDictionaryKeyServiceName[] = "service_name";
const char kDictionaryKeyDisplayName[] = "display_name";
const char kDictionaryKeyDescription[] = "description";
const char kDictionaryKeyType[] = "type";
const char kDictionaryKeyIsWifi[] = "is_wifi";
const char kDictionaryKeyID[] = "id";

const char kKeyPrefixMDns[] = "MDns:";

#if defined(ENABLE_WIFI_BOOTSTRAPPING)
const char kKeyPrefixWifi[] = "WiFi:";
#endif  // ENABLE_WIFI_BOOTSTRAPPING

int g_num_visible = 0;

const int kCloudDevicesPrivetVersion = 3;

scoped_ptr<base::DictionaryValue> CreateDeviceInfo(
    const CloudDeviceListDelegate::Device& description) {
  scoped_ptr<base::DictionaryValue> return_value(new base::DictionaryValue);

  return_value->SetString(kDictionaryKeyID, description.id);
  return_value->SetString(kDictionaryKeyDisplayName, description.display_name);
  return_value->SetString(kDictionaryKeyDescription, description.description);
  return_value->SetString(kDictionaryKeyType, description.type);

  return return_value.Pass();
}

void ReadDevicesList(
    const std::vector<CloudDeviceListDelegate::Device>& devices,
    const std::set<std::string>& local_ids,
    base::ListValue* devices_list) {
  for (CloudDeviceList::iterator i = devices.begin(); i != devices.end(); i++) {
    if (local_ids.count(i->id) > 0) {
      devices_list->Append(CreateDeviceInfo(*i).release());
    }
  }

  for (CloudDeviceList::iterator i = devices.begin(); i != devices.end(); i++) {
    if (local_ids.count(i->id) == 0) {
      devices_list->Append(CreateDeviceInfo(*i).release());
    }
  }
}

}  // namespace

LocalDiscoveryUIHandler::LocalDiscoveryUIHandler()
    : is_visible_(false),
      failed_list_count_(0),
      succeded_list_count_(0) {
#if defined(CLOUD_PRINT_CONNECTOR_UI_AVAILABLE)
#if !defined(GOOGLE_CHROME_BUILD) && defined(OS_WIN)
  // On Windows, we need the PDF plugin which is only guaranteed to exist on
  // Google Chrome builds. Use a command-line switch for Windows non-Google
  //  Chrome builds.
  cloud_print_connector_ui_enabled_ =
      CommandLine::ForCurrentProcess()->HasSwitch(
      switches::kEnableCloudPrintProxy);
#else
  // Always enabled for Linux and Google Chrome Windows builds.
  // Never enabled for Chrome OS, we don't even need to indicate it.
  cloud_print_connector_ui_enabled_ = true;
#endif
#endif  // defined(CLOUD_PRINT_CONNECTOR_UI_AVAILABLE)
}

LocalDiscoveryUIHandler::~LocalDiscoveryUIHandler() {
  Profile* profile = Profile::FromWebUI(web_ui());
  SigninManagerBase* signin_manager =
      SigninManagerFactory::GetInstance()->GetForProfile(profile);
  if (signin_manager)
    signin_manager->RemoveObserver(this);
  ResetCurrentRegistration();
  SetIsVisible(false);
}

// static
bool LocalDiscoveryUIHandler::GetHasVisible() {
  return g_num_visible != 0;
}

void LocalDiscoveryUIHandler::RegisterMessages() {
  web_ui()->RegisterMessageCallback("start", base::Bind(
      &LocalDiscoveryUIHandler::HandleStart,
      base::Unretained(this)));
  web_ui()->RegisterMessageCallback("isVisible", base::Bind(
      &LocalDiscoveryUIHandler::HandleIsVisible,
      base::Unretained(this)));
  web_ui()->RegisterMessageCallback("registerDevice", base::Bind(
      &LocalDiscoveryUIHandler::HandleRegisterDevice,
      base::Unretained(this)));
  web_ui()->RegisterMessageCallback(
      "confirmCode",
      base::Bind(&LocalDiscoveryUIHandler::HandleConfirmCode,
                 base::Unretained(this)));
  web_ui()->RegisterMessageCallback("cancelRegistration", base::Bind(
      &LocalDiscoveryUIHandler::HandleCancelRegistration,
      base::Unretained(this)));
  web_ui()->RegisterMessageCallback(
      "requestDeviceList",
      base::Bind(&LocalDiscoveryUIHandler::HandleRequestDeviceList,
                 base::Unretained(this)));
  web_ui()->RegisterMessageCallback("openCloudPrintURL", base::Bind(
      &LocalDiscoveryUIHandler::HandleOpenCloudPrintURL,
      base::Unretained(this)));
  web_ui()->RegisterMessageCallback("showSyncUI", base::Bind(
      &LocalDiscoveryUIHandler::HandleShowSyncUI,
      base::Unretained(this)));

  // Cloud print connector related messages
#if defined(CLOUD_PRINT_CONNECTOR_UI_AVAILABLE)
  if (cloud_print_connector_ui_enabled_) {
    web_ui()->RegisterMessageCallback(
        "showCloudPrintSetupDialog",
        base::Bind(&LocalDiscoveryUIHandler::ShowCloudPrintSetupDialog,
                   base::Unretained(this)));
    web_ui()->RegisterMessageCallback(
        "disableCloudPrintConnector",
        base::Bind(&LocalDiscoveryUIHandler::HandleDisableCloudPrintConnector,
                   base::Unretained(this)));
  }
#endif  // defined(CLOUD_PRINT_CONNECTOR_UI_AVAILABLE)
}

void LocalDiscoveryUIHandler::HandleStart(const base::ListValue* args) {
  Profile* profile = Profile::FromWebUI(web_ui());

  // If privet_lister_ is already set, it is a mock used for tests or the result
  // of a reload.
  if (!privet_lister_) {
    service_discovery_client_ = ServiceDiscoverySharedClient::GetInstance();
    privet_lister_.reset(
        new PrivetDeviceListerImpl(service_discovery_client_.get(), this));
    privet_http_factory_ = PrivetHTTPAsynchronousFactory::CreateInstance(
        service_discovery_client_.get(), profile->GetRequestContext());

    SigninManagerBase* signin_manager =
        SigninManagerFactory::GetInstance()->GetForProfile(profile);
    if (signin_manager)
      signin_manager->AddObserver(this);
  }

  privet_lister_->Start();
  privet_lister_->DiscoverNewDevices(false);

#if defined(CLOUD_PRINT_CONNECTOR_UI_AVAILABLE)
  StartCloudPrintConnector();
#endif

#if defined(ENABLE_WIFI_BOOTSTRAPPING)
  if (CommandLine::ForCurrentProcess()->HasSwitch(
          switches::kEnableCloudDevices)) {
    StartWifiBootstrapping();
  }
#endif

  CheckUserLoggedIn();
}

void LocalDiscoveryUIHandler::HandleIsVisible(const base::ListValue* args) {
  bool is_visible = false;
  bool rv = args->GetBoolean(0, &is_visible);
  DCHECK(rv);
  SetIsVisible(is_visible);
}

void LocalDiscoveryUIHandler::HandleRegisterDevice(
    const base::ListValue* args) {
  std::string device;

  bool rv = args->GetString(0, &device);
  DCHECK(rv);

  DeviceDescriptionMap::iterator found = device_descriptions_.find(device);
  if (found == device_descriptions_.end()) {
    OnSetupError();
    return;
  }

  if (found->second.version == kCloudDevicesPrivetVersion) {
    current_setup_operation_.reset(new PrivetV3SetupFlow(this));
    current_setup_operation_->Register(device);
  } else if (found->second.version <= 2) {
    privet_resolution_ = privet_http_factory_->CreatePrivetHTTP(
        device,
        found->second.address,
        base::Bind(&LocalDiscoveryUIHandler::StartRegisterHTTP,
                   base::Unretained(this)));
    privet_resolution_->Start();
  } else {
    OnSetupError();
  }
}

void LocalDiscoveryUIHandler::HandleConfirmCode(const base::ListValue* args) {
  device_code_callback_.Run(true);
}

void LocalDiscoveryUIHandler::HandleCancelRegistration(
    const base::ListValue* args) {
  ResetCurrentRegistration();
}

void LocalDiscoveryUIHandler::HandleRequestDeviceList(
    const base::ListValue* args) {
  failed_list_count_ = 0;
  succeded_list_count_ = 0;
  cloud_devices_.clear();

  cloud_print_printer_list_ = CreateApiFlow();
  if (CommandLine::ForCurrentProcess()->HasSwitch(
      switches::kEnableCloudDevices)) {
    cloud_device_list_ = CreateApiFlow();
  }

  if (cloud_print_printer_list_) {
    cloud_print_printer_list_->Start(
        make_scoped_ptr<GCDApiFlow::Request>(new CloudPrintPrinterList(this)));
  }
  if (cloud_device_list_) {
    cloud_device_list_->Start(
        make_scoped_ptr<GCDApiFlow::Request>(new CloudDeviceList(this)));
  }
  CheckListingDone();
}

void LocalDiscoveryUIHandler::HandleOpenCloudPrintURL(
    const base::ListValue* args) {
  std::string id;
  bool rv = args->GetString(0, &id);
  DCHECK(rv);

  Browser* browser = chrome::FindBrowserWithWebContents(
      web_ui()->GetWebContents());
  DCHECK(browser);

  chrome::AddSelectedTabWithURL(browser,
                                cloud_devices::GetCloudPrintManageDeviceURL(id),
                                content::PAGE_TRANSITION_FROM_API);
}

void LocalDiscoveryUIHandler::HandleShowSyncUI(
    const base::ListValue* args) {
  Browser* browser = chrome::FindBrowserWithWebContents(
      web_ui()->GetWebContents());
  DCHECK(browser);

  GURL url(signin::GetPromoURL(signin::SOURCE_DEVICES_PAGE,
                               true));  // auto close after success.

  browser->OpenURL(
      content::OpenURLParams(url, content::Referrer(), SINGLETON_TAB,
                             content::PAGE_TRANSITION_AUTO_BOOKMARK, false));
}

void LocalDiscoveryUIHandler::StartRegisterHTTP(
    scoped_ptr<PrivetHTTPClient> http_client) {
  current_http_client_ = PrivetV1HTTPClient::CreateDefault(http_client.Pass());

  std::string user = GetSyncAccount();

  if (!current_http_client_) {
    SendRegisterError();
    return;
  }

  current_register_operation_ =
      current_http_client_->CreateRegisterOperation(user, this);
  current_register_operation_->Start();
}

void LocalDiscoveryUIHandler::OnPrivetRegisterClaimToken(
    PrivetRegisterOperation* operation,
    const std::string& token,
    const GURL& url) {
  web_ui()->CallJavascriptFunction(
      "local_discovery.onRegistrationConfirmedOnPrinter");
  if (device_descriptions_.count(current_http_client_->GetName()) == 0) {
    SendRegisterError();
    return;
  }

  confirm_api_call_flow_ = CreateApiFlow();
  if (!confirm_api_call_flow_) {
    SendRegisterError();
    return;
  }
  confirm_api_call_flow_->Start(
      make_scoped_ptr<GCDApiFlow::Request>(new PrivetConfirmApiCallFlow(
          token,
          base::Bind(&LocalDiscoveryUIHandler::OnConfirmDone,
                     base::Unretained(this)))));
}

void LocalDiscoveryUIHandler::OnPrivetRegisterError(
    PrivetRegisterOperation* operation,
    const std::string& action,
    PrivetRegisterOperation::FailureReason reason,
    int printer_http_code,
    const base::DictionaryValue* json) {
  std::string error;

  if (reason == PrivetRegisterOperation::FAILURE_JSON_ERROR &&
      json->GetString(kPrivetKeyError, &error)) {
    if (error == kPrivetErrorTimeout) {
        web_ui()->CallJavascriptFunction(
            "local_discovery.onRegistrationTimeout");
      return;
    } else if (error == kPrivetErrorCancel) {
      web_ui()->CallJavascriptFunction(
            "local_discovery.onRegistrationCanceledPrinter");
      return;
    }
  }

  SendRegisterError();
}

void LocalDiscoveryUIHandler::OnPrivetRegisterDone(
    PrivetRegisterOperation* operation,
    const std::string& device_id) {
  std::string name = operation->GetHTTPClient()->GetName();
  current_setup_operation_.reset();
  current_register_operation_.reset();
  current_http_client_.reset();
  SendRegisterDone(name);
}

void LocalDiscoveryUIHandler::GetWiFiCredentials(
    const CredentialsCallback& callback) {
  callback.Run("", "");
}

void LocalDiscoveryUIHandler::SwitchToSetupWiFi(
    const ResultCallback& callback) {
  callback.Run(true);
}

void LocalDiscoveryUIHandler::ConfirmSecurityCode(
    const std::string& confirmation_code,
    const ResultCallback& callback) {
  device_code_callback_ = callback;
  web_ui()->CallJavascriptFunction(
      "local_discovery.onRegistrationConfirmDeviceCode",
      base::StringValue(confirmation_code));
}

void LocalDiscoveryUIHandler::RestoreWifi(const ResultCallback& callback) {
  callback.Run(true);
}

void LocalDiscoveryUIHandler::OnSetupDone() {
  std::string service_name = current_setup_operation_->service_name();
  current_setup_operation_.reset();
  current_register_operation_.reset();
  current_http_client_.reset();
  SendRegisterDone(service_name);
}

void LocalDiscoveryUIHandler::OnSetupError() {
  ResetCurrentRegistration();
  SendRegisterError();
}

void LocalDiscoveryUIHandler::OnConfirmDone(GCDApiFlow::Status status) {
  if (status == GCDApiFlow::SUCCESS) {
    confirm_api_call_flow_.reset();
    current_register_operation_->CompleteRegistration();
  } else {
    SendRegisterError();
  }
}

void LocalDiscoveryUIHandler::DeviceChanged(
    bool added,
    const std::string& name,
    const DeviceDescription& description) {
  device_descriptions_[name] = description;

  base::DictionaryValue info;

  base::StringValue service_key(kKeyPrefixMDns + name);

  if (description.id.empty()) {
    info.SetString(kDictionaryKeyServiceName, name);
    info.SetString(kDictionaryKeyDisplayName, description.name);
    info.SetString(kDictionaryKeyDescription, description.description);
    info.SetString(kDictionaryKeyType, description.type);
    info.SetBoolean(kDictionaryKeyIsWifi, false);

    web_ui()->CallJavascriptFunction(
        "local_discovery.onUnregisteredDeviceUpdate", service_key, info);
  } else {
    scoped_ptr<base::Value> null_value(base::Value::CreateNullValue());

    web_ui()->CallJavascriptFunction(
        "local_discovery.onUnregisteredDeviceUpdate", service_key, *null_value);
  }
}

void LocalDiscoveryUIHandler::DeviceRemoved(const std::string& name) {
  device_descriptions_.erase(name);
  scoped_ptr<base::Value> null_value(base::Value::CreateNullValue());
  base::StringValue name_value(kKeyPrefixMDns + name);

  web_ui()->CallJavascriptFunction("local_discovery.onUnregisteredDeviceUpdate",
                                   name_value, *null_value);
}

void LocalDiscoveryUIHandler::DeviceCacheFlushed() {
  web_ui()->CallJavascriptFunction("local_discovery.onDeviceCacheFlushed");
  privet_lister_->DiscoverNewDevices(false);
}

void LocalDiscoveryUIHandler::OnDeviceListReady(
    const std::vector<Device>& devices) {
  cloud_devices_.insert(cloud_devices_.end(), devices.begin(), devices.end());
  ++succeded_list_count_;
  CheckListingDone();
}

void LocalDiscoveryUIHandler::OnDeviceListUnavailable() {
  ++failed_list_count_;
  CheckListingDone();
}

void LocalDiscoveryUIHandler::GoogleSigninSucceeded(
    const std::string& username,
    const std::string& password) {
  CheckUserLoggedIn();
}

void LocalDiscoveryUIHandler::GoogleSignedOut(const std::string& username) {
  CheckUserLoggedIn();
}

void LocalDiscoveryUIHandler::SendRegisterError() {
  web_ui()->CallJavascriptFunction("local_discovery.onRegistrationFailed");
}

void LocalDiscoveryUIHandler::SendRegisterDone(
    const std::string& service_name) {
  // HACK(noamsml): Generate network traffic so the Windows firewall doesn't
  // block the printer's announcement.
  privet_lister_->DiscoverNewDevices(false);

  DeviceDescriptionMap::iterator found =
      device_descriptions_.find(service_name);

  if (found == device_descriptions_.end()) {
    // TODO(noamsml): Handle the case where a printer's record is not present at
    // the end of registration.
    SendRegisterError();
    return;
  }

  const DeviceDescription& device = found->second;
  base::DictionaryValue device_value;

  device_value.SetString(kDictionaryKeyType, device.type);
  device_value.SetString(kDictionaryKeyID, device.id);
  device_value.SetString(kDictionaryKeyDisplayName, device.name);
  device_value.SetString(kDictionaryKeyDescription, device.description);
  device_value.SetString(kDictionaryKeyServiceName, service_name);

  web_ui()->CallJavascriptFunction("local_discovery.onRegistrationSuccess",
                                   device_value);
}

void LocalDiscoveryUIHandler::SetIsVisible(bool visible) {
  if (visible != is_visible_) {
    g_num_visible += visible ? 1 : -1;
    is_visible_ = visible;
  }
}

std::string LocalDiscoveryUIHandler::GetSyncAccount() {
  Profile* profile = Profile::FromWebUI(web_ui());
  SigninManagerBase* signin_manager =
      SigninManagerFactory::GetForProfileIfExists(profile);

  if (!signin_manager) {
    return "";
  }

  return signin_manager->GetAuthenticatedUsername();
}

// TODO(noamsml): Create master object for registration flow.
void LocalDiscoveryUIHandler::ResetCurrentRegistration() {
  if (current_register_operation_) {
    current_register_operation_->Cancel();
    current_register_operation_.reset();
  }

  current_setup_operation_.reset();
  confirm_api_call_flow_.reset();
  privet_resolution_.reset();
  current_http_client_.reset();
}

void LocalDiscoveryUIHandler::PrivetClientToV3(
    const PrivetClientCallback& callback,
    scoped_ptr<PrivetHTTPClient> client) {
  callback.Run(client.Pass());
}

void LocalDiscoveryUIHandler::CheckUserLoggedIn() {
  base::FundamentalValue logged_in_value(!GetSyncAccount().empty());
  web_ui()->CallJavascriptFunction("local_discovery.setUserLoggedIn",
                                   logged_in_value);
}

void LocalDiscoveryUIHandler::CheckListingDone() {
  int started = 0;
  if (cloud_print_printer_list_)
    ++started;
  if (cloud_device_list_)
    ++started;

  if (started > failed_list_count_ + succeded_list_count_)
    return;

  if (succeded_list_count_ <= 0) {
    web_ui()->CallJavascriptFunction(
        "local_discovery.onCloudDeviceListUnavailable");
    return;
  }

  base::ListValue devices_list;
  std::set<std::string> local_ids;

  for (DeviceDescriptionMap::iterator i = device_descriptions_.begin();
       i != device_descriptions_.end(); i++) {
    local_ids.insert(i->second.id);
  }

  ReadDevicesList(cloud_devices_, local_ids, &devices_list);

  web_ui()->CallJavascriptFunction(
      "local_discovery.onCloudDeviceListAvailable", devices_list);
  cloud_print_printer_list_.reset();
  cloud_device_list_.reset();
}

scoped_ptr<GCDApiFlow> LocalDiscoveryUIHandler::CreateApiFlow() {
  Profile* profile = Profile::FromWebUI(web_ui());
  if (!profile)
    return scoped_ptr<GCDApiFlow>();
  ProfileOAuth2TokenService* token_service =
      ProfileOAuth2TokenServiceFactory::GetForProfile(profile);
  if (!token_service)
    return scoped_ptr<GCDApiFlow>();
  SigninManagerBase* signin_manager =
      SigninManagerFactory::GetInstance()->GetForProfile(profile);
  if (!signin_manager)
    return scoped_ptr<GCDApiFlow>();
  return GCDApiFlow::Create(profile->GetRequestContext(),
                            token_service,
                            signin_manager->GetAuthenticatedAccountId());
}

void LocalDiscoveryUIHandler::CreatePrivetV3Client(
    const std::string& device,
    const PrivetClientCallback& callback) {
  DeviceDescriptionMap::iterator found = device_descriptions_.find(device);
  if (found == device_descriptions_.end())
    return callback.Run(scoped_ptr<PrivetHTTPClient>());
  PrivetHTTPAsynchronousFactory::ResultCallback new_callback =
      base::Bind(&LocalDiscoveryUIHandler::PrivetClientToV3,
                 base::Unretained(this),
                 callback);
  privet_resolution_ =
      privet_http_factory_->CreatePrivetHTTP(device,
                                             found->second.address,
                                             new_callback).Pass();
  if (!privet_resolution_)
    return callback.Run(scoped_ptr<PrivetHTTPClient>());
  privet_resolution_->Start();
}

#if defined(CLOUD_PRINT_CONNECTOR_UI_AVAILABLE)
void LocalDiscoveryUIHandler::StartCloudPrintConnector() {
  Profile* profile = Profile::FromWebUI(web_ui());

  base::Closure cloud_print_callback = base::Bind(
      &LocalDiscoveryUIHandler::OnCloudPrintPrefsChanged,
          base::Unretained(this));

  if (cloud_print_connector_email_.GetPrefName().empty()) {
    cloud_print_connector_email_.Init(
        prefs::kCloudPrintEmail, profile->GetPrefs(), cloud_print_callback);
  }

  if (cloud_print_connector_enabled_.GetPrefName().empty()) {
    cloud_print_connector_enabled_.Init(
        prefs::kCloudPrintProxyEnabled, profile->GetPrefs(),
        cloud_print_callback);
  }

  if (cloud_print_connector_ui_enabled_) {
    SetupCloudPrintConnectorSection();
    RefreshCloudPrintStatusFromService();
  } else {
    RemoveCloudPrintConnectorSection();
  }
}

void LocalDiscoveryUIHandler::OnCloudPrintPrefsChanged() {
  if (cloud_print_connector_ui_enabled_)
    SetupCloudPrintConnectorSection();
}

void LocalDiscoveryUIHandler::ShowCloudPrintSetupDialog(
    const base::ListValue* args) {
  content::RecordAction(
      base::UserMetricsAction("Options_EnableCloudPrintProxy"));
  // Open the connector enable page in the current tab.
  Profile* profile = Profile::FromWebUI(web_ui());
  content::OpenURLParams params(
      cloud_devices::GetCloudPrintEnableURL(
          CloudPrintProxyServiceFactory::GetForProfile(profile)->proxy_id()),
      content::Referrer(),
      CURRENT_TAB,
      content::PAGE_TRANSITION_LINK,
      false);
  web_ui()->GetWebContents()->OpenURL(params);
}

void LocalDiscoveryUIHandler::HandleDisableCloudPrintConnector(
    const base::ListValue* args) {
  content::RecordAction(
      base::UserMetricsAction("Options_DisableCloudPrintProxy"));
  CloudPrintProxyServiceFactory::GetForProfile(Profile::FromWebUI(web_ui()))->
      DisableForUser();
}

void LocalDiscoveryUIHandler::SetupCloudPrintConnectorSection() {
  Profile* profile = Profile::FromWebUI(web_ui());

  if (!CloudPrintProxyServiceFactory::GetForProfile(profile)) {
    cloud_print_connector_ui_enabled_ = false;
    RemoveCloudPrintConnectorSection();
    return;
  }

  bool cloud_print_connector_allowed =
      !cloud_print_connector_enabled_.IsManaged() ||
      cloud_print_connector_enabled_.GetValue();
  base::FundamentalValue allowed(cloud_print_connector_allowed);

  std::string email;
  if (profile->GetPrefs()->HasPrefPath(prefs::kCloudPrintEmail) &&
      cloud_print_connector_allowed) {
    email = profile->GetPrefs()->GetString(prefs::kCloudPrintEmail);
  }
  base::FundamentalValue disabled(email.empty());

  base::string16 label_str;
  if (email.empty()) {
    label_str = l10n_util::GetStringFUTF16(
        IDS_LOCAL_DISCOVERY_CLOUD_PRINT_CONNECTOR_DISABLED_LABEL,
        l10n_util::GetStringUTF16(IDS_GOOGLE_CLOUD_PRINT));
  } else {
    label_str = l10n_util::GetStringFUTF16(
        IDS_OPTIONS_CLOUD_PRINT_CONNECTOR_ENABLED_LABEL,
        l10n_util::GetStringUTF16(IDS_GOOGLE_CLOUD_PRINT),
        base::UTF8ToUTF16(email));
  }
  base::StringValue label(label_str);

  web_ui()->CallJavascriptFunction(
      "local_discovery.setupCloudPrintConnectorSection", disabled, label,
      allowed);
}

void LocalDiscoveryUIHandler::RemoveCloudPrintConnectorSection() {
  web_ui()->CallJavascriptFunction(
      "local_discovery.removeCloudPrintConnectorSection");
}

void LocalDiscoveryUIHandler::RefreshCloudPrintStatusFromService() {
  if (cloud_print_connector_ui_enabled_)
    CloudPrintProxyServiceFactory::GetForProfile(Profile::FromWebUI(web_ui()))->
        RefreshStatusFromService();
}

#endif // cloud print connector option stuff

#if defined(ENABLE_WIFI_BOOTSTRAPPING)

void LocalDiscoveryUIHandler::StartWifiBootstrapping() {
  // Since LocalDiscoveryUIHandler isn't destroyed every time the page is
  // refreshed, reset bootstrapping_device_lister_ so it's destoryed before
  // wifi_manager_ is.
  bootstrapping_device_lister_.reset();

  wifi_manager_ = wifi::WifiManager::Create();
  bootstrapping_device_lister_.reset(new wifi::BootstrappingDeviceLister(
      wifi_manager_.get(),
      base::Bind(&LocalDiscoveryUIHandler::OnBootstrappingDeviceChanged,
                 base::Unretained(this))));

  wifi_manager_->Start();
  bootstrapping_device_lister_->Start();
  wifi_manager_->RequestScan();
}

void LocalDiscoveryUIHandler::OnBootstrappingDeviceChanged(
    bool available,
    const wifi::BootstrappingDeviceDescription& description) {
  base::DictionaryValue info;

  base::StringValue service_key(kKeyPrefixWifi + description.device_ssid);

  if (available) {
    info.SetString(kDictionaryKeyServiceName, description.device_ssid);
    info.SetString(kDictionaryKeyDisplayName, description.device_name);
    info.SetString(kDictionaryKeyDescription, std::string());
    info.SetString(kDictionaryKeyType, description.device_kind);
    info.SetBoolean(kDictionaryKeyIsWifi, true);

    web_ui()->CallJavascriptFunction(
        "local_discovery.onUnregisteredDeviceUpdate", service_key, info);
  } else {
    scoped_ptr<base::Value> null_value(base::Value::CreateNullValue());

    web_ui()->CallJavascriptFunction(
        "local_discovery.onUnregisteredDeviceUpdate", service_key, *null_value);
  }
}

#endif  // ENABLE_WIFI_BOOTSTRAPPING

}  // namespace local_discovery


text:
require 'insertion_sort'
require 'merge_sort'
require 'bubble_sort'
class Sortable
  attr_reader :array, :desc
  def initialize array, desc=false
    unless array.is_a? Enumerable
      raise "Please provide an array or other Enumerable"
    end
    unless (array.all? {|item| item.is_a? Comparable})
      raise "All objects must implement Comparable"
    end
    @array = array
    @desc = desc
  end

  def insertion_sort!
    @array = InsertionSort.order(@array, desc=@desc)
  end

  def merge_sort!
    @array = MergeSort.order(@array, desc= @desc)
  end

  def equal? sortable
    unless sortable.is_a? Sortable
      return false
    end
    self.array == sortable.array
  end

  protected
  def is_desc?
    @desc
  end

end

redpajama_set_name: RedPajamaGithub


text:
/*global QUnit */

sap.ui.define([
	"sap/ui/qunit/QUnitUtils",
	"sap/ui/dom/containsOrEquals",
	"sap/ui/core/Control",
	"sap/ui/unified/Shell",
	"sap/ui/unified/ShellOverlay",
	"sap/base/util/ObjectPath",
	"sap/ui/thirdparty/jquery"
], function(qutils, containsOrEquals, Control, Shell, ShellOverlay, ObjectPath, jQuery) {
	"use strict";

	// Control initialization

	function testMultiAggregation(sName, oCtrl, assert){
		var oAggMetaData = oCtrl.getMetadata().getAggregations()[sName];
		var oType = ObjectPath.get(oAggMetaData.type === "sap.ui.core.Control" ? "my.Test" : oAggMetaData.type);

		function _get(){
			return oCtrl[oAggMetaData._sGetter]();
		}

		function _mutator(bInsert, aArgs){
			var sMutator = oAggMetaData._sMutator;
			if (bInsert) {
				sMutator = sMutator.replace("add", "insert");
			}
			oCtrl[sMutator].apply(oCtrl, aArgs);
		}

		function _removeAll(){
			var sMutator = oAggMetaData._sGetter;
			sMutator = sMutator.replace("get", "removeAll");
			oCtrl[sMutator].apply(oCtrl);
		}

		assert.equal(_get().length, 0, "Initial number of " + sName + " controls");
		_mutator(false, [new oType(sName + "_1")]);
		assert.equal(_get().length, 1, "Number of " + sName + " controls after add");
		_mutator(true, [new oType(sName + "_2"), 0]);
		assert.equal(_get().length, 2, "Number of " + sName + " controls after insert");
		assert.equal(_get()[0].getId(), sName + "_2", "First " + sName + " control");
		assert.equal(_get()[1].getId(), sName + "_1", "Second " + sName + " control");
		oCtrl[oAggMetaData._sRemoveMutator](0);
		assert.equal(_get().length, 1, "Number of " + sName + " controls after remove");
		assert.equal(_get()[0].getId(), sName + "_1", "First " + sName + " control");
		_removeAll();
		assert.equal(_get().length, 0, "Number of " + sName + " controls after removeAll");
	}

	function checkVisibility(){
		return jQuery("#overlay1").is(":visible");
	}

	function testCloseOverlay(bViaAPI, assert, done){
		var testTimer, eventFired;

		function finalize() {
			clearTimeout(testTimer);
			oShellOverlay1.detachClosed(onClosed);
			assert.ok(!checkVisibility(), "Overlay initially hidden");
			assert.ok(!!eventFired, "Closed event was fired");
			done();
		}

		function onClosed(){
			eventFired = true;
			finalize();
		}

		oShellOverlay1.attachClosed(onClosed);
		assert.ok(checkVisibility(), "Overlay visible");
		if (bViaAPI) {
			oShellOverlay1.close();
		} else {
			qutils.triggerEvent("click", "overlay1-close");
		}

		testTimer = setTimeout(finalize, 3000);
	}

	var TestControl = Control.extend("my.Test", {
		renderer: {
			apiVersion: 2,
			render: function(rm, ctrl){
				rm.openStart("div", ctrl);
				rm.style("width", "10px");
				rm.style("height", "10px");
				rm.style("background-color", "gray");
				rm.openEnd();
				rm.close("div");
			}
		}
	});

	var oShell = new Shell("shell", {
		search: new TestControl("search0")
	});
	oShell.placeAt("content");

	var oShellOverlay0 = new ShellOverlay("overlay0");

	var oShellOverlay1 = new ShellOverlay("overlay1", {
		search: new TestControl("search1"),
		content: [new TestControl("content")],
		shell: oShell
	});

	// Test functions

	QUnit.module("API");

	QUnit.test("Aggregation 'content'", function(assert) {
		testMultiAggregation("content", oShellOverlay0, assert);
	});

	QUnit.test("Aggregation 'search'", function(assert) {
		assert.ok(!oShellOverlay0.getSearch(), "Initially no search control");
		oShellOverlay0.setSearch(new TestControl());
		assert.ok(!!oShellOverlay0.getSearch(), "Search control available after set");
		oShellOverlay0.setSearch(null);
		assert.ok(!oShellOverlay0.getSearch(), "No search control again");
	});

	QUnit.module("Behavior");

	QUnit.test("Open Overlay", function(assert) {
		var done = assert.async();
		assert.ok(!checkVisibility(), "Overlay initially hidden");
		oShellOverlay1.open();

		setTimeout(function(){
			assert.ok(checkVisibility(), "Overlay visible");
			done();
		}, 600);
	});

	QUnit.test("Close Overlay (via function call)", function(assert) {
		var done = assert.async();
		testCloseOverlay(true, assert, done);
	});

	QUnit.test("Rendering", function(assert) {
		var done = assert.async();
		assert.ok(!checkVisibility(), "Overlay initially hidden");
		oShellOverlay1.open();

		setTimeout(function(){
			assert.ok(checkVisibility(), "Overlay visible");
			assert.ok(containsOrEquals(document.getElementById("overlay1-hdr-center"), document.getElementById("search1")), "Search rendered correctly");
			assert.ok(containsOrEquals(document.getElementById("overlay1-cntnt"), document.getElementById("content")), "Content rendered correctly");
			done();
		}, 600);
	});

	QUnit.test("Close Overlay (via click)", function(assert) {
		var done = assert.async();
		testCloseOverlay(false, assert, done);
	});

	QUnit.test("Clear UI", function(assert) {
		assert.expect(0);
		jQuery("#content").remove();
	});

});


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

-->
<resources>

    <color name="window_background">#FF191919</color>
    <color name="grid_dark_background">#EB191919</color>
    <color name="bubble_dark_background">#B2191919</color>
    <color name="delete_color_filter">#A5FF0000</color>
    <color name="dock_color_filter">#A500FF00</color>
    <color name="thumbnail_workspace_background">#80000000</color>
    <color name="appwidget_error_color">#FCCC</color>
    <color name="snag_callout_color">#F444</color>
    <color name="gesture_color">#ff0563c1</color>
    <color name="uncertain_gesture_color">#ff848484</color>
    <color name="white">#ffffffff</color>
    <color name="black">#ff000000</color>
    <color name="transparent">#00000000</color>
    <color name="transparent_background">#7f000000</color>
    <color name="help_bg">#00000000</color>
    <color name="gray">#ff444444</color>
    <color name="silver">#ffaaaaaa</color>
    <color name="tgray">#b0666666</color>
    <color name="help_white">#ffeeeeee</color>
    <color name="folder_text_color">#ff583710</color>

</resources>


text:
This is a sample application that showcases the [Parse JavaScript SDK](https://www.parse.com/docs/js_guide). It's based on the [canonical Backbone Todo app](http://addyosmani.github.com/todomvc/).

[View the live application hosted on Parse here](http://todolist.parseapp.com).

[Learn how we built it in the tutorial](https://parse.com/tutorials/todo-app-with-javascript).


text:
import LuminanceSource from './LuminanceSource';
import IllegalArgumentException from './IllegalArgumentException';

/**
 * //FIXME fix doc
 * This class is used to help decode images from files which arrive as RGB data from
 * an ARGB pixel array. It does not support rotation.
 *
 * @author dswitkin@google.com (Daniel Switkin)
 * @author Betaminos
 */
export default class Uint8RGBLuminanceSource extends LuminanceSource {

  constructor(width, height, pixels, dataWidth = width, dataHeight = height, left = 0, top = 0,
              isAlreadyGreyScale = false) {
    super(width, height);

    this.dataWidth = dataWidth;
    this.dataHeight = dataHeight;
    this.left = left;
    this.top = top;

    if (isAlreadyGreyScale) {
      this.luminances = pixels;
    } else {
      // In order to measure pure decoding speed, we convert the entire image to a greyscale array
      // up front, which is the same as the Y channel of the YUVLuminanceSource in the real app.
      const length = width * height;
      this.luminances = new Uint8ClampedArray(length);
      for (let i = 0; i < length; i++) {

        const pos = i * 4;
        const r = pixels[pos];
        const g = pixels[pos + 1];
        const b = pixels[pos + 2];
        const a = pixels[pos + 3];

        let luminance;
        if (r === g && g === b) {
          // Image is already greyscale, so pick any channel.
          luminance = r;
        } else {
          // Calculate luminance cheaply, favoring green.
          luminance = Math.floor((r + 2 * g + b) / 4);
        }
        if (a === 0xFF) {
          this.luminances[i] = luminance;
        } else {
          // assume white background for transparent images
          this.luminances[i] = Math.floor(((luminance * a) + 0xFF * (0xFF - a)) / 0xFF);
        }
      }
    }
  }

  getRow(y, row) {
    if (y < 0 || y >= this.getHeight()) {
      throw new IllegalArgumentException('Requested row is outside the image: ' + y);
    }
    const width = this.getWidth();
    if (!row || row.length < width) {
      row = new Uint8ClampedArray(width);
    }
    const offset = (y + this.top) * this.dataWidth + this.left;
    for (let i = 0; i < width; i++) {
      row[i] = this.luminances[offset + i];
    }

    return row;
  }

  getMatrix() {
    const width = this.getWidth();
    const height = this.getHeight();

    // If the caller asks for the entire underlying image, save the copy and give them the
    // original data. The docs specifically warn that result.length must be ignored.
    if (width === this.dataWidth && height === this.dataHeight) {
      return this.luminances;
    }

    const area = width * height;
    const matrix = new Uint8ClampedArray(area);
    let inputOffset = this.top * this.dataWidth + this.left;

    // If the width matches the full width of the underlying data, perform a single copy.
    if (width === this.dataWidth) {
      for (let i = 0; i < area; i++) {
        matrix[i] = this.luminances[inputOffset + i];
      }
      return matrix;
    }

    // Otherwise copy one cropped row at a time.
    const rgb = this.luminances;
    for (let y = 0; y < height; y++) {
      let outputOffset = y * width;
      for (let i = 0; i < width; i++) {
        matrix[outputOffset + i] = rgb[inputOffset + i];
      }
      inputOffset += this.dataWidth;
    }
    return matrix;
  }

  isCropSupported() {
    return true;
  }

  crop(left, top, width, height) {
    return new Uint8RGBLuminanceSource(width,
                                       height,
                                       this.luminances,
                                       this.dataWidth, this.dataHeight,
                                       this.left + left,
                                       this.top + top,
                                       true);
  }

}


text:
module Satellite
  module Adapters
    class GoogleAnalytics

      attr_accessor :debug, :user_agent, :accept_language

      def initialize(params, use_ssl=false)
        @utm_params = extend_with_default_params(params)
        self.utm_location = (use_ssl ? 'https://ssl' : 'http://www') + UTM_GIF_LOCATION
      end

      def track
        utm_url = tracking_url

        #if (debug == true)
        #puts "--------sending request to GA-----------------------"
        #puts @utm_params.inspect
        #puts utm_url
        #end

        # actually send request
        open(utm_url, { "User-Agent" => 'Satellite/0.2.1', "Accept-Language" => self[:utmul] || 'de' })

        # reset events / custom variables here so they won't be reused in later requests
        self[:utme] = Utme.new
        true
      end

      def tracking_url
        utm_location + "?" + @utm_params.to_query
      end

      def track_event(category, action, label=nil, value=nil)
        self[:utme] = Utme.new if self[:utme].nil?
        self[:utme].set_event(category, action, label, value)
        track
      end

      def track_page_view(path=nil)
        self[:utmp] = path if path
        track
      end

      def set_custom_variable(index, name, value, scope=nil)
        self[:utme] = Utme.new if self[:utme].nil?
        self[:utme].set_custom_variable(index, name, value, scope)
      end

      def unset_custom_variable(index)
        self[:utme] = Utme.new if self[:utme].nil?
        self[:utme].unset_custom_variable(index)
      end

      def []=(key, value)
        value = Utme.parse(value) if key.to_s == 'utme'
        @utm_params[key] = value
      end

      def [](key)
        @utm_params[key]
      end

      class << self
        attr_accessor :account_id
      end

      protected

      attr_accessor :utm_location

      private

      # seems to be the current version
      # search for 'utmwv' in http://www.google-analytics.com/ga.js
      #VERSION = '4.4sh'
      VERSION = '5.1.5'
      UTM_GIF_LOCATION = ".google-analytics.com/__utm.gif"

      # adds default params
      def extend_with_default_params(params)
        utme = params.delete(:utme)
        {
            :utmac => self.class.account_id,
            :utmcc => '__utma=999.999.999.999.999.1;', # stub for non-existent cookie,
            :utmcs => 'UTF-8',
            :utme => Utme.parse(utme),
            :utmhid => rand(0x7fffffff).to_s,
            :utmn => rand(0x7fffffff).to_s,
            :utmvid => rand(0x7fffffff).to_s,
            :utmwv => VERSION,
            :utmul => 'en',
            # should get configured when initializing
            #:utmhn => 'google-analytics.satellite.local',
            #:utmr => 'https://rubygems.org/gems/satellite',
            #:utmp => '/google-analytics',
            #:utmip => '127.0.0.1',
        }.merge(params)
      end

    end
  end
end

module Satellite
  module Adapters
    class GoogleAnalytics::Utme

      def initialize
        @custom_variables = CustomVariables.new
      end

      def set_event(category, action, label=nil, value=nil)
        @event = Event.new(category, action, label, value)
        self
      end

      def set_custom_variable(slot, name, value, scope=nil)
        @custom_variables.set_custom_variable(slot, CustomVariable.new(name, value, scope))
        self
      end

      def unset_custom_variable(slot)
        @custom_variables.unset_custom_variable(slot)
        self
      end

      def to_s
        @event.to_s + @custom_variables.to_s
      end

      alias_method :to_param, :to_s

      class << self

        @@regex_event = /5\((\w+)\*(\w+)(\*(\w+))?\)(\((\d+)\))?/
        @@regex_custom_variables = /8\(([^\)]*)\)9\(([^\)]*)\)(11\(([^\)]*)\))?/
        @@regex_custom_variable_value = /((\d)!)?([^\(\*]+)/

        def parse(args)
          return self.new if args.nil?
          case args
            when String
              return self.from_string(args.dup)
            when self
              return args
            else
              raise ArgumentError, "Could parse argument neither as String nor GATracker::Utme"
          end
        end

        def from_string(str)
          utme = self.new

          # parse event
          str.gsub!(@@regex_event) do |match|
            utme.set_event($1, $2, $4, $6)
            ''
          end

          # parse custom variables
          str.gsub!(@@regex_custom_variables) do |match|
            custom_vars = { }
            match_names, match_values, match_scopes = $1, $2, $4

            names = match_names.to_s.split('*')
            values = match_values.to_s.split('*')
            scopes = match_scopes.to_s.split('*')

            raise ArgumentError, "Each custom variable must have a value defined." if names.length != values.length

            names.each_with_index do |raw_name, i|
              match_data = raw_name.match(@@regex_custom_variable_value)
              slot, name = (match_data[2] || i+1).to_i, match_data[3]
              custom_vars[slot] = { :name => name }
            end

            values.each_with_index do |raw_value, i|
              match_data = raw_value.match(@@regex_custom_variable_value)
              slot, value = (match_data[2] || i+1).to_i, match_data[3]
              custom_vars[slot][:value] = value
            end

            scopes.each_with_index do |raw_scope, i|
              match_data = raw_scope.match(@@regex_custom_variable_value)
              slot, scope = (match_data[2] || i+1).to_i, match_data[3]
              # silently ignore scope if there's no corresponding custom variable
              custom_vars[slot][:scope] = scope if custom_vars[slot]
            end

            # finally set all the gathered custom vars
            custom_vars.each do |key, custom_var|
              utme.set_custom_variable(key, custom_var[:name], custom_var[:value], custom_var[:scope])
            end
            ''
          end

          utme
        end
      end

      private

      Event = Struct.new(:category, :action, :opt_label, :opt_value) do
        def to_s
          output = "5(#{category}*#{action}"
          output += "*#{opt_label}" if opt_label
          output += ")"
          output += "(#{opt_value})" if opt_value
          output
        end
      end

      # The total combined length of any custom variable name and value may not exceed 64 bytes.
      # http://code.google.com/intl/en/apis/analytics/docs/tracking/gaTrackingCustomVariables.html
      CustomVariable = Struct.new(:name, :value, :opt_scope)

      class CustomVariables

        @@valid_keys = 1..5

        def initialize
          @contents = { }
        end

        def set_custom_variable(slot, custom_variable)
          raise ArgumentError, "Cannot set a slot other than #{@@valid_keys}. Given #{slot}" if not @@valid_keys.include?(slot)
          @contents[slot] = custom_variable
        end

        def unset_custom_variable(slot)
          raise ArgumentError, "Cannot unset a slot other than #{@@valid_keys}. Given #{slot}" if not @@valid_keys.include?(slot)
          @contents.delete(slot)
        end

        # follows google custom variable format
        #
        # 8(NAMES)9(VALUES)11(SCOPES)
        #
        # best explained by examples
        #
        # 1)
        # pageTracker._setCustomVar(1,"foo", "val", 1)
        # ==> 8(foo)9(bar)11(1)
        #
        # 2)
        # pageTracker._setCustomVar(1,"foo", "val", 1)
        # pageTracker._setCustomVar(2,"bar", "vok", 3)
        # ==> 8(foo*bar)9(val*vok)11(1*3)
        #
        # 3)
        # pageTracker._setCustomVar(1,"foo", "val", 1)
        # pageTracker._setCustomVar(2,"bar", "vok", 3)
        # pageTracker._setCustomVar(4,"baz", "vol", 1)
        # ==> 8(foo*bar*4!baz)9(val*vak*4!vol)11(1*3*4!1)
        #
        # 4)
        # pageTracker._setCustomVar(4,"foo", "bar", 1)
        # ==> 8(4!foo)9(4!bar)11(4!1)
        #
        def to_s
          return '' if @contents.empty?

          ordered_keys = @contents.keys.sort
          names = values = scopes = ''

          ordered_keys.each do |slot|
            custom_variable = @contents[slot]
            predecessor = @contents[slot-1]

            has_predecessor = !!predecessor
            has_scoped_predecessor = !!(predecessor.try(:opt_scope))

            star = names.empty? ? '' : '*'
            bang = (slot == 1 || has_predecessor) ? '' : "#{slot}!"

            scope_star = scopes.empty? ? '' : '*'
            scope_bang = (slot == 1 || has_scoped_predecessor) ? '' : "#{slot}!"

            names += "#{star}#{bang}#{custom_variable.name}"
            values += "#{star}#{bang}#{custom_variable.value}"
            scopes += "#{scope_star}#{scope_bang}#{custom_variable.opt_scope}" if custom_variable.opt_scope
          end

          output = "8(#{names})9(#{values})"
          output += "11(#{scopes})" if not scopes.empty?
          output
        end

      end
    end
  end
end


text:
package org.wildfly.swarm.plugin.gradle;

import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import org.gradle.api.Action;
import org.gradle.api.Project;
import org.gradle.api.artifacts.Configuration;
import org.gradle.api.artifacts.DependencySet;
import org.gradle.api.artifacts.ResolvedDependency;
import org.gradle.api.artifacts.repositories.MavenArtifactRepository;
import org.gradle.api.internal.artifacts.DefaultExcludeRule;
import org.gradle.api.internal.artifacts.dependencies.DefaultDependencyArtifact;
import org.gradle.api.internal.artifacts.dependencies.DefaultExternalModuleDependency;
import org.gradle.api.internal.artifacts.dependencies.DefaultProjectDependency;
import org.gradle.api.internal.project.DefaultProjectAccessListener;
import org.gradle.api.internal.project.ProjectInternal;
import org.wildfly.swarm.tools.ArtifactResolvingHelper;
import org.wildfly.swarm.tools.ArtifactSpec;

/**
 * @author Bob McWhirter
 */
public class GradleArtifactResolvingHelper implements ArtifactResolvingHelper {

    private final Project project;
    Map<String, Project> projects;

    public GradleArtifactResolvingHelper(Project project) {
        this.project = project;
        this.projects = project.getRootProject().getAllprojects().stream().collect(Collectors.toMap(p -> p.getGroup() + ":" + p.getName() + ":" + p.getVersion(), p -> p));
        this.project.getRepositories().maven(new Action<MavenArtifactRepository>() {
            @Override
            public void execute(MavenArtifactRepository repo) {
                repo.setName("jboss-public");
                repo.setUrl("http://repository.jboss.org/nexus/content/groups/public/");
            }
        });
    }

    @Override
    public ArtifactSpec resolve(final ArtifactSpec spec) {
        if (spec.file != null) {
            return spec;
        }

        final Iterator<ResolvedDependency> iterator =
                doResolve(new HashSet<>(Collections.singletonList(spec))).iterator();
        if (iterator.hasNext()) {
            spec.file = iterator.next()
                    .getModuleArtifacts()
                    .iterator().next()
                    .getFile();

            return spec;
        }

        return null;
    }

    @Override
    public Set<ArtifactSpec> resolveAll(final Set<ArtifactSpec> specs) throws Exception {
        if (specs.isEmpty()) {

            return specs;
        }

        final Set<ArtifactSpec> resolvedSpecs = new HashSet<>();

        doResolve(specs).forEach(dep -> dep.getModuleArtifacts()
                .forEach(artifact -> resolvedSpecs
                        .add(new ArtifactSpec(dep.getConfiguration(),
                                              dep.getModuleGroup(),
                                              artifact.getName(),
                                              dep.getModuleVersion(),
                                              artifact.getExtension(),
                                              artifact.getClassifier(),
                                              artifact.getFile()))));

        return resolvedSpecs.stream()
                .filter(a -> !"system".equals(a.scope))
                .collect(Collectors.toSet());
    }

    private Set<ResolvedDependency> doResolve(final Collection<ArtifactSpec> deps) {
        final Configuration config = this.project.getConfigurations().detachedConfiguration();
        final DependencySet dependencySet = config.getDependencies();

        deps.stream()
                .forEach(spec -> {
                    if (projects.containsKey(spec.groupId() + ":" + spec.artifactId() + ":" + spec.version())) {
                        dependencySet.add(new DefaultProjectDependency((ProjectInternal) projects.get(spec.groupId() + ":" + spec.artifactId() + ":" + spec.version()), new DefaultProjectAccessListener(), false));
                    } else {
                        final DefaultExternalModuleDependency d =
                                new DefaultExternalModuleDependency(spec.groupId(), spec.artifactId(), spec.version());
                        final DefaultDependencyArtifact da =
                                new DefaultDependencyArtifact(spec.artifactId(), spec.type(), spec.type(), spec.classifier(), null);
                        d.addArtifact(da);
                        d.getExcludeRules().add(new DefaultExcludeRule());
                        dependencySet.add(d);
                    }
                });

        return config.getResolvedConfiguration().getFirstLevelModuleDependencies();
    }

}


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Options;

namespace Microsoft.CodeAnalysis.CSharp.UseExpressionBody
{
    [ExportCodeRefactoringProvider(LanguageNames.CSharp,
        Name = PredefinedCodeRefactoringProviderNames.UseExpressionBody), Shared]
    internal class UseExpressionBodyCodeRefactoringProvider : CodeRefactoringProvider
    {
        private static readonly ImmutableArray<UseExpressionBodyHelper> _helpers = UseExpressionBodyHelper.Helpers;

        public UseExpressionBodyCodeRefactoringProvider()
        {
        }

        public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
        {
            if (context.Span.Length > 0)
            {
                return;
            }

            var position = context.Span.Start;
            var document = context.Document;
            var cancellationToken = context.CancellationToken;

            var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
            var node = root.FindToken(position).Parent;
            if (node == null)
            {
                return;
            }

            var containingLambda = node.FirstAncestorOrSelf<LambdaExpressionSyntax>();
            if (containingLambda != null &&
                node.AncestorsAndSelf().Contains(containingLambda.Body))
            {
                // don't offer inside a lambda.  Lambdas can be quite large, and it will be very noisy
                // inside the body of one to be offering to use a block/expression body for the containing
                // class member.
                return;
            }

            var optionSet = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);

            foreach (var helper in _helpers)
            {
                var succeeded = TryComputeRefactoring(context, root, node, optionSet, helper);
                if (succeeded)
                {
                    return;
                }
            }
        }

        private bool TryComputeRefactoring(
            CodeRefactoringContext context,
            SyntaxNode root, SyntaxNode node, OptionSet optionSet,
            UseExpressionBodyHelper helper)
        {
            var declaration = GetDeclaration(node, helper);
            if (declaration == null)
            {
                return false;
            }

            var document = context.Document;

            bool succeeded = false;
            if (helper.CanOfferUseExpressionBody(optionSet, declaration, forAnalyzer: false))
            {
                context.RegisterRefactoring(new MyCodeAction(
                    helper.UseExpressionBodyTitle.ToString(),
                    c => UpdateDocumentAsync(
                        document, root, declaration, optionSet, helper,
                        useExpressionBody: true, cancellationToken: c)));
                succeeded = true;
            }

            var (canOffer, _) = helper.CanOfferUseBlockBody(optionSet, declaration, forAnalyzer: false);
            if (canOffer)
            {
                context.RegisterRefactoring(new MyCodeAction(
                    helper.UseBlockBodyTitle.ToString(),
                    c => UpdateDocumentAsync(
                        document, root, declaration, optionSet, helper,
                        useExpressionBody: false, cancellationToken: c)));
                succeeded = true;
            }

            return succeeded;
        }

        private SyntaxNode GetDeclaration(SyntaxNode node, UseExpressionBodyHelper helper)
        {
            for (var current = node; current != null; current = current.Parent)
            {
                if (helper.SyntaxKinds.Contains(current.Kind()))
                {
                    return current;
                }
            }

            return null;
        }

        private async Task<Document> UpdateDocumentAsync(
            Document document, SyntaxNode root, SyntaxNode declaration,
            OptionSet options, UseExpressionBodyHelper helper, bool useExpressionBody,
            CancellationToken cancellationToken)
        {
            var parseOptions = root.SyntaxTree.Options;
            var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
            var updatedDeclaration = helper.Update(semanticModel, declaration, options, parseOptions, useExpressionBody);

            var parent = declaration is AccessorDeclarationSyntax
                ? declaration.Parent
                : declaration;
            var updatedParent = parent.ReplaceNode(declaration, updatedDeclaration)
                                      .WithAdditionalAnnotations(Formatter.Annotation);

            var newRoot = root.ReplaceNode(parent, updatedParent);
            return document.WithSyntaxRoot(newRoot);
        }

        private class MyCodeAction : CodeAction.DocumentChangeAction
        {
            public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument)
                : base(title, createChangedDocument)
            {
            }
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PicnicOrm.Dapper.Demo.Models
{
    public class Address
    {
        public int Id { get; set; }

        public string Street { get; set; }

        public string City { get; set; }

        public string State { get; set; }

        public string PostalCode { get; set; }
    }
}


text:
<?php

namespace OpenDataAPI\aggregator\tools;

class Request {

    /**
     * Send HTTP request with GET method.
     *
     * @param string $url URL.
     * @param array $request Request parameters.
     *
     * @return mixed Response on success, false on failure.
     */
    public static function get($url, $request = []) {
        if (!empty($request)) {
            $url.= "?" . self::getRequestStr($request);
        }
        $ch = curl_init($url);

        curl_setopt_array($ch, [
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_RETURNTRANSFER => true,
        ]);

        $response = curl_exec($ch);

        curl_close($ch);

        return $response;
    }

    /**
     * Send HTTP request with POST method.
     *
     * @param string $url URL.
     * @param array $request Request parameters.
     *
     * @return mixed Response on success, false on failure.
     */
    public static function post($url, $request = []) {
        $ch = curl_init($url);

        curl_setopt_array($ch, [
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => self::getRequestStr($request),
            CURLOPT_RETURNTRANSFER => true,
            //CURLOPT_POST => true,
        ]);

        $response = curl_exec($ch);

        curl_close($ch);

        return $response;
    }

    /**
     * Send HTTP request with POST method and JSON data.
     *
     * @param string $url URL.
     * @param array $request Data to send with JSON.
     *
     * @return mixed Response on success, false on failure.
     */
    public static function postJSON($url, $request = []) {
        $requestJSON = json_encode($request);
        //var_dump($requestJSON);
        //exit();

        $ch = curl_init($url);

        curl_setopt_array($ch, [
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_HTTPHEADER => [
                'Content-Type: application/json',
                'Content-Length: ' . strlen($requestJSON)
            ],
            CURLOPT_POSTFIELDS => $requestJSON,
            CURLOPT_RETURNTRANSFER => true,
            //CURLOPT_POST => true,
        ]);

        $response = curl_exec($ch);

        curl_close($ch);

        return json_decode($response);
    }

    /**
     * Generates request parameters string from array.
     *
     * @param array $request Request parameters array.
     *
     * @return string
     */
    private static function getRequestStr($request) {
        $params = [];
        foreach ($request as $k => $v) {
            $params[] = "$k=$v";
        }

        return implode("&", $params);
    }

}


text:
if [ $# -ne 2 ]
  then
    echo "Usage: mysql-backup-run.sh /path/to/mysql /path/to/backup"
    exit
fi
#Set the name of the file containing the backup - a backup on the 21st December 2016 at 21:00 would have the following name - backup.201612212100.sql
BACKUPFILE=backup.`date +"%Y%m%d%H%M"`.sql
# Call backup method in mysql and redirect output to backup file.
${1}/bin/mysqldump -uroot --all-databases > ${2}/${BACKUPFILE}
#Check if for some reason no data was written in to the file.
if [ ! -s ${2}/${BACKUPFILE} ]
then
    echo 'No data was written - is the database working correctly? Cleaning up empty file...'
    rm ${2}/${BACKUPFILE}
fi


text:
#ifndef CMetricMapBuilder_H
#define CMetricMapBuilder_H

#include <mrpt/utils/CSerializable.h>
#include <mrpt/utils/CListOfClasses.h>
#include <mrpt/utils/CDebugOutputCapable.h>
#include <mrpt/synch.h>
#include <mrpt/slam/CMultiMetricMap.h>
#include <mrpt/slam/CSensoryFrame.h>
#include <mrpt/slam/CSimpleMap.h>
#include <mrpt/poses/CPose3DPDF.h>
#include <mrpt/slam/CActionCollection.h>

#include <mrpt/slam/link_pragmas.h>

namespace mrpt
{
namespace slam
{
	/** @defgroup metric_slam_grp Metric SLAM algorithms
	  * \ingroup mrpt_slam_grp */

	/** This virtual class is the base for SLAM implementations. See derived classes for more information.
	 *
	 * \sa CMetricMap  \ingroup metric_slam_grp
	 */
	class SLAM_IMPEXP CMetricMapBuilder : public mrpt::utils::CDebugOutputCapable
	{
	protected:
		/** Critical zones
		  */
		synch::CCriticalSection	critZoneChangingMap;

		/** Enter critical section for map updating:
		  */
		inline void  enterCriticalSection() { critZoneChangingMap.enter(); }

		/** Leave critical section for map updating:
		  */
		inline void  leaveCriticalSection() { critZoneChangingMap.leave(); }

	public:
		CMetricMapBuilder();           //!< Constructor
		virtual ~CMetricMapBuilder( ); //!< Destructor.

		// ---------------------------------------------------------------------
		/** @name Pure virtual methods to implement in any particular SLAM algorithm
		    @{ */

		/** Initialize the method, starting with a known location PDF "x0"(if supplied, set to NULL to left unmodified) and a given fixed, past map. */
		virtual void  initialize(
				const CSimpleMap &initialMap = CSimpleMap(),
				CPosePDF					*x0 = NULL
				) = 0;

		/** Returns a copy of the current best pose estimation as a pose PDF. */
		virtual CPose3DPDFPtr  getCurrentPoseEstimation() const = 0;

		/** Process a new action and observations pair to update this map: See the description of the class at the top of this page to see a more complete description.
		 *  \param action The estimation of the incremental pose change in the robot pose.
		 *	\param observations The set of observations that robot senses at the new pose.
		 */
		virtual void  processActionObservation( CActionCollection &action,CSensoryFrame	&observations ) = 0;

		/** Fills "out_map" with the set of "poses"-"sensory-frames", thus the so far built map. */
		virtual void  getCurrentlyBuiltMap(CSimpleMap &out_map) const = 0;

		/** Returns just how many sensory-frames are stored in the currently build map. */
		virtual unsigned int  getCurrentlyBuiltMapSize() = 0;

		/** Returns the map built so far. NOTE that for efficiency a pointer to the internal object is passed, DO NOT delete nor modify the object in any way, if desired, make a copy of ir with "duplicate()". */
		virtual CMultiMetricMap*   getCurrentlyBuiltMetricMap() = 0;

		/** A useful method for debugging: the current map (and/or poses) estimation is dumped to an image file.
		  * \param file The output file name
		  * \param formatEMF_BMP Output format = true:EMF, false:BMP
		  */
		virtual void  saveCurrentEstimationToImage(const std::string &file, bool formatEMF_BMP = true) = 0;

		/** @} */
		// ---------------------------------------------------------------------

		/** Clear all elements of the maps, and reset localization to (0,0,0deg). */
		void  clear();

		/** Enables or disables the map updating (default state is enabled) */
		void  enableMapUpdating( bool enable )
		{
			options.enableMapUpdating = enable;
		}

		/** Load map (mrpt::slam::CSimpleMap) from a ".simplemap" file */
		void  loadCurrentMapFromFile(const std::string &fileName);

		/** Save map (mrpt::slam::CSimpleMap) to a ".simplemap" file. */
		void  saveCurrentMapToFile(const std::string &fileName, bool compressGZ=true) const;

		/** Options for the algorithm */
		struct SLAM_IMPEXP TOptions
		{
			TOptions() : verbose(true),
						 enableMapUpdating(true),
						 debugForceInsertion(false),
						 alwaysInsertByClass()
			{
			}

			bool	verbose;             //!< If true shows debug information in the console, default is true.
			bool	enableMapUpdating;   //!< Enable map updating, default is true.
			bool	debugForceInsertion; //!< Always insert into map. Default is false: detect if necesary.

			/** A list of observation classes (derived from mrpt::slam::CObservation) which will be always inserted in the map, disregarding the minimum insertion distances).
			  *  Default: Empty. How to insert classes:
			  *   \code
			  *     alwaysInserByClass.insert(CLASS_ID(CObservationImage));
			  *   \endcode
			  * \sa mrpt::utils::CListOfClasses
			  */
			mrpt::utils::CListOfClasses		alwaysInsertByClass;

		};

		TOptions options;

		public:
			EIGEN_MAKE_ALIGNED_OPERATOR_NEW

	}; // End of class def.

	} // End of namespace
} // End of namespace

#endif


text:
var pkg = require('../package');
var config = require('../config');
var logger = require("../logger/logger");
var wrap = require('co-express');

var userHelper = require('../services/userHelper');
var messageHelper = require('../services/messageHelper');

var mongoose = require('../config/db.js').mongoose;
var user = mongoose.model('User', require('../models/user'));
var userMessage = mongoose.model('UserMessage', require('../models/userMessage'));
var systemMessage = mongoose.model('SystemMessage', require('../models/systemMessage'));

module.exports = function(app, passport) {
    app.get('/profile/messages',
        wrap(function*(req, res, next) {
            if (userHelper.auth(req, res, app.locals.site)) {
                var messages = {};
                req.user.isMain = true;

                messages.systemMessages = yield messageHelper.getSystemMessages(req.user._id, req.user.isAdmin);
                for (var i = 0; i < messages.systemMessages.length; i++) {
                    messages.systemMessages[i].admin = yield userHelper.getUser(messages.systemMessages[i].adminId);
                }

                messages.userMessages = yield messageHelper.getUserMessages(req.user._id, req.user.isAdmin);
                for (var i = 0; i < messages.userMessages.length; i++) {
                    messages.userMessages[i].fromuser = yield userHelper.getUser(messages.userMessages[i].fromUserId);
                    messages.userMessages[i].toUser = yield userHelper.getUser(messages.userMessages[i].toUserId);
                }

                if (!messages) messages = {};

                req = userHelper.processUser(req);
                res.render('messages/messages', { site: app.locals.site, user: req.user, messages: messages, req: req });
            }
        })
    );

    app.get('/user/:userId/message',
        function(req, res, next) {
            if (userHelper.auth(req, res, app.locals.site)) {
                req = userHelper.processUser(req);
                res.render('messages/user-message', { site: app.locals.site, user: req.user, req: req, userId: req.params.userId });
            }
        }
    );

    app.post('/user/:userId/message', function(req, res, next) {
        if (userHelper.auth(req, res, app.locals.site)) {
            req.user.isMain = true;

            var iUserMessage = new userMessage({
                message: req.body.message,
                date: new Date(),
                priority: req.body.priority,
                adminId: null,
                fromUserId: req.user._id,
                toUserId: req.params.userId,
                bookId: null,
                transactionId: null
            });
            iUserMessage.save();

            logger.warn("created user message");

            req = userHelper.processUser(req);
            req.flash('success', "created message to userid: " + req.params.userId);

            res.redirect(req.session.returnTo || '/');
        }
    });

    app.get('/admin/system-message',
        function(req, res, next) {
            if (userHelper.auth(req, res, app.locals.site, true)) {
                req = userHelper.processUser(req);
                res.render('messages/system-message', { site: app.locals.site, user: req.user, req: req });
            }
        }
    );

    app.post('/admin/system-message', function(req, res, next) {
        if (userHelper.auth(req, res, app.locals.site, true)) {
            req.user.isMain = true;
            req = userHelper.processUser(req);

            var iSystemMessage = new systemMessage({
                message: req.body.message,
                date: new Date(),
                priority: req.body.priority,
                adminId: req.user._id
            });
            iSystemMessage.save();

            logger.warn("created system message");

            req.flash('success', "created system message");
            res.redirect(req.session.returnTo || '/');
        }
    });

    app.get('/message/:messageId/reply',
        wrap(function*(req, res, next) {
            if (userHelper.auth(req, res, app.locals.site)) {
                req = userHelper.processUser(req);
                var originalMessage = yield messageHelper.getUserMessage(req.params.messageId);
                res.render('messages/reply-message', { site: app.locals.site, user: req.user, req: req, messageId: req.params.messageId, originalMessage: originalMessage.message });
            }
        })
    );

    app.post('/message/:messageId/reply', wrap(function*(req, res, next) {
        if (userHelper.auth(req, res, app.locals.site)) {
            req.user.isMain = true;
            req = userHelper.processUser(req);

            var oldMessage = yield messageHelper.getUserMessage(req.params.messageId);
            var toUserId = null;
            if (oldMessage.fromUserId === req.user._id) {
                toUserId = oldMessage.toUserId;
            } else {
                toUserId = oldMessage.fromUserId;
            }

            var iUserMessage = new userMessage({
                message: req.body.message,
                date: new Date(),
                priority: req.body.priority,
                adminId: null,
                fromUserId: req.user._id,
                toUserId: toUserId,
                previousMessageId: req.params.messageId
            });
            iUserMessage.save();

            logger.warn("created message reply");

            req.flash('success', "created reply for messageId: " + req.params.messageId);
            res.redirect('/profile/messages');
        }
    }));
}


text:
import setupStore from 'dummy/tests/helpers/store';
import Ember from 'ember';

import { module, test } from 'qunit';

import DS from 'ember-data';

import customAdapter from 'dummy/tests/helpers/custom-adapter';

const {
  get,
  set,
  run
} = Ember;

let store, env, data, recordArray;

const Person = DS.Model.extend({
  name: DS.attr('string'),
  bestFriend: DS.belongsTo('person', { inverse: null, async: false }),
  upperName: Ember.computed('name', function() {
    return this.get('name').toUpperCase();
  }).readOnly()
});

module('integration/filter - DS.Model updating', {
  beforeEach() {
    data = [
      {
        id: '1',
        type: 'person',
        attributes: {
          name: 'Scumbag Dale'
        },
        relationships: {
          bestFriend: {
            data: {
              id: '2',
              type: 'person'
            }
          }
        }
      },
      {
        id: '2',
        type: 'person',
        attributes: {
          name: 'Scumbag Katz'
        }
      },
      {
        id: '3',
        type: 'person',
        attributes: {
          name: 'Scumbag Bryn'
        }
      }
    ];

    env = setupStore({ person: Person });
    store = env.store;
  },

  afterEach() {
    edited = null;
    data = null;

    run(store, 'destroy');
  }
});

function tapFn(fn, callback) {
  const old_fn = fn;

  function new_fn() {
    let result = old_fn.apply(this, arguments);
    if (callback) {
      callback.apply(fn, arguments);
    }
    new_fn.summary.called.push(arguments);
    return result;
  }
  new_fn.summary = { called: [] };

  return new_fn;
}

test('when a DS.Model updates its attributes, its changes affect its filtered Array membership', function(assert) {
  run(() => store.push({ data }));

  let people = run(() => {
    return store.filter('person', hash => {
      if (hash.get('name').match(/Katz$/)) {
        return true;
      }
    });
  });

  assert.equal(get(people, 'length'), 1, 'precond - one item is in the RecordArray');

  const person = people.objectAt(0);

  assert.equal(get(person, 'name'), 'Scumbag Katz', 'precond - the item is correct');

  run(() => set(person, 'name', 'Yehuda Katz'));

  assert.equal(get(people, 'length'), 1, 'there is still one item');
  assert.equal(get(person, 'name'), 'Yehuda Katz', "it has the updated item");

  run(() => set(person, 'name', 'Yehuda Katz-Foo'));

  assert.equal(get(people, 'query'), null, 'expected no query object set');
  assert.equal(get(people, 'length'), 0, 'there are now no items');
});

test('when a DS.Model updates its relationships, its changes affect its filtered Array membership', function(assert) {
  run(() => store.push({ data }));

  let people = run(() => {
    return store.filter('person', person => {
      if (person.get('bestFriend') && person.get('bestFriend.name').match(/Katz$/)) {
        return true;
      }
    });
  });

  run(() => assert.equal(get(people, 'length'), 1, 'precond - one item is in the RecordArray'));

  let person = people.objectAt(0);

  assert.equal(get(person, 'name'), 'Scumbag Dale', 'precond - the item is correct');

  run(() => set(person, 'bestFriend', null));

  assert.equal(get(people, 'length'), 0, 'there are now 0 items');

  let erik = store.peekRecord('person', 3);
  let yehuda = store.peekRecord('person', 2);

  run(() => erik.set('bestFriend', yehuda));

  person = people.objectAt(0);
  assert.equal(get(people, 'length'), 1, 'there is now 1 item');
  assert.equal(get(person, 'name'), 'Scumbag Bryn', 'precond - the item is correct');
});

test('a record array can have a filter on it', function(assert) {
  run(() => store.push({ data }));

  let recordArray = run(() => {
    return store.filter('person', hash => {
      if (hash.get('name').match(/Scumbag [KD]/)) {
        return true;
      }
    });
  });

  assert.equal(get(recordArray, 'length'), 2, 'The Record Array should have the filtered objects on it');

  run(() => {
    store.push({
      data: [{
        id: '4',
        type: 'person',
        attributes: {
          name: 'Scumbag Koz'
        }
      }]
    });
  });

  assert.equal(get(recordArray, 'length'), 3, 'The Record Array should be updated as new items are added to the store');

  run(() => {
    store.push({
      data: [{
        id: '1',
        type: 'person',
        attributes: {
          name: 'Scumbag Tom'
        }
      }]
    });
  });

  assert.equal(get(recordArray, 'length'), 2, 'The Record Array should be updated as existing members are updated');
});

test('a filtered record array includes created elements', function(assert) {
  run(() => store.push({ data }));

  let recordArray = run(() => {
    return store.filter('person', hash => {
      if (hash.get('name').match(/Scumbag [KD]/)) {
        return true;
      }
    });
  });

  assert.equal(get(recordArray, 'length'), 2, 'precond - The Record Array should have the filtered objects on it');

  run(() => {
    store.createRecord('person', { name: 'Scumbag Koz' });
  });

  assert.equal(get(recordArray, 'length'), 3, 'The record array has the new object on it');
});

test('a Record Array can update its filter', function(assert) {
  customAdapter(env, DS.Adapter.extend({
    deleteRecord(store, type, snapshot) { },
    shouldBackgroundReloadRecord() { return false; }
  }));

  run(() => store.push({ data }));

  let dickens = run(() => {
    let record = store.createRecord('person', { id: 4, name: 'Scumbag Dickens' });
    record.deleteRecord();
    return record;
  });

  let asyncData = run(() => {
    return {
      dale: store.findRecord('person', 1),
      katz: store.findRecord('person', 2),
      bryn: store.findRecord('person', 3)
    };
  });

  return store.filter('person', hash => {
    if (hash.get('name').match(/Scumbag [KD]/)) {
      return true;
    }
  }).then(recordArray => {

    return Ember.RSVP.hash(asyncData).then(records => {
      assert.contains(recordArray, records.dale);
      assert.contains(recordArray, records.katz);
      assert.without(recordArray, records.bryn);
      assert.without(recordArray, dickens);

      run(() => {
        recordArray.set('filterFunction', hash => {
          if (hash.get('name').match(/Katz/)) {
            return true;
          }
        });
      });

      assert.equal(get(recordArray, 'length'), 1, 'The Record Array should have one object on it');

      run(() => {
        store.push({
          data: [{
            id: '5',
            type: 'person',
            attributes: {
              name: 'Other Katz'
            }
          }]
        });
      });

      assert.equal(get(recordArray, 'length'), 2, 'The Record Array now has the new object matching the filter');

      run(() => {
        store.push({
          data: [{
            id: '6',
            type: 'person',
            attributes: {
              name: 'Scumbag Demon'
            }
          }]
        });
      });

      assert.equal(get(recordArray, 'length'), 2, 'The Record Array doesn\'t have objects matching the old filter');
    });
  });
});

test('a Record Array can update its filter and notify array observers', function(assert) {
  customAdapter(env, DS.Adapter.extend({
    deleteRecord(store, type, snapshot) { },
    shouldBackgroundReloadRecord() { return false; }
  }));

  run(() => store.push({ data }));

  let dickens = run(() => {
    dickens = store.createRecord('person', { id: 4, name: 'Scumbag Dickens' });
    dickens.deleteRecord();
    return dickens;
  });

  let asyncData = run(() => {
    return [
      store.findRecord('person', 1),
      store.findRecord('person', 2),
      store.findRecord('person', 3)
    ];
  });

  return store.filter('person', hash => {
    if (hash.get('name').match(/Scumbag [KD]/)) {
      return true;
    }
  }).then(recordArray => {

    let didChangeIdx;
    let didChangeRemoved = 0;
    let didChangeAdded = 0;

    let arrayObserver = {
      arrayWillChange() { },

      arrayDidChange(array, idx, removed, added) {
        didChangeIdx = idx;
        didChangeRemoved += removed;
        didChangeAdded += added;
      }
    };

    recordArray.addArrayObserver(arrayObserver);

    run(() => {
      recordArray.set('filterFunction', hash => {
        if (hash.get('name').match(/Katz/)) {
          return true;
        }
      });
    });

    return Ember.RSVP.all(asyncData).then(() => {
      assert.equal(didChangeRemoved, 1, 'removed one item from array');
      didChangeRemoved = 0;

      run(() => {
        store.push({
          data: [{
            id: '5',
            type: 'person',
            attributes: {
              name: 'Other Katz'
            }
          }]
        });
      });

      assert.equal(didChangeAdded, 1, 'one item was added');
      didChangeAdded = 0;

      assert.equal(recordArray.objectAt(didChangeIdx).get('name'), 'Other Katz');

      run(() => {
        store.push({
          data: [{
            id: '6',
            type: 'person',
            attributes: {
              name: 'Scumbag Demon'
            }
          }]
        });
      });

      assert.equal(didChangeAdded, 0, 'did not get called when an object that doesn\'t match is added');

      run(() => {
        recordArray.set('filterFunction', hash => {
          if (hash.get('name').match(/Scumbag [KD]/)) {
            return true;
          }
        });
      });

      assert.equal(didChangeAdded, 2, 'one item is added when going back');
      assert.equal(recordArray.objectAt(didChangeIdx).get('name'), 'Scumbag Demon');
      assert.equal(recordArray.objectAt(didChangeIdx-1).get('name'), 'Scumbag Dale');
    });
  });
});

test('it is possible to filter by computed properties', function(assert) {
  customAdapter(env, DS.Adapter.extend({
    shouldBackgroundReloadRecord: () => false
  }));

  let filter = run(() => {
    return store.filter('person', person => person.get('upperName') === 'TOM DALE');
  });

  assert.equal(filter.get('length'), 0, 'precond - the filter starts empty');

  run(() => {
    store.push({
      data: [{
        id: '1',
        type: 'person',
        attributes: {
          name: 'Tom Dale'
        }
      }]
    });
  });

  assert.equal(filter.get('length'), 1, 'the filter now has a record in it');

  return store.findRecord('person', 1).then(person => {
    run(() => {
      person.set('name', 'Yehuda Katz');
    });

    assert.equal(filter.get('length'), 0, 'the filter is empty again');
  });
});

test('a filter created after a record is already loaded works', function(assert) {
  customAdapter(env, DS.Adapter.extend({
    shouldBackgroundReloadRecord() { return false; }
  }));

  run(() => {
    store.push({
      data: [{
        id: '1',
        type: 'person',
        attributes: {
          name: 'Tom Dale'
        }
      }]
    });
  });

  let filter = run(() => {
    return store.filter('person', person => person.get('upperName') === 'TOM DALE');
  });

  assert.equal(filter.get('length'), 1, 'the filter now has a record in it');

  return store.findRecord('person', 1).then(person => {
    assert.equal(filter.objectAt(0), person);
  });
});

test('filter with query persists query on the resulting filteredRecordArray', function(assert) {
  customAdapter(env, DS.Adapter.extend({
    query(store, type, id) {
      return [
        {
          id: id,
          name: 'Tom Dale'
        }
      ];
    }
  }));

  let filter = run(() => {
    return store.filter('person', { foo: 1 }, person => true);
  });

  return run(() => {
    return filter.then(array => {
      assert.deepEqual(get(array, 'query'), { foo: 1 }, 'has expected query');
    });
  });
});

test('it is possible to filter by state flags', function(assert) {
  customAdapter(env, DS.Adapter.extend({
    findRecord(store, type, id, snapshot) {
      return {
        id,
        name: 'Tom Dale'
      };
    }
  }));

  let filter = run(() => {
    return store.filter('person', person => person.get('isLoaded'));
  });

  assert.equal(filter.get('length'), 0, 'precond - there are no records yet');

  let person = run(() => {
    let person = store.findRecord('person', 1);

    // run will block `find` from being synchronously
    // resolved in test mode

    assert.equal(filter.get('length'), 0, 'the unloaded record isn\'t in the filter');
    return person;
  });

  return person.then(person => {
    assert.equal(filter.get('length'), 1, 'the now-loaded record is in the filter');
    assert.equal(filter.objectAt(0), person);
  });
});

test('it is possible to filter loaded records by dirtiness', function(assert) {
  customAdapter(env, DS.Adapter.extend({
    updateRecord(type, model, snapshot) {
      return { id: snapshot.id };
    },
    shouldBackgroundReloadRecord() {
      return false;
    }
  }));

  let filter = store.filter('person', person => !person.get('hasDirtyAttributes'));

  run(() => {
    store.push({
      data: [{
        id: '1',
        type: 'person',
        attributes: {
          name: 'Tom Dale'
        }
      }]
    });
  });

  return store.findRecord('person', 1).then(person => {
    assert.equal(filter.get('length'), 1, 'the clean record is in the filter');

    // Force synchronous update of the filter, even though
    // we're already inside a run loop
    run(() => person.set('name', 'Yehuda Katz'));

    assert.equal(filter.get('length'), 0, 'the now-dirty record is not in the filter');

    return person.save();
  }).then(person => {
    assert.equal(filter.get('length'), 1, 'the clean record is back in the filter');
  });
});

test('it is possible to filter created records by dirtiness', function(assert) {
  run(() => {
    customAdapter(env, DS.Adapter.extend({
      createRecord(type, model, snapshot) {
        return Ember.merge(Ember.merge({}, snapshot._attributes), { id: snapshot.id} )
      },
      shouldBackgroundReloadRecord() { return false; }
    }));
  });

  let filter = run(() => {
    return store.filter('person', person => !person.get('hasDirtyAttributes'));
  });

  let person = run(() => {
    return store.createRecord('person', {
      id: 1,
      name: 'Tom Dale'
    });
  });

  assert.equal(filter.get('length'), 0, 'the dirty record is not in the filter');

  return run(() => {
    return person.save().then(person => {
      assert.equal(filter.get('length'), 1, 'the clean record is in the filter');
    });
  });
});

test('it is possible to filter created records by isReloading', function(assert) {
  customAdapter(env, DS.Adapter.extend({
    findRecord(store, type, id, snapshot) {
      return {
        id: 1,
        name: 'Tom Dalle'
      };
    }
  }));

  let filter = store.filter('person', person => {
    return !person.get('isReloading');
  });

  let person = store.createRecord('person', {
    id: 1,
    name: 'Tom Dale'
  });

  return person.reload().then(person => {
    assert.equal(filter.get('length'), 1, 'the filter correctly returned a reloaded object');
  });
});

// SERVER SIDE TESTS
let edited;

function clientEdits(ids) {
  edited = [];

  ids.forEach(id => {
    // wrap in an run to guarantee coalescence of the
    // iterated `set` calls and promise resolution.
    run(() => {
      store.findRecord('person', id).then(person => {
        edited.push(person);
        person.set('name', 'Client-side ' + id );
      });
    });
  });
}

function clientCreates(names) {
  // wrap in an run to guarantee coalescence of the
  // iterated `set` calls.
  edited = run(() => {
    return names.map(name => store.createRecord('person', { name: 'Client-side ' + name }));
  });
}

function serverResponds() {
  edited.forEach(person => run(person, 'save'));
}

function setup(assert, serverCallbacks) {
  customAdapter(env, DS.Adapter.extend(serverCallbacks));

  run(() => {
    store.push({ data });

    recordArray = store.filter('person', hash => {
      if (hash.get('name').match(/Scumbag/)) {
        return true;
      }
    });
  });

  assert.equal(get(recordArray, 'length'), 3, 'The filter function should work');
}

test('a Record Array can update its filter after server-side updates one record', function(assert) {
  setup(assert, {
    updateRecord(store, type, snapshot) {
      return {
        id: 1,
        name: 'Scumbag Server-side Dale'
      };
    },
    shouldBackgroundReloadRecord() { return false; }
  });

  clientEdits([1]);
  assert.equal(get(recordArray, 'length'), 2, 'The record array updates when the client changes records');

  serverResponds();
  assert.equal(get(recordArray, 'length'), 3, 'The record array updates when the server changes one record');
});

test('a Record Array can update its filter after server-side updates multiple records', function(assert) {
  setup(assert, {
    updateRecord(store, type, snapshot) {
      switch (snapshot.id) {
        case '1':
          return {
            id: 1,
            name: 'Scumbag Server-side Dale'
          };
        case '2':
          return {
            id: 2,
            name: 'Scumbag Server-side Katz'
          };
      }
    },
    shouldBackgroundReloadRecord() { return false; }
  });

  clientEdits([1, 2]);
  assert.equal(get(recordArray, 'length'), 1, 'The record array updates when the client changes records');

  serverResponds();
  assert.equal(get(recordArray, 'length'), 3, 'The record array updates when the server changes multiple records');
});

test('a Record Array can update its filter after server-side creates one record', function(assert) {
  setup(assert, {
    createRecord(store, type, snapshot) {
      return {
        id: 4,
        name: 'Scumbag Server-side Tim'
      };
    }
  });

  clientCreates(['Tim']);
  assert.equal(get(recordArray, 'length'), 3, 'The record array does not include non-matching records');

  serverResponds();
  assert.equal(get(recordArray, 'length'), 4, 'The record array updates when the server creates a record');
});

test('a Record Array can update its filter after server-side creates multiple records', function(assert) {
  setup(assert, {
    createRecord(store, type, snapshot) {
      switch (snapshot.attr('name')) {
        case 'Client-side Mike':
          return {
            id: 4,
            name: 'Scumbag Server-side Mike'
          };
        case 'Client-side David':
          return {
            id: 5,
            name: 'Scumbag Server-side David'
          };
      }
    }
  });

  clientCreates(['Mike', 'David']);
  assert.equal(get(recordArray, 'length'), 3, 'The record array does not include non-matching records');

  serverResponds();
  assert.equal(get(recordArray, 'length'), 5, 'The record array updates when the server creates multiple records');
});

test('a Record Array can update its filter after server-side creates multiple records', function(assert) {
  setup(assert, {
    createRecord(store, type, snapshot) {
      switch (snapshot.attr('name')) {
        case 'Client-side Mike':
          return {
            id: 4,
            name: 'Scumbag Server-side Mike'
          };
        case 'Client-side David':
          return {
            id: 5,
            name: 'Scumbag Server-side David'
          };
      }
    }
  });

  clientCreates(['Mike', 'David']);
  assert.equal(get(recordArray, 'length'), 3, 'The record array does not include non-matching records');

  serverResponds();
  assert.equal(get(recordArray, 'length'), 5, 'The record array updates when the server creates multiple records');
});

test('destroying filteredRecordArray unregisters models from being filtered', function(assert) {
  const filterFn = tapFn(() => true);

  customAdapter(env, DS.Adapter.extend({
    shouldBackgroundReloadRecord() { return false; }
  }));

  run(() => {
    store.push({
      data: [{
        id: '1',
        type: 'person',
        attributes: {
          name: 'Tom Dale'
        }
      }]
    });
  });

  const recordArray = run(() => store.filter('person', filterFn));

  assert.equal(filterFn.summary.called.length, 1);

  run(() => recordArray.then(array => array.destroy()));

  clientEdits([1]);

  assert.equal(filterFn.summary.called.length, 1, 'expected the filter function not being called anymore');
});


text:
'use strict';

angular.module('myApp.home', ['ngRoute'])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/home', {
    templateUrl: 'home/home.html',
    controller: 'HomeCtrl'
  });
}])

.controller('HomeCtrl', ['$scope', 'Restangular', function($scope, Restangular) {
    Restangular.all('recipes').customGETLIST().then(function(recipes) {
        $scope.recipes = recipes;
    });

      $scope.getImageUrl = function (src) {
        return src.replace(/http:\/\/.*\/media/, BASE_URL + "/media");
    }

}]);


text:
package com.github.tkurz.sparqlmm.function.general.accessor;

import com.github.tkurz.media.ontology.type.SpatialEntity;
import com.github.tkurz.media.ontology.type.SpatialTemporalEntity;
import com.github.tkurz.sparqlmm.Constants;
import com.github.tkurz.sparqlmm.doc.FunctionDoc;
import com.github.tkurz.sparqlmm.utils.FunctionHelper;
import org.openrdf.model.Value;
import org.openrdf.model.ValueFactory;
import org.openrdf.query.algebra.evaluation.ValueExprEvaluationException;
import org.openrdf.query.algebra.evaluation.function.Function;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;

/**
 * ...
 * <p/>
 * Author: Thomas Kurz (tkurz@apache.org)
 */
@FunctionDoc(title = "MediaFragment", properties = {SpatialTemporalEntity.class}, reference = FunctionDoc.Reference.combined, description = "returns a string representation of a media fragment.", type = FunctionDoc.Type.accessorFunction)
public class MediaFragment implements Function {
    @Override
    public String getURI() {
        return Constants.NAMESPACE + "mediaFragment";
    }

    @Override
    public Value evaluate(ValueFactory valueFactory, Value... values) throws ValueExprEvaluationException {
        if(values.length == 1) {
            try {
                return valueFactory.createLiteral(FunctionHelper.toSpatialTemporalEntity(values[0]).stringValue()); //TODO check
            } catch (IllegalArgumentException | NullPointerException e) {
                return null;
            }
        } else if(values.length == 2) {
            //TODO implement specific to string parameters
            throw new NotImplementedException();
        }

        return null;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<billStatus>
  <bill>
    <calendarNumbers />
    <updateDate>2017-09-11T03:02:10Z</updateDate>
    <cboCostEstimates />
    <policyArea>
      <name>Transportation and Public Works</name>
    </policyArea>
    <relatedBills />
    <billType>S</billType>
    <congress>115</congress>
    <laws />
    <createDate>2017-07-25T01:41:35Z</createDate>
    <originChamber>Senate</originChamber>
    <cosponsors />
    <committees>
      <billCommittees>
        <item>
          <subcommittees />
          <chamber>Senate</chamber>
          <name>Commerce, Science, and Transportation Committee</name>
          <activities>
            <item>
              <name>Referred to</name>
              <date>2017-07-24T23:06:05Z</date>
            </item>
          </activities>
          <type>Standing</type>
          <systemCode>sscm00</systemCode>
        </item>
      </billCommittees>
    </committees>
    <recordedVotes />
    <notes />
    <latestAction>
      <actionDate>2017-07-24</actionDate>
      <text>Read twice and referred to the Committee on Commerce, Science, and Transportation.</text>
      <links />
    </latestAction>
    <actions>
      <item>
        <actionDate>2017-07-24</actionDate>
        <committee>
          <systemCode>sscm00</systemCode>
          <name>Commerce, Science, and Transportation Committee</name>
        </committee>
        <links />
        <sourceSystem>
          <name>Senate</name>
          0
        </sourceSystem>
        <text>Read twice and referred to the Committee on Commerce, Science, and Transportation.</text>
        <type>IntroReferral</type>
      </item>
      <item>
        <type>IntroReferral</type>
        <actionDate>2017-07-24</actionDate>
        <links />
        <text>Introduced in Senate</text>
        <sourceSystem>
          <name>Library of Congress</name>
          9
        </sourceSystem>
        <actionCode>10000</actionCode>
        <committee />
      </item>
      <actionTypeCounts>
        <referredToCommittee>1</referredToCommittee>
        <introducedInSenate>1</introducedInSenate>
      </actionTypeCounts>
      <actionByCounts>
        <senate>2</senate>
      </actionByCounts>
    </actions>
    <titles>
      <item>
        <parentTitleType />
        <titleType>Short Titles as Introduced</titleType>
        <title>Real Transparency in Airfares Act of 2017</title>
        <chamberCode />
        <chamberName />
      </item>
      <item>
        <parentTitleType />
        <titleType>Official Title as Introduced</titleType>
        <title>A bill to increase the maximum penalty for unfair and deceptive practices relating to advertising of the costs of air transportation.</title>
        <chamberCode />
        <chamberName />
      </item>
      <item>
        <parentTitleType />
        <titleType>Display Title</titleType>
        <title>Real Transparency in Airfares Act of 2017</title>
        <chamberCode />
        <chamberName />
      </item>
      <item>
        <parentTitleType />
        <titleType>(Extracted from GPO) Short Titles as Introduced</titleType>
        <title>Real Transparency in Airfares Act of 2017</title>
        <chamberCode />
        <chamberName />
      </item>
    </titles>
    <version>1.0.0</version>
    <subjects>
      <billSubjects>
        <legislativeSubjects />
        <policyArea>
          <name>Transportation and Public Works</name>
        </policyArea>
      </billSubjects>
    </subjects>
    <introducedDate>2017-07-24</introducedDate>
    <sponsors>
      <item>
        <bioguideId>M000639</bioguideId>
        <lastName>MENENDEZ</lastName>
        <state>NJ</state>
        <identifiers>
          <gpoId>8239</gpoId>
          <lisID>791</lisID>
          <bioguideId>M000639</bioguideId>
        </identifiers>
        <byRequestType />
        <firstName>ROBERT</firstName>
        <middleName />
        <party>D</party>
        <fullName>Sen. Menendez, Robert [D-NJ]</fullName>
      </item>
    </sponsors>
    <summaries>
      <billSummaries />
    </summaries>
    <amendments />
    <committeeReports />
    <billNumber>1623</billNumber>
    <title>Real Transparency in Airfares Act of 2017</title>
  </bill>
  <dublinCore xmlns:dc="http://purl.org/dc/elements/1.1/">
    <dc:format>text/xml</dc:format>
    <dc:language>EN</dc:language>
    <dc:rights>Pursuant to Title 17 Section 105 of the United States Code, this file is not subject to copyright protection and is in the public domain.</dc:rights>
    <dc:contributor>Congressional Research Service, Library of Congress</dc:contributor>
    <dc:description>This file contains bill summaries and statuses for federal legislation. A bill summary describes the most significant provisions of a piece of legislation and details the effects the legislative text may have on current law and federal programs. Bill summaries are authored by the Congressional Research Service (CRS) of the Library of Congress. As stated in Public Law 91-510 (2 USC 166 (d)(6)), one of the duties of CRS is "to prepare summaries and digests of bills and resolutions of a public general nature introduced in the Senate or House of Representatives". For more information, refer to the User Guide that accompanies this file.</dc:description>
  </dublinCore>
</billStatus>