<commit_before>/*
 * V1.cpp
 *
 *  Created on: Jul 30, 2008
 *      Author: rasmussn
 */

#include "../include/pv_common.h"
#include "../include/default_params.h"
#include "../connections/PVConnection.h"
#include "HyPerLayer.hpp"
#include "V1.hpp"

#include <assert.h>
#include <float.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

namespace PV
{

V1Params V1DefaultParams =
{
    V_REST, V_EXC, V_INH, V_INHB,            // V (mV)
    TAU_VMEM, TAU_EXC, TAU_INH, TAU_INHB,
    VTH_REST,  TAU_VTH, DELTA_VTH,	     // tau (ms)
    250, NOISE_AMP*( 1.0/TAU_EXC ) * ( ( TAU_INH * (V_REST-V_INH) + TAU_INHB * (V_REST-V_INHB) ) / (V_EXC-V_REST) ),
    250, NOISE_AMP*1.0,
    250, NOISE_AMP*1.0                       // noise (G)
};

V1::V1(const char* name, HyPerCol * hc)
  : HyPerLayer(name, hc)
{
   initialize(TypeV1Simple);
}

V1::V1(const char* name, HyPerCol * hc, PVLayerType type)
  : HyPerLayer(name, hc)
{
   initialize(type);
}

int V1::initialize(PVLayerType type)
{
   float time = 0.0f;

   setParams(parent->parameters(), &V1DefaultParams);

   pvlayer_setFuncs(clayer, (INIT_FN) &LIF2_init, (UPDATE_FN) &LIF2_update_exact_linear);
   this->clayer->layerType = type;

   parent->addLayer(this);

   if (parent->parameters()->value(name, "restart", 0) != 0) {
      readState(name, &time);
   }

   return 0;
}

int V1::setParams(PVParams * params, V1Params * p)
{
   float dt = .001 * parent->getDeltaTime();  // seconds

   clayer->params = (float *) malloc(sizeof(*p));
   assert(clayer->params != NULL);
   memcpy(clayer->params, p, sizeof(*p));

   clayer->numParams = sizeof(*p) / sizeof(float);
   assert(clayer->numParams == 17);

   V1Params * cp = (V1Params *) clayer->params;

   if (params->present(name, "Vrest")) cp->Vrest = params->value(name, "Vrest");
   if (params->present(name, "Vexc"))  cp->Vexc  = params->value(name, "Vexc");
   if (params->present(name, "Vinh"))  cp->Vinh  = params->value(name, "Vinh");
   if (params->present(name, "VinhB")) cp->VinhB = params->value(name, "VinhB");

   if (params->present(name, "tau"))   cp->tau   = params->value(name, "tau");
   if (params->present(name, "tauE"))  cp->tauE  = params->value(name, "tauE");
   if (params->present(name, "tauI"))  cp->tauI  = params->value(name, "tauI");
   if (params->present(name, "tauIB")) cp->tauIB = params->value(name, "tauIB");

   if (params->present(name, "VthRest"))  cp->VthRest  = params->value(name, "VthRest");
   if (params->present(name, "tauVth"))   cp->tauVth   = params->value(name, "tauVth");
   if (params->present(name, "deltaVth")) cp->deltaVth = params->value(name, "deltaVth");

   if (params->present(name, "noiseAmpE"))   cp->noiseAmpE   = params->value(name, "noiseAmpE");
   if (params->present(name, "noiseAmpI"))   cp->noiseAmpI   = params->value(name, "noiseAmpI");
   if (params->present(name, "noiseAmpIB"))  cp->noiseAmpIB  = params->value(name, "noiseAmpIB");

   if (params->present(name, "noiseFreqE")) {
      cp->noiseFreqE  = params->value(name, "noiseFreqE");
      if (dt * cp->noiseFreqE > 1.0) cp->noiseFreqE = 1.0 / dt;
   }
   if (params->present(name, "noiseFreqI")) {
      cp->noiseFreqI  = params->value(name, "noiseFreqI");
      if (dt * cp->noiseFreqI > 1.0) cp->noiseFreqI = 1.0 / dt;
   }
   if (params->present(name, "noiseFreqIB")) {
      cp->noiseFreqIB = params->value(name, "noiseFreqIB");
      if (dt * cp->noiseFreqIB > 1.0) cp->noiseFreqIB = 1.0 / dt;
   }

   return 0;
}

int V1::updateState(float time, float dt)
{
   PVParams * params = parent->parameters();
   int spikingFlag = 1;

   pv_debug_info("[%d]: V1::updateState:", clayer->columnId);

   if (params->present(name, "spikingFlag")) {
      spikingFlag = params->value(name, "spikingFlag");
   }

   if (spikingFlag != 0) {
      return LIF2_update_exact_linear(clayer, dt);
   }

   // just copy accumulation buffer to membrane potential
   // and activity buffer (nonspiking)

   const int nx = clayer->loc.nx;
   const int ny = clayer->loc.ny;
   const int nf = clayer->numFeatures;
   const int marginWidth = clayer->loc.nPad;

   pvdata_t * V = clayer->V;
   pvdata_t * phiExc   = clayer->phi[PHI_EXC];
   pvdata_t * phiInh   = clayer->phi[PHI_INH];
   pvdata_t * activity = clayer->activity->data;

   // make sure activity in border is zero
   //
   for (int k = 0; k < clayer->numExtended; k++) {
      activity[k] = 0.0;
   }

   for (int k = 0; k < clayer->numNeurons; k++) {
      int kex = kIndexExtended(k, nx, ny, nf, marginWidth);
      V[k] = phiExc[k] - phiInh[k];
      activity[kex] = V[k];

      // reset accumulation buffers
      phiExc[k] = 0.0;
      phiInh[k] = 0.0;
   }

   return 0;
}

int V1::writeState(const char * path, float time)
{
   HyPerLayer::writeState(path, time);

#ifdef DEBUG_OUTPUT
   // print activity at center of image

   int sx = clayer->numFeatures;
   int sy = sx*clayer->loc.nx;
   pvdata_t * a = clayer->activity->data;

   int n = (int) (sy*(clayer->loc.ny/2 - 1) + sx*(clayer->loc.nx/2));
   for (int f = 0; f < clayer->numFeatures; f++) {
      printf("f = %d, a[%d] = %f\n", f, n, a[n]);
      n += 1;
   }
   printf("\n");

   n = (int) (sy*(clayer->loc.ny/2 - 1) + sx*(clayer->loc.nx/2));
   n -= 8;
   for (int f = 0; f < clayer->numFeatures; f++) {
      printf("f = %d, a[%d] = %f\n", f, n, a[n]);
      n += 1;
   }
#endif

   return 0;
}

int V1::findPostSynaptic(int dim, int maxSize, int col,
// input: which layer, which neuron
		HyPerLayer *lSource, float pos[],

		// output: how many of our neurons are connected.
		// an array with their indices.
		// an array with their feature vectors.
		int* nNeurons, int nConnectedNeurons[], float *vPos)
{
	return 0;
}

} // namespace PV
<commit_msg>Casts (and the like, mostly to ints) to remove compiler warnings on Lobo.<commit_after>/*
 * V1.cpp
 *
 *  Created on: Jul 30, 2008
 *      Author: rasmussn
 */

#include "../include/pv_common.h"
#include "../include/default_params.h"
#include "../connections/PVConnection.h"
#include "HyPerLayer.hpp"
#include "V1.hpp"

#include <assert.h>
#include <float.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

namespace PV
{

V1Params V1DefaultParams =
{
    V_REST, V_EXC, V_INH, V_INHB,            // V (mV)
    TAU_VMEM, TAU_EXC, TAU_INH, TAU_INHB,
    VTH_REST,  TAU_VTH, DELTA_VTH,	     // tau (ms)
    250, NOISE_AMP*( 1.0/TAU_EXC ) * ( ( TAU_INH * (V_REST-V_INH) + TAU_INHB * (V_REST-V_INHB) ) / (V_EXC-V_REST) ),
    250, NOISE_AMP*1.0,
    250, NOISE_AMP*1.0                       // noise (G)
};

V1::V1(const char* name, HyPerCol * hc)
  : HyPerLayer(name, hc)
{
   initialize(TypeV1Simple);
}

V1::V1(const char* name, HyPerCol * hc, PVLayerType type)
  : HyPerLayer(name, hc)
{
   initialize(type);
}

int V1::initialize(PVLayerType type)
{
   float time = 0.0f;

   setParams(parent->parameters(), &V1DefaultParams);

   pvlayer_setFuncs(clayer, (INIT_FN) &LIF2_init, (UPDATE_FN) &LIF2_update_exact_linear);
   this->clayer->layerType = type;

   parent->addLayer(this);

   if (parent->parameters()->value(name, "restart", 0) != 0) {
      readState(name, &time);
   }

   return 0;
}

int V1::setParams(PVParams * params, V1Params * p)
{
   float dt = .001 * parent->getDeltaTime();  // seconds

   clayer->params = (float *) malloc(sizeof(*p));
   assert(clayer->params != NULL);
   memcpy(clayer->params, p, sizeof(*p));

   clayer->numParams = sizeof(*p) / sizeof(float);
   assert(clayer->numParams == 17);

   V1Params * cp = (V1Params *) clayer->params;

   if (params->present(name, "Vrest")) cp->Vrest = params->value(name, "Vrest");
   if (params->present(name, "Vexc"))  cp->Vexc  = params->value(name, "Vexc");
   if (params->present(name, "Vinh"))  cp->Vinh  = params->value(name, "Vinh");
   if (params->present(name, "VinhB")) cp->VinhB = params->value(name, "VinhB");

   if (params->present(name, "tau"))   cp->tau   = params->value(name, "tau");
   if (params->present(name, "tauE"))  cp->tauE  = params->value(name, "tauE");
   if (params->present(name, "tauI"))  cp->tauI  = params->value(name, "tauI");
   if (params->present(name, "tauIB")) cp->tauIB = params->value(name, "tauIB");

   if (params->present(name, "VthRest"))  cp->VthRest  = params->value(name, "VthRest");
   if (params->present(name, "tauVth"))   cp->tauVth   = params->value(name, "tauVth");
   if (params->present(name, "deltaVth")) cp->deltaVth = params->value(name, "deltaVth");

   if (params->present(name, "noiseAmpE"))   cp->noiseAmpE   = params->value(name, "noiseAmpE");
   if (params->present(name, "noiseAmpI"))   cp->noiseAmpI   = params->value(name, "noiseAmpI");
   if (params->present(name, "noiseAmpIB"))  cp->noiseAmpIB  = params->value(name, "noiseAmpIB");

   if (params->present(name, "noiseFreqE")) {
      cp->noiseFreqE  = params->value(name, "noiseFreqE");
      if (dt * cp->noiseFreqE > 1.0) cp->noiseFreqE = 1.0 / dt;
   }
   if (params->present(name, "noiseFreqI")) {
      cp->noiseFreqI  = params->value(name, "noiseFreqI");
      if (dt * cp->noiseFreqI > 1.0) cp->noiseFreqI = 1.0 / dt;
   }
   if (params->present(name, "noiseFreqIB")) {
      cp->noiseFreqIB = params->value(name, "noiseFreqIB");
      if (dt * cp->noiseFreqIB > 1.0) cp->noiseFreqIB = 1.0 / dt;
   }

   return 0;
}

int V1::updateState(float time, float dt)
{
   PVParams * params = parent->parameters();

   pv_debug_info("[%d]: V1::updateState:", clayer->columnId);

   int spikingFlag = (int) params->value(name, "spikingFlag", 1);

   if (spikingFlag != 0) {
      return LIF2_update_exact_linear(clayer, dt);
   }

   // just copy accumulation buffer to membrane potential
   // and activity buffer (nonspiking)

   const int nx = clayer->loc.nx;
   const int ny = clayer->loc.ny;
   const int nf = clayer->numFeatures;
   const int marginWidth = clayer->loc.nPad;

   pvdata_t * V = clayer->V;
   pvdata_t * phiExc   = clayer->phi[PHI_EXC];
   pvdata_t * phiInh   = clayer->phi[PHI_INH];
   pvdata_t * activity = clayer->activity->data;

   // make sure activity in border is zero
   //
   for (int k = 0; k < clayer->numExtended; k++) {
      activity[k] = 0.0;
   }

   for (int k = 0; k < clayer->numNeurons; k++) {
      int kex = kIndexExtended(k, nx, ny, nf, marginWidth);
      V[k] = phiExc[k] - phiInh[k];
      activity[kex] = V[k];

      // reset accumulation buffers
      phiExc[k] = 0.0;
      phiInh[k] = 0.0;
   }

   return 0;
}

int V1::writeState(const char * path, float time)
{
   HyPerLayer::writeState(path, time);

#ifdef DEBUG_OUTPUT
   // print activity at center of image

   int sx = clayer->numFeatures;
   int sy = sx*clayer->loc.nx;
   pvdata_t * a = clayer->activity->data;

   int n = (int) (sy*(clayer->loc.ny/2 - 1) + sx*(clayer->loc.nx/2));
   for (int f = 0; f < clayer->numFeatures; f++) {
      printf("f = %d, a[%d] = %f\n", f, n, a[n]);
      n += 1;
   }
   printf("\n");

   n = (int) (sy*(clayer->loc.ny/2 - 1) + sx*(clayer->loc.nx/2));
   n -= 8;
   for (int f = 0; f < clayer->numFeatures; f++) {
      printf("f = %d, a[%d] = %f\n", f, n, a[n]);
      n += 1;
   }
#endif

   return 0;
}

int V1::findPostSynaptic(int dim, int maxSize, int col,
// input: which layer, which neuron
		HyPerLayer *lSource, float pos[],

		// output: how many of our neurons are connected.
		// an array with their indices.
		// an array with their feature vectors.
		int* nNeurons, int nConnectedNeurons[], float *vPos)
{
	return 0;
}

} // namespace PV
<|endoftext|>


<commit_before>#include <iostream>
#include <fstream>
#include <boost/program_options.hpp>

#include "schedule.h"
#include "actions.h"
#include "group_cache.h"
#include "display/line_display.h"

namespace po = boost::program_options;

po::variables_map GetSettings(int argc, char **argv) {
    // Visible options
    po::options_description visibleOptions("Command line options");
    visibleOptions.add_options()
            ("help,h", "display help")
            ("renew-cache,rc", "renew group cache");;

    // Hidden option (to specify action)
    po::options_description HiddenOptions("Hidden options");
    HiddenOptions.add_options()
            ("action", po::value<std::string>(), "action");

    // Common options (cli + config file)
    po::options_description commonOptions("Command line or config file options");
    commonOptions.add_options()
            ("output,o", po::value<std::string>()->default_value("line"), "display help")
            ("group,g", po::value<std::string>(), "set the group used for the request");

    // Create cli options from visible and hidden options
    po::options_description cliOptions;
    cliOptions.add(commonOptions).add(visibleOptions).add(HiddenOptions);

    // Set action as a positional argument
    po::positional_options_description op;
    op.add("action", -1);

    // Create settings map
    po::variables_map settings;
    po::store(po::command_line_parser(argc, argv).
            options(cliOptions).positional(op).run(), settings);
    po::notify(settings);

    // Config file parsing
    po::options_description fileOptions;
    fileOptions.add(commonOptions);
    std::string configPath;
    configPath += getenv("HOME");
    configPath += "/.chronosrc";
    std::ifstream ifs(configPath.c_str());
    if (ifs) {
        store(po::parse_config_file(ifs, fileOptions), settings);
        notify(settings);
    }

    // Display help
    if (settings.count("help") || argc == 1) {
        std::cout << commonOptions;
        std::cout << visibleOptions << std::endl;
        exit(1);
    }
    return settings;
}

int main(int argc, char *argv[]) {

    // Get settings
    po::variables_map settings;
    try {
        settings = GetSettings(argc, argv);
    }
    catch (int e) {
        std::cout << "Error " << e << ": config parsing error" << std::endl;
        exit(1);
    }

    // Check for mandatory settings
    if (settings.count("action") != 1) {
        std::cout << "Error: you need to specify an action";
    }
    if (settings.count("group") != 1) {
        std::cout << "Error: you need to specify a group in your config file or as an argument";
    }

    // Check if need to renew cache
    if (settings.count("renew-cache")) {
        GroupCache::RenewCache();
    }

    std::vector<Group> groupsList = GroupCache::GetGroupeCache();

    // Get action and call the correct function
    Actions::ScheduleActions action = Actions::GetAction(settings["action"].as<std::string>());
    Group g = GroupCache::GetGroupeName(settings["group"].as<std::string>(), groupsList);
    std::vector<Event> schedule;
    if (action == Actions::ScheduleActions::Today) {
        schedule = Schedule::GetToday(g);
    }
    else if (action == Actions::ScheduleActions::Week)
    {
        schedule = Schedule::GetCurrentWeek(g);
    }
    else if (action == Actions::ScheduleActions::Next)
    {
        schedule = Schedule::GetNext(g);
    }

    // Print according to the given printer
    Display::OutputSystems outputSystem = Display::GetOutput(settings["output"].as<std::string>());
    if (outputSystem == Display::OutputSystems::Line)
    {
        LineDisplay::Print(schedule);
    }
    /*else if (outputSystem == Display::OutputSystems::Ascii)
    {
        AsciiDisplay::Print(schedule);
    }*/
    return 0;
}<commit_msg>Better errors messages when catching config parsing errors<commit_after>#include <iostream>
#include <fstream>
#include <boost/program_options.hpp>

#include "schedule.h"
#include "actions.h"
#include "group_cache.h"
#include "display/line_display.h"

namespace po = boost::program_options;

po::variables_map GetSettings(int argc, char **argv) {
    // Visible options
    po::options_description visibleOptions("Command line options");
    visibleOptions.add_options()
            ("help,h", "display help")
            ("renew-cache,rc", "renew group cache");;

    // Hidden option (to specify action)
    po::options_description HiddenOptions("Hidden options");
    HiddenOptions.add_options()
            ("action", po::value<std::string>(), "action");

    // Common options (cli + config file)
    po::options_description commonOptions("Command line or config file options");
    commonOptions.add_options()
            ("output,o", po::value<std::string>()->default_value("line"), "display help")
            ("group,g", po::value<std::string>(), "set the group used for the request");

    // Create cli options from visible and hidden options
    po::options_description cliOptions;
    cliOptions.add(commonOptions).add(visibleOptions).add(HiddenOptions);

    // Set action as a positional argument
    po::positional_options_description op;
    op.add("action", -1);

    // Create settings map
    po::variables_map settings;
    po::store(po::command_line_parser(argc, argv).
            options(cliOptions).positional(op).run(), settings);
    po::notify(settings);

    // Config file parsing
    po::options_description fileOptions;
    fileOptions.add(commonOptions);
    std::string configPath;
    configPath += getenv("HOME");
    configPath += "/.chronosrc";
    std::ifstream ifs(configPath.c_str());
    if (ifs) {
        store(po::parse_config_file(ifs, fileOptions), settings);
        notify(settings);
    }

    // Display help
    if (settings.count("help") || argc == 1) {
        std::cout << commonOptions;
        std::cout << visibleOptions << std::endl;
        exit(1);
    }
    return settings;
}

int main(int argc, char *argv[]) {

    // Get settings
    po::variables_map settings;
    try {
        settings = GetSettings(argc, argv);
    }
    catch (po::error& e) {
        std::cout << e.what() << std::endl;
        exit(1);
    }

    // Check for mandatory settings
    if (settings.count("action") != 1) {
        std::cout << "Error: you need to specify an action";
    }
    if (settings.count("group") != 1) {
        std::cout << "Error: you need to specify a group in your config file or as an argument";
    }

    // Check if need to renew cache
    if (settings.count("renew-cache")) {
        GroupCache::RenewCache();
    }

    std::vector<Group> groupsList = GroupCache::GetGroupeCache();

    // Get action and call the correct function
    Actions::ScheduleActions action = Actions::GetAction(settings["action"].as<std::string>());
    Group g = GroupCache::GetGroupeName(settings["group"].as<std::string>(), groupsList);
    std::vector<Event> schedule;
    if (action == Actions::ScheduleActions::Today) {
        schedule = Schedule::GetToday(g);
    }
    else if (action == Actions::ScheduleActions::Week)
    {
        schedule = Schedule::GetCurrentWeek(g);
    }
    else if (action == Actions::ScheduleActions::Next)
    {
        schedule = Schedule::GetNext(g);
    }

    // Print according to the given printer
    Display::OutputSystems outputSystem = Display::GetOutput(settings["output"].as<std::string>());
    if (outputSystem == Display::OutputSystems::Line)
    {
        LineDisplay::Print(schedule);
    }
    /*else if (outputSystem == Display::OutputSystems::Ascii)
    {
        AsciiDisplay::Print(schedule);
    }*/
    return 0;
}<|endoftext|>


<commit_before>#include "ten/task/qutex.hh"
#include "proc.hh"

namespace ten {

void qutex::lock() {
    task *t = this_proc()->ctask;
    DCHECK(t) << "BUG: qutex::lock called outside of task";
    {
        std::unique_lock<std::timed_mutex> lk{_m};
        DCHECK(_owner != t) << "no recursive locking";
        if (_owner == nullptr) {
            _owner = t;
            DVLOG(5) << "LOCK qutex: " << this << " owner: " << _owner;
            return;
        }
        DVLOG(5) << "QUTEX[" << this << "] lock waiting add: " << t <<  " owner: " << _owner;
        _waiting.push_back(t);
    }

    // loop to handle spurious wakeups from other threads
    for (;;) {
        DCHECK(t->cancel_points == 0) << "BUG: cannot cancel a lock";
        t->swap();
        std::unique_lock<std::timed_mutex> lk{_m};
        if (_owner == this_proc()->ctask) {
            break;
        }
    }
}

bool qutex::try_lock() {
    task *t = this_proc()->ctask;
    DCHECK(t) << "BUG: qutex::try_lock called outside of task";
    std::unique_lock<std::timed_mutex> lk{_m, std::try_to_lock};
    if (lk.owns_lock()) {
        if (_owner == nullptr) {
            _owner = t;
            return true;
        }
    }
    return false;
}

void qutex::unlock() {
    std::unique_lock<std::timed_mutex> lk{_m};
    task *t = this_proc()->ctask;
    DCHECK(lk.owns_lock()) << "BUG: lock not owned " << t;
    DVLOG(5) << "QUTEX[" << this << "] unlock: " << t;
    DCHECK(t == _owner) << "BUG: lock not owned by this task";
    if (!_waiting.empty()) {
        t = _owner = _waiting.front();
        _waiting.pop_front();
    } else {
        t = _owner = nullptr;
    }
    DVLOG(5) << "UNLOCK qutex: " << this
        << " new owner: " << _owner
        << " waiting: " << _waiting.size();
    lk.unlock();
    // must use t here, not owner because
    // lock has been released
    if (t) t->ready();
}

} // namespace
<commit_msg>more debug checks<commit_after>#include "ten/task/qutex.hh"
#include "proc.hh"

namespace ten {

void qutex::lock() {
    task *t = this_proc()->ctask;
    DCHECK(t->cancel_points == 0) << "BUG: cannot cancel a lock";
    DCHECK(t) << "BUG: qutex::lock called outside of task";
    {
        std::unique_lock<std::timed_mutex> lk{_m};
        DCHECK(_owner != t) << "no recursive locking";
        if (_owner == nullptr) {
            _owner = t;
            DVLOG(5) << "LOCK qutex: " << this << " owner: " << _owner;
            return;
        }
        DVLOG(5) << "QUTEX[" << this << "] lock waiting add: " << t <<  " owner: " << _owner;
        _waiting.push_back(t);
    }

    // loop to handle spurious wakeups from other threads
    for (;;) {
        DCHECK(t->cancel_points == 0) << "BUG: cannot cancel a lock";
        t->swap();
        std::unique_lock<std::timed_mutex> lk{_m};
        if (_owner == this_proc()->ctask) {
            break;
        }
    }
}

bool qutex::try_lock() {
    task *t = this_proc()->ctask;
    DCHECK(t) << "BUG: qutex::try_lock called outside of task";
    std::unique_lock<std::timed_mutex> lk{_m, std::try_to_lock};
    if (lk.owns_lock()) {
        if (_owner == nullptr) {
            _owner = t;
            return true;
        }
    }
    return false;
}

void qutex::unlock() {
    std::unique_lock<std::timed_mutex> lk{_m};
    task *t = this_proc()->ctask;
    DCHECK(lk.owns_lock()) << "BUG: lock not owned " << t;
    DVLOG(5) << "QUTEX[" << this << "] unlock: " << t;
    DCHECK(t == _owner) << "BUG: lock not owned by this task";
    if (!_waiting.empty()) {
        t = _owner = _waiting.front();
        _waiting.pop_front();
    } else {
        t = _owner = nullptr;
    }
    DVLOG(5) << "UNLOCK qutex: " << this
        << " new owner: " << _owner
        << " waiting: " << _waiting.size();
    lk.unlock();
    // must use t here, not owner because
    // lock has been released
    if (t) t->ready();
}

} // namespace
<|endoftext|>


<commit_before>//===--------------------- LLDBAssert.cpp ------------------------*- C++-*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "lldb/Utility/LLDBAssert.h"

#include "llvm/Support/Format.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/raw_ostream.h"

using namespace llvm;
using namespace lldb_private;

void lldb_private::lldb_assert(bool expression, const char *expr_text,
                               const char *func, const char *file,
                               unsigned int line) {
  if (expression)
    ;
  else {
    errs() << format("Assertion failed: (%s), function %s, file %s, line %u\n",
                     expr_text, func, file, line);
    errs() << "backtrace leading to the failure:\n";
    llvm::sys::PrintStackTrace(errs());
    errs() << "please file a bug report against lldb reporting this failure "
              "log, and as many details as possible\n";
  }
}
<commit_msg>Terminate debugger if an assert was hit<commit_after>//===--------------------- LLDBAssert.cpp ------------------------*- C++-*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "lldb/Utility/LLDBAssert.h"

#include "llvm/Support/Format.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/raw_ostream.h"

using namespace llvm;
using namespace lldb_private;

void lldb_private::lldb_assert(bool expression, const char *expr_text,
                               const char *func, const char *file,
                               unsigned int line) {
  if (LLVM_LIKELY(expression))
    return;

  errs() << format("Assertion failed: (%s), function %s, file %s, line %u\n",
                   expr_text, func, file, line);
  errs() << "backtrace leading to the failure:\n";
  llvm::sys::PrintStackTrace(errs());
  errs() << "please file a bug report against lldb reporting this failure "
            "log, and as many details as possible\n";
  abort();
}
<|endoftext|>


<commit_before>/*!
    \file launcher.cpp
    \brief Launcher base implementation
    \author Ivan Shynkarenka
    \date 07.07.2015
    \copyright MIT License
*/

#include "benchmark/launcher.h"

#include <algorithm>
#include <regex>

namespace CppBenchmark {

void Launcher::Launch(const std::string& pattern)
{
    int current = 0;
    int total = 0;
    std::vector<std::shared_ptr<BenchmarkBase>> benchmarks;

    // Build pending benchmark
    for (auto& builder : _builders)
        AddBenchmark(builder());

    // Filter benchmarks
    std::regex matcher(pattern);
    for (auto& benchmark : _benchmarks)
    {
        // Match benchmark name with the given pattern
        if (pattern.empty() || std::regex_match(benchmark->name(), matcher))
        {
            total += benchmark->CountLaunches();
            benchmarks.push_back(benchmark);
        }
    }

    // Launch filtered benchmarks
    for (auto& benchmark : benchmarks)
        benchmark->Launch(current, total, *this);
}

void Launcher::Report(Reporter& reporter) const
{
    // Report header, system & environment
    reporter.ReportHeader();
    reporter.ReportSystem();
    reporter.ReportEnvironment();
    reporter.ReportBenchmarksHeader();

    // For all registered benchmarks...
    for (auto& benchmark : _benchmarks)
    {
        // Filter performed benchmarks
        if (benchmark->_launched)
        {
            // Report benchmark results
            reporter.ReportBenchmarkHeader();
            reporter.ReportBenchmark(*benchmark, benchmark->settings());
            reporter.ReportPhasesHeader();
            for (auto& root_phase : benchmark->_phases)
                ReportPhase(reporter, *root_phase, root_phase->name());
            reporter.ReportPhasesFooter();
            reporter.ReportBenchmarkFooter();
        }
    }

    // Report footer
    reporter.ReportBenchmarksFooter();
    reporter.ReportFooter();
}

void Launcher::ReportPhase(Reporter& reporter, const PhaseCore& phase, const std::string& name) const
{
    reporter.ReportPhaseHeader();
    reporter.ReportPhase(phase, phase.metrics());
    reporter.ReportPhaseFooter();
    for (auto& child : phase._child)
    {
        std::string child_name = name + "." + child->name();
        ReportPhase(reporter, *child, child_name);
    }
}

void Launcher::ReportHistograms(int32_t resolution) const
{
    // For all registered benchmarks...
    for (auto& benchmark : _benchmarks)
    {
        // Filter performed benchmarks
        if (benchmark->_launched)
        {
            // Report benchmark histograms
            for (auto& root_phase : benchmark->_phases)
                ReportPhaseHistograms(resolution, *root_phase, root_phase->name());
        }
    }
}

void Launcher::ReportPhaseHistograms(int32_t resolution, const PhaseCore& phase, const std::string& name) const
{
    ReportPhaseHistogram(resolution, phase, name);
    for (auto& child : phase._child)
    {
        std::string child_name = name + "." + child->name();
        ReportPhaseHistograms(resolution, *child, child_name);
    }
}

void Launcher::ReportPhaseHistogram(int32_t resolution, const PhaseCore& phase, const std::string& name) const
{
    if (phase.metrics().latency())
    {
        const char deprecated[] = "\\/?%*:|\"<>";

        // Validate filename
        std::string filename(name + ".hdr");
        for (auto& ch : filename)
            if ((ch != '\\') && (ch != '/') && (std::find(deprecated, deprecated + sizeof(deprecated), ch) != (deprecated + sizeof(deprecated))))
                ch = '_';

        // Open histogram filename
        FILE* file = fopen(filename.c_str(), "w");
        if (file != nullptr)
        {
            // Print histogram
            phase.PrintLatencyHistogram(file, resolution);

            // Close file
            fclose(file);
        }
    }
}

} // namespace CppBenchmark
<commit_msg>bugfixes<commit_after>/*!
    \file launcher.cpp
    \brief Launcher base implementation
    \author Ivan Shynkarenka
    \date 07.07.2015
    \copyright MIT License
*/

#include "benchmark/launcher.h"

#include <algorithm>
#include <regex>

namespace CppBenchmark {

void Launcher::Launch(const std::string& pattern)
{
    int current = 0;
    int total = 0;
    std::vector<std::shared_ptr<BenchmarkBase>> benchmarks;

    // Build pending benchmark
    for (auto& builder : _builders)
        if (builder)
            AddBenchmark(builder());

    // Filter benchmarks
    std::regex matcher(pattern);
    for (auto& benchmark : _benchmarks)
    {
        // Match benchmark name with the given pattern
        if (pattern.empty() || std::regex_match(benchmark->name(), matcher))
        {
            total += benchmark->CountLaunches();
            benchmarks.push_back(benchmark);
        }
    }

    // Launch filtered benchmarks
    for (auto& benchmark : benchmarks)
        benchmark->Launch(current, total, *this);
}

void Launcher::Report(Reporter& reporter) const
{
    // Report header, system & environment
    reporter.ReportHeader();
    reporter.ReportSystem();
    reporter.ReportEnvironment();
    reporter.ReportBenchmarksHeader();

    // For all registered benchmarks...
    for (auto& benchmark : _benchmarks)
    {
        // Filter performed benchmarks
        if (benchmark->_launched)
        {
            // Report benchmark results
            reporter.ReportBenchmarkHeader();
            reporter.ReportBenchmark(*benchmark, benchmark->settings());
            reporter.ReportPhasesHeader();
            for (auto& root_phase : benchmark->_phases)
                ReportPhase(reporter, *root_phase, root_phase->name());
            reporter.ReportPhasesFooter();
            reporter.ReportBenchmarkFooter();
        }
    }

    // Report footer
    reporter.ReportBenchmarksFooter();
    reporter.ReportFooter();
}

void Launcher::ReportPhase(Reporter& reporter, const PhaseCore& phase, const std::string& name) const
{
    reporter.ReportPhaseHeader();
    reporter.ReportPhase(phase, phase.metrics());
    reporter.ReportPhaseFooter();
    for (auto& child : phase._child)
    {
        std::string child_name = name + "." + child->name();
        ReportPhase(reporter, *child, child_name);
    }
}

void Launcher::ReportHistograms(int32_t resolution) const
{
    // For all registered benchmarks...
    for (auto& benchmark : _benchmarks)
    {
        // Filter performed benchmarks
        if (benchmark->_launched)
        {
            // Report benchmark histograms
            for (auto& root_phase : benchmark->_phases)
                ReportPhaseHistograms(resolution, *root_phase, root_phase->name());
        }
    }
}

void Launcher::ReportPhaseHistograms(int32_t resolution, const PhaseCore& phase, const std::string& name) const
{
    ReportPhaseHistogram(resolution, phase, name);
    for (auto& child : phase._child)
    {
        std::string child_name = name + "." + child->name();
        ReportPhaseHistograms(resolution, *child, child_name);
    }
}

void Launcher::ReportPhaseHistogram(int32_t resolution, const PhaseCore& phase, const std::string& name) const
{
    if (phase.metrics().latency())
    {
        const char deprecated[] = "\\/?%*:|\"<>";

        // Validate filename
        std::string filename(name + ".hdr");
        for (auto& ch : filename)
            if ((ch != '\\') && (ch != '/') && (std::find(deprecated, deprecated + sizeof(deprecated), ch) != (deprecated + sizeof(deprecated))))
                ch = '_';

        // Open histogram filename
        FILE* file = fopen(filename.c_str(), "w");
        if (file != nullptr)
        {
            // Print histogram
            phase.PrintLatencyHistogram(file, resolution);

            // Close file
            fclose(file);
        }
    }
}

} // namespace CppBenchmark
<|endoftext|>


<commit_before>#include "stdafx.h"
#include <windows.h>
#include "pwdPopUp.h"

_PWDHANDLES pwdHandles;
_PWDAXIS pwdBtns[2];
_PWDAXIS pwdEditInputField[1];
_PWDCOORDINATES pwdCoordinates;
TCHAR windowTitle[MAXCHAR] = L"";
TCHAR drawTextMessage[MAXCHAR] = L"";
TCHAR passwordValue[MAXCHAR] = L"";
bool isExitPasswordNeedToBeDone = false;
bool isEnteredPasswordCorrect = false;
bool isWMDevice = false;

BOOL IsDeviceInLandScape(){
  DEVMODE devmode;
  ZeroMemory(&devmode, sizeof(DEVMODE));
  devmode.dmSize = sizeof(DEVMODE);
  devmode.dmDisplayOrientation = DMDO_0;
  devmode.dmFields = DM_DISPLAYORIENTATION;
  ChangeDisplaySettingsEx(NULL, &devmode, NULL, CDS_TEST, NULL);

  return ((devmode.dmDisplayOrientation == DMDO_90) || (devmode.dmDisplayOrientation == DMDO_270));
}
BOOL IsDeviceInPortrait(){
  DEVMODE devmode;
  ZeroMemory(&devmode, sizeof(DEVMODE));
  devmode.dmSize = sizeof(DEVMODE);
  devmode.dmDisplayOrientation = DMDO_0;
  devmode.dmFields = DM_DISPLAYORIENTATION;
  ChangeDisplaySettingsEx(NULL, &devmode, NULL, CDS_TEST, NULL);

  return ((devmode.dmDisplayOrientation == DMDO_0) || (devmode.dmDisplayOrientation == DMDO_180));
}

ATOM PwdMyRegisterClass(HINSTANCE hInstance){
	WNDCLASS wcx; // WINDOW class information
	if (!GetClassInfo(hInstance, L"CheckPassword", &wcx))
	{
		//Initialize the struct to zero
		ZeroMemory(&wcx,sizeof(WNDCLASS));
		wcx.style = 0; //CS_HREDRAW|CS_VREDRAW |CS_DBLCLKS ; // Class styles
		wcx.lpfnWndProc = (WNDPROC)PwdMainWndProc; // Pointer to the callback procedure
		wcx.cbClsExtra = 0; // Extra byte to allocate following the wndclassex structure
		wcx.cbWndExtra = 0; // Extra byte to allocate following an instance of the structure
		wcx.hInstance = hInstance; // Instance of the application
		wcx.hIcon = NULL; // Class Icon
		wcx.hCursor = 0; //LoadCursor(NULL, IDC_ARROW); // Class Cursor
		wcx.hbrBackground = (HBRUSH) GetStockObject(WHITE_BRUSH); // Background brush
		wcx.lpszMenuName = NULL; // Menu resource
		wcx.lpszClassName = L"CheckPassword"; // Name of this class
		wcx.hIcon = NULL; // Small icon for this class
		return RegisterClass(&wcx);
	}
	return TRUE;
}

BOOL PwdInitInstance(HWND hWnd, HINSTANCE hInstance){

	// Create the window
	pwdHandles.parent = CreateWindow(L"CheckPassword", // Window class name
			windowTitle, // Window title
			WS_POPUP | WS_CAPTION, // Window style
			(pwdCoordinates.xCenter-pwdCoordinates.mainWndXpos/2),(pwdCoordinates.yCenter-pwdCoordinates.mainWndYpos/2),//1200,730, // (x,y) pos of the window
			pwdCoordinates.mainWndXpos,pwdCoordinates.mainWndYpos + 30, // Width and height of the window
			hWnd,//HWND_DESKTOP, // HWND of the parent window (can be null also)
			NULL, // Handle to menu
			pwdHandles.hInstance, // Handle to application instance
			NULL); // Pointer to window creation data

	// Check if window creation was successful
	if (!pwdHandles.parent)
		return 0;

	// Make the window visible
	ShowWindow(pwdHandles.parent,SW_SHOW);
	UpdateWindow(pwdHandles.parent);

	return TRUE;
}

VOID PwdCreateButtons(HWND hwnd){
	pwdHandles.parent = hwnd;
	HWND *buttons = &(pwdHandles.okButton);
	for(int i = 0; i < 2; i++){
		*buttons = CreateWindowEx(WS_EX_CLIENTEDGE,
								   L"button", pwdBtns[i].buttonName,
								   WS_VISIBLE | WS_CHILD | WS_TABSTOP,
								   pwdBtns[i].x, pwdBtns[i].y,
								   pwdBtns[i].width,pwdBtns[i].height,
								   hwnd,
								   (HMENU) (PWD_INITIAL_BUTTON+i),
								   pwdHandles.hInstance, NULL) ;

		buttons++;
	}
}

VOID PwdCreateInputFieldWindow(HWND hwnd){
	pwdHandles.parent = hwnd;
	HWND *editInputFieldWindow = &(pwdHandles.inputField);
	*editInputFieldWindow = CreateWindowEx(WS_EX_CLIENTEDGE,
						L"edit", L"",
						WS_VISIBLE | WS_CHILD | WS_TABSTOP | ES_AUTOHSCROLL | ES_PASSWORD,
						pwdEditInputField[PWD_AXIS_INPUTFIELD].x, pwdEditInputField[PWD_AXIS_INPUTFIELD].y,
						pwdEditInputField[PWD_AXIS_INPUTFIELD].width,pwdEditInputField[PWD_AXIS_INPUTFIELD].height,
						hwnd,
						NULL,
						pwdHandles.hInstance, NULL);
}

VOID PwdDrawTextOnSubTitleArea(HWND bgHandle, LPCWSTR message, int x, int y)
{
	RECT rect;
	HDC wdc = GetWindowDC(bgHandle);
	GetClientRect (bgHandle, &rect) ;
	SetTextColor(wdc, 0x00000000);
	SetBkMode(wdc,TRANSPARENT);
	rect.left = x;
	rect.top = y;
	DrawText( wdc, message, -1, &rect, DT_NOCLIP | DT_WORDBREAK | DT_NOPREFIX ) ;
	DeleteDC(wdc);
}

LRESULT CALLBACK PwdMainWndProc(HWND hwnd,UINT msg,WPARAM wParam,LPARAM lParam)
 {
	switch (msg)
	{
		case WM_CREATE:
			PwdCreateButtons(hwnd);
			PwdCreateInputFieldWindow(hwnd);
		    break;

		case WM_ACTIVATE:
			//ShowWindow(pwdHandles.mainParentWnd,SW_SHOW);
			break;

		case WM_PAINT:
			PAINTSTRUCT ps;
			HDC hdc;
			hdc = BeginPaint(hwnd, &ps);
			DeleteDC (hdc);
			EndPaint(hwnd, &ps);
			if(isWMDevice){
				PwdDrawTextOnSubTitleArea(hwnd, drawTextMessage, 20, 50);
			}else{
				PwdDrawTextOnSubTitleArea(hwnd, drawTextMessage, 20, 25);
			}
			break;

		case WM_COMMAND:
			TCHAR enteredPassWord[MAXCHAR];
			switch (LOWORD(wParam))
			{
				case VK_RETURN:
				case PWD_IDB_BTN_OK:
					{
						SendMessage(pwdHandles.inputField,WM_GETTEXT,MAXCHAR,(LPARAM)(enteredPassWord));
						if(isExitPasswordNeedToBeDone){
							if(_tcscmp(passwordValue,enteredPassWord) == 0)
							{
								isEnteredPasswordCorrect = true;
								DestroyWindow(pwdHandles.parent);
							}
							else
							{
								PwdDrawTextOnSubTitleArea(hwnd, L"InValid Password", 20, pwdCoordinates.mainWndYpos);
								SendMessage(pwdHandles.inputField,WM_SETTEXT,MAXCHAR,(LPARAM)L"");
								isEnteredPasswordCorrect = false;
							}
						}
						else
						{
							//Currently Do Nothing
						}
					}
					break;
				case PWD_IDB_BTN_CANCEL:
					{
						isEnteredPasswordCorrect = false;
						PostMessage(pwdHandles.parent , WM_KEYDOWN, VK_ESCAPE, 0);
					}
					break;
			}
			break;

		case WM_DESTROY:
			EnableWindow(pwdHandles.mainParentWnd, TRUE);
			SetForegroundWindow(pwdHandles.mainParentWnd);
			DestroyWindow(hwnd);
			PostQuitMessage(0);
			break;

		default:
			return DefWindowProc(hwnd,msg,wParam,lParam);// Call the default window handler
	}
	return 0;
 }
VOID PwdInitialiseCoordinates()
{
	bool isCheckCoordinatesDifferent = false;
	pwdCoordinates.width  = GetSystemMetrics(SM_CXVIRTUALSCREEN);
	pwdCoordinates.height = GetSystemMetrics(SM_CYVIRTUALSCREEN);
	if(pwdCoordinates.width <480 && isWMDevice){
		isCheckCoordinatesDifferent = true;
		pwdCoordinates.width = 380;
	}
	if(pwdCoordinates.height <480 && isWMDevice){
		isCheckCoordinatesDifferent = true;
		pwdCoordinates.height = 440;
	}
	pwdCoordinates.xCenter = (pwdCoordinates.width/2);
	if(pwdCoordinates.height <480 && isWMDevice)
	{
		pwdCoordinates.yCenter = (pwdCoordinates.height/2) - 50;
	}
	else
	{
		pwdCoordinates.yCenter = (pwdCoordinates.height/2);
	}
	if(IsDeviceInPortrait())
	{
		pwdCoordinates.mainWndXpos = (pwdCoordinates.width * 8)/10;
		pwdCoordinates.mainWndYpos = (pwdCoordinates.height * 3)/10;
	}
	else if(isCheckCoordinatesDifferent && isWMDevice)
	{
		pwdCoordinates.mainWndXpos = (pwdCoordinates.width * 8)/10;
		pwdCoordinates.mainWndYpos = (pwdCoordinates.height * 3)/10;
	}
	else
	{
		pwdCoordinates.mainWndXpos = ((pwdCoordinates.width * 8)/10) - 80;
		pwdCoordinates.mainWndYpos = ((pwdCoordinates.height * 3)/10) + 20;
	}

	//Edit Input Field
	pwdEditInputField[PWD_AXIS_INPUTFIELD].x = 20;
	if(isWMDevice){
		pwdEditInputField[PWD_AXIS_INPUTFIELD].y = 40;
	}
	else{
		pwdEditInputField[PWD_AXIS_INPUTFIELD].y = 20;
	}
	pwdEditInputField[PWD_AXIS_INPUTFIELD].width = (pwdCoordinates.mainWndXpos * 8)/10;
	pwdEditInputField[PWD_AXIS_INPUTFIELD].height = (pwdCoordinates.mainWndYpos * 2)/10;
	pwdEditInputField[PWD_AXIS_INPUTFIELD].buttonName = L"";

	//Ok Button
	pwdBtns[PWD_AXIS_OK].x = 20;
	if(isWMDevice){
		pwdBtns[PWD_AXIS_OK].y = ((pwdCoordinates.mainWndYpos * 2)/10) + 50;
	}
	else{
		pwdBtns[PWD_AXIS_OK].y = ((pwdCoordinates.mainWndYpos * 2)/10) + 30;
	}
	pwdBtns[PWD_AXIS_OK].width = (pwdCoordinates.mainWndXpos * 3)/10;
	pwdBtns[PWD_AXIS_OK].height = (pwdCoordinates.mainWndYpos * 2)/10;
	pwdBtns[PWD_AXIS_OK].buttonName = L"OK";

	//Cancel Button
	pwdBtns[PWD_AXIS_CANCEL].x = ((pwdCoordinates.mainWndXpos * 3)/10) + 20 + 35;
	if(isWMDevice){
		pwdBtns[PWD_AXIS_CANCEL].y = ((pwdCoordinates.mainWndYpos * 2)/10) + 50;
	}
	else{
		pwdBtns[PWD_AXIS_CANCEL].y = ((pwdCoordinates.mainWndYpos * 2)/10) + 30;
	}
	pwdBtns[PWD_AXIS_CANCEL].width= (pwdCoordinates.mainWndXpos * 3)/10;
	pwdBtns[PWD_AXIS_CANCEL].height = (pwdCoordinates.mainWndYpos * 2)/10;
	pwdBtns[PWD_AXIS_CANCEL].buttonName = L"CANCEL";
}

bool ShowPasswordDialog(bool setDeviceType, bool isExiting, HWND hWnd, HINSTANCE hInstance, LPCTSTR szWindowTitle, LPCTSTR szDrawTextMessage, LPCTSTR szPasswordValue)
{
	isExitPasswordNeedToBeDone = isExiting;

	//Window Title
	memset(windowTitle, 0,sizeof(windowTitle));
	_tcscpy(windowTitle,szWindowTitle);

	//DrawTextMessage
	memset(drawTextMessage, 0,sizeof(drawTextMessage));
	_tcscpy(drawTextMessage,szDrawTextMessage);

	//Password Value
	memset(passwordValue, 0,sizeof(passwordValue));
	_tcscpy(passwordValue,szPasswordValue);

	isWMDevice = setDeviceType;
	pwdHandles.mainParentWnd = hWnd;
	pwdHandles.hInstance = hInstance;
	PwdInitialiseCoordinates();

	MSG msg; // MSG structure to store messages

	// Register Window Class
	if (!PwdMyRegisterClass(hInstance))
	{
		isEnteredPasswordCorrect = false;
		return isEnteredPasswordCorrect;
	}

	// Perform application initialization:
	if (!PwdInitInstance (hWnd,hInstance))
	{
		isEnteredPasswordCorrect = false;
		return isEnteredPasswordCorrect;
	}

	// Main message loop: Process messages coming to this window
	while (GetMessage(&msg,NULL,0,0))
	{
		if (msg.message == WM_KEYDOWN)
		{
			//if pressed Enter button
			if (msg.wParam == VK_RETURN)
            {
				PostMessage(pwdHandles.parent , WM_COMMAND, VK_RETURN, 0);
			}
			//if pressed Cancel button
			if (msg.wParam == VK_ESCAPE)
            {
				SendMessage(pwdHandles.parent , WM_DESTROY, 0, 0);
                isEnteredPasswordCorrect = false;
            }
		}
		TranslateMessage(&msg);
		DispatchMessage(&msg);
	}
	return isEnteredPasswordCorrect;
}
<commit_msg>Update pwdPopUp.cpp<commit_after>#include "stdafx.h"
#include <windows.h>
#include "pwdPopUp.h"

_PWDHANDLES pwdHandles;
_PWDAXIS pwdBtns[2];
_PWDAXIS pwdEditInputField[1];
_PWDCOORDINATES pwdCoordinates;
TCHAR windowTitle[MAXCHAR] = L"";
TCHAR drawTextMessage[MAXCHAR] = L"";
TCHAR passwordValue[MAXCHAR] = L"";
bool isExitPasswordNeedToBeDone = false;
bool isEnteredPasswordCorrect = false;
bool isWMDevice = false;

BOOL IsDeviceInLandScape(){
  DEVMODE devmode;
  ZeroMemory(&devmode, sizeof(DEVMODE));
  devmode.dmSize = sizeof(DEVMODE);
  devmode.dmDisplayOrientation = DMDO_0;
  devmode.dmFields = DM_DISPLAYORIENTATION;
  ChangeDisplaySettingsEx(NULL, &devmode, NULL, CDS_TEST, NULL);

  return ((devmode.dmDisplayOrientation == DMDO_90) || (devmode.dmDisplayOrientation == DMDO_270));
}
BOOL IsDeviceInPortrait(){
  DEVMODE devmode;
  ZeroMemory(&devmode, sizeof(DEVMODE));
  devmode.dmSize = sizeof(DEVMODE);
  devmode.dmDisplayOrientation = DMDO_0;
  devmode.dmFields = DM_DISPLAYORIENTATION;
  ChangeDisplaySettingsEx(NULL, &devmode, NULL, CDS_TEST, NULL);

  return ((devmode.dmDisplayOrientation == DMDO_0) || (devmode.dmDisplayOrientation == DMDO_180));
}

ATOM PwdMyRegisterClass(HINSTANCE hInstance){
	WNDCLASS wcx; // WINDOW class information
	if (!GetClassInfo(hInstance, L"CheckPassword", &wcx))
	{
		//Initialize the struct to zero
		ZeroMemory(&wcx,sizeof(WNDCLASS));
		wcx.style = 0; //CS_HREDRAW|CS_VREDRAW |CS_DBLCLKS ; // Class styles
		wcx.lpfnWndProc = (WNDPROC)PwdMainWndProc; // Pointer to the callback procedure
		wcx.cbClsExtra = 0; // Extra byte to allocate following the wndclassex structure
		wcx.cbWndExtra = 0; // Extra byte to allocate following an instance of the structure
		wcx.hInstance = hInstance; // Instance of the application
		wcx.hIcon = NULL; // Class Icon
		wcx.hCursor = 0; //LoadCursor(NULL, IDC_ARROW); // Class Cursor
		wcx.hbrBackground = (HBRUSH) GetStockObject(WHITE_BRUSH); // Background brush
		wcx.lpszMenuName = NULL; // Menu resource
		wcx.lpszClassName = L"CheckPassword"; // Name of this class
		wcx.hIcon = NULL; // Small icon for this class
		return RegisterClass(&wcx);
	}
	return TRUE;
}

BOOL PwdInitInstance(HWND hWnd, HINSTANCE hInstance){

	// Create the window
	pwdHandles.parent = CreateWindow(L"CheckPassword", // Window class name
			windowTitle, // Window title
			WS_POPUP | WS_CAPTION, // Window style
			(pwdCoordinates.xCenter-pwdCoordinates.mainWndXpos/2),(pwdCoordinates.yCenter-pwdCoordinates.mainWndYpos/2),//1200,730, // (x,y) pos of the window
			pwdCoordinates.mainWndXpos,pwdCoordinates.mainWndYpos + 30, // Width and height of the window
			hWnd,//HWND_DESKTOP, // HWND of the parent window (can be null also)
			NULL, // Handle to menu
			pwdHandles.hInstance, // Handle to application instance
			NULL); // Pointer to window creation data

	// Check if window creation was successful
	if (!pwdHandles.parent)
		return 0;

	// Make the window visible
	ShowWindow(pwdHandles.parent,SW_SHOW);
	UpdateWindow(pwdHandles.parent);

	return TRUE;
}

VOID PwdCreateButtons(HWND hwnd){
	pwdHandles.parent = hwnd;
	HWND *buttons = &(pwdHandles.okButton);
	for(int i = 0; i < 2; i++){
		*buttons = CreateWindowEx(WS_EX_CLIENTEDGE,
								   L"button", pwdBtns[i].buttonName,
								   WS_VISIBLE | WS_CHILD | WS_TABSTOP,
								   pwdBtns[i].x, pwdBtns[i].y,
								   pwdBtns[i].width,pwdBtns[i].height,
								   hwnd,
								   (HMENU) (PWD_INITIAL_BUTTON+i),
								   pwdHandles.hInstance, NULL) ;

		buttons++;
	}
}

VOID PwdCreateInputFieldWindow(HWND hwnd){
	pwdHandles.parent = hwnd;
	HWND *editInputFieldWindow = &(pwdHandles.inputField);
	*editInputFieldWindow = CreateWindowEx(WS_EX_CLIENTEDGE,
						L"edit", L"",
						WS_VISIBLE | WS_CHILD | WS_TABSTOP | ES_AUTOHSCROLL | ES_PASSWORD,
						pwdEditInputField[PWD_AXIS_INPUTFIELD].x, pwdEditInputField[PWD_AXIS_INPUTFIELD].y,
						pwdEditInputField[PWD_AXIS_INPUTFIELD].width,pwdEditInputField[PWD_AXIS_INPUTFIELD].height,
						hwnd,
						NULL,
						pwdHandles.hInstance, NULL);
}

VOID PwdDrawTextOnSubTitleArea(HWND bgHandle, LPCWSTR message, int x, int y)
{
	RECT rect;
	HDC wdc = GetWindowDC(bgHandle);
	GetClientRect (bgHandle, &rect) ;
	SetTextColor(wdc, 0x00000000);
	SetBkMode(wdc,TRANSPARENT);
	rect.left = x;
	rect.top = y;
	DrawText( wdc, message, -1, &rect, DT_NOCLIP | DT_WORDBREAK | DT_NOPREFIX ) ;
	DeleteDC(wdc);
}

LRESULT CALLBACK PwdMainWndProc(HWND hwnd,UINT msg,WPARAM wParam,LPARAM lParam)
 {
	switch (msg)
	{
		case WM_CREATE:
			PwdCreateButtons(hwnd);
			PwdCreateInputFieldWindow(hwnd);
			SetFocus(pwdHandles.inputField);
		    break;

		case WM_ACTIVATE:
			//ShowWindow(pwdHandles.mainParentWnd,SW_SHOW);
			break;

		case WM_PAINT:
			PAINTSTRUCT ps;
			HDC hdc;
			hdc = BeginPaint(hwnd, &ps);
			DeleteDC (hdc);
			EndPaint(hwnd, &ps);
			if(isWMDevice){
				PwdDrawTextOnSubTitleArea(hwnd, drawTextMessage, 20, 50);
			}else{
				PwdDrawTextOnSubTitleArea(hwnd, drawTextMessage, 20, 25);
			}
			break;

		case WM_COMMAND:
			TCHAR enteredPassWord[MAXCHAR];
			switch (LOWORD(wParam))
			{
				case VK_RETURN:
				case PWD_IDB_BTN_OK:
					{
						SendMessage(pwdHandles.inputField,WM_GETTEXT,MAXCHAR,(LPARAM)(enteredPassWord));
						if(isExitPasswordNeedToBeDone){
							if(_tcscmp(passwordValue,enteredPassWord) == 0)
							{
								isEnteredPasswordCorrect = true;
								DestroyWindow(pwdHandles.parent);
							}
							else
							{
								PwdDrawTextOnSubTitleArea(hwnd, L"InValid Password", 20, pwdCoordinates.mainWndYpos);
								SendMessage(pwdHandles.inputField,WM_SETTEXT,MAXCHAR,(LPARAM)L"");
								isEnteredPasswordCorrect = false;
							}
						}
						else
						{
							//Currently Do Nothing
						}
					}
					break;
				case PWD_IDB_BTN_CANCEL:
					{
						isEnteredPasswordCorrect = false;
						PostMessage(pwdHandles.parent , WM_KEYDOWN, VK_ESCAPE, 0);
					}
					break;
			}
			break;

		case WM_DESTROY:
			EnableWindow(pwdHandles.mainParentWnd, TRUE);
			SetForegroundWindow(pwdHandles.mainParentWnd);
			DestroyWindow(hwnd);
			PostQuitMessage(0);
			break;

		default:
			return DefWindowProc(hwnd,msg,wParam,lParam);// Call the default window handler
	}
	return 0;
 }
VOID PwdInitialiseCoordinates()
{
	bool isCheckCoordinatesDifferent = false;
	pwdCoordinates.width  = GetSystemMetrics(SM_CXVIRTUALSCREEN);
	pwdCoordinates.height = GetSystemMetrics(SM_CYVIRTUALSCREEN);
	if(pwdCoordinates.width <480 && isWMDevice){
		isCheckCoordinatesDifferent = true;
		pwdCoordinates.width = 380;
	}
	if(pwdCoordinates.height <480 && isWMDevice){
		isCheckCoordinatesDifferent = true;
		pwdCoordinates.height = 440;
	}
	pwdCoordinates.xCenter = (pwdCoordinates.width/2);
	if(pwdCoordinates.height <480 && isWMDevice)
	{
		pwdCoordinates.yCenter = (pwdCoordinates.height/2) - 50;
	}
	else
	{
		pwdCoordinates.yCenter = (pwdCoordinates.height/2);
	}
	if(IsDeviceInPortrait())
	{
		pwdCoordinates.mainWndXpos = (pwdCoordinates.width * 8)/10;
		pwdCoordinates.mainWndYpos = (pwdCoordinates.height * 3)/10;
	}
	else if(isCheckCoordinatesDifferent && isWMDevice)
	{
		pwdCoordinates.mainWndXpos = (pwdCoordinates.width * 8)/10;
		pwdCoordinates.mainWndYpos = (pwdCoordinates.height * 3)/10;
	}
	else
	{
		pwdCoordinates.mainWndXpos = ((pwdCoordinates.width * 8)/10) - 80;
		pwdCoordinates.mainWndYpos = ((pwdCoordinates.height * 3)/10) + 20;
	}

	//Edit Input Field
	pwdEditInputField[PWD_AXIS_INPUTFIELD].x = 20;
	if(isWMDevice){
		pwdEditInputField[PWD_AXIS_INPUTFIELD].y = 40;
	}
	else{
		pwdEditInputField[PWD_AXIS_INPUTFIELD].y = 20;
	}
	pwdEditInputField[PWD_AXIS_INPUTFIELD].width = (pwdCoordinates.mainWndXpos * 8)/10;
	pwdEditInputField[PWD_AXIS_INPUTFIELD].height = (pwdCoordinates.mainWndYpos * 2)/10;
	pwdEditInputField[PWD_AXIS_INPUTFIELD].buttonName = L"";

	//Ok Button
	pwdBtns[PWD_AXIS_OK].x = 20;
	if(isWMDevice){
		pwdBtns[PWD_AXIS_OK].y = ((pwdCoordinates.mainWndYpos * 2)/10) + 50;
	}
	else{
		pwdBtns[PWD_AXIS_OK].y = ((pwdCoordinates.mainWndYpos * 2)/10) + 30;
	}
	pwdBtns[PWD_AXIS_OK].width = (pwdCoordinates.mainWndXpos * 3)/10;
	pwdBtns[PWD_AXIS_OK].height = (pwdCoordinates.mainWndYpos * 2)/10;
	pwdBtns[PWD_AXIS_OK].buttonName = L"OK";

	//Cancel Button
	pwdBtns[PWD_AXIS_CANCEL].x = ((pwdCoordinates.mainWndXpos * 3)/10) + 20 + 35;
	if(isWMDevice){
		pwdBtns[PWD_AXIS_CANCEL].y = ((pwdCoordinates.mainWndYpos * 2)/10) + 50;
	}
	else{
		pwdBtns[PWD_AXIS_CANCEL].y = ((pwdCoordinates.mainWndYpos * 2)/10) + 30;
	}
	pwdBtns[PWD_AXIS_CANCEL].width= (pwdCoordinates.mainWndXpos * 3)/10;
	pwdBtns[PWD_AXIS_CANCEL].height = (pwdCoordinates.mainWndYpos * 2)/10;
	pwdBtns[PWD_AXIS_CANCEL].buttonName = L"CANCEL";
}

bool ShowPasswordDialog(bool setDeviceType, bool isExiting, HWND hWnd, HINSTANCE hInstance, LPCTSTR szWindowTitle, LPCTSTR szDrawTextMessage, LPCTSTR szPasswordValue)
{
	isExitPasswordNeedToBeDone = isExiting;

	//Window Title
	memset(windowTitle, 0,sizeof(windowTitle));
	_tcscpy(windowTitle,szWindowTitle);

	//DrawTextMessage
	memset(drawTextMessage, 0,sizeof(drawTextMessage));
	_tcscpy(drawTextMessage,szDrawTextMessage);

	//Password Value
	memset(passwordValue, 0,sizeof(passwordValue));
	_tcscpy(passwordValue,szPasswordValue);

	isWMDevice = setDeviceType;
	pwdHandles.mainParentWnd = hWnd;
	pwdHandles.hInstance = hInstance;
	PwdInitialiseCoordinates();

	MSG msg; // MSG structure to store messages

	// Register Window Class
	if (!PwdMyRegisterClass(hInstance))
	{
		isEnteredPasswordCorrect = false;
		return isEnteredPasswordCorrect;
	}

	// Perform application initialization:
	if (!PwdInitInstance (hWnd,hInstance))
	{
		isEnteredPasswordCorrect = false;
		return isEnteredPasswordCorrect;
	}

	// Main message loop: Process messages coming to this window
	while (GetMessage(&msg,NULL,0,0))
	{
		if (msg.message == WM_KEYDOWN)
		{
			//if pressed Enter button
			if (msg.wParam == VK_RETURN)
            {
				PostMessage(pwdHandles.parent , WM_COMMAND, VK_RETURN, 0);
			}
			//if pressed Cancel button
			if (msg.wParam == VK_ESCAPE)
            {
				SendMessage(pwdHandles.parent , WM_DESTROY, 0, 0);
                isEnteredPasswordCorrect = false;
            }
		}
		TranslateMessage(&msg);
		DispatchMessage(&msg);
	}
	return isEnteredPasswordCorrect;
}
<|endoftext|>


<commit_before>#include <string>

#include "util/Sysout.h"

#include "language/Lexicographer.h"
#include "command/CmdLexicographer.h"

#include "Fuzzy.h"

#include "Asnd.h"
#include "AsndDog.h"

#include <vector>

// Initialization put in a handy auxiliary function!
void init()
{
    // Set the display width to 80 chars long
    Sysout::setDisplayWidth(80);

    // Legend
    Sysout::println("Fuzzy Computing Machine");
    Sysout::println();

    // Add words
    Lexicographer::graph();

    // Add commands
    CmdLexicographer::graph();
}

// This is where the magic happens!
int main()
{
    bool (*func)();
    func = &Asnd::say;

    (*func)();

    // Initialize
    init();

    // I REALLY need a better name soon...
    Fuzzy::run();

    // Died quietly
    return 0;
}
<commit_msg>Function pointer typedef<commit_after>#include <string>

#include "util/Sysout.h"

#include "language/Lexicographer.h"
#include "command/CmdLexicographer.h"

#include "Fuzzy.h"

#include "Asnd.h"
#include "AsndDog.h"

#include <vector>

// Initialization put in a handy auxiliary function!
void init()
{
    // Set the display width to 80 chars long
    Sysout::setDisplayWidth(80);

    // Legend
    Sysout::println("Fuzzy Computing Machine");
    Sysout::println();

    // Add words
    Lexicographer::graph();

    // Add commands
    CmdLexicographer::graph();
}

typedef bool (*Funk)();

// This is where the magic happens!
int main()
{
    Funk potato;
    potato = &Asnd::say;

    //std::vector<(*funk)()> funkies;

    //funkies.push_back(funk);

    potato();

    // Initialize
    init();

    // I REALLY need a better name soon...
    Fuzzy::run();

    // Died quietly
    return 0;
}
<|endoftext|>


<commit_before><commit_msg>`loaders::load_texture`: Preliminary support for `GL_MIRRORED_REPEAT`.<commit_after><|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <GL/glew.h>
#include <SDL2/SDL.h>
#include <glm/glm.hpp>
#include <glm/ext.hpp>
#include "util.h"

const int WIN_WIDTH = 640;
const int WIN_HEIGHT = 480;

int main(int argc, char **argv){
	if (SDL_Init(SDL_INIT_EVERYTHING) != 0){
		std::cout << "Failed to init: " << SDL_GetError() << std::endl;
		return 1;
	}

	SDL_Window *win = SDL_CreateWindow("Deferred Renderer",
		SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, WIN_WIDTH, WIN_HEIGHT,
		SDL_WINDOW_OPENGL);

	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);

	SDL_GLContext context = SDL_GL_CreateContext(win);

	util::logGLError("Post SDL init");

	glewExperimental = GL_TRUE;
	GLenum err = glewInit();
	if (err != GLEW_OK){
		std::cout << "GLEW init error: " << err << std::endl;
		return 1;
	}
	//Note: If we see an invalid enumerant error that's a result of glewExperimental
	//and it sounds like it can be safely ignored
	util::logGLError("Post GLEW init");

	glClearColor(0.5f, 0.5f, 0.5f, 1);
	glEnable(GL_DEPTH_TEST);

	std::cout << "OpenGL Version: " << glGetString(GL_VERSION) << "\n"
		<< "OpenGL Vendor: " << glGetString(GL_VENDOR) << "\n"
		<< "OpenGL Renderer: " << glGetString(GL_RENDERER) << "\n"
		<< "GLSL Version: " << glGetString(GL_SHADING_LANGUAGE_VERSION) << "\n";

	GLint progStatus = util::loadProgram("res/vshader.glsl", "res/fshader.glsl");
	if (progStatus == -1){
		return 1;
	}
	GLuint program = progStatus;
	glUseProgram(program);

	GLint modelLoc = glGetUniformLocation(program, "model");
	GLint projLoc = glGetUniformLocation(program, "proj");

	glm::mat4 model = glm::translate<GLfloat>(0.f, 0.f, -2.f);
	glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model));

	glm::mat4 projection = glm::perspective(75.f,
		WIN_WIDTH / static_cast<float>(WIN_HEIGHT), 0.1f, 100.f);
	projection = projection * glm::lookAt(glm::vec3(0.f, 0.f, -5.f), glm::vec3(0.f, 0.f, 0.f),
		glm::vec3(0.f, 1.f, 0.f));
	glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(projection));

	GLuint vao;
	glGenVertexArrays(1, &vao);
	glBindVertexArray(vao);

	GLuint obj[2];
	glGenBuffers(2, obj);
	size_t nElems = 0;
	//Note: Resource paths are relative to the top level directory as that's where it's expected
	//you're running the program
	if (!util::loadOBJ("res/polyhedron.obj", obj[0], obj[1], nElems)){
		std::cout << "obj loading failed" << std::endl;
		return 1;
	}
	//Position is 0, normals is 1, uv is 2
	glEnableVertexAttribArray(0);
	glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 9 * sizeof(GLfloat), 0);

	glEnableVertexAttribArray(1);
	glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 9 * sizeof(GL_FLOAT),
		(void*)(3 * sizeof(GL_FLOAT)));

	glEnableVertexAttribArray(2);
	glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 9 * sizeof(GL_FLOAT),
		(void*)(6 * sizeof(GL_FLOAT)));

	//Setup our render targets
	GLuint fbo;
	glGenFramebuffers(1, &fbo);
	glBindFramebuffer(GL_FRAMEBUFFER, fbo);

	util::logGLError("Made fbo");

	//0: diffuse, 1: normals, 2: depth
	GLuint texBuffers[3];
	glGenTextures(3, texBuffers);
	for (int i = 0; i < 2; ++i){
		glActiveTexture(GL_TEXTURE0 + i);
		glBindTexture(GL_TEXTURE_2D, texBuffers[i]);
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, WIN_WIDTH, WIN_HEIGHT, 0, GL_RGB,
			GL_UNSIGNED_BYTE, NULL);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
		glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, GL_TEXTURE_2D,
			texBuffers[i], 0);
	}
	glActiveTexture(GL_TEXTURE2);
	glBindTexture(GL_TEXTURE_2D, texBuffers[2]);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, WIN_WIDTH, WIN_HEIGHT,
		0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, NULL);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D,
		texBuffers[2], 0);

	util::logGLError("made & attached render targets");

	GLenum drawBuffers[2] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 };
	glDrawBuffers(2, drawBuffers);

	//Need another shader program for the second pass, then load up the quad
	//apply no transforms and set it to use texture units 0 (diffuse) & 1 (normals)
	//and later 3 (depth)
	//Quad VAO, VBO, EBO
	GLuint quad[3];
	glGenVertexArrays(1, quad);
	glGenBuffers(2, quad + 1);
	size_t quadElems = 0;
	glBindVertexArray(quad[0]);
	if (!util::loadOBJ("res/quad.obj", quad[1], quad[2], quadElems)){
		std::cout << "Failed to load quad\n";
		return 1;
	}
	glEnableVertexAttribArray(0);
	glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 9 * sizeof(GLfloat), 0);

	glEnableVertexAttribArray(1);
	glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 9 * sizeof(GL_FLOAT),
		(void*)(6 * sizeof(GL_FLOAT)));

	progStatus = util::loadProgram("res/vsecondpass.glsl", "res/fsecondpass.glsl");
	if (progStatus == -1){
		return 1;
	}
	GLuint quadProg = progStatus;
	glUseProgram(quadProg);
	GLuint diffuseUnif = glGetUniformLocation(quadProg, "diffuse");
	GLuint normalUnif = glGetUniformLocation(quadProg, "normal");
	GLuint depthUnif = glGetUniformLocation(quadProg, "depth");
	glUniform1i(diffuseUnif, 0);
	glUniform1i(normalUnif, 1);
	glUniform1i(depthUnif, 2);

	if (util::logGLError("Pre-loop error check")){
		return 1;
	}

	SDL_Event e;
	bool quit = false;
	while (!quit){
		while (SDL_PollEvent(&e)){
			if (e.type == SDL_QUIT || (e.type == SDL_KEYDOWN && e.key.keysym.sym == SDLK_ESCAPE)){
				quit = true;
			}
		}
		//First pass
		glUseProgram(program);
		glBindVertexArray(vao);
		glBindFramebuffer(GL_FRAMEBUFFER, fbo);
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
		glDrawElements(GL_TRIANGLES, nElems, GL_UNSIGNED_SHORT, 0);

		util::logGLError("post first pass");

		//Second pass
		glBindFramebuffer(GL_FRAMEBUFFER, 0);
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
		glBindVertexArray(quad[0]);
		glUseProgram(quadProg);
		glDrawElements(GL_TRIANGLES, quadElems, GL_UNSIGNED_SHORT, 0);

		util::logGLError("post second pass");

		SDL_GL_SwapWindow(win);
		//We're not doing anything interactive, just testing some rendering
		//so don't use so much cpu
		SDL_Delay(15);
	}
	glDeleteFramebuffers(1, &fbo);
	glDeleteTextures(3, texBuffers);

	glDeleteBuffers(2, obj);
	glDeleteVertexArrays(1, &vao);
	glDeleteBuffers(2, quad + 1);
	glDeleteVertexArrays(1, quad);

	glDeleteProgram(program);
	glDeleteProgram(quadProg);

	SDL_GL_DeleteContext(context);
	SDL_DestroyWindow(win);

	return 0;
}

<commit_msg>SDL defaults to doublebuffering on<commit_after>#include <iostream>
#include <string>
#include <GL/glew.h>
#include <SDL2/SDL.h>
#include <glm/glm.hpp>
#include <glm/ext.hpp>
#include "util.h"

const int WIN_WIDTH = 640;
const int WIN_HEIGHT = 480;

int main(int argc, char **argv){
	if (SDL_Init(SDL_INIT_EVERYTHING) != 0){
		std::cout << "Failed to init: " << SDL_GetError() << std::endl;
		return 1;
	}

	SDL_Window *win = SDL_CreateWindow("Deferred Renderer",
		SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, WIN_WIDTH, WIN_HEIGHT,
		SDL_WINDOW_OPENGL);

	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);

	SDL_GLContext context = SDL_GL_CreateContext(win);

	util::logGLError("Post SDL init");

	glewExperimental = GL_TRUE;
	GLenum err = glewInit();
	if (err != GLEW_OK){
		std::cout << "GLEW init error: " << err << std::endl;
		return 1;
	}
	//Note: If we see an invalid enumerant error that's a result of glewExperimental
	//and it sounds like it can be safely ignored
	util::logGLError("Post GLEW init");

	glClearColor(0.5f, 0.5f, 0.5f, 1);
	glEnable(GL_DEPTH_TEST);

	std::cout << "OpenGL Version: " << glGetString(GL_VERSION) << "\n"
		<< "OpenGL Vendor: " << glGetString(GL_VENDOR) << "\n"
		<< "OpenGL Renderer: " << glGetString(GL_RENDERER) << "\n"
		<< "GLSL Version: " << glGetString(GL_SHADING_LANGUAGE_VERSION) << "\n";

	GLint progStatus = util::loadProgram("res/vshader.glsl", "res/fshader.glsl");
	if (progStatus == -1){
		return 1;
	}
	GLuint program = progStatus;
	glUseProgram(program);

	GLint modelLoc = glGetUniformLocation(program, "model");
	GLint projLoc = glGetUniformLocation(program, "proj");

	glm::mat4 model = glm::translate<GLfloat>(0.f, 0.f, -2.f);
	glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model));

	glm::mat4 projection = glm::perspective(75.f,
		WIN_WIDTH / static_cast<float>(WIN_HEIGHT), 0.1f, 100.f);
	projection = projection * glm::lookAt(glm::vec3(0.f, 0.f, -5.f), glm::vec3(0.f, 0.f, 0.f),
		glm::vec3(0.f, 1.f, 0.f));
	glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(projection));

	GLuint vao;
	glGenVertexArrays(1, &vao);
	glBindVertexArray(vao);

	GLuint obj[2];
	glGenBuffers(2, obj);
	size_t nElems = 0;
	//Note: Resource paths are relative to the top level directory as that's where it's expected
	//you're running the program
	if (!util::loadOBJ("res/polyhedron.obj", obj[0], obj[1], nElems)){
		std::cout << "obj loading failed" << std::endl;
		return 1;
	}
	//Position is 0, normals is 1, uv is 2
	glEnableVertexAttribArray(0);
	glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 9 * sizeof(GLfloat), 0);

	glEnableVertexAttribArray(1);
	glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 9 * sizeof(GL_FLOAT),
		(void*)(3 * sizeof(GL_FLOAT)));

	glEnableVertexAttribArray(2);
	glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 9 * sizeof(GL_FLOAT),
		(void*)(6 * sizeof(GL_FLOAT)));

	//Setup our render targets
	GLuint fbo;
	glGenFramebuffers(1, &fbo);
	glBindFramebuffer(GL_FRAMEBUFFER, fbo);

	util::logGLError("Made fbo");

	//0: diffuse, 1: normals, 2: depth
	GLuint texBuffers[3];
	glGenTextures(3, texBuffers);
	for (int i = 0; i < 2; ++i){
		glActiveTexture(GL_TEXTURE0 + i);
		glBindTexture(GL_TEXTURE_2D, texBuffers[i]);
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, WIN_WIDTH, WIN_HEIGHT, 0, GL_RGB,
			GL_UNSIGNED_BYTE, NULL);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
		glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, GL_TEXTURE_2D,
			texBuffers[i], 0);
	}
	glActiveTexture(GL_TEXTURE2);
	glBindTexture(GL_TEXTURE_2D, texBuffers[2]);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, WIN_WIDTH, WIN_HEIGHT,
		0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, NULL);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D,
		texBuffers[2], 0);

	util::logGLError("made & attached render targets");

	GLenum drawBuffers[2] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 };
	glDrawBuffers(2, drawBuffers);

	//Need another shader program for the second pass, then load up the quad
	//apply no transforms and set it to use texture units 0 (diffuse) & 1 (normals)
	//and later 3 (depth)
	//Quad VAO, VBO, EBO
	GLuint quad[3];
	glGenVertexArrays(1, quad);
	glGenBuffers(2, quad + 1);
	size_t quadElems = 0;
	glBindVertexArray(quad[0]);
	if (!util::loadOBJ("res/quad.obj", quad[1], quad[2], quadElems)){
		std::cout << "Failed to load quad\n";
		return 1;
	}
	glEnableVertexAttribArray(0);
	glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 9 * sizeof(GLfloat), 0);

	glEnableVertexAttribArray(1);
	glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 9 * sizeof(GL_FLOAT),
		(void*)(6 * sizeof(GL_FLOAT)));

	progStatus = util::loadProgram("res/vsecondpass.glsl", "res/fsecondpass.glsl");
	if (progStatus == -1){
		return 1;
	}
	GLuint quadProg = progStatus;
	glUseProgram(quadProg);
	GLuint diffuseUnif = glGetUniformLocation(quadProg, "diffuse");
	GLuint normalUnif = glGetUniformLocation(quadProg, "normal");
	GLuint depthUnif = glGetUniformLocation(quadProg, "depth");
	glUniform1i(diffuseUnif, 0);
	glUniform1i(normalUnif, 1);
	glUniform1i(depthUnif, 2);

	if (util::logGLError("Pre-loop error check")){
		return 1;
	}

	SDL_Event e;
	bool quit = false;
	while (!quit){
		while (SDL_PollEvent(&e)){
			if (e.type == SDL_QUIT || (e.type == SDL_KEYDOWN && e.key.keysym.sym == SDLK_ESCAPE)){
				quit = true;
			}
		}
		//First pass
		glUseProgram(program);
		glBindVertexArray(vao);
		glBindFramebuffer(GL_FRAMEBUFFER, fbo);
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
		glDrawElements(GL_TRIANGLES, nElems, GL_UNSIGNED_SHORT, 0);

		util::logGLError("post first pass");

		//Second pass
		glBindFramebuffer(GL_FRAMEBUFFER, 0);
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
		glBindVertexArray(quad[0]);
		glUseProgram(quadProg);
		glDrawElements(GL_TRIANGLES, quadElems, GL_UNSIGNED_SHORT, 0);

		util::logGLError("post second pass");

		SDL_GL_SwapWindow(win);
		//We're not doing anything interactive, just testing some rendering
		//so don't use so much cpu
		SDL_Delay(15);
	}
	glDeleteFramebuffers(1, &fbo);
	glDeleteTextures(3, texBuffers);

	glDeleteBuffers(2, obj);
	glDeleteVertexArrays(1, &vao);
	glDeleteBuffers(2, quad + 1);
	glDeleteVertexArrays(1, quad);

	glDeleteProgram(program);
	glDeleteProgram(quadProg);

	SDL_GL_DeleteContext(context);
	SDL_DestroyWindow(win);

	return 0;
}

<|endoftext|>


<commit_before>#include <iostream>

#include <boost/program_options.hpp>

// Project
#include "Client.h"
#include "ClientOptions.h"

using namespace boost::program_options;

boost::program_options::options_description client_options() {
  boost::program_options::options_description desc("Options");

  desc.add_options()
	  ("ip,i", value<std::string>()->default_value("localhost"),"Server address")
	  ("port,p", value<std::string>()->default_value("2061"),"Server port")
	  ("player-name,n", value<std::string>()->required())
	  ("player-team,t", value<std::string>())
	  ("window-width,w", value<int>())
	  ("window-height,h", value<int>());

  return desc;
}

ClientOptions parseClientOptions(int argc, char const *argv[]) noexcept {
  options_description desc = client_options();

  try {
    variables_map vm;

    store(command_line_parser(argc, argv).options(desc).run(), vm);
    notify(vm);

    // Looking forward to C++20 designated initializers
    ClientOptions opts{
        vm["ip"].as<std::string>(),
        vm["port"].as<std::string>(),
        vm["player-name"].as<std::string>(),
        vm.count("player-team") ? vm["player-team"].as<std::string>() : "",
        vm.count("window-width") ? vm["window-width"].as<int>() : -1,
        vm.count("window-height") ? vm["window-height"].as<int>() : -1};

    return opts;
  } catch (std::exception const &e) {
    std::cerr << "Cannot parse arguments:\n"
              << e.what() << std::endl
              << std::endl;
    std::cerr << desc << std::endl;
    std::exit(1);
  }
}

void runClientWithOptions(ClientOptions const &options) {
  try {
    Client client{options};
    client.run();
  } catch (std::exception &e) {
    std::cerr << "Error: \n" << e.what() << std::endl << std::endl;
	std::exit(1);
  }
}

int main(int argc, const char **argv) {
  std::cout << "Toogashada Client" << std::endl;
  ClientOptions options = parseClientOptions(argc, argv);
  runClientWithOptions(options);
}
<commit_msg>Reformat<commit_after>#include <iostream>

#include <boost/program_options.hpp>

// Project
#include "Client.h"
#include "ClientOptions.h"

using namespace boost::program_options;

boost::program_options::options_description client_options() {
  boost::program_options::options_description desc("Options");

  desc.add_options()("ip,i", value<std::string>()->default_value("localhost"),
                     "Server address");
  desc.add_options()("port,p", value<std::string>()->default_value("2061"),
                     "Server port");
  desc.add_options()("player-name,n", value<std::string>()->required());
  desc.add_options()("player-team,t", value<std::string>());
  desc.add_options()("window-width,w", value<int>());
  desc.add_options()("window-height,h", value<int>());

  return desc;
}

ClientOptions parseClientOptions(int argc, char const *argv[]) noexcept {
  options_description desc = client_options();

  try {
    variables_map vm;

    store(command_line_parser(argc, argv).options(desc).run(), vm);
    notify(vm);

    // Looking forward to C++20 designated initializers
    ClientOptions opts{
        vm["ip"].as<std::string>(),
        vm["port"].as<std::string>(),
        vm["player-name"].as<std::string>(),
        vm.count("player-team") ? vm["player-team"].as<std::string>() : "",
        vm.count("window-width") ? vm["window-width"].as<int>() : -1,
        vm.count("window-height") ? vm["window-height"].as<int>() : -1};

    return opts;
  } catch (std::exception const &e) {
    std::cerr << "Cannot parse arguments:\n"
              << e.what() << std::endl
              << std::endl;
    std::cerr << desc << std::endl;
    std::exit(1);
  }
}

void runClientWithOptions(ClientOptions const &options) {
  try {
    Client client{options};
    client.run();
  } catch (std::exception &e) {
    std::cerr << "Error: \n" << e.what() << std::endl << std::endl;
    std::exit(1);
  }
}

int main(int argc, const char **argv) {
  std::cout << "Toogashada Client" << std::endl;
  ClientOptions options = parseClientOptions(argc, argv);
  runClientWithOptions(options);
}
<|endoftext|>


<commit_before>#include "application.hpp"
#include "singletons/nativemessagingmanager.hpp"
#include "singletons/pathmanager.hpp"
#include "util/networkmanager.hpp"

#include <QAbstractNativeEventFilter>
#include <QApplication>
#include <QFile>
#include <QLibrary>
#include <QStringList>

#ifdef USEWINSDK
#include "util/nativeeventhelper.hpp"
#endif

#include <fstream>
#include <iostream>

#ifdef Q_OS_WIN
#include <fcntl.h>
#include <io.h>
#include <stdio.h>
#endif

bool isBigEndian()
{
    int test = 1;
    char *p = (char *)&test;

    return p[0] == 0;
}

void runNativeMessagingHost();
int runGui(int argc, char *argv[]);

int main(int argc, char *argv[])
{
    // read args
    QStringList args;

    for (int i = 1; i < argc; i++) {
        args << argv[i];
    }

    // TODO: can be any argument
    if (args.size() > 0 && args[0].startsWith("chrome-extension://")) {
        runNativeMessagingHost();
        return 0;
    }

    // run gui
    return runGui(argc, argv);
}

int runGui(int argc, char *argv[])
{
    QApplication::setAttribute(Qt::AA_Use96Dpi, true);
#ifdef Q_OS_WIN32
    QApplication::setAttribute(Qt::AA_DisableHighDpiScaling, true);
#endif
    //    QApplication::setAttribute(Qt::AA_UseSoftwareOpenGL, true);
    QApplication a(argc, argv);

// Install native event handler for hidpi on windows
#ifdef USEWINSDK
    a.installNativeEventFilter(new chatterino::util::DpiNativeEventFilter);
#endif

    // Initialize settings
    bool success = chatterino::singletons::PathManager::getInstance().init(argc, argv);
    if (!success) {
        printf("Error initializing paths\n");
        return 1;
    }

    // Initialize NetworkManager
    chatterino::util::NetworkManager::init();

    {
        // Initialize application
        chatterino::Application app;

        // Start the application
        app.run(a);

        // Application will go out of scope here and deinitialize itself
    }

    // Save settings
    pajlada::Settings::SettingManager::save();

    // Deinitialize NetworkManager (stop thread and wait for finish, should be instant)
    chatterino::util::NetworkManager::deinit();

    _exit(0);
}

void runNativeMessagingHost()
{
#ifdef Q_OS_WIN
    _setmode(_fileno(stdin), _O_BINARY);
    _setmode(_fileno(stdout), _O_BINARY);
#endif

    auto &nmm = chatterino::singletons::NativeMessagingManager::getInstance();

    bool bigEndian = isBigEndian();

    while (true) {
        char size_c[4];
        std::cin.read(size_c, 4);

        if (std::cin.eof()) {
            break;
        }

        uint32_t size = 0;
        if (bigEndian) {
            size = size_c[3] | static_cast<uint32_t>(size_c[2]) << 8 |
                   static_cast<uint32_t>(size_c[1]) << 16 | static_cast<uint32_t>(size_c[0]) << 24;
        } else {
            size = size_c[0] | static_cast<uint32_t>(size_c[1]) << 8 |
                   static_cast<uint32_t>(size_c[2]) << 16 | static_cast<uint32_t>(size_c[3]) << 24;
        }

        char *b = (char *)malloc(size + 1);
        std::cin.read(b, size);
        *(b + size) = '\0';

        nmm.sendToGuiProcess(QByteArray(b, size));

        free(b);
    }
}
<commit_msg>Disable the experimental code, oops KKona<commit_after>#include "application.hpp"
#include "singletons/nativemessagingmanager.hpp"
#include "singletons/pathmanager.hpp"
#include "util/networkmanager.hpp"

#include <QAbstractNativeEventFilter>
#include <QApplication>
#include <QFile>
#include <QLibrary>
#include <QStringList>

#ifdef USEWINSDK
#include "util/nativeeventhelper.hpp"
#endif

#include <fstream>
#include <iostream>

#ifdef Q_OS_WIN
#include <fcntl.h>
#include <io.h>
#include <stdio.h>
#endif

bool isBigEndian()
{
    int test = 1;
    char *p = (char *)&test;

    return p[0] == 0;
}

void runNativeMessagingHost();
int runGui(int argc, char *argv[]);

int main(int argc, char *argv[])
{
    // read args
    QStringList args;

    for (int i = 1; i < argc; i++) {
        args << argv[i];
    }

    // TODO: can be any argument
    if (args.size() > 0 && args[0].startsWith("chrome-extension://")) {
        runNativeMessagingHost();
        return 0;
    }

    // run gui
    return runGui(argc, argv);
}

int runGui(int argc, char *argv[])
{
    QApplication::setAttribute(Qt::AA_Use96Dpi, true);
#ifdef Q_OS_WIN32
    QApplication::setAttribute(Qt::AA_DisableHighDpiScaling, true);
#endif
    //    QApplication::setAttribute(Qt::AA_UseSoftwareOpenGL, true);
    QApplication a(argc, argv);

// Install native event handler for hidpi on windows
#ifdef USEWINSDK
    a.installNativeEventFilter(new chatterino::util::DpiNativeEventFilter);
#endif

    // Initialize settings
    bool success = chatterino::singletons::PathManager::getInstance().init(argc, argv);
    if (!success) {
        printf("Error initializing paths\n");
        return 1;
    }

    // Initialize NetworkManager
    chatterino::util::NetworkManager::init();

    {
        // Initialize application
        chatterino::Application app;

        // Start the application
        app.run(a);

        // Application will go out of scope here and deinitialize itself
    }

    // Save settings
    pajlada::Settings::SettingManager::save();

    // Deinitialize NetworkManager (stop thread and wait for finish, should be instant)
    chatterino::util::NetworkManager::deinit();

    _exit(0);
}

void runNativeMessagingHost()
{
#ifdef Q_OS_WIN
    _setmode(_fileno(stdin), _O_BINARY);
    _setmode(_fileno(stdout), _O_BINARY);
#endif

    auto &nmm = chatterino::singletons::NativeMessagingManager::getInstance();

#if 0
    bool bigEndian = isBigEndian();
#endif

    while (true) {
        char size_c[4];
        std::cin.read(size_c, 4);

        if (std::cin.eof()) {
            break;
        }

        uint32_t size = *reinterpret_cast<uint32_t *>(size_c);
#if 0
        // To avoid breaking strict-aliasing rules and potentially inducing undefined behaviour, the following code can be run instead
        uint32_t size = 0;
        if (bigEndian) {
            size = size_c[3] | static_cast<uint32_t>(size_c[2]) << 8 |
                   static_cast<uint32_t>(size_c[1]) << 16 | static_cast<uint32_t>(size_c[0]) << 24;
        } else {
            size = size_c[0] | static_cast<uint32_t>(size_c[1]) << 8 |
                   static_cast<uint32_t>(size_c[2]) << 16 | static_cast<uint32_t>(size_c[3]) << 24;
        }
#endif

        char *b = (char *)malloc(size + 1);
        std::cin.read(b, size);
        *(b + size) = '\0';

        nmm.sendToGuiProcess(QByteArray(b, size));

        free(b);
    }
}
<|endoftext|>


<commit_before>#include <iostream>
#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <sys/wait.h>
#include <vector>
#include <boost/tokenizer.hpp>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
using namespace std;
using namespace boost;

int status;

int main(int argc, char **argv)
{
	bool finish = false;
	string login = getlogin();
	if(getlogin() == NULL)
	{
		login = "";
		perror("get login failed");
	}
	char hostarray[64];
	gethostname(hostarray, 64);
	if(gethostname(hostarray, 64) == -1)
		perror("get host name failed");

	//rshell loop
	while(!finish)
	{
		bool syntaxerror = false;
		int semicolon= 0;
		int ampersand = 0;
		int pipe = 0;
		int right = 0;
		int left = 0;
		string command = "";
		vector <string> commands;

		//login name and host info prompt
		if(getlogin() != NULL)
			cout << login << "@" << hostarray;

		//ready prompt
		cout << "$ ";

		//take in command from user
		getline(cin, command);
	//	cout << command << endl;

		//account for #
		if(command.find("#") != string::npos)
		{
			command = command.substr(0, command.find("#"));
		//	cout << command << endl;
		}

		//account for empty command
		if(command == "")
			continue;

		//tokenizer init
		char_separator<char> delim(" ",";&|#<>");
		tokenizer< char_separator<char> > mytok(command, delim);

		//token check
		//for(tokenizer<char_separator<char> >::iterator it = mytok.begin(); it != mytok.end(); it++)
		//{
		//	cout << "(" << *it << ")" << " ";
		//}
		//cout << "listed the arguements" << endl;

		for(tokenizer<char_separator<char> >::iterator it = mytok.begin(); it != mytok.end(); it++)
		{
			cout << "(" << *it << ")" << " ";
		}
		cout << "listed the arguements" << endl;

		string temp;
		//command list formatting
		for(tokenizer<char_separator<char> >::iterator it = mytok.begin(); it != mytok.end(); it++)
		{
			//cout << "; = " << semicolon << ", & = " << ampersand << ", | =" << pipe << endl;
			//if(*it == ""); //do nothing

			if(*it == ";") //semicolon handling
			{
				semicolon++;
				if(semicolon > 1)
				{
					perror("Syntax error. Too many ; characters.");
					syntaxerror = true;
					break;
				}
				else if(semicolon == 1)
				{
					if(ampersand == 0 && pipe == 0)
					{
						if(temp == "")
						{
							perror("No arguments before connector");
							syntaxerror = true;
							break;
						}
						commands.push_back(temp);
						temp = "";
						commands.push_back(";");
						semicolon = 0;
					}
					else
					{
						perror("Syntax error. Improper use of connectors.");
						syntaxerror = true;
						break;
					}
				}

			}
			else if(*it == "&") //ampersand handling
			{
				ampersand++;
				if(ampersand > 2)
				{
					perror("Syntax error. Too many & characters");
					syntaxerror = true;
					break;
				}
				else if(ampersand == 2)
				{
					if(semicolon == 0 && pipe == 0)
					{
						if(temp == "")
						{
							perror("No arguments before connector");
							syntaxerror = true;
						}
						commands.push_back(temp);
						temp = "";
						commands.push_back("&&");
						ampersand = 0;
					}
					else
					{
						perror("Syntax error. Improper use of connectors.");
						syntaxerror = true;
						break;
					}
				}

			}
			else if(*it == "|") //pipe handling
			{
				//cout << "PIPE!!!!!!!!!!!" << endl;
				pipe++;
				if(pipe > 2)
				{
					perror("Syntax error. Too many | characters.");
					syntaxerror = true;
					break;
				}
				else if(pipe == 1)
				{
					if(semicolon == 0 && ampersand == 0)
					{
						if(temp == "")
						{
							perror("No arguments before connector");
							syntaxerror = true;
							break;
						}
						commands.push_back(temp);
						temp = "";
						commands.push_back("|");
					}
					else
					{
						perror("Syntax error. Improper use of connectors.");
						syntaxerror = true;
						break;
					}

				}
				else if(pipe == 2)
				{
					if(semicolon == 0 && ampersand == 0)
					{
						commands.push_back("|");
						pipe = 0;
					}
					else
					{
						perror("Syntax error. Improper use of connectors.");
						syntaxerror = true;
						break;
					}
				}

			}
			else if(*it == ">") //> handling
			{
				right++;
				if(right > 2)
				{
					perror("Syntax error. Too many > characters.");
					syntaxerror = true;
					break;
				}
				else if(right == 1)
				{
					if(semicolon == 0 && ampersand == 0)
					{
						if(temp == "")
						{
							perror("No arguments before connector");
							syntaxerror = true;
							break;
						}
						commands.push_back(temp);
						temp = "";
						commands.push_back(">");
					}
					else
					{
						perror("Syntax error. Improper use of connectors.");
						syntaxerror = true;
						break;
					}

				}
				else if(right == 2)
				{
					if(semicolon == 0 && ampersand == 0)
					{
						commands.push_back(">");
						right = 0;
					}
					else
					{
						perror("Syntax error. Improper use of connectors.");
						syntaxerror = true;
						break;
					}
				}

			}
			else if(*it == "<") //< handling
			{
				left++;
				if(left > 2)
				{
					perror("Syntax error. Too many < characters.");
					syntaxerror = true;
					break;
				}
				else if(left == 1)
				{
					if(semicolon == 0 && ampersand == 0)
					{
						if(temp == "")
						{
							perror("No arguments before connector");
							syntaxerror = true;
							break;
						}
						commands.push_back(temp);
						temp = "";
						commands.push_back("<");
					}
					else
					{
						perror("Syntax error. Improper use of connectors.");
						syntaxerror = true;
						break;
					}

				}
				else if(left == 2)
				{
					if(semicolon == 0 && ampersand == 0)
					{
						commands.push_back("<");
						left = 0;
					}
					else
					{
						perror("Syntax error. Improper use of connectors.");
						syntaxerror = true;
						break;
					}
				}

			}
			else
			{
				if(semicolon != 0 || ampersand != 0)
				{
					perror("Syntax error. Improper use of connectors.");
					//cout << semicolon << " " << ampersand << " " << pipe << endl;
					syntaxerror = true;
					break;
				}
				if(temp != "")
				{
					temp += ' ';
				}
				temp += *it;
				if(pipe == 1)
					pipe = 0;
				if(right == 1)
					right = 0;
				if(left == 1)
					left = 0;
			}
		}
		commands.push_back(temp.c_str());
		temp = "";

		//check commands
		for(unsigned int i = 0; i < commands.size(); i++)
		{
			cout << "(" << commands.at(i) << ") ";
		}
		cout << endl;
		//combine two pipes, two >, and two < together
		bool prevpipe = false;
		bool prevright = false;
		bool prevleft = false;
		for(unsigned int i = 1; i < commands.size(); i++)
		{
			if(commands.at(i - 1) == "|")
				prevpipe = true;
			else
				prevpipe = false;

			if(commands.at(i - 1) == ">")
				prevright = true;
			else
				prevright = false;

			if(commands.at(i - 1) == "<")
				prevleft = true;
			else
				prevleft = false;

			if(prevpipe)
			{
				if(commands.at(i) == "|")
				{
					commands.at(i - 1) = "||";
					commands.erase(commands.begin() + i);
					i--;
				}
			}
			if(prevright)
			{
				if(commands.at(i) == ">")
				{
					commands.at(i - 1) = ">>";
					commands.erase(commands.begin() + i);
					i--;
				}
			}
			if(prevleft)
			{
				if(commands.at(i) == "<")
				{
					commands.at(i - 1) = "<<";
					commands.erase(commands.begin() + i);
					i--;
				}
			}
		}

		//check commands
		for(unsigned int i = 0; i < commands.size(); i++)
		{
			cout << "(" << commands.at(i) << ") ";
		}

		cout << "combined arguements into groups" << endl;
		if(!syntaxerror)
		{
			char *input[999];
			//exec commands
			for(unsigned int i = 0; i < commands.size(); i++)
			{
				string current = "";
				string word = "";
				int k = 0;
				for(unsigned int j = 0; j < commands.at(i).size(); j++) //itterate through letters
				{
					current = commands.at(i);
					if(current[j] == ' ')
					{
						input[k] = new char[word.size() + 1];
						strcpy(input[k], word.c_str());
						k++;
						word = "";
					}
					else
						word += current[j]; //add letter
				}
				input[k] = new char[word.size() + 1];
				strcpy(input[k], word.c_str());
				k++;

				input[k] = new char[1]; //add the NULL char *
				input[k] = NULL;

				if(commands.at(i) ==  "exit") //exit command
				{
					finish = true;
					cout << "ending session...";
					break;
				}

				else if(commands.at(i) == ";") //semicolon case
				{
					continue;
				}

				else if(commands.at(i) == "||") //double pipe case
				{
					if(status)
						continue;
					else
					{
						i++;
						continue;
					}
				}

				else if(commands.at(i) == "&&") //ampersand case
				{
					if(status == 0)
						continue;
					else
					{
						i++;
						continue;
					}
				}

				//execute command. based off of in-lecture notes
				int pid = fork();
				if(pid == -1)
				{
					perror("There was an error with fork(). ");
					exit(1);
				}
				else if(pid == 0) //in child
				{
					//cout << "CHILD IS RUNNING :D" << endl;
					//cout << input << endl;
					int fd = 0;
					//bool inputRedir = false;
					bool outputRedir = false;
					if(i + 1 < commands.size())
					{
						if(commands.at(i + 1) == ">") //HANDLE >
						{
							outputRedir = true;
							if(i + 2 < commands.size())
							{
								if(-1 == close(1))
									perror("close");
								if((fd=open(commands.at(i + 2).c_str(),O_CREAT|O_WRONLY|O_TRUNC,0666))==-1)
									perror("open");
							    if((dup2(fd,1))==-1)
							        perror("dup2");
							}
						}
					}

					status = execvp(input[0], input);
					if(-1 == status)
					{
						perror("There was an error in execvp.");

					}

					if(outputRedir)
						i = i + 2;
					exit(1);
				}
				else if(pid > 0) //in parent
				{
					if(-1 == waitpid(pid, &status, 0)) //wait for child to finish
						perror("There was an error with wait().");

				}

			}

			//shell termination
			if(finish)
			{
				cout << "good-bye!" << endl;
				break;
			}
		}
	}
	return 0;
}
<commit_msg>Fixed exec bug<commit_after>#include <iostream>
#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <sys/wait.h>
#include <vector>
#include <boost/tokenizer.hpp>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
using namespace std;
using namespace boost;

int status;

int main(int argc, char **argv)
{
	bool finish = false;
	string login = getlogin();
	if(getlogin() == NULL)
	{
		login = "";
		perror("get login failed");
	}
	char hostarray[64];
	gethostname(hostarray, 64);
	if(gethostname(hostarray, 64) == -1)
		perror("get host name failed");

	//rshell loop
	while(!finish)
	{
		bool syntaxerror = false;
		int semicolon= 0;
		int ampersand = 0;
		int pipe = 0;
		int right = 0;
		int left = 0;
		string command = "";
		vector <string> commands;

		//login name and host info prompt
		if(getlogin() != NULL)
			cout << login << "@" << hostarray;

		//ready prompt
		cout << "$ ";

		//take in command from user
		getline(cin, command);
	//	cout << command << endl;

		//account for #
		if(command.find("#") != string::npos)
		{
			command = command.substr(0, command.find("#"));
		//	cout << command << endl;
		}

		//account for empty command
		if(command == "")
			continue;

		//tokenizer init
		char_separator<char> delim(" ",";&|#<>");
		tokenizer< char_separator<char> > mytok(command, delim);

		//token check
		//for(tokenizer<char_separator<char> >::iterator it = mytok.begin(); it != mytok.end(); it++)
		//{
		//	cout << "(" << *it << ")" << " ";
		//}
		//cout << "listed the arguements" << endl;

		for(tokenizer<char_separator<char> >::iterator it = mytok.begin(); it != mytok.end(); it++)
		{
			cout << "(" << *it << ")" << " ";
		}
		cout << "listed the arguements" << endl;

		string temp;
		//command list formatting
		for(tokenizer<char_separator<char> >::iterator it = mytok.begin(); it != mytok.end(); it++)
		{
			//cout << "; = " << semicolon << ", & = " << ampersand << ", | =" << pipe << endl;
			//if(*it == ""); //do nothing

			if(*it == ";") //semicolon handling
			{
				semicolon++;
				if(semicolon > 1)
				{
					perror("Syntax error. Too many ; characters.");
					syntaxerror = true;
					break;
				}
				else if(semicolon == 1)
				{
					if(ampersand == 0 && pipe == 0)
					{
						if(temp == "")
						{
							perror("No arguments before connector");
							syntaxerror = true;
							break;
						}
						commands.push_back(temp);
						temp = "";
						commands.push_back(";");
						semicolon = 0;
					}
					else
					{
						perror("Syntax error. Improper use of connectors.");
						syntaxerror = true;
						break;
					}
				}

			}
			else if(*it == "&") //ampersand handling
			{
				ampersand++;
				if(ampersand > 2)
				{
					perror("Syntax error. Too many & characters");
					syntaxerror = true;
					break;
				}
				else if(ampersand == 2)
				{
					if(semicolon == 0 && pipe == 0)
					{
						if(temp == "")
						{
							perror("No arguments before connector");
							syntaxerror = true;
						}
						commands.push_back(temp);
						temp = "";
						commands.push_back("&&");
						ampersand = 0;
					}
					else
					{
						perror("Syntax error. Improper use of connectors.");
						syntaxerror = true;
						break;
					}
				}

			}
			else if(*it == "|") //pipe handling
			{
				//cout << "PIPE!!!!!!!!!!!" << endl;
				pipe++;
				if(pipe > 2)
				{
					perror("Syntax error. Too many | characters.");
					syntaxerror = true;
					break;
				}
				else if(pipe == 1)
				{
					if(semicolon == 0 && ampersand == 0)
					{
						if(temp == "")
						{
							perror("No arguments before connector");
							syntaxerror = true;
							break;
						}
						commands.push_back(temp);
						temp = "";
						commands.push_back("|");
					}
					else
					{
						perror("Syntax error. Improper use of connectors.");
						syntaxerror = true;
						break;
					}

				}
				else if(pipe == 2)
				{
					if(semicolon == 0 && ampersand == 0)
					{
						commands.push_back("|");
						pipe = 0;
					}
					else
					{
						perror("Syntax error. Improper use of connectors.");
						syntaxerror = true;
						break;
					}
				}

			}
			else if(*it == ">") //> handling
			{
				right++;
				if(right > 2)
				{
					perror("Syntax error. Too many > characters.");
					syntaxerror = true;
					break;
				}
				else if(right == 1)
				{
					if(semicolon == 0 && ampersand == 0)
					{
						if(temp == "")
						{
							perror("No arguments before connector");
							syntaxerror = true;
							break;
						}
						commands.push_back(temp);
						temp = "";
						commands.push_back(">");
					}
					else
					{
						perror("Syntax error. Improper use of connectors.");
						syntaxerror = true;
						break;
					}

				}
				else if(right == 2)
				{
					if(semicolon == 0 && ampersand == 0)
					{
						commands.push_back(">");
						right = 0;
					}
					else
					{
						perror("Syntax error. Improper use of connectors.");
						syntaxerror = true;
						break;
					}
				}

			}
			else if(*it == "<") //< handling
			{
				left++;
				if(left > 2)
				{
					perror("Syntax error. Too many < characters.");
					syntaxerror = true;
					break;
				}
				else if(left == 1)
				{
					if(semicolon == 0 && ampersand == 0)
					{
						if(temp == "")
						{
							perror("No arguments before connector");
							syntaxerror = true;
							break;
						}
						commands.push_back(temp);
						temp = "";
						commands.push_back("<");
					}
					else
					{
						perror("Syntax error. Improper use of connectors.");
						syntaxerror = true;
						break;
					}

				}
				else if(left == 2)
				{
					if(semicolon == 0 && ampersand == 0)
					{
						commands.push_back("<");
						left = 0;
					}
					else
					{
						perror("Syntax error. Improper use of connectors.");
						syntaxerror = true;
						break;
					}
				}

			}
			else
			{
				if(semicolon != 0 || ampersand != 0)
				{
					perror("Syntax error. Improper use of connectors.");
					//cout << semicolon << " " << ampersand << " " << pipe << endl;
					syntaxerror = true;
					break;
				}
				if(temp != "")
				{
					temp += ' ';
				}
				temp += *it;
				if(pipe == 1)
					pipe = 0;
				if(right == 1)
					right = 0;
				if(left == 1)
					left = 0;
			}
		}
		commands.push_back(temp.c_str());
		temp = "";

		//check commands
		for(unsigned int i = 0; i < commands.size(); i++)
		{
			cout << "(" << commands.at(i) << ") ";
		}
		cout << endl;
		//combine two pipes, two >, and two < together
		bool prevpipe = false;
		bool prevright = false;
		bool prevleft = false;
		for(unsigned int i = 1; i < commands.size(); i++)
		{
			if(commands.at(i - 1) == "|")
				prevpipe = true;
			else
				prevpipe = false;

			if(commands.at(i - 1) == ">")
				prevright = true;
			else
				prevright = false;

			if(commands.at(i - 1) == "<")
				prevleft = true;
			else
				prevleft = false;

			if(prevpipe)
			{
				if(commands.at(i) == "|")
				{
					commands.at(i - 1) = "||";
					commands.erase(commands.begin() + i);
					i--;
				}
			}
			if(prevright)
			{
				if(commands.at(i) == ">")
				{
					commands.at(i - 1) = ">>";
					commands.erase(commands.begin() + i);
					i--;
				}
			}
			if(prevleft)
			{
				if(commands.at(i) == "<")
				{
					commands.at(i - 1) = "<<";
					commands.erase(commands.begin() + i);
					i--;
				}
			}
		}

		//check commands
		for(unsigned int i = 0; i < commands.size(); i++)
		{
			cout << "(" << commands.at(i) << ") ";
		}

		cout << "combined arguements into groups" << endl;
		if(!syntaxerror)
		{
			char *input[999];
			//exec commands
			for(unsigned int i = 0; i < commands.size(); i++)
			{
				string current = "";
				string word = "";
				int k = 0;
				for(unsigned int j = 0; j < commands.at(i).size(); j++) //itterate through letters
				{
					current = commands.at(i);
					if(current[j] == ' ')
					{
						input[k] = new char[word.size() + 1];
						strcpy(input[k], word.c_str());
						k++;
						word = "";
					}
					else
						word += current[j]; //add letter
				}
				input[k] = new char[word.size() + 1];
				strcpy(input[k], word.c_str());
				k++;

				input[k] = new char[1]; //add the NULL char *
				input[k] = NULL;

				if(commands.at(i) ==  "exit") //exit command
				{
					finish = true;
					cout << "ending session...";
					break;
				}

				else if(commands.at(i) == ";") //semicolon case
				{
					continue;
				}

				else if(commands.at(i) == "||") //double pipe case
				{
					if(status)
						continue;
					else
					{
						i++;
						continue;
					}
				}

				else if(commands.at(i) == "&&") //ampersand case
				{
					if(status == 0)
						continue;
					else
					{
						i++;
						continue;
					}
				}
				bool outputRedir = false;
				if(i + 1 < commands.size())
				{
					if(commands.at(i + 1) == ">") //HANDLE >
					{
						outputRedir = true;
					}
				}
				//execute command. based off of in-lecture notes
				int pid = fork();
				if(pid == -1)
				{
					perror("There was an error with fork(). ");
					exit(1);
				}
				else if(pid == 0) //in child
				{
					//cout << "CHILD IS RUNNING :D" << endl;
					//cout << input << endl;
					int fd = 0;
					//bool inputRedir = false;
					if(outputRedir)
					{
						if(i + 2 < commands.size())
						{
							if(-1 == close(1))
								perror("close");
							if((fd=open(commands.at(i + 2).c_str(),O_CREAT|O_WRONLY|O_TRUNC,0666))==-1)
								perror("open");
							if((dup2(fd,1))==-1)
							    perror("dup2");
						}
					}

					status = execvp(input[0], input);
					if(-1 == status)
					{
						perror("There was an error in execvp.");

					}

					exit(1);
				}
				else if(pid > 0) //in parent
				{
					if(-1 == waitpid(pid, &status, 0)) //wait for child to finish
						perror("There was an error with wait().");
					if(outputRedir)
						i = i + 2;
				}

			}

			//shell termination
			if(finish)
			{
				cout << "good-bye!" << endl;
				break;
			}
		}
	}
	return 0;
}
<|endoftext|>