text:
namespace ash {

namespace {

// Time in seconds after which we decide that the device has not rebooted
// automatically. If reboot didn't happen during this interval, ask user to
// reboot device manually.
constexpr const base::TimeDelta kWaitForRebootTime = base::Seconds(3);

// Progress bar stages. Each represents progress bar value
// at the beginning of each stage.
// TODO(nkostylev): Base stage progress values on approximate time.
// TODO(nkostylev): Animate progress during each state.
const int kBeforeUpdateCheckProgress = 7;
const int kBeforeDownloadProgress = 14;
const int kBeforeVerifyingProgress = 74;
const int kBeforeFinalizingProgress = 81;
const int kProgressComplete = 100;

// Defines what part of update progress does download part takes.
const int kDownloadProgressIncrement = 60;

// Period of time between planned updates.
constexpr const base::TimeDelta kUpdateTime = base::Seconds(1);

}  // anonymous namespace

VersionUpdater::UpdateInfo::UpdateInfo() {}

VersionUpdater::VersionUpdater(VersionUpdater::Delegate* delegate)
    : delegate_(delegate),
      wait_for_reboot_time_(kWaitForRebootTime),
      tick_clock_(base::DefaultTickClock::GetInstance()) {
  Init();
}

VersionUpdater::~VersionUpdater() {
  DBusThreadManager::Get()->GetUpdateEngineClient()->RemoveObserver(this);
  network_portal_detector::GetInstance()->RemoveObserver(this);
}

void VersionUpdater::Init() {
  time_estimator_ = UpdateTimeEstimator();
  is_first_detection_notification_ = true;
  update_info_ = UpdateInfo();
}

void VersionUpdater::StartNetworkCheck() {
  // If portal detector is enabled and portal detection before AU is
  // allowed, initiate network state check. Otherwise, directly
  // proceed to update.
  if (!network_portal_detector::GetInstance()->IsEnabled()) {
    StartUpdateCheck();
    return;
  }
  update_info_.state = State::STATE_FIRST_PORTAL_CHECK;
  delegate_->UpdateInfoChanged(update_info_);

  is_first_detection_notification_ = true;
  network_portal_detector::GetInstance()->AddAndFireObserver(this);
}

void VersionUpdater::StartUpdateCheck() {
  delegate_->PrepareForUpdateCheck();
  RequestUpdateCheck();
}

void VersionUpdater::SetUpdateOverCellularOneTimePermission() {
  DBusThreadManager::Get()
      ->GetUpdateEngineClient()
      ->SetUpdateOverCellularOneTimePermission(
          update_info_.update_version, update_info_.update_size,
          base::BindOnce(
              &VersionUpdater::OnSetUpdateOverCellularOneTimePermission,
              weak_ptr_factory_.GetWeakPtr()));
}

void VersionUpdater::RejectUpdateOverCellular() {
  // Reset UI context to show curtain again when the user goes back to the
  // screen.
  update_info_.progress_unavailable = true;
  update_info_.requires_permission_for_cellular = false;
  delegate_->UpdateInfoChanged(update_info_);
}

void VersionUpdater::RebootAfterUpdate() {
  VLOG(1) << "Initiate reboot after update";
  DBusThreadManager::Get()->GetUpdateEngineClient()->RebootAfterUpdate();
  if (wait_for_reboot_time_.is_zero())  // Primarily for testing.
    OnWaitForRebootTimeElapsed();
  else
    reboot_timer_.Start(FROM_HERE, wait_for_reboot_time_, this,
                        &VersionUpdater::OnWaitForRebootTimeElapsed);
}

void VersionUpdater::StartExitUpdate(Result result) {
  DBusThreadManager::Get()->GetUpdateEngineClient()->RemoveObserver(this);
  network_portal_detector::GetInstance()->RemoveObserver(this);
  delegate_->FinishExitUpdate(result);
  // Reset internal state, because in case of error user may make another
  // update attempt.
  Init();
}

base::OneShotTimer* VersionUpdater::GetRebootTimerForTesting() {
  return &reboot_timer_;
}

void VersionUpdater::GetEolInfo(EolInfoCallback callback) {
  UpdateEngineClient* update_engine_client =
      DBusThreadManager::Get()->GetUpdateEngineClient();
  // Request the End of Life (Auto Update Expiration) status. Bind to a weak_ptr
  // bound method rather than passing `callback` directly so that `callback`
  // does not outlive `this`.
  update_engine_client->GetEolInfo(
      base::BindOnce(&VersionUpdater::OnGetEolInfo,
                     weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
}

void VersionUpdater::OnGetEolInfo(EolInfoCallback callback,
                                  UpdateEngineClient::EolInfo info) {
  std::move(callback).Run(std::move(info));
}

void VersionUpdater::UpdateStatusChangedForTesting(
    const update_engine::StatusResult& status) {
  UpdateStatusChanged(status);
}

void VersionUpdater::RequestUpdateCheck() {
  update_info_.state = State::STATE_UPDATE;
  update_info_.progress = kBeforeUpdateCheckProgress;
  update_info_.update_version = std::string();
  update_info_.update_size = 0;
  delegate_->UpdateInfoChanged(update_info_);

  network_portal_detector::GetInstance()->RemoveObserver(this);
  DBusThreadManager::Get()->GetUpdateEngineClient()->AddObserver(this);
  VLOG(1) << "Initiate update check";
  DBusThreadManager::Get()->GetUpdateEngineClient()->RequestUpdateCheck(
      base::BindOnce(&VersionUpdater::OnUpdateCheckStarted,
                     weak_ptr_factory_.GetWeakPtr()));
}

void VersionUpdater::UpdateStatusChanged(
    const update_engine::StatusResult& status) {
  update_info_.status = status;

  if (update_info_.is_checking_for_update &&
      status.current_operation() >
          update_engine::Operation::CHECKING_FOR_UPDATE &&
      status.current_operation() != update_engine::Operation::ERROR &&
      status.current_operation() !=
          update_engine::Operation::REPORTING_ERROR_EVENT) {
    update_info_.is_checking_for_update = false;
  }
  if (ignore_idle_status_ &&
      status.current_operation() > update_engine::Operation::IDLE) {
    ignore_idle_status_ = false;
  }

  time_estimator_.Update(status);

  bool exit_update = false;
  switch (status.current_operation()) {
    case update_engine::Operation::CHECKING_FOR_UPDATE:
      break;
    case update_engine::Operation::UPDATE_AVAILABLE:
      update_info_.progress = kBeforeDownloadProgress;
      update_info_.progress_message =
          l10n_util::GetStringUTF16(IDS_UPDATE_AVAILABLE);
      update_info_.show_estimated_time_left = false;
      update_info_.progress_unavailable = false;
      break;
    case update_engine::Operation::DOWNLOADING:
      update_info_.progress_message =
          l10n_util::GetStringUTF16(IDS_INSTALLING_UPDATE);
      update_info_.progress_unavailable = false;
      update_info_.progress =
          kBeforeDownloadProgress +
          static_cast<int>(status.progress() * kDownloadProgressIncrement);
      update_info_.show_estimated_time_left = time_estimator_.HasDownloadTime();
      update_info_.estimated_time_left_in_secs =
          time_estimator_.GetDownloadTimeLeft().InSeconds();
      break;
    case update_engine::Operation::VERIFYING:
      update_info_.progress = kBeforeVerifyingProgress;
      update_info_.progress_message =
          l10n_util::GetStringUTF16(IDS_UPDATE_VERIFYING);
      update_info_.show_estimated_time_left = false;
      break;
    case update_engine::Operation::FINALIZING:
      update_info_.progress = kBeforeFinalizingProgress;
      update_info_.progress_message =
          l10n_util::GetStringUTF16(IDS_UPDATE_FINALIZING);
      update_info_.show_estimated_time_left = false;
      break;
    case update_engine::Operation::UPDATED_NEED_REBOOT:
      update_info_.progress = kProgressComplete;
      update_info_.show_estimated_time_left = false;
      update_info_.progress_unavailable = false;
      break;
    case update_engine::Operation::NEED_PERMISSION_TO_UPDATE:
      VLOG(1) << "Update requires user permission to proceed.";
      update_info_.state = State::STATE_REQUESTING_USER_PERMISSION;
      update_info_.update_version = status.new_version();
      update_info_.update_size = status.new_size();
      update_info_.requires_permission_for_cellular = true;
      update_info_.progress_unavailable = false;

      DBusThreadManager::Get()->GetUpdateEngineClient()->RemoveObserver(this);
      break;
    case update_engine::Operation::ATTEMPTING_ROLLBACK:
      VLOG(1) << "Attempting rollback";
      break;
    case update_engine::Operation::IDLE:
      // Exit update only if update engine was in non-idle status before.
      // Otherwise, it's possible that the update request has not yet been
      // started.
      if (!ignore_idle_status_)
        exit_update = true;
      break;
    case update_engine::Operation::DISABLED:
    case update_engine::Operation::ERROR:
    case update_engine::Operation::REPORTING_ERROR_EVENT:
      break;
    default:
      NOTREACHED();
  }

  if (time_estimator_.HasTotalTime(status.current_operation())) {
    const auto update_status = time_estimator_.GetUpdateStatus();
    update_info_.total_time_left = update_status.time_left;
    update_info_.better_update_progress = update_status.progress;
    if (!refresh_timer_) {
      refresh_timer_ = std::make_unique<base::RepeatingTimer>(tick_clock_);
      refresh_timer_->Start(FROM_HERE, kUpdateTime, this,
                            &VersionUpdater::RefreshTimeLeftEstimation);
    }
  } else {
    if (refresh_timer_) {
      refresh_timer_->Stop();
      refresh_timer_.reset();
    }
  }

  delegate_->UpdateInfoChanged(update_info_);
  if (exit_update)
    StartExitUpdate(Result::UPDATE_NOT_REQUIRED);
}

void VersionUpdater::RefreshTimeLeftEstimation() {
  const auto update_status = time_estimator_.GetUpdateStatus();
  update_info_.total_time_left = update_status.time_left;
  update_info_.better_update_progress = update_status.progress;
  delegate_->UpdateInfoChanged(update_info_);
}

void VersionUpdater::OnPortalDetectionCompleted(
    const NetworkState* network,
    const NetworkPortalDetector::CaptivePortalStatus status) {
  VLOG(1) << "VersionUpdater::OnPortalDetectionCompleted(): "
          << "network=" << (network ? network->path() : "") << ", "
          << "status=" << status;

  // Wait for sane detection results.
  if (network &&
      status == NetworkPortalDetector::CAPTIVE_PORTAL_STATUS_UNKNOWN) {
    return;
  }

  // Restart portal detection for the first notification about offline state.
  if ((!network ||
       status == NetworkPortalDetector::CAPTIVE_PORTAL_STATUS_OFFLINE) &&
      is_first_detection_notification_) {
    is_first_detection_notification_ = false;
    base::ThreadTaskRunnerHandle::Get()->PostTask(
        FROM_HERE, base::BindOnce([]() {
          network_portal_detector::GetInstance()->StartPortalDetection();
        }));
    return;
  }
  is_first_detection_notification_ = false;

  if (update_info_.state == State::STATE_ERROR) {
    // In the case of online state hide error message and proceed to
    // the update stage. Otherwise, update error message content.
    if (status == NetworkPortalDetector::CAPTIVE_PORTAL_STATUS_ONLINE)
      StartUpdateCheck();
    else
      UpdateErrorMessage(network, status);
  } else if (update_info_.state == State::STATE_FIRST_PORTAL_CHECK) {
    // In the case of online state immediately proceed to the update
    // stage. Otherwise, prepare and show error message.
    if (status == NetworkPortalDetector::CAPTIVE_PORTAL_STATUS_ONLINE) {
      StartUpdateCheck();
    } else {
      UpdateErrorMessage(network, status);

      // StartUpdateCheck, which gets called when the error clears up, will add
      // the update engine observer back.
      DBusThreadManager::Get()->GetUpdateEngineClient()->RemoveObserver(this);

      update_info_.state = State::STATE_ERROR;
      delegate_->UpdateInfoChanged(update_info_);
      if (status == NetworkPortalDetector::CAPTIVE_PORTAL_STATUS_PORTAL)
        delegate_->DelayErrorMessage();
      else
        delegate_->ShowErrorMessage();
    }
  }
}

void VersionUpdater::OnWaitForRebootTimeElapsed() {
  delegate_->OnWaitForRebootTimeElapsed();
}

void VersionUpdater::UpdateErrorMessage(
    const NetworkState* network,
    const NetworkPortalDetector::CaptivePortalStatus status) {
  std::string network_name = std::string();
  NetworkError::ErrorState error_state;
  switch (status) {
    case NetworkPortalDetector::CAPTIVE_PORTAL_STATUS_UNKNOWN:
    case NetworkPortalDetector::CAPTIVE_PORTAL_STATUS_OFFLINE:
      error_state = NetworkError::ERROR_STATE_OFFLINE;
      break;
    case NetworkPortalDetector::CAPTIVE_PORTAL_STATUS_PORTAL:
      DCHECK(network);
      error_state = NetworkError::ERROR_STATE_PORTAL;
      network_name = network->name();
      break;
    case NetworkPortalDetector::CAPTIVE_PORTAL_STATUS_PROXY_AUTH_REQUIRED:
      error_state = NetworkError::ERROR_STATE_PROXY;
      break;
    default:
      NOTREACHED();
      return;
  }
  delegate_->UpdateErrorMessage(status, error_state, network_name);
}

void VersionUpdater::OnSetUpdateOverCellularOneTimePermission(bool success) {
  update_info_.requires_permission_for_cellular = false;
  if (!success) {
    // Reset UI context to show curtain again when the user goes back to the
    // screen.
    update_info_.progress_unavailable = true;
  }
  delegate_->UpdateInfoChanged(update_info_);

  if (success) {
    StartUpdateCheck();
  } else {
    StartExitUpdate(Result::UPDATE_ERROR);
  }
}

void VersionUpdater::OnUpdateCheckStarted(
    UpdateEngineClient::UpdateCheckResult result) {
  VLOG(1) << "Callback from RequestUpdateCheck, result " << result;
  if (result != UpdateEngineClient::UPDATE_RESULT_SUCCESS)
    StartExitUpdate(Result::UPDATE_NOT_REQUIRED);
}

}  // namespace ash


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>OrderCallback (OlePaySDK-iAppPay)</title>
<meta name="date" content="2015-11-24">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

您的浏览器已禁用 JavaScript。

跳过导航链接

概览

程序包

类

树

已过时

索引

帮助

上一个类

下一个类

框架

无框架

所有类

概要:

嵌套 |

字段 |

构造器 |

方法

详细资料:

字段 |

构造器 |

方法

com.olemob.paysdk.interfaces

接口 OrderCallback

public interface OrderCallback

订单回调接口

从以下版本开始:

2015年8月4日

方法概要

所有方法 实例方法 抽象方法

限定符和类型
方法和说明

void
onResult(OrderInfo order,
        java.lang.String msg)

请求订单的结果。

方法详细资料

onResult

void onResult(OrderInfo order,
              java.lang.String msg)

请求订单的结果。

参数:

order -

从以下版本开始:

2015年8月4日

跳过导航链接

概览

程序包

类

树

已过时

索引

帮助

上一个类

下一个类

框架

无框架

所有类

概要:

嵌套 |

字段 |

构造器 |

方法

详细资料:

字段 |

构造器 |

方法

redpajama_set_name: RedPajamaGithub


text: yum install -y openstack-nova* openstack-utils


text:
package adoc

import (
	"bytes"
	"crypto/tls"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"math/rand"
	"net/http"
	"net/url"
	"strings"
	"sync"
	"time"
)

type AuthConfig struct {
	UserName string `json:"username,omitempty"`
	Password string `json:"password,omitempty"`
	Email    string `json:"email,omitempty"`
}

func (auth AuthConfig) Encode() string {
	var buffer bytes.Buffer
	json.NewEncoder(&buffer).Encode(auth)
	return base64.URLEncoding.EncodeToString(buffer.Bytes())
}

type Error struct {
	StatusCode int
	Status     string
}

func (e Error) Error() string {
	return fmt.Sprintf("%d: %s", e.StatusCode, e.Status)
}

func IsNotFound(err error) bool {
	if adocErr, ok := err.(Error); ok {
		return adocErr.StatusCode == 404
	}
	return false
}

func IsServerInternalError(err error) bool {
	if adocErr, ok := err.(Error); ok {
		return adocErr.StatusCode == 500
	}
	return false
}

const (
	kDefaultApiVersion = "v1.17"
	kDefaultTimeout    = 30
	kDefaultRWTimeout  = 60
)

var apiVersions = map[string]bool{
	"v1.17": true,
	"v1.18": true,
}

type DockerClient struct {
	daemonUrl      *url.URL
	httpClient     *http.Client
	longpollClient *http.Client
	tlsConfig      *tls.Config
	apiVersion     string
	isSwarm        bool

	monitorLock sync.RWMutex
	monitors    map[int64]struct{}
}

func NewSwarmClient(swarmUrl string, tlsConfig *tls.Config, apiVersion ...string) (*DockerClient, error) {
	return NewSwarmClientTimeout(swarmUrl, tlsConfig,
		time.Duration(kDefaultTimeout*time.Second),
		time.Duration(kDefaultRWTimeout*time.Second),
		apiVersion...)
}

func NewSwarmClientTimeout(swarmUrl string, tlsConfig *tls.Config, timeout time.Duration, rwTimeout time.Duration, apiVersion ...string) (*DockerClient, error) {
	docker, err := NewDockerClientTimeout(swarmUrl, tlsConfig, timeout, rwTimeout, apiVersion...)
	docker.isSwarm = true
	return docker, err
}

func NewDockerClient(daemonUrl string, tlsConfig *tls.Config, apiVersion ...string) (*DockerClient, error) {
	return NewDockerClientTimeout(daemonUrl, tlsConfig,
		time.Duration(kDefaultTimeout*time.Second),
		time.Duration(kDefaultRWTimeout*time.Second),
		apiVersion...)
}

func NewDockerClientTimeout(daemonUrl string, tlsConfig *tls.Config, timeout time.Duration, rwTimeout time.Duration, apiVersion ...string) (*DockerClient, error) {
	u, err := url.Parse(daemonUrl)
	if err != nil {
		return nil, err
	}
	if u.Scheme == "" || u.Scheme == "tcp" {
		if tlsConfig == nil {
			u.Scheme = "http"
		} else {
			u.Scheme = "https"
		}
	}
	httpClient := newHttpClient(u, tlsConfig, timeout, rwTimeout)
	longpollClient := newHttpClient(u, tlsConfig, timeout, 0)
	clientApiVersion := kDefaultApiVersion
	if len(apiVersion) > 0 && apiVersion[0] != "" {
		clientApiVersion = apiVersion[0]
		if !strings.HasPrefix(clientApiVersion, "v") {
			clientApiVersion = "v" + clientApiVersion
		}
	}
	if _, checked := apiVersions[clientApiVersion]; !checked {
		err = fmt.Errorf("*WARNING: Adoc haven't check out if the remote api version %s is supported, maybe not stable, but you can keep using the client anyway.", clientApiVersion)
	}
	return &DockerClient{
		daemonUrl:      u,
		httpClient:     httpClient,
		longpollClient: longpollClient,
		tlsConfig:      tlsConfig,
		apiVersion:     clientApiVersion,
		monitors:       make(map[int64]struct{}),
	}, err
}

type responseCallback func(resp *http.Response) error

func (client *DockerClient) sendRequestCallback(method string, path string, body []byte, headers map[string]string, callback responseCallback, isLongpoll ...bool) error {
	b := bytes.NewBuffer(body)
	urlPath := fmt.Sprintf("%s/%s/%s", client.daemonUrl.String(), client.apiVersion, path)
	logger.Debugf("SendRequest %q, [%s]", method, urlPath)
	req, err := http.NewRequest(method, urlPath, b)
	if err != nil {
		return err
	}
	req.Header.Add("Content-Type", "application/json")
	if headers != nil {
		for key, value := range headers {
			req.Header.Add(key, value)
		}
	}
	httpClient := client.httpClient
	if len(isLongpoll) > 0 && isLongpoll[0] {
		httpClient = client.longpollClient
	}
	resp, err := httpClient.Do(req)
	if err != nil {
		if !strings.Contains(err.Error(), "connection refused") && client.tlsConfig == nil {
			return fmt.Errorf("%v. Are you trying to connect to a TLS-enabled daemon without TLS?", err)
		}
		return err
	}
	if resp.StatusCode >= 400 {
		return Error{resp.StatusCode, resp.Status}
	}

	defer resp.Body.Close()
	return callback(resp)
}

func (client *DockerClient) sendRequest(method string, path string, body []byte, headers map[string]string, isLongpoll ...bool) ([]byte, error) {
	var data []byte
	err := client.sendRequestCallback(method, path, body, headers, func(resp *http.Response) error {
		var cbErr error
		if data, cbErr = ioutil.ReadAll(resp.Body); cbErr != nil {
			return cbErr
		}
		return nil
	}, isLongpoll...)
	return data, err
}

var random *rand.Rand

func init() {
	random = rand.New(rand.NewSource(time.Now().UnixNano()))
}


text:
using namespace lldb;
using namespace lldb_private;

SBFrame::SBFrame() : m_opaque_sp(new ExecutionContextRef()) {
  LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBFrame);
}

SBFrame::SBFrame(const StackFrameSP &lldb_object_sp)
    : m_opaque_sp(new ExecutionContextRef(lldb_object_sp)) {
  LLDB_RECORD_CONSTRUCTOR(SBFrame, (const lldb::StackFrameSP &),
                          lldb_object_sp);
}

SBFrame::SBFrame(const SBFrame &rhs) : m_opaque_sp() {
  LLDB_RECORD_CONSTRUCTOR(SBFrame, (const lldb::SBFrame &), rhs);

  m_opaque_sp = clone(rhs.m_opaque_sp);
}

SBFrame::~SBFrame() = default;

const SBFrame &SBFrame::operator=(const SBFrame &rhs) {
  LLDB_RECORD_METHOD(const lldb::SBFrame &,
                     SBFrame, operator=,(const lldb::SBFrame &), rhs);

  if (this != &rhs)
    m_opaque_sp = clone(rhs.m_opaque_sp);
  return LLDB_RECORD_RESULT(*this);
}

StackFrameSP SBFrame::GetFrameSP() const {
  return (m_opaque_sp ? m_opaque_sp->GetFrameSP() : StackFrameSP());
}

void SBFrame::SetFrameSP(const StackFrameSP &lldb_object_sp) {
  return m_opaque_sp->SetFrameSP(lldb_object_sp);
}

bool SBFrame::IsValid() const {
  LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBFrame, IsValid);
  return this->operator bool();
}
SBFrame::operator bool() const {
  LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBFrame, operator bool);

  std::unique_lock<std::recursive_mutex> lock;
  ExecutionContext exe_ctx(m_opaque_sp.get(), lock);

  Target *target = exe_ctx.GetTargetPtr();
  Process *process = exe_ctx.GetProcessPtr();
  if (target && process) {
    Process::StopLocker stop_locker;
    if (stop_locker.TryLock(&process->GetRunLock()))
      return GetFrameSP().get() != nullptr;
  }

  // Without a target & process we can't have a valid stack frame.
  return false;
}

SBSymbolContext SBFrame::GetSymbolContext(uint32_t resolve_scope) const {
  LLDB_RECORD_METHOD_CONST(lldb::SBSymbolContext, SBFrame, GetSymbolContext,
                           (uint32_t), resolve_scope);

  SBSymbolContext sb_sym_ctx;
  std::unique_lock<std::recursive_mutex> lock;
  ExecutionContext exe_ctx(m_opaque_sp.get(), lock);
  SymbolContextItem scope = static_cast<SymbolContextItem>(resolve_scope);
  StackFrame *frame = nullptr;
  Target *target = exe_ctx.GetTargetPtr();
  Process *process = exe_ctx.GetProcessPtr();
  if (target && process) {
    Process::StopLocker stop_locker;
    if (stop_locker.TryLock(&process->GetRunLock())) {
      frame = exe_ctx.GetFramePtr();
      if (frame)
        sb_sym_ctx.SetSymbolContext(&frame->GetSymbolContext(scope));
    }
  }

  return LLDB_RECORD_RESULT(sb_sym_ctx);
}

SBModule SBFrame::GetModule() const {
  LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::SBModule, SBFrame, GetModule);

  SBModule sb_module;
  ModuleSP module_sp;
  std::unique_lock<std::recursive_mutex> lock;
  ExecutionContext exe_ctx(m_opaque_sp.get(), lock);

  StackFrame *frame = nullptr;
  Target *target = exe_ctx.GetTargetPtr();
  Process *process = exe_ctx.GetProcessPtr();
  if (target && process) {
    Process::StopLocker stop_locker;
    if (stop_locker.TryLock(&process->GetRunLock())) {
      frame = exe_ctx.GetFramePtr();
      if (frame) {
        module_sp = frame->GetSymbolContext(eSymbolContextModule).module_sp;
        sb_module.SetSP(module_sp);
      }
    }
  }

  return LLDB_RECORD_RESULT(sb_module);
}

SBCompileUnit SBFrame::GetCompileUnit() const {
  LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::SBCompileUnit, SBFrame,
                                   GetCompileUnit);

  SBCompileUnit sb_comp_unit;
  std::unique_lock<std::recursive_mutex> lock;
  ExecutionContext exe_ctx(m_opaque_sp.get(), lock);

  StackFrame *frame = nullptr;
  Target *target = exe_ctx.GetTargetPtr();
  Process *process = exe_ctx.GetProcessPtr();
  if (target && process) {
    Process::StopLocker stop_locker;
    if (stop_locker.TryLock(&process->GetRunLock())) {
      frame = exe_ctx.GetFramePtr();
      if (frame) {
        sb_comp_unit.reset(
            frame->GetSymbolContext(eSymbolContextCompUnit).comp_unit);
      }
    }
  }

  return LLDB_RECORD_RESULT(sb_comp_unit);
}

SBFunction SBFrame::GetFunction() const {
  LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::SBFunction, SBFrame, GetFunction);

  SBFunction sb_function;
  std::unique_lock<std::recursive_mutex> lock;
  ExecutionContext exe_ctx(m_opaque_sp.get(), lock);

  StackFrame *frame = nullptr;
  Target *target = exe_ctx.GetTargetPtr();
  Process *process = exe_ctx.GetProcessPtr();
  if (target && process) {
    Process::StopLocker stop_locker;
    if (stop_locker.TryLock(&process->GetRunLock())) {
      frame = exe_ctx.GetFramePtr();
      if (frame) {
        sb_function.reset(
            frame->GetSymbolContext(eSymbolContextFunction).function);
      }
    }
  }

  return LLDB_RECORD_RESULT(sb_function);
}

SBSymbol SBFrame::GetSymbol() const {
  LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::SBSymbol, SBFrame, GetSymbol);

  SBSymbol sb_symbol;
  std::unique_lock<std::recursive_mutex> lock;
  ExecutionContext exe_ctx(m_opaque_sp.get(), lock);

  StackFrame *frame = nullptr;
  Target *target = exe_ctx.GetTargetPtr();
  Process *process = exe_ctx.GetProcessPtr();
  if (target && process) {
    Process::StopLocker stop_locker;
    if (stop_locker.TryLock(&process->GetRunLock())) {
      frame = exe_ctx.GetFramePtr();
      if (frame) {
        sb_symbol.reset(frame->GetSymbolContext(eSymbolContextSymbol).symbol);
      }
    }
  }

  return LLDB_RECORD_RESULT(sb_symbol);
}

SBBlock SBFrame::GetBlock() const {
  LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::SBBlock, SBFrame, GetBlock);

  SBBlock sb_block;
  std::unique_lock<std::recursive_mutex> lock;
  ExecutionContext exe_ctx(m_opaque_sp.get(), lock);

  StackFrame *frame = nullptr;
  Target *target = exe_ctx.GetTargetPtr();
  Process *process = exe_ctx.GetProcessPtr();
  if (target && process) {
    Process::StopLocker stop_locker;
    if (stop_locker.TryLock(&process->GetRunLock())) {
      frame = exe_ctx.GetFramePtr();
      if (frame)
        sb_block.SetPtr(frame->GetSymbolContext(eSymbolContextBlock).block);
    }
  }
  return LLDB_RECORD_RESULT(sb_block);
}

SBBlock SBFrame::GetFrameBlock() const {
  LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::SBBlock, SBFrame, GetFrameBlock);

  SBBlock sb_block;
  std::unique_lock<std::recursive_mutex> lock;
  ExecutionContext exe_ctx(m_opaque_sp.get(), lock);

  StackFrame *frame = nullptr;
  Target *target = exe_ctx.GetTargetPtr();
  Process *process = exe_ctx.GetProcessPtr();
  if (target && process) {
    Process::StopLocker stop_locker;
    if (stop_locker.TryLock(&process->GetRunLock())) {
      frame = exe_ctx.GetFramePtr();
      if (frame)
        sb_block.SetPtr(frame->GetFrameBlock());
    }
  }
  return LLDB_RECORD_RESULT(sb_block);
}

SBLineEntry SBFrame::GetLineEntry() const {
  LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::SBLineEntry, SBFrame, GetLineEntry);

  SBLineEntry sb_line_entry;
  std::unique_lock<std::recursive_mutex> lock;
  ExecutionContext exe_ctx(m_opaque_sp.get(), lock);

  StackFrame *frame = nullptr;
  Target *target = exe_ctx.GetTargetPtr();
  Process *process = exe_ctx.GetProcessPtr();
  if (target && process) {
    Process::StopLocker stop_locker;
    if (stop_locker.TryLock(&process->GetRunLock())) {
      frame = exe_ctx.GetFramePtr();
      if (frame) {
        sb_line_entry.SetLineEntry(
            frame->GetSymbolContext(eSymbolContextLineEntry).line_entry);
      }
    }
  }
  return LLDB_RECORD_RESULT(sb_line_entry);
}

uint32_t SBFrame::GetFrameID() const {
  LLDB_RECORD_METHOD_CONST_NO_ARGS(uint32_t, SBFrame, GetFrameID);

  uint32_t frame_idx = UINT32_MAX;

  std::unique_lock<std::recursive_mutex> lock;
  ExecutionContext exe_ctx(m_opaque_sp.get(), lock);

  StackFrame *frame = exe_ctx.GetFramePtr();
  if (frame)
    frame_idx = frame->GetFrameIndex();

  return frame_idx;
}

lldb::addr_t SBFrame::GetCFA() const {
  LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::addr_t, SBFrame, GetCFA);

  std::unique_lock<std::recursive_mutex> lock;
  ExecutionContext exe_ctx(m_opaque_sp.get(), lock);

  StackFrame *frame = exe_ctx.GetFramePtr();
  if (frame)
    return frame->GetStackID().GetCallFrameAddress();
  return LLDB_INVALID_ADDRESS;
}

addr_t SBFrame::GetPC() const {
  LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::addr_t, SBFrame, GetPC);

  addr_t addr = LLDB_INVALID_ADDRESS;
  std::unique_lock<std::recursive_mutex> lock;
  ExecutionContext exe_ctx(m_opaque_sp.get(), lock);

  StackFrame *frame = nullptr;
  Target *target = exe_ctx.GetTargetPtr();
  Process *process = exe_ctx.GetProcessPtr();
  if (target && process) {
    Process::StopLocker stop_locker;
    if (stop_locker.TryLock(&process->GetRunLock())) {
      frame = exe_ctx.GetFramePtr();
      if (frame) {
        addr = frame->GetFrameCodeAddress().GetOpcodeLoadAddress(
            target, AddressClass::eCode);
      }
    }
  }

  return addr;
}

bool SBFrame::SetPC(addr_t new_pc) {
  LLDB_RECORD_METHOD(bool, SBFrame, SetPC, (lldb::addr_t), new_pc);

  bool ret_val = false;
  std::unique_lock<std::recursive_mutex> lock;
  ExecutionContext exe_ctx(m_opaque_sp.get(), lock);

  StackFrame *frame = nullptr;
  Target *target = exe_ctx.GetTargetPtr();
  Process *process = exe_ctx.GetProcessPtr();
  if (target && process) {
    Process::StopLocker stop_locker;
    if (stop_locker.TryLock(&process->GetRunLock())) {
      frame = exe_ctx.GetFramePtr();
      if (frame) {
        ret_val = frame->GetRegisterContext()->SetPC(new_pc);
      }
    }
  }

  return ret_val;
}

addr_t SBFrame::GetSP() const {
  LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::addr_t, SBFrame, GetSP);

  addr_t addr = LLDB_INVALID_ADDRESS;
  std::unique_lock<std::recursive_mutex> lock;
  ExecutionContext exe_ctx(m_opaque_sp.get(), lock);

  StackFrame *frame = nullptr;
  Target *target = exe_ctx.GetTargetPtr();
  Process *process = exe_ctx.GetProcessPtr();
  if (target && process) {
    Process::StopLocker stop_locker;
    if (stop_locker.TryLock(&process->GetRunLock())) {
      frame = exe_ctx.GetFramePtr();
      if (frame) {
        addr = frame->GetRegisterContext()->GetSP();
      }
    }
  }

  return addr;
}

addr_t SBFrame::GetFP() const {
  LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::addr_t, SBFrame, GetFP);

  addr_t addr = LLDB_INVALID_ADDRESS;
  std::unique_lock<std::recursive_mutex> lock;
  ExecutionContext exe_ctx(m_opaque_sp.get(), lock);

  StackFrame *frame = nullptr;
  Target *target = exe_ctx.GetTargetPtr();
  Process *process = exe_ctx.GetProcessPtr();
  if (target && process) {
    Process::StopLocker stop_locker;
    if (stop_locker.TryLock(&process->GetRunLock())) {
      frame = exe_ctx.GetFramePtr();
      if (frame)
        addr = frame->GetRegisterContext()->GetFP();
    }
  }

  return addr;
}

SBAddress SBFrame::GetPCAddress() const {
  LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::SBAddress, SBFrame, GetPCAddress);

  SBAddress sb_addr;
  std::unique_lock<std::recursive_mutex> lock;
  ExecutionContext exe_ctx(m_opaque_sp.get(), lock);

  StackFrame *frame = exe_ctx.GetFramePtr();
  Target *target = exe_ctx.GetTargetPtr();
  Process *process = exe_ctx.GetProcessPtr();
  if (target && process) {
    Process::StopLocker stop_locker;
    if (stop_locker.TryLock(&process->GetRunLock())) {
      frame = exe_ctx.GetFramePtr();
      if (frame)
        sb_addr.SetAddress(&frame->GetFrameCodeAddress());
    }
  }
  return LLDB_RECORD_RESULT(sb_addr);
}

void SBFrame::Clear() {
  LLDB_RECORD_METHOD_NO_ARGS(void, SBFrame, Clear);

  m_opaque_sp->Clear();
}

lldb::SBValue SBFrame::GetValueForVariablePath(const char *var_path) {
  LLDB_RECORD_METHOD(lldb::SBValue, SBFrame, GetValueForVariablePath,
                     (const char *), var_path);

  SBValue sb_value;
  std::unique_lock<std::recursive_mutex> lock;
  ExecutionContext exe_ctx(m_opaque_sp.get(), lock);

  StackFrame *frame = exe_ctx.GetFramePtr();
  Target *target = exe_ctx.GetTargetPtr();
  if (frame && target) {
    lldb::DynamicValueType use_dynamic =
        frame->CalculateTarget()->GetPreferDynamicValue();
    sb_value = GetValueForVariablePath(var_path, use_dynamic);
  }
  return LLDB_RECORD_RESULT(sb_value);
}

lldb::SBValue SBFrame::GetValueForVariablePath(const char *var_path,
                                               DynamicValueType use_dynamic) {
  LLDB_RECORD_METHOD(lldb::SBValue, SBFrame, GetValueForVariablePath,
                     (const char *, lldb::DynamicValueType), var_path,
                     use_dynamic);

  SBValue sb_value;
  if (var_path == nullptr || var_path[0] == '\0') {
    return LLDB_RECORD_RESULT(sb_value);
  }

  std::unique_lock<std::recursive_mutex> lock;
  ExecutionContext exe_ctx(m_opaque_sp.get(), lock);

  StackFrame *frame = nullptr;
  Target *target = exe_ctx.GetTargetPtr();
  Process *process = exe_ctx.GetProcessPtr();
  if (target && process) {
    Process::StopLocker stop_locker;
    if (stop_locker.TryLock(&process->GetRunLock())) {
      frame = exe_ctx.GetFramePtr();
      if (frame) {
        VariableSP var_sp;
        Status error;
        ValueObjectSP value_sp(frame->GetValueForVariableExpressionPath(
            var_path, eNoDynamicValues,
            StackFrame::eExpressionPathOptionCheckPtrVsMember |
                StackFrame::eExpressionPathOptionsAllowDirectIVarAccess,
            var_sp, error));
        sb_value.SetSP(value_sp, use_dynamic);
      }
    }
  }
  return LLDB_RECORD_RESULT(sb_value);
}

SBValue SBFrame::FindVariable(const char *name) {
  LLDB_RECORD_METHOD(lldb::SBValue, SBFrame, FindVariable, (const char *),
                     name);

  SBValue value;
  std::unique_lock<std::recursive_mutex> lock;
  ExecutionContext exe_ctx(m_opaque_sp.get(), lock);

  StackFrame *frame = exe_ctx.GetFramePtr();
  Target *target = exe_ctx.GetTargetPtr();
  if (frame && target) {
    lldb::DynamicValueType use_dynamic =
        frame->CalculateTarget()->GetPreferDynamicValue();
    value = FindVariable(name, use_dynamic);
  }
  return LLDB_RECORD_RESULT(value);
}

SBValue SBFrame::FindVariable(const char *name,
                              lldb::DynamicValueType use_dynamic) {
  LLDB_RECORD_METHOD(lldb::SBValue, SBFrame, FindVariable,
                     (const char *, lldb::DynamicValueType), name, use_dynamic);

  VariableSP var_sp;
  SBValue sb_value;

  if (name == nullptr || name[0] == '\0') {
    return LLDB_RECORD_RESULT(sb_value);
  }

  ValueObjectSP value_sp;
  std::unique_lock<std::recursive_mutex> lock;
  ExecutionContext exe_ctx(m_opaque_sp.get(), lock);

  StackFrame *frame = nullptr;
  Target *target = exe_ctx.GetTargetPtr();
  Process *process = exe_ctx.GetProcessPtr();
  if (target && process) {
    Process::StopLocker stop_locker;
    if (stop_locker.TryLock(&process->GetRunLock())) {
      frame = exe_ctx.GetFramePtr();
      if (frame) {
        value_sp = frame->FindVariable(ConstString(name));

        if (value_sp)
          sb_value.SetSP(value_sp, use_dynamic);
      }
    }
  }

  return LLDB_RECORD_RESULT(sb_value);
}

SBValue SBFrame::FindValue(const char *name, ValueType value_type) {
  LLDB_RECORD_METHOD(lldb::SBValue, SBFrame, FindValue,
                     (const char *, lldb::ValueType), name, value_type);

  SBValue value;
  std::unique_lock<std::recursive_mutex> lock;
  ExecutionContext exe_ctx(m_opaque_sp.get(), lock);

  StackFrame *frame = exe_ctx.GetFramePtr();
  Target *target = exe_ctx.GetTargetPtr();
  if (frame && target) {
    lldb::DynamicValueType use_dynamic =
        frame->CalculateTarget()->GetPreferDynamicValue();
    value = FindValue(name, value_type, use_dynamic);
  }
  return LLDB_RECORD_RESULT(value);
}

SBValue SBFrame::FindValue(const char *name, ValueType value_type,
                           lldb::DynamicValueType use_dynamic) {
  LLDB_RECORD_METHOD(lldb::SBValue, SBFrame, FindValue,
                     (const char *, lldb::ValueType, lldb::DynamicValueType),
                     name, value_type, use_dynamic);

  SBValue sb_value;

  if (name == nullptr || name[0] == '\0') {
    return LLDB_RECORD_RESULT(sb_value);
  }

  ValueObjectSP value_sp;
  std::unique_lock<std::recursive_mutex> lock;
  ExecutionContext exe_ctx(m_opaque_sp.get(), lock);

  StackFrame *frame = nullptr;
  Target *target = exe_ctx.GetTargetPtr();
  Process *process = exe_ctx.GetProcessPtr();
  if (target && process) {
    Process::StopLocker stop_locker;
    if (stop_locker.TryLock(&process->GetRunLock())) {
      frame = exe_ctx.GetFramePtr();
      if (frame) {
        VariableList variable_list;

        switch (value_type) {
        case eValueTypeVariableGlobal:      // global variable
        case eValueTypeVariableStatic:      // static variable
        case eValueTypeVariableArgument:    // function argument variables
        case eValueTypeVariableLocal:       // function local variables
        case eValueTypeVariableThreadLocal: // thread local variables
        {
          SymbolContext sc(frame->GetSymbolContext(eSymbolContextBlock));

          const bool can_create = true;
          const bool get_parent_variables = true;
          const bool stop_if_block_is_inlined_function = true;

          if (sc.block)
            sc.block->AppendVariables(
                can_create, get_parent_variables,
                stop_if_block_is_inlined_function,
                [frame](Variable *v) { return v->IsInScope(frame); },
                &variable_list);
          if (value_type == eValueTypeVariableGlobal) {
            const bool get_file_globals = true;
            VariableList *frame_vars = frame->GetVariableList(get_file_globals);
            if (frame_vars)
              frame_vars->AppendVariablesIfUnique(variable_list);
          }
          ConstString const_name(name);
          VariableSP variable_sp(
              variable_list.FindVariable(const_name, value_type));
          if (variable_sp) {
            value_sp = frame->GetValueObjectForFrameVariable(variable_sp,
                                                             eNoDynamicValues);
            sb_value.SetSP(value_sp, use_dynamic);
          }
        } break;

        case eValueTypeRegister: // stack frame register value
        {
          RegisterContextSP reg_ctx(frame->GetRegisterContext());
          if (reg_ctx) {
            const uint32_t num_regs = reg_ctx->GetRegisterCount();
            for (uint32_t reg_idx = 0; reg_idx < num_regs; ++reg_idx) {
              const RegisterInfo *reg_info =
                  reg_ctx->GetRegisterInfoAtIndex(reg_idx);
              if (reg_info &&
                  ((reg_info->name && strcasecmp(reg_info->name, name) == 0) ||
                   (reg_info->alt_name &&
                    strcasecmp(reg_info->alt_name, name) == 0))) {
                value_sp = ValueObjectRegister::Create(frame, reg_ctx, reg_idx);
                sb_value.SetSP(value_sp);
                break;
              }
            }
          }
        } break;

        case eValueTypeRegisterSet: // A collection of stack frame register
                                    // values
        {
          RegisterContextSP reg_ctx(frame->GetRegisterContext());
          if (reg_ctx) {
            const uint32_t num_sets = reg_ctx->GetRegisterSetCount();
            for (uint32_t set_idx = 0; set_idx < num_sets; ++set_idx) {
              const RegisterSet *reg_set = reg_ctx->GetRegisterSet(set_idx);
              if (reg_set &&
                  ((reg_set->name && strcasecmp(reg_set->name, name) == 0) ||
                   (reg_set->short_name &&
                    strcasecmp(reg_set->short_name, name) == 0))) {
                value_sp =
                    ValueObjectRegisterSet::Create(frame, reg_ctx, set_idx);
                sb_value.SetSP(value_sp);
                break;
              }
            }
          }
        } break;

        case eValueTypeConstResult: // constant result variables
        {
          ConstString const_name(name);
          ExpressionVariableSP expr_var_sp(
              target->GetPersistentVariable(const_name));
          if (expr_var_sp) {
            value_sp = expr_var_sp->GetValueObject();
            sb_value.SetSP(value_sp, use_dynamic);
          }
        } break;

        default:
          break;
        }
      }
    }
  }

  return LLDB_RECORD_RESULT(sb_value);
}

bool SBFrame::IsEqual(const SBFrame &that) const {
  LLDB_RECORD_METHOD_CONST(bool, SBFrame, IsEqual, (const lldb::SBFrame &),
                           that);

  lldb::StackFrameSP this_sp = GetFrameSP();
  lldb::StackFrameSP that_sp = that.GetFrameSP();
  return (this_sp && that_sp && this_sp->GetStackID() == that_sp->GetStackID());
}

bool SBFrame::operator==(const SBFrame &rhs) const {
  LLDB_RECORD_METHOD_CONST(bool, SBFrame, operator==,(const lldb::SBFrame &),
                           rhs);

  return IsEqual(rhs);
}

bool SBFrame::operator!=(const SBFrame &rhs) const {
  LLDB_RECORD_METHOD_CONST(bool, SBFrame, operator!=,(const lldb::SBFrame &),
                           rhs);

  return !IsEqual(rhs);
}

SBThread SBFrame::GetThread() const {
  LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::SBThread, SBFrame, GetThread);

  std::unique_lock<std::recursive_mutex> lock;
  ExecutionContext exe_ctx(m_opaque_sp.get(), lock);

  ThreadSP thread_sp(exe_ctx.GetThreadSP());
  SBThread sb_thread(thread_sp);

  return LLDB_RECORD_RESULT(sb_thread);
}

const char *SBFrame::Disassemble() const {
  LLDB_RECORD_METHOD_CONST_NO_ARGS(const char *, SBFrame, Disassemble);

  const char *disassembly = nullptr;
  std::unique_lock<std::recursive_mutex> lock;
  ExecutionContext exe_ctx(m_opaque_sp.get(), lock);

  StackFrame *frame = nullptr;
  Target *target = exe_ctx.GetTargetPtr();
  Process *process = exe_ctx.GetProcessPtr();
  if (target && process) {
    Process::StopLocker stop_locker;
    if (stop_locker.TryLock(&process->GetRunLock())) {
      frame = exe_ctx.GetFramePtr();
      if (frame) {
        disassembly = frame->Disassemble();
      }
    }
  }

  return disassembly;
}

SBValueList SBFrame::GetVariables(bool arguments, bool locals, bool statics,
                                  bool in_scope_only) {
  LLDB_RECORD_METHOD(lldb::SBValueList, SBFrame, GetVariables,
                     (bool, bool, bool, bool), arguments, locals, statics,
                     in_scope_only);

  SBValueList value_list;
  std::unique_lock<std::recursive_mutex> lock;
  ExecutionContext exe_ctx(m_opaque_sp.get(), lock);

  StackFrame *frame = exe_ctx.GetFramePtr();
  Target *target = exe_ctx.GetTargetPtr();
  if (frame && target) {
    lldb::DynamicValueType use_dynamic =
        frame->CalculateTarget()->GetPreferDynamicValue();
    const bool include_runtime_support_values =
        target ? target->GetDisplayRuntimeSupportValues() : false;

    SBVariablesOptions options;
    options.SetIncludeArguments(arguments);
    options.SetIncludeLocals(locals);
    options.SetIncludeStatics(statics);
    options.SetInScopeOnly(in_scope_only);
    options.SetIncludeRuntimeSupportValues(include_runtime_support_values);
    options.SetUseDynamic(use_dynamic);

    value_list = GetVariables(options);
  }
  return LLDB_RECORD_RESULT(value_list);
}

lldb::SBValueList SBFrame::GetVariables(bool arguments, bool locals,
                                        bool statics, bool in_scope_only,
                                        lldb::DynamicValueType use_dynamic) {
  LLDB_RECORD_METHOD(lldb::SBValueList, SBFrame, GetVariables,
                     (bool, bool, bool, bool, lldb::DynamicValueType),
                     arguments, locals, statics, in_scope_only, use_dynamic);

  std::unique_lock<std::recursive_mutex> lock;
  ExecutionContext exe_ctx(m_opaque_sp.get(), lock);

  Target *target = exe_ctx.GetTargetPtr();
  const bool include_runtime_support_values =
      target ? target->GetDisplayRuntimeSupportValues() : false;
  SBVariablesOptions options;
  options.SetIncludeArguments(arguments);
  options.SetIncludeLocals(locals);
  options.SetIncludeStatics(statics);
  options.SetInScopeOnly(in_scope_only);
  options.SetIncludeRuntimeSupportValues(include_runtime_support_values);
  options.SetUseDynamic(use_dynamic);
  return LLDB_RECORD_RESULT(GetVariables(options));
}

SBValueList SBFrame::GetVariables(const lldb::SBVariablesOptions &options) {
  LLDB_RECORD_METHOD(lldb::SBValueList, SBFrame, GetVariables,
                     (const lldb::SBVariablesOptions &), options);

  SBValueList value_list;
  std::unique_lock<std::recursive_mutex> lock;
  ExecutionContext exe_ctx(m_opaque_sp.get(), lock);

  StackFrame *frame = nullptr;
  Target *target = exe_ctx.GetTargetPtr();

  const bool statics = options.GetIncludeStatics();
  const bool arguments = options.GetIncludeArguments();
  const bool recognized_arguments =
        options.GetIncludeRecognizedArguments(SBTarget(exe_ctx.GetTargetSP()));
  const bool locals = options.GetIncludeLocals();
  const bool in_scope_only = options.GetInScopeOnly();
  const bool include_runtime_support_values =
      options.GetIncludeRuntimeSupportValues();
  const lldb::DynamicValueType use_dynamic = options.GetUseDynamic();

  std::set<VariableSP> variable_set;
  Process *process = exe_ctx.GetProcessPtr();
  if (target && process) {
    Process::StopLocker stop_locker;
    if (stop_locker.TryLock(&process->GetRunLock())) {
      frame = exe_ctx.GetFramePtr();
      if (frame) {
        size_t i;
        VariableList *variable_list = nullptr;
        variable_list = frame->GetVariableList(true);
        if (variable_list) {
          const size_t num_variables = variable_list->GetSize();
          if (num_variables) {
            for (i = 0; i < num_variables; ++i) {
              VariableSP variable_sp(variable_list->GetVariableAtIndex(i));
              if (variable_sp) {
                bool add_variable = false;
                switch (variable_sp->GetScope()) {
                case eValueTypeVariableGlobal:
                case eValueTypeVariableStatic:
                case eValueTypeVariableThreadLocal:
                  add_variable = statics;
                  break;

                case eValueTypeVariableArgument:
                  add_variable = arguments;
                  break;

                case eValueTypeVariableLocal:
                  add_variable = locals;
                  break;

                default:
                  break;
                }
                if (add_variable) {
                  // Only add variables once so we don't end up with duplicates
                  if (variable_set.find(variable_sp) == variable_set.end())
                    variable_set.insert(variable_sp);
                  else
                    continue;

                  if (in_scope_only && !variable_sp->IsInScope(frame))
                    continue;

                  ValueObjectSP valobj_sp(frame->GetValueObjectForFrameVariable(
                      variable_sp, eNoDynamicValues));

                  if (!include_runtime_support_values && valobj_sp != nullptr &&
                      valobj_sp->IsRuntimeSupportValue())
                    continue;

                  SBValue value_sb;
                  value_sb.SetSP(valobj_sp, use_dynamic);
                  value_list.Append(value_sb);
                }
              }
            }
          }
        }
        if (recognized_arguments) {
          auto recognized_frame = frame->GetRecognizedFrame();
          if (recognized_frame) {
            ValueObjectListSP recognized_arg_list =
                recognized_frame->GetRecognizedArguments();
            if (recognized_arg_list) {
              for (auto &rec_value_sp : recognized_arg_list->GetObjects()) {
                SBValue value_sb;
                value_sb.SetSP(rec_value_sp, use_dynamic);
                value_list.Append(value_sb);
              }
            }
          }
        }
      }
    }
  }

  return LLDB_RECORD_RESULT(value_list);
}

SBValueList SBFrame::GetRegisters() {
  LLDB_RECORD_METHOD_NO_ARGS(lldb::SBValueList, SBFrame, GetRegisters);

  SBValueList value_list;
  std::unique_lock<std::recursive_mutex> lock;
  ExecutionContext exe_ctx(m_opaque_sp.get(), lock);

  StackFrame *frame = nullptr;
  Target *target = exe_ctx.GetTargetPtr();
  Process *process = exe_ctx.GetProcessPtr();
  if (target && process) {
    Process::StopLocker stop_locker;
    if (stop_locker.TryLock(&process->GetRunLock())) {
      frame = exe_ctx.GetFramePtr();
      if (frame) {
        RegisterContextSP reg_ctx(frame->GetRegisterContext());
        if (reg_ctx) {
          const uint32_t num_sets = reg_ctx->GetRegisterSetCount();
          for (uint32_t set_idx = 0; set_idx < num_sets; ++set_idx) {
            value_list.Append(
                ValueObjectRegisterSet::Create(frame, reg_ctx, set_idx));
          }
        }
      }
    }
  }

  return LLDB_RECORD_RESULT(value_list);
}

SBValue SBFrame::FindRegister(const char *name) {
  LLDB_RECORD_METHOD(lldb::SBValue, SBFrame, FindRegister, (const char *),
                     name);

  SBValue result;
  ValueObjectSP value_sp;
  std::unique_lock<std::recursive_mutex> lock;
  ExecutionContext exe_ctx(m_opaque_sp.get(), lock);

  StackFrame *frame = nullptr;
  Target *target = exe_ctx.GetTargetPtr();
  Process *process = exe_ctx.GetProcessPtr();
  if (target && process) {
    Process::StopLocker stop_locker;
    if (stop_locker.TryLock(&process->GetRunLock())) {
      frame = exe_ctx.GetFramePtr();
      if (frame) {
        RegisterContextSP reg_ctx(frame->GetRegisterContext());
        if (reg_ctx) {
          const uint32_t num_regs = reg_ctx->GetRegisterCount();
          for (uint32_t reg_idx = 0; reg_idx < num_regs; ++reg_idx) {
            const RegisterInfo *reg_info =
                reg_ctx->GetRegisterInfoAtIndex(reg_idx);
            if (reg_info &&
                ((reg_info->name && strcasecmp(reg_info->name, name) == 0) ||
                 (reg_info->alt_name &&
                  strcasecmp(reg_info->alt_name, name) == 0))) {
              value_sp = ValueObjectRegister::Create(frame, reg_ctx, reg_idx);
              result.SetSP(value_sp);
              break;
            }
          }
        }
      }
    }
  }

  return LLDB_RECORD_RESULT(result);
}

bool SBFrame::GetDescription(SBStream &description) {
  LLDB_RECORD_METHOD(bool, SBFrame, GetDescription, (lldb::SBStream &),
                     description);

  Stream &strm = description.ref();

  std::unique_lock<std::recursive_mutex> lock;
  ExecutionContext exe_ctx(m_opaque_sp.get(), lock);

  StackFrame *frame;
  Target *target = exe_ctx.GetTargetPtr();
  Process *process = exe_ctx.GetProcessPtr();
  if (target && process) {
    Process::StopLocker stop_locker;
    if (stop_locker.TryLock(&process->GetRunLock())) {
      frame = exe_ctx.GetFramePtr();
      if (frame) {
        frame->DumpUsingSettingsFormat(&strm);
      }
    }

  } else
    strm.PutCString("No value");

  return true;
}

SBValue SBFrame::EvaluateExpression(const char *expr) {
  LLDB_RECORD_METHOD(lldb::SBValue, SBFrame, EvaluateExpression, (const char *),
                     expr);

  SBValue result;
  std::unique_lock<std::recursive_mutex> lock;
  ExecutionContext exe_ctx(m_opaque_sp.get(), lock);

  StackFrame *frame = exe_ctx.GetFramePtr();
  Target *target = exe_ctx.GetTargetPtr();
  if (frame && target) {
    SBExpressionOptions options;
    lldb::DynamicValueType fetch_dynamic_value =
        frame->CalculateTarget()->GetPreferDynamicValue();
    options.SetFetchDynamicValue(fetch_dynamic_value);
    options.SetUnwindOnError(true);
    options.SetIgnoreBreakpoints(true);
    if (target->GetLanguage() != eLanguageTypeUnknown)
      options.SetLanguage(target->GetLanguage());
    else
      options.SetLanguage(frame->GetLanguage());
    return LLDB_RECORD_RESULT(EvaluateExpression(expr, options));
  }
  return LLDB_RECORD_RESULT(result);
}

SBValue
SBFrame::EvaluateExpression(const char *expr,
                            lldb::DynamicValueType fetch_dynamic_value) {
  LLDB_RECORD_METHOD(lldb::SBValue, SBFrame, EvaluateExpression,
                     (const char *, lldb::DynamicValueType), expr,
                     fetch_dynamic_value);

  SBExpressionOptions options;
  options.SetFetchDynamicValue(fetch_dynamic_value);
  options.SetUnwindOnError(true);
  options.SetIgnoreBreakpoints(true);
  std::unique_lock<std::recursive_mutex> lock;
  ExecutionContext exe_ctx(m_opaque_sp.get(), lock);

  StackFrame *frame = exe_ctx.GetFramePtr();
  Target *target = exe_ctx.GetTargetPtr();
  if (target && target->GetLanguage() != eLanguageTypeUnknown)
    options.SetLanguage(target->GetLanguage());
  else if (frame)
    options.SetLanguage(frame->GetLanguage());
  return LLDB_RECORD_RESULT(EvaluateExpression(expr, options));
}

SBValue SBFrame::EvaluateExpression(const char *expr,
                                    lldb::DynamicValueType fetch_dynamic_value,
                                    bool unwind_on_error) {
  LLDB_RECORD_METHOD(lldb::SBValue, SBFrame, EvaluateExpression,
                     (const char *, lldb::DynamicValueType, bool), expr,
                     fetch_dynamic_value, unwind_on_error);

  SBExpressionOptions options;
  std::unique_lock<std::recursive_mutex> lock;
  ExecutionContext exe_ctx(m_opaque_sp.get(), lock);

  options.SetFetchDynamicValue(fetch_dynamic_value);
  options.SetUnwindOnError(unwind_on_error);
  options.SetIgnoreBreakpoints(true);
  StackFrame *frame = exe_ctx.GetFramePtr();
  Target *target = exe_ctx.GetTargetPtr();
  if (target && target->GetLanguage() != eLanguageTypeUnknown)
    options.SetLanguage(target->GetLanguage());
  else if (frame)
    options.SetLanguage(frame->GetLanguage());
  return LLDB_RECORD_RESULT(EvaluateExpression(expr, options));
}

lldb::SBValue SBFrame::EvaluateExpression(const char *expr,
                                          const SBExpressionOptions &options) {
  LLDB_RECORD_METHOD(lldb::SBValue, SBFrame, EvaluateExpression,
                     (const char *, const lldb::SBExpressionOptions &), expr,
                     options);

  Log *expr_log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));

  SBValue expr_result;

  if (expr == nullptr || expr[0] == '\0') {
    return LLDB_RECORD_RESULT(expr_result);
  }

  ValueObjectSP expr_value_sp;

  std::unique_lock<std::recursive_mutex> lock;
  ExecutionContext exe_ctx(m_opaque_sp.get(), lock);

  StackFrame *frame = nullptr;
  Target *target = exe_ctx.GetTargetPtr();
  Process *process = exe_ctx.GetProcessPtr();

  if (target && process) {
    Process::StopLocker stop_locker;
    if (stop_locker.TryLock(&process->GetRunLock())) {
      frame = exe_ctx.GetFramePtr();
      if (frame) {
        std::unique_ptr<llvm::PrettyStackTraceFormat> stack_trace;
        if (target->GetDisplayExpressionsInCrashlogs()) {
          StreamString frame_description;
          frame->DumpUsingSettingsFormat(&frame_description);
          stack_trace = std::make_unique<llvm::PrettyStackTraceFormat>(
              "SBFrame::EvaluateExpression (expr = \"%s\", fetch_dynamic_value "
              "= %u) %s",
              expr, options.GetFetchDynamicValue(),
              frame_description.GetData());
        }

        target->EvaluateExpression(expr, frame, expr_value_sp, options.ref());
        expr_result.SetSP(expr_value_sp, options.GetFetchDynamicValue());
      }
    }
  }

  LLDB_LOGF(expr_log,
            "** [SBFrame::EvaluateExpression] Expression result is "
            "%s, summary %s **",
            expr_result.GetValue(), expr_result.GetSummary());

  return LLDB_RECORD_RESULT(expr_result);
}

bool SBFrame::IsInlined() {
  LLDB_RECORD_METHOD_NO_ARGS(bool, SBFrame, IsInlined);

  return static_cast<const SBFrame *>(this)->IsInlined();
}

bool SBFrame::IsInlined() const {
  LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBFrame, IsInlined);

  std::unique_lock<std::recursive_mutex> lock;
  ExecutionContext exe_ctx(m_opaque_sp.get(), lock);

  StackFrame *frame = nullptr;
  Target *target = exe_ctx.GetTargetPtr();
  Process *process = exe_ctx.GetProcessPtr();
  if (target && process) {
    Process::StopLocker stop_locker;
    if (stop_locker.TryLock(&process->GetRunLock())) {
      frame = exe_ctx.GetFramePtr();
      if (frame) {

        Block *block = frame->GetSymbolContext(eSymbolContextBlock).block;
        if (block)
          return block->GetContainingInlinedBlock() != nullptr;
      }
    }
  }
  return false;
}

bool SBFrame::IsArtificial() {
  LLDB_RECORD_METHOD_NO_ARGS(bool, SBFrame, IsArtificial);

  return static_cast<const SBFrame *>(this)->IsArtificial();
}

bool SBFrame::IsArtificial() const {
  LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBFrame, IsArtificial);

  std::unique_lock<std::recursive_mutex> lock;
  ExecutionContext exe_ctx(m_opaque_sp.get(), lock);

  StackFrame *frame = exe_ctx.GetFramePtr();
  if (frame)
    return frame->IsArtificial();

  return false;
}

const char *SBFrame::GetFunctionName() {
  LLDB_RECORD_METHOD_NO_ARGS(const char *, SBFrame, GetFunctionName);

  return static_cast<const SBFrame *>(this)->GetFunctionName();
}

lldb::LanguageType SBFrame::GuessLanguage() const {
  LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::LanguageType, SBFrame, GuessLanguage);

  std::unique_lock<std::recursive_mutex> lock;
  ExecutionContext exe_ctx(m_opaque_sp.get(), lock);

  StackFrame *frame = nullptr;
  Target *target = exe_ctx.GetTargetPtr();
  Process *process = exe_ctx.GetProcessPtr();
  if (target && process) {
    Process::StopLocker stop_locker;
    if (stop_locker.TryLock(&process->GetRunLock())) {
      frame = exe_ctx.GetFramePtr();
      if (frame) {
        return frame->GuessLanguage();
      }
    }
  }
  return eLanguageTypeUnknown;
}

const char *SBFrame::GetFunctionName() const {
  LLDB_RECORD_METHOD_CONST_NO_ARGS(const char *, SBFrame, GetFunctionName);

  const char *name = nullptr;
  std::unique_lock<std::recursive_mutex> lock;
  ExecutionContext exe_ctx(m_opaque_sp.get(), lock);

  StackFrame *frame = nullptr;
  Target *target = exe_ctx.GetTargetPtr();
  Process *process = exe_ctx.GetProcessPtr();
  if (target && process) {
    Process::StopLocker stop_locker;
    if (stop_locker.TryLock(&process->GetRunLock())) {
      frame = exe_ctx.GetFramePtr();
      if (frame) {
        SymbolContext sc(frame->GetSymbolContext(eSymbolContextFunction |
                                                 eSymbolContextBlock |
                                                 eSymbolContextSymbol));
        if (sc.block) {
          Block *inlined_block = sc.block->GetContainingInlinedBlock();
          if (inlined_block) {
            const InlineFunctionInfo *inlined_info =
                inlined_block->GetInlinedFunctionInfo();
            name =
                inlined_info->GetName(sc.function->GetLanguage()).AsCString();
          }
        }

        if (name == nullptr) {
          if (sc.function)
            name = sc.function->GetName().GetCString();
        }

        if (name == nullptr) {
          if (sc.symbol)
            name = sc.symbol->GetName().GetCString();
        }
      }
    }
  }
  return name;
}

const char *SBFrame::GetDisplayFunctionName() {
  LLDB_RECORD_METHOD_NO_ARGS(const char *, SBFrame, GetDisplayFunctionName);

  const char *name = nullptr;

  std::unique_lock<std::recursive_mutex> lock;
  ExecutionContext exe_ctx(m_opaque_sp.get(), lock);

  StackFrame *frame = nullptr;
  Target *target = exe_ctx.GetTargetPtr();
  Process *process = exe_ctx.GetProcessPtr();
  if (target && process) {
    Process::StopLocker stop_locker;
    if (stop_locker.TryLock(&process->GetRunLock())) {
      frame = exe_ctx.GetFramePtr();
      if (frame) {
        SymbolContext sc(frame->GetSymbolContext(eSymbolContextFunction |
                                                 eSymbolContextBlock |
                                                 eSymbolContextSymbol));
        if (sc.block) {
          Block *inlined_block = sc.block->GetContainingInlinedBlock();
          if (inlined_block) {
            const InlineFunctionInfo *inlined_info =
                inlined_block->GetInlinedFunctionInfo();
            name = inlined_info->GetDisplayName(sc.function->GetLanguage())
                       .AsCString();
          }
        }

        if (name == nullptr) {
          if (sc.function)
            name = sc.function->GetDisplayName().GetCString();
        }

        if (name == nullptr) {
          if (sc.symbol)
            name = sc.symbol->GetDisplayName().GetCString();
        }
      }
    }
  }
  return name;
}

namespace lldb_private {
namespace repro {

template <>
void RegisterMethods<SBFrame>(Registry &R) {
  LLDB_REGISTER_CONSTRUCTOR(SBFrame, ());
  LLDB_REGISTER_CONSTRUCTOR(SBFrame, (const lldb::StackFrameSP &));
  LLDB_REGISTER_CONSTRUCTOR(SBFrame, (const lldb::SBFrame &));
  LLDB_REGISTER_METHOD(const lldb::SBFrame &,
                       SBFrame, operator=,(const lldb::SBFrame &));
  LLDB_REGISTER_METHOD_CONST(bool, SBFrame, IsValid, ());
  LLDB_REGISTER_METHOD_CONST(bool, SBFrame, operator bool, ());
  LLDB_REGISTER_METHOD_CONST(lldb::SBSymbolContext, SBFrame, GetSymbolContext,
                             (uint32_t));
  LLDB_REGISTER_METHOD_CONST(lldb::SBModule, SBFrame, GetModule, ());
  LLDB_REGISTER_METHOD_CONST(lldb::SBCompileUnit, SBFrame, GetCompileUnit,
                             ());
  LLDB_REGISTER_METHOD_CONST(lldb::SBFunction, SBFrame, GetFunction, ());
  LLDB_REGISTER_METHOD_CONST(lldb::SBSymbol, SBFrame, GetSymbol, ());
  LLDB_REGISTER_METHOD_CONST(lldb::SBBlock, SBFrame, GetBlock, ());
  LLDB_REGISTER_METHOD_CONST(lldb::SBBlock, SBFrame, GetFrameBlock, ());
  LLDB_REGISTER_METHOD_CONST(lldb::SBLineEntry, SBFrame, GetLineEntry, ());
  LLDB_REGISTER_METHOD_CONST(uint32_t, SBFrame, GetFrameID, ());
  LLDB_REGISTER_METHOD_CONST(lldb::addr_t, SBFrame, GetCFA, ());
  LLDB_REGISTER_METHOD_CONST(lldb::addr_t, SBFrame, GetPC, ());
  LLDB_REGISTER_METHOD(bool, SBFrame, SetPC, (lldb::addr_t));
  LLDB_REGISTER_METHOD_CONST(lldb::addr_t, SBFrame, GetSP, ());
  LLDB_REGISTER_METHOD_CONST(lldb::addr_t, SBFrame, GetFP, ());
  LLDB_REGISTER_METHOD_CONST(lldb::SBAddress, SBFrame, GetPCAddress, ());
  LLDB_REGISTER_METHOD(void, SBFrame, Clear, ());
  LLDB_REGISTER_METHOD(lldb::SBValue, SBFrame, GetValueForVariablePath,
                       (const char *));
  LLDB_REGISTER_METHOD(lldb::SBValue, SBFrame, GetValueForVariablePath,
                       (const char *, lldb::DynamicValueType));
  LLDB_REGISTER_METHOD(lldb::SBValue, SBFrame, FindVariable, (const char *));
  LLDB_REGISTER_METHOD(lldb::SBValue, SBFrame, FindVariable,
                       (const char *, lldb::DynamicValueType));
  LLDB_REGISTER_METHOD(lldb::SBValue, SBFrame, FindValue,
                       (const char *, lldb::ValueType));
  LLDB_REGISTER_METHOD(
      lldb::SBValue, SBFrame, FindValue,
      (const char *, lldb::ValueType, lldb::DynamicValueType));
  LLDB_REGISTER_METHOD_CONST(bool, SBFrame, IsEqual, (const lldb::SBFrame &));
  LLDB_REGISTER_METHOD_CONST(bool,
                             SBFrame, operator==,(const lldb::SBFrame &));
  LLDB_REGISTER_METHOD_CONST(bool,
                             SBFrame, operator!=,(const lldb::SBFrame &));
  LLDB_REGISTER_METHOD_CONST(lldb::SBThread, SBFrame, GetThread, ());
  LLDB_REGISTER_METHOD_CONST(const char *, SBFrame, Disassemble, ());
  LLDB_REGISTER_METHOD(lldb::SBValueList, SBFrame, GetVariables,
                       (bool, bool, bool, bool));
  LLDB_REGISTER_METHOD(lldb::SBValueList, SBFrame, GetVariables,
                       (bool, bool, bool, bool, lldb::DynamicValueType));
  LLDB_REGISTER_METHOD(lldb::SBValueList, SBFrame, GetVariables,
                       (const lldb::SBVariablesOptions &));
  LLDB_REGISTER_METHOD(lldb::SBValueList, SBFrame, GetRegisters, ());
  LLDB_REGISTER_METHOD(lldb::SBValue, SBFrame, FindRegister, (const char *));
  LLDB_REGISTER_METHOD(bool, SBFrame, GetDescription, (lldb::SBStream &));
  LLDB_REGISTER_METHOD(lldb::SBValue, SBFrame, EvaluateExpression,
                       (const char *));
  LLDB_REGISTER_METHOD(lldb::SBValue, SBFrame, EvaluateExpression,
                       (const char *, lldb::DynamicValueType));
  LLDB_REGISTER_METHOD(lldb::SBValue, SBFrame, EvaluateExpression,
                       (const char *, lldb::DynamicValueType, bool));
  LLDB_REGISTER_METHOD(lldb::SBValue, SBFrame, EvaluateExpression,
                       (const char *, const lldb::SBExpressionOptions &));
  LLDB_REGISTER_METHOD(bool, SBFrame, IsInlined, ());
  LLDB_REGISTER_METHOD_CONST(bool, SBFrame, IsInlined, ());
  LLDB_REGISTER_METHOD(bool, SBFrame, IsArtificial, ());
  LLDB_REGISTER_METHOD_CONST(bool, SBFrame, IsArtificial, ());
  LLDB_REGISTER_METHOD(const char *, SBFrame, GetFunctionName, ());
  LLDB_REGISTER_METHOD_CONST(lldb::LanguageType, SBFrame, GuessLanguage, ());
  LLDB_REGISTER_METHOD_CONST(const char *, SBFrame, GetFunctionName, ());
  LLDB_REGISTER_METHOD(const char *, SBFrame, GetDisplayFunctionName, ());
}

}
}


text:
package org.nanocontainer.nanowar.webwork2;

import java.util.Map;

import com.opensymphony.xwork.ActionProxy;
import com.opensymphony.xwork.DefaultActionInvocation;

/**
 * Implementation of {@link com.opensymphony.xwork.ActionInvocation ActionInvocation}
 * which uses a PicoContainer to create Action instances.
 *
 * @author Chris Sturm
 * @author Aslak Hellesøy
 * @deprecated Use DefaultActionInvocation
 */
public class PicoActionInvocation extends DefaultActionInvocation {

    public PicoActionInvocation(ActionProxy proxy) throws Exception {
        super(proxy);
    }

    public PicoActionInvocation(ActionProxy proxy, Map extraContext) throws Exception {
        super(proxy, extraContext);
    }

    public PicoActionInvocation(ActionProxy proxy, Map extraContext, boolean pushAction) throws Exception {
        super(proxy, extraContext, pushAction);
    }

}


text:
layout: page
title: Sapphire Cube Aerospace Show
date: 2016-05-24
author: Mary Mills
tags: weekly links, java
status: published
summary: Maecenas aliquam, quam lacinia rutrum.
banner: images/banner/leisure-04.jpg
booking:
  startDate: 01/04/2019
  endDate: 01/09/2019
  ctyhocn: BFLWPHX
  groupCode: SCAS
published: true
---
Praesent sed maximus lacus. Nunc vel lacus nibh. Quisque nec porta felis, vitae pretium est. Praesent fermentum pellentesque enim vitae tincidunt. Aliquam ornare nisl nisi, ut convallis magna accumsan ac. Donec at efficitur orci. Duis eu porta lectus. Vivamus blandit eros ut lorem posuere, sed vehicula velit interdum. Fusce vulputate sem vel eros accumsan rutrum. Mauris in justo cursus, semper urna ac, fringilla quam. Ut et erat nisl. Praesent hendrerit felis eget mattis placerat. Maecenas feugiat faucibus ex et interdum.
Cras eget nisl nec felis porta sodales sed in ante. Duis pulvinar nunc eget erat elementum condimentum. Proin dictum diam dolor, vel maximus leo malesuada quis. Sed vitae cursus ipsum, at vehicula magna. Praesent eu nisl id nibh dignissim convallis id sed dolor. Vestibulum dignissim sit amet nibh fermentum molestie. Sed sollicitudin at lacus sed ultricies. Pellentesque efficitur ex nec nisi tempor, ac vestibulum libero sodales. Nunc aliquam blandit est, ut convallis lectus scelerisque feugiat. Vestibulum nec consequat nunc. Nunc dictum posuere risus, a luctus augue tristique non. Aliquam congue a justo ultrices volutpat.

* Praesent porttitor arcu quis ullamcorper egestas
* Proin accumsan neque vel mauris varius luctus.

Curabitur vitae mi consectetur, porttitor lacus a, dignissim sapien. Aenean enim dui, posuere ac mauris vel, ornare aliquam nulla. Maecenas venenatis eleifend consequat. Nulla facilisi. Suspendisse potenti. Nulla facilisi. Integer rutrum mi id semper elementum. Proin magna sapien, laoreet non sagittis quis, sodales sit amet ipsum. Praesent vitae arcu eros.


text:
#! /usr/bin/env node
"use strict";

Object.defineProperty(exports, "__esModule", {
    value: true
});
exports.installAppDeps = undefined;

var _bluebirdLst;

function _load_bluebirdLst() {
    return _bluebirdLst = require("bluebird-lst");
}

var _bluebirdLst2;

function _load_bluebirdLst2() {
    return _bluebirdLst2 = _interopRequireDefault(require("bluebird-lst"));
}

/** @internal */
let installAppDeps = exports.installAppDeps = (() => {
    var _ref = (0, (_bluebirdLst || _load_bluebirdLst()).coroutine)(function* (args) {
        try {
            (0, (_builderUtil || _load_builderUtil()).log)("electron-builder " + "19.45.5");
        } catch (e) {
            // error in dev mode without babel
            if (!(e instanceof ReferenceError)) {
                throw e;
            }
        }
        const projectDir = process.cwd();
        const packageMetadata = new (_lazyVal || _load_lazyVal()).Lazy(function () {
            return (0, (_readConfigFile || _load_readConfigFile()).orNullIfFileNotExist)((0, (_fsExtraP || _load_fsExtraP()).readJson)(_path.join(projectDir, "package.json")));
        });
        const config = yield (0, (_config || _load_config()).getConfig)(projectDir, null, null, packageMetadata);
        const muonVersion = config.muonVersion;
        const results = yield (_bluebirdLst2 || _load_bluebirdLst2()).default.all([(0, (_config || _load_config()).computeDefaultAppDirectory)(projectDir, (0, (_builderUtil || _load_builderUtil()).use)(config.directories, function (it) {
            return it.app;
        })), muonVersion == null ? (0, (_electronVersion || _load_electronVersion()).getElectronVersion)(projectDir, config, packageMetadata) : (_bluebirdLst2 || _load_bluebirdLst2()).default.resolve(muonVersion)]);
        // if two package.json — force full install (user wants to install/update app deps in addition to dev)
        yield (0, (_yarn || _load_yarn()).installOrRebuild)(config, results[0], {
            frameworkInfo: { version: results[1], useCustomDist: muonVersion == null },
            platform: args.platform,
            arch: args.arch,
            productionDeps: (0, (_packageDependencies || _load_packageDependencies()).createLazyProductionDeps)(results[0])
        }, results[0] !== projectDir);
    });

    return function installAppDeps(_x) {
        return _ref.apply(this, arguments);
    };
})();

exports.configureInstallAppDepsCommand = configureInstallAppDepsCommand;

var _builderUtil;

function _load_builderUtil() {
    return _builderUtil = require("builder-util");
}

var _promise;

function _load_promise() {
    return _promise = require("builder-util/out/promise");
}

var _fsExtraP;

function _load_fsExtraP() {
    return _fsExtraP = require("fs-extra-p");
}

var _lazyVal;

function _load_lazyVal() {
    return _lazyVal = require("lazy-val");
}

var _path = _interopRequireWildcard(require("path"));

var _readConfigFile;

function _load_readConfigFile() {
    return _readConfigFile = require("read-config-file");
}

var _yargs;

function _load_yargs() {
    return _yargs = _interopRequireDefault(require("yargs"));
}

var _config;

function _load_config() {
    return _config = require("../util/config");
}

var _electronVersion;

function _load_electronVersion() {
    return _electronVersion = require("../util/electronVersion");
}

var _packageDependencies;

function _load_packageDependencies() {
    return _packageDependencies = require("../util/packageDependencies");
}

var _yarn;

function _load_yarn() {
    return _yarn = require("../util/yarn");
}

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/** @internal */
function configureInstallAppDepsCommand(yargs) {
    // https://github.com/yargs/yargs/issues/760
    // demandOption is required to be set
    return yargs.option("platform", {
        choices: ["linux", "darwin", "win32"],
        default: process.platform,
        description: "The target platform"
    }).option("arch", {
        choices: ["ia32", "x64", "all"],
        default: process.arch,
        description: "The target arch"
    });
}
function main() {
    return installAppDeps(configureInstallAppDepsCommand((_yargs || _load_yargs()).default).argv);
}
if (process.mainModule === module) {
    (0, (_builderUtil || _load_builderUtil()).warn)("Please use as subcommand: electron-builder install-app-deps");
    main().catch((_promise || _load_promise()).printErrorAndExit);
}
//# sourceMappingURL=install-app-deps.js.map


text:
#include <algorithm>
#include <memory>
#include <shogun/base/init.h>
#include <shogun/lib/SGMatrix.h>
#include <shogun/lib/SGVector.h>
#include <shogun/features/Features.h>
#include <shogun/features/DenseFeatures.h>
#include <shogun/kernel/Kernel.h>
#include <shogun/kernel/GaussianKernel.h>
#include <shogun/statistical_testing/MMD.h>
#include <shogun/statistical_testing/internals/mmd/WithinBlockPermutation.h>
#include <shogun/statistical_testing/internals/mmd/WithinBlockPermutationBatch.h>
#include <benchmark/benchmark.h>

using namespace shogun;
using namespace internal;
using namespace mmd;

/*
 * $ g++ -O3 -std=c++14 mmd_permutation_benchmark.cpp -lshogun -lbenchmark -lpthread -fopenmp
 * $ ./a.out
 * Run on (4 X 2999.95 MHz CPU s)
 * 2016-04-15 08:39:04
 * ***WARNING*** CPU scaling is enabled, the benchmark real time measurements may be noisy and will incur extra overhead.
 * Benchmark    Time(ns)    CPU(ns) Iterations
 * -------------------------------------------
 *  BM_Batch   5176712791 15645935000          1
 *  BM_Serial  10088581387 31100171000          1
 */

struct Data
{
	Data() : dim(2), n(1000), m(1000), num_null_samples(250)
	{
		init_shogun_with_defaults();
		SGMatrix<float64_t> data_p(dim, n);
		std::iota(data_p.matrix, data_p.matrix+dim*n, 1);
		std::for_each(data_p.matrix, data_p.matrix+dim*n, [this](float64_t& val) { val/=n; });

		SGMatrix<float64_t> data_q(dim, m);
		std::iota(data_q.matrix, data_q.matrix+dim*m, n+1);
		std::for_each(data_q.matrix, data_q.matrix+dim*m, [this](float64_t& val) { val/=2*m; });

		auto feats_p=new CDenseFeatures<float64_t>(data_p);
		auto feats_q=new CDenseFeatures<float64_t>(data_q);
		auto feats=feats_p->create_merged_copy(feats_q);
		SG_REF(feats);
		SG_UNREF(feats_p);
		SG_UNREF(feats_q);

		auto kernel=std::make_unique<CGaussianKernel>();
		kernel->set_width(2.0);

		kernel->init(feats, feats);
		mat=kernel->get_kernel_matrix();
	}
	~Data()
	{
		exit_shogun();
	}
	const index_t dim;
	const index_t n;
	const index_t m;
	const index_t num_null_samples;
	SGMatrix<float64_t> mat;
};

Data data;

SGVector<float64_t> batch_permutation()
{
	const index_t& n=data.n;
	const index_t& m=data.m;
	const index_t& num_null_samples=data.num_null_samples;
	SGMatrix<float64_t>& mat=data.mat;

	WithinBlockPermutationBatch batch(n, m, num_null_samples, EStatisticType::BIASED_FULL);
	sg_rand->set_seed(12345);
	return batch(mat);
}

SGVector<float64_t> serial_permutation()
{
	const index_t& n=data.n;
	const index_t& m=data.m;
	const index_t& num_null_samples=data.num_null_samples;
	SGMatrix<float64_t>& mat=data.mat;

	SGVector<float64_t> result(num_null_samples);
	WithinBlockPermutation compute(n, m, EStatisticType::BIASED_FULL);
	sg_rand->set_seed(12345);
#pragma omp parallel for
	for (auto i=0; i<num_null_samples; ++i)
	{
		result[i]=compute(mat);
	}
	return result;
}

static void BM_Batch(benchmark::State& state)
{
	while (state.KeepRunning())
	{
		auto result=batch_permutation();
	}
}

BENCHMARK(BM_Batch);

static void BM_Serial(benchmark::State& state)
{
	while (state.KeepRunning())
	{
		auto result=serial_permutation();
	}
}

BENCHMARK(BM_Serial);

BENCHMARK_MAIN();


text:
from __future__ import absolute_import
import re

from telemetry.internal.browser import web_contents

def UrlToExtensionId(url):
  return re.match(r"(chrome-extension://)([^/]+)", url).group(2)

class ExtensionPage(web_contents.WebContents):
  """Represents an extension page in the browser"""

  def __init__(self, inspector_backend):
    super().__init__(inspector_backend)
    self.url = inspector_backend.url
    self.extension_id = UrlToExtensionId(self.url)

  def Reload(self):
    """Reloading an extension page is used as a workaround for an extension
    binding bug for old versions of Chrome (crbug.com/263162). After Navigate
    returns, we are guaranteed that the inspected page is in the correct state.
    """
    self._inspector_backend.Navigate(self.url, None, 10)


text: transfer HL7 message and acknowledgements


text:
<?php

namespace Aes3xs\Tasker\Service;

/**
 * Helper service to manage releases.
 */
class Releaser
{
    /**
     * @var Shell
     */
    protected $shell;

    /**
     * @var string
     */
    protected $deployPath;

    /**
     * @var string
     */
    protected $releaseName;

    /**
     * @var string
     */
    protected $releasePath;

    /**
     * Constructor.
     *
     * @param Shell $shell
     */
    public function __construct(Shell $shell)
    {
        $this->shell = $shell;
    }

    /**
     * Set deploy path.
     *
     * @param $path
     */
    public function setDeployPath($path)
    {
        $this->deployPath = $path;
    }

    /**
     * Get deploy path.
     *
     * @return string
     */
    public function getDeployPath()
    {
        if (null === $this->deployPath) {
            throw new \RuntimeException('Deploy path is not defined');
        }

        return $this->deployPath;
    }

    /**
     * Get release name
     *
     * @return string
     */
    public function getReleaseName()
    {
        if (!$this->releaseName) {
            throw new \RuntimeException('No release in process, create one first.');
        }

        return $this->releaseName;
    }

    /**
     * Set release name
     *
     * @param string $releaseName
     *
     * @return Releaser
     */
    public function setReleaseName($releaseName)
    {
        $this->releaseName = $releaseName;

        return $this;
    }

    /**
     * Get release path
     *
     * @return string
     */
    public function getReleasePath()
    {
        $path = $this->getDeployPath();
        $name = $this->getReleaseName();

        $releasePath = "$path/releases/$name";

        if (!$this->shell->exists($releasePath)) {
            throw new \RuntimeException('Release path not exists.');
        }

        return $this->shell->realpath($releasePath);
    }

    /**
     * Lock deploy.
     */
    public function lock()
    {
        $path = $this->getDeployPath();

        if ($this->isLocked()) {
            throw new \RuntimeException("Deploy locked. Unlock to proceed.");
        } else {
            $this->shell->touch("$path/deploy.lock");
        }
    }

    /**
     * Check if deploy is locked.
     *
     * @return bool
     */
    public function isLocked()
    {
        $path = $this->getDeployPath();

        return $this->shell->exists("$path/deploy.lock");
    }

    /**
     * Unlock deploy.
     */
    public function unlock()
    {
        $path = $this->getDeployPath();

        $this->shell->rm("$path/deploy.lock");
    }

    /**
     * Prepare directory structure for deploy.
     */
    public function prepare()
    {
        $path = $this->getDeployPath();

        if (!$this->shell->isDir($path)) {
            throw new \RuntimeException('Not a directory: ' . $path);
        }
        if ($this->shell->exists("$path/current") && !$this->shell->isLink("$path/current")) {
            throw new \RuntimeException('Not a link: ' . "$path/current");
        }
        if (!$this->shell->isDir("$path/releases")) {
            $this->shell->mkdir("$path/releases");
        }
        if (!$this->shell->isDir("$path/shared")) {
            $this->shell->mkdir("$path/shared");
        }
    }

    /**
     * Delete old and broken releases.
     *
     * @param int $keep
     */
    public function cleanup($keep)
    {
        $path = $this->getDeployPath();

        $releases = $this->getReleaseList();

        $list = $this->shell->ls("$path/releases");

        $broken = array_diff($list, $releases);
        foreach ($broken as $release) {
            $this->shell->rm("$path/releases/$release");
        }

        $outdated = array_slice($releases, $keep);
        foreach ($outdated as $release) {
            $this->shell->rm("$path/releases/$release");
        }
    }

    /**
     * Create release.
     *
     * @param $name
     *
     * @return string
     */
    public function create($name = null)
    {
        if ($this->releaseName) {
            throw new \RuntimeException('There is already release in process.');
        }

        $path = $this->getDeployPath();

        $name = $name ?: date('YmdHis');
        $releasePath = "$path/releases/$name";

        if ($this->shell->exists($releasePath)) {
            throw new \RuntimeException('Path already exists: ' . $releasePath);
        }

        $this->setReleaseName($name);

        $this->shell->mkdir($releasePath);

        return $name;
    }

    /**
     * Do a release.
     */
    public function release()
    {
        $path = $this->getDeployPath();
        $name = $this->getReleaseName();

        $this->shell->ln("$path/releases/$name", "$path/current");
        $date = date('Y-m-d H:i:s');
        $this->shell->exec("echo -n '$date' > $path/releases/$name/release.lock");
    }

    /**
     * Directly link release.
     *
     * @param $name
     */
    public function link($name)
    {
        $path = $this->getDeployPath();

        $this->shell->ln("$path/releases/$name", "$path/current");
    }

    /**
     * Rollback to previous release.
     *
     * @return string
     */
    public function rollback()
    {
        $path = $this->getDeployPath();

        $releases = $this->getReleaseList();
        krsort($releases);

        $currentRelease = array_shift($releases);
        $previousRelease = reset($releases);

        if ($previousRelease) {
            $this->shell->ln("$path/releases/$previousRelease", "$path/current");
            $this->shell->rm("$path/releases/$currentRelease");
        } else {
            throw new \RuntimeException('No available release to revert to');
        }

        return $previousRelease;
    }

    /**
     * Update release shares.
     *
     * @param array $sharedDirs
     * @param array $sharedFiles
     */
    public function updateReleaseShares($sharedDirs = [], $sharedFiles = [])
    {
        $path = $this->getDeployPath();

        foreach ($sharedDirs as $a) {
            foreach ($sharedDirs as $b) {
                if ($a !== $b && strpos($a, $b) === 0) {
                    throw new \RuntimeException("Nested shared directories: $a, $b");
                }
            }
        }

        $release = $this->getReleasePath();

        foreach ($sharedDirs as $dir) {

            if (!$this->shell->exists("$path/shared/$dir")) {
                $this->shell->mkdir("$path/shared/$dir");

                // Initialize share from source release
                if ($this->shell->isDir("$release/$dir")) {
                    $this->shell->copy("$release/$dir", "$path/shared/" . dirname($dir));
                }
            }

            if (!$this->shell->isDir("$path/shared/$dir")) {
                throw new \RuntimeException('Not a directory: ' . "$path/shared/$dir");
            }

            $this->shell->rm("$release/$dir");
            $this->shell->mkdir(dirname("$release/$dir"));
            $this->shell->ln("$path/shared/$dir", "$release/$dir");
        }

        foreach ($sharedFiles as $file) {

            $this->shell->mkdir(dirname("$path/shared/$file"));

            if (!$this->shell->exists("$path/shared/$file")) {
                $this->shell->touch("$path/shared/$file");

                // Initialize share from source release
                if ($this->shell->isFile("$release/$file")) {
                    $this->shell->copy("$release/$file", "$path/shared/$file");
                }
            }

            if (!$this->shell->isFile("$path/shared/$file")) {
                throw new \RuntimeException('Not a file: ' . "$path/shared/$file");
            }

            $this->shell->rm("$release/$file");
            $this->shell->mkdir(dirname("$release/$file"));
            $this->shell->ln("$path/shared/$file", "$release/$file");
        }
    }

    /**
     * Get release list.
     *
     * @return array
     */
    public function getReleaseList()
    {
        $path = $this->getDeployPath();

        $path = rtrim($path, '/');

        if (!$this->shell->isDir("$path/releases")) {
            return [];
        }

        $output = $this->shell->exec("find $path/releases -maxdepth 2 -mindepth 2 -path \"*/*/release.lock\"");

        $list = [];
        $rplc = ['/' => '\/', '.' => '\.'];
        $pattern = strtr("$path/releases/", $rplc) . '(.+)' . strtr('/release.lock', $rplc);
        if (preg_match_all("~$pattern~", $output, $matches)) {
            $list = $matches[1];
        }

        $releases = [];
        foreach ($list as $name) {
            $date = $this->shell->read("$path/releases/$name/release.lock");
            if ($date) {
                $releases[$date] = $name;
            }
        }

        krsort($releases);

        return $releases;
    }

    /**
     * Get current release path.
     *
     * @return string|null
     */
    public function getCurrentReleasePath()
    {
        $path = $this->getDeployPath();

        return $this->shell->exists("$path/current") ? $this->shell->realpath("$path/current") : null;
    }

    /**
     * Get current release name.
     *
     * @return string|null
     */
    public function getCurrentReleaseName()
    {
        $path = $this->getDeployPath();

        $current = $this->getCurrentReleasePath();

        $rplc = ['/' => '\/', '.' => '\.'];
        $pattern = strtr("$path/releases/", $rplc) . '(.+)';
        if (preg_match("~$pattern~", $current, $matches)) {
            return $matches[1];
        }

        return null;
    }

    /**
     * Get release path by name.
     *
     * @param $name
     *
     * @return string
     */
    public function getReleasePathByName($name)
    {
        $path = $this->getDeployPath();

        $releasePath = "$path/releases/$name";

        if (!$this->shell->exists($releasePath)) {
            throw new \RuntimeException('Release path not exists.');
        }

        return $this->shell->realpath($releasePath);
    }
}


text:
Instalace Cordovy
=================

```npm install -g cordova```

Vytvoreni aplikace pomoci Cordovy
=================================

Je potreba mit nainstalovane Android SDK a nastavene cesty.

```
cordova create gcm com.example.gcm GCM
cd gcm
```

Tim vznikne:

```
$ tree
.
├── config.xml
├── hooks
│   └── README.md
├── platforms
├── plugins
└── www
    ├── css
    │   └── index.css
    ├── img
    │   └── logo.png
    ├── index.html
    └── js
        └── index.js

7 directories, 6 files
```

Pridame Android:

```
cordova platform add android
cordova platforms ls
```

Obsah app je v adresari **www**.

Sestaveni a test
----------------

```
cordova build
cordova emulate android
cordova run android

```

emulate=emulator, run=mobil pres usb.

GCM plugin (Google Cloud Messaging)
-----------------------------------

Pravdepodobne je to tento: https://github.com/phonegap/phonegap-plugin-push

Instalace:

```
cordova plugin add phonegap-plugin-push
cordova plugin ls
```

Cordova app - jak na to
=======================

Po vygenerovani kostry app jsem jenom upravil tuto kostru. Dulezity je pouze obsah adresare **www**.

Pridal jsem *jQuery* a *materialise.js* JS knihovny, ale slo by to i bez nich.

Je potreba upravit *www/js/index.js*. Hlavne tam dat ID z webu GCM.

APK pro android bude v *gcm/platforms/android/build/outputs/apk/android-debug.apk*

Poznamky
=======

Ziskani GCM ID/KEY: https://developers.google.com/cloud-messaging/

Pokud je na mobilu apliakce otevrena, prichozi notifikace se pripise na konec a to je vse. Pokud je aplikace na pozadi (nema otevrene okno), mobil zahlasi notifikaci a prida ji do notifiakcniho menu (nevim jak se to jmenuje - proste jak se stahne horni lista dolu...).


text:
/*
* Gets the input from the input.txt. Does a check for existence first.
*/
var fs   = require('fs');
var when = require('when');

module.exports = function (fileName) {
  return when.promise(function (resolve, reject) {

    fs.readFile(__dirname+'/../'+fileName, function (err, result) {

      // Recognised error
      if (err && err.toString().indexOf('no such file or directory')) {
        reject(new Error('input with `fileName` "'+fileName+'" does not exist'));
      }

      // Unrecognised error
      else if (err) {
        reject(err);
      }

      // All good! Resolve as a string
      else {
        resolve(result.toString());
      }

    });

  });
};


text:
import React from 'react'
import ReactDOM from 'react-dom'
import { expect } from 'chai'
import { browserHistory } from 'react-router'
import questions from './../fixtures/questions'
import categories from './../fixtures/categories'
import TestUtils from 'react-addons-test-utils'
import sinon from 'sinon'

import SurveyQuestionPager
  from './../../../../assets/js/components/ecosystems/SurveyQuestionPager.jsx'

import {
  incrementSurveyQuestionIndex,
  decrementSurveyQuestionIndex,
  removeSurveyQuestionResponseAndIntensity
} from './../../../../assets/js/redux/survey/survey-actions.js'

describe('Survey Question Pager', () => {

  let component, stub, dispatch

  context('Sanity Check', () => {
    beforeEach(() => {
      dispatch = sinon.spy()
      stub = sinon.stub(browserHistory, 'push', (() => true))
      component = TestUtils.renderIntoDocument(
        <SurveyQuestionPager
          categories={categories}
          questions={questions}
          index={1}
          dispatch={dispatch} />
      )
    })

    it('will exist', () => {
      expect(component).to.be.ok
    })

    it('will have an initial alerts object in its state', () => {
      expect(component).to.have.property('state')
        .that.have.property('alerts')
        .that.is.an('object')
    })
  })

  context('Survey Question Pager', () => {

    context('Back Button', () => {

      let component

      before(() => {
        component = TestUtils.renderIntoDocument(
          <SurveyQuestionPager
            categories={categories}
            questions={questions}
            index={1}
            dispatch={dispatch} />
        )
      })

      it('should show the previous question in the survey if clicked and the ' +
         'use has answered at least one question', () => {

        const backButton = ReactDOM.findDOMNode(component.refs.backButton)

        TestUtils.Simulate.click(backButton)
        expect(dispatch).to.be.called
        sinon.assert.calledWith(dispatch, decrementSurveyQuestionIndex())

      })

      it('should go back to the first page if clicked on the first index', () => {

        const backButton = ReactDOM.findDOMNode(component.refs.backButton)

        TestUtils.Simulate.click(backButton)
        expect(stub).to.have.been.called

      })

    })

    context('Skip Button', () => {

      it('should allow the use to skip to the next question', () => {

        const skipButton = ReactDOM.findDOMNode(component.refs.skipButton)

        TestUtils.Simulate.click(skipButton)
        expect(dispatch).to.have.been.called

      })

      it('should dispatch an action to remove this response', () => {

        const skipButton = ReactDOM.findDOMNode(component.refs.skipButton)

        TestUtils.Simulate.click(skipButton)
        sinon.assert.calledWith(dispatch, incrementSurveyQuestionIndex())

      })

    })

    context('Next Button', () => {

      it('should allow the user to skip to the next question if they have ' +
         'not interacted with other parts of the form', () => {

        const nextButton = ReactDOM.findDOMNode(component.refs.nextButton)

        TestUtils.Simulate.click(nextButton)
        sinon.assert.calledWith(dispatch, incrementSurveyQuestionIndex())

      })

      it('should go to the next question if clicked and the user has answered ' +
         'the question and selected how strong they feel', () => {

        const nextButton = ReactDOM.findDOMNode(component.refs.nextButton)

        TestUtils.Simulate.click(nextButton)
        sinon.assert.calledWith(dispatch, incrementSurveyQuestionIndex())

      })

      it('should provide messaging if clicked and if intensity was not selected', () => {

        const nextButton = ReactDOM.findDOMNode(component.refs.nextButton)

        questions[1] = Object.assign(questions[1], {
          selectedAnswer: 'Potato Brain'
        })

        TestUtils.Simulate.click(nextButton)
        expect(Object.keys(component.state.alerts).length).to.equal(1)

      })

      it('should provide messaging if clicked and if an answer was not selected', () => {

        const nextButton = ReactDOM.findDOMNode(component.refs.nextButton)

        questions[3] = Object.assign(questions[3], {
          intensity: 5
        })

        component.state.index = 3
        TestUtils.Simulate.click(nextButton)
        expect(component.state.index).to.equal(3)
        expect(Object.keys(component.state.alerts).length).to.equal(1)

      })

      it('should navigate to the next page if the user is on the last question ' +
         ' and validation passes.', () => {

        questions[35] = Object.assign(questions[3], {
          intensity: 5,
          selectedAnswer: 'My Neighbor Totoro'
        })

        const nextButton = ReactDOM.findDOMNode(component.refs.nextButton)
        component.state.index = 35
        TestUtils.Simulate.click(nextButton)
        expect(component.state.index).to.equal(35)
        expect(stub).to.have.been.called
      })

    })

  })

  afterEach(() => {
    stub.restore()
  })
})


text:
import React from 'react'
import { mount, shallow } from 'enzyme'
import { Dummy } from './utils'
import { compose, withProps, withStateHandlers } from '..'

describe('withStateHandlers', () => {
  it('adds a stateful value and a function for updating it', () => {
    const Counter = withStateHandlers(
      { counter: 0 },
      {
        updateCounter: ({ counter }) => increment => ({
          counter: counter + increment,
        }),
      },
    )(Dummy)

    const wrapper = mount(<Counter pass="through" />)
    const { updateCounter } = wrapper.find(Dummy).props()

    expect(wrapper.find(Dummy).prop('counter')).toBe(0)
    expect(wrapper.find(Dummy).prop('pass')).toBe('through')

    updateCounter(9)
    wrapper.update()
    expect(wrapper.find(Dummy).prop('counter')).toBe(9)
    updateCounter(1)
    wrapper.update()
    updateCounter(10)
    wrapper.update()
    expect(wrapper.find(Dummy).prop('counter')).toBe(20)
    expect(wrapper.find(Dummy).prop('pass')).toBe('through')
  })

  it('accepts initialState as a function of props', () => {
    const Counter = withStateHandlers(
      ({ initialCounter }) => ({ counter: initialCounter }),
      {
        updateCounter: ({ counter }) => increment => ({
          counter: counter + increment,
        }),
      },
    )(Dummy)

    const initialCounter = 101
    const wrapper = mount(<Counter initialCounter={initialCounter} />)

    expect(wrapper.find(Dummy).prop('counter')).toBe(initialCounter)
  })

  it('has access to props', () => {
    const Counter = withStateHandlers(
      ({ initialCounter }) => ({ counter: initialCounter }),
      {
        increment: ({ counter }, { incrementValue }) => () => ({
          counter: counter + incrementValue,
        }),
      },
    )(Dummy)

    const initialCounter = 101
    const incrementValue = 37
    const wrapper = mount(
      <Counter
        initialCounter={initialCounter}
        incrementValue={incrementValue}
      />,
    )
    const { increment } = wrapper.find(Dummy).props()

    increment()
    wrapper.update()

    expect(wrapper.find(Dummy).prop('counter')).toBe(
      initialCounter + incrementValue,
    )
  })

  it('passes immutable state updaters', () => {
    const EnhancedDummy = withStateHandlers(
      {},
      {
        handler: () => () => null,
      },
    )(Dummy)
    expect(EnhancedDummy.displayName).toBe('withStateHandlers(Dummy)')

    const wrapper = shallow(<EnhancedDummy />)
    const handler = wrapper.prop('handler')

    wrapper.setProps({ foo: 'bar' })
    expect(wrapper.prop('foo')).toBe('bar')
    expect(wrapper.prop('handler')).toBe(handler)
  })

  it('handles state updater returning undefined', () => {
    const Counter = withStateHandlers(
      ({ initialCounter }) => ({ counter: initialCounter }),
      {
        updateCounter: ({ counter }) => increment =>
          increment === 0 ? undefined : { counter: counter + increment },
      },
    )(Dummy)

    const initialCounter = 101
    const wrapper = mount(<Counter initialCounter={initialCounter} />)
    const { updateCounter } = wrapper.find(Dummy).props()

    updateCounter(0)
    wrapper.update()

    expect(wrapper.find(Dummy).prop('counter')).toBe(initialCounter)
  })

  it('is merged with other HOCs', () => {
    const Component = compose(
      withProps({ initialCounter: 1 }),
      withStateHandlers(({ initialCounter }) => ({ counter: initialCounter }), {
        updateCounter: ({ counter }) => increment => counter + increment,
      }),
    )(Dummy)

    const wrapper = shallow(<Component />)
    expect(wrapper.instance().constructor.displayName).toBe(
      'withProps(withStateHandlers(Dummy))',
    )
    expect(wrapper.prop('counter')).toBe(1)
    expect(wrapper.prop('initialCounter')).toBe(1)
  })

  it('does not rerender if state updater returns undefined', () => {
    const component = jest.fn(() => null)
    component.displayName = 'component'

    const Counter = withStateHandlers(
      ({ initialCounter }) => ({
        counter: initialCounter,
      }),
      {
        updateCounter: ({ counter }) => increment =>
          increment === 0
            ? undefined
            : {
                counter: counter + increment,
              },
      },
    )(component)

    const initialCounter = 101

    mount(<Counter initialCounter={initialCounter} />)
    expect(component.mock.calls.length).toBe(1)

    const { updateCounter } = component.mock.calls[0][0]

    updateCounter(1)
    expect(component.mock.calls.length).toBe(2)

    updateCounter(0)
    expect(component.mock.calls.length).toBe(2)
  })
})


text:
#pragma once

#if USE_FALLBACK_EEPROM
  #define FLASH_EEPROM_EMULATION
#elif EITHER(I2C_EEPROM, SPI_EEPROM)
  #define USE_SHARED_EEPROM 1
#endif


text:
@implementation UIViewController (WMFHideKeyboard)

- (void)wmf_hideKeyboard {
    //http://stackoverflow.com/questions/11879745/an-utility-method-for-hiding-the-keyboard
    [[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];
}

@end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1">
<title>Class Index</title>
<link href="../css/codadoc.css" rel="stylesheet" type="text/css">

Main Page
Classes

Class Index

A | C | E | F | N | P | S | T

A

ArrayOrderingEnum

C

Coda (nl.stcorp.coda)

CodaException (nl.stcorp.coda)

Cursor (nl.stcorp.coda)

E

Expression (nl.stcorp.coda)

F

FormatEnum

N

NativeTypeEnum

P

Product (nl.stcorp.coda)

S

SpecialTypeEnum

T

Type (nl.stcorp.coda)

TypeClassEnum

Copyright © 2007-2022 s[&]t, The Netherlands.