<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/browser/chromeos/cros/mount_library.h"

#include "base/message_loop.h"
#include "base/string_util.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/chromeos/cros/cros_library.h"

// Allows InvokeLater without adding refcounting. This class is a Singleton and
// won't be deleted until it's last InvokeLater is run.
DISABLE_RUNNABLE_METHOD_REFCOUNT(chromeos::MountLibraryImpl);

namespace chromeos {

void MountLibraryImpl::AddObserver(Observer* observer) {
  observers_.AddObserver(observer);
}

void MountLibraryImpl::RemoveObserver(Observer* observer) {
  observers_.RemoveObserver(observer);
}

bool MountLibraryImpl::MountPath(const char* device_path) {
  return MountDevicePath(device_path);
}

void MountLibraryImpl::ParseDisks(const MountStatus& status) {
  disks_.clear();
  for (int i = 0; i < status.size; i++) {
    std::string path;
    std::string mountpath;
    std::string systempath;
    bool parent;
    bool hasmedia;
    if (status.disks[i].path != NULL) {
      path = status.disks[i].path;
    }
    if (status.disks[i].mountpath != NULL) {
      mountpath = status.disks[i].mountpath;
    }
    if (status.disks[i].systempath != NULL) {
      systempath = status.disks[i].systempath;
    }
    parent = status.disks[i].isparent;
    hasmedia = status.disks[i].hasmedia;
    disks_.push_back(Disk(path,
                          mountpath,
                          systempath,
                          parent,
                          hasmedia));
  }
}

MountLibraryImpl::MountLibraryImpl() : mount_status_connection_(NULL) {
  if (CrosLibrary::Get()->EnsureLoaded()) {
    Init();
  } else {
    LOG(ERROR) << "Cros Library has not been loaded";
  }
}

MountLibraryImpl::~MountLibraryImpl() {
  if (mount_status_connection_) {
    DisconnectMountStatus(mount_status_connection_);
  }
}

// static
void MountLibraryImpl::MountStatusChangedHandler(void* object,
                                                 const MountStatus& status,
                                                 MountEventType evt,
                                                 const  char* path) {
  MountLibraryImpl* mount = static_cast<MountLibraryImpl*>(object);
  std::string devicepath = path;
  mount->ParseDisks(status);
  mount->UpdateMountStatus(status, evt, devicepath);
}

void MountLibraryImpl::Init() {
  // Getting the monitor status so that the daemon starts up.
  MountStatus* mount = RetrieveMountInformation();
  ParseDisks(*mount);
  FreeMountStatus(mount);

  mount_status_connection_ = MonitorMountStatus(
      &MountStatusChangedHandler, this);
}

void MountLibraryImpl::UpdateMountStatus(const MountStatus& status,
                                     MountEventType evt,
                                     const std::string& path) {
  // Make sure we run on UI thread.
  DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));

  FOR_EACH_OBSERVER(Observer, observers_, MountChanged(this, evt, path));
}

}  // namespace chromeos
<commit_msg>Fix a potential crash in MountLibraryImpl::Init().<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/browser/chromeos/cros/mount_library.h"

#include "base/message_loop.h"
#include "base/string_util.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/chromeos/cros/cros_library.h"

// Allows InvokeLater without adding refcounting. This class is a Singleton and
// won't be deleted until it's last InvokeLater is run.
DISABLE_RUNNABLE_METHOD_REFCOUNT(chromeos::MountLibraryImpl);

namespace chromeos {

void MountLibraryImpl::AddObserver(Observer* observer) {
  observers_.AddObserver(observer);
}

void MountLibraryImpl::RemoveObserver(Observer* observer) {
  observers_.RemoveObserver(observer);
}

bool MountLibraryImpl::MountPath(const char* device_path) {
  return MountDevicePath(device_path);
}

void MountLibraryImpl::ParseDisks(const MountStatus& status) {
  disks_.clear();
  for (int i = 0; i < status.size; i++) {
    std::string path;
    std::string mountpath;
    std::string systempath;
    bool parent;
    bool hasmedia;
    if (status.disks[i].path != NULL) {
      path = status.disks[i].path;
    }
    if (status.disks[i].mountpath != NULL) {
      mountpath = status.disks[i].mountpath;
    }
    if (status.disks[i].systempath != NULL) {
      systempath = status.disks[i].systempath;
    }
    parent = status.disks[i].isparent;
    hasmedia = status.disks[i].hasmedia;
    disks_.push_back(Disk(path,
                          mountpath,
                          systempath,
                          parent,
                          hasmedia));
  }
}

MountLibraryImpl::MountLibraryImpl() : mount_status_connection_(NULL) {
  if (CrosLibrary::Get()->EnsureLoaded()) {
    Init();
  } else {
    LOG(ERROR) << "Cros Library has not been loaded";
  }
}

MountLibraryImpl::~MountLibraryImpl() {
  if (mount_status_connection_) {
    DisconnectMountStatus(mount_status_connection_);
  }
}

// static
void MountLibraryImpl::MountStatusChangedHandler(void* object,
                                                 const MountStatus& status,
                                                 MountEventType evt,
                                                 const  char* path) {
  MountLibraryImpl* mount = static_cast<MountLibraryImpl*>(object);
  std::string devicepath = path;
  mount->ParseDisks(status);
  mount->UpdateMountStatus(status, evt, devicepath);
}

void MountLibraryImpl::Init() {
  // Getting the monitor status so that the daemon starts up.
  MountStatus* mount = RetrieveMountInformation();
  if (!mount) {
    LOG(ERROR) << "Failed to retrieve mount information";
    return;
  }
  ParseDisks(*mount);
  FreeMountStatus(mount);

  mount_status_connection_ = MonitorMountStatus(
      &MountStatusChangedHandler, this);
}

void MountLibraryImpl::UpdateMountStatus(const MountStatus& status,
                                     MountEventType evt,
                                     const std::string& path) {
  // Make sure we run on UI thread.
  DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));

  FOR_EACH_OBSERVER(Observer, observers_, MountChanged(this, evt, path));
}

}  // namespace chromeos
<|endoftext|>


<commit_before>#include <iostream>
#include <iomanip>
#include "../Global.h"
#include "../Options.h"
#include "../Data.h"
#include "../Scheme.h"
#include "../Inputs/Input.h"
#include "../Loggers/Logger.h"
#include "../Loggers/Default.h"
#include "../Location.h"
#include "../Member.h"
#include <cstring>
bool mShowAll;
bool mShowSpecific;
void showLocations(Input* input);
void showOffsets(Input* input);
void showDates(Input* input);
void showMembers(Input* input);
void showVariables(Input* input);

int main(int argc, const char *argv[]) {
   Global::setLogger(new LoggerDefault(Logger::message));

   if(argc != 2 && argc != 3 && argc != 4) {
      std::cout << "Show information about a COMPS dataset" << std::endl;
      std::cout << std::endl;
      std::cout << "usage: info.exe dataset [--show-all]    show information about dataset" << std::endl;
      std::cout << "   or: info.exe dataset date            show detailed information for a specific date" << std::endl;
      std::cout << std::endl;
      std::cout << "Arguments:" << std::endl;
      std::cout << "   dataset         Tag of dataset from namelist" << std::endl;
      std::cout << "   date            Date in YYYYMMDD format" << std::endl;
      std::cout << "   --show-all      Do not limit variables/dates/offsets to the first 100" << std::endl;

      return 0;
   }

   mShowAll = false;
   mShowSpecific = false;
   int date = 0;

   std::string dataset(argv[1]);
   if(argc >= 3) {
      if(!std::strcmp(argv[2], "--show-all")) {
         mShowAll = true;
      }
      else {
         std::stringstream ss;
         ss<< std::string(argv[2]);
         ss >> date;
         mShowSpecific = true;
      }
   }

   InputContainer inputContainer(Options(""));
   Input* input = inputContainer.getInput(dataset);

   if(mShowSpecific) {
      // Show results for one specific date
      std::vector<float> offsets = input->getOffsets();
      std::vector<std::string> variables = input->getVariables();
      std::vector<Location> locations = input->getLocations();
      std::vector<Member> members = input->getMembers();

      std::vector<float> mean;
      mean.resize(variables.size(), 0);
      std::vector<int> num;
      num.resize(variables.size(), 0);

      std::cout << "Variable     mean       count (max "
                << offsets.size()*locations.size()*members.size() << ")" << std::endl;
      for(int v = 0; v < variables.size(); v++) {
         for(int i = 0; i < offsets.size(); i++) {
            for(int k = 0; k < locations.size(); k++) {
               for(int m = 0; m < members.size(); m++) {
                  float value = input->getValue(date, 0, offsets[i], locations[k].getId(), members[m].getId(), variables[v]);
                  if(Global::isValid(value)) {
                     mean[v] += value;
                     num[v]++;
                  }
               }
            }
         }
         if(num[v] > 0)
            mean[v] /= num[v];
         else
            mean[v] = Global::MV;
         std::cout << std::left << std::setfill(' ') << std::setw(12) << variables[v] << " " << std::setprecision(3) << std::setw(10) << mean[v] << " " << num[v] << std::endl;
      }
   }
   else {
      // Show general statistics
      showLocations(input);
      showOffsets(input);
      showDates(input);
      showVariables(input);
      showMembers(input);
   }
}
void showLocations(Input* input) {
   std::cout << "Locations:" << std::endl;
   const std::vector<Location>& locations = input->getLocations();
   std::cout << "Id       code   lat   lon   elev" << std::endl;
   for(int i = 0; i < locations.size(); i++) {
      if(mShowAll || locations.size() < 100 || i < 5 || i >= locations.size()-5) {
         std::cout << std::setw(6) << locations[i].getId() << " "
                   << std::setw(6) << locations[i].getCode() << " "
                   << std::setw(6) << std::fixed << std::setprecision(1) << locations[i].getLat() << " "
                   << std::setw(6) << locations[i].getLon() << " "
                   << std::setw(6) << std::fixed << std::setprecision(1) << locations[i].getElev() << std::endl;
      }
      else if(i == 5) {
         std::cout << "..." << std::endl;
      }
   }
   std::cout << std::endl;
}
void showOffsets(Input* input) {
   std::cout << "Offsets:" << std::endl;
   std::vector<float> offsets = input->getOffsets();
   std::cout << "Id       offset (h)" << std::endl;
   for(int i = 0; i < offsets.size(); i++) {
      if(mShowAll || offsets.size() < 100 || i < 5 || i >= offsets.size()-5) {
         std::cout << std::setw(6) << i << " "
                   << std::setw(6) << offsets[i] << std::endl;
      }
      else if(i == 5) {
         std::cout << "..." << std::endl;
      }
   }
   std::cout << std::endl;
}
void showDates(Input* input) {
   std::cout << "Dates:" << std::endl;
   std::vector<int> dates;
   input->getDates(dates);
   std::cout << "Id        dates" << std::endl;
   for(int i = 0; i < dates.size(); i++) {
      if(mShowAll || dates.size() < 100 || i < 5 || i >= dates.size()-5) {
         std::cout << std::setw(6) << i
                   << std::setw(9) << dates[i] << std::endl;
      }
      else if(i == 5) {
         std::cout << "..." << std::endl;
      }
   }
   std::cout << std::endl;
}
void showVariables(Input* input) {
   std::cout << "Variables:" << std::endl;
   std::vector<std::string> variables = input->getVariables();
   std::cout << "   Id      variable" << std::endl;
   for(int i = 0; i < variables.size(); i++) {
      if(mShowAll || variables.size() < 100 || i < 5 || i >= variables.size()-5) {
         std::cout << std::setw(6) << i << " "
                   << std::setw(12) << variables[i] << std::endl;
      }
      else if(i == 5) {
         std::cout << "..." << std::endl;
      }
   }
}
void showMembers(Input* input) {
   std::cout << "Members:" << std::endl;
   std::vector<Member> members = input->getMembers();
   std::cout << "   Id         model resolution" << std::endl;
   for(int i = 0; i < members.size(); i++) {
      if(mShowAll || members.size() < 100 || i < 5 || i >= members.size()-5) {
         float res = members[i].getResolution();
         std::cout << std::setw(6) << i << " "
                   << std::setw(12) << members[i].getModel();
         if(Global::isValid(res))
            std::cout << std::setw(9) << res << "km";
         std::cout << std::endl;
      }
      else if(i == 5) {
         std::cout << "..." << std::endl;
      }
   }
   std::cout << std::endl;
}
<commit_msg>Show the min and max of each variable in info.exe<commit_after>#include <iostream>
#include <iomanip>
#include "../Global.h"
#include "../Options.h"
#include "../Data.h"
#include "../Scheme.h"
#include "../Inputs/Input.h"
#include "../Loggers/Logger.h"
#include "../Loggers/Default.h"
#include "../Location.h"
#include "../Member.h"
#include <cstring>
bool mShowAll;
bool mShowSpecific;
void showLocations(Input* input);
void showOffsets(Input* input);
void showDates(Input* input);
void showMembers(Input* input);
void showVariables(Input* input);

int main(int argc, const char *argv[]) {
   Global::setLogger(new LoggerDefault(Logger::message));

   if(argc != 2 && argc != 3 && argc != 4) {
      std::cout << "Show information about a COMPS dataset" << std::endl;
      std::cout << std::endl;
      std::cout << "usage: info.exe dataset [--show-all]    show information about dataset" << std::endl;
      std::cout << "   or: info.exe dataset date            show detailed information for a specific date" << std::endl;
      std::cout << std::endl;
      std::cout << "Arguments:" << std::endl;
      std::cout << "   dataset         Tag of dataset from namelist" << std::endl;
      std::cout << "   date            Date in YYYYMMDD format" << std::endl;
      std::cout << "   --show-all      Do not limit variables/dates/offsets to the first 100" << std::endl;

      return 0;
   }

   mShowAll = false;
   mShowSpecific = false;
   int date = 0;

   std::string dataset(argv[1]);
   if(argc >= 3) {
      if(!std::strcmp(argv[2], "--show-all")) {
         mShowAll = true;
      }
      else {
         std::stringstream ss;
         ss<< std::string(argv[2]);
         ss >> date;
         mShowSpecific = true;
      }
   }

   InputContainer inputContainer(Options(""));
   Input* input = inputContainer.getInput(dataset);

   if(mShowSpecific) {
      // Show results for one specific date
      std::vector<float> offsets = input->getOffsets();
      std::vector<std::string> variables = input->getVariables();
      std::vector<Location> locations = input->getLocations();
      std::vector<Member> members = input->getMembers();

      std::vector<float> min(variables.size(), Global::INF);
      std::vector<float> mean(variables.size(), 0);
      std::vector<float> max(variables.size(), -Global::INF);
      std::vector<int> num(variables.size(), 0);

      std::cout << "Variable     min   mean  max        count (max "
                << offsets.size()*locations.size()*members.size() << ")" << std::endl;
      for(int v = 0; v < variables.size(); v++) {
         for(int i = 0; i < offsets.size(); i++) {
            for(int k = 0; k < locations.size(); k++) {
               for(int m = 0; m < members.size(); m++) {
                  float value = input->getValue(date, 0, offsets[i], locations[k].getId(), members[m].getId(), variables[v]);
                  if(Global::isValid(value)) {
                     min[v] = std::min(min[v], value);
                     mean[v] += value;
                     max[v] = std::max(max[v], value);
                     num[v]++;
                  }
               }
            }
         }
         if(num[v] > 0)
            mean[v] /= num[v];
         else {
            min[v] = Global::MV;
            mean[v] = Global::MV;
            max[v] = Global::MV;
         }
         std::cout << std::left << std::setfill(' ') << std::setw(12) << variables[v] << " "
                   << std::setprecision(3) << std::setw(5) << min[v] << " "
                   << std::setprecision(3) << std::setw(5) << mean[v]<< " "
                   << std::setprecision(3) << std::setw(10) << max[v] << " " << num[v] << std::endl;
      }
   }
   else {
      // Show general statistics
      showLocations(input);
      showOffsets(input);
      showDates(input);
      showVariables(input);
      showMembers(input);
   }
}
void showLocations(Input* input) {
   std::cout << "Locations:" << std::endl;
   const std::vector<Location>& locations = input->getLocations();
   std::cout << "Id       code   lat   lon   elev" << std::endl;
   for(int i = 0; i < locations.size(); i++) {
      if(mShowAll || locations.size() < 100 || i < 5 || i >= locations.size()-5) {
         std::cout << std::setw(6) << locations[i].getId() << " "
                   << std::setw(6) << locations[i].getCode() << " "
                   << std::setw(6) << std::fixed << std::setprecision(1) << locations[i].getLat() << " "
                   << std::setw(6) << locations[i].getLon() << " "
                   << std::setw(6) << std::fixed << std::setprecision(1) << locations[i].getElev() << std::endl;
      }
      else if(i == 5) {
         std::cout << "..." << std::endl;
      }
   }
   std::cout << std::endl;
}
void showOffsets(Input* input) {
   std::cout << "Offsets:" << std::endl;
   std::vector<float> offsets = input->getOffsets();
   std::cout << "Id       offset (h)" << std::endl;
   for(int i = 0; i < offsets.size(); i++) {
      if(mShowAll || offsets.size() < 100 || i < 5 || i >= offsets.size()-5) {
         std::cout << std::setw(6) << i << " "
                   << std::setw(6) << offsets[i] << std::endl;
      }
      else if(i == 5) {
         std::cout << "..." << std::endl;
      }
   }
   std::cout << std::endl;
}
void showDates(Input* input) {
   std::cout << "Dates:" << std::endl;
   std::vector<int> dates;
   input->getDates(dates);
   std::cout << "Id        dates" << std::endl;
   for(int i = 0; i < dates.size(); i++) {
      if(mShowAll || dates.size() < 100 || i < 5 || i >= dates.size()-5) {
         std::cout << std::setw(6) << i
                   << std::setw(9) << dates[i] << std::endl;
      }
      else if(i == 5) {
         std::cout << "..." << std::endl;
      }
   }
   std::cout << std::endl;
}
void showVariables(Input* input) {
   std::cout << "Variables:" << std::endl;
   std::vector<std::string> variables = input->getVariables();
   std::cout << "   Id      variable" << std::endl;
   for(int i = 0; i < variables.size(); i++) {
      if(mShowAll || variables.size() < 100 || i < 5 || i >= variables.size()-5) {
         std::cout << std::setw(6) << i << " "
                   << std::setw(12) << variables[i] << std::endl;
      }
      else if(i == 5) {
         std::cout << "..." << std::endl;
      }
   }
}
void showMembers(Input* input) {
   std::cout << "Members:" << std::endl;
   std::vector<Member> members = input->getMembers();
   std::cout << "   Id         model resolution" << std::endl;
   for(int i = 0; i < members.size(); i++) {
      if(mShowAll || members.size() < 100 || i < 5 || i >= members.size()-5) {
         float res = members[i].getResolution();
         std::cout << std::setw(6) << i << " "
                   << std::setw(12) << members[i].getModel();
         if(Global::isValid(res))
            std::cout << std::setw(9) << res << "km";
         std::cout << std::endl;
      }
      else if(i == 5) {
         std::cout << "..." << std::endl;
      }
   }
   std::cout << std::endl;
}
<|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/browser/chromeos/usb_mount_observer.h"

#include "chrome/browser/browser.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/dom_ui/filebrowse_ui.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/url_constants.h"

namespace chromeos {

const char* kFilebrowseURLHash = "chrome://filebrowse#";
const char* kFilebrowseScanning = "scanningdevice";
const int kPopupLeft = 0;
const int kPopupTop = 0;
const int kPopupWidth = 250;
const int kPopupHeight = 300;

void USBMountObserver::Observe(NotificationType type,
                               const NotificationSource& source,
                               const NotificationDetails& details) {
  DCHECK(type == NotificationType::BROWSER_CLOSED);
  for (BrowserIterator i = browsers_.begin(); i != browsers_.end();
       ++i) {
    if (Source<Browser>(source).ptr() == i->browser) {
      i->browser = NULL;
      registrar_.Remove(this,
                        NotificationType::BROWSER_CLOSED,
                        source);
      return;
    }
  }
}

void USBMountObserver::OpenFileBrowse(const std::string& url,
                                      const std::string& device_path,
                                      bool small) {
  Browser* browser;
  Profile* profile;
  profile = BrowserList::GetLastActive()->profile();
  if (small) {
    browser = FileBrowseUI::OpenPopup(profile,
                                      url,
                                      FileBrowseUI::kSmallPopupWidth,
                                      FileBrowseUI::kSmallPopupHeight);
  } else {
    browser = FileBrowseUI::OpenPopup(profile,
                                      url,
                                      FileBrowseUI::kPopupWidth,
                                      FileBrowseUI::kPopupHeight);
  }
  registrar_.Add(this,
                 NotificationType::BROWSER_CLOSED,
                 Source<Browser>(browser));
  BrowserIterator iter = FindBrowserForPath(device_path);
  if (iter == browsers_.end()) {
    BrowserWithPath new_browser;
    new_browser.browser = browser;
    new_browser.device_path = device_path;
    browsers_.push_back(new_browser);
  } else {
    iter->browser = browser;
  }
}

void USBMountObserver::MountChanged(chromeos::MountLibrary* obj,
                                    chromeos::MountEventType evt,
                                    const std::string& path) {
  if (evt == chromeos::DISK_ADDED) {
    const chromeos::MountLibrary::DiskVector& disks = obj->disks();
    for (size_t i = 0; i < disks.size(); ++i) {
      chromeos::MountLibrary::Disk disk = disks[i];
      if (disk.device_path == path) {
        if (disk.is_parent) {
          if (!disk.has_media) {
            RemoveBrowserFromVector(disk.system_path);
          }
        } else if (!obj->MountPath(path.c_str())) {
          RemoveBrowserFromVector(disk.system_path);
        }
      }
    }
    LOG(INFO) << "Got added mount:" << path;
  } else if (evt == chromeos::DISK_REMOVED ||
             evt == chromeos::DEVICE_REMOVED) {
    RemoveBrowserFromVector(path);
  } else if (evt == chromeos::DISK_CHANGED) {
    BrowserIterator iter = FindBrowserForPath(path);
    LOG(INFO) << "Got changed mount:" << path;
    if (iter == browsers_.end() && iter->browser) {
      // We don't currently have this one, so it must have been
      // mounted
      const chromeos::MountLibrary::DiskVector& disks = obj->disks();
      for (size_t i = 0; i < disks.size(); ++i) {
        if (disks[i].device_path == path) {
          if (!disks[i].mount_path.empty()) {
            // Doing second search to see if the current disk has already
            // been popped up due to its parent device being plugged in.
            iter = FindBrowserForPath(disks[i].system_path);
            if (iter != browsers_.end() && iter->browser) {
              std::string url = kFilebrowseURLHash;
              url += disks[i].mount_path;
              TabContents* tab = iter->browser->GetSelectedTabContents();
              iter->browser->window()->SetBounds(gfx::Rect(
                  0, 0, FileBrowseUI::kPopupWidth, FileBrowseUI::kPopupHeight));
              tab->OpenURL(GURL(url), GURL(), CURRENT_TAB,
                  PageTransition::LINK);
              tab->NavigateToPendingEntry(NavigationController::RELOAD);
              iter->device_path = path;
            } else {
              OpenFileBrowse(disks[i].mount_path, disks[i].device_path, false);
            }
          }
          return;
        }
      }
    }
  } else if (evt == chromeos::DEVICE_ADDED) {
    LOG(INFO) << "Got device added" << path;
    OpenFileBrowse(kFilebrowseScanning, path, true);
  } else if (evt == chromeos::DEVICE_SCANNED) {
    LOG(INFO) << "Got device scanned:" << path;
  }
}

USBMountObserver::BrowserIterator USBMountObserver::FindBrowserForPath(
    const std::string& path) {
  for (BrowserIterator i = browsers_.begin();i != browsers_.end();
       ++i) {
    // Doing a substring match so that we find if this new one is a subdevice
    // of another already inserted device.
    if (path.find(i->device_path) != std::string::npos) {
      return i;
    }
  }
  return browsers_.end();
}

void USBMountObserver::RemoveBrowserFromVector(const std::string& path) {
  BrowserIterator i = FindBrowserForPath(path);
  std::string mount_path;
  if (i != browsers_.end()) {
    registrar_.Remove(this,
                      NotificationType::BROWSER_CLOSED,
                      Source<Browser>(i->browser));
    mount_path = i->mount_path;
    browsers_.erase(i);
  }
  std::vector<Browser*> close_these;
  for (BrowserList::const_iterator it = BrowserList::begin();
       it != BrowserList::end(); ++it) {
    if ((*it)->type() == Browser::TYPE_POPUP) {
      if (*it && (*it)->GetTabContentsAt((*it)->selected_index())) {
        const GURL& url =
            (*it)->GetTabContentsAt((*it)->selected_index())->GetURL();
        if (url.SchemeIs(chrome::kChromeUIScheme) &&
            url.host() == chrome::kChromeUIFileBrowseHost &&
            url.ref().find(mount_path) != std::string::npos) {
          close_these.push_back(*it);
        }
      }
    }
  }
  for (size_t x = 0; x < close_these.size(); x++) {
    if (close_these[x]->window()) {
      close_these[x]->window()->Close();
    }
  }
}

} // namespace chromeos
<commit_msg>Fixing mounting case.<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/browser/chromeos/usb_mount_observer.h"

#include "chrome/browser/browser.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/dom_ui/filebrowse_ui.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/url_constants.h"

namespace chromeos {

const char* kFilebrowseURLHash = "chrome://filebrowse#";
const char* kFilebrowseScanning = "scanningdevice";
const int kPopupLeft = 0;
const int kPopupTop = 0;
const int kPopupWidth = 250;
const int kPopupHeight = 300;

void USBMountObserver::Observe(NotificationType type,
                               const NotificationSource& source,
                               const NotificationDetails& details) {
  DCHECK(type == NotificationType::BROWSER_CLOSED);
  for (BrowserIterator i = browsers_.begin(); i != browsers_.end();
       ++i) {
    if (Source<Browser>(source).ptr() == i->browser) {
      i->browser = NULL;
      registrar_.Remove(this,
                        NotificationType::BROWSER_CLOSED,
                        source);
      return;
    }
  }
}

void USBMountObserver::OpenFileBrowse(const std::string& url,
                                      const std::string& device_path,
                                      bool small) {
  Browser* browser;
  Profile* profile;
  profile = BrowserList::GetLastActive()->profile();
  if (small) {
    browser = FileBrowseUI::OpenPopup(profile,
                                      url,
                                      FileBrowseUI::kSmallPopupWidth,
                                      FileBrowseUI::kSmallPopupHeight);
  } else {
    browser = FileBrowseUI::OpenPopup(profile,
                                      url,
                                      FileBrowseUI::kPopupWidth,
                                      FileBrowseUI::kPopupHeight);
  }
  registrar_.Add(this,
                 NotificationType::BROWSER_CLOSED,
                 Source<Browser>(browser));
  BrowserIterator iter = FindBrowserForPath(device_path);
  if (iter == browsers_.end()) {
    BrowserWithPath new_browser;
    new_browser.browser = browser;
    new_browser.device_path = device_path;
    browsers_.push_back(new_browser);
  } else {
    iter->browser = browser;
  }
}

void USBMountObserver::MountChanged(chromeos::MountLibrary* obj,
                                    chromeos::MountEventType evt,
                                    const std::string& path) {
  if (evt == chromeos::DISK_ADDED) {
    const chromeos::MountLibrary::DiskVector& disks = obj->disks();
    for (size_t i = 0; i < disks.size(); ++i) {
      chromeos::MountLibrary::Disk disk = disks[i];
      if (disk.device_path == path) {
        if (disk.is_parent) {
          if (!disk.has_media) {
            RemoveBrowserFromVector(disk.system_path);
          }
        } else if (!obj->MountPath(path.c_str())) {
          RemoveBrowserFromVector(disk.system_path);
        }
      }
    }
    LOG(INFO) << "Got added mount:" << path;
  } else if (evt == chromeos::DISK_REMOVED ||
             evt == chromeos::DEVICE_REMOVED) {
    RemoveBrowserFromVector(path);
  } else if (evt == chromeos::DISK_CHANGED) {
    BrowserIterator iter = FindBrowserForPath(path);
    LOG(INFO) << "Got changed mount:" << path;
    if (iter == browsers_.end()) {
      // We don't currently have this one, so it must have been
      // mounted
      const chromeos::MountLibrary::DiskVector& disks = obj->disks();
      for (size_t i = 0; i < disks.size(); ++i) {
        if (disks[i].device_path == path) {
          if (!disks[i].mount_path.empty()) {
            // Doing second search to see if the current disk has already
            // been popped up due to its parent device being plugged in.
            iter = FindBrowserForPath(disks[i].system_path);
            if (iter != browsers_.end() && iter->browser) {
              std::string url = kFilebrowseURLHash;
              url += disks[i].mount_path;
              TabContents* tab = iter->browser->GetSelectedTabContents();
              iter->browser->window()->SetBounds(gfx::Rect(
                  0, 0, FileBrowseUI::kPopupWidth, FileBrowseUI::kPopupHeight));
              tab->OpenURL(GURL(url), GURL(), CURRENT_TAB,
                  PageTransition::LINK);
              tab->NavigateToPendingEntry(NavigationController::RELOAD);
              iter->device_path = path;
            } else {
              OpenFileBrowse(disks[i].mount_path, disks[i].device_path, false);
            }
          }
          return;
        }
      }
    }
  } else if (evt == chromeos::DEVICE_ADDED) {
    LOG(INFO) << "Got device added" << path;
    OpenFileBrowse(kFilebrowseScanning, path, true);
  } else if (evt == chromeos::DEVICE_SCANNED) {
    LOG(INFO) << "Got device scanned:" << path;
  }
}

USBMountObserver::BrowserIterator USBMountObserver::FindBrowserForPath(
    const std::string& path) {
  for (BrowserIterator i = browsers_.begin();i != browsers_.end();
       ++i) {
    // Doing a substring match so that we find if this new one is a subdevice
    // of another already inserted device.
    if (path.find(i->device_path) != std::string::npos) {
      return i;
    }
  }
  return browsers_.end();
}

void USBMountObserver::RemoveBrowserFromVector(const std::string& path) {
  BrowserIterator i = FindBrowserForPath(path);
  std::string mount_path;
  if (i != browsers_.end()) {
    registrar_.Remove(this,
                      NotificationType::BROWSER_CLOSED,
                      Source<Browser>(i->browser));
    mount_path = i->mount_path;
    browsers_.erase(i);
  }
  std::vector<Browser*> close_these;
  for (BrowserList::const_iterator it = BrowserList::begin();
       it != BrowserList::end(); ++it) {
    if ((*it)->type() == Browser::TYPE_POPUP) {
      if (*it && (*it)->GetTabContentsAt((*it)->selected_index())) {
        const GURL& url =
            (*it)->GetTabContentsAt((*it)->selected_index())->GetURL();
        if (url.SchemeIs(chrome::kChromeUIScheme) &&
            url.host() == chrome::kChromeUIFileBrowseHost &&
            url.ref().find(mount_path) != std::string::npos) {
          close_these.push_back(*it);
        }
      }
    }
  }
  for (size_t x = 0; x < close_these.size(); x++) {
    if (close_these[x]->window()) {
      close_these[x]->window()->Close();
    }
  }
}

} // namespace chromeos
<|endoftext|>


<commit_before>#include "EditDistance.hpp"

#include <vector>
#include <algorithm>
using namespace std;

int EditDistance::minDistance(string word1, string word2)
{
  int n1 = word1.size();
  int n2 = word2.size();
  vector<vector<int>> dp(n1 + 1, vector<int>(n2 + 1, 0));

  for (int i = 1; i <= n1; i++)
    dp[i][0] = i;

  for (int j = 1; j <= n2; j++)
    dp[0][j] = j;

  for (int i = 1; i <= n1; i++) {
    for (int j = 1; j <= n2; j++) {
      if (word1[i - 1] == word2[j - 1])
        dp[i][j] = min(dp[i - 1][j - 1], dp[i - 1][j] + 1);
      else
        dp[i][j] = min(dp[i - 1][j - 1], min(dp[i][j - 1], dp[i - 1][j])) + 1;
    }
  }

  return dp[n1][n2];
}
<commit_msg>Refine Problem 72. Edit Distance<commit_after>#include "EditDistance.hpp"

#include <vector>
#include <algorithm>
using namespace std;

int EditDistance::minDistance(string word1, string word2)
{
  int n1 = word1.size();
  int n2 = word2.size();
  vector<vector<int>> dp(n1 + 1, vector<int>(n2 + 1, 0));

  for (int i = 1; i <= n1; i++)
    dp[i][0] = i;

  for (int j = 1; j <= n2; j++)
    dp[0][j] = j;

  for (int i = 1; i <= n1; i++) {
    for (int j = 1; j <= n2; j++) {
      if (word1[i - 1] == word2[j - 1])
        dp[i][j] = dp[i - 1][j - 1];
      else
        dp[i][j] = min(dp[i - 1][j - 1], min(dp[i][j - 1], dp[i - 1][j])) + 1;
    }
  }

  return dp[n1][n2];
}
<|endoftext|>


<commit_before>// Copyright (c) 2010 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/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/extensions/extension_test_message_listener.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/test/ui_test_utils.h"

const std::string kAllUrlsTarget =
    "files/extensions/api_test/all_urls/index.html";

typedef ExtensionApiTest AllUrlsApiTest;

// Note: This test is flaky, but is actively being worked on.
// See http://crbug.com/57694. Finnur is adding traces to figure out where the
// problem lies and needs to check in these traces because the problem doesn't
// repro locally (nor on the try bots).
IN_PROC_BROWSER_TEST_F(AllUrlsApiTest, WhitelistedExtension) {
  // First setup the two extensions.
  FilePath extension_dir1 = test_data_dir_.AppendASCII("all_urls")
                                          .AppendASCII("content_script");
  FilePath extension_dir2 = test_data_dir_.AppendASCII("all_urls")
                                          .AppendASCII("execute_script");

  // Then add the two extensions to the whitelist.
  Extension::ScriptingWhitelist whitelist;
  whitelist.push_back(Extension::GenerateIdForPath(extension_dir1));
  whitelist.push_back(Extension::GenerateIdForPath(extension_dir2));
  Extension::SetScriptingWhitelist(whitelist);

  // Then load extensions.
  ExtensionsService* service = browser()->profile()->GetExtensionsService();
  const size_t size_before = service->extensions()->size();
  printf("***** LoadExtension1 called \n");
  ASSERT_TRUE(LoadExtension(extension_dir1));
  printf("***** LoadExtension2 called \n");
  ASSERT_TRUE(LoadExtension(extension_dir2));
  printf("***** LoadExtensions done \n");
  EXPECT_EQ(size_before + 2, service->extensions()->size());

  std::string url;

  // Now verify we run content scripts on chrome://newtab/.
  url = "chrome://newtab/";
  printf("***** %s\n", url.c_str());
  ExtensionTestMessageListener listener1a("content script: " + url, false);
  ExtensionTestMessageListener listener1b("execute: " + url, false);
  ui_test_utils::NavigateToURL(browser(), GURL(url));
  printf("***** Wait 1a\n");
  ASSERT_TRUE(listener1a.WaitUntilSatisfied());
  printf("***** Wait 1b\n");
  ASSERT_TRUE(listener1b.WaitUntilSatisfied());

  // Now verify data: urls.
  url = "data:text/html;charset=utf-8,asdf";
  printf("***** %s\n", url.c_str());
  ExtensionTestMessageListener listener2a("content script: " + url, false);
  ExtensionTestMessageListener listener2b("execute: " + url, false);
  ui_test_utils::NavigateToURL(browser(), GURL(url));
  printf("***** Wait 2a\n");
  ASSERT_TRUE(listener2a.WaitUntilSatisfied());
  printf("***** Wait 2b\n");
  ASSERT_TRUE(listener2b.WaitUntilSatisfied());

  // Now verify about:version.
  url = "about:version";
  printf("***** %s\n", url.c_str());
  ExtensionTestMessageListener listener3a("content script: " + url, false);
  ExtensionTestMessageListener listener3b("execute: " + url, false);
  ui_test_utils::NavigateToURL(browser(), GURL(url));
  printf("***** Wait 3a\n");
  ASSERT_TRUE(listener3a.WaitUntilSatisfied());
  printf("***** Wait 3b\n");
  ASSERT_TRUE(listener3b.WaitUntilSatisfied());

  // Now verify about:blank.
  url = "about:blank";
  printf("***** %s\n", url.c_str());
  ExtensionTestMessageListener listener4a("content script: " + url, false);
  ExtensionTestMessageListener listener4b("execute: " + url, false);
  ui_test_utils::NavigateToURL(browser(), GURL(url));
  printf("***** Wait 4a\n");
  ASSERT_TRUE(listener4a.WaitUntilSatisfied());
  printf("***** Wait 4b\n");
  ASSERT_TRUE(listener4b.WaitUntilSatisfied());

  // Now verify we can script a regular http page.
  ASSERT_TRUE(test_server()->Start());
  GURL page_url = test_server()->GetURL(kAllUrlsTarget);
  printf("***** %s\n", page_url.spec().c_str());
  ExtensionTestMessageListener listener5a("content script: " + page_url.spec(),
                                          false);
  ExtensionTestMessageListener listener5b("execute: " + page_url.spec(), false);
  ui_test_utils::NavigateToURL(browser(), page_url);
  printf("***** Wait 5a\n");
  ASSERT_TRUE(listener5a.WaitUntilSatisfied());
  printf("***** Wait 5b\n");
  ASSERT_TRUE(listener5b.WaitUntilSatisfied());

  printf("***** DONE!\n");
}

// Test that an extension NOT whitelisted for scripting can ask for <all_urls>
// and run scripts on non-restricted all pages.
IN_PROC_BROWSER_TEST_F(AllUrlsApiTest, RegularExtensions) {
  // First load the two extension.
  FilePath extension_dir1 = test_data_dir_.AppendASCII("all_urls")
                                          .AppendASCII("content_script");
  FilePath extension_dir2 = test_data_dir_.AppendASCII("all_urls")
                                          .AppendASCII("execute_script");

  ExtensionsService* service = browser()->profile()->GetExtensionsService();
  const size_t size_before = service->extensions()->size();
  ASSERT_TRUE(LoadExtension(extension_dir1));
  ASSERT_TRUE(LoadExtension(extension_dir2));
  EXPECT_EQ(size_before + 2, service->extensions()->size());

  // Now verify we can script a regular http page.
  ASSERT_TRUE(test_server()->Start());
  GURL page_url = test_server()->GetURL(kAllUrlsTarget);
  ExtensionTestMessageListener listener1a("content script: " + page_url.spec(),
                                          false);
  ExtensionTestMessageListener listener1b("execute: " + page_url.spec(), false);
  ui_test_utils::NavigateToURL(browser(), page_url);
  ASSERT_TRUE(listener1a.WaitUntilSatisfied());
  ASSERT_TRUE(listener1b.WaitUntilSatisfied());
}
<commit_msg>Convert the traces in the WhitelistedExtension test.<commit_after>// Copyright (c) 2010 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/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/extensions/extension_test_message_listener.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/test/ui_test_utils.h"

const std::string kAllUrlsTarget =
    "files/extensions/api_test/all_urls/index.html";

typedef ExtensionApiTest AllUrlsApiTest;

namespace {

void Checkpoint(const char* message, const base::TimeTicks& start_time) {
  LOG(INFO) << message << " : "
            << (base::TimeTicks::Now() - start_time).InMilliseconds()
            << " ms" << std::flush;
}

}  // namespace

IN_PROC_BROWSER_TEST_F(AllUrlsApiTest, WhitelistedExtension) {
  base::TimeTicks start_time = base::TimeTicks::Now();
  Checkpoint("Setting up extensions", start_time);

  // First setup the two extensions.
  FilePath extension_dir1 = test_data_dir_.AppendASCII("all_urls")
                                          .AppendASCII("content_script");
  FilePath extension_dir2 = test_data_dir_.AppendASCII("all_urls")
                                          .AppendASCII("execute_script");

  // Then add the two extensions to the whitelist.
  Checkpoint("Setting up whitelist", start_time);
  Extension::ScriptingWhitelist whitelist;
  whitelist.push_back(Extension::GenerateIdForPath(extension_dir1));
  whitelist.push_back(Extension::GenerateIdForPath(extension_dir2));
  Extension::SetScriptingWhitelist(whitelist);

  // Then load extensions.
  Checkpoint("LoadExtension1", start_time);
  ExtensionsService* service = browser()->profile()->GetExtensionsService();
  const size_t size_before = service->extensions()->size();
  ASSERT_TRUE(LoadExtension(extension_dir1));
  Checkpoint("LoadExtension2", start_time);
  ASSERT_TRUE(LoadExtension(extension_dir2));
  EXPECT_EQ(size_before + 2, service->extensions()->size());

  std::string url;

  // Now verify we run content scripts on chrome://newtab/.
  Checkpoint("Verify content scripts", start_time);
  url = "chrome://newtab/";
  ExtensionTestMessageListener listener1a("content script: " + url, false);
  ExtensionTestMessageListener listener1b("execute: " + url, false);
  ui_test_utils::NavigateToURL(browser(), GURL(url));
  Checkpoint("Wait for 1a", start_time);
  ASSERT_TRUE(listener1a.WaitUntilSatisfied());
  Checkpoint("Wait for 1b", start_time);
  ASSERT_TRUE(listener1b.WaitUntilSatisfied());

  // Now verify data: urls.
  Checkpoint("Verify data:urls", start_time);
  url = "data:text/html;charset=utf-8,asdf";
  ExtensionTestMessageListener listener2a("content script: " + url, false);
  ExtensionTestMessageListener listener2b("execute: " + url, false);
  ui_test_utils::NavigateToURL(browser(), GURL(url));
  Checkpoint("Wait for 2a", start_time);
  ASSERT_TRUE(listener2a.WaitUntilSatisfied());
  Checkpoint("Wait for 2b", start_time);
  ASSERT_TRUE(listener2b.WaitUntilSatisfied());

  // Now verify about:version.
  Checkpoint("Verify about:version", start_time);
  url = "about:version";
  ExtensionTestMessageListener listener3a("content script: " + url, false);
  ExtensionTestMessageListener listener3b("execute: " + url, false);
  ui_test_utils::NavigateToURL(browser(), GURL(url));
  Checkpoint("Wait for 3a", start_time);
  ASSERT_TRUE(listener3a.WaitUntilSatisfied());
  Checkpoint("Wait for 3b", start_time);
  ASSERT_TRUE(listener3b.WaitUntilSatisfied());

  // Now verify about:blank.
  Checkpoint("Verify about:blank", start_time);
  url = "about:blank";
  ExtensionTestMessageListener listener4a("content script: " + url, false);
  ExtensionTestMessageListener listener4b("execute: " + url, false);
  ui_test_utils::NavigateToURL(browser(), GURL(url));
  Checkpoint("Wait for 4a", start_time);
  ASSERT_TRUE(listener4a.WaitUntilSatisfied());
  Checkpoint("Wait for 4b", start_time);
  ASSERT_TRUE(listener4b.WaitUntilSatisfied());

  // Now verify we can script a regular http page.
  Checkpoint("Verify regular http page", start_time);
  ASSERT_TRUE(test_server()->Start());
  GURL page_url = test_server()->GetURL(kAllUrlsTarget);
  ExtensionTestMessageListener listener5a("content script: " + page_url.spec(),
                                          false);
  ExtensionTestMessageListener listener5b("execute: " + page_url.spec(), false);
  ui_test_utils::NavigateToURL(browser(), page_url);
  Checkpoint("Wait for 5a", start_time);
  ASSERT_TRUE(listener5a.WaitUntilSatisfied());
  Checkpoint("Wait for 5ba", start_time);
  ASSERT_TRUE(listener5b.WaitUntilSatisfied());

  Checkpoint("Test complete", start_time);
}

// Test that an extension NOT whitelisted for scripting can ask for <all_urls>
// and run scripts on non-restricted all pages.
IN_PROC_BROWSER_TEST_F(AllUrlsApiTest, RegularExtensions) {
  // First load the two extension.
  FilePath extension_dir1 = test_data_dir_.AppendASCII("all_urls")
                                          .AppendASCII("content_script");
  FilePath extension_dir2 = test_data_dir_.AppendASCII("all_urls")
                                          .AppendASCII("execute_script");

  ExtensionsService* service = browser()->profile()->GetExtensionsService();
  const size_t size_before = service->extensions()->size();
  ASSERT_TRUE(LoadExtension(extension_dir1));
  ASSERT_TRUE(LoadExtension(extension_dir2));
  EXPECT_EQ(size_before + 2, service->extensions()->size());

  // Now verify we can script a regular http page.
  ASSERT_TRUE(test_server()->Start());
  GURL page_url = test_server()->GetURL(kAllUrlsTarget);
  ExtensionTestMessageListener listener1a("content script: " + page_url.spec(),
                                          false);
  ExtensionTestMessageListener listener1b("execute: " + page_url.spec(), false);
  ui_test_utils::NavigateToURL(browser(), page_url);
  ASSERT_TRUE(listener1a.WaitUntilSatisfied());
  ASSERT_TRUE(listener1b.WaitUntilSatisfied());
}
<|endoftext|>


<commit_before>AliAnalysisVertexingHF* ConfigVertexingHF() {

  printf("Call to AliAnalysisVertexingHF parameters setting :\n");
  vHF = new AliAnalysisVertexingHF();

  //--- switch-off candidates finding (default: all on)
  //vHF->SetD0toKpiOff();
  //vHF->SetJPSItoEleOff();
  //vHF->Set3ProngOff();
  vHF->SetLikeSignOff(); // like-sign pairs and triplets
  //vHF->Set4ProngOff();
  //vHF->SetDstarOff();
  vHF->SetFindVertexForDstar(kFALSE);
  //--- secondary vertex with KF?
  //vHF->SetSecVtxWithKF();
  //  vHF->SetCascadesOff();
  vHF->SetFindVertexForCascades(kFALSE);

  //--- set cuts for single-track selection
  //     displaced tracks
  AliESDtrackCuts *esdTrackCuts = new AliESDtrackCuts("AliESDtrackCuts","default");
  esdTrackCuts->SetRequireTPCRefit(kTRUE);
  esdTrackCuts->SetMinNClustersTPC(70);
  esdTrackCuts->SetRequireITSRefit(kTRUE);
  //esdTrackCuts->SetMinNClustersITS(4);
  esdTrackCuts->SetClusterRequirementITS(AliESDtrackCuts::kSPD,
					 AliESDtrackCuts::kAny);
  esdTrackCuts->SetMinDCAToVertexXY(0.);
  esdTrackCuts->SetPtRange(0.3,1.e10);
  esdTrackCuts->SetEtaRange(-0.8,+0.8);
  AliAnalysisFilter *trkFilter = new AliAnalysisFilter("trackFilter");
  trkFilter->AddCuts(esdTrackCuts);
  vHF->SetTrackFilter(trkFilter);
  //     D* soft pion tracks
  AliESDtrackCuts *esdTrackCutsSoftPi = new AliESDtrackCuts("AliESDtrackCuts","default");
  esdTrackCutsSoftPi->SetMinNClustersITS(2);
  esdTrackCutsSoftPi->SetEtaRange(-0.8,+0.8);
  AliAnalysisFilter *trkFilterSoftPi = new AliAnalysisFilter("trackFilterSoftPi");
  trkFilterSoftPi->AddCuts(esdTrackCutsSoftPi);
  vHF->SetTrackFilterSoftPi(trkFilterSoftPi);
  //--- set cuts for candidates selection
  AliRDHFCutsD0toKpi *cutsD0toKpi = new AliRDHFCutsD0toKpi("CutsD0toKpi");
  cutsD0toKpi->SetUsePhysicsSelection(kFALSE);
  cutsD0toKpi->SetMaxVtxZ(1.e6);
  cutsD0toKpi->SetTriggerClass("");
  Float_t cutsArrayD0toKpi[11]={0.3,999999.,1.1,0.,0.,999999.,999999.,999999.,0.,-1,0.};
  cutsD0toKpi->SetCuts(11,cutsArrayD0toKpi);
  cutsD0toKpi->AddTrackCuts(esdTrackCuts);
  vHF->SetCutsD0toKpi(cutsD0toKpi);
  AliRDHFCutsJpsitoee *cutsJpsitoee = new AliRDHFCutsJpsitoee("CutsJpsitoee");
  Float_t cutsArrayJpsitoee[9]={0.350,100000.,1.1,0.,0.,100000.,100000.,100000000.,-1.1};
  cutsJpsitoee->SetCuts(9,cutsArrayJpsitoee);
  cutsJpsitoee->AddTrackCuts(esdTrackCuts);
  vHF->SetCutsJpsitoee(cutsJpsitoee);
  AliRDHFCutsDplustoKpipi *cutsDplustoKpipi = new AliRDHFCutsDplustoKpipi("CutsDplustoKpipi");
  Float_t cutsArrayDplustoKpipi[14]={0.2,0.3,0.3,0.,0.,0.01,0.06,0.02,0.,0.7,0.,10000000000.,0.,-1.};
  cutsDplustoKpipi->SetCuts(14,cutsArrayDplustoKpipi);
  cutsDplustoKpipi->AddTrackCuts(esdTrackCuts);
  vHF->SetCutsDplustoKpipi(cutsDplustoKpipi);
  AliRDHFCutsDstoKKpi *cutsDstoKKpi = new AliRDHFCutsDstoKKpi("CutsDstoKKpi");
  Float_t cutsArrayDstoKKpi[16]={0.35,0.3,0.3,0.,0.,0.005,0.06,0.,0.,0.7,0.,1000.,0.1,0.1,-1.,1.};
  cutsDstoKKpi->SetCuts(16,cutsArrayDstoKKpi);
  cutsDstoKKpi->AddTrackCuts(esdTrackCuts);
  vHF->SetCutsDstoKKpi(cutsDstoKKpi);
  AliRDHFCutsLctopKpi *cutsLctopKpi = new AliRDHFCutsLctopKpi("CutsLctopKpi");
  //Float_t cutsArrayLctopKpi[12]={0.2,0.4,0.4,0.,0.,0.01,0.06,0.02,0.,0.85,0.,10000000000.};
  Float_t cutsArrayLctopKpi[13]={0.18,0.3,0.3,0.,0.,0.,0.06,0.,0.,-1.,0.,0.05,0.3};
  cutsLctopKpi->SetCuts(13,cutsArrayLctopKpi);
  cutsLctopKpi->AddTrackCuts(esdTrackCuts);
  vHF->SetCutsLctopKpi(cutsLctopKpi);
  AliRDHFCutsD0toKpipipi *cutsD0toKpipipi = new AliRDHFCutsD0toKpipipi("CutsD0toKpipipi");
  Float_t cutsArrayD0toKpipipi[9]={0.2,0.04,0.00,0.01,0.02,0.8,0.,0.1,0.};
  cutsD0toKpipipi->SetCuts(9,cutsArrayD0toKpipipi);
  cutsD0toKpipipi->AddTrackCuts(esdTrackCuts);
  vHF->SetCutsD0toKpipipi(cutsD0toKpipipi);
  AliRDHFCutsDStartoKpipi *cutsDStartoKpipi = new AliRDHFCutsDStartoKpipi("CutsDStartoKpipi");
  Float_t cutsArrayDStartoKpipi[16]={0.3,999999.,1.1,0.,0.,999999.,999999.,999999.,0.,0.3, 0.1, 0.05, 100000000000.0, 0.5,-1.,0.}; // first 9 for D0 from D*, next 5 for D*, last 2 for D0 again
  cutsDStartoKpipi->SetCuts(16,cutsArrayDStartoKpipi);
  cutsDStartoKpipi->AddTrackCuts(esdTrackCuts);
  cutsDStartoKpipi->AddTrackCutsSoftPi(esdTrackCutsSoftPi);
  vHF->SetCutsDStartoKpipi(cutsDStartoKpipi);
  AliRDHFCutsLctoV0 *cutsLctoV0 = new AliRDHFCutsLctoV0("CutsLctoV0");
  Float_t cutsArrayLctoV0[9]={4.0,4.0,2.0,2.0,0.0,0.0,0.0,1000.,1000.};
  cutsLctoV0->SetCuts(9,cutsArrayLctoV0);
  cutsLctoV0->AddTrackCuts(esdTrackCuts);
  vHF->SetCutsLctoV0(cutsLctoV0);
  //
  //--- set this if you want to reconstruct primary vertex candidate by
  //    candidate using other tracks in the event (for pp, broad
  //    interaction region)
  //vHF->SetRecoPrimVtxSkippingTrks();
  //--- OR set this if you want to remove the candidate daughters from
  //    the primary vertex, without recostructing it from scratch
  //vHF->SetRmTrksFromPrimVtx();

  //--- check the settings
  vHF->PrintStatus();
  //--- verbose
  //  AliLog::SetClassDebugLevel("AliAnalysisVertexingHF",2);

  return vHF;
}

<commit_msg>Updated cuts for Lc->V0+bachelor<commit_after>AliAnalysisVertexingHF* ConfigVertexingHF() {

  printf("Call to AliAnalysisVertexingHF parameters setting :\n");
  vHF = new AliAnalysisVertexingHF();

  //--- switch-off candidates finding (default: all on)
  //vHF->SetD0toKpiOff();
  //vHF->SetJPSItoEleOff();
  //vHF->Set3ProngOff();
  vHF->SetLikeSignOff(); // like-sign pairs and triplets
  //vHF->Set4ProngOff();
  //vHF->SetDstarOff();
  vHF->SetFindVertexForDstar(kFALSE);
  //--- secondary vertex with KF?
  //vHF->SetSecVtxWithKF();
  //vHF->SetCascadesOff();
  vHF->SetFindVertexForCascades(kTRUE);

  //--- set cuts for single-track selection
  //     displaced tracks
  AliESDtrackCuts *esdTrackCuts = new AliESDtrackCuts("AliESDtrackCuts","default");
  esdTrackCuts->SetRequireTPCRefit(kTRUE);
  esdTrackCuts->SetMinNClustersTPC(70);
  esdTrackCuts->SetRequireITSRefit(kTRUE);
  //esdTrackCuts->SetMinNClustersITS(4);
  esdTrackCuts->SetClusterRequirementITS(AliESDtrackCuts::kSPD,
					 AliESDtrackCuts::kAny);
  esdTrackCuts->SetMinDCAToVertexXY(0.);
  esdTrackCuts->SetPtRange(0.3,1.e10);
  esdTrackCuts->SetEtaRange(-0.8,+0.8);
  AliAnalysisFilter *trkFilter = new AliAnalysisFilter("trackFilter");
  trkFilter->AddCuts(esdTrackCuts);
  vHF->SetTrackFilter(trkFilter);
  //     D* soft pion tracks
  AliESDtrackCuts *esdTrackCutsSoftPi = new AliESDtrackCuts("AliESDtrackCuts","default");
  esdTrackCutsSoftPi->SetMinNClustersITS(2);
  esdTrackCutsSoftPi->SetEtaRange(-0.8,+0.8);
  AliAnalysisFilter *trkFilterSoftPi = new AliAnalysisFilter("trackFilterSoftPi");
  trkFilterSoftPi->AddCuts(esdTrackCutsSoftPi);
  vHF->SetTrackFilterSoftPi(trkFilterSoftPi);
  //--- set cuts for candidates selection
  AliRDHFCutsD0toKpi *cutsD0toKpi = new AliRDHFCutsD0toKpi("CutsD0toKpi");
  cutsD0toKpi->SetUsePhysicsSelection(kFALSE);
  cutsD0toKpi->SetMaxVtxZ(1.e6);
  cutsD0toKpi->SetTriggerClass("");
  Float_t cutsArrayD0toKpi[11]={0.3,999999.,1.1,0.,0.,999999.,999999.,999999.,0.,-1,0.};
  cutsD0toKpi->SetCuts(11,cutsArrayD0toKpi);
  cutsD0toKpi->AddTrackCuts(esdTrackCuts);
  vHF->SetCutsD0toKpi(cutsD0toKpi);
  AliRDHFCutsJpsitoee *cutsJpsitoee = new AliRDHFCutsJpsitoee("CutsJpsitoee");
  Float_t cutsArrayJpsitoee[9]={0.350,100000.,1.1,0.,0.,100000.,100000.,100000000.,-1.1};
  cutsJpsitoee->SetCuts(9,cutsArrayJpsitoee);
  cutsJpsitoee->AddTrackCuts(esdTrackCuts);
  vHF->SetCutsJpsitoee(cutsJpsitoee);
  AliRDHFCutsDplustoKpipi *cutsDplustoKpipi = new AliRDHFCutsDplustoKpipi("CutsDplustoKpipi");
  Float_t cutsArrayDplustoKpipi[14]={0.2,0.3,0.3,0.,0.,0.01,0.06,0.02,0.,0.7,0.,10000000000.,0.,-1.};
  cutsDplustoKpipi->SetCuts(14,cutsArrayDplustoKpipi);
  cutsDplustoKpipi->AddTrackCuts(esdTrackCuts);
  vHF->SetCutsDplustoKpipi(cutsDplustoKpipi);
  AliRDHFCutsDstoKKpi *cutsDstoKKpi = new AliRDHFCutsDstoKKpi("CutsDstoKKpi");
  Float_t cutsArrayDstoKKpi[16]={0.35,0.3,0.3,0.,0.,0.005,0.06,0.,0.,0.7,0.,1000.,0.1,0.1,-1.,1.};
  cutsDstoKKpi->SetCuts(16,cutsArrayDstoKKpi);
  cutsDstoKKpi->AddTrackCuts(esdTrackCuts);
  vHF->SetCutsDstoKKpi(cutsDstoKKpi);
  AliRDHFCutsLctopKpi *cutsLctopKpi = new AliRDHFCutsLctopKpi("CutsLctopKpi");
  //Float_t cutsArrayLctopKpi[12]={0.2,0.4,0.4,0.,0.,0.01,0.06,0.02,0.,0.85,0.,10000000000.};
  Float_t cutsArrayLctopKpi[13]={0.18,0.3,0.3,0.,0.,0.,0.06,0.,0.,-1.,0.,0.05,0.3};
  cutsLctopKpi->SetCuts(13,cutsArrayLctopKpi);
  cutsLctopKpi->AddTrackCuts(esdTrackCuts);
  vHF->SetCutsLctopKpi(cutsLctopKpi);
  AliRDHFCutsD0toKpipipi *cutsD0toKpipipi = new AliRDHFCutsD0toKpipipi("CutsD0toKpipipi");
  Float_t cutsArrayD0toKpipipi[9]={0.2,0.04,0.00,0.01,0.02,0.8,0.,0.1,0.};
  cutsD0toKpipipi->SetCuts(9,cutsArrayD0toKpipipi);
  cutsD0toKpipipi->AddTrackCuts(esdTrackCuts);
  vHF->SetCutsD0toKpipipi(cutsD0toKpipipi);
  AliRDHFCutsDStartoKpipi *cutsDStartoKpipi = new AliRDHFCutsDStartoKpipi("CutsDStartoKpipi");
  Float_t cutsArrayDStartoKpipi[16]={0.3,999999.,1.1,0.,0.,999999.,999999.,999999.,0.,0.3, 0.1, 0.05, 100000000000.0, 0.5,-1.,0.}; // first 9 for D0 from D*, next 5 for D*, last 2 for D0 again
  cutsDStartoKpipi->SetCuts(16,cutsArrayDStartoKpipi);
  cutsDStartoKpipi->AddTrackCuts(esdTrackCuts);
  cutsDStartoKpipi->AddTrackCutsSoftPi(esdTrackCutsSoftPi);
  vHF->SetCutsDStartoKpipi(cutsDStartoKpipi);
  AliRDHFCutsLctoV0 *cutsLctoV0 = new AliRDHFCutsLctoV0("CutsLctoV0");
  Float_t cutsArrayLctoV0[9]={1.0,1.0,0.05,0.05,0.0,0.0,0.0,1000.,1000.};
  cutsLctoV0->SetCuts(9,cutsArrayLctoV0);
  cutsLctoV0->AddTrackCuts(esdTrackCuts);
  vHF->SetCutsLctoV0(cutsLctoV0);
  //
  //--- set this if you want to reconstruct primary vertex candidate by
  //    candidate using other tracks in the event (for pp, broad
  //    interaction region)
  //vHF->SetRecoPrimVtxSkippingTrks();
  //--- OR set this if you want to remove the candidate daughters from
  //    the primary vertex, without recostructing it from scratch
  //vHF->SetRmTrksFromPrimVtx();

  //--- check the settings
  vHF->PrintStatus();
  //--- verbose
  //  AliLog::SetClassDebugLevel("AliAnalysisVertexingHF",2);

  return vHF;
}

<|endoftext|>


<commit_before>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2015.  All rights reserved
 */
#ifndef _Stroika_Foundation_Streams_BufferedInputStream_inl_
#define _Stroika_Foundation_Streams_BufferedInputStream_inl_  1

/*
 ********************************************************************************
 ***************************** Implementation Details ***************************
 ********************************************************************************
 */

#include    "../Debug/AssertExternallySynchronizedLock.h"

namespace   Stroika {
    namespace   Foundation {
        namespace   Streams {

            /*
             ********************************************************************************
             ******************** Streams::BufferedInputStream::Rep_ ************************
             ********************************************************************************
             */
            template    <typename ELEMENT_TYPE>
            class   BufferedInputStream<ELEMENT_TYPE>::Rep_ : public InputStream<ELEMENT_TYPE>::_IRep, private Debug::AssertExternallySynchronizedLock {
            public:
                Rep_ (const InputStream<ELEMENT_TYPE>& realIn)
                    : InputStream<ELEMENT_TYPE>::_IRep ()
                    , fRealIn_ (realIn)
                {
                }
                virtual bool    IsSeekable () const override
                {
                    return false;      // @todo - COULD be seekable if underlying fRealIn_ was!!!
                }
                virtual SeekOffsetType  GetReadOffset () const override
                {
                    RequireNotReached ();
                    return 0;
                }
                virtual SeekOffsetType  SeekRead (Whence whence, SignedSeekOffsetType offset) override
                {
                    RequireNotReached ();
                    return 0;
                }
                virtual size_t  Read (SeekOffsetType* offset, ELEMENT_TYPE* intoStart, ELEMENT_TYPE* intoEnd) override
                {
                    lock_guard<const AssertExternallySynchronizedLock> critSec { *this };
                    return fRealIn_.Read (intoStart, intoEnd);
                }

            private:
                mutable mutex               fCriticalSection_;
                InputStream<ELEMENT_TYPE>   fRealIn_;
            };

            /*
             ********************************************************************************
             ************************ Streams::BinaryInputStream ****************************
             ********************************************************************************
             */
            template    <typename ELEMENT_TYPE>
            BufferedInputStream<ELEMENT_TYPE>::BufferedInputStream (const InputStream<ELEMENT_TYPE>& realIn)
                : InputStream<ELEMENT_TYPE> (make_shared<Rep_> (realIn))
            {
            }

        }
    }
}
#endif  /*_Stroika_Foundation_Streams_BufferedInputStream_inl_*/
<commit_msg>lose fCriticalSection_; from Streams/BufferedInputStream<commit_after>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2015.  All rights reserved
 */
#ifndef _Stroika_Foundation_Streams_BufferedInputStream_inl_
#define _Stroika_Foundation_Streams_BufferedInputStream_inl_  1

/*
 ********************************************************************************
 ***************************** Implementation Details ***************************
 ********************************************************************************
 */

#include    "../Debug/AssertExternallySynchronizedLock.h"

namespace   Stroika {
    namespace   Foundation {
        namespace   Streams {

            /*
             ********************************************************************************
             ******************** Streams::BufferedInputStream::Rep_ ************************
             ********************************************************************************
             */
            template    <typename ELEMENT_TYPE>
            class   BufferedInputStream<ELEMENT_TYPE>::Rep_ : public InputStream<ELEMENT_TYPE>::_IRep, private Debug::AssertExternallySynchronizedLock {
            public:
                Rep_ (const InputStream<ELEMENT_TYPE>& realIn)
                    : InputStream<ELEMENT_TYPE>::_IRep ()
                    , fRealIn_ (realIn)
                {
                }
                virtual bool    IsSeekable () const override
                {
                    return false;      // @todo - COULD be seekable if underlying fRealIn_ was!!!
                }
                virtual SeekOffsetType  GetReadOffset () const override
                {
                    RequireNotReached ();
                    return 0;
                }
                virtual SeekOffsetType  SeekRead (Whence whence, SignedSeekOffsetType offset) override
                {
                    RequireNotReached ();
                    return 0;
                }
                virtual size_t  Read (SeekOffsetType* offset, ELEMENT_TYPE* intoStart, ELEMENT_TYPE* intoEnd) override
                {
                    lock_guard<const AssertExternallySynchronizedLock> critSec { *this };
                    return fRealIn_.Read (intoStart, intoEnd);
                }

            private:
                InputStream<ELEMENT_TYPE>   fRealIn_;
            };

            /*
             ********************************************************************************
             ************************ Streams::BinaryInputStream ****************************
             ********************************************************************************
             */
            template    <typename ELEMENT_TYPE>
            BufferedInputStream<ELEMENT_TYPE>::BufferedInputStream (const InputStream<ELEMENT_TYPE>& realIn)
                : InputStream<ELEMENT_TYPE> (make_shared<Rep_> (realIn))
            {
            }

        }
    }
}
#endif  /*_Stroika_Foundation_Streams_BufferedInputStream_inl_*/
<|endoftext|>


<commit_before>#include "RapidExternalEvtGen.h"

#include <cstdlib>
#include <fstream>
#include <queue>

#include "TRandom.h"
#include "TSystem.h"

#ifdef RAPID_EVTGEN
#include "EvtGen/EvtGen.hh"
#include "EvtGenBase/EvtRandomEngine.hh"
#include "EvtGenBase/EvtAbsRadCorr.hh"
#include "EvtGenBase/EvtDecayBase.hh"
#include "EvtGenBase/EvtParticle.hh"
#include "EvtGenBase/EvtParticleFactory.hh"
#include "EvtGenBase/EvtPatches.hh"
#include "EvtGenBase/EvtPDL.hh"
#include "EvtGenBase/EvtMTRandomEngine.hh"

#include "EvtGenExternal/EvtExternalGenList.hh"
#endif

bool RapidExternalEvtGen::decay(std::vector<RapidParticle*>& parts) {
#ifdef RAPID_EVTGEN
	EvtParticle* theParent(0);

	if(parts.size() < 1) {
		std::cout << "WARNING in RapidExternalEvtGen::decay : There are no particles to decay." << std::endl;
		return false;
	}
	EvtId theId = EvtPDL::evtIdFromLundKC(parts[0]->id());

	// Parent particle 4-momentum
	TLorentzVector pIn = parts[0]->getP();
	EvtVector4R pInit(pIn.E(),pIn.Px(),pIn.Py(),pIn.Pz());

	theParent = EvtParticleFactory::particleFactory(theId, pInit);
	if (theParent->getSpinStates() == 3) {theParent->setVectorSpinDensity();}

	// Generate the event
	evtGen_->generateDecay(theParent);

	// Store particles to read in the order RapidSim stores them
	std::queue<EvtParticle*> evtParts;
	// Also store the number of children expected for each of these particles so we can remove PHOTOS photons
	std::queue<int> nExpectedChildren;
	evtParts.push(theParent);
	nExpectedChildren.push(parts[0]->nDaughters());

	EvtVector4R x4Evt;
	EvtVector4R p4Evt;
	TLorentzVector p4TLV;

	int iPart=1; // The momentum and origin vertex of the first particle are already set

	while(!evtParts.empty()) {
		EvtParticle* theParticle = evtParts.front();

		// B0 and Bs may mix in EvtGen - RapidSim ignores this step and only records the second state
		while(theParticle->getNDaug()==1) {
			theParticle = theParticle->getDaug(0);
		}

		uint nChildren = nExpectedChildren.front();

		// Loop over the daughter tracks
		for (uint iChild = 0; iChild < nChildren; ++iChild) {
			EvtParticle* child = theParticle->getDaug(iChild);

			if (child != 0) {
				p4Evt = child->getP4Lab();
				x4Evt = child->get4Pos();
				p4TLV.SetPxPyPzE(p4Evt.get(1),p4Evt.get(2),p4Evt.get(3),p4Evt.get(0));
				if(parts.size() < iPart+1u) {
					std::cout << "WARNING in RapidExternalEvtGen::decay : EvtGen has produced too many particles." << std::endl;
					return false;
				}
				parts[iPart]->setP(p4TLV);
				parts[iPart]->getOriginVertex()->setXYZ(1e3*x4Evt.get(1),1e3*x4Evt.get(2),1e3*x4Evt.get(3));
				evtParts.push(child);
				nExpectedChildren.push(parts[iPart]->nDaughters());
				++iPart;
			}
		}

		// Clean up any PHOTOS photons
		for (uint iChild = nChildren; iChild < theParticle->getNDaug(); ++iChild) {
			delete theParticle->getDaug(iChild);
		}
		delete theParticle;
		evtParts.pop();
		nExpectedChildren.pop();
	}

	return true;
#else
	if(!suppressWarning_) {
		std::cout << "WARNING in RapidExternalEvtGen::decay : EvtGen extension not compiled. Will not use EvtGen to decay " << parts[0]->name() << "." << std::endl;
		suppressWarning_=true;
	}

	return false;
#endif
}

bool RapidExternalEvtGen::setup() {
#ifdef RAPID_EVTGEN
	std::cout << "INFO in RapidExternalEvtGen::setup : Setting decay for external EvtGen generator." << std::endl;
	if(!evtGen_) setupGenerator();
	evtGen_->readUDecay(decFileName_.Data());
	return true;
#else
	std::cout << "WARNING in RapidExternalEvtGen::setup : EvtGen extension not compiled." << std::endl;
	return false;
#endif
}

bool RapidExternalEvtGen::setupGenerator() {
#ifdef RAPID_EVTGEN
	std::cout << "INFO in RapidExternalEvtGen::setupGenerator : Setting up external EvtGen generator." << std::endl;
	EvtRandomEngine* randomEngine = 0;
	EvtAbsRadCorr* radCorrEngine = 0;
	std::list<EvtDecayBase*> extraModels;

	// Define the random number generator
	uint seed = gRandom->GetSeed();
	randomEngine = new EvtMTRandomEngine(seed);

	bool useEvtGenRandom(false);
	EvtExternalGenList genList(true, "", "gamma", useEvtGenRandom);
	radCorrEngine = genList.getPhotosModel();
	extraModels = genList.getListOfModels();

	TString evtPDLPath;
	evtPDLPath += getenv("EVTGEN_ROOT");
	evtPDLPath += "/evt.pdl";

	bool foundDec=false;

	TString decPath;
	decPath += getenv("RAPIDSIM_CONFIG");
	if(decPath!="") {
		decPath += "/config/evtgen/DECAY.DEC";
		if(!gSystem->AccessPathName(decPath)) foundDec=true;
	}

	// We want to initialise EvtGen before we define our DEC file so we can use EvtPDL
	// To do this pass an empty DEC file as the main decay file and pass our file later as a user file
	if(!foundDec) {
		decPath += getenv("RAPIDSIM_ROOT");
		decPath += "/config/evtgen/DECAY.DEC";
	}

	evtGen_ = new EvtGen(decPath.Data(), evtPDLPath.Data(), randomEngine,
			radCorrEngine, &extraModels);

	return true;
#else
	std::cout << "WARNING in RapidExternalEvtGen::setup : EvtGen extension not compiled." << std::endl;
	return false;
#endif
}

void RapidExternalEvtGen::writeDecFile(TString fname, std::vector<RapidParticle*>& parts, bool usePhotos) {
#ifdef RAPID_EVTGEN
	if(!evtGen_) setupGenerator();

	decFileName_ = fname+".DEC";
	std::cout << "INFO in RapidExternalEvtGen::writeDecFile : Writing EvtGen DEC file : " << decFileName_ << std::endl;

	std::ofstream fout;
	fout.open(decFileName_, std::ofstream::out);

	if(usePhotos) {
		fout << "yesPhotos\n" << std::endl;
	} else {
		fout << "noPhotos\n" << std::endl;
	}

	// Loop over all particles and write out Decay rule for each
	for(unsigned int iPart=0; iPart<parts.size(); ++iPart) {
		unsigned int nChildren = parts[iPart]->nDaughters();
		if(nChildren>0) {
			int id = parts[iPart]->id();
			fout << "Decay " << getEvtGenName(id) << "\n1.00\t";
			if ( !(parts[iPart]->evtGenDecayModel()).Contains("TAUOLA") ) {
				for(unsigned int iChild=0; iChild<nChildren; ++iChild) {
					fout << getEvtGenName(parts[iPart]->daughter(iChild)->id()) << "\t";
				}
			}
			fout << parts[iPart]->evtGenDecayModel() << ";" << std::endl;
			fout <<"Enddecay" << std::endl;

			// Workaround to deal with mixing of B0 and Bs
			if(TMath::Abs(id)==531||TMath::Abs(id)==511) fout <<"CDecay " << getEvtGenConjName(id) << std::endl << std::endl;
		}
	}
	fout <<"End\n" << std::endl;
	fout.close();
#else
	std::cout << "WARNING in RapidExternalEvtGen::writeDecFile : EvtGen extension not compiled. Cannot write DEC file "
		  << fname << " for " << parts.size() << "particles with usePhotos=" << usePhotos << "." << std::endl;
#endif
}

TString RapidExternalEvtGen::getEvtGenName(int id) {
#ifdef RAPID_EVTGEN
	EvtId evtId = EvtPDL::evtIdFromLundKC(id);
	TString name = EvtPDL::name(evtId);
	return name;
#else
	std::cout << "WARNING in RapidExternalEvtGen::getEvtGenName : EvtGen extension not compiled. Cannot lookup name for particle ID " << id << "." << std::endl;
	return "";
#endif
}

TString RapidExternalEvtGen::getEvtGenConjName(int id) {
#ifdef RAPID_EVTGEN
	EvtId evtId = EvtPDL::evtIdFromLundKC(id);
	EvtId evtConjId = EvtPDL::chargeConj(evtId);
	TString name = EvtPDL::name(evtConjId);
	return name;
#else
	std::cout << "WARNING in RapidExternalEvtGen::getEvtGenConjName : EvtGen extension not compiled. Cannot lookup conjugate name for particle ID " << id << "." << std::endl;
	return "";
#endif
}
<commit_msg>Update RapidExternalEvtGen.cc<commit_after>#include "RapidExternalEvtGen.h"

#include <cstdlib>
#include <fstream>
#include <queue>

#include "TRandom.h"
#include "TSystem.h"

#ifdef RAPID_EVTGEN
#include "EvtGen/EvtGen.hh"
#include "EvtGenBase/EvtRandomEngine.hh"
#include "EvtGenBase/EvtAbsRadCorr.hh"
#include "EvtGenBase/EvtDecayBase.hh"
#include "EvtGenBase/EvtParticle.hh"
#include "EvtGenBase/EvtParticleFactory.hh"
#include "EvtGenBase/EvtPatches.hh"
#include "EvtGenBase/EvtPDL.hh"
#include "EvtGenBase/EvtMTRandomEngine.hh"

#include "EvtGenExternal/EvtExternalGenList.hh"
#endif

bool RapidExternalEvtGen::decay(std::vector<RapidParticle*>& parts) {
#ifdef RAPID_EVTGEN
	EvtParticle* theParent(0);

	if(parts.size() < 1) {
		std::cout << "WARNING in RapidExternalEvtGen::decay : There are no particles to decay." << std::endl;
		return false;
	}
	EvtId theId = EvtPDL::evtIdFromLundKC(parts[0]->id());

	// Parent particle 4-momentum
	TLorentzVector pIn = parts[0]->getP();
	EvtVector4R pInit(pIn.E(),pIn.Px(),pIn.Py(),pIn.Pz());

	theParent = EvtParticleFactory::particleFactory(theId, pInit);
	if (theParent->getSpinStates() == 3) {theParent->setVectorSpinDensity();}

	// Generate the event
	evtGen_->generateDecay(theParent);

	// Store particles to read in the order RapidSim stores them
	std::queue<EvtParticle*> evtParts;
	// Also store the number of children expected for each of these particles so we can remove PHOTOS photons
	std::queue<int> nExpectedChildren;
	evtParts.push(theParent);
	nExpectedChildren.push(parts[0]->nDaughters());

	EvtVector4R x4Evt;
	EvtVector4R p4Evt;
	TLorentzVector p4TLV;

	int iPart=1; // The momentum and origin vertex of the first particle are already set

	while(!evtParts.empty()) {
		EvtParticle* theParticle = evtParts.front();

		// B0 and Bs may mix in EvtGen - RapidSim ignores this step and only records the second state
		while(theParticle->getNDaug()==1) {
			theParticle = theParticle->getDaug(0);
		}

		uint nChildren = nExpectedChildren.front();

		// Loop over the daughter tracks
		for (uint iChild = 0; iChild < nChildren; ++iChild) {
			EvtParticle* child = theParticle->getDaug(iChild);

			if (child != 0) {
				p4Evt = child->getP4Lab();
				x4Evt = child->get4Pos();
				p4TLV.SetPxPyPzE(p4Evt.get(1),p4Evt.get(2),p4Evt.get(3),p4Evt.get(0));
				if(parts.size() < iPart+1u) {
					std::cout << "WARNING in RapidExternalEvtGen::decay : EvtGen has produced too many particles." << std::endl;
					return false;
				}
				parts[iPart]->setP(p4TLV);
				parts[iPart]->getOriginVertex()->setXYZ(x4Evt.get(1),x4Evt.get(2),x4Evt.get(3));
				evtParts.push(child);
				nExpectedChildren.push(parts[iPart]->nDaughters());
				++iPart;
			}
		}

		// Clean up any PHOTOS photons
		for (uint iChild = nChildren; iChild < theParticle->getNDaug(); ++iChild) {
			delete theParticle->getDaug(iChild);
		}
		delete theParticle;
		evtParts.pop();
		nExpectedChildren.pop();
	}

	return true;
#else
	if(!suppressWarning_) {
		std::cout << "WARNING in RapidExternalEvtGen::decay : EvtGen extension not compiled. Will not use EvtGen to decay " << parts[0]->name() << "." << std::endl;
		suppressWarning_=true;
	}

	return false;
#endif
}

bool RapidExternalEvtGen::setup() {
#ifdef RAPID_EVTGEN
	std::cout << "INFO in RapidExternalEvtGen::setup : Setting decay for external EvtGen generator." << std::endl;
	if(!evtGen_) setupGenerator();
	evtGen_->readUDecay(decFileName_.Data());
	return true;
#else
	std::cout << "WARNING in RapidExternalEvtGen::setup : EvtGen extension not compiled." << std::endl;
	return false;
#endif
}

bool RapidExternalEvtGen::setupGenerator() {
#ifdef RAPID_EVTGEN
	std::cout << "INFO in RapidExternalEvtGen::setupGenerator : Setting up external EvtGen generator." << std::endl;
	EvtRandomEngine* randomEngine = 0;
	EvtAbsRadCorr* radCorrEngine = 0;
	std::list<EvtDecayBase*> extraModels;

	// Define the random number generator
	uint seed = gRandom->GetSeed();
	randomEngine = new EvtMTRandomEngine(seed);

	bool useEvtGenRandom(false);
	EvtExternalGenList genList(true, "", "gamma", useEvtGenRandom);
	radCorrEngine = genList.getPhotosModel();
	extraModels = genList.getListOfModels();

	TString evtPDLPath;
	evtPDLPath += getenv("EVTGEN_ROOT");
	evtPDLPath += "/evt.pdl";

	bool foundDec=false;

	TString decPath;
	decPath += getenv("RAPIDSIM_CONFIG");
	if(decPath!="") {
		decPath += "/config/evtgen/DECAY.DEC";
		if(!gSystem->AccessPathName(decPath)) foundDec=true;
	}

	// We want to initialise EvtGen before we define our DEC file so we can use EvtPDL
	// To do this pass an empty DEC file as the main decay file and pass our file later as a user file
	if(!foundDec) {
		decPath += getenv("RAPIDSIM_ROOT");
		decPath += "/config/evtgen/DECAY.DEC";
	}

	evtGen_ = new EvtGen(decPath.Data(), evtPDLPath.Data(), randomEngine,
			radCorrEngine, &extraModels);

	return true;
#else
	std::cout << "WARNING in RapidExternalEvtGen::setup : EvtGen extension not compiled." << std::endl;
	return false;
#endif
}

void RapidExternalEvtGen::writeDecFile(TString fname, std::vector<RapidParticle*>& parts, bool usePhotos) {
#ifdef RAPID_EVTGEN
	if(!evtGen_) setupGenerator();

	decFileName_ = fname+".DEC";
	std::cout << "INFO in RapidExternalEvtGen::writeDecFile : Writing EvtGen DEC file : " << decFileName_ << std::endl;

	std::ofstream fout;
	fout.open(decFileName_, std::ofstream::out);

	if(usePhotos) {
		fout << "yesPhotos\n" << std::endl;
	} else {
		fout << "noPhotos\n" << std::endl;
	}

	// Loop over all particles and write out Decay rule for each
	for(unsigned int iPart=0; iPart<parts.size(); ++iPart) {
		unsigned int nChildren = parts[iPart]->nDaughters();
		if(nChildren>0) {
			int id = parts[iPart]->id();
			fout << "Decay " << getEvtGenName(id) << "\n1.00\t";
			if ( !(parts[iPart]->evtGenDecayModel()).Contains("TAUOLA") ) {
				for(unsigned int iChild=0; iChild<nChildren; ++iChild) {
					fout << getEvtGenName(parts[iPart]->daughter(iChild)->id()) << "\t";
				}
			}
			fout << parts[iPart]->evtGenDecayModel() << ";" << std::endl;
			fout <<"Enddecay" << std::endl;

			// Workaround to deal with mixing of B0 and Bs
			if(TMath::Abs(id)==531||TMath::Abs(id)==511) fout <<"CDecay " << getEvtGenConjName(id) << std::endl << std::endl;
		}
	}
	fout <<"End\n" << std::endl;
	fout.close();
#else
	std::cout << "WARNING in RapidExternalEvtGen::writeDecFile : EvtGen extension not compiled. Cannot write DEC file "
		  << fname << " for " << parts.size() << "particles with usePhotos=" << usePhotos << "." << std::endl;
#endif
}

TString RapidExternalEvtGen::getEvtGenName(int id) {
#ifdef RAPID_EVTGEN
	EvtId evtId = EvtPDL::evtIdFromLundKC(id);
	TString name = EvtPDL::name(evtId);
	return name;
#else
	std::cout << "WARNING in RapidExternalEvtGen::getEvtGenName : EvtGen extension not compiled. Cannot lookup name for particle ID " << id << "." << std::endl;
	return "";
#endif
}

TString RapidExternalEvtGen::getEvtGenConjName(int id) {
#ifdef RAPID_EVTGEN
	EvtId evtId = EvtPDL::evtIdFromLundKC(id);
	EvtId evtConjId = EvtPDL::chargeConj(evtId);
	TString name = EvtPDL::name(evtConjId);
	return name;
#else
	std::cout << "WARNING in RapidExternalEvtGen::getEvtGenConjName : EvtGen extension not compiled. Cannot lookup conjugate name for particle ID " << id << "." << std::endl;
	return "";
#endif
}
<|endoftext|>


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

#include "chrome/browser/net/sdch_dictionary_fetcher.h"

#include "chrome/browser/profile.h"
#include "net/url_request/url_request_status.h"

void SdchDictionaryFetcher::Schedule(const GURL& dictionary_url) {
  // Avoid pushing duplicate copy onto queue.  We may fetch this url again later
  // and get a different dictionary, but there is no reason to have it in the
  // queue twice at one time.
  if (!fetch_queue_.empty() && fetch_queue_.back() == dictionary_url) {
    SdchManager::SdchErrorRecovery(
        SdchManager::DICTIONARY_ALREADY_SCHEDULED_TO_DOWNLOAD);
    return;
  }
  fetch_queue_.push(dictionary_url);
  ScheduleDelayedRun();
}

void SdchDictionaryFetcher::ScheduleDelayedRun() {
  if (fetch_queue_.empty() || current_fetch_.get() || task_is_pending_)
    return;
  MessageLoop::current()->PostDelayedTask(FROM_HERE,
      method_factory_.NewRunnableMethod(&SdchDictionaryFetcher::StartFetching),
      kMsDelayFromRequestTillDownload);
  task_is_pending_ = true;
}

void SdchDictionaryFetcher::StartFetching() {
  DCHECK(task_is_pending_);
  task_is_pending_ = false;

  current_fetch_.reset(new URLFetcher(fetch_queue_.front(), URLFetcher::GET,
                                      this));
  fetch_queue_.pop();
  current_fetch_->set_request_context(Profile::GetDefaultRequestContext());
  current_fetch_->Start();
}

void SdchDictionaryFetcher::OnURLFetchComplete(const URLFetcher* source,
                                               const GURL& url,
                                               const URLRequestStatus& status,
                                               int response_code,
                                               const ResponseCookies& cookies,
                                               const std::string& data) {
  if ((200 == response_code) && (status.status() == URLRequestStatus::SUCCESS))
    SdchManager::Global()->AddSdchDictionary(data, url);
  current_fetch_.reset(NULL);
  ScheduleDelayedRun();
}
<commit_msg>Protect dictionary fetch operation in shutdown scenario.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/net/sdch_dictionary_fetcher.h"

#include "chrome/browser/profile.h"
#include "net/url_request/url_request_status.h"

void SdchDictionaryFetcher::Schedule(const GURL& dictionary_url) {
  // Avoid pushing duplicate copy onto queue.  We may fetch this url again later
  // and get a different dictionary, but there is no reason to have it in the
  // queue twice at one time.
  if (!fetch_queue_.empty() && fetch_queue_.back() == dictionary_url) {
    SdchManager::SdchErrorRecovery(
        SdchManager::DICTIONARY_ALREADY_SCHEDULED_TO_DOWNLOAD);
    return;
  }
  fetch_queue_.push(dictionary_url);
  ScheduleDelayedRun();
}

void SdchDictionaryFetcher::ScheduleDelayedRun() {
  if (fetch_queue_.empty() || current_fetch_.get() || task_is_pending_)
    return;
  MessageLoop::current()->PostDelayedTask(FROM_HERE,
      method_factory_.NewRunnableMethod(&SdchDictionaryFetcher::StartFetching),
      kMsDelayFromRequestTillDownload);
  task_is_pending_ = true;
}

void SdchDictionaryFetcher::StartFetching() {
  DCHECK(task_is_pending_);
  task_is_pending_ = false;

  URLRequestContext* context = Profile::GetDefaultRequestContext();
  if (!context) {
    // Shutdown in progress.
    // Simulate handling of all dictionary requests by clearing queue.
    while (!fetch_queue_.empty())
      fetch_queue_.pop();
    return;
  }

  current_fetch_.reset(new URLFetcher(fetch_queue_.front(), URLFetcher::GET,
                                      this));
  fetch_queue_.pop();
  current_fetch_->set_request_context(context);
  current_fetch_->Start();
}

void SdchDictionaryFetcher::OnURLFetchComplete(const URLFetcher* source,
                                               const GURL& url,
                                               const URLRequestStatus& status,
                                               int response_code,
                                               const ResponseCookies& cookies,
                                               const std::string& data) {
  if ((200 == response_code) && (status.status() == URLRequestStatus::SUCCESS))
    SdchManager::Global()->AddSdchDictionary(data, url);
  current_fetch_.reset(NULL);
  ScheduleDelayedRun();
}
<|endoftext|>