text:
// -*- C++ -*-

//=============================================================================
/**
 *  @file    Service_Config_Test.cpp
 *
 *  $Id: Service_Config_Test.cpp 84175 2009-01-15 18:52:34Z johnnyw $
 *
 *  This is a simple test to make sure the ACE Service Configurator
 *  framework is working correctly.
 *
 *  @author David Levine <levine@cs.wustl.edu>
 *  @author Ossama Othman <ossama@uci.edu>
 */
//=============================================================================

#include "test_config.h"
#include "ace/OS_NS_stdio.h"
#include "ace/OS_NS_errno.h"
#include "ace/OS_NS_Thread.h"
#include "ace/Log_Msg.h"
#include "ace/Object_Manager.h"
#include "ace/Service_Config.h"
#include "ace/Service_Object.h"
#include "ace/Service_Repository.h"
#include "ace/Service_Types.h"
#include "ace/Reactor.h"
#include "ace/Thread_Manager.h"
#include "ace/ARGV.h"

ACE_RCSID (tests,
           Service_Config_Test,
           "$Id: Service_Config_Test.cpp 84175 2009-01-15 18:52:34Z johnnyw $")

static const u_int VARIETIES = 3;

static u_int error = 0;

class MyRepository : public ACE_Service_Repository
{
public:
  array_type& array ()
  {
    return service_array_;
  }
};

/**
 * @class Test_Singleton
 *
 * @brief Test the Singleton
 *
 * This should be a template class, with singleton instantiations.
 * But to avoid having to deal with compilers that want template
 * declarations in separate files, it's just a plain class.  The
 * instance argument differentiates the "singleton" instances.  It
 * also demonstrates the use of the param arg to the cleanup ()
 * function.
 */
class Test_Singleton
{
public:
  static Test_Singleton *instance (u_short variety);
  ~Test_Singleton (void);

private:
  u_short variety_;
  static u_short current_;

  Test_Singleton (u_short variety);

  friend class misspelled_verbase_friend_declaration_to_avoid_compiler_warning_with_private_ctor;
};

u_short Test_Singleton::current_ = 0;

extern "C" void
test_singleton_cleanup (void *object, void *)
{
  // We can't reliably use ACE_Log_Msg in a cleanup hook.  Yet.
  /* ACE_DEBUG ((LM_DEBUG, "cleanup %d\n", (u_short) param)); */

  delete (Test_Singleton *) object;
}

Test_Singleton *
Test_Singleton::instance (u_short variety)
{
  static Test_Singleton *instances[VARIETIES] = { 0 };

  if (instances[variety] == 0)
    {
      ACE_NEW_RETURN (instances[variety],
                      Test_Singleton (variety),
                      0);
    }

  ACE_Object_Manager::at_exit (instances[variety],
                               test_singleton_cleanup,
                  reinterpret_cast<void *> (static_cast<size_t> (variety)),
                  "Test_Singleton");
  return instances[variety];
}

Test_Singleton::Test_Singleton (u_short variety)
  : variety_ (variety)
{
  if (variety_ != current_++)
    {
      ACE_DEBUG ((LM_ERROR,
                  ACE_TEXT ("ERROR: instance %u created out of order!\n"),
                 variety_));
      ++error;
    }
}

// We can't reliably use ACE_Log_Msg in a destructor that is called by
// ACE_Object_Manager.  Yet.

Test_Singleton::~Test_Singleton (void)
{
  /* ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("Test_Singleton %u dtor\n"), variety_)); */

  if (variety_ != --current_)
    {
      ACE_OS::fprintf (stderr,
                       ACE_TEXT ("ERROR: instance %u destroyed out of order!\n"),
                       variety_);
      /* ACE_DEBUG ((LM_ERROR, ACE_TEXT ("ERROR: instance %u destroyed out of order!\n"),
                 variety_)); */
      ++error;
    }
}

void
testFailedServiceInit (int, ACE_TCHAR *[])
{
  static const ACE_TCHAR *refuse_svc =
#if (ACE_USES_CLASSIC_SVC_CONF == 1)
    ACE_TEXT ("dynamic Refuses_Svc Service_Object * ")
    ACE_TEXT ("  Service_Config_DLL:_make_Refuses_Init() \"\"")
#else
    ACE_TEXT ("<dynamic id=\"Refuses_Svc\" type=\"Service_Object\">")
    ACE_TEXT ("  <initializer init=\"_make_Refuses_Init\" path=\"Service_Config_DLL\" params=\"\"/>")
    ACE_TEXT ("</dynamic>")
#endif /* (ACE_USES_CLASSIC_SVC_CONF == 1) */
    ;

  int error_count = 0;
  if ((error_count = ACE_Service_Config::process_directive (refuse_svc)) != 1)
    {
      ++error;
      ACE_ERROR ((LM_ERROR,
                  ACE_TEXT ("Failed init test should have returned 1; ")
                  ACE_TEXT ("returned %d instead\n"),
                  error_count));
    }

  // Try to find the service; it should not be there.
  ACE_Service_Type const *svcp = 0;
  if (-1 != ACE_Service_Repository::instance ()->find (ACE_TEXT ("Refuses_Svc"),
                                                       &svcp))
    {
      ++error;
      ACE_ERROR ((LM_ERROR,
                  ACE_TEXT ("Found service repo entry for Refuses_Svc\n")));
      ACE_Service_Type_Impl const *svc_impl = svcp->type ();
      ACE_TCHAR msg[1024];
      ACE_TCHAR *msgp = msg;
      if (svc_impl->info (&msgp, sizeof (msg) / sizeof (ACE_TCHAR)) > 0)
        ACE_ERROR ((LM_ERROR, ACE_TEXT ("Refuses_Svc said: %s\n"), msg));
    }
  else
    ACE_DEBUG ((LM_DEBUG,
                ACE_TEXT ("Repo reports no Refuses_Svc; correct.\n")));
}

void
testLoadingServiceConfFileAndProcessNo (int argc, ACE_TCHAR *argv[])
{
  ACE_ARGV new_argv;

#if defined (ACE_USES_WCHAR)
  // When using full Unicode support, use the version of the Service
  // Configurator file appropriate to the platform.
  // For example, Windows Unicode uses UTF-16.
  //
  //          iconv(1) found on Linux and Solaris, for example, can
  //          be used to convert between encodings.
  //
  //          Byte ordering is also an issue, so we should be
  //          generating this file on-the-fly from the UTF-8 encoded
  //          file by using functions like iconv(1) or iconv(3).
#  if defined (ACE_WIN32)
  const ACE_TCHAR svc_conf[] =
    ACE_TEXT ("Service_Config_Test.UTF-16")
    ACE_TEXT (ACE_DEFAULT_SVC_CONF_EXT);
#  else
  const ACE_TCHAR svc_conf[] =
    ACE_TEXT ("Service_Config_Test.WCHAR_T")
    ACE_TEXT (ACE_DEFAULT_SVC_CONF_EXT);
#  endif /* ACE_WIN32 */
#else
    // ASCII (UTF-8) encoded Service Configurator file.
  const ACE_TCHAR svc_conf[] =
    ACE_TEXT ("Service_Config_Test")
    ACE_TEXT (ACE_DEFAULT_SVC_CONF_EXT);
#endif  /* ACE_USES_WCHAR */

  // Process the Service Configurator directives in this test's Making
  // sure we have more than one option with an argument, to capture
  // any errors caused by "reshuffling" of the options.
  if (new_argv.add (argv) == -1
              || new_argv.add (ACE_TEXT ("-d")) == -1
              || new_argv.add (ACE_TEXT ("-k")) == -1
              || new_argv.add (ACE_TEXT ("xxx")) == -1
              || new_argv.add (ACE_TEXT ("-p")) == -1
              || new_argv.add (ACE_TEXT ("Service_Config_Test.pid")) == -1
              || new_argv.add (ACE_TEXT ("-f")) == -1
              || new_argv.add (svc_conf) == -1)
    {
      ACE_ERROR ((LM_ERROR,
                  ACE_TEXT ("line %l %p\n"),
                  ACE_TEXT ("new_argv.add")));
      ++error;
    }

  // We need this scope to make sure that the destructor for the
  // <ACE_Service_Config> gets called.
  ACE_Service_Config daemon;

  if (daemon.open (new_argv.argc (), new_argv.argv ()) == -1 &&
      errno != ENOENT)
    {
      ACE_ERROR ((LM_ERROR,
                  ACE_TEXT ("line %l %p\n"),
                  ACE_TEXT ("daemon.open")));
      ++error;
    }

  ACE_Time_Value tv (argc > 1 ? ACE_OS::atoi (argv[1]) : 2);

  if (ACE_Reactor::instance()->run_reactor_event_loop (tv) == -1)
    {
      ++error;
      ACE_ERROR ((LM_ERROR,
                  ACE_TEXT ("line %l %p\n"),
                  ACE_TEXT ("run_reactor_event_loop")));
    }

  // Wait for all threads to complete.
  ACE_Thread_Manager::instance ()->wait ();
}

void
testLoadingServiceConfFile (int argc, ACE_TCHAR *argv[])
{
  ACE_ARGV new_argv;

#if defined (ACE_USES_WCHAR)
  // When using full Unicode support, use the version of the Service
  // Configurator file appropriate to the platform.
  // For example, Windows Unicode uses UTF-16.
  //
  //          iconv(1) found on Linux and Solaris, for example, can
  //          be used to convert between encodings.
  //
  //          Byte ordering is also an issue, so we should be
  //          generating this file on-the-fly from the UTF-8 encoded
  //          file by using functions like iconv(1) or iconv(3).
#  if defined (ACE_WIN32)
  const ACE_TCHAR svc_conf[] =
    ACE_TEXT ("Service_Config_Test.UTF-16")
    ACE_TEXT (ACE_DEFAULT_SVC_CONF_EXT);
#  else
  const ACE_TCHAR svc_conf[] =
    ACE_TEXT ("Service_Config_Test.WCHAR_T")
    ACE_TEXT (ACE_DEFAULT_SVC_CONF_EXT);
#  endif /* ACE_WIN32 */
#else
    // ASCII (UTF-8) encoded Service Configurator file.
  const ACE_TCHAR svc_conf[] =
    ACE_TEXT ("Service_Config_Test")
    ACE_TEXT (ACE_DEFAULT_SVC_CONF_EXT);
#endif  /* ACE_USES_WCHAR */

  // Process the Service Configurator directives in this test's
  if (new_argv.add (argv) == -1
              || new_argv.add (ACE_TEXT ("-f")) == -1
              || new_argv.add (svc_conf) == -1)
    {
      ACE_ERROR ((LM_ERROR,
                  ACE_TEXT ("line %l %p\n"),
                  ACE_TEXT ("new_argv.add")));
      ++error;
    }

  // We need this scope to make sure that the destructor for the
  // <ACE_Service_Config> gets called.
  ACE_Service_Config daemon;

  if (daemon.open (new_argv.argc (), new_argv.argv ()) == -1)
    {
      if (errno == ENOENT)
        ACE_DEBUG ((LM_WARNING,
                    ACE_TEXT ("ACE_Service_Config::open: %p\n"),
                    svc_conf));
      else
        ACE_ERROR ((LM_ERROR,
                    ACE_TEXT ("ACE_Service_Config::open: %p\n"),
                    ACE_TEXT ("error")));
    }

  ACE_Time_Value tv (argc > 1 ? ACE_OS::atoi (argv[1]) : 2);

  if (ACE_Reactor::instance()->run_reactor_event_loop (tv) == -1)
    {
      ++error;
      ACE_ERROR ((LM_ERROR,
                  ACE_TEXT ("line %l %p\n"),
                  ACE_TEXT ("run_reactor_event_loop")));
    }

  // Wait for all threads to complete.
  ACE_Thread_Manager::instance ()->wait ();
}

// @brief The size of a repository is unlimited and can be exceeded
void
testLimits (int , ACE_TCHAR *[])
{
  static const ACE_TCHAR *svc_desc1 =
#if (ACE_USES_CLASSIC_SVC_CONF == 1)
    ACE_TEXT ("dynamic Test_Object_1_More Service_Object * ")
    ACE_TEXT ("  Service_Config_DLL:_make_Service_Config_DLL() \"Test_Object_1_More\"")
#else
    ACE_TEXT ("<dynamic id=\"Test_Object_1_More\" type=\"Service_Object\">")
    ACE_TEXT ("  <initializer init=\"_make_Service_Config_DLL\" path=\"Service_Config_DLL\" params=\"Test_Object_1_More\"/>")
    ACE_TEXT ("</dynamic>")
#endif /* (ACE_USES_CLASSIC_SVC_CONF == 1) */
    ;

  static const ACE_TCHAR *svc_desc2 =
#if (ACE_USES_CLASSIC_SVC_CONF == 1)
    ACE_TEXT ("dynamic Test_Object_2_More Service_Object * ")
    ACE_TEXT ("  Service_Config_DLL:_make_Service_Config_DLL() \"Test_Object_2_More\"")
#else
    ACE_TEXT ("<dynamic id=\"Test_Object_2_More\" type=\"Service_Object\">")
    ACE_TEXT ("  <initializer init=\"_make_Service_Config_DLL\" path=\"Service_Config_DLL\" params=\"Test_Object_2_More\"/>")
    ACE_TEXT ("</dynamic>")
#endif /* (ACE_USES_CLASSIC_SVC_CONF == 1) */
    ;

  u_int error0 = error;

  // Ensure enough room for one in a own, the repository can extend
  ACE_Service_Gestalt one (1, true);

  // Add two.
  // We cant simply rely on the fact that insertion fails, because it
  // is typical to have no easy way of getting detailed error
  // information from a parser.
  one.process_directive (svc_desc1);
  one.process_directive (svc_desc2);

  if (-1 == one.find (ACE_TEXT ("Test_Object_1_More"), 0, 0))
    {
      ++error;
      ACE_ERROR ((LM_ERROR, ACE_TEXT("Expected to have registered the first service\n")));
    }

  if (-1 == one.find (ACE_TEXT ("Test_Object_2_More"), 0, 0))
    {
      ++error;
      ACE_ERROR ((LM_ERROR, ACE_TEXT("Expected to have registered the second service\n")));
    }

  ACE_Service_Repository_Iterator sri (*one.current_service_repository (), 0);

  size_t index = 0;
  for (const ACE_Service_Type *sr;
       sri.next (sr) != 0;
       sri.advance ())
    {
      if (index == 0 && ACE_OS::strcmp (sr->name(), ACE_TEXT ("Test_Object_1_More")) != 0)
        {
          ++error;
          ACE_ERROR ((LM_ERROR, ACE_TEXT("Service 1 is wrong\n")));
        }
      if (index == 1 && ACE_OS::strcmp (sr->name(), ACE_TEXT ("Test_Object_2_More")) != 0)
        {
          ++error;
          ACE_ERROR ((LM_ERROR, ACE_TEXT("Service 2 is wrong\n")));
        }
      ++index;
    }

  // Test close
  one.current_service_repository ()->close();

  if (one.current_service_repository ()->current_size () != 0)
    {
      ++error;
      ACE_ERROR ((LM_ERROR, ACE_TEXT("Size of repository should be 0\n")));
    }

  if (error == error0)
    ACE_DEBUG ((LM_DEBUG, ACE_TEXT("Limits test completed successfully\n")));
  else
    ACE_DEBUG ((LM_DEBUG, ACE_TEXT("Limits test failed\n")));

}

void
testrepository (int, ACE_TCHAR *[])
{
  MyRepository repository;
  ACE_DLL handle;
  ACE_Service_Type s0 (ACE_TEXT ("0"), 0, handle, false);
  ACE_Service_Type s1 (ACE_TEXT ("1"), 0, handle, false);
  ACE_Service_Type s2 (ACE_TEXT ("2"), 0, handle, false);
  ACE_Service_Type s3 (ACE_TEXT ("3"), 0, handle, false);
  ACE_Service_Type* result = 0;
  repository.insert (&s0);
  if (repository.current_size () != 1)
    {
      ++error;
      ACE_ERROR ((LM_ERROR,
                  ACE_TEXT ("Repository was wrong size %d\n"),
                  repository.current_size ()));
    }
  repository.insert (&s1);
  if (repository.current_size () != 2)
    {
      ++error;
      ACE_ERROR ((LM_ERROR,
                  ACE_TEXT ("Repository was wrong size %d\n"),
                  repository.current_size ()));
    }
  repository.insert (&s2);
  if (repository.current_size () != 3)
    {
      ++error;
      ACE_ERROR ((LM_ERROR,
                  ACE_TEXT ("Repository was wrong size %d\n"),
                  repository.current_size ()));
    }
  if (repository.remove (ACE_TEXT ("1"), &result) != 0)
    {
      ++error;
      ACE_ERROR ((LM_ERROR,
                  ACE_TEXT ("Remove failed\n")));
    }
  if (repository.current_size () != 3)
    {
      ++error;
      ACE_ERROR ((LM_ERROR,
                  ACE_TEXT ("Repository was wrong size %d\n"),
                  repository.current_size ()));
    }
  if (repository.array ()[1] != 0)
    {
      ++error;
      ACE_ERROR ((LM_ERROR,
                  ACE_TEXT ("Element 1 not zero\n"),
                  repository.current_size ()));
    }
  repository.insert (&s3);
  if (repository.current_size () != 4)
    {
      ++error;
      ACE_ERROR ((LM_ERROR,
                  ACE_TEXT ("Repository was wrong size %d\n"),
                  repository.current_size ()));
    }
  repository.remove (ACE_TEXT ("0"), &result);
  if (repository.remove (ACE_TEXT ("1"), &result) != -1)
    {
      ++error;
      ACE_ERROR ((LM_ERROR,
                  ACE_TEXT ("Double remove didn't return -1\n")));
    }
  repository.remove (ACE_TEXT ("2"), &result);
  repository.remove (ACE_TEXT ("3"), &result);
  if (repository.current_size () != 4)
    {
      ++error;
      ACE_ERROR ((LM_ERROR,
                  ACE_TEXT ("Repository was wrong size %d\n"),
                  repository.current_size ()));
    }
  repository.close ();
  if (repository.current_size () != 0)
    {
      ++error;
      ACE_ERROR ((LM_ERROR,
                  ACE_TEXT ("Repository was wrong size %d\n"),
                  repository.current_size ()));
    }
}

// @brief ??
void
testOrderlyInstantiation (int , ACE_TCHAR *[])
{
  for (u_int i = 0; i < VARIETIES; ++i)
    {
      Test_Singleton *s = Test_Singleton::instance (i);

      if (s == 0)
        {
          ++error;
          ACE_ERROR ((LM_ERROR,
                      ACE_TEXT ("instance () allocate failed!\n")));
        }
    }
}

// This test verifies that services loaded by a normal ACE startup can be
// located from a thread spawned outside of ACE's control.
//
// To do this, we need a native thread entry and, thus, it needs special care
// for each platform type. Feel free to add more platforms as needed here and
// in main() where the test is called.
#if defined (ACE_HAS_WTHREADS) || defined (ACE_HAS_PTHREADS_STD)
#  if defined (ACE_HAS_WTHREADS)
extern "C" unsigned int __stdcall
#  else
extern "C" ACE_THR_FUNC_RETURN
#  endif
nonacethreadentry (void *args)
{
  ACE_Log_Msg::inherit_hook (0, *(ACE_OS_Log_Msg_Attributes *)args);

  if (ACE_Service_Config::instance()->find(ACE_TEXT("Test_Object_1_Thr")) != 0)
    {
      ACE_ERROR ((LM_ERROR,
                  ACE_TEXT ("In thr %t cannot find Test_Object_1_Thr ")
                  ACE_TEXT ("via ACE_Service_Config\n")));
      ++error;
    }
  else
    ACE_DEBUG ((LM_DEBUG,
                ACE_TEXT ("In thr %t, located Test_Object_1_Thr ")
                ACE_TEXT ("via ACE_Service_Config\n")));

  if (0 != ACE_Service_Repository::instance()->find
      (ACE_TEXT("Test_Object_1_Thr")))
    {
      ACE_ERROR ((LM_ERROR,
                  ACE_TEXT ("In thr %t cannot find Test_Object_1_Thr ")
                  ACE_TEXT ("via ACE_Service_Repository\n")));
      ++error;
    }
  else
    ACE_DEBUG ((LM_DEBUG,
                ACE_TEXT ("In thr %t, located Test_Object_1_Thr ")
                ACE_TEXT ("via ACE_Service_Repository\n")));

  return 0;
}

void
testNonACEThread ()
{
  ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("Beginning non-ACE thread lookup test\n")));

  static const ACE_TCHAR *svc_desc =
#if (ACE_USES_CLASSIC_SVC_CONF == 1)
    ACE_TEXT ("dynamic Test_Object_1_Thr Service_Object * ")
    ACE_TEXT ("  Service_Config_DLL:_make_Service_Config_DLL() \"Test_Object_1_Thr\"")
#else
    ACE_TEXT ("<dynamic id=\"Test_Object_1_Thr\" type=\"Service_Object\">")
    ACE_TEXT ("  <initializer init=\"_make_Service_Config_DLL\" path=\"Service_Config_DLL\" params=\"Test_Object_1_Thr\"/>")
    ACE_TEXT ("</dynamic>")
#endif /* (ACE_USES_CLASSIC_SVC_CONF == 1) */
    ;

  static const ACE_TCHAR *svc_remove =
#if (ACE_USES_CLASSIC_SVC_CONF == 1)
    ACE_TEXT ("remove Test_Object_1_Thr")
#else
    ACE_TEXT ("<remove id=\"Test_Object_1_Thr\"/>")
    ACE_TEXT ("</remove>")
#endif /* (ACE_USES_CLASSIC_SVC_CONF == 1) */
    ;

  if (-1 == ACE_Service_Config::process_directive (svc_desc))
    {
      ACE_ERROR ((LM_ERROR,
                  ACE_TEXT ("%p\n"),
                  ACE_TEXT ("Error loading service")));
      ++error;
      return;
    }

  // Allow the spawned thread to contribute to the logging output.
  ACE_OS_Log_Msg_Attributes log_msg_attrs;
  ACE_Log_Msg::init_hook (log_msg_attrs);

  u_int errors_before = error;

#if defined (ACE_HAS_WTHREADS) && !defined (ACE_HAS_WINCE)
  HANDLE thr_h = (HANDLE)_beginthreadex (0,
                                         0,
                                         &nonacethreadentry,
                                         &log_msg_attrs,
                                         0,
                                         0);
  if (thr_h == 0)
    {
      ACE_ERROR ((LM_ERROR, ACE_TEXT ("%p\n"), ACE_TEXT ("_beginthreadex")));
    }
  else
    {
      WaitForSingleObject (thr_h, INFINITE);
      CloseHandle (thr_h);
    }
#elif defined (ACE_HAS_PTHREADS_STD)
  pthread_t thr_id;
  int status = pthread_create (&thr_id, 0, nonacethreadentry, &log_msg_attrs);
  if (status != 0)
    {
      errno = status;
      ACE_ERROR ((LM_ERROR, ACE_TEXT ("%p\n"), ACE_TEXT ("pthread_create")));
    }
  else
    {
      pthread_join (thr_id, 0);
    }
#endif

  if (error != errors_before)  // The test failed; see if we can still see it
    {
      if (0 != ACE_Service_Config::instance()->find
          (ACE_TEXT ("Test_Object_1_Thr")))
        ACE_ERROR ((LM_ERROR,
                    ACE_TEXT ("Main thr %t cannot find Test_Object_1_Thr\n")));
      else
        ACE_DEBUG ((LM_DEBUG,
                    ACE_TEXT ("Main thr %t DOES find Test_Object_1_Thr\n")));
    }

  if (-1 == ACE_Service_Config::process_directive (svc_remove))
    {
      ACE_ERROR ((LM_ERROR,
                  ACE_TEXT ("%p\n"),
                  ACE_TEXT ("Error removing service")));
      ++error;
      return;
    }
  ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("Non-ACE thread lookup test completed\n")));
}
#endif /* ACE_HAS_WTHREADS || ACE_HAS_PTHREADS_STD */

int
run_main (int argc, ACE_TCHAR *argv[])
{
  ACE_START_TEST (ACE_TEXT ("Service_Config_Test"));

  testOrderlyInstantiation (argc, argv);
  testFailedServiceInit (argc, argv);
  testLoadingServiceConfFile (argc, argv);
  testLoadingServiceConfFileAndProcessNo (argc, argv);
  testLimits (argc, argv);
  testrepository (argc, argv);
#if defined (ACE_HAS_WTHREADS) || defined (ACE_HAS_PTHREADS_STD)
  testNonACEThread();
#endif

  ACE_END_TEST;
  return error;
}


text:
<?php
return array (
  'Your account has been successfully created!' => 'Jūsų paskyra sėkmingai sukurta!',
  'After activating your account by the administrator, you will receive a notification by email.' => 'Kai administratorius aktyvuos Jūsų anketą, elektroniniu paštu Jums bus atsiųstas pranešimas.',
  'Go to login page' => 'Eikite į registracijos puslapį',
  'To log in with your new account, click the button below.' => 'Norint prisiregistruoti naująja paskyra, paspauskite žemiau esantį mygtuką.',
  'back to home' => 'atgal į namų puslapį',
);

redpajama_set_name: RedPajamaGithub


text:
exec_program(hadoop ARGS version OUTPUT_VARIABLE Hadoop_VERSION
             RETURN_VALUE Hadoop_RETURN)

# Only look in HADOOP_INCLUDE_DIR
find_path(HDFS_INCLUDE_DIR hdfs.h PATHS
  $ENV{HADOOP_INCLUDE_DIR}
  # make sure we don't accidentally pick up a different version
  NO_DEFAULT_PATH
)

if ("${CMAKE_SIZEOF_VOID_P}" STREQUAL "8")
  set(arch_hint "x64")
elseif ("$ENV{LIB}" MATCHES "(amd64|ia64)")
  set(arch_hint "x64")
else ()
  set(arch_hint "x86")
endif()

set(HDFS_LIB_PATHS $ENV{HADOOP_LIB_DIR}/native)

if (NOT HDFS_FIND_QUIETLY)
  message(STATUS "Architecture: ${arch_hint}")
  message(STATUS "HDFS_LIB_PATHS: ${HDFS_LIB_PATHS}")
endif()

find_library(HDFS_STATIC_LIB NAMES libhdfs.a PATHS
  ${HDFS_LIB_PATHS}
  # make sure we don't accidentally pick up a different version
  NO_DEFAULT_PATH
  )
find_library(HDFS_SHARED_LIB NAMES libhdfs.so PATHS
  ${HDFS_LIB_PATHS}
  # make sure we don't accidentally pick up a different version
  NO_DEFAULT_PATH
  )

if (HDFS_STATIC_LIB AND HDFS_SHARED_LIB)
  set(HDFS_FOUND TRUE)
else ()
  set(HDFS_FOUND FALSE)
endif ()

if (HDFS_FOUND)
  if (NOT HDFS_FIND_QUIETLY)
    message(STATUS "${Hadoop_VERSION}")
    message(STATUS "HDFS_INCLUDE_DIR: ${HDFS_INCLUDE_DIR}")
    message(STATUS "HDFS_STATIC_LIB: ${HDFS_STATIC_LIB}")
    message(STATUS "HDFS_SHARED_LIB: ${HDFS_SHARED_LIB}")
  endif ()
else ()
  message(FATAL_ERROR "HDFS includes and libraries NOT found. "
    "${HDFS_INCLUDE_DIR}, ${HDFS_LIB})")
endif ()

mark_as_advanced(
  HDFS_STATIC_LIB
  HDFS_SHARED_LIB
  HDFS_INCLUDE_DIR
  HDFS_STATIC
)


text:
<!DOCTYPE html>

  <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">

  <meta charset="utf-8">

  <title>My responsive blog: picture story</title>

  <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700" rel="stylesheet" type="text/css">
  <link rel="stylesheet" href="../style/main.css" />

      <picture>
        <source media="(min-width: 750px)" srcset="../images/postcard-1600_large_2x.jpg 2x, ../images/postcard-800_large_1x.jpg" />
        <source media="(min-width: 500px)" srcset="../images/postcard_medium.jpg" />

      </picture>

        Pecorino pepper jack cheesy feet. Smelly cheese cauliflower cheese fromage
        halloumi cream cheese who moved my cheese fromage fondue. Feta danish fontina
        cheesy grin mozzarella fromage cheesy grin airedale paneer. Cheddar halloumi
        cheese and biscuits jarlsberg cheese and biscuits cheese and biscuits squirty
        cheese.

      My Blog Post


text:
<polymer-element
  name="favicon-image"
  attributes="icon suffix sizes msTileColor"
>

<template>

  <template bind if="{{msTileColor}}">
    <meta name="msapplication-TileColor" content="{{msTileColor}}">
  </template>

  <template repeat="{{size in sizes}}">

    <template repeat="{{appleTouchIconSize in appleTouchIconSizes}}">
      <template if="{{size == appleTouchIconSize}}">
        <link rel="apple-touch-icon" sizes="{{size}}x{{size}}" href="{{icon}}-{{size}}x{{size}}.{{suffix}}">
      </template>
    </template>

    <template repeat="{{iconSize in iconSizes}}">
      <template if="{{size == iconSize}}">
        <link rel="icon" type="image/{{suffix}}" sizes="{{size}}x{{size}}" href="{{icon}}-{{size}}x{{size}}.{{suffix}}">
      </template>
    </template>

    <template repeat="{{msTileSize in msTileSizes}}">
      <template if="{{size == msTileSize}}">
        <link rel="icon" type="image/{{suffix}}" sizes="{{size}}x{{size}}" href="{{icon}}-{{size}}x{{size}}.{{suffix}}">
      </template>
    </template>

  </template>

</template>

<script>
  Polymer('favicon-image', {
    appleTouchIconSizes: [57, 114, 72, 144, 60, 120, 76, 152],
    iconSizes: [196, 160, 96, 16, 32],
    msTileColor: '#ffffff',
    msTileSizes: [144],
    suffix: 'png',
    ready: function(){
      this.sizes = eval(this.sizes) || [];
    }
  });
</script>
</polymer-element>


text:
package org.drip.measure.discretemarginal;

/*
 * -*- mode: java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
 */

/*!
 * Copyright (C) 2017 Lakshmi Krishnamurthy
 * Copyright (C) 2016 Lakshmi Krishnamurthy
 * Copyright (C) 2015 Lakshmi Krishnamurthy
 *
 *  This file is part of DRIP, a free-software/open-source library for buy/side financial/trading model
 *  	libraries targeting analysts and developers
 *  	https://lakshmidrip.github.io/DRIP/
 *
 *  DRIP is composed of four main libraries:
 *
 *  - DRIP Fixed Income - https://lakshmidrip.github.io/DRIP-Fixed-Income/
 *  - DRIP Asset Allocation - https://lakshmidrip.github.io/DRIP-Asset-Allocation/
 *  - DRIP Numerical Optimizer - https://lakshmidrip.github.io/DRIP-Numerical-Optimizer/
 *  - DRIP Statistical Learning - https://lakshmidrip.github.io/DRIP-Statistical-Learning/
 *
 *  - DRIP Fixed Income: Library for Instrument/Trading Conventions, Treasury Futures/Options,
 *  	Funding/Forward/Overnight Curves, Multi-Curve Construction/Valuation, Collateral Valuation and XVA
 *  	Metric Generation, Calibration and Hedge Attributions, Statistical Curve Construction, Bond RV
 *  	Metrics, Stochastic Evolution and Option Pricing, Interest Rate Dynamics and Option Pricing, LMM
 *  	Extensions/Calibrations/Greeks, Algorithmic Differentiation, and Asset Backed Models and Analytics.
 *
 *  - DRIP Asset Allocation: Library for model libraries for MPT framework, Black Litterman Strategy
 *  	Incorporator, Holdings Constraint, and Transaction Costs.
 *
 *  - DRIP Numerical Optimizer: Library for Numerical Optimization and Spline Functionality.
 *
 *  - DRIP Statistical Learning: Library for Statistical Evaluation and Machine Learning.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *   	you may not use this file except in compliance with the License.
 *
 *  You may obtain a copy of the License at
 *  	http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  	distributed under the License is distributed on an "AS IS" BASIS,
 *  	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *
 *  See the License for the specific language governing permissions and
 *  	limitations under the License.
 */

/**
 * PoissonDistribution implements the Univariate Poisson Distribution using the specified Mean/Variance.
 *
 * @author Lakshmi Krishnamurthy
 */

public class PoissonDistribution extends org.drip.measure.continuousmarginal.R1 {
	private double _dblLambda = java.lang.Double.NaN;
	private double _dblExponentialLambda = java.lang.Double.NaN;

	/**
	 * Construct a PoissonDistribution Instance
	 *
	 * @param dblLambda Lambda
	 *
	 * @throws java.lang.Exception Thrown if the inputs are invalid
	 */

	public PoissonDistribution (
		final double dblLambda)
		throws java.lang.Exception
	{
		if (!org.drip.quant.common.NumberUtil.IsValid (_dblLambda = dblLambda) || 0. >= _dblLambda)
			throw new java.lang.Exception ("PoissonDistribution constructor: Invalid inputs");

		_dblExponentialLambda = java.lang.Math.exp (-1. * _dblLambda);
	}

	/**
	 * Retrieve Lambda
	 *
	 * @return Lambda
	 */

	public double lambda()
	{
		return _dblLambda;
	}

	@Override public double cumulative (
		final double dblX)
		throws java.lang.Exception
	{
		if (!org.drip.quant.common.NumberUtil.IsValid (dblX))
			throw new java.lang.Exception ("PoissonDistribution::cumulative => Invalid inputs");

		int iEnd = (int) dblX;
		double dblYLocal = 1.;
		double dblYCumulative = 0.;

		for (int i = 1; i < iEnd; ++i) {
			i = i + 1;
			dblYLocal *= _dblLambda / i;
			dblYCumulative += _dblExponentialLambda * dblYLocal;
		}

		return dblYCumulative;
	}

	@Override public double incremental (
		final double dblXLeft,
		final double dblXRight)
		throws java.lang.Exception
	{
		return cumulative (dblXRight) - cumulative (dblXLeft);
	}

	@Override public double invCumulative (
		final double dblY)
		throws java.lang.Exception
	{
		if (!org.drip.quant.common.NumberUtil.IsValid (dblY))
			throw new java.lang.Exception ("PoissonDistribution::invCumulative => Invalid inputs");

		int i = 0;
		double dblYLocal = 1.;
		double dblYCumulative = 0.;

		while (dblYCumulative < dblY) {
			i = i + 1;
			dblYLocal *= _dblLambda / i;
			dblYCumulative += _dblExponentialLambda * dblYLocal;
		}

		return i - 1;
	}

	@Override public double density (
		final double dblX)
		throws java.lang.Exception
	{
		throw new java.lang.Exception
			("PoissonDistribution::density => Not available for discrete distributions");
	}

	@Override public double mean()
	{
	    return _dblLambda;
	}

	@Override public double variance()
	{
	    return _dblLambda;
	}

	@Override public org.drip.quant.common.Array2D histogram()
	{
		return null;
	}
}


text:
package com.orientechnologies.orient.client.remote.message;

import com.orientechnologies.orient.client.binary.OBinaryRequestExecutor;
import com.orientechnologies.orient.client.remote.OBinaryRequest;
import com.orientechnologies.orient.client.remote.OBinaryResponse;
import com.orientechnologies.orient.client.remote.OStorageRemote;
import com.orientechnologies.orient.client.remote.OStorageRemoteSession;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.serialization.serializer.record.ORecordSerializer;
import com.orientechnologies.orient.core.serialization.serializer.record.binary.ORecordSerializerNetworkV37Client;
import com.orientechnologies.orient.enterprise.channel.binary.OChannelBinaryProtocol;
import com.orientechnologies.orient.enterprise.channel.binary.OChannelDataInput;
import com.orientechnologies.orient.enterprise.channel.binary.OChannelDataOutput;
import java.io.IOException;
import java.util.Map;

/** Created by tglman on 17/05/17. */
public class OSubscribeLiveQueryRequest implements OBinaryRequest<OSubscribeLiveQueryResponse> {

  private String query;
  private Map<String, Object> params;
  private boolean namedParams;

  public OSubscribeLiveQueryRequest(String query, Map<String, Object> params) {
    this.query = query;
    this.params = params;
    this.namedParams = true;
  }

  public OSubscribeLiveQueryRequest(String query, Object[] params) {
    this.query = query;
    this.params = OStorageRemote.paramsArrayToParamsMap(params);
    this.namedParams = false;
  }

  public OSubscribeLiveQueryRequest() {}

  @Override
  public void write(OChannelDataOutput network, OStorageRemoteSession session) throws IOException {
    ORecordSerializerNetworkV37Client serializer = new ORecordSerializerNetworkV37Client();
    network.writeString(query);
    // params
    ODocument parms = new ODocument();
    parms.field("params", this.params);

    byte[] bytes = OMessageHelper.getRecordBytes(parms, serializer);
    network.writeBytes(bytes);
    network.writeBoolean(namedParams);
  }

  @Override
  public void read(OChannelDataInput channel, int protocolVersion, ORecordSerializer serializer)
      throws IOException {
    this.query = channel.readString();
    ODocument paramsDoc = new ODocument();
    byte[] bytes = channel.readBytes();
    serializer.fromStream(bytes, paramsDoc, null);
    this.params = paramsDoc.field("params");
    this.namedParams = channel.readBoolean();
  }

  @Override
  public byte getCommand() {
    return OChannelBinaryProtocol.SUBSCRIBE_PUSH_LIVE_QUERY;
  }

  @Override
  public OSubscribeLiveQueryResponse createResponse() {
    return new OSubscribeLiveQueryResponse();
  }

  @Override
  public OBinaryResponse execute(OBinaryRequestExecutor executor) {
    return executor.executeSubscribeLiveQuery(this);
  }

  @Override
  public String getDescription() {
    return null;
  }

  public String getQuery() {
    return query;
  }

  public Map<String, Object> getParams() {
    return params;
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

 File:      $RCSfile: generate.xml,v $
 Version:   $Revision: 1.10 $
 Modified:  $Date: 2011/05/30 20:20:45 $

 (c) Copyright 2005-2014 by Mentor Graphics Corp.  All rights reserved.

-->
<project name="mc-java.test" default="all" basedir=".">
	<target name="all" description="Run verify select test" depends="sql,java,sql_cond_test,java_cond_test">
	</target>

	<property name="eclipse-home" value="${basedir}/../.." />

	<property environment="env" />
	<property name="bp_bin_dir" value="${env.PT_HOME_DRIVE}${env.PT_HOME}\bin" />
    <property name="mc_bin_dir" value="${env.PT_HOME_DRIVE}${env.PT_HOME}\mc3020\bin" />

	<property name="sql.input" value="../models/MC-Java.test/verify_sel" />
	<property name="sql.output" value="verify_sel.sql" />

	<property name="subsystems_to_remove" value="ACT_ V_ E_" />

	<target name="sql.depends">
		<uptodate property="sql.buildNotNeeded" value="yes" targetfile="sql/${sql.output}">
	 	     <srcfiles dir= "${sql.input}" includes="**/*.xtuml" />
		  </uptodate>
	</target>

	<target name="sql" depends="sql.depends" description="Generate the sql version of verify select model" unless="sql.buildNotNeeded">
		<echo>Generating ${sql.output} ...</echo>
		<exec vmlauncher="false" failonerror="true" executable="${mc_bin_dir}\xtumlmc_build.exe" >
				<arg line="xtumlmc_cleanse_for_BridgePoint ${sql.input} sql/${sql.output} ${subsystems_to_remove}" />
		</exec>
	</target>

	<property name="sql_cond_test.input" value="verify_sel_cond_test.xtuml" />
	<property name="sql_cond_test.output" value="verify_sel_cond_test.sql" />

	<target name="sql_cond_test.depends">
		<uptodate property="sql_cond_test.buildNotNeeded" value="yes" srcfile="../models/${sql_cond_test.input}" targetfile="sql/${sql_cond_test.output}" />
	</target>

	<target name="sql_cond_test" depends="sql_cond_test.depends" description="Generate the sql version of verify select conditionality test model" unless="sql_cond_test.buildNotNeeded">
		<echo>Generating ${sql_cond_test.output} ...</echo>
		<copy file="../models/${sql_cond_test.input}" tofile="sql/${sql_cond_test.output}" />
	</target>

	<property name="mcj_path" value="../../MC-Java" />
	<property file="${mcj_path}/mc_java.depends" />

	<property name="sg_tj.dep" value="ooa_schema.sql,${pg_schema_gen.arc.depends}" />
	<property name="schema.output" value="verify_sel_pg_schema.sql" />
	<property name="schema_cond_test.output" value="verify_sel_cond_test_pg_schema.sql" />

	<target name="schema.depends">
		<uptodate property="schema.buildNotNeeded" targetfile="sql/${schema.output}">
			<srcfiles dir="sql" includes="${sql.output}" />
			<srcfiles dir="${mcj_path}" includes="${sg_tj.dep}" />
		</uptodate>
	</target>

	<target name="schema" depends="schema.depends" description="Generate the verify select test database schema file" unless="schema.buildNotNeeded">
		<echo>Generating ${schema.output} ...</echo>
		<ant antfile="${mcj_path}/build.xml" target="generate.db.schema">
			<property name="param1" value="${sql.output}" />
			<property name="param2" value="${mcj_path}" />
		</ant>
		<!-- Need to touch the output file for the case where the input data
	     changed, but the output didn't -->
		<touch file="sql/${schema.output}" />
	</target>

	<target name="schema_cond_test.depends">
		<uptodate property="schema_cond_test.buildNotNeeded" targetfile="sql/${schema_cond_test.output}">
			<srcfiles dir="sql" includes="${sql.output}" />
			<srcfiles dir="${mcj_path}" includes="${sg_tj.dep}" />
		</uptodate>
	</target>

	<target name="schema_cond_test" depends="schema_cond_test.depends" description="Generate the verify select conditionality test database schema file" unless="schema_cond_test.buildNotNeeded">
		<echo>Generating ${schema_cond_test.output} ...</echo>
		<ant antfile="${mcj_path}/build.xml" target="generate.db.schema">
			<property name="param1" value="${sql.output}" />
			<property name="param2" value="${mcj_path}" />
		</ant>
		<!-- Need to touch the output file for the case where the input data
	     changed, but the output didn't -->
		<touch file="sql/${schema_cond_test.output}" />
	</target>

	<property name="java.sql.dep" value="${sql.output}" />
	<property name="java.color.dep" value="verify_sel_startspec.clr,verify_sel_import_spec.clr,verify_sel_package_spec.clr" />
	<property name="java_cond_test.sql.dep" value="${sql_cond_test.output}" />
	<property name="java_cond_test.color.dep" value="verify_sel_cond_test_startspec.clr,verify_sel_cond_test_import_spec.clr,verify_sel_cond_test_package_spec.clr" />

	<property name="java.tj.dep" value="ooa_schema.sql,${ooa_oal_pop.arc.depends},${java.arc.depends}" />

	<property name="java.output" value="src/Verify_sel.java" />
	<property name="java_cond_test.output" value="src/Verify_sel_cond_test.java" />

	<target name="java.depends">
		<uptodate property="java.buildNotNeeded" targetfile="${java.output}">
			<srcfiles dir="sql" includes="${java.sql.dep}" />
			<srcfiles dir="color" includes="${java.color.dep}" />
			<srcfiles dir="${mcj_path}" includes="${java.tj.dep}" />
		</uptodate>
	</target>

	<target name="java_cond_test.depends">
		<uptodate property="java_cond_test.buildNotNeeded" targetfile="${java_cond_test.output}">
			<srcfiles dir="sql" includes="${java_cond_test.sql.dep}" />
			<srcfiles dir="color" includes="${java_cond_test.color.dep}" />
			<srcfiles dir="${mcj_path}" includes="${java.tj.dep}" />
		</uptodate>
	</target>

	<target name="java" description="Generate java code for this project" depends="java.depends" unless="java.buildNotNeeded">
		<echo>Generating java files ...</echo>
		<ant antfile="${mcj_path}/build.xml" target="generate.java">
			<property name="param1" value="verify_sel" />
			<property name="param2" value="Verify_sel" />
			<property name="param3" value="${mcj_path}" />
			<property name="verify_selects" value="true" />
		</ant>
		<!-- Need to touch the output file for the case where the input data
	     changed, but the output didn't -->
		<touch file="${java.output}" />
	</target>

	<target name="java_cond_test" description="Generate java code for this project" depends="java_cond_test.depends" unless="java_cond_test.buildNotNeeded">
		<echo>Generating java files ...</echo>
		<ant antfile="${mcj_path}/build.xml" target="generate.java">
			<property name="param1" value="verify_sel_cond_test" />
			<property name="param2" value="Verify_sel_cond_test" />
			<property name="param3" value="${mcj_path}" />
			<property name="verify_selects" value="true" />
			<property name="persist" value="-nopersist" />
		</ant>
		<!-- Need to touch the output file for the case where the input data
	     changed, but the output didn't -->
		<touch file="${java_cond_test.output}" />
	</target>

	<taskdef name="Compare" classname="CompareTask" classpath="../tools" />

	<target name="compare_verifyselect_results" description="Compare verify selects output to expected results">

		<Compare firstfile="expected_results/verify_sel_verify_selects_output.txt" secondfile="verify_sel_verify_selects_output.txt" />
	</target>

	<target name="compare_verifyselectcond_results" description="Compare verify selects output to expected results">

		<Compare firstfile="expected_results/verify_sel_cond_test_verify_selects_output.txt" secondfile="verify_sel_cond_test_verify_selects_output.txt" />
	</target>

	<!-- Clean Targets -->

	<target name="clean_all" description="Remove all generated output" depends="clean_output, clean_sql">
		<echo>Cleaning entire project</echo>
	</target>

	<target name="clean_output" description="Remove all generated output">
		<echo>Removing all generated output ...</echo>
		<delete>
			<fileset dir="src" includes="*" />
			<fileset dir="." includes="Verify_sel_verify_selects_output.txt, Verify_sel_cond_test_verify_selects_output.txt" />
		</delete>
	</target>

	<target name="clean_sql" description="Remove all generated sql output">
		<echo>Removing all generated sql output ...</echo>
		<delete>
			<fileset dir="sql" includes="*.sql" />
		</delete>
	</target>

</project>


text:
"""Fixtures for Nova tests."""
from __future__ import absolute_import

import logging as std_logging
import os
import warnings

import fixtures
import mock
from oslo_config import cfg
from oslo_db.sqlalchemy import enginefacade
from oslo_messaging import conffixture as messaging_conffixture
import six

from nova.compute import rpcapi as compute_rpcapi
from nova import context
from nova.db import migration
from nova.db.sqlalchemy import api as session
from nova import exception
from nova import objects
from nova.objects import base as obj_base
from nova.objects import service as service_obj
from nova import rpc
from nova import service
from nova.tests.functional.api import client

_TRUE_VALUES = ('True', 'true', '1', 'yes')

CONF = cfg.CONF
DB_SCHEMA = {'main': "", 'api': ""}
SESSION_CONFIGURED = False

class ServiceFixture(fixtures.Fixture):
    """Run a service as a test fixture."""

    def __init__(self, name, host=None, **kwargs):
        name = name
        # If not otherwise specified, the host will default to the
        # name of the service. Some things like aggregates care that
        # this is stable.
        host = host or name
        kwargs.setdefault('host', host)
        kwargs.setdefault('binary', 'nova-%s' % name)
        self.kwargs = kwargs

    def setUp(self):
        super(ServiceFixture, self).setUp()
        self.service = service.Service.create(**self.kwargs)
        self.service.start()
        self.addCleanup(self.service.kill)

class NullHandler(std_logging.Handler):
    """custom default NullHandler to attempt to format the record.

    Used in conjunction with
    log_fixture.get_logging_handle_error_fixture to detect formatting errors in
    debug level logs without saving the logs.
    """
    def handle(self, record):
        self.format(record)

    def emit(self, record):
        pass

    def createLock(self):
        self.lock = None

class StandardLogging(fixtures.Fixture):
    """Setup Logging redirection for tests.

    There are a number of things we want to handle with logging in tests:

    * Redirect the logging to somewhere that we can test or dump it later.

    * Ensure that as many DEBUG messages as possible are actually
       executed, to ensure they are actually syntactically valid (they
       often have not been).

    * Ensure that we create useful output for tests that doesn't
      overwhelm the testing system (which means we can't capture the
      100 MB of debug logging on every run).

    To do this we create a logger fixture at the root level, which
    defaults to INFO and create a Null Logger at DEBUG which lets
    us execute log messages at DEBUG but not keep the output.

    To support local debugging OS_DEBUG=True can be set in the
    environment, which will print out the full debug logging.

    There are also a set of overrides for particularly verbose
    modules to be even less than INFO.

    """

    def setUp(self):
        super(StandardLogging, self).setUp()

        # set root logger to debug
        root = std_logging.getLogger()
        root.setLevel(std_logging.DEBUG)

        # supports collecting debug level for local runs
        if os.environ.get('OS_DEBUG') in _TRUE_VALUES:
            level = std_logging.DEBUG
        else:
            level = std_logging.INFO

        # Collect logs
        fs = '%(asctime)s %(levelname)s [%(name)s] %(message)s'
        self.logger = self.useFixture(
            fixtures.FakeLogger(format=fs, level=None))
        # TODO(sdague): why can't we send level through the fake
        # logger? Tests prove that it breaks, but it's worth getting
        # to the bottom of.
        root.handlers[0].setLevel(level)

        if level > std_logging.DEBUG:
            # Just attempt to format debug level logs, but don't save them
            handler = NullHandler()
            self.useFixture(fixtures.LogHandler(handler, nuke_handlers=False))
            handler.setLevel(std_logging.DEBUG)

            # Don't log every single DB migration step
            std_logging.getLogger(
                'migrate.versioning.api').setLevel(std_logging.WARNING)

        # At times we end up calling back into main() functions in
        # testing. This has the possibility of calling logging.setup
        # again, which completely unwinds the logging capture we've
        # created here. Once we've setup the logging the way we want,
        # disable the ability for the test to change this.
        def fake_logging_setup(*args):
            pass

        self.useFixture(
            fixtures.MonkeyPatch('oslo_log.log.setup', fake_logging_setup))

class OutputStreamCapture(fixtures.Fixture):
    """Capture output streams during tests.

    This fixture captures errant printing to stderr / stdout during
    the tests and lets us see those streams at the end of the test
    runs instead. Useful to see what was happening during failed
    tests.
    """
    def setUp(self):
        super(OutputStreamCapture, self).setUp()
        if os.environ.get('OS_STDOUT_CAPTURE') in _TRUE_VALUES:
            self.out = self.useFixture(fixtures.StringStream('stdout'))
            self.useFixture(
                fixtures.MonkeyPatch('sys.stdout', self.out.stream))
        if os.environ.get('OS_STDERR_CAPTURE') in _TRUE_VALUES:
            self.err = self.useFixture(fixtures.StringStream('stderr'))
            self.useFixture(
                fixtures.MonkeyPatch('sys.stderr', self.err.stream))

    @property
    def stderr(self):
        return self.err._details["stderr"].as_text()

    @property
    def stdout(self):
        return self.out._details["stdout"].as_text()

class Timeout(fixtures.Fixture):
    """Setup per test timeouts.

    In order to avoid test deadlocks we support setting up a test
    timeout parameter read from the environment. In almost all
    cases where the timeout is reached this means a deadlock.

    A class level TIMEOUT_SCALING_FACTOR also exists, which allows
    extremely long tests to specify they need more time.
    """

    def __init__(self, timeout, scaling=1):
        super(Timeout, self).__init__()
        try:
            self.test_timeout = int(timeout)
        except ValueError:
            # If timeout value is invalid do not set a timeout.
            self.test_timeout = 0
        if scaling >= 1:
            self.test_timeout *= scaling
        else:
            raise ValueError('scaling value must be >= 1')

    def setUp(self):
        super(Timeout, self).setUp()
        if self.test_timeout > 0:
            self.useFixture(fixtures.Timeout(self.test_timeout, gentle=True))

class DatabasePoisonFixture(fixtures.Fixture):
    def setUp(self):
        super(DatabasePoisonFixture, self).setUp()
        self.useFixture(fixtures.MonkeyPatch(
            'oslo_db.sqlalchemy.enginefacade._TransactionFactory.'
            '_create_session',
            self._poison_configure))

    def _poison_configure(self, *a, **k):
        warnings.warn('This test uses methods that set internal oslo_db '
                      'state, but it does not claim to use the database. '
                      'This will conflict with the setup of tests that '
                      'do use the database and cause failures later.')
        return mock.MagicMock()

class Database(fixtures.Fixture):
    def __init__(self, database='main', connection=None):
        """Create a database fixture.

        :param database: The type of database, 'main' or 'api'
        :param connection: The connection string to use
        """
        super(Database, self).__init__()
        # NOTE(pkholkin): oslo_db.enginefacade is configured in tests the same
        # way as it is done for any other service that uses db
        global SESSION_CONFIGURED
        if not SESSION_CONFIGURED:
            session.configure(CONF)
            SESSION_CONFIGURED = True
        self.database = database
        if database == 'main':
            if connection is not None:
                ctxt_mgr = session.create_context_manager(
                        connection=connection)
                facade = ctxt_mgr.get_legacy_facade()
                self.get_engine = facade.get_engine
            else:
                self.get_engine = session.get_engine
        elif database == 'api':
            self.get_engine = session.get_api_engine

    def _cache_schema(self):
        global DB_SCHEMA
        if not DB_SCHEMA[self.database]:
            engine = self.get_engine()
            conn = engine.connect()
            migration.db_sync(database=self.database)
            DB_SCHEMA[self.database] = "".join(line for line
                                               in conn.connection.iterdump())
            engine.dispose()

    def cleanup(self):
        engine = self.get_engine()
        engine.dispose()

    def reset(self):
        self._cache_schema()
        engine = self.get_engine()
        engine.dispose()
        conn = engine.connect()
        conn.connection.executescript(DB_SCHEMA[self.database])

    def setUp(self):
        super(Database, self).setUp()
        self.reset()
        self.addCleanup(self.cleanup)

class DatabaseAtVersion(fixtures.Fixture):
    def __init__(self, version, database='main'):
        """Create a database fixture.

        :param version: Max version to sync to (or None for current)
        :param database: The type of database, 'main' or 'api'
        """
        super(DatabaseAtVersion, self).__init__()
        self.database = database
        self.version = version
        if database == 'main':
            self.get_engine = session.get_engine
        elif database == 'api':
            self.get_engine = session.get_api_engine

    def cleanup(self):
        engine = self.get_engine()
        engine.dispose()

    def reset(self):
        engine = self.get_engine()
        engine.dispose()
        engine.connect()
        migration.db_sync(version=self.version, database=self.database)

    def setUp(self):
        super(DatabaseAtVersion, self).setUp()
        self.reset()
        self.addCleanup(self.cleanup)

class DefaultFlavorsFixture(fixtures.Fixture):
    def setUp(self):
        super(DefaultFlavorsFixture, self).setUp()
        ctxt = context.get_admin_context()
        defaults = {'rxtx_factor': 1.0, 'disabled': False, 'is_public': True,
                    'ephemeral_gb': 0, 'swap': 0}
        default_flavors = [
            objects.Flavor(context=ctxt, memory_mb=512, vcpus=1,
                           root_gb=1, flavorid='1', name='m1.tiny',
                           **defaults),
            objects.Flavor(context=ctxt, memory_mb=2048, vcpus=1,
                           root_gb=20, flavorid='2', name='m1.small',
                           **defaults),
            objects.Flavor(context=ctxt, memory_mb=4096, vcpus=2,
                           root_gb=40, flavorid='3', name='m1.medium',
                           **defaults),
            objects.Flavor(context=ctxt, memory_mb=8192, vcpus=4,
                           root_gb=80, flavorid='4', name='m1.large',
                           **defaults),
            objects.Flavor(context=ctxt, memory_mb=16384, vcpus=8,
                           root_gb=160, flavorid='5', name='m1.xlarge',
                           **defaults),
            ]
        for flavor in default_flavors:
            flavor.create()

class RPCFixture(fixtures.Fixture):
    def __init__(self, *exmods):
        super(RPCFixture, self).__init__()
        self.exmods = []
        self.exmods.extend(exmods)

    def setUp(self):
        super(RPCFixture, self).setUp()
        self.addCleanup(rpc.cleanup)
        rpc.add_extra_exmods(*self.exmods)
        self.addCleanup(rpc.clear_extra_exmods)
        self.messaging_conf = messaging_conffixture.ConfFixture(CONF)
        self.messaging_conf.transport_driver = 'fake'
        self.useFixture(self.messaging_conf)
        rpc.init(CONF)

class WarningsFixture(fixtures.Fixture):
    """Filters out warnings during test runs."""

    def setUp(self):
        super(WarningsFixture, self).setUp()
        # NOTE(sdague): Make deprecation warnings only happen once. Otherwise
        # this gets kind of crazy given the way that upstream python libs use
        # this.
        warnings.simplefilter("once", DeprecationWarning)
        warnings.filterwarnings('ignore',
                                message='With-statements now directly support'
                                        ' multiple context managers')

        self.addCleanup(warnings.resetwarnings)

class ConfPatcher(fixtures.Fixture):
    """Fixture to patch and restore global CONF.

    This also resets overrides for everything that is patched during
    it's teardown.

    """

    def __init__(self, **kwargs):
        """Constructor

        :params group: if specified all config options apply to that group.

        :params **kwargs: the rest of the kwargs are processed as a
        set of key/value pairs to be set as configuration override.

        """
        super(ConfPatcher, self).__init__()
        self.group = kwargs.pop('group', None)
        self.args = kwargs

    def setUp(self):
        super(ConfPatcher, self).setUp()
        for k, v in six.iteritems(self.args):
            self.addCleanup(CONF.clear_override, k, self.group)
            CONF.set_override(k, v, self.group)

class OSAPIFixture(fixtures.Fixture):
    """Create an OS API server as a fixture.

    This spawns an OS API server as a fixture in a new greenthread in
    the current test. The fixture has a .api paramenter with is a
    simple rest client that can communicate with it.

    This fixture is extremely useful for testing REST responses
    through the WSGI stack easily in functional tests.

    Usage:

        api = self.useFixture(fixtures.OSAPIFixture()).api
        resp = api.api_request('/someurl')
        self.assertEqual(200, resp.status_code)
        resp = api.api_request('/otherurl', method='POST', body='{foo}')

    The resp is a requests library response. Common attributes that
    you'll want to use are:

    - resp.status_code - integer HTTP status code returned by the request
    - resp.content - the body of the response
    - resp.headers - dictionary of HTTP headers returned

    """

    def __init__(self, api_version='v2',
                 project_id='6f70656e737461636b20342065766572'):
        """Constructor

        :param api_version: the API version that we're interested in
        using. Currently this expects 'v2' or 'v2.1' as possible
        options.
        :param project_id: the project id to use on the API.

        """
        super(OSAPIFixture, self).__init__()
        self.api_version = api_version
        self.project_id = project_id

    def setUp(self):
        super(OSAPIFixture, self).setUp()
        # in order to run these in tests we need to bind only to local
        # host, and dynamically allocate ports
        conf_overrides = {
            'osapi_compute_listen': '127.0.0.1',
            'osapi_compute_listen_port': 0,
            'verbose': True,
            'debug': True,
        }
        self.useFixture(ConfPatcher(**conf_overrides))

        self.osapi = service.WSGIService("osapi_compute")
        self.osapi.start()
        self.addCleanup(self.osapi.stop)

        self.auth_url = 'http://%(host)s:%(port)s/%(api_version)s' % ({
            'host': self.osapi.host, 'port': self.osapi.port,
            'api_version': self.api_version})
        self.api = client.TestOpenStackClient('fake', 'fake', self.auth_url,
                                              self.project_id)
        self.admin_api = client.TestOpenStackClient(
            'admin', 'admin', self.auth_url, self.project_id)

class OSMetadataServer(fixtures.Fixture):
    """Create an OS Metadata API server as a fixture.

    This spawns an OS Metadata API server as a fixture in a new
    greenthread in the current test.

    TODO(sdague): ideally for testing we'd have something like the
    test client which acts like requests, but connects any of the
    interactions needed.

    """
    def setUp(self):
        super(OSMetadataServer, self).setUp()
        # in order to run these in tests we need to bind only to local
        # host, and dynamically allocate ports
        conf_overrides = {
            'metadata_listen': '127.0.0.1',
            'metadata_listen_port': 0,
            'verbose': True,
            'debug': True
        }
        self.useFixture(ConfPatcher(**conf_overrides))

        # NOTE(mikal): we don't have root to manipulate iptables, so just
        # zero that bit out.
        self.useFixture(fixtures.MonkeyPatch(
            'nova.network.linux_net.IptablesManager._apply',
            lambda _: None))

        self.metadata = service.WSGIService("metadata")
        self.metadata.start()
        self.addCleanup(self.metadata.stop)
        self.md_url = "http://%s:%s/" % (
            conf_overrides['metadata_listen'],
            self.metadata.port)

class PoisonFunctions(fixtures.Fixture):
    """Poison functions so they explode if we touch them.

    When running under a non full stack test harness there are parts
    of the code that you don't want to go anywhere near. These include
    things like code that spins up extra threads, which just
    introduces races.

    """

    def setUp(self):
        super(PoisonFunctions, self).setUp()

        # The nova libvirt driver starts an event thread which only
        # causes trouble in tests. Make sure that if tests don't
        # properly patch it the test explodes.

        # explicit import because MonkeyPatch doesn't magic import
        # correctly if we are patching a method on a class in a
        # module.
        import nova.virt.libvirt.host  # noqa

        def evloop(*args, **kwargs):
            import sys
            warnings.warn("Forgot to disable libvirt event thread")
            sys.exit(1)

        self.useFixture(fixtures.MonkeyPatch(
            'nova.virt.libvirt.host.Host._init_events',
            evloop))

class IndirectionAPIFixture(fixtures.Fixture):
    """Patch and restore the global NovaObject indirection api."""

    def __init__(self, indirection_api):
        """Constructor

        :param indirection_api: the indirection API to be used for tests.

        """
        super(IndirectionAPIFixture, self).__init__()
        self.indirection_api = indirection_api

    def cleanup(self):
        obj_base.NovaObject.indirection_api = self.orig_indirection_api

    def setUp(self):
        super(IndirectionAPIFixture, self).setUp()
        self.orig_indirection_api = obj_base.NovaObject.indirection_api
        obj_base.NovaObject.indirection_api = self.indirection_api
        self.addCleanup(self.cleanup)

class _FakeGreenThread(object):
    def __init__(self, func, *args, **kwargs):
        self._result = func(*args, **kwargs)

    def cancel(self, *args, **kwargs):
        # This method doesn't make sense for a synchronous call, it's just
        # defined to satisfy the interface.
        pass

    def kill(self, *args, **kwargs):
        # This method doesn't make sense for a synchronous call, it's just
        # defined to satisfy the interface.
        pass

    def link(self, func, *args, **kwargs):
        func(self, *args, **kwargs)

    def unlink(self, func, *args, **kwargs):
        # This method doesn't make sense for a synchronous call, it's just
        # defined to satisfy the interface.
        pass

    def wait(self):
        return self._result

class SpawnIsSynchronousFixture(fixtures.Fixture):
    """Patch and restore the spawn_n utility method to be synchronous"""

    def setUp(self):
        super(SpawnIsSynchronousFixture, self).setUp()
        self.useFixture(fixtures.MonkeyPatch(
            'nova.utils.spawn_n', _FakeGreenThread))
        self.useFixture(fixtures.MonkeyPatch(
            'nova.utils.spawn', _FakeGreenThread))

class BannedDBSchemaOperations(fixtures.Fixture):
    """Ban some operations for migrations"""
    def __init__(self, banned_resources=None):
        super(BannedDBSchemaOperations, self).__init__()
        self._banned_resources = banned_resources or []

    @staticmethod
    def _explode(resource, op):
        raise exception.DBNotAllowed(
            'Operation %s.%s() is not allowed in a database migration' % (
                resource, op))

    def setUp(self):
        super(BannedDBSchemaOperations, self).setUp()
        for thing in self._banned_resources:
            self.useFixture(fixtures.MonkeyPatch(
                'sqlalchemy.%s.drop' % thing,
                lambda *a, **k: self._explode(thing, 'drop')))
            self.useFixture(fixtures.MonkeyPatch(
                'sqlalchemy.%s.alter' % thing,
                lambda *a, **k: self._explode(thing, 'alter')))

class EngineFacadeFixture(fixtures.Fixture):
    """Fixture to isolation EngineFacade during tests.

    Because many elements of EngineFacade are based on globals, once
    an engine facade has been initialized, all future code goes
    through it. This means that the initialization of sqlite in
    databases in our Database fixture will drive all connections to
    sqlite. While that's fine in a production environment, during
    testing this means we can't test against multiple backends in the
    same test run.

    oslo.db does not yet support a reset mechanism here. This builds a
    custom in tree engine facade fixture to handle this. Eventually
    this will be added to oslo.db and this can be removed. Tracked by
    https://bugs.launchpad.net/oslo.db/+bug/1548960

    """
    def __init__(self, ctx_manager, engine, sessionmaker):
        super(EngineFacadeFixture, self).__init__()
        self._ctx_manager = ctx_manager
        self._engine = engine
        self._sessionmaker = sessionmaker

    def setUp(self):
        super(EngineFacadeFixture, self).setUp()

        self._existing_factory = self._ctx_manager._root_factory
        self._ctx_manager._root_factory = enginefacade._TestTransactionFactory(
            self._engine, self._sessionmaker, apply_global=False,
            synchronous_reader=True)
        self.addCleanup(self.cleanup)

    def cleanup(self):
        self._ctx_manager._root_factory = self._existing_factory

class ForbidNewLegacyNotificationFixture(fixtures.Fixture):
    """Make sure the test fails if new legacy notification is added"""
    def __init__(self):
        super(ForbidNewLegacyNotificationFixture, self).__init__()
        self.notifier = rpc.LegacyValidatingNotifier

    def setUp(self):
        super(ForbidNewLegacyNotificationFixture, self).setUp()
        self.notifier.fatal = True

        # allow the special test value used in
        # nova.tests.unit.test_notifications.NotificationsTestCase
        self.notifier.allowed_legacy_notification_event_types.append(
                '_decorated_function')

        self.addCleanup(self.cleanup)

    def cleanup(self):
        self.notifier.fatal = False
        self.notifier.allowed_legacy_notification_event_types.remove(
                '_decorated_function')

class AllServicesCurrent(fixtures.Fixture):
    def setUp(self):
        super(AllServicesCurrent, self).setUp()
        self.useFixture(fixtures.MonkeyPatch(
            'nova.objects.Service.get_minimum_version_multi',
            self._fake_minimum))
        compute_rpcapi.LAST_VERSION = None

    def _fake_minimum(self, *args, **kwargs):
        return service_obj.SERVICE_VERSION

class NeutronFixture(fixtures.Fixture):
    """A fixture to boot instances with neutron ports"""

    # the default project_id in OsaAPIFixtures
    tenant_id = '6f70656e737461636b20342065766572'
    network_1 = {
        'status': 'ACTIVE',
        'subnets': [],
        'name': 'private-network',
        'admin_state_up': True,
        'tenant_id': tenant_id,
        'id': '3cb9bc59-5699-4588-a4b1-b87f96708bc6',
    }
    subnet_1 = {
        'name': 'private-subnet',
        'enable_dhcp': True,
        'network_id': network_1['id'],
        'tenant_id': tenant_id,
        'dns_nameservers': [],
        'allocation_pools': [
            {
                'start': '192.168.1.1',
                'end': '192.168.1.254'
            }
        ],
        'host_routes': [],
        'ip_version': 4,
        'gateway_ip': '192.168.1.1',
        'cidr': '192.168.1.1/24',
        'id': 'f8a6e8f8-c2ec-497c-9f23-da9616de54ef'
    }
    network_1['subnets'] = [subnet_1['id']]

    port_1 = {
        'id': 'ce531f90-199f-48c0-816c-13e38010b442',
        'network_id': network_1['id'],
        'admin_state_up': True,
        'status': 'ACTIVE',
        'mac_address': 'fa:16:3e:4c:2c:30',
        'fixed_ips': [
            {
                'ip_address': '192.168.1.3',
                'subnet_id': subnet_1['id']
            }
        ],
        'tenant_id': tenant_id
    }

    def __init__(self, test):
        super(NeutronFixture, self).__init__()
        self.test = test

    def setUp(self):
        super(NeutronFixture, self).setUp()

        self.test.stub_out(
            'nova.network.neutronv2.api.API.'
            'validate_networks',
            lambda *args, **kwargs: 1)
        self.test.stub_out(
            'nova.network.neutronv2.api.API.'
            'create_pci_requests_for_sriov_ports',
            lambda *args, **kwargs: None)
        self.test.stub_out(
            'nova.network.security_group.neutron_driver.SecurityGroupAPI.'
            'get_instances_security_groups_bindings',
            lambda *args, **kwargs: {})

        mock_neutron_client = mock.Mock()
        mock_neutron_client.list_extensions.return_value = {'extensions': []}
        mock_neutron_client.show_port.return_value = {
            'port': NeutronFixture.port_1}
        mock_neutron_client.list_networks.return_value = {
            'networks': [NeutronFixture.network_1]}
        mock_neutron_client.list_ports.return_value = {
            'ports': [NeutronFixture.port_1]}
        mock_neutron_client.list_subnets.return_value = {
            'subnets': [NeutronFixture.subnet_1]}
        mock_neutron_client.list_floatingips.return_value = {'floatingips': []}
        mock_neutron_client.update_port.return_value = {
            'port': NeutronFixture.port_1}

        self.test.stub_out(
            'nova.network.neutronv2.api.get_client',
            lambda *args, **kwargs: mock_neutron_client)

class _NoopConductor(object):
    def __getattr__(self, key):
        def _noop_rpc(*args, **kwargs):
            return None
        return _noop_rpc

class NoopConductorFixture(fixtures.Fixture):
    """Stub out the conductor API to do nothing"""

    def setUp(self):
        super(NoopConductorFixture, self).setUp()
        self.useFixture(fixtures.MonkeyPatch(
            'nova.conductor.ComputeTaskAPI', _NoopConductor))
        self.useFixture(fixtures.MonkeyPatch(
            'nova.conductor.API', _NoopConductor))

class CinderFixture(fixtures.Fixture):
    """A fixture to volume operations"""

    # the default project_id in OSAPIFixtures
    tenant_id = '6f70656e737461636b20342065766572'

    SWAP_OLD_VOL = 'a07f71dc-8151-4e7d-a0cc-cd24a3f11113'
    SWAP_NEW_VOL = '227cc671-f30b-4488-96fd-7d0bf13648d8'
    SWAP_ERR_OLD_VOL = '828419fa-3efb-4533-b458-4267ca5fe9b1'
    SWAP_ERR_NEW_VOL = '9c6d9c2d-7a8f-4c80-938d-3bf062b8d489'

    def __init__(self, test):
        super(CinderFixture, self).__init__()
        self.test = test
        self.swap_error = False
        self.swap_volume_instance_uuid = None
        self.swap_volume_instance_error_uuid = None

    def setUp(self):
        super(CinderFixture, self).setUp()

        def fake_get(self_api, context, volume_id):
            if volume_id in (CinderFixture.SWAP_OLD_VOL,
                             CinderFixture.SWAP_ERR_OLD_VOL):
                volume = {
                             'status': 'available',
                             'display_name': 'TEST1',
                             'attach_status': 'detached',
                             'id': volume_id,
                             'size': 1
                         }
                if ((self.swap_volume_instance_uuid and
                     volume_id == CinderFixture.SWAP_OLD_VOL) or
                    (self.swap_volume_instance_error_uuid and
                     volume_id == CinderFixture.SWAP_ERR_OLD_VOL)):
                    instance_uuid = (self.swap_volume_instance_uuid
                        if volume_id == CinderFixture.SWAP_OLD_VOL
                        else self.swap_volume_instance_error_uuid)

                    volume.update({
                        'status': 'in-use',
                        'attachments': {
                            instance_uuid: {
                                'mountpoint': '/dev/vdb',
                                'attachment_id': volume_id
                            }
                        },
                        'attach_status': 'attached'
                    })
                return volume
            else:
                return {
                           'status': 'available',
                           'display_name': 'TEST2',
                           'attach_status': 'detached',
                           'id': volume_id,
                           'size': 1
                       }

        def fake_initialize_connection(self, context, volume_id, connector):
            if volume_id == CinderFixture.SWAP_ERR_NEW_VOL:
                # Return a tuple in order to raise an exception.
                return ()
            return {}

        def fake_migrate_volume_completion(self, context, old_volume_id,
                                           new_volume_id, error):
            return {'save_volume_id': new_volume_id}

        def fake_unreserve_volume(self_api, context, volume_id):
            # Signaling that swap_volume has encountered the error
            # from initialize_connection and is working on rolling back
            # the reservation on SWAP_ERR_NEW_VOL.
            self.swap_error = True

        self.test.stub_out('nova.volume.cinder.API.attach',
                           lambda *args, **kwargs: None)
        self.test.stub_out('nova.volume.cinder.API.begin_detaching',
                           lambda *args, **kwargs: None)
        self.test.stub_out('nova.volume.cinder.API.check_attach',
                           lambda *args, **kwargs: None)
        self.test.stub_out('nova.volume.cinder.API.check_detach',
                           lambda *args, **kwargs: None)
        self.test.stub_out('nova.volume.cinder.API.get',
                           fake_get)
        self.test.stub_out('nova.volume.cinder.API.initialize_connection',
                           fake_initialize_connection)
        self.test.stub_out(
            'nova.volume.cinder.API.migrate_volume_completion',
            fake_migrate_volume_completion)
        self.test.stub_out('nova.volume.cinder.API.reserve_volume',
                           lambda *args, **kwargs: None)
        self.test.stub_out('nova.volume.cinder.API.roll_detaching',
                           lambda *args, **kwargs: None)
        self.test.stub_out('nova.volume.cinder.API.terminate_connection',
                           lambda *args, **kwargs: None)
        self.test.stub_out('nova.volume.cinder.API.unreserve_volume',
                           fake_unreserve_volume)


text:
@implementation MapInfo

@end


text:
package scalaoauth2.provider

import org.apache.commons.codec.binary.Base64

case class ClientCredential(clientId: String, clientSecret: String)

trait ClientCredentialFetcher {

  def fetch(request: AuthorizationRequest): Option[ClientCredential] = {
    request.header("Authorization") match {
      case Some(authorization) if authorization.length > 5 => {
        val decoded = new String(Base64.decodeBase64(authorization.substring(6).getBytes), "UTF-8")
        if (decoded.indexOf(':') > 0) {
          decoded.split(":", 2) match {
            case Array(clientId, clientSecret) => Option(ClientCredential(clientId, clientSecret))
            case Array(clientId) => Option(ClientCredential(clientId, ""))
            case _ => None
          }
        } else {
          None
        }
      }
      case _ => request.clientId.map { clientId =>
        ClientCredential(clientId, request.clientSecret.getOrElse(""))
      }
    }
  }
}

object ClientCredentialFetcher extends ClientCredentialFetcher


text:
<macros>
    <token name="@VERSION@">1.0.1</token>
    <xml name="requirements">
        <requirements>
            <requirement type="package" version="@VERSION@">krocus</requirement>
        </requirements>
    </xml>

    <xml name="version_command">
        <version_command>krocus --version</version_command>
    </xml>

    <xml name="citations">
        <citations>
            <citation type="doi">10.7717/peerj.5233</citation>
        </citations>
    </xml>
</macros>


text:
package com.intrbiz.schema.pretty;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

public class Dumper implements AutoCloseable
{
    private String url;

    private String username;

    private String password;

    private Connection connection;

    public Dumper(String url, String username, String password) throws SQLException
    {
        this.url = url;
        this.username = username;
        this.password = password;
        this.connection = DriverManager.getConnection(this.url, this.username, this.password);
    }

    public void dump(File outDir) throws SQLException, IOException
    {
        outDir.mkdirs();
        // list the schemas
        try (PreparedStatement stmt = this.connection.prepareStatement("SELECT nspname, pg_get_userbyid(nspowner) FROM pg_namespace WHERE nspname <> 'public' AND nspname <> 'information_schema' AND nspname !~ '^pg_';"))
        {
            try (ResultSet rs = stmt.executeQuery())
            {
                while (rs.next())
                {
                    String schemaName  = rs.getString(1);
                    String schemaOwner = rs.getString(2);
                    this.dumpSchema(schemaName, schemaOwner, outDir);
                }
            }
        }
    }

    private void dumpSchema(String name, String owner, File outDir) throws SQLException, IOException
    {
        File schemaDir    = new File(outDir, name);
        File tablesDir    = new File(schemaDir, "tables");
        File typesDir     = new File(schemaDir, "types");
        File functionsDir = new File(schemaDir, "functions");
        File triggersDir = new File(schemaDir, "triggers");
        // create dirs
        schemaDir.mkdirs();
        tablesDir.mkdirs();
        typesDir.mkdirs();
        functionsDir.mkdirs();
        triggersDir.mkdirs();
        // dump the schema
        // create schema
        this.writeCreateSchema(name, owner, new File(schemaDir, "create.sql"));
        // tables
        List<File> tables    = this.dumpTables(name, tablesDir);
        List<File> types     = this.dumpTypes(name, typesDir);
        List<File> functions = this.dumpFunctions(name, functionsDir);
        List<File> triggers  = this.dumpTriggers(name, triggersDir);
        // build script
        this.writeSchemaBuildScript(name, functions, tables, types, triggers, new File(schemaDir, "create.sh"));
        //this.writeBuildAllScript(new File(outDir, "create_all.sh"));
        //this.writeBuildUtilScript(new File(outDir, "util.sh"));
    }

    private void writeSchemaBuildScript(String name, List<File> functions, List<File> tables, List<File> types, List<File> triggers, File to) throws IOException
    {
        try (Writer out = new BufferedWriter(new FileWriter(to)))
        {
            out.write("#!/bin/bash\n");
            out.write("source ../util.sh\n");
            out.write("# Create schema, executing this script will output the SQL schema to stdout\n\n");
            out.write("begin\n");
            out.write("say \"Creating schema " + name + "\"\n");
            out.write("include \"create.sql\"\n\n");
            out.write("# Tables\n");
            for (String table : tables.stream().map((f) -> f.getName().replace(".sql", "")).sorted().collect(Collectors.toList()))
            {
                out.write("include_table \"" + table + "\"\n");
            }
            out.write("\n");
            out.write("# Types\n");
            for (String type : types.stream().map((f) -> f.getName().replace(".sql", "")).sorted().collect(Collectors.toList()))
            {
                out.write("include_type \"" + type + "\"\n");
            }
            out.write("\n");
            out.write("# Functions\n");
            for (String function : functions.stream().map((f) -> f.getName().replace(".sql", "")).sorted().collect(Collectors.toList()))
            {
                out.write("include_function \"" + function + "\"\n");
            }
            out.write("\n");
            out.write("# Triggers\n");
            for (String trigger : triggers.stream().map((f) -> f.getName().replace(".sql", "")).sorted().collect(Collectors.toList()))
            {
                out.write("include_trigger \"" + trigger + "\"\n");
            }
            out.write("\n");
            out.write("# Testing testing testing\n");
            out.write("test\n");
            out.write("\n");
            out.write("commit\n");
        }
    }

    private void writeBuildAllScript(File to) throws IOException
    {
        try (Writer out = new BufferedWriter(new FileWriter(to)))
        {
            out.write("#!/bin/sh\n");
            out.write("echo \"BEGIN;\"\n");
            out.write("for x in */create.sh ; do\n");
            out.write("  pushd `dirname $x` > /dev/null\n");
            out.write("  IN_TRANS=yes sh ../$x\n");
            out.write("  popd > /dev/null\n");
            out.write("done\n");
            out.write("echo \"COMMIT;\"\n");
        }
    }

    private void writeBuildUtilScript(File to) throws IOException
    {
        try (Writer out = new BufferedWriter(new FileWriter(to)))
        {
            out.write("#!/bin/sh\n");
            out.write("\n");
            out.write("function begin {\n");
            out.write("  if [ \"$IN_TRANS\" != \"yes\" ]; then\n");
            out.write("    echo \"BEGIN;\"\n");
            out.write("  fi\n");
            out.write("}\n");
            out.write("\n");
            out.write("function commit {\n");
            out.write("  if [ \"$IN_TRANS\" != \"yes\" ]; then\n");
            out.write("    echo \"COMMIT;\"\n");
            out.write("  fi\n");
            out.write("}\n");
            out.write("\n");
        }
    }

    private void writeCreateSchema(String name, String owner, File to) throws SQLException, IOException
    {
        try (Writer fw = new BufferedWriter(new FileWriter(to)))
        {
            fw.write("CREATE SCHEMA IF NOT EXISTS " + name + " AUTHORIZATION " + "myenergy" + ";\n\n");
        }
    }

    public List<File> dumpTables(String schema, File outDir) throws SQLException, IOException
    {
        List<File> files = new LinkedList<File>();
        try (PreparedStatement stmt = this.connection.prepareStatement("SELECT c.relname, pg_get_userbyid(c.relowner) FROM pg_class c JOIN pg_namespace n ON (n.oid = c.relnamespace) WHERE n.nspname = ? AND c.relkind = 'r' AND c.relpersistence = 'p'"))
        {
            stmt.setString(1, schema);
            try (ResultSet rs = stmt.executeQuery())
            {
                while (rs.next())
                {
                    String name = rs.getString(1);
                    String owner = rs.getString(2);
                    // dump the table
                    File tableFile = new File (outDir, name + ".sql");
                    files.add(tableFile);
                    this.dumpTable(schema, name, owner, tableFile);
                }
            }
        }
        return files;
    }

    public void dumpTable(String schema, String table, String owner, File to) throws SQLException, IOException
    {
        try (Writer writer = new BufferedWriter(new FileWriter(to)))
        {
            writer.write("CREATE TABLE IF NOT EXISTS \"" + schema + "\".\"" + table + "\" (\n");
            boolean ns = false;
            // get the columns
            try (PreparedStatement stmt = this.connection.prepareStatement("SELECT a.attnum, quote_ident(a.attname), format_type(a.atttypid, a.atttypmod) FROM pg_class c JOIN pg_namespace n ON (n.oid = c.relnamespace) JOIN pg_attribute a ON (a.attrelid = c.oid) WHERE n.nspname = ? AND c.relname = ? AND a.attnum > 0 ORDER BY a.attnum"))
            {
                stmt.setString(1, schema);
                stmt.setString(2, table);
                try (ResultSet rs = stmt.executeQuery())
                {
                    while (rs.next())
                    {
                        String name = rs.getString(2);
                        String type = rs.getString(3);
                        if (ns) writer.write(",\n");
                        writer.write("  " + name + " " + type.toUpperCase());
                        ns = true;
                    }
                }
            }
            // constraints
            try (PreparedStatement stmt = this.connection.prepareStatement("SELECT quote_ident(c.conname), pg_get_constraintdef(c.oid) FROM pg_constraint c JOIN pg_class r ON (c.conrelid = r.oid) JOIN pg_namespace n ON (r.relnamespace = n.oid) WHERE n.nspname = ? AND r.relname = ? ORDER BY c.contype DESC, c.conname"))
            {
                stmt.setString(1, schema);
                stmt.setString(2, table);
                try (ResultSet rs = stmt.executeQuery())
                {
                    while (rs.next())
                    {
                        if (ns) writer.write(",\n");
                        writer.write("  CONSTRAINT " + rs.getString(1) +  " ");
                        writer.write(rs.getString(2));
                    }
                }
            }
            // end table
            writer.write("\n)");
            // inherits
            try (PreparedStatement stmt = this.connection.prepareStatement("SELECT quote_ident(n2.nspname), quote_ident(r2.relname) FROM pg_inherits i JOIN pg_class r1 ON (i.inhrelid = r1.oid) JOIN pg_namespace n1 ON (r1.relnamespace = n1.oid) JOIN pg_class r2 ON (i.inhparent = r2.oid) JOIN pg_namespace n2 ON (r2.relnamespace = n2.oid) WHERE n1.nspname = ? AND r1.relname = ?"))
            {
                stmt.setString(1, schema);
                stmt.setString(2, table);
                try (ResultSet rs = stmt.executeQuery())
                {
                    while (rs.next())
                    {
                        writer.write("\nINHERITS (" + rs.getString(1) + "." + rs.getString(2) + ")");
                    }
                }
            }
            writer.write(";\n\n");
            writer.write("ALTER TABLE \"" + schema + "\".\"" + table + "\" OWNER TO " + "myenergy" + ";\n\n");
            // indexes
            try (PreparedStatement stmt = this.connection.prepareStatement("SELECT n2.nspname, c2.relname, pg_get_indexdef(c2.oid) FROM pg_index i JOIN pg_class c2 ON (i.indexrelid = c2.oid AND c2.relkind = 'i') JOIN pg_namespace n2 ON (c2.relnamespace = n2.oid) JOIN pg_class c1 ON (i.indrelid = c1.oid) JOIN pg_namespace n1 ON (c1.relnamespace = n1.oid) LEFT JOIN pg_constraint con ON (c2.oid = con.conindid) WHERE con.conname IS NULL AND n1.nspname = ? AND c1.relname = ?"))
            {
                stmt.setString(1, schema);
                stmt.setString(2, table);
                try (ResultSet rs = stmt.executeQuery())
                {
                    while (rs.next())
                    {
                        writer.write(rs.getString(3) + ";\n\n");
                    }
                }
            }
        }
    }

    public List<File> dumpTriggers(String schema, File outDir) throws SQLException, IOException
    {
        List<File> files = new LinkedList<File>();
        try (PreparedStatement stmt = this.connection.prepareStatement("SELECT c.relname, pg_get_userbyid(c.relowner) FROM pg_class c JOIN pg_namespace n ON (n.oid = c.relnamespace) WHERE n.nspname = ? AND c.relkind = 'r' AND c.relpersistence = 'p'"))
        {
            stmt.setString(1, schema);
            try (ResultSet rs = stmt.executeQuery())
            {
                while (rs.next())
                {
                    String name = rs.getString(1);
                    String owner = rs.getString(2);
                    // dump the table
                    File triggerFile = new File (outDir, name + ".sql");
                    if (this.dumpTrigger(schema, name, owner, triggerFile))
                    {
                        files.add(triggerFile);
                    }
                    else
                    {
                        triggerFile.delete();
                    }
                }
            }
        }
        return files;
    }

    public boolean dumpTrigger(String schema, String table, String owner, File to) throws SQLException, IOException
    {
        boolean ret = false;
        try (Writer writer = new BufferedWriter(new FileWriter(to)))
        {
            // triggers
            try (PreparedStatement stmt = this.connection.prepareStatement("SELECT t.tgname, pg_get_triggerdef(t.oid) FROM pg_trigger t JOIN pg_class r ON (t.tgrelid = r.oid) JOIN pg_namespace n ON (r.relnamespace = n.oid) WHERE (NOT t.tgisinternal) AND n.nspname = ? AND r.relname = ?"))
            {
                stmt.setString(1, schema);
                stmt.setString(2, table);
                try (ResultSet rs = stmt.executeQuery())
                {
                    while (rs.next())
                    {
                        writer.write(rs.getString(2) + ";\n\n");
                        ret = true;
                    }
                }
            }
        }
        return ret;
    }

    public List<File> dumpFunctions(String schema, File to) throws SQLException, IOException
    {
        List<File> files = new LinkedList<File>();
        try (PreparedStatement stmt = this.connection.prepareStatement("SELECT pg_get_functiondef(p.oid), p.proname, (SELECT string_agg((SELECT t.typname FROM pg_type t WHERE t.oid = u.v), '_') AS argtypes FROM unnest(p.proargtypes) u(v)), pg_get_userbyid(p.proowner), pg_get_function_identity_arguments(p.oid)  FROM pg_proc p JOIN pg_language l ON (p.prolang = l.oid) JOIN pg_namespace n ON (p.pronamespace = n.oid) WHERE n.nspname = ? AND l.lanname <> 'plv8'"))
        {
            stmt.setString(1, schema);
            try (ResultSet rs = stmt.executeQuery())
            {
                while (rs.next())
                {
                    String def    = rs.getString(1);
                    String name   = rs.getString(2);
                    String args   = rs.getString(3);
                    String owner  = rs.getString(4);
                    String idargs = rs.getString(5);
                    // write out the def
                    File functionFile = new File (to, name + (args == null ? "" : "_" + args) + ".sql");
                    try (Writer fw = new BufferedWriter(new FileWriter(functionFile)))
                    {
                        fw.write(def + ";\n\n");
                        fw.write("ALTER FUNCTION \"" + schema + "\".\"" + name + "\"(" + idargs + ") OWNER TO " + "myenergy" + ";\n\n");
                    }
                    files.add(functionFile);
                }
            }
        }
        return files;
    }

    public List<File> dumpTypes(String schema, File outDir) throws SQLException, IOException
    {
        List<File> files = new LinkedList<File>();
        try (PreparedStatement stmt = this.connection.prepareStatement("SELECT t.typname, pg_get_userbyid(t.typowner) FROM pg_type t JOIN pg_namespace tn ON (t.typnamespace = tn.oid) JOIN pg_class r ON (t.typrelid = r.oid) WHERE t.typtype = 'c' AND r.relkind = 'c' AND tn.nspname = ?"))
        {
            stmt.setString(1, schema);
            try (ResultSet rs = stmt.executeQuery())
            {
                while (rs.next())
                {
                    String name = rs.getString(1);
                    String owner = rs.getString(2);
                    // dump the table
                    File typeFile = new File (outDir, name + ".sql");
                    files.add(typeFile);
                    this.dumpType(schema, name, owner, typeFile);
                }
            }
        }
        return files;
    }

    public void dumpType(String schema, String type, String owner, File to) throws SQLException, IOException
    {
        try (Writer writer = new BufferedWriter(new FileWriter(to)))
        {
            writer.write("CREATE TYPE \"" + schema + "\".\"" + type + "\" AS (\n");
            boolean ns = false;
            // get the columns
            try (PreparedStatement stmt = this.connection.prepareStatement("SELECT a.attnum, quote_ident(a.attname), format_type(a.atttypid, a.atttypmod) FROM pg_type t JOIN pg_namespace n ON (n.oid = t.typnamespace) JOIN pg_class c ON (t.typrelid = c.oid) JOIN pg_attribute a ON (a.attrelid = c.oid) WHERE n.nspname = ? AND c.relname = ? AND a.attnum > 0 ORDER BY a.attnum"))
            {
                stmt.setString(1, schema);
                stmt.setString(2, type);
                try (ResultSet rs = stmt.executeQuery())
                {
                    while (rs.next())
                    {
                        String aname = rs.getString(2);
                        String atype = rs.getString(3);
                        if (ns) writer.write(",\n");
                        writer.write("  " + aname + " " + atype.toUpperCase());
                        ns = true;
                    }
                }
            }
            // end table
            writer.write("\n);\n\n");
            writer.write("ALTER TYPE \"" + schema + "\".\"" + type + "\" OWNER TO " + "myenergy" + ";\n\n");
        }
    }

    public void close()
    {
        if (this.connection != null)
        {
            try
            {
                this.connection.close();
            }
            catch (Exception e)
            {
            }
        }
    }
}


text:
layout: default
title: 维基词典
---
# 维基词典

<!-- [Wiktionary](http://www.wiktionary.org)  is an online dictionary for several languages with limited spoken words. -->

[维基词典](http://www.wiktionary.org)是一个支持多钟语言的在线词典。

<!-- Because Wiktionary has a very limited set of spoken words, you may want to  use it as [part of a service group](/usage/groups.html) so that you can  fallback to [another service](/services) when  Wiktionary does not have audio for your input. -->

<!-- ## Requirements -->

## 要求

<!-- An Internet connection is required to use Wiktionary from AwesomeTTS in  addition to having `mplayer` and `lame` available.  Wiktionary is available on all operating systems except Mac OS X, which  lacks a way to convert the OGG files Wiktionary uses. -->

只需要有网就行啦:clap:但是不支持Mac平台,因为Mac不能转换维基词典使用的OGG文件。

<!-- Because Wiktionary is a public Internet service, mass generation of MP3s  using the [tool in the Card Browser](/usage/browser.html) is  rate-limited. In addition, Wiktionary is rate-limited by **twice the  amount** of most of the other Internet-based services because  Wiktionary requires two requests for every word. If you would like to tweak  the rate-limiting behavior for your installation of AwesomeTTS, go to the  [MP3s configuration tab](/config/mp3s.html) and look for the  “Download Throttling” settings. -->

VoiceText对所有AwesomeTTS用户开放,但是[在浏览器中用AwesomeTTS工具](/usage/browser.html)批量生成音频有频率限制,如果你想改变这个限制请移步[音频配置标签](/config/mp3s.html),然后你会看到"下载限制"这个设置。


text:
package org.apache.ignite.loadtests.direct.session;

import java.io.Serializable;
import org.apache.ignite.IgniteLogger;
import org.apache.ignite.compute.ComputeJobAdapter;
import org.apache.ignite.compute.ComputeTaskSession;
import org.apache.ignite.resources.LoggerResource;
import org.apache.ignite.resources.TaskSessionResource;

/**
 * Session load test job.
 */
public class GridSessionLoadTestJob extends ComputeJobAdapter {
    /** */
    @TaskSessionResource
    private ComputeTaskSession taskSes;

    /** */
    @LoggerResource
    private IgniteLogger log;

    /** */
    public GridSessionLoadTestJob() {
        // No-op.
    }

    /**
     * @param arg Argument.
     */
    public GridSessionLoadTestJob(String arg) {
        super(arg);
    }

    /** {@inheritDoc} */
    @Override public Serializable execute() {
        assert taskSes != null;

        Object arg = argument(0);

        assert arg != null;

        Serializable ser = taskSes.getAttribute(arg);

        assert ser != null;

        int val = (Integer)ser + 1;

        // Generate garbage.
        for (int i = 0; i < 10; i++)
            taskSes.setAttribute(arg, i);

        // Set final value.
        taskSes.setAttribute(arg, val);

        if (log.isDebugEnabled())
            log.debug("Set session attribute [name=" + arg + ", value=" + val + ']');

        return val;
    }
}