summaryrefslogtreecommitdiffstats
path: root/src/bm/bmmisc.cpp
blob: 90d4062df014c33ef2bb79afe329b7137c1497d2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information (qt-info@nokia.com)
**
** This file is part of the BM project on Qt Labs.
**
** This file may be used under the terms of the GNU General Public
** License version 2.0 or 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of
** this file.  Please review the following information to ensure GNU
** General Public Licensing requirements will be met:
** http://www.fsf.org/licensing/licenses/info/GPLv2.html and
** http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
****************************************************************************/

#include "bmmisc.h"
#include <QFile>
#include <QSqlError>
#include <QSqlDriver>
#include <QVariant>
#include <QDebug>
#include <qnumeric.h>
#include <qmath.h>
#include <cstdio>

bool BMMisc::getTimestamp(
    const QStringList &args, int pos, QString *timestamp, QString *error)
{
    Q_ASSERT((0 <= pos) && (pos < args.size()));
    *timestamp = args.at(pos);
    if ((*timestamp != "first") && (*timestamp != "last")) {
        bool ok;
        const int val = timestamp->toInt(&ok);
        if (!ok || val < 0) {
            if (error)
                *error = "failed to extract timestamp as a non-negative integer";
            return false;
        }
    }
    return true;
}

void BMMisc::printJSONOutput(const QString &s)
{
    printf("Content-type: text/json\n\n%s\n", s.toLatin1().data());
}

void BMMisc::printHTMLOutput(const QString &s)
{
    printf("Content-type: text/html\n\n%s\n", s.toLatin1().data());
}

void BMMisc::printHTMLErrorPage(const QString &s)
{
    printHTMLOutput(
        QString("<br /><br /><html><body><strong>ERROR:</strong>&nbsp;&nbsp;%1</body></html>")
        .arg(s));
}

void BMMisc::printImageOutput(
    const QImage &image, const QString &format, const QString &error, bool httpHeader)
{
    if (image.isNull()) {
        if (httpHeader)
            printf("Content-type: text/html\n\n%s\n", error.toLatin1().data());
    } else {
        if (httpHeader)
            printf("Content-type: image/png\n\n");
        QFile out;
        out.open(stdout, QIODevice::WriteOnly);
        image.save(&out, format.toLatin1().data());
        out.close();
    }
}

bool BMMisc::getLastInsertId(QSqlQuery *query, int *id)
{
    // ### hm ... maybe return false and report an error instead of just asserting here?
    // Or even better: write the backup code (involving an extra query to get the new id)!
    if (!query->driver()->hasFeature(QSqlDriver::LastInsertId))
        return false;
    QVariant lastInsertId = query->lastInsertId();
    if (!lastInsertId.isValid())
        return false; // hm ... is this really possible?
    *id = lastInsertId.toInt();
    return true;
}

QString BMMisc::lastQueryError(const QSqlQuery &query)
{
    return query.lastError().text().trimmed().replace(QChar('"'), "&quot;");
}

// Computes the normalized difference between two real values.
qreal BMMisc::normalizedDifference(qreal a, qreal b)
{
    return (a == b) ? 0 : ((a - b) / (qMax(qAbs(a), qAbs(b))));
}

// ### 2 B DOCUMENTED!
QString BMMisc::getOption(const QStringList &args, const QString &name, int offset)
{
    int pos;
    Q_ASSERT(offset >= 0);
    if (((pos = args.indexOf(name)) == -1) || (pos >= (args.size() - (1 + offset))))
        return QString();
    return args.at(pos + 1 + offset);
}

// ### 2 B DOCUMENTED!
bool BMMisc::getOption(
    const QStringList &args, const QString &option, QStringList *values, int nvalues, int nskip,
    QString *error)
{
    int pos = -1;
    for (int i = 0; i <= nskip; ++i) {
        pos = args.indexOf(option, pos + 1);
        if (pos == -1)
            return false;
    }

    if (values)
        *values = QStringList();
    const int lastValuePos = pos + nvalues;
    if (lastValuePos >= args.size()) {
        if (error)
            *error = QString("too few values for %1 option").arg(option);
        return false;
    }
    if (values) {
        for (int i = pos + 1; i <= lastValuePos; ++i)
            values->append(args.at(i).trimmed());
    }

    return true;
}

// ### 2 B DOCUMENTED!
bool BMMisc::getMultiOption(
    const QStringList &args, const QString &option, QStringList *values, QString *error,
    bool unique)
{
    for (int i = 0; ; ++i) {
        QStringList values_;
        if (getOption(args, option, &values_, 1, i, error)) {
            if (!(unique && values->contains(values_.first())))
                values->append(values_.first());
        } else {
            if (!error->isEmpty())
                return false;
            break;
        }
    }
    return true;
}

// ### 2 B DOCUMENTED!
bool BMMisc::getMultiOption2(
    const QStringList &args, const QString &option, QList<QStringList> *values, int n,
    QString *error)
{
    for (int i = 0; ; ++i) {
        QStringList values_;
        if (getOption(args, option, &values_, n, i, error)) {
            Q_ASSERT(values_.size() == n);
            values->append(values_);
        } else {
            if (!error->isEmpty())
                return false;
            break;
        }
    }
    return true;
}

bool BMMisc::hasOption(const QStringList &args, const QString &option)
{
    QStringList dummyValues;
    return getOption(args, option, &dummyValues, 0, 0);
}

// Computes the median value of the numbers in \a values.
qreal BMMisc::median(const QList<qreal> &values)
{
    Q_ASSERT(!values.isEmpty());
    QList<qreal> sortedValues = values;
    qSort(sortedValues);
    return sortedValues.at(sortedValues.size() / 2);
}

// Computes the (zero-based) position of the median value of the numbers in \a values.
// If the median value occurs multiple times, the position of either the last or first
// duplicate is returned depending on whether \a lastDuplicate is true or false respectively.
int BMMisc::medianPos(const QList<qreal> &values, bool lastDuplicate)
{
    Q_ASSERT(!values.isEmpty());
    QList<qreal> sortedValues = values;
    qSort(sortedValues);
    const qreal medianValue = sortedValues.at(sortedValues.size() / 2);
    return lastDuplicate ? values.lastIndexOf(medianValue) : values.indexOf(medianValue);
}

qreal BMMisc::v2y(
    const qreal v, const qreal ymax, const qreal vmin, const qreal yfact, const qreal ydefault)
{
    const qreal y = ymax - (v - vmin) * yfact;
    return qIsFinite(y) ? y : ydefault;
}

QDateTime BMMisc::createCurrDateTime(int timestamp)
{
    if (timestamp < 0)
        return QDateTime::currentDateTime();
    QDateTime currDateTime;
    currDateTime.setTime_t(timestamp);
    return currDateTime;
}

QString BMMisc::secs2daysText(const int secs, const uint precision)
{
    const int secsInDay = 86400; // 24 * 60 * 60
    return QString().setNum(secs / (double)secsInDay, 'f', precision);
}

bool BMMisc::saveImageToFile(const QImage &image, const QString &fileName, QString *error)
{
    // Open output file ...
    QFile file(fileName);
    if (!file.open(QIODevice::WriteOnly)) {
        *error = QString("failed to open plot file '%1' for writing").arg(fileName);
        return false;
    }

    // Save image to output file ...
    image.save(&file, "png");
    file.close();

    return true;
}

// ### Warning: this function duplicates a JavaScript function!
QString BMMisc::ageColor(const int secs)
{
    const int minSecs = 0;
    const int maxSecs = 31536000; // secs in year
    const int minR = 255;
    const int minG = 128;
    const int minB = 0;
    const int maxR = 228;
    const int maxG = 228;
    const int maxB = 228;

    qreal frac = (qMax(qMin(secs, maxSecs), minSecs) - minSecs) / qreal(maxSecs - minSecs);

    int r = int(qRound((1 - frac) * minR + frac * maxR));
    r = qMax(qMin(r, 255), 0);
    int g = int(qRound((1 - frac) * minG + frac * maxG));
    g = qMax(qMin(g, 255), 0);
    int b = int(qRound((1 - frac) * minB + frac * maxB));
    b = qMax(qMin(b, 255), 0);

    QString color = QString("#%1%2%3")
        .arg(r, 2, 16, QChar('0'))
        .arg(g, 2, 16, QChar('0'))
        .arg(b, 2, 16, QChar('0'));
    return color;
}

// ### Warning: this function duplicates a JavaScript function!
QString BMMisc::redToGreenColor(
    qreal val, qreal minAbsVal, qreal maxAbsVal, bool higherIsBetter)
{
    if (!higherIsBetter)
        val = -val;

    int r = 255;
    int g = 255;
    int b = 255;
    const qreal frac = (qAbs(val) - minAbsVal) / (maxAbsVal - minAbsVal);
    if (val >= minAbsVal) {
        r = (val >= maxAbsVal) ? 0 : qRound((1 - frac) * 255);
        g = 255;
        b = r;
    } else if (val <= -minAbsVal) {
        r = 255;
        g = (val <= -maxAbsVal) ? 0 : qRound((1 - frac) * 255);
        b = g;
    }

    QString color = QString("#%1%2%3")
        .arg(r, 2, 16, QChar('0'))
        .arg(g, 2, 16, QChar('0'))
        .arg(b, 2, 16, QChar('0'));
    return color;
}

// ### Warning: this function duplicates a JavaScript function!
QString BMMisc::diffColor(qreal diff, bool higherIsBetter)
{
    return redToGreenColor(diff, 0.0001, 0.01, higherIsBetter);
}

bool BMMisc::lowerIsBetter(const QString &metric)
{
    if (metric == "FramesPerSecond") // ### More to be added ...
        return false;
    return true;
}

qreal BMMisc::log2val(qreal val, const QString &metric)
{
    Q_ASSERT(val > 0);
    const qreal v = qLn(val) / qLn(2);
    return lowerIsBetter(metric) ? -v : v;
}

qreal BMMisc::log2diff(qreal val1, qreal val2, const QString &metric)
{
    Q_ASSERT(val1 > 0);
    Q_ASSERT(val2 > 0);
    return (log2val(val1 / val2, metric));
}

bool BMMisc::normalize(QList<qreal> &v)
{
    qreal sum = 0.0;
    for (int i = 0; i < v.size(); ++i)
        sum += v.at(i);
    if (sum == 0.0)
        return false;
    for (int i = 0; i < v.size(); ++i) {
        v[i] /= sum;
        Q_ASSERT(qIsFinite(v.at(i)));
    }
    return true;
}

QString BMMisc::compactDateString(int timestamp)
{
    QDateTime dateTime;
    dateTime.setTime_t(timestamp);
    return dateTime.toString("dd MMM yyyy");
}