<commit_before>//------------------------------------------------------------------------------
// main.cpp
//
// Written by Dr Elliot Carr (2013-2014)
// cole Centrale Paris and Queensland University of Technology
//
// This code is part of TwoScalRich.
//
// This is the main program file.
//
//------------------------------------------------------------------------------

#include "main.h"

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

    int i, j, k;
    int flag;
    time_t tic, toc;

    //--------------------------------------------------------------------------
    // START: User changeable parameters
    //--------------------------------------------------------------------------

//     cout << "There are " << argc << " arguments:" << endl;
//
//     // Loop through each argument and print its number and value
//     for (int nArg=0; nArg < argc; nArg++)
//     {
//         cout << nArg << " " << argv[nArg] << endl;
//     }

    // Problem configuration file
    const char* config_file = argv[1];

    // Read configuration file
    cout << "Reading configuration file\n";
    FILE * myfile;
    myfile = fopen(config_file,"r");

    if (myfile == NULL)
    {
        return 1;
    }

    // Mesh files
    char macro_mesh_file[90];
    fscanf(myfile, "%s", macro_mesh_file);
    char micro_mesh_file[90];
    fscanf(myfile, "%s", micro_mesh_file);

    cout << "Macroscopic mesh: " << macro_mesh_file << "\n";
    cout << "Microscopic mesh: " << micro_mesh_file << "\n";

    // Solution output file
    char solution_file[90];
    fscanf(myfile, "%s", solution_file);

    // Uniform initial condition [m]
    long double h0;
    fscanf(myfile, "%Lf", &h0);

    // Simulation end time (hours)
    long double tend;
    fscanf(myfile, "%Lf", &tend);

    // Number of solutions to store
    int no_solns;
    fscanf(myfile, "%i", &no_solns);

    //const char* macro_mesh_file = argv[1]; //"macro_structured_20by20.msh";
    //const char* micro_mesh_file = "microB_unstructured_20by20.msh";

    // Stores solution at time values specified in tspan array
    //string solution_file = "solution.txt";
    //int no_solns = (int) tend;
    //double* tspan = new double [no_solns+1];
//     tspan[0] = no_solns; // Store number as first element
//     for (i=1; i<no_solns+1; i++)
//     {
//         tspan[i] = (double)i*3600.0;
//     }

    double* tspan = new double [no_solns+1];
    tspan[0] = no_solns; // Store number as first element
    long double a;
    for (i=1; i<no_solns+1; i++)
    {
        fscanf(myfile, "%Lf", &a);
        tspan[i] = a*3600.0;
    }

    // Solver statistics
    string statistics_file = "statistics.txt";

    // Print Solver information (true or false)
    bool PrintStepInfo = true;

    // Print Solver information every 'PrintStep' steps
    int PrintStep = 1;

    // Soil properties
    // A: connected sub-domain
    // B: disconnected sub-domin (inclusions)
    // ***Important***
    // Changing these parameters requires the effective conductivity to be
    // computed again (see Keff/run.m)
    soil_struct soilA;
    soil_struct soilB;

    fscanf(myfile, "%Lf", &a); // hydraulic conductivity
    soilA.Ksat   = a; //0.044 / 3600.0;
    fscanf(myfile, "%Lf", &a);
    soilA.thetar = a; // residual moisture content
    fscanf(myfile, "%Lf", &a);
    soilA.thetas = a; // saturated moisture content
    fscanf(myfile, "%Lf", &a);
    soilA.alpha = a; // alpha paramter (van Genuchten relations)
    fscanf(myfile, "%Lf", &a);
    soilA.n = a; // n parameter (van Genuchten relations)

    soilA.m = 1.0 - 1.0 / soilA.n; // m = 1 - 1/n (van Genuchten relations)

    fscanf(myfile, "%Lf", &a); // hydraulic conductivity
    soilB.Ksat   = a; //0.044 / 3600.0;
    fscanf(myfile, "%Lf", &a);
    soilB.thetar = a; // residual moisture content
    fscanf(myfile, "%Lf", &a);
    soilB.thetas = a; // saturated moisture content
    fscanf(myfile, "%Lf", &a);
    soilB.alpha = a; // alpha paramter (van Genuchten relations)
    fscanf(myfile, "%Lf", &a);
    soilB.n = a; // n parameter (van Genuchten relations)

    fclose(myfile);

    soilB.m = 1.0 - 1.0 / soilB.n; // m = 1 - 1/n (van Genuchten relations)

    // Effective conductivity file
    const char* Keff_file = "Keff.txt";

    // Macro boundary conditions
    int *macro_bc = new int [5];

    //--------------------------------------------------------------------------
    // Set Macro boundary conditions (boundary faces labelled below)
    //
    //              |- Influx -| North
    //          **************************
    //          *                        *
    //          *                        *
    //          *                        *
    //          *                        *
    //          *                        *
    //          *                        *
    //     West *                        * East
    //          *                        *
    //          *                        *
    //          *                        *
    //          *                        *
    //          *                        *
    //          *                        *
    //          **************************
    //                    South
    //
    // 1: Flux specified (q.n = boundary_flux)
    // 2: No flux (q.n = 0)
    // 3: dh/dx = 0 (Free drainage condition for East and West boundaries)
    // 4: dh/dy = 0 (Free drainage condition for North and South boundaries)

    // Boundary flux [m/s]
    double boundary_flux  = -0.01 / 3600.0;
    macro_bc[0] = 1; // Influx
    macro_bc[1] = 3; // South
    macro_bc[2] = 2; // East
    macro_bc[3] = 2; // West
    macro_bc[4] = 2; // North (excluding Influx segment)
    //--------------------------------------------------------------------------

    // Model type
    // 1: uniform micro boundary condition
    // 2: non-uniform micro boundary condition
    // 3: non-uniform micro boundary condition, inclusion flux included at
    //    macro-scale
    int model_type = 3;

    //--------------------------------------------------------------------------
    // Get environment variables defined in script files (.sh files)

    // Parallel or serial implementation of right-hand side function (Gfunc)
    int parallel = atoi(getenv("parallel"));
    int (*Gfunc_type)(double* g, double* u, user_data_struct user_data);
    if (parallel == 0)
    {
        Gfunc_type = Gfunc_serial;
    }
    else if (parallel == 1)
    {
        Gfunc_type = Gfunc_parallel;
    }
    else
    {
        cout << "Variable `parallel' defined in script .sh file must be " << \
                "either 0 or 1.\n";
        exit(EXIT_FAILURE);
    }

    // Number of OpenMP Threads
    unsigned int NUM_THREADS = max(atoi(getenv("OMP_NUM_THREADS")), 1);
    //--------------------------------------------------------------------------

    string mesh_type      = "structured_";
    string d = "_10by10.txt";

    //--------------------------------------------------------------------------
    // Read effective conductivity values
    Keff_struct effective_conductivity;
    flag = read_effective_conductivity(Keff_file, effective_conductivity);
    //--------------------------------------------------------------------------

    //--------------------------------------------------------------------------
    // Process macro and micro meshes and compute mesh properties (normals,
    // control volume areas, etc.)

    // Macro mesh
    macro_mesh_struct macro_mesh;
    flag = macro_mesh_properties(macro_mesh_file, macro_mesh, macro_bc);

    if (flag == 1)
    {
        cout << "Error opening macro mesh file. Simulation aborted.\n";
        return 0;
    }

    // Micro mesh
    micro_mesh_struct micro_mesh;
    flag = micro_mesh_properties(micro_mesh_file, micro_mesh);

    if (flag == 1)
    {
        cout << "Error opening micro mesh file. Simulation aborted.\n";
        return 0;
    }
    //--------------------------------------------------------------------------

    // EXPREM solver options
    exprem_options_struct exprem_options;
    flag = set_exprem_options(exprem_options);

    // EXPREM solver stats
    exprem_stats_struct exprem_stats;

    // Number of unknowns
    int N = macro_mesh.no_nodes + macro_mesh.no_elements * micro_mesh.no_nodes;

    // Initial solution
    double* u0 = new double [N];
    for (i=0; i<N; i++)
    {
        u0[i] = h0;
    }

    // Store initial solution
    double* tspan_solns = new double [N*(no_solns+1)];
    for (i=0; i<N; i++)
    {
        tspan_solns[i] = u0[i];
    }

    int num_sims;
    string folder;

    num_sims = 1;
    folder = "Results/";

    // User data
    user_data_struct user_data;
    user_data.macro_mesh             = macro_mesh;
    user_data.micro_mesh             = micro_mesh;
    user_data.soilA                  = soilA;
    user_data.soilB                  = soilB;
    user_data.boundary_flux          = boundary_flux;
    user_data.NUM_THREADS            = NUM_THREADS;
    user_data.effective_conductivity = effective_conductivity;
    user_data.model_type             = model_type;
    user_data.N                      = N;

    ofstream stats_file;
    stats_file.open(statistics_file.c_str());

    if (!stats_file.is_open())
    {
        cout << "Error opening solution file\n";
        return 0;
    }

    // Simulation wall time
    double dtime = omp_get_wtime();

    cout << scientific;
    cout << std::setprecision(2);

    //--------------------------------------------------------------------------
    // Time stepping
    double t = 0.0;
    tend = tend * 3600.0; // Hours to seconds
    while (t < tend)
    {
        // exprem takes one internal step and then exits
        flag = exprem(Gfunc_type, N, t, tend, tspan, tspan_solns, u0, \
                user_data, exprem_options, exprem_stats);

        if (flag == -1)
        {
            return 0;
        }

        stats_file << setw(5) << exprem_stats.NumSteps << " ";
        stats_file << scientific;
        stats_file << std::setprecision(4);
        stats_file << t/3600.0 << " ";
        stats_file << exprem_stats.CurrentStep << " ";
        stats_file << exprem_stats.CurrentKryDim << "\n";

        // Print every 'PrintStep' steps
        if (exprem_stats.NumSteps % PrintStep == 0 && PrintStepInfo == true)
        {
            cout << "NSTEPS: " << setw(5) << exprem_stats.NumSteps << " | ";
            cout << scientific;
            cout << std::setprecision(4) << "TIME [H]: " << t/3600.0 << " | ";
            cout << "STEPSIZE [S]: " << exprem_stats.CurrentStep << " | ";
            cout << "KRYDIM: " << exprem_stats.CurrentKryDim << "\n";
        }

    }
    //--------------------------------------------------------------------------

    stats_file.close();

    // Simulation wall time
    dtime = omp_get_wtime() - dtime;

    cout << scientific;
    cout << fixed << "Runtime: " << dtime << " secs" << "  N: " << N << \
            "   FuncEvals: " << exprem_stats.FuncEvals << "\n";
    cout << "Simulation completed successfully.\n";

    // Save solution to file
    save_solution(solution_file, tspan, tspan_solns, no_solns, user_data);

    // Free memory allocations
    delete[] tspan;
    delete[] macro_bc;
    delete[] u0;
    delete[] tspan_solns;

    return 0;
}
<commit_msg>Update main.cpp<commit_after>//------------------------------------------------------------------------------
// main.cpp
//
// Written by Elliot Carr
// Queensland University of Technology
//
// This code is part of TwoScalRich.
//
// This is the main program file.
//
//------------------------------------------------------------------------------

#include "main.h"

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

    int i, j, k;
    int flag;
    time_t tic, toc;

    //--------------------------------------------------------------------------
    // START: User changeable parameters
    //--------------------------------------------------------------------------

//     cout << "There are " << argc << " arguments:" << endl;
//
//     // Loop through each argument and print its number and value
//     for (int nArg=0; nArg < argc; nArg++)
//     {
//         cout << nArg << " " << argv[nArg] << endl;
//     }

    // Problem configuration file
    const char* config_file = argv[1];

    // Read configuration file
    cout << "Reading configuration file\n";
    FILE * myfile;
    myfile = fopen(config_file,"r");

    if (myfile == NULL)
    {
        return 1;
    }

    // Mesh files
    char macro_mesh_file[90];
    fscanf(myfile, "%s", macro_mesh_file);
    char micro_mesh_file[90];
    fscanf(myfile, "%s", micro_mesh_file);

    cout << "Macroscopic mesh: " << macro_mesh_file << "\n";
    cout << "Microscopic mesh: " << micro_mesh_file << "\n";

    // Solution output file
    char solution_file[90];
    fscanf(myfile, "%s", solution_file);

    // Uniform initial condition [m]
    long double h0;
    fscanf(myfile, "%Lf", &h0);

    // Simulation end time (hours)
    long double tend;
    fscanf(myfile, "%Lf", &tend);

    // Number of solutions to store
    int no_solns;
    fscanf(myfile, "%i", &no_solns);

    //const char* macro_mesh_file = argv[1]; //"macro_structured_20by20.msh";
    //const char* micro_mesh_file = "microB_unstructured_20by20.msh";

    // Stores solution at time values specified in tspan array
    //string solution_file = "solution.txt";
    //int no_solns = (int) tend;
    //double* tspan = new double [no_solns+1];
//     tspan[0] = no_solns; // Store number as first element
//     for (i=1; i<no_solns+1; i++)
//     {
//         tspan[i] = (double)i*3600.0;
//     }

    double* tspan = new double [no_solns+1];
    tspan[0] = no_solns; // Store number as first element
    long double a;
    for (i=1; i<no_solns+1; i++)
    {
        fscanf(myfile, "%Lf", &a);
        tspan[i] = a*3600.0;
    }

    // Solver statistics
    string statistics_file = "statistics.txt";

    // Print Solver information (true or false)
    bool PrintStepInfo = true;

    // Print Solver information every 'PrintStep' steps
    int PrintStep = 1;

    // Soil properties
    // A: connected sub-domain
    // B: disconnected sub-domin (inclusions)
    // ***Important***
    // Changing these parameters requires the effective conductivity to be
    // computed again (see Keff/run.m)
    soil_struct soilA;
    soil_struct soilB;

    fscanf(myfile, "%Lf", &a); // hydraulic conductivity
    soilA.Ksat   = a; //0.044 / 3600.0;
    fscanf(myfile, "%Lf", &a);
    soilA.thetar = a; // residual moisture content
    fscanf(myfile, "%Lf", &a);
    soilA.thetas = a; // saturated moisture content
    fscanf(myfile, "%Lf", &a);
    soilA.alpha = a; // alpha paramter (van Genuchten relations)
    fscanf(myfile, "%Lf", &a);
    soilA.n = a; // n parameter (van Genuchten relations)

    soilA.m = 1.0 - 1.0 / soilA.n; // m = 1 - 1/n (van Genuchten relations)

    fscanf(myfile, "%Lf", &a); // hydraulic conductivity
    soilB.Ksat   = a; //0.044 / 3600.0;
    fscanf(myfile, "%Lf", &a);
    soilB.thetar = a; // residual moisture content
    fscanf(myfile, "%Lf", &a);
    soilB.thetas = a; // saturated moisture content
    fscanf(myfile, "%Lf", &a);
    soilB.alpha = a; // alpha paramter (van Genuchten relations)
    fscanf(myfile, "%Lf", &a);
    soilB.n = a; // n parameter (van Genuchten relations)

    fclose(myfile);

    soilB.m = 1.0 - 1.0 / soilB.n; // m = 1 - 1/n (van Genuchten relations)

    // Effective conductivity file
    const char* Keff_file = "Keff.txt";

    // Macro boundary conditions
    int *macro_bc = new int [5];

    //--------------------------------------------------------------------------
    // Set Macro boundary conditions (boundary faces labelled below)
    //
    //              |- Influx -| North
    //          **************************
    //          *                        *
    //          *                        *
    //          *                        *
    //          *                        *
    //          *                        *
    //          *                        *
    //     West *                        * East
    //          *                        *
    //          *                        *
    //          *                        *
    //          *                        *
    //          *                        *
    //          *                        *
    //          **************************
    //                    South
    //
    // 1: Flux specified (q.n = boundary_flux)
    // 2: No flux (q.n = 0)
    // 3: dh/dx = 0 (Free drainage condition for East and West boundaries)
    // 4: dh/dy = 0 (Free drainage condition for North and South boundaries)

    // Boundary flux [m/s]
    double boundary_flux  = -0.01 / 3600.0;
    macro_bc[0] = 1; // Influx
    macro_bc[1] = 3; // South
    macro_bc[2] = 2; // East
    macro_bc[3] = 2; // West
    macro_bc[4] = 2; // North (excluding Influx segment)
    //--------------------------------------------------------------------------

    // Model type
    // 1: uniform micro boundary condition
    // 2: non-uniform micro boundary condition
    // 3: non-uniform micro boundary condition, inclusion flux included at
    //    macro-scale
    int model_type = 3;

    //--------------------------------------------------------------------------
    // Get environment variables defined in script files (.sh files)

    // Parallel or serial implementation of right-hand side function (Gfunc)
    int parallel = atoi(getenv("parallel"));
    int (*Gfunc_type)(double* g, double* u, user_data_struct user_data);
    if (parallel == 0)
    {
        Gfunc_type = Gfunc_serial;
    }
    else if (parallel == 1)
    {
        Gfunc_type = Gfunc_parallel;
    }
    else
    {
        cout << "Variable `parallel' defined in script .sh file must be " << \
                "either 0 or 1.\n";
        exit(EXIT_FAILURE);
    }

    // Number of OpenMP Threads
    unsigned int NUM_THREADS = max(atoi(getenv("OMP_NUM_THREADS")), 1);
    //--------------------------------------------------------------------------

    string mesh_type      = "structured_";
    string d = "_10by10.txt";

    //--------------------------------------------------------------------------
    // Read effective conductivity values
    Keff_struct effective_conductivity;
    flag = read_effective_conductivity(Keff_file, effective_conductivity);
    //--------------------------------------------------------------------------

    //--------------------------------------------------------------------------
    // Process macro and micro meshes and compute mesh properties (normals,
    // control volume areas, etc.)

    // Macro mesh
    macro_mesh_struct macro_mesh;
    flag = macro_mesh_properties(macro_mesh_file, macro_mesh, macro_bc);

    if (flag == 1)
    {
        cout << "Error opening macro mesh file. Simulation aborted.\n";
        return 0;
    }

    // Micro mesh
    micro_mesh_struct micro_mesh;
    flag = micro_mesh_properties(micro_mesh_file, micro_mesh);

    if (flag == 1)
    {
        cout << "Error opening micro mesh file. Simulation aborted.\n";
        return 0;
    }
    //--------------------------------------------------------------------------

    // EXPREM solver options
    exprem_options_struct exprem_options;
    flag = set_exprem_options(exprem_options);

    // EXPREM solver stats
    exprem_stats_struct exprem_stats;

    // Number of unknowns
    int N = macro_mesh.no_nodes + macro_mesh.no_elements * micro_mesh.no_nodes;

    // Initial solution
    double* u0 = new double [N];
    for (i=0; i<N; i++)
    {
        u0[i] = h0;
    }

    // Store initial solution
    double* tspan_solns = new double [N*(no_solns+1)];
    for (i=0; i<N; i++)
    {
        tspan_solns[i] = u0[i];
    }

    int num_sims;
    string folder;

    num_sims = 1;
    folder = "Results/";

    // User data
    user_data_struct user_data;
    user_data.macro_mesh             = macro_mesh;
    user_data.micro_mesh             = micro_mesh;
    user_data.soilA                  = soilA;
    user_data.soilB                  = soilB;
    user_data.boundary_flux          = boundary_flux;
    user_data.NUM_THREADS            = NUM_THREADS;
    user_data.effective_conductivity = effective_conductivity;
    user_data.model_type             = model_type;
    user_data.N                      = N;

    ofstream stats_file;
    stats_file.open(statistics_file.c_str());

    if (!stats_file.is_open())
    {
        cout << "Error opening solution file\n";
        return 0;
    }

    // Simulation wall time
    double dtime = omp_get_wtime();

    cout << scientific;
    cout << std::setprecision(2);

    //--------------------------------------------------------------------------
    // Time stepping
    double t = 0.0;
    tend = tend * 3600.0; // Hours to seconds
    while (t < tend)
    {
        // exprem takes one internal step and then exits
        flag = exprem(Gfunc_type, N, t, tend, tspan, tspan_solns, u0, \
                user_data, exprem_options, exprem_stats);

        if (flag == -1)
        {
            return 0;
        }

        stats_file << setw(5) << exprem_stats.NumSteps << " ";
        stats_file << scientific;
        stats_file << std::setprecision(4);
        stats_file << t/3600.0 << " ";
        stats_file << exprem_stats.CurrentStep << " ";
        stats_file << exprem_stats.CurrentKryDim << "\n";

        // Print every 'PrintStep' steps
        if (exprem_stats.NumSteps % PrintStep == 0 && PrintStepInfo == true)
        {
            cout << "NSTEPS: " << setw(5) << exprem_stats.NumSteps << " | ";
            cout << scientific;
            cout << std::setprecision(4) << "TIME [H]: " << t/3600.0 << " | ";
            cout << "STEPSIZE [S]: " << exprem_stats.CurrentStep << " | ";
            cout << "KRYDIM: " << exprem_stats.CurrentKryDim << "\n";
        }

    }
    //--------------------------------------------------------------------------

    stats_file.close();

    // Simulation wall time
    dtime = omp_get_wtime() - dtime;

    cout << scientific;
    cout << fixed << "Runtime: " << dtime << " secs" << "  N: " << N << \
            "   FuncEvals: " << exprem_stats.FuncEvals << "\n";
    cout << "Simulation completed successfully.\n";

    // Save solution to file
    save_solution(solution_file, tspan, tspan_solns, no_solns, user_data);

    // Free memory allocations
    delete[] tspan;
    delete[] macro_bc;
    delete[] u0;
    delete[] tspan_solns;

    return 0;
}
<|endoftext|>


<commit_before>//For the OLED Display
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
// For the one wire temp sensor DS18B20
#include <OneWire.h>
#include <DallasTemperature.h>

// Set up the pins to communicate with the display
// Using software SPI
#define OLED_MOSI  10
#define OLED_CLK   11
#define OLED_DC    12
#define OLED_CS    14
#define OLED_RESET 13
Adafruit_SSD1306 display(OLED_MOSI, OLED_CLK, OLED_DC, OLED_RESET, OLED_CS);

// Setup the pin for the one wire temp sensor
#define ONE_WIRE_BUS 4

// Define some key constants
// 15 minute intervals for 24 hours -> 24*4 = 96
#define HISTORY_SIZE 96
// How many milliseconds in each history bin -> 15*60*1000 = 900,000
#define BIN_MILLIS 900000
// Define the display modes
#define MODE_LIVE 0
#define MODE_HL_IN 1
#define MODE_HL_OUT 2
#define MODE_HIST_IN 3
#define MODE_HIST_OUT 4
// MAX_MODES used to roll aroind the modes using: mode++ % MAX_MODES
#define MAX_MODES 5

// Button
#define BUTTON_PIN 2
#define DEBOUNCE 100
#define LONG_PRESS 3000

// Define variables used
// These are used to record highs and lows since reset
float inHigh, inLow;
float outHigh, outLow;
// These arrays store highs and lows at 15 minute intervals for 24 hours
float inHigh24[HISTORY_SIZE];
float inLow24[HISTORY_SIZE];
float outHigh24[HISTORY_SIZE];
float outLow24[HISTORY_SIZE];
// Define variables to hold the current temperature values
float in;
float out;
// Store the current display mode
// Declared volatile as we will update this in an interrupt
volatile static unsigned long last_interrupt_time = 0;
volatile static unsigned long btn_pressed;
volatile static unsigned long btn_released;
volatile int mode = MODE_LIVE;

// Setup a oneWire instance to communicate with any OneWire devices
// (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);
// Pass our oneWire reference to Dallas Temperature.
DallasTemperature sensors(&oneWire);

// Functions
// Display the live data
void displayLive(){
  display.setTextSize(2);
  display.setTextColor(WHITE);
  display.clearDisplay();
  display.setCursor(0,0);
  display.print("In:  ");
  display.print(in);
  display.setCursor(0,16);
  display.print("Out: ");
  display.print(out);
  display.display();
}

// Display the High and Low inside temperatures
void displayHLIn(){
  display.setTextSize(2);
  display.setTextColor(WHITE);
  display.clearDisplay();
  display.setCursor(0,0);
  display.print("Mode HL In");
  display.display();
}

// Display the High and Low outside temperatures
void displayHLOut(){
  display.setTextSize(2);
  display.setTextColor(WHITE);
  display.clearDisplay();
  display.setCursor(0,0);
  display.print("Mode HL Out");
  display.display();
}

// Display a graph of the history data for inside
void displayHistIn(){
  display.setTextSize(2);
  display.setTextColor(WHITE);
  display.clearDisplay();
  display.setCursor(0,0);
  display.print("Mode Hist In");
  display.display();
}

// Display a graph of the history data for outside
void displayHistOut(){
  display.setTextSize(2);
  display.setTextColor(WHITE);
  display.clearDisplay();
  display.setCursor(0,0);
  display.print("Mode Hist Out");
  display.display();
}

// Create the Graph axes
void displayAxes(){

}

// Update the display
void updateDisplay() {
  switch (mode) {
    case MODE_LIVE:
      displayLive();
      break;
    case MODE_HL_IN:
      displayHLIn();
      break;
    case MODE_HL_OUT:
      displayHLOut();
      break;
    case MODE_HIST_IN:
      displayHistIn();
      break;
    case MODE_HIST_OUT:
      displayHistOut();
      break;
    default:
      mode = MODE_LIVE;
      displayLive();
      break;
  }
}
// Do Button actions
void buttonPress() {
  if (digitalRead(BUTTON_PIN) == LOW){
    // The button is still pressed and this will be considered a Long Press
    btn_pressed = millis();
  } else {
    // The Button has been released
    unsigned long pressed_for = millis() - btn_pressed;
    if (pressed_for > LONG_PRESS){
      mode = MODE_LIVE;
    } else {
      mode = (mode + 1) % MAX_MODES;
    }
    updateDisplay();
  }
}

// Interrupt handler to take user button input
void buttonInterrupt() {
  unsigned long now = millis();
  if (now - last_interrupt_time > DEBOUNCE) {
    buttonPress();
    last_interrupt_time = now;
  }
}

// Setup
void setup(){
  // Initialise the Display
  display.begin(SSD1306_SWITCHCAPVCC);
  // Start up the DallasTemperature sensor
  sensors.begin();  // Start up the library
  mode = MODE_HL_IN;
  // Attach Button Interrupt
  pinMode(BUTTON_PIN, INPUT);
  attachInterrupt(digitalPinToInterrupt(BUTTON_PIN), buttonInterrupt, CHANGE);
}

// Loop
void loop() {
  // call sensors.requestTemperatures() to issue a global temperature
  // request to all devices on the bus
  sensors.requestTemperatures(); // Send the command to get temperatures
  in = sensors.getTempCByIndex(0);
  out = sensors.getTempCByIndex(1);
  updateDisplay();
  delay(1000);
}
<commit_msg>Added graph functionality to display last 24 hours of data<commit_after>//For the OLED Display
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
// For the one wire temp sensor DS18B20
#include <OneWire.h>
#include <DallasTemperature.h>

// Set up the pins to communicathttp://www.hobbytronics.co.uk/ds18b20-arduinoe with the display
// Using software SPI
#define OLED_MOSI  10
#define OLED_CLK   11
#define OLED_DC    12
#define OLED_CS    14
#define OLED_RESET 13
Adafruit_SSD1306 display(OLED_MOSI, OLED_CLK, OLED_DC, OLED_RESET, OLED_CS);

// Setup the pin for the one wire temp sensor
#define ONE_WIRE_BUS 4

// Define some key constants
// 15 minute intervals for 24 hours -> 24*4 = 96
#define HISTORY_SIZE 96
// How many milliseconds in each history bin -> 15*60*1000 = 900,000
#define BIN_MILLIS 900000
// Define the display modes
#define MODE_LIVE 0
#define MODE_HL_IN 1
#define MODE_HL_OUT 2
#define MODE_HIST_IN 3
#define MODE_HIST_OUT 4
// MAX_MODES used to roll aroind the modes using: mode++ % MAX_MODES
#define MAX_MODES 3

// Button
#define BUTTON_PIN 2
#define DEBOUNCE 100
#define LONG_PRESS 3000

// Display constants
#define START_GRAPH 32

// Define variables used
// The buffer bin containing the next temperature reading
int nextBin;
int timeBin;
// These are used to record highs and lows since reset
float inHigh, inLow;
float outHigh, outLow;
// These arrays store highs and lows at 15 minute intervals for 24 hours
float inBuffer[HISTORY_SIZE];
float outBuffer[HISTORY_SIZE];
// Define variables to hold the current temperature values
float in;
float out;
// Store the current display mode
// Declared volatile as we will update this in an interrupt
volatile static unsigned long last_interrupt_time = 0;
volatile static unsigned long btn_pressed;
volatile static unsigned long btn_released;
volatile int mode = MODE_LIVE;

// Setup a oneWire instance to communicate with any OneWire devices
// (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);
// Pass our oneWire reference to Dallas Temperature.
DallasTemperature sensors(&oneWire);

// Helper Functions
float highest(float* data){
  float highest = -274.0;
  for (int i=0; i<HISTORY_SIZE; i++){
    if(data[i] > highest){
      highest = data[i];
    }
  }
  return highest;
}
float lowest(float* data){
  float lowest = 1000;
  for (int i=0; i<HISTORY_SIZE; i++){
    if(data[i] < lowest){
      lowest = data[i];
    }
  }
  return lowest;
}

// Create the Graph axes
void drawAxes(){
  // Draw Tickmarks
  for(int i=0; i<HISTORY_SIZE; i++){
    if (i % (HISTORY_SIZE/4) == 0){
      int xTick = START_GRAPH + i;
      display.drawLine(xTick, display.height(),xTick, display.height()-4, WHITE);
    } else if (i % (HISTORY_SIZE/24) == 0) {
      int xTick = START_GRAPH + i;
      display.drawLine(xTick, display.height(),xTick, display.height()-2, WHITE);
    }
  }
}

void label(char* text){
  display.setTextSize(1);
  display.setTextColor(WHITE);
  display.setCursor(0,12);
  display.print(text);
}

void plot(float* data){
  float max = highest(data);
  float min = lowest(data);
  float scale = display.height()/(max-min);
  int nowBin = (millis()/BIN_MILLIS) % HISTORY_SIZE;
  int newY;
  for (int i=1; i<HISTORY_SIZE; i++){
    newY = display.height() - (int) floor(data[(i + nowBin + 1) % HISTORY_SIZE]*scale);
    display.drawPixel(START_GRAPH + i, newY, WHITE);
  }
  display.setTextSize(1);
  display.setTextColor(WHITE);
  display.setCursor(0,0);
  display.print(max);
  display.setCursor(0,display.height() - 7);
  display.print(min);
}

// Functions
// Display the live data
void displayLive(){
  display.setTextSize(2);
  display.setTextColor(WHITE);
  display.clearDisplay();
  display.setCursor(0,0);
  display.print("In:  ");
  display.print(in);
  display.setCursor(0,16);
  display.print("Out: ");
  display.print(out);
  display.display();
}

// Display the High and Low inside temperatures
void displayHLIn(){
  display.clearDisplay();
  label("In");
  drawAxes();
  plot(inBuffer);
  display.display();
}

// Display the High and Low outside temperatures
void displayHLOut(){
  display.clearDisplay();
  label("Out");
  drawAxes();
  plot(outBuffer);
  display.display();
}

// Display a graph of the history data for inside
void displayHistIn(){
  display.setTextSize(2);
  display.setTextColor(WHITE);
  display.clearDisplay();
  display.setCursor(0,0);
  display.print("Mode Hist In");
  display.display();
}

// Display a graph of the history data for outside
void displayHistOut(){
  display.setTextSize(2);
  display.setTextColor(WHITE);
  display.clearDisplay();
  display.setCursor(0,0);
  display.print("Mode Hist Out");
  display.display();
}

// Update the display
void updateDisplay() {
  switch (mode) {
    case MODE_LIVE:
      displayLive();
      break;
    case MODE_HL_IN:
      displayHLIn();
      break;
    case MODE_HL_OUT:
      displayHLOut();
      break;
    case MODE_HIST_IN:
      displayHistIn();
      break;
    case MODE_HIST_OUT:
      displayHistOut();
      break;
    default:
      mode = MODE_LIVE;
      displayLive();
      break;
  }
}
// Do Button actions
void buttonPress() {
  if (digitalRead(BUTTON_PIN) == LOW){
    // The button is still pressed and this will be considered a Long Press
    btn_pressed = millis();
  } else {
    // The Button has been released
    unsigned long pressed_for = millis() - btn_pressed;
    if (pressed_for > LONG_PRESS){
      mode = MODE_LIVE;
    } else {
      mode = (mode + 1) % MAX_MODES;
    }
    updateDisplay();
  }
}

// Interrupt handler to take user button input
void buttonInterrupt() {
  unsigned long now = millis();
  if (now - last_interrupt_time > DEBOUNCE) {
    buttonPress();
    last_interrupt_time = now;
  }
}

// Setup
void setup(){
  // Initialise the Display
  display.begin(SSD1306_SWITCHCAPVCC);
  // Start up the DallasTemperature sensor
  sensors.begin();  // Start up the library
  mode = MODE_LIVE;
  // Attach Button Interrupt
  pinMode(BUTTON_PIN, INPUT);
  attachInterrupt(digitalPinToInterrupt(BUTTON_PIN), buttonInterrupt, CHANGE);
  // Set the last read time to 0
  sensors.requestTemperatures(); // Send the command to get temperatures
  in = sensors.getTempCByIndex(0);
  out = sensors.getTempCByIndex(1);
  nextBin = 0;
  for (int i=0; i<HISTORY_SIZE; i++){
    inBuffer[i] = in;
    outBuffer[i] = out;
  }
}

// Loop
void loop() {
  // call sensors.requestTemperatures() to issue a global temperature
  // request to all devices on the bus
  timeBin = (millis() / BIN_MILLIS) % HISTORY_SIZE;
  if (timeBin == nextBin) {
    sensors.requestTemperatures(); // Send the command to get temperatures
    in = sensors.getTempCByIndex(0);
    out = sensors.getTempCByIndex(1);
    inBuffer[nextBin] = in;
    outBuffer[nextBin] = out;
    nextBin = (nextBin + 1) % HISTORY_SIZE;
    updateDisplay();
  }
  delay(1000);
}
<|endoftext|>


<commit_before>// Copyright (c) 2011-2015 The Cryptonote developers
// Copyright (c) 2016-2020 The Karbowanec developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <QApplication>
#include <QCommandLineParser>
#include <QLocale>
#include <QTranslator>
#include <QLockFile>
#include <QMessageBox>
#include <QProcess>
#include <QRegularExpression>
#include <QSplashScreen>
#include <QStyleFactory>
#include <QSettings>
#include <QTextCodec>

#include "CommandLineParser.h"
#include "CurrencyAdapter.h"
#include "LoggerAdapter.h"
#include "NodeAdapter.h"
#include "Settings.h"
#include "SignalHandler.h"
#include "WalletAdapter.h"
#include "gui/MainWindow.h"
#include "Update.h"
#include "PaymentServer.h"
#include "TranslatorManager.h"
#include "LogFileWatcher.h"

#define DEBUG 1

using namespace WalletGui;

const QRegularExpression LOG_SPLASH_REG_EXP("\\] ");

QSplashScreen* splash(nullptr);

inline void newLogString(const QString& _string) {
  QRegularExpressionMatch match = LOG_SPLASH_REG_EXP.match(_string);
  if (match.hasMatch()) {
    QString message = _string.mid(match.capturedEnd());
    splash->showMessage(message, Qt::AlignLeft | Qt::AlignBottom, Qt::white);
  }
}

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

  QApplication app(argc, argv);
  app.setAttribute(Qt::AA_EnableHighDpiScaling);
  app.setAttribute(Qt::AA_UseHighDpiPixmaps);
  app.setApplicationName(CurrencyAdapter::instance().getCurrencyName() + "wallet");
  app.setApplicationVersion(Settings::instance().getVersion());
  app.setQuitOnLastWindowClosed(false);

#ifndef Q_OS_MAC
  QApplication::setStyle(QStyleFactory::create("Fusion"));
#endif

  CommandLineParser cmdLineParser(nullptr);
  Settings::instance().setCommandLineParser(&cmdLineParser);
  bool cmdLineParseResult = cmdLineParser.process(app.arguments());
  Settings::instance().load();

  //Translator must be created before the application's widgets.
  TranslatorManager* tmanager = TranslatorManager::instance();
  Q_UNUSED(tmanager)

  setlocale(LC_ALL, "");

  QFile File1(":/qdarkstyle/style.qss");
  File1.open(QFile::ReadOnly);
  QString StyleSheet1 = QLatin1String(File1.readAll());

  QFile File2(":/skin/dark.qss");
  File2.open(QFile::ReadOnly);
  QString StyleSheet2 = QLatin1String(File2.readAll());

  // fix font sizes for MacOS
  const char MAC_FIX_STYLE_SHEET[] = "QWidget{font-size:12px}";
#ifdef Q_OS_MAC
  qApp->setStyleSheet(MAC_FIX_STYLE_SHEET + StyleSheet1 + StyleSheet2);
#else
  qApp->setStyleSheet(StyleSheet1 + StyleSheet2);
#endif

  if (PaymentServer::ipcSendCommandLine())
  exit(0);

  PaymentServer* paymentServer = new PaymentServer(&app);

#ifdef Q_OS_WIN
  if(!cmdLineParseResult) {
    QMessageBox::critical(nullptr, QObject::tr("Error"), cmdLineParser.getErrorText());
    return app.exec();
  } else if (cmdLineParser.hasHelpOption()) {
    QMessageBox::information(nullptr, QObject::tr("Help"), cmdLineParser.getHelpText());
    return app.exec();
  }

  //Create registry entries for URL execution
  QSettings karbowanecKey("HKEY_CLASSES_ROOT\\karbowanec", QSettings::NativeFormat);
  karbowanecKey.setValue(".", "Karbo Wallet");
  karbowanecKey.setValue("URL Protocol", "");
  QSettings karbowanecOpenKey("HKEY_CLASSES_ROOT\\karbowanec\\shell\\open\\command", QSettings::NativeFormat);
  karbowanecOpenKey.setValue(".", "\"" + QCoreApplication::applicationFilePath().replace("/", "\\") + "\" \"%1\"");
#endif

#if defined(Q_OS_LINUX)
  QStringList args;
  QProcess exec;

  //as root
  args << "-c" << "printf '[Desktop Entry]\\nName = Karbo URL Handler\\nGenericName = Karbo\\nComment = Handle URL Sheme karbowanec://\\nExec = " + QCoreApplication::applicationFilePath() + " %%u\\nTerminal = false\\nType = Application\\nMimeType = x-scheme-handler/karbowanec;\\nIcon = Karbo-Wallet' | tee /usr/share/applications/karbowanec-handler.desktop";
  exec.start("/bin/sh", args);
  exec.waitForFinished();

  args.clear();
  args << "-c" << "update-desktop-database";
  exec.start("/bin/sh", args);
  exec.waitForFinished();
#endif

  LoggerAdapter::instance().init();

  QString dataDirPath = Settings::instance().getDataDir().absolutePath();

  if (!QDir().exists(dataDirPath)) {
    QDir().mkpath(dataDirPath);
  }

  QLockFile lockFile(Settings::instance().getDataDir().absoluteFilePath(QApplication::applicationName() + ".lock"));
  if (!lockFile.tryLock()) {
    QMessageBox::warning(nullptr, QObject::tr("Fail"), QObject::tr("%1 wallet already running or cannot create lock file %2. Check your permissions.").arg(CurrencyAdapter::instance().getCurrencyDisplayName()).arg(Settings::instance().getDataDir().absoluteFilePath(QApplication::applicationName() + ".lock")));
    return 0;
  }

  SignalHandler::instance().init();
  QObject::connect(&SignalHandler::instance(), &SignalHandler::quitSignal, &app, &QApplication::quit);

  if (splash == nullptr) {
    splash = new QSplashScreen(QPixmap(":images/splash"), Qt::X11BypassWindowManagerHint);
  }

  if (!splash->isVisible()) {
    splash->show();
  }

  splash->showMessage(QObject::tr("Loading blockchain..."), Qt::AlignLeft | Qt::AlignBottom, Qt::white);

  LogFileWatcher* logWatcher(nullptr);
  if (logWatcher == nullptr) {
    logWatcher = new LogFileWatcher(Settings::instance().getDataDir().absoluteFilePath(QCoreApplication::applicationName() + ".log"), &app);
    QObject::connect(logWatcher, &LogFileWatcher::newLogStringSignal, &app, &newLogString);
  }

  app.processEvents();
  qRegisterMetaType<CryptoNote::TransactionId>("CryptoNote::TransactionId");
  qRegisterMetaType<QList<CryptoNote::TransactionOutputInformation>>("QList<CryptoNote::TransactionOutputInformation>");
  qRegisterMetaType<quintptr>("quintptr");
  if (!NodeAdapter::instance().init()) {
    return 0;
  }

  splash->finish(&MainWindow::instance());

  if (logWatcher != nullptr) {
    logWatcher->deleteLater();
    logWatcher = nullptr;
  }

  splash->deleteLater();
  splash = nullptr;

  Updater *d = new Updater();
  d->checkForUpdate();

  MainWindow::instance().show();
  WalletAdapter::instance().open("");

  QTimer::singleShot(1000, paymentServer, SLOT(uiReady()));
  QObject::connect(paymentServer, &PaymentServer::receivedURI, &MainWindow::instance(), &MainWindow::handlePaymentRequest, Qt::QueuedConnection);

  QObject::connect(QApplication::instance(), &QApplication::aboutToQuit, []() {
    MainWindow::instance().quit();
    if (WalletAdapter::instance().isOpen()) {
      WalletAdapter::instance().close();
    }

    NodeAdapter::instance().deinit();
  });

  return app.exec();
}
<commit_msg>Those should be declared prior QApplication init<commit_after>// Copyright (c) 2011-2015 The Cryptonote developers
// Copyright (c) 2016-2020 The Karbowanec developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <QApplication>
#include <QCommandLineParser>
#include <QLocale>
#include <QTranslator>
#include <QLockFile>
#include <QMessageBox>
#include <QProcess>
#include <QRegularExpression>
#include <QSplashScreen>
#include <QStyleFactory>
#include <QSettings>
#include <QTextCodec>

#include "CommandLineParser.h"
#include "CurrencyAdapter.h"
#include "LoggerAdapter.h"
#include "NodeAdapter.h"
#include "Settings.h"
#include "SignalHandler.h"
#include "WalletAdapter.h"
#include "gui/MainWindow.h"
#include "Update.h"
#include "PaymentServer.h"
#include "TranslatorManager.h"
#include "LogFileWatcher.h"

#define DEBUG 1

using namespace WalletGui;

const QRegularExpression LOG_SPLASH_REG_EXP("\\] ");

QSplashScreen* splash(nullptr);

inline void newLogString(const QString& _string) {
  QRegularExpressionMatch match = LOG_SPLASH_REG_EXP.match(_string);
  if (match.hasMatch()) {
    QString message = _string.mid(match.capturedEnd());
    splash->showMessage(message, Qt::AlignLeft | Qt::AlignBottom, Qt::white);
  }
}

int main(int argc, char* argv[]) {
  QApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
  QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
  QApplication app(argc, argv);
  app.setApplicationName(CurrencyAdapter::instance().getCurrencyName() + "wallet");
  app.setApplicationVersion(Settings::instance().getVersion());
  app.setQuitOnLastWindowClosed(false);

#ifndef Q_OS_MAC
  QApplication::setStyle(QStyleFactory::create("Fusion"));
#endif

  CommandLineParser cmdLineParser(nullptr);
  Settings::instance().setCommandLineParser(&cmdLineParser);
  bool cmdLineParseResult = cmdLineParser.process(app.arguments());
  Settings::instance().load();

  //Translator must be created before the application's widgets.
  TranslatorManager* tmanager = TranslatorManager::instance();
  Q_UNUSED(tmanager)

  setlocale(LC_ALL, "");

  QFile File1(":/qdarkstyle/style.qss");
  File1.open(QFile::ReadOnly);
  QString StyleSheet1 = QLatin1String(File1.readAll());

  QFile File2(":/skin/dark.qss");
  File2.open(QFile::ReadOnly);
  QString StyleSheet2 = QLatin1String(File2.readAll());

  // fix font sizes for MacOS
  const char MAC_FIX_STYLE_SHEET[] = "QWidget{font-size:12px}";
#ifdef Q_OS_MAC
  qApp->setStyleSheet(MAC_FIX_STYLE_SHEET + StyleSheet1 + StyleSheet2);
#else
  qApp->setStyleSheet(StyleSheet1 + StyleSheet2);
#endif

  if (PaymentServer::ipcSendCommandLine())
  exit(0);

  PaymentServer* paymentServer = new PaymentServer(&app);

#ifdef Q_OS_WIN
  if(!cmdLineParseResult) {
    QMessageBox::critical(nullptr, QObject::tr("Error"), cmdLineParser.getErrorText());
    return app.exec();
  } else if (cmdLineParser.hasHelpOption()) {
    QMessageBox::information(nullptr, QObject::tr("Help"), cmdLineParser.getHelpText());
    return app.exec();
  }

  //Create registry entries for URL execution
  QSettings karbowanecKey("HKEY_CLASSES_ROOT\\karbowanec", QSettings::NativeFormat);
  karbowanecKey.setValue(".", "Karbo Wallet");
  karbowanecKey.setValue("URL Protocol", "");
  QSettings karbowanecOpenKey("HKEY_CLASSES_ROOT\\karbowanec\\shell\\open\\command", QSettings::NativeFormat);
  karbowanecOpenKey.setValue(".", "\"" + QCoreApplication::applicationFilePath().replace("/", "\\") + "\" \"%1\"");
#endif

#if defined(Q_OS_LINUX)
  QStringList args;
  QProcess exec;

  //as root
  args << "-c" << "printf '[Desktop Entry]\\nName = Karbo URL Handler\\nGenericName = Karbo\\nComment = Handle URL Sheme karbowanec://\\nExec = " + QCoreApplication::applicationFilePath() + " %%u\\nTerminal = false\\nType = Application\\nMimeType = x-scheme-handler/karbowanec;\\nIcon = Karbo-Wallet' | tee /usr/share/applications/karbowanec-handler.desktop";
  exec.start("/bin/sh", args);
  exec.waitForFinished();

  args.clear();
  args << "-c" << "update-desktop-database";
  exec.start("/bin/sh", args);
  exec.waitForFinished();
#endif

  LoggerAdapter::instance().init();

  QString dataDirPath = Settings::instance().getDataDir().absolutePath();

  if (!QDir().exists(dataDirPath)) {
    QDir().mkpath(dataDirPath);
  }

  QLockFile lockFile(Settings::instance().getDataDir().absoluteFilePath(QApplication::applicationName() + ".lock"));
  if (!lockFile.tryLock()) {
    QMessageBox::warning(nullptr, QObject::tr("Fail"), QObject::tr("%1 wallet already running or cannot create lock file %2. Check your permissions.").arg(CurrencyAdapter::instance().getCurrencyDisplayName()).arg(Settings::instance().getDataDir().absoluteFilePath(QApplication::applicationName() + ".lock")));
    return 0;
  }

  SignalHandler::instance().init();
  QObject::connect(&SignalHandler::instance(), &SignalHandler::quitSignal, &app, &QApplication::quit);

  if (splash == nullptr) {
    splash = new QSplashScreen(QPixmap(":images/splash"), Qt::X11BypassWindowManagerHint);
  }

  if (!splash->isVisible()) {
    splash->show();
  }

  splash->showMessage(QObject::tr("Loading blockchain..."), Qt::AlignLeft | Qt::AlignBottom, Qt::white);

  LogFileWatcher* logWatcher(nullptr);
  if (logWatcher == nullptr) {
    logWatcher = new LogFileWatcher(Settings::instance().getDataDir().absoluteFilePath(QCoreApplication::applicationName() + ".log"), &app);
    QObject::connect(logWatcher, &LogFileWatcher::newLogStringSignal, &app, &newLogString);
  }

  app.processEvents();
  qRegisterMetaType<CryptoNote::TransactionId>("CryptoNote::TransactionId");
  qRegisterMetaType<QList<CryptoNote::TransactionOutputInformation>>("QList<CryptoNote::TransactionOutputInformation>");
  qRegisterMetaType<quintptr>("quintptr");
  if (!NodeAdapter::instance().init()) {
    return 0;
  }

  splash->finish(&MainWindow::instance());

  if (logWatcher != nullptr) {
    logWatcher->deleteLater();
    logWatcher = nullptr;
  }

  splash->deleteLater();
  splash = nullptr;

  Updater *d = new Updater();
  d->checkForUpdate();

  MainWindow::instance().show();
  WalletAdapter::instance().open("");

  QTimer::singleShot(1000, paymentServer, SLOT(uiReady()));
  QObject::connect(paymentServer, &PaymentServer::receivedURI, &MainWindow::instance(), &MainWindow::handlePaymentRequest, Qt::QueuedConnection);

  QObject::connect(QApplication::instance(), &QApplication::aboutToQuit, []() {
    MainWindow::instance().quit();
    if (WalletAdapter::instance().isOpen()) {
      WalletAdapter::instance().close();
    }

    NodeAdapter::instance().deinit();
  });

  return app.exec();
}
<|endoftext|>


<commit_before>#include <ncurses.h>

#include "board.hpp"
using namespace roadagain;

int main()
{
    initscr();
    cbreak();
    noecho();

    Board().print();
    getch();

    endwin();
    return (0);
}
<commit_msg>Add init Colors part in main()<commit_after>#include <ncurses.h>

#include "board.hpp"
#include "color.hpp"
using namespace roadagain;

int main()
{
    initscr();
    cbreak();
    noecho();
    Colors.init();

    Board().print();
    getch();

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


<commit_before>#include <Bridge.h>
#include <BridgeClient.h>
#include <MQTT.h>
#include <ArduinoJson.h>

// Sensors and actuators libs
#include "Ultrasonic.h"
#include "DHT.h"

// MQTT credentials
#define MQTT_HOSTNAME
#define MQTT_USERNAME
#define MQTT_PASSWORD

// Networking
BridgeClient net;
MQTTClient client;

// Sensors and actuators
#define DHTTYPE DHT11

int ultrasonicPin = 2;
int DHTPin = 4;
int buzzerPin = 8;
int ledPin = 3;

DHT dht(DHTPin, DHTTYPE);
Ultrasonic ultrasonic(ultrasonicPin);

// Program
void connect()
{
    Serial.print("Connecting...");
    while (!client.connect("arduino", "try", "try"))
    {
        Serial.print(".");
        delay(1000);
    }

    Serial.println("\nConnected!");
    client.subscribe("/hello");
}

void messageReceived(String &topic, String &payload)
{
    Serial.println("incoming: " + topic + " - " + payload);
}

void setup()
{
    Bridge.begin();
    Serial.begin(115200);

    client.begin(MQTT_HOSTNAME, net);
    client.onMessage(messageReceived);
    connect();

    Serial.begin(9600);
    dht.begin();
    pinMode(buzzerPin, OUTPUT);
    pinMode(ledPin, OUTPUT);
}

void loop()
{
    // MQTT
    client.loop();
    if (!client.connected())
    {
        connect();
    }

    // read message and operate

    delay(1000);
}

void toggleDigital(int pin, int delayTime)
{
    digitalWrite(pin, HIGH);
    delay(delayTime);
    digitalWrite(pin, LOW);
}

void printDHT(float h, int t)
{
    Serial.print("Humidity: ");
    Serial.print(h);
    Serial.print("\t Temperature: ");
    Serial.print(t);
    Serial.println(" *C");
}
<commit_msg>macros<commit_after>#include <Bridge.h>
#include <BridgeClient.h>
#include <MQTT.h>
#include <ArduinoJson.h>

// Sensors and actuators libs
#include "Ultrasonic.h"
#include "DHT.h"

// MQTT credentials
#ifndef MQTT_HOSTNAME
#define MQTT_HOSTNAME ""
#endif
#ifndef MQTT_USERNAME
#define MQTT_USERNAME ""
#endif
#ifndef MQTT_PASSWORD
#define MQTT_PASSWORD ""
#endif

// Networking
BridgeClient net;
MQTTClient client;

// Sensors and actuators
#define DHTTYPE DHT11

int ultrasonicPin = 2;
int DHTPin = 4;
int buzzerPin = 8;
int ledPin = 3;

DHT dht(DHTPin, DHTTYPE);
Ultrasonic ultrasonic(ultrasonicPin);

// Program
void connect()
{
    Serial.print("Connecting...");
    while (!client.connect("arduino", "try", "try"))
    {
        Serial.print(".");
        delay(1000);
    }

    Serial.println("\nConnected!");
    client.subscribe("/hello");
}

void messageReceived(String &topic, String &payload)
{
    Serial.println("incoming: " + topic + " - " + payload);
}

void setup()
{
    Bridge.begin();
    Serial.begin(115200);

    client.begin(MQTT_HOSTNAME, net);
    client.onMessage(messageReceived);
    connect();

    Serial.begin(9600);
    dht.begin();
    pinMode(buzzerPin, OUTPUT);
    pinMode(ledPin, OUTPUT);
}

void loop()
{
    // MQTT
    client.loop();
    if (!client.connected())
    {
        connect();
    }

    // read message and operate

    delay(1000);
}

void toggleDigital(int pin, int delayTime)
{
    digitalWrite(pin, HIGH);
    delay(delayTime);
    digitalWrite(pin, LOW);
}

void printDHT(float h, int t)
{
    Serial.print("Humidity: ");
    Serial.print(h);
    Serial.print("\t Temperature: ");
    Serial.print(t);
    Serial.println(" *C");
}
<|endoftext|>


<commit_before>// The MIT License (MIT)
//
// Copyright (c) 2015 Relja Ljubobratovic, ljubobratovic.relja@gmail.com
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// Author:
// Relja Ljubobratovic, ljubobratovic.relja@gmail.com

#include <io.hpp>
#include <gui.hpp>
#include <image.hpp>
#include <improc.hpp>
#include <region.hpp>
#include <contour.hpp>
#include <draw.hpp>

#include <iostream>
#include <fstream>

#include "calibpattern.hpp"
#include "homography.hpp"

bool write_pattern_results(const std::vector<std::vector<cv::vec2r> > &patterns, const std::string &path) {

	std::ofstream stream(path);

	if (!stream.is_open()) {
		return false;
	}

	for (unsigned i = 0; i < patterns.size(); ++i) {
		stream << patterns[i][0];
		for (unsigned j = 1; j < patterns[i].size(); ++j) {
			stream << "," << patterns[i][j];
		}
		stream << std::endl;
	}

	stream.close();

	return true;
}

void pattern_detection() {

	std::string calib_patterns[] = {"1.png", "2.png", "3.png", "4.png", "5.png", "6.png", "7.png"};

	std::vector<std::vector<cv::vec2r> > patterns;

	for (auto im_path : calib_patterns) {

		auto image = cv::imread("/home/relja/calibration/ground_truth/" + im_path, cv::REAL, 1);

		unsigned p_rows = 6;
		unsigned p_cols = 9;

		cv::matrixr im_r = image, im_rb;
		cv::matrixr gauss_k = cv::gauss({5, 5});

		im_rb = cv::conv(im_r, gauss_k);

		auto pattern = detect_pattern(im_rb, p_rows, p_cols, 18., 0.15, 12);

		if (pattern.size() == p_rows*p_cols) {

			pattern = sub_pixel_detect(pattern, im_r, {5, 5});

			cv::matrix3r im_draw = im_r.clone();
			draw_chessboard(im_draw, pattern, {255., 0., 0.});

			cv::imshow("pattern", im_draw);
			auto r = cv::wait_key();

			if (r == 'n') {
				std::cout << "Pattern " << im_path << " rejected." << std::endl;
				continue;
			} else if (r == 'q') {
				std::cout << "Pattern detection exit" << std::endl;
				break;
			} else {
				std::cout << "Pattern " << im_path << " accepted." << std::endl;
				patterns.push_back(pattern);
			}
		} else {
			std::cout << "Pattern " << im_path << " not found" << std::endl;
			continue;
		}
	}

	std::string out_path;
	std::cout << "Where to write results?" << std::endl;
	std::cin >> out_path;

	if (write_pattern_results(patterns, out_path)) {
		std::cout << "Writing results to " << out_path << " successfull!" << std::endl;
	} else {
		std::cout << "Writing results to " << out_path << " failed!" << std::endl;
	}
}

cv::matrixr calculate_homography() {
	cv::matrixr H;
	return H;
}

std::vector<cv::vec3r> calculate_object_points(unsigned rows, unsigned cols, real_t square_size) {
	std::vector<cv::vec3r> obj_pts;
	obj_pts.reserve(rows*cols);

	for(unsigned i = 0; i < rows; ++i) {
		for(unsigned j = 0; j < cols; ++j) {
			obj_pts.push_back({static_cast<real_t>(j*square_size), static_cast<real_t>(i*square_size), static_cast<real_t>(0.)});
		}
	}

	return obj_pts;
}

int main() {

	//pattern_detection();

	std::vector<cv::vec2r> start = {{30., 10}, {12, 30}, {93, 12}, {12, 32}, {7, 5}, {12, 98}, {123, 543}};
	auto end = start;

	real_t x_offset = 10.0;
	real_t y_offset = 0.;
	for (auto &v : end) {
		v += {x_offset, y_offset};
	}

	for (auto i : start) {
		std::cout << i << " ";
	}
	std::cout << std::endl;
	for (auto i : end) {
		std::cout << i << " ";
	}
	std::cout << std::endl;

	cv::matrixr H;

	DLT(start, end, H);

	std::cout << H << std::endl;

	real_t err = 0.0;

	err += fabs(1.0 - H(0, 0));
	err += fabs(1.0 - H(1, 1));
	err += fabs(1.0 - H(2, 2));

	err += fabs(x_offset - H(0, 2));
	err += fabs(y_offset - H(1, 2));

	err += fabs(0.0 - H(0, 1));
	err += fabs(0.0 - H(1, 0));

	err += fabs(0.0 - H(2, 0));
	err += fabs(0.0 - H(2, 1));

	std::cout << "Homography calculation error: " << err << std::endl;

	return 0;
}
<commit_msg>implemented homography optimization using lev-marq and reprojection error<commit_after>// The MIT License (MIT)
//
// Copyright (c) 2015 Relja Ljubobratovic, ljubobratovic.relja@gmail.com
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// Author:
// Relja Ljubobratovic, ljubobratovic.relja@gmail.com

#include <io.hpp>
#include <gui.hpp>
#include <image.hpp>
#include <improc.hpp>
#include <region.hpp>
#include <contour.hpp>
#include <draw.hpp>
#include <linalg.hpp>
#include <optimization.hpp>

#include <iostream>
#include <fstream>

#include <minpack.h>

#include "calibpattern.hpp"
#include "homography.hpp"

bool write_pattern_results(const std::vector<std::vector<cv::vec2r> > &patterns, const std::string &path) {

	std::ofstream stream(path);

	if (!stream.is_open()) {
		return false;
	}

	for (unsigned i = 0; i < patterns.size(); ++i) {
		stream << patterns[i][0];
		for (unsigned j = 1; j < patterns[i].size(); ++j) {
			stream << "," << patterns[i][j];
		}
		stream << std::endl;
	}

	stream.close();

	return true;
}

void pattern_detection() {

	std::string calib_patterns[] = {"1.png", "2.png", "3.png", "4.png", "5.png", "6.png", "7.png"};

	std::vector<std::vector<cv::vec2r> > patterns;

	for (auto im_path : calib_patterns) {

		auto image = cv::imread("/home/relja/calibration/ground_truth/" + im_path, cv::REAL, 1);

		unsigned p_rows = 6;
		unsigned p_cols = 9;

		cv::matrixr im_r = image, im_rb;
		cv::matrixr gauss_k = cv::gauss({5, 5});

		im_rb = cv::conv(im_r, gauss_k);

		auto pattern = detect_pattern(im_rb, p_rows, p_cols, 18., 0.15, 12);

		if (pattern.size() == p_rows*p_cols) {

			pattern = sub_pixel_detect(pattern, im_r, {5, 5});

			cv::matrix3r im_draw = im_r.clone();
			draw_chessboard(im_draw, pattern, {255., 0., 0.});

			cv::imshow("pattern", im_draw);
			auto r = cv::wait_key();

			if (r == 'n') {
				std::cout << "Pattern " << im_path << " rejected." << std::endl;
				continue;
			} else if (r == 'q') {
				std::cout << "Pattern detection exit" << std::endl;
				break;
			} else {
				std::cout << "Pattern " << im_path << " accepted." << std::endl;
				patterns.push_back(pattern);
			}
		} else {
			std::cout << "Pattern " << im_path << " not found" << std::endl;
			continue;
		}
	}

	std::string out_path;
	std::cout << "Where to write results?" << std::endl;
	std::cin >> out_path;

	if (write_pattern_results(patterns, out_path)) {
		std::cout << "Writing results to " << out_path << " successfull!" << std::endl;
	} else {
		std::cout << "Writing results to " << out_path << " failed!" << std::endl;
	}
}

cv::matrixr calculate_homography() {
	cv::matrixr H;
	return H;
}

std::vector<cv::vec3r> calculate_object_points(unsigned rows, unsigned cols, real_t square_size) {
	std::vector<cv::vec3r> obj_pts;
	obj_pts.reserve(rows*cols);

	for(unsigned i = 0; i < rows; ++i) {
		for(unsigned j = 0; j < cols; ++j) {
			obj_pts.push_back({static_cast<real_t>(j*square_size), static_cast<real_t>(i*square_size), static_cast<real_t>(0.)});
		}
	}

	return obj_pts;
}

real_t calc_homography_error(const cv::matrixr &H, real_t x_offset, real_t y_offset) {

	real_t err = 0.0;

	err += fabs(1.0 - H(0, 0));
	err += fabs(1.0 - H(1, 1));
	err += fabs(1.0 - H(2, 2));

	err += fabs(x_offset - H(0, 2));
	err += fabs(y_offset - H(1, 2));

	err += fabs(0.0 - H(0, 1));
	err += fabs(0.0 - H(1, 0));

	err += fabs(0.0 - H(2, 0));
	err += fabs(0.0 - H(2, 1));

	return err;
}

int main() {

	//pattern_detection();
	std::vector<cv::vec2r> start = {{30., 10}, {12, 30}, {93, 12}, {12, 32}, {7, 5}, {12, 98}, {123, 543}, {321, 324}, {43, 65}, {123, 43}};
	std::vector<cv::vec2r> end;

	real_t x_offset = 10.0;
	real_t y_offset = 0.;

	end = start;

	for (auto &v : end) {
		v += {x_offset, y_offset};
	}

	for (auto i : start) {
		std::cout << i << " ";
	}
	std::cout << std::endl;
	for (auto i : end) {
		std::cout << i << " ";
	}
	std::cout << std::endl;

	cv::matrixr H;

	DLT(start, end, H);

	std::cout << "Initial homography:" << std::endl;
	std::cout << H << std::endl << std::endl;
	std::cout << "Initial homography calculation error: " << calc_homography_error(H, x_offset, y_offset) << std::endl;

	homography_optimization::source_pts = start;
	homography_optimization::target_pts = end;
	homography_optimization::evaluate(H, homography_optimization::reprojection_fcn);

	std::cout << "Homography after geometric error minimization:" << std::endl;
	std::cout << H << std::endl << std::endl;
	std::cout << "After geometric optimization, homography calculation error: " << calc_homography_error(H, x_offset, y_offset) << std::endl;

	return 0;
}
<|endoftext|>


<commit_before>#include "commandengine.h"
#include <cmath>
#include <iostream>

CommandEngine::CommandEngine() {
	mCommands = {
		{ "help", [](Args args) {
			std::string cmdStart = "   ";
			std::cout << "Commands:" << std::endl;
			std::cout << cmdStart << ":exit|:q|:quit Exits the program." << std::endl;
			std::cout << cmdStart << ":bin           Sets to display the result in base 2." << std::endl;
			std::cout << cmdStart << ":dec           Sets to display the result in base 10. (default)" << std::endl;
			std::cout << cmdStart << ":hex           Sets to display the result in base 16." << std::endl;
			std::cout << cmdStart << ":vars          Prints the defined variables." << std::endl;
			std::cout << cmdStart << ":mode          Sets the evaluation mode: float (default) or int." << std::endl;
			return false;
		} },
		{ "exit", [](Args args) {
			return true;
		} },
		{ "bin", [&](Args args) {
			mPrintNumBase = NumberBase::BINARY;
			return false;
		} },
		{ "dec", [&](Args args) {
			mPrintNumBase = NumberBase::DECIMAL;
			return false;
		} },
		{ "hex", [&](Args args) {
			mPrintNumBase = NumberBase::HEXADECIMAL;
			return false;
		} },
		{ "vars", [&](Args args) {
			for (auto var : mEnv.variables()) {
				std::cout << var.first << ": " << var.second << std::endl;
			}
			return false;
		} },
		{ "mode", [&](Args args) {
			if (args.size() == 1) {
				if (args[0] == "float") {
					mEngine.setEvalMode(ResultValueType::FLOAT);
				} else if (args[0] == "int") {
					mEngine.setEvalMode(ResultValueType::INTEGER);
				} else {
					std::cout << "'" << args[0] << "' is not a valid value. Valid values are: float and int." << std::endl;
				}
			} else {
				std::cout << "Expected one argument (float or int)." << std::endl;
			}
			return false;
		} },
	};

	//Aliases
	mCommands["q"] = mCommands["exit"];
	mCommands["quit"] = mCommands["exit"];
}

std::string toBase(int base, long value) {
	std::string res;
	while (value > 0) {
		res += std::to_string(value % base);
		value /= base;
	}

	return std::string(res.rbegin(), res.rend());
}

std::vector<std::string> splitString(std::string str, std::string delimiter) {
	std::vector<std::string> parts;

	size_t pos = 0;
	std::string token;
	while ((pos = str.find(delimiter)) != std::string::npos) {
	    token = str.substr(0, pos);
	    parts.push_back(token);
	    str.erase(0, pos + delimiter.length());
	}

	parts.push_back(str);
	return parts;
}

bool CommandEngine::execute(std::string line) {
	if (line[0] == ':' && line.size() > 1) {
		auto parts = splitString(line.substr(1), " ");
		std::string cmd = parts[0];

		if (mCommands.count(cmd) > 0) {
			parts.erase(parts.begin());
			return mCommands[cmd](parts);
		} else {
			std::cout << "There exists no command called '" + cmd + "'.";
		}
	}

	if (line == "") {
		return false;
	}

	try {
		auto res = mEngine.eval(line, mEnv);

		if (res.type() == ResultValueType::FLOAT) {
			//Display only different base if result is an integer
			double resInt;
			if (std::modf(res.doubleValue(), &resInt) == 0.0) {
				switch (mPrintNumBase) {
				case NumberBase::BINARY:
					std::cout << "0b" << toBase(2, (long)res.doubleValue()) << std::endl;
					break;
				case NumberBase::DECIMAL:
					std::cout << std::dec << res << std::endl;
					break;
				case NumberBase::HEXADECIMAL:
					std::cout << std::hex << "0x" << (long)res.doubleValue() << std::endl;
					break;
				}
			} else {
				std::cout << std::dec << res << std::endl;
			}
		} else {
			switch (mPrintNumBase) {
			case NumberBase::BINARY:
				std::cout << "0b" << toBase(2, res.longValue()) << std::endl;
				break;
			case NumberBase::DECIMAL:
				std::cout << std::dec << res << std::endl;
				break;
			case NumberBase::HEXADECIMAL:
				std::cout << std::hex << "0x" << res.longValue() << std::endl;
				break;
			}
		}

		mEnv.set("ans", res);
	} catch (std::runtime_error& e) {
		std::cout << "Error: " << e.what() << std::endl;
	}

	return false;
}<commit_msg>Fixed error message for invalid commands.<commit_after>#include "commandengine.h"
#include <cmath>
#include <iostream>

CommandEngine::CommandEngine() {
	mCommands = {
		{ "help", [](Args args) {
			std::string cmdStart = "   ";
			std::cout << "Commands:" << std::endl;
			std::cout << cmdStart << ":exit|:q|:quit Exits the program." << std::endl;
			std::cout << cmdStart << ":bin           Sets to display the result in base 2." << std::endl;
			std::cout << cmdStart << ":dec           Sets to display the result in base 10. (default)" << std::endl;
			std::cout << cmdStart << ":hex           Sets to display the result in base 16." << std::endl;
			std::cout << cmdStart << ":vars          Prints the defined variables." << std::endl;
			std::cout << cmdStart << ":mode          Sets the evaluation mode: float (default) or int." << std::endl;
			return false;
		} },
		{ "exit", [](Args args) {
			return true;
		} },
		{ "bin", [&](Args args) {
			mPrintNumBase = NumberBase::BINARY;
			return false;
		} },
		{ "dec", [&](Args args) {
			mPrintNumBase = NumberBase::DECIMAL;
			return false;
		} },
		{ "hex", [&](Args args) {
			mPrintNumBase = NumberBase::HEXADECIMAL;
			return false;
		} },
		{ "vars", [&](Args args) {
			for (auto var : mEnv.variables()) {
				std::cout << var.first << ": " << var.second << std::endl;
			}
			return false;
		} },
		{ "mode", [&](Args args) {
			if (args.size() == 1) {
				if (args[0] == "float") {
					mEngine.setEvalMode(ResultValueType::FLOAT);
				} else if (args[0] == "int") {
					mEngine.setEvalMode(ResultValueType::INTEGER);
				} else {
					std::cout << "'" << args[0] << "' is not a valid value. Valid values are: float and int." << std::endl;
				}
			} else {
				std::cout << "Expected one argument (float or int)." << std::endl;
			}
			return false;
		} },
	};

	//Aliases
	mCommands["q"] = mCommands["exit"];
	mCommands["quit"] = mCommands["exit"];
}

std::string toBase(int base, long value) {
	std::string res;
	while (value > 0) {
		res += std::to_string(value % base);
		value /= base;
	}

	return std::string(res.rbegin(), res.rend());
}

std::vector<std::string> splitString(std::string str, std::string delimiter) {
	std::vector<std::string> parts;

	size_t pos = 0;
	std::string token;
	while ((pos = str.find(delimiter)) != std::string::npos) {
	    token = str.substr(0, pos);
	    parts.push_back(token);
	    str.erase(0, pos + delimiter.length());
	}

	parts.push_back(str);
	return parts;
}

bool CommandEngine::execute(std::string line) {
	if (line[0] == ':' && line.size() > 1) {
		auto parts = splitString(line.substr(1), " ");
		std::string cmd = parts[0];

		if (mCommands.count(cmd) > 0) {
			parts.erase(parts.begin());
			return mCommands[cmd](parts);
		} else {
			std::cout << "There exists no command called '" + cmd + "'." << std::endl;
		}

		return false;
	}

	if (line == "") {
		return false;
	}

	try {
		auto res = mEngine.eval(line, mEnv);

		if (res.type() == ResultValueType::FLOAT) {
			//Display only different base if result is an integer
			double resInt;
			if (std::modf(res.doubleValue(), &resInt) == 0.0) {
				switch (mPrintNumBase) {
				case NumberBase::BINARY:
					std::cout << "0b" << toBase(2, (long)res.doubleValue()) << std::endl;
					break;
				case NumberBase::DECIMAL:
					std::cout << std::dec << res << std::endl;
					break;
				case NumberBase::HEXADECIMAL:
					std::cout << std::hex << "0x" << (long)res.doubleValue() << std::endl;
					break;
				}
			} else {
				std::cout << std::dec << res << std::endl;
			}
		} else {
			switch (mPrintNumBase) {
			case NumberBase::BINARY:
				std::cout << "0b" << toBase(2, res.longValue()) << std::endl;
				break;
			case NumberBase::DECIMAL:
				std::cout << std::dec << res << std::endl;
				break;
			case NumberBase::HEXADECIMAL:
				std::cout << std::hex << "0x" << res.longValue() << std::endl;
				break;
			}
		}

		mEnv.set("ans", res);
	} catch (std::runtime_error& e) {
		std::cout << "Error: " << e.what() << std::endl;
	}

	return false;
}<|endoftext|>


<commit_before>// Copyright (c) 2016-2020 The ZCash developers
// Copyright (c) 2020 The PIVX developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "wallet/test/wallet_test_fixture.h"

#include "sapling/sapling_util.h"
#include "sapling/address.h"
#include "wallet/wallet.h"
#include "wallet/walletdb.h"
#include "util.h"
#include <boost/test/unit_test.hpp>

/**
 * This test covers methods on CWallet
 * GenerateNewZKey()
 * AddZKey()
 * LoadZKey()
 * LoadZKeyMetadata()
 */

BOOST_FIXTURE_TEST_SUITE(wallet_zkeys_tests, WalletTestingSetup)

/**
  * This test covers Sapling methods on CWallet
  * GenerateNewSaplingZKey()
  * AddSaplingZKey()
  * LoadSaplingZKey()
  * LoadSaplingZKeyMetadata()
  */
BOOST_AUTO_TEST_CASE(StoreAndLoadSaplingZkeys) {
    SelectParams(CBaseChainParams::MAIN);

    CWallet wallet;
    LOCK(wallet.cs_wallet);
    // wallet should be empty
    std::set<libzcash::SaplingPaymentAddress> addrs;
    wallet.GetSaplingPaymentAddresses(addrs);
    BOOST_CHECK_EQUAL(0, addrs.size());

    // No HD seed in the wallet
    BOOST_CHECK_THROW(wallet.GenerateNewSaplingZKey(), std::runtime_error);

    // Random seed
    CKey seed;
    seed.MakeNewKey(true);
    wallet.AddKeyPubKey(seed, seed.GetPubKey());
    wallet.GetSaplingScriptPubKeyMan()->SetHDSeed(seed.GetPubKey(), false, true);

    // wallet should have one key
    auto address = wallet.GenerateNewSaplingZKey();
    wallet.GetSaplingPaymentAddresses(addrs);
    BOOST_CHECK_EQUAL(1, addrs.size());

    // verify wallet has incoming viewing key for the address
    BOOST_CHECK(wallet.HaveSaplingIncomingViewingKey(address));

    // manually add new spending key to wallet
    HDSeed seed1(seed.GetPrivKey());
    auto m = libzcash::SaplingExtendedSpendingKey::Master(seed1);
    auto sk = m.Derive(0);
    BOOST_CHECK(wallet.AddSaplingZKey(sk));

    // verify wallet did add it
    auto extfvk = sk.ToXFVK();
    BOOST_CHECK(wallet.HaveSaplingSpendingKey(extfvk));

    // verify spending key stored correctly
    libzcash::SaplingExtendedSpendingKey keyOut;
    wallet.GetSaplingSpendingKey(extfvk, keyOut);
    BOOST_CHECK(sk == keyOut);

    // verify there are two keys
    wallet.GetSaplingPaymentAddresses(addrs);
    BOOST_CHECK_EQUAL(2, addrs.size());
    BOOST_CHECK_EQUAL(1, addrs.count(address));
    BOOST_CHECK_EQUAL(1, addrs.count(sk.DefaultAddress()));

    // Generate a diversified address different to the default
    // If we can't get an early diversified address, we are very unlucky
    blob88 diversifier;
    diversifier.begin()[0] = 10;
    auto dpa = sk.ToXFVK().Address(diversifier).get().second;

    // verify wallet only has the default address
    libzcash::SaplingPaymentAddress defaultAddr = sk.DefaultAddress();
    BOOST_CHECK(wallet.HaveSaplingIncomingViewingKey(defaultAddr));

    // Keep trying different diversifiers until we get a different address
    while (dpa == defaultAddr && diversifier.begin()[0] < 255) {
        diversifier.begin()[0] += 1;
        dpa = sk.ToXFVK().Address(diversifier).get().second;
    }
    BOOST_CHECK(!wallet.HaveSaplingIncomingViewingKey(dpa));

    // manually add a diversified address
    auto ivk = extfvk.fvk.in_viewing_key();
    BOOST_CHECK(wallet.AddSaplingIncomingViewingKeyW(ivk, dpa));

    // verify wallet did add it
    BOOST_CHECK(wallet.HaveSaplingIncomingViewingKey(sk.DefaultAddress()));
    BOOST_CHECK(wallet.HaveSaplingIncomingViewingKey(dpa));

    // Load a third key into the wallet
    auto sk2 = m.Derive(1);
    BOOST_CHECK(wallet.LoadSaplingZKey(sk2));

    // attach metadata to this third key
    auto ivk2 = sk2.expsk.full_viewing_key().in_viewing_key();
    int64_t now = GetTime();
    CKeyMetadata meta(now);
    BOOST_CHECK(wallet.LoadSaplingZKeyMetadata(ivk2, meta));

    // check metadata is the same
    BOOST_CHECK_EQUAL(wallet.GetSaplingScriptPubKeyMan()->mapSaplingZKeyMetadata[ivk2].nCreateTime, now);

    // Load a diversified address for the third key into the wallet
    auto dpa2 = sk2.ToXFVK().Address(diversifier).get().second;
    BOOST_CHECK(wallet.HaveSaplingIncomingViewingKey(sk2.DefaultAddress()));
    BOOST_CHECK(!wallet.HaveSaplingIncomingViewingKey(dpa2));
    BOOST_CHECK(wallet.LoadSaplingPaymentAddress(dpa2, ivk2));
    BOOST_CHECK(wallet.HaveSaplingIncomingViewingKey(dpa2));
}

/**
  * This test covers methods on CWalletDB to load/save crypted sapling z keys.
  */
BOOST_AUTO_TEST_CASE(WriteCryptedSaplingZkeyDirectToDb) {
    SelectParams(CBaseChainParams::TESTNET);

    BOOST_CHECK(!pwalletMain->HasSaplingSPKM());
    assert(pwalletMain->SetupSPKM(true));

    // wallet should be empty
    std::set<libzcash::SaplingPaymentAddress> addrs;
    pwalletMain->GetSaplingPaymentAddresses(addrs);
    BOOST_CHECK_EQUAL(0, addrs.size());

    // Add random key to the wallet
    auto address = pwalletMain->GenerateNewSaplingZKey();

    // wallet should have one key
    pwalletMain->GetSaplingPaymentAddresses(addrs);
    BOOST_CHECK_EQUAL(1, addrs.size());

    // encrypt wallet
    SecureString strWalletPass;
    strWalletPass.reserve(100);
    strWalletPass = "hello";
    BOOST_CHECK(pwalletMain->EncryptWallet(strWalletPass));

    // adding a new key will fail as the wallet is locked
    BOOST_CHECK_THROW(pwalletMain->GenerateNewSaplingZKey(), std::runtime_error);

    // unlock wallet and then add
    pwalletMain->Unlock(strWalletPass);
    libzcash::SaplingPaymentAddress address2 = pwalletMain->GenerateNewSaplingZKey();

    // Create a new wallet from the existing wallet path
    bool fFirstRun;
    std::unique_ptr<CWalletDBWrapper> dbw(new CWalletDBWrapper(&bitdb, pwalletMain->GetDBHandle().GetName()));
    CWallet wallet2(std::move(dbw));
    BOOST_CHECK_EQUAL(DB_LOAD_OK, wallet2.LoadWallet(fFirstRun));

    // Confirm it's not the same as the other wallet
    BOOST_CHECK(pwalletMain != &wallet2);
    BOOST_CHECK(wallet2.HasSaplingSPKM());

    // wallet should have two keys
    wallet2.GetSaplingPaymentAddresses(addrs);
    BOOST_CHECK_EQUAL(2, addrs.size());

    //check we have entries for our payment addresses
    BOOST_CHECK(addrs.count(address));
    BOOST_CHECK(addrs.count(address2));

    // spending key is crypted, so we can't extract valid payment address
    libzcash::SaplingExtendedSpendingKey keyOut;
    BOOST_CHECK(!wallet2.GetSaplingExtendedSpendingKey(address, keyOut));

    // unlock wallet to get spending keys and verify payment addresses
    wallet2.Unlock(strWalletPass);

    BOOST_CHECK(wallet2.GetSaplingExtendedSpendingKey(address, keyOut));
    BOOST_CHECK(address == keyOut.DefaultAddress());

    BOOST_CHECK(wallet2.GetSaplingExtendedSpendingKey(address2, keyOut));
    BOOST_CHECK(address2 == keyOut.DefaultAddress());
}

BOOST_AUTO_TEST_SUITE_END()
<commit_msg>[Tests] Check for diversified addresse equal to default one<commit_after>// Copyright (c) 2016-2020 The ZCash developers
// Copyright (c) 2020 The PIVX developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "wallet/test/wallet_test_fixture.h"

#include "sapling/sapling_util.h"
#include "sapling/address.h"
#include "wallet/wallet.h"
#include "wallet/walletdb.h"
#include "util.h"
#include <boost/test/unit_test.hpp>

/**
 * This test covers methods on CWallet
 * GenerateNewZKey()
 * AddZKey()
 * LoadZKey()
 * LoadZKeyMetadata()
 */

BOOST_FIXTURE_TEST_SUITE(wallet_zkeys_tests, WalletTestingSetup)

/**
  * This test covers Sapling methods on CWallet
  * GenerateNewSaplingZKey()
  * AddSaplingZKey()
  * LoadSaplingZKey()
  * LoadSaplingZKeyMetadata()
  */
BOOST_AUTO_TEST_CASE(StoreAndLoadSaplingZkeys) {
    SelectParams(CBaseChainParams::MAIN);

    CWallet wallet;
    LOCK(wallet.cs_wallet);
    // wallet should be empty
    std::set<libzcash::SaplingPaymentAddress> addrs;
    wallet.GetSaplingPaymentAddresses(addrs);
    BOOST_CHECK_EQUAL(0, addrs.size());

    // No HD seed in the wallet
    BOOST_CHECK_THROW(wallet.GenerateNewSaplingZKey(), std::runtime_error);

    // Random seed
    CKey seed;
    seed.MakeNewKey(true);
    wallet.AddKeyPubKey(seed, seed.GetPubKey());
    wallet.GetSaplingScriptPubKeyMan()->SetHDSeed(seed.GetPubKey(), false, true);

    // wallet should have one key
    auto address = wallet.GenerateNewSaplingZKey();
    wallet.GetSaplingPaymentAddresses(addrs);
    BOOST_CHECK_EQUAL(1, addrs.size());

    // verify wallet has incoming viewing key for the address
    BOOST_CHECK(wallet.HaveSaplingIncomingViewingKey(address));

    // manually add new spending key to wallet
    HDSeed seed1(seed.GetPrivKey());
    auto m = libzcash::SaplingExtendedSpendingKey::Master(seed1);
    auto sk = m.Derive(0);
    BOOST_CHECK(wallet.AddSaplingZKey(sk));

    // verify wallet did add it
    auto extfvk = sk.ToXFVK();
    BOOST_CHECK(wallet.HaveSaplingSpendingKey(extfvk));

    // verify spending key stored correctly
    libzcash::SaplingExtendedSpendingKey keyOut;
    wallet.GetSaplingSpendingKey(extfvk, keyOut);
    BOOST_CHECK(sk == keyOut);

    // verify there are two keys
    wallet.GetSaplingPaymentAddresses(addrs);
    BOOST_CHECK_EQUAL(2, addrs.size());
    BOOST_CHECK_EQUAL(1, addrs.count(address));
    BOOST_CHECK_EQUAL(1, addrs.count(sk.DefaultAddress()));

    // Generate a diversified address different to the default
    // If we can't get an early diversified address, we are very unlucky
    blob88 diversifier;
    diversifier.begin()[0] = 10;
    auto dpa = sk.ToXFVK().Address(diversifier).get().second;

    // verify wallet only has the default address
    libzcash::SaplingPaymentAddress defaultAddr = sk.DefaultAddress();
    BOOST_CHECK(wallet.HaveSaplingIncomingViewingKey(defaultAddr));

    // Keep trying different diversifiers until we get a different address
    while (dpa == defaultAddr && diversifier.begin()[0] < 255) {
        diversifier.begin()[0] += 1;
        dpa = sk.ToXFVK().Address(diversifier).get().second;
    }
    BOOST_CHECK(!wallet.HaveSaplingIncomingViewingKey(dpa));

    // manually add a diversified address
    auto ivk = extfvk.fvk.in_viewing_key();
    BOOST_CHECK(wallet.AddSaplingIncomingViewingKeyW(ivk, dpa));

    // verify wallet did add it
    BOOST_CHECK(wallet.HaveSaplingIncomingViewingKey(sk.DefaultAddress()));
    BOOST_CHECK(wallet.HaveSaplingIncomingViewingKey(dpa));

    // Load a third key into the wallet
    auto sk2 = m.Derive(1);
    BOOST_CHECK(wallet.LoadSaplingZKey(sk2));

    // attach metadata to this third key
    auto ivk2 = sk2.expsk.full_viewing_key().in_viewing_key();
    int64_t now = GetTime();
    CKeyMetadata meta(now);
    BOOST_CHECK(wallet.LoadSaplingZKeyMetadata(ivk2, meta));

    // check metadata is the same
    BOOST_CHECK_EQUAL(wallet.GetSaplingScriptPubKeyMan()->mapSaplingZKeyMetadata[ivk2].nCreateTime, now);

    // Load a diversified address for the third key into the wallet
    libzcash::SaplingPaymentAddress defaultAddr2 = sk2.DefaultAddress();
    diversifier.begin()[0] = 10;
    auto dpa2 = sk2.ToXFVK().Address(diversifier).get().second;
    while (dpa2 == defaultAddr2 && diversifier.begin()[0] < 255) {
        diversifier.begin()[0] += 1;
        dpa2 = sk2.ToXFVK().Address(diversifier).get().second;
    }
    BOOST_CHECK(wallet.HaveSaplingIncomingViewingKey(sk2.DefaultAddress()));
    BOOST_CHECK(!wallet.HaveSaplingIncomingViewingKey(dpa2));
    BOOST_CHECK(wallet.LoadSaplingPaymentAddress(dpa2, ivk2));
    BOOST_CHECK(wallet.HaveSaplingIncomingViewingKey(dpa2));
}

/**
  * This test covers methods on CWalletDB to load/save crypted sapling z keys.
  */
BOOST_AUTO_TEST_CASE(WriteCryptedSaplingZkeyDirectToDb) {
    SelectParams(CBaseChainParams::TESTNET);

    BOOST_CHECK(!pwalletMain->HasSaplingSPKM());
    assert(pwalletMain->SetupSPKM(true));

    // wallet should be empty
    std::set<libzcash::SaplingPaymentAddress> addrs;
    pwalletMain->GetSaplingPaymentAddresses(addrs);
    BOOST_CHECK_EQUAL(0, addrs.size());

    // Add random key to the wallet
    auto address = pwalletMain->GenerateNewSaplingZKey();

    // wallet should have one key
    pwalletMain->GetSaplingPaymentAddresses(addrs);
    BOOST_CHECK_EQUAL(1, addrs.size());

    // encrypt wallet
    SecureString strWalletPass;
    strWalletPass.reserve(100);
    strWalletPass = "hello";
    BOOST_CHECK(pwalletMain->EncryptWallet(strWalletPass));

    // adding a new key will fail as the wallet is locked
    BOOST_CHECK_THROW(pwalletMain->GenerateNewSaplingZKey(), std::runtime_error);

    // unlock wallet and then add
    pwalletMain->Unlock(strWalletPass);
    libzcash::SaplingPaymentAddress address2 = pwalletMain->GenerateNewSaplingZKey();

    // Create a new wallet from the existing wallet path
    bool fFirstRun;
    std::unique_ptr<CWalletDBWrapper> dbw(new CWalletDBWrapper(&bitdb, pwalletMain->GetDBHandle().GetName()));
    CWallet wallet2(std::move(dbw));
    BOOST_CHECK_EQUAL(DB_LOAD_OK, wallet2.LoadWallet(fFirstRun));

    // Confirm it's not the same as the other wallet
    BOOST_CHECK(pwalletMain != &wallet2);
    BOOST_CHECK(wallet2.HasSaplingSPKM());

    // wallet should have two keys
    wallet2.GetSaplingPaymentAddresses(addrs);
    BOOST_CHECK_EQUAL(2, addrs.size());

    //check we have entries for our payment addresses
    BOOST_CHECK(addrs.count(address));
    BOOST_CHECK(addrs.count(address2));

    // spending key is crypted, so we can't extract valid payment address
    libzcash::SaplingExtendedSpendingKey keyOut;
    BOOST_CHECK(!wallet2.GetSaplingExtendedSpendingKey(address, keyOut));

    // unlock wallet to get spending keys and verify payment addresses
    wallet2.Unlock(strWalletPass);

    BOOST_CHECK(wallet2.GetSaplingExtendedSpendingKey(address, keyOut));
    BOOST_CHECK(address == keyOut.DefaultAddress());

    BOOST_CHECK(wallet2.GetSaplingExtendedSpendingKey(address2, keyOut));
    BOOST_CHECK(address2 == keyOut.DefaultAddress());
}

BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>


<commit_before>/* bzflag
 * Copyright (c) 1993 - 2004 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named LICENSE that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */
#if defined(_MSC_VER)
// turn off bogus `this used in base member initialization list'
#  pragma warning(disable: 4786)
#endif

#include "global.h"

const struct GlobalDBItem globalDBItems[] = {
  { "_agilityAdVel",		"2.25",				false, StateDatabase::Locked},
  { "_agilityTimeWindow",	"1.0",				false, StateDatabase::Locked},
  { "_agilityVelDelta",	        "0.3",				false, StateDatabase::Locked},
  { "_angleTolerance",		"0.05",				false, StateDatabase::Locked},
  { "_angularAd",		"1.5",				false, StateDatabase::Locked},
  { "_avenueSize",		"2.0*_boxBase",			false, StateDatabase::Locked},
  { "_baseSize",		"60.0",                         false, StateDatabase::Locked},
  { "_boxBase",			"30.0",				false, StateDatabase::Locked},
  { "_boxHeight",		"6.0*_muzzleHeight",		false, StateDatabase::Locked},
  { "_burrowAngularAd",		"0.55",				false, StateDatabase::Locked},
  { "_burrowDepth",		"-1.32",			false, StateDatabase::Locked},
  { "_burrowSpeedAd",		"0.80",				false, StateDatabase::Locked},
  { "_deadUnder",		"-32767.0",			false, StateDatabase::Locked},
  { "_explodeTime",		"5.0",				false, StateDatabase::Locked},
  { "_fakeLag",			"0.5",				false, StateDatabase::Locked},
  { "_flagAltitude",		"11.0",				false, StateDatabase::Locked},
  { "_flagHeight",		"10.0",				false, StateDatabase::Locked},
  { "_flagPoleWidth",		"0.025",                        false, StateDatabase::Locked},
  { "_flagPoleSize",		"0.8",				false, StateDatabase::Locked},
  { "_flagRadius",		"2.5",				false, StateDatabase::Locked},
  { "_friction",		"0",				false, StateDatabase::Locked},
  { "_gMissileAng",		"0.628319",			false, StateDatabase::Locked},
  { "_gMissileAdLife",		"0.95",				false, StateDatabase::Locked},
  { "_gravity",			"-9.8",				false, StateDatabase::Locked},
  { "_identifyRange",		"50.0",				false, StateDatabase::Locked},
  { "_jumpVelocity",		"19.0",				false, StateDatabase::Locked},
  { "_laserAdLife",		"0.1",				false, StateDatabase::Locked},
  { "_laserAdRate",		"0.5",				false, StateDatabase::Locked},
  { "_laserAdVel",		"1000.0",			false, StateDatabase::Locked},
  { "_lockOnAngle",		"0.15",				false, StateDatabase::Locked},
  { "_lRAdRate",		"0.5",				false, StateDatabase::Locked},
  { "_maxAngVel",		"_tankAngVel * _angularAd",	false, StateDatabase::Locked},
  { "_maxBumpHeight",		"0.33",				false, StateDatabase::Locked},
  { "_maxFlagGrabs",		"4.0",				false, StateDatabase::Locked},
  { "_maxLOD",			"32767.0",			false, StateDatabase::Locked},
  { "_maxVel",			"_tankSpeed * _agilityAdVel",	false, StateDatabase::Locked},
  { "_momentumAngAcc",		"1.0",				false, StateDatabase::Locked},
  { "_momentumLinAcc",		"1.0",				false, StateDatabase::Locked},
  { "_momentumFriction",	"0",				false, StateDatabase::Locked},
  { "_mGunAdLife",		"1.0 / _mGunAdRate",		false, StateDatabase::Locked},
  { "_mGunAdRate",		"10.0",				false, StateDatabase::Locked},
  { "_mGunAdVel",		"1.5",				false, StateDatabase::Locked},
  { "_muzzleFront",		"_tankRadius + 0.1",		false, StateDatabase::Locked},
  { "_muzzleHeight",		"1.57",				false, StateDatabase::Locked},
  { "_noSmallPackets",		"0",				false, StateDatabase::Locked},
  { "_notRespondingTime",	"5.0",				false, StateDatabase::Locked},
  { "_obeseFactor",		"2.5",				false, StateDatabase::Locked},
  { "_pauseDropTime",		"15.0",				false, StateDatabase::Locked},
  { "_positionTolerance",	"0.09",				false, StateDatabase::Locked},
  { "_pyrBase",			"4.0*_tankHeight",		false, StateDatabase::Locked},
  { "_pyrHeight",		"5.0*_tankHeight",		false, StateDatabase::Locked},
  { "_rejoinTime",		"_explodeTime",			false, StateDatabase::Locked},
  { "_reloadTime",		"_shotRange / _shotSpeed",	false, StateDatabase::Locked},
  { "_rFireAdLife",		"1.0 / _rFireAdRate",		false, StateDatabase::Locked},
  { "_rFireAdRate",		"2.0",				false, StateDatabase::Locked},
  { "_rFireAdVel",		"1.5",				false, StateDatabase::Locked},
  { "_shieldFlight",		"2.7",				false, StateDatabase::Locked},
  { "_shockAdLife",		"0.2",				false, StateDatabase::Locked},
  { "_shockInRadius",		"_tankLength",			false, StateDatabase::Locked},
  { "_shockOutRadius",		"60.0",				false, StateDatabase::Locked},
  { "_shotTailLength",		"4.0",				false, StateDatabase::Locked},
  { "_shotRadius",		"0.5",				false, StateDatabase::Locked},
  { "_shotRange",		"350.0",			false, StateDatabase::Locked},
  { "_shotSpeed",		"100.0",			false, StateDatabase::Locked},
  { "_shotsKeepVerticalVelocity",	"0",			false, StateDatabase::Locked},
  { "_srRadiusMult",		"2.0",				false, StateDatabase::Locked},
  { "_syncTime",		"0",				false, StateDatabase::Locked},
  { "_tankExplosionSize",	"3.5 * _tankLength", 		false, StateDatabase::Locked},
  { "_tankAngVel",		"0.785398", 			false, StateDatabase::Locked},
  { "_tankHeight",		"2.05",				false, StateDatabase::Locked},
  { "_tankLength",		"6.0",				false, StateDatabase::Locked},
  { "_tankRadius",		"0.72 * _tankLength",		false, StateDatabase::Locked},
  { "_tankSpeed",		"25.0",				false, StateDatabase::Locked},
  { "_tankWidth",		"2.8",				false, StateDatabase::Locked},
  { "_targetingAngle",		"0.3",				false, StateDatabase::Locked},
  { "_teleportBreadth",		"4.48",				false, StateDatabase::Locked},
  { "_teleportHeight",		"10.08",			false, StateDatabase::Locked},
  { "_teleportTime",		"1.0",				false, StateDatabase::Locked},
  { "_teleportWidth",		"1.12",				false, StateDatabase::Locked},
  { "_thiefAdLife",		"0.05",				false, StateDatabase::Locked},
  { "_thiefAdRate",		"12.0",				false, StateDatabase::Locked},
  { "_thiefAdShotVel",		"8.0",				false, StateDatabase::Locked},
  { "_thiefTinyFactor",		"0.5",				false, StateDatabase::Locked},
  { "_thiefVelAd",		"1.67",				false, StateDatabase::Locked},
  { "_thiefDropTime",		"_reloadTime * 0.5",		false, StateDatabase::Locked},
  { "_tinyFactor",		"0.4",				false, StateDatabase::Locked},
  { "_updateThrottleRate",	"30.0",				false, StateDatabase::Locked},
  { "_velocityAd",		"1.5",				false, StateDatabase::Locked},
  { "_wallHeight",		"3.0*_tankHeight",		false, StateDatabase::Locked},
  { "_wideAngleAng",		"1.745329", 			false, StateDatabase::Locked},
  { "_wingsGravity",		"_gravity",			false, StateDatabase::Locked},
  { "_wingsJumpCount",		"1",				false, StateDatabase::Locked},
  { "_wingsJumpVelocity",	"_jumpVelocity",		false, StateDatabase::Locked},
  { "_worldSize",		"800.0",			false, StateDatabase::Locked}
};
const unsigned int	numGlobalDBItems = countof(globalDBItems);

// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>disable smallPackets for now, remove later<commit_after>/* bzflag
 * Copyright (c) 1993 - 2004 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named LICENSE that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */
#if defined(_MSC_VER)
// turn off bogus `this used in base member initialization list'
#  pragma warning(disable: 4786)
#endif

#include "global.h"

const struct GlobalDBItem globalDBItems[] = {
  { "_agilityAdVel",		"2.25",				false, StateDatabase::Locked},
  { "_agilityTimeWindow",	"1.0",				false, StateDatabase::Locked},
  { "_agilityVelDelta",	        "0.3",				false, StateDatabase::Locked},
  { "_angleTolerance",		"0.05",				false, StateDatabase::Locked},
  { "_angularAd",		"1.5",				false, StateDatabase::Locked},
  { "_avenueSize",		"2.0*_boxBase",			false, StateDatabase::Locked},
  { "_baseSize",		"60.0",                         false, StateDatabase::Locked},
  { "_boxBase",			"30.0",				false, StateDatabase::Locked},
  { "_boxHeight",		"6.0*_muzzleHeight",		false, StateDatabase::Locked},
  { "_burrowAngularAd",		"0.55",				false, StateDatabase::Locked},
  { "_burrowDepth",		"-1.32",			false, StateDatabase::Locked},
  { "_burrowSpeedAd",		"0.80",				false, StateDatabase::Locked},
  { "_deadUnder",		"-32767.0",			false, StateDatabase::Locked},
  { "_explodeTime",		"5.0",				false, StateDatabase::Locked},
  { "_fakeLag",			"0.5",				false, StateDatabase::Locked},
  { "_flagAltitude",		"11.0",				false, StateDatabase::Locked},
  { "_flagHeight",		"10.0",				false, StateDatabase::Locked},
  { "_flagPoleWidth",		"0.025",                        false, StateDatabase::Locked},
  { "_flagPoleSize",		"0.8",				false, StateDatabase::Locked},
  { "_flagRadius",		"2.5",				false, StateDatabase::Locked},
  { "_friction",		"0",				false, StateDatabase::Locked},
  { "_gMissileAng",		"0.628319",			false, StateDatabase::Locked},
  { "_gMissileAdLife",		"0.95",				false, StateDatabase::Locked},
  { "_gravity",			"-9.8",				false, StateDatabase::Locked},
  { "_identifyRange",		"50.0",				false, StateDatabase::Locked},
  { "_jumpVelocity",		"19.0",				false, StateDatabase::Locked},
  { "_laserAdLife",		"0.1",				false, StateDatabase::Locked},
  { "_laserAdRate",		"0.5",				false, StateDatabase::Locked},
  { "_laserAdVel",		"1000.0",			false, StateDatabase::Locked},
  { "_lockOnAngle",		"0.15",				false, StateDatabase::Locked},
  { "_lRAdRate",		"0.5",				false, StateDatabase::Locked},
  { "_maxAngVel",		"_tankAngVel * _angularAd",	false, StateDatabase::Locked},
  { "_maxBumpHeight",		"0.33",				false, StateDatabase::Locked},
  { "_maxFlagGrabs",		"4.0",				false, StateDatabase::Locked},
  { "_maxLOD",			"32767.0",			false, StateDatabase::Locked},
  { "_maxVel",			"_tankSpeed * _agilityAdVel",	false, StateDatabase::Locked},
  { "_momentumAngAcc",		"1.0",				false, StateDatabase::Locked},
  { "_momentumLinAcc",		"1.0",				false, StateDatabase::Locked},
  { "_momentumFriction",	"0",				false, StateDatabase::Locked},
  { "_mGunAdLife",		"1.0 / _mGunAdRate",		false, StateDatabase::Locked},
  { "_mGunAdRate",		"10.0",				false, StateDatabase::Locked},
  { "_mGunAdVel",		"1.5",				false, StateDatabase::Locked},
  { "_muzzleFront",		"_tankRadius + 0.1",		false, StateDatabase::Locked},
  { "_muzzleHeight",		"1.57",				false, StateDatabase::Locked},
  { "_noSmallPackets",		"1",				false, StateDatabase::Locked},
  { "_notRespondingTime",	"5.0",				false, StateDatabase::Locked},
  { "_obeseFactor",		"2.5",				false, StateDatabase::Locked},
  { "_pauseDropTime",		"15.0",				false, StateDatabase::Locked},
  { "_positionTolerance",	"0.09",				false, StateDatabase::Locked},
  { "_pyrBase",			"4.0*_tankHeight",		false, StateDatabase::Locked},
  { "_pyrHeight",		"5.0*_tankHeight",		false, StateDatabase::Locked},
  { "_rejoinTime",		"_explodeTime",			false, StateDatabase::Locked},
  { "_reloadTime",		"_shotRange / _shotSpeed",	false, StateDatabase::Locked},
  { "_rFireAdLife",		"1.0 / _rFireAdRate",		false, StateDatabase::Locked},
  { "_rFireAdRate",		"2.0",				false, StateDatabase::Locked},
  { "_rFireAdVel",		"1.5",				false, StateDatabase::Locked},
  { "_shieldFlight",		"2.7",				false, StateDatabase::Locked},
  { "_shockAdLife",		"0.2",				false, StateDatabase::Locked},
  { "_shockInRadius",		"_tankLength",			false, StateDatabase::Locked},
  { "_shockOutRadius",		"60.0",				false, StateDatabase::Locked},
  { "_shotTailLength",		"4.0",				false, StateDatabase::Locked},
  { "_shotRadius",		"0.5",				false, StateDatabase::Locked},
  { "_shotRange",		"350.0",			false, StateDatabase::Locked},
  { "_shotSpeed",		"100.0",			false, StateDatabase::Locked},
  { "_shotsKeepVerticalVelocity",	"0",			false, StateDatabase::Locked},
  { "_srRadiusMult",		"2.0",				false, StateDatabase::Locked},
  { "_syncTime",		"0",				false, StateDatabase::Locked},
  { "_tankExplosionSize",	"3.5 * _tankLength", 		false, StateDatabase::Locked},
  { "_tankAngVel",		"0.785398", 			false, StateDatabase::Locked},
  { "_tankHeight",		"2.05",				false, StateDatabase::Locked},
  { "_tankLength",		"6.0",				false, StateDatabase::Locked},
  { "_tankRadius",		"0.72 * _tankLength",		false, StateDatabase::Locked},
  { "_tankSpeed",		"25.0",				false, StateDatabase::Locked},
  { "_tankWidth",		"2.8",				false, StateDatabase::Locked},
  { "_targetingAngle",		"0.3",				false, StateDatabase::Locked},
  { "_teleportBreadth",		"4.48",				false, StateDatabase::Locked},
  { "_teleportHeight",		"10.08",			false, StateDatabase::Locked},
  { "_teleportTime",		"1.0",				false, StateDatabase::Locked},
  { "_teleportWidth",		"1.12",				false, StateDatabase::Locked},
  { "_thiefAdLife",		"0.05",				false, StateDatabase::Locked},
  { "_thiefAdRate",		"12.0",				false, StateDatabase::Locked},
  { "_thiefAdShotVel",		"8.0",				false, StateDatabase::Locked},
  { "_thiefTinyFactor",		"0.5",				false, StateDatabase::Locked},
  { "_thiefVelAd",		"1.67",				false, StateDatabase::Locked},
  { "_thiefDropTime",		"_reloadTime * 0.5",		false, StateDatabase::Locked},
  { "_tinyFactor",		"0.4",				false, StateDatabase::Locked},
  { "_updateThrottleRate",	"30.0",				false, StateDatabase::Locked},
  { "_velocityAd",		"1.5",				false, StateDatabase::Locked},
  { "_wallHeight",		"3.0*_tankHeight",		false, StateDatabase::Locked},
  { "_wideAngleAng",		"1.745329", 			false, StateDatabase::Locked},
  { "_wingsGravity",		"_gravity",			false, StateDatabase::Locked},
  { "_wingsJumpCount",		"1",				false, StateDatabase::Locked},
  { "_wingsJumpVelocity",	"_jumpVelocity",		false, StateDatabase::Locked},
  { "_worldSize",		"800.0",			false, StateDatabase::Locked}
};
const unsigned int	numGlobalDBItems = countof(globalDBItems);

// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|>