<commit_before>#ifndef STAN_MATH_OPENCL_PRIM_BINOMIAL_LPMF_HPP
#define STAN_MATH_OPENCL_PRIM_BINOMIAL_LPMF_HPP
#ifdef STAN_OPENCL

#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/err.hpp>
#include <stan/math/opencl/kernel_generator.hpp>
#include <stan/math/prim/functor/operands_and_partials.hpp>

namespace stan {
namespace math {

/** \ingroup opencl
 * Returns the log PMF for the binomial distribution evaluated at the
 * specified success, population size, and chance of success. If given
 * containers of matching lengths, returns the log sum of probabilities.
 *
 * @tparam T_n_cl type of successes parameter
 * @tparam T_N_cl type of population size parameter
 * @tparam T_prob_cl type of chance of success parameter
 * @param n successes parameter
 * @param N population size parameter
 * @param theta chance of success parameter
 * @return log sum of probabilities
 * @throw std::domain_error if n is negative or greater than N
 * @throw std::domain_error if N is negative
 * @throw std::domain_error if theta is not a valid probability
 * @throw std::invalid_argument if container sizes mismatch
 */
template <
    bool propto, typename T_n_cl, typename T_N_cl, typename T_prob_cl,
    require_all_prim_or_rev_kernel_expression_t<T_n_cl, T_prob_cl>* = nullptr,
    require_any_not_stan_scalar_t<T_n_cl, T_prob_cl>* = nullptr>
return_type_t<T_prob_cl> binomial_lpmf(const T_n_cl& n, const T_N_cl N,
                                       const T_prob_cl& theta) {
  static const char* function = "binomial_lpmf(OpenCL)";
  using T_partials_return = partials_return_t<T_prob_cl>;
  using std::isnan;

  check_consistent_sizes(function, "Successes variable", n,
                         "Population size parameter", N,
                         "Probability parameter", theta);
  const size_t siz = max_size(n, N, theta);
  if (siz == 0) {
    return 0.0;
  }
  if (!include_summand<propto, T_prob_cl>::value) {
    return 0.0;
  }

  const auto& theta_val = value_of(theta);

  auto check_n_bounded
      = check_cl(function, "Successes variable", n, "in the interval [0, N]");
  auto n_bounded = 0 <= n && n <= N;
  auto check_N_nonnegative
      = check_cl(function, "Population size variable", n, "nonnegative");
  auto N_nonnegative = N >= 0;
  auto check_theta_bounded = check_cl(function, "Probability parameter",
                                      theta_val, "in the interval [0, 1]");
  auto theta_bounded = 0.0 <= theta_val && theta_val <= 1.0;

  auto log1m_theta = log1p(-theta_val);

  auto n_times_log_theta = elt_multiply(n, log(theta_val));
  auto n_is_zero = n == 0;
  auto N_is_zero = N == 0;
  auto n_is_N = n == N;
  auto N_minus_n = N - n;
  auto logp1 = select(
      N_is_zero, 0.0,
      select(n_is_zero, elt_multiply(N, log1m_theta),
             select(n_is_N, n_times_log_theta,
                    n_times_log_theta + elt_multiply(N_minus_n, log1m_theta))));
  auto logp_expr = colwise_sum(static_select<include_summand<propto>::value>(
      logp1 + binomial_coefficient_log(N, n), logp1));

  auto sum_n_expr = colwise_sum(n);
  auto sum_N_expr = colwise_sum(N);

  auto n_div_theta = elt_divide(n, theta_val);
  auto one_m_theta = 1.0 - theta_val;
  auto deriv_theta = select(
      N_is_zero, 0.0,
      select(n_is_zero, -elt_divide(N, one_m_theta),
             select(n_is_N, n_div_theta,
                    n_div_theta - elt_divide(N_minus_n, one_m_theta))));

  matrix_cl<int> sum_n_cl;
  matrix_cl<int> sum_N_cl;
  matrix_cl<double> logp_cl;
  matrix_cl<double> deriv_cl;

  constexpr bool need_sums
      = !is_constant_all<T_prob_cl>::value && is_stan_scalar<T_prob_cl>::value;
  constexpr bool need_deriv
      = !is_constant_all<T_prob_cl>::value && !is_stan_scalar<T_prob_cl>::value;

  results(check_n_bounded, check_N_nonnegative, check_theta_bounded, logp_cl,
          sum_n_cl, sum_N_cl, deriv_cl)
      = expressions(n_bounded, N_nonnegative, theta_bounded, logp_expr,
                    calc_if<need_sums>(sum_n_expr),
                    calc_if<need_sums>(sum_N_expr),
                    calc_if<need_deriv>(deriv_theta));

  T_partials_return logp = sum(from_matrix_cl(logp_cl));
  operands_and_partials<T_prob_cl> ops_partials(theta);

  if (!is_constant_all<T_prob_cl>::value) {
    if (need_sums) {
      int sum_n = sum(from_matrix_cl(sum_n_cl));
      int sum_N = sum(from_matrix_cl(sum_N_cl));
      double theta_dbl = forward_as<double>(theta_val);
      double& partial = forward_as<internal::broadcast_array<double>>(
          ops_partials.edge1_.partials_)[0];
      if (sum_N != 0) {
        if (sum_n == 0) {
          partial = -sum_N / (1.0 - theta_dbl);
        } else if (sum_n == sum_N) {
          partial = sum_n / theta_dbl;
        } else {
          partial = sum_n / theta_dbl - (sum_N - sum_n) / (1.0 - theta_dbl);
        }
      }
    } else {
      ops_partials.edge1_.partials_ = std::move(deriv_cl);
    }
  }

  return ops_partials.build(logp);
}

}  // namespace math
}  // namespace stan
#endif
#endif
<commit_msg>binomial_lpmf fixes<commit_after>#ifndef STAN_MATH_OPENCL_PRIM_BINOMIAL_LPMF_HPP
#define STAN_MATH_OPENCL_PRIM_BINOMIAL_LPMF_HPP
#ifdef STAN_OPENCL

#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/err.hpp>
#include <stan/math/opencl/kernel_generator.hpp>
#include <stan/math/prim/functor/operands_and_partials.hpp>
#include <stan/math/prim/fun/binomial_coefficient_log.hpp>

namespace stan {
namespace math {

/** \ingroup opencl
 * Returns the log PMF for the binomial distribution evaluated at the
 * specified success, population size, and chance of success. If given
 * containers of matching lengths, returns the log sum of probabilities.
 *
 * @tparam T_n_cl type of successes parameter
 * @tparam T_N_cl type of population size parameter
 * @tparam T_prob_cl type of chance of success parameter
 * @param n successes parameter
 * @param N population size parameter
 * @param theta chance of success parameter
 * @return log sum of probabilities
 * @throw std::domain_error if n is negative or greater than N
 * @throw std::domain_error if N is negative
 * @throw std::domain_error if theta is not a valid probability
 * @throw std::invalid_argument if container sizes mismatch
 */
template <
    bool propto, typename T_n_cl, typename T_N_cl, typename T_prob_cl,
    require_all_prim_or_rev_kernel_expression_t<T_n_cl, T_N_cl, T_prob_cl>* = nullptr,
    require_any_nonscalar_prim_or_rev_kernel_expression_t<T_n_cl, T_N_cl, T_prob_cl>* = nullptr>
return_type_t<T_prob_cl> binomial_lpmf(const T_n_cl& n, const T_N_cl N,
                                       const T_prob_cl& theta) {
  static const char* function = "binomial_lpmf(OpenCL)";
  using T_partials_return = partials_return_t<T_prob_cl>;
  using std::isnan;

  check_consistent_sizes(function, "Successes variable", n,
                         "Population size parameter", N,
                         "Probability parameter", theta);
  const size_t siz = max_size(n, N, theta);
  if (siz == 0) {
    return 0.0;
  }
  if (!include_summand<propto, T_prob_cl>::value) {
    return 0.0;
  }

  const auto& theta_val = value_of(theta);

  auto check_n_bounded
      = check_cl(function, "Successes variable", n, "in the interval [0, N]");
  auto n_bounded = 0 <= n && n <= N;
  auto check_N_nonnegative
      = check_cl(function, "Population size variable", n, "nonnegative");
  auto N_nonnegative = N >= 0;
  auto check_theta_bounded = check_cl(function, "Probability parameter",
                                      theta_val, "in the interval [0, 1]");
  auto theta_bounded = 0.0 <= theta_val && theta_val <= 1.0;

  auto log1m_theta = log1p(-theta_val);

  auto n_times_log_theta = elt_multiply(n, log(theta_val));
  auto n_is_zero = n == 0;
  auto N_is_zero = N == 0;
  auto n_is_N = n == N;
  auto N_minus_n = N - n;
  auto logp1 = select(
      N_is_zero, 0.0,
      select(n_is_zero, elt_multiply(N, log1m_theta),
             select(n_is_N, n_times_log_theta,
                    n_times_log_theta + elt_multiply(N_minus_n, log1m_theta))));
  auto logp_expr = colwise_sum(static_select<include_summand<propto>::value>(
      logp1 + binomial_coefficient_log(N, n), logp1));

  auto sum_n_expr = colwise_sum(n);
  auto sum_N_expr = colwise_sum(N);

  auto n_div_theta = elt_divide(n, theta_val);
  auto one_m_theta = 1.0 - theta_val;
  auto deriv_theta = select(
      N_is_zero, 0.0,
      select(n_is_zero, -elt_divide(N, one_m_theta),
             select(n_is_N, n_div_theta,
                    n_div_theta - elt_divide(N_minus_n, one_m_theta))));

  matrix_cl<int> sum_n_cl;
  matrix_cl<int> sum_N_cl;
  matrix_cl<double> logp_cl;
  matrix_cl<double> deriv_cl;

  constexpr bool need_sums
      = !is_constant_all<T_prob_cl>::value && is_stan_scalar<T_prob_cl>::value;
  constexpr bool need_deriv
      = !is_constant_all<T_prob_cl>::value && !is_stan_scalar<T_prob_cl>::value;

  results(check_n_bounded, check_N_nonnegative, check_theta_bounded, logp_cl,
          sum_n_cl, sum_N_cl, deriv_cl)
      = expressions(n_bounded, N_nonnegative, theta_bounded, logp_expr,
                    calc_if<need_sums>(sum_n_expr),
                    calc_if<need_sums>(sum_N_expr),
                    calc_if<need_deriv>(deriv_theta));

  T_partials_return logp = sum(from_matrix_cl(logp_cl));
  operands_and_partials<T_prob_cl> ops_partials(theta);

  if (!is_constant_all<T_prob_cl>::value) {
    if (need_sums) {
      int sum_n = sum(from_matrix_cl(sum_n_cl));
      int sum_N = sum(from_matrix_cl(sum_N_cl));
      double theta_dbl = forward_as<double>(theta_val);
      double& partial = forward_as<internal::broadcast_array<double>>(
          ops_partials.edge1_.partials_)[0];
      if (sum_N != 0) {
        if (sum_n == 0) {
          partial = -sum_N / (1.0 - theta_dbl);
        } else if (sum_n == sum_N) {
          partial = sum_n / theta_dbl;
        } else {
          partial = sum_n / theta_dbl - (sum_N - sum_n) / (1.0 - theta_dbl);
        }
      }
    } else {
      ops_partials.edge1_.partials_ = std::move(deriv_cl);
    }
  }

  return ops_partials.build(logp);
}

}  // namespace math
}  // namespace stan
#endif
#endif
<|endoftext|>


<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <windows.h>
#include <shlwapi.h>

#include "chrome/app/breakpad_win.h"
#include "chrome/app/client_util.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/result_codes.h"
#include "chrome/installer/util/browser_distribution.h"
#include "chrome/installer/util/install_util.h"
#include "chrome/installer/util/google_update_constants.h"
#include "chrome/installer/util/util_constants.h"

namespace {
// The entry point signature of chrome.dll.
typedef int (*DLL_MAIN)(HINSTANCE, sandbox::SandboxInterfaceInfo*, wchar_t*);

typedef void (*RelaunchChromeBrowserWithNewCommandLineIfNeededFunc)();

// Not generic, we only handle strings up to 128 chars.
bool ReadRegistryStr(HKEY key, const wchar_t* name, std::wstring* value) {
  BYTE out[128 * sizeof(wchar_t)];
  DWORD size = sizeof(out);
  DWORD type = 0;
  if (ERROR_SUCCESS != ::RegQueryValueExW(key, name, NULL, &type, out, &size))
    return false;
  if (type != REG_SZ)
    return false;
  value->assign(reinterpret_cast<wchar_t*>(out));
  return true;
}

// Gets chrome version according to the load path. |exe_path| must be the
// backslash terminated directory of the current chrome.exe.
bool GetVersion(const wchar_t* exe_path, const wchar_t* key_path,
                std::wstring* version) {
  HKEY reg_root = InstallUtil::IsPerUserInstall(exe_path) ? HKEY_CURRENT_USER :
                                                            HKEY_LOCAL_MACHINE;
  HKEY key;
  if (::RegOpenKeyEx(reg_root, key_path, 0, KEY_READ, &key) != ERROR_SUCCESS)
    return false;

  // If 'new_chrome.exe' is present it means chrome was auto-updated while
  // running. We need to consult the opv value so we can load the old dll.
  // TODO(cpu) : This is solving the same problem as the environment variable
  // so one of them will eventually be deprecated.
  std::wstring new_chrome_exe(exe_path);
  new_chrome_exe.append(installer_util::kChromeNewExe);
  if (::PathFileExistsW(new_chrome_exe.c_str()) &&
      ReadRegistryStr(key, google_update::kRegOldVersionField, version)) {
    ::RegCloseKey(key);
    return true;
  }

  bool ret = ReadRegistryStr(key, google_update::kRegVersionField, version);
  ::RegCloseKey(key);
  return ret;
}

// Gets the path of the current exe with a trailing backslash.
std::wstring GetExecutablePath() {
  wchar_t path[MAX_PATH];
  ::GetModuleFileNameW(NULL, path, MAX_PATH);
  if (!::PathRemoveFileSpecW(path))
    return std::wstring();
  std::wstring exe_path(path);
  return exe_path.append(L"\\");
}

// Not generic, we only handle strings up to 128 chars.
bool EnvQueryStr(const wchar_t* key_name, std::wstring* value) {
  wchar_t out[128];
  DWORD count = sizeof(out)/sizeof(out[0]);
  DWORD rv = ::GetEnvironmentVariableW(key_name, out, count);
  if ((rv == 0) || (rv >= count))
    return false;
  *value = out;
  return true;
}

bool IsRunningHeadless() {
  return (0 != ::GetEnvironmentVariableW(L"CHROME_HEADLESS", NULL, 0));
}

// Expects that |dir| has a trailing backslash. |dir| is modified so it
// contains the full path that was tried. Caller must check for the return
// value not being null to dermine if this path contains a valid dll.
HMODULE LoadChromeWithDirectory(std::wstring* dir) {
  ::SetCurrentDirectoryW(dir->c_str());
#ifdef _WIN64
  const CommandLine& cmd_line = *CommandLine::ForCurrentProcess();
  if ((cmd_line.GetSwitchValueASCII(switches::kProcessType) ==
      switches::kNaClBrokerProcess) ||
      (cmd_line.GetSwitchValueASCII(switches::kProcessType) ==
      switches::kNaClLoaderProcess)) {
    // Load the 64-bit DLL when running in a 64-bit process.
    dir->append(installer_util::kChromeNaCl64Dll);
  } else {
    // Only NaCl broker and loader can be launched as Win64 processes.
    NOTREACHED();
    return NULL;
  }
#else
  dir->append(installer_util::kChromeDll);
#endif

  // Experimental pre-reading optimization
  // The idea is to pre read significant portion of chrome.dll in advance
  // so that subsequent hard page faults are avoided.
  DWORD pre_read_size_mb = 0;
  const CommandLine& cmd_line = *CommandLine::ForCurrentProcess();
  if (!cmd_line.HasSwitch(switches::kProcessType) &&
      (IsRunningHeadless() || InstallUtil::IsChromeFrameProcess())) {
    HKEY key = NULL;
    if (::RegOpenKeyEx(HKEY_CURRENT_USER, L"Software\\Google\\ChromeFrame",
                       0, KEY_QUERY_VALUE, &key) == ERROR_SUCCESS) {
      DWORD unused = sizeof(pre_read_size_mb);
      RegQueryValueEx(key, L"PreRead", NULL, NULL,
                      reinterpret_cast<LPBYTE>(&pre_read_size_mb), &unused);
      RegCloseKey(key);
      key = NULL;
    } else {
      pre_read_size_mb = 16; // Read in first 16 MB by default.
    }
  }

  if (pre_read_size_mb) {
    HANDLE chrome_dll = CreateFile(dir->c_str(),
                                       GENERIC_READ,
                                       FILE_SHARE_READ | FILE_SHARE_WRITE,
                                       NULL,
                                       OPEN_EXISTING,
                                       FILE_FLAG_SEQUENTIAL_SCAN,
                                       NULL);
    if (chrome_dll == INVALID_HANDLE_VALUE) {
      DWORD error = GetLastError();
      DLOG(ERROR) << __FUNCTION__ << " CreateFile( "
          << dir->c_str() << " ) failed. Error: " << error;
    } else {
      const size_t kChunkSize = 1024 * 1024; // 1 MB
      void* buffer = VirtualAlloc(NULL, kChunkSize, MEM_COMMIT, PAGE_READWRITE);
      if (buffer) {
        size_t read_size = pre_read_size_mb * kChunkSize;
        DWORD read = 0;
        while (::ReadFile(chrome_dll, buffer, kChunkSize, &read, NULL)) {
          // nothing to do here...
          read_size -= std::min(size_t(read), read_size);
          if (!read || !read_size)
            break;
        }

        VirtualFree(buffer, 0, MEM_RELEASE);
      }

      CloseHandle(chrome_dll);
    }
  }

  return ::LoadLibraryExW(dir->c_str(), NULL,
                          LOAD_WITH_ALTERED_SEARCH_PATH);
}

// Set did_run "dr" in omaha's client state for this product.
bool SetDidRunState(const wchar_t* guid, const wchar_t* value) {
  std::wstring key_path(google_update::kRegPathClientState);
  key_path.append(L"\\").append(guid);
  HKEY reg_key;
  if (::RegCreateKeyExW(HKEY_CURRENT_USER, key_path.c_str(), 0, NULL,
                        REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL,
                        &reg_key, NULL) == ERROR_SUCCESS) {
    // Note that the length here must be in bytes and must account for the
    // terminating null char.
    ::RegSetValueExW(reg_key, google_update::kRegDidRunField, 0, REG_SZ,
                     reinterpret_cast<const BYTE *>(value),
                     (::lstrlenW(value) + 1) * sizeof(wchar_t));
    ::RegCloseKey(reg_key);
    return true;
  }
  return false;
}

bool RecordDidRun(const wchar_t* guid) {
  return SetDidRunState(guid, L"1");
}

bool ClearDidRun(const wchar_t* guid) {
  return SetDidRunState(guid, L"0");
}

}
//=============================================================================

MainDllLoader::MainDllLoader() : dll_(NULL) {
}

MainDllLoader::~MainDllLoader() {
#ifdef PURIFY
  // We should never unload the dll. There is only risk and no gain from
  // doing so. The singleton dtors have been already run by AtExitManager.
  ::FreeLibrary(dll_);
#endif
}

// Loading chrome is an interesting afair. First we try loading from the current
// directory to support run-what-you-compile and other development scenarios.
// If that fails then we look at the 'CHROME_VERSION' env variable to determine
// if we should stick with an older dll version even if a new one is available
// to support upgrade-in-place scenarios, and if that fails we finally we look
// at the registry which should point us to the latest version.
HMODULE MainDllLoader::Load(std::wstring* version, std::wstring* file) {
  std::wstring dir(GetExecutablePath());
  *file = dir;
  HMODULE dll = LoadChromeWithDirectory(file);
  if (dll)
    return dll;

  if (!EnvQueryStr(
          BrowserDistribution::GetDistribution()->GetEnvVersionKey().c_str(),
          version)) {
    std::wstring reg_path(GetRegistryPath());
    // Look into the registry to find the latest version.
    if (!GetVersion(dir.c_str(), reg_path.c_str(), version))
      return NULL;
  }

  *file = dir;
  file->append(*version).append(L"\\");
  return LoadChromeWithDirectory(file);
}

// Launching is a matter of loading the right dll, setting the CHROME_VERSION
// environment variable and just calling the entry point. Derived classes can
// add custom code in the OnBeforeLaunch callback.
int MainDllLoader::Launch(HINSTANCE instance,
                          sandbox::SandboxInterfaceInfo* sbox_info) {
  std::wstring version;
  std::wstring file;
  dll_ = Load(&version, &file);
  if (!dll_)
    return ResultCodes::MISSING_DATA;

  ::SetEnvironmentVariableW(
      BrowserDistribution::GetDistribution()->GetEnvVersionKey().c_str(),
      version.c_str());

  InitCrashReporterWithDllPath(file);
  OnBeforeLaunch(version);

  DLL_MAIN entry_point =
      reinterpret_cast<DLL_MAIN>(::GetProcAddress(dll_, "ChromeMain"));
  if (!entry_point)
    return ResultCodes::BAD_PROCESS_TYPE;

  int rc = entry_point(instance, sbox_info, ::GetCommandLineW());
  return OnBeforeExit(rc);
}

void MainDllLoader::RelaunchChromeBrowserWithNewCommandLineIfNeeded() {
  RelaunchChromeBrowserWithNewCommandLineIfNeededFunc relaunch_function =
      reinterpret_cast<RelaunchChromeBrowserWithNewCommandLineIfNeededFunc>(
          ::GetProcAddress(dll_,
                           "RelaunchChromeBrowserWithNewCommandLineIfNeeded"));
  if (!relaunch_function) {
    LOG(ERROR) << "Could not find exported function "
               << "RelaunchChromeBrowserWithNewCommandLineIfNeeded";
  } else {
    relaunch_function();
  }
}

//=============================================================================

class ChromeDllLoader : public MainDllLoader {
 public:
  virtual std::wstring GetRegistryPath() {
    std::wstring key(google_update::kRegPathClients);
    BrowserDistribution* dist = BrowserDistribution::GetDistribution();
    key.append(L"\\").append(dist->GetAppGuid());
    return key;
  }

  virtual void OnBeforeLaunch(const std::wstring& version) {
    BrowserDistribution* dist = BrowserDistribution::GetDistribution();
    RecordDidRun(dist->GetAppGuid().c_str());
  }

  virtual int OnBeforeExit(int return_code) {
    // NORMAL_EXIT_CANCEL is used for experiments when the user cancels
    // so we need to reset the did_run signal so omaha does not count
    // this run as active usage.
    if (ResultCodes::NORMAL_EXIT_CANCEL == return_code) {
      BrowserDistribution* dist = BrowserDistribution::GetDistribution();
      ClearDidRun(dist->GetAppGuid().c_str());
    }
    return return_code;
  }
};

//=============================================================================

class ChromiumDllLoader : public MainDllLoader {
 public:
  virtual std::wstring GetRegistryPath() {
    BrowserDistribution* dist = BrowserDistribution::GetDistribution();
    return dist->GetVersionKey();
  }
};

MainDllLoader* MakeMainDllLoader() {
#if defined(GOOGLE_CHROME_BUILD)
  return new ChromeDllLoader();
#else
  return new ChromiumDllLoader();
#endif
}
<commit_msg>Fix nacl build<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <windows.h>
#include <shlwapi.h>

#include "chrome/app/breakpad_win.h"
#include "chrome/app/client_util.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/result_codes.h"
#include "chrome/installer/util/browser_distribution.h"
#include "chrome/installer/util/install_util.h"
#include "chrome/installer/util/google_update_constants.h"
#include "chrome/installer/util/util_constants.h"

namespace {
// The entry point signature of chrome.dll.
typedef int (*DLL_MAIN)(HINSTANCE, sandbox::SandboxInterfaceInfo*, wchar_t*);

typedef void (*RelaunchChromeBrowserWithNewCommandLineIfNeededFunc)();

// Not generic, we only handle strings up to 128 chars.
bool ReadRegistryStr(HKEY key, const wchar_t* name, std::wstring* value) {
  BYTE out[128 * sizeof(wchar_t)];
  DWORD size = sizeof(out);
  DWORD type = 0;
  if (ERROR_SUCCESS != ::RegQueryValueExW(key, name, NULL, &type, out, &size))
    return false;
  if (type != REG_SZ)
    return false;
  value->assign(reinterpret_cast<wchar_t*>(out));
  return true;
}

// Gets chrome version according to the load path. |exe_path| must be the
// backslash terminated directory of the current chrome.exe.
bool GetVersion(const wchar_t* exe_path, const wchar_t* key_path,
                std::wstring* version) {
  HKEY reg_root = InstallUtil::IsPerUserInstall(exe_path) ? HKEY_CURRENT_USER :
                                                            HKEY_LOCAL_MACHINE;
  HKEY key;
  if (::RegOpenKeyEx(reg_root, key_path, 0, KEY_READ, &key) != ERROR_SUCCESS)
    return false;

  // If 'new_chrome.exe' is present it means chrome was auto-updated while
  // running. We need to consult the opv value so we can load the old dll.
  // TODO(cpu) : This is solving the same problem as the environment variable
  // so one of them will eventually be deprecated.
  std::wstring new_chrome_exe(exe_path);
  new_chrome_exe.append(installer_util::kChromeNewExe);
  if (::PathFileExistsW(new_chrome_exe.c_str()) &&
      ReadRegistryStr(key, google_update::kRegOldVersionField, version)) {
    ::RegCloseKey(key);
    return true;
  }

  bool ret = ReadRegistryStr(key, google_update::kRegVersionField, version);
  ::RegCloseKey(key);
  return ret;
}

// Gets the path of the current exe with a trailing backslash.
std::wstring GetExecutablePath() {
  wchar_t path[MAX_PATH];
  ::GetModuleFileNameW(NULL, path, MAX_PATH);
  if (!::PathRemoveFileSpecW(path))
    return std::wstring();
  std::wstring exe_path(path);
  return exe_path.append(L"\\");
}

// Not generic, we only handle strings up to 128 chars.
bool EnvQueryStr(const wchar_t* key_name, std::wstring* value) {
  wchar_t out[128];
  DWORD count = sizeof(out)/sizeof(out[0]);
  DWORD rv = ::GetEnvironmentVariableW(key_name, out, count);
  if ((rv == 0) || (rv >= count))
    return false;
  *value = out;
  return true;
}

bool IsRunningHeadless() {
  return (0 != ::GetEnvironmentVariableW(L"CHROME_HEADLESS", NULL, 0));
}

// Expects that |dir| has a trailing backslash. |dir| is modified so it
// contains the full path that was tried. Caller must check for the return
// value not being null to dermine if this path contains a valid dll.
HMODULE LoadChromeWithDirectory(std::wstring* dir) {
  ::SetCurrentDirectoryW(dir->c_str());
  const CommandLine& cmd_line = *CommandLine::ForCurrentProcess();
#ifdef _WIN64
  if ((cmd_line.GetSwitchValueASCII(switches::kProcessType) ==
      switches::kNaClBrokerProcess) ||
      (cmd_line.GetSwitchValueASCII(switches::kProcessType) ==
      switches::kNaClLoaderProcess)) {
    // Load the 64-bit DLL when running in a 64-bit process.
    dir->append(installer_util::kChromeNaCl64Dll);
  } else {
    // Only NaCl broker and loader can be launched as Win64 processes.
    NOTREACHED();
    return NULL;
  }
#else
  dir->append(installer_util::kChromeDll);
#endif

  // Experimental pre-reading optimization
  // The idea is to pre read significant portion of chrome.dll in advance
  // so that subsequent hard page faults are avoided.
  DWORD pre_read_size_mb = 0;
  if (!cmd_line.HasSwitch(switches::kProcessType) &&
      (IsRunningHeadless() || InstallUtil::IsChromeFrameProcess())) {
    HKEY key = NULL;
    if (::RegOpenKeyEx(HKEY_CURRENT_USER, L"Software\\Google\\ChromeFrame",
                       0, KEY_QUERY_VALUE, &key) == ERROR_SUCCESS) {
      DWORD unused = sizeof(pre_read_size_mb);
      RegQueryValueEx(key, L"PreRead", NULL, NULL,
                      reinterpret_cast<LPBYTE>(&pre_read_size_mb), &unused);
      RegCloseKey(key);
      key = NULL;
    } else {
      pre_read_size_mb = 16; // Read in first 16 MB by default.
    }
  }

  if (pre_read_size_mb) {
    HANDLE chrome_dll = CreateFile(dir->c_str(),
                                       GENERIC_READ,
                                       FILE_SHARE_READ | FILE_SHARE_WRITE,
                                       NULL,
                                       OPEN_EXISTING,
                                       FILE_FLAG_SEQUENTIAL_SCAN,
                                       NULL);
    if (chrome_dll == INVALID_HANDLE_VALUE) {
      DWORD error = GetLastError();
      DLOG(ERROR) << __FUNCTION__ << " CreateFile( "
          << dir->c_str() << " ) failed. Error: " << error;
    } else {
      const size_t kChunkSize = 1024 * 1024; // 1 MB
      void* buffer = VirtualAlloc(NULL, kChunkSize, MEM_COMMIT, PAGE_READWRITE);
      if (buffer) {
        size_t read_size = pre_read_size_mb * kChunkSize;
        DWORD read = 0;
        while (::ReadFile(chrome_dll, buffer, kChunkSize, &read, NULL)) {
          // nothing to do here...
          read_size -= std::min(size_t(read), read_size);
          if (!read || !read_size)
            break;
        }

        VirtualFree(buffer, 0, MEM_RELEASE);
      }

      CloseHandle(chrome_dll);
    }
  }

  return ::LoadLibraryExW(dir->c_str(), NULL,
                          LOAD_WITH_ALTERED_SEARCH_PATH);
}

// Set did_run "dr" in omaha's client state for this product.
bool SetDidRunState(const wchar_t* guid, const wchar_t* value) {
  std::wstring key_path(google_update::kRegPathClientState);
  key_path.append(L"\\").append(guid);
  HKEY reg_key;
  if (::RegCreateKeyExW(HKEY_CURRENT_USER, key_path.c_str(), 0, NULL,
                        REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL,
                        &reg_key, NULL) == ERROR_SUCCESS) {
    // Note that the length here must be in bytes and must account for the
    // terminating null char.
    ::RegSetValueExW(reg_key, google_update::kRegDidRunField, 0, REG_SZ,
                     reinterpret_cast<const BYTE *>(value),
                     (::lstrlenW(value) + 1) * sizeof(wchar_t));
    ::RegCloseKey(reg_key);
    return true;
  }
  return false;
}

bool RecordDidRun(const wchar_t* guid) {
  return SetDidRunState(guid, L"1");
}

bool ClearDidRun(const wchar_t* guid) {
  return SetDidRunState(guid, L"0");
}

}
//=============================================================================

MainDllLoader::MainDllLoader() : dll_(NULL) {
}

MainDllLoader::~MainDllLoader() {
#ifdef PURIFY
  // We should never unload the dll. There is only risk and no gain from
  // doing so. The singleton dtors have been already run by AtExitManager.
  ::FreeLibrary(dll_);
#endif
}

// Loading chrome is an interesting afair. First we try loading from the current
// directory to support run-what-you-compile and other development scenarios.
// If that fails then we look at the 'CHROME_VERSION' env variable to determine
// if we should stick with an older dll version even if a new one is available
// to support upgrade-in-place scenarios, and if that fails we finally we look
// at the registry which should point us to the latest version.
HMODULE MainDllLoader::Load(std::wstring* version, std::wstring* file) {
  std::wstring dir(GetExecutablePath());
  *file = dir;
  HMODULE dll = LoadChromeWithDirectory(file);
  if (dll)
    return dll;

  if (!EnvQueryStr(
          BrowserDistribution::GetDistribution()->GetEnvVersionKey().c_str(),
          version)) {
    std::wstring reg_path(GetRegistryPath());
    // Look into the registry to find the latest version.
    if (!GetVersion(dir.c_str(), reg_path.c_str(), version))
      return NULL;
  }

  *file = dir;
  file->append(*version).append(L"\\");
  return LoadChromeWithDirectory(file);
}

// Launching is a matter of loading the right dll, setting the CHROME_VERSION
// environment variable and just calling the entry point. Derived classes can
// add custom code in the OnBeforeLaunch callback.
int MainDllLoader::Launch(HINSTANCE instance,
                          sandbox::SandboxInterfaceInfo* sbox_info) {
  std::wstring version;
  std::wstring file;
  dll_ = Load(&version, &file);
  if (!dll_)
    return ResultCodes::MISSING_DATA;

  ::SetEnvironmentVariableW(
      BrowserDistribution::GetDistribution()->GetEnvVersionKey().c_str(),
      version.c_str());

  InitCrashReporterWithDllPath(file);
  OnBeforeLaunch(version);

  DLL_MAIN entry_point =
      reinterpret_cast<DLL_MAIN>(::GetProcAddress(dll_, "ChromeMain"));
  if (!entry_point)
    return ResultCodes::BAD_PROCESS_TYPE;

  int rc = entry_point(instance, sbox_info, ::GetCommandLineW());
  return OnBeforeExit(rc);
}

void MainDllLoader::RelaunchChromeBrowserWithNewCommandLineIfNeeded() {
  RelaunchChromeBrowserWithNewCommandLineIfNeededFunc relaunch_function =
      reinterpret_cast<RelaunchChromeBrowserWithNewCommandLineIfNeededFunc>(
          ::GetProcAddress(dll_,
                           "RelaunchChromeBrowserWithNewCommandLineIfNeeded"));
  if (!relaunch_function) {
    LOG(ERROR) << "Could not find exported function "
               << "RelaunchChromeBrowserWithNewCommandLineIfNeeded";
  } else {
    relaunch_function();
  }
}

//=============================================================================

class ChromeDllLoader : public MainDllLoader {
 public:
  virtual std::wstring GetRegistryPath() {
    std::wstring key(google_update::kRegPathClients);
    BrowserDistribution* dist = BrowserDistribution::GetDistribution();
    key.append(L"\\").append(dist->GetAppGuid());
    return key;
  }

  virtual void OnBeforeLaunch(const std::wstring& version) {
    BrowserDistribution* dist = BrowserDistribution::GetDistribution();
    RecordDidRun(dist->GetAppGuid().c_str());
  }

  virtual int OnBeforeExit(int return_code) {
    // NORMAL_EXIT_CANCEL is used for experiments when the user cancels
    // so we need to reset the did_run signal so omaha does not count
    // this run as active usage.
    if (ResultCodes::NORMAL_EXIT_CANCEL == return_code) {
      BrowserDistribution* dist = BrowserDistribution::GetDistribution();
      ClearDidRun(dist->GetAppGuid().c_str());
    }
    return return_code;
  }
};

//=============================================================================

class ChromiumDllLoader : public MainDllLoader {
 public:
  virtual std::wstring GetRegistryPath() {
    BrowserDistribution* dist = BrowserDistribution::GetDistribution();
    return dist->GetVersionKey();
  }
};

MainDllLoader* MakeMainDllLoader() {
#if defined(GOOGLE_CHROME_BUILD)
  return new ChromeDllLoader();
#else
  return new ChromiumDllLoader();
#endif
}
<|endoftext|>


<commit_before>#ifndef STAN_MATH_PRIM_MAT_ERR_CHECK_FINITE_HPP
#define STAN_MATH_PRIM_MAT_ERR_CHECK_FINITE_HPP

#include <Eigen/Dense>
#include <stan/math/prim/scal/err/check_finite.hpp>

namespace stan {
namespace math {
namespace {
template <typename T, int R, int C>
struct finite<Eigen::Matrix<T, R, C>, true> {
  static void check(const char* function, const char* name,
                    const Eigen::Matrix<T, R, C>& y) {
    if (!y.allFinite())
      domain_error(function, name, y, "is ", ", but must be finite!");
  }
};
}
}
}

#endif
<commit_msg>[Jenkins] auto-formatting by clang-format version 6.0.0 (tags/google/stable/2017-11-14)<commit_after>#ifndef STAN_MATH_PRIM_MAT_ERR_CHECK_FINITE_HPP
#define STAN_MATH_PRIM_MAT_ERR_CHECK_FINITE_HPP

#include <Eigen/Dense>
#include <stan/math/prim/scal/err/check_finite.hpp>

namespace stan {
namespace math {
namespace {
template <typename T, int R, int C>
struct finite<Eigen::Matrix<T, R, C>, true> {
  static void check(const char* function, const char* name,
                    const Eigen::Matrix<T, R, C>& y) {
    if (!y.allFinite())
      domain_error(function, name, y, "is ", ", but must be finite!");
  }
};
}  // namespace
}  // namespace math
}  // namespace stan

#endif
<|endoftext|>


<commit_before><commit_msg>Fix spacing that was supposed to go in a previous checkin and somehow  missed it.<commit_after><|endoftext|>


<commit_before>#ifndef STAN_MATH_PRIM_MAT_FUN_COV_EXP_QUAD_HPP
#define STAN_MATH_PRIM_MAT_FUN_COV_EXP_QUAD_HPP

#include <stan/math/prim/scal/meta/return_type.hpp>
#include <stan/math/prim/scal/err/check_size_match.hpp>
#include <stan/math/prim/mat/fun/Eigen.hpp>
#include <stan/math/prim/mat/fun/squared_distance.hpp>
#include <stan/math/prim/scal/err/check_not_nan.hpp>
#include <stan/math/prim/scal/err/check_positive.hpp>
#include <stan/math/prim/scal/fun/square.hpp>
#include <vector>

namespace stan {
  namespace math {

    /**
     * Returns a squared exponential kernel.
     *
     * @tparam T_x type of std::vector of elements
     * @tparam T_sigma type of sigma
     * @tparam T_l type of length scale
     *
     * @param x std::vector of elements that can be used in square distance.
     *    This function assumes each element of x is the same size.
     * @param sigma standard deviation
     * @param l length scale
     * @return squared distance
     * @throw std::domain_error if sigma <= 0, l <= 0, or
     *   x is nan or infinite
     */
    template<typename T_x, typename T_sigma, typename T_l>
    inline typename
    Eigen::Matrix<typename stan::return_type<T_x, T_sigma, T_l>::type,
                  Eigen::Dynamic, Eigen::Dynamic>
    cov_exp_quad(const std::vector<T_x>& x,
                 const T_sigma& sigma,
                 const T_l& l) {
      check_positive("cov_exp_quad", "sigma", sigma);
      check_positive("cov_exp_quad", "l", l);
      for (size_t n = 0; n < x.size(); ++n)
        check_not_nan("cov_exp_quad", "x", x[n]);

      Eigen::Matrix<typename stan::return_type<T_x, T_sigma, T_l>::type,
                    Eigen::Dynamic, Eigen::Dynamic>
        cov(x.size(), x.size());

      int x_size = x.size();
      if (x_size == 0)
        return cov;

      T_sigma sigma_sq = square(sigma);
      T_l neg_half_inv_l_sq = - 0.5 / square(l);

      for (int j = 0; j < (x_size - 1); ++j) {
        cov(j, j) = sigma_sq;
        for (int i = j + 1; i < x_size; ++i) {
          cov(i, j) = sigma_sq * exp(squared_distance(x[i], x[j])
                                     * neg_half_inv_l_sq);
          cov(j, i) = cov(i, j);
        }
      }
      cov(x_size - 1, x_size - 1) = sigma_sq;
      return cov;
    }

    /**
     * Returns a squared exponential kernel.
     *
     * @tparam T_x1 type of first std::vector of elements
     * @tparam T_x2 type of second std::vector of elements
     * @tparam T_sigma type of sigma
     * @tparam T_l type of length scale
     *
     * @param x1 std::vector of elements that can be used in square distance
     * @param x2 std::vector of elements that can be used in square distance
     * @param sigma standard deviation
     * @param l length scale
     * @return squared distance
     * @throw std::domain_error if sigma <= 0, l <= 0, or
     *   x is nan or infinite
     */
    template<typename T_x1, typename T_x2, typename T_sigma, typename T_l>
    inline typename
    Eigen::Matrix<typename stan::return_type<T_x1, T_x2, T_sigma, T_l>::type,
                  Eigen::Dynamic, Eigen::Dynamic>
    cov_exp_quad(const std::vector<T_x1>& x1,
                 const std::vector<T_x2>& x2,
                 const T_sigma& sigma,
                 const T_l& l) {
      check_positive("cov_exp_quad", "sigma", sigma);
      check_positive("cov_exp_quad", "l", l);
      for (size_t n = 0; n < x1.size(); ++n)
        check_not_nan("cov_exp_quad", "x1", x1[n]);
      for (size_t n = 0; n < x2.size(); ++n)
        check_not_nan("cov_exp_quad", "x2", x2[n]);

      Eigen::Matrix<typename stan::return_type<T_x1, T_x2, T_sigma, T_l>::type,
                    Eigen::Dynamic, Eigen::Dynamic>
        cov(x1.size(), x2.size());
      if (x1.size() == 0 || x2.size() == 0)
        return cov;

      T_sigma sigma_sq = square(sigma);
      T_l neg_half_inv_l_sq = - 0.5 / square(l);

      for (size_t i = 0; i < x1.size(); ++i) {
        for (size_t j = 0; j < x2.size(); ++j) {
          cov(i, j) = sigma_sq * exp(squared_distance(x1[i], x2[j])
                                     * neg_half_inv_l_sq);
        }
      }
      return cov;
    }

  }
}
#endif
<commit_msg>Added explicit stan::math::exp include<commit_after>#ifndef STAN_MATH_PRIM_MAT_FUN_COV_EXP_QUAD_HPP
#define STAN_MATH_PRIM_MAT_FUN_COV_EXP_QUAD_HPP

#include <stan/math/prim/scal/meta/return_type.hpp>
#include <stan/math/prim/scal/err/check_size_match.hpp>
#include <stan/math/prim/mat/fun/Eigen.hpp>
#include <stan/math/prim/mat/fun/squared_distance.hpp>
#include <stan/math/prim/scal/err/check_not_nan.hpp>
#include <stan/math/prim/scal/err/check_positive.hpp>
#include <stan/math/prim/scal/fun/square.hpp>
#include <stan/math/prim/scal/fun/exp.hpp>
#include <vector>

namespace stan {
  namespace math {

    /**
     * Returns a squared exponential kernel.
     *
     * @tparam T_x type of std::vector of elements
     * @tparam T_sigma type of sigma
     * @tparam T_l type of length scale
     *
     * @param x std::vector of elements that can be used in square distance.
     *    This function assumes each element of x is the same size.
     * @param sigma standard deviation
     * @param l length scale
     * @return squared distance
     * @throw std::domain_error if sigma <= 0, l <= 0, or
     *   x is nan or infinite
     */
    template<typename T_x, typename T_sigma, typename T_l>
    inline typename
    Eigen::Matrix<typename stan::return_type<T_x, T_sigma, T_l>::type,
                  Eigen::Dynamic, Eigen::Dynamic>
    cov_exp_quad(const std::vector<T_x>& x,
                 const T_sigma& sigma,
                 const T_l& l) {
      check_positive("cov_exp_quad", "sigma", sigma);
      check_positive("cov_exp_quad", "l", l);
      for (size_t n = 0; n < x.size(); ++n)
        check_not_nan("cov_exp_quad", "x", x[n]);

      Eigen::Matrix<typename stan::return_type<T_x, T_sigma, T_l>::type,
                    Eigen::Dynamic, Eigen::Dynamic>
        cov(x.size(), x.size());

      int x_size = x.size();
      if (x_size == 0)
        return cov;

      T_sigma sigma_sq = square(sigma);
      T_l neg_half_inv_l_sq = - 0.5 / square(l);

      for (int j = 0; j < (x_size - 1); ++j) {
        cov(j, j) = sigma_sq;
        for (int i = j + 1; i < x_size; ++i) {
          cov(i, j) = sigma_sq * exp(squared_distance(x[i], x[j])
                                     * neg_half_inv_l_sq);
          cov(j, i) = cov(i, j);
        }
      }
      cov(x_size - 1, x_size - 1) = sigma_sq;
      return cov;
    }

    /**
     * Returns a squared exponential kernel.
     *
     * @tparam T_x1 type of first std::vector of elements
     * @tparam T_x2 type of second std::vector of elements
     * @tparam T_sigma type of sigma
     * @tparam T_l type of length scale
     *
     * @param x1 std::vector of elements that can be used in square distance
     * @param x2 std::vector of elements that can be used in square distance
     * @param sigma standard deviation
     * @param l length scale
     * @return squared distance
     * @throw std::domain_error if sigma <= 0, l <= 0, or
     *   x is nan or infinite
     */
    template<typename T_x1, typename T_x2, typename T_sigma, typename T_l>
    inline typename
    Eigen::Matrix<typename stan::return_type<T_x1, T_x2, T_sigma, T_l>::type,
                  Eigen::Dynamic, Eigen::Dynamic>
    cov_exp_quad(const std::vector<T_x1>& x1,
                 const std::vector<T_x2>& x2,
                 const T_sigma& sigma,
                 const T_l& l) {
      check_positive("cov_exp_quad", "sigma", sigma);
      check_positive("cov_exp_quad", "l", l);
      for (size_t n = 0; n < x1.size(); ++n)
        check_not_nan("cov_exp_quad", "x1", x1[n]);
      for (size_t n = 0; n < x2.size(); ++n)
        check_not_nan("cov_exp_quad", "x2", x2[n]);

      Eigen::Matrix<typename stan::return_type<T_x1, T_x2, T_sigma, T_l>::type,
                    Eigen::Dynamic, Eigen::Dynamic>
        cov(x1.size(), x2.size());
      if (x1.size() == 0 || x2.size() == 0)
        return cov;

      T_sigma sigma_sq = square(sigma);
      T_l neg_half_inv_l_sq = - 0.5 / square(l);

      for (size_t i = 0; i < x1.size(); ++i) {
        for (size_t j = 0; j < x2.size(); ++j) {
          cov(i, j) = sigma_sq * exp(squared_distance(x1[i], x2[j])
                                     * neg_half_inv_l_sq);
        }
      }
      return cov;
    }

  }
}
#endif
<|endoftext|>


<commit_before><commit_msg>Fixes bug so that if we restore popups (as we do on chrome os) we restore them to the correct size.<commit_after><|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2001 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xerces" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache\@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation, and was
 * originally based on software copyright (c) 2001, International
 * Business Machines, Inc., http://www.ibm.com .  For more information
 * on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

/*
 * $Log$
 * Revision 1.2  2002/02/14 15:17:31  peiyongz
 * getEnumString()
 *
 * Revision 1.1.1.1  2002/02/01 22:22:40  peiyongz
 * sane_include
 *
 * Revision 1.7  2001/10/02 18:59:29  peiyongz
 * Invalid_Facet_Tag to display the tag name
 *
 * Revision 1.6  2001/06/22 16:26:01  peiyongz
 * fix: redefinition of SIZE
 *
 * Revision 1.5  2001/05/29 19:49:33  tng
 * Schema: Constraint Checking Fix in datatypeValidators.  By Pei Yong Zhang.
 *
 * Revision 1.4  2001/05/28 21:11:17  tng
 * Schema: Various DatatypeValidator fix.  By Pei Yong Zhang
 *
 * Revision 1.3  2001/05/18 13:36:44  tng
 * Schema: Catch RegularExpression exception and NumberFormatException
 *
 * Revision 1.2  2001/05/11 13:27:26  tng
 * Copyright update.
 *
 * Revision 1.1  2001/05/09 18:43:35  tng
 * Add StringDatatypeValidator and BooleanDatatypeValidator.  By Pei Yong Zhang.
 *
 */

// ---------------------------------------------------------------------------
//  Includes
// ---------------------------------------------------------------------------
#include <xercesc/validators/datatype/BooleanDatatypeValidator.hpp>
#include <xercesc/validators/schema/SchemaSymbols.hpp>
#include <xercesc/validators/datatype/InvalidDatatypeFacetException.hpp>
#include <xercesc/validators/datatype/InvalidDatatypeValueException.hpp>

const int   ARRAYSIZE = 4;
const XMLCh fgValueSpace[][32] =
{
    { chLatin_f, chLatin_a, chLatin_l, chLatin_s, chLatin_e, chNull },
    { chLatin_t, chLatin_r, chLatin_u, chLatin_e, chNull },
    { chDigit_0, chNull },
    { chDigit_1, chNull }
};

// ---------------------------------------------------------------------------
//  Constructors and Destructor
// ---------------------------------------------------------------------------
BooleanDatatypeValidator::BooleanDatatypeValidator(
                          DatatypeValidator*            const baseValidator
                        , RefHashTableOf<KVStringPair>* const facets
                        , RefVectorOf<XMLCh>*           const enums
                        , const int                           finalSet)
:DatatypeValidator(baseValidator, facets, finalSet, DatatypeValidator::Boolean)
{

    // Set Facets if any defined
    if ( facets )
    {

        // Boolean shall NOT have enumeration
        if (enums)
            ThrowXML1(InvalidDatatypeFacetException
                    , XMLExcepts::FACET_Invalid_Tag
                    , "enumeration");

        XMLCh* key;
        XMLCh* value;
        RefHashTableOfEnumerator<KVStringPair> e(facets);

        while (e.hasMoreElements())
        {
            KVStringPair pair = e.nextElement();
            key = pair.getKey();
            value = pair.getValue();

            if (XMLString::compareString(key, SchemaSymbols::fgELT_PATTERN)==0)
            {
                setPattern(value);
                setFacetsDefined(DatatypeValidator::FACET_PATTERN);
            }
            else
            {
                ThrowXML1(InvalidDatatypeFacetException
                        , XMLExcepts::FACET_Invalid_Tag
                        , key);
            }

        }

    }// End of facet setting
}

void BooleanDatatypeValidator::checkContent( const XMLCh* const content, bool asBase)
{

    //validate against base validator if any
    BooleanDatatypeValidator *pBaseValidator = (BooleanDatatypeValidator*) this->getBaseValidator();
    if (pBaseValidator !=0)
        pBaseValidator->checkContent(content, true);

    // we check pattern first
    if ( (getFacetsDefined() & DatatypeValidator::FACET_PATTERN ) != 0 )
    {
        // lazy construction
        if (getRegex() ==0) {
            try {
                setRegex(new RegularExpression(getPattern(), SchemaSymbols::fgRegEx_XOption));
            }
            catch (XMLException &e)
            {
                ThrowXML1(InvalidDatatypeValueException, XMLExcepts::RethrowError, e.getMessage());
            }
        }

        if (getRegex()->matches(content) ==false)
        {
            ThrowXML2(InvalidDatatypeValueException
                    , XMLExcepts::VALUE_NotMatch_Pattern
                    , content
                    , getPattern());
        }
    }

    // if this is a base validator, we only need to check pattern facet
    // all other facet were inherited by the derived type
    if (asBase)
        return;

    int   i = 0;
    for ( ; i < ARRAYSIZE; i++ )
    {
        if ( XMLString::compareString(content, fgValueSpace[i]) ==0 )
            break;
    }

    if (i == ARRAYSIZE)
        ThrowXML(InvalidDatatypeValueException, XMLExcepts::CM_UnaryOpHadBinType);
        //Not valid boolean type

}

int BooleanDatatypeValidator::compare(const XMLCh* const lValue
                                    , const XMLCh* const rValue)
{
    // need to check by bool semantics
    // 1 == true
    // 0 == false

    if (( XMLString::compareString(lValue, fgValueSpace[0]) ==0 ) ||
        ( XMLString::compareString(lValue, fgValueSpace[2]) ==0 ) )
    {
        if (( XMLString::compareString(rValue, fgValueSpace[0]) ==0 ) ||
            ( XMLString::compareString(rValue, fgValueSpace[2]) ==0 ) )
            return 0;
    }
    else
    if (( XMLString::compareString(lValue, fgValueSpace[1]) ==0 ) ||
        ( XMLString::compareString(lValue, fgValueSpace[3]) ==0 ) )
    {
        if (( XMLString::compareString(rValue, fgValueSpace[1]) ==0 ) ||
            ( XMLString::compareString(rValue, fgValueSpace[3]) ==0 ) )
            return 0;
    }

    return 1;
}

const RefVectorOf<XMLCh>* BooleanDatatypeValidator::getEnumString() const
{
	return 0;
}

/**
  * End of file BooleanDatatypeValidator.cpp
  */

<commit_msg>Memory leak fix: enums is not deleted if an error occurred.<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2001 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xerces" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache\@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation, and was
 * originally based on software copyright (c) 2001, International
 * Business Machines, Inc., http://www.ibm.com .  For more information
 * on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

/*
 * $Log$
 * Revision 1.3  2002/08/23 20:16:50  tng
 * Memory leak fix: enums is not deleted if an error occurred.
 *
 * Revision 1.2  2002/02/14 15:17:31  peiyongz
 * getEnumString()
 *
 * Revision 1.1.1.1  2002/02/01 22:22:40  peiyongz
 * sane_include
 *
 * Revision 1.7  2001/10/02 18:59:29  peiyongz
 * Invalid_Facet_Tag to display the tag name
 *
 * Revision 1.6  2001/06/22 16:26:01  peiyongz
 * fix: redefinition of SIZE
 *
 * Revision 1.5  2001/05/29 19:49:33  tng
 * Schema: Constraint Checking Fix in datatypeValidators.  By Pei Yong Zhang.
 *
 * Revision 1.4  2001/05/28 21:11:17  tng
 * Schema: Various DatatypeValidator fix.  By Pei Yong Zhang
 *
 * Revision 1.3  2001/05/18 13:36:44  tng
 * Schema: Catch RegularExpression exception and NumberFormatException
 *
 * Revision 1.2  2001/05/11 13:27:26  tng
 * Copyright update.
 *
 * Revision 1.1  2001/05/09 18:43:35  tng
 * Add StringDatatypeValidator and BooleanDatatypeValidator.  By Pei Yong Zhang.
 *
 */

// ---------------------------------------------------------------------------
//  Includes
// ---------------------------------------------------------------------------
#include <xercesc/validators/datatype/BooleanDatatypeValidator.hpp>
#include <xercesc/validators/schema/SchemaSymbols.hpp>
#include <xercesc/validators/datatype/InvalidDatatypeFacetException.hpp>
#include <xercesc/validators/datatype/InvalidDatatypeValueException.hpp>

const int   ARRAYSIZE = 4;
const XMLCh fgValueSpace[][32] =
{
    { chLatin_f, chLatin_a, chLatin_l, chLatin_s, chLatin_e, chNull },
    { chLatin_t, chLatin_r, chLatin_u, chLatin_e, chNull },
    { chDigit_0, chNull },
    { chDigit_1, chNull }
};

// ---------------------------------------------------------------------------
//  Constructors and Destructor
// ---------------------------------------------------------------------------
BooleanDatatypeValidator::BooleanDatatypeValidator(
                          DatatypeValidator*            const baseValidator
                        , RefHashTableOf<KVStringPair>* const facets
                        , RefVectorOf<XMLCh>*           const enums
                        , const int                           finalSet)
:DatatypeValidator(baseValidator, facets, finalSet, DatatypeValidator::Boolean)
{

    // Set Facets if any defined
    if ( facets )
    {

        // Boolean shall NOT have enumeration
        if (enums) {
            delete enums;
            ThrowXML1(InvalidDatatypeFacetException
                    , XMLExcepts::FACET_Invalid_Tag
                    , "enumeration");
        }

        XMLCh* key;
        XMLCh* value;
        RefHashTableOfEnumerator<KVStringPair> e(facets);

        while (e.hasMoreElements())
        {
            KVStringPair pair = e.nextElement();
            key = pair.getKey();
            value = pair.getValue();

            if (XMLString::compareString(key, SchemaSymbols::fgELT_PATTERN)==0)
            {
                setPattern(value);
                setFacetsDefined(DatatypeValidator::FACET_PATTERN);
            }
            else
            {
                ThrowXML1(InvalidDatatypeFacetException
                        , XMLExcepts::FACET_Invalid_Tag
                        , key);
            }

        }

    }// End of facet setting
}

void BooleanDatatypeValidator::checkContent( const XMLCh* const content, bool asBase)
{

    //validate against base validator if any
    BooleanDatatypeValidator *pBaseValidator = (BooleanDatatypeValidator*) this->getBaseValidator();
    if (pBaseValidator !=0)
        pBaseValidator->checkContent(content, true);

    // we check pattern first
    if ( (getFacetsDefined() & DatatypeValidator::FACET_PATTERN ) != 0 )
    {
        // lazy construction
        if (getRegex() ==0) {
            try {
                setRegex(new RegularExpression(getPattern(), SchemaSymbols::fgRegEx_XOption));
            }
            catch (XMLException &e)
            {
                ThrowXML1(InvalidDatatypeValueException, XMLExcepts::RethrowError, e.getMessage());
            }
        }

        if (getRegex()->matches(content) ==false)
        {
            ThrowXML2(InvalidDatatypeValueException
                    , XMLExcepts::VALUE_NotMatch_Pattern
                    , content
                    , getPattern());
        }
    }

    // if this is a base validator, we only need to check pattern facet
    // all other facet were inherited by the derived type
    if (asBase)
        return;

    int   i = 0;
    for ( ; i < ARRAYSIZE; i++ )
    {
        if ( XMLString::compareString(content, fgValueSpace[i]) ==0 )
            break;
    }

    if (i == ARRAYSIZE)
        ThrowXML(InvalidDatatypeValueException, XMLExcepts::CM_UnaryOpHadBinType);
        //Not valid boolean type

}

int BooleanDatatypeValidator::compare(const XMLCh* const lValue
                                    , const XMLCh* const rValue)
{
    // need to check by bool semantics
    // 1 == true
    // 0 == false

    if (( XMLString::compareString(lValue, fgValueSpace[0]) ==0 ) ||
        ( XMLString::compareString(lValue, fgValueSpace[2]) ==0 ) )
    {
        if (( XMLString::compareString(rValue, fgValueSpace[0]) ==0 ) ||
            ( XMLString::compareString(rValue, fgValueSpace[2]) ==0 ) )
            return 0;
    }
    else
    if (( XMLString::compareString(lValue, fgValueSpace[1]) ==0 ) ||
        ( XMLString::compareString(lValue, fgValueSpace[3]) ==0 ) )
    {
        if (( XMLString::compareString(rValue, fgValueSpace[1]) ==0 ) ||
            ( XMLString::compareString(rValue, fgValueSpace[3]) ==0 ) )
            return 0;
    }

    return 1;
}

const RefVectorOf<XMLCh>* BooleanDatatypeValidator::getEnumString() const
{
	return 0;
}

/**
  * End of file BooleanDatatypeValidator.cpp
  */

<|endoftext|>


<commit_before>#ifndef STAN_MATH_PRIM_META_vector_SEQ_VIEW_HPP
#define STAN_MATH_PRIM_META_vector_SEQ_VIEW_HPP

#include <stan/math/prim/fun/Eigen.hpp>
#include <stan/math/prim/meta.hpp>
#include <vector>

namespace stan {

/** \ingroup type_trait
 * This class provides a low-cost wrapper for situations where you either need
 * an Eigen Vector or RowVector or a std::vector of them and you want to be
 * agnostic between those two options. This is similar to scalar_seq_view but
 * instead of being a sequence-like view over a scalar or seq of scalars, it's
 * a sequence-like view over a Vector or seq of Vectors. Notably this version
 * only allows std::vectors as the container type, since we would have
 * difficulty figuring out which contained type was the container otherwise.
 *
 * @tparam T the wrapped type, either a Vector or std::vector of them.
 */
template <typename T, typename = void>
class vector_seq_view {};

/** \ingroup type_trait
 * This class provides a low-cost wrapper for situations where you either need
 * an Eigen Vector or RowVector or a std::vector of them and you want to be
 * agnostic between those two options. This is similar to scalar_seq_view but
 * instead of being a sequence-like view over a scalar or seq of scalars, it's
 * a sequence-like view over a Vector or seq of Vectors. Notably this version
 * only allows std::vectors as the container type, since we would have
 * difficulty figuring out which contained type was the container otherwise.
 *
 * @tparam T the type of the underlying Vector
 */
template <typename T>
class vector_seq_view<T, require_eigen_t<T>> {
 public:
  explicit vector_seq_view(const T& m) : m_(m) {}
  int size() const { return 1; }
  const ref_type_t<T>& operator[](int /* i */) const { return m_; }

 private:
  const ref_type_t<T> m_;
};

/** \ingroup type_trait
 * This class provides a low-cost wrapper for situations where you either need
 * an Eigen Vector or RowVector or a std::vector of them and you want to be
 * agnostic between those two options. This is similar to scalar_seq_view but
 * instead of being a sequence-like view over a scalar or seq of scalars, it's
 * a sequence-like view over a Vector or seq of Vectors. Notably this version
 * only allows std::vectors as the container type, since we would have
 * difficulty figuring out which contained type was the container otherwise.
 *
 * @tparam S the type inside of the std::vector
 */
template <typename T>
class vector_seq_view<T, require_std_vector_vt<is_container, T>> {
 public:
  explicit vector_seq_view(const T& v) : v_(v) {}
  int size() const { return v_.size(); }
  const value_type_t<T>& operator[](int i) const { return v_[i]; }

 private:
  const T& v_;
};

}  // namespace stan

#endif
<commit_msg>made vector_seq_view comment clearer<commit_after>#ifndef STAN_MATH_PRIM_META_vector_SEQ_VIEW_HPP
#define STAN_MATH_PRIM_META_vector_SEQ_VIEW_HPP

#include <stan/math/prim/fun/Eigen.hpp>
#include <stan/math/prim/meta.hpp>
#include <vector>

namespace stan {

/** \ingroup type_trait
 * This class provides a low-cost wrapper for situations where you either need
 * an Eigen Vector or RowVector or a std::vector of them and you want to be
 * agnostic between those two options. This is similar to scalar_seq_view but
 * instead of being a sequence-like view over a scalar or seq of scalars, it's
 * a sequence-like view over a Vector or seq of Vectors. Notably this version
 * only allows std::vectors as the outer container type, since we would have
 * difficulty figuring out which contained type was the container otherwise.
 *
 * @tparam T the wrapped type, either a Vector or std::vector of them.
 */
template <typename T, typename = void>
class vector_seq_view {};

/** \ingroup type_trait
 * This class provides a low-cost wrapper for situations where you either need
 * an Eigen Vector or RowVector or a std::vector of them and you want to be
 * agnostic between those two options. This is similar to scalar_seq_view but
 * instead of being a sequence-like view over a scalar or seq of scalars, it's
 * a sequence-like view over a Vector or seq of Vectors. Notably this version
 * only allows std::vectors as the outer container type, since we would have
 * difficulty figuring out which contained type was the container otherwise.
 *
 * @tparam T the type of the underlying Vector
 */
template <typename T>
class vector_seq_view<T, require_eigen_t<T>> {
 public:
  explicit vector_seq_view(const T& m) : m_(m) {}
  int size() const { return 1; }
  const ref_type_t<T>& operator[](int /* i */) const { return m_; }

 private:
  const ref_type_t<T> m_;
};

/** \ingroup type_trait
 * This class provides a low-cost wrapper for situations where you either need
 * an Eigen Vector or RowVector or a std::vector of them and you want to be
 * agnostic between those two options. This is similar to scalar_seq_view but
 * instead of being a sequence-like view over a scalar or seq of scalars, it's
 * a sequence-like view over a Vector or seq of Vectors. Notably this version
 * only allows std::vectors as the outer container type, since we would have
 * difficulty figuring out which contained type was the container otherwise.
 *
 * @tparam S the type inside of the std::vector
 */
template <typename T>
class vector_seq_view<T, require_std_vector_vt<is_container, T>> {
 public:
  explicit vector_seq_view(const T& v) : v_(v) {}
  int size() const { return v_.size(); }
  const value_type_t<T>& operator[](int i) const { return v_[i]; }

 private:
  const T& v_;
};

}  // namespace stan

#endif
<|endoftext|>


<commit_before><commit_msg>Fix a leak caught by valgrind following r31199<commit_after><|endoftext|>


<commit_before><commit_msg>Fix mac ui test valgrind.<commit_after><|endoftext|>


<commit_before><commit_msg>Modify the save as code to be able to display the new enhanced save dialog on Windows 7.<commit_after><|endoftext|>


<commit_before><commit_msg>linux: add a temporary flag for disabling xshm<commit_after><|endoftext|>


<commit_before>#include <iostream>

#include <ros/ros.h>
#include <geometry_msgs/Twist.h>
#include <std_msgs/UInt16.h>

#define LEFT  1
#define RIGHT -1

class RobotDriver
{
  int time_count;
  int speed_smoother;
  bool turn_right;

private:
  //! The node handle we'll be using
  ros::NodeHandle nh_;
  //! We will be publishing to the "/base_controller/command" topic to issue commands
  ros::Publisher cmd_vel_pub_;
  // Subscribes to /face_detector/face_width to know if a face is detected or not
  ros::Subscriber face_width_sub_;

public:
  //! ROS node initialization
  RobotDriver() : time_count(0), speed_smoother(0), turn_right(false)
  {
    //set up the publisher for the cmd_vel topic
    cmd_vel_pub_ = nh_.advertise<geometry_msgs::Twist>("/base_controller/command", 1);

    // Sets the subscriber for face_width. The size of the queue is 1
    face_width_sub_ = nh_.subscribe("/face_detector/face_width", 1, &RobotDriver::isThereAface, this);
  }

  //! Loop forever while sending drive commands based on keyboard input
  // bool driveKeyboard()
  // {
  //   std::cout << "Type a command and then press enter.  "
  //     "Use '+' to move forward, 'l' to turn left, "
  //     "'r' to turn right, '.' to exit.\n";

  //   //we will be sending commands of type "twist"
  //   geometry_msgs::Twist base_cmd;

  //   char cmd[50];
  //   while(nh_.ok()){

  //     std::cin.getline(cmd, 50);
  //     if(cmd[0]!='+' && cmd[0]!='l' && cmd[0]!='r' && cmd[0]!='.')
  //     {
  //       std::cout << "unknown command:" << cmd << "\n";
  //       continue;
  //     }

  //     base_cmd.linear.x = base_cmd.linear.y = base_cmd.angular.z = 0;
  //     //move forward
  //     if(cmd[0]=='+'){
  //       base_cmd.linear.x = 0.25;
  //     }
  //     //turn left (yaw) and drive forward at the same time
  //     else if(cmd[0]=='l'){
  //       base_cmd.angular.z = 0.75;
  //       base_cmd.linear.x = 0.25;
  //     }
  //     //turn right (yaw) and drive forward at the same time
  //     else if(cmd[0]=='r'){
  //       base_cmd.angular.z = -0.75;
  //       base_cmd.linear.x = 0.25;
  //     }
  //     //quit
  //     else if(cmd[0]=='.'){
  //       break;
  //     }

  //     //publish the assembled command
  //     cmd_vel_pub_.publish(base_cmd);
  //   }
  //   return true;
  // }

  void moveSlightly()
  {
    int direction;
    geometry_msgs::Twist drive_cmd;

    if (turn_right){
      direction = LEFT;
    }else{
      direction = RIGHT;
    }

      // std::cout<<time_count<<std::endl;

    if (time_count < 30)
    {
      time_count++;
      drive_cmd.angular.z = direction*0.6;
      drive_cmd.linear.x = 0;
      cmd_vel_pub_.publish(drive_cmd);
    }else if (time_count >= 30 && time_count < 35){
      time_count++;
      drive_cmd.angular.z = 0;
    }else{
      time_count = 0;
      drive_cmd.angular.z = 0;
      turn_right = !turn_right;
    }

  }

  void isThereAface(std_msgs::UInt16 face_width)
  {
    // std::cout<<"face_width: " <<face_width<<std::endl;
    // std::cout<<"face_width.data: "<< face_width.data<<std::endl;
    if (face_width.data == 0)
    {
      // std::cout<<"if"<<std::endl;
      moveSlightly();
    }
  }

};

int main(int argc, char** argv)
{
  //init the ROS node
  ros::init(argc, argv, "robot_driver");
  RobotDriver robotDriver;
  ros::spin();
  return 0;
}<commit_msg>update steer_turtlebot.cpp<commit_after>#include <iostream>

#include <ros/ros.h>
#include <geometry_msgs/Twist.h>
#include <std_msgs/UInt16.h>

#define LEFT  1
#define RIGHT -1
#define TIME_COUNT 40

class RobotDriver
{
  int time_count;
  int speed_smoother;
  bool turn_right;
  unsigned long int face_posx;

private:
  //! The node handle we'll be using
  ros::NodeHandle nh_;
  //! We will be publishing to the "/base_controller/command" topic to issue commands
  ros::Publisher cmd_vel_pub_;
  // Subscribes to /face_detector/face_width to know if a face is detected or not
  ros::Subscriber face_width_sub_;
  ros::Subscriber face_posx_sub_;

public:
  //! ROS node initialization
  RobotDriver() : time_count(0), speed_smoother(0), turn_right(false), face_posx(0)
  {
    //set up the publisher for the cmd_vel topic
    cmd_vel_pub_ = nh_.advertise<geometry_msgs::Twist>("/base_controller/command", 1);

    // Sets the subscriber for face_width. The size of the queue is 1
    face_width_sub_ = nh_.subscribe("/face_detector/face_width", 1, &RobotDriver::isThereAface, this);
    face_posx_sub_ = nh_.subscribe("/face_detector/face_position_X", 1, &RobotDriver::newPosx, this);
  }

  void moveSlightly()
  {
    int direction;
    geometry_msgs::Twist drive_cmd;

    if (turn_right){
      direction = LEFT;
    }else{
      direction = RIGHT;
    }

      // std::cout<<time_count<<std::endl;

    if (time_count < TIME_COUNT)
    {
      time_count++;
      drive_cmd.angular.z = direction*0.6;
      drive_cmd.linear.x = 0;
      cmd_vel_pub_.publish(drive_cmd);
    }else if (time_count >= TIME_COUNT && time_count < TIME_COUNT+20){
      time_count++;
      drive_cmd.angular.z = 0;
    }else{
      time_count = 0;
      drive_cmd.angular.z = 0;
      turn_right = !turn_right;
    }

  }

  void isThereAface(std_msgs::UInt16 face_width)
  {
    // std::cout<<"face_width: " <<face_width<<std::endl;
    // std::cout<<"face_width.data: "<< face_width.data<<std::endl;
    if (face_width.data == 0)
    {
      // std::cout<<"if"<<std::endl;
      moveSlightly();
    }else{
      moveTowardsFace();
    }
  }

  void newPosx(std_msgs::UInt16 posx){
    face_posx = posx.data;
  }

  void moveTowardsFace(){
    geometry_msgs::Twist drive_cmd;
    if (face_posx < 213){
      drive_cmd.angular.z = LEFT*0.6;
      drive_cmd.linear.x = 0;
    }else if (face_posx > 427){
      drive_cmd.angular.z = RIGHT*0.6;
      drive_cmd.linear.x = 0;
    }else{
      drive_cmd.angular.z = 0;
      drive_cmd.linear.x = 0;
    }
    cmd_vel_pub_.publish(drive_cmd);
  }

};

int main(int argc, char** argv)
{
  //init the ROS node
  ros::init(argc, argv, "robot_driver");
  RobotDriver robotDriver;
  ros::spin();
  return 0;
}<|endoftext|>


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

#include "wx/aui/auibook.h"
#include "wx/dnd.h"
#include "gui/canvas-change-event.hh"
#include "gui/canvas-panel.hh"
#include "gui/freezer.hh"
#include "gui/tab-ctrl.hh"
#include "util-wx/bind-event.hh"
#include "util-wx/convert-wx.hh"
#include "util-wx/gui-util.hh"
#include "util/generator-adapter.hh"
#include "util/image-props.hh"
#include "util/index-iter.hh"

namespace faint{

const wxEventType FAINT_ACTIVE_CANVAS_CHANGE = wxNewEventType();
const wxEventTypeTag<CanvasChangeEvent> EVT_FAINT_ACTIVE_CANVAS_CHANGE(
  FAINT_ACTIVE_CANVAS_CHANGE);

static wxString get_title(CanvasPanel* canvas){
  const Optional<FilePath> filePath(canvas->GetFilePath());
  wxString title = filePath.IsSet() ?
    to_wx(filePath.Get().StripPath().Str()) :
    get_new_canvas_title();

  if (canvas->IsDirty()){
    title += " *";
  }
  return title;
}

class CanvasFileDropTarget : public wxFileDropTarget {
public:
  explicit CanvasFileDropTarget(AppContext& app)
    : m_app(app)
  {}

  bool OnDropFiles(wxCoord, wxCoord, const wxArrayString& files) override{
    m_app.Load(to_FileList(files));
    return true;
  }
  AppContext& m_app;
};

const auto style = wxAUI_NB_DEFAULT_STYLE | wxWANTS_CHARS;

class TabCtrlImpl : public wxAuiNotebook {
public:
  TabCtrlImpl(wxWindow* parent,
    const Art& art,
    AppContext& app,
    StatusInterface& status)
    : wxAuiNotebook(parent, wxID_ANY, wxDefaultPosition, wxDefaultSize, style),
      m_app(app),
      m_art(art),
      m_statusInfo(status)
  {
    SetCanFocus(false);
    SetAcceleratorTable(wxNullAcceleratorTable);

    bind_fwd(this, wxEVT_AUINOTEBOOK_PAGE_CLOSE,
      [this, &app](wxAuiNotebookEvent& event){
        event.Veto();
        int page = event.GetSelection();
        CanvasPanel* canvas = GetCanvasPage(Index(page));
        canvas->Preempt(PreemptOption::ALLOW_COMMAND);
        if (canvas->IsDirty()){
          SaveChoice choice = ask_close_unsaved_tab(this,
            app,
            canvas->GetFilePath());
          if (choice == SaveChoice::CANCEL){
            return;
          }

          if (choice == SaveChoice::YES){
            bool saved = m_app.Save(canvas->GetInterface());
            if (!saved){
              return;
            }
          }
        }

        if (GetPageCount() == 1){
          // Remove annyoing flashing appearance on windows when closing
          // last tab. This freeze must only be done when the last tab is
          // closed, because it causes a refresh error if the tabcontrol
          // is split (see issue 86).
          auto freezer = freeze(this);
          DeletePage(to_size_t(page));
        }
        else {
          DeletePage(to_size_t(page));
        }
        if (GetPageCount() == 0){
          // Avoid flicker in the upper-left of the tab-bar from page
          // creation
          auto freezer = freeze(this);

          AddPage(new CanvasPanel(this,
              ImageList(ImageProps(m_app.GetDefaultImageInfo())),
              initially_dirty(false),
              CreateFileDropTarget(),
              m_art,
              m_app,
              m_statusInfo),
            get_new_canvas_title(),
            false);
        }
      });

    bind(this, wxEVT_AUINOTEBOOK_PAGE_CHANGED,
      [&](){
        const CanvasPanel* canvas = GetCanvasPage(Index(GetSelection()));
        CanvasChangeEvent newEvent(FAINT_ACTIVE_CANVAS_CHANGE,
          canvas->GetCanvasId());
        ProcessEvent(newEvent);
      });

    bind_fwd(this, wxEVT_AUINOTEBOOK_PAGE_CHANGING,
      [this](wxAuiNotebookEvent& event){
        int selection = GetSelection();

        // Selection is -1 if the change was due to page close
        if (GetPageCount() > 1 && selection >= 0){
          assert(selection < resigned(GetPageCount()));
          CanvasPanel* canvas = GetCanvasPage(Index(selection));
          canvas->Preempt(PreemptOption::ALLOW_COMMAND);
        }
        event.Skip();
      });

    events::on_canvas_modified_skip(this,
      [&](CanvasId canvasId){
        RefreshTabName(canvasId);
      });
  }

  void Close(const Index& page){
    // Create a close event so that its handler is called to avoid
    // duplication between calls to CloseActiveTab and built in tab
    // close (the x-button).
    wxAuiNotebookEvent e(wxEVT_COMMAND_AUINOTEBOOK_PAGE_CLOSE, GetId());
    e.SetSelection(page.Get());
    e.SetEventObject(this);
    GetEventHandler()->ProcessEvent(e);
  }

  void CloseActive(){
    if (GetPageCount() == 0){
      return;
    }
    Close(Index(GetSelection()));
  }

  CanvasPanel* GetCanvasPage(const Index& i){
    wxWindow* page = GetPage(to_size_t(i));
    assert(page != nullptr);
    CanvasPanel* canvas(dynamic_cast<CanvasPanel*>(page));
    assert(canvas != nullptr);
    return canvas;
  }

  Index GetCanvasCount() const{
    return Index(resigned(GetPageCount()));
  }

  Optional<Index> GetIndexForId(const CanvasId& id){
    const auto canvas_id_matches =
      [&](const Index& i){return GetCanvasPage(i)->GetCanvasId() == id;};

    return find_if(up_to(GetCanvasCount()), canvas_id_matches);
  }

  CanvasPanel* NewDocument(ImageProps&& props, const change_tab& changeTab,
    const initially_dirty& startDirty)
  {
    // Avoid flicker in the upper-left of the tab-bar from page
    // creation
    auto freezer = freeze(this);

    CanvasPanel* canvas = new CanvasPanel(this,
      ImageList(std::move(props)),
      startDirty,
      CreateFileDropTarget(),
      m_art,
      m_app,
      m_statusInfo);
    AddPage(canvas, get_title(canvas), changeTab.Get());
    return canvas;
  }

  CanvasPanel* NewDocument(std::vector<ImageProps>&& props,
    const change_tab& changeTab, const initially_dirty& startDirty)
  {
    // Avoid flicker in the upper-left of the tab-bar from page
    // creation
    auto freezer = freeze(this);

    CanvasPanel* canvas = new CanvasPanel(this,
      ImageList(std::move(props)),
      startDirty,
      CreateFileDropTarget(),
      m_art,
      m_app,
      m_statusInfo);
    AddPage(canvas, get_title(canvas), changeTab.Get());
    return canvas;
  }

  void RefreshTabName(Index i){
    CanvasPanel* canvas = GetCanvasPage(i);
    SetPageText(to_size_t(i), get_title(canvas));
  }

  void RefreshTabName(const CanvasId& id){
    RefreshTabName(GetIndexForId(id).Get());
  }

  wxFileDropTarget* CreateFileDropTarget(){
    return new CanvasFileDropTarget(m_app);
  }
private:
  AppContext& m_app;
  const Art& m_art;
  StatusInterface& m_statusInfo;
};

TabCtrl::TabCtrl(wxWindow* parent,
  const Art& art,
  AppContext& app,
  StatusInterface& status)
{
  m_impl = new TabCtrlImpl(parent, art, app, status);
  m_defaultTabHeight = m_impl->GetTabCtrlHeight();
}

wxWindow* TabCtrl::AsWindow(){
  return m_impl;
}

void TabCtrl::Close(const Index& i){
  assert(i < GetCanvasCount());
  m_impl->Close(i);
}

void TabCtrl::CloseActive(){
  m_impl->CloseActive();
}

CanvasPanel* TabCtrl::GetActiveCanvas(){
  assert(m_impl->GetPageCount() != 0);
  Index page(m_impl->GetSelection());
  CanvasPanel* canvas = m_impl->GetCanvasPage(page);
  return canvas;
}

CanvasPanel* TabCtrl::GetCanvas(const Index& page){
  assert(page < GetCanvasCount());
  CanvasPanel* cb = m_impl->GetCanvasPage(page);
  return cb;
}

CanvasPanel* TabCtrl::GetCanvas(const CanvasId& id){
  return m_impl->GetIndexForId(id).Visit(
    [&](const Index& index){
      return GetCanvas(index);
    },
    [](){
      return nullptr;
    });
}

Index TabCtrl::GetCanvasCount() const{
  return m_impl->GetCanvasCount();
}

bool TabCtrl::Has(const CanvasId& id){
  return m_impl->GetIndexForId(id).IsSet();
}

void TabCtrl::HideTabs(){
  m_defaultTabHeight = m_impl->GetTabCtrlHeight();
  m_impl->SetTabCtrlHeight(0);
}

CanvasPanel* TabCtrl::NewDocument(ImageProps&& props,
  const change_tab& changeTab,
  const initially_dirty& startDirty)
{
  return m_impl->NewDocument(std::move(props), changeTab, startDirty);
}

CanvasPanel* TabCtrl::NewDocument(std::vector<ImageProps>&& props,
  const change_tab& changeTab,
  const initially_dirty& startDirty)
{
  return m_impl->NewDocument(std::move(props), changeTab, startDirty);
}

void TabCtrl::Select(const CanvasId& id){
  auto index = m_impl->GetIndexForId(id);
  m_impl->SetSelection(to_size_t(index.Get()));
}

void TabCtrl::SelectNext(){
  m_impl->AdvanceSelection();
}

void TabCtrl::SelectPrevious(){
  m_impl->AdvanceSelection(false);
}

void TabCtrl::ShowTabs(){
  m_impl->SetTabCtrlHeight(m_defaultTabHeight);
}

bool TabCtrl::UnsavedDocuments() const{
  auto is_dirty = [this](const Index& i){
    return m_impl->GetCanvasPage(i)->IsDirty();
  };

  return any_of(up_to(GetCanvasCount()), is_dirty);
}

} // namespace

namespace faint{ namespace events{

void on_switch_canvas(window_t w, const std::function<void(CanvasId)>& f){
  bind_fwd(w.w, EVT_FAINT_ACTIVE_CANVAS_CHANGE,
    [f](CanvasChangeEvent& e){
      f(e.GetCanvasId());
    });
}

}}
<commit_msg>Just added a comment.<commit_after>// -*- coding: us-ascii-unix -*-
// Copyright 2012 Lukas Kemmer
//
// Licensed under the Apache License, Version 2.0 (the "License"); you
// may not use this file except in compliance with the License. You
// may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.

#include "wx/aui/auibook.h"
#include "wx/dnd.h"
#include "gui/canvas-change-event.hh"
#include "gui/canvas-panel.hh"
#include "gui/freezer.hh"
#include "gui/tab-ctrl.hh"
#include "util-wx/bind-event.hh"
#include "util-wx/convert-wx.hh"
#include "util-wx/gui-util.hh"
#include "util/generator-adapter.hh"
#include "util/image-props.hh"
#include "util/index-iter.hh"

namespace faint{

const wxEventType FAINT_ACTIVE_CANVAS_CHANGE = wxNewEventType();
const wxEventTypeTag<CanvasChangeEvent> EVT_FAINT_ACTIVE_CANVAS_CHANGE(
  FAINT_ACTIVE_CANVAS_CHANGE);

static wxString get_title(CanvasPanel* canvas){
  const Optional<FilePath> filePath(canvas->GetFilePath());
  wxString title = filePath.IsSet() ?
    to_wx(filePath.Get().StripPath().Str()) :
    get_new_canvas_title();

  if (canvas->IsDirty()){
    title += " *";
  }
  return title;
}

class CanvasFileDropTarget : public wxFileDropTarget {
public:
  explicit CanvasFileDropTarget(AppContext& app)
    : m_app(app)
  {}

  bool OnDropFiles(wxCoord, wxCoord, const wxArrayString& files) override{
    m_app.Load(to_FileList(files));
    return true;
  }
  AppContext& m_app;
};

const auto style = wxAUI_NB_DEFAULT_STYLE | wxWANTS_CHARS;

class TabCtrlImpl : public wxAuiNotebook {
public:
  TabCtrlImpl(wxWindow* parent,
    const Art& art,
    AppContext& app,
    StatusInterface& status)
    : wxAuiNotebook(parent, wxID_ANY, wxDefaultPosition, wxDefaultSize, style),
      m_app(app),
      m_art(art),
      m_statusInfo(status)
  {
    SetCanFocus(false);
    SetAcceleratorTable(wxNullAcceleratorTable);

    bind_fwd(this, wxEVT_AUINOTEBOOK_PAGE_CLOSE,
      [this, &app](wxAuiNotebookEvent& event){
        event.Veto();
        int page = event.GetSelection();
        CanvasPanel* canvas = GetCanvasPage(Index(page));
        canvas->Preempt(PreemptOption::ALLOW_COMMAND);
        if (canvas->IsDirty()){
          SaveChoice choice = ask_close_unsaved_tab(this,
            app,
            canvas->GetFilePath());
          if (choice == SaveChoice::CANCEL){
            return;
          }

          if (choice == SaveChoice::YES){
            bool saved = m_app.Save(canvas->GetInterface());
            if (!saved){
              return;
            }
          }
        }

        if (GetPageCount() == 1){
          // Remove annyoing flashing appearance on windows when closing
          // last tab. This freeze must only be done when the last tab is
          // closed, because it causes a refresh error if the tabcontrol
          // is split (see issue 86).
          auto freezer = freeze(this);
          DeletePage(to_size_t(page));
        }
        else {
          DeletePage(to_size_t(page));
        }
        if (GetPageCount() == 0){
          // Avoid flicker in the upper-left of the tab-bar from page
          // creation
          auto freezer = freeze(this);

          AddPage(new CanvasPanel(this,
              ImageList(ImageProps(m_app.GetDefaultImageInfo())),
              initially_dirty(false),
              CreateFileDropTarget(),
              m_art,
              m_app,
              m_statusInfo),
            get_new_canvas_title(),
            false);
        }
      });

    bind(this, wxEVT_AUINOTEBOOK_PAGE_CHANGED,
      [&](){
        const CanvasPanel* canvas = GetCanvasPage(Index(GetSelection()));
        CanvasChangeEvent newEvent(FAINT_ACTIVE_CANVAS_CHANGE,
          canvas->GetCanvasId());
        ProcessEvent(newEvent);
      });

    bind_fwd(this, wxEVT_AUINOTEBOOK_PAGE_CHANGING,
      [this](wxAuiNotebookEvent& event){
        int selection = GetSelection();

        // Selection is -1 if the change was due to page close
        if (GetPageCount() > 1 && selection >= 0){
          assert(selection < resigned(GetPageCount()));
          CanvasPanel* canvas = GetCanvasPage(Index(selection));
          canvas->Preempt(PreemptOption::ALLOW_COMMAND);
        }
        event.Skip();
      });

    events::on_canvas_modified_skip(this,
      [&](CanvasId canvasId){
        RefreshTabName(canvasId);
      });
  }

  void Close(const Index& page){
    // Create a close event so that its handler is called to avoid
    // duplication between calls to CloseActiveTab and built in tab
    // close (the x-button).
    wxAuiNotebookEvent e(wxEVT_COMMAND_AUINOTEBOOK_PAGE_CLOSE, GetId());
    e.SetSelection(page.Get());
    e.SetEventObject(this);
    GetEventHandler()->ProcessEvent(e);
  }

  void CloseActive(){
    if (GetPageCount() == 0){
      return;
    }
    Close(Index(GetSelection()));
  }

  CanvasPanel* GetCanvasPage(const Index& i){
    wxWindow* page = GetPage(to_size_t(i));
    assert(page != nullptr);
    CanvasPanel* canvas(dynamic_cast<CanvasPanel*>(page));
    assert(canvas != nullptr);
    return canvas;
  }

  Index GetCanvasCount() const{
    return Index(resigned(GetPageCount()));
  }

  Optional<Index> GetIndexForId(const CanvasId& id){
    const auto canvas_id_matches =
      [&](const Index& i){return GetCanvasPage(i)->GetCanvasId() == id;};

    return find_if(up_to(GetCanvasCount()), canvas_id_matches);
  }

  CanvasPanel* NewDocument(ImageProps&& props, const change_tab& changeTab,
    const initially_dirty& startDirty)
  {
    // Avoid flicker in the upper-left of the tab-bar from page
    // creation
    auto freezer = freeze(this);

    CanvasPanel* canvas = new CanvasPanel(this,
      ImageList(std::move(props)),
      startDirty,
      CreateFileDropTarget(),
      m_art,
      m_app,
      m_statusInfo);
    AddPage(canvas, get_title(canvas), changeTab.Get());
    return canvas;
  }

  CanvasPanel* NewDocument(std::vector<ImageProps>&& props,
    const change_tab& changeTab, const initially_dirty& startDirty)
  {
    // Avoid flicker in the upper-left of the tab-bar from page
    // creation
    auto freezer = freeze(this);

    CanvasPanel* canvas = new CanvasPanel(this,
      ImageList(std::move(props)),
      startDirty,
      CreateFileDropTarget(),
      m_art,
      m_app,
      m_statusInfo);
    AddPage(canvas, get_title(canvas), changeTab.Get());
    return canvas;
  }

  void RefreshTabName(Index i){
    CanvasPanel* canvas = GetCanvasPage(i);
    SetPageText(to_size_t(i), get_title(canvas));
  }

  void RefreshTabName(const CanvasId& id){
    RefreshTabName(GetIndexForId(id).Get());
  }

  wxFileDropTarget* CreateFileDropTarget(){
    return new CanvasFileDropTarget(m_app);
  }
private:
  AppContext& m_app;
  const Art& m_art;
  StatusInterface& m_statusInfo;
};

TabCtrl::TabCtrl(wxWindow* parent,
  const Art& art,
  AppContext& app,
  StatusInterface& status)
{
  m_impl = new TabCtrlImpl(parent, art, app, status);
  m_defaultTabHeight = m_impl->GetTabCtrlHeight();
}

wxWindow* TabCtrl::AsWindow(){
  return m_impl;
}

void TabCtrl::Close(const Index& i){
  assert(i < GetCanvasCount());
  m_impl->Close(i);
}

void TabCtrl::CloseActive(){
  m_impl->CloseActive();
}

CanvasPanel* TabCtrl::GetActiveCanvas(){
  assert(m_impl->GetPageCount() != 0);
  Index page(m_impl->GetSelection());
  CanvasPanel* canvas = m_impl->GetCanvasPage(page);
  return canvas;
}

CanvasPanel* TabCtrl::GetCanvas(const Index& page){
  assert(page < GetCanvasCount());
  CanvasPanel* cb = m_impl->GetCanvasPage(page);
  return cb;
}

CanvasPanel* TabCtrl::GetCanvas(const CanvasId& id){
  return m_impl->GetIndexForId(id).Visit(
    [&](const Index& index){
      return GetCanvas(index);
    },
    [](){
      return nullptr;
    });
}

Index TabCtrl::GetCanvasCount() const{
  return m_impl->GetCanvasCount();
}

bool TabCtrl::Has(const CanvasId& id){
  return m_impl->GetIndexForId(id).IsSet();
}

void TabCtrl::HideTabs(){
  m_defaultTabHeight = m_impl->GetTabCtrlHeight();
  m_impl->SetTabCtrlHeight(0);
}

CanvasPanel* TabCtrl::NewDocument(ImageProps&& props,
  const change_tab& changeTab,
  const initially_dirty& startDirty)
{
  return m_impl->NewDocument(std::move(props), changeTab, startDirty);
}

CanvasPanel* TabCtrl::NewDocument(std::vector<ImageProps>&& props,
  const change_tab& changeTab,
  const initially_dirty& startDirty)
{
  return m_impl->NewDocument(std::move(props), changeTab, startDirty);
}

void TabCtrl::Select(const CanvasId& id){
  auto index = m_impl->GetIndexForId(id);
  m_impl->SetSelection(to_size_t(index.Get()));
}

void TabCtrl::SelectNext(){
  m_impl->AdvanceSelection();
}

void TabCtrl::SelectPrevious(){
  m_impl->AdvanceSelection(false);
}

void TabCtrl::ShowTabs(){
  m_impl->SetTabCtrlHeight(m_defaultTabHeight);
}

bool TabCtrl::UnsavedDocuments() const{
  auto is_dirty = [this](const Index& i){
    return m_impl->GetCanvasPage(i)->IsDirty();
  };

  return any_of(up_to(GetCanvasCount()), is_dirty);
}

} // namespace

namespace faint{ namespace events{

void on_switch_canvas(window_t w, const std::function<void(CanvasId)>& f){
  bind_fwd(w.w, EVT_FAINT_ACTIVE_CANVAS_CHANGE,
    [f](CanvasChangeEvent& e){
      f(e.GetCanvasId());
    });
}

}} // namespace
<|endoftext|>