<commit_before>#include <fstream>
#include <iostream>
#include <math.h>
#include <stdio.h>
#include <string>
#include <time.h>
#include <unistd.h>
#include <stdlib.h>

using namespace std;

double pi = 3.141592653589793238463;
double todeg = 180.0 / pi;
double torad = pi / 180.0;
double hstep = 1.0 / 24;
double mstep = 1.0 / 1440;
double sstep = 1.0 / 86400;

double riseduration = sstep * 5400;

struct julian {
  double jrise;
  double jset;
};

// display fraction of a day in hours and minutes, but return a string
string j2h(double jd) {
  int hr, mn;
  char buffer[10];
  hr = (int)(jd * 24);
  mn = (int)(((jd * 24) - (double(hr))) * 60);
  snprintf(buffer, sizeof(buffer), "%02d:%02d", hr, mn);
  return buffer;
}

void setlights(double dayhour, double dawn, double rise, double set,
               double dusk) {
  bool lights;
  bool riseordawn;
  double riseduration_red = riseduration;
  double riseduration_green = riseduration * 0.8;
  double riseduration_blue = riseduration * 0.6;
  double rperc = 1 / riseduration_red;
  double gperc = 1 / riseduration_green;
  double bperc = 1 / riseduration_blue;
  double red = 0, green = 0, blue = 0;
  char buffer[128];

  // first check if the main lights should be turned on or off
  if ((dayhour < rise) || (dayhour > set)) {
    lights = 0;
  } else {
    lights = 1;
  }

  // now check if we are in sunrise
  if ((dayhour >= dawn) && (dayhour <= (rise + mstep))) {
    riseordawn = 1;
    red = (dayhour - dawn) * rperc;
    if (dayhour >= (dawn + (riseduration_red - riseduration_green))) {
      green =
          (dayhour - (dawn + (riseduration_red - riseduration_green))) * gperc;
    }
    if (dayhour >= (dawn + (riseduration_red - riseduration_blue))) {
      blue =
          (dayhour - (dawn + (riseduration_red - riseduration_blue))) * bperc;
    }
  } else if ((dayhour >= (set - mstep)) && (dayhour <= dusk)) {
    // or are we in sunset
    red = 1 - ((dayhour - (dusk - riseduration_red)) * rperc);
    green = 1 - ((dayhour - (dusk - riseduration_red)) * gperc);
    blue = 1 - ((dayhour - (dusk - riseduration_red)) * bperc);
    riseordawn = 1;
  } else {
    // or no twilight
    riseordawn = 0;
    red = green = blue = 0;
  }

  // failsafe if calculations took a wrong direction somewhere
  if (red > 1) {
    red = 1;
  }
  if (green > 1) {
    green = 1;
  }
  if (blue > 1) {
    blue = 1;
  }
  if (red < 0) {
    red = 0;
  }
  if (green < 0) {
    green = 0;
  }
  if (blue < 0) {
    blue = 0;
  }

  /* // debugging
  cout << "dayhour " << dayhour << ", lights " << lights << ", riseordawn "
       << riseordawn << ", red " << red << ", green " << green << ", blue "
       << blue << endl;
       */

  // write the calculated values to the system
  // the pins are hardcoded - that's not very
  // nice, but it works...
  system("/usr/bin/gpio mode 8 out");
  system("/usr/bin/gpio mode 9 out");
  snprintf(buffer, sizeof(buffer), "/usr/bin/gpio write 8 %d",(int)(lights));
  system(buffer);
  snprintf(buffer, sizeof(buffer), "/usr/bin/gpio write 9 %d",(int)(riseordawn));
  system(buffer);
  if ((red > 0) && (red < 1)) {
    ofstream filehandler;
    string filename = "/dev/pi-blaster";
    filehandler.open(filename.c_str());
    if (filehandler.is_open()) {
      filehandler << "14=" << red << endl;
      filehandler << "15=" << green << endl;
      filehandler << "18=" << blue << endl;
      filehandler.close();
    }
  }
}

struct julian calcjtimes(time_t t) {

  struct tm *current_time = gmtime(&t);
  // longitude west of magdeburg
  double low = -11.6322;
  // latitude of magdeburg
  double lam = 52.1243;
  // latitude of madagascar (if it were on northern hemishpere)
  // double lam=22.5;

  // calculate julian day number based on
  // https://de.wikipedia.org/wiki/Julianisches_Datum
  int m = current_time->tm_mon + 1;
  int y = current_time->tm_year + 1900;
  if (m <= 2) {
    m += 12;
    y--;
  }
  int d = current_time->tm_mday;
  int a = floor((y) / 100);
  double b = 2 - a + floor(a / 4);
  double jd =
      floor(365.25 * (y + 4716)) + floor(30.6001 * (m + 1)) + d + b - 1524.5;

  // calculation of sunrise based on
  // https://en.wikipedia.org/wiki/Sunrise_equation
  // current julian day
  double n = jd - 2451545 + 0.0008;
  // mean solar noon
  double js = low / 360 + n;
  // mean anomaly
  double ma = fmod((357.5291 + 0.98560028 * js), 360);
  // equation of the center
  double c = 1.9148 * sin(ma * torad) + 0.02 * sin(2 * ma * torad) +
             0.0003 * sin(3 * ma * torad);
  // ecliptic longitude
  double l = fmod((ma + c + 180 + 102.9372), 360);
  // solar transit - it seems they have forgotten the 2451545.5 on the wikipedia
  // page. or i did not understand correctly.
  double jt =
      2451545.5 + js + 0.0053 * sin(ma * torad) - 0.0069 * sin(2 * l * torad);
  // declination of the sun
  double de = asin(sin(l * torad) * sin(23.44 * torad)) * todeg;
  // hour angle
  double w = acos((sin(-0.83 * torad) - sin(lam * torad) * sin(de * torad)) /
                  (cos(lam * torad) * cos(de * torad))) *
             todeg;

  double jset = jt + w / 360;
  double jrise = jt - w / 360;

  struct julian cjt = {jrise, jset};

  return cjt;
}

int main() {
  cout << "starting up..." << endl;
  time_t now = time(0);
  struct tm *nowt;
  int nowd = localtime(&now)->tm_yday;
  int curd = nowd + 1;
  struct julian jt;

  double sunrise;
  double sunset;
  double lightson;
  double lightsoff;
  double dawn;
  double dusk;

  // better float precision for debugging purposes
  std::cout.setf(std::ios_base::fixed, std::ios_base::floatfield);
  std::cout.precision(10);

  // here is the main loop, that just loops over and over again
  while (true) {
    now = time(0);
    nowt = localtime(&now);
    nowd = nowt->tm_yday;
    if (nowd != curd) {
      cout << "a new day" << endl;
      // the day changed, so this is a new day
      curd = nowd;
      jt = calcjtimes(now);

      // now we have the correct times. first skip the acutal
      // date because i only need the times. as julian day .5 is
      // 00:00 gmt we have to subtract .5 so we get the correct
      // values for hour, minute and second.
      // they will be shifted so
      // the day of the terrarium matches the day of the owners and
      // also i want to have a nice dawn and dusk.
      // the dawn and dusk will spread evenly before and after
      // the actal sunrise

      sunrise = (jt.jrise - .5 - floor(jt.jrise - .5)) + mstep * 60;
      sunset = (jt.jset - .5 - floor(jt.jset - .5)) + mstep * 60;
      lightson = sunrise + riseduration / 2;
      lightsoff = sunset - riseduration / 2;
      dawn = sunrise - riseduration / 2;
      dusk = sunset + riseduration / 2;
      cout << "name        julian time | utc" << endl;
      cout << "sunrise:    " << sunrise << "|" << j2h(sunrise) << endl;
      cout << "sunset:     " << sunset << "|" << j2h(sunset) << endl;
      cout << "lights on:  " << lightson << "|" << j2h(lightson) << endl;
      cout << "lights off: " << lightsoff << "|" << j2h(lightsoff) << endl;
      cout << "dawn start: " << dawn << "|" << j2h(dawn) << endl;
      cout << "dusk stop:  " << dusk << "|" << j2h(dusk) << endl;
    }
    // sleep for a second
    usleep(1000000);
    // set the lights
    setlights(nowt->tm_hour * hstep + nowt->tm_min * mstep +
                  nowt->tm_sec * sstep,
              dawn, sunrise, sunset, dusk);
  }
  // this will never be reached, but anyway
  return 0;
}
<commit_msg>formatting and write status to file<commit_after>#include <fstream>
#include <iostream>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <time.h>
#include <unistd.h>

using namespace std;

double pi = 3.141592653589793238463;
double todeg = 180.0 / pi;
double torad = pi / 180.0;
double hstep = 1.0 / 24;
double mstep = 1.0 / 1440;
double sstep = 1.0 / 86400;

double riseduration = sstep * 5400;

struct julian {
  double jrise;
  double jset;
};

// display fraction of a day in hours and minutes, but return a string
string j2h(double jd) {
  int hr, mn;
  char buffer[10];
  hr = (int)(jd * 24);
  mn = (int)(((jd * 24) - (double(hr))) * 60);
  snprintf(buffer, sizeof(buffer), "%02d:%02d", hr, mn);
  return buffer;
}

void setlights(double dayhour, double dawn, double rise, double set, double dusk) {
  bool lights;
  bool riseordawn;
  double riseduration_red = riseduration;
  double riseduration_green = riseduration * 0.8;
  double riseduration_blue = riseduration * 0.6;
  double rperc = 1 / riseduration_red;
  double gperc = 1 / riseduration_green;
  double bperc = 1 / riseduration_blue;
  double red = 0, green = 0, blue = 0;
  char buffer[128];

  // first check if the main lights should be turned on or off
  if ((dayhour < rise) || (dayhour > set)) {
    lights = 0;
  } else {
    lights = 1;
  }

  // now check if we are in sunrise
  if ((dayhour >= dawn) && (dayhour <= (rise + mstep))) {
    riseordawn = 1;
    red = (dayhour - dawn) * rperc;
    if (dayhour >= (dawn + (riseduration_red - riseduration_green))) {
      green = (dayhour - (dawn + (riseduration_red - riseduration_green))) * gperc;
    }
    if (dayhour >= (dawn + (riseduration_red - riseduration_blue))) {
      blue = (dayhour - (dawn + (riseduration_red - riseduration_blue))) * bperc;
    }
  } else if ((dayhour >= (set - mstep)) && (dayhour <= dusk)) {
    // or are we in sunset
    red = 1 - ((dayhour - (dusk - riseduration_red)) * rperc);
    green = 1 - ((dayhour - (dusk - riseduration_red)) * gperc);
    blue = 1 - ((dayhour - (dusk - riseduration_red)) * bperc);
    riseordawn = 1;
  } else {
    // or no twilight
    riseordawn = 0;
    red = green = blue = 0;
  }

  // failsafe if calculations took a wrong direction somewhere
  if (red > 1) {
    red = 1;
  }
  if (green > 1) {
    green = 1;
  }
  if (blue > 1) {
    blue = 1;
  }
  if (red < 0) {
    red = 0;
  }
  if (green < 0) {
    green = 0;
  }
  if (blue < 0) {
    blue = 0;
  }

  /* // debugging
  cout << "dayhour " << dayhour << ", lights " << lights << ", riseordawn "
       << riseordawn << ", red " << red << ", green " << green << ", blue "
       << blue << endl;
       */

  // write the calculated values to the system
  // the pins are hardcoded - that's not very
  // nice, but it works...
  system("/usr/bin/gpio mode 8 out");
  system("/usr/bin/gpio mode 9 out");
  snprintf(buffer, sizeof(buffer), "/usr/bin/gpio write 8 %d", (int)(lights));
  system(buffer);
  snprintf(buffer, sizeof(buffer), "/usr/bin/gpio write 9 %d", (int)(riseordawn));
  system(buffer);
  if ((red > 0) && (red < 1)) {
    ofstream filehandler;
    string filename = "/dev/pi-blaster";
    filehandler.open(filename.c_str());
    if (filehandler.is_open()) {
      filehandler << "14=" << red << endl;
      filehandler << "15=" << green << endl;
      filehandler << "18=" << blue << endl;
      filehandler.close();
    }
  }
}

struct julian calcjtimes(time_t t) {

  struct tm *current_time = gmtime(&t);
  // longitude west of magdeburg
  double low = -11.6322;
  // latitude of magdeburg
  double lam = 52.1243;
  // latitude of madagascar (if it were on northern hemishpere)
  // double lam=22.5;

  // calculate julian day number based on
  // https://de.wikipedia.org/wiki/Julianisches_Datum
  int m = current_time->tm_mon + 1;
  int y = current_time->tm_year + 1900;
  if (m <= 2) {
    m += 12;
    y--;
  }
  int d = current_time->tm_mday;
  int a = floor((y) / 100);
  double b = 2 - a + floor(a / 4);
  double jd = floor(365.25 * (y + 4716)) + floor(30.6001 * (m + 1)) + d + b - 1524.5;

  // calculation of sunrise based on
  // https://en.wikipedia.org/wiki/Sunrise_equation
  // current julian day
  double n = jd - 2451545 + 0.0008;
  // mean solar noon
  double js = low / 360 + n;
  // mean anomaly
  double ma = fmod((357.5291 + 0.98560028 * js), 360);
  // equation of the center
  double c = 1.9148 * sin(ma * torad) + 0.02 * sin(2 * ma * torad) + 0.0003 * sin(3 * ma * torad);
  // ecliptic longitude
  double l = fmod((ma + c + 180 + 102.9372), 360);
  // solar transit - it seems they have forgotten the 2451545.5 on the wikipedia
  // page. or i did not understand correctly.
  double jt = 2451545.5 + js + 0.0053 * sin(ma * torad) - 0.0069 * sin(2 * l * torad);
  // declination of the sun
  double de = asin(sin(l * torad) * sin(23.44 * torad)) * todeg;
  // hour angle
  double w =
      acos((sin(-0.83 * torad) - sin(lam * torad) * sin(de * torad)) / (cos(lam * torad) * cos(de * torad))) * todeg;

  double jset = jt + w / 360;
  double jrise = jt - w / 360;

  struct julian cjt = {jrise, jset};

  return cjt;
}

int main() {
  cout << "starting up..." << endl;
  time_t now = time(0);
  struct tm *nowt;
  int nowd = localtime(&now)->tm_yday;
  int curd = nowd + 1;
  struct julian jt;

  double sunrise;
  double sunset;
  double lightson;
  double lightsoff;
  double dawn;
  double dusk;

  // better float precision for debugging purposes
  std::cout.setf(std::ios_base::fixed, std::ios_base::floatfield);
  std::cout.precision(10);

  // here is the main loop, that just loops over and over again
  while (true) {
    now = time(0);
    nowt = localtime(&now);
    nowd = nowt->tm_yday;
    if (nowd != curd) {
      cout << "a new day" << endl;
      // the day changed, so this is a new day
      curd = nowd;
      jt = calcjtimes(now);

      // now we have the correct times. first skip the acutal
      // date because i only need the times. as julian day .5 is
      // 00:00 gmt we have to subtract .5 so we get the correct
      // values for hour, minute and second.
      // they will be shifted so
      // the day of the terrarium matches the day of the owners and
      // also i want to have a nice dawn and dusk.
      // the dawn and dusk will spread evenly before and after
      // the actal sunrise

      sunrise = (jt.jrise - .5 - floor(jt.jrise - .5)) + mstep * 60;
      sunset = (jt.jset - .5 - floor(jt.jset - .5)) + mstep * 60;
      lightson = sunrise + riseduration / 2;
      lightsoff = sunset - riseduration / 2;
      dawn = sunrise - riseduration / 2;
      dusk = sunset + riseduration / 2;

      // write everything to the log
      cout << "name        julian time | utc" << endl;
      cout << "sunrise:    " << sunrise << "|" << j2h(sunrise) << endl;
      cout << "sunset:     " << sunset << "|" << j2h(sunset) << endl;
      cout << "lights on:  " << lightson << "|" << j2h(lightson) << endl;
      cout << "lights off: " << lightsoff << "|" << j2h(lightsoff) << endl;
      cout << "dawn start: " << dawn << "|" << j2h(dawn) << endl;
      cout << "dusk stop:  " << dusk << "|" << j2h(dusk) << endl;

      // write everything zo a file
      ofstream filehandler;
      string filename = "/dev/shm/terrarium_times";
      filehandler.open(filename.c_str());
      if (filehandler.is_open()) {
        filehandler << "sunrise " << sunrise << " " << j2h(sunrise) << endl;
        filehandler << "sunset " << sunrise << " " << j2h(sunset) << endl;
        filehandler << "start dawn " << sunrise << " " << j2h(dawn) << endl;
        filehandler << "start daylight " << sunrise << " " << j2h(lightson) << endl;
        filehandler << "stop daylight " << sunrise << " " << j2h(lightsoff) << endl;
        filehandler << "stop dusk " << sunrise << " " << j2h(dusk) << endl;
        filehandler.close();
      }
    }
    // sleep for a second
    usleep(1000000);
    // set the lights
    setlights(nowt->tm_hour * hstep + nowt->tm_min * mstep + nowt->tm_sec * sstep, dawn, sunrise, sunset, dusk);
  }
  // this will never be reached, but anyway
  return 0;
}
<|endoftext|>


<commit_before>// CTS.cpp : Testing class
//

#include <iostream>
#include <fstream>

#include "../headers/io.h"

using namespace std;

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

	try {
		ofstream out("WKTOut");
		ifstream in("WKTIn");
		string instr;
		string outstr;
		WKTReader *r = new WKTReader(GeometryFactory(PrecisionModel(),10));
		WKTWriter *w=new WKTWriter();
		Geometry *g;

		cout << "Start Testing:" << endl;
		while(!in.eof()) {
			&getline(in,instr);
			if (instr!="") {
				g=r->read(instr);
				outstr=w->write(g);
				out << "----------" << endl;
				out << instr << endl;
				out << outstr << endl;
				out << "----------" << endl << endl;
			}
		}
		out.flush();
		out.close();
		cout << "End of Testing" << endl;

	} catch (char *message){
        cout << message << endl;
	} catch (ParseException pe) {
		cout << pe.toString() << endl;
	}

	return 0;
}

<commit_msg>Fixed small bug in call to GeometryFactory (instantiate PrecisionModel with new)<commit_after>// CTS.cpp : Testing class
//

#include <iostream>
#include <fstream>

#include "../headers/io.h"

using namespace std;

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

	try {
		ofstream out("WKTOut");
		ifstream in("WKTIn");
		string instr;
		string outstr;
		WKTReader *r = new WKTReader(GeometryFactory(new PrecisionModel(),10));
		WKTWriter *w=new WKTWriter();
		Geometry *g;

		cout << "Start Testing:" << endl;
		while(!in.eof()) {
			&getline(in,instr);
			if (instr!="") {
				g=r->read(instr);
				outstr=w->write(g);
				out << "----------" << endl;
				out << instr << endl;
				out << outstr << endl;
				out << "----------" << endl << endl;
			}
		}
		out.flush();
		out.close();
		cout << "End of Testing" << endl;

	} catch (char *message){
        cout << message << endl;
	} catch (ParseException pe) {
		cout << pe.toString() << endl;
	}

	return 0;
}

<|endoftext|>


<commit_before>/***************************************************************
 *
 * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
 * University of Wisconsin-Madison, WI.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you
 * may not use this file except in compliance with the License.  You may
 * obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 ***************************************************************/

#include "condor_common.h"
#include "condor_config.h"
#include "condor_debug.h"
#include "sysapi.h"
#include "sysapi_externs.h"
#include "my_popen.h"

static char *_sysapi_vsyscall_gate_addr = NULL;

#define BUFFER_SIZE 2048

/* The memory returned from here must be freed */
static char* find_ckpt_probe(void);

static char* find_ckpt_probe(void)
{
	char *tmp = NULL;
	char *tmp2 = NULL;

	tmp = param("CKPT_PROBE");

	if (tmp != NULL) {
		return tmp;
	}

	tmp = param("LIBEXEC");

	if (tmp != NULL) {
		tmp2 = (char *) malloc(strlen(tmp) + strlen("/condor_ckpt_probe") + 1);
		if (tmp2 == NULL) {
			EXCEPT("Out of memory!");
		}

		/* build up the path to the probe process */
		strcpy(tmp2, tmp);
		strcat(tmp2, "/condor_ckpt_probe");
		free(tmp);

		/* now check to see if it exists */
		if (access(tmp2, X_OK) < 0) {
			/* Nope, it isn't there */
			free(tmp2);
			return NULL;
		}

		/* Ok it is executable, give it back to the caller */
		return tmp2;
	}

	tmp = param("RELEASE_DIR");

	if (tmp != NULL) {
		tmp2 = (char*) malloc(strlen(tmp) + strlen("/libexec/condor_ckpt_probe") + 1);
		if (tmp2 == NULL) {
			EXCEPT("Out of memory!");
		}

		/* build up the path to the probe process */
		strcpy(tmp2, tmp);
		strcat(tmp2, "/libexec/condor_ckpt_probe");
		free(tmp);

		/* now check to see if it exists */
		if (access(tmp2, X_OK) < 0) {
			/* Nope, it isn't there */
			free(tmp2);
			return NULL;
		}

		/* Ok it is executable, give it back to the caller */
		return tmp2;
	}

	return NULL;
}

/* the raw version */
/* Do not free the returned pointer */
const char *
sysapi_vsyscall_gate_addr_raw(void)
{
	char *tmp;
	char *cmd[3];
	FILE *fin;
	char buf[BUFFER_SIZE];
	char addr[BUFFER_SIZE];

	/* immediately set this up if it isn't already */
	if (_sysapi_vsyscall_gate_addr == NULL) {
		/* Set this up immediately for the rest of the algorithm */
		_sysapi_vsyscall_gate_addr = strdup("N/A");
	}

#if defined(LINUX)
	if (strcmp(_sysapi_vsyscall_gate_addr, "N/A") == MATCH) {

		/* get the probe process executable */
		tmp = find_ckpt_probe();
		if (tmp == NULL) {
			/* Can't find it at all, so bail */
			return _sysapi_vsyscall_gate_addr;
		}

		/* exec probe */
		cmd[0] = tmp;
		cmd[1] = "--vdso-addr";
		cmd[2] = NULL;
		fin = my_popenv(cmd, "r", TRUE);
		free(tmp);
		if (fin == NULL) {
			dprintf(D_ALWAYS, "my_popenv failed\n");
			return _sysapi_vsyscall_gate_addr;
		}
		if (fgets(buf, BUFFER_SIZE, fin) == NULL) {
			my_pclose(fin);
			dprintf(D_ALWAYS, "fgets failed\n");
			return _sysapi_vsyscall_gate_addr;
		}
		my_pclose(fin);

		if (sscanf(buf, "VDSO: %s\n", addr) != 1) {
			dprintf(D_ALWAYS, "sscanf didn't parse correctly\n");
			return _sysapi_vsyscall_gate_addr;
		}

	/* set up global with correct vdso address */
		if(_sysapi_vsyscall_gate_addr == NULL) {
			EXCEPT("Programmer error! _sysapi_vsyscall_gate_addr == NULL");
		}
		free(_sysapi_vsyscall_gate_addr);
		_sysapi_vsyscall_gate_addr = strdup(addr);
	}
#endif

	return _sysapi_vsyscall_gate_addr;
}

/* the cooked version */
/* Do not free the returned pointer */
const char *
sysapi_vsyscall_gate_addr(void)
{
	sysapi_internal_reconfig();

	return sysapi_vsyscall_gate_addr_raw();
}

<commit_msg>Removed param() of LIBEXEC and RELEASE_DIR from find_ckpt_probe(). CKPT_PROBE has been around since 7.0 and will be used exclusively.<commit_after>/***************************************************************
 *
 * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
 * University of Wisconsin-Madison, WI.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you
 * may not use this file except in compliance with the License.  You may
 * obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 ***************************************************************/

#include "condor_common.h"
#include "condor_config.h"
#include "condor_debug.h"
#include "sysapi.h"
#include "sysapi_externs.h"
#include "my_popen.h"

static char *_sysapi_vsyscall_gate_addr = NULL;

#define BUFFER_SIZE 2048

/* The memory returned from here must be freed */
static char* find_ckpt_probe(void);

static char* find_ckpt_probe(void)
{
	return param("CKPT_PROBE");
}

/* the raw version */
/* Do not free the returned pointer */
const char *
sysapi_vsyscall_gate_addr_raw(void)
{
	char *tmp;
	char *cmd[3];
	FILE *fin;
	char buf[BUFFER_SIZE];
	char addr[BUFFER_SIZE];

	/* immediately set this up if it isn't already */
	if (_sysapi_vsyscall_gate_addr == NULL) {
		/* Set this up immediately for the rest of the algorithm */
		_sysapi_vsyscall_gate_addr = strdup("N/A");
	}

#if defined(LINUX)
	if (strcmp(_sysapi_vsyscall_gate_addr, "N/A") == MATCH) {

		/* get the probe process executable */
		tmp = find_ckpt_probe();
		if (tmp == NULL) {
			/* Can't find it at all, so bail */
			return _sysapi_vsyscall_gate_addr;
		}

		/* exec probe */
		cmd[0] = tmp;
		cmd[1] = "--vdso-addr";
		cmd[2] = NULL;
		fin = my_popenv(cmd, "r", TRUE);
		free(tmp);
		if (fin == NULL) {
			dprintf(D_ALWAYS, "my_popenv failed\n");
			return _sysapi_vsyscall_gate_addr;
		}
		if (fgets(buf, BUFFER_SIZE, fin) == NULL) {
			my_pclose(fin);
			dprintf(D_ALWAYS, "fgets failed\n");
			return _sysapi_vsyscall_gate_addr;
		}
		my_pclose(fin);

		if (sscanf(buf, "VDSO: %s\n", addr) != 1) {
			dprintf(D_ALWAYS, "sscanf didn't parse correctly\n");
			return _sysapi_vsyscall_gate_addr;
		}

	/* set up global with correct vdso address */
		if(_sysapi_vsyscall_gate_addr == NULL) {
			EXCEPT("Programmer error! _sysapi_vsyscall_gate_addr == NULL");
		}
		free(_sysapi_vsyscall_gate_addr);
		_sysapi_vsyscall_gate_addr = strdup(addr);
	}
#endif

	return _sysapi_vsyscall_gate_addr;
}

/* the cooked version */
/* Do not free the returned pointer */
const char *
sysapi_vsyscall_gate_addr(void)
{
	sysapi_internal_reconfig();

	return sysapi_vsyscall_gate_addr_raw();
}

<|endoftext|>


<commit_before>/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-

Copyright 2016 Raffaello D. Di Napoli

This file is part of Abaclade.

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

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

You should have received a copy of the GNU Lesser General Public License along with Abaclade. If
not, see <http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------------------------------*/

#include <abaclade.hxx>
#include <abaclade/from_str.hxx>
#include <abaclade/text.hxx>

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

namespace abc { namespace _pvt {

void throw_on_unused_from_str_chars(io::text::str_istream const & sis) {
   if (std::size_t cchRemaining = sis.remaining_size_in_chars()) {
      // There are still unused characters in sis, so the conversion failed.
      str const & sSrc = sis.get_str();
      ABC_THROW(text::syntax_error, (
         ABC_SL("unexpected character"), sSrc,
         static_cast<unsigned>(sSrc.index_from_char_index(sSrc.size_in_chars() - cchRemaining))
      ));
   }
}

}} //namespace abc::_pvt

namespace abc {

void throw_on_unused_streaming_format_chars(
   str::const_iterator const & itFormatConsumedEnd, str const & sFormat
) {
   if (itFormatConsumedEnd != sFormat.cend()) {
      ABC_THROW(text::syntax_error, (
         ABC_SL("unexpected character in format string"), sFormat,
         static_cast<unsigned>(itFormatConsumedEnd - sFormat.cbegin())
      ));
   }
}

} //namespace abc

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

namespace abc {

from_text_istream<bool>::from_text_istream() :
   m_sTrue(ABC_SL("true")),
   m_sFalse(ABC_SL("false")) {
}

void from_text_istream<bool>::set_format(str const & sFormat) {
   ABC_TRACE_FUNC(this, sFormat);

   throw_on_unused_streaming_format_chars(sFormat.cbegin(), sFormat);
}

void from_text_istream<bool>::read(bool * pb, io::text::istream * ptis) {
   ABC_TRACE_FUNC(this, pb, ptis);

   sstr<16> sRead;
   for (str sPeek; (sPeek = ptis->peek_chars(1)); ptis->consume_chars(sPeek.size_in_chars())) {
      for (auto itPeek(sPeek.cbegin()), itPeekEnd(sPeek.cend()); itPeek != itPeekEnd; ++itPeek) {
         char32_t cp = *itPeek;
         // TODO: replace this with the UCD equivalent of \w from abc::text.
         if ((cp < '0' || cp > '9') && (cp < 'A' || cp > 'Z') && (cp < 'a' || cp > 'z')) {
            // Consume all preceding characters and stop.
            ptis->consume_chars(itPeek.char_index());
            goto break_outer_while;
         }
         sRead += cp;
      }
   }
break_outer_while:
   if (sRead == m_sTrue) {
      *pb = true;
   } else if (sRead == m_sFalse) {
      *pb = false;
   } else {
      ptis->unconsume_chars(sRead.str());
      // TODO: provide more information in the exception and/or use a better exception class.
      ABC_THROW(text::syntax_error, (ABC_SL("unrecognized input"), sRead));
   }
}

} //namespace abc
<commit_msg>Rename label<commit_after>/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-

Copyright 2016 Raffaello D. Di Napoli

This file is part of Abaclade.

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

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

You should have received a copy of the GNU Lesser General Public License along with Abaclade. If
not, see <http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------------------------------*/

#include <abaclade.hxx>
#include <abaclade/from_str.hxx>
#include <abaclade/text.hxx>

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

namespace abc { namespace _pvt {

void throw_on_unused_from_str_chars(io::text::str_istream const & sis) {
   if (std::size_t cchRemaining = sis.remaining_size_in_chars()) {
      // There are still unused characters in sis, so the conversion failed.
      str const & sSrc = sis.get_str();
      ABC_THROW(text::syntax_error, (
         ABC_SL("unexpected character"), sSrc,
         static_cast<unsigned>(sSrc.index_from_char_index(sSrc.size_in_chars() - cchRemaining))
      ));
   }
}

}} //namespace abc::_pvt

namespace abc {

void throw_on_unused_streaming_format_chars(
   str::const_iterator const & itFormatConsumedEnd, str const & sFormat
) {
   if (itFormatConsumedEnd != sFormat.cend()) {
      ABC_THROW(text::syntax_error, (
         ABC_SL("unexpected character in format string"), sFormat,
         static_cast<unsigned>(itFormatConsumedEnd - sFormat.cbegin())
      ));
   }
}

} //namespace abc

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

namespace abc {

from_text_istream<bool>::from_text_istream() :
   m_sTrue(ABC_SL("true")),
   m_sFalse(ABC_SL("false")) {
}

void from_text_istream<bool>::set_format(str const & sFormat) {
   ABC_TRACE_FUNC(this, sFormat);

   throw_on_unused_streaming_format_chars(sFormat.cbegin(), sFormat);
}

void from_text_istream<bool>::read(bool * pb, io::text::istream * ptis) {
   ABC_TRACE_FUNC(this, pb, ptis);

   sstr<16> sRead;
   for (str sPeek; (sPeek = ptis->peek_chars(1)); ptis->consume_chars(sPeek.size_in_chars())) {
      for (auto itPeek(sPeek.cbegin()), itPeekEnd(sPeek.cend()); itPeek != itPeekEnd; ++itPeek) {
         char32_t cp = *itPeek;
         // TODO: replace this with the UCD equivalent of \w from abc::text.
         if ((cp < '0' || cp > '9') && (cp < 'A' || cp > 'Z') && (cp < 'a' || cp > 'z')) {
            // Consume all preceding characters and stop.
            ptis->consume_chars(itPeek.char_index());
            goto break_outer_for;
         }
         sRead += cp;
      }
   }
break_outer_for:
   if (sRead == m_sTrue) {
      *pb = true;
   } else if (sRead == m_sFalse) {
      *pb = false;
   } else {
      ptis->unconsume_chars(sRead.str());
      // TODO: provide more information in the exception and/or use a better exception class.
      ABC_THROW(text::syntax_error, (ABC_SL("unrecognized input"), sRead));
   }
}

} //namespace abc
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qcontactabstractrequest.h"
#include "qcontactabstractrequest_p.h"
#include "qcontactmanager.h"
#include "qcontactmanager_p.h"
#include "qcontactmanagerengine.h"

QTM_BEGIN_NAMESPACE
/*!
  \class QContactAbstractRequest

  \brief The QContactAbstractRequest class provides a mechanism for
  asynchronous requests to be made of a manager if it supports them.

  \ingroup contacts-main

  It allows a client to asynchronously request some functionality of a
  particular QContactManager.
 */

/*!
  \fn QContactAbstractRequest::stateChanged(QContactAbstractRequest::State newState)
  This signal is emitted when the state of the request is changed.  The new state of
  the request will be contained in \a newState.
 */

/*!
  \fn QContactAbstractRequest::resultsAvailable()
  This signal is emitted when new results are available.  Results can include
  the operation error which may be accessed via error(), or derived-class-specific
  results which are accessible through the derived class API.

  \sa error()
 */

/*!
  \enum QContactAbstractRequest::RequestType
  Enumerates the various possible types of asynchronous requests
  \value InvalidRequest An invalid request
  \value ContactFetchRequest A request to fetch a list of contacts
  \value ContactLocalIdFetchRequest A request to fetch a list of local contact ids
  \value ContactRemoveRequest A request to remove a list of contacts
  \value ContactSaveRequest A request to save a list of contacts
  \value DetailDefinitionFetchRequest A request to fetch a collection of detail definitions
  \value DetailDefinitionRemoveRequest A request to remove a list of detail definitions
  \value DetailDefinitionSaveRequest A request to save a list of detail definitions
  \value RelationshipFetchRequest A request to fetch relationships between contacts
  \value RelationshipRemoveRequest A request to remove any relationships which match the request criteria
  \value RelationshipSaveRequest A request to save a list of relationships
 */

/*!
  \enum QContactAbstractRequest::Status
  \internal
  Enumerates the various states that a request may be in at any given time.  Deprecated - use QContactAbstractRequest::State instead!
  \value Inactive Operation not yet started
  \value Active Operation started, not yet finished
  \value Cancelling Operation started then cancelled, not yet finished
  \value Cancelled Operation is finished due to cancellation
  \value Finished Operation successfully completed
 */

/*!
  \enum QContactAbstractRequest::State
  Enumerates the various states that a request may be in at any given time
  \value InactiveState Operation not yet started
  \value ActiveState Operation started, not yet finished
  \value CanceledState Operation is finished due to cancellation
  \value FinishedState Operation successfully completed
 */

/*!
  \fn QContactAbstractRequest::QContactAbstractRequest()
  Constructs a new, invalid asynchronous request
 */

/*! Constructs a new request from the given request data \a otherd */
QContactAbstractRequest::QContactAbstractRequest(QContactAbstractRequestPrivate* otherd)
    : d_ptr(otherd)
{
}

/*! Cleans up the memory used by this request */
QContactAbstractRequest::~QContactAbstractRequest()
{
    if (d_ptr) {
        QContactManagerEngine *engine = QContactManagerData::engine(d_ptr->m_manager);
        if (engine) {
            engine->requestDestroyed(this);
        }

        delete d_ptr;
    }
}

/*!
  Returns true if the request is in the \c QContactAbstractRequest::InactiveState state; otherwise, returns false

  \sa state()
 */
bool QContactAbstractRequest::isInactive() const
{
    return (d_ptr->m_state == QContactAbstractRequest::InactiveState);
}

/*!
  Returns true if the request is in the \c QContactAbstractRequest::ActiveState state; otherwise, returns false

  \sa state()
 */
bool QContactAbstractRequest::isActive() const
{
    return (d_ptr->m_state == QContactAbstractRequest::ActiveState);
}

/*!
  Returns true if the request is in the \c QContactAbstractRequest::FinishedState; otherwise, returns false

  \sa state()
 */
bool QContactAbstractRequest::isFinished() const
{
    return (d_ptr->m_state == QContactAbstractRequest::FinishedState);
}

/*!
  Returns true if the request is in the \c QContactAbstractRequest::CanceledState; otherwise, returns false

  \sa state()
 */
bool QContactAbstractRequest::isCanceled() const
{
    return (d_ptr->m_state == QContactAbstractRequest::CanceledState);
}

/*! Returns the overall error of the most recent asynchronous operation */
QContactManager::Error QContactAbstractRequest::error() const
{
    return d_ptr->m_error;
}

/*!
  \internal
  Returns the list of errors which occurred during the most recent asynchronous operation.  Each individual error in the list corresponds to a result in the result list.
 */
QList<QContactManager::Error> QContactAbstractRequest::errors() const
{
    return QList<QContactManager::Error>();
}

/*!
  Returns the type of this asynchronous request
 */
QContactAbstractRequest::RequestType QContactAbstractRequest::type() const
{
    return d_ptr->type();
}

/*!
  \internal
  Returns the current status of the request.
 */
QContactAbstractRequest::Status QContactAbstractRequest::status() const
{
    return static_cast<QContactAbstractRequest::Status>(d_ptr->m_state);
}

/*!
  Returns the current state of the request.
 */
QContactAbstractRequest::State QContactAbstractRequest::state() const
{
    return d_ptr->m_state;
}

/*! Returns a pointer to the manager of which this request instance requests operations */
QContactManager* QContactAbstractRequest::manager() const
{
    return d_ptr->m_manager;
}

/*! Sets the manager of which this request instance requests operations to \a manager */
void QContactAbstractRequest::setManager(QContactManager* manager)
{
    d_ptr->m_manager = manager;
}

/*! Attempts to start the request.  Returns false if the request is not in the \c QContactAbstractRequest::Inactive, \c QContactAbstractRequest::Finished or \c QContactAbstractRequest::Cancelled states,
    or if the request was unable to be performed by the manager engine; otherwise returns true. */
bool QContactAbstractRequest::start()
{
    QContactManagerEngine *engine = QContactManagerData::engine(d_ptr->m_manager);
    if (engine && (d_ptr->m_state == QContactAbstractRequest::CanceledState
                   || d_ptr->m_state == QContactAbstractRequest::FinishedState
                   || d_ptr->m_state == QContactAbstractRequest::InactiveState)) {
        return engine->startRequest(this);
    }

    return false; // unable to start operation; another operation already in progress or no engine.
}

/*! Attempts to cancel the request.  Returns false if the request is not in the \c QContactAbstractRequest::Active state,
    or if the request is unable to be cancelled by the manager engine; otherwise returns true. */
bool QContactAbstractRequest::cancel()
{
    QContactManagerEngine *engine = QContactManagerData::engine(d_ptr->m_manager);
    if (engine && state() == QContactAbstractRequest::ActiveState) {
        return engine->cancelRequest(this);
    }

    return false; // unable to cancel operation; not in progress or no engine.
}

/*! Blocks until the request has been completed by the manager engine, or until \a msecs milliseconds has elapsed.
    If \a msecs is zero, this function will block indefinitely.
    Returns true if the request was cancelled or completed successfully within the given period, otherwise false.
    Some backends are unable to support this operation safely, and will return false immediately.
 */
bool QContactAbstractRequest::waitForFinished(int msecs)
{
    QContactManagerEngine *engine = QContactManagerData::engine(d_ptr->m_manager);
    if (engine) {
        switch (d_ptr->m_state) {
        case QContactAbstractRequest::ActiveState:
            return engine->waitForRequestFinished(this, msecs);
        case QContactAbstractRequest::CanceledState:
        case QContactAbstractRequest::FinishedState:
            return true;
        default:
            return false;
        }
    }

    return false; // unable to wait for operation; not in progress or no engine.
}

/*! Blocks until the manager engine signals that more partial results are available for the request, or until \a msecs milliseconds has elapsed.
    If \a msecs is zero, this function will block indefinitely.
    Returns true if the request was cancelled or more partial results were made available within the given period, otherwise false. */
bool QContactAbstractRequest::waitForProgress(int msecs)
{
    QContactManagerEngine *engine = QContactManagerData::engine(d_ptr->m_manager);
    if (engine) {
        switch (d_ptr->m_state) {
        case QContactAbstractRequest::ActiveState:
            return engine->waitForRequestProgress(this, msecs);
        case QContactAbstractRequest::CanceledState:
        case QContactAbstractRequest::FinishedState:
            return true;
        default:
            return false;
        }
    }

    return false; // unable to wait for operation; not in progress or no engine.
}

#include "moc_qcontactabstractrequest.cpp"

QTM_END_NAMESPACE
<commit_msg>Mark another deprecated function as internal<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qcontactabstractrequest.h"
#include "qcontactabstractrequest_p.h"
#include "qcontactmanager.h"
#include "qcontactmanager_p.h"
#include "qcontactmanagerengine.h"

QTM_BEGIN_NAMESPACE
/*!
  \class QContactAbstractRequest

  \brief The QContactAbstractRequest class provides a mechanism for
  asynchronous requests to be made of a manager if it supports them.

  \ingroup contacts-main

  It allows a client to asynchronously request some functionality of a
  particular QContactManager.
 */

/*!
  \fn QContactAbstractRequest::stateChanged(QContactAbstractRequest::State newState)
  This signal is emitted when the state of the request is changed.  The new state of
  the request will be contained in \a newState.
 */

/*!
  \fn QContactAbstractRequest::resultsAvailable()
  This signal is emitted when new results are available.  Results can include
  the operation error which may be accessed via error(), or derived-class-specific
  results which are accessible through the derived class API.

  \sa error()
 */

/*!
  \enum QContactAbstractRequest::RequestType
  Enumerates the various possible types of asynchronous requests
  \value InvalidRequest An invalid request
  \value ContactFetchRequest A request to fetch a list of contacts
  \value ContactLocalIdFetchRequest A request to fetch a list of local contact ids
  \value ContactRemoveRequest A request to remove a list of contacts
  \value ContactSaveRequest A request to save a list of contacts
  \value DetailDefinitionFetchRequest A request to fetch a collection of detail definitions
  \value DetailDefinitionRemoveRequest A request to remove a list of detail definitions
  \value DetailDefinitionSaveRequest A request to save a list of detail definitions
  \value RelationshipFetchRequest A request to fetch relationships between contacts
  \value RelationshipRemoveRequest A request to remove any relationships which match the request criteria
  \value RelationshipSaveRequest A request to save a list of relationships
 */

/*!
  \enum QContactAbstractRequest::Status
  \internal
  Enumerates the various states that a request may be in at any given time.  Deprecated - use QContactAbstractRequest::State instead!
  \value Inactive Operation not yet started
  \value Active Operation started, not yet finished
  \value Cancelling Operation started then cancelled, not yet finished
  \value Cancelled Operation is finished due to cancellation
  \value Finished Operation successfully completed
 */

/*!
  \enum QContactAbstractRequest::State
  Enumerates the various states that a request may be in at any given time
  \value InactiveState Operation not yet started
  \value ActiveState Operation started, not yet finished
  \value CanceledState Operation is finished due to cancellation
  \value FinishedState Operation successfully completed
 */

/*!
  \fn QContactAbstractRequest::QContactAbstractRequest()
  Constructs a new, invalid asynchronous request
 */

/*! Constructs a new request from the given request data \a otherd */
QContactAbstractRequest::QContactAbstractRequest(QContactAbstractRequestPrivate* otherd)
    : d_ptr(otherd)
{
}

/*! Cleans up the memory used by this request */
QContactAbstractRequest::~QContactAbstractRequest()
{
    if (d_ptr) {
        QContactManagerEngine *engine = QContactManagerData::engine(d_ptr->m_manager);
        if (engine) {
            engine->requestDestroyed(this);
        }

        delete d_ptr;
    }
}

/*!
  Returns true if the request is in the \c QContactAbstractRequest::InactiveState state; otherwise, returns false

  \sa state()
 */
bool QContactAbstractRequest::isInactive() const
{
    return (d_ptr->m_state == QContactAbstractRequest::InactiveState);
}

/*!
  Returns true if the request is in the \c QContactAbstractRequest::ActiveState state; otherwise, returns false

  \sa state()
 */
bool QContactAbstractRequest::isActive() const
{
    return (d_ptr->m_state == QContactAbstractRequest::ActiveState);
}

/*!
  Returns true if the request is in the \c QContactAbstractRequest::FinishedState; otherwise, returns false

  \sa state()
 */
bool QContactAbstractRequest::isFinished() const
{
    return (d_ptr->m_state == QContactAbstractRequest::FinishedState);
}

/*!
  Returns true if the request is in the \c QContactAbstractRequest::CanceledState; otherwise, returns false

  \sa state()
 */
bool QContactAbstractRequest::isCanceled() const
{
    return (d_ptr->m_state == QContactAbstractRequest::CanceledState);
}

/*! Returns the overall error of the most recent asynchronous operation */
QContactManager::Error QContactAbstractRequest::error() const
{
    return d_ptr->m_error;
}

/*!
  \internal
  Returns the list of errors which occurred during the most recent asynchronous operation.  Each individual error in the list corresponds to a result in the result list.
 */
QList<QContactManager::Error> QContactAbstractRequest::errors() const
{
    return QList<QContactManager::Error>();
}

/*!
  Returns the type of this asynchronous request
 */
QContactAbstractRequest::RequestType QContactAbstractRequest::type() const
{
    return d_ptr->type();
}

/*!
  \internal
  Returns the current status of the request.
 */
QContactAbstractRequest::Status QContactAbstractRequest::status() const
{
    return static_cast<QContactAbstractRequest::Status>(d_ptr->m_state);
}

/*!
  Returns the current state of the request.
 */
QContactAbstractRequest::State QContactAbstractRequest::state() const
{
    return d_ptr->m_state;
}

/*! Returns a pointer to the manager of which this request instance requests operations */
QContactManager* QContactAbstractRequest::manager() const
{
    return d_ptr->m_manager;
}

/*! Sets the manager of which this request instance requests operations to \a manager */
void QContactAbstractRequest::setManager(QContactManager* manager)
{
    d_ptr->m_manager = manager;
}

/*! Attempts to start the request.  Returns false if the request is not in the \c QContactAbstractRequest::Inactive, \c QContactAbstractRequest::Finished or \c QContactAbstractRequest::Cancelled states,
    or if the request was unable to be performed by the manager engine; otherwise returns true. */
bool QContactAbstractRequest::start()
{
    QContactManagerEngine *engine = QContactManagerData::engine(d_ptr->m_manager);
    if (engine && (d_ptr->m_state == QContactAbstractRequest::CanceledState
                   || d_ptr->m_state == QContactAbstractRequest::FinishedState
                   || d_ptr->m_state == QContactAbstractRequest::InactiveState)) {
        return engine->startRequest(this);
    }

    return false; // unable to start operation; another operation already in progress or no engine.
}

/*! Attempts to cancel the request.  Returns false if the request is not in the \c QContactAbstractRequest::Active state,
    or if the request is unable to be cancelled by the manager engine; otherwise returns true. */
bool QContactAbstractRequest::cancel()
{
    QContactManagerEngine *engine = QContactManagerData::engine(d_ptr->m_manager);
    if (engine && state() == QContactAbstractRequest::ActiveState) {
        return engine->cancelRequest(this);
    }

    return false; // unable to cancel operation; not in progress or no engine.
}

/*! Blocks until the request has been completed by the manager engine, or until \a msecs milliseconds has elapsed.
    If \a msecs is zero, this function will block indefinitely.
    Returns true if the request was cancelled or completed successfully within the given period, otherwise false.
    Some backends are unable to support this operation safely, and will return false immediately.
 */
bool QContactAbstractRequest::waitForFinished(int msecs)
{
    QContactManagerEngine *engine = QContactManagerData::engine(d_ptr->m_manager);
    if (engine) {
        switch (d_ptr->m_state) {
        case QContactAbstractRequest::ActiveState:
            return engine->waitForRequestFinished(this, msecs);
        case QContactAbstractRequest::CanceledState:
        case QContactAbstractRequest::FinishedState:
            return true;
        default:
            return false;
        }
    }

    return false; // unable to wait for operation; not in progress or no engine.
}

/*! \internal
    Blocks until the manager engine signals that more partial results are available for the request, or until \a msecs milliseconds has elapsed.
    If \a msecs is zero, this function will block indefinitely.
    Returns true if the request was cancelled or more partial results were made available within the given period, otherwise false. */
bool QContactAbstractRequest::waitForProgress(int msecs)
{
    QContactManagerEngine *engine = QContactManagerData::engine(d_ptr->m_manager);
    if (engine) {
        switch (d_ptr->m_state) {
        case QContactAbstractRequest::ActiveState:
            return engine->waitForRequestProgress(this, msecs);
        case QContactAbstractRequest::CanceledState:
        case QContactAbstractRequest::FinishedState:
            return true;
        default:
            return false;
        }
    }

    return false; // unable to wait for operation; not in progress or no engine.
}

#include "moc_qcontactabstractrequest.cpp"

QTM_END_NAMESPACE
<|endoftext|>


<commit_before><commit_msg>Added short usage description.<commit_after><|endoftext|>


<commit_before>#ifndef STAN_MATH_PRIM_PROB_CAUCHY_LPDF_HPP
#define STAN_MATH_PRIM_PROB_CAUCHY_LPDF_HPP

#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/err.hpp>
#include <stan/math/prim/fun/constants.hpp>
#include <stan/math/prim/fun/log.hpp>
#include <stan/math/prim/fun/log1p.hpp>
#include <stan/math/prim/fun/max_size.hpp>
#include <stan/math/prim/fun/size.hpp>
#include <stan/math/prim/fun/size_zero.hpp>
#include <stan/math/prim/fun/value_of.hpp>
#include <cmath>

namespace stan {
namespace math {

/** \ingroup prob_dists
 * The log of the Cauchy density for the specified scalar(s) given
 * the specified location parameter(s) and scale parameter(s). y,
 * mu, or sigma can each either be scalar a vector.  Any vector
 * inputs must be the same length.
 *
 * <p> The result log probability is defined to be the sum of
 * the log probabilities for each observation/mu/sigma triple.
 *
 * @tparam T_y type of scalar outcome
 * @tparam T_loc type of location
 * @tparam T_scale type of scale
 * @param y (Sequence of) scalar(s).
 * @param mu (Sequence of) location(s).
 * @param sigma (Sequence of) scale(s).
 * @return The log of the product of densities.
 */
template <bool propto, typename T_y, typename T_loc, typename T_scale>
return_type_t<T_y, T_loc, T_scale> cauchy_lpdf(const T_y& y, const T_loc& mu,
                                               const T_scale& sigma) {
  using T_partials_return = partials_return_t<T_y, T_loc, T_scale>;
  using T_partials_array = Eigen::Array<T_partials_return, Eigen::Dynamic, 1>;
  using std::log;
  using T_y_ref = ref_type_if_t<!is_constant<T_y>::value, T_y>;
  using T_mu_ref = ref_type_if_t<!is_constant<T_loc>::value, T_loc>;
  using T_sigma_ref = ref_type_if_t<!is_constant<T_scale>::value, T_scale>;
  static const char* function = "cauchy_lpdf";
  check_consistent_sizes(function, "Random variable", y, "Location parameter",
                         mu, "Scale parameter", sigma);
  T_y_ref y_ref = y;
  T_mu_ref mu_ref = mu;
  T_sigma_ref sigma_ref = sigma;

  if (size_zero(y, mu, sigma)) {
    return 0.0;
  }
  if (!include_summand<propto, T_y, T_loc, T_scale>::value) {
    return 0.0;
  }

  T_partials_return logp(0.0);
  operands_and_partials<T_y_ref, T_mu_ref, T_sigma_ref> ops_partials(
      y_ref, mu_ref, sigma_ref);

  const auto& y_col = as_column_vector_or_scalar(y_ref);
  const auto& mu_col = as_column_vector_or_scalar(mu_ref);
  const auto& sigma_col = as_column_vector_or_scalar(sigma_ref);

  const auto& y_arr = as_array_or_scalar(y_col);
  const auto& mu_arr = as_array_or_scalar(mu_col);
  const auto& sigma_arr = as_array_or_scalar(sigma_col);

  ref_type_t<decltype(value_of(y_arr))> y_val = value_of(y_arr);
  ref_type_t<decltype(value_of(mu_arr))> mu_val = value_of(mu_arr);
  ref_type_t<decltype(value_of(sigma_arr))> sigma_val = value_of(sigma_arr);
  check_not_nan(function, "Random variable", y_val);
  check_finite(function, "Location parameter", mu_val);
  check_positive_finite(function, "Scale parameter", sigma_val);

  size_t N = max_size(y, mu, sigma);

  const auto& inv_sigma
      = to_ref_if<!is_constant_all<T_scale>::value>(inv(sigma_val));
  const auto& y_minus_mu
      = to_ref_if<!is_constant_all<T_y, T_loc, T_scale>::value>(y_val - mu_val);

  logp -= sum(log1p(square(y_minus_mu * inv_sigma)));
  if (include_summand<propto>::value) {
    logp -= N * LOG_PI;
  }
  if (include_summand<propto, T_scale>::value) {
    logp -= sum(log(sigma_val)) * N / size(sigma);
  }

  if (!is_constant_all<T_y, T_loc, T_scale>::value) {
    const auto& sigma_squared
        = to_ref_if<!is_constant_all<T_scale>::value>(square(sigma_val));
    const auto& y_minus_mu_squared
        = to_ref_if<!is_constant_all<T_scale>::value>(square(y_minus_mu));
    if (!is_constant_all<T_y, T_loc>::value) {
      const auto& mu_deriv
          = to_ref_if < !is_constant_all<T_y>::value
            && !is_constant_all<T_loc>::value
                   > (2 * y_minus_mu / (sigma_squared + y_minus_mu_squared));
      if (!is_constant_all<T_y>::value) {
        if (is_vector<T_y>::value) {
          ops_partials.edge1_.partials_
              = forward_as<T_partials_array>(-mu_deriv);
        } else {
          ops_partials.edge1_.partials_[0] = -sum(mu_deriv);
        }
      }
      if (!is_constant_all<T_loc>::value) {
        if (is_vector<T_loc>::value) {
          ops_partials.edge2_.partials_
              = std::move(forward_as<T_partials_array>(mu_deriv));
        } else {
          ops_partials.edge2_.partials_[0] = sum(mu_deriv);
        }
      }
    }
    if (!is_constant_all<T_scale>::value) {
      if (is_vector<T_scale>::value) {
        ops_partials.edge3_.partials_ = forward_as<T_partials_array>(
            (y_minus_mu_squared - sigma_squared) * inv_sigma
            / (sigma_squared + y_minus_mu_squared));
      } else {
        ops_partials.edge3_.partials_[0]
            = sum((y_minus_mu_squared - sigma_squared) * inv_sigma
                  / (sigma_squared + y_minus_mu_squared));
      }
    }
  }
  return ops_partials.build(logp);
}

template <typename T_y, typename T_loc, typename T_scale>
inline return_type_t<T_y, T_loc, T_scale> cauchy_lpdf(const T_y& y,
                                                      const T_loc& mu,
                                                      const T_scale& sigma) {
  return cauchy_lpdf<false>(y, mu, sigma);
}

}  // namespace math
}  // namespace stan
#endif
<commit_msg>added missing include<commit_after>#ifndef STAN_MATH_PRIM_PROB_CAUCHY_LPDF_HPP
#define STAN_MATH_PRIM_PROB_CAUCHY_LPDF_HPP

#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/err.hpp>
#include <stan/math/prim/fun/constants.hpp>
#include <stan/math/prim/fun/log.hpp>
#include <stan/math/prim/fun/log1p.hpp>
#include <stan/math/prim/fun/max_size.hpp>
#include <stan/math/prim/fun/size.hpp>
#include <stan/math/prim/fun/size_zero.hpp>
#include <stan/math/prim/fun/to_ref.hpp>
#include <stan/math/prim/fun/value_of.hpp>
#include <cmath>

namespace stan {
namespace math {

/** \ingroup prob_dists
 * The log of the Cauchy density for the specified scalar(s) given
 * the specified location parameter(s) and scale parameter(s). y,
 * mu, or sigma can each either be scalar a vector.  Any vector
 * inputs must be the same length.
 *
 * <p> The result log probability is defined to be the sum of
 * the log probabilities for each observation/mu/sigma triple.
 *
 * @tparam T_y type of scalar outcome
 * @tparam T_loc type of location
 * @tparam T_scale type of scale
 * @param y (Sequence of) scalar(s).
 * @param mu (Sequence of) location(s).
 * @param sigma (Sequence of) scale(s).
 * @return The log of the product of densities.
 */
template <bool propto, typename T_y, typename T_loc, typename T_scale>
return_type_t<T_y, T_loc, T_scale> cauchy_lpdf(const T_y& y, const T_loc& mu,
                                               const T_scale& sigma) {
  using T_partials_return = partials_return_t<T_y, T_loc, T_scale>;
  using T_partials_array = Eigen::Array<T_partials_return, Eigen::Dynamic, 1>;
  using std::log;
  using T_y_ref = ref_type_if_t<!is_constant<T_y>::value, T_y>;
  using T_mu_ref = ref_type_if_t<!is_constant<T_loc>::value, T_loc>;
  using T_sigma_ref = ref_type_if_t<!is_constant<T_scale>::value, T_scale>;
  static const char* function = "cauchy_lpdf";
  check_consistent_sizes(function, "Random variable", y, "Location parameter",
                         mu, "Scale parameter", sigma);
  T_y_ref y_ref = y;
  T_mu_ref mu_ref = mu;
  T_sigma_ref sigma_ref = sigma;

  if (size_zero(y, mu, sigma)) {
    return 0.0;
  }
  if (!include_summand<propto, T_y, T_loc, T_scale>::value) {
    return 0.0;
  }

  T_partials_return logp(0.0);
  operands_and_partials<T_y_ref, T_mu_ref, T_sigma_ref> ops_partials(
      y_ref, mu_ref, sigma_ref);

  const auto& y_col = as_column_vector_or_scalar(y_ref);
  const auto& mu_col = as_column_vector_or_scalar(mu_ref);
  const auto& sigma_col = as_column_vector_or_scalar(sigma_ref);

  const auto& y_arr = as_array_or_scalar(y_col);
  const auto& mu_arr = as_array_or_scalar(mu_col);
  const auto& sigma_arr = as_array_or_scalar(sigma_col);

  ref_type_t<decltype(value_of(y_arr))> y_val = value_of(y_arr);
  ref_type_t<decltype(value_of(mu_arr))> mu_val = value_of(mu_arr);
  ref_type_t<decltype(value_of(sigma_arr))> sigma_val = value_of(sigma_arr);
  check_not_nan(function, "Random variable", y_val);
  check_finite(function, "Location parameter", mu_val);
  check_positive_finite(function, "Scale parameter", sigma_val);

  size_t N = max_size(y, mu, sigma);

  const auto& inv_sigma
      = to_ref_if<!is_constant_all<T_scale>::value>(inv(sigma_val));
  const auto& y_minus_mu
      = to_ref_if<!is_constant_all<T_y, T_loc, T_scale>::value>(y_val - mu_val);

  logp -= sum(log1p(square(y_minus_mu * inv_sigma)));
  if (include_summand<propto>::value) {
    logp -= N * LOG_PI;
  }
  if (include_summand<propto, T_scale>::value) {
    logp -= sum(log(sigma_val)) * N / size(sigma);
  }

  if (!is_constant_all<T_y, T_loc, T_scale>::value) {
    const auto& sigma_squared
        = to_ref_if<!is_constant_all<T_scale>::value>(square(sigma_val));
    const auto& y_minus_mu_squared
        = to_ref_if<!is_constant_all<T_scale>::value>(square(y_minus_mu));
    if (!is_constant_all<T_y, T_loc>::value) {
      const auto& mu_deriv
          = to_ref_if < !is_constant_all<T_y>::value
            && !is_constant_all<T_loc>::value
                   > (2 * y_minus_mu / (sigma_squared + y_minus_mu_squared));
      if (!is_constant_all<T_y>::value) {
        if (is_vector<T_y>::value) {
          ops_partials.edge1_.partials_
              = forward_as<T_partials_array>(-mu_deriv);
        } else {
          ops_partials.edge1_.partials_[0] = -sum(mu_deriv);
        }
      }
      if (!is_constant_all<T_loc>::value) {
        if (is_vector<T_loc>::value) {
          ops_partials.edge2_.partials_
              = std::move(forward_as<T_partials_array>(mu_deriv));
        } else {
          ops_partials.edge2_.partials_[0] = sum(mu_deriv);
        }
      }
    }
    if (!is_constant_all<T_scale>::value) {
      if (is_vector<T_scale>::value) {
        ops_partials.edge3_.partials_ = forward_as<T_partials_array>(
            (y_minus_mu_squared - sigma_squared) * inv_sigma
            / (sigma_squared + y_minus_mu_squared));
      } else {
        ops_partials.edge3_.partials_[0]
            = sum((y_minus_mu_squared - sigma_squared) * inv_sigma
                  / (sigma_squared + y_minus_mu_squared));
      }
    }
  }
  return ops_partials.build(logp);
}

template <typename T_y, typename T_loc, typename T_scale>
inline return_type_t<T_y, T_loc, T_scale> cauchy_lpdf(const T_y& y,
                                                      const T_loc& mu,
                                                      const T_scale& sigma) {
  return cauchy_lpdf<false>(y, mu, sigma);
}

}  // namespace math
}  // namespace stan
#endif
<|endoftext|>


<commit_before>#include "aggregator_solver_protocol.hpp"
#include "netbuffer.hpp"
#include "sample_data.hpp"

#include <algorithm>
#include <string>
#include <iterator>
#include <array>
#include <vector>

#include <iostream>

using namespace aggregator_solver;

std::vector<unsigned char> aggregator_solver::makeHandshakeMsg() {
  std::vector<unsigned char> buff(4);
  std::string protocol_string = "GRAIL solver protocol";
  buff.insert(buff.end(), protocol_string.begin(), protocol_string.end());
  //Version number and extension are both currently zero
  buff.push_back(0);
  buff.push_back(0);
  //Insert the length of the protocol string into the buffer
  pushBackVal<uint32_t>(protocol_string.length(), buff, 0);
  return buff;
}

std::vector<unsigned char>&& aggregator_solver::makeCertMsg();

std::vector<unsigned char>&& aggregator_solver::ackCertMsg();

std::vector<unsigned char> aggregator_solver::makeSubscribeReqMsg(Subscription& rules) {
  //The total length starts out at one for the message type field.
  //Each rule will add additional length.
  uint32_t total_length = 1;

  std::vector<unsigned char> buff;

  buff.push_back(0);
  buff.push_back(0);
  buff.push_back(0);
  buff.push_back(0);
  buff.push_back((unsigned char)subscription_request);

  //Push back the rules
  {
    //First push the number of rules onto the buffer
    uint32_t num_rules = rules.size();
    total_length += pushBackVal(num_rules, buff);

    //For each rule push back the physical layer, the number of
    //tx rules and the tx rules, the number of boxes and the boxes,
    //and the number of FSM/TR rules and the FSM/TR rules.
    for (auto rule = rules.begin(); rule != rules.end(); ++rule) {
      //Push the physical layer
      total_length += pushBackVal(rule->physical_layer, buff);

      //Push the transmitter information
      uint32_t num_txers = rule->txers.size();
      total_length += pushBackVal(num_txers, buff);
      //Each transmitter is made of an ID and a MASK
      for (auto txer = rule->txers.begin(); txer != rule->txers.end(); ++txer) {
        total_length += pushBackVal(txer->base_id, buff);
        total_length += pushBackVal(txer->mask, buff);
      }

      //Finish the rule with the update interval
      total_length += pushBackVal(rule->update_interval, buff);
    }
  }

  //Store the message length in the first four bytes
  pushBackVal<uint32_t>(total_length, buff, 0);

  return buff;
}

Subscription aggregator_solver::decodeSubscribeMsg(std::vector<unsigned char>& buff, unsigned int length) {
  Subscription rules;

  //Only process the message if its type matches one of the subscription ids
  //and if the message is large enough to be valid.
  if ( length > 4 ) {

    BuffReader reader(buff);
    uint32_t entire_length = reader.readPrimitive<uint32_t>();
    MessageID msg_type = MessageID(reader.readPrimitive<uint8_t>());
    if (entire_length + 4 == length and
        (subscription_request == msg_type or
         subscription_response == msg_type)) {

      uint32_t num_rules = reader.readPrimitive<uint32_t>();
      for (size_t rule_no = 0; rule_no < num_rules; ++rule_no) {
        Rule rule;
        rule.physical_layer = reader.readPrimitive<unsigned char>();
        //Read in the txer ids and masks
        uint32_t num_txers = reader.readPrimitive<uint32_t>();
        for (size_t txer_no = 0; txer_no < num_txers; ++txer_no) {
          Transmitter t;
          t.base_id = reader.readPrimitive<uint128_t>();
          t.mask = reader.readPrimitive<uint128_t>();
          rule.txers.push_back(t);
        }

        rule.update_interval = reader.readPrimitive<decltype(rule.update_interval)>();

        rules.push_back(rule);

      }
    }
  }

  return rules;
}

std::vector<unsigned char> aggregator_solver::makeSampleMsg(SampleData& sample) {
  //The total length starts out at one for the message type field.
  //Each rule will add additional length.
  uint32_t total_length = 1;

  std::vector<unsigned char> buff;

  buff.push_back(0);
  buff.push_back(0);
  buff.push_back(0);
  buff.push_back(0);
  buff.push_back((unsigned char)server_sample);

  total_length += pushBackVal(sample.physical_layer, buff);
  total_length += pushBackVal(sample.tx_id, buff);
  total_length += pushBackVal(sample.rx_id, buff);
  total_length += pushBackVal(sample.rx_timestamp, buff);
  total_length += pushBackVal(sample.rss, buff);
  if (sample.sense_data.size() > 0) {
    total_length += pushContainer(sample.sense_data, buff);
  }

  pushBackVal<uint32_t>(total_length, buff, 0);

  return buff;
}

SampleData aggregator_solver::decodeSampleMsg(std::vector<unsigned char>& buff, unsigned int length) {
  SampleData sample;
  //Assume that the sample is invalid until we manage to get data out of buff
  sample.valid = false;

  //Only process the message if its type matches the server_sample id
  //and the length is sane.
  if ( length > 4 ) {

    //Make a new buffer reader for this message and put the data into the
    //sample structure.
    BuffReader reader(buff);
    uint32_t entire_length = reader.readPrimitive<uint32_t>();
    MessageID msg_type = MessageID(reader.readPrimitive<uint8_t>());
    if (entire_length + 4 == length and
        server_sample == msg_type) {
      //Since we found data to read into the sample, mark it as valid.
      sample.valid = true;
      sample.physical_layer = reader.readPrimitive<decltype(sample.physical_layer)>();
      sample.tx_id = reader.readPrimitive<decltype(sample.tx_id)>();
      sample.rx_id = reader.readPrimitive<decltype(sample.rx_id)>();
      sample.rx_timestamp = reader.readPrimitive<decltype(sample.rx_timestamp)>();
      sample.rss = reader.readPrimitive<decltype(sample.rss)>();
      //Get the size of the sense data
      unsigned int left = length - reader.cur_index;
      sample.sense_data = std::vector<unsigned char>(left);
      reader.readPrimitiveContainer(sample.sense_data);
    }
  }

  return sample;
}

<commit_msg>Adding file documentation header.<commit_after>/*
 * Copyright (c) 2012 Bernhard Firner and Rutgers University
 * All rights reserved.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 * or visit http://www.gnu.org/licenses/gpl-2.0.html
 */

/**
 * @file aggregator_solver_protocol.cpp
 * Defines messages between aggregators and solvers in the
 * owl/grail platform format.
 *
 * @author Bernhard Firner
 */

#include "aggregator_solver_protocol.hpp"
#include "netbuffer.hpp"
#include "sample_data.hpp"

#include <algorithm>
#include <string>
#include <iterator>
#include <array>
#include <vector>

#include <iostream>

using namespace aggregator_solver;

std::vector<unsigned char> aggregator_solver::makeHandshakeMsg() {
  std::vector<unsigned char> buff(4);
  std::string protocol_string = "GRAIL solver protocol";
  buff.insert(buff.end(), protocol_string.begin(), protocol_string.end());
  //Version number and extension are both currently zero
  buff.push_back(0);
  buff.push_back(0);
  //Insert the length of the protocol string into the buffer
  pushBackVal<uint32_t>(protocol_string.length(), buff, 0);
  return buff;
}

std::vector<unsigned char>&& aggregator_solver::makeCertMsg();

std::vector<unsigned char>&& aggregator_solver::ackCertMsg();

std::vector<unsigned char> aggregator_solver::makeSubscribeReqMsg(Subscription& rules) {
  //The total length starts out at one for the message type field.
  //Each rule will add additional length.
  uint32_t total_length = 1;

  std::vector<unsigned char> buff;

  buff.push_back(0);
  buff.push_back(0);
  buff.push_back(0);
  buff.push_back(0);
  buff.push_back((unsigned char)subscription_request);

  //Push back the rules
  {
    //First push the number of rules onto the buffer
    uint32_t num_rules = rules.size();
    total_length += pushBackVal(num_rules, buff);

    //For each rule push back the physical layer, the number of
    //tx rules and the tx rules, the number of boxes and the boxes,
    //and the number of FSM/TR rules and the FSM/TR rules.
    for (auto rule = rules.begin(); rule != rules.end(); ++rule) {
      //Push the physical layer
      total_length += pushBackVal(rule->physical_layer, buff);

      //Push the transmitter information
      uint32_t num_txers = rule->txers.size();
      total_length += pushBackVal(num_txers, buff);
      //Each transmitter is made of an ID and a MASK
      for (auto txer = rule->txers.begin(); txer != rule->txers.end(); ++txer) {
        total_length += pushBackVal(txer->base_id, buff);
        total_length += pushBackVal(txer->mask, buff);
      }

      //Finish the rule with the update interval
      total_length += pushBackVal(rule->update_interval, buff);
    }
  }

  //Store the message length in the first four bytes
  pushBackVal<uint32_t>(total_length, buff, 0);

  return buff;
}

Subscription aggregator_solver::decodeSubscribeMsg(std::vector<unsigned char>& buff, unsigned int length) {
  Subscription rules;

  //Only process the message if its type matches one of the subscription ids
  //and if the message is large enough to be valid.
  if ( length > 4 ) {

    BuffReader reader(buff);
    uint32_t entire_length = reader.readPrimitive<uint32_t>();
    MessageID msg_type = MessageID(reader.readPrimitive<uint8_t>());
    if (entire_length + 4 == length and
        (subscription_request == msg_type or
         subscription_response == msg_type)) {

      uint32_t num_rules = reader.readPrimitive<uint32_t>();
      for (size_t rule_no = 0; rule_no < num_rules; ++rule_no) {
        Rule rule;
        rule.physical_layer = reader.readPrimitive<unsigned char>();
        //Read in the txer ids and masks
        uint32_t num_txers = reader.readPrimitive<uint32_t>();
        for (size_t txer_no = 0; txer_no < num_txers; ++txer_no) {
          Transmitter t;
          t.base_id = reader.readPrimitive<uint128_t>();
          t.mask = reader.readPrimitive<uint128_t>();
          rule.txers.push_back(t);
        }

        rule.update_interval = reader.readPrimitive<decltype(rule.update_interval)>();

        rules.push_back(rule);

      }
    }
  }

  return rules;
}

std::vector<unsigned char> aggregator_solver::makeSampleMsg(SampleData& sample) {
  //The total length starts out at one for the message type field.
  //Each rule will add additional length.
  uint32_t total_length = 1;

  std::vector<unsigned char> buff;

  buff.push_back(0);
  buff.push_back(0);
  buff.push_back(0);
  buff.push_back(0);
  buff.push_back((unsigned char)server_sample);

  total_length += pushBackVal(sample.physical_layer, buff);
  total_length += pushBackVal(sample.tx_id, buff);
  total_length += pushBackVal(sample.rx_id, buff);
  total_length += pushBackVal(sample.rx_timestamp, buff);
  total_length += pushBackVal(sample.rss, buff);
  if (sample.sense_data.size() > 0) {
    total_length += pushContainer(sample.sense_data, buff);
  }

  pushBackVal<uint32_t>(total_length, buff, 0);

  return buff;
}

SampleData aggregator_solver::decodeSampleMsg(std::vector<unsigned char>& buff, unsigned int length) {
  SampleData sample;
  //Assume that the sample is invalid until we manage to get data out of buff
  sample.valid = false;

  //Only process the message if its type matches the server_sample id
  //and the length is sane.
  if ( length > 4 ) {

    //Make a new buffer reader for this message and put the data into the
    //sample structure.
    BuffReader reader(buff);
    uint32_t entire_length = reader.readPrimitive<uint32_t>();
    MessageID msg_type = MessageID(reader.readPrimitive<uint8_t>());
    if (entire_length + 4 == length and
        server_sample == msg_type) {
      //Since we found data to read into the sample, mark it as valid.
      sample.valid = true;
      sample.physical_layer = reader.readPrimitive<decltype(sample.physical_layer)>();
      sample.tx_id = reader.readPrimitive<decltype(sample.tx_id)>();
      sample.rx_id = reader.readPrimitive<decltype(sample.rx_id)>();
      sample.rx_timestamp = reader.readPrimitive<decltype(sample.rx_timestamp)>();
      sample.rss = reader.readPrimitive<decltype(sample.rss)>();
      //Get the size of the sense data
      unsigned int left = length - reader.cur_index;
      sample.sense_data = std::vector<unsigned char>(left);
      reader.readPrimitiveContainer(sample.sense_data);
    }
  }

  return sample;
}

<|endoftext|>


<commit_before>/*
 * Copyright (C) 2006-2020  Music Technology Group - Universitat Pompeu Fabra
 *
 * This file is part of Essentia
 *
 * Essentia is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License as published by the Free
 * Software Foundation (FSF), either version 3 of the License, or (at your
 * option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the Affero GNU General Public License
 * version 3 along with this program.  If not, see http://www.gnu.org/licenses/
 */

#include "histogram.h"

using namespace essentia;
using namespace standard;

const char* Histogram::name = "Histogram";
const char* Histogram::category = "Statistics";
const char* Histogram::description = DOC("This algorithm computes a histogram. Values outside the range are ignored");

void Histogram::configure() {
  _normalize = parameter("normalize").toString();
  _minValue = parameter("minValue").toReal();
  _maxValue = parameter("maxValue").toReal();
  _numberBins = parameter("numberBins").toInt();

  if(_maxValue < _minValue)
    throw EssentiaException("Histogram: maxValue must be > minValue");

  if(_maxValue == _minValue) {
    if(_numberBins > 1)
       throw EssentiaException("Histogram: numberBins must = 1 when maxValue = minValue");
  }

  binWidth =  (_maxValue - _minValue)/(Real)_numberBins;

  tempBinEdges.resize(_numberBins+1);

  tempBinEdges[0] = _minValue;
  for(std::vector<Real>::iterator it = tempBinEdges.begin()+1; it != tempBinEdges.end(); it++) {
    *it = *(it-1) + binWidth;
  }

}

void Histogram::compute() {

  const std::vector<Real>& array = _array.get();
  std::vector<Real>& histogram = _histogram.get();
  std::vector<Real>& binEdges = _binEdges.get();

  histogram.resize(_numberBins);
  binEdges.assign(tempBinEdges.begin(), tempBinEdges.end());

  for(size_t i = 0; i < array.size(); i++){
    if(array[i] < _maxValue && array[i] >= _minValue)
      histogram[floor(array[i]/(Real)binWidth)]++;
    else if(array[i] == _maxValue)
      histogram[_numberBins-1]++;
  }

  if(_normalize != "none"){
    Real denominator = 0;
    if(_normalize == "unit_sum") {
      for(std::vector<Real>::iterator it = histogram.begin(); it != histogram.end(); it++) {
        denominator += *it;
      }
    }
    if(_normalize == "unit_max") {
      for(std::vector<Real>::iterator it = histogram.begin(); it != histogram.end(); it++) {
        if(*it > denominator)
          denominator = *it;
      }
    }
    for(std::vector<Real>::iterator it = histogram.begin(); it != histogram.end(); it++) {
      *it = *it/denominator;
    }
  }
}
<commit_msg>Fixed histogram logic<commit_after>/*
 * Copyright (C) 2006-2020  Music Technology Group - Universitat Pompeu Fabra
 *
 * This file is part of Essentia
 *
 * Essentia is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License as published by the Free
 * Software Foundation (FSF), either version 3 of the License, or (at your
 * option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the Affero GNU General Public License
 * version 3 along with this program.  If not, see http://www.gnu.org/licenses/
 */

#include "histogram.h"

using namespace essentia;
using namespace standard;

const char* Histogram::name = "Histogram";
const char* Histogram::category = "Statistics";
const char* Histogram::description = DOC("This algorithm computes a histogram. Values outside the range are ignored");

void Histogram::configure() {
  _normalize = parameter("normalize").toString();
  _minValue = parameter("minValue").toReal();
  _maxValue = parameter("maxValue").toReal();
  _numberBins = parameter("numberBins").toInt();

  if(_maxValue < _minValue)
    throw EssentiaException("Histogram: maxValue must be > minValue");

  if(_maxValue == _minValue) {
    if(_numberBins > 1)
       throw EssentiaException("Histogram: numberBins must = 1 when maxValue = minValue");
  }

  binWidth =  (_maxValue - _minValue)/(Real)_numberBins;

  tempBinEdges.resize(_numberBins+1);

  tempBinEdges[0] = _minValue;
  for(std::vector<Real>::iterator it = tempBinEdges.begin()+1; it != tempBinEdges.end(); it++) {
    *it = *(it-1) + binWidth;
  }

}

void Histogram::compute() {

  const std::vector<Real>& array = _array.get();
  std::vector<Real>& histogram = _histogram.get();
  std::vector<Real>& binEdges = _binEdges.get();

  histogram.resize(_numberBins);
  binEdges.assign(tempBinEdges.begin(), tempBinEdges.end());

  for(size_t i = 0; i < array.size(); i++){
    if(array[i] < _maxValue && array[i] >= _minValue)
      histogram[floor((array[i] - _minValue)/(Real)binWidth)]++;
    else if(array[i] == _maxValue)
      histogram[_numberBins-1]++;
  }

  if(_normalize != "none"){
    Real denominator = 0;
    if(_normalize == "unit_sum") {
      for(std::vector<Real>::iterator it = histogram.begin(); it != histogram.end(); it++) {
        denominator += *it;
      }
    }
    if(_normalize == "unit_max") {
      for(std::vector<Real>::iterator it = histogram.begin(); it != histogram.end(); it++) {
        if(*it > denominator)
          denominator = *it;
      }
    }
    for(std::vector<Real>::iterator it = histogram.begin(); it != histogram.end(); it++) {
      *it = *it/denominator;
    }
  }
}
<|endoftext|>


<commit_before>/*
 * ApproxBetweenness.cpp
 *
 *  Created on: 09.04.2014
 *      Author: cls
 */

#include "ApproxBetweenness.h"
#include "../auxiliary/Random.h"
#include "../properties/Diameter.h"
#include "../graph/Sampling.h"
#include "../graph/Dijkstra.h"
#include "../graph/BFS.h"
#include "../graph/SSSP.h"
#include "../auxiliary/Log.h"

#include <math.h>
#include <algorithm>
#include <memory>
#include <omp.h>

namespace NetworKit {

ApproxBetweenness::ApproxBetweenness(const Graph& G, double epsilon, double delta, count diameterSamples) : Centrality(G, true), epsilon(epsilon), delta(delta), diameterSamples(diameterSamples) {

}

void ApproxBetweenness::run() {
	scoreData.clear();
	scoreData.resize(G.upperNodeIdBound());

	double c = 0.5; // universal positive constant - see reference in paper

	edgeweight vd = 0;
	if (diameterSamples == 0) {
		INFO("estimating vertex diameter pedantically");
		vd = Diameter::estimatedVertexDiameterPedantic(G);
	} else {
		/**
		* This is an optimization which deviates from the original algorithm.
		* Instead of getting an estimate for each of possibly thousands of connected component and taking the maximum,
		* we sample the graph and take the maximum diameter found. This has a high chance of  hitting the component with the maximum vertex diameter.
		*/
		INFO("estimating vertex diameter roughly");
		vd = Diameter::estimatedVertexDiameter(G, diameterSamples);
	}

	INFO("estimated diameter: ", vd);
	r = ceil((c / (epsilon * epsilon)) * (floor(log(vd - 2)) + 1 + log(1 / delta)));

	INFO("taking ", r, " path samples");

	// parallelization:
	count maxThreads = omp_get_max_threads();
	DEBUG("max threads: ", maxThreads);
	std::vector<std::vector<double> > scorePerThread(maxThreads, std::vector<double>(G.upperNodeIdBound()));
	DEBUG("score per thread size: ", scorePerThread.size());

	#pragma omp parallel for
	for (count i = 1; i <= r; i++) {
		count thread = omp_get_thread_num();
		DEBUG("sample ", i);
		// if (i >= 1000) throw std::runtime_error("too many iterations");
		// DEBUG
		// sample random node pair
		node u, v;
		u = Sampling::randomNode(G);
		do {
			v = Sampling::randomNode(G);
		} while (v == u);

		// runs faster for unweighted graphs
		std::unique_ptr<SSSP> sssp;
		if (G.isWeighted()) {
			sssp.reset(new Dijkstra(G, u));
		} else {
			sssp.reset(new BFS(G, u));
		}
		DEBUG("running shortest path algorithm for node ", u);
		sssp->run(); // TODO: this can be optimized by stopping the search once the target node has been reached
		if (sssp->numberOfPaths(v) > 0) { // at least one path between {u, v} exists
			DEBUG("updating estimate for path ", u, " <-> ", v);
			// random path sampling and estimation update
			// node s = v;
			node t = v;
			while (t != u)  {
				// sample z in P_u(t) with probability sigma_uz / sigma_us
				std::vector<std::pair<node, double> > choices;

				for (node z : sssp->getPredecessors(t)) {
					choices.emplace_back(z, sssp->numberOfPaths(z) / (double) sssp->numberOfPaths(t)); 	// sigma_uz / sigma_us
				}
				node z = Aux::Random::weightedChoice(choices);
				assert (z <= G.upperNodeIdBound());
				if (z != u) {
					scorePerThread[thread][z] += 1 / (double) r;
				}
				// s = t;
				t = z;
			}
		}
	}

	INFO("adding thread-local scores");
	// add up all thread-local values
	for (auto local : scorePerThread) {
		G.parallelForNodes([&](node v){
			scoreData[v] += local[v];
		});
	}

}

count ApproxBetweenness::numberOfSamples() {
	return r;
}

} /* namespace NetworKit */
<commit_msg>made ApproxBetweenness faster using the BFS stop after it finds the target vertex<commit_after>/*
 * ApproxBetweenness.cpp
 *
 *  Created on: 09.04.2014
 *      Author: cls
 */

#include "ApproxBetweenness.h"
#include "../auxiliary/Random.h"
#include "../properties/Diameter.h"
#include "../graph/Sampling.h"
#include "../graph/Dijkstra.h"
#include "../graph/BFS.h"
#include "../graph/SSSP.h"
#include "../auxiliary/Log.h"

#include <math.h>
#include <algorithm>
#include <memory>
#include <omp.h>

namespace NetworKit {

ApproxBetweenness::ApproxBetweenness(const Graph& G, double epsilon, double delta, count diameterSamples) : Centrality(G, true), epsilon(epsilon), delta(delta), diameterSamples(diameterSamples) {

}

void ApproxBetweenness::run() {
	scoreData.clear();
	scoreData.resize(G.upperNodeIdBound());

	double c = 0.5; // universal positive constant - see reference in paper

	edgeweight vd = 0;
	if (diameterSamples == 0) {
		INFO("estimating vertex diameter pedantically");
		vd = Diameter::estimatedVertexDiameterPedantic(G);
	} else {
		/**
		* This is an optimization which deviates from the original algorithm.
		* Instead of getting an estimate for each of possibly thousands of connected component and taking the maximum,
		* we sample the graph and take the maximum diameter found. This has a high chance of  hitting the component with the maximum vertex diameter.
		*/
		INFO("estimating vertex diameter roughly");
		vd = Diameter::estimatedVertexDiameter(G, diameterSamples);
	}

	INFO("estimated diameter: ", vd);
	r = ceil((c / (epsilon * epsilon)) * (floor(log(vd - 2)) + 1 + log(1 / delta)));

	INFO("taking ", r, " path samples");

	// parallelization:
	count maxThreads = omp_get_max_threads();
	DEBUG("max threads: ", maxThreads);
	std::vector<std::vector<double> > scorePerThread(maxThreads, std::vector<double>(G.upperNodeIdBound()));
	DEBUG("score per thread size: ", scorePerThread.size());

	#pragma omp parallel for
	for (count i = 1; i <= r; i++) {
		count thread = omp_get_thread_num();
		DEBUG("sample ", i);
		// if (i >= 1000) throw std::runtime_error("too many iterations");
		// DEBUG
		// sample random node pair
		node u, v;
		u = Sampling::randomNode(G);
		do {
			v = Sampling::randomNode(G);
		} while (v == u);

		// runs faster for unweighted graphs
		std::unique_ptr<SSSP> sssp;
		if (G.isWeighted()) {
			sssp.reset(new Dijkstra(G, u));
		} else {
			sssp.reset(new BFS(G, u));
		}
		DEBUG("running shortest path algorithm for node ", u);
		sssp->run(v); // TODO: this can be optimized by stopping the search once the target node has been reached
		if (sssp->numberOfPaths(v) > 0) { // at least one path between {u, v} exists
			DEBUG("updating estimate for path ", u, " <-> ", v);
			// random path sampling and estimation update
			// node s = v;
			node t = v;
			while (t != u)  {
				// sample z in P_u(t) with probability sigma_uz / sigma_us
				std::vector<std::pair<node, double> > choices;

				for (node z : sssp->getPredecessors(t)) {
					choices.emplace_back(z, sssp->numberOfPaths(z) / (double) sssp->numberOfPaths(t)); 	// sigma_uz / sigma_us
				}
				node z = Aux::Random::weightedChoice(choices);
				assert (z <= G.upperNodeIdBound());
				if (z != u) {
					scorePerThread[thread][z] += 1 / (double) r;
				}
				// s = t;
				t = z;
			}
		}
	}

	INFO("adding thread-local scores");
	// add up all thread-local values
	for (auto local : scorePerThread) {
		G.parallelForNodes([&](node v){
			scoreData[v] += local[v];
		});
	}

}

count ApproxBetweenness::numberOfSamples() {
	return r;
}

} /* namespace NetworKit */
<|endoftext|>