blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2 values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 905 values | visit_date timestamp[us]date 2015-08-09 11:21:18 2023-09-06 10:45:07 | revision_date timestamp[us]date 1997-09-14 05:04:47 2023-09-17 19:19:19 | committer_date timestamp[us]date 1997-09-14 05:04:47 2023-09-06 06:22:19 | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22 values | gha_event_created_at timestamp[us]date 2012-06-07 00:51:45 2023-09-14 21:58:39 ⌀ | gha_created_at timestamp[us]date 2008-03-27 23:40:48 2023-08-21 23:17:38 ⌀ | gha_language stringclasses 141 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 3 10.4M | extension stringclasses 115 values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2d06c97be4ea22ef6e1f3c2f05d373378ab637d8 | e5aa28feb4461043db39238a717436476f34ed72 | /src/qtimespan.cpp | 09c84a543bf721cd4e9e81fd221fe813d5dec0f5 | [] | no_license | siquel/SotkuMuija-sailfish | 45fe1b34b8759695f4b38608db6f60f3ab5afc0e | 74dade95f8679049e6eab31f5f629e1ad3f8ff5a | refs/heads/master | 2021-01-10T19:51:54.509534 | 2014-02-22T21:21:47 | 2014-02-22T21:21:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 76,295 | cpp | /****************************************************************************
**
** Copyright (C) 2011 Andre Somers, Sean Harmer.
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtCore module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qplatformdefs.h"
#include "qregexp.h"
#include "qdatastream.h"
#include "qlocale.h"
#include "qtimespan.h"
#include "qdebug.h"
#include "qcoreapplication.h"
#include "QtGlobal"
#if defined(Q_OS_WIN32) || defined(Q_OS_WINCE)
#include <qt_windows.h>
#endif
#ifndef Q_WS_WIN
#include <locale.h>
#endif
#include <time.h>
#if defined(Q_OS_WINCE)
#include "qfunctions_wince.h"
#endif
#if defined(Q_WS_MAC)
#include <private/qcore_mac_p.h>
#endif
#if defined(Q_OS_SYMBIAN)
#include <e32std.h>
#endif
#if defined(Q_WS_WIN)
#undef max
#endif
#include <limits>
#include <math.h>
/*!
\class QTimeSpan
\brief The QTimeSpan represents a span of time
\since 4.8
QTimeSpan represents a span of time, which is optionally in reference to a specific
point in time. A QTimeSpan behaves slightly different if it has a reference date or time
or not.
\section1 Constructing a QTimeSpan
A QTimeSpan can be created by initializing it directly with a length and optionally with
a reference (start) date, or by substracting two \l QDate or \l QDateTime values. By substracting
\l QDate or \l QDateTime values, you create a QTimeSpan with the \l QDate or \l QDateTime on the right
hand side of the - operator as the reference date.
\code
//Creates a QTimeSpan representing the time from October 10, 1975 to now
QDate birthDay(1975, 10, 10);
QTimeSpan age = QDate::currentDate() - birthDay;
\endcode
QTimeSpan defines a series of static methods that can be used for initializing a QTimeSpan.
\c second(), \c minute(), \c hour(), \c day() and \c week() all return QTimeSpan instances with the corresponding
length and no reference date. You can use those to create new instances. See the
section on \l {Date arithmetic} below.
\code
//Creates a QTimeSpan representing 2 days, 4 hours and 31 minutes.
QTimeSpan span(2 * QTimeSpan::day() + 4 * QTimeSpan::hour() + 31 * QTimeSpan::minute());
\endcode
Finally, a QTimeSpan can be constructed by using one of the static constructors
\l fromString() or \l fromTimeUnit().
\section1 Date arithmetic
A negative QTimeSpan means that the reference date lies before the referenced date. Call
\l normalize() to ensure that the reference date is smaller or equal than the referenced date.
Basic arithmetic can be done with QTimeSpan. QTimeSpans can be added up or substracted, or
be multiplied by a scalar factor. For this, the usual operators are implemented. The union
of QTimeSpans will yield the minimal QTimeSpan that covers both the original QTimeSpans,
while the intersection will yield the overlap between them (or an empty one if there is no
overlap). Please refer to the method documentation for details on what happens to a
reference date when using these methods.
QTimeSpans can also be added to or substracted from a \l QDate, \l QTime or \l QDateTime. This will yield
a new \l QDate, \l QTime or \l QDateTime moved by the interval described by the QTimeSpan. Note
that the QTimeSpan must be the right-hand argument of the operator. You can not add a \l QDate
to a QTimeSpan, but you can do the reverse.
\code
QTimeSpan span(QTimeSpan::hour() * 5 + 45 * QTimeSpan::hinute());
QDateTime t1 = QDateTime::currentDateTime();
QDateTime t2 = t1 + span; // t2 is now the date time 5 hours and 45 minutes in the future.
\endcode
\section1 Accessing the length of a QTimeSpan
There are two sets of methods that return the length of a QTimeSpan. The to* methods such
as \l toSeconds() and \l toMinutes() return the total time in the requested unit. That may be a
fractional number.
\code
QTimeSpan span = QTimeSpan::hour() * 6;
qreal days = span.toDays(); //yields 0.25
\endcode
On the other hand, you may be interested in a number of units at the same time. If you want
to know the number of days, hours and minutes in a QTimeSpan, you can use the to*Part
methods such as \l toDayPart() and \l toHourPart(). These functions take a \c QTimeSpan::TimeSpanFormat
argument to indicate the units you want to use for the presentation of the QTimeSpan.
This is used to calculate the number of the requested time units. You can also use the
parts method directly, passing pointers to ints for the units you are interested in and 0
for the other units.
\section1 Using months and years
It is natural to use units like months
and years when dealing with longer time periods, such as the age of people. The problem with
these units is that unlike the time units for a week or shorter, the length of a month or a
year is not fixed. It it dependent on the reference date. The time period '1 month' has a
different meaning when we are speaking of Februari or Januari. Qt does not take leap seconds
into account.
QTimeSpan can only use the month and year time units if a valid reference date has been
set. Without a valid reference date, month and year as time units are meaningless and their
use will result in an assert. The largest unit of time that can be expressed without a reference
date is a week. The time period of one month is understood to mean the period
from a day and time one month to the same date and time in the next. If the next month does
not have that date and time, one month will be taken to mean the period to the end of that
month.
\b Examples:
\list
\o The time from Januari 2, 12 PM to Februari 2, 12 PM will be understood as exactly one month.
\o The time from Januari 30, 2 PM to March 1, 00:00:00.000 will also be one month, because
Februari does not have 30 days but 28 or 29 depending on the year.
\o The time from Januari 30, 2 PM to March 30, 2 PM will be 2 months.
\endlist
The same goes for years.
\section1 Limitations and counterintuitive behaviour
QTimeSpan can be used to describe almost any length of time, ranging from milliseconds to
decades and beyond. QTimeSpan internally uses a 64 bit integer value to represent the interval;
enough for any application not dealing with geological or astronomical time scales.
The use of a single interval value also means that arithmetic with time periods set as months
or years may not always yield what you might expect. A time period set as the year describing
the whole of 2007 that you multiply by two, will not end up having a length of two years, but
of 1 year, 11 months and 30 days, as 2008 is one day longer than 2007. When months and years
are used, they are converted to the exact time span they describe relative to the reference
date set for the QTimeSpan. With another reference date, or when negated, that time span may
or may not describe the same number of years and months.
*/
QT_BEGIN_NAMESPACE
QTimeSpan QTimeSpan::second() {return QTimeSpan( Q_INT64_C(1000) );}
QTimeSpan QTimeSpan::minute() {return QTimeSpan( Q_INT64_C(1000) * Q_INT64_C(60) );}
QTimeSpan QTimeSpan::hour() {return QTimeSpan( Q_INT64_C(1000) * Q_INT64_C(60) * Q_INT64_C(60) );}
QTimeSpan QTimeSpan::day() {return QTimeSpan( Q_INT64_C(1000) * Q_INT64_C(60) * Q_INT64_C(60) * Q_INT64_C(24) );}
QTimeSpan QTimeSpan::week() {return QTimeSpan( Q_INT64_C(1000) * Q_INT64_C(60) * Q_INT64_C(60) * Q_INT64_C(24) * Q_INT64_C(7) );}
class QTimeSpanPrivate : public QSharedData {
public:
qint64 interval;
QDateTime reference;
void addUnit(QTimeSpan* self, Qt::TimeSpanUnit unit, qreal value)
{
if (unit >= Qt::Months) {
QTimeSpan tempSpan(self->referencedDate());
tempSpan.setFromTimeUnit(unit, value);
interval += tempSpan.toMSecs();
} else {
switch (unit) {
case Qt::Weeks:
interval += value * Q_INT64_C(1000) * Q_INT64_C(60) * Q_INT64_C(60) * Q_INT64_C(24) * Q_INT64_C(7);
break;
case Qt::Days:
interval += value * Q_INT64_C(1000) * Q_INT64_C(60) * Q_INT64_C(60) * Q_INT64_C(24);
break;
case Qt::Hours:
interval += value * Q_INT64_C(1000) * Q_INT64_C(60) * Q_INT64_C(60);
break;
case Qt::Minutes:
interval += value * Q_INT64_C(1000) * Q_INT64_C(60);
break;
case Qt::Seconds:
interval += value * Q_INT64_C(1000);
break;
case Qt::Milliseconds:
interval += value;
break;
default:
break;
}
}
}
//returns the number of days in the month of the indicated date. If lookback is true, and
//the date is exactly on the month boundary, the month before is used.
int daysInMonth (const QDateTime& date, bool lookBack = false) const {
QDateTime measureDate(date);
if (lookBack)
measureDate = measureDate.addMSecs(-1);
return measureDate.date().daysInMonth();
}
class TimePartHash: public QHash<Qt::TimeSpanUnit, int*>
{
public:
TimePartHash(Qt::TimeSpanFormat format)
{
for (int i(Qt::Milliseconds); i <= Qt::Years; i *= 2) {
Qt::TimeSpanUnit u = static_cast<Qt::TimeSpanUnit>(i);
if (format.testFlag(u)) {
int* newValue = new int;
*newValue = 0;
insert(u, newValue); //perhaps we can optimize this not to new each int individually?
} else {
insert(u, 0);
}
}
}
~TimePartHash()
{
qDeleteAll(*this);
}
inline bool fill(const QTimeSpan& span)
{
bool result = span.parts(value(Qt::Milliseconds),
value(Qt::Seconds),
value(Qt::Minutes),
value(Qt::Hours),
value(Qt::Days),
value(Qt::Weeks),
value(Qt::Months),
value(Qt::Years));
return result;
}
inline void addUnit(const Qt::TimeSpanUnit unit)
{
if (value(unit) != 0)
return;
int* newValue = new int;
*newValue = 0;
insert(unit, newValue);
}
};
//returns a string representation of time in a single time unit
QString unitString(Qt::TimeSpanUnit unit, int num) const
{
switch (unit) {
case::Qt::Milliseconds:
return qApp->translate("QTimeSpanPrivate", "%n millisecond(s)", "", num);
case::Qt::Seconds:
return qApp->translate("QTimeSpanPrivate", "%n second(s)", "", num);
case::Qt::Minutes:
return qApp->translate("QTimeSpanPrivate", "%n minute(s)", "", num);
case::Qt::Hours:
return qApp->translate("QTimeSpanPrivate", "%n hour(s)", "", num);
case::Qt::Days:
return qApp->translate("QTimeSpanPrivate", "%n day(s)", "", num);
case::Qt::Weeks:
return qApp->translate("QTimeSpanPrivate", "%n week(s)", "", num);
case::Qt::Months:
return qApp->translate("QTimeSpanPrivate", "%n month(s)", "", num);
case::Qt::Years:
return qApp->translate("QTimeSpanPrivate", "%n year(s)", "", num);
default:
return QString();
}
}
#ifndef QT_NO_DATESTRING
struct TimeFormatToken
{
Qt::TimeSpanUnit type; //Qt::NoUnit is used for string literal types
int length; //number of characters to use
QString string; //only used for string literals
};
QList<TimeFormatToken> parseFormatString(const QString& formatString, Qt::TimeSpanFormat &format) const
{
QHash<QChar, Qt::TimeSpanUnit> tokenHash;
tokenHash.insert(QChar('y', 0), Qt::Years);
tokenHash.insert(QChar('M', 0), Qt::Months);
tokenHash.insert(QChar('w', 0), Qt::Weeks);
tokenHash.insert(QChar('d', 0), Qt::Days);
tokenHash.insert(QChar('h', 0), Qt::Hours);
tokenHash.insert(QChar('m', 0), Qt::Minutes);
tokenHash.insert(QChar('s', 0), Qt::Seconds);
tokenHash.insert(QChar('z', 0), Qt::Milliseconds);
QList<TimeFormatToken> tokenList;
format = Qt::NoUnit;
int pos(0);
int length(formatString.length());
bool inLiteral(false);
while (pos < length) {
const QChar currentChar(formatString[pos]);
if (inLiteral) {
if (currentChar == QLatin1Char('\'')) {
inLiteral = false; //exit literal string mode
if ((pos+1)<length) {
if (formatString[pos+1] == QLatin1Char('\'')) {
++pos;
TimeFormatToken token = tokenList.last();
token.string.append(QChar('\'', 0));
token.length = token.string.length();
tokenList[tokenList.length()-1] = token;
inLiteral = true; //we *are* staying in literal string mode
}
}
} else {
TimeFormatToken token = tokenList.last();
token.string.append(currentChar);
token.length = token.string.length();
tokenList[tokenList.length()-1] = token;
}
} else { //not in literal string
if (currentChar == QLatin1Char('\'')) {
inLiteral = true; //enter literal string mode
TimeFormatToken token;
token.type = Qt::NoUnit;
token.length = 0;
tokenList << token;
} else {
if (tokenHash.contains(currentChar)) {
Qt::TimeSpanUnit unit = tokenHash.value(currentChar);
TimeFormatToken token;
token.length = 0;
token.type = unit;
if ((!tokenList.isEmpty()) && (tokenList.last().type == unit))
token = tokenList.takeLast();
token.length+=1;
tokenList.append(token);
format |= unit;
} else {
//ignore character?
TimeFormatToken token;
token.length = 0;
token.type = Qt::NoUnit;
if ((!tokenList.isEmpty()) && (tokenList.last().type == Qt::NoUnit))
token = tokenList.takeLast();
token.string.append(currentChar);
token.length= token.string.length();
tokenList.append(token);
}
}
}
++pos;
}
return tokenList;
}
#endif
};
/*!
Default constructor
Constructs a null QTimeSpan
*/
QTimeSpan::QTimeSpan()
: d(new QTimeSpanPrivate)
{
d->interval = 0;
}
/*!
Constructor
\overload QTimeSpan()
Constructs QTimeSpan of size \a msecs milliseconds. The reference date will
be invalid.
*/
QTimeSpan::QTimeSpan(qint64 msecs)
: d(new QTimeSpanPrivate)
{
d->interval = msecs;
}
/*!
Copy Constructor
*/
QTimeSpan::QTimeSpan(const QTimeSpan& other):
d(other.d)
{
}
/*!
Constructor
\overload QTimeSpan()
Constructs QTimeSpan of size \a msecs milliseconds from the given \a reference date
and time.
*/
QTimeSpan::QTimeSpan(const QDateTime &reference, qint64 msecs)
: d(new QTimeSpanPrivate)
{
d->interval = msecs;
d->reference = reference;
}
/*!
Constructor
\overload QTimeSpan()
Constructs QTimeSpan of size \a msecs milliseconds from the given \a reference date.
The reference time will be 0:00:00.000
*/
QTimeSpan::QTimeSpan(const QDate &reference, quint64 msecs)
: d(new QTimeSpanPrivate)
{
d->interval = msecs;
d->reference = QDateTime(reference);
}
/*!
Constructor
\overload QTimeSpan()
Constructs QTimeSpan of size \a msecs milliseconds from the given \a reference time.
The reference date will be today's date.
*/
QTimeSpan::QTimeSpan(const QTime &reference, quint64 msecs)
: d(new QTimeSpanPrivate)
{
d->interval = msecs;
QDateTime todayReference(QDate::currentDate());
todayReference.setTime(reference);
d->reference = todayReference;
}
/*!
Constructor
\overload QTimeSpan()
Constructs a QTimeSpan of the same length as \a other from the given \a reference date time.
*/
QTimeSpan::QTimeSpan(const QDateTime& reference, const QTimeSpan& other)
: d(new QTimeSpanPrivate)
{
d->reference = reference;
d->interval = other.d->interval;
}
/*!
Constructor
Constructs a QTimeSpan of the same length as \a other from the given \a reference date.
The reference time will be 00:00:00.000
*/
QTimeSpan::QTimeSpan(const QDate& reference, const QTimeSpan& other)
: d(new QTimeSpanPrivate)
{
d->reference = QDateTime(reference);
d->interval = other.d->interval;
}
/*!
Constructor
Constructs a QTimeSpan of the same length as \a other from the given \a reference time.
The reference date will be today's date.
*/
QTimeSpan::QTimeSpan(const QTime& reference, const QTimeSpan& other)
: d(new QTimeSpanPrivate)
{
QDateTime todayReference(QDate::currentDate());
todayReference.setTime(reference);
d->reference = todayReference;
d->interval = other.d->interval;
}
/*!
Destructor
*/
QTimeSpan::~QTimeSpan()
{
}
/*!
Returns true if the time span is 0; that is, if no time is spanned by
this instance. There may or may not be a valid reference date.
\sa isNull() hasValidReference()
*/
bool QTimeSpan::isEmpty() const
{
return d->interval == 0;
}
/*!
Returns true if the time span is 0; that is, if no time is spanned by
this instance and there is no valid reference date.
\sa isEmpty()
*/
bool QTimeSpan::isNull() const
{
return isEmpty() && (!hasValidReference());
}
/*!
Assignment operator
*/
QTimeSpan& QTimeSpan::operator=(const QTimeSpan& other) {
if (&other == this)
return *this;
d = other.d;
return *this;
}
/*!
Returns a new QTimeSpan instance initialized to \a interval number of
units \a unit. The default reference date is invalid.
Note that you can only construct a valid QTimeSpan using the Months or Years
time units if you supply a valid \a reference date.
\sa setFromTimeUnit()
*/
QTimeSpan QTimeSpan::fromTimeUnit(Qt::TimeSpanUnit unit, qreal interval, const QDateTime& reference )
{
switch (unit){ //note: fall through is intentional!
case Qt::Weeks:
interval *= 7.0;
case Qt::Days:
interval *= 24.0;
case Qt::Hours:
interval *= 60.0;
case Qt::Minutes:
interval *= 60.0;
case Qt::Seconds:
interval *= 1000.0;
case Qt::Milliseconds:
break;
default:
if (reference.isValid()) {
QTimeSpan result(reference);
result.setFromTimeUnit(unit, interval);
return result;
}
Q_ASSERT_X(false, "static constructor", "Can not construct QTimeSpan from Month or Year TimeSpanUnit without a valid reference date.");
return QTimeSpan();
}
return QTimeSpan(reference, qint64(interval));
}
/*!
Returns the number of the requested units indicated by \a unit when formatted
as \a format.
\sa parts()
*/
int QTimeSpan::part(Qt::TimeSpanUnit unit, Qt::TimeSpanFormat format) const
{
if (!format.testFlag(unit))
return 0;
if (!hasValidReference()) {
Q_ASSERT_X(!(unit == Qt::Months || unit == Qt::Years),
"part", "Can not calculate Month or Year part without a reference date");
if (format.testFlag(Qt::Months) || format.testFlag(Qt::Years)) {
qWarning() << "Unsetting Qt::Months and Qt::Years flags from format. Not supported without a reference date";
//should this assert instead?
format&= (Qt::AllUnits ^ (Qt::Months | Qt::Years));
}
}
//build up hash with pointers to ints for the units that are set in format, and 0's for those that are not.
QTimeSpanPrivate::TimePartHash partsHash(format);
bool result = partsHash.fill(*this);
if (!result) {
//what to do? Assert perhaps?
qWarning() << "Result is invalid!";
return 0;
}
int val = *(partsHash.value(unit));
return val;
}
#define CHECK_INT_LIMIT(interval, unitFactor) if (interval >= (qint64(unitFactor) * qint64(std::numeric_limits<int>::max()) ) ) {qWarning() << "out of range" << unitFactor; return false;}
/*!
Retreives a breakup of the length of the QTimeSpan in different time units.
While \l part() allows you to retreive the value of a single unit for a specific
representation of time, this method allows you to retreive all these values
with a single call. The units that you want to use in the representation of the
time span are defined implicitly by the pointers you pass. Passing a valid pointer
for a time unit will include that unit in the representation, while passing 0
for that pointer will exclude it.
The passed integer pointers will be set to the correct value so that together
they represent the whole time span. This function will then return true.
If it is impossible to represent the whole time span in the requested units,
this function returns false.
The \a fractionalSmallestUnit qreal pointer can optionally be passed in to
retreive the value for the smallest time unit passed in as a fractional number.
For instance, if your time span contains 4 minutes and 30 seconds, but the
smallest time unit you pass in an integer pointer for is the minute unit, then
the minute integer will be set to 4 and the \a fractionalSmallestUnit will be set
to 4.5.
A negative QTimeSpan will result in all the parts of the representation to be
negative, while a positive QTimeSpan will result in an all positive
representation.
Note that months and years are only valid as units for time spans that have a valid
reference date. Requesting the number of months or years for time spans without
a valid reference date will return false.
If this function returns false, the value of the passed in pointers is undefined.
\sa part()
*/
bool QTimeSpan::parts(int *msecondsPtr,
int *secondsPtr,
int *minutesPtr,
int *hoursPtr,
int *daysPtr,
int *weeksPtr,
int *monthsPtr,
int *yearsPtr,
qreal *fractionalSmallestUnit) const
{
/* \todo We should probably cache the results of this operation. However, that requires keeping a dirty flag
in the private data store, or a copy of the reference date, interval and last used parts. Is that worth it?
*/
// Has the user asked for a fractional component? If yes, find which unit it corresponds to.
Qt::TimeSpanUnit smallestUnit = Qt::NoUnit;
if (fractionalSmallestUnit) {
if (yearsPtr)
smallestUnit = Qt::Years;
if (monthsPtr)
smallestUnit = Qt::Months;
if (weeksPtr)
smallestUnit = Qt::Weeks;
if (daysPtr)
smallestUnit = Qt::Days;
if (hoursPtr)
smallestUnit = Qt::Hours;
if (minutesPtr)
smallestUnit = Qt::Minutes;
if (secondsPtr)
smallestUnit = Qt::Seconds;
if (msecondsPtr)
smallestUnit = Qt::Milliseconds;
}
QTimeSpan ts(*this);
qint64 unitFactor;
if (yearsPtr || monthsPtr) { //deal with months and years
//we can not deal with months or years if there is no valid reference date
if (!hasValidReference()) {
qWarning() << "Can not request month or year parts of a QTimeSpan without a valid reference date.";
return false;
}
QDate startDate = ts.startDate().date();
QDate endDate = ts.endDate().date();
//Deal with years
int years = endDate.year() - startDate.year();
if (endDate.month() < startDate.month()) {
years--;
} else if (endDate.month() == startDate.month()) {
if (endDate.day() < startDate.day())
years--;
}
if (yearsPtr)
*yearsPtr = years;
QDate newStartDate(startDate);
unitFactor = Q_INT64_C(365) * Q_INT64_C(24) * Q_INT64_C(60) * Q_INT64_C(60) * Q_INT64_C(1000);
newStartDate = newStartDate.addYears(years);
ts = QDateTime(endDate, ts.endDate().time()) - QDateTime(newStartDate, ts.startDate().time());
if (smallestUnit == Qt::Years) {
if (QDate::isLeapYear(newStartDate.year()))
unitFactor = Q_INT64_C(366) * Q_INT64_C(24) * Q_INT64_C(60) * Q_INT64_C(60) * Q_INT64_C(1000);
*fractionalSmallestUnit = static_cast<qreal>(years)
+ (static_cast<qreal>(ts.toMSecs()) / static_cast<qreal>(unitFactor));
return true;
}
//Deal with months
if (monthsPtr) {
int months = endDate.month() - startDate.month();
if (months < 0)
months += 12;
if (endDate.day() < startDate.day())
months--;
newStartDate = newStartDate.addMonths(months);
ts = QDateTime(endDate, ts.endDate().time()) - QDateTime(newStartDate, ts.startDate().time());
if (!yearsPtr)
months += years * 12;
*monthsPtr = months;
if (smallestUnit == Qt::Months) {
unitFactor = Q_INT64_C(24) * Q_INT64_C(60) * Q_INT64_C(60) * Q_INT64_C(1000); //one day
unitFactor *= d->daysInMonth(QDateTime(newStartDate), isNegative());
*fractionalSmallestUnit = static_cast<qreal>(months)
+ (static_cast<qreal>(ts.toMSecs()) / static_cast<qreal>(unitFactor));
return true;
}
}
}
//from here on, we use ts as the time span!
qint64 intervalLeft = ts.toMSecs();
if (weeksPtr) {
unitFactor = Q_INT64_C(7) * Q_INT64_C(24) * Q_INT64_C(60) * Q_INT64_C(60) * Q_INT64_C(1000);
CHECK_INT_LIMIT(intervalLeft, unitFactor)
*weeksPtr = intervalLeft / unitFactor;
if (smallestUnit == Qt::Weeks) {
QTimeSpan leftOverTime(referencedDate(), -intervalLeft);
leftOverTime.normalize();
*fractionalSmallestUnit = leftOverTime.toTimeUnit(smallestUnit);
return true;
}
if (*weeksPtr != 0)
intervalLeft = intervalLeft % unitFactor;
}
if (daysPtr) {
unitFactor = (Q_INT64_C(24) * Q_INT64_C(60) * Q_INT64_C(60) * Q_INT64_C(1000));
CHECK_INT_LIMIT(intervalLeft, unitFactor)
*daysPtr = intervalLeft / unitFactor;
if (smallestUnit == Qt::Days) {
QTimeSpan leftOverTime(referencedDate(), -intervalLeft);
leftOverTime.normalize();
*fractionalSmallestUnit = leftOverTime.toTimeUnit(smallestUnit);
return true;
}
if (*daysPtr != 0 )
intervalLeft = intervalLeft % unitFactor;
}
if (hoursPtr) {
unitFactor = (Q_INT64_C(60) * Q_INT64_C(60) * Q_INT64_C(1000));
CHECK_INT_LIMIT(intervalLeft, unitFactor)
*hoursPtr = intervalLeft / unitFactor;
if (smallestUnit == Qt::Hours) {
QTimeSpan leftOverTime(referencedDate(), -intervalLeft);
leftOverTime.normalize();
*fractionalSmallestUnit = leftOverTime.toTimeUnit(smallestUnit);
return true;
}
if (*hoursPtr != 0 )
intervalLeft = intervalLeft % unitFactor;
}
if (minutesPtr) {
unitFactor = (Q_INT64_C(60) * Q_INT64_C(1000));
CHECK_INT_LIMIT(intervalLeft, unitFactor)
*minutesPtr = intervalLeft / unitFactor;
if (smallestUnit == Qt::Minutes) {
QTimeSpan leftOverTime(referencedDate(), -intervalLeft);
leftOverTime.normalize();
*fractionalSmallestUnit = leftOverTime.toTimeUnit(smallestUnit);
return true;
}
if (*minutesPtr != 0 )
intervalLeft = intervalLeft % unitFactor;
}
if (secondsPtr) {
unitFactor = (Q_INT64_C(1000));
CHECK_INT_LIMIT(intervalLeft, unitFactor)
*secondsPtr = intervalLeft / unitFactor;
if (smallestUnit == Qt::Seconds) {
QTimeSpan leftOverTime(referencedDate(), -intervalLeft);
leftOverTime.normalize();
*fractionalSmallestUnit = leftOverTime.toTimeUnit(smallestUnit);
return true;
}
if (*secondsPtr > 0 )
intervalLeft = intervalLeft % unitFactor;
}
if (msecondsPtr) {
unitFactor = 1;
CHECK_INT_LIMIT(intervalLeft, unitFactor)
*msecondsPtr = intervalLeft;
if (fractionalSmallestUnit) {
*fractionalSmallestUnit = qreal(intervalLeft);
}
}
return true;
}
/*!
Sets a part of the time span in the given format.
setPart allows you to adapt the current time span interval unit-by-unit based on
any time format. Where \l setFromTimeUnit resets the complete time interval, setPart
only sets a specific part in a chosen format.
\b Example:
If you have a time span representing 3 weeks, 2 days, 4 hours, 31 minutes
and 12 seconds, you can change the number of hours to 2 by just calling
\code
span.setPart(Qt::Hours, 2, Qt::Weeks | Qt::Days | Qt::Hours | Qt::Minutes | Qt::Seconds);
\endcode
Note that just like with any other function, you can not use the Months and Years
units without using a reference date.
*/
void QTimeSpan::setPart(Qt::TimeSpanUnit unit, int interval, Qt::TimeSpanFormat format)
{
if (!format.testFlag(unit)) {
qWarning() << "Can not set a unit that is not part of the format. Ignoring.";
return;
}
QTimeSpanPrivate::TimePartHash partsHash(format);
bool result = partsHash.fill(*this);
if (!result) {
qWarning() << "Retreiving parts failed, cannot set parts. Ignoring.";
return;
}
d->addUnit(this, unit, interval - *(partsHash.value(unit) ) );
}
/*!
Returns \c Qt::TimeSpanUnit representing the order of magnitude of the time span.
That is, the largest unit that can be used to display the time span that
will result in a non-zero value.
If the QTimeSpan does not have a valid reference date, the largest
possible time unit that will be returned is Qt::Weeks. Otherwise,
the largest possible time unit is Qt::Years.
*/
Qt::TimeSpanUnit QTimeSpan::magnitude()
{
qint64 mag = d->interval;
mag = qAbs(mag);
if (mag < 1000)
return Qt::Milliseconds;
if (mag < (Q_INT64_C(60) * Q_INT64_C(1000)))
return Qt::Seconds;
if (mag < (Q_INT64_C(60) * Q_INT64_C(60) * Q_INT64_C(1000)))
return Qt::Minutes;
if (mag < (Q_INT64_C(24) * Q_INT64_C(60) * Q_INT64_C(60) * Q_INT64_C(1000)))
return Qt::Hours;
if (mag < (Q_INT64_C(7) * Q_INT64_C(24) * Q_INT64_C(60) * Q_INT64_C(60) * Q_INT64_C(1000)))
return Qt::Days;
//those the simple cases. The rest is dependent on if there is a reference date
if (hasValidReference()) {
//simple test. If bigger than 366 (not 365!) then we are certain of dealing with years
if (mag > (Q_INT64_C(366) * Q_INT64_C(24) * Q_INT64_C(60) * Q_INT64_C(60) * Q_INT64_C(1000)))
return Qt::Years;
//we need a more complicated test
int years = 0;
int months = 0;
parts(0, 0, 0, 0, 0, 0, &months, &years);
if (years > 0)
return Qt::Years;
if (months > 0)
return Qt::Months;
}
return Qt::Weeks;
}
/*!
Returns \c true if there is a valid reference date set, false otherwise.
*/
bool QTimeSpan::hasValidReference() const
{
return d->reference.isValid();
}
/*!
Returns the reference date. Note that the reference date may be invalid.
*/
QDateTime QTimeSpan::referenceDate() const
{
return d->reference;
}
/*!
Sets the reference date.
If there currently is a reference date, the referenced date will
not be affected. That means that the length of the time span will
change. If there currently is no reference date set, the interval
will not be affected and this function will have the same
effect as \l moveReferenceDate().
\sa moveReferenceDate() setReferencedDate() moveReferencedDate()
*/
void QTimeSpan::setReferenceDate(const QDateTime &referenceDate)
{
if (d->reference.isValid() && referenceDate.isValid()) {
*this = referencedDate() - referenceDate;
} else {
d->reference = referenceDate;
}
}
/*!
Moves the time span to align the time spans reference date with the
new reference date \a referenceDate.
Note that the length of the time span will not be modified, so the
referenced date will shift as well. If no reference date was set
before, it is set now and the referenced date will become valid.
\sa setReferenceDate() setReferencedDate() moveReferencedDate()
*/
void QTimeSpan::moveReferenceDate(const QDateTime &referenceDate)
{
d->reference = referenceDate;
}
/*!
Sets the referenced date.
If there currently is a reference date, that reference date will
not be affected. This implies that the length of the time span changes.
If there currently is no reference date set, the interval
will not be affected and this function will have the same
effect as \l moveReferencedDate().
\sa setReferenceDate() moveReferenceDate() moveReferencedDate()
*/
void QTimeSpan::setReferencedDate(const QDateTime &referencedDate)
{
if (d->reference.isValid()) {
*this = referencedDate - d->reference;
} else {
d->reference = referencedDate.addMSecs(-(d->interval));
}
}
/*!
Moves the time span to align the time spans referenced date with the
new referenced date.
Note that the length of the time span will not be modified, so the
reference date will shift as well. If no reference date was set
before, it is set now.
\sa setReferenceDate() setReferencedDate() moveReferencedDate()
*/
void QTimeSpan::moveReferencedDate(const QDateTime &referencedDate)
{
d->reference = referencedDate.addMSecs(-(d->interval));
}
/*!
Returns the referenced date and time.
The referenced QDateTime is the "other end" of the QTimeSpan from
the reference date.
An invalid QDateTime will be returned if no valid reference date
has been set.
*/
QDateTime QTimeSpan::referencedDate() const
{
if (!(d->reference.isValid()))
return QDateTime();
QDateTime dt(d->reference);
dt = dt.addMSecs(d->interval);
return dt;
}
// Comparison operators
/*!
Returns true if this QTimeSpan and \a other have both the same
reference date and the same length.
Note that two QTimeSpan objects that span the same period, but
where one is positive and the other is negative are \b not considdered
equal. If you need to compare those, compare the normalized
versions.
\sa matchesLength()
*/
bool QTimeSpan::operator==(const QTimeSpan &other) const
{
return ((d->interval == other.d->interval)
&& (d->reference == other.d->reference));
}
/*!
Returns true if the interval of this QTimeSpan is shorter than
the interval of the \a other QTimeSpan.
*/
bool QTimeSpan::operator<(const QTimeSpan &other) const
{
return d->interval < other.d->interval;
}
/*!
Returns true if the interval of this QTimeSpan is shorter or equal
than the interval of the \a other QTimeSpan.
*/
bool QTimeSpan::operator<=(const QTimeSpan &other) const
{
return d->interval <= other.d->interval;
}
/*!
Returns true if the interval of this QTimeSpan is equal
to the interval of the \a other QTimeSpan. That is, if they have the
same length.
The default value of \a normalize is false. If normalize is true, the
absolute values of the interval lengths are compared instead of the
real values.
\code
QTimeSpan s1 = 2 * QTimeSpan::day();
QTimeSpan s2 = -2 * QTimeSpan::day();
qDebug() << s1.matchesLength(s2); //returns false
qDebug() << s1.matchesLength(s2, true); //returns true
\endcode
*/
bool QTimeSpan::matchesLength(const QTimeSpan &other, bool normalize) const
{
if (!normalize) {
return d->interval == other.d->interval;
} else {
return qAbs(d->interval) == qAbs(other.d->interval);
}
}
// Arithmetic operators
/*!
Adds the interval of the \a other QTimeSpan to the interval of
this QTimeSpan. The reference date of the \a other QTimeSpan is
ignored.
*/
QTimeSpan & QTimeSpan::operator+=(const QTimeSpan &other)
{
d->interval += other.d->interval;
return *this;
}
/*!
Adds the number of milliseconds \a msecs to the interval of
this QTimeSpan. The reference date of the QTimeSpan is
not affected.
*/
QTimeSpan & QTimeSpan::operator+=(qint64 msecs)
{
d->interval += msecs;
return *this;
}
/*!
Substracts the interval of the \a other QTimeSpan from the interval of
this QTimeSpan. The reference date of the \a other QTimeSpan is
ignored while the reference date of this QTimeSpan is not affected.
*/
QTimeSpan & QTimeSpan::operator-=(const QTimeSpan &other)
{
d->interval -= (other.d->interval);
return *this;
}
/*!
Substracts the number of milliseconds \a msecs from the interval of
this QTimeSpan. The reference date of the QTimeSpan is
not affected.
*/
QTimeSpan & QTimeSpan::operator-=(qint64 msecs)
{
d->interval -= msecs;
return *this;
}
/*!
Multiplies the interval described by this QTimeSpan by the
given \a factor. The reference date of the QTimeSpan is not
affected.
*/
QTimeSpan & QTimeSpan::operator*=(qreal factor)
{
d->interval *= factor;
return *this;
}
/*!
Multiplies the interval described by this QTimeSpan by the
given \a factor. The reference date of the QTimeSpan is not
affected.
*/
QTimeSpan & QTimeSpan::operator*=(int factor)
{
d->interval *= factor;
return *this;
}
/*!
Divides the interval described by this QTimeSpan by the
given \a factor. The reference date of the QTimeSpan is not
affected.
*/
QTimeSpan & QTimeSpan::operator/=(qreal factor)
{
d->interval /= factor;
return *this;
}
/*!
Divides the interval described by this QTimeSpan by the
given \a factor. The reference date of the QTimeSpan is not
affected.
*/
QTimeSpan & QTimeSpan::operator/=(int factor)
{
d->interval /= factor;
return *this;
}
/*!
Modifies this QTimeSpan to be the union of this QTimeSpan with \a other.
The union of two QTimeSpans is defined as the minimum QTimeSpan that
encloses both QTimeSpans. The QTimeSpans need not be overlapping.
\warning Only works if both QTimeSpans have a valid reference date.
\sa operator&=()
\sa operator|()
\sa united()
*/
QTimeSpan& QTimeSpan::operator|=(const QTimeSpan& other) // Union
{
Q_ASSERT_X((hasValidReference() && other.hasValidReference()),
"assignment-or operator", "Both participating time spans need a valid reference date");
//do we need to check for self-assignment?
QDateTime start = qMin(startDate(), other.startDate());
QDateTime end = qMax(endDate(), other.endDate());
*this = end - start;
return *this;
}
/*!
Modifies this QTimeSpan to be the intersection of this QTimeSpan and \a other.
The intersection of two QTimeSpans is defined as the maximum QTimeSpan that
both QTimeSpans have in common. If the QTimeSpans don't overlap, a null QTimeSpan
will be returned. The returned QTimeSpan will be positive.
\warning Only works if both QTimeSpans have a valid reference date.
\sa operator&=()
\sa operator&()
\sa overlapped()
*/
QTimeSpan& QTimeSpan::operator&=(const QTimeSpan &other) // Intersection
{
Q_ASSERT_X((hasValidReference() && other.hasValidReference()),
"assignment-or operator", "Both participating time spans need a valid reference date");
//do we need to check for self-assignment?
const QTimeSpan* first = this;
const QTimeSpan* last = &other;
if (other.startDate() < startDate()) {
first = &other;
last = this;
}
//check if there is overlap at all. If not, reset the interval to 0
if (!(first->endDate() > last->startDate()) ) {
d->interval = 0;
return *this;
}
*this = qMin(first->endDate(), last->endDate()) - last->startDate();
return *this;
}
/*!
Returns true if this QTimeSpan overlaps with the \a other QTimeSpan.
If one or both of the QTimeSpans do not have a valid reference date, this
function returns false.
*/
bool QTimeSpan::overlaps(const QTimeSpan &other) const
{
if (!hasValidReference() || !other.hasValidReference())
return false;
const QTimeSpan* first = this;
const QTimeSpan* last = &other;
if (other.startDate() < startDate()) {
first = &other;
last = this;
}
return (first->endDate() > last->startDate());
}
/*!
Returns a new QTimeSpan that represents the intersection of this QTimeSpan with \a other.
The intersection of two QTimeSpans is defined as the maximum QTimeSpan that
both QTimeSpans have in common. If the QTimeSpans don't overlap, a null QTimeSpan
will be returned. Any valid returned QTimeSpan will be positive.
\warning Only works if both QTimeSpans have a valid reference date.
\sa operator&=()
\sa operator&()
*/
QTimeSpan QTimeSpan::overlapped(const QTimeSpan &other) const
{
Q_ASSERT_X((hasValidReference() && other.hasValidReference()),
"assignment-or operator", "Both participating time spans need a valid reference date");
const QTimeSpan* first = this;
const QTimeSpan* last = &other;
if (other.startDate() < startDate()) {
first = &other;
last = this;
}
//check if there is overlap at all. If not, reset the interval to 0
if (!(first->endDate() >= last->startDate()) ) {
return QTimeSpan();
}
return qMin(first->endDate(), last->endDate()) - last->startDate();
}
/*!
Returns a new QTimeSpan that represents the union of this QTimeSpan with \a other.
The union of two QTimeSpans is defined as the minimum QTimeSpan that
encloses both QTimeSpans. The QTimeSpans need not be overlapping.
\warning Only works if both QTimeSpans have a valid reference date.
\sa operator|=()
\sa operator|()
*/
QTimeSpan QTimeSpan::united(const QTimeSpan &other) const
{
Q_ASSERT_X((hasValidReference() && other.hasValidReference()),
"assignment-or operator", "Both participating time spans need a valid reference date");
QDateTime start = qMin(startDate(), other.startDate());
QDateTime end = qMax(endDate(), other.endDate());
return ( end - start );
}
/*!
Determines if the given \a dateTime lies within the time span. The begin
and end times are taken to be contained in the time span in this function.
If the time span does not have a valid reference date, this function
returns false.
*/
bool QTimeSpan::contains(const QDateTime &dateTime) const
{
if (!hasValidReference())
return false;
return ((startDate() <= dateTime)
&& (endDate()) >= dateTime);
}
/*!
Determines if the given date lies within the time span. The begin
and end times are taken to be contained in the time span in this function.
Just like in the QTimeSpan constructors that take a QDate, the time will assumed
to be 00:00:00.000.
If the time span does not have a valid reference date, this function
returns false.
*/
bool QTimeSpan::contains(const QDate &date) const
{
QDateTime dt(date);
return contains(dt);
}
/*!
Determines if the given \a time lies within this QTimeSpan. The begin
and end times are taken to be contained in the time span in this function.
Just like in the QTimeSpan constructors that take a QTime, the date
will be set to today.
If the time span does not have a valid reference date, this function
returns false.
*/
bool QTimeSpan::contains(const QTime &time) const
{
QDateTime dt(QDate::currentDate());
dt.setTime(time);
return contains(dt);
}
/*!
Determines if the \a other QTimeSpan lies within this time span. Another
time span is contained if its start time is the same or later then the
start time of this time span, and its end time is the same or earlier
than the end time of this time span.
If either time span does not have a valid reference date, this function
returns false.
*/
bool QTimeSpan::contains(const QTimeSpan &other) const
{
if (!(hasValidReference() && other.hasValidReference()))
return false;
return ((startDate() <= other.startDate())
&& (endDate()) >= other.endDate());
}
/*!
Returns a new QTimeSpan representing the same time span as this QTimeSpan, but
that is guaranteed to be positive; that is, to have the reference date before or
equal to the referenced date.
\sa normalize()
\sa abs()
*/
QTimeSpan QTimeSpan::normalized() const
{
QTimeSpan ts(*this);
ts.normalize();
return ts;
}
/*!
Modifies this QTimeSpan to represent the same time span, but
that is guaranteed to be positive; that is, to have the reference date before or
equal to the referenced date. If there is no valid reference date, the interval
will just be made positive.
\sa normalized()
\sa abs()
*/
void QTimeSpan::normalize()
{
if (d->interval < 0) {
if (hasValidReference())
d->reference = referencedDate();
d->interval = qAbs(d->interval);
}
}
/*!
Returns a copy of this QTimeSpan that is guaranteed to be positive; that is,
to have the reference date before or equal to the referenced date. The reference
date is not modified. That implies that if there is a reference date, and the
QTimeSpan is negative, the returned QTimeSpan will describe the time span \i after
the reference date instead of the time span \i before.
If there is no valid reference date, the interval will just be made positive.
\sa normalize()
\sa normalized()
*/
QTimeSpan QTimeSpan::abs() const
{
QTimeSpan result(*this);
result.d->interval = qAbs(result.d->interval);
return result;
}
/*!
Returns true if the interval is negative.
\sa isNormal()
*/
bool QTimeSpan::isNegative() const
{
return d->interval < 0;
}
/*!
\fn QTimeSpan::isNormal() const
Returns true if the interval is normal, that is: not negative.
\sa isNegative()
*/
/*!
Returns the first date of the spanned time period. If there is no valid
reference date, an invalid QDateTime will be returned.
*/
QDateTime QTimeSpan::startDate() const
{
if (isNegative())
return referencedDate();
return referenceDate();
}
/*!
Returns the last date of the spanned time period. If there is no valid
reference date, an invalid QDateTime will be returned.
*/
QDateTime QTimeSpan::endDate() const
{
if (isNegative())
return referenceDate();
return referencedDate();
}
/*!
Returns the duration of the QTimeSpan expressed in milliseconds. This
value may be negative.
*/
qint64 QTimeSpan::toMSecs() const
{
return d->interval;
}
/*!
Returns the duration of the QTimeSpan expressed in the given TimeSpanUnit. This
value may be negative.
*/
qreal QTimeSpan::toTimeUnit(Qt::TimeSpanUnit unit) const
{
qreal interval = qreal(d->interval);
switch (unit){ //fall through is intentional
case Qt::Weeks:
interval /= 7.0;
case Qt::Days:
interval /= 24.0;
case Qt::Hours:
interval /= 60.0;
case Qt::Minutes:
interval /= 60.0;
case Qt::Seconds:
interval /= 1000.0;
case Qt::Milliseconds:
break;
default:
Q_ASSERT_X(hasValidReference(), "toTimeUnit", "Can not convert to time units that depend on the reference date (month and year).");
qreal result(0.0);
int intResult(0);
bool succes(false);
if (unit == Qt::Months) {
succes = parts(0, 0, 0, 0, 0, 0, &intResult, 0, &result);
} else if (unit == Qt::Years) {
succes = parts(0, 0, 0, 0, 0, 0, 0, &intResult, &result);
}
if (!succes)
return 0.0;
return result;
}
return interval;
}
/*!
Sets the length of this QTimeSpan from the given number of milliseconds \msecs.
The reference date is not affected.
*/
void QTimeSpan::setFromMSecs(qint64 msecs)
{
d->interval = msecs;
}
/*!
Sets the length of this QTimeSpan from the \a interval number of TimeSpanUnits \a unit.
The reference date is not affected.
*/
void QTimeSpan::setFromTimeUnit(Qt::TimeSpanUnit unit, qreal interval)
{
switch (unit){
case Qt::Weeks: //fall through of cases is intentional!
interval *= 7.0;
case Qt::Days:
interval *= 24.0;
case Qt::Hours:
interval *= 60.0;
case Qt::Minutes:
interval *= 60.0;
case Qt::Seconds:
interval *= 1000.0;
case Qt::Milliseconds:
break;
case Qt::Months:
setFromMonths(interval);
return;
case Qt::Years:
setFromYears(interval);
return;
default:
Q_ASSERT_X(false, "setFromTimeUnit", "Can not set a QTimeSpan duration from unknown TimeSpanUnit.");
}
d->interval = qint64(interval);
}
/*!
Sets the interval of the time span as a number of \a months.
\warning This function can only be used if a valid reference date has been set.
The setFromMonths method deals with fractional months in the following way: first,
the whole number of months is extracted and added to the reference date. The fractional
part of the number of months is then multiplied with the number of days in the month
in which that date falls. If the number of months is negative and adding a whole month
yields a date exactly on a month boundary, the number of days in the month before is
used instead.
That number is used as the number of days and is added to the interval.
\code
QTimeSpan ts(QDate(2010,01,01));
ts.setFromMonths(1.5); // ts's referenced date is now Februari 15, 0:00:00
ts.setFromMonths(2.5); // ts's referenced date is now March 16, 12:00:00
QTimeSpan ts2(QDate(2008,01,01)); //2008 is a leap year
ts2.setFromMonths(1.5); // ts2's referenced date is now Februari 15, 12:00:00
QTimeSpan ts3(QDate(2008,03,01)); //2008 is a leap year
ts3.setFromMonths(-0.5); // ts3's referenced date is now Februari 15: 12:00:00 //
\endcode
*/
void QTimeSpan::setFromMonths(qreal months)
{
Q_ASSERT_X(hasValidReference(), "setFromMonths", "Can not set interval from time unit month if there is no reference date.");
int fullMonths = int(months);
qreal fractionalMonth = months - fullMonths;
QDateTime endDate = d->reference;
endDate = endDate.addMonths(fullMonths);
int days = d->daysInMonth(endDate, fractionalMonth < 0);
QTimeSpan tmp = endDate - d->reference;
qreal fractionalDays = fractionalMonth * days;
d->interval = tmp.toMSecs() + qint64(fractionalDays * 24.0 * 60.0 * 60.0 * 1000.0);
}
/*!
Sets the interval of the time span as a number of \a years.
\warning This function can only be used if a valid reference date has been set.
The setFromYears method deals with fractional years in the following way: first,
the whole number of years is extracted and added to the reference date. The fractional
part of the number of years is then multiplied with the number of days in the year
in which that date falls. That number is used as the number of days and is added to the
interval.
If the number of years is negative and adding the whole years yields a date exactly on
a year boundary, the number of days in the year before is used instead.
*/
void QTimeSpan::setFromYears(qreal years)
{
Q_ASSERT_X(hasValidReference(), "setFromYears", "Can not set interval from time unit year if there is no reference date.");
int fullYears = int(years);
qreal fractionalYear = years - fullYears;
QDateTime endDate = d->reference;
endDate = endDate.addYears(fullYears);
qreal days = 365.0;
QDateTime measureDate(endDate);
if (fractionalYear < 0)
measureDate = measureDate.addMSecs(-1);
if (QDate::isLeapYear(measureDate.date().year()))
days += 1.0; //februari has an extra day this year...
QTimeSpan tmp = endDate - d->reference;
qreal fractionalDays = fractionalYear * days;
d->interval = tmp.toMSecs() + qint64(fractionalDays * 24.0 * 60.0 * 60.0 * 1000.0);
}
#ifndef QT_NO_DATASTREAM
/*!
Streaming operator.
This operator allows you to stream a QTimeSpan into a QDataStream.
\sa operator>>(QDataStream &stream, QTimeSpan &span)
*/
QDataStream & operator<<(QDataStream &stream, const QTimeSpan & span)
{
stream << span.d->reference << span.d->interval;
return stream;
}
/*!
Streaming operator.
This operator allows you to stream a QTimeSpan out of a QDataStream.
\sa operator>>(QDataStream &stream, QTimeSpan &span)
*/
QDataStream & operator>>(QDataStream &stream, QTimeSpan &span)
{
stream >> span.d->reference >> span.d->interval;
return stream;
}
#endif
/*!
Adds two QTimeSpan instances.
The values of the intervals of the QTimeSpans are added up with normal
arithmetic. Negative values will work as expected.
If the \a left argument has a reference date, that reference will be used.
If only the \a right argument has a reference date, then that reference
date will be used as the new reference date.
The above can have suprising consequences:
\code
// s1 and s2 are two QTimeSpan objects
QTimeSpan s12 = s1 + s2;
QTimeSpan s21 = s2 + s1;
if (s12 == s21) {
//may or may not happen, depending on the reference dates of s1 and s2.
}
\endcode
\sa operator-()
*/
QTimeSpan operator+(const QTimeSpan &left, const QTimeSpan &right)
{
QTimeSpan result(left);
result += right;
// only keep the right reference date if the left argument does not have one
if (!left.hasValidReference() && right.hasValidReference())
result.setReferenceDate(right.referenceDate());
return result;
}
/*!
Substracts one QTimeSpan from another QTimeSpan.
The value of the interval of the \a right QTimeSpan is substracted from the
\a left QTimeSpan with normal arithmetic. Negative values will work as expected.
If the \a left argument has a reference date, that reference will be kept.
If only the \a right argument has a reference date, then that reference
date will be used as the new reference date.
\sa operator+()
*/
QTimeSpan operator-(const QTimeSpan &left, const QTimeSpan &right)
{
QTimeSpan result(left);
result -= right;
// only keep the right reference date if the left argument does not have one
if (!left.hasValidReference() && right.hasValidReference())
result.setReferenceDate(right.referenceDate());
return result;
}
/*!
Multiply a QTimeSpan by a scalar factor.
Returns a new QTimeSpan object that has the same reference date as the
\a left QTimeSpan, but with an interval length that is multiplied by the
\a right argument.
*/
QTimeSpan operator*(const QTimeSpan &left, qreal right)
{
QTimeSpan result(left);
result*=right;
return result;
}
/*!
Multiply a QTimeSpan by a scalar factor.
\overload
*/
QTimeSpan operator*(const QTimeSpan &left, int right)
{
QTimeSpan result(left);
result*=right;
return result;
}
/*!
Divide a QTimeSpan by a scalar factor.
Returns a new QTimeSpan object that has the same reference date as the
\a left QTimeSpan, but with an interval length that is devided by the
\a right argument.
*/
QTimeSpan operator/(const QTimeSpan &left, qreal right)
{
QTimeSpan result(left);
result/=right;
return result;
}
/*!
Divide a QTimeSpan by a scalar factor.
\overload
*/
QTimeSpan operator/(const QTimeSpan &left, int right)
{
QTimeSpan result(left);
result/=right;
return result;
}
/*!
Devides two QTimeSpans. The devision works on the interval lengths of
the two QTimeSpan objects as you would expect from normal artithmatic.
*/
qreal operator/(const QTimeSpan &left, const QTimeSpan &right)
{
return (qreal(left.toMSecs()) / qreal(right.toMSecs()));
}
/*!
Returns a QTimeSpan object with the same reference date as the \a right
hand argument, but with a negated interval. Note that unlike with the
\l normalize() method, this function will result in a QTimeSpan that
describes a different period if the QTimeSpan has a reference date because
the reference date is not modified.
\sa normalize()
*/
QTimeSpan operator-(const QTimeSpan &right) // Unary negation
{
QTimeSpan result(right);
result.setFromMSecs(-result.toMSecs());
return result;
}
/*!
Returns the union of the two QTimeSpans.
\sa united()
*/
QTimeSpan operator|(const QTimeSpan &left, const QTimeSpan &right) // Union
{
QTimeSpan result(left);
result|=right;
return result;
}
/*!
Returns the intersection of the two QTimeSpans.
\sa overlapped()
*/
QTimeSpan operator&(const QTimeSpan &left, const QTimeSpan &right) // Intersection
{
QTimeSpan result(left);
result&=right;
return result;
}
// Operators that use QTimeSpan and other date/time classes
/*!
Creates a new QTimeSpan object that describes the period between the two
QDateTime objects. The \a right hand object will be used as the reference date,
so that substracting a date in the past from a date representing now will yield
a positive QTimeSpan.
Note that while substracting two dates will result in a QTimeSpan describing
the time between those dates, there is no pendant operation for adding two dates.
Substractions involving an invalid QDateTime, will result in a time span with
an interval length 0. If the right-hand QDateTime is valid, it will still be
used as the reference date.
*/
QTimeSpan operator-(const QDateTime &left, const QDateTime &right)
{
QTimeSpan result(right);
if (left.isValid() && right.isValid())
result = QTimeSpan(right, right.msecsTo(left));
return result;
}
/*!
Creates a new QTimeSpan object that describes the period between the two
QDate objects. The \a right hand object will be used as the reference date,
so that substracting a date in the past from a date representing now will yield
a positive QTimeSpan.
Note that while substracting two dates will result in a QTimeSpan describing
the time between those dates, there is no pendant operation for adding two dates.
\overload
*/
QTimeSpan operator-(const QDate &left, const QDate &right)
{
QTimeSpan result = QDateTime(left) - QDateTime(right);
return result;
}
/*!
Creates a new QTimeSpan object that describes the period between the two
QTime objects. The \a right hand time will be used as the reference time,
so that substracting a time in the past from a time representing now will yield
a positive QTimeSpan.
Note that that both times will be assumed to be on the current date.
Also observe that while substracting two times will result in a QTimeSpan describing
the time between those, there is no pendant operation for adding two times.
*/
QTimeSpan operator-(const QTime &left, const QTime &right)
{
return QDateTime(QDate::currentDate(), left) - QDateTime(QDate::currentDate(), right);
}
/*!
Returns the date described by the \a left hand date, shifted by the interval
described in the QTimeSpan \a right. The reference date of the QTimeSpan, if set, is
ignored.
No rounding takes place. If a QTimeSpan describes 1 day, 23 hours and 59 minutes,
adding that QTimeSpan to a QDate respresenting April 1 will still yield April 2.
\overload
*/
QDate operator+(const QDate &left, const QTimeSpan &right)
{
QDateTime dt(left);
return (dt + right).date();
}
/*!
Returns the date and time described by the \a left hand QDateTime, shifted by
the interval described in the QTimeSpan \a right. The reference date of the QTimeSpan, if set,
is ignored.
*/
QDateTime operator+(const QDateTime &left, const QTimeSpan &right)
{
QDateTime result(left);
result = result.addMSecs(right.toMSecs());
return result;
}
/*!
Returns the time described by the \a left hand QTime, shifted by
the interval described in the QTimeSpan \right. The reference date of the QTimeSpan, if set,
is ignored.
\note that since QTimeSpan works with dates and times, the time returned will never
be bigger than 23:59:59.999. The time will wrap to the next date. Use QDateTime objects
if you need to keep track of that.
\overload
*/
QTime operator+(const QTime &left, const QTimeSpan &right)
{
QDateTime dt(QDate::currentDate(), left);
dt = dt.addMSecs(right.toMSecs());
return dt.time();
}
/*!
Returns the date described by the \a left hand date, shifted by the negated interval
described in the QTimeSpan \a right. The reference date of the QTimeSpan, if set, is
ignored.
No rounding takes place. If a QTimeSpan describes 1 day, 23 hours and 59 minutes,
adding that QTimeSpan to a QDate respresenting April 1 will still yield April 2.
\overload
*/
QDate operator-(const QDate &left, const QTimeSpan &right)
{
QDateTime dt(left);
return (dt - right).date();
}
/*!
Returns the date and time described by the \a left hand QDateTime, shifted by
the negated interval described in the QTimeSpan \a right. The reference date of the
QTimeSpan, if set, is ignored.
*/
QDateTime operator-(const QDateTime &left, const QTimeSpan &right)
{
QDateTime result(left);
result = result.addMSecs( -(right.toMSecs()) );
return result;
}
/*!
Returns the time described by the \a left hand QTime, shifted by
the negated interval described in the QTimeSpan \a right. The reference date of
the QTimeSpan, if set, is ignored.
\note that since QTimeSpan works with dates and times, the time returned will never
be bigger than 23:59:59.999. The time will wrap to the next date. Use QDateTimes
if you need to keep track of that.
*/
QTime operator-(const QTime &left, const QTimeSpan &right)
{
QDateTime dt(QDate::currentDate(), left);
dt = dt.addMSecs( -(right.toMSecs()) );
return dt.time();
}
#if !defined(QT_NO_DEBUG_STREAM) && !defined(QT_NO_DATESTRING)
/*!
Operator to stream QTimeSpan objects to a debug stream.
*/
QDebug operator<<(QDebug debug, const QTimeSpan &ts)
{
debug << "QTimeSpan(Reference Date =" << ts.referenceDate()
<< "msecs =" << ts.toMSecs() << ")";
return debug;
}
#endif
//String conversions
#ifndef QT_NO_DATESTRING
/*!
Returns an approximate representation of the time span length
When representing the lenght of a time span, it is often not nessecairy to be
completely accurate. For instance, when dispaying the age of a person, it is
often enough to just state the number of years, or possibly the number of years
and the number of months. Similary, when displaying how long a certain operation
the user of your application started will run, it is useless to display the
number of seconds left if the operation will run for hours more.
toApproximateString() provides functionality to display the length of the
QTimeSpan in such an approximate way. It will format the time using one or two
neighbouring time units, chosen from the units set in \a format. The first
time unit that will be used is the unit that represents the biggest portion
of time in the span. The second time unit will be the time unit directly under
that. The second unit will only be used if it is not 0, and if the first number
is smaller than the indicated \a suppresSecondUnitLimit.
The \a suppressSecondUnitLimit argument can be used to suppres, for instance,
the number of seconds when the operation will run for more than five minutes
more. The idea is that for an approximate representation of the time length,
it is no longer relevant to display the second unit if the first respresents
a time span that is perhaps an order of magnitude larger already.
If you set \a suppressSecondUnitLimit to a negative number, the second unit will
always be displayed, unless no valid unit for it could be found.
\sa magnitude() toString()
*/
QString QTimeSpan::toApproximateString(int suppresSecondUnitLimit, Qt::TimeSpanFormat format)
{
if (format==Qt::NoUnit)
return QString();
//retreive the time unit to use as the primairy unit
int primairy = -1;
int secondairy = -1;
Qt::TimeSpanUnit primairyUnit = magnitude();
while (!format.testFlag(primairyUnit ) && primairyUnit > Qt::NoUnit)
primairyUnit = Qt::TimeSpanUnit(primairyUnit / 2);
Qt::TimeSpanUnit secondairyUnit = Qt::NoUnit;
if (primairyUnit > 1) {
secondairyUnit = Qt::TimeSpanUnit(primairyUnit / 2);
} else {
primairy = 0;
}
while (!format.testFlag(secondairyUnit) && secondairyUnit > Qt::NoUnit)
secondairyUnit = Qt::TimeSpanUnit(secondairyUnit / 2);
//build up hash with pointers to ints for the units that are set in format, and 0's for those that are not.
if (primairy < 0) {
QTimeSpanPrivate::TimePartHash partsHash(format);
bool result = partsHash.fill(*this);
if (!result) {
qDebug() << "false result from parts function";
return QString();
}
primairy = *(partsHash.value(primairyUnit));
if (secondairyUnit > 0) {
secondairy = *(partsHash.value(secondairyUnit));
} else {
secondairy = 0;
}
}
if ((primairy > 0
&& secondairy > 0
&& primairy < suppresSecondUnitLimit)
|| (suppresSecondUnitLimit < 0
&& secondairyUnit > Qt::NoUnit) )
{
//we will display with two units
return d->unitString(primairyUnit, primairy) + QLatin1String(", ") + d->unitString(secondairyUnit, secondairy);
}
//we will display with only the primairy unit
return d->unitString(primairyUnit, primairy);
}
/*!
Returns a string representation of the duration of this time span in the requested \a format
This function returns a representation of only the \i length of this time span. If
you need the reference or referenced dates, access those using one of the provided
methods and output them directly.
The format parameter determines the format of the result string. The duration will be
expressed in the units you use in the format.
\table
\header
\o character
\o meaning
\row
\o y
\o The number of years
\row
\o M
\o The number of months
\row
\o w
\o The number of weeks
\row
\o d
\o The number of days
\row
\o h
\o The number of hours
\row
\o m
\o The number of minutes
\row
\o s
\o The number of seconds
\row
\o z
\o The number of milliseconds
\endtable
Use a letter repeatingly to force leading zeros.
Note that you can not use years or months if the QTimeSpan does not have a valid reference
date.
Characters in the string that don't represent a time unit, are used as literal strings in the
output. Everything between single quotes will always be used as a literal string. This makes
it possible to use the characters used for the time span format also as literal output. To use a
single quote in the output, put two consecutive single quotes within a single quote literal
string block. To just put a single quote in a the output, you need four consequtive single
quotes.
\sa toApproximateString()
*/
QString QTimeSpan::toString(const QString &format) const
{
Qt::TimeSpanFormat tsFormat = Qt::NoUnit;
QList<QTimeSpanPrivate::TimeFormatToken> tokenList = d->parseFormatString(format, tsFormat);
QTimeSpanPrivate::TimePartHash partsHash(tsFormat);
bool result = partsHash.fill(*this);
if (!result)
return QString();
QString formattedString;
foreach(QTimeSpanPrivate::TimeFormatToken token, tokenList) {
if (token.type == 0) {
formattedString.append(token.string);
} else {
Qt::TimeSpanUnit unit(token.type);
formattedString.append (QString(QString::fromLatin1("%1"))
.arg(*partsHash.value(unit),
token.length,
10,
QChar('0', 0) ) );
}
}
return formattedString;
}
/*!
Returns a time span represented by the \a string using the \a format given, or an empty
time span if the string cannot be parsed.
The optional \a reference argument will be used as the reference date for the string.
\note You can only use months or years if you also pass a valid reference.
*/
QTimeSpan QTimeSpan::fromString(const QString &string, const QString &format, const QDateTime &reference)
{
/*
There are at least two possible ways of parsing a string. On the one hand, you could use
the lengths of string literals to determine the positions in the string where you expect
the different parts of the string. On the other hand, you could use the actual contents
of the literals as delimiters to figure out what parts of the string refer to what
unit of time. In that case, the length of the time units would only matter if they are
not surrounded by a string literal. Both seem useful. Perhaps we need two different
modes for this?
The code here implements the first option. The overloaded version below implements a
more flexible regexp based approach.
*/
//stage one: parse the format string
QTimeSpan span(reference);
Qt::TimeSpanFormat tsFormat = Qt::NoUnit;
QList<QTimeSpanPrivate::TimeFormatToken> tokenList = span.d->parseFormatString(format, tsFormat);
//prepare the temporaries
QTimeSpanPrivate::TimePartHash partsHash(tsFormat);
QString input(string);
//extract the values from the input string into our temporary structure
foreach(const QTimeSpanPrivate::TimeFormatToken token, tokenList) {
if (token.type == Qt::NoUnit) {
input = input.remove(0, token.length);
} else {
QString part = input.left(token.length);
input = input.remove(0, token.length);
bool success(false);
part = part.trimmed();
int value = part.toInt(&success, 10);
if (!success)
return QTimeSpan();
*(partsHash.value(token.type)) = value;
}
}
//construct the time span from the temporary data
//we must set the number of years and months first; for the rest order is not important
if (partsHash.value(Qt::Years)) {
span.d->addUnit(&span, Qt::Years, *(partsHash.value(Qt::Years)));
delete partsHash.value(Qt::Years);
partsHash.insert(Qt::Years, 0);
}
if (partsHash.value(Qt::Months)) {
span.d->addUnit(&span, Qt::Months, *(partsHash.value(Qt::Months)));
delete partsHash.value(Qt::Months);
partsHash.insert(Qt::Months, 0);
}
//add the rest of the units
QHashIterator<Qt::TimeSpanUnit, int*> it(partsHash);
while (it.hasNext()) {
it.next();
if (it.value()) {
span.d->addUnit(&span, it.key(), *(it.value()));
qDebug() << "Added unit" << it.key() << "with value" << *(it.value()) << "new value" << span.d->interval;
}
}
return span;
}
/*!
Returns a time span represented by the \a string using the \a patern given, or an empty
time span if the \a string cannot be parsed. Each pair of capturing parenthesis can
extract a time unit. The order in which the units appear is given by the list of
arguments unit1 to unit8. Captures for which the corresponding type is set to
Qt::NoUnit will be ignored.
The \a reference argument will be used as the reference date for the string.
\note You can only use months or years if you also pass a valid \a reference.
*/
QTimeSpan QTimeSpan::fromString(const QString &string, const QRegExp &pattern, const QDateTime &reference,
Qt::TimeSpanUnit unit1, Qt::TimeSpanUnit unit2, Qt::TimeSpanUnit unit3,
Qt::TimeSpanUnit unit4, Qt::TimeSpanUnit unit5, Qt::TimeSpanUnit unit6,
Qt::TimeSpanUnit unit7, Qt::TimeSpanUnit unit8)
{
if (pattern.indexIn(string) < 0)
return QTimeSpan();
QTimeSpanPrivate::TimePartHash partsHash(Qt::NoUnit);
QList<Qt::TimeSpanUnit> unitList;
unitList << unit1 << unit2 << unit3 << unit4 << unit5 << unit6 << unit7 << unit8;
for (int i(0); i < qMin(pattern.captureCount(), 8 ); ++i) {
if (unitList.at(i) > Qt::NoUnit) {
partsHash.addUnit(unitList.at(i));
QString capture = pattern.cap(i + 1);
bool ok(false);
int value = capture.toInt(&ok, 10);
if (!ok)
return QTimeSpan();
*(partsHash.value(unitList.at(i))) = value;
}
}
//create the time span to return
QTimeSpan span(reference);
//construct the time span from the temporary data
//we must set the number of years and months first; for the rest order is not important
if (partsHash.value(Qt::Years)) {
span.d->addUnit(&span, Qt::Years, *(partsHash.value(Qt::Years)));
delete partsHash.value(Qt::Years);
partsHash.insert(Qt::Years, 0);
}
if (partsHash.value(Qt::Months)) {
span.d->addUnit(&span, Qt::Months, *(partsHash.value(Qt::Months)));
delete partsHash.value(Qt::Months);
partsHash.insert(Qt::Months, 0);
}
//add the rest of the units
QHashIterator<Qt::TimeSpanUnit, int*> it(partsHash);
while (it.hasNext()) {
it.next();
if (it.value())
span.d->addUnit(&span, it.key(), *(it.value()));
}
return span;
}
#endif
QT_END_NAMESPACE
| [
"squual@kahvipaussi.net"
] | squual@kahvipaussi.net |
32663debfe682c9ef244f125e9ee675f6fb00ad2 | cfeac52f970e8901871bd02d9acb7de66b9fb6b4 | /generated/src/aws-cpp-sdk-ec2/source/model/GetCoipPoolUsageRequest.cpp | daee2872508f86176bd7096dfac25ef966e7efb8 | [
"Apache-2.0",
"MIT",
"JSON"
] | permissive | aws/aws-sdk-cpp | aff116ddf9ca2b41e45c47dba1c2b7754935c585 | 9a7606a6c98e13c759032c2e920c7c64a6a35264 | refs/heads/main | 2023-08-25T11:16:55.982089 | 2023-08-24T18:14:53 | 2023-08-24T18:14:53 | 35,440,404 | 1,681 | 1,133 | Apache-2.0 | 2023-09-12T15:59:33 | 2015-05-11T17:57:32 | null | UTF-8 | C++ | false | false | 1,481 | cpp | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/ec2/model/GetCoipPoolUsageRequest.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>
using namespace Aws::EC2::Model;
using namespace Aws::Utils;
GetCoipPoolUsageRequest::GetCoipPoolUsageRequest() :
m_poolIdHasBeenSet(false),
m_filtersHasBeenSet(false),
m_maxResults(0),
m_maxResultsHasBeenSet(false),
m_nextTokenHasBeenSet(false),
m_dryRun(false),
m_dryRunHasBeenSet(false)
{
}
Aws::String GetCoipPoolUsageRequest::SerializePayload() const
{
Aws::StringStream ss;
ss << "Action=GetCoipPoolUsage&";
if(m_poolIdHasBeenSet)
{
ss << "PoolId=" << StringUtils::URLEncode(m_poolId.c_str()) << "&";
}
if(m_filtersHasBeenSet)
{
unsigned filtersCount = 1;
for(auto& item : m_filters)
{
item.OutputToStream(ss, "Filter.", filtersCount, "");
filtersCount++;
}
}
if(m_maxResultsHasBeenSet)
{
ss << "MaxResults=" << m_maxResults << "&";
}
if(m_nextTokenHasBeenSet)
{
ss << "NextToken=" << StringUtils::URLEncode(m_nextToken.c_str()) << "&";
}
if(m_dryRunHasBeenSet)
{
ss << "DryRun=" << std::boolalpha << m_dryRun << "&";
}
ss << "Version=2016-11-15";
return ss.str();
}
void GetCoipPoolUsageRequest::DumpBodyToUrl(Aws::Http::URI& uri ) const
{
uri.SetQueryString(SerializePayload());
}
| [
"sdavtaker@users.noreply.github.com"
] | sdavtaker@users.noreply.github.com |
495c133809f1be0759d9d317921fdb258f849e89 | c37be0d1ddf85325c6bd02a0c57cb1dfe2df8c36 | /chrome/browser/media/router/mojo/extension_media_route_provider_proxy_unittest.cc | e324ddcdb4ddc7ff8e06880556332c8433687387 | [
"BSD-3-Clause"
] | permissive | idofilus/chromium | 0f78b085b1b4f59a5fc89d6fc0efef16beb63dcd | 47d58b9c7cb40c09a7bdcdaa0feead96ace95284 | refs/heads/master | 2023-03-04T18:08:14.105865 | 2017-11-14T18:26:28 | 2017-11-14T18:26:28 | 111,206,269 | 0 | 0 | null | 2017-11-18T13:06:33 | 2017-11-18T13:06:32 | null | UTF-8 | C++ | false | false | 11,392 | cc | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/media/router/mojo/extension_media_route_provider_proxy.h"
#include "base/macros.h"
#include "base/memory/ptr_util.h"
#include "base/test/mock_callback.h"
#include "chrome/browser/media/router/event_page_request_manager.h"
#include "chrome/browser/media/router/event_page_request_manager_factory.h"
#include "chrome/browser/media/router/mojo/media_router_mojo_test.h"
#include "chrome/test/base/testing_profile.h"
#include "content/public/test/test_browser_thread_bundle.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using testing::_;
using testing::ElementsAre;
using testing::Invoke;
using testing::Mock;
using testing::StrictMock;
using testing::WithArg;
namespace media_router {
namespace {
using MockRouteCallback =
base::MockCallback<MockMediaRouteProvider::RouteCallback>;
using MockTerminateRouteCallback =
base::MockCallback<mojom::MediaRouteProvider::TerminateRouteCallback>;
using MockBoolCallback = base::MockCallback<base::OnceCallback<void(bool)>>;
using MockSearchSinksCallback =
base::MockCallback<base::OnceCallback<void(const std::string&)>>;
const char kDescription[] = "description";
const bool kIsIncognito = false;
const char kSource[] = "source1";
const char kRouteId[] = "routeId";
const char kSinkId[] = "sink";
const int kTabId = 1;
const char kPresentationId[] = "presentationId";
const char kOrigin[] = "http://origin/";
const int kTimeoutMillis = 5 * 1000;
} // namespace
class ExtensionMediaRouteProviderProxyTest : public testing::Test {
public:
ExtensionMediaRouteProviderProxyTest() = default;
~ExtensionMediaRouteProviderProxyTest() override = default;
protected:
void SetUp() override {
request_manager_ = static_cast<MockEventPageRequestManager*>(
EventPageRequestManagerFactory::GetInstance()->SetTestingFactoryAndUse(
&profile_, &MockEventPageRequestManager::Create));
ON_CALL(*request_manager_, RunOrDeferInternal(_, _))
.WillByDefault(Invoke([](base::OnceClosure& request,
MediaRouteProviderWakeReason wake_reason) {
std::move(request).Run();
}));
provider_proxy_ = base::MakeUnique<ExtensionMediaRouteProviderProxy>(
&profile_, mojo::MakeRequest(&provider_proxy_ptr_));
RegisterMockMediaRouteProvider();
}
const MediaSource media_source_ = MediaSource(kSource);
const MediaRoute route_ = MediaRoute(kRouteId,
media_source_,
kSinkId,
kDescription,
false,
"",
false);
std::unique_ptr<ExtensionMediaRouteProviderProxy> provider_proxy_;
mojom::MediaRouteProviderPtr provider_proxy_ptr_;
StrictMock<MockMediaRouteProvider> mock_provider_;
MockEventPageRequestManager* request_manager_ = nullptr;
std::unique_ptr<mojo::Binding<mojom::MediaRouteProvider>> binding_;
private:
void RegisterMockMediaRouteProvider() {
mock_provider_.SetRouteToReturn(route_);
mojom::MediaRouteProviderPtr mock_provider_ptr;
binding_ = base::MakeUnique<mojo::Binding<mojom::MediaRouteProvider>>(
&mock_provider_, mojo::MakeRequest(&mock_provider_ptr));
provider_proxy_->RegisterMediaRouteProvider(std::move(mock_provider_ptr));
}
content::TestBrowserThreadBundle thread_bundle_;
TestingProfile profile_;
DISALLOW_COPY_AND_ASSIGN(ExtensionMediaRouteProviderProxyTest);
};
TEST_F(ExtensionMediaRouteProviderProxyTest, CreateRoute) {
EXPECT_CALL(
mock_provider_,
CreateRouteInternal(kSource, kSinkId, kPresentationId,
url::Origin::Create(GURL(kOrigin)), kTabId,
base::TimeDelta::FromMilliseconds(kTimeoutMillis),
kIsIncognito, _))
.WillOnce(WithArg<7>(Invoke(
&mock_provider_, &MockMediaRouteProvider::RouteRequestSuccess)));
MockRouteCallback callback;
provider_proxy_->CreateRoute(
kSource, kSinkId, kPresentationId, url::Origin::Create(GURL(kOrigin)),
kTabId, base::TimeDelta::FromMilliseconds(kTimeoutMillis), kIsIncognito,
base::BindOnce(&MockRouteCallback::Run, base::Unretained(&callback)));
base::RunLoop().RunUntilIdle();
}
TEST_F(ExtensionMediaRouteProviderProxyTest, JoinRoute) {
EXPECT_CALL(
mock_provider_,
JoinRouteInternal(
kSource, kPresentationId, url::Origin::Create(GURL(kOrigin)), kTabId,
base::TimeDelta::FromMilliseconds(kTimeoutMillis), kIsIncognito, _))
.WillOnce(WithArg<6>(Invoke(
&mock_provider_, &MockMediaRouteProvider::RouteRequestSuccess)));
MockRouteCallback callback;
provider_proxy_->JoinRoute(
kSource, kPresentationId, url::Origin::Create(GURL(kOrigin)), kTabId,
base::TimeDelta::FromMilliseconds(kTimeoutMillis), kIsIncognito,
base::BindOnce(&MockRouteCallback::Run, base::Unretained(&callback)));
base::RunLoop().RunUntilIdle();
}
TEST_F(ExtensionMediaRouteProviderProxyTest, ConnectRouteByRouteId) {
EXPECT_CALL(
mock_provider_,
ConnectRouteByRouteIdInternal(
kSource, kRouteId, kPresentationId,
url::Origin::Create(GURL(kOrigin)), kTabId,
base::TimeDelta::FromMilliseconds(kTimeoutMillis), kIsIncognito, _))
.WillOnce(WithArg<7>(Invoke(
&mock_provider_, &MockMediaRouteProvider::RouteRequestSuccess)));
MockRouteCallback callback;
provider_proxy_->ConnectRouteByRouteId(
kSource, kRouteId, kPresentationId, url::Origin::Create(GURL(kOrigin)),
kTabId, base::TimeDelta::FromMilliseconds(kTimeoutMillis), kIsIncognito,
base::BindOnce(&MockRouteCallback::Run, base::Unretained(&callback)));
base::RunLoop().RunUntilIdle();
}
TEST_F(ExtensionMediaRouteProviderProxyTest, TerminateRoute) {
EXPECT_CALL(mock_provider_, TerminateRouteInternal(kRouteId, _))
.WillOnce(WithArg<1>(Invoke(
&mock_provider_, &MockMediaRouteProvider::TerminateRouteSuccess)));
MockTerminateRouteCallback callback;
provider_proxy_->TerminateRoute(
kRouteId, base::BindOnce(&MockTerminateRouteCallback::Run,
base::Unretained(&callback)));
base::RunLoop().RunUntilIdle();
}
TEST_F(ExtensionMediaRouteProviderProxyTest, SendRouteMessage) {
const std::string message = "message";
EXPECT_CALL(mock_provider_, SendRouteMessageInternal(kRouteId, message, _))
.WillOnce(WithArg<2>(Invoke(
&mock_provider_, &MockMediaRouteProvider::SendRouteMessageSuccess)));
MockBoolCallback callback;
provider_proxy_->SendRouteMessage(
kRouteId, message,
base::BindOnce(&MockBoolCallback::Run, base::Unretained(&callback)));
base::RunLoop().RunUntilIdle();
}
TEST_F(ExtensionMediaRouteProviderProxyTest, SendRouteBinaryMessage) {
std::vector<uint8_t> data = {42};
EXPECT_CALL(mock_provider_,
SendRouteBinaryMessageInternal(kRouteId, ElementsAre(42), _))
.WillOnce(WithArg<2>(
Invoke(&mock_provider_,
&MockMediaRouteProvider::SendRouteBinaryMessageSuccess)));
MockBoolCallback callback;
provider_proxy_->SendRouteBinaryMessage(
kRouteId, data,
base::BindOnce(&MockBoolCallback::Run, base::Unretained(&callback)));
base::RunLoop().RunUntilIdle();
}
TEST_F(ExtensionMediaRouteProviderProxyTest, StartAndStopObservingMediaSinks) {
EXPECT_CALL(mock_provider_, StopObservingMediaSinks(kSource));
provider_proxy_->StopObservingMediaSinks(kSource);
base::RunLoop().RunUntilIdle();
}
TEST_F(ExtensionMediaRouteProviderProxyTest, StartAndStopObservingMediaRoutes) {
EXPECT_CALL(mock_provider_, StopObservingMediaRoutes(kSource));
provider_proxy_->StopObservingMediaRoutes(kSource);
base::RunLoop().RunUntilIdle();
}
TEST_F(ExtensionMediaRouteProviderProxyTest, StartListeningForRouteMessages) {
EXPECT_CALL(mock_provider_, StartListeningForRouteMessages(kSource));
provider_proxy_->StartListeningForRouteMessages(kSource);
base::RunLoop().RunUntilIdle();
}
TEST_F(ExtensionMediaRouteProviderProxyTest, StopListeningForRouteMessages) {
EXPECT_CALL(mock_provider_, StopListeningForRouteMessages(kSource));
provider_proxy_->StopListeningForRouteMessages(kSource);
base::RunLoop().RunUntilIdle();
}
TEST_F(ExtensionMediaRouteProviderProxyTest, DetachRoute) {
EXPECT_CALL(mock_provider_, DetachRoute(kRouteId));
provider_proxy_->DetachRoute(kRouteId);
base::RunLoop().RunUntilIdle();
}
TEST_F(ExtensionMediaRouteProviderProxyTest, EnableMdnsDiscovery) {
EXPECT_CALL(mock_provider_, EnableMdnsDiscovery());
provider_proxy_->EnableMdnsDiscovery();
base::RunLoop().RunUntilIdle();
}
TEST_F(ExtensionMediaRouteProviderProxyTest, UpdateMediaSinks) {
EXPECT_CALL(mock_provider_, UpdateMediaSinks(kSource));
provider_proxy_->UpdateMediaSinks(kSource);
base::RunLoop().RunUntilIdle();
}
TEST_F(ExtensionMediaRouteProviderProxyTest, SearchSinks) {
EXPECT_CALL(mock_provider_, SearchSinksInternal(kSinkId, kSource, _, _))
.WillOnce(WithArg<3>(Invoke(
&mock_provider_, &MockMediaRouteProvider::SearchSinksSuccess)));
auto sink_search_criteria = mojom::SinkSearchCriteria::New();
MockSearchSinksCallback callback;
provider_proxy_->SearchSinks(kSinkId, kSource,
std::move(sink_search_criteria),
base::BindOnce(&MockSearchSinksCallback::Run,
base::Unretained(&callback)));
base::RunLoop().RunUntilIdle();
}
TEST_F(ExtensionMediaRouteProviderProxyTest, ProvideSinks) {
const std::string provider_name = "provider name";
MediaSinkInternal sink;
sink.set_sink_id(kSinkId);
const std::vector<media_router::MediaSinkInternal> sinks = {sink};
EXPECT_CALL(mock_provider_, ProvideSinks(provider_name, ElementsAre(sink)));
provider_proxy_->ProvideSinks(provider_name, sinks);
base::RunLoop().RunUntilIdle();
}
TEST_F(ExtensionMediaRouteProviderProxyTest, CreateMediaRouteController) {
EXPECT_CALL(mock_provider_,
CreateMediaRouteControllerInternal(kRouteId, _, _, _))
.WillOnce(WithArg<3>(
Invoke(&mock_provider_,
&MockMediaRouteProvider::CreateMediaRouteControllerSuccess)));
mojom::MediaControllerPtr controller_ptr;
mojom::MediaControllerRequest controller_request =
mojo::MakeRequest(&controller_ptr);
mojom::MediaStatusObserverPtr observer_ptr;
mojom::MediaStatusObserverRequest observer_request =
mojo::MakeRequest(&observer_ptr);
MockBoolCallback callback;
provider_proxy_->CreateMediaRouteController(
kRouteId, std::move(controller_request), std::move(observer_ptr),
base::BindOnce(&MockBoolCallback::Run, base::Unretained(&callback)));
base::RunLoop().RunUntilIdle();
}
TEST_F(ExtensionMediaRouteProviderProxyTest, NotifyRequestManagerOnError) {
// Invalidating the Mojo pointer to the MRP held by the proxy should make it
// notify request manager.
EXPECT_CALL(*request_manager_, OnMojoConnectionError());
binding_.reset();
base::RunLoop().RunUntilIdle();
}
} // namespace media_router
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
906b39e70de12e65a3ab34d7030be09abfb766de | 75452de12ec9eea346e3b9c7789ac0abf3eb1d73 | /src/storage/fs_test/link.cc | ab8d7439e770cb0f6c1aae58b932ab98d79bf280 | [
"BSD-3-Clause"
] | permissive | oshunter/fuchsia | c9285cc8c14be067b80246e701434bbef4d606d1 | 2196fc8c176d01969466b97bba3f31ec55f7767b | refs/heads/master | 2022-12-22T11:30:15.486382 | 2020-08-16T03:41:23 | 2020-08-16T03:41:23 | 287,920,017 | 2 | 2 | BSD-3-Clause | 2022-12-16T03:30:27 | 2020-08-16T10:18:30 | C++ | UTF-8 | C++ | false | false | 12,907 | cc | // Copyright 2017 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <unistd.h>
#include <optional>
#include <vector>
#include "src/storage/fs_test/fs_test_fixture.h"
#include "src/storage/fs_test/misc.h"
namespace fs_test {
namespace {
using HardLinkTest = FilesystemTest;
void CheckLinkCount(const std::string& path, unsigned count) {
struct stat s;
ASSERT_EQ(stat(path.c_str(), &s), 0);
ASSERT_EQ(s.st_nlink, count);
}
TEST_P(HardLinkTest, Basic) {
const std::string old_path = GetPath("a");
const std::string new_path = GetPath("b");
// Make a file, fill it with content
int fd = open(old_path.c_str(), O_RDWR | O_CREAT | O_EXCL, 0644);
ASSERT_GT(fd, 0);
uint8_t buf[100];
for (size_t i = 0; i < sizeof(buf); i++) {
buf[i] = (uint8_t)rand();
}
ASSERT_EQ(write(fd, buf, sizeof(buf)), static_cast<ssize_t>(sizeof(buf)));
ASSERT_NO_FATAL_FAILURE(CheckFileContents(fd, buf));
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(old_path, 1));
ASSERT_EQ(link(old_path.c_str(), new_path.c_str()), 0);
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(old_path, 2));
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(new_path, 2));
// Confirm that both the old link and the new links exist
int fd2 = open(new_path.c_str(), O_RDONLY, 0644);
ASSERT_GT(fd2, 0);
ASSERT_NO_FATAL_FAILURE(CheckFileContents(fd2, buf));
ASSERT_NO_FATAL_FAILURE(CheckFileContents(fd, buf));
// Remove the old link
ASSERT_EQ(close(fd), 0);
ASSERT_EQ(close(fd2), 0);
ASSERT_EQ(unlink(old_path.c_str()), 0);
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(new_path, 1));
// Open the link by its new name, and verify that the contents have
// not been altered by the removal of the old link.
fd = open(new_path.c_str(), O_RDONLY, 0644);
ASSERT_GT(fd, 0);
ASSERT_NO_FATAL_FAILURE(CheckFileContents(fd, buf));
ASSERT_EQ(close(fd), 0);
ASSERT_EQ(unlink(new_path.c_str()), 0);
}
TEST_P(HardLinkTest, test_link_count_dirs) {
ASSERT_EQ(mkdir(GetPath("dira").c_str(), 0755), 0);
// New directories should have two links:
// Parent --> newdir
// newdir ('.') --> newdir
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dira"), 2));
// Adding a file won't change the parent link count...
int fd = open(GetPath("dira/file").c_str(), O_RDWR | O_CREAT | O_EXCL, 0644);
ASSERT_GT(fd, 0);
ASSERT_EQ(close(fd), 0);
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dira"), 2));
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dira/file"), 1));
// But adding a directory WILL change the parent link count.
ASSERT_EQ(mkdir(GetPath("dira/dirb").c_str(), 0755), 0);
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dira"), 3));
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dira/dirb"), 2));
// Test that adding "depth" increases the dir count as we expect.
ASSERT_EQ(mkdir(GetPath("dira/dirb/dirc").c_str(), 0755), 0);
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dira"), 3));
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dira/dirb"), 3));
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dira/dirb/dirc"), 2));
// Demonstrate that unwinding also reduces the link count.
ASSERT_EQ(unlink(GetPath("dira/dirb/dirc").c_str()), 0);
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dira"), 3));
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dira/dirb"), 2));
ASSERT_EQ(unlink(GetPath("dira/dirb").c_str()), 0);
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dira"), 2));
// Test that adding "width" increases the dir count too.
ASSERT_EQ(mkdir(GetPath("dira/dirb").c_str(), 0755), 0);
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dira"), 3));
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dira/dirb"), 2));
ASSERT_EQ(mkdir(GetPath("dira/dirc").c_str(), 0755), 0);
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dira"), 4));
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dira/dirb"), 2));
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dira/dirc"), 2));
// Demonstrate that unwinding also reduces the link count.
ASSERT_EQ(unlink(GetPath("dira/dirc").c_str()), 0);
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dira"), 3));
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dira/dirb"), 2));
ASSERT_EQ(unlink(GetPath("dira/dirb").c_str()), 0);
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dira"), 2));
ASSERT_EQ(unlink(GetPath("dira/file").c_str()), 0);
ASSERT_EQ(unlink(GetPath("dira").c_str()), 0);
}
TEST_P(HardLinkTest, CorrectLinkCountAfterRename) {
// Check that link count does not change with simple rename
ASSERT_EQ(mkdir(GetPath("dir").c_str(), 0755), 0);
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dir"), 2));
ASSERT_EQ(rename(GetPath("dir").c_str(), GetPath("dir_parent").c_str()), 0);
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dir_parent"), 2));
// Set up parent directory with child directories
ASSERT_EQ(mkdir(GetPath("dir_parent/dir_child_a").c_str(), 0755), 0);
ASSERT_EQ(mkdir(GetPath("dir_parent/dir_child_b").c_str(), 0755), 0);
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dir_parent"), 4));
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dir_parent/dir_child_a"), 2));
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dir_parent/dir_child_b"), 2));
// Rename a child directory out of its parent directory
ASSERT_EQ(rename(GetPath("dir_parent/dir_child_b").c_str(), GetPath("dir_parent_alt").c_str()),
0);
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dir_parent"), 3));
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dir_parent/dir_child_a"), 2));
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dir_parent_alt"), 2));
// Rename a parent directory into another directory
ASSERT_EQ(
rename(GetPath("dir_parent").c_str(), GetPath("dir_parent_alt/dir_semi_parent").c_str()), 0);
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dir_parent_alt"), 3));
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dir_parent_alt/dir_semi_parent"), 3));
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dir_parent_alt/dir_semi_parent/dir_child_a"), 2));
// Rename a directory on top of an empty directory
ASSERT_EQ(mkdir(GetPath("dir_child").c_str(), 0755), 0);
ASSERT_EQ(rename(GetPath("dir_child").c_str(),
GetPath("dir_parent_alt/dir_semi_parent/dir_child_a").c_str()),
0);
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dir_parent_alt"), 3));
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dir_parent_alt/dir_semi_parent"), 3));
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dir_parent_alt/dir_semi_parent/dir_child_a"), 2));
// Rename a directory on top of an empty directory from a non-root directory
ASSERT_EQ(mkdir(GetPath("dir").c_str(), 0755), 0);
ASSERT_EQ(mkdir(GetPath("dir/dir_child").c_str(), 0755), 0);
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dir"), 3));
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dir/dir_child"), 2));
ASSERT_EQ(rename(GetPath("dir/dir_child").c_str(),
GetPath("dir_parent_alt/dir_semi_parent/dir_child_a").c_str()),
0);
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dir"), 2));
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dir_parent_alt"), 3));
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dir_parent_alt/dir_semi_parent"), 3));
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dir_parent_alt/dir_semi_parent/dir_child_a"), 2));
// Rename a file on top of a file from a non-root directory
ASSERT_EQ(unlink(GetPath("dir_parent_alt/dir_semi_parent/dir_child_a").c_str()), 0);
int fd = open(GetPath("dir/dir_child").c_str(), O_RDWR | O_CREAT | O_EXCL, 0644);
ASSERT_GT(fd, 0);
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dir"), 2));
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dir/dir_child"), 1));
int fd2 = open(GetPath("dir_parent_alt/dir_semi_parent/dir_child_a").c_str(),
O_RDWR | O_CREAT | O_EXCL, 0644);
ASSERT_GT(fd2, 0);
ASSERT_EQ(rename(GetPath("dir/dir_child").c_str(),
GetPath("dir_parent_alt/dir_semi_parent/dir_child_a").c_str()),
0);
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dir"), 2));
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dir_parent_alt"), 3));
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dir_parent_alt/dir_semi_parent"), 2));
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dir_parent_alt/dir_semi_parent/dir_child_a"), 1));
ASSERT_EQ(close(fd), 0);
ASSERT_EQ(close(fd2), 0);
// Clean up
ASSERT_EQ(unlink(GetPath("dir_parent_alt/dir_semi_parent/dir_child_a").c_str()), 0);
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dir_parent_alt"), 3));
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dir_parent_alt/dir_semi_parent"), 2));
ASSERT_EQ(unlink(GetPath("dir_parent_alt/dir_semi_parent").c_str()), 0);
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dir_parent_alt"), 2));
ASSERT_EQ(unlink(GetPath("dir_parent_alt").c_str()), 0);
ASSERT_EQ(unlink(GetPath("dir").c_str()), 0);
}
TEST_P(HardLinkTest, AcrossDirectories) {
ASSERT_EQ(mkdir(GetPath("dira").c_str(), 0755), 0);
// New directories should have two links:
// Parent --> newdir
// newdir ('.') --> newdir
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dira"), 2));
ASSERT_EQ(mkdir(GetPath("dirb").c_str(), 0755), 0);
ASSERT_NO_FATAL_FAILURE(CheckLinkCount(GetPath("dirb"), 2));
const std::string old_path = GetPath("dira/a");
const std::string new_path = GetPath("dirb/b");
// Make a file, fill it with content
int fd = open(old_path.c_str(), O_RDWR | O_CREAT | O_EXCL, 0644);
ASSERT_GT(fd, 0);
uint8_t buf[100];
for (size_t i = 0; i < sizeof(buf); i++) {
buf[i] = (uint8_t)rand();
}
ASSERT_EQ(write(fd, buf, sizeof(buf)), static_cast<ssize_t>(sizeof(buf)));
ASSERT_NO_FATAL_FAILURE(CheckFileContents(fd, buf));
ASSERT_EQ(link(old_path.c_str(), new_path.c_str()), 0);
// Confirm that both the old link and the new links exist
int fd2 = open(new_path.c_str(), O_RDWR, 0644);
ASSERT_GT(fd2, 0);
ASSERT_NO_FATAL_FAILURE(CheckFileContents(fd2, buf));
ASSERT_NO_FATAL_FAILURE(CheckFileContents(fd, buf));
// Remove the old link
ASSERT_EQ(close(fd), 0);
ASSERT_EQ(close(fd2), 0);
ASSERT_EQ(unlink(old_path.c_str()), 0);
// Open the link by its new name
fd = open(new_path.c_str(), O_RDWR, 0644);
ASSERT_GT(fd, 0);
ASSERT_NO_FATAL_FAILURE(CheckFileContents(fd, buf));
ASSERT_EQ(close(fd), 0);
ASSERT_EQ(unlink(new_path.c_str()), 0);
ASSERT_EQ(unlink(GetPath("dira").c_str()), 0);
ASSERT_EQ(unlink(GetPath("dirb").c_str()), 0);
}
TEST_P(HardLinkTest, Errors) {
const std::string dir_path = GetPath("dir");
const std::string old_path = GetPath("a");
const std::string new_path = GetPath("b");
const std::string new_path_dir = GetPath("b/");
// We should not be able to create hard links to directories
ASSERT_EQ(mkdir(dir_path.c_str(), 0755), 0);
ASSERT_EQ(link(dir_path.c_str(), new_path.c_str()), -1);
ASSERT_EQ(unlink(dir_path.c_str()), 0);
// We should not be able to create hard links to non-existent files
ASSERT_EQ(link(old_path.c_str(), new_path.c_str()), -1);
ASSERT_EQ(errno, ENOENT);
int fd = open(old_path.c_str(), O_RDWR | O_CREAT | O_EXCL, 0644);
ASSERT_GT(fd, 0);
ASSERT_EQ(close(fd), 0);
// We should not be able to link to or from . or ..
ASSERT_EQ(link(old_path.c_str(), GetPath(".").c_str()), -1);
ASSERT_EQ(link(old_path.c_str(), GetPath("..").c_str()), -1);
ASSERT_EQ(link(GetPath(".").c_str(), new_path.c_str()), -1);
ASSERT_EQ(link(GetPath("..").c_str(), new_path.c_str()), -1);
// We should not be able to link a file to itself
ASSERT_EQ(link(old_path.c_str(), old_path.c_str()), -1);
ASSERT_EQ(errno, EEXIST);
// We should not be able to link a file to a path that implies it must be a directory
ASSERT_EQ(link(old_path.c_str(), new_path_dir.c_str()), -1);
// After linking, we shouldn't be able to link again
ASSERT_EQ(link(old_path.c_str(), new_path.c_str()), 0);
ASSERT_EQ(link(old_path.c_str(), new_path.c_str()), -1);
ASSERT_EQ(errno, EEXIST);
// In either order
ASSERT_EQ(link(new_path.c_str(), old_path.c_str()), -1);
ASSERT_EQ(errno, EEXIST);
ASSERT_EQ(unlink(new_path.c_str()), 0);
ASSERT_EQ(unlink(old_path.c_str()), 0);
}
INSTANTIATE_TEST_SUITE_P(
/*no prefix*/, HardLinkTest,
testing::ValuesIn(MapAndFilterAllTestFilesystems(
[](const TestFilesystemOptions& options) -> std::optional<TestFilesystemOptions> {
if (options.filesystem->GetTraits().supports_hard_links) {
return options;
} else {
return std::nullopt;
}
})),
testing::PrintToStringParamName());
} // namespace
} // namespace fs_test
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
a9feebad607de513a0b89388802646dac3e3081f | 02c22f9cdab5fa3462469c827f76c505897f5b76 | /src/core/integrators/photon_map/Photon.hpp | f0f441916df8ca19d6a3a4561e9ffdfa5f052fae | [
"Zlib",
"BSD-3-Clause",
"MIT",
"BSL-1.0",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"Unlicense",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | libingzeng/tungsten | 42070b9d64c66c2abc9de4b33a58eb30e0188aef | 8d3e08f6fe825ee90da9ab3e8008b45821ba3c67 | refs/heads/master | 2020-03-31T09:48:13.683372 | 2018-11-04T07:37:59 | 2018-11-04T07:37:59 | 152,111,453 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,336 | hpp | #ifndef PHOTON_HPP_
#define PHOTON_HPP_
#include "math/Vec.hpp"
namespace Tungsten {
struct Photon
{
uint32 splitData;
uint32 bounce;
Vec3f pos;
Vec3f dir;
Vec3f power;
void setSplitInfo(uint32 childIdx, uint32 splitDim, uint32 childCount)
{
uint32 childMask = childCount == 0 ? 0 : (childCount == 1 ? 1 : 3);
splitData = (splitDim << 30u) | (childMask << 28u) | childIdx;
}
bool hasLeftChild() const
{
return (splitData & (1u << 28u)) != 0;
}
bool hasRightChild() const
{
return (splitData & (1u << 29u)) != 0;
}
uint32 splitDim() const
{
return splitData >> 30u;
}
uint32 childIdx() const
{
return splitData & 0x0FFFFFFFu;
}
};
struct VolumePhoton : public Photon
{
Vec3f minBounds;
Vec3f maxBounds;
float radiusSq;
};
struct PathPhoton
{
Vec3f pos;
Vec3f power;
Vec3f dir;
float length;
float sampledLength;
uint32 data;
void setPathInfo(uint32 bounce, bool onSurface)
{
data = bounce;
if (onSurface)
data |= (1u << 31u);
}
bool onSurface() const
{
return (data & (1u << 31u)) != 0;
}
uint32 bounce() const
{
return data & ~(1u << 31u);
}
};
struct PhotonBeam
{
Vec3f p0, p1;
Vec3f dir;
float length;
Vec3f power;
int bounce;
bool valid;
};
struct PhotonPlane0D
{
Vec3f p0, p1, p2, p3;
Vec3f power;
Vec3f d1;
float l1;
int bounce;
bool valid;
Box3f bounds() const
{
Box3f box;
box.grow(p0);
box.grow(p1);
box.grow(p2);
box.grow(p3);
return box;
}
};
struct PhotonPlane1D
{
Vec3f p;
Vec3f invU, invV, invW;
Vec3f center, a, b, c;
Vec3f power;
Vec3f d1;
float l1;
float invDet;
float binCount;
int bounce;
bool valid;
Box3f bounds() const
{
Box3f box;
box.grow(center + a + b + c);
box.grow(center - a + b + c);
box.grow(center + a - b + c);
box.grow(center - a - b + c);
box.grow(center + a + b - c);
box.grow(center - a + b - c);
box.grow(center + a - b - c);
box.grow(center - a - b - c);
return box;
}
};
}
#endif /* PHOTON_HPP_ */
| [
"mail@noobody.org"
] | mail@noobody.org |
499a464d33c11783fd3171e0923f6fd7ae3e73d2 | 44ab461147c679c6f654b5ca8643557e1033ffb9 | /geo_normal_3d_omp.cpp | 8af6006bb32a07c23e37e642f6151e1129950c3c | [
"BSD-3-Clause"
] | permissive | snowmanman/structrock | 767e6f5544aae48e1d70e2c3cf56091f5e7ff40f | 754d8c481d22a48ea7eb4e055eb16c64c44055ab | refs/heads/master | 2021-07-31T01:03:37.715307 | 2020-07-16T07:32:03 | 2020-07-16T07:32:03 | 193,132,993 | 1 | 1 | BSD-3-Clause | 2019-06-21T16:56:32 | 2019-06-21T16:56:32 | null | UTF-8 | C++ | false | false | 2,019 | cpp | /*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2010-2011, Willow Garage, Inc.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* $Id$
*
*/
#include <pcl/point_types.h>
#include <pcl/impl/instantiate.hpp>
#include "geo_normal_3d_omp.h"
// Instantiations of specific point types
template class GeoNormalEstimationOMP<pcl::PointXYZ, pcl::Normal>;
template class GeoNormalEstimationOMP<pcl::PointXYZRGB, pcl::Normal>;
| [
"WXGHolmes@Gmail.com"
] | WXGHolmes@Gmail.com |
acb9df39bd96bba5f0d39befbd0c510017a27ba5 | 28dba754ddf8211d754dd4a6b0704bbedb2bd373 | /Topcoder/FiveHundredEleven.cpp | fc0ab1ccbd74c616c6787170b50421e79a72bca9 | [] | no_license | zjsxzy/algo | 599354679bd72ef20c724bb50b42fce65ceab76f | a84494969952f981bfdc38003f7269e5c80a142e | refs/heads/master | 2023-08-31T17:00:53.393421 | 2023-08-19T14:20:31 | 2023-08-19T14:20:31 | 10,140,040 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,684 | cpp | #line 2 "FiveHundredEleven.cpp"
#include <map>
#include <set>
#include <list>
#include <cmath>
#include <queue>
#include <stack>
#include <bitset>
#include <vector>
#include <cstdio>
#include <string>
#include <sstream>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
int dp[555][55];
vector<int> c;
int n;
int dfs(int mem, int played)
{
if (mem == 511) return 1;
if (played == n) return 0;
int &res = dp[mem][played];
if (res == -1)
{
res = false;
int cnt = 0;
for (int i = 0; i < n; i++)
if ((mem | c[i]) == mem)
{
cnt++;
}
if (cnt > played && !dfs(mem, played + 1))
res = true;
for (int i = 0; i < n; i++)
if ((mem | c[i]) != mem && !dfs((mem | c[i]), played + 1))
res = true;
}
return res;
}
class FiveHundredEleven
{
public:
string theWinner(vector <int> cards)
{
memset(dp, -1, sizeof(dp));
c = cards;
n = c.size();
return dfs(0, 0) ? "Fox Ciel" : "Toastman";
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const string &Expected, const string &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { int Arr0[] = {3, 5, 7, 9, 510}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arg1 = "Fox Ciel"; verify_case(0, Arg1, theWinner(Arg0)); }
void test_case_1() { int Arr0[] = {0, 0, 0, 0}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arg1 = "Toastman"; verify_case(1, Arg1, theWinner(Arg0)); }
void test_case_2() { int Arr0[] = {511}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arg1 = "Toastman"; verify_case(2, Arg1, theWinner(Arg0)); }
void test_case_3() { int Arr0[] = {5, 58, 192, 256}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arg1 = "Fox Ciel"; verify_case(3, Arg1, theWinner(Arg0)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main()
{
FiveHundredEleven ___test;
for (int i = 0; i <= 5; i++)
___test.run_test(i);
return 0;
}
// END CUT HERE
| [
"zjsxzy@gmail.com"
] | zjsxzy@gmail.com |
7149fc13ad7642c91ce070746fee5cd3991ae785 | fe5223cead58a475e43d5289a695d01aab1ec15f | /hphp/compiler/type_annotation.cpp | 19bdd7532fe87e74faeb90329e7d7fb1953ae62e | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-generic-cla",
"PHP-3.01",
"Zend-2.0"
] | permissive | zilberstein/hhvm | ca188c730f5bdbdfb3f3ed0867418a6bcf6ec1b6 | 34f129dce3a7686d32e1ace6b0f6ba03013d7b6e | refs/heads/master | 2021-01-15T10:07:12.837945 | 2014-02-28T20:08:48 | 2014-02-28T20:08:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,187 | cpp | /*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-2014 Facebook, Inc. (http://www.facebook.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include "hphp/compiler/type_annotation.h"
#include "hphp/util/util.h"
namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
// constructors/destructors
TypeAnnotation::TypeAnnotation(const std::string &name,
TypeAnnotationPtr typeArgs) : m_name(name),
m_typeArgs(typeArgs),
m_typeList(TypeAnnotationPtr()),
m_nullable(false),
m_soft(false),
m_tuple(false),
m_function(false),
m_xhp(false),
m_typevar(false) { }
std::string TypeAnnotation::vanillaName() const {
// filter out types that should not be exposed to the runtime
if (m_nullable || m_soft || m_typevar || m_function) {
return "";
}
if (!m_name.compare("mixed") || !m_name.compare("this")) {
return "";
}
return m_name;
}
std::string TypeAnnotation::fullName() const {
std::string name;
if (m_soft) {
name += '@';
}
if (m_nullable) {
name += '?';
}
if (m_function) {
functionTypeName(name);
} else if (m_xhp) {
xhpTypeName(name);
} else if (m_tuple) {
tupleTypeName(name);
} else if (m_typeArgs) {
genericTypeName(name);
} else {
name += m_name;
}
return name;
}
DataType TypeAnnotation::dataType(bool expectedType /*= false */) const {
if (m_function || m_xhp || m_tuple) {
return KindOfObject;
}
if (m_typeArgs) {
return !m_name.compare("array") ? KindOfArray : KindOfObject;
}
if (!expectedType && (m_nullable || m_soft)) {
return KindOfUnknown;
}
if (!m_name.compare("null") || !m_name.compare("void")) {
return KindOfNull;
}
if (!m_name.compare("bool")) return KindOfBoolean;
if (!m_name.compare("int")) return KindOfInt64;
if (!m_name.compare("float")) return KindOfDouble;
if (!m_name.compare("num")) return KindOfUnknown;
if (!m_name.compare("string")) return KindOfString;
if (!m_name.compare("array")) return KindOfArray;
if (!m_name.compare("resource")) return KindOfResource;
if (!m_name.compare("mixed")) return KindOfUnknown;
return KindOfObject;
}
void TypeAnnotation::getAllSimpleNames(std::vector<std::string>& names) const {
names.push_back(m_name);
if (m_typeList) {
m_typeList->getAllSimpleNames(names);
} else if (m_typeArgs) {
m_typeArgs->getAllSimpleNames(names);
}
}
void TypeAnnotation::functionTypeName(std::string &name) const {
name += "(function (";
// return value of function types is the first element of type list
TypeAnnotationPtr retType = m_typeArgs;
TypeAnnotationPtr typeEl = m_typeArgs->m_typeList;
bool hasArgs = (typeEl != nullptr);
while (typeEl) {
name += typeEl->fullName();
typeEl = typeEl->m_typeList;
name += ", ";
}
// replace the trailing ", " (if any) with "): "
if (hasArgs) {
name.replace(name.size() - 2, 2, "): ");
} else {
name += "): ";
}
// add function return value
name += retType->fullName();
name += ")";
}
// xhp names are mangled so we get them back to their original definition
// @see the mangling in ScannerToken::xhpLabel
void TypeAnnotation::xhpTypeName(std::string &name) const {
// remove prefix if any
if (m_name.compare(0, sizeof("xhp_") - 1, "xhp_") == 0) {
name += std::string(m_name).replace(0, sizeof("xhp_") - 1, ":");
} else {
name += m_name;
}
// un-mangle back
Util::replaceAll(name, "__", ":");
Util::replaceAll(name, "_", "-");
}
void TypeAnnotation::tupleTypeName(std::string &name) const {
name += "(";
TypeAnnotationPtr typeEl = m_typeArgs;
while (typeEl) {
name += typeEl->fullName();
typeEl = typeEl->m_typeList;
name += ", ";
}
// replace the trailing ", " with ")"
name.replace(name.size() - 2, 2, ")");
}
void TypeAnnotation::genericTypeName(std::string &name) const {
name += m_name;
name += "<";
TypeAnnotationPtr typeEl = m_typeArgs;
while (typeEl) {
name += typeEl->fullName();
typeEl = typeEl->m_typeList;
name += ", ";
}
// replace the trailing ", " with ">"
name.replace(name.size() - 2, 2, ">");
}
void TypeAnnotation::appendToTypeList(TypeAnnotationPtr typeList) {
if (m_typeList) {
TypeAnnotationPtr current = m_typeList;
while (current->m_typeList) {
current = current->m_typeList;
}
current->m_typeList = typeList;
} else {
m_typeList = typeList;
}
}
void TypeAnnotation::outputCodeModel(CodeGenerator& cg) {
TypeAnnotationPtr typeArgsElem = m_typeArgs;
auto numTypeArgs = 0;
while (typeArgsElem != nullptr) {
numTypeArgs++;
typeArgsElem = typeArgsElem->m_typeList;
}
typeArgsElem = m_typeArgs;
auto numProps = 1;
if (m_nullable) numProps++;
if (m_soft) numProps++;
if (m_function) {
numProps++;
// Since this is a function type, the first type argument is the return type
// and no typeArguments property will be serialized unless there are at
// least two type arguments.
if (numTypeArgs > 1) numProps++;
} else {
if (numTypeArgs > 0) numProps++;
}
cg.printObjectHeader("TypeExpression", numProps);
cg.printPropertyHeader("name");
cg.printValue(m_tuple ? "tuple" : m_name);
if (m_nullable) {
cg.printPropertyHeader("isNullable");
cg.printBool(true);
}
if (m_soft) {
cg.printPropertyHeader("isSoft");
cg.printBool(true);
}
if (m_function) {
cg.printPropertyHeader("returnType");
typeArgsElem->outputCodeModel(cg);
typeArgsElem = typeArgsElem->m_typeList;
// Since we've grabbed the first element of the list as the return
// type, make sure that the logic for serializing type arguments gets
// disabled unless there is at least one more type argument.
numTypeArgs--;
}
if (numTypeArgs > 0) {
cg.printPropertyHeader("typeArguments");
cg.printf("V:9:\"HH\\Vector\":%d:{", numTypeArgs);
while (typeArgsElem != nullptr) {
typeArgsElem->outputCodeModel(cg);
typeArgsElem = typeArgsElem->m_typeList;
}
cg.printf("}");
}
cg.printObjectFooter();
}
}
| [
"sgolemon@fb.com"
] | sgolemon@fb.com |
47884bfb4ca1d013c02678a75adb9a24b49fd605 | 9614eda056137277b2da5097ceb7583cb9a42fdb | /Cluedo/room.h | 2ce431fa326f72357d6fa5ef2baeb5a429a32449 | [] | no_license | CPeacockEngineeringLTD/Cluedo | 4a6ddb58dbf80296706ccf5f7385abac471a20df | 34ce55c406c0f4c498b90b235ac87cff39405146 | refs/heads/master | 2023-06-03T12:13:34.889883 | 2021-06-26T08:37:39 | 2021-06-26T08:37:39 | 324,749,885 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 185 | h | #pragma once
#include <string>
#include <chrono>
class room{
public:
static std::wstring getContents(int a);
static void chooseMurder();
static bool checkMurder(int a);
};
| [
"clegguy@hotmail.co.uk"
] | clegguy@hotmail.co.uk |
cd15ab34b66ef0c6ac0e93d2c9184a03748da5cb | 574c0dbf05e263357b32d58fc5e2af79a845b3e0 | /Engine_Graphics/include/ComputeShader.h | 859b09dd0e96333b17de497f6eb4dfb99a53660f | [
"MIT"
] | permissive | subr3v/s-engine | 8d2d5d2063f99231c4f7b95b8137037fe6252e1d | d77b9ccd0fff3982a303f14ce809691a570f61a3 | refs/heads/master | 2021-01-10T03:04:33.928634 | 2016-04-02T14:12:29 | 2016-04-02T14:12:29 | 55,234,945 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 911 | h | #ifndef ComputeShader_h__
#define ComputeShader_h__
#include <d3d11.h>
class FGraphicsContext;
class FShaderProgramInfo;
class FComputeShader
{
public:
FComputeShader(FGraphicsContext* GraphicsContext, const FShaderProgramInfo* ComputeShaderInfo);
~FComputeShader();
void Bind(ID3D11DeviceContext* DeviceContext);
void SetShaderResources(ID3D11DeviceContext* DeviceContext, ID3D11ShaderResourceView** Resources, int ResourceCount);
void SetShaderUnorderedAccessViews(ID3D11DeviceContext* DeviceContext, ID3D11UnorderedAccessView** Uavs, int UavsCount, const UINT* InitialCounts);
void SetShaderConstantBuffers(ID3D11DeviceContext* DeviceContext, ID3D11Buffer** Buffers, int BuffersCount);
void Execute(ID3D11DeviceContext* DeviceContext, int ThreadGroupCountX, int ThreadGroupCountY, int ThreadGroupCountZ);
private:
ID3D11ComputeShader* ComputeShader = nullptr;
};
#endif // ComputeShader_h__
| [
"subr3v@gmail.com"
] | subr3v@gmail.com |
30a02e5de3fa2d8f8b3c2cbd43ea7f6019403106 | 424601113e009bf6efecc9ef33b964eb89ad4cea | /mediadevice/qffmpegencoder.cpp | 1ad40910d4dc5befc1343068d6649abee67fa3fe | [] | no_license | robby31/multimedia | b34ad589559b2124c460e7bfb057f5ad8c74ecf5 | ba4c9c51cd0e347e703c3dcfeafc01f9aa770fdd | refs/heads/master | 2021-06-07T07:28:28.635996 | 2020-02-15T07:42:12 | 2020-02-15T07:42:12 | 96,641,230 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,351 | cpp | #include "qffmpegencoder.h"
QFfmpegEncoder::QFfmpegEncoder(QObject *parent):
QFfmpegCodec(parent)
{
}
QFfmpegEncoder::~QFfmpegEncoder()
{
_close();
}
void QFfmpegEncoder::close()
{
_close();
}
void QFfmpegEncoder::_close()
{
#if !defined(QT_NO_DEBUG_OUTPUT)
if (codecCtx() != Q_NULLPTR)
qDebug() << format() << codecCtx()->frame_number << "frames encoded.";
#endif
if (!m_encodedPkt.isEmpty())
qWarning() << m_encodedPkt.size() << "frames not encoded remains in encoder" << format();
clear();
QFfmpegCodec::close();
}
bool QFfmpegEncoder::encodeFrame(QFfmpegFrame *frame)
{
bool result = false;
if (isValid())
{
AVPacket *pkt = Q_NULLPTR;
pkt = av_packet_alloc();
if (!pkt)
{
qCritical() << "Could not allocate packet";
}
else
{
int ret;
av_init_packet(pkt);
/* send the frame to the encoder */
if (frame != Q_NULLPTR && frame->ptr() != Q_NULLPTR)
ret = avcodec_send_frame(codecCtx(), frame->ptr());
else
ret = avcodec_send_frame(codecCtx(), Q_NULLPTR); // flush encoder
if (ret == AVERROR_EOF)
{
// EOF reached
}
else if (ret < 0)
{
qCritical() << "Error sending a frame for encoding";
}
else
{
while (ret >= 0)
{
ret = avcodec_receive_packet(codecCtx(), pkt);
if (ret == 0)
{
m_encodedPkt << pkt;
pkt = av_packet_alloc();
av_init_packet(pkt);
}
else if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
{
result = true;
}
else if (ret < 0)
{
qCritical() << "Error during encoding";
}
av_packet_unref(pkt);
}
}
}
av_packet_free(&pkt);
}
else
{
qCritical() << "codec is invalid for encoding.";
}
return result;
}
qint64 QFfmpegEncoder::encodedPktAvailable() const
{
return m_encodedPkt.size();
}
AVPacket *QFfmpegEncoder::takeEncodedPkt()
{
if (!m_encodedPkt.isEmpty())
return m_encodedPkt.takeFirst();
return Q_NULLPTR;
}
QByteArray QFfmpegEncoder::getRawData()
{
QByteArray res;
foreach (AVPacket *pkt, m_encodedPkt)
{
if (pkt != Q_NULLPTR)
res.append(QByteArray::fromRawData(reinterpret_cast<char *>(pkt->data), pkt->size));
}
return res;
}
bool QFfmpegEncoder::setSampleFmt(const AVSampleFormat &format)
{
if (codecCtx())
{
codecCtx()->sample_fmt = format;
return true;
}
return false;
}
bool QFfmpegEncoder::setPixelFormat(const AVPixelFormat &format)
{
if (codecCtx())
{
codecCtx()->pix_fmt = format;
return true;
}
return false;
}
bool QFfmpegEncoder::setChannelLayout(const uint64_t &layout)
{
if (codecCtx())
{
codecCtx()->channel_layout = layout;
codecCtx()->channels = av_get_channel_layout_nb_channels(layout);
return true;
}
return false;
}
bool QFfmpegEncoder::setChannelCount(const int &nb)
{
if (codecCtx())
{
codecCtx()->channel_layout = static_cast<uint64_t>(av_get_default_channel_layout(nb));
codecCtx()->channels = nb;
return true;
}
return false;
}
bool QFfmpegEncoder::setSampleRate(const int &rate) const
{
if (codecCtx())
{
codecCtx()->sample_rate = rate;
return true;
}
return false;
}
bool QFfmpegEncoder::setBitRate(const qint64 &bitrate)
{
if (codecCtx())
{
codecCtx()->bit_rate = bitrate;
return true;
}
return false;
}
qint64 QFfmpegEncoder::nextPts() const
{
return next_pts;
}
void QFfmpegEncoder::incrNextPts(const int &duration)
{
next_pts += duration;
}
void QFfmpegEncoder::clear()
{
while (!m_encodedPkt.isEmpty())
{
AVPacket *pkt = m_encodedPkt.takeFirst();
av_packet_free(&pkt);
}
}
| [
"guillaume.himbert@gmail.com"
] | guillaume.himbert@gmail.com |
3a1739865ce70ba4d7bcfe87380648ad24a6adb8 | 4060dfd3ee62b32ecf287944ebbc38ef889f5fca | /Dynamic Programming/392. Is Subsequence.cpp | 9b7a4a57567c9ad3bfef27a1fad38e49ed3153b9 | [] | no_license | Sensrdt/Leet-Code-Sol | e5cd6b25a6aa9628f1d311d02ad03c4a435fe47c | 893d0614849b2416d920929e0ee1156b6218c6b9 | refs/heads/master | 2020-07-01T15:12:07.546062 | 2020-06-07T13:34:55 | 2020-06-07T13:34:55 | 201,206,677 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 447 | cpp | class Solution
{
public:
bool isSubsequence(string s, string t)
{
int n = s.length(), m = t.length();
int i = 0, j = 0;
while (i < n && j < m)
{
if (s[i] == t[j])
{
i++;
j++;
}
else
j++;
}
if (i == n)
return true;
else
return false;
}
}; | [
"stsdutta2@gmail.com"
] | stsdutta2@gmail.com |
5b5d13f0c89a783af659e096a9c2448a3894259e | 7b80d8166c41e164db46403cf10c2e5300238dd6 | /APP/COMMON/InvBusinessFunc.cpp | d93d0955fda11c65e705f6ba21af4ca7bd654d60 | [] | no_license | duanwenhuiIMAU/SKJ_FWSK_1.0000 | d7a3862d1f02d1a62a6726fd7efc3d348c666383 | 004d47182ebca13428d78500a0425ada195c5e7b | refs/heads/master | 2020-04-27T13:39:35.511980 | 2015-09-16T09:45:36 | 2015-09-16T09:46:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,910 | cpp |
#include "InvBusinessFunc.h"
#include "commonFunc.h"
#include "YWXML_FPDR.h"
#include "YWXML_BSPFPFF.h"
#include "YWXML_BSPFPSH.h"
#include "YWXML_FJTH.h"
#include "YWXML_GPXXXP.h"
#include "YWXML_GPXXXPJS.h"
#include "YWXML_BSPFPCX.h"
#include "BusinessBase.h"
#include "LOGCTRL.h"
//#define NO_POS_DEBUG
#include "pos_debug.h"
CInvBusinessFunc::CInvBusinessFunc()
{
}
CInvBusinessFunc::~CInvBusinessFunc()
{
}
INT32 CInvBusinessFunc::BSPFPCXPro(CYWXML_GY &ywxml_gy, UINT32 &InvCount, CInvVol *pInvVol, string &strErr)
{
INT32 ret = SUCCESS;
ret = g_pBusBase->BSPFPCX_Business(ywxml_gy, InvCount, pInvVol, strErr);
return g_pBusBase->ErrParse(ret, strErr);;
}
INT32 CInvBusinessFunc::InvReadIn(CYWXML_GY &ywxml_gy, UINT8 strJzlx, string &strErr)
{
INT32 ret = SUCCESS;
ret = g_pBusBase->FPDR_Business(ywxml_gy, strJzlx, strErr);
return g_pBusBase->ErrParse(ret, strErr);;
}
INT32 CInvBusinessFunc::ZJInvDistribute(CYWXML_GY &ywxml_gy, CInvVol *pInvVol, UINT8 strJzlx, string &strErr)
{
INT32 ret = SUCCESS;
ret = g_pBusBase->BSPFPFF_Business(ywxml_gy, strJzlx, pInvVol, strErr);
return g_pBusBase->ErrParse(ret, strErr);;
}
INT32 CInvBusinessFunc::ZJInvRecover(CYWXML_GY &ywxml_gy, CInvVol *pInvVol, UINT8 strJzlx, string &strErr)
{
INT32 ret = SUCCESS;
ret = g_pBusBase->BSPFPSH_Business(ywxml_gy, strJzlx, pInvVol, strErr);
return g_pBusBase->ErrParse(ret, strErr);;
}
INT32 CInvBusinessFunc::FJInvReturn(CYWXML_GY &ywxml_gy, UINT8 strJzlx, string &strErr)
{
INT32 ret = SUCCESS;
ret = g_pBusBase->FJTH_Business(ywxml_gy, strJzlx, strErr);
return g_pBusBase->ErrParse(ret, strErr);;
}
INT32 CInvBusinessFunc::TJXXCXPro(CYWXML_GY &ywxml_gy, INT32 &monthcount, CTjxxhz *pTjxxhz, string &strErr)
{
INT32 ret = SUCCESS;
ret = g_pBusBase->TJXXCX_Business(ywxml_gy, monthcount, pTjxxhz, strErr);
return g_pBusBase->ErrParse(ret, strErr);
}
INT32 CInvBusinessFunc::WLLQFPPro(CYWXML_GY &ywxml_gy, CInvVol *pInvVol, string &strErr)
{
INT32 ret = SUCCESS;
UINT8 xxlx = SKSBQTYXXCX_XXLX_WLLQFPJGQR;
string sksbxx("");
ret = g_pBusBase->SKSBQTYXXCX_Business(ywxml_gy, xxlx, sksbxx, strErr);
ret = g_pBusBase->ErrParse(ret, strErr);
if(ret != SUCCESS)
{
return FAILURE;
}
if(sksbxx.length() > 0)
{
DBG_PRINT(("here"));
ret = g_pBusBase->WLLQFPJGQR_Business(ywxml_gy, pInvVol, sksbxx, strErr);
ret = g_pBusBase->ErrParse(ret, strErr);
if(ret != SUCCESS)
{
return FAILURE;
}
ret = g_pBusBase->GPXXXPJS_Business(ywxml_gy, pInvVol->m_fpjjsmw, strErr);
ret = g_pBusBase->ErrParse(ret, strErr);
if(ret != SUCCESS)
{
return FAILURE;
}
}
else
{
DBG_PRINT(("here"));
xxlx = SKSBQTYXXCX_XXLX_WLLQFP;
ret = g_pBusBase->SKSBQTYXXCX_Business(ywxml_gy, xxlx, sksbxx, strErr);
ret = g_pBusBase->ErrParse(ret, strErr);
if(ret != SUCCESS)
{
return FAILURE;
}
ret = g_pBusBase->WLLQFP_Business(ywxml_gy, pInvVol, sksbxx, strErr);
ret = g_pBusBase->ErrParse(ret, strErr);
if(ret != SUCCESS)
{
return FAILURE;
}
ret = g_pBusBase->GPXXXP_Business(ywxml_gy, pInvVol->m_fpjmw, strErr);
ret = g_pBusBase->ErrParse(ret, strErr);
if(ret != SUCCESS)
{
return FAILURE;
}
CommonSleep(1000);
ret = WLLQFPJGQRPro(ywxml_gy, pInvVol, strErr);
}
return ret;
}
INT32 CInvBusinessFunc::WLLQFPJGQRPro(CYWXML_GY &ywxml_gy, CInvVol *pInvVol, string &strErr)
{
INT32 ret = SUCCESS;
UINT8 xxlx = SKSBQTYXXCX_XXLX_WLLQFPJGQR;
string sksbxx("");
ret = g_pBusBase->SKSBQTYXXCX_Business(ywxml_gy, xxlx, sksbxx, strErr);
ret = g_pBusBase->ErrParse(ret, strErr);
if(ret != SUCCESS)
{
return FAILURE;
}
ret = g_pBusBase->WLLQFPJGQR_Business(ywxml_gy, pInvVol, sksbxx, strErr);
ret = g_pBusBase->ErrParse(ret, strErr);
if(ret != SUCCESS)
{
return FAILURE;
}
ret = g_pBusBase->GPXXXPJS_Business(ywxml_gy, pInvVol->m_fpjjsmw, strErr);
ret = g_pBusBase->ErrParse(ret, strErr);
return ret;
}
| [
"zhangchaoyang@aisino.com"
] | zhangchaoyang@aisino.com |
86923448d578c330e3c6763d488d5bfb8dfe952b | 8694f8a9ca03012ac173ed4e30025fe815ed9581 | /Chapter7/quick_sort.cpp | fff7b89c3759b43f032d3791422222317a92d7f5 | [] | no_license | kenyangzq/Introduction_to_Algorithms | 2dff7aa8ac8cef8966d2b5d027fb162e76f7fd4d | a1764fef7093e8bd7159b28592fa4a1cd8d99abf | refs/heads/master | 2020-03-08T17:17:14.089603 | 2018-04-15T20:30:48 | 2018-04-15T20:30:48 | 128,264,855 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 812 | cpp |
#include <algorithm>
#include <iostream>
#include <vector>
#include <stdexcept>
#include <cmath>
int partition(std::vector<int> & vec, int l, int r) {
int x = vec[r];
int i = l;
for (int j = l; j < r; j++) {
if (vec[j] <= x)
std::swap(vec[i++], vec[j]);
}
std::swap(vec[i], vec[r]);
return i;
}
void quick_sort_help(std::vector<int> & vec, int l, int r) {
if (l < r) {
int q = partition(vec, l, r);
quick_sort_help(vec,l,q-1);
quick_sort_help(vec,q+1,r);
}
}
void quick_sort(std::vector<int> & vec) {
quick_sort_help(vec, 0, vec.size()-1);
}
int main() {
std::ostream_iterator<int> iter(std::cout, " ");
int arr[12] = {3,2,1,3,4,15,32,6,3,31,34,8};
std::vector<int> tmp(arr, arr+12);
quick_sort(tmp);
std::copy(tmp.begin(),tmp.end(), iter);
std::cout << std::endl;
}
| [
"ziqi.yang@vanderbilt.edu"
] | ziqi.yang@vanderbilt.edu |
ba1170d9c00eaf7450e27fbea157c8e4cb4fd402 | f5bfa81cf4a06d449bd1a7e33587ef84d6b1c9a3 | /source/DirectionalLight.cpp | f3d159b10862ee5d7f10aada7baaca59344260dc | [] | no_license | kevanvanderstichelen/Rasterizer | 8a23b6cb9ac50b3105ddca261447f0bdcb1ae5ff | 53a249abe25400c6c840e55b4bb37080f397733f | refs/heads/main | 2022-12-28T04:11:55.830748 | 2020-10-10T15:19:27 | 2020-10-10T15:19:27 | 302,929,640 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 576 | cpp | #include "DirectionalLight.h"
DirectionalLight::DirectionalLight(const FVector3& normal, const RGBColor& color, float intensity)
:m_Direction{ GetNormalized(normal) }
,m_Color{ color }
,m_Intensity{ intensity }
{
}
const RGBColor DirectionalLight::CalculateShading(const FVector3& normal, const RGBColor& diffuse) const
{
const float observedArea = Dot(-normal, m_Direction);
if (observedArea < 0.f) return RGBColor{ 0, 0, 0 };
return (m_Color * m_Intensity * diffuse * observedArea);
}
const FVector3& DirectionalLight::GetDirection() const
{
return m_Direction;
}
| [
"52068354+kevanvanderstichelen@users.noreply.github.com"
] | 52068354+kevanvanderstichelen@users.noreply.github.com |
ff5158eb6e56886f120dadafb3b99ce51bfda92e | b25898993f8646c8517d93662cbe9ae33cf51095 | /o2xfs-xfs3/src/o2xfs-xfs310-test.dll/cpp/cim/PowerSaveControl3_10.cpp | 219514a453dc3b7f8feeb95a101a8e413fc5e0ed | [
"BSD-2-Clause"
] | permissive | dotfeng/O2Xfs | 5e4a16cd11305d4476ce28fb15887d6393ca90cd | 27e9b09fc8f5a8f4b0c6d9a5d1746cadb61b121d | refs/heads/master | 2021-01-24T20:25:10.044447 | 2017-03-08T22:07:02 | 2017-03-08T22:07:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,871 | cpp | /*
* Copyright (c) 2017, Andreas Fagschlunger. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "cim/at_o2xfs_xfs_cim_v3_10_PowerSaveControl3_10Test.h"
#include <Windows.h>
#include <XFSCIM.H>
#include "at.o2xfs.win32.h"
WFSCIMPOWERSAVECONTROL PowerSaveControl;
JNIEXPORT jobject JNICALL Java_at_o2xfs_xfs_cim_v3_110_PowerSaveControl3_110Test_buildPowerSaveControl3_110(JNIEnv *env, jobject obj) {
PowerSaveControl.usMaxPowerSaveRecoveryTime = 1234;
return NewBuffer(env, &PowerSaveControl, sizeof(WFSCIMPOWERSAVECONTROL));
} | [
"github@fagschlunger.co.at"
] | github@fagschlunger.co.at |
672e57bf4a0dbe3f343eeaf474cd66345ba5b041 | 144d2d44e3fa9c561d069009276ae76db8ff8b1c | /Examples/Features/LogisticContrastEnhancementImageFilter/Main.cpp | 89ec509d0ffc8e9830e6d33cb429d5ee4350090d | [] | no_license | cancan101/ITK | f6f51d6cec93ed907886b3dcb477b65261cd8d6d | d8c89499eedeb228f5b127e11055bc245deb891a | refs/heads/master | 2021-08-08T04:23:53.232248 | 2017-10-06T12:56:44 | 2017-10-06T12:56:44 | 108,953,488 | 1 | 0 | null | 2017-10-31T06:15:57 | 2017-10-31T06:15:57 | null | UTF-8 | C++ | false | false | 2,018 | cpp | #include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkLogisticContrastEnhancementImageFilter.h"
int main(int argc, char* argv[])
{
if ( argc < 4 )
{
std::cerr << "Missing parameters. " << std::endl;
std::cerr << "Usage: " << std::endl;
std::cerr << argv[0]
<< " inputImageFileName outputImageFileName [flipObject:(1 is true or 0 is false)] thrMethod "
<< std::endl;
return -1;
}
const unsigned int Dimension = 3;
typedef float PixelType;
typedef itk::Image<PixelType, Dimension> InputImageType;
typedef itk::Image<PixelType, Dimension> OutputImageType;
typedef itk::ImageFileReader<InputImageType> ReaderType;
typedef itk::ImageFileWriter<OutputImageType> WriterType;
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName(argv[1]);
try
{
reader->Update();
}
catch ( itk::ExceptionObject &err)
{
std::cerr << "ExceptionObject caught !" << std::endl;
std::cerr << err << std::endl;
return -1;
}
typedef itk::LogisticContrastEnhancementImageFilter<InputImageType, OutputImageType> FilterType;
FilterType::Pointer filter = FilterType::New();
filter->SetInput(reader->GetOutput());
filter->SetNumberOfBins(128);
if (atof(argv[3])==1) {
filter->FlipObjectAreaOn();
}
filter->SetThresholdMethod(atoi(argv[4]));
filter->Update();
std::cout<<"Alpha: "<<filter->GetAlpha()<<std::endl;
std::cout<<"Beta: "<<filter->GetBeta()<<std::endl;
typename WriterType::Pointer writer = WriterType::New();
writer->SetFileName(argv[2]);
writer->SetInput(filter->GetOutput());
try
{
writer->Update();
}
catch ( itk::ExceptionObject &err)
{
std::cerr << "ExceptionObject caught !" << std::endl;
std::cerr << err << std::endl;
return -1;
}
return EXIT_SUCCESS;
}
| [
"acsenrafilho@gmail.com"
] | acsenrafilho@gmail.com |
8b216672a7fd7fc582af19186085131e3308e1a3 | d63e9b801d9b1e5b959310db757c7e13fa51c5d7 | /C++/Queue_Wt/Queue_Wt/Queue_Wt.hpp | a9c8cc510b030da2de4098e1e6beb8746c47350e | [] | no_license | BillMark98/xcode | 5a5a6257d02bd15f64e6b2eba92beee7ae602970 | 9da7a1632b0448fde9cf0e02bed3e25d32c1cc35 | refs/heads/master | 2020-04-02T10:17:18.161830 | 2018-10-23T13:33:55 | 2018-10-23T13:33:55 | 154,330,027 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,249 | hpp | //
// Queue_Wt.hpp
// Queue_Wt
//
// Created by Bill on 10/31/17.
// Copyright © 2017 Bill. All rights reserved.
//
#ifndef Queue_Wt_hpp
#define Queue_Wt_hpp
#include <iostream>
#include <string>
#include <iomanip>
using std::cout;
using std::cin;
using std::endl;
using std::setw;
using std::string;
template < typename T>
class Queue
{
class Node
{
public:
T item;
Node * next;
Node(const T & it): item(it),next(nullptr) {}
};
private:
/*struct Node
{
T item;
Node * next;
};*/
enum {Q_SIZE = 10};
Node * front;
Node * rear;
int items;
const int qsize;
Queue(const Queue & q) : qsize(0),items(0) {}
Queue & operator[](const Queue & q) {return *this;}
public:
Queue(int qs = Q_SIZE) : qsize(qs){ front = rear = nullptr; items = 0;}
~Queue();
bool isempty() const {return items == 0;}
bool isfull() const { return items == qsize;}
int queuecount() const {return items;}
bool enqueue(const T & item);
bool dequeue(T & item);
};
template <typename T>
Queue<T>::~Queue()
{
Node * temp = front;
while(temp != nullptr)
{
temp = front;
front = front -> next;
delete temp;
}
}
template <typename T>
bool Queue<T>::enqueue(const T & item)
{
if(isfull())
return false;
/*Node * temp = new Node;
temp -> item = item;
temp -> next = nullptr;*/
Node * temp = new Node(item);
if(rear == nullptr)
{
front = rear = temp;
//front -> next = rear -> next = nullptr;
}
else
{
rear -> next = temp;
}
items ++;
rear = temp;
return true;
}
template <typename T>
bool Queue<T>::dequeue(T & item)
{
if(isempty())
return false;
Node * temp = front;
item = front -> item;
front = front -> next;
delete temp;
items --;
if(front == nullptr)
rear = nullptr;
return true;
}
class Worker
{
private:
string fullname;
long id;
public:
Worker(): fullname("no one"),id(0L) {}
Worker(const string & s, long n) : fullname(s),id(n) {}
~Worker() {}
void Set();
void Show() const;
};
#endif /* Queue_Wt_hpp */
| [
"panwei.hu@rwth-aachen.de"
] | panwei.hu@rwth-aachen.de |
31664c5453e631e0b1d84d0451e1451eebd91d6a | 09029c871c08379f427ce472000673411bd6b21c | /lib/libnet/nstream_proactor.cpp | d63773e0476f2a4250e6441b4ed0d70eeaa44650 | [] | no_license | sbunce/p2p | 0c1a9fb8259fc0d60623c22f5950bed9fad234e2 | e5e97714de193295b88b2610080acebd9be18252 | refs/heads/master | 2021-05-02T07:37:54.674279 | 2018-11-19T05:29:30 | 2018-11-19T05:29:30 | 17,999,320 | 2 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 15,103 | cpp | #include <net/nstream_proactor.hpp>
//BEGIN events
net::nstream_proactor::conn_info::conn_info(
const boost::uint64_t conn_ID_in,
const dir_t dir_in,
const tran_t tran_in,
const boost::optional<endpoint> & local_ep_in,
const boost::optional<endpoint> & remote_ep_in
):
conn_ID(conn_ID_in),
dir(dir_in),
tran(tran_in),
local_ep(local_ep_in),
remote_ep(remote_ep_in)
{
}
net::nstream_proactor::connect_event::connect_event(
const boost::shared_ptr<const conn_info> & info_in
):
info(info_in)
{
}
net::nstream_proactor::disconnect_event::disconnect_event(
const boost::shared_ptr<const conn_info> & info_in,
const error_t error_in
):
info(info_in),
error(error_in)
{
}
net::nstream_proactor::recv_event::recv_event(
const boost::shared_ptr<const conn_info> & info_in,
const buffer & buf_in
):
info(info_in),
buf(buf_in)
{
}
net::nstream_proactor::send_event::send_event(
const boost::shared_ptr<const conn_info> & info_in,
const unsigned last_send_in,
const unsigned send_buf_size_in
):
info(info_in),
last_send(last_send_in),
send_buf_size(send_buf_size_in)
{
}
//END events
//BEGIN conn
net::nstream_proactor::conn::~conn()
{
}
void net::nstream_proactor::conn::schedule_send(const buffer & buf,
const bool close_on_empty)
{
}
bool net::nstream_proactor::conn::timed_out()
{
return false;
}
void net::nstream_proactor::conn::write()
{
}
//END conn
//BEGIN conn_container
net::nstream_proactor::conn_container::conn_container():
unused_conn_ID(0),
last_time(std::time(NULL)),
incoming_conn_limit(0),
outgoing_conn_limit(0),
incoming_conns(0),
outgoing_conns(0)
{
}
void net::nstream_proactor::conn_container::add(const boost::shared_ptr<conn> & C)
{
Socket.insert(std::make_pair(C->socket(), C));
ID.insert(std::make_pair(C->info()->conn_ID, C));
}
void net::nstream_proactor::conn_container::check_timeouts()
{
if(last_time != std::time(NULL)){
last_time = std::time(NULL);
std::list<boost::uint64_t> timed_out;
for(std::map<boost::uint64_t, boost::shared_ptr<conn> >::iterator
it_cur = ID.begin(), it_end = ID.end(); it_cur != it_end; ++it_cur)
{
if(it_cur->second->timed_out()){
timed_out.push_back(it_cur->second->info()->conn_ID);
it_cur->second->set_error(timeout_error);
}
}
for(std::list<boost::uint64_t>::iterator it_cur = timed_out.begin(),
it_end = timed_out.end(); it_cur != it_end; ++it_cur)
{
remove(*it_cur);
}
}
}
boost::uint64_t net::nstream_proactor::conn_container::new_conn_ID()
{
return unused_conn_ID++;
}
std::set<int> net::nstream_proactor::conn_container::read_set()
{
return _read_set;
}
void net::nstream_proactor::conn_container::monitor_read(const int socket_FD)
{
_read_set.insert(socket_FD);
}
void net::nstream_proactor::conn_container::monitor_write(const int socket_FD)
{
_write_set.insert(socket_FD);
}
void net::nstream_proactor::conn_container::perform_reads(
const std::set<int> & read_set_in)
{
for(std::set<int>::const_iterator it_cur = read_set_in.begin(),
it_end = read_set_in.end(); it_cur != it_end; ++it_cur)
{
std::map<int, boost::shared_ptr<conn> >::iterator
it = Socket.find(*it_cur);
if(it != Socket.end()){
it->second->read();
}
}
}
void net::nstream_proactor::conn_container::perform_writes(
const std::set<int> & write_set_in)
{
for(std::set<int>::const_iterator it_cur = write_set_in.begin(),
it_end = write_set_in.end(); it_cur != it_end; ++it_cur)
{
std::map<int, boost::shared_ptr<conn> >::iterator
it = Socket.find(*it_cur);
if(it != Socket.end()){
it->second->write();
}
}
}
void net::nstream_proactor::conn_container::remove(const boost::uint64_t conn_ID)
{
std::map<boost::uint64_t, boost::shared_ptr<conn> >::iterator
it = ID.find(conn_ID);
if(it != ID.end()){
_read_set.erase(it->second->socket());
_write_set.erase(it->second->socket());
Socket.erase(it->second->socket());
ID.erase(it->second->info()->conn_ID);
}
}
void net::nstream_proactor::conn_container::schedule_send(
const boost::uint64_t conn_ID, const buffer & buf, const bool close_on_empty)
{
std::map<boost::uint64_t, boost::shared_ptr<conn> >::iterator
it = ID.find(conn_ID);
if(it != ID.end()){
it->second->schedule_send(buf, close_on_empty);
}
}
void net::nstream_proactor::conn_container::unmonitor_read(const int socket_FD)
{
_read_set.erase(socket_FD);
}
void net::nstream_proactor::conn_container::unmonitor_write(const int socket_FD)
{
_write_set.erase(socket_FD);
}
std::set<int> net::nstream_proactor::conn_container::write_set()
{
return _write_set;
}
//END conn_container
//BEGIN conn_nstream
net::nstream_proactor::conn_nstream::conn_nstream(
dispatcher & Dispatcher_in,
conn_container & Conn_Container_in,
const endpoint & ep
):
Dispatcher(Dispatcher_in),
Conn_Container(Conn_Container_in),
N(new nstream()),
close_on_empty(false),
half_open(true),
timeout(std::time(NULL) + connect_timeout),
error(no_error)
{
N->open_async(ep);
socket_FD = N->socket();
_info.reset(new conn_info(
Conn_Container.new_conn_ID(),
outgoing_dir,
nstream_tran,
N->local_ep(),
N->remote_ep()
));
Conn_Container.monitor_write(socket_FD);
}
net::nstream_proactor::conn_nstream::conn_nstream(
dispatcher & Dispatcher_in,
conn_container & Conn_Container_in,
boost::shared_ptr<nstream> N_in
):
Dispatcher(Dispatcher_in),
Conn_Container(Conn_Container_in),
N(N_in),
close_on_empty(false),
half_open(false),
timeout(std::time(NULL) + idle_timeout),
error(no_error)
{
socket_FD = N->socket();
assert(N->is_open());
_info.reset(new conn_info(
Conn_Container.new_conn_ID(),
incoming_dir,
nstream_tran,
N->local_ep(),
N->remote_ep()
));
Dispatcher.connect(connect_event(_info));
Conn_Container.monitor_read(socket_FD);
}
net::nstream_proactor::conn_nstream::~conn_nstream()
{
Dispatcher.disconnect(disconnect_event(_info, error));
}
boost::shared_ptr<const net::nstream_proactor::conn_info>
net::nstream_proactor::conn_nstream::info()
{
return _info;
}
void net::nstream_proactor::conn_nstream::read()
{
touch();
buffer buf;
int n_bytes = N->recv(buf);
if(n_bytes <= 0){
//assume connection reset (may not be)
error = connection_reset_error;
Conn_Container.remove(_info->conn_ID);
}else{
Dispatcher.recv(recv_event(_info, buf));
}
}
void net::nstream_proactor::conn_nstream::schedule_send(const buffer & buf,
const bool close_on_empty_in)
{
if(close_on_empty_in){
close_on_empty = true;
}
send_buf.append(buf);
if(send_buf.empty() && close_on_empty){
Conn_Container.remove(_info->conn_ID);
}else{
Conn_Container.monitor_write(socket_FD);
}
}
void net::nstream_proactor::conn_nstream::set_error(const error_t error_in)
{
error = error_in;
}
int net::nstream_proactor::conn_nstream::socket()
{
return socket_FD;
}
bool net::nstream_proactor::conn_nstream::timed_out()
{
return timeout > std::time(NULL);
}
void net::nstream_proactor::conn_nstream::touch()
{
timeout = std::time(NULL) + idle_timeout;
}
void net::nstream_proactor::conn_nstream::write()
{
touch();
if(half_open){
if(N->is_open_async()){
half_open = false;
Dispatcher.connect(connect_event(_info));
//send_buf always empty after connect
Conn_Container.unmonitor_write(socket_FD);
Conn_Container.monitor_read(socket_FD);
}else{
error = connect_error;
Conn_Container.remove(_info->conn_ID);
}
}else{
int n_bytes = N->send(send_buf);
if(send_buf.empty()){
Conn_Container.unmonitor_write(socket_FD);
}
if(n_bytes <= 0){
error = connection_reset_error;
Conn_Container.remove(_info->conn_ID);
}else if(close_on_empty && send_buf.empty()){
Conn_Container.remove(_info->conn_ID);
}else{
Dispatcher.send(send_event(_info, n_bytes, send_buf.size()));
}
}
};
//END conn_nstream
//BEGIN conn_listener
net::nstream_proactor::conn_listener::conn_listener(
dispatcher & Dispatcher_in,
conn_container & Conn_Container_in,
const endpoint & ep
):
Dispatcher(Dispatcher_in),
Conn_Container(Conn_Container_in),
error(no_error)
{
Listener.open(ep);
Listener.set_non_blocking(true);
socket_FD = Listener.socket();
_info.reset(new conn_info(
Conn_Container.new_conn_ID(),
outgoing_dir,
nstream_listen_tran,
ep
));
if(Listener.is_open()){
Dispatcher.connect(connect_event(_info));
Conn_Container.monitor_read(socket_FD);
}else{
error = listen_error;
}
}
net::nstream_proactor::conn_listener::~conn_listener()
{
Dispatcher.disconnect(disconnect_event(_info, error));
}
boost::shared_ptr<const net::nstream_proactor::conn_info>
net::nstream_proactor::conn_listener::info()
{
return _info;
}
boost::optional<net::endpoint> net::nstream_proactor::conn_listener::ep()
{
return Listener.local_ep();
}
void net::nstream_proactor::conn_listener::read()
{
while(boost::shared_ptr<nstream> N = Listener.accept()){
boost::shared_ptr<conn_nstream> CN(new conn_nstream(Dispatcher,
Conn_Container, N));
Conn_Container.add(CN);
}
}
void net::nstream_proactor::conn_listener::set_error(const error_t error_in)
{
error = error_in;
}
int net::nstream_proactor::conn_listener::socket()
{
return socket_FD;
}
//END conn_listener
//BEGIN dispatcher
net::nstream_proactor::dispatcher::dispatcher(
const boost::function<void (connect_event)> & connect_call_back_in,
const boost::function<void (disconnect_event)> & disconnect_call_back_in,
const boost::function<void (recv_event)> & recv_call_back_in,
const boost::function<void (send_event)> & send_call_back_in
):
connect_call_back(connect_call_back_in),
disconnect_call_back(disconnect_call_back_in),
recv_call_back(recv_call_back_in),
send_call_back(send_call_back_in),
producer_cnt(1),
job_cnt(0)
{
for(unsigned x=0; x<threads; ++x){
workers.create_thread(boost::bind(&dispatcher::dispatch, this));
}
}
net::nstream_proactor::dispatcher::~dispatcher()
{
join();
workers.interrupt_all();
workers.join_all();
}
void net::nstream_proactor::dispatcher::connect(const connect_event & CE)
{
boost::mutex::scoped_lock lock(mutex);
while(Job.size() >= max_buf){
consumer_cond.wait(mutex);
}
boost::function<void ()> func = boost::bind(connect_call_back, CE);
Job.push_back(std::make_pair(CE.info->conn_ID, func));
++producer_cnt;
++job_cnt;
producer_cond.notify_one();
}
void net::nstream_proactor::dispatcher::disconnect(const disconnect_event & DE)
{
boost::mutex::scoped_lock lock(mutex);
while(Job.size() >= max_buf){
consumer_cond.wait(mutex);
}
boost::function<void ()> func = boost::bind(disconnect_call_back, DE);
Job.push_back(std::make_pair(DE.info->conn_ID, func));
++producer_cnt;
++job_cnt;
producer_cond.notify_one();
}
void net::nstream_proactor::dispatcher::join()
{
boost::mutex::scoped_lock lock(mutex);
while(job_cnt > 0){
empty_cond.wait(mutex);
}
}
void net::nstream_proactor::dispatcher::recv(const recv_event & RE)
{
boost::mutex::scoped_lock lock(mutex);
while(Job.size() >= max_buf){
consumer_cond.wait(mutex);
}
boost::function<void ()> func = boost::bind(recv_call_back, RE);
Job.push_back(std::make_pair(RE.info->conn_ID, func));
++producer_cnt;
++job_cnt;
producer_cond.notify_one();
}
void net::nstream_proactor::dispatcher::send(const send_event & SE)
{
boost::mutex::scoped_lock lock(mutex);
while(Job.size() >= max_buf){
consumer_cond.wait(mutex);
}
boost::function<void ()> func = boost::bind(send_call_back, SE);
Job.push_back(std::make_pair(SE.info->conn_ID, func));
++producer_cnt;
++job_cnt;
producer_cond.notify_one();
}
void net::nstream_proactor::dispatcher::dispatch()
{
//when no job to run we wait until producer_cnt greater than this
boost::uint64_t wait_until = 0;
while(true){
std::pair<boost::uint64_t, boost::function<void ()> > p;
{//BEGIN lock scope
boost::mutex::scoped_lock lock(mutex);
while(Job.empty() || wait_until > producer_cnt){
producer_cond.wait(mutex);
}
for(std::list<std::pair<boost::uint64_t, boost::function<void ()> > >::iterator
it_cur = Job.begin(), it_end = Job.end(); it_cur != it_end; ++it_cur)
{
if(memoize.insert(it_cur->first).second){
p = *it_cur;
Job.erase(it_cur);
break;
}
}
if(!p.second){
//no job we can currently run, wait until a job added to check again
wait_until = producer_cnt + 1;
continue;
}
}//END lock scope
p.second();
{//BEGIN lock scope
boost::mutex::scoped_lock lock(mutex);
memoize.erase(p.first);
--job_cnt;
if(job_cnt == 0){
empty_cond.notify_all();
}
}//END lock scope
consumer_cond.notify_one();
}
}
//END dispatcher
net::nstream_proactor::nstream_proactor(
const boost::function<void (connect_event)> & connect_call_back_in,
const boost::function<void (disconnect_event)> & disconnect_call_back_in,
const boost::function<void (recv_event)> & recv_call_back_in,
const boost::function<void (send_event)> & send_call_back_in
):
Dispatcher(
connect_call_back_in,
disconnect_call_back_in,
recv_call_back_in,
send_call_back_in
),
Internal_TP(1, 1024)
{
Internal_TP.enqueue(boost::bind(&nstream_proactor::main_loop, this));
}
void net::nstream_proactor::connect(const endpoint & ep)
{
Internal_TP.enqueue(boost::bind(&nstream_proactor::connect_relay, this, ep));
Select.interrupt();
}
void net::nstream_proactor::connect_relay(const endpoint & ep)
{
boost::shared_ptr<conn_nstream> CL(new conn_nstream(Dispatcher,
Conn_Container, ep));
if(CL->socket() != -1){
Conn_Container.add(CL);
}
}
void net::nstream_proactor::disconnect(const boost::uint64_t conn_ID)
{
Internal_TP.enqueue(boost::bind(&nstream_proactor::disconnect_relay, this, conn_ID));
Select.interrupt();
}
void net::nstream_proactor::disconnect_relay(const boost::uint64_t conn_ID)
{
Conn_Container.remove(conn_ID);
}
channel::future<boost::optional<net::endpoint> > net::nstream_proactor::listen(
const endpoint & ep)
{
channel::promise<boost::optional<net::endpoint> > promise;
Internal_TP.enqueue(boost::bind(&nstream_proactor::listen_relay, this, ep, promise));
Select.interrupt();
return promise.get_future();
}
void net::nstream_proactor::listen_relay(const endpoint ep,
channel::promise<boost::optional<net::endpoint> > promise)
{
boost::shared_ptr<conn_listener> CL(new conn_listener(Dispatcher,
Conn_Container, ep));
if(CL->socket() != -1){
Conn_Container.add(CL);
}
promise = CL->ep();
}
void net::nstream_proactor::main_loop()
{
std::set<int> read_set = Conn_Container.read_set();
std::set<int> write_set = Conn_Container.write_set();
Select(read_set, write_set, 1000);
Conn_Container.perform_reads(read_set);
Conn_Container.perform_writes(write_set);
Conn_Container.check_timeouts();
Internal_TP.enqueue(boost::bind(&nstream_proactor::main_loop, this));
}
void net::nstream_proactor::send(const boost::uint64_t conn_ID,
const buffer & buf, const bool close_on_empty)
{
Internal_TP.enqueue(boost::bind(&nstream_proactor::send_relay, this, conn_ID,
buf, close_on_empty));
Select.interrupt();
}
void net::nstream_proactor::send_relay(const boost::uint64_t conn_ID,
const buffer buf, const bool close_on_empty)
{
Conn_Container.schedule_send(conn_ID, buf, close_on_empty);
}
| [
"seth@seth.dnsdojo.net"
] | seth@seth.dnsdojo.net |
ef0de11f5dcff3f6ccb028dbcf9b1510c027b9a0 | 3da18f95e457f3ac8c41c468cd7271ba9717bb19 | /03.sdl_MoveImage/app/simplesdl.cpp | f1943482165743e78f9b1be4097ed5ac7cba401b | [] | no_license | Falmouth-Games-Academy/GAM340-SDL | f61cfb9fe3d42f8957a1b972c5b5630c3721bfc8 | f9dc8c545b38536d1858276fe6720223517fdb5f | refs/heads/master | 2020-08-11T21:28:10.741500 | 2019-10-12T10:55:22 | 2019-10-12T10:55:22 | 214,630,576 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,183 | cpp | #include <SDL.h>
#include <SDL_image.h>
#include <stdlib.h>
#include <stdio.h>
#include <windows.h>
#undef main
#include <stdlib.h> //rand()
#pragma comment(lib, "SDL2main.lib")
#pragma comment(lib, "SDL2.lib")
#pragma comment(lib, "SDL2_image.lib")
SDL_Window *window = NULL;
SDL_Renderer *renderer = NULL;
int main(int argc, char *argv[])
{
//Initialise IMG system, this allows us to load PNG files
int imgFlags = IMG_INIT_PNG;
IMG_Init(imgFlags);
//Initialise window & renderer
window = NULL;
renderer = NULL;
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS) != 0)
{
SDL_Log("Failed to initialize SDL: %s", SDL_GetError());
return false;
}
//create a window that is 800x600 pixels
window = SDL_CreateWindow("title", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 800, 600, SDL_WINDOW_OPENGL);
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
//load a bitmap using the IMG library
SDL_Surface* srcImage = IMG_Load("resources/ball.png");
if (srcImage == NULL)
{
SDL_Log("SDL_Surface: can't load image\n");
goto quit;
}
SDL_Texture* ballTexture;
//convert the
ballTexture = SDL_CreateTextureFromSurface(renderer, srcImage);
if (ballTexture == NULL)
{
SDL_Log("SDL_Texture: can't create texture\n");
goto quit;
}
Uint32 lastElapsedTime=0, fpsTimer=0;
Uint32 elaspedTime = 0;
Uint32 fpsTime = 0;
SDL_Event event;
bool quitting = false;
signed int ball_xvel = 0;
signed int ball_yvel = 0;
signed int ballX = 800/2;
signed int ballY = 600/2;
//The main application loop
//This uses SDL_GetTicks() to record elapsed time and pause the application with Sleep to keep it running at 60fps rather than thousands of fps
while (!quitting)
{
fpsTime = SDL_GetTicks() - lastElapsedTime;
lastElapsedTime = SDL_GetTicks();
//Clear the screen before we draw to it
//https://wiki.libsdl.org/SDL_RenderClear
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
SDL_RenderClear(renderer);
// SDL uses events to communicate with the application
// In this instance, the app is just responding to SDL_QUIT messages which occur when the application is closed
// to close the app down, either press the X icon on the window or get you program to generation an SDL_QUIT event internally
while (SDL_PollEvent(&event))
{
switch(event.type)
{
case SDL_QUIT:
{
quitting = true;
}
break;
/* Look for a keypress */
//https://www.libsdl.org/release/SDL-1.2.15/docs/html/guideinputkeyboard.html
case SDL_KEYDOWN:
{
switch (event.key.keysym.sym)
{
case SDLK_LEFT:
ball_xvel = -1;
break;
case SDLK_RIGHT:
ball_xvel = 1;
break;
case SDLK_UP:
ball_yvel = -1;
break;
case SDLK_DOWN:
ball_yvel = 1;
break;
default:
break;
}
break;
}
case SDL_KEYUP:
{
switch (event.key.keysym.sym)
{
case SDLK_LEFT:
if (ball_xvel < 0)
ball_xvel = 0;
break;
case SDLK_RIGHT:
if (ball_xvel > 0)
ball_xvel = 0;
break;
case SDLK_UP:
if (ball_yvel < 0)
ball_yvel = 0;
break;
case SDLK_DOWN:
if (ball_yvel > 0)
ball_yvel = 0;
break;
default:
break;
}
}
break;
}
}
ballX += ball_xvel;
ballY += ball_yvel;
//draw the ball using SDL_RenderCopy
//this requires a rectangle of the ball's position and size (for scalability)
SDL_Rect dest;
dest.x = ballX;
dest.y = ballY;
dest.w = 32;
dest.h = 32;
SDL_RenderCopy(renderer, ballTexture, NULL, &dest);
//This uses the window title to display frame performance information
{
char temp[255];
sprintf(temp, "Frame Time:%.3f (%3.0f FPS)", (float)(fpsTime), 1000.0f/fpsTime);
SDL_SetWindowTitle(window, temp);
}
//End of frame rendering
SDL_RenderPresent(renderer);
//Sleep the app
if (elaspedTime < 16)
{
Sleep(16 - elaspedTime);
}
}
quit:
//On end of application, close down resources and exit
SDL_DestroyWindow(window);
SDL_Quit();
window = NULL;
renderer = NULL;
return 0;
} | [
"gareth_lewis@yahoo.com"
] | gareth_lewis@yahoo.com |
c1d503576b286fc58fc0c0bdf8b77e78cae54f4a | dd20b761f4f5df086f9c3c64f1e642286270324e | /adjacency_list/adjacency_list.cpp | a1409880fa52c7990756324be96f790066faa4c3 | [
"MIT"
] | permissive | guiaugusto/cpp_playground | bccaab8710af1a243e65cdb7a3f5707df6e7988c | e68b4c1c209b9bc4ea1a44bcd81d4ccb8fafa678 | refs/heads/master | 2020-05-17T01:05:07.647080 | 2019-05-22T18:37:43 | 2019-05-22T18:37:43 | 183,416,317 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,231 | cpp | #include <bits/stdc++.h>
using namespace std;
class Node{
public:
int index;
vector<int> list;
bool visited;
};
vector<Node> nodes;
void marked_as_visited(int c){
nodes[c].visited = true;
vector<int>::iterator begin = nodes[c].list.begin();
for(int i = 0; i < nodes[c].list.size(); i++){
if(!nodes[nodes[c].list[i]].visited){
marked_as_visited(nodes[c].list[i]);
nodes[c].list.erase(begin+i);
i--;
}
}
}
int main(){
int n, q, qc, c, res = 0;
int from, to;
Node node_aux;
vector<int> vazio;
cin >> n >> q;
for(int i = 0; i < n; i++){
node_aux.index = i;
node_aux.list = vazio;
node_aux.visited = false;
nodes.push_back(node_aux);
}
for(int i = 0; i < q; i++){
cin >> from >> to;
nodes[from-1].list.push_back(to-1);
nodes[to-1].list.push_back(from-1);
}
cin >> qc;
for(int i = 0; i < qc; i++){
cin >> c;
marked_as_visited(c-1);
}
for(int i = 0; i < nodes.size(); i++){
if(!nodes[i].visited){
marked_as_visited(i);
res++;
}
}
cout << res << endl;
}
| [
"guilherme.francais@gmail.com"
] | guilherme.francais@gmail.com |
83ca2014792c62eb3b1a554386d63be592d6f227 | 438e2b02741015225f5b54130f3a97d4005c3f58 | /BOJ/1275.cpp | 0e3c88a03ca2808d581071c5f58fe5ea280fd4a6 | [] | no_license | jiho5993/solving_algorithm | 20c2e3e3ee6e14116554d0fd00918447ca21784c | fbbe52bc372d418e204128e78432038dfb60b410 | refs/heads/master | 2022-10-27T13:36:27.393518 | 2022-10-16T09:32:18 | 2022-10-16T09:32:18 | 193,317,544 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,544 | cpp | #include <bits/stdc++.h>
using namespace std;
#define pb push_back
#define mp make_pair
#define all(x) (x).begin(), (x).end()
typedef long long ll;
ll arr[100001];
typedef struct SegTree {
vector<ll> tree;
int size;
SegTree(int N): size(N) {
tree.resize(N*4);
}
ll init(int node, int st, int en) {
if(st == en) return tree[node] = arr[st];
int mid = (st+en)/2;
return tree[node] = init(node*2, st, mid) + init(node*2+1, mid+1, en);
}
void update(int idx, ll diff) { update(1, 0, size-1, idx, diff); }
void update(int node, int st, int en, int idx, ll diff) {
if(!(st <= idx && idx <= en)) return;
tree[node] += diff;
if(st != en) {
int mid = (st+en)/2;
update(node*2, st, mid, idx, diff);
update(node*2+1, mid+1, en, idx, diff);
}
}
ll sum(int left, int right) { return sum(1, 0, size-1, left, right); }
ll sum(int node, int st, int en, int left, int right) {
if(en < left || right < st) return 0;
if(left <= st && en <= right) return tree[node];
int mid = (st+en)/2;
return sum(node*2, st, mid, left, right) + sum(node*2+1, mid+1, en, left, right);
}
} ST;
int main() {
ios_base::sync_with_stdio(false), cin.tie(0);
int N, Q; cin >> N >> Q;
for(int i=0; i<N; i++) cin >> arr[i];
ST tree(N);
tree.init(1, 0, N-1);
while(Q--) {
int a, b, c, d; cin >> a >> b >> c >> d;
if(a > b) swap(a, b);
cout << tree.sum(a-1, b-1) << '\n';
ll diff = d-arr[c-1];
arr[c-1] = d;
tree.update(c-1, diff);
}
return 0;
} | [
"jiho5993@naver.com"
] | jiho5993@naver.com |
68a9f515c4489b4070112007eae98def7213bd67 | b01cf41ed58bf297cf13d0a8a7f4feeecedafb4b | /Contest 3/H TAXI/main.cpp | c7d2e474a2ceab94dcd52302e77b0b3dc8b26a95 | [] | no_license | thanhnx12/TTUD-1 | 636a25f2c7486a820253c36b182be9345a6e6495 | f05a71692622ce36e5b5efc85a58d4f953b592ff | refs/heads/master | 2023-03-15T16:49:09.091169 | 2020-07-19T11:02:25 | 2020-07-19T11:02:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,038 | cpp | #include <bits/stdc++.h>
using namespace std;
int n,k,c[23][23],d[23],dem = 0,_min = 1e9;
int res = 1e9,s = 0,t;
void Try(int x,int y){
if(dem < k)
for(int i = 1; i <= n; i++){
if(!d[i]){
dem++;
d[i] = 1;
s+=c[y][i];
if(s + (t-x)*_min < res) Try(x+1,i);
s-=c[y][i];
d[i] = 0;
dem--;
}
}
for(int i = n+1; i < t; i++){
if(!d[i] && d[i-n]){
dem--;
d[i] = 1;
s+=c[y][i];
if(x == t - 1) {
res = min(res,s+c[i][0]);
}
if(s + (t-x)*_min < res) Try(x+1,i);
s-=c[y][i];
d[i] = 0;
dem++;
}
}
}
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> n;
k = 1;
t = (n << 1)+1;
for(int i = 0; i < t; i++)
for(int j = 0; j < t; j++){
cin >> c[i][j];
if(i != j) _min = min(_min,c[i][j]);
}
Try(1,0);
cout << res;
}
| [
"ntd275@gmail.com"
] | ntd275@gmail.com |
319ddeeb26f32637d62ef98d079fea0dff532ad0 | 452f7ba589dec9c9c7fbfbf9f0e4f8fedbdf392c | /xerolibs/xeromisc/MessageDestFile.cpp | 39f74314e203363993bc4e3894eed3fd5606d393 | [] | no_license | errorcodexero/endurance2019 | 51364f9e2a638029439002622e445d60016fb772 | f2442d43c845c3b9c6d94e86c21ecc571a3410b6 | refs/heads/master | 2020-12-29T22:42:08.917542 | 2020-02-06T18:54:22 | 2020-02-06T18:54:22 | 238,759,923 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,403 | cpp | #include "MessageDestFile.h"
namespace xero
{
namespace misc
{
void MessageDestFile::initialize()
{
strm_p_ = nullptr;
setTimeout(15 * 1000); // Default to 15 seconds. Stored in ms.
}
MessageDestFile::MessageDestFile()
{
initialize();
}
MessageDestFile::MessageDestFile(const std::string &name)
{
initialize();
setFile(name);
}
MessageDestFile::~MessageDestFile()
{
if (strm_p_ != nullptr)
delete strm_p_;
}
void MessageDestFile::setTimeout(unsigned long int timeout_limit)
{
timeout_limit_ = timeout_limit;
}
bool MessageDestFile::setFile(const std::string &name)
{
filename_ = name;
strm_p_ = new std::ofstream(name);
if (!strm_p_->is_open())
{
if (!ref_established_)
{
start_ = std::chrono::steady_clock::now();
ref_established_ = true;
std::cout << "Warning: Could not open log file '" << name << "' for writing. Will keep trying to reopen it." << std::endl;
}
strm_p_ = nullptr;
return false;
}
return true;
}
void MessageDestFile::displayMessage(const MessageLogger::MessageType &type, uint64_t subs, const std::string &msg)
{
if (!enabled_)
{
return;
}
std::string prefix;
if (type == MessageLogger::MessageType::warning)
prefix == "WARNING: ";
if (type == MessageLogger::MessageType::error)
prefix == "ERROR: ";
std::string appended_msg = prefix + msg;
if (strm_p_ != nullptr)
{
(*strm_p_) << (appended_msg) << std::endl;
}
else
{
if (setFile(filename_))
{ // Succeeded in opening file
std::cout << "Succeeded in opening log file." << std::endl;
for (auto const &m : msg_q_)
{
(*strm_p_) << m << std::endl;
}
msg_q_.clear();
(*strm_p_) << (appended_msg) << std::endl;
}
else
{
msg_q_.push_back(appended_msg);
auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start_).count();
if (elapsed > timeout_limit_)
{
std::cout << "Logging disabled. Timeout reached and log file still not successfully opened." << std::endl;
enabled_ = false;
}
};
}
}
} // namespace misc
} // namespace xero
| [
"bwg@cypress.com"
] | bwg@cypress.com |
790244b04b966a3f6349a7430883688fcb39aba3 | 41a4994a18f3e3a411a63e028a5c75e2e5f820f4 | /2020_StressW/2020_StressW/DrawModule.cpp | ae3e298158d01e094697496d9923fbab36453cda | [] | no_license | JS-0125/2021GameServerTermProject | f2c74b954794b4b10346a06e93bcafb2434b4531 | 85c3ff47593f1a4c6d7ff789e5fb244a81c50b6c | refs/heads/main | 2023-05-27T12:54:29.419528 | 2021-06-15T14:49:11 | 2021-06-15T14:49:11 | 375,627,551 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 18,138 | cpp | /*
* This Code Was Created By Jeff Molofee 2000
* Modified by Shawn T. to handle (%3.2f, num) parameters.
* A HUGE Thanks To Fredric Echols For Cleaning Up
* And Optimizing The Base Code, Making It More Flexible!
* If You've Found This Code Useful, Please Let Me Know.
* Visit My Site At nehe.gamedev.net
*/
#include <windows.h> // Header File For Windows
#include <math.h> // Header File For Windows Math Library
#include <stdio.h> // Header File For Standard Input/Output
#include <stdarg.h> // Header File For Variable Argument Routines
#include <gl\gl.h> // Header File For The OpenGL32 Library
#include <gl\glu.h> // Header File For The GLu32 Library
#include <atomic>
#include <memory>
//#include <gl\glaux.h> // Header File For The Glaux Library
#pragma comment (lib, "opengl32.lib")
#pragma comment (lib, "glu32.lib")
#include "NetworkModule.h"
HDC hDC = NULL; // Private GDI Device Context
HGLRC hRC = NULL; // Permanent Rendering Context
HWND hWnd = NULL; // Holds Our Window Handle
HINSTANCE hInstance; // Holds The Instance Of The Application
GLuint base; // Base Display List For The Font Set
GLfloat cnt1; // 1st Counter Used To Move Text & For Coloring
GLfloat cnt2; // 2nd Counter Used To Move Text & For Coloring
bool keys[256]; // Array Used For The Keyboard Routine
bool active = TRUE; // Window Active Flag Set To TRUE By Default
bool fullscreen = TRUE; // Fullscreen Flag Set To Fullscreen Mode By Default
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); // Declaration For WndProc
GLvoid BuildFont(GLvoid) // Build Our Bitmap Font
{
HFONT font; // Windows Font ID
HFONT oldfont; // Used For Good House Keeping
base = glGenLists(96); // Storage For 96 Characters
font = CreateFont(-24, // Height Of Font
0, // Width Of Font
0, // Angle Of Escapement
0, // Orientation Angle
FW_BOLD, // Font Weight
FALSE, // Italic
FALSE, // Underline
FALSE, // Strikeout
ANSI_CHARSET, // Character Set Identifier
OUT_TT_PRECIS, // Output Precision
CLIP_DEFAULT_PRECIS, // Clipping Precision
ANTIALIASED_QUALITY, // Output Quality
FF_DONTCARE | DEFAULT_PITCH, // Family And Pitch
L"Courier New"); // Font Name
oldfont = (HFONT)SelectObject(hDC, font); // Selects The Font We Want
wglUseFontBitmaps(hDC, 32, 96, base); // Builds 96 Characters Starting At Character 32
SelectObject(hDC, oldfont); // Selects The Font We Want
DeleteObject(font); // Delete The Font
}
GLvoid KillFont(GLvoid) // Delete The Font List
{
glDeleteLists(base, 96); // Delete All 96 Characters
}
GLvoid glPrint(const char* fmt, ...) // Custom GL "Print" Routine
{
char text[256]; // Holds Our String
va_list ap; // Pointer To List Of Arguments
if (fmt == NULL) // If There's No Text
return; // Do Nothing
va_start(ap, fmt); // Parses The String For Variables
vsprintf_s(text, fmt, ap); // And Converts Symbols To Actual Numbers
va_end(ap); // Results Are Stored In Text
glPushAttrib(GL_LIST_BIT); // Pushes The Display List Bits
glListBase(base - 32); // Sets The Base Character to 32
glCallLists((GLsizei)strlen(text), GL_UNSIGNED_BYTE, text); // Draws The Display List Text
glPopAttrib(); // Pops The Display List Bits
}
GLvoid ReSizeGLScene(GLsizei width, GLsizei height) // Resize And Initialize The GL Window
{
if (height == 0) // Prevent A Divide By Zero By
{
height = 1; // Making Height Equal One
}
glViewport(0, 0, width, height); // Reset The Current Viewport
glMatrixMode(GL_PROJECTION); // Select The Projection Matrix
glLoadIdentity(); // Reset The Projection Matrix
// Calculate The Aspect Ratio Of The Window
gluPerspective(45.0f, (GLfloat)width / (GLfloat)height, 0.1f, 100.0f);
glMatrixMode(GL_MODELVIEW); // Select The Modelview Matrix
glLoadIdentity(); // Reset The Modelview Matrix
glMatrixMode(GL_MODELVIEW); // Select The Modelview Matrix
glLoadIdentity(); // Reset The Modelview Matrix
}
int InitGL(GLvoid) // All Setup For OpenGL Goes Here
{
glShadeModel(GL_SMOOTH); // Enable Smooth Shading
glClearColor(0.0f, 0.0f, 0.0f, 0.5f); // Black Background
glClearDepth(1.0f); // Depth Buffer Setup
glEnable(GL_DEPTH_TEST); // Enables Depth Testing
glDepthFunc(GL_LEQUAL); // The Type Of Depth Testing To Do
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // Really Nice Perspective Calculations
BuildFont(); // Build The Font
return TRUE; // Initialization Went OK
}
int DrawGLScene(GLvoid) // Here's Where We Do All The Drawing
{
int size = 0;
float* points = nullptr;
// 클라이언트가 몇 개 접속, 캐릭터들 x,y 좌표
GetPointCloud(&size, &points);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear Screen And Depth Buffer
glLoadIdentity(); // Reset The Current Modelview Matrix
glTranslatef(0.14f, -0.4f, -1.0f); // Move One Unit Into The Screen
// Pulsing Colors Based On Text Position
glColor3f(1, 1, 0);
// Position The Text On The Screen
glRasterPos2f(0.0f, 0.00f);
glPrint("STRESS TEST [%d]", (int)active_clients); // Print GL Text To The Screen
glRasterPos2f(0.0f, 0.05f);
glPrint("Delay : %dms", global_delay);
glColor3f(1, 1, 1);
glPointSize(2.0);
glBegin(GL_POINTS);
for (int i = 0; i < size; i++)
{
float x, y, z;
x = points[i * 2] / 200.0f - 1.25f;
y = 1.25f - points[i * 2 + 1] / 200.0f;
z = -1.0f;
glVertex3f(x, y, z);
}
glEnd();
return TRUE; // Everything Went OK
}
GLvoid KillGLWindow(GLvoid) // Properly Kill The Window
{
if (fullscreen) // Are We In Fullscreen Mode?
{
ChangeDisplaySettings(NULL, 0); // If So Switch Back To The Desktop
ShowCursor(TRUE); // Show Mouse Pointer
}
if (hRC) // Do We Have A Rendering Context?
{
if (!wglMakeCurrent(NULL, NULL)) // Are We Able To Release The DC And RC Contexts?
{
MessageBox(NULL, L"Release Of DC And RC Failed.", L"SHUTDOWN ERROR", MB_OK | MB_ICONINFORMATION);
}
if (!wglDeleteContext(hRC)) // Are We Able To Delete The RC?
{
MessageBox(NULL, L"Release Rendering Context Failed.", L"SHUTDOWN ERROR", MB_OK | MB_ICONINFORMATION);
}
hRC = NULL; // Set RC To NULL
}
if (hDC && !ReleaseDC(hWnd, hDC)) // Are We Able To Release The DC
{
MessageBox(NULL, L"Release Device Context Failed.", L"SHUTDOWN ERROR", MB_OK | MB_ICONINFORMATION);
hDC = NULL; // Set DC To NULL
}
if (hWnd && !DestroyWindow(hWnd)) // Are We Able To Destroy The Window?
{
MessageBox(NULL, L"Could Not Release hWnd.", L"SHUTDOWN ERROR", MB_OK | MB_ICONINFORMATION);
hWnd = NULL; // Set hWnd To NULL
}
if (!UnregisterClass(L"OpenGL", hInstance)) // Are We Able To Unregister Class
{
MessageBox(NULL, L"Could Not Unregister Class.", L"SHUTDOWN ERROR", MB_OK | MB_ICONINFORMATION);
hInstance = NULL; // Set hInstance To NULL
}
KillFont();
}
/* This Code Creates Our OpenGL Window. Parameters Are: *
* title - Title To Appear At The Top Of The Window *
* width - Width Of The GL Window Or Fullscreen Mode *
* height - Height Of The GL Window Or Fullscreen Mode *
* bits - Number Of Bits To Use For Color (8/16/24/32) *
* fullscreenflag - Use Fullscreen Mode (TRUE) Or Windowed Mode (FALSE) */
BOOL CreateGLWindow(const wchar_t* title, int width, int height, BYTE bits, bool fullscreenflag)
{
GLuint PixelFormat; // Holds The Results After Searching For A Match
WNDCLASS wc; // Windows Class Structure
DWORD dwExStyle; // Window Extended Style
DWORD dwStyle; // Window Style
RECT WindowRect; // Grabs Rectangle Upper Left / Lower Right Values
WindowRect.left = (long)0; // Set Left Value To 0
WindowRect.right = (long)width; // Set Right Value To Requested Width
WindowRect.top = (long)0; // Set Top Value To 0
WindowRect.bottom = (long)height; // Set Bottom Value To Requested Height
fullscreen = fullscreenflag; // Set The Global Fullscreen Flag
hInstance = GetModuleHandle(NULL); // Grab An Instance For Our Window
wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; // Redraw On Size, And Own DC For Window.
wc.lpfnWndProc = (WNDPROC)WndProc; // WndProc Handles Messages
wc.cbClsExtra = 0; // No Extra Window Data
wc.cbWndExtra = 0; // No Extra Window Data
wc.hInstance = hInstance; // Set The Instance
wc.hIcon = LoadIcon(NULL, IDI_WINLOGO); // Load The Default Icon
wc.hCursor = LoadCursor(NULL, IDC_ARROW); // Load The Arrow Pointer
wc.hbrBackground = NULL; // No Background Required For GL
wc.lpszMenuName = NULL; // We Don't Want A Menu
wc.lpszClassName = L"OpenGL"; // Set The Class Name
if (!RegisterClass(&wc)) // Attempt To Register The Window Class
{
MessageBox(NULL, L"Failed To Register The Window Class.", L"ERROR", MB_OK | MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}
if (fullscreen) // Attempt Fullscreen Mode?
{
DEVMODE dmScreenSettings; // Device Mode
memset(&dmScreenSettings, 0, sizeof(dmScreenSettings)); // Makes Sure Memory's Cleared
dmScreenSettings.dmSize = sizeof(dmScreenSettings); // Size Of The Devmode Structure
dmScreenSettings.dmPelsWidth = width; // Selected Screen Width
dmScreenSettings.dmPelsHeight = height; // Selected Screen Height
dmScreenSettings.dmBitsPerPel = bits; // Selected Bits Per Pixel
dmScreenSettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
// Try To Set Selected Mode And Get Results. NOTE: CDS_FULLSCREEN Gets Rid Of Start Bar.
if (ChangeDisplaySettings(&dmScreenSettings, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL)
{
// If The Mode Fails, Offer Two Options. Quit Or Use Windowed Mode.
if (MessageBox(NULL, L"The Requested Fullscreen Mode Is Not Supported By\nYour Video Card. Use Windowed Mode Instead?", L"NeHe GL", MB_YESNO | MB_ICONEXCLAMATION) == IDYES)
{
fullscreen = FALSE; // Windowed Mode Selected. Fullscreen = FALSE
}
else
{
// Pop Up A Message Box Letting User Know The Program Is Closing.
MessageBox(NULL, L"Program Will Now Close.", L"ERROR", MB_OK | MB_ICONSTOP);
return FALSE; // Return FALSE
}
}
}
if (fullscreen) // Are We Still In Fullscreen Mode?
{
dwExStyle = WS_EX_APPWINDOW; // Window Extended Style
dwStyle = WS_POPUP; // Windows Style
ShowCursor(FALSE); // Hide Mouse Pointer
}
else
{
dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; // Window Extended Style
dwStyle = WS_OVERLAPPEDWINDOW; // Windows Style
}
AdjustWindowRectEx(&WindowRect, dwStyle, FALSE, dwExStyle); // Adjust Window To True Requested Size
// Create The Window
if (!(hWnd = CreateWindowEx(dwExStyle, // Extended Style For The Window
L"OpenGL", // Class Name
title, // Window Title
dwStyle | // Defined Window Style
WS_CLIPSIBLINGS | // Required Window Style
WS_CLIPCHILDREN, // Required Window Style
0, 0, // Window Position
WindowRect.right - WindowRect.left, // Calculate Window Width
WindowRect.bottom - WindowRect.top, // Calculate Window Height
NULL, // No Parent Window
NULL, // No Menu
hInstance, // Instance
NULL))) // Dont Pass Anything To WM_CREATE
{
KillGLWindow(); // Reset The Display
MessageBox(NULL, L"Window Creation Error.", L"ERROR", MB_OK | MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}
static PIXELFORMATDESCRIPTOR pfd = // pfd Tells Windows How We Want Things To Be
{
sizeof(PIXELFORMATDESCRIPTOR), // Size Of This Pixel Format Descriptor
1, // Version Number
PFD_DRAW_TO_WINDOW | // Format Must Support Window
PFD_SUPPORT_OPENGL | // Format Must Support OpenGL
PFD_DOUBLEBUFFER, // Must Support Double Buffering
PFD_TYPE_RGBA, // Request An RGBA Format
bits, // Select Our Color Depth
0, 0, 0, 0, 0, 0, // Color Bits Ignored
0, // No Alpha Buffer
0, // Shift Bit Ignored
0, // No Accumulation Buffer
0, 0, 0, 0, // Accumulation Bits Ignored
16, // 16Bit Z-Buffer (Depth Buffer)
0, // No Stencil Buffer
0, // No Auxiliary Buffer
PFD_MAIN_PLANE, // Main Drawing Layer
0, // Reserved
0, 0, 0 // Layer Masks Ignored
};
if (!(hDC = GetDC(hWnd))) // Did We Get A Device Context?
{
KillGLWindow(); // Reset The Display
MessageBox(NULL, L"Can't Create A GL Device Context.", L"ERROR", MB_OK | MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}
if (!(PixelFormat = ChoosePixelFormat(hDC, &pfd))) // Did Windows Find A Matching Pixel Format?
{
KillGLWindow(); // Reset The Display
MessageBox(NULL, L"Can't Find A Suitable PixelFormat.", L"ERROR", MB_OK | MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}
if (!SetPixelFormat(hDC, PixelFormat, &pfd)) // Are We Able To Set The Pixel Format?
{
KillGLWindow(); // Reset The Display
MessageBox(NULL, L"Can't Set The PixelFormat.", L"ERROR", MB_OK | MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}
if (!(hRC = wglCreateContext(hDC))) // Are We Able To Get A Rendering Context?
{
KillGLWindow(); // Reset The Display
MessageBox(NULL, L"Can't Create A GL Rendering Context.", L"ERROR", MB_OK | MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}
if (!wglMakeCurrent(hDC, hRC)) // Try To Activate The Rendering Context
{
KillGLWindow(); // Reset The Display
MessageBox(NULL, L"Can't Activate The GL Rendering Context.", L"ERROR", MB_OK | MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}
ShowWindow(hWnd, SW_SHOW); // Show The Window
SetForegroundWindow(hWnd); // Slightly Higher Priority
SetFocus(hWnd); // Sets Keyboard Focus To The Window
ReSizeGLScene(width, height); // Set Up Our Perspective GL Screen
if (!InitGL()) // Initialize Our Newly Created GL Window
{
KillGLWindow(); // Reset The Display
MessageBox(NULL, L"Initialization Failed.", L"ERROR", MB_OK | MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}
return TRUE; // Success
}
LRESULT CALLBACK WndProc(HWND hWnd, // Handle For This Window
UINT uMsg, // Message For This Window
WPARAM wParam, // Additional Message Information
LPARAM lParam) // Additional Message Information
{
switch (uMsg) // Check For Windows Messages
{
case WM_ACTIVATE: // Watch For Window Activate Message
{
if (!HIWORD(wParam)) // Check Minimization State
{
active = TRUE; // Program Is Active
}
else
{
active = FALSE; // Program Is No Longer Active
}
return 0; // Return To The Message Loop
}
case WM_SYSCOMMAND: // Intercept System Commands
{
switch (wParam) // Check System Calls
{
case SC_SCREENSAVE: // Screensaver Trying To Start?
case SC_MONITORPOWER: // Monitor Trying To Enter Powersave?
return 0; // Prevent From Happening
}
break; // Exit
}
case WM_CLOSE: // Did We Receive A Close Message?
{
PostQuitMessage(0); // Send A Quit Message
return 0; // Jump Back
}
case WM_KEYDOWN: // Is A Key Being Held Down?
{
keys[wParam] = TRUE; // If So, Mark It As TRUE
return 0; // Jump Back
}
case WM_KEYUP: // Has A Key Been Released?
{
keys[wParam] = FALSE; // If So, Mark It As FALSE
return 0; // Jump Back
}
case WM_SIZE: // Resize The OpenGL Window
{
ReSizeGLScene(LOWORD(lParam), HIWORD(lParam)); // LoWord=Width, HiWord=Height
return 0; // Jump Back
}
}
// Pass All Unhandled Messages To DefWindowProc
return DefWindowProc(hWnd, uMsg, wParam, lParam);
}
int WINAPI WinMain(HINSTANCE hInstance, // Instance
HINSTANCE hPrevInstance, // Previous Instance
LPSTR lpCmdLine, // Command Line Parameters
int nCmdShow) // Window Show State
{
MSG msg; // Windows Message Structure
BOOL done = FALSE; // Bool Variable To Exit Loop
fullscreen = FALSE; // Windowed Mode
// Create Our OpenGL Window
if (!CreateGLWindow(L"Stress Test Client", 640, 480, 16, fullscreen))
{
return 0; // Quit If Window Was Not Created
}
InitializeNetwork();
while (!done) // Loop That Runs While done=FALSE
{
if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) // Is There A Message Waiting?
{
if (msg.message == WM_QUIT) // Have We Received A Quit Message?
{
done = TRUE; // If So done=TRUE
}
else // If Not, Deal With Window Messages
{
TranslateMessage(&msg); // Translate The Message
DispatchMessage(&msg); // Dispatch The Message
}
}
else // If There Are No Messages
{
// Draw The Scene. Watch For ESC Key And Quit Messages From DrawGLScene()
if ((active && !DrawGLScene()) || keys[VK_ESCAPE]) // Active? Was There A Quit Received?
{
done = TRUE; // ESC or DrawGLScene Signalled A Quit
}
else // Not Time To Quit, Update Screen
{
SwapBuffers(hDC); // Swap Buffers (Double Buffering)
}
if (keys[VK_F1]) // Is F1 Being Pressed?
{
keys[VK_F1] = FALSE; // If So Make Key FALSE
KillGLWindow(); // Kill Our Current Window
fullscreen = !fullscreen; // Toggle Fullscreen / Windowed Mode
// Recreate Our OpenGL Window
if (!CreateGLWindow(L"NeHe's Bitmap Font Tutorial", 640, 480, 16, fullscreen))
{
return 0; // Quit If Window Was Not Created
}
}
}
}
// Shutdown
KillGLWindow(); // Kill The Window
return ((int)msg.wParam); // Exit The Program
}
| [
"realline@kpu.ac.kr"
] | realline@kpu.ac.kr |
f10fac8f10c4bc63ef9058e613cdb0c4611f6036 | 27e0a8065d73de8deedfb58a94730f7c3c55261e | /数组中常见的问题/167. 两数之和 II - 输入有序数组/main.cpp | 21a16c516c2624004646a54ccc0ae050f82de929 | [] | no_license | Jae1010/leetcode | 5ea717eb15f5fff560b04a6f5301c4ed682fcbda | 8f55d4ead6cd1ebb7e166d64a73e5d2890bf4425 | refs/heads/master | 2023-02-02T05:39:00.627840 | 2020-12-22T06:54:04 | 2020-12-22T06:54:04 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,883 | cpp | //==================================================================
// Leetcode代码
// 作者:曹佳
//==================================================================
//
// 167. 两数之和 II - 输入有序数组
// 题目:给定一个已按照升序排列 的有序数组,找到两个数使得它们相加之和等于目标数。
// 函数应该返回这两个下标值 index1 和 index2,其中 index1 必须小于 index2。
//说明:
//返回的下标值(index1 和 index2)不是从零开始的。
//你可以假设每个输入只对应唯一的答案,而且你不可以重复使用相同的元素。
//
#include <iostream>
#include <vector>
using namespace std;
//暴力解法
vector<int> twoSum1(vector<int>& numbers, int target) {
vector<int> result;
for(int i = 0; i < numbers.size()-1;i++)
for(int j = i+1; j < numbers.size(); j++){
if(numbers[i] + numbers[j] == target){
result.push_back(++i);
result.push_back(++j);
return result;
}
}
return result;
}
//双指针 时间复杂度O(n), 空间复杂度O(1), 对撞指针
vector<int> twoSum2(vector<int>& numbers, int target) {
int i = 0;
vector<int> result;
if(numbers[i] > target)
return result ;
int j = numbers.size()-1;
while( j > i){
if(numbers[j] >= target){
j--;
continue;
}
if(numbers[i] + numbers[j] > target)
j--;
else if(numbers[i] + numbers[j] < target)
i++;
else{
result.push_back(i+1);
result.push_back(j+1);
return result;
}
}
return result;
}
int main()
{
vector<int> ivec = { -1, 0};
vector<int> vec = twoSum1(ivec, -1);
for(auto i : vec)
cout << i << " ";
cout << endl;
return 0;
}
| [
"335181140@qq.com"
] | 335181140@qq.com |
15330a65ac0b9f447bc06b3a7909dfe622121e53 | 74359a77bc2ee4f4730d1bd9716fd3cea13fa54c | /src/api/udf/UDFFactory.h | 36396a5fc8508828a16fa6a63eeb4198c6e02230 | [
"Apache-2.0"
] | permissive | Anewczs/nebula | 32c0d82e982a41886d3ea0d8d3d331b7e5c5a473 | f9bcd3c6df47c459712c1c30c5183873970182ae | refs/heads/master | 2022-04-23T00:01:30.514432 | 2020-04-18T00:46:56 | 2020-04-20T22:27:54 | 257,549,610 | 1 | 0 | null | 2020-04-21T09:47:01 | 2020-04-21T09:47:00 | null | UTF-8 | C++ | false | false | 2,698 | h | /*
* Copyright 2017-present Shawn Cao
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include "Avg.h"
#include "Count.h"
#include "In.h"
#include "Like.h"
#include "Max.h"
#include "Min.h"
#include "Not.h"
#include "Pct.h"
#include "Prefix.h"
#include "Sum.h"
#include "api/dsl/Base.h"
#include "surface/eval/UDF.h"
#include "type/Type.h"
/**
* Create UDF/UDAF object based on parameters
*/
namespace nebula {
namespace api {
namespace udf {
using UDFKind = nebula::surface::eval::UDFType;
class UDFFactory {
public:
template <UDFKind UKIND, nebula::type::Kind IK, typename... Args>
static std::unique_ptr<nebula::surface::eval::ValueEval>
createUDF(std::shared_ptr<nebula::api::dsl::Expression> expr, Args&&... args) {
constexpr auto name = nebula::surface::eval::UdfTraits<UKIND, IK>::Name;
if constexpr (UKIND == UDFKind::NOT) {
return std::make_unique<Not>(name, expr->asEval());
}
if constexpr (UKIND == UDFKind::MAX) {
return std::make_unique<Max<IK>>(name, expr->asEval());
}
if constexpr (UKIND == UDFKind::MIN) {
return std::make_unique<Min<IK>>(name, expr->asEval());
}
if constexpr (UKIND == UDFKind::COUNT) {
return std::make_unique<Count<IK>>(name, expr->asEval());
}
if constexpr (UKIND == UDFKind::SUM) {
return std::make_unique<Sum<IK>>(name, expr->asEval());
}
if constexpr (UKIND == UDFKind::AVG) {
return std::make_unique<Avg<IK>>(name, expr->asEval());
}
if constexpr (UKIND == UDFKind::PCT) {
return std::make_unique<Pct<IK>>(name, expr->asEval(), std::forward<Args>(args)...);
}
if constexpr (UKIND == UDFKind::LIKE) {
return std::make_unique<Like>(name, expr->asEval(), std::forward<Args>(args)...);
}
if constexpr (UKIND == UDFKind::PREFIX) {
return std::make_unique<Prefix>(name, expr->asEval(), std::forward<Args>(args)...);
}
if constexpr (UKIND == UDFKind::IN) {
return std::make_unique<In<IK>>(name, expr, std::forward<Args>(args)...);
}
throw NException(fmt::format("Unimplemented UDF {0}", name));
}
};
} // namespace udf
} // namespace api
} // namespace nebula | [
"caoxhua@gmail.com"
] | caoxhua@gmail.com |
31cc2f89f1954b3b5018f203b67b5ce4f91d9211 | 3288e8ff6adc21524a399dd97fc018469520b323 | /cpp_cookbok/3-5.cpp | e5f6ae78a86f2ea275d43c8e7d89d33e2a1e98e2 | [] | no_license | arraytools/C | 2a04cfe07da43d385dc1c3b3b86e6f9cd0099a52 | 42e127024f19ad432d82240cca9435ec3882a542 | refs/heads/master | 2018-12-28T16:07:51.710347 | 2015-01-17T00:25:20 | 2015-01-17T00:25:20 | 10,589,340 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 904 | cpp | #include <iostream>
#include <boost/lexical_cast.hpp>
using namespace std;
using boost::lexical_cast;
using boost::bad_lexical_cast;
template<typename T>
bool isValid(const string& num) {
bool res = true;
try {
T tmp = lexical_cast<T>(num);
}
catch (bad_lexical_cast &e) {
res = false;
}
return(res);
}
void test(const string& s) {
if (isValid<int>(s))
cout << s << " is a valid integer." << endl;
else
cout << s << " is NOT a valid integer." << endl;
if (isValid<double>(s))
cout << s << " is a valid double." << endl;
else
cout << s << " is NOT a valid double." << endl;
if (isValid<float>(s))
cout << s << " is a valid float." << endl;
else
cout << s << " is NOT a valid float." << endl;
}
int main( ) {
test("12345");
test("1.23456");
test("-1.23456");
test(" - 1.23456");
test("+1.23456");
test(" 1.23456 ");
test("asdf");
}
| [
"arraytools@gmail.com"
] | arraytools@gmail.com |
70808b5a528d05962adaa67cadc6783fa4d37556 | b04aba222b36f229061fd38edf806aae31534449 | /include/scalapackpp/wrappers/linear_systems/posv.hpp | 8758c3e780d55df9cdcf9c58c029d19cf7bbd273 | [] | no_license | ValeevGroup/scalapackpp | 49ce1a5db96b0585f214d0115fcaad46fc1c3e92 | 321b6fc8749fd020042fd1d75cb2292613cec178 | refs/heads/master | 2022-06-13T01:48:12.633522 | 2020-02-07T17:03:49 | 2020-02-07T17:03:49 | 239,920,851 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 437 | hpp | #pragma once
#include <scalapackpp/types.hpp>
#include <scalapackpp/util/sfinae.hpp>
namespace scalapackpp::wrappers {
template <typename T>
detail::enable_if_scalapack_supported_t<T, scalapack_int>
pposv( const char* UPLO, scalapack_int N, scalapack_int NRHS,
const T* A, scalapack_int IA, scalapack_int JA, const scalapack_desc& DESCA,
T* B, scalapack_int IB, scalapack_int JB, const scalapack_desc& DESCB );
}
| [
"dbwy@lbl.gov"
] | dbwy@lbl.gov |
6db0d0ae48960109b30c22d919ca11f857788ff4 | b4ba3bc2725c8ff84cd80803c8b53afbe5e95e07 | /Medusa/Medusa/Geometry/Size3.h | a8a89c08ec57e315cb8cf864dacd7e638b6e29c5 | [
"MIT"
] | permissive | xueliuxing28/Medusa | c4be1ed32c2914ff58bf02593f41cf16e42cc293 | 15b0a59d7ecc5ba839d66461f62d10d6dbafef7b | refs/heads/master | 2021-06-06T08:27:41.655517 | 2016-10-08T09:49:54 | 2016-10-08T09:49:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,396 | h | // Copyright (c) 2015 fjz13. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
#pragma once
#include "MedusaPreDeclares.h"
#include "Core/Assertion/CommonAssert.h"
#include "Geometry/Size2.h"
#include "Core/Math/Math.h"
#include "Core/System/BitConverter.h"
MEDUSA_BEGIN;
template<typename T>
class Size3
{
public:
union
{
T Buffer[3];
struct
{
T Width;
T Height;
T Depth;
};
};
const static Size3 Zero;
public:
Size3(void){}
Size3(T width,T height,T depth):Width(width),Height(height),Depth(depth){}
template<typename T1>
Size3(const Size3<T1>& size):Width((T)size.Width),Height((T)size.Height),Depth((T)size.Depth){}
template<typename T1>
Size3(const Size2<T1>& size):Width((T)size.Width),Height((T)size.Height),Depth((T)0){}
template<typename T1>
explicit Size3(T1 val):Width((T)val),Height((T)val),Depth((T)val){}
template<typename T1>
Size3& operator=(const Size3<T1>& size){Width=(T)size.Width;Height=(T)size.Height;Depth=(T)size.Depth;return *this;}
template<typename T1>
Size3& operator=(const Size2<T1>& size){Width=(T)size.Width;Height=(T)size.Height;Depth=(T)0;return *this;}
template<typename T1>
Size3& operator=(T1 val){Width=(T)val;Height=(T)val;Depth=(T)val;return *this;}
template<typename T1>
bool operator==(const Size3<T1>& size)const{return Math::IsEqual(Width,size.Width)&&Math::IsEqual(Height,size.Height)&&Math::IsEqual(Depth,size.Depth);}
template<typename T1>
bool operator!=(const Size3<T1>& size)const{return !operator==(size);}
template<typename T1>
bool operator>(const Size3<T1>& size)const{return Width>size.Width&&Height>size.Height&&Depth>size.Depth;}
template<typename T1>
bool operator<(const Size3<T1>& size)const{return Width<size.Width&&Height<size.Height&&Depth<size.Depth;}
template<typename T1>
bool operator>=(const Size3<T1>& size)const{return Width>=size.Width&&Height>=size.Height&&Depth>=size.Depth;}
template<typename T1>
bool operator<=(const Size3<T1>& size)const{return Width<=size.Width&&Height<=size.Height&&Depth<=size.Depth;}
template<typename T1>
Size3 operator+(const Size3<T1>& size)const{return Size3(Width+size.Width,Height+size.Height,Depth+size.Depth);}
template<typename T1>
Size3 operator-(const Size3<T1>& size)const{return Size3(Width-size.Width,Height-size.Height,Depth-size.Depth);}
template<typename T1>
Size3& operator+=(const Size3<T1>& size){Width+=size.Width;Height+=size.Height;Depth+=size.Depth;return *this;}
template<typename T1>
Size3& operator-=(const Size3<T1>& size){Width-=size.Width;Height-=size.Height;Depth-=size.Depth;return *this;}
template<typename T1>
Size3 operator*(T1 delta)const{return Size3(Width*delta,Height*delta,Depth*delta);}
template<typename T1>
Size3& operator*=(T1 delta){Width*=delta;Height*=delta;Depth*=delta;return *this;}
template<typename T1>
Size3 operator/(T1 delta)const{MEDUSA_ASSERT_NOT_ZERO(delta,"");return Size3(Width/delta,Height/delta,Depth/delta);}
template<typename T1>
Size3& operator/=(T1 delta){MEDUSA_ASSERT_NOT_ZERO(delta,"");Width/=delta;Height/=delta;Depth/=delta;return *this;}
template<typename T1>
Size3 operator+(T1 delta)const{return Size3(Width+delta,Height+delta,Depth+delta);}
template<typename T1>
Size3& operator+=(T1 delta){Width+=delta;Height+=delta;Depth+=delta;return *this;}
template<typename T1>
Size3 operator-(T1 delta)const{return Size3(Width-delta,Height-delta,Depth-delta);}
template<typename T1>
Size3& operator-=(T1 delta){Width-=delta;Height-=delta;Depth-=delta;return *this;}
Size3 operator<<(uint32 delta)const{return Size3(Width<<delta,Height<<delta,Depth<<delta);}
Size3& operator<<=(uint32 delta){Width<<=delta;Height<<=delta;Depth<<=delta;return *this;}
Size3 operator>>(uint32 delta)const{return Size3(Width>>delta,Height>>delta,Depth>>delta);}
Size3& operator>>=(uint32 delta){Width>>=delta;Height>>=delta;Depth>>=delta;return *this;}
Size3& operator++(){++Width;++Height;++Depth;return *this;}
Size3& operator--(){--Width;--Height;--Depth;return *this;}
Size3 operator++(int){Size3 orign=*this;++Width;++Height;++Depth;return orign;}
Size3 operator--(int){Size3 orign=*this;--Width;--Height;--Depth;return orign;}
Size3 operator-()const { return Size3(-Width, -Height,-Depth); }
template<typename T1>
friend Size3 operator*(T1 delta,const Size3<T>& size){return Size3(delta*size.Width,delta*size.Height,delta*size.Depth);}
Size2<T> To2D()const{return Size2<T>(Width,Height);}
bool IsEmpty()const{return Math::IsZero(Width)||Math::IsZero(Height)||Math::IsZero(Depth);}
T Volume()const{return Width*Height*Depth;}
intp HashCode()const{return HashUtility::Hash(Buffer);}
bool IsNearlyZero(float tolerance = 1.e-4f)const
{
return Math::Abs(Width) <= tolerance && Math::Abs(Height) <= tolerance&&Math::Abs(Depth) <= tolerance;
}
static Size3 LinearInterpolate(const Size3& begin,const Size3& end,float blend)
{
return Size2<T>(Math::LinearInterpolate(begin.Width,end.Width,blend),Math::LinearInterpolate(begin.Height,end.Height,blend),Math::LinearInterpolate(begin.Depth,end.Depth,blend));
}
};
template<typename T>
MEDUSA_WEAK_MULTIPLE_DEFINE const Size3<T> Size3<T>::Zero(0,0,0);
//[PRE_DECLARE_BEGIN]
typedef Size3<uint32> Size3U;
typedef Size3<int> Size3I;
typedef Size3<float> Size3F;
//[PRE_DECLARE_END]
#define msize3u(x,y,z) Size3U(x,y,z)
#define msize3i(x,y,z) Size3I(x,y,z)
#define msize3(x,y,z) Size3F(x,y,z)
MEDUSA_END;
#ifdef MEDUSA_LUA
#include "Core/Lua/LuaState.h"
MEDUSA_BEGIN;
template <typename T>
struct LuaTypeMapping <Size3<T>>//[IGNORE_PRE_DECLARE]
{
static void Push(lua_State* L, const Size3<T>& val)
{
LuaStack s(L);
s.NewTable(0, 3);
s.Rawset("Width", val.Width);
s.Rawset("Height", val.Height);
s.Rawset("Depth", val.Depth);
}
static Size3<T> Get(lua_State* L, int index)
{
Size3<T> result;
LuaStack s(L);
result.Width = s.Get<T>("Width",index);
result.Height = s.Get<T>("Height",index);
result.Depth = s.Get<T>("Depth",index);
return result;
}
static Size3<T> Optional(lua_State* L, int index, const Size3<T>& def)
{
return lua_isnoneornil(L, index) ? Size3<T>::Zero : Get(L, index);
}
static bool TryGet(lua_State* L, int index, Size3<T>& outValue)
{
RETURN_FALSE_IF(lua_isnoneornil(L, index));
outValue = Get(L, index);
return true;
}
};
MEDUSA_END;
#endif
| [
"fjz13@live.cn"
] | fjz13@live.cn |
8d5585974d3998a3b38d87026aa3daa0ca7bc8cc | 820f4cd8567a92f3d4d98c234871fa3256ce9d5a | /src/Sim/BarnesHut.hpp | f3da3bbef8fa90f7d25e40f2ec4e30dffccb71fa | [] | no_license | matty9090/Procedural-Universe | 6635805cb8bb4ce4ae31ed459c8f49486fb8b324 | 3242f594bfe1553b4359fb97db6b0b1975e7503b | refs/heads/master | 2022-08-06T16:25:18.399832 | 2020-05-23T22:21:18 | 2020-05-23T22:21:18 | 208,433,218 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 940 | hpp | #pragma once
#include <GeometricPrimitive.h>
#include "Octree.hpp"
#include "INBodySim.hpp"
#include "Render/Model/Cube.hpp"
#include "Core/ThreadPool.hpp"
class BarnesHut : public INBodySim
{
public:
BarnesHut(ID3D11DeviceContext* context);
~BarnesHut();
void Init(std::vector<Particle>& particles) final;
void Update(float dt) final;
void RenderDebug(DirectX::SimpleMath::Matrix view, DirectX::SimpleMath::Matrix proj);
private:
BoundingCube Bounds;
std::unique_ptr<Octree> Tree;
std::vector<Particle>* Particles;
ID3D11DeviceContext* Context;
struct ParticleInfo
{
size_t Index;
size_t Loops;
};
CThreadPool<ParticleInfo> Pool;
std::unique_ptr<Cube> DebugCube;
std::unique_ptr<DirectX::GeometricPrimitive> DebugSphere;
void Exec(const ParticleInfo& info);
}; | [
"lowe.matthew@mail.com"
] | lowe.matthew@mail.com |
15e2221369b1c3cabde9170f5bedc3fb7c877b94 | 49b878b65e9eb00232490243ccb9aea9760a4a6d | /ash/public/cpp/holding_space/holding_space_constants.h | 1d07baf95dac95d4817a530ef8820e4eb7cf7cf6 | [
"BSD-3-Clause"
] | permissive | romanzes/chromium | 5a46f234a233b3e113891a5d643a79667eaf2ffb | 12893215d9efc3b0b4d427fc60f5369c6bf6b938 | refs/heads/master | 2022-12-28T00:20:03.524839 | 2020-10-08T21:01:52 | 2020-10-08T21:01:52 | 302,470,347 | 0 | 0 | BSD-3-Clause | 2020-10-08T22:10:22 | 2020-10-08T21:54:38 | null | UTF-8 | C++ | false | false | 2,634 | h | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef ASH_PUBLIC_CPP_HOLDING_SPACE_HOLDING_SPACE_CONSTANTS_H_
#define ASH_PUBLIC_CPP_HOLDING_SPACE_HOLDING_SPACE_CONSTANTS_H_
#include "ash/public/cpp/app_menu_constants.h"
#include "ui/gfx/geometry/insets.h"
#include "ui/gfx/geometry/size.h"
namespace ash {
// Appearance.
constexpr int kHoldingSpaceBubbleWidth = 360;
constexpr gfx::Insets kHoldingSpaceContainerPadding(16);
constexpr int kHoldingSpaceContainerChildSpacing = 16;
constexpr int kHoldingSpaceContainerSpacing = 8;
constexpr gfx::Insets kHoldingSpaceChipPadding(8);
constexpr int kHoldingSpaceChipChildSpacing = 8;
constexpr int kHoldingSpaceChipHeight = 40;
constexpr int kHoldingSpaceChipIconSize = 24;
constexpr int kHoldingSpaceChipWidth = 160;
constexpr int kHoldingSpaceChipsPerRow = 2;
constexpr int kHoldingSpaceColumnSpacing = 8;
constexpr int kHoldingSpaceColumnWidth = 160;
constexpr int kHoldingSpaceContextMenuMargin = 8;
constexpr int kHoldingSpaceCornerRadius = 8;
constexpr int kHoldingSpaceDownloadsChevronIconSize = 20;
constexpr int kHoldingSpaceDownloadsHeaderSpacing = 16;
constexpr int kHoldingSpacePinIconSize = 20;
constexpr int kHoldingSpaceRowSpacing = 8;
constexpr gfx::Insets kHoldingSpaceScreenshotPadding(8);
constexpr gfx::Size kHoldingSpaceScreenshotPinButtonSize(24, 24);
constexpr int kHoldingSpaceScreenshotSpacing = 8;
constexpr gfx::Size kHoldingSpaceScreenshotSize(104, 80);
constexpr gfx::Insets kHoldingSpaceScreenshotsContainerPadding(8, 0);
constexpr float kHoldingSpaceSelectedOverlayOpacity = 0.24f;
constexpr int kHoldingSpaceTrayMainAxisMargin = 6;
// Context menu commands.
enum HoldingSpaceCommandId {
kPinItem,
kCopyImageToClipboard,
kShowInFolder,
kUnpinItem,
kMaxValue = kUnpinItem
};
// View IDs.
constexpr int kHoldingSpacePinnedFilesContainerId = 1;
constexpr int kHoldingSpaceRecentFilesContainerId = 2;
// The maximum allowed age for files restored into the holding space model.
// Note that this is not enforced for pinned items.
constexpr base::TimeDelta kMaxFileAge = base::TimeDelta::FromDays(1);
// The maximum allowed number of downloads to display in holding space UI.
constexpr size_t kMaxDownloads = 2u;
// The maximum allowed number of screenshots to display in holding space UI.
constexpr size_t kMaxScreenshots = 3u;
// Mime type with wildcard which matches all image types.
constexpr char kMimeTypeImage[] = "image/*";
} // namespace ash
#endif // ASH_PUBLIC_CPP_HOLDING_SPACE_HOLDING_SPACE_CONSTANTS_H_
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
4ef2ffc17ddb791a484d830030875b4c423b79df | ce588945eabc48c36ce87e7601751d9addcb2cec | /yooncpp/project/step10/AccountHandler.cpp | db4a7766eeeffc014e964bd5b2ec2e025289b454 | [] | no_license | jun097kim/study-cpp | 6512f482d45fc2f958014e7f59b238b3d2920eee | 282e93aa0ee7cc09289e0c3478cba2b2b7dab263 | refs/heads/master | 2020-03-21T05:07:56.110571 | 2018-07-18T15:20:25 | 2018-07-18T15:20:25 | 138,145,698 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,344 | cpp | #include "BankingCommonDecl.h"
#include "AccountHandler.h"
#include "NormalAccount.h"
#include "HighCreditAccount.h"
void AccountHandler::ShowMenu() const
{
cout << "-----Menu-----" << endl;
cout << "1. 계좌개설" << endl;
cout << "2. 입 금" << endl;
cout << "3. 출 금" << endl;
cout << "4. 계좌정보 전체 출력" << endl;
cout << "5. 프로그램 종료" << endl;
}
void AccountHandler::MakeAccount()
{
int sel;
cout << "[계좌종류선택]" << endl;
cout << "1. 보통예금계좌 ";
cout << "2. 신용신뢰계좌 " << endl;
cout << "선택: ";
cin >> sel;
if (sel == NORMAL)
MakeNormalAccount();
else
MakeCreditAccount();
}
void AccountHandler::MakeNormalAccount()
{
int id;
String name;
int balance;
int interRate;
cout << "[보틍예금계좌 개설]" << endl;
cout << "계좌ID: "; cin >> id;
cout << "이 름: "; cin >> name;
cout << "입금액: "; cin >> balance;
cout << "이자율: "; cin >> interRate;
cout << endl;
accArr[accNum++] = new NormalAccount(id, balance, name, interRate);
}
void AccountHandler::MakeCreditAccount()
{
int id;
String name;
int balance;
int interRate;
int creditLevel;
cout << "[신용신뢰계좌 개설]" << endl;
cout << "계좌ID: "; cin >> id;
cout << "이 름: "; cin >> name;
cout << "입금액: "; cin >> balance;
cout << "이자율: "; cin >> interRate;
cout << "신용등급(1toA, 2toB, 3toC): "; cin >> creditLevel;
cout << endl;
switch (creditLevel)
{
case 1:
accArr[accNum++] = new HighCreditAccount(id, balance, name, interRate, LEVEL_A);
break;
case 2:
accArr[accNum++] = new HighCreditAccount(id, balance, name, interRate, LEVEL_B);
break;
case 3:
accArr[accNum++] = new HighCreditAccount(id, balance, name, interRate, LEVEL_C);
break;
}
}
void AccountHandler::DepositMoney()
{
int money;
int id;
cout << "[입 금]" << endl;
cout << "계좌ID: "; cin >> id;
cout << "입금액: "; cin >> money;
for (int i = 0; i < accNum; i++)
{
if (accArr[i]->GetAccID() == id)
{
accArr[i]->Deposit(money);
cout << "입금완료" << endl << endl;
return;
}
}
cout << "유효하지 않은 ID 입니다." << endl << endl;
}
void AccountHandler::WithdrawMoney()
{
int money;
int id;
cout << "[출 금]" << endl;
cout << "계좌ID: "; cin >> id;
cout << "출금액: "; cin >> money;
for (int i = 0; i < accNum; i++)
{
if (accArr[i]->GetAccID() == id)
{
if (accArr[i]->Withdraw(money) == 0)
{
cout << "잔액부족" << endl << endl;
return;
}
cout << "출금완료" << endl << endl;
return;
}
}
cout << "유효하지 않은 ID 입니다." << endl << endl;
}
void AccountHandler::ShowAllAccInfo() const
{
for (int i = 0; i < accNum; i++)
{
accArr[i]->ShowAccInfo();
}
}
AccountHandler::AccountHandler()
: accNum(0)
{ }
AccountHandler::~AccountHandler()
{
for (int i = 0; i < accNum; i++)
delete accArr[i];
} | [
"jun097kim@gmail.com"
] | jun097kim@gmail.com |
0aec9bf3a97a6d36914b6c4a41342c2b392510a4 | e44283331c214e69f049d3d23b6350dbf2abbf32 | /All ACM Codes/contest/light oj 02.09.2016/F.cpp | bdbf7737f690345559b7df376fd2b25178edfe7c | [] | no_license | Abiduddin/Competitive-Programming-Codes | cd2a8730998859d751e1891b4bc9bd3a790b8416 | 59b51b08c6f34c1bed941c8b86490ee9a250e5a9 | refs/heads/master | 2020-09-09T22:54:09.708942 | 2019-11-14T02:31:06 | 2019-11-14T02:31:06 | 221,588,892 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 308 | cpp | #include <stdio.h>
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int i,j,l=0,k,m,n,p;
scanf("%d",&i);
while(i--)
{
scanf("%d.%d.%d.%d",&k,&m,&n,&p);
printf("Case %d: ",++l);
cout<<oct<<k<<"."<<oct<<m<<"."<<oct<<n<<"."<<oct<<p<<endl;
}
}
| [
"abidakash456@gmail.com"
] | abidakash456@gmail.com |
5d03165d9339fbf6d9dc4eaf388c284d3d861b23 | 8e86c2e07a7f3c275c395761634c0ed2ed412db8 | /uva/10004-Bicoloring/solution.cpp | e803569b584f424e89f1b3a81767c1c1e811bf4d | [] | no_license | ramirezjpdf/problems | e145d82d876f7c4d0b99a6453a22aecec07d1fe5 | 0896b8e072f5a29752f02d38878ac361ed3586b5 | refs/heads/master | 2021-01-19T19:38:06.205467 | 2017-04-17T14:31:42 | 2017-04-17T14:31:42 | 88,431,062 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,315 | cpp | #include <iostream>
#include <vector>
#include <queue>
using namespace std;
const int MAXV = 200;
const int MAXDEGREE = 200;
struct graph{
vector<vector<int> > edges;
vector<int> degrees;
int nvertices;
int nedges;
graph() : edges(MAXV, vector<int>(MAXDEGREE)),
degrees(MAXV, 0) {}
};
void insertedge(graph &g, int x, int y, bool directed) {
if (g.degrees[x] > MAXDEGREE) {
cout << "Warning: insertion(" << x << ", " << y;
cout << " exceeds max degrees" << endl;
}
g.edges[x][g.degrees[x]] = y;
g.degrees[x]++;
if (directed) insertedge(g, y, x, false);
else g.nedges++;
}
bool readgraph(graph &g, bool directed) {
int m;
int x, y;
cin >> g.nvertices >> m;
if (g.nvertices == 0) return false;
for (int i = 0; i < m; i++) {
cin >> x >> y;
insertedge(g, x, y, directed);
}
return true;
}
void printgraph(graph &g) {
for (vector<vector<int> >::iterator it = g.edges.begin();
it != g.edges.end(); ++it) {
cout << (it - g.edges.begin()) << ":";
for (vector<int>::iterator it2 = (*it).begin();
it2 != (*it).end(); ++it2) {
cout << " " << *it2;
}
cout << endl;
}
}
const int RED = 2;
const int BLUE = 3;
const int UNCOLOR = 0;
int ccolor(int color) {
if (color == RED) return BLUE;
if (color == BLUE) return RED;
if (color = UNCOLOR) return UNCOLOR;
}
bool bicoloredbfs(graph g, int start) {
vector<bool> discovered(g.nvertices, false);
vector<bool> processed(g.nvertices, false);
bool bicolored = true;
vector<int> colors(g.nvertices, UNCOLOR);
queue<int> q;
q.push(start);
discovered[start] = true;
colors[start] = RED;
while(!q.empty()) {
int v = q.front();
q.pop();
processed[v] = true;
for (int i = 0; i < g.degrees[v]; i++) {
if (!discovered[g.edges[v][i]]) {
q.push(g.edges[v][i]);
discovered[g.edges[v][i]] = true;
colors[g.edges[v][i]] = ccolor(colors[v]);
} else {
if (colors[v] == colors[g.edges[v][i]]) {
bicolored = false;
return bicolored;
}
}
}
}
return bicolored;
}
int main() {
graph *g = new graph();
while (readgraph(*g, false)) {
if (bicoloredbfs(*g, 0))
cout << "BICOLORABLE." << endl;
else
cout << "NOT BICOLORABLE." << endl;
delete g;
g = new graph();
}
delete g;
return 0;
} | [
"ramirez.jpdf@ymail.com"
] | ramirez.jpdf@ymail.com |
1838d39fc88c7664d78bd5cee5c32705f02e3700 | b72a026e8f6a3f7e87c8aefcb7ae50031fea9c71 | /backend/backend/passengernode.cpp | 73648bb5a1527f4d0a1d4317de77499967ce6096 | [] | no_license | quoccuonglqd/CTDL2018-2019 | ab985f691168ffb4a972b9e324bb14b225eb2e5a | ecd6c3b023b32effec8b629276596b8e84b635a9 | refs/heads/master | 2020-06-11T22:46:19.463247 | 2019-06-27T14:17:23 | 2019-06-27T14:17:23 | 194,110,991 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 554 | cpp | #include "stdafx.h"
#include "passengernode.h"
passengernode * passengernode::getleft() const
{
return left;
}
passengernode * passengernode::getright() const
{
return right;
}
passengernode * passengernode::getpar() const
{
return par;
}
void passengernode::setleft(passengernode * src)
{
left = src;
}
void passengernode::setright(passengernode * src)
{
right = src;
}
void passengernode::setpar(passengernode * src)
{
par = src;
}
passengernode::passengernode()
{
left = right = par = nullptr;
}
passengernode::~passengernode()
{
}
| [
"quoccuonglqd123@gmail.com"
] | quoccuonglqd123@gmail.com |
a4ebdba4b4e5b0e8e0309dd4d8caaefef35a5642 | 2eb8c826a7d6d097f503a9fbc94ee4eaae09faeb | /C로배우는 자료구조/03장/3-14_재귀호출로_factorial_값_구하기/3-14.cpp | 68a462324c76ae53635beb07b63268c9cacbb0c4 | [] | no_license | kimth007kim/C_dataStructure | a93ef4b7ce4c30509ceb4fa32d588faec81e754b | 96cdbece50ed8d3c98de42ed14b5190b325cf2d6 | refs/heads/master | 2023-03-01T14:25:50.837999 | 2021-02-06T15:19:31 | 2021-02-06T15:19:31 | 321,634,656 | 1 | 0 | null | null | null | null | UHC | C++ | false | false | 526 | cpp | #include<stdio.h>
long int fact(int);
void main() {
int n, result;
printf("\n 정수를 입력하세요!! ");
scanf_s("%d", &n);
result = fact(n);
printf("\n\n %d의 factorial 값은 %ld입니다.\n", n, result);
getchar();
}
long int fact(int n)
{
int value;
if (n <= 1) {
printf("\n fact(1)함수 호출!");
printf("\n fact(1)값 1 반환!!");
return 1;
}
else {
printf("\n fact(%d)함수 호출!", n);
value = (n * fact(n - 1));
printf("\n fact(%d)값 %ld 반환!!", n, value);
return value;
}
} | [
"kimth007kim@naver.com"
] | kimth007kim@naver.com |
5b0230bd6ca0c645077030692a6fa632e67482f8 | fb61b5a0264d42d976ee383b7302779621aab327 | /02_OF_cylinder/ppWall/5/U | 2c8c31ab6f0d3b3848f62b8d0e5da58763e0db75 | [] | no_license | Ccaccia73/Aerodinamica | 31062b24a6893262000df2f3d53dde304969182a | 49485cde03a6a4fd569722c9ca4b3558825221ad | refs/heads/master | 2021-01-23T03:16:31.037716 | 2018-01-21T14:55:05 | 2018-01-21T14:55:05 | 86,064,538 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 10,328 | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: 4.1 |
| \\ / A nd | Web: www.OpenFOAM.org |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volVectorField;
location "5";
object U;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 1 -1 0 0 0 0];
internalField nonuniform List<vector>
400
(
(0.025 -1.63442e-16 0)
(0.025 -1.02891e-16 0)
(0.025 3.3873e-18 0)
(0.025 -7.86043e-18 0)
(0.025 7.16088e-18 0)
(0.025 -7.7648e-18 0)
(0.025 7.22531e-18 0)
(0.025 -3.61277e-18 0)
(0.025 3.95437e-19 0)
(0.025 -2.78522e-18 0)
(0.025 3.6346e-18 0)
(0.025 2.49842e-18 0)
(0.025 -2.16921e-18 0)
(0.025 -1.93857e-18 0)
(0.025 -4.705e-18 0)
(0.025 3.06388e-18 0)
(0.025 -1.88352e-18 0)
(0.025 4.00054e-18 0)
(0.025 -5.98892e-17 0)
(0.025 -9.46342e-17 0)
(0.075 -6.86875e-16 0)
(0.075 -5.12172e-16 0)
(0.075 -4.10061e-18 0)
(0.075 -2.4642e-17 0)
(0.075 2.15357e-17 0)
(0.075 -2.81892e-17 0)
(0.075 2.66668e-17 0)
(0.075 -9.70675e-18 0)
(0.075 -3.17665e-18 0)
(0.075 -1.00084e-17 0)
(0.075 1.57736e-17 0)
(0.075 1.3311e-17 0)
(0.075 -7.34549e-18 0)
(0.075 -1.43516e-17 0)
(0.075 -2.00545e-17 0)
(0.075 1.10498e-17 0)
(0.075 -6.00873e-18 0)
(0.075 1.54285e-17 0)
(0.075 -3.20519e-16 0)
(0.075 -4.31488e-16 0)
(0.125 -1.52225e-15 0)
(0.125 -1.27652e-15 0)
(0.125 -4.54593e-17 0)
(0.125 -3.96384e-17 0)
(0.125 3.41347e-17 0)
(0.125 -5.30348e-17 0)
(0.125 5.16068e-17 0)
(0.125 -1.42723e-17 0)
(0.125 -1.6441e-17 0)
(0.125 -2.01759e-17 0)
(0.125 3.8705e-17 0)
(0.125 3.24285e-17 0)
(0.125 -1.41058e-17 0)
(0.125 -4.02875e-17 0)
(0.125 -4.64532e-17 0)
(0.125 2.32484e-17 0)
(0.125 -1.01305e-17 0)
(0.125 2.83635e-17 0)
(0.125 -8.35877e-16 0)
(0.125 -1.02086e-15 0)
(0.175 -2.46166e-15 0)
(0.175 -2.21436e-15 0)
(0.175 -1.15884e-16 0)
(0.175 -4.56795e-17 0)
(0.175 4.22127e-17 0)
(0.175 -7.93279e-17 0)
(0.175 7.68652e-17 0)
(0.175 -1.33537e-17 0)
(0.175 -4.03005e-17 0)
(0.175 -3.21412e-17 0)
(0.175 6.72488e-17 0)
(0.175 5.7145e-17 0)
(0.175 -1.85104e-17 0)
(0.175 -7.51122e-17 0)
(0.175 -8.00405e-17 0)
(0.175 3.7998e-17 0)
(0.175 -1.31194e-17 0)
(0.175 4.22554e-17 0)
(0.175 -1.50708e-15 0)
(0.175 -1.74389e-15 0)
(0.225 -3.35311e-15 0)
(0.225 -3.16604e-15 0)
(0.225 -2.03295e-16 0)
(0.225 -4.14634e-17 0)
(0.225 4.41501e-17 0)
(0.225 -1.06422e-16 0)
(0.225 1.03468e-16 0)
(0.225 -7.54734e-18 0)
(0.225 -7.34495e-17 0)
(0.225 -4.78043e-17 0)
(0.225 1.01886e-16 0)
(0.225 8.32988e-17 0)
(0.225 -2.0438e-17 0)
(0.225 -1.14388e-16 0)
(0.225 -1.13803e-16 0)
(0.225 5.51259e-17 0)
(0.225 -1.81307e-17 0)
(0.225 5.18157e-17 0)
(0.225 -2.2341e-15 0)
(0.225 -2.49728e-15 0)
(0.275 -4.09107e-15 0)
(0.275 -4.00756e-15 0)
(0.275 -2.92567e-16 0)
(0.275 -3.19341e-17 0)
(0.275 4.22998e-17 0)
(0.275 -1.30287e-16 0)
(0.275 1.28669e-16 0)
(0.275 5.24956e-18 0)
(0.275 -1.11347e-16 0)
(0.275 -6.88367e-17 0)
(0.275 1.36818e-16 0)
(0.275 1.08514e-16 0)
(0.275 -1.57828e-17 0)
(0.275 -1.52772e-16 0)
(0.275 -1.48301e-16 0)
(0.275 7.05401e-17 0)
(0.275 -2.19275e-17 0)
(0.275 5.73473e-17 0)
(0.275 -2.93229e-15 0)
(0.275 -3.1966e-15 0)
(0.325 -4.60325e-15 0)
(0.325 -4.64796e-15 0)
(0.325 -3.76358e-16 0)
(0.325 -1.60505e-17 0)
(0.325 3.707e-17 0)
(0.325 -1.49847e-16 0)
(0.325 1.53995e-16 0)
(0.325 1.82288e-17 0)
(0.325 -1.51595e-16 0)
(0.325 -8.92879e-17 0)
(0.325 1.67683e-16 0)
(0.325 1.30057e-16 0)
(0.325 -7.13734e-18 0)
(0.325 -1.8552e-16 0)
(0.325 -1.80517e-16 0)
(0.325 8.03663e-17 0)
(0.325 -2.04971e-17 0)
(0.325 6.18502e-17 0)
(0.325 -3.53506e-15 0)
(0.325 -3.77985e-15 0)
(0.375 -4.84633e-15 0)
(0.375 -5.02838e-15 0)
(0.375 -4.4697e-16 0)
(0.375 3.43088e-18 0)
(0.375 3.09221e-17 0)
(0.375 -1.64555e-16 0)
(0.375 1.81019e-16 0)
(0.375 2.75651e-17 0)
(0.375 -1.94577e-16 0)
(0.375 -1.03217e-16 0)
(0.375 1.94797e-16 0)
(0.375 1.45321e-16 0)
(0.375 4.92203e-18 0)
(0.375 -2.10282e-16 0)
(0.375 -2.08516e-16 0)
(0.375 8.37388e-17 0)
(0.375 -1.29865e-17 0)
(0.375 6.33526e-17 0)
(0.375 -3.98719e-15 0)
(0.375 -4.19071e-15 0)
(0.425 -4.80648e-15 0)
(0.425 -5.12694e-15 0)
(0.425 -4.94139e-16 0)
(0.425 2.80945e-17 0)
(0.425 1.9392e-17 0)
(0.425 -1.68989e-16 0)
(0.425 2.01054e-16 0)
(0.425 3.49329e-17 0)
(0.425 -2.36454e-16 0)
(0.425 -1.10146e-16 0)
(0.425 2.19307e-16 0)
(0.425 1.49498e-16 0)
(0.425 1.4915e-17 0)
(0.425 -2.1969e-16 0)
(0.425 -2.27499e-16 0)
(0.425 7.79375e-17 0)
(0.425 -1.36894e-18 0)
(0.425 6.66469e-17 0)
(0.425 -4.24856e-15 0)
(0.425 -4.39552e-15 0)
(0.475 -4.49542e-15 0)
(0.475 -4.94428e-15 0)
(0.475 -5.08008e-16 0)
(0.475 5.39534e-17 0)
(0.475 2.46781e-18 0)
(0.475 -1.63248e-16 0)
(0.475 2.11683e-16 0)
(0.475 4.14842e-17 0)
(0.475 -2.68841e-16 0)
(0.475 -1.19613e-16 0)
(0.475 2.36995e-16 0)
(0.475 1.45162e-16 0)
(0.475 2.62059e-17 0)
(0.475 -2.16309e-16 0)
(0.475 -2.37383e-16 0)
(0.475 6.52932e-17 0)
(0.475 1.02234e-17 0)
(0.475 6.96942e-17 0)
(0.475 -4.29586e-15 0)
(0.475 -4.37761e-15 0)
(0.525 -3.9569e-15 0)
(0.525 -4.50333e-15 0)
(0.525 -4.91101e-16 0)
(0.525 7.28154e-17 0)
(0.525 -1.5306e-17 0)
(0.525 -1.47715e-16 0)
(0.525 2.14994e-16 0)
(0.525 4.15118e-17 0)
(0.525 -2.86744e-16 0)
(0.525 -1.23231e-16 0)
(0.525 2.42765e-16 0)
(0.525 1.29883e-16 0)
(0.525 3.95682e-17 0)
(0.525 -2.03943e-16 0)
(0.525 -2.39939e-16 0)
(0.525 5.54614e-17 0)
(0.525 1.72156e-17 0)
(0.525 7.15347e-17 0)
(0.525 -4.13098e-15 0)
(0.525 -4.14184e-15 0)
(0.575 -3.24452e-15 0)
(0.575 -3.86334e-15 0)
(0.575 -4.49835e-16 0)
(0.575 8.39648e-17 0)
(0.575 -3.25721e-17 0)
(0.575 -1.22815e-16 0)
(0.575 2.11093e-16 0)
(0.575 4.10279e-17 0)
(0.575 -2.95383e-16 0)
(0.575 -1.23126e-16 0)
(0.575 2.39401e-16 0)
(0.575 1.10639e-16 0)
(0.575 4.70455e-17 0)
(0.575 -1.86629e-16 0)
(0.575 -2.26491e-16 0)
(0.575 4.43936e-17 0)
(0.575 1.95724e-17 0)
(0.575 7.40034e-17 0)
(0.575 -3.77932e-15 0)
(0.575 -3.71481e-15 0)
(0.625 -2.43462e-15 0)
(0.625 -3.09685e-15 0)
(0.625 -3.89103e-16 0)
(0.625 9.15862e-17 0)
(0.625 -5.53413e-17 0)
(0.625 -9.2049e-17 0)
(0.625 1.97694e-16 0)
(0.625 4.92682e-17 0)
(0.625 -2.86074e-16 0)
(0.625 -1.31198e-16 0)
(0.625 2.24112e-16 0)
(0.625 1.00604e-16 0)
(0.625 4.84322e-17 0)
(0.625 -1.71422e-16 0)
(0.625 -1.95471e-16 0)
(0.625 3.15861e-17 0)
(0.625 1.68603e-17 0)
(0.625 7.65407e-17 0)
(0.625 -3.27573e-15 0)
(0.625 -3.14452e-15 0)
(0.675 -1.60897e-15 0)
(0.675 -2.2873e-15 0)
(0.675 -3.23073e-16 0)
(0.675 1.01992e-16 0)
(0.675 -7.70956e-17 0)
(0.675 -5.32052e-17 0)
(0.675 1.72744e-16 0)
(0.675 5.33235e-17 0)
(0.675 -2.60213e-16 0)
(0.675 -1.31635e-16 0)
(0.675 1.98584e-16 0)
(0.675 8.53645e-17 0)
(0.675 4.1368e-17 0)
(0.675 -1.61535e-16 0)
(0.675 -1.49546e-16 0)
(0.675 2.80224e-17 0)
(0.675 1.04492e-17 0)
(0.675 7.29014e-17 0)
(0.675 -2.66916e-15 0)
(0.675 -2.49328e-15 0)
(0.725 -8.59153e-16 0)
(0.725 -1.51893e-15 0)
(0.725 -2.55465e-16 0)
(0.725 1.06832e-16 0)
(0.725 -8.3744e-17 0)
(0.725 -2.01515e-17 0)
(0.725 1.33649e-16 0)
(0.725 5.24927e-17 0)
(0.725 -2.15596e-16 0)
(0.725 -1.25797e-16 0)
(0.725 1.67299e-16 0)
(0.725 6.20418e-17 0)
(0.725 3.22885e-17 0)
(0.725 -1.40618e-16 0)
(0.725 -1.04089e-16 0)
(0.725 2.29693e-17 0)
(0.725 3.00429e-18 0)
(0.725 6.34064e-17 0)
(0.725 -2.02744e-15 0)
(0.725 -1.82022e-15 0)
(0.775 -2.57206e-16 0)
(0.775 -8.69856e-16 0)
(0.775 -1.87093e-16 0)
(0.775 9.78688e-17 0)
(0.775 -8.2131e-17 0)
(0.775 7.89345e-18 0)
(0.775 9.10133e-17 0)
(0.775 3.63829e-17 0)
(0.775 -1.64375e-16 0)
(0.775 -1.02599e-16 0)
(0.775 1.30585e-16 0)
(0.775 4.15056e-17 0)
(0.775 2.13665e-17 0)
(0.775 -1.13225e-16 0)
(0.775 -5.8307e-17 0)
(0.775 1.94477e-17 0)
(0.775 -6.27511e-18 0)
(0.775 4.951e-17 0)
(0.775 -1.40469e-15 0)
(0.775 -1.18445e-15 0)
(0.825 1.4001e-16 0)
(0.825 -3.88237e-16 0)
(0.825 -1.28826e-16 0)
(0.825 7.12279e-17 0)
(0.825 -7.33466e-17 0)
(0.825 3.40088e-17 0)
(0.825 5.35721e-17 0)
(0.825 1.57367e-17 0)
(0.825 -1.20495e-16 0)
(0.825 -6.41861e-17 0)
(0.825 9.01961e-17 0)
(0.825 2.48468e-17 0)
(0.825 1.24278e-17 0)
(0.825 -8.36437e-17 0)
(0.825 -1.94592e-17 0)
(0.825 1.12115e-17 0)
(0.825 -1.40556e-17 0)
(0.825 3.41836e-17 0)
(0.825 -8.50665e-16 0)
(0.825 -6.46288e-16 0)
(0.875 2.92156e-16 0)
(0.875 -9.3292e-17 0)
(0.875 -8.02891e-17 0)
(0.875 4.00281e-17 0)
(0.875 -5.20977e-17 0)
(0.875 4.20719e-17 0)
(0.875 2.4081e-17 0)
(0.875 1.24121e-18 0)
(0.875 -7.68219e-17 0)
(0.875 -3.20565e-17 0)
(0.875 5.45158e-17 0)
(0.875 1.24346e-17 0)
(0.875 7.46547e-18 0)
(0.875 -4.66554e-17 0)
(0.875 -1.86172e-18 0)
(0.875 -3.11424e-18 0)
(0.875 -1.53548e-17 0)
(0.875 2.61e-17 0)
(0.875 -4.15422e-16 0)
(0.875 -2.53619e-16 0)
(0.925 2.46104e-16 0)
(0.925 1.9431e-17 0)
(0.925 -4.02636e-17 0)
(0.925 1.84241e-17 0)
(0.925 -3.04405e-17 0)
(0.925 3.05673e-17 0)
(0.925 1.06717e-17 0)
(0.925 -4.62345e-18 0)
(0.925 -4.19307e-17 0)
(0.925 -1.35844e-17 0)
(0.925 3.18854e-17 0)
(0.925 3.71058e-18 0)
(0.925 8.24278e-18 0)
(0.925 -1.9177e-17 0)
(0.925 3.87005e-19 0)
(0.925 -6.99901e-18 0)
(0.925 -9.3528e-18 0)
(0.925 1.37353e-17 0)
(0.925 -1.36414e-16 0)
(0.925 -3.50476e-17 0)
(0.975 9.21789e-17 0)
(0.975 1.9269e-17 0)
(0.975 -1.20951e-17 0)
(0.975 4.45301e-18 0)
(0.975 -9.59767e-18 0)
(0.975 1.11509e-17 0)
(0.975 2.59073e-19 0)
(0.975 -1.91008e-18 0)
(0.975 -1.14918e-17 0)
(0.975 -2.98895e-18 0)
(0.975 9.78727e-18 0)
(0.975 -4.76877e-19 0)
(0.975 1.94634e-18 0)
(0.975 -3.28777e-18 0)
(0.975 -1.50696e-18 0)
(0.975 -4.59078e-18 0)
(0.975 -5.28051e-19 0)
(0.975 2.69132e-18 0)
(0.975 -1.72461e-17 0)
(0.975 1.34087e-17 0)
)
;
boundaryField
{
top
{
type fixedValue;
value uniform (1 0 0);
}
bottom
{
type fixedValue;
value uniform (0 0 0);
}
inlet
{
type zeroGradient;
}
outlet
{
type zeroGradient;
}
frontAndBack
{
type empty;
}
}
// ************************************************************************* //
| [
"c.caccia@libero.it"
] | c.caccia@libero.it | |
c78c28e786c707ef691a7ee1430e22affa1df716 | 54bd24a7ec00e2128e74704833035740926fe1a2 | /c3dEngine2/c3dEngine/c3dEngine/platform/win32/appFrame/mainWindowGlobal.cpp | 0616e9ea5140a25de95191681d4b717bd01f47d1 | [
"MIT"
] | permissive | qaz734913414/c3dEngine2 | 3739073d7d6f1046cdfce19ca7a5fdc9c7a9bada | 0c12d077d8f2bac8c12b8f720eccc5a2f3f3a7c1 | refs/heads/master | 2020-04-15T19:47:52.391730 | 2015-12-14T16:07:29 | 2015-12-14T16:07:29 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 479 | cpp | #include "mainWindowGlobal.h"
//global var
bool isTouching;
long tf=0,t=0,dt=0;//tf上次进入idle,t本次进入idle,dt本次与上次进入idle时间间隔--abc
float captionHeight=0;//标题栏高度--abc
float frameBoarder=0;//窗口边框宽度--abc
//win32 global var
HDC hDC=NULL; // Private GDI Device Context
HGLRC hRC=NULL; // Permanent Rendering Context
HWND hWnd=NULL; // Holds Our Window Handle
HINSTANCE hInstance; // Holds The Instance Of The Application | [
"350479720@qq.com"
] | 350479720@qq.com |
1e6a0b3ca628c1fa0dcef34af9fda0d341923cf1 | c2672fa922da6f0c292206c99a551565a145d942 | /crazyclient/frameworks/cocos2d-x/cocos/scripting/lua-bindings/manual/cocostudio/lua-cocos-studio-conversions.cpp | b0044442be3dad998f90d39ff4f4adf08e5c543a | [
"MIT"
] | permissive | lache/RacingKingLee | 2b37d7962766cfc99cacc1949e55bd055715414b | eb3a961c6c71d44e797eb2394613e4c8196feb31 | refs/heads/master | 2022-11-09T02:24:15.448152 | 2015-07-27T16:40:09 | 2015-07-27T16:40:09 | 36,938,174 | 0 | 1 | MIT | 2022-10-27T05:03:56 | 2015-06-05T14:47:06 | C++ | UTF-8 | C++ | false | false | 3,174 | cpp | /****************************************************************************
Copyright (c) 2013-2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
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.
****************************************************************************/
#include "lua-cocos-studio-conversions.h"
#include "ActionTimeline/CCActionTimeline.h"
#if COCOS2D_DEBUG >=1
extern void luaval_to_native_err(lua_State* L,const char* msg,tolua_Error* err, const char* funcName);
#endif
bool luaval_to_animationInfo(lua_State* L, int lo, cocostudio::timeline::AnimationInfo* outValue , const char* funcName)
{
if (nullptr == L || nullptr == outValue)
return false;
bool ok = true;
tolua_Error tolua_err;
if (!tolua_istable(L, lo, 0, &tolua_err) )
{
#if COCOS2D_DEBUG >=1
luaval_to_native_err(L,"#ferror:",&tolua_err,funcName);
#endif
ok = false;
}
if (ok)
{
lua_pushstring(L, "name"); /* L: paramStack key */
lua_gettable(L,lo); /* L: paramStack paramStack[lo][key] */
outValue->name = lua_isstring(L, -1)? lua_tostring(L, -1) : "";
lua_pop(L,1); /* L: paramStack*/
lua_pushstring(L, "startIndex");
lua_gettable(L,lo);
outValue->startIndex = lua_isnumber(L, -1)?(int)lua_tonumber(L, -1) : 0;
lua_pop(L,1);
lua_pushstring(L, "endIndex");
lua_gettable(L, lo);
outValue->endIndex = lua_isnumber(L, -1)?(int)lua_tonumber(L, -1) : 0;
lua_pop(L, 1);
return true;
}
return false;
}
void animationInfo_to_luaval(lua_State* L,const cocostudio::timeline::AnimationInfo& inValue)
{
if (nullptr == L)
return;
lua_newtable(L);
lua_pushstring(L, "name");
lua_pushstring(L, inValue.name.c_str());
lua_rawset(L, -3);
lua_pushstring(L, "startIndex");
lua_pushnumber(L, (lua_Number)inValue.startIndex);
lua_rawset(L, -3);
lua_pushstring(L, "endIndex");
lua_pushnumber(L, (lua_Number)inValue.endIndex);
lua_rawset(L, -3);
}
| [
"gasbank@msn.com"
] | gasbank@msn.com |
ed55f5d416a845e1c57846fbc85989bca8e1612d | 709b54207de45074aede80d7f4cf8373f15a208a | /CPP/Special Palindrome Again/SpecialPalindromeAgain.cpp | 259e80eb0865cd9499fa8ee3d9cea3ff2a8a7645 | [] | no_license | codemasa/Hackerrank | 40f5b86d9f3680fc3fe62434e4d82bffa7f31961 | a82ed18680e18656609dd7658875fd8f25764156 | refs/heads/master | 2020-03-30T21:37:48.245959 | 2019-05-23T16:05:05 | 2019-05-23T16:05:05 | 151,635,401 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 415 | cpp | #include <bits/stdc++.h>
using namespace std;
// Complete the substrCount function below.
long substrCount(int n, string s) {
}
int main()
{
ofstream fout(getenv("OUTPUT_PATH"));
int n;
cin >> n;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
string s;
getline(cin, s);
long result = substrCount(n, s);
fout << result << "\n";
fout.close();
return 0;
}
| [
"cody.masao@gmail.com"
] | cody.masao@gmail.com |
3e10ed5e09663fbf07c1c714ff2e2fafa207925d | 49fc9092d53d1c06843986e57cf3b7e63007acdf | /include/shipeditordlg.h | 8752155ef01b62b8e2d9722b4ce825ec264cf455 | [] | no_license | ptitSeb/freespace2 | 8615e5c55b9a19bdf280bc0e0b164f9e33640045 | 500ee249f7033aac9b389436b1737a404277259c | refs/heads/master | 2020-09-20T19:13:59.618314 | 2019-01-02T10:51:59 | 2019-01-02T10:51:59 | 67,286,355 | 9 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 7,869 | h | /*
* Copyright (C) Volition, Inc. 1999. All rights reserved.
*
* All source code herein is the property of Volition, Inc. You may not sell
* or otherwise commercially exploit the source or things you created based on
* the source.
*/
/*
* $Logfile: /Freespace2/code/Fred2/ShipEditorDlg.h $
* $Revision: 110 $
* $Date: 2002-06-09 06:41:30 +0200 (Sun, 09 Jun 2002) $
* $Author: relnev $
*
* Single ship editing dialog
*
* $Log$
* Revision 1.2 2002/06/09 04:41:15 relnev
* added copyright header
*
* Revision 1.1.1.1 2002/05/03 03:28:12 root
* Initial import.
*
*
* 4 5/20/99 7:00p Dave
* Added alternate type names for ships. Changed swarm missile table
* entries.
*
* 3 2/11/99 2:15p Andsager
* Add ship explosion modification to FRED
*
* 2 10/07/98 6:28p Dave
* Initial checkin. Renamed all relevant stuff to be Fred2 instead of
* Fred. Globalized mission and campaign file extensions. Removed Silent
* Threat specific code.
*
* 1 10/07/98 3:01p Dave
*
* 1 10/07/98 3:00p Dave
*
* 65 4/07/98 9:42a Allender
* put in persona combo box into ship editor. Removed code to assign
* personas based on message
*
* 64 3/27/98 12:02p Sandeep
*
* 63 3/25/98 4:14p Hoffoss
* Split ship editor up into ship editor and a misc dialog, which tracks
* flags and such.
*
* 62 3/16/98 8:27p Allender
* Fred support for two new AI flags -- kamikaze and no dynamic goals.
*
* 61 3/09/98 4:30p Allender
* multiplayer secondary weapon changes. red-alert and cargo-known-delay
* sexpressions. Add time cargo revealed to ship structure
*
* 60 2/17/98 11:42a Hoffoss
* Added support for hidden from sensors condition.
*
* 59 2/06/98 2:54p Hoffoss
* Fixed some bugs in dialog init, and cleared up some of the confusion
* about how it works by renaming some variables and adding comments.
*
* 58 1/29/98 5:14p Hoffoss
* Added support for a SF_INVULNERABLE ship flag in Fred.
*
* 57 11/13/97 4:14p Allender
* automatic assignment of hotkeys for starting wings. Appripriate
* warnings when they are incorrectly used. hotkeys correctly assigned to
* ships/wing arriving after mission start
*
* 56 11/10/97 10:13p Allender
* added departure anchor to Fred and Freespace in preparation for using
* docking bays. Functional in Fred, not in FreeSpace.
*
* 55 10/21/97 4:49p Allender
* added flags to Fred and FreeSpace to forgo warp effect (toggle in ship
* editor in Fred)
*
* 54 10/14/97 5:33p Hoffoss
* Added Fred support (and fsm support) for the no_arrival_music flags in
* ships and wings.
*
* 53 9/17/97 5:43p Hoffoss
* Added Fred support for new player start information.
*
* 52 9/04/97 4:31p Hoffoss
* Fixed bug: Changed ship editor to not touch wing info (arrival or
* departure cues) to avoid conflicts with wing editor's changes.
*
* 51 8/30/97 9:52p Hoffoss
* Implemented arrival location, distance, and anchor in Fred.
*
* 50 8/25/97 5:56p Hoffoss
* Added multiple asteroid field support, loading and saving of asteroid
* fields, and ship score field to Fred.
*
* 49 8/20/97 6:53p Hoffoss
* Implemented escort flag support in Fred.
*
* 48 8/16/97 12:06p Hoffoss
* Fixed bug where a whole wing is deleted that is being referenced.
*
* 47 8/12/97 7:17p Hoffoss
* Added previous button to ship and wing editors.
*
* 46 8/12/97 6:32p Hoffoss
* Added code to allow hiding of arrival and departure cues in editors.
*
* 45 8/08/97 1:31p Hoffoss
* Added syncronization protection to cur_object_index changes.
*
* $NoKeywords: $
*/
#ifndef _SHIPEDITORDLG_H
#define _SHIPEDITORDLG_H
#include "sexp_tree.h"
#include "shipgoalsdlg.h"
#include "management.h"
/////////////////////////////////////////////////////////////////////////////
// CShipEditorDlg dialog
#define WM_GOODBYE (WM_USER+5)
#define ID_ALWAYS_ON_TOP 0x0f00
class numeric_edit_control
{
int value;
int unique;
int control_id;
CWnd *dlg;
public:
void setup(int id, CWnd *wnd);
void blank() { unique = 0; }
void init(int n);
void set(int n);
void display();
void save(int *n);
void fix(int n);
};
class CShipEditorDlg : public CDialog
{
private:
int make_ship_list(int *arr);
int update_ship(int ship);
int initialized;
int multi_edit;
int always_on_top;
int cue_height;
int mission_type; // indicates if single player(1) or multiplayer(0)
CView* m_pSEView;
CCriticalSection CS_update;
// Construction
public:
int player_ship, single_ship;
int editing;
int modified;
int select_sexp_node;
int bypass_errors;
int bypass_all;
int enable; // used to enable(1)/disable(0) controls based on if any ship selected
int p_enable; // used to enable(1)/disable(0) controls based on if a player ship
int tristate_set(int val, int cur_state);
void show_hide_sexp_help();
void calc_cue_height();
int verify();
void OnInitMenu(CMenu *m);
void OnOK();
int update_data(int redraw = 1);
void initialize_data(int full);
CShipEditorDlg(CWnd* pParent = NULL); // standard constructor
CShipEditorDlg(CView* pView);
// alternate ship name stuff
void ship_alt_name_init(int base_ship);
void ship_alt_name_close(int base_ship);
BOOL Create();
// Dialog Data
//{{AFX_DATA(CShipEditorDlg)
enum { IDD = IDD_SHIP_EDITOR };
CButton m_no_departure_warp;
CButton m_no_arrival_warp;
CButton m_player_ship;
CSpinButtonCtrl m_destroy_spin;
CSpinButtonCtrl m_departure_delay_spin;
CSpinButtonCtrl m_arrival_delay_spin;
sexp_tree m_departure_tree;
sexp_tree m_arrival_tree;
CString m_ship_name;
CString m_cargo1;
int m_ship_class;
int m_team;
int m_arrival_location;
int m_departure_location;
int m_ai_class;
numeric_edit_control m_arrival_delay;
numeric_edit_control m_departure_delay;
int m_hotkey;
BOOL m_update_arrival;
BOOL m_update_departure;
numeric_edit_control m_destroy_value;
numeric_edit_control m_score;
numeric_edit_control m_arrival_dist;
numeric_edit_control m_kdamage;
int m_arrival_target;
int m_departure_target;
int m_persona;
//}}AFX_DATA
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CShipEditorDlg)
public:
virtual BOOL Create(LPCTSTR lpszClassName, LPCTSTR lpszWindowName, DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID, CCreateContext* pContext = NULL);
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
virtual BOOL OnCommand(WPARAM wParam, LPARAM lParam);
//}}AFX_VIRTUAL
// Implementation
protected:
// Generated message map functions
//{{AFX_MSG(CShipEditorDlg)
afx_msg void OnClose();
afx_msg void OnRclickArrivalTree(NMHDR* pNMHDR, LRESULT* pResult);
afx_msg void OnRclickDepartureTree(NMHDR* pNMHDR, LRESULT* pResult);
afx_msg void OnBeginlabeleditArrivalTree(NMHDR* pNMHDR, LRESULT* pResult);
afx_msg void OnBeginlabeleditDepartureTree(NMHDR* pNMHDR, LRESULT* pResult);
afx_msg void OnEndlabeleditArrivalTree(NMHDR* pNMHDR, LRESULT* pResult);
afx_msg void OnEndlabeleditDepartureTree(NMHDR* pNMHDR, LRESULT* pResult);
afx_msg void OnGoals();
afx_msg void OnSelchangeShipClass();
afx_msg void OnInitialStatus();
afx_msg void OnWeapons();
afx_msg void OnShipReset();
afx_msg void OnDeleteShip();
afx_msg void OnShipTbl();
afx_msg void OnNext();
afx_msg void OnSelchangedArrivalTree(NMHDR* pNMHDR, LRESULT* pResult);
afx_msg void OnSelchangedDepartureTree(NMHDR* pNMHDR, LRESULT* pResult);
afx_msg void OnHideCues();
afx_msg void OnPrev();
afx_msg void OnSelchangeArrivalLocation();
afx_msg void OnPlayerShip();
afx_msg void OnNoArrivalWarp();
afx_msg void OnNoDepartureWarp();
afx_msg void OnSelchangeDepartureLocation();
afx_msg void OnSelchangeHotkey();
afx_msg void OnFlags();
afx_msg void OnIgnoreOrders();
afx_msg void OnSpecialExp();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
#endif
| [
"sebastien.chev@gmail.com"
] | sebastien.chev@gmail.com |
8ef003f4e85e511c0438ebe75fee7990ba1936b1 | 290575cb248a2d31ee83d329bf4cf0fb9cb82950 | /server/ppm-reader.cc | 38be77618c0dcac5494e40ea476d7a91a39d662b | [] | no_license | scottyallen/flaschen-taschen | cc8bda61df3e8ea43aa9a7dae1b92f16bf4342fa | 9cd03255154ceac7cd8fd93a0079ab3e3348f5a1 | refs/heads/master | 2020-04-05T23:38:18.586179 | 2016-05-06T17:43:15 | 2016-05-10T04:25:39 | 58,512,269 | 0 | 1 | null | 2016-05-11T03:43:42 | 2016-05-11T03:43:39 | null | UTF-8 | C++ | false | false | 3,539 | cc | // -*- mode: c++; c-basic-offset: 4; indent-tabs-mode: nil; -*-
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation version 2.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://gnu.org/licenses/gpl-2.0.txt>
// Very simple ppm reader.
#include "ppm-reader.h"
#include <stdlib.h>
#include <ctype.h>
static const char *skipWhitespace(const char *buffer, const char *end) {
for (;;) {
while (buffer < end && isspace(*buffer))
++buffer;
if (buffer >= end)
return NULL;
if (*buffer == '#') {
while (buffer < end && *buffer != '\n') // read to end of line.
++buffer;
continue; // Back to whitespace eating.
}
return buffer;
}
}
// Read next number. Start reading at *start; modifies the *start pointer
// to point to the character just after the decimal number or NULL if reading
// was not successful.
static int readNextNumber(const char **start, const char *end) {
const char *start_number = skipWhitespace(*start, end);
if (start_number == NULL) { *start = NULL; return 0; }
char *end_number = NULL;
int result = strtol(start_number, &end_number, 10);
if (end_number == start_number) { *start = NULL; return 0; }
*start = end_number;
return result;
}
const char *ReadImageData(const char *in_buffer, size_t buf_len,
struct ImageMetaInfo *info) {
if (in_buffer[0] != 'P' || in_buffer[1] != '6' ||
(!isspace(in_buffer[2]) && in_buffer[2] != '#')) {
return in_buffer; // raw image. No P6 magic header.
}
const char *const end = in_buffer + buf_len;
const char *parse_buffer = in_buffer + 2;
const int width = readNextNumber(&parse_buffer, end);
if (parse_buffer == NULL) return in_buffer;
const int height = readNextNumber(&parse_buffer, end);
if (parse_buffer == NULL) return in_buffer;
const int range = readNextNumber(&parse_buffer, end);
if (parse_buffer == NULL) return in_buffer;
if (!isspace(*parse_buffer++)) return in_buffer; // last char before data
// Now make sure that the rest of the buffer still makes sense
const size_t expected_image_data = width * height * 3;
const size_t actual_data = end - parse_buffer;
if (actual_data < expected_image_data)
return in_buffer; // Uh, not enough data.
if (actual_data > expected_image_data) {
// Our extension: at the end of the binary data, we provide an optional
// offset. We can't store it in the header, as it is fixed in number
// of fields. But nobody cares what is at the end of the buffer.
const char *offset_data = parse_buffer + expected_image_data;
info->offset_x = readNextNumber(&offset_data, end);
if (offset_data != NULL) {
info->offset_y = readNextNumber(&offset_data, end);
}
if (offset_data != NULL) {
info->layer = readNextNumber(&offset_data, end);
}
}
info->width = width;
info->height = height;
info->range = range;
return parse_buffer;
}
| [
"h.zeller@acm.org"
] | h.zeller@acm.org |
80ead1a20f7c2c0100b176d566c510ea12385c0f | 10854fab019a83ad29f4e16fe45616720c95d75b | /MilesMacklin-Sandbox/core/vec2.h | 83f132fa2f273b0c5be8e75a513323d87f22b165 | [] | no_license | Woking-34/daedalus-playground | 2e928e95f371196d039e035ef035a90ad468c5e5 | 41a884194aa8b42e1aa2ecbc76e71b1390e085ba | refs/heads/master | 2021-06-16T03:35:19.755817 | 2021-05-29T10:52:44 | 2021-05-29T10:52:44 | 175,941,574 | 8 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 4,011 | h | #pragma once
#if defined(_WIN32) && !defined(__CUDACC__)
#if defined(_DEBUG)
#define VEC2_VALIDATE() { assert(_finite(x));\
assert(!_isnan(x));\
\
assert(_finite(y));\
assert(!_isnan(y));\
}
#else
#define VEC2_VALIDATE() {\
assert(isfinite(x));\
assert(isfinite(y)); }\
#endif // _WIN32
#else
#define VEC2_VALIDATE()
#endif
#ifdef _DEBUG
#define FLOAT_VALIDATE(f) { assert(_finite(f)); assert(!_isnan(f)); }
#else
#define FLOAT_VALIDATE(f)
#endif
// vec2
template <typename T>
class XVector2
{
public:
typedef T value_type;
CUDA_CALLABLE XVector2() : x(0.0f), y(0.0f) { VEC2_VALIDATE(); }
CUDA_CALLABLE XVector2(T _x) : x(_x), y(_x) { VEC2_VALIDATE(); }
CUDA_CALLABLE XVector2(T _x, T _y) : x(_x), y(_y) { VEC2_VALIDATE(); }
CUDA_CALLABLE XVector2(const T* p) : x(p[0]), y(p[1]) {}
template <typename U>
CUDA_CALLABLE explicit XVector2(const XVector2<U>& v) : x(v.x), y(v.y) {}
CUDA_CALLABLE operator T* () { return &x; }
CUDA_CALLABLE operator const T* () const { return &x; };
CUDA_CALLABLE void Set(T x_, T y_) { VEC2_VALIDATE(); x = x_; y = y_; }
CUDA_CALLABLE XVector2<T> operator * (T scale) const { XVector2<T> r(*this); r *= scale; VEC2_VALIDATE(); return r; }
CUDA_CALLABLE XVector2<T> operator / (T scale) const { XVector2<T> r(*this); r /= scale; VEC2_VALIDATE(); return r; }
CUDA_CALLABLE XVector2<T> operator + (const XVector2<T>& v) const { XVector2<T> r(*this); r += v; VEC2_VALIDATE(); return r; }
CUDA_CALLABLE XVector2<T> operator - (const XVector2<T>& v) const { XVector2<T> r(*this); r -= v; VEC2_VALIDATE(); return r; }
CUDA_CALLABLE XVector2<T>& operator *=(T scale) {x *= scale; y *= scale; VEC2_VALIDATE(); return *this;}
CUDA_CALLABLE XVector2<T>& operator /=(T scale) {T s(1.0f/scale); x *= s; y *= s; VEC2_VALIDATE(); return *this;}
CUDA_CALLABLE XVector2<T>& operator +=(const XVector2<T>& v) {x += v.x; y += v.y; VEC2_VALIDATE(); return *this;}
CUDA_CALLABLE XVector2<T>& operator -=(const XVector2<T>& v) {x -= v.x; y -= v.y; VEC2_VALIDATE(); return *this;}
CUDA_CALLABLE XVector2<T>& operator *=(const XVector2<T>& scale) {x *= scale.x; y *= scale.y; VEC2_VALIDATE(); return *this;}
// negate
CUDA_CALLABLE XVector2<T> operator -() const { VEC2_VALIDATE(); return XVector2<T>(-x, -y); }
// returns this vector
CUDA_CALLABLE void Normalize() { *this /= Length(*this); }
CUDA_CALLABLE void SafeNormalize(const XVector2<T>& v=XVector2<T>(0.0f,0.0f))
{
T length = Length(*this);
*this = (length==0.00001f)?v:(*this /= length);
}
T x;
T y;
};
typedef XVector2<float> Vec2;
typedef XVector2<float> Vector2;
// lhs scalar scale
template <typename T>
CUDA_CALLABLE XVector2<T> operator *(T lhs, const XVector2<T>& rhs)
{
XVector2<T> r(rhs);
r *= lhs;
return r;
}
template <typename T>
CUDA_CALLABLE XVector2<T> operator*(const XVector2<T>& lhs, const XVector2<T>& rhs)
{
XVector2<T> r(lhs);
r *= rhs;
return r;
}
template <typename T>
CUDA_CALLABLE bool operator==(const XVector2<T>& lhs, const XVector2<T>& rhs)
{
return (lhs.x == rhs.x && lhs.y == rhs.y);
}
template <typename T>
CUDA_CALLABLE T Dot(const XVector2<T>& v1, const XVector2<T>& v2)
{
return v1.x * v2.x + v1.y * v2.y;
}
// returns the ccw perpendicular vector
template <typename T>
CUDA_CALLABLE XVector2<T> PerpCCW(const XVector2<T>& v)
{
return XVector2<T>(-v.y, v.x);
}
template <typename T>
CUDA_CALLABLE XVector2<T> PerpCW(const XVector2<T>& v)
{
return XVector2<T>(v.y, -v.x);
}
// component wise min max functions
template <typename T>
CUDA_CALLABLE XVector2<T> Max(const XVector2<T>& a, const XVector2<T>& b)
{
return XVector2<T>(Max(a.x, b.x), Max(a.y, b.y));
}
template <typename T>
CUDA_CALLABLE XVector2<T> Min(const XVector2<T>& a, const XVector2<T>& b)
{
return XVector2<T>(Min(a.x, b.x), Min(a.y, b.y));
}
// 2d cross product, treat as if a and b are in the xy plane and return magnitude of z
template <typename T>
CUDA_CALLABLE T Cross(const XVector2<T>& a, const XVector2<T>& b)
{
return (a.x*b.y - a.y*b.x);
}
| [
"m_nyers@yahoo.com"
] | m_nyers@yahoo.com |
060f7a8ba41e89bd99fa7921b39c1143602e9e6c | c681c3fb11347eaa9ce3a4a51f8ad55bc89c80ed | /GoblinEngine with SFML/Core/MapCell.cpp | 72ae8daca3dd42dac5434d6b0673446e8a0e9e7f | [] | no_license | chibicitiberiu/goblin-engine | 933b72778691eda084042892429e1578645b211e | a66466cb9bb148473f062d49e1e8d8790d375b9d | refs/heads/master | 2016-09-06T05:36:52.160481 | 2013-09-06T21:26:21 | 2013-09-06T21:26:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 455 | cpp | #include "MapCell.h"
namespace Goblin
{
MapCell::MapCell(void)
{
}
MapCell::~MapCell(void)
{
}
int MapCell::getTerrainType() const
{
return this->terrainType;
}
float MapCell::getHeight() const
{
return this->height;
}
void MapCell::setTerrainType(int value)
{
this->terrainType = value;
}
void MapCell::setHeight(float value)
{
this->height = value;
}
Object* MapCell::clone() const
{
return new MapCell(*this);
}
} | [
"chibicitiberiu@gmail.com"
] | chibicitiberiu@gmail.com |
42a02da877b41b9855a921ecaedbfb975f93f548 | 309975d60e30260f2e02d11e71eaaf6e08b93659 | /Sources/Internal/Render/RHI/Common/PreProcessor.h | 34720025c39672d79a6a8c7cd44d9372d7baa34c | [] | permissive | BlitzModder/dava.engine | e83b038a9d24b37c00b095e83ffdfd8cd497823c | 0c7a16e627fc0d12309250d6e5e207333b35361e | refs/heads/development | 2023-03-15T12:30:32.342501 | 2018-02-19T11:09:02 | 2018-02-19T11:09:02 | 122,161,150 | 4 | 3 | BSD-3-Clause | 2018-02-20T06:00:07 | 2018-02-20T06:00:07 | null | UTF-8 | C++ | false | false | 3,115 | h | #pragma once
#include "ExpressionEvaluator.h"
namespace DAVA
{
class PreProc
{
public:
struct FileCallback
{
virtual ~FileCallback() = default;
virtual bool Open(const char* /*file_name*/) = 0;
virtual void Close() = 0;
virtual uint32 Size() const = 0;
virtual uint32 Read(uint32 /*max_sz*/, void* /*dst*/) = 0;
};
using TextBuffer = std::vector<char>;
public:
PreProc(FileCallback* fc = nullptr);
~PreProc();
bool ProcessFile(const char* file_name, TextBuffer* output);
bool Process(const char* src_text, TextBuffer* output);
void Clear();
bool AddDefine(const char* name, const char* value);
private:
struct Line
{
uint32 line_n;
const char* text;
Line(const char* t, uint32 n)
: text(t)
, line_n(n)
{
}
};
using LineVector = std::vector<Line>;
void Reset();
char* AllocBuffer(uint32 sz);
bool ProcessInplaceInternal(char* src_text, TextBuffer* output);
bool ProcessBuffer(char* text, LineVector& line);
bool ProcessInclude(const char* file_name, LineVector& line);
bool ProcessDefine(const char* name, const char* val);
void Undefine(const char* name);
void GenerateOutput(TextBuffer* output, LineVector& line);
char* GetExpression(char* txt, char** end) const;
char* GetIdentifier(char* txt, char** end) const;
int32 GetNameAndValue(char* txt, char** name, char** value, char** end) const;
void ReportExprEvalError(uint32 line_n);
char* ExpandMacroInLine(char* txt);
char* GetNextToken(char* txt, ptrdiff_t txtSize, ptrdiff_t& tokenSize);
const char* GetNextToken(const char* txt, ptrdiff_t txtSize, ptrdiff_t& tokenSize);
public:
enum : uint32
{
MaxMacroValueLength = 128,
MaxLocalStringLength = 2048,
};
struct MacroStringBuffer
{
const char* value = nullptr;
uint32 length = 0;
MacroStringBuffer() = default;
MacroStringBuffer(const char* nm, uint32 sz)
: value(nm)
, length(sz)
{
}
bool operator==(const MacroStringBuffer& r) const
{
bool equals = false;
if (length == r.length)
{
equals = (strncmp(value, r.value, length) == 0);
}
return equals;
}
};
struct MacroStringBufferHash
{
uint64 operator()(const MacroStringBuffer& m) const
{
return DAVA::HashValue_N(m.value, m.length);
}
};
using MacroMap = UnorderedMap<MacroStringBuffer, MacroStringBuffer, MacroStringBufferHash>;
private:
enum : uint32
{
InvalidValue = static_cast<uint32>(-1)
};
enum : char
{
Tab = '\t',
Zero = '\0',
Space = ' ',
NewLine = '\n',
DoubleQuotes = '\"',
CarriageReturn = '\r',
};
MacroMap macro;
Vector<char*> buffer;
ExpressionEvaluator evaluator;
FileCallback* fileCB = nullptr;
const char* curFileName = "<buffer>";
};
} | [
"m_molokovskih@wargaming.net"
] | m_molokovskih@wargaming.net |
6e5cc19f0eee9dd659fcc0edce453b52584b289a | 0b1dfd176953fdb3675eb0085dae5d0dd8873574 | /Algorithms/Sorting/SelectionSort/SelectionSortLinkedList.cpp | a741048f0805403d7e0713cb68a88662f63a1071 | [] | no_license | ManasMahapatra/DS-Algo-Implementations | 54fee36a5bb90f42b4947c7fb0b7c53f719e734f | 639941a020134cfd483136e9774f2dc6184d1e1c | refs/heads/master | 2020-07-28T06:05:43.202647 | 2019-10-10T04:29:29 | 2019-10-10T04:29:29 | 209,331,511 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,769 | cpp | #include <stdio.h>
#include <iostream>
#include "../../../DataStructures/LinearDataStructures/LinkedList/LinkedList.cpp"
class SortedLinkedList : public LinkedList {
public:
void selectionSort() {
//Variable to store current minimum value
int newMinimumValue;
//Pointer to point at the new minimum index
node* newMinimumNode = NULL;
//Variable to store current minimum Node
node* currentMinimumNode;
//Inner and outer traverse Node
node* innerTraverseNode;
//Start the outer loop from head
node* traverseNode = head;
while (traverseNode != NULL) {
//set the current node as minimum
currentMinimumNode = traverseNode;
//Store the minimuym considered data
newMinimumValue = currentMinimumNode->data;
//Start the inner lop from the next node onwards
innerTraverseNode = traverseNode->next;
while(innerTraverseNode != NULL) {
//change the new minimum only when the traversing node's data will be less than the current minimum data
if (innerTraverseNode->data < newMinimumValue) {
newMinimumValue = innerTraverseNode->data;
newMinimumNode = innerTraverseNode;
}
innerTraverseNode = innerTraverseNode->next;
}
//Swap only if theres a node and then reset the minimum node to NULL
if (newMinimumNode != NULL) {
newMinimumNode->data = currentMinimumNode->data;
currentMinimumNode->data = newMinimumValue;
newMinimumNode = NULL;
}
traverseNode = traverseNode->next;
}
}
};
| [
"chirag301212@gmail.com"
] | chirag301212@gmail.com |
56fb32cda41c77a4991911c4e64499921e591188 | 3cf9e141cc8fee9d490224741297d3eca3f5feff | /C++ Benchmark Programs/Benchmark Files 1/classtester/autogen-sources/source-4701.cpp | 54ef0911cbf36626b42b137984caf04c3aa75cf9 | [] | no_license | TeamVault/tauCFI | e0ac60b8106fc1bb9874adc515fc01672b775123 | e677d8cc7acd0b1dd0ac0212ff8362fcd4178c10 | refs/heads/master | 2023-05-30T20:57:13.450360 | 2021-06-14T09:10:24 | 2021-06-14T09:10:24 | 154,563,655 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,765 | cpp | struct c0;
void __attribute__ ((noinline)) tester0(c0* p);
struct c0
{
bool active0;
c0() : active0(true) {}
virtual ~c0()
{
tester0(this);
active0 = false;
}
virtual void f0(){}
};
void __attribute__ ((noinline)) tester0(c0* p)
{
p->f0();
}
struct c1;
void __attribute__ ((noinline)) tester1(c1* p);
struct c1
{
bool active1;
c1() : active1(true) {}
virtual ~c1()
{
tester1(this);
active1 = false;
}
virtual void f1(){}
};
void __attribute__ ((noinline)) tester1(c1* p)
{
p->f1();
}
struct c2;
void __attribute__ ((noinline)) tester2(c2* p);
struct c2 : c0
{
bool active2;
c2() : active2(true) {}
virtual ~c2()
{
tester2(this);
c0 *p0_0 = (c0*)(c2*)(this);
tester0(p0_0);
active2 = false;
}
virtual void f2(){}
};
void __attribute__ ((noinline)) tester2(c2* p)
{
p->f2();
if (p->active0)
p->f0();
}
struct c3;
void __attribute__ ((noinline)) tester3(c3* p);
struct c3 : virtual c1, c0
{
bool active3;
c3() : active3(true) {}
virtual ~c3()
{
tester3(this);
c0 *p0_0 = (c0*)(c3*)(this);
tester0(p0_0);
c1 *p1_0 = (c1*)(c3*)(this);
tester1(p1_0);
active3 = false;
}
virtual void f3(){}
};
void __attribute__ ((noinline)) tester3(c3* p)
{
p->f3();
if (p->active0)
p->f0();
if (p->active1)
p->f1();
}
struct c4;
void __attribute__ ((noinline)) tester4(c4* p);
struct c4 : virtual c1, virtual c2, c3
{
bool active4;
c4() : active4(true) {}
virtual ~c4()
{
tester4(this);
c0 *p0_0 = (c0*)(c2*)(c4*)(this);
tester0(p0_0);
c0 *p0_1 = (c0*)(c3*)(c4*)(this);
tester0(p0_1);
c1 *p1_0 = (c1*)(c4*)(this);
tester1(p1_0);
c1 *p1_1 = (c1*)(c3*)(c4*)(this);
tester1(p1_1);
c2 *p2_0 = (c2*)(c4*)(this);
tester2(p2_0);
c3 *p3_0 = (c3*)(c4*)(this);
tester3(p3_0);
active4 = false;
}
virtual void f4(){}
};
void __attribute__ ((noinline)) tester4(c4* p)
{
p->f4();
if (p->active3)
p->f3();
if (p->active1)
p->f1();
if (p->active2)
p->f2();
}
int __attribute__ ((noinline)) inc(int v) {return ++v;}
int main()
{
c0* ptrs0[25];
ptrs0[0] = (c0*)(new c0());
ptrs0[1] = (c0*)(c2*)(new c2());
ptrs0[2] = (c0*)(c3*)(new c3());
ptrs0[3] = (c0*)(c2*)(c4*)(new c4());
ptrs0[4] = (c0*)(c3*)(c4*)(new c4());
for (int i=0;i<5;i=inc(i))
{
tester0(ptrs0[i]);
delete ptrs0[i];
}
c1* ptrs1[25];
ptrs1[0] = (c1*)(new c1());
ptrs1[1] = (c1*)(c3*)(new c3());
ptrs1[2] = (c1*)(c4*)(new c4());
ptrs1[3] = (c1*)(c3*)(c4*)(new c4());
for (int i=0;i<4;i=inc(i))
{
tester1(ptrs1[i]);
delete ptrs1[i];
}
c2* ptrs2[25];
ptrs2[0] = (c2*)(new c2());
ptrs2[1] = (c2*)(c4*)(new c4());
for (int i=0;i<2;i=inc(i))
{
tester2(ptrs2[i]);
delete ptrs2[i];
}
c3* ptrs3[25];
ptrs3[0] = (c3*)(new c3());
ptrs3[1] = (c3*)(c4*)(new c4());
for (int i=0;i<2;i=inc(i))
{
tester3(ptrs3[i]);
delete ptrs3[i];
}
c4* ptrs4[25];
ptrs4[0] = (c4*)(new c4());
for (int i=0;i<1;i=inc(i))
{
tester4(ptrs4[i]);
delete ptrs4[i];
}
return 0;
}
| [
"ga72foq@mytum.de"
] | ga72foq@mytum.de |
cf86dd40e683355353298b44f6db48632b066139 | 3f6b0498b97a3f71f444a58b5a7e06f09f4571e0 | /Source/InfiniEx/Public/Characters/Heros/InfiniKnight.h | c9622fabb0105b310d52cbfdd9dece4353213609 | [] | no_license | aalhamoudi/InfiniWar | 517aad84f0ed1c3fba5fec204df4007f6165a9d8 | 2f6cfcf9ce4a8062e4f8ba4df61bb15f71e1ec0d | refs/heads/master | 2020-04-20T12:33:54.830018 | 2017-01-29T04:06:42 | 2017-01-29T04:06:42 | 168,846,326 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 631 | h | // Copyright Abdulrahman Alhamoudi, 2016 - All rights reserved.
#pragma once
#include "InfiniHero.h"
#include "InfiniKnight.generated.h"
/**
*
*/
UCLASS()
class INFINIEX_API AInfiniKnight : public AInfiniHero
{
GENERATED_BODY()
public:
// Character Vitals //
/** Max Stamina */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Vitals)
float MaxStamina;
/** Stamina Regen */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Vitals)
float StaminaRegen;
/** Actual Stamina */
UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = Vitals)
float Stamina;
};
| [
"aalha028@uottawa.ca"
] | aalha028@uottawa.ca |
5b421b25131b907b73ca8fc247a14cfea9087b25 | fe4ebfc4a21f996e4e792e75961c74453fab85c0 | /src/error.h | 83963ee566c20715cc3d397cab81e8ef39bc7cd6 | [] | no_license | xeekworx/spacetheory | 4e2971e83e9eaeb0640cfabb2595679e495ab1b9 | 753c88e96e9880c8485f0930e7476faedebbde28 | refs/heads/master | 2021-01-19T22:52:39.807236 | 2018-03-11T03:23:21 | 2018-03-11T03:23:21 | 88,878,200 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 463 | h | #pragma once
#include <stdexcept>
namespace spacetheory {
class error : public std::runtime_error
{
// May extend the capability of this in the future, but to avoid the
// mass changes needed I'm going to go ahead and make use of this
// everywhere.
public:
explicit error(const std::string& what_arg) : runtime_error(what_arg) {}
explicit error(const char* what_arg) : runtime_error(what_arg) {}
};
} | [
"xeek@xeekworx.com"
] | xeek@xeekworx.com |
3f62efe84a200de69cc7eb01af27631456f490bb | 553a22eb54b2bc5df030d0c72d4a74ac4003aa4e | /unitrotate.cpp | ea63c22944956dbb691ae425615e09b2e3056fff | [] | no_license | jchristi/taddraw | d2cffaae01c660351e0f56235671e9d2fad6e0a1 | b52868b1f5ffede884c9c0ea46fb11b105d24f2b | refs/heads/master | 2016-09-06T14:36:20.774557 | 2015-05-30T16:11:35 | 2015-05-30T16:11:35 | 35,358,173 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,652 | cpp | #include "oddraw.h"
#include "iddrawsurface.h"
#include "unitrotate.h"
char *NewMem;
CUnitRotate::CUnitRotate()
{
LocalShare->UnitRotate = this;
IDDrawSurface::OutptTxt ( "New CUnitRotate");
}
CUnitRotate::~CUnitRotate()
{
}
bool CUnitRotate::Message(HWND WinProchWnd, UINT Msg, WPARAM wParam, LPARAM lParam)
{
switch(Msg)
{
case WM_KEYDOWN:
if(wParam == 81 && (GetAsyncKeyState(17)&0x8000)>0) // ctrl + q
{
Rotate();
//SetMem();
return true;
}
break;
}
return false;
}
void CUnitRotate::SetMem()
{
NewMem = new char[500000];
int Add = (int)&NewMem;
WriteProcessMemory(GetCurrentProcess(), (void*)0x42E46A, &Add, 4, NULL);
memset(NewMem, 500000, 0);
}
void CUnitRotate::Rotate()
{
//FixAck();
int UnitOffset = 0x118;
int *PTR1 = (int*)0x511de8;
int *UnitPTR = (int*)((*PTR1)+0x1b8e+0x3c);
int NumUnits = *((int*)(*PTR1+0x1ca7))& 0x0000ffff;
int i=0;
int OwnUnitBegin = 0;
while(OwnUnitBegin<NumUnits)
{
//short *OwnUnitBegin = (short*)(*UnitPTR + 2 + i*UnitOffset);
char *UnitDead = (char*)(*UnitPTR + 247 + i*UnitOffset);
char *Builder = (char*)(*UnitPTR + 31 + i*UnitOffset);
short *XPos = (short*)(*UnitPTR + 0x6c + i*UnitOffset);
short *YPos = (short*)(*UnitPTR + 0x74 + i*UnitOffset);
int *IsUnit = (int*)(*UnitPTR + 0 + i*UnitOffset);
char *UnitSelected = (char*)(*UnitPTR + 272 + i*UnitOffset);
//char *Working = (char*)(*UnitPTR + 186 + i*UnitOffset);
//int *Moving = (int*)(*UnitPTR + 208 + i*UnitOffset);
int *UnitOrderPTR = (int*)(*UnitPTR + 92 + i*UnitOffset);
int *DefiPTR = (int*)(*UnitPTR + 146 + i*UnitOffset);
int *DefPTR = (int*)*DefiPTR;
if(*UnitDead!=0 && *UnitDead!=1)
{
if(strcmp((char*)DefPTR, "Vehicle Plant") == 0)
{
char *NewUnitDef = new char[0x249];
memcpy(NewUnitDef, (char*)*DefiPTR, 0x249);
*DefiPTR = (int)NewUnitDef;
char *NewYardMap = new char[48];
int *YardMap = (int*)(NewUnitDef + 334);
memcpy(NewYardMap, (char*)*YardMap, 48);
NewYardMap[2] = 0x2d;
NewYardMap[3] = 0x2d;
NewYardMap[4] = 0x2d;
NewYardMap[5] = 0x2d;
//for(int x=0; x<480; x++)
// NewYardMap[x] = 0x2D;
int *tmpPTR = (int*)YardMap;
*tmpPTR = (int)NewYardMap;
IDDrawSurface::OutptTxt(NewUnitDef);
}
OwnUnitBegin++;
}
i++;
if(i == 5000)
{
//LastNum = 0;
return;
}
}
}
| [
"xpoy@d74ebf05-6d01-4e7b-8b90-17afc8ece2ee"
] | xpoy@d74ebf05-6d01-4e7b-8b90-17afc8ece2ee |
bf4dc8196b11390cf6d1858ebb65458dd8deabb8 | 91b241f1340b2062f5f7fa257b6f59f58ba24fbe | /Lab04OOP/VolumetricShape/CBody.h | 196b06cbbac0d0c6262e0d8c6cbe1a4b29cfc6a3 | [] | no_license | fjodor-rybakov/OOP | fed50967936da4d59075cbaf7939c7b36cf54e47 | 38971571177d0be9a1d7f33de8ecdb0720ac62bc | refs/heads/master | 2020-03-11T11:10:45.203118 | 2018-05-22T17:38:24 | 2018-05-22T17:38:24 | 129,962,735 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 389 | h | #pragma once
#include "string"
#include "vector"
class CBody
{
public:
CBody(const std::string &type);
CBody(const std::string &type, double density);
virtual double GetDensity() const;
virtual double GetVolume() const;
double GetMass() const;
std::string ToString() const;
std::string GetType() const;
private:
double m_density, m_volume = 0, m_mass = 0;
std::string m_type;
}; | [
"fedryb@mail.ru"
] | fedryb@mail.ru |
d5910ae213634215bb41c35ea9d97bef4d90e9de | 7b0c32697ea55325608dfaca954538292acd7e8f | /src/main.cpp | eb21d0a742794e0a50b79ade0497bcac9dead1a0 | [] | no_license | TobyPDE/cntk-api-experiment | 197819f619c7a962370c76bd068ef3bbe80e7774 | 70750da43bf0cea9304a2f4a4dceefad0d20f7d9 | refs/heads/master | 2021-06-10T08:51:17.600560 | 2016-12-22T21:01:43 | 2016-12-22T21:01:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 445 | cpp | //
// Created by toby on 01.12.16.
//
#include "chianti/layers.h"
#include <string>
#include <iostream>
int main(int argc, const char** argv)
{
auto device = CNTK::DeviceDescriptor::GPUDevice(0);
auto X = CNTK::InputVariable({ 2, 2, 3 }, CNTK::DataType::Float);
CNTK::FunctionPtr network;
network = Chianti::Layers::Conv2DLayer(X, device)
.filterSize({3, 3})
.pad("same")
.numFilters(64);
} | [
"tobias.pohlen@gmail.com"
] | tobias.pohlen@gmail.com |
13e213b98d4623b49ffde49642bb47f425a66370 | 76874343d99e3292df374deeca5e1cb7dd064f81 | /algorithms/ShellSort.cpp | 5e44992c51713bd9363cd886a1d0c59ef44cd499 | [] | no_license | wfwei/coding | 2e8afa40ed8fdec9b63d426d42695bf6292e31b8 | 1d31c640b2882217fbf8235889b07cc27235a54e | refs/heads/master | 2021-01-10T19:54:53.933525 | 2013-09-23T07:31:53 | 2013-09-23T07:31:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 527 | cpp | #include<stdio.h>
#define SIZE 12
void prt(int A[], int size){
int i;
for(i=0; i<size; i++)
printf("%d ", A[i]);
printf("\n");
}
void ShellSort(int *A, int s, int e){
int i, j, tmp, inc;
for(inc=(e-s)/2; inc>0; inc/=2){
for(i=inc+s; i<=e; i++){
tmp = A[i];
j = i;
while(j-inc>=s && tmp<A[j-inc]){
A[j] = A[j-inc];
j-=inc;
}
A[j] = tmp;
}
}
}
int main(int argc, char* argv[])
{
int A[SIZE] = {1, 10, 14, 16, 4, 7, 9, 3, 2, 8, 5, 11};
ShellSort(A, 0, SIZE-1);
prt(A, SIZE);
return 0;
}
| [
"cf.wfwei@gmail.com"
] | cf.wfwei@gmail.com |
80e34a3bf7d64e059e631eaffa96110b5060c441 | 068c1a644084a3920969949dfd0f0de5b9528a29 | /cpp-cgdk/model/Unit.h | 9056d5370dc08c5fcd4304555f14aa0cdb68c54f | [] | no_license | m16a/game01 | 28374fa824aa95daa556dc157e220ec1c1d057f1 | ef9169e82ce551539c5bb4d5720ba39f8c551125 | refs/heads/master | 2021-01-15T22:52:57.832889 | 2013-11-29T18:09:09 | 2013-11-29T18:09:09 | 14,368,124 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 451 | h | #pragma once
#ifndef _UNIT_H_
#define _UNIT_H_
namespace model {
class Unit {
private:
long long id;
int x;
int y;
protected:
Unit(long long id, int x, int y);
public:
virtual ~Unit();
long long getId() const;
int getX() const;
int getY() const;
double getDistanceTo(int x, int y) const;
double getDistanceTo(const Unit& unit) const;
};
}
#endif
| [
"mshvorak@gmail.com"
] | mshvorak@gmail.com |
683a8c9a04ee349aadec78d77d060b5dcbbc37e9 | 51635684d03e47ebad12b8872ff469b83f36aa52 | /external/gcc-12.1.0/libstdc++-v3/testsuite/29_atomics/atomic/65147.cc | 0c390bb86420dc47e6566df048e8fb7009799039 | [
"LGPL-2.1-only",
"GPL-3.0-only",
"GCC-exception-3.1",
"GPL-2.0-only",
"LGPL-3.0-only",
"LGPL-2.0-or-later",
"Zlib",
"LicenseRef-scancode-public-domain"
] | permissive | zhmu/ananas | 8fb48ddfe3582f85ff39184fc7a3c58725fe731a | 30850c1639f03bccbfb2f2b03361792cc8fae52e | refs/heads/master | 2022-06-25T10:44:46.256604 | 2022-06-12T17:04:40 | 2022-06-12T17:04:40 | 30,108,381 | 59 | 8 | Zlib | 2021-09-26T17:30:30 | 2015-01-31T09:44:33 | C | UTF-8 | C++ | false | false | 960 | cc | // Copyright (C) 2015-2022 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, or (at your option)
// any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
// { dg-do compile { target c++11 } }
#include <atomic>
struct S16 {
char c[16];
};
static_assert( alignof(std::atomic<S16>) >= 16,
"atomic<S16> must be aligned to at least its size" );
| [
"rink@rink.nu"
] | rink@rink.nu |
ca40657bd158f4e699cbf901e41f232b7120358a | 717c70331e83947539c4a68dd63d1863bbed32e0 | /textga/textga_cpplib/trunk/src/tag/AbstractElement.cpp | e296d4cafd0f39234be57f9a3267247e81357af7 | [] | no_license | hoboaki/oldcode | 5907bdd01af84d6d2d779e26d6e4dbd3be1a028c | 2c2aa0b20dc3f48656011dd5eb197d79fa3266cf | refs/heads/master | 2020-12-03T03:51:03.125931 | 2017-06-29T13:44:19 | 2017-06-29T13:44:19 | 95,781,642 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 964 | cpp | /**
* @file
* @brief AbstractElement.hppの実装を記述する。
*/
#include <textga/tag/AbstractElement.hpp>
//------------------------------------------------------------
namespace textga {
namespace tag {
//------------------------------------------------------------
AbstractElement::AbstractElement(
const char *name
, const ElementKind aKind
)
: name_( name )
, elementKind_( aKind )
{
}
//------------------------------------------------------------
AbstractElement::~AbstractElement()
{
}
//------------------------------------------------------------
const char* AbstractElement::name()const
{
return name_;
}
//------------------------------------------------------------
ElementKind AbstractElement::elementKind()const
{
return elementKind_;
}
//------------------------------------------------------------
}}
//------------------------------------------------------------
// EOF
| [
"hoboaki@10106.net"
] | hoboaki@10106.net |
732ac11c843ec35b1b22d949eb6cffa7607a0a06 | 06810247a5fe519f3521adcc031b9a65011b485e | /No/2020.cpp | 546b0cf6044ce8f1a41ea4282456248925cb864d | [] | no_license | yjhmelody/hdoj | ce036b7573200a4b075f4d8815595e5afc904887 | 4fabb95b2cb42c984ad5f0e7e8cc9680110c1b0c | refs/heads/master | 2020-02-26T13:31:30.066347 | 2016-11-22T14:21:39 | 2016-11-22T14:21:39 | 68,513,913 | 0 | 0 | null | 2016-11-21T09:21:58 | 2016-09-18T10:21:50 | C++ | UTF-8 | C++ | false | false | 568 | cpp | #include<stdio.h>
#include<string.h>
int main()
{
int n,i,temp,k,j;
while(~scanf("%d",&n)&&n)
{
int a[100],b[100];
memset(b,0,sizeof(b));
for(i=0;i<n;i++)
{
scanf("%d",a+i);
if(a[i]<0)
{
b[i]=1;
a[i]=-a[i];
}
}
for(i=0;i<n;++i)
{
k=i;
for(j=i+1;j<n;++j)
{
if(a[k]<a[j])
k=j;
}
temp=a[k];
a[k]=a[i];
a[i]=temp;
temp=b[k];
b[k]=b[i];
b[i]=temp;
}
for(i=0;i<n-1;i++)
{
if(b[i])
printf("-");
printf("%d ",a[i]);
}
if(b[i])
printf("-");
printf("%d\n",a[i]);
}
return 0;
}
| [
"465402634@qq.com"
] | 465402634@qq.com |
4ffcd993dcc3945c439a3e08513e557fbc285915 | ec7a0d96847f30a34d0502697c92f51b1b7adc52 | /src/RayTracer.h | 47f39a8eca8c1131a891537c3c6a734170f6376a | [] | no_license | LeeDua/RayTracing | fd7cc0d90605c703d1941b39cc0252023310f2ed | d9498e74a2a10c3538cea1347680e97255266e77 | refs/heads/master | 2023-02-03T07:36:13.576376 | 2020-12-16T15:30:15 | 2020-12-16T15:30:15 | 319,074,879 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,261 | h | #ifndef RAY_TRACER_H
#define RAY_TRACER_H
#include "HittableVec.h"
#include "Ray.h"
#include "Material.h"
#include "BVH.h"
namespace RayTracing{
class RayTracerBase{
public:
virtual MatColor trace(Ray& ray) const = 0;
private:
virtual void recursiveTrace(Ray& ray, HitRecord& hit_record, MatColor& color) const = 0;
};
class RayTracer: public virtual RayTracerBase{
public:
RayTracer(HittableVec& scene):scene(scene){};
MatColor trace(Ray& ray) const override{
HitRecord hit_record;
MatColor color(1.0,1.0,1.0);
recursiveTrace(ray, hit_record, color);
#ifdef COLORED_BG
dtype mix = (1.0 + ray.direction()[1])*0.5;
MatColor mixed_color = (1.0-mix)*MatColor(1.0,1.0,1.0) + mix * MatColor(0.5,0.7,1.0);
return color * mixed_color;
#endif
if(ray.hit_once)
return color;
return MatColor();
}
private:
void recursiveTrace(Ray& ray, HitRecord& hit_record, MatColor& color) const override{
if(scene.hit(ray, hit_record)){
hit_record.material->interactWithLight(ray, hit_record, color);
ray.updateDepthCounter();
if(ray.isAlive()){
return recursiveTrace(ray, hit_record, color);
}
}
}
HittableVec scene;
};
class BVHRayTracer: public RayTracer{
public:
//has to do post init for bbox, so the scene is not marked const
BVHRayTracer(HittableVec& scene):RayTracer(scene){
scene.init();
tree = std::make_shared<BVHTree>(scene);
}
private:
void recursiveTrace(Ray& ray, HitRecord& hit_record, MatColor& color) const override{
if(tree->hit(ray, hit_record)){
hit_record.material->interactWithLight(ray, hit_record, color);
ray.updateDepthCounter();
if(ray.isAlive()){
recursiveTrace(ray, hit_record, color);
}
}
}
private:
std::shared_ptr<BVHTree> tree;
};
}
#endif | [
"1063809383@qq.com"
] | 1063809383@qq.com |
b803bcb0f8dd44db80198fbb85549ec464fec015 | 0f7a4119185aff6f48907e8a5b2666d91a47c56b | /sstd_utility/windows_boost/boost/unordered/detail/fwd.hpp | 27978bd932a7ec830ef5cbe353737a16074d9068 | [] | no_license | jixhua/QQmlQuickBook | 6636c77e9553a86f09cd59a2e89a83eaa9f153b6 | 782799ec3426291be0b0a2e37dc3e209006f0415 | refs/heads/master | 2021-09-28T13:02:48.880908 | 2018-11-17T10:43:47 | 2018-11-17T10:43:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,975 | hpp |
// Copyright (C) 2008-2016 Daniel James.
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_UNORDERED_FWD_HPP_INCLUDED
#define BOOST_UNORDERED_FWD_HPP_INCLUDED
#include <boost/config.hpp>
#if defined(BOOST_HAS_PRAGMA_ONCE)
#pragma once
#endif
#include <boost/predef.h>
#if defined(BOOST_UNORDERED_HAVE_PIECEWISE_CONSTRUCT)
// Already defined.
#elif defined(BOOST_LIBSTDCXX11)
// https://github.com/gcc-mirror/gcc/blob/gcc-4_6-branch/libstdc++-v3/include/bits/stl_pair.h#L70
#if BOOST_LIBSTDCXX_VERSION > 40600
#define BOOST_UNORDERED_HAVE_PIECEWISE_CONSTRUCT 1
#endif
#elif BOOST_LIB_STD_CXX
// https://github.com/llvm-mirror/libcxx/blob/release_30/include/utility#L206
#if BOOST_LIB_STD_CXX >= BOOST_VERSION_NUMBER(3, 0, 0)
#define BOOST_UNORDERED_HAVE_PIECEWISE_CONSTRUCT 1
#endif
#elif defined(BOOST_LIB_STD_DINKUMWARE)
// Apparently C++11 standard supported in Visual Studio 2012
// https://msdn.microsoft.com/en-us/library/hh567368.aspx#stl
// 2012 = VC+11 = BOOST_MSVC 1700 Hopefully!
// I have no idea when Dinkumware added it, probably a lot
// earlier than this check.
#if BOOST_LIB_STD_DINKUMWARE >= BOOST_VERSION_NUMBER(6, 50, 0) || \
BOOST_COMP_MSVC >= BOOST_VERSION_NUMBER(17, 0, 0)
#define BOOST_UNORDERED_HAVE_PIECEWISE_CONSTRUCT 1
#endif
#endif
// Assume that an unknown library does not support piecewise construction.
#if !defined(BOOST_UNORDERED_HAVE_PIECEWISE_CONSTRUCT)
#define BOOST_UNORDERED_HAVE_PIECEWISE_CONSTRUCT 0
#endif
#if BOOST_UNORDERED_HAVE_PIECEWISE_CONSTRUCT
#include <utility>
#endif
namespace boost {
namespace unordered {
#if BOOST_UNORDERED_HAVE_PIECEWISE_CONSTRUCT
using std::piecewise_construct_t;
using std::piecewise_construct;
#else
struct piecewise_construct_t
{
};
const piecewise_construct_t piecewise_construct = piecewise_construct_t();
#endif
}
}
#endif
| [
"nanguazhude@vip.qq.com"
] | nanguazhude@vip.qq.com |
0fd85692c4b1ad5719c87a96bac8ab6ca55da0b1 | 3680fc5ba33cea0fbaf0bd7f686569370059359a | /worker/main.cpp | 0aa2b03d63c74beb6d9a258c5d1c155dd558d4cc | [] | no_license | recheal-zhang/fifo | bca3044b0487ef4c806f1a46a5b1e3891f53773e | ea30e955f3768670882a49310a82ed0b5379ed90 | refs/heads/master | 2021-06-16T03:07:06.477311 | 2017-04-26T01:49:29 | 2017-04-26T01:49:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 799 | cpp | #include <unistd.h>
#include <iostream>
#include <string>
#include "Util.h"
#include "Define.h"
#include "Fifo.h"
#include "Epoll.h"
using namespace std;
int main(){
cout << "hello worker" << endl;
std::string fifoClientName =
CUtil::getFifoName(WORKER_1_KEY);
CFifo fifoSend(fifoClientName.c_str());
int fd = open(fifoClientName.c_str(),
O_WRONLY,
0);
char msg[5] = "1234";
CUtil::writeMsgToFifo(fd, msg, 5);
Epoll workerEpoll;
std::string fifoServerName =
CUtil::getFifoName(MASTER_1_KEY);
workerEpoll.addFifoWriteFdInfo(fd);
workerEpoll.addFifoFdFromServer(
CUtil::openfileReadonlyNonblock(
fifoServerName.c_str()));
workerEpoll.monitor();
return 0;
}
| [
"zhanglichao0331@163.com"
] | zhanglichao0331@163.com |
5ffb44c96596a9d4957ed49c296e5adca57ed302 | 592490cd67944e3d2e777de130e5e5a121ef2dca | /module04/ex01/AWeapon.hpp | c98861c4b8b60ce18f72b4d4bd942e10e3437c78 | [] | no_license | VictorTennekes/CPP_Piscine | 322b0298755cf16c1387fc155c0ea082f6ce163f | fad40c86c0fe67d5a151e72b26685c42f4e07460 | refs/heads/master | 2023-01-01T17:46:20.249434 | 2020-10-22T09:53:09 | 2020-10-22T09:53:09 | 291,345,452 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,374 | hpp | /* ************************************************************************** */
/* */
/* :::::::: */
/* AWeapon.hpp :+: :+: */
/* +:+ */
/* By: vtenneke <vtenneke@student.codam.nl> +#+ */
/* +#+ */
/* Created: 2020/08/04 15:55:49 by vtenneke #+# #+# */
/* Updated: 2020/08/04 15:55:49 by vtenneke ######## odam.nl */
/* */
/* ************************************************************************** */
#ifndef AWEAPON_HPP
# define AWEAPON_HPP
# include <string>
class AWeapon {
public:
AWeapon(std::string const &name, int apcost, int damage);
AWeapon(const AWeapon &src);
AWeapon &operator=(const AWeapon &weapon);
virtual ~AWeapon();
std::string const &getName() const;
int getAPCost() const;
int getDamage() const;
virtual void attack() const = 0;
protected:
std::string _name;
int _apCost;
int _damage;
private:
AWeapon();
};
#endif
| [
"victor@tennekes.nl"
] | victor@tennekes.nl |
7f22c3a63446e839a2a6ee577e5edb7e79aa4c4c | 75e49b7e53cf60c99b7ab338127028a457e2721b | /sources/plug_osg/src/luna/bind_osgUtil_RenderBin_SortCallback.cpp | ac50a7b77870f7b98a2e81e4415308fa67b0b485 | [] | no_license | roche-emmanuel/singularity | 32f47813c90b9cd5655f3bead9997215cbf02d6a | e9165d68fc09d2767e8acb1e9e0493a014b87399 | refs/heads/master | 2021-01-12T01:21:39.961949 | 2012-10-05T10:48:21 | 2012-10-05T10:48:21 | 78,375,325 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,382 | cpp | #include <plug_common.h>
class luna_wrapper_osgUtil_RenderBin_SortCallback {
public:
typedef Luna< osgUtil::RenderBin::SortCallback > luna_t;
// Derived class converters:
static int _cast_from_Referenced(lua_State *L) {
// all checked are already performed before reaching this point.
osgUtil::RenderBin::SortCallback* ptr= dynamic_cast< osgUtil::RenderBin::SortCallback* >(Luna< osg::Referenced >::check(L,1));
if(!ptr)
return 0;
// Otherwise push the pointer:
Luna< osgUtil::RenderBin::SortCallback >::push(L,ptr,false);
return 1;
};
// Function checkers:
inline static bool _lg_typecheck_sortImplementation(lua_State *L) {
if( lua_gettop(L)!=2 ) return false;
if( (lua_isnil(L,2)==0 && !Luna<void>::has_uniqueid(L,2,50169651)) ) return false;
return true;
}
// Operator checkers:
// (found 0 valid operators)
// Function binds:
// void osgUtil::RenderBin::SortCallback::sortImplementation(osgUtil::RenderBin * )
static int _bind_sortImplementation(lua_State *L) {
if (!_lg_typecheck_sortImplementation(L)) {
luna_printStack(L);
luaL_error(L, "luna typecheck failed in void osgUtil::RenderBin::SortCallback::sortImplementation(osgUtil::RenderBin * ) function, expected prototype:\nvoid osgUtil::RenderBin::SortCallback::sortImplementation(osgUtil::RenderBin * )\nClass arguments details:\narg 1 ID = 50169651\n");
}
osgUtil::RenderBin* _arg1=dynamic_cast< osgUtil::RenderBin* >(Luna< osg::Referenced >::check(L,2));
osgUtil::RenderBin::SortCallback* self=dynamic_cast< osgUtil::RenderBin::SortCallback* >(Luna< osg::Referenced >::check(L,1));
if(!self) {
luna_printStack(L);
luaL_error(L, "Invalid object in function call void osgUtil::RenderBin::SortCallback::sortImplementation(osgUtil::RenderBin *)");
}
self->sortImplementation(_arg1);
return 0;
}
// Operator binds:
};
osgUtil::RenderBin::SortCallback* LunaTraits< osgUtil::RenderBin::SortCallback >::_bind_ctor(lua_State *L) {
return NULL; // Class is abstract.
// Abstract methods:
// void osgUtil::RenderBin::SortCallback::sortImplementation(osgUtil::RenderBin * )
// Abstract operators:
}
void LunaTraits< osgUtil::RenderBin::SortCallback >::_bind_dtor(osgUtil::RenderBin::SortCallback* obj) {
osg::ref_ptr<osg::Referenced> refptr = obj;
}
const char LunaTraits< osgUtil::RenderBin::SortCallback >::className[] = "SortCallback";
const char LunaTraits< osgUtil::RenderBin::SortCallback >::fullName[] = "osgUtil::RenderBin::SortCallback";
const char LunaTraits< osgUtil::RenderBin::SortCallback >::moduleName[] = "osgUtil";
const char* LunaTraits< osgUtil::RenderBin::SortCallback >::parents[] = {"osg.Referenced", 0};
const int LunaTraits< osgUtil::RenderBin::SortCallback >::hash = 60083473;
const int LunaTraits< osgUtil::RenderBin::SortCallback >::uniqueIDs[] = {50169651,0};
luna_RegType LunaTraits< osgUtil::RenderBin::SortCallback >::methods[] = {
{"sortImplementation", &luna_wrapper_osgUtil_RenderBin_SortCallback::_bind_sortImplementation},
{0,0}
};
luna_ConverterType LunaTraits< osgUtil::RenderBin::SortCallback >::converters[] = {
{"osg::Referenced", &luna_wrapper_osgUtil_RenderBin_SortCallback::_cast_from_Referenced},
{0,0}
};
luna_RegEnumType LunaTraits< osgUtil::RenderBin::SortCallback >::enumValues[] = {
{0,0}
};
| [
"roche.emmanuel@gmail.com"
] | roche.emmanuel@gmail.com |
4878fdb76b5859886e438583c7ef5b5e13a15cbf | eb2f8b3271e8ef9c9b092fcaeff3ff8307f7af86 | /Grade 10-12/2018 autumn/NOIP/NOIP2018提高组Day2程序包/answers/GD-0014/travel/travel.cpp | 96532cbf32bb1f23f8954a9452fdd533290e70c0 | [] | no_license | Orion545/OI-Record | 0071ecde8f766c6db1f67b9c2adf07d98fd4634f | fa7d3a36c4a184fde889123d0a66d896232ef14c | refs/heads/master | 2022-01-13T19:39:22.590840 | 2019-05-26T07:50:17 | 2019-05-26T07:50:17 | 188,645,194 | 4 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,374 | cpp | #include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
const int N = 5005;
int n, m, dfsq[2 * N], dfn[N], list[N], cnt = 0;
struct edge
{
int from, to, next;
void add(int x, int y) {
from = x; to = y;
next = list[x]; list[x] = cnt;
}
} e[2 * N];
struct node {
int num;
bool operator < (const node &x) const {
return num > x.num;
}
};
typedef priority_queue<node> pq;
pq a[N];
bool v[N];
int ans[N], curr[N];
void minn() {
bool flag = false;
for(int i = 1; i <= n; i++) {
if (flag) ans[i] = curr[i];
else if (curr[i] < ans[i]) {
flag = true;
ans[i] = curr[i];
} else if (curr[i] > ans[i]) {
return;
}
}
}
void dfs(int x, int sum) {
}
void print(int x) {
v[x] = 1;
printf("%d ", x);
while(! a[x].empty()) {
node tmp = a[x].top();
int y = tmp.num;
a[x].pop();
if (! v[y]) {
print(y);
}
}
}
void print1() {
for (int i = 1; i <= n; i++) {
printf("%d ", ans[i]);
}
}
int main () {
freopen("travel.in", "r", stdin);
freopen("travel.out", "w", stdout);
scanf("%d%d", &n, &m);
for (int i = 1; i <= m; i++) {
int x, y;
scanf("%d%d", &x, &y);
node tmp;
tmp.num = y;
a[x].push(tmp);
tmp.num = x;
a[y].push(tmp);
e[++cnt].add(x, y);
e[++cnt].add(y, x);
}
if (m == n - 1) {
print(1);
} else if (m == n) {
dfs(1, 0);
print1();
}
fclose(stdin); fclose(stdout);
return 0;
}
| [
"orion545@qq.com"
] | orion545@qq.com |
f9e49a693614c9e0107e9cbf5c2751b65dd0a009 | d0c44dd3da2ef8c0ff835982a437946cbf4d2940 | /cmake-build-debug/programs_tiling/function14699/function14699_schedule_30/function14699_schedule_30_wrapper.cpp | d14ce7e376b2a21490105cbf2accf64336b29dc3 | [] | no_license | IsraMekki/tiramisu_code_generator | 8b3f1d63cff62ba9f5242c019058d5a3119184a3 | 5a259d8e244af452e5301126683fa4320c2047a3 | refs/heads/master | 2020-04-29T17:27:57.987172 | 2019-04-23T16:50:32 | 2019-04-23T16:50:32 | 176,297,755 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 933 | cpp | #include "Halide.h"
#include "function14699_schedule_30_wrapper.h"
#include "tiramisu/utils.h"
#include <cstdlib>
#include <iostream>
#include <time.h>
#include <fstream>
#include <chrono>
#define MAX_RAND 200
int main(int, char **){
Halide::Buffer<int32_t> buf00(256, 256, 512);
Halide::Buffer<int32_t> buf0(256, 256, 512);
init_buffer(buf0, (int32_t)0);
auto t1 = std::chrono::high_resolution_clock::now();
function14699_schedule_30(buf00.raw_buffer(), buf0.raw_buffer());
auto t2 = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> diff = t2 - t1;
std::ofstream exec_times_file;
exec_times_file.open("../data/programs/function14699/function14699_schedule_30/exec_times.txt", std::ios_base::app);
if (exec_times_file.is_open()){
exec_times_file << diff.count() * 1000000 << "us" <<std::endl;
exec_times_file.close();
}
return 0;
} | [
"ei_mekki@esi.dz"
] | ei_mekki@esi.dz |
ec4348a8ee15a7bcdc8a37ae04286738da6b416b | a9f6a3dfc2fb54547c5451d5c1380842aff45311 | /EM_8x8/ArduinoTestCode/Arduino_EM_8x8_scanner8/Arduino_EM_8x8_scanner8.ino | d5935c2a35088c312cf62a5ca7e05c01577003ca | [
"MIT"
] | permissive | CmdrZin/chips_avr_examples | e7b5403db501456f26f88909bc27d40ae20ba831 | d4b57a8efd6aff2a678adef4fd405e6359e891e6 | refs/heads/master | 2021-08-06T03:38:08.789930 | 2021-01-13T04:42:03 | 2021-01-13T04:42:03 | 26,470,544 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,941 | ino | /*
* The MIT License (MIT)
*
* Copyright (c) 2016 Nels D. "Chip" Pearson (aka CmdrZin)
*
* 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.
*/
/*
* Arduino Emote Mod 8x8 Load Icon Test - Scanner8
* This code changes a vertical line of dots to scan back and forth.
*/
#include <Wire.h>
#define SERIAL_USB 1
/* *** LOCAL PROTOTYPES *** */
uint8_t makeHeader( uint8_t len );
#define SLAVE_ADRS 0x60 // MUST match AVR chip I2C address
/* NOTE: ALL commands are a minimum of three bytes. LEN MOD CMD .. .. */
#define MOD_EM_SERVICE_ID 0x20
#define MES_SET_ICON 0x01
#define MES_SET_ICON_LEN 4
#define MES_LOAD_ICON 0x02
#define MES_LOAD_ICON_LEN 11
int slave = SLAVE_ADRS; // has to be an int.
byte count = 0; // simple counter
int cmdLen;
bool state = true; // toggle state to change direction of scan
uint8_t outBuff[16];
uint8_t icon[8] = {
0b00000000,
0b00000000,
0b00000000,
0b00000000,
0b00000000,
0b00000000,
0b00000000,
0b00000000
};
void setup()
{
Wire.begin(); // join i2c bus
#if(SERIAL_USB == 1)
Serial.begin(57600); // Set BAUD rate
#endif
}
void loop()
{
uint8_t row;
#if(SERIAL_USB == 1)
Serial.print("Count ");
Serial.println(count++, DEC);
#else
++count;
#endif
// Update icon
if( state )
{
for( row=0; row<8; ++row )
icon[row] <<= 1;
if( icon[3] == 0 )
{
for( row=0; row<8; ++row )
icon[row] = 0x80;
state = !state;
}
}
else
{
for( row=0; row<8; ++row )
icon[row] >>= 1;
if( icon[3] == 0 )
{
for( row=0; row<8; ++row )
icon[row] = 0x01;
state = !state;
}
}
// Send CMD to Slave.
outBuff[0] = makeHeader( MES_LOAD_ICON_LEN-3 );
outBuff[1] = MOD_EM_SERVICE_ID;
outBuff[2] = MES_LOAD_ICON;
for( row = 0; row<8; ++row ) {
outBuff[row+3] = icon[row];
}
cmdLen = MES_LOAD_ICON_LEN;
#if(SERIAL_USB == 1)
Serial.print(outBuff[0], HEX);
Serial.print(" ");
Serial.print(outBuff[1], HEX);
Serial.print(" ");
Serial.print(outBuff[2], HEX);
Serial.print(" ");
Serial.print(outBuff[3], HEX);
Serial.print(" ");
Serial.print(outBuff[4], HEX);
Serial.print(" ");
Serial.print(outBuff[5], HEX);
Serial.print(" ");
Serial.print(outBuff[6], HEX);
Serial.print(" ");
Serial.print(outBuff[7], HEX);
Serial.print(" ");
Serial.print(outBuff[8], HEX);
Serial.print(" ");
Serial.print(outBuff[9], HEX);
Serial.print(" ");
Serial.println(outBuff[10], HEX);
#endif
Wire.beginTransmission(slave); // transmit to Slave. Have to do this each time.
Wire.write(outBuff, cmdLen); // sends device ID and data
Wire.endTransmission(); // complete transmit
delay(200);
}
uint8_t makeHeader( uint8_t len )
{
uint8_t temp;
temp = ((~len) << 4) & 0xF0; // shift and mask
temp = temp | (len & 0x0F);
return (temp);
}
| [
"chip@gameactive.org"
] | chip@gameactive.org |
7fe86cdbd85130cde70c881e178f255ff74240f0 | d741c1b64758eec7a7619dfce0ebf7015bcd4675 | /ekbase/base/sessionmanager.cpp | 555f7b58799339c02d609ff6adbd59e2853076e2 | [
"MIT"
] | permissive | maat2019/exkit | ebc4def068efb98c594dacc3013893b06a0d36d2 | 18d71e84d688060f0c30af456dcbec5252ebbdac | refs/heads/master | 2022-01-25T12:05:08.042818 | 2019-05-20T10:00:20 | 2019-05-20T10:00:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 461 | cpp | #include "sessionmanager.h"
#include "holder.h"
SessionManager::SessionManager(Holder *hld)
: hld(hld), session()
{
}
SessionManager::~SessionManager()
{
}
Session SessionManager::GetSession()
{
std::lock_guard<std::mutex> lock(mtx);
if (session.sessId == 0)
LOGW("SessMan has no session");
return session;
}
void SessionManager::Update(Session &session)
{
std::lock_guard<std::mutex> lock(mtx);
this->session = session;
}
| [
"artintexo@yandex.ru"
] | artintexo@yandex.ru |
229751f0e206b96ff80af466e8f6ca188f1798b5 | afaf58bfe495edc9da224d597912763df1b5a410 | /src/kt84/openmesh/debug_writeSVG.hh | 92e57d80ae33d11765548fac2be55577e3c6738c | [] | no_license | tian0ti/sketch | 1c5ee62a6411e478f292cfbaa98760d98f62288e | 3ef958dfc69a32a822c6ce71c2d3b4839e1592a0 | refs/heads/master | 2016-09-06T13:40:57.836963 | 2015-04-13T08:46:58 | 2015-04-13T08:46:58 | 33,857,540 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,989 | hh | #pragma once
#include <cstdio>
#include <sstream>
#include "simple_svg_1.0.0.hpp"
namespace {
#ifdef _WIN32
inline FILE* popen(const char* command, const char* mode) { return _popen(command, mode); }
inline int pclose(FILE* file) { return _pclose(file); }
#endif
}
namespace kt84 {
template <class TMesh>
inline void debug_writeSVG(
const TMesh& mesh,
const char* filename = "debug.svg",
bool export_pdf = false,
double dimension = 500.0,
double stroke_width = 1.0,
bool draw_vidx = true,
bool draw_fidx = true,
bool draw_eidx = true,
const char* font_family = "Courier",
double font_size = 10.0,
double font_stroke_width = 1.0)
{
auto p0 = mesh.point(mesh.vertex_handle(0));
double xmin = p0[0], xmax = xmin;
double ymin = p0[1], ymax = ymin;
for (auto v : mesh.vertices()) {
if (mesh.has_vertex_status() && mesh.status(v).deleted()) continue;
auto p = mesh.point(v);
xmin = std::min<double>(xmin, p[0]);
xmax = std::max<double>(xmax, p[0]);
ymin = std::min<double>(ymin, p[1]);
ymax = std::max<double>(ymax, p[1]);
}
double margin = (xmax - xmin + ymax - ymin) * 0.1;
xmin -= margin; xmax += margin;
ymin -= margin; ymax += margin;
double scaling = dimension / std::min<double>(xmax - xmin, ymax - ymin);
svg::Document doc(filename, svg::Layout(svg::Dimensions(scaling * (xmax - xmin), scaling * (ymax - ymin))));
auto make_svgPoint = [&] (const typename TMesh::Point& p) {
return svg::Point(scaling * (p[0] - xmin),
scaling * (p[1] - ymin));
};
auto int2str = [](int i) {
std::stringstream ss;
ss << i;
return ss.str();
};
for (auto f : mesh.faces()) {
if (mesh.has_face_status() && mesh.status(f).deleted()) continue;
svg::Polygon polygon(svg::Fill(svg::Color::Silver), svg::Stroke(font_stroke_width, svg::Color::Black));
for (auto fv = mesh.cfv_iter(f); fv.is_valid(); ++fv)
polygon << make_svgPoint(mesh.point(*fv));
doc << polygon;
}
svg::Font font(font_size, font_family);
if (draw_vidx) {
for (auto v : mesh.vertices()) {
if (mesh.has_vertex_status() && mesh.status(v).deleted()) continue;
doc << svg::Text(make_svgPoint(mesh.point(v)), int2str(v.idx()), svg::Fill(), font, svg::Stroke(font_stroke_width, svg::Color::Red));
}
}
if (draw_fidx) {
for (auto f : mesh.faces()) {
if (mesh.has_face_status() && mesh.status(f).deleted()) continue;
typename TMesh::Point p;
p.vectorize(0);
int cnt = 0;
for (auto fv = mesh.cfv_iter(f); fv.is_valid(); ++fv) {
p += mesh.point(*fv);
++cnt;
}
p *= 1.0 / cnt;
doc << svg::Text(make_svgPoint(p), int2str(f.idx()), svg::Fill(), font, svg::Stroke(font_stroke_width, svg::Color::Blue));
}
}
if (draw_eidx) {
for (auto e : mesh.edges()) {
if (mesh.has_edge_status() && mesh.status(e).deleted()) continue;
auto p0 = mesh.point(mesh.to_vertex_handle(mesh.halfedge_handle(e, 0)));
auto p1 = mesh.point(mesh.to_vertex_handle(mesh.halfedge_handle(e, 1)));
doc << svg::Text(make_svgPoint((p0 + p1) * 0.5), int2str(e.idx()), svg::Fill(), font, svg::Stroke(1, svg::Color::Brown));
}
}
doc.save();
if (export_pdf) {
std::stringstream command;
command << "inkscape --export-pdf=" << filename << ".pdf " << filename;
FILE* p = popen(command.str().c_str(), "r");
const int BUF_SIZE = 4096;
char buf[BUF_SIZE];
buf[0] = 0;
while (fgets(buf, BUF_SIZE, p) != nullptr) {}
pclose(p);
}
}
}
| [
"sjulin@gmail.com"
] | sjulin@gmail.com |
ea0627d8876c11909807b564cf1f701253e0c9b0 | 2511b9066113f8c1e9cb18b6943094616e15fea0 | /WinrtApp/MainPage.cpp | feff90adc31e4920d70f9a08e46244ce2c897c07 | [] | no_license | wcj233/StaticLibraryWinrt | d3af71cf16ba7a1d0b4a5a355c2b114ec79cff31 | 2047eeea2d522bfe8bfcf14e0d71a7d6ca12fbc7 | refs/heads/master | 2022-11-13T16:38:09.622454 | 2020-06-23T08:32:41 | 2020-06-23T08:32:41 | 274,352,115 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 666 | cpp | #include "pch.h"
#include "MainPage.h"
#include "MainPage.g.cpp"
#include <winrt/StaticLibrary1.h>
using namespace winrt;
using namespace Windows::UI::Xaml;
namespace winrt::WinrtApp::implementation
{
MainPage::MainPage()
{
InitializeComponent();
}
int32_t MainPage::MyProperty()
{
throw hresult_not_implemented();
}
void MainPage::MyProperty(int32_t /* value */)
{
throw hresult_not_implemented();
}
void MainPage::ClickHandler(IInspectable const&, RoutedEventArgs const&)
{
myButton().Content(box_value(L"Clicked"));
StaticLibrary1::Class aa;
aa.showP1();
}
}
| [
"v-faywan@microsoft.com"
] | v-faywan@microsoft.com |
1615f37d81f147a8ecc9820d9625355300c8fe66 | 53aaac390ce455b4039aa0e68375885adae99111 | /Array/reverse_array.cpp | 99a482c66b0067cb006446ae548941682bba5e7f | [] | no_license | devesh-iitism/Data-Structures | 419bd41207d58edf23d72f946a080be5b32f3e21 | 8c955fc2a55f8ef01b17b3fc3d5fdbc39bc06ae3 | refs/heads/master | 2023-05-14T11:19:29.099647 | 2021-06-08T02:03:41 | 2021-06-08T02:03:41 | 368,142,197 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 499 | cpp | #include<bits/stdc++.h>
#define pb push_back
using namespace std;
int main()
{
int n; cin>>n;
vector<int> arr(n, 0);
for(int i=0;i<n;i++) {
cin>>arr[i];
}
cout<<"Before: ";
for(int i=0;i<n;i++) {
cout<<arr[i]<<" ";
}
cout<<"\n";
int l = 0, r = n-1;
while(l<r) {
swap(arr[l], arr[r]);
l++;
r--;
}
cout<<"After: ";
for(int i=0;i<n;i++) {
cout<<arr[i]<<" ";
}
cout<<"\n";
return 0;
} | [
"dcdev001@gmail.com"
] | dcdev001@gmail.com |
6870ac65a787817b64c4dde8594a1141adfc4f20 | 85b9ce4fb88972d9b86dce594ae4fb3acfcd0a4b | /build/Android/Release/Global Pot/app/src/main/include/Fuse.Animations.MasterPropertyGet.h | a733d6ac85b16a46bf4b5cb4616e6ea7b020f558 | [] | no_license | bgirr/Global-Pot_App | 16431a99e26f1c60dc16223fb388d9fd525cb5fa | c96c5a8fb95acde66fc286bcd9a5cdf160ba8b1b | refs/heads/master | 2021-01-09T06:29:18.255583 | 2017-02-21T23:27:47 | 2017-02-21T23:27:47 | 80,985,681 | 0 | 0 | null | 2017-02-21T23:27:48 | 2017-02-05T10:29:14 | C++ | UTF-8 | C++ | false | false | 685 | h | // This file was generated based on C:\Users\EliteBook-User\AppData\Local\Fusetools\Packages\Fuse.Animations\0.44.1\$.uno.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Uno.Object.h>
namespace g{
namespace Fuse{
namespace Animations{
// internal abstract interface MasterPropertyGet :1704
// {
uInterfaceType* MasterPropertyGet_typeof();
struct MasterPropertyGet
{
void(*fp_GetPropertyObject)(uObject*, uObject**);
static uObject* GetPropertyObject(const uInterface& __this) { uObject* __retval; return __this.VTable<MasterPropertyGet>()->fp_GetPropertyObject(__this, &__retval), __retval; }
};
// }
}}} // ::g::Fuse::Animations
| [
"girr.benjamin@gmail.com"
] | girr.benjamin@gmail.com |
ee30b318a81b221ce7770cb5b0a082e289ffc982 | 41b4adb10cc86338d85db6636900168f55e7ff18 | /aws-cpp-sdk-storagegateway/source/model/ErrorCode.cpp | 6307f8d502af4e923b791bf91d805c84ee83b32e | [
"JSON",
"MIT",
"Apache-2.0"
] | permissive | totalkyos/AWS | 1c9ac30206ef6cf8ca38d2c3d1496fa9c15e5e80 | 7cb444814e938f3df59530ea4ebe8e19b9418793 | refs/heads/master | 2021-01-20T20:42:09.978428 | 2016-07-16T00:03:49 | 2016-07-16T00:03:49 | 63,465,708 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 21,369 | cpp | /*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include <aws/storagegateway/model/ErrorCode.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>
using namespace Aws::Utils;
namespace Aws
{
namespace StorageGateway
{
namespace Model
{
namespace ErrorCodeMapper
{
static const int ActivationKeyExpired_HASH = HashingUtils::HashString("ActivationKeyExpired");
static const int ActivationKeyInvalid_HASH = HashingUtils::HashString("ActivationKeyInvalid");
static const int ActivationKeyNotFound_HASH = HashingUtils::HashString("ActivationKeyNotFound");
static const int GatewayInternalError_HASH = HashingUtils::HashString("GatewayInternalError");
static const int GatewayNotConnected_HASH = HashingUtils::HashString("GatewayNotConnected");
static const int GatewayNotFound_HASH = HashingUtils::HashString("GatewayNotFound");
static const int GatewayProxyNetworkConnectionBusy_HASH = HashingUtils::HashString("GatewayProxyNetworkConnectionBusy");
static const int AuthenticationFailure_HASH = HashingUtils::HashString("AuthenticationFailure");
static const int BandwidthThrottleScheduleNotFound_HASH = HashingUtils::HashString("BandwidthThrottleScheduleNotFound");
static const int Blocked_HASH = HashingUtils::HashString("Blocked");
static const int CannotExportSnapshot_HASH = HashingUtils::HashString("CannotExportSnapshot");
static const int ChapCredentialNotFound_HASH = HashingUtils::HashString("ChapCredentialNotFound");
static const int DiskAlreadyAllocated_HASH = HashingUtils::HashString("DiskAlreadyAllocated");
static const int DiskDoesNotExist_HASH = HashingUtils::HashString("DiskDoesNotExist");
static const int DiskSizeGreaterThanVolumeMaxSize_HASH = HashingUtils::HashString("DiskSizeGreaterThanVolumeMaxSize");
static const int DiskSizeLessThanVolumeSize_HASH = HashingUtils::HashString("DiskSizeLessThanVolumeSize");
static const int DiskSizeNotGigAligned_HASH = HashingUtils::HashString("DiskSizeNotGigAligned");
static const int DuplicateCertificateInfo_HASH = HashingUtils::HashString("DuplicateCertificateInfo");
static const int DuplicateSchedule_HASH = HashingUtils::HashString("DuplicateSchedule");
static const int EndpointNotFound_HASH = HashingUtils::HashString("EndpointNotFound");
static const int IAMNotSupported_HASH = HashingUtils::HashString("IAMNotSupported");
static const int InitiatorInvalid_HASH = HashingUtils::HashString("InitiatorInvalid");
static const int InitiatorNotFound_HASH = HashingUtils::HashString("InitiatorNotFound");
static const int InternalError_HASH = HashingUtils::HashString("InternalError");
static const int InvalidGateway_HASH = HashingUtils::HashString("InvalidGateway");
static const int InvalidEndpoint_HASH = HashingUtils::HashString("InvalidEndpoint");
static const int InvalidParameters_HASH = HashingUtils::HashString("InvalidParameters");
static const int InvalidSchedule_HASH = HashingUtils::HashString("InvalidSchedule");
static const int LocalStorageLimitExceeded_HASH = HashingUtils::HashString("LocalStorageLimitExceeded");
static const int LunAlreadyAllocated_HASH = HashingUtils::HashString("LunAlreadyAllocated ");
static const int LunInvalid_HASH = HashingUtils::HashString("LunInvalid");
static const int MaximumContentLengthExceeded_HASH = HashingUtils::HashString("MaximumContentLengthExceeded");
static const int MaximumTapeCartridgeCountExceeded_HASH = HashingUtils::HashString("MaximumTapeCartridgeCountExceeded");
static const int MaximumVolumeCountExceeded_HASH = HashingUtils::HashString("MaximumVolumeCountExceeded");
static const int NetworkConfigurationChanged_HASH = HashingUtils::HashString("NetworkConfigurationChanged");
static const int NoDisksAvailable_HASH = HashingUtils::HashString("NoDisksAvailable");
static const int NotImplemented_HASH = HashingUtils::HashString("NotImplemented");
static const int NotSupported_HASH = HashingUtils::HashString("NotSupported");
static const int OperationAborted_HASH = HashingUtils::HashString("OperationAborted");
static const int OutdatedGateway_HASH = HashingUtils::HashString("OutdatedGateway");
static const int ParametersNotImplemented_HASH = HashingUtils::HashString("ParametersNotImplemented");
static const int RegionInvalid_HASH = HashingUtils::HashString("RegionInvalid");
static const int RequestTimeout_HASH = HashingUtils::HashString("RequestTimeout");
static const int ServiceUnavailable_HASH = HashingUtils::HashString("ServiceUnavailable");
static const int SnapshotDeleted_HASH = HashingUtils::HashString("SnapshotDeleted");
static const int SnapshotIdInvalid_HASH = HashingUtils::HashString("SnapshotIdInvalid");
static const int SnapshotInProgress_HASH = HashingUtils::HashString("SnapshotInProgress");
static const int SnapshotNotFound_HASH = HashingUtils::HashString("SnapshotNotFound");
static const int SnapshotScheduleNotFound_HASH = HashingUtils::HashString("SnapshotScheduleNotFound");
static const int StagingAreaFull_HASH = HashingUtils::HashString("StagingAreaFull");
static const int StorageFailure_HASH = HashingUtils::HashString("StorageFailure");
static const int TapeCartridgeNotFound_HASH = HashingUtils::HashString("TapeCartridgeNotFound");
static const int TargetAlreadyExists_HASH = HashingUtils::HashString("TargetAlreadyExists");
static const int TargetInvalid_HASH = HashingUtils::HashString("TargetInvalid");
static const int TargetNotFound_HASH = HashingUtils::HashString("TargetNotFound");
static const int UnauthorizedOperation_HASH = HashingUtils::HashString("UnauthorizedOperation");
static const int VolumeAlreadyExists_HASH = HashingUtils::HashString("VolumeAlreadyExists");
static const int VolumeIdInvalid_HASH = HashingUtils::HashString("VolumeIdInvalid");
static const int VolumeInUse_HASH = HashingUtils::HashString("VolumeInUse");
static const int VolumeNotFound_HASH = HashingUtils::HashString("VolumeNotFound");
static const int VolumeNotReady_HASH = HashingUtils::HashString("VolumeNotReady");
ErrorCode GetErrorCodeForName(const Aws::String& name)
{
int hashCode = HashingUtils::HashString(name.c_str());
if (hashCode == ActivationKeyExpired_HASH)
{
return ErrorCode::ActivationKeyExpired;
}
else if (hashCode == ActivationKeyInvalid_HASH)
{
return ErrorCode::ActivationKeyInvalid;
}
else if (hashCode == ActivationKeyNotFound_HASH)
{
return ErrorCode::ActivationKeyNotFound;
}
else if (hashCode == GatewayInternalError_HASH)
{
return ErrorCode::GatewayInternalError;
}
else if (hashCode == GatewayNotConnected_HASH)
{
return ErrorCode::GatewayNotConnected;
}
else if (hashCode == GatewayNotFound_HASH)
{
return ErrorCode::GatewayNotFound;
}
else if (hashCode == GatewayProxyNetworkConnectionBusy_HASH)
{
return ErrorCode::GatewayProxyNetworkConnectionBusy;
}
else if (hashCode == AuthenticationFailure_HASH)
{
return ErrorCode::AuthenticationFailure;
}
else if (hashCode == BandwidthThrottleScheduleNotFound_HASH)
{
return ErrorCode::BandwidthThrottleScheduleNotFound;
}
else if (hashCode == Blocked_HASH)
{
return ErrorCode::Blocked;
}
else if (hashCode == CannotExportSnapshot_HASH)
{
return ErrorCode::CannotExportSnapshot;
}
else if (hashCode == ChapCredentialNotFound_HASH)
{
return ErrorCode::ChapCredentialNotFound;
}
else if (hashCode == DiskAlreadyAllocated_HASH)
{
return ErrorCode::DiskAlreadyAllocated;
}
else if (hashCode == DiskDoesNotExist_HASH)
{
return ErrorCode::DiskDoesNotExist;
}
else if (hashCode == DiskSizeGreaterThanVolumeMaxSize_HASH)
{
return ErrorCode::DiskSizeGreaterThanVolumeMaxSize;
}
else if (hashCode == DiskSizeLessThanVolumeSize_HASH)
{
return ErrorCode::DiskSizeLessThanVolumeSize;
}
else if (hashCode == DiskSizeNotGigAligned_HASH)
{
return ErrorCode::DiskSizeNotGigAligned;
}
else if (hashCode == DuplicateCertificateInfo_HASH)
{
return ErrorCode::DuplicateCertificateInfo;
}
else if (hashCode == DuplicateSchedule_HASH)
{
return ErrorCode::DuplicateSchedule;
}
else if (hashCode == EndpointNotFound_HASH)
{
return ErrorCode::EndpointNotFound;
}
else if (hashCode == IAMNotSupported_HASH)
{
return ErrorCode::IAMNotSupported;
}
else if (hashCode == InitiatorInvalid_HASH)
{
return ErrorCode::InitiatorInvalid;
}
else if (hashCode == InitiatorNotFound_HASH)
{
return ErrorCode::InitiatorNotFound;
}
else if (hashCode == InternalError_HASH)
{
return ErrorCode::InternalError;
}
else if (hashCode == InvalidGateway_HASH)
{
return ErrorCode::InvalidGateway;
}
else if (hashCode == InvalidEndpoint_HASH)
{
return ErrorCode::InvalidEndpoint;
}
else if (hashCode == InvalidParameters_HASH)
{
return ErrorCode::InvalidParameters;
}
else if (hashCode == InvalidSchedule_HASH)
{
return ErrorCode::InvalidSchedule;
}
else if (hashCode == LocalStorageLimitExceeded_HASH)
{
return ErrorCode::LocalStorageLimitExceeded;
}
else if (hashCode == LunAlreadyAllocated_HASH)
{
return ErrorCode::LunAlreadyAllocated;
}
else if (hashCode == LunInvalid_HASH)
{
return ErrorCode::LunInvalid;
}
else if (hashCode == MaximumContentLengthExceeded_HASH)
{
return ErrorCode::MaximumContentLengthExceeded;
}
else if (hashCode == MaximumTapeCartridgeCountExceeded_HASH)
{
return ErrorCode::MaximumTapeCartridgeCountExceeded;
}
else if (hashCode == MaximumVolumeCountExceeded_HASH)
{
return ErrorCode::MaximumVolumeCountExceeded;
}
else if (hashCode == NetworkConfigurationChanged_HASH)
{
return ErrorCode::NetworkConfigurationChanged;
}
else if (hashCode == NoDisksAvailable_HASH)
{
return ErrorCode::NoDisksAvailable;
}
else if (hashCode == NotImplemented_HASH)
{
return ErrorCode::NotImplemented;
}
else if (hashCode == NotSupported_HASH)
{
return ErrorCode::NotSupported;
}
else if (hashCode == OperationAborted_HASH)
{
return ErrorCode::OperationAborted;
}
else if (hashCode == OutdatedGateway_HASH)
{
return ErrorCode::OutdatedGateway;
}
else if (hashCode == ParametersNotImplemented_HASH)
{
return ErrorCode::ParametersNotImplemented;
}
else if (hashCode == RegionInvalid_HASH)
{
return ErrorCode::RegionInvalid;
}
else if (hashCode == RequestTimeout_HASH)
{
return ErrorCode::RequestTimeout;
}
else if (hashCode == ServiceUnavailable_HASH)
{
return ErrorCode::ServiceUnavailable;
}
else if (hashCode == SnapshotDeleted_HASH)
{
return ErrorCode::SnapshotDeleted;
}
else if (hashCode == SnapshotIdInvalid_HASH)
{
return ErrorCode::SnapshotIdInvalid;
}
else if (hashCode == SnapshotInProgress_HASH)
{
return ErrorCode::SnapshotInProgress;
}
else if (hashCode == SnapshotNotFound_HASH)
{
return ErrorCode::SnapshotNotFound;
}
else if (hashCode == SnapshotScheduleNotFound_HASH)
{
return ErrorCode::SnapshotScheduleNotFound;
}
else if (hashCode == StagingAreaFull_HASH)
{
return ErrorCode::StagingAreaFull;
}
else if (hashCode == StorageFailure_HASH)
{
return ErrorCode::StorageFailure;
}
else if (hashCode == TapeCartridgeNotFound_HASH)
{
return ErrorCode::TapeCartridgeNotFound;
}
else if (hashCode == TargetAlreadyExists_HASH)
{
return ErrorCode::TargetAlreadyExists;
}
else if (hashCode == TargetInvalid_HASH)
{
return ErrorCode::TargetInvalid;
}
else if (hashCode == TargetNotFound_HASH)
{
return ErrorCode::TargetNotFound;
}
else if (hashCode == UnauthorizedOperation_HASH)
{
return ErrorCode::UnauthorizedOperation;
}
else if (hashCode == VolumeAlreadyExists_HASH)
{
return ErrorCode::VolumeAlreadyExists;
}
else if (hashCode == VolumeIdInvalid_HASH)
{
return ErrorCode::VolumeIdInvalid;
}
else if (hashCode == VolumeInUse_HASH)
{
return ErrorCode::VolumeInUse;
}
else if (hashCode == VolumeNotFound_HASH)
{
return ErrorCode::VolumeNotFound;
}
else if (hashCode == VolumeNotReady_HASH)
{
return ErrorCode::VolumeNotReady;
}
EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
if(overflowContainer)
{
overflowContainer->StoreOverflow(hashCode, name);
return static_cast<ErrorCode>(hashCode);
}
return ErrorCode::NOT_SET;
}
Aws::String GetNameForErrorCode(ErrorCode enumValue)
{
switch(enumValue)
{
case ErrorCode::ActivationKeyExpired:
return "ActivationKeyExpired";
case ErrorCode::ActivationKeyInvalid:
return "ActivationKeyInvalid";
case ErrorCode::ActivationKeyNotFound:
return "ActivationKeyNotFound";
case ErrorCode::GatewayInternalError:
return "GatewayInternalError";
case ErrorCode::GatewayNotConnected:
return "GatewayNotConnected";
case ErrorCode::GatewayNotFound:
return "GatewayNotFound";
case ErrorCode::GatewayProxyNetworkConnectionBusy:
return "GatewayProxyNetworkConnectionBusy";
case ErrorCode::AuthenticationFailure:
return "AuthenticationFailure";
case ErrorCode::BandwidthThrottleScheduleNotFound:
return "BandwidthThrottleScheduleNotFound";
case ErrorCode::Blocked:
return "Blocked";
case ErrorCode::CannotExportSnapshot:
return "CannotExportSnapshot";
case ErrorCode::ChapCredentialNotFound:
return "ChapCredentialNotFound";
case ErrorCode::DiskAlreadyAllocated:
return "DiskAlreadyAllocated";
case ErrorCode::DiskDoesNotExist:
return "DiskDoesNotExist";
case ErrorCode::DiskSizeGreaterThanVolumeMaxSize:
return "DiskSizeGreaterThanVolumeMaxSize";
case ErrorCode::DiskSizeLessThanVolumeSize:
return "DiskSizeLessThanVolumeSize";
case ErrorCode::DiskSizeNotGigAligned:
return "DiskSizeNotGigAligned";
case ErrorCode::DuplicateCertificateInfo:
return "DuplicateCertificateInfo";
case ErrorCode::DuplicateSchedule:
return "DuplicateSchedule";
case ErrorCode::EndpointNotFound:
return "EndpointNotFound";
case ErrorCode::IAMNotSupported:
return "IAMNotSupported";
case ErrorCode::InitiatorInvalid:
return "InitiatorInvalid";
case ErrorCode::InitiatorNotFound:
return "InitiatorNotFound";
case ErrorCode::InternalError:
return "InternalError";
case ErrorCode::InvalidGateway:
return "InvalidGateway";
case ErrorCode::InvalidEndpoint:
return "InvalidEndpoint";
case ErrorCode::InvalidParameters:
return "InvalidParameters";
case ErrorCode::InvalidSchedule:
return "InvalidSchedule";
case ErrorCode::LocalStorageLimitExceeded:
return "LocalStorageLimitExceeded";
case ErrorCode::LunAlreadyAllocated:
return "LunAlreadyAllocated ";
case ErrorCode::LunInvalid:
return "LunInvalid";
case ErrorCode::MaximumContentLengthExceeded:
return "MaximumContentLengthExceeded";
case ErrorCode::MaximumTapeCartridgeCountExceeded:
return "MaximumTapeCartridgeCountExceeded";
case ErrorCode::MaximumVolumeCountExceeded:
return "MaximumVolumeCountExceeded";
case ErrorCode::NetworkConfigurationChanged:
return "NetworkConfigurationChanged";
case ErrorCode::NoDisksAvailable:
return "NoDisksAvailable";
case ErrorCode::NotImplemented:
return "NotImplemented";
case ErrorCode::NotSupported:
return "NotSupported";
case ErrorCode::OperationAborted:
return "OperationAborted";
case ErrorCode::OutdatedGateway:
return "OutdatedGateway";
case ErrorCode::ParametersNotImplemented:
return "ParametersNotImplemented";
case ErrorCode::RegionInvalid:
return "RegionInvalid";
case ErrorCode::RequestTimeout:
return "RequestTimeout";
case ErrorCode::ServiceUnavailable:
return "ServiceUnavailable";
case ErrorCode::SnapshotDeleted:
return "SnapshotDeleted";
case ErrorCode::SnapshotIdInvalid:
return "SnapshotIdInvalid";
case ErrorCode::SnapshotInProgress:
return "SnapshotInProgress";
case ErrorCode::SnapshotNotFound:
return "SnapshotNotFound";
case ErrorCode::SnapshotScheduleNotFound:
return "SnapshotScheduleNotFound";
case ErrorCode::StagingAreaFull:
return "StagingAreaFull";
case ErrorCode::StorageFailure:
return "StorageFailure";
case ErrorCode::TapeCartridgeNotFound:
return "TapeCartridgeNotFound";
case ErrorCode::TargetAlreadyExists:
return "TargetAlreadyExists";
case ErrorCode::TargetInvalid:
return "TargetInvalid";
case ErrorCode::TargetNotFound:
return "TargetNotFound";
case ErrorCode::UnauthorizedOperation:
return "UnauthorizedOperation";
case ErrorCode::VolumeAlreadyExists:
return "VolumeAlreadyExists";
case ErrorCode::VolumeIdInvalid:
return "VolumeIdInvalid";
case ErrorCode::VolumeInUse:
return "VolumeInUse";
case ErrorCode::VolumeNotFound:
return "VolumeNotFound";
case ErrorCode::VolumeNotReady:
return "VolumeNotReady";
default:
EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
if(overflowContainer)
{
return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
}
return "";
}
}
} // namespace ErrorCodeMapper
} // namespace Model
} // namespace StorageGateway
} // namespace Aws
| [
"henso@amazon.com"
] | henso@amazon.com |
981a8fbedba3b2b38b6778717cf006506b9adc33 | f730e0181244b8035c0a08f43f3ca157f16c3eed | /admin.cpp | 99f2472c0032df11e15971179c6650ad4055eca1 | [] | no_license | EdelAlan/PurchaseOrderManagementSystem | fc9f062a9d0dd7007f7be578d56cae490ff1628a | 690b9008aceef73b658fed9c4610a6cfdf597be4 | refs/heads/master | 2021-01-01T19:31:24.891290 | 2017-07-28T02:41:42 | 2017-07-28T02:41:42 | 98,600,313 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,311 | cpp | #include <stdio.h>
#include "admin.h"
using namespace std;
void admin::menu() {
std::cout << "Signed as Admin" << std::endl;
std::cout << std::endl;
std::cout << "1. Item Entry" << std::endl;
std::cout << "2. Supplier Entry" << std::endl;
std::cout << "3. Daily Sales Entry" << std::endl;
std::cout << "4. Create a Purchase Requisition" << std::endl;
std::cout << "5. Display Requisitions" << std::endl;
std::cout << "6. Display Purchase Orders" << std::endl;
std::cout << "7. Display Items" << std::endl;
std::cout << "8. Display Suppliers" << std::endl;
std::cout << "9. Register New User" << std::endl;
std::cout << "0. Log out" << std::endl;
int i;
std::cout << "Enter the number: ";
std::cin >> i;
std::cout << std::endl;
if (i == 1) itemEntry();
else if (i == 2) supplierEntry();
else if (i == 3) dailySalesEntry();
else if (i == 4) createPR();
else if (i == 5) displayPRs();
else if (i == 6) displayPOs();
else if (i == 7) displayItems();
else if (i == 8) displaySuppliers();
else if (i == 9) registerUser();
else if (i == 0) logout();
else menu();
}
admin::admin() {}
const std::string &admin::getUsername() const {
return username;
}
const std::string &admin::getPassword() const {
return password;
}
void admin::createPO() {
PurchaseManager::createPO();
menu();
}
void admin::displayItems() {
for (unsigned int i = 0; i < salesManager.getItems()->size(); ++i) {
cout << i + 1 << ". ID - " << salesManager.getItems()->at(i).getId()
<< ". Name - " << salesManager.getItems()->at(i).getName()
<< ". Quantity - " << salesManager.getItems()->at(i).getQuantity()
<< ". Supplier - " << salesManager.getItems()->at(i).getSupplier() << endl;
}
menu();
}
void admin::displaySuppliers() {
for (unsigned int i = 0; i < salesManager.getSuppliers()->size(); ++i) {
cout << i + 1 << ". ID: " << salesManager.getSuppliers()->at(i).getId() << ". Name: "
<< salesManager.getSuppliers()->at(i).getName() << endl;
}
menu();
}
void admin::itemEntry() {
cout << "Item Entry Menu" << endl;
cout << endl;
cout << "1. Add Item" << endl;
cout << "2. Delete Item" << endl;
cout << "3. Edit Item" << endl;
cout << "0. Exit to Main Menu" << endl;
int i;
cout << "Enter the number: ";
cin >> i;
if (i == 1) addItem();
else if (i == 2) deleteItem();
else if (i == 3) editItem();
else if (i == 0) menu();
else itemEntry();
}
void admin::addItem() {
SalesManager::addItem();
}
void admin::deleteItem() {
SalesManager::deleteItem();
}
void admin::editItem() {
SalesManager::editItem();
}
void admin::supplierEntry() {
cout << "Supplier Entry Menu" << endl;
cout << endl;
cout << "1. Add Supplier" << endl;
cout << "2. Delete Supplier" << endl;
cout << "3. Edit Supplier" << endl;
cout << "0. Exit to Main Menu" << endl;
int i;
cout << "Enter the number: ";
cin >> i;
if (i == 1) addSupplier();
else if (i == 2) deleteSupplier();
else if (i == 3) editSupplier();
else if (i == 0) menu();
else supplierEntry();
}
void admin::addSupplier() {
SalesManager::addSupplier();
}
void admin::deleteSupplier() {
SalesManager::deleteSupplier();
}
void admin::editSupplier() {
SalesManager::editSupplier();
}
void admin::dailySalesEntry() {
int id;
int quantity;
cout << "Daily Sales Entry Menu" << endl;
cout << endl;
cout << "Enter id: " << endl;
cin >> id;
cout << "Enter quantity: " << endl;
cin >> quantity;
int choose;
for (unsigned int i = 0; i < items->size(); ++i) {
cout << i + 1 << ". ID - " << items->at(i).getId()
<< ". Name - " << items->at(i).getName()
<< ". Quantity - " << items->at(i).getQuantity()
<< ". Supplier - " << items->at(i).getSupplier() << endl;
}
cout << endl;
cout << "Enter item's number: ";
cin >> choose;
cout << endl;
if (quantity < 0) {
cout << "Wrong input" << endl;
menu();
} else {
items->at(choose - 1).setQuantity(items->at(choose - 1).getQuantity() - quantity);
cout << "Item - " << items->at(choose - 1).getName() << endl
<< "New quantity - " << items->at(choose - 1).getQuantity() << endl;
}
DailyItemWise *dailyItemWise = new DailyItemWise(id, quantity);
dailyItemWises->push_back(*dailyItemWise);
menu();
}
void admin::createPR() {
SalesManager::createPR();
menu();
}
void admin::displayPRs() {
for (unsigned int i = 0; i < purchaseRequisitions->size(); ++i) {
cout << endl
<< endl << "Purchase Requisition ID - " << purchaseRequisitions->at(i).getId()
<< endl << "Item - ID" << purchaseRequisitions->at(i).getItem()
<< endl << "Quantity asked - " << purchaseRequisitions->at(i).getNeededQuantity()
<< endl << "Created by Sales Manager - ID" << purchaseRequisitions->at(i).getSalesManager() << endl;
}
menu();
}
void admin::displayPOs() {
for (unsigned int i = 0; i < purchaseOrders->size(); ++i) {
cout << endl
<< endl << "Purchase Order ID - " << purchaseOrders->at(i).getID()
<< endl << "Purchase Requisition ID - " << purchaseOrders->at(i).getPrID()
<< endl << "Approved by Purchase Manager - ID" << purchaseOrders->at(i).getPurchaseManager();
}
menu();
}
void admin::logout() {
login();
}
void admin::registerUser() {
std::cout << "Register Menu" << std::endl;
std::cout << std::endl;
std::cout << "1. Register Sales Manager" << std::endl;
std::cout << "2. Register Purchase Manager" << std::endl;
std::cout << "0. Menu" << std::endl;
int i;
std::cout << "Enter the number: ";
std::cin >> i;
std::cout << std::endl;
if (i == 1) registerSm();
else if (i == 2) registerPm();
else menu();
}
void admin::registerPm() {
std::string null = "0";
int id;
std::string name;
std::string password;
std::cout << std::endl;
std::cout << "Enter Purchase Manager's ID, enter 0 to exit: ";
std::cin >> id;
if (id == 0) { registerUser(); }
else {
for (unsigned int i = 0; i < purchaseManagers->size(); ++i) {
if (purchaseManagers->at(i).getId() == id) {
std::cout << std::endl << " Purchase Manager with such Id already exists" << std::endl;
registerUser();
break;
} else continue;
}
std::cout << std::endl;
std::cout << "Enter Purchase Manager's name, enter 0 to exit: ";
std::cin >> name;
if (name == null) { registerUser(); }
else {
for (unsigned int i = 0; i < purchaseManagers->size(); ++i) {
if (purchaseManagers->at(i).getName() == name) {
std::cout << " Purchase Manager with such name already exists" << std::endl;
registerUser();
break;
} else continue;
}
std::cout << "Create password: ";
std::cin >> password;
std::cout << std::endl;
PurchaseManager *purchaseManager = new PurchaseManager(id, name, password);
purchaseManagers->push_back(*purchaseManager);
std::cout << std::endl << "New Purchase Manager was saved"
<< std::endl << "ID: " << id
<< std::endl << "Name: " << name << std::endl;
registerUser();
}
}
}
void admin::registerSm() {
std::string null = "0";
int id;
std::string name;
std::string password;
std::cout << std::endl;
std::cout << "Enter Sales Manager's ID, enter 0 to exit: ";
std::cin >> id;
if (id == 0) { registerUser(); }
else {
for (unsigned int i = 0; i < salesManagers->size(); ++i) {
if (salesManagers->at(i).getId() == id) {
std::cout << std::endl << " Sales Manager with such Id already exists" << std::endl;
registerUser();
break;
} else continue;
}
std::cout << std::endl;
std::cout << "Enter Sales Manager's name, enter 0 to exit: ";
std::cin >> name;
if (name == null) { registerUser(); }
else {
for (unsigned int i = 0; i < salesManagers->size(); ++i) {
if (salesManagers->at(i).getName() == name) {
std::cout << " Sales Manager with such name already exists" << std::endl;
registerUser();
break;
} else continue;
}
std::cout << "Create password: ";
std::cin >> password;
std::cout << std::endl;
SalesManager *salesManager = new SalesManager(id, name, password);
salesManagers->push_back(*salesManager);
std::cout << std::endl << "New Sales Manager was saved"
<< std::endl << "ID: " << id
<< std::endl << "Name: " << name << std::endl;
registerUser();
}
}
}
void admin::login() {
std::string username;
std::string password;
std::cout << std::endl << "Login Menu" << std::endl;
std::cout << "Enter username: ";
std::cin >> username;
std::cout << "Enter password: ";
std::cin >> password;
if (username == this->getUsername() && password == this->getPassword()) {
this->menu();
}
for (unsigned int i = 0; i < purchaseManagers->size(); ++i) {
if (username == purchaseManagers->at(i).getName() && password == purchaseManagers->at(i).getPassword()) {
purchaseManagers->at(i).menu();
}
}
for (unsigned int i = 0; i < salesManagers->size(); ++i) {
if (username == salesManagers->at(i).getName() && password == salesManagers->at(i).getPassword()) {
salesManagers->at(i).menu();
} else if (username == this->getUsername() && password == this->getPassword()) {
this->menu();
}
}
std::cout << "wrong input" << std::endl;
login();
}
| [
"my.magic@mail.ru"
] | my.magic@mail.ru |
7daaa44851dee0f89b9408248a411398998fe570 | 220a9d0f6a7dea7c6eeea192a820e8c53dd4bbd1 | /crack/main.cpp | 5c5780ad7a95541d364dc3407fbf3900a111b6b1 | [] | no_license | IamLupo/hackhound-cyber-challenge | 8e340fc4ef8ec62be1eaadf183e16311d9e57fa2 | 759c322924f7594d35e396c24fb7edbc2a181a6c | refs/heads/master | 2021-01-10T17:56:52.258273 | 2014-02-05T18:27:44 | 2014-02-05T18:27:44 | 44,474,075 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 34,243 | cpp | #include <boost/thread.hpp>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <windows.h>
using namespace std;
enum Secret_Message
{
MSG_DEC_SUCCES,
MSG_ENC_SUCCES,
MSG_USAGE,
MSG_ERROR_INPUT_FILE,
MSG_ERROR_OUTPUT_FILE,
MSG_ERROR_FILE_FORMAT,
MSG_ERROR_PASSWORD,
MSG_ERROR_MALFUNCTION
};
enum Thread_Status
{
THREAD_STATUS_NONE = -1,
THREAD_STATUS_RUNNING,
THREAD_STATUS_FINISHED
};
//Functions
unsigned int ThreadReverseMultiplication(int threads, unsigned int output, unsigned int mul);
void FindMasterThree(Thread_Status* thread_status, unsigned int begin, unsigned int end,
unsigned int master_key[4], unsigned int enc_file_keys_3, unsigned int time);
char secret_message_0[] = { 0x4C, 0x77, 0x21, 0x26, 0x53, 0x50, 0x7C, 0x23, 0x25, 0x7A, 0x60,
0x51, 0x27, 0x21, 0x21, 0x77, 0x77, 0x4C, 0x77, 0x4C, 0x00 };
char secret_message_1[] = { 0x77, 0x7A, 0x21, 0x26, 0x53, 0x50, 0x7C, 0x23, 0x25, 0x7A, 0x60,
0x51, 0x27, 0x21, 0x21, 0x77, 0x77, 0x4C, 0x77, 0x4C, 0x00 };
char secret_message_2[] = { 0x27, 0x51, 0x4B, 0x4D, 0x77, 0x3E, 0x60, 0x21, 0x26, 0x53, 0x50,
0x7C, 0x60, 0x0F, 0x49, 0x4C, 0x65, 0x77, 0x1F, 0x60, 0x49, 0x22,
0x23, 0x24, 0x77, 0x75, 0x23, 0x7A, 0x1F, 0x60, 0x49, 0x22, 0x23,
0x24, 0x77, 0x75, 0x25, 0x27, 0x7C, 0x1F, 0x60, 0x49, 0x50, 0x4B,
0x51, 0x51, 0x7D, 0x25, 0x26, 0x4C, 0x1F, 0x00 };
char secret_message_3[] = { 0x77, 0x26, 0x26, 0x25, 0x26, 0x3E, 0x60, 0x21, 0x4B, 0x7A, 0x60,
0x7A, 0x25, 0x7C, 0x60, 0x25, 0x50, 0x77, 0x7A, 0x60, 0x23, 0x7A,
0x50, 0x27, 0x7C, 0x60, 0x22, 0x23, 0x24, 0x77, 0x00 };
char secret_message_4[] = { 0x77, 0x26, 0x26, 0x25, 0x26, 0x3E, 0x60, 0x21, 0x4B, 0x7A, 0x60,
0x7A, 0x25, 0x7C, 0x60, 0x25, 0x50, 0x77, 0x7A, 0x60, 0x25, 0x27,
0x7C, 0x50, 0x27, 0x7C, 0x60, 0x22, 0x23, 0x24, 0x77, 0x00 };
char secret_message_5[] = { 0x77, 0x26, 0x26, 0x25, 0x26, 0x3E, 0x60, 0x23, 0x7A, 0x52, 0x4B,
0x24, 0x23, 0x4C, 0x60, 0x22, 0x23, 0x24, 0x77, 0x60, 0x22, 0x25,
0x26, 0x4F, 0x4B, 0x7C, 0x00 };
char secret_message_6[] = { 0x77, 0x26, 0x26, 0x25, 0x26, 0x3E, 0x60, 0x23, 0x7A, 0x21, 0x25,
0x26, 0x26, 0x77, 0x21, 0x7C, 0x60, 0x50, 0x4B, 0x51, 0x51, 0x7D,
0x25, 0x26, 0x4C, 0x00 };
char secret_message_7[] = { 0x77, 0x26, 0x26, 0x25, 0x26, 0x3E, 0x60, 0x51, 0x25, 0x4F, 0x77,
0x7C, 0x78, 0x23, 0x7A, 0x4D, 0x60, 0x21, 0x4B, 0x27, 0x51, 0x77,
0x4C, 0x60, 0x7C, 0x78, 0x77, 0x60, 0x4B, 0x50, 0x50, 0x24, 0x23,
0x21, 0x4B, 0x7C, 0x23, 0x25, 0x7A, 0x60, 0x7C, 0x25, 0x60, 0x4F,
0x4B, 0x24, 0x22, 0x27, 0x7A, 0x21, 0x7C, 0x23, 0x25, 0x7A, 0x00 };
char secret_message_8[] = { 0x1C, 0x26, 0x25, 0x24, 0x25, 0x24, 0x25, 0x24, 0x25, 0x00 };
void DecryptMessage(char* message)
{
unsigned int message_length = (unsigned)strlen(message);
int i;
for (i = 0; i < message_length; i++)
{
message[i] = (message[i] * 3) & 0x8000007F;
}
}
void ShowMessageAndExit(Secret_Message id)
{
char* message_ptr;
if(id == MSG_DEC_SUCCES)
message_ptr = secret_message_0;
else if(id == MSG_ENC_SUCCES)
message_ptr = secret_message_1;
else if(id == MSG_USAGE)
message_ptr = secret_message_2;
else if(id == MSG_ERROR_INPUT_FILE)
message_ptr = secret_message_3;
else if(id == MSG_ERROR_OUTPUT_FILE)
message_ptr = secret_message_4;
else if(id == MSG_ERROR_FILE_FORMAT)
message_ptr = secret_message_5;
else if(id == MSG_ERROR_PASSWORD)
message_ptr = secret_message_6;
else if(id == MSG_ERROR_MALFUNCTION)
message_ptr = secret_message_7;
//Decrypt
DecryptMessage(message_ptr);
//Draw
printf("%s \n", message_ptr);
//Exit
if(id == MSG_DEC_SUCCES || id == MSG_ENC_SUCCES || id == MSG_USAGE)
exit(EXIT_SUCCESS);
else
exit(EXIT_FAILURE);
/* You already know the answer! :D */
}
void InitKey(unsigned int generated_key[4], char* _password)
{
unsigned int i, temp_value;
temp_value = 0x3C;
for(i = 0; i < 16; i++)
{
unsigned int byte_id = i / 4;
unsigned int byte_position = i % 4;
if(byte_position == 0)
generated_key[byte_id] += (temp_value);
else if(byte_position == 1)
generated_key[byte_id] += (temp_value * 0x100);
else if(byte_position == 2)
generated_key[byte_id] += (temp_value * 0x10000);
else if(byte_position == 3)
generated_key[byte_id] += (temp_value * 0x1000000);
}
//Password
unsigned int password_length = strlen(_password);
unsigned int fix = 0x0;
temp_value = (((generated_key[0] & 0xFF000000) / 0x1000000) + password_length) & 0xFF;
generated_key[0] = (temp_value * 0x1000000) + (generated_key[0] & 0x00FFFFFF);
for(i = 0; i < password_length + fix; i++)
{
unsigned int byte_id = ((i + 1) % 16) / 4;
unsigned int byte_position = ((i + 1) % 16) % 4;
if(byte_position == 0 && byte_id == 0)
{
fix += 0x1;
}
else if(byte_position == 0)
{
temp_value = (generated_key[byte_id] & 0xFF000000) / 0x1000000;
temp_value = (temp_value + (unsigned int)_password[i - fix]) & 0xFF;
generated_key[byte_id] = (temp_value * 0x1000000) + (generated_key[byte_id] & 0x00FFFFFF);
}
else if(byte_position == 1)
{
temp_value = (generated_key[byte_id] & 0xFF0000) / 0x10000;
temp_value = (temp_value + (unsigned int)_password[i - fix]) & 0xFF;
generated_key[byte_id] = (temp_value * 0x10000) + (generated_key[byte_id] & 0xFF00FFFF);
}
else if(byte_position == 2)
{
temp_value = (generated_key[byte_id] & 0xFF00) / 0x100;
temp_value = (temp_value + (unsigned int)_password[i - fix]) & 0xFF;
generated_key[byte_id] = (temp_value * 0x100) + (generated_key[byte_id] & 0xFFFF00FF);
}
else if(byte_position == 3)
{
temp_value = generated_key[byte_id] & 0xFF;
temp_value = (temp_value + (unsigned int)_password[i - fix]) & 0xFF;
/* You like carrot? */
generated_key[byte_id] = temp_value + (generated_key[byte_id] & 0xFFFFFF00);
}
}
}
void GenerateKey(unsigned int master_key[4], unsigned int generated_key[4])
{
unsigned int key_values[] = { 0xE, // 0000 1110
0x3, // 0001 0011
0xA, // 0010 1010
0xB, // 0011 1011
0x0, // 0100 0000
0x9, // 0101 1001
0x8, // 0110 1000
0x5, // 0111 0101
0xC, // 1000 1100
0xF, // 1001 1111
0x6, // 1010 0110
0x1, // 1011 0001
0x4, // 1100 0100
0xD, // 1101 1101
0x2, // 1110 0010
0x7 }; // 1111 0111 //4e byte doesnt change! :D hehe :D
unsigned int i;
unsigned int j;
for (i = 0; i < 32; i++)
{
generated_key[0] = (generated_key[0] + master_key[0]) * 0xF97CE7B7;
generated_key[1] = (generated_key[1] + master_key[1]) * 0xE9701ECB;
generated_key[2] = (generated_key[2] + master_key[2]) * 0x70103AA1;
generated_key[3] = (generated_key[3] + master_key[i % 3] + i) * 0xBD810313;
unsigned int temp_key[] = { 0x0, 0x0, 0x0, 0x0 };
for(j = 0; j < 32; j++)
{
unsigned int id;
id = (((generated_key[3] >> (0x1F - j)) & 0x1) * 0x2);
id = (id ^ (generated_key[2] >> (0x1F - j)) & 0x1) * 0x2;
id = (id ^ ((generated_key[1] >> (0x1F - j)) & 0x1)) * 0x2;
id = id ^ ((generated_key[0] >> (0x1F - j)) & 0x1);
temp_key[0] = (key_values[id] & 0x1) ^ (temp_key[0] + temp_key[0]); // Because the first bit never change the generate_key will also not change :D
temp_key[1] = ((key_values[id] >> 0x1) & 0x1) ^ (temp_key[1] + temp_key[1]);
temp_key[2] = ((key_values[id] >> 0x2) & 0x1) ^ (temp_key[2] + temp_key[2]);
temp_key[3] = ((key_values[id] >> 0x3) & 0x1) ^ (temp_key[3] + temp_key[3]);
}
generated_key[0] = temp_key[0];
generated_key[1] = temp_key[1];
generated_key[2] = temp_key[2];
generated_key[3] = temp_key[3];
}
generated_key[0] += master_key[0];
generated_key[1] += master_key[1];
generated_key[2] += master_key[2];
generated_key[3] += master_key[0];
}
void InitMasterKey(unsigned int master_key[4], unsigned int generated_key[4])
{
master_key[0] = generated_key[0];
master_key[1] = generated_key[1];
master_key[2] = generated_key[2];
master_key[3] = generated_key[3];
generated_key[0] = master_key[2] ^ master_key[1] ^ master_key[0];
generated_key[1] = master_key[3] ^ master_key[1] ^ master_key[0];
generated_key[2] = master_key[3] ^ master_key[2] ^ master_key[0];
generated_key[3] = master_key[3] ^ master_key[2] ^ master_key[1];
}
/* Blub */
void InitMasterTimeKey(unsigned int master_key[4], unsigned int mastertime_key[4], unsigned int time)
{
mastertime_key[0] = master_key[0] ^ time;
mastertime_key[1] = master_key[1] ^ time;
mastertime_key[2] = master_key[2] ^ time;
mastertime_key[3] = master_key[3] ^ time;
GenerateKey(master_key, mastertime_key);
}
void Encrypt(char* _input_file, char* _output_file, char* _password)
{
FILE* input_file;
FILE* output_file;
size_t result;
//Open Input File
input_file = fopen(_input_file,"rb");
if(input_file == NULL)
ShowMessageAndExit(MSG_ERROR_INPUT_FILE);
//Create Output File
output_file = fopen(_output_file,"wb");
if(output_file == NULL)
{
fclose(input_file);
ShowMessageAndExit(MSG_ERROR_OUTPUT_FILE);
}
//Make Header
char header[4] = { 'E', 'N', 'C', '/' };
fwrite(header, sizeof(char), 4, output_file);
//generate password hash and write to file
unsigned int generated_key[4] = { 0x0, 0x0, 0x0, 0x0 };
unsigned int master_key[4] = { 0x0, 0x0, 0x0, 0x0 };
InitKey(generated_key, _password);
GenerateKey(master_key, generated_key);
InitMasterKey(master_key, generated_key);
GenerateKey(master_key, generated_key);
char password_hash[4] = { ((generated_key[0] & 0xFF) / 0x1),
((generated_key[0] & 0xFF00) / 0x100),
((generated_key[0] & 0xFF0000) / 0x10000),
((generated_key[0] & 0xFF000000) / 0x1000000)};
fwrite(password_hash, sizeof(char), 4, output_file);
unsigned int time = GetTickCount();
InitMasterTimeKey(master_key, generated_key, time); //WTF WHY?!
char key[4];
for(int i = 0; i < 4; i++)
{
char key[4] = { ((generated_key[i] & 0xFF) / 0x1),
((generated_key[i] & 0xFF00) / 0x100),
((generated_key[i] & 0xFF0000) / 0x10000),
((generated_key[i] & 0xFF000000) / 0x1000000)};
fwrite(key, sizeof(char), 4, output_file);
}
//read data and encrypt it
char buffer[16];
do
{
GenerateKey(master_key, generated_key);
result = fread(buffer, 1, 16, input_file);
buffer[0] = (buffer[0] & 0xFF) ^ (generated_key[0] & 0xFF); // HOP
buffer[1] = (buffer[1] & 0xFF) ^ ((generated_key[0] & 0xFF00) / 0x100); // HOP
buffer[2] = (buffer[2] & 0xFF) ^ ((generated_key[0] & 0xFF0000) / 0x10000); // HOP
buffer[3] = (buffer[3] & 0xFF) ^ ((generated_key[0] & 0xFF000000) / 0x1000000); // HOP
buffer[4] = (buffer[4] & 0xFF) ^ (generated_key[1] & 0xFF); // HOP
buffer[5] = (buffer[5] & 0xFF) ^ ((generated_key[1] & 0xFF00) / 0x100); // HOP
buffer[6] = (buffer[6] & 0xFF) ^ ((generated_key[1] & 0xFF0000) / 0x10000); // HOP
buffer[7] = (buffer[7] & 0xFF) ^ ((generated_key[1] & 0xFF000000) / 0x1000000); // HOP
buffer[8] = (buffer[8] & 0xFF) ^ (generated_key[2] & 0xFF); // HOP
buffer[9] = (buffer[9] & 0xFF) ^ ((generated_key[2] & 0xFF00) / 0x100); // HOP
buffer[10] = (buffer[10] & 0xFF) ^ ((generated_key[2] & 0xFF0000) / 0x10000); // HOP
buffer[11] = (buffer[11] & 0xFF) ^ ((generated_key[2] & 0xFF000000) / 0x1000000); // HOP
buffer[12] = (buffer[12] & 0xFF) ^ (generated_key[3] & 0xFF); // HOP
buffer[13] = (buffer[13] & 0xFF) ^ ((generated_key[3] & 0xFF00) / 0x100); // HOP
buffer[14] = (buffer[14] & 0xFF) ^ ((generated_key[3] & 0xFF0000) / 0x10000); // HOP
buffer[15] = (buffer[15] & 0xFF) ^ ((generated_key[3] & 0xFF000000) / 0x1000000); // HOP
fwrite(buffer, sizeof(char), result, output_file);
}
while(result == 16);
fclose(input_file);
fclose(output_file);
ShowMessageAndExit(MSG_ENC_SUCCES);
}
void Decrypt(char* _input_file, char* _output_file, char* _password)
{
FILE* input_file;
FILE* output_file;
size_t result;
//Open Input File
input_file = fopen(_input_file,"rb");
if(input_file == NULL)
ShowMessageAndExit(MSG_ERROR_INPUT_FILE);
//Create Output File
output_file = fopen(_output_file,"wb");
if(output_file == NULL)
{
fclose(input_file);
ShowMessageAndExit(MSG_ERROR_OUTPUT_FILE);
}
//Read Format
char header[4];
result = fread(header, 1, 4, input_file);
if(result != 4)
{
fclose(input_file);
fclose(output_file);
ShowMessageAndExit(MSG_ERROR_MALFUNCTION);
}
if(header[0] == 0x2F && header[1] == 0x43 && header[2] == 0x4E && header[3] == 0x45 ) // header is "ENC/"
{
fclose(input_file);
fclose(output_file);
ShowMessageAndExit(MSG_ERROR_FILE_FORMAT);
}
//generate password hash with password
unsigned int generated_key[4] = { 0x0, 0x0, 0x0, 0x0 };
unsigned int master_key[4] = { 0x0, 0x0, 0x0, 0x0 };
InitKey(generated_key, _password);
GenerateKey(master_key, generated_key);
InitMasterKey(master_key, generated_key);
GenerateKey(master_key, generated_key);
//Get password hash out of file
char password_hash[4];
result = fread(password_hash, 1, 4, input_file);
if(result != 4)
{
fclose(input_file);
fclose(output_file);
ShowMessageAndExit(MSG_ERROR_MALFUNCTION);
}
//Check Password hash with each other
if( (password_hash[0] & 0xFF) != ((generated_key[0] & 0xFF) / 0x1) ||
(password_hash[1] & 0xFF) != ((generated_key[0] & 0xFF00) / 0x100) ||
(password_hash[2] & 0xFF) != ((generated_key[0] & 0xFF0000) / 0x10000) ||
(password_hash[3] & 0xFF) != ((generated_key[0] & 0xFF000000) / 0x1000000))
{
fclose(input_file);
fclose(output_file);
/* I told you so! */
ShowMessageAndExit(MSG_ERROR_PASSWORD);
}
//Get generated_key out of file
char key[4];
for(int i = 0; i < 4; i++)
{
result = fread(key, 1, 4, input_file);
if(result != 4)
{
fclose(input_file);
fclose(output_file);
ShowMessageAndExit(MSG_ERROR_MALFUNCTION);
}
generated_key[i] = ((key[3] & 0xFF) * 0x1000000) + ((key[2] & 0xFF) * 0x10000) + ((key[1] & 0xFF) * 0x100) + (key[0] & 0xFF);
}
//read data and decrypt it
char buffer[16];
do
{
GenerateKey(master_key, generated_key);
result = fread(buffer, 1, 16, input_file);
buffer[0] = (buffer[0] & 0xFF) ^ (generated_key[0] & 0xFF); // HOP
buffer[1] = (buffer[1] & 0xFF) ^ ((generated_key[0] & 0xFF00) / 0x100); // HOP
buffer[2] = (buffer[2] & 0xFF) ^ ((generated_key[0] & 0xFF0000) / 0x10000); // HOP
buffer[3] = (buffer[3] & 0xFF) ^ ((generated_key[0] & 0xFF000000) / 0x1000000); // HOP
buffer[4] = (buffer[4] & 0xFF) ^ (generated_key[1] & 0xFF); // HOP
buffer[5] = (buffer[5] & 0xFF) ^ ((generated_key[1] & 0xFF00) / 0x100); // HOP
buffer[6] = (buffer[6] & 0xFF) ^ ((generated_key[1] & 0xFF0000) / 0x10000); // HOP
buffer[7] = (buffer[7] & 0xFF) ^ ((generated_key[1] & 0xFF000000) / 0x1000000); // HOP
buffer[8] = (buffer[8] & 0xFF) ^ (generated_key[2] & 0xFF); // HOP
buffer[9] = (buffer[9] & 0xFF) ^ ((generated_key[2] & 0xFF00) / 0x100); // HOP
buffer[10] = (buffer[10] & 0xFF) ^ ((generated_key[2] & 0xFF0000) / 0x10000); // HOP
buffer[11] = (buffer[11] & 0xFF) ^ ((generated_key[2] & 0xFF000000) / 0x1000000); // HOP
buffer[12] = (buffer[12] & 0xFF) ^ (generated_key[3] & 0xFF); // HOP
buffer[13] = (buffer[13] & 0xFF) ^ ((generated_key[3] & 0xFF00) / 0x100); // HOP
buffer[14] = (buffer[14] & 0xFF) ^ ((generated_key[3] & 0xFF0000) / 0x10000); // HOP
buffer[15] = (buffer[15] & 0xFF) ^ ((generated_key[3] & 0xFF000000) / 0x1000000); // HOP
fwrite(buffer, sizeof(char), result, output_file);
}
while(result == 16);
fclose(input_file);
fclose(output_file);
ShowMessageAndExit(MSG_DEC_SUCCES);
}
//---- Reverse Functions ----
void ReverseBites(unsigned int key[4])
{
unsigned int key_values[] = { 0x4, //x
0xB, //x
0xE, //x
0x1, //x
0xC, //x
0x7, //x
0xA, //x
0xF, //x
0x6, //x
0x5, //x
0x2, //x
0x3, //x
0x8, //x
0xD, //x
0x0, //
0x9 }; //
unsigned int id;
unsigned int i;
unsigned int temp_key[] = { 0x0, 0x0, 0x0, 0x0 };
for(i = 0; i < 32; i++)
{
id = (((key[3] >> (0x1F - i)) & 0x1) * 0x2);
id = (id ^ (key[2] >> (0x1F - i)) & 0x1) * 0x2;
id = (id ^ ((key[1] >> (0x1F - i)) & 0x1)) * 0x2;
id = id ^ ((key[0] >> (0x1F - i)) & 0x1);
//temp_key[3] = (key_values[id] & 0x1) ^ (temp_key[3] + temp_key[3]); //fail ! This we can make better :D
temp_key[0] = ((key[0] >> (0x1F - i)) & 0x1) ^ (temp_key[0] + temp_key[0]); // Fix
temp_key[1] = ((key_values[id] >> 0x1) & 0x1) ^ (temp_key[1] + temp_key[1]);
temp_key[2] = ((key_values[id] >> 0x2) & 0x1) ^ (temp_key[2] + temp_key[2]);
temp_key[3] = ((key_values[id] >> 0x3) & 0x1) ^ (temp_key[3] + temp_key[3]);
}
key[0] = temp_key[0];
key[1] = temp_key[1];
key[2] = temp_key[2];
key[3] = temp_key[3];
}
void ReverseMultiplication(unsigned int* return_value, Thread_Status* thread_status, unsigned int begin, unsigned int end, unsigned int output, unsigned int mul)
{
try
{
unsigned int i;
for(i = begin; i < end; i++)
{
if((i * mul) == output)
{
*thread_status = THREAD_STATUS_FINISHED;
*return_value = i;
return;
}
}
}
catch(boost::thread_interrupted&)
{
return;
}
}
void ReverseGenerateKey(int threads, unsigned int master_key[4], unsigned int password_edited[4])
{
password_edited[0] = master_key[0];
password_edited[1] = master_key[1];
password_edited[2] = master_key[2];
password_edited[3] = master_key[3];
unsigned int i;
unsigned int j;
unsigned int id;
for(i = 0; i < 32; i++)
{
id = (31 - i);
ReverseBites(password_edited);
//Multiply
password_edited[0] = ThreadReverseMultiplication(threads, password_edited[0], 0xF97CE7B7);
password_edited[1] = ThreadReverseMultiplication(threads, password_edited[1], 0xE9701ECB);
password_edited[2] = ThreadReverseMultiplication(threads, password_edited[2], 0x70103AA1);
password_edited[3] = ThreadReverseMultiplication(threads, password_edited[3], 0xBD810313) - id;
}
char password[15];
password[0] = (((password_edited[0] & 0xFF00) / 0x100) - 0x3C) & 0xFF;
password[1] = ((password_edited[0] & 0xFF) - 0x3C) & 0xFF;
password[2] = (((password_edited[1] & 0xFF000000) / 0x1000000) - 0x3C) & 0xFF;
password[3] = (((password_edited[1] & 0xFF0000) / 0x10000) - 0x3C) & 0xFF;
password[4] = (((password_edited[1] & 0xFF00) / 0x100) - 0x3C) & 0xFF;
password[5] = ((password_edited[1] & 0xFF) - 0x3C) & 0xFF;
password[6] = (((password_edited[2] & 0xFF000000) / 0x1000000) - 0x3C) & 0xFF;
password[7] = (((password_edited[2] & 0xFF0000) / 0x10000) - 0x3C) & 0xFF;
password[8] = (((password_edited[2] & 0xFF00) / 0x100) - 0x3C) & 0xFF;
password[9] = ((password_edited[2] & 0xFF) - 0x3C) & 0xFF;
password[10] = (((password_edited[3] & 0xFF000000) / 0x1000000) - 0x3C) & 0xFF;
password[11] = (((password_edited[3] & 0xFF0000) / 0x10000) - 0x3C) & 0xFF;
password[12] = (((password_edited[3] & 0xFF00) / 0x100) - 0x3C) & 0xFF;
password[13] = ((password_edited[3] & 0xFF) - 0x3C) & 0xFF;
password[14] = '\0';
cout << master_key[3] << " - " << ((((password_edited[0] & 0xFF0000) / 0x10000) - 0x3C) & 0xFF) << " - " << password << endl;
}
//---- Threads ----
unsigned int ThreadReverseMultiplication(int threads, unsigned int output, unsigned int mul)
{
unsigned int i;
boost::thread_group tgroup;
unsigned int return_value[threads];
Thread_Status thread_status[threads];
unsigned int space = 0xFFFFFFFF / threads;
for(i = 0; i < threads; i++)
{
return_value[i] = 0;
thread_status[i] = THREAD_STATUS_RUNNING;
tgroup.create_thread(
boost::bind(
&ReverseMultiplication,
&return_value[i],
&thread_status[i],
i * space,
(i + 1) * space,
output,
mul
)
);
}
bool found = false;
unsigned int id = 0;
while(!found)
{
for(i = 0; i < threads; i++)
{
if(thread_status[i] == THREAD_STATUS_FINISHED)
{
thread_status[i] = THREAD_STATUS_NONE;
if(return_value[i] != 0)
{
found = true;
id = i;
}
}
}
}
//Ending threads
tgroup.interrupt_all();
tgroup.join_all();
return return_value[id];
}
void FindMasterThree(Thread_Status* thread_status, unsigned int begin, unsigned int end,
unsigned int master_key[4], unsigned int enc_file_keys_3, unsigned int time)
{
try
{
unsigned int i;
unsigned int mastertime_key[4] = { 0x0, 0x0, 0x0, 0x0 };
for(i = begin; i < end; i++)
{
master_key[3] = i;
InitMasterTimeKey(master_key, mastertime_key, time);
if(mastertime_key[3] == enc_file_keys_3)
{
cout << "found = " << i << endl;
}
}
*thread_status = THREAD_STATUS_FINISHED;
return;
}
catch(boost::thread_interrupted&)
{
return;
}
}
//---- Cracker ----
//Part 1
/*
We know that a zip begins with "0x50, 0x4b, 0x03, 0x04". Also we know the encrypted data. We can calculated the next encryption key.
Next we know that GenerateKey function has a bug.
generated_key_0_output = (generated_key_0_input * master_key_0) * 0xF97CE7B7 <- 32 times repeated.
Now we have this case:
generated_key_output = next_encryption_key
generated_key_0_input = 0xe4d6f212;
We now only have to bruteforce the master_key_0
*/
unsigned int Crack_Part_1(unsigned int enc_file_keys_0, unsigned int enc_file_data_0)
{
unsigned int generate;
unsigned int master;
unsigned int check_0 = 0x50 ^ (enc_file_data_0 & 0xFF); //Key part 1
unsigned int check_1 = 0x4b ^ ((enc_file_data_0 & 0xFF00) / 0x100); //Key part 2
unsigned int check_2 = 0x03 ^ ((enc_file_data_0 & 0xFF0000) / 0x10000); //Key part 3
unsigned int check_3 = 0x04 ^ ((enc_file_data_0 & 0xFF000000) / 0x1000000); //Key part 4
unsigned int check_key = (check_3 * 0x1000000) + (check_2 * 0x10000) + (check_1 * 0x100) + check_0;
unsigned int i;
for(i = 0x4293777F; i < 0xFFFFFFFF; i++)
{
generate = enc_file_keys_0;
master = i;
generate += master;
generate *= 0xF97CE7B7;
generate += master;
generate *= 0xF97CE7B7;
generate += master;
generate *= 0xF97CE7B7;
generate += master;
generate *= 0xF97CE7B7;
generate += master;
generate *= 0xF97CE7B7;
generate += master;
generate *= 0xF97CE7B7;
generate += master;
generate *= 0xF97CE7B7;
generate += master;
generate *= 0xF97CE7B7;
generate += master;
generate *= 0xF97CE7B7;
generate += master;
generate *= 0xF97CE7B7;
generate += master;
generate *= 0xF97CE7B7;
generate += master;
generate *= 0xF97CE7B7;
generate += master;
generate *= 0xF97CE7B7;
generate += master;
generate *= 0xF97CE7B7;
generate += master;
generate *= 0xF97CE7B7;
generate += master;
generate *= 0xF97CE7B7;
generate += master;
generate *= 0xF97CE7B7;
generate += master;
generate *= 0xF97CE7B7;
generate += master;
generate *= 0xF97CE7B7;
generate += master;
generate *= 0xF97CE7B7;
generate += master;
generate *= 0xF97CE7B7;
generate += master;
generate *= 0xF97CE7B7;
generate += master;
generate *= 0xF97CE7B7;
generate += master;
generate *= 0xF97CE7B7;
generate += master;
generate *= 0xF97CE7B7;
generate += master;
generate *= 0xF97CE7B7;
generate += master;
generate *= 0xF97CE7B7;
generate += master;
generate *= 0xF97CE7B7;
generate += master;
generate *= 0xF97CE7B7;
generate += master;
generate *= 0xF97CE7B7;
generate += master;
generate *= 0xF97CE7B7;
generate += master;
generate *= 0xF97CE7B7;
generate += master;
if(generate == check_key)
return i;
}
return 0;
}
//Part 2
/*
Now we have the master_key_0 we can now bruteforce the time
*/
unsigned int Crack_Part_2(unsigned int master_key_0, unsigned int enc_file_keys_0)
{
unsigned int generate;
unsigned int i;
for(i = 0xE1C871; i < 0xFFFFFFFF; i++)
{
generate = master_key_0 ^ i;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
if(enc_file_keys_0 == generate)
return i;
}
return 0;
}
//Part 3
/*
Because we have the master_key_0 and the enc_file_passwordhash we can try to find the generator_0
*/
unsigned int Crack_Part_3(unsigned int master_key_0, unsigned int enc_file_passwordhash)
{
unsigned int generate;
unsigned int i;
for(i = 0x72EE2D82; i < 0xFFFFFFFF; i++)
{
generate = i;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
generate *= 0xF97CE7B7;
generate += master_key_0;
if(enc_file_passwordhash == generate)
return i;
}
return 0;
}
/*
Because we know that "master_key_1XORmaster_key_2 = master_key_1 ^ master_key_2". We know that there are only 2^32 posibilities to bruteforce.
Also master_key_3 is useless in GenerateKey because it hasnt been used.
*/
void Crack_Part_4(unsigned int master_key[4], unsigned int enc_file_keys[4], unsigned int enc_file_data_1, unsigned int master_key_1XORmaster_key_2, unsigned int options[10])
{
unsigned int found = 0x0;
unsigned int check_0 = 0x14 ^ (enc_file_data_1 & 0xFF); //Key part 1
unsigned int check_1 = 0x00 ^ ((enc_file_data_1 & 0xFF00) / 0x100); //Key part 2
unsigned int check_2 = 0x00 ^ ((enc_file_data_1 & 0xFF0000) / 0x10000); //Key part 3
unsigned int check_3 = 0x00 ^ ((enc_file_data_1 & 0xFF000000) / 0x1000000); //Key part 4
unsigned int check_key = (check_3 * 0x1000000) + (check_2 * 0x10000) + (check_1 * 0x100) + check_0;
unsigned int i;
for(i = 0x1DD79212; i < 0x1DD79213; i++) // Right answer
{
unsigned int generate[] = { enc_file_keys[0], enc_file_keys[1], enc_file_keys[2], enc_file_keys[3] };
unsigned int master[] = { master_key[0], i, (i ^ master_key_1XORmaster_key_2), 0 };
GenerateKey(master, generate);
if(generate[1] == check_key)
{
options[found] = i;
found++;
}
}
}
//Part 5
/*
Because we only don't know the master_key_3 we need to bruteforce to get the same values as "enc_file_keys".
*/
void Crack_Part_5(int threads, unsigned int master_key[4], unsigned int enc_file_keys_3, unsigned int time)
{
unsigned int i;
boost::thread_group tgroup;
Thread_Status thread_status[threads];
unsigned int space = 0xFFFFFFFF / threads;
for(i = 0; i < threads; i++)
{
unsigned int temp_master_key[4] = { master_key[0], master_key[1], master_key[2], 0x0 };
thread_status[i] = THREAD_STATUS_RUNNING;
tgroup.create_thread(
boost::bind(
&FindMasterThree,
&thread_status[i],
i * space,
(i + 1) * space,
temp_master_key,
enc_file_keys_3,
time
)
);
}
unsigned int done = 0;
bool found = false;
while(!found)
{
for(i = 0; i < threads; i++)
{
if(thread_status[i] == THREAD_STATUS_FINISHED)
{
thread_status[i] = THREAD_STATUS_NONE;
done++;
cout << "done = " << done << endl;
if(done >= threads)
found = true;
}
}
}
//Ending threads
tgroup.interrupt_all();
tgroup.join_all();
}
//Part 6
/*
Because we have the generate and the master_key complete, we can reverse the "GenerateKey" function to get
the output of "InitKey" function. What we know that the first value - 3C is the length. Also if the password is longer then
15 symbols it will add 2 charter with each other. like the 1e and the 16e charter + 3C. In this case our password is 16 charters.
We have to look with our eyes what the 1e and 16e charter will be.
*/
void Crack_Part_6(int threads, unsigned int master_key[4], unsigned int password_edited[4])
{
unsigned int i;
unsigned int options[43] = {
0x023B6A2D, 0x04F502B4, 0x065D6A2D, 0x0C7502B4,
0x0E5D6A2D, 0x125D6A2D, 0x1A06A22D, 0x2306A22D,
0x28116A2D, 0x2B7B6A2D, 0x2C116A2D, 0x2E5D6A2D,
0x3A3B6A2D, 0x3E86A22D, 0x48F502B4, 0x4C7502B4,
0x525D6A2D, 0x5ADD6A2D, 0x637D6A2D, 0x6D9D6A2D,
0x6E5D6A2D, 0x7E86A22D, 0x823B6A2D, 0x865D6A2D,
0x8E5D6A2D, 0x925D6A2D, 0x965D6A2D, 0x9A06A22D,
0xA8116A2D, 0xA8F502B4, 0xAE5D6A2D, 0xBA3B6A2D,
0xC37D6A2D, 0xC686A22D, 0xC8F502B4, 0xDA06A22D,
0xE25D6A2D, 0xE37D6A2D, 0xE8116A2D, 0xED9D6A2D,
0xF25D6A2D, 0xFA3B6A2D, 0xFE86A22D
};
for (i = 0; i < 43; i++)
{
master_key[3] = options[i];
ReverseGenerateKey(threads, master_key, password_edited);
}
}
//---- Main ----
int main(int argc, char* argv[])
{
if(argc == 5 && strcmp(argv[1], "-e") == 0)
{
Encrypt(argv[2], argv[3], argv[4]);
}
else if(argc == 5 && strcmp(argv[1], "-d") == 0)
{
Decrypt(argv[2], argv[3], argv[4]);
}
else if(argc == 3 && strcmp(argv[1], "-c") == 0)
{
int threads = static_cast<int>(boost::thread::hardware_concurrency());
//Known values
unsigned int enc_file_passwordhash = 0xb0a0da81;
unsigned int enc_file_keys[] = { 0xac9b280d, 0x753012f2, 0xa700d292, 0x64017b35 };
unsigned int enc_file_data[] = { 0xbc7d475c, 0x4843623c, 0xe61aa83c, 0x6248ea14 };
unsigned int generated_key[4] = { 0x0, 0x0, 0x0, 0x0 };
unsigned int password_edited[4] = { 0x0, 0x0, 0x0, 0x0 };
unsigned int master_key_1XORmaster_key_2 = 0x0;
unsigned int mastertime_key[4] = { 0x0, 0x0, 0x0, 0x0 };
//Bruteforced values
unsigned int master_key[4] = { 0x4293777F, 0x1DD79212, 0x2DAAC8EF, 0x965D6A2D };
unsigned int enc_file_time = 0x00E1C871;
if(strcmp(argv[2], "master") == 0)
{
//Master key 0
master_key[0] = Crack_Part_1(enc_file_keys[0], enc_file_data[0]);
cout << "master_key_0 = " << master_key[0] << endl;
//Encryption Time
enc_file_time = Crack_Part_2(master_key[0], enc_file_keys[0]);
cout << "enc_file_time = " << enc_file_time << endl;
//Generator 0
generated_key[0] = Crack_Part_3(master_key[0], enc_file_passwordhash);
master_key_1XORmaster_key_2 = generated_key[0] ^ master_key[0];
cout << "generated_key = " << generated_key[0] << endl;
cout << "master_key_1XORmaster_key_2 = " << master_key_1XORmaster_key_2 << endl;
//Master key 1 & 2
unsigned int options[10] = { 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 };
Crack_Part_4(master_key, enc_file_keys, enc_file_data[1], master_key_1XORmaster_key_2, options);
//Draw
cout << "Options" << endl;
unsigned int i;
for(i = 0; i < 10 && options[i] != 0; i++)
{
cout << "master_key = " << master_key[0] << " - " << options[i] << " - " << (options[i] ^ master_key_1XORmaster_key_2) << endl;
}
}
else if(strcmp(argv[2], "full_master") == 0) // Look at the keys.txt for the output
{
Crack_Part_5(threads, master_key, enc_file_keys[3], enc_file_time);
}
else if(strcmp(argv[2], "password") == 0) // Look at the keys.txt for the output
{
Crack_Part_6(threads, master_key, password_edited);
}
/*
Result:
4C B7 7C 7F - A7 84 6C 91 - AA 80 70 91 - 7C AA 80 A9
-----------------------------------------------------
48 40 43 - 6b 48 30 55 - 6e 44 34 55 - 40 6e 44 6d
33
charters = 0xC4 - 0xC3 = 0x10 = 16 charters
Pass: H@CkH0UnD4U@nDm3
*/
}
else
{
ShowMessageAndExit(MSG_USAGE);
}
}
| [
"admin@ludoruisch.nl"
] | admin@ludoruisch.nl |
9997ceb4aab912b427c1cde4a4c663c97fcccfcf | aad71b18989fb7e67c577b3c9e6309f6475e03b2 | /rootex/framework/entity_factory.h | 043bb13e893f45f9484736573d1acd96efc7dec3 | [
"MIT"
] | permissive | meetcshah19/Rootex | 8bb5f79834777c10966dc5dbd2d0f0ca18a142b5 | 002725f80ee6ce02a01e1d18630f5635ad2a5b0c | refs/heads/master | 2021-05-18T21:50:12.894803 | 2020-07-27T16:33:48 | 2020-07-27T16:33:48 | 251,438,812 | 0 | 0 | MIT | 2020-03-30T22:04:07 | 2020-03-30T22:04:07 | null | UTF-8 | C++ | false | false | 2,369 | h | #pragma once
#include "common/common.h"
#include "resource_file.h"
#include "entity.h"
#include "component.h"
/// Invalid ID for an entity
#define INVALID_ID 0
/// Root entity ID
#define ROOT_ENTITY_ID 1
/// Function pointer to a function that constructs a component, taking in a set of component data.
typedef Component* (*ComponentCreator)(const JSON::json& componentDescription);
/// Function pointer to a function that default constructs a component.
typedef Component* (*ComponentDefaultCreator)();
typedef int EntityID;
/// Collection of a component, its name, and a function that constructs that component.
typedef Vector<Tuple<ComponentID, String, ComponentCreator>> ComponentDatabase;
/// Collection of a component, its name, and a function that constructs a default component.
typedef Vector<Tuple<ComponentID, String, ComponentDefaultCreator>> DefaultComponentDatabase;
class EntityFactory
{
static EntityID s_CurrentID;
static EntityID s_CurrentEditorID;
HashMap<EntityID, Ref<Entity>> m_Entities;
EntityID getNextID();
EntityID getNextEditorID();
protected:
ComponentDatabase m_ComponentCreators;
DefaultComponentDatabase m_DefaultComponentCreators;
EntityFactory();
EntityFactory(EntityFactory&) = delete;
~EntityFactory();
Ref<Entity> createRootEntity();
friend class HierarchyGraph;
Variant deleteEntityEvent(const Event* event);
public:
static void RegisterAPI(sol::state& rootex);
static EntityFactory* GetSingleton();
Ref<Component> createComponent(const String& name, const JSON::json& componentData);
Ref<Component> createDefaultComponent(const String& name);
Ref<Entity> createEntity(TextResourceFile* entityJSONDescription, bool isEditorOnly = false);
/// Get entity by ID.
Ref<Entity> findEntity(EntityID entityID);
void setupLiveEntities();
void addDefaultComponent(Ref<Entity> entity, String componentName);
void addComponent(Ref<Entity> entity, Ref<Component> component);
/// Pass in a boolean that determines whether the Root entity should be saved from destruction or not.
void destroyEntities(bool saveRoot);
void deleteEntity(Ref<Entity> entity);
const ComponentDatabase& getComponentDatabase() const { return m_ComponentCreators; }
const HashMap<EntityID, Ref<Entity>>& getEntities() const { return m_Entities; }
HashMap<EntityID, Ref<Entity>>& getMutableEntities() { return m_Entities; }
};
| [
"wtwarit@gmail.com"
] | wtwarit@gmail.com |
41c0c8d723450b591519783178c5787f65d439e4 | 69a2604ec0058aadc68d4a003661881a4674b7d8 | /cpp/server/main.cpp | 7eaac2d5c57d6891bc96fb8b5dbf094d467ac7ef | [
"MIT"
] | permissive | danieljoos/grpc-error-details | f62e6c0fdbe1b72cfe2fd195e279589ee907b5f2 | 3e127d1b4d3cccc6c86c5bfe71a683170b5bea06 | refs/heads/master | 2022-03-18T20:22:26.090404 | 2022-03-09T18:12:51 | 2022-03-09T18:12:51 | 128,110,245 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,550 | cpp |
#include <grpc++/grpc++.h>
#include <grpc++/support/error_details.h>
#include <grpc/grpc.h>
#include "example.grpc.pb.h"
#include "example.pb.h"
// This is the compiled protobuf header of `google::rpc::Status`.
#include "status.pb.h"
class ExampleHelloImpl final : public example::ExampleHello::Service {
grpc::Status SaySomething(grpc::ServerContext* context,
const example::SaySomethingRequest* request,
example::SaySomethingResponse* response) final override {
// Create a protobuf message object that represents our custom information
example::ErrorDetails details;
details.set_why("some detailed error information");
// Create a google::rpc::Status protobuf message object that will be sent in
// the grpc trailers. The custom error-details object (see above) will be
// packed into an `Any` field.
google::rpc::Status status;
status.set_code(grpc::StatusCode::UNKNOWN);
status.set_message("normal error message");
status.add_details()->PackFrom(details);
// Call the `SetErrorDetails` support function of grpc.
grpc::Status result;
grpc::SetErrorDetails(status, &result);
return result;
}
};
int main(int argc, char** argv) {
ExampleHelloImpl service;
grpc::ServerBuilder()
.AddListeningPort("127.0.0.1:50001", grpc::InsecureServerCredentials())
.RegisterService(&service)
.BuildAndStart()
->Wait();
return 0;
}
| [
"daniel@joosweb.de"
] | daniel@joosweb.de |
344e5463bf57057605d10ce82ce12d025e413dee | 45e0fbd9a9dbcdd4fbe6aaa2fdb2aed296f81e33 | /FindSecret/Classes/Native/mscorlib_System_Array_InternalEnumerator_1_gen3490621956.h | c1411b4d6113c3f87907f446a3999f1d05ba3f51 | [
"MIT"
] | permissive | GodIsWord/NewFindSecret | d4a5d2d810ee1f9d6b3bc91168895cc808bac817 | 4f98f316d29936380f9665d6a6d89962d9ee5478 | refs/heads/master | 2020-03-24T09:54:50.239014 | 2018-10-27T05:22:11 | 2018-10-27T05:22:11 | 142,641,511 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,458 | h | #pragma once
#include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <stdint.h>
#include "mscorlib_System_ValueType3640485471.h"
// System.Array
struct Il2CppArray;
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Array/InternalEnumerator`1<EasyAR.IRecorderNotify>
struct InternalEnumerator_1_t3490621956
{
public:
// System.Array System.Array/InternalEnumerator`1::array
Il2CppArray * ___array_0;
// System.Int32 System.Array/InternalEnumerator`1::idx
int32_t ___idx_1;
public:
inline static int32_t get_offset_of_array_0() { return static_cast<int32_t>(offsetof(InternalEnumerator_1_t3490621956, ___array_0)); }
inline Il2CppArray * get_array_0() const { return ___array_0; }
inline Il2CppArray ** get_address_of_array_0() { return &___array_0; }
inline void set_array_0(Il2CppArray * value)
{
___array_0 = value;
Il2CppCodeGenWriteBarrier(&___array_0, value);
}
inline static int32_t get_offset_of_idx_1() { return static_cast<int32_t>(offsetof(InternalEnumerator_1_t3490621956, ___idx_1)); }
inline int32_t get_idx_1() const { return ___idx_1; }
inline int32_t* get_address_of_idx_1() { return &___idx_1; }
inline void set_idx_1(int32_t value)
{
___idx_1 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
| [
"zhangyide@9fbank.cc"
] | zhangyide@9fbank.cc |
e855ae2bb6d2b6401b5a5aa0a49d19522687f9b2 | 2482d7f225d0e2a30fd86fc884d1b09f0f709a67 | /source/piece.h | b2e5cb299e67ccade852f9d7e189906e2af27644 | [] | no_license | EduardGomezEscandell/ConsoleChess | 0f194683b6e6aad16d562077bbf9b132c999d639 | bc2a2ef7e262b320633f4120b2ec0a8597f55b93 | refs/heads/master | 2023-04-27T13:13:18.258816 | 2021-05-10T17:01:38 | 2021-05-10T17:01:38 | 356,655,820 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,428 | h | #ifndef CHESS_PIECE_H
#define CHESS_PIECE_H
#include "defines.h"
#include "move.h"
#include <vector>
#include <memory>
#define CHESS_DEFINE_PIECE_BOILERPLATE(Name, NameCapitalized, Symbol)\
\
Name::Name(const int & rank, \
const int & file, \
Board * parent_board, \
const Colour & colour) \
: Piece(rank, file, parent_board, colour) \
{ \
} \
\
Piece * Name::Clone(Board * parent_board) const \
{ \
Piece * ptr = new Name(*this); \
ptr->ChangeBoard(parent_board); \
return ptr; \
} \
\
char Name::GetPieceCharacter() const \
{ \
static constexpr char c = Symbol; \
return mColour==Colour::BLACK ? c : (c + 'A'-'a'); \
} \
\
PieceSet Name::GetPieceType() const \
{ \
return PieceSet::NameCapitalized; \
} \
namespace ConsoleChess {
class Board;
class Piece
{
public:
// Constructors
Piece(const int & rank, const int & file, Board * parent_board, const Colour & colour);
/**
* @brief Clone: This method allocates a raw pointer and copies the relevant information top clone the piece.
* Ownership is granted to the caller, so it's recomended to use this method only to construct smart pointers.
* @param parent_board: The board that will contain the clone.
* @return Piece*: The raw pointer containing the clone.
*/
virtual Piece * Clone(Board * parent_board) const = 0;
// Editors
virtual void UpdateLegalMoves() = 0;
void SetLocation(const int & rank, const int & file);
void ChangeBoard(Board * rNewBoard);
void SetAliveState(bool alive);
// Getters
bool IsAlive() const;
virtual PieceSet GetPieceType() const = 0;
virtual char GetPieceCharacter() const = 0;
std::vector<Move> & GetMoves();
const std::vector<Move> & GetMoves() const;
Colour GetColour() const;
virtual void RemoveCastlingRights();
// Queries
virtual bool IsInCheck() const;
bool CanMoveTo(const int rank, const int file) const;
virtual bool HasCastlingRights() const;
protected:
bool mIsAlive = true;
int mLocation[2];
Board * mParentBoard;
std::vector<Move> mLegalMoves;
const Colour mColour = Colour::UNDEFINED;
friend class Board;
// Editors
void StraightLineMoveUpdate(const int delta_r, const int delta_f);
// Queries
bool CheckDestinationSquare(const int & rank, const int & file) const;
bool CheckIfCaptures(const int & rank, const int & file) const;
};
}
#endif // CHESS_PIECE_H
| [
"eduard.gomez.escandell@gmail.com"
] | eduard.gomez.escandell@gmail.com |
806accfbc483f5c0c17301747d9de7c5caffb20a | 41d0aee2205d1d1d244faf6b72bae5b48d3839af | /testsuites/unittest/posix/mqueue/full/It_posix_queue_150.cpp | 6852a595d460782605c8a3ba45550a54662ae954 | [
"BSD-3-Clause"
] | permissive | SunnyLy/kernel_liteos_a_note | 75d2df014abce78e85722406331343832f74cec4 | 9c54aa38d2330b365e55e5feff1f808c3b6dba25 | refs/heads/master | 2023-08-19T13:15:21.905929 | 2021-10-22T09:26:15 | 2021-10-22T09:26:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,077 | cpp | /*
* Copyright (c) 2013-2019 Huawei Technologies Co., Ltd. All rights reserved.
* Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be used
* to endorse or promote products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "It_posix_queue.h"
static UINT32 Testcase(VOID)
{
INT32 ret;
const CHAR *msgptr = MQUEUE_SEND_STRING_TEST;
CHAR msgrcd[MQUEUE_STANDARD_NAME_LENGTH] = {0};
CHAR mqname[MQUEUE_STANDARD_NAME_LENGTH] = "";
mqd_t mqueue;
struct mq_attr attr = { 0 };
attr.mq_msgsize = MQUEUE_STANDARD_NAME_LENGTH;
attr.mq_maxmsg = MQUEUE_STANDARD_NAME_LENGTH;
snprintf(mqname, MQUEUE_STANDARD_NAME_LENGTH, "/mq150_%d", LosCurTaskIDGet());
mqueue = mq_open(mqname, O_CREAT | O_RDWR | O_NONBLOCK, S_IRUSR | S_IWUSR, &attr);
ICUNIT_GOTO_NOT_EQUAL(mqueue, (mqd_t)-1, mqueue, EXIT1);
ret = mq_send((mqd_t)(-1), msgptr, strlen(msgptr), 0);
ICUNIT_GOTO_EQUAL(ret, MQUEUE_IS_ERROR, ret, EXIT1);
ICUNIT_GOTO_EQUAL(errno, EBADF, errno, EXIT1);
ret = mq_receive(mqueue, msgrcd, MQUEUE_STANDARD_NAME_LENGTH, NULL);
ICUNIT_GOTO_EQUAL(ret, MQUEUE_IS_ERROR, ret, EXIT1);
ICUNIT_GOTO_EQUAL(errno, EAGAIN, errno, EXIT1);
ret = mq_close(mqueue);
ICUNIT_GOTO_EQUAL(ret, MQUEUE_NO_ERROR, ret, EXIT1);
ret = mq_unlink(mqname);
ICUNIT_GOTO_EQUAL(ret, MQUEUE_NO_ERROR, ret, EXIT);
return MQUEUE_NO_ERROR;
EXIT1:
mq_close(mqueue);
EXIT:
mq_unlink(mqname);
return MQUEUE_NO_ERROR;
}
VOID ItPosixQueue150(VOID) // IT_Layer_ModuleORFeature_No
{
TEST_ADD_CASE("IT_POSIX_QUEUE_150", Testcase, TEST_POSIX, TEST_QUE, TEST_LEVEL2, TEST_FUNCTION);
}
| [
"kuangyufei@126.com"
] | kuangyufei@126.com |
848fcf7c4528214efe623f166c525a9484b7ffbf | b2119eea95c182c183913cc3574e75e8689d3130 | /SOURCES/ui/src/common/missions.cpp | 99b17abf6de96f5da054016678a56f5753f8d400 | [
"Unlicense"
] | permissive | 1059444127/Negev-Storm | 11233b1b3741f643ff14b5aa7b6ee08de40ab69f | 86de63e195577339f6e4a94198bedd31833a8be8 | refs/heads/master | 2021-05-28T10:48:53.536896 | 2015-02-08T10:42:15 | 2015-02-08T10:42:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,003 | cpp | //
// Mission Building stuff for the UI
//
//
#include <windows.h>
#include "unit.h"
#include "campwp.h"
#include "campstr.h"
#include "squadron.h"
#include "division.h"
#include "flight.h"
#include "team.h"
#include "find.h"
#include "misseval.h"
#include "camplist.h"
#include "chandler.h"
#include "ui95_ext.h"
#include "cmap.h"
#include "uicomms.h"
#include "userids.h"
#include "textids.h"
#include "classtbl.h"
#include "ui_cmpgn.h"
#include "ACSelect.h"
#include "gps.h"
#include "urefresh.h"
void UpdateMissionWindow(long ID);
void MakeIndividualATO(VU_ID flightID);
void SetupFlightSpecificControls (Flight flt);
void SetSingle_Comms_Ctrls();
extern C_Handler *gMainHandler;
extern VU_ID gSelectedFlightID;
VU_ID gPlayerFlightID=FalconNullId;
VU_ID gCurrentFlightID=FalconNullId;
short gCurrentAircraftNum;
short gPlayerPlane=-1;
long StopLookingforMission=0;
extern short InCleanup;
extern int gTimeModeServer;
extern bool g_bServer;
extern C_Map *gMapMgr;
extern GlobalPositioningSystem *gGps;
static short FlightStatusID[]= // 1 to 1 correspondence with enum list in ui_cmpgn.h
{
TXT_BRIEFING,
TXT_ENROUTE,
TXT_INGRESS,
TXT_PATROL,
TXT_EGRESS,
TXT_RETURNTOBASE,
TXT_LANDING,
};
long GetFlightTime(Flight element)
{
WayPoint wp;
if(!element)
return(0);
wp=element->GetCurrentUnitWP();
if(wp)
return(wp->GetWPDepartureTime());
return(0);
}
short GetFlightStatusID(Flight element)
{
WayPoint wp=NULL;
int found=0;
short ID=0;
if(!element)
return(0);
wp=element->GetCurrentUnitWP();
if(wp)
{
if(wp->GetWPAction() == WP_TAKEOFF)
{
ID=_MIS_BRIEFING;
found = 1;
}
else if(element->GetOverrideWP())
{
ID=_MIS_ENROUTE;
found = 1;
}
else
{
found;
ID=_MIS_RTB;
while ((found == 0) && (wp))
{
if(wp->GetWPAction() == WP_ASSEMBLE)
{
ID=_MIS_ENROUTE;
found=1;
}
else if(wp->GetWPAction() == WP_POSTASSEMBLE)
{
ID=_MIS_EGRESS;
found=1;
}
else if(wp->GetWPFlags() & WPF_TARGET)
{
if
(
element->GetUnitMission() == AMIS_BARCAP ||
element->GetUnitMission() == AMIS_BARCAP2 ||
element->GetUnitMission() == AMIS_HAVCAP ||
element->GetUnitMission() == AMIS_RESCAP ||
element->GetUnitMission() == AMIS_TARCAP ||
element->GetUnitMission() == AMIS_AMBUSHCAP
)
{
ID=_MIS_PATROL;
}
else
{
ID=_MIS_INGRESS;
}
found=1;
}
else if(wp->GetWPAction() == WP_LAND)
{
ID=_MIS_LAND;
found=0;
}
if(wp->GetWPAction() == WP_LAND)
{
wp=NULL;
}
else
{
wp=wp->GetNextWP();
}
}
}
if ((TheCampaign.Flags & CAMP_TACTICAL) && (!found))
{
ID=_MIS_ENROUTE;
}
}
else
{
ID=_MIS_RTB;
}
return(ID);
}
void CheckCampaignFlyButton()
{
C_Window *win;
C_Button *btn;
Flight flt;
short plane;
short Enabled=0;
flt = FalconLocalSession->GetPlayerFlight();
plane = FalconLocalSession->GetPilotSlot();
if ((gCommsMgr) && (gCommsMgr->Online ()))
{
// Don't care about restricting access when online
if(flt && plane != 255)
Enabled=1;
}
else
{
// OW - sylvains checkfly fix
#if 1
if(flt && plane != 255 && GetFlightStatusID(flt) < _MIS_EGRESS)
// ADDED BY S.G. SO UNINITIALIZED FLIGHTS CAN'T TAKE OFF
{
int i, dontEnable = 0;
if (GetFlightStatusID(flt) > _MIS_BRIEFING) {
for (i = 0; i < 4 && dontEnable == 0; i++) {
if (FalconLocalSession->GetPlayerFlight()->plane_stats[i] == AIRCRAFT_AVAILABLE && FalconLocalSession->GetPlayerFlight()->pilots[i] == NO_PILOT)
dontEnable = 1;
}
}
if (!dontEnable)
// END OF ADDED SECTION
Enabled=1;
}
#else
if(flt && plane != 255 && GetFlightStatusID(flt) < _MIS_EGRESS)
Enabled=1;
#endif
}
win=gMainHandler->FindWindow(CP_TOOLBAR);
if(win)
{
btn=(C_Button *)win->FindControl(SINGLE_FLY_CTRL);
if(btn)
{
if(Enabled)
btn->SetFlagBitOn(C_BIT_ENABLED);
else
btn->SetFlagBitOff(C_BIT_ENABLED);
btn->Refresh();
}
btn=(C_Button *)win->FindControl(COMMS_FLY_CTRL);
if(btn)
{
if(Enabled)
btn->SetFlagBitOn(C_BIT_ENABLED);
else
btn->SetFlagBitOff(C_BIT_ENABLED);
btn->Refresh();
}
}
win=gMainHandler->FindWindow(TAC_TOOLBAR_WIN);
if(win)
{
btn=(C_Button *)win->FindControl(SINGLE_FLY_CTRL);
if(btn)
{
if(Enabled)
btn->SetFlagBitOn(C_BIT_ENABLED);
else
btn->SetFlagBitOff(C_BIT_ENABLED);
btn->Refresh();
}
btn=(C_Button *)win->FindControl(COMMS_FLY_CTRL);
if(btn)
{
if(Enabled)
btn->SetFlagBitOn(C_BIT_ENABLED);
else
btn->SetFlagBitOff(C_BIT_ENABLED);
btn->Refresh();
}
}
}
static void MissionSelectCB(long,short hittype,C_Base *control)
{
C_Window *win;
Flight flight;
F4CSECTIONHANDLE *Leave;
if(hittype != C_TYPE_LMOUSEUP)
return;
Leave=UI_Enter(control->Parent_);
win=control->Parent_;
if(win)
{
gCurrentFlightID=((C_Mission*)control)->GetVUID();
gSelectedFlightID=gCurrentFlightID;
flight = (Flight)vuDatabase->Find(gCurrentFlightID);
if(flight && !flight->IsDead())
{
TheCampaign.MissionEvaluator->PreMissionEval(flight,255);
UpdateMissionWindow(win->GetID());
MakeIndividualATO(gCurrentFlightID);
if(gMapMgr)
{
gMapMgr->SetCurrentWaypointList(gCurrentFlightID);
SetupFlightSpecificControls(flight);
gMapMgr->FitFlightPlan();
gMapMgr->DrawMap();
}
}
}
control->SetState(static_cast<short>(control->GetState()|1));
control->Refresh();
CheckCampaignFlyButton();
UI_Leave(Leave);
}
static void SelectMission(C_Base *control)
{
C_Window *win;
Flight flight;
F4CSECTIONHANDLE *Leave;
Leave=UI_Enter(control->Parent_);
win=control->Parent_;
if(win)
{
gCurrentFlightID=((C_Mission*)control)->GetVUID();
gSelectedFlightID=gCurrentFlightID;
flight = (Flight)vuDatabase->Find(gCurrentFlightID);
if(flight && !flight->IsDead())
{
TheCampaign.MissionEvaluator->PreMissionEval(flight,255);
UpdateMissionWindow(win->GetID());
MakeIndividualATO(gCurrentFlightID);
}
}
control->SetState(static_cast<short>(control->GetState()|1));
control->Refresh();
CheckCampaignFlyButton();
UI_Leave(Leave);
}
void FindMissionInBriefing(long ID)
{
C_Window *win;
C_TreeList *tree;
TREELIST *cur;
Flight flight;
win=gMainHandler->FindWindow(ID);
if(win)
{
tree=(C_TreeList *)win->FindControl(MISSION_LIST_TREE);
if(tree)
{
cur=tree->GetRoot();
while(cur)
{
if(cur->Item_ && !(cur->Item_->GetFlags() & C_BIT_INVISIBLE))
{
if(((C_Mission*)cur->Item_)->GetStatusID() < _MIS_EGRESS)
{
flight=(Flight)vuDatabase->Find(((C_Mission*)cur->Item_)->GetVUID());
if(flight)
{
if(flight->GetTotalVehicles())
{
cur->Item_->SetState(1);
if(!StopLookingforMission)
{
MissionSelectCB(cur->ID_,C_TYPE_LMOUSEUP,cur->Item_);
// KLUDGE: Throw player in 1st slot
// KCK: This should be done regardless of online status
// if(!gCommsMgr->Online())
// { // Throw player in 1st slot
RequestACSlot(flight, 0, static_cast<uchar>(flight->GetAdjustedAircraftSlot(0)), 0, 0, 1);
// }
StopLookingforMission=1;
}
else
SelectMission(cur->Item_);
return;
}
}
}
}
cur=cur->Next;
}
}
}
}
UI_Refresher *FindMissionItem(Flight flight)
{
UI_Refresher *urec;
urec = (UI_Refresher*)gGps->Find(flight->GetCampID());
if (urec && urec->Mission_)
{
MissionSelectCB(urec->Mission_->GetID(),C_TYPE_LMOUSEUP,urec->Mission_);
return urec;
}
return NULL;
}
C_Mission *MakeMissionItem(C_TreeList *tree,Flight element)
{
C_Mission *mission;
C_Window *win;
_TCHAR buffer[200];
TREELIST *item;
int ent_mission;
Package package;
WayPoint wp;
if(!element->Final())
return(NULL);
if(TheCampaign.Flags & CAMP_TACTICAL)
{
if (element->GetOwner () != FalconLocalSession->GetTeam ())
{
return NULL;
}
}
else
{
if(element->GetUnitSquadronID() != FalconLocalSession->GetPlayerSquadronID())
return(NULL);
}
if(!tree || !element || !element->GetUnitParent())
return(NULL);
// Create new record
mission=new C_Mission;
if(!mission)
return(NULL);
win=tree->GetParent();
if(!win)
return(NULL);
mission->Setup(element->GetCampID(),0); // ID=element->CampID;
mission->SetFont(win->Font_);
mission->SetClient(tree->GetClient());
mission->SetW(win->ClientArea_[tree->GetClient()].right - win->ClientArea_[tree->GetClient()].left);
mission->SetH(gFontList->GetHeight(tree->GetFont()));
// Set takeoff time string
wp = element->GetFirstUnitWP();
if (wp) { // JPO CTD fix
GetTimeString(wp->GetWPDepartureTime(),buffer);
mission->SetTakeOff(static_cast<short>(tree->GetUserNumber(C_STATE_0)),0,buffer);
mission->SetTakeOffTime(wp->GetWPDepartureTime());
}
// Set Mission Type
ent_mission = element->GetUnitMission();
if (ent_mission == AMIS_ALERT)
ent_mission = AMIS_INTERCEPT;
mission->SetMission(static_cast<short>(tree->GetUserNumber(C_STATE_1)),0,MissStr[ent_mission]);
mission->SetMissionID(static_cast<short>(element->GetUnitMission()));
// Set Package (campID of package)
_stprintf(buffer,"%1d",element->GetUnitParent()->GetCampID());
mission->SetPackage(static_cast<short>(tree->GetUserNumber(C_STATE_2)),0,buffer);
mission->SetPackageID(element->GetUnitParent()->GetCampID());
// Set Mission Status String
mission->SetStatusID(GetFlightStatusID(element));
mission->SetStatus(static_cast<short>(tree->GetUserNumber(C_STATE_3)),0,gStringMgr->GetString(FlightStatusID[mission->GetStatusID()]));
// Set Mission Priority String
package = element->GetUnitPackage();
buffer[1]=0;
// KCK: It seemed more logical to get the priority from the flight, not the package's request
// PJW: Why Kevin you are sooo fucking wrong... and ASK when making changes butt fuck
// buffer[0]=(255 - element->GetUnitPriority()) / 51 + _T('A');
buffer[0]=static_cast<char>((255 - package->GetMissionRequest()->priority) / 51 + _T('A'));
mission->SetPriority(static_cast<short>(tree->GetUserNumber(C_STATE_4)),0,buffer);
mission->SetPriorityID(static_cast<short>(255 - package->GetMissionRequest()->priority));
// Set a callback incase someone actually wants to see this mission
// if (TheCampaign.Flags & CAMP_TACTICAL)
// {
// mission->SetCallback (TacMissionSelectCB);
// }
// else
// {
mission->SetCallback(MissionSelectCB);
// }
// Tack on the VU_ID
mission->SetVUID(element->Id());
mission->SetUserNumber(C_STATE_0,element->GetTeam());
mission->SetUserNumber(C_STATE_1,wp ? wp->GetWPDepartureTime() : 0);
mission->SetUserNumber(C_STATE_2,1000 - element->GetUnitPriority()); // Priority
mission->SetUserNumber(C_STATE_3,element->GetUnitMission());
if (!element->Final() || element->GetUnitMission() == AMIS_ALERT)
{
mission->SetFlagBitOn(C_BIT_INVISIBLE);
}
// Add to tree
item=tree->CreateItem(element->GetCampID(),C_TYPE_ITEM,mission);
mission->SetOwner(item);
if(tree->AddItem(tree->GetRoot(),item))
return(mission);
mission->Cleanup();
delete mission;
delete item;
return(NULL);
}
void MissionUpdateStatus(Flight element,C_Mission *mission)
{
mission->Refresh();
mission->SetStatusID(GetFlightStatusID(element));
mission->SetStatus(gStringMgr->GetString(FlightStatusID[mission->GetStatusID()]));
if(gPlayerFlightID == element->Id())
{
if(mission->GetStatusID() >= _MIS_EGRESS)
{
mission->SetState(static_cast<short>(mission->GetState()&1));
FalconLocalSession->SetPlayerFlight(NULL);
FalconLocalSession->SetPilotSlot(255);
gPlayerFlightID=FalconNullId;
gPlayerPlane=-1;
}
}
mission->Refresh();
if(gCurrentFlightID == element->Id())
{
UpdateMissionWindow(CB_MISSION_SCREEN);
UpdateMissionWindow(TAC_AIRCRAFT);
}
if(gMapMgr)
gMapMgr->UpdateWaypoint(element);
}
void MissionUpdateTime(Flight element,C_Mission *mission)
{
_TCHAR buffer[80];
mission->Refresh();
WayPoint wp = element->GetFirstUnitWP();
if (wp) { // JPO CTD fix
GetTimeString(wp->GetWPDepartureTime(),buffer);
mission->SetTakeOff(buffer);
mission->SetTakeOffTime(wp->GetWPDepartureTime());
}
else
mission->SetTakeOff(_T("Unknown"));
mission->Refresh();
}
void RemoveMissionCB(TREELIST *item)
{
C_Mission *mis;
if(!item)
return;
mis=(C_Mission*)item->Item_;
if(gPlayerFlightID == mis->GetVUID())
{
gPlayerFlightID=FalconNullId;
gPlayerPlane=-1;
}
if(gMapMgr)
gMapMgr->RemoveWaypoints(static_cast<short>(item->Item_->GetUserNumber(0)),item->Item_->GetID() << 8);
if(InCleanup)
return;
if(gCurrentFlightID == mis->GetVUID()) // our mission is being removed... find the next mission in briefing
{
if(TheCampaign.Flags & CAMP_TACTICAL)
{
if (gTimeModeServer||g_bServer)
{
FindMissionInBriefing(TAC_AIRCRAFT);
}
UpdateMissionWindow(TAC_AIRCRAFT);
}
else
{
if (gTimeModeServer||g_bServer)
{
FindMissionInBriefing(CB_MISSION_SCREEN);
UpdateMissionWindow(CB_MISSION_SCREEN);
}
}
}
}
| [
"israelyflightsimulator@gmail.com"
] | israelyflightsimulator@gmail.com |
cc008d030e816170c6a4ae37bb3c468c8f708fa9 | a805a483de393a9110bb339522a90582f8817367 | /Display.h | fef21f2ad07d330c4ad7505a57c5b4e632ae6324 | [] | no_license | Nanoxium/hpc_cellular_automata | 98900025fe86f59f4173b1cc46e23c8f98f7ad62 | 1c9134863cbde11e972dc411e8a656cbfb97d06b | refs/heads/master | 2023-03-14T16:22:08.808017 | 2020-07-17T12:15:52 | 2020-07-17T12:15:52 | 350,714,700 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 568 | h | #ifndef Display_H_
#define Display_H_
#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
struct color{
float r;
float g;
float b;
};
template <class T>
class Display {
public:
Display( T* data, unsigned int sizex, unsigned int sizey, T max );
~Display();
void show();
char waitForKey();
static void groundColorMix( color &col, float x, float min, float max );
private:
T *data_;
unsigned int sizeX_;
unsigned int sizeY_;
unsigned int max_;
cv::Mat img_;
};
#include "Display.cpp"
#endif /* Display_H_ */
| [
"jerome.chetelat@etu.hesge.ch"
] | jerome.chetelat@etu.hesge.ch |
b1cdfe7aec7059aab02d56b2126877b3f2e6e464 | 00f95f1ce60a571faefd214db17442d7d32450c6 | /src/midi/render.cpp | 2d67e368b51846681086028ccf20b973025f1c40 | [] | no_license | emildekeyser/midi-parser | fcff34a6d5a2874fe66e9f8e7442d45cf0ae442d | e452b30bb2a7e85d8c90d253253e65ec71c3ac9b | refs/heads/master | 2023-01-09T22:24:56.619955 | 2020-08-09T13:56:41 | 2020-08-09T13:56:41 | 312,271,949 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,618 | cpp | #include <iostream>
#include <fstream>
#include <vector>
#include <map>
#include <sstream>
#include <numeric>
#include <iomanip>
#include "imaging/bitmap.h"
#include "imaging/bmp-format.h"
#include "midi/midi.h"
#include "render.h"
std::map<int, imaging::Color> gen_colors(std::vector<midi::NOTE> notes)
{
imaging::Color available_colors[] = {
imaging::Color(0, 0, 1),
imaging::Color(0, 1, 0),
imaging::Color(0, 1, 1),
imaging::Color(1, 0, 0),
imaging::Color(1, 0, 1),
imaging::Color(1, 1, 0),
imaging::Color(1, 1, 1)
};
std::map<int, imaging::Color> colors;
int i = 0;
for (midi::NOTE n : notes)
{
int ins = value(n.instrument);
if (colors.count(ins) == 0) {
colors[ins] = available_colors[i];
if(i < 7) {
i++;
}
}
}
return colors;
}
double gen_total_height(std::vector<midi::NOTE> notes)
{
std::vector<double> note_ends;
for (midi::NOTE n : notes) {
note_ends.push_back(value(n.start) + value(n.duration));
}
double max = 0;
for (double note_end : note_ends) {
if (note_end > max) {
max = note_end;
}
}
return max;
}
std::pair<double, double> gen_low_high_notes(std::vector<midi::NOTE> notes)
{
double max = 0;
double min = 127;
for (midi::NOTE n : notes) {
if (value(n.note_number) > max) {
max = value(n.note_number);
}
if (value(n.note_number) < min) {
min = value(n.note_number);
}
}
return std::pair<double, double>(min, max);
}
std::string indexed_filename(int index, std::string pattern)
{
std::string filename = pattern;
std::stringstream formatted_index;
formatted_index << std::setfill('0') << std::setw(5) << index;
size_t pos = filename.find("%d");
filename.replace(pos, 2, formatted_index.str());
return filename;
}
void render(Parameters params)
{
std::ifstream ifs(params.midifile);
std::vector<midi::NOTE> notes = midi::read_notes(ifs);
double scale = (double) params.scale / 100.0;
auto color_init = [](Position p){return imaging::Color(0, 0, 0); };
double total_heigth = gen_total_height(notes);
auto bitmap = imaging::Bitmap(params.width, (total_heigth + params.height) * scale, color_init);
auto colors = gen_colors(notes);
auto low_high_notes_pair = gen_low_high_notes(notes);
double low = low_high_notes_pair.first;
double high = low_high_notes_pair.second;
double width = params.width / (high - low + 1);
for (midi::NOTE note : notes) {
if (params.verbose)
std::cout << note << "\n";
double height = value(note.duration) * scale;
double x = (value(note.note_number) - low) * width;
double y = value(note.start) * scale;
auto color = colors[value(note.instrument)];
auto slice = bitmap.slice(x, y, width, height);
auto offset = Position(x, y);
slice->for_each_position([&bitmap, &color, &offset](const Position& p) {
bitmap[offset + p] = color;
});
}
for (double y = 0; y <= total_heigth; y += params.step) {
auto slice = bitmap.slice(0, y, params.width, params.height);
auto filename = indexed_filename(y / params.step, params.pattern);
if (params.verbose)
std::cout << filename << "\n";
imaging::save_as_bmp(filename, *slice);
}
}
| [
"emil.dekeyser@student.ucll.be"
] | emil.dekeyser@student.ucll.be |
8c2b55df03516fcbb4a31c25d0888b4b45a61643 | 48e4c9712b38a90b819c84db064422e1088c4565 | /toolchains/motoezx/qt/include/qt-2.3.8/qwssocket_qws.h | d359b1b6d2cfc1299f592979dab894452cfbc564 | [] | no_license | blchinezu/EZX-SDK_CPP-QT-SDL | 8e4605ed5940805f49d76e7700f19023dea9e36b | cbb01e0f1dd03bdf8b071f503c4e3e43b2e6ac33 | refs/heads/master | 2020-06-05T15:25:21.527826 | 2020-05-15T11:11:13 | 2020-05-15T11:11:13 | 39,446,244 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,356 | h | /****************************************************************************
** $Id: qt/src/kernel/qwssocket_qws.h 2.3.8 edited 2004-08-05 $
**
** Definition of QWSSocket and related classes.
**
** Created : 970521
**
** Copyright (C) 1992-2000 Trolltech AS. All rights reserved.
**
** This file is part of the kernel module of the Qt GUI Toolkit.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition
** licenses for Qt/Embedded may use this file in accordance with the
** Qt Embedded Commercial License Agreement provided with the Software.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
** information about Qt Commercial License Agreements.
** See http://www.trolltech.com/gpl/ for GPL licensing information.
**
** Contact info@trolltech.com if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/
#ifndef QWSSOCKETDEVICE_H
#define QWSSOCKETDEVICE_H
#ifndef QT_H
#include "qsocket.h"
#include "qserversocket.h"
#endif // QT_H
#ifndef QT_NO_QWS_MULTIPROCESS
class QWSSocket : public QSocket
{
Q_OBJECT
public:
QWSSocket( QObject *parent=0, const char *name=0 );
~QWSSocket();
virtual void connectToLocalFile( const QString &file );
private: // Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
QWSSocket( const QWSSocket & );
QWSSocket &operator=( const QWSSocket & );
#endif
};
class QWSServerSocket : public QServerSocket
{
Q_OBJECT
public:
QWSServerSocket( const QString& file, int backlog = 0,
QObject *parent=0, const char *name=0 );
~QWSServerSocket();
private: // Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
QWSServerSocket( const QWSServerSocket & );
QWSServerSocket &operator=( const QWSServerSocket & );
#endif
};
#endif //QT_NO_QWS_MULTIPROCESS
#endif // QWSSOCKETDEVICE_H
| [
"eu.gabii@yahoo.com"
] | eu.gabii@yahoo.com |
42ebf8c1402d81c926ac1d3c29dfc91313306215 | bd8bcdb88c102a1ddf2c0f429dbef392296b67af | /include/fengine/IO/Crypto/DecryptionException.h | 6239efde4b21add78b9b21041b260f8b1ded655c | [
"BSD-2-Clause",
"BSD-3-Clause"
] | permissive | LukasBanana/ForkENGINE | be03cee942b0e20e30a01318c2639de87a72c79c | 8b575bd1d47741ad5025a499cb87909dbabc3492 | refs/heads/master | 2020-05-23T09:08:44.864715 | 2017-01-30T16:35:34 | 2017-01-30T16:35:34 | 80,437,868 | 14 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 856 | h | /*
* Decryption exception header
*
* This file is part of the "ForkENGINE" (Copyright (c) 2014 by Lukas Hermanns)
* See "LICENSE.txt" for license information.
*/
#ifndef __FORK_DECRYPTION_EXCEPTION_H__
#define __FORK_DECRYPTION_EXCEPTION_H__
#include "Core/Exception/DefaultException.h"
namespace Fork
{
/**
Decryption exception.
\ingroup fork_exception
*/
class FORK_EXPORT DecryptionException : public DefaultException
{
public:
DecryptionException(
const std::string& decryptionMethod, const std::string& errorDesc) :
DefaultException
{
"DecryptionException",
"Encryption: " + decryptionMethod + ", Description: " + errorDesc
}
{
}
};
} // /namespace Fork
#endif
// ======================== | [
"lukas.hermanns90@gmail.com"
] | lukas.hermanns90@gmail.com |
f193ef483bff463ebfdf2c17d2c21249364bdb4e | 4ae1d3431c99958b4a79ffb003588738ac5724df | /gengen/staticcodegetter.h | 99fcd336f4708b8552aa5ff918799d49d6f7b9a7 | [
"MIT"
] | permissive | JaDogg/GenGen | 2971e0c0c8c40f1ff0a7dff6e88c9df7bba8a6eb | 29a28ce809095a28683193d55d2291996cc90b47 | refs/heads/master | 2021-01-19T18:10:38.662843 | 2015-02-01T14:52:05 | 2015-02-01T14:52:05 | 30,136,109 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 683 | h | #ifndef STATICCODEGETTER_H
#define STATICCODEGETTER_H
#include <string>
class StaticCodeGetter {
public:
virtual std::string GetBeforePreHeader() = 0; // our header message
virtual std::string GetAfterPreHeader() = 0; // our includes and functions before main()
virtual std::string GetAfterHeader() = 0; // int main(){
virtual std::string GetBeforeFooter() = 0; // }
virtual std::string GetAfterFooter() = 0; // functions after main()
virtual std::string GetAfterPostFooter() = 0; // our post code ex=> if __init__ == '__main__':
virtual unsigned int GetStartingIndent() = 0; // get starting indent of all line code, doesn't affect block code
};
#endif
| [
"jadogg.coder@gmail.com"
] | jadogg.coder@gmail.com |
255e6131640b0864b72b32e008802d3f726e938b | 100000b8c66f0b7a95c8985518e2214f1ede2597 | /Homework 10/Homework 10/HW10Source.cpp | 8d149c4fd2b78547bd142c7ff9f29ca9846494aa | [] | no_license | Kardbord/CS1400 | 9803a3941c544e2eadb31a7966d32c4aaf908deb | 8130b970b7c1c9f85c42e9e4098e1f6ad1a93ea5 | refs/heads/master | 2021-05-11T09:01:28.322815 | 2018-01-19T02:34:25 | 2018-01-19T02:34:25 | 118,066,492 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,841 | cpp | //Tanner Kvarfordt
//A02052217
/*This program uses input from a file to display the average high and low temperatures
over however many days are included in the file. It will also display how many days are
in the file and the number of days that the temperature was below 32 degrees Fahrenheit.*/
#include<iostream>
#include<fstream>
#include<string>
#include<iomanip>
using namespace std;
int main() {
//create input file variable and link it to weather.txt
ifstream inputFile;
inputFile.open("weather.txt");
if (inputFile.fail()) {
cout << "\aError opening weather.txt\n\n";
return 1;
}
//declare any other necessary variables
int entry = 0;
int days = 0; //this will be our counter variable for number of days
int coldDays = 0; //another counter variable for days below freezing
double highTemp = 0, lowTemp = 0; //individual temps for each day
double highTemps = 0, lowTemps = 0; //running totals of high and low temps
double avgHighTemps, avgLowTemps;
string day; //using this to read past the day of the week in the input file and check that weather.txt is formatted correctly
//use a while loop to gather data from weather.txt
while (inputFile >> day) {
entry++;
//check that we are reading days of the week
if (day == "Saturday" || day == "saturday"
|| day == "Sunday" || day == "sunday"
|| day == "Monday" || day == "monday"
|| day == "Tuesday" || day == "tuesday"
|| day == "Wednesday" || day == "wednesday"
|| day == "Thursday" || day == "thursday"
|| day == "Friday" || day == "friday") {
inputFile >> highTemp;
inputFile >> lowTemp;
//check that the high temp is greater than the low temp
if (highTemp < lowTemp) {
cout << "\aWarning! weather.txt is not formatted correctly.\n"
"High and low temperatures are reversed for entry number " << entry << ". \n"
"Entry number " << entry << " will be skipped.\n\n";
}
else {
days++;
highTemps += highTemp;
lowTemps += lowTemp;
//if statement to test for temperatures below freezing
if (highTemp <= 32 || lowTemp <= 32) {
coldDays++;
}
}
}
else {
cout << "\aWarning! weather.txt is not formatted correctly.\n"
"Entry number " << entry << " is not a valid day (" << day << ") and will be skipped.\n\n";
}
}
//close the file
inputFile.close();
//processing to get the average high and low temps
avgHighTemps = highTemps / days;
avgLowTemps = lowTemps / days;
//display output
cout << "Total number of days: " << days << endl;
cout << "Total number of days below freezing: " << coldDays << endl;
cout << setprecision(2) << fixed;
cout << "Average low temperature: " << avgLowTemps << " degrees Fahrenheit." << endl;
cout << "Average high temperature: " << avgHighTemps << " degrees Fahrenheit." << endl;
cout << endl << endl;
return 0;
} | [
"tanner.kvarfordt@aggiemail.usu.edu"
] | tanner.kvarfordt@aggiemail.usu.edu |
b9eb3f5b0acdee3edcd6e9e72277e6256224c5a4 | 603f67d050fa72f3df712fc4c4f197401e88ee04 | /image_manip/src/iir_image.cpp | 7a206b2040dd65bad7b33d666238901470a104b3 | [
"BSD-3-Clause"
] | permissive | lucasw/image_manip | da4caed0e97037f661d38ddbd1df412248d28243 | 68b82cf48107244eecc431799168d5a4d57e7204 | refs/heads/master | 2023-06-07T19:18:03.398800 | 2023-01-20T16:00:10 | 2023-01-20T16:00:10 | 95,515,758 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,468 | cpp | /*
* Copyright (c) 2017 Lucas Walter
* June 2017
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <cv_bridge/cv_bridge.h>
#include <image_manip/iir_image.h>
#include <image_manip/utility.h>
#include <image_manip/utility_ros.h>
#include <sensor_msgs/Image.h>
#include <sensor_msgs/image_encodings.h>
#include <string>
#include <vector>
namespace image_manip
{
IIRImage::IIRImage() :
use_time_sequence_(true),
dirty_(false)
{
}
IIRImage::~IIRImage()
{
}
void IIRImage::updateTopics(image_manip::IIRImageConfig& config)
{
std::vector<std::string*> topics;
topics.resize(8);
topics[0] = &config.topic0;
topics[1] = &config.topic1;
topics[2] = &config.topic2;
topics[3] = &config.topic3;
topics[4] = &config.topic4;
topics[5] = &config.topic5;
topics[6] = &config.topic6;
topics[7] = &config.topic7;
for (size_t i = 0; i < 8; ++i) {
if (i < image_subs_.size()) {
*topics[i] = image_subs_[i].getTopic();
} else {
*topics[i] = "none";
}
}
}
void IIRImage::callback(
image_manip::IIRImageConfig& config,
uint32_t level)
{
updateTimer(timer_, config.frame_rate, config_.frame_rate);
updateTopics(config);
config_ = config;
if (level & 2)
{
if (use_time_sequence_)
{
b_coeffs_.resize(8);
a_coeffs_.resize(8);
}
if (b_coeffs_.size() > 0)
b_coeffs_[0] = config_.b0;
if (b_coeffs_.size() > 1)
b_coeffs_[1] = config_.b1;
if (b_coeffs_.size() > 2)
b_coeffs_[2] = config_.b2;
if (b_coeffs_.size() > 3)
b_coeffs_[3] = config_.b3;
if (b_coeffs_.size() > 4)
b_coeffs_[4] = config_.b4;
if (b_coeffs_.size() > 5)
b_coeffs_[5] = config_.b5;
if (b_coeffs_.size() > 6)
b_coeffs_[6] = config_.b6;
if (b_coeffs_.size() > 7)
b_coeffs_[7] = config_.b7;
if (a_coeffs_.size() > 0)
a_coeffs_[0] = config_.a0;
if (a_coeffs_.size() > 1)
a_coeffs_[1] = config_.a1;
if (a_coeffs_.size() > 2)
a_coeffs_[2] = config_.a2;
if (a_coeffs_.size() > 3)
a_coeffs_[3] = config_.a3;
if (a_coeffs_.size() > 4)
a_coeffs_[4] = config_.a4;
if (a_coeffs_.size() > 5)
a_coeffs_[5] = config_.a5;
if (a_coeffs_.size() > 6)
a_coeffs_[6] = config_.a6;
if (a_coeffs_.size() > 7)
a_coeffs_[7] = config_.a7;
}
dirty_ = true;
}
void IIRImage::update(const ros::TimerEvent& e)
{
if (!dirty_)
return;
cv::Mat out_frame;
size_t max_ind = 0;
if ((in_images_.size() > 0) && (b_coeffs_.size() > 0))
{
max_ind = in_images_.size() < b_coeffs_.size() ? in_images_.size() - 1 : b_coeffs_.size() - 1;
}
std::vector<size_t> inds;
if (!config_.reverse)
{
for (size_t i = 0; i <= max_ind; ++i) {
inds.push_back(i);
}
}
else
{
for (size_t i = max_ind; i >= 0 && i <= max_ind; --i) {
inds.push_back(i);
}
}
for (const auto& i : inds)
{
if (!in_images_[i])
continue;
// convert the image on demand
if (!in_cv_images_[i])
{
try
{
// TODO(lucasw) don't want to convert the same images over and over,
// so store both the sensor_msg and convert and save on demand?
// TBD why converting to BGR8-
// this will incur image data copy if not the native format
in_cv_images_[i] =
cv_bridge::toCvShare(in_images_[i],
sensor_msgs::image_encodings::RGB8);
//, "mono8"); // sensor_msgs::image_encodings::MONO8);
}
catch (cv_bridge::Exception& e)
{
ROS_ERROR("cv_bridge exception: %s", e.what());
continue;
}
}
const double bn = b_coeffs_[i];
if (out_frame.empty())
{
out_frame = in_cv_images_[i]->image * bn;
}
else if ( // (out_frame.size() == in_cv_images_[i]->image.size()) &&
(out_frame.type() == in_cv_images_[i]->image.type()))
{
// TODO(lucasw) if size/type mismatch have optional mode
// to convert the cv_ptr image.
cv::Mat resized;
cv::resize(in_cv_images_[i]->image, resized,
out_frame.size(),
cv::INTER_NEAREST);
if (bn > 0)
out_frame += resized * bn;
else if (bn < 0)
out_frame -= resized * -bn;
}
} // loop through b coefficient inds
if (out_frame.empty())
return;
// since the current frame hasn't been pushed yet,
// i-1 is actually index i for out_frames_.
for (size_t i = 1; (i - 1) < out_frames_.size() && i < a_coeffs_.size(); ++i)
{
if ((out_frame.size() == out_frames_[i - 1].size()) &&
(out_frame.type() == out_frames_[i - 1].type()))
{
const float an = -a_coeffs_[i];
if (an > 0)
out_frame += out_frames_[i - 1] * an;
else if (an < 0)
out_frame -= out_frames_[i - 1] * -an;
}
}
if (!out_frame.empty() && a_coeffs_.size() > 0)
{
out_frame *= 1.0 / a_coeffs_[0];
}
// TODO(lucasw) this may be argument for keeping original Image messages around
cv_bridge::CvImage cv_image;
cv_image.header.stamp = ros::Time::now(); // or reception time of original message?
cv_image.image = out_frame;
cv_image.encoding = "rgb8";
const sensor_msgs::ImageConstPtr out_image(cv_image.toImageMsg());
pub_.publish(out_image);
out_frames_.push_front(out_frame);
if (out_frames_.size() > a_coeffs_.size())
out_frames_.pop_back();
// don't care if dirty_ would have become true again
// had it been set false immediately after testing it.
dirty_ = false;
}
void IIRImage::imageCallback(const sensor_msgs::ImageConstPtr& msg)
{
in_images_.push_front(msg);
in_cv_images_.push_front(cv_bridge::CvImageConstPtr());
if (in_images_.size() > b_coeffs_.size())
{
in_images_.pop_back();
in_cv_images_.pop_back();
}
dirty_ = true;
ros::TimerEvent e;
// negative frame_rate is a disable
// TODO(lucasw) or should that be the other way around?
if (config_.frame_rate == 0)
update(e);
}
void IIRImage::imagesCallback(const sensor_msgs::ImageConstPtr& msg, const size_t index)
{
if (index >= in_images_.size())
return;
in_images_[index] = msg;
in_cv_images_[index] = cv_bridge::CvImageConstPtr();
dirty_ = true;
}
void IIRImage::onInit()
{
dirty_ = false;
use_time_sequence_ = true;
pub_ = getNodeHandle().advertise<sensor_msgs::Image>("image_out", 5);
server_.reset(new ReconfigureServer(dr_mutex_, getPrivateNodeHandle()));
dynamic_reconfigure::Server<image_manip::IIRImageConfig>::CallbackType cbt =
boost::bind(&IIRImage::callback, this, boost::placeholders::_1, boost::placeholders::_2);
server_->setCallback(cbt);
getPrivateNodeHandle().getParam("use_time_sequence", use_time_sequence_);
if (!use_time_sequence_)
{
// TODO(lucasw) update config from b_coeffs
getPrivateNodeHandle().getParam("b_coeffs", b_coeffs_);
if (b_coeffs_.size() == 0)
{
ROS_WARN_STREAM("no b coefficients");
}
in_images_.resize(b_coeffs_.size());
in_cv_images_.resize(b_coeffs_.size());
for (size_t i = 0; i < b_coeffs_.size(); ++i)
{
std::stringstream ss;
ss << "image_" << i;
ROS_INFO_STREAM("subscribe " << ss.str() << " " << b_coeffs_[i]);
image_subs_.push_back(getNodeHandle().subscribe<sensor_msgs::Image>(
ss.str(), 1,
boost::bind(&IIRImage::imagesCallback, this, boost::placeholders::_1, i)));
}
// getPrivateNodeHandle().getParam("a_coeffs", a_coeffs_);
updateTopics(config_);
}
else
{
sub_ = getNodeHandle().subscribe("image_in", 1, &IIRImage::imageCallback, this);
}
timer_ = getPrivateNodeHandle().createTimer(ros::Duration(1.0),
&IIRImage::update, this);
// force timer start by making old frame_rate different
updateTimer(timer_, config_.frame_rate, config_.frame_rate - 1.0);
}
}; // namespace image_manip
#include <pluginlib/class_list_macros.hpp>
PLUGINLIB_EXPORT_CLASS(image_manip::IIRImage, nodelet::Nodelet)
| [
"wsacul@gmail.com"
] | wsacul@gmail.com |
096f14a0b2793f9e7600d44af3a67389d9b445a7 | 2eec9db7c8890de85eaa2140b59116e573dd0b53 | /src/zmq/zmqrpc.h | d141191dc14c0a2422106c1ed9b00108365ee2d2 | [
"MIT"
] | permissive | Alonewolf-123/PaydayCoin-Core | 45bca042a8014f4486977f951bc2083728d8fb5e | d807d95550d955bfa9ffda2b39cad745422224e5 | refs/heads/master | 2023-01-13T15:33:54.226987 | 2019-12-16T04:54:53 | 2019-12-16T04:54:53 | 227,445,703 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 354 | h | // Copyright (c) 2018 The PaydayCoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef PAYDAYCOIN_ZMQ_ZMQRPC_H
#define PAYDAYCOIN_ZMQ_ZMQRPC_H
class CRPCTable;
void RegisterZMQRPCCommands(CRPCTable& t);
#endif // PAYDAYCOIN_ZMQ_ZMRRPC_H
| [
"alonewolf2ksk@gmail.com"
] | alonewolf2ksk@gmail.com |
86c2f57ddb1c4e91c195eef28bd49974040824f4 | 3909a0dc9c4f72be2152f2423db0f45441c0592c | /Software/GebaeudeManagement/Server/Lampe.h | 05e14672317c3803a5d296395df6dad234f22cfc | [] | no_license | FHWestkuesteSWE/projektgebaeude-team-2 | f75037d64ebf72c56e41e094be4ba1b14af5d97a | 4bb6b6b3cd041e42063d8e7b9e1f64de876d8109 | refs/heads/master | 2021-05-23T19:56:41.890029 | 2020-06-15T15:31:12 | 2020-06-15T15:31:12 | 253,443,373 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 213 | h | #pragma once
#include "Actor.h"
class Lampe : Actor {
private:
string name;
public:
Lampe();
~Lampe();
void setState(bool p_action);
bool getState();
void setName(string p_name);
string getName();
};
| [
"rinaldysutyono@gmail.com"
] | rinaldysutyono@gmail.com |
88e3d137992b1d44093ce92c9f3b4c774ba2a879 | 81a312c9b19a009e1067f4cd58492dc686742027 | /src/tools.h | 4a3aa9a03b2dc917442e17c6394b038539811d34 | [
"Apache-2.0"
] | permissive | corum/procrastitracker | e3301ee6dc1e6730bf50468153ef49e257aad41f | 31da8bbf53c6da75a4c9d7f99528e5c1df0b4c3d | refs/heads/master | 2023-04-06T14:38:59.602671 | 2022-08-22T20:51:26 | 2022-08-22T20:51:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,369 | h | typedef unsigned char uchar;
typedef unsigned short ushort;
typedef unsigned int uint;
static const float PI = 3.14159265358979323846264338327950288419716939937510f; // :)
static const float RAD = PI / 180.0f;
#ifdef _DEBUG
#define ASSERT(c) \
if (!(c)) { __asm int 3 }
#else
#define ASSERT(c) \
if (c) {}
#endif
#define loop(i, m) for (int i = 0; i < (m); i++)
#define loopv(i, v) loop(i, (v).size())
#define varargs(v, fmt, body) \
{ \
va_list v; \
va_start(v, fmt); \
body; \
va_end(v); \
}
#define DELETEP(p) \
if (p) { \
delete p; \
p = NULL; \
}
#define DELETEA(a) \
if (a) { \
delete[] a; \
a = NULL; \
}
#define bound(v, a, s, e) \
{ \
v += a; \
if (v > (e)) v = (e); \
if (v < (s)) v = (s); \
}
template <class T>
inline void swap(T &a, T &b) {
T c = a;
a = b;
b = c;
};
#ifdef WIN32
#pragma warning(3 : 4189) // local variable is initialized but not referenced
#pragma warning(disable : 4244) // conversion from 'int' to 'float', possible loss of data
#pragma warning(disable : 4355) // 'this' : used in base member initializer list
#pragma warning(disable : 4996) // 'strncpy' was declared deprecated
#endif
template <typename T>
struct SlabAllocated {
#ifndef _DEBUG
void *operator new(size_t size) {
assert(size == sizeof(T));
return pool.alloc(size);
}
void operator delete(void *p) { pool.dealloc(p, sizeof(T)); };
#endif
};
// from boost, stops a class from being accidental victim to default copy + destruct twice problem
// class that inherits from NonCopyable will work correctly with Vector, but give compile time error
// with std::vector
class NonCopyable {
NonCopyable(const NonCopyable &);
const NonCopyable &operator=(const NonCopyable &);
protected:
NonCopyable() {}
};
// helper function for containers below to delete members if they are of pointer type only
template <class X>
void DelPtr(X &) {}
template <class X>
void DelPtr(X *&m) {
DELETEP(m);
}
// replacement for STL vector
// for any T that has a non-trivial destructor, STL requires a correct copy constructor / assignment
// op
// or otherwise it will free things twice on a reallocate/by value push_back.
// The vector below will behave correctly irrespective of whether a copy constructor is available
// or not and avoids the massive unnecessary (de/re)allocations the STL forces you to.
// The class itself never calls T's copy constructor, however the user of the class is still
// responsable for making sure of correct copying of elements obtained from the vector, or setting
// NonCopyable
// also automatically deletes pointer members and other neat things
template <class T>
class Vector : public NonCopyable {
T *buf;
uint alen, ulen;
void reallocate(uint n) {
ASSERT(n > ulen);
T *obuf = buf;
buf =
(T *)malloc(sizeof(T) * (alen = n)); // use malloc instead of new to avoid constructor
ASSERT(buf);
if (ulen) memcpy(buf, obuf, ulen * sizeof(T)); // memcpy avoids copy constructor
if (obuf) free(obuf);
}
void destruct(uint i) {
buf[i].~T();
DelPtr(buf[i]);
}
public:
T &push_nocons() {
if (ulen == alen) reallocate(alen * 2);
return buf[ulen++];
}
T &operator[](uint i) {
ASSERT(i < ulen);
return buf[i];
}
Vector() : ulen(0), buf(NULL) { reallocate(8); }
Vector(uint n) : ulen(0), buf(NULL) { reallocate(n); }
Vector(uint n, int c) : ulen(0), buf(NULL) {
reallocate(n);
loop(i, c) push();
}
~Vector() {
setsize(0);
free(buf);
}
T &push(const T &elem) {
push_nocons() = elem;
return buf[ulen - 1];
}
T *getbuf() { return buf; }
T &last() { return (*this)[ulen - 1]; }
T &pop() { return buf[--ulen]; }
void drop() {
ASSERT(ulen);
destruct(--ulen);
}
bool empty() { return ulen == 0; }
int size() { return ulen; }
void setsize(uint i) {
while (ulen > i) drop();
} // explicitly destruct elements
void setsize_nd(uint i) { ulen = std::min(ulen, i); }
void sort(void *cf) {
qsort(buf, ulen, sizeof(T), (int(__cdecl *)(const void *, const void *))cf);
}
void add_unique(T x) {
loop(i, (int)ulen) if (buf[i] == x) return;
push() = x;
}
void remove(uint i) {
ASSERT(i < ulen);
destruct(i);
memmove(buf + i, buf + i + 1, sizeof(T) * (ulen-- - i - 1));
}
void removeobj(T o) {
loop(i, (int)ulen) if (buf[i] == o) {
remove(i);
return;
}
}
T &insert_nc(uint i) {
push_nocons();
memmove(&buf[i + 1], &buf[i], sizeof(T) * (ulen - i - 1));
return buf[i];
}
T &insert(uint i) {
T &t = insert_nc(i);
t = T();
return t;
}
};
// simple safe string class
class String : public NonCopyable {
static const int smallsize = 32;
char *buf;
int ulen, alen;
char sbuf[smallsize];
public:
String() : buf(NULL), ulen(0), alen(smallsize) { sbuf[0] = 0; }
explicit String(const char *s) : buf(NULL), ulen(0), alen(smallsize) {
sbuf[0] = 0;
Copy(s);
}
~String() { DELETEP(buf); }
char *c_str() { return buf ? buf : sbuf; }
operator char *() { return c_str(); }
int Len() { return ulen; }
char *Copy(const char *s) { return Copy(s, (int)strlen(s)); }
char *Copy(const char *s, int len) {
ulen = 0;
return Cat(s, len);
}
char *Copy(float f) { return Format("%f", f); }
char *Copy(int i) { return Format("%d", i); }
char *Cat(const char *s) { return Cat(s, (int)strlen(s)); }
char *Cat(uchar c) { return Cat((char *)&c, 1); }
char *Cat(const char *s, int len) {
char *b = c_str();
if (len + ulen >= alen) {
char *nb = new char[alen = ((len + ulen) / smallsize + 1) * smallsize];
if (ulen) strcpy(nb, b);
if (b != sbuf) DELETEP(b);
buf = b = nb;
}
strncpy(b + ulen, s, len);
b[ulen += len] = 0;
return b;
}
void Trim(int p) { c_str()[ulen = p] = 0; }
char *Format(char *fmt, ...) {
Clear();
char *r;
varargs(v, fmt, r = FormatVA(fmt, v));
return r;
}
char *FormatCat(char *fmt, ...) {
char *r;
varargs(v, fmt, r = FormatVA(fmt, v));
return r;
}
char *FormatVA(char *fmt, va_list v) {
char t[1000]; // FIXME ugh. any way to know size ahead of time?
_vsnprintf(t, 1000, fmt, v);
return Cat(t);
}
void Clear() { Copy(""); }
char &operator[](int i) {
ASSERT(i >= 0 && i <= ulen);
return c_str()[i];
}
bool operator==(String &o) { return !strcmp(c_str(), o.c_str()); }
void Lowercase() { loop(i, ulen) c_str()[i] = tolower(c_str()[i]); }
};
inline void OutputDebugF(char *fmt, ...) {
String s;
varargs(v, fmt, s.FormatVA(fmt, v));
OutputDebugStringA(s);
}
// Hashtable that uses strings for keys
// Does not copy keys, client responsible for key memory
// Upon destruction, deletes contained values if they are pointers
template <class T>
class Hashtable : public NonCopyable {
protected:
struct chain : SlabAllocated<chain> {
chain *next;
char *key;
T data;
};
int size;
chain **table;
public:
int numelems;
Hashtable(int nbits = 10) {
this->size = 1 << nbits;
numelems = 0;
table = new chain *[size];
loop(i, size) table[i] = NULL;
}
~Hashtable() {
clear();
DELETEA(table);
}
void clear(bool delptr = true) {
loop(i, size) {
for (chain *d, *c = table[i]; d = c;) {
c = c->next;
if (delptr) DelPtr(d->data);
DELETEP(d);
}
table[i] = NULL;
}
numelems = 0;
}
void remove(char *key) {
unsigned int h;
chain *t = find(key, h);
if (t) {
for (chain **c = &table[h]; *c; c = &(*c)->next)
if (strcmp(key, (*c)->key) == 0) {
chain *next = (*c)->next;
delete (*c);
*c = next;
numelems--;
return;
}
}
}
T &operator[](char *key) {
unsigned int h;
chain *old = find(key, h);
return old ? old->data : insert(key, h)->data;
}
T *find(char *key) {
unsigned int h;
chain *c = find(key, h);
return c ? &c->data : NULL;
}
void getelements(Vector<T> &v) {
loop(h, size) for (chain *c = table[h]; c; c = c->next) v.push(c->data);
}
int biter;
chain *citer;
void resetiter() {
biter = 0;
citer = table[0];
advanceiter();
}
void advanceiter() {
while (!citer) {
biter++;
if (biter == size) break;
citer = table[biter];
}
}
bool validiter() { return biter < size; }
T &nextiter() {
T &cur = citer->data;
citer = citer->next;
advanceiter();
return cur;
}
chain *insert(char *key, unsigned int h) {
chain *c = new chain;
c->key = key;
c->next = table[h];
memset(&c->data, 0, sizeof(T));
table[h] = c;
numelems++;
return c;
}
chain *find(char *key, unsigned int &h) {
h = 5381;
for (int i = 0, k; k = key[i]; i++) h = ((h << 5) + h) ^ k; // bernstein k=33 xor
h = h & (size - 1); // primes not much of an advantage
for (chain *c = table[h]; c; c = c->next)
if (strcmp(key, c->key) == 0) return c;
return NULL;
}
};
struct StringPool {
struct Nothing {}; // FIXME: this still has a sizeof() of 1, thus costs 8 bytes extra
Hashtable<Nothing> ht;
StringPool() : ht(16) {}
char *add(char *s) {
unsigned int h;
auto c = ht.find(s, h);
if (c) return c->key;
s = pool.alloc_string(s);
ht.insert(s, h);
return s;
}
void clear() {
ht.resetiter();
while (ht.validiter()) {
pool.dealloc_string(ht.citer->key);
ht.citer = ht.citer->next;
ht.advanceiter();
}
ht.clear(false);
}
};
inline const char *stristr(const char *haystack, const char *needle) {
if (!*needle) { return haystack; }
char firstneedle = toupper(*needle);
for (; *haystack; ++haystack) {
if (toupper(*haystack) == firstneedle) {
// Matched starting char -- loop through remaining chars.
const char *h, *n;
for (h = haystack, n = needle; *h && *n; ++h, ++n) {
if (toupper(*h) != toupper(*n)) { break; }
}
if (!*n) /* matched all of 'needle' to null termination */
{
return haystack; /* return the start of the match */
}
}
}
return 0;
}
class MTRnd {
const static uint N = 624;
const static uint M = 397;
const static uint K = 0x9908B0DFU;
uint hiBit(uint u) { return u & 0x80000000U; }
uint loBit(uint u) { return u & 0x00000001U; }
uint loBits(uint u) { return u & 0x7FFFFFFFU; }
uint mixBits(uint u, uint v) { return hiBit(u) | loBits(v); }
uint state[N + 1];
uint *next;
int left;
public:
MTRnd() : left(-1) {}
void SeedMT(uint seed) {
uint x = (seed | 1U) & 0xFFFFFFFFU, *s = state;
int j;
for (left = 0, *s++ = x, j = N; --j; *s++ = (x *= 69069U) & 0xFFFFFFFFU)
;
}
uint ReloadMT() {
uint *p0 = state, *p2 = state + 2, *pM = state + M, s0, s1;
int j;
if (left < -1) SeedMT(4357U);
left = N - 1, next = state + 1;
for (s0 = state[0], s1 = state[1], j = N - M + 1; --j; s0 = s1, s1 = *p2++)
*p0++ = *pM++ ^ (mixBits(s0, s1) >> 1) ^ (loBit(s1) ? K : 0U);
for (pM = state, j = M; --j; s0 = s1, s1 = *p2++)
*p0++ = *pM++ ^ (mixBits(s0, s1) >> 1) ^ (loBit(s1) ? K : 0U);
s1 = state[0], *p0 = *pM ^ (mixBits(s0, s1) >> 1) ^ (loBit(s1) ? K : 0U);
s1 ^= (s1 >> 11);
s1 ^= (s1 << 7) & 0x9D2C5680U;
s1 ^= (s1 << 15) & 0xEFC60000U;
return (s1 ^ (s1 >> 18));
}
uint RandomMT() {
uint y;
if (--left < 0) return (ReloadMT());
y = *next++;
y ^= (y >> 11);
y ^= (y << 7) & 0x9D2C5680U;
y ^= (y << 15) & 0xEFC60000U;
return (y ^ (y >> 18));
}
int operator()(int max) { return RandomMT() % max; }
};
// for use with vc++ crtdbg
/*
#ifdef _DEBUG
void *__cdecl operator new(size_t n, const char *fn, int l) { return ::operator new(n, 1, fn, l); }
void __cdecl operator delete(void *p, const char *fn, int l) { ::operator delete(p, 1, fn, l); }
#define new new(__FILE__,__LINE__)
#endif
*/
| [
"aardappel@gmail.com"
] | aardappel@gmail.com |
ac66f94eb65d7aee4b6c84736d55e6ffa96b1743 | 4e988b4482c10dad0be54fd8c6c668a16ce01f11 | /src/structures/AABB.hpp | 457b4e1f92f4a4c9918f087ee9a82aa10fe21370 | [] | no_license | WXDawaken/MPUImplicits | 909ab24a57db3a7adfb50b4b87ece0e829eda3a7 | 3485a8e6988a5f8c8e41526c4cfcef49db97041a | refs/heads/master | 2020-04-15T22:04:32.228389 | 2017-06-24T18:07:48 | 2017-06-24T18:07:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,288 | hpp |
#include "Point.hpp"
#include <glm/glm.hpp>
template<class T>
class AABB {
public:
AABB();
~AABB() {};
// Sets AABB from the given points
AABB(const vector<Point<T> > &points);
// Extends AABB with the given points
void extend(const vector<Point<T> > &points);
// Sets the AABB based on the input vectors
void setAABB(tvec3<T> min, tvec3<T> max) { this->minP = min; this->maxP = max; }
// Fetches AABB diagonal
glm::tvec3<T> AABB<T>::getDiagonal() const;
// Fetches magnitude longest edge of the AABB
T getLongestEdge() const;
tvec3<T> getCenter() const;
// Resets the AABB
void setNull() { this->minP = tvec3<T>(1.0); this->maxP = tvec3<T>(-1.0); }
bool isNull() const { return this->minP.x > this->maxP.x || this->minP.y > this->maxP.y || this->minP.z > this->maxP.z; }
// Getters
glm::tvec3<T> getMin() { return minP; }
glm::tvec3<T> getMax() { return maxP; }
private:
// AABB bounds
tvec3<T> minP;
tvec3<T> maxP;
T compMax(const tvec3<T> vec) const;
};
template <class T>
AABB<T>::AABB() {
this->setNull();
}
template <class T>
AABB<T>::AABB(const vector<Point<T> > &points) {
this->setNull();
this->extend(points);
}
template <class T>
void AABB<T>::extend(const vector<Point<T> > &points) {
if (points.size() <= 0) {
return;
}
auto pointsIt = points.begin();
// Set initial min max
if (this->isNull()) {
this->minP = pointsIt->position;
this->maxP = pointsIt->position;
pointsIt++;
}
for (auto it = pointsIt; it != points.end(); it++) {
this->minP = glm::min(this->minP, it->position);
this->maxP = glm::max(this->maxP, it->position);
}
}
template <class T>
glm::tvec3<T> AABB<T>::getDiagonal() const {
if (!this->isNull()) {
return this->maxP - this->minP;
}
else {
return glm::tvec3<T>(0);
}
}
template <class T>
glm::tvec3<T> AABB<T>::getCenter() const {
if (!this->isNull()) {
glm::tvec3<T> d = this->getDiagonal();
return this->minP + (d * static_cast<T>(0.5));
}
else {
return glm::tvec3<T>(0.0);
}
}
template <class T>
T AABB<T>::getLongestEdge() const {
return this->compMax(getDiagonal());
}
template <class T>
T AABB<T>::compMax(const tvec3<T> vec) const {
T rez = vec[0];
for (length_t i = 1, n = vec.length(); i < n; ++i)
rez = (rez < vec[i]) ? vec[i] : rez;
return rez;
} | [
"primozlavric16@gmail.com"
] | primozlavric16@gmail.com |
2e7f8ef29790595b1cd80747512893ab135dfc54 | f7a9767c7b7ad7de482e590741721bab995e5e7c | /clang-tools-extra/test/clang-tidy/checkers/bugprone/easily-swappable-parameters-qualifiermixing.cpp | bf980d951307b782aa9d7eabe74a44205a6a8c56 | [
"NCSA",
"LLVM-exception",
"Apache-2.0"
] | permissive | kitaisreal/llvm-project | 891a43345e35c6643ad13ed489018b3273e183e9 | ac357a4773c22e0022558b627d8c3fb4aaabc125 | refs/heads/main | 2023-08-08T13:21:00.967289 | 2023-07-26T16:06:13 | 2023-07-26T16:16:41 | 230,374,981 | 0 | 0 | Apache-2.0 | 2019-12-27T04:50:32 | 2019-12-27T04:50:32 | null | UTF-8 | C++ | false | false | 10,258 | cpp | // RUN: %check_clang_tidy %s bugprone-easily-swappable-parameters %t \
// RUN: -config='{CheckOptions: [ \
// RUN: {key: bugprone-easily-swappable-parameters.MinimumLength, value: 2}, \
// RUN: {key: bugprone-easily-swappable-parameters.IgnoredParameterNames, value: ""}, \
// RUN: {key: bugprone-easily-swappable-parameters.IgnoredParameterTypeSuffixes, value: ""}, \
// RUN: {key: bugprone-easily-swappable-parameters.QualifiersMix, value: 1}, \
// RUN: {key: bugprone-easily-swappable-parameters.ModelImplicitConversions, value: 0}, \
// RUN: {key: bugprone-easily-swappable-parameters.SuppressParametersUsedTogether, value: 0}, \
// RUN: {key: bugprone-easily-swappable-parameters.NamePrefixSuffixSilenceDissimilarityTreshold, value: 0} \
// RUN: ]}' --
typedef int MyInt1;
typedef int MyInt2;
using CInt = const int;
using CMyInt1 = const MyInt1;
using CMyInt2 = const MyInt2;
void qualified1(int I, const int CI) {}
// CHECK-MESSAGES: :[[@LINE-1]]:17: warning: 2 adjacent parameters of 'qualified1' of similar type are easily swapped by mistake [bugprone-easily-swappable-parameters]
// CHECK-MESSAGES: :[[@LINE-2]]:21: note: the first parameter in the range is 'I'
// CHECK-MESSAGES: :[[@LINE-3]]:34: note: the last parameter in the range is 'CI'
// CHECK-MESSAGES: :[[@LINE-4]]:24: note: 'int' and 'const int' parameters accept and bind the same kind of values
void qualified2(int I, volatile int VI) {}
// CHECK-MESSAGES: :[[@LINE-1]]:17: warning: 2 adjacent parameters of 'qualified2' of similar type are
// CHECK-MESSAGES: :[[@LINE-2]]:21: note: the first parameter in the range is 'I'
// CHECK-MESSAGES: :[[@LINE-3]]:37: note: the last parameter in the range is 'VI'
// CHECK-MESSAGES: :[[@LINE-4]]:24: note: 'int' and 'volatile int' parameters accept and bind the same kind of values
void qualified3(int I, const volatile int CVI) {}
// CHECK-MESSAGES: :[[@LINE-1]]:17: warning: 2 adjacent parameters of 'qualified3' of similar type are
// CHECK-MESSAGES: :[[@LINE-2]]:21: note: the first parameter in the range is 'I'
// CHECK-MESSAGES: :[[@LINE-3]]:43: note: the last parameter in the range is 'CVI'
// CHECK-MESSAGES: :[[@LINE-4]]:24: note: 'int' and 'const volatile int' parameters accept and bind the same kind of values
void qualified4(int *IP, const int *CIP) {}
// CHECK-MESSAGES: :[[@LINE-1]]:17: warning: 2 adjacent parameters of 'qualified4' of similar type are
// CHECK-MESSAGES: :[[@LINE-2]]:22: note: the first parameter in the range is 'IP'
// CHECK-MESSAGES: :[[@LINE-3]]:37: note: the last parameter in the range is 'CIP'
// CHECK-MESSAGES: :[[@LINE-4]]:26: note: 'int *' and 'const int *' parameters accept and bind the same kind of values
void qualified5(const int CI, const long CL) {} // NO-WARN: Not the same type
void qualifiedPtr1(int *IP, int *const IPC) {}
// CHECK-MESSAGES: :[[@LINE-1]]:20: warning: 2 adjacent parameters of 'qualifiedPtr1' of similar type are
// CHECK-MESSAGES: :[[@LINE-2]]:25: note: the first parameter in the range is 'IP'
// CHECK-MESSAGES: :[[@LINE-3]]:40: note: the last parameter in the range is 'IPC'
// CHECK-MESSAGES: :[[@LINE-4]]:29: note: 'int *' and 'int *const' parameters accept and bind the same kind of values
void qualifiedPtr2(int *IP, int *volatile IPV) {}
// CHECK-MESSAGES: :[[@LINE-1]]:20: warning: 2 adjacent parameters of 'qualifiedPtr2' of similar type are
// CHECK-MESSAGES: :[[@LINE-2]]:25: note: the first parameter in the range is 'IP'
// CHECK-MESSAGES: :[[@LINE-3]]:43: note: the last parameter in the range is 'IPV'
// CHECK-MESSAGES: :[[@LINE-4]]:29: note: 'int *' and 'int *volatile' parameters accept and bind the same kind of values
void qualifiedTypeAndQualifiedPtr1(const int *CIP, int *const volatile IPCV) {}
// CHECK-MESSAGES: :[[@LINE-1]]:36: warning: 2 adjacent parameters of 'qualifiedTypeAndQualifiedPtr1' of similar type are
// CHECK-MESSAGES: :[[@LINE-2]]:47: note: the first parameter in the range is 'CIP'
// CHECK-MESSAGES: :[[@LINE-3]]:72: note: the last parameter in the range is 'IPCV'
// CHECK-MESSAGES: :[[@LINE-4]]:52: note: 'const int *' and 'int *const volatile' parameters accept and bind the same kind of values
void qualifiedThroughTypedef1(int I, CInt CI) {}
// CHECK-MESSAGES: :[[@LINE-1]]:31: warning: 2 adjacent parameters of 'qualifiedThroughTypedef1' of similar type are
// CHECK-MESSAGES: :[[@LINE-2]]:35: note: the first parameter in the range is 'I'
// CHECK-MESSAGES: :[[@LINE-3]]:43: note: the last parameter in the range is 'CI'
// CHECK-MESSAGES: :[[@LINE-4]]:31: note: after resolving type aliases, 'int' and 'CInt' share a common type
// CHECK-MESSAGES: :[[@LINE-5]]:38: note: 'int' and 'CInt' parameters accept and bind the same kind of values
void qualifiedThroughTypedef2(CInt CI1, const int CI2) {}
// CHECK-MESSAGES: :[[@LINE-1]]:31: warning: 2 adjacent parameters of 'qualifiedThroughTypedef2' of similar type are
// CHECK-MESSAGES: :[[@LINE-2]]:36: note: the first parameter in the range is 'CI1'
// CHECK-MESSAGES: :[[@LINE-3]]:51: note: the last parameter in the range is 'CI2'
// CHECK-MESSAGES: :[[@LINE-4]]:31: note: after resolving type aliases, 'CInt' and 'const int' are the same
void qualifiedThroughTypedef3(CInt CI1, const MyInt1 CI2, const int CI3) {}
// CHECK-MESSAGES: :[[@LINE-1]]:31: warning: 3 adjacent parameters of 'qualifiedThroughTypedef3' of similar type are
// CHECK-MESSAGES: :[[@LINE-2]]:36: note: the first parameter in the range is 'CI1'
// CHECK-MESSAGES: :[[@LINE-3]]:69: note: the last parameter in the range is 'CI3'
// CHECK-MESSAGES: :[[@LINE-4]]:31: note: after resolving type aliases, the common type of 'CInt' and 'const MyInt1' is 'const int'
// CHECK-MESSAGES: :[[@LINE-5]]:31: note: after resolving type aliases, 'CInt' and 'const int' are the same
// CHECK-MESSAGES: :[[@LINE-6]]:41: note: after resolving type aliases, 'const MyInt1' and 'const int' are the same
void qualifiedThroughTypedef4(CInt CI1, const MyInt1 CI2, const MyInt2 CI3) {}
// CHECK-MESSAGES: :[[@LINE-1]]:31: warning: 3 adjacent parameters of 'qualifiedThroughTypedef4' of similar type are
// CHECK-MESSAGES: :[[@LINE-2]]:36: note: the first parameter in the range is 'CI1'
// CHECK-MESSAGES: :[[@LINE-3]]:72: note: the last parameter in the range is 'CI3'
// CHECK-MESSAGES: :[[@LINE-4]]:31: note: after resolving type aliases, the common type of 'CInt' and 'const MyInt1' is 'const int'
// CHECK-MESSAGES: :[[@LINE-5]]:31: note: after resolving type aliases, the common type of 'CInt' and 'const MyInt2' is 'const int'
// CHECK-MESSAGES: :[[@LINE-6]]:41: note: after resolving type aliases, the common type of 'const MyInt1' and 'const MyInt2' is 'const int'
void qualifiedThroughTypedef5(CMyInt1 CMI1, CMyInt2 CMI2) {}
// CHECK-MESSAGES: :[[@LINE-1]]:31: warning: 2 adjacent parameters of 'qualifiedThroughTypedef5' of similar type are
// CHECK-MESSAGES: :[[@LINE-2]]:39: note: the first parameter in the range is 'CMI1'
// CHECK-MESSAGES: :[[@LINE-3]]:53: note: the last parameter in the range is 'CMI2'
// CHECK-MESSAGES: :[[@LINE-4]]:31: note: after resolving type aliases, the common type of 'CMyInt1' and 'CMyInt2' is 'const int'
void qualifiedThroughTypedef6(CMyInt1 CMI1, int I) {}
// CHECK-MESSAGES: :[[@LINE-1]]:31: warning: 2 adjacent parameters of 'qualifiedThroughTypedef6' of similar type are
// CHECK-MESSAGES: :[[@LINE-2]]:39: note: the first parameter in the range is 'CMI1'
// CHECK-MESSAGES: :[[@LINE-3]]:49: note: the last parameter in the range is 'I'
// CHECK-MESSAGES: :[[@LINE-4]]:31: note: after resolving type aliases, 'CMyInt1' and 'int' share a common type
// CHECK-MESSAGES: :[[@LINE-5]]:45: note: 'CMyInt1' and 'int' parameters accept and bind the same kind of values
void referenceToTypedef1(CInt &CIR, int I) {}
// CHECK-MESSAGES: :[[@LINE-1]]:26: warning: 2 adjacent parameters of 'referenceToTypedef1' of similar type are
// CHECK-MESSAGES: :[[@LINE-2]]:32: note: the first parameter in the range is 'CIR'
// CHECK-MESSAGES: :[[@LINE-3]]:41: note: the last parameter in the range is 'I'
// CHECK-MESSAGES: :[[@LINE-4]]:37: note: 'CInt &' and 'int' parameters accept and bind the same kind of values
template <typename T>
void copy(const T *Dest, T *Source) {}
// CHECK-MESSAGES: :[[@LINE-1]]:11: warning: 2 adjacent parameters of 'copy' of similar type are
// CHECK-MESSAGES: :[[@LINE-2]]:20: note: the first parameter in the range is 'Dest'
// CHECK-MESSAGES: :[[@LINE-3]]:29: note: the last parameter in the range is 'Source'
// CHECK-MESSAGES: :[[@LINE-4]]:26: note: 'const T *' and 'T *' parameters accept and bind the same kind of values
void attributedParam1TypedefRef(
const __attribute__((address_space(256))) int &OneR,
__attribute__((address_space(256))) MyInt1 &TwoR) {}
// CHECK-MESSAGES: :[[@LINE-2]]:5: warning: 2 adjacent parameters of 'attributedParam1TypedefRef' of similar type are
// CHECK-MESSAGES: :[[@LINE-3]]:52: note: the first parameter in the range is 'OneR'
// CHECK-MESSAGES: :[[@LINE-3]]:49: note: the last parameter in the range is 'TwoR'
// CHECK-MESSAGES: :[[@LINE-5]]:5: note: after resolving type aliases, the common type of 'const __attribute__((address_space(256))) int &' and '__attribute__((address_space(256))) MyInt1 &' is '__attribute__((address_space(256))) int &'
// CHECK-MESSAGES: :[[@LINE-5]]:5: note: 'const __attribute__((address_space(256))) int &' and '__attribute__((address_space(256))) MyInt1 &' parameters accept and bind the same kind of values
void attributedParam2(__attribute__((address_space(256))) int *One,
const __attribute__((address_space(256))) MyInt1 *Two) {}
// CHECK-MESSAGES: :[[@LINE-2]]:23: warning: 2 adjacent parameters of 'attributedParam2' of similar type are
// CHECK-MESSAGES: :[[@LINE-3]]:64: note: the first parameter in the range is 'One'
// CHECK-MESSAGES: :[[@LINE-3]]:73: note: the last parameter in the range is 'Two'
// CHECK-MESSAGES: :[[@LINE-5]]:23: note: after resolving type aliases, '__attribute__((address_space(256))) int *' and 'const __attribute__((address_space(256))) MyInt1 *' share a common type
// CHECK-MESSAGES: :[[@LINE-5]]:23: note: '__attribute__((address_space(256))) int *' and 'const __attribute__((address_space(256))) MyInt1 *' parameters accept and bind the same kind of values
| [
"whisperity@gmail.com"
] | whisperity@gmail.com |
cb33b63d556c81ae617c2a28d5bf407a61fe662c | 9bbef6def62136a555bbe5dd6962fe929f5f102d | /lldb/include/lldb/Target/TraceCursor.h | c27bba3abf4cb9a9e740e24d587e10874c8e80b6 | [
"NCSA",
"Apache-2.0",
"LLVM-exception"
] | permissive | jmorse/llvm-project | ca96001f51957966a718d350f51e88580cd96a83 | ee8da6369225f47f85e61e1ef2807af6a8677a0d | refs/heads/master | 2023-07-27T02:18:21.584156 | 2021-07-11T14:10:11 | 2021-07-11T14:10:11 | 183,056,402 | 1 | 0 | null | 2023-03-03T20:51:17 | 2019-04-23T16:39:17 | null | UTF-8 | C++ | false | false | 5,377 | h | //===-- TraceCursor.h -------------------------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#ifndef LLDB_TARGET_TRACE_CURSOR_H
#define LLDB_TARGET_TRACE_CURSOR_H
#include "lldb/lldb-private.h"
namespace lldb_private {
/// Class used for iterating over the instructions of a thread's trace.
///
/// This class attempts to be a generic interface for accessing the instructions
/// of the trace so that each Trace plug-in can reconstruct, represent and store
/// the instruction data in an flexible way that is efficient for the given
/// technology.
///
/// Live processes:
/// In the case of a live process trace, an instance of a \a TraceCursor should
/// point to the trace at the moment it was collected. If the process is later
/// resumed and new trace data is collected, that should leave that old cursor
/// unaffected.
///
/// Errors in the trace:
/// As there could be errors when reconstructing the instructions of a trace,
/// these errors are represented as failed instructions, and the cursor can
/// point at them. The consumer should invoke \a TraceCursor::GetError() to
/// check if the cursor is pointing to either a valid instruction or an error.
///
/// Instructions:
/// A \a TraceCursor always points to a specific instruction or error in the
/// trace.
///
/// The Trace initially points to the last item in the trace.
///
/// Sample usage:
///
/// TraceCursorUP cursor = trace.GetTrace(thread);
///
/// auto granularity = eTraceInstructionControlFlowTypeCall |
/// eTraceInstructionControlFlowTypeReturn;
///
/// do {
/// if (llvm::Error error = cursor->GetError())
/// cout << "error found at: " << llvm::toString(error) << endl;
/// else if (cursor->GetInstructionControlFlowType() &
/// eTraceInstructionControlFlowTypeCall)
/// std::cout << "call found at " << cursor->GetLoadAddress() <<
/// std::endl;
/// else if (cursor->GetInstructionControlFlowType() &
/// eTraceInstructionControlFlowTypeReturn)
/// std::cout << "return found at " << cursor->GetLoadAddress() <<
/// std::endl;
/// } while(cursor->Prev(granularity));
class TraceCursor {
public:
virtual ~TraceCursor() = default;
/// Move the cursor to the next instruction more recent chronologically in the
/// trace given the provided granularity. If such instruction is not found,
/// the cursor doesn't move.
///
/// \param[in] granularity
/// Bitmask granularity filter. The cursor stops at the next
/// instruction that matches the specified granularity.
///
/// \param[in] ignore_errors
/// If \b false, the cursor stops as soon as it finds a failure in the
/// trace and points at it.
///
/// \return
/// \b true if the cursor effectively moved and now points to a different
/// item in the trace, including errors when \b ignore_errors is \b false.
/// In other words, if \b false is returned, then the trace is pointing at
/// the same item in the trace as before.
virtual bool Next(lldb::TraceInstructionControlFlowType granularity =
lldb::eTraceInstructionControlFlowTypeInstruction,
bool ignore_errors = false) = 0;
/// Similar to \a TraceCursor::Next(), but moves backwards chronologically.
virtual bool Prev(lldb::TraceInstructionControlFlowType granularity =
lldb::eTraceInstructionControlFlowTypeInstruction,
bool ignore_errors = false) = 0;
/// Force the cursor to point to the end of the trace, i.e. the most recent
/// item.
virtual void SeekToEnd() = 0;
/// Force the cursor to point to the beginning of the trace, i.e. the oldest
/// item.
virtual void SeekToBegin() = 0;
/// \return
/// \b true if the trace corresponds to a live process who has resumed after
/// the trace cursor was created. Otherwise, including the case in which the
/// process is a post-mortem one, return \b false.
bool IsStale();
/// Instruction or error information
/// \{
/// Get the corresponding error message if the cursor points to an error in
/// the trace.
///
/// \return
/// \b llvm::Error::success if the cursor is not pointing to an error in
/// the trace. Otherwise return an \a llvm::Error describing the issue.
virtual llvm::Error GetError() = 0;
/// \return
/// The load address of the instruction the cursor is pointing at. If the
/// cursor points to an error in the trace, return \b
/// LLDB_INVALID_ADDRESS.
virtual lldb::addr_t GetLoadAddress() = 0;
/// \return
/// The \a lldb::TraceInstructionControlFlowType categories the
/// instruction the cursor is pointing at falls into. If the cursor points
/// to an error in the trace, return \b 0.
virtual lldb::TraceInstructionControlFlowType
GetInstructionControlFlowType() = 0;
/// \}
private:
/// The stop ID when the cursor was created.
uint32_t m_stop_id = 0;
/// The trace that owns this cursor.
lldb::TraceSP m_trace_sp;
};
} // namespace lldb_private
#endif // LLDB_TARGET_TRACE_CURSOR_H
| [
"wallace@fb.com"
] | wallace@fb.com |
a09e078eb8dd6367ff30ede189de09fd4d7c2cce | 519c64b3f1a8d8c12121141f9f950db8c31d3ac9 | /Poj/2376.cpp | 3855ebb58af6ba8c050ea127ed4257a0386e8e55 | [] | no_license | Ronnoc/Training | 7c7db931865dd5a7ba222b3c1c384a43459737f0 | 75d16ac8f33dfe0cf47548bf75d35a8b51967184 | refs/heads/master | 2022-11-11T19:57:53.845777 | 2022-11-06T02:54:34 | 2022-11-06T02:54:34 | 13,489,501 | 17 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 1,343 | cpp | #include <map>
#include <set>
#include <list>
#include <cmath>
#include <ctime>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <cctype>
#include <cstdio>
#include <string>
#include <vector>
#include <cassert>
#include <cstdlib>
#include <cstring>
#include <iomanip>
#include <sstream>
#include <iostream>
#include <algorithm>
using namespace std;
#define PB push_back
#define MP make_pair
#define AA first
#define BB second
#define OP begin()
#define ED end()
#define SZ size()
#define SORT(x) sort(x.OP,x.ED)
#define SQ(x) ((x)*(x))
#define SSP system("pause")
#define cmin(x,y) x=min(x,y)
#define cmax(x,y) x=max(x,y)
typedef long long LL;
typedef pair<int, int> PII;
const double eps=1e-8;
const double PI=acos( -1. );
const LL MOD = 1000000007;
int G[1000005];
int F[1000005];
int main() {
//freopen("","r",stdin);
//freopen("","w",stdout);
int i,j,k,T;
int n,m;
while(~scanf("%d%d",&n,&m)){
for(i=1;i<=m;i++)G[i]=-1;
for(i=1;i<=n;i++){
int u,v;
scanf("%d%d",&u,&v);
if(u<1)u=1;
if(v>m)v=m;
cmax(G[u],v);
}
F[1]=G[1];
for(i=2;i<=m;i++)F[i]=max(F[i-1],G[i]);
int ans=0;
int where=0;
int fail=0;
while(where<m){
int next=F[where+1];
if(next<where+1){fail=1;break;}
where=next;
ans++;
}
if(!fail)printf("%d\n",ans);
else printf("-1\n");
}
return 0;
}
| [
"kybconnor@126.com"
] | kybconnor@126.com |
3830cfc2fd5b8a3c57f7e1391f1ab65f56a9f147 | 641fa8341d8c436ad24945bcbf8e7d7d1dd7dbb2 | /android_webview/browser/aw_content_browser_client.h | a3472c5393350e9f9d622eae6a55c8cec5cab240 | [
"BSD-3-Clause"
] | permissive | massnetwork/mass-browser | 7de0dfc541cbac00ffa7308541394bac1e945b76 | 67526da9358734698c067b7775be491423884339 | refs/heads/master | 2022-12-07T09:01:31.027715 | 2017-01-19T14:29:18 | 2017-01-19T14:29:18 | 73,799,690 | 4 | 4 | BSD-3-Clause | 2022-11-26T11:53:23 | 2016-11-15T09:49:29 | null | UTF-8 | C++ | false | false | 6,732 | h | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef ANDROID_WEBVIEW_LIB_AW_CONTENT_BROWSER_CLIENT_H_
#define ANDROID_WEBVIEW_LIB_AW_CONTENT_BROWSER_CLIENT_H_
#include <stddef.h>
#include <memory>
#include "android_webview/browser/aw_web_preferences_populater.h"
#include "base/compiler_specific.h"
#include "base/macros.h"
#include "content/public/browser/content_browser_client.h"
namespace android_webview {
class AwBrowserContext;
class JniDependencyFactory;
class AwContentBrowserClient : public content::ContentBrowserClient {
public:
// This is what AwContentBrowserClient::GetAcceptLangs uses.
static std::string GetAcceptLangsImpl();
// Deprecated: use AwBrowserContext::GetDefault() instead.
static AwBrowserContext* GetAwBrowserContext();
AwContentBrowserClient(JniDependencyFactory* native_factory);
~AwContentBrowserClient() override;
// Allows AwBrowserMainParts to initialize a BrowserContext at the right
// moment during startup. AwContentBrowserClient owns the result.
AwBrowserContext* InitBrowserContext();
content::BrowserMainParts* CreateBrowserMainParts(
const content::MainFunctionParams& parameters) override;
content::WebContentsViewDelegate* GetWebContentsViewDelegate(
content::WebContents* web_contents) override;
void RenderProcessWillLaunch(content::RenderProcessHost* host) override;
bool IsHandledURL(const GURL& url) override;
std::string GetCanonicalEncodingNameByAliasName(
const std::string& alias_name) override;
void AppendExtraCommandLineSwitches(base::CommandLine* command_line,
int child_process_id) override;
std::string GetApplicationLocale() override;
std::string GetAcceptLangs(content::BrowserContext* context) override;
const gfx::ImageSkia* GetDefaultFavicon() override;
bool AllowAppCache(const GURL& manifest_url,
const GURL& first_party,
content::ResourceContext* context) override;
bool AllowGetCookie(const GURL& url,
const GURL& first_party,
const net::CookieList& cookie_list,
content::ResourceContext* context,
int render_process_id,
int render_frame_id) override;
bool AllowSetCookie(const GURL& url,
const GURL& first_party,
const std::string& cookie_line,
content::ResourceContext* context,
int render_process_id,
int render_frame_id,
const net::CookieOptions& options) override;
void AllowWorkerFileSystem(
const GURL& url,
content::ResourceContext* context,
const std::vector<std::pair<int, int>>& render_frames,
base::Callback<void(bool)> callback) override;
bool AllowWorkerIndexedDB(
const GURL& url,
const base::string16& name,
content::ResourceContext* context,
const std::vector<std::pair<int, int>>& render_frames) override;
content::QuotaPermissionContext* CreateQuotaPermissionContext() override;
void AllowCertificateError(
content::WebContents* web_contents,
int cert_error,
const net::SSLInfo& ssl_info,
const GURL& request_url,
content::ResourceType resource_type,
bool overridable,
bool strict_enforcement,
bool expired_previous_decision,
const base::Callback<void(content::CertificateRequestResultType)>&
callback) override;
void SelectClientCertificate(
content::WebContents* web_contents,
net::SSLCertRequestInfo* cert_request_info,
std::unique_ptr<content::ClientCertificateDelegate> delegate) override;
bool CanCreateWindow(const GURL& opener_url,
const GURL& opener_top_level_frame_url,
const GURL& source_origin,
WindowContainerType container_type,
const GURL& target_url,
const content::Referrer& referrer,
const std::string& frame_name,
WindowOpenDisposition disposition,
const blink::WebWindowFeatures& features,
bool user_gesture,
bool opener_suppressed,
content::ResourceContext* context,
int render_process_id,
int opener_render_view_id,
int opener_render_frame_id,
bool* no_javascript_access) override;
void ResourceDispatcherHostCreated() override;
net::NetLog* GetNetLog() override;
void ClearCache(content::RenderFrameHost* rfh) override;
void ClearCookies(content::RenderFrameHost* rfh) override;
base::FilePath GetDefaultDownloadDirectory() override;
std::string GetDefaultDownloadName() override;
void DidCreatePpapiPlugin(content::BrowserPpapiHost* browser_host) override;
bool AllowPepperSocketAPI(
content::BrowserContext* browser_context,
const GURL& url,
bool private_api,
const content::SocketPermissionRequest* params) override;
bool IsPepperVpnProviderAPIAllowed(content::BrowserContext* browser_context,
const GURL& url) override;
content::TracingDelegate* GetTracingDelegate() override;
void GetAdditionalMappedFilesForChildProcess(
const base::CommandLine& command_line,
int child_process_id,
content::FileDescriptorInfo* mappings,
std::map<int, base::MemoryMappedFile::Region>* regions) override;
void OverrideWebkitPrefs(content::RenderViewHost* rvh,
content::WebPreferences* web_prefs) override;
ScopedVector<content::NavigationThrottle> CreateThrottlesForNavigation(
content::NavigationHandle* navigation_handle) override;
content::DevToolsManagerDelegate* GetDevToolsManagerDelegate() override;
std::unique_ptr<base::Value> GetServiceManifestOverlay(
const std::string& name) override;
void RegisterRenderFrameMojoInterfaces(
service_manager::InterfaceRegistry* registry,
content::RenderFrameHost* render_frame_host) override;
private:
// Android WebView currently has a single global (non-off-the-record) browser
// context.
std::unique_ptr<AwBrowserContext> browser_context_;
std::unique_ptr<AwWebPreferencesPopulater> preferences_populater_;
JniDependencyFactory* native_factory_;
DISALLOW_COPY_AND_ASSIGN(AwContentBrowserClient);
};
} // namespace android_webview
#endif // ANDROID_WEBVIEW_LIB_AW_CONTENT_BROWSER_CLIENT_H_
| [
"xElvis89x@gmail.com"
] | xElvis89x@gmail.com |
001d3287221292acba4f62fafcd84c69c21046c4 | 6d1c143787686870c2bd792b75836c5a707dad3f | /Server/CommonCPlus/CommonCPlus/boost_old/math/distributions/exponential.hpp | 99c50b73aa6afc9e229758024053b88eacd6bf4c | [] | no_license | jakeowner/lastbattle | 66dad639dd0ac43fd46bac7a0005cc157d350cc9 | 22d310f5bca796461678ccf044389ed5f60e03e0 | refs/heads/master | 2021-05-06T18:25:48.932112 | 2017-11-24T08:21:59 | 2017-11-24T08:21:59 | 111,915,246 | 45 | 34 | null | 2017-11-24T12:19:15 | 2017-11-24T12:19:15 | null | UTF-8 | C++ | false | false | 8,855 | hpp | // Copyright John Maddock 2006.
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_STATS_EXPONENTIAL_HPP
#define BOOST_STATS_EXPONENTIAL_HPP
#include <boost/math/distributions/fwd.hpp>
#include <boost/math/constants/constants.hpp>
#include <boost/math/special_functions/log1p.hpp>
#include <boost/math/special_functions/expm1.hpp>
#include <boost/math/distributions/complement.hpp>
#include <boost/math/distributions/detail/common_error_handling.hpp>
#include <boost/config/no_tr1/cmath.hpp>
#ifdef BOOST_MSVC
# pragma warning(push)
# pragma warning(disable: 4127) // conditional expression is constant
# pragma warning(disable: 4702) // unreachable code (return after domain_error throw).
#endif
#include <utility>
namespace boost{ namespace math{
namespace detail{
//
// Error check:
//
template <class RealType, class Policy>
inline bool verify_lambda(const char* function, RealType l, RealType* presult, const Policy& pol)
{
if((l <= 0) || !(boost::math::isfinite)(l))
{
*presult = policies::raise_domain_error<RealType>(
function,
"The scale parameter \"lambda\" must be > 0, but was: %1%.", l, pol);
return false;
}
return true;
}
template <class RealType, class Policy>
inline bool verify_exp_x(const char* function, RealType x, RealType* presult, const Policy& pol)
{
if((x < 0) || (boost::math::isnan)(x))
{
*presult = policies::raise_domain_error<RealType>(
function,
"The random variable must be >= 0, but was: %1%.", x, pol);
return false;
}
return true;
}
} // namespace detail
template <class RealType = double, class Policy = policies::policy<> >
class exponential_distribution
{
public:
typedef RealType value_type;
typedef Policy policy_type;
exponential_distribution(RealType l_lambda = 1)
: m_lambda(l_lambda)
{
RealType err;
detail::verify_lambda("boost::math::exponential_distribution<%1%>::exponential_distribution", l_lambda, &err, Policy());
} // exponential_distribution
RealType lambda()const { return m_lambda; }
private:
RealType m_lambda;
};
typedef exponential_distribution<double> exponential;
template <class RealType, class Policy>
inline const std::pair<RealType, RealType> range(const exponential_distribution<RealType, Policy>& /*dist*/)
{ // Range of permissible values for random variable x.
if (std::numeric_limits<RealType>::has_infinity)
{
return std::pair<RealType, RealType>(static_cast<RealType>(0), std::numeric_limits<RealType>::infinity()); // 0 to + infinity.
}
else
{
using boost::math::tools::max_value;
return std::pair<RealType, RealType>(static_cast<RealType>(0), max_value<RealType>()); // 0 to + max
}
}
template <class RealType, class Policy>
inline const std::pair<RealType, RealType> support(const exponential_distribution<RealType, Policy>& /*dist*/)
{ // Range of supported values for random variable x.
// This is range where cdf rises from 0 to 1, and outside it, the pdf is zero.
using boost::math::tools::max_value;
using boost::math::tools::min_value;
return std::pair<RealType, RealType>(min_value<RealType>(), max_value<RealType>());
// min_value<RealType>() to avoid a discontinuity at x = 0.
}
template <class RealType, class Policy>
inline RealType pdf(const exponential_distribution<RealType, Policy>& dist, const RealType& x)
{
BOOST_MATH_STD_USING // for ADL of std functions
static const char* function = "boost::math::pdf(const exponential_distribution<%1%>&, %1%)";
RealType lambda = dist.lambda();
RealType result = 0;
if(0 == detail::verify_lambda(function, lambda, &result, Policy()))
return result;
if(0 == detail::verify_exp_x(function, x, &result, Policy()))
return result;
result = lambda * exp(-lambda * x);
return result;
} // pdf
template <class RealType, class Policy>
inline RealType cdf(const exponential_distribution<RealType, Policy>& dist, const RealType& x)
{
BOOST_MATH_STD_USING // for ADL of std functions
static const char* function = "boost::math::cdf(const exponential_distribution<%1%>&, %1%)";
RealType result = 0;
RealType lambda = dist.lambda();
if(0 == detail::verify_lambda(function, lambda, &result, Policy()))
return result;
if(0 == detail::verify_exp_x(function, x, &result, Policy()))
return result;
result = -boost::math::expm1(-x * lambda, Policy());
return result;
} // cdf
template <class RealType, class Policy>
inline RealType quantile(const exponential_distribution<RealType, Policy>& dist, const RealType& p)
{
BOOST_MATH_STD_USING // for ADL of std functions
static const char* function = "boost::math::quantile(const exponential_distribution<%1%>&, %1%)";
RealType result = 0;
RealType lambda = dist.lambda();
if(0 == detail::verify_lambda(function, lambda, &result, Policy()))
return result;
if(0 == detail::check_probability(function, p, &result, Policy()))
return result;
if(p == 0)
return 0;
if(p == 1)
return policies::raise_overflow_error<RealType>(function, 0, Policy());
result = -boost::math::log1p(-p, Policy()) / lambda;
return result;
} // quantile
template <class RealType, class Policy>
inline RealType cdf(const complemented2_type<exponential_distribution<RealType, Policy>, RealType>& c)
{
BOOST_MATH_STD_USING // for ADL of std functions
static const char* function = "boost::math::cdf(const exponential_distribution<%1%>&, %1%)";
RealType result = 0;
RealType lambda = c.dist.lambda();
if(0 == detail::verify_lambda(function, lambda, &result, Policy()))
return result;
if(0 == detail::verify_exp_x(function, c.param, &result, Policy()))
return result;
result = exp(-c.param * lambda);
return result;
}
template <class RealType, class Policy>
inline RealType quantile(const complemented2_type<exponential_distribution<RealType, Policy>, RealType>& c)
{
BOOST_MATH_STD_USING // for ADL of std functions
static const char* function = "boost::math::quantile(const exponential_distribution<%1%>&, %1%)";
RealType result = 0;
RealType lambda = c.dist.lambda();
if(0 == detail::verify_lambda(function, lambda, &result, Policy()))
return result;
RealType q = c.param;
if(0 == detail::check_probability(function, q, &result, Policy()))
return result;
if(q == 1)
return 0;
if(q == 0)
return policies::raise_overflow_error<RealType>(function, 0, Policy());
result = -log(q) / lambda;
return result;
}
template <class RealType, class Policy>
inline RealType mean(const exponential_distribution<RealType, Policy>& dist)
{
RealType result = 0;
RealType lambda = dist.lambda();
if(0 == detail::verify_lambda("boost::math::mean(const exponential_distribution<%1%>&)", lambda, &result, Policy()))
return result;
return 1 / lambda;
}
template <class RealType, class Policy>
inline RealType standard_deviation(const exponential_distribution<RealType, Policy>& dist)
{
RealType result = 0;
RealType lambda = dist.lambda();
if(0 == detail::verify_lambda("boost::math::standard_deviation(const exponential_distribution<%1%>&)", lambda, &result, Policy()))
return result;
return 1 / lambda;
}
template <class RealType, class Policy>
inline RealType mode(const exponential_distribution<RealType, Policy>& /*dist*/)
{
return 0;
}
template <class RealType, class Policy>
inline RealType median(const exponential_distribution<RealType, Policy>& dist)
{
using boost::math::constants::ln_two;
return ln_two<RealType>() / dist.lambda(); // ln(2) / lambda
}
template <class RealType, class Policy>
inline RealType skewness(const exponential_distribution<RealType, Policy>& /*dist*/)
{
return 2;
}
template <class RealType, class Policy>
inline RealType kurtosis(const exponential_distribution<RealType, Policy>& /*dist*/)
{
return 9;
}
template <class RealType, class Policy>
inline RealType kurtosis_excess(const exponential_distribution<RealType, Policy>& /*dist*/)
{
return 6;
}
} // namespace math
} // namespace boost
#ifdef BOOST_MSVC
# pragma warning(pop)
#endif
// This include must be at the end, *after* the accessors
// for this distribution have been defined, in order to
// keep compilers that support two-phase lookup happy.
#include <boost/math/distributions/detail/derived_accessors.hpp>
#endif // BOOST_STATS_EXPONENTIAL_HPP
| [
"613961636@qq.com"
] | 613961636@qq.com |
5f946e425be39e8576a32949de202a755c75abf1 | eb7caa862eb8cb9ed81b6568c13303f9a8590b02 | /build3/vs2010/InhousePGSSOlver/SolverConfig.h | c1d72b6b3277d667870ec2f3055ca97c8e2b0c19 | [
"Zlib"
] | permissive | Valvador/bullet3Experiments | 43c80fd72b074abd80fbaeabad8c922ee11e5ba5 | d345149a2ea3a9c92eb6397b9d79bfda966d6652 | refs/heads/master | 2021-01-15T18:16:34.281231 | 2020-09-08T02:39:14 | 2020-09-08T02:39:14 | 35,391,137 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 151 | h | #pragma once
namespace Config
{
const static float positionalCorrectionFactor = 0.3f;
const static float positionCorrectionDepthThreshold = 0.02f;
} | [
"val.v.gorbunov@gmail.com"
] | val.v.gorbunov@gmail.com |
0dcb67d268ccd7726983a5da01c75eafcf44a5c4 | 484ffbe24d1c4331ac9e630ed5bb761bcf4b1641 | /G1-2/C++/B073040049_HW3/CH7/ch7-6.h | b4f69d5d694632548134ff553bd2e302bab246f8 | [] | no_license | Max-Hsu/Homework | f2f0aca06e26c29e6d4ea148ede5144fdff093c1 | acae82866899da0af49d25e7008e5f43ddc88ebb | refs/heads/master | 2021-07-02T13:39:52.635266 | 2020-11-19T04:39:18 | 2020-11-19T04:39:18 | 198,411,243 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 541 | h | #include <iostream>
#include <string>
#include <vector>
using namespace std;
#ifndef PIZZA
class pizzaData{
public:
pizzaData(string size,string type,int pep,int che);
void outputDescription();
int computePrize();
private:
string size;
string type;
int pep;
int che;
};
class Order{
public:
Order();
Order(string size,string type,int pep,int che);
void outputDescription();
void computePrize();
void order(string size,string type,int pep,int che);
private:
vector<class pizzaData> Data;
};
#define PIZZA
#endif | [
"evaair3317@hotmail.com.tw"
] | evaair3317@hotmail.com.tw |
1c540dfb9a93348c02052b0744dcebd76ac1b6ec | 5390eac0ac54d2c3c1c664ae525881fa988e2cf9 | /include/Pothos/serialization/impl/type_traits/detail/bool_trait_def.hpp | a0ed8abb2deb5da4118c30e2949c59e0ffe693da | [
"BSL-1.0"
] | permissive | pothosware/pothos-serialization | 2935b8ab1fe51299a6beba2a3e11611928186849 | c59130f916a3e5b833a32ba415063f9cb306a8dd | refs/heads/master | 2021-08-16T15:22:12.642058 | 2015-12-10T03:32:04 | 2015-12-10T03:32:04 | 19,961,886 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,635 | hpp |
// NO INCLUDE GUARDS, THE HEADER IS INTENDED FOR MULTIPLE INCLUSION
// Copyright Aleksey Gurtovoy 2002-2004
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// $Source$
// $Date: 2011-10-09 15:28:33 -0700 (Sun, 09 Oct 2011) $
// $Revision: 74865 $
#include <Pothos/serialization/impl/type_traits/detail/template_arity_spec.hpp>
#include <Pothos/serialization/impl/type_traits/integral_constant.hpp>
#include <Pothos/serialization/impl/mpl/bool.hpp>
#include <Pothos/serialization/impl/mpl/aux_/lambda_support.hpp>
#include <Pothos/serialization/impl/config.hpp>
//
// Unfortunately some libraries have started using this header without
// cleaning up afterwards: so we'd better undef the macros just in case
// they've been defined already....
//
#ifdef POTHOS_TT_AUX_BOOL_TRAIT_VALUE_DECL
#undef POTHOS_TT_AUX_BOOL_TRAIT_VALUE_DECL
#undef POTHOS_TT_AUX_BOOL_C_BASE
#undef POTHOS_TT_AUX_BOOL_TRAIT_DEF1
#undef POTHOS_TT_AUX_BOOL_TRAIT_DEF2
#undef POTHOS_TT_AUX_BOOL_TRAIT_SPEC1
#undef POTHOS_TT_AUX_BOOL_TRAIT_SPEC2
#undef POTHOS_TT_AUX_BOOL_TRAIT_IMPL_SPEC1
#undef POTHOS_TT_AUX_BOOL_TRAIT_IMPL_SPEC2
#undef POTHOS_TT_AUX_BOOL_TRAIT_PARTIAL_SPEC1_1
#undef POTHOS_TT_AUX_BOOL_TRAIT_PARTIAL_SPEC1_2
#undef POTHOS_TT_AUX_BOOL_TRAIT_PARTIAL_SPEC2_1
#undef POTHOS_TT_AUX_BOOL_TRAIT_PARTIAL_SPEC2_2
#undef POTHOS_TT_AUX_BOOL_TRAIT_IMPL_PARTIAL_SPEC2_1
#undef POTHOS_TT_AUX_BOOL_TRAIT_CV_SPEC1
#endif
#if defined(__SUNPRO_CC) && (__SUNPRO_CC < 0x570)
# define POTHOS_TT_AUX_BOOL_TRAIT_VALUE_DECL(C) \
typedef ::Pothos::integral_constant<bool,C> type; \
enum { value = type::value }; \
/**/
# define POTHOS_TT_AUX_BOOL_C_BASE(C)
#elif defined(POTHOS_MSVC) && POTHOS_MSVC < 1300
# define POTHOS_TT_AUX_BOOL_TRAIT_VALUE_DECL(C) \
typedef ::Pothos::integral_constant<bool,C> base_; \
using base_::value; \
/**/
#endif
#ifndef POTHOS_TT_AUX_BOOL_TRAIT_VALUE_DECL
# define POTHOS_TT_AUX_BOOL_TRAIT_VALUE_DECL(C) /**/
#endif
#ifndef POTHOS_TT_AUX_BOOL_C_BASE
# define POTHOS_TT_AUX_BOOL_C_BASE(C) : public ::Pothos::integral_constant<bool,C>
#endif
#define POTHOS_TT_AUX_BOOL_TRAIT_DEF1(trait,T,C) \
template< typename T > struct trait \
POTHOS_TT_AUX_BOOL_C_BASE(C) \
{ \
public:\
POTHOS_TT_AUX_BOOL_TRAIT_VALUE_DECL(C) \
POTHOS_MPL_AUX_LAMBDA_SUPPORT(1,trait,(T)) \
}; \
\
POTHOS_TT_AUX_TEMPLATE_ARITY_SPEC(1,trait) \
/**/
#define POTHOS_TT_AUX_BOOL_TRAIT_DEF2(trait,T1,T2,C) \
template< typename T1, typename T2 > struct trait \
POTHOS_TT_AUX_BOOL_C_BASE(C) \
{ \
public:\
POTHOS_TT_AUX_BOOL_TRAIT_VALUE_DECL(C) \
POTHOS_MPL_AUX_LAMBDA_SUPPORT(2,trait,(T1,T2)) \
}; \
\
POTHOS_TT_AUX_TEMPLATE_ARITY_SPEC(2,trait) \
/**/
#define POTHOS_TT_AUX_BOOL_TRAIT_DEF3(trait,T1,T2,T3,C) \
template< typename T1, typename T2, typename T3 > struct trait \
POTHOS_TT_AUX_BOOL_C_BASE(C) \
{ \
public:\
POTHOS_TT_AUX_BOOL_TRAIT_VALUE_DECL(C) \
POTHOS_MPL_AUX_LAMBDA_SUPPORT(3,trait,(T1,T2,T3)) \
}; \
\
POTHOS_TT_AUX_TEMPLATE_ARITY_SPEC(3,trait) \
/**/
#define POTHOS_TT_AUX_BOOL_TRAIT_SPEC1(trait,sp,C) \
template<> struct trait< sp > \
POTHOS_TT_AUX_BOOL_C_BASE(C) \
{ \
public:\
POTHOS_TT_AUX_BOOL_TRAIT_VALUE_DECL(C) \
POTHOS_MPL_AUX_LAMBDA_SUPPORT_SPEC(1,trait,(sp)) \
}; \
/**/
#define POTHOS_TT_AUX_BOOL_TRAIT_SPEC2(trait,sp1,sp2,C) \
template<> struct trait< sp1,sp2 > \
POTHOS_TT_AUX_BOOL_C_BASE(C) \
{ \
public:\
POTHOS_TT_AUX_BOOL_TRAIT_VALUE_DECL(C) \
POTHOS_MPL_AUX_LAMBDA_SUPPORT_SPEC(2,trait,(sp1,sp2)) \
}; \
/**/
#define POTHOS_TT_AUX_BOOL_TRAIT_IMPL_SPEC1(trait,sp,C) \
template<> struct trait##_impl< sp > \
{ \
public:\
POTHOS_STATIC_CONSTANT(bool, value = (C)); \
}; \
/**/
#define POTHOS_TT_AUX_BOOL_TRAIT_IMPL_SPEC2(trait,sp1,sp2,C) \
template<> struct trait##_impl< sp1,sp2 > \
{ \
public:\
POTHOS_STATIC_CONSTANT(bool, value = (C)); \
}; \
/**/
#define POTHOS_TT_AUX_BOOL_TRAIT_PARTIAL_SPEC1_1(param,trait,sp,C) \
template< param > struct trait< sp > \
POTHOS_TT_AUX_BOOL_C_BASE(C) \
{ \
public:\
POTHOS_TT_AUX_BOOL_TRAIT_VALUE_DECL(C) \
}; \
/**/
#define POTHOS_TT_AUX_BOOL_TRAIT_PARTIAL_SPEC1_2(param1,param2,trait,sp,C) \
template< param1, param2 > struct trait< sp > \
POTHOS_TT_AUX_BOOL_C_BASE(C) \
{ \
public:\
POTHOS_TT_AUX_BOOL_TRAIT_VALUE_DECL(C) \
}; \
/**/
#define POTHOS_TT_AUX_BOOL_TRAIT_PARTIAL_SPEC2_1(param,trait,sp1,sp2,C) \
template< param > struct trait< sp1,sp2 > \
POTHOS_TT_AUX_BOOL_C_BASE(C) \
{ \
public:\
POTHOS_TT_AUX_BOOL_TRAIT_VALUE_DECL(C) \
POTHOS_MPL_AUX_LAMBDA_SUPPORT_SPEC(2,trait,(sp1,sp2)) \
}; \
/**/
#define POTHOS_TT_AUX_BOOL_TRAIT_PARTIAL_SPEC2_2(param1,param2,trait,sp1,sp2,C) \
template< param1, param2 > struct trait< sp1,sp2 > \
POTHOS_TT_AUX_BOOL_C_BASE(C) \
{ \
public:\
POTHOS_TT_AUX_BOOL_TRAIT_VALUE_DECL(C) \
}; \
/**/
#define POTHOS_TT_AUX_BOOL_TRAIT_IMPL_PARTIAL_SPEC2_1(param,trait,sp1,sp2,C) \
template< param > struct trait##_impl< sp1,sp2 > \
{ \
public:\
POTHOS_STATIC_CONSTANT(bool, value = (C)); \
}; \
/**/
#ifndef POTHOS_NO_CV_SPECIALIZATIONS
# define POTHOS_TT_AUX_BOOL_TRAIT_CV_SPEC1(trait,sp,value) \
POTHOS_TT_AUX_BOOL_TRAIT_SPEC1(trait,sp,value) \
POTHOS_TT_AUX_BOOL_TRAIT_SPEC1(trait,sp const,value) \
POTHOS_TT_AUX_BOOL_TRAIT_SPEC1(trait,sp volatile,value) \
POTHOS_TT_AUX_BOOL_TRAIT_SPEC1(trait,sp const volatile,value) \
/**/
#else
# define POTHOS_TT_AUX_BOOL_TRAIT_CV_SPEC1(trait,sp,value) \
POTHOS_TT_AUX_BOOL_TRAIT_SPEC1(trait,sp,value) \
/**/
#endif
| [
"josh@joshknows.com"
] | josh@joshknows.com |
f457a046614c5ca8f636e3ae188e10d6bd4c5465 | e8f7e608dd1e409c56092652e54f93512062250d | /src/component/Component/Component.cpp | f01523faccbd05b69d4e861934673515259bb220 | [] | no_license | 1000happiness/CutSimulation | 1b524e395474eddc6111a718161ee7d931936ea2 | 88b368f445a502e7a6e7d1cf6c47dcfbca476c4c | refs/heads/master | 2023-04-07T05:19:43.437949 | 2021-04-25T00:32:11 | 2021-04-25T00:32:11 | 361,340,919 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,658 | cpp | #include "Component.h"
#include "../Transform/Transform.h"
#include "../Camera/Camera.h"
#include "../AutoRotation/AutoRotation.h"
#include "../AutoColor/AutoColor.h"
#include "../AutoConfiguration/AutoConfiguration.h"
#include "../Light/AmbientLight.h"
#include "../Light/DiffuseLight.h"
#include "../Light/SpecularLight.h"
#include "../ParticleSystem/ParticleSystem.h"
#include "../WorkPiece/WorkPiece.h"
#include "../CoordinateSystemLines/CoordinateSystemLines.h"
#include "../UI/Label.h"
#include "../UI/BezierPanel.h"
#include "../UI/Text.h"
#include "../../object/Object/Object.h"
namespace CMP
{
Component::Component(Kind kind, OBJ::Object *game_object)
{
this->kind = kind;
this->game_object = game_object;
this->removed = false;
this->changeFlag = true;
}
Component::~Component()
{
}
void Component::apply(OBJ::Prefab *prefab)
{
delete (*(prefab->components))[kind];
(*(prefab->components))[kind] = createComponent(this);
}
void Component::render(MAT::ShaderProgram* shader) {
}
Component *Component::createComponent(Component *component)
{
switch (component->kind)
{
case Kind::TRANSFORM:
return new Transform(*((Transform *)component));//直接使用默认的拷贝构造函数
case Kind::CAMERA:
return new Camera(*((Camera *)component));
case Kind::AUTOROTATION:
return new AutoRotation(*((AutoRotation*)component));
case Kind::AUTOCOLOR:
return new AutoColor(*((AutoColor*)component));
case Kind::AUTOCOMFIGURATION:
return new AutoConfiguration(*(AutoConfiguration*)component);
case Kind::AMBIENTLIGHT:
return new AmbientLight(*(AmbientLight*)component);
case Kind::DIFFUSELIGHT:
return new DiffuseLight(*(DiffuseLight*)component);
case Kind::SPECULARLIGHT:
return new SpecularLight(*(SpecularLight*)component);
case Kind::PARTICLESYSTEM:
return new ParticleSystem(*(ParticleSystem*)component);
case Kind::WORKPIECE:
return new WorkPiece(*(WorkPiece*)component);
case Kind::COORDINATESYSTEMLINES:
return new CoordinateSystemLines(*(CoordinateSystemLines*)component);
case Kind::LABEL:
return new Label(*(Label*)component);
case Kind::BEZIERPANEL:
return new BezierPanel(*(BezierPanel*)component);
case Kind::TEXT:
return new Text(*(Text*)component);
default:
break;
}
return NULL;
}
} // namespace CMP
| [
"1000happiness@sjtu.edu.cn"
] | 1000happiness@sjtu.edu.cn |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.