<commit_before>// Copyright 2017 Global Phasing Ltd.
//
// 3d grid used by CCP4 maps and cell-method search.

#ifndef GEMMI_GRID_HPP_
#define GEMMI_GRID_HPP_

#include <cassert>
#include <functional> // for function
#include <vector>
#include "unitcell.hpp"
#include "symmetry.hpp"
#include "util.hpp"  // for fail

namespace gemmi {

inline int modulo(int a, int n) {
  if (a >= n)
    a %= n;
  else if (a < 0)
    a = (a + 1) % n + n - 1;
  return a;
}

inline bool has_small_factorization(int n) {
  for (int k : {2, 3, 5})
    while (n % k == 0)
      n /= k;
  return n == 1 || n == -1;
}

// For now, for simplicity, the grid covers whole unit cell
// and space group is P1.
template<typename T=float>
struct Grid {
  int nu, nv, nw;
  UnitCell unit_cell;
  bool full_canonical; // grid for the whole unit cell with X,Y,Z order
  const SpaceGroup* space_group = nullptr;
  double spacing[3];

  std::vector<T> data;

  void calculate_spacing() {
    spacing[0] = 1.0 / (nu * unit_cell.ar);
    spacing[1] = 1.0 / (nv * unit_cell.br);
    spacing[2] = 1.0 / (nw * unit_cell.cr);
  }

  void set_size_without_checking(int u, int v, int w) {
    nu = u, nv = v, nw = w;
    data.resize(u * v * w);
    calculate_spacing();
    full_canonical = true;
  }

  void set_size(int u, int v, int w) {
    if (space_group) {
      auto factors = space_group->operations().find_grid_factors();
      if (u % factors[0] != 0 || v % factors[1] != 0 || w % factors[2] != 0)
        fail("Grid not compatible with the space group " + space_group->xhm());
    }
    set_size_without_checking(u, v, w);
  }

  // The resulting spacing can be smaller (if denser=true) or greater than arg.
  void set_size_from_spacing(double approx_spacing, bool denser) {
    const SpaceGroup& sg = space_group ? *space_group : get_spacegroup_p1();
    std::array<int, 3> sg_fac = sg.operations().find_grid_factors();
    int m[3];
    double abc[3] = {1./unit_cell.ar, 1./unit_cell.br, 1./unit_cell.cr};
    for (int i = 0; i != 3; ++i) {
      if (i > 0 && fabs(abc[i] - abc[0]) < 0.1 && sg_fac[i] == sg_fac[0]) {
        m[i] = m[0];
        continue;
      }
      if (i > 1 && fabs(abc[i] - abc[1]) < 0.1 && sg_fac[i] == sg_fac[1]) {
        m[i] = m[1];
        continue;
      }
      int f = std::max(2, sg_fac[i]);
      int n;
      if (denser) {
        n = int(std::ceil(abc[i] / (approx_spacing * f)));
        while (!has_small_factorization(n))
          ++n;
      } else {
        n = int(std::floor(abc[i] / (approx_spacing * f)));
        if (n > 1)
          while (!has_small_factorization(n))
            --n;
        else
          n = 1;
      }
      m[i] = n * f;
    }
    set_size_without_checking(m[0], m[1], m[2]);
  }

  void set_unit_cell(double a, double b, double c,
                     double alpha, double beta, double gamma) {
    unit_cell.set(a, b, c, alpha, beta, gamma);
    calculate_spacing();
  }

  void set_unit_cell(const UnitCell& cell) {
    unit_cell = cell;
    calculate_spacing();
  }

  // Quick but unsafe. assumes (for efficiency) that 0 <= u < nu, etc.
  int index_q(int u, int v, int w) const { return w * nu * nv + v * nu + u; }

  // Assumes (for efficiency) that -nu <= u < 2*nu, etc.
  int index_n(int u, int v, int w) const {
    if (u >= nu) u -= nu; else if (u < 0) u += nu;
    if (v >= nv) v -= nv; else if (v < 0) v += nv;
    if (w >= nw) w -= nw; else if (w < 0) w += nw;
    return index_q(u, v, w);
  }

  // Safe but slower.
  int index_s(int u, int v, int w) const {
    return index_q(modulo(u, nu), modulo(v, nv), modulo(w, nw));
  }

  T get_value_q(int u, int v, int w) const { return data[index_q(u, v, w)]; }

  // _s stands for safe
  T get_value_s(int u, int v, int w) const { return data[index_s(u, v, w)]; }

  void set_value_s(int u, int v, int w, T x) { data[index_s(u, v, w)] = x; }

  void fill(T value) { std::fill(data.begin(), data.end(), value); }

  void set_points_around(const Position& ctr, double radius, T value) {
    int du = (int) std::ceil(radius / spacing[0]);
    int dv = (int) std::ceil(radius / spacing[1]);
    int dw = (int) std::ceil(radius / spacing[2]);
    if (du > nu || dv > nv || dw > nw)
      fail("Masking radius bigger than the unit cell?");
    Fractional fctr = unit_cell.fractionalize(ctr).wrap_to_unit();
    int u0 = iround(fctr.x * nu);
    int v0 = iround(fctr.y * nv);
    int w0 = iround(fctr.z * nw);
    for (int w = w0-dw; w <= w0+dw; ++w)
      for (int v = v0-dv; v <= v0+dv; ++v)
        for (int u = u0-du; u <= u0+du; ++u) {
          Fractional fdelta{fctr.x - u * (1.0 / nu),
                            fctr.y - v * (1.0 / nv),
                            fctr.z - w * (1.0 / nw)};
          fdelta.move_toward_zero_by_one();
          Position d = unit_cell.orthogonalize(fdelta);
          if (d.x*d.x + d.y*d.y + d.z*d.z < radius*radius) {
            data[index_n(u, v, w)] = value;
          }
        }
  }

  void mask_atom(double x, double y, double z, double radius) {
    set_points_around(Position(x, y, z), radius, 1);
  }

  void make_zeros_and_ones(double threshold) {
    for (auto& d : data)
      d = d > threshold ? 1 : 0;
  }

  // Use provided function to reduce values of all symmetry mates of each
  // grid points, then assign the result to all the points.
  void symmetrize(std::function<T(T, T)> func) {
    if (!space_group || space_group->number == 1 || !full_canonical)
      return;
    std::vector<Op> ops = space_group->operations().all_ops_sorted();
    auto id = std::find(ops.begin(), ops.end(), Op::identity());
    if (id != ops.end())
      ops.erase(id);
    for (Op& op : ops) {
      op.tran[0] = op.tran[0] * nu / Op::TDEN;
      op.tran[1] = op.tran[1] * nv / Op::TDEN;
      op.tran[2] = op.tran[2] * nw / Op::TDEN;
    }
    std::vector<int> mates(ops.size(), 0);
    std::vector<bool> visited(data.size(), false);
    int idx = 0;
    for (int w = 0; w != nw; ++w)
      for (int v = 0; v != nv; ++v)
        for (int u = 0; u != nu; ++u, ++idx) {
          assert(idx == index_q(u, v, w));
          if (visited[idx])
            continue;
          for (size_t k = 0; k < ops.size(); ++k) {
            int tu = u, tv = v, tw = w;
            ops[k].apply_in_place_mult(tu, tv, tw, 1);
            mates[k] = index_n(tu, tv, tw);
          }
          T value = data[idx];
          for (int k : mates) {
            assert(!visited[k]);
            value = func(value, data[k]);
          }
          data[idx] = value;
          visited[idx] = true;
          for (int k : mates) {
            data[k] = value;
            visited[k] = true;
          }
        }
    assert(idx == (int) data.size());
  }

  // two most common symmetrize functions
  void symmetrize_min() { symmetrize([](T a, T b) { return a < b ? a : b; }); }
  void symmetrize_max() { symmetrize([](T a, T b) { return a > b ? a : b; }); }
};

} // namespace gemmi
#endif
// vim:sw=2:ts=2:et
<commit_msg>avoid one more Intel compiler warning<commit_after>// Copyright 2017 Global Phasing Ltd.
//
// 3d grid used by CCP4 maps and cell-method search.

#ifndef GEMMI_GRID_HPP_
#define GEMMI_GRID_HPP_

#include <cassert>
#include <functional> // for function
#include <vector>
#include "unitcell.hpp"
#include "symmetry.hpp"
#include "util.hpp"  // for fail

namespace gemmi {

inline int modulo(int a, int n) {
  if (a >= n)
    a %= n;
  else if (a < 0)
    a = (a + 1) % n + n - 1;
  return a;
}

inline bool has_small_factorization(int n) {
  for (int k : {2, 3, 5})
    while (n % k == 0)
      n /= k;
  return n == 1 || n == -1;
}

// For now, for simplicity, the grid covers whole unit cell
// and space group is P1.
template<typename T=float>
struct Grid {
  int nu, nv, nw;
  UnitCell unit_cell;
  bool full_canonical; // grid for the whole unit cell with X,Y,Z order
  const SpaceGroup* space_group = nullptr;
  double spacing[3];

  std::vector<T> data;

  void calculate_spacing() {
    spacing[0] = 1.0 / (nu * unit_cell.ar);
    spacing[1] = 1.0 / (nv * unit_cell.br);
    spacing[2] = 1.0 / (nw * unit_cell.cr);
  }

  void set_size_without_checking(int u, int v, int w) {
    nu = u, nv = v, nw = w;
    data.resize(u * v * w);
    calculate_spacing();
    full_canonical = true;
  }

  void set_size(int u, int v, int w) {
    if (space_group) {
      auto factors = space_group->operations().find_grid_factors();
      if (u % factors[0] != 0 || v % factors[1] != 0 || w % factors[2] != 0)
        fail("Grid not compatible with the space group " + space_group->xhm());
    }
    set_size_without_checking(u, v, w);
  }

  // The resulting spacing can be smaller (if denser=true) or greater than arg.
  void set_size_from_spacing(double approx_spacing, bool denser) {
    const SpaceGroup& sg = space_group ? *space_group : get_spacegroup_p1();
    std::array<int, 3> sg_fac = sg.operations().find_grid_factors();
    int m[3] = {0, 0, 0};
    double abc[3] = {1./unit_cell.ar, 1./unit_cell.br, 1./unit_cell.cr};
    for (int i = 0; i != 3; ++i) {
      for (int j = 0; j < i; ++j)
        if (fabs(abc[i] - abc[j]) < 0.1 && sg_fac[i] == sg_fac[j]) {
          m[i] = m[j];
          break;
        }
      if (m[i] == 0) {
        int f = std::max(2, sg_fac[i]);
        int n;
        if (denser) {
          n = int(std::ceil(abc[i] / (approx_spacing * f)));
          while (!has_small_factorization(n))
            ++n;
        } else {
          n = int(std::floor(abc[i] / (approx_spacing * f)));
          if (n > 1)
            while (!has_small_factorization(n))
              --n;
          else
            n = 1;
        }
        m[i] = n * f;
      }
    }
    set_size_without_checking(m[0], m[1], m[2]);
  }

  void set_unit_cell(double a, double b, double c,
                     double alpha, double beta, double gamma) {
    unit_cell.set(a, b, c, alpha, beta, gamma);
    calculate_spacing();
  }

  void set_unit_cell(const UnitCell& cell) {
    unit_cell = cell;
    calculate_spacing();
  }

  // Quick but unsafe. assumes (for efficiency) that 0 <= u < nu, etc.
  int index_q(int u, int v, int w) const { return w * nu * nv + v * nu + u; }

  // Assumes (for efficiency) that -nu <= u < 2*nu, etc.
  int index_n(int u, int v, int w) const {
    if (u >= nu) u -= nu; else if (u < 0) u += nu;
    if (v >= nv) v -= nv; else if (v < 0) v += nv;
    if (w >= nw) w -= nw; else if (w < 0) w += nw;
    return index_q(u, v, w);
  }

  // Safe but slower.
  int index_s(int u, int v, int w) const {
    return index_q(modulo(u, nu), modulo(v, nv), modulo(w, nw));
  }

  T get_value_q(int u, int v, int w) const { return data[index_q(u, v, w)]; }

  // _s stands for safe
  T get_value_s(int u, int v, int w) const { return data[index_s(u, v, w)]; }

  void set_value_s(int u, int v, int w, T x) { data[index_s(u, v, w)] = x; }

  void fill(T value) { std::fill(data.begin(), data.end(), value); }

  void set_points_around(const Position& ctr, double radius, T value) {
    int du = (int) std::ceil(radius / spacing[0]);
    int dv = (int) std::ceil(radius / spacing[1]);
    int dw = (int) std::ceil(radius / spacing[2]);
    if (du > nu || dv > nv || dw > nw)
      fail("Masking radius bigger than the unit cell?");
    Fractional fctr = unit_cell.fractionalize(ctr).wrap_to_unit();
    int u0 = iround(fctr.x * nu);
    int v0 = iround(fctr.y * nv);
    int w0 = iround(fctr.z * nw);
    for (int w = w0-dw; w <= w0+dw; ++w)
      for (int v = v0-dv; v <= v0+dv; ++v)
        for (int u = u0-du; u <= u0+du; ++u) {
          Fractional fdelta{fctr.x - u * (1.0 / nu),
                            fctr.y - v * (1.0 / nv),
                            fctr.z - w * (1.0 / nw)};
          fdelta.move_toward_zero_by_one();
          Position d = unit_cell.orthogonalize(fdelta);
          if (d.x*d.x + d.y*d.y + d.z*d.z < radius*radius) {
            data[index_n(u, v, w)] = value;
          }
        }
  }

  void mask_atom(double x, double y, double z, double radius) {
    set_points_around(Position(x, y, z), radius, 1);
  }

  void make_zeros_and_ones(double threshold) {
    for (auto& d : data)
      d = d > threshold ? 1 : 0;
  }

  // Use provided function to reduce values of all symmetry mates of each
  // grid points, then assign the result to all the points.
  void symmetrize(std::function<T(T, T)> func) {
    if (!space_group || space_group->number == 1 || !full_canonical)
      return;
    std::vector<Op> ops = space_group->operations().all_ops_sorted();
    auto id = std::find(ops.begin(), ops.end(), Op::identity());
    if (id != ops.end())
      ops.erase(id);
    for (Op& op : ops) {
      op.tran[0] = op.tran[0] * nu / Op::TDEN;
      op.tran[1] = op.tran[1] * nv / Op::TDEN;
      op.tran[2] = op.tran[2] * nw / Op::TDEN;
    }
    std::vector<int> mates(ops.size(), 0);
    std::vector<bool> visited(data.size(), false);
    int idx = 0;
    for (int w = 0; w != nw; ++w)
      for (int v = 0; v != nv; ++v)
        for (int u = 0; u != nu; ++u, ++idx) {
          assert(idx == index_q(u, v, w));
          if (visited[idx])
            continue;
          for (size_t k = 0; k < ops.size(); ++k) {
            int tu = u, tv = v, tw = w;
            ops[k].apply_in_place_mult(tu, tv, tw, 1);
            mates[k] = index_n(tu, tv, tw);
          }
          T value = data[idx];
          for (int k : mates) {
            assert(!visited[k]);
            value = func(value, data[k]);
          }
          data[idx] = value;
          visited[idx] = true;
          for (int k : mates) {
            data[k] = value;
            visited[k] = true;
          }
        }
    assert(idx == (int) data.size());
  }

  // two most common symmetrize functions
  void symmetrize_min() { symmetrize([](T a, T b) { return a < b ? a : b; }); }
  void symmetrize_max() { symmetrize([](T a, T b) { return a > b ? a : b; }); }
};

} // namespace gemmi
#endif
// vim:sw=2:ts=2:et
<|endoftext|>


<commit_before>#ifndef __NODE_MAPNIK_FONTS_H__
#define __NODE_MAPNIK_FONTS_H__

// v8
#include <v8.h>

// node
#include <node.h>

// mapnik
#include <mapnik/font_engine_freetype.hpp>

// stl
#include <vector>

#include "utils.hpp"

using namespace v8;
using namespace node;

namespace node_mapnik {

static inline Handle<Value> register_fonts(const Arguments& args)
{
    HandleScope scope;

    try
    {
        if (!args.Length() >= 1 || !args[0]->IsString())
            return ThrowException(Exception::TypeError(
                                      String::New("first argument must be a path to a directory of fonts")));

        bool found = false;

        std::vector<std::string> const names_before = mapnik::freetype_engine::face_names();

        // option hash
        if (args.Length() == 2){
            if (!args[1]->IsObject())
                return ThrowException(Exception::TypeError(
                                          String::New("second argument is optional, but if provided must be an object, eg. { recurse:Boolean }")));

            Local<Object> options = args[1]->ToObject();
            if (options->Has(String::New("recurse")))
            {
                Local<Value> recurse_opt = options->Get(String::New("recurse"));
                if (!recurse_opt->IsBoolean())
                    return ThrowException(Exception::TypeError(
                                              String::New("'recurse' must be a Boolean")));

                bool recurse = recurse_opt->BooleanValue();
                std::string const& path = TOSTR(args[0]);
                found = mapnik::freetype_engine::register_fonts(path,recurse);
            }
        }
        else
        {
            std::string const& path = TOSTR(args[0]);
            found = mapnik::freetype_engine::register_fonts(path);
        }

        std::vector<std::string> const& names_after = mapnik::freetype_engine::face_names();
        if (names_after.size() == names_before.size())
            found = false;

        return scope.Close(Boolean::New(found));
    }
    catch (std::exception const& ex)
    {
        return ThrowException(Exception::Error(
                                  String::New(ex.what())));
    }
}

static inline Handle<Value> available_font_faces(const Arguments& args)
{
    HandleScope scope;
    std::vector<std::string> const& names = mapnik::freetype_engine::face_names();
    Local<Array> a = Array::New(names.size());
    for (unsigned i = 0; i < names.size(); ++i)
    {
        a->Set(i, String::New(names[i].c_str()));
    }
    return scope.Close(a);
}

static inline Handle<Value> available_font_files(const Arguments& args)
{
    HandleScope scope;
    std::map<std::string,std::pair<int,std::string> > const& mapping = mapnik::freetype_engine::get_mapping();
    Local<Object> obj = Object::New();
    std::map<std::string,std::pair<int,std::string> >::const_iterator itr;
    for (itr = mapping.begin();itr!=mapping.end();++itr)
    {
        obj->Set(String::NewSymbol(itr->first.c_str()),String::New(itr->second.second.c_str()));
    }
    return scope.Close(obj);
}

}

#endif // __NODE_MAPNIK_FONTS_H__
<commit_msg>avoid possibility of taking reference to temporary<commit_after>#ifndef __NODE_MAPNIK_FONTS_H__
#define __NODE_MAPNIK_FONTS_H__

// v8
#include <v8.h>

// node
#include <node.h>

// mapnik
#include <mapnik/font_engine_freetype.hpp>

// stl
#include <vector>

#include "utils.hpp"

using namespace v8;
using namespace node;

namespace node_mapnik {

static inline Handle<Value> register_fonts(const Arguments& args)
{
    HandleScope scope;

    try
    {
        if (!args.Length() >= 1 || !args[0]->IsString())
            return ThrowException(Exception::TypeError(
                                      String::New("first argument must be a path to a directory of fonts")));

        bool found = false;

        std::vector<std::string> const names_before = mapnik::freetype_engine::face_names();

        // option hash
        if (args.Length() == 2){
            if (!args[1]->IsObject())
                return ThrowException(Exception::TypeError(
                                          String::New("second argument is optional, but if provided must be an object, eg. { recurse:Boolean }")));

            Local<Object> options = args[1]->ToObject();
            if (options->Has(String::New("recurse")))
            {
                Local<Value> recurse_opt = options->Get(String::New("recurse"));
                if (!recurse_opt->IsBoolean())
                    return ThrowException(Exception::TypeError(
                                              String::New("'recurse' must be a Boolean")));

                bool recurse = recurse_opt->BooleanValue();
                std::string path = TOSTR(args[0]);
                found = mapnik::freetype_engine::register_fonts(path,recurse);
            }
        }
        else
        {
            std::string path = TOSTR(args[0]);
            found = mapnik::freetype_engine::register_fonts(path);
        }

        std::vector<std::string> const& names_after = mapnik::freetype_engine::face_names();
        if (names_after.size() == names_before.size())
            found = false;

        return scope.Close(Boolean::New(found));
    }
    catch (std::exception const& ex)
    {
        return ThrowException(Exception::Error(
                                  String::New(ex.what())));
    }
}

static inline Handle<Value> available_font_faces(const Arguments& args)
{
    HandleScope scope;
    std::vector<std::string> const& names = mapnik::freetype_engine::face_names();
    Local<Array> a = Array::New(names.size());
    for (unsigned i = 0; i < names.size(); ++i)
    {
        a->Set(i, String::New(names[i].c_str()));
    }
    return scope.Close(a);
}

static inline Handle<Value> available_font_files(const Arguments& args)
{
    HandleScope scope;
    std::map<std::string,std::pair<int,std::string> > const& mapping = mapnik::freetype_engine::get_mapping();
    Local<Object> obj = Object::New();
    std::map<std::string,std::pair<int,std::string> >::const_iterator itr;
    for (itr = mapping.begin();itr!=mapping.end();++itr)
    {
        obj->Set(String::NewSymbol(itr->first.c_str()),String::New(itr->second.second.c_str()));
    }
    return scope.Close(obj);
}

}

#endif // __NODE_MAPNIK_FONTS_H__
<|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 1999-2000 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xerces" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache\@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation, and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com .  For more information
 * on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

/**
 * $Log$
 * Revision 1.3  2000/02/17 22:32:45  aruna1
 * Masking changes made due to swap of 16bit to 32 bit
 *
 * Revision 1.2  2000/02/06 07:48:01  rahulj
 * Year 2K copyright swat.
 *
 * Revision 1.1.1.1  1999/11/09 01:04:08  twl
 * Initial checkin
 *
 * Revision 1.3  1999/11/08 20:45:05  rahul
 * Swat for adding in Product name and CVS comment log variable.
 *
 */

#if !defined(BITOPS_HPP)
#define BITOPS_HPP

#include <util/XML4CDefs.hpp>

class XMLUTIL_EXPORT BitOps
{
public:
    // -----------------------------------------------------------------------
    //  Public static methods
    // -----------------------------------------------------------------------
    static inline XMLCh swapBytes(const XMLUInt16 toSwap)
    {
        return XMLCh(((toSwap >> 8) | (toSwap << 8)) & 0xFFFF);
    }

    static inline unsigned int swapBytes(const XMLUInt32 toSwap)
    {
        return
        (
            (toSwap >> 24)
            | (toSwap << 24)
            | ((toSwap & 0xFF00) << 8)
            | ((toSwap & 0xFF0000) >> 8)
        );
    }

private :
    // -----------------------------------------------------------------------
    //  Unimplemented constructors and operators
    // -----------------------------------------------------------------------
    BitOps();
    BitOps(const BitOps&);
    void operator=(const BitOps);
};

#endif
<commit_msg>Added comment on mask<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 1999-2000 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xerces" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache\@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation, and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com .  For more information
 * on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

/**
 * $Log$
 * Revision 1.4  2000/02/17 22:49:17  aruna1
 * Added comment on mask
 *
 * Revision 1.3  2000/02/17 22:32:45  aruna1
 * Masking changes made due to swap of 16bit to 32 bit
 *
 * Revision 1.2  2000/02/06 07:48:01  rahulj
 * Year 2K copyright swat.
 *
 * Revision 1.1.1.1  1999/11/09 01:04:08  twl
 * Initial checkin
 *
 * Revision 1.3  1999/11/08 20:45:05  rahul
 * Swat for adding in Product name and CVS comment log variable.
 *
 */

#if !defined(BITOPS_HPP)
#define BITOPS_HPP

#include <util/XML4CDefs.hpp>

class XMLUTIL_EXPORT BitOps
{
public:
    // -----------------------------------------------------------------------
    //  Public static methods
    // -----------------------------------------------------------------------
    static inline XMLCh swapBytes(const XMLUInt16 toSwap)
    {
        //The mask is required to overcome a compiler error on solaris
        return XMLCh(((toSwap >> 8) | (toSwap << 8)) & 0xFFFF);
    }

    static inline unsigned int swapBytes(const XMLUInt32 toSwap)
    {
        return
        (
            (toSwap >> 24)
            | (toSwap << 24)
            | ((toSwap & 0xFF00) << 8)
            | ((toSwap & 0xFF0000) >> 8)
        );
    }

private :
    // -----------------------------------------------------------------------
    //  Unimplemented constructors and operators
    // -----------------------------------------------------------------------
    BitOps();
    BitOps(const BitOps&);
    void operator=(const BitOps);
};

#endif
<|endoftext|>


<commit_before>/**
 * @file		sysmanager.cpp
 * @brief		COSSB system manager
 * @author		Byunghun Hwang<bhhwang@nsynapse.com>
 * @date 		2015. 7. 29
 * @details
 */

#include "manager.hpp"
#include "logger.hpp"

namespace cossb {
namespace manager {

system_manager::system_manager()
{
	cossb_log->info("test");
}

system_manager::~system_manager()
{
	cossb_component_manager->destroy();
	cossb_log->destroy();
}

bool system_manager::setup(base::config* config)
{
	//1. load dependent components
	for(auto dep:*config->get_dependency()) {
		if(dep->type==base::dependencyType::COMPONENT)
			cossb_component_manager->install(dep->name.c_str());
	}

	return true;
}

bool system_manager::is_setup() const
{
	return initialized;
}

} /* namespace manager */
} /* namespace cossb */
<commit_msg>remove cossb_log destroy function<commit_after>/**
 * @file		sysmanager.cpp
 * @brief		COSSB system manager
 * @author		Byunghun Hwang<bhhwang@nsynapse.com>
 * @date 		2015. 7. 29
 * @details
 */

#include "manager.hpp"
#include "logger.hpp"

namespace cossb {
namespace manager {

system_manager::system_manager()
{

}

system_manager::~system_manager()
{
	cossb_component_manager->destroy();
}

bool system_manager::setup(base::config* config)
{
	//1. load dependent components
	for(auto dep:*config->get_dependency()) {
		if(dep->type==base::dependencyType::COMPONENT)
			cossb_component_manager->install(dep->name.c_str());
	}

	return true;
}

bool system_manager::is_setup() const
{
	return initialized;
}

} /* namespace manager */
} /* namespace cossb */
<|endoftext|>


<commit_before>/**
 * @file		sysmanager.cpp
 * @brief		COSSB system manager
 * @author		Byunghun Hwang<bhhwang@nsynapse.com>
 * @date 		2015. 7. 29
 * @details
 */

#include "manager.hpp"
#include "logger.hpp"
#include "interface/ilog.hpp"
#include "base/libadopter.hpp"

namespace cossb {
namespace manager {

system_manager::system_manager()
{

}

system_manager::~system_manager()
{
	cossb_component_manager->destroy();
	cossb_log->destroy();

	if(!_srv_container.empty()) {
		for(auto srv:_srv_container)
			delete srv.second;
		_srv_container.clear();
	}

	if(_log_adopter)	delete _log_adopter;
	if(_mdns_adopter)	delete _mdns_adopter;
}

bool system_manager::setup(base::configreader* config)
{
	//1. load log library
	for(auto dep:*config->get_library()) {
		if(!dep->use.compare("log") && !dep->sofile.empty()) {
			_log_adopter = new base::libadopter<interface::ilog>(dep->sofile.c_str());
			cossb_log->adopt(_log_adopter->get_lib());
		}

		/*if(!dep->use.compare("mdns") && !dep->sofile.empty()) {
			_mdns_adopter = new base::libadopter<interface::isimpleservice>(dep->sofile.c_str());
		}*/

		_srv_container.insert(std::pair<string, base::libadopter<interface::isimpleservice>*>("mdns", new base::libadopter<interface::isimpleservice>(dep->sofile.c_str())));
	}

	//2. load dependent components
	for(auto dep:*config->get_dependency()) {
		if(dep->type==base::dependencyType::COMPONENT)
			cossb_component_manager->install(dep->name.c_str());
	}

	return true;
}

bool system_manager::is_setup() const
{
	return initialized;
}

} /* namespace manager */
} /* namespace cossb */
<commit_msg>add load service library<commit_after>/**
 * @file		sysmanager.cpp
 * @brief		COSSB system manager
 * @author		Byunghun Hwang<bhhwang@nsynapse.com>
 * @date 		2015. 7. 29
 * @details
 */

#include "manager.hpp"
#include "logger.hpp"
#include "interface/ilog.hpp"
#include "base/libadopter.hpp"

namespace cossb {
namespace manager {

system_manager::system_manager()
{

}

system_manager::~system_manager()
{
	cossb_component_manager->destroy();
	cossb_log->destroy();

	if(!_srv_container.empty()) {
		for(auto srv:_srv_container)
			delete srv.second;
		_srv_container.clear();
	}

	if(_log_adopter)	delete _log_adopter;
	if(_mdns_adopter)	delete _mdns_adopter;
}

bool system_manager::setup(base::configreader* config)
{
	//1. load log library
	for(auto dep:*config->get_library()) {
		if(!dep->use.compare("log") && !dep->sofile.empty()) {
			_log_adopter = new base::libadopter<interface::ilog>(dep->sofile.c_str());
			cossb_log->adopt(_log_adopter->get_lib());
			cossb_log->log(log::loglevel::INFO, fmt::format("Load library : {}", dep->sofile).c_str());
		}
	}

	//2. load service library
	for(auto dep:*config->get_service()) {
		if(!dep.first.empty() && !dep.second.empty()) {
			_srv_container.insert(std::pair<string, base::libadopter<interface::isimpleservice>*>(dep.first, new base::libadopter<interface::isimpleservice>(dep.second.c_str())));
			cossb_log->log(log::loglevel::INFO, fmt::format("Load service : {}", dep.second).c_str());
		}
	}

	//3. load dependent components
	for(auto dep:*config->get_dependency()) {
		if(dep->type==base::dependencyType::COMPONENT)
			cossb_component_manager->install(dep->name.c_str());
	}

	return true;
}

bool system_manager::is_setup() const
{
	return initialized;
}

} /* namespace manager */
} /* namespace cossb */
<|endoftext|>


<commit_before><commit_msg>fdo#39468 translate more German comments, etc.<commit_after><|endoftext|>


<commit_before>#include "string.hpp"

#include <cstdarg>
#include <array>

#include "debug.hpp"

using namespace utki;

std::string utki::make_string_va_list(const char* format, va_list args){
	std::array<char, 0x400> buf; // first guess is that the resulting string will take less than 1k

	std::string ret;

	auto buf_ptr = &*buf.begin();
	auto buf_size = buf.size();

	for(unsigned i = 0;; ++i){
		int size = vsnprintf(
				buf_ptr,
				buf_size,
				format,
				args
			);

		if(size < 0){
			throw std::logic_error("snprintf() failed");
		}

		if(decltype(buf_size)(size) >= buf_size){
			// resulting string takes more than we have first guessed, allocate enough memory and try again
			ret.resize(size);

			buf_ptr = &*ret.begin();
			buf_size = ret.size() + 1; // NOTE: C++11 guarantees that std::string's internal buffeer has 1 extra byte for null nerminator.
		}else{
			ret = std::string(buf_ptr, size);
			break;
		}

		ASSERT(i < 1)
	}

    return ret;
}

std::string utki::make_string(const char* format, ...){
	va_list args;
	va_start(args, format);
	auto ret = make_string_va_list(format, args);
	va_end(args);
	return ret;
}
<commit_msg>copy va_list<commit_after>#include "string.hpp"

#include <cstdarg>
#include <array>

#include "debug.hpp"

using namespace utki;

std::string utki::make_string_va_list(const char* format, va_list args){
	std::array<char, 0x400> buf; // first guess is that the resulting string will take less than 1k

	std::string ret;

	auto buf_ptr = &*buf.begin();
	auto buf_size = buf.size();

	va_list cur_args;
	va_copy(cur_args, args);

	for(unsigned i = 0;; ++i){
		int size = vsnprintf(
				buf_ptr,
				buf_size,
				format,
				cur_args
			);

		if(size < 0){
			throw std::logic_error("snprintf() failed");
		}

		if(decltype(buf_size)(size) >= buf_size){
			// resulting string takes more than we have first guessed, allocate enough memory and try again
			ret.resize(size);

			buf_ptr = &*ret.begin();
			buf_size = ret.size() + 1; // NOTE: C++11 guarantees that std::string's internal buffeer has 1 extra byte for null nerminator.

			va_copy(cur_args, args);
		}else{
			ret = std::string(buf_ptr, size);
			break;
		}

		ASSERT(i < 1)
	}

    return ret;
}

std::string utki::make_string(const char* format, ...){
	va_list args;
	va_start(args, format);
	auto ret = make_string_va_list(format, args);
	va_end(args);
	return ret;
}
<|endoftext|>


<commit_before>
#include <pthread.h>
#include <iostream>

struct subArys{
  int** ary11;
  int** ary12;
  int** ary21;
  int** ary22;
  int n;
};

struct multArgs{
  int** c;
  int** a;
  int** b;
  int n;

  public:
    multArgs(int** c, int** a, int** b, int n){
      c=c;
      a=a;
      b=b;
      n=n;
    }

};

struct addArgs{
  int**c;
  int**t;
  int n;

  public:
    addArgs(int** c, int** t, int n){
      c=c;
      t=t;
      n=n;
    }
};

void *multMtx(int**, int**, int**, int);
void *addMtx(int**, int**, int);
int** newAry(int);
subArys* split(int**, int);

void testSplit(int);

using namespace std;

int main()
{
  testSplit(4);

    return 0;
}

void *multMtx(void* param){
	  multArgs* par = (multArgs*) param;
	  int ** tt = newAry(par->n); //create empty array
	if(par->n == 1){
	  par->c[0][0] = par->a[0][0] * par->b[0][0];
	  //need to bundle for return here
	}
	else{

	  subArys* a = split(par->a, par->n); //aplit arrays
	  subArys* b = split(par->b, par->n);
	  subArys* c = split(par->c, par->n);
	  subArys* t = split(tt, par->n);
	  //package all params
	  multArgs* param1 = new multArgs(c->ary11, a->ary11, b->ary11, t->n);
	  multArgs* param2 = new multArgs(c->ary12, a->ary11, b->ary12, t->n);
	  multArgs* param3 = new multArgs(c->ary21, a->ary21, b->ary11, t->n);
	  multArgs* param4 = new multArgs(c->ary22, a->ary21, b->ary12, t->n);
	  multArgs* param5 = new multArgs(t->ary11, a->ary12, b->ary22, t->n);
	  multArgs* param6 = new multArgs(t->ary12, a->ary12, b->ary22, t->n);
	  multArgs* param7 = new multArgs(t->ary21, a->ary22, b->ary21, t->n);
	  multArgs* param8 = new multArgs(t->ary22, a->ary22, b->ary22, t->n);
	  pthread_t* m1, m2, m3, m4, m5, m6, m7, m8;
	  pthread_create(m1, NULL, multMtx, (void*) param1);
	  //add and bundle for return here
	}

	delete tt;
	return new void*;
}

void *addMtx(void* param) {
	addArgs* par = (addArgs*) param;
	int ** tt = newAry(par->n);

	if(par->n==1){
	  par->c[0][0]+=par->t[0][0];

	}
	else{
	  subArys* c = split(par->c, par->n);
	  subArys* t = split(tt, par->n);

	  addArgs* param1 = new addArgs(c->ary11, t->ary11, t->n);
	  addArgs* param2 = new addArgs(c->ary21, t->ary21, t->n);
	  addArgs* param3 = new addArgs(c->ary21, t->ary21, t->n);
	  addArgs* param4 = new addArgs(c->ary22, t->ary22, t->n);

	  pthread_t* m1, m2, m3, m4;

	}
	return new void*;
}

int** newAry(int n){
  int** temp = new int*[n]; //outer array for poitners
  for(int i=0;i<n;++i){
   temp[i]=new int[n]; //inner 1d arrays of int*
   for(int j=0;j<n;++j){
     temp[i][j]= 0;
   }
  }
  return temp;
}

subArys* split(int** ary, int n){
 subArys* temp = new subArys;

 temp->ary11 = newAry(n/2); //define all initial vals
 temp->ary12 = newAry(n/2);
 temp->ary21 = newAry(n/2);
 temp->ary22 = newAry(n/2);
 temp->n = n/2;
 int shift=n/2;

 for(int i=0;i<n;++i){ //loop through original and push to correct quad

   if(i<n/2){
     temp->ary11[i]=&ary[i][0];
     temp->ary12[i]=&ary[i][n/shift];
   }
   else{
    temp->ary21[i%shift]=&ary[i][0];
    temp->ary22[i%shift]=&ary[i][n%shift];
   }
 }
   return temp;
}

void testSplit(int n){

  int** ptr=newAry(n);

  cout<<"parent matrix to be split\n";
  for(int i=0;i<n;++i){
    for(int j=0;j<n;++j){
      ptr[i][j]=(i*10)+j+1; //asign values to location pointed to
      cout<<ptr[i][j]<<" ";
    }
    cout<<endl;
  }
  cout<<endl;

  subArys* test=split(ptr, n);
  n=test->n;

  cout<<"top left quad, ary11\n";
  for(int i=0;i<n;++i){
    for(int j=0;j<n;++j){
      ptr[i][j]=(i*10)+j+1;
      cout<<test->ary11[i][j]<<" ";
    }
    cout<<endl;
  }

  cout<<"top right quad, ary12\n";
  for(int i=0;i<n;++i){
    for(int j=0;j<n;++j){
      ptr[i][j]=(i*10)+j+1;
      cout<<test->ary12[i][j]<<" ";
    }
    cout<<endl;
  }

  cout<<"bottom left quad, ary21\n";
  for(int i=0;i<n;++i){
    for(int j=0;j<n;++j){
      ptr[i][j]=(i*10)+j+1;
      cout<<test->ary21[i][j]<<" ";
    }
    cout<<endl;
  }

  cout<<"bottom right quad, ary22\n";
  for(int i=0;i<n;++i){
    for(int j=0;j<n;++j){
      ptr[i][j]=(i*10)+j+1;
      cout<<test->ary22[i][j]<<" ";
    }
    cout<<endl;
  }
}
<commit_msg>addition method complete?<commit_after>
#include <pthread.h>
#include <iostream>

struct subArys{
  int** ary11;
  int** ary12;
  int** ary21;
  int** ary22;
  int n;
};

struct multArgs{
  int** c;
  int** a;
  int** b;
  int n;

  public:
    multArgs(int** c, int** a, int** b, int n){
      c=c;
      a=a;
      b=b;
      n=n;
    }

};

struct addArgs{
  int**c;
  int**t;
  int n;

  public:
    addArgs(int** c, int** t, int n){
      c=c;
      t=t;
      n=n;
    }
};

void *multMtx(int**, int**, int**, int);
void *addMtx(int**, int**, int);
int** newAry(int);
subArys* split(int**, int);

void testSplit(int);

using namespace std;

int main()
{
  testSplit(4);

    return 0;
}

void *multMtx(void* param){
	  multArgs* par = (multArgs*) param;
	  int ** tt = newAry(par->n); //create empty array
	if(par->n == 1){
	  par->c[0][0] = par->a[0][0] * par->b[0][0];
	  //need to bundle for return here
	}
	else{

	  subArys* a = split(par->a, par->n); //aplit arrays
	  subArys* b = split(par->b, par->n);
	  subArys* c = split(par->c, par->n);
	  subArys* t = split(tt, par->n);
	  //package all params
	  multArgs* param1 = new multArgs(c->ary11, a->ary11, b->ary11, t->n);
	  multArgs* param2 = new multArgs(c->ary12, a->ary11, b->ary12, t->n);
	  multArgs* param3 = new multArgs(c->ary21, a->ary21, b->ary11, t->n);
	  multArgs* param4 = new multArgs(c->ary22, a->ary21, b->ary12, t->n);
	  multArgs* param5 = new multArgs(t->ary11, a->ary12, b->ary22, t->n);
	  multArgs* param6 = new multArgs(t->ary12, a->ary12, b->ary22, t->n);
	  multArgs* param7 = new multArgs(t->ary21, a->ary22, b->ary21, t->n);
	  multArgs* param8 = new multArgs(t->ary22, a->ary22, b->ary22, t->n);
	  pthread_t *m1, *m2, *m3, *m4, *m5, *m6, *m7, *m8;
	  pthread_create(m1, NULL, multMtx, (void*) param1);
	  //add and bundle for return here
	}

	delete tt;
	return new void*;
}

void *addMtx(void* param) {
	addArgs* par = (addArgs*) param;
	int ** tt = newAry(par->n);

	if(par->n==1){
	  par->c[0][0]+=par->t[0][0];

	}
	else{
	  subArys* c = split(par->c, par->n);
	  subArys* t = split(tt, par->n);

	  addArgs* param1 = new addArgs(c->ary11, t->ary11, t->n);
	  addArgs* param2 = new addArgs(c->ary21, t->ary21, t->n);
	  addArgs* param3 = new addArgs(c->ary21, t->ary21, t->n);
	  addArgs* param4 = new addArgs(c->ary22, t->ary22, t->n);
	  pthread_t *m1,*m2, *m3, *m4;
	  pthread_t* threads[4]={m1, m2, m3, m4};

	  pthread_create(m1, NULL, addMtx, (void*) param1);
	  pthread_create(m2, NULL, addMtx, (void*) param2);
	  pthread_create(m3, NULL, addMtx, (void*) param3);
	  pthread_create(m4, NULL, addMtx, (void*) param4);

	  //thread syntax is all over the place and looks like a toddler threw up in my code
	  for(int i=0;i<4;++i){
	   pthread_join(*threads[i],NULL);
	  }
	}
	return new void*;
}

int** newAry(int n){
  int** temp = new int*[n]; //outer array for poitners
  for(int i=0;i<n;++i){
   temp[i]=new int[n]; //inner 1d arrays of int*
   for(int j=0;j<n;++j){
     temp[i][j]= 0;
   }
  }
  return temp;
}

subArys* split(int** ary, int n){
 subArys* temp = new subArys;

 temp->ary11 = newAry(n/2); //define all initial vals
 temp->ary12 = newAry(n/2);
 temp->ary21 = newAry(n/2);
 temp->ary22 = newAry(n/2);
 temp->n = n/2;
 int shift=n/2;

 for(int i=0;i<n;++i){ //loop through original and push to correct quad

   if(i<n/2){
     temp->ary11[i]=&ary[i][0];
     temp->ary12[i]=&ary[i][n/shift];
   }
   else{
    temp->ary21[i%shift]=&ary[i][0];
    temp->ary22[i%shift]=&ary[i][n%shift];
   }
 }
   return temp;
}

void testSplit(int n){
  int** ptr=newAry(n);

  cout<<"parent matrix to be split\n";
  for(int i=0;i<n;++i){
    for(int j=0;j<n;++j){
      ptr[i][j]=(i*10)+j+1; //asign values to location pointed to
      cout<<ptr[i][j]<<" ";
    }
    cout<<endl;
  }
  cout<<endl;

  subArys* test=split(ptr, n);
  n=test->n;

  cout<<"top left quad, ary11\n";
  for(int i=0;i<n;++i){
    for(int j=0;j<n;++j){
      ptr[i][j]=(i*10)+j+1;
      cout<<test->ary11[i][j]<<" ";
    }
    cout<<endl;
  }

  cout<<"top right quad, ary12\n";
  for(int i=0;i<n;++i){
    for(int j=0;j<n;++j){
      ptr[i][j]=(i*10)+j+1;
      cout<<test->ary12[i][j]<<" ";
    }
    cout<<endl;
  }

  cout<<"bottom left quad, ary21\n";
  for(int i=0;i<n;++i){
    for(int j=0;j<n;++j){
      ptr[i][j]=(i*10)+j+1;
      cout<<test->ary21[i][j]<<" ";
    }
    cout<<endl;
  }

  cout<<"bottom right quad, ary22\n";
  for(int i=0;i<n;++i){
    for(int j=0;j<n;++j){
      ptr[i][j]=(i*10)+j+1;
      cout<<test->ary22[i][j]<<" ";
    }
    cout<<endl;
  }
}
<|endoftext|>


<commit_before><commit_msg>Make TryDrawPolyLineDirect a public function of OutputDevice<commit_after><|endoftext|>


<commit_before>#include <iostream>
#include <cstdlib>
#include <string>

#include "generator.hpp"

#define EASY 1
#define MEDIUM 2
#define HARD 3

#define EASY_NUM 24
#define MEDIUM_NUM 30
#define HARD_NUM 40

int main() {
	std::cout << " Welcome to C-Doku++ ! An interactive terminal based Sudoku Game" << std::endl;
	std::cout << std::endl;
	std::cout << std::endl;
	std::cout << "Please select a difficulty level. \n 1. Easy \n 2. Medium \n 3. Hard\n\n";
	int difficulty;
	int move_count;
	while(true) {
		std::cin >> difficulty;
		if (difficulty == EASY) {
			std::cout << "\nYou have selected level 1 (Easy)\n" << std::endl;
			move_count = EASY_NUM;
			break;
		} else if (difficulty == MEDIUM) {
			std::cout << "\nYou have selected level 2 (Medium)\n" << std::endl;
			move_count = MEDIUM_NUM;
			break;
		} else if (difficulty == HARD){
			std::cout << "\nYou have selected level 3 (Hard)\n" << std::endl;
			move_count = HARD_NUM;
			break;
		} else {
			std::cout << "\nInvalid Choice. Try Again.\n" << std::endl;
			std::cout << "Please select a difficulty level. \n 1. Easy \n 2. Medium \n 3. Hard\n\n";
		}
	}
	std::cout << "Loading Grid \n\n";

	Grid g = Generator::getGrid(difficulty);
	g.print();
	while (move_count > 0) {
		std::cout << "\nEnter a move \n";
		std::string cmd;
		std::cin >> cmd;
		// Command needs to be parsed and a valid move made if command is valid
		// move_count decremented when valid move is made
		// Valid move is also a move which doesn't break Sudoku invariant
		std::cout << std::endl;
		g.print();
		std::cout << std::endl;
	}
	return 0;
}<commit_msg>Added option to quit the game<commit_after>#include <iostream>
#include <cstdlib>
#include <string>

#include "generator.hpp"

#define EASY 1
#define MEDIUM 2
#define HARD 3

#define EASY_NUM 24
#define MEDIUM_NUM 30
#define HARD_NUM 40

int main() {
	std::cout << " Welcome to C-Doku++ ! An interactive terminal based Sudoku Game" << std::endl;
	std::cout << std::endl;
	std::cout << std::endl;
	std::cout << "Please select a difficulty level. \n 1. Easy \n 2. Medium \n 3. Hard\n\n";
	int difficulty;
	int move_count;
	while(true) {
		std::cin >> difficulty;
		if (difficulty == EASY) {
			std::cout << "\nYou have selected level 1 (Easy)\n" << std::endl;
			move_count = EASY_NUM;
			break;
		} else if (difficulty == MEDIUM) {
			std::cout << "\nYou have selected level 2 (Medium)\n" << std::endl;
			move_count = MEDIUM_NUM;
			break;
		} else if (difficulty == HARD){
			std::cout << "\nYou have selected level 3 (Hard)\n" << std::endl;
			move_count = HARD_NUM;
			break;
		} else {
			std::cout << "\nInvalid Choice. Try Again.\n" << std::endl;
			std::cout << "Please select a difficulty level. \n 1. Easy \n 2. Medium \n 3. Hard\n\n";
		}
	}
	std::cout << "Loading Grid \n\n";

	Grid g = Generator::getGrid(difficulty);
	g.print();
	while (move_count > 0) {
		std::cout << "\nEnter a move (or 'quit' to quit the game) \n";
		std::string cmd;
		std::cin >> cmd;
		// Command needs to be parsed and a valid move made if command is valid
		// move_count decremented when valid move is made
		// Valid move is also a move which doesn't break Sudoku invariant
        if (cmd == "quit") return 0;
		std::cout << std::endl;
		g.print();
		std::cout << std::endl;
	}
	return 0;
}
<|endoftext|>


<commit_before>// Calendar class for KOrganizer
// (c) 1998 Preston Brown
// 	$Id$

#include "config.h"

#include <pwd.h>
#include <sys/types.h>
#include <unistd.h>
#include <netdb.h>
#include <time.h>
#include <stdlib.h>

#include <qclipboard.h>
#include <qdialog.h>
#include <qfile.h>

#include <kapp.h>
#include <kdebug.h>
#include <kstddirs.h>
#include <klocale.h>
#include <kglobal.h>
#include <kiconloader.h>
#include <kmessagebox.h>

#include "vcaldrag.h"
#include "qdatelist.h"
//#include "koprefs.h"
#include "vcalformat.h"
#include "icalformat.h"
#include "koexceptions.h"
#include "calfilter.h"

#include "calendar.h"
#include "calendar.moc"

extern "C" {
  char *parse_holidays(const char *, int year, short force);
  /** \internal */
  struct holiday {
    char            *string;        /* name of holiday, 0=not a holiday */
    unsigned short  dup;            /* reference count */
  };
  extern struct holiday holiday[366];
};

using namespace KCal;

/** \internal */
class AddIncidenceVisitor : public IncidenceVisitor {
  public:
    /** Add incidence to calendar \a calendar. */
    AddIncidenceVisitor(Calendar *calendar) : mCalendar(calendar) {}

    bool visit(Event *e) { mCalendar->addEvent(e); return true; }
    bool visit(Todo *t) { mCalendar->addTodo(t); return true; }

  private:
    Calendar *mCalendar;
};

Calendar::Calendar()
  : QObject()
{
  mDndFormat = new VCalFormat(this);

  mFormat = 0;

  mICalFormat = new ICalFormat(this);

  // Setup default filter, which does nothing
  mFilter = new CalFilter;
  mFilter->setEnabled(false);

  struct passwd *pwent;
  uid_t userId;
  QString tmpStr;

  mDialogsOn = true;

  // initialize random numbers.  This is a hack, and not
  // even that good of one at that.
//  srandom(time(0L));

  // TODO: Fix the user information part.

  // user information...
  userId = getuid();
  pwent = getpwuid(userId);
  tmpStr = i18n("Unknown Name");
//  tmpStr = KOPrefs::instance()->mName;
  if (tmpStr.isEmpty()) {
    if (strlen(pwent->pw_gecos) > 0)
      setOwner(pwent->pw_gecos);
    else
      setOwner(pwent->pw_name);
//      KOPrefs::instance()->mName = getOwner();
  } else {
    setOwner(tmpStr);
  }

  tmpStr = i18n("unknown@nowhere");
//  tmpStr = KOPrefs::instance()->mEmail;
  if (tmpStr.isEmpty()) {
    tmpStr = pwent->pw_name;
    tmpStr += "@";

#ifdef HAVE_GETHOSTNAME
    char cbuf[80];
    if (gethostname(cbuf, 79)) {
      // error getting hostname
      tmpStr += "localhost";
    } else {
      hostent he;
      if (gethostbyname(cbuf)) {
	  he = *gethostbyname(cbuf);
	  tmpStr += he.h_name;
      } else {
	// error getting hostname
	tmpStr += "localhost";
      }
    }
#else
    tmpStr += "localhost";
#endif
    setEmail(tmpStr);
//    KOPrefs::instance()->mEmail = tmpStr;
  } else {
    setEmail(tmpStr);
  }

  readHolidayFileName();

#if 0
  tmpStr = KOPrefs::instance()->mTimeZone;
//  kdDebug() << "Calendar::Calendar(): TimeZone: " << tmpStr << endl;
  int dstSetting = KOPrefs::instance()->mDaylightSavings;
  extern long int timezone;
  struct tm *now;
  time_t curtime;
  curtime = time(0);
  now = localtime(&curtime);
  int hourOff = - ((timezone / 60) / 60);
  if (now->tm_isdst)
    hourOff += 1;
  QString tzStr;
  tzStr.sprintf("%.2d%.2d",
		hourOff,
		abs((timezone / 60) % 60));

  // if no time zone was in the config file, write what we just discovered.
  if (tmpStr.isEmpty()) {
//    KOPrefs::instance()->mTimeZone = tzStr;
  } else {
    tzStr = tmpStr;
  }

  // if daylight savings has changed since last load time, we need
  // to rewrite these settings to the config file.
  if ((now->tm_isdst && !dstSetting) ||
      (!now->tm_isdst && dstSetting)) {
    KOPrefs::instance()->mTimeZone = tzStr;
    KOPrefs::instance()->mDaylightSavings = now->tm_isdst;
  }

  setTimeZone(tzStr);
#endif
//  KOPrefs::instance()->writeConfig();
}

Calendar::~Calendar()
{
  delete mICalFormat;
  delete mDndFormat;
  delete mFormat;
}

ICalFormat *Calendar::iCalFormat()
{
  return mICalFormat;
}

VCalDrag *Calendar::createDrag(Event *selectedEv, QWidget *owner)
{
  return mDndFormat->createDrag(selectedEv,owner);
}

VCalDrag *Calendar::createDragTodo(Todo *selectedEv, QWidget *owner)
{
  return mDndFormat->createDragTodo(selectedEv,owner);
}

Event *Calendar::createDrop(QDropEvent *de)
{
  return mDndFormat->createDrop(de);
}

Todo *Calendar::createDropTodo(QDropEvent *de)
{
  kdDebug() << "Calendar::createDropTodo()" << endl;
  return mDndFormat->createDropTodo(de);
}

void Calendar::cutEvent(Event *selectedEv)
{
  if (copyEvent(selectedEv))
    deleteEvent(selectedEv);
}

bool Calendar::copyEvent(Event *selectedEv)
{
  return mDndFormat->copyEvent(selectedEv);
}

Event *Calendar::pasteEvent(const QDate *newDate,const QTime *newTime)
{
  return mDndFormat->pasteEvent(newDate,newTime);
}

const QString &Calendar::getOwner() const
{
  return mOwner;
}

void Calendar::setOwner(const QString &os)
{
  int i;
  // mOwner = os.ascii(); // to detach it
  mOwner = os; // #### Why? This should be okay?
  i = mOwner.find(',');
  if (i != -1)
    mOwner = mOwner.left(i);
}

void Calendar::setTimeZone(const QString & tz)
{
  bool neg = FALSE;
  int hours, minutes;
  QString tmpStr(tz);

  if (tmpStr.left(1) == "-")
    neg = TRUE;
  if (tmpStr.left(1) == "-" || tmpStr.left(1) == "+")
    tmpStr.remove(0, 1);
  hours = tmpStr.left(2).toInt();
  if (tmpStr.length() > 2)
    minutes = tmpStr.right(2).toInt();
  else
    minutes = 0;
  mTimeZone = (60*hours+minutes);
  if (neg)
    mTimeZone = -mTimeZone;
}

QString Calendar::getTimeZoneStr() const
{
  QString tmpStr;
  int hours = abs(mTimeZone / 60);
  int minutes = abs(mTimeZone % 60);
  bool neg = mTimeZone < 0;

  tmpStr.sprintf("%c%.2d%.2d",
		 (neg ? '-' : '+'),
		 hours, minutes);
  return tmpStr;
}

const QString &Calendar::getEmail()
{
  return mOwnerEmail;
}

void Calendar::setEmail(const QString &e)
{
  mOwnerEmail = e;
}

void Calendar::setTimeZone(int tz)
{
  mTimeZone = tz;
}

int Calendar::getTimeZone() const
{
  return mTimeZone;
}

void Calendar::showDialogs(bool d)
{
  mDialogsOn = d;
}

// don't ever call this unless a kapp exists!
void Calendar::updateConfig()
{
//  kdDebug() << "Calendar::updateConfig()" << endl;

  bool updateFlag = FALSE;

  // TODO: update Organizer in all events
#if 0
  mOwner = KOPrefs::instance()->mName;

  // update events to new organizer (email address)
  // if it has changed...
  QString configEmail = KOPrefs::instance()->mEmail;

  if (mOwnerEmail != configEmail) {
    QString oldEmail = mOwnerEmail;
    //    oldEmail.detach();
    mOwnerEmail = configEmail;
    Event *firstEvent, *currEvent;
    bool atFirst = TRUE;

    firstEvent = last();
    // gotta skip over the first one, which is same as first.
    // I know, bad coding.
    for (currEvent = prev(); currEvent; currEvent = prev()) {
//      kdDebug() << "in Calendar::updateConfig(), currEvent summary: " << currEvent->getSummary() << endl;
      if ((currEvent == firstEvent) && !atFirst) {
	break;
      }
      if (currEvent->getOrganizer() == oldEmail) {
	currEvent->setReadOnly(FALSE);
	currEvent->setOrganizer(mOwnerEmail);
        updateFlag = TRUE;
      }
      atFirst = FALSE;
    }
  }
#endif
  readHolidayFileName();

// TODO: Fix time zone setting
//  setTimeZone(KOPrefs::instance()->mTimeZone.latin1());

  if (updateFlag)
    emit calUpdated((Event *) 0L);
}

QString Calendar::getHolidayForDate(const QDate &qd)
{
  static int lastYear = 0;

//  kdDebug() << "CalendarLocal::getHolidayForDate(): Holiday: " << holidays << endl;

  if (mHolidayfile.isEmpty()) return (QString(""));

  if ((lastYear == 0) || (qd.year() != lastYear)) {
      lastYear = qd.year() - 1900; // silly parse_year takes 2 digit year...
      parse_holidays(QFile::encodeName(mHolidayfile), lastYear, 0);
  }

  if (holiday[qd.dayOfYear()-1].string) {
    QString holidayname = QString::fromLocal8Bit(holiday[qd.dayOfYear()-1].string);
//    kdDebug() << "Holi name: " << holidayname << endl;
    return(holidayname);
  } else {
//    kdDebug() << "No holiday" << endl;
    return(QString(""));
  }
}

void Calendar::readHolidayFileName()
{
  QString holidays(mHoliday);
  if (holidays == "(none)") mHolidayfile = "";
  holidays = holidays.prepend("holiday_");
  mHolidayfile = locate("appdata",holidays);

//  kdDebug() << "holifile: " << mHolidayfile << endl;
}

void Calendar::setFilter(CalFilter *filter)
{
  mFilter = filter;
}

CalFilter *Calendar::filter()
{
  return mFilter;
}

QList<Event> Calendar::getEventsForDate(const QDate &date,bool sorted)
{
  QList<Event> el = eventsForDate(date,sorted);
  mFilter->apply(&el);
  return el;
}

QList<Event> Calendar::getEventsForDate(const QDateTime &qdt)
{
  QList<Event> el = eventsForDate(qdt);
  mFilter->apply(&el);
  return el;
}

QList<Event> Calendar::getEvents(const QDate &start,const QDate &end,
                                    bool inclusive)
{
  QList<Event> el = events(start,end,inclusive);
  mFilter->apply(&el);
  return el;
}

void Calendar::addIncidence(Incidence *i)
{
  AddIncidenceVisitor v(this);

  i->accept(v);
}

QList<Todo> Calendar::getFilteredTodoList()
{
  QList<Todo> tl = getTodoList();
  mFilter->apply(&tl);
  return tl;
}
<commit_msg>Reordered some functions.<commit_after>// Calendar class for KOrganizer
// (c) 1998 Preston Brown
// 	$Id$

#include "config.h"

#include <pwd.h>
#include <sys/types.h>
#include <unistd.h>
#include <netdb.h>
#include <time.h>
#include <stdlib.h>

#include <qclipboard.h>
#include <qdialog.h>
#include <qfile.h>

#include <kapp.h>
#include <kdebug.h>
#include <kstddirs.h>
#include <klocale.h>
#include <kglobal.h>
#include <kiconloader.h>
#include <kmessagebox.h>

#include "vcaldrag.h"
#include "qdatelist.h"
//#include "koprefs.h"
#include "vcalformat.h"
#include "icalformat.h"
#include "koexceptions.h"
#include "calfilter.h"

#include "calendar.h"
#include "calendar.moc"

extern "C" {
  char *parse_holidays(const char *, int year, short force);
  /** \internal */
  struct holiday {
    char            *string;        /* name of holiday, 0=not a holiday */
    unsigned short  dup;            /* reference count */
  };
  extern struct holiday holiday[366];
};

using namespace KCal;

/** \internal */
class AddIncidenceVisitor : public IncidenceVisitor {
  public:
    /** Add incidence to calendar \a calendar. */
    AddIncidenceVisitor(Calendar *calendar) : mCalendar(calendar) {}

    bool visit(Event *e) { mCalendar->addEvent(e); return true; }
    bool visit(Todo *t) { mCalendar->addTodo(t); return true; }

  private:
    Calendar *mCalendar;
};

Calendar::Calendar()
  : QObject()
{
  mDndFormat = new VCalFormat(this);

  mFormat = 0;

  mICalFormat = new ICalFormat(this);

  // Setup default filter, which does nothing
  mFilter = new CalFilter;
  mFilter->setEnabled(false);

  struct passwd *pwent;
  uid_t userId;
  QString tmpStr;

  mDialogsOn = true;

  // initialize random numbers.  This is a hack, and not
  // even that good of one at that.
//  srandom(time(0L));

  // TODO: Fix the user information part.

  // user information...
  userId = getuid();
  pwent = getpwuid(userId);
  tmpStr = i18n("Unknown Name");
//  tmpStr = KOPrefs::instance()->mName;
  if (tmpStr.isEmpty()) {
    if (strlen(pwent->pw_gecos) > 0)
      setOwner(pwent->pw_gecos);
    else
      setOwner(pwent->pw_name);
//      KOPrefs::instance()->mName = getOwner();
  } else {
    setOwner(tmpStr);
  }

  tmpStr = i18n("unknown@nowhere");
//  tmpStr = KOPrefs::instance()->mEmail;
  if (tmpStr.isEmpty()) {
    tmpStr = pwent->pw_name;
    tmpStr += "@";

#ifdef HAVE_GETHOSTNAME
    char cbuf[80];
    if (gethostname(cbuf, 79)) {
      // error getting hostname
      tmpStr += "localhost";
    } else {
      hostent he;
      if (gethostbyname(cbuf)) {
	  he = *gethostbyname(cbuf);
	  tmpStr += he.h_name;
      } else {
	// error getting hostname
	tmpStr += "localhost";
      }
    }
#else
    tmpStr += "localhost";
#endif
    setEmail(tmpStr);
//    KOPrefs::instance()->mEmail = tmpStr;
  } else {
    setEmail(tmpStr);
  }

  readHolidayFileName();

#if 0
  tmpStr = KOPrefs::instance()->mTimeZone;
//  kdDebug() << "Calendar::Calendar(): TimeZone: " << tmpStr << endl;
  int dstSetting = KOPrefs::instance()->mDaylightSavings;
  extern long int timezone;
  struct tm *now;
  time_t curtime;
  curtime = time(0);
  now = localtime(&curtime);
  int hourOff = - ((timezone / 60) / 60);
  if (now->tm_isdst)
    hourOff += 1;
  QString tzStr;
  tzStr.sprintf("%.2d%.2d",
		hourOff,
		abs((timezone / 60) % 60));

  // if no time zone was in the config file, write what we just discovered.
  if (tmpStr.isEmpty()) {
//    KOPrefs::instance()->mTimeZone = tzStr;
  } else {
    tzStr = tmpStr;
  }

  // if daylight savings has changed since last load time, we need
  // to rewrite these settings to the config file.
  if ((now->tm_isdst && !dstSetting) ||
      (!now->tm_isdst && dstSetting)) {
    KOPrefs::instance()->mTimeZone = tzStr;
    KOPrefs::instance()->mDaylightSavings = now->tm_isdst;
  }

  setTimeZone(tzStr);
#endif
//  KOPrefs::instance()->writeConfig();
}

Calendar::~Calendar()
{
  delete mICalFormat;
  delete mDndFormat;
  delete mFormat;
}

ICalFormat *Calendar::iCalFormat()
{
  return mICalFormat;
}

VCalDrag *Calendar::createDrag(Event *selectedEv, QWidget *owner)
{
  return mDndFormat->createDrag(selectedEv,owner);
}

VCalDrag *Calendar::createDragTodo(Todo *selectedEv, QWidget *owner)
{
  return mDndFormat->createDragTodo(selectedEv,owner);
}

Event *Calendar::createDrop(QDropEvent *de)
{
  return mDndFormat->createDrop(de);
}

Todo *Calendar::createDropTodo(QDropEvent *de)
{
  kdDebug() << "Calendar::createDropTodo()" << endl;
  return mDndFormat->createDropTodo(de);
}

void Calendar::cutEvent(Event *selectedEv)
{
  if (copyEvent(selectedEv))
    deleteEvent(selectedEv);
}

bool Calendar::copyEvent(Event *selectedEv)
{
  return mDndFormat->copyEvent(selectedEv);
}

Event *Calendar::pasteEvent(const QDate *newDate,const QTime *newTime)
{
  return mDndFormat->pasteEvent(newDate,newTime);
}

const QString &Calendar::getOwner() const
{
  return mOwner;
}

void Calendar::setOwner(const QString &os)
{
  int i;
  // mOwner = os.ascii(); // to detach it
  mOwner = os; // #### Why? This should be okay?
  i = mOwner.find(',');
  if (i != -1)
    mOwner = mOwner.left(i);
}

void Calendar::setTimeZone(const QString & tz)
{
  bool neg = FALSE;
  int hours, minutes;
  QString tmpStr(tz);

  if (tmpStr.left(1) == "-")
    neg = TRUE;
  if (tmpStr.left(1) == "-" || tmpStr.left(1) == "+")
    tmpStr.remove(0, 1);
  hours = tmpStr.left(2).toInt();
  if (tmpStr.length() > 2)
    minutes = tmpStr.right(2).toInt();
  else
    minutes = 0;
  mTimeZone = (60*hours+minutes);
  if (neg)
    mTimeZone = -mTimeZone;
}

QString Calendar::getTimeZoneStr() const
{
  QString tmpStr;
  int hours = abs(mTimeZone / 60);
  int minutes = abs(mTimeZone % 60);
  bool neg = mTimeZone < 0;

  tmpStr.sprintf("%c%.2d%.2d",
		 (neg ? '-' : '+'),
		 hours, minutes);
  return tmpStr;
}

void Calendar::setTimeZone(int tz)
{
  mTimeZone = tz;
}

int Calendar::getTimeZone() const
{
  return mTimeZone;
}

const QString &Calendar::getEmail()
{
  return mOwnerEmail;
}

void Calendar::setEmail(const QString &e)
{
  mOwnerEmail = e;
}

void Calendar::showDialogs(bool d)
{
  mDialogsOn = d;
}

// don't ever call this unless a kapp exists!
void Calendar::updateConfig()
{
//  kdDebug() << "Calendar::updateConfig()" << endl;

  bool updateFlag = FALSE;

  // TODO: update Organizer in all events
#if 0
  mOwner = KOPrefs::instance()->mName;

  // update events to new organizer (email address)
  // if it has changed...
  QString configEmail = KOPrefs::instance()->mEmail;

  if (mOwnerEmail != configEmail) {
    QString oldEmail = mOwnerEmail;
    //    oldEmail.detach();
    mOwnerEmail = configEmail;
    Event *firstEvent, *currEvent;
    bool atFirst = TRUE;

    firstEvent = last();
    // gotta skip over the first one, which is same as first.
    // I know, bad coding.
    for (currEvent = prev(); currEvent; currEvent = prev()) {
//      kdDebug() << "in Calendar::updateConfig(), currEvent summary: " << currEvent->getSummary() << endl;
      if ((currEvent == firstEvent) && !atFirst) {
	break;
      }
      if (currEvent->getOrganizer() == oldEmail) {
	currEvent->setReadOnly(FALSE);
	currEvent->setOrganizer(mOwnerEmail);
        updateFlag = TRUE;
      }
      atFirst = FALSE;
    }
  }
#endif
  readHolidayFileName();

// TODO: Fix time zone setting
//  setTimeZone(KOPrefs::instance()->mTimeZone.latin1());

  if (updateFlag)
    emit calUpdated((Event *) 0L);
}

QString Calendar::getHolidayForDate(const QDate &qd)
{
  static int lastYear = 0;

//  kdDebug() << "CalendarLocal::getHolidayForDate(): Holiday: " << holidays << endl;

  if (mHolidayfile.isEmpty()) return (QString(""));

  if ((lastYear == 0) || (qd.year() != lastYear)) {
      lastYear = qd.year() - 1900; // silly parse_year takes 2 digit year...
      parse_holidays(QFile::encodeName(mHolidayfile), lastYear, 0);
  }

  if (holiday[qd.dayOfYear()-1].string) {
    QString holidayname = QString::fromLocal8Bit(holiday[qd.dayOfYear()-1].string);
//    kdDebug() << "Holi name: " << holidayname << endl;
    return(holidayname);
  } else {
//    kdDebug() << "No holiday" << endl;
    return(QString(""));
  }
}

void Calendar::readHolidayFileName()
{
  QString holidays(mHoliday);
  if (holidays == "(none)") mHolidayfile = "";
  holidays = holidays.prepend("holiday_");
  mHolidayfile = locate("appdata",holidays);

//  kdDebug() << "holifile: " << mHolidayfile << endl;
}

void Calendar::setFilter(CalFilter *filter)
{
  mFilter = filter;
}

CalFilter *Calendar::filter()
{
  return mFilter;
}

QList<Event> Calendar::getEventsForDate(const QDate &date,bool sorted)
{
  QList<Event> el = eventsForDate(date,sorted);
  mFilter->apply(&el);
  return el;
}

QList<Event> Calendar::getEventsForDate(const QDateTime &qdt)
{
  QList<Event> el = eventsForDate(qdt);
  mFilter->apply(&el);
  return el;
}

QList<Event> Calendar::getEvents(const QDate &start,const QDate &end,
                                    bool inclusive)
{
  QList<Event> el = events(start,end,inclusive);
  mFilter->apply(&el);
  return el;
}

void Calendar::addIncidence(Incidence *i)
{
  AddIncidenceVisitor v(this);

  i->accept(v);
}

QList<Todo> Calendar::getFilteredTodoList()
{
  QList<Todo> tl = getTodoList();
  mFilter->apply(&tl);
  return tl;
}
<|endoftext|>


<commit_before>//===--- Logging.cpp ------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

#include "SourceKit/Support/Logging.h"
#include "SourceKit/Support/UIdent.h"
#include "llvm/Config/config.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/Mutex.h"
#include "llvm/Support/Timer.h"

#if HAVE_PTHREAD_H
#include <pthread.h>
#endif

#if __APPLE__
#include <asl.h>
#endif

using namespace SourceKit;

static llvm::sys::Mutex LoggingMutex;

std::string Logger::LoggerName;
Logger::Level Logger::LoggingLevel = Logger::Level::None;

Logger &Logger::operator<<(UIdent UID) {
  *this << UID.getName();
  return *this;
}

Logger &Logger::operator<<(const llvm::format_object_base &Fmt) {
  LogOS << Fmt;
  return *this;
}

Logger::~Logger() {
  llvm::sys::ScopedLock L(LoggingMutex);

  static llvm::TimeRecord sBeginTR = llvm::TimeRecord::getCurrentTime();

  SmallString<64> LogMsg;
  llvm::raw_svector_ostream LogMsgOS(LogMsg);
  raw_ostream &OS = LogMsgOS;

  OS << '[' << int(CurrLevel) << ':' << Name << ':';

  // FIXME: Portability.
#if HAVE_PTHREAD_H && __APPLE__
  mach_port_t tid = pthread_mach_thread_np(pthread_self());
  OS << tid << ':';
#endif

  llvm::TimeRecord TR = llvm::TimeRecord::getCurrentTime();
  OS << llvm::format("%7.4f] ", TR.getWallTime() - sBeginTR.getWallTime());
  OS << Msg.str();

  fprintf(stderr, "%s: %s", LoggerName.c_str(), LogMsg.c_str());

#if __APPLE__
  // Use the Apple System Log facility.
  aslclient asl = asl_open(LoggerName.c_str(), "com.apple.console",
                           ASL_OPT_NO_DELAY);
  aslmsg msg = asl_new(ASL_TYPE_MSG);
  static const char *levstr[] = {"0", "1", "2", "3", "4", "5", "6", "7"};
  asl_set(msg, ASL_KEY_LEVEL, levstr[int(CurrLevel)]);
  asl_set(msg, ASL_KEY_MSG, LogMsg.c_str());
  asl_send(asl, msg);
  asl_free(msg);
  asl_close(asl);
#endif
}
<commit_msg>SourceKit: add a newline to logged messages<commit_after>//===--- Logging.cpp ------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

#include "SourceKit/Support/Logging.h"
#include "SourceKit/Support/UIdent.h"
#include "llvm/Config/config.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/Mutex.h"
#include "llvm/Support/Timer.h"

#if HAVE_PTHREAD_H
#include <pthread.h>
#endif

#if __APPLE__
#include <asl.h>
#endif

using namespace SourceKit;

static llvm::sys::Mutex LoggingMutex;

std::string Logger::LoggerName;
Logger::Level Logger::LoggingLevel = Logger::Level::None;

Logger &Logger::operator<<(UIdent UID) {
  *this << UID.getName();
  return *this;
}

Logger &Logger::operator<<(const llvm::format_object_base &Fmt) {
  LogOS << Fmt;
  return *this;
}

Logger::~Logger() {
  llvm::sys::ScopedLock L(LoggingMutex);

  static llvm::TimeRecord sBeginTR = llvm::TimeRecord::getCurrentTime();

  SmallString<64> LogMsg;
  llvm::raw_svector_ostream LogMsgOS(LogMsg);
  raw_ostream &OS = LogMsgOS;

  OS << '[' << int(CurrLevel) << ':' << Name << ':';

  // FIXME: Portability.
#if HAVE_PTHREAD_H && __APPLE__
  mach_port_t tid = pthread_mach_thread_np(pthread_self());
  OS << tid << ':';
#endif

  llvm::TimeRecord TR = llvm::TimeRecord::getCurrentTime();
  OS << llvm::format("%7.4f] ", TR.getWallTime() - sBeginTR.getWallTime());
  OS << Msg.str();

  fprintf(stderr, "%s: %s\n", LoggerName.c_str(), LogMsg.c_str());

#if __APPLE__
  // Use the Apple System Log facility.
  aslclient asl = asl_open(LoggerName.c_str(), "com.apple.console",
                           ASL_OPT_NO_DELAY);
  aslmsg msg = asl_new(ASL_TYPE_MSG);
  static const char *levstr[] = {"0", "1", "2", "3", "4", "5", "6", "7"};
  asl_set(msg, ASL_KEY_LEVEL, levstr[int(CurrLevel)]);
  asl_set(msg, ASL_KEY_MSG, LogMsg.c_str());
  asl_send(asl, msg);
  asl_free(msg);
  asl_close(asl);
#endif
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2018 ARM Limited
 * All rights reserved
 *
 * The license below extends only to copyright in the software and shall
 * not be construed as granting a license to any other intellectual
 * property including but not limited to intellectual property relating
 * to a hardware implementation of the functionality of the software
 * licensed hereunder.  You may use the software subject to the license
 * terms below provided that you ensure that this notice is replicated
 * unmodified and in its entirety in all distributions of the software,
 * modified or unmodified, in source code or in binary form.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "mem/mem_delay.hh"

#include "params/MemDelay.hh"
#include "params/SimpleMemDelay.hh"

MemDelay::MemDelay(const MemDelayParams *p)
    : ClockedObject(p),
      masterPort(name() + "-master", *this),
      slavePort(name() + "-slave", *this),
      reqQueue(*this, masterPort),
      respQueue(*this, slavePort),
      snoopRespQueue(*this, masterPort)
{
}

void
MemDelay::init()
{
    if (!slavePort.isConnected() || !masterPort.isConnected())
        fatal("Memory delay is not connected on both sides.\n");
}

Port &
MemDelay::getPort(const std::string &if_name, PortID idx)
{
    if (if_name == "master") {
        return masterPort;
    } else if (if_name == "slave") {
        return slavePort;
    } else {
        return ClockedObject::getPort(if_name, idx);
    }
}

bool
MemDelay::trySatisfyFunctional(PacketPtr pkt)
{
    return slavePort.trySatisfyFunctional(pkt) ||
        masterPort.trySatisfyFunctional(pkt);
}

MemDelay::MasterPort::MasterPort(const std::string &_name, MemDelay &_parent)
    : QueuedMasterPort(_name, &_parent,
                       _parent.reqQueue, _parent.snoopRespQueue),
      parent(_parent)
{
}

bool
MemDelay::MasterPort::recvTimingResp(PacketPtr pkt)
{
    const Tick when = curTick() + parent.delayResp(pkt);

    parent.slavePort.schedTimingResp(pkt, when);

    return true;
}

void
MemDelay::MasterPort::recvFunctionalSnoop(PacketPtr pkt)
{
    if (parent.trySatisfyFunctional(pkt)) {
        pkt->makeResponse();
    } else {
        parent.slavePort.sendFunctionalSnoop(pkt);
    }
}

Tick
MemDelay::MasterPort::recvAtomicSnoop(PacketPtr pkt)
{
    const Tick delay = parent.delaySnoopResp(pkt);

    return delay + parent.slavePort.sendAtomicSnoop(pkt);
}

void
MemDelay::MasterPort::recvTimingSnoopReq(PacketPtr pkt)
{
    parent.slavePort.sendTimingSnoopReq(pkt);
}

MemDelay::SlavePort::SlavePort(const std::string &_name, MemDelay &_parent)
    : QueuedSlavePort(_name, &_parent, _parent.respQueue),
      parent(_parent)
{
}

Tick
MemDelay::SlavePort::recvAtomic(PacketPtr pkt)
{
    const Tick delay = parent.delayReq(pkt) + parent.delayResp(pkt);

    return delay + parent.masterPort.sendAtomic(pkt);
}

bool
MemDelay::SlavePort::recvTimingReq(PacketPtr pkt)
{
    const Tick when = curTick() + parent.delayReq(pkt);

    parent.masterPort.schedTimingReq(pkt, when);

    return true;
}

void
MemDelay::SlavePort::recvFunctional(PacketPtr pkt)
{
    if (parent.trySatisfyFunctional(pkt)) {
        pkt->makeResponse();
    } else {
        parent.masterPort.sendFunctional(pkt);
    }
}

bool
MemDelay::SlavePort::recvTimingSnoopResp(PacketPtr pkt)
{
    const Tick when = curTick() + parent.delaySnoopResp(pkt);

    parent.masterPort.schedTimingSnoopResp(pkt, when);

    return true;
}

SimpleMemDelay::SimpleMemDelay(const SimpleMemDelayParams *p)
    : MemDelay(p),
      readReqDelay(p->read_req),
      readRespDelay(p->read_resp),
      writeReqDelay(p->write_req),
      writeRespDelay(p->write_resp)
{
}

Tick
SimpleMemDelay::delayReq(PacketPtr pkt)
{
    if (pkt->isRead()) {
        return readReqDelay;
    } else if (pkt->isWrite()) {
        return writeReqDelay;
    } else {
        return 0;
    }
}

Tick
SimpleMemDelay::delayResp(PacketPtr pkt)
{
    if (pkt->isRead()) {
        return readRespDelay;
    } else if (pkt->isWrite()) {
        return writeRespDelay;
    } else {
        return 0;
    }
}

SimpleMemDelay *
SimpleMemDelayParams::create()
{
    return new SimpleMemDelay(this);
}
<commit_msg>mem: Fix latency handling in MemDelay<commit_after>/*
 * Copyright (c) 2018, 2020 ARM Limited
 * All rights reserved
 *
 * The license below extends only to copyright in the software and shall
 * not be construed as granting a license to any other intellectual
 * property including but not limited to intellectual property relating
 * to a hardware implementation of the functionality of the software
 * licensed hereunder.  You may use the software subject to the license
 * terms below provided that you ensure that this notice is replicated
 * unmodified and in its entirety in all distributions of the software,
 * modified or unmodified, in source code or in binary form.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "mem/mem_delay.hh"

#include "params/MemDelay.hh"
#include "params/SimpleMemDelay.hh"

MemDelay::MemDelay(const MemDelayParams *p)
    : ClockedObject(p),
      masterPort(name() + "-master", *this),
      slavePort(name() + "-slave", *this),
      reqQueue(*this, masterPort),
      respQueue(*this, slavePort),
      snoopRespQueue(*this, masterPort)
{
}

void
MemDelay::init()
{
    if (!slavePort.isConnected() || !masterPort.isConnected())
        fatal("Memory delay is not connected on both sides.\n");
}

Port &
MemDelay::getPort(const std::string &if_name, PortID idx)
{
    if (if_name == "master") {
        return masterPort;
    } else if (if_name == "slave") {
        return slavePort;
    } else {
        return ClockedObject::getPort(if_name, idx);
    }
}

bool
MemDelay::trySatisfyFunctional(PacketPtr pkt)
{
    return slavePort.trySatisfyFunctional(pkt) ||
        masterPort.trySatisfyFunctional(pkt);
}

MemDelay::MasterPort::MasterPort(const std::string &_name, MemDelay &_parent)
    : QueuedMasterPort(_name, &_parent,
                       _parent.reqQueue, _parent.snoopRespQueue),
      parent(_parent)
{
}

bool
MemDelay::MasterPort::recvTimingResp(PacketPtr pkt)
{
    // technically the packet only reaches us after the header delay,
    // and typically we also need to deserialise any payload
    const Tick receive_delay = pkt->headerDelay + pkt->payloadDelay;
    pkt->headerDelay = pkt->payloadDelay = 0;

    const Tick when = curTick() + parent.delayResp(pkt) + receive_delay;

    parent.slavePort.schedTimingResp(pkt, when);

    return true;
}

void
MemDelay::MasterPort::recvFunctionalSnoop(PacketPtr pkt)
{
    if (parent.trySatisfyFunctional(pkt)) {
        pkt->makeResponse();
    } else {
        parent.slavePort.sendFunctionalSnoop(pkt);
    }
}

Tick
MemDelay::MasterPort::recvAtomicSnoop(PacketPtr pkt)
{
    const Tick delay = parent.delaySnoopResp(pkt);

    return delay + parent.slavePort.sendAtomicSnoop(pkt);
}

void
MemDelay::MasterPort::recvTimingSnoopReq(PacketPtr pkt)
{
    parent.slavePort.sendTimingSnoopReq(pkt);
}

MemDelay::SlavePort::SlavePort(const std::string &_name, MemDelay &_parent)
    : QueuedSlavePort(_name, &_parent, _parent.respQueue),
      parent(_parent)
{
}

Tick
MemDelay::SlavePort::recvAtomic(PacketPtr pkt)
{
    const Tick delay = parent.delayReq(pkt) + parent.delayResp(pkt);

    return delay + parent.masterPort.sendAtomic(pkt);
}

bool
MemDelay::SlavePort::recvTimingReq(PacketPtr pkt)
{
    // technically the packet only reaches us after the header
    // delay, and typically we also need to deserialise any
    // payload
    Tick receive_delay = pkt->headerDelay + pkt->payloadDelay;
    pkt->headerDelay = pkt->payloadDelay = 0;

    const Tick when = curTick() + parent.delayReq(pkt) + receive_delay;

    parent.masterPort.schedTimingReq(pkt, when);

    return true;
}

void
MemDelay::SlavePort::recvFunctional(PacketPtr pkt)
{
    if (parent.trySatisfyFunctional(pkt)) {
        pkt->makeResponse();
    } else {
        parent.masterPort.sendFunctional(pkt);
    }
}

bool
MemDelay::SlavePort::recvTimingSnoopResp(PacketPtr pkt)
{
    const Tick when = curTick() + parent.delaySnoopResp(pkt);

    parent.masterPort.schedTimingSnoopResp(pkt, when);

    return true;
}

SimpleMemDelay::SimpleMemDelay(const SimpleMemDelayParams *p)
    : MemDelay(p),
      readReqDelay(p->read_req),
      readRespDelay(p->read_resp),
      writeReqDelay(p->write_req),
      writeRespDelay(p->write_resp)
{
}

Tick
SimpleMemDelay::delayReq(PacketPtr pkt)
{
    if (pkt->isRead()) {
        return readReqDelay;
    } else if (pkt->isWrite()) {
        return writeReqDelay;
    } else {
        return 0;
    }
}

Tick
SimpleMemDelay::delayResp(PacketPtr pkt)
{
    if (pkt->isRead()) {
        return readRespDelay;
    } else if (pkt->isWrite()) {
        return writeRespDelay;
    } else {
        return 0;
    }
}

SimpleMemDelay *
SimpleMemDelayParams::create()
{
    return new SimpleMemDelay(this);
}
<|endoftext|>