<commit_before>// Copyright (c) 2012 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 "base/base_switches.h"
#include "base/command_line.h"
#include "base/debug/debugger.h"
#include "base/debug/leak_annotations.h"
#include "base/debug/stack_trace.h"
#include "base/i18n/rtl.h"
#include "base/message_loop/message_loop.h"
#include "base/metrics/field_trial.h"
#include "base/metrics/histogram.h"
#include "base/metrics/statistics_recorder.h"
#include "base/pending_task.h"
#include "base/strings/string_util.h"
#include "base/sys_info.h"
#include "base/threading/platform_thread.h"
#include "base/timer/hi_res_timer_manager.h"
#include "base/trace_event/trace_event.h"
#include "components/scheduler/renderer/renderer_scheduler.h"
#include "content/child/child_process.h"
#include "content/common/content_constants_internal.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/main_function_params.h"
#include "content/public/renderer/content_renderer_client.h"
#include "content/renderer/render_process_impl.h"
#include "content/renderer/render_thread_impl.h"
#include "content/renderer/renderer_main_platform_delegate.h"
#include "ui/base/ui_base_switches.h"

#if defined(OS_ANDROID)
#include "base/android/library_loader/library_loader_hooks.h"
#include "third_party/skia/include/core/SkGraphics.h"
#endif  // OS_ANDROID

#if defined(OS_MACOSX)
#include <Carbon/Carbon.h>
#include <signal.h>
#include <unistd.h>

#include "base/mac/scoped_nsautorelease_pool.h"
#include "base/message_loop/message_pump_mac.h"
#include "third_party/WebKit/public/web/WebView.h"
#endif  // OS_MACOSX

#if defined(ENABLE_PLUGINS)
#include "content/renderer/pepper/pepper_plugin_registry.h"
#endif

#if defined(ENABLE_WEBRTC)
#include "third_party/libjingle/overrides/init_webrtc.h"
#endif

namespace content {
namespace {
// This function provides some ways to test crash and assertion handling
// behavior of the renderer.
static void HandleRendererErrorTestParameters(
    const base::CommandLine& command_line) {
  if (command_line.HasSwitch(switches::kWaitForDebugger))
    base::debug::WaitForDebugger(60, true);

  if (command_line.HasSwitch(switches::kRendererStartupDialog))
    ChildProcess::WaitForDebugger("Renderer");
}

}  // namespace

// mainline routine for running as the Renderer process
int RendererMain(const MainFunctionParams& parameters) {
  TRACE_EVENT_BEGIN_ETW("RendererMain", 0, "");
  base::trace_event::TraceLog::GetInstance()->SetProcessName("Renderer");
  base::trace_event::TraceLog::GetInstance()->SetProcessSortIndex(
      kTraceEventRendererProcessSortIndex);

  const base::CommandLine& parsed_command_line = parameters.command_line;

#if defined(OS_MACOSX)
  base::mac::ScopedNSAutoreleasePool* pool = parameters.autorelease_pool;
#endif  // OS_MACOSX

#if defined(OS_CHROMEOS)
  // As Zygote process starts up earlier than browser process gets its own
  // locale (at login time for Chrome OS), we have to set the ICU default
  // locale for renderer process here.
  // ICU locale will be used for fallback font selection etc.
  if (parsed_command_line.HasSwitch(switches::kLang)) {
    const std::string locale =
        parsed_command_line.GetSwitchValueASCII(switches::kLang);
    base::i18n::SetICUDefaultLocale(locale);
  }
#endif

#if defined(OS_ANDROID)
  const int kMB = 1024 * 1024;
  size_t font_cache_limit =
      base::SysInfo::IsLowEndDevice() ? kMB : 8 * kMB;
  SkGraphics::SetFontCacheLimit(font_cache_limit);
#endif

  // This function allows pausing execution using the --renderer-startup-dialog
  // flag allowing us to attach a debugger.
  // Do not move this function down since that would mean we can't easily debug
  // whatever occurs before it.
  HandleRendererErrorTestParameters(parsed_command_line);

  RendererMainPlatformDelegate platform(parameters);
#if defined(OS_MACOSX)
  // As long as scrollbars on Mac are painted with Cocoa, the message pump
  // needs to be backed by a Foundation-level loop to process NSTimers. See
  // http://crbug.com/306348#c24 for details.
  scoped_ptr<base::MessagePump> pump(new base::MessagePumpNSRunLoop());
  scoped_ptr<base::MessageLoop> main_message_loop(
      new base::MessageLoop(pump.Pass()));
#else
  // The main message loop of the renderer services doesn't have IO or UI tasks.
  scoped_ptr<base::MessageLoop> main_message_loop(new base::MessageLoop());
#endif

  base::PlatformThread::SetName("CrRendererMain");
  scoped_ptr<scheduler::RendererScheduler> renderer_scheduler(
      scheduler::RendererScheduler::Create());

  bool no_sandbox = parsed_command_line.HasSwitch(switches::kNoSandbox);

  // Initialize histogram statistics gathering system.
  base::StatisticsRecorder::Initialize();

#if defined(OS_ANDROID)
  // If we have a pending chromium android linker histogram, record it.
  base::android::RecordChromiumAndroidLinkerRendererHistogram();
#endif

  // Initialize statistical testing infrastructure.  We set the entropy provider
  // to NULL to disallow the renderer process from creating its own one-time
  // randomized trials; they should be created in the browser process.
  base::FieldTrialList field_trial_list(NULL);
  // Ensure any field trials in browser are reflected into renderer.
  if (parsed_command_line.HasSwitch(switches::kForceFieldTrials)) {
    bool result = base::FieldTrialList::CreateTrialsFromString(
        parsed_command_line.GetSwitchValueASCII(switches::kForceFieldTrials),
        base::FieldTrialList::DONT_ACTIVATE_TRIALS,
        std::set<std::string>());
    DCHECK(result);
  }

  // PlatformInitialize uses FieldTrials, so this must happen later.
  platform.PlatformInitialize();

#if defined(ENABLE_PLUGINS)
  // Load pepper plugins before engaging the sandbox.
  PepperPluginRegistry::GetInstance();
#endif
#if defined(ENABLE_WEBRTC)
  // Initialize WebRTC before engaging the sandbox.
  // NOTE: On linux, this call could already have been made from
  // zygote_main_linux.cc.  However, calling multiple times from the same thread
  // is OK.
  InitializeWebRtcModule();
#endif

  {
#if defined(OS_WIN) || defined(OS_MACOSX)
    // TODO(markus): Check if it is OK to unconditionally move this
    // instruction down.
    RenderProcessImpl render_process;
    RenderThreadImpl::Create(main_message_loop.Pass(),
                             renderer_scheduler.Pass());
#endif
    bool run_loop = true;
    if (!no_sandbox) {
      run_loop = platform.EnableSandbox();
    } else {
      LOG(ERROR) << "Running without renderer sandbox";
#ifndef NDEBUG
      // For convenience, we print the stack traces for crashes.  When sandbox
      // is enabled, the in-process stack dumping is enabled as part of the
      // EnableSandbox() call.
      base::debug::EnableInProcessStackDumping();
#endif
    }
#if defined(OS_POSIX) && !defined(OS_MACOSX)
    RenderProcessImpl render_process;
    RenderThreadImpl::Create(main_message_loop.Pass(),
                             renderer_scheduler.Pass());
#endif
    base::HighResolutionTimerManager hi_res_timer_manager;

    if (run_loop) {
#if defined(OS_MACOSX)
      if (pool)
        pool->Recycle();
#endif
      TRACE_EVENT_BEGIN_ETW("RendererMain.START_MSG_LOOP", 0, 0);
      base::MessageLoop::current()->Run();
      TRACE_EVENT_END_ETW("RendererMain.START_MSG_LOOP", 0, 0);
    }
#if defined(LEAK_SANITIZER)
    // Run leak detection before RenderProcessImpl goes out of scope. This helps
    // ignore shutdown-only leaks.
    __lsan_do_leak_check();
#endif
  }
  platform.PlatformUninitialize();
  TRACE_EVENT_END_ETW("RendererMain", 0, "");
  return 0;
}

}  // namespace content
<commit_msg>Have renderer call SkGraphics::Init() at startup.<commit_after>// Copyright (c) 2012 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 "base/base_switches.h"
#include "base/command_line.h"
#include "base/debug/debugger.h"
#include "base/debug/leak_annotations.h"
#include "base/debug/stack_trace.h"
#include "base/i18n/rtl.h"
#include "base/message_loop/message_loop.h"
#include "base/metrics/field_trial.h"
#include "base/metrics/histogram.h"
#include "base/metrics/statistics_recorder.h"
#include "base/pending_task.h"
#include "base/strings/string_util.h"
#include "base/sys_info.h"
#include "base/threading/platform_thread.h"
#include "base/timer/hi_res_timer_manager.h"
#include "base/trace_event/trace_event.h"
#include "components/scheduler/renderer/renderer_scheduler.h"
#include "content/child/child_process.h"
#include "content/common/content_constants_internal.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/main_function_params.h"
#include "content/public/renderer/content_renderer_client.h"
#include "content/renderer/render_process_impl.h"
#include "content/renderer/render_thread_impl.h"
#include "content/renderer/renderer_main_platform_delegate.h"
#include "third_party/skia/include/core/SkGraphics.h"
#include "ui/base/ui_base_switches.h"

#if defined(OS_ANDROID)
#include "base/android/library_loader/library_loader_hooks.h"
#endif  // OS_ANDROID

#if defined(OS_MACOSX)
#include <Carbon/Carbon.h>
#include <signal.h>
#include <unistd.h>

#include "base/mac/scoped_nsautorelease_pool.h"
#include "base/message_loop/message_pump_mac.h"
#include "third_party/WebKit/public/web/WebView.h"
#endif  // OS_MACOSX

#if defined(ENABLE_PLUGINS)
#include "content/renderer/pepper/pepper_plugin_registry.h"
#endif

#if defined(ENABLE_WEBRTC)
#include "third_party/libjingle/overrides/init_webrtc.h"
#endif

namespace content {
namespace {
// This function provides some ways to test crash and assertion handling
// behavior of the renderer.
static void HandleRendererErrorTestParameters(
    const base::CommandLine& command_line) {
  if (command_line.HasSwitch(switches::kWaitForDebugger))
    base::debug::WaitForDebugger(60, true);

  if (command_line.HasSwitch(switches::kRendererStartupDialog))
    ChildProcess::WaitForDebugger("Renderer");
}

}  // namespace

// mainline routine for running as the Renderer process
int RendererMain(const MainFunctionParams& parameters) {
  TRACE_EVENT_BEGIN_ETW("RendererMain", 0, "");
  base::trace_event::TraceLog::GetInstance()->SetProcessName("Renderer");
  base::trace_event::TraceLog::GetInstance()->SetProcessSortIndex(
      kTraceEventRendererProcessSortIndex);

  const base::CommandLine& parsed_command_line = parameters.command_line;

#if defined(OS_MACOSX)
  base::mac::ScopedNSAutoreleasePool* pool = parameters.autorelease_pool;
#endif  // OS_MACOSX

#if defined(OS_CHROMEOS)
  // As Zygote process starts up earlier than browser process gets its own
  // locale (at login time for Chrome OS), we have to set the ICU default
  // locale for renderer process here.
  // ICU locale will be used for fallback font selection etc.
  if (parsed_command_line.HasSwitch(switches::kLang)) {
    const std::string locale =
        parsed_command_line.GetSwitchValueASCII(switches::kLang);
    base::i18n::SetICUDefaultLocale(locale);
  }
#endif

  SkGraphics::Init();
#if defined(OS_ANDROID)
  const int kMB = 1024 * 1024;
  size_t font_cache_limit =
      base::SysInfo::IsLowEndDevice() ? kMB : 8 * kMB;
  SkGraphics::SetFontCacheLimit(font_cache_limit);
#endif

  // This function allows pausing execution using the --renderer-startup-dialog
  // flag allowing us to attach a debugger.
  // Do not move this function down since that would mean we can't easily debug
  // whatever occurs before it.
  HandleRendererErrorTestParameters(parsed_command_line);

  RendererMainPlatformDelegate platform(parameters);
#if defined(OS_MACOSX)
  // As long as scrollbars on Mac are painted with Cocoa, the message pump
  // needs to be backed by a Foundation-level loop to process NSTimers. See
  // http://crbug.com/306348#c24 for details.
  scoped_ptr<base::MessagePump> pump(new base::MessagePumpNSRunLoop());
  scoped_ptr<base::MessageLoop> main_message_loop(
      new base::MessageLoop(pump.Pass()));
#else
  // The main message loop of the renderer services doesn't have IO or UI tasks.
  scoped_ptr<base::MessageLoop> main_message_loop(new base::MessageLoop());
#endif

  base::PlatformThread::SetName("CrRendererMain");
  scoped_ptr<scheduler::RendererScheduler> renderer_scheduler(
      scheduler::RendererScheduler::Create());

  bool no_sandbox = parsed_command_line.HasSwitch(switches::kNoSandbox);

  // Initialize histogram statistics gathering system.
  base::StatisticsRecorder::Initialize();

#if defined(OS_ANDROID)
  // If we have a pending chromium android linker histogram, record it.
  base::android::RecordChromiumAndroidLinkerRendererHistogram();
#endif

  // Initialize statistical testing infrastructure.  We set the entropy provider
  // to NULL to disallow the renderer process from creating its own one-time
  // randomized trials; they should be created in the browser process.
  base::FieldTrialList field_trial_list(NULL);
  // Ensure any field trials in browser are reflected into renderer.
  if (parsed_command_line.HasSwitch(switches::kForceFieldTrials)) {
    bool result = base::FieldTrialList::CreateTrialsFromString(
        parsed_command_line.GetSwitchValueASCII(switches::kForceFieldTrials),
        base::FieldTrialList::DONT_ACTIVATE_TRIALS,
        std::set<std::string>());
    DCHECK(result);
  }

  // PlatformInitialize uses FieldTrials, so this must happen later.
  platform.PlatformInitialize();

#if defined(ENABLE_PLUGINS)
  // Load pepper plugins before engaging the sandbox.
  PepperPluginRegistry::GetInstance();
#endif
#if defined(ENABLE_WEBRTC)
  // Initialize WebRTC before engaging the sandbox.
  // NOTE: On linux, this call could already have been made from
  // zygote_main_linux.cc.  However, calling multiple times from the same thread
  // is OK.
  InitializeWebRtcModule();
#endif

  {
#if defined(OS_WIN) || defined(OS_MACOSX)
    // TODO(markus): Check if it is OK to unconditionally move this
    // instruction down.
    RenderProcessImpl render_process;
    RenderThreadImpl::Create(main_message_loop.Pass(),
                             renderer_scheduler.Pass());
#endif
    bool run_loop = true;
    if (!no_sandbox) {
      run_loop = platform.EnableSandbox();
    } else {
      LOG(ERROR) << "Running without renderer sandbox";
#ifndef NDEBUG
      // For convenience, we print the stack traces for crashes.  When sandbox
      // is enabled, the in-process stack dumping is enabled as part of the
      // EnableSandbox() call.
      base::debug::EnableInProcessStackDumping();
#endif
    }
#if defined(OS_POSIX) && !defined(OS_MACOSX)
    RenderProcessImpl render_process;
    RenderThreadImpl::Create(main_message_loop.Pass(),
                             renderer_scheduler.Pass());
#endif
    base::HighResolutionTimerManager hi_res_timer_manager;

    if (run_loop) {
#if defined(OS_MACOSX)
      if (pool)
        pool->Recycle();
#endif
      TRACE_EVENT_BEGIN_ETW("RendererMain.START_MSG_LOOP", 0, 0);
      base::MessageLoop::current()->Run();
      TRACE_EVENT_END_ETW("RendererMain.START_MSG_LOOP", 0, 0);
    }
#if defined(LEAK_SANITIZER)
    // Run leak detection before RenderProcessImpl goes out of scope. This helps
    // ignore shutdown-only leaks.
    __lsan_do_leak_check();
#endif
  }
  platform.PlatformUninitialize();
  TRACE_EVENT_END_ETW("RendererMain", 0, "");
  return 0;
}

}  // namespace content
<|endoftext|>


<commit_before>#include <graphlab/sdk/toolkit_function_macros.hpp>
#include <graphlab/sdk/gl_sgraph.hpp>
#include <iostream>
#include <fstream>
#include <assert.h>

#define NUM_STATES 4
#define NUM_OBSERVATIONS 8
using namespace graphlab;
using namespace std;

std::vector<double> vector_multiply(std::vector<flexible_type> a,
        std::vector<flexible_type> b) {

    assert(a.size() == b.size());
    std::vector<double> result;
    result.resize(b.size());

    for (int i = 0; i < a.size(); i++) {
        result[i] = a[i] * b[i];
    }

    return result;
}

std::vector<double> vector_divide(std::vector<double> a,
        std::vector<double> b) {
    assert(a.size() == b.size());
    std::vector<double> result;
    result.resize(b.size());

    for (int i = 0; i < a.size(); i++) {
        result[i] = a[i] / b[i];
    }

    return result;
}

void get_gammas(gl_sgraph& g) {

}

gl_sgraph fp(gl_sgraph& g, std::vector<int> observation_seq, int n) {

	for (int i = 0; i < n; i++) {

	int t_iteration;
	int obseqt;
	double normalizer = 1;
    	int OBSEQ_SIZE = observation_seq.size();
    	std::vector<double> normalizers(OBSEQ_SIZE + 1,1);

	logprogress_stream << "allocation of normalizers";

    // compute alpha_i(t)
    for (t_iteration = 1; t_iteration < OBSEQ_SIZE + 1; t_iteration++) {

        // https://github.com/dato-code/GraphLab-Create-SDK/blob/master/sdk_example/sgraph_weighted_pagerank.cpp
        // Normalization function
        // based on documentation at https://dato.com/products/create/sdk/docs/classgraphlab_1_1gl__sframe.html
        obseqt = observation_seq[t_iteration - 1];
        // note ait is 1-indexed while observation sequence is 0 indexed
     	g = g.triple_apply([t_iteration, obseqt, normalizer](edge_triple& triple) {

            triple.target["ait"][t_iteration] += triple.target["b"][obseqt] * (((float)triple.source["ait"][t_iteration-1] / normalizer) * (float)triple.edge["aij"]);
            if (triple.source["i"] == (triple.target["i"] - 1 + NUM_STATES) % NUM_STATES) {
                triple.target["ait"][t_iteration] += triple.target["b"][obseqt] * (((float)triple.target["ait"][t_iteration-1] / normalizer) * (float)triple.target["self"]);

            }

        }, {"ait"});

        gl_sframe v = g.vertices();

        normalizer = v["ait"].apply([t_iteration](const std::vector<flexible_type>& x) {
            return (float)x[t_iteration];
        }, flex_type_enum::FLOAT).sum();
        normalizers[t_iteration] = normalizer;

	}

	logprogress_stream << "done first tripleapply for forward probs";

	// calculate beta_i(t)
    for (t_iteration = OBSEQ_SIZE -1; t_iteration >= 0; t_iteration--) {
        // https://github.com/dato-code/GraphLab-Create-SDK/blob/master/sdk_example/sgraph_weighted_pagerank.cpp
        // Normalization function
        // based on documentation at https://dato.com/products/create/sdk/docs/classgraphlab_1_1gl__sframe.html

        obseqt = observation_seq[t_iteration];
        double normalizer = normalizers[t_iteration + 1];
        // Ding, note bit is 1-indexed while observation sequence is 0 indexed.
        // fuck off
     	g = g.triple_apply([t_iteration, obseqt, normalizer](edge_triple& triple) {

		triple.source["bit"][t_iteration] += triple.target["b"][obseqt] * (((double)triple.target["bit"][t_iteration+1]) * (double)triple.edge["aij"]) / normalizer;

            if (triple.target["i"] == (triple.source["i"] - 1 + NUM_STATES) % NUM_STATES) {

		triple.source["bit"][t_iteration] += triple.source["b"][obseqt] * (((double)triple.source["bit"][t_iteration+1]) * (double)triple.source["self"]) / normalizer;

            }

        }, {"bit"});
	}
	logprogress_stream << "done first tripleapply for backwards probs";

        g.vertices()["git"] = g.vertices()["ait"] * g.vertices()["bit"] / normalizers;

	logprogress_stream << "done gone git";

    int obseq_size = OBSEQ_SIZE;
    g.vertices()["git_sum"] = g.vertices()["git"].apply([obseq_size](const std::vector<flexible_type>& x) {
	float git_sum = 0;
	for (int t = 1; t <= obseq_size; t++) {
		git_sum += (float)x[t];
	}
	return git_sum;
    }, flex_type_enum::FLOAT);

	logprogress_stream << " get sum";

	logprogress_stream << "git_sum finished";

    // update Xi, first edges, then self edges in vertices
    // Kevin, note bit is 1-indexed while observation sequence is 0 indexed.
    // Thanks, Ding. I love comments. They're so helpful.
    g = g.triple_apply([observation_seq, normalizers, OBSEQ_SIZE](edge_triple& triple) {
        float xi = 0;

	for (int t = 1; t < OBSEQ_SIZE; t++) {
        	xi += (float)(triple.source["ait"][t]*triple.edge["aij"]*triple.target["bit"][t+1]*triple.target["b"][observation_seq[t]] / (normalizers[t+1] * normalizers[t]));
        }

	triple.edge["aij"] = xi/triple.source["git_sum"];

    },{"aij"});

    g.vertices()["self"] = g.vertices()[{"ait", "self", "bit", "b", "git_sum"}].apply([observation_seq, normalizers, OBSEQ_SIZE](const std::vector<flexible_type>& x) {
	float self_sum = 0.0;
	for (int t = 1; t < OBSEQ_SIZE; t++) {
		self_sum += (float)x[0][t] * (float)x[1] * (float)x[2][t + 1] * (float)x[3][observation_seq[t]] / (normalizers[t] * normalizers[t+1]);
        }
	return self_sum / x[4];

    }, flex_type_enum::FLOAT);

    // self edges
    g.vertices()["b"] = g.vertices()[{"git"}].apply([observation_seq](const std::vector<flexible_type>& x) {
	    std::vector<double> result;
	    result.resize(NUM_OBSERVATIONS);
	    for (int i = 0; i < NUM_OBSERVATIONS; i++) {
		result[i] = 0.0;
		float summ = 0;
		for (int j = 0; j < observation_seq.size(); j++) {
			if (observation_seq[j] == i) {
				result[i] += (float)(x[j+1]);
			}
			summ+=(float)(x[j+1]);

		}
	    	result[i] /= summ;
            }
	    return result;
    }, flex_type_enum::VECTOR);

    std::vector<double> result(OBSEQ_SIZE + 1, 0.0);
    result[OBSEQ_SIZE] = 1.0;
    g.vertices()["bit"] = result;

    g.vertices()["ait"] = g.vertices()[{"git"}].apply([OBSEQ_SIZE](const std::vector<flexible_type>& x) {
	std::vector<double> result(OBSEQ_SIZE + 1, 0.0);
	result[0] = x[0][0];
	return result;
    }, flex_type_enum::VECTOR);

    g.vertices()["git_sum"] = 0.0;
	}
    return g;
}

BEGIN_FUNCTION_REGISTRATION
REGISTER_FUNCTION(fp, "g", "observation_seq", "n"); // provide named parameters
END_FUNCTION_REGISTRATION
<commit_msg>Removed prints<commit_after>#include <graphlab/sdk/toolkit_function_macros.hpp>
#include <graphlab/sdk/gl_sgraph.hpp>
#include <iostream>
#include <fstream>
#include <assert.h>

#define NUM_STATES 4
#define NUM_OBSERVATIONS 8
using namespace graphlab;
using namespace std;

std::vector<double> vector_multiply(std::vector<flexible_type> a,
        std::vector<flexible_type> b) {

    assert(a.size() == b.size());
    std::vector<double> result;
    result.resize(b.size());

    for (int i = 0; i < a.size(); i++) {
        result[i] = a[i] * b[i];
    }

    return result;
}

std::vector<double> vector_divide(std::vector<double> a,
        std::vector<double> b) {
    assert(a.size() == b.size());
    std::vector<double> result;
    result.resize(b.size());

    for (int i = 0; i < a.size(); i++) {
        result[i] = a[i] / b[i];
    }

    return result;
}

void get_gammas(gl_sgraph& g) {

}

gl_sgraph fp(gl_sgraph& g, std::vector<int> observation_seq, int n) {

	for (int i = 0; i < n; i++) {

	int t_iteration;
	int obseqt;
	double normalizer = 1;
    	int OBSEQ_SIZE = observation_seq.size();
    	std::vector<double> normalizers(OBSEQ_SIZE + 1,1);

    // compute alpha_i(t)
    for (t_iteration = 1; t_iteration < OBSEQ_SIZE + 1; t_iteration++) {

        // https://github.com/dato-code/GraphLab-Create-SDK/blob/master/sdk_example/sgraph_weighted_pagerank.cpp
        // Normalization function
        // based on documentation at https://dato.com/products/create/sdk/docs/classgraphlab_1_1gl__sframe.html
        obseqt = observation_seq[t_iteration - 1];
        // note ait is 1-indexed while observation sequence is 0 indexed
     	g = g.triple_apply([t_iteration, obseqt, normalizer](edge_triple& triple) {

            triple.target["ait"][t_iteration] += triple.target["b"][obseqt] * (((float)triple.source["ait"][t_iteration-1] / normalizer) * (float)triple.edge["aij"]);
            if (triple.source["i"] == (triple.target["i"] - 1 + NUM_STATES) % NUM_STATES) {
                triple.target["ait"][t_iteration] += triple.target["b"][obseqt] * (((float)triple.target["ait"][t_iteration-1] / normalizer) * (float)triple.target["self"]);

            }

        }, {"ait"});

        gl_sframe v = g.vertices();

        normalizer = v["ait"].apply([t_iteration](const std::vector<flexible_type>& x) {
            return (float)x[t_iteration];
        }, flex_type_enum::FLOAT).sum();
        normalizers[t_iteration] = normalizer;

	}

	// calculate beta_i(t)
    for (t_iteration = OBSEQ_SIZE -1; t_iteration >= 0; t_iteration--) {
        // https://github.com/dato-code/GraphLab-Create-SDK/blob/master/sdk_example/sgraph_weighted_pagerank.cpp
        // Normalization function
        // based on documentation at https://dato.com/products/create/sdk/docs/classgraphlab_1_1gl__sframe.html

        obseqt = observation_seq[t_iteration];
        double normalizer = normalizers[t_iteration + 1];
        // Ding, note bit is 1-indexed while observation sequence is 0 indexed.
        // fuck off
     	g = g.triple_apply([t_iteration, obseqt, normalizer](edge_triple& triple) {

		triple.source["bit"][t_iteration] += triple.target["b"][obseqt] * (((double)triple.target["bit"][t_iteration+1]) * (double)triple.edge["aij"]) / normalizer;

            if (triple.target["i"] == (triple.source["i"] - 1 + NUM_STATES) % NUM_STATES) {

		triple.source["bit"][t_iteration] += triple.source["b"][obseqt] * (((double)triple.source["bit"][t_iteration+1]) * (double)triple.source["self"]) / normalizer;

            }

        }, {"bit"});
	}

        g.vertices()["git"] = g.vertices()["ait"] * g.vertices()["bit"] / normalizers;

    int obseq_size = OBSEQ_SIZE;
    g.vertices()["git_sum"] = g.vertices()["git"].apply([obseq_size](const std::vector<flexible_type>& x) {
	float git_sum = 0;
	for (int t = 1; t <= obseq_size; t++) {
		git_sum += (float)x[t];
	}
	return git_sum;
    }, flex_type_enum::FLOAT);

    // update Xi, first edges, then self edges in vertices
    // Kevin, note bit is 1-indexed while observation sequence is 0 indexed.
    // Thanks, Ding. I love comments. They're so helpful.
    g = g.triple_apply([observation_seq, normalizers, OBSEQ_SIZE](edge_triple& triple) {
        float xi = 0;

	for (int t = 1; t < OBSEQ_SIZE; t++) {
        	xi += (float)(triple.source["ait"][t]*triple.edge["aij"]*triple.target["bit"][t+1]*triple.target["b"][observation_seq[t]] / (normalizers[t+1] * normalizers[t]));
        }

	triple.edge["aij"] = xi/triple.source["git_sum"];

    },{"aij"});

    g.vertices()["self"] = g.vertices()[{"ait", "self", "bit", "b", "git_sum"}].apply([observation_seq, normalizers, OBSEQ_SIZE](const std::vector<flexible_type>& x) {
	float self_sum = 0.0;
	for (int t = 1; t < OBSEQ_SIZE; t++) {
		self_sum += (float)x[0][t] * (float)x[1] * (float)x[2][t + 1] * (float)x[3][observation_seq[t]] / (normalizers[t] * normalizers[t+1]);
        }
	return self_sum / x[4];

    }, flex_type_enum::FLOAT);

    // self edges
    g.vertices()["b"] = g.vertices()[{"git"}].apply([observation_seq](const std::vector<flexible_type>& x) {
	    std::vector<double> result;
	    result.resize(NUM_OBSERVATIONS);
	    for (int i = 0; i < NUM_OBSERVATIONS; i++) {
		result[i] = 0.0;
		float summ = 0;
		for (int j = 0; j < observation_seq.size(); j++) {
			if (observation_seq[j] == i) {
				result[i] += (float)(x[j+1]);
			}
			summ+=(float)(x[j+1]);

		}
	    	result[i] /= summ;
            }
	    return result;
    }, flex_type_enum::VECTOR);

    std::vector<double> result(OBSEQ_SIZE + 1, 0.0);
    result[OBSEQ_SIZE] = 1.0;
    g.vertices()["bit"] = result;

    g.vertices()["ait"] = g.vertices()[{"git"}].apply([OBSEQ_SIZE](const std::vector<flexible_type>& x) {
	std::vector<double> result(OBSEQ_SIZE + 1, 0.0);
	result[0] = x[0][0];
	return result;
    }, flex_type_enum::VECTOR);

    g.vertices()["git_sum"] = 0.0;
	}
    return g;
}

BEGIN_FUNCTION_REGISTRATION
REGISTER_FUNCTION(fp, "g", "observation_seq", "n"); // provide named parameters
END_FUNCTION_REGISTRATION
<|endoftext|>


<commit_before>#include <iostream>
#include <cstring>
#include <map>
#include <fstream>
#include "cppGzip/DecodeGzip.h"
#include <math.h>
#include <sstream>
#include <fstream>
#include <stdlib.h>
#include "VectorTile.h"
using namespace std;

//curl https://api.mapbox.com/v4/mapbox.mapbox-streets-v7/3/2/3.vector.pbf?access_token=<API_key> > map.bin

int ReadFileContents(const char *filename, int binaryMode, std::string &contentOut)
{
	contentOut = "";
	std::ios_base::openmode mode = (std::ios_base::openmode)0;
	if(binaryMode)
		mode ^= std::ios::binary;
	std::ifstream file(filename, mode);
	if(!file) return 0;

	file.seekg(0,std::ios::end);
	std::streampos length = file.tellg();
	file.seekg(0,std::ios::beg);

	std::vector<char> buffer(length);
	file.read(&buffer[0],length);

	contentOut.assign(&buffer[0], length);
	return 1;
}

///This class would need to be expanded to store features as needed.
class ExampleDataStore : public DecodeVectorTileResults
{
public:
	ExampleDataStore() : DecodeVectorTileResults()
	{
		cout << "Create custom data store..." << endl;
	}

	void Feature(int typeEnum, bool hasId, unsigned long long id,
		const std::map<std::string, std::string> &tagMap,
		std::vector<Point2D> &pointsOut,
		std::vector<std::vector<Point2D> > &linesOut,
		std::vector<Polygon2D> &polygonsOut)
	{
		//In real use, delete this function call and add your own functionality.
		DecodeVectorTileResults::Feature(typeEnum, hasId, id,
			tagMap, pointsOut, linesOut, polygonsOut);
	}
};

int main()
{
	// Verify that the version of the library that we linked against is
	// compatible with the version of the headers we compiled against.
	GOOGLE_PROTOBUF_VERIFY_VERSION;

	std::filebuf fb;
	std::filebuf* ret = fb.open("map.vector.pbf", std::ios::in | std::ios::binary);
	if (ret == NULL)
	{
		cout << "Error opening input file" << endl;
		exit(0);
	}

	//Ungzip the data
	DecodeGzip dec(fb);

	string tileData;

	char tmp[1024];
	while(dec.in_avail())
	{
		streamsize bytes = dec.sgetn(tmp, 1024);
		tileData.append(tmp, bytes);
	}

	//Decode vector data to stdout
	class ExampleDataStore results;
	class DecodeVectorTile vectorDec(3, 2, 3, results);
	vectorDec.DecodeTileData(tileData);

	//Reencode data to file
	std::ofstream outputFi("mapout.vector.pbf");
	class EncodeVectorTile vectorEnc(3, 2, 3, outputFi);
	class DecodeVectorTile vectorDec2(3, 2, 3, vectorEnc);
	vectorDec2.DecodeTileData(tileData);
	fb.close();

	// Optional:  Delete all global objects allocated by libprotobuf.
	google::protobuf::ShutdownProtobufLibrary();

}

<commit_msg>Move file close to sensible place<commit_after>#include <iostream>
#include <cstring>
#include <map>
#include <fstream>
#include "cppGzip/DecodeGzip.h"
#include <math.h>
#include <sstream>
#include <fstream>
#include <stdlib.h>
#include "VectorTile.h"
using namespace std;

//curl https://api.mapbox.com/v4/mapbox.mapbox-streets-v7/3/2/3.vector.pbf?access_token=<API_key> > map.bin

int ReadFileContents(const char *filename, int binaryMode, std::string &contentOut)
{
	contentOut = "";
	std::ios_base::openmode mode = (std::ios_base::openmode)0;
	if(binaryMode)
		mode ^= std::ios::binary;
	std::ifstream file(filename, mode);
	if(!file) return 0;

	file.seekg(0,std::ios::end);
	std::streampos length = file.tellg();
	file.seekg(0,std::ios::beg);

	std::vector<char> buffer(length);
	file.read(&buffer[0],length);

	contentOut.assign(&buffer[0], length);
	return 1;
}

///This class would need to be expanded to store features as needed.
class ExampleDataStore : public DecodeVectorTileResults
{
public:
	ExampleDataStore() : DecodeVectorTileResults()
	{
		cout << "Create custom data store..." << endl;
	}

	void Feature(int typeEnum, bool hasId, unsigned long long id,
		const std::map<std::string, std::string> &tagMap,
		std::vector<Point2D> &pointsOut,
		std::vector<std::vector<Point2D> > &linesOut,
		std::vector<Polygon2D> &polygonsOut)
	{
		//In real use, delete this function call and add your own functionality.
		DecodeVectorTileResults::Feature(typeEnum, hasId, id,
			tagMap, pointsOut, linesOut, polygonsOut);
	}
};

int main()
{
	// Verify that the version of the library that we linked against is
	// compatible with the version of the headers we compiled against.
	GOOGLE_PROTOBUF_VERIFY_VERSION;

	std::filebuf fb;
	std::filebuf* ret = fb.open("map.vector.pbf", std::ios::in | std::ios::binary);
	if (ret == NULL)
	{
		cout << "Error opening input file" << endl;
		exit(0);
	}

	//Ungzip the data
	DecodeGzip dec(fb);

	string tileData;

	char tmp[1024];
	while(dec.in_avail())
	{
		streamsize bytes = dec.sgetn(tmp, 1024);
		tileData.append(tmp, bytes);
	}
	fb.close();

	//Decode vector data to stdout
	class ExampleDataStore results;
	class DecodeVectorTile vectorDec(3, 2, 3, results);
	vectorDec.DecodeTileData(tileData);

	//Reencode data to file
	std::ofstream outputFi("mapout.vector.pbf");
	class EncodeVectorTile vectorEnc(3, 2, 3, outputFi);
	class DecodeVectorTile vectorDec2(3, 2, 3, vectorEnc);
	vectorDec2.DecodeTileData(tileData);

	// Optional:  Delete all global objects allocated by libprotobuf.
	google::protobuf::ShutdownProtobufLibrary();

}

<|endoftext|>


<commit_before>#include <gtest/gtest.h>

#include "Addition.h"

class AdditionTest : public ::testing::Test
{
    virtual void SetUp() {}
    virtual void TearDown() {}

};

TEST_F(AdditionTest, twoValues)
{
    const int x = 2;
    const int y = 3;
    Addition addition;
    EXPECT_EQ(5, addition.twoValues(x, y));
    EXPECT_EQ(10, addition.twoValues(5, 5));
}

<commit_msg>See how Travis handles failing test.<commit_after>#include <gtest/gtest.h>

#include "Addition.h"

class AdditionTest : public ::testing::Test
{
    virtual void SetUp() {}
    virtual void TearDown() {}

};

TEST_F(AdditionTest, twoValues)
{
    const int x = 2;
    const int y = 3;
    Addition addition;
    EXPECT_EQ(5, addition.twoValues(x, y));
    EXPECT_EQ(10, addition.twoValues(5, 6));
}

<|endoftext|>


<commit_before>#include <iostream>
#include <sstream>
#include <fstream>
#include <vector>
#include <string>
#include <stdio.h>
#include <stdlib.h>

#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/filesystem/convenience.hpp>
#include <boost/algorithm/string.hpp>

#include "testdriverconfig.h" // SRC and BIN dir definitions
#include "specification.h" // parsing spec files
#include <zorba/zorba.h>
#include <zorba/error_handler.h>
#include <zorba/exception.h>

namespace fs = boost::filesystem;

void
printFile(std::ostream& os, std::string aInFile)
{
  std::ifstream lInFileStream(aInFile.c_str());
  assert(lInFileStream);

  os << lInFileStream.rdbuf() << std::endl;
}

// print parts of a file
// starting at aStartPos with the length of aLen
void
printPart(std::ostream& os, std::string aInFile,
          int aStartPos, int aLen)
{
  char* buffer = new char [aLen];
  try {
    std::ifstream lIn(aInFile.c_str());
    lIn.seekg(aStartPos);

    int lCharsRead = lIn.readsome (buffer, aLen);
    os.write (buffer, lCharsRead);
    os.flush();
    delete[] buffer;
  } catch (...)
  {
    delete[] buffer;
  }
  return;
}

zorba::XQuery::CompilerHints
getCompilerHints()
{
  zorba::XQuery::CompilerHints lHints;

  // ZORBA_OPTLEVEL=O0 | O1
  char* lOptLevel = getenv("ZORBA_OPTLEVEL");
  if ( lOptLevel != NULL && strcmp(lOptLevel, "O0") == 0 ) {
    lHints.opt_level = zorba::XQuery::CompilerHints::O0;
    std::cout << "testdriver is using optimization level O0" << std::endl;
  } else {
    lHints.opt_level = zorba::XQuery::CompilerHints::O1;
    std::cout << "testdriver is using optimization level O1" << std::endl;
  }
  return lHints;
}

class TestErrorHandler : public zorba::ErrorHandler {
  public:
    void staticError(const zorba::StaticException& aStaticError)
    {
      registerError(aStaticError);
    }

    void dynamicError(const zorba::DynamicException& aDynamicError)
    {
      registerError(aDynamicError);
    }

    void typeError(const zorba::TypeException& aTypeError)
    {
      registerError(aTypeError);
    }

    void serializationError(const zorba::SerializationException& aSerializationError)
    {
      registerError(aSerializationError);
    }

    void systemError(const zorba::SystemException& aSystemError)
    {
      registerError(aSystemError);
    }

    bool errors()
    {
      return !m_errors.empty();
    }

    const std::vector<std::string>& getErrorList()
    {
      return m_errors;
    }
    const std::vector<zorba::String>& getErrorDescs()
    {
      return m_desc;
    }

  private:
    std::vector<std::string> m_errors;
    std::vector<zorba::String> m_desc;

    void registerError(const zorba::ZorbaException& e)
    {
      m_errors.push_back(zorba::ZorbaError::getErrorCode(e.getErrorCode()).c_str());
      m_desc.push_back(e.getDescription());
    }
};

// check of an error that was repored was expected
// by the given specification object
bool
isErrorExpected(TestErrorHandler& errHandler, Specification* aSpec)
{
  const std::vector<std::string>& errors = errHandler.getErrorList();
  for(std::vector<std::string>::const_iterator i = errors.begin(); i != errors.end(); ++i) {
    for(std::vector<std::string>::const_iterator j = aSpec->errorsBegin(); j != aSpec->errorsEnd(); ++j) {
      if (i->compare(*j) == 0) {
        return true;
      }
    }
  }
  return false;
}

// print all errors that were raised
void
printErrors(TestErrorHandler& errHandler, const char *msg)
{
  if (!errHandler.errors()) {
    return;
  }
  std::cerr << msg << ":" << std::endl;

  const std::vector<std::string>& errors = errHandler.getErrorList();
  const std::vector<zorba::String>& descs = errHandler.getErrorDescs();

  std::vector<std::string>::const_iterator codeIter = errors.begin();
  std::vector<zorba::String>::const_iterator descIter = descs.begin();

    for(; codeIter != errors.end(); ++codeIter, ++descIter) {
      assert (descIter != descs.end());
      std::cerr << *codeIter << ": " << *descIter << std::endl;
  }
  return;
}

// set a variable in the dynamic context
// inlineFile specifies whether the given parameter is a file and it's value should
// be inlined or not
void
set_var (bool inlineFile, std::string name, std::string val, zorba::DynamicContext* dctx)
{
  boost::replace_all(val, "$RBKT_SRC_DIR", "file://" + zorba::RBKT_SRC_DIR);

  zorba::ItemFactory* lFactory = zorba::Zorba::getInstance()->getItemFactory();

  if (!inlineFile) {
    zorba::Item lItem = lFactory->createString(val);
		if(name != ".")
			dctx->setVariable (name, lItem);
		else
			dctx->setContextItem (lItem);
  } else {
    std::ifstream is (val.c_str ());
    assert (is);
		if(name != ".")
			dctx->setVariableAsDocument (name, val.c_str(), is);
		else
			dctx->setContextItemAsDocument (val.c_str(), is);
  }
}

void
set_vars (Specification* aSpec, zorba::DynamicContext* dctx)
{
  for (std::vector<Specification::Variable>::const_iterator lIter = aSpec->variablesBegin();
       lIter != aSpec->variablesEnd(); ++lIter)
  {
    set_var ((*lIter).theInline, (*lIter).theVarName, (*lIter).theVarValue, dctx);
  }
}

void
trim(std::string& str) {

  std::string::size_type  notwhite = str.find_first_not_of(" \t\n");
  str.erase(0,notwhite);

  notwhite = str.find_last_not_of(" \t\n");
  str.erase(notwhite+1);
}

// return false if the files are not equal
// aLine contains the line number in which the first difference occurs
// aCol contains the column number in which the first difference occurs
// aPos is the character number off the first difference in the file
// -1 is returned for aLine, aCol, and aPos if the files are equal
bool
isEqual(fs::path aRefFile, fs::path aResFile, int& aLine, int& aCol, int& aPos)
{
  std::ifstream li(aRefFile.native_file_string().c_str());
  std::ifstream ri(aResFile.native_file_string().c_str());

  std::string lLine, rLine;

  aLine = 1; aCol = 0; aPos = -1;
  while (! li.eof() )
  {
    if ( ri.eof() ) {
      std::getline(li, lLine);
      if (li.peek() == -1) // ignore end-of-line in the ref result
        return true;
      else
        return false;
    }
    std::getline(li, lLine);
    std::getline(ri, rLine);
    ++aLine;
    if ( (aCol = lLine.compare(rLine)) != 0) {
      return false;
    }
  }

  return true;
}

void
slurp_file (const char *fname, std::string &result) {
  std::ifstream qfile(fname, std::ios::binary | std::ios_base::in); assert (qfile);

  qfile.seekg (0, std::ios::end);
  size_t len = qfile.tellg ();
  qfile.seekg (0, std::ios::beg);
  char *str = new char [len];
  qfile.read (str, len);
  len = qfile.gcount();

  std::string sstr (str, len);
  result.swap (sstr);
  delete [] str;
}

int
#ifdef _WIN32_WCE
_tmain(int argc, _TCHAR* argv[])
#else
main(int argc, char** argv)
#endif
{
  fs::path lQueryFile, lResultFile, lErrorFile, lRefFile, lSpecFile;
  Specification lSpec;

  // do initial stuff
  if ( argc == 2 )
  {
    std::string lQueryFileString  = zorba::RBKT_SRC_DIR +"/Queries/" + argv[1];
    lQueryFile = fs::system_complete( fs::path( lQueryFileString, fs::native ) );

    std::string lQueryWithoutSuffix = std::string(argv[1]).substr( 0, std::string(argv[1]).size()-3 );
    std::cout << "test " << lQueryWithoutSuffix << std::endl;
    lResultFile = fs::system_complete(fs::path( zorba::RBKT_BINARY_DIR +"/QueryResults/"
                                      +lQueryWithoutSuffix + ".res", fs::native) );
    lErrorFile = fs::system_complete(fs::path(zorba::RBKT_BINARY_DIR +"/"
                                     +lQueryWithoutSuffix + ".err", fs::native) );
    lRefFile   = fs::system_complete(fs::path( zorba::RBKT_SRC_DIR +"/ExpQueryResults/"
                                     +lQueryWithoutSuffix +".xml.res", fs::native) );
    lSpecFile  = fs::system_complete(fs::path(zorba::RBKT_SRC_DIR+ "/Queries/"
                                     +lQueryWithoutSuffix +".spec", fs::native) );
  }
  else
  {
    std::cerr << "\nusage:   testdriver [testfile]" << std::endl;
    return 1;
  }

  // does the query file exists
  if ( (! fs::exists( lQueryFile )) || fs::is_directory( lQueryFile) ) {
    std::cerr << "\n query file " << lQueryFile.native_file_string()
              << " does not exist or is not a file" << std::endl;
    return 2;
  }

  // delete previous files if they exists
  if ( fs::exists ( lResultFile ) ) { fs::remove (lResultFile); }
  if ( fs::exists ( lErrorFile ) )  { fs::remove (lErrorFile);  }

  // create the result directory
  fs::path lBucket = fs::system_complete(fs::path( lResultFile.branch_path().string(), fs::native ));
  if ( ! fs::exists( lBucket ) )
    fs::create_directories(lBucket); // create deep directories

  // read the xargs and errors if the spec file exists
  if ( fs::exists( lSpecFile ))
  {
    lSpec.parseFile(lSpecFile.native_file_string());
  }

  // we must either have a reference file or an expected error code
  if ( (lSpec.errorsSize() == 0) && ((! fs::exists( lRefFile )) || fs::is_directory( lRefFile)))
  {
    std::cerr << "No reference result and no expected errors." << std::endl;
    return 3;
  }

  // print the query
  std::cout << "Query:" << std::endl;
  printFile(std::cout, lQueryFile.native_file_string());
  std::cout << std::endl;

  zorba::Zorba *engine = zorba::Zorba::getInstance();

  TestErrorHandler errHandler;

  // create and compile the query
  std::string lQueryString;
  slurp_file(lQueryFile.native_file_string().c_str(), lQueryString);
  zorba::XQuery_t lQuery = engine->compileQuery(lQueryString.c_str(), getCompilerHints(), &errHandler);

  if (errHandler.errors())
  {
    if (isErrorExpected(errHandler, &lSpec))
    {
      // done, we expected an error during compile
      return 0;
    }
    else
    {
      printErrors(errHandler, "Error compiling query");
      return 4;
    }
  }

  // set the variables in the dynamic context
  zorba::DynamicContext* lDynCtxt = lQuery->getDynamicContext();

  if (lSpec.hasDateSet()) {
    // set the current date time such that tests that use fn:current-time behave deterministically
    zorba::Item lDateTimeItem = engine->getItemFactory()->createDateTime(lSpec.getDate());

    lDynCtxt->setCurrentDateTime(lDateTimeItem);
  }

  if (lSpec.hasTimezoneSet()) {
    int lTimezone = atoi(lSpec.getTimezone().c_str());

    std::cout << "timezone " << lTimezone << std::endl;
    lDynCtxt->setImplicitTimezone(lTimezone);
  }

  set_vars(&lSpec, lDynCtxt);

  {
    // serialize xml
    std::ofstream lResFileStream(lResultFile.native_file_string().c_str());
    assert (lResFileStream.good());

    lResFileStream << lQuery;

    if (errHandler.errors()) {
      if (isErrorExpected(errHandler, &lSpec)) {
        printErrors(errHandler, "The following execution error occurred as expected");
        return 0;
      } else {
        printErrors(errHandler, "Unexpected error executing query");
        return 6;
      }
    } else if ( lSpec.errorsSize() > 0 ) {
      if ( ! fs::exists(lRefFile) ) {
        std::cerr << "Expected error(s)";
        for (std::vector<std::string>::const_iterator lIter = lSpec.errorsBegin();
            lIter != lSpec.errorsEnd(); ++lIter)
        {
          std::cerr << " " << *lIter;
        }
        if ( fs::exists(lResultFile) && fs::file_size(lResultFile) == 0)
          std::cerr << " but got empty result" << std::endl;
        else {
          std::cerr << " but got result:" << std::endl;
          printFile(std::cerr, lResultFile.native_file_string());
          std::cerr << "=== end of result ===" << std::endl;
        }
        return 7;
      }
    }
  }
  std::cout << "Result:" << std::endl;
  printFile(std::cout, lResultFile.native_file_string());
  std::cout << "=== end of result ===" << std::endl;
  std::cout.flush();

  // last, we have to diff the result
  int lLine, lCol, lPos; // where do the files differ
  bool lRes = isEqual(lRefFile, lResultFile, lLine, lCol, lPos);
  if ( !lRes )  // results differ
  {
    std::cerr << std::endl << "Result does not match expected result:" << std::endl;
    printFile(std::cerr, lRefFile.native_file_string());
    std::cerr << "=== end of expected result ===" << std::endl;

    std::cerr << "See line " << lLine << ", col " << lCol << " of expected result. " << std::endl;
    std::cerr << "Actual: <";
    printPart(std::cerr, lResultFile.native_file_string(), lPos, 15);
    std::cerr << ">" << std::endl;
    std::cerr << "Expected: <";
    printPart(std::cerr, lRefFile.native_file_string(), lPos, 15);
    std::cerr << ">" << std::endl;

    return 8;
  }

  return 0;
}
<commit_msg>Better error message to help debug the testdriver w3c_testsuite  dashboard failures.<commit_after>#include <iostream>
#include <sstream>
#include <fstream>
#include <vector>
#include <string>
#include <stdio.h>
#include <stdlib.h>

#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/filesystem/convenience.hpp>
#include <boost/algorithm/string.hpp>

#include "testdriverconfig.h" // SRC and BIN dir definitions
#include "specification.h" // parsing spec files
#include <zorba/zorba.h>
#include <zorba/error_handler.h>
#include <zorba/exception.h>

namespace fs = boost::filesystem;

void
printFile(std::ostream& os, std::string aInFile)
{
  std::ifstream lInFileStream(aInFile.c_str());
  assert(lInFileStream);

  os << lInFileStream.rdbuf() << std::endl;
}

// print parts of a file
// starting at aStartPos with the length of aLen
void
printPart(std::ostream& os, std::string aInFile,
          int aStartPos, int aLen)
{
  char* buffer = new char [aLen];
  try {
    std::ifstream lIn(aInFile.c_str());
    lIn.seekg(aStartPos);

    int lCharsRead = lIn.readsome (buffer, aLen);
    os.write (buffer, lCharsRead);
    os.flush();
    delete[] buffer;
  } catch (...)
  {
    delete[] buffer;
  }
  return;
}

zorba::XQuery::CompilerHints
getCompilerHints()
{
  zorba::XQuery::CompilerHints lHints;

  // ZORBA_OPTLEVEL=O0 | O1
  char* lOptLevel = getenv("ZORBA_OPTLEVEL");
  if ( lOptLevel != NULL && strcmp(lOptLevel, "O0") == 0 ) {
    lHints.opt_level = zorba::XQuery::CompilerHints::O0;
    std::cout << "testdriver is using optimization level O0" << std::endl;
  } else {
    lHints.opt_level = zorba::XQuery::CompilerHints::O1;
    std::cout << "testdriver is using optimization level O1" << std::endl;
  }
  return lHints;
}

class TestErrorHandler : public zorba::ErrorHandler {
  public:
    void staticError(const zorba::StaticException& aStaticError)
    {
      registerError(aStaticError);
    }

    void dynamicError(const zorba::DynamicException& aDynamicError)
    {
      registerError(aDynamicError);
    }

    void typeError(const zorba::TypeException& aTypeError)
    {
      registerError(aTypeError);
    }

    void serializationError(const zorba::SerializationException& aSerializationError)
    {
      registerError(aSerializationError);
    }

    void systemError(const zorba::SystemException& aSystemError)
    {
      registerError(aSystemError);
    }

    bool errors()
    {
      return !m_errors.empty();
    }

    const std::vector<std::string>& getErrorList()
    {
      return m_errors;
    }
    const std::vector<zorba::String>& getErrorDescs()
    {
      return m_desc;
    }

  private:
    std::vector<std::string> m_errors;
    std::vector<zorba::String> m_desc;

    void registerError(const zorba::ZorbaException& e)
    {
      m_errors.push_back(zorba::ZorbaError::getErrorCode(e.getErrorCode()).c_str());
      m_desc.push_back(e.getDescription());
    }
};

// check of an error that was repored was expected
// by the given specification object
bool
isErrorExpected(TestErrorHandler& errHandler, Specification* aSpec)
{
  const std::vector<std::string>& errors = errHandler.getErrorList();
  for(std::vector<std::string>::const_iterator i = errors.begin(); i != errors.end(); ++i) {
    for(std::vector<std::string>::const_iterator j = aSpec->errorsBegin(); j != aSpec->errorsEnd(); ++j) {
      if (i->compare(*j) == 0) {
        return true;
      }
    }
  }
  return false;
}

// print all errors that were raised
void
printErrors(TestErrorHandler& errHandler, const char *msg)
{
  if (!errHandler.errors()) {
    return;
  }
  std::cerr << msg << ":" << std::endl;

  const std::vector<std::string>& errors = errHandler.getErrorList();
  const std::vector<zorba::String>& descs = errHandler.getErrorDescs();

  std::vector<std::string>::const_iterator codeIter = errors.begin();
  std::vector<zorba::String>::const_iterator descIter = descs.begin();

    for(; codeIter != errors.end(); ++codeIter, ++descIter) {
      assert (descIter != descs.end());
      std::cerr << *codeIter << ": " << *descIter << std::endl;
  }
  return;
}

// set a variable in the dynamic context
// inlineFile specifies whether the given parameter is a file and it's value should
// be inlined or not
void
set_var (bool inlineFile, std::string name, std::string val, zorba::DynamicContext* dctx)
{
  boost::replace_all(val, "$RBKT_SRC_DIR", "file://" + zorba::RBKT_SRC_DIR);

  zorba::ItemFactory* lFactory = zorba::Zorba::getInstance()->getItemFactory();

  if (!inlineFile) {
    zorba::Item lItem = lFactory->createString(val);
		if(name != ".")
			dctx->setVariable (name, lItem);
		else
			dctx->setContextItem (lItem);
  } else {
    const char *val_fname = val.c_str ();
    std::ifstream is (val_fname);
    if (! is) {
      std::cerr << "Could not open file `" << val_fname << "' for variable `" << name << "'" << std::endl;
      assert (false);
    }
		if(name != ".")
			dctx->setVariableAsDocument (name, val.c_str(), is);
		else
			dctx->setContextItemAsDocument (val.c_str(), is);
  }
}

void
set_vars (Specification* aSpec, zorba::DynamicContext* dctx)
{
  for (std::vector<Specification::Variable>::const_iterator lIter = aSpec->variablesBegin();
       lIter != aSpec->variablesEnd(); ++lIter)
  {
    set_var ((*lIter).theInline, (*lIter).theVarName, (*lIter).theVarValue, dctx);
  }
}

void
trim(std::string& str) {

  std::string::size_type  notwhite = str.find_first_not_of(" \t\n");
  str.erase(0,notwhite);

  notwhite = str.find_last_not_of(" \t\n");
  str.erase(notwhite+1);
}

// return false if the files are not equal
// aLine contains the line number in which the first difference occurs
// aCol contains the column number in which the first difference occurs
// aPos is the character number off the first difference in the file
// -1 is returned for aLine, aCol, and aPos if the files are equal
bool
isEqual(fs::path aRefFile, fs::path aResFile, int& aLine, int& aCol, int& aPos)
{
  std::ifstream li(aRefFile.native_file_string().c_str());
  std::ifstream ri(aResFile.native_file_string().c_str());

  std::string lLine, rLine;

  aLine = 1; aCol = 0; aPos = -1;
  while (! li.eof() )
  {
    if ( ri.eof() ) {
      std::getline(li, lLine);
      if (li.peek() == -1) // ignore end-of-line in the ref result
        return true;
      else
        return false;
    }
    std::getline(li, lLine);
    std::getline(ri, rLine);
    ++aLine;
    if ( (aCol = lLine.compare(rLine)) != 0) {
      return false;
    }
  }

  return true;
}

void
slurp_file (const char *fname, std::string &result) {
  std::ifstream qfile(fname, std::ios::binary | std::ios_base::in); assert (qfile);

  qfile.seekg (0, std::ios::end);
  size_t len = qfile.tellg ();
  qfile.seekg (0, std::ios::beg);
  char *str = new char [len];
  qfile.read (str, len);
  len = qfile.gcount();

  std::string sstr (str, len);
  result.swap (sstr);
  delete [] str;
}

int
#ifdef _WIN32_WCE
_tmain(int argc, _TCHAR* argv[])
#else
main(int argc, char** argv)
#endif
{
  fs::path lQueryFile, lResultFile, lErrorFile, lRefFile, lSpecFile;
  Specification lSpec;

  // do initial stuff
  if ( argc == 2 )
  {
    std::string lQueryFileString  = zorba::RBKT_SRC_DIR +"/Queries/" + argv[1];
    lQueryFile = fs::system_complete( fs::path( lQueryFileString, fs::native ) );

    std::string lQueryWithoutSuffix = std::string(argv[1]).substr( 0, std::string(argv[1]).size()-3 );
    std::cout << "test " << lQueryWithoutSuffix << std::endl;
    lResultFile = fs::system_complete(fs::path( zorba::RBKT_BINARY_DIR +"/QueryResults/"
                                      +lQueryWithoutSuffix + ".res", fs::native) );
    lErrorFile = fs::system_complete(fs::path(zorba::RBKT_BINARY_DIR +"/"
                                     +lQueryWithoutSuffix + ".err", fs::native) );
    lRefFile   = fs::system_complete(fs::path( zorba::RBKT_SRC_DIR +"/ExpQueryResults/"
                                     +lQueryWithoutSuffix +".xml.res", fs::native) );
    lSpecFile  = fs::system_complete(fs::path(zorba::RBKT_SRC_DIR+ "/Queries/"
                                     +lQueryWithoutSuffix +".spec", fs::native) );
  }
  else
  {
    std::cerr << "\nusage:   testdriver [testfile]" << std::endl;
    return 1;
  }

  // does the query file exists
  if ( (! fs::exists( lQueryFile )) || fs::is_directory( lQueryFile) ) {
    std::cerr << "\n query file " << lQueryFile.native_file_string()
              << " does not exist or is not a file" << std::endl;
    return 2;
  }

  // delete previous files if they exists
  if ( fs::exists ( lResultFile ) ) { fs::remove (lResultFile); }
  if ( fs::exists ( lErrorFile ) )  { fs::remove (lErrorFile);  }

  // create the result directory
  fs::path lBucket = fs::system_complete(fs::path( lResultFile.branch_path().string(), fs::native ));
  if ( ! fs::exists( lBucket ) )
    fs::create_directories(lBucket); // create deep directories

  // read the xargs and errors if the spec file exists
  if ( fs::exists( lSpecFile ))
  {
    lSpec.parseFile(lSpecFile.native_file_string());
  }

  // we must either have a reference file or an expected error code
  if ( (lSpec.errorsSize() == 0) && ((! fs::exists( lRefFile )) || fs::is_directory( lRefFile)))
  {
    std::cerr << "No reference result and no expected errors." << std::endl;
    return 3;
  }

  // print the query
  std::cout << "Query:" << std::endl;
  printFile(std::cout, lQueryFile.native_file_string());
  std::cout << std::endl;

  zorba::Zorba *engine = zorba::Zorba::getInstance();

  TestErrorHandler errHandler;

  // create and compile the query
  std::string lQueryString;
  slurp_file(lQueryFile.native_file_string().c_str(), lQueryString);
  zorba::XQuery_t lQuery = engine->compileQuery(lQueryString.c_str(), getCompilerHints(), &errHandler);

  if (errHandler.errors())
  {
    if (isErrorExpected(errHandler, &lSpec))
    {
      // done, we expected an error during compile
      return 0;
    }
    else
    {
      printErrors(errHandler, "Error compiling query");
      return 4;
    }
  }

  // set the variables in the dynamic context
  zorba::DynamicContext* lDynCtxt = lQuery->getDynamicContext();

  if (lSpec.hasDateSet()) {
    // set the current date time such that tests that use fn:current-time behave deterministically
    zorba::Item lDateTimeItem = engine->getItemFactory()->createDateTime(lSpec.getDate());

    lDynCtxt->setCurrentDateTime(lDateTimeItem);
  }

  if (lSpec.hasTimezoneSet()) {
    int lTimezone = atoi(lSpec.getTimezone().c_str());

    std::cout << "timezone " << lTimezone << std::endl;
    lDynCtxt->setImplicitTimezone(lTimezone);
  }

  set_vars(&lSpec, lDynCtxt);

  {
    // serialize xml
    std::ofstream lResFileStream(lResultFile.native_file_string().c_str());
    assert (lResFileStream.good());

    lResFileStream << lQuery;

    if (errHandler.errors()) {
      if (isErrorExpected(errHandler, &lSpec)) {
        printErrors(errHandler, "The following execution error occurred as expected");
        return 0;
      } else {
        printErrors(errHandler, "Unexpected error executing query");
        return 6;
      }
    } else if ( lSpec.errorsSize() > 0 ) {
      if ( ! fs::exists(lRefFile) ) {
        std::cerr << "Expected error(s)";
        for (std::vector<std::string>::const_iterator lIter = lSpec.errorsBegin();
            lIter != lSpec.errorsEnd(); ++lIter)
        {
          std::cerr << " " << *lIter;
        }
        if ( fs::exists(lResultFile) && fs::file_size(lResultFile) == 0)
          std::cerr << " but got empty result" << std::endl;
        else {
          std::cerr << " but got result:" << std::endl;
          printFile(std::cerr, lResultFile.native_file_string());
          std::cerr << "=== end of result ===" << std::endl;
        }
        return 7;
      }
    }
  }
  std::cout << "Result:" << std::endl;
  printFile(std::cout, lResultFile.native_file_string());
  std::cout << "=== end of result ===" << std::endl;
  std::cout.flush();

  // last, we have to diff the result
  int lLine, lCol, lPos; // where do the files differ
  bool lRes = isEqual(lRefFile, lResultFile, lLine, lCol, lPos);
  if ( !lRes )  // results differ
  {
    std::cerr << std::endl << "Result does not match expected result:" << std::endl;
    printFile(std::cerr, lRefFile.native_file_string());
    std::cerr << "=== end of expected result ===" << std::endl;

    std::cerr << "See line " << lLine << ", col " << lCol << " of expected result. " << std::endl;
    std::cerr << "Actual: <";
    printPart(std::cerr, lResultFile.native_file_string(), lPos, 15);
    std::cerr << ">" << std::endl;
    std::cerr << "Expected: <";
    printPart(std::cerr, lRefFile.native_file_string(), lPos, 15);
    std::cerr << ">" << std::endl;

    return 8;
  }

  return 0;
}
<|endoftext|>


<commit_before>// Copyright (c) 2013 GitHub, Inc. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "browser/native_window.h"

#include <string>

#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "brightray/browser/inspectable_web_contents.h"
#include "brightray/browser/inspectable_web_contents_view.h"
#include "browser/api/atom_browser_bindings.h"
#include "browser/atom_browser_context.h"
#include "browser/atom_browser_main_parts.h"
#include "browser/atom_javascript_dialog_manager.h"
#include "browser/media/media_stream_devices_controller.h"
#include "browser/window_list.h"
#include "content/public/browser/invalidate_type.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/browser/notification_details.h"
#include "content/public/browser/notification_source.h"
#include "content/public/browser/notification_types.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "common/api/api_messages.h"
#include "common/options_switches.h"
#include "ipc/ipc_message_macros.h"
#include "ui/gfx/point.h"
#include "ui/gfx/rect.h"
#include "ui/gfx/size.h"

using content::NavigationEntry;

namespace atom {

NativeWindow::NativeWindow(content::WebContents* web_contents,
                           base::DictionaryValue* options)
    : content::WebContentsObserver(web_contents),
      is_closed_(false),
      inspectable_web_contents_(
          brightray::InspectableWebContents::Create(web_contents)) {
  web_contents->SetDelegate(this);

  WindowList::AddWindow(this);

  // Get notified of title updated message.
  registrar_.Add(this, content::NOTIFICATION_WEB_CONTENTS_TITLE_UPDATED,
      content::Source<content::WebContents>(web_contents));
}

NativeWindow::~NativeWindow() {
  // It's possible that the windows gets destroyed before it's closed, in that
  // case we need to ensure the OnWindowClosed message is still notified.
  NotifyWindowClosed();
}

// static
NativeWindow* NativeWindow::Create(base::DictionaryValue* options) {
  content::WebContents::CreateParams create_params(AtomBrowserContext::Get());
  return Create(content::WebContents::Create(create_params), options);
}

// static
NativeWindow* NativeWindow::FromRenderView(int process_id, int routing_id) {
  // Stupid iterating.
  WindowList& window_list = *WindowList::GetInstance();
  for (auto window : window_list) {
    content::WebContents* web_contents = window->GetWebContents();
    int window_process_id = web_contents->GetRenderProcessHost()->GetID();
    int window_routing_id = web_contents->GetRoutingID();
    if (window_routing_id == routing_id && window_process_id == process_id)
      return window;
  }

  return NULL;
}

void NativeWindow::InitFromOptions(base::DictionaryValue* options) {
  // Setup window from options.
  int x, y;
  bool center;
  if (options->GetInteger(switches::kX, &x) &&
      options->GetInteger(switches::kY, &y)) {
    int width, height;
    options->GetInteger(switches::kWidth, &width);
    options->GetInteger(switches::kHeight, &height);
    Move(gfx::Rect(x, y, width, height));
  } else if (options->GetBoolean(switches::kCenter, &center) && center) {
    Center();
  }
  int min_height, min_width;
  if (options->GetInteger(switches::kMinHeight, &min_height) &&
      options->GetInteger(switches::kMinWidth, &min_width)) {
    SetMinimumSize(gfx::Size(min_width, min_height));
  }
  int max_height, max_width;
  if (options->GetInteger(switches::kMaxHeight, &max_height) &&
      options->GetInteger(switches::kMaxWidth, &max_width)) {
    SetMaximumSize(gfx::Size(max_width, max_height));
  }
  bool resizable;
  if (options->GetBoolean(switches::kResizable, &resizable)) {
    SetResizable(resizable);
  }
  bool top;
  if (options->GetBoolean(switches::kAlwaysOnTop, &top) && top) {
    SetAlwaysOnTop(true);
  }
  bool fullscreen;
  if (options->GetBoolean(switches::kFullscreen, &fullscreen) && fullscreen) {
    SetFullscreen(true);
  }
  bool kiosk;
  if (options->GetBoolean(switches::kKiosk, &kiosk) && kiosk) {
    SetKiosk(kiosk);
  }
  std::string title("Atom Shell");
  options->GetString(switches::kTitle, &title);
  SetTitle(title);

  // Then show it.
  bool show = true;
  options->GetBoolean(switches::kShow, &show);
  if (show)
    Show();
}

void NativeWindow::OpenDevTools() {
  inspectable_web_contents()->ShowDevTools();
}

void NativeWindow::CloseDevTools() {
  inspectable_web_contents()->GetView()->CloseDevTools();
}

void NativeWindow::FocusOnWebView() {
  GetWebContents()->GetRenderViewHost()->Focus();
}

void NativeWindow::BlurWebView() {
  GetWebContents()->GetRenderViewHost()->Blur();
}

void NativeWindow::RestartHangMonitorTimeout() {
  GetWebContents()->GetRenderViewHost()->RestartHangMonitorTimeout();
}

void NativeWindow::CloseWebContents() {
  bool prevent_default = false;
  FOR_EACH_OBSERVER(NativeWindowObserver,
                    observers_,
                    WillCloseWindow(&prevent_default));
  if (prevent_default) {
    WindowList::WindowCloseCancelled(this);
    return;
  }

  content::WebContents* web_contents(GetWebContents());

  if (web_contents->NeedToFireBeforeUnload())
    web_contents->GetRenderViewHost()->FirePageBeforeUnload(false);
  else
    web_contents->Close();
}

content::WebContents* NativeWindow::GetWebContents() const {
  return inspectable_web_contents_->GetWebContents();
}

void NativeWindow::NotifyWindowClosed() {
  if (is_closed_)
    return;

  is_closed_ = true;
  FOR_EACH_OBSERVER(NativeWindowObserver, observers_, OnWindowClosed());

  WindowList::RemoveWindow(this);
}

void NativeWindow::NotifyWindowBlur() {
  FOR_EACH_OBSERVER(NativeWindowObserver, observers_, OnWindowBlur());
}

// Window opened by window.open.
void NativeWindow::WebContentsCreated(
    content::WebContents* source_contents,
    int64 source_frame_id,
    const string16& frame_name,
    const GURL& target_url,
    content::WebContents* new_contents) {
  LOG(WARNING) << "Please use node-style Window API to create window, "
                  "using window.open has very strict constrains.";

  scoped_ptr<base::DictionaryValue> options(new base::DictionaryValue);
  options->SetInteger(switches::kWidth, 800);
  options->SetInteger(switches::kHeight, 600);

  NativeWindow* window = Create(new_contents, options.get());
  window->InitFromOptions(options.get());
}

content::JavaScriptDialogManager* NativeWindow::GetJavaScriptDialogManager() {
  if (!dialog_manager_)
    dialog_manager_.reset(new AtomJavaScriptDialogManager);

  return dialog_manager_.get();
}

void NativeWindow::BeforeUnloadFired(content::WebContents* tab,
                                     bool proceed,
                                     bool* proceed_to_fire_unload) {
  *proceed_to_fire_unload = proceed;

  if (!proceed)
    WindowList::WindowCloseCancelled(this);
}

void NativeWindow::RequestToLockMouse(content::WebContents* web_contents,
                                      bool user_gesture,
                                      bool last_unlocked_by_target) {
  GetWebContents()->GotResponseToLockMouseRequest(true);
}

void NativeWindow::RequestMediaAccessPermission(
      content::WebContents* web_contents,
      const content::MediaStreamRequest& request,
      const content::MediaResponseCallback& callback) {
  MediaStreamDevicesController controller(request, callback);
  controller.TakeAction();
}

bool NativeWindow::CanOverscrollContent() const {
  return false;
}

void NativeWindow::ActivateContents(content::WebContents* contents) {
  FocusOnWebView();
}

void NativeWindow::DeactivateContents(content::WebContents* contents) {
  BlurWebView();
}

void NativeWindow::MoveContents(content::WebContents* source,
                                const gfx::Rect& pos) {
  SetPosition(pos.origin());
  SetSize(pos.size());
}

void NativeWindow::CloseContents(content::WebContents* source) {
  // When the web contents is gone, close the window immediately, but the
  // memory will not be freed until you call delete.
  // In this way, it would be safe to manage windows via smart pointers. If you
  // want to free memory when the window is closed, you can do deleting by
  // overriding the OnWindowClosed method in the observer.
  CloseImmediately();

  NotifyWindowClosed();
}

bool NativeWindow::IsPopupOrPanel(const content::WebContents* source) const {
  // Only popup window can use things like window.moveTo.
  return true;
}

void NativeWindow::RendererUnresponsive(content::WebContents* source) {
  FOR_EACH_OBSERVER(NativeWindowObserver, observers_, OnRendererUnresponsive());
}

void NativeWindow::RendererResponsive(content::WebContents* source) {
  FOR_EACH_OBSERVER(NativeWindowObserver, observers_, OnRendererResponsive());
}

void NativeWindow::NavigationStateChanged(const content::WebContents* source,
                                          unsigned changed_flags) {
  if (changed_flags == content::INVALIDATE_TYPE_TAB &&
      source->IsCrashed())
    FOR_EACH_OBSERVER(NativeWindowObserver, observers_, OnRendererCrashed());
}

bool NativeWindow::OnMessageReceived(const IPC::Message& message) {
  bool handled = true;
  IPC_BEGIN_MESSAGE_MAP(NativeWindow, message)
    IPC_MESSAGE_HANDLER(AtomViewHostMsg_Message, OnRendererMessage)
    IPC_MESSAGE_HANDLER(AtomViewHostMsg_Message_Sync, OnRendererMessageSync)
    IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP()

  return handled;
}

void NativeWindow::Observe(int type,
                           const content::NotificationSource& source,
                           const content::NotificationDetails& details) {
  if (type == content::NOTIFICATION_WEB_CONTENTS_TITLE_UPDATED) {
    std::pair<NavigationEntry*, bool>* title =
        content::Details<std::pair<NavigationEntry*, bool>>(details).ptr();

    if (title->first) {
      bool prevent_default = false;
      std::string text = UTF16ToUTF8(title->first->GetTitle());
      FOR_EACH_OBSERVER(NativeWindowObserver,
                        observers_,
                        OnPageTitleUpdated(&prevent_default, text));

      if (!prevent_default)
        SetTitle(text);
    }
  }
}

void NativeWindow::OnRendererMessage(const std::string& channel,
                                     const base::ListValue& args) {
  AtomBrowserMainParts::Get()->atom_bindings()->OnRendererMessage(
      GetWebContents()->GetRenderProcessHost()->GetID(),
      GetWebContents()->GetRoutingID(),
      channel,
      args);
}

void NativeWindow::OnRendererMessageSync(const std::string& channel,
                                         const base::ListValue& args,
                                         base::DictionaryValue* result) {
  AtomBrowserMainParts::Get()->atom_bindings()->OnRendererMessageSync(
      GetWebContents()->GetRenderProcessHost()->GetID(),
      GetWebContents()->GetRoutingID(),
      channel,
      args,
      result);
}

}  // namespace atom
<commit_msg>Fix compilation errors and warnings on native_window.cc.<commit_after>// Copyright (c) 2013 GitHub, Inc. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "browser/native_window.h"

#include <string>

#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "brightray/browser/inspectable_web_contents.h"
#include "brightray/browser/inspectable_web_contents_view.h"
#include "browser/api/atom_browser_bindings.h"
#include "browser/atom_browser_context.h"
#include "browser/atom_browser_main_parts.h"
#include "browser/atom_javascript_dialog_manager.h"
#include "browser/media/media_stream_devices_controller.h"
#include "browser/window_list.h"
#include "content/public/browser/invalidate_type.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/browser/notification_details.h"
#include "content/public/browser/notification_source.h"
#include "content/public/browser/notification_types.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "common/api/api_messages.h"
#include "common/options_switches.h"
#include "ipc/ipc_message_macros.h"
#include "ui/gfx/point.h"
#include "ui/gfx/rect.h"
#include "ui/gfx/size.h"

using content::NavigationEntry;

namespace atom {

NativeWindow::NativeWindow(content::WebContents* web_contents,
                           base::DictionaryValue* options)
    : content::WebContentsObserver(web_contents),
      is_closed_(false),
      inspectable_web_contents_(
          brightray::InspectableWebContents::Create(web_contents)) {
  web_contents->SetDelegate(this);

  WindowList::AddWindow(this);

  // Get notified of title updated message.
  registrar_.Add(this, content::NOTIFICATION_WEB_CONTENTS_TITLE_UPDATED,
      content::Source<content::WebContents>(web_contents));
}

NativeWindow::~NativeWindow() {
  // It's possible that the windows gets destroyed before it's closed, in that
  // case we need to ensure the OnWindowClosed message is still notified.
  NotifyWindowClosed();
}

// static
NativeWindow* NativeWindow::Create(base::DictionaryValue* options) {
  content::WebContents::CreateParams create_params(AtomBrowserContext::Get());
  return Create(content::WebContents::Create(create_params), options);
}

// static
NativeWindow* NativeWindow::FromRenderView(int process_id, int routing_id) {
  // Stupid iterating.
  WindowList& window_list = *WindowList::GetInstance();
  for (auto w = window_list.begin(); w != window_list.end(); ++w) {
    auto& window = *w;
    content::WebContents* web_contents = window->GetWebContents();
    int window_process_id = web_contents->GetRenderProcessHost()->GetID();
    int window_routing_id = web_contents->GetRoutingID();
    if (window_routing_id == routing_id && window_process_id == process_id)
      return window;
  }

  return NULL;
}

void NativeWindow::InitFromOptions(base::DictionaryValue* options) {
  // Setup window from options.
  int x = -1, y = -1;
  bool center;
  if (options->GetInteger(switches::kX, &x) &&
      options->GetInteger(switches::kY, &y)) {
    int width = -1, height = -1;
    options->GetInteger(switches::kWidth, &width);
    options->GetInteger(switches::kHeight, &height);
    Move(gfx::Rect(x, y, width, height));
  } else if (options->GetBoolean(switches::kCenter, &center) && center) {
    Center();
  }
  int min_height = -1, min_width = -1;
  if (options->GetInteger(switches::kMinHeight, &min_height) &&
      options->GetInteger(switches::kMinWidth, &min_width)) {
    SetMinimumSize(gfx::Size(min_width, min_height));
  }
  int max_height = -1, max_width = -1;
  if (options->GetInteger(switches::kMaxHeight, &max_height) &&
      options->GetInteger(switches::kMaxWidth, &max_width)) {
    SetMaximumSize(gfx::Size(max_width, max_height));
  }
  bool resizable;
  if (options->GetBoolean(switches::kResizable, &resizable)) {
    SetResizable(resizable);
  }
  bool top;
  if (options->GetBoolean(switches::kAlwaysOnTop, &top) && top) {
    SetAlwaysOnTop(true);
  }
  bool fullscreen;
  if (options->GetBoolean(switches::kFullscreen, &fullscreen) && fullscreen) {
    SetFullscreen(true);
  }
  bool kiosk;
  if (options->GetBoolean(switches::kKiosk, &kiosk) && kiosk) {
    SetKiosk(kiosk);
  }
  std::string title("Atom Shell");
  options->GetString(switches::kTitle, &title);
  SetTitle(title);

  // Then show it.
  bool show = true;
  options->GetBoolean(switches::kShow, &show);
  if (show)
    Show();
}

void NativeWindow::OpenDevTools() {
  inspectable_web_contents()->ShowDevTools();
}

void NativeWindow::CloseDevTools() {
  inspectable_web_contents()->GetView()->CloseDevTools();
}

void NativeWindow::FocusOnWebView() {
  GetWebContents()->GetRenderViewHost()->Focus();
}

void NativeWindow::BlurWebView() {
  GetWebContents()->GetRenderViewHost()->Blur();
}

void NativeWindow::RestartHangMonitorTimeout() {
  GetWebContents()->GetRenderViewHost()->RestartHangMonitorTimeout();
}

void NativeWindow::CloseWebContents() {
  bool prevent_default = false;
  FOR_EACH_OBSERVER(NativeWindowObserver,
                    observers_,
                    WillCloseWindow(&prevent_default));
  if (prevent_default) {
    WindowList::WindowCloseCancelled(this);
    return;
  }

  content::WebContents* web_contents(GetWebContents());

  if (web_contents->NeedToFireBeforeUnload())
    web_contents->GetRenderViewHost()->FirePageBeforeUnload(false);
  else
    web_contents->Close();
}

content::WebContents* NativeWindow::GetWebContents() const {
  return inspectable_web_contents_->GetWebContents();
}

void NativeWindow::NotifyWindowClosed() {
  if (is_closed_)
    return;

  is_closed_ = true;
  FOR_EACH_OBSERVER(NativeWindowObserver, observers_, OnWindowClosed());

  WindowList::RemoveWindow(this);
}

void NativeWindow::NotifyWindowBlur() {
  FOR_EACH_OBSERVER(NativeWindowObserver, observers_, OnWindowBlur());
}

// Window opened by window.open.
void NativeWindow::WebContentsCreated(
    content::WebContents* source_contents,
    int64 source_frame_id,
    const string16& frame_name,
    const GURL& target_url,
    content::WebContents* new_contents) {
  LOG(WARNING) << "Please use node-style Window API to create window, "
                  "using window.open has very strict constrains.";

  scoped_ptr<base::DictionaryValue> options(new base::DictionaryValue);
  options->SetInteger(switches::kWidth, 800);
  options->SetInteger(switches::kHeight, 600);

  NativeWindow* window = Create(new_contents, options.get());
  window->InitFromOptions(options.get());
}

content::JavaScriptDialogManager* NativeWindow::GetJavaScriptDialogManager() {
  if (!dialog_manager_)
    dialog_manager_.reset(new AtomJavaScriptDialogManager);

  return dialog_manager_.get();
}

void NativeWindow::BeforeUnloadFired(content::WebContents* tab,
                                     bool proceed,
                                     bool* proceed_to_fire_unload) {
  *proceed_to_fire_unload = proceed;

  if (!proceed)
    WindowList::WindowCloseCancelled(this);
}

void NativeWindow::RequestToLockMouse(content::WebContents* web_contents,
                                      bool user_gesture,
                                      bool last_unlocked_by_target) {
  GetWebContents()->GotResponseToLockMouseRequest(true);
}

void NativeWindow::RequestMediaAccessPermission(
      content::WebContents* web_contents,
      const content::MediaStreamRequest& request,
      const content::MediaResponseCallback& callback) {
  MediaStreamDevicesController controller(request, callback);
  controller.TakeAction();
}

bool NativeWindow::CanOverscrollContent() const {
  return false;
}

void NativeWindow::ActivateContents(content::WebContents* contents) {
  FocusOnWebView();
}

void NativeWindow::DeactivateContents(content::WebContents* contents) {
  BlurWebView();
}

void NativeWindow::MoveContents(content::WebContents* source,
                                const gfx::Rect& pos) {
  SetPosition(pos.origin());
  SetSize(pos.size());
}

void NativeWindow::CloseContents(content::WebContents* source) {
  // When the web contents is gone, close the window immediately, but the
  // memory will not be freed until you call delete.
  // In this way, it would be safe to manage windows via smart pointers. If you
  // want to free memory when the window is closed, you can do deleting by
  // overriding the OnWindowClosed method in the observer.
  CloseImmediately();

  NotifyWindowClosed();
}

bool NativeWindow::IsPopupOrPanel(const content::WebContents* source) const {
  // Only popup window can use things like window.moveTo.
  return true;
}

void NativeWindow::RendererUnresponsive(content::WebContents* source) {
  FOR_EACH_OBSERVER(NativeWindowObserver, observers_, OnRendererUnresponsive());
}

void NativeWindow::RendererResponsive(content::WebContents* source) {
  FOR_EACH_OBSERVER(NativeWindowObserver, observers_, OnRendererResponsive());
}

void NativeWindow::NavigationStateChanged(const content::WebContents* source,
                                          unsigned changed_flags) {
  if (changed_flags == content::INVALIDATE_TYPE_TAB &&
      source->IsCrashed())
    FOR_EACH_OBSERVER(NativeWindowObserver, observers_, OnRendererCrashed());
}

bool NativeWindow::OnMessageReceived(const IPC::Message& message) {
  bool handled = true;
  IPC_BEGIN_MESSAGE_MAP(NativeWindow, message)
    IPC_MESSAGE_HANDLER(AtomViewHostMsg_Message, OnRendererMessage)
    IPC_MESSAGE_HANDLER(AtomViewHostMsg_Message_Sync, OnRendererMessageSync)
    IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP()

  return handled;
}

void NativeWindow::Observe(int type,
                           const content::NotificationSource& source,
                           const content::NotificationDetails& details) {
  if (type == content::NOTIFICATION_WEB_CONTENTS_TITLE_UPDATED) {
    std::pair<NavigationEntry*, bool>* title =
        content::Details<std::pair<NavigationEntry*, bool>>(details).ptr();

    if (title->first) {
      bool prevent_default = false;
      std::string text = UTF16ToUTF8(title->first->GetTitle());
      FOR_EACH_OBSERVER(NativeWindowObserver,
                        observers_,
                        OnPageTitleUpdated(&prevent_default, text));

      if (!prevent_default)
        SetTitle(text);
    }
  }
}

void NativeWindow::OnRendererMessage(const std::string& channel,
                                     const base::ListValue& args) {
  AtomBrowserMainParts::Get()->atom_bindings()->OnRendererMessage(
      GetWebContents()->GetRenderProcessHost()->GetID(),
      GetWebContents()->GetRoutingID(),
      channel,
      args);
}

void NativeWindow::OnRendererMessageSync(const std::string& channel,
                                         const base::ListValue& args,
                                         base::DictionaryValue* result) {
  AtomBrowserMainParts::Get()->atom_bindings()->OnRendererMessageSync(
      GetWebContents()->GetRenderProcessHost()->GetID(),
      GetWebContents()->GetRoutingID(),
      channel,
      args,
      result);
}

}  // namespace atom
<|endoftext|>


<commit_before>#include "OpenCLManager.hpp"

using namespace cl;

oul::OpenCLManager* oul::OpenCLManager::getInstance() {
    if(this->instance == NULL) {
        this->instance = new OpenCLManager();
    }
    return this->instance;
}

oul::Context oul::OpenCLManager::createContext(
        std::vector<cl::Device> devices) {
    return oul::Context(devices);
}

/**
 * This method parses program arguments into device criteria and returns a context
 */
oul::Context oul::OpenCLManager::createContext(int argc, char** argv) {
}

/**
 * This method finds a set of devices which satisfies the supplied device criteria and creates a context
 */
oul::Context oul::OpenCLManager::createContext(DeviceCriteria deviceCriteria) {

    std::vector<Device> validDevices;

    // First, get all the platforms that fit the platform criteria
    std::vector<Platform> validPlatforms;
    if(deviceCriteria.getPlatformCriteria() == oul::DEVICE_PLATFORM_ANY) {
        validPlatforms = this->platforms;
    } else {
        // TODO: Find the correct platform and add to validPlatforms
    }

    for(int i = 0; i < validPlatforms.size(); i++) {
        // Next, get all devices of correct type for each of those platforms
        std::vector<Device> platformDevices;
        cl_device_type deviceType;
        if(deviceCriteria.getTypeCriteria() == oul::DEVICE_TYPE_ANY) {
            deviceType = CL_DEVICE_TYPE_ALL;
        } else if(deviceCriteria.getTypeCriteria() == oul::DEVICE_TYPE_GPU) {
            deviceType = CL_DEVICE_TYPE_GPU;
        } else if(deviceCriteria.getTypeCriteria() == oul::DEVICE_TYPE_CPU) {
            deviceType = CL_DEVICE_TYPE_CPU;
        }
        platforms[i].getDevices(deviceType, &platformDevices);

        // Go through each device and see if they have the correct capabilities (if any)
        for(int j = 0; j < platformDevices.size(); j++) {
            if(deviceCriteria.getCapabilityCriteria().size() > 0) {
                // TODO: implement some capability criteria
            }
            validDevices.push_back(platformDevices[j]);

            // Watch the device count
            if(deviceCriteria.getDeviceCount() != oul::DEVICE_COUNT_INFINITE && deviceCriteria.getDeviceCount() == validDevices.size())
                break;
        }

        // Watch the device count
        if(deviceCriteria.getDeviceCount() != oul::DEVICE_COUNT_INFINITE && deviceCriteria.getDeviceCount() == validDevices.size())
            break;
    }

    return oul::Context(validDevices);
}

void oul::OpenCLManager::setDebugMode(bool mode) {
    this->debugMode = mode;
}
<commit_msg>implemented selection of platform<commit_after>#include "OpenCLManager.hpp"

using namespace cl;

oul::OpenCLManager* oul::OpenCLManager::getInstance() {
    if(this->instance == NULL) {
        this->instance = new OpenCLManager();
    }
    return this->instance;
}

oul::Context oul::OpenCLManager::createContext(
        std::vector<cl::Device> devices) {
    return oul::Context(devices);
}

/**
 * This method parses program arguments into device criteria and returns a context
 */
oul::Context oul::OpenCLManager::createContext(int argc, char** argv) {
}

/**
 * This method finds a set of devices which satisfies the supplied device criteria and creates a context
 */
oul::Context oul::OpenCLManager::createContext(DeviceCriteria deviceCriteria) {

    std::vector<Device> validDevices;

    // First, get all the platforms that fit the platform criteria
    std::vector<Platform> validPlatforms;
    if(deviceCriteria.getPlatformCriteria() == oul::DEVICE_PLATFORM_ANY) {
        validPlatforms = this->platforms;
    } else {
        // Find the correct platform and add to validPlatforms
        std::string find;
        switch(deviceCriteria.getPlatformCriteria()) {
            case oul::DEVICE_PLATFORM_NVIDIA:
                find = "NVIDIA";
            break;
            case oul::DEVICE_PLATFORM_AMD:
                find = "Advanced Micro Devices";
            break;
            case oul::DEVICE_PLATFORM_INTEL:
                find = "Intel";
            break;
        }
        for(int i = 0; i < platforms.size(); i++) {
            if(platforms[i].getInfo<CL_PLATFORM_VENDOR>().find(find) != std::string::npos) {
                validPlatforms.push_back(platforms[i]);
                break;
            }
        }
    }

    for(int i = 0; i < validPlatforms.size(); i++) {
        // Next, get all devices of correct type for each of those platforms
        std::vector<Device> platformDevices;
        cl_device_type deviceType;
        if(deviceCriteria.getTypeCriteria() == oul::DEVICE_TYPE_ANY) {
            deviceType = CL_DEVICE_TYPE_ALL;
        } else if(deviceCriteria.getTypeCriteria() == oul::DEVICE_TYPE_GPU) {
            deviceType = CL_DEVICE_TYPE_GPU;
        } else if(deviceCriteria.getTypeCriteria() == oul::DEVICE_TYPE_CPU) {
            deviceType = CL_DEVICE_TYPE_CPU;
        }
        platforms[i].getDevices(deviceType, &platformDevices);

        // Go through each device and see if they have the correct capabilities (if any)
        for(int j = 0; j < platformDevices.size(); j++) {
            if(deviceCriteria.getCapabilityCriteria().size() > 0) {
                // TODO: implement some capability criteria
            }
            validDevices.push_back(platformDevices[j]);

            // Watch the device count
            if(deviceCriteria.getDeviceCount() != oul::DEVICE_COUNT_INFINITE && deviceCriteria.getDeviceCount() == validDevices.size())
                break;
        }

        // Watch the device count
        if(deviceCriteria.getDeviceCount() != oul::DEVICE_COUNT_INFINITE && deviceCriteria.getDeviceCount() == validDevices.size())
            break;
    }

    return oul::Context(validDevices);
}

void oul::OpenCLManager::setDebugMode(bool mode) {
    this->debugMode = mode;
}
<|endoftext|>


<commit_before>
#include "AConfig.h"
#if(HAS_STD_PILOT)
#include "Device.h"
#include "Pin.h"
#include "Pilot.h"
#include "Timer.h"

Timer pilotTimer;
bool _headingHoldEnabled = false;
int  _headingHoldTarget = 0;
int hdg = 0;
int hdg_Error;
int raw_Left, raw_Right;
int left, right;  // motor outputs in microseconds, +/-500
int loop_Gain = 1;
int integral_Divisor = 100;
long hdg_Error_Integral = 0;
int tgt_Hdg = 0;
bool _depthHoldEnabled = false;
int _depthHoldTarget = 0;
int depth = 0;
int depth_Error = 0;
int raw_lift =0;
int lift = 0;
int target_depth;
int raw_yaw, yaw;

void Pilot::device_setup(){
  pilotTimer.reset();
  Serial.println(F("log:pilot setup complete;"));
}

void Pilot::device_loop(Command command){
//intended to respond to fly by wire commands: MaintainHeading(); TurnTo(compassheading); DiveTo(depth);
    if( command.cmp("holdHeading_toggle")){
      if (_headingHoldEnabled) {
        _headingHoldEnabled = false;
        raw_Left = 0;
        raw_Right = 0;
        hdg_Error_Integral = 0;  // Reset error integrator
        tgt_Hdg = -500;  // -500 = system not in hdg hold

        int argsToSend[] = {1,00}; //include number of parms as last parm
        command.pushCommand("yaw",argsToSend);
        Serial.println(F("log:heading_hold_disabled;"));

      } else {
        _headingHoldEnabled = true;
        if(command.args[0]==0){
          _headingHoldTarget = navdata::HDGD;
        } else {
          _headingHoldTarget = command.args[1];
        }
        tgt_Hdg = _headingHoldTarget;
        Serial.print(F("log:heading_hold_enabled on="));
        Serial.print(tgt_Hdg);
        Serial.println(';');
      }
      Serial.print(F("targetHeading:"));
      if (_headingHoldEnabled) {
        Serial.print(tgt_Hdg);
      } else {
        Serial.print(DISABLED);
      }
      Serial.println(';');
    }

    if( command.cmp("holdDepth_toggle")){
      if (_depthHoldEnabled) {
        _depthHoldEnabled = false;
        raw_lift = 0;
        target_depth = 0;

        int argsToSend[] = {1,0}; //include number of parms as last parm
        command.pushCommand("lift",argsToSend);
        Serial.println(F("log:depth_hold_disabled;"));

      } else {
        _depthHoldEnabled = true;
        if(command.args[0]==0){
          _depthHoldTarget = navdata::DEAP*100;  //casting to cm
        } else {
          _depthHoldTarget = command.args[1];
        }
        target_depth = _depthHoldTarget;
        Serial.print(F("log:depth_hold_enabled on="));
        Serial.print(target_depth);
        Serial.println(';');
      }
      Serial.print(F("targetDepth:"));
      if (_depthHoldEnabled) {
        Serial.print(target_depth);
      } else {
        Serial.pitnt(DISABLED);
      }
      Serial.println(';');
    }

    if (pilotTimer.elapsed (50)) {

      // Autopilot Test #3 6 Jan 2014
      // Hold vehicle at arbitrary heading
      // Integer math; proportional control plus basic integrator
      // No hysteresis around 180 degree error

      // Check whether hold mode is on

      if (_depthHoldEnabled)
      {
        depth = navdata::DEAP*100;
        depth_Error = target_depth-depth;  //positive error = positive lift = go deaper.

        raw_lift = depth_Error * loop_Gain;
        lift = constrain(raw_lift, -50, 50);

        Serial.println(F("log:dhold pushing command;"));
        Serial.print(F("dp_er:"));
        Serial.print(depth_Error);
        Serial.println(';');
        int argsToSend[] = {1,lift}; //include number of parms as last parm
        command.pushCommand("lift",argsToSend);

      }

      if (_headingHoldEnabled)
      {

        // Code for hold mode here
        hdg = navdata::HDGD;

        // Calculate heading error

        hdg_Error = hdg - tgt_Hdg;

        if (hdg_Error > 180)
        {
        hdg_Error = hdg_Error - 360;
        }

        if (hdg_Error < -179)
        {
        hdg_Error = hdg_Error + 360;
        }

        // Run error accumulator (integrator)
        hdg_Error_Integral = hdg_Error_Integral + hdg_Error;

        // Calculator motor outputs
        raw_yaw = -1 * hdg_Error * loop_Gain;

        // raw_Left = raw_Left - (hdg_Error_Integral / integral_Divisor);
        // raw_Right = raw_Right + (hdg_Error_Integral / integral_Divisor);

        // Constrain and output to motors

        yaw = constrain(raw_yaw, -50, 50);
        Serial.println(F("log:hold pushing command;"));
        Serial.print(F("p_er:"));
        Serial.print(hdg_Error);
        Serial.println(';');

        int argsToSend[] = {1,yaw}; //include number of parms as last parm
        command.pushCommand("yaw",argsToSend);
      }

    }
}
#endif

<commit_msg>Revert "Fix spelling in Arduino"<commit_after>
#include "AConfig.h"
#if(HAS_STD_PILOT)
#include "Device.h"
#include "Pin.h"
#include "Pilot.h"
#include "Timer.h"

Timer pilotTimer;
bool _headingHoldEnabled = false;
int  _headingHoldTarget = 0;
int hdg = 0;
int hdg_Error;
int raw_Left, raw_Right;
int left, right;  // motor outputs in microseconds, +/-500
int loop_Gain = 1;
int integral_Divisor = 100;
long hdg_Error_Integral = 0;
int tgt_Hdg = 0;
bool _depthHoldEnabled = false;
int _depthHoldTarget = 0;
int depth = 0;
int depth_Error = 0;
int raw_lift =0;
int lift = 0;
int target_depth;
int raw_yaw, yaw;

void Pilot::device_setup(){
  pilotTimer.reset();
  Serial.println(F("log:pilot setup complete;"));
}

void Pilot::device_loop(Command command){
//intended to respond to fly by wire commands: MaintainHeading(); TurnTo(compassheading); DiveTo(depth);
    if( command.cmp("holdHeading_toggle")){
      if (_headingHoldEnabled) {
        _headingHoldEnabled = false;
        raw_Left = 0;
        raw_Right = 0;
        hdg_Error_Integral = 0;  // Reset error integrator
        tgt_Hdg = -500;  // -500 = system not in hdg hold

        int argsToSend[] = {1,00}; //include number of parms as last parm
        command.pushCommand("yaw",argsToSend);
        Serial.println(F("log:heading_hold_disabled;"));

      } else {
        _headingHoldEnabled = true;
        if(command.args[0]==0){
          _headingHoldTarget = navdata::HDGD;
        } else {
          _headingHoldTarget = command.args[1];
        }
        tgt_Hdg = _headingHoldTarget;
        Serial.print(F("log:heading_hold_enabled on="));
        Serial.print(tgt_Hdg);
        Serial.println(';');
      }
      Serial.print(F("targetHeading:"));
      if (_headingHoldEnabled) {
        Serial.print(tgt_Hdg);
      } else {
        Serial.print(DISAABLED);
      }
      Serial.println(';');
    }

    if( command.cmp("holdDepth_toggle")){
      if (_depthHoldEnabled) {
        _depthHoldEnabled = false;
        raw_lift = 0;
        target_depth = 0;

        int argsToSend[] = {1,0}; //include number of parms as last parm
        command.pushCommand("lift",argsToSend);
        Serial.println(F("log:depth_hold_disabled;"));

      } else {
        _depthHoldEnabled = true;
        if(command.args[0]==0){
          _depthHoldTarget = navdata::DEAP*100;  //casting to cm
        } else {
          _depthHoldTarget = command.args[1];
        }
        target_depth = _depthHoldTarget;
        Serial.print(F("log:depth_hold_enabled on="));
        Serial.print(target_depth);
        Serial.println(';');
      }
      Serial.print(F("targetDepth:"));
      if (_depthHoldEnabled) {
        Serial.print(target_depth);
      } else {
        Serial.pitnt(DISABLED);
      }
      Serial.println(';');
    }

    if (pilotTimer.elapsed (50)) {

      // Autopilot Test #3 6 Jan 2014
      // Hold vehicle at arbitrary heading
      // Integer math; proportional control plus basic integrator
      // No hysteresis around 180 degree error

      // Check whether hold mode is on

      if (_depthHoldEnabled)
      {
        depth = navdata::DEAP*100;
        depth_Error = target_depth-depth;  //positive error = positive lift = go deaper.

        raw_lift = depth_Error * loop_Gain;
        lift = constrain(raw_lift, -50, 50);

        Serial.println(F("log:dhold pushing command;"));
        Serial.print(F("dp_er:"));
        Serial.print(depth_Error);
        Serial.println(';');
        int argsToSend[] = {1,lift}; //include number of parms as last parm
        command.pushCommand("lift",argsToSend);

      }

      if (_headingHoldEnabled)
      {

        // Code for hold mode here
        hdg = navdata::HDGD;

        // Calculate heading error

        hdg_Error = hdg - tgt_Hdg;

        if (hdg_Error > 180)
        {
        hdg_Error = hdg_Error - 360;
        }

        if (hdg_Error < -179)
        {
        hdg_Error = hdg_Error + 360;
        }

        // Run error accumulator (integrator)
        hdg_Error_Integral = hdg_Error_Integral + hdg_Error;

        // Calculator motor outputs
        raw_yaw = -1 * hdg_Error * loop_Gain;

        // raw_Left = raw_Left - (hdg_Error_Integral / integral_Divisor);
        // raw_Right = raw_Right + (hdg_Error_Integral / integral_Divisor);

        // Constrain and output to motors

        yaw = constrain(raw_yaw, -50, 50);
        Serial.println(F("log:hold pushing command;"));
        Serial.print(F("p_er:"));
        Serial.print(hdg_Error);
        Serial.println(';');

        int argsToSend[] = {1,yaw}; //include number of parms as last parm
        command.pushCommand("yaw",argsToSend);
      }

    }
}
#endif

<|endoftext|>