<commit_before>#include "JWModules.hpp"
#include "dsp/digital.hpp"

struct SimpleClock : Module {
	enum ParamIds {
		CLOCK_PARAM,
		RUN_PARAM,
		PROB_PARAM,
		NUM_PARAMS
	};
	enum InputIds {
		NUM_INPUTS
	};
	enum OutputIds {
		GATES_OUTPUT,
		RESET_OUTPUT,
		NUM_OUTPUTS
	};

	bool running = true;
	bool rndReset = false;
	SchmittTrigger runningTrigger;
	float runningLight = 0.0;

	float phase = 0.0;
	PulseGenerator gatePulse;
	PulseGenerator resetPulse;

	SimpleClock() : Module(NUM_PARAMS, NUM_INPUTS, NUM_OUTPUTS) {}
	void step();

	json_t *toJson() {
		json_t *rootJ = json_object();
		json_object_set_new(rootJ, "running", json_boolean(running));
		return rootJ;
	}

	void fromJson(json_t *rootJ) {
		json_t *runningJ = json_object_get(rootJ, "running");
		if (runningJ)
			running = json_is_true(runningJ);
	}

	void initialize() {
	}

	void randomize() {
	}
};

void SimpleClock::step() {
	if (runningTrigger.process(params[RUN_PARAM].value)) {
		running = !running;
		if(running){
			resetPulse.trigger(0.01);
		}
	}
	runningLight = running ? 1.0 : 0.0;

	bool nextStep = false;
	if (running) {
		float clockTime = powf(2.0, params[CLOCK_PARAM].value);
		phase += clockTime / gSampleRate;
		if (phase >= 1.0) {
			phase -= 1.0;
			nextStep = true;
		}
	}

	if (nextStep) {
		float probScaled = rescalef(params[PROB_PARAM].value, -2, 6, 0, 1);
		if(randomf() < probScaled){
			resetPulse.trigger(0.01);
		}
		gatePulse.trigger(1e-3);
	}

	bool gpulse = gatePulse.process(1.0 / gSampleRate);
	bool rpulse = resetPulse.process(1.0 / gSampleRate);
	outputs[RESET_OUTPUT].value = running && rpulse ? 10.0 : 0.0;
	outputs[GATES_OUTPUT].value = running && gpulse ? 10.0 : 0.0;
}

SimpleClockWidget::SimpleClockWidget() {
	SimpleClock *module = new SimpleClock();
	setModule(module);
	box.size = Vec(15*4, 380);

	{
		SVGPanel *panel = new SVGPanel();
		panel->box.size = box.size;
		panel->setBackground(SVG::load(assetPlugin(plugin, "res/SimpleClock.svg")));
		addChild(panel);
	}

	addChild(createScrew<ScrewSilver>(Vec(15, 0)));
	addChild(createScrew<ScrewSilver>(Vec(box.size.x-30, 0)));
	addChild(createScrew<ScrewSilver>(Vec(15, 365)));
	addChild(createScrew<ScrewSilver>(Vec(box.size.x-30, 365)));

	addParam(createParam<Davies1900hSmallBlackKnob>(Vec(17, 40), module, SimpleClock::CLOCK_PARAM, -2.0, 6.0, 2.0));
	addOutput(createOutput<PJ301MPort>(Vec(18, 78), module, SimpleClock::GATES_OUTPUT));
	addParam(createParam<LEDButton>(Vec(21, 140), module, SimpleClock::RUN_PARAM, 0.0, 1.0, 0.0));
	addChild(createValueLight<SmallLight<MyBlueValueLight>>(Vec(26, 140+5), &module->runningLight));

	addOutput(createOutput<PJ301MPort>(Vec(18, 198), module, SimpleClock::RESET_OUTPUT));
	addParam(createParam<Davies1900hSmallBlackKnob>(Vec(16, 280), module, SimpleClock::PROB_PARAM, -2.0, 6.0, -2));
}
<commit_msg>looking into clock swing<commit_after>#include "JWModules.hpp"
#include "dsp/digital.hpp"

struct SimpleClock : Module {
	enum ParamIds {
		CLOCK_PARAM,
		RUN_PARAM,
		PROB_PARAM,
		NUM_PARAMS
	};
	enum InputIds {
		NUM_INPUTS
	};
	enum OutputIds {
		GATES_OUTPUT,
		RESET_OUTPUT,
		NUM_OUTPUTS
	};

	bool running = true;
	bool rndReset = false;
	SchmittTrigger runningTrigger;
	float runningLight = 0.0;
	int beat = 0;
	float phase = 0.0;
	PulseGenerator gatePulse;
	PulseGenerator resetPulse;

	SimpleClock() : Module(NUM_PARAMS, NUM_INPUTS, NUM_OUTPUTS) {}
	void step();

	json_t *toJson() {
		json_t *rootJ = json_object();
		json_object_set_new(rootJ, "running", json_boolean(running));
		return rootJ;
	}

	void fromJson(json_t *rootJ) {
		json_t *runningJ = json_object_get(rootJ, "running");
		if (runningJ)
			running = json_is_true(runningJ);
	}

	void initialize() {
	}

	void randomize() {
	}
};

/*
SWING - Roger Linn https://www.attackmagazine.com/features/interview/roger-linn-swing-groove-magic-mpc-timing/
"I merely delay the second 16th note within each 8th note. In other words, I delay all the even-numbered 16th notes
within the beat (2, 4, 6, 8, etc.) In my products I describe the swing amount in terms of the ratio of time duration
between the first and second 16th notes within each 8th note. For example, 50% is no swing, meaning that both 16th
notes within each 8th note are given equal timing. And 66% means perfect triplet swing, meaning that the first
16th note of each pair gets 2/3 of the time, and the second 16th note gets 1/3, so the second 16th note falls on
a perfect 8th note triplet. The fun comes in the in-between settings. For example, a 90 BPM swing groove will
feel looser at 62% than at a perfect swing setting of 66%. And for straight 16th-note beats (no swing), a swing
setting of 54% will loosen up the feel without it sounding like swing. Between 50% and around 70% are lots of
wonderful little settings that, for a particular beat and tempo, can change a rigid beat into something that makes people move."" */
void SimpleClock::step() {
	if (runningTrigger.process(params[RUN_PARAM].value)) {
		running = !running;
		if(running){
			resetPulse.trigger(0.01);
		}
	}
	runningLight = running ? 1.0 : 0.0;

	bool nextStep = false;
	if (running) {
		float clockTime = powf(2.0, params[CLOCK_PARAM].value);
		phase += clockTime / gSampleRate;
		// printf("clockTime:%f phase:%f\n", clockTime, phase);
		if (phase >= 1.0) {
			phase -= 1.0;
			nextStep = true;
		}
	}
	if (nextStep) {
		float probScaled = rescalef(params[PROB_PARAM].value, -2, 6, 0, 1);
		if(randomf() < probScaled){
			resetPulse.trigger(0.01);
		}
		gatePulse.trigger(1e-3);

		beat = (beat + 1) % 16;//in music the first beat is one so increment before
		// if(beat%2 == 0){
		// 	printf("even beat %i, %f\n", beat, phase);
		// } else {
		// 	printf("odd beat %i, %f\n", beat, phase);

		// }
	}

	bool gpulse = gatePulse.process(1.0 / gSampleRate);
	bool rpulse = resetPulse.process(1.0 / gSampleRate);
	outputs[RESET_OUTPUT].value = running && rpulse ? 10.0 : 0.0;
	outputs[GATES_OUTPUT].value = running && gpulse ? 10.0 : 0.0;
}

SimpleClockWidget::SimpleClockWidget() {
	SimpleClock *module = new SimpleClock();
	setModule(module);
	box.size = Vec(15*4, 380);

	{
		SVGPanel *panel = new SVGPanel();
		panel->box.size = box.size;
		panel->setBackground(SVG::load(assetPlugin(plugin, "res/SimpleClock.svg")));
		addChild(panel);
	}

	addChild(createScrew<ScrewSilver>(Vec(15, 0)));
	addChild(createScrew<ScrewSilver>(Vec(box.size.x-30, 0)));
	addChild(createScrew<ScrewSilver>(Vec(15, 365)));
	addChild(createScrew<ScrewSilver>(Vec(box.size.x-30, 365)));

	addParam(createParam<Davies1900hSmallBlackKnob>(Vec(17, 40), module, SimpleClock::CLOCK_PARAM, -2.0, 6.0, 2.0));
	addOutput(createOutput<PJ301MPort>(Vec(18, 78), module, SimpleClock::GATES_OUTPUT));
	addParam(createParam<LEDButton>(Vec(21, 140), module, SimpleClock::RUN_PARAM, 0.0, 1.0, 0.0));
	addChild(createValueLight<SmallLight<MyBlueValueLight>>(Vec(26, 140+5), &module->runningLight));

	addOutput(createOutput<PJ301MPort>(Vec(18, 198), module, SimpleClock::RESET_OUTPUT));
	addParam(createParam<Davies1900hSmallBlackKnob>(Vec(16, 280), module, SimpleClock::PROB_PARAM, -2.0, 6.0, -2));
}
<|endoftext|>


<commit_before>#include <stdint.h>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iostream>
#include <algorithm>
#include <vector>
#include <memory>
#include <systemd/sd-bus.h>
#include <mapper.h>
#include <elog.hpp>
#include <elog-errors-HostEvent.hpp>
#include "host-ipmid/ipmid-api.h"
#include "sensorhandler.h"
#include "storagehandler.h"

using namespace std;
using namespace phosphor::logging;

//////////////////////////
struct esel_section_headers_t {
	uint8_t sectionid[2];
	uint8_t sectionlength[2];
	uint8_t version;
	uint8_t subsectiontype;
	uint8_t compid;
};

struct severity_values_t {
	uint8_t type;
	const char *description;
};

const std::vector<severity_values_t> g_sev_desc = {
	{0x10, "recoverable error"},
	{0x20, "predictive error"},
	{0x40, "unrecoverable error"},
	{0x50, "critical error"},
	{0x60, "error from a diagnostic test"},
	{0x70, "recovered symptom "},
	{0xFF, "Unknown"},
};

const char* sev_lookup(uint8_t n) {
	auto i = std::find_if(std::begin(g_sev_desc), std::end(g_sev_desc),
	                      [n](auto p){ return p.type == n || p.type == 0xFF; });
	return i->description;
}

int find_sensor_type_string(uint8_t sensor_number, char **s) {

	dbus_interface_t a;
	const char *p;
	int r;

	r = find_openbmc_path("SENSOR", sensor_number, &a);

	if ((r < 0) || (a.bus[0] == 0)) {
		// Just make a generic message for errors that
		// occur on sensors that dont exist
		r = asprintf(s, "Unknown Sensor (0x%02x)", sensor_number);
	} else {

		if ((p = strrchr (a.path, '/')) == NULL) {
			p = "/Unknown Sensor";
		}

		*s = strdup(p+1);
	}

	return 0;
}

size_t getfilestream(const char *fn, uint8_t **buffer) {

	FILE *fp;
	ssize_t size = 0;
	int r;

	if ((fp = fopen(fn, "rb")) != NULL) {

		r = fseek(fp, 0, SEEK_END);
		if (r) {
			fprintf(stderr,"Fseek failed\n");
			goto fclose_fp;
		}

		size = ftell(fp);
		if (size == -1L) {
			fprintf(stderr,"Ftell failed for %s\n", strerror(errno));
			size = 0;
			goto fclose_fp;
		}

		r = fseek(fp, 0, SEEK_SET);
		if (r) {
			fprintf(stderr,"Fseek failed\n");
			size = 0;
			goto fclose_fp;
		}

		*buffer = new uint8_t [size];

		r = fread(*buffer, 1, size, fp);
		if ( r != size) {
			size = 0;
			fprintf(stderr,"Fread failed\n");
		}

fclose_fp:
		fclose(fp);
	}

	return static_cast<size_t>(size);
}

const char *create_esel_severity(const uint8_t *buffer) {

	uint8_t severity;
	// Dive in to the IBM log to find the severity
	severity = (0xF0  & buffer[0x4A]);

	return sev_lookup(severity);
}

int create_esel_association(const uint8_t *buffer, char **m) {

	ipmi_add_sel_request_t *p;
	dbus_interface_t dbusint;
	uint8_t sensor;

	p = ( ipmi_add_sel_request_t *) buffer;

	sensor = p->sensornumber;

	find_openbmc_path("SENSOR", sensor, &dbusint);

	// Simply no associations if the sensor can not be found
	if (strlen(dbusint.path) < 1) {
		printf("Sensor 0x%x not found\n", sensor);
		memset(dbusint.path,0,sizeof(dbusint.path));
	}

	*m = strdup(dbusint.path);

	return 0;
}

int create_esel_description(const uint8_t *buffer, const char *sev, char **message) {

	ipmi_add_sel_request_t *p;
	char *m;
	int r;

	p =  ( ipmi_add_sel_request_t *) buffer;

	find_sensor_type_string(p->sensornumber,&m);

	r = asprintf(message, "A %s has experienced a %s", m, sev );
	if (r == -1) {
		fprintf(stderr,
			"Failed to allocate memory for ESEL description\n");
	}

	free(m);

	return 0;
}

int send_esel_to_dbus(const char *desc, const char *sev, const char *details, uint8_t *debug, size_t debuglen) {

    // Allocate enough space to represent the data in hex separated by spaces,
    // to mimic how IPMI would display the data.
    unique_ptr<char[]> selData(new char[debuglen*3]());
    uint32_t i = 0;
    for(i = 0; i < debuglen; i++)
    {
        sprintf(&selData[i*3], "%02x ", 0xFF & ((char*)debug)[i]);
    }
    log<level::INFO>("Received Host Event", entry("ESEL=%s", selData.get()));

    try
    {
        elog<org::open_power::Error::Host::Event>(
            prev_entry<org::open_power::Error::Host::Event::ESEL>());
    }
    catch (elogException<org::open_power::Error::Host::Event>& e)
    {
        commit(e.name());
    }

    return 0;
}

void send_esel(uint16_t recordid) {
	char *desc, *assoc;
	const char *sev;
	uint8_t *buffer = NULL;
	const char *path = "/tmp/esel";
	ssize_t sz;
	int r;

	sz = getfilestream(path, &buffer);
	if (sz == 0) {
		printf("Error file does not exist %d\n",__LINE__);
		return;
	}

	sev = create_esel_severity(buffer);
	create_esel_association(buffer, &assoc);
	create_esel_description(buffer, sev, &desc);

	r = send_esel_to_dbus(desc, sev, assoc, buffer, sz);
	if (r < 0) {
		fprintf(stderr, "Failed to send esel to dbus\n");
	}

	free(assoc);
	free(desc);
	delete[] buffer;

	return;
}
<commit_msg>Import phosphor-logging header files from new directory.<commit_after>#include <stdint.h>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iostream>
#include <algorithm>
#include <vector>
#include <memory>
#include <systemd/sd-bus.h>
#include <mapper.h>
#include <phosphor-logging/elog.hpp>
#include <phosphor-logging/elog-errors-HostEvent.hpp>
#include "host-ipmid/ipmid-api.h"
#include "sensorhandler.h"
#include "storagehandler.h"

using namespace std;
using namespace phosphor::logging;

//////////////////////////
struct esel_section_headers_t {
	uint8_t sectionid[2];
	uint8_t sectionlength[2];
	uint8_t version;
	uint8_t subsectiontype;
	uint8_t compid;
};

struct severity_values_t {
	uint8_t type;
	const char *description;
};

const std::vector<severity_values_t> g_sev_desc = {
	{0x10, "recoverable error"},
	{0x20, "predictive error"},
	{0x40, "unrecoverable error"},
	{0x50, "critical error"},
	{0x60, "error from a diagnostic test"},
	{0x70, "recovered symptom "},
	{0xFF, "Unknown"},
};

const char* sev_lookup(uint8_t n) {
	auto i = std::find_if(std::begin(g_sev_desc), std::end(g_sev_desc),
	                      [n](auto p){ return p.type == n || p.type == 0xFF; });
	return i->description;
}

int find_sensor_type_string(uint8_t sensor_number, char **s) {

	dbus_interface_t a;
	const char *p;
	int r;

	r = find_openbmc_path("SENSOR", sensor_number, &a);

	if ((r < 0) || (a.bus[0] == 0)) {
		// Just make a generic message for errors that
		// occur on sensors that dont exist
		r = asprintf(s, "Unknown Sensor (0x%02x)", sensor_number);
	} else {

		if ((p = strrchr (a.path, '/')) == NULL) {
			p = "/Unknown Sensor";
		}

		*s = strdup(p+1);
	}

	return 0;
}

size_t getfilestream(const char *fn, uint8_t **buffer) {

	FILE *fp;
	ssize_t size = 0;
	int r;

	if ((fp = fopen(fn, "rb")) != NULL) {

		r = fseek(fp, 0, SEEK_END);
		if (r) {
			fprintf(stderr,"Fseek failed\n");
			goto fclose_fp;
		}

		size = ftell(fp);
		if (size == -1L) {
			fprintf(stderr,"Ftell failed for %s\n", strerror(errno));
			size = 0;
			goto fclose_fp;
		}

		r = fseek(fp, 0, SEEK_SET);
		if (r) {
			fprintf(stderr,"Fseek failed\n");
			size = 0;
			goto fclose_fp;
		}

		*buffer = new uint8_t [size];

		r = fread(*buffer, 1, size, fp);
		if ( r != size) {
			size = 0;
			fprintf(stderr,"Fread failed\n");
		}

fclose_fp:
		fclose(fp);
	}

	return static_cast<size_t>(size);
}

const char *create_esel_severity(const uint8_t *buffer) {

	uint8_t severity;
	// Dive in to the IBM log to find the severity
	severity = (0xF0  & buffer[0x4A]);

	return sev_lookup(severity);
}

int create_esel_association(const uint8_t *buffer, char **m) {

	ipmi_add_sel_request_t *p;
	dbus_interface_t dbusint;
	uint8_t sensor;

	p = ( ipmi_add_sel_request_t *) buffer;

	sensor = p->sensornumber;

	find_openbmc_path("SENSOR", sensor, &dbusint);

	// Simply no associations if the sensor can not be found
	if (strlen(dbusint.path) < 1) {
		printf("Sensor 0x%x not found\n", sensor);
		memset(dbusint.path,0,sizeof(dbusint.path));
	}

	*m = strdup(dbusint.path);

	return 0;
}

int create_esel_description(const uint8_t *buffer, const char *sev, char **message) {

	ipmi_add_sel_request_t *p;
	char *m;
	int r;

	p =  ( ipmi_add_sel_request_t *) buffer;

	find_sensor_type_string(p->sensornumber,&m);

	r = asprintf(message, "A %s has experienced a %s", m, sev );
	if (r == -1) {
		fprintf(stderr,
			"Failed to allocate memory for ESEL description\n");
	}

	free(m);

	return 0;
}

int send_esel_to_dbus(const char *desc, const char *sev, const char *details, uint8_t *debug, size_t debuglen) {

    // Allocate enough space to represent the data in hex separated by spaces,
    // to mimic how IPMI would display the data.
    unique_ptr<char[]> selData(new char[debuglen*3]());
    uint32_t i = 0;
    for(i = 0; i < debuglen; i++)
    {
        sprintf(&selData[i*3], "%02x ", 0xFF & ((char*)debug)[i]);
    }
    log<level::INFO>("Received Host Event", entry("ESEL=%s", selData.get()));

    try
    {
        elog<org::open_power::Error::Host::Event>(
            prev_entry<org::open_power::Error::Host::Event::ESEL>());
    }
    catch (elogException<org::open_power::Error::Host::Event>& e)
    {
        commit(e.name());
    }

    return 0;
}

void send_esel(uint16_t recordid) {
	char *desc, *assoc;
	const char *sev;
	uint8_t *buffer = NULL;
	const char *path = "/tmp/esel";
	ssize_t sz;
	int r;

	sz = getfilestream(path, &buffer);
	if (sz == 0) {
		printf("Error file does not exist %d\n",__LINE__);
		return;
	}

	sev = create_esel_severity(buffer);
	create_esel_association(buffer, &assoc);
	create_esel_description(buffer, sev, &desc);

	r = send_esel_to_dbus(desc, sev, assoc, buffer, sz);
	if (r < 0) {
		fprintf(stderr, "Failed to send esel to dbus\n");
	}

	free(assoc);
	free(desc);
	delete[] buffer;

	return;
}
<|endoftext|>


<commit_before>/****************************************************************************
*
*   Copyright (c) 2012-2015 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
*    notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
*    notice, this list of conditions and the following disclaimer in
*    the documentation and/or other materials provided with the
*    distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
*    used to endorse or promote products derived from this software
*    without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/

/**
* @file PreflightCheck.cpp
*
* Preflight check for main system components
*
* @author Lorenz Meier <lorenz@px4.io>
* @author Johan Jansen <jnsn.johan@gmail.com>
*/

#include <nuttx/config.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
#include <math.h>
#include <poll.h>

#include <systemlib/err.h>
#include <systemlib/param/param.h>
#include <systemlib/rc_check.h>

#include <drivers/drv_hrt.h>
#include <drivers/drv_mag.h>
#include <drivers/drv_gyro.h>
#include <drivers/drv_accel.h>
#include <drivers/drv_baro.h>
#include <drivers/drv_airspeed.h>

#include <uORB/topics/airspeed.h>
#include <uORB/topics/vehicle_gps_position.h>

#include <mavlink/mavlink_log.h>

#include "PreflightCheck.h"

namespace Commander
{
static bool magnometerCheck(int mavlink_fd, unsigned instance, bool optional)
{
	bool success = true;

	char s[30];
	sprintf(s, "%s%u", MAG_BASE_DEVICE_PATH, instance);
	int fd = open(s, 0);

	if (fd < 0) {
		if (!optional) {
			mavlink_and_console_log_critical(mavlink_fd,
							 "PREFLIGHT FAIL: NO MAG SENSOR #%u", instance);
		}

		return false;
	}

	int calibration_devid;
	int ret;
	int devid = ioctl(fd, DEVIOCGDEVICEID, 0);
	sprintf(s, "CAL_MAG%u_ID", instance);
	param_get(param_find(s), &(calibration_devid));

	if (devid != calibration_devid) {
		mavlink_and_console_log_critical(mavlink_fd,
						 "PREFLIGHT FAIL: MAG #%u UNCALIBRATED", instance);
		success = false;
		goto out;
	}

	ret = ioctl(fd, MAGIOCSELFTEST, 0);

	if (ret != OK) {
		mavlink_and_console_log_critical(mavlink_fd,
						 "PREFLIGHT FAIL: MAG #%u SELFTEST FAILED", instance);
		success = false;
		goto out;
	}

out:
	close(fd);
	return success;
}

static bool accelerometerCheck(int mavlink_fd, unsigned instance, bool optional, bool dynamic)
{
	bool success = true;

	char s[30];
	sprintf(s, "%s%u", ACCEL_BASE_DEVICE_PATH, instance);
	int fd = open(s, O_RDONLY);

	if (fd < 0) {
		if (!optional) {
			mavlink_and_console_log_critical(mavlink_fd,
							 "PREFLIGHT FAIL: NO ACCEL SENSOR #%u", instance);
		}

		return false;
	}

	int calibration_devid;
	int ret;
	int devid = ioctl(fd, DEVIOCGDEVICEID, 0);
	sprintf(s, "CAL_ACC%u_ID", instance);
	param_get(param_find(s), &(calibration_devid));

	if (devid != calibration_devid) {
		mavlink_and_console_log_critical(mavlink_fd,
						 "PREFLIGHT FAIL: ACCEL #%u UNCALIBRATED", instance);
		success = false;
		goto out;
	}

	ret = ioctl(fd, ACCELIOCSELFTEST, 0);

	if (ret != OK) {
		mavlink_and_console_log_critical(mavlink_fd,
						 "PREFLIGHT FAIL: ACCEL #%u SELFTEST FAILED", instance);
		success = false;
		goto out;
	}

	if (dynamic) {
		/* check measurement result range */
		struct accel_report acc;
		ret = read(fd, &acc, sizeof(acc));

		if (ret == sizeof(acc)) {
			/* evaluate values */
			float accel_magnitude = sqrtf(acc.x * acc.x + acc.y * acc.y + acc.z * acc.z);

			if (accel_magnitude < 4.0f || accel_magnitude > 15.0f /* m/s^2 */) {
				mavlink_and_console_log_critical(mavlink_fd, "PREFLIGHT FAIL: ACCEL RANGE, hold still on arming");
				/* this is frickin' fatal */
				success = false;
				goto out;
			}
		} else {
			mavlink_log_critical(mavlink_fd, "PREFLIGHT FAIL: ACCEL READ");
			/* this is frickin' fatal */
			success = false;
			goto out;
		}
	}

out:
	close(fd);
	return success;
}

static bool gyroCheck(int mavlink_fd, unsigned instance, bool optional)
{
	bool success = true;

	char s[30];
	sprintf(s, "%s%u", GYRO_BASE_DEVICE_PATH, instance);
	int fd = open(s, 0);

	if (fd < 0) {
		if (!optional) {
			mavlink_and_console_log_critical(mavlink_fd,
							 "PREFLIGHT FAIL: NO GYRO SENSOR #%u", instance);
		}

		return false;
	}

	int calibration_devid;
	int ret;
	int devid = ioctl(fd, DEVIOCGDEVICEID, 0);
	sprintf(s, "CAL_GYRO%u_ID", instance);
	param_get(param_find(s), &(calibration_devid));

	if (devid != calibration_devid) {
		mavlink_and_console_log_critical(mavlink_fd,
						 "PREFLIGHT FAIL: GYRO #%u UNCALIBRATED", instance);
		success = false;
		goto out;
	}

	ret = ioctl(fd, GYROIOCSELFTEST, 0);

	if (ret != OK) {
		mavlink_and_console_log_critical(mavlink_fd,
						 "PREFLIGHT FAIL: GYRO #%u SELFTEST FAILED", instance);
		success = false;
		goto out;
	}

out:
	close(fd);
	return success;
}

static bool baroCheck(int mavlink_fd, unsigned instance, bool optional)
{
	bool success = true;

	char s[30];
	sprintf(s, "%s%u", BARO_BASE_DEVICE_PATH, instance);
	int fd = open(s, 0);

	if (fd < 0) {
		if (!optional) {
			mavlink_and_console_log_critical(mavlink_fd,
							 "PREFLIGHT FAIL: NO BARO SENSOR #%u", instance);
		}

		return false;
	}

	close(fd);
	return success;
}

static bool airspeedCheck(int mavlink_fd, bool optional)
{
	bool success = true;
	int ret;
	int fd = orb_subscribe(ORB_ID(airspeed));

	struct airspeed_s airspeed;

	if ((ret = orb_copy(ORB_ID(airspeed), fd, &airspeed)) ||
	    (hrt_elapsed_time(&airspeed.timestamp) > (500 * 1000))) {
		mavlink_and_console_log_critical(mavlink_fd, "PREFLIGHT FAIL: AIRSPEED SENSOR MISSING");
		success = false;
		goto out;
	}

	if (fabsf(airspeed.indicated_airspeed_m_s > 6.0f)) {
		mavlink_and_console_log_critical(mavlink_fd, "AIRSPEED WARNING: WIND OR CALIBRATION ISSUE");
		// XXX do not make this fatal yet
	}

out:
	close(fd);
	return success;
}

static bool gnssCheck(int mavlink_fd)
{
	bool success = true;

	int gpsSub = orb_subscribe(ORB_ID(vehicle_gps_position));

	//Wait up to 1000ms to allow the driver to detect a GNSS receiver module
	struct pollfd fds[1];
	fds[0].fd = gpsSub;
	fds[0].events = POLLIN;
	if(poll(fds, 1, 4000) <= 0) {
		success = false;
	}
	else {
		struct vehicle_gps_position_s gps;
		if ( (OK != orb_copy(ORB_ID(vehicle_gps_position), gpsSub, &gps)) ||
		    (hrt_elapsed_time(&gps.timestamp_position) > 1000000)) {
			success = false;
		}
	}

	//Report failure to detect module
	if(!success) {
		mavlink_and_console_log_critical(mavlink_fd, "PREFLIGHT FAIL: GPS RECEIVER MISSING");
	}

	close(gpsSub);
	return success;
}

bool preflightCheck(int mavlink_fd, bool checkMag, bool checkAcc, bool checkGyro,
		    bool checkBaro, bool checkAirspeed, bool checkRC, bool checkGNSS, bool checkDynamic)
{
	bool failed = false;

	/* ---- MAG ---- */
	if (checkMag) {
		/* check all sensors, but fail only for mandatory ones */
		for (unsigned i = 0; i < max_optional_mag_count; i++) {
			bool required = (i < max_mandatory_mag_count);

			if (!magnometerCheck(mavlink_fd, i, !required) && required) {
				failed = true;
			}
		}
	}

	/* ---- ACCEL ---- */
	if (checkAcc) {
		/* check all sensors, but fail only for mandatory ones */
		for (unsigned i = 0; i < max_optional_accel_count; i++) {
			bool required = (i < max_mandatory_accel_count);

			if (!accelerometerCheck(mavlink_fd, i, !required, checkDynamic) && required) {
				failed = true;
			}
		}
	}

	/* ---- GYRO ---- */
	if (checkGyro) {
		/* check all sensors, but fail only for mandatory ones */
		for (unsigned i = 0; i < max_optional_gyro_count; i++) {
			bool required = (i < max_mandatory_gyro_count);

			if (!gyroCheck(mavlink_fd, i, !required) && required) {
				failed = true;
			}
		}
	}

	/* ---- BARO ---- */
	if (checkBaro) {
		/* check all sensors, but fail only for mandatory ones */
		for (unsigned i = 0; i < max_optional_baro_count; i++) {
			bool required = (i < max_mandatory_baro_count);

			if (!baroCheck(mavlink_fd, i, !required) && required) {
				failed = true;
			}
		}
	}

	/* ---- AIRSPEED ---- */
	if (checkAirspeed) {
		if (!airspeedCheck(mavlink_fd, true)) {
			failed = true;
		}
	}

	/* ---- RC CALIBRATION ---- */
	if (checkRC) {
		if (rc_calibration_check(mavlink_fd) != OK) {
			failed = true;
		}
	}

	/* ---- Global Navigation Satellite System receiver ---- */
	if(checkGNSS) {
		if(!gnssCheck(mavlink_fd)) {
			failed = true;
		}
	}

	/* Report status */
	return !failed;
}

}
<commit_msg>PreflightCheck: Reduce GPS timeout to 2 sec<commit_after>/****************************************************************************
*
*   Copyright (c) 2012-2015 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
*    notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
*    notice, this list of conditions and the following disclaimer in
*    the documentation and/or other materials provided with the
*    distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
*    used to endorse or promote products derived from this software
*    without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/

/**
* @file PreflightCheck.cpp
*
* Preflight check for main system components
*
* @author Lorenz Meier <lorenz@px4.io>
* @author Johan Jansen <jnsn.johan@gmail.com>
*/

#include <nuttx/config.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
#include <math.h>
#include <poll.h>

#include <systemlib/err.h>
#include <systemlib/param/param.h>
#include <systemlib/rc_check.h>

#include <drivers/drv_hrt.h>
#include <drivers/drv_mag.h>
#include <drivers/drv_gyro.h>
#include <drivers/drv_accel.h>
#include <drivers/drv_baro.h>
#include <drivers/drv_airspeed.h>

#include <uORB/topics/airspeed.h>
#include <uORB/topics/vehicle_gps_position.h>

#include <mavlink/mavlink_log.h>

#include "PreflightCheck.h"

namespace Commander
{
static bool magnometerCheck(int mavlink_fd, unsigned instance, bool optional)
{
	bool success = true;

	char s[30];
	sprintf(s, "%s%u", MAG_BASE_DEVICE_PATH, instance);
	int fd = open(s, 0);

	if (fd < 0) {
		if (!optional) {
			mavlink_and_console_log_critical(mavlink_fd,
							 "PREFLIGHT FAIL: NO MAG SENSOR #%u", instance);
		}

		return false;
	}

	int calibration_devid;
	int ret;
	int devid = ioctl(fd, DEVIOCGDEVICEID, 0);
	sprintf(s, "CAL_MAG%u_ID", instance);
	param_get(param_find(s), &(calibration_devid));

	if (devid != calibration_devid) {
		mavlink_and_console_log_critical(mavlink_fd,
						 "PREFLIGHT FAIL: MAG #%u UNCALIBRATED", instance);
		success = false;
		goto out;
	}

	ret = ioctl(fd, MAGIOCSELFTEST, 0);

	if (ret != OK) {
		mavlink_and_console_log_critical(mavlink_fd,
						 "PREFLIGHT FAIL: MAG #%u SELFTEST FAILED", instance);
		success = false;
		goto out;
	}

out:
	close(fd);
	return success;
}

static bool accelerometerCheck(int mavlink_fd, unsigned instance, bool optional, bool dynamic)
{
	bool success = true;

	char s[30];
	sprintf(s, "%s%u", ACCEL_BASE_DEVICE_PATH, instance);
	int fd = open(s, O_RDONLY);

	if (fd < 0) {
		if (!optional) {
			mavlink_and_console_log_critical(mavlink_fd,
							 "PREFLIGHT FAIL: NO ACCEL SENSOR #%u", instance);
		}

		return false;
	}

	int calibration_devid;
	int ret;
	int devid = ioctl(fd, DEVIOCGDEVICEID, 0);
	sprintf(s, "CAL_ACC%u_ID", instance);
	param_get(param_find(s), &(calibration_devid));

	if (devid != calibration_devid) {
		mavlink_and_console_log_critical(mavlink_fd,
						 "PREFLIGHT FAIL: ACCEL #%u UNCALIBRATED", instance);
		success = false;
		goto out;
	}

	ret = ioctl(fd, ACCELIOCSELFTEST, 0);

	if (ret != OK) {
		mavlink_and_console_log_critical(mavlink_fd,
						 "PREFLIGHT FAIL: ACCEL #%u SELFTEST FAILED", instance);
		success = false;
		goto out;
	}

	if (dynamic) {
		/* check measurement result range */
		struct accel_report acc;
		ret = read(fd, &acc, sizeof(acc));

		if (ret == sizeof(acc)) {
			/* evaluate values */
			float accel_magnitude = sqrtf(acc.x * acc.x + acc.y * acc.y + acc.z * acc.z);

			if (accel_magnitude < 4.0f || accel_magnitude > 15.0f /* m/s^2 */) {
				mavlink_and_console_log_critical(mavlink_fd, "PREFLIGHT FAIL: ACCEL RANGE, hold still on arming");
				/* this is frickin' fatal */
				success = false;
				goto out;
			}
		} else {
			mavlink_log_critical(mavlink_fd, "PREFLIGHT FAIL: ACCEL READ");
			/* this is frickin' fatal */
			success = false;
			goto out;
		}
	}

out:
	close(fd);
	return success;
}

static bool gyroCheck(int mavlink_fd, unsigned instance, bool optional)
{
	bool success = true;

	char s[30];
	sprintf(s, "%s%u", GYRO_BASE_DEVICE_PATH, instance);
	int fd = open(s, 0);

	if (fd < 0) {
		if (!optional) {
			mavlink_and_console_log_critical(mavlink_fd,
							 "PREFLIGHT FAIL: NO GYRO SENSOR #%u", instance);
		}

		return false;
	}

	int calibration_devid;
	int ret;
	int devid = ioctl(fd, DEVIOCGDEVICEID, 0);
	sprintf(s, "CAL_GYRO%u_ID", instance);
	param_get(param_find(s), &(calibration_devid));

	if (devid != calibration_devid) {
		mavlink_and_console_log_critical(mavlink_fd,
						 "PREFLIGHT FAIL: GYRO #%u UNCALIBRATED", instance);
		success = false;
		goto out;
	}

	ret = ioctl(fd, GYROIOCSELFTEST, 0);

	if (ret != OK) {
		mavlink_and_console_log_critical(mavlink_fd,
						 "PREFLIGHT FAIL: GYRO #%u SELFTEST FAILED", instance);
		success = false;
		goto out;
	}

out:
	close(fd);
	return success;
}

static bool baroCheck(int mavlink_fd, unsigned instance, bool optional)
{
	bool success = true;

	char s[30];
	sprintf(s, "%s%u", BARO_BASE_DEVICE_PATH, instance);
	int fd = open(s, 0);

	if (fd < 0) {
		if (!optional) {
			mavlink_and_console_log_critical(mavlink_fd,
							 "PREFLIGHT FAIL: NO BARO SENSOR #%u", instance);
		}

		return false;
	}

	close(fd);
	return success;
}

static bool airspeedCheck(int mavlink_fd, bool optional)
{
	bool success = true;
	int ret;
	int fd = orb_subscribe(ORB_ID(airspeed));

	struct airspeed_s airspeed;

	if ((ret = orb_copy(ORB_ID(airspeed), fd, &airspeed)) ||
	    (hrt_elapsed_time(&airspeed.timestamp) > (500 * 1000))) {
		mavlink_and_console_log_critical(mavlink_fd, "PREFLIGHT FAIL: AIRSPEED SENSOR MISSING");
		success = false;
		goto out;
	}

	if (fabsf(airspeed.indicated_airspeed_m_s > 6.0f)) {
		mavlink_and_console_log_critical(mavlink_fd, "AIRSPEED WARNING: WIND OR CALIBRATION ISSUE");
		// XXX do not make this fatal yet
	}

out:
	close(fd);
	return success;
}

static bool gnssCheck(int mavlink_fd)
{
	bool success = true;

	int gpsSub = orb_subscribe(ORB_ID(vehicle_gps_position));

	//Wait up to 2000ms to allow the driver to detect a GNSS receiver module
	struct pollfd fds[1];
	fds[0].fd = gpsSub;
	fds[0].events = POLLIN;
	if(poll(fds, 1, 2000) <= 0) {
		success = false;
	}
	else {
		struct vehicle_gps_position_s gps;
		if ( (OK != orb_copy(ORB_ID(vehicle_gps_position), gpsSub, &gps)) ||
		    (hrt_elapsed_time(&gps.timestamp_position) > 1000000)) {
			success = false;
		}
	}

	//Report failure to detect module
	if(!success) {
		mavlink_and_console_log_critical(mavlink_fd, "PREFLIGHT FAIL: GPS RECEIVER MISSING");
	}

	close(gpsSub);
	return success;
}

bool preflightCheck(int mavlink_fd, bool checkMag, bool checkAcc, bool checkGyro,
		    bool checkBaro, bool checkAirspeed, bool checkRC, bool checkGNSS, bool checkDynamic)
{
	bool failed = false;

	/* ---- MAG ---- */
	if (checkMag) {
		/* check all sensors, but fail only for mandatory ones */
		for (unsigned i = 0; i < max_optional_mag_count; i++) {
			bool required = (i < max_mandatory_mag_count);

			if (!magnometerCheck(mavlink_fd, i, !required) && required) {
				failed = true;
			}
		}
	}

	/* ---- ACCEL ---- */
	if (checkAcc) {
		/* check all sensors, but fail only for mandatory ones */
		for (unsigned i = 0; i < max_optional_accel_count; i++) {
			bool required = (i < max_mandatory_accel_count);

			if (!accelerometerCheck(mavlink_fd, i, !required, checkDynamic) && required) {
				failed = true;
			}
		}
	}

	/* ---- GYRO ---- */
	if (checkGyro) {
		/* check all sensors, but fail only for mandatory ones */
		for (unsigned i = 0; i < max_optional_gyro_count; i++) {
			bool required = (i < max_mandatory_gyro_count);

			if (!gyroCheck(mavlink_fd, i, !required) && required) {
				failed = true;
			}
		}
	}

	/* ---- BARO ---- */
	if (checkBaro) {
		/* check all sensors, but fail only for mandatory ones */
		for (unsigned i = 0; i < max_optional_baro_count; i++) {
			bool required = (i < max_mandatory_baro_count);

			if (!baroCheck(mavlink_fd, i, !required) && required) {
				failed = true;
			}
		}
	}

	/* ---- AIRSPEED ---- */
	if (checkAirspeed) {
		if (!airspeedCheck(mavlink_fd, true)) {
			failed = true;
		}
	}

	/* ---- RC CALIBRATION ---- */
	if (checkRC) {
		if (rc_calibration_check(mavlink_fd) != OK) {
			failed = true;
		}
	}

	/* ---- Global Navigation Satellite System receiver ---- */
	if(checkGNSS) {
		if(!gnssCheck(mavlink_fd)) {
			failed = true;
		}
	}

	/* Report status */
	return !failed;
}

}
<|endoftext|>


<commit_before>// Copyright (c) 2010 Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

// Original author: Jim Blandy <jimb@mozilla.com> <jimb@red-bean.com>

// language.cc: Subclasses and singletons for google_breakpad::Language.
// See language.h for details.

#include "common/language.h"

namespace google_breakpad {

// C++ language-specific operations.
class CPPLanguage: public Language {
 public:
  CPPLanguage() {}
  string MakeQualifiedName(const string &parent_name,
                           const string &name) const {
    if (parent_name.empty())
      return name;
    else
      return parent_name + "::" + name;
  }
};

const CPPLanguage CPPLanguageSingleton;

// Java language-specific operations.
class JavaLanguage: public Language {
 public:
  string MakeQualifiedName(const string &parent_name,
                           const string &name) const {
    if (parent_name.empty())
      return name;
    else
      return parent_name + "." + name;
  }
};

JavaLanguage JavaLanguageSingleton;

// Assembler language-specific operations.
class AssemblerLanguage: public Language {
  bool HasFunctions() const { return false; }
  string MakeQualifiedName(const string &parent_name,
                           const string &name) const {
    return name;
  }
};

AssemblerLanguage AssemblerLanguageSingleton;

const Language * const Language::CPlusPlus = &CPPLanguageSingleton;
const Language * const Language::Java = &JavaLanguageSingleton;
const Language * const Language::Assembler = &AssemblerLanguageSingleton;

} // namespace google_breakpad
<commit_msg>Upstream fix for compiling of breakpad with gcc-4.6.  Remove an unnecessary "const" that causes an error with the newer gcc.<commit_after>// Copyright (c) 2010 Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

// Original author: Jim Blandy <jimb@mozilla.com> <jimb@red-bean.com>

// language.cc: Subclasses and singletons for google_breakpad::Language.
// See language.h for details.

#include "common/language.h"

namespace google_breakpad {

// C++ language-specific operations.
class CPPLanguage: public Language {
 public:
  CPPLanguage() {}
  string MakeQualifiedName(const string &parent_name,
                           const string &name) const {
    if (parent_name.empty())
      return name;
    else
      return parent_name + "::" + name;
  }
};

CPPLanguage CPPLanguageSingleton;

// Java language-specific operations.
class JavaLanguage: public Language {
 public:
  string MakeQualifiedName(const string &parent_name,
                           const string &name) const {
    if (parent_name.empty())
      return name;
    else
      return parent_name + "." + name;
  }
};

JavaLanguage JavaLanguageSingleton;

// Assembler language-specific operations.
class AssemblerLanguage: public Language {
  bool HasFunctions() const { return false; }
  string MakeQualifiedName(const string &parent_name,
                           const string &name) const {
    return name;
  }
};

AssemblerLanguage AssemblerLanguageSingleton;

const Language * const Language::CPlusPlus = &CPPLanguageSingleton;
const Language * const Language::Java = &JavaLanguageSingleton;
const Language * const Language::Assembler = &AssemblerLanguageSingleton;

} // namespace google_breakpad
<|endoftext|>


<commit_before>/*  $Id$
 *
 *  Copyright 2010 Anders Wallin (anders.e.e.wallin "at" gmail.com)
 *
 *  This file is part of OpenCAMlib.
 *
 *  OpenCAMlib 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 3 of the License, or
 *  (at your option) any later version.
 *
 *  OpenCAMlib 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 OpenCAMlib.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <iostream>
#include <cmath> // for fabs()
#include <cassert>

#include "numeric.hpp"
#include "point.hpp"

namespace ocl {

#define TOLERANCE 0.0000001

double xyVectorToDiangle(double x, double y) {
    double diangle;
    if (y >= 0)
        diangle = (x >= 0 ? y/(x+y) : 1-x/(-x+y));
    else
        diangle = (x < 0 ? 2-y/(-x-y) : 3+x/(x-y));
    if ( isnan(diangle) ) { // Windows platform problem: error C3861: 'isnan': identifier not found
        std::cout << "numeric::xyVectorToDiangle() error (x,y)= ("<< x << " , " << y  << " ) and diangle=" << diangle << "\n";
        assert(0);
    }
    return diangle;
}

double sign(double x) {
    if (x<0.0)
        return -1;
    else
        return 1;
}

bool isPositive(double x) {
    if (x > 0.0 )
        return true;
    else
        return false;
}

bool isNegative(double x) {
    if ( x < 0.0 )
        return true;
    else
        return false;
}

bool isZero_tol(double x) {
    if (fabs(x)<TOLERANCE)
        return true;
    else
        return false;
}

/// return machine epsilon
double eps() {
    double r;
    r = 1.0;
    while ( 1.0 <  (1.0 + r) )
        r = r / 2.0;
    return ( 2.0 * r );
}

double epsD(double x) {
    double r;
    r = 1000.0;
    while ( x <  (x + r) )
        r = r / 2.0;
    return ( 2.0 * r );
}

float epsF(float x) {
    float r;
    r = 1000.0;
    while ( x <  (x + r) )
        r = r / (float)2.0;
    return ( (float)2.0 * r );
}

void assert_msg( bool assertion, std::string message) {
    if ( !assertion ) {
        std::cout << message;
        assert( assertion );
    }
}

/// solve system Ax = y by inverting A
/// x = Ainv * y
/// returns false if det(A)==0, i.e. no solution found
bool two_by_two_solver( const double& a,
                        const double& b,
                        const double& c,
                        const double& d,
                        const double& e,
                        const double& f,
                        double& u,
                        double& v) {
    //  [ a  b ] [u] = [ e ]
    //  [ c  d ] [v] = [ f ]
    // matrix inverse is
    //          [ d  -b ]
    //  1/det * [ -c  a ]
    //  so
    //  [u]              [ d  -b ] [ e ]
    //  [v]  =  1/det *  [ -c  a ] [ f ]
    double det = a*d-c*b;
    if (isZero_tol(det))
        return false;
    u = (1.0/det) * (d*e - b*f);
    v = (1.0/det) * (-c*e + a*f);
    return true;
}

/// find an intersection point in the XY-plane between two lines
/// first line:   p1 + v*(p2-p1)
/// second line:  p3 + t*(p4-p3)
/// sets (v,t) to the intersection point and returns true if an intersection was found
bool xy_line_line_intersection( const Point& p1, const Point& p2, double& v,
                                const Point& p3, const Point& p4, double& t) {
    // p1 + v*(p2-p1) = p3 + t*(p4-p3)
    // =>
    // [ (p2-p1).x  -(p4-p3).x ] [ v ]  = [ (p3-p1).x ]
    // [ (p2-p1).y  -(p4-p3).y ] [ t ]  = [ (p3-p1).y ]
    return two_by_two_solver( (p2-p1).x , -(p4-p3).x , (p2-p1).y , -(p4-p3).y,  (p3-p1).x, (p3-p1).y, v, t);
}

} // end namespace
// end file numeric.cpp
<commit_msg>fix forgotten namespace<commit_after>/*  $Id$
 *
 *  Copyright 2010 Anders Wallin (anders.e.e.wallin "at" gmail.com)
 *
 *  This file is part of OpenCAMlib.
 *
 *  OpenCAMlib 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 3 of the License, or
 *  (at your option) any later version.
 *
 *  OpenCAMlib 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 OpenCAMlib.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <iostream>
#include <cmath> // for fabs()
#include <cassert>

#include "numeric.hpp"
#include "point.hpp"

namespace ocl {

#define TOLERANCE 0.0000001

double xyVectorToDiangle(double x, double y) {
    double diangle;
    if (y >= 0)
        diangle = (x >= 0 ? y/(x+y) : 1-x/(-x+y));
    else
        diangle = (x < 0 ? 2-y/(-x-y) : 3+x/(x-y));
    if (std::isnan(diangle) ) { // Windows platform problem: error C3861: 'isnan': identifier not found
        std::cout << "numeric::xyVectorToDiangle() error (x,y)= ("<< x << " , " << y  << " ) and diangle=" << diangle << "\n";
        assert(0);
    }
    return diangle;
}

double sign(double x) {
    if (x<0.0)
        return -1;
    else
        return 1;
}

bool isPositive(double x) {
    if (x > 0.0 )
        return true;
    else
        return false;
}

bool isNegative(double x) {
    if ( x < 0.0 )
        return true;
    else
        return false;
}

bool isZero_tol(double x) {
    if (fabs(x)<TOLERANCE)
        return true;
    else
        return false;
}

/// return machine epsilon
double eps() {
    double r;
    r = 1.0;
    while ( 1.0 <  (1.0 + r) )
        r = r / 2.0;
    return ( 2.0 * r );
}

double epsD(double x) {
    double r;
    r = 1000.0;
    while ( x <  (x + r) )
        r = r / 2.0;
    return ( 2.0 * r );
}

float epsF(float x) {
    float r;
    r = 1000.0;
    while ( x <  (x + r) )
        r = r / (float)2.0;
    return ( (float)2.0 * r );
}

void assert_msg( bool assertion, std::string message) {
    if ( !assertion ) {
        std::cout << message;
        assert( assertion );
    }
}

/// solve system Ax = y by inverting A
/// x = Ainv * y
/// returns false if det(A)==0, i.e. no solution found
bool two_by_two_solver( const double& a,
                        const double& b,
                        const double& c,
                        const double& d,
                        const double& e,
                        const double& f,
                        double& u,
                        double& v) {
    //  [ a  b ] [u] = [ e ]
    //  [ c  d ] [v] = [ f ]
    // matrix inverse is
    //          [ d  -b ]
    //  1/det * [ -c  a ]
    //  so
    //  [u]              [ d  -b ] [ e ]
    //  [v]  =  1/det *  [ -c  a ] [ f ]
    double det = a*d-c*b;
    if (isZero_tol(det))
        return false;
    u = (1.0/det) * (d*e - b*f);
    v = (1.0/det) * (-c*e + a*f);
    return true;
}

/// find an intersection point in the XY-plane between two lines
/// first line:   p1 + v*(p2-p1)
/// second line:  p3 + t*(p4-p3)
/// sets (v,t) to the intersection point and returns true if an intersection was found
bool xy_line_line_intersection( const Point& p1, const Point& p2, double& v,
                                const Point& p3, const Point& p4, double& t) {
    // p1 + v*(p2-p1) = p3 + t*(p4-p3)
    // =>
    // [ (p2-p1).x  -(p4-p3).x ] [ v ]  = [ (p3-p1).x ]
    // [ (p2-p1).y  -(p4-p3).y ] [ t ]  = [ (p3-p1).y ]
    return two_by_two_solver( (p2-p1).x , -(p4-p3).x , (p2-p1).y , -(p4-p3).y,  (p3-p1).x, (p3-p1).y, v, t);
}

} // end namespace
// end file numeric.cpp
<|endoftext|>


<commit_before>/* Copyright (C) 2012,2013 IBM Corp.
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */
#include <cassert>
#include <cstdio>

#include "FHE.h"
#include "timing.h"
#include "EncryptedArray.h"

#define pSize (NTL_SP_NBITS/2) /* The size of levels in the chain */

long rotationAmount(const EncryptedArray& ea, const FHEPubKey& publicKey,
	       bool withMatrix=false);
void timeOps(const EncryptedArray& ea, const FHEPubKey& publicKey, Ctxt& ret,
	     const vector<Ctxt>& c, ZZX& p, long nTests, long nPrimes=0);

// Returns either a random automorphism amount or an amount
// for which we have a key-switching matrix s^k -> s.
long rotationAmount(const EncryptedArray& ea, const FHEPubKey& publicKey,
	       bool onlyWithMatrix)
{
  const PAlgebra& pa = ea.getContext().zMStar;
  long nSlots = pa.getNSlots();
  long r = RandomBnd(nSlots);
  long k = pa.ith_rep(r);
  if (onlyWithMatrix) { // return the 1st step in the path to k
    const KeySwitch& matrix = publicKey.getNextKSWmatrix(k,0);
    k = matrix.fromKey.getPowerOfX();
  }
  return k;
}

void timeOps(const EncryptedArray& ea, const FHEPubKey& publicKey, Ctxt& ret,
	     const vector<Ctxt>& c, ZZX& p, long nTests, long nPrimes)
{
  assert(c.size()>=3);
  vector<Ctxt> cc = c;
  // perform operations at a lower level
  if (nPrimes>0) for (long i=0; i<(long)cc.size(); i++)
    cc[i].modDownToLevel(nPrimes);
  else
    nPrimes = cc[0].findBaseLevel();

  // inner-product of size-5 vectors
  if (nPrimes > 2) {
    cerr << "." << std::flush;
    startFHEtimer("dimension-5-innerProduct");
    innerProduct(ret,cc,cc);
    ret.modDownToLevel(ret.findBaseLevel());
    stopFHEtimer("dimension-5-innerProduct");
  }

  // Multiplication with 2,3 arguments
  cerr << "." << std::flush;
  for (long i=0; i<nTests; i++) {
    Ctxt c0 = cc[0];
    startFHEtimer("multiplyBy");
    c0.multiplyBy(cc[1]);
    c0.modDownToLevel(c0.findBaseLevel());      // mod-down if needed
    stopFHEtimer("multiplyBy");
    ret += c0; // Just so the compiler doesn't optimize it away
  }

  if (nPrimes > 2) {
    cerr << "." << std::flush;
    for (long i=0; i<nTests; i++) {
      Ctxt c0 = cc[0];
      startFHEtimer("multiplyBy2");
      c0.multiplyBy2(cc[1],cc[2]);
      c0.modDownToLevel(c0.findBaseLevel());      // mod-down if needed
      stopFHEtimer("multiplyBy2");
      ret += c0; // Just so the compiler doesn't optimize it away
    }
  }

  // Multiply by constant
  cerr << "." << std::flush;
  for (long i=0; i<3*nTests; i++) {
    Ctxt c0 = cc[0];
    startFHEtimer("multByConstant");
    c0.multByConstant(p);
    stopFHEtimer("multByConstant");
    ret -= c0; // Just so the compiler doesn't optimize it away
  }

  // Add constant
  cerr << "." << std::flush;
  for (long i=0; i<10*nTests; i++) {
    Ctxt c0 = cc[0];
    startFHEtimer("addConstant");
    c0.addConstant(p);
    stopFHEtimer("addConstant");
    ret += c0; // Just so the compiler doesn't optimize it away
  }

  // Rotation by an amount k for which we have a key-switching matrix
  cerr << "." << std::flush;
  for (long i=0; i<nTests; i++) {
    Ctxt c0 = cc[0];
    long k = rotationAmount(ea,publicKey,/*withMatrix=*/true);
    startFHEtimer("automorph-with-matrix");
    c0.smartAutomorph(k);
    c0.modDownToLevel(c0.findBaseLevel());      // mod-down if needed
    stopFHEtimer("automorph-with-matrix");
    ret += c0; // Just so the compiler doesn't optimize it away
  }
  // Rotation by a random amount k
  cerr << "." << std::flush;
  for (long i=0; i<nTests; i++) {
    Ctxt c0 = cc[0];
    long k = rotationAmount(ea,publicKey,/*withMatrix=*/false);
    startFHEtimer("automorph");
    c0.smartAutomorph(k);
    c0.modDownToLevel(c0.findBaseLevel());      // mod-down if needed
    stopFHEtimer("automorph");
    ret += c0; // Just so the compiler doesn't optimize it away
  }
}

void  TimeIt(long m, long p, long r, bool d_eq_1)
{
  cerr << "\n\n******** TimeIt: m=" << m
       << ", p=" << p
       << ", r=" << r
       << ", d=" << d_eq_1
       << endl;
  resetAllTimers();

  // Build the context, with as many primes as possible wrt to secparam=80
  startFHEtimer("Initialize context");
  FHEcontext context(m, p, r);
  stopFHEtimer("Initialize context");

  long phim = context.zMStar.getPhiM();
  long L = floor((7.2*phim)/(pSize* /*cc*/1.33* (110+/*k*/80))) -1;
  assert(L>1); // Make sure we have at least a few primes

  startFHEtimer("buildModChain");
  buildModChain(context, L, /*c=*/3);
  stopFHEtimer("buildModChain");

  startFHEtimer("keyGen");
  FHESecKey secretKey(context);
  const FHEPubKey& publicKey = secretKey;
  secretKey.GenSecKey(64); // A Hamming-weight-64 secret key
  addSome1DMatrices(secretKey); // compute key-switching matrices that we need
  stopFHEtimer("keyGen");

  ZZX G;
  if (d_eq_1)
    SetX(G); // set G(X)=X
  else
    G = context.alMod.getFactorsOverZZ()[0];

  startFHEtimer("Initialize EncryptedArray");
  EncryptedArray ea(context, G);
  stopFHEtimer("Initialize EncryptedArray");

  ZZX poly;
  PlaintextArray pp(ea);
  vector<PlaintextArray> vp(5,pp);
  for (long i=0; i<(long)vp.size(); i++)
    vp[i].random();

  Ctxt cc(publicKey);
  vector<Ctxt> vc(5,cc);

  for (long i=0; i<(long)vc.size(); i++) {
    startFHEtimer("encode");
    ea.encode(poly, vp[i]);
    stopFHEtimer("encode");
    startFHEtimer("SK-encrypt");
    secretKey.Encrypt(vc[i], poly);
    stopFHEtimer("SK-encrypt");
    startFHEtimer("PK-encrypt");
    publicKey.Encrypt(vc[i], poly);
    stopFHEtimer("PK-encrypt");
  }

  cerr << "Initialization time:\n";
  printAllTimers();
  resetAllTimers();
  cerr << endl;

  long nTests = 5;

  for (long i=2; i<L; i*=2) {
    cerr << "Operations with "<<i<<" primes in the chain: ";
    timeOps(ea, publicKey, cc,vc, poly, nTests, i);
    cerr << endl;
    printAllTimers();
    resetAllTimers();
    cerr << endl;
  }
  cerr << "Operations with "<<L<<" primes in the chain: ";
  timeOps(ea, publicKey, cc,vc, poly, nTests);
  cerr << endl;
  printAllTimers();
  resetAllTimers();
  cerr << endl;

  for (long i=0; i<(long)vc.size(); i++) {
    startFHEtimer("decrypt");
    secretKey.Decrypt(poly, vc[i]);
    stopFHEtimer("decrypt");
    startFHEtimer("decode");
    ea.decode(vp[i], poly);
    stopFHEtimer("decode");
  }

  cerr << "Decoding/decryption time:\n";
  printAllTimers();
}

void usage(char *prog)
{
  cerr << "Usage: "<<prog<<" [ optional parameters ]...\n";
  cerr << "  optional parameters have the form 'attr1=val1 attr2=val2 ...'\n";
  cerr << "  e.g, 'm=11441 p=2 r=1'\n\n";
  cerr << "  m determines the cyclotomic ring, defaults to all the set\n";
  cerr << "    m in { 4051, 4369, 4859, 10261,11023,11441,\n";
  cerr << "          18631,20485,21845, 49981,53261       }\n";
  cerr << "  p is the plaintext base [default=2]" << endl;
  cerr << "  r is the lifting [default=1]" << endl;
  cerr << "  d is the degree of the field extension [default==1]\n";
  cerr << "    (d == 0 => factors[0] defined the extension)\n";
  exit(0);
}

int main(int argc, char *argv[])
{
  argmap_t argmap;
  argmap["p"] = "2";
  argmap["r"] = "1";
  argmap["m"] = "0";
  argmap["d"] = "1";

  // get parameters from the command line
  if (!parseArgs(argc, argv, argmap)) usage(argv[0]);

  long p = atoi(argmap["p"]);
  long r = atoi(argmap["r"]);
  long m = atoi(argmap["m"]);
  long d = atoi(argmap["d"]);

  long ms[11] = { 4051, 4369, 4859, 10261,11023,11441,
		 18631,20485,21845, 49981,53261};
  if (m>0)
    TimeIt(m, p, r, (d==1));
  else for (long i=0; i<11; i++)
      TimeIt(ms[i], p, r, (d==1));
}
<commit_msg>no mod-down from level 2<commit_after>/* Copyright (C) 2012,2013 IBM Corp.
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */
#include <cassert>
#include <cstdio>

#include "FHE.h"
#include "timing.h"
#include "EncryptedArray.h"

#define pSize (NTL_SP_NBITS/2) /* The size of levels in the chain */

long rotationAmount(const EncryptedArray& ea, const FHEPubKey& publicKey,
	       bool withMatrix=false);
void timeOps(const EncryptedArray& ea, const FHEPubKey& publicKey, Ctxt& ret,
	     const vector<Ctxt>& c, ZZX& p, long nTests, long nPrimes=0);

// Returns either a random automorphism amount or an amount
// for which we have a key-switching matrix s^k -> s.
long rotationAmount(const EncryptedArray& ea, const FHEPubKey& publicKey,
	       bool onlyWithMatrix)
{
  const PAlgebra& pa = ea.getContext().zMStar;
  long nSlots = pa.getNSlots();
  long r = RandomBnd(nSlots);
  long k = pa.ith_rep(r);
  if (onlyWithMatrix) { // return the 1st step in the path to k
    const KeySwitch& matrix = publicKey.getNextKSWmatrix(k,0);
    k = matrix.fromKey.getPowerOfX();
  }
  return k;
}

void timeOps(const EncryptedArray& ea, const FHEPubKey& publicKey, Ctxt& ret,
	     const vector<Ctxt>& c, ZZX& p, long nTests, long nPrimes)
{
  assert(c.size()>=3);
  vector<Ctxt> cc = c;
  // perform operations at a lower level
  if (nPrimes>0) for (long i=0; i<(long)cc.size(); i++)
    cc[i].modDownToLevel(nPrimes);
  else
    nPrimes = cc[0].findBaseLevel();

  if (nPrimes <= 2)
    cerr << "(no mod-Down)";
  // inner-product of size-5 vectors
  cerr << "." << std::flush;
  startFHEtimer("dimension-5-innerProduct");
  innerProduct(ret,cc,cc);
  if (nPrimes > 2) ret.modDownToLevel(ret.findBaseLevel());
  stopFHEtimer("dimension-5-innerProduct");

  // Multiplication with 2,3 arguments
  cerr << "." << std::flush;
  for (long i=0; i<nTests; i++) {
    Ctxt c0 = cc[0];
    startFHEtimer("multiplyBy");
    c0.multiplyBy(cc[1]);
    if (nPrimes > 2) c0.modDownToLevel(c0.findBaseLevel()); // mod-down if needed
    stopFHEtimer("multiplyBy");
    ret += c0; // Just so the compiler doesn't optimize it away
  }

  cerr << "." << std::flush;
  for (long i=0; i<nTests; i++) {
    Ctxt c0 = cc[0];
    startFHEtimer("multiplyBy2");
    c0.multiplyBy2(cc[1],cc[2]);
    if (nPrimes > 2) c0.modDownToLevel(c0.findBaseLevel()); // mod-down if needed
    stopFHEtimer("multiplyBy2");
    ret += c0; // Just so the compiler doesn't optimize it away
  }

  // Multiply by constant
  cerr << "." << std::flush;
  for (long i=0; i<3*nTests; i++) {
    Ctxt c0 = cc[0];
    startFHEtimer("multByConstant");
    c0.multByConstant(p);
    stopFHEtimer("multByConstant");
    ret -= c0; // Just so the compiler doesn't optimize it away
  }

  // Add constant
  cerr << "." << std::flush;
  for (long i=0; i<10*nTests; i++) {
    Ctxt c0 = cc[0];
    startFHEtimer("addConstant");
    c0.addConstant(p);
    stopFHEtimer("addConstant");
    ret += c0; // Just so the compiler doesn't optimize it away
  }

  // Rotation by an amount k for which we have a key-switching matrix
  cerr << "." << std::flush;
  for (long i=0; i<nTests; i++) {
    Ctxt c0 = cc[0];
    long k = rotationAmount(ea,publicKey,/*withMatrix=*/true);
    startFHEtimer("automorph-with-matrix");
    c0.smartAutomorph(k);
    if (nPrimes > 2) c0.modDownToLevel(c0.findBaseLevel()); // mod-down if needed
    stopFHEtimer("automorph-with-matrix");
    ret += c0; // Just so the compiler doesn't optimize it away
  }
  // Rotation by a random amount k
  cerr << "." << std::flush;
  for (long i=0; i<nTests; i++) {
    Ctxt c0 = cc[0];
    long k = rotationAmount(ea,publicKey,/*withMatrix=*/false);
    startFHEtimer("automorph");
    c0.smartAutomorph(k);
    if (nPrimes > 2) c0.modDownToLevel(c0.findBaseLevel()); // mod-down if needed
    stopFHEtimer("automorph");
    ret += c0; // Just so the compiler doesn't optimize it away
  }
}

void  TimeIt(long m, long p, long r, bool d_eq_1)
{
  cerr << "\n\n******** TimeIt: m=" << m
       << ", p=" << p
       << ", r=" << r
       << ", d=" << d_eq_1
       << endl;
  resetAllTimers();

  // Build the context, with as many primes as possible wrt to secparam=80
  startFHEtimer("Initialize context");
  FHEcontext context(m, p, r);
  stopFHEtimer("Initialize context");

  long phim = context.zMStar.getPhiM();
  long L = floor((7.2*phim)/(pSize* /*cc*/1.33* (110+/*k*/80))) -1;
  assert(L>1); // Make sure we have at least a few primes

  startFHEtimer("buildModChain");
  buildModChain(context, L, /*c=*/3);
  stopFHEtimer("buildModChain");

  startFHEtimer("keyGen");
  FHESecKey secretKey(context);
  const FHEPubKey& publicKey = secretKey;
  secretKey.GenSecKey(64); // A Hamming-weight-64 secret key
  addSome1DMatrices(secretKey); // compute key-switching matrices that we need
  stopFHEtimer("keyGen");

  ZZX G;
  if (d_eq_1)
    SetX(G); // set G(X)=X
  else
    G = context.alMod.getFactorsOverZZ()[0];

  startFHEtimer("Initialize EncryptedArray");
  EncryptedArray ea(context, G);
  stopFHEtimer("Initialize EncryptedArray");

  ZZX poly;
  PlaintextArray pp(ea);
  vector<PlaintextArray> vp(5,pp);
  for (long i=0; i<(long)vp.size(); i++)
    vp[i].random();

  Ctxt cc(publicKey);
  vector<Ctxt> vc(5,cc);

  for (long i=0; i<(long)vc.size(); i++) {
    startFHEtimer("encode");
    ea.encode(poly, vp[i]);
    stopFHEtimer("encode");
    startFHEtimer("SK-encrypt");
    secretKey.Encrypt(vc[i], poly);
    stopFHEtimer("SK-encrypt");
    startFHEtimer("PK-encrypt");
    publicKey.Encrypt(vc[i], poly);
    stopFHEtimer("PK-encrypt");
  }

  cerr << "Initialization time:\n";
  printAllTimers();
  resetAllTimers();
  cerr << endl;

  long nTests = 5;

  for (long i=2; i<L; i*=2) {
    cerr << "Operations with "<<i<<" primes in the chain: ";
    timeOps(ea, publicKey, cc,vc, poly, nTests, i);
    cerr << endl;
    printAllTimers();
    resetAllTimers();
    cerr << endl;
  }
  cerr << "Operations with "<<L<<" primes in the chain: ";
  timeOps(ea, publicKey, cc,vc, poly, nTests);
  cerr << endl;
  printAllTimers();
  resetAllTimers();
  cerr << endl;

  for (long i=0; i<(long)vc.size(); i++) {
    startFHEtimer("decrypt");
    secretKey.Decrypt(poly, vc[i]);
    stopFHEtimer("decrypt");
    startFHEtimer("decode");
    ea.decode(vp[i], poly);
    stopFHEtimer("decode");
  }

  cerr << "Decoding/decryption time:\n";
  printAllTimers();
}

void usage(char *prog)
{
  cerr << "Usage: "<<prog<<" [ optional parameters ]...\n";
  cerr << "  optional parameters have the form 'attr1=val1 attr2=val2 ...'\n";
  cerr << "  e.g, 'm=11441 p=2 r=1'\n\n";
  cerr << "  m determines the cyclotomic ring, defaults to all the set\n";
  cerr << "    m in { 4051, 4369, 4859, 10261,11023,11441,\n";
  cerr << "          18631,20485,21845, 49981,53261       }\n";
  cerr << "  p is the plaintext base [default=2]" << endl;
  cerr << "  r is the lifting [default=1]" << endl;
  cerr << "  d is the degree of the field extension [default==1]\n";
  cerr << "    (d == 0 => factors[0] defined the extension)\n";
  exit(0);
}

int main(int argc, char *argv[])
{
  argmap_t argmap;
  argmap["p"] = "2";
  argmap["r"] = "1";
  argmap["m"] = "0";
  argmap["d"] = "1";

  // get parameters from the command line
  if (!parseArgs(argc, argv, argmap)) usage(argv[0]);

  long p = atoi(argmap["p"]);
  long r = atoi(argmap["r"]);
  long m = atoi(argmap["m"]);
  long d = atoi(argmap["d"]);

  long ms[11] = { 4051, 4369, 4859, 10261,11023,11441,
		 18631,20485,21845, 49981,53261};
  if (m>0)
    TimeIt(m, p, r, (d==1));
  else for (long i=0; i<11; i++)
      TimeIt(ms[i], p, r, (d==1));
}
<|endoftext|>


<commit_before>#include <cstdio>
#include <limits>
#include <algorithm>

typedef long long LL;

using std::sort;
using std::max;
using std::numeric_limits;

const int kMaximumShopsNumber = 100000;

class Shop {
  public:
    class Comparer {
      public:
        Comparer(int (*coord_accessor)(const Shop&))
                : coord_accessor_(coord_accessor) {}
        bool operator()(const Shop &a, const Shop &b);
      private:
        int (*coord_accessor_)(const Shop&);
    };

    static const int kInitX = 0;
    static const int kInitY = 0;
    static const int kInitVisitCount = -1LL;

    Shop() : x_(kInitX), y_(kInitY), visit_count_(kInitVisitCount) {}

    int x() const { return x_; }
    int y() const { return y_; }
    LL visit_count() const { return visit_count_; }
    static int GetX(const Shop &s) { return s.x_; }
    static int GetY(const Shop &s) { return s.y_; }
    void Init(int x, int y, LL visit_count);
    void Rotate();

  private:
    int x_;
    int y_;
    LL visit_count_;
};

bool Shop::Comparer::operator()(const Shop &a, const Shop &b) {
    return (*coord_accessor_)(a) < (*coord_accessor_)(b);
}

void Shop::Init(int x, int y, LL visit_count) {
    x_ = x;
    y_ = y;
    visit_count_ = visit_count;
}

void Shop::Rotate() {
    int x = x_;
    x_ = x - y_;
    y_ = x + y_;
}

int GetNthCoord(const Shop sorted_shops[], LL nth,
        int (*coord_accessor)(const Shop&)) {
    int i = 0;
    int retval = 0;
    LL shops_passed = 0;
    while (shops_passed < nth) {
        retval = (*coord_accessor)(sorted_shops[i]);
        shops_passed += sorted_shops[i].visit_count();
        ++i;
    }
    return retval;
}

int GetMedianCoord(Shop shops[], int n, LL median_visit,
        int (*coord_accessor)(const Shop&)) {
    Shop::Comparer shop_comparer = Shop::Comparer(coord_accessor);
    sort(shops, shops + n, shop_comparer);
    return GetNthCoord(shops, median_visit, coord_accessor);
}

LL Distance(LL x1, LL y1, LL x2, LL y2) {
    return max(abs(x1 - x2), abs(y1 - y2));
}

LL TotalDistance(int x, int y, const Shop shops[], int n) {
    LL total = 0;
    for (int i = 0; i < n; ++i)
        total += shops[i].visit_count() * Distance(x, y, shops[i].x(),
                                                   shops[i].y());
    return total;
}

int main() {
    int n = 0;
    LL total_visit_count = 0;
    Shop shops[kMaximumShopsNumber];
    Shop rotated_shops[kMaximumShopsNumber];

    scanf("%d", &n);
    for (int i = 0; i < n; i++) {
        int x, y, visit_count;
        scanf("%d%d%d", &x, &y, &visit_count);
        total_visit_count += visit_count;
        shops[i].Init(x, y, visit_count);
        rotated_shops[i].Init(x, y, visit_count);
        rotated_shops[i].Rotate();
    }

    const LL median_visit = (total_visit_count + 1) / 2;
    const int best_x_rotated = GetMedianCoord(rotated_shops, n,
                                              median_visit,
                                              &Shop::GetX);
    const int best_y_rotated = GetMedianCoord(rotated_shops, n,
                                              median_visit,
                                              &Shop::GetY);
    const int x = (best_x_rotated + best_y_rotated) / 2;
    const int y = (best_y_rotated - best_x_rotated) / 2;
    const int xs[] = { 0, 1, 0, 1 };
    const int ys[] = { 0, 1, 1, 0 };
    int best_x = x;
    int best_y = y;
    LL lowest_total_distance = numeric_limits<LL>::max();
    for (int i = 0; i < 4; i++) {
        int current_x = x + xs[i];
        int current_y = y + ys[i];
        LL current_distance = TotalDistance(current_x, current_y, shops, n);
        //printf("%d %d TD: %lu\n", current_x, current_y, current_distance);
        if (current_distance < lowest_total_distance) {
            lowest_total_distance = current_distance;
            best_x = current_x;
            best_y = current_y;
        }
    }
    printf("%d %d\n", best_x, best_y);
    return 0;
}
<commit_msg>Changed usage of LL to int64_t<commit_after>#include <stdint.h>
#include <cstdio>
#include <limits>
#include <algorithm>

using std::sort;
using std::max;
using std::numeric_limits;

const int kMaximumShopsNumber = 100000;

class Shop {
  public:
    class Comparer {
      public:
        Comparer(int (*coord_accessor)(const Shop&))
                : coord_accessor_(coord_accessor) {}
        bool operator()(const Shop &a, const Shop &b);
      private:
        int (*coord_accessor_)(const Shop&);
    };

    static const int kInitX = 0;
    static const int kInitY = 0;
    static const int kInitVisitCount = -1;

    Shop() : x_(kInitX), y_(kInitY), visit_count_(kInitVisitCount) {}

    int x() const { return x_; }
    int y() const { return y_; }
    int visit_count() const { return visit_count_; }
    static int GetX(const Shop &s) { return s.x_; }
    static int GetY(const Shop &s) { return s.y_; }
    void Init(int x, int y, int visit_count);
    void Rotate();

  private:
    int x_;
    int y_;
    int visit_count_;
};

bool Shop::Comparer::operator()(const Shop &a, const Shop &b) {
    return (*coord_accessor_)(a) < (*coord_accessor_)(b);
}

void Shop::Init(int x, int y, int visit_count) {
    x_ = x;
    y_ = y;
    visit_count_ = visit_count;
}

void Shop::Rotate() {
    int x = x_;
    x_ = x - y_;
    y_ = x + y_;
}

int GetNthCoord(const Shop sorted_shops[], int64_t nth,
        int (*coord_accessor)(const Shop&)) {
    int i = 0;
    int retval = 0;
    int64_t shops_passed = 0;
    while (shops_passed < nth) {
        retval = (*coord_accessor)(sorted_shops[i]);
        shops_passed += static_cast<int64_t>(sorted_shops[i].visit_count());
        ++i;
    }
    return retval;
}

int GetMedianCoord(Shop shops[], int n, int64_t median_visit,
        int (*coord_accessor)(const Shop&)) {
    Shop::Comparer shop_comparer = Shop::Comparer(coord_accessor);
    sort(shops, shops + n, shop_comparer);
    return GetNthCoord(shops, median_visit, coord_accessor);
}

int64_t Distance(int64_t x1, int64_t y1, int64_t x2, int64_t y2) {
    return max(abs(x1 - x2), abs(y1 - y2));
}

int64_t TotalDistance(int x, int y, const Shop shops[], int n) {
    int64_t total = 0;
    for (int i = 0; i < n; ++i)
        total += static_cast<int64_t>(shops[i].visit_count()) *
                Distance(x, y, shops[i].x(), shops[i].y());
    return total;
}

int main() {
    int n = 0;
    int64_t total_visit_count = 0;
    Shop shops[kMaximumShopsNumber];
    Shop rotated_shops[kMaximumShopsNumber];

    scanf("%d", &n);
    for (int i = 0; i < n; i++) {
        int x, y, visit_count;
        scanf("%d%d%d", &x, &y, &visit_count);
        total_visit_count += visit_count;
        shops[i].Init(x, y, visit_count);
        rotated_shops[i].Init(x, y, visit_count);
        rotated_shops[i].Rotate();
    }

    const int64_t median_visit = (total_visit_count + 1) / 2;
    const int best_x_rotated = GetMedianCoord(rotated_shops, n,
                                              median_visit,
                                              &Shop::GetX);
    const int best_y_rotated = GetMedianCoord(rotated_shops, n,
                                              median_visit,
                                              &Shop::GetY);
    const int x = (best_x_rotated + best_y_rotated) / 2;
    const int y = (best_y_rotated - best_x_rotated) / 2;
    const int xs[] = { 0, 1, 0, 1 };
    const int ys[] = { 0, 1, 1, 0 };
    int best_x = x;
    int best_y = y;
    int64_t lowest_total_distance = numeric_limits<int64_t>::max();
    for (int i = 0; i < 4; i++) {
        int current_x = x + xs[i];
        int current_y = y + ys[i];
        int64_t current_distance = TotalDistance(current_x, current_y,
                                                 shops, n);
        if (current_distance < lowest_total_distance) {
            lowest_total_distance = current_distance;
            best_x = current_x;
            best_y = current_y;
        }
    }
    printf("%d %d\n", best_x, best_y);
    return 0;
}
<|endoftext|>


<commit_before>/*
 * Copyright 2011, 2012 Esrille Inc.
 *
 * 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 "CounterImp.h"

namespace org
{
namespace w3c
{
namespace dom
{
namespace bootstrap
{

namespace {

struct AdditiveGlyph
{
    int weight;
    char16_t* glyph;
};

// 1 4999
AdditiveGlyph upperRoman[] =
{
    1000, u"M",
    900, u"CM",
    500, u"D",
    400, u"CD",
    100, u"C",
    90, u"XC",
    50, u"L",
    40, u"XL",
    10, u"X",
    9, u"IX",
    5, u"V",
    4, u"IV",
    1, u"I",
    0, 0
};

// 1 4999
AdditiveGlyph lowerRoman[] =
{
    1000, u"m",
    900, u"cm",
    500, u"d",
    400, u"cd",
    100, u"c",
    90, u"xc",
    50, u"l",
    40, u"xl",
    10, u"x",
    9, u"ix",
    5, u"v",
    4, u"iv",
    1, u"i",
    0, 0
};

std::u16string convertToRoman(int n, AdditiveGlyph* glyphList)
{
    if (n < 0 || 5000 <= n)
        return toString(n);
    std::u16string value;
    for (AdditiveGlyph* i = glyphList; i->glyph; ++i) {
        int t = n / i->weight;
        if (0 < t) {
            n -= t * i->weight;
            while (0 < t--)
                value += i->glyph;
        }
    }
    return value;
}

std::u16string emit(int i, unsigned type)
{
    std::u16string value;
    switch (type) {
    case CSSListStyleTypeValueImp::None:
        break;
    case CSSListStyleTypeValueImp::Disc:
        value = u"\u2022";    // •
        break;
    case CSSListStyleTypeValueImp::Circle:
        value = u"\u25E6";    // ◦
        break;
    case CSSListStyleTypeValueImp::Square:
        // Use u25A0 instead of u25FE for the IPA font for now
        value = u"\u25A0";    // ◾ "\u25FE"
        break;
    case CSSListStyleTypeValueImp::Decimal:
        value = toString(i);
        break;
    case CSSListStyleTypeValueImp::DecimalLeadingZero:
        value = toString(i < 0 ? -i : i);
        if (-9 <= i && i <= 9)
            value = u"0" + value;
        if (i < 0)
            value = u"-" + value;
        break;
    case CSSListStyleTypeValueImp::LowerAlpha:
    case CSSListStyleTypeValueImp::LowerLatin:
        value = std::u16string(1, u'a' + static_cast<unsigned>(i) % 26 - 1);
        break;
    case CSSListStyleTypeValueImp::UpperAlpha:
    case CSSListStyleTypeValueImp::UpperLatin:
        value = std::u16string(1, u'A' + static_cast<unsigned>(i) % 26 - 1);
        break;
    case CSSListStyleTypeValueImp::LowerGreek:
        // This style is only defined because CSS2.1 has it.
        // It doesn't appear to actually be used in Greek texts.
        value = std::u16string(1, u"αβγδεζηθικλμνξοπρστυφχψω"[static_cast<unsigned>(i - 1) % 24]);
        break;
    case CSSListStyleTypeValueImp::LowerRoman:
        value = convertToRoman(i, lowerRoman);
        break;
    case CSSListStyleTypeValueImp::UpperRoman:
        value = convertToRoman(i, upperRoman);
        break;
    case CSSListStyleTypeValueImp::Armenian:
    case CSSListStyleTypeValueImp::Georgian:
    default:
        value = toString(i);
        break;
    }
    return value;
}

}

void CounterImp::nest(int number)
{
    counters.push_back(number);
}

void CounterImp::reset(int number)
{
    if (counters.empty())
        nest(number);
    else
        counters.back() = number;
}

void CounterImp::increment(int number)
{
    if (counters.empty())
        nest(0);
    counters.back() += number;
}

bool CounterImp::restore()
{
    counters.pop_back();
    return counters.empty();
}

std::u16string CounterImp::eval(unsigned type, CSSAutoNumberingValueImp::CounterContext* context)
{
    this->separator = u"";
    this->listStyle.setValue(type);
    if (counters.empty()) {
        nest(0);
        context->addCounter(this);
    }
    return emit(counters.back(), type);
}

std::u16string CounterImp::eval(const std::u16string& separator, unsigned type, CSSAutoNumberingValueImp::CounterContext* context)
{
    this->separator = separator;
    this->listStyle.setValue(type);
    if (counters.empty()) {
        nest(0);
        context->addCounter(this);
    }
    std::u16string value;
    for (auto i = counters.begin(); i != counters.end(); ++i) {
        if (i != counters.begin())
            value += separator;
        value += emit(*i, type);
    }
    return value;
}

std::u16string CounterImp::getIdentifier()
{
    return identifier;
}

std::u16string CounterImp::getListStyle()
{
    return listStyle.getCssText();
}

std::u16string CounterImp::getSeparator()
{
    return separator;
}

}
}
}
}
<commit_msg>(CounterImp) : Support 'armenian' and 'georgian'; cf. content-counter-009 and content-counter-010.<commit_after>/*
 * Copyright 2011, 2012 Esrille Inc.
 *
 * 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 "CounterImp.h"

namespace org
{
namespace w3c
{
namespace dom
{
namespace bootstrap
{

namespace {

struct AdditiveGlyph
{
    int weight;
    char16_t* glyph;
};

// 1 4999
AdditiveGlyph upperRoman[] =
{
    1000, u"M",
    900, u"CM",
    500, u"D",
    400, u"CD",
    100, u"C",
    90, u"XC",
    50, u"L",
    40, u"XL",
    10, u"X",
    9, u"IX",
    5, u"V",
    4, u"IV",
    1, u"I",
    0, 0
};

// 1 4999
AdditiveGlyph lowerRoman[] =
{
    1000, u"m",
    900, u"cm",
    500, u"d",
    400, u"cd",
    100, u"c",
    90, u"xc",
    50, u"l",
    40, u"xl",
    10, u"x",
    9, u"ix",
    5, u"v",
    4, u"iv",
    1, u"i",
    0, 0
};

// 1 9999
AdditiveGlyph armenian[] =
{
    9000, u"\u0554",
    8000, u"\u0553",
    7000, u"\u0552",
    6000, u"\u0551",
    5000, u"\u0550",
    4000, u"\u054F",
    3000, u"\u054E",
    2000, u"\u054D",
    1000, u"\u054C",
    900, u"\u054B",
    800, u"\u054A",
    700, u"\u0549",
    600, u"\u0548",
    500, u"\u0547",
    400, u"\u0546",
    300, u"\u0545",
    200, u"\u0544",
    100, u"\u0543",
    90, u"\u0542",
    80, u"\u0541",
    70, u"\u0540",
    60, u"\u053F",
    50, u"\u053E",
    40, u"\u053D",
    30, u"\u053C",
    20, u"\u053B",
    10, u"\u053A",
    9, u"\u0539",
    8, u"\u0538",
    7, u"\u0537",
    6, u"\u0536",
    5, u"\u0535",
    4, u"\u0534",
    3, u"\u0533",
    2, u"\u0532",
    1, u"\u0531"
};

// 1 19999
AdditiveGlyph georgian[] =
{
    10000, u"\u10F5",
    9000, u"\u10F0",
    8000, u"\u10EF",
    7000, u"\u10F4",
    6000, u"\u10EE",
    5000, u"\u10ED",
    4000, u"\u10EC",
    3000, u"\u10EB",
    2000, u"\u10EA",
    1000, u"\u10E9",
    900, u"\u10E8",
    800, u"\u10E7",
    700, u"\u10E6",
    600, u"\u10E5",
    500, u"\u10E4",
    400, u"\u10F3",
    300, u"\u10E2",
    200, u"\u10E1",
    100, u"\u10E0",
    90, u"\u10DF",
    80, u"\u10DE",
    70, u"\u10DD",
    60, u"\u10F2",
    50, u"\u10DC",
    40, u"\u10DB",
    30, u"\u10DA",
    20, u"\u10D9",
    10, u"\u10D8",
    9, u"\u10D7",
    8, u"\u10F1",
    7, u"\u10D6",
    6, u"\u10D5",
    5, u"\u10D4",
    4, u"\u10D3",
    3, u"\u10D2",
    2, u"\u10D1",
    1, u"\u10D0"
};

std::u16string convertToRoman(int n, AdditiveGlyph* glyphList, int min = 1, int max = 4999)
{
    if (n < min || max < n)
        return toString(n);
    std::u16string value;
    for (AdditiveGlyph* i = glyphList; i->glyph; ++i) {
        int t = n / i->weight;
        if (0 < t) {
            n -= t * i->weight;
            while (0 < t--)
                value += i->glyph;
        }
    }
    return value;
}

std::u16string emit(int i, unsigned type)
{
    std::u16string value;
    switch (type) {
    case CSSListStyleTypeValueImp::None:
        break;
    case CSSListStyleTypeValueImp::Disc:
        value = u"\u2022";    // •
        break;
    case CSSListStyleTypeValueImp::Circle:
        value = u"\u25E6";    // ◦
        break;
    case CSSListStyleTypeValueImp::Square:
        // Use u25A0 instead of u25FE for the IPA font for now
        value = u"\u25A0";    // ◾ "\u25FE"
        break;
    case CSSListStyleTypeValueImp::Decimal:
        value = toString(i);
        break;
    case CSSListStyleTypeValueImp::DecimalLeadingZero:
        value = toString(i < 0 ? -i : i);
        if (-9 <= i && i <= 9)
            value = u"0" + value;
        if (i < 0)
            value = u"-" + value;
        break;
    case CSSListStyleTypeValueImp::LowerAlpha:
    case CSSListStyleTypeValueImp::LowerLatin:
        value = std::u16string(1, u'a' + static_cast<unsigned>(i) % 26 - 1);
        break;
    case CSSListStyleTypeValueImp::UpperAlpha:
    case CSSListStyleTypeValueImp::UpperLatin:
        value = std::u16string(1, u'A' + static_cast<unsigned>(i) % 26 - 1);
        break;
    case CSSListStyleTypeValueImp::LowerGreek:
        // This style is only defined because CSS2.1 has it.
        // It doesn't appear to actually be used in Greek texts.
        value = std::u16string(1, u"αβγδεζηθικλμνξοπρστυφχψω"[static_cast<unsigned>(i - 1) % 24]);
        break;
    case CSSListStyleTypeValueImp::LowerRoman:
        value = convertToRoman(i, lowerRoman);
        break;
    case CSSListStyleTypeValueImp::UpperRoman:
        value = convertToRoman(i, upperRoman);
        break;
    case CSSListStyleTypeValueImp::Armenian:
        value = convertToRoman(i, armenian, 1, 9999);
        break;
    case CSSListStyleTypeValueImp::Georgian:
        value = convertToRoman(i, georgian, 1, 19999);
        break;
    default:
        value = toString(i);
        break;
    }
    return value;
}

}

void CounterImp::nest(int number)
{
    counters.push_back(number);
}

void CounterImp::reset(int number)
{
    if (counters.empty())
        nest(number);
    else
        counters.back() = number;
}

void CounterImp::increment(int number)
{
    if (counters.empty())
        nest(0);
    counters.back() += number;
}

bool CounterImp::restore()
{
    counters.pop_back();
    return counters.empty();
}

std::u16string CounterImp::eval(unsigned type, CSSAutoNumberingValueImp::CounterContext* context)
{
    this->separator = u"";
    this->listStyle.setValue(type);
    if (counters.empty()) {
        nest(0);
        context->addCounter(this);
    }
    return emit(counters.back(), type);
}

std::u16string CounterImp::eval(const std::u16string& separator, unsigned type, CSSAutoNumberingValueImp::CounterContext* context)
{
    this->separator = separator;
    this->listStyle.setValue(type);
    if (counters.empty()) {
        nest(0);
        context->addCounter(this);
    }
    std::u16string value;
    for (auto i = counters.begin(); i != counters.end(); ++i) {
        if (i != counters.begin())
            value += separator;
        value += emit(*i, type);
    }
    return value;
}

std::u16string CounterImp::getIdentifier()
{
    return identifier;
}

std::u16string CounterImp::getListStyle()
{
    return listStyle.getCssText();
}

std::u16string CounterImp::getSeparator()
{
    return separator;
}

}
}
}
}
<|endoftext|>


<commit_before>//===- IntervalPartition.cpp - Interval Partition module code -------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the definition of the IntervalPartition class, which
// calculates and represent the interval partition of a function.
//
//===----------------------------------------------------------------------===//

#include "llvm/Analysis/IntervalIterator.h"
using namespace llvm;

char IntervalPartition::ID = 0;
static RegisterPass<IntervalPartition>
X("intervals", "Interval Partition Construction", true, true);

//===----------------------------------------------------------------------===//
// IntervalPartition Implementation
//===----------------------------------------------------------------------===//

// destroy - Reset state back to before function was analyzed
void IntervalPartition::destroy() {
  for (unsigned i = 0, e = Intervals.size(); i != e; ++i)
    delete Intervals[i];
  IntervalMap.clear();
  RootInterval = 0;
}

void IntervalPartition::print(std::ostream &O, const Module*) const {
  for(unsigned i = 0, e = Intervals.size(); i != e; ++i)
    Intervals[i]->print(O);
}

// addIntervalToPartition - Add an interval to the internal list of intervals,
// and then add mappings from all of the basic blocks in the interval to the
// interval itself (in the IntervalMap).
//
void IntervalPartition::addIntervalToPartition(Interval *I) {
  Intervals.push_back(I);

  // Add mappings for all of the basic blocks in I to the IntervalPartition
  for (Interval::node_iterator It = I->Nodes.begin(), End = I->Nodes.end();
       It != End; ++It)
    IntervalMap.insert(std::make_pair(*It, I));
}

// updatePredecessors - Interval generation only sets the successor fields of
// the interval data structures.  After interval generation is complete,
// run through all of the intervals and propagate successor info as
// predecessor info.
//
void IntervalPartition::updatePredecessors(Interval *Int) {
  BasicBlock *Header = Int->getHeaderNode();
  for (Interval::succ_iterator I = Int->Successors.begin(),
         E = Int->Successors.end(); I != E; ++I)
    getBlockInterval(*I)->Predecessors.push_back(Header);
}

// IntervalPartition ctor - Build the first level interval partition for the
// specified function...
//
bool IntervalPartition::runOnFunction(Function &F) {
  // Pass false to intervals_begin because we take ownership of it's memory
  function_interval_iterator I = intervals_begin(&F, false);
  assert(I != intervals_end(&F) && "No intervals in function!?!?!");

  addIntervalToPartition(RootInterval = *I);

  ++I;  // After the first one...

  // Add the rest of the intervals to the partition.
  for (function_interval_iterator E = intervals_end(&F); I != E; ++I)
    addIntervalToPartition(*I);

  // Now that we know all of the successor information, propagate this to the
  // predecessors for each block.
  for (unsigned i = 0, e = Intervals.size(); i != e; ++i)
    updatePredecessors(Intervals[i]);
  return false;
}

// IntervalPartition ctor - Build a reduced interval partition from an
// existing interval graph.  This takes an additional boolean parameter to
// distinguish it from a copy constructor.  Always pass in false for now.
//
IntervalPartition::IntervalPartition(IntervalPartition &IP, bool)
  : FunctionPass((intptr_t) &ID) {
  Interval *FunctionStart = IP.getRootInterval();
  assert(FunctionStart && "Cannot operate on empty IntervalPartitions!");

  // Pass false to intervals_begin because we take ownership of it's memory
  interval_part_interval_iterator I = intervals_begin(IP, false);
  assert(I != intervals_end(IP) && "No intervals in interval partition!?!?!");

  addIntervalToPartition(RootInterval = *I);

  ++I;  // After the first one...

  // Add the rest of the intervals to the partition.
  for (interval_part_interval_iterator E = intervals_end(IP); I != E; ++I)
    addIntervalToPartition(*I);

  // Now that we know all of the successor information, propagate this to the
  // predecessors for each block.
  for (unsigned i = 0, e = Intervals.size(); i != e; ++i)
    updatePredecessors(Intervals[i]);
}

<commit_msg>fix warning when assertions disabled.<commit_after>//===- IntervalPartition.cpp - Interval Partition module code -------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the definition of the IntervalPartition class, which
// calculates and represent the interval partition of a function.
//
//===----------------------------------------------------------------------===//

#include "llvm/Analysis/IntervalIterator.h"
using namespace llvm;

char IntervalPartition::ID = 0;
static RegisterPass<IntervalPartition>
X("intervals", "Interval Partition Construction", true, true);

//===----------------------------------------------------------------------===//
// IntervalPartition Implementation
//===----------------------------------------------------------------------===//

// destroy - Reset state back to before function was analyzed
void IntervalPartition::destroy() {
  for (unsigned i = 0, e = Intervals.size(); i != e; ++i)
    delete Intervals[i];
  IntervalMap.clear();
  RootInterval = 0;
}

void IntervalPartition::print(std::ostream &O, const Module*) const {
  for(unsigned i = 0, e = Intervals.size(); i != e; ++i)
    Intervals[i]->print(O);
}

// addIntervalToPartition - Add an interval to the internal list of intervals,
// and then add mappings from all of the basic blocks in the interval to the
// interval itself (in the IntervalMap).
//
void IntervalPartition::addIntervalToPartition(Interval *I) {
  Intervals.push_back(I);

  // Add mappings for all of the basic blocks in I to the IntervalPartition
  for (Interval::node_iterator It = I->Nodes.begin(), End = I->Nodes.end();
       It != End; ++It)
    IntervalMap.insert(std::make_pair(*It, I));
}

// updatePredecessors - Interval generation only sets the successor fields of
// the interval data structures.  After interval generation is complete,
// run through all of the intervals and propagate successor info as
// predecessor info.
//
void IntervalPartition::updatePredecessors(Interval *Int) {
  BasicBlock *Header = Int->getHeaderNode();
  for (Interval::succ_iterator I = Int->Successors.begin(),
         E = Int->Successors.end(); I != E; ++I)
    getBlockInterval(*I)->Predecessors.push_back(Header);
}

// IntervalPartition ctor - Build the first level interval partition for the
// specified function...
//
bool IntervalPartition::runOnFunction(Function &F) {
  // Pass false to intervals_begin because we take ownership of it's memory
  function_interval_iterator I = intervals_begin(&F, false);
  assert(I != intervals_end(&F) && "No intervals in function!?!?!");

  addIntervalToPartition(RootInterval = *I);

  ++I;  // After the first one...

  // Add the rest of the intervals to the partition.
  for (function_interval_iterator E = intervals_end(&F); I != E; ++I)
    addIntervalToPartition(*I);

  // Now that we know all of the successor information, propagate this to the
  // predecessors for each block.
  for (unsigned i = 0, e = Intervals.size(); i != e; ++i)
    updatePredecessors(Intervals[i]);
  return false;
}

// IntervalPartition ctor - Build a reduced interval partition from an
// existing interval graph.  This takes an additional boolean parameter to
// distinguish it from a copy constructor.  Always pass in false for now.
//
IntervalPartition::IntervalPartition(IntervalPartition &IP, bool)
  : FunctionPass((intptr_t) &ID) {
  assert(IP.getRootInterval() && "Cannot operate on empty IntervalPartitions!");

  // Pass false to intervals_begin because we take ownership of it's memory
  interval_part_interval_iterator I = intervals_begin(IP, false);
  assert(I != intervals_end(IP) && "No intervals in interval partition!?!?!");

  addIntervalToPartition(RootInterval = *I);

  ++I;  // After the first one...

  // Add the rest of the intervals to the partition.
  for (interval_part_interval_iterator E = intervals_end(IP); I != E; ++I)
    addIntervalToPartition(*I);

  // Now that we know all of the successor information, propagate this to the
  // predecessors for each block.
  for (unsigned i = 0, e = Intervals.size(); i != e; ++i)
    updatePredecessors(Intervals[i]);
}

<|endoftext|>