<commit_before>/*
  Copyright (C) 2005 Steven L. Scott

  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 Street, Fifth Floor, Boston, MA  02110-1301, USA
*/

/*
 *  Mathlib : A C Library of Special Functions
 *  Copyright (C) 1998 Ross Ihaka
 *  Copyright (C) 2000-2001 The R Development Core Team
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program 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 General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA.
 *
 *  SYNOPSIS
 *
 *    #include "Bmath.hpp"
 *    double rhyper(double NR, double NB, double n);
 *
 *  DESCRIPTION
 *
 *    Random variates from the hypergeometric distribution.
 *    Returns the number of white balls drawn when kk balls
 *    are drawn at random from an urn containing nn1 white
 *    and nn2 black balls.
 *
 *  REFERENCE
 *
 *    V. Kachitvichyanukul and B. Schmeiser (1985).
 *    ``Computer generation of hypergeometric random variates,''
 *    Journal of Statistical Computation and Simulation 22, 127-145.
 */

#include "nmath.hpp"
#include <sstream>
namespace Rmath{

/* afc(i) :=  ln( i! )  [logarithm of the factorial i.
 *         If (i > 7), use Stirling's approximation, otherwise use table lookup.
*/

double afc(int i) {
    const double al[9] =
    {
        0.0,
        0.0,/*ln(0!)=ln(1)*/
        0.0,/*ln(1!)=ln(1)*/
        0.69314718055994530941723212145817,/*ln(2) */
        1.79175946922805500081247735838070,/*ln(6) */
        3.17805383034794561964694160129705,/*ln(24)*/
        4.78749174278204599424770093452324,
        6.57925121201010099506017829290394,
        8.52516136106541430016553103634712
        /*, 10.60460290274525022841722740072165*/
    };
    double di, value = 0;

    if (i < 0) {
      std::ostringstream err;
      err << "rhyper.cpp:  afc(i), i = " << i
          << " < 0 -- SHOULD NOT HAPPEN!";
      report_error(err.str());
    } else if (i <= 7) {
        value = al[i + 1];
    } else {
        di = i;
        value = (di + 0.5) * log(di) - di + 0.08333333333333 / di
            - 0.00277777777777 / di / di / di + 0.9189385332;
    }
    return value;
}

double rhyper(double nn1in, double nn2in, double kkin){
  return rhyper_mt(BOOM::GlobalRng::rng, nn1in, nn2in, kkin); }

double rhyper_mt(BOOM::RNG & rng, double nn1in, double nn2in, double kkin)
{
    const double con = 57.56462733;
    const double deltal = 0.0078;
    const double deltau = 0.0034;
    const double scale = 1e25;

    /* extern double afc(int); */

    int nn1, nn2, kk;
    int i, ix;
    Rboolean reject; // , setup1, setup2;
    const bool setup1=true;
    const bool setup2=true;

    double e, f, g, p, r, t, u, v, y;
    double de, dg, dr, ds, dt, gl, gu, nk, nm, ub;
    double xk, xm, xn, y1, ym, yn, yk, alv;

    /* These should become `thread_local globals' : */
    int ks = -1;
    int n1s = -1, n2s = -1;

    int k, m;
    int minjx, maxjx, n1, n2;

    double a, d, s, w;
    double tn, xl, xr, kl, kr, lamdl, lamdr, p1, p2, p3;

    /* check parameter validity */

    if(!R_FINITE(nn1in) || !R_FINITE(nn2in) || !R_FINITE(kkin))
        ML_ERR_return_NAN;

    nn1 = FLOOR(nn1in+0.5);
    nn2 = FLOOR(nn2in+0.5);
    kk  = FLOOR(kkin +0.5);

    if (nn1 < 0 || nn2 < 0 || kk < 0 || kk > nn1 + nn2)
        ML_ERR_return_NAN;

    /* if new parameter values, initialize */
    reject = true;
    if (setup1) {
        n1s = nn1;
        n2s = nn2;
        tn = nn1 + nn2;
        if (nn1 <= nn2) {
            n1 = nn1;
            n2 = nn2;
        } else {
            n1 = nn2;
            n2 = nn1;
        }
    }
    if (setup2) {
        ks = kk;
        if (kk + kk >= tn) {
          k = static_cast<int>(tn - kk);
        } else {
            k = kk;
        }
    }
    if (setup1 || setup2) {
        m = static_cast<int>((k + 1.0) * (n1 + 1.0) / (tn + 2.0));
        minjx = std::max(0, k - n2);
        maxjx = std::min(n1, k);
    }
    /* generate random variate --- Three basic cases */

    if (minjx == maxjx) { /* I: degenerate distribution ---------------- */
        ix = maxjx;
        /* return ix;
           No, need to unmangle <TSL>*/
        /* return appropriate variate */

        if (kk + kk >= tn) {
          if (nn1 > nn2) {
            ix = kk - nn2 + ix;
          } else {
            ix = nn1 - ix;
          }
        } else {
          if (nn1 > nn2)
            ix = kk - ix;
        }
        return ix;

    } else if (m - minjx < 10) { /* II: inverse transformation ---------- */
        if (setup1 || setup2) {
            if (k < n2) {
                w = exp(con + afc(n2) + afc(n1 + n2 - k)
                        - afc(n2 - k) - afc(n1 + n2));
            } else {
                w = exp(con + afc(n1) + afc(k)
                        - afc(k - n2) - afc(n1 + n2));
            }
        }
      L10:
        p = w;
        ix = minjx;
        u = rng() * scale;
      L20:
        if (u > p) {
            u -= p;
            p *= (n1 - ix) * (k - ix);
            ix++;
            p = p / ix / (n2 - k + ix);
            if (ix > maxjx)
                goto L10;
            goto L20;
        }
    } else { /* III : h2pe --------------------------------------------- */

        if (setup1 || setup2) {
            s = sqrt((tn - k) * k * n1 * n2 / (tn - 1) / tn / tn);

            /* remark: d is defined in reference without int. */
            /* the truncation centers the cell boundaries at 0.5 */

            d = (int) (1.5 * s) + .5;
            xl = m - d + .5;
            xr = m + d + .5;
            a = afc(m) + afc(n1 - m) + afc(k - m) + afc(n2 - k + m);
            kl = exp(a - afc((int) (xl)) - afc((int) (n1 - xl))
                     - afc((int) (k - xl))
                     - afc((int) (n2 - k + xl)));
            kr = exp(a - afc((int) (xr - 1))
                     - afc((int) (n1 - xr + 1))
                     - afc((int) (k - xr + 1))
                     - afc((int) (n2 - k + xr - 1)));
            lamdl = -log(xl * (n2 - k + xl) / (n1 - xl + 1) / (k - xl + 1));
            lamdr = -log((n1 - xr + 1) * (k - xr + 1) / xr / (n2 - k + xr));
            p1 = d + d;
            p2 = p1 + kl / lamdl;
            p3 = p2 + kr / lamdr;
        }
      L30:
        u = rng() * p3;
        v = rng();
        if (u < p1) {           /* rectangular region */
          ix = static_cast<int>(xl + u);
        } else if (u <= p2) {   /* left tail */
          ix = static_cast<int>(xl + log(v) / lamdl);
            if (ix < minjx)
                goto L30;
            v = v * (u - p1) * lamdl;
        } else {                /* right tail */
            ix = static_cast<int>(xr - log(v) / lamdr);
            if (ix > maxjx)
                goto L30;
            v = v * (u - p2) * lamdr;
        }

        /* acceptance/rejection test */

        if (m < 100 || ix <= 50) {
            /* explicit evaluation */
            f = 1.0;
            if (m < ix) {
                for (i = m + 1; i <= ix; i++)
                    f = f * (n1 - i + 1) * (k - i + 1) / (n2 - k + i) / i;
            } else if (m > ix) {
                for (i = ix + 1; i <= m; i++)
                    f = f * i * (n2 - k + i) / (n1 - i) / (k - i);
            }
            if (v <= f) {
                reject = false;
            }
        } else {
            /* squeeze using upper and lower bounds */
            y = ix;
            y1 = y + 1.0;
            ym = y - m;
            yn = n1 - y + 1.0;
            yk = k - y + 1.0;
            nk = n2 - k + y1;
            r = -ym / y1;
            s = ym / yn;
            t = ym / yk;
            e = -ym / nk;
            g = yn * yk / (y1 * nk) - 1.0;
            dg = 1.0;
            if (g < 0.0)
                dg = 1.0 + g;
            gu = g * (1.0 + g * (-0.5 + g / 3.0));
            gl = gu - .25 * (g * g * g * g) / dg;
            xm = m + 0.5;
            xn = n1 - m + 0.5;
            xk = k - m + 0.5;
            nm = n2 - k + xm;
            ub = y * gu - m * gl + deltau
                + xm * r * (1. + r * (-0.5 + r / 3.0))
                + xn * s * (1. + s * (-0.5 + s / 3.0))
                + xk * t * (1. + t * (-0.5 + t / 3.0))
                + nm * e * (1. + e * (-0.5 + e / 3.0));
            /* test against upper bound */
            alv = log(v);
            if (alv > ub) {
                reject = true;
            } else {
                                /* test against lower bound */
                dr = xm * (r * r * r * r);
                if (r < 0.0)
                    dr /= (1.0 + r);
                ds = xn * (s * s * s * s);
                if (s < 0.0)
                    ds /= (1.0 + s);
                dt = xk * (t * t * t * t);
                if (t < 0.0)
                    dt /= (1.0 + t);
                de = nm * (e * e * e * e);
                if (e < 0.0)
                    de /= (1.0 + e);
                if (alv < ub - 0.25 * (dr + ds + dt + de)
                    + (y + m) * (gl - gu) - deltal) {
                    reject = false;
                }
                else {
                    /* * Stirling's formula to machine accuracy
                     */
                    if (alv <= (a - afc(ix) - afc(n1 - ix)
                                - afc(k - ix) - afc(n2 - k + ix))) {
                        reject = false;
                    } else {
                        reject = true;
                    }
                }
            }
        }
        if (reject)
            goto L30;
    }

    /* return appropriate variate */

    if (kk + kk >= tn) {
        if (nn1 > nn2) {
            ix = kk - nn2 + ix;
        } else {
            ix = nn1 - ix;
        }
    } else {
        if (nn1 > nn2)
            ix = kk - ix;
    }
    return ix;
}
}
<commit_msg>Remove set but unused variables.<commit_after>/*
  Copyright (C) 2005 Steven L. Scott

  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 Street, Fifth Floor, Boston, MA  02110-1301, USA
*/

/*
 *  Mathlib : A C Library of Special Functions
 *  Copyright (C) 1998 Ross Ihaka
 *  Copyright (C) 2000-2001 The R Development Core Team
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program 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 General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA.
 *
 *  SYNOPSIS
 *
 *    #include "Bmath.hpp"
 *    double rhyper(double NR, double NB, double n);
 *
 *  DESCRIPTION
 *
 *    Random variates from the hypergeometric distribution.
 *    Returns the number of white balls drawn when kk balls
 *    are drawn at random from an urn containing nn1 white
 *    and nn2 black balls.
 *
 *  REFERENCE
 *
 *    V. Kachitvichyanukul and B. Schmeiser (1985).
 *    ``Computer generation of hypergeometric random variates,''
 *    Journal of Statistical Computation and Simulation 22, 127-145.
 */

#include "nmath.hpp"
#include <sstream>
namespace Rmath{

/* afc(i) :=  ln( i! )  [logarithm of the factorial i.
 *         If (i > 7), use Stirling's approximation, otherwise use table lookup.
*/

double afc(int i) {
    const double al[9] =
    {
        0.0,
        0.0,/*ln(0!)=ln(1)*/
        0.0,/*ln(1!)=ln(1)*/
        0.69314718055994530941723212145817,/*ln(2) */
        1.79175946922805500081247735838070,/*ln(6) */
        3.17805383034794561964694160129705,/*ln(24)*/
        4.78749174278204599424770093452324,
        6.57925121201010099506017829290394,
        8.52516136106541430016553103634712
        /*, 10.60460290274525022841722740072165*/
    };
    double di, value = 0;

    if (i < 0) {
      std::ostringstream err;
      err << "rhyper.cpp:  afc(i), i = " << i
          << " < 0 -- SHOULD NOT HAPPEN!";
      report_error(err.str());
    } else if (i <= 7) {
        value = al[i + 1];
    } else {
        di = i;
        value = (di + 0.5) * log(di) - di + 0.08333333333333 / di
            - 0.00277777777777 / di / di / di + 0.9189385332;
    }
    return value;
}

double rhyper(double nn1in, double nn2in, double kkin){
  return rhyper_mt(BOOM::GlobalRng::rng, nn1in, nn2in, kkin); }

double rhyper_mt(BOOM::RNG & rng, double nn1in, double nn2in, double kkin)
{
    const double con = 57.56462733;
    const double deltal = 0.0078;
    const double deltau = 0.0034;
    const double scale = 1e25;

    /* extern double afc(int); */

    int nn1, nn2, kk;
    int i, ix;
    Rboolean reject; // , setup1, setup2;
    const bool setup1=true;
    const bool setup2=true;

    double e, f, g, p, r, t, u, v, y;
    double de, dg, dr, ds, dt, gl, gu, nk, nm, ub;
    double xk, xm, xn, y1, ym, yn, yk, alv;

    /* These should become `thread_local globals' : */

    int k, m;
    int minjx, maxjx, n1, n2;

    double a, d, s, w;
    double tn, xl, xr, kl, kr, lamdl, lamdr, p1, p2, p3;

    /* check parameter validity */

    if(!R_FINITE(nn1in) || !R_FINITE(nn2in) || !R_FINITE(kkin))
        ML_ERR_return_NAN;

    nn1 = FLOOR(nn1in+0.5);
    nn2 = FLOOR(nn2in+0.5);
    kk  = FLOOR(kkin +0.5);

    if (nn1 < 0 || nn2 < 0 || kk < 0 || kk > nn1 + nn2)
        ML_ERR_return_NAN;

    /* if new parameter values, initialize */
    reject = true;
    if (setup1) {
        tn = nn1 + nn2;
        if (nn1 <= nn2) {
            n1 = nn1;
            n2 = nn2;
        } else {
            n1 = nn2;
            n2 = nn1;
        }
    }
    if (setup2) {
        if (kk + kk >= tn) {
          k = static_cast<int>(tn - kk);
        } else {
            k = kk;
        }
    }
    if (setup1 || setup2) {
        m = static_cast<int>((k + 1.0) * (n1 + 1.0) / (tn + 2.0));
        minjx = std::max(0, k - n2);
        maxjx = std::min(n1, k);
    }
    /* generate random variate --- Three basic cases */

    if (minjx == maxjx) { /* I: degenerate distribution ---------------- */
        ix = maxjx;
        /* return ix;
           No, need to unmangle <TSL>*/
        /* return appropriate variate */

        if (kk + kk >= tn) {
          if (nn1 > nn2) {
            ix = kk - nn2 + ix;
          } else {
            ix = nn1 - ix;
          }
        } else {
          if (nn1 > nn2)
            ix = kk - ix;
        }
        return ix;

    } else if (m - minjx < 10) { /* II: inverse transformation ---------- */
        if (setup1 || setup2) {
            if (k < n2) {
                w = exp(con + afc(n2) + afc(n1 + n2 - k)
                        - afc(n2 - k) - afc(n1 + n2));
            } else {
                w = exp(con + afc(n1) + afc(k)
                        - afc(k - n2) - afc(n1 + n2));
            }
        }
      L10:
        p = w;
        ix = minjx;
        u = rng() * scale;
      L20:
        if (u > p) {
            u -= p;
            p *= (n1 - ix) * (k - ix);
            ix++;
            p = p / ix / (n2 - k + ix);
            if (ix > maxjx)
                goto L10;
            goto L20;
        }
    } else { /* III : h2pe --------------------------------------------- */

        if (setup1 || setup2) {
            s = sqrt((tn - k) * k * n1 * n2 / (tn - 1) / tn / tn);

            /* remark: d is defined in reference without int. */
            /* the truncation centers the cell boundaries at 0.5 */

            d = (int) (1.5 * s) + .5;
            xl = m - d + .5;
            xr = m + d + .5;
            a = afc(m) + afc(n1 - m) + afc(k - m) + afc(n2 - k + m);
            kl = exp(a - afc((int) (xl)) - afc((int) (n1 - xl))
                     - afc((int) (k - xl))
                     - afc((int) (n2 - k + xl)));
            kr = exp(a - afc((int) (xr - 1))
                     - afc((int) (n1 - xr + 1))
                     - afc((int) (k - xr + 1))
                     - afc((int) (n2 - k + xr - 1)));
            lamdl = -log(xl * (n2 - k + xl) / (n1 - xl + 1) / (k - xl + 1));
            lamdr = -log((n1 - xr + 1) * (k - xr + 1) / xr / (n2 - k + xr));
            p1 = d + d;
            p2 = p1 + kl / lamdl;
            p3 = p2 + kr / lamdr;
        }
      L30:
        u = rng() * p3;
        v = rng();
        if (u < p1) {           /* rectangular region */
          ix = static_cast<int>(xl + u);
        } else if (u <= p2) {   /* left tail */
          ix = static_cast<int>(xl + log(v) / lamdl);
            if (ix < minjx)
                goto L30;
            v = v * (u - p1) * lamdl;
        } else {                /* right tail */
            ix = static_cast<int>(xr - log(v) / lamdr);
            if (ix > maxjx)
                goto L30;
            v = v * (u - p2) * lamdr;
        }

        /* acceptance/rejection test */

        if (m < 100 || ix <= 50) {
            /* explicit evaluation */
            f = 1.0;
            if (m < ix) {
                for (i = m + 1; i <= ix; i++)
                    f = f * (n1 - i + 1) * (k - i + 1) / (n2 - k + i) / i;
            } else if (m > ix) {
                for (i = ix + 1; i <= m; i++)
                    f = f * i * (n2 - k + i) / (n1 - i) / (k - i);
            }
            if (v <= f) {
                reject = false;
            }
        } else {
            /* squeeze using upper and lower bounds */
            y = ix;
            y1 = y + 1.0;
            ym = y - m;
            yn = n1 - y + 1.0;
            yk = k - y + 1.0;
            nk = n2 - k + y1;
            r = -ym / y1;
            s = ym / yn;
            t = ym / yk;
            e = -ym / nk;
            g = yn * yk / (y1 * nk) - 1.0;
            dg = 1.0;
            if (g < 0.0)
                dg = 1.0 + g;
            gu = g * (1.0 + g * (-0.5 + g / 3.0));
            gl = gu - .25 * (g * g * g * g) / dg;
            xm = m + 0.5;
            xn = n1 - m + 0.5;
            xk = k - m + 0.5;
            nm = n2 - k + xm;
            ub = y * gu - m * gl + deltau
                + xm * r * (1. + r * (-0.5 + r / 3.0))
                + xn * s * (1. + s * (-0.5 + s / 3.0))
                + xk * t * (1. + t * (-0.5 + t / 3.0))
                + nm * e * (1. + e * (-0.5 + e / 3.0));
            /* test against upper bound */
            alv = log(v);
            if (alv > ub) {
                reject = true;
            } else {
                                /* test against lower bound */
                dr = xm * (r * r * r * r);
                if (r < 0.0)
                    dr /= (1.0 + r);
                ds = xn * (s * s * s * s);
                if (s < 0.0)
                    ds /= (1.0 + s);
                dt = xk * (t * t * t * t);
                if (t < 0.0)
                    dt /= (1.0 + t);
                de = nm * (e * e * e * e);
                if (e < 0.0)
                    de /= (1.0 + e);
                if (alv < ub - 0.25 * (dr + ds + dt + de)
                    + (y + m) * (gl - gu) - deltal) {
                    reject = false;
                }
                else {
                    /* * Stirling's formula to machine accuracy
                     */
                    if (alv <= (a - afc(ix) - afc(n1 - ix)
                                - afc(k - ix) - afc(n2 - k + ix))) {
                        reject = false;
                    } else {
                        reject = true;
                    }
                }
            }
        }
        if (reject)
            goto L30;
    }

    /* return appropriate variate */

    if (kk + kk >= tn) {
        if (nn1 > nn2) {
            ix = kk - nn2 + ix;
        } else {
            ix = nn1 - ix;
        }
    } else {
        if (nn1 > nn2)
            ix = kk - ix;
    }
    return ix;
}
}
<|endoftext|>


<commit_before>/** @date 2015

    @author
    Sensics, Inc.
    <http://sensics.com/osvr>
*/

// Copyright 2015 Vuzix Corporation.
//
// 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.

// Internal Includes
#include "DriverWrapper.h"
#include <osvr/PluginKit/PluginKit.h>
#include <osvr/PluginKit/TrackerInterfaceC.h>
#include <osvr/Util/PlatformConfig.h>

// Generated JSON header file
#include "com_osvr_Vive_json.h"

// Library/third-party includes
#include <math.h>
#include <openvr_driver.h>

// Standard includes
#include <iostream>
#include <memory>
#include <vector>

using namespace vr;

// Anonymous namespace to avoid symbol collision
namespace {
static const auto PREFIX = "[OSVR-Vive] ";
class ViveDriverHost : public ServerDriverHost {
  public:
    /// @return false if we failed to start up for some reason.
    bool start(OSVR_PluginRegContext ctx, osvr::vive::DriverWrapper &&inVive) {
        if (!inVive) {
            std::cerr << PREFIX << "Error: called ViveDriverHost::start() with "
                                   "an invalid vive object!"
                      << std::endl;
        }
        /// Take ownership of the Vive.
        m_vive.reset(new osvr::vive::DriverWrapper(std::move(inVive)));

        /// Finish setting up the Vive.
        if (!m_vive->startServerDeviceProvider()) {
            std::cerr
                << PREFIX
                << "Error: could not start the server device provider in the "
                   "Vive driver. Exiting."
                << std::endl;
            return false;
        }

        /// Power the system up.
        m_vive->serverDevProvider().LeaveStandby();

        auto handleNewDevice =
            [&](const char *serialNum) {
                auto dev = m_vive->serverDevProvider().FindTrackedDeviceDriver(
                    serialNum, vr::ITrackedDeviceServerDriver_Version);
                if (!dev) {
                    std::cout
                        << PREFIX
                        << "Couldn't find the corresponding device driver for "
                        << serialNum << std::endl;
                    return false;
                }
                auto ret = m_vive->addAndActivateDevice(dev);
                if (!ret.first) {
                    std::cout << PREFIX << "Device with serial number "
                              << serialNum
                              << " couldn't be added to the devices vector."
                              << std::endl;
                    return false;
                }
                std::cout << "\n"
                          << PREFIX << "Device with s/n " << serialNum
                          << " activated, assigned ID " << ret.second
                          << std::endl;
                return true;
            };

        m_vive->driverHost().onTrackedDeviceAdded = handleNewDevice;

        {
            auto numDevices =
                m_vive->serverDevProvider().GetTrackedDeviceCount();
            std::cout << PREFIX << "Got " << numDevices
                      << " tracked devices at startup" << std::endl;
            for (decltype(numDevices) i = 0; i < numDevices; ++i) {
                auto dev = m_vive->serverDevProvider().GetTrackedDeviceDriver(
                    i, vr::ITrackedDeviceServerDriver_Version);
                m_vive->addAndActivateDevice(dev);
                std::cout << PREFIX << "Device " << i << std::endl;
#if 0
                addDeviceType(dev);
#endif
            }
        }

        /// Finish setting this up as an OSVR device.
        /// Create the initialization options
        OSVR_DeviceInitOptions opts = osvrDeviceCreateInitOptions(ctx);

        osvrDeviceTrackerConfigure(opts, &m_tracker);

        /// Create the sync device token with the options
        m_dev.initSync(ctx, "Vive", opts);

        /// Send JSON descriptor
        m_dev.sendJsonDescriptor(com_osvr_Vive_json);

        /// Register update callback
        m_dev.registerUpdateCallback(this);

        return true;
    }

    OSVR_ReturnCode update() {
        m_vive->serverDevProvider().RunFrame();
        return OSVR_RETURN_SUCCESS;
    }

    void TrackedDevicePoseUpdated(uint32_t unWhichDevice,
                                  const DriverPose_t &newPose) override {

        std::cout << PREFIX << "TrackedDevicePoseUpdated(" << unWhichDevice
                  << ", newPose)" << std::endl;

        OSVR_TimeValue now;
        osvrTimeValueGetNow(&now);
        if (newPose.poseIsValid) {
            OSVR_PoseState pose;
            pose.translation.data[0] = newPose.vecPosition[0];
            pose.translation.data[1] = newPose.vecPosition[1];
            pose.translation.data[2] = newPose.vecPosition[2];
            pose.rotation.data[0] = newPose.qRotation.w;
            pose.rotation.data[1] = newPose.qRotation.x;
            pose.rotation.data[2] = newPose.qRotation.y;
            pose.rotation.data[3] = newPose.qRotation.z;

            osvrDeviceTrackerSendPoseTimestamped(m_dev, m_tracker, &pose,
                                                 unWhichDevice, &now);
        }
    }

    void DeviceDescriptorUpdated(std::string const &json) {

        m_dev.sendJsonDescriptor(json);
    }

  private:
    osvr::pluginkit::DeviceToken m_dev;
    OSVR_TrackerDeviceInterface m_tracker;
    std::unique_ptr<osvr::vive::DriverWrapper> m_vive;
};
using DriverHostPtr = std::unique_ptr<ViveDriverHost>;

class HardwareDetection {

  public:
    HardwareDetection() {}
    OSVR_ReturnCode operator()(OSVR_PluginRegContext ctx) {

        std::cout << PREFIX << "Got a hardware detection request" << std::endl;

        if (m_driverHost) {
            // Already found a Vive.
            /// @todo what are the semantics of the return value from a hardware
            /// detect?
            return OSVR_RETURN_SUCCESS;
        }

        {
            DriverHostPtr host(new ViveDriverHost);

            auto vive = osvr::vive::DriverWrapper(host.get());

            if (vive.foundDriver()) {
                std::cout << PREFIX << "Found the Vive driver at "
                          << vive.getDriverFileLocation() << std::endl;
            }

            if (!vive.haveDriverLoaded()) {
                std::cout << PREFIX << "Could not open driver." << std::endl;
                return OSVR_RETURN_FAILURE;
            }

            if (vive.foundConfigDirs()) {
                std::cout << PREFIX << "Driver config dir is: "
                          << vive.getDriverConfigDir() << std::endl;
            }

            if (!vive) {
                std::cerr << PREFIX
                          << "Error in first-stage Vive driver startup. Exiting"
                          << std::endl;
                return OSVR_RETURN_FAILURE;
            }

            if (!vive.isHMDPresent()) {
                std::cerr << PREFIX
                          << "Driver loaded, but no Vive is connected. Exiting"
                          << std::endl;
                return OSVR_RETURN_FAILURE;
            }

            std::cout << PREFIX << "Vive is connected." << std::endl;

            /// Hand the Vive object off to the OSVR driver.
            auto startResult = host->start(ctx, std::move(vive));
            if (startResult) {
                /// and it started up the rest of the way just fine!
                /// We'll keep the driver around!
                m_driverHost = std::move(host);
                std::cout << PREFIX
                          << "Vive driver finished startup successfully!"
                          << std::endl;
                return OSVR_RETURN_SUCCESS;
            }
        }

        std::cout << PREFIX << "Vive driver startup failed somewhere, "
                               "unloading to perhaps try again later."
                  << std::endl;
        return OSVR_RETURN_FAILURE;
    }

    static void addDeviceType(vr::ITrackedDeviceServerDriver *dev) {
        // @todo add device type (controller, tracker) to generate
        // dynamic device descriptor
    }

  private:
    std::vector<std::string> m_deviceTypes;
    /// This is the OSVR driver object, which also serves as the "SteamVR"
    /// driver host. We can only run one Vive at a time.
    std::unique_ptr<ViveDriverHost> m_driverHost;
};
} // namespace

OSVR_PLUGIN(com_osvr_Vive) {
    osvr::pluginkit::PluginContext context(ctx);

    /// Register a detection callback function object.
    context.registerHardwareDetectCallback(new HardwareDetection());

    return OSVR_RETURN_SUCCESS;
}
<commit_msg>Quiet the driver<commit_after>/** @date 2015

    @author
    Sensics, Inc.
    <http://sensics.com/osvr>
*/

// Copyright 2015 Vuzix Corporation.
//
// 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.

// Internal Includes
#include "DriverWrapper.h"
#include <osvr/PluginKit/PluginKit.h>
#include <osvr/PluginKit/TrackerInterfaceC.h>
#include <osvr/Util/PlatformConfig.h>

// Generated JSON header file
#include "com_osvr_Vive_json.h"

// Library/third-party includes
#include <math.h>
#include <openvr_driver.h>

// Standard includes
#include <iostream>
#include <memory>
#include <vector>

using namespace vr;

// Anonymous namespace to avoid symbol collision
namespace {
static const auto PREFIX = "[OSVR-Vive] ";
class ViveDriverHost : public ServerDriverHost {
  public:
    /// @return false if we failed to start up for some reason.
    bool start(OSVR_PluginRegContext ctx, osvr::vive::DriverWrapper &&inVive) {
        if (!inVive) {
            std::cerr << PREFIX << "Error: called ViveDriverHost::start() with "
                                   "an invalid vive object!"
                      << std::endl;
        }
        /// Take ownership of the Vive.
        m_vive.reset(new osvr::vive::DriverWrapper(std::move(inVive)));

        /// Finish setting up the Vive.
        if (!m_vive->startServerDeviceProvider()) {
            std::cerr
                << PREFIX
                << "Error: could not start the server device provider in the "
                   "Vive driver. Exiting."
                << std::endl;
            return false;
        }

        /// Power the system up.
        m_vive->serverDevProvider().LeaveStandby();

        auto handleNewDevice =
            [&](const char *serialNum) {
                auto dev = m_vive->serverDevProvider().FindTrackedDeviceDriver(
                    serialNum, vr::ITrackedDeviceServerDriver_Version);
                if (!dev) {
                    std::cout
                        << PREFIX
                        << "Couldn't find the corresponding device driver for "
                        << serialNum << std::endl;
                    return false;
                }
                auto ret = m_vive->addAndActivateDevice(dev);
                if (!ret.first) {
                    std::cout << PREFIX << "Device with serial number "
                              << serialNum
                              << " couldn't be added to the devices vector."
                              << std::endl;
                    return false;
                }
                std::cout << "\n"
                          << PREFIX << "Device with s/n " << serialNum
                          << " activated, assigned ID " << ret.second
                          << std::endl;
                return true;
            };

        m_vive->driverHost().onTrackedDeviceAdded = handleNewDevice;

        {
            auto numDevices =
                m_vive->serverDevProvider().GetTrackedDeviceCount();
            std::cout << PREFIX << "Got " << numDevices
                      << " tracked devices at startup" << std::endl;
            for (decltype(numDevices) i = 0; i < numDevices; ++i) {
                auto dev = m_vive->serverDevProvider().GetTrackedDeviceDriver(
                    i, vr::ITrackedDeviceServerDriver_Version);
                m_vive->addAndActivateDevice(dev);
                std::cout << PREFIX << "Device " << i << std::endl;
#if 0
                addDeviceType(dev);
#endif
            }
        }

        /// Finish setting this up as an OSVR device.
        /// Create the initialization options
        OSVR_DeviceInitOptions opts = osvrDeviceCreateInitOptions(ctx);

        osvrDeviceTrackerConfigure(opts, &m_tracker);

        /// Create the sync device token with the options
        m_dev.initSync(ctx, "Vive", opts);

        /// Send JSON descriptor
        m_dev.sendJsonDescriptor(com_osvr_Vive_json);

        /// Register update callback
        m_dev.registerUpdateCallback(this);

        return true;
    }

    OSVR_ReturnCode update() {
        m_vive->serverDevProvider().RunFrame();
        return OSVR_RETURN_SUCCESS;
    }

    void TrackedDevicePoseUpdated(uint32_t unWhichDevice,
                                  const DriverPose_t &newPose) override {
#if 0
        std::cout << PREFIX << "TrackedDevicePoseUpdated(" << unWhichDevice
                  << ", newPose)" << std::endl;
#endif
        OSVR_TimeValue now;
        osvrTimeValueGetNow(&now);
        if (newPose.poseIsValid) {
            OSVR_PoseState pose;
            pose.translation.data[0] = newPose.vecPosition[0];
            pose.translation.data[1] = newPose.vecPosition[1];
            pose.translation.data[2] = newPose.vecPosition[2];
            pose.rotation.data[0] = newPose.qRotation.w;
            pose.rotation.data[1] = newPose.qRotation.x;
            pose.rotation.data[2] = newPose.qRotation.y;
            pose.rotation.data[3] = newPose.qRotation.z;

            osvrDeviceTrackerSendPoseTimestamped(m_dev, m_tracker, &pose,
                                                 unWhichDevice, &now);
        }
    }

    void DeviceDescriptorUpdated(std::string const &json) {

        m_dev.sendJsonDescriptor(json);
    }

  private:
    osvr::pluginkit::DeviceToken m_dev;
    OSVR_TrackerDeviceInterface m_tracker;
    std::unique_ptr<osvr::vive::DriverWrapper> m_vive;
};
using DriverHostPtr = std::unique_ptr<ViveDriverHost>;

class HardwareDetection {

  public:
    HardwareDetection() {}
    OSVR_ReturnCode operator()(OSVR_PluginRegContext ctx) {

        std::cout << PREFIX << "Got a hardware detection request" << std::endl;

        if (m_driverHost) {
            // Already found a Vive.
            /// @todo what are the semantics of the return value from a hardware
            /// detect?
            return OSVR_RETURN_SUCCESS;
        }

        {
            DriverHostPtr host(new ViveDriverHost);

            auto vive = osvr::vive::DriverWrapper(host.get());

            if (vive.foundDriver()) {
                std::cout << PREFIX << "Found the Vive driver at "
                          << vive.getDriverFileLocation() << std::endl;
            }

            if (!vive.haveDriverLoaded()) {
                std::cout << PREFIX << "Could not open driver." << std::endl;
                return OSVR_RETURN_FAILURE;
            }

            if (vive.foundConfigDirs()) {
                std::cout << PREFIX << "Driver config dir is: "
                          << vive.getDriverConfigDir() << std::endl;
            }

            if (!vive) {
                std::cerr << PREFIX
                          << "Error in first-stage Vive driver startup. Exiting"
                          << std::endl;
                return OSVR_RETURN_FAILURE;
            }

            if (!vive.isHMDPresent()) {
                std::cerr << PREFIX
                          << "Driver loaded, but no Vive is connected. Exiting"
                          << std::endl;
                return OSVR_RETURN_FAILURE;
            }

            std::cout << PREFIX << "Vive is connected." << std::endl;

            /// Hand the Vive object off to the OSVR driver.
            auto startResult = host->start(ctx, std::move(vive));
            if (startResult) {
                /// and it started up the rest of the way just fine!
                /// We'll keep the driver around!
                m_driverHost = std::move(host);
                std::cout << PREFIX
                          << "Vive driver finished startup successfully!"
                          << std::endl;
                return OSVR_RETURN_SUCCESS;
            }
        }

        std::cout << PREFIX << "Vive driver startup failed somewhere, "
                               "unloading to perhaps try again later."
                  << std::endl;
        return OSVR_RETURN_FAILURE;
    }

    static void addDeviceType(vr::ITrackedDeviceServerDriver *dev) {
        // @todo add device type (controller, tracker) to generate
        // dynamic device descriptor
    }

  private:
    std::vector<std::string> m_deviceTypes;
    /// This is the OSVR driver object, which also serves as the "SteamVR"
    /// driver host. We can only run one Vive at a time.
    std::unique_ptr<ViveDriverHost> m_driverHost;
};
} // namespace

OSVR_PLUGIN(com_osvr_Vive) {
    osvr::pluginkit::PluginContext context(ctx);

    /// Register a detection callback function object.
    context.registerHardwareDetectCallback(new HardwareDetection());

    return OSVR_RETURN_SUCCESS;
}
<|endoftext|>


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

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_slideshow.hxx"

// must be first
#include "canvas/debug.hxx"
#include "canvas/verbosetrace.hxx"
#include "coloranimation.hxx"
#include "hslcoloranimation.hxx"
#include "animationcolornode.hxx"
#include "animationfactory.hxx"
#include "activitiesfactory.hxx"
#include "com/sun/star/animations/AnimationColorSpace.hpp"

using namespace com::sun::star;

namespace presentation {
namespace internal {

namespace {
/** Little wrapper for HSL to RGB mapping.

    This class implements the HSLColorAnimation interface,
    internally converting to RGB and forwarding to
    ColorAnimation.
*/
class HSLWrapper : public HSLColorAnimation
{
public:
    HSLWrapper( const ColorAnimationSharedPtr& rAnimation )
        : mpAnimation( rAnimation )
    {
        ENSURE_AND_THROW(
            mpAnimation.get(),
            "HSLWrapper::HSLWrapper(): Invalid color animation delegate" );
    }

    virtual void start( const AnimatableShapeSharedPtr&     rShape,
                        const ShapeAttributeLayerSharedPtr& rAttrLayer )
    {
        mpAnimation->start( rShape, rAttrLayer );
    }

    virtual void end()
    {
        mpAnimation->end();
    }

    virtual bool operator()( const HSLColor& rColor )
    {
        return (*mpAnimation)( RGBColor( rColor ) );
    }

    virtual HSLColor getUnderlyingValue() const
    {
        return HSLColor( mpAnimation->getUnderlyingValue() );
    }

private:
    ColorAnimationSharedPtr mpAnimation;
};

} // anon namespace

AnimationActivitySharedPtr AnimationColorNode::createActivity() const
{
    ActivitiesFactory::CommonParameters aParms( fillCommonParameters() );

    switch( mxColorNode->getColorInterpolation() )
    {
    case animations::AnimationColorSpace::RGB:
        return ActivitiesFactory::createAnimateActivity(
            aParms,
            AnimationFactory::createColorPropertyAnimation(
                mxColorNode->getAttributeName(),
                getShape(),
                getContext().mpLayerManager ),
            getXAnimateNode() );

    case animations::AnimationColorSpace::HSL:
        // Wrap a plain ColorAnimation with the HSL
        // wrapper, which implements the HSLColorAnimation
        // interface, and internally converts HSL to RGB color
        return ActivitiesFactory::createAnimateActivity(
            aParms,
            HSLColorAnimationSharedPtr(
                new HSLWrapper(
                    AnimationFactory::createColorPropertyAnimation(
                        mxColorNode->getAttributeName(),
                        getShape(),
                        getContext().mpLayerManager ) ) ),
            mxColorNode );

    default:
        ENSURE_AND_THROW( false, "AnimationColorNode::createColorActivity(): "
                          "Unexpected color space" );
    }

    return AnimationActivitySharedPtr();
}

} // namespace internal
} // namespace presentation

<commit_msg>INTEGRATION: CWS presfixes09 (1.3.18); FILE MERGED 2006/10/18 19:54:22 thb 1.3.18.5: RESYNC: (1.4-1.5); FILE MERGED 2006/09/15 22:13:35 thb 1.3.18.4: RESYNC: (1.3-1.4); FILE MERGED 2006/04/12 20:40:06 thb 1.3.18.3: #i37778# Replaced all shared_ptr.get() != NULL places with the more elegant automatic-conversion-to-bool version (at least where the compiler tolerated that) 2006/03/24 18:23:16 thb 1.3.18.2: #i37778# Moved whole slideshow engine from namespace presentation (which conflicts with one of the UNO subnamespaces) to slideshow 2006/03/15 15:22:19 thb 1.3.18.1: #i49357# Removed external include guards from all non-export headers (and from the cxx files, anyway)<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: animationcolornode.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: kz $ $Date: 2006-12-13 15:28:51 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_slideshow.hxx"

// must be first
#include "canvas/debug.hxx"
#include "canvas/verbosetrace.hxx"
#include "coloranimation.hxx"
#include "hslcoloranimation.hxx"
#include "animationcolornode.hxx"
#include "animationfactory.hxx"
#include "activitiesfactory.hxx"
#include "com/sun/star/animations/AnimationColorSpace.hpp"

using namespace com::sun::star;

namespace slideshow {
namespace internal {

namespace {
/** Little wrapper for HSL to RGB mapping.

    This class implements the HSLColorAnimation interface,
    internally converting to RGB and forwarding to
    ColorAnimation.
*/
class HSLWrapper : public HSLColorAnimation
{
public:
    HSLWrapper( const ColorAnimationSharedPtr& rAnimation )
        : mpAnimation( rAnimation )
    {
        ENSURE_AND_THROW(
            mpAnimation,
            "HSLWrapper::HSLWrapper(): Invalid color animation delegate" );
    }

    virtual void start( const AnimatableShapeSharedPtr&     rShape,
                        const ShapeAttributeLayerSharedPtr& rAttrLayer )
    {
        mpAnimation->start( rShape, rAttrLayer );
    }

    virtual void end()
    {
        mpAnimation->end();
    }

    virtual bool operator()( const HSLColor& rColor )
    {
        return (*mpAnimation)( RGBColor( rColor ) );
    }

    virtual HSLColor getUnderlyingValue() const
    {
        return HSLColor( mpAnimation->getUnderlyingValue() );
    }

private:
    ColorAnimationSharedPtr mpAnimation;
};

} // anon namespace

AnimationActivitySharedPtr AnimationColorNode::createActivity() const
{
    ActivitiesFactory::CommonParameters aParms( fillCommonParameters() );

    switch( mxColorNode->getColorInterpolation() )
    {
    case animations::AnimationColorSpace::RGB:
        return ActivitiesFactory::createAnimateActivity(
            aParms,
            AnimationFactory::createColorPropertyAnimation(
                mxColorNode->getAttributeName(),
                getShape(),
                getContext().mpLayerManager ),
            getXAnimateNode() );

    case animations::AnimationColorSpace::HSL:
        // Wrap a plain ColorAnimation with the HSL
        // wrapper, which implements the HSLColorAnimation
        // interface, and internally converts HSL to RGB color
        return ActivitiesFactory::createAnimateActivity(
            aParms,
            HSLColorAnimationSharedPtr(
                new HSLWrapper(
                    AnimationFactory::createColorPropertyAnimation(
                        mxColorNode->getAttributeName(),
                        getShape(),
                        getContext().mpLayerManager ) ) ),
            mxColorNode );

    default:
        ENSURE_AND_THROW( false, "AnimationColorNode::createColorActivity(): "
                          "Unexpected color space" );
    }

    return AnimationActivitySharedPtr();
}

} // namespace internal
} // namespace slideshow

<|endoftext|>


<commit_before>/* Please refer to license.txt */

#include <sys/stat.h>
#include <errno.h>
#include <stdio.h>
#include <iostream>
#include <string.h>
#include <dirent.h>

#include "file.hpp"

#include "../error/error.hpp"

#include "../string/string.hpp"

#include "../internal_header.hpp"

namespace mfile
{

FileManager::FileManager()
{
}

FileManager::~FileManager()
{
}

void FileManager::exportFile(std::string filepath, std::string output_data, bool overwrite) //Export a file.
{
	FILE *file = nullptr; //The file.

	if (overwrite) file = fopen(filepath.c_str(), "w+"); //Open the file for writing, overwriting whatever currently exists, if anything.
	else file = fopen(filepath.c_str(), "a"); //Open the file for writing. Do not overwrite, append.

	if (!file) //Error checking.
	{
		//cout << "Failed to open file: \"" << filepath << "\".\n"; //Let the user know there was an error.
		//cout << "Attempting to create folder...\n"; //Let the user know we're trying to create the directory.

		//TODO: This portiong needs to be put into a "make_directories_until()" function.

		//TODO: This needs to be adjusted to recursively make the missing folders.

		bool start_saving = false; //Start saving the characters from the string?
		std::string folderpath = ""; //The folderpath.
		std::string temp_string = ""; //Folderpath is initially read into this, backwards. Used for ordering it correctly.
		for (int i = filepath.length() - 1; i >= 0; --i) //Loop through and extract the folderpath
		{
			if (!start_saving && (filepath[i] == '\\' || filepath[i] == '/')) //If not already saving the characters...Check if it's a / or \ character.
			{
				start_saving = true; //Yay, end of filename found, now we can extract the folderpath.
			}
			if (start_saving) //Ok, it is saving the characters.
			{
				temp_string += filepath[i]; //Save the character.
			}
		}
		for (int i = temp_string.length() - 1; i >= 0; --i) //Now reverse the order of characters so that the folderpath is no longer backwards.
		{
			folderpath += temp_string[i]; //Save the character.
		}

		try
		{
			mkDir("./" + folderpath); //Create the folder. With error checking.
		}
		catch (...)
		{
			std::string *filename = new std::string; //The filename.
			*filename = mstring::toString(__FILE__); //Convert the char* that is filename to a string.
			std::string *message = new std::string;
			*message = "Failed to create directory: \"";
			*message += folderpath;
			*message += "\".";
			merror::Error *error = generateError(merror::FUNCTION_FAILURE, message, merror::SEVERITY_IGNORE, __LINE__, filename);
			throw error;
		}

		if (overwrite) file = fopen(filepath.c_str(), "w+"); //Open the file for writing, overwriting any currently existing file.
		else file = fopen(filepath.c_str(), "a"); //Open the file for writing. Do not overwrite, append.

		if (!file) //Error checking.
		{
			std::string *filename = new std::string; //The filename.
			*filename = mstring::toString(__FILE__); //Convert the char* that is filename to a string.
			std::string *message = new std::string;
			*message = "Failed to create file.";
			merror::Error *error = generateError(merror::FUNCTION_FAILURE, message, merror::SEVERITY_IGNORE, __LINE__, filename);
			throw error; //Failure.
		}

		//TODO: End portion that needs being put into a "make_directories_until()" function.
	}

	fprintf(file, output_data.c_str());  //Write out the string.

	fclose(file); //Close the file.
} //FileManager::exportFile()

void FileManager::mkDir(std::string path) //Create a directory at the specified location.
{
	#if OS == OS_WINDOWS //If the operating system is windows.
		if (mkdir(path.c_str()) == -1) //Create the directory.
		{
			//throw strerror(errno); //Throw an error. //TODO: Refine the error to use the error module.
			std::string *error_message = new std::string; //The error message.
			*error_message = mstring::toString(strerror(errno)); //Convert the char* that is strerror to a string.
			std::string *filename = new std::string; //The filename.
			*filename = mstring::toString(__FILE__); //Convert the char* that is filename to a string.
			merror::Error *error = generateError(merror::FUNCTION_FAILURE, error_message, merror::SEVERITY_IGNORE, __LINE__, filename);
			throw error;
		}
	#else //OS is not windows.
		if (mkdir(path.c_str(), 0777) == -1)//creating a directory
		{
			//throw strerror(errno); //Throw an error. //TODO: Refine the error to use the error module.
			std::string *error_message = new std::string; //The error message.
			*error_message = mstring::toString(strerror(errno)); //Convert the char* that is strerror to a string.
			std::string *filename = new std::string; //The filename.
			*filename = mstring::toString(__FILE__); //Convert the char* that is filename to a string.
			merror::Error *error = generateError(merror::FUNCTION_FAILURE, error_message, merror::SEVERITY_IGNORE, __LINE__, filename);
			throw error;
		}
	#endif
}

bool FileManager::directoryExists(std::string path) //Checks if specified directory exists.
{
	//This function could probably be done better with a call to an external library's superoptimised directory_exists() function.
	//But, until such a time that we have such a library, this will be used.

	//TODO: This portion probably can be put into an external function.

	//This portion of code determines the path to the directory the directory we're looking for is in.

	bool start_saving = false; //Start saving the characters from the string?
	std::string folderpath = ""; //The folderpath.
	std::string temp_string = ""; //Folderpath is initially read into this, backwards. Used for ordering it correctly.
	std::string directory_name_reverse = ""; //The name of the folder it's looking for. Reversed. This is used because the path is read backwards and everything after the slash is chopped off, thus determining the directory we're looking for's name.
	std::string directory_name = ""; //The name of the folder it's looking for.
	for (int i = path.length() - 1; i >= 0; --i) //Loop through and extract the folderpath. Pretty much the folder the folder is in.
	{
		if (!start_saving && (path[i] == '\\' || path[i] == '/')) //If not already saving the characters...Check if it's a / or \ character.
		{
			start_saving = true; //Yay, end of filename found, now we can extract the folderpath.
			directory_name_reverse += path[i];
		}
		else if (start_saving) //Ok, it is saving the characters.
		{
			temp_string += path[i]; //Save the character.
		}
	}
	for (int i = temp_string.length() - 1; i >= 0; --i) //Now reverse the order of characters so that the folderpath is no longer backwards.
	{
		folderpath += temp_string[i]; //Save the character.
	}
	for (int i = directory_name_reverse.length() - 1;  i >= 0; --i)
	{
		if (directory_name_reverse[i] != '\\' && directory_name_reverse[i] != '/') directory_name += directory_name_reverse[i];
	}
	//TODO: End portion that can be put in external function.

	//This portion of code looks at all the contents in the directory of the directory we're checking the existence of, and looks to see if the directory exists.
	//If it does, then return true. Else return false.

	std::vector<std::string> folders; //Stores all the folder names it finds.

	getFolders(folderpath, folders); //Grabs all the folders in the folder containing the folder which we're checking the existence of.

	if (folders.size() == 0)
	{
		return false; //If it found nothing...The directory definitely does not exist!
	}

	for (unsigned int i = 0; i < folders.size(); ++i)
	{
		if (folders[i] == directory_name) return true; //Yes, directory exists.
	}

	return false; //Default case: does not exist.
} //FileManager::directoryExists()

void FileManager::seperatePathFromFilename(std::string &path_with_filename, std::string &path)
{
	//Loop from the back, find the /, chop off everything.

	int count = 0;
	std::string input(path_with_filename);
	std::cout << "Starting with: " << input << "\n";
	std::string::iterator i = input.end();
	bool done = false;
	while (!done)
	{
		std::cout << "i = \"" << (*i) << "\" & count = " << count << "\n";

		//If it found where the filepath ends...
		if ((*i) != '/')
		{
			--i; //Keep going.
			input.pop_back(); //Delete the last character.
			count++;
		}
		else
		{
			done = true;
		}
	}

	path = input;
}

void FileManager::getFolders(std::string path, std::vector<std::string> &folders) //Get all the folders in a directory.
{
	#if OS == OS_WINDOWS
		struct stat s; //Required for the Windows version of the code
	#endif

	DIR *dir ; //Open the bases folder.

	if ((dir = opendir(path.c_str())) == nullptr) //Open directory. With error checking.
	{
		std::string *filename = new std::string; //The filename.
		*filename = mstring::toString(__FILE__); //Convert the char* that is filename to a string.
		std::string *message = new std::string;
		*message = "Failed to open directory.";
		merror::Error *error = generateError(merror::FUNCTION_FAILURE, message, merror::SEVERITY_IGNORE, __LINE__, filename);
		throw error;
	}

	struct dirent *entry = readdir(dir); //The current directory entry

	while (entry != NULL) //Loop through all the folders (and files) in this directory.
	{
		#if OS == OS_WINDOWS

			//TODO: Test this to see if it works in Windows.

			stat(entry->d_name, &s);
			if (s.st_mode & S_IFDIR)
			{
				if (strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0) //Make sure it's not the current directory, or the one containing this directory!
				{
					folders.push_back(entry->d_name);
				}
			}

			entry = readdir(dir); //Load in the next entry.

		#else

			if (entry->d_type == DT_DIR) //If the entry type is a folder.
			{
				if (strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0) //Make sure it's not the current directory, or the one containing this directory!
				{
					folders.push_back(entry->d_name);
				}
			}

		#endif
	}

	closedir(dir);
} //FileManager::getFolders()

} //namespace mfile
<commit_msg>Debugging.<commit_after>/* Please refer to license.txt */

#include <sys/stat.h>
#include <errno.h>
#include <stdio.h>
#include <iostream>
#include <string.h>
#include <dirent.h>

#include "file.hpp"

#include "../error/error.hpp"

#include "../string/string.hpp"

#include "../internal_header.hpp"

namespace mfile
{

FileManager::FileManager()
{
}

FileManager::~FileManager()
{
}

void FileManager::exportFile(std::string filepath, std::string output_data, bool overwrite) //Export a file.
{
	FILE *file = nullptr; //The file.

	if (overwrite) file = fopen(filepath.c_str(), "w+"); //Open the file for writing, overwriting whatever currently exists, if anything.
	else file = fopen(filepath.c_str(), "a"); //Open the file for writing. Do not overwrite, append.

	if (!file) //Error checking.
	{
		//cout << "Failed to open file: \"" << filepath << "\".\n"; //Let the user know there was an error.
		//cout << "Attempting to create folder...\n"; //Let the user know we're trying to create the directory.

		//TODO: This portiong needs to be put into a "make_directories_until()" function.

		//TODO: This needs to be adjusted to recursively make the missing folders.

		bool start_saving = false; //Start saving the characters from the string?
		std::string folderpath = ""; //The folderpath.
		std::string temp_string = ""; //Folderpath is initially read into this, backwards. Used for ordering it correctly.
		for (int i = filepath.length() - 1; i >= 0; --i) //Loop through and extract the folderpath
		{
			if (!start_saving && (filepath[i] == '\\' || filepath[i] == '/')) //If not already saving the characters...Check if it's a / or \ character.
			{
				start_saving = true; //Yay, end of filename found, now we can extract the folderpath.
			}
			if (start_saving) //Ok, it is saving the characters.
			{
				temp_string += filepath[i]; //Save the character.
			}
		}
		for (int i = temp_string.length() - 1; i >= 0; --i) //Now reverse the order of characters so that the folderpath is no longer backwards.
		{
			folderpath += temp_string[i]; //Save the character.
		}

		try
		{
			mkDir("./" + folderpath); //Create the folder. With error checking.
		}
		catch (...)
		{
			std::string *filename = new std::string; //The filename.
			*filename = mstring::toString(__FILE__); //Convert the char* that is filename to a string.
			std::string *message = new std::string;
			*message = "Failed to create directory: \"";
			*message += folderpath;
			*message += "\".";
			merror::Error *error = generateError(merror::FUNCTION_FAILURE, message, merror::SEVERITY_IGNORE, __LINE__, filename);
			throw error;
		}

		if (overwrite) file = fopen(filepath.c_str(), "w+"); //Open the file for writing, overwriting any currently existing file.
		else file = fopen(filepath.c_str(), "a"); //Open the file for writing. Do not overwrite, append.

		if (!file) //Error checking.
		{
			std::string *filename = new std::string; //The filename.
			*filename = mstring::toString(__FILE__); //Convert the char* that is filename to a string.
			std::string *message = new std::string;
			*message = "Failed to create file.";
			merror::Error *error = generateError(merror::FUNCTION_FAILURE, message, merror::SEVERITY_IGNORE, __LINE__, filename);
			throw error; //Failure.
		}

		//TODO: End portion that needs being put into a "make_directories_until()" function.
	}

	fprintf(file, output_data.c_str());  //Write out the string.

	fclose(file); //Close the file.
} //FileManager::exportFile()

void FileManager::mkDir(std::string path) //Create a directory at the specified location.
{
	#if OS == OS_WINDOWS //If the operating system is windows.
		if (mkdir(path.c_str()) == -1) //Create the directory.
		{
			//throw strerror(errno); //Throw an error. //TODO: Refine the error to use the error module.
			std::string *error_message = new std::string; //The error message.
			*error_message = mstring::toString(strerror(errno)); //Convert the char* that is strerror to a string.
			std::string *filename = new std::string; //The filename.
			*filename = mstring::toString(__FILE__); //Convert the char* that is filename to a string.
			merror::Error *error = generateError(merror::FUNCTION_FAILURE, error_message, merror::SEVERITY_IGNORE, __LINE__, filename);
			throw error;
		}
	#else //OS is not windows.
		if (mkdir(path.c_str(), 0777) == -1)//creating a directory
		{
			//throw strerror(errno); //Throw an error. //TODO: Refine the error to use the error module.
			std::string *error_message = new std::string; //The error message.
			*error_message = mstring::toString(strerror(errno)); //Convert the char* that is strerror to a string.
			std::string *filename = new std::string; //The filename.
			*filename = mstring::toString(__FILE__); //Convert the char* that is filename to a string.
			merror::Error *error = generateError(merror::FUNCTION_FAILURE, error_message, merror::SEVERITY_IGNORE, __LINE__, filename);
			throw error;
		}
	#endif
}

bool FileManager::directoryExists(std::string path) //Checks if specified directory exists.
{
	//This function could probably be done better with a call to an external library's superoptimised directory_exists() function.
	//But, until such a time that we have such a library, this will be used.

	//TODO: This portion probably can be put into an external function.

	//This portion of code determines the path to the directory the directory we're looking for is in.

	bool start_saving = false; //Start saving the characters from the string?
	std::string folderpath = ""; //The folderpath.
	std::string temp_string = ""; //Folderpath is initially read into this, backwards. Used for ordering it correctly.
	std::string directory_name_reverse = ""; //The name of the folder it's looking for. Reversed. This is used because the path is read backwards and everything after the slash is chopped off, thus determining the directory we're looking for's name.
	std::string directory_name = ""; //The name of the folder it's looking for.
	for (int i = path.length() - 1; i >= 0; --i) //Loop through and extract the folderpath. Pretty much the folder the folder is in.
	{
		if (!start_saving && (path[i] == '\\' || path[i] == '/')) //If not already saving the characters...Check if it's a / or \ character.
		{
			start_saving = true; //Yay, end of filename found, now we can extract the folderpath.
			directory_name_reverse += path[i];
		}
		else if (start_saving) //Ok, it is saving the characters.
		{
			temp_string += path[i]; //Save the character.
		}
	}
	for (int i = temp_string.length() - 1; i >= 0; --i) //Now reverse the order of characters so that the folderpath is no longer backwards.
	{
		folderpath += temp_string[i]; //Save the character.
	}
	for (int i = directory_name_reverse.length() - 1;  i >= 0; --i)
	{
		if (directory_name_reverse[i] != '\\' && directory_name_reverse[i] != '/') directory_name += directory_name_reverse[i];
	}
	//TODO: End portion that can be put in external function.

	//This portion of code looks at all the contents in the directory of the directory we're checking the existence of, and looks to see if the directory exists.
	//If it does, then return true. Else return false.

	std::vector<std::string> folders; //Stores all the folder names it finds.

	getFolders(folderpath, folders); //Grabs all the folders in the folder containing the folder which we're checking the existence of.

	if (folders.size() == 0)
	{
		return false; //If it found nothing...The directory definitely does not exist!
	}

	for (unsigned int i = 0; i < folders.size(); ++i)
	{
		if (folders[i] == directory_name) return true; //Yes, directory exists.
	}

	return false; //Default case: does not exist.
} //FileManager::directoryExists()

void FileManager::seperatePathFromFilename(std::string &path_with_filename, std::string &path)
{
	//Loop from the back, find the /, chop off everything.

	int count = 0;
	std::string input(path_with_filename);
	std::cout << "Starting with: " << input << "\n";
	std::string::iterator i = input.end()-1;
	bool done = false;
	while (!done)
	{
		std::cout << "i = \"" << (*i) << "\" & count = " << count << "\n";

		//If it found where the filepath ends...
		if ((*i) != '/')
		{
			--i; //Keep going.
			input.pop_back(); //Delete the last character.
			count++;
		}
		else
		{
			done = true;
		}
	}

	path = input;
}

void FileManager::getFolders(std::string path, std::vector<std::string> &folders) //Get all the folders in a directory.
{
	#if OS == OS_WINDOWS
		struct stat s; //Required for the Windows version of the code
	#endif

	DIR *dir ; //Open the bases folder.

	if ((dir = opendir(path.c_str())) == nullptr) //Open directory. With error checking.
	{
		std::string *filename = new std::string; //The filename.
		*filename = mstring::toString(__FILE__); //Convert the char* that is filename to a string.
		std::string *message = new std::string;
		*message = "Failed to open directory.";
		merror::Error *error = generateError(merror::FUNCTION_FAILURE, message, merror::SEVERITY_IGNORE, __LINE__, filename);
		throw error;
	}

	struct dirent *entry = readdir(dir); //The current directory entry

	while (entry != NULL) //Loop through all the folders (and files) in this directory.
	{
		#if OS == OS_WINDOWS

			//TODO: Test this to see if it works in Windows.

			stat(entry->d_name, &s);
			if (s.st_mode & S_IFDIR)
			{
				if (strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0) //Make sure it's not the current directory, or the one containing this directory!
				{
					folders.push_back(entry->d_name);
				}
			}

			entry = readdir(dir); //Load in the next entry.

		#else

			if (entry->d_type == DT_DIR) //If the entry type is a folder.
			{
				if (strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0) //Make sure it's not the current directory, or the one containing this directory!
				{
					folders.push_back(entry->d_name);
				}
			}

		#endif
	}

	closedir(dir);
} //FileManager::getFolders()

} //namespace mfile
<|endoftext|>


<commit_before>#include "meme_format.hpp"

sparse_hash_map<char, unordered_set<char>> iupac_or_nuc_to_nucs {
    {'A', {'A'}},
    {'C', {'C'}},
    {'G', {'G'}},
    {'T', {'T'}},
    {'R', {'A','G'}},
    {'Y', {'C','T'}},
    {'S', {'G','C'}},
    {'W', {'A','T'}},
    {'K', {'G','T'}},
    {'M', {'A','C'}},
    {'B', {'C','G','T'}},
    {'D', {'A','G','T'}},
    {'H', {'A','C','T'}},
    {'V', {'A','C','G'}},
    {'N', {'A','C','G','T'}}
};

void generate_exact_successor_motifs_rec(vector<string> &res, const string &motif, string &acc, unsigned int pos, unsigned int l) {
    if (pos == l) {
        res.emplace_back(acc);
        return;
    }
    for (auto nuc : iupac_or_nuc_to_nucs[motif[pos]]) {
        acc.push_back(nuc);
        generate_exact_successor_motifs_rec(res, motif, acc, pos+1, l);
        acc.pop_back();
    }
}

void generate_exact_successor_motifs(vector<string> &res, const string &motif, unsigned int l) {
    string acc;
    generate_exact_successor_motifs_rec(res, motif, acc, 0, l);
}

int create_meme_file(vector<pair<const string, pair<int, Node *> > *> &entries,
                     sparse_hash_map<string, pair<int, Node *>> &exact_motifs,
                     sparse_hash_map<char, unsigned int> &neg_nuc_count,
                     unsigned int l,
                     string &filename) {

    ofstream meme_file;

    meme_file.open(filename, std::ios::out | std::ios::trunc);
    // checking if the file could be opened
    if (!meme_file.is_open()) {
        cerr << "Error opening meme file, make sure that the program has write access to \"" << filename << "\"." << endl;
        cerr << "Meme file creation has failed" << endl;
        return 1;
    }

    double total_neg_nuc_count = 0;
    for (auto const &entry : neg_nuc_count) {
        total_neg_nuc_count += entry.second;
    }

    //en-tête
    meme_file << "MEME version 4" << endl
              << endl
              << "ALPHABET= ACGT" << endl
              << endl
              << "strands: + -" << endl
              << endl
              << "Background letter frequencies" << endl
              << "A " << neg_nuc_count['A'] / total_neg_nuc_count << " C " << neg_nuc_count['C'] / total_neg_nuc_count << " G " << neg_nuc_count['G'] / total_neg_nuc_count << " T " << neg_nuc_count['T'] / total_neg_nuc_count << endl
              << endl;

    //corps
    for (auto const &entry : entries) {
        meme_file << "MOTIF " << entry->first << endl << endl;
        meme_file << "#\tMI\tP-value" << endl;
        meme_file << "#\t" << entry->second.second->get_mi() << "\t" << entry->second.second->get_pvalue() << endl << endl;
        meme_file << "letter-probability matrix:" << endl;

        vector<string> exact_successor_motifs;
        generate_exact_successor_motifs(exact_successor_motifs, entry->first, l);
        for (size_t i=0; i < l; i++) {
            size_t exact_motifs_count = 0;
            sparse_hash_map<char, float> nuc_counts{
                {'A', 0.0},
                {'C', 0.0},
                {'G', 0.0},
                {'T', 0.0}
            };
            for (auto const &motif : exact_successor_motifs) {
                nuc_counts[motif[i]] += exact_motifs[motif].second->get_positive_count();
                exact_motifs_count += exact_motifs[motif].second->get_positive_count();
            }
            meme_file << nuc_counts['A'] / exact_motifs_count << "\t"
                      << nuc_counts['C'] / exact_motifs_count << "\t"
                      << nuc_counts['G'] / exact_motifs_count << "\t"
                      << 1.0 - nuc_counts['A'] / exact_motifs_count
                             - nuc_counts['C'] / exact_motifs_count
                             - nuc_counts['G'] / exact_motifs_count
                      << endl;
        }
        meme_file << endl;
    }
    return 0;
}
<commit_msg>[~FIX] Removed parts of the code that complicated generation of frequencies and did not work - STILL UNIMPLEMENTED<commit_after>#include "meme_format.hpp"

sparse_hash_map<char, unordered_set<char>> iupac_or_nuc_to_nucs {
    {'A', {'A'}},
    {'C', {'C'}},
    {'G', {'G'}},
    {'T', {'T'}},
    {'R', {'A','G'}},
    {'Y', {'C','T'}},
    {'S', {'G','C'}},
    {'W', {'A','T'}},
    {'K', {'G','T'}},
    {'M', {'A','C'}},
    {'B', {'C','G','T'}},
    {'D', {'A','G','T'}},
    {'H', {'A','C','T'}},
    {'V', {'A','C','G'}},
    {'N', {'A','C','G','T'}}
};

void generate_exact_successor_motifs_rec(vector<string> &res, const string &motif, string &acc, unsigned int pos, unsigned int l) {
    if (pos == l) {
        res.emplace_back(acc);
        return;
    }
    for (auto nuc : iupac_or_nuc_to_nucs[motif[pos]]) {
        acc.push_back(nuc);
        generate_exact_successor_motifs_rec(res, motif, acc, pos+1, l);
        acc.pop_back();
    }
}

void generate_exact_successor_motifs(vector<string> &res, const string &motif, unsigned int l) {
    string acc;
    generate_exact_successor_motifs_rec(res, motif, acc, 0, l);
}

int create_meme_file(vector<pair<const string, pair<int, Node *> > *> &entries,
                     sparse_hash_map<string, pair<int, Node *>> &exact_motifs,
                     sparse_hash_map<char, unsigned int> &neg_nuc_count,
                     unsigned int l,
                     string &filename) {

    ofstream meme_file;

    meme_file.open(filename, std::ios::out | std::ios::trunc);
    // checking if the file could be opened
    if (!meme_file.is_open()) {
        cerr << "Error opening meme file, make sure that the program has write access to \"" << filename << "\"." << endl;
        cerr << "Meme file creation has failed" << endl;
        return 1;
    }

    double total_neg_nuc_count = 0;
    for (auto const &entry : neg_nuc_count) {
        total_neg_nuc_count += entry.second;
    }

    double A_frequency = neg_nuc_count['A'] / total_neg_nuc_count;
    double C_frequency = neg_nuc_count['C'] / total_neg_nuc_count;
    double G_frequency = neg_nuc_count['G'] / total_neg_nuc_count;
    double T_frequency = neg_nuc_count['T'] / total_neg_nuc_count;

    //en-tête
    meme_file << "MEME version 4" << endl
              << endl
              << "ALPHABET= ACGT" << endl
              << endl
              << "strands: + -" << endl
              << endl
              << "Background letter frequencies" << endl
              << "A " << A_frequency << " C " << C_frequency << " G " << G_frequency << " T " << T_frequency << endl
              << endl;

    //corps
    for (auto const &entry : entries) {
        meme_file << "MOTIF " << entry->first << endl << endl;
        meme_file << "#\tMI\tP-value" << endl;
        meme_file << "#\t" << entry->second.second->get_mi() << "\t" << entry->second.second->get_pvalue() << endl << endl;
        meme_file << "letter-probability matrix:" << endl;

        vector<string> exact_successor_motifs;
        generate_exact_successor_motifs(exact_successor_motifs, entry->first, l);
        for (size_t i=0; i < l; i++) {
            size_t exact_motifs_count = 0;
            sparse_hash_map<char, double> nuc_counts{
                {'A', 0.0},
                {'C', 0.0},
                {'G', 0.0},
                {'T', 0.0}
            };
            for (auto const &motif : exact_successor_motifs) {
                nuc_counts[motif[i]] += exact_motifs[motif].second->get_positive_count();
                exact_motifs_count += exact_motifs[motif].second->get_positive_count();
            }
            meme_file << nuc_counts['A'] / exact_motifs_count << "\t"
                      << nuc_counts['C'] / exact_motifs_count << "\t"
                      << nuc_counts['G'] / exact_motifs_count << "\t"
                      << nuc_counts['T'] / exact_motifs_count << endl;
        }
        meme_file << endl;
    }
    return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <functional>
#include <utility>

#include "config.hpp"
#include "vfs.hpp"
#include "game.hpp"

GameManager::GameManager()
{
    m_width = 800;
    m_height = 600;
    m_fullscreen = false;
    m_title = "Game";

    m_window = std::unique_ptr<MgCore::Window>(new MgCore::Window(m_width, m_height, m_fullscreen, m_title));
    m_context = std::unique_ptr<MgCore::Context>(new MgCore::Context(3, 2, 0));
    m_events = std::unique_ptr<MgCore::Events>(new MgCore::Events());
    m_clock = std::unique_ptr<MgCore::FpsTimer>(new MgCore::FpsTimer());
    m_running = true;

    m_window->make_current(m_context.get());

    VFS.AddLoader(new ttvfs::DiskLoader);
    VFS.AddArchiveLoader(new ttvfs::VFSZipArchiveLoader);

    //
    // AppPath gets mounted on osx
    // BasePath gets mounted and overwrites any files similar to those in AppPath (data)
    // HomePath gets mounted and overwrites any files similar to those in BasePath (configs)
    // std::cout << MgCore::GetBasePath() << std::endl;
#if OSX_APP_BUNDLE
    VFS.Mount( MgCore::GetAppPath().c_str(), "" );
#endif
    VFS.Mount( MgCore::GetBasePath().c_str(), "" );
    VFS.Mount( MgCore::GetHomePath().c_str(), "" );

    VFS.Mount( "data", "" );

    if(ogl_LoadFunctions() == ogl_LOAD_FAILED)
    {
        std::cout << "Error: glLoadGen failed to load.";
    }

    m_lis.handler = std::bind(&GameManager::event_handler, this, std::placeholders::_1);
    m_lis.mask = MgCore::EventType::Quit | MgCore::EventType::WindowSized | MgCore::EventType::MouseMove;

    m_events->add_listener(m_lis);

    m_fpsTime = 0.0;

    m_ss = std::cout.precision();

    glGenVertexArrays(1, &m_vao);
    glBindVertexArray(m_vao);

    MgCore::ShaderInfo vertInfo {GL_VERTEX_SHADER, "shaders/main.vs"};
    MgCore::ShaderInfo fragInfo {GL_FRAGMENT_SHADER, "shaders/main.fs"};

    MgCore::Shader vertShader(vertInfo);
    MgCore::Shader fragShader(fragInfo);

    m_program = std::make_unique<MgCore::ShaderProgram>(&vertShader, &fragShader);
    m_program->use();
    m_orthoID = m_program->uniform_attribute("ortho");

    m_texture = std::make_unique<MgCore::Texture>("icon.png", m_program.get());

    std::cout << (m_width / 37) * (m_height / 37) << std::endl;

    for (int x = 0; x < (m_width / 37); x++) {
        for (int y = 0; y < (m_height / 37); y++) {
            MeshPtr mesh = std::make_unique<MgCore::Mesh2D>(m_program.get(), m_texture.get());
            mesh->scale(32.0f, 32.0f);
            mesh->translate(x * 37.0f, y * 37.0f);
            m_meshes.push_back(std::move(mesh));
        }
    }

    m_ortho = glm::ortho(0.0f, static_cast<float>(m_width), static_cast<float>(m_height), 0.0f, -1.0f, 1.0f);

    m_program->set_uniform(m_orthoID, m_ortho);

    glClearColor(0.5, 0.5, 0.5, 1.0);
}

GameManager::~GameManager()
{

    glDeleteVertexArrays(1, &m_vao);
    m_window->make_current(nullptr);

}

void GameManager::start()
{

    while (m_running)
    {
        m_fpsTime += m_clock->tick();
        m_events->process();

        update();
        render();

        m_window->flip();
        if (m_fpsTime >= 2.0) {
            std::cout.precision (5);
            std::cout << "FPS: " << m_clock->get_fps() << std::endl;
            std::cout.precision (m_ss);
            m_fpsTime = 0;
        }
    }

}

void GameManager::resize(int width, int height)
{
    m_width = width;
    m_height = height;
    glViewport(0, 0, m_width, m_height);
    m_ortho = glm::ortho(0.0f, static_cast<float>(m_width), static_cast<float>(m_height), 0.0f, -1.0f, 1.0f);
    m_program->set_uniform(m_orthoID, m_ortho);

    int size = m_meshes.size();
    int newSize = (m_width/37) * (m_height/37);
    if (newSize > size) {
        m_meshes.resize(newSize);
    } else if (newSize < size) {
        while (m_meshes.size() != newSize) {
            m_meshes.pop_back();
        }
    }

    int i = 0;
    for (int y = 0; y < (m_height/37); y++) {
        for (int x = 0; x < (m_width/37); x++) {
            i = (y * (m_width/37) + x);
            if (i >= size) {
                MeshPtr mesh = std::make_unique<MgCore::Mesh2D>(m_program.get(), m_texture.get());
                m_meshes[i] = std::move(mesh);
            }
            m_meshes[i]->scale(32.0f, 32.0f);
            m_meshes[i]->translate(x * 37.0f, y * 37.0f);
        }
    }
}

bool GameManager::event_handler(MgCore::Event &event)
{
    MgCore::EventType type = event.type;
    switch(type) {
        case MgCore::EventType::Quit:
            m_running = false;
            break;
        case MgCore::EventType::MouseMove:
            m_mouseX = event.event.mouseMove.x;
            m_mouseY = event.event.mouseMove.y;
            //m_mesh->translate(static_cast<float>(m_mouseX), static_cast<float>(m_mouseY));
            break;
        case MgCore::EventType::WindowSized:
            resize(event.event.windowSized.width, event.event.windowSized.height);
            //std::cout << event.event.windowSized.width  << " "
            //          << event.event.windowSized.height << " "
            //          << event.event.windowSized.id     << std::endl;
            break;
        default:
            break;

    }
    return true;
}

void GameManager::update()
{
    for (auto& mesh : m_meshes) {
        mesh->update();
    }

}

void GameManager::render()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    m_program->use();
    for (auto& mesh : m_meshes) {
        mesh->render();
    }

}
<commit_msg>This change didn't get staged properly...<commit_after>#include <iostream>
#include <functional>
#include <utility>

#include "config.hpp"
#include "vfs.hpp"
#include "game.hpp"

GameManager::GameManager()
{
    m_width = 800;
    m_height = 600;
    m_fullscreen = false;
    m_title = "Game";

    m_window = std::unique_ptr<MgCore::Window>(new MgCore::Window(m_width, m_height, m_fullscreen, m_title));
    m_context = std::unique_ptr<MgCore::Context>(new MgCore::Context(3, 2, 0));
    m_events = std::unique_ptr<MgCore::Events>(new MgCore::Events());
    m_clock = std::unique_ptr<MgCore::FpsTimer>(new MgCore::FpsTimer());
    m_running = true;

    m_window->make_current(m_context.get());

    VFS.AddLoader(new ttvfs::DiskLoader);

    //
    // AppPath gets mounted on osx
    // BasePath gets mounted and overwrites any files similar to those in AppPath (data)
    // HomePath gets mounted and overwrites any files similar to those in BasePath (configs)
    // std::cout << MgCore::GetBasePath() << std::endl;
#if OSX_APP_BUNDLE
    VFS.Mount( MgCore::GetAppPath().c_str(), "" );
#endif
    VFS.Mount( MgCore::GetBasePath().c_str(), "" );
    VFS.Mount( MgCore::GetHomePath().c_str(), "" );

    VFS.Mount( "data", "" );

    if(ogl_LoadFunctions() == ogl_LOAD_FAILED)
    {
        std::cout << "Error: glLoadGen failed to load.";
    }

    m_lis.handler = std::bind(&GameManager::event_handler, this, std::placeholders::_1);
    m_lis.mask = MgCore::EventType::Quit | MgCore::EventType::WindowSized | MgCore::EventType::MouseMove;

    m_events->add_listener(m_lis);

    m_fpsTime = 0.0;

    m_ss = std::cout.precision();

    glGenVertexArrays(1, &m_vao);
    glBindVertexArray(m_vao);

    MgCore::ShaderInfo vertInfo {GL_VERTEX_SHADER, "shaders/main.vs"};
    MgCore::ShaderInfo fragInfo {GL_FRAGMENT_SHADER, "shaders/main.fs"};

    MgCore::Shader vertShader(vertInfo);
    MgCore::Shader fragShader(fragInfo);

    m_program = std::make_unique<MgCore::ShaderProgram>(&vertShader, &fragShader);
    m_program->use();
    m_orthoID = m_program->uniform_attribute("ortho");

    m_texture = std::make_unique<MgCore::Texture>("icon.png", m_program.get());

    std::cout << (m_width / 37) * (m_height / 37) << std::endl;

    for (int x = 0; x < (m_width / 37); x++) {
        for (int y = 0; y < (m_height / 37); y++) {
            MeshPtr mesh = std::make_unique<MgCore::Mesh2D>(m_program.get(), m_texture.get());
            mesh->scale(32.0f, 32.0f);
            mesh->translate(x * 37.0f, y * 37.0f);
            m_meshes.push_back(std::move(mesh));
        }
    }

    m_ortho = glm::ortho(0.0f, static_cast<float>(m_width), static_cast<float>(m_height), 0.0f, -1.0f, 1.0f);

    m_program->set_uniform(m_orthoID, m_ortho);

    glClearColor(0.5, 0.5, 0.5, 1.0);
}

GameManager::~GameManager()
{

    glDeleteVertexArrays(1, &m_vao);
    m_window->make_current(nullptr);

}

void GameManager::start()
{

    while (m_running)
    {
        m_fpsTime += m_clock->tick();
        m_events->process();

        update();
        render();

        m_window->flip();
        if (m_fpsTime >= 2.0) {
            std::cout.precision (5);
            std::cout << "FPS: " << m_clock->get_fps() << std::endl;
            std::cout.precision (m_ss);
            m_fpsTime = 0;
        }
    }

}

void GameManager::resize(int width, int height)
{
    m_width = width;
    m_height = height;
    glViewport(0, 0, m_width, m_height);
    m_ortho = glm::ortho(0.0f, static_cast<float>(m_width), static_cast<float>(m_height), 0.0f, -1.0f, 1.0f);
    m_program->set_uniform(m_orthoID, m_ortho);

    int size = m_meshes.size();
    int newSize = (m_width/37) * (m_height/37);
    if (newSize > size) {
        m_meshes.resize(newSize);
    } else if (newSize < size) {
        while (m_meshes.size() != newSize) {
            m_meshes.pop_back();
        }
    }

    int i = 0;
    for (int y = 0; y < (m_height/37); y++) {
        for (int x = 0; x < (m_width/37); x++) {
            i = (y * (m_width/37) + x);
            if (i >= size) {
                MeshPtr mesh = std::make_unique<MgCore::Mesh2D>(m_program.get(), m_texture.get());
                m_meshes[i] = std::move(mesh);
            }
            m_meshes[i]->scale(32.0f, 32.0f);
            m_meshes[i]->translate(x * 37.0f, y * 37.0f);
        }
    }
}

bool GameManager::event_handler(MgCore::Event &event)
{
    MgCore::EventType type = event.type;
    switch(type) {
        case MgCore::EventType::Quit:
            m_running = false;
            break;
        case MgCore::EventType::MouseMove:
            m_mouseX = event.event.mouseMove.x;
            m_mouseY = event.event.mouseMove.y;
            //m_mesh->translate(static_cast<float>(m_mouseX), static_cast<float>(m_mouseY));
            break;
        case MgCore::EventType::WindowSized:
            resize(event.event.windowSized.width, event.event.windowSized.height);
            //std::cout << event.event.windowSized.width  << " "
            //          << event.event.windowSized.height << " "
            //          << event.event.windowSized.id     << std::endl;
            break;
        default:
            break;

    }
    return true;
}

void GameManager::update()
{
    for (auto& mesh : m_meshes) {
        mesh->update();
    }

}

void GameManager::render()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    m_program->use();
    for (auto& mesh : m_meshes) {
        mesh->render();
    }

}
<|endoftext|>