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

// stl
#include <algorithm>
#include <stdexcept>
// boost
#include <boost/thread/mutex.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/algorithm/string.hpp>
// mapnik
#include <mapnik/datasource_cache.hpp>
// ltdl
#include <ltdl.h>

namespace mapnik
{
   using namespace std;
   using namespace boost;

   bool is_input_plugin (std::string const& filename)
   {
      return boost::algorithm::ends_with(filename,".input");
   }

   datasource_cache::datasource_cache()
   {
      if (lt_dlinit()) throw;
   }

   datasource_cache::~datasource_cache()
   {
      lt_dlexit();
   }

   std::map<string,boost::shared_ptr<PluginInfo> > datasource_cache::plugins_;
   bool datasource_cache::registered_=false;

   datasource_ptr datasource_cache::create(const parameters& params)
   {
      datasource_ptr ds;
      try
      {
         boost::optional<std::string> type = params.get<std::string>("type");
         if (type)
         {
            map<string,boost::shared_ptr<PluginInfo> >::iterator itr=plugins_.find(*type);
            if (itr!=plugins_.end())
            {
               if (itr->second->handle())
               {
                  create_ds* create_datasource =
                     (create_ds*) lt_dlsym(itr->second->handle(), "create");
                  if (!create_datasource)
                  {
                     std::clog << "Cannot load symbols: " << lt_dlerror() << std::endl;
                  }
                  else
                  {
                     ds=datasource_ptr(create_datasource(params), datasource_deleter());
                  }
               }
               else
               {
                  std::clog << "Cannot load library: " << lt_dlerror() << std::endl;
               }
            }
         }
#ifdef MAPNIK_DEBUG
         std::clog<<"datasource="<<ds<<" type="<<type<<std::endl;
#endif
      }
      catch (datasource_exception& ex)
      {
         std::clog << ex.what() << "\n";
      }
      catch (...)
      {
         std::clog << " exception caught\n";
      }
      return ds;
   }

   bool datasource_cache::insert(const std::string& type,const lt_dlhandle module)
   {
      return plugins_.insert(make_pair(type,boost::shared_ptr<PluginInfo>
                                       (new PluginInfo(type,module)))).second;
   }

   void datasource_cache::register_datasources(const std::string& str)
   {
      mutex::scoped_lock lock(mapnik::singleton<mapnik::datasource_cache,
                              mapnik::CreateStatic>::mutex_);
      filesystem::path path(str);
      filesystem::directory_iterator end_itr;
      if (exists(path) && is_directory(path))
      {
         for (filesystem::directory_iterator itr(path);itr!=end_itr;++itr )
         {
            if (!is_directory( *itr ) && is_input_plugin(itr->leaf()))
            {
               try
               {
                  lt_dlhandle module=lt_dlopen(itr->string().c_str());
                  if (module)
                  {
                     datasource_name* ds_name =
                        (datasource_name*) lt_dlsym(module, "datasource_name");
                     if (ds_name && insert(ds_name(),module))
                     {
#ifdef MAPNIK_DEBUG
                        std::clog<<"registered datasource : "<<ds_name()<<std::endl;
#endif
                        registered_=true;
                     }
                  }
                  else
                  {
                     std::clog << lt_dlerror() << "\n";
                  }
               }
               catch (...) {}
            }
         }
      }
   }
}
<commit_msg>fixed is_datasource_plugin predicate   <commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2006 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/
//$Id: datasource_cache.cpp 23 2005-03-22 22:16:34Z pavlenko $

// stl
#include <algorithm>
#include <stdexcept>
// boost
#include <boost/thread/mutex.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/algorithm/string.hpp>
// mapnik
#include <mapnik/datasource_cache.hpp>
// ltdl
#include <ltdl.h>

namespace mapnik
{
   using namespace std;
   using namespace boost;

   bool is_input_plugin (std::string const& filename)
   {
      return boost::algorithm::ends_with(filename,std::string(".input"));
   }

   datasource_cache::datasource_cache()
   {
      if (lt_dlinit()) throw;
   }

   datasource_cache::~datasource_cache()
   {
      lt_dlexit();
   }

   std::map<string,boost::shared_ptr<PluginInfo> > datasource_cache::plugins_;
   bool datasource_cache::registered_=false;

   datasource_ptr datasource_cache::create(const parameters& params)
   {
      datasource_ptr ds;
      try
      {
         boost::optional<std::string> type = params.get<std::string>("type");
         if (type)
         {
            map<string,boost::shared_ptr<PluginInfo> >::iterator itr=plugins_.find(*type);
            if (itr!=plugins_.end())
            {
               if (itr->second->handle())
               {
                  create_ds* create_datasource =
                     (create_ds*) lt_dlsym(itr->second->handle(), "create");
                  if (!create_datasource)
                  {
                     std::clog << "Cannot load symbols: " << lt_dlerror() << std::endl;
                  }
                  else
                  {
                     ds=datasource_ptr(create_datasource(params), datasource_deleter());
                  }
               }
               else
               {
                  std::clog << "Cannot load library: " << lt_dlerror() << std::endl;
               }
            }
         }
#ifdef MAPNIK_DEBUG
         std::clog<<"datasource="<<ds<<" type="<<type<<std::endl;
#endif
      }
      catch (datasource_exception& ex)
      {
         std::clog << ex.what() << "\n";
      }
      catch (...)
      {
         std::clog << " exception caught\n";
      }
      return ds;
   }

   bool datasource_cache::insert(const std::string& type,const lt_dlhandle module)
   {
      return plugins_.insert(make_pair(type,boost::shared_ptr<PluginInfo>
                                       (new PluginInfo(type,module)))).second;
   }

   void datasource_cache::register_datasources(const std::string& str)
   {
      mutex::scoped_lock lock(mapnik::singleton<mapnik::datasource_cache,
                              mapnik::CreateStatic>::mutex_);
      filesystem::path path(str);
      filesystem::directory_iterator end_itr;
      if (exists(path) && is_directory(path))
      {
         for (filesystem::directory_iterator itr(path);itr!=end_itr;++itr )
         {
            if (!is_directory( *itr )  && is_input_plugin(itr->leaf()))
            {
               try
               {
                  lt_dlhandle module=lt_dlopen(itr->string().c_str());
                  if (module)
                  {
                     datasource_name* ds_name =
                        (datasource_name*) lt_dlsym(module, "datasource_name");
                     if (ds_name && insert(ds_name(),module))
                     {
#ifdef MAPNIK_DEBUG
                        std::clog<<"registered datasource : "<<ds_name()<<std::endl;
#endif
                        registered_=true;
                     }
                  }
                  else
                  {
                     std::clog << lt_dlerror() << "\n";
                  }
               }
               catch (...) {}
            }
         }
      }
   }
}
<|endoftext|>


<commit_before><commit_msg>coverity#736157 Dereference null return value<commit_after><|endoftext|>


<commit_before>/*
 * Copyright 2011 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "gm.h"
#include "SkCanvas.h"
#include "SkColorPriv.h"
#include "SkShader.h"

#include "SkArithmeticMode.h"
#include "SkGradientShader.h"
#define WW  100
#define HH  32

static SkBitmap make_bm() {
    SkBitmap bm;
    bm.setConfig(SkBitmap::kARGB_8888_Config, WW, HH);
    bm.allocPixels();
    bm.eraseColor(0);
    return bm;
}

static SkBitmap make_src() {
    SkBitmap bm = make_bm();
    SkCanvas canvas(bm);
    SkPaint paint;
    SkPoint pts[] = { 0, 0, SkIntToScalar(WW), SkIntToScalar(HH) };
    SkColor colors[] = {
        SK_ColorBLACK, SK_ColorGREEN, SK_ColorCYAN,
        SK_ColorRED, SK_ColorMAGENTA, SK_ColorWHITE
    };
    SkShader* s = SkGradientShader::CreateLinear(pts, colors, NULL, SK_ARRAY_COUNT(colors),
                                                 SkShader::kClamp_TileMode);
    paint.setShader(s)->unref();
    canvas.drawPaint(paint);
    return bm;
}

static SkBitmap make_dst() {
    SkBitmap bm = make_bm();
    SkCanvas canvas(bm);
    SkPaint paint;
    SkPoint pts[] = { 0, SkIntToScalar(HH), SkIntToScalar(WW), 0 };
    SkColor colors[] = {
        SK_ColorBLUE, SK_ColorYELLOW, SK_ColorBLACK, SK_ColorGREEN, SK_ColorGRAY
    };
    SkShader* s = SkGradientShader::CreateLinear(pts, colors, NULL, SK_ARRAY_COUNT(colors),
                                                 SkShader::kClamp_TileMode);
    paint.setShader(s)->unref();
    canvas.drawPaint(paint);
    return bm;
}

static SkBitmap make_arith(const SkBitmap& src, const SkBitmap& dst,
                           const SkScalar k[]) {
    SkBitmap bm = make_bm();
    SkCanvas canvas(bm);
    SkPaint paint;
    canvas.drawBitmap(dst, 0, 0, NULL);
    SkXfermode* xfer = SkArithmeticMode::Create(k[0], k[1], k[2], k[3]);
    paint.setXfermode(xfer)->unref();
    canvas.drawBitmap(src, 0, 0, &paint);
    return bm;
}

static void show_k_text(SkCanvas* canvas, SkScalar x, SkScalar y, const SkScalar k[]) {
    SkPaint paint;
    paint.setTextSize(SkIntToScalar(24));
    paint.setAntiAlias(true);
    for (int i = 0; i < 4; ++i) {
        SkString str;
        str.appendScalar(k[i]);
        SkScalar width = paint.measureText(str.c_str(), str.size());
        canvas->drawText(str.c_str(), str.size(), x, y + paint.getTextSize(), paint);
        x += width + SkIntToScalar(10);
    }
}

class ArithmodeGM : public skiagm::GM {
public:
    ArithmodeGM () {}

protected:

    virtual SkString onShortName() {
        return SkString("arithmode");
    }

    virtual SkISize onISize() { return SkISize::Make(640, 480); }

    virtual void onDraw(SkCanvas* canvas) {
        SkBitmap src = make_src();
        SkBitmap dst = make_dst();

        const SkScalar one = SK_Scalar1;
        static const SkScalar K[] = {
            0, 0, 0, 0,
            0, 0, 0, one,
            0, one, 0, 0,
            0, 0, one, 0,
            0, one, one, 0,
            0, one, -one, 0,
            0, one/2, one/2, 0,
            0, one/2, one/2, one/4,
            0, one/2, one/2, -one/4,
            one/4, one/2, one/2, 0,
            -one/4, one/2, one/2, 0,
        };

        const SkScalar* k = K;
        const SkScalar* stop = k + SK_ARRAY_COUNT(K);
        SkScalar y = 0;
        SkScalar x = 0;
        SkScalar gap = src.width() + SkIntToScalar(20);
        while (k < stop) {
            SkScalar x = 0;
            SkBitmap res = make_arith(src, dst, k);
            canvas->drawBitmap(src, x, y, NULL);
            x += gap;
            canvas->drawBitmap(dst, x, y, NULL);
            x += gap;
            canvas->drawBitmap(res, x, y, NULL);
            x += gap;
            show_k_text(canvas, x, y, k);
            k += 4;
            y += src.height() + SkIntToScalar(12);
        }
    }

private:
    typedef GM INHERITED;
};

///////////////////////////////////////////////////////////////////////////////

static skiagm::GM* MyFactory(void*) { return new ArithmodeGM; }
static skiagm::GMRegistry reg(MyFactory);
<commit_msg>fix positioning for scalar=fixed, still need to fix actual mode<commit_after>/*
 * Copyright 2011 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "gm.h"
#include "SkCanvas.h"
#include "SkColorPriv.h"
#include "SkShader.h"

#include "SkArithmeticMode.h"
#include "SkGradientShader.h"
#define WW  100
#define HH  32

static SkBitmap make_bm() {
    SkBitmap bm;
    bm.setConfig(SkBitmap::kARGB_8888_Config, WW, HH);
    bm.allocPixels();
    bm.eraseColor(0);
    return bm;
}

static SkBitmap make_src() {
    SkBitmap bm = make_bm();
    SkCanvas canvas(bm);
    SkPaint paint;
    SkPoint pts[] = { 0, 0, SkIntToScalar(WW), SkIntToScalar(HH) };
    SkColor colors[] = {
        SK_ColorBLACK, SK_ColorGREEN, SK_ColorCYAN,
        SK_ColorRED, SK_ColorMAGENTA, SK_ColorWHITE
    };
    SkShader* s = SkGradientShader::CreateLinear(pts, colors, NULL, SK_ARRAY_COUNT(colors),
                                                 SkShader::kClamp_TileMode);
    paint.setShader(s)->unref();
    canvas.drawPaint(paint);
    return bm;
}

static SkBitmap make_dst() {
    SkBitmap bm = make_bm();
    SkCanvas canvas(bm);
    SkPaint paint;
    SkPoint pts[] = { 0, SkIntToScalar(HH), SkIntToScalar(WW), 0 };
    SkColor colors[] = {
        SK_ColorBLUE, SK_ColorYELLOW, SK_ColorBLACK, SK_ColorGREEN, SK_ColorGRAY
    };
    SkShader* s = SkGradientShader::CreateLinear(pts, colors, NULL, SK_ARRAY_COUNT(colors),
                                                 SkShader::kClamp_TileMode);
    paint.setShader(s)->unref();
    canvas.drawPaint(paint);
    return bm;
}

static SkBitmap make_arith(const SkBitmap& src, const SkBitmap& dst,
                           const SkScalar k[]) {
    SkBitmap bm = make_bm();
    SkCanvas canvas(bm);
    SkPaint paint;
    canvas.drawBitmap(dst, 0, 0, NULL);
    SkXfermode* xfer = SkArithmeticMode::Create(k[0], k[1], k[2], k[3]);
    paint.setXfermode(xfer)->unref();
    canvas.drawBitmap(src, 0, 0, &paint);
    return bm;
}

static void show_k_text(SkCanvas* canvas, SkScalar x, SkScalar y, const SkScalar k[]) {
    SkPaint paint;
    paint.setTextSize(SkIntToScalar(24));
    paint.setAntiAlias(true);
    for (int i = 0; i < 4; ++i) {
        SkString str;
        str.appendScalar(k[i]);
        SkScalar width = paint.measureText(str.c_str(), str.size());
        canvas->drawText(str.c_str(), str.size(), x, y + paint.getTextSize(), paint);
        x += width + SkIntToScalar(10);
    }
}

class ArithmodeGM : public skiagm::GM {
public:
    ArithmodeGM () {}

protected:

    virtual SkString onShortName() {
        return SkString("arithmode");
    }

    virtual SkISize onISize() { return SkISize::Make(640, 480); }

    virtual void onDraw(SkCanvas* canvas) {
        SkBitmap src = make_src();
        SkBitmap dst = make_dst();

        const SkScalar one = SK_Scalar1;
        static const SkScalar K[] = {
            0, 0, 0, 0,
            0, 0, 0, one,
            0, one, 0, 0,
            0, 0, one, 0,
            0, one, one, 0,
            0, one, -one, 0,
            0, one/2, one/2, 0,
            0, one/2, one/2, one/4,
            0, one/2, one/2, -one/4,
            one/4, one/2, one/2, 0,
            -one/4, one/2, one/2, 0,
        };

        const SkScalar* k = K;
        const SkScalar* stop = k + SK_ARRAY_COUNT(K);
        SkScalar y = 0;
        SkScalar x = 0;
        SkScalar gap = SkIntToScalar(src.width() + 20);
        while (k < stop) {
            SkScalar x = 0;
            SkBitmap res = make_arith(src, dst, k);
            canvas->drawBitmap(src, x, y, NULL);
            x += gap;
            canvas->drawBitmap(dst, x, y, NULL);
            x += gap;
            canvas->drawBitmap(res, x, y, NULL);
            x += gap;
            show_k_text(canvas, x, y, k);
            k += 4;
            y += SkIntToScalar(src.height() + 12);
        }
    }

private:
    typedef GM INHERITED;
};

///////////////////////////////////////////////////////////////////////////////

static skiagm::GM* MyFactory(void*) { return new ArithmodeGM; }
static skiagm::GMRegistry reg(MyFactory);
<|endoftext|>


<commit_before>//===-- SystemInitializerLLGS.cpp -------------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#include "SystemInitializerLLGS.h"

#if defined(__APPLE__)
#include "Plugins/ObjectFile/Mach-O/ObjectFileMachO.h"
using HostObjectFile = ObjectFileMachO;
#elif defined(_WIN32)
#include "Plugins/ObjectFile/PECOFF/ObjectFilePECOFF.h"
using HostObjectFile = ObjectFilePECOFF;
#else
#include "Plugins/ObjectFile/ELF/ObjectFileELF.h"
using HostObjectFile = ObjectFileELF;
#endif

#if defined(__arm__) || defined(__arm) || defined(_ARM) || defined(_M_ARM)
#define LLDB_TARGET_ARM
#include "Plugins/Instruction/ARM/EmulateInstructionARM.h"
#endif

#if defined(__mips__) || defined(mips) || defined(__mips) ||                   \
    defined(__MIPS__) || defined(_M_MIPS)
#define LLDB_TARGET_MIPS
#include "Plugins/Instruction/MIPS/EmulateInstructionMIPS.h"
#endif

#if defined(__mips64__) || defined(mips64) || defined(__mips64) ||             \
    defined(__MIPS64__) || defined(_M_MIPS64)
#define LLDB_TARGET_MIPS64
#include "Plugins/Instruction/MIPS64/EmulateInstructionMIPS64.h"
#endif

using namespace lldb_private;

llvm::Error SystemInitializerLLGS::Initialize() {
  if (auto e = SystemInitializerCommon::Initialize())
    return e;

  HostObjectFile::Initialize();

#if defined(LLDB_TARGET_ARM)
  EmulateInstructionARM::Initialize();
#endif
#if defined(LLDB_TARGET_MIPS)
  EmulateInstructionMIPS::Initialize();
#endif
#if defined(LLDB_TARGET_MIPS64)
  EmulateInstructionMIPS64::Initialize();
#endif

  return llvm::Error::success();
}

void SystemInitializerLLGS::Terminate() {
  HostObjectFile::Terminate();

#if defined(LLDB_TARGET_ARM)
  EmulateInstructionARM::Terminate();
#endif
#if defined(LLDB_TARGET_MIPS)
  EmulateInstructionMIPS::Terminate();
#endif
#if defined(LLDB_TARGET_MIPS64)
  EmulateInstructionMIPS64::Terminate();
#endif

  SystemInitializerCommon::Terminate();
}
<commit_msg>lldb-server: LLGS: support 32-bit on 64-bit hosts<commit_after>//===-- SystemInitializerLLGS.cpp -------------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#include "SystemInitializerLLGS.h"

#if defined(__APPLE__)
#include "Plugins/ObjectFile/Mach-O/ObjectFileMachO.h"
using HostObjectFile = ObjectFileMachO;
#elif defined(_WIN32)
#include "Plugins/ObjectFile/PECOFF/ObjectFilePECOFF.h"
using HostObjectFile = ObjectFilePECOFF;
#else
#include "Plugins/ObjectFile/ELF/ObjectFileELF.h"
using HostObjectFile = ObjectFileELF;
#endif

#if defined(__arm64__) || defined(__aarch64__) || defined(_M_ARM64)
#define LLDB_TARGET_ARM64
#endif

#if defined(__arm__) || defined(__arm) || defined(_ARM) || defined(_M_ARM) ||  \
    defined(LLDB_TARGET_ARM64)
#define LLDB_TARGET_ARM
#include "Plugins/Instruction/ARM/EmulateInstructionARM.h"
#endif

#if defined(__mips64__) || defined(mips64) || defined(__mips64) ||             \
    defined(__MIPS64__) || defined(_M_MIPS64)
#define LLDB_TARGET_MIPS64
#include "Plugins/Instruction/MIPS64/EmulateInstructionMIPS64.h"
#endif

#if defined(__mips__) || defined(mips) || defined(__mips) ||                   \
    defined(__MIPS__) || defined(_M_MIPS) || defined(LLDB_TARGET_MIPS64)
#define LLDB_TARGET_MIPS
#include "Plugins/Instruction/MIPS/EmulateInstructionMIPS.h"
#endif

using namespace lldb_private;

llvm::Error SystemInitializerLLGS::Initialize() {
  if (auto e = SystemInitializerCommon::Initialize())
    return e;

  HostObjectFile::Initialize();

#if defined(LLDB_TARGET_ARM) || defined(LLDB_TARGET_ARM64)
  EmulateInstructionARM::Initialize();
#endif
#if defined(LLDB_TARGET_MIPS) || defined(LLDB_TARGET_MIPS64)
  EmulateInstructionMIPS::Initialize();
#endif
#if defined(LLDB_TARGET_MIPS64)
  EmulateInstructionMIPS64::Initialize();
#endif

  return llvm::Error::success();
}

void SystemInitializerLLGS::Terminate() {
  HostObjectFile::Terminate();

#if defined(LLDB_TARGET_ARM) || defined(LLDB_TARGET_ARM64)
  EmulateInstructionARM::Terminate();
#endif
#if defined(LLDB_TARGET_MIPS) || defined(LLDB_TARGET_MIPS64)
  EmulateInstructionMIPS::Terminate();
#endif
#if defined(LLDB_TARGET_MIPS64)
  EmulateInstructionMIPS64::Terminate();
#endif

  SystemInitializerCommon::Terminate();
}
<|endoftext|>


<commit_before>// 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.

#ifndef __STOUT_WINDOWS_OS_HPP__
#define __STOUT_WINDOWS_OS_HPP__

#include <direct.h>
#include <io.h>

#include <sys/utime.h>

#include <list>
#include <map>
#include <set>
#include <string>

#include <stout/duration.hpp>
#include <stout/none.hpp>
#include <stout/nothing.hpp>
#include <stout/option.hpp>
#include <stout/path.hpp>
#include <stout/try.hpp>
#include <stout/windows.hpp>

#include <stout/os/os.hpp>
#include <stout/os/read.hpp>

#include <stout/os/raw/environment.hpp>

namespace os {

/*
// Sets the value associated with the specified key in the set of
// environment variables.
inline void setenv(const std::string& key,
                   const std::string& value,
                   bool overwrite = true)
{
  UNIMPLEMENTED;
}

// Unsets the value associated with the specified key in the set of
// environment variables.
inline void unsetenv(const std::string& key)
{
  UNIMPLEMENTED;
}

// Executes a command by calling "/bin/sh -c <command>", and returns
// after the command has been completed. Returns 0 if succeeds, and
// return -1 on error (e.g., fork/exec/waitpid failed). This function
// is async signal safe. We return int instead of returning a Try
// because Try involves 'new', which is not async signal safe.
inline int system(const std::string& command)
{
  UNIMPLEMENTED;
}

// This function is a portable version of execvpe ('p' means searching
// executable from PATH and 'e' means setting environments). We add
// this function because it is not available on all systems.
//
// NOTE: This function is not thread safe. It is supposed to be used
// only after fork (when there is only one thread). This function is
// async signal safe.
inline int execvpe(const char* file, char** argv, char** envp)
{
  UNIMPLEMENTED;
}

inline Try<Nothing> chown(
    uid_t uid,
    gid_t gid,
    const std::string& path,
    bool recursive)
{
  UNIMPLEMENTED;
}

inline Try<Nothing> chmod(const std::string& path, int mode)
{
  UNIMPLEMENTED;
}

inline Try<Nothing> chroot(const std::string& directory)
{
  UNIMPLEMENTED;
}

inline Try<Nothing> mknod(
    const std::string& path,
    mode_t mode,
    dev_t dev)
{
  UNIMPLEMENTED;
}

inline Result<uid_t> getuid(const Option<std::string>& user = None())
{
  UNIMPLEMENTED;
}

inline Result<gid_t> getgid(const Option<std::string>& user = None())
{
  UNIMPLEMENTED;
}

inline Try<Nothing> su(const std::string& user)
{
  UNIMPLEMENTED;
}

inline Result<std::string> user(Option<uid_t> uid = None())
{
  UNIMPLEMENTED;
}

// Suspends execution for the given duration.
inline Try<Nothing> sleep(const Duration& duration)
{
  UNIMPLEMENTED;
}

// Returns the list of files that match the given (shell) pattern.
inline Try<std::list<std::string>> glob(const std::string& pattern)
{
  UNIMPLEMENTED;
}

// Returns the total number of cpus (cores).
inline Try<long> cpus()
{
  UNIMPLEMENTED;
}

// Returns load struct with average system loads for the last
// 1, 5 and 15 minutes respectively.
// Load values should be interpreted as usual average loads from
// uptime(1).
inline Try<Load> loadavg()
{
  UNIMPLEMENTED;
}

// Returns the total size of main and free memory.
inline Try<Memory> memory()
{
  UNIMPLEMENTED;
}

// Return the system information.
inline Try<UTSInfo> uname()
{
  UNIMPLEMENTED;
}

inline Try<std::list<Process>> processes()
{
  UNIMPLEMENTED;
}

// Overload of os::pids for filtering by groups and sessions.
// A group / session id of 0 will fitler on the group / session ID
// of the calling process.
inline Try<std::set<pid_t>> pids(Option<pid_t> group, Option<pid_t> session)
{
  UNIMPLEMENTED;
}
*/
} // namespace os {

#endif // __STOUT_WINDOWS_OS_HPP__
<commit_msg>Windows: Stout: Removed user based functions.<commit_after>// 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.

#ifndef __STOUT_WINDOWS_OS_HPP__
#define __STOUT_WINDOWS_OS_HPP__

#include <direct.h>
#include <io.h>

#include <sys/utime.h>

#include <list>
#include <map>
#include <set>
#include <string>

#include <stout/duration.hpp>
#include <stout/none.hpp>
#include <stout/nothing.hpp>
#include <stout/option.hpp>
#include <stout/path.hpp>
#include <stout/try.hpp>
#include <stout/windows.hpp>

#include <stout/os/os.hpp>
#include <stout/os/read.hpp>

#include <stout/os/raw/environment.hpp>

namespace os {

/*
// Sets the value associated with the specified key in the set of
// environment variables.
inline void setenv(const std::string& key,
                   const std::string& value,
                   bool overwrite = true)
{
  UNIMPLEMENTED;
}

// Unsets the value associated with the specified key in the set of
// environment variables.
inline void unsetenv(const std::string& key)
{
  UNIMPLEMENTED;
}

// Executes a command by calling "/bin/sh -c <command>", and returns
// after the command has been completed. Returns 0 if succeeds, and
// return -1 on error (e.g., fork/exec/waitpid failed). This function
// is async signal safe. We return int instead of returning a Try
// because Try involves 'new', which is not async signal safe.
inline int system(const std::string& command)
{
  UNIMPLEMENTED;
}

// This function is a portable version of execvpe ('p' means searching
// executable from PATH and 'e' means setting environments). We add
// this function because it is not available on all systems.
//
// NOTE: This function is not thread safe. It is supposed to be used
// only after fork (when there is only one thread). This function is
// async signal safe.
inline int execvpe(const char* file, char** argv, char** envp)
{
  UNIMPLEMENTED;
}

inline Try<Nothing> chown(
    uid_t uid,
    gid_t gid,
    const std::string& path,
    bool recursive)
{
  UNIMPLEMENTED;
}

inline Try<Nothing> chmod(const std::string& path, int mode)
{
  UNIMPLEMENTED;
}

inline Try<Nothing> chroot(const std::string& directory)
{
  UNIMPLEMENTED;
}

inline Try<Nothing> mknod(
    const std::string& path,
    mode_t mode,
    dev_t dev)
{
  UNIMPLEMENTED;
}

// Suspends execution for the given duration.
inline Try<Nothing> sleep(const Duration& duration)
{
  UNIMPLEMENTED;
}

// Returns the list of files that match the given (shell) pattern.
inline Try<std::list<std::string>> glob(const std::string& pattern)
{
  UNIMPLEMENTED;
}

// Returns the total number of cpus (cores).
inline Try<long> cpus()
{
  UNIMPLEMENTED;
}

// Returns load struct with average system loads for the last
// 1, 5 and 15 minutes respectively.
// Load values should be interpreted as usual average loads from
// uptime(1).
inline Try<Load> loadavg()
{
  UNIMPLEMENTED;
}

// Returns the total size of main and free memory.
inline Try<Memory> memory()
{
  UNIMPLEMENTED;
}

// Return the system information.
inline Try<UTSInfo> uname()
{
  UNIMPLEMENTED;
}

inline Try<std::list<Process>> processes()
{
  UNIMPLEMENTED;
}

// Overload of os::pids for filtering by groups and sessions.
// A group / session id of 0 will fitler on the group / session ID
// of the calling process.
inline Try<std::set<pid_t>> pids(Option<pid_t> group, Option<pid_t> session)
{
  UNIMPLEMENTED;
}
*/
} // namespace os {

#endif // __STOUT_WINDOWS_OS_HPP__
<|endoftext|>


<commit_before>#include <climits>
#include <iostream>
#include <atomic>
#include <thread>
#include <chrono>
#include <set>
#include <signal.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <wibble/commandline/parser.h>
#include <string.h>
#include <elevator/driver.h>
#include <elevator/test.h>
#include <elevator/elevator.h>
#include <elevator/scheduler.h>
#include <elevator/udptools.h>
#include <elevator/udpqueue.h>
#include <elevator/sessionmanager.h>

void handler( int sig, siginfo_t *info, void * ) {
    elevator::Driver driver;
    driver.stopElevator();
    std::cerr << "elevator stopped" << std::endl;
    if ( sig != SIGCHLD ) {
        exit( sig );
    } else {
        int pid = info->si_pid;
        waitpid( pid, nullptr, WNOHANG );
    }
}

namespace elevator {

using namespace wibble;
using namespace wibble::commandline;
using namespace udp;

struct Main {

    const Address commSend{ IPv4Address::any, Port{ 64123 } };
    const Address commRcv{ IPv4Address::any, Port{ 64125 } };
    const Address commBroadcast{ IPv4Address::broadcast, Port{ 64125 } };

    const Port stateChangePort{ 64016 };
    const Port commandPort{ 64017 };

    StandardParser opts;
    OptionGroup *execution;
    IntOption *optNodes;
    BoolOption *avoidRecovery;
    const int peerMsg = 1000;
    std::set< IPv4Address > peerAddresses;
    int id = INT_MIN;
    int nodes = 1;

    Main( int argc, const char **argv ) : opts( "elevator", "0.1" ) {
        // setup options
        execution = opts.createGroup( "Execution options" );
        optNodes = execution->add< IntOption >(
                "nodes", 'n', "nodes", "",
                "specifies number of elevator nodes to expect" );

        avoidRecovery = execution->add< BoolOption >(
                "avoid recovery", 0, "avoid-recovery", "",
                "avoid auto-recovery when program is killed (do not fork)" );

        opts.usage = "";
        opts.description = "Elevator control software as a project for the "
                           "TTK4145 Real-Time Programming at NTNU. Controls "
                           "multiple elevator connected with local network.\n"
                           "(c) 2014, Vladimír Štill and Sameh Khalil\n"
                           "https://github.com/vlstill/ttk4145/tree/master/project";

        opts.add( execution );

        // parse options
        try {
            opts.parse( argc, argv );
        } catch ( exception::BadOption &ex ) {
            std::cerr << "FATAL: " << ex.fullInfo() << std::endl;
            exit( 1 );
        }
        if ( opts.help->boolValue() || opts.version->boolValue() )
            exit( 0 );
    }

    void setupChild() {
        struct sigaction act;
        memset( &act, 0, sizeof( struct sigaction ) );
        act.sa_handler = SIG_DFL;
        sigaction( SIGCHLD, &act, nullptr );
        sigaction( SIGINT, &act, nullptr );

        runElevator();
    }

    void watchChild( int childPid ) {
        while ( true ) {
            pause(); // wait for signal
            initRecovery();
        }
    }

    void setupSignals() {
        struct sigaction act;
        memset( &act, 0, sizeof( struct sigaction ) );
        act.sa_sigaction = handler;
        act.sa_flags = SA_SIGINFO;
        sigaction( SIGCHLD, &act, nullptr ); // child died
        sigaction( SIGINT, &act, nullptr ); // ctrl+c
    }

    void initRecovery() {
        setupSignals();
        int pid = fork();
        if ( pid == 0 ) { // child
            setupChild();
        } else if ( pid > 0 ) { // parent
            watchChild( pid );
        } else {
            std::cerr << "Fatal error: fork failed" << std::endl;
            exit( 1 );
        }
    }

    void main() {

        if ( avoidRecovery->boolValue() ) {
            runElevator();
        } else {
            initRecovery();
        }
    }

    void runElevator() {
        int id;
        GlobalState global;
        HeartBeatManager heartbeatManager;
        SessionManager sessman{ global };

        if ( optNodes->boolValue() && optNodes->intValue() > 1 ) {
            nodes = optNodes->intValue();
            sessman.connect( heartbeatManager.getNew( 5000 ), nodes );
            id = sessman.id();
        } else {
            id = 0;
        }

        std::cout << "starting elevator, id " << id << " of " << nodes << " elevators" << std::endl;

        ConcurrentQueue< Command > commandsToLocalElevator;
        ConcurrentQueue< Command > commandsToOthers;
        ConcurrentQueue< StateChange > stateChangesIn;
        ConcurrentQueue< StateChange > stateChangesOut;

        QueueReceiver< Command > commandsToLocalElevatorReceiver {
            Address{ IPv4Address::any, commandPort },
            commandsToLocalElevator,
            [id]( const Command &comm ) { return comm.targetElevatorId == id; }
        };
        QueueReceiver< StateChange > stateChangesInReceiver {
            Address{ IPv4Address::any, stateChangePort },
            stateChangesIn,
            [id]( const StateChange &chan ) { return chan.state.id != id; }
        };
        QueueSender< StateChange > stateChangesOutSender {
            commSend,
            Address{ IPv4Address::broadcast, stateChangePort },
            stateChangesOut
        };
        QueueSender< Command > commandsToOthersReceiver {
            commSend,
            Address{ IPv4Address::broadcast, commandPort },
            commandsToOthers
        };

        /* about heartbeat lengths:
         * - elevator loop is polling and never sleeping, therefore its scheduling
         *   is quite relieable and it can have short heartbeat,
         *   furthermore we need to make sure we will detect any floor change,
         *   therefore heartbeat it must respond faster then is time to cross sensor
         *   (approx 400ms), also note that even with heartbeat of 10ms the elevator
         *   seems to be running reliably
         * - scheduler again has quite tight demand, as it should be able to handle
         *   all state changes from elevator, but we have to be more carefull here
         *   as it is sleeping sometimes
         */
        Elevator elevator {
            id,
            heartbeatManager.getNew( 500 /* ms */ ),
            commandsToLocalElevator,
            stateChangesIn
        };
        Scheduler scheduler {
            id,
            elevator.info(),
            global,
            stateChangesIn,
            stateChangesOut,
            commandsToOthers,
            commandsToLocalElevator
        };

        if ( nodes > 1 ) {
            commandsToLocalElevatorReceiver.run();
            stateChangesInReceiver.run();
            commandsToOthersReceiver.run();
            stateChangesOutSender.run();
        }
        elevator.run();
        scheduler.run( heartbeatManager.getNew( 1000 ), heartbeatManager.getNew( 1000 ) );

        // wait for 2 seconds so that everything has chance to start
        // it something fails to start in this time heartbeat will
        // fail and process will be terminated
        std::this_thread::sleep_for( std::chrono::seconds( 2 ) );
        // heartbeat failure will throw an exception which will terminate
        // process (as it is not catched)
        heartbeatManager.runInThisThread();
    }
};

}

int main( int args, const char **argv ) {
    elevator::Main m( args, argv );
    m.main();
}
<commit_msg>main: Run state recovery if needed.<commit_after>#include <climits>
#include <iostream>
#include <atomic>
#include <thread>
#include <chrono>
#include <set>
#include <signal.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <wibble/commandline/parser.h>
#include <string.h>
#include <elevator/driver.h>
#include <elevator/test.h>
#include <elevator/elevator.h>
#include <elevator/scheduler.h>
#include <elevator/udptools.h>
#include <elevator/udpqueue.h>
#include <elevator/sessionmanager.h>

void handler( int sig, siginfo_t *info, void * ) {
    elevator::Driver driver;
    driver.stopElevator();
    std::cerr << "elevator stopped" << std::endl;
    if ( sig != SIGCHLD ) {
        exit( sig );
    } else {
        int pid = info->si_pid;
        waitpid( pid, nullptr, WNOHANG );
    }
}

namespace elevator {

using namespace wibble;
using namespace wibble::commandline;
using namespace udp;

struct Main {

    const Address commSend{ IPv4Address::any, Port{ 64123 } };
    const Address commRcv{ IPv4Address::any, Port{ 64125 } };
    const Address commBroadcast{ IPv4Address::broadcast, Port{ 64125 } };

    const Port stateChangePort{ 64016 };
    const Port commandPort{ 64017 };

    StandardParser opts;
    OptionGroup *execution;
    IntOption *optNodes;
    BoolOption *avoidRecovery;
    const int peerMsg = 1000;
    std::set< IPv4Address > peerAddresses;
    int id = INT_MIN;
    int nodes = 1;

    Main( int argc, const char **argv ) : opts( "elevator", "0.1" ) {
        // setup options
        execution = opts.createGroup( "Execution options" );
        optNodes = execution->add< IntOption >(
                "nodes", 'n', "nodes", "",
                "specifies number of elevator nodes to expect" );

        avoidRecovery = execution->add< BoolOption >(
                "avoid recovery", 0, "avoid-recovery", "",
                "avoid auto-recovery when program is killed (do not fork)" );

        opts.usage = "";
        opts.description = "Elevator control software as a project for the "
                           "TTK4145 Real-Time Programming at NTNU. Controls "
                           "multiple elevator connected with local network.\n"
                           "(c) 2014, Vladimír Štill and Sameh Khalil\n"
                           "https://github.com/vlstill/ttk4145/tree/master/project";

        opts.add( execution );

        // parse options
        try {
            opts.parse( argc, argv );
        } catch ( exception::BadOption &ex ) {
            std::cerr << "FATAL: " << ex.fullInfo() << std::endl;
            exit( 1 );
        }
        if ( opts.help->boolValue() || opts.version->boolValue() )
            exit( 0 );
    }

    void setupChild() {
        struct sigaction act;
        memset( &act, 0, sizeof( struct sigaction ) );
        act.sa_handler = SIG_DFL;
        sigaction( SIGCHLD, &act, nullptr );
        sigaction( SIGINT, &act, nullptr );

        runElevator();
    }

    void watchChild( int childPid ) {
        while ( true ) {
            pause(); // wait for signal
            initRecovery();
        }
    }

    void setupSignals() {
        struct sigaction act;
        memset( &act, 0, sizeof( struct sigaction ) );
        act.sa_sigaction = handler;
        act.sa_flags = SA_SIGINFO;
        sigaction( SIGCHLD, &act, nullptr ); // child died
        sigaction( SIGINT, &act, nullptr ); // ctrl+c
    }

    void initRecovery() {
        setupSignals();
        int pid = fork();
        if ( pid == 0 ) { // child
            setupChild();
        } else if ( pid > 0 ) { // parent
            watchChild( pid );
        } else {
            std::cerr << "Fatal error: fork failed" << std::endl;
            exit( 1 );
        }
    }

    void main() {

        if ( avoidRecovery->boolValue() ) {
            runElevator();
        } else {
            initRecovery();
        }
    }

    void runElevator() {
        int id;
        GlobalState global;
        HeartBeatManager heartbeatManager;
        SessionManager sessman{ global };

        if ( optNodes->boolValue() && optNodes->intValue() > 1 ) {
            nodes = optNodes->intValue();
            sessman.connect( heartbeatManager.getNew( 5000 ), nodes );
            id = sessman.id();
        } else {
            id = 0;
        }

        std::cout << "starting elevator, id " << id << " of " << nodes << " elevators" << std::endl;

        ConcurrentQueue< Command > commandsToLocalElevator;
        ConcurrentQueue< Command > commandsToOthers;
        ConcurrentQueue< StateChange > stateChangesIn;
        ConcurrentQueue< StateChange > stateChangesOut;

        QueueReceiver< Command > commandsToLocalElevatorReceiver {
            Address{ IPv4Address::any, commandPort },
            commandsToLocalElevator,
            [id]( const Command &comm ) { return comm.targetElevatorId == id; }
        };
        QueueReceiver< StateChange > stateChangesInReceiver {
            Address{ IPv4Address::any, stateChangePort },
            stateChangesIn,
            [id]( const StateChange &chan ) { return chan.state.id != id; }
        };
        QueueSender< StateChange > stateChangesOutSender {
            commSend,
            Address{ IPv4Address::broadcast, stateChangePort },
            stateChangesOut
        };
        QueueSender< Command > commandsToOthersReceiver {
            commSend,
            Address{ IPv4Address::broadcast, commandPort },
            commandsToOthers
        };

        /* about heartbeat lengths:
         * - elevator loop is polling and never sleeping, therefore its scheduling
         *   is quite relieable and it can have short heartbeat,
         *   furthermore we need to make sure we will detect any floor change,
         *   therefore heartbeat it must respond faster then is time to cross sensor
         *   (approx 400ms), also note that even with heartbeat of 10ms the elevator
         *   seems to be running reliably
         * - scheduler again has quite tight demand, as it should be able to handle
         *   all state changes from elevator, but we have to be more carefull here
         *   as it is sleeping sometimes
         */
        Elevator elevator {
            id,
            heartbeatManager.getNew( 500 /* ms */ ),
            commandsToLocalElevator,
            stateChangesIn
        };
        Scheduler scheduler {
            id,
            elevator.info(),
            global,
            stateChangesIn,
            stateChangesOut,
            commandsToOthers,
            commandsToLocalElevator
        };

        if ( nodes > 1 ) {
            commandsToLocalElevatorReceiver.run();
            stateChangesInReceiver.run();
            commandsToOthersReceiver.run();
            stateChangesOutSender.run();
        }

        if ( sessman.needRecoveryState() )
            elevator.recover( sessman.recoveryState() );

        elevator.run();
        scheduler.run( heartbeatManager.getNew( 1000 ), heartbeatManager.getNew( 1000 ) );

        // wait for 2 seconds so that everything has chance to start
        // it something fails to start in this time heartbeat will
        // fail and process will be terminated
        std::this_thread::sleep_for( std::chrono::seconds( 2 ) );
        // heartbeat failure will throw an exception which will terminate
        // process (as it is not catched)
        heartbeatManager.runInThisThread();
    }
};

}

int main( int args, const char **argv ) {
    elevator::Main m( args, argv );
    m.main();
}
<|endoftext|>


<commit_before>// ConsoleApplication1.cpp : Defines the entry point for the console application.
// TODO: Run a bunch of times and average runtimes

#include "stdio.h"
#include "math.h"
#include "string.h"
#include <iostream>

using namespace std;

/// This function performs a serial Sieve of Eratosthenes to find all prime number
void eratosthenesSieve(int bound, bool * primeArray)
{
	int sqrtBound = (int)sqrt((double)bound);
	memset(primeArray, 0, sizeof(bool) * (bound + 1));
	primeArray[0] = true;
	primeArray[1] = true;
	for (int m = 2; m <= sqrtBound; m++)
	{
		if (!primeArray[m])
		{
			for (int k = m * m; k <= bound; k += m)
			{
				primeArray[k] = true;
			}
		}
	}

	//this code block was used for debugging
	//for (int m = 2; m < bound; m++)
	//{
	//	if (!primeArray[m])
	//	{
	//		std::cout << m << ", ";
	//	}
	//}
}

///This function performs a serial Sieve of sundaram to find all primes
void sundaramSieve(int bound, bool * primeArray)
{
	bool* findArray = new bool[bound + 1];
	memset(findArray, 0, sizeof(bool) * (bound + 1));
	memset(primeArray, 1, sizeof(bool) * (bound + 1));

	for (int i = 1; i < bound; i++)
	{
		for (int j = i; j <= (bound - i) / (2 * i + 1); j++)
		{
			findArray[i + j + (2 * i * j)] = true;
		}
	}
	for (int i = 1; i < ((bound - 1) / 2); i++)
	{
		if (!findArray[i])
		{
			primeArray[((i * 2) + 1)] = false;
		}
	}
	primeArray[2] = false; // Sundaram doesnt find two so ill find it for it

	//code block below used for debuggin purposes
	//for (int m = 2; m < bound; m++)
	//{
	//	if (!primeArray[m])
	//	{
	//		std::cout << m << ", ";
	//	}
	//}
}

void sundPartOneSerial(int bound, bool * findArray)
{
	int max = 0;
	int denom = 0;
	for(int i = 1; i < bound; i++)
	{
		denom = (i << 1) + 1;
		max = (bound - i) / denom;
		for(int j = i; j <= max; j++)
		{
			findArray[i + j * denom] = true;
		}
	}
}

void sundPartTwoSerial(int bound, bool * findArray, bool * primeArray)
{
	int max = (bound - 1) >> 1;
	for(int i = 1; i < max; i++)
	{
		if(!findArray[i])
		{
			primeArray[((i << 1) + 1)] = false;
		}
	}
	primeArray[2] = false;
}

///This function compares two arrays to see if they match in the range of prime numbers
void validatePrimes(int bound, bool* goldArray, bool* checkArray)
{
	/*for (int i = 0; i <= 100; i++)
	{
		cout << i << ".\t" << goldArray[i] << "\t" << checkArray[i] << endl;
	}*/

	for (int i = 0; i <= bound; i++)
	{
		if (goldArray[i] != checkArray[i])
		{
			std::cout << "Difference at Position " << i << "\n";
			std::cout << "Array is Incorrect! \n";
			return;
		}
	}
	std::cout << "Found all primes! \n";
}

<commit_msg>debugging<commit_after>// ConsoleApplication1.cpp : Defines the entry point for the console application.
// TODO: Run a bunch of times and average runtimes

#include "stdio.h"
#include "math.h"
#include "string.h"
#include <iostream>

using namespace std;

/// This function performs a serial Sieve of Eratosthenes to find all prime number
void eratosthenesSieve(int bound, bool * primeArray)
{
	int sqrtBound = (int)sqrt((double)bound);
	memset(primeArray, 0, sizeof(bool) * (bound + 1));
	primeArray[0] = true;
	primeArray[1] = true;
	for (int m = 2; m <= sqrtBound; m++)
	{
		if (!primeArray[m])
		{
			for (int k = m * m; k <= bound; k += m)
			{
				primeArray[k] = true;
			}
		}
	}

	//this code block was used for debugging
	//for (int m = 2; m < bound; m++)
	//{
	//	if (!primeArray[m])
	//	{
	//		std::cout << m << ", ";
	//	}
	//}
}

///This function performs a serial Sieve of sundaram to find all primes
void sundaramSieve(int bound, bool * primeArray)
{
	bool* findArray = new bool[bound + 1];
	memset(findArray, 0, sizeof(bool) * (bound + 1));
	memset(primeArray, 1, sizeof(bool) * (bound + 1));

	for (int i = 1; i < bound; i++)
	{
		for (int j = i; j <= (bound - i) / (2 * i + 1); j++)
		{
			findArray[i + j + (2 * i * j)] = true;
		}
	}
	for (int i = 1; i < ((bound - 1) / 2); i++)
	{
		if (!findArray[i])
		{
			primeArray[((i * 2) + 1)] = false;
		}
	}
	primeArray[2] = false; // Sundaram doesnt find two so ill find it for it

	//code block below used for debuggin purposes
	//for (int m = 2; m < bound; m++)
	//{
	//	if (!primeArray[m])
	//	{
	//		std::cout << m << ", ";
	//	}
	//}
}

void sundPartOneSerial(int bound, bool * findArray)
{
	int max = 0;
	int denom = 0;
	for(int i = 1; i < bound; i++)
	{
		denom = (i << 1) + 1;
		max = (bound - i) / denom;
		for(int j = i; j <= max; j++)
		{
			findArray[i + j * denom] = true;
		}
	}
}

void sundPartTwoSerial(int bound, bool * findArray, bool * primeArray)
{
	int max = (bound - 1) >> 1;
	for(int i = 1; i < max; i++)
	{
		if(!findArray[i])
		{
			primeArray[((i << 1) + 1)] = false;
		}
	}
	primeArray[2] = false;
}

///This function compares two arrays to see if they match in the range of prime numbers
void validatePrimes(int bound, bool* goldArray, bool* checkArray)
{
	for (int i = 0; i <= 100; i++)
	{
		cout << i << ".\t" << goldArray[i] << "\t" << checkArray[i] << endl;
	}

	for (int i = 0; i <= bound; i++)
	{
		if (goldArray[i] != checkArray[i])
		{
			std::cout << "Difference at Position " << i << "\n";
			std::cout << "Array is Incorrect! \n";
			return;
		}
	}
	std::cout << "Found all primes! \n";
}

<|endoftext|>


<commit_before>// Copyright 2018 The clvk 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.

#pragma once

#include "log.hpp"

#include <cassert>

#include <vulkan/vulkan.h>

#ifndef _MSC_VER
#define CHECK_RETURN __attribute__((warn_unused_result))
#else
#define CHECK_RETURN
#endif

char* cvk_mkdtemp(std::string& tmpl);
int cvk_exec(const std::string& cmd, std::string* output = nullptr);

#define CVK_VK_CHECK_INTERNAL(logfn, res, msg)                                 \
    do {                                                                       \
        if (res != VK_SUCCESS) {                                               \
            logfn(msg " : %s", vulkan_error_string(res));                      \
        }                                                                      \
    } while (0);

#define CVK_VK_CHECK_INTERNAL_RET(logfn, res, ret, msg)                        \
    do {                                                                       \
        if (res != VK_SUCCESS) {                                               \
            logfn(msg " : %s", vulkan_error_string(res));                      \
            return ret;                                                        \
        }                                                                      \
    } while (0);

#define CVK_VK_CHECK_FATAL(res, msg) CVK_VK_CHECK_INTERNAL(cvk_fatal, res, msg)
#define CVK_VK_CHECK_ERROR(res, msg) CVK_VK_CHECK_INTERNAL(cvk_error, res, msg)
#define CVK_VK_CHECK_ERROR_RET(res, ret, msg)                                  \
    CVK_VK_CHECK_INTERNAL_RET(cvk_error, res, ret, msg)

#define CVK_ASSERT(cond) assert(cond)

#define UNUSED(X) ((void)(X))

#define ARRAY_SIZE(X) (sizeof(X) / sizeof(X[0]))

static inline void* pointer_offset(const void* ptr, size_t offset) {
    auto ptrint = reinterpret_cast<uintptr_t>(ptr);
    return reinterpret_cast<void*>(ptrint + offset);
}

static inline uint32_t ceil_div(uint32_t num, uint32_t divisor) {
    CVK_ASSERT(divisor != 0);
    return (num + divisor - 1) / divisor;
}

static inline uint32_t round_up(uint32_t num, uint32_t multiple) {
    CVK_ASSERT(multiple != 0);
    return ceil_div(num, multiple) * multiple;
}

// Return the hex string representation of `bytes`.
static inline std::string to_hex_string(const uint8_t* bytes, uint32_t len) {
    const char chars[] = "0123456789abcdef";
    std::string str = "";
    for (uint32_t i = 0; i < len; i++) {
        str += *(chars + (bytes[i] >> 4));
        str += *(chars + (bytes[i] & 0xF));
    }
    return str;
}
<commit_msg>fix ceil-div to avoid overflow (#370)<commit_after>// Copyright 2018 The clvk 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.

#pragma once

#include "log.hpp"

#include <cassert>

#include <vulkan/vulkan.h>

#ifndef _MSC_VER
#define CHECK_RETURN __attribute__((warn_unused_result))
#else
#define CHECK_RETURN
#endif

char* cvk_mkdtemp(std::string& tmpl);
int cvk_exec(const std::string& cmd, std::string* output = nullptr);

#define CVK_VK_CHECK_INTERNAL(logfn, res, msg)                                 \
    do {                                                                       \
        if (res != VK_SUCCESS) {                                               \
            logfn(msg " : %s", vulkan_error_string(res));                      \
        }                                                                      \
    } while (0);

#define CVK_VK_CHECK_INTERNAL_RET(logfn, res, ret, msg)                        \
    do {                                                                       \
        if (res != VK_SUCCESS) {                                               \
            logfn(msg " : %s", vulkan_error_string(res));                      \
            return ret;                                                        \
        }                                                                      \
    } while (0);

#define CVK_VK_CHECK_FATAL(res, msg) CVK_VK_CHECK_INTERNAL(cvk_fatal, res, msg)
#define CVK_VK_CHECK_ERROR(res, msg) CVK_VK_CHECK_INTERNAL(cvk_error, res, msg)
#define CVK_VK_CHECK_ERROR_RET(res, ret, msg)                                  \
    CVK_VK_CHECK_INTERNAL_RET(cvk_error, res, ret, msg)

#define CVK_ASSERT(cond) assert(cond)

#define UNUSED(X) ((void)(X))

#define ARRAY_SIZE(X) (sizeof(X) / sizeof(X[0]))

static inline void* pointer_offset(const void* ptr, size_t offset) {
    auto ptrint = reinterpret_cast<uintptr_t>(ptr);
    return reinterpret_cast<void*>(ptrint + offset);
}

static inline uint32_t ceil_div(uint32_t num, uint32_t divisor) {
    CVK_ASSERT(divisor != 0);
    return num / divisor + (num % divisor != 0);
}

static inline uint32_t round_up(uint32_t num, uint32_t multiple) {
    CVK_ASSERT(multiple != 0);
    return ceil_div(num, multiple) * multiple;
}

// Return the hex string representation of `bytes`.
static inline std::string to_hex_string(const uint8_t* bytes, uint32_t len) {
    const char chars[] = "0123456789abcdef";
    std::string str = "";
    for (uint32_t i = 0; i < len; i++) {
        str += *(chars + (bytes[i] >> 4));
        str += *(chars + (bytes[i] & 0xF));
    }
    return str;
}
<|endoftext|>


<commit_before>// https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=submit_problem&problemid=784&category=

#include <iostream>
#include <vector>
#include <algorithm>
#include <sstream>
#include <unordered_map>
#include <unordered_set>
#include <iterator>
using namespace std;

using mapping_t = unordered_map<char, char>;
using mapped_t = unordered_set<char>;
using iterator_t = vector<string>::const_iterator;

mapping_t find_mapping(iterator_t word, const iterator_t &w_end,
                       const vector<string> &dict,
                       const mapping_t &mapping, const mapped_t &mapped)
{
    iterator_t dword = dict.begin();

    // Skip all longer words
    while (word->size() < dword->size()) {
        ++dword;
        if (dword == dict.end()) return mapping_t();
    }

    while (dword != dict.end()) {
        // Do we have a matching word in the dictionary?
        if (word->size() > dword->size()) return mapping_t();

        mapping_t ret(mapping);
        mapped_t upd_mapped(mapped);
        const char* pd = dword->c_str();
        for (const auto c: *word) {
            const auto it = ret.find(c);
            const auto it2 = mapped.find(*pd);
            if (it == ret.end() && it2 == upd_mapped.end()) {
                ret[c] = *pd;
                upd_mapped.insert(*pd);
            }
            else if (it == ret.end() || it->second != *pd) {
                ++dword;
                ret.clear();
                break;
            }
            ++pd;
        }
        if (!ret.empty()) {
            if (++word == w_end) return ret;
            // mapping ok, try next word
            else return find_mapping(word, w_end, dict, ret, upd_mapped);
        };
    }

}

int main() {
    string str;
    int dict_size{0};
    cin >> dict_size;
    getline(cin, str); // consume endl

    vector<string> dict;
    dict.reserve(dict_size);
    for (int i = 0; i < dict_size; ++i) {
        getline(cin, str);
        dict.push_back(str);
    }
    sort(dict.begin(), dict.end(), [](const string &a, const string &b){
        return a.size() > b.size();
    });
    //cout << dict[0] << endl;
    while (true) {
        getline(cin, str);
        if (!cin) break;

        istringstream iss(str);
        vector<string> words{istream_iterator<string>{iss},
                             istream_iterator<string>{}};
        sort(words.begin(), words.end(), [](const string &a, string auto &b){
            return a.size() > b.size();
        });

        auto mapping = find_mapping(words.begin(), words.end(), dict, mapping_t(), mapped_t());
        bool is_found = !mapping.empty();
        for (const auto c: str) {
            if (c == ' ') cout << c;
            else if (is_found) cout << mapping[c];
            else cout << '*';
        }
        cout << endl;
    }
    return 0;
}<commit_msg>Crypt Kicker: accepted solution<commit_after>// https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=submit_problem&problemid=784&category=

#include <iostream>
#include <vector>
#include <algorithm>
#include <sstream>
#include <array>
#include <iterator>
#include <cassert>
using namespace std;

using iterator_t = vector<string>::const_iterator;

class Mapping {
    static constexpr size_t N_CHAR = 26;
    array<char, 26> forward_ = {0}; // to clear
    array<char, 26> back_    = {0}; // to cypher
    size_t count = 0;

    size_t idx(char c) { return c - 'a'; }
public:
    bool empty() const { return count == 0; }
    bool add(char from, char to) {
        if (forward_[idx(from)] == 0 && back_[idx(to)] == 0) {
            forward_[idx(from)] = to;
            back_[idx(to)]      = from;
            ++count;
            return true;
        }
        return forward_[idx(from)] == to;
    }
    char operator[](char c) {
        assert(forward_[idx(c)]);
        return forward_[idx(c)];
    }
};

bool map_word(const string &word, const string &dword, Mapping &m)
{
    assert (word.size() == dword.size());
    const char *pF = word.c_str();
    const char *pT = dword.c_str();
    while (*pF) {
        if (!m.add(*pF++, *pT++))
            return false;
    }
    return true;
}

// DFS with recursion
Mapping find_mapping(iterator_t word, const iterator_t &w_end,
                       const vector<string> &dict,
                       const Mapping &mapping)
{
    if (word == w_end) return mapping;
    for (const auto &dword: dict) {
        if (dword.size() > word->size()) continue;
        if (dword.size() < word->size()) break;
        Mapping m(mapping);
        if (map_word(*word, dword, m)) {

            Mapping mret = find_mapping(word+1, w_end, dict, m);
            if (!mret.empty()) return mret;
        }
    }
    return Mapping();
}

void sortDescending(vector<string> &v) {
    sort(begin(v), end(v), [](const string &a, const string &b){
        return a.size() > b.size();
    });
}

int main() {
    string str;
    int dict_size{0};
    cin >> dict_size;
    getline(cin, str); // consume endl

    vector<string> dict;
    dict.reserve(dict_size);
    for (int i = 0; i < dict_size; ++i) {
        getline(cin, str);
        dict.push_back(str);
    }
    // Sort dictionary and input sentence in size descending order,
    // betting on the fact that longer words are less requent and
    // have a better chance of having repeating letters
    sortDescending(dict);

    while (true) {
        getline(cin, str);
        if (!cin) break;

        istringstream iss(str);
        vector<string> words{istream_iterator<string>{iss},
                             istream_iterator<string>{}};
        sortDescending(words);

        auto mapping = find_mapping(words.begin(), words.end(), dict, Mapping());
        bool is_found = !mapping.empty();
        for (const auto c: str) {
            if (c == ' ') cout << c;
            else if (is_found) cout << mapping[c];
            else cout << '*';
        }
        cout << endl;
    }
    return 0;
}
<|endoftext|>


<commit_before>#include <vector>

#include "weapons.h"
#include "error_handling.h"
#include "magic.h"
#include "monster.h"
#include "player.h"
#include "game.h"
#include "colors.h"
#include "fight.h"
#include "misc.h"
#include "rogue.h"

#include "wand.h"

using namespace std;

// "walk" in the zap direction until we find a target
static Monster* wand_find_target(int* y, int* x, int dy, int dx) {

  *y = player->get_position().y;
  *x = player->get_position().x;

  while (Game::level->can_step(*x, *y)) {
    *y += dy;
    *x += dx;
  }

  return Game::level->get_monster(*x, *y);
}

static void wand_spell_light(void)
{
  room* player_room = Game::level->get_room(player->get_position());
  if (player_room == nullptr || player_room->is_gone) {
    Game::io->message("the corridor glows and then fades");

  } else {
    player_room->is_dark = false;
    Game::io->message("the rooms is lit by a shimmering blue light");
  }
}

// take away 1/2 of hero's hit points, then take it away
// evenly from the monsters in the room (or next to hero
// if he is in a passage)
static void
wand_spell_drain_health(void) {

  // Add nearby monsters to a list
  vector<Monster*> drainee;

  for (Monster* monster : Game::level->monsters) {
    if (player->can_see(*monster)) {
      drainee.push_back(monster);
    }
  }

  // No monster found -> return
  if (drainee.empty()) {
    Game::io->message("you have a tingling feeling");
    return;
  }

  int damage = player->get_health() / 2;
  player->take_damage(damage);
  Game::io->message("You feel an intense pain");

  // Now zot all of the monsters
  // Must use manual loop here, since monsters can be deleted
  auto it = drainee.begin();
  while (it != drainee.end()) {
    Monster* monster = *it++;
    monster->take_damage(damage);

    if (monster->get_health() < 0) {
      monster_on_death(&monster, player->can_see(*monster));

    } else {
      monster_start_running(&monster->get_position());
      Game::io->message(monster->get_name() + " screams in pain");
    }
  }
}

static void
wand_spell_polymorph(Monster& target)
{
  monster_polymorph(&target);
  if (player->can_see(*&target)) {
    Wand::set_known(Wand::Polymorph);
  }
}

static void
wand_spell_cancel(Monster& target)
{
  target.set_cancelled();
  target.set_not_invisible();
  target.remove_confusing_attack();

  target.set_disguise(target.get_look());
}

static void
wand_spell_magic_missile(int dy, int dx)
{
  class Weapon bolt(Weapon::Dagger);
  bolt.o_type    = '*';
  bolt.set_hit_plus(100);
  bolt.set_damage_plus(1);
  bolt.set_attack_damage({0, 0});
  bolt.set_throw_damage({1, 4});

  Item* weapon = player->equipped_weapon();
  if (weapon != nullptr) {
    bolt.o_launch = weapon->o_which;
  }

  Game::io->missile_motion(&bolt, dy, dx);

  Monster* target = Game::level->get_monster(bolt.get_position());
  if (target == nullptr) {
    Game::io->message("the missle vanishes with a puff of smoke");

  } else if (monster_save_throw(VS_MAGIC, target)) {
    Game::io->message("the missle missed the " + target->get_name());

  } else {
    fight_against_monster(&bolt.get_position(), &bolt, true);
  }
}

bool
wand_zap(void)
{
  Coordinate const* dir = get_dir();
  if (dir == nullptr) {
    return false;
  }

  Item* obj = player->pack_find_item("zap with", IO::Wand);
  Wand* wand = dynamic_cast<Wand*>(obj);
  if (obj == nullptr)
    return false;

  else if (obj->o_type != IO::Wand || wand == nullptr) {
    Game::io->message("you can't zap with that!");
    return false;

  } else if (wand->get_charges() == 0) {
    Game::io->message("nothing happens");
    return true;
  }

  Wand::Type subtype = static_cast<Wand::Type>(obj->o_which);
  switch (subtype)
  {

    case Wand::Light: {
      Wand::set_known(subtype);
      wand_spell_light();
    } break;

    case Wand::DrainLife: {
      if (player->get_health() > 1) {
        wand_spell_drain_health();

      } else {
        Game::io->message("you are too weak to use it");
        return true;
      }
    } break;

    case Wand::InvisibleOther: {
        Coordinate c;
        Monster* tp = wand_find_target(&c.y, &c.x, dir->y, dir->x);
        if (tp != nullptr) {
          tp->set_invisible();
        } else {
          Game::io->message("You did not hit anything");
        }
      } break;

    case Wand::Polymorph:
      {
        Coordinate c;
        Monster* tp = wand_find_target(&c.y, &c.x, dir->y, dir->x);
        if (tp != nullptr)
          wand_spell_polymorph(*tp);
        else
          Game::io->message("You did not hit anything");
      } break;

    case Wand::Cancellation: {
        Coordinate c;
        Monster* tp = wand_find_target(&c.y, &c.x, dir->y, dir->x);
        if (tp != nullptr) {
          wand_spell_cancel(*tp);
        } else {
          Game::io->message("You did not hit anything");
        }
      } break;

    case Wand::TeleportAway: {
      Wand::set_known(subtype);
      player->teleport(nullptr);
    } break;

    case Wand::TeleportTo: {
        Wand::set_known(subtype);
        int x;
        int y;
        Coordinate delta = *dir;
        Monster* tp = wand_find_target(&y, &x, delta.y, delta.x);
        if (tp != nullptr)
        {
          Coordinate new_pos;
          new_pos.y = y - delta.y;
          new_pos.x = x - delta.x;

          tp->set_target(&player->get_position());
          tp->set_chasing();

          player->teleport(&new_pos);
        }
        else
          Game::io->message("You did not hit anything");
      } break;

    case Wand::MagicMissile: {
      Wand::set_known(subtype);
      wand_spell_magic_missile(dir->y, dir->x);
    } break;

    case Wand::HasteMonster: {
        Coordinate c;
        Monster* tp = wand_find_target(&c.y, &c.x, dir->y, dir->x);
        if (tp != nullptr) {
          Wand::set_known(subtype);
          tp->increase_speed();
          monster_start_running(&c);
          Game::io->message(tp->get_name() + " became faster");

        } else {
          Game::io->message("You did not hit anything");
        }
      } break;

    case Wand::SlowMonster: {
        Coordinate c;
        Monster* tp = wand_find_target(&c.y, &c.x, dir->y, dir->x);
        if (tp != nullptr) {
          tp->decrease_speed();
          monster_start_running(&c);
          Game::io->message(tp->get_name() + " became slower");

        } else {
          Game::io->message("You did not hit anything");
        }
      } break;

    case Wand::ElectricBolt: {
      Wand::set_known(subtype);
      Coordinate delta = *dir;
      Coordinate coord = player->get_position();
      magic_bolt(&coord, &delta, "bolt");
    } break;

    case Wand::FireBolt: {
      Wand::set_known(subtype);
      Coordinate coord = player->get_position();
      Coordinate delta = *dir;
      magic_bolt(&coord, &delta, "flame");
    } break;

    case Wand::ColdBolt: {
      Wand::set_known(subtype);
      Coordinate coord = player->get_position();
      Coordinate delta = *dir;
      magic_bolt(&coord, &delta, "ice");
    } break;

    case Wand::NWANDS: error("Unknown type NWANDS");
  }

    wand->modify_charges(-1);
    return true;
}

<commit_msg>Slow wands IDs on hit<commit_after>#include <vector>

#include "weapons.h"
#include "error_handling.h"
#include "magic.h"
#include "monster.h"
#include "player.h"
#include "game.h"
#include "colors.h"
#include "fight.h"
#include "misc.h"
#include "rogue.h"

#include "wand.h"

using namespace std;

// "walk" in the zap direction until we find a target
static Monster* wand_find_target(int* y, int* x, int dy, int dx) {

  *y = player->get_position().y;
  *x = player->get_position().x;

  while (Game::level->can_step(*x, *y)) {
    *y += dy;
    *x += dx;
  }

  return Game::level->get_monster(*x, *y);
}

static void wand_spell_light(void)
{
  room* player_room = Game::level->get_room(player->get_position());
  if (player_room == nullptr || player_room->is_gone) {
    Game::io->message("the corridor glows and then fades");

  } else {
    player_room->is_dark = false;
    Game::io->message("the rooms is lit by a shimmering blue light");
  }
}

// take away 1/2 of hero's hit points, then take it away
// evenly from the monsters in the room (or next to hero
// if he is in a passage)
static void
wand_spell_drain_health(void) {

  // Add nearby monsters to a list
  vector<Monster*> drainee;

  for (Monster* monster : Game::level->monsters) {
    if (player->can_see(*monster)) {
      drainee.push_back(monster);
    }
  }

  // No monster found -> return
  if (drainee.empty()) {
    Game::io->message("you have a tingling feeling");
    return;
  }

  int damage = player->get_health() / 2;
  player->take_damage(damage);
  Game::io->message("You feel an intense pain");

  // Now zot all of the monsters
  // Must use manual loop here, since monsters can be deleted
  auto it = drainee.begin();
  while (it != drainee.end()) {
    Monster* monster = *it++;
    monster->take_damage(damage);

    if (monster->get_health() < 0) {
      monster_on_death(&monster, player->can_see(*monster));

    } else {
      monster_start_running(&monster->get_position());
      Game::io->message(monster->get_name() + " screams in pain");
    }
  }
}

static void
wand_spell_polymorph(Monster& target)
{
  monster_polymorph(&target);
  if (player->can_see(*&target)) {
    Wand::set_known(Wand::Polymorph);
  }
}

static void
wand_spell_cancel(Monster& target)
{
  target.set_cancelled();
  target.set_not_invisible();
  target.remove_confusing_attack();

  target.set_disguise(target.get_look());
}

static void
wand_spell_magic_missile(int dy, int dx)
{
  class Weapon bolt(Weapon::Dagger);
  bolt.o_type    = '*';
  bolt.set_hit_plus(100);
  bolt.set_damage_plus(1);
  bolt.set_attack_damage({0, 0});
  bolt.set_throw_damage({1, 4});

  Item* weapon = player->equipped_weapon();
  if (weapon != nullptr) {
    bolt.o_launch = weapon->o_which;
  }

  Game::io->missile_motion(&bolt, dy, dx);

  Monster* target = Game::level->get_monster(bolt.get_position());
  if (target == nullptr) {
    Game::io->message("the missle vanishes with a puff of smoke");

  } else if (monster_save_throw(VS_MAGIC, target)) {
    Game::io->message("the missle missed the " + target->get_name());

  } else {
    fight_against_monster(&bolt.get_position(), &bolt, true);
  }
}

bool
wand_zap(void)
{
  Coordinate const* dir = get_dir();
  if (dir == nullptr) {
    return false;
  }

  Item* obj = player->pack_find_item("zap with", IO::Wand);
  Wand* wand = dynamic_cast<Wand*>(obj);
  if (obj == nullptr)
    return false;

  else if (obj->o_type != IO::Wand || wand == nullptr) {
    Game::io->message("you can't zap with that!");
    return false;

  } else if (wand->get_charges() == 0) {
    Game::io->message("nothing happens");
    return true;
  }

  Wand::Type subtype = static_cast<Wand::Type>(obj->o_which);
  switch (subtype)
  {

    case Wand::Light: {
      Wand::set_known(subtype);
      wand_spell_light();
    } break;

    case Wand::DrainLife: {
      if (player->get_health() > 1) {
        wand_spell_drain_health();

      } else {
        Game::io->message("you are too weak to use it");
        return true;
      }
    } break;

    case Wand::InvisibleOther: {
        Coordinate c;
        Monster* tp = wand_find_target(&c.y, &c.x, dir->y, dir->x);
        if (tp != nullptr) {
          tp->set_invisible();
        } else {
          Game::io->message("You did not hit anything");
        }
      } break;

    case Wand::Polymorph:
      {
        Coordinate c;
        Monster* tp = wand_find_target(&c.y, &c.x, dir->y, dir->x);
        if (tp != nullptr)
          wand_spell_polymorph(*tp);
        else
          Game::io->message("You did not hit anything");
      } break;

    case Wand::Cancellation: {
        Coordinate c;
        Monster* tp = wand_find_target(&c.y, &c.x, dir->y, dir->x);
        if (tp != nullptr) {
          wand_spell_cancel(*tp);
        } else {
          Game::io->message("You did not hit anything");
        }
      } break;

    case Wand::TeleportAway: {
      Wand::set_known(subtype);
      player->teleport(nullptr);
    } break;

    case Wand::TeleportTo: {
        Wand::set_known(subtype);
        int x;
        int y;
        Coordinate delta = *dir;
        Monster* tp = wand_find_target(&y, &x, delta.y, delta.x);
        if (tp != nullptr)
        {
          Coordinate new_pos;
          new_pos.y = y - delta.y;
          new_pos.x = x - delta.x;

          tp->set_target(&player->get_position());
          tp->set_chasing();

          player->teleport(&new_pos);
        }
        else
          Game::io->message("You did not hit anything");
      } break;

    case Wand::MagicMissile: {
      Wand::set_known(subtype);
      wand_spell_magic_missile(dir->y, dir->x);
    } break;

    case Wand::HasteMonster: {
        Coordinate c;
        Monster* tp = wand_find_target(&c.y, &c.x, dir->y, dir->x);
        if (tp != nullptr) {
          Wand::set_known(subtype);
          tp->increase_speed();
          monster_start_running(&c);
          Game::io->message(tp->get_name() + " became faster");

        } else {
          Game::io->message("You did not hit anything");
        }
      } break;

    case Wand::SlowMonster: {
        Coordinate c;
        Monster* tp = wand_find_target(&c.y, &c.x, dir->y, dir->x);
        if (tp != nullptr) {
          Wand::set_known(subtype);
          tp->decrease_speed();
          monster_start_running(&c);
          Game::io->message(tp->get_name() + " became slower");

        } else {
          Game::io->message("You did not hit anything");
        }
      } break;

    case Wand::ElectricBolt: {
      Wand::set_known(subtype);
      Coordinate delta = *dir;
      Coordinate coord = player->get_position();
      magic_bolt(&coord, &delta, "bolt");
    } break;

    case Wand::FireBolt: {
      Wand::set_known(subtype);
      Coordinate coord = player->get_position();
      Coordinate delta = *dir;
      magic_bolt(&coord, &delta, "flame");
    } break;

    case Wand::ColdBolt: {
      Wand::set_known(subtype);
      Coordinate coord = player->get_position();
      Coordinate delta = *dir;
      magic_bolt(&coord, &delta, "ice");
    } break;

    case Wand::NWANDS: error("Unknown type NWANDS");
  }

    wand->modify_charges(-1);
    return true;
}

<|endoftext|>


<commit_before>#include "StdAfx.h"
#include "DngDecoderSlices.h"
/*
    RawSpeed - RAW file decoder.

    Copyright (C) 2009-2014 Klaus Post

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

    http://www.klauspost.com
*/

namespace RawSpeed {

void *DecodeThread(void *_this) {
  DngDecoderThread* me = (DngDecoderThread*)_this;
  DngDecoderSlices* parent = me->parent;
  try {
    parent->decodeSlice(me);
  } catch (...) {
    parent->mRaw->setError("DNGDEcodeThread: Caught exception.");
  }
  return NULL;
}

DngDecoderSlices::DngDecoderSlices(FileMap* file, RawImage img, int _compression) :
    mFile(file), mRaw(img) {
  mFixLjpeg = false;
  compression = _compression;
}

DngDecoderSlices::~DngDecoderSlices(void) {
}

void DngDecoderSlices::addSlice(DngSliceElement slice) {
  slices.push(slice);
}

void DngDecoderSlices::startDecoding() {
#ifdef NO_PTHREAD
  DngDecoderThread t;
  while (!slices.empty()) {
    t.slices.push(slices.front());
    slices.pop();
  }
  t.parent = this;
  DecodeThread(&t);
#else
  // Create threads

  nThreads = getThreadCount();
  int slicesPerThread = ((int)slices.size() + nThreads - 1) / nThreads;
//  decodedSlices = 0;
  pthread_attr_t attr;
  /* Initialize and set thread detached attribute */
  pthread_attr_init(&attr);
  pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);

  for (uint32 i = 0; i < nThreads; i++) {
    DngDecoderThread* t = new DngDecoderThread();
    for (int j = 0; j < slicesPerThread ; j++) {
      if (!slices.empty()) {
        t->slices.push(slices.front());
        slices.pop();
      }
    }
    t->parent = this;
    pthread_create(&t->threadid, &attr, DecodeThread, t);
    threads.push_back(t);
  }
  pthread_attr_destroy(&attr);

  void *status;
  for (uint32 i = 0; i < nThreads; i++) {
    pthread_join(threads[i]->threadid, &status);
    delete(threads[i]);
  }
#endif
}

#if JPEG_LIB_VERSION < 80

#define JPEG_MEMSRC(A,B,C) jpeg_mem_src_int(A,B,C)
/* Read JPEG image from a memory segment */

static void init_source (j_decompress_ptr cinfo) {}
static boolean fill_input_buffer (j_decompress_ptr cinfo)
{
  struct jpeg_source_mgr* src = (struct jpeg_source_mgr*) cinfo->src;
  return (boolean)!!src->bytes_in_buffer;
}
static void skip_input_data (j_decompress_ptr cinfo, long num_bytes)
{
  struct jpeg_source_mgr* src = (struct jpeg_source_mgr*) cinfo->src;

  if (num_bytes > (int)src->bytes_in_buffer)
    ThrowIOE("JPEG Decoder - read out of buffer");
  if (num_bytes > 0) {
    src->next_input_byte += (size_t) num_bytes;
    src->bytes_in_buffer -= (size_t) num_bytes;
  }
}
static void term_source (j_decompress_ptr cinfo) {}
static void jpeg_mem_src_int (j_decompress_ptr cinfo, unsigned char* buffer, long nbytes)
{
  struct jpeg_source_mgr* src;

  if (cinfo->src == NULL) {   /* first time for this JPEG object? */
    cinfo->src = (struct jpeg_source_mgr *)
      (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
      sizeof(struct jpeg_source_mgr));
  }

  src = (struct jpeg_source_mgr*) cinfo->src;
  src->init_source = init_source;
  src->fill_input_buffer = fill_input_buffer;
  src->skip_input_data = skip_input_data;
  src->resync_to_restart = jpeg_resync_to_restart; /* use default method */
  src->term_source = term_source;
  src->bytes_in_buffer = nbytes;
  src->next_input_byte = (JOCTET*)buffer;
}
#else
#define JPEG_MEMSRC(A,B,C) jpeg_mem_src(A,B,C)
#endif

METHODDEF(void)
my_error_throw (j_common_ptr cinfo)
{
  ThrowRDE("JPEG decoder error!");
}

void DngDecoderSlices::decodeSlice(DngDecoderThread* t) {
  if (compression == 7) {
    while (!t->slices.empty()) {
      LJpegPlain l(mFile, mRaw);
      l.mDNGCompatible = mFixLjpeg;
      DngSliceElement e = t->slices.front();
      l.mUseBigtable = e.mUseBigtable;
      t->slices.pop();
      try {
        l.startDecoder(e.byteOffset, e.byteCount, e.offX, e.offY);
      } catch (RawDecoderException &err) {
        mRaw->setError(err.what());
      } catch (IOException &err) {
        mRaw->setError(err.what());
      }
    }
    /* Lossy DNG */
  } else if (compression == 0x884c) {
    /* Each slice is a JPEG image */
    struct jpeg_decompress_struct dinfo;
    struct jpeg_error_mgr jerr;
    while (!t->slices.empty()) {
      DngSliceElement e = t->slices.front();
      t->slices.pop();
      uchar8 *complete_buffer = NULL;
      JSAMPARRAY buffer = (JSAMPARRAY)malloc(sizeof(JSAMPROW));

      try {
        jpeg_create_decompress(&dinfo);
        dinfo.err = jpeg_std_error(&jerr);
        jerr.error_exit = my_error_throw;
        JPEG_MEMSRC(&dinfo, (unsigned char*)mFile->getData(e.byteOffset, e.byteCount), e.byteCount);

        if (JPEG_HEADER_OK != jpeg_read_header(&dinfo, TRUE))
          ThrowRDE("DngDecoderSlices: Unable to read JPEG header");

        jpeg_start_decompress(&dinfo);
        if (dinfo.output_components != (int)mRaw->getCpp())
          ThrowRDE("DngDecoderSlices: Component count doesn't match");
        int row_stride = dinfo.output_width * dinfo.output_components;
        int pic_size = dinfo.output_height * row_stride;
        complete_buffer = (uchar8*)_aligned_malloc(pic_size, 16);
        while (dinfo.output_scanline < dinfo.output_height) {
          buffer[0] = (JSAMPROW)(&complete_buffer[dinfo.output_scanline*row_stride]);
          if (0 == jpeg_read_scanlines(&dinfo, buffer, 1))
            ThrowRDE("DngDecoderSlices: JPEG Error while decompressing image.");
        }
        jpeg_finish_decompress(&dinfo);

        // Now the image is decoded, and we copy the image data
        int copy_w = min(mRaw->dim.x-e.offX, dinfo.output_width);
        int copy_h = min(mRaw->dim.y-e.offY, dinfo.output_height);
        for (int y = 0; y < copy_h; y++) {
          uchar8* src = &complete_buffer[row_stride*y];
          ushort16* dst = (ushort16*)mRaw->getData(e.offX, y+e.offY);
          for (int x = 0; x < copy_w; x++) {
            for (int c=0; c < dinfo.output_components; c++)
              *dst++ = (*src++);
          }
        }
      } catch (RawDecoderException &err) {
        mRaw->setError(err.what());
      } catch (IOException &err) {
        mRaw->setError(err.what());
      }
      free(buffer);
      if (complete_buffer)
        _aligned_free(complete_buffer);
      jpeg_destroy_decompress(&dinfo);
    }
  }
  else
    mRaw->setError("DngDecoderSlices: Unknown compression");
}

int DngDecoderSlices::size() {
  return (int)slices.size();
}

} // namespace RawSpeed
<commit_msg>DngDecodeSlices::DecodeThread(): passthrough exc.what()<commit_after>#include "StdAfx.h"
#include "DngDecoderSlices.h"
/*
    RawSpeed - RAW file decoder.

    Copyright (C) 2009-2014 Klaus Post

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

    http://www.klauspost.com
*/

namespace RawSpeed {

void *DecodeThread(void *_this) {
  DngDecoderThread* me = (DngDecoderThread*)_this;
  DngDecoderSlices* parent = me->parent;
  try {
    parent->decodeSlice(me);
  } catch (const std::exception &exc) {
    parent->mRaw->setError(
        string(string("DNGDEcodeThread: Caught exception: ") +
               string(exc.what()))
            .c_str());
  } catch (...) {
    parent->mRaw->setError("DNGDEcodeThread: Caught unhandled exception.");
  }
  return NULL;
}

DngDecoderSlices::DngDecoderSlices(FileMap* file, RawImage img, int _compression) :
    mFile(file), mRaw(img) {
  mFixLjpeg = false;
  compression = _compression;
}

DngDecoderSlices::~DngDecoderSlices(void) {
}

void DngDecoderSlices::addSlice(DngSliceElement slice) {
  slices.push(slice);
}

void DngDecoderSlices::startDecoding() {
#ifdef NO_PTHREAD
  DngDecoderThread t;
  while (!slices.empty()) {
    t.slices.push(slices.front());
    slices.pop();
  }
  t.parent = this;
  DecodeThread(&t);
#else
  // Create threads

  nThreads = getThreadCount();
  int slicesPerThread = ((int)slices.size() + nThreads - 1) / nThreads;
//  decodedSlices = 0;
  pthread_attr_t attr;
  /* Initialize and set thread detached attribute */
  pthread_attr_init(&attr);
  pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);

  for (uint32 i = 0; i < nThreads; i++) {
    DngDecoderThread* t = new DngDecoderThread();
    for (int j = 0; j < slicesPerThread ; j++) {
      if (!slices.empty()) {
        t->slices.push(slices.front());
        slices.pop();
      }
    }
    t->parent = this;
    pthread_create(&t->threadid, &attr, DecodeThread, t);
    threads.push_back(t);
  }
  pthread_attr_destroy(&attr);

  void *status;
  for (uint32 i = 0; i < nThreads; i++) {
    pthread_join(threads[i]->threadid, &status);
    delete(threads[i]);
  }
#endif
}

#if JPEG_LIB_VERSION < 80

#define JPEG_MEMSRC(A,B,C) jpeg_mem_src_int(A,B,C)
/* Read JPEG image from a memory segment */

static void init_source (j_decompress_ptr cinfo) {}
static boolean fill_input_buffer (j_decompress_ptr cinfo)
{
  struct jpeg_source_mgr* src = (struct jpeg_source_mgr*) cinfo->src;
  return (boolean)!!src->bytes_in_buffer;
}
static void skip_input_data (j_decompress_ptr cinfo, long num_bytes)
{
  struct jpeg_source_mgr* src = (struct jpeg_source_mgr*) cinfo->src;

  if (num_bytes > (int)src->bytes_in_buffer)
    ThrowIOE("JPEG Decoder - read out of buffer");
  if (num_bytes > 0) {
    src->next_input_byte += (size_t) num_bytes;
    src->bytes_in_buffer -= (size_t) num_bytes;
  }
}
static void term_source (j_decompress_ptr cinfo) {}
static void jpeg_mem_src_int (j_decompress_ptr cinfo, unsigned char* buffer, long nbytes)
{
  struct jpeg_source_mgr* src;

  if (cinfo->src == NULL) {   /* first time for this JPEG object? */
    cinfo->src = (struct jpeg_source_mgr *)
      (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
      sizeof(struct jpeg_source_mgr));
  }

  src = (struct jpeg_source_mgr*) cinfo->src;
  src->init_source = init_source;
  src->fill_input_buffer = fill_input_buffer;
  src->skip_input_data = skip_input_data;
  src->resync_to_restart = jpeg_resync_to_restart; /* use default method */
  src->term_source = term_source;
  src->bytes_in_buffer = nbytes;
  src->next_input_byte = (JOCTET*)buffer;
}
#else
#define JPEG_MEMSRC(A,B,C) jpeg_mem_src(A,B,C)
#endif

METHODDEF(void)
my_error_throw (j_common_ptr cinfo)
{
  ThrowRDE("JPEG decoder error!");
}

void DngDecoderSlices::decodeSlice(DngDecoderThread* t) {
  if (compression == 7) {
    while (!t->slices.empty()) {
      LJpegPlain l(mFile, mRaw);
      l.mDNGCompatible = mFixLjpeg;
      DngSliceElement e = t->slices.front();
      l.mUseBigtable = e.mUseBigtable;
      t->slices.pop();
      try {
        l.startDecoder(e.byteOffset, e.byteCount, e.offX, e.offY);
      } catch (RawDecoderException &err) {
        mRaw->setError(err.what());
      } catch (IOException &err) {
        mRaw->setError(err.what());
      }
    }
    /* Lossy DNG */
  } else if (compression == 0x884c) {
    /* Each slice is a JPEG image */
    struct jpeg_decompress_struct dinfo;
    struct jpeg_error_mgr jerr;
    while (!t->slices.empty()) {
      DngSliceElement e = t->slices.front();
      t->slices.pop();
      uchar8 *complete_buffer = NULL;
      JSAMPARRAY buffer = (JSAMPARRAY)malloc(sizeof(JSAMPROW));

      try {
        jpeg_create_decompress(&dinfo);
        dinfo.err = jpeg_std_error(&jerr);
        jerr.error_exit = my_error_throw;
        JPEG_MEMSRC(&dinfo, (unsigned char*)mFile->getData(e.byteOffset, e.byteCount), e.byteCount);

        if (JPEG_HEADER_OK != jpeg_read_header(&dinfo, TRUE))
          ThrowRDE("DngDecoderSlices: Unable to read JPEG header");

        jpeg_start_decompress(&dinfo);
        if (dinfo.output_components != (int)mRaw->getCpp())
          ThrowRDE("DngDecoderSlices: Component count doesn't match");
        int row_stride = dinfo.output_width * dinfo.output_components;
        int pic_size = dinfo.output_height * row_stride;
        complete_buffer = (uchar8*)_aligned_malloc(pic_size, 16);
        while (dinfo.output_scanline < dinfo.output_height) {
          buffer[0] = (JSAMPROW)(&complete_buffer[dinfo.output_scanline*row_stride]);
          if (0 == jpeg_read_scanlines(&dinfo, buffer, 1))
            ThrowRDE("DngDecoderSlices: JPEG Error while decompressing image.");
        }
        jpeg_finish_decompress(&dinfo);

        // Now the image is decoded, and we copy the image data
        int copy_w = min(mRaw->dim.x-e.offX, dinfo.output_width);
        int copy_h = min(mRaw->dim.y-e.offY, dinfo.output_height);
        for (int y = 0; y < copy_h; y++) {
          uchar8* src = &complete_buffer[row_stride*y];
          ushort16* dst = (ushort16*)mRaw->getData(e.offX, y+e.offY);
          for (int x = 0; x < copy_w; x++) {
            for (int c=0; c < dinfo.output_components; c++)
              *dst++ = (*src++);
          }
        }
      } catch (RawDecoderException &err) {
        mRaw->setError(err.what());
      } catch (IOException &err) {
        mRaw->setError(err.what());
      }
      free(buffer);
      if (complete_buffer)
        _aligned_free(complete_buffer);
      jpeg_destroy_decompress(&dinfo);
    }
  }
  else
    mRaw->setError("DngDecoderSlices: Unknown compression");
}

int DngDecoderSlices::size() {
  return (int)slices.size();
}

} // namespace RawSpeed
<|endoftext|>