<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2015 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

// mapnik
#include <mapnik/color.hpp>
#include <mapnik/color_factory.hpp>
#include <mapnik/config_error.hpp>
// agg
#include "agg_color_rgba.h"

#pragma GCC diagnostic push
#include <mapnik/warning_ignore.hpp>
#include <boost/spirit/include/karma.hpp>
#pragma GCC diagnostic pop

// stl
#include <sstream>

namespace mapnik {

color::color(std::string const& str, bool premultiplied)
{
    *this = parse_color(str);
    premultiplied_ = premultiplied;
}

std::string color::to_string() const
{
    namespace karma = boost::spirit::karma;
    boost::spirit::karma::eps_type eps;
    boost::spirit::karma::double_type double_;
    boost::spirit::karma::uint_generator<uint8_t,10> color_;
    std::string str;
    std::back_insert_iterator<std::string> sink(str);
    karma::generate(sink, eps(alpha() < 255)
                    // begin grammar
                    << "rgba("
                    << color_(red()) << ','
                    << color_(green()) << ','
                    << color_(blue()) << ','
                    << double_(alpha()/255.0) << ')'
                    |
                    "rgb("
                    << color_(red()) << ','
                    << color_(green()) << ','
                    << color_(blue()) << ')'
                    // end grammar
        );
    return str;
}

std::string color::to_hex_string() const
{
    namespace karma = boost::spirit::karma;
    boost::spirit::karma::hex_type hex;
    boost::spirit::karma::eps_type eps;
    boost::spirit::karma::right_align_type right_align;
    std::string str;
    std::back_insert_iterator<std::string> sink(str);
    karma::generate(sink,
                    // begin grammar
                    '#'
                    << right_align(2,'0')[hex(red())]
                    << right_align(2,'0')[hex(green())]
                    << right_align(2,'0')[hex(blue())]
                    << eps(alpha() < 255) << right_align(2,'0')[hex(alpha())]
                    // end grammar
        );
    return str;
}

bool color::premultiply()
{
    if (premultiplied_) return false;
    agg::rgba8 pre_c = agg::rgba8(red_,green_,blue_,alpha_);
    pre_c.premultiply();
    red_ = pre_c.r;
    green_ = pre_c.g;
    blue_ = pre_c.b;
    premultiplied_ = true;
    return true;
}

bool color::demultiply()
{
    if (!premultiplied_) return false;
    agg::rgba8 pre_c = agg::rgba8(red_,green_,blue_,alpha_);
    pre_c.demultiply();
    red_ = pre_c.r;
    green_ = pre_c.g;
    blue_ = pre_c.b;
    premultiplied_ = false;
    return true;
}

}
<commit_msg>color.cpp - port premultiply/demultiply and remove agg dependency<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2015 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

// mapnik
#include <mapnik/color.hpp>
#include <mapnik/color_factory.hpp>
#include <mapnik/config_error.hpp>

#pragma GCC diagnostic push
#include <mapnik/warning_ignore.hpp>
#include <boost/spirit/include/karma.hpp>
#pragma GCC diagnostic pop

// stl
#include <sstream>

namespace mapnik {

color::color(std::string const& str, bool premultiplied)
{
    *this = parse_color(str);
    premultiplied_ = premultiplied;
}

std::string color::to_string() const
{
    namespace karma = boost::spirit::karma;
    boost::spirit::karma::eps_type eps;
    boost::spirit::karma::double_type double_;
    boost::spirit::karma::uint_generator<uint8_t,10> color_;
    std::string str;
    std::back_insert_iterator<std::string> sink(str);
    karma::generate(sink, eps(alpha() < 255)
                    // begin grammar
                    << "rgba("
                    << color_(red()) << ','
                    << color_(green()) << ','
                    << color_(blue()) << ','
                    << double_(alpha()/255.0) << ')'
                    |
                    "rgb("
                    << color_(red()) << ','
                    << color_(green()) << ','
                    << color_(blue()) << ')'
                    // end grammar
        );
    return str;
}

std::string color::to_hex_string() const
{
    namespace karma = boost::spirit::karma;
    boost::spirit::karma::hex_type hex;
    boost::spirit::karma::eps_type eps;
    boost::spirit::karma::right_align_type right_align;
    std::string str;
    std::back_insert_iterator<std::string> sink(str);
    karma::generate(sink,
                    // begin grammar
                    '#'
                    << right_align(2,'0')[hex(red())]
                    << right_align(2,'0')[hex(green())]
                    << right_align(2,'0')[hex(blue())]
                    << eps(alpha() < 255) << right_align(2,'0')[hex(alpha())]
                    // end grammar
        );
    return str;
}

namespace  {

static std::uint8_t multiply(std::uint8_t c, std::uint8_t a)
{
    std::uint32_t t = c * a + 128;
    return std::uint8_t(((t >> 8) + t) >> 8);
}

}

bool color::premultiply()
{
    if (premultiplied_) return false;
    if (alpha_ != 255)
    {
        red_ = multiply(red_, alpha_);
        green_ = multiply(green_, alpha_);
        blue_ = multiply(blue_, alpha_);
    }
    premultiplied_ = true;
    return true;
}

bool color::demultiply()
{
    if (!premultiplied_) return false;
    if (alpha_ < 255)
    {
        if (alpha_ == 0)
        {
            red_ = green_ = blue_ = 0;
        }
        else
        {
            std::uint32_t r = (std::uint32_t(red_) * 255) / alpha_;
            std::uint32_t g = (std::uint32_t(green_) * 255) / alpha_;
            std::uint32_t b = (std::uint32_t(blue_) * 255) / alpha_;
            red_ = (r > 255) ? 255 : r;
            green_ = (g > 255) ? 255 : g;
            blue_ = (b > 255) ? 255 : b;
        }
    }
    premultiplied_ = false;
    return true;
}
}
<|endoftext|>


<commit_before>// Copyright (c) 2009 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 "chrome/common/chrome_switches.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_layout_test.h"

// TODO(jorlow): Enable all of these tests, eventually...
static const char* kEventsFiles[] = {
  //"complex-values.html",
  //"iframe-events.html",
  //"index-get-and-set.html",
  //"onstorage-attribute-markup.html",
  //"onstorage-attribute-setattribute.html",
  //"onstorage-attribute-setwindow.html",
  "simple-events.html",
  //"string-conversion.html",
  //"window-open.html",
  NULL
};

static const char* kTopLevelFiles[] = {
  "clear.html",
  "quota.html",
  "remove-item.html",
  //"window-attributes-exist.html",
  NULL
};

static const char* kNoEventsFiles[] = {
  //"complex-keys.html",
  "delete-removal.html",
  "enumerate-storage.html",
  "enumerate-with-length-and-key.html",
  "simple-usage.html",
  NULL
};

static const char* kLocalStorageFiles[] = {
  //  "quota.html",
  NULL
};

static const char* kSessionStorageFiles[] = {
  //  "no-quota.html",
  NULL
};

class DOMStorageTest : public UILayoutTest {
 protected:
  DOMStorageTest()
      : UILayoutTest(),
        test_dir_(FilePath().AppendASCII("LayoutTests").
                  AppendASCII("storage").AppendASCII("domstorage")) {
  }

  virtual ~DOMStorageTest() { }

  virtual void SetUp() {
    launch_arguments_.AppendSwitch(switches::kDisablePopupBlocking);
    launch_arguments_.AppendSwitch(switches::kEnableSessionStorage);
    UILayoutTest::SetUp();
  }

  // We require fast/js/resources and storage/domstorage/script-tests for most
  // of the DOM Storage layout tests.  Add those to the list to be copied.
  void AddResources() {
    // Add other paths our tests require.
    FilePath js_dir = FilePath().AppendASCII("LayoutTests").
                      AppendASCII("fast").AppendASCII("js");
    AddResourceForLayoutTest(js_dir, FilePath().AppendASCII("resources"));
    AddResourceForLayoutTest(test_dir_, FilePath().AppendASCII("script-tests"));
  }

  // This is somewhat of a hack because we're running a real browser that
  // actually persists the LocalStorage state vs. DRT and TestShell which don't.
  // The correct fix is to fix the LayoutTests, but similar patches have been
  // rejected in the past.
  void ClearDOMStorage() {
    scoped_refptr<TabProxy> tab(GetActiveTab());
    ASSERT_TRUE(tab.get());

    GURL url = GetTestUrl(L"layout_tests", L"clear_dom_storage.html");
    tab->SetCookie(url, "");
    ASSERT_TRUE(tab->NavigateToURL(url));

    WaitUntilCookieNonEmpty(tab.get(), url, "cleared", kTestIntervalMs,
                            kTestWaitTimeoutMs);
  }

  // Runs each test in an array of strings until it hits a NULL.
  void RunTests(const char** files) {
    while (*files) {
      ClearDOMStorage();
      RunLayoutTest(*files, false);
      ++files;
    }
  }

  FilePath test_dir_;
};

TEST_F(DOMStorageTest, DOMStorageLayoutTests) {
  InitializeForLayoutTest(test_dir_, FilePath(), false);
  AddResources();
  RunTests(kTopLevelFiles);
}

TEST_F(DOMStorageTest, LocalStorageLayoutTests) {
  InitializeForLayoutTest(test_dir_, FilePath().AppendASCII("localstorage"),
                          false);
  AddResources();
  RunTests(kNoEventsFiles);
  RunTests(kEventsFiles);
  RunTests(kLocalStorageFiles);
}

TEST_F(DOMStorageTest, SessionStorageLayoutTests) {
  InitializeForLayoutTest(test_dir_, FilePath().AppendASCII("sessionstorage"),
                          false);
  AddResources();
  RunTests(kNoEventsFiles);
  //RunTests(kEventsFiles);
  RunTests(kSessionStorageFiles);
}
<commit_msg>Mark DOMStorageTest.LocalStorageLayoutTests as flaky. Failed http://build.chromium.org/buildbot/waterfall/builders/XP%20Tests/builds/14458/steps/ui_tests/logs/stdio<commit_after>// Copyright (c) 2009 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 "chrome/common/chrome_switches.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_layout_test.h"

// TODO(jorlow): Enable all of these tests, eventually...
static const char* kEventsFiles[] = {
  //"complex-values.html",
  //"iframe-events.html",
  //"index-get-and-set.html",
  //"onstorage-attribute-markup.html",
  //"onstorage-attribute-setattribute.html",
  //"onstorage-attribute-setwindow.html",
  "simple-events.html",
  //"string-conversion.html",
  //"window-open.html",
  NULL
};

static const char* kTopLevelFiles[] = {
  "clear.html",
  "quota.html",
  "remove-item.html",
  //"window-attributes-exist.html",
  NULL
};

static const char* kNoEventsFiles[] = {
  //"complex-keys.html",
  "delete-removal.html",
  "enumerate-storage.html",
  "enumerate-with-length-and-key.html",
  "simple-usage.html",
  NULL
};

static const char* kLocalStorageFiles[] = {
  //  "quota.html",
  NULL
};

static const char* kSessionStorageFiles[] = {
  //  "no-quota.html",
  NULL
};

class DOMStorageTest : public UILayoutTest {
 protected:
  DOMStorageTest()
      : UILayoutTest(),
        test_dir_(FilePath().AppendASCII("LayoutTests").
                  AppendASCII("storage").AppendASCII("domstorage")) {
  }

  virtual ~DOMStorageTest() { }

  virtual void SetUp() {
    launch_arguments_.AppendSwitch(switches::kDisablePopupBlocking);
    launch_arguments_.AppendSwitch(switches::kEnableSessionStorage);
    UILayoutTest::SetUp();
  }

  // We require fast/js/resources and storage/domstorage/script-tests for most
  // of the DOM Storage layout tests.  Add those to the list to be copied.
  void AddResources() {
    // Add other paths our tests require.
    FilePath js_dir = FilePath().AppendASCII("LayoutTests").
                      AppendASCII("fast").AppendASCII("js");
    AddResourceForLayoutTest(js_dir, FilePath().AppendASCII("resources"));
    AddResourceForLayoutTest(test_dir_, FilePath().AppendASCII("script-tests"));
  }

  // This is somewhat of a hack because we're running a real browser that
  // actually persists the LocalStorage state vs. DRT and TestShell which don't.
  // The correct fix is to fix the LayoutTests, but similar patches have been
  // rejected in the past.
  void ClearDOMStorage() {
    scoped_refptr<TabProxy> tab(GetActiveTab());
    ASSERT_TRUE(tab.get());

    GURL url = GetTestUrl(L"layout_tests", L"clear_dom_storage.html");
    tab->SetCookie(url, "");
    ASSERT_TRUE(tab->NavigateToURL(url));

    WaitUntilCookieNonEmpty(tab.get(), url, "cleared", kTestIntervalMs,
                            kTestWaitTimeoutMs);
  }

  // Runs each test in an array of strings until it hits a NULL.
  void RunTests(const char** files) {
    while (*files) {
      ClearDOMStorage();
      RunLayoutTest(*files, false);
      ++files;
    }
  }

  FilePath test_dir_;
};

TEST_F(DOMStorageTest, DOMStorageLayoutTests) {
  InitializeForLayoutTest(test_dir_, FilePath(), false);
  AddResources();
  RunTests(kTopLevelFiles);
}

TEST_F(DOMStorageTest, FLAKY_LocalStorageLayoutTests) {
  InitializeForLayoutTest(test_dir_, FilePath().AppendASCII("localstorage"),
                          false);
  AddResources();
  RunTests(kNoEventsFiles);
  RunTests(kEventsFiles);
  RunTests(kLocalStorageFiles);
}

TEST_F(DOMStorageTest, SessionStorageLayoutTests) {
  InitializeForLayoutTest(test_dir_, FilePath().AppendASCII("sessionstorage"),
                          false);
  AddResources();
  RunTests(kNoEventsFiles);
  //RunTests(kEventsFiles);
  RunTests(kSessionStorageFiles);
}
<|endoftext|>


<commit_before>// Copyright 2013 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 "chrome/browser/local_discovery/privet_notifications.h"

#include "base/bind.h"
#include "base/message_loop/message_loop.h"
#include "base/rand_util.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/local_discovery/privet_device_lister_impl.h"
#include "chrome/browser/local_discovery/privet_http_asynchronous_factory.h"
#include "chrome/browser/local_discovery/privet_traffic_detector.h"
#include "chrome/browser/local_discovery/service_discovery_shared_client.h"
#include "chrome/browser/notifications/notification.h"
#include "chrome/browser/notifications/notification_ui_manager.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/host_desktop.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/browser/ui/webui/local_discovery/local_discovery_ui_handler.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/navigation_controller.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/page_transition_types.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/message_center/notifier_settings.h"

namespace local_discovery {

namespace {
const int kTenMinutesInSeconds = 600;
const char kPrivetInfoKeyUptime[] = "uptime";
const char kPrivetNotificationIDPrefix[] = "privet_notification:";
const char kPrivetNotificationOriginUrl[] = "chrome://devices";
const int kStartDelaySeconds = 5;
}

PrivetNotificationsListener::PrivetNotificationsListener(
    scoped_ptr<PrivetHTTPAsynchronousFactory> privet_http_factory,
    Delegate* delegate) : delegate_(delegate) {
  privet_http_factory_.swap(privet_http_factory);
}

PrivetNotificationsListener::~PrivetNotificationsListener() {
}

void PrivetNotificationsListener::DeviceChanged(
    bool added,
    const std::string& name,
    const DeviceDescription& description) {
  DeviceContextMap::iterator found = devices_seen_.find(name);
  if (found != devices_seen_.end()) {
    if (!description.id.empty() &&  // Device is registered
        found->second->notification_may_be_active) {
      found->second->notification_may_be_active = false;
      delegate_->PrivetRemoveNotification(name);
    }
    return;  // Already saw this device.
  }

  linked_ptr<DeviceContext> device_context(new DeviceContext);

  device_context->notification_may_be_active = false;
  device_context->registered = !description.id.empty();
  device_context->human_readable_name = description.name;
  device_context->description = description.description;

  devices_seen_.insert(make_pair(name, device_context));

  if (!device_context->registered) {
    device_context->privet_http_resolution =
        privet_http_factory_->CreatePrivetHTTP(
            name,
            description.address,
            base::Bind(&PrivetNotificationsListener::CreateInfoOperation,
                       base::Unretained(this)));

    device_context->privet_http_resolution->Start();
  }
}

void PrivetNotificationsListener::CreateInfoOperation(
    scoped_ptr<PrivetHTTPClient> http_client) {
  std::string name = http_client->GetName();
  DeviceContextMap::iterator device_iter = devices_seen_.find(name);
  DCHECK(device_iter != devices_seen_.end());
  DeviceContext* device = device_iter->second.get();
  device->privet_http.swap(http_client);
  device->info_operation =
       device->privet_http->CreateInfoOperation(this);
  device->info_operation->Start();
}

void PrivetNotificationsListener::OnPrivetInfoDone(
      PrivetInfoOperation* operation,
      int http_code,
      const base::DictionaryValue* json_value) {
  std::string name = operation->GetHTTPClient()->GetName();
  DeviceContextMap::iterator device_iter = devices_seen_.find(name);
  DCHECK(device_iter != devices_seen_.end());
  DeviceContext* device = device_iter->second.get();

  int uptime;

  if (!json_value ||
      !json_value->GetInteger(kPrivetInfoKeyUptime, &uptime) ||
      uptime > kTenMinutesInSeconds) {
    return;
  }

  DCHECK(!device->notification_may_be_active);
  device->notification_may_be_active = true;
  delegate_->PrivetNotify(name, device->human_readable_name,
                          device->description);
}

void PrivetNotificationsListener::DeviceRemoved(const std::string& name) {
  DCHECK_EQ(1u, devices_seen_.count(name));
  DeviceContextMap::iterator device_iter = devices_seen_.find(name);
  DCHECK(device_iter != devices_seen_.end());
  DeviceContext* device = device_iter->second.get();

  device->info_operation.reset();
  device->privet_http_resolution.reset();
  device->notification_may_be_active = false;
  delegate_->PrivetRemoveNotification(name);
}

void PrivetNotificationsListener::DeviceCacheFlushed() {
  for (DeviceContextMap::iterator i = devices_seen_.begin();
       i != devices_seen_.end(); ++i) {
    DeviceContext* device = i->second.get();

    device->info_operation.reset();
    device->privet_http_resolution.reset();
    if (device->notification_may_be_active) {
      device->notification_may_be_active = false;
      delegate_->PrivetRemoveNotification(i->first);
    }
  }
}

PrivetNotificationsListener::DeviceContext::DeviceContext() {
}

PrivetNotificationsListener::DeviceContext::~DeviceContext() {
}

PrivetNotificationService::PrivetNotificationService(
    content::BrowserContext* profile)
    : profile_(profile) {
  base::MessageLoop::current()->PostDelayedTask(
      FROM_HERE,
      base::Bind(&PrivetNotificationService::Start, AsWeakPtr()),
      base::TimeDelta::FromSeconds(kStartDelaySeconds +
                                   base::RandInt(0, kStartDelaySeconds/4)));
}

PrivetNotificationService::~PrivetNotificationService() {
}

void PrivetNotificationService::DeviceChanged(
    bool added,
    const std::string& name,
    const DeviceDescription& description) {
  privet_notifications_listener_->DeviceChanged(added, name, description);
}

void PrivetNotificationService::DeviceRemoved(const std::string& name) {
  privet_notifications_listener_->DeviceRemoved(name);
}

void PrivetNotificationService::DeviceCacheFlushed() {
  privet_notifications_listener_->DeviceCacheFlushed();
}

void PrivetNotificationService::PrivetNotify(
    const std::string& device_name,
    const std::string& human_readable_name,
    const std::string& description) {
  if (!LocalDiscoveryUIHandler::GetHasVisible()) {
    Profile* profile_object = Profile::FromBrowserContext(profile_);
    message_center::RichNotificationData rich_notification_data;

    rich_notification_data.buttons.push_back(
        message_center::ButtonInfo(l10n_util::GetStringUTF16(
            IDS_LOCAL_DISOCVERY_NOTIFICATION_BUTTON_PRINTER)));

    Notification notification(
        message_center::NOTIFICATION_TYPE_SIMPLE,
        GURL(kPrivetNotificationOriginUrl),
        l10n_util::GetStringUTF16(
            IDS_LOCAL_DISOCVERY_NOTIFICATION_TITLE_PRINTER),
        l10n_util::GetStringFUTF16(
            IDS_LOCAL_DISOCVERY_NOTIFICATION_CONTENTS_PRINTER,
            UTF8ToUTF16(human_readable_name)),
        ui::ResourceBundle::GetSharedInstance().GetImageNamed(
            IDR_LOCAL_DISCOVERY_CLOUDPRINT_ICON),
        WebKit::WebTextDirectionDefault,
        message_center::NotifierId(
            message_center::NotifierId::SYSTEM_COMPONENT),
        l10n_util::GetStringUTF16(
            IDS_LOCAL_DISOCVERY_NOTIFICATION_DISPLAY_SOURCE_PRINTER),
        UTF8ToUTF16(kPrivetNotificationIDPrefix +
                    device_name),
        rich_notification_data,
        new PrivetNotificationDelegate(device_name, profile_));

    g_browser_process->notification_ui_manager()->Add(notification,
                                                      profile_object);
  }
}

void PrivetNotificationService::PrivetRemoveNotification(
    const std::string& device_name) {
  g_browser_process->notification_ui_manager()->CancelById(
      kPrivetNotificationIDPrefix + device_name);
}

void PrivetNotificationService::Start() {
  traffic_detector_v4_ =
      new PrivetTrafficDetector(
          net::ADDRESS_FAMILY_IPV4,
          base::Bind(&PrivetNotificationService::StartLister, AsWeakPtr()));
  traffic_detector_v6_ =
      new PrivetTrafficDetector(
          net::ADDRESS_FAMILY_IPV6,
          base::Bind(&PrivetNotificationService::StartLister, AsWeakPtr()));
}

void PrivetNotificationService::StartLister() {
  traffic_detector_v4_ = NULL;
  traffic_detector_v6_ = NULL;
  DCHECK(!service_discovery_client_);
  service_discovery_client_ = ServiceDiscoverySharedClient::GetInstance();
  device_lister_.reset(new PrivetDeviceListerImpl(service_discovery_client_,
                                                  this));
  device_lister_->Start();

  scoped_ptr<PrivetHTTPAsynchronousFactory> http_factory(
      PrivetHTTPAsynchronousFactory::CreateInstance(
          service_discovery_client_.get(), profile_->GetRequestContext()));

  privet_notifications_listener_.reset(new PrivetNotificationsListener(
      http_factory.Pass(), this));
}

PrivetNotificationDelegate::PrivetNotificationDelegate(
    const std::string& device_id, content::BrowserContext* profile)
    : device_id_(device_id), profile_(profile) {
}

PrivetNotificationDelegate::~PrivetNotificationDelegate() {
}

std::string PrivetNotificationDelegate::id() const {
  return kPrivetNotificationIDPrefix + device_id_;
}

content::RenderViewHost* PrivetNotificationDelegate::GetRenderViewHost() const {
  return NULL;
}

void PrivetNotificationDelegate::Display() {
}

void PrivetNotificationDelegate::Error() {
  LOG(ERROR) << "Error displaying privet notification " << device_id_;
}

void PrivetNotificationDelegate::Close(bool by_user) {
}

void PrivetNotificationDelegate::Click() {
}

void PrivetNotificationDelegate::ButtonClick(int button_index) {
  if (button_index == 0) {
    // TODO(noamsml): Direct-to-register URL
    OpenTab(GURL(kPrivetNotificationOriginUrl));
  }
}

void PrivetNotificationDelegate::OpenTab(const GURL& url) {
  Profile* profile_obj = Profile::FromBrowserContext(profile_);

  Browser* browser = FindOrCreateTabbedBrowser(profile_obj,
                                               chrome::GetActiveDesktop());
  content::WebContents::CreateParams create_params(profile_obj);

  scoped_ptr<content::WebContents> contents(
      content::WebContents::Create(create_params));
  contents->GetController().LoadURL(url,
                                    content::Referrer(),
                                    content::PAGE_TRANSITION_AUTO_TOPLEVEL,
                                    "");

  browser->tab_strip_model()->AppendWebContents(contents.release(), true);
}

}  // namespace local_discovery
<commit_msg>Discover local devices when privet notification service starts for real<commit_after>// Copyright 2013 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 "chrome/browser/local_discovery/privet_notifications.h"

#include "base/bind.h"
#include "base/message_loop/message_loop.h"
#include "base/rand_util.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/local_discovery/privet_device_lister_impl.h"
#include "chrome/browser/local_discovery/privet_http_asynchronous_factory.h"
#include "chrome/browser/local_discovery/privet_traffic_detector.h"
#include "chrome/browser/local_discovery/service_discovery_shared_client.h"
#include "chrome/browser/notifications/notification.h"
#include "chrome/browser/notifications/notification_ui_manager.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/host_desktop.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/browser/ui/webui/local_discovery/local_discovery_ui_handler.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/navigation_controller.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/page_transition_types.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/message_center/notifier_settings.h"

namespace local_discovery {

namespace {
const int kTenMinutesInSeconds = 600;
const char kPrivetInfoKeyUptime[] = "uptime";
const char kPrivetNotificationIDPrefix[] = "privet_notification:";
const char kPrivetNotificationOriginUrl[] = "chrome://devices";
const int kStartDelaySeconds = 5;
}

PrivetNotificationsListener::PrivetNotificationsListener(
    scoped_ptr<PrivetHTTPAsynchronousFactory> privet_http_factory,
    Delegate* delegate) : delegate_(delegate) {
  privet_http_factory_.swap(privet_http_factory);
}

PrivetNotificationsListener::~PrivetNotificationsListener() {
}

void PrivetNotificationsListener::DeviceChanged(
    bool added,
    const std::string& name,
    const DeviceDescription& description) {
  DeviceContextMap::iterator found = devices_seen_.find(name);
  if (found != devices_seen_.end()) {
    if (!description.id.empty() &&  // Device is registered
        found->second->notification_may_be_active) {
      found->second->notification_may_be_active = false;
      delegate_->PrivetRemoveNotification(name);
    }
    return;  // Already saw this device.
  }

  linked_ptr<DeviceContext> device_context(new DeviceContext);

  device_context->notification_may_be_active = false;
  device_context->registered = !description.id.empty();
  device_context->human_readable_name = description.name;
  device_context->description = description.description;

  devices_seen_.insert(make_pair(name, device_context));

  if (!device_context->registered) {
    device_context->privet_http_resolution =
        privet_http_factory_->CreatePrivetHTTP(
            name,
            description.address,
            base::Bind(&PrivetNotificationsListener::CreateInfoOperation,
                       base::Unretained(this)));

    device_context->privet_http_resolution->Start();
  }
}

void PrivetNotificationsListener::CreateInfoOperation(
    scoped_ptr<PrivetHTTPClient> http_client) {
  std::string name = http_client->GetName();
  DeviceContextMap::iterator device_iter = devices_seen_.find(name);
  DCHECK(device_iter != devices_seen_.end());
  DeviceContext* device = device_iter->second.get();
  device->privet_http.swap(http_client);
  device->info_operation =
       device->privet_http->CreateInfoOperation(this);
  device->info_operation->Start();
}

void PrivetNotificationsListener::OnPrivetInfoDone(
      PrivetInfoOperation* operation,
      int http_code,
      const base::DictionaryValue* json_value) {
  std::string name = operation->GetHTTPClient()->GetName();
  DeviceContextMap::iterator device_iter = devices_seen_.find(name);
  DCHECK(device_iter != devices_seen_.end());
  DeviceContext* device = device_iter->second.get();

  int uptime;

  if (!json_value ||
      !json_value->GetInteger(kPrivetInfoKeyUptime, &uptime) ||
      uptime > kTenMinutesInSeconds) {
    return;
  }

  DCHECK(!device->notification_may_be_active);
  device->notification_may_be_active = true;
  delegate_->PrivetNotify(name, device->human_readable_name,
                          device->description);
}

void PrivetNotificationsListener::DeviceRemoved(const std::string& name) {
  DCHECK_EQ(1u, devices_seen_.count(name));
  DeviceContextMap::iterator device_iter = devices_seen_.find(name);
  DCHECK(device_iter != devices_seen_.end());
  DeviceContext* device = device_iter->second.get();

  device->info_operation.reset();
  device->privet_http_resolution.reset();
  device->notification_may_be_active = false;
  delegate_->PrivetRemoveNotification(name);
}

void PrivetNotificationsListener::DeviceCacheFlushed() {
  for (DeviceContextMap::iterator i = devices_seen_.begin();
       i != devices_seen_.end(); ++i) {
    DeviceContext* device = i->second.get();

    device->info_operation.reset();
    device->privet_http_resolution.reset();
    if (device->notification_may_be_active) {
      device->notification_may_be_active = false;
      delegate_->PrivetRemoveNotification(i->first);
    }
  }
}

PrivetNotificationsListener::DeviceContext::DeviceContext() {
}

PrivetNotificationsListener::DeviceContext::~DeviceContext() {
}

PrivetNotificationService::PrivetNotificationService(
    content::BrowserContext* profile)
    : profile_(profile) {
  base::MessageLoop::current()->PostDelayedTask(
      FROM_HERE,
      base::Bind(&PrivetNotificationService::Start, AsWeakPtr()),
      base::TimeDelta::FromSeconds(kStartDelaySeconds +
                                   base::RandInt(0, kStartDelaySeconds/4)));
}

PrivetNotificationService::~PrivetNotificationService() {
}

void PrivetNotificationService::DeviceChanged(
    bool added,
    const std::string& name,
    const DeviceDescription& description) {
  privet_notifications_listener_->DeviceChanged(added, name, description);
}

void PrivetNotificationService::DeviceRemoved(const std::string& name) {
  privet_notifications_listener_->DeviceRemoved(name);
}

void PrivetNotificationService::DeviceCacheFlushed() {
  privet_notifications_listener_->DeviceCacheFlushed();
}

void PrivetNotificationService::PrivetNotify(
    const std::string& device_name,
    const std::string& human_readable_name,
    const std::string& description) {
  if (!LocalDiscoveryUIHandler::GetHasVisible()) {
    Profile* profile_object = Profile::FromBrowserContext(profile_);
    message_center::RichNotificationData rich_notification_data;

    rich_notification_data.buttons.push_back(
        message_center::ButtonInfo(l10n_util::GetStringUTF16(
            IDS_LOCAL_DISOCVERY_NOTIFICATION_BUTTON_PRINTER)));

    Notification notification(
        message_center::NOTIFICATION_TYPE_SIMPLE,
        GURL(kPrivetNotificationOriginUrl),
        l10n_util::GetStringUTF16(
            IDS_LOCAL_DISOCVERY_NOTIFICATION_TITLE_PRINTER),
        l10n_util::GetStringFUTF16(
            IDS_LOCAL_DISOCVERY_NOTIFICATION_CONTENTS_PRINTER,
            UTF8ToUTF16(human_readable_name)),
        ui::ResourceBundle::GetSharedInstance().GetImageNamed(
            IDR_LOCAL_DISCOVERY_CLOUDPRINT_ICON),
        WebKit::WebTextDirectionDefault,
        message_center::NotifierId(
            message_center::NotifierId::SYSTEM_COMPONENT),
        l10n_util::GetStringUTF16(
            IDS_LOCAL_DISOCVERY_NOTIFICATION_DISPLAY_SOURCE_PRINTER),
        UTF8ToUTF16(kPrivetNotificationIDPrefix +
                    device_name),
        rich_notification_data,
        new PrivetNotificationDelegate(device_name, profile_));

    g_browser_process->notification_ui_manager()->Add(notification,
                                                      profile_object);
  }
}

void PrivetNotificationService::PrivetRemoveNotification(
    const std::string& device_name) {
  g_browser_process->notification_ui_manager()->CancelById(
      kPrivetNotificationIDPrefix + device_name);
}

void PrivetNotificationService::Start() {
  traffic_detector_v4_ =
      new PrivetTrafficDetector(
          net::ADDRESS_FAMILY_IPV4,
          base::Bind(&PrivetNotificationService::StartLister, AsWeakPtr()));
  traffic_detector_v6_ =
      new PrivetTrafficDetector(
          net::ADDRESS_FAMILY_IPV6,
          base::Bind(&PrivetNotificationService::StartLister, AsWeakPtr()));
}

void PrivetNotificationService::StartLister() {
  traffic_detector_v4_ = NULL;
  traffic_detector_v6_ = NULL;
  DCHECK(!service_discovery_client_);
  service_discovery_client_ = ServiceDiscoverySharedClient::GetInstance();
  device_lister_.reset(new PrivetDeviceListerImpl(service_discovery_client_,
                                                  this));
  device_lister_->Start();
  device_lister_->DiscoverNewDevices(false);

  scoped_ptr<PrivetHTTPAsynchronousFactory> http_factory(
      PrivetHTTPAsynchronousFactory::CreateInstance(
          service_discovery_client_.get(), profile_->GetRequestContext()));

  privet_notifications_listener_.reset(new PrivetNotificationsListener(
      http_factory.Pass(), this));
}

PrivetNotificationDelegate::PrivetNotificationDelegate(
    const std::string& device_id, content::BrowserContext* profile)
    : device_id_(device_id), profile_(profile) {
}

PrivetNotificationDelegate::~PrivetNotificationDelegate() {
}

std::string PrivetNotificationDelegate::id() const {
  return kPrivetNotificationIDPrefix + device_id_;
}

content::RenderViewHost* PrivetNotificationDelegate::GetRenderViewHost() const {
  return NULL;
}

void PrivetNotificationDelegate::Display() {
}

void PrivetNotificationDelegate::Error() {
  LOG(ERROR) << "Error displaying privet notification " << device_id_;
}

void PrivetNotificationDelegate::Close(bool by_user) {
}

void PrivetNotificationDelegate::Click() {
}

void PrivetNotificationDelegate::ButtonClick(int button_index) {
  if (button_index == 0) {
    // TODO(noamsml): Direct-to-register URL
    OpenTab(GURL(kPrivetNotificationOriginUrl));
  }
}

void PrivetNotificationDelegate::OpenTab(const GURL& url) {
  Profile* profile_obj = Profile::FromBrowserContext(profile_);

  Browser* browser = FindOrCreateTabbedBrowser(profile_obj,
                                               chrome::GetActiveDesktop());
  content::WebContents::CreateParams create_params(profile_obj);

  scoped_ptr<content::WebContents> contents(
      content::WebContents::Create(create_params));
  contents->GetController().LoadURL(url,
                                    content::Referrer(),
                                    content::PAGE_TRANSITION_AUTO_TOPLEVEL,
                                    "");

  browser->tab_strip_model()->AppendWebContents(contents.release(), true);
}

}  // namespace local_discovery
<|endoftext|>


<commit_before>// Integration test for Blinky class.
// The test node implements a mock Blinky actionlib server, which we test
// against when using the Blinky class.

#include "rapid/display/display.h"

#include <string>
#include <vector>

#include "actionlib/server/simple_action_server.h"
#include "blinky/FaceAction.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "ros/ros.h"

using ::testing::Pointwise;
using ::testing::Eq;
using actionlib::SimpleActionServer;
using blinky::FaceAction;
using blinky::FaceGoal;
using blinky::FaceGoalConstPtr;
using blinky::FaceResult;

namespace rapid {
namespace display {

class MockBlinkyServer {
 public:
  MockBlinkyServer()
      : nh_(),
        server_(nh_, "blinky",
                boost::bind(&MockBlinkyServer::ExecuteCb, this, _1), false),
        last_goal_() {}
  void Start() { server_.start(); }

  // Processes all available callbacks, and gets the most recent goal that was
  // processed. If you are testing with the MockBlinkyServer, you are guaranteed
  // that the execute callback was processed after calling this method.
  //
  // See roscpp documentation on callbacks and spinning.
  FaceGoal WaitForGoal() {
    ros::getGlobalCallbackQueue()->callAvailable(ros::WallDuration(0.1));
    return last_goal_;
  }

 protected:
  void ExecuteCb(const FaceGoalConstPtr& goal) {
    last_goal_ = *goal;
    FaceResult result;
    if (goal->display_type == FaceGoal::ASK_CHOICE) {
      result.choice = goal->choices[0];
    }
    server_.setSucceeded(result);
  }
  ros::NodeHandle nh_;
  SimpleActionServer<FaceAction> server_;
  FaceGoal last_goal_;
};

class BlinkyTest : public ::testing::Test {
 public:
  // We have a long server wait time to make sure the test isn't flaky.
  BlinkyTest() : node_handle_(), server_(), blinky_(30) {}

  void SetUp() {}

 protected:
  ros::NodeHandle node_handle_;
  MockBlinkyServer server_;
  Blinky blinky_;
};

TEST_F(BlinkyTest, ShowDefault) {
  server_.Start();
  bool success = blinky_.ShowDefault();
  FaceGoal goal = server_.WaitForGoal();
  EXPECT_EQ(true, success);
  EXPECT_EQ(FaceGoal::DEFAULT, goal.display_type);
}

TEST_F(BlinkyTest, ShouldFailIfServerNotStarted) {
  // By not calling server_.Start(), the action server should not exist.
  bool success = blinky_.ShowDefault();
  FaceGoal goal = server_.WaitForGoal();
  EXPECT_EQ(false, success);
}

TEST_F(BlinkyTest, ShowMessage) {
  server_.Start();
  bool success = blinky_.ShowMessage("Hello world!", "I'm ready to help.");
  FaceGoal goal = server_.WaitForGoal();
  EXPECT_EQ(FaceGoal::DISPLAY_MESSAGE, goal.display_type);
  EXPECT_EQ("Hello world!", goal.h1_text);
  EXPECT_EQ("I'm ready to help.", goal.h2_text);
  EXPECT_EQ(true, success);
}

TEST_F(BlinkyTest, AskMultipleChoice) {
  server_.Start();
  std::vector<std::string> choices;
  choices.push_back("Indigo");
  choices.push_back("Jade");
  std::string choice;
  bool success = blinky_.AskMultipleChoice("What's your favorite color?",
                                           choices, &choice);
  EXPECT_EQ(true, success);
  EXPECT_EQ("Indigo", choice);
  FaceGoal goal = server_.WaitForGoal();
  EXPECT_EQ(true, success);
  EXPECT_EQ(FaceGoal::ASK_CHOICE, goal.display_type);
  EXPECT_THAT(goal.choices, Eq(choices));
}
}  // namespace display
}  // namespace rapid

int main(int argc, char** argv) {
  testing::InitGoogleTest(&argc, argv);
  ros::init(argc, argv, "blinky_test");

  ros::AsyncSpinner spinner(1);
  spinner.start();
  int ret = RUN_ALL_TESTS();
  spinner.stop();
  ros::shutdown();
  return ret;
}
<commit_msg>Try using a multi-threaded spinner in case waitForServer doesn't work.<commit_after>// Integration test for Blinky class.
// The test node implements a mock Blinky actionlib server, which we test
// against when using the Blinky class.

#include "rapid/display/display.h"

#include <string>
#include <vector>

#include "actionlib/server/simple_action_server.h"
#include "blinky/FaceAction.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "ros/ros.h"

using ::testing::Pointwise;
using ::testing::Eq;
using actionlib::SimpleActionServer;
using blinky::FaceAction;
using blinky::FaceGoal;
using blinky::FaceGoalConstPtr;
using blinky::FaceResult;

namespace rapid {
namespace display {

class MockBlinkyServer {
 public:
  MockBlinkyServer()
      : nh_(),
        server_(nh_, "blinky",
                boost::bind(&MockBlinkyServer::ExecuteCb, this, _1), false),
        last_goal_() {}
  void Start() { server_.start(); }

  // Processes all available callbacks, and gets the most recent goal that was
  // processed. If you are testing with the MockBlinkyServer, you are guaranteed
  // that the execute callback was processed after calling this method.
  //
  // See roscpp documentation on callbacks and spinning.
  FaceGoal WaitForGoal() {
    ros::getGlobalCallbackQueue()->callAvailable(ros::WallDuration(0.1));
    return last_goal_;
  }

 protected:
  void ExecuteCb(const FaceGoalConstPtr& goal) {
    last_goal_ = *goal;
    FaceResult result;
    if (goal->display_type == FaceGoal::ASK_CHOICE) {
      result.choice = goal->choices[0];
    }
    server_.setSucceeded(result);
  }
  ros::NodeHandle nh_;
  SimpleActionServer<FaceAction> server_;
  FaceGoal last_goal_;
};

class BlinkyTest : public ::testing::Test {
 public:
  // We have a long server wait time to make sure the test isn't flaky.
  BlinkyTest() : node_handle_(), server_(), blinky_(30) {}

  void SetUp() {}

 protected:
  ros::NodeHandle node_handle_;
  MockBlinkyServer server_;
  Blinky blinky_;
};

TEST_F(BlinkyTest, ShowDefault) {
  server_.Start();
  bool success = blinky_.ShowDefault();
  FaceGoal goal = server_.WaitForGoal();
  EXPECT_EQ(true, success);
  EXPECT_EQ(FaceGoal::DEFAULT, goal.display_type);
}

TEST_F(BlinkyTest, ShouldFailIfServerNotStarted) {
  // By not calling server_.Start(), the action server should not exist.
  bool success = blinky_.ShowDefault();
  FaceGoal goal = server_.WaitForGoal();
  EXPECT_EQ(false, success);
}

TEST_F(BlinkyTest, ShowMessage) {
  server_.Start();
  bool success = blinky_.ShowMessage("Hello world!", "I'm ready to help.");
  FaceGoal goal = server_.WaitForGoal();
  EXPECT_EQ(FaceGoal::DISPLAY_MESSAGE, goal.display_type);
  EXPECT_EQ("Hello world!", goal.h1_text);
  EXPECT_EQ("I'm ready to help.", goal.h2_text);
  EXPECT_EQ(true, success);
}

TEST_F(BlinkyTest, AskMultipleChoice) {
  server_.Start();
  std::vector<std::string> choices;
  choices.push_back("Indigo");
  choices.push_back("Jade");
  std::string choice;
  bool success = blinky_.AskMultipleChoice("What's your favorite color?",
                                           choices, &choice);
  EXPECT_EQ(true, success);
  EXPECT_EQ("Indigo", choice);
  FaceGoal goal = server_.WaitForGoal();
  EXPECT_EQ(true, success);
  EXPECT_EQ(FaceGoal::ASK_CHOICE, goal.display_type);
  EXPECT_THAT(goal.choices, Eq(choices));
}
}  // namespace display
}  // namespace rapid

int main(int argc, char** argv) {
  testing::InitGoogleTest(&argc, argv);
  ros::init(argc, argv, "blinky_test");

  ros::AsyncSpinner spinner(2);
  spinner.start();
  int ret = RUN_ALL_TESTS();
  spinner.stop();
  ros::shutdown();
  return ret;
}
<|endoftext|>


<commit_before>#pragma once

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

#include <upl/common.hpp>
#include <upl/errors.hpp>
#include <upl/input.hpp>
#include <upl/tokens.hpp>

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

namespace UPL {

//======================================================================
//----------------------------------------------------------------------
//======================================================================

class Lexer
{
public:
	explicit Lexer (InputStream & input, Error::Reporter & reporter);

	bool eoi () const {return m_cur_tok.is(TT::EOI);}
	bool error () const {return m_has_error;}

	Token const & curr () const {return m_cur_tok;}

	bool pop ();

private:
	InputStream & m_input;
	Error::Reporter & m_reporter;
	Token m_cur_tok;
	bool m_has_error;
	Char m_current_char;
	Location m_current_location;

	bool consume_whitespace();
	bool consume_comment();
	bool pop_name();
	bool pop_bool_literal();
	bool pop_numeric_literal();
	bool pop_string_literal();
	bool pop_separator_or_operator();

	bool has_more_input();
	Char current_char();
	Location current_location();
	void ensure_current_char();
	void consume_one_char();
};

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

}	// namespace UPL

//======================================================================
<commit_msg>Moved private methods to before private data members in UPL::Lexer declaration.<commit_after>#pragma once

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

#include <upl/common.hpp>
#include <upl/errors.hpp>
#include <upl/input.hpp>
#include <upl/tokens.hpp>

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

namespace UPL {

//======================================================================
//----------------------------------------------------------------------
//======================================================================

class Lexer
{
public:
	explicit Lexer (InputStream & input, Error::Reporter & reporter);

	bool eoi () const {return m_cur_tok.is(TT::EOI);}
	bool error () const {return m_has_error;}

	Token const & curr () const {return m_cur_tok;}

	bool pop ();

private:
	bool consume_whitespace();
	bool consume_comment();
	bool pop_name();
	bool pop_bool_literal();
	bool pop_numeric_literal();
	bool pop_string_literal();
	bool pop_separator_or_operator();

	bool has_more_input();
	Char current_char();
	Location current_location();
	void ensure_current_char();
	void consume_one_char();

private:
	InputStream & m_input;
	Error::Reporter & m_reporter;
	Token m_cur_tok;
	bool m_has_error;
	Char m_current_char;
	Location m_current_location;
};

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

}	// namespace UPL

//======================================================================
<|endoftext|>


<commit_before>//============================================================================
// include/vsmc/vsmc.hpp
//----------------------------------------------------------------------------
//
//                         vSMC: Scalable Monte Carlo
//
// This file is distribured under the 2-clauses BSD License.
// See LICENSE for details.
//============================================================================

#ifndef VSMC_HPP
#define VSMC_HPP

/// \defgroup Config Configuration
/// \brief Configuration macros and default values if undefined

/// \defgroup Definitions Enumerators, placeholders and macros
/// \brief Enumerator, placeholder and macro definitions

/// \defgroup Traits Traits
/// \brief Trait classes

/// \defgroup Core Core
/// \brief Constructing samplers with operations on the whole particle set

/// \defgroup Dispatch Grand Central Dispatch
/// \brief C++ wrapper of Apple GCD

/// \defgroup Resample Resampling algorithms
/// \brief Resampling algorithm functor classes

/// \defgroup Adapter Adapter
/// \brief Adapter class templates for constructing concrete objects

/// \defgroup Integrate Integration
/// \brief Numerical integration

/// \defgroup MPI Message Passing Interface
/// \brief Parallel samplers using MPI

/// \defgroup OpenCL OpenCL
/// \brief Parallel sampler using OpenCL

/// \defgroup SMP Symmetric Multiprocessing
/// \brief Parallel samplers using multi-threading on SMP architecture

/// \defgroup CILK Intel Cilk Plus
/// \ingroup SMP
/// \brief Parallel samplers using Intel Cilk Plus

/// \defgroup GCD Grand Central Dispatch
/// \ingroup SMP
/// \brief Parallel samplers using Apple GCD

/// \defgroup OMP OpenMP
/// \ingroup SMP
/// \brief Parallel samplers using OpenMP

/// \defgroup PPL Parallel Pattern Library
/// \ingroup SMP
/// \brief Parallel samplers using Microsoft PPL

/// \defgroup SEQ Sequential
/// \ingroup SMP
/// \brief Sequential samplers

/// \defgroup STD C++11 concurrency
/// \ingroup SMP
/// \brief Parallel samplers using C++11 concurrency

/// \defgroup TBB Intel Threading Building Blocks
/// \ingroup SMP
/// \brief Parallel samplers using Intel TBB

/// \defgroup Math Mathematics
/// \brief Mathematical utilities

/// \defgroup CBLAS C BLAS
/// \brief Selected C BLAS like routines

/// \defgroup Constants Constants
/// \ingroup Math
/// \brief Mathematical constants

/// \defgroup vMath Vector math functions
/// \ingroup Math
/// \brief Math functions on vectors (optional optimization through Intel MKL)

/// \defgroup RNG Random number generating
/// \brief Random number generating engines and utilities

/// \defgroup AESNIRNG AES-NI
/// \ingroup RNG
/// \brief Random number generating using AES-NI

/// \defgroup CLRNG OpenCL
/// \ingroup RNG
/// \brief Random number generating in OpenCL kernels

/// \defgroup Distribution Distribution
/// \ingroup RNG
/// \brief Distribution random varaites

/// \defgroup GSLRNG GSL
/// \ingroup RNG
/// \brief Random number generating using GSL RNG

/// \defgroup MKLRNG MKL
/// \ingroup RNG
/// \brief Random number generating using MKL RNG

/// \defgroup R123RNG Random123
/// \ingroup RNG
/// \brief Random number generating using Random123 RNG

/// \defgroup RDRNG Intel DRNG
/// \ingroup RNG
/// \brief Random number generating using Intel RDRAND instructions

/// \defgroup RNGWrapper Wrapper
/// \ingroup RNG
/// \brief C++11 RNG engines that wrap other RNG generators

/// \defgroup U01 U01
/// \ingroup RNG
/// \brief Converting random integers to random floating points

/// \defgroup Xorshift Xorshift
/// \ingroup RNG
/// \brief Random number generating using the Xorshift algorithm

/// \defgroup Thread Thread
/// \brief C++11 threading support

/// \defgroup Utility Utility
/// \brief Utilities independent of other part of the library

/// \defgroup Array Array
/// \ingroup Utility
/// \brief Container with static size

/// \defgroup AVector AVector
/// \ingroup Utility
/// \brief Container for arithmetic types with aligned memory allocation

/// \defgroup CPUID CPUID
/// \ingroup Utility
/// \brief Query CPUID information

/// \defgroup Counter Counter
/// \ingroup Utility
/// \brief Using Array of unsinged integers as counters

/// \defgroup HDF5IO HDF5 objects saving
/// \ingroup Utility
/// \brief Functions for saving objects in HDF5 format

/// \defgroup Option Program option
/// \ingroup Utility
/// \brief Process program command line options

/// \defgroup Progress Progress
/// \ingroup Utility
/// \brief Display progress while algorithms proceed

/// \defgroup RDTSC RDTSC
/// \ingroup Utility
/// \brief CPU clock cycles count using RDTSC and RDTSCP

/// \defgroup StopWatch Stop watch
/// \ingroup Utility
/// \brief Utilities for measuring the time of procedures

#include <vsmc/internal/config.hpp>

#include <vsmc/core/monitor.hpp>
#include <vsmc/core/normalizing_constant.hpp>
#include <vsmc/core/particle.hpp>
#include <vsmc/core/path.hpp>
#include <vsmc/core/sampler.hpp>
#include <vsmc/core/single_particle.hpp>
#include <vsmc/core/state_matrix.hpp>
#include <vsmc/core/weight_set.hpp>

#include <vsmc/cxx11/cmath.hpp>
#include <vsmc/cxx11/functional.hpp>
#include <vsmc/cxx11/random.hpp>
#include <vsmc/cxx11/type_traits.hpp>

#include <vsmc/utility/program_option.hpp>
#include <vsmc/utility/stop_watch.hpp>

#endif // VSMC_HPP
<commit_msg>remove unused doc group<commit_after>//============================================================================
// include/vsmc/vsmc.hpp
//----------------------------------------------------------------------------
//
//                         vSMC: Scalable Monte Carlo
//
// This file is distribured under the 2-clauses BSD License.
// See LICENSE for details.
//============================================================================

#ifndef VSMC_HPP
#define VSMC_HPP

/// \defgroup Config Configuration
/// \brief Configuration macros and default values if undefined

/// \defgroup Definitions Enumerators, placeholders and macros
/// \brief Enumerator, placeholder and macro definitions

/// \defgroup Traits Traits
/// \brief Trait classes

/// \defgroup Core Core
/// \brief Constructing samplers with operations on the whole particle set

/// \defgroup Dispatch Grand Central Dispatch
/// \brief C++ wrapper of Apple GCD

/// \defgroup Resample Resampling algorithms
/// \brief Resampling algorithm functor classes

/// \defgroup Adapter Adapter
/// \brief Adapter class templates for constructing concrete objects

/// \defgroup Integrate Integration
/// \brief Numerical integration

/// \defgroup MPI Message Passing Interface
/// \brief Parallel samplers using MPI

/// \defgroup OpenCL OpenCL
/// \brief Parallel sampler using OpenCL

/// \defgroup SMP Symmetric Multiprocessing
/// \brief Parallel samplers using multi-threading on SMP architecture

/// \defgroup CILK Intel Cilk Plus
/// \ingroup SMP
/// \brief Parallel samplers using Intel Cilk Plus

/// \defgroup GCD Grand Central Dispatch
/// \ingroup SMP
/// \brief Parallel samplers using Apple GCD

/// \defgroup OMP OpenMP
/// \ingroup SMP
/// \brief Parallel samplers using OpenMP

/// \defgroup PPL Parallel Pattern Library
/// \ingroup SMP
/// \brief Parallel samplers using Microsoft PPL

/// \defgroup SEQ Sequential
/// \ingroup SMP
/// \brief Sequential samplers

/// \defgroup STD C++11 concurrency
/// \ingroup SMP
/// \brief Parallel samplers using C++11 concurrency

/// \defgroup TBB Intel Threading Building Blocks
/// \ingroup SMP
/// \brief Parallel samplers using Intel TBB

/// \defgroup Math Mathematics
/// \brief Mathematical utilities

/// \defgroup CBLAS C BLAS
/// \brief Selected C BLAS like routines

/// \defgroup Constants Constants
/// \ingroup Math
/// \brief Mathematical constants

/// \defgroup vMath Vector math functions
/// \ingroup Math
/// \brief Math functions on vectors (optional optimization through Intel MKL)

/// \defgroup RNG Random number generating
/// \brief Random number generating engines and utilities

/// \defgroup AESNIRNG AES-NI
/// \ingroup RNG
/// \brief Random number generating using AES-NI

/// \defgroup CLRNG OpenCL
/// \ingroup RNG
/// \brief Random number generating in OpenCL kernels

/// \defgroup Distribution Distribution
/// \ingroup RNG
/// \brief Distribution random varaites

/// \defgroup GSLRNG GSL
/// \ingroup RNG
/// \brief Random number generating using GSL RNG

/// \defgroup MKLRNG MKL
/// \ingroup RNG
/// \brief Random number generating using MKL RNG

/// \defgroup R123RNG Random123
/// \ingroup RNG
/// \brief Random number generating using Random123 RNG

/// \defgroup RDRNG Intel DRNG
/// \ingroup RNG
/// \brief Random number generating using Intel RDRAND instructions

/// \defgroup RNGWrapper Wrapper
/// \ingroup RNG
/// \brief C++11 RNG engines that wrap other RNG generators

/// \defgroup U01 U01
/// \ingroup RNG
/// \brief Converting random integers to random floating points

/// \defgroup Xorshift Xorshift
/// \ingroup RNG
/// \brief Random number generating using the Xorshift algorithm

/// \defgroup Thread Thread
/// \brief C++11 threading support

/// \defgroup Utility Utility
/// \brief Utilities independent of other part of the library

/// \defgroup Array Array
/// \ingroup Utility
/// \brief Container with static size

/// \defgroup CPUID CPUID
/// \ingroup Utility
/// \brief Query CPUID information

/// \defgroup Counter Counter
/// \ingroup Utility
/// \brief Using Array of unsinged integers as counters

/// \defgroup HDF5IO HDF5 objects saving
/// \ingroup Utility
/// \brief Functions for saving objects in HDF5 format

/// \defgroup Option Program option
/// \ingroup Utility
/// \brief Process program command line options

/// \defgroup Progress Progress
/// \ingroup Utility
/// \brief Display progress while algorithms proceed

/// \defgroup RDTSC RDTSC
/// \ingroup Utility
/// \brief CPU clock cycles count using RDTSC and RDTSCP

/// \defgroup StopWatch Stop watch
/// \ingroup Utility
/// \brief Utilities for measuring the time of procedures

#include <vsmc/internal/config.hpp>

#include <vsmc/core/monitor.hpp>
#include <vsmc/core/normalizing_constant.hpp>
#include <vsmc/core/particle.hpp>
#include <vsmc/core/path.hpp>
#include <vsmc/core/sampler.hpp>
#include <vsmc/core/single_particle.hpp>
#include <vsmc/core/state_matrix.hpp>
#include <vsmc/core/weight_set.hpp>

#include <vsmc/cxx11/cmath.hpp>
#include <vsmc/cxx11/functional.hpp>
#include <vsmc/cxx11/random.hpp>
#include <vsmc/cxx11/type_traits.hpp>

#include <vsmc/utility/program_option.hpp>
#include <vsmc/utility/stop_watch.hpp>

#endif // VSMC_HPP
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- vim:set ts=4 sw=4 sts=4 noet: */
#ifndef FLINT_LAYOUT_GENERATE_HH_
#define FLINT_LAYOUT_GENERATE_HH_

#include "sqlite3.h"

namespace flint {
namespace layout {

/*
 * Return true in case of success, otherwise false.
 */
bool Generate(sqlite3 *db, const char *filename);

}
}

#endif
<commit_msg>Fix #include guard<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- vim:set ts=4 sw=4 sts=4 noet: */
#ifndef FLINT_LAYOUT_HH_
#define FLINT_LAYOUT_HH_

#include "sqlite3.h"

namespace flint {
namespace layout {

/*
 * Return true in case of success, otherwise false.
 */
bool Generate(sqlite3 *db, const char *filename);

}
}

#endif
<|endoftext|>


<commit_before>#include "lexer.h"

#include <string>

#include "lexerexception.h"
#include "log.h"
#include "scriptsource.h"
#include "token.h"

namespace peachy {

  Lexer::~Lexer() {
    logger->debug("Lexer destructor");
  }

  Token * Lexer::nextToken() {
    logger->debug("Lexer::nextToken()");

    Token * token;
    bool gotToken = false;

    while(!gotToken) {
      currentChar = currentLine[currentPos];
      switch(state) {
        case LEXER_COMPLETE:
	  logger->debug("In state LEXER_COMPLETE");
	  token = new Token(logger, TOKEN_EOF);
	  resetToken();
	  gotToken = true;
          break;
        case LEXER_DEFAULT:
          logger->debug("In state LEXER_DEFAULT");
          switch(currentChar) {
	    case ' ':
	    case '\t':
	      logger->debug("Whitespace");
	      consume(false);
	      break;
	    case '\n':
	    case '\r':
	    case NULL:
	      logger->debug("End of line");
	      resetLine();
	      break;
            default:
	      if(isNumeric(currentChar)) {
                logger->debug("Current char is a number");
		setState(LEXER_IN_NUMBER);
		consume(true);
	      } else if(isLetter(currentChar)) {
	        logger->debug("Current char is a letter");
                setState(LEXER_IN_IDENTIFIER);
                consume(true);
              } else if(isOperator(currentChar)) {
	        logger->debug("Current char is an operator");
		setState(LEXER_IN_OPERATOR);
		consume(true);
	      } else {
                throw LexerException(
		  std::string("Invalid character encountered: ").append(
		    1, currentChar));
	      }
	      break;
	  }
          break;
	case LEXER_IN_NUMBER:
	  logger->debug("In state LEXER_IN_NUMBER");
	  if(isNumeric(currentChar)) {
            logger->debug("Another digit of the current number");
	    consume(true);
	  } else {
            logger->debug("End of number");
            token = new Token(logger, TOKEN_NUMBER, currentSequence);
	    resetToken();
            gotToken = true;
	  }
	  break;
	case LEXER_IN_IDENTIFIER:
	  logger->debug("In state LEXER_IN_IDENTIFIER");
	  if(isIdentifier(currentChar)) {
            logger->debug("Another character of the current identifier");
	    consume(true);
	  } else {
            logger->debug("End of identifier");
	    if(isKeyword(currentSequence)) {
              token = new Token(logger, TOKEN_KEYWORD, currentSequence);
	    } else {
	      token = new Token(logger, TOKEN_IDENTIFIER, currentSequence);
	    }
	    resetToken();
	    gotToken = true;
	  }
	  break;
	case LEXER_IN_OPERATOR:
	  logger->debug("In state LEXER_IN_OPERATOR");
	  if(isOperator(currentChar)) {
            logger->debug("Another character of the current operator");
	    consume(true);
	  } else if(isNumeric(currentChar) &&
	          currentSequence.compare("-") == 0) {
            logger->debug("Looks like a negative number");
	    setState(LEXER_IN_NUMBER);
	    consume(true);
	  } else {
            logger->debug("End of operator");
	    token = new Token(logger, TOKEN_OPERATOR, currentSequence);
	    resetToken();
	    gotToken = true;
	  }
	  break;
        case LEXER_NEED_INPUT:
          logger->debug("In state LEXER_NEED_INPUT");
	  if(!scriptSource->hasMoreLines()) {
            logger->debug("End of input");
	    setState(LEXER_COMPLETE);
	  } else {
            setCurrentLine(scriptSource->getLine());
	    logger->debug("Got new line from script source");
	    resetToken();
	  }
          break;
	case LEXER_ERROR:
          logger->debug("In state LEXER_ERROR");
	  throw LexerException("Invalid lexer state");
          break;
	default:
          logger->debug("In an unknown state");
          setState(LEXER_ERROR);
          break;
      }
    }

    return token;
  }

  void Lexer::consume(bool appendChar) {
    logger->debug("Lexer::consume()");
    if(appendChar) {
      currentSequence.append(1, currentChar);
    }
    currentPos++;
  }

  void Lexer::resetLine() {
    logger->debug("Lexer::resetLine()");
    setState(LEXER_NEED_INPUT);
    currentPos = 0;
  }

  void Lexer::resetToken() {
    logger->debug("Lexer::resetToken()");
    setState(LEXER_DEFAULT);
    currentSequence = std::string("");
  }

  void Lexer::setState(LexerState state) {
    logger->debug("Lexer::setState()");
    this->state = state;
  }

  void Lexer::setCurrentLine(std::string line) {
    logger->debug("Lexer::setCurrentLine()");
    this->currentLine = line;
  }

  LexerState Lexer::getState() {
    logger->debug("Lexer::getState()");
    return this->state;
  }

  bool Lexer::isNumeric(char c) {
    return (
      c >= '0' &&
      c <= '9'
    );
  }

  bool Lexer::isLetter(char c) {
    return (
      ( c >= 'a' && c <= 'z' ) ||
      ( c >= 'A' && c <= 'Z' )
    );
  }

  bool Lexer::isOperator(char c) {
    return (
      c == '=' ||
      c == '-' ||
      c == '+'
    );
  }

  bool Lexer::isIdentifier(char c) {
    return (
      isLetter(c) ||
      isNumeric(c)
    );
  }

  bool Lexer::isKeyword(std::string s) {
    return (
      s.compare("class") == 0 ||
      s.compare("function") == 0
    );
  }
}

<commit_msg>sort out indentation<commit_after>#include "lexer.h"

#include <string>

#include "lexerexception.h"
#include "log.h"
#include "scriptsource.h"
#include "token.h"

namespace peachy {

  Lexer::~Lexer() {
    logger->debug("Lexer destructor");
  }

  Token * Lexer::nextToken() {
    logger->debug("Lexer::nextToken()");

    Token * token;
    bool gotToken = false;

    while(!gotToken) {
      currentChar = currentLine[currentPos];
      switch(state) {
        case LEXER_COMPLETE:
          logger->debug("In state LEXER_COMPLETE");
          token = new Token(logger, TOKEN_EOF);
          resetToken();
          gotToken = true;
          break;
        case LEXER_DEFAULT:
          logger->debug("In state LEXER_DEFAULT");
          switch(currentChar) {
            case ' ':
            case '\t':
              logger->debug("Whitespace");
              consume(false);
              break;
            case '\n':
            case '\r':
            case NULL:
              logger->debug("End of line");
              resetLine();
              break;
            default:
              if(isNumeric(currentChar)) {
                logger->debug("Current char is a number");
                setState(LEXER_IN_NUMBER);
                consume(true);
              } else if(isLetter(currentChar)) {
                logger->debug("Current char is a letter");
                setState(LEXER_IN_IDENTIFIER);
                consume(true);
              } else if(isOperator(currentChar)) {
                logger->debug("Current char is an operator");
                setState(LEXER_IN_OPERATOR);
                consume(true);
              } else {
                throw LexerException(
                  std::string("Invalid character encountered: ").append(
                    1, currentChar));
              }
              break;
          }
          break;
        case LEXER_IN_NUMBER:
          logger->debug("In state LEXER_IN_NUMBER");
          if(isNumeric(currentChar)) {
            logger->debug("Another digit of the current number");
            consume(true);
          } else {
            logger->debug("End of number");
            token = new Token(logger, TOKEN_NUMBER, currentSequence);
            resetToken();
            gotToken = true;
          }
          break;
        case LEXER_IN_IDENTIFIER:
          logger->debug("In state LEXER_IN_IDENTIFIER");
          if(isIdentifier(currentChar)) {
            logger->debug("Another character of the current identifier");
            consume(true);
          } else {
            logger->debug("End of identifier");
            if(isKeyword(currentSequence)) {
              token = new Token(logger, TOKEN_KEYWORD, currentSequence);
            } else {
              token = new Token(logger, TOKEN_IDENTIFIER, currentSequence);
            }
            resetToken();
            gotToken = true;
          }
          break;
        case LEXER_IN_OPERATOR:
          logger->debug("In state LEXER_IN_OPERATOR");
          if(isOperator(currentChar)) {
            logger->debug("Another character of the current operator");
            consume(true);
          } else if(isNumeric(currentChar) &&
            currentSequence.compare("-") == 0) {
            logger->debug("Looks like a negative number");
            setState(LEXER_IN_NUMBER);
            consume(true);
          } else {
            logger->debug("End of operator");
            token = new Token(logger, TOKEN_OPERATOR, currentSequence);
            resetToken();
            gotToken = true;
          }
          break;
        case LEXER_NEED_INPUT:
          logger->debug("In state LEXER_NEED_INPUT");
          if(!scriptSource->hasMoreLines()) {
            logger->debug("End of input");
            setState(LEXER_COMPLETE);
          } else {
            setCurrentLine(scriptSource->getLine());
            logger->debug("Got new line from script source");
            resetToken();
          }
          break;
        case LEXER_ERROR:
          logger->debug("In state LEXER_ERROR");
          throw LexerException("Invalid lexer state");
          break;
        default:
          logger->debug("In an unknown state");
          setState(LEXER_ERROR);
          break;
      }
    }

    return token;
  }

  void Lexer::consume(bool appendChar) {
    logger->debug("Lexer::consume()");
    if(appendChar) {
      currentSequence.append(1, currentChar);
    }
    currentPos++;
  }

  void Lexer::resetLine() {
    logger->debug("Lexer::resetLine()");
    setState(LEXER_NEED_INPUT);
    currentPos = 0;
  }

  void Lexer::resetToken() {
    logger->debug("Lexer::resetToken()");
    setState(LEXER_DEFAULT);
    currentSequence = std::string("");
  }

  void Lexer::setState(LexerState state) {
    logger->debug("Lexer::setState()");
    this->state = state;
  }

  void Lexer::setCurrentLine(std::string line) {
    logger->debug("Lexer::setCurrentLine()");
    this->currentLine = line;
  }

  LexerState Lexer::getState() {
    logger->debug("Lexer::getState()");
    return this->state;
  }

  bool Lexer::isNumeric(char c) {
    return (
      c >= '0' &&
      c <= '9'
    );
  }

  bool Lexer::isLetter(char c) {
    return (
      ( c >= 'a' && c <= 'z' ) ||
      ( c >= 'A' && c <= 'Z' )
    );
  }

  bool Lexer::isOperator(char c) {
    return (
      c == '=' ||
      c == '-' ||
      c == '+'
    );
  }

  bool Lexer::isIdentifier(char c) {
    return (
      isLetter(c) ||
      isNumeric(c)
    );
  }

  bool Lexer::isKeyword(std::string s) {
    return (
      s.compare("class") == 0 ||
      s.compare("function") == 0
    );
  }
}

<|endoftext|>


<commit_before>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**
 * CONDOR Copyright Notice
 *
 * See LICENSE.TXT for additional notices and disclaimers.
 *
 * Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department,
 * University of Wisconsin-Madison, Madison, WI.  All Rights Reserved.
 * No use of the CONDOR Software Program Source Code is authorized
 * without the express consent of the CONDOR Team.  For more information
 * contact: CONDOR Team, Attention: Professor Miron Livny,
 * 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685,
 * (608) 262-0856 or miron@cs.wisc.edu.
 *
 * U.S. Government Rights Restrictions: Use, duplication, or disclosure
 * by the U.S. Government is subject to restrictions as set forth in
 * subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer
 * Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and
 * (2) of Commercial Computer Software-Restricted Rights at 48 CFR
 * 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron
 * Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison,
 * WI 53706-1685, (608) 262-0856 or miron@cs.wisc.edu.
****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/

///////////////////////////////////////////////////////////////////////////////
// Get the ip address and port number of a schedd from the collector.
///////////////////////////////////////////////////////////////////////////////

#include "condor_common.h"
#include "condor_query.h"
#include "condor_config.h"
#include "my_hostname.h"
#include "get_full_hostname.h"
#include "daemon_types.h"

extern "C" {

// Return the host portion of a daemon name string.  Either the name
// includes an "@" sign, in which case we return whatever is after it,
// or it doesn't, in which case we just return what we got passed.
const char*
get_host_part( const char* name )
{
	char* tmp;
	tmp = strchr( name, '@' );
	if( tmp ) {
		return ++tmp;
	} else {
		return name;
	}
}

// Return a pointer to a static buffer that contains the valid daemon
// name that corresponds with the given name.  Basically, see if
// there's an '@'.  If so, resolve everything after it as a hostname.
// If not, resolve what we were passed as a hostname.
char*
get_daemon_name( const char* name )
{
	char *tmp, *fullname, *tmpname;
	static char daemon_name[256];
	daemon_name[0] = '\0';
	tmpname= strdup( name );
	int had_error = 0;

		// First, check for a '@' in the name.
	tmp = strchr( tmpname, '@' );
	if( tmp ) {
			// There's a '@'.
		*tmp = '\0';
		tmp++;
		if( *tmp ) {
				// There was something after the @, try to resolve it
				// as a full hostname:
			fullname = get_full_hostname( tmp );
		} else {
				// There was nothing after the @, use localhost:
			fullname = my_full_hostname();
		}
		if( fullname ) {
			sprintf( daemon_name, "%s@%s", tmpname, fullname );
		} else {
			had_error = 1;
		}
	} else {
			// There's no '@', just try to resolve the hostname.
		if( (fullname = get_full_hostname(tmpname)) ) {
			sprintf( daemon_name, "%s", fullname );
		} else {
			had_error = 1;
		}
	}
	free( tmpname );
	if( had_error ) {
		return NULL;
	} else {
		return daemon_name;
	}
}

// Given some name, create a valid name for ourself with our full
// hostname.  If the name contains an '@', strip off everything after
// it and append my_full_hostname().  If there's no '@', try to
// resolve what we have and see if it's my_full_hostname.  If so, use
// it, otherwise, use name@my_full_hostname().
char*
build_valid_daemon_name( char* name )
{
	char *tmp;
	static char daemonName[100];

	if( name && *name ) {
		tmp = strchr( name, '@' );
		if( tmp ) {
				// name we were passed has an '@'
			*tmp = '\0';
			sprintf( daemonName, "%s@%s", name, my_full_hostname() );
		} else {
				// no '@', see if what we have is our hostname
			if( !strcmp(get_full_hostname(name), my_full_hostname()) ) {
				sprintf( daemonName, "%s", my_full_hostname() );
			} else {
				sprintf( daemonName, "%s@%s", name, my_full_hostname() );
			}
		}
	} else {
		sprintf( daemonName, "%s", my_full_hostname() );
	}
	return daemonName;
}

// Return a pointer to a static buffer which contains the name of the
// given daemon (specified by subsys string) as configured on the
// local host.
char*
my_daemon_name( const char* subsys )
{
	static char my_name[100];
	char line [100], *tmp;
	sprintf( line, "%s_NAME", subsys );
	tmp = param( line );
	if( tmp ) {
		sprintf( my_name, "%s", build_valid_daemon_name(tmp) );
		free( tmp );
	} else {
		sprintf( my_name, "%s", my_full_hostname() );
	}
	return my_name;
}

char*
real_get_daemon_addr( const char* constraint_attr,
				 const char* name, AdTypes adtype,
				 const char* attribute, const char* subsys,
				 const char* pool )
{

	static char			daemonAddr[100];
	char				constraint[500];
	char				*fullname = NULL, *addr_file, *tmp, *my_name;
	FILE				*addr_fp;
	int					is_local = 0;

	daemonAddr[0] = '\0';
	my_name = my_daemon_name( subsys );

		// Figure out if we want to find a local daemon or not.
	if( name && *name ) {
		fullname = (char*)name;
		if( !strcmp( fullname, my_name ) ) {
			is_local = 1;
		}
	} else {
		fullname = my_name;
		is_local = 1;
	}

	if( is_local ) {
		sprintf( constraint, "%s_ADDRESS_FILE", subsys );
		addr_file = param( constraint );
		if( addr_file ) {
			if( (addr_fp = fopen(addr_file, "r")) ) {
					// Read out the sinful string.
				fgets( daemonAddr, 100, addr_fp );
					// chop off the newline
				tmp = strchr( daemonAddr, '\n' );
				if( tmp ) {
					*tmp = '\0';
				}
				fclose( addr_fp );
			}
			free( addr_file );
		}
		if( daemonAddr[0] == '<' ) {
				// We found something reasonable.
			return daemonAddr;
		}
	}

	CondorQuery			query(adtype);
	ClassAd*			scan;
	ClassAdList			ads;

	sprintf(constraint, "%s == \"%s\"", constraint_attr, fullname );
	query.addConstraint(constraint);
	query.fetchAds(ads, pool);
	ads.Open();
	scan = ads.Next();
	if(!scan)
	{
		return NULL;
	}
	if(scan->EvalString(attribute, NULL, daemonAddr) == FALSE)
	{
		return NULL;
	}
	return daemonAddr;
}

char*
get_schedd_addr(const char* name, const char* pool)
{
	return real_get_daemon_addr( ATTR_NAME, name, SCHEDD_AD,
								 ATTR_SCHEDD_IP_ADDR, "SCHEDD", pool );
}

char*
get_startd_addr(const char* name, const char* pool)
{
	return real_get_daemon_addr( ATTR_MACHINE, name, STARTD_AD,
								 ATTR_STARTD_IP_ADDR, "STARTD", pool );
}

char*
get_master_addr(const char* name, const char* pool)
{
	return real_get_daemon_addr( ATTR_NAME, name, MASTER_AD,
								 ATTR_MASTER_IP_ADDR, "MASTER", pool );
}

char*
get_cm_addr( const char* name, char* config_name, int port )
{
	static char addr[30];
	struct hostent* hostp;
	char* tmp = NULL;

	if( name && *name ) {
		tmp = strdup( name );
	} else {
		tmp = param( config_name );
	}
	if( ! tmp ) {
		return NULL;
	}
	hostp = gethostbyname( tmp );
	free( tmp );
	if( ! hostp ) {
		return NULL;
	}
	sprintf( addr, "<%s:%d>",
			 inet_ntoa( *(struct in_addr*)(hostp->h_addr_list[0]) ),
			 port );
	return addr;
}

char*
get_negotiator_addr(const char* name)
{
	return get_cm_addr( name, "NEGOTIATOR_HOST", NEGOTIATOR_PORT );
}

char*
get_collector_addr(const char* name)
{
	return get_cm_addr( name, "COLLECTOR_HOST", COLLECTOR_PORT );
}

char*
get_daemon_addr( daemonType dt, const char* name, const char* pool )
{
	switch( dt ) {
	case DT_MASTER:
		return get_master_addr( name, pool );
	case DT_STARTD:
		return get_startd_addr( name, pool );
	case DT_SCHEDD:
		return get_schedd_addr( name, pool );
	case DT_NEGOTIATOR:
		return get_negotiator_addr( name );
	case DT_COLLECTOR:
		return get_collector_addr( name );
	default:
		return NULL;
	}
	return NULL;
}

int
is_valid_sinful( char *sinful )
{
	char* tmp;
	if( !sinful ) return FALSE;
	if( !(sinful[0] == '<') ) return FALSE;
	if( !(tmp = strchr(sinful, ':')) ) return FALSE;
	if( !(tmp = strrchr(sinful, '>')) ) return FALSE;
	return TRUE;
}

} /* extern "C" */
<commit_msg>on startd query, use only host part and query for ATTR_MACHINE<commit_after>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**
 * CONDOR Copyright Notice
 *
 * See LICENSE.TXT for additional notices and disclaimers.
 *
 * Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department,
 * University of Wisconsin-Madison, Madison, WI.  All Rights Reserved.
 * No use of the CONDOR Software Program Source Code is authorized
 * without the express consent of the CONDOR Team.  For more information
 * contact: CONDOR Team, Attention: Professor Miron Livny,
 * 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685,
 * (608) 262-0856 or miron@cs.wisc.edu.
 *
 * U.S. Government Rights Restrictions: Use, duplication, or disclosure
 * by the U.S. Government is subject to restrictions as set forth in
 * subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer
 * Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and
 * (2) of Commercial Computer Software-Restricted Rights at 48 CFR
 * 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron
 * Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison,
 * WI 53706-1685, (608) 262-0856 or miron@cs.wisc.edu.
****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/

///////////////////////////////////////////////////////////////////////////////
// Get the ip address and port number of a schedd from the collector.
///////////////////////////////////////////////////////////////////////////////

#include "condor_common.h"
#include "condor_query.h"
#include "condor_config.h"
#include "my_hostname.h"
#include "get_full_hostname.h"
#include "daemon_types.h"

extern "C" {

// Return the host portion of a daemon name string.  Either the name
// includes an "@" sign, in which case we return whatever is after it,
// or it doesn't, in which case we just return what we got passed.
const char*
get_host_part( const char* name )
{
	char* tmp;
	tmp = strchr( name, '@' );
	if( tmp ) {
		return ++tmp;
	} else {
		return name;
	}
}

// Return a pointer to a static buffer that contains the valid daemon
// name that corresponds with the given name.  Basically, see if
// there's an '@'.  If so, resolve everything after it as a hostname.
// If not, resolve what we were passed as a hostname.
char*
get_daemon_name( const char* name )
{
	char *tmp, *fullname, *tmpname;
	static char daemon_name[256];
	daemon_name[0] = '\0';
	tmpname= strdup( name );
	int had_error = 0;

		// First, check for a '@' in the name.
	tmp = strchr( tmpname, '@' );
	if( tmp ) {
			// There's a '@'.
		*tmp = '\0';
		tmp++;
		if( *tmp ) {
				// There was something after the @, try to resolve it
				// as a full hostname:
			fullname = get_full_hostname( tmp );
		} else {
				// There was nothing after the @, use localhost:
			fullname = my_full_hostname();
		}
		if( fullname ) {
			sprintf( daemon_name, "%s@%s", tmpname, fullname );
		} else {
			had_error = 1;
		}
	} else {
			// There's no '@', just try to resolve the hostname.
		if( (fullname = get_full_hostname(tmpname)) ) {
			sprintf( daemon_name, "%s", fullname );
		} else {
			had_error = 1;
		}
	}
	free( tmpname );
	if( had_error ) {
		return NULL;
	} else {
		return daemon_name;
	}
}

// Given some name, create a valid name for ourself with our full
// hostname.  If the name contains an '@', strip off everything after
// it and append my_full_hostname().  If there's no '@', try to
// resolve what we have and see if it's my_full_hostname.  If so, use
// it, otherwise, use name@my_full_hostname().
char*
build_valid_daemon_name( char* name )
{
	char *tmp;
	static char daemonName[100];

	if( name && *name ) {
		tmp = strchr( name, '@' );
		if( tmp ) {
				// name we were passed has an '@'
			*tmp = '\0';
			sprintf( daemonName, "%s@%s", name, my_full_hostname() );
		} else {
				// no '@', see if what we have is our hostname
			if( !strcmp(get_full_hostname(name), my_full_hostname()) ) {
				sprintf( daemonName, "%s", my_full_hostname() );
			} else {
				sprintf( daemonName, "%s@%s", name, my_full_hostname() );
			}
		}
	} else {
		sprintf( daemonName, "%s", my_full_hostname() );
	}
	return daemonName;
}

// Return a pointer to a static buffer which contains the name of the
// given daemon (specified by subsys string) as configured on the
// local host.
char*
my_daemon_name( const char* subsys )
{
	static char my_name[100];
	char line [100], *tmp;
	sprintf( line, "%s_NAME", subsys );
	tmp = param( line );
	if( tmp ) {
		sprintf( my_name, "%s", build_valid_daemon_name(tmp) );
		free( tmp );
	} else {
		sprintf( my_name, "%s", my_full_hostname() );
	}
	return my_name;
}

char*
real_get_daemon_addr( const char* constraint_attr,
				 const char* name, AdTypes adtype,
				 const char* attribute, const char* subsys,
				 const char* pool )
{

	static char			daemonAddr[100];
	char				constraint[500];
	char				*fullname = NULL, *addr_file, *tmp, *my_name;
	FILE				*addr_fp;
	int					is_local = 0;

	daemonAddr[0] = '\0';
	my_name = my_daemon_name( subsys );

		// Figure out if we want to find a local daemon or not.
	if( name && *name ) {
		fullname = (char*)name;
		if( !strcmp( fullname, my_name ) ) {
			is_local = 1;
		}
	} else {
		fullname = my_name;
		is_local = 1;
	}

	if( is_local ) {
		sprintf( constraint, "%s_ADDRESS_FILE", subsys );
		addr_file = param( constraint );
		if( addr_file ) {
			if( (addr_fp = fopen(addr_file, "r")) ) {
					// Read out the sinful string.
				fgets( daemonAddr, 100, addr_fp );
					// chop off the newline
				tmp = strchr( daemonAddr, '\n' );
				if( tmp ) {
					*tmp = '\0';
				}
				fclose( addr_fp );
			}
			free( addr_file );
		}
		if( daemonAddr[0] == '<' ) {
				// We found something reasonable.
			return daemonAddr;
		}
	}

	CondorQuery			query(adtype);
	ClassAd*			scan;
	ClassAdList			ads;

	sprintf(constraint, "%s == \"%s\"", constraint_attr, fullname );
	query.addConstraint(constraint);
	query.fetchAds(ads, pool);
	ads.Open();
	scan = ads.Next();
	if(!scan)
	{
		return NULL;
	}
	if(scan->EvalString(attribute, NULL, daemonAddr) == FALSE)
	{
		return NULL;
	}
	return daemonAddr;
}

char*
get_schedd_addr(const char* name, const char* pool)
{
	return real_get_daemon_addr( ATTR_NAME, name, SCHEDD_AD,
								 ATTR_SCHEDD_IP_ADDR, "SCHEDD", pool );
}

char*
get_startd_addr(const char* name, const char* pool)
{
	return real_get_daemon_addr( ATTR_MACHINE, get_host_part(name), STARTD_AD,
								 ATTR_STARTD_IP_ADDR, "STARTD", pool );
}

char*
get_master_addr(const char* name, const char* pool)
{
	return real_get_daemon_addr( ATTR_NAME, name, MASTER_AD,
								 ATTR_MASTER_IP_ADDR, "MASTER", pool );
}

char*
get_cm_addr( const char* name, char* config_name, int port )
{
	static char addr[30];
	struct hostent* hostp;
	char* tmp = NULL;

	if( name && *name ) {
		tmp = strdup( name );
	} else {
		tmp = param( config_name );
	}
	if( ! tmp ) {
		return NULL;
	}
	hostp = gethostbyname( tmp );
	free( tmp );
	if( ! hostp ) {
		return NULL;
	}
	sprintf( addr, "<%s:%d>",
			 inet_ntoa( *(struct in_addr*)(hostp->h_addr_list[0]) ),
			 port );
	return addr;
}

char*
get_negotiator_addr(const char* name)
{
	return get_cm_addr( name, "NEGOTIATOR_HOST", NEGOTIATOR_PORT );
}

char*
get_collector_addr(const char* name)
{
	return get_cm_addr( name, "COLLECTOR_HOST", COLLECTOR_PORT );
}

char*
get_daemon_addr( daemonType dt, const char* name, const char* pool )
{
	switch( dt ) {
	case DT_MASTER:
		return get_master_addr( name, pool );
	case DT_STARTD:
		return get_startd_addr( name, pool );
	case DT_SCHEDD:
		return get_schedd_addr( name, pool );
	case DT_NEGOTIATOR:
		return get_negotiator_addr( name );
	case DT_COLLECTOR:
		return get_collector_addr( name );
	default:
		return NULL;
	}
	return NULL;
}

int
is_valid_sinful( char *sinful )
{
	char* tmp;
	if( !sinful ) return FALSE;
	if( !(sinful[0] == '<') ) return FALSE;
	if( !(tmp = strchr(sinful, ':')) ) return FALSE;
	if( !(tmp = strrchr(sinful, '>')) ) return FALSE;
	return TRUE;
}

} /* extern "C" */
<|endoftext|>