<commit_before>/**
 * test_post_weights.cpp
 *
 *  Created on: Feb 4, 2010
 *      Author: Craig Rasmussen
 *
 * This file tests the conversion of pre-synaptic weight patches to post-synaptic
 * weight patches.
 *
 */

#undef DEBUG_PRINT

#include "../src/columns/HyPerCol.hpp"
#include "../src/layers/HyPerLayer.hpp"
#include "../src/connections/HyPerConn.hpp"
#include "../src/layers/Example.hpp"
#include "../src/io/ConnectionProbe.hpp"
#include "../src/io/PostConnProbe.hpp"

using namespace PV;

static int set_weights_to_source_index(HyPerConn * c);
static int check_weights(HyPerConn * c, PVPatch ** postWeights);

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

   int status = 0;

   HyPerCol  * hc = new HyPerCol("column", argc, argv);
   Example   * l1 = new Example("test_post_weights L1", hc);
   Example   * l2 = new Example("test_post_weights L2", hc);
   Example   * l3 = new Example("test_post_weights L3", hc);
   HyPerConn * c1 = new HyPerConn("test_post_weights L1 to L1", hc, l1, l1, CHANNEL_EXC);
   HyPerConn * c2 = new HyPerConn("test_post_weights L2 to L3", hc, l2, l3, CHANNEL_EXC);

   // set weights to be k index source in pre-synaptic layer
   //
   status = set_weights_to_source_index(c1);
   status = set_weights_to_source_index(c2);

   postWeights = c1->convertPreSynapticWeights(0.0f);
   status = check_weights(c1, postWeights);
   if (status) return status;

   postWeights = c2->convertPreSynapticWeights(0.0f);

   ConnectionProbe * cp = new ConnectionProbe(-1, -2, 0);
   c2->insertProbe(cp);

   PostConnProbe * pcp = new PostConnProbe(125);
   pcp->setOutputIndices(true);
   c2->insertProbe(pcp);

   c2->outputState(0);

   status = check_weights(c2, postWeights);
   if (status) return status;

   return status;
}

static int check_weights(HyPerConn * c, PVPatch ** postWeights)
{
   int status = 0;

   const int nxPre = c->preSynapticLayer()->clayer->loc.nx;
   const int nyPre = c->preSynapticLayer()->clayer->loc.ny;
   const int nfPre = c->preSynapticLayer()->clayer->loc.nBands;

   const int nPadPre = c->preSynapticLayer()->clayer->loc.nPad;

   const int nx = c->postSynapticLayer()->clayer->loc.nx;
   const int ny = c->postSynapticLayer()->clayer->loc.ny;
   const int nf = c->postSynapticLayer()->clayer->loc.nBands;

   const int numPatches = nx * ny * nf;

   // assume (or at least use) only one arbor (set of weight patches)
   for (int kPost = 0; kPost < numPatches; kPost++) {
      int kxPre, kyPre, kfPre = 0;

      const int kxPost = kxPos(kPost, nx, ny, nf);
      const int kyPost = kyPos(kPost, nx, ny, nf);
      const int kfPost = featureIndex(kPost, nx, ny, nf);

      PVPatch * p = postWeights[kPost];

      const int nxp = p->nx;
      const int nyp = p->ny;
      const int nfp = p->nf;

      // these strides are from the extended pre-synaptic layer, not the patch
      // NOTE: assumes nf from layer == nf from patch
      //
      const int sx = nfPre;
      const int sy = (nxPre + 2*nPadPre) * nfPre;
      const int sf = p->sf;

      pvdata_t * w = p->data;

      c->preSynapticPatchHead(kxPost, kyPost, kfPost, &kxPre, &kyPre);

      // convert to extended indices
      //
      kxPre += nPadPre;
      kyPre += nPadPre;

      int kPreHead = kIndex(kxPre, kyPre, kfPre, nxPre+2*nPadPre, nyPre+2*nPadPre, nfPre);

      // FIND OUT WHY THIS DOESN'T WORK
      //int kPreHead = kIndex(kxPre, kyPre, kfPre, nxPre, nyPre, nfPre);
      //kPreHead = kIndexExtended(kPreHead, nxPre, nyPre, nfPre, nPadPre);

      // loop over patch indices (writing out layer indices)
      //
      int kp = 0;
      for (int f = 0; f < nfp; f++) {
         for (int j = 0; j < nyp; j++) {
            for (int i = 0; i < nxp; i++) {
               int kPre = kPreHead + i*sx + j*sy + f*sf;

               if (kPre != (int) w[kp++]) {
                  status = -1;
                  fprintf(stderr, "ERROR: check_weights: kPost==%d kPre==%d kp==%d != w==%d\n",
                          kPost, kPre, kp, (int) w[kp-1]);
                  return status;
               }
            }
         }
      }

   } // end loop over weight patches

   return status;
}

static int set_weights_to_source_index(HyPerConn * c)
{
   int status = 0;
   int arbor = 0;
   short wPacked[2];

   assert(sizeof(short) == 2);

   const PVLayer * lPre  = c->preSynapticLayer()->clayer;
   const PVLayer * lPost = c->postSynapticLayer()->clayer;

   const int nxPre = c->preSynapticLayer()->clayer->loc.nx;
   const int nyPre = c->preSynapticLayer()->clayer->loc.ny;
   const int nfPre = c->preSynapticLayer()->clayer->loc.nBands;

   const int nPadPre = c->preSynapticLayer()->clayer->loc.nPad;

   const int nxPost = c->postSynapticLayer()->clayer->loc.nx;
   const int nyPost = c->postSynapticLayer()->clayer->loc.ny;
   const int nfPost = c->postSynapticLayer()->clayer->loc.nBands;

   int numPatches = c->numWeightPatches(arbor);

   // assume (or at least use) only one arbor (set of weight patches)
   // k index is in extended space
   for (int kPre = 0; kPre < numPatches; kPre++) {
      PVPatch * p = c->getWeights(kPre, arbor);

      const int nxp = p->nx;
      const int nyp = p->ny;
      const int nfp = p->nf;

      const int sxp = p->sx;
      const int syp = p->sy;
      const int sfp = p->sf;

      pvdata_t * w = p->data;

      int kxPre = kxPos(kPre, nxPre+2*nPadPre, nyPre+2*nPadPre, nfPre);
      int kyPre = kxPos(kPre, nxPre+2*nPadPre, nyPre+2*nPadPre, nfPre);

      int kxPatchHead = zPatchHead(kxPre-nPadPre, nxp, lPre->xScale, lPost->xScale);
      int kyPatchHead = zPatchHead(kyPre-nPadPre, nyp, lPre->xScale, lPost->xScale);

      for (int y = 0; y < nyp; y++) {
         for (int x = 0; x < nxp; x++) {
            for (int f = 0; f < nfp; f++) {
               int kxPost = kxPatchHead + x;
               int kyPost = kyPatchHead + y;
               int kPost = kIndex(kxPost, kyPost, f, nxPost, nyPost, nfPost);

               wPacked[0] = kPre;
               wPacked[1] = kPost;
               //w[x*sxp + y*syp + f*sfp] = * ((float *) wPacked);
               w[x*sxp + y*syp + f*sfp] = kPre;
            }
         }
      }

   } // end loop over weight patches

   return status;
}
<commit_msg>Improved test by adding both pre and post indices to patch weights.<commit_after>/**
 * test_post_weights.cpp
 *
 *  Created on: Feb 4, 2010
 *      Author: Craig Rasmussen
 *
 * This file tests the conversion of pre-synaptic weight patches to post-synaptic
 * weight patches.
 *
 */

#undef DEBUG_PRINT

#include "../src/columns/HyPerCol.hpp"
#include "../src/layers/HyPerLayer.hpp"
#include "../src/connections/HyPerConn.hpp"
#include "../src/layers/Example.hpp"
#include "../src/io/ConnectionProbe.hpp"
#include "../src/io/PostConnProbe.hpp"

using namespace PV;

static int set_weights_to_source_index(HyPerConn * c);
static int check_weights(HyPerConn * c, PVPatch ** postWeights);

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

   int status = 0;

   HyPerCol  * hc = new HyPerCol("column", argc, argv);
   Example   * l1 = new Example("test_post_weights L1", hc);
   Example   * l2 = new Example("test_post_weights L2", hc);
   Example   * l3 = new Example("test_post_weights L3", hc);
   HyPerConn * c1 = new HyPerConn("test_post_weights L1 to L1", hc, l1, l1, CHANNEL_EXC);
   HyPerConn * c2 = new HyPerConn("test_post_weights L2 to L3", hc, l2, l3, CHANNEL_EXC);

   // set weights to be k index source in pre-synaptic layer
   //
   status = set_weights_to_source_index(c1);
   status = set_weights_to_source_index(c2);

   postWeights = c1->convertPreSynapticWeights(0.0f);
   status = check_weights(c1, postWeights);
   if (status) return status;

   postWeights = c2->convertPreSynapticWeights(0.0f);
   status = check_weights(c2, postWeights);
   if (status) return status;

#ifdef DEBUG_PRING
   ConnectionProbe * cp = new ConnectionProbe(-1, -2, 0);
   c2->insertProbe(cp);

   PostConnProbe * pcp = new PostConnProbe(0);
   pcp->setOutputIndices(true);
   c2->insertProbe(pcp);

   c2->outputState(0);
#endif

   return status;
}

static int check_weights(HyPerConn * c, PVPatch ** postWeights)
{
   int status = 0;

   const int nxPre = c->preSynapticLayer()->clayer->loc.nx;
   const int nyPre = c->preSynapticLayer()->clayer->loc.ny;
   const int nfPre = c->preSynapticLayer()->clayer->loc.nBands;

   const int nPadPre = c->preSynapticLayer()->clayer->loc.nPad;

   const int nx = c->postSynapticLayer()->clayer->loc.nx;
   const int ny = c->postSynapticLayer()->clayer->loc.ny;
   const int nf = c->postSynapticLayer()->clayer->loc.nBands;

   const int numPatches = nx * ny * nf;

   // assume (or at least use) only one arbor (set of weight patches)
   for (int kPost = 0; kPost < numPatches; kPost++) {
      int kxPre, kyPre, kfPre = 0;

      const int kxPost = kxPos(kPost, nx, ny, nf);
      const int kyPost = kyPos(kPost, nx, ny, nf);
      const int kfPost = featureIndex(kPost, nx, ny, nf);

      PVPatch * p = postWeights[kPost];

      const int nxp = p->nx;
      const int nyp = p->ny;
      const int nfp = p->nf;

      // these strides are from the extended pre-synaptic layer, not the patch
      // NOTE: assumes nf from layer == nf from patch
      //
      const int sx = nfPre;
      const int sy = (nxPre + 2*nPadPre) * nfPre;
      const int sf = p->sf;

      pvdata_t * w = p->data;

      c->preSynapticPatchHead(kxPost, kyPost, kfPost, &kxPre, &kyPre);

      // convert to extended indices
      //
      kxPre += nPadPre;
      kyPre += nPadPre;

      int kPreHead = kIndex(kxPre, kyPre, kfPre, nxPre+2*nPadPre, nyPre+2*nPadPre, nfPre);

      // FIND OUT WHY THIS DOESN'T WORK
      //int kPreHead = kIndex(kxPre, kyPre, kfPre, nxPre, nyPre, nfPre);
      //kPreHead = kIndexExtended(kPreHead, nxPre, nyPre, nfPre, nPadPre);

      // loop over patch indices (writing out layer indices)
      //
      int kp = 0;
      for (int f = 0; f < nfp; f++) {
         for (int j = 0; j < nyp; j++) {
            for (int i = 0; i < nxp; i++) {
               short * ws;
               int kPre = kPreHead + i*sx + j*sy + f*sf;

               ws = (short *) &w[kp++];

               if (kPre != (int) ws[0] || kPost != (int) ws[1]) {
                  status = -1;
                  fprintf(stderr, "ERROR: check_weights: kPost==%d kPre==%d kp==%d != w==%d\n",
                          kPost, kPre, kp, (int) w[kp-1]);
                  return status;
               }
            }
         }
      }

   } // end loop over weight patches

   return status;
}

static int set_weights_to_source_index(HyPerConn * c)
{
   int status = 0;
   int arbor = 0;
   short wPacked[2];

   assert(sizeof(short) == 2);

   const PVLayer * lPost = c->postSynapticLayer()->clayer;

   const int nxPost = lPost->loc.nx;
   const int nyPost = lPost->loc.ny;
   const int nfPost = lPost->loc.nBands;

   int numPatches = c->numWeightPatches(arbor);

   // assume (or at least use) only one arbor (set of weight patches)
   // k index is in extended space
   for (int kPre = 0; kPre < numPatches; kPre++) {
      int kxPostHead, kyPostHead, kfPostHead;
      int nxp, nyp;
      int dx, dy;
      PVPatch * p = c->getWeights(kPre, arbor);

      c->postSynapticPatchHead(kPre, &kxPostHead, &kyPostHead, &kfPostHead, &dx, &dy, &nxp, &nyp);

      const int nfp = p->nf;

      assert(nxp == p->nx);
      assert(nyp == p->ny);
      assert(nfp == lPost->numFeatures);

      const int sxp = p->sx;
      const int syp = p->sy;
      const int sfp = p->sf;

      pvdata_t * w = p->data;

      for (int y = 0; y < nyp; y++) {
         for (int x = 0; x < nxp; x++) {
            for (int f = 0; f < nfp; f++) {
               int kxPost = kxPostHead + x;
               int kyPost = kyPostHead + y;
               int kfPost = kfPostHead + f;
               int kPost = kIndex(kxPost, kyPost, kfPost, nxPost, nyPost, nfPost);

               wPacked[0] = kPre;
               wPacked[1] = kPost;
               w[x*sxp + y*syp + f*sfp] = * ((float *) wPacked);
               //w[x*sxp + y*syp + f*sfp] = kPre;
            }
         }
      }

   } // end loop over weight patches

   return status;
}
<|endoftext|>


<commit_before>/*
 *  solarsystem.cpp
 *  SolarSystem
 *
 *  Created by Jadzia on 1/1/09.
 *  Copyright 2009 Rachel Reddick. All rights reserved.
 *
 */

#include "solarsystem.h"
#include "orbital.h"
#include "parameter_readin.h"

int main(int argc, char **argv) {
    //Time to figure out the input arguments
    if(argc < 2) {
        cout << "ERROR: Insufficient number of arguments" << endl;
        cout << "FORMAT: " << endl;
        exit(1);
    }

    int myarg = 0;
    //Arguments needed:
    //Input file name
    string filename = argv[1];

    //Type of position input -- X, Y, Z, or orbital elements?
    //Default X, Y, Z

    //Size of timestep (in seconds)
    //Default 1 hour

    //Total desired runtime
    //Default is 3 Earth-years

    //How often to output positions
    //Default is every time step

    //Read the input file
    vector<valarray<long double> > positions;
    vector<string> names;
    positions = ReadParameterFile(filename, 0, names);

    //Initialize the solar system
    //Note that this includes setting the timestep
    SolarSystem system;
    long double dt = 3600.;
    system.Initialize(dt, "");

    //Add the Sun as a planet
    valarray<long double> solar_position(6);
    solar_position[0] = 0.; solar_position[1] = 0.; solar_position[2] = 0.;
    solar_position[3] = 0.; solar_position[4] = -0.0894690; solar_position[5] = 0.;
    system.AddPlanet(1.9891e30, 6.96e8, solar_position, 0., "TheSun");

    //Add the Earth as a planet
    valarray<long double> initial(6);
    long double eccEarth = 0.01671;
    long double semimajorEarth = 1.49498e11; //m
    long double semiminorEarth = semimajorEarth*sqrt(1-eccEarth*eccEarth); //m
    long double incEarth = 1.+34/60. ; //degrees
    long double ascNodeEarth = 348.74; //degrees
    long double argPeriEarth = 114.21; //degrees
    long double startAngle = 0;
    //initial conditions set to ascending node
    initial = orbitalElementConverter(semimajorEarth,semiminorEarth,incEarth,ascNodeEarth,argPeriEarth,startAngle);
    system.AddPlanet(5.972e24, 6.371e6, initial, 0., "TheEarth");

    cout<<initial[0]<<" "<<initial[1]<<" "<<initial[2]<<" "<<initial[3]<<" "<<initial[4]<<" "<<initial[5]<<endl;
    cout<<"Radius: "<<sqrt(initial[0]*initial[0]+initial[1]*initial[1])<<endl;
    cout<<"Velocity: "<<sqrt(initial[3]*initial[3]+initial[4]*initial[4])<<endl;
    cout<<incEarth*M_PI/180<<endl;

    //Add Jupiter as a planet
    initial = orbitalElementConverter(7.785e11, 7.785e11*sqrt(1-0.0488*0.0488), 1.305, 100.492, 275.066, 0);
    system.AddPlanet(1.899e27, 7.15e7, initial, 0, "Jupiter");

    //Recenter our system on the center of mass
    system.MoveToCenterOfMass();

    //Run everything!
    cout << "Ready to run!" << endl;
    system.PrintPlanets();
    RunTheSystem(system, 10*365.24*24.*3600.);
    //RunTheSystem(system, 50*3600.);

return(0);
}
<commit_msg>Updated now so that the input parameter file for the set of objects is actually used to initialize the planets<commit_after>/*
 *  solarsystem.cpp
 *  SolarSystem
 *
 *  Created by Jadzia on 1/1/09.
 *  Copyright 2009 Rachel Reddick. All rights reserved.
 *
 */

#include "solarsystem.h"
#include "orbital.h"
#include "parameter_readin.h"

int main(int argc, char **argv) {
    //Time to figure out the input arguments
    if(argc < 2) {
        cout << "ERROR: Insufficient number of arguments" << endl;
        cout << "FORMAT: " << endl;
        exit(1);
    }

    int myarg = 0;
    int filetype = 0;
    //Arguments needed:
    //Input file name
    string filename = argv[1];

    //Type of position input -- X, Y, Z, or orbital elements?
    //Default X, Y, Z

    //Size of timestep (in seconds)
    //Default 1 hour

    //Total desired runtime
    //Default is 3 Earth-years

    //How often to output positions
    //Default is every time step
    filetype = 0;

    //Where to place the output files
    //Default is current working directory
    string output_directory = "";

    //Read the input file
    vector<valarray<long double> > positions;
    vector<string> names;
    cout << "Ready for readin" << endl;
    positions = ReadParameterFile(filename, filetype, names);
    cout << "Readin complete" << endl;

    //Initialize the solar system
    //Note that this includes setting the timestep
    SolarSystem system;
    long double dt = 3600.;
    system.Initialize(dt, output_directory);

    //Add all the desired input objects
    valarray<long double> xtemp(6);
    for(int i=0; i<positions.size(); i++) {
        for(int j=0; j<6; j++){
            xtemp[j] = positions[i][j+2];
        }
        system.AddPlanet(positions[i][0], positions[i][1], xtemp, 0, names[i]);
    }
    cout << "Done initializing " << positions.size() << " objects" << endl;

    //Recenter our system on the center of mass
    system.MoveToCenterOfMass();

    //Run everything!
    cout << "Ready to run!" << endl;
    system.PrintPlanets();
    RunTheSystem(system, 10*365.24*24.*3600.);
    //RunTheSystem(system, 50*3600.);

return(0);
}
<|endoftext|>


<commit_before>#include "Boid.h"

void Boid::seek(sf::Vector2f& target) {
	auto desired = target - location;
	desired = maxSpeed * norm(desired);
	auto steer = desired - velocity;
	if (mag(steer) > maxForce) {
		steer = norm(steer) * coheseCoef * maxForce;
	}
	applyForce(steer);
};

void Boid::separate(const std::vector<Boid>& v_vec) {
	auto averageRepulsVec = sf::Vector2f{ 0,0 };
	int cntr = 0;
	for (auto veh : v_vec) {
		auto d = mag(location - veh.getLocation());

		if (d > 0 && d < desiredSeparation) {
			averageRepulsVec += norm(location - veh.getLocation()) / d;
			++cntr;
		}

	}
	if (cntr > 0) {
		averageRepulsVec = maxSpeed * norm(averageRepulsVec) / cntr;
		auto steer = averageRepulsVec - velocity;
		if (mag(steer) > maxForce)
			steer = norm(steer) *separateCoef* maxForce;
		applyForce(steer);
	}

}

void Boid::align(const std::vector<Boid>& v_vec) {
	auto averageAlignVec = sf::Vector2f{ 0,0 };
	int cntr = 0;
	for (auto veh : v_vec) {
		auto d = mag(location - veh.getLocation());

		if (d > 0 && d < visionRadius) {
			averageAlignVec += veh.getVelocity();
			++cntr;
		}

	}
	if (cntr > 0) {
		averageAlignVec = maxSpeed * norm(averageAlignVec) / cntr;
		auto steer = averageAlignVec - velocity;
		if (mag(steer) > maxForce)
			steer = norm(steer) * alignCoef * maxForce;
		applyForce(steer);
	}
}

void Boid::cohese(const std::vector<Boid>& v_vec) {
	auto averageCoheseVec = sf::Vector2f{ 0,0 };
	int cntr = 0;
	for (auto veh : v_vec) {
		auto d = mag(location - veh.getLocation());

		if (d > 0 && d < visionRadius) {
			averageCoheseVec += veh.getLocation();
			++cntr;
		}

	}
	if (cntr > 0) {
		averageCoheseVec = averageCoheseVec / cntr;
		seek(averageCoheseVec);
	}
}

void Boid::swarm(const std::vector<Boid>& v_vec) {
	auto averageRepulsVec = sf::Vector2f{ 0,0 };
	auto averageAlignVec  = averageRepulsVec;
	auto averageCoheseVec = averageRepulsVec;

	int cntrRepuls = 0;
	int cntrAC = 0;

	for (auto& veh : v_vec) {
		auto otherVec = veh.getLocation();
		auto d = mag(location - otherVec);

		if (d > 0 && d < visionRadius) {
			averageAlignVec  += veh.getVelocity();
			averageCoheseVec += otherVec;
			++cntrAC;
			if (d > 0 && d < desiredSeparation) {
				averageRepulsVec += norm(location - otherVec) / d;
				++cntrRepuls;
			}
		}
	}

	if (cntrRepuls > 0) {
		averageRepulsVec = maxSpeed * norm(averageRepulsVec) / cntrRepuls;
		auto steer = averageRepulsVec - velocity;
		if (mag(steer) > maxForce)
			steer = norm(steer) *separateCoef* maxForce;
		applyForce(steer);
	}

	if (cntrAC > 0) {
		averageAlignVec = maxSpeed * norm(averageAlignVec) / cntrAC;
		auto steer = averageAlignVec - velocity;
		if (mag(steer) > maxForce)
			steer = norm(steer) * alignCoef * maxForce;
		applyForce(steer);

		averageCoheseVec = averageCoheseVec / cntrAC;
		seek(averageCoheseVec);
	}
}

void Boid::ignoreEdges(const sf::RenderWindow& window) {
	int win_x = window.getSize().x;
	int win_y = window.getSize().y;
	int diameter = 2 * getRadius();

	if (location.x > win_x) {
		location.x = 0;
	}
	else if (location.x < 0) {
		location.x = win_x;
	}

	if (location.y > win_y) {
		location.y = 0;
	}
	else if (location.y < 0) {
		location.y = win_y ;
	}
}

void Boid::checkEdges(const sf::RenderWindow& window) {
	int win_x = window.getSize().x;
	int win_y = window.getSize().y;
	int diameter = 2 * getRadius();

	if (location.x >= win_x - diameter) {
		velocity.x *= -1;
		location.x = win_x - diameter;
	}
	else if (location.x <= 0) {
		velocity.x *= -1;
		location.x = 0;
	}

	if (location.y >= win_y - diameter) {
		velocity.y *= -1;
		location.y = win_y - diameter;
	}
	else if (location.y <= 0) {
		velocity.y *= -1;
		location.y = 0;
	}
}

void Boid::update(const sf::RenderWindow& window) {
	velocity += acceleration;
	limit(maxSpeed);
	location += velocity;
	ignoreEdges(window);
	shape.setPosition(location);
	acceleration = sf::Vector2f(0, 0);
}

void Boid::draw(sf::RenderWindow& window) {
	window.draw(shape);
}

<commit_msg>Update Boid.cpp<commit_after>#include "Boid.h"

void Boid::seek(sf::Vector2f& target) {
	auto desired = target - location;
	desired = boid_params.maxSpeed * norm(desired);
	auto steer = desired - velocity;
	if (mag(steer) > boid_params.maxForce) {
		steer = norm(steer) * boid_params.coheseCoef * boid_params.maxForce;
	}
	applyForce(steer);
};

void Boid::swarm(const std::vector<Boid>& v_vec) {
	auto averageRepulsVec = sf::Vector2f{ 0,0 };
	auto averageAlignVec  = averageRepulsVec;
	auto averageCoheseVec = averageRepulsVec;

	int cntrRepuls = 0;
	int cntrAC = 0;

	for (auto& veh : v_vec) {
		auto otherVec = veh.getLocation();
		auto d = mag(location - otherVec);

		if (d > 0 && d < boid_params.visionRadius) {
			averageAlignVec  += veh.getVelocity();
			averageCoheseVec += otherVec;
			++cntrAC;
			if (d > 0 && d < boid_params.desiredSeparation) {
				averageRepulsVec += norm(location - otherVec) / d;
				++cntrRepuls;
			}
		}
	}

	if (cntrRepuls > 0) {
		averageRepulsVec = boid_params.maxSpeed * norm(averageRepulsVec) / cntrRepuls;
		auto steer = averageRepulsVec - velocity;
		if (mag(steer) > boid_params.maxForce)
			steer = norm(steer) *boid_params.separateCoef* boid_params.maxForce;
		applyForce(steer);
	}

	if (cntrAC > 0) {
		averageAlignVec = boid_params.maxSpeed * norm(averageAlignVec) / cntrAC;
		auto steer = averageAlignVec - velocity;
		if (mag(steer) > boid_params.maxForce)
			steer = norm(steer) * boid_params.alignCoef * boid_params.maxForce;
		applyForce(steer);

		averageCoheseVec = averageCoheseVec / cntrAC;
		seek(averageCoheseVec);
	}
}

void parallel_swarm(const std::vector<Boid*>& v_ptr,
	const std::vector<Boid*>::iterator& start,
	const std::vector<Boid*>::iterator& end)
{
	// check if ( v_boids().empty() ) ?
	auto& boid_params = v_ptr[0]->getBoidParams();

	for (auto ptr = start; ptr != end; ++ptr){

		auto averageRepulsVec = sf::Vector2f{ 0,0 };
		auto averageAlignVec = averageRepulsVec;
		auto averageCoheseVec = averageRepulsVec;

		int cntrRepuls = 0;
		int cntrAC = 0;

		auto& curr_boid = **ptr; // hmm

		for (auto& boid : v_ptr) {
			auto d = mag(curr_boid.getLocation() - boid->getLocation());

			if (d > 0 && d < boid_params.visionRadius) {
				averageAlignVec += boid->getVelocity();
				averageCoheseVec += boid->getLocation();
				++cntrAC;

				if (d < boid_params.desiredSeparation) {
					averageRepulsVec += norm(curr_boid.getLocation() - boid->getLocation()) / d;
					++cntrRepuls;
				}
			}

		}

		if (cntrRepuls > 0) {
			averageRepulsVec = boid_params.maxSpeed * norm(averageRepulsVec) / cntrRepuls;
			auto steer = averageRepulsVec - curr_boid.getVelocity();
			if (mag(steer) > boid_params.maxForce)
				steer = norm(steer) * boid_params.separateCoef * boid_params.maxForce;
			curr_boid.applyForce(steer);
		}

		if (cntrAC > 0) {
			averageAlignVec = boid_params.maxSpeed * norm(averageAlignVec) / cntrAC;
			auto steer = averageAlignVec - curr_boid.getVelocity();
			if (mag(steer) > boid_params.maxForce)
				steer = norm(steer) * boid_params.alignCoef * boid_params.maxForce;
			curr_boid.applyForce(steer);

			averageCoheseVec = averageCoheseVec / cntrAC;
			curr_boid.seek(averageCoheseVec);
		}
	}

}

void Boid::ignoreEdges(const sf::RenderWindow& window) {
	int win_x = window.getSize().x;
	int win_y = window.getSize().y;
	int diameter = 2 * getRadius();

	if (location.x > win_x) {
		location.x = 0;
	}
	else if (location.x < 0) {
		location.x = win_x;
	}

	if (location.y > win_y) {
		location.y = 0;
	}
	else if (location.y < 0) {
		location.y = win_y ;
	}
}

void Boid::checkEdges(const sf::RenderWindow& window) {
	int win_x = window.getSize().x;
	int win_y = window.getSize().y;
	int diameter = 2 * getRadius();

	if (location.x >= win_x - diameter) {
		velocity.x *= -1;
		location.x = win_x - diameter;
	}
	else if (location.x <= 0) {
		velocity.x *= -1;
		location.x = 0;
	}

	if (location.y >= win_y - diameter) {
		velocity.y *= -1;
		location.y = win_y - diameter;
	}
	else if (location.y <= 0) {
		velocity.y *= -1;
		location.y = 0;
	}
}

void Boid::update(const sf::RenderWindow& window) {
	velocity += acceleration;
	limit(boid_params.maxSpeed);
	location += velocity;
	ignoreEdges(window);
	shape.setPosition(location);
	acceleration = sf::Vector2f(0, 0);
}

void Boid::draw(sf::RenderWindow& window) {
	window.draw(shape);
}

<|endoftext|>


<commit_before>///
/// Book.cpp
/// Manages the eBook.
///

#include <cmath>
#include <numeric>
#include <fstream>
#include <iostream>
#include <algorithm>

#include "pp2d/pp2d.h"
#include "tinyxml2/tinyxml2.h"

#include "Book.hpp"

using namespace tinyxml2;

void shortenString(std::vector<std::string>& vec, std::string str)
{
	if (str.size() > 715)
	{
		std::string final = str.substr(0, 715);
		vec.push_back(final);

		std::string rest = str.substr(716, str.size());
		shortenString(vec, final);
	}
	else
	{
		vec.push_back(str);
	}
}

Book::Book(const std::string& epub)
{
    m_book = "sdmc:/books/" + epub;
    BLUnZip zip(m_book);

    parseContainer(zip);
    parseOPF(zip);
    parsePages(zip);

    zip.Close();
}

Book::~Book()
{
    m_manifest.clear();
    m_spine.clear();
    m_text.clear();

    m_book = "";
    m_opf = "";
    m_title = "";
    m_author = "";
    m_container = "";
}

void Book::parseContainer(BLUnZip& zip)
{
    std::string data = zip.ExtractToString("META-INF/container.xml");

    XMLDocument doc;
    doc.Parse(data.c_str());

    XMLElement* container = doc.FirstChildElement("container");
    XMLElement* rootfiles = container->FirstChildElement("rootfiles");
    XMLElement* rootfile = rootfiles->FirstChildElement("rootfile");

    m_opf = rootfile->Attribute("full-path");

    auto pos = m_opf.find("content.opf");
    if (pos == 0)
    {
        m_container = "";
    }
    else
    {
        m_container = m_opf.substr(0, pos);
    }
}

void Book::parseOPF(BLUnZip& zip)
{
    std::string data = zip.ExtractToString(m_opf);

    XMLDocument doc;
    doc.Parse(data.c_str());

    XMLElement* package = doc.FirstChildElement("package");
    XMLElement* metadata = package->FirstChildElement("metadata");
    XMLElement* manifest = package->FirstChildElement("manifest");
    XMLElement* item = manifest->FirstChildElement("item");

    m_title = metadata->FirstChildElement("dc:title")->GetText();
    m_author = metadata->FirstChildElement("dc:creator")->GetText();

    for(XMLElement* rfe = item; rfe != nullptr; rfe = rfe->NextSiblingElement("item"))
    {
       m_manifest.emplace(rfe->Attribute("id"), rfe->Attribute("href"));
    }

    XMLElement* spine = package->FirstChildElement("spine");
    XMLElement* itemref = spine->FirstChildElement("itemref");

    for (XMLElement* it = itemref; it != nullptr; it = it->NextSiblingElement("itemref"))
    {
        m_spine.push_back(it->Attribute("idref"));
    }
}

void Book::parsePages(BLUnZip& zip)
{
    for (size_t i = 0; i < m_spine.size(); ++i)
    {
        std::string data = zip.ExtractToString(m_container + m_manifest[m_spine[i]]);

        XMLDocument doc;
        doc.Parse(data.c_str());

        XMLElement* html = doc.FirstChildElement("html");
    	XMLElement* body = html->FirstChildElement("body");

        for (XMLElement* next = body->FirstChildElement(); next != nullptr; next = next->NextSiblingElement())
        {
        	if (next)
        	{
        		const char* textStr = next->GetText();
            	if (textStr)
            	{
            		shortenString(m_text, textStr);
            	}
        	}
        }
    }
}

const std::vector<std::string>& Book::getBookText() const
{
    return m_text;
}<commit_msg>Book.cpp: fix shortenString<commit_after>///
/// Book.cpp
/// Manages the eBook.
///

#include <cmath>
#include <numeric>
#include <fstream>
#include <iostream>
#include <algorithm>

#include "pp2d/pp2d.h"
#include "tinyxml2/tinyxml2.h"

#include "Book.hpp"

using namespace tinyxml2;

static void shortenString(std::vector<std::string>& vec, std::string& str)
{
	if (str.size() > 715)
	{
		std::string&& chunk = str.substr(0, 715);
		vec.push_back(chunk);

		str.erase(0, 715);
		shortenString(vec, str);
	}
	else
	{
		vec.push_back(str);
	}
}

Book::Book(const std::string& epub)
{
    m_book = "sdmc:/books/" + epub;
    BLUnZip zip(m_book);

    parseContainer(zip);
    parseOPF(zip);
    parsePages(zip);

    zip.Close();
}

Book::~Book()
{
    m_manifest.clear();
    m_spine.clear();
    m_text.clear();

    m_book = "";
    m_opf = "";
    m_title = "";
    m_author = "";
    m_container = "";
}

void Book::parseContainer(BLUnZip& zip)
{
    std::string data = zip.ExtractToString("META-INF/container.xml");

    XMLDocument doc;
    doc.Parse(data.c_str());

    XMLElement* container = doc.FirstChildElement("container");
    XMLElement* rootfiles = container->FirstChildElement("rootfiles");
    XMLElement* rootfile = rootfiles->FirstChildElement("rootfile");

    m_opf = rootfile->Attribute("full-path");

    auto pos = m_opf.find("content.opf");
    if (pos == 0)
    {
        m_container = "";
    }
    else
    {
        m_container = m_opf.substr(0, pos);
    }
}

void Book::parseOPF(BLUnZip& zip)
{
    std::string data = zip.ExtractToString(m_opf);

    XMLDocument doc;
    doc.Parse(data.c_str());

    XMLElement* package = doc.FirstChildElement("package");
    XMLElement* metadata = package->FirstChildElement("metadata");
    XMLElement* manifest = package->FirstChildElement("manifest");
    XMLElement* item = manifest->FirstChildElement("item");

    m_title = metadata->FirstChildElement("dc:title")->GetText();
    m_author = metadata->FirstChildElement("dc:creator")->GetText();

    for(XMLElement* rfe = item; rfe != nullptr; rfe = rfe->NextSiblingElement("item"))
    {
       m_manifest.emplace(rfe->Attribute("id"), rfe->Attribute("href"));
    }

    XMLElement* spine = package->FirstChildElement("spine");
    XMLElement* itemref = spine->FirstChildElement("itemref");

    for (XMLElement* it = itemref; it != nullptr; it = it->NextSiblingElement("itemref"))
    {
        m_spine.push_back(it->Attribute("idref"));
    }
}

void Book::parsePages(BLUnZip& zip)
{
    for (size_t i = 0; i < m_spine.size(); ++i)
    {
        std::string data = zip.ExtractToString(m_container + m_manifest[m_spine[i]]);

        XMLDocument doc;
        doc.Parse(data.c_str());

        XMLElement* html = doc.FirstChildElement("html");
    	XMLElement* body = html->FirstChildElement("body");

        for (XMLElement* next = body->FirstChildElement(); next != nullptr; next = next->NextSiblingElement())
        {
        	if (next)
        	{
        		const char* textStr = next->GetText();
			if (textStr)
			{
				std::string str(textStr);
				shortenString(m_text, str);
			}
        	}
        }
    }
}

const std::vector<std::string>& Book::getBookText() const
{
    return m_text;
}
<|endoftext|>


<commit_before>#include <cmath>
#include <iostream>

#include "grid.hpp"
#include "observers.hpp"
#include "model.hpp"
#include "photons.hpp"

double FlaredDisk::density(double x, double y, double z) const
{
    double const r2 = x*x + y*y;
    double const r  = std::sqrt(r2);

    // Disk Geometry
    if(( r >= rInner_ ) && ( r <= rOuter_ ))
    {
        double const h = h0_ * std::pow(r/r0_, beta_);
        return rho0_ * std::pow(r0_ / r, alpha_) * std::exp(-0.5*z*z / (h*h)); // rho in g/cm^3
    } else {
        return 0.0;
    }
}

Grid::Grid(
        double const xmax,
        double const ymax,
        double const zmax,
        double const kappa,
        uint32_t const nx,
        uint32_t const ny,
        uint32_t const nz,
        FlaredDiskCPtr disk)
    : nx_{ nx }
    , ny_{ ny }
    , nz_{ nz }
    , xmax_{ xmax }
    , ymax_{ ymax }
    , zmax_{ zmax }
    , disk_{ std::move(disk) }
{
    rhokappa_ = new double[nx_ * ny_ * nz_];
    minrho_ = 1e+38;

    for (size_t cntx=0; cntx!=nx_; ++cntx)
    {
        double const x = (cntx*2.0+1) * xmax_/nx_ - xmax_;
        for (size_t cnty=0; cnty!=ny_; ++cnty)
        {
            double const y=(cnty*2.0+1) * ymax_/ny_ - ymax_;
            for (size_t cntz=0; cntz!=nz_; ++cntz)
            {
                double const z=(cntz*2.0+1) * zmax_/nz_ - zmax_;
                size_t const idx = cntx+cnty*nx+cntz*ny*nx;
                rhokappa_[idx] = disk_->density(x, y, z) * kappa * 1.5e13; // rho*kappa*R,
                if (minrho_ > rhokappa_[idx] && rhokappa_[idx] > 0)
                    minrho_ = rhokappa_[idx];
            }
        }
    }
}

// calculate smax -- maximum distance photon can travel *******
double Grid::maxDistance(Photon const& ph) const
{
    double dsx=0.0, dsy=0.0, dsz=0.0, smax =0.0;
    if(ph.dir().x() > 0.0) {
        dsx = (xmax_ - ph.pos().x()) / ph.dir().x();
    } else if(ph.dir().x() < 0.0) {
        dsx =-(ph.pos().x() + xmax_) / ph.dir().x();
    } else {
        dsx = 200.0*xmax_;
    }
    if(ph.dir().y() > 0.0) {
        dsy = (ymax_ - ph.pos().y()) / ph.dir().y();
    } else if(ph.dir().y() < 0.0) {
        dsy =-(ph.pos().y() + ymax_) / ph.dir().y();
    } else {
        dsy =200.0*ymax_;
    }
    if(ph.dir().z() > 0.0) {
        dsz= (zmax_ - ph.pos().z()) / ph.dir().z();
    } else if(ph.dir().z() < 0.0) {
        dsz=-(ph.pos().z() + zmax_) / ph.dir().z();
    } else {
        dsz=200.0*zmax_;
    }
    smax = ( dsx < dsy) ? dsx  : dsy;
    smax = (smax < dsz) ? smax : dsz;
    return smax;
}

// find distance to next x, y, and z cell walls.
// note that dx is not the x-distance, but the actual distance along
// the direction of travel to the next x-face, and likewise for dy and dz.
double Grid::cellDistance(Photon& ph, double delta) const
{
    double dx=200.0*xmax_, dy=200.0*ymax_, dz=200.0*zmax_, dcell=0.0;
    if (delta < 0.0) delta=0.0001*(2.*xmax_/nx_);
    double tmp = 2.0*xmax_/nx_;
    if(ph.dir().x() > 0.0)
    {
        dx = (( int( (ph.pos().x()+xmax_) / tmp ) + 1.0 )* tmp - xmax_ - ph.pos().x() )/ph.dir().x();
        if (dx < delta)
        {
            dx = tmp/ph.dir().x();
            ph.x() = (int( (ph.pos().x()+xmax_) / tmp ) + 1.0 )*tmp - xmax_ + delta;
        }
    } else if (ph.dir().x() < 0.0) {
        dx = (( int( (ph.pos().x()+xmax_)/ tmp ) )* tmp - xmax_ - ph.pos().x() )/ph.dir().x();
        if (dx < delta)
        {
            dx =-tmp/ph.dir().x();
            ph.x() = ( int( (ph.pos().x()+xmax_)/tmp) )* tmp - xmax_ - delta;
        }
    }

    tmp = 2.0*ymax_/ny_;
    if(ph.dir().y() > 0.0)
    {
        dy = (( int( (ph.pos().y()+ymax_)/tmp ) + 1.0 )* tmp - ymax_ - ph.pos().y() )/ph.dir().y();
        if (dy < delta)
        {
            dy = tmp/ph.dir().y();
            ph.y() = (int( (ph.pos().y()+ymax_)/tmp) + 1.0 )* tmp - ymax_+ delta;
        }
    } else if (ph.dir().y() < 0.0) {
        dy = (( int( (ph.pos().y()+ymax_)/tmp ) )*tmp - ymax_ - ph.pos().y() )/ph.dir().y();
        if (dy < delta)
        {
            dy =-tmp/ph.dir().y();
            ph.y() = ( int( (ph.pos().y()+xmax_)/tmp ) )* tmp - ymax_ - delta;
        }
    }

    tmp=2.0*zmax_/nz_;
    if(ph.dir().z() > 0.0)
    {
        dz = (( int( (ph.pos().z()+zmax_)/tmp ) + 1.0 )* tmp - zmax_ - ph.pos().z() )/ph.dir().z();
        if (dz < delta)
        {
            dz = tmp/ph.dir().z();
            ph.z() = (int( (ph.pos().z()+zmax_)/tmp ) + 1.0 )* tmp - zmax_ + delta;
        }
    } else if (ph.dir().z() < 0.0) {
        dz = (( int( (ph.pos().z()+zmax_)/tmp ))* tmp- zmax_ - ph.pos().z() )/ph.dir().z();
        if (dz < delta)
        {
            dz =-tmp/ph.dir().z();
            ph.z() = ( int( (ph.pos().z()+zmax_)/tmp ) )* tmp - zmax_ - delta;
        }
    }

    dcell = ( dx   < dy ) ? dx    : dy;
    dcell = (dcell < dz ) ? dcell : dz;
//	printf("d %g %g %g \n", dx, dy, dz);
    return dcell;
}

double Grid::findOpticalDepth( Photon ph, double delta ) const
{
    double taurun=0.0, d=0.0;

    if (delta < 0.0 ) delta=0.0001*(2.*xmax_/nx_);
    double const smax = maxDistance(ph);

    if(smax < delta)
    {
        return 0.0;
    }

    while (d < 0.999*smax)
    {
        double const dcell = cellDistance(ph, delta);
        auto const x = uint32_t( (ph.pos().x()+xmax_)*nx_ / 2.0 / xmax_ );
        auto const y = uint32_t( (ph.pos().y()+ymax_)*ny_ / 2.0 / ymax_ );
        auto const z = uint32_t( (ph.pos().z()+zmax_)*nz_ / 2.0 / zmax_ );

        taurun += dcell * rhokappa_[ x+y*nx_+z*ny_*nx_ ];
        ph.Move(dcell);
        d += dcell;
    }

    return taurun;
}

int Grid::movePhotonAtDepth( Photon & ph, double tau, double tauold, double delta ) const
{
    double taurun=tauold, d=0.0;

    if (delta < 0.0 )
    {
        delta=0.0001*(2.*xmax_/nx_);
    }

    double const smax = maxDistance(ph);

    // integrate through grid
    while (taurun < tau && d < (0.9999*smax))
    {
        double const dcell = cellDistance(ph, delta);
        auto const x = uint32_t( (ph.pos().x()+xmax_)*nx_ / 2.0 / xmax_ );
        auto const y = uint32_t( (ph.pos().y()+ymax_)*ny_ / 2.0 / ymax_ );
        auto const z = uint32_t( (ph.pos().z()+zmax_)*nz_ / 2.0 / zmax_ );
        double const taucell = dcell*rhokappa_[ x+y*nx_+z*ny_*nx_ ];

        if(taurun + taucell >= tau)
        {
            double const d1 = (tau-taurun) / rhokappa_[ x+y*nx_+z*ny_*nx_ ];
            d += d1;
            ph.Move(d1);
        } else {
            d += dcell;
            ph.Move(dcell);
        }

        taurun += taucell;
    }

    // calculate photon final position.  if it escapes envelope then
    // set tflag=1.  if photon doesn't escape leave tflag=0 and update
    // photon position.
    return d >= 0.999 * smax;
}

int Grid::movePhotonAtRandomDepth( Photon &ph, double delta ) const
{
    double const tau = -std::log(ran.Get());
    return movePhotonAtDepth(ph, tau, 0.0, delta);
}

void Grid::peeloff(Photon ph, Observer& observer, DustCRef dust) const
{
    double const hgfac = ph.Scatt(dust, Direction3d{observer.pos()});
    double const tau = findOpticalDepth(ph);

    if (tau == 0.0)
    {
        return;
    }

    ph.weight() *= hgfac * exp(-tau);
    // Bin the photon into the image according to its position and direction of travel.
    observer.Bin(ph);
}
<commit_msg>Simplify Grid::maxDistance method<commit_after>#include <algorithm>
#include <cmath>
#include <iostream>

#include "grid.hpp"
#include "observers.hpp"
#include "model.hpp"
#include "photons.hpp"

namespace
{
    inline double ds(double const pos, double const velocity, double const max)
    {
        if(velocity > 0.0)
        {
            return (max - pos) / velocity;
        } else if(velocity < 0.0) {
            return (pos + max) / velocity;
        }
        return 2.0 * max;
    }
}

double FlaredDisk::density(double x, double y, double z) const
{
    double const r2 = x*x + y*y;
    double const r  = std::sqrt(r2);

    // Disk Geometry
    if(( r >= rInner_ ) && ( r <= rOuter_ ))
    {
        double const h = h0_ * std::pow(r/r0_, beta_);
        return rho0_ * std::pow(r0_ / r, alpha_) * std::exp(-0.5*z*z / (h*h)); // rho in g/cm^3
    } else {
        return 0.0;
    }
}

Grid::Grid(
        double const xmax,
        double const ymax,
        double const zmax,
        double const kappa,
        uint32_t const nx,
        uint32_t const ny,
        uint32_t const nz,
        FlaredDiskCPtr disk)
    : nx_{ nx }
    , ny_{ ny }
    , nz_{ nz }
    , xmax_{ xmax }
    , ymax_{ ymax }
    , zmax_{ zmax }
    , disk_{ std::move(disk) }
{
    rhokappa_ = new double[nx_ * ny_ * nz_];
    minrho_ = 1e+38;

    for (size_t cntx=0; cntx!=nx_; ++cntx)
    {
        double const x = (cntx*2.0+1) * xmax_/nx_ - xmax_;
        for (size_t cnty=0; cnty!=ny_; ++cnty)
        {
            double const y=(cnty*2.0+1) * ymax_/ny_ - ymax_;
            for (size_t cntz=0; cntz!=nz_; ++cntz)
            {
                double const z=(cntz*2.0+1) * zmax_/nz_ - zmax_;
                size_t const idx = cntx+cnty*nx+cntz*ny*nx;
                rhokappa_[idx] = disk_->density(x, y, z) * kappa * 1.5e13; // rho*kappa*R,
                if (minrho_ > rhokappa_[idx] && rhokappa_[idx] > 0)
                    minrho_ = rhokappa_[idx];
            }
        }
    }
}

// calculate smax -- maximum distance photon can travel *******
double Grid::maxDistance(Photon const& ph) const
{
    double const dsx = ds(ph.pos().x(), ph.dir().x(), xmax_);
    double const dsy = ds(ph.pos().y(), ph.dir().y(), xmax_);
    double const dsz = ds(ph.pos().z(), ph.dir().z(), xmax_);

    return std::max(dsx, std::max(dsy, dsz));
}

// find distance to next x, y, and z cell walls.
// note that dx is not the x-distance, but the actual distance along
// the direction of travel to the next x-face, and likewise for dy and dz.
double Grid::cellDistance(Photon& ph, double delta) const
{
    double dx=200.0*xmax_, dy=200.0*ymax_, dz=200.0*zmax_, dcell=0.0;
    if (delta < 0.0) delta=0.0001*(2.*xmax_/nx_);
    double tmp = 2.0*xmax_/nx_;
    if(ph.dir().x() > 0.0)
    {
        dx = (( int( (ph.pos().x()+xmax_) / tmp ) + 1.0 )* tmp - xmax_ - ph.pos().x() )/ph.dir().x();
        if (dx < delta)
        {
            dx = tmp/ph.dir().x();
            ph.x() = (int( (ph.pos().x()+xmax_) / tmp ) + 1.0 )*tmp - xmax_ + delta;
        }
    } else if (ph.dir().x() < 0.0) {
        dx = (( int( (ph.pos().x()+xmax_)/ tmp ) )* tmp - xmax_ - ph.pos().x() )/ph.dir().x();
        if (dx < delta)
        {
            dx =-tmp/ph.dir().x();
            ph.x() = ( int( (ph.pos().x()+xmax_)/tmp) )* tmp - xmax_ - delta;
        }
    }

    tmp = 2.0*ymax_/ny_;
    if(ph.dir().y() > 0.0)
    {
        dy = (( int( (ph.pos().y()+ymax_)/tmp ) + 1.0 )* tmp - ymax_ - ph.pos().y() )/ph.dir().y();
        if (dy < delta)
        {
            dy = tmp/ph.dir().y();
            ph.y() = (int( (ph.pos().y()+ymax_)/tmp) + 1.0 )* tmp - ymax_+ delta;
        }
    } else if (ph.dir().y() < 0.0) {
        dy = (( int( (ph.pos().y()+ymax_)/tmp ) )*tmp - ymax_ - ph.pos().y() )/ph.dir().y();
        if (dy < delta)
        {
            dy =-tmp/ph.dir().y();
            ph.y() = ( int( (ph.pos().y()+xmax_)/tmp ) )* tmp - ymax_ - delta;
        }
    }

    tmp=2.0*zmax_/nz_;
    if(ph.dir().z() > 0.0)
    {
        dz = (( int( (ph.pos().z()+zmax_)/tmp ) + 1.0 )* tmp - zmax_ - ph.pos().z() )/ph.dir().z();
        if (dz < delta)
        {
            dz = tmp/ph.dir().z();
            ph.z() = (int( (ph.pos().z()+zmax_)/tmp ) + 1.0 )* tmp - zmax_ + delta;
        }
    } else if (ph.dir().z() < 0.0) {
        dz = (( int( (ph.pos().z()+zmax_)/tmp ))* tmp- zmax_ - ph.pos().z() )/ph.dir().z();
        if (dz < delta)
        {
            dz =-tmp/ph.dir().z();
            ph.z() = ( int( (ph.pos().z()+zmax_)/tmp ) )* tmp - zmax_ - delta;
        }
    }

    dcell = ( dx   < dy ) ? dx    : dy;
    dcell = (dcell < dz ) ? dcell : dz;
//	printf("d %g %g %g \n", dx, dy, dz);
    return dcell;
}

double Grid::findOpticalDepth( Photon ph, double delta ) const
{
    double taurun=0.0, d=0.0;

    if (delta < 0.0) delta=0.0001*(2.*xmax_/nx_);
    double const smax = maxDistance(ph);

    if(smax < delta)
    {
        return 0.0;
    }

    while (d < 0.999*smax)
    {
        double const dcell = cellDistance(ph, delta);
        auto const x = uint32_t( (ph.pos().x()+xmax_)*nx_ / 2.0 / xmax_ );
        auto const y = uint32_t( (ph.pos().y()+ymax_)*ny_ / 2.0 / ymax_ );
        auto const z = uint32_t( (ph.pos().z()+zmax_)*nz_ / 2.0 / zmax_ );

        taurun += dcell * rhokappa_[ x+y*nx_+z*ny_*nx_ ];
        ph.Move(dcell);
        d += dcell;
    }

    return taurun;
}

int Grid::movePhotonAtDepth( Photon & ph, double tau, double tauold, double delta ) const
{
    double taurun=tauold, d=0.0;

    if (delta < 0.0 )
    {
        delta=0.0001*(2.*xmax_/nx_);
    }

    double const smax = maxDistance(ph);

    // integrate through grid
    while (taurun < tau && d < (0.9999*smax))
    {
        double const dcell = cellDistance(ph, delta);
        auto const x = uint32_t( (ph.pos().x()+xmax_)*nx_ / 2.0 / xmax_ );
        auto const y = uint32_t( (ph.pos().y()+ymax_)*ny_ / 2.0 / ymax_ );
        auto const z = uint32_t( (ph.pos().z()+zmax_)*nz_ / 2.0 / zmax_ );
        double const taucell = dcell*rhokappa_[ x+y*nx_+z*ny_*nx_ ];

        if(taurun + taucell >= tau)
        {
            double const d1 = (tau-taurun) / rhokappa_[ x+y*nx_+z*ny_*nx_ ];
            d += d1;
            ph.Move(d1);
        } else {
            d += dcell;
            ph.Move(dcell);
        }

        taurun += taucell;
    }

    // calculate photon final position.  if it escapes envelope then
    // set tflag=1.  if photon doesn't escape leave tflag=0 and update
    // photon position.
    return d >= 0.999 * smax;
}

int Grid::movePhotonAtRandomDepth( Photon &ph, double delta ) const
{
    double const tau = -std::log(ran.Get());
    return movePhotonAtDepth(ph, tau, 0.0, delta);
}

void Grid::peeloff(Photon ph, Observer& observer, DustCRef dust) const
{
    double const hgfac = ph.Scatt(dust, Direction3d{observer.pos()});
    double const tau = findOpticalDepth(ph);

    if (tau == 0.0)
    {
        return;
    }

    ph.weight() *= hgfac * exp(-tau);
    // Bin the photon into the image according to its position and direction of travel.
    observer.Bin(ph);
}
<|endoftext|>


<commit_before>//udp_sync_echo_server.cpp
#include <iostream>
using namespace std;

#ifdef WIN32
#define _WIN32_WINNT 0x0501
#include <stdio.h>
#endif

#include <boost/bind.hpp>
#include <boost/asio.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>
using namespace boost::asio;
using namespace boost::posix_time;
io_service service;
void handle_connections() {
	char buff[1024];
	ip::udp::socket sock(service, ip::udp::endpoint(ip::udp::v4(), 8001));
	while (true) {
		ip::udp::endpoint sender_ep;
		int bytes = sock.receive_from(buffer(buff), sender_ep);
		std::string msg(buff, bytes);
		sock.send_to(buffer(msg), sender_ep);
	}
}
int main(int argc, char* argv[]) {
	std::cout << "udp_sync_echo_server.cpp port 8001" << endl;
	handle_connections();
}

//#define BOOST_ASIO_SEPARATE_COMPILATION
/*

#include <boost/thread.hpp>
#include <boost/bind.hpp>
#include <boost/asio.hpp>
#include <iostream>

using namespace std;
using namespace boost::asio;
//io_service service;
*/

/*//
void func(int i)
{
	std::cout << "func called, i= " << i << std::endl;
}
void worker_thread()
{
	service.run();
}

int main(int argc, char* argv[])
{
	for (int i = 0; i < 10; ++i)
		service.post(boost::bind(func, i));

	boost::thread_group threads;
	for (int i = 0; i < 3; ++i)
		threads.create_thread(worker_thread);
	// wait for all threads to be created
	boost::this_thread::sleep(boost::posix_time::millisec(500));
	threads.join_all();
	system("pause");
}
*/

/*//
void func(int i)
{
	std::cout << "func called, i= " << i << "/" << boost::this_thread::get_id() << std::endl;
}
void worker_thread()
{
	service.run();
}
int main(int argc, char* argv[])
{
	io_service::strand strand_one(service), strand_two(service);
	for (int i = 0; i < 5; ++i)
		service.post(strand_one.wrap(boost::bind(func, i)));

	for (int i = 5; i < 10; ++i)
		service.post(strand_two.wrap(boost::bind(func, i)));

	boost::thread_group threads;
	for (int i = 0; i < 3; ++i)
		threads.create_thread(worker_thread);	// wait for all threads to be created

	boost::this_thread::sleep(boost::posix_time::millisec(500));
	threads.join_all();

	system("pause");
	return 1;
}*/

/*//  service.dispatch    :
void func(int i)
{
	std::cout << "func called, i= " << i << std::endl;
}

void run_dispatch_and_post()
{
	for (int i = 0; i < 10; i += 2)
	{
		service.dispatch(boost::bind(func, i));
		service.post(boost::bind(func, i + 1));
	}
}
int main(int argc, char* argv[])
{
	service.post(run_dispatch_and_post);
	service.run();
	system("pause");
	return 0;
}*/

/*//    service.wrap(handler).wrap()  ,
//     :
void dispatched_func_1()
{
	std::cout << "dispatched 1" << std::endl;
}
void dispatched_func_2()
{
	std::cout << "dispatched 2" << std::endl;
}
void test(boost::function<void()> func)
{
	std::cout << "test" << std::endl;
	service.dispatch(dispatched_func_1);
	func();
}
void service_run()
{
	service.run();
}
int main(int argc, char* argv[])
{
	test(service.wrap(dispatched_func_2));
	boost::thread th(service_run);
	boost::this_thread::sleep(boost::posix_time::millisec(500));
	th.join();
	system("pause");
	return 0;
}*/

//      :
/*using boost::asio;
typedef boost::shared_ptr<ip::tcp::socket> socket_ptr;
io_service service;
ip::tcp::endpoint ep(ip::tcp::v4(), 2001)); // listen on 2001
ip::tcp::acceptor acc(service, ep);
socket_ptr sock(new ip::tcp::socket(service));
start_accept(sock);
service.run();
void start_accept(socket_ptr sock)
{
	acc.async_accept(*sock, boost::bind(handle_accept, sock, _1));
}
void handle_accept(socket_ptr sock, const boost::system::error_code & err)
{
	if (err) return;
	// at this point, you can read/write to the socket
	socket_ptr sock(new ip::tcp::socket(service));
	start_accept(sock);
}*/

//-------------------------------------

 /*,           100 :

bool read = false;
void deadline_handler(const boost::system::error_code &)
{
    std::cout << (read ? "read successfully" : "read failed") << std::endl;
}
void read_handler(const boost::system::error_code &)
{
    read = true;
}
ip::tcp::socket sock(service);

read = false;
char data[512];
sock.async_read_some(buffer(data, 512));
deadline_timer t(service, boost::posix_time::milliseconds(100));
t.async_wait(&deadline_handler);
service.run();
*/

/*
.run()   ,
  ,  service.run()  ,      .
  .      connect_handler,     .
       ,   :
typedef boost::shared_ptr<io_service::work> work_ptr;
work_ptr dummy_work(new io_service::work(service_));

      service_.run()
useservice_.stop()  dummy_work.reset(0); // destroy dummy_work.
*/<commit_msg>Add system login (TCP)<commit_after>#ifdef WIN32
#define _WIN32_WINNT 0x0501
#include <stdio.h>
#endif

#include <boost/thread.hpp>
#include <boost/bind.hpp>
#include <boost/asio.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>
using namespace boost::asio;
using namespace boost::posix_time;
io_service service;

struct talk_to_client;
typedef boost::shared_ptr<talk_to_client> client_ptr;
typedef std::vector<client_ptr> array;
array clients;
// thread-safe access to clients array
boost::recursive_mutex cs;

void update_clients_changed();

/** simple connection to server:
- logs in just with username (no password)
- all connections are initiated by the client: client asks, server answers
- server disconnects any client that hasn't pinged for 5 seconds

Possible requests:
- gets a list of all connected clients
- ping: the server answers either with "ping ok" or "ping client_list_changed"
*/
struct talk_to_client : boost::enable_shared_from_this<talk_to_client> {
	talk_to_client()
		: sock_(service), started_(false), already_read_(0) {
		last_ping = microsec_clock::local_time();
	}
	std::string username() const { return username_; }

	void answer_to_client() {
		try {
			read_request();
			process_request();
		}
		catch (boost::system::system_error&) {
			stop();
		}
		if (timed_out()) {
			stop();
			std::cout << "stopping " << username_ << " - no ping in time" << std::endl;
		}
	}
	void set_clients_changed() { clients_changed_ = true; }
	ip::tcp::socket & sock() { return sock_; }
	bool timed_out() const {
		ptime now = microsec_clock::local_time();
		long long ms = (now - last_ping).total_milliseconds();
		return ms > 5000;
	}
	void stop() {
		// close client connection
		boost::system::error_code err;
		sock_.close(err);
	}
private:
	void read_request() {
		if (sock_.available())
			already_read_ += sock_.read_some(
			buffer(buff_ + already_read_, max_msg - already_read_));
	}
	void process_request() {
		bool found_enter = std::find(buff_, buff_ + already_read_, '\n')
			< buff_ + already_read_;
		if (!found_enter)
			return; // message is not full
		// process the msg
		last_ping = microsec_clock::local_time();
		size_t pos = std::find(buff_, buff_ + already_read_, '\n') - buff_;
		std::string msg(buff_, pos);
		std::copy(buff_ + already_read_, buff_ + max_msg, buff_);
		already_read_ -= pos + 1;

		if (msg.find("login ") == 0) on_login(msg);
		else if (msg.find("ping") == 0) on_ping();
		else if (msg.find("ask_clients") == 0) on_clients();
		else std::cerr << "invalid msg " << msg << std::endl;
	}

	void on_login(const std::string & msg) {
		std::istringstream in(msg);
		in >> username_ >> username_;
		std::cout << username_ << " logged in" << std::endl;
		write("login ok\n");
		update_clients_changed();
	}
	void on_ping() {
		write(clients_changed_ ? "ping client_list_changed\n" : "ping ok\n");
		clients_changed_ = false;
	}
	void on_clients() {
		std::string msg;
		{ boost::recursive_mutex::scoped_lock lk(cs);
		for (array::const_iterator b = clients.begin(), e = clients.end(); b != e; ++b)
			msg += (*b)->username() + " ";
		}
		write("clients " + msg + "\n");
	}

	void write(const std::string & msg) {
		sock_.write_some(buffer(msg));
	}
private:
	ip::tcp::socket sock_;
	enum { max_msg = 1024 };
	int already_read_;
	char buff_[max_msg];
	bool started_;
	std::string username_;
	bool clients_changed_;
	ptime last_ping;
};

void update_clients_changed() {
	boost::recursive_mutex::scoped_lock lk(cs);
	for (array::iterator b = clients.begin(), e = clients.end(); b != e; ++b)
		(*b)->set_clients_changed();
}

void accept_thread() {
	ip::tcp::acceptor acceptor(service, ip::tcp::endpoint(ip::tcp::v4(), 8001));
	while (true) {
		client_ptr new_(new talk_to_client);
		acceptor.accept(new_->sock());

		boost::recursive_mutex::scoped_lock lk(cs);
		clients.push_back(new_);
	}
}

void handle_clients_thread() {
	while (true) {
		boost::this_thread::sleep(millisec(1));
		boost::recursive_mutex::scoped_lock lk(cs);
		for (array::iterator b = clients.begin(), e = clients.end(); b != e; ++b)
			(*b)->answer_to_client();
		// erase clients that timed out
		clients.erase(std::remove_if(clients.begin(), clients.end(),
			boost::bind(&talk_to_client::timed_out, _1)), clients.end());
	}
}

int main(int argc, char* argv[]) {
	boost::thread_group threads;
	threads.create_thread(accept_thread);
	threads.create_thread(handle_clients_thread);
	threads.join_all();
}

<|endoftext|>


<commit_before>#include <ctrcommon/input.hpp>
#include <ctrcommon/platform.hpp>
#include <ctrcommon/ui.hpp>

#include <stdio.h>

#include <sstream>
#include <iomanip>

#include <sys/dirent.h>
#include <3ds.h>
#include <ctrcommon/app.hpp>

typedef enum {
    INSTALL_CIA,
    DELETE_CIA,
    DELETE_TITLE,
    LAUNCH_TITLE
} Mode;

int main(int argc, char **argv) {
    if(!platformInit()) {
        return 0;
    }

    bool ninjhax = platformIsNinjhax();

    std::vector<std::string> extensions;
    extensions.push_back("cia");

    MediaType destination = SD;
    Mode mode = INSTALL_CIA;
    bool exit = false;
    bool netInstall = false;
    u64 freeSpace = fsGetFreeSpace(destination);
    auto onLoop = [&]() {
        if(ninjhax && inputIsPressed(BUTTON_START)) {
            exit = true;
            return true;
        }

        bool breakLoop = false;

        if(inputIsPressed(BUTTON_L)) {
            if(destination == SD) {
                destination = NAND;
            } else {
                destination = SD;
            }

            freeSpace = fsGetFreeSpace(destination);
            if(mode == DELETE_TITLE || mode == LAUNCH_TITLE) {
                breakLoop = true;
            }
        }

        if(inputIsPressed(BUTTON_R)) {
            if(mode == INSTALL_CIA) {
                mode = DELETE_CIA;
            } else if(mode == DELETE_CIA) {
                mode = DELETE_TITLE;
                breakLoop = true;
            } else if(mode == DELETE_TITLE) {
                mode = LAUNCH_TITLE;
            } else if(mode == LAUNCH_TITLE) {
                mode = INSTALL_CIA;
                breakLoop = true;
            }
        }

        if(mode == INSTALL_CIA && inputIsPressed(BUTTON_Y)) {
            netInstall = true;
            breakLoop = true;
        }

        std::stringstream stream;
        stream << "Free Space: " << freeSpace << " bytes (" << std::fixed << std::setprecision(2) << freeSpace / 1024.0f / 1024.0f << "MB)" << "\n";
        stream << "Destination: " << (destination == NAND ? "NAND" : "SD") << ", Mode: " << (mode == INSTALL_CIA ? "Install CIA" : mode == DELETE_CIA ? "Delete CIA" : mode == DELETE_TITLE ? "Delete Title" : "Launch Title") << "\n";
        stream << "L - Switch Destination, R - Switch Mode" << "\n";
        if(mode == INSTALL_CIA) {
            stream << "X - Install all CIAs in the current directory" << "\n";
            stream << "Y - Receive an app over the network" << "\n";
        } else if(mode == DELETE_CIA) {
            stream << "X - Delete all CIAs in the current directory" << "\n";
        }

        if(ninjhax) {
            stream << "START - Exit to launcher" << "\n";
        }

        std::string str = stream.str();
        screenDrawString(str, (screenGetWidth() - screenGetStrWidth(str)) / 2, screenGetHeight() - 4 - screenGetStrHeight(str), 255, 255, 255);

        return breakLoop;
    };

    auto onProgress = [&](u64 pos, u64 totalSize) {
        std::stringstream details;
        details << "(" << std::fixed << std::setprecision(2) << ((double) pos / 1024.0 / 1024.0) << "MB / " << std::fixed << std::setprecision(2) << ((double) totalSize / 1024.0 / 1024.0) << "MB)" << "\n";
        details << "Press B to cancel.";

        u32 progress = (u32) (((double) pos / (double) totalSize) * 100);
        uiDisplayProgress(TOP_SCREEN, "Installing", details.str(), true, progress);
        inputPoll();
        return !inputIsPressed(BUTTON_B);
    };

    while(platformIsRunning()) {
        std::string fileTarget;
        App appTarget;
        if(mode == INSTALL_CIA || mode == DELETE_CIA) {
            uiSelectFile(&fileTarget, "/", extensions, [&](const std::string currDirectory, bool inRoot, bool &updateList) {
                if(inputIsPressed(BUTTON_X)) {
                    std::stringstream confirmMsg;
                    if(mode == INSTALL_CIA) {
                        confirmMsg << "Install ";
                    } else {
                        confirmMsg << "Delete ";
                    }

                    confirmMsg << "all CIAs in the current directory?";
                    if(uiPrompt(TOP_SCREEN, confirmMsg.str(), true)) {
                        bool failed = false;
                        std::vector<FileInfo> contents = fsGetDirectoryContents(currDirectory);
                        for(std::vector<FileInfo>::iterator it = contents.begin(); it != contents.end(); it++) {
                            std::string path = (*it).path;
                            std::string fileName = (*it).name;
                            if(!fsIsDirectory(path) && fsHasExtensions(path, extensions)) {
                                if(mode == INSTALL_CIA) {
                                    AppResult ret = appInstallFile(destination, path, onProgress);
                                    if(ret != APP_SUCCESS) {
                                        std::stringstream resultMsg;
                                        resultMsg << "Install failed!" << "\n";
                                        resultMsg << fileName << "\n";
                                        resultMsg << appGetResultString(ret) << "\n";
                                        uiPrompt(TOP_SCREEN, resultMsg.str(), false);
                                        failed = true;
                                        break;
                                    }
                                } else {
                                    if(!fsDelete(path)) {
                                        std::stringstream resultMsg;
                                        resultMsg << "Delete failed!" << "\n";
                                        resultMsg << fileName << "\n";
                                        resultMsg << platformGetErrorString(platformGetError()) << "\n";
                                        uiPrompt(TOP_SCREEN, resultMsg.str(), false);
                                        failed = true;
                                        break;
                                    } else {
                                        updateList = true;
                                    }
                                }
                            }
                        }

                        if(!failed) {
                            uiPrompt(TOP_SCREEN, "Install succeeded!\n", false);
                        }

                        freeSpace = fsGetFreeSpace(destination);
                    }
                }

                return onLoop();
            }, [&](const std::string path, bool &updateList) {
                std::stringstream confirmMsg;
                if(mode == INSTALL_CIA) {
                    confirmMsg << "Install ";
                } else {
                    confirmMsg << "Delete ";
                }

                confirmMsg << "the selected CIA?";
                if(uiPrompt(TOP_SCREEN, confirmMsg.str(), true)) {
                    std::stringstream resultMsg;
                    if(mode == INSTALL_CIA) {
                        resultMsg << "Install ";
                    } else {
                        resultMsg << "Delete ";
                    }

                    if(mode == INSTALL_CIA) {
                        AppResult ret = appInstallFile(destination, path, onProgress);
                        if(ret == APP_SUCCESS) {
                            resultMsg << "succeeded!";
                        } else {
                            resultMsg << "failed!" << "\n";
                            resultMsg << appGetResultString(ret) << "\n";
                        }
                    } else {
                        if(fsDelete(path)) {
                            updateList = true;
                            resultMsg << "succeeded!";
                        } else {
                            resultMsg << "failed!" << "\n";
                            resultMsg << platformGetErrorString(platformGetError()) << "\n";
                        }
                    }

                    uiPrompt(TOP_SCREEN, resultMsg.str(), false);

                    freeSpace = fsGetFreeSpace(destination);
                }

                return false;
            });
        } else if(mode == DELETE_TITLE || mode == LAUNCH_TITLE) {
            uiSelectApp(&appTarget, destination, [&](bool &updateList) {
                return onLoop();
            }, [&](App app, bool &updateList) {
                if(mode == DELETE_TITLE) {
                    if(uiPrompt(TOP_SCREEN, "Delete the selected title?", true)) {
                        updateList = true;
                        uiDisplayMessage(TOP_SCREEN, "Deleting title...");
                        AppResult ret = appDelete(app);

                        std::stringstream resultMsg;
                        resultMsg << "Delete ";
                        if(ret == APP_SUCCESS) {
                            resultMsg << "succeeded!";
                        } else {
                            resultMsg << "failed!" << "\n";
                            resultMsg << appGetResultString(ret) << "\n";
                        }

                        uiPrompt(TOP_SCREEN, resultMsg.str(), false);

                        freeSpace = fsGetFreeSpace(destination);
                    }
                } else if(mode == LAUNCH_TITLE) {
                    if(uiPrompt(TOP_SCREEN, "Launch the selected title?", true)) {
                        updateList = true;
                        uiDisplayMessage(TOP_SCREEN, "Launching title...");
                        AppResult ret = appLaunch(app);

                        if(ret != APP_SUCCESS) {
                            std::stringstream resultMsg;
                            resultMsg << "Launch failed!" << "\n";
                            resultMsg << appGetResultString(ret) << "\n";
                            uiPrompt(TOP_SCREEN, resultMsg.str(), false);
                        } else {
                            while(true) {
                            }
                        }
                    }
                }

                return false;
            });
        }

        if(netInstall && !exit) {
            netInstall = false;

            screenClearBuffers(BOTTOM_SCREEN, 0, 0, 0);

            RemoteFile file = uiAcceptRemoteFile(TOP_SCREEN);
            if(file.fd == NULL) {
                continue;
            }

            std::stringstream confirmStream;
            confirmStream << "Install the received application?" << "\n";
            confirmStream << "Size: " << file.fileSize << " bytes (" << std::fixed << std::setprecision(2) << file.fileSize / 1024.0f / 1024.0f << "MB)" << "\n";
            if(uiPrompt(TOP_SCREEN, confirmStream.str(), true)) {
                AppResult ret = appInstall(destination, file.fd, file.fileSize, onProgress);
                std::stringstream resultMsg;
                resultMsg << "Install ";
                if(ret == APP_SUCCESS) {
                    resultMsg << "succeeded!";
                } else {
                    resultMsg << "failed!" << "\n";
                    resultMsg << appGetResultString(ret) << "\n";
                }

                uiPrompt(TOP_SCREEN, resultMsg.str(), false);
            }

            fclose(file.fd);
            continue;
        }

        if(exit) {
            break;
        }
    }

    platformCleanup();
    return 0;
}
<commit_msg>Display message while loading title list.<commit_after>#include <ctrcommon/app.hpp>
#include <ctrcommon/input.hpp>
#include <ctrcommon/platform.hpp>
#include <ctrcommon/ui.hpp>

#include <stdio.h>

#include <sstream>
#include <iomanip>

#include <sys/dirent.h>

typedef enum {
    INSTALL_CIA,
    DELETE_CIA,
    DELETE_TITLE,
    LAUNCH_TITLE
} Mode;

int main(int argc, char **argv) {
    if(!platformInit()) {
        return 0;
    }

    bool ninjhax = platformIsNinjhax();

    std::vector<std::string> extensions;
    extensions.push_back("cia");

    MediaType destination = SD;
    Mode mode = INSTALL_CIA;
    bool exit = false;
    bool netInstall = false;
    u64 freeSpace = fsGetFreeSpace(destination);
    auto onLoop = [&]() {
        if(ninjhax && inputIsPressed(BUTTON_START)) {
            exit = true;
            return true;
        }

        bool breakLoop = false;

        if(inputIsPressed(BUTTON_L)) {
            if(destination == SD) {
                destination = NAND;
            } else {
                destination = SD;
            }

            freeSpace = fsGetFreeSpace(destination);
            if(mode == DELETE_TITLE || mode == LAUNCH_TITLE) {
                breakLoop = true;
            }
        }

        if(inputIsPressed(BUTTON_R)) {
            if(mode == INSTALL_CIA) {
                mode = DELETE_CIA;
            } else if(mode == DELETE_CIA) {
                mode = DELETE_TITLE;
                breakLoop = true;
            } else if(mode == DELETE_TITLE) {
                mode = LAUNCH_TITLE;
            } else if(mode == LAUNCH_TITLE) {
                mode = INSTALL_CIA;
                breakLoop = true;
            }
        }

        if(mode == INSTALL_CIA && inputIsPressed(BUTTON_Y)) {
            netInstall = true;
            breakLoop = true;
        }

        std::stringstream stream;
        stream << "Free Space: " << freeSpace << " bytes (" << std::fixed << std::setprecision(2) << freeSpace / 1024.0f / 1024.0f << "MB)" << "\n";
        stream << "Destination: " << (destination == NAND ? "NAND" : "SD") << ", Mode: " << (mode == INSTALL_CIA ? "Install CIA" : mode == DELETE_CIA ? "Delete CIA" : mode == DELETE_TITLE ? "Delete Title" : "Launch Title") << "\n";
        stream << "L - Switch Destination, R - Switch Mode" << "\n";
        if(mode == INSTALL_CIA) {
            stream << "X - Install all CIAs in the current directory" << "\n";
            stream << "Y - Receive an app over the network" << "\n";
        } else if(mode == DELETE_CIA) {
            stream << "X - Delete all CIAs in the current directory" << "\n";
        }

        if(ninjhax) {
            stream << "START - Exit to launcher" << "\n";
        }

        std::string str = stream.str();
        screenDrawString(str, (screenGetWidth() - screenGetStrWidth(str)) / 2, screenGetHeight() - 4 - screenGetStrHeight(str), 255, 255, 255);

        return breakLoop;
    };

    auto onProgress = [&](u64 pos, u64 totalSize) {
        std::stringstream details;
        details << "(" << std::fixed << std::setprecision(2) << ((double) pos / 1024.0 / 1024.0) << "MB / " << std::fixed << std::setprecision(2) << ((double) totalSize / 1024.0 / 1024.0) << "MB)" << "\n";
        details << "Press B to cancel.";

        u32 progress = (u32) (((double) pos / (double) totalSize) * 100);
        uiDisplayProgress(TOP_SCREEN, "Installing", details.str(), true, progress);
        inputPoll();
        return !inputIsPressed(BUTTON_B);
    };

    while(platformIsRunning()) {
        std::string fileTarget;
        App appTarget;
        if(mode == INSTALL_CIA || mode == DELETE_CIA) {
            uiSelectFile(&fileTarget, "/", extensions, [&](const std::string currDirectory, bool inRoot, bool &updateList) {
                if(inputIsPressed(BUTTON_X)) {
                    std::stringstream confirmMsg;
                    if(mode == INSTALL_CIA) {
                        confirmMsg << "Install ";
                    } else {
                        confirmMsg << "Delete ";
                    }

                    confirmMsg << "all CIAs in the current directory?";
                    if(uiPrompt(TOP_SCREEN, confirmMsg.str(), true)) {
                        bool failed = false;
                        std::vector<FileInfo> contents = fsGetDirectoryContents(currDirectory);
                        for(std::vector<FileInfo>::iterator it = contents.begin(); it != contents.end(); it++) {
                            std::string path = (*it).path;
                            std::string fileName = (*it).name;
                            if(!fsIsDirectory(path) && fsHasExtensions(path, extensions)) {
                                if(mode == INSTALL_CIA) {
                                    AppResult ret = appInstallFile(destination, path, onProgress);
                                    if(ret != APP_SUCCESS) {
                                        std::stringstream resultMsg;
                                        resultMsg << "Install failed!" << "\n";
                                        resultMsg << fileName << "\n";
                                        resultMsg << appGetResultString(ret) << "\n";
                                        uiPrompt(TOP_SCREEN, resultMsg.str(), false);
                                        failed = true;
                                        break;
                                    }
                                } else {
                                    if(!fsDelete(path)) {
                                        std::stringstream resultMsg;
                                        resultMsg << "Delete failed!" << "\n";
                                        resultMsg << fileName << "\n";
                                        resultMsg << platformGetErrorString(platformGetError()) << "\n";
                                        uiPrompt(TOP_SCREEN, resultMsg.str(), false);
                                        failed = true;
                                        break;
                                    } else {
                                        updateList = true;
                                    }
                                }
                            }
                        }

                        if(!failed) {
                            uiPrompt(TOP_SCREEN, "Install succeeded!\n", false);
                        }

                        freeSpace = fsGetFreeSpace(destination);
                    }
                }

                return onLoop();
            }, [&](const std::string path, bool &updateList) {
                std::stringstream confirmMsg;
                if(mode == INSTALL_CIA) {
                    confirmMsg << "Install ";
                } else {
                    confirmMsg << "Delete ";
                }

                confirmMsg << "the selected CIA?";
                if(uiPrompt(TOP_SCREEN, confirmMsg.str(), true)) {
                    std::stringstream resultMsg;
                    if(mode == INSTALL_CIA) {
                        resultMsg << "Install ";
                    } else {
                        resultMsg << "Delete ";
                    }

                    if(mode == INSTALL_CIA) {
                        AppResult ret = appInstallFile(destination, path, onProgress);
                        if(ret == APP_SUCCESS) {
                            resultMsg << "succeeded!";
                        } else {
                            resultMsg << "failed!" << "\n";
                            resultMsg << appGetResultString(ret) << "\n";
                        }
                    } else {
                        if(fsDelete(path)) {
                            updateList = true;
                            resultMsg << "succeeded!";
                        } else {
                            resultMsg << "failed!" << "\n";
                            resultMsg << platformGetErrorString(platformGetError()) << "\n";
                        }
                    }

                    uiPrompt(TOP_SCREEN, resultMsg.str(), false);

                    freeSpace = fsGetFreeSpace(destination);
                }

                return false;
            });
        } else if(mode == DELETE_TITLE || mode == LAUNCH_TITLE) {
            uiDisplayMessage(BOTTOM_SCREEN, "Loading title list...");
            uiSelectApp(&appTarget, destination, [&](bool &updateList) {
                return onLoop();
            }, [&](App app, bool &updateList) {
                if(mode == DELETE_TITLE) {
                    if(uiPrompt(TOP_SCREEN, "Delete the selected title?", true)) {
                        updateList = true;
                        uiDisplayMessage(TOP_SCREEN, "Deleting title...");
                        AppResult ret = appDelete(app);

                        std::stringstream resultMsg;
                        resultMsg << "Delete ";
                        if(ret == APP_SUCCESS) {
                            resultMsg << "succeeded!";
                        } else {
                            resultMsg << "failed!" << "\n";
                            resultMsg << appGetResultString(ret) << "\n";
                        }

                        uiPrompt(TOP_SCREEN, resultMsg.str(), false);

                        freeSpace = fsGetFreeSpace(destination);
                    }
                } else if(mode == LAUNCH_TITLE) {
                    if(uiPrompt(TOP_SCREEN, "Launch the selected title?", true)) {
                        updateList = true;
                        uiDisplayMessage(TOP_SCREEN, "Launching title...");
                        AppResult ret = appLaunch(app);

                        if(ret != APP_SUCCESS) {
                            std::stringstream resultMsg;
                            resultMsg << "Launch failed!" << "\n";
                            resultMsg << appGetResultString(ret) << "\n";
                            uiPrompt(TOP_SCREEN, resultMsg.str(), false);
                        } else {
                            while(true) {
                            }
                        }
                    }
                }

                return false;
            });
        }

        if(netInstall && !exit) {
            netInstall = false;

            screenClearBuffers(BOTTOM_SCREEN, 0, 0, 0);

            RemoteFile file = uiAcceptRemoteFile(TOP_SCREEN);
            if(file.fd == NULL) {
                continue;
            }

            std::stringstream confirmStream;
            confirmStream << "Install the received application?" << "\n";
            confirmStream << "Size: " << file.fileSize << " bytes (" << std::fixed << std::setprecision(2) << file.fileSize / 1024.0f / 1024.0f << "MB)" << "\n";
            if(uiPrompt(TOP_SCREEN, confirmStream.str(), true)) {
                AppResult ret = appInstall(destination, file.fd, file.fileSize, onProgress);
                std::stringstream resultMsg;
                resultMsg << "Install ";
                if(ret == APP_SUCCESS) {
                    resultMsg << "succeeded!";
                } else {
                    resultMsg << "failed!" << "\n";
                    resultMsg << appGetResultString(ret) << "\n";
                }

                uiPrompt(TOP_SCREEN, resultMsg.str(), false);
            }

            fclose(file.fd);
            continue;
        }

        if(exit) {
            break;
        }
    }

    platformCleanup();
    return 0;
}
<|endoftext|>


<commit_before>#include <cmath>
#include <iostream>

using namespace std;

static bool is_prime(int i) {
	if (i == 1) return false;		// 1 isn't prime
	if (i == 2) return true;		// 2 is though
	if (i % 2 == 0) return false;	// Even numbers aren't prime

	int div = 3;					// No need to test even dividers either
	while (div <= sqrt(i)) {
		if (i%div == 0) {
			return false;
		}
		div = div + 2;
	}
	return true;
}

int main() {
	int n;
	cin >> n;
	while (n--) {
		int i;
		cin >> i;
		if (is_prime(i))
		{
			cout << "Prime" << endl;
		}
		else {
			cout << "Not prime" << endl;
		}
	}
	return 0;
}
<commit_msg>Update ctci-big-o.cpp<commit_after>#include <cmath>
#include <iostream>

using namespace std;

static bool is_prime(int i) {
	if (i == 1) return false;		// 1 isn't prime
	if (i == 2) return true;		// 2 is though
	if (i % 2 == 0) return false;		// Even numbers aren't prime

	int div = 3;				// No need to test even dividers either
	while (div <= sqrt(i)) {
		if (i%div == 0) {
			return false;
		}
		div = div + 2;
	}
	return true;
}

int main() {
	int n;
	cin >> n;
	while (n--) {
		int i;
		cin >> i;
		if (is_prime(i))
		{
			cout << "Prime" << endl;
		}
		else {
			cout << "Not prime" << endl;
		}
	}
	return 0;
}
<|endoftext|>


<commit_before>#pragma once

#include <string>
#include <vector>
#include <tuple>
#include <sstream>
#include <type_traits>
#include <functional>
#include <memory>
#include <unordered_map>

namespace argparse {

namespace detail {
    template <typename In, typename Out, bool pass = std::is_convertible<In, Out>::value>
    struct lexical_cast_t;

    template <typename In, typename Out>
    struct lexical_cast_t<In, Out, true> {
        static Out apply(In const& val) {
            return static_cast<Out>(val);
        }
    };

    template <typename In>
    struct lexical_cast_t<In, std::string, false> {
        static std::string apply(In const& val) {
            std::ostringstream osstr;
            osstr << val;
            return osstr.str();
        }
    };

    template <typename Out>
    struct lexical_cast_t<std::string, Out, false> {
        static Out apply(std::string const& val) {
            std::istringstream isstr(val);
            Out out;
            isstr >> out;
            return out;
        }
    };

    template <typename Out, std::size_t N>
    struct lexical_cast_t<char[N], Out, false> {
        static Out apply(char const (&val)[N]) {
            std::istringstream isstr(val);
            Out out;
            isstr >> out;
            return out;
        }
    };

    template <typename Out, std::size_t N>
    struct lexical_cast_t<char const[N], Out, false> {
        static Out apply(char const (&val)[N]) {
            std::istringstream isstr(val);
            Out out;
            isstr >> out;
            return out;
        }
    };
} // namespace detail;

template <typename Out, typename In>
inline Out lexical_cast(In const& val) {
    return detail::lexical_cast_t<In, Out>::apply(val);
}

//

struct argument_base {
   virtual void assign(std::string const& src) = 0;
   virtual void store_true() = 0;
   virtual bool with_value() const = 0;

   argument_base(std::string const& name, char short_name,
                 std::string const& help)
     : name_{name}, short_name_{short_name}, help_{help}
  {
  }

   std::string const& name() const { return name_; }
   char short_name() const { return short_name_; }

private:
   std::string name_;
   char short_name_;
   std::string help_;
};

template <typename T>
struct argument_with_value : public argument_base {
   using arg_type = T;

   argument_with_value(std::string const& name, char short_name,
                       std::string const& help)
      : argument_base{name, short_name, help}
   {
   }

   void assign(std::string const& src) override {
      val_.reset(new T(lexical_cast<T>(src)));
   }

   void store_true() override { /* do nothing. */ }
   bool with_value() const override { return true; }

private:
   std::unique_ptr<T> val_;
};

struct argument_flag : public argument_base {
   using arg_type = bool;

   argument_flag(std::string const& name, char short_name,
            std::string const& help)
      : argument_base{ name, short_name, help }
   {
   }

   void assign(std::string const&) override { /* do nothing. */ }
   void store_true() override { val_ = true; }
   bool with_value() const override { return false; }

private:
   bool val_ = false;
};

template <typename T>
inline argument_with_value<T> arg(std::string const& name, char short_name = '\0',
                                  std::string const& help = "")
{
   return argument_with_value<T>{ name, short_name, help };
}

template <typename T>
inline argument_with_value<T> arg(std::string const& name, std::string const& help)
{
   return argument_with_value<T>{ name, '\0', help };
}

inline argument_flag flag(std::string const& name, char short_name = '\0',
                          std::string const& help = "")
{
   return argument_flag{ name, short_name, help };
}

inline argument_flag flag(std::string const& name, std::string const& help)
{
   return argument_flag{ name, '\0', help };
}

template <typename... Args>
struct parser
{
   using args_type = std::tuple<typename Args::arg_type...>;

   parser(Args&&... args)
      : args_{ std::forward<Args>(args)... }
   {
      // make lookup tables.
   }

   void parse(std::vector<std::string> const& args) {
      if (args.empty())
         throw std::runtime_error("argument must be at least one item(s).");

      progname_ = args[0];

      for (auto it = args.begin(); it != args.end(); ++it)
      {
         auto& arg = *it;
         if (arg.substr(0,2)=="--") { // long option
            std::string::size_type pos = arg.find('=',2);
            if (pos==std::string::npos) {
               std::string key = arg.substr(2);
               if (lookup_.count(key) == 0)
                  throw std::runtime_error("unknown option: --" + key);
               argument_base& a = lookup_.at(key).get();
               if (a.with_value()) {
                  // read next argument
                  ++it;
                  std::string val = *it;
                  a.assign(val);
               }
               else {
                  a.store_true();
               }
            }
            else {
               std::string key = arg.substr(2, pos);
               std::string val = arg.substr(pos+1);
               argument_base& a = lookup_.at(key).get();
               if (a.with_value()) {
                  a.assign(val);
               }
               else {
                  a.store_true();
               }
            }
         }
         else if (arg[0] == '-') { // short option
            if (arg.length() < 2) continue;
            char s = arg[1];
            if (short_lookup_.count(s) == 0)
               throw std::runtime_error(std::string("unknown short option: -") + s);
            argument_base& a = short_lookup_.at(s).get();
            if (a.with_value()) {
               ++it;
               std::string val = *it;
               a.assign(val);
            } else {
               a.store_true();
            }
         }
         else { // normal argument
            remains_.push_back(arg);
         }
      }
   }

   std::string const& progname() const { return progname_; }
   args_type const& options() const { return options_; }
   std::vector<std::string> const& remains() const { return remains_; }

private:
   std::tuple<Args...> args_;
   std::unordered_map<std::string, std::reference_wrapper<argument_base>> lookup_;
   std::unordered_map<char,        std::reference_wrapper<argument_base>> short_lookup_;

   std::string progname_;
   args_type options_;
   std::vector<std::string> remains_;
};

template <typename... Args>
parser<Args...> make_parser(Args&&... args) {
   return parser<Args...>{ std::forward<Args>(args)... };
}

} // namespace argparse;
<commit_msg>implement: construction of lookup table<commit_after>#pragma once

#include <string>
#include <vector>
#include <tuple>
#include <sstream>
#include <type_traits>
#include <functional>
#include <memory>
#include <unordered_map>

namespace argparse {

namespace detail {
    template <typename In, typename Out, bool pass = std::is_convertible<In, Out>::value>
    struct lexical_cast_t;

    template <typename In, typename Out>
    struct lexical_cast_t<In, Out, true> {
        static Out apply(In const& val) {
            return static_cast<Out>(val);
        }
    };

    template <typename In>
    struct lexical_cast_t<In, std::string, false> {
        static std::string apply(In const& val) {
            std::ostringstream osstr;
            osstr << val;
            return osstr.str();
        }
    };

    template <typename Out>
    struct lexical_cast_t<std::string, Out, false> {
        static Out apply(std::string const& val) {
            std::istringstream isstr(val);
            Out out;
            isstr >> out;
            return out;
        }
    };

    template <typename Out, std::size_t N>
    struct lexical_cast_t<char[N], Out, false> {
        static Out apply(char const (&val)[N]) {
            std::istringstream isstr(val);
            Out out;
            isstr >> out;
            return out;
        }
    };

    template <typename Out, std::size_t N>
    struct lexical_cast_t<char const[N], Out, false> {
        static Out apply(char const (&val)[N]) {
            std::istringstream isstr(val);
            Out out;
            isstr >> out;
            return out;
        }
    };
} // namespace detail;

template <typename Out, typename In>
inline Out lexical_cast(In const& val) {
    return detail::lexical_cast_t<In, Out>::apply(val);
}

//

struct argument_base {
   virtual void assign(std::string const& src) = 0;
   virtual void store_true() = 0;
   virtual bool with_value() const = 0;

   argument_base(std::string const& name, char short_name,
                 std::string const& help)
     : name_{name}, short_name_{short_name}, help_{help}
  {
  }

   std::string const& name() const { return name_; }
   char short_name() const { return short_name_; }

private:
   std::string name_;
   char short_name_;
   std::string help_;
};

template <typename T>
struct argument_with_value : public argument_base {
   using arg_type = T;

   argument_with_value(std::string const& name, char short_name,
                       std::string const& help)
      : argument_base{name, short_name, help}
   {
   }

   void assign(std::string const& src) override {
      val_.reset(new T(lexical_cast<T>(src)));
   }

   void store_true() override { /* do nothing. */ }
   bool with_value() const override { return true; }

private:
   std::unique_ptr<T> val_;
};

struct argument_flag : public argument_base {
   using arg_type = bool;

   argument_flag(std::string const& name, char short_name,
            std::string const& help)
      : argument_base{ name, short_name, help }
   {
   }

   void assign(std::string const&) override { /* do nothing. */ }
   void store_true() override { val_ = true; }
   bool with_value() const override { return false; }

private:
   bool val_ = false;
};

template <typename T>
inline argument_with_value<T> arg(std::string const& name, char short_name = '\0',
                                  std::string const& help = "")
{
   return argument_with_value<T>{ name, short_name, help };
}

template <typename T>
inline argument_with_value<T> arg(std::string const& name, std::string const& help)
{
   return argument_with_value<T>{ name, '\0', help };
}

inline argument_flag flag(std::string const& name, char short_name = '\0',
                          std::string const& help = "")
{
   return argument_flag{ name, short_name, help };
}

inline argument_flag flag(std::string const& name, std::string const& help)
{
   return argument_flag{ name, '\0', help };
}

template <std::size_t... Idx>
struct index_sequence {
   using next = index_sequence<Idx..., sizeof...(Idx)>;
};

template <std::size_t Nt, std::size_t N>
struct iota {
   using type = typename iota<Nt-1, N-1>::type::next;
};

template <std::size_t Nt>
struct iota<Nt, 0> {
   using type = index_sequence<>;
};

template <std::size_t N>
using make_index_sequence = typename iota<N, N>::type;

template <typename... T> inline void dummy(T...) {}

template <typename... Args>
struct parser
{
   using args_type = std::tuple<typename Args::arg_type...>;

   parser(Args&&... args)
      : args_{ std::forward<Args>(args)... }
   {
      make_lookup_tables(args_, make_index_sequence<sizeof...(Args)>());
   }

   template <typename Tuple, std::size_t... Idx>
   void make_lookup_tables(Tuple& args, index_sequence<Idx...>) {
      dummy( append_to_lookup_table(std::get<Idx>(args))... );
   }

   template <typename Arg>
   int append_to_lookup_table(Arg& arg) {
      std::string const& name = arg.name();
      lookup_.insert({ name, static_cast<argument_base&>(arg) });

      char s = arg.short_name();
      if (s != '\0')
         short_lookup_.insert({ s, static_cast<argument_base&>(arg) });

      return 0;
   }

   void parse(std::vector<std::string> const& args) {
      if (args.empty())
         throw std::runtime_error("argument must be at least one item(s).");

      progname_ = args[0];

      for (auto it = args.begin(); it != args.end(); ++it)
      {
         auto& arg = *it;
         if (arg.substr(0,2)=="--") { // long option
            std::string::size_type pos = arg.find('=',2);
            if (pos==std::string::npos) {
               std::string key = arg.substr(2);
               if (lookup_.count(key) == 0)
                  throw std::runtime_error("unknown option: --" + key);
               argument_base& a = lookup_.at(key).get();
               if (a.with_value()) {
                  // read next argument
                  ++it;
                  std::string val = *it;
                  a.assign(val);
               }
               else {
                  a.store_true();
               }
            }
            else {
               std::string key = arg.substr(2, pos);
               std::string val = arg.substr(pos+1);
               argument_base& a = lookup_.at(key).get();
               if (a.with_value()) {
                  a.assign(val);
               }
               else {
                  a.store_true();
               }
            }
         }
         else if (arg[0] == '-') { // short option
            if (arg.length() < 2) continue;
            char s = arg[1];
            if (short_lookup_.count(s) == 0)
               throw std::runtime_error(std::string("unknown short option: -") + s);
            argument_base& a = short_lookup_.at(s).get();
            if (a.with_value()) {
               ++it;
               std::string val = *it;
               a.assign(val);
            } else {
               a.store_true();
            }
         }
         else { // normal argument
            remains_.push_back(arg);
         }
      }
   }

   std::string const& progname() const { return progname_; }
   args_type const& options() const { return options_; }
   std::vector<std::string> const& remains() const { return remains_; }

private:
   std::tuple<Args...> args_;
   std::unordered_map<std::string, std::reference_wrapper<argument_base>> lookup_;
   std::unordered_map<char,        std::reference_wrapper<argument_base>> short_lookup_;

   std::string progname_;
   args_type options_;
   std::vector<std::string> remains_;
};

template <typename... Args>
parser<Args...> make_parser(Args&&... args) {
   return parser<Args...>{ std::forward<Args>(args)... };
}

} // namespace argparse;
<|endoftext|>