<commit_before>#pragma once
#include "rack.hpp"
#include "QuantizeUtils.cpp"
#define RIGHT_ARROW "▸"

using namespace rack;
extern Plugin *pluginInstance;

////////////////////////////////////////////// PANELS //////////////////////////////////////////////

struct BGPanel : Widget {
	Widget *panelBorder;
	NVGcolor color;

	BGPanel(NVGcolor _color) {
		panelBorder = new PanelBorder;
		color = _color;
		addChild(panelBorder);
	}

	void step() override {
		panelBorder->box.size = box.size;
		Widget::step();
	}

	void draw(const DrawArgs &args) override {
		nvgBeginPath(args.vg);
		nvgRect(args.vg, 0.0, 0.0, box.size.x, box.size.y);
		nvgFillColor(args.vg, color);
		nvgFill(args.vg);
		Widget::draw(args);
	}
};

////////////////////////////////////////////// LABELS //////////////////////////////////////////////

struct CenteredLabel : Widget {
	std::string text;
	int fontSize;
	CenteredLabel(int _fontSize = 12) {
		fontSize = _fontSize;
		box.size.y = BND_WIDGET_HEIGHT;
	}
	void draw(const DrawArgs &args) override {
		nvgTextAlign(args.vg, NVG_ALIGN_CENTER);
		nvgFillColor(args.vg, nvgRGB(25, 150, 252));
		nvgFontSize(args.vg, fontSize);
		nvgText(args.vg, box.pos.x, box.pos.y, text.c_str(), NULL);
	}
};

////////////////////////////////////////////// KNOBS //////////////////////////////////////////////

struct SmallWhiteKnob : RoundKnob {
	CenteredLabel* linkedLabel = NULL;
	Module* linkedModule = NULL;

	SmallWhiteKnob() {
		shadow->opacity = 0;
		setSVG(APP->window->loadSvg(asset::plugin(pluginInstance, "res/SmallWhiteKnob.svg")));
	}

	void connectLabel(CenteredLabel* label, Module* module) {
		linkedLabel = label;
		linkedModule = module;
		if (linkedModule && linkedLabel) {
			linkedLabel->text = formatCurrentValue();
		}
	}

	void onChange(const event::Change &e) override {
		RoundKnob::onChange(e);
		if (linkedModule && linkedLabel) {
			linkedLabel->text = formatCurrentValue();
		}
	}

	virtual std::string formatCurrentValue() {
		if(paramQuantity != NULL){
			return std::to_string(static_cast<unsigned int>(paramQuantity->getValue()));
		}
		return "";
	}
};

struct NoteKnob : SmallWhiteKnob {
	QuantizeUtils *quantizeUtils;
	NoteKnob(){
		snap = true;
	}
	std::string formatCurrentValue() override {
		if(paramQuantity != NULL){
			return quantizeUtils->noteName(int(paramQuantity->getValue()));
		}
		return "";
	}
};

struct ScaleKnob : SmallWhiteKnob {
	QuantizeUtils *quantizeUtils;
	ScaleKnob(){
		snap = true;
	}
	std::string formatCurrentValue() override {
		if(paramQuantity != NULL){
			return quantizeUtils->scaleName(int(paramQuantity->getValue()));
		}
		return "";
	}
};

struct JwSmallSnapKnob : SmallWhiteKnob {
	JwSmallSnapKnob() {
		snap = true;
	}
};

struct JwTinyKnob : RoundKnob {
	JwTinyKnob() {
		setSVG(APP->window->loadSvg(asset::plugin(pluginInstance, "res/TinyWhiteKnob.svg")));
	}
};

struct JwTinyGrayKnob : RoundKnob {
	JwTinyGrayKnob() {
		setSVG(APP->window->loadSvg(asset::plugin(pluginInstance, "res/TinyWhiteGrayKnob.svg")));
	}
};

struct BPMPartKnob : JwSmallSnapKnob {
	BPMPartKnob(){}
};

////////////////////////////////////////////// SWITCHES //////////////////////////////////////////////

struct JwHorizontalSwitch : SVGSwitch {
	JwHorizontalSwitch() {
		addFrame(APP->window->loadSvg(asset::plugin(pluginInstance, "res/Switch_Horizontal_0.svg")));
		addFrame(APP->window->loadSvg(asset::plugin(pluginInstance, "res/Switch_Horizontal_1.svg")));
	}
};

struct JwVerticalSwitch : SVGSwitch {
	JwVerticalSwitch() {
		addFrame(APP->window->loadSvg(asset::plugin(pluginInstance, "res/Switch_Vertical_0.svg")));
		addFrame(APP->window->loadSvg(asset::plugin(pluginInstance, "res/Switch_Vertical_1.svg")));
	}
};

struct BowlSwitch : SVGSwitch {
	BowlSwitch() {
		shadow->opacity = 0;
		addFrame(APP->window->loadSvg(asset::plugin(pluginInstance, "res/Bowl-no-food.svg")));
		addFrame(APP->window->loadSvg(asset::plugin(pluginInstance, "res/Bowl-food.svg")));
	}
};

////////////////////////////////////////////// PORTS //////////////////////////////////////////////

struct TinyPJ301MPort : SvgPort {
	TinyPJ301MPort() {
		setSvg(APP->window->loadSvg(asset::plugin(pluginInstance, "res/TinyPJ301M.svg")));
	}
};

struct Orange_TinyPJ301MPort : SvgPort {
	Orange_TinyPJ301MPort() {
		setSvg(APP->window->loadSvg(asset::plugin(pluginInstance, "res/TinyPJ301M_orange.svg")));
	}
};

struct Yellow_TinyPJ301MPort : SvgPort {
	Yellow_TinyPJ301MPort() {
		setSvg(APP->window->loadSvg(asset::plugin(pluginInstance, "res/TinyPJ301M_yellow.svg")));
	}
};

struct Purple_TinyPJ301MPort : SvgPort {
	Purple_TinyPJ301MPort() {
		setSvg(APP->window->loadSvg(asset::plugin(pluginInstance, "res/TinyPJ301M_purple.svg")));
	}
};

struct Blue_TinyPJ301MPort : SvgPort {
	Blue_TinyPJ301MPort() {
		setSvg(APP->window->loadSvg(asset::plugin(pluginInstance, "res/TinyPJ301M_blue.svg")));
	}
};

struct White_TinyPJ301MPort : SvgPort {
	White_TinyPJ301MPort() {
		setSvg(APP->window->loadSvg(asset::plugin(pluginInstance, "res/TinyPJ301M_white.svg")));
	}
};

////////////////////////////////////////////// LIGHTS //////////////////////////////////////////////

struct MyBlueValueLight : ModuleLightWidget {
	MyBlueValueLight() {
		firstLightId = 1;
		addBaseColor(nvgRGB(25, 150, 252));
	}
};

struct MyYellowValueLight : ModuleLightWidget {
	MyYellowValueLight() {
		firstLightId = 1;
		addBaseColor(nvgRGB(255, 243, 9));
	}
};

struct MyOrangeValueLight : ModuleLightWidget {
	MyOrangeValueLight() {
		firstLightId = 1;
		addBaseColor(nvgRGB(255, 151, 9));
	}
};

struct MyGreenValueLight : ModuleLightWidget {
	MyGreenValueLight() {
		firstLightId = 1;
		addBaseColor(nvgRGB(0, 200, 0));
	}
};

struct MyRedValueLight : ModuleLightWidget {
	MyRedValueLight() {
		firstLightId = 1;
		addBaseColor(nvgRGB(200, 0, 0));
	}
};

////////////////////////////////////////////// BUTTONS //////////////////////////////////////////////

struct RightMoveButton : SVGSwitch {
	RightMoveButton() {
		momentary = true;
		shadow->opacity = 0;
		addFrame(APP->window->loadSvg(asset::plugin(pluginInstance, "res/RightButton.svg")));
		addFrame(APP->window->loadSvg(asset::plugin(pluginInstance, "res/RightButtonDown.svg")));
	}
};

struct LeftMoveButton : SVGSwitch {
	LeftMoveButton() {
		momentary = true;
		shadow->opacity = 0;
		addFrame(APP->window->loadSvg(asset::plugin(pluginInstance, "res/LeftButton.svg")));
		addFrame(APP->window->loadSvg(asset::plugin(pluginInstance, "res/LeftButtonDown.svg")));
	}
};

struct DownMoveButton : SVGSwitch {
	DownMoveButton() {
		momentary = true;
		shadow->opacity = 0;
		addFrame(APP->window->loadSvg(asset::plugin(pluginInstance, "res/DownButton.svg")));
		addFrame(APP->window->loadSvg(asset::plugin(pluginInstance, "res/DownButtonDown.svg")));
	}
};

struct UpMoveButton : SVGSwitch {
	UpMoveButton() {
		momentary = true;
		shadow->opacity = 0;
		addFrame(APP->window->loadSvg(asset::plugin(pluginInstance, "res/UpButton.svg")));
		addFrame(APP->window->loadSvg(asset::plugin(pluginInstance, "res/UpButtonDown.svg")));
	}
};

struct RndMoveButton : SVGSwitch {
	RndMoveButton() {
		momentary = true;
		shadow->opacity = 0;
		addFrame(APP->window->loadSvg(asset::plugin(pluginInstance, "res/RndButton.svg")));
		addFrame(APP->window->loadSvg(asset::plugin(pluginInstance, "res/RndButtonDown.svg")));
	}
};

struct RepMoveButton : SVGSwitch {
	RepMoveButton() {
		momentary = true;
		shadow->opacity = 0;
		addFrame(APP->window->loadSvg(asset::plugin(pluginInstance, "res/RepButton.svg")));
		addFrame(APP->window->loadSvg(asset::plugin(pluginInstance, "res/RepButtonDown.svg")));
	}
};

struct TinyButton : SVGSwitch {
	TinyButton() {
		momentary = true;
		addFrame(APP->window->loadSvg(asset::plugin(pluginInstance, "res/TinyButtonUp.svg")));
		addFrame(APP->window->loadSvg(asset::plugin(pluginInstance, "res/TinyButtonDown.svg")));
	}
};

struct SmallButton : SVGSwitch {
	SmallButton() {
		momentary = true;
		addFrame(APP->window->loadSvg(asset::plugin(pluginInstance, "res/SmallButtonUp.svg")));
		addFrame(APP->window->loadSvg(asset::plugin(pluginInstance, "res/SmallButtonDown.svg")));
	}
};

////////////////////////////////////////////// SCREWS //////////////////////////////////////////////

struct Snowflake : SVGScrew {
	Snowflake() {
		sw->setSVG(APP->window->loadSvg(asset::plugin(pluginInstance, "res/SnowFlake.svg")));
		box.size = sw->box.size;
	}
};

struct WavHeadLogo : SVGScrew {
	WavHeadLogo() {
		sw->setSVG(APP->window->loadSvg(asset::plugin(pluginInstance, "res/WavHeadSmall.svg")));
		box.size = sw->box.size;
	}
};

struct Screw_J : SVGScrew {
	Screw_J() {
		sw->setSVG(APP->window->loadSvg(asset::plugin(pluginInstance, "res/Screw_J.svg")));
		box.size = sw->box.size;
	}
};

struct Screw_W : SVGScrew {
	Screw_W() {
		sw->setSVG(APP->window->loadSvg(asset::plugin(pluginInstance, "res/Screw_W.svg")));
		box.size = sw->box.size;
	}
};

struct CatScrew : SVGScrew {
	CatScrew() {
		sw->setSVG(APP->window->loadSvg(asset::plugin(pluginInstance, "res/Cat.svg")));
		box.size = sw->box.size;
	}
};

struct HairballScrew : SVGScrew {
	HairballScrew() {
		sw->setSVG(APP->window->loadSvg(asset::plugin(pluginInstance, "res/Hairball.svg")));
		box.size = sw->box.size;
	}
};

////////////////////////////////////////////// WIDGETS //////////////////////////////////////////////

extern Model *modelAdd5;
extern Model *modelBouncyBalls;
extern Model *modelSimpleClock;
extern Model *modelStr1ker;
extern Model *modelD1v1de;
extern Model *modelPres1t;
extern Model *modelMinMax;
extern Model *modelQuantizer;
extern Model *modelNoteSeq;
extern Model *modelNoteSeqFu;
extern Model *modelNoteSeq16;
extern Model *modelOnePattern;
extern Model *modelPatterns;
extern Model *modelWavHead;
extern Model *modelXYPad;
extern Model *modelFullScope;
extern Model *modelGridSeq;
extern Model *modelThingThing;
extern Model *modelCat;
extern Model *modelBlankPanel1hp;
extern Model *modelBlankPanelSmall;
extern Model *modelBlankPanelMedium;
extern Model *modelBlankPanelLarge;
extern Model *modelCoolBreeze;

inline int clampijw(int x, int minimum, int maximum) {
	return clamp(x, minimum, maximum);
}
inline float clampfjw(float x, float minimum, float maximum) {
	return fminf(fmaxf(x, minimum), maximum);
}
inline float rescalefjw(float x, float xMin, float xMax, float yMin, float yMax) {
	return yMin + (x - xMin) / (xMax - xMin) * (yMax - yMin);
}

<commit_msg>changed blue light background to white<commit_after>#pragma once
#include "rack.hpp"
#include "QuantizeUtils.cpp"
#define RIGHT_ARROW "▸"

using namespace rack;
extern Plugin *pluginInstance;

////////////////////////////////////////////// PANELS //////////////////////////////////////////////

struct BGPanel : Widget {
	Widget *panelBorder;
	NVGcolor color;

	BGPanel(NVGcolor _color) {
		panelBorder = new PanelBorder;
		color = _color;
		addChild(panelBorder);
	}

	void step() override {
		panelBorder->box.size = box.size;
		Widget::step();
	}

	void draw(const DrawArgs &args) override {
		nvgBeginPath(args.vg);
		nvgRect(args.vg, 0.0, 0.0, box.size.x, box.size.y);
		nvgFillColor(args.vg, color);
		nvgFill(args.vg);
		Widget::draw(args);
	}
};

////////////////////////////////////////////// LABELS //////////////////////////////////////////////

struct CenteredLabel : Widget {
	std::string text;
	int fontSize;
	CenteredLabel(int _fontSize = 12) {
		fontSize = _fontSize;
		box.size.y = BND_WIDGET_HEIGHT;
	}
	void draw(const DrawArgs &args) override {
		nvgTextAlign(args.vg, NVG_ALIGN_CENTER);
		nvgFillColor(args.vg, nvgRGB(25, 150, 252));
		nvgFontSize(args.vg, fontSize);
		nvgText(args.vg, box.pos.x, box.pos.y, text.c_str(), NULL);
	}
};

////////////////////////////////////////////// KNOBS //////////////////////////////////////////////

struct SmallWhiteKnob : RoundKnob {
	CenteredLabel* linkedLabel = NULL;
	Module* linkedModule = NULL;

	SmallWhiteKnob() {
		shadow->opacity = 0;
		setSVG(APP->window->loadSvg(asset::plugin(pluginInstance, "res/SmallWhiteKnob.svg")));
	}

	void connectLabel(CenteredLabel* label, Module* module) {
		linkedLabel = label;
		linkedModule = module;
		if (linkedModule && linkedLabel) {
			linkedLabel->text = formatCurrentValue();
		}
	}

	void onChange(const event::Change &e) override {
		RoundKnob::onChange(e);
		if (linkedModule && linkedLabel) {
			linkedLabel->text = formatCurrentValue();
		}
	}

	virtual std::string formatCurrentValue() {
		if(paramQuantity != NULL){
			return std::to_string(static_cast<unsigned int>(paramQuantity->getValue()));
		}
		return "";
	}
};

struct NoteKnob : SmallWhiteKnob {
	QuantizeUtils *quantizeUtils;
	NoteKnob(){
		snap = true;
	}
	std::string formatCurrentValue() override {
		if(paramQuantity != NULL){
			return quantizeUtils->noteName(int(paramQuantity->getValue()));
		}
		return "";
	}
};

struct ScaleKnob : SmallWhiteKnob {
	QuantizeUtils *quantizeUtils;
	ScaleKnob(){
		snap = true;
	}
	std::string formatCurrentValue() override {
		if(paramQuantity != NULL){
			return quantizeUtils->scaleName(int(paramQuantity->getValue()));
		}
		return "";
	}
};

struct JwSmallSnapKnob : SmallWhiteKnob {
	JwSmallSnapKnob() {
		snap = true;
	}
};

struct JwTinyKnob : RoundKnob {
	JwTinyKnob() {
		setSVG(APP->window->loadSvg(asset::plugin(pluginInstance, "res/TinyWhiteKnob.svg")));
	}
};

struct JwTinyGrayKnob : RoundKnob {
	JwTinyGrayKnob() {
		setSVG(APP->window->loadSvg(asset::plugin(pluginInstance, "res/TinyWhiteGrayKnob.svg")));
	}
};

struct BPMPartKnob : JwSmallSnapKnob {
	BPMPartKnob(){}
};

////////////////////////////////////////////// SWITCHES //////////////////////////////////////////////

struct JwHorizontalSwitch : SVGSwitch {
	JwHorizontalSwitch() {
		addFrame(APP->window->loadSvg(asset::plugin(pluginInstance, "res/Switch_Horizontal_0.svg")));
		addFrame(APP->window->loadSvg(asset::plugin(pluginInstance, "res/Switch_Horizontal_1.svg")));
	}
};

struct JwVerticalSwitch : SVGSwitch {
	JwVerticalSwitch() {
		addFrame(APP->window->loadSvg(asset::plugin(pluginInstance, "res/Switch_Vertical_0.svg")));
		addFrame(APP->window->loadSvg(asset::plugin(pluginInstance, "res/Switch_Vertical_1.svg")));
	}
};

struct BowlSwitch : SVGSwitch {
	BowlSwitch() {
		shadow->opacity = 0;
		addFrame(APP->window->loadSvg(asset::plugin(pluginInstance, "res/Bowl-no-food.svg")));
		addFrame(APP->window->loadSvg(asset::plugin(pluginInstance, "res/Bowl-food.svg")));
	}
};

////////////////////////////////////////////// PORTS //////////////////////////////////////////////

struct TinyPJ301MPort : SvgPort {
	TinyPJ301MPort() {
		setSvg(APP->window->loadSvg(asset::plugin(pluginInstance, "res/TinyPJ301M.svg")));
	}
};

struct Orange_TinyPJ301MPort : SvgPort {
	Orange_TinyPJ301MPort() {
		setSvg(APP->window->loadSvg(asset::plugin(pluginInstance, "res/TinyPJ301M_orange.svg")));
	}
};

struct Yellow_TinyPJ301MPort : SvgPort {
	Yellow_TinyPJ301MPort() {
		setSvg(APP->window->loadSvg(asset::plugin(pluginInstance, "res/TinyPJ301M_yellow.svg")));
	}
};

struct Purple_TinyPJ301MPort : SvgPort {
	Purple_TinyPJ301MPort() {
		setSvg(APP->window->loadSvg(asset::plugin(pluginInstance, "res/TinyPJ301M_purple.svg")));
	}
};

struct Blue_TinyPJ301MPort : SvgPort {
	Blue_TinyPJ301MPort() {
		setSvg(APP->window->loadSvg(asset::plugin(pluginInstance, "res/TinyPJ301M_blue.svg")));
	}
};

struct White_TinyPJ301MPort : SvgPort {
	White_TinyPJ301MPort() {
		setSvg(APP->window->loadSvg(asset::plugin(pluginInstance, "res/TinyPJ301M_white.svg")));
	}
};

////////////////////////////////////////////// LIGHTS //////////////////////////////////////////////

struct MyBlueValueLight : ModuleLightWidget {
	MyBlueValueLight() {
		firstLightId = 1;
		this->bgColor = nvgRGB(255, 255, 255);
		addBaseColor(nvgRGB(25, 150, 252));
	}
};

struct MyYellowValueLight : ModuleLightWidget {
	MyYellowValueLight() {
		firstLightId = 1;
		addBaseColor(nvgRGB(255, 243, 9));
	}
};

struct MyOrangeValueLight : ModuleLightWidget {
	MyOrangeValueLight() {
		firstLightId = 1;
		addBaseColor(nvgRGB(255, 151, 9));
	}
};

struct MyGreenValueLight : ModuleLightWidget {
	MyGreenValueLight() {
		firstLightId = 1;
		addBaseColor(nvgRGB(0, 200, 0));
	}
};

struct MyRedValueLight : ModuleLightWidget {
	MyRedValueLight() {
		firstLightId = 1;
		addBaseColor(nvgRGB(200, 0, 0));
	}
};

////////////////////////////////////////////// BUTTONS //////////////////////////////////////////////

struct RightMoveButton : SVGSwitch {
	RightMoveButton() {
		momentary = true;
		shadow->opacity = 0;
		addFrame(APP->window->loadSvg(asset::plugin(pluginInstance, "res/RightButton.svg")));
		addFrame(APP->window->loadSvg(asset::plugin(pluginInstance, "res/RightButtonDown.svg")));
	}
};

struct LeftMoveButton : SVGSwitch {
	LeftMoveButton() {
		momentary = true;
		shadow->opacity = 0;
		addFrame(APP->window->loadSvg(asset::plugin(pluginInstance, "res/LeftButton.svg")));
		addFrame(APP->window->loadSvg(asset::plugin(pluginInstance, "res/LeftButtonDown.svg")));
	}
};

struct DownMoveButton : SVGSwitch {
	DownMoveButton() {
		momentary = true;
		shadow->opacity = 0;
		addFrame(APP->window->loadSvg(asset::plugin(pluginInstance, "res/DownButton.svg")));
		addFrame(APP->window->loadSvg(asset::plugin(pluginInstance, "res/DownButtonDown.svg")));
	}
};

struct UpMoveButton : SVGSwitch {
	UpMoveButton() {
		momentary = true;
		shadow->opacity = 0;
		addFrame(APP->window->loadSvg(asset::plugin(pluginInstance, "res/UpButton.svg")));
		addFrame(APP->window->loadSvg(asset::plugin(pluginInstance, "res/UpButtonDown.svg")));
	}
};

struct RndMoveButton : SVGSwitch {
	RndMoveButton() {
		momentary = true;
		shadow->opacity = 0;
		addFrame(APP->window->loadSvg(asset::plugin(pluginInstance, "res/RndButton.svg")));
		addFrame(APP->window->loadSvg(asset::plugin(pluginInstance, "res/RndButtonDown.svg")));
	}
};

struct RepMoveButton : SVGSwitch {
	RepMoveButton() {
		momentary = true;
		shadow->opacity = 0;
		addFrame(APP->window->loadSvg(asset::plugin(pluginInstance, "res/RepButton.svg")));
		addFrame(APP->window->loadSvg(asset::plugin(pluginInstance, "res/RepButtonDown.svg")));
	}
};

struct TinyButton : SVGSwitch {
	TinyButton() {
		momentary = true;
		addFrame(APP->window->loadSvg(asset::plugin(pluginInstance, "res/TinyButtonUp.svg")));
		addFrame(APP->window->loadSvg(asset::plugin(pluginInstance, "res/TinyButtonDown.svg")));
	}
};

struct SmallButton : SVGSwitch {
	SmallButton() {
		momentary = true;
		addFrame(APP->window->loadSvg(asset::plugin(pluginInstance, "res/SmallButtonUp.svg")));
		addFrame(APP->window->loadSvg(asset::plugin(pluginInstance, "res/SmallButtonDown.svg")));
	}
};

////////////////////////////////////////////// SCREWS //////////////////////////////////////////////

struct Snowflake : SVGScrew {
	Snowflake() {
		sw->setSVG(APP->window->loadSvg(asset::plugin(pluginInstance, "res/SnowFlake.svg")));
		box.size = sw->box.size;
	}
};

struct WavHeadLogo : SVGScrew {
	WavHeadLogo() {
		sw->setSVG(APP->window->loadSvg(asset::plugin(pluginInstance, "res/WavHeadSmall.svg")));
		box.size = sw->box.size;
	}
};

struct Screw_J : SVGScrew {
	Screw_J() {
		sw->setSVG(APP->window->loadSvg(asset::plugin(pluginInstance, "res/Screw_J.svg")));
		box.size = sw->box.size;
	}
};

struct Screw_W : SVGScrew {
	Screw_W() {
		sw->setSVG(APP->window->loadSvg(asset::plugin(pluginInstance, "res/Screw_W.svg")));
		box.size = sw->box.size;
	}
};

struct CatScrew : SVGScrew {
	CatScrew() {
		sw->setSVG(APP->window->loadSvg(asset::plugin(pluginInstance, "res/Cat.svg")));
		box.size = sw->box.size;
	}
};

struct HairballScrew : SVGScrew {
	HairballScrew() {
		sw->setSVG(APP->window->loadSvg(asset::plugin(pluginInstance, "res/Hairball.svg")));
		box.size = sw->box.size;
	}
};

////////////////////////////////////////////// WIDGETS //////////////////////////////////////////////

extern Model *modelAdd5;
extern Model *modelBouncyBalls;
extern Model *modelSimpleClock;
extern Model *modelStr1ker;
extern Model *modelD1v1de;
extern Model *modelPres1t;
extern Model *modelMinMax;
extern Model *modelQuantizer;
extern Model *modelNoteSeq;
extern Model *modelNoteSeqFu;
extern Model *modelNoteSeq16;
extern Model *modelOnePattern;
extern Model *modelPatterns;
extern Model *modelWavHead;
extern Model *modelXYPad;
extern Model *modelFullScope;
extern Model *modelGridSeq;
extern Model *modelThingThing;
extern Model *modelCat;
extern Model *modelBlankPanel1hp;
extern Model *modelBlankPanelSmall;
extern Model *modelBlankPanelMedium;
extern Model *modelBlankPanelLarge;
extern Model *modelCoolBreeze;

inline int clampijw(int x, int minimum, int maximum) {
	return clamp(x, minimum, maximum);
}
inline float clampfjw(float x, float minimum, float maximum) {
	return fminf(fmaxf(x, minimum), maximum);
}
inline float rescalefjw(float x, float xMin, float xMax, float yMin, float yMax) {
	return yMin + (x - xMin) / (xMax - xMin) * (yMax - yMin);
}

<|endoftext|>


<commit_before>#include "MPBuilder.h"

MPBuilder::MPBuilder(const BMessage &msg, const BMessenger &msgr, BString windowTitle, int ideaID)
	:	BWindow(BRect(100, 100, 900, 700), windowTitle, B_TITLED_WINDOW, B_ASYNCHRONOUS_CONTROLS | B_AUTO_UPDATE_SIZE_LIMITS, B_CURRENT_WORKSPACE), launcherMessage(msg), launcherMessenger(msgr)
{
	// initialize controls
	BRect r = Bounds();
	r.bottom = r.bottom - 50;
	availableThoughtListView = new BListView(BRect(10, 10, 100, 30), NULL, B_MULTIPLE_SELECTION_LIST, B_FOLLOW_ALL, B_WILL_DRAW);
	orderedThoughtListView = new BListView(BRect(10, 10, 100, 30), NULL, B_MULTIPLE_SELECTION_LIST, B_FOLLOW_ALL, B_WILL_DRAW);
	rightButton = new BButton(BRect(10, 10, 90, 35), NULL, ">", new BMessage(MOVE_RIGHT), B_FOLLOW_NONE, B_WILL_DRAW);
	leftButton = new BButton(BRect(10, 10, 90, 35), NULL, "<", new BMessage(MOVE_LEFT), B_FOLLOW_NONE, B_WILL_DRAW);
	topButton = new BButton(BRect(10, 10, 90, 35), NULL, "TOP", new BMessage(MOVE_TOP), B_FOLLOW_NONE, B_WILL_DRAW);
	upButton = new BButton(BRect(10, 10, 90, 35), NULL, "UP", new BMessage(MOVE_UP), B_FOLLOW_NONE, B_WILL_DRAW)l
	downButton = new BButton(BRect(10, 10, 90, 35), NULL, "DOWN", new BMessage(MOVE_DOWN), B_FOLLOW_NONE, B_WILL_DRAW);
	bottomButton = new BButton(BRect(10, 10, 90, 35), NULL, "BOTTOM", new BMessage(MOVE_BOTTOM), B_FOLLOW_NONE, B_WILL_DRAW);
	backView = new BView(Bounds(), "backview", B_FOLLOW_ALL, B_WILL_DRAW);
	backView->SetViewColor(ui_color(B_PANEL_BACKGROUND_COLOR));
	AddChild(backView);
	backView->SetLayout(new BGroupLayout(B_HORIZONTAL, 0.0));
	backView->AddChild(BGridLayoutBuilder()
		.Add(new BuilderMenu(), 0, 0)
		.Add(new BScrollView("scroll_available", availableThoughtListView, B_FOLLOW_ALL_SIDES, 0, false, true, B_FANCY_BORDER), 0, 1)
		.SetInsets(0, 0, 0, 0)
	);

	currentideaID = ideaID; // pass current idea id selected to builder window to use

	mpdb = OpenSqliteDB(); // open mpdb db
	if(mpdb == NULL) // if db doesn't exist
	{
		eAlert = new ErrorAlert("1.21 Sql Error: Sql DB was not opened properly");
		eAlert->Launch();
	}
}
void MPBuilder::MessageReceived(BMessage* msg)
{
	switch(msg->what)
	{
		default:
		{
			BWindow::MessageReceived(msg);
			break;
		}
	}
}
bool MPBuilder::QuitRequested(void)
{
	// on quit, show launcher with message
	launcherMessage.MakeEmpty();
	launcherMessage.AddInt64("showLauncher", 1);
	launcherMessenger.SendMessage(&launcherMessage);
	return true;
}
<commit_msg>working on mpbuilder layout<commit_after>#include "MPBuilder.h"

MPBuilder::MPBuilder(const BMessage &msg, const BMessenger &msgr, BString windowTitle, int ideaID)
	:	BWindow(BRect(100, 100, 900, 700), windowTitle, B_TITLED_WINDOW, B_ASYNCHRONOUS_CONTROLS | B_AUTO_UPDATE_SIZE_LIMITS, B_CURRENT_WORKSPACE), launcherMessage(msg), launcherMessenger(msgr)
{
	// initialize controls
	BRect r = Bounds();
	r.bottom = r.bottom - 50;
	availableThoughtListView = new BListView(BRect(10, 10, 100, 30), NULL, B_MULTIPLE_SELECTION_LIST, B_FOLLOW_ALL, B_WILL_DRAW);
	orderedThoughtListView = new BListView(BRect(10, 10, 100, 30), NULL, B_MULTIPLE_SELECTION_LIST, B_FOLLOW_ALL, B_WILL_DRAW);
	rightButton = new BButton(BRect(10, 10, 90, 35), NULL, ">", new BMessage(MOVE_RIGHT), B_FOLLOW_NONE, B_WILL_DRAW);
	leftButton = new BButton(BRect(10, 10, 90, 35), NULL, "<", new BMessage(MOVE_LEFT), B_FOLLOW_NONE, B_WILL_DRAW);
	topButton = new BButton(BRect(10, 10, 90, 35), NULL, "TOP", new BMessage(MOVE_TOP), B_FOLLOW_NONE, B_WILL_DRAW);
	upButton = new BButton(BRect(10, 10, 90, 35), NULL, "UP", new BMessage(MOVE_UP), B_FOLLOW_NONE, B_WILL_DRAW);
	downButton = new BButton(BRect(10, 10, 90, 35), NULL, "DOWN", new BMessage(MOVE_DOWN), B_FOLLOW_NONE, B_WILL_DRAW);
	bottomButton = new BButton(BRect(10, 10, 90, 35), NULL, "BOTTOM", new BMessage(MOVE_BOTTOM), B_FOLLOW_NONE, B_WILL_DRAW);
	backView = new BView(Bounds(), "backview", B_FOLLOW_ALL, B_WILL_DRAW);
	backView->SetViewColor(ui_color(B_PANEL_BACKGROUND_COLOR));
	AddChild(backView);
	backView->SetLayout(new BGroupLayout(B_HORIZONTAL, 0.0));
	backView->AddChild(BGridLayoutBuilder()
		.Add(new BuilderMenu(), 0, 0)
		.Add(new BScrollView("scroll_available", availableThoughtListView, B_FOLLOW_ALL_SIDES, 0, false, true, B_FANCY_BORDER), 0, 1)
		.SetInsets(0, 0, 0, 0)
	);

	currentideaID = ideaID; // pass current idea id selected to builder window to use

	mpdb = OpenSqliteDB(); // open mpdb db
	if(mpdb == NULL) // if db doesn't exist
	{
		eAlert = new ErrorAlert("1.21 Sql Error: Sql DB was not opened properly");
		eAlert->Launch();
	}
}
void MPBuilder::MessageReceived(BMessage* msg)
{
	switch(msg->what)
	{
		default:
		{
			BWindow::MessageReceived(msg);
			break;
		}
	}
}
bool MPBuilder::QuitRequested(void)
{
	// on quit, show launcher with message
	launcherMessage.MakeEmpty();
	launcherMessage.AddInt64("showLauncher", 1);
	launcherMessenger.SendMessage(&launcherMessage);
	return true;
}
<|endoftext|>


<commit_before>// IsingWL.cpp -- WangLandau convergence of the Ising model
// Greg Brown (gbrown@fsu.edu,browngrg@comcast.net)

#include"MC_WangLandau.hpp"
#include"WL_Walker.hpp"
#include"../mfia/Mfia_Hamiltonian.hpp"
#include"../ehmodel/EHModel_Hamiltonian.hpp"
#include"MPI_Struct.hpp"
#include"Random.hpp"
#include"EMX_Measure.hpp"
#include"Null_Measure.hpp"
#include"ProgramOptions.hpp"

#include<stdio.h>
#include<ctime>
#include<algorithm>

template<typename HAMILTON, typename MEASURE>
void WangLandauDriver(ProgramOptions& options, int& argc, char* argv[])
{

   //  Get basic MPI information
   MPI_Struct world;
   world = MPI_Struct::world();
#  ifdef USE_MPI
   MPI_Comm_rank(world.comm,&world.iproc);
   MPI_Comm_size(world.comm,&world.nproc);
#  endif

   bool verbose = options.get_value<bool>("verbose") && (world.iproc==0);
   if(verbose) std::cout << __FILE__ << ":" << __LINE__ << " Construction objects" << std::endl;

   // Construct a hamiltonian object
   HAMILTON hamilton;
   hamilton.add_options(options);

   // Construct the sampling object
   MC_WangLandau simulation;
   simulation.add_options(options);

   typedef WL_Walker<typename HAMILTON::Config,typename HAMILTON::Observables> Walker;
   std::vector<Walker> walkerpool(1);

   // The measurement object
   // EMX_Measure measure_obj;
   MEASURE measure_obj;

   // Get parameters
   if(verbose) std::cout << __FILE__ << ":" << __LINE__ << " Parsing parameters" << std::endl;
   options.parse_command_line(argc,argv);
   if( options.get_value<bool>("help") ) return;

   // seed the random number geneator
   if(verbose) std::cout << __FILE__ << ":" << __LINE__ << " Creating random number generator" << std::endl;
   simulation.urng.seed( ParallelSeed(SeedFromClock()) );
   bool rng_output = false;
   bool rng_failed = RNGTestMoments(simulation.urng,rng_output,std::cout);
   if( false && rng_failed )
      std::cout << __FILE__ << ":" << __LINE__ << "Problem detected with random number generator (returns 1?)" << std::endl;

   // Initialize objects based on ProgramOptions
   if(verbose) std::cout << __FILE__ << ":" << __LINE__ << " Call Init routines" << std::endl;
   hamilton.init(verbose);
   hamilton.initial(walkerpool[0].sigma);
   simulation.init(hamilton,walkerpool,verbose);
   measure_obj.init(simulation);

   // Construct a representation of the model
   // This includes the "microscopic" configuration sigma_i
   // and the macroscopic quantities like magnetization and energy
   if(verbose) std::cout << __FILE__ << ":" << __LINE__ << " Beginning simulation" << std::endl;
   simulation.DoConverge(hamilton,walkerpool,measure_obj);

   if(verbose) std::cout << __FILE__ << ":" << __LINE__ << " Saving options" << std::endl;
   options.write();
}

int main(int argc, char* argv[])
{
   const bool very_verbose = true;
   time_t start_time_main;
   if( very_verbose )
   {
      std::cout << "cmdline:";
      for(int i=0; i<argc; i++) std::cout << " " << argv[i];
      std::cout << std::endl;
      time(&start_time_main);
      struct tm * timeinfo = localtime(&start_time_main);
      std::cout << "start time = " << asctime(timeinfo); // << std::endl;
      int pid = 0;
      if(true) pid = getpid();
      std::cout << "process id = " << pid << std::endl;
   }

   //  Get basic MPI information
   MPI_Struct world;
#  ifdef USE_MPI
   MPI_Init(&argc,&argv);
   world = MPI_Struct::world();
#  endif

   ProgramOptions options("caledonia","Monte Carlo simulations");
   char model_name[128] = "ising";
   char sim_name[128] = "wanglandau";
   options.add_option("model","Hamiltonian type", ' ', model_name);
   options.add_option("sim",  "Monte Carlo simulation type", ' ', sim_name);
   options.parse_command_line2(argc,argv);
   if( strcmp(sim_name,"wanglandau")==0 )
   {
      if( strcmp(model_name,"ising")==0 )   {  WangLandauDriver<Mfia_Hamiltonian,EMX_Measure>(options,argc,argv); }
      else if( strcmp(model_name,"ehmodel")==0 ) {  WangLandauDriver<EHModel_Hamiltonian,EMX_Measure>(options,argc,argv); }
      else { if(world.iproc==0) std::cout << "model \"" << model_name << "\" not recognized for \"" << sim_name << "\"" << std::endl; }
   }

#  ifdef USE_MPI
   MPI_Finalize();
#  endif

   time_t stop_time_main;
   if( very_verbose )
   {
      time(&stop_time_main);
      double secs = difftime(stop_time_main,start_time_main);
      clock_t tics = clock();
      double psecs = static_cast<double>(tics)/static_cast<double>(CLOCKS_PER_SEC);
      struct tm* timeinfo = localtime(&stop_time_main);
      std::cout << "end time = " << asctime(timeinfo); // << std::endl;
      std::cout << "wall time = " << secs << std::endl;
      std::cout << "process time = " << psecs << std::endl;
#     if 1
      int tSize = 0, resident = 0, share = 0;   // In kilobytes
      if(true)
      {
         std::ifstream buffer("/proc/self/statm");
         buffer >> tSize >> resident >> share;
         buffer.close();
         long page_size_kb = sysconf(_SC_PAGE_SIZE) / 1024; // in case x86-64 is configured to use 2MB pages
         resident = resident * page_size_kb;
         share = share * page_size_kb;
         std::cout << "resident memory = " << resident << " KBytes" << std::endl;
      }
#     endif
   }

}
<commit_msg>Moving towards factory<commit_after>// IsingWL.cpp -- WangLandau convergence of the Ising model
// Greg Brown (gbrown@fsu.edu,browngrg@comcast.net)

#include"MC_WangLandau.hpp"
#include"WL_Walker.hpp"
#include"../mfia/Mfia_Hamiltonian.hpp"
#include"../ehmodel/EHModel_Hamiltonian.hpp"
#include"MPI_Struct.hpp"
#include"Random.hpp"
#include"EMX_Measure.hpp"
#include"Null_Measure.hpp"
#include"ProgramOptions.hpp"

#include<stdio.h>
#include<ctime>
#include<algorithm>

class CaledoniaDriver
{
   public:
      virtual void DoCalculation(ProgramOptions& options, int& argc, char* argv[] ) = 0;
};

template<typename HAMILTON, typename MEASURE>
class WangLandauDriver : public CaledoniaDriver
{
public:
   void DoCalculation(ProgramOptions& options, int& argc, char* argv[]);
};

template<typename HAMILTON, typename MEASURE>
void WangLandauDriver<HAMILTON,MEASURE>::DoCalculation(ProgramOptions& options, int& argc, char* argv[])
{
   //  Get basic MPI information
   MPI_Struct world;
   world = MPI_Struct::world();
#  ifdef USE_MPI
   MPI_Comm_rank(world.comm,&world.iproc);
   MPI_Comm_size(world.comm,&world.nproc);
#  endif

   bool verbose = options.get_value<bool>("verbose") && (world.iproc==0);
   if(verbose) std::cout << __FILE__ << ":" << __LINE__ << " Construction objects" << std::endl;

   // Construct a hamiltonian object
   HAMILTON hamilton;
   hamilton.add_options(options);

   // Construct the sampling object
   MC_WangLandau simulation;
   simulation.add_options(options);

   typedef WL_Walker<typename HAMILTON::Config,typename HAMILTON::Observables> Walker;
   std::vector<Walker> walkerpool(1);

   // The measurement object
   // EMX_Measure measure_obj;
   MEASURE measure_obj;

   // Get parameters
   if(verbose) std::cout << __FILE__ << ":" << __LINE__ << " Parsing parameters" << std::endl;
   options.parse_command_line(argc,argv);
   if( options.get_value<bool>("help") ) return;

   // seed the random number geneator
   if(verbose) std::cout << __FILE__ << ":" << __LINE__ << " Creating random number generator" << std::endl;
   simulation.urng.seed( ParallelSeed(SeedFromClock()) );
   bool rng_output = false;
   bool rng_failed = RNGTestMoments(simulation.urng,rng_output,std::cout);
   if( false && rng_failed )
      std::cout << __FILE__ << ":" << __LINE__ << "Problem detected with random number generator (returns 1?)" << std::endl;

   // Initialize objects based on ProgramOptions
   if(verbose) std::cout << __FILE__ << ":" << __LINE__ << " Call Init routines" << std::endl;
   hamilton.init(verbose);
   hamilton.initial(walkerpool[0].sigma);
   simulation.init(hamilton,walkerpool,verbose);
   measure_obj.init(simulation);

   // Construct a representation of the model
   // This includes the "microscopic" configuration sigma_i
   // and the macroscopic quantities like magnetization and energy
   if(verbose) std::cout << __FILE__ << ":" << __LINE__ << " Beginning simulation" << std::endl;
   simulation.DoConverge(hamilton,walkerpool,measure_obj);

   if(verbose) std::cout << __FILE__ << ":" << __LINE__ << " Saving options" << std::endl;
   options.write();
}

int main(int argc, char* argv[])
{
   const bool very_verbose = true;
   time_t start_time_main;
   if( very_verbose )
   {
      std::cout << "cmdline:";
      for(int i=0; i<argc; i++) std::cout << " " << argv[i];
      std::cout << std::endl;
      time(&start_time_main);
      struct tm * timeinfo = localtime(&start_time_main);
      std::cout << "start time = " << asctime(timeinfo); // << std::endl;
      int pid = 0;
      if(true) pid = getpid();
      std::cout << "process id = " << pid << std::endl;
   }

   //  Get basic MPI information
   MPI_Struct world;
#  ifdef USE_MPI
   MPI_Init(&argc,&argv);
   world = MPI_Struct::world();
#  endif

   CaledoniaDriver* Driver = 0;
   ProgramOptions options("caledonia","Monte Carlo simulations");
   char model_name[128] = "ising";
   char sim_name[128] = "wanglandau";
   options.add_option("model","Hamiltonian type", ' ', model_name);
   options.add_option("sim",  "Monte Carlo simulation type", ' ', sim_name);
   options.parse_command_line2(argc,argv);
   if( strcmp(sim_name,"wanglandau")==0 )
   {
      if( strcmp(model_name,"ising")==0 )   { Driver = new WangLandauDriver<Mfia_Hamiltonian,EMX_Measure>(); }
      else if( strcmp(model_name,"ehmodel")==0 ) { Driver = new  WangLandauDriver<EHModel_Hamiltonian,EMX_Measure>(); }
      else { if(world.iproc==0) std::cout << "model \"" << model_name << "\" not recognized for \"" << sim_name << "\"" << std::endl; }
   }

   Driver->DoCalculation(options,argc,argv);

#  ifdef USE_MPI
   MPI_Finalize();
#  endif

   time_t stop_time_main;
   if( very_verbose )
   {
      time(&stop_time_main);
      double secs = difftime(stop_time_main,start_time_main);
      clock_t tics = clock();
      double psecs = static_cast<double>(tics)/static_cast<double>(CLOCKS_PER_SEC);
      struct tm* timeinfo = localtime(&stop_time_main);
      std::cout << "end time = " << asctime(timeinfo); // << std::endl;
      std::cout << "wall time = " << secs << std::endl;
      std::cout << "process time = " << psecs << std::endl;
#     if 1
      int tSize = 0, resident = 0, share = 0;   // In kilobytes
      if(true)
      {
         std::ifstream buffer("/proc/self/statm");
         buffer >> tSize >> resident >> share;
         buffer.close();
         long page_size_kb = sysconf(_SC_PAGE_SIZE) / 1024; // in case x86-64 is configured to use 2MB pages
         resident = resident * page_size_kb;
         share = share * page_size_kb;
         std::cout << "resident memory = " << resident << " KBytes" << std::endl;
      }
#     endif
   }

}
<|endoftext|>


<commit_before>#pragma once

#include <json.hpp>
using json = nlohmann::json;

#include <string>
#include <iostream>
#include <memory>
#include <vector>
#include <map>
#include <initializer_list>
using namespace std;

#include <cpr/cpr.h>
using namespace cpr;

#ifndef FORMAT_HEADER
#define FORMAT_HEADER
#include <fmt/format.h>
#include <fmt/format.cc>
#endif
using namespace fmt;

#include <range/v3/all.hpp>

#include <cryptlite/sha256.h>
#include <cryptlite/hmac.h>
using namespace cryptlite;

namespace api {
  typedef map<string, string> Map;

  enum class REQUEST_TYPE : size_t {
    GET,
    POST,
    PUT,
    DELETE
  };

  class Api {
  private:
    string api_key;
    string api_secret;
    string domain;
    Header public_header;
    Header user_header;

  public:
    explicit Api(string key, string secret);
    auto flatten_params(const Map &params) -> string;
    auto append_params(const string &url, const Map &params) -> string;
    auto append_params(const string &url, const string &params_str) -> string;
    auto response_tweak(Response response) -> json;
    auto request(REQUEST_TYPE method, const string &url, const Header &header) -> json;
    auto public_get(const string &url, const Map &params) -> json;
    auto public_get(const string &url) -> json;
    auto user_get(const string &url, const  Map &params) -> json;
    auto user_get(const string &url) -> json;
    auto signed_get(const string &url, const  Map &params) -> json;
    auto signed_get(const string &url) -> json;
    auto public_post(const string &url, const Map &params) -> json;
    auto public_post(const string &url) -> json;
    auto user_post(const string &url, const  Map &params) -> json;
    auto user_post(const string &url) -> json;
    auto signed_post(const string &url, const  Map &params) -> json;
    auto signed_post(const string &url) -> json;
    auto public_put(const string &url, const Map &params) -> json;
    auto public_put(const string &url) -> json;
    auto user_put(const string &url, const  Map &params) -> json;
    auto user_put(const string &url) -> json;
    auto signed_put(const string &url, const  Map &params) -> json;
    auto signed_put(const string &url) -> json;
    auto public_delete(const string &url, const Map &params) -> json;
    auto public_delete(const string &url) -> json;
    auto user_delete(const string &url, const  Map &params) -> json;
    auto user_delete(const string &url) -> json;
    auto signed_delete(const string &url, const  Map &params) -> json;
    auto signed_delete(const string &url) -> json;
  };

  Api::Api(string key, string secret): api_key(key), api_secret(secret) {
    this->domain = "https://www.binance.com";
    this->public_header = {
      { "User-Agent", "Mozilla/4.0 (compatible; Node Binance API)" },
      { "accept", "application/json" },
      { "Content-Type", "application/x-www-form-urlencoded" }
    };
    this->user_header = {
      { "User-Agent", "Mozilla/4.0 (compatible; Node Binance API)" },
      { "accept", "application/json" },
      { "Content-Type", "application/x-www-form-urlencoded" },
      { "X-MBX-APIKEY", format("{}", this->api_key) }
    };
  }

  auto Api::flatten_params(const Map &params) -> string {
    vector<string> params_vec = params
      | ranges::view::transform([](const auto &pair) {
          return format("{0}={1}", pair.first, pair.second);
        });
    return params_vec | ranges::view::join('&');
  }

  auto Api::append_params(const string &url, const Map &params) -> string {
    auto params_str = flatten_params(params);
    if (params_str.empty()) {
      return url;
    } else {
      return format("{0}?{1}", url, params_str);
    }
  }

  auto Api::append_params(const string &url, const string &params_str) -> string {
    if (params_str.empty()) {
      return url;
    } else {
      return format("{0}?{1}", url, params_str);
    }
  }

  auto Api::response_tweak(Response response) -> json {
    if (response.status_code < 400) {
      return nlohmann::json::parse(response.text);
    } else {
      cout << response.status_code << " " << response.text << endl;
      return nullptr;
    }
  }

  auto Api::request(REQUEST_TYPE method, const string &url, const Header &header) -> json {
    Session session;
    session.SetUrl(Url{ format("{0}{1}", this->domain, url) });
    session.SetHeader(header);
    session.SetVerifySsl(VerifySsl{ false });

    Response response;
    switch (method) {
    case REQUEST_TYPE::GET: {
      response = session.Get();
      break;
    }
    case REQUEST_TYPE::POST: {
      response = session.Post();
      break;
    }
    case REQUEST_TYPE::PUT: {
      response = session.Put();
      break;
    }
    case REQUEST_TYPE::DELETE: {
      response = session.Delete();
      break;
    }
    default:
      break;
    }

    return response_tweak(response);
  }

  auto Api::public_get(const string &url, const Map &params) -> json {
    return request(REQUEST_TYPE::GET, append_params(url, params), public_header);
  }

  auto Api::public_get(const string &url) -> json {
    return public_get(url, Map({}));
  }

  auto Api::user_get(const string &url, const  Map &params) -> json {
    return request(REQUEST_TYPE::GET, append_params(url, params), user_header);
  }

  auto Api::user_get(const string &url) -> json {
    return user_get(url, Map({}));
  }

  auto Api::signed_get(const string &url, const Map &params) -> json {
    auto params_str = flatten_params(params);
    auto signature = hmac<sha256>::calc_hex(params_str, api_secret);
    Map new_params = params;
    new_params["signature"] = signature;

    return request(REQUEST_TYPE::GET, append_params(url, new_params), user_header);
  }

  auto Api::signed_get(const string &url) -> json {
    return signed_get(url, Map({}));
  }

  auto Api::public_post(const string &url, const Map &params) -> json {
    return request(REQUEST_TYPE::POST, append_params(url, params), public_header);
  }

  auto Api::public_post(const string &url) -> json {
    return public_post(url, Map({}));
  }

  auto Api::user_post(const string &url, const Map &params) -> json {
    return request(REQUEST_TYPE::POST, append_params(url, params), user_header);
  }

  auto Api::user_post(const string &url) -> json {
    return user_post(url, Map({}));
  }

  auto Api::signed_post(const string &url, const Map &params) -> json {
    auto params_str = flatten_params(params);
    auto signature = hmac<sha256>::calc_hex(params_str, api_secret);
    Map new_params = params;
    new_params["signature"] = signature;

    return request(REQUEST_TYPE::POST, append_params(url, new_params), user_header);
  }

  auto Api::signed_post(const string &url) -> json {
    return request(REQUEST_TYPE::POST, url, user_header);
  }

  auto Api::public_put(const string &url, const Map &params) -> json {
    return request(REQUEST_TYPE::PUT, append_params(url, params), public_header);
  }

  auto Api::public_put(const string &url) -> json {
    return public_put(url, Map({}));
  }

  auto Api::user_put(const string &url, const Map &params) -> json {
    return request(REQUEST_TYPE::PUT, append_params(url, params), user_header);
  }

  auto Api::user_put(const string &url) -> json {
    return user_put(url, Map({}));
  }

  auto Api::signed_put(const string &url, const Map &params) -> json {
    auto params_str = flatten_params(params);
    auto signature = hmac<sha256>::calc_hex(params_str, api_secret);
    Map new_params = params;
    new_params["signature"] = signature;

    return request(REQUEST_TYPE::PUT, append_params(url, new_params), user_header);
  }

  auto Api::signed_put(const string &url) -> json {
    return signed_put(url, Map({}));
  }

  auto Api::public_delete(const string &url, const Map &params) -> json {
    return request(REQUEST_TYPE::DELETE, append_params(url, params), public_header);
  }

  auto Api::public_delete(const string &url) -> json {
    return public_delete(url, Map({}));
  }

  auto Api::user_delete(const string &url, const Map &params) -> json {
    return request(REQUEST_TYPE::DELETE, append_params(url, params), user_header);
  }

  auto Api::user_delete(const string &url) -> json {
    return user_delete(url, Map({}));
  }

  auto Api::signed_delete(const string &url, const Map &params) -> json {
    auto params_str = flatten_params(params);
    auto signature = hmac<sha256>::calc_hex(params_str, api_secret);
    Map new_params = params;
    new_params["signature"] = signature;

    return request(REQUEST_TYPE::DELETE, append_params(url, new_params), user_header);
  }

  auto Api::signed_delete(const string &url) -> json {
    return signed_delete(url, Map({}));
  }
}
<commit_msg>Extract add_signature<commit_after>#pragma once

#include <json.hpp>
using json = nlohmann::json;

#include <string>
#include <iostream>
#include <memory>
#include <vector>
#include <map>
#include <initializer_list>
using namespace std;

#include <cpr/cpr.h>
using namespace cpr;

#ifndef FORMAT_HEADER
#define FORMAT_HEADER
#include <fmt/format.h>
#include <fmt/format.cc>
#endif
using namespace fmt;

#include <range/v3/all.hpp>

#include <cryptlite/sha256.h>
#include <cryptlite/hmac.h>
using namespace cryptlite;

namespace api {
  typedef map<string, string> Map;

  enum class REQUEST_TYPE : size_t {
    GET,
    POST,
    PUT,
    DELETE
  };

  class Api {
  private:
    string api_key;
    string api_secret;
    string domain;
    Header public_header;
    Header user_header;

  public:
    explicit Api(string key, string secret);
    auto flatten_params(const Map &params) -> string;
    auto append_params(const string &url, const Map &params) -> string;
    auto append_params(const string &url, const string &params_str) -> string;
    auto response_tweak(Response response) -> json;
    auto request(REQUEST_TYPE method, const string &url, const Header &header) -> json;
    auto add_signature(const Map &params) -> Map;
    auto public_get(const string &url, const Map &params) -> json;
    auto public_get(const string &url) -> json;
    auto user_get(const string &url, const  Map &params) -> json;
    auto user_get(const string &url) -> json;
    auto signed_get(const string &url, const  Map &params) -> json;
    auto signed_get(const string &url) -> json;
    auto public_post(const string &url, const Map &params) -> json;
    auto public_post(const string &url) -> json;
    auto user_post(const string &url, const  Map &params) -> json;
    auto user_post(const string &url) -> json;
    auto signed_post(const string &url, const  Map &params) -> json;
    auto signed_post(const string &url) -> json;
    auto public_put(const string &url, const Map &params) -> json;
    auto public_put(const string &url) -> json;
    auto user_put(const string &url, const  Map &params) -> json;
    auto user_put(const string &url) -> json;
    auto signed_put(const string &url, const  Map &params) -> json;
    auto signed_put(const string &url) -> json;
    auto public_delete(const string &url, const Map &params) -> json;
    auto public_delete(const string &url) -> json;
    auto user_delete(const string &url, const  Map &params) -> json;
    auto user_delete(const string &url) -> json;
    auto signed_delete(const string &url, const  Map &params) -> json;
    auto signed_delete(const string &url) -> json;
  };

  Api::Api(string key, string secret): api_key(key), api_secret(secret) {
    this->domain = "https://www.binance.com";
    this->public_header = {
      { "User-Agent", "Mozilla/4.0 (compatible; Node Binance API)" },
      { "accept", "application/json" },
      { "Content-Type", "application/x-www-form-urlencoded" }
    };
    this->user_header = {
      { "User-Agent", "Mozilla/4.0 (compatible; Node Binance API)" },
      { "accept", "application/json" },
      { "Content-Type", "application/x-www-form-urlencoded" },
      { "X-MBX-APIKEY", format("{}", this->api_key) }
    };
  }

  auto Api::flatten_params(const Map &params) -> string {
    vector<string> params_vec = params
      | ranges::view::transform([](const auto &pair) {
          return format("{0}={1}", pair.first, pair.second);
        });
    return params_vec | ranges::view::join('&');
  }

  auto Api::append_params(const string &url, const Map &params) -> string {
    auto params_str = flatten_params(params);
    if (params_str.empty()) {
      return url;
    } else {
      return format("{0}?{1}", url, params_str);
    }
  }

  auto Api::append_params(const string &url, const string &params_str) -> string {
    if (params_str.empty()) {
      return url;
    } else {
      return format("{0}?{1}", url, params_str);
    }
  }

  auto Api::response_tweak(Response response) -> json {
    if (response.status_code < 400) {
      return nlohmann::json::parse(response.text);
    } else {
      cout << response.status_code << " " << response.text << endl;
      return nullptr;
    }
  }

  auto Api::add_signature(const Map &params) -> Map {
    auto params_str = flatten_params(params);
    auto signature = hmac<sha256>::calc_hex(params_str, this->api_secret);
    Map new_params = params;
    new_params["signature"] = signature;
    return new_params;
  }

  auto Api::request(REQUEST_TYPE method, const string &url, const Header &header) -> json {
    Session session;
    session.SetUrl(Url{ format("{0}{1}", this->domain, url) });
    session.SetHeader(header);
    session.SetVerifySsl(VerifySsl{ false });

    Response response;
    switch (method) {
    case REQUEST_TYPE::GET: {
      response = session.Get();
      break;
    }
    case REQUEST_TYPE::POST: {
      response = session.Post();
      break;
    }
    case REQUEST_TYPE::PUT: {
      response = session.Put();
      break;
    }
    case REQUEST_TYPE::DELETE: {
      response = session.Delete();
      break;
    }
    default:
      break;
    }

    return response_tweak(response);
  }

  auto Api::public_get(const string &url, const Map &params) -> json {
    return request(REQUEST_TYPE::GET, append_params(url, params), public_header);
  }

  auto Api::public_get(const string &url) -> json {
    return public_get(url, Map({}));
  }

  auto Api::user_get(const string &url, const  Map &params) -> json {
    return request(REQUEST_TYPE::GET, append_params(url, params), user_header);
  }

  auto Api::user_get(const string &url) -> json {
    return user_get(url, Map({}));
  }

  auto Api::signed_get(const string &url, const Map &params) -> json {
    return request(REQUEST_TYPE::GET, append_params(url, add_signature(params)), user_header);
  }

  auto Api::signed_get(const string &url) -> json {
    return signed_get(url, Map({}));
  }

  auto Api::public_post(const string &url, const Map &params) -> json {
    return request(REQUEST_TYPE::POST, append_params(url, params), public_header);
  }

  auto Api::public_post(const string &url) -> json {
    return public_post(url, Map({}));
  }

  auto Api::user_post(const string &url, const Map &params) -> json {
    return request(REQUEST_TYPE::POST, append_params(url, params), user_header);
  }

  auto Api::user_post(const string &url) -> json {
    return user_post(url, Map({}));
  }

  auto Api::signed_post(const string &url, const Map &params) -> json {
    return request(REQUEST_TYPE::POST, append_params(url, add_signature(params)), user_header);
  }

  auto Api::signed_post(const string &url) -> json {
    return request(REQUEST_TYPE::POST, url, user_header);
  }

  auto Api::public_put(const string &url, const Map &params) -> json {
    return request(REQUEST_TYPE::PUT, append_params(url, params), public_header);
  }

  auto Api::public_put(const string &url) -> json {
    return public_put(url, Map({}));
  }

  auto Api::user_put(const string &url, const Map &params) -> json {
    return request(REQUEST_TYPE::PUT, append_params(url, params), user_header);
  }

  auto Api::user_put(const string &url) -> json {
    return user_put(url, Map({}));
  }

  auto Api::signed_put(const string &url, const Map &params) -> json {
    return request(REQUEST_TYPE::PUT, append_params(url, add_signature(params)), user_header);
  }

  auto Api::signed_put(const string &url) -> json {
    return signed_put(url, Map({}));
  }

  auto Api::public_delete(const string &url, const Map &params) -> json {
    return request(REQUEST_TYPE::DELETE, append_params(url, params), public_header);
  }

  auto Api::public_delete(const string &url) -> json {
    return public_delete(url, Map({}));
  }

  auto Api::user_delete(const string &url, const Map &params) -> json {
    return request(REQUEST_TYPE::DELETE, append_params(url, params), user_header);
  }

  auto Api::user_delete(const string &url) -> json {
    return user_delete(url, Map({}));
  }

  auto Api::signed_delete(const string &url, const Map &params) -> json {
    return request(REQUEST_TYPE::DELETE, append_params(url, add_signature(params)), user_header);
  }

  auto Api::signed_delete(const string &url) -> json {
    return signed_delete(url, Map({}));
  }
}
<|endoftext|>


<commit_before>// janssonxx - C++ wrapper for jansson
//
// author: Sean Middleditch <sean@middleditch.us>
//
// janssonxx is free software; you can redistribute it and/or modify
// it under the terms of the MIT license. See LICENSE for details.

#if !defined(JANSSON_HPP)
#define JANSSON_HPP 1

#include <string>
#include <ostream>
#include <istream>
#include <sstream>
#include <cstdlib>

namespace json {
	// include Jansson C library into the json namespace
	#include <jansson.h>

	class Iterator;
	class Value;

	// implementation details; do not use directly
	namespace _private {
		class ElementProxy;
		class PropertyProxy;

		// base class for JSON value interface
		template <typename _Base>
		class ValueBase : public _Base {
		public:
			// empty constructor
			ValueBase() : _Base() {}

			// copy constructor
			ValueBase(const _Base& base) : _Base(base) {}

			// create reference to value
			ValueBase(json_t* json) : _Base(json) {}

			// assignment operator
			inline ValueBase& operator=(const Value& value);

			// check value type
			inline bool is_undefined() const;
			inline bool is_object() const;
			inline bool is_array() const;
			inline bool is_string() const;
			inline bool is_integer() const;
			inline bool is_real() const;
			inline bool is_number() const;
			inline bool is_true() const;
			inline bool is_false() const;
			inline bool is_boolean() const;
			inline bool is_null() const;

			// get size of array or object
			inline unsigned int size() const;

			// get value at array index (const version)
			inline const Value at(unsigned int index) const;

			inline const Value operator[](signed int index) const;
			inline const Value operator[](unsigned int index) const;
			inline const Value operator[](signed short index) const;
			inline const Value operator[](unsigned short index) const;
			inline const Value operator[](signed long index) const;
			inline const Value operator[](unsigned long index) const;

			// get value at array index (non-const version)
			inline ValueBase<ElementProxy> at(unsigned int index);

			inline ValueBase<ElementProxy> operator[](signed int index);
			inline ValueBase<ElementProxy> operator[](unsigned int index);
			inline ValueBase<ElementProxy> operator[](signed short index);
			inline ValueBase<ElementProxy> operator[](unsigned short index);
			inline ValueBase<ElementProxy> operator[](signed long index);
			inline ValueBase<ElementProxy> operator[](unsigned long index);

			// get object property (const version)
			inline const Value get(const char* key) const;

			inline const Value get(const std::string& key) const;
			inline const Value operator[](const char* key) const;
			inline const Value operator[](const std::string& key) const;

			// get object property (non-const version)
			inline ValueBase<PropertyProxy> get(const char* key);

			inline ValueBase<PropertyProxy> get(const std::string& key);
			inline ValueBase<PropertyProxy> operator[](const char* key);
			inline ValueBase<PropertyProxy> operator[](const std::string& key);

			// clear all array/object values
			inline void clear();

			// get value cast to specified type
			inline const char* as_cstring() const;
			inline std::string as_string() const;
			inline int as_integer() const;
			inline double as_real() const;
			inline double as_number() const;
			inline bool as_boolean() const;

			// set an object property (converts value to object is not one already)
			inline _Base& set_key(const char* key, const Value& value);

			inline _Base& set_key(const std::string& key, const Value& value);

			// set an array index (converts value to object is not one already)
			inline _Base& set_at(unsigned int index, const Value& value);

			// delete an object key
			inline _Base& del_key(const char* key);

			inline _Base& del_key(const std::string& key);

			// delete an item from an array by index
			inline _Base& del_at(unsigned int index);

			// insert an item into an array at a given index
			inline _Base& insert_at(unsigned int index, const Value& value);

			// write the value to a file
			inline int save_file(const char* path, int flags = 0) const;

			// write the value to a string (caller must deallocate with free()!)
			inline char* save_string(int flags = 0) const;
		};

		// represents any JSON value, private base
		class Basic {
		public:
			// construct new Value with an undefined value
			Basic() : _value(0) {}

			// copy constructor
			Basic(const Basic& value) : _value(json_incref(value._value)) {}

			// make a reference to an existing json_t value
			explicit Basic(json_t* value) : _value(json_incref(value)) {}

			// free Value resources
			inline ~Basic();

			// copy an existing Value
			inline Basic& operator=(const Basic& e);

			// get the underlying json_t
			inline json_t* as_json() const;

			// take ownership of a json_t (does not increase reference count)
			inline static Basic take_ownership(json_t* json);

		protected:
			// internal value pointer
			json_t* _value;
		};

		// proxies an array element
		class ElementProxy {
		public:
			// constructor
			ElementProxy(json_t* array, unsigned int index) : _array(array), _index(index) {}

			// assign to the proxied element
			inline ElementProxy& operator=(const Value& value);

			// get the proxied element
			inline json_t* as_json() const;

		private:
			// array object we wrap
			json_t* _array;

			// index of property
			unsigned int _index;
		};

		// proxies an object property
		class PropertyProxy {
		public:
			// constructor
			PropertyProxy(json_t* array, const char* key) : _object(array), _key(key) {}

			// assign to the proxied element
			inline PropertyProxy& operator=(const Value& value);

			// get the proxied element
			inline json_t* as_json() const;

		private:
			// array object we wrap
			json_t* _object;

			// key of property
			const char* _key;
		};

	} // namespace json::_private

	// represents any JSON value
	class Value : public _private::ValueBase<_private::Basic> {
	public:
		// construct Value from input
		explicit inline Value(const char* value);
		explicit inline Value(const std::string& value);
		explicit inline Value(bool value);
		explicit inline Value(signed int value);
		explicit inline Value(unsigned int value);
		explicit inline Value(signed short value);
		explicit inline Value(unsigned short value);
		explicit inline Value(signed long value);
		explicit inline Value(unsigned long value);
		explicit inline Value(float value);
		explicit inline Value(double value);

		// empty constructor
		Value() : _private::ValueBase<_private::Basic>() {}

		// copy constructor for base
		Value(const _private::Basic& value) : _private::ValueBase<_private::Basic>(value) {}

		// copy constructor for base
		Value(const _private::ValueBase<_private::Basic>& value) : _private::ValueBase<_private::Basic>(value) {}

		// copy constructor
		Value(const Value& value) : _private::ValueBase<_private::Basic>(value) {}

		// create reference to value
		explicit Value(json_t* json) : _private::ValueBase<_private::Basic>(json) {}
	};

	// iterators over a JSON object
	class Iterator {
	public:
		// construct a new iterator for a given object
		inline Iterator(const Value& value);

		// construct a new iterator for a given object
		inline Iterator(const _private::ValueBase<_private::PropertyProxy>& value);

		// increment iterator
		inline void next();

		inline Iterator& operator++();

		// test if iterator is still valid
		inline bool valid() const;

		inline operator bool() const;

		// get key
		inline const char* ckey() const;

		inline std::string key() const;

		// get value
		inline const Value value() const;

		// dereference value
		inline const Value operator*() const;

	private:
		// disallow copying
		Iterator(const Iterator&);
		Iterator& operator=(const Iterator&);

		// object being iterated over
		Value _object;

		// iterator value
		void* _iter;
	};

	// create a new empty object
	inline Value object();

	// create a new empty array
	inline Value array();

	// create a new null value
	inline Value null();

	// load a file as a JSON value
	inline Value load_file(const char* path, json_error_t* error = 0);

	// load a string as a JSON value
	inline Value load_string(const char* string, json_error_t* error = 0);

} // namespace json

// stream JSON value out -- inefficient and not recommended for production use
inline std::ostream& operator<<(std::ostream& os, const json::Value& value);

// read JSON value -- inefficient and not recommended for production use
inline std::istream& operator>>(std::istream& is, json::Value& value);

// include implementation code
#define IN_JANSSON_HPP 1
#include "jansson-impl.hpp"
#undef IN_JANSSON_HPP

#endif // defined(JANSSON_HPP)
<commit_msg>add meaningful copyright to jansson.hpp<commit_after>// Copyright (c) 2010 Sean Middleditch <sean@middleditch.us>
//
// Jansson is free software; you can redistribute it and/or modify
// it under the terms of the MIT license. See LICENSE for details.

#if !defined(JANSSON_HPP)
#define JANSSON_HPP 1

#include <string>
#include <ostream>
#include <istream>
#include <sstream>
#include <cstdlib>

namespace json {
	// include Jansson C library into the json namespace
	#include <jansson.h>

	class Iterator;
	class Value;

	// implementation details; do not use directly
	namespace _private {
		class ElementProxy;
		class PropertyProxy;

		// base class for JSON value interface
		template <typename _Base>
		class ValueBase : public _Base {
		public:
			// empty constructor
			ValueBase() : _Base() {}

			// copy constructor
			ValueBase(const _Base& base) : _Base(base) {}

			// create reference to value
			ValueBase(json_t* json) : _Base(json) {}

			// assignment operator
			inline ValueBase& operator=(const Value& value);

			// check value type
			inline bool is_undefined() const;
			inline bool is_object() const;
			inline bool is_array() const;
			inline bool is_string() const;
			inline bool is_integer() const;
			inline bool is_real() const;
			inline bool is_number() const;
			inline bool is_true() const;
			inline bool is_false() const;
			inline bool is_boolean() const;
			inline bool is_null() const;

			// get size of array or object
			inline unsigned int size() const;

			// get value at array index (const version)
			inline const Value at(unsigned int index) const;

			inline const Value operator[](signed int index) const;
			inline const Value operator[](unsigned int index) const;
			inline const Value operator[](signed short index) const;
			inline const Value operator[](unsigned short index) const;
			inline const Value operator[](signed long index) const;
			inline const Value operator[](unsigned long index) const;

			// get value at array index (non-const version)
			inline ValueBase<ElementProxy> at(unsigned int index);

			inline ValueBase<ElementProxy> operator[](signed int index);
			inline ValueBase<ElementProxy> operator[](unsigned int index);
			inline ValueBase<ElementProxy> operator[](signed short index);
			inline ValueBase<ElementProxy> operator[](unsigned short index);
			inline ValueBase<ElementProxy> operator[](signed long index);
			inline ValueBase<ElementProxy> operator[](unsigned long index);

			// get object property (const version)
			inline const Value get(const char* key) const;

			inline const Value get(const std::string& key) const;
			inline const Value operator[](const char* key) const;
			inline const Value operator[](const std::string& key) const;

			// get object property (non-const version)
			inline ValueBase<PropertyProxy> get(const char* key);

			inline ValueBase<PropertyProxy> get(const std::string& key);
			inline ValueBase<PropertyProxy> operator[](const char* key);
			inline ValueBase<PropertyProxy> operator[](const std::string& key);

			// clear all array/object values
			inline void clear();

			// get value cast to specified type
			inline const char* as_cstring() const;
			inline std::string as_string() const;
			inline int as_integer() const;
			inline double as_real() const;
			inline double as_number() const;
			inline bool as_boolean() const;

			// set an object property (converts value to object is not one already)
			inline _Base& set_key(const char* key, const Value& value);

			inline _Base& set_key(const std::string& key, const Value& value);

			// set an array index (converts value to object is not one already)
			inline _Base& set_at(unsigned int index, const Value& value);

			// delete an object key
			inline _Base& del_key(const char* key);

			inline _Base& del_key(const std::string& key);

			// delete an item from an array by index
			inline _Base& del_at(unsigned int index);

			// insert an item into an array at a given index
			inline _Base& insert_at(unsigned int index, const Value& value);

			// write the value to a file
			inline int save_file(const char* path, int flags = 0) const;

			// write the value to a string (caller must deallocate with free()!)
			inline char* save_string(int flags = 0) const;
		};

		// represents any JSON value, private base
		class Basic {
		public:
			// construct new Value with an undefined value
			Basic() : _value(0) {}

			// copy constructor
			Basic(const Basic& value) : _value(json_incref(value._value)) {}

			// make a reference to an existing json_t value
			explicit Basic(json_t* value) : _value(json_incref(value)) {}

			// free Value resources
			inline ~Basic();

			// copy an existing Value
			inline Basic& operator=(const Basic& e);

			// get the underlying json_t
			inline json_t* as_json() const;

			// take ownership of a json_t (does not increase reference count)
			inline static Basic take_ownership(json_t* json);

		protected:
			// internal value pointer
			json_t* _value;
		};

		// proxies an array element
		class ElementProxy {
		public:
			// constructor
			ElementProxy(json_t* array, unsigned int index) : _array(array), _index(index) {}

			// assign to the proxied element
			inline ElementProxy& operator=(const Value& value);

			// get the proxied element
			inline json_t* as_json() const;

		private:
			// array object we wrap
			json_t* _array;

			// index of property
			unsigned int _index;
		};

		// proxies an object property
		class PropertyProxy {
		public:
			// constructor
			PropertyProxy(json_t* array, const char* key) : _object(array), _key(key) {}

			// assign to the proxied element
			inline PropertyProxy& operator=(const Value& value);

			// get the proxied element
			inline json_t* as_json() const;

		private:
			// array object we wrap
			json_t* _object;

			// key of property
			const char* _key;
		};

	} // namespace json::_private

	// represents any JSON value
	class Value : public _private::ValueBase<_private::Basic> {
	public:
		// construct Value from input
		explicit inline Value(const char* value);
		explicit inline Value(const std::string& value);
		explicit inline Value(bool value);
		explicit inline Value(signed int value);
		explicit inline Value(unsigned int value);
		explicit inline Value(signed short value);
		explicit inline Value(unsigned short value);
		explicit inline Value(signed long value);
		explicit inline Value(unsigned long value);
		explicit inline Value(float value);
		explicit inline Value(double value);

		// empty constructor
		Value() : _private::ValueBase<_private::Basic>() {}

		// copy constructor for base
		Value(const _private::Basic& value) : _private::ValueBase<_private::Basic>(value) {}

		// copy constructor for base
		Value(const _private::ValueBase<_private::Basic>& value) : _private::ValueBase<_private::Basic>(value) {}

		// copy constructor
		Value(const Value& value) : _private::ValueBase<_private::Basic>(value) {}

		// create reference to value
		explicit Value(json_t* json) : _private::ValueBase<_private::Basic>(json) {}
	};

	// iterators over a JSON object
	class Iterator {
	public:
		// construct a new iterator for a given object
		inline Iterator(const Value& value);

		// construct a new iterator for a given object
		inline Iterator(const _private::ValueBase<_private::PropertyProxy>& value);

		// increment iterator
		inline void next();

		inline Iterator& operator++();

		// test if iterator is still valid
		inline bool valid() const;

		inline operator bool() const;

		// get key
		inline const char* ckey() const;

		inline std::string key() const;

		// get value
		inline const Value value() const;

		// dereference value
		inline const Value operator*() const;

	private:
		// disallow copying
		Iterator(const Iterator&);
		Iterator& operator=(const Iterator&);

		// object being iterated over
		Value _object;

		// iterator value
		void* _iter;
	};

	// create a new empty object
	inline Value object();

	// create a new empty array
	inline Value array();

	// create a new null value
	inline Value null();

	// load a file as a JSON value
	inline Value load_file(const char* path, json_error_t* error = 0);

	// load a string as a JSON value
	inline Value load_string(const char* string, json_error_t* error = 0);

} // namespace json

// stream JSON value out -- inefficient and not recommended for production use
inline std::ostream& operator<<(std::ostream& os, const json::Value& value);

// read JSON value -- inefficient and not recommended for production use
inline std::istream& operator>>(std::istream& is, json::Value& value);

// include implementation code
#define IN_JANSSON_HPP 1
#include "jansson-impl.hpp"
#undef IN_JANSSON_HPP

#endif // defined(JANSSON_HPP)
<|endoftext|>


<commit_before>#include <gtest/gtest.h>
#include <string>
#include "concurrent.hpp"
#include <vector>
#include <atomic>
#include <iostream>
#include <memory>
#include <chrono>
#include <iostream>
namespace {
   struct DummyObject { };

   // Verify clean destruction
   struct TrueAtExit {
      std::atomic<bool>* flag;
      explicit TrueAtExit(std::atomic<bool>* f) : flag(f) {
         flag->store(false);
      }

      bool value() { return *flag; }

      ~TrueAtExit() { flag->store(true); }

      // concurrent improvement from the original Herb Sutter example
      // Which would copy/move the object into the concurrent wrapper
      // i.e the original concurrent wrapper could not use an object such as this (or a unique_ptr for that matter)
      TrueAtExit(const TrueAtExit&) = delete;
      TrueAtExit& operator=(const TrueAtExit&) = delete;
   };

   // Verify concurrent runs,. "no" delay for the caller.
   struct DelayedCaller {
      void DoDelayedCall() {
         std::this_thread::sleep_for(std::chrono::seconds(1));
      }
   };
}

TEST(TestOfconcurrent, CompilerCheckForEmptyStruct) {
   concurrent<DummyObject> doNothing1{};
   concurrent<DummyObject> doNothing2;
   concurrent<DummyObject> doNothing3 = {};
}

namespace {
   struct Animal {
      virtual void sound() = 0;
   };
   struct Dog : public Animal {
      void sound() override { std::cout << "Wof Wof" << std::endl; }
   };

   struct Cat : public Animal {
     void sound() override { std::cout << "Miauu Miauu" << std::endl; }
   };
}

TEST(TestOfConcurrent, CompilerCheckUniquePtrTest) {
   typedef std::unique_ptr<Animal> RaiiAnimal;
   concurrent<RaiiAnimal> animal1 {new Dog};
   concurrent<RaiiAnimal> animal2 {new Cat};

   auto make_sound = []( RaiiAnimal& animal ) { animal->sound(); };
   animal1(make_sound);
   animal2(make_sound);
}

TEST(TestOfconcurrent, VerifyDestruction) {
   std::atomic<bool> flag{true};
   {
      concurrent<TrueAtExit> notifyAtExit1{&flag};
      EXPECT_FALSE(flag); // i.e. constructor has run
   }
   {
      EXPECT_TRUE(flag); // notifyAtExit destructor
      concurrent<TrueAtExit> notifyAtExit2 = {&flag};
      EXPECT_FALSE(flag);
   }
   EXPECT_TRUE(flag); // notifyAtExit destructor
}

TEST(TestOfconcurrent, VerifyFifoCalls) {

   concurrent<std::string> asyncString = {"start"};
   auto received = asyncString([](std::string & s) { s.append(" received message"); return std::string{s}; });

   auto clear = asyncString([](std::string & s) { s.clear(); return s; });

   EXPECT_EQ("start received message", received.get());
   EXPECT_EQ("", clear.get());

   std::string toCompare;
   for (size_t index = 0; index < 100000; ++index) {
      toCompare.append(std::to_string(index)).append(" ");
      asyncString([ = ](std::string & s){s.append(std::to_string(index)).append(" ");});
   }

   auto appended = asyncString([](const std::string & s) { return s; });
   EXPECT_EQ(appended.get(), toCompare);
}

TEST(TestOfconcurrent, VerifyImmediateReturnForSlowFunctionCalls) {

   typedef std::chrono::steady_clock clock;
   auto start = clock::now();
   {
      concurrent<DelayedCaller> snail;
      for (size_t call = 0; call < 10; ++call) {
         snail([](DelayedCaller & slowRunner) { slowRunner.DoDelayedCall(); });
      }
      EXPECT_LT(std::chrono::duration_cast<std::chrono::seconds>(clock::now() - start).count(), 1);
   } // at destruction all 1 second calls will be executed before we quit

   EXPECT_TRUE(std::chrono::duration_cast<std::chrono::seconds>(clock::now() - start).count() >= 10); //
}

<commit_msg>cosmetic<commit_after>#include <gtest/gtest.h>
#include <string>
#include "concurrent.hpp"
#include <vector>
#include <atomic>
#include <iostream>
#include <memory>
#include <chrono>
#include <iostream>
namespace {
   struct DummyObject { };

   // Verify clean destruction
   struct TrueAtExit {
      std::atomic<bool>* flag;
      explicit TrueAtExit(std::atomic<bool>* f) : flag(f) {
         flag->store(false);
      }

      bool value() { return *flag; }

      ~TrueAtExit() { flag->store(true); }

      // concurrent improvement from the original Herb Sutter example
      // Which would copy/move the object into the concurrent wrapper
      // i.e the original concurrent wrapper could not use an object such as this (or a unique_ptr for that matter)
      TrueAtExit(const TrueAtExit&) = delete;
      TrueAtExit& operator=(const TrueAtExit&) = delete;
   };

   // Verify concurrent runs,. "no" delay for the caller.
   struct DelayedCaller {
      void DoDelayedCall() {
         std::this_thread::sleep_for(std::chrono::seconds(1));
      }
   };
}

TEST(TestOfConcurrent, CompilerCheckForEmptyStruct) {
   concurrent<DummyObject> doNothing1{};
   concurrent<DummyObject> doNothing2;
   concurrent<DummyObject> doNothing3 = {};
}

namespace {
   struct Animal {
      virtual std::string sound() = 0;
   };
   struct Dog : public Animal {
      std::string sound() override { return {"Wof Wof"}; }
   };

   struct Cat : public Animal {
     std::string sound() override { return {"Miauu Miauu"}; }
   };
}

TEST(TestOfConcurrent, CompilerCheckUniquePtrTest) {
   typedef std::unique_ptr<Animal> RaiiAnimal;
   concurrent<RaiiAnimal> animal1 {new Dog};
   concurrent<RaiiAnimal> animal2 {new Cat};

   auto make_sound = []( RaiiAnimal& animal ) { return animal->sound(); };
   EXPECT_EQ("Wof Wof", animal1(make_sound).get());
   EXPECT_EQ("Miauu Miauu", animal2(make_sound).get());
}

TEST(TestOfConcurrent, VerifyDestruction) {
   std::atomic<bool> flag{true};
   {
      concurrent<TrueAtExit> notifyAtExit1{&flag};
      EXPECT_FALSE(flag); // i.e. constructor has run
   }
   {
      EXPECT_TRUE(flag); // notifyAtExit destructor
      concurrent<TrueAtExit> notifyAtExit2 = {&flag};
      EXPECT_FALSE(flag);
   }
   EXPECT_TRUE(flag); // notifyAtExit destructor
}

TEST(TestOfConcurrent, VerifyFifoCalls) {

   concurrent<std::string> asyncString = {"start"};
   auto received = asyncString([](std::string & s) { s.append(" received message"); return std::string{s}; });

   auto clear = asyncString([](std::string & s) { s.clear(); return s; });

   EXPECT_EQ("start received message", received.get());
   EXPECT_EQ("", clear.get());

   std::string toCompare;
   for (size_t index = 0; index < 100000; ++index) {
      toCompare.append(std::to_string(index)).append(" ");
      asyncString([ = ](std::string & s){s.append(std::to_string(index)).append(" ");});
   }

   auto appended = asyncString([](const std::string & s) { return s; });
   EXPECT_EQ(appended.get(), toCompare);
}

TEST(TestOfConcurrent, VerifyImmediateReturnForSlowFunctionCalls) {

   typedef std::chrono::steady_clock clock;
   auto start = clock::now();
   {
      concurrent<DelayedCaller> snail;
      for (size_t call = 0; call < 10; ++call) {
         snail([](DelayedCaller & slowRunner) { slowRunner.DoDelayedCall(); });
      }
      EXPECT_LT(std::chrono::duration_cast<std::chrono::seconds>(clock::now() - start).count(), 1);
   } // at destruction all 1 second calls will be executed before we quit

   EXPECT_TRUE(std::chrono::duration_cast<std::chrono::seconds>(clock::now() - start).count() >= 10); //
}

<|endoftext|>