<commit_before>/*
 *
 * Copyright 2015 gRPC authors.
 *
 * 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.
 *
 */

/* Posix implementation for gpr threads. */

#include <grpc/support/port_platform.h>

#ifdef GPR_POSIX_SYNC

#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/sync.h>
#include <grpc/support/thd.h>
#include <grpc/support/useful.h>
#include <pthread.h>
#include <stdlib.h>
#include <string.h>

#include "src/core/lib/gpr/fork.h"

static gpr_mu g_mu;
static gpr_cv g_cv;
static int g_thread_count;
static int g_awaiting_threads;

struct thd_arg {
  void (*body)(void* arg); /* body of a thread */
  void* arg;               /* argument to a thread */
  const char* name;        /* name of thread. Can be nullptr. */
};

static void inc_thd_count();
static void dec_thd_count();

/* Body of every thread started via gpr_thd_new. */
static void* thread_body(void* v) {
  struct thd_arg a = *(struct thd_arg*)v;
  free(v);
  if (a.name != nullptr) {
#if GPR_APPLE_PTHREAD_NAME
    /* Apple supports 64 characters, and will truncate if it's longer. */
    pthread_setname_np(a.name);
#elif GPR_TIZENRT_PTHREAD_NAME
    pthread_setname_np(pthread_self(), a.name);
#elif GPR_LINUX_PTHREAD_NAME
    /* Linux supports 16 characters max, and will error if it's longer. */
    char buf[16];
    size_t buf_len = GPR_ARRAY_SIZE(buf) - 1;
    strncpy(buf, a.name, buf_len);
    buf[buf_len] = '\0';
    pthread_setname_np(pthread_self(), buf);
#endif  // GPR_APPLE_PTHREAD_NAME
  }
  (*a.body)(a.arg);
  dec_thd_count();
  return nullptr;
}

// TODO(TizenRT)
#ifndef GRPC_THD_CLIENT_STACK_SIZE
#define GRPC_THD_CLIENT_STACK_SIZE 10240
#endif
int gpr_thd_new(gpr_thd_id* t, const char* thd_name,
                void (*thd_body)(void* arg), void* arg,
                const gpr_thd_options* options) {
  int thread_started;
  pthread_attr_t attr;
  pthread_t p;
  /* don't use gpr_malloc as we may cause an infinite recursion with
   * the profiling code */
  struct thd_arg* a = (struct thd_arg*)malloc(sizeof(*a));
  GPR_ASSERT(a != nullptr);
  a->body = thd_body;
  a->arg = arg;
  a->name = thd_name;
  inc_thd_count();

  GPR_ASSERT(pthread_attr_init(&attr) == 0);
  // TODO(TizenRT)
  #ifndef __TizenRT__
  if (gpr_thd_options_is_detached(options)) {
    GPR_ASSERT(pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED) ==
               0);
  } else {
    GPR_ASSERT(pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE) ==
               0);
  }
  #else
  int r;
  if ((r = pthread_attr_setstacksize(&attr, GRPC_THD_CLIENT_STACK_SIZE)) != 0) {
		return -1;
  }
  #endif
  thread_started = (pthread_create(&p, &attr, &thread_body, a) == 0);
  GPR_ASSERT(pthread_attr_destroy(&attr) == 0);
  if (!thread_started) {
    /* don't use gpr_free, as this was allocated using malloc (see above) */
    free(a);
    dec_thd_count();
  }
  *t = (gpr_thd_id)p;
  return thread_started;
}

gpr_thd_id gpr_thd_currentid(void) { return (gpr_thd_id)pthread_self(); }

void gpr_thd_join(gpr_thd_id t) { pthread_join((pthread_t)t, nullptr); }

/*****************************************
 * Only used when fork support is enabled
 */

static void inc_thd_count() {
  if (grpc_fork_support_enabled()) {
    gpr_mu_lock(&g_mu);
    g_thread_count++;
    gpr_mu_unlock(&g_mu);
  }
}

static void dec_thd_count() {
  if (grpc_fork_support_enabled()) {
    gpr_mu_lock(&g_mu);
    g_thread_count--;
    if (g_awaiting_threads && g_thread_count == 0) {
      gpr_cv_signal(&g_cv);
    }
    gpr_mu_unlock(&g_mu);
  }
}

void gpr_thd_init() {
  gpr_mu_init(&g_mu);
  gpr_cv_init(&g_cv);
  g_thread_count = 0;
  g_awaiting_threads = 0;
}

int gpr_await_threads(gpr_timespec deadline) {
  gpr_mu_lock(&g_mu);
  g_awaiting_threads = 1;
  int res = 0;
  if (g_thread_count > 0) {
    res = gpr_cv_wait(&g_cv, &g_mu, deadline);
  }
  g_awaiting_threads = 0;
  gpr_mu_unlock(&g_mu);
  return res == 0;
}

#endif /* GPR_POSIX_SYNC */
<commit_msg>external/grpc: Name grpc threads for debugging purposes, and understandability<commit_after>/*
 *
 * Copyright 2015 gRPC authors.
 *
 * 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.
 *
 */

/* Posix implementation for gpr threads. */

#include <grpc/support/port_platform.h>

#ifdef GPR_POSIX_SYNC

#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/sync.h>
#include <grpc/support/thd.h>
#include <grpc/support/useful.h>
#include <pthread.h>
#include <stdlib.h>
#include <string.h>

#include "src/core/lib/gpr/fork.h"

static gpr_mu g_mu;
static gpr_cv g_cv;
static int g_thread_count;
static int g_awaiting_threads;

struct thd_arg {
  void (*body)(void* arg); /* body of a thread */
  void* arg;               /* argument to a thread */
  const char* name;        /* name of thread. Can be nullptr. */
};

static void inc_thd_count();
static void dec_thd_count();

/* Body of every thread started via gpr_thd_new. */
static void* thread_body(void* v) {
  struct thd_arg a = *(struct thd_arg*)v;
  free(v);
  if (a.name != nullptr) {
#if GPR_APPLE_PTHREAD_NAME
    /* Apple supports 64 characters, and will truncate if it's longer. */
    pthread_setname_np(a.name);
#elif GPR_TIZENRT_PTHREAD_NAME
    pthread_setname_np(pthread_self(), a.name);
#elif GPR_LINUX_PTHREAD_NAME
    /* Linux supports 16 characters max, and will error if it's longer. */
    char buf[16];
    size_t buf_len = GPR_ARRAY_SIZE(buf) - 1;
    strncpy(buf, a.name, buf_len);
    buf[buf_len] = '\0';
    pthread_setname_np(pthread_self(), buf);
#endif  // GPR_APPLE_PTHREAD_NAME
  }
  (*a.body)(a.arg);
  dec_thd_count();
  return nullptr;
}

// TODO(TizenRT)
#ifndef GRPC_THD_CLIENT_STACK_SIZE
#define GRPC_THD_CLIENT_STACK_SIZE 10240
#endif
int gpr_thd_new(gpr_thd_id* t, const char* thd_name,
                void (*thd_body)(void* arg), void* arg,
                const gpr_thd_options* options) {
  int thread_started;
  pthread_attr_t attr;
  pthread_t p;
  /* don't use gpr_malloc as we may cause an infinite recursion with
   * the profiling code */
  struct thd_arg* a = (struct thd_arg*)malloc(sizeof(*a));
  GPR_ASSERT(a != nullptr);
  a->body = thd_body;
  a->arg = arg;
  a->name = thd_name;
  inc_thd_count();

  GPR_ASSERT(pthread_attr_init(&attr) == 0);
  // TODO(TizenRT)
  #ifndef __TizenRT__
  if (gpr_thd_options_is_detached(options)) {
    GPR_ASSERT(pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED) ==
               0);
  } else {
    GPR_ASSERT(pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE) ==
               0);
  }
  #else
  int r;
  if ((r = pthread_attr_setstacksize(&attr, GRPC_THD_CLIENT_STACK_SIZE)) != 0) {
		return -1;
  }
  #endif
  thread_started = (pthread_create(&p, &attr, &thread_body, a) == 0);
  GPR_ASSERT(pthread_attr_destroy(&attr) == 0);
  if (!thread_started) {
    /* don't use gpr_free, as this was allocated using malloc (see above) */
    free(a);
    dec_thd_count();
  } else {
    pthread_setname_np(thread_started, a->name);
  }
  *t = (gpr_thd_id)p;
  return thread_started;
}

gpr_thd_id gpr_thd_currentid(void) { return (gpr_thd_id)pthread_self(); }

void gpr_thd_join(gpr_thd_id t) { pthread_join((pthread_t)t, nullptr); }

/*****************************************
 * Only used when fork support is enabled
 */

static void inc_thd_count() {
  if (grpc_fork_support_enabled()) {
    gpr_mu_lock(&g_mu);
    g_thread_count++;
    gpr_mu_unlock(&g_mu);
  }
}

static void dec_thd_count() {
  if (grpc_fork_support_enabled()) {
    gpr_mu_lock(&g_mu);
    g_thread_count--;
    if (g_awaiting_threads && g_thread_count == 0) {
      gpr_cv_signal(&g_cv);
    }
    gpr_mu_unlock(&g_mu);
  }
}

void gpr_thd_init() {
  gpr_mu_init(&g_mu);
  gpr_cv_init(&g_cv);
  g_thread_count = 0;
  g_awaiting_threads = 0;
}

int gpr_await_threads(gpr_timespec deadline) {
  gpr_mu_lock(&g_mu);
  g_awaiting_threads = 1;
  int res = 0;
  if (g_thread_count > 0) {
    res = gpr_cv_wait(&g_cv, &g_mu, deadline);
  }
  g_awaiting_threads = 0;
  gpr_mu_unlock(&g_mu);
  return res == 0;
}

#endif /* GPR_POSIX_SYNC */
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: WinImplHelper.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-20 00:14:57 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _WINIMPLHELPER_HXX_
#define _WINIMPLHELPER_HXX_

//------------------------------------------------------------------------
// includes
//------------------------------------------------------------------------

#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif

#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif

#include <windows.h>

#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif

#ifndef _COM_SUN_STAR_LANG_ILLEGALARGUMENTEXCEPTION_HPP_
#include <com/sun/star/lang/IllegalArgumentException.hpp>
#endif

//------------------------------------------------------------------------
// deklarations
//------------------------------------------------------------------------

bool SAL_CALL IsWindows2000();
bool SAL_CALL IsWindowsXP();
bool SAL_CALL IsWindows98();
bool SAL_CALL IsWindowsME();

// returns true if the platform is
// Windows 2000 or above
bool SAL_CALL IsWindows2000Platform();

#define IsWin2000 IsWindows2000

// set actions
void SAL_CALL ListboxAddItem(
    HWND hwnd, const ::com::sun::star::uno::Any& aItem, const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& rXInterface, sal_Int16 aArgPos )
    throw( ::com::sun::star::lang::IllegalArgumentException );

void SAL_CALL ListboxAddItems(
    HWND hwnd, const ::com::sun::star::uno::Any& aItemList, const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& rXInterface, sal_Int16 aArgPos )
    throw( ::com::sun::star::lang:: IllegalArgumentException );

void SAL_CALL ListboxDeleteItem(
    HWND hwnd, const ::com::sun::star::uno::Any& aPosition, const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& rXInterface, sal_Int16 aArgPos )
    throw( ::com::sun::star::lang::IllegalArgumentException );

void SAL_CALL ListboxDeleteItems(
    HWND hwnd, const ::com::sun::star::uno::Any& aUnused, const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& rXInterface, sal_Int16 aArgPos )
    throw( ::com::sun::star::lang::IllegalArgumentException );

void SAL_CALL ListboxSetSelectedItem(
    HWND hwnd, const ::com::sun::star::uno::Any& aPosition, const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& rXInterface, sal_Int16 aArgPos )
    throw( ::com::sun::star::lang::IllegalArgumentException );

// get actions
::com::sun::star::uno::Any SAL_CALL ListboxGetItems( HWND hwnd );
::com::sun::star::uno::Any SAL_CALL ListboxGetSelectedItem( HWND hwnd );
::com::sun::star::uno::Any SAL_CALL ListboxGetSelectedItemIndex( HWND hwnd );

// checkbox helper functions
::com::sun::star::uno::Any SAL_CALL CheckboxGetState( HWND hwnd );

void SAL_CALL CheckboxSetState(
    HWND hwnd, const ::com::sun::star::uno::Any& aState, const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& rXInterface, sal_Int16 aArgPos )
    throw( ::com::sun::star::lang::IllegalArgumentException );

// calculates the length of '\0' separated and '\0\0'
// ending strings used in some Win32 functions
// e.g. Filter\0*.txt\0\0
// the returned length excludes the last '\0'
sal_uInt32 SAL_CALL _wcslenex( const sal_Unicode* pStr );

// converts a soffice label to a windows label
// the following rules for character replacements
// will be done:
// '~'  -> '&'
// '~~' -> '~'
// '&'  -> '&&'
rtl::OUString SOfficeToWindowsLabel( const rtl::OUString& aSOLabel );

// converts a windows label to a soffice label
// the following rules for character replacements
// will be done:
// '&'  -> '~'
// '&&' -> '&'
// '~'  -> '~~'
rtl::OUString WindowsToSOfficeLabel( const rtl::OUString& aWinLabel );

#endif
<commit_msg>INTEGRATION: CWS sb59 (1.6.30); FILE MERGED 2006/08/10 12:04:54 sb 1.6.30.1: #i67487# Made code warning-free (wntmsci10).<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: WinImplHelper.hxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: obo $ $Date: 2006-10-12 10:56:24 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _WINIMPLHELPER_HXX_
#define _WINIMPLHELPER_HXX_

//------------------------------------------------------------------------
// includes
//------------------------------------------------------------------------

#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif

#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif

#if defined _MSC_VER
#pragma warning(push, 1)
#endif
#include <windows.h>
#if defined _MSC_VER
#pragma warning(pop)
#endif

#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif

#ifndef _COM_SUN_STAR_LANG_ILLEGALARGUMENTEXCEPTION_HPP_
#include <com/sun/star/lang/IllegalArgumentException.hpp>
#endif

//------------------------------------------------------------------------
// deklarations
//------------------------------------------------------------------------

bool SAL_CALL IsWindows2000();
bool SAL_CALL IsWindowsXP();
bool SAL_CALL IsWindows98();
bool SAL_CALL IsWindowsME();

// returns true if the platform is
// Windows 2000 or above
bool SAL_CALL IsWindows2000Platform();

#define IsWin2000 IsWindows2000

// set actions
void SAL_CALL ListboxAddItem(
    HWND hwnd, const ::com::sun::star::uno::Any& aItem, const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& rXInterface, sal_Int16 aArgPos )
    throw( ::com::sun::star::lang::IllegalArgumentException );

void SAL_CALL ListboxAddItems(
    HWND hwnd, const ::com::sun::star::uno::Any& aItemList, const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& rXInterface, sal_Int16 aArgPos )
    throw( ::com::sun::star::lang:: IllegalArgumentException );

void SAL_CALL ListboxDeleteItem(
    HWND hwnd, const ::com::sun::star::uno::Any& aPosition, const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& rXInterface, sal_Int16 aArgPos )
    throw( ::com::sun::star::lang::IllegalArgumentException );

void SAL_CALL ListboxDeleteItems(
    HWND hwnd, const ::com::sun::star::uno::Any& aUnused, const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& rXInterface, sal_Int16 aArgPos )
    throw( ::com::sun::star::lang::IllegalArgumentException );

void SAL_CALL ListboxSetSelectedItem(
    HWND hwnd, const ::com::sun::star::uno::Any& aPosition, const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& rXInterface, sal_Int16 aArgPos )
    throw( ::com::sun::star::lang::IllegalArgumentException );

// get actions
::com::sun::star::uno::Any SAL_CALL ListboxGetItems( HWND hwnd );
::com::sun::star::uno::Any SAL_CALL ListboxGetSelectedItem( HWND hwnd );
::com::sun::star::uno::Any SAL_CALL ListboxGetSelectedItemIndex( HWND hwnd );

// checkbox helper functions
::com::sun::star::uno::Any SAL_CALL CheckboxGetState( HWND hwnd );

void SAL_CALL CheckboxSetState(
    HWND hwnd, const ::com::sun::star::uno::Any& aState, const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& rXInterface, sal_Int16 aArgPos )
    throw( ::com::sun::star::lang::IllegalArgumentException );

// calculates the length of '\0' separated and '\0\0'
// ending strings used in some Win32 functions
// e.g. Filter\0*.txt\0\0
// the returned length excludes the last '\0'
sal_uInt32 SAL_CALL _wcslenex( const sal_Unicode* pStr );

// converts a soffice label to a windows label
// the following rules for character replacements
// will be done:
// '~'  -> '&'
// '~~' -> '~'
// '&'  -> '&&'
rtl::OUString SOfficeToWindowsLabel( const rtl::OUString& aSOLabel );

// converts a windows label to a soffice label
// the following rules for character replacements
// will be done:
// '&'  -> '~'
// '&&' -> '&'
// '~'  -> '~~'
rtl::OUString WindowsToSOfficeLabel( const rtl::OUString& aWinLabel );

#endif
<|endoftext|>


<commit_before>#ifndef	ANN_SCENERY_MANAGER
#define ANN_SCENERY_MANAGER

#include "systemMacro.h"
#include "AnnSubsystem.hpp"
#include "OgreSceneManager.h"
#include "AnnTypes.h"
#include "OgreVRRender.hpp"

namespace Annwvyn
{
	class DLL AnnSceneryManager : public AnnSubSystem
	{
	public:

		///Construct the AnnSceneryManager
		AnnSceneryManager(OgreVRRender* renderer);

		///This subsystem doesn't need to be updated
		bool needUpdate() { return false; }

		///Set the ogre material for the skydome with params
		/// \param activate if true put a skydome
		/// \param materialName name of a material known from the Ogre Resource group manager
		/// \param curvature curvature of the texture
		/// \param tilling tilling of the texture
		void setSkyDomeMaterial(bool activate,
			const char materialName[],
			float curvature = 2.0f,
			float tiling = 1.0f); //scene

		///Set the ogre material for the skybox with params
		/// \param activate if true put the skybox on the scene
		/// \param materialName name of a material declared on the resource manager
		/// \param distance distance of the sky from the camera
		/// \param renderedFirst if true, the skybox will be the first thing rendered
		void setSkyBoxMaterial(bool activate,
			const char materialName[],
			float distance = 8000,
			bool renderedFirst = true);

		///Set the viewports background color
		/// \param v background color
		void setWorldBackgroundColor(AnnColor color = AnnColor(0, 0.56, 1));

		///Remove the sky dome
		void removeSkyDome();

		///Remove the sky box
		void removeSkyBox();

		///Set the ambiant light
		/// \param v the color of the light
		void setAmbiantLight(AnnColor color);

		///Set the distance of the near clipping plane
		/// \param distace the distance to the clipping plane
		void setNearClippingDistance(float distance);

	private:
		///Scene manager created by the VR renderer
		Ogre::SceneManager* smgr;

		///Pointer to the VR renderer
		OgreVRRender* renderer;
	};
}

#endif<commit_msg>Correct warning double -> float<commit_after>#ifndef	ANN_SCENERY_MANAGER
#define ANN_SCENERY_MANAGER

#include "systemMacro.h"
#include "AnnSubsystem.hpp"
#include "OgreSceneManager.h"
#include "AnnTypes.h"
#include "OgreVRRender.hpp"

namespace Annwvyn
{
	class DLL AnnSceneryManager : public AnnSubSystem
	{
	public:

		///Construct the AnnSceneryManager
		AnnSceneryManager(OgreVRRender* renderer);

		///This subsystem doesn't need to be updated
		bool needUpdate() { return false; }

		///Set the ogre material for the skydome with params
		/// \param activate if true put a skydome
		/// \param materialName name of a material known from the Ogre Resource group manager
		/// \param curvature curvature of the texture
		/// \param tilling tilling of the texture
		void setSkyDomeMaterial(bool activate,
			const char materialName[],
			float curvature = 2.0f,
			float tiling = 1.0f); //scene

		///Set the ogre material for the skybox with params
		/// \param activate if true put the skybox on the scene
		/// \param materialName name of a material declared on the resource manager
		/// \param distance distance of the sky from the camera
		/// \param renderedFirst if true, the skybox will be the first thing rendered
		void setSkyBoxMaterial(bool activate,
			const char materialName[],
			float distance = 8000,
			bool renderedFirst = true);

		///Set the viewports background color
		/// \param v background color
		void setWorldBackgroundColor(AnnColor color = AnnColor(0, 0.56f, 1));

		///Remove the sky dome
		void removeSkyDome();

		///Remove the sky box
		void removeSkyBox();

		///Set the ambiant light
		/// \param v the color of the light
		void setAmbiantLight(AnnColor color);

		///Set the distance of the near clipping plane
		/// \param distace the distance to the clipping plane
		void setNearClippingDistance(float distance);

	private:
		///Scene manager created by the VR renderer
		Ogre::SceneManager* smgr;

		///Pointer to the VR renderer
		OgreVRRender* renderer;
	};
}

#endif<|endoftext|>


<commit_before>#ifndef __LOG_VISOR_HPP__
#define __LOG_VISOR_HPP__

#include <stdarg.h>
#include <string.h>
#include <stdio.h>
#include <vector>
#include <atomic>
#include <memory>
#include <locale>
#include <codecvt>

namespace LogVisor
{

#if _WIN32 && UNICODE
#define LOG_UCS2 1
#endif

#if LOG_VISOR_EXCEPTIONS
/**
 * @brief Exception thrown when FatalError is issued
 */
class FatalException : public std::exception
{
    std::string m_what;
public:
    FatalException(const char* format, va_list ap)
    {
        char buf[1024];
        vsnprintf(buf, 1024, format, ap);
        m_what.assign(buf);
    }
    FatalException(const wchar_t* format, va_list ap)
    {
        wchar_t buf[1024];
        vswprintf(buf, 1024, format, ap);
        std::wstring_convert<std::codecvt_utf8<wchar_t>> conv;
        m_what.assign(conv.to_bytes(buf));
    }
#if _MSC_VER
    inline const char* what() const {return m_what.c_str();}
#else
    inline const char* what() const noexcept {return m_what.c_str();}
#endif
};
#endif

/**
 * @brief Severity level for log messages
 */
enum Level
{
    Info,        /**< Non-error informative message */
    Warning,     /**< Non-error warning message */
    Error,       /**< Recoverable error message */
    FatalError   /**< Non-recoverable error message (throws exception) */
};

/**
 * @brief Backend interface for receiving app-wide log events
 */
struct ILogger
{
    virtual ~ILogger() {}
    virtual void report(const char* modName, Level severity,
                        const char* format, va_list ap)=0;
    virtual void report(const char* modName, Level severity,
                        const wchar_t* format, va_list ap)=0;
    virtual void reportSource(const char* modName, Level severity,
                              const char* file, unsigned linenum,
                              const char* format, va_list ap)=0;
    virtual void reportSource(const char* modName, Level severity,
                              const char* file, unsigned linenum,
                              const wchar_t* format, va_list ap)=0;
};

/**
 * @brief Assign calling thread a descriptive name
 * @param name Descriptive thread name
 */
void RegisterThreadName(const char* name);

/**
 * @brief Centralized logger vector
 *
 * All loggers added to this vector will receive reports as they occur
 */
extern std::vector<std::unique_ptr<ILogger>> MainLoggers;

/**
 * @brief Centralized error counter
 *
 * All submodules accumulate this value
 */
extern std::atomic_size_t ErrorCount;

/**
 * @brief Centralized frame index
 *
 * All log events include this as part of their timestamp if non-zero.
 * The default value is zero, the app is responsible for updating it
 * within its main loop.
 */
extern std::atomic_uint_fast64_t FrameIndex;

/**
 * @brief Restore centralized logger vector to default state (silent operation)
 */
static inline void UnregisterLoggers() {MainLoggers.clear();}

/**
 * @brief Construct and register a real-time console logger singleton
 *
 * This will output to stderr on POSIX platforms and spawn a new console window on Windows.
 * If there's already a registered console logger, this is a no-op.
 */
void RegisterConsoleLogger();

/**
 * @brief Construct and register a file logger
 * @param filepath Path to write the file
 *
 * If there's already a file logger registered to the same file, this is a no-op.
 */
void RegisterFileLogger(const char* filepath);

#if LOG_UCS2

/**
 * @brief Construct and register a file logger (wchar_t version)
 * @param filepath Path to write the file
 *
 * If there's already a file logger registered to the same file, this is a no-op.
 */
void RegisterFileLogger(const wchar_t* filepath);

#endif

/**
 * @brief This is constructed per-subsystem in a locally centralized fashon
 */
class LogModule
{
    const char* m_modName;
public:
    LogModule(const char* modName) : m_modName(modName) {}

    /**
     * @brief Route new log message to centralized ILogger
     * @param severity Level of log report severity
     * @param format Standard printf-style format string
     */
    template <typename CharType>
    inline void report(Level severity, const CharType* format, ...)
    {
        va_list ap;
        va_start(ap, format);
        report(severity, format, ap);
        va_end(ap);
    }

    template <typename CharType>
    inline void report(Level severity, const CharType* format, va_list ap)
    {
        for (auto& logger : MainLoggers)
            logger->report(m_modName, severity, format, ap);
        if (severity == FatalError)
#if LOG_VISOR_EXCEPTIONS
            throw FatalException(format, ap);
#else
            abort();
#endif
        else if (severity == Error)
            ++ErrorCount;
    }

    /**
     * @brief Route new log message with source info to centralized ILogger
     * @param severity Level of log report severity
     * @param file Source file name from __FILE__ macro
     * @param linenum Source line number from __LINE__ macro
     * @param format Standard printf-style format string
     */
    template <typename CharType>
    inline void reportSource(Level severity, const char* file, unsigned linenum, const CharType* format, ...)
    {
        va_list ap;
        va_start(ap, format);
        reportSource(severity, file, linenum, format, ap);
        va_end(ap);
    }

    template <typename CharType>
    inline void reportSource(Level severity, const char* file, unsigned linenum, const CharType* format, va_list ap)
    {
        for (auto& logger : MainLoggers)
            logger->reportSource(m_modName, severity, file, linenum, format, ap);
        if (severity == FatalError)
#if LOG_VISOR_EXCEPTIONS
            throw FatalException(format, ap);
#else
            abort();
#endif
        else if (severity == Error)
            ++ErrorCount;
    }
};

}

#endif // __LOG_VISOR_HPP__
<commit_msg>Removed exceptions completely<commit_after>#ifndef __LOG_VISOR_HPP__
#define __LOG_VISOR_HPP__

#include <stdarg.h>
#include <string.h>
#include <stdio.h>
#include <vector>
#include <atomic>
#include <memory>

namespace LogVisor
{

#if _WIN32 && UNICODE
#define LOG_UCS2 1
#endif

/**
 * @brief Severity level for log messages
 */
enum Level
{
    Info,        /**< Non-error informative message */
    Warning,     /**< Non-error warning message */
    Error,       /**< Recoverable error message */
    FatalError   /**< Non-recoverable error message (throws exception) */
};

/**
 * @brief Backend interface for receiving app-wide log events
 */
struct ILogger
{
    virtual ~ILogger() {}
    virtual void report(const char* modName, Level severity,
                        const char* format, va_list ap)=0;
    virtual void report(const char* modName, Level severity,
                        const wchar_t* format, va_list ap)=0;
    virtual void reportSource(const char* modName, Level severity,
                              const char* file, unsigned linenum,
                              const char* format, va_list ap)=0;
    virtual void reportSource(const char* modName, Level severity,
                              const char* file, unsigned linenum,
                              const wchar_t* format, va_list ap)=0;
};

/**
 * @brief Assign calling thread a descriptive name
 * @param name Descriptive thread name
 */
void RegisterThreadName(const char* name);

/**
 * @brief Centralized logger vector
 *
 * All loggers added to this vector will receive reports as they occur
 */
extern std::vector<std::unique_ptr<ILogger>> MainLoggers;

/**
 * @brief Centralized error counter
 *
 * All submodules accumulate this value
 */
extern std::atomic_size_t ErrorCount;

/**
 * @brief Centralized frame index
 *
 * All log events include this as part of their timestamp if non-zero.
 * The default value is zero, the app is responsible for updating it
 * within its main loop.
 */
extern std::atomic_uint_fast64_t FrameIndex;

/**
 * @brief Restore centralized logger vector to default state (silent operation)
 */
static inline void UnregisterLoggers() {MainLoggers.clear();}

/**
 * @brief Construct and register a real-time console logger singleton
 *
 * This will output to stderr on POSIX platforms and spawn a new console window on Windows.
 * If there's already a registered console logger, this is a no-op.
 */
void RegisterConsoleLogger();

/**
 * @brief Construct and register a file logger
 * @param filepath Path to write the file
 *
 * If there's already a file logger registered to the same file, this is a no-op.
 */
void RegisterFileLogger(const char* filepath);

#if LOG_UCS2

/**
 * @brief Construct and register a file logger (wchar_t version)
 * @param filepath Path to write the file
 *
 * If there's already a file logger registered to the same file, this is a no-op.
 */
void RegisterFileLogger(const wchar_t* filepath);

#endif

/**
 * @brief This is constructed per-subsystem in a locally centralized fashon
 */
class LogModule
{
    const char* m_modName;
public:
    LogModule(const char* modName) : m_modName(modName) {}

    /**
     * @brief Route new log message to centralized ILogger
     * @param severity Level of log report severity
     * @param format Standard printf-style format string
     */
    template <typename CharType>
    inline void report(Level severity, const CharType* format, ...)
    {
        va_list ap;
        va_start(ap, format);
        report(severity, format, ap);
        va_end(ap);
    }

    template <typename CharType>
    inline void report(Level severity, const CharType* format, va_list ap)
    {
        for (auto& logger : MainLoggers)
            logger->report(m_modName, severity, format, ap);
        if (severity == FatalError)
            abort();
        else if (severity == Error)
            ++ErrorCount;
    }

    /**
     * @brief Route new log message with source info to centralized ILogger
     * @param severity Level of log report severity
     * @param file Source file name from __FILE__ macro
     * @param linenum Source line number from __LINE__ macro
     * @param format Standard printf-style format string
     */
    template <typename CharType>
    inline void reportSource(Level severity, const char* file, unsigned linenum, const CharType* format, ...)
    {
        va_list ap;
        va_start(ap, format);
        reportSource(severity, file, linenum, format, ap);
        va_end(ap);
    }

    template <typename CharType>
    inline void reportSource(Level severity, const char* file, unsigned linenum, const CharType* format, va_list ap)
    {
        for (auto& logger : MainLoggers)
            logger->reportSource(m_modName, severity, file, linenum, format, ap);
        if (severity == FatalError)
            abort();
        else if (severity == Error)
            ++ErrorCount;
    }
};

}

#endif // __LOG_VISOR_HPP__
<|endoftext|>


<commit_before>/*$Id$
 *
 * This source file is a part of the Berlin Project.
 * Copyright (C) 1999 Stefan Seefeld <seefelds@magellan.umontreal.ca>
 * http://www.berlin-consortium.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
 * MA 02139, USA.
 */
#ifndef _Plugin_hh
#define _Plugin_hh

#include <Prague/Sys/DLL.hh>

namespace Prague
{

template <class T>
class Plugin : public DLL
{
public:
  Plugin(const string &file, const string &loader = "load") : DLL(file)
    {
      typedef T *(* DL) ();
      DL dl = (DL) resolve(loader);
      t = dl ? (T *) dl() : 0;
    }
  ~Dynamic() { delete t;}
  T *operator () { return t;}
private:
  T *t;
};

#define dload(T) extern "C" T *load() { return new T;}

};

#endif /* _Plugin_hh */
<commit_msg><commit_after>/*$Id$
 *
 * This source file is a part of the Berlin Project.
 * Copyright (C) 1999 Stefan Seefeld <seefelds@magellan.umontreal.ca>
 * http://www.berlin-consortium.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
 * MA 02139, USA.
 */
#ifndef _Plugin_hh
#define _Plugin_hh

#include <Prague/Sys/DLL.hh>

namespace Prague {

template <class T>
class Plugin : public DLL
{
public:
  Plugin(const string &file, const string &loader = "load") : DLL(file)
    {
      typedef T *(* DL) ();
      DL dl = (DL) resolve(loader);
      t = dl ? (T *) dl() : 0;
    }
  ~Plugin() { delete t; }
  T * operator () () { return t; }
protected:
private:
  T *t;
};

#define dload(T) extern "C" T *load() { return new T;}

};

#endif /* _Plugin_hh */
<|endoftext|>


<commit_before>/* Copyright 2019 Axel Huebl, Benjamin Worpitz, Erik Zenker
 *
 * This file is part of alpaka.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#pragma once

#include <alpaka/vec/Vec.hpp>
#include <alpaka/core/Common.hpp>
#include <alpaka/core/Unused.hpp>

#include <type_traits>

namespace alpaka
{
    namespace idx
    {
        namespace detail
        {
            //#############################################################################
            //! Maps a linear index to a N dimensional index.
            template<
                std::size_t TidxDimOut,
                std::size_t TidxDimIn,
                typename TSfinae = void>
            struct MapIdx;
            //#############################################################################
            //! Maps a N dimensional index to the same N dimensional index.
            template<
                std::size_t TidxDim>
            struct MapIdx<
                TidxDim,
                TidxDim>
            {
                //-----------------------------------------------------------------------------
                // \tparam TElem Type of the index values.
                // \param idx Idx to be mapped.
                // \param extent Spatial size to map the index to.
                // \return A N dimensional vector.
                ALPAKA_NO_HOST_ACC_WARNING
                template<
                    typename TElem>
                ALPAKA_FN_HOST_ACC static auto mapIdx(
                    vec::Vec<dim::DimInt<TidxDim>, TElem> const & idx,
                    vec::Vec<dim::DimInt<TidxDim>, TElem> const & extent)
                -> vec::Vec<dim::DimInt<TidxDim>, TElem>
                {
                    alpaka::ignore_unused(extent);

                    return idx;
                }
            };
            //#############################################################################
            //! Maps a 1 dimensional index to a N dimensional index.
            template<
                std::size_t TidxDimOut>
            struct MapIdx<
                TidxDimOut,
                1u,
                std::enable_if_t<TidxDimOut != 1u>>
            {
                //-----------------------------------------------------------------------------
                // \tparam TElem Type of the index values.
                // \param idx Idx to be mapped.
                // \param extent Spatial size to map the index to
                // \return A N dimensional vector.
                ALPAKA_NO_HOST_ACC_WARNING
                template<
                    typename TElem>
                ALPAKA_FN_HOST_ACC static auto mapIdx(
                    vec::Vec<dim::DimInt<1u>, TElem> const & idx,
                    vec::Vec<dim::DimInt<TidxDimOut>, TElem> const & extent)
                -> vec::Vec<dim::DimInt<TidxDimOut>, TElem>
                {
                    auto idxNd(vec::Vec<dim::DimInt<TidxDimOut>, TElem>::all(0u));

                    constexpr std::size_t lastIdx(TidxDimOut - 1u);

                    // fast-dim
                    idxNd[lastIdx] = static_cast<TElem>(idx[0u] % extent[lastIdx]);

                    // in-between
                    TElem hyperPlanesBefore = extent[lastIdx];
                    for(std::size_t r(1u); r < lastIdx; ++r)
                    {
                        std::size_t const d = lastIdx - r;
                        idxNd[d] = static_cast<TElem>(idx[0u] / hyperPlanesBefore % extent[d]);
                        hyperPlanesBefore *= extent[d];
                    }

                    // slow-dim
                    idxNd[0u] = static_cast<TElem>(idx[0u] / hyperPlanesBefore);

                    return idxNd;
                }
            };
            //#############################################################################
            //! Maps a N dimensional index to a 1 dimensional index.
            template<
                std::size_t TidxDimIn>
            struct MapIdx<
                1u,
                TidxDimIn,
                std::enable_if_t<TidxDimIn != 1u>>
            {
                //-----------------------------------------------------------------------------
                // \tparam TElem Type of the index values.
                // \param idx Idx to be mapped.
                // \param extent Spatial size to map the index to.
                // \return A 1 dimensional vector.
                ALPAKA_NO_HOST_ACC_WARNING
                template<
                    typename TElem>
                ALPAKA_FN_HOST_ACC static auto mapIdx(
                    vec::Vec<dim::DimInt<TidxDimIn>, TElem> const & idx,
                    vec::Vec<dim::DimInt<TidxDimIn>, TElem> const & extent)
                -> vec::Vec<dim::DimInt<1u>, TElem>
                {
                    TElem idx1d(idx[0u]);
                    for(std::size_t d(1u); d < TidxDimIn; ++d)
                    {
                        idx1d = static_cast<TElem>(idx1d * extent[d] + idx[d]);
                    }
                    return {idx1d};
                }
            };
        }

        //#############################################################################
        //! Maps a N dimensional index to a N dimensional position.
        //!
        //! \tparam TidxDimOut Dimension of the index vector to map to.
        //! \tparam TidxDimIn Dimension of the index vector to map from.
        //! \tparam TElem Type of the elements of the index vector to map from.
        ALPAKA_NO_HOST_ACC_WARNING
        template<
            std::size_t TidxDimOut,
            std::size_t TidxDimIn,
            typename TElem>
        ALPAKA_FN_HOST_ACC auto mapIdx(
            vec::Vec<dim::DimInt<TidxDimIn>, TElem> const & idx,
            vec::Vec<dim::DimInt<(TidxDimOut < TidxDimIn) ? TidxDimIn : TidxDimOut>, TElem> const & extent)
        -> vec::Vec<dim::DimInt<TidxDimOut>, TElem>
        {
            static_assert(TidxDimOut > 0u, "The dimension of the output vector has to be greater than zero!");
            static_assert(TidxDimIn > 0u, "The dimension of the input vector has to be greater than zero!");

            return
                detail::MapIdx<
                    TidxDimOut,
                    TidxDimIn>
                ::mapIdx(
                    idx,
                    extent);
        }
    }
}
<commit_msg>Add MapIdxPitch<commit_after>/* Copyright 2019 Axel Huebl, Benjamin Worpitz, Erik Zenker
 *
 * This file is part of alpaka.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#pragma once

#include <alpaka/vec/Vec.hpp>
#include <alpaka/core/Common.hpp>
#include <alpaka/core/Unused.hpp>

#include <type_traits>

namespace alpaka
{
    namespace idx
    {
        namespace detail
        {
            //#############################################################################
            //! Maps a linear index to a N dimensional index.
            template<
                std::size_t TidxDimOut,
                std::size_t TidxDimIn,
                typename TSfinae = void>
            struct MapIdx;
            //#############################################################################
            //! Maps a N dimensional index to the same N dimensional index.
            template<
                std::size_t TidxDim>
            struct MapIdx<
                TidxDim,
                TidxDim>
            {
                //-----------------------------------------------------------------------------
                // \tparam TElem Type of the index values.
                // \param idx Idx to be mapped.
                // \param extent Spatial size to map the index to.
                // \return A N dimensional vector.
                ALPAKA_NO_HOST_ACC_WARNING
                template<
                    typename TElem>
                ALPAKA_FN_HOST_ACC static auto mapIdx(
                    vec::Vec<dim::DimInt<TidxDim>, TElem> const & idx,
                    vec::Vec<dim::DimInt<TidxDim>, TElem> const & extent)
                -> vec::Vec<dim::DimInt<TidxDim>, TElem>
                {
                    alpaka::ignore_unused(extent);

                    return idx;
                }
            };
            //#############################################################################
            //! Maps a 1 dimensional index to a N dimensional index.
            template<
                std::size_t TidxDimOut>
            struct MapIdx<
                TidxDimOut,
                1u,
                std::enable_if_t<TidxDimOut != 1u>>
            {
                //-----------------------------------------------------------------------------
                // \tparam TElem Type of the index values.
                // \param idx Idx to be mapped.
                // \param extent Spatial size to map the index to
                // \return A N dimensional vector.
                ALPAKA_NO_HOST_ACC_WARNING
                template<
                    typename TElem>
                ALPAKA_FN_HOST_ACC static auto mapIdx(
                    vec::Vec<dim::DimInt<1u>, TElem> const & idx,
                    vec::Vec<dim::DimInt<TidxDimOut>, TElem> const & extent)
                -> vec::Vec<dim::DimInt<TidxDimOut>, TElem>
                {
                    auto idxNd(vec::Vec<dim::DimInt<TidxDimOut>, TElem>::all(0u));

                    constexpr std::size_t lastIdx(TidxDimOut - 1u);

                    // fast-dim
                    idxNd[lastIdx] = static_cast<TElem>(idx[0u] % extent[lastIdx]);

                    // in-between
                    TElem hyperPlanesBefore = extent[lastIdx];
                    for(std::size_t r(1u); r < lastIdx; ++r)
                    {
                        std::size_t const d = lastIdx - r;
                        idxNd[d] = static_cast<TElem>(idx[0u] / hyperPlanesBefore % extent[d]);
                        hyperPlanesBefore *= extent[d];
                    }

                    // slow-dim
                    idxNd[0u] = static_cast<TElem>(idx[0u] / hyperPlanesBefore);

                    return idxNd;
                }
            };
            //#############################################################################
            //! Maps a N dimensional index to a 1 dimensional index.
            template<
                std::size_t TidxDimIn>
            struct MapIdx<
                1u,
                TidxDimIn,
                std::enable_if_t<TidxDimIn != 1u>>
            {
                //-----------------------------------------------------------------------------
                // \tparam TElem Type of the index values.
                // \param idx Idx to be mapped.
                // \param extent Spatial size to map the index to.
                // \return A 1 dimensional vector.
                ALPAKA_NO_HOST_ACC_WARNING
                template<
                    typename TElem>
                ALPAKA_FN_HOST_ACC static auto mapIdx(
                    vec::Vec<dim::DimInt<TidxDimIn>, TElem> const & idx,
                    vec::Vec<dim::DimInt<TidxDimIn>, TElem> const & extent)
                -> vec::Vec<dim::DimInt<1u>, TElem>
                {
                    TElem idx1d(idx[0u]);
                    for(std::size_t d(1u); d < TidxDimIn; ++d)
                    {
                        idx1d = static_cast<TElem>(idx1d * extent[d] + idx[d]);
                    }
                    return {idx1d};
                }
            };
        }

        //#############################################################################
        //! Maps a N dimensional index to a N dimensional position.
        //!
        //! \tparam TidxDimOut Dimension of the index vector to map to.
        //! \tparam TidxDimIn Dimension of the index vector to map from.
        //! \tparam TElem Type of the elements of the index vector to map from.
        ALPAKA_NO_HOST_ACC_WARNING
        template<
            std::size_t TidxDimOut,
            std::size_t TidxDimIn,
            typename TElem>
        ALPAKA_FN_HOST_ACC auto mapIdx(
            vec::Vec<dim::DimInt<TidxDimIn>, TElem> const & idx,
            vec::Vec<dim::DimInt<(TidxDimOut < TidxDimIn) ? TidxDimIn : TidxDimOut>, TElem> const & extent)
        -> vec::Vec<dim::DimInt<TidxDimOut>, TElem>
        {
            static_assert(TidxDimOut > 0u, "The dimension of the output vector has to be greater than zero!");
            static_assert(TidxDimIn > 0u, "The dimension of the input vector has to be greater than zero!");

            return
                detail::MapIdx<
                    TidxDimOut,
                    TidxDimIn>
                ::mapIdx(
                    idx,
                    extent);
        }

        namespace detail
        {
            //#############################################################################
            //! Maps a linear index to a N dimensional index.
            template<
                std::size_t TidxDimOut,
                std::size_t TidxDimIn,
                typename TSfinae = void>
            struct MapIdxPitch;
            //#############################################################################
            //! Maps a N dimensional index to the same N dimensional index.
            template<
                std::size_t TidxDim>
            struct MapIdxPitch<
                TidxDim,
                TidxDim>
            {
                //-----------------------------------------------------------------------------
                // \tparam TElem Type of the index values.
                // \param idx Idx to be mapped.
                // \param pitch Spatial pitch (in elems) to map the index to
                // \return A N dimensional vector.
                ALPAKA_NO_HOST_ACC_WARNING
                template<
                    typename TElem>
                ALPAKA_FN_HOST_ACC static auto mapIdxPitch(
                    vec::Vec<dim::DimInt<TidxDim>, TElem> const & idx,
                    vec::Vec<dim::DimInt<TidxDim>, TElem> const & pitch)
                -> vec::Vec<dim::DimInt<TidxDim>, TElem>
                {
                    alpaka::ignore_unused(pitch);

                    return idx;
                }
            };
            //#############################################################################
            //! Maps a 1 dimensional index to a N dimensional index.
            template<
                std::size_t TidxDimOut>
            struct MapIdxPitch<
                TidxDimOut,
                1u,
                typename std::enable_if<TidxDimOut != 1u>::type>
            {
                //-----------------------------------------------------------------------------
                // \tparam TElem Type of the index values.
                // \param idx Idx to be mapped.
                // \param pitch Spatial pitch (in elems) to map the index to
                // \return A N dimensional vector.
                ALPAKA_NO_HOST_ACC_WARNING
                template<
                    typename TElem>
                ALPAKA_FN_HOST_ACC static auto mapIdxPitch(
                    vec::Vec<dim::DimInt<1u>, TElem> const & idx,
                    vec::Vec<dim::DimInt<TidxDimOut>, TElem> const & pitch)
                -> vec::Vec<dim::DimInt<TidxDimOut>, TElem>
                {
                    auto idxNd(vec::Vec<dim::DimInt<TidxDimOut>, TElem>::all(0u));

                    constexpr std::size_t lastIdx(TidxDimOut - 1u);

                    TElem tmp = idx[0u];
                    for(std::size_t d(0u); d < lastIdx; ++d)
                    {
                        idxNd[d] = static_cast<TElem>(tmp / pitch[d+1]);
                        tmp %= pitch[d+1];
                    }
                    idxNd[lastIdx] = tmp;

                    return idxNd;
                }
            };
            //#############################################################################
            //! Maps a N dimensional index to a 1 dimensional index.
            template<
                std::size_t TidxDimIn>
            struct MapIdxPitch<
                1u,
                TidxDimIn,
                typename std::enable_if<TidxDimIn != 1u>::type>
            {
                //-----------------------------------------------------------------------------
                // \tparam TElem Type of the index values.
                // \param idx Idx to be mapped.
                // \param pitch Spatial pitch (in elems) to map the index to
                // \return A 1 dimensional vector.
                ALPAKA_NO_HOST_ACC_WARNING
                template<
                    typename TElem>
                ALPAKA_FN_HOST_ACC static auto mapIdxPitch(
                    vec::Vec<dim::DimInt<TidxDimIn>, TElem> const & idx,
                    vec::Vec<dim::DimInt<TidxDimIn>, TElem> const & pitch)
                -> vec::Vec<dim::DimInt<1u>, TElem>
                {
                    constexpr auto lastDim = TidxDimIn - 1;
                    TElem idx1d(idx[lastDim]);
                    for(std::size_t d(0u); d < lastDim; ++d)
                    {
                        idx1d = static_cast<TElem>(idx1d + pitch[d+1] * idx[d]);
                    }
                    return {idx1d};
                }
            };
        }

        //#############################################################################
        //! Maps a N dimensional index to a N dimensional position.
        //!
        //! \tparam TidxDimOut Dimension of the index vector to map to.
        //! \tparam TidxDimIn Dimension of the index vector to map from.
        //! \tparam TElem Type of the elements of the index vector to map from.
        ALPAKA_NO_HOST_ACC_WARNING
        template<
            std::size_t TidxDimOut,
            std::size_t TidxDimIn,
            typename TElem>
        ALPAKA_FN_HOST_ACC auto mapIdxPitch(
            vec::Vec<dim::DimInt<TidxDimIn>, TElem> const & idx,
            vec::Vec<dim::DimInt<(TidxDimOut < TidxDimIn) ? TidxDimIn : TidxDimOut>, TElem> const & pitch)
        -> vec::Vec<dim::DimInt<TidxDimOut>, TElem>
        {
            static_assert(TidxDimOut > 0u, "The dimension of the output vector has to be greater than zero!");
            static_assert(TidxDimIn > 0u, "The dimension of the input vector has to be greater than zero!");

            return
                detail::MapIdxPitch<
                    TidxDimOut,
                    TidxDimIn>
                ::mapIdxPitch(
                    idx,
                    pitch);
        }
    }
}
<|endoftext|>


<commit_before>#include "stdafx.h"
#include "CppUnitTest.h"
#include "..\ProjectEuler\Problem1.h"

using namespace Microsoft::VisualStudio::CppUnitTestFramework;

namespace ProjectEulerTests
{
	TEST_CLASS(Problem1Tests)
	{
	public:

		TEST_METHOD(SumMultiplesOf3And5Below_Input0_Returns0)
		{
            auto result = Problem1::SumMultiplesOf3And5Below(0);
            Assert::AreEqual(0, result);
		}

        TEST_METHOD(SumMultiplesOf3And5Below_Input1_Returns0)
        {
            auto result = Problem1::SumMultiplesOf3And5Below(1);
            Assert::AreEqual(0, result);
        }

        TEST_METHOD(SumMultiplesOf3And5Below_Input2_Returns0)
        {
            auto result = Problem1::SumMultiplesOf3And5Below(2);
            Assert::AreEqual(0, result);
        }

        TEST_METHOD(SumMultiplesOf3And5Below_Input3_Returns0)
        {
            auto result = Problem1::SumMultiplesOf3And5Below(3);
            Assert::AreEqual(0, result);
        }

        TEST_METHOD(SumMultiplesOf3And5Below_Input4_Returns3)
        {
            auto result = Problem1::SumMultiplesOf3And5Below(4);
            Assert::AreEqual(3, result);
        }

        TEST_METHOD(SumMultiplesOf3And5Below_Input5_Returns3)
        {
            auto result = Problem1::SumMultiplesOf3And5Below(5);
            Assert::AreEqual(3, result);
        }

        TEST_METHOD(SumMultiplesOf3And5Below_Input6_Returns8)
        {
            auto result = Problem1::SumMultiplesOf3And5Below(6);
            Assert::AreEqual(8, result);
        }

        TEST_METHOD(SumMultiplesOf3And5Below_Input7_Returns14)
        {
            auto result = Problem1::SumMultiplesOf3And5Below(7);
            Assert::AreEqual(14, result);
        }

        TEST_METHOD(SumMultiplesOf3And5Below_Input8_Returns14)
        {
            auto result = Problem1::SumMultiplesOf3And5Below(8);
            Assert::AreEqual(14, result);
        }

        TEST_METHOD(SumMultiplesOf3And5Below_Input9_Returns14)
        {
            auto result = Problem1::SumMultiplesOf3And5Below(9);
            Assert::AreEqual(14, result);
        }

        TEST_METHOD(SumMultiplesOf3And5Below_Input10_Returns23)
        {
            auto result = Problem1::SumMultiplesOf3And5Below(10);
            Assert::AreEqual(23, result);
        }

        TEST_METHOD(SumMultiplesOf3And5Below_Input100_Returns2318)
        {
            auto result = Problem1::SumMultiplesOf3And5Below(100);
            Assert::AreEqual(2318, result);
        }

        TEST_METHOD(SumMultiplesOf3And5Below_Input1000_Returns233168)
        {
            auto result = Problem1::SumMultiplesOf3And5Below(1000);
            Assert::AreEqual(233168, result);
        }

        TEST_METHOD(SumMultiplesOf3And5Below_Input10000_Returns23331668)
        {
            auto result = Problem1::SumMultiplesOf3And5Below(10000);
            Assert::AreEqual(23331668, result);
        }

        TEST_METHOD(SumBelow_Input0_Returns0)
        {
            auto result = Problem1::SumBelow(0);
            Assert::AreEqual(0L, result);
        }

        TEST_METHOD(SumBelow_Input1_Returns0)
        {
            auto result = Problem1::SumBelow(1);
            Assert::AreEqual(0L, result);
        }
	};
}<commit_msg>red-commit - SumBelow_Input2_Returns1<commit_after>#include "stdafx.h"
#include "CppUnitTest.h"
#include "..\ProjectEuler\Problem1.h"

using namespace Microsoft::VisualStudio::CppUnitTestFramework;

namespace ProjectEulerTests
{
	TEST_CLASS(Problem1Tests)
	{
	public:

		TEST_METHOD(SumMultiplesOf3And5Below_Input0_Returns0)
		{
            auto result = Problem1::SumMultiplesOf3And5Below(0);
            Assert::AreEqual(0, result);
		}

        TEST_METHOD(SumMultiplesOf3And5Below_Input1_Returns0)
        {
            auto result = Problem1::SumMultiplesOf3And5Below(1);
            Assert::AreEqual(0, result);
        }

        TEST_METHOD(SumMultiplesOf3And5Below_Input2_Returns0)
        {
            auto result = Problem1::SumMultiplesOf3And5Below(2);
            Assert::AreEqual(0, result);
        }

        TEST_METHOD(SumMultiplesOf3And5Below_Input3_Returns0)
        {
            auto result = Problem1::SumMultiplesOf3And5Below(3);
            Assert::AreEqual(0, result);
        }

        TEST_METHOD(SumMultiplesOf3And5Below_Input4_Returns3)
        {
            auto result = Problem1::SumMultiplesOf3And5Below(4);
            Assert::AreEqual(3, result);
        }

        TEST_METHOD(SumMultiplesOf3And5Below_Input5_Returns3)
        {
            auto result = Problem1::SumMultiplesOf3And5Below(5);
            Assert::AreEqual(3, result);
        }

        TEST_METHOD(SumMultiplesOf3And5Below_Input6_Returns8)
        {
            auto result = Problem1::SumMultiplesOf3And5Below(6);
            Assert::AreEqual(8, result);
        }

        TEST_METHOD(SumMultiplesOf3And5Below_Input7_Returns14)
        {
            auto result = Problem1::SumMultiplesOf3And5Below(7);
            Assert::AreEqual(14, result);
        }

        TEST_METHOD(SumMultiplesOf3And5Below_Input8_Returns14)
        {
            auto result = Problem1::SumMultiplesOf3And5Below(8);
            Assert::AreEqual(14, result);
        }

        TEST_METHOD(SumMultiplesOf3And5Below_Input9_Returns14)
        {
            auto result = Problem1::SumMultiplesOf3And5Below(9);
            Assert::AreEqual(14, result);
        }

        TEST_METHOD(SumMultiplesOf3And5Below_Input10_Returns23)
        {
            auto result = Problem1::SumMultiplesOf3And5Below(10);
            Assert::AreEqual(23, result);
        }

        TEST_METHOD(SumMultiplesOf3And5Below_Input100_Returns2318)
        {
            auto result = Problem1::SumMultiplesOf3And5Below(100);
            Assert::AreEqual(2318, result);
        }

        TEST_METHOD(SumMultiplesOf3And5Below_Input1000_Returns233168)
        {
            auto result = Problem1::SumMultiplesOf3And5Below(1000);
            Assert::AreEqual(233168, result);
        }

        TEST_METHOD(SumMultiplesOf3And5Below_Input10000_Returns23331668)
        {
            auto result = Problem1::SumMultiplesOf3And5Below(10000);
            Assert::AreEqual(23331668, result);
        }

        TEST_METHOD(SumBelow_Input0_Returns0)
        {
            auto result = Problem1::SumBelow(0);
            Assert::AreEqual(0L, result);
        }

        TEST_METHOD(SumBelow_Input1_Returns0)
        {
            auto result = Problem1::SumBelow(1);
            Assert::AreEqual(0L, result);
        }

        TEST_METHOD(SumBelow_Input2_Returns1)
        {
            auto result = Problem1::SumBelow(2);
            Assert::AreEqual(1L, result);
        }
	};
}<|endoftext|>


<commit_before><commit_msg>cid#1169841 Big parameter passed by value<commit_after><|endoftext|>


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

#include "chrome/test/ui/ui_test.h"

#include "base/command_line.h"
#include "base/file_util.h"
#include "net/base/net_util.h"

typedef UITest ChromeMainTest;

// Launch the app, then close the app.
TEST_F(ChromeMainTest, AppLaunch) {
  // If we make it here at all, we've succeeded in retrieving the app window
  // in UITest::SetUp()--otherwise we'd fail with an exception in SetUp().

  if (UITest::in_process_renderer()) {
    EXPECT_EQ(1, UITest::GetBrowserProcessCount());
  } else {
#if defined(OS_CHROMEOS)
    // On Linux we'll have five processes: browser, renderer, app launcher,
    // zygote and sandbox helper.
    EXPECT_EQ(5, UITest::GetBrowserProcessCount());
#elif defined(OS_LINUX)
    // On Linux we'll have four processes: browser, renderer, zygote and
    // sandbox helper.
    EXPECT_EQ(4, UITest::GetBrowserProcessCount());
#else
    // We should have two instances of the browser process alive -
    // one is the Browser and the other is the Renderer.
    EXPECT_EQ(2, UITest::GetBrowserProcessCount());
#endif
  }
}

// Make sure that the testing interface is there and giving reasonable answers.
TEST_F(ChromeMainTest, AppTestingInterface) {
  int window_count = 0;
  EXPECT_TRUE(automation()->GetBrowserWindowCount(&window_count));
  EXPECT_EQ(1, window_count);

  EXPECT_EQ(1, GetTabCount());
}

// Make sure that the second invocation creates a new window.
TEST_F(ChromeMainTest, SecondLaunch) {
  include_testing_id_ = false;
  use_existing_browser_ = true;

  ASSERT_TRUE(LaunchAnotherBrowserBlockUntilClosed(
                  CommandLine(CommandLine::ARGUMENTS_ONLY)));

  ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2, action_timeout_ms()));
}

TEST_F(ChromeMainTest, ReuseBrowserInstanceWhenOpeningFile) {
  include_testing_id_ = false;
  use_existing_browser_ = true;

  FilePath test_file = test_data_directory_.AppendASCII("empty.html");

  CommandLine command_line(CommandLine::ARGUMENTS_ONLY);
  command_line.AppendLooseValue(test_file.ToWStringHack());
  ASSERT_TRUE(LaunchAnotherBrowserBlockUntilClosed(command_line));

  ASSERT_TRUE(automation()->IsURLDisplayed(net::FilePathToFileURL(test_file)));
}
<commit_msg>Fixing a comment.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/test/ui/ui_test.h"

#include "base/command_line.h"
#include "base/file_util.h"
#include "net/base/net_util.h"

typedef UITest ChromeMainTest;

// Launch the app, then close the app.
TEST_F(ChromeMainTest, AppLaunch) {
  // If we make it here at all, we've succeeded in retrieving the app window
  // in UITest::SetUp()--otherwise we'd fail with an exception in SetUp().

  if (UITest::in_process_renderer()) {
    EXPECT_EQ(1, UITest::GetBrowserProcessCount());
  } else {
#if defined(OS_CHROMEOS)
    // On Chromeos we'll have five processes: browser, renderer, app launcher,
    // zygote and sandbox helper.
    EXPECT_EQ(5, UITest::GetBrowserProcessCount());
#elif defined(OS_LINUX)
    // On Linux we'll have four processes: browser, renderer, zygote and
    // sandbox helper.
    EXPECT_EQ(4, UITest::GetBrowserProcessCount());
#else
    // We should have two instances of the browser process alive -
    // one is the Browser and the other is the Renderer.
    EXPECT_EQ(2, UITest::GetBrowserProcessCount());
#endif
  }
}

// Make sure that the testing interface is there and giving reasonable answers.
TEST_F(ChromeMainTest, AppTestingInterface) {
  int window_count = 0;
  EXPECT_TRUE(automation()->GetBrowserWindowCount(&window_count));
  EXPECT_EQ(1, window_count);

  EXPECT_EQ(1, GetTabCount());
}

// Make sure that the second invocation creates a new window.
TEST_F(ChromeMainTest, SecondLaunch) {
  include_testing_id_ = false;
  use_existing_browser_ = true;

  ASSERT_TRUE(LaunchAnotherBrowserBlockUntilClosed(
                  CommandLine(CommandLine::ARGUMENTS_ONLY)));

  ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2, action_timeout_ms()));
}

TEST_F(ChromeMainTest, ReuseBrowserInstanceWhenOpeningFile) {
  include_testing_id_ = false;
  use_existing_browser_ = true;

  FilePath test_file = test_data_directory_.AppendASCII("empty.html");

  CommandLine command_line(CommandLine::ARGUMENTS_ONLY);
  command_line.AppendLooseValue(test_file.ToWStringHack());
  ASSERT_TRUE(LaunchAnotherBrowserBlockUntilClosed(command_line));

  ASSERT_TRUE(automation()->IsURLDisplayed(net::FilePathToFileURL(test_file)));
}
<|endoftext|>


<commit_before>#include "lm/trie_sort.hh"

#include "lm/config.hh"
#include "lm/lm_exception.hh"
#include "lm/read_arpa.hh"
#include "lm/vocab.hh"
#include "lm/weights.hh"
#include "lm/word_index.hh"
#include "util/file_piece.hh"
#include "util/mmap.hh"
#include "util/proxy_iterator.hh"
#include "util/sized_iterator.hh"

#include <algorithm>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <deque>
#include <limits>
#include <vector>

namespace lm {
namespace ngram {
namespace trie {

void WriteOrThrow(FILE *to, const void *data, size_t size) {
  assert(size);
  if (1 != std::fwrite(data, size, 1, to)) UTIL_THROW(util::ErrnoException, "Short write; requested size " << size);
}

namespace {

typedef util::SizedIterator NGramIter;

// Proxy for an entry except there is some extra cruft between the entries.  This is used to sort (n-1)-grams using the same memory as the sorted n-grams.
class PartialViewProxy {
  public:
    PartialViewProxy() : attention_size_(0), inner_() {}

    PartialViewProxy(void *ptr, std::size_t block_size, std::size_t attention_size) : attention_size_(attention_size), inner_(ptr, block_size) {}

    operator std::string() const {
      return std::string(reinterpret_cast<const char*>(inner_.Data()), attention_size_);
    }

    PartialViewProxy &operator=(const PartialViewProxy &from) {
      memcpy(inner_.Data(), from.inner_.Data(), attention_size_);
      return *this;
    }

    PartialViewProxy &operator=(const std::string &from) {
      memcpy(inner_.Data(), from.data(), attention_size_);
      return *this;
    }

    const void *Data() const { return inner_.Data(); }
    void *Data() { return inner_.Data(); }

  private:
    friend class util::ProxyIterator<PartialViewProxy>;

    typedef std::string value_type;

    const std::size_t attention_size_;

    typedef util::SizedInnerIterator InnerIterator;
    InnerIterator &Inner() { return inner_; }
    const InnerIterator &Inner() const { return inner_; }
    InnerIterator inner_;
};

typedef util::ProxyIterator<PartialViewProxy> PartialIter;

FILE *DiskFlush(const void *mem_begin, const void *mem_end, const util::TempMaker &maker) {
  util::scoped_fd file(maker.Make());
  util::WriteOrThrow(file.get(), mem_begin, (uint8_t*)mem_end - (uint8_t*)mem_begin);
  return util::FDOpenOrThrow(file);
}

FILE *WriteContextFile(uint8_t *begin, uint8_t *end, const util::TempMaker &maker, std::size_t entry_size, unsigned char order) {
  const size_t context_size = sizeof(WordIndex) * (order - 1);
  // Sort just the contexts using the same memory.
  PartialIter context_begin(PartialViewProxy(begin + sizeof(WordIndex), entry_size, context_size));
  PartialIter context_end(PartialViewProxy(end + sizeof(WordIndex), entry_size, context_size));

#if defined(_WIN32) || defined(_WIN64)
  std::stable_sort
#else
  std::sort
#endif
    (context_begin, context_end, util::SizedCompare<EntryCompare, PartialViewProxy>(EntryCompare(order - 1)));

  util::scoped_FILE out(maker.MakeFile());

  // Write out to file and uniqueify at the same time.  Could have used unique_copy if there was an appropriate OutputIterator.
  if (context_begin == context_end) return out.release();
  PartialIter i(context_begin);
  WriteOrThrow(out.get(), i->Data(), context_size);
  const void *previous = i->Data();
  ++i;
  for (; i != context_end; ++i) {
    if (memcmp(previous, i->Data(), context_size)) {
      WriteOrThrow(out.get(), i->Data(), context_size);
      previous = i->Data();
    }
  }
  return out.release();
}

struct ThrowCombine {
  void operator()(std::size_t /*entry_size*/, const void * /*first*/, const void * /*second*/, FILE * /*out*/) const {
    UTIL_THROW(FormatLoadException, "Duplicate n-gram detected.");
  }
};

// Useful for context files that just contain records with no value.
struct FirstCombine {
  void operator()(std::size_t entry_size, const void *first, const void * /*second*/, FILE *out) const {
    WriteOrThrow(out, first, entry_size);
  }
};

template <class Combine> FILE *MergeSortedFiles(FILE *first_file, FILE *second_file, const util::TempMaker &maker, std::size_t weights_size, unsigned char order, const Combine &combine) {
  std::size_t entry_size = sizeof(WordIndex) * order + weights_size;
  RecordReader first, second;
  first.Init(first_file, entry_size);
  second.Init(second_file, entry_size);
  util::scoped_FILE out_file(maker.MakeFile());
  EntryCompare less(order);
  while (first && second) {
    if (less(first.Data(), second.Data())) {
      WriteOrThrow(out_file.get(), first.Data(), entry_size);
      ++first;
    } else if (less(second.Data(), first.Data())) {
      WriteOrThrow(out_file.get(), second.Data(), entry_size);
      ++second;
    } else {
      combine(entry_size, first.Data(), second.Data(), out_file.get());
      ++first; ++second;
    }
  }
  for (RecordReader &remains = (first ? first : second); remains; ++remains) {
    WriteOrThrow(out_file.get(), remains.Data(), entry_size);
  }
  return out_file.release();
}

} // namespace

void RecordReader::Init(FILE *file, std::size_t entry_size) {
  rewind(file);
  file_ = file;
  data_.reset(malloc(entry_size));
  UTIL_THROW_IF(!data_.get(), util::ErrnoException, "Failed to malloc read buffer");
  remains_ = true;
  entry_size_ = entry_size;
  ++*this;
}

void RecordReader::Overwrite(const void *start, std::size_t amount) {
  long internal = (uint8_t*)start - (uint8_t*)data_.get();
  UTIL_THROW_IF(fseek(file_, internal - entry_size_, SEEK_CUR), util::ErrnoException, "Couldn't seek backwards for revision");
  WriteOrThrow(file_, start, amount);
  long forward = entry_size_ - internal - amount;
#if !defined(_WIN32) && !defined(_WIN64)
  if (forward)
#endif
    UTIL_THROW_IF(fseek(file_, forward, SEEK_CUR), util::ErrnoException, "Couldn't seek forwards past revision");
}

void RecordReader::Rewind() {
  rewind(file_);
  remains_ = true;
  ++*this;
}

SortedFiles::SortedFiles(const Config &config, util::FilePiece &f, std::vector<uint64_t> &counts, size_t buffer, const std::string &file_prefix, SortedVocabulary &vocab) {
  util::TempMaker maker(file_prefix);
  PositiveProbWarn warn(config.positive_log_probability);
  unigram_.reset(maker.Make());
  {
    // In case <unk> appears.
    size_t size_out = (counts[0] + 1) * sizeof(ProbBackoff);
    util::scoped_mmap unigram_mmap(util::MapZeroedWrite(unigram_.get(), size_out), size_out);
    Read1Grams(f, counts[0], vocab, reinterpret_cast<ProbBackoff*>(unigram_mmap.get()), warn);
    CheckSpecials(config, vocab);
    if (!vocab.SawUnk()) ++counts[0];
  }

  // Only use as much buffer as we need.
  size_t buffer_use = 0;
  for (unsigned int order = 2; order < counts.size(); ++order) {
    buffer_use = std::max<size_t>(buffer_use, static_cast<size_t>((sizeof(WordIndex) * order + 2 * sizeof(float)) * counts[order - 1]));
  }
  buffer_use = std::max<size_t>(buffer_use, static_cast<size_t>((sizeof(WordIndex) * counts.size() + sizeof(float)) * counts.back()));
  buffer = std::min<size_t>(buffer, buffer_use);

  util::scoped_malloc mem;
  mem.reset(malloc(buffer));
  if (!mem.get()) UTIL_THROW(util::ErrnoException, "malloc failed for sort buffer size " << buffer);

  for (unsigned char order = 2; order <= counts.size(); ++order) {
    ConvertToSorted(f, vocab, counts, maker, order, warn, mem.get(), buffer);
  }
  ReadEnd(f);
}

namespace {
class Closer {
  public:
    explicit Closer(std::deque<FILE*> &files) : files_(files) {}

    ~Closer() {
      for (std::deque<FILE*>::iterator i = files_.begin(); i != files_.end(); ++i) {
        util::scoped_FILE deleter(*i);
      }
    }

    void PopFront() {
      util::scoped_FILE deleter(files_.front());
      files_.pop_front();
    }
  private:
    std::deque<FILE*> &files_;
};
} // namespace

void SortedFiles::ConvertToSorted(util::FilePiece &f, const SortedVocabulary &vocab, const std::vector<uint64_t> &counts, const util::TempMaker &maker, unsigned char order, PositiveProbWarn &warn, void *mem, std::size_t mem_size) {
  ReadNGramHeader(f, order);
  const size_t count = counts[order - 1];
  // Size of weights.  Does it include backoff?
  const size_t words_size = sizeof(WordIndex) * order;
  const size_t weights_size = sizeof(float) + ((order == counts.size()) ? 0 : sizeof(float));
  const size_t entry_size = words_size + weights_size;
  const size_t batch_size = std::min(count, mem_size / entry_size);
  uint8_t *const begin = reinterpret_cast<uint8_t*>(mem);

  std::deque<FILE*> files, contexts;
  Closer files_closer(files), contexts_closer(contexts);

  for (std::size_t batch = 0, done = 0; done < count; ++batch) {
    uint8_t *out = begin;
    uint8_t *out_end = out + std::min(count - done, batch_size) * entry_size;
    if (order == counts.size()) {
      for (; out != out_end; out += entry_size) {
        ReadNGram(f, order, vocab, reinterpret_cast<WordIndex*>(out), *reinterpret_cast<Prob*>(out + words_size), warn);
      }
    } else {
      for (; out != out_end; out += entry_size) {
        ReadNGram(f, order, vocab, reinterpret_cast<WordIndex*>(out), *reinterpret_cast<ProbBackoff*>(out + words_size), warn);
      }
    }
    // Sort full records by full n-gram.
    util::SizedProxy proxy_begin(begin, entry_size), proxy_end(out_end, entry_size);
    // parallel_sort uses too much RAM.  TODO: figure out why windows sort doesn't like my proxies.
#if defined(_WIN32) || defined(_WIN64)
    std::stable_sort
#else
    std::sort
#endif
        (NGramIter(proxy_begin), NGramIter(proxy_end), util::SizedCompare<EntryCompare>(EntryCompare(order)));
    files.push_back(DiskFlush(begin, out_end, maker));
    contexts.push_back(WriteContextFile(begin, out_end, maker, entry_size, order));

    done += (out_end - begin) / entry_size;
  }

  // All individual files created.  Merge them.

  while (files.size() > 1) {
    files.push_back(MergeSortedFiles(files[0], files[1], maker, weights_size, order, ThrowCombine()));
    files_closer.PopFront();
    files_closer.PopFront();
    contexts.push_back(MergeSortedFiles(contexts[0], contexts[1], maker, 0, order - 1, FirstCombine()));
    contexts_closer.PopFront();
    contexts_closer.PopFront();
  }

  if (!files.empty()) {
    // Steal from closers.
    full_[order - 2].reset(files.front());
    files.pop_front();
    context_[order - 2].reset(contexts.front());
    contexts.pop_front();
  }
}

} // namespace trie
} // namespace ngram
} // namespace lm
<commit_msg>Don't segfault trie building when there is no n-gram of a given order.  Jon Clark.<commit_after>#include "lm/trie_sort.hh"

#include "lm/config.hh"
#include "lm/lm_exception.hh"
#include "lm/read_arpa.hh"
#include "lm/vocab.hh"
#include "lm/weights.hh"
#include "lm/word_index.hh"
#include "util/file_piece.hh"
#include "util/mmap.hh"
#include "util/proxy_iterator.hh"
#include "util/sized_iterator.hh"

#include <algorithm>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <deque>
#include <limits>
#include <vector>

namespace lm {
namespace ngram {
namespace trie {

void WriteOrThrow(FILE *to, const void *data, size_t size) {
  assert(size);
  if (1 != std::fwrite(data, size, 1, to)) UTIL_THROW(util::ErrnoException, "Short write; requested size " << size);
}

namespace {

typedef util::SizedIterator NGramIter;

// Proxy for an entry except there is some extra cruft between the entries.  This is used to sort (n-1)-grams using the same memory as the sorted n-grams.
class PartialViewProxy {
  public:
    PartialViewProxy() : attention_size_(0), inner_() {}

    PartialViewProxy(void *ptr, std::size_t block_size, std::size_t attention_size) : attention_size_(attention_size), inner_(ptr, block_size) {}

    operator std::string() const {
      return std::string(reinterpret_cast<const char*>(inner_.Data()), attention_size_);
    }

    PartialViewProxy &operator=(const PartialViewProxy &from) {
      memcpy(inner_.Data(), from.inner_.Data(), attention_size_);
      return *this;
    }

    PartialViewProxy &operator=(const std::string &from) {
      memcpy(inner_.Data(), from.data(), attention_size_);
      return *this;
    }

    const void *Data() const { return inner_.Data(); }
    void *Data() { return inner_.Data(); }

  private:
    friend class util::ProxyIterator<PartialViewProxy>;

    typedef std::string value_type;

    const std::size_t attention_size_;

    typedef util::SizedInnerIterator InnerIterator;
    InnerIterator &Inner() { return inner_; }
    const InnerIterator &Inner() const { return inner_; }
    InnerIterator inner_;
};

typedef util::ProxyIterator<PartialViewProxy> PartialIter;

FILE *DiskFlush(const void *mem_begin, const void *mem_end, const util::TempMaker &maker) {
  util::scoped_fd file(maker.Make());
  util::WriteOrThrow(file.get(), mem_begin, (uint8_t*)mem_end - (uint8_t*)mem_begin);
  return util::FDOpenOrThrow(file);
}

FILE *WriteContextFile(uint8_t *begin, uint8_t *end, const util::TempMaker &maker, std::size_t entry_size, unsigned char order) {
  const size_t context_size = sizeof(WordIndex) * (order - 1);
  // Sort just the contexts using the same memory.
  PartialIter context_begin(PartialViewProxy(begin + sizeof(WordIndex), entry_size, context_size));
  PartialIter context_end(PartialViewProxy(end + sizeof(WordIndex), entry_size, context_size));

#if defined(_WIN32) || defined(_WIN64)
  std::stable_sort
#else
  std::sort
#endif
    (context_begin, context_end, util::SizedCompare<EntryCompare, PartialViewProxy>(EntryCompare(order - 1)));

  util::scoped_FILE out(maker.MakeFile());

  // Write out to file and uniqueify at the same time.  Could have used unique_copy if there was an appropriate OutputIterator.
  if (context_begin == context_end) return out.release();
  PartialIter i(context_begin);
  WriteOrThrow(out.get(), i->Data(), context_size);
  const void *previous = i->Data();
  ++i;
  for (; i != context_end; ++i) {
    if (memcmp(previous, i->Data(), context_size)) {
      WriteOrThrow(out.get(), i->Data(), context_size);
      previous = i->Data();
    }
  }
  return out.release();
}

struct ThrowCombine {
  void operator()(std::size_t /*entry_size*/, const void * /*first*/, const void * /*second*/, FILE * /*out*/) const {
    UTIL_THROW(FormatLoadException, "Duplicate n-gram detected.");
  }
};

// Useful for context files that just contain records with no value.
struct FirstCombine {
  void operator()(std::size_t entry_size, const void *first, const void * /*second*/, FILE *out) const {
    WriteOrThrow(out, first, entry_size);
  }
};

template <class Combine> FILE *MergeSortedFiles(FILE *first_file, FILE *second_file, const util::TempMaker &maker, std::size_t weights_size, unsigned char order, const Combine &combine) {
  std::size_t entry_size = sizeof(WordIndex) * order + weights_size;
  RecordReader first, second;
  first.Init(first_file, entry_size);
  second.Init(second_file, entry_size);
  util::scoped_FILE out_file(maker.MakeFile());
  EntryCompare less(order);
  while (first && second) {
    if (less(first.Data(), second.Data())) {
      WriteOrThrow(out_file.get(), first.Data(), entry_size);
      ++first;
    } else if (less(second.Data(), first.Data())) {
      WriteOrThrow(out_file.get(), second.Data(), entry_size);
      ++second;
    } else {
      combine(entry_size, first.Data(), second.Data(), out_file.get());
      ++first; ++second;
    }
  }
  for (RecordReader &remains = (first ? first : second); remains; ++remains) {
    WriteOrThrow(out_file.get(), remains.Data(), entry_size);
  }
  return out_file.release();
}

} // namespace

void RecordReader::Init(FILE *file, std::size_t entry_size) {
  entry_size_ = entry_size;
  data_.reset(malloc(entry_size));
  UTIL_THROW_IF(!data_.get(), util::ErrnoException, "Failed to malloc read buffer");
  file_ = file;
  if (file) {
    rewind(file);
    remains_ = true;
    ++*this;
  } else {
    remains_ = false;
  }
}

void RecordReader::Overwrite(const void *start, std::size_t amount) {
  long internal = (uint8_t*)start - (uint8_t*)data_.get();
  UTIL_THROW_IF(fseek(file_, internal - entry_size_, SEEK_CUR), util::ErrnoException, "Couldn't seek backwards for revision");
  WriteOrThrow(file_, start, amount);
  long forward = entry_size_ - internal - amount;
#if !defined(_WIN32) && !defined(_WIN64)
  if (forward)
#endif
    UTIL_THROW_IF(fseek(file_, forward, SEEK_CUR), util::ErrnoException, "Couldn't seek forwards past revision");
}

void RecordReader::Rewind() {
  if (file_) {
    rewind(file_);
    remains_ = true;
    ++*this;
  } else {
    remains_ = false;
  }
}

SortedFiles::SortedFiles(const Config &config, util::FilePiece &f, std::vector<uint64_t> &counts, size_t buffer, const std::string &file_prefix, SortedVocabulary &vocab) {
  util::TempMaker maker(file_prefix);
  PositiveProbWarn warn(config.positive_log_probability);
  unigram_.reset(maker.Make());
  {
    // In case <unk> appears.
    size_t size_out = (counts[0] + 1) * sizeof(ProbBackoff);
    util::scoped_mmap unigram_mmap(util::MapZeroedWrite(unigram_.get(), size_out), size_out);
    Read1Grams(f, counts[0], vocab, reinterpret_cast<ProbBackoff*>(unigram_mmap.get()), warn);
    CheckSpecials(config, vocab);
    if (!vocab.SawUnk()) ++counts[0];
  }

  // Only use as much buffer as we need.
  size_t buffer_use = 0;
  for (unsigned int order = 2; order < counts.size(); ++order) {
    buffer_use = std::max<size_t>(buffer_use, static_cast<size_t>((sizeof(WordIndex) * order + 2 * sizeof(float)) * counts[order - 1]));
  }
  buffer_use = std::max<size_t>(buffer_use, static_cast<size_t>((sizeof(WordIndex) * counts.size() + sizeof(float)) * counts.back()));
  buffer = std::min<size_t>(buffer, buffer_use);

  util::scoped_malloc mem;
  mem.reset(malloc(buffer));
  if (!mem.get()) UTIL_THROW(util::ErrnoException, "malloc failed for sort buffer size " << buffer);

  for (unsigned char order = 2; order <= counts.size(); ++order) {
    ConvertToSorted(f, vocab, counts, maker, order, warn, mem.get(), buffer);
  }
  ReadEnd(f);
}

namespace {
class Closer {
  public:
    explicit Closer(std::deque<FILE*> &files) : files_(files) {}

    ~Closer() {
      for (std::deque<FILE*>::iterator i = files_.begin(); i != files_.end(); ++i) {
        util::scoped_FILE deleter(*i);
      }
    }

    void PopFront() {
      util::scoped_FILE deleter(files_.front());
      files_.pop_front();
    }
  private:
    std::deque<FILE*> &files_;
};
} // namespace

void SortedFiles::ConvertToSorted(util::FilePiece &f, const SortedVocabulary &vocab, const std::vector<uint64_t> &counts, const util::TempMaker &maker, unsigned char order, PositiveProbWarn &warn, void *mem, std::size_t mem_size) {
  ReadNGramHeader(f, order);
  const size_t count = counts[order - 1];
  // Size of weights.  Does it include backoff?
  const size_t words_size = sizeof(WordIndex) * order;
  const size_t weights_size = sizeof(float) + ((order == counts.size()) ? 0 : sizeof(float));
  const size_t entry_size = words_size + weights_size;
  const size_t batch_size = std::min(count, mem_size / entry_size);
  uint8_t *const begin = reinterpret_cast<uint8_t*>(mem);

  std::deque<FILE*> files, contexts;
  Closer files_closer(files), contexts_closer(contexts);

  for (std::size_t batch = 0, done = 0; done < count; ++batch) {
    uint8_t *out = begin;
    uint8_t *out_end = out + std::min(count - done, batch_size) * entry_size;
    if (order == counts.size()) {
      for (; out != out_end; out += entry_size) {
        ReadNGram(f, order, vocab, reinterpret_cast<WordIndex*>(out), *reinterpret_cast<Prob*>(out + words_size), warn);
      }
    } else {
      for (; out != out_end; out += entry_size) {
        ReadNGram(f, order, vocab, reinterpret_cast<WordIndex*>(out), *reinterpret_cast<ProbBackoff*>(out + words_size), warn);
      }
    }
    // Sort full records by full n-gram.
    util::SizedProxy proxy_begin(begin, entry_size), proxy_end(out_end, entry_size);
    // parallel_sort uses too much RAM.  TODO: figure out why windows sort doesn't like my proxies.
#if defined(_WIN32) || defined(_WIN64)
    std::stable_sort
#else
    std::sort
#endif
        (NGramIter(proxy_begin), NGramIter(proxy_end), util::SizedCompare<EntryCompare>(EntryCompare(order)));
    files.push_back(DiskFlush(begin, out_end, maker));
    contexts.push_back(WriteContextFile(begin, out_end, maker, entry_size, order));

    done += (out_end - begin) / entry_size;
  }

  // All individual files created.  Merge them.

  while (files.size() > 1) {
    files.push_back(MergeSortedFiles(files[0], files[1], maker, weights_size, order, ThrowCombine()));
    files_closer.PopFront();
    files_closer.PopFront();
    contexts.push_back(MergeSortedFiles(contexts[0], contexts[1], maker, 0, order - 1, FirstCombine()));
    contexts_closer.PopFront();
    contexts_closer.PopFront();
  }

  if (!files.empty()) {
    // Steal from closers.
    full_[order - 2].reset(files.front());
    files.pop_front();
    context_[order - 2].reset(contexts.front());
    contexts.pop_front();
  }
}

} // namespace trie
} // namespace ngram
} // namespace lm
<|endoftext|>


<commit_before><commit_msg>Reenable PosixSessionEnd test.<commit_after><|endoftext|>


<commit_before>/*

@Copyright Barrett Adair 2015-2017
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)

*/

#ifndef BOOST_CLBL_TRTS_ADD_MEMBER_CONST_HPP
#define BOOST_CLBL_TRTS_ADD_MEMBER_CONST_HPP

#include <boost/callable_traits/detail/core.hpp>

namespace boost { namespace callable_traits {

//[ add_member_const_hpp
/*`
[section:ref_add_member_const add_member_const]
[heading Header]
``#include <boost/callable_traits/add_member_const.hpp>``
[heading Definition]
*/

template<typename T>
using add_member_const_t = //see below
//<-
#ifdef BOOST_CLBL_TRTS_DISABLE_ABOMINABLE_FUNCTIONS

    detail::sfinae_try<
        typename detail::traits<T>::add_member_const,

        detail::fail_when_same<typename detail::traits<T>::add_member_const,
            detail::abominable_functions_not_supported_on_this_compiler,
            this_compiler_doesnt_support_abominable_function_types>,

        detail::fail_if_invalid<typename detail::traits<T>::add_member_const,
            member_qualifiers_are_illegal_for_this_type>>;
#else

    detail::try_but_fail_if_invalid<
        typename detail::traits<T>::add_member_const,
        member_qualifiers_are_illegal_for_this_type>;

#endif // #ifdef BOOST_CLBL_TRTS_DISABLE_ABOMINABLE_FUNCTIONS

namespace detail {

    template<typename T, typename = std::false_type>
    struct add_member_const_impl {};

    template<typename T>
    struct add_member_const_impl <T, typename std::is_same<
        add_member_const_t<T>, detail::dummy>::type>
    {
        using type = add_member_const_t<T>;
    };
}

//->

template<typename T>
struct add_member_const : detail::add_member_const_impl<T> {};

//<-
}} // namespace boost::callable_traits
//->

/*`
[heading Constraints]
* `T` must be a function type or a member function pointer type
* If `T` is a pointer, it may not be cv/ref qualified

[heading Behavior]
* A substitution failure occurs if the constraints are violated.
* Adds a member `const` qualifier to `T`, if not already present.

[heading Input/Output Examples]
[table
    [[`T`]                              [`add_member_const_t<T>`]]
    [[`int()`]                          [`int() const`]]
    [[`int(foo::*)()`]                  [`int(foo::*)() const`]]
    [[`int(foo::*)() &`]                [`int(foo::*)() const &`]]
    [[`int(foo::*)() &&`]               [`int(foo::*)() const &&`]]
    [[`int(foo::*)() const`]            [`int(foo::*)() const`]]
    [[`int(foo::*)() volatile`]         [`int(foo::*)() const volatile`]]
    [[`int(foo::*)() transaction_safe`] [`int(foo::*)() const transaction_safe`]]
    [[`int`]                            [(substitution failure)]]
    [[`int (&)()`]                      [(substitution failure)]]
    [[`int (*)()`]                      [(substitution failure)]]
    [[`int foo::*`]                     [(substitution failure)]]
    [[`int (foo::* const)()`]           [(substitution failure)]]
]

[heading Example Program]
[import ../example/add_member_const.cpp]
[add_member_const]
[endsect]
*/
//]

#endif // #ifndef BOOST_CLBL_TRTS_ADD_MEMBER_CONST_HPP

<commit_msg>Delete add_member_const.hpp<commit_after><|endoftext|>


<commit_before><commit_msg>start centre: Solid color fits the new artwork better.<commit_after><|endoftext|>