blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
listlengths
1
1
author
stringlengths
0
119
0cdfcd374f39e6cb82bfd96204f5d697f5dd29ec
d9c1f9fd6353be7cd2eca1edcd5d15f7ef993d98
/Qt5/include/QtQml/5.12.2/QtQml/private/qqmlpropertycachecreator_p.h
6bee599c0aef0c5ff8ce8964431e23089b816667
[]
no_license
LuxCoreRender/WindowsCompileDeps
f0e3cdba92880f5340ae9df18c6aa81779cbc2ea
f96d4b5a701679f3222385c1ac099aaf3f0e0be9
refs/heads/master
2021-12-28T20:20:19.752792
2021-11-25T16:21:17
2021-11-25T16:21:17
113,448,564
3
8
null
2019-11-06T09:41:07
2017-12-07T12:31:38
C++
UTF-8
C++
false
false
36,114
h
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the tools applications of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QQMLPROPERTYCACHECREATOR_P_H #define QQMLPROPERTYCACHECREATOR_P_H // // W A R N I N G // ------------- // // This file is not part of the Qt API. It exists purely as an // implementation detail. This header file may change from version to // version without notice, or even be removed. // // We mean it. // #include <private/qqmlvaluetype_p.h> #include <private/qqmlengine_p.h> QT_BEGIN_NAMESPACE struct QQmlBindingInstantiationContext { QQmlBindingInstantiationContext() {} QQmlBindingInstantiationContext(int referencingObjectIndex, const QV4::CompiledData::Binding *instantiatingBinding, const QString &instantiatingPropertyName, QQmlPropertyCache *referencingObjectPropertyCache); bool resolveInstantiatingProperty(); QQmlRefPointer<QQmlPropertyCache> instantiatingPropertyCache(QQmlEnginePrivate *enginePrivate) const; int referencingObjectIndex = -1; const QV4::CompiledData::Binding *instantiatingBinding = nullptr; QString instantiatingPropertyName; QQmlRefPointer<QQmlPropertyCache> referencingObjectPropertyCache; QQmlPropertyData *instantiatingProperty = nullptr; }; struct QQmlPendingGroupPropertyBindings : public QVector<QQmlBindingInstantiationContext> { void resolveMissingPropertyCaches(QQmlEnginePrivate *enginePrivate, QQmlPropertyCacheVector *propertyCaches) const; }; struct QQmlPropertyCacheCreatorBase { Q_DECLARE_TR_FUNCTIONS(QQmlPropertyCacheCreatorBase) public: static QAtomicInt classIndexCounter; }; template <typename ObjectContainer> class QQmlPropertyCacheCreator : public QQmlPropertyCacheCreatorBase { public: typedef typename ObjectContainer::CompiledObject CompiledObject; QQmlPropertyCacheCreator(QQmlPropertyCacheVector *propertyCaches, QQmlPendingGroupPropertyBindings *pendingGroupPropertyBindings, QQmlEnginePrivate *enginePrivate, const ObjectContainer *objectContainer, const QQmlImports *imports); QQmlCompileError buildMetaObjects(); protected: QQmlCompileError buildMetaObjectRecursively(int objectIndex, const QQmlBindingInstantiationContext &context); QQmlRefPointer<QQmlPropertyCache> propertyCacheForObject(const CompiledObject *obj, const QQmlBindingInstantiationContext &context, QQmlCompileError *error) const; QQmlCompileError createMetaObject(int objectIndex, const CompiledObject *obj, const QQmlRefPointer<QQmlPropertyCache> &baseTypeCache); QString stringAt(int index) const { return objectContainer->stringAt(index); } QQmlEnginePrivate * const enginePrivate; const ObjectContainer * const objectContainer; const QQmlImports * const imports; QQmlPropertyCacheVector *propertyCaches; QQmlPendingGroupPropertyBindings *pendingGroupPropertyBindings; }; template <typename ObjectContainer> inline QQmlPropertyCacheCreator<ObjectContainer>::QQmlPropertyCacheCreator(QQmlPropertyCacheVector *propertyCaches, QQmlPendingGroupPropertyBindings *pendingGroupPropertyBindings, QQmlEnginePrivate *enginePrivate, const ObjectContainer *objectContainer, const QQmlImports *imports) : enginePrivate(enginePrivate) , objectContainer(objectContainer) , imports(imports) , propertyCaches(propertyCaches) , pendingGroupPropertyBindings(pendingGroupPropertyBindings) { propertyCaches->resize(objectContainer->objectCount()); } template <typename ObjectContainer> inline QQmlCompileError QQmlPropertyCacheCreator<ObjectContainer>::buildMetaObjects() { QQmlBindingInstantiationContext context; return buildMetaObjectRecursively(/*root object*/0, context); } template <typename ObjectContainer> inline QQmlCompileError QQmlPropertyCacheCreator<ObjectContainer>::buildMetaObjectRecursively(int objectIndex, const QQmlBindingInstantiationContext &context) { const CompiledObject *obj = objectContainer->objectAt(objectIndex); bool needVMEMetaObject = obj->propertyCount() != 0 || obj->aliasCount() != 0 || obj->signalCount() != 0 || obj->functionCount() != 0 || obj->enumCount() != 0; if (!needVMEMetaObject) { auto binding = obj->bindingsBegin(); auto end = obj->bindingsEnd(); for ( ; binding != end; ++binding) { if (binding->type == QV4::CompiledData::Binding::Type_Object && (binding->flags & QV4::CompiledData::Binding::IsOnAssignment)) { // If the on assignment is inside a group property, we need to distinguish between QObject based // group properties and value type group properties. For the former the base type is derived from // the property that references us, for the latter we only need a meta-object on the referencing object // because interceptors can't go to the shared value type instances. if (context.instantiatingProperty && QQmlValueTypeFactory::isValueType(context.instantiatingProperty->propType())) { if (!propertyCaches->needsVMEMetaObject(context.referencingObjectIndex)) { const CompiledObject *obj = objectContainer->objectAt(context.referencingObjectIndex); auto *typeRef = objectContainer->resolvedType(obj->inheritedTypeNameIndex); Q_ASSERT(typeRef); QQmlRefPointer<QQmlPropertyCache> baseTypeCache = typeRef->createPropertyCache(QQmlEnginePrivate::get(enginePrivate)); QQmlCompileError error = createMetaObject(context.referencingObjectIndex, obj, baseTypeCache); if (error.isSet()) return error; } } else { // On assignments are implemented using value interceptors, which require a VME meta object. needVMEMetaObject = true; } break; } } } QQmlRefPointer<QQmlPropertyCache> baseTypeCache; { QQmlCompileError error; baseTypeCache = propertyCacheForObject(obj, context, &error); if (error.isSet()) return error; } if (baseTypeCache) { if (needVMEMetaObject) { QQmlCompileError error = createMetaObject(objectIndex, obj, baseTypeCache); if (error.isSet()) return error; } else { propertyCaches->set(objectIndex, baseTypeCache); } } if (QQmlPropertyCache *thisCache = propertyCaches->at(objectIndex)) { auto binding = obj->bindingsBegin(); auto end = obj->bindingsEnd(); for ( ; binding != end; ++binding) if (binding->type >= QV4::CompiledData::Binding::Type_Object) { QQmlBindingInstantiationContext context(objectIndex, &(*binding), stringAt(binding->propertyNameIndex), thisCache); // Binding to group property where we failed to look up the type of the // property? Possibly a group property that is an alias that's not resolved yet. // Let's attempt to resolve it after we're done with the aliases and fill in the // propertyCaches entry then. if (!context.resolveInstantiatingProperty()) pendingGroupPropertyBindings->append(context); QQmlCompileError error = buildMetaObjectRecursively(binding->value.objectIndex, context); if (error.isSet()) return error; } } QQmlCompileError noError; return noError; } template <typename ObjectContainer> inline QQmlRefPointer<QQmlPropertyCache> QQmlPropertyCacheCreator<ObjectContainer>::propertyCacheForObject(const CompiledObject *obj, const QQmlBindingInstantiationContext &context, QQmlCompileError *error) const { if (context.instantiatingProperty) { return context.instantiatingPropertyCache(enginePrivate); } else if (obj->inheritedTypeNameIndex != 0) { auto *typeRef = objectContainer->resolvedType(obj->inheritedTypeNameIndex); Q_ASSERT(typeRef); if (typeRef->isFullyDynamicType) { if (obj->propertyCount() > 0 || obj->aliasCount() > 0) { *error = QQmlCompileError(obj->location, QQmlPropertyCacheCreatorBase::tr("Fully dynamic types cannot declare new properties.")); return nullptr; } if (obj->signalCount() > 0) { *error = QQmlCompileError(obj->location, QQmlPropertyCacheCreatorBase::tr("Fully dynamic types cannot declare new signals.")); return nullptr; } if (obj->functionCount() > 0) { *error = QQmlCompileError(obj->location, QQmlPropertyCacheCreatorBase::tr("Fully Dynamic types cannot declare new functions.")); return nullptr; } } return typeRef->createPropertyCache(QQmlEnginePrivate::get(enginePrivate)); } else if (context.instantiatingBinding && context.instantiatingBinding->isAttachedProperty()) { auto *typeRef = objectContainer->resolvedType( context.instantiatingBinding->propertyNameIndex); Q_ASSERT(typeRef); QQmlType qmltype = typeRef->type; if (!qmltype.isValid()) { QString propertyName = stringAt(context.instantiatingBinding->propertyNameIndex); if (imports->resolveType(propertyName, &qmltype, nullptr, nullptr, nullptr)) { if (qmltype.isComposite()) { QQmlRefPointer<QQmlTypeData> tdata = enginePrivate->typeLoader.getType(qmltype.sourceUrl()); Q_ASSERT(tdata); Q_ASSERT(tdata->isComplete()); auto compilationUnit = tdata->compilationUnit(); qmltype = QQmlMetaType::qmlType(compilationUnit->metaTypeId); } } } const QMetaObject *attachedMo = qmltype.attachedPropertiesType(enginePrivate); if (!attachedMo) { *error = QQmlCompileError(context.instantiatingBinding->location, QQmlPropertyCacheCreatorBase::tr("Non-existent attached object")); return nullptr; } return enginePrivate->cache(attachedMo); } return nullptr; } template <typename ObjectContainer> inline QQmlCompileError QQmlPropertyCacheCreator<ObjectContainer>::createMetaObject(int objectIndex, const CompiledObject *obj, const QQmlRefPointer<QQmlPropertyCache> &baseTypeCache) { QQmlRefPointer<QQmlPropertyCache> cache; cache.adopt(baseTypeCache->copyAndReserve(obj->propertyCount() + obj->aliasCount(), obj->functionCount() + obj->propertyCount() + obj->aliasCount() + obj->signalCount(), obj->signalCount() + obj->propertyCount() + obj->aliasCount(), obj->enumCount())); propertyCaches->set(objectIndex, cache); propertyCaches->setNeedsVMEMetaObject(objectIndex); struct TypeData { QV4::CompiledData::Property::Type dtype; int metaType; } builtinTypes[] = { { QV4::CompiledData::Property::Var, QMetaType::QVariant }, { QV4::CompiledData::Property::Variant, QMetaType::QVariant }, { QV4::CompiledData::Property::Int, QMetaType::Int }, { QV4::CompiledData::Property::Bool, QMetaType::Bool }, { QV4::CompiledData::Property::Real, QMetaType::Double }, { QV4::CompiledData::Property::String, QMetaType::QString }, { QV4::CompiledData::Property::Url, QMetaType::QUrl }, { QV4::CompiledData::Property::Color, QMetaType::QColor }, { QV4::CompiledData::Property::Font, QMetaType::QFont }, { QV4::CompiledData::Property::Time, QMetaType::QTime }, { QV4::CompiledData::Property::Date, QMetaType::QDate }, { QV4::CompiledData::Property::DateTime, QMetaType::QDateTime }, { QV4::CompiledData::Property::Rect, QMetaType::QRectF }, { QV4::CompiledData::Property::Point, QMetaType::QPointF }, { QV4::CompiledData::Property::Size, QMetaType::QSizeF }, { QV4::CompiledData::Property::Vector2D, QMetaType::QVector2D }, { QV4::CompiledData::Property::Vector3D, QMetaType::QVector3D }, { QV4::CompiledData::Property::Vector4D, QMetaType::QVector4D }, { QV4::CompiledData::Property::Matrix4x4, QMetaType::QMatrix4x4 }, { QV4::CompiledData::Property::Quaternion, QMetaType::QQuaternion } }; static const uint builtinTypeCount = sizeof(builtinTypes) / sizeof(TypeData); QByteArray newClassName; if (objectIndex == /*root object*/0) { const QString path = objectContainer->url().path(); int lastSlash = path.lastIndexOf(QLatin1Char('/')); if (lastSlash > -1) { const QStringRef nameBase = path.midRef(lastSlash + 1, path.length() - lastSlash - 5); if (!nameBase.isEmpty() && nameBase.at(0).isUpper()) newClassName = nameBase.toUtf8() + "_QMLTYPE_" + QByteArray::number(classIndexCounter.fetchAndAddRelaxed(1)); } } if (newClassName.isEmpty()) { newClassName = QQmlMetaObject(baseTypeCache.data()).className(); newClassName.append("_QML_"); newClassName.append(QByteArray::number(classIndexCounter.fetchAndAddRelaxed(1))); } cache->_dynamicClassName = newClassName; int varPropCount = 0; QmlIR::PropertyResolver resolver(baseTypeCache); auto p = obj->propertiesBegin(); auto pend = obj->propertiesEnd(); for ( ; p != pend; ++p) { if (p->type == QV4::CompiledData::Property::Var) varPropCount++; bool notInRevision = false; QQmlPropertyData *d = resolver.property(stringAt(p->nameIndex), &notInRevision); if (d && d->isFinal()) return QQmlCompileError(p->location, QQmlPropertyCacheCreatorBase::tr("Cannot override FINAL property")); } auto a = obj->aliasesBegin(); auto aend = obj->aliasesEnd(); for ( ; a != aend; ++a) { bool notInRevision = false; QQmlPropertyData *d = resolver.property(stringAt(a->nameIndex), &notInRevision); if (d && d->isFinal()) return QQmlCompileError(a->location, QQmlPropertyCacheCreatorBase::tr("Cannot override FINAL property")); } int effectivePropertyIndex = cache->propertyIndexCacheStart; int effectiveMethodIndex = cache->methodIndexCacheStart; // For property change signal override detection. // We prepopulate a set of signal names which already exist in the object, // and throw an error if there is a signal/method defined as an override. QSet<QString> seenSignals; seenSignals << QStringLiteral("destroyed") << QStringLiteral("parentChanged") << QStringLiteral("objectNameChanged"); QQmlPropertyCache *parentCache = cache.data(); while ((parentCache = parentCache->parent())) { if (int pSigCount = parentCache->signalCount()) { int pSigOffset = parentCache->signalOffset(); for (int i = pSigOffset; i < pSigCount; ++i) { QQmlPropertyData *currPSig = parentCache->signal(i); // XXX TODO: find a better way to get signal name from the property data :-/ for (QQmlPropertyCache::StringCache::ConstIterator iter = parentCache->stringCache.begin(); iter != parentCache->stringCache.end(); ++iter) { if (currPSig == (*iter).second) { seenSignals.insert(iter.key()); break; } } } } } // Set up notify signals for properties - first normal, then alias p = obj->propertiesBegin(); pend = obj->propertiesEnd(); for ( ; p != pend; ++p) { auto flags = QQmlPropertyData::defaultSignalFlags(); QString changedSigName = stringAt(p->nameIndex) + QLatin1String("Changed"); seenSignals.insert(changedSigName); cache->appendSignal(changedSigName, flags, effectiveMethodIndex++); } a = obj->aliasesBegin(); aend = obj->aliasesEnd(); for ( ; a != aend; ++a) { auto flags = QQmlPropertyData::defaultSignalFlags(); QString changedSigName = stringAt(a->nameIndex) + QLatin1String("Changed"); seenSignals.insert(changedSigName); cache->appendSignal(changedSigName, flags, effectiveMethodIndex++); } auto e = obj->enumsBegin(); auto eend = obj->enumsEnd(); for ( ; e != eend; ++e) { const int enumValueCount = e->enumValueCount(); QVector<QQmlEnumValue> values; values.reserve(enumValueCount); auto enumValue = e->enumValuesBegin(); auto end = e->enumValuesEnd(); for ( ; enumValue != end; ++enumValue) values.append(QQmlEnumValue(stringAt(enumValue->nameIndex), enumValue->value)); cache->appendEnum(stringAt(e->nameIndex), values); } // Dynamic signals auto s = obj->signalsBegin(); auto send = obj->signalsEnd(); for ( ; s != send; ++s) { const int paramCount = s->parameterCount(); QList<QByteArray> names; names.reserve(paramCount); QVarLengthArray<int, 10> paramTypes(paramCount?(paramCount + 1):0); if (paramCount) { paramTypes[0] = paramCount; int i = 0; auto param = s->parametersBegin(); auto end = s->parametersEnd(); for ( ; param != end; ++param, ++i) { names.append(stringAt(param->nameIndex).toUtf8()); if (param->type < builtinTypeCount) { // built-in type paramTypes[i + 1] = builtinTypes[param->type].metaType; } else { // lazily resolved type Q_ASSERT(param->type == QV4::CompiledData::Property::Custom); const QString customTypeName = stringAt(param->customTypeNameIndex); QQmlType qmltype; if (!imports->resolveType(customTypeName, &qmltype, nullptr, nullptr, nullptr)) return QQmlCompileError(s->location, QQmlPropertyCacheCreatorBase::tr("Invalid signal parameter type: %1").arg(customTypeName)); if (qmltype.isComposite()) { QQmlRefPointer<QQmlTypeData> tdata = enginePrivate->typeLoader.getType(qmltype.sourceUrl()); Q_ASSERT(tdata); Q_ASSERT(tdata->isComplete()); auto compilationUnit = tdata->compilationUnit(); paramTypes[i + 1] = compilationUnit->metaTypeId; } else { paramTypes[i + 1] = qmltype.typeId(); } } } } auto flags = QQmlPropertyData::defaultSignalFlags(); if (paramCount) flags.hasArguments = true; QString signalName = stringAt(s->nameIndex); if (seenSignals.contains(signalName)) return QQmlCompileError(s->location, QQmlPropertyCacheCreatorBase::tr("Duplicate signal name: invalid override of property change signal or superclass signal")); seenSignals.insert(signalName); cache->appendSignal(signalName, flags, effectiveMethodIndex++, paramCount?paramTypes.constData():nullptr, names); } // Dynamic slots auto function = objectContainer->objectFunctionsBegin(obj); auto fend = objectContainer->objectFunctionsEnd(obj); for ( ; function != fend; ++function) { auto flags = QQmlPropertyData::defaultSlotFlags(); const QString slotName = stringAt(function->nameIndex); if (seenSignals.contains(slotName)) return QQmlCompileError(function->location, QQmlPropertyCacheCreatorBase::tr("Duplicate method name: invalid override of property change signal or superclass signal")); // Note: we don't append slotName to the seenSignals list, since we don't // protect against overriding change signals or methods with properties. QList<QByteArray> parameterNames; auto formal = function->formalsBegin(); auto end = function->formalsEnd(); for ( ; formal != end; ++formal) { flags.hasArguments = true; parameterNames << stringAt(*formal).toUtf8(); } cache->appendMethod(slotName, flags, effectiveMethodIndex++, parameterNames); } // Dynamic properties int effectiveSignalIndex = cache->signalHandlerIndexCacheStart; int propertyIdx = 0; p = obj->propertiesBegin(); pend = obj->propertiesEnd(); for ( ; p != pend; ++p, ++propertyIdx) { int propertyType = 0; int propertTypeMinorVersion = 0; QQmlPropertyData::Flags propertyFlags; if (p->type == QV4::CompiledData::Property::Var) { propertyType = QMetaType::QVariant; propertyFlags.type = QQmlPropertyData::Flags::VarPropertyType; } else if (p->type < builtinTypeCount) { propertyType = builtinTypes[p->type].metaType; if (p->type == QV4::CompiledData::Property::Variant) propertyFlags.type = QQmlPropertyData::Flags::QVariantType; } else { Q_ASSERT(p->type == QV4::CompiledData::Property::CustomList || p->type == QV4::CompiledData::Property::Custom); QQmlType qmltype; if (!imports->resolveType(stringAt(p->customTypeNameIndex), &qmltype, nullptr, nullptr, nullptr)) { return QQmlCompileError(p->location, QQmlPropertyCacheCreatorBase::tr("Invalid property type")); } Q_ASSERT(qmltype.isValid()); if (qmltype.isComposite()) { QQmlRefPointer<QQmlTypeData> tdata = enginePrivate->typeLoader.getType(qmltype.sourceUrl()); Q_ASSERT(tdata); Q_ASSERT(tdata->isComplete()); auto compilationUnit = tdata->compilationUnit(); if (p->type == QV4::CompiledData::Property::Custom) { propertyType = compilationUnit->metaTypeId; } else { propertyType = compilationUnit->listMetaTypeId; } } else { if (p->type == QV4::CompiledData::Property::Custom) { propertyType = qmltype.typeId(); propertTypeMinorVersion = qmltype.minorVersion(); } else { propertyType = qmltype.qListTypeId(); } } if (p->type == QV4::CompiledData::Property::Custom) propertyFlags.type = QQmlPropertyData::Flags::QObjectDerivedType; else propertyFlags.type = QQmlPropertyData::Flags::QListType; } if (!(p->flags & QV4::CompiledData::Property::IsReadOnly) && p->type != QV4::CompiledData::Property::CustomList) propertyFlags.isWritable = true; QString propertyName = stringAt(p->nameIndex); if (!obj->defaultPropertyIsAlias && propertyIdx == obj->indexOfDefaultPropertyOrAlias) cache->_defaultPropertyName = propertyName; cache->appendProperty(propertyName, propertyFlags, effectivePropertyIndex++, propertyType, propertTypeMinorVersion, effectiveSignalIndex); effectiveSignalIndex++; } QQmlCompileError noError; return noError; } template <typename ObjectContainer> class QQmlPropertyCacheAliasCreator { public: typedef typename ObjectContainer::CompiledObject CompiledObject; QQmlPropertyCacheAliasCreator(QQmlPropertyCacheVector *propertyCaches, const ObjectContainer *objectContainer); void appendAliasPropertiesToMetaObjects(); QQmlCompileError appendAliasesToPropertyCache(const CompiledObject &component, int objectIndex); private: void appendAliasPropertiesInMetaObjectsWithinComponent(const CompiledObject &component, int firstObjectIndex); QQmlCompileError propertyDataForAlias(const CompiledObject &component, const QV4::CompiledData::Alias &alias, int *type, int *rev, QQmlPropertyRawData::Flags *propertyFlags); void collectObjectsWithAliasesRecursively(int objectIndex, QVector<int> *objectsWithAliases) const; int objectForId(const CompiledObject &component, int id) const; QQmlPropertyCacheVector *propertyCaches; const ObjectContainer *objectContainer; }; template <typename ObjectContainer> inline QQmlPropertyCacheAliasCreator<ObjectContainer>::QQmlPropertyCacheAliasCreator(QQmlPropertyCacheVector *propertyCaches, const ObjectContainer *objectContainer) : propertyCaches(propertyCaches) , objectContainer(objectContainer) { } template <typename ObjectContainer> inline void QQmlPropertyCacheAliasCreator<ObjectContainer>::appendAliasPropertiesToMetaObjects() { // skip the root object (index 0) as that one does not have a first object index originating // from a binding. for (int i = 1; i < objectContainer->objectCount(); ++i) { const CompiledObject &component = *objectContainer->objectAt(i); if (!(component.flags & QV4::CompiledData::Object::IsComponent)) continue; const auto rootBinding = component.bindingsBegin(); appendAliasPropertiesInMetaObjectsWithinComponent(component, rootBinding->value.objectIndex); } const int rootObjectIndex = 0; appendAliasPropertiesInMetaObjectsWithinComponent(*objectContainer->objectAt(rootObjectIndex), rootObjectIndex); } template <typename ObjectContainer> inline void QQmlPropertyCacheAliasCreator<ObjectContainer>::appendAliasPropertiesInMetaObjectsWithinComponent(const CompiledObject &component, int firstObjectIndex) { QVector<int> objectsWithAliases; collectObjectsWithAliasesRecursively(firstObjectIndex, &objectsWithAliases); if (objectsWithAliases.isEmpty()) return; const auto allAliasTargetsExist = [this, &component](const CompiledObject &object) { auto alias = object.aliasesBegin(); auto end = object.aliasesEnd(); for ( ; alias != end; ++alias) { Q_ASSERT(alias->flags & QV4::CompiledData::Alias::Resolved); const int targetObjectIndex = objectForId(component, alias->targetObjectId); Q_ASSERT(targetObjectIndex >= 0); if (alias->aliasToLocalAlias) continue; if (alias->encodedMetaPropertyIndex == -1) continue; const QQmlPropertyCache *targetCache = propertyCaches->at(targetObjectIndex); Q_ASSERT(targetCache); int coreIndex = QQmlPropertyIndex::fromEncoded(alias->encodedMetaPropertyIndex).coreIndex(); QQmlPropertyData *targetProperty = targetCache->property(coreIndex); if (!targetProperty) return false; } return true; }; do { QVector<int> pendingObjects; for (int objectIndex: qAsConst(objectsWithAliases)) { const CompiledObject &object = *objectContainer->objectAt(objectIndex); if (allAliasTargetsExist(object)) { appendAliasesToPropertyCache(component, objectIndex); } else { pendingObjects.append(objectIndex); } } qSwap(objectsWithAliases, pendingObjects); } while (!objectsWithAliases.isEmpty()); } template <typename ObjectContainer> inline void QQmlPropertyCacheAliasCreator<ObjectContainer>::collectObjectsWithAliasesRecursively(int objectIndex, QVector<int> *objectsWithAliases) const { const CompiledObject &object = *objectContainer->objectAt(objectIndex); if (object.aliasCount() > 0) objectsWithAliases->append(objectIndex); // Stop at Component boundary if (object.flags & QV4::CompiledData::Object::IsComponent && objectIndex != /*root object*/0) return; auto binding = object.bindingsBegin(); auto end = object.bindingsEnd(); for (; binding != end; ++binding) { if (binding->type != QV4::CompiledData::Binding::Type_Object && binding->type != QV4::CompiledData::Binding::Type_AttachedProperty && binding->type != QV4::CompiledData::Binding::Type_GroupProperty) continue; collectObjectsWithAliasesRecursively(binding->value.objectIndex, objectsWithAliases); } } template <typename ObjectContainer> inline QQmlCompileError QQmlPropertyCacheAliasCreator<ObjectContainer>::propertyDataForAlias( const CompiledObject &component, const QV4::CompiledData::Alias &alias, int *type, int *minorVersion, QQmlPropertyData::Flags *propertyFlags) { const int targetObjectIndex = objectForId(component, alias.targetObjectId); Q_ASSERT(targetObjectIndex >= 0); const CompiledObject &targetObject = *objectContainer->objectAt(targetObjectIndex); *type = 0; bool writable = false; bool resettable = false; propertyFlags->isAlias = true; if (alias.aliasToLocalAlias) { auto targetAlias = targetObject.aliasesBegin(); for (uint i = 0; i < alias.localAliasIndex; ++i) ++targetAlias; return propertyDataForAlias(component, *targetAlias, type, minorVersion, propertyFlags); } else if (alias.encodedMetaPropertyIndex == -1) { Q_ASSERT(alias.flags & QV4::CompiledData::Alias::AliasPointsToPointerObject); auto *typeRef = objectContainer->resolvedType(targetObject.inheritedTypeNameIndex); if (!typeRef) { // Can be caused by the alias target not being a valid id or property. E.g.: // property alias dataValue: dataVal // invalidAliasComponent { id: dataVal } return QQmlCompileError(targetObject.location, QQmlPropertyCacheCreatorBase::tr("Invalid alias target")); } if (typeRef->type.isValid()) *type = typeRef->type.typeId(); else *type = typeRef->compilationUnit->metaTypeId; *minorVersion = typeRef->minorVersion; propertyFlags->type = QQmlPropertyData::Flags::QObjectDerivedType; } else { int coreIndex = QQmlPropertyIndex::fromEncoded(alias.encodedMetaPropertyIndex).coreIndex(); int valueTypeIndex = QQmlPropertyIndex::fromEncoded(alias.encodedMetaPropertyIndex).valueTypeIndex(); QQmlPropertyCache *targetCache = propertyCaches->at(targetObjectIndex); Q_ASSERT(targetCache); QQmlPropertyData *targetProperty = targetCache->property(coreIndex); Q_ASSERT(targetProperty); *type = targetProperty->propType(); writable = targetProperty->isWritable(); resettable = targetProperty->isResettable(); if (valueTypeIndex != -1) { const QMetaObject *valueTypeMetaObject = QQmlValueTypeFactory::metaObjectForMetaType(*type); if (valueTypeMetaObject->property(valueTypeIndex).isEnumType()) *type = QVariant::Int; else *type = valueTypeMetaObject->property(valueTypeIndex).userType(); } else { if (targetProperty->isEnum()) { *type = QVariant::Int; } else { // Copy type flags propertyFlags->copyPropertyTypeFlags(targetProperty->flags()); if (targetProperty->isVarProperty()) propertyFlags->type = QQmlPropertyData::Flags::QVariantType; } } } propertyFlags->isWritable = !(alias.flags & QV4::CompiledData::Property::IsReadOnly) && writable; propertyFlags->isResettable = resettable; return QQmlCompileError(); } template <typename ObjectContainer> inline QQmlCompileError QQmlPropertyCacheAliasCreator<ObjectContainer>::appendAliasesToPropertyCache( const CompiledObject &component, int objectIndex) { const CompiledObject &object = *objectContainer->objectAt(objectIndex); if (!object.aliasCount()) return QQmlCompileError(); QQmlPropertyCache *propertyCache = propertyCaches->at(objectIndex); Q_ASSERT(propertyCache); int effectiveSignalIndex = propertyCache->signalHandlerIndexCacheStart + propertyCache->propertyIndexCache.count(); int effectivePropertyIndex = propertyCache->propertyIndexCacheStart + propertyCache->propertyIndexCache.count(); int aliasIndex = 0; auto alias = object.aliasesBegin(); auto end = object.aliasesEnd(); for ( ; alias != end; ++alias, ++aliasIndex) { Q_ASSERT(alias->flags & QV4::CompiledData::Alias::Resolved); int type = 0; int minorVersion = 0; QQmlPropertyData::Flags propertyFlags; QQmlCompileError error = propertyDataForAlias(component, *alias, &type, &minorVersion, &propertyFlags); if (error.isSet()) return error; const QString propertyName = objectContainer->stringAt(alias->nameIndex); if (object.defaultPropertyIsAlias && aliasIndex == object.indexOfDefaultPropertyOrAlias) propertyCache->_defaultPropertyName = propertyName; propertyCache->appendProperty(propertyName, propertyFlags, effectivePropertyIndex++, type, minorVersion, effectiveSignalIndex++); } return QQmlCompileError(); } template <typename ObjectContainer> inline int QQmlPropertyCacheAliasCreator<ObjectContainer>::objectForId(const CompiledObject &component, int id) const { for (quint32 i = 0, count = component.namedObjectsInComponentCount(); i < count; ++i) { const int candidateIndex = component.namedObjectsInComponentTable()[i]; const CompiledObject &candidate = *objectContainer->objectAt(candidateIndex); if (candidate.id == id) return candidateIndex; } return -1; } QT_END_NAMESPACE #endif // QQMLPROPERTYCACHECREATOR_P_H
118936f95b1a192d8c95404c68c80e3f6b5f04f2
b6273de390c64cf56ba009223dda3cd5f76412be
/GeeksForGeeks/strings/6_RomanNumerToInteger.cpp
f8e965fce82ed228c0bbaa53c335740524e1e4a2
[]
no_license
SaiEashwarKS/RandomCodingProblems
daa08a73b622383bb338ed4d8ec9af736192be1b
8b908408945617dc6b353a8eb75d16dcfa466bc1
refs/heads/master
2023-06-14T21:13:15.041972
2021-07-10T18:21:11
2021-07-10T18:21:11
290,248,532
0
1
null
2020-10-01T15:46:21
2020-08-25T15:12:13
C
UTF-8
C++
false
false
1,733
cpp
#if 0 Given a string in roman no format (s) your task is to convert it to an integer . Various symbols and their values are given below. I 1 V 5 X 10 L 50 C 100 D 500 M 1000 Example 1: Input: s = V Output: 5 Example 2: Input: s = III Output: 3 Your Task: Complete the function romanToDecimal() which takes an string as input parameter and returns the equivalent decimal number. Expected Time Complexity: O(|S|), |S| = length of string S. Expected Auxiliary Space: O(1) Constraints: 1<=roman no range<=3999 #endif // { Driver Code Starts // Initial template for C++ // Program to convert Roman Numerals to Numbers #include <bits/stdc++.h> using namespace std; // Returns decimal value of roman numaral int romanToDecimal(string &); int main() { int t; cin >> t; while (t--) { string s; cin >> s; cout << romanToDecimal(s) << endl; } }// } Driver Code Ends // User fuunction teemplate for C++ // str given roman number string // Returns decimal value of roman numaral int util(char c) { switch(c) { case 'I' : return 1; break; case 'V' : return 5; break; case 'X' : return 10; break; case 'L' : return 50; break; case 'C' : return 100; break; case 'D' : return 500; break; case 'M' : return 1000; break; } } int romanToDecimal(string &str) { // code here int res = 0; for(int i = 0; i < str.size(); ++i) { int next = -1; if(i != str.size() - 1) next = util(str[i+1]); int curr = util(str[i]); if(next > curr) res -= curr; else res += curr; } return res; }
a9f607d62bdf50c333e53cd73543e5d0e51ccbb1
13771efbe4bd2803f21b75c0edb621a0d68d0f6c
/완전탐색/연산자끼워넣기2_BF_15658.cpp
5d4c0929999ab48ff59144627addae4e5982b4d2
[]
no_license
Flare-k/Algorithm
f6e597bcb376d8c0f50e91556cadf2cceadd786c
64ab13c5304712292c41a26a4347f010d70daf98
refs/heads/master
2023-04-08T21:05:08.130284
2023-04-03T13:57:01
2023-04-03T13:57:01
236,532,243
2
0
null
null
null
null
UTF-8
C++
false
false
995
cpp
#include <iostream> #include <algorithm> #include <vector> using namespace std; int n; int arr[11]; int operate[4]; int sum; int maxAns = -1000000000; int minAns = 1000000000; void go(int sum, int idx, int plus, int minus, int mult, int div) { if (idx >= n) { if (sum > maxAns) maxAns = sum; if (sum < minAns) minAns = sum; return; } if (plus) go(sum+arr[idx], idx+1, plus-1, minus, mult, div); if (minus) go(sum-arr[idx], idx+1, plus, minus-1, mult, div); if (mult) go(sum*arr[idx], idx+1, plus, minus, mult-1, div); if (div) go(sum/arr[idx], idx+1, plus, minus, mult, div-1); } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cin >> n; for (int i = 0; i < n; i++) cin >> arr[i]; for (int i = 0; i < 4; i++) cin >> operate[i]; go(arr[0], 1, operate[0], operate[1], operate[2], operate[3]); cout << maxAns << '\n' << minAns << '\n'; return 0; }
d2bce32ec422f6132db8c3ee66397964e4040b26
4563ac48f177dc65ddcc94ffb0dc8e65bfc260eb
/140-Word-Break-II/solution.cpp
846a14ce23a62a400fd99df84059471fe3ab9d6d
[]
no_license
lanbing510/LeetCode
f435ff1f7e22f0c0eab9cf3c4545502b8aa95407
751efdcecb0ca18ecde22a213b9fa39c01685eac
refs/heads/master
2021-01-21T14:11:35.806452
2016-07-01T02:37:36
2016-07-01T02:37:36
57,301,924
0
5
null
null
null
null
UTF-8
C++
false
false
1,398
cpp
// O(n^2) O(n^2) class Solution { public: // 动规 vector<string> wordBreak(string s, unordered_set<string>& wordDict) { vector<vector<bool> > prev(s.length()+1,vector<bool>(s.length())); vector<bool> f(s.size()+1); f[0]=true; for(int i=1;i<=s.size();++i){ for(int j=0;j<i;++j){ if(f[j]&&wordDict.find(s.substr(j,i-j))!=wordDict.end()){ f[i]=true; prev[i][j]=true;//prev[i][j]为true表示s[j,i)是个合法单词,可以从j切开 } } } vector<string> result; vector<string> path; gen_path(s,prev,s.length(),path,result); return result; } private: // DFS 生成路径 void gen_path(const string &s, const vector<vector<bool> > &prev, int cur, vector<string>& path, vector<string>& result){ if(cur==0){ string tmp; for(auto iter=path.crbegin();iter!=path.crend();++iter){ tmp+=*iter+" "; } tmp.erase(tmp.end()-1); result.push_back(tmp); } for(size_t i=0;i<cur;++i){ if(prev[cur][i]){ path.push_back(s.substr(i,cur-i)); gen_path(s,prev,i,path,result); path.pop_back(); } } } };
4d287112455d9490f4a63c06659d8a5c55729717
3d643e50e304d3ffd3f697905e441556be377cfc
/ios/versioned-react-native/ABI35_0_0/ReactCommon/ABI35_0_0fabric/components/text/paragraph/ABI35_0_0ParagraphProps.h
dbbc9398b953d20c3ea576887e007f5bce1a1a7d
[ "BSD-3-Clause", "MIT", "Apache-2.0" ]
permissive
Qdigital/expo
326c5c1c0167295c173f2388f078a2f1e73835c9
8865a523d754b2332ffb512096da4998c18c9822
refs/heads/master
2023-07-07T18:37:39.814195
2020-02-18T23:28:20
2020-02-18T23:28:20
241,549,344
1
0
MIT
2023-07-06T14:55:15
2020-02-19T06:28:39
null
UTF-8
C++
false
false
1,293
h
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #pragma once #include <limits> #include <memory> #include <ReactABI35_0_0/attributedstring/ParagraphAttributes.h> #include <ReactABI35_0_0/components/text/BaseTextProps.h> #include <ReactABI35_0_0/components/view/ViewProps.h> #include <ReactABI35_0_0/core/Props.h> namespace facebook { namespace ReactABI35_0_0 { /* * Props of <Paragraph> component. * Most of the props are directly stored in composed `ParagraphAttributes` * object. */ class ParagraphProps : public ViewProps, public BaseTextProps { public: ParagraphProps() = default; ParagraphProps(const ParagraphProps &sourceProps, const RawProps &rawProps); #pragma mark - Props /* * Contains all prop values that affect visual representation of the * paragraph. */ const ParagraphAttributes paragraphAttributes{}; /* * Defines can the text be selected (and copied) or not. */ const bool isSelectable{}; #pragma mark - DebugStringConvertible #if RN_DEBUG_STRING_CONVERTIBLE SharedDebugStringConvertibleList getDebugProps() const override; #endif }; } // namespace ReactABI35_0_0 } // namespace facebook
db499103642b2d30d60566df0c5ec1a7389b1501
2c5e22d9511f87cd14aa2ec0d11c2a1c26f17862
/CIQ/linkedList/2.cc
72fec6ed62c1a6e86f830993b95f0d238358f813
[]
no_license
fang0099/Mr.Fundamental
4fa4e290a8e396f761baa25e4a5373cc994c6773
979886ba4a140c0bc412b3f4f0c1be7a08879074
refs/heads/master
2020-06-03T10:00:30.246900
2014-09-08T16:13:41
2014-09-08T16:13:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
442
cc
/* * find last Kth element */ #include "List.h" ListNode* findLastK(ListNode* head, int k) { if(k < 0) throw std::runtime_error("invalid input"); ListNode *p1 = head, *p2 = head; for(int i = 0; i< k; ++i) { if(p1 == NULL) throw std::runtime_error("list is shorter than k"); p1 = p1->next; } while(p1!=NULL) { p1 = p1->next; p2 = p2->next; } return p2; }
707cbe924881c920c6e321b02a5fac264ab600b6
6861ababd3572292d5d718b496f8e20e33cfa1e0
/deps/asio/asio/detail/fd_set_adapter.hpp
9c88fb1e0d35d465d8138b647146c912f3abac05
[ "BSL-1.0" ]
permissive
tscmoo/tsc-bw
e6d973c425147f071102e0bc3d8b930b5292e5c7
a9baf0a7775bdf44fafe2757526245950c6725dc
refs/heads/master
2020-04-05T23:41:36.565984
2017-06-01T10:42:29
2017-06-01T10:42:29
28,708,148
39
4
null
null
null
null
UTF-8
C++
false
false
941
hpp
// // detail/fd_set_adapter.hpp // ~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2016 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // 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 ASIO_DETAIL_FD_SET_ADAPTER_HPP #define ASIO_DETAIL_FD_SET_ADAPTER_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "./config.hpp" #if !defined(ASIO_WINDOWS_RUNTIME) #include "./posix_fd_set_adapter.hpp" #include "./win_fd_set_adapter.hpp" namespace asio { namespace detail { #if defined(ASIO_WINDOWS) || defined(__CYGWIN__) typedef win_fd_set_adapter fd_set_adapter; #else typedef posix_fd_set_adapter fd_set_adapter; #endif } // namespace detail } // namespace asio #endif // !defined(ASIO_WINDOWS_RUNTIME) #endif // ASIO_DETAIL_FD_SET_ADAPTER_HPP
7f89a537858b43bd79327be15968f56bac841b76
d1ba0c42c9c2f6c28ef780e4d080a803d26cddf2
/Test/src/Test/TestCDVScrollbar.h
82bb6082de69d13c1ce4e2ff47facde4a2ccd0c3
[]
no_license
Synodiporos/TestC
3889aebba67fa2de5d98436700ec7e2c70da74bd
ab021cf1370226d7df047b1e967afa55154cbcb5
refs/heads/master
2020-03-16T14:24:21.719390
2018-07-24T21:07:57
2018-07-24T21:07:57
132,715,552
0
0
null
2018-07-02T15:55:53
2018-05-09T07:03:02
C++
UTF-8
C++
false
false
2,180
h
/* * TestCDVScrollbar.h * * Created on: 18 Ιουν 2018 * Author: Synodiporos */ #ifndef TEST_TESTCDVSCROLLBAR_H_ #define TEST_TESTCDVSCROLLBAR_H_ #include <iostream> #include <ctime> using namespace std; #include "../CD/LCDConsole.h" #include "../View/ViewAssets.h" #include <string> class TestCDVScrollbar { public: static void run() { bool res = false; cout << "Test CDVScrollbar!" << endl; LCD* lcd = new LCDConsole(SCREEN_WIDTH, SCREEN_HEIGHT); LCD* lcd2 = new LCDSimulator(SCREEN_WIDTH, SCREEN_HEIGHT); CDFrame frame = CDFrame((int)SCREEN_WIDTH, 2, lcd2); TaskContainer* taskCont = new TaskContainer(TaskLoader::getAvailableTasks()); TaskContainerController* taskContCtrl = TaskContainerFactory::createController(*taskCont); TaskContainerView* taskContView = taskContCtrl->getView(); MainController* mainCtrl = MainFactory::createController(); mainCtrl->setTaskContainerController(taskContCtrl); mainCtrl->setFrame(&frame); mainCtrl->activate(); frame.setPage(mainCtrl->getView()); for(int i=0; i<10; i++){ std::string* name = new std::string("Task_"); *name = *name + std::to_string(i); taskCont->insertTask(new Task(name->c_str(), 1000)); } cout << "View size: " << (int)taskContView->getSize() << endl; cout << "View height: " << (int)taskContView->getHeight() << endl; //frame.print(); mainCtrl->onForwardClicked(); mainCtrl->onForwardClicked(); mainCtrl->onForwardClicked(); // Stats mainCtrl->onForwardClicked(); mainCtrl->onEnterClicked(); cout << "SET POSITION "<<endl; taskContView->setPosition(0, -8); cout << "SET POSITION "<<endl; taskContView->setPosition(0, -0); /* clock_t start = clock(); int i = 1; bool run = false; while ( run && (clock() - start < 10000)) { unsigned long millis = clock() - start; if (millis >= 4000 && i == 1) { cout << "=================" << endl; mainCtrl->onForwardClicked(); i++; } if (millis >= 5000 && i == 2) { i++; } frame.validate(); } */ } }; #endif /* TEST_TESTCDVSCROLLBAR_H_ */
d32a8d1a4372b87e6c932b37ff6e169094c84f19
364e5cd1ce6948183e6ebb38bd8f555511b54495
/DesignPattern/Proxy/ProxyOrder/src/OrderProxy.cpp
5462d2517bb368490857262e494aebe3cd9c8d3e
[]
no_license
danelumax/CPP_study
c38e37f0d2cebe4adccc65ad1064aa338913f044
22124f8d83d59e5b351f16983d638a821197b7ae
refs/heads/master
2021-01-22T21:41:11.867311
2017-03-19T09:01:11
2017-03-19T09:01:11
85,462,945
0
0
null
null
null
null
UTF-8
C++
false
false
1,536
cpp
/* * OrderProxy.cpp * * Created on: Oct 24, 2016 * Author: eliwech */ #include "OrderProxy.h" OrderProxy::OrderProxy(OrderApi* realSubject) : _order(realSubject) { } OrderProxy::~OrderProxy() { } int OrderProxy::getOrderNum() { return _order->getOrderNum(); } std::string OrderProxy::getOrderUser() { return _order->getOrderUser(); } std::string OrderProxy::getProductName() { return _order->getProductName(); } void OrderProxy::setOrderNum(int orderNum, std::string user) { if (user!="" && user == getOrderUser()) { _order->setOrderNum(orderNum, user); } else { std::cout << "Sorry <" << user <<">, you have no permission to change <Order Number> ..." << std::endl; } } void OrderProxy::setOrderUser(std::string orderUser, std::string user) { if (user!="" && user == getOrderUser()) { _order->setOrderUser(orderUser, user); } else { std::cout << "Sorry <" << user <<">, you have no permission to change <Order User> ..." << std::endl; } } void OrderProxy::setProductName(std::string productName, std::string user) { if (user!="" && user == getOrderUser()) { _order->setProductName(productName, user); } else { std::cout << "Sorry <" << user <<">, you have no permission to change <Product Name> ..." << std::endl; } } void OrderProxy::toString() { std::cout << "ProductName: " << getProductName() << ", OrderNum: " << getOrderNum() << ", OrderUser: " << getOrderUser() << std::endl; }
eeeabd52b846cded453f71adfa42b355dad59fd3
e4567a3ff64601ba050bb78d1b365b611161ffde
/day04/04_TCP/clientwidget.cpp
ca31d9e0483329e12cc863ba6d7fa35197350318
[]
no_license
MisakiFx/QtCode
383afdb2c09f9c15edb23e44033b4c5e6a7f410d
bc81276599c6c8b39cd4ada40e5bfb3facef1e64
refs/heads/master
2020-07-09T18:26:16.630194
2020-03-19T13:52:03
2020-03-19T13:52:03
204,047,505
0
0
null
null
null
null
UTF-8
C++
false
false
1,380
cpp
#include "clientwidget.h" #include "ui_clientwidget.h" #include <QHostAddress> ClientWidget::ClientWidget(QWidget *parent) : QWidget(parent), ui(new Ui::ClientWidget), tcpSocket(nullptr) { ui->setupUi(this); tcpSocket = new QTcpSocket(this); connect(tcpSocket, &QTcpSocket::connected, [=]() { ui->textEditRead->setText("成功和服务器建立好连接"); } ); connect(tcpSocket, &QTcpSocket::readyRead, [=]() { //获取对方发送的内容 QByteArray array = tcpSocket->readAll(); ui->textEditRead->append(array); } ); } ClientWidget::~ClientWidget() { delete ui; } void ClientWidget::on_buttonConnect_clicked() { //获取服务器ip和端口 QString ip = ui->lineEditIp->text(); quint16 port = ui->lineEditPort->text().toInt(); //主动和服务器建立连接 tcpSocket->connectToHost(QHostAddress(ip), port); } void ClientWidget::on_buttonSend_clicked() { if(tcpSocket->state() != 3) { return; } QString str = ui->textEditWrite->toPlainText(); tcpSocket->write(str.toUtf8().data()); ui->textEditWrite->clear(); } void ClientWidget::on_buttonClose_clicked() { tcpSocket->disconnectFromHost(); tcpSocket->close(); }
be71995224633b76184abb2dbd98e4e3d63a67f4
cbee63d796a4fddc20fa844d05e14cad10def961
/GxNetwork/Src/Network/NetworkRemoteEngine.cpp
330fa43767af3f48e7d2b7e9f66b45da042dc086
[]
no_license
Gletschr/GxNetwork
df179528894747b5766af12e747ab54144f0095d
1b48d0c621358d34c05efb714330276676ef1e7e
refs/heads/master
2020-04-08T22:23:54.896484
2018-11-30T07:33:55
2018-11-30T07:33:55
159,785,663
0
0
null
null
null
null
UTF-8
C++
false
false
332
cpp
#include "../../Include/Network/NetworkRemoteEngine.h" namespace gx { namespace network { FRemoteEngine::FRemoteEngine(const FGuid& GUID) : _GUID(GUID) { } FRemoteEngine::~FRemoteEngine() { } const FGuid& FRemoteEngine::GetGUID() const { return _GUID; } FBuffer& FRemoteEngine::GetEventsFrame() { return _eventsFrame; } } }
a5e7fe7b01503f9539a318e23a7591d953a4d6a1
d7db098f4b1d1cd7d32952ebde8106e1f297252e
/AOJ/NTL_1_C.cpp
645b25abe1e8bf224014a86ab2d4d0cca07706e1
[]
no_license
monman53/online_judge
d1d3ce50f5a8a3364a259a78bb89980ce05b9419
dec972d2b2b3922227d9eecaad607f1d9cc94434
refs/heads/master
2021-01-16T18:36:27.455888
2019-05-26T14:03:14
2019-05-26T14:03:14
25,679,069
0
0
null
null
null
null
UTF-8
C++
false
false
690
cpp
// header {{{ #include <bits/stdc++.h> using namespace std; // {U}{INT,LONG,LLONG}_{MAX,MIN} #define ALPHABET (26) #define INF INT_MAX #define MOD (1000000007LL) #define EPS (1e-10) #define EQ(a, b) (abs((a)-(b)) < EPS) using LL = long long; int di[] = {0, -1, 0, 1}; int dj[] = {1, 0, -1, 0}; // }}} // 最大公約数 LL gcd(LL x, LL y) { return y ? gcd(y, x%y) : x; } // 最小公倍数 LL lcm(LL m, LL n) { return m/gcd(m, n)*n; } int main() { std::ios::sync_with_stdio(false); int n;cin >> n; LL ans = 1; for(int i=0;i<n;i++){ LL a;cin >> a; ans = lcm(ans, a); } cout << ans << endl; return 0; }
b874b99b170038fb7c4934b4ec8d58cac0030499
85e7114ea63a080c1b9b0579e66c7a2d126cffec
/SDK/SoT_wsp_sea_rock_cluster_d_functions.cpp
36105b18cfb277044e7d39115513f25dff665599
[]
no_license
EO-Zanzo/SeaOfThieves-Hack
97094307d943c2b8e2af071ba777a000cf1369c2
d8e2a77b1553154e1d911a3e0c4e68ff1c02ee51
refs/heads/master
2020-04-02T14:18:24.844616
2018-10-24T15:02:43
2018-10-24T15:02:43
154,519,316
0
2
null
null
null
null
UTF-8
C++
false
false
802
cpp
// Sea of Thieves (1.2.6) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "SoT_wsp_sea_rock_cluster_d_parameters.hpp" namespace SDK { //--------------------------------------------------------------------------- //Functions //--------------------------------------------------------------------------- // Function wsp_sea_rock_cluster_d.wsp_sea_rock_cluster_d_C.UserConstructionScript // (Event, Public, BlueprintCallable, BlueprintEvent) void Awsp_sea_rock_cluster_d_C::UserConstructionScript() { static auto fn = UObject::FindObject<UFunction>("Function wsp_sea_rock_cluster_d.wsp_sea_rock_cluster_d_C.UserConstructionScript"); Awsp_sea_rock_cluster_d_C_UserConstructionScript_Params params; UObject::ProcessEvent(fn, &params); } } #ifdef _MSC_VER #pragma pack(pop) #endif
7c6b6fb664d54173f5c64d0d0a19dbd8ad0b5e60
82192f5803998708fb9f820172d4f5264f5daefe
/NewGoBang2/NewGoBangTalkSer/socket_lib/tcplisten.cpp
6a912e63710f8091f1d035eda451329e66b5933a
[]
no_license
a624762529/NewGoBang
f73fe3c41be42491eba48c36b6b6348b071de089
4e778e7d327f04fa7f7a9774fdb36deaba3cd1c3
refs/heads/master
2023-04-12T19:40:48.624576
2021-05-09T11:48:55
2021-05-09T11:48:55
262,213,454
4
0
null
null
null
null
UTF-8
C++
false
false
1,723
cpp
#include "tcplisten.h" TcpListen::TcpListen(int port) { m_magic=CanUse; struct sockaddr_in serv_addr; socklen_t serv_len = sizeof(serv_addr); // 创建套接字 lfd = socket(AF_INET, SOCK_STREAM, 0); // 初始化服务器 sockaddr_in memset(&serv_addr, 0, serv_len); serv_addr.sin_family = AF_INET; // 地址族 serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); // 监听本机所有的IP serv_addr.sin_port = htons(port); // 设置端口 // 绑定IP和端口 bind(lfd, (struct sockaddr*)&serv_addr, serv_len); // 设置同时监听的最大个数 listen(lfd, 2000); //设置监听文件描述符为非阻塞 int flag=fcntl(lfd,F_GETFL,0); fcntl(lfd,F_SETFL,flag|O_NONBLOCK); } pair<int,sockaddr_in> TcpListen::acceptConnect() { sockaddr_in client; socklen_t len=sizeof(client); int cfd=accept(lfd,(sockaddr*)(&client),&len); pair<int,sockaddr_in> ret; ret.first=-1; if(cfd==-1) { if(errno==EWOULDBLOCK||errno==ECONNABORTED ||errno==EPROTO||errno==EINTR) { return ret; } else { cout<<"accept err"<<endl; perror("accept err"); throw bad_alloc(); } } ret.first=cfd; ret.second=client; // char ipbuf[64] = {0}; // printf("client IP: %s, port: %d\n", // inet_ntop(AF_INET, &client.sin_addr.s_addr, ipbuf, sizeof(ipbuf)), // ntohs(client.sin_port)); return ret; } void TcpListen::destory() { m_magic=-1; close(lfd); memset(&ser,0,sizeof(ser)); } TcpListen::~TcpListen() { } int TcpListen::getFd() { return lfd; }
d0722ded87b90d13e2c72561d519183604c408cd
b5ec2a2253fb46337901df859cefce736f752656
/src/stock/CoGet.hxx
4c86c580b8d8ab41ed2add12ccd1f7ba17bc6988
[]
no_license
August2111/libcommon
bf55a16976db74f0d8534bd4b44a59aca4dfad96
f79e3c4c2eaa395de6c29945c6fa9b76fb6a2a0b
refs/heads/master
2023-04-17T05:41:00.093627
2021-05-21T13:25:45
2021-05-21T13:25:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,884
hxx
/* * Copyright 2007-2021 CM4all GmbH * All rights reserved. * * author: Max Kellermann <[email protected]> * * 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 * FOUNDATION 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. */ #pragma once #include "Stock.hxx" #include "GetHandler.hxx" #include "co/Compat.hxx" /** * Coroutine wrapper for Stock::Get(). */ class CoStockGet final : public StockGetHandler { CancellablePointer cancel_ptr{nullptr}; StockItem *item = nullptr; std::exception_ptr error; std::coroutine_handle<> continuation; public: CoStockGet(Stock &stock, StockRequest request) noexcept { stock.Get(std::move(request), *this, cancel_ptr); } ~CoStockGet() noexcept { if (cancel_ptr) cancel_ptr.Cancel(); else if (item != nullptr) item->Put(false); } auto operator co_await() noexcept { struct Awaitable final { CoStockGet &get; bool await_ready() const noexcept { return get.item != nullptr || get.error; } std::coroutine_handle<> await_suspend(std::coroutine_handle<> _continuation) const noexcept { get.continuation = _continuation; return std::noop_coroutine(); } StockItem *await_resume() { if (get.error) std::rethrow_exception(get.error); return std::exchange(get.item, nullptr); } }; return Awaitable{*this}; } private: /* virtual methods from StockGetHandler */ void OnStockItemReady(StockItem &_item) noexcept override { cancel_ptr = nullptr; item = &_item; if (continuation) continuation.resume(); } void OnStockItemError(std::exception_ptr ep) noexcept override { cancel_ptr = nullptr; error = std::move(ep); if (continuation) continuation.resume(); } };
23f6d40dfa0123abe523f7e355e66cfcd687854f
97729ab4eae7a0d1812ded8727d8c05b300aba44
/Dijkstra.cpp
4983be7204e77744b70ff40db89004e733e0107c
[]
no_license
GottBott/GraphFriendFinder
803a8a057e1113539e8b7b570b090843f963da14
390a5dd03eff2fcf19ed7524a00011bb1739cad0
refs/heads/master
2020-03-27T02:33:03.893912
2018-08-23T04:03:08
2018-08-23T04:03:08
145,797,978
0
0
null
null
null
null
UTF-8
C++
false
false
3,082
cpp
#include "Network.h" #include "Dijkstra.h" #include <iostream> #include <fstream> #include <iomanip> #include <cmath> #include <algorithm> #include <vector> #include <limits> using namespace std; using std::cout; using std::cerr; using std::ifstream; using std::endl; using std::vector; using std::numeric_limits; /** * Finds all of the shortest paths from source to each other User in the * Network. Stores the dist, prior vertex in path as properties on the User class. * The User class also has a property to store a pointer to a Container * (the heap node) that represents that User. */ void dijkstra_getShortestPaths(Network *net, User *source, bool printOutput) { // create heap MinBinaryHeap heap; double inf = numeric_limits<double>::infinity(); //added every node to the heap and set the source node distance to 0 for (vector<User*>::iterator iter = net->vertices.begin();iter != net->vertices.end(); iter++) { User* v = *iter; v->dist = inf; v->heapNode = heap.insert(v); } source->dist=0; heap.decreaseKey(source->heapNode); //while the heap is not empty delete the min while(heap.isEmpty() != true){ User* u = (User*)heap.deleteMin(); //loop over all of the mins friends for(int i = 0; i<u->links.size();i++){ User* frnd = u->links[i]->target; //update the distance if necessary if(frnd->dist > u->links[i]->weight + u->dist){ frnd->dist = u->links[i]->weight + u->dist; frnd->prior = u; heap.decreaseKey(frnd->heapNode); } } } } LinkedList bfs(Network *net, User *source, bool printOutput) { // create queue and a output list LinkedList queue; LinkedList visited; //enqueueing the source queue.enqueue(source); //Repeat until the queue is empty while(queue.size()>0){ // dequeue the first element in the queue User* u = (User*)queue.dequeue(); if(printOutput ==true){ cout<<endl; cout<<u->firstname<<" was dequeued and added to bfs results "<<endl; } // add it to the visited list visited.enqueue(u); if(printOutput ==true) cout<<"visited list size = "<<visited.size()<<" queue size = "<<queue.size()<<endl; // visit all of the recently dequeued's friends to the back of the queue; for(int j = 0; j<u->links.size();j++){ User* s = u->links[j]->target; bool add =true; //dont add if already in result for(int k=0; k<visited.size();k++){ User* t = (User*)visited.get(k); int x = t->id; if(s->id == x){ add = false; } } //Don't add if already in queue for(int k=0; k<queue.size();k++){ User* t = (User*)queue.get(k); int x = t->id; if(s->id == x){ add = false; } } //add to queue if conditions are met if(add == true){ queue.enqueue(s); if(printOutput ==true) cout<<"added to queue "<<u->firstname<<"'S friend "<< s->firstname<<endl; } // else{ // if(printOutput ==true) // cout<<"did not add to queue "<< s->firstname<<endl; // } } } return visited; // TODO: complete the implementation }
bb38b8bbf680f08e3d7407695787c3f04ae40513
cd06a8aa7469d8f4e79ba48a12c40ca42b84cae7
/beepTest/beepTest.ino
e40565864b3d62d7c29ba3d3c29057220ad9f290
[]
no_license
pfory/central-heating
bb550ef1eecc8e91854cad9768e3ef1bd7a6f540
b24680e020d6cb24faefbdd7361f752e57b6277d
refs/heads/master
2020-05-21T12:44:07.741615
2020-03-22T17:13:22
2020-03-22T17:13:22
45,404,685
0
0
null
null
null
null
UTF-8
C++
false
false
1,042
ino
#include "beep.h" const byte pin=13; byte volume=255; int beepLength=100; int pauseLength=100; byte count=1; Beep beep(pin); void setup() { Serial.begin(9600); beep.Delay(beepLength, pauseLength, count, volume); } void loop() { beep.loop(); if (Serial.available() > 0) { byte incomingByte = Serial.read(); if (incomingByte==97) { //a volume+=10; } else if (incomingByte==115) { //s volume-=10; } else if (incomingByte==119) { //w beepLength+=10; } else if (incomingByte==122) { //z beepLength-=10; } else if (incomingByte==43) { //+ pauseLength+=10; } else if (incomingByte==45) { //- pauseLength-=10; } else if (incomingByte==114) { //repeat } else { count = incomingByte-48; } beep.noDelay(beepLength, pauseLength, count, volume); Serial.print(beepLength); Serial.print(","); Serial.print(pauseLength); Serial.print(","); Serial.print(count); Serial.print(","); Serial.println(volume); } //delay(5000); }
966ae9be73a7eaa02641d98a87f968ff5f977989
96c5ab5658521e8737d37f6c21ba39714422d932
/Differenciator/main.cpp
6f8fcdd05090d4e026ae271bc71ee051ffe7d950
[]
no_license
dashapavlova12/1sem
9de4cb9a0f398a0903647a52028f019e5992549c
1d49608f7e3564525a5940be9fa102af07a06fd9
refs/heads/master
2020-04-07T22:10:01.725971
2018-12-20T10:25:33
2018-12-20T10:25:33
158,757,899
0
0
null
null
null
null
UTF-8
C++
false
false
530
cpp
#include "diff.h" int main() { int input = open(way_to_in, O_RDONLY|O_BINARY); assert(input >= 0); Tree* in_tree = Tree_construct(); in_tree = read_expression(input); assert(in_tree != NULL); print_expression(in_tree); Tree* out_tree = Tree_construct(); out_tree = differenciation(in_tree); assert(out_tree != NULL); printf("\n"); print_expression(out_tree); printf("\n"); to_be_simple(out_tree); print_expression(out_tree); Tree_distruct(&in_tree); return 0; }
46bdd32d2b418eead3a51f711fe451e2e7127cec
aee58e2c2e1834c6dea645a2d34afd2e0107579a
/JSParser/FunctionDecl.h
d343f29a3aec92d011163b78175741af385957ed
[]
no_license
AwesomeTextEdtor/JSParser
86ca18cc3aca473d97b4e0b3e34d74d0fad0a55f
2f642c09376d6fce447ac68cc4aec22bff250bfb
refs/heads/master
2022-02-24T13:06:56.713909
2019-03-28T09:03:52
2019-03-28T09:03:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,131
h
#pragma once #include<vector> #include "Decl.h" #include"Identifier.h" #include"BlockStmt.h" class FunctionDecl :public Decl { protected: vector<Identifier*> params; BlockStmt* body; public: FunctionDecl(Identifier* id,NodeType t=FunctionDecl_t):Node(t),Decl(id){ setValue("Function Declaration"); } void appendParam(Identifier* a) { params.push_back(a); } void appendBody(BlockStmt* b) { body = b; } void display(int layer=1) { cout << setw(layer * 2) << " " << "[FunctionDeclaration]:" << endl; Node::display(layer); cout << setw(layer * 2 + 2) << " " << "id:" << endl; id->display(layer+2); cout << setw(layer * 2 + 2) << " " << "params[" <<params.size()<<"]:"<< endl; if (params.size()) { for (int i = 0; i < params.size(); i++) { params[i]->display(layer + 2); } } else { cout << setw(layer * 2 + 4) << " " << "null" << endl; } cout << setw(layer * 2 + 2) << " " << "body:" << endl; if (body) { body->display(layer+2); } else { cout << setw(layer * 2 + 4) << " " << "null" << endl; } } void execute() { Decl::execute(); body->execute(); } };
84c396d0eca230f309954070030766e96f5e53f4
93b24e6296dade8306b88395648377e1b2a7bc8c
/client/boost/boost/mpl/set/set0_c.hpp
cfdaef116ac4ee13b89aafb5fe9ab4fe7dcfc250
[]
no_license
dahahua/pap_wclinet
79c5ac068cd93cbacca5b3d0b92e6c9cba11a893
d0cde48be4d63df4c4072d4fde2e3ded28c5040f
refs/heads/master
2022-01-19T21:41:22.000190
2013-10-12T04:27:59
2013-10-12T04:27:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
791
hpp
#ifndef BOOST_MPL_SET_SET0_C_HPP_INCLUDED #define BOOST_MPL_SET_SET0_C_HPP_INCLUDED // Copyright Aleksey Gurtovoy 2003-2004 // Copyright David Abrahams 2003-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) // // See http://www.boost.org/libs/mpl for documentation. // $Source: /CVSROOT/boost/boost/mpl/set/set0_c.hpp,v $ // $Date: 2007/10/29 07:32:42 $ // $Revision: 1.1.1.1 $ #include <boost/mpl/set/set0.hpp> #include <boost/mpl/integral_c.hpp> namespace boost { namespace mpl { template< typename T > struct set0_c : set0<> { typedef set0_c type; typedef T value_type; }; }} #endif // BOOST_MPL_SET_SET0_C_HPP_INCLUDED
14a0c22496575930013dc1b3fe5605d41478b675
f9fe33be8d046538593398282231b379449213f5
/Solutions/18.6/Lib/Edit.h
46da2e03bdeb27a3f741a9d1fea65ac17b261eac
[]
no_license
liuxinbo1984/cplus-in-action
d777a09523439d66fd2cd941694370724b77b163
1087742fdf6528bc7e810db351492034b24c4dbb
refs/heads/master
2021-04-23T21:20:55.827607
2020-03-25T16:32:10
2020-03-25T16:32:10
250,007,524
0
0
null
null
null
null
UTF-8
C++
false
false
1,851
h
#if !defined (EDIT_H) #define EDIT_H // (c) Bartosz Milewski 2000 #include "controls.h" #include <string> namespace Win { class StaticText: public SimpleCtrl { public: StaticText (HWND winParent, int id) : SimpleCtrl (winParent, id) {} }; class EditReadOnly: public SimpleCtrl { public: EditReadOnly (HWND winParent, int id) : SimpleCtrl (winParent, id) {} void Select (int offStart, int offEnd) { SendMsg (EM_SETSEL, (WPARAM) offStart, (LPARAM) offEnd); } }; class Edit: public SimpleCtrl { public: Edit (HWND winParent, int id) : SimpleCtrl (winParent, id) {} Edit (HWND win = 0) : SimpleCtrl (win) {} void Append (char const * buf); void Select (int offStart, int offEnd) { SendMsg (EM_SETSEL, (WPARAM) offStart, (LPARAM) offEnd); } void SetReadonly (bool flag) { SendMsg (EM_SETREADONLY, (WPARAM) (flag ? TRUE : FALSE), 0); } // code is the HIWORD (wParam) static bool IsChanged (int code) { return code == EN_CHANGE; } int GetLen () const { return SendMsg (WM_GETTEXTLENGTH); } int GetLineCount () { return SendMsg (EM_GETLINECOUNT); } void GetText (char * buf, int len) const { SendMsg (WM_GETTEXT, (WPARAM) len, (LPARAM) buf); } std::string GetText () const; void Select () { SendMsg (EM_SETSEL, 0, -1); } void SelectLine (int lineIdx); void ReplaceSelection (char const * info) { SendMsg (EM_REPLACESEL, 0, reinterpret_cast<LPARAM>(info)); } void Clear (); }; class EditMaker: public ControlMaker { public: EditMaker (HWND winParent, int id) : ControlMaker ("EDIT", winParent, id) {} void MakeReadOnly () { _style |= ES_READONLY; } void WantReturn () { _style |= ES_WANTRETURN; } }; } #endif
22ac8dd7e7b2ae2f76134747a343cd5f5b7bdee0
c4e41f7dac8934fb008887c128697f9ea4236b2b
/win/nxt-tools/nxtOSEK/ecrobot/c++/util/New.cpp
2e438eb3c6ce2bb5e7039d0f102b0cd27723dfb4
[]
no_license
qreal/nxt-tools
ecc408f33757ed276d61d854f14e207d562871c0
5cb78f437990ea7ffecc6412d097c4d1038055e7
refs/heads/master
2021-01-10T19:33:00.165167
2018-10-23T15:09:56
2018-10-23T15:09:56
26,807,179
1
2
null
2020-10-28T21:11:07
2014-11-18T11:58:37
C++
UTF-8
C++
false
false
1,429
cpp
// // New.cpp // // Simple new/delete overload to reduce the memory consumption. // Note that there is NO exception handling and NOT thread safe. // // Copyright 2009 by Takashi Chikamasa, Jon C. Martin and Robert W. Kramer // #include <stdlib.h> //============================================================================= // new operators overload // // normal single new void* operator new(size_t size) throw() { if (size < 1) { size = 1; // size 0 is set as size 1 } return malloc(size); } // normal array new void* operator new [](size_t size) throw() { if (size < 1) { size = 1; // size 0 is set as size 1 } return malloc(size); } // default placement version of single new void* operator new(size_t, void* ptr) throw() { return ptr; } // default placement version of array new void* operator new [](size_t, void* ptr) throw() { return ptr; } //============================================================================= // delete operators overload // // normal single delete void operator delete(void* ptr) throw() { free(ptr); } // normal array delete void operator delete [](void* ptr) throw() { free(ptr); } // default placement version of single delete void operator delete(void*, void*) throw() { /* do nothing */ } // default placement version of array delete void operator delete [](void*, void*) throw() { /* do nothing */ }
ee4443ea50a7cd47983c63f4227aa37433b877be
5853b26c6abeaae30183b68d81e3f18a9b76901b
/solved/LightOJ/1069 - Lift/solution.cpp
1d93b90f6320686a0a147e43a83a1c0d1e2c315a
[]
no_license
mdfaridmiah/competitive-programming
c18c04cb89c0d66819db35cf9534c3d1a0960b31
2c94a375e71ccacd316550b4c58080253549fbee
refs/heads/master
2023-03-02T07:29:52.850660
2021-02-11T03:38:16
2021-02-11T03:38:16
336,281,254
0
0
null
null
null
null
UTF-8
C++
false
false
468
cpp
#include<stdio.h> #include<iostream> #include<string.h> #include<math.h> #include<algorithm> using namespace std; char nm[10005]; long long ar[1000005]; int main() { long long a,b,tk,i,c=0,mx,len,res; scanf("%lld",&tk); while(tk--) { res=0; c++; scanf("%lld%lld",&a,&b); if(a>b) mx=a-b; else mx=b-a; res=9+10+(mx*4)+(4*a); printf("Case %lld: %lld\n",c,res); } return 0; }
fffabd9b4e3fdace147c826e15ebf25a3ae5c71a
a4d5ab8b22d2f76dae1e5af4581d4c579d93ef60
/paquete.hpp
ccb73c4684ba26ba410672180e9eda7083616095
[]
no_license
Xabras123/EDD
038c74ad23626dc639a7b8c98e3f13cb46535b7f
90dd98ca46cc0cb631e9dc80e8bc3e37536b89d6
refs/heads/master
2021-01-24T16:19:22.254852
2018-02-27T16:52:26
2018-02-27T16:52:26
123,183,071
0
0
null
2018-02-27T20:17:44
2018-02-27T20:17:43
null
UTF-8
C++
false
false
844
hpp
#ifndef __PAQUETE__HPP__ #define __PAQUETE__HPP__ #include <iostream> #include "paquete.h" #include <string> #include <list> #include "Persona.h" using namespace std; void Paquete::setRemitente(Persona remitenteIn){ remitente = remitenteIn; } void Paquete::setDestinatario(Persona destinatarioIn){ destinatario = destinatarioIn; } void Paquete::setPeso(int pesoIn){ peso = pesoIn; } void Paquete::setTipo(string tipoIn){ tipo = tipoIn; } void Paquete::setNumGuia(string numGuiaIn){ numGuia = numGuiaIn; } Persona Paquete::getRemitente( ){ return remitente; } Persona Paquete::getDestinatario( ){ return destinatario; } int Paquete::getPeso( ){ return peso; } string Paquete::getTipo( ){ return tipo; } string Paquete::getNumGuia(){ return numGuia; } #endif
50d65230b2e8a9571de24162c2367d6d0f26368f
d2c0ac9b68c5e68664d6dc645ece52398c58fbcd
/FlightStrip-Config-Tool/FlightStrip Config Tool/Compiled Program V0.2/data/FlightStrip.cpp
64bca598df70c0a31e20fcd78f3dc572ad5789c9
[]
no_license
MorS25/FlightStrip
00b2dca1916167333f76f2c9c92f77afca08216e
8644050f90a1bf29797e86df5bcc06be33ba6a00
refs/heads/master
2021-01-18T04:09:25.260703
2015-04-26T13:57:32
2015-04-26T13:57:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
21,926
cpp
/* FlightStrip.cpp - Library for WS2812 LED Strip Management. Version 0.7 (15.03.2015) This Code is published by Yannik Wertz under the "Creativ Common Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0)" License For more Information see : http://creativecommons.org/licenses/by-nc-sa/4.0/ */ #include "Arduino.h" #include "FlightStrip.h" FlightStrip::FlightStrip(Adafruit_NeoPixel &stripToUse, uint16_t startLed, uint16_t endLed) { randomSeed(analogRead(A0)); strip = &stripToUse; lowerBound = startLed; origLowerBound = startLed; upperBound = endLed; origUpperBound = endLed; lastTimeUpdated = 0; mode = 0; counter = 0; number = 0; up = true; reversed = false; disabled = false; //Effekt Stadardwerte constColor_color = 16711680; //Rot constTripleColor_color[0] = 16711680; //Rot constTripleColor_color[1] = 65280; //Grün constTripleColor_color[2] = 255; //Blau constTripleColor_interval = 200; //200ms chaseSingleColor_color = 16711680; //Rot chaseSingleColor_interval = 50; //50ms chaseTripleColor_color[0] = 16711680; //Rot chaseTripleColor_color[1] = 65280; //Grün chaseTripleColor_color[2] = 255; //Blau chaseTripleColor_interval = 50; //50ms fillTripleColor_color[0] = 16711680; //Rot fillTripleColor_color[1] = 65280; //Grün fillTripleColor_color[2] = 255; //Blau fillTripleColor_interval = 50; //50ms blinkColor_color = 16777215; //Weiß blinkColor_onTime = 50; //50ms blinkColor_offTime = 150; //150ms doubleflash_color = 16777215; //Weiß doubleflash_longOff = false; fillAgainst_color[0] = 16711680; //Rot fillAgainst_color[1] = 65280; //Grün fillAgainst_interval = 50; //50ms theaterChase_color = 16747520; //Orange theaterChase_interval = 50; //50ms knightrider_color = 16711680; //Rot knightrider_background_color = 0; //Aus knightrider_interval = 70; //70ms knightrider_width = 3; //3 LEDs Breite thunderstorm_color = 16777215; //Weiß thunderstorm_interval = 40; //40ms policeRight_interval = 40; //40ms policeLeft_interval = 350; //250ms rainbow_interval = 5; //5ms blockswitch_color[0] = 16711680; //Rot blockswitch_color[1] = 65280; //Grün blockswitch_width = 5; //Pro Block 5 LEDs Breite blockswitch_interval = 150; //150ms randomflash_interval = 25; //25ms } void FlightStrip::learnMode(uint8_t modeNumber, uint8_t effectNumber) { modes[modeNumber] = effectNumber; } void FlightStrip::setMode(uint8_t actMode) { mode = actMode; //Originale Grenzen setzten lowerBound = origLowerBound; upperBound = origUpperBound; //Zurücksetzten aller Counter-Variablen if(!reversed) counter = 0; else counter = (upperBound - lowerBound); up = true; number = 0; disabled = false; for(int i = lowerBound ; i <= upperBound ; i++) //Alle LEDs ausschalten (*strip).setPixelColor(i, 0, 0, 0); } void FlightStrip::update() { if(!disabled) { actTime = millis(); switch(modes[mode]) { case CONST_COLOR: if((actTime - lastTimeUpdated) > 125) { lastTimeUpdated = actTime; constColor(); } break; case CONST_TRIPLE_COLOR: if((actTime - lastTimeUpdated) > constTripleColor_interval) { lastTimeUpdated = actTime; constTripleColor(); } break; case CHASE_SINGLE_COLOR: if((actTime - lastTimeUpdated) > chaseSingleColor_interval) { lastTimeUpdated = actTime; chaseSingleColor(); } break; case CHASE_TRIPLE_COLOR: if((actTime - lastTimeUpdated) > chaseTripleColor_interval) { lastTimeUpdated = actTime; chaseTripleColor(); } break; case FILL_TRIPLE_COLOR: if((actTime - lastTimeUpdated) > fillTripleColor_interval) { lastTimeUpdated = actTime; fillTripleColor(); } break; case BLINK_COLOR: if(up) //up = true bedeutet Off Zustand! { if((actTime - lastTimeUpdated) > blinkColor_offTime) { lastTimeUpdated = actTime; blinkColor(); } } else //On Zustand { if((actTime - lastTimeUpdated) > blinkColor_onTime) { lastTimeUpdated = actTime; blinkColor(); } } break; case DOUBLEFLASH: if(up) //up = true bedeutet Off Zustand! { if(doubleflash_longOff) { if((actTime - lastTimeUpdated) > 500) { lastTimeUpdated = actTime; doubleflash_longOff = false; doubleflash(); } } else { if((actTime - lastTimeUpdated) > 120) { lastTimeUpdated = actTime; doubleflash_longOff = true; doubleflash(); } } } else //On Zustand { if((actTime - lastTimeUpdated) > 60) { lastTimeUpdated = actTime; doubleflash(); } } break; case FILL_AGAINST: if((actTime - lastTimeUpdated) > fillAgainst_interval) { lastTimeUpdated = actTime; fillAgainst(); } break; case THEATER_CHASE: if((actTime - lastTimeUpdated) > theaterChase_interval) { lastTimeUpdated = actTime; theaterChase(); } break; case KNIGHTRIDER: if((actTime - lastTimeUpdated) > knightrider_interval) { lastTimeUpdated = actTime; knightrider(); } break; case THUNDERSTORM: if((actTime - lastTimeUpdated) > thunderstorm_interval) { lastTimeUpdated = actTime; thunderstorm(); } break; case POLICE_RIGHT: if((actTime - lastTimeUpdated) > policeRight_interval) { lastTimeUpdated = actTime; policeRight(); } break; case POLICE_LEFT: if((actTime - lastTimeUpdated) > policeLeft_interval) { lastTimeUpdated = actTime; policeLeft(); } break; case RAINBOW: if((actTime - lastTimeUpdated) > rainbow_interval) { lastTimeUpdated = actTime; rainbow(); } break; case BLOCKSWITCH: if((actTime - lastTimeUpdated) > blockswitch_interval) { lastTimeUpdated = actTime; blockswitch(); } break; case RANDOMFLASH: if((actTime - lastTimeUpdated) > blockswitch_interval) { lastTimeUpdated = actTime; randomflash(); } break; }//switch(mode) }//if(!disabled) } void FlightStrip::updateParameter(uint8_t effectNumber, uint32_t color1, uint32_t color2, uint32_t color3, uint16_t interval) { switch(effectNumber) { case CONST_COLOR: if(color1 != 0) constColor_color = color1; break; case CONST_TRIPLE_COLOR: if(color1 != 0) constTripleColor_color[0] = color1; if(color2 != 0) constTripleColor_color[1] = color2; if(color3 != 0) constTripleColor_color[2] = color3; if(interval != 0) constTripleColor_interval = interval; break; case CHASE_SINGLE_COLOR: if(color1 != 0) chaseSingleColor_color = color1; if(interval != 0) chaseSingleColor_interval = interval; break; case CHASE_TRIPLE_COLOR: if(color1 != 0) chaseTripleColor_color[0] = color1; if(color2 != 0) chaseTripleColor_color[1] = color2; if(color3 != 0) chaseTripleColor_color[2] = color3; if(interval != 0) chaseTripleColor_interval = interval; break; case FILL_TRIPLE_COLOR: if(color1 != 0) fillTripleColor_color[0] = color1; if(color2 != 0) fillTripleColor_color[1] = color2; if(color3 != 0) fillTripleColor_color[2] = color3; if(interval != 0) fillTripleColor_interval = interval; break; case BLINK_COLOR: if(color1 != 0) blinkColor_color = color1; if(color2 != 0) blinkColor_onTime = color2; if(color3 != 0) blinkColor_offTime = color3; break; case DOUBLEFLASH: if(color1 != 0) doubleflash_color = color1; break; case FILL_AGAINST: if(color1 != 0) fillAgainst_color[0] = color1; if(color2 != 0) fillAgainst_color[1] = color2; if(interval != 0) fillAgainst_interval = interval; break; case THEATER_CHASE: if(color1 != 0) theaterChase_color = color1; if(interval != 0) theaterChase_interval = interval; break; case KNIGHTRIDER: if(color1 != 0) knightrider_color = color1; if(color2 != 0) knightrider_background_color = color2; if(color3 != 0) knightrider_width = color3; if(interval != 0) knightrider_interval = interval; break; case THUNDERSTORM: if(color1 != 0) thunderstorm_color = color1; break; case POLICE_RIGHT: break; case POLICE_LEFT: break; case RAINBOW: if(interval != 0) rainbow_interval = interval; break; case BLOCKSWITCH: if(color1 != 0) blockswitch_color[0] = color1; if(color2 != 0) blockswitch_color[1] = color2; if(color3 != 0) blockswitch_width = color3; if(interval != 0) blockswitch_interval = interval; break; case RANDOMFLASH: if(interval != 0) randomflash_interval = interval; break; } } void FlightStrip::reverse() { reversed = !reversed; if(!reversed) counter = 0; else counter = (upperBound - lowerBound); } void FlightStrip::setBounds(uint16_t startLed, uint16_t endLed) { lowerBound = startLed; upperBound = endLed; } void FlightStrip::disable() { disabled = true; } void FlightStrip::constColor() { for(int i = lowerBound ; i <= upperBound ; i++) (*strip).setPixelColor(i, constColor_color); } void FlightStrip::constTripleColor() { for(int i = lowerBound ; i <= upperBound ; i++) (*strip).setPixelColor(i, constTripleColor_color[number]); if(number < 2) number++; else number = 0; } void FlightStrip::chaseSingleColor() { if(up) (*strip).setPixelColor((counter + lowerBound), chaseSingleColor_color); else (*strip).setPixelColor((counter + lowerBound), 0, 0, 0); if(!reversed) { if((counter + lowerBound) < upperBound && up) counter++; else if((counter + lowerBound) == upperBound && up) up = false; else if(counter > 0 && !up) counter--; else if(counter == 0 && !up) up = true; } else //reversed { if(counter > 0 && up) counter--; else if(counter == 0 && up) up = false; else if((counter + lowerBound) < upperBound && !up) counter++; else if((counter + lowerBound) == upperBound && !up) up = true; } } void FlightStrip::chaseTripleColor() { if(up) (*strip).setPixelColor((counter + lowerBound), chaseTripleColor_color[number]); else (*strip).setPixelColor((counter + lowerBound), 0, 0, 0); if(!reversed) { if((counter + lowerBound) < upperBound && up) counter++; else if((counter + lowerBound) == upperBound && up) up = false; else if(counter > 0 && !up) counter--; else if(counter == 0 && !up) { up = true; if(number < 2) number++; else number = 0; } } else //reversed { if(counter > 0 && up) counter--; else if(counter == 0 && up) up = false; else if((counter + lowerBound) < upperBound && !up) counter++; else if((counter + lowerBound) == upperBound && !up) { up = true; if(number < 2) number++; else number = 0; } } } void FlightStrip::fillTripleColor() { (*strip).setPixelColor((counter + lowerBound), fillTripleColor_color[number]); if(!reversed) { if((counter + lowerBound) == upperBound) { counter = 0; if(number < 2) number++; else number = 0; } else counter++; } else //reversed { if(counter == 0) { counter = (upperBound - lowerBound); if(number < 2) number++; else number = 0; } else counter--; } } void FlightStrip::blinkColor() { if(up) //Aktuell aus -> Einschalten { for(int i = lowerBound ; i <= upperBound ; i++) (*strip).setPixelColor(i, blinkColor_color); up = false; } else //Aktuell an -> Ausschalten { for(int i = lowerBound ; i <= upperBound ; i++) (*strip).setPixelColor(i, 0, 0, 0); up = true; } } void FlightStrip::doubleflash() { if(up) //Aktuell aus -> Einschalten { for(int i = lowerBound ; i <= upperBound ; i++) (*strip).setPixelColor(i, doubleflash_color); up = false; } else //Aktuell an -> Ausschalten { for(int i = lowerBound ; i <= upperBound ; i++) (*strip).setPixelColor(i, 0, 0, 0); up = true; } } void FlightStrip::fillAgainst() { if(up) (*strip).setPixelColor((counter + lowerBound), fillAgainst_color[0]); else (*strip).setPixelColor((counter + lowerBound), fillAgainst_color[1]); if((counter + lowerBound) < upperBound && up) counter++; else if((counter + lowerBound) == upperBound && up) up = false; else if(counter > 0 && !up) counter--; else if(counter == 0 && !up) up = true; } void FlightStrip::theaterChase() { for(int i = lowerBound ; i <= upperBound ; i++) (*strip).setPixelColor(i, 0, 0, 0); for(int i = (lowerBound + number) ; i <= upperBound ; i = (i + 3)) (*strip).setPixelColor(i, theaterChase_color); if(number < 2) number++; else number = 0; } void FlightStrip::knightrider() { for(int i = lowerBound ; i <= upperBound ; i++) (*strip).setPixelColor(i, knightrider_background_color); if(!reversed) //normal { for(int i = 0 ; i < knightrider_width ; i++) (*strip).setPixelColor((lowerBound + counter + i), knightrider_color); if((counter + lowerBound) < (upperBound - knightrider_width + 1) && up) counter++; else if((counter + lowerBound) == (upperBound - knightrider_width + 1) && up) { up = false; counter--; } else if(counter > 0 && !up) counter--; else if(counter == 0 && !up) { up = true; counter++; } } else { for(int i = 0 ; i < knightrider_width ; i++) (*strip).setPixelColor((lowerBound + counter - i), knightrider_color); if((counter + lowerBound) < upperBound && up) counter++; else if((counter + lowerBound) == upperBound && up) { up = false; counter--; } else if(counter > (knightrider_width - 1) && !up) counter--; else if(counter == (knightrider_width - 1) && !up) { up = true; counter++; } } } void FlightStrip::thunderstorm() { if(!up) { for(int i = lowerBound ; i <= upperBound ; i++) (*strip).setPixelColor(i, thunderstorm_color); up = true; thunderstorm_interval = random(30, 50); } else { for(int i = lowerBound ; i <= upperBound ; i++) (*strip).setPixelColor(i, 0, 0, 0); up = false; thunderstorm_interval = random(50, 120); } } void FlightStrip::policeRight() { if(!up) //Momentan aus { switch(number) { case 0: for(int i = lowerBound ; i <= upperBound ; i++) (*strip).setPixelColor(i, 255, 0 , 0); break; case 1: for(int i = lowerBound ; i <= upperBound ; i++) (*strip).setPixelColor(i, 255, 0 , 0); break; case 2: for(int i = lowerBound ; i <= upperBound ; i++) (*strip).setPixelColor(i, 0, 0 , 255); break; } //switch up = true; policeRight_interval = 60; } //if else //up -> Momentan an { switch(number) { case 0: for(int i = lowerBound ; i <= upperBound ; i++) (*strip).setPixelColor(i, 0, 0 , 0); policeRight_interval = 60; break; case 1: for(int i = lowerBound ; i <= upperBound ; i++) (*strip).setPixelColor(i, 0, 0 , 0); policeRight_interval = 60; break; case 2: for(int i = lowerBound ; i <= upperBound ; i++) (*strip).setPixelColor(i, 0, 0 , 0); policeRight_interval = 400; break; }//switch up = false; if(number < 2) number++; else number = 0; } } void FlightStrip::policeLeft() { if(!up) //Momentan aus { switch(number) { case 0: for(int i = lowerBound ; i <= upperBound ; i++) (*strip).setPixelColor(i, 255, 0 , 0); break; case 1: for(int i = lowerBound ; i <= upperBound ; i++) (*strip).setPixelColor(i, 255, 0 , 0); break; case 2: for(int i = lowerBound ; i <= upperBound ; i++) (*strip).setPixelColor(i, 0, 0 , 255); break; } //switch up = true; policeLeft_interval = 60; } //if else //up -> Momentan an { switch(number) { case 0: for(int i = lowerBound ; i <= upperBound ; i++) (*strip).setPixelColor(i, 0, 0 , 0); policeLeft_interval = 60; break; case 1: for(int i = lowerBound ; i <= upperBound ; i++) (*strip).setPixelColor(i, 0, 0 , 0); policeLeft_interval = 60; break; case 2: for(int i = lowerBound ; i <= upperBound ; i++) (*strip).setPixelColor(i, 0, 0 , 0); policeLeft_interval = 400; break; }//switch up = false; if(number < 2) number++; else number = 0; } } void FlightStrip::rainbow() //Basierend auf RainbowCycle der Neopixel Library { if(!reversed) { for(int i = 0 ; i <= (upperBound - lowerBound); i++) { (*strip).setPixelColor(i, wheel(((i * 256 / (upperBound - lowerBound + 1)) + counter) & 255)); } if(counter < 255) counter++; else counter = 0; } else { for(int i = 0 ; i <= (upperBound - lowerBound); i++) { (*strip).setPixelColor(i, wheel(((i * 256 / (upperBound - lowerBound + 1)) + counter) & 255)); } if(counter > 0) counter--; else counter = 255; } } uint32_t FlightStrip::wheel(byte wheelPos) //Basireend auf Wheel der Neopixel Library { wheelPos = 255 - wheelPos; if(wheelPos < 85) return (*strip).Color(255 - wheelPos * 3, 0, wheelPos * 3); else if(wheelPos < 170) { wheelPos -= 85; return (*strip).Color(0, wheelPos * 3, 255 - wheelPos * 3); } else { wheelPos -= 170; return (*strip).Color(wheelPos * 3, 255 - wheelPos * 3, 0); } } void FlightStrip::blockswitch() { if(!reversed) { if(up) //aktuell leuchtet zweiter -> auf ersten Schalten { for(int i = lowerBound ; i <= upperBound ; i++) (*strip).setPixelColor(i, 0); for(int a = 0; a <= (upperBound - lowerBound) ; a++) { if(a % (blockswitch_width * 2) == 0) { for(int i = 0; i < blockswitch_width; i++) (*strip).setPixelColor(constrain((a + i + lowerBound), lowerBound, upperBound), blockswitch_color[0]); } } up = !up; } else //aktuell leuchtet zweiter -> auf ersten Schalten { for(int i = lowerBound ; i <= upperBound ; i++) (*strip).setPixelColor(i, 0); for(int a = 0; a <= (upperBound - lowerBound) ; a++) { if((a + blockswitch_width) % (blockswitch_width * 2) == 0) { for(int i = 0; i < blockswitch_width; i++) (*strip).setPixelColor(constrain((a + i + lowerBound), lowerBound, upperBound), blockswitch_color[1]); } } up = !up; } } else { if(!up) { for(int i = lowerBound ; i <= upperBound ; i++) (*strip).setPixelColor(i, 0); for(int a = 0; a <= (upperBound - lowerBound) ; a++) { if(a % (blockswitch_width * 2) == 0) { for(int i = 0; i < blockswitch_width; i++) (*strip).setPixelColor(constrain((a + i + lowerBound), lowerBound, upperBound), blockswitch_color[0]); } } up = !up; } else //aktuell leuchtet zweiter -> auf ersten Schalten { for(int i = lowerBound ; i <= upperBound ; i++) (*strip).setPixelColor(i, 0); for(int a = 0; a <= (upperBound - lowerBound) ; a++) { if((a + blockswitch_width) % (blockswitch_width * 2) == 0) { for(int i = 0; i < blockswitch_width; i++) (*strip).setPixelColor(constrain((a + i + lowerBound), lowerBound, upperBound), blockswitch_color[1]); } } up = !up; } } } void FlightStrip::randomflash() { uint8_t value[] = {0,100,255}; for(int i = lowerBound ; i <= upperBound ; i++) (*strip).setPixelColor(i, (*strip).Color(value[random(0,3)], value[random(0,3)], value[random(0,3)])); }
ec91a71d50bb31455f89576640d082eaba135d1b
9016a5ac6659d7d89029ecc50693330b410adc85
/Core/Network/Connections/ScarabServerConnection.h
580d32a5bdf71c01330910eadb20298970e2109a
[]
no_license
mworks-project/mw_core
35349273cc8c3acbd136f36d5680748c312742cf
f98ce9502a097b0c7a9e501d0e5bb513c7d0e835
refs/heads/master
2016-08-05T10:05:49.457160
2011-08-24T19:56:00
2011-08-24T19:56:00
108,497
2
1
null
null
null
null
UTF-8
C++
false
false
2,333
h
/** * ScarabServerConnection.h * * Description: Used by the Scarab Server to accept client connections. * Moved the functionality for accepting clients from the ScarabClient class * to here because i was confusing myself. * * History: * Paul Jankunas on 8/9/05 - Created. * Paul Jankunas on 08/24/05 - Added new member scheduleInterval to control * thread scheduling * * Copyright 2005 MIT. All rights reserved. */ #ifndef _SCARAB_SERVER_CONNECTION_H__ #define _SCARAB_SERVER_CONNECTION_H__ #include "ScarabReadConnection.h" #include "ScarabWriteConnection.h" #include "NetworkReturn.h" namespace mw { class ScarabServerConnection { protected: shared_ptr<ScarabReadConnection> reader; // a connection for reading shared_ptr<ScarabWriteConnection> writer; // a connection for writing int readPort; // readPort we have connected to int writePort; // writePort we have connected to std::string foreignHost; int scheduleInterval; shared_ptr<EventBuffer> incoming_event_buffer; shared_ptr<EventBuffer> outgoing_event_buffer; public: /** * Initializes the object. Interval must be a positive time. It * is the interval that the read and write threads are scheduled at. * A negative value will result in the default value of 200ms */ ScarabServerConnection(shared_ptr<EventBuffer> _incoming_event_buffer, shared_ptr<EventBuffer> _outgoing_event_buffer, int interval); /** * Frees memory. */ ~ScarabServerConnection(); /** * Wait for incoming connections. Call blocks. */ shared_ptr<NetworkReturn> accept(ScarabSession * listener); /** * Starts the read write threads */ void start(); /** * Disconnects the client attached to this connection. */ void disconnect(); /** * Returns the ports that are used for reading and writing. */ int getReadPort(); int getWritePort(); /** * Returns the foreign hostname. */ std::string getForeignHost(); }; } #endif
016012ed4ca25f188bbbd3ef878ef0c4b3bf5276
e6594775d1e0c4bfef1354189b144262e23a1a73
/trunk/synthetiseur/circularbuffer.cpp
465fddc097343a10409aa5fa2791bf447c4841a5
[]
no_license
tomotello/polyphone-tom
b04335b4c8b9cfc7a0908106f5e2d270dde80ffe
4fd8e0a92a376938afd6231bb6e0482936a35e34
refs/heads/master
2021-01-19T00:24:52.533896
2016-08-13T13:35:08
2016-08-13T13:35:08
65,304,181
1
0
null
null
null
null
UTF-8
C++
false
false
5,499
cpp
/*************************************************************************** ** ** ** Polyphone, a soundfont editor ** ** Copyright (C) 2013-2015 Davy Triponney ** ** 2014 Andrea Celani ** ** ** ** This program is free software: you can redistribute it and/or modify ** ** it under the terms of the GNU General Public License as published by ** ** the Free Software Foundation, either version 3 of the License, or ** ** (at your option) any later version. ** ** ** ** This program is distributed in the hope that it will be useful, ** ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** ** GNU General Public License for more details. ** ** ** ** You should have received a copy of the GNU General Public License ** ** along with this program. If not, see http://www.gnu.org/licenses/. ** ** ** **************************************************************************** ** Author: Davy Triponney ** ** Website/Contact: http://www.polyphone.fr/ ** ** Date: 01.01.2013 ** ***************************************************************************/ #include "circularbuffer.h" CircularBuffer::CircularBuffer(int minBuffer, int maxBuffer) : QObject(NULL), _minBuffer(minBuffer), _maxBuffer(maxBuffer), _bufferSize(4 * maxBuffer), _posEcriture(0), _posLecture(0), _currentLengthAvailable(0), _interrupted(0) { // Initialisation des buffers _dataL = new float [_bufferSize]; _dataR = new float [_bufferSize]; _dataTmpL = new float [_bufferSize]; _dataTmpR = new float [_bufferSize]; _dataRevL = new float [_bufferSize]; _dataRevR = new float [_bufferSize]; _dataTmpRevL = new float [_bufferSize]; _dataTmpRevR = new float [_bufferSize]; } CircularBuffer::~CircularBuffer() { delete [] _dataL; delete [] _dataR; delete [] _dataTmpL; delete [] _dataTmpR; delete [] _dataRevL; delete [] _dataRevR; delete [] _dataTmpRevL; delete [] _dataTmpRevR; } void CircularBuffer::stop() { _interrupted = 1; _mutexSynchro.tryLock(); _mutexSynchro.unlock(); } void CircularBuffer::start() { int avance = _maxBuffer - _minBuffer; // Surveillance du buffer après chaque lecture while (_interrupted == 0) { // Génération de données _mutexBuffer.lock(); generateData(_dataTmpL, _dataTmpR, _dataTmpRevL, _dataTmpRevR, avance); writeData(_dataTmpL, _dataTmpR, _dataTmpRevL, _dataTmpRevR, avance); _mutexBuffer.unlock(); _mutexSynchro.lock(); } _mutexSynchro.tryLock(); _mutexSynchro.unlock(); } // Sound engine thread => write data in the buffer // "len" contains at the end the data length that should have been written to meet the buffer requirements void CircularBuffer::writeData(const float *dataL, const float *dataR, float *dataRevL, float *dataRevR, int &len) { int total = 0; while (len - total > 0) { const int chunk = qMin(_bufferSize - _posEcriture, len - total); memcpy(&_dataL [_posEcriture], &dataL [total], 4 * chunk); memcpy(&_dataR [_posEcriture], &dataR [total], 4 * chunk); memcpy(&_dataRevL[_posEcriture], &dataRevL[total], 4 * chunk); memcpy(&_dataRevR[_posEcriture], &dataRevR[total], 4 * chunk); _posEcriture += chunk; if (_posEcriture >= _bufferSize) _posEcriture = 0; total += chunk; } // Quantité qu'il aurait fallu écrire (mise à jour pour la fois suivante) len = _maxBuffer - _currentLengthAvailable; if (len < _maxBuffer - _minBuffer) len = _maxBuffer - _minBuffer; // Mise à jour avance _currentLengthAvailable.fetchAndAddAcquire(total); } // Read data (audio thread) void CircularBuffer::addData(float *dataL, float *dataR, float *dataRevL, float *dataRevR, int maxlen) { int writeLen = qMin(maxlen, (int)_currentLengthAvailable); int total = 0; while (writeLen - total > 0) { const int chunk = qMin((_bufferSize - _posLecture), writeLen - total); for (int i = 0; i < chunk; i++) { dataL [total + i] += _dataL [_posLecture + i]; dataR [total + i] += _dataR [_posLecture + i]; dataRevL[total + i] += _dataRevL[_posLecture + i]; dataRevR[total + i] += _dataRevR[_posLecture + i]; } _posLecture = (_posLecture + chunk) % _bufferSize; total += chunk; } for (int i = total; i < maxlen; i++) dataL[i] = dataR[i] = dataRevL[i] = dataRevR[i] = 0; if (_currentLengthAvailable.fetchAndAddAcquire(-total) - total <= _minBuffer) { _mutexSynchro.tryLock(); _mutexSynchro.unlock(); } }
[ "tomotello" ]
tomotello
58c3a242c4c9d471ea7097805fb4f51f117b220f
fd97099ed918261b9870ef289114f7ef0e4c449b
/trie/app.cpp
ebdd08f11568645a17c5024ebe14d3c05147eafc
[]
no_license
YegangWu/Alogirthms
8b10b8ee23c3eba7266894a55eddf0f8e97f3e6b
9fa041d9af29a6e936c72e719cc2f7e190cd880b
refs/heads/master
2021-11-05T13:46:34.219360
2021-10-30T17:34:59
2021-10-30T17:34:59
215,429,555
0
1
null
2020-10-07T16:13:35
2019-10-16T01:29:19
C++
UTF-8
C++
false
false
1,700
cpp
#include "trie.h" #include <iostream> std::string check(bool flag) { return flag ? "yes" : "no"; } int main() { Trie trie("data/input.txt"); std::cout << "file contains by? " << check( trie.contains("by") ) << std::endl; std::cout << "file contains sells? " << check( trie.contains("sells") ) << std::endl; std::cout << "file contains sell? " << check( trie.contains("sell") ) << std::endl; std::cout << "file contains shore? " << check( trie.contains("shore") ) << std::endl; std::cout << "file contains the? " << check( trie.contains("the") ) << std::endl; std::cout << "file contains abc? " << check( trie.contains("abc") ) << std::endl; std::cout << "file contains sea? " << check( trie.contains("sea") ) << std::endl; trie.deleteKey("sells"); std::cout << "file contains sells? " << check( trie.contains("sells") ) << std::endl; std::cout << "file contains sea? " << check( trie.contains("sea") ) << std::endl; trie.deleteKey("by"); std::cout << "file contains sells? " << check( trie.contains("sells") ) << std::endl; std::cout << "file contains sea? " << check( trie.contains("sea") ) << std::endl; std::cout << "file contains by? " << check( trie.contains("by") ) << std::endl; std::cout << "file contains bye? " << check( trie.contains("bye") ) << std::endl; std::vector<std::string> keys = trie.getKeys(); for(size_t i = 0; i < keys.size(); ++i) { std::cout << keys[i] << std::endl; } const std::string str = "select"; std::cout << " The longest prefix of " << str << " is " << trie.longestPrefix(str) << std::endl; trie.addKey("sells", 1); std::cout << " The longest prefix of " << str << " is " << trie.longestPrefix(str) << std::endl; return 0; }
bcfcbdbf0b47f436231c33269b006913810a768c
b278695d3f1b411f3bf10fb2adf9a8baf11542d3
/Solutions/repeatedDNASequences.cpp
4aa2ae1ac9c54a3670443f900d54ee243d1017c0
[]
no_license
VenkataAnilKumar/LeetCode
445f62dc8e8eec430b6ea0709dc77cbdb7494621
df6d9e4b7172266bef4bc1f771fce3abb2216298
refs/heads/master
2021-06-25T07:56:54.217539
2020-12-18T05:54:59
2020-12-18T05:54:59
176,710,300
1
0
null
null
null
null
UTF-8
C++
false
false
2,586
cpp
// Source : https://oj.leetcode.com/problems/repeated-dna-sequences/ // Author : Venkata Anil Kumar /********************************************************************************** * * All DNA is composed of a series of nucleotides abbreviated as A, C, G, and T, * * For example: "ACGAATTCCG". * When studying DNA, it is sometimes useful to identify repeated sequences within the DNA. * * Write a function to find all the 10-letter-long sequences (substrings) that * occur more than once in a DNA molecule. * * For example, * * Given s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT", * * Return: * ["AAAAACCCCC", "CCCCCAAAAA"]. * * **********************************************************************************/ #include <stdlib.h> #include <iostream> #include <string> #include <vector> #include <functional> #include <unordered_map> using namespace std; const int MAX_LEN = 10; int ACGT2Int(char ch){ switch(ch){ case 'A': return 0; case 'C': return 1; case 'G': return 2; case 'T': return 3; } return -1; } int DNASeqs2Int(string &s, int begin){ int result=0; for(int i=0; i<MAX_LEN; i++){ result = result*4 + ACGT2Int(s[i+begin]); } return result; } vector<string> findRepeatedDnaSequences_01(string s) { unordered_map<int, int> stat; vector<string> result; for( int i=0; i+MAX_LEN<=s.size(); i++ ){ int hash_code = DNASeqs2Int(s, i); stat[hash_code]++; if (stat[hash_code]==2){ result.push_back(s.substr(i, MAX_LEN)); } } return result; } vector<string> findRepeatedDnaSequences_02(string s) { unordered_map<size_t, int> stat; hash<string> hash_func; vector<string> result; for( int i=0; i+MAX_LEN<=s.size(); i++ ){ string word = s.substr(i, MAX_LEN); size_t hash_code = hash_func(word); stat[hash_code]++; if (stat[hash_code]==2){ result.push_back(word); } } return result; } vector<string> findRepeatedDnaSequences(string s) { srand(time(0)); if (random()%2){ return findRepeatedDnaSequences_01(s); } return findRepeatedDnaSequences_02(s); } void printVector( vector<string> v ) { cout << "[ " ; for(int i=0; i<v.size(); i++ ){ cout << v[i] << (i<v.size()-1 ? ", " : ""); } cout << " ]" << endl; } int main(int argc, char** argv) { string s = "GAGAGAGAGAGAG" ; if (argc > 1){ s = argv[1]; } printVector(findRepeatedDnaSequences(s)); }
6c09fd3bfa6b76227ad73fa2a1c1b06438396a57
76d4430567b68151df1855f45ea4408f9bebe025
/src/rpc/protocol.h
9598ef8dec915a3fa2cb0c5dd2d22a395f33c03b
[ "MIT" ]
permissive
MicroBitcoinOrg/MicroBitcoin
f761b2ff04bdcb650d7c0ddbef431ef95cd69541
db7911968445606bf8899903322d5d818d393d88
refs/heads/master
2022-12-27T10:04:21.040945
2022-12-18T05:05:17
2022-12-18T05:05:17
132,959,214
21
33
MIT
2020-06-12T04:38:45
2018-05-10T22:07:51
C++
UTF-8
C++
false
false
4,823
h
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2019 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef MICRO_RPC_PROTOCOL_H #define MICRO_RPC_PROTOCOL_H //! HTTP status codes enum HTTPStatusCode { HTTP_OK = 200, HTTP_BAD_REQUEST = 400, HTTP_UNAUTHORIZED = 401, HTTP_FORBIDDEN = 403, HTTP_NOT_FOUND = 404, HTTP_BAD_METHOD = 405, HTTP_INTERNAL_SERVER_ERROR = 500, HTTP_SERVICE_UNAVAILABLE = 503, }; //! MicroBitcoin RPC error codes enum RPCErrorCode { //! Standard JSON-RPC 2.0 errors // RPC_INVALID_REQUEST is internally mapped to HTTP_BAD_REQUEST (400). // It should not be used for application-layer errors. RPC_INVALID_REQUEST = -32600, // RPC_METHOD_NOT_FOUND is internally mapped to HTTP_NOT_FOUND (404). // It should not be used for application-layer errors. RPC_METHOD_NOT_FOUND = -32601, RPC_INVALID_PARAMS = -32602, // RPC_INTERNAL_ERROR should only be used for genuine errors in microd // (for example datadir corruption). RPC_INTERNAL_ERROR = -32603, RPC_PARSE_ERROR = -32700, //! General application defined errors RPC_MISC_ERROR = -1, //!< std::exception thrown in command handling RPC_TYPE_ERROR = -3, //!< Unexpected type was passed as parameter RPC_INVALID_ADDRESS_OR_KEY = -5, //!< Invalid address or key RPC_OUT_OF_MEMORY = -7, //!< Ran out of memory during operation RPC_INVALID_PARAMETER = -8, //!< Invalid, missing or duplicate parameter RPC_DATABASE_ERROR = -20, //!< Database error RPC_DESERIALIZATION_ERROR = -22, //!< Error parsing or validating structure in raw format RPC_VERIFY_ERROR = -25, //!< General error during transaction or block submission RPC_VERIFY_REJECTED = -26, //!< Transaction or block was rejected by network rules RPC_VERIFY_ALREADY_IN_CHAIN = -27, //!< Transaction already in chain RPC_IN_WARMUP = -28, //!< Client still warming up RPC_METHOD_DEPRECATED = -32, //!< RPC method is deprecated //! Aliases for backward compatibility RPC_TRANSACTION_ERROR = RPC_VERIFY_ERROR, RPC_TRANSACTION_REJECTED = RPC_VERIFY_REJECTED, RPC_TRANSACTION_ALREADY_IN_CHAIN= RPC_VERIFY_ALREADY_IN_CHAIN, //! P2P client errors RPC_CLIENT_NOT_CONNECTED = -9, //!< MicroBitcoin is not connected RPC_CLIENT_IN_INITIAL_DOWNLOAD = -10, //!< Still downloading initial blocks RPC_CLIENT_NODE_ALREADY_ADDED = -23, //!< Node is already added RPC_CLIENT_NODE_NOT_ADDED = -24, //!< Node has not been added before RPC_CLIENT_NODE_NOT_CONNECTED = -29, //!< Node to disconnect not found in connected nodes RPC_CLIENT_INVALID_IP_OR_SUBNET = -30, //!< Invalid IP/Subnet RPC_CLIENT_P2P_DISABLED = -31, //!< No valid connection manager instance found RPC_CLIENT_NODE_CAPACITY_REACHED= -34, //!< Max number of outbound or block-relay connections already open //! Chain errors RPC_CLIENT_MEMPOOL_DISABLED = -33, //!< No mempool instance found //! Wallet errors RPC_WALLET_ERROR = -4, //!< Unspecified problem with wallet (key not found etc.) RPC_WALLET_INSUFFICIENT_FUNDS = -6, //!< Not enough funds in wallet or account RPC_WALLET_INVALID_LABEL_NAME = -11, //!< Invalid label name RPC_WALLET_KEYPOOL_RAN_OUT = -12, //!< Keypool ran out, call keypoolrefill first RPC_WALLET_UNLOCK_NEEDED = -13, //!< Enter the wallet passphrase with walletpassphrase first RPC_WALLET_PASSPHRASE_INCORRECT = -14, //!< The wallet passphrase entered was incorrect RPC_WALLET_WRONG_ENC_STATE = -15, //!< Command given in wrong wallet encryption state (encrypting an encrypted wallet etc.) RPC_WALLET_ENCRYPTION_FAILED = -16, //!< Failed to encrypt the wallet RPC_WALLET_ALREADY_UNLOCKED = -17, //!< Wallet is already unlocked RPC_WALLET_NOT_FOUND = -18, //!< Invalid wallet specified RPC_WALLET_NOT_SPECIFIED = -19, //!< No wallet specified (error when there are multiple wallets loaded) RPC_WALLET_ALREADY_LOADED = -35, //!< This same wallet is already loaded //! Backwards compatible aliases RPC_WALLET_INVALID_ACCOUNT_NAME = RPC_WALLET_INVALID_LABEL_NAME, //! Unused reserved codes, kept around for backwards compatibility. Do not reuse. RPC_FORBIDDEN_BY_SAFE_MODE = -2, //!< Server is in safe mode, and command is not allowed in safe mode }; #endif // MICRO_RPC_PROTOCOL_H
9065d848befda6ce030f72d00abcfd5876258afe
83e1ab5e61526513f694ec42b3ed441d218c03ca
/linkedList.cpp
3f8c0c29c7eab095333547a056b5b84b36c33c72
[]
no_license
TaylorSanchez/linkedList
2d2b5f70dca211b7df4e17b7bba66169dc0f77a2
6a2cf476b37d7a76de57cf4131285efae32084a6
refs/heads/master
2021-01-21T12:39:56.934171
2014-01-30T19:16:30
2014-01-30T19:16:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,648
cpp
/** * Implementation of the linkedList.cpp * * @author Taylor Sanchez * @version 1.0 * @date Jan 25, 2014 * @file linkedList.cpp */ /** * Summary: * This will create a singly linked list data type. * Being singly linked, it must be traversed from the head node downward. * this is similar to a stack, but can have data rearranged and entered * at mutliple points. * Since it lacks an index, the nodes and their pointers must be traversed * each time data needs to be accessed. * Nodes are the memory allocations for data and pointer storage. * Multiple nodes make up a linked list, but I forwent this formality and * simply named my struct linkedList as it seemed more fitting to me. */ #include <iostream> #include <fstream> using namespace std; struct linkedList{ int data; linkedList *next; }; /** * Creates the first node (or memory space) of the linkedList * This Should be called before attemping any other fuctions */ linkedList* createLinkedList(){ //first pointer to start/header of linked list, //this will be used to add to the beginning of the linkedList linkedList *head = NULL; return head; } /** * Inserts walks through the linkedList and outputs both the data and pointer * of each node. */ void outputLinkedList(linkedList* head){ //This will output each node in the linkedList linkedList *end; end=head; int i = 0; while( end!=NULL ){ printf("%i ",end->data ); printf("%p\n",end->next ); end = end->next; // tranfer the address of 'end->next' to 'end' if (i > 9){break;} i++; } printf("\n"); } /** * Inserts a new node to the top/beginning of the linkedList. * This will replace the head node with the new data, and move the data down * the 'stack'. */ linkedList* insertToHead(int newData, linkedList *head){ //temporary pointer for 'juggling' nodes, also first data holder linkedList *newHead = NULL; newHead = (linkedList*)malloc(sizeof(linkedList)); newHead->data = newData; newHead->next = head; return head = newHead; } /** * Inserts a new node to the end/bottom of the linkedList. * The head node stays constant, so there is no need for a return value. */ void insertToEnd(int newData, linkedList *head){ //This adds a node to the END of the linkedList linkedList *temp = NULL; linkedList *end = NULL; end = (linkedList*)malloc(sizeof(linkedList)); temp = head; while(temp->next!=NULL){ temp = temp->next; } end->data = newData; end->next = NULL; temp->next = end; } /** * Inserts a new node to the middle of the linkedList. * The head node stays constant, so there is no need for a return value. * nodeLocation requires a minimum of 2 be input, as it will not insert * to the top location. Instead use insertToTop, as it requires the head node * to change, and must return a value. */ void insertToMid(int newData, int nodeLocation, linkedList *head){ //inserting after 'x' number of nodes linkedList *temp = NULL; linkedList *mid = NULL; mid = (linkedList*)malloc(sizeof(linkedList)); temp = head; for( int i = 1; i <= nodeLocation ; i++ ){ if( temp->next == NULL ){ printf("Node %i does not exist," " added to end Node.\n", nodeLocation); mid->data = newData; mid->next = NULL; temp->next = mid; break; } else if ( i == nodeLocation ){ mid->data = newData; mid->next = temp->next; temp->next = mid; break; } temp = temp->next; } } /** * Inserts a new node to any part of the linkedList. * This function has logic to automatically chose insertToTop/End/Mid * based on the imput it is given. */ linkedList* insertNode(int newData, int nodeLocation, linkedList *head){ if ( nodeLocation == 0 ){ head = insertToHead(newData, head); } else if ( nodeLocation == -1 ) { insertToEnd(newData, head); } else{ insertToMid(newData, nodeLocation, head); } return head; } /** * Moves the a node to the last position of the linkedList * tempPrt: points to the node being moved * stepPtr: pointer used to traverse through linkedList * This is is called as needed by moveNode() */ void moveToEnd( linkedList *tempPtr, linkedList *stepPtr){ tempPtr->next = NULL; stepPtr->next = tempPtr; } /** * Moves the head node to the the new position specified * newLocation: new position specified * tempPrt: points to the node being moved * stepPtr: pointer used to traverse through linkedList * head: the head node used to traverse down * This is is called as needed by moveNode() */ linkedList* moveHeadNode(int newLocation, linkedList* tempPtr, linkedList* stepPtr, linkedList* head) { tempPtr = stepPtr; head = stepPtr->next; //update pionter to point past the one we are moving stepPtr->next = tempPtr->next; //start back at the top: stepPtr = head; if ( newLocation == -1 ){ while( stepPtr->next != NULL ){ stepPtr = stepPtr->next; } moveToEnd( tempPtr, stepPtr ); } for( int j=0; j <= newLocation; j++){ if( stepPtr->next == NULL ){ moveToEnd( tempPtr, stepPtr); break; } else if ( j == newLocation - 2 ){ tempPtr->next = stepPtr->next; stepPtr->next = tempPtr; break; } stepPtr = stepPtr->next; } return head; } /** * Moves the a node specified to the the new position specified * currentLocation: node specified * newLocation: new position specified * tempPrt: points to the node being moved * stepPtr: pointer used to traverse through linkedList * head: the head node used to traverse down * This is is called as needed by moveNode() */ linkedList* moveMidNode(int currentLocation, int newLocation, linkedList* tempPtr,linkedList* stepPtr, linkedList* head ) { for( int i = 0; i <= currentLocation ; i++ ){ if( stepPtr->next == NULL ){ printf("Node %i for currentLocation does not exist. " "Exiting moveNode early.\n", currentLocation ); break; } else if ( i == currentLocation-2 ){ tempPtr = stepPtr->next; stepPtr->next = tempPtr->next; stepPtr = head; if ( newLocation == -1 ){ while( stepPtr->next != NULL ){ stepPtr = stepPtr->next; } moveToEnd( tempPtr, stepPtr); break; } for( int j=0; j <= newLocation; j++){ if ( newLocation == 1 || newLocation == 0){ tempPtr->next = head; head = tempPtr; break; } else if( stepPtr->next == NULL ){ moveToEnd( tempPtr, stepPtr ); break; } else if ( j == newLocation - 2 ){ tempPtr->next = stepPtr->next; stepPtr->next = tempPtr; break; } stepPtr = stepPtr->next; } break; } stepPtr = stepPtr->next; } return head; } /** * Moves the last node to the the new position specified * newLocation: new position specified * tempPrt: points to the node being moved * stepPtr: pointer used to traverse through linkedList * head: the head node used to traverse down * This is is called as needed by moveNode() */ linkedList* moveEndNode(int newLocation, linkedList* tempPtr, linkedList* stepPtr, linkedList* head) { while( stepPtr->next->next != NULL ){ stepPtr = stepPtr->next; } tempPtr = stepPtr->next; stepPtr->next = NULL; stepPtr = head; if ( newLocation == -1 ){ while( stepPtr->next != NULL ) { stepPtr = stepPtr->next; } moveToEnd( tempPtr, stepPtr ); } for ( int j=0; j <= newLocation; j++){ if ( newLocation == 1 || newLocation == 0){ tempPtr->next = head; head = tempPtr; break; } else if ( stepPtr->next == NULL ){ moveToEnd( tempPtr, stepPtr ); break; } else if ( j == newLocation - 2 ){ tempPtr->next = stepPtr->next; stepPtr->next = tempPtr; break; } stepPtr = stepPtr->next; } return head; } /** * Moves a node specified to the the new position specified * currentLocation: node specified * newLocation: new position specified * tempPtr: points to the node being moved * stepPtr: pointer used to traverse through linkedList * head: the head node used to traverse down * This calls the necessary functions needed based on the input * shorthand: * 0 for newLocation/Location refers to the head node or 1st position * -1 for newLocation/Location refers to the last node or last position */ linkedList* moveNode(int currentLocation,int newLocation,linkedList* head){ linkedList *stepPtr; linkedList *tempPtr; stepPtr = head; if ( currentLocation == -1 ) { head = moveEndNode(newLocation, tempPtr, stepPtr, head); } else if ( currentLocation == 0 || currentLocation == 1 ){ head = moveHeadNode(newLocation, tempPtr, stepPtr, head); } else { head = moveMidNode(currentLocation, newLocation, tempPtr, stepPtr, head); } return head; } /** * Deletes the head node * tempPtr: pointer used to hold head location for deletion * head: updated to new head node location. * This is is called as needed by deleteNode() */ linkedList* deleteHeadNode(linkedList* head){ linkedList* tempPtr; tempPtr = head; // xfer the address of 'head' to 'tempPtr' head = head->next; // set head equal to next Node in list free(tempPtr); return head; } /** * Deletes the end node * stepPtr: pointer used to traverse through linkedList, * and is eventually deleted * head: the head node used to start traverse downward * This is is called as needed by deleteNode() */ void deleteEndNode(linkedList* head){ //This deletes a node to the END of the linkedList linkedList* stepPtr; linkedList* end; stepPtr = head; // transfer the address of 'head' to 'end' while(stepPtr->next!=NULL){ // go to the last node end = stepPtr; stepPtr = stepPtr->next;//tranfer the address of //'end1->next' to 'end' } end->next = NULL; free(stepPtr); } /** * Deletes the a node to the the node position specified * nodeLocation: node position specified * stepPtr: pointer used to traverse through linkedList, * and is eventually deleted * head: the head node used to start traverse downward * This is is called as needed by deleteNode() */ void deleteMidNode(int nodeLocation, linkedList* head){ linkedList* stepPtr; linkedList* end; stepPtr = head; for( int i = 1; i <= nodeLocation ; i++ ){ if( stepPtr->next == NULL ){ if ( i++ == nodeLocation ) { deleteEndNode(head); } else { printf("Node %i does not exist.\n", nodeLocation); } break; } else if ( i == nodeLocation ){ end->next = stepPtr ->next; free(stepPtr); break; } end = stepPtr; stepPtr = stepPtr->next; // go to the next node } } /** * Deletes the node specified to the the * nodeLocation: node specified * head: the head node used to traverse down and update for return * This calls the necessary functions needed based on the input * shorthand: * 0 for nodeLocation refers to the head node or 1st position * -1 for nodeLocation refers to the last node or last position */ linkedList* deleteNode(int nodeLocation, linkedList* head){ if (nodeLocation == -1 ){ deleteEndNode(head); } else if ( nodeLocation == 1 | nodeLocation == 0 ){ head = deleteHeadNode(head); } else { deleteMidNode(nodeLocation, head); } return head; } void changeData(int nodeLocation, int nodeData, linkedList* head){ linkedList* stepPtr; stepPtr = head; if ( nodeLocation == 0 ) { head->data = nodeData; } else if ( nodeLocation == -1 ) { while( stepPtr->next!=NULL ){ stepPtr = stepPtr->next; } stepPtr->data = nodeData; } else for( int i = 1; i <= nodeLocation ; i++ ){ if( stepPtr->next == NULL ){ if ( i++ == nodeLocation ) { stepPtr->data = nodeData; } else { printf("Node %i does not exist.\n", nodeLocation); } break; } else if ( i == nodeLocation ){ stepPtr->data = nodeData; break; } stepPtr = stepPtr->next; // go to the next node } } /** *Change functions here to make use of linkedList */ int main(){ int node_number; //first pointer to start/header of linked list, //this will be used to add to the beginning of the linkedList linkedList *head = createLinkedList(); head = insertToHead(345, head); head = insertToHead(346, head); head = insertToHead(347, head); insertToEnd(344, head); insertToEnd(343, head); insertToEnd(342, head); insertToEnd(341, head); insertToMid(5000, 2, head); head = insertNode(80085, 7, head); outputLinkedList(head); //head = moveNode(0,-1,head); //add -1 to choose last one //head = deleteNode(9, head); changeData(-1, 348, head); outputLinkedList(head); return 0; }
5872730ffefc951bbed2abd8fd380242a8dee57a
9049844781b7eb35aabcd9c63b307e869eb53f74
/opencv_ectracted_lib2/src/src/copy.cpp
6aa739343893384fc2f7ec6beebe234815727308
[]
no_license
sclee0095/vco
a118931341b3842088d0e78ba8f86d766e11a388
c2e08955bc9c833805084fac7913bd82133b7984
refs/heads/master
2021-01-19T06:03:05.459348
2016-08-19T13:38:32
2016-08-19T13:38:32
61,896,867
0
1
null
null
null
null
UTF-8
C++
false
false
49,409
cpp
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009-2011, Willow Garage Inc., all rights reserved. // Copyright (C) 2014, Itseez Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's 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. // // * The name of the copyright holders may not 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 Intel Corporation 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. // //M*/ /* //////////////////////////////////////////////////////////////////// // // Mat basic operations: Copy, Set // // */ #include "opencv2/core/precomp.hpp" #include "opencl_kernels_core.hpp" namespace cv { template<typename T> static void copyMask_(const uchar* _src, size_t sstep, const uchar* mask, size_t mstep, uchar* _dst, size_t dstep, Size size) { for( ; size.height--; mask += mstep, _src += sstep, _dst += dstep ) { const T* src = (const T*)_src; T* dst = (T*)_dst; int x = 0; #if CV_ENABLE_UNROLLED for( ; x <= size.width - 4; x += 4 ) { if( mask[x] ) dst[x] = src[x]; if( mask[x+1] ) dst[x+1] = src[x+1]; if( mask[x+2] ) dst[x+2] = src[x+2]; if( mask[x+3] ) dst[x+3] = src[x+3]; } #endif for( ; x < size.width; x++ ) if( mask[x] ) dst[x] = src[x]; } } template<> void copyMask_<uchar>(const uchar* _src, size_t sstep, const uchar* mask, size_t mstep, uchar* _dst, size_t dstep, Size size) { CV_IPP_RUN(true, ippiCopy_8u_C1MR(_src, (int)sstep, _dst, (int)dstep, ippiSize(size), mask, (int)mstep) >= 0) for( ; size.height--; mask += mstep, _src += sstep, _dst += dstep ) { const uchar* src = (const uchar*)_src; uchar* dst = (uchar*)_dst; int x = 0; #if CV_SSE4_2 if(USE_SSE4_2)// { __m128i zero = _mm_setzero_si128 (); for( ; x <= size.width - 16; x += 16 ) { const __m128i rSrc = _mm_lddqu_si128((const __m128i*)(src+x)); __m128i _mask = _mm_lddqu_si128((const __m128i*)(mask+x)); __m128i rDst = _mm_lddqu_si128((__m128i*)(dst+x)); __m128i _negMask = _mm_cmpeq_epi8(_mask, zero); rDst = _mm_blendv_epi8(rSrc, rDst, _negMask); _mm_storeu_si128((__m128i*)(dst + x), rDst); } } #elif CV_NEON uint8x16_t v_one = vdupq_n_u8(1); for( ; x <= size.width - 16; x += 16 ) { uint8x16_t v_mask = vcgeq_u8(vld1q_u8(mask + x), v_one); uint8x16_t v_dst = vld1q_u8(dst + x), v_src = vld1q_u8(src + x); vst1q_u8(dst + x, vbslq_u8(v_mask, v_src, v_dst)); } #endif for( ; x < size.width; x++ ) if( mask[x] ) dst[x] = src[x]; } } template<> void copyMask_<ushort>(const uchar* _src, size_t sstep, const uchar* mask, size_t mstep, uchar* _dst, size_t dstep, Size size) { CV_IPP_RUN(true, ippiCopy_16u_C1MR((const Ipp16u *)_src, (int)sstep, (Ipp16u *)_dst, (int)dstep, ippiSize(size), mask, (int)mstep) >= 0) for( ; size.height--; mask += mstep, _src += sstep, _dst += dstep ) { const ushort* src = (const ushort*)_src; ushort* dst = (ushort*)_dst; int x = 0; #if CV_SSE4_2 if(USE_SSE4_2)// { __m128i zero = _mm_setzero_si128 (); for( ; x <= size.width - 8; x += 8 ) { const __m128i rSrc =_mm_lddqu_si128((const __m128i*)(src+x)); __m128i _mask = _mm_loadl_epi64((const __m128i*)(mask+x)); _mask = _mm_unpacklo_epi8(_mask, _mask); __m128i rDst = _mm_lddqu_si128((const __m128i*)(dst+x)); __m128i _negMask = _mm_cmpeq_epi8(_mask, zero); rDst = _mm_blendv_epi8(rSrc, rDst, _negMask); _mm_storeu_si128((__m128i*)(dst + x), rDst); } } #elif CV_NEON uint8x8_t v_one = vdup_n_u8(1); for( ; x <= size.width - 8; x += 8 ) { uint8x8_t v_mask = vcge_u8(vld1_u8(mask + x), v_one); uint8x8x2_t v_mask2 = vzip_u8(v_mask, v_mask); uint16x8_t v_mask_res = vreinterpretq_u16_u8(vcombine_u8(v_mask2.val[0], v_mask2.val[1])); uint16x8_t v_src = vld1q_u16(src + x), v_dst = vld1q_u16(dst + x); vst1q_u16(dst + x, vbslq_u16(v_mask_res, v_src, v_dst)); } #endif for( ; x < size.width; x++ ) if( mask[x] ) dst[x] = src[x]; } } static void copyMaskGeneric(const uchar* _src, size_t sstep, const uchar* mask, size_t mstep, uchar* _dst, size_t dstep, Size size, void* _esz) { size_t k, esz = *(size_t*)_esz; for( ; size.height--; mask += mstep, _src += sstep, _dst += dstep ) { const uchar* src = _src; uchar* dst = _dst; int x = 0; for( ; x < size.width; x++, src += esz, dst += esz ) { if( !mask[x] ) continue; for( k = 0; k < esz; k++ ) dst[k] = src[k]; } } } #define DEF_COPY_MASK(suffix, type) \ static void copyMask##suffix(const uchar* src, size_t sstep, const uchar* mask, size_t mstep, \ uchar* dst, size_t dstep, Size size, void*) \ { \ copyMask_<type>(src, sstep, mask, mstep, dst, dstep, size); \ } #if defined HAVE_IPP #define DEF_COPY_MASK_F(suffix, type, ippfavor, ipptype) \ static void copyMask##suffix(const uchar* src, size_t sstep, const uchar* mask, size_t mstep, \ uchar* dst, size_t dstep, Size size, void*) \ { \ CV_IPP_RUN(true, ippiCopy_##ippfavor((const ipptype *)src, (int)sstep, (ipptype *)dst, (int)dstep, ippiSize(size), (const Ipp8u *)mask, (int)mstep) >= 0)\ copyMask_<type>(src, sstep, mask, mstep, dst, dstep, size); \ } #else #define DEF_COPY_MASK_F(suffix, type, ippfavor, ipptype) \ static void copyMask##suffix(const uchar* src, size_t sstep, const uchar* mask, size_t mstep, \ uchar* dst, size_t dstep, Size size, void*) \ { \ copyMask_<type>(src, sstep, mask, mstep, dst, dstep, size); \ } #endif #if IPP_VERSION_X100 == 901 // bug in IPP 9.0.1 DEF_COPY_MASK(32sC3, Vec3i) DEF_COPY_MASK(8uC3, Vec3b) #else DEF_COPY_MASK_F(8uC3, Vec3b, 8u_C3MR, Ipp8u) DEF_COPY_MASK_F(32sC3, Vec3i, 32s_C3MR, Ipp32s) #endif DEF_COPY_MASK(8u, uchar) DEF_COPY_MASK(16u, ushort) DEF_COPY_MASK_F(32s, int, 32s_C1MR, Ipp32s) DEF_COPY_MASK_F(16uC3, Vec3s, 16u_C3MR, Ipp16u) DEF_COPY_MASK(32sC2, Vec2i) DEF_COPY_MASK_F(32sC4, Vec4i, 32s_C4MR, Ipp32s) DEF_COPY_MASK(32sC6, Vec6i) DEF_COPY_MASK(32sC8, Vec8i) BinaryFunc copyMaskTab[] = { 0, copyMask8u, copyMask16u, copyMask8uC3, copyMask32s, 0, copyMask16uC3, 0, copyMask32sC2, 0, 0, 0, copyMask32sC3, 0, 0, 0, copyMask32sC4, 0, 0, 0, 0, 0, 0, 0, copyMask32sC6, 0, 0, 0, 0, 0, 0, 0, copyMask32sC8 }; BinaryFunc getCopyMaskFunc(size_t esz) { return esz <= 32 && copyMaskTab[esz] ? copyMaskTab[esz] : copyMaskGeneric; } /* dst = src */ void Mat::copyTo( OutputArray _dst ) const { int dtype = _dst.type(); if( _dst.fixedType() && dtype != type() ) { CV_Assert( channels() == CV_MAT_CN(dtype) ); convertTo( _dst, dtype ); return; } if( empty() ) { _dst.release(); return; } if( _dst.isUMat() ) { _dst.create( dims, size.p, type() ); UMat dst = _dst.getUMat(); size_t i, sz[CV_MAX_DIM], dstofs[CV_MAX_DIM], esz = elemSize(); for( i = 0; i < (size_t)dims; i++ ) sz[i] = size.p[i]; sz[dims-1] *= esz; dst.ndoffset(dstofs); dstofs[dims-1] *= esz; dst.u->currAllocator->upload(dst.u, data, dims, sz, dstofs, dst.step.p, step.p); return; } if( dims <= 2 ) { _dst.create( rows, cols, type() ); Mat dst = _dst.getMat(); if( data == dst.data ) return; if( rows > 0 && cols > 0 ) { // For some cases (with vector) dst.size != src.size, so force to column-based form // It prevents memory corruption in case of column-based src if (_dst.isVector()) dst = dst.reshape(0, (int)dst.total()); const uchar* sptr = data; uchar* dptr = dst.data; CV_IPP_RUN( (size_t)cols*elemSize() <= (size_t)INT_MAX && (size_t)step <= (size_t)INT_MAX && (size_t)dst.step <= (size_t)INT_MAX , ippiCopy_8u_C1R(sptr, (int)step, dptr, (int)dst.step, ippiSize((int)(cols*elemSize()), rows)) >= 0 ) Size sz = getContinuousSize(*this, dst); size_t len = sz.width*elemSize(); for( ; sz.height--; sptr += step, dptr += dst.step ) memcpy( dptr, sptr, len ); } return; } _dst.create( dims, size, type() ); Mat dst = _dst.getMat(); if( data == dst.data ) return; if( total() != 0 ) { const Mat* arrays[] = { this, &dst }; uchar* ptrs[2]; NAryMatIterator it(arrays, ptrs, 2); size_t sz = it.size*elemSize(); for( size_t i = 0; i < it.nplanes; i++, ++it ) memcpy(ptrs[1], ptrs[0], sz); } } void Mat::copyTo( OutputArray _dst, InputArray _mask ) const { Mat mask = _mask.getMat(); if( !mask.data ) { copyTo(_dst); return; } int cn = channels(), mcn = mask.channels(); CV_Assert( mask.depth() == CV_8U && (mcn == 1 || mcn == cn) ); bool colorMask = mcn > 1; size_t esz = colorMask ? elemSize1() : elemSize(); BinaryFunc copymask = getCopyMaskFunc(esz); uchar* data0 = _dst.getMat().data; _dst.create( dims, size, type() ); Mat dst = _dst.getMat(); if( dst.data != data0 ) // do not leave dst uninitialized dst = Scalar(0); if( dims <= 2 ) { CV_Assert( size() == mask.size() ); Size sz = getContinuousSize(*this, dst, mask, mcn); copymask(data, step, mask.data, mask.step, dst.data, dst.step, sz, &esz); return; } const Mat* arrays[] = { this, &dst, &mask, 0 }; uchar* ptrs[3]; NAryMatIterator it(arrays, ptrs); Size sz((int)(it.size*mcn), 1); for( size_t i = 0; i < it.nplanes; i++, ++it ) copymask(ptrs[0], 0, ptrs[2], 0, ptrs[1], 0, sz, &esz); } Mat& Mat::operator = (const Scalar& s) { const Mat* arrays[] = { this }; uchar* dptr; NAryMatIterator it(arrays, &dptr, 1); size_t elsize = it.size*elemSize(); const int64* is = (const int64*)&s.val[0]; if( is[0] == 0 && is[1] == 0 && is[2] == 0 && is[3] == 0 ) { #if defined HAVE_IPP && !defined HAVE_IPP_ICV_ONLY && IPP_DISABLE_BLOCK CV_IPP_CHECK() { if (dims <= 2 || isContinuous()) { IppiSize roisize = { cols, rows }; if (isContinuous()) { roisize.width = (int)total(); roisize.height = 1; if (ippsZero_8u(data, static_cast<int>(roisize.width * elemSize())) >= 0) { CV_IMPL_ADD(CV_IMPL_IPP) return *this; } setIppErrorStatus(); } roisize.width *= (int)elemSize(); if (ippiSet_8u_C1R(0, data, (int)step, roisize) >= 0) { CV_IMPL_ADD(CV_IMPL_IPP) return *this; } setIppErrorStatus(); } } #endif for( size_t i = 0; i < it.nplanes; i++, ++it ) memset( dptr, 0, elsize ); } else { if( it.nplanes > 0 ) { double scalar[12]; scalarToRawData(s, scalar, type(), 12); size_t blockSize = 12*elemSize1(); for( size_t j = 0; j < elsize; j += blockSize ) { size_t sz = MIN(blockSize, elsize - j); memcpy( dptr + j, scalar, sz ); } } for( size_t i = 1; i < it.nplanes; i++ ) { ++it; memcpy( dptr, data, elsize ); } } return *this; } #if defined HAVE_IPP static bool ipp_Mat_setTo(Mat *src, Mat &value, Mat &mask) { int cn = src->channels(), depth0 = src->depth(); if (!mask.empty() && (src->dims <= 2 || (src->isContinuous() && mask.isContinuous())) && (/*depth0 == CV_8U ||*/ depth0 == CV_16U || depth0 == CV_16S || depth0 == CV_32S || depth0 == CV_32F) && (cn == 1 || cn == 3 || cn == 4)) { uchar _buf[32]; void * buf = _buf; convertAndUnrollScalar( value, src->type(), _buf, 1 ); IppStatus status = (IppStatus)-1; IppiSize roisize = { src->cols, src->rows }; int mstep = (int)mask.step[0], dstep = (int)src->step[0]; if (src->isContinuous() && mask.isContinuous()) { roisize.width = (int)src->total(); roisize.height = 1; } if (cn == 1) { /*if (depth0 == CV_8U) status = ippiSet_8u_C1MR(*(Ipp8u *)buf, (Ipp8u *)data, dstep, roisize, mask.data, mstep); else*/ if (depth0 == CV_16U) status = ippiSet_16u_C1MR(*(Ipp16u *)buf, (Ipp16u *)src->data, dstep, roisize, mask.data, mstep); else if (depth0 == CV_16S) status = ippiSet_16s_C1MR(*(Ipp16s *)buf, (Ipp16s *)src->data, dstep, roisize, mask.data, mstep); else if (depth0 == CV_32S) status = ippiSet_32s_C1MR(*(Ipp32s *)buf, (Ipp32s *)src->data, dstep, roisize, mask.data, mstep); else if (depth0 == CV_32F) status = ippiSet_32f_C1MR(*(Ipp32f *)buf, (Ipp32f *)src->data, dstep, roisize, mask.data, mstep); } else if (cn == 3 || cn == 4) { #define IPP_SET(ippfavor, ippcn) \ do \ { \ typedef Ipp##ippfavor ipptype; \ ipptype ippvalue[4] = { ((ipptype *)buf)[0], ((ipptype *)buf)[1], ((ipptype *)buf)[2], ((ipptype *)buf)[3] }; \ status = ippiSet_##ippfavor##_C##ippcn##MR(ippvalue, (ipptype *)src->data, dstep, roisize, mask.data, mstep); \ } while ((void)0, 0) #define IPP_SET_CN(ippcn) \ do \ { \ if (cn == ippcn) \ { \ /*if (depth0 == CV_8U) \ IPP_SET(8u, ippcn); \ else*/ if (depth0 == CV_16U) \ IPP_SET(16u, ippcn); \ else if (depth0 == CV_16S) \ IPP_SET(16s, ippcn); \ else if (depth0 == CV_32S) \ IPP_SET(32s, ippcn); \ else if (depth0 == CV_32F) \ IPP_SET(32f, ippcn); \ } \ } while ((void)0, 0) IPP_SET_CN(3); IPP_SET_CN(4); #undef IPP_SET_CN #undef IPP_SET } if (status >= 0) return true; } return false; } #endif Mat& Mat::setTo(InputArray _value, InputArray _mask) { if( empty() ) return *this; Mat value = _value.getMat(), mask = _mask.getMat(); CV_Assert( checkScalar(value, type(), _value.kind(), _InputArray::MAT )); CV_Assert( mask.empty() || (mask.type() == CV_8U && size == mask.size) ); CV_IPP_RUN(true, ipp_Mat_setTo((cv::Mat*)this, value, mask), *this) size_t esz = elemSize(); BinaryFunc copymask = getCopyMaskFunc(esz); const Mat* arrays[] = { this, !mask.empty() ? &mask : 0, 0 }; uchar* ptrs[2]={0,0}; NAryMatIterator it(arrays, ptrs); int totalsz = (int)it.size, blockSize0 = std::min(totalsz, (int)((BLOCK_SIZE + esz-1)/esz)); AutoBuffer<uchar> _scbuf(blockSize0*esz + 32); uchar* scbuf = alignPtr((uchar*)_scbuf, (int)sizeof(double)); convertAndUnrollScalar( value, type(), scbuf, blockSize0 ); for( size_t i = 0; i < it.nplanes; i++, ++it ) { for( int j = 0; j < totalsz; j += blockSize0 ) { Size sz(std::min(blockSize0, totalsz - j), 1); size_t blockSize = sz.width*esz; if( ptrs[1] ) { copymask(scbuf, 0, ptrs[1], 0, ptrs[0], 0, sz, &esz); ptrs[1] += sz.width; } else memcpy(ptrs[0], scbuf, blockSize); ptrs[0] += blockSize; } } return *this; } static void flipHoriz( const uchar* src, size_t sstep, uchar* dst, size_t dstep, Size size, size_t esz ) { int i, j, limit = (int)(((size.width + 1)/2)*esz); AutoBuffer<int> _tab(size.width*esz); int* tab = _tab; for( i = 0; i < size.width; i++ ) for( size_t k = 0; k < esz; k++ ) tab[i*esz + k] = (int)((size.width - i - 1)*esz + k); for( ; size.height--; src += sstep, dst += dstep ) { for( i = 0; i < limit; i++ ) { j = tab[i]; uchar t0 = src[i], t1 = src[j]; dst[i] = t1; dst[j] = t0; } } } static void flipVert( const uchar* src0, size_t sstep, uchar* dst0, size_t dstep, Size size, size_t esz ) { const uchar* src1 = src0 + (size.height - 1)*sstep; uchar* dst1 = dst0 + (size.height - 1)*dstep; size.width *= (int)esz; for( int y = 0; y < (size.height + 1)/2; y++, src0 += sstep, src1 -= sstep, dst0 += dstep, dst1 -= dstep ) { int i = 0; if( ((size_t)src0|(size_t)dst0|(size_t)src1|(size_t)dst1) % sizeof(int) == 0 ) { for( ; i <= size.width - 16; i += 16 ) { int t0 = ((int*)(src0 + i))[0]; int t1 = ((int*)(src1 + i))[0]; ((int*)(dst0 + i))[0] = t1; ((int*)(dst1 + i))[0] = t0; t0 = ((int*)(src0 + i))[1]; t1 = ((int*)(src1 + i))[1]; ((int*)(dst0 + i))[1] = t1; ((int*)(dst1 + i))[1] = t0; t0 = ((int*)(src0 + i))[2]; t1 = ((int*)(src1 + i))[2]; ((int*)(dst0 + i))[2] = t1; ((int*)(dst1 + i))[2] = t0; t0 = ((int*)(src0 + i))[3]; t1 = ((int*)(src1 + i))[3]; ((int*)(dst0 + i))[3] = t1; ((int*)(dst1 + i))[3] = t0; } for( ; i <= size.width - 4; i += 4 ) { int t0 = ((int*)(src0 + i))[0]; int t1 = ((int*)(src1 + i))[0]; ((int*)(dst0 + i))[0] = t1; ((int*)(dst1 + i))[0] = t0; } } for( ; i < size.width; i++ ) { uchar t0 = src0[i]; uchar t1 = src1[i]; dst0[i] = t1; dst1[i] = t0; } } } #ifdef HAVE_OPENCL enum { FLIP_COLS = 1 << 0, FLIP_ROWS = 1 << 1, FLIP_BOTH = FLIP_ROWS | FLIP_COLS }; static bool ocl_flip(InputArray _src, OutputArray _dst, int flipCode ) { CV_Assert(flipCode >= -1 && flipCode <= 1); const ocl::Device & dev = ocl::Device::getDefault(); int type = _src.type(), depth = CV_MAT_DEPTH(type), cn = CV_MAT_CN(type), flipType, kercn = std::min(ocl::predictOptimalVectorWidth(_src, _dst), 4); bool doubleSupport = dev.doubleFPConfig() > 0; if (!doubleSupport && depth == CV_64F) kercn = cn; if (cn > 4) return false; const char * kernelName; if (flipCode == 0) kernelName = "arithm_flip_rows", flipType = FLIP_ROWS; else if (flipCode > 0) kernelName = "arithm_flip_cols", flipType = FLIP_COLS; else kernelName = "arithm_flip_rows_cols", flipType = FLIP_BOTH; int pxPerWIy = (dev.isIntel() && (dev.type() & ocl::Device::TYPE_GPU)) ? 4 : 1; kercn = (cn!=3 || flipType == FLIP_ROWS) ? std::max(kercn, cn) : cn; ocl::Kernel k(kernelName, ocl::core::flip_oclsrc, format( "-D T=%s -D T1=%s -D cn=%d -D PIX_PER_WI_Y=%d -D kercn=%d", kercn != cn ? ocl::typeToStr(CV_MAKE_TYPE(depth, kercn)) : ocl::vecopTypeToStr(CV_MAKE_TYPE(depth, kercn)), kercn != cn ? ocl::typeToStr(depth) : ocl::vecopTypeToStr(depth), cn, pxPerWIy, kercn)); if (k.empty()) return false; Size size = _src.size(); _dst.create(size, type); UMat src = _src.getUMat(), dst = _dst.getUMat(); int cols = size.width * cn / kercn, rows = size.height; cols = flipType == FLIP_COLS ? (cols + 1) >> 1 : cols; rows = flipType & FLIP_ROWS ? (rows + 1) >> 1 : rows; k.args(ocl::KernelArg::ReadOnlyNoSize(src), ocl::KernelArg::WriteOnly(dst, cn, kercn), rows, cols); size_t maxWorkGroupSize = dev.maxWorkGroupSize(); CV_Assert(maxWorkGroupSize % 4 == 0); size_t globalsize[2] = { (size_t)cols, ((size_t)rows + pxPerWIy - 1) / pxPerWIy }, localsize[2] = { maxWorkGroupSize / 4, 4 }; return k.run(2, globalsize, (flipType == FLIP_COLS) && !dev.isIntel() ? localsize : NULL, false); } #endif #if defined HAVE_IPP static bool ipp_flip( Mat &src, Mat &dst, int flip_mode ) { int type = src.type(); typedef IppStatus (CV_STDCALL * ippiMirror)(const void * pSrc, int srcStep, void * pDst, int dstStep, IppiSize roiSize, IppiAxis flip); typedef IppStatus (CV_STDCALL * ippiMirrorI)(const void * pSrcDst, int srcDstStep, IppiSize roiSize, IppiAxis flip); ippiMirror ippFunc = 0; ippiMirrorI ippFuncI = 0; if (src.data == dst.data) { CV_SUPPRESS_DEPRECATED_START ippFuncI = type == CV_8UC1 ? (ippiMirrorI)ippiMirror_8u_C1IR : type == CV_8UC3 ? (ippiMirrorI)ippiMirror_8u_C3IR : type == CV_8UC4 ? (ippiMirrorI)ippiMirror_8u_C4IR : type == CV_16UC1 ? (ippiMirrorI)ippiMirror_16u_C1IR : type == CV_16UC3 ? (ippiMirrorI)ippiMirror_16u_C3IR : type == CV_16UC4 ? (ippiMirrorI)ippiMirror_16u_C4IR : type == CV_16SC1 ? (ippiMirrorI)ippiMirror_16s_C1IR : type == CV_16SC3 ? (ippiMirrorI)ippiMirror_16s_C3IR : type == CV_16SC4 ? (ippiMirrorI)ippiMirror_16s_C4IR : type == CV_32SC1 ? (ippiMirrorI)ippiMirror_32s_C1IR : type == CV_32SC3 ? (ippiMirrorI)ippiMirror_32s_C3IR : type == CV_32SC4 ? (ippiMirrorI)ippiMirror_32s_C4IR : type == CV_32FC1 ? (ippiMirrorI)ippiMirror_32f_C1IR : type == CV_32FC3 ? (ippiMirrorI)ippiMirror_32f_C3IR : type == CV_32FC4 ? (ippiMirrorI)ippiMirror_32f_C4IR : 0; CV_SUPPRESS_DEPRECATED_END } else { ippFunc = type == CV_8UC1 ? (ippiMirror)ippiMirror_8u_C1R : type == CV_8UC3 ? (ippiMirror)ippiMirror_8u_C3R : type == CV_8UC4 ? (ippiMirror)ippiMirror_8u_C4R : type == CV_16UC1 ? (ippiMirror)ippiMirror_16u_C1R : type == CV_16UC3 ? (ippiMirror)ippiMirror_16u_C3R : type == CV_16UC4 ? (ippiMirror)ippiMirror_16u_C4R : type == CV_16SC1 ? (ippiMirror)ippiMirror_16s_C1R : type == CV_16SC3 ? (ippiMirror)ippiMirror_16s_C3R : type == CV_16SC4 ? (ippiMirror)ippiMirror_16s_C4R : type == CV_32SC1 ? (ippiMirror)ippiMirror_32s_C1R : type == CV_32SC3 ? (ippiMirror)ippiMirror_32s_C3R : type == CV_32SC4 ? (ippiMirror)ippiMirror_32s_C4R : type == CV_32FC1 ? (ippiMirror)ippiMirror_32f_C1R : type == CV_32FC3 ? (ippiMirror)ippiMirror_32f_C3R : type == CV_32FC4 ? (ippiMirror)ippiMirror_32f_C4R : 0; } IppiAxis axis = flip_mode == 0 ? ippAxsHorizontal : flip_mode > 0 ? ippAxsVertical : ippAxsBoth; IppiSize roisize = { dst.cols, dst.rows }; if (ippFunc != 0) { if (ippFunc(src.ptr(), (int)src.step, dst.ptr(), (int)dst.step, ippiSize(src.cols, src.rows), axis) >= 0) return true; } else if (ippFuncI != 0) { if (ippFuncI(dst.ptr(), (int)dst.step, roisize, axis) >= 0) return true; } return false; } #endif void flip( InputArray _src, OutputArray _dst, int flip_mode ) { CV_Assert( _src.dims() <= 2 ); Size size = _src.size(); if (flip_mode < 0) { if (size.width == 1) flip_mode = 0; if (size.height == 1) flip_mode = 1; } if ((size.width == 1 && flip_mode > 0) || (size.height == 1 && flip_mode == 0) || (size.height == 1 && size.width == 1 && flip_mode < 0)) { return _src.copyTo(_dst); } CV_OCL_RUN( _dst.isUMat(), ocl_flip(_src, _dst, flip_mode)) Mat src = _src.getMat(); int type = src.type(); _dst.create( size, type ); Mat dst = _dst.getMat(); CV_IPP_RUN(true, ipp_flip(src, dst, flip_mode)); size_t esz = CV_ELEM_SIZE(type); if( flip_mode <= 0 ) flipVert( src.ptr(), src.step, dst.ptr(), dst.step, src.size(), esz ); else flipHoriz( src.ptr(), src.step, dst.ptr(), dst.step, src.size(), esz ); if( flip_mode < 0 ) flipHoriz( dst.ptr(), dst.step, dst.ptr(), dst.step, dst.size(), esz ); } #if defined HAVE_OPENCL && !defined __APPLE__ static bool ocl_repeat(InputArray _src, int ny, int nx, OutputArray _dst) { if (ny == 1 && nx == 1) { _src.copyTo(_dst); return true; } int type = _src.type(), depth = CV_MAT_DEPTH(type), cn = CV_MAT_CN(type), rowsPerWI = ocl::Device::getDefault().isIntel() ? 4 : 1, kercn = ocl::predictOptimalVectorWidth(_src, _dst); ocl::Kernel k("repeat", ocl::core::repeat_oclsrc, format("-D T=%s -D nx=%d -D ny=%d -D rowsPerWI=%d -D cn=%d", ocl::memopTypeToStr(CV_MAKE_TYPE(depth, kercn)), nx, ny, rowsPerWI, kercn)); if (k.empty()) return false; UMat src = _src.getUMat(), dst = _dst.getUMat(); k.args(ocl::KernelArg::ReadOnly(src, cn, kercn), ocl::KernelArg::WriteOnlyNoSize(dst)); size_t globalsize[] = { (size_t)src.cols * cn / kercn, ((size_t)src.rows + rowsPerWI - 1) / rowsPerWI }; return k.run(2, globalsize, NULL, false); } #endif void repeat(InputArray _src, int ny, int nx, OutputArray _dst) { CV_Assert( _src.dims() <= 2 ); CV_Assert( ny > 0 && nx > 0 ); Size ssize = _src.size(); _dst.create(ssize.height*ny, ssize.width*nx, _src.type()); #if !defined __APPLE__ CV_OCL_RUN(_dst.isUMat(), ocl_repeat(_src, ny, nx, _dst)) #endif Mat src = _src.getMat(), dst = _dst.getMat(); Size dsize = dst.size(); int esz = (int)src.elemSize(); int x, y; ssize.width *= esz; dsize.width *= esz; for( y = 0; y < ssize.height; y++ ) { for( x = 0; x < dsize.width; x += ssize.width ) memcpy( dst.ptr(y) + x, src.ptr(y), ssize.width ); } for( ; y < dsize.height; y++ ) memcpy( dst.ptr(y), dst.ptr(y - ssize.height), dsize.width ); } Mat repeat(const Mat& src, int ny, int nx) { if( nx == 1 && ny == 1 ) return src; Mat dst; repeat(src, ny, nx, dst); return dst; } } // cv /* Various border types, image boundaries are denoted with '|' * BORDER_REPLICATE: aaaaaa|abcdefgh|hhhhhhh * BORDER_REFLECT: fedcba|abcdefgh|hgfedcb * BORDER_REFLECT_101: gfedcb|abcdefgh|gfedcba * BORDER_WRAP: cdefgh|abcdefgh|abcdefg * BORDER_CONSTANT: iiiiii|abcdefgh|iiiiiii with some specified 'i' */ int cv::borderInterpolate( int p, int len, int borderType ) { if( (unsigned)p < (unsigned)len ) ; else if( borderType == BORDER_REPLICATE ) p = p < 0 ? 0 : len - 1; else if( borderType == BORDER_REFLECT || borderType == BORDER_REFLECT_101 ) { int delta = borderType == BORDER_REFLECT_101; if( len == 1 ) return 0; do { if( p < 0 ) p = -p - 1 + delta; else p = len - 1 - (p - len) - delta; } while( (unsigned)p >= (unsigned)len ); } else if( borderType == BORDER_WRAP ) { CV_Assert(len > 0); if( p < 0 ) p -= ((p-len+1)/len)*len; if( p >= len ) p %= len; } else if( borderType == BORDER_CONSTANT ) p = -1; else CV_Error( CV_StsBadArg, "Unknown/unsupported border type" ); return p; } namespace { void copyMakeBorder_8u( const uchar* src, size_t srcstep, cv::Size srcroi, uchar* dst, size_t dststep, cv::Size dstroi, int top, int left, int cn, int borderType ) { const int isz = (int)sizeof(int); int i, j, k, elemSize = 1; bool intMode = false; if( (cn | srcstep | dststep | (size_t)src | (size_t)dst) % isz == 0 ) { cn /= isz; elemSize = isz; intMode = true; } cv::AutoBuffer<int> _tab((dstroi.width - srcroi.width)*cn); int* tab = _tab; int right = dstroi.width - srcroi.width - left; int bottom = dstroi.height - srcroi.height - top; for( i = 0; i < left; i++ ) { j = cv::borderInterpolate(i - left, srcroi.width, borderType)*cn; for( k = 0; k < cn; k++ ) tab[i*cn + k] = j + k; } for( i = 0; i < right; i++ ) { j = cv::borderInterpolate(srcroi.width + i, srcroi.width, borderType)*cn; for( k = 0; k < cn; k++ ) tab[(i+left)*cn + k] = j + k; } srcroi.width *= cn; dstroi.width *= cn; left *= cn; right *= cn; uchar* dstInner = dst + dststep*top + left*elemSize; for( i = 0; i < srcroi.height; i++, dstInner += dststep, src += srcstep ) { if( dstInner != src ) memcpy(dstInner, src, srcroi.width*elemSize); if( intMode ) { const int* isrc = (int*)src; int* idstInner = (int*)dstInner; for( j = 0; j < left; j++ ) idstInner[j - left] = isrc[tab[j]]; for( j = 0; j < right; j++ ) idstInner[j + srcroi.width] = isrc[tab[j + left]]; } else { for( j = 0; j < left; j++ ) dstInner[j - left] = src[tab[j]]; for( j = 0; j < right; j++ ) dstInner[j + srcroi.width] = src[tab[j + left]]; } } dstroi.width *= elemSize; dst += dststep*top; for( i = 0; i < top; i++ ) { j = cv::borderInterpolate(i - top, srcroi.height, borderType); memcpy(dst + (i - top)*dststep, dst + j*dststep, dstroi.width); } for( i = 0; i < bottom; i++ ) { j = cv::borderInterpolate(i + srcroi.height, srcroi.height, borderType); memcpy(dst + (i + srcroi.height)*dststep, dst + j*dststep, dstroi.width); } } void copyMakeConstBorder_8u( const uchar* src, size_t srcstep, cv::Size srcroi, uchar* dst, size_t dststep, cv::Size dstroi, int top, int left, int cn, const uchar* value ) { int i, j; cv::AutoBuffer<uchar> _constBuf(dstroi.width*cn); uchar* constBuf = _constBuf; int right = dstroi.width - srcroi.width - left; int bottom = dstroi.height - srcroi.height - top; for( i = 0; i < dstroi.width; i++ ) { for( j = 0; j < cn; j++ ) constBuf[i*cn + j] = value[j]; } srcroi.width *= cn; dstroi.width *= cn; left *= cn; right *= cn; uchar* dstInner = dst + dststep*top + left; for( i = 0; i < srcroi.height; i++, dstInner += dststep, src += srcstep ) { if( dstInner != src ) memcpy( dstInner, src, srcroi.width ); memcpy( dstInner - left, constBuf, left ); memcpy( dstInner + srcroi.width, constBuf, right ); } dst += dststep*top; for( i = 0; i < top; i++ ) memcpy(dst + (i - top)*dststep, constBuf, dstroi.width); for( i = 0; i < bottom; i++ ) memcpy(dst + (i + srcroi.height)*dststep, constBuf, dstroi.width); } } #ifdef HAVE_OPENCL namespace cv { static bool ocl_copyMakeBorder( InputArray _src, OutputArray _dst, int top, int bottom, int left, int right, int borderType, const Scalar& value ) { int type = _src.type(), cn = CV_MAT_CN(type), depth = CV_MAT_DEPTH(type), rowsPerWI = ocl::Device::getDefault().isIntel() ? 4 : 1; bool isolated = (borderType & BORDER_ISOLATED) != 0; borderType &= ~cv::BORDER_ISOLATED; if ( !(borderType == BORDER_CONSTANT || borderType == BORDER_REPLICATE || borderType == BORDER_REFLECT || borderType == BORDER_WRAP || borderType == BORDER_REFLECT_101) || cn > 4) return false; const char * const borderMap[] = { "BORDER_CONSTANT", "BORDER_REPLICATE", "BORDER_REFLECT", "BORDER_WRAP", "BORDER_REFLECT_101" }; int scalarcn = cn == 3 ? 4 : cn; int sctype = CV_MAKETYPE(depth, scalarcn); String buildOptions = format("-D T=%s -D %s -D T1=%s -D cn=%d -D ST=%s -D rowsPerWI=%d", ocl::memopTypeToStr(type), borderMap[borderType], ocl::memopTypeToStr(depth), cn, ocl::memopTypeToStr(sctype), rowsPerWI); ocl::Kernel k("copyMakeBorder", ocl::core::copymakeborder_oclsrc, buildOptions); if (k.empty()) return false; UMat src = _src.getUMat(); if( src.isSubmatrix() && !isolated ) { Size wholeSize; Point ofs; src.locateROI(wholeSize, ofs); int dtop = std::min(ofs.y, top); int dbottom = std::min(wholeSize.height - src.rows - ofs.y, bottom); int dleft = std::min(ofs.x, left); int dright = std::min(wholeSize.width - src.cols - ofs.x, right); src.adjustROI(dtop, dbottom, dleft, dright); top -= dtop; left -= dleft; bottom -= dbottom; right -= dright; } _dst.create(src.rows + top + bottom, src.cols + left + right, type); UMat dst = _dst.getUMat(); if (top == 0 && left == 0 && bottom == 0 && right == 0) { if(src.u != dst.u || src.step != dst.step) src.copyTo(dst); return true; } k.args(ocl::KernelArg::ReadOnly(src), ocl::KernelArg::WriteOnly(dst), top, left, ocl::KernelArg::Constant(Mat(1, 1, sctype, value))); size_t globalsize[2] = { (size_t)dst.cols, ((size_t)dst.rows + rowsPerWI - 1) / rowsPerWI }; return k.run(2, globalsize, NULL, false); } } #endif void cv::copyMakeBorder( InputArray _src, OutputArray _dst, int top, int bottom, int left, int right, int borderType, const Scalar& value ) { CV_Assert( top >= 0 && bottom >= 0 && left >= 0 && right >= 0 ); CV_OCL_RUN(_dst.isUMat() && _src.dims() <= 2, ocl_copyMakeBorder(_src, _dst, top, bottom, left, right, borderType, value)) Mat src = _src.getMat(); int type = src.type(); if( src.isSubmatrix() && (borderType & BORDER_ISOLATED) == 0 ) { Size wholeSize; Point ofs; src.locateROI(wholeSize, ofs); int dtop = std::min(ofs.y, top); int dbottom = std::min(wholeSize.height - src.rows - ofs.y, bottom); int dleft = std::min(ofs.x, left); int dright = std::min(wholeSize.width - src.cols - ofs.x, right); src.adjustROI(dtop, dbottom, dleft, dright); top -= dtop; left -= dleft; bottom -= dbottom; right -= dright; } _dst.create( src.rows + top + bottom, src.cols + left + right, type ); Mat dst = _dst.getMat(); if(top == 0 && left == 0 && bottom == 0 && right == 0) { if(src.data != dst.data || src.step != dst.step) src.copyTo(dst); return; } borderType &= ~BORDER_ISOLATED; #if defined HAVE_IPP && IPP_DISABLE_BLOCK CV_IPP_CHECK() { typedef IppStatus (CV_STDCALL * ippiCopyMakeBorder)(const void * pSrc, int srcStep, IppiSize srcRoiSize, void * pDst, int dstStep, IppiSize dstRoiSize, int topBorderHeight, int leftBorderWidth); typedef IppStatus (CV_STDCALL * ippiCopyMakeBorderI)(const void * pSrc, int srcDstStep, IppiSize srcRoiSize, IppiSize dstRoiSize, int topBorderHeight, int leftborderwidth); typedef IppStatus (CV_STDCALL * ippiCopyConstBorder)(const void * pSrc, int srcStep, IppiSize srcRoiSize, void * pDst, int dstStep, IppiSize dstRoiSize, int topBorderHeight, int leftBorderWidth, void * value); IppiSize srcRoiSize = { src.cols, src.rows }, dstRoiSize = { dst.cols, dst.rows }; ippiCopyMakeBorder ippFunc = 0; ippiCopyMakeBorderI ippFuncI = 0; ippiCopyConstBorder ippFuncConst = 0; bool inplace = dst.datastart == src.datastart; if (borderType == BORDER_CONSTANT) { ippFuncConst = // type == CV_8UC1 ? (ippiCopyConstBorder)ippiCopyConstBorder_8u_C1R : bug in IPP 8.1 type == CV_16UC1 ? (ippiCopyConstBorder)ippiCopyConstBorder_16u_C1R : // type == CV_16SC1 ? (ippiCopyConstBorder)ippiCopyConstBorder_16s_C1R : bug in IPP 8.1 // type == CV_32SC1 ? (ippiCopyConstBorder)ippiCopyConstBorder_32s_C1R : bug in IPP 8.1 // type == CV_32FC1 ? (ippiCopyConstBorder)ippiCopyConstBorder_32f_C1R : bug in IPP 8.1 type == CV_8UC3 ? (ippiCopyConstBorder)ippiCopyConstBorder_8u_C3R : type == CV_16UC3 ? (ippiCopyConstBorder)ippiCopyConstBorder_16u_C3R : type == CV_16SC3 ? (ippiCopyConstBorder)ippiCopyConstBorder_16s_C3R : type == CV_32SC3 ? (ippiCopyConstBorder)ippiCopyConstBorder_32s_C3R : type == CV_32FC3 ? (ippiCopyConstBorder)ippiCopyConstBorder_32f_C3R : type == CV_8UC4 ? (ippiCopyConstBorder)ippiCopyConstBorder_8u_C4R : type == CV_16UC4 ? (ippiCopyConstBorder)ippiCopyConstBorder_16u_C4R : type == CV_16SC4 ? (ippiCopyConstBorder)ippiCopyConstBorder_16s_C4R : type == CV_32SC4 ? (ippiCopyConstBorder)ippiCopyConstBorder_32s_C4R : type == CV_32FC4 ? (ippiCopyConstBorder)ippiCopyConstBorder_32f_C4R : 0; } else if (borderType == BORDER_WRAP) { if (inplace) { CV_SUPPRESS_DEPRECATED_START ippFuncI = type == CV_32SC1 ? (ippiCopyMakeBorderI)ippiCopyWrapBorder_32s_C1IR : type == CV_32FC1 ? (ippiCopyMakeBorderI)ippiCopyWrapBorder_32s_C1IR : 0; CV_SUPPRESS_DEPRECATED_END } else { ippFunc = type == CV_32SC1 ? (ippiCopyMakeBorder)ippiCopyWrapBorder_32s_C1R : type == CV_32FC1 ? (ippiCopyMakeBorder)ippiCopyWrapBorder_32s_C1R : 0; } } else if (borderType == BORDER_REPLICATE) { if (inplace) { CV_SUPPRESS_DEPRECATED_START ippFuncI = type == CV_8UC1 ? (ippiCopyMakeBorderI)ippiCopyReplicateBorder_8u_C1IR : type == CV_16UC1 ? (ippiCopyMakeBorderI)ippiCopyReplicateBorder_16u_C1IR : type == CV_16SC1 ? (ippiCopyMakeBorderI)ippiCopyReplicateBorder_16s_C1IR : type == CV_32SC1 ? (ippiCopyMakeBorderI)ippiCopyReplicateBorder_32s_C1IR : type == CV_32FC1 ? (ippiCopyMakeBorderI)ippiCopyReplicateBorder_32f_C1IR : type == CV_8UC3 ? (ippiCopyMakeBorderI)ippiCopyReplicateBorder_8u_C3IR : type == CV_16UC3 ? (ippiCopyMakeBorderI)ippiCopyReplicateBorder_16u_C3IR : type == CV_16SC3 ? (ippiCopyMakeBorderI)ippiCopyReplicateBorder_16s_C3IR : type == CV_32SC3 ? (ippiCopyMakeBorderI)ippiCopyReplicateBorder_32s_C3IR : type == CV_32FC3 ? (ippiCopyMakeBorderI)ippiCopyReplicateBorder_32f_C3IR : type == CV_8UC4 ? (ippiCopyMakeBorderI)ippiCopyReplicateBorder_8u_C4IR : type == CV_16UC4 ? (ippiCopyMakeBorderI)ippiCopyReplicateBorder_16u_C4IR : type == CV_16SC4 ? (ippiCopyMakeBorderI)ippiCopyReplicateBorder_16s_C4IR : type == CV_32SC4 ? (ippiCopyMakeBorderI)ippiCopyReplicateBorder_32s_C4IR : type == CV_32FC4 ? (ippiCopyMakeBorderI)ippiCopyReplicateBorder_32f_C4IR : 0; CV_SUPPRESS_DEPRECATED_END } else { ippFunc = type == CV_8UC1 ? (ippiCopyMakeBorder)ippiCopyReplicateBorder_8u_C1R : type == CV_16UC1 ? (ippiCopyMakeBorder)ippiCopyReplicateBorder_16u_C1R : type == CV_16SC1 ? (ippiCopyMakeBorder)ippiCopyReplicateBorder_16s_C1R : type == CV_32SC1 ? (ippiCopyMakeBorder)ippiCopyReplicateBorder_32s_C1R : type == CV_32FC1 ? (ippiCopyMakeBorder)ippiCopyReplicateBorder_32f_C1R : type == CV_8UC3 ? (ippiCopyMakeBorder)ippiCopyReplicateBorder_8u_C3R : type == CV_16UC3 ? (ippiCopyMakeBorder)ippiCopyReplicateBorder_16u_C3R : type == CV_16SC3 ? (ippiCopyMakeBorder)ippiCopyReplicateBorder_16s_C3R : type == CV_32SC3 ? (ippiCopyMakeBorder)ippiCopyReplicateBorder_32s_C3R : type == CV_32FC3 ? (ippiCopyMakeBorder)ippiCopyReplicateBorder_32f_C3R : type == CV_8UC4 ? (ippiCopyMakeBorder)ippiCopyReplicateBorder_8u_C4R : type == CV_16UC4 ? (ippiCopyMakeBorder)ippiCopyReplicateBorder_16u_C4R : type == CV_16SC4 ? (ippiCopyMakeBorder)ippiCopyReplicateBorder_16s_C4R : type == CV_32SC4 ? (ippiCopyMakeBorder)ippiCopyReplicateBorder_32s_C4R : type == CV_32FC4 ? (ippiCopyMakeBorder)ippiCopyReplicateBorder_32f_C4R : 0; } } if (ippFunc || ippFuncI || ippFuncConst) { uchar scbuf[32]; scalarToRawData(value, scbuf, type); if ( (ippFunc && ippFunc(src.data, (int)src.step, srcRoiSize, dst.data, (int)dst.step, dstRoiSize, top, left) >= 0) || (ippFuncI && ippFuncI(src.data, (int)src.step, srcRoiSize, dstRoiSize, top, left) >= 0) || (ippFuncConst && ippFuncConst(src.data, (int)src.step, srcRoiSize, dst.data, (int)dst.step, dstRoiSize, top, left, scbuf) >= 0)) { CV_IMPL_ADD(CV_IMPL_IPP); return; } setIppErrorStatus(); } } #endif if( borderType != BORDER_CONSTANT ) copyMakeBorder_8u( src.ptr(), src.step, src.size(), dst.ptr(), dst.step, dst.size(), top, left, (int)src.elemSize(), borderType ); else { int cn = src.channels(), cn1 = cn; AutoBuffer<double> buf(cn); if( cn > 4 ) { CV_Assert( value[0] == value[1] && value[0] == value[2] && value[0] == value[3] ); cn1 = 1; } scalarToRawData(value, buf, CV_MAKETYPE(src.depth(), cn1), cn); copyMakeConstBorder_8u( src.ptr(), src.step, src.size(), dst.ptr(), dst.step, dst.size(), top, left, (int)src.elemSize(), (uchar*)(double*)buf ); } } /* dst = src */ CV_IMPL void cvCopy( const void* srcarr, void* dstarr, const void* maskarr ) { if( CV_IS_SPARSE_MAT(srcarr) && CV_IS_SPARSE_MAT(dstarr)) { CV_Assert( maskarr == 0 ); CvSparseMat* src1 = (CvSparseMat*)srcarr; CvSparseMat* dst1 = (CvSparseMat*)dstarr; CvSparseMatIterator iterator; CvSparseNode* node; dst1->dims = src1->dims; memcpy( dst1->size, src1->size, src1->dims*sizeof(src1->size[0])); dst1->valoffset = src1->valoffset; dst1->idxoffset = src1->idxoffset; cvClearSet( dst1->heap ); if( src1->heap->active_count >= dst1->hashsize*CV_SPARSE_HASH_RATIO ) { cvFree( &dst1->hashtable ); dst1->hashsize = src1->hashsize; dst1->hashtable = (void**)cvAlloc( dst1->hashsize*sizeof(dst1->hashtable[0])); } memset( dst1->hashtable, 0, dst1->hashsize*sizeof(dst1->hashtable[0])); for( node = cvInitSparseMatIterator( src1, &iterator ); node != 0; node = cvGetNextSparseNode( &iterator )) { CvSparseNode* node_copy = (CvSparseNode*)cvSetNew( dst1->heap ); int tabidx = node->hashval & (dst1->hashsize - 1); memcpy( node_copy, node, dst1->heap->elem_size ); node_copy->next = (CvSparseNode*)dst1->hashtable[tabidx]; dst1->hashtable[tabidx] = node_copy; } return; } cv::Mat src = cv::cvarrToMat(srcarr, false, true, 1), dst = cv::cvarrToMat(dstarr, false, true, 1); CV_Assert( src.depth() == dst.depth() && src.size == dst.size ); int coi1 = 0, coi2 = 0; if( CV_IS_IMAGE(srcarr) ) coi1 = cvGetImageCOI((const IplImage*)srcarr); if( CV_IS_IMAGE(dstarr) ) coi2 = cvGetImageCOI((const IplImage*)dstarr); if( coi1 || coi2 ) { CV_Assert( (coi1 != 0 || src.channels() == 1) && (coi2 != 0 || dst.channels() == 1) ); int pair[] = { std::max(coi1-1, 0), std::max(coi2-1, 0) }; cv::mixChannels( &src, 1, &dst, 1, pair, 1 ); return; } else CV_Assert( src.channels() == dst.channels() ); if( !maskarr ) src.copyTo(dst); else src.copyTo(dst, cv::cvarrToMat(maskarr)); } CV_IMPL void cvSet( void* arr, CvScalar value, const void* maskarr ) { cv::Mat m = cv::cvarrToMat(arr); if( !maskarr ) m = value; else m.setTo(cv::Scalar(value), cv::cvarrToMat(maskarr)); } CV_IMPL void cvSetZero( CvArr* arr ) { if( CV_IS_SPARSE_MAT(arr) ) { CvSparseMat* mat1 = (CvSparseMat*)arr; cvClearSet( mat1->heap ); if( mat1->hashtable ) memset( mat1->hashtable, 0, mat1->hashsize*sizeof(mat1->hashtable[0])); return; } cv::Mat m = cv::cvarrToMat(arr); m = cv::Scalar(0); } CV_IMPL void cvFlip( const CvArr* srcarr, CvArr* dstarr, int flip_mode ) { cv::Mat src = cv::cvarrToMat(srcarr); cv::Mat dst; if (!dstarr) dst = src; else dst = cv::cvarrToMat(dstarr); CV_Assert( src.type() == dst.type() && src.size() == dst.size() ); cv::flip( src, dst, flip_mode ); } CV_IMPL void cvRepeat( const CvArr* srcarr, CvArr* dstarr ) { cv::Mat src = cv::cvarrToMat(srcarr), dst = cv::cvarrToMat(dstarr); CV_Assert( src.type() == dst.type() && dst.rows % src.rows == 0 && dst.cols % src.cols == 0 ); cv::repeat(src, dst.rows/src.rows, dst.cols/src.cols, dst); } /* End of file. */
9cd01d26ee35f4b2ed2e4d7a5d3d89e8c90f2af2
3e067c51b5a4b007c95ac67b9e611a8438f8eb8f
/HashTable.cpp
4afbaf4c463ef7aa30eb0ede926cb648b5a7e055
[]
no_license
EpicDriveP3/hashTable
7007dd98adf93c023a112140d2dcc3575763e702
d1fe19a2a96bb3b53a8719f020dd5ab8bdd91a5e
refs/heads/master
2021-01-16T20:38:41.734494
2016-06-17T23:35:25
2016-06-17T23:35:25
61,407,964
0
0
null
null
null
null
UTF-8
C++
false
false
4,770
cpp
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: Student.cpp * Author: betolan * * Created on 4 de junio de 2016, 08:10 AM */ #include "HashTable.h" using namespace std; HashTable::HashTable(){ elements_for_bucket=(int*)malloc(sizeof(int)*sizeof(buckets)); } HashTable::HashTable(const HashTable& orig){} HashTable::~HashTable(){} void HashTable::Write(int key, string data){ int total=0; int total2=0; int indice; indice=key%buckets; for(int i=0; i<=indice; i++){ total=total+elements_for_bucket[i]; } for(int i=0; i<buckets; i++){ total2=total2+elements_for_bucket[i]; } ifstream inFile; inFile.open("HashTable.dat", ios::binary); ofstream outFile; outFile.open("temp.dat", ios::binary|ios::app); HashTable obj; HashTable obj2; obj2.key=key; obj2.data=(char*)malloc(sizeof(char)*sizeof(data)); strcpy(obj2.data, data.c_str()); int cont=0; bool first=true; if(total2==0){ outFile.write((char*)&obj2, sizeof(obj2)); elements_for_bucket[indice]++; } if(total==0 && total2!=0){ while(inFile.read((char*)&obj, sizeof(obj))){ if(first==true){ outFile.write((char*)&obj2, sizeof(obj2)); outFile.write((char*)&obj, sizeof(obj)); elements_for_bucket[indice]++; first=false; } else{ outFile.write((char*)&obj, sizeof(obj)); } } } else{ while(inFile.read((char*)&obj, sizeof(obj))){ cont++; if(total==cont){ outFile.write((char*)&obj, sizeof(obj)); outFile.write((char*)&obj2, sizeof(obj2)); elements_for_bucket[indice]++; } else{ outFile.write((char*)&obj, sizeof(obj)); } } } inFile.close(); outFile.close(); remove("HashTable.dat"); rename("temp.dat", "HashTable.dat"); } void HashTable::Display(){ cout<<"------------------------------------------"<<endl; ifstream inFile; inFile.open("HashTable.dat", ios::binary); HashTable obj; while(inFile.read((char*)&obj, sizeof(obj))){ cout<<" "<<"Key: "<<obj.key<<endl; cout<<" "<<"Data: "<<obj.data<<endl; cout<<endl; } cout<<"------------------------------------------"<<endl; inFile.close(); } void HashTable::Delete(int key){ HashTable obj; int indice; indice=key%buckets; ifstream inFile; inFile.open("HashTable.dat", ios::binary); ofstream outFile; outFile.open("temp.dat", ios::out|ios::binary); while(inFile.read((char*)&obj, sizeof(obj))){ if(obj.key!=key){ outFile.write((char*)&obj, sizeof(obj)); elements_for_bucket[indice]--; } } inFile.close(); outFile.close(); remove("HashTable.dat"); rename("temp.dat", "HashTable.dat"); } void HashTable::search(int key) { int total=0; int indice; indice=key%buckets; ifstream inFile; inFile.open("HashTable.dat", ios::binary); for(int i=0; i<indice; i++){ total=total+elements_for_bucket[i]; } HashTable obj; if(elements_for_bucket[indice]==0){ cout<<"No hay elementos en este bucket"<<endl; } else{ for(int i=0; i<total;i++){ inFile.read((char*)&obj, sizeof(obj)); } bool out=false; for(int i=0; i<elements_for_bucket[indice] && out==false; i++){ inFile.read((char*)&obj, sizeof(obj)); if(obj.key == key) { cout<<" "<<"Key: "<<obj.key<<endl; cout<<" "<<"Data: "<<obj.data<<endl; out=true; } } } inFile.close(); } void HashTable::WriteControl(){ ofstream outFile; outFile.open("Control.dat", ios::binary|ios::app); for(int i=0; i<buckets; i++){ outFile.write((char*)&elements_for_bucket[i], sizeof(elements_for_bucket[i])); } outFile.close(); } void HashTable::ReadControl(){ ifstream inFile; inFile.open("Control.dat", ios::binary); int temp=0; for(int i=0; i<buckets; i++){ inFile.read((char*)&temp, sizeof(temp)); elements_for_bucket[i]=temp; cout<<temp<<endl; } inFile.close(); }
[ "betolan@betolan-Alienware-14" ]
betolan@betolan-Alienware-14
85d9f6f966a0dcfc54ecf378b398ed07140f1299
3636175d49df1ebc5472f572da35099148859cd6
/source/core/shared_memory.h
909c640645ec80de1364a20de4b088689a4d07d1
[ "CC0-1.0" ]
permissive
lymanZerga11/multithreaded_order_matching_engine
62ea99fe752de04adbd716f15d6002850997bbb1
fa3f51bde2abbc3d625318aed1fc8a4ab400a70d
refs/heads/master
2021-03-22T05:04:40.495305
2018-01-29T23:07:56
2018-01-29T23:07:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,445
h
#ifndef _SHARED_MEMORY_H_ #define _SHARED_MEMORY_H_ #include <core/memory/virtual_memory.h> #ifdef __linux__ #elif _WIN32 #include <windows.h> #endif #include <string> #include <cstddef> namespace core { class SharedMemory { public: SharedMemory(); ~SharedMemory(); bool open(std::string name, std::size_t maxSize = DEFAULT_VIRTUAL_MEMORY_PAGE_SIZE, bool createFile = false, bool ipc = false, bool buffered = false); void append(void* buffer, std::size_t size); void write(void* buffer , std::size_t size, std::size_t writeOffset); void read(void* buffer, std::size_t size, std::size_t readOffset); void close(); std::size_t getSize() const { return m_size; } std::size_t getWrittenSize() const { return m_writtenSize; } std::size_t getReadSize() const { return m_readSize; } bool isOpen() const { bool ret = false; #ifdef __linux__ ret = m_buffer != nullptr; #elif _WIN32 ret = m_handle != INVALID_HANDLE_VALUE; #endif return ret; } private : char* m_buffer; std::size_t m_size; std::size_t m_writtenSize; std::size_t m_readSize; #ifdef __linux__ int m_fileDescriptor; #elif _WIN32 HANDLE m_handle; HANDLE m_fileHandle; #endif void copyMemory(void* from, void* to, std::size_t size); }; } // namespace #endif
72eb19df43815ee84c72c1807c3f15b1bbf01ccf
d14b5d78b72711e4614808051c0364b7bd5d6d98
/third_party/llvm-16.0/llvm/lib/Target/XCore/XCoreISelLowering.h
cfd0619cba8fd521b63fcf2ef738b08dcbf0c098
[ "Apache-2.0" ]
permissive
google/swiftshader
76659addb1c12eb1477050fded1e7d067f2ed25b
5be49d4aef266ae6dcc95085e1e3011dad0e7eb7
refs/heads/master
2023-07-21T23:19:29.415159
2023-07-21T19:58:29
2023-07-21T20:50:19
62,297,898
1,981
306
Apache-2.0
2023-07-05T21:29:34
2016-06-30T09:25:24
C++
UTF-8
C++
false
false
8,970
h
//===-- XCoreISelLowering.h - XCore DAG Lowering Interface ------*- 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 // //===----------------------------------------------------------------------===// // // This file defines the interfaces that XCore uses to lower LLVM code into a // selection DAG. // //===----------------------------------------------------------------------===// #ifndef LLVM_LIB_TARGET_XCORE_XCOREISELLOWERING_H #define LLVM_LIB_TARGET_XCORE_XCOREISELLOWERING_H #include "XCore.h" #include "llvm/CodeGen/SelectionDAG.h" #include "llvm/CodeGen/TargetLowering.h" namespace llvm { // Forward delcarations class XCoreSubtarget; namespace XCoreISD { enum NodeType : unsigned { // Start the numbering where the builtin ops and target ops leave off. FIRST_NUMBER = ISD::BUILTIN_OP_END, // Branch and link (call) BL, // pc relative address PCRelativeWrapper, // dp relative address DPRelativeWrapper, // cp relative address CPRelativeWrapper, // Load word from stack LDWSP, // Store word to stack STWSP, // Corresponds to retsp instruction RETSP, // Corresponds to LADD instruction LADD, // Corresponds to LSUB instruction LSUB, // Corresponds to LMUL instruction LMUL, // Corresponds to MACCU instruction MACCU, // Corresponds to MACCS instruction MACCS, // Corresponds to CRC8 instruction CRC8, // Jumptable branch. BR_JT, // Jumptable branch using long branches for each entry. BR_JT32, // Offset from frame pointer to the first (possible) on-stack argument FRAME_TO_ARGS_OFFSET, // Exception handler return. The stack is restored to the first // followed by a jump to the second argument. EH_RETURN, }; } //===--------------------------------------------------------------------===// // TargetLowering Implementation //===--------------------------------------------------------------------===// class XCoreTargetLowering : public TargetLowering { public: explicit XCoreTargetLowering(const TargetMachine &TM, const XCoreSubtarget &Subtarget); using TargetLowering::isZExtFree; bool isZExtFree(SDValue Val, EVT VT2) const override; unsigned getJumpTableEncoding() const override; MVT getScalarShiftAmountTy(const DataLayout &DL, EVT) const override { return MVT::i32; } /// LowerOperation - Provide custom lowering hooks for some operations. SDValue LowerOperation(SDValue Op, SelectionDAG &DAG) const override; /// ReplaceNodeResults - Replace the results of node with an illegal result /// type with new values built out of custom code. /// void ReplaceNodeResults(SDNode *N, SmallVectorImpl<SDValue>&Results, SelectionDAG &DAG) const override; /// getTargetNodeName - This method returns the name of a target specific // DAG node. const char *getTargetNodeName(unsigned Opcode) const override; MachineBasicBlock * EmitInstrWithCustomInserter(MachineInstr &MI, MachineBasicBlock *MBB) const override; bool isLegalAddressingMode(const DataLayout &DL, const AddrMode &AM, Type *Ty, unsigned AS, Instruction *I = nullptr) const override; /// If a physical register, this returns the register that receives the /// exception address on entry to an EH pad. Register getExceptionPointerRegister(const Constant *PersonalityFn) const override { return XCore::R0; } /// If a physical register, this returns the register that receives the /// exception typeid on entry to a landing pad. Register getExceptionSelectorRegister(const Constant *PersonalityFn) const override { return XCore::R1; } private: const TargetMachine &TM; const XCoreSubtarget &Subtarget; // Lower Operand helpers SDValue LowerCCCArguments(SDValue Chain, CallingConv::ID CallConv, bool isVarArg, const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const; SDValue LowerCCCCallTo(SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, bool isTailCall, const SmallVectorImpl<ISD::OutputArg> &Outs, const SmallVectorImpl<SDValue> &OutVals, const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const; SDValue getReturnAddressFrameIndex(SelectionDAG &DAG) const; SDValue getGlobalAddressWrapper(SDValue GA, const GlobalValue *GV, SelectionDAG &DAG) const; SDValue lowerLoadWordFromAlignedBasePlusOffset(const SDLoc &DL, SDValue Chain, SDValue Base, int64_t Offset, SelectionDAG &DAG) const; // Lower Operand specifics SDValue LowerLOAD(SDValue Op, SelectionDAG &DAG) const; SDValue LowerSTORE(SDValue Op, SelectionDAG &DAG) const; SDValue LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const; SDValue LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const; SDValue LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const; SDValue LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const; SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) const; SDValue LowerBR_JT(SDValue Op, SelectionDAG &DAG) const; SDValue LowerVAARG(SDValue Op, SelectionDAG &DAG) const; SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) const; SDValue LowerUMUL_LOHI(SDValue Op, SelectionDAG &DAG) const; SDValue LowerSMUL_LOHI(SDValue Op, SelectionDAG &DAG) const; SDValue LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const; SDValue LowerFRAME_TO_ARGS_OFFSET(SDValue Op, SelectionDAG &DAG) const; SDValue LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const; SDValue LowerINIT_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) const; SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) const; SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const; SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG) const; SDValue LowerATOMIC_LOAD(SDValue Op, SelectionDAG &DAG) const; SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) const; MachineMemOperand::Flags getTargetMMOFlags( const Instruction &I) const override; // Inline asm support std::pair<unsigned, const TargetRegisterClass *> getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const override; // Expand specifics SDValue TryExpandADDWithMul(SDNode *Op, SelectionDAG &DAG) const; SDValue ExpandADDSUB(SDNode *Op, SelectionDAG &DAG) const; SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const override; void computeKnownBitsForTargetNode(const SDValue Op, KnownBits &Known, const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth = 0) const override; SDValue LowerFormalArguments(SDValue Chain, CallingConv::ID CallConv, bool isVarArg, const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl, SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const override; SDValue LowerCall(TargetLowering::CallLoweringInfo &CLI, SmallVectorImpl<SDValue> &InVals) const override; SDValue LowerReturn(SDValue Chain, CallingConv::ID CallConv, bool isVarArg, const SmallVectorImpl<ISD::OutputArg> &Outs, const SmallVectorImpl<SDValue> &OutVals, const SDLoc &dl, SelectionDAG &DAG) const override; bool CanLowerReturn(CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg, const SmallVectorImpl<ISD::OutputArg> &ArgsFlags, LLVMContext &Context) const override; bool shouldInsertFencesForAtomic(const Instruction *I) const override { return true; } }; } #endif
57d8e008528b934a61cdae9a9a41d654712529d9
59675401ec69e867477f93b0c44e7587c431dfb6
/Project04_Lighting & Shading/function.cpp
2b4ff150d3ab9610feafd3d4c8f100788f613f79
[]
no_license
Ether-YiTseWu/Computer-Graphics
b4741fd9c7b09e7ee478012e4e851a926935559b
2b6efa150706ec1ea69b1159ec47b590fd3a3124
refs/heads/master
2023-02-21T12:27:48.032472
2020-06-25T08:10:43
2020-06-25T08:10:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
15,072
cpp
#include <stdio.h> #include <iostream> #include <windows.h> #include <math.h> #include <GL/glut.h> #include "parameter.h" #define CRT_SECURE_NO_WARNINGS GLUquadricObj* sphere = NULL, * cylind = NULL, * disk; int style = 4; // 4-windows mode // Procedure to initialize the working environment. void myinit() { glClearColor(0.0, 0.0, 0.0, 1.0); // set the background color BLACK /*Clear the Depth & Color Buffers */ glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glShadeModel(GL_SMOOTH); glEnable(GL_DEPTH_TEST); /*Enable depth buffer for shading computing */ if (sphere == NULL) { sphere = gluNewQuadric(); gluQuadricDrawStyle(sphere, GLU_FILL); gluQuadricNormals(sphere, GLU_SMOOTH); } if (cylind == NULL) { cylind = gluNewQuadric(); gluQuadricDrawStyle(cylind, GLU_FILL); gluQuadricNormals(cylind, GLU_SMOOTH); } if (disk == NULL) { disk = gluNewQuadric(); gluQuadricDrawStyle(disk, GLU_FILL); gluQuadricNormals(disk, GLU_SMOOTH); } glEnable(GL_NORMALIZE); /*Enable mornalization */ glEnable(GL_LIGHTING); /*Enable lighting effects */ glEnable(GL_LIGHT0); /*Turn on light0 */ glEnable(GL_LIGHT1); /*Turn on light1 */ /*-----Define light0 ---------*/ glLightfv(GL_LIGHT0, GL_DIFFUSE, lit_diffuse); glLightfv(GL_LIGHT0, GL_SPECULAR, lit_specular); /*-----Define light1 ---------*/ glLightfv(GL_LIGHT1, GL_DIFFUSE, lit1_diffuse); glLightfv(GL_LIGHT1, GL_SPECULAR, lit_specular); /*-----Define some global lighting status -----*/ glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE); /* local viewer */ glLightModelfv(GL_LIGHT_MODEL_AMBIENT, global_ambient); /*global ambient*/ /*-----Enable face culling -----*/ glCullFace(GL_BACK); glEnable(GL_CULL_FACE); } void sun() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Define the current eye position and the eye-coordinate system glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glRotatef(head, 0.0, 1.0, 0.0); // Transformation in Eye coord. sys glRotatef(roll, 0.0, .0, 1.0); glRotatef(Epitch, 1.0, 0.0, 0.0); glTranslatef(0.0, up, 0.0); glTranslatef(-right, 0.0, 0.0); glTranslatef(0.0, 0.0, -zoom); // Draw the Directional light ------------- glLightfv(GL_LIGHT1, GL_POSITION, lit1_position); // fixed position in eye space glTranslatef(-0.5, 1.0, -2.0); glDisable(GL_LIGHTING); glColor3f(0.80, 0.80, 0.0); glutSolidSphere(0.3, 12, 12); } void make_view(int x) { sun(); switch (x) { case 1: // X direction parallel viewing gluLookAt(eyeDx, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0); break; case 2: // Y direction parallel viewing gluLookAt(0.0, eyeDy, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0); break; case 3: // z direction parallel viewing gluLookAt(0.0, 0.0, eyeDz, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0); break; case 4: // Perspective /* In this sample program, eye position and Xe, Ye, Ze are computed by ourselves. Therefore, use them directly; no trabsform is applied upon eye coordinate system */ gluLookAt(30.0, 13.0, 20.0, 4.0, 4.0, 0.0, 0.0, 1.0, 0.0); // Define Viewing Matrix break; } } void make_projection(int x) { glMatrixMode(GL_PROJECTION); glLoadIdentity(); if (x == 4) gluPerspective(90.0, (double)width / (double)height, 1.5, 50.0); else glOrtho(-40.0, 40.0, -40.0 * (float)height / (float)width, 40.0 * (float)height / (float)width, -0.0, 100.0); glMatrixMode(GL_MODELVIEW); } void my_reshape(int w, int h) { width = w; height = h; glViewport(0, 0, w, h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(90.0, (double)w / (double)h, 1.5, 50.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } void draw_cube() { int i; float range; for (i = 0; i < 6; i++) { // draw the six faces one by one range = 1.0; glNormal3fv(normal[i]); glBegin(GL_POLYGON); // Draw the face glVertex3fv(points[face[i][0]]); glVertex3fv(points[face[i][1]]); glVertex3fv(points[face[i][2]]); glVertex3fv(points[face[i][3]]); glEnd(); } } void draw_obstacles() { int i; float range; // Obstacles 1 glPushMatrix(); glTranslatef(38, 1, -5); glRotatef(-40, 0, 1, 0); glScalef(2, 3, 40); for (int i = 0; i < 6; i++) { range = 1.0; glNormal3fv(normal[i]); glBegin(GL_POLYGON); glVertex3fv(points[face[i][0]]); glVertex3fv(points[face[i][1]]); glVertex3fv(points[face[i][2]]); glVertex3fv(points[face[i][3]]); glEnd(); } glPopMatrix(); // Obstacles 2 glPushMatrix(); glTranslatef(10, 1, 25); glRotatef(-130, 0, 1, 0); glScalef(2, 3, 25); for (int i = 0; i < 6; i++) { range = 1.0; glNormal3fv(normal[i]); glBegin(GL_POLYGON); glVertex3fv(points[face[i][0]]); glVertex3fv(points[face[i][1]]); glVertex3fv(points[face[i][2]]); glVertex3fv(points[face[i][3]]); glEnd(); } glPopMatrix(); } void display() { int i, j; //gluLookAt(30.0, 13.0, 20.0, 4.0, 4.0, 0.0, 0.0, 1.0, 0.0); // Define Viewing Matrix // Draw the POINT light--------------- glPushMatrix(); glTranslatef(16.0, 0.0, 16.0); // Move to [8, 0, 8] glPushMatrix(); glTranslatef(lit2_position[0], lit2_position[1], lit2_position[2]); glColor3f(1.0, 1.0, 1.0); glutWireSphere(0.5, 2, 2); glPopMatrix(); glEnable(GL_LIGHTING); // Turn on lighting glLightfv(GL_LIGHT2, GL_POSITION, lit2_position); // Redefine position and direction of light2 glLightfv(GL_LIGHT2, GL_AMBIENT, lit2_AMBIENT); glLightfv(GL_LIGHT2, GL_DIFFUSE, lit2_DIFFUSE); glLightfv(GL_LIGHT2, GL_SPECULAR, lit2_SPECULAR); glPopMatrix(); //----------------------------------------------------------------------------------------------------------------- // Draw the floor glMaterialfv(GL_FRONT, GL_DIFFUSE, flr_diffuse); // diffuse color glMaterialfv(GL_FRONT, GL_SPECULAR, flr_specular); glMaterialfv(GL_FRONT, GL_AMBIENT, flr_ambient); glNormal3f(0.0, 1.0, 0.0); for (i = -35; i <= 35; i++) { for (j = -35; j <= 35; j++) { glBegin(GL_POLYGON); glVertex3f(i * 2.0 + 0.0, 0.0, j * 2.0 + 0.0); glVertex3f(i * 2.0 + 0.0, 0.0, j * 2.0 + 2.0); glVertex3f(i * 2.0 + 2.0, 0.0, j * 2.0 + 2.0); glVertex3f(i * 2.0 + 2.0, 0.0, j * 2.0 + 0.0); glEnd(); } } // obstacles glPushMatrix(); //glLoadIdentity(); glMaterialfv(GL_FRONT, GL_AMBIENT, obstacle_ambient); glMaterialfv(GL_FRONT, GL_SPECULAR, obstacle_specular); glMaterialfv(GL_FRONT, GL_DIFFUSE, obstacle_diffuse); glMaterialf(GL_FRONT, GL_SHININESS, obstacle_shininess); glNormal3f(0.0, 1.0, 0.0); draw_obstacles(); glPopMatrix(); // Define robot material properties if (countRobotMa % 3 == 0) { glMaterialfv(GL_FRONT, GL_AMBIENT, robot_ambient); glMaterialfv(GL_FRONT, GL_SPECULAR, robot_specular); glMaterialfv(GL_FRONT, GL_DIFFUSE, robot_diffuse); glMaterialf(GL_FRONT, GL_SHININESS, robot_shininess); } else if (countRobotMa % 3 == 1) { glMaterialfv(GL_FRONT, GL_AMBIENT, robot1_ambient); glMaterialfv(GL_FRONT, GL_SPECULAR, robot1_specular); glMaterialfv(GL_FRONT, GL_DIFFUSE, robot1_diffuse); glMaterialf(GL_FRONT, GL_SHININESS, robot1_shininess); } else if (countRobotMa % 3 == 2) { glMaterialfv(GL_FRONT, GL_AMBIENT, robot2_ambient); glMaterialfv(GL_FRONT, GL_SPECULAR, robot2_specular); glMaterialfv(GL_FRONT, GL_DIFFUSE, robot2_diffuse); glMaterialf(GL_FRONT, GL_SHININESS, robot2_shininess); } if (countRobotEmi % 2 == 0) robotEmission[1] = 0.0; else if (countRobotEmi % 2 == 1) robotEmission[1] = 0.05; glMaterialfv(GL_FRONT, GL_EMISSION, robotEmission); // Draw the legs glPushMatrix(); // initial coordinate system glPushMatrix(); // initial coordinate system glPushMatrix(); // initial coordinate system glTranslatef(position[0], position[1] - 2, position[2] + 1); glRotatef(self_ang, 0, 1, 0); gluSphere(sphere, 1, 7, 7); glPushMatrix(); // right Knee coordinate system glTranslatef(0, -1, 0); glRotatef(knee_ang_small, 0, 0, 1); glScalef(1, 2, 1); draw_cube(); // right small legs glPopMatrix(); // Knee coordinate system glTranslatef(0, 1, 0); glRotatef(knee_ang_big, 0, 0, 1); glScalef(1, 2, 1); draw_cube(); // right big legs glPopMatrix(); // initial coordinate system glTranslatef(position[0], position[1] - 2, position[2] - 1); glRotatef(self_ang, 0, 1, 0); gluSphere(sphere, 1, 7, 7); glPushMatrix(); // left Knee coordinate system glTranslatef(0, -1, 0); glRotatef(knee_ang_small, 0, 0, 1); glScalef(1, 2, 1); draw_cube(); // left small legs glPopMatrix(); // left Knee coordinate system glTranslatef(0, 1, 0); glRotatef(knee_ang_big, 0, 0, 1); glScalef(1, 2, 1); draw_cube(); // left big legs // Draw the robot body which is a cube glPopMatrix(); // initial coordinate system glTranslatef(position[0], position[1] + 2, position[2]); glRotatef(self_ang, 0.0, 1.0, 0.0); glScalef(5, 4, 5); draw_cube(); // Draw the SPOT LIGHT glTranslatef(0.2, 1.1, 0); glRotatef(lit_angle+90, 0.0, 1.0, 0.0); glColor3f(1.0, 0.0, 0.0); glutWireSphere(0.2, 8, 8); glEnable(GL_LIGHTING); // Turn on lighting glLightfv(GL_LIGHT0, GL_POSITION, lit_position); // Redefine position and direction of light0 glLightfv(GL_LIGHT0, GL_SPOT_DIRECTION, lit2_direction); glLightf(GL_LIGHT0, GL_SPOT_CUTOFF, lit_cutoff); glLightf(GL_LIGHT0, GL_SPOT_EXPONENT, lit_exponent); // Draw the head glPopMatrix(); // initial coordinate system glTranslatef(position[0], position[1] + 5, position[2]); glRotatef(self_ang, 0.0, 1.0, 0.0); glPushMatrix(); // head coordinate system glPushMatrix(); // head coordinate system glScalef(3, 2, 3); draw_cube(); // Draw the hands glPopMatrix(); // head coordinate system glColor3f(0.6, 0.6, 0); glTranslatef(0, -2.5, 2.5); gluSphere(sphere, 0.3, 7, 7); glPushMatrix(); // hand swing coordinate system glColor3f(0.0, 0.6, 0.6); glPopMatrix(); // hand swing coordinate system glRotatef(swing_ang, 0.0, 0.0, 1.0); glTranslatef(0, -1.0, 0); glScalef(1, 2, 2); gluCylinder(cylind, 0.5, 0.5, 0.5, 26, 3); glPopMatrix(); // head coordinate system glColor3f(0.6, 0.6, 0); glTranslatef(0, -2.5, -2.5); gluSphere(sphere, 0.3, 7, 7); glPushMatrix(); // hand swing coordinate system glColor3f(0.0, 0.6, 0.6); glPopMatrix(); // hand swing coordinate system glRotatef(swing_ang, 0.0, 0.0, 1.0); glTranslatef(0.0, -1.0, -1.0); glScalef(1, 2, 2); gluCylinder(cylind, 0.5, 0.5, 0.5, 26, 3); // Swap the back buffer to the front glutSwapBuffers(); glFlush(); // Display the results } // Display callback procedure to draw the scene void display_() { // Clear previous frame and the depth buffer //glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Drawing style 5:4-windows, 4:perspective, 3:z direction, 2:y direction, 1:x-dirtection switch (style) { case 5: glViewport(width / 2, 0, width / 2, height / 2); make_view(4); make_projection(4); display(); glViewport(0, height / 2, width / 2, height / 2); make_view(1); make_projection(1); display(); make_view(1); glViewport(width / 2, height / 2, width / 2, height / 2); make_view(2); display(); make_view(2); glViewport(0, 0, width / 2, height / 2); make_view(3); display(); make_view(3); break; case 4: glViewport(0, 0, width, height); make_view(4); make_projection(4); display(); break; case 3: glViewport(0, 0, width, height); make_view(3); make_projection(1); display(); break; case 2: glViewport(0, 0, width, height); make_view(2); make_projection(1); display(); break; case 1: glViewport(0, 0, width, height); make_view(1); make_projection(1); display(); break; } //glutSwapBuffers(); // Swap the back buffer to the front return; } // Keyboard callback func. When a 'q' key is pressed, exit. void key_func(unsigned char key, int x, int y) { if (key == '`' || key == '~') exit(0); if (key == 'r' || key == 'R') head = roll = Epitch = Wpitch = up = right = zoom = 0.0, lit_cutoff = 37.0, lit_exponent = 4.0, lit1_position[0] = 10; if (key == 'q') lit_exponent += 0.5; if (key == 'e') lit_exponent -= 0.5; if (key == 't') lit_cutoff += 0.5; if (key == 'y') lit_cutoff -= 0.5; // Rotate light position if (key == ' ') lit_angle += 5.0; if (key == 'u') lit1_position[0] += 0.5; if (key == 'i') lit1_position[0] -= 0.5; // On/off Robot Emission if (key == 'o') countRobotEmi++; // Change Robot Material if (key == 'p') countRobotMa++; // Walking if (key == 'w') { position[0] += Step * cos(self_ang * PI / 180.0); position[2] -= Step * sin(self_ang * PI / 180.0); } // move car back b-key else if (key == 's') { position[0] -= Step * cos(self_ang * PI / 180.0); position[2] += Step * sin(self_ang * PI / 180.0); } // make a left turn else if (key == 'a') { self_ang += 10.0; if (self_ang > 360.0) self_ang -= 360.0; } // make a right turn else if (key == 'd') { self_ang += -10.0; if (self_ang < 0.0) self_ang += 360.0; } if (key == 'n' || key == 'N') right += 0.5; else if (key == 'b' || key == 'B') right -= 0.5; if (key == 'x' || key == 'X') up += 0.5; else if (key == 'z' || key == 'Z') up -= 0.5; if (key == 'c' || key == 'C') zoom -= 0.5; else if (key == 'v' || key == 'V') zoom += 0.5; if (key == 'g') Epitch += 10.0; else if (key == 'f') Epitch -= 10.0; if (key == 'j') head += 10.0; else if (key == 'h') head -= 10.0; if (key == 'k') roll += 10.0; else if (key == 'l') roll -= 10.0; if (key == '1') countSun ++; if (key == '2') countPoint ++; if (key == '3') countSpot ++; if (key == '4') countPointColor++; if (key == '6') style = 1; if (key == '7') style = 2; if (key == '8') style = 3; if (key == '9') style = 4; if (key == '0') style = 5; if (countSun % 2 == 0) glEnable(GL_LIGHT1); else glDisable(GL_LIGHT1); if (countPoint % 2 == 0) glEnable(GL_LIGHT0); else glDisable(GL_LIGHT0); if (countSpot % 2 == 0) glEnable(GL_LIGHT2); else glDisable(GL_LIGHT2); if (countPointColor % 2 == 0) for (int i = 0; i < 3; i++) lit2_DIFFUSE[i] = 1; else lit2_DIFFUSE[0] = 0; if (key == '5') { lit2_DIFFUSE[0] = 1, lit2_DIFFUSE[1] = lit2_DIFFUSE[2] = 0; make_view(style); display_(); Sleep(100); lit2_DIFFUSE[1] = 1, lit2_DIFFUSE[0] = lit2_DIFFUSE[2] = 0; make_view(style); display_(); Sleep(100); lit2_DIFFUSE[2] = 1, lit2_DIFFUSE[0] = lit2_DIFFUSE[1] = 0; make_view(style); display_(); Sleep(100); lit2_DIFFUSE[1] = 1, lit2_DIFFUSE[0] = lit2_DIFFUSE[2] = 0; make_view(style); display_(); Sleep(100); lit2_DIFFUSE[0] = 1, lit2_DIFFUSE[1] = lit2_DIFFUSE[2] = 0; make_view(style); display_(); Sleep(100); for (int i = 0; i < 3; i++) lit2_DIFFUSE[i] = 1; } display_(); } // Main procedure which defines the graphics environment,
986b5a31d08af26b3c4f894f41f595d990bdb294
eba078a18f3cffd5b80ee66155051cca17a3baa0
/piezo_speaker/speaker.ino
2fb589d835490995fbb16559f0eee22684eca479
[]
no_license
msheehan0109/Code
656ba3971ca2f96a4e9386a9516243220e9ba2d1
32469185b132b32f0cc1c92bb6dafe99a010c672
refs/heads/master
2021-04-25T18:22:55.784783
2018-04-13T13:27:47
2018-04-13T13:27:47
108,302,668
0
0
null
null
null
null
UTF-8
C++
false
false
136
ino
void setup() { pinMode(13, OUTPUT); } void loop() { digitalWrite(13, HIGH); delay(1); digitalWrite(13, LOW); delay(1); }
b980e4667be0f395a07e1924d59c6ff62a3b96e7
2102757001bf9cc63f8bac13d5b4834e361b3352
/ITP1/5_A.cpp
35cd9019ca754c2a80daa79d5de9726a50491d7a
[]
no_license
shinter61/competition
79b181426813308133eedfd8cf94252afe3f26e8
8799c9b807659a7a0a2de179e7aa49537d9556f7
refs/heads/main
2023-07-30T15:28:25.617968
2021-09-12T12:19:22
2021-09-12T12:19:22
405,633,656
0
0
null
null
null
null
UTF-8
C++
false
false
727
cpp
#include <bits/stdc++.h> using namespace std; int main() { vector< vector <int> > input(1000, vector<int>(2)); for (int i = 0; i < input.size(); i++) { cin >> input[i][0] >> input[i][1]; cout << "hello" << endl; if (input[i][0] == 0 && input[i][1] == 0) break; cout << "world" << endl; } cout << "this is interval" << endl; for (int i = 0; i < input.size(); i++) { cout << "are you ready" << endl; if (input[i][0] == 0 && input[i][1] == 0) break; cout << "whooooo" << endl; for (int j = 0; j < input[i][0]; j++) { string s = ""; for (int k = 0; j < input[i][1]; k++) { s += "#"; } cout << s << endl; } cout << "\n" << endl; } return 0; }
44a15efd57a4f8738b60334413aca66d217169c5
ef8a3418cd5bdcce4265f489823b299a7a67fe9b
/car class (OOP)/CAR.cpp
4656c254045fcc2ffd859b4c53fd6c38ae04e51c
[]
no_license
MahmoodMakhloof/CPP-OOP
2d98720be7a0a82a63dc4b705abf0a0bc0285d68
0860211f75da8af399976d861115d88aee1951b0
refs/heads/master
2023-01-08T12:30:55.895195
2020-11-02T08:31:59
2020-11-02T08:31:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
873
cpp
/* * CAR.cpp * * Created on: 12\5\2020 * Author: Bob */ #include "CAR.h" int CAR::ctr = 0; //constructor : code executed in the start of object life time CAR::CAR(string m ,int l ,string c):maker(m),model(l),color(c) //initializing list { ctr++; cout<<"the car "<<ctr<<" is initialized\n"; } //overloading constructor (default) CAR::CAR():maker("Honda"),model(2020),color("White") //initializing list { ctr++; cout<<"the car "<<ctr<<" is initialized\n"; } //destructor : code executed in the end of object life time CAR::~CAR() { cout <<"car "<<ctr<<" out of scope , Goodbye\n"; ctr--; } void CAR::setmaker(string mak) { maker = mak; } string CAR::getmaker() { return maker; } void CAR::setmodel(int mod) { model = mod; } int CAR::getmodel() { return model; } void CAR::setcolor(string c) { color = c; } string CAR::getcolor() { return color; }
a31c345d817c7c7b780ca14aea9b4d4c556d567c
3cde95eb79ef19d390023e75c71209fec9ec57ce
/ds/audioEncoding.cpp
3d00b5f63498f6058d3814ee5f218b397942fd44
[ "Apache-2.0" ]
permissive
BobDeng1974/rdk-devicesettings
d002fee5584dbcea5cd2ebe82da0b47f7bb5e8fa
b34ed545b533a0cf4d29d221cc23daad47f32644
refs/heads/master
2020-11-28T07:20:41.199755
2018-07-25T07:34:07
2018-07-28T21:30:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,987
cpp
/* * If not stated otherwise in this file or this component's Licenses.txt file the * following copyright and licenses apply: * * Copyright 2016 RDK Management * * 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. */ /** * @file audioEncoding.cpp * @brief This file contains implementation of AudioEncoding class methods, * support functions and variable assignments to manage the audio encoding types. */ /** * @defgroup devicesettings * @{ * @defgroup ds * @{ **/ #include "audioEncoding.hpp" #include "audioOutputPortConfig.hpp" #include "illegalArgumentException.hpp" #include "dsTypes.h" #include "dsUtl.h" #include <string.h> #include "dslogger.h" namespace { const char *_names[] = { "NONE", "DISPLAY", "PCM", "AC3", "EAC3", }; inline const bool isValid(int id) { return dsAudioEncoding_isValid(id); } } namespace device { typedef int _SafetyCheck[(dsUTL_DIM(_names) == dsAUDIO_ENC_MAX) ? 1 : -1]; const int AudioEncoding::kNone = dsAUDIO_ENC_NONE; const int AudioEncoding::kDisplay = dsAUDIO_ENC_DISPLAY; const int AudioEncoding::kPCM = dsAUDIO_ENC_PCM; const int AudioEncoding::kAC3 = dsAUDIO_ENC_AC3; const int AudioEncoding::kMax = dsAUDIO_ENC_MAX; /** * @addtogroup dssettingsaudencodingapi * @{ */ /** * @fn AudioEncoding::getInstance(int id) * @brief This function gets an AudioEncoding instance against the id parameter, only if the id * passed is valid. * * @param[in] id Indicates the id against which the AudioEncoding instance is required. The id * is used to identify the audio encoding types. * * @return Returns AudioEncoding instance if the id is valid else throws an IllegalArgumentException. */ const AudioEncoding & AudioEncoding::getInstance(int id) { if (::isValid(id)) { return AudioOutputPortConfig::getInstance().getEncoding(id); } else { throw IllegalArgumentException(); } } /** * @fn AudioEncoding::getInstance(const std::string &name) * @brief This function gets an AudioEncoding instance against the specified name, only if the name * passed is valid. * * @param[in] name Indicates the name against which the AudioEncoding instance is required and it is also * used to identify the audio encoding types. * * @return Returns AudioEncoding instance if the name is valid else throws an IllegalArgumentException. */ const AudioEncoding & AudioEncoding::getInstance(const std::string &name) { for (size_t i = 0; i < dsUTL_DIM(_names); i++) { if (name.compare(_names[i]) == 0) { return AudioEncoding::getInstance(i); } } throw IllegalArgumentException(); } /** * @fn AudioEncoding::AudioEncoding(int id) * @brief This function is the default constructor for AudioEncoding. It initializes the instance with * the id passed as input. If the id parameter is invalid then it throws an IllegalArgumentException. * * @param[in] id Indicates the audio encoding type. * <ul> * <li> id 0 indicates encoding type None * <li> id 1 indicates digital audio encoding format * <li> id 2 indicates PCM encoding type * <li> id 3 indicates AC3 encoding type * </ul> * * @return None */ AudioEncoding::AudioEncoding(int id) { if (::isValid(id)) { _id = id; _name = std::string(_names[id]); } else { throw IllegalArgumentException(); } } /** * @fn AudioEncoding::~AudioEncoding() * @brief This function is the default destructor of AudioEncoding class. * * @return None */ AudioEncoding::~AudioEncoding() { } } /** @} */ /** @} */ /** @} */
4c6be74d65ae4b0cb9b2b560ef532e20b9b8c6fb
009108564b404256fc5a1c5626ae0098cf1adda3
/Rect.cpp
51751a3fb830fa9a3e5419368d11e50c41bb7439
[]
no_license
AD87/Super-Smash-TV
7235130d800160d5c15d6ae7cebbdd4952b40d43
a534a796c1ffdab9355c3600de4e13eb03aba55b
refs/heads/master
2023-07-21T03:16:58.937980
2016-03-26T21:30:19
2016-03-26T21:30:19
54,674,992
1
3
null
2023-07-15T16:56:36
2016-03-24T21:20:22
C++
UTF-8
C++
false
false
728
cpp
#include "Rect.h" #include "Vec2.h" Rect::Rect(){ m_minX = 0; m_maxX = 0; m_minY = 0; m_maxY = 0; } Rect::Rect(float minX, float maxX, float minY, float maxY){ m_minX = minX; m_maxX = maxX; m_minY = minY; m_maxY = maxY; } bool Rect::intersects(const Rect& otherRect)const{ return ((m_maxX > otherRect.m_minX) && (otherRect.m_maxX > m_minX) && (m_maxY > otherRect.m_minY) && (otherRect.m_maxY > m_minY)); } Rect Rect::scale(float number)const{ Vec2f centre((m_maxX + m_minX)*0.5f, (m_maxY + m_minY)*0.5f); float w = m_maxX - m_minX; float h = m_maxY - m_minY; return Rect(centre.x - w*0.5f*number, centre.x + w*0.5f*number, centre.y - h*0.5f*number, centre.y + h*0.5f*number); }
39de2dddee8d0801ec5e6a8c28e9692e8f627d85
d2fb019e63eb66f9ddcbdf39d07f7670f8cf79de
/groups/bsl/bsl+bslhdrs/bsl_cassert.h
b6a641b54d60993677b7416878b6c8cbb4fb36fa
[ "MIT" ]
permissive
gosuwachu/bsl
4fa8163a7e4b39e4253ad285b97f8a4d58020494
88cc2b2c480bcfca19e0f72753b4ec0359aba718
refs/heads/master
2021-01-17T05:36:55.605787
2013-01-15T19:48:00
2013-01-15T19:48:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,089
h
// bsl_cassert.h -*-C++-*- #ifndef INCLUDED_BSL_CASSERT #define INCLUDED_BSL_CASSERT #ifndef INCLUDED_BSLS_IDENT #include <bsls_ident.h> #endif BSLS_IDENT("$Id: $") //@PURPOSE: Provide functionality of the corresponding C++ Standard header. // //@SEE_ALSO: package bsl+stdhdrs // //@DESCRIPTION: Provide types, in the 'bsl' namespace, equivalent to those // defined in the corresponding C++ standard header. Include the native // compiler-provided standard header, and also directly include Bloomberg's // implementation of the C++ standard type (if one exists). Finally, place the // included symbols from the 'std' namespace (if any) into the 'bsl' namespace. #ifndef INCLUDED_BSLS_NATIVESTD #include <bsls_nativestd.h> #endif #include <cassert> #endif // ---------------------------------------------------------------------------- // Copyright (C) 2012 Bloomberg L.P. // // 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. // ----------------------------- END-OF-FILE ----------------------------------
1e414b56b69caee324a65e7ddbe5abf5c0ba2501
b22588340d7925b614a735bbbde1b351ad657ffc
/athena/Trigger/TrigAnalysis/TrigInDetAnalysis/TrigInDetAnalysis/TIDAEvent.h
1e59ed7a037ed633e644ba8b76f548329968e20d
[]
no_license
rushioda/PIXELVALID_athena
90befe12042c1249cbb3655dde1428bb9b9a42ce
22df23187ef85e9c3120122c8375ea0e7d8ea440
refs/heads/master
2020-12-14T22:01:15.365949
2020-01-19T03:59:35
2020-01-19T03:59:35
234,836,993
1
0
null
null
null
null
UTF-8
C++
false
false
3,965
h
// emacs: this is -*- c++ -*- /* Copyright (C) 2002-2018 CERN for the benefit of the ATLAS collaboration */ // // @file TIDAEvent.h // // Basic event class to contain a vector of // chains for trigger analysis // // // $Id: TIDAEvent.h, v0.0 Mon 1 Feb 2010 11:43:51 GMT sutt $ #ifndef TRIGINDETANALYSIS_TIDAEVENT_H #define TRIGINDETANALYSIS_TIDAEVENT_H #include <iostream> #include <vector> #include <string> #include "TrigInDetAnalysis/TIDAChain.h" #include "TrigInDetAnalysis/TIDAVertex.h" //#include "TrigInDetTruthEvent/TrigInDetTrackTruthMap.h" #include "TObject.h" namespace TIDA { class Event : public TObject { public: Event(); virtual ~Event(); /// accessors void run_number(unsigned r) { m_run_number = r; } void event_number(unsigned long long e) { m_event_number = e; } void lumi_block(unsigned lb) { m_lumi_block = lb; } void time_stamp(unsigned t) { m_time_stamp = t; } void bunch_crossing_id(unsigned b) { m_bunch_crossing_id = b; } void mu(double m) { m_mu = m;} unsigned run_number() const { return m_run_number; } unsigned long long event_number() const { return m_event_number; } unsigned lumi_block() const { return m_lumi_block; } unsigned time_stamp() const { return m_time_stamp; } unsigned bunch_crossing_id() const { return m_bunch_crossing_id; } /// FIXME: what is this ? need a comment describing any not /// descriptive variable name double mu() const { return m_mu; } /// vertex multiplicity ? /// NB all these could be avoided simply be inheriting /// from and std::vector<TIDA::Chain> rather than /// a member variable /// number of chains added to this event unsigned size() const { return m_chains.size(); } /// methods to add and access chains void addChain(const std::string& chainname) { m_chains.push_back(TIDA::Chain(chainname)); } void addVertex(const TIDA::Vertex& v) { m_vertices.push_back(v); } const std::vector<TIDA::Chain>& chains() const { return m_chains; }; std::vector<TIDA::Chain>& chains() { return m_chains; }; //void setTruthMap(TrigInDetTrackTruthMap truthmap) { // m_truthmap = truthmap; //} /// clear the event void clear() { m_chains.clear(); m_vertices.clear(); } /// get the last chain from the vector TIDA::Chain& back() { return m_chains.back(); } // iterators std::vector<TIDA::Chain>::iterator begin() { return m_chains.begin(); } std::vector<TIDA::Chain>::iterator end() { return m_chains.end(); } std::vector<TIDA::Chain>::const_iterator begin() const { return m_chains.begin(); } std::vector<TIDA::Chain>::const_iterator end() const { return m_chains.end(); } /// vector operator TIDA::Chain& operator[](int i) { return m_chains.at(i); } const std::vector<TIDA::Vertex>& vertices() const { return m_vertices; } std::vector<std::string> chainnames() const; void erase( const std::string& name ); private: unsigned m_run_number; unsigned long long m_event_number; unsigned m_lumi_block; unsigned m_time_stamp; unsigned m_bunch_crossing_id; double m_mu; /// vertex multiplicity ? /// trigger chain information std::vector<TIDA::Chain> m_chains; std::vector<TIDA::Vertex> m_vertices; ClassDef(TIDA::Event,4) }; } inline std::ostream& operator<<( std::ostream& s, const TIDA::Event& t ) { s << "Event run: " << t.run_number() << "\tevent: " << t.event_number() << "\tlb: " << t.lumi_block() << "\tbc: " << t.bunch_crossing_id() << "\ttime: " << t.time_stamp(); for ( unsigned i=0 ; i<t.vertices().size() ; i++ ) s << "\n" << t.vertices()[i]; for ( unsigned i=0 ; i<t.chains().size() ; i++ ) s << "\n" << t.chains()[i]; return s; } #endif // TRIGINDETANALYSIS_TIDAEVENT_H
5d40a4d43db89466913bea18cef002b248c96826
2ae297942f7deea0919e5c12f6a6be77068cc224
/variates.cpp
5f0049916c6d5589a33e094cbd33ed3643bb1e75
[]
no_license
G-VAR/switchedDigitalVideo
7b4dc6de6c6d2880f25c9f6e8a3662c91c4edd9b
d863e0dc3737b92926e4ae74ed44cc979c38558f
refs/heads/master
2021-01-22T00:36:29.444053
2014-09-14T04:11:06
2014-09-14T04:11:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,166
cpp
/*------------------------------------------------------------------------ * Module: Variates * * Function: provides several routines to generator random variates * * The zipf RV code is from Kenneth J. Christensen (University of South Florida ) -------------------------------------------------------------------------*/ #include "variates.h" #include <iostream> /*************************************************************** * Routine: int zipfRN(double shape, int n) * * Inputs: * double shape: power law shape parameter * int n : the number of items in the list * * Outputs: * Returns a variate (a random sample) * **************************************************************/ int zipfRN(double shape, int n) { static int first = TRUE; // Static first time flag static double c = 0; // Normalization constant double z; // Uniform random number (0 < z < 1) double sum_prob; // Sum of probabilities double zipf_value; // Computed exponential value to be returned int i; // Loop counter // Compute normalization constant on first call only if (first == TRUE) { //printf("zipfRN: First invocation, n:%d \n",n); for (i=1; i<=n; i++) c = c + (1.0 / pow((double) i, shape)); c = 1.0 / c; first = FALSE; // set the RNG seed to a default value just the first time!! srand(time(NULL)); rand_val(random()); } // Pull a uniform random number (0 < z < 1) do { z = rand_val(0); } while ((z == 0) || (z == 1)); // Map z to the value sum_prob = 0; for (i=1; i<=n; i++) { sum_prob = sum_prob + c / pow((double) i, shape); if (sum_prob >= z) { zipf_value = i; break; } } // Assert that zipf_value is between 1 and N assert((zipf_value >=1) && (zipf_value <= n)); return(zipf_value); } //========================================================================= //= Multiplicative LCG for generating uniform(0.0, 1.0) random numbers = //= - x_n = 7^5*x_(n-1)mod(2^31 - 1) = //= - With x seeded to 1 the 10000th x value should be 1043618065 = //= - From R. Jain, "The Art of Computer Systems Performance Analysis," = //= John Wiley & Sons, 1991. (Page 443, Figure 26.2) = //========================================================================= double rand_val(int seed) { const long a = 16807; // Multiplier const long m = 2147483647; // Modulus const long q = 127773; // m div a const long r = 2836; // m mod a static long x; // Random int value long x_div_q; // x divided by q long x_mod_q; // x modulo q long x_new; // New x value // Set the seed if argument is non-zero and then return zero if (seed > 0) { x = seed; return(0.0); } // RNG using integer arithmetic x_div_q = x / q; x_mod_q = x % q; x_new = (a * x_mod_q) - (r * x_div_q); if (x_new > 0) x = x_new; else x = x_new + m; // Return a random value between 0.0 and 1.0 return((double) x / m); } /*************************************************************** * Routine: double exponentialRN(double meanRV) * * Inputs: * double meanRV: The requested mean of the Random Variable * * Outputs: * Returns a variate (a random sample) * **************************************************************/ double exponentialRN(double meanRV) { double uniformRN = 1.0; double expoRN = - 1.0; static int first = TRUE; // Static first time flag // Compute normalization constant on first call only if (first == TRUE) { //printf("exponentialRN: First invocation, mean:%3.3f \n",meanRV); first = FALSE; // set the RNG seed to a default value just the first time!! srand(time(NULL)); rand_val(random()); } uniformRN = rand_val(0); expoRN = -(1/meanRV)*log(uniformRN); return expoRN; }
c57caddeaad527c9753fc7f0e6a313eb3eb54915
874246e0d83fb6e2ef7d10136e8caa3f26d606d7
/addons/85th_items/functions/script_component.hpp
4a82ea5889e1716a92d2800df05548798e211654
[]
no_license
85th-PMC/85th
e598502cd4de7a177ad08face9153eaf898c521a
ed42e80f63770f365815459793c2f5aa40e8eb29
refs/heads/master
2020-03-28T19:21:49.101420
2018-10-03T10:39:08
2018-10-03T10:39:08
148,968,051
0
0
null
2019-04-02T13:08:54
2018-09-16T05:59:12
C++
UTF-8
C++
false
false
64
hpp
#include "\z\85th_items\addons\85th_items\script_component.hpp"
bd73a67b280a27760424aef7a696f3bd099df6c6
43a54d76227b48d851a11cc30bbe4212f59e1154
/iotvideo/include/tencentcloud/iotvideo/v20191126/model/ModifyDeviceResponse.h
83c77dbb7795269986664e9a612442d985eca62a
[ "Apache-2.0" ]
permissive
make1122/tencentcloud-sdk-cpp
175ce4d143c90d7ea06f2034dabdb348697a6c1c
2af6954b2ee6c9c9f61489472b800c8ce00fb949
refs/heads/master
2023-06-04T03:18:47.169750
2021-06-18T03:00:01
2021-06-18T03:00:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,554
h
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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. * 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. */ #ifndef TENCENTCLOUD_IOTVIDEO_V20191126_MODEL_MODIFYDEVICERESPONSE_H_ #define TENCENTCLOUD_IOTVIDEO_V20191126_MODEL_MODIFYDEVICERESPONSE_H_ #include <string> #include <vector> #include <map> #include <tencentcloud/core/AbstractModel.h> namespace TencentCloud { namespace Iotvideo { namespace V20191126 { namespace Model { /** * ModifyDevice返回参数结构体 */ class ModifyDeviceResponse : public AbstractModel { public: ModifyDeviceResponse(); ~ModifyDeviceResponse() = default; CoreInternalOutcome Deserialize(const std::string &payload); private: }; } } } } #endif // !TENCENTCLOUD_IOTVIDEO_V20191126_MODEL_MODIFYDEVICERESPONSE_H_
c7ef76da20268c73031ea36f08e008cbca7811e2
858dc012ed841ccecb032084d276c514776076a8
/source/OnesAndZeroes.cpp
0409964c1b3952ab67b23960455809e84f201b89
[]
no_license
navyhu/LeetCodeCpp
43ac8944df414fab38f42efa526416a38a660a82
f772eaad71aeb019bdc58ccb6c1ba9c4614759be
refs/heads/master
2020-05-17T03:25:47.789400
2018-07-20T03:57:08
2018-07-20T03:57:08
32,626,934
0
0
null
null
null
null
UTF-8
C++
false
false
1,305
cpp
#include <iostream> #include <vector> #include <string> using namespace std; class Solution { public: int findMaxForm(vector<string>& strs, int m, int n) { vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0)); for (auto str : strs) { int count0 = 0; int count1 = 0; for (auto ch : str) { if (ch == '0') count0++; else count1++; } for (int i = m; i >= count0; --i) { for (int j = n; j >= count1; --j) { dp[i][j] = max(dp[i][j], dp[i - count0][j - count1] + 1); } } /*for (auto row : dp) { for (auto num : row) cout<<num<<" "; cout<<endl; } cout<<endl;*/ } return dp[m][n]; } }; int main() { //vector<string> strs = {"10", "0001", "111001", "1", "0"};//{"10", "0", "1"};//{"10", "0001", "111001", "1", "0"}; //int m = 5; //int n = 3; vector<string> strs = {"011","1","11","0","010","1","10","1","1","0","0","0","01111","011","11","00","11","10","1","0","0","0","0","101","001110","1","0","1","0","0","10","00100","0","10","1","1","1","011","11","11","10","10","0000","01","1","10","0"}; int m = 44; int n = 39; for (auto str : strs) cout<<str<<", "; cout<<endl; cout<<"m = "<<m<<endl; cout<<"n = "<<n<<endl; Solution test; int result = test.findMaxForm(strs, m, n); cout<<"result = "<<result<<endl; return 0; }
39aa24f9ef1b8d56ee9392bc4eefe24ba93952a4
d4919fb471c6ca382f68e6f1bc67c8e8a80a7b28
/src/bvh/sphere_bvh_mpi.cpp
220e1cfb9f362966d973085c5e2102746edd78ab
[]
no_license
ZwFink/ParRay
1cc6556cc1393f43e537c9c888741a280ee300a1
c1bad0a8b056e621e93948aa19fcd9f93dc9d767
refs/heads/master
2023-04-28T05:32:57.393581
2021-05-08T23:58:31
2021-05-08T23:58:31
353,145,710
1
0
null
2021-05-08T23:58:32
2021-03-30T21:26:27
C++
UTF-8
C++
false
false
12,340
cpp
#include "bvh.hpp" #include <mpi.h> #include "data_porting.h" #include "vec3.h" #include "camera.h" #include <vector> #include "color.h" #include <ctime> #include "boundable.h" #include <omp.h> #include <thread> #include <atomic> #include <condition_variable> #include "ray_tracing.h" #define RENDER_COMPLETE std::numeric_limits<int>::min() static color ray_color(const ray &r, BVH &world, int depth) { hit_record rec; Sphere *hitObject = nullptr; if (depth <= 0) return color(0, 0, 0); if (world.intersect(r, &hitObject, rec)) { ray scattered; color attenuation; if (rec.mat_ptr->scatter(r, rec, attenuation, scattered)) { return attenuation * ray_color(scattered, world, depth - 1); } else { return color(0, 0, 0); } } //otherwise return the background color vec3 unit_direction = unit_vector(r.direction()); auto t = 0.5 * (unit_direction.y() + 1.0); return (1.0 - t) * color(1.0, 1.0, 1.0) + t * color(0.5, 0.7, 1.0); } // a global distributor that processes request work from void work_distributor_loop(const traceConfig& config, int minimum_assignment ) { const int total_rows = config.height; // one processor is the work distributor, will not be doing any work const int num_procs = config.numProcs - 1; int remaining_rows = total_rows; int finish_messages_distributed = 0; int incoming_request_buf = 0; int outgoing_request_buf[2]; int last_row_assigned = 0; if(num_procs == 1) minimum_assignment = total_rows; while(finish_messages_distributed < num_procs) { // receive a work request from some process MPI_Recv(&incoming_request_buf, 1, MPI_INT, MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, MPI_STATUS_IGNORE ); int requesting_process = incoming_request_buf; // calculate the work that should be distributed int num_rows = remaining_rows / (3*num_procs); if(num_rows > 0) { if(num_rows < minimum_assignment) { num_rows = minimum_assignment; } outgoing_request_buf[0] = last_row_assigned; // each process does inclusive render of rows assigned to it outgoing_request_buf[1] = last_row_assigned + num_rows; last_row_assigned += num_rows - 1; remaining_rows -= num_rows; if(remaining_rows < minimum_assignment) { outgoing_request_buf[1] = total_rows - 1; remaining_rows = 0; } } else { outgoing_request_buf[0] = 0; outgoing_request_buf[1] = 0; finish_messages_distributed++; } MPI_Send(outgoing_request_buf, 2, MPI_INT, requesting_process, 0, MPI_COMM_WORLD ); } } void request_work(int myRank, std::atomic_int& row_iter, std::atomic_int& minimum_row ) { // there is more work to be done int requestor = myRank; int received_data[2]; MPI_Send(&requestor, 1, MPI_INT, 0, 0, MPI_COMM_WORLD ); MPI_Recv(received_data, 2, MPI_INT, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE ); if(received_data[0] == 0 && received_data[1] == 0) { row_iter = RENDER_COMPLETE; minimum_row = RENDER_COMPLETE; } else { row_iter = received_data[1]; minimum_row = received_data[0]; } } void render_loop(const traceConfig& config, BVH& world, color *output_image, std::atomic_int& row_iter, std::atomic_int& row_end, std::atomic<bool>& render_complete, std::condition_variable& get_work_var, std::mutex& wait_mutex, std::atomic_int& prev_row_start, std::atomic_int& prev_row_end, std::atomic_int& threads_seen, int num_threads, MPI_Datatype &color_type, MPI_Win &window ) { const camera& cam = config.cam; const int samples_per_pixel = config.samplePerPixel; const int image_width = config.width; const int image_height = config.height; const int max_depth = config.traceDepth; int last_row_end = prev_row_end; int last_row_start = prev_row_start; int my_iter = 0; RENDER_LOOP: my_iter = row_iter--; while(my_iter >= row_end && my_iter >= 0) { if(render_complete) { threads_seen = 0; get_work_var.notify_all(); return; } for(int i = 0; i < image_width; i++) { color pixel_color(0, 0, 0); for(int s = 0; s < samples_per_pixel; ++s) { auto u = (i + random_double()) / (image_width - 1); auto v = (my_iter + random_double()) / (image_height - 1); ray r = cam.get_ray(u, v); pixel_color += ray_color(r, world, max_depth); } int access_idx = ((image_height - 1 - my_iter)*image_width + i); output_image[((image_height - 1 - my_iter)*image_width + i)] = pixel_color; } my_iter = row_iter--; } ++threads_seen; if(threads_seen == num_threads) { last_row_end = prev_row_end; last_row_start = prev_row_start; request_work(config.myRank, row_iter, row_end ); int prev_end = row_end; int prev_start = row_iter; prev_row_end = prev_end; prev_row_start = prev_start; int offset_pixels = (image_height - last_row_start - 1) * image_width; int num_pixels = (1 + last_row_start - last_row_end) * image_width; threads_seen = 0; // done: the start and end are eqal to some value if(row_end == RENDER_COMPLETE && row_iter == RENDER_COMPLETE) render_complete = true; get_work_var.notify_all(); if(!(last_row_start == 0 && last_row_end == 0)) { MPI_Put(output_image + offset_pixels, num_pixels, color_type, 0, offset_pixels, num_pixels, color_type, window ); } if(render_complete) return; } else { std::unique_lock<std::mutex> ul(wait_mutex); get_work_var.wait(ul, [&] {return threads_seen == 0 || render_complete.load();}); } goto RENDER_LOOP; } void raytracing(const traceConfig config, BVH &world, int num_threads){ const camera &cam = config.cam; const int image_width = config.width; const int image_height = config.height; const int max_depth = config.traceDepth; const int samples_per_pixel = config.samplePerPixel; const int rows_per_process = image_height / config.numProcs; if(config.myRank == 0) { std ::cout << "P3\n" << image_width << ' ' << image_height << "\n255\n"; } MPI_Win window; MPI_Datatype MPI_COLOR; color *output_image = nullptr; MPI_Alloc_mem(sizeof(color) * image_height * image_width, MPI_INFO_NULL, &output_image ); for(int i = 0; i < image_height * image_width; i++) { output_image[i] = color(255, 0, 255); } MPI_Win_create(output_image, sizeof(color) * image_height * image_width, sizeof(color), MPI_INFO_NULL, MPI_COMM_WORLD, &window); MPI_Type_contiguous(3, MPI_DOUBLE, &MPI_COLOR); MPI_Type_commit(&MPI_COLOR); double tstart = omp_get_wtime(); MPI_Win_fence(0, window); std::atomic_int remaining_iters{-1}; std::atomic_int row_end{-1}; // TODO: change this // TODO: add thread_config as analog to traceConfig int minimum_distribution = 2*num_threads; if(config.myRank == 0) { std::thread work_distributor = std::thread(work_distributor_loop, std::ref(config), minimum_distribution ); work_distributor.join(); } else { std::atomic<bool> render_complete{false}; std::condition_variable work_var; std::mutex wait_mutex; std::atomic_int prev_row_start{0}; std::atomic_int prev_row_end{0}; std::atomic_int threads_seen{0}; std::thread threads[num_threads]; for(int i = 0; i < num_threads; i++) { threads[i] = std::thread(render_loop, std::ref(config), std::ref(world), output_image, std::ref(remaining_iters), std::ref(row_end), std::ref(render_complete), std::ref(work_var), std::ref(wait_mutex), std::ref(prev_row_start), std::ref(prev_row_end), std::ref(threads_seen), num_threads, std::ref(MPI_COLOR), std::ref(window) ); } for(int i = 0; i < num_threads; i++) { threads[i].join(); } } double tend = omp_get_wtime(); MPI_Win_fence(0, window); double t_elapsed = tend - tstart; double tend_all = omp_get_wtime(); double *receive_data = nullptr; if(config.myRank == 0) { receive_data = new double[config.numProcs]; } MPI_Gather(&t_elapsed, 1, MPI_DOUBLE, receive_data, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD ); if(config.myRank == 0) { for(int i = 0; i < image_height * image_width; i++) write_color(std::cout, output_image[i], samples_per_pixel); } if(config.myRank == 0) { std::cerr << "TIME_ALL: " << tend_all - tstart << "\n"; for(int i = 0; i < config.numProcs; i++) { std::cerr << "TIME_PROCESS: " << i << " " << receive_data[i] << "\n"; } } MPI_Win_free(&window); MPI_Free_mem(output_image); MPI_Type_free(&MPI_COLOR); delete[] receive_data; } int main(int argc, char **argv) { int multithread_support = 0; MPI_Init_thread(&argc, &argv, MPI_THREAD_SERIALIZED, &multithread_support); assert(multithread_support == MPI_THREAD_SERIALIZED); if(argc<3){ std::cerr<<"Usage:"<<argv[0]<<" sceneFile num_threads"<<std::endl; exit(1); } int my_rank = 0; int nprocs = 0; MPI_Comm_rank(MPI_COMM_WORLD, &my_rank); MPI_Comm_size(MPI_COMM_WORLD, &nprocs); std::string sceneFile = argv[1]; ShapeDataIO io; std::vector<Sphere*> scene_spheres = io.load_scene(sceneFile); int num_threads = std::atoi(argv[2]); if(my_rank == 0) { std::cerr << "Rendering scene " << sceneFile << " using " << num_threads << " threads per process, " << nprocs << " processes.\n"; } // Image const auto aspect_ratio = 3.0 / 2.0; const int image_width = 1200; const int image_height = static_cast<int>(image_width / aspect_ratio); const int samples_per_pixel = 500; const int max_depth = 50; // World BVH world(scene_spheres); point3 lookfrom(13, 2, 3); point3 lookat(0, 0, 0); vec3 vup(0, 1, 0); auto dist_to_focus = 10.0; auto aperture = 0.1; camera cam(lookfrom, lookat, vup, 20, aspect_ratio, aperture, dist_to_focus); traceConfig config(cam, image_width, image_height, max_depth, samples_per_pixel, nprocs, my_rank, num_threads); raytracing(config, world, num_threads); if(my_rank == 0) { std::cerr << "\nDone.\n"; } io.clear_scene(scene_spheres); MPI_Finalize(); }
a5e7afc9b7aa0e5a6b897b92c10f3218a4b86fdf
ed9102ec21c1a7c276360b27c524ac3fc8939356
/assign2.cpp
8eb404278ecaa7e2571ddc4641e7809417e66fee
[]
no_license
SHG0202/DSL-Assignments-SPPU
23ecc931e98ae393706b2ee1d4a30d449d138d6e
d041bcd51381328c2aef23ae3fa526a925adb527
refs/heads/master
2022-12-06T15:44:58.283322
2020-09-01T14:49:07
2020-09-01T14:49:07
292,024,154
0
0
null
null
null
null
UTF-8
C++
false
false
4,363
cpp
//============================================================================ // Name : assign2.cpp // Author : saket // Version : // Copyright : Your copyright notice // Description : Hello World in C++, Ansi-style //============================================================================ #include <iostream> using namespace std; class matrix { int row,collom; int mat[3][3]; public: void getmatrix() { cout<<"no. of rows="<<endl; cin>>row; cout<<"no. of collom="<<endl; cin>>collom; cout<<"enter elements of matrix"<<endl; for(int i=0;i<row;i++) { for(int j=0;j<collom;j++) { cin>>mat[i][j]; } } } void dispmatrix() { cout<<"matrix is:"<<endl; for(int i=0;i<row;i++) { for(int j=0;j<collom;j++) { cout<<mat[i][j]; cout<<" "; } cout<<endl; } } void trimatrix() { int count=0; if(row==collom) { for(int i=1;i<row;i++) { for(int j=0;j<i;j++) { if(mat[i][j]==0) { count+=1; } } } if(count==3) { cout<<"it is upper triangular matrix"<<endl; } else { cout<<"it is not a upper triangular matrix"<<endl; } } else { cout<<"it is not a square martix"<<endl; } } void sum_di() { int sum=0; for(int i=0;i<row;i++) { sum+=mat[i][i]; } cout<<"sum of diagonal elements is:"<<sum<<endl; } void transmatrix() { matrix tmat; tmat.row=collom; tmat.collom=row; for(int i=0;i<row;i++) { for(int j=0;j<collom;j++) { tmat.mat[j][i]=mat[i][j]; } } tmat.dispmatrix(); } void addition(matrix p) { matrix q, r; cout<<"we need second matrix"<<endl; q.getmatrix(); if(q.row==p.row && p.collom==q.collom) { for(int i=0;i<row;i++) { for(int j=0;j<collom;j++) { r.mat[i][j]=p.mat[i][j]+q.mat[i][j]; } } r.row=p.row; r.collom=p.collom; r.dispmatrix(); } else { cout<<"please enter a valid matrix"<<endl; } } void subtract(matrix p) { matrix q, r; cout<<"we need second matrix"<<endl; q.getmatrix(); if(q.row==p.row && q.collom==p.collom) { for(int i=0;i<row;i++) { for(int j=0;j<collom;j++) { r.mat[i][j]=p.mat[i][j]-q.mat[i][j]; } } r.row=p.row; r.collom=p.collom; r.dispmatrix(); } else { cout<<"please enter a valid matrix"<<endl; } } void multiply(matrix p) { matrix q, r; int t; cout<<"we need second matrix"<<endl; q.getmatrix(); if(p.collom==q.row) { for(int i=0;i<row;i++) { for(int j=0;j<collom;j++) { r.mat[i][j]=0; for(t=0;t<collom;t++) { r.mat[i][j]=r.mat[i][j]+(p.mat[i][t]*q.mat[t][j]); } } } r.row=p.row; r.collom=q.collom; r.dispmatrix(); } else { cout<<"please enter a valid matrix"<<endl; } } void saddle() { int c1,c2,c3,p,q; for(int i=0;i<row;i++) { for(int j=0;j<collom;j++) { c1=0,c2=0; for(int l=0;l<collom;l++) { if(mat[i][j]<mat[i][l]) { c1+=1; } } for(int m=0;m<row;m++) { if(mat[i][j]>mat[m][j]) { c2+=1; } } if(c1==2 && c2==2) { c3+=1; p=i; q=j; } } } if(c3>0) { cout<<"saddle point is present in the matrix at the position "<<p<<","<<q<<endl; cout<<"it's value is "<<mat[p][q]<<endl; } } }; int main() { matrix a; a.getmatrix(); a.dispmatrix(); int x; while(x!=8) { cout<<"enter a choice:"<<endl; cout<<"1. to check if it is upper triangular matrix or not"<<endl; cout<<"2. to find the sum of diagonal elements"<<endl; cout<<"3. to find the transpose of given matrix"<<endl; cout<<"4. to find sum"<<endl; cout<<"5. to find difference"<<endl; cout<<"6. to find multiplication"<<endl; cout<<"7. to check if the matrix has a saddle point"<<endl; cout<<"8. EXIT"<<endl; cin>>x; switch(x) { case 1: a.trimatrix(); break; case 2: a.sum_di(); break; case 3: a.transmatrix(); break; case 4: a.addition(a); break; case 5: a.subtract(a); break; case 6: a.multiply(a); break; case 7: a.saddle(); break; case 8: break; default: cout<<"enter a valid choice:"<<endl; break; } } return 0; }
971e9b60129ac5aa12b9cf962e144054ae7bb3e3
4e49a9fc7bc1a99b09e629055c3bc75e0106c2bf
/source-cpp/treemap/source/buffers/AbstractLinearizedBuffer.cpp
f8826702e6a3693a4c234b595a81bc655d303bde
[ "MIT" ]
permissive
varg-dev/treemap-hub
f66c2fd1584764cf02f182d5439857e6187e16f6
75d4d2ced3fdf0a73ea1c6b079c70557882ac3b0
refs/heads/master
2023-08-11T04:53:16.362165
2021-10-06T08:21:17
2021-10-06T08:21:17
358,201,293
1
0
MIT
2021-07-28T15:02:54
2021-04-15T09:26:24
C++
UTF-8
C++
false
false
287
cpp
#include <treemap/buffers/AbstractLinearizedBuffer.h> #include <treemap/linearizedtree/LinearizedTreeNode.h> AbstractLinearizedBuffer::AbstractLinearizedBuffer() { } std::uint32_t AbstractLinearizedBuffer::indexOf(const LinearizedTreeNode *node) const { return node->index(); }
d733cb2c45857f25f36381130f944d858161cc89
0de72d530d147475b478ca2088313a151b1efd4d
/splitgate/core/sdk/sdk/Landscape_functions.cpp
8aaa94ad05a9a2a679feb778925548b30f73b466
[]
no_license
gamefortech123/splitgate-cheat
aca411678799ea3d316197acbde3ee1775b1ca76
bf935f5b3c0dfc5d618298e76e474b1c8b3cea4b
refs/heads/master
2023-07-15T00:56:45.222698
2021-08-22T03:26:21
2021-08-22T03:26:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
22,599
cpp
#include "..\..\pch.h" /*!!DEFINE!!*/ /*!!HELPER_DEF!!*/ /*!!HELPER_INC!!*/ #ifdef _MSC_VER #pragma pack(push, 0x01) #endif namespace CG { //--------------------------------------------------------------------------- // Functions //--------------------------------------------------------------------------- // Function Landscape.LandscapeProxy.SetLandscapeMaterialVectorParameterValue // (Final, RequiredAPI, Native, Public, HasDefaults, BlueprintCallable) // Parameters: // struct FName ParameterName (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic) // struct FLinearColor Value (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic) void ALandscapeProxy::SetLandscapeMaterialVectorParameterValue(const struct FName& ParameterName, const struct FLinearColor& Value) { static auto fn = UObject::FindObject<UFunction>("Function Landscape.LandscapeProxy.SetLandscapeMaterialVectorParameterValue"); ALandscapeProxy_SetLandscapeMaterialVectorParameterValue_Params params; params.ParameterName = ParameterName; params.Value = Value; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x00000400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Landscape.LandscapeProxy.SetLandscapeMaterialTextureParameterValue // (Final, RequiredAPI, Native, Public, BlueprintCallable) // Parameters: // struct FName ParameterName (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic) // class UTexture* Value (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic) void ALandscapeProxy::SetLandscapeMaterialTextureParameterValue(const struct FName& ParameterName, class UTexture* Value) { static auto fn = UObject::FindObject<UFunction>("Function Landscape.LandscapeProxy.SetLandscapeMaterialTextureParameterValue"); ALandscapeProxy_SetLandscapeMaterialTextureParameterValue_Params params; params.ParameterName = ParameterName; params.Value = Value; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x00000400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Landscape.LandscapeProxy.SetLandscapeMaterialScalarParameterValue // (Final, RequiredAPI, Native, Public, BlueprintCallable) // Parameters: // struct FName ParameterName (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic) // float Value (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic) void ALandscapeProxy::SetLandscapeMaterialScalarParameterValue(const struct FName& ParameterName, float Value) { static auto fn = UObject::FindObject<UFunction>("Function Landscape.LandscapeProxy.SetLandscapeMaterialScalarParameterValue"); ALandscapeProxy_SetLandscapeMaterialScalarParameterValue_Params params; params.ParameterName = ParameterName; params.Value = Value; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x00000400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Landscape.LandscapeProxy.LandscapeExportHeightmapToRenderTarget // (Final, Native, Public, BlueprintCallable) // Parameters: // class UTextureRenderTarget2D* InRenderTarget (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic) // bool InExportHeightIntoRGChannel (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic) // bool InExportLandscapeProxies (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic) // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic) bool ALandscapeProxy::LandscapeExportHeightmapToRenderTarget(class UTextureRenderTarget2D* InRenderTarget, bool InExportHeightIntoRGChannel, bool InExportLandscapeProxies) { static auto fn = UObject::FindObject<UFunction>("Function Landscape.LandscapeProxy.LandscapeExportHeightmapToRenderTarget"); ALandscapeProxy_LandscapeExportHeightmapToRenderTarget_Params params; params.InRenderTarget = InRenderTarget; params.InExportHeightIntoRGChannel = InExportHeightIntoRGChannel; params.InExportLandscapeProxies = InExportLandscapeProxies; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x00000400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function Landscape.LandscapeProxy.EditorSetLandscapeMaterial // (Final, Native, Public, BlueprintCallable) // Parameters: // class UMaterialInterface* NewLandscapeMaterial (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic) void ALandscapeProxy::EditorSetLandscapeMaterial(class UMaterialInterface* NewLandscapeMaterial) { static auto fn = UObject::FindObject<UFunction>("Function Landscape.LandscapeProxy.EditorSetLandscapeMaterial"); ALandscapeProxy_EditorSetLandscapeMaterial_Params params; params.NewLandscapeMaterial = NewLandscapeMaterial; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x00000400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Landscape.LandscapeProxy.EditorApplySpline // (Final, RequiredAPI, Native, Public, BlueprintCallable) // Parameters: // class USplineComponent* InSplineComponent (Parm, ZeroConstructor, InstancedReference, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic) // float StartWidth (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic) // float EndWidth (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic) // float StartSideFalloff (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic) // float EndSideFalloff (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic) // float StartRoll (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic) // float EndRoll (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic) // int NumSubdivisions (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic) // bool bRaiseHeights (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic) // bool bLowerHeights (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic) // class ULandscapeLayerInfoObject* PaintLayer (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic) // struct FName EditLayerName (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic) void ALandscapeProxy::EditorApplySpline(class USplineComponent* InSplineComponent, float StartWidth, float EndWidth, float StartSideFalloff, float EndSideFalloff, float StartRoll, float EndRoll, int NumSubdivisions, bool bRaiseHeights, bool bLowerHeights, class ULandscapeLayerInfoObject* PaintLayer, const struct FName& EditLayerName) { static auto fn = UObject::FindObject<UFunction>("Function Landscape.LandscapeProxy.EditorApplySpline"); ALandscapeProxy_EditorApplySpline_Params params; params.InSplineComponent = InSplineComponent; params.StartWidth = StartWidth; params.EndWidth = EndWidth; params.StartSideFalloff = StartSideFalloff; params.EndSideFalloff = EndSideFalloff; params.StartRoll = StartRoll; params.EndRoll = EndRoll; params.NumSubdivisions = NumSubdivisions; params.bRaiseHeights = bRaiseHeights; params.bLowerHeights = bLowerHeights; params.PaintLayer = PaintLayer; params.EditLayerName = EditLayerName; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x00000400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Landscape.LandscapeProxy.ChangeUseTessellationComponentScreenSizeFalloff // (Native, Public, BlueprintCallable) // Parameters: // bool InComponentScreenSizeToUseSubSections (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic) void ALandscapeProxy::ChangeUseTessellationComponentScreenSizeFalloff(bool InComponentScreenSizeToUseSubSections) { static auto fn = UObject::FindObject<UFunction>("Function Landscape.LandscapeProxy.ChangeUseTessellationComponentScreenSizeFalloff"); ALandscapeProxy_ChangeUseTessellationComponentScreenSizeFalloff_Params params; params.InComponentScreenSizeToUseSubSections = InComponentScreenSizeToUseSubSections; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x00000400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Landscape.LandscapeProxy.ChangeTessellationComponentScreenSizeFalloff // (Native, Public, BlueprintCallable) // Parameters: // float InUseTessellationComponentScreenSizeFalloff (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic) void ALandscapeProxy::ChangeTessellationComponentScreenSizeFalloff(float InUseTessellationComponentScreenSizeFalloff) { static auto fn = UObject::FindObject<UFunction>("Function Landscape.LandscapeProxy.ChangeTessellationComponentScreenSizeFalloff"); ALandscapeProxy_ChangeTessellationComponentScreenSizeFalloff_Params params; params.InUseTessellationComponentScreenSizeFalloff = InUseTessellationComponentScreenSizeFalloff; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x00000400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Landscape.LandscapeProxy.ChangeTessellationComponentScreenSize // (Native, Public, BlueprintCallable) // Parameters: // float InTessellationComponentScreenSize (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic) void ALandscapeProxy::ChangeTessellationComponentScreenSize(float InTessellationComponentScreenSize) { static auto fn = UObject::FindObject<UFunction>("Function Landscape.LandscapeProxy.ChangeTessellationComponentScreenSize"); ALandscapeProxy_ChangeTessellationComponentScreenSize_Params params; params.InTessellationComponentScreenSize = InTessellationComponentScreenSize; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x00000400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Landscape.LandscapeProxy.ChangeLODDistanceFactor // (Native, Public, BlueprintCallable) // Parameters: // float InLODDistanceFactor (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic) void ALandscapeProxy::ChangeLODDistanceFactor(float InLODDistanceFactor) { static auto fn = UObject::FindObject<UFunction>("Function Landscape.LandscapeProxy.ChangeLODDistanceFactor"); ALandscapeProxy_ChangeLODDistanceFactor_Params params; params.InLODDistanceFactor = InLODDistanceFactor; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x00000400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Landscape.LandscapeProxy.ChangeComponentScreenSizeToUseSubSections // (Native, Public, BlueprintCallable) // Parameters: // float InComponentScreenSizeToUseSubSections (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic) void ALandscapeProxy::ChangeComponentScreenSizeToUseSubSections(float InComponentScreenSizeToUseSubSections) { static auto fn = UObject::FindObject<UFunction>("Function Landscape.LandscapeProxy.ChangeComponentScreenSizeToUseSubSections"); ALandscapeProxy_ChangeComponentScreenSizeToUseSubSections_Params params; params.InComponentScreenSizeToUseSubSections = InComponentScreenSizeToUseSubSections; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x00000400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Landscape.LandscapeBlueprintBrushBase.RequestLandscapeUpdate // (Final, Native, Public, BlueprintCallable) void ALandscapeBlueprintBrushBase::RequestLandscapeUpdate() { static auto fn = UObject::FindObject<UFunction>("Function Landscape.LandscapeBlueprintBrushBase.RequestLandscapeUpdate"); ALandscapeBlueprintBrushBase_RequestLandscapeUpdate_Params params; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x00000400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Landscape.LandscapeBlueprintBrushBase.Render // (Native, Event, Public, HasOutParms, BlueprintEvent) // Parameters: // bool InIsHeightmap (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic) // class UTextureRenderTarget2D* InCombinedResult (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic) // struct FName InWeightmapLayerName (ConstParm, Parm, OutParm, ZeroConstructor, ReferenceParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic) // class UTextureRenderTarget2D* ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic) class UTextureRenderTarget2D* ALandscapeBlueprintBrushBase::Render(bool InIsHeightmap, class UTextureRenderTarget2D* InCombinedResult, const struct FName& InWeightmapLayerName) { static auto fn = UObject::FindObject<UFunction>("Function Landscape.LandscapeBlueprintBrushBase.Render"); ALandscapeBlueprintBrushBase_Render_Params params; params.InIsHeightmap = InIsHeightmap; params.InCombinedResult = InCombinedResult; params.InWeightmapLayerName = InWeightmapLayerName; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x00000400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function Landscape.LandscapeBlueprintBrushBase.Initialize // (Native, Event, Public, HasOutParms, HasDefaults, BlueprintEvent) // Parameters: // struct FTransform InLandscapeTransform (ConstParm, Parm, OutParm, ReferenceParm, IsPlainOldData, NoDestructor, NativeAccessSpecifierPublic) // struct FIntPoint InLandscapeSize (ConstParm, Parm, OutParm, ZeroConstructor, ReferenceParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic) // struct FIntPoint InLandscapeRenderTargetSize (ConstParm, Parm, OutParm, ZeroConstructor, ReferenceParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic) void ALandscapeBlueprintBrushBase::Initialize(const struct FTransform& InLandscapeTransform, const struct FIntPoint& InLandscapeSize, const struct FIntPoint& InLandscapeRenderTargetSize) { static auto fn = UObject::FindObject<UFunction>("Function Landscape.LandscapeBlueprintBrushBase.Initialize"); ALandscapeBlueprintBrushBase_Initialize_Params params; params.InLandscapeTransform = InLandscapeTransform; params.InLandscapeSize = InLandscapeSize; params.InLandscapeRenderTargetSize = InLandscapeRenderTargetSize; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x00000400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Landscape.LandscapeBlueprintBrushBase.GetBlueprintRenderDependencies // (Event, Public, HasOutParms, BlueprintEvent) // Parameters: // TArray<class UObject*> OutStreamableAssets (Parm, OutParm, ZeroConstructor, NativeAccessSpecifierPublic) void ALandscapeBlueprintBrushBase::GetBlueprintRenderDependencies(TArray<class UObject*>* OutStreamableAssets) { static auto fn = UObject::FindObject<UFunction>("Function Landscape.LandscapeBlueprintBrushBase.GetBlueprintRenderDependencies"); ALandscapeBlueprintBrushBase_GetBlueprintRenderDependencies_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (OutStreamableAssets != nullptr) *OutStreamableAssets = params.OutStreamableAssets; } // Function Landscape.LandscapeComponent.GetMaterialInstanceDynamic // (Final, Native, Public, BlueprintCallable, BlueprintPure, Const) // Parameters: // int InIndex (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic) // class UMaterialInstanceDynamic* ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic) class UMaterialInstanceDynamic* ULandscapeComponent::GetMaterialInstanceDynamic(int InIndex) { static auto fn = UObject::FindObject<UFunction>("Function Landscape.LandscapeComponent.GetMaterialInstanceDynamic"); ULandscapeComponent_GetMaterialInstanceDynamic_Params params; params.InIndex = InIndex; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x00000400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function Landscape.LandscapeComponent.EditorGetPaintLayerWeightByNameAtLocation // (Final, RequiredAPI, Native, Public, HasOutParms, HasDefaults, BlueprintCallable) // Parameters: // struct FVector InLocation (ConstParm, Parm, OutParm, ZeroConstructor, ReferenceParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic) // struct FName InPaintLayerName (ConstParm, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic) // float ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic) float ULandscapeComponent::EditorGetPaintLayerWeightByNameAtLocation(const struct FVector& InLocation, const struct FName& InPaintLayerName) { static auto fn = UObject::FindObject<UFunction>("Function Landscape.LandscapeComponent.EditorGetPaintLayerWeightByNameAtLocation"); ULandscapeComponent_EditorGetPaintLayerWeightByNameAtLocation_Params params; params.InLocation = InLocation; params.InPaintLayerName = InPaintLayerName; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x00000400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function Landscape.LandscapeComponent.EditorGetPaintLayerWeightAtLocation // (Final, RequiredAPI, Native, Public, HasOutParms, HasDefaults, BlueprintCallable) // Parameters: // struct FVector InLocation (ConstParm, Parm, OutParm, ZeroConstructor, ReferenceParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic) // class ULandscapeLayerInfoObject* PaintLayer (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic) // float ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic) float ULandscapeComponent::EditorGetPaintLayerWeightAtLocation(const struct FVector& InLocation, class ULandscapeLayerInfoObject* PaintLayer) { static auto fn = UObject::FindObject<UFunction>("Function Landscape.LandscapeComponent.EditorGetPaintLayerWeightAtLocation"); ULandscapeComponent_EditorGetPaintLayerWeightAtLocation_Params params; params.InLocation = InLocation; params.PaintLayer = PaintLayer; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x00000400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function Landscape.LandscapeHeightfieldCollisionComponent.GetRenderComponent // (Final, Native, Public, BlueprintCallable, BlueprintPure, Const) // Parameters: // class ULandscapeComponent* ReturnValue (ExportObject, Parm, OutParm, ZeroConstructor, ReturnParm, InstancedReference, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic) class ULandscapeComponent* ULandscapeHeightfieldCollisionComponent::GetRenderComponent() { static auto fn = UObject::FindObject<UFunction>("Function Landscape.LandscapeHeightfieldCollisionComponent.GetRenderComponent"); ULandscapeHeightfieldCollisionComponent_GetRenderComponent_Params params; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x00000400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function Landscape.LandscapeSplinesComponent.GetSplineMeshComponents // (Final, Native, Public, BlueprintCallable) // Parameters: // TArray<class USplineMeshComponent*> ReturnValue (ExportObject, Parm, OutParm, ZeroConstructor, ReturnParm, ContainsInstancedReference, NativeAccessSpecifierPublic) TArray<class USplineMeshComponent*> ULandscapeSplinesComponent::GetSplineMeshComponents() { static auto fn = UObject::FindObject<UFunction>("Function Landscape.LandscapeSplinesComponent.GetSplineMeshComponents"); ULandscapeSplinesComponent_GetSplineMeshComponents_Params params; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x00000400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } } #ifdef _MSC_VER #pragma pack(pop) #endif
1eb43538717c6667ecb3123766d3a3cbcc81faee
5bbeacb6613fdaa184a5bda4bdb54b16dc8654e1
/zMuSource/GameServer/EledoradoEvent.cpp
ab2b5b9c09e8fbaa75c5ee1c5c10d5adf827c6e0
[]
no_license
yiyilookduy/IGCN-SS12
0e4b6c655c2f15e561ad150e1dd0f047a72ef23b
6a3f8592f4fa9260e56c1d5fee7a62277dc3691d
refs/heads/master
2020-04-04T09:03:13.134134
2018-11-02T03:02:29
2018-11-02T03:02:29
155,804,847
0
4
null
null
null
null
UTF-8
C++
false
false
34,430
cpp
//////////////////////////////////////////////////////////////////////////////// // EledoradoEvent.cpp // ------------------------------ // Decompiled by Deathway // Date : 2007-05-09 // ------------------------------ #include "stdafx.h" #include "EledoradoEvent.h" #include "Gamemain.h" #include "TLog.h" #include "user.h" #include "TNotice.h" #include "configread.h" #include "MapServerManager.h" CEledoradoEvent gEledoradoEvent; CEledoradoEvent::CEledoradoEvent() { this->m_BossGoldDerconMapNumber[0] = -1; this->m_BossGoldDerconMapNumber[1] = -1; this->m_BossGoldDerconMapNumber[2] = -1; this->m_BossGoldDerconMapNumber[3] = -1; InitializeCriticalSection(&this->m_MonCriti); } CEledoradoEvent::~CEledoradoEvent() { DeleteCriticalSection(&this->m_MonCriti); } void CEledoradoEvent::ClearMonster() { EnterCriticalSection(&this->m_MonCriti); for (std::map<int, ELEDORADO_MONSTER_INFO>::iterator It = this->m_mapMonsterInfo.begin(); It != this->m_mapMonsterInfo.end(); It++) { gObjDel(It->second.m_Index); } this->m_mapMonsterInfo.clear(); LeaveCriticalSection(&this->m_MonCriti); } void CEledoradoEvent::Init() { this->ClearMonster(); this->m_vtMonsterPos.clear(); char * szFile = g_ConfigRead.GetPath("\\Events\\IGC_GoldenInvasion.xml"); pugi::xml_document file; pugi::xml_parse_result res = file.load_file(szFile); if (res.status != pugi::status_ok) { g_Log.MsgBox("%s load fail (%s)", szFile, res.description()); return; } pugi::xml_node main = file.child("GoldenInvasion"); pugi::xml_node spot = main.child("Spot"); for (pugi::xml_node spawn = spot.child("Spawn"); spawn; spawn = spawn.next_sibling()) { ELEDORARO_MONSTER_POS m_Pos; m_Pos.m_Type = spawn.attribute("Index").as_int(); m_Pos.m_MapNumber[0] = spawn.attribute("MapNumber1").as_int(); m_Pos.m_MapNumber[1] = spawn.attribute("MapNumber2").as_int(); m_Pos.m_MapNumber[2] = spawn.attribute("MapNumber3").as_int(); m_Pos.m_MapNumber[3] = spawn.attribute("MapNumber4").as_int(); m_Pos.m_Dis = spawn.attribute("Distance").as_int(); m_Pos.m_X = spawn.attribute("StartX").as_int(); m_Pos.m_Y = spawn.attribute("StartY").as_int(); m_Pos.m_W = spawn.attribute("EndX").as_int(); m_Pos.m_H = spawn.attribute("EndY").as_int(); m_Pos.m_Dir = spawn.attribute("Dir").as_int(); m_Pos.m_Count = spawn.attribute("Count").as_int(); this->m_vtMonsterPos.insert(std::pair<int, ELEDORARO_MONSTER_POS>(m_Pos.m_Type, m_Pos)); } } void CEledoradoEvent::SetEventState(int State) { this->EventState = State; } void CEledoradoEvent::Run() { return; } void CEledoradoEvent::RegenGoldGoblen() { std::map<int, ELEDORARO_MONSTER_POS>::iterator It = this->m_vtMonsterPos.find(78); if (It == this->m_vtMonsterPos.end()) { return; } int MapNumber; for (int i = 0; i < It->second.m_Count; i++) { MapNumber = this->GetMapNumber(It); if (g_MapServerManager.CheckMapCanMove(MapNumber) == FALSE) { return; } if (MapNumber == -1) { g_Log.AddC(TColor::Red, "%s MapNumber == -1", __FUNCTION__); return; } int result = gObjAddMonster(MapNumber); if (result == -1) { g_Log.AddC(TColor::Red, "%s result == -1", __FUNCTION__); return; } gObj[result].MapNumber = MapNumber; while (this->GetBoxPosition(MapNumber, It->second.m_X, It->second.m_Y, It->second.m_W, It->second.m_H, gObj[result].X, gObj[result].Y) == 0) { } gObj[result].m_PosNum = -1; gObj[result].TX = gObj[result].X; gObj[result].TY = gObj[result].Y; gObj[result].MTX = gObj[result].X; gObj[result].MTY = gObj[result].Y; gObj[result].m_OldX = gObj[result].X; gObj[result].m_OldY = gObj[result].Y; gObj[result].StartX = gObj[result].X; gObj[result].StartY = gObj[result].Y; if (It->second.m_Dir == (BYTE)-1) { gObj[result].Dir = rand() % 8; } else { gObj[result].Dir = It->second.m_Dir; } gObjSetMonster(result, It->second.m_Type); EnterCriticalSection(&this->m_MonCriti); ELEDORADO_MONSTER_INFO m_MonsterInfo; m_MonsterInfo.m_Index = result; this->m_mapMonsterInfo.insert(std::pair<int, ELEDORADO_MONSTER_INFO>(result, m_MonsterInfo)); LeaveCriticalSection(&this->m_MonCriti); } } void CEledoradoEvent::RegenTitan() { std::map<int, ELEDORARO_MONSTER_POS>::iterator It = this->m_vtMonsterPos.find(53); if (It == this->m_vtMonsterPos.end()) { return; } int MapNumber; for (int i = 0; i < It->second.m_Count; i++) { MapNumber = this->GetMapNumber(It); if (g_MapServerManager.CheckMapCanMove(MapNumber) == FALSE) { return; } if (MapNumber == -1) { g_Log.AddC(TColor::Red, "%s MapNumber == -1", __FUNCTION__); return; } int result = gObjAddMonster(MapNumber); if (result == -1) { g_Log.AddC(TColor::Red, "%s result == -1", __FUNCTION__); return; } gObj[result].MapNumber = MapNumber; while (this->GetBoxPosition(MapNumber, It->second.m_X, It->second.m_Y, It->second.m_W, It->second.m_H, gObj[result].X, gObj[result].Y) == 0) { } this->m_BossTitanMapNumber = gObj[result].MapNumber; this->m_BossTitanMapX = gObj[result].X; this->m_BossTitanMapY = gObj[result].Y; gObj[result].m_PosNum = -1; gObj[result].TX = gObj[result].X; gObj[result].TY = gObj[result].Y; gObj[result].MTX = gObj[result].X; gObj[result].MTY = gObj[result].Y; gObj[result].m_OldX = gObj[result].X; gObj[result].m_OldY = gObj[result].Y; gObj[result].StartX = gObj[result].X; gObj[result].StartY = gObj[result].Y; if (It->second.m_Dir == (BYTE)-1) { gObj[result].Dir = rand() % 8; } else { gObj[result].Dir = It->second.m_Dir; } gObjSetMonster(result, It->second.m_Type); EnterCriticalSection(&this->m_MonCriti); ELEDORADO_MONSTER_INFO m_MonsterInfo; m_MonsterInfo.m_Index = result; this->m_mapMonsterInfo.insert(std::pair<int, ELEDORADO_MONSTER_INFO>(result, m_MonsterInfo)); LeaveCriticalSection(&this->m_MonCriti); } It = this->m_vtMonsterPos.find(54); if (It == this->m_vtMonsterPos.end()) { return; } for (int i = 0; i < It->second.m_Count; i++) { MapNumber = this->m_BossTitanMapNumber; int result = gObjAddMonster(MapNumber); if (result == -1) { g_Log.AddC(TColor::Red, "%s result == -1", __FUNCTION__); return; } gObj[result].MapNumber = MapNumber; this->GetBoxPosition(MapNumber, this->m_BossTitanMapX - 4, this->m_BossTitanMapY - 4, this->m_BossTitanMapX + 4, this->m_BossTitanMapY + 4, gObj[result].X, gObj[result].Y); gObj[result].m_PosNum = -1; gObj[result].TX = gObj[result].X; gObj[result].TY = gObj[result].Y; gObj[result].MTX = gObj[result].X; gObj[result].MTY = gObj[result].Y; gObj[result].m_OldX = gObj[result].X; gObj[result].m_OldY = gObj[result].Y; gObj[result].StartX = gObj[result].X; gObj[result].StartY = gObj[result].Y; if (It->second.m_Dir == (BYTE)-1) { gObj[result].Dir = rand() % 8; } else { gObj[result].Dir = It->second.m_Dir; } EnterCriticalSection(&this->m_MonCriti); ELEDORADO_MONSTER_INFO m_MonsterInfo; m_MonsterInfo.m_Index = result; this->m_mapMonsterInfo.insert(std::pair<int, ELEDORADO_MONSTER_INFO>(result, m_MonsterInfo)); LeaveCriticalSection(&this->m_MonCriti); gObjSetMonster(result, It->second.m_Type); } } void CEledoradoEvent::RegenGoldDercon() { std::map<int, ELEDORARO_MONSTER_POS>::iterator It = this->m_vtMonsterPos.find(79); if (It == this->m_vtMonsterPos.end()) { return; } int MapNumber = -1; int SelMap = -1; int count = 0; for (int i = 0; i < It->second.m_Count; i++) { MapNumber = this->GetMapNumber(It); if (g_MapServerManager.CheckMapCanMove(MapNumber) == FALSE) { return; } if (MapNumber == -1) { g_Log.AddC(TColor::Red, "%s MapNumber == -1", __FUNCTION__); return; } if (SelMap == -1) { SelMap = MapNumber; } else { MapNumber = SelMap; } int result = gObjAddMonster(MapNumber); if (result == -1) { g_Log.AddC(TColor::Red, "%s result == -1", __FUNCTION__); return; } gObj[result].MapNumber = MapNumber; while (this->GetBoxPosition(MapNumber, It->second.m_X, It->second.m_Y, It->second.m_W, It->second.m_H, gObj[result].X, gObj[result].Y) == 0) { } gObj[result].m_PosNum = -1; gObj[result].TX = gObj[result].X; gObj[result].TY = gObj[result].Y; gObj[result].MTX = gObj[result].X; gObj[result].MTY = gObj[result].Y; gObj[result].m_OldX = gObj[result].X; gObj[result].m_OldY = gObj[result].Y; gObj[result].StartX = gObj[result].X; gObj[result].StartY = gObj[result].Y; if (It->second.m_Dir == (BYTE)-1) { gObj[result].Dir = rand() % 8; } else { gObj[result].Dir = It->second.m_Dir; } gObjSetMonster(result, It->second.m_Type); EnterCriticalSection(&this->m_MonCriti); ELEDORADO_MONSTER_INFO m_MonsterInfo; m_MonsterInfo.m_Index = result; this->m_mapMonsterInfo.insert(std::pair<int, ELEDORADO_MONSTER_INFO>(result, m_MonsterInfo)); LeaveCriticalSection(&this->m_MonCriti); this->m_BossGoldDerconMapNumber[count] = MapNumber; gObj[result].m_BossGoldDerconMapNumber = MapNumber; // #error change count by MapNumber count++; } if (MapNumber != -1) { char szTemp[256]; strcpy(szTemp, Lang.GetMap(0, MapNumber)); PMSG_NOTICE pNotice; TNotice::MakeNoticeMsgEx(&pNotice, 0, Lang.GetText(0, 64), szTemp); TNotice::SendNoticeToAllUser(&pNotice); } this->CheckGoldDercon(MapNumber); } void CEledoradoEvent::RegenDevilLizardKing() { std::map<int, ELEDORARO_MONSTER_POS>::iterator It = this->m_vtMonsterPos.find(80); if (It == this->m_vtMonsterPos.end()) { return; } int MapNumber; for (int i = 0; i < It->second.m_Count; i++) { MapNumber = this->GetMapNumber(It); if (g_MapServerManager.CheckMapCanMove(MapNumber) == FALSE) { return; } if (MapNumber == -1) { g_Log.AddC(TColor::Red, "%s MapNumber == -1", __FUNCTION__); return; } int result = gObjAddMonster(MapNumber); if (result == -1) { g_Log.AddC(TColor::Red, "%s result == -1", __FUNCTION__); return; } gObj[result].MapNumber = MapNumber; while (this->GetBoxPosition(MapNumber, It->second.m_X, It->second.m_Y, It->second.m_W, It->second.m_H, gObj[result].X, gObj[result].Y) == 0) { } this->m_BossDevilLizardKingMapNumber = gObj[result].MapNumber; this->m_BossDevilLizardKingMapX = gObj[result].X; this->m_BossDevilLizardKingMapY = gObj[result].Y; gObj[result].m_PosNum = -1; gObj[result].TX = gObj[result].X; gObj[result].TY = gObj[result].Y; gObj[result].MTX = gObj[result].X; gObj[result].MTY = gObj[result].Y; gObj[result].m_OldX = gObj[result].X; gObj[result].m_OldY = gObj[result].Y; gObj[result].StartX = gObj[result].X; gObj[result].StartY = gObj[result].Y; if (It->second.m_Dir == (BYTE)-1) { gObj[result].Dir = rand() % 8; } else { gObj[result].Dir = It->second.m_Dir; } gObjSetMonster(result, It->second.m_Type); EnterCriticalSection(&this->m_MonCriti); ELEDORADO_MONSTER_INFO m_MonsterInfo; m_MonsterInfo.m_Index = result; this->m_mapMonsterInfo.insert(std::pair<int, ELEDORADO_MONSTER_INFO>(result, m_MonsterInfo)); LeaveCriticalSection(&this->m_MonCriti); } It = this->m_vtMonsterPos.find(81); if (It == this->m_vtMonsterPos.end()) { return; } for (int i = 0; i < It->second.m_Count; i++) { MapNumber = this->m_BossDevilLizardKingMapNumber; int result = gObjAddMonster(MapNumber); if (result == -1) { g_Log.AddC(TColor::Red, "%s result == -1", __FUNCTION__); return; } gObj[result].MapNumber = MapNumber; this->GetBoxPosition(MapNumber, this->m_BossDevilLizardKingMapX - 4, this->m_BossDevilLizardKingMapY - 4, this->m_BossDevilLizardKingMapX + 4, this->m_BossDevilLizardKingMapY + 4, gObj[result].X, gObj[result].Y); gObj[result].m_PosNum = -1; gObj[result].TX = gObj[result].X; gObj[result].TY = gObj[result].Y; gObj[result].MTX = gObj[result].X; gObj[result].MTY = gObj[result].Y; gObj[result].m_OldX = gObj[result].X; gObj[result].m_OldY = gObj[result].Y; gObj[result].StartX = gObj[result].X; gObj[result].StartY = gObj[result].Y; if (It->second.m_Dir == (BYTE)-1) { gObj[result].Dir = rand() % 8; } else { gObj[result].Dir = It->second.m_Dir; } gObjSetMonster(result, It->second.m_Type); EnterCriticalSection(&this->m_MonCriti); ELEDORADO_MONSTER_INFO m_MonsterInfo; m_MonsterInfo.m_Index = result; this->m_mapMonsterInfo.insert(std::pair<int, ELEDORADO_MONSTER_INFO>(result, m_MonsterInfo)); LeaveCriticalSection(&this->m_MonCriti); } } void CEledoradoEvent::RegenKantur() { std::map<int, ELEDORARO_MONSTER_POS>::iterator It = this->m_vtMonsterPos.find(82); if (It == this->m_vtMonsterPos.end()) { return; } int MapNumber; for (int i = 0; i < It->second.m_Count; i++) { MapNumber = this->GetMapNumber(It); if (g_MapServerManager.CheckMapCanMove(MapNumber) == FALSE) { return; } if (MapNumber == -1) { g_Log.AddC(TColor::Red, "%s MapNumber == -1", __FUNCTION__); return; } int result = gObjAddMonster(MapNumber); if (result == -1) { g_Log.AddC(TColor::Red, "%s result == -1", __FUNCTION__); return; } gObj[result].MapNumber = MapNumber; while (this->GetBoxPosition(MapNumber, It->second.m_X, It->second.m_Y, It->second.m_W, It->second.m_H, gObj[result].X, gObj[result].Y) == 0) { } this->m_BossKanturMapNumber = gObj[result].MapNumber; this->m_BossKanturMapX = gObj[result].X; this->m_BossKanturMapY = gObj[result].Y; gObj[result].m_PosNum = -1; gObj[result].TX = gObj[result].X; gObj[result].TY = gObj[result].Y; gObj[result].MTX = gObj[result].X; gObj[result].MTY = gObj[result].Y; gObj[result].m_OldX = gObj[result].X; gObj[result].m_OldY = gObj[result].Y; gObj[result].StartX = gObj[result].X; gObj[result].StartY = gObj[result].Y; if (It->second.m_Dir == (BYTE)-1) { gObj[result].Dir = rand() % 8; } else { gObj[result].Dir = It->second.m_Dir; } gObjSetMonster(result, It->second.m_Type); EnterCriticalSection(&this->m_MonCriti); ELEDORADO_MONSTER_INFO m_MonsterInfo; m_MonsterInfo.m_Index = result; this->m_mapMonsterInfo.insert(std::pair<int, ELEDORADO_MONSTER_INFO>(result, m_MonsterInfo)); LeaveCriticalSection(&this->m_MonCriti); } It = this->m_vtMonsterPos.find(83); if (It == this->m_vtMonsterPos.end()) { return; } for (int i = 0; i < It->second.m_Count; i++) { MapNumber = this->m_BossKanturMapNumber; int result = gObjAddMonster(MapNumber); if (result == -1) { g_Log.AddC(TColor::Red, "%s result == -1", __FUNCTION__); return; } gObj[result].MapNumber = MapNumber; this->GetBoxPosition(MapNumber, this->m_BossKanturMapX - 10, m_BossKanturMapY - 10, this->m_BossKanturMapX + 10, m_BossKanturMapY + 10, gObj[result].X, gObj[result].Y); gObj[result].m_PosNum = -1; gObj[result].TX = gObj[result].X; gObj[result].TY = gObj[result].Y; gObj[result].MTX = gObj[result].X; gObj[result].MTY = gObj[result].Y; gObj[result].m_OldX = gObj[result].X; gObj[result].m_OldY = gObj[result].Y; gObj[result].StartX = gObj[result].X; gObj[result].StartY = gObj[result].Y; if (It->second.m_Dir == (BYTE)-1) { gObj[result].Dir = rand() % 8; } else { gObj[result].Dir = It->second.m_Dir; } gObjSetMonster(result, It->second.m_Type); EnterCriticalSection(&this->m_MonCriti); ELEDORADO_MONSTER_INFO m_MonsterInfo; m_MonsterInfo.m_Index = result; this->m_mapMonsterInfo.insert(std::pair<int, ELEDORADO_MONSTER_INFO>(result, m_MonsterInfo)); LeaveCriticalSection(&this->m_MonCriti); } } void CEledoradoEvent::CheckGoldDercon(int MapNumber) { if (this->EventState == 0) return; BOOL EventOn = FALSE; int EventClearMapNumber = -1; for (int i = 0; i < 4; i++) { if (this->m_BossGoldDerconMapNumber[i] != -1) { if (this->m_BossGoldDerconMapNumber[i] == MapNumber) { EventOn = TRUE; } else { EventClearMapNumber = this->m_BossGoldDerconMapNumber[i]; } } } if (EventClearMapNumber != -1) { GSProtocol.GCMapEventStateSend(EventClearMapNumber, 0, 3); } if (EventOn != FALSE) { GSProtocol.GCMapEventStateSend(MapNumber, 1, 3); } else { GSProtocol.GCMapEventStateSend(MapNumber, 0, 3); } } void CEledoradoEvent::Start_Menual() { this->SetMenualStart(TRUE); this->ClearMonster(); g_Log.Add("[Event Management] [Start] Eledorado Event!"); this->RegenGoldGoblen(); this->RegenTitan(); this->RegenGoldDercon();; this->RegenDevilLizardKing(); this->RegenKantur(); this->RegenRabbit(); this->RegenDarkKnight(); this->RegenDevil(); this->RegenDarkKnightAida(); this->RegenCrust(); this->RegenSatiros(); this->RegenTwinTail(); this->RegenIronKnight(); this->RegenNeipin(); this->RegenGreatDragon(); } void CEledoradoEvent::End_Menual() { this->SetMenualStart(FALSE); this->ClearMonster(); } void CEledoradoEvent::RegenRabbit() { std::map<int, ELEDORARO_MONSTER_POS>::iterator It = this->m_vtMonsterPos.find(502); if (It == this->m_vtMonsterPos.end()) { return; } int MapNumber; for (int i = 0; i < It->second.m_Count; i++) { MapNumber = this->GetMapNumber(It); if (g_MapServerManager.CheckMapCanMove(MapNumber) == FALSE) { return; } if (MapNumber == -1) { g_Log.AddC(TColor::Red, "%s MapNumber == -1", __FUNCTION__); return; } int result = gObjAddMonster(MapNumber); if (result == -1) { g_Log.AddC(TColor::Red, "%s result == -1", __FUNCTION__); return; } gObj[result].MapNumber = MapNumber; while (this->GetBoxPosition(MapNumber, It->second.m_X, It->second.m_Y, It->second.m_W, It->second.m_H, gObj[result].X, gObj[result].Y) == 0) { } gObj[result].m_PosNum = -1; gObj[result].TX = gObj[result].X; gObj[result].TY = gObj[result].Y; gObj[result].MTX = gObj[result].X; gObj[result].MTY = gObj[result].Y; gObj[result].m_OldX = gObj[result].X; gObj[result].m_OldY = gObj[result].Y; gObj[result].StartX = gObj[result].X; gObj[result].StartY = gObj[result].Y; if (It->second.m_Dir == (BYTE)-1) { gObj[result].Dir = rand() % 8; } else { gObj[result].Dir = It->second.m_Dir; } gObjSetMonster(result, It->second.m_Type); EnterCriticalSection(&this->m_MonCriti); ELEDORADO_MONSTER_INFO m_MonsterInfo; m_MonsterInfo.m_Index = result; this->m_mapMonsterInfo.insert(std::pair<int, ELEDORADO_MONSTER_INFO>(result, m_MonsterInfo)); LeaveCriticalSection(&this->m_MonCriti); } } void CEledoradoEvent::RegenDarkKnight() { std::map<int, ELEDORARO_MONSTER_POS>::iterator It = this->m_vtMonsterPos.find(493); if (It == this->m_vtMonsterPos.end()) { return; } int MapNumber; for (int i = 0; i < It->second.m_Count; i++) { MapNumber = this->GetMapNumber(It); if (g_MapServerManager.CheckMapCanMove(MapNumber) == FALSE) { return; } if (MapNumber == -1) { g_Log.AddC(TColor::Red, "%s MapNumber == -1", __FUNCTION__); return; } int result = gObjAddMonster(MapNumber); if (result == -1) { g_Log.AddC(TColor::Red, "%s result == -1", __FUNCTION__); return; } gObj[result].MapNumber = MapNumber; while (this->GetBoxPosition(MapNumber, It->second.m_X, It->second.m_Y, It->second.m_W, It->second.m_H, gObj[result].X, gObj[result].Y) == 0) { } gObj[result].m_PosNum = -1; gObj[result].TX = gObj[result].X; gObj[result].TY = gObj[result].Y; gObj[result].MTX = gObj[result].X; gObj[result].MTY = gObj[result].Y; gObj[result].m_OldX = gObj[result].X; gObj[result].m_OldY = gObj[result].Y; gObj[result].StartX = gObj[result].X; gObj[result].StartY = gObj[result].Y; if (It->second.m_Dir == (BYTE)-1) { gObj[result].Dir = rand() % 8; } else { gObj[result].Dir = It->second.m_Dir; } gObjSetMonster(result, It->second.m_Type); EnterCriticalSection(&this->m_MonCriti); ELEDORADO_MONSTER_INFO m_MonsterInfo; m_MonsterInfo.m_Index = result; this->m_mapMonsterInfo.insert(std::pair<int, ELEDORADO_MONSTER_INFO>(result, m_MonsterInfo)); LeaveCriticalSection(&this->m_MonCriti); } } void CEledoradoEvent::RegenDevil() { std::map<int, ELEDORARO_MONSTER_POS>::iterator It = this->m_vtMonsterPos.find(494); if (It == this->m_vtMonsterPos.end()) { return; } int MapNumber; for (int i = 0; i < It->second.m_Count; i++) { MapNumber = this->GetMapNumber(It); if (g_MapServerManager.CheckMapCanMove(MapNumber) == FALSE) { return; } if (MapNumber == -1) { g_Log.AddC(TColor::Red, "%s MapNumber == -1", __FUNCTION__); return; } int result = gObjAddMonster(MapNumber); if (result == -1) { g_Log.AddC(TColor::Red, "%s result == -1", __FUNCTION__); return; } gObj[result].MapNumber = MapNumber; while (this->GetBoxPosition(MapNumber, It->second.m_X, It->second.m_Y, It->second.m_W, It->second.m_H, gObj[result].X, gObj[result].Y) == 0) { } gObj[result].m_PosNum = -1; gObj[result].TX = gObj[result].X; gObj[result].TY = gObj[result].Y; gObj[result].MTX = gObj[result].X; gObj[result].MTY = gObj[result].Y; gObj[result].m_OldX = gObj[result].X; gObj[result].m_OldY = gObj[result].Y; gObj[result].StartX = gObj[result].X; gObj[result].StartY = gObj[result].Y; if (It->second.m_Dir == (BYTE)-1) { gObj[result].Dir = rand() % 8; } else { gObj[result].Dir = It->second.m_Dir; } gObjSetMonster(result, It->second.m_Type); EnterCriticalSection(&this->m_MonCriti); ELEDORADO_MONSTER_INFO m_MonsterInfo; m_MonsterInfo.m_Index = result; this->m_mapMonsterInfo.insert(std::pair<int, ELEDORADO_MONSTER_INFO>(result, m_MonsterInfo)); LeaveCriticalSection(&this->m_MonCriti); } } void CEledoradoEvent::RegenDarkKnightAida() { std::map<int, ELEDORARO_MONSTER_POS>::iterator It = this->m_vtMonsterPos.find(495); if (It == this->m_vtMonsterPos.end()) { return; } int MapNumber; for (int i = 0; i < It->second.m_Count; i++) { MapNumber = this->GetMapNumber(It); if (g_MapServerManager.CheckMapCanMove(MapNumber) == FALSE) { return; } if (MapNumber == -1) { g_Log.AddC(TColor::Red, "%s MapNumber == -1", __FUNCTION__); return; } int result = gObjAddMonster(MapNumber); if (result == -1) { g_Log.AddC(TColor::Red, "%s result == -1", __FUNCTION__); return; } gObj[result].MapNumber = MapNumber; while (this->GetBoxPosition(MapNumber, It->second.m_X, It->second.m_Y, It->second.m_W, It->second.m_H, gObj[result].X, gObj[result].Y) == 0) { } gObj[result].m_PosNum = -1; gObj[result].TX = gObj[result].X; gObj[result].TY = gObj[result].Y; gObj[result].MTX = gObj[result].X; gObj[result].MTY = gObj[result].Y; gObj[result].m_OldX = gObj[result].X; gObj[result].m_OldY = gObj[result].Y; gObj[result].StartX = gObj[result].X; gObj[result].StartY = gObj[result].Y; if (It->second.m_Dir == (BYTE)-1) { gObj[result].Dir = rand() % 8; } else { gObj[result].Dir = It->second.m_Dir; } gObjSetMonster(result, It->second.m_Type); EnterCriticalSection(&this->m_MonCriti); ELEDORADO_MONSTER_INFO m_MonsterInfo; m_MonsterInfo.m_Index = result; this->m_mapMonsterInfo.insert(std::pair<int, ELEDORADO_MONSTER_INFO>(result, m_MonsterInfo)); LeaveCriticalSection(&this->m_MonCriti); } } void CEledoradoEvent::RegenCrust() { std::map<int, ELEDORARO_MONSTER_POS>::iterator It = this->m_vtMonsterPos.find(496); if (It == this->m_vtMonsterPos.end()) { return; } int MapNumber; for (int i = 0; i < It->second.m_Count; i++) { MapNumber = this->GetMapNumber(It); if (g_MapServerManager.CheckMapCanMove(MapNumber) == FALSE) { return; } if (MapNumber == -1) { g_Log.AddC(TColor::Red, "%s MapNumber == -1", __FUNCTION__); return; } int result = gObjAddMonster(MapNumber); if (result == -1) { g_Log.AddC(TColor::Red, "%s result == -1", __FUNCTION__); return; } gObj[result].MapNumber = MapNumber; while (this->GetBoxPosition(MapNumber, It->second.m_X, It->second.m_Y, It->second.m_W, It->second.m_H, gObj[result].X, gObj[result].Y) == 0) { } gObj[result].m_PosNum = -1; gObj[result].TX = gObj[result].X; gObj[result].TY = gObj[result].Y; gObj[result].MTX = gObj[result].X; gObj[result].MTY = gObj[result].Y; gObj[result].m_OldX = gObj[result].X; gObj[result].m_OldY = gObj[result].Y; gObj[result].StartX = gObj[result].X; gObj[result].StartY = gObj[result].Y; if (It->second.m_Dir == (BYTE)-1) { gObj[result].Dir = rand() % 8; } else { gObj[result].Dir = It->second.m_Dir; } gObjSetMonster(result, It->second.m_Type); EnterCriticalSection(&this->m_MonCriti); ELEDORADO_MONSTER_INFO m_MonsterInfo; m_MonsterInfo.m_Index = result; this->m_mapMonsterInfo.insert(std::pair<int, ELEDORADO_MONSTER_INFO>(result, m_MonsterInfo)); LeaveCriticalSection(&this->m_MonCriti); } } void CEledoradoEvent::RegenSatiros() { std::map<int, ELEDORARO_MONSTER_POS>::iterator It = this->m_vtMonsterPos.find(497); if (It == this->m_vtMonsterPos.end()) { return; } int MapNumber; for (int i = 0; i < It->second.m_Count; i++) { MapNumber = this->GetMapNumber(It); if (g_MapServerManager.CheckMapCanMove(MapNumber) == FALSE) { return; } if (MapNumber == -1) { g_Log.AddC(TColor::Red, "%s MapNumber == -1", __FUNCTION__); return; } int result = gObjAddMonster(MapNumber); if (result == -1) { g_Log.AddC(TColor::Red, "%s result == -1", __FUNCTION__); return; } gObj[result].MapNumber = MapNumber; while (this->GetBoxPosition(MapNumber, It->second.m_X, It->second.m_Y, It->second.m_W, It->second.m_H, gObj[result].X, gObj[result].Y) == 0) { } gObj[result].m_PosNum = -1; gObj[result].TX = gObj[result].X; gObj[result].TY = gObj[result].Y; gObj[result].MTX = gObj[result].X; gObj[result].MTY = gObj[result].Y; gObj[result].m_OldX = gObj[result].X; gObj[result].m_OldY = gObj[result].Y; gObj[result].StartX = gObj[result].X; gObj[result].StartY = gObj[result].Y; if (It->second.m_Dir == (BYTE)-1) { gObj[result].Dir = rand() % 8; } else { gObj[result].Dir = It->second.m_Dir; } gObjSetMonster(result, It->second.m_Type); EnterCriticalSection(&this->m_MonCriti); ELEDORADO_MONSTER_INFO m_MonsterInfo; m_MonsterInfo.m_Index = result; this->m_mapMonsterInfo.insert(std::pair<int, ELEDORADO_MONSTER_INFO>(result, m_MonsterInfo)); LeaveCriticalSection(&this->m_MonCriti); } } void CEledoradoEvent::RegenTwinTail() { std::map<int, ELEDORARO_MONSTER_POS>::iterator It = this->m_vtMonsterPos.find(498); if (It == this->m_vtMonsterPos.end()) { return; } int MapNumber; for (int i = 0; i < It->second.m_Count; i++) { MapNumber = this->GetMapNumber(It); if (g_MapServerManager.CheckMapCanMove(MapNumber) == FALSE) { return; } if (MapNumber == -1) { g_Log.AddC(TColor::Red, "%s MapNumber == -1", __FUNCTION__); return; } int result = gObjAddMonster(MapNumber); if (result == -1) { g_Log.AddC(TColor::Red, "%s result == -1", __FUNCTION__); return; } gObj[result].MapNumber = MapNumber; while (this->GetBoxPosition(MapNumber, It->second.m_X, It->second.m_Y, It->second.m_W, It->second.m_H, gObj[result].X, gObj[result].Y) == 0) { } gObj[result].m_PosNum = -1; gObj[result].TX = gObj[result].X; gObj[result].TY = gObj[result].Y; gObj[result].MTX = gObj[result].X; gObj[result].MTY = gObj[result].Y; gObj[result].m_OldX = gObj[result].X; gObj[result].m_OldY = gObj[result].Y; gObj[result].StartX = gObj[result].X; gObj[result].StartY = gObj[result].Y; if (It->second.m_Dir == (BYTE)-1) { gObj[result].Dir = rand() % 8; } else { gObj[result].Dir = It->second.m_Dir; } gObjSetMonster(result, It->second.m_Type); EnterCriticalSection(&this->m_MonCriti); ELEDORADO_MONSTER_INFO m_MonsterInfo; m_MonsterInfo.m_Index = result; this->m_mapMonsterInfo.insert(std::pair<int, ELEDORADO_MONSTER_INFO>(result, m_MonsterInfo)); LeaveCriticalSection(&this->m_MonCriti); } } void CEledoradoEvent::RegenIronKnight() { std::map<int, ELEDORARO_MONSTER_POS>::iterator It = this->m_vtMonsterPos.find(499); if (It == this->m_vtMonsterPos.end()) { return; } int MapNumber; for (int i = 0; i < It->second.m_Count; i++) { MapNumber = this->GetMapNumber(It); if (g_MapServerManager.CheckMapCanMove(MapNumber) == FALSE) { return; } if (MapNumber == -1) { g_Log.AddC(TColor::Red, "%s MapNumber == -1", __FUNCTION__); return; } int result = gObjAddMonster(MapNumber); if (result == -1) { g_Log.AddC(TColor::Red, "%s result == -1", __FUNCTION__); return; } gObj[result].MapNumber = MapNumber; while (this->GetBoxPosition(MapNumber, It->second.m_X, It->second.m_Y, It->second.m_W, It->second.m_H, gObj[result].X, gObj[result].Y) == 0) { } gObj[result].m_PosNum = -1; gObj[result].TX = gObj[result].X; gObj[result].TY = gObj[result].Y; gObj[result].MTX = gObj[result].X; gObj[result].MTY = gObj[result].Y; gObj[result].m_OldX = gObj[result].X; gObj[result].m_OldY = gObj[result].Y; gObj[result].StartX = gObj[result].X; gObj[result].StartY = gObj[result].Y; if (It->second.m_Dir == (BYTE)-1) { gObj[result].Dir = rand() % 8; } else { gObj[result].Dir = It->second.m_Dir; } gObjSetMonster(result, It->second.m_Type); EnterCriticalSection(&this->m_MonCriti); ELEDORADO_MONSTER_INFO m_MonsterInfo; m_MonsterInfo.m_Index = result; this->m_mapMonsterInfo.insert(std::pair<int, ELEDORADO_MONSTER_INFO>(result, m_MonsterInfo)); LeaveCriticalSection(&this->m_MonCriti); } } void CEledoradoEvent::RegenNeipin() { std::map<int, ELEDORARO_MONSTER_POS>::iterator It = this->m_vtMonsterPos.find(500); if (It == this->m_vtMonsterPos.end()) { return; } int MapNumber; for (int i = 0; i < It->second.m_Count; i++) { MapNumber = this->GetMapNumber(It); if (g_MapServerManager.CheckMapCanMove(MapNumber) == FALSE) { return; } if (MapNumber == -1) { g_Log.AddC(TColor::Red, "%s MapNumber == -1", __FUNCTION__); return; } int result = gObjAddMonster(MapNumber); if (result == -1) { g_Log.AddC(TColor::Red, "%s result == -1", __FUNCTION__); return; } gObj[result].MapNumber = MapNumber; while (this->GetBoxPosition(MapNumber, It->second.m_X, It->second.m_Y, It->second.m_W, It->second.m_H, gObj[result].X, gObj[result].Y) == 0) { } gObj[result].m_PosNum = -1; gObj[result].TX = gObj[result].X; gObj[result].TY = gObj[result].Y; gObj[result].MTX = gObj[result].X; gObj[result].MTY = gObj[result].Y; gObj[result].m_OldX = gObj[result].X; gObj[result].m_OldY = gObj[result].Y; gObj[result].StartX = gObj[result].X; gObj[result].StartY = gObj[result].Y; if (It->second.m_Dir == (BYTE)-1) { gObj[result].Dir = rand() % 8; } else { gObj[result].Dir = It->second.m_Dir; } gObjSetMonster(result, It->second.m_Type); EnterCriticalSection(&this->m_MonCriti); ELEDORADO_MONSTER_INFO m_MonsterInfo; m_MonsterInfo.m_Index = result; this->m_mapMonsterInfo.insert(std::pair<int, ELEDORADO_MONSTER_INFO>(result, m_MonsterInfo)); LeaveCriticalSection(&this->m_MonCriti); } } void CEledoradoEvent::RegenGreatDragon() { std::map<int, ELEDORARO_MONSTER_POS>::iterator It = this->m_vtMonsterPos.find(501); if (It == this->m_vtMonsterPos.end()) { return; } int MapNumber; for (int i = 0; i < It->second.m_Count; i++) { MapNumber = this->GetMapNumber(It); if (g_MapServerManager.CheckMapCanMove(MapNumber) == FALSE) { return; } if (MapNumber == -1) { g_Log.AddC(TColor::Red, "%s MapNumber == -1", __FUNCTION__); return; } int result = gObjAddMonster(MapNumber); if (result == -1) { g_Log.AddC(TColor::Red, "%s result == -1", __FUNCTION__); return; } gObj[result].MapNumber = MapNumber; while (this->GetBoxPosition(MapNumber, It->second.m_X, It->second.m_Y, It->second.m_W, It->second.m_H, gObj[result].X, gObj[result].Y) == 0) { } gObj[result].m_PosNum = -1; gObj[result].TX = gObj[result].X; gObj[result].TY = gObj[result].Y; gObj[result].MTX = gObj[result].X; gObj[result].MTY = gObj[result].Y; gObj[result].m_OldX = gObj[result].X; gObj[result].m_OldY = gObj[result].Y; gObj[result].StartX = gObj[result].X; gObj[result].StartY = gObj[result].Y; if (It->second.m_Dir == (BYTE)-1) { gObj[result].Dir = rand() % 8; } else { gObj[result].Dir = It->second.m_Dir; } gObjSetMonster(result, It->second.m_Type); EnterCriticalSection(&this->m_MonCriti); ELEDORADO_MONSTER_INFO m_MonsterInfo; m_MonsterInfo.m_Index = result; this->m_mapMonsterInfo.insert(std::pair<int, ELEDORADO_MONSTER_INFO>(result, m_MonsterInfo)); LeaveCriticalSection(&this->m_MonCriti); } } BOOL CEledoradoEvent::GetBoxPosition(int mapnumber, int ax, int ay, int aw, int ah, short &mx, short &my) { int count = 100; int w; int h; int tx; int ty; BYTE attr; while (count-- != 0) { w = aw - ax; h = ah - ay; __try { tx = ax + (rand() % w); ty = ay + (rand() % h); } __except (w = 1, h = 1, 1) { } attr = MapC[mapnumber].GetAttr(tx, ty); if (((attr & 1) != 1) && ((attr & 4) != 4) && ((attr & 8) != 8)) { mx = tx; my = ty; return TRUE; } } return false; } BYTE CEledoradoEvent::GetMapNumber(std::map<int, ELEDORARO_MONSTER_POS>::iterator Iter) { int count = 100; BYTE MapNumber = -1; while (count-- != 0) { MapNumber = Iter->second.m_MapNumber[rand() % 4]; if (MapNumber != (BYTE)-1) { break; } } if (MapNumber == (BYTE)-1) { MapNumber = Iter->second.m_MapNumber[0]; } return MapNumber; } ELEDORARO_MONSTER_POS * CEledoradoEvent::GetMonsterPos(int iMonsterIndex) { std::map<int, ELEDORARO_MONSTER_POS>::iterator It = this->m_vtMonsterPos.find(iMonsterIndex); if (It == this->m_vtMonsterPos.end()) { return nullptr; } return &It->second; } bool CEledoradoEvent::IsEledoradoMonster(int iIndex) { std::map<int, ELEDORADO_MONSTER_INFO>::iterator It = this->m_mapMonsterInfo.find(iIndex); if (It == this->m_mapMonsterInfo.end()) { return false; } return true; } //////////////////////////////////////////////////////////////////////////////// // vnDev.Games - MuServer S12EP2 IGC v12.0.1.0 - Trong.LIVE - DAO VAN TRONG // ////////////////////////////////////////////////////////////////////////////////
f60a79a38f47636b6beba15e92fa0eab7fe2fcea
979a7439f73e608c82f32edfd05336ee114e3158
/lib/Logger-1.0.3/src/Logger.cpp
939e43bf0fd0d2eee3a8d1f81bdbc448e9d399c6
[]
no_license
damiandrzewicz/air-sensor-iot
c105454f3c76d10bc53625c3e6fc92dc914c694f
891943f52e4e5ad46c76ad34b00eb46dd6adc6aa
refs/heads/main
2023-05-15T21:56:47.396328
2021-05-24T21:39:10
2021-05-24T21:39:10
355,950,832
0
0
null
null
null
null
UTF-8
C++
false
false
3,140
cpp
// ============================================================================= // // Copyright (c) 2013-2016 Christopher Baker <http://christopherbaker.net> // // 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 "Logger.h" #if defined(ARDUINO_ARCH_AVR) #include <avr/pgmspace.h> #endif // There appears to be an incompatibility with ESP8266 2.3.0. #if defined(ESP8266) #define MEM_TYPE #else #define MEM_TYPE PROGMEM #endif const char LEVEL_VERBOSE[] MEM_TYPE = "VERBOSE"; const char LEVEL_DEBUG[] MEM_TYPE = "DEBUG"; const char LEVEL_NOTICE[] MEM_TYPE = "NOTICE"; const char LEVEL_WARNING[] MEM_TYPE = "WARNING"; const char LEVEL_ERROR[] MEM_TYPE = "ERROR"; const char LEVEL_FATAL[] MEM_TYPE = "FATAL"; const char LEVEL_PROFILE[] MEM_TYPE = "PROFILE"; const char LEVEL_SILENT[] MEM_TYPE = "SILENT"; const char* const LOG_LEVEL_STRINGS[] MEM_TYPE = { LEVEL_VERBOSE, LEVEL_DEBUG, LEVEL_NOTICE, LEVEL_WARNING, LEVEL_ERROR, LEVEL_FATAL, LEVEL_PROFILE, LEVEL_SILENT }; char Logger::MessageBuffer[100] = {}; char Logger::LevelBuffer[10] = {}; char Logger::OutputBuffer[300] = {}; Logger::Logger(): _level(WARNING), _loggerOutputFunction(defaultOutputFunction) { } void Logger::setLogLevel(Level level) { getInstance()._level = level; } Logger::Level Logger::getLogLevel() { return getInstance()._level; } void Logger::setOutputFunction(LoggerOutputFunction loggerOutputFunction) { getInstance()._loggerOutputFunction = loggerOutputFunction; } Logger& Logger::getInstance() { static Logger logger; return logger; } const char* Logger::asString(Level level) { strcpy_P(LevelBuffer, reinterpret_cast<PGM_P>(pgm_read_word(&LOG_LEVEL_STRINGS[level]))); return LevelBuffer; } void Logger::defaultOutputFunction(Level level, const char* module, const char* message) { sprintf(OutputBuffer, "[%-12ld] [%-8s] [%-20s] %s", millis(), asString(level), module, message ); Serial.println(OutputBuffer); }
bfdd579cb150ffe91bd8d26a2947116845e23d1f
950b506e3f8fd978f076a5b9a3a950f6f4d5607b
/inno/summer-shop-2017/05:07/kthstat/solutions/no_graders/x.cpp
1125422140c7ac7d9e422f1b9e6f7ad9ddf4ae5d
[]
no_license
Mityai/contests
2e130ebb8d4280b82e7e017037fc983063228931
5b406b2a94cc487b0c71cb10386d1b89afd1e143
refs/heads/master
2021-01-09T06:09:17.441079
2019-01-19T12:47:20
2019-01-19T12:47:20
80,909,953
4
0
null
null
null
null
UTF-8
C++
false
false
346
cpp
#include <cstdio> #include <algorithm> #define forn(i, n) for (int i = 0; i < (int)(n); i++) const int n = 10; int a[n]; void out() { printf("%d :", n); forn(i, n) printf(" %d", a[i]); puts(""); } int main() { forn(i, n) a[i] = i; out(); std::rotate(a, a + n - 1, a + n); out(); return 0; }
e5911037b182ed9a342e106f518bea810ef1220c
a37534f6e3b3a6b1c3e9b158fc4d4ce7c733a8cb
/ros/champ/champ_base/src/quadruped_controller.cpp
f11ab8f7591fedf66d485ad1ee3ba527ae7a9f2b
[]
no_license
nicholaspalomo/spot-loco
3701da378980ebcbf2d86b7fa191b87586eeca4c
b9125003be04b4fd2c5eb76224eab7369a2307e6
refs/heads/main
2023-05-06T03:25:04.502820
2021-06-03T05:02:36
2021-06-03T05:02:36
371,278,363
0
0
null
null
null
null
UTF-8
C++
false
false
29,612
cpp
/* Copyright (c) 2019-2020, Juan Miguel Jimeno 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 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 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 <quadruped_controller.h> QuadrupedController::QuadrupedController(ros::NodeHandle* nh, ros::NodeHandle* pnh) : body_controller_(base_), leg_controller_(base_), kinematics_(base_) { std::string joint_control_topic = "joint_group_position_controller/command"; std::string knee_orientation; double loop_rate = 250.0; nh->getParam("gait/pantograph_leg", gait_config_.pantograph_leg); nh->getParam("gait/max_linear_velocity_x", gait_config_.max_linear_velocity_x); nh->getParam("gait/max_linear_velocity_y", gait_config_.max_linear_velocity_y); nh->getParam("gait/max_angular_velocity_z", gait_config_.max_angular_velocity_z); nh->getParam("gait/com_x_translation", gait_config_.com_x_translation); nh->getParam("gait/swing_height", gait_config_.swing_height); nh->getParam("gait/stance_depth", gait_config_.stance_depth); nh->getParam("gait/stance_duration", gait_config_.stance_duration); nh->getParam("gait/nominal_height", gait_config_.nominal_height); nh->getParam("gait/knee_orientation", knee_orientation); pnh->getParam("publish_foot_contacts", publish_foot_contacts_); pnh->getParam("publish_joint_states", publish_joint_states_); pnh->getParam("publish_joint_control", publish_joint_control_); pnh->getParam("gazebo", in_gazebo_); pnh->getParam("joint_controller_topic", joint_control_topic); pnh->getParam("loop_rate", loop_rate); // vvv For RL locomotion controller // Load the parameters for the RL controller from the parameter server nh->getParam("rl_controller/p_gain", rl_controller_config_.p_gain); nh->getParam("rl_controller/d_gain", rl_controller_config_.d_gain); nh->getParam("rl_controller/control_dt", rl_controller_config_.control_dt); nh->getParam("rl_controller/obs_dim", rl_controller_config_.obs_dim); nh->getParam("rl_controller/acts_dim", rl_controller_config_.acts_dim); nh->getParam("rl_controller/target_vel_lim_x", rl_controller_config_.target_vel_lim_x); nh->getParam("rl_controller/target_vel_lim_y", rl_controller_config_.target_vel_lim_y); nh->getParam("rl_controller/target_vel_lim_r", rl_controller_config_.target_vel_lim_r); nh->getParam("rl_controller/n_joints", rl_controller_config_.n_joints); // Load action scalings from parameter server nh->getParam("rl_controller/action_scaling/action_mean/haa", rl_controller_config_.action_mean_haa); nh->getParam("rl_controller/action_scaling/action_mean/hfe", rl_controller_config_.action_mean_hfe); nh->getParam("rl_controller/action_scaling/action_mean/kfe", rl_controller_config_.action_mean_kfe); nh->getParam("rl_controller/action_scaling/action_mean/gait_frequency", rl_controller_config_.action_mean_gait_freq); nh->getParam("rl_controller/action_scaling/action_std/haa", rl_controller_config_.action_std_haa); nh->getParam("rl_controller/action_scaling/action_std/hfe", rl_controller_config_.action_std_hfe); nh->getParam("rl_controller/action_scaling/action_std/kfe", rl_controller_config_.action_std_kfe); nh->getParam("rl_controller/action_scaling/action_std/gait_frequency", rl_controller_config_.action_std_gait_freq); // Load observation scalings from parameter server nh->getParam("rl_controller/observation_scaling/observation_mean/base_height", rl_controller_config_.obs_mean_base_height); nh->getParam( "rl_controller/observation_scaling/observation_mean/gravity_axis", rl_controller_config_.obs_mean_grav_axis); nh->getParam( "rl_controller/observation_scaling/observation_mean/joint_position/haa", rl_controller_config_.obs_mean_joint_pos_haa); nh->getParam( "rl_controller/observation_scaling/observation_mean/joint_position/hfe", rl_controller_config_.obs_mean_joint_pos_hfe); nh->getParam( "rl_controller/observation_scaling/observation_mean/joint_position/kfe", rl_controller_config_.obs_mean_joint_pos_kfe); nh->getParam( "rl_controller/observation_scaling/observation_mean/body_lin_vel", rl_controller_config_.obs_mean_body_lin_vel); nh->getParam( "rl_controller/observation_scaling/observation_mean/body_ang_vel", rl_controller_config_.obs_mean_body_ang_vel); nh->getParam("rl_controller/observation_scaling/observation_mean/joint_vel", rl_controller_config_.obs_mean_joint_vel); nh->getParam( "rl_controller/observation_scaling/observation_mean/target_vel/x", rl_controller_config_.obs_mean_target_vel_x); nh->getParam( "rl_controller/observation_scaling/observation_mean/target_vel/y", rl_controller_config_.obs_mean_target_vel_y); nh->getParam( "rl_controller/observation_scaling/observation_mean/target_vel/r", rl_controller_config_.obs_mean_target_vel_r); nh->getParam("rl_controller/observation_scaling/observation_mean/action_hist", rl_controller_config_.obs_mean_action_hist); nh->getParam("rl_controller/observation_scaling/observation_mean/stride", rl_controller_config_.obs_mean_stride); nh->getParam("rl_controller/observation_scaling/observation_mean/swing_start", rl_controller_config_.obs_mean_swing_start); nh->getParam( "rl_controller/observation_scaling/observation_mean/swing_duration", rl_controller_config_.obs_mean_swing_duration); nh->getParam( "rl_controller/observation_scaling/observation_mean/phase_time_left", rl_controller_config_.obs_mean_phase_time_left); nh->getParam( "rl_controller/observation_scaling/observation_mean/foot_contact_state", rl_controller_config_.obs_mean_foot_contact); nh->getParam("rl_controller/observation_scaling/observation_mean/" "desired_contact_state", rl_controller_config_.obs_mean_des_foot_contact); nh->getParam( "rl_controller/observation_scaling/observation_mean/ee_clearance", rl_controller_config_.obs_mean_ee_clearance); nh->getParam("rl_controller/observation_scaling/observation_mean/ee_target", rl_controller_config_.obs_mean_ee_target); nh->getParam( "rl_controller/observation_scaling/observation_mean/body_vel_error", rl_controller_config_.obs_mean_body_vel_error); nh->getParam("rl_controller/observation_scaling/observation_std/base_height", rl_controller_config_.obs_std_base_height); nh->getParam("rl_controller/observation_scaling/observation_std/gravity_axis", rl_controller_config_.obs_std_grav_axis); nh->getParam( "rl_controller/observation_scaling/observation_std/joint_position/haa", rl_controller_config_.obs_std_joint_pos_haa); nh->getParam( "rl_controller/observation_scaling/observation_std/joint_position/hfe", rl_controller_config_.obs_std_joint_pos_hfe); nh->getParam( "rl_controller/observation_scaling/observation_std/joint_position/kfe", rl_controller_config_.obs_std_joint_pos_kfe); nh->getParam("rl_controller/observation_scaling/observation_std/body_lin_vel", rl_controller_config_.obs_std_body_lin_vel); nh->getParam("rl_controller/observation_scaling/observation_std/body_ang_vel", rl_controller_config_.obs_std_body_ang_vel); nh->getParam("rl_controller/observation_scaling/observation_std/joint_vel", rl_controller_config_.obs_std_joint_vel); nh->getParam("rl_controller/observation_scaling/observation_std/target_vel/x", rl_controller_config_.obs_std_target_vel_x); nh->getParam("rl_controller/observation_scaling/observation_std/target_vel/y", rl_controller_config_.obs_std_target_vel_y); nh->getParam("rl_controller/observation_scaling/observation_std/target_vel/r", rl_controller_config_.obs_std_target_vel_r); nh->getParam("rl_controller/observation_scaling/observation_std/action_hist", rl_controller_config_.obs_std_action_hist); nh->getParam("rl_controller/observation_scaling/observation_std/stride", rl_controller_config_.obs_std_stride); nh->getParam("rl_controller/observation_scaling/observation_std/swing_start", rl_controller_config_.obs_std_swing_start); nh->getParam( "rl_controller/observation_scaling/observation_std/swing_duration", rl_controller_config_.obs_std_swing_duration); nh->getParam( "rl_controller/observation_scaling/observation_std/phase_time_left", rl_controller_config_.obs_std_phase_time_left); nh->getParam( "rl_controller/observation_scaling/observation_std/foot_contact_state", rl_controller_config_.obs_std_foot_contact); nh->getParam("rl_controller/observation_scaling/observation_std/" "desired_contact_state", rl_controller_config_.obs_std_des_foot_contact); nh->getParam("rl_controller/observation_scaling/observation_std/ee_clearance", rl_controller_config_.obs_std_ee_clearance); nh->getParam("rl_controller/observation_scaling/observation_std/ee_target", rl_controller_config_.obs_std_ee_target); nh->getParam( "rl_controller/observation_scaling/observation_std/body_vel_error", rl_controller_config_.obs_std_body_vel_error); nh->getParam("rl_controller/gait_params/stride", rl_controller_config_.gait_stride); nh->getParam("rl_controller/gait_params/max_foot_height", rl_controller_config_.max_foot_height); nh->getParam("rl_controller/gait_params/swing_start", *(rl_controller_config_.swing_start)); nh->getParam("rl_controller/gait_params/swing_duration", *(rl_controller_config_.swing_duration)); nh->getParam("rl_controller/sim_dt", loop_rate_); nh->getParam("rl_controller/control_dt", control_dt_); // Load the parameters for self-righting nh->getParam("rl_controller/self_right_params/automatic", automatic_self_righting_enabled_); nh->getParam("rl_controller/self_right_params/model_name", gazebo_model_name_); // Load the parameters for the IMU subscription nh->getParam("rl_controller/imu/topic_name", imu_topic_name_); nh->getParam("rl_controller/imu/position", *(imu_lin_offset_pos_)); nh->getParam("rl_controller/imu/orientation", *(imu_ang_offset_pos_)); // Get the transformation matrix from the IMU to the body center. T_B_to_imu_ = getTransformBtoIMU(imu_lin_offset_pos_, imu_ang_offset_pos_); getRotationAndOffsetFromTransformation( T_B_to_imu_, rot_base_to_imu_, offset_base_to_imu_); quat_base_to_imu_ = rotMatToQuat(rot_base_to_imu_); rl_controller_config_.initialize_controller_scalings(); state_scaled_.setZero(rl_controller_config_.obs_dim); state_unscaled_.setZero(rl_controller_config_.obs_dim); joint_velocity_.setZero(rl_controller_config_.n_joints); joint_position_.setZero(rl_controller_config_.n_joints); action_history_.setZero(3 * rl_controller_config_.acts_dim); action_.setZero(rl_controller_config_.acts_dim); currErr_.setZero(rl_controller_config_.n_joints); prevErr_.setZero(rl_controller_config_.n_joints); joint_angle_subscriber_ = nh->subscribe( "joint_states", 100, &QuadrupedController::jointStatesCallback_, this); ground_truth_odom_subscriber_ = nh->subscribe("ground_truth/odometry", 100, &QuadrupedController::groundTruthOdomCallback_, this); set_spot_pose_srv_ = nh->serviceClient<gazebo_msgs::SetModelState>("/gazebo/set_model_state"); self_righting_srv_ = nh->advertiseService( "self_right", &QuadrupedController::selfRightRobotSrvCallback_, this); pause_gazebo_ = nh->serviceClient<std_srvs::Empty>("/gazebo/pause_physics"); unpause_gazebo_ = nh->serviceClient<std_srvs::Empty>("/gazebo/unpause_physics"); std::string torchscriptNetDir(NETWORK_WEIGHTS_DIR); torchscriptNetDir.append("loco_controller.pt"); net_.load(torchscriptNetDir); //^^^ cmd_vel_subscriber_ = nh->subscribe( "cmd_vel/smooth", 100, &QuadrupedController::cmdVelCallback_, this); cmd_pose_subscriber_ = nh->subscribe( "body_pose", 100, &QuadrupedController::cmdPoseCallback_, this); if (publish_joint_control_) { joint_commands_publisher_ = nh->advertise<std_msgs::Float64MultiArray>(joint_control_topic, 100); } if (publish_joint_states_ && !in_gazebo_) { joint_states_publisher_ = nh->advertise<sensor_msgs::JointState>("joint_states", 100); } if (publish_foot_contacts_ && !in_gazebo_) { foot_contacts_publisher_ = nh->advertise<champ_msgs::ContactsStamped>("foot_contacts", 100); } gait_config_.knee_orientation = knee_orientation.c_str(); base_.setGaitConfig(gait_config_); champ::URDF::loadFromServer(base_, nh); joint_names_ = champ::URDF::getJointNames(nh); loop_timer_ = pnh->createTimer( ros::Duration(loop_rate_), &QuadrupedController::controlLoopRl_, this); start_ = ros::WallTime::now(); req_pose_.position.z = gait_config_.nominal_height; } bool QuadrupedController::selfRightRobotSrvCallback_( std_srvs::Trigger::Request& req, std_srvs::Trigger::Response& res) { setRobotUpright_(); res.success = true; return true; } void QuadrupedController::setRobotUpright_() { if (rotMatBtoI_.row(2)[2] < 0.7) { pose_.model_name = gazebo_model_name_; pose_.pose.position.x = body_position_(0); pose_.pose.position.y = body_position_(1); pose_.pose.position.z = 0.54; // get the projection of the x-axis in the horizontal plane Eigen::Vector3d x = rotMatBtoI_.col(0); double theta = std::atan2(x(1), x(0)); pose_.pose.orientation.x = 0.; pose_.pose.orientation.y = 0.; pose_.pose.orientation.z = std::sin(theta / 2.); pose_.pose.orientation.w = std::cos(theta / 2.); gazebo_msgs::SetModelState srv; srv.request.model_state = pose_; std_srvs::Empty empty_srv; pause_gazebo_.call(empty_srv); set_spot_pose_srv_.call(srv); unpause_gazebo_.call(empty_srv); } } void QuadrupedController::callback( const sensor_msgs::JointState::ConstPtr& joint_msg, const nav_msgs::OdometryConstPtr& ground_truth_msg) { jointStatesCallback_(joint_msg); groundTruthOdomCallback_(ground_truth_msg); } void QuadrupedController::controlLoopRl_(const ros::TimerEvent& event) { if (control_step_ % int(control_dt_ / max(loop_rate_, (start_ - ros::WallTime::now()).toSec())) == 0) { control_step_ = 0; getStateForRlLocoController_(); getActionFromRlLocoController_(); updateGaitParameters_(); // publish joint angle targets float target_joint_positions[12]; for (int i = 0; i < rl_controller_config_.n_joints; i++) { target_joint_positions[i] = (float)action_(i); } publishJoints_(target_joint_positions); } control_step_++; // perform self-righting, if the robot is in danger of falling over if (automatic_self_righting_enabled_) { setRobotUpright_(); } start_ = ros::WallTime::now(); } void QuadrupedController::setJointControllersGains_() { // TODO: Set the PID gains for the joint controllers to the same as those used // in the training code } void QuadrupedController::getStateForRlLocoController_() { int pos = 0; // base gravity axis rotMatBtoI_ = quatToRotMat(quat_base_to_inertial_); state_unscaled_.segment(pos, 3) = rotMatBtoI_.row(2); pos += 3; // joint angles state_unscaled_.segment(pos, rl_controller_config_.n_joints) = joint_position_; pos += rl_controller_config_.n_joints; // body velocities (in the body frame) state_unscaled_.segment(pos, 3) = body_lin_velocity_; pos += 3; state_unscaled_.segment(pos, 3) = body_ang_velocity_; pos += 3; // joint velocities state_unscaled_.segment(pos, rl_controller_config_.n_joints) = joint_velocity_; pos += rl_controller_config_.n_joints; // target velocity state_unscaled_(pos) = req_vel_.linear.x; pos++; state_unscaled_(pos) = req_vel_.linear.y; pos++; state_unscaled_(pos) = req_vel_.angular.z; pos++; // action history state_unscaled_.segment(pos, 3 * rl_controller_config_.acts_dim) = action_history_; pos += 3 * rl_controller_config_.acts_dim; // stride state_unscaled_(pos) = rl_controller_config_.gait_stride; pos++; for (int i = 0; i < 4; i++) { if (!is_stance_gait_) { // swing start state_unscaled_(pos) = rl_controller_config_.swing_start[i]; // swing duration state_unscaled_(pos + 4) = rl_controller_config_.swing_duration[i]; // phase time left state_unscaled_(pos + 8) = phase_time_left_[i]; } else { // swing start state_unscaled_(pos) = rl_controller_config_.stance_swing_start[i]; // swing duration state_unscaled_(pos + 4) = rl_controller_config_.stance_swing_duration[i]; // phase time left state_unscaled_(pos + 8) = 1.; phase_ = 0.; } if (!is_stance_gait_) { // desired contact states state_unscaled_(pos + 12) = desired_foot_contacts_[i]; } else { state_unscaled_(pos + 12) = true; } pos++; } pos += 12; // 16; int n_joints = rl_controller_config_.n_joints; int buffer_len = rl_controller_config_.buffer_len; if (step_ % rl_controller_config_.buffer_stride == 0) { step_ = 0; // joint position history Eigen::VectorXd temp; temp.setZero((buffer_len - 1) * n_joints); temp = state_unscaled_.segment(pos + n_joints, n_joints * (buffer_len - 1)); state_unscaled_.segment(pos + n_joints * (buffer_len - 1), n_joints) = action_.segment(0, n_joints) - joint_position_; state_unscaled_.segment(pos, n_joints * (buffer_len - 1)) = temp; pos += n_joints * buffer_len; // joint velocity history temp.setZero((buffer_len - 1) * n_joints); temp = state_unscaled_.segment(pos + n_joints, n_joints * (buffer_len - 1)); state_unscaled_.segment(pos + n_joints * (buffer_len - 1), n_joints) = joint_velocity_; state_unscaled_.segment(pos, n_joints * (buffer_len - 1)) = temp; pos += n_joints * buffer_len; temp.setZero(3 * (buffer_len - 1)); temp = state_unscaled_.segment(pos + 3, 3 * (buffer_len - 1)); Eigen::Vector3d bodyVelErr; bodyVelErr(0) = req_vel_.linear.x - body_lin_velocity_(0); bodyVelErr(1) = req_vel_.linear.y - body_lin_velocity_(1); bodyVelErr(2) = req_vel_.angular.z - body_ang_velocity_(2); state_unscaled_.segment(pos + 3 * (buffer_len - 1), 3) = bodyVelErr; state_unscaled_.segment(pos, 3 * (buffer_len - 1)) = temp; pos += 3 * buffer_len; } step_++; state_scaled_ = (state_unscaled_ - rl_controller_config_.obsMean) .cwiseQuotient(rl_controller_config_.obsStd); } void QuadrupedController::getActionFromRlLocoController_() { Eigen::Matrix<double, 13, 1> action_unscaled; net_.forward<double, 13, 362>(action_unscaled, state_scaled_); action_ = action_unscaled.cwiseProduct(rl_controller_config_.actionStd) + rl_controller_config_.actionMean; Eigen::VectorXd temp; temp.setZero(2 * rl_controller_config_.acts_dim); temp = action_history_.segment(rl_controller_config_.acts_dim, 2 * rl_controller_config_.acts_dim); action_history_.segment(0, 2 * rl_controller_config_.acts_dim) = temp; action_history_.segment(2 * rl_controller_config_.acts_dim, rl_controller_config_.acts_dim) = action_; } void QuadrupedController::updateGaitParameters_() { if (!is_stance_gait_) { double freq = (1.0 / rl_controller_config_.gait_stride + action_(rl_controller_config_.acts_dim - 1)) * rl_controller_config_.control_dt; phase_ = wrap_01(phase_ + freq); for (int i = 0; i < 4; i++) { double swingEnd = wrap_01(rl_controller_config_.swing_start[i] + rl_controller_config_.swing_duration[i]); double phaseShifted = wrap_01(phase_ - swingEnd); double swingStartShifted = 1.0 - rl_controller_config_.swing_duration[i]; if (phaseShifted < swingStartShifted) { desired_foot_contacts_[i] = true; phase_time_left_[i] = (swingStartShifted - phaseShifted) * rl_controller_config_.gait_stride; target_foot_clearance_[i] = 0.0; } else { desired_foot_contacts_[i] = false; phase_time_left_[i] = (1.0 - phaseShifted) * rl_controller_config_.gait_stride; target_foot_clearance_[i] = rl_controller_config_.max_foot_height * (-std::sin(2 * M_PI * phaseShifted) < 0. ? 0. : -std::sin(2 * M_PI * phaseShifted)); } } } } void QuadrupedController::groundTruthOdomCallback_( const nav_msgs::OdometryConstPtr& msg) { body_position_(0) = msg->pose.pose.position.x; body_position_(1) = msg->pose.pose.position.y; body_position_(2) = msg->pose.pose.position.z; quat_base_to_inertial_(0) = msg->pose.pose.orientation.w; quat_base_to_inertial_(1) = msg->pose.pose.orientation.x; quat_base_to_inertial_(2) = msg->pose.pose.orientation.y; quat_base_to_inertial_(3) = msg->pose.pose.orientation.z; quat_base_to_inertial_.normalize(); rotMatBtoI_ = quatToRotMat(quat_base_to_inertial_); body_lin_velocity_(0) = msg->twist.twist.linear.x; body_lin_velocity_(1) = msg->twist.twist.linear.y; body_lin_velocity_(2) = msg->twist.twist.linear.z; body_lin_velocity_ = rotMatBtoI_.transpose() * body_lin_velocity_; body_ang_velocity_(0) = msg->twist.twist.angular.x; body_ang_velocity_(1) = msg->twist.twist.angular.y; body_ang_velocity_(2) = msg->twist.twist.angular.z; body_ang_velocity_ = rotMatBtoI_.transpose() * body_ang_velocity_; } void QuadrupedController::endEffectorContactCallback_( const gazebo_msgs::ContactsState::ConstPtr& msg) { // order of the legs is: FL, FR, RL, RR std::vector<std::string> foot_names = { "spot1::front_left_lower_leg::front_left_lower_leg_collision", "spot1::front_right_lower_leg::front_right_lower_leg_collision", "spot1::rear_left_lower_leg::rear_left_lower_leg_collision", "spot1::rear_right_lower_leg::rear_right_lower_leg_collision"}; std::string ground_name = "ground_plane::link::collision"; for (int i = 0; i < 4; i++) foot_contacts_[i] = false; for (int i = 0; i < msg->states.size(); i++) { std::set<std::string> contact_strings; contact_strings.insert(msg->states[i].collision1_name); contact_strings.insert(msg->states[i].collision2_name); for (int j = 0; j < 4; j++) { if (contact_strings.find(foot_names[j]) != contact_strings.end()) { if (contact_strings.find(ground_name) != contact_strings.end()) { foot_contacts_[j] = true; } } } } } void QuadrupedController::imuCallback_(const sensor_msgs::Imu::ConstPtr& msg) { quat_base_to_inertial_(0) = msg->orientation.w; quat_base_to_inertial_(1) = msg->orientation.x; quat_base_to_inertial_(2) = msg->orientation.y; quat_base_to_inertial_(3) = msg->orientation.z; quat_base_to_inertial_.normalize(); body_ang_velocity_(0) = msg->angular_velocity.x; body_ang_velocity_(1) = msg->angular_velocity.y; body_ang_velocity_(2) = msg->angular_velocity.z; // transform the vectors into the correct frame according to the IMU // orientation given in the URDF (for now, hardcoded into the startup script). quat_base_to_inertial_ = quatMult( quat_base_to_inertial_, quat_base_to_imu_); // quaternion rotation from body frame to global frame body_ang_velocity_ = rot_base_to_imu_.transpose() * body_ang_velocity_; // base angular velocity expressed in base frame } void QuadrupedController::bodyVelocityCallback_( const geometry_msgs::Twist::ConstPtr& msg) { body_lin_velocity_(0) = msg->linear.x; body_lin_velocity_(1) = msg->linear.y; body_lin_velocity_(2) = msg->linear.z; body_ang_velocity_(0) = msg->angular.x; body_ang_velocity_(1) = msg->angular.y; body_ang_velocity_(2) = msg->angular.z; } void QuadrupedController::jointStatesCallback_( const sensor_msgs::JointState::ConstPtr& msg) { for (int i = 0; i < rl_controller_config_.n_joints; i++) { joint_position_(i) = msg->position[i]; joint_velocity_(i) = msg->velocity[i]; } } void QuadrupedController::controlLoop_(const ros::TimerEvent& event) { float target_joint_positions[12]; geometry::Transformation target_foot_positions[4]; bool foot_contacts[4]; body_controller_.poseCommand(target_foot_positions, req_pose_); leg_controller_.velocityCommand(target_foot_positions, req_vel_); kinematics_.inverse(target_joint_positions, target_foot_positions); for(size_t i = 0; i < 4; i++) { if(base_.legs[i]->gait_phase()) foot_contacts[i] = 1; else foot_contacts[i] = 0; } publishFootContacts_(foot_contacts); publishJoints_(target_joint_positions); } void QuadrupedController::cmdVelCallback_(const geometry_msgs::Twist::ConstPtr& msg) { req_vel_.linear.x = clamp(msg->linear.x, -rl_controller_config_.target_vel_lim_x, rl_controller_config_.target_vel_lim_x); req_vel_.linear.y = clamp(msg->linear.y, -rl_controller_config_.target_vel_lim_y, rl_controller_config_.target_vel_lim_y); req_vel_.angular.z = clamp(msg->angular.z, -rl_controller_config_.target_vel_lim_r, rl_controller_config_.target_vel_lim_r); // if ((req_vel_.linear.x * req_vel_.linear.x + // req_vel_.linear.y * req_vel_.linear.y + // req_vel_.angular.z * req_vel_.angular.z) < 0.1) { // is_stance_gait_ = true; // req_vel_.linear.x = 0.; // req_vel_.linear.y = 0.; // req_vel_.angular.z = 0.; // } else { // is_stance_gait_ = false; // } } void QuadrupedController::cmdPoseCallback_(const geometry_msgs::Pose::ConstPtr& msg) { tf::Quaternion base_quat; base_quat[0] = msg->orientation.x; base_quat[1] = msg->orientation.y; base_quat[2] = msg->orientation.z; base_quat[3] = msg->orientation.w; tf::Matrix3x3 m(base_quat); double roll, pitch, yaw; m.getRPY(roll, pitch, yaw); req_pose_.orientation.roll = roll; req_pose_.orientation.pitch = pitch; req_pose_.orientation.yaw = yaw; req_pose_.position.x = msg->position.x; req_pose_.position.y = msg->position.y; req_pose_.position.z = msg->position.z + gait_config_.nominal_height; } void QuadrupedController::publishJoints_(float target_joints[12]) { if(publish_joint_control_) { std_msgs::Float64MultiArray joints_cmd_msg; joints_cmd_msg.data.resize(12); for (size_t i = 0; i < 12; i++) { joints_cmd_msg.data[i] = target_joints[i]; } joint_commands_publisher_.publish(joints_cmd_msg); } if(publish_joint_states_ && !in_gazebo_) { sensor_msgs::JointState joints_msg; joints_msg.header.stamp = ros::Time::now(); joints_msg.name.resize(joint_names_.size()); joints_msg.position.resize(joint_names_.size()); joints_msg.name = joint_names_; for (size_t i = 0; i < joint_names_.size(); ++i) { joints_msg.position[i]= target_joints[i]; } joint_states_publisher_.publish(joints_msg); } } void QuadrupedController::publishFootContacts_(bool foot_contacts[4]) { if(publish_foot_contacts_ && !in_gazebo_) { champ_msgs::ContactsStamped contacts_msg; contacts_msg.header.stamp = ros::Time::now(); contacts_msg.contacts.resize(4); for(size_t i = 0; i < 4; i++) { contacts_msg.contacts[i] = foot_contacts[i]; } foot_contacts_publisher_.publish(contacts_msg); } }
2192cb9bbaa0e4e927cf38792953be76bb43f158
835c3fe722b0b39cf57765c11c037f3a628a73a1
/OldMaidCardGame-MockTesting/test/OldMaidUIMockTest.h
85ba8de4e7af7b37fcd1dadf8c9faf7e14276586
[]
no_license
richardsm32/SchoolProjects
07909a80d909b98c279067ccf5ea91dfc304fc1d
388200311c4c5a855270be151e3545ca0c74edef
refs/heads/master
2020-12-13T16:38:13.126600
2020-01-21T05:03:33
2020-01-21T05:03:33
234,474,086
0
0
null
null
null
null
UTF-8
C++
false
false
1,088
h
#ifndef OLDMAIDUIMOCKTEST_H_INCLUDED #define OLDMAIDUIMOCKTEST_H_INCLUDED #include "OldMaidUI.h" #include <vector> #include <string> #include "gmock/gmock.h" using testing::Return; class MockOldMaidUI : public OldMaidUI { public: MockOldMaidUI() {} ~MockOldMaidUI() {} MOCK_METHOD0(welcome, void()); MOCK_METHOD0(invalid, void()); MOCK_METHOD1(getReady, void(int players)); MOCK_METHOD0(initPairs, void()); MOCK_METHOD1(startGame, void(int playerTurn)); MOCK_METHOD3(pTurn, void(int, int, vector<vector<Cards*> >)); MOCK_METHOD2(pEndTurn, void(int, vector<vector<Cards*> >)); MOCK_METHOD1(printHand, void(vector<vector<Cards*> >)); MOCK_METHOD2(aiStartTurn, void(int, int)); MOCK_METHOD3(aiEndTurn, void(int, int, vector<vector<Cards*> >)); MOCK_METHOD1(discardCheck, void(Deck*)); MOCK_METHOD0(emptyHand, void()); MOCK_METHOD0(announcePair, void()); MOCK_METHOD1(endGame, void(int)); MOCK_METHOD1(suitToStr, string(Cards*)); MOCK_METHOD1(valueToStr, string(Cards*)); }; #endif // OLDMAIDUIMOCKTEST_H_INCLUDED
b2f365f0fceae9bcd4294f8eafdf3bc023ff00a5
428989cb9837b6fedeb95e4fcc0a89f705542b24
/erle/ros2_ws/build/std_msgs/rosidl_generator_cpp/std_msgs/msg/float32_multi_array__struct.hpp
b2ac5308659643b9cbda290c69dd746fe87aa7c6
[]
no_license
swift-nav/ros_rover
70406572cfcf413ce13cf6e6b47a43d5298d64fc
308f10114b35c70b933ee2a47be342e6c2f2887a
refs/heads/master
2020-04-14T22:51:38.911378
2016-07-08T21:44:22
2016-07-08T21:44:22
60,873,336
1
2
null
null
null
null
UTF-8
C++
false
false
3,694
hpp
// generated from rosidl_generator_cpp/resource/msg__struct.hpp.template #ifndef __std_msgs__msg__float32_multi_array__struct__hpp__ #define __std_msgs__msg__float32_multi_array__struct__hpp__ #include <array> #include <memory> #include <string> #include <vector> // include message dependencies #include <std_msgs/msg/multi_array_layout.hpp> #ifndef _WIN32 # define DEPRECATED_std_msgs_msg_Float32MultiArray __attribute__((deprecated)) #else # define DEPRECATED_std_msgs_msg_Float32MultiArray __declspec(deprecated) #endif namespace std_msgs { namespace msg { // message struct template<class ContainerAllocator> struct Float32MultiArray_ { using Type = Float32MultiArray_<ContainerAllocator>; Float32MultiArray_() { } Float32MultiArray_(const ContainerAllocator & _alloc) : data(_alloc) { } // field types and members using _layout_type = std_msgs::msg::MultiArrayLayout_<ContainerAllocator>; _layout_type layout; using _data_type = std::vector<float, typename ContainerAllocator::template rebind<float>::other>; _data_type data; // setters for named parameter idiom Type * set__layout(const std_msgs::msg::MultiArrayLayout_<ContainerAllocator> & _arg) { this->layout = _arg; return this; } Type * set__data(const std::vector<float, typename ContainerAllocator::template rebind<float>::other> & _arg) { this->data = _arg; return this; } // constants // pointer types using RawPtr = std_msgs::msg::Float32MultiArray_<ContainerAllocator> *; using ConstRawPtr = const std_msgs::msg::Float32MultiArray_<ContainerAllocator> *; using SharedPtr = std::shared_ptr<std_msgs::msg::Float32MultiArray_<ContainerAllocator>>; using ConstSharedPtr = std::shared_ptr<std_msgs::msg::Float32MultiArray_<ContainerAllocator> const>; template<typename Deleter = std::default_delete<std_msgs::msg::Float32MultiArray_<ContainerAllocator>>> using UniquePtrWithDeleter = std::unique_ptr<std_msgs::msg::Float32MultiArray_<ContainerAllocator>, Deleter>; using UniquePtr = UniquePtrWithDeleter<>; template<typename Deleter = std::default_delete<std_msgs::msg::Float32MultiArray_<ContainerAllocator>>> using ConstUniquePtrWithDeleter = std::unique_ptr<std_msgs::msg::Float32MultiArray_<ContainerAllocator> const, Deleter>; using ConstUniquePtr = ConstUniquePtrWithDeleter<>; using WeakPtr = std::weak_ptr<std_msgs::msg::Float32MultiArray_<ContainerAllocator>>; using ConstWeakPtr = std::weak_ptr<std_msgs::msg::Float32MultiArray_<ContainerAllocator> const>; // pointer types similar to ROS 1, use SharedPtr / ConstSharedPtr instead // NOTE: Can't use 'using' here because GNU C++ can't parse attributes properly typedef DEPRECATED_std_msgs_msg_Float32MultiArray std::shared_ptr<std_msgs::msg::Float32MultiArray_<ContainerAllocator>> Ptr; typedef DEPRECATED_std_msgs_msg_Float32MultiArray std::shared_ptr<std_msgs::msg::Float32MultiArray_<ContainerAllocator> const> ConstPtr; // comparison operators bool operator==(const Float32MultiArray_ & other) const { if (this->layout != other.layout) { return false; } if (this->data != other.data) { return false; } return true; } bool operator!=(const Float32MultiArray_ & other) const { return !this->operator==(other); } }; // struct Float32MultiArray_ // alias to use template instance with default allocator using Float32MultiArray = std_msgs::msg::Float32MultiArray_<std::allocator<void>>; // constants requiring out of line definition } // namespace msg } // namespace std_msgs #endif // __std_msgs__msg__float32_multi_array__struct__hpp__
457c7ee2e55c478f7546a2391a191d9efb26c69d
0a435c7742b0517156b69b5a14ddde08c42a69cb
/Plugins/AdvancedSessions/AdvancedSessions/Intermediate/Build/Mac/UE4/Inc/AdvancedSessions/AdvancedFriendsLibrary.gen.cpp
d60d23a0d0495c3569b3f51366016c85efb9b59b
[ "MIT" ]
permissive
sworley8/miSoMadness
bca7cd6e93748978f317456caacd698d3612923d
f604537ee6ccc4da4043fc317642d6f3743cc29f
refs/heads/master
2023-01-28T10:17:12.756037
2020-11-30T23:27:22
2020-11-30T23:27:22
293,003,717
0
6
null
2020-12-06T01:43:50
2020-09-05T04:41:35
C++
UTF-8
C++
false
false
38,593
cpp
// Copyright Epic Games, Inc. All Rights Reserved. /*=========================================================================== Generated code exported from UnrealHeaderTool. DO NOT modify this manually! Edit the corresponding .h files instead! ===========================================================================*/ #include "UObject/GeneratedCppIncludes.h" #include "AdvancedSessions/Classes/AdvancedFriendsLibrary.h" #ifdef _MSC_VER #pragma warning (push) #pragma warning (disable : 4883) #endif PRAGMA_DISABLE_DEPRECATION_WARNINGS void EmptyLinkFunctionForGeneratedCodeAdvancedFriendsLibrary() {} // Cross Module References ADVANCEDSESSIONS_API UClass* Z_Construct_UClass_UAdvancedFriendsLibrary_NoRegister(); ADVANCEDSESSIONS_API UClass* Z_Construct_UClass_UAdvancedFriendsLibrary(); ENGINE_API UClass* Z_Construct_UClass_UBlueprintFunctionLibrary(); UPackage* Z_Construct_UPackage__Script_AdvancedSessions(); ADVANCEDSESSIONS_API UScriptStruct* Z_Construct_UScriptStruct_FBPFriendInfo(); ADVANCEDSESSIONS_API UScriptStruct* Z_Construct_UScriptStruct_FBPUniqueNetId(); ENGINE_API UClass* Z_Construct_UClass_APlayerController_NoRegister(); ADVANCEDSESSIONS_API UScriptStruct* Z_Construct_UScriptStruct_FBPOnlineRecentPlayer(); ADVANCEDSESSIONS_API UEnum* Z_Construct_UEnum_AdvancedSessions_EBlueprintResultSwitch(); // End Cross Module References DEFINE_FUNCTION(UAdvancedFriendsLibrary::execIsAFriend) { P_GET_OBJECT(APlayerController,Z_Param_PlayerController); P_GET_STRUCT(FBPUniqueNetId,Z_Param_UniqueNetId); P_GET_UBOOL_REF(Z_Param_Out_IsFriend); P_FINISH; P_NATIVE_BEGIN; UAdvancedFriendsLibrary::IsAFriend(Z_Param_PlayerController,Z_Param_UniqueNetId,Z_Param_Out_IsFriend); P_NATIVE_END; } DEFINE_FUNCTION(UAdvancedFriendsLibrary::execGetStoredRecentPlayersList) { P_GET_STRUCT(FBPUniqueNetId,Z_Param_UniqueNetId); P_GET_TARRAY_REF(FBPOnlineRecentPlayer,Z_Param_Out_PlayersList); P_FINISH; P_NATIVE_BEGIN; UAdvancedFriendsLibrary::GetStoredRecentPlayersList(Z_Param_UniqueNetId,Z_Param_Out_PlayersList); P_NATIVE_END; } DEFINE_FUNCTION(UAdvancedFriendsLibrary::execGetStoredFriendsList) { P_GET_OBJECT(APlayerController,Z_Param_PlayerController); P_GET_TARRAY_REF(FBPFriendInfo,Z_Param_Out_FriendsList); P_FINISH; P_NATIVE_BEGIN; UAdvancedFriendsLibrary::GetStoredFriendsList(Z_Param_PlayerController,Z_Param_Out_FriendsList); P_NATIVE_END; } DEFINE_FUNCTION(UAdvancedFriendsLibrary::execGetFriend) { P_GET_OBJECT(APlayerController,Z_Param_PlayerController); P_GET_STRUCT(FBPUniqueNetId,Z_Param_FriendUniqueNetId); P_GET_STRUCT_REF(FBPFriendInfo,Z_Param_Out_Friend); P_FINISH; P_NATIVE_BEGIN; UAdvancedFriendsLibrary::GetFriend(Z_Param_PlayerController,Z_Param_FriendUniqueNetId,Z_Param_Out_Friend); P_NATIVE_END; } DEFINE_FUNCTION(UAdvancedFriendsLibrary::execSendSessionInviteToFriend) { P_GET_OBJECT(APlayerController,Z_Param_PlayerController); P_GET_STRUCT_REF(FBPUniqueNetId,Z_Param_Out_FriendUniqueNetId); P_GET_ENUM_REF(EBlueprintResultSwitch,Z_Param_Out_Result); P_FINISH; P_NATIVE_BEGIN; UAdvancedFriendsLibrary::SendSessionInviteToFriend(Z_Param_PlayerController,Z_Param_Out_FriendUniqueNetId,(EBlueprintResultSwitch&)(Z_Param_Out_Result)); P_NATIVE_END; } DEFINE_FUNCTION(UAdvancedFriendsLibrary::execSendSessionInviteToFriends) { P_GET_OBJECT(APlayerController,Z_Param_PlayerController); P_GET_TARRAY_REF(FBPUniqueNetId,Z_Param_Out_Friends); P_GET_ENUM_REF(EBlueprintResultSwitch,Z_Param_Out_Result); P_FINISH; P_NATIVE_BEGIN; UAdvancedFriendsLibrary::SendSessionInviteToFriends(Z_Param_PlayerController,Z_Param_Out_Friends,(EBlueprintResultSwitch&)(Z_Param_Out_Result)); P_NATIVE_END; } void UAdvancedFriendsLibrary::StaticRegisterNativesUAdvancedFriendsLibrary() { UClass* Class = UAdvancedFriendsLibrary::StaticClass(); static const FNameNativePtrPair Funcs[] = { { "GetFriend", &UAdvancedFriendsLibrary::execGetFriend }, { "GetStoredFriendsList", &UAdvancedFriendsLibrary::execGetStoredFriendsList }, { "GetStoredRecentPlayersList", &UAdvancedFriendsLibrary::execGetStoredRecentPlayersList }, { "IsAFriend", &UAdvancedFriendsLibrary::execIsAFriend }, { "SendSessionInviteToFriend", &UAdvancedFriendsLibrary::execSendSessionInviteToFriend }, { "SendSessionInviteToFriends", &UAdvancedFriendsLibrary::execSendSessionInviteToFriends }, }; FNativeFunctionRegistrar::RegisterFunctions(Class, Funcs, UE_ARRAY_COUNT(Funcs)); } struct Z_Construct_UFunction_UAdvancedFriendsLibrary_GetFriend_Statics { struct AdvancedFriendsLibrary_eventGetFriend_Parms { APlayerController* PlayerController; FBPUniqueNetId FriendUniqueNetId; FBPFriendInfo Friend; }; static const UE4CodeGen_Private::FStructPropertyParams NewProp_Friend; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_FriendUniqueNetId_MetaData[]; #endif static const UE4CodeGen_Private::FStructPropertyParams NewProp_FriendUniqueNetId; static const UE4CodeGen_Private::FObjectPropertyParams NewProp_PlayerController; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; const UE4CodeGen_Private::FStructPropertyParams Z_Construct_UFunction_UAdvancedFriendsLibrary_GetFriend_Statics::NewProp_Friend = { "Friend", nullptr, (EPropertyFlags)0x0010000000000180, UE4CodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(AdvancedFriendsLibrary_eventGetFriend_Parms, Friend), Z_Construct_UScriptStruct_FBPFriendInfo, METADATA_PARAMS(nullptr, 0) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UAdvancedFriendsLibrary_GetFriend_Statics::NewProp_FriendUniqueNetId_MetaData[] = { { "NativeConst", "" }, }; #endif const UE4CodeGen_Private::FStructPropertyParams Z_Construct_UFunction_UAdvancedFriendsLibrary_GetFriend_Statics::NewProp_FriendUniqueNetId = { "FriendUniqueNetId", nullptr, (EPropertyFlags)0x0010000000000082, UE4CodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(AdvancedFriendsLibrary_eventGetFriend_Parms, FriendUniqueNetId), Z_Construct_UScriptStruct_FBPUniqueNetId, METADATA_PARAMS(Z_Construct_UFunction_UAdvancedFriendsLibrary_GetFriend_Statics::NewProp_FriendUniqueNetId_MetaData, UE_ARRAY_COUNT(Z_Construct_UFunction_UAdvancedFriendsLibrary_GetFriend_Statics::NewProp_FriendUniqueNetId_MetaData)) }; const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UFunction_UAdvancedFriendsLibrary_GetFriend_Statics::NewProp_PlayerController = { "PlayerController", nullptr, (EPropertyFlags)0x0010000000000080, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(AdvancedFriendsLibrary_eventGetFriend_Parms, PlayerController), Z_Construct_UClass_APlayerController_NoRegister, METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UAdvancedFriendsLibrary_GetFriend_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UAdvancedFriendsLibrary_GetFriend_Statics::NewProp_Friend, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UAdvancedFriendsLibrary_GetFriend_Statics::NewProp_FriendUniqueNetId, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UAdvancedFriendsLibrary_GetFriend_Statics::NewProp_PlayerController, }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UAdvancedFriendsLibrary_GetFriend_Statics::Function_MetaDataParams[] = { { "Category", "Online|AdvancedFriends|FriendsList" }, { "Comment", "// Get a friend from the previously read/saved friends list (Must Call GetFriends first for this to return anything)\n" }, { "ModuleRelativePath", "Classes/AdvancedFriendsLibrary.h" }, { "ToolTip", "Get a friend from the previously read/saved friends list (Must Call GetFriends first for this to return anything)" }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UAdvancedFriendsLibrary_GetFriend_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UAdvancedFriendsLibrary, nullptr, "GetFriend", nullptr, nullptr, sizeof(AdvancedFriendsLibrary_eventGetFriend_Parms), Z_Construct_UFunction_UAdvancedFriendsLibrary_GetFriend_Statics::PropPointers, UE_ARRAY_COUNT(Z_Construct_UFunction_UAdvancedFriendsLibrary_GetFriend_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x04422401, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UAdvancedFriendsLibrary_GetFriend_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_UAdvancedFriendsLibrary_GetFriend_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_UAdvancedFriendsLibrary_GetFriend() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UAdvancedFriendsLibrary_GetFriend_Statics::FuncParams); } return ReturnFunction; } struct Z_Construct_UFunction_UAdvancedFriendsLibrary_GetStoredFriendsList_Statics { struct AdvancedFriendsLibrary_eventGetStoredFriendsList_Parms { APlayerController* PlayerController; TArray<FBPFriendInfo> FriendsList; }; static const UE4CodeGen_Private::FArrayPropertyParams NewProp_FriendsList; static const UE4CodeGen_Private::FStructPropertyParams NewProp_FriendsList_Inner; static const UE4CodeGen_Private::FObjectPropertyParams NewProp_PlayerController; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; const UE4CodeGen_Private::FArrayPropertyParams Z_Construct_UFunction_UAdvancedFriendsLibrary_GetStoredFriendsList_Statics::NewProp_FriendsList = { "FriendsList", nullptr, (EPropertyFlags)0x0010000000000180, UE4CodeGen_Private::EPropertyGenFlags::Array, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(AdvancedFriendsLibrary_eventGetStoredFriendsList_Parms, FriendsList), EArrayPropertyFlags::None, METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FStructPropertyParams Z_Construct_UFunction_UAdvancedFriendsLibrary_GetStoredFriendsList_Statics::NewProp_FriendsList_Inner = { "FriendsList", nullptr, (EPropertyFlags)0x0000000000000000, UE4CodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, 0, Z_Construct_UScriptStruct_FBPFriendInfo, METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UFunction_UAdvancedFriendsLibrary_GetStoredFriendsList_Statics::NewProp_PlayerController = { "PlayerController", nullptr, (EPropertyFlags)0x0010000000000080, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(AdvancedFriendsLibrary_eventGetStoredFriendsList_Parms, PlayerController), Z_Construct_UClass_APlayerController_NoRegister, METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UAdvancedFriendsLibrary_GetStoredFriendsList_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UAdvancedFriendsLibrary_GetStoredFriendsList_Statics::NewProp_FriendsList, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UAdvancedFriendsLibrary_GetStoredFriendsList_Statics::NewProp_FriendsList_Inner, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UAdvancedFriendsLibrary_GetStoredFriendsList_Statics::NewProp_PlayerController, }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UAdvancedFriendsLibrary_GetStoredFriendsList_Statics::Function_MetaDataParams[] = { { "Category", "Online|AdvancedFriends|FriendsList" }, { "Comment", "// Get the previously read/saved friends list (Must Call GetFriends first for this to return anything)\n" }, { "ModuleRelativePath", "Classes/AdvancedFriendsLibrary.h" }, { "ToolTip", "Get the previously read/saved friends list (Must Call GetFriends first for this to return anything)" }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UAdvancedFriendsLibrary_GetStoredFriendsList_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UAdvancedFriendsLibrary, nullptr, "GetStoredFriendsList", nullptr, nullptr, sizeof(AdvancedFriendsLibrary_eventGetStoredFriendsList_Parms), Z_Construct_UFunction_UAdvancedFriendsLibrary_GetStoredFriendsList_Statics::PropPointers, UE_ARRAY_COUNT(Z_Construct_UFunction_UAdvancedFriendsLibrary_GetStoredFriendsList_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x04422401, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UAdvancedFriendsLibrary_GetStoredFriendsList_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_UAdvancedFriendsLibrary_GetStoredFriendsList_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_UAdvancedFriendsLibrary_GetStoredFriendsList() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UAdvancedFriendsLibrary_GetStoredFriendsList_Statics::FuncParams); } return ReturnFunction; } struct Z_Construct_UFunction_UAdvancedFriendsLibrary_GetStoredRecentPlayersList_Statics { struct AdvancedFriendsLibrary_eventGetStoredRecentPlayersList_Parms { FBPUniqueNetId UniqueNetId; TArray<FBPOnlineRecentPlayer> PlayersList; }; static const UE4CodeGen_Private::FArrayPropertyParams NewProp_PlayersList; static const UE4CodeGen_Private::FStructPropertyParams NewProp_PlayersList_Inner; static const UE4CodeGen_Private::FStructPropertyParams NewProp_UniqueNetId; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; const UE4CodeGen_Private::FArrayPropertyParams Z_Construct_UFunction_UAdvancedFriendsLibrary_GetStoredRecentPlayersList_Statics::NewProp_PlayersList = { "PlayersList", nullptr, (EPropertyFlags)0x0010000000000180, UE4CodeGen_Private::EPropertyGenFlags::Array, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(AdvancedFriendsLibrary_eventGetStoredRecentPlayersList_Parms, PlayersList), EArrayPropertyFlags::None, METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FStructPropertyParams Z_Construct_UFunction_UAdvancedFriendsLibrary_GetStoredRecentPlayersList_Statics::NewProp_PlayersList_Inner = { "PlayersList", nullptr, (EPropertyFlags)0x0000000000000000, UE4CodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, 0, Z_Construct_UScriptStruct_FBPOnlineRecentPlayer, METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FStructPropertyParams Z_Construct_UFunction_UAdvancedFriendsLibrary_GetStoredRecentPlayersList_Statics::NewProp_UniqueNetId = { "UniqueNetId", nullptr, (EPropertyFlags)0x0010000000000080, UE4CodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(AdvancedFriendsLibrary_eventGetStoredRecentPlayersList_Parms, UniqueNetId), Z_Construct_UScriptStruct_FBPUniqueNetId, METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UAdvancedFriendsLibrary_GetStoredRecentPlayersList_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UAdvancedFriendsLibrary_GetStoredRecentPlayersList_Statics::NewProp_PlayersList, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UAdvancedFriendsLibrary_GetStoredRecentPlayersList_Statics::NewProp_PlayersList_Inner, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UAdvancedFriendsLibrary_GetStoredRecentPlayersList_Statics::NewProp_UniqueNetId, }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UAdvancedFriendsLibrary_GetStoredRecentPlayersList_Statics::Function_MetaDataParams[] = { { "Category", "Online|AdvancedFriends|RecentPlayersList" }, { "Comment", "// Get the previously read/saved recent players list (Must Call GetRecentPlayers first for this to return anything)\n" }, { "ModuleRelativePath", "Classes/AdvancedFriendsLibrary.h" }, { "ToolTip", "Get the previously read/saved recent players list (Must Call GetRecentPlayers first for this to return anything)" }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UAdvancedFriendsLibrary_GetStoredRecentPlayersList_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UAdvancedFriendsLibrary, nullptr, "GetStoredRecentPlayersList", nullptr, nullptr, sizeof(AdvancedFriendsLibrary_eventGetStoredRecentPlayersList_Parms), Z_Construct_UFunction_UAdvancedFriendsLibrary_GetStoredRecentPlayersList_Statics::PropPointers, UE_ARRAY_COUNT(Z_Construct_UFunction_UAdvancedFriendsLibrary_GetStoredRecentPlayersList_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x04422401, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UAdvancedFriendsLibrary_GetStoredRecentPlayersList_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_UAdvancedFriendsLibrary_GetStoredRecentPlayersList_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_UAdvancedFriendsLibrary_GetStoredRecentPlayersList() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UAdvancedFriendsLibrary_GetStoredRecentPlayersList_Statics::FuncParams); } return ReturnFunction; } struct Z_Construct_UFunction_UAdvancedFriendsLibrary_IsAFriend_Statics { struct AdvancedFriendsLibrary_eventIsAFriend_Parms { APlayerController* PlayerController; FBPUniqueNetId UniqueNetId; bool IsFriend; }; static void NewProp_IsFriend_SetBit(void* Obj); static const UE4CodeGen_Private::FBoolPropertyParams NewProp_IsFriend; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_UniqueNetId_MetaData[]; #endif static const UE4CodeGen_Private::FStructPropertyParams NewProp_UniqueNetId; static const UE4CodeGen_Private::FObjectPropertyParams NewProp_PlayerController; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; void Z_Construct_UFunction_UAdvancedFriendsLibrary_IsAFriend_Statics::NewProp_IsFriend_SetBit(void* Obj) { ((AdvancedFriendsLibrary_eventIsAFriend_Parms*)Obj)->IsFriend = 1; } const UE4CodeGen_Private::FBoolPropertyParams Z_Construct_UFunction_UAdvancedFriendsLibrary_IsAFriend_Statics::NewProp_IsFriend = { "IsFriend", nullptr, (EPropertyFlags)0x0010000000000180, UE4CodeGen_Private::EPropertyGenFlags::Bool | UE4CodeGen_Private::EPropertyGenFlags::NativeBool, RF_Public|RF_Transient|RF_MarkAsNative, 1, sizeof(bool), sizeof(AdvancedFriendsLibrary_eventIsAFriend_Parms), &Z_Construct_UFunction_UAdvancedFriendsLibrary_IsAFriend_Statics::NewProp_IsFriend_SetBit, METADATA_PARAMS(nullptr, 0) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UAdvancedFriendsLibrary_IsAFriend_Statics::NewProp_UniqueNetId_MetaData[] = { { "NativeConst", "" }, }; #endif const UE4CodeGen_Private::FStructPropertyParams Z_Construct_UFunction_UAdvancedFriendsLibrary_IsAFriend_Statics::NewProp_UniqueNetId = { "UniqueNetId", nullptr, (EPropertyFlags)0x0010000000000082, UE4CodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(AdvancedFriendsLibrary_eventIsAFriend_Parms, UniqueNetId), Z_Construct_UScriptStruct_FBPUniqueNetId, METADATA_PARAMS(Z_Construct_UFunction_UAdvancedFriendsLibrary_IsAFriend_Statics::NewProp_UniqueNetId_MetaData, UE_ARRAY_COUNT(Z_Construct_UFunction_UAdvancedFriendsLibrary_IsAFriend_Statics::NewProp_UniqueNetId_MetaData)) }; const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UFunction_UAdvancedFriendsLibrary_IsAFriend_Statics::NewProp_PlayerController = { "PlayerController", nullptr, (EPropertyFlags)0x0010000000000080, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(AdvancedFriendsLibrary_eventIsAFriend_Parms, PlayerController), Z_Construct_UClass_APlayerController_NoRegister, METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UAdvancedFriendsLibrary_IsAFriend_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UAdvancedFriendsLibrary_IsAFriend_Statics::NewProp_IsFriend, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UAdvancedFriendsLibrary_IsAFriend_Statics::NewProp_UniqueNetId, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UAdvancedFriendsLibrary_IsAFriend_Statics::NewProp_PlayerController, }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UAdvancedFriendsLibrary_IsAFriend_Statics::Function_MetaDataParams[] = { { "Category", "Online|AdvancedFriends|FriendsList" }, { "Comment", "// Check if a UniqueNetId is a friend\n" }, { "ModuleRelativePath", "Classes/AdvancedFriendsLibrary.h" }, { "ToolTip", "Check if a UniqueNetId is a friend" }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UAdvancedFriendsLibrary_IsAFriend_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UAdvancedFriendsLibrary, nullptr, "IsAFriend", nullptr, nullptr, sizeof(AdvancedFriendsLibrary_eventIsAFriend_Parms), Z_Construct_UFunction_UAdvancedFriendsLibrary_IsAFriend_Statics::PropPointers, UE_ARRAY_COUNT(Z_Construct_UFunction_UAdvancedFriendsLibrary_IsAFriend_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x14422401, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UAdvancedFriendsLibrary_IsAFriend_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_UAdvancedFriendsLibrary_IsAFriend_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_UAdvancedFriendsLibrary_IsAFriend() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UAdvancedFriendsLibrary_IsAFriend_Statics::FuncParams); } return ReturnFunction; } struct Z_Construct_UFunction_UAdvancedFriendsLibrary_SendSessionInviteToFriend_Statics { struct AdvancedFriendsLibrary_eventSendSessionInviteToFriend_Parms { APlayerController* PlayerController; FBPUniqueNetId FriendUniqueNetId; EBlueprintResultSwitch Result; }; static const UE4CodeGen_Private::FEnumPropertyParams NewProp_Result; static const UE4CodeGen_Private::FBytePropertyParams NewProp_Result_Underlying; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_FriendUniqueNetId_MetaData[]; #endif static const UE4CodeGen_Private::FStructPropertyParams NewProp_FriendUniqueNetId; static const UE4CodeGen_Private::FObjectPropertyParams NewProp_PlayerController; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; const UE4CodeGen_Private::FEnumPropertyParams Z_Construct_UFunction_UAdvancedFriendsLibrary_SendSessionInviteToFriend_Statics::NewProp_Result = { "Result", nullptr, (EPropertyFlags)0x0010000000000180, UE4CodeGen_Private::EPropertyGenFlags::Enum, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(AdvancedFriendsLibrary_eventSendSessionInviteToFriend_Parms, Result), Z_Construct_UEnum_AdvancedSessions_EBlueprintResultSwitch, METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FBytePropertyParams Z_Construct_UFunction_UAdvancedFriendsLibrary_SendSessionInviteToFriend_Statics::NewProp_Result_Underlying = { "UnderlyingType", nullptr, (EPropertyFlags)0x0000000000000000, UE4CodeGen_Private::EPropertyGenFlags::Byte, RF_Public|RF_Transient|RF_MarkAsNative, 1, 0, nullptr, METADATA_PARAMS(nullptr, 0) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UAdvancedFriendsLibrary_SendSessionInviteToFriend_Statics::NewProp_FriendUniqueNetId_MetaData[] = { { "NativeConst", "" }, }; #endif const UE4CodeGen_Private::FStructPropertyParams Z_Construct_UFunction_UAdvancedFriendsLibrary_SendSessionInviteToFriend_Statics::NewProp_FriendUniqueNetId = { "FriendUniqueNetId", nullptr, (EPropertyFlags)0x0010000008000182, UE4CodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(AdvancedFriendsLibrary_eventSendSessionInviteToFriend_Parms, FriendUniqueNetId), Z_Construct_UScriptStruct_FBPUniqueNetId, METADATA_PARAMS(Z_Construct_UFunction_UAdvancedFriendsLibrary_SendSessionInviteToFriend_Statics::NewProp_FriendUniqueNetId_MetaData, UE_ARRAY_COUNT(Z_Construct_UFunction_UAdvancedFriendsLibrary_SendSessionInviteToFriend_Statics::NewProp_FriendUniqueNetId_MetaData)) }; const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UFunction_UAdvancedFriendsLibrary_SendSessionInviteToFriend_Statics::NewProp_PlayerController = { "PlayerController", nullptr, (EPropertyFlags)0x0010000000000080, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(AdvancedFriendsLibrary_eventSendSessionInviteToFriend_Parms, PlayerController), Z_Construct_UClass_APlayerController_NoRegister, METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UAdvancedFriendsLibrary_SendSessionInviteToFriend_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UAdvancedFriendsLibrary_SendSessionInviteToFriend_Statics::NewProp_Result, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UAdvancedFriendsLibrary_SendSessionInviteToFriend_Statics::NewProp_Result_Underlying, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UAdvancedFriendsLibrary_SendSessionInviteToFriend_Statics::NewProp_FriendUniqueNetId, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UAdvancedFriendsLibrary_SendSessionInviteToFriend_Statics::NewProp_PlayerController, }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UAdvancedFriendsLibrary_SendSessionInviteToFriend_Statics::Function_MetaDataParams[] = { { "Category", "Online|AdvancedFriends|FriendsList" }, { "Comment", "// Sends an Invite to the current online session to a friend\n" }, { "ExpandEnumAsExecs", "Result" }, { "ModuleRelativePath", "Classes/AdvancedFriendsLibrary.h" }, { "ToolTip", "Sends an Invite to the current online session to a friend" }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UAdvancedFriendsLibrary_SendSessionInviteToFriend_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UAdvancedFriendsLibrary, nullptr, "SendSessionInviteToFriend", nullptr, nullptr, sizeof(AdvancedFriendsLibrary_eventSendSessionInviteToFriend_Parms), Z_Construct_UFunction_UAdvancedFriendsLibrary_SendSessionInviteToFriend_Statics::PropPointers, UE_ARRAY_COUNT(Z_Construct_UFunction_UAdvancedFriendsLibrary_SendSessionInviteToFriend_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x04422401, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UAdvancedFriendsLibrary_SendSessionInviteToFriend_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_UAdvancedFriendsLibrary_SendSessionInviteToFriend_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_UAdvancedFriendsLibrary_SendSessionInviteToFriend() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UAdvancedFriendsLibrary_SendSessionInviteToFriend_Statics::FuncParams); } return ReturnFunction; } struct Z_Construct_UFunction_UAdvancedFriendsLibrary_SendSessionInviteToFriends_Statics { struct AdvancedFriendsLibrary_eventSendSessionInviteToFriends_Parms { APlayerController* PlayerController; TArray<FBPUniqueNetId> Friends; EBlueprintResultSwitch Result; }; static const UE4CodeGen_Private::FEnumPropertyParams NewProp_Result; static const UE4CodeGen_Private::FBytePropertyParams NewProp_Result_Underlying; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_Friends_MetaData[]; #endif static const UE4CodeGen_Private::FArrayPropertyParams NewProp_Friends; static const UE4CodeGen_Private::FStructPropertyParams NewProp_Friends_Inner; static const UE4CodeGen_Private::FObjectPropertyParams NewProp_PlayerController; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; const UE4CodeGen_Private::FEnumPropertyParams Z_Construct_UFunction_UAdvancedFriendsLibrary_SendSessionInviteToFriends_Statics::NewProp_Result = { "Result", nullptr, (EPropertyFlags)0x0010000000000180, UE4CodeGen_Private::EPropertyGenFlags::Enum, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(AdvancedFriendsLibrary_eventSendSessionInviteToFriends_Parms, Result), Z_Construct_UEnum_AdvancedSessions_EBlueprintResultSwitch, METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FBytePropertyParams Z_Construct_UFunction_UAdvancedFriendsLibrary_SendSessionInviteToFriends_Statics::NewProp_Result_Underlying = { "UnderlyingType", nullptr, (EPropertyFlags)0x0000000000000000, UE4CodeGen_Private::EPropertyGenFlags::Byte, RF_Public|RF_Transient|RF_MarkAsNative, 1, 0, nullptr, METADATA_PARAMS(nullptr, 0) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UAdvancedFriendsLibrary_SendSessionInviteToFriends_Statics::NewProp_Friends_MetaData[] = { { "NativeConst", "" }, }; #endif const UE4CodeGen_Private::FArrayPropertyParams Z_Construct_UFunction_UAdvancedFriendsLibrary_SendSessionInviteToFriends_Statics::NewProp_Friends = { "Friends", nullptr, (EPropertyFlags)0x0010000008000182, UE4CodeGen_Private::EPropertyGenFlags::Array, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(AdvancedFriendsLibrary_eventSendSessionInviteToFriends_Parms, Friends), EArrayPropertyFlags::None, METADATA_PARAMS(Z_Construct_UFunction_UAdvancedFriendsLibrary_SendSessionInviteToFriends_Statics::NewProp_Friends_MetaData, UE_ARRAY_COUNT(Z_Construct_UFunction_UAdvancedFriendsLibrary_SendSessionInviteToFriends_Statics::NewProp_Friends_MetaData)) }; const UE4CodeGen_Private::FStructPropertyParams Z_Construct_UFunction_UAdvancedFriendsLibrary_SendSessionInviteToFriends_Statics::NewProp_Friends_Inner = { "Friends", nullptr, (EPropertyFlags)0x0000000000000000, UE4CodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, 0, Z_Construct_UScriptStruct_FBPUniqueNetId, METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UFunction_UAdvancedFriendsLibrary_SendSessionInviteToFriends_Statics::NewProp_PlayerController = { "PlayerController", nullptr, (EPropertyFlags)0x0010000000000080, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(AdvancedFriendsLibrary_eventSendSessionInviteToFriends_Parms, PlayerController), Z_Construct_UClass_APlayerController_NoRegister, METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UAdvancedFriendsLibrary_SendSessionInviteToFriends_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UAdvancedFriendsLibrary_SendSessionInviteToFriends_Statics::NewProp_Result, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UAdvancedFriendsLibrary_SendSessionInviteToFriends_Statics::NewProp_Result_Underlying, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UAdvancedFriendsLibrary_SendSessionInviteToFriends_Statics::NewProp_Friends, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UAdvancedFriendsLibrary_SendSessionInviteToFriends_Statics::NewProp_Friends_Inner, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UAdvancedFriendsLibrary_SendSessionInviteToFriends_Statics::NewProp_PlayerController, }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UAdvancedFriendsLibrary_SendSessionInviteToFriends_Statics::Function_MetaDataParams[] = { { "Category", "Online|AdvancedFriends|FriendsList" }, { "Comment", "// Sends an Invite to the current online session to a list of friends\n" }, { "ExpandEnumAsExecs", "Result" }, { "ModuleRelativePath", "Classes/AdvancedFriendsLibrary.h" }, { "ToolTip", "Sends an Invite to the current online session to a list of friends" }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UAdvancedFriendsLibrary_SendSessionInviteToFriends_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UAdvancedFriendsLibrary, nullptr, "SendSessionInviteToFriends", nullptr, nullptr, sizeof(AdvancedFriendsLibrary_eventSendSessionInviteToFriends_Parms), Z_Construct_UFunction_UAdvancedFriendsLibrary_SendSessionInviteToFriends_Statics::PropPointers, UE_ARRAY_COUNT(Z_Construct_UFunction_UAdvancedFriendsLibrary_SendSessionInviteToFriends_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x04422401, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UAdvancedFriendsLibrary_SendSessionInviteToFriends_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_UAdvancedFriendsLibrary_SendSessionInviteToFriends_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_UAdvancedFriendsLibrary_SendSessionInviteToFriends() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UAdvancedFriendsLibrary_SendSessionInviteToFriends_Statics::FuncParams); } return ReturnFunction; } UClass* Z_Construct_UClass_UAdvancedFriendsLibrary_NoRegister() { return UAdvancedFriendsLibrary::StaticClass(); } struct Z_Construct_UClass_UAdvancedFriendsLibrary_Statics { static UObject* (*const DependentSingletons[])(); static const FClassFunctionLinkInfo FuncInfo[]; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Class_MetaDataParams[]; #endif static const FCppClassTypeInfoStatic StaticCppClassTypeInfo; static const UE4CodeGen_Private::FClassParams ClassParams; }; UObject* (*const Z_Construct_UClass_UAdvancedFriendsLibrary_Statics::DependentSingletons[])() = { (UObject* (*)())Z_Construct_UClass_UBlueprintFunctionLibrary, (UObject* (*)())Z_Construct_UPackage__Script_AdvancedSessions, }; const FClassFunctionLinkInfo Z_Construct_UClass_UAdvancedFriendsLibrary_Statics::FuncInfo[] = { { &Z_Construct_UFunction_UAdvancedFriendsLibrary_GetFriend, "GetFriend" }, // 2239987131 { &Z_Construct_UFunction_UAdvancedFriendsLibrary_GetStoredFriendsList, "GetStoredFriendsList" }, // 432295403 { &Z_Construct_UFunction_UAdvancedFriendsLibrary_GetStoredRecentPlayersList, "GetStoredRecentPlayersList" }, // 2596305625 { &Z_Construct_UFunction_UAdvancedFriendsLibrary_IsAFriend, "IsAFriend" }, // 1186971954 { &Z_Construct_UFunction_UAdvancedFriendsLibrary_SendSessionInviteToFriend, "SendSessionInviteToFriend" }, // 1971466884 { &Z_Construct_UFunction_UAdvancedFriendsLibrary_SendSessionInviteToFriends, "SendSessionInviteToFriends" }, // 291925237 }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UAdvancedFriendsLibrary_Statics::Class_MetaDataParams[] = { { "IncludePath", "AdvancedFriendsLibrary.h" }, { "ModuleRelativePath", "Classes/AdvancedFriendsLibrary.h" }, }; #endif const FCppClassTypeInfoStatic Z_Construct_UClass_UAdvancedFriendsLibrary_Statics::StaticCppClassTypeInfo = { TCppClassTypeTraits<UAdvancedFriendsLibrary>::IsAbstract, }; const UE4CodeGen_Private::FClassParams Z_Construct_UClass_UAdvancedFriendsLibrary_Statics::ClassParams = { &UAdvancedFriendsLibrary::StaticClass, nullptr, &StaticCppClassTypeInfo, DependentSingletons, FuncInfo, nullptr, nullptr, UE_ARRAY_COUNT(DependentSingletons), UE_ARRAY_COUNT(FuncInfo), 0, 0, 0x000000A0u, METADATA_PARAMS(Z_Construct_UClass_UAdvancedFriendsLibrary_Statics::Class_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UClass_UAdvancedFriendsLibrary_Statics::Class_MetaDataParams)) }; UClass* Z_Construct_UClass_UAdvancedFriendsLibrary() { static UClass* OuterClass = nullptr; if (!OuterClass) { UE4CodeGen_Private::ConstructUClass(OuterClass, Z_Construct_UClass_UAdvancedFriendsLibrary_Statics::ClassParams); } return OuterClass; } IMPLEMENT_CLASS(UAdvancedFriendsLibrary, 2419239469); template<> ADVANCEDSESSIONS_API UClass* StaticClass<UAdvancedFriendsLibrary>() { return UAdvancedFriendsLibrary::StaticClass(); } static FCompiledInDefer Z_CompiledInDefer_UClass_UAdvancedFriendsLibrary(Z_Construct_UClass_UAdvancedFriendsLibrary, &UAdvancedFriendsLibrary::StaticClass, TEXT("/Script/AdvancedSessions"), TEXT("UAdvancedFriendsLibrary"), false, nullptr, nullptr, nullptr); DEFINE_VTABLE_PTR_HELPER_CTOR(UAdvancedFriendsLibrary); PRAGMA_ENABLE_DEPRECATION_WARNINGS #ifdef _MSC_VER #pragma warning (pop) #endif
a941db3eb947262703be6114e729ad2ccc0a9fb0
61c8fc5b49bc9be71bb0da73d4a6c9eeb2c861d2
/BackjoonAlgorithm/17298. 오큰수.cpp
6368ffb73ead3b28c4a6f8bf780037944a8413ef
[ "Unlicense" ]
permissive
Minusie357/Algorithm
188e8555b5edcf425a35e7228b7df4123a1cb7a1
f579f91024a582cdf7e36591308123f8c920e204
refs/heads/master
2022-06-18T06:50:13.904143
2020-05-14T13:42:47
2020-05-14T13:42:47
191,180,848
0
0
null
null
null
null
UTF-8
C++
false
false
1,517
cpp
//#include <iostream> //#include <stack> //#include <vector> //using namespace std; // ////#define DEBUG //#ifdef DEBUG //#include <chrono> //#include "Utility.h" // //chrono::system_clock::time_point Start; //chrono::nanoseconds Time; //#endif // // // //int main() //{ // ios::sync_with_stdio(false); // cin.tie(NULL); // // int N; // cin >> N; // // // int Result[1000000]; // stack<int> Stack; // stack<int> IdxArchieve; // int Index = 0; // // int Input; // for (int i = 0; i < N; ++i) // { //#ifdef DEBUG // Input = GenerateSingleTestData<int>(1, 15); // cout << Input << " "; //#else // cin >> Input; //#endif // DEBUG // // // /* 스택에 쌓인 게 없으면 바로 집어넣습니다. */ // if (Stack.size() == 0) // { // Stack.push(Input); // IdxArchieve.push(Index++); // continue; // } // // // // if (Stack.top() >= Input) // { // Stack.push(Input); // IdxArchieve.push(Index++); // } // else // { // do // { // Result[IdxArchieve.top()] = Input; // Stack.pop(); // IdxArchieve.pop(); // // if (Stack.size() == 0) // break; // } while (Stack.top() < Input); // // Stack.push(Input); // IdxArchieve.push(Index++); // } // } //#ifdef DEBUG // cout << "\n"; //#endif // DEBUG // // // if (Stack.size() > 0) // { // do // { // Result[IdxArchieve.top()] = -1; // Stack.pop(); // IdxArchieve.pop(); // } while (Stack.size() > 0); // } // // for (int i = 0; i < N; ++i) // { // cout << Result[i] << " "; // } // cout << "\n"; // // return 0; //}
492724f9e46cb2ec9b2e4f130403eebec8b588df
6ce706b69c13371b57dd4ab8669fbb9dde7917f7
/Source/AssetsWindow.cpp
8b0ef3697a138c72f7f184e23f6991dfaacecb15
[ "Unlicense", "MIT" ]
permissive
viriato22/The-Creator-3D
86be7d0b33781124f87ad03b4199e30b3c3e6379
943b0d9545b590e67775bc208f54f5132792daa2
refs/heads/master
2021-08-30T12:14:02.363208
2017-12-17T22:21:21
2017-12-17T22:21:21
111,550,666
0
0
null
2017-11-21T13:11:47
2017-11-21T13:11:46
null
UTF-8
C++
false
false
9,368
cpp
#include "AssetsWindow.h" #include "Application.h" #include "ModuleEditor.h" #include "Resource.h" #include "ModuleResources.h" #include "ModuleTextureImporter.h" #include "tinyfiledialogs.h" #include "Texture.h" #include "ModuleFileSystem.h" #include "ModuleScene.h" #include "Data.h" AssetsWindow::AssetsWindow() { active = true; window_name = "Assets"; node = 0; show_new_folder_window = false; file_options_open = true; texture_icon = nullptr; show_delete_window = false; mesh_icon = App->texture_importer->LoadTextureFromLibrary(EDITOR_IMAGES_FOLDER"mesh_icon.png"); font_icon = App->texture_importer->LoadTextureFromLibrary(EDITOR_IMAGES_FOLDER"font_icon.png"); folder_icon = App->texture_importer->LoadTextureFromLibrary(EDITOR_IMAGES_FOLDER"folder_icon.png"); if (!App->file_system->DirectoryExist(ASSETS_FOLDER_PATH)) { if (!App->file_system->Create_Directory(ASSETS_FOLDER_PATH)) { CONSOLE_ERROR("Assets folder is not found and can't create new folder"); return; } } assets_folder_path = App->file_system->StringToPathFormat(ASSETS_FOLDER_PATH); selected_folder = assets_folder_path; } AssetsWindow::~AssetsWindow() { RELEASE(mesh_icon); RELEASE(font_icon); RELEASE(folder_icon) } void AssetsWindow::DrawWindow() { if (ImGui::BeginDock(window_name.c_str(), false, false, App->IsPlaying(), ImGuiWindowFlags_HorizontalScrollbar)) { ImGui::Columns(2); node = 0; ImGui::Spacing(); DrawChilds(assets_folder_path); if (ImGui::IsMouseClicked(1) && ImGui::IsMouseHoveringWindow()) { ImGui::SetNextWindowPos(ImGui::GetMousePos()); ImGui::OpenPopup("Assets Options"); } if (!App->file_system->DirectoryIsEmpty(selected_folder)) { if (ImGui::BeginPopup("Assets Options")) { if (ImGui::MenuItem("Create Folder")) { show_new_folder_window = true; } if (App->file_system->GetDirectoryName(selected_folder) != "Assets") { if (ImGui::MenuItem("Delete")) { show_delete_window = true; delete_path = selected_folder; } } ImGui::Separator(); /*if (ImGui::MenuItem("Import Texture")) { char const * lFilterPatterns[4] = { "*.jpg", "*.png", "*.tga", "*.dds" }; const char* texture_path = tinyfd_openFileDialog("Select Texture...", NULL, 4, lFilterPatterns, NULL, 0); if (texture_path != NULL) { std::string oldPath(texture_path); std::string newPath(selected_folder + "\\" + App->file_system->GetDirectoryName(oldPath)); if (!App->file_system->DirectoryExist(newPath)) { if (oldPath != newPath) { App->file_system->Copy_File(oldPath, newPath); } else { tinyfd_messageBox("Error", "Open file name is NULL", "ok", "error", 1); } } else { tinyfd_messageBox("Error", "A file with this name exist in the current folder", "ok", "error", 1); } } }*/ ImGui::EndPopup(); } } if (show_new_folder_window) { CreateDirectortWindow(); } if (show_delete_window) { DeleteWindow(delete_path); } ImGui::NextColumn(); if (ImGui::BeginChild("Files", ImVec2(0, 0), false, ImGuiWindowFlags_HorizontalScrollbar, App->IsPlaying())) { if (!selected_folder.empty()) { std::vector<std::string> files = App->file_system->GetFilesInDirectory(selected_folder); for (std::vector<std::string>::iterator it = files.begin(); it != files.end(); it++) { bool selected = false; float font_size = ImGui::GetFontSize(); std::string file_extension = App->file_system->GetFileExtension(*it); std::string file_name = App->file_system->GetFileNameWithoutExtension(*it); Resource::ResourceType type = (Resource::ResourceType)App->resources->AssetExtensionToResourceType(file_extension); switch (type) { case Resource::TextureResource: texture_icon = App->resources->GetTexture(file_name); ImGui::Image((ImTextureID)texture_icon->GetID(), { font_size, font_size }, ImVec2(0, 1), ImVec2(1, 0)); ImGui::SameLine(); break; case Resource::MeshResource: ImGui::Image((ImTextureID)mesh_icon->GetID(), { font_size, font_size }, ImVec2(0, 1), ImVec2(1, 0)); ImGui::SameLine(); break; case Resource::FontResource: ImGui::Image((ImTextureID)font_icon->GetID(), { font_size, font_size }, ImVec2(0, 1), ImVec2(1, 0)); ImGui::SameLine(); break; case Resource::Unknown: continue; //if the type is unknown skip and don't draw the file in the panel break; } if (*it == selected_file_path) { if (App->scene->selected_gameobjects.empty()) { selected = true; } else { selected_file_path.clear(); } } ImGui::Selectable((file_name + file_extension).c_str(), &selected); if (ImGui::IsItemHoveredRect()) { if (ImGui::IsItemClicked(0) || ImGui::IsItemClicked(1) && !file_options_open) { selected_file_path = *it; App->scene->selected_gameobjects.clear(); if (ImGui::IsItemClicked(1)) { ImGui::SetNextWindowPos(ImGui::GetMousePos()); ImGui::OpenPopup("File Options"); file_options_open = true; } } } } } if (ImGui::BeginPopup("File Options")) { if (ImGui::MenuItem("Rename")) { file_options_open = false; } if (ImGui::MenuItem("Delete")) { delete_path = selected_file_path; show_delete_window = true; file_options_open = false; } std::string extension = App->file_system->GetFileExtension(selected_file_path); if (extension == ".prefab" || extension == ".fbx" || extension == ".FBX") { if (ImGui::MenuItem("Load to scene")) { std::string file_name = App->file_system->GetFileNameWithoutExtension(selected_file_path); Prefab* prefab = App->resources->GetPrefab(file_name); App->scene->LoadPrefab(prefab); } } ImGui::EndPopup(); } else { file_options_open = false; } } ImGui::EndChild(); } ImGui::EndDock(); } void AssetsWindow::DrawChilds(std::string path) { std::string path_name; path_name = App->file_system->GetDirectoryName(path); sprintf_s(node_name, 150, "%s##node_%i", path_name.c_str(), node++); uint flag = 0; if (!App->file_system->DirectoryHasSubDirectories(path)) { flag |= ImGuiTreeNodeFlags_Leaf; } flag |= ImGuiTreeNodeFlags_OpenOnArrow; if (selected_folder == path && !show_new_folder_window) { flag |= ImGuiTreeNodeFlags_Selected; } if (ImGui::TreeNodeExI(node_name, (ImTextureID)folder_icon->GetID(), flag)) { if (ImGui::IsItemClicked(0) || ImGui::IsItemClicked(1)) { selected_folder = path; } std::vector<std::string> sub_directories = App->file_system->GetSubDirectories(path); for (std::vector<std::string>::iterator it = sub_directories.begin(); it != sub_directories.end(); it++) { DrawChilds(*it); } ImGui::TreePop(); } else { if (ImGui::IsItemClicked(0) || ImGui::IsItemClicked(1)) { selected_folder = path; } } } void AssetsWindow::CreateDirectortWindow() { ImGui::SetNextWindowPos(ImVec2(ImGui::GetWindowSize().x / 2, ImGui::GetWindowSize().y / 2)); ImGui::SetNextWindowPosCenter(); ImGui::Begin("New Folder Name", &active, ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_ShowBorders | ImGuiWindowFlags_NoTitleBar); ImGui::Spacing(); ImGui::Text("New Folder Name"); static char inputText[20]; ImGui::InputText("", inputText, 20); ImGui::Spacing(); if (ImGui::Button("Confirm")) { std::string str(inputText); std::string temp = selected_folder; if (App->file_system->Create_Directory(selected_folder += ("\\" + str))) { show_new_folder_window = false; } else { selected_folder = temp; } strcpy(inputText, ""); } ImGui::SameLine(); if (ImGui::Button("Cancel")) { strcpy(inputText, ""); show_new_folder_window = false; } ImGui::End(); } void AssetsWindow::DeleteWindow(std::string path) { std::string tittle; if (App->file_system->IsDirectory(path)) { tittle = "Delete Diretory"; } else { tittle = "Delete File"; } ImGui::SetNextWindowPos(ImVec2(ImGui::GetWindowSize().x / 2, ImGui::GetWindowSize().y / 2)); ImGui::SetNextWindowPosCenter(); ImGui::Begin(tittle.c_str(), &active, ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_ShowBorders | ImGuiWindowFlags_NoTitleBar); ImGui::Spacing(); if (App->file_system->IsDirectory(path)) { ImGui::Text("Directory %s will be deleted from disk with all the files inside. Continue?", App->file_system->GetDirectoryName(path).c_str()); } else { ImGui::Text("File %s will be deleted from disk. Continue?", App->file_system->GetFileName(path).c_str()); } ImGui::Spacing(); if (ImGui::Button("Confirm")) { if (App->file_system->IsDirectory(path)) { std::vector<std::string> files = App->file_system->GetFilesInDirectory(path); for (int i = 0; i < files.size(); i++) { App->file_system->Delete_File(path); App->resources->DeleteResource(path); } App->file_system->DeleteDirectory(path); } else { App->file_system->Delete_File(path); App->resources->DeleteResource(path); } show_delete_window = false; } ImGui::SameLine(); if (ImGui::Button("Cancel")) { show_delete_window = false; } ImGui::End(); }
108410c7638d389054ca1680cc61072e7ae1f9d8
1997dac27478dee3b55c4d9b3449fab837a95ca9
/MinCut.cpp
c3475912e11554839d883dcd05d9e8839f514771
[]
no_license
ming5656/581-competive
4dffedd4438bdaab6d9cd97f558ecde022b0d3f0
fe4dc43d9a44e9ef2e545ed185209d58a5cacaa7
refs/heads/master
2021-09-03T18:35:22.602147
2018-01-11T04:19:23
2018-01-11T04:19:23
111,436,633
0
0
null
null
null
null
UTF-8
C++
false
false
1,539
cpp
#include <bits/stdc++.h> #define oo 0x3f3f3f3f #define ll long long using namespace std; ll mp[10002][10002]; int n,m; bool combine[10002]; ll minC=oo; void ss(int &s,int &t){ bool vis[n]; int w[n]; memset(vis,0,sizeof(vis)); memset(w,0,sizeof(w)); int tmpj=9999; for(int i=0;i<n;i++) { int maxv=-oo; for(int j=0;j<n;j++) { if(!vis[j]&& !combine[j] && maxv<w[j] ) { maxv=w[j]; tmpj=j; } } if(t==tmpj) { minC=w[t]; return; } vis[tmpj]=true ; s=t; t=tmpj; for(int j=0;j<n;j++) { if(!vis[j]&&!combine[j]) w[j]+=mp[t][j]; } } minC=w[t]; } ll mincut(){ ll ans =oo; int s,t; memset(combine,0,sizeof(combine)); for(int i=0;i<n-1;i++){ s=t=-1; ss(s,t); combine[t]=true; ans=min(minC,ans); for(int j=0;j<n;j++){ mp[s][j]+=mp[t][j]; mp[j][s]+=mp[j][t]; } } return ans; } int main(){ int t; scanf("%d",&t); while(t--){ scanf("%d%d",&n,&m); memset(mp,0,sizeof(mp)); int u,v; ll w; for(int i=0;i<m;i++) { scanf("%d%d%lld",&u,&v,&w); mp[u][v]+=w; mp[v][u]+=w; } cout<<mincut()<<endl; } return 0; }
1c304e56f751a460fbc7fca06b6ca555a7dcd363
7b5ad3d593376094cd505bc1b22f82743f9d2c93
/src/shared/headers/renderer.h
ef92cadf05f0928b74f7dbe08c55d8814e49db04
[]
no_license
RyanLadley/ArcadeGL
5620203eee78829694d7246708d4205598051bc2
6a3ca1440f04c09a667f08573b6753f310c36f4a
refs/heads/master
2016-09-13T17:10:11.337605
2016-05-28T04:02:44
2016-05-28T04:02:44
59,177,959
0
0
null
null
null
null
UTF-8
C++
false
false
578
h
#ifndef RENDERER_H #define RENDERER_H #define GLEW_STATIC #define GLM_FORCE_RADIANS #include <GL/glew.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include <glm/ext.hpp> #include "shader.h" #include "texture.h" class Renderer{ private: Shader shader; const int SCREEN_WIDTH, SCREEN_HEIGHT; public: Renderer(Shader new_shader, int screen_width, int screen_height); void draw(Texture texture, glm::vec2 position, glm::vec2 dimensions, GLfloat rotate, glm::vec3 color); void init_renderer(); }; #endif
f3c388a69cb0b1af055e1906faca047e981f45ee
2e60e0c889854cfb15ba31d9b95be05002b1002e
/10807.cpp
d1e944966905790e98bab054b54fc79be378fd80
[]
no_license
tlstk1101/Baekjoon
03315f15df0421993c947a631c94c29d8824914f
d668be8f24a7c62772bbeea9f1b731e14ff7aa9a
refs/heads/master
2020-04-21T11:51:05.166301
2020-03-26T06:18:52
2020-03-26T06:18:52
169,539,525
0
0
null
null
null
null
UTF-8
C++
false
false
279
cpp
#include <iostream> using namespace std; int main() { int N, v, count = 0; cin >> N; int *Arr = new int[N]; for (int i = 0; i < N; i++) { cin >> Arr[i]; } cin >> v; for (int i = 0; i < N; i++) { if (Arr[i] == v) count++; } cout << count << endl; return 0; }
089acab2964eb85e83d17b1a0e60f15a971e402b
f3f7cf4a65cc3c9354ad04d86b14e853d34f7c08
/Module_03/ex01/ScavTrap.hpp
8b74b74a00d3fad9abde85d78742369682387f9f
[]
no_license
hamanmax/Piscine_CPP
4aadce72e3feee00e4ca274dd68a876da785f36d
18d62d0f2a4ec4023b2f167d4e63504b90253259
refs/heads/master
2023-04-07T02:17:12.599736
2021-04-19T09:18:36
2021-04-19T09:18:36
348,053,922
0
0
null
null
null
null
UTF-8
C++
false
false
1,557
hpp
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ScavTrap.hpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mhaman <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/03/19 13:52:10 by mhaman #+# #+# */ /* Updated: 2021/03/20 12:39:48 by mhaman ### ########lyon.fr */ /* */ /* ************************************************************************** */ #ifndef SCAVTRAP_HPP #define SCAVTRAP_HPP #include <iostream> class ScavTrap { private: int _hit_point; unsigned int _max_hit_point; int _energy_point; unsigned int _max_energy_point; int _level; std::string _name; int _melee_damage; int _ranged_damage; int _armor_damage_reduction; public: ScavTrap(); ScavTrap(const ScavTrap & cp); ScavTrap & operator=(const ScavTrap & op); ~ScavTrap(); ScavTrap(std::string name); void rangedAttack(std::string const & target); void meleeAttack(std::string const & target); void takeDamage(unsigned int amount); void beRepaired(unsigned int amount); void challengeNewcomer(); }; #endif
19be1e7a9e43270ba46ac727c05b64054de56be1
0224a30ff811a65e452a32143ed1d7a73aebc3be
/src/ui_interface.h
96695c106b6377b601259d05911818ddd6f0731c
[ "MIT" ]
permissive
xiaolin1579/TDC
893667bfd0bc83e43cb11b0e7a03eb41572837c2
c5aadc1676cc9bdb7e558500c55944d3a78fb8be
refs/heads/TDC
2022-10-06T09:07:45.172219
2020-05-30T04:58:52
2020-05-30T04:58:52
267,499,071
0
0
MIT
2020-05-28T10:51:14
2020-05-28T05:12:24
null
UTF-8
C++
false
false
6,651
h
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_UI_INTERFACE_H #define BITCOIN_UI_INTERFACE_H #include <string> #include "util.h" // for int64 #include <boost/signals2/signal.hpp> #include <boost/signals2/last_value.hpp> class CBasicKeyStore; class CWallet; class uint256; /** General change type (added, updated, removed). Общие типы изменения (добавление, обновление, удаление) */ enum ChangeType { CT_NEW, CT_UPDATED, CT_DELETED }; /** Signals for UI communication. сигналы для UI коммуникации */ class CClientUIInterface { public: /** Flags for CClientUIInterface::ThreadSafeMessageBox флаги */ enum MessageBoxFlags { ICON_INFORMATION = 0, ICON_WARNING = (1U << 0), ICON_ERROR = (1U << 1), /** * Mask of all available icons in CClientUIInterface::MessageBoxFlags Маска всех доступных иконок в CClientUIInterface::MessageBoxFlags * This needs to be updated, when icons are changed there! Это нуждается в обновлении, когда иконки меняются там! */ ICON_MASK = (ICON_INFORMATION | ICON_WARNING | ICON_ERROR), /** These values are taken(взяты) from qmessagebox.h "enum StandardButton" to be directly usable(чтобы быть напрямую пользоваными) */ BTN_OK = 0x00000400U, // QMessageBox::Ok BTN_YES = 0x00004000U, // QMessageBox::Yes BTN_NO = 0x00010000U, // QMessageBox::No BTN_ABORT = 0x00040000U, // QMessageBox::Abort BTN_RETRY = 0x00080000U, // QMessageBox::Retry BTN_IGNORE = 0x00100000U, // QMessageBox::Ignore BTN_CLOSE = 0x00200000U, // QMessageBox::Close BTN_CANCEL = 0x00400000U, // QMessageBox::Cancel BTN_DISCARD = 0x00800000U, // QMessageBox::Discard BTN_HELP = 0x01000000U, // QMessageBox::Help BTN_APPLY = 0x02000000U, // QMessageBox::Apply BTN_RESET = 0x04000000U, // QMessageBox::Reset /** * Mask of all available buttons in CClientUIInterface::MessageBoxFlags Маска всех доступных кнопок в CClientUIInterface::MessageBoxFlags * This needs to be updated, when buttons are changed there! Это нуждается в обновлении, когда кнопки меняются там! */ BTN_MASK = (BTN_OK | BTN_YES | BTN_NO | BTN_ABORT | BTN_RETRY | BTN_IGNORE | BTN_CLOSE | BTN_CANCEL | BTN_DISCARD | BTN_HELP | BTN_APPLY | BTN_RESET), /** Force blocking, modal message box dialog (not just OS notification) Силовое блокирование, модальный диалог окна сообщения (не только ОС уведомления)*/ MODAL = 0x10000000U, /** Predefined combinations for certain default usage cases Предопределенные комбинации для определенных случаев использования по умолчанию */ MSG_INFORMATION = ICON_INFORMATION, MSG_WARNING = (ICON_WARNING | BTN_OK | MODAL), MSG_ERROR = (ICON_ERROR | BTN_OK | MODAL) }; /** Show message box. Показать окно сообщений */ boost::signals2::signal<bool (const std::string& message, const std::string& caption, unsigned int style), boost::signals2::last_value<bool> > ThreadSafeMessageBox; /** Ask the user whether they want to pay a fee or not. Спросите пользователя, хочет ли он заплатить коммиссию или нет */ boost::signals2::signal<bool (int64 nFeeRequired), boost::signals2::last_value<bool> > ThreadSafeAskFee; /** Handle a URL passed at the command line. Обрабатывать URL-адрес, переданный в командной строке */ boost::signals2::signal<void (const std::string& strURI)> ThreadSafeHandleURI; /** Progress message during initialization. Сообщение о ходе выполнения во время инициализации. */ boost::signals2::signal<void (const std::string &message)> InitMessage; /** Translate a message to the native language of the user. Перевод сообщения на роднй язык пользователя. */ boost::signals2::signal<std::string (const char* psz)> Translate; /** Block chain changed. Цепь блоков изменилась */ boost::signals2::signal<void ()> NotifyBlocksChanged; /** Number of network connections changed. Изменение количества сетевых подключений */ boost::signals2::signal<void (int newNumConnections)> NotifyNumConnectionsChanged; /** * New, updated or cancelled alert. Новоее, обновленное или предупреждение отмены * @note called with lock cs_mapAlerts held. @note вызывается с закрытым cs_mapAlerts проведением */ boost::signals2::signal<void (const uint256 &hash, ChangeType status)> NotifyAlertChanged; }; extern CClientUIInterface uiInterface; /** * Translation function: Call Translate signal on UI interface, which returns a boost::optional result. * If no translation slot is registered, nothing is returned, and simply return the input. * Функция перевода: Вызывает сигнал перевода в UI интерфейсе, который возвращает boost::optional результаты. * Если нет переводимого слота, ничего не возвращается, а просто возвращается ввод */ inline std::string _(const char* psz) { boost::optional<std::string> rv = uiInterface.Translate(psz); return rv ? (*rv) : psz; } #endif
c79ab02de0b4faa7991bbff070a575ed5a24d310
33d3a88e0f52dd89a4fb358617d464c8626e364c
/tests/set_tests.cpp
848f8ee8fb9aa5189d3d3a84f047657cd0a30d93
[]
no_license
tuan9999/Containers
d5f89e807ce8e1efbfdcacb7661fb5e862b18ac9
63ee02c0c6f704cd9b6ebe2fc1a51122ccb9d941
refs/heads/main
2023-04-07T20:03:56.757151
2021-04-12T14:36:12
2021-04-12T14:36:12
325,959,087
0
0
null
null
null
null
UTF-8
C++
false
false
4,163
cpp
// // Created by Tuan Perera on 27.02.21. // #include <set> #include "gtest/gtest.h" #include "../library.h" TEST(SetTest, ContructorTests) { ft::set<int> fs1; std::set<int> ss1; fs1.insert(230); fs1.insert(20); ss1.insert(230); ss1.insert(20); ft::set<int> fs2(fs1.begin(), fs1.end()); std::set<int> ss2(ss1.begin(), ss1.end()); ft::set<int>::iterator fit = fs2.begin(); std::set<int>::iterator sit = ss2.begin(); while (fit != fs2.end()) { ASSERT_TRUE(*fit == *sit) << "Iterator constructor: ft: " << *fit << " std: " << *sit << "\n"; fit++; sit++; } } TEST(SetTest, IteratorTests) { ft::set<int> fs1; std::set<int> ss1; fs1.insert(230); fs1.insert(20); ss1.insert(230); ss1.insert(20); ft::set<int>::iterator fit = fs1.begin(); std::set<int>::iterator sit = ss1.begin(); while (fit != fs1.end()) { ASSERT_TRUE(*fit == *sit) << "Iterator: ft: " << *fit << " std: " << *sit << "\n"; fit++; sit++; } ft::set<int>::reverse_iterator rfit = fs1.rbegin(); std::set<int>::reverse_iterator rsit = ss1.rbegin(); while (rfit != fs1.rend()) { ASSERT_TRUE(*rfit == *rsit) << "Reverse iterator: ft: " << *fit << " std: " << *sit << "\n"; rfit++; rsit++; } } TEST(SetTest, CapacityTests) { ft::set<int> fs1; std::set<int> ss1; fs1.insert(230); fs1.insert(20); ss1.insert(230); ss1.insert(20); ASSERT_TRUE(fs1.empty() == ss1.empty()) << "Size: ft: " << fs1.empty() << " std: " << ss1.empty() << "\n"; ASSERT_TRUE(fs1.size() == ss1.size()) << "Size: ft: " << fs1.size() << " std: " << ss1.size() << "\n"; } TEST(SetTest, InsertTests) { ft::set<int> fs1; std::set<int> ss1; fs1.insert(230); fs1.insert(20); ss1.insert(230); ss1.insert(20); ft::set<int> fs2; std::set<int> ss2; fs2.insert(fs1.begin(), fs1.end()); ss2.insert(ss1.begin(), ss1.end()); ft::set<int>::iterator fit = fs2.begin(); std::set<int>::iterator sit = ss2.begin(); while (fit != fs2.end()) { ASSERT_TRUE(*fit == *sit) << "Insert iterators: Failed with ft: " << *fit << " std: " << *sit << "\n"; fit++; sit++; } } TEST(SetTest, EraseTests) { ft::set<int> fs1; std::set<int> ss1; fs1.insert(230); fs1.insert(20); ss1.insert(230); ss1.insert(20); fs1.erase(fs1.begin()); ss1.erase(ss1.begin()); ft::set<int>::iterator fit = fs1.begin(); std::set<int>::iterator sit = ss1.begin(); while (fit != fs1.end()) { ASSERT_TRUE(*fit == *sit) << "Erase pos: Failed with ft: " << *fit << " std: " << *sit << "\n"; fit++; sit++; } } TEST(SetTest, SwapTests) { ft::set<int> fs1; std::set<int> ss1; ft::set<int> fs2; std::set<int> ss2; fs1.insert(230); fs1.insert(20); ss1.insert(230); ss1.insert(20); fs2.insert(11); fs2.insert(14); ss2.insert(11); ss2.insert(14); fs1.swap(fs2); ss1.swap(ss2); ft::set<int>::iterator fit = fs1.begin(); std::set<int>::iterator sit = ss1.begin(); while (fit != fs1.end()) { ASSERT_TRUE(*fit == *sit) << "Swap: Failed with ft: " << *fit << " std: " << *sit << "\n"; fit++; sit++; } } TEST(SetTest, ClearTests) { ft::set<int> fs1; std::set<int> ss1; fs1.insert(230); fs1.insert(20); ss1.insert(230); ss1.insert(20); fs1.clear(); ss1.clear(); ASSERT_TRUE(fs1.size() == ss1.size()) << "Clear: Failed with ft: " << fs1.size() << " std: " << ss1.size() << "\n"; } TEST(SetTest, FindTests) { ft::set<int> fs1; std::set<int> ss1; fs1.insert(230); fs1.insert(20); ss1.insert(230); ss1.insert(20); ASSERT_TRUE(*(fs1.find(20)) == *(ss1.find(20))) << "Find: Failed with ft: " << *(fs1.find(20)) << " std: " << *(ss1.find(20)) << "\n"; } TEST(SetTest, CountTests) { ft::set<int> fs1; std::set<int> ss1; fs1.insert(230); fs1.insert(20); ss1.insert(230); ss1.insert(20); ASSERT_TRUE((fs1.count(20)) == (ss1.count(20))) << "Count: Failed with ft: " << (fs1.count(20)) << " std: " << (ss1.count(20)) << "\n"; } TEST(SetTest, BoundTests) { ft::set<int> fs1; std::set<int> ss1; fs1.insert(230); fs1.insert(20); ss1.insert(230); ss1.insert(20); ASSERT_TRUE(*(fs1.lower_bound(20)) == *(ss1.lower_bound(20))) << "Lower bound: Failed with ft: " << *(fs1.lower_bound(20)) << " std: " << *(ss1.lower_bound(20)) << "\n"; }
636bf6385d5fa90f2e225caffdc7933e4597a3db
8442f074cfeecb4ca552ff0d6e752f939d6326f0
/996A Hit the Lottery.cpp
a16d5d1df232aa18f1aed28522114a6226c231e4
[]
no_license
abufarhad/Codeforces-Problems-Solution
197d3f351fc01231bfefd1c4057be80643472502
b980371e887f62040bee340a8cf4af61a29eac26
refs/heads/master
2021-06-15T16:35:07.327687
2021-03-23T17:29:49
2021-03-23T17:29:49
170,741,904
43
32
null
null
null
null
UTF-8
C++
false
false
287
cpp
#include<bits/stdc++.h> #include<stdio.h> using namespace std; #define ll long long int main() { ll m,n,t,a,b,c,d,i,j,k,x,y,z,ans; cin>>n; a=n/100;b=n%100; c=b/20; d=b%20; x=d/10; y=d%10; i=y/5; j=y%5; ll p=a+c+x+i+j; cout<<p<<endl; return 0; }
0232178d63c94de08f67f6212dae60fae0758931
301ed54244fd41502fd6f23a2e016c6e0cfba2dd
/07 CSES/04 Graph Algorithms/17.cpp
419414594358506b522f8649885a7053ae665bff
[]
no_license
iCodeIN/Competitive-Programming-4
660607a74c4a846340b6fb08316668057f75a7ba
05b55d2736f6b22758cd57f3ed5093cf8a2f4e2f
refs/heads/master
2023-02-22T12:53:39.878593
2021-01-28T10:57:50
2021-01-28T10:57:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,027
cpp
// Game Routes #include <bits/stdc++.h> using namespace std; #define en "\n" #define INF (int) 9e18 #define HELL (int) (1e9 + 7) #define int long long #define double long double #define uint unsigned long long #define pii pair<int, int> #define pb push_back #define fs first #define sc second #define size(a) (int) a.size() #define deb(x) cerr << #x << " => " << x << en #define debp(a) cerr << #a << " => " <<"("<<a.fs<<", "<<a.sc<<") " << en; #define deba(x) cerr << #x << en; for (auto a : x) cerr << a << " "; cerr << en; #define debpa(x) cerr << #x << en; for (auto a : x)cerr<<"("<<a.fs<<", "<<a.sc<<") "; cerr << en; #define debm(x) cerr << #x << en; for (auto a : x){for(auto b : a) cerr << b << " "; cerr << en;} #define getMat(x, n, m, val) vector<vector<int>> x(n, vector<int> (m, val)) #define fastio ios_base :: sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); #define pout cout << fixed << setprecision(10) int fastpow(int a, int b, int m = HELL) { int res = 1; a %= m; while (b > 0) { if (b & 1) res = (res * a) % m; a = (a * a) % m; b >>= 1; } return res;} #define inv(a) fastpow(a, HELL - 2) #define mul(a, b) ((a % HELL) * (b % HELL)) % HELL int n, m; const int maxN = 1e5 + 5; vector<int> adj[maxN]; void topoDFS(int v, vector<bool> &visited, vector<int> &res) { visited[v] = true; for (auto a : adj[v]) { if (!visited[a]) { topoDFS(a, visited, res); } } res.pb(v); } vector<int> topoSort() { vector<int> res; vector<bool> visited(n + 5); for (int i = 1; i <= n; i++) { if (!visited[i]) { topoDFS(i, visited, res); } } reverse(res.begin(), res.end()); return res; } int32_t main() { fastio; cin >> n >> m; int a, b; for (int i = 0; i < m; i++) { cin >> a >> b; adj[a].pb(b); } auto ts = topoSort(); vector<int> final(n + 1, 0); final[1] = 1; for (auto t : ts) { for (auto x : adj[t]) { final[x] = (final[x] + final[t]) % HELL; } } cout << final[n] << endl; return 0; }
c3cd55bd8cf0df35c44d5bf5cebcc4942847e288
f2c2d1266bf0ecb15d2606b41dea0333cdcb287e
/src/etat/etat26.h
2ffef377f3fb0860e1ffd710c969b1d9f659994b
[]
no_license
HexaRAM/GL
509df1b67e2ae00056620678bc277eb4ec104189
5fd815494eadd7d07dbdf58d97bb72dc951a3df4
refs/heads/master
2021-01-22T06:54:46.726257
2015-04-02T22:34:20
2015-04-02T22:34:20
31,501,898
0
1
null
2015-03-24T16:27:08
2015-03-01T16:13:19
C++
UTF-8
C++
false
false
389
h
#if !defined ( Etat26_H ) #define Etat26_H #include <string> #include "../automate/automate.h" #include "../symbole/symbole.h" #include "etat.h" using namespace std; class Etat26 : public Etat { public: Etat26(string name); Etat26(); virtual ~Etat26(); void print() const; bool transition(Automate & automate, Symbole * s ); protected: string name; }; #endif
[ "root@debian" ]
root@debian
d2314a373d443013167b2145efb0a85d931e06ca
c0f901fe1531ad06bdb1f4914f5ffb432ff3f97c
/include/base/ext/img_codecs/decoder/png.h
852c825e0555043e8f430b324ee298ec84b9ca51
[]
no_license
LitingLin/base-libs
c4a43d03cc258bf0a4dc5b9ec856151457261e0d
a8ad78eb27dc39ed240ce684ff9967745e4f0af3
refs/heads/master
2021-06-18T20:02:48.425819
2021-02-18T14:00:00
2021-02-18T14:00:00
177,100,956
0
0
null
null
null
null
UTF-8
C++
false
false
765
h
#pragma once #ifdef HAVE_LIB_PNG #include <base/ext/img_codecs/common.h> #include <png.h> #include <vector> #include <cstdint> namespace Base { class IMAGE_CODECS_INTERFACE PNGDecoder { public: PNGDecoder(); PNGDecoder(const PNGDecoder&) = delete; PNGDecoder(PNGDecoder&& object) noexcept; ~PNGDecoder(); void load(const void* image, uint64_t size); [[nodiscard]] unsigned getWidth() const; [[nodiscard]] unsigned getHeight() const; [[nodiscard]] uint64_t getDecompressedSize() const; void decode(void* buffer); private: unsigned char* _sourceImage; unsigned char* _currentImagePosition; png_structp _png_ptr; png_infop _info_ptr; unsigned long _image_width, _image_height; ::std::vector<png_bytep> _row_pointers; }; } #endif
853a0d626039f5a1aebf69f4cc1baa9615cc49ec
af0518e315d51aa55992dcaeb2211145a8379b6b
/Arduino/Arduino/setupUploadViaBluetooth/setupUploadViaBluetooth.ino
105c68a5195adb4062f0a09a59a79cc0b9a6526b
[]
no_license
kram1138/Capstone-G17
6ec9c61b6159badc4233d90c6e47dec88a65c92e
51666b237a1c3ec711e924501d57fc51cbd8d2b9
refs/heads/master
2021-09-10T06:39:46.223630
2018-03-21T17:37:29
2018-03-21T17:37:29
105,687,027
0
0
null
null
null
null
UTF-8
C++
false
false
316
ino
#include <SoftwareSerial.h> SoftwareSerial BTSerial(8, 9); // RX, TX void setup() { Serial.begin(9600); Serial.println("Enter AT commands:"); BTSerial.begin(38400); } void loop() { if (BTSerial.available()) Serial.write(BTSerial.read()); if (Serial.available()) BTSerial.write(Serial.read()); }
04a882e0c0237b5e8c86811b6c1c6969121487bb
58cfaabdf22bd7b378c38ca7080d1129dd7cd451
/astl/iterator/iterator.hpp
7e07f1cd7d7b60ce4e689004bf92f172b69f497a
[]
no_license
PeihongKe/aSTL
522625aa22ba52590a59eb06b9fb668d2b42606f
55c16908f78e0f529082a18006361d853a53712f
refs/heads/master
2021-01-19T07:30:30.484935
2017-07-10T22:12:36
2017-07-10T22:12:36
73,131,560
0
0
null
null
null
null
UTF-8
C++
false
false
1,992
hpp
#ifndef _ANOTHERSTL_ITERATOR_ #define _ANOTHERSTL_ITERATOR_ #include "iterator_traits.hpp" namespace anotherSTL { template<typename Category, typename T, typename Distance = ptrdiff_t, typename Pointer = T*, typename Reference = T&> struct iterator { typedef T value_type; typedef Pointer pointer; typedef Reference reference; typedef Distance difference_type; typedef Category iterator_category; }; template<typename InputIterator, typename Distance > inline void __advance(InputIterator& it, Distance n, input_interator_tag) { while (n-- > 0) { ++it; } } template<typename BiDirectionaryIterator, typename Distance> inline void __advance(BiDirectionaryIterator& first, Distance n, bidirectional_iterator_tag) { if (n > 0) { while (n-- > 0){++it;} } else { while (n++ < 0){--it;} } } template<typename InputIterator, typename Distance > inline void __advance(InputIterator& it, Distance n, random_access_iterator_tag) { it += n; } template<typename InputIterator, class Distance> inline void advance(InputIterator& it, Distance n) { __advance(it, n, category(it)); } // TOCHECK: how about output iterator; not defined for output iterator template<typename InputIterator> inline typename iterator_traits<InputIterator>::difference_type __distance(InputIterator first, InputIterator last, input_interator_tag) { iterator_traits<InputIterator>::difference_type n = 0; while (first != last) { ++first; ++n; } return n; } template<typename RandomAccessIteraotr> inline typename iterator_traits<RandomAccessIteraotr>::difference_type __distance(RandomAccessIteraotr first, RandomAccessIteraotr last, random_access_iterator_tag) { return last - first; } template<typename InputIterator> inline typename iterator_traits<InputIterator>::difference_type distance(InputIterator first, InputIterator second) { return __distance(first, second, category(first)); } } #endif //
10d8d8ab9c0915444494438d06055b6302bb8540
7062078795d41f7f0c053b2f8837205022d0377f
/Laboratoire9/EmployeGUI/employegui.h
2bb7b98375eea17d937e63fb90603c401cba342b
[]
no_license
PMarcL/LaboratoireGIF1003
551f80bae25d4bb80ebbbe0ba8231b5b47e34f85
e21c90044fcdae335b5a1e19ed618973a1b0165f
refs/heads/master
2021-01-19T12:35:12.317014
2017-04-07T18:48:20
2017-04-07T18:48:20
82,325,693
1
1
null
null
null
null
UTF-8
C++
false
false
398
h
#ifndef EMPLOYEGUI_H #define EMPLOYEGUI_H #include <QtGui/QMainWindow> #include "ui_employegui.h" #include "Entreprise.h" class EmployeGUI: public QMainWindow { Q_OBJECT public: EmployeGUI(QWidget *parent = 0); ~EmployeGUI(); private slots: void dialogCommis(); void dialogSupprimerEmploye(); private: labo10::Entreprise m_entreprise; Ui::EmployeGUIClass ui; }; #endif // EMPLOYEGUI_H
b785ff3a4ac45e737bd45b4f7e7d69cc897c24ca
51f6ba1832964ed9c5992bcdef1bef9b86b8b727
/src/interpreter/bytecode-array-builder.h
04c08f46c4abac0d17168af4427f5dc6020d1425
[ "SunPro", "BSD-3-Clause", "bzip2-1.0.6" ]
permissive
jonasmattisson/v8
b5f5d9a08ae325563ecaaa892e6e3bfe8c2e99e8
0a7e08ef26fb6afe473f7a51809207894c588f84
refs/heads/master
2020-04-05T07:14:12.471288
2018-11-08T06:51:53
2018-11-08T07:29:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
29,130
h
// Copyright 2015 the V8 project 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 V8_INTERPRETER_BYTECODE_ARRAY_BUILDER_H_ #define V8_INTERPRETER_BYTECODE_ARRAY_BUILDER_H_ #include "src/ast/ast.h" #include "src/base/compiler-specific.h" #include "src/globals.h" #include "src/interpreter/bytecode-array-writer.h" #include "src/interpreter/bytecode-flags.h" #include "src/interpreter/bytecode-register-allocator.h" #include "src/interpreter/bytecode-register.h" #include "src/interpreter/bytecode-source-info.h" #include "src/interpreter/bytecodes.h" #include "src/interpreter/constant-array-builder.h" #include "src/interpreter/handler-table-builder.h" #include "src/zone/zone-containers.h" namespace v8 { namespace internal { class FeedbackVectorSpec; class Isolate; namespace interpreter { class BytecodeLabel; class BytecodeNode; class BytecodeRegisterOptimizer; class BytecodeJumpTable; class Register; class V8_EXPORT_PRIVATE BytecodeArrayBuilder final { public: BytecodeArrayBuilder( Zone* zone, int parameter_count, int locals_count, FeedbackVectorSpec* feedback_vector_spec = nullptr, SourcePositionTableBuilder::RecordingMode source_position_mode = SourcePositionTableBuilder::RECORD_SOURCE_POSITIONS); Handle<BytecodeArray> ToBytecodeArray(Isolate* isolate); // Get the number of parameters expected by function. int parameter_count() const { DCHECK_GE(parameter_count_, 0); return parameter_count_; } // Get the number of locals required for bytecode array. int locals_count() const { DCHECK_GE(local_register_count_, 0); return local_register_count_; } // Returns the number of fixed (non-temporary) registers. int fixed_register_count() const { return locals_count(); } // Returns the number of fixed and temporary registers. int total_register_count() const { DCHECK_LE(fixed_register_count(), register_allocator()->maximum_register_count()); return register_allocator()->maximum_register_count(); } Register Local(int index) const; Register Parameter(int parameter_index) const; Register Receiver() const; // Constant loads to accumulator. BytecodeArrayBuilder& LoadConstantPoolEntry(size_t entry); BytecodeArrayBuilder& LoadLiteral(Smi value); BytecodeArrayBuilder& LoadLiteral(double value); BytecodeArrayBuilder& LoadLiteral(const AstRawString* raw_string); BytecodeArrayBuilder& LoadLiteral(const Scope* scope); BytecodeArrayBuilder& LoadLiteral(AstBigInt bigint); BytecodeArrayBuilder& LoadLiteral(AstSymbol symbol); BytecodeArrayBuilder& LoadUndefined(); BytecodeArrayBuilder& LoadNull(); BytecodeArrayBuilder& LoadTheHole(); BytecodeArrayBuilder& LoadTrue(); BytecodeArrayBuilder& LoadFalse(); BytecodeArrayBuilder& LoadBoolean(bool value); // Global loads to the accumulator and stores from the accumulator. BytecodeArrayBuilder& LoadGlobal(const AstRawString* name, int feedback_slot, TypeofMode typeof_mode); BytecodeArrayBuilder& StoreGlobal(const AstRawString* name, int feedback_slot); // Load the object at |slot_index| at |depth| in the context chain starting // with |context| into the accumulator. enum ContextSlotMutability { kImmutableSlot, kMutableSlot }; BytecodeArrayBuilder& LoadContextSlot(Register context, int slot_index, int depth, ContextSlotMutability immutable); // Stores the object in the accumulator into |slot_index| at |depth| in the // context chain starting with |context|. BytecodeArrayBuilder& StoreContextSlot(Register context, int slot_index, int depth); // Load from a module variable into the accumulator. |depth| is the depth of // the current context relative to the module context. BytecodeArrayBuilder& LoadModuleVariable(int cell_index, int depth); // Store from the accumulator into a module variable. |depth| is the depth of // the current context relative to the module context. BytecodeArrayBuilder& StoreModuleVariable(int cell_index, int depth); // Register-accumulator transfers. BytecodeArrayBuilder& LoadAccumulatorWithRegister(Register reg); BytecodeArrayBuilder& StoreAccumulatorInRegister(Register reg); // Register-register transfer. BytecodeArrayBuilder& MoveRegister(Register from, Register to); // Named load property. BytecodeArrayBuilder& LoadNamedProperty(Register object, const AstRawString* name, int feedback_slot); // Named load property without feedback BytecodeArrayBuilder& LoadNamedPropertyNoFeedback(Register object, const AstRawString* name); // Keyed load property. The key should be in the accumulator. BytecodeArrayBuilder& LoadKeyedProperty(Register object, int feedback_slot); // Named load property of the @@iterator symbol. BytecodeArrayBuilder& LoadIteratorProperty(Register object, int feedback_slot); // Named load property of the @@asyncIterator symbol. BytecodeArrayBuilder& LoadAsyncIteratorProperty(Register object, int feedback_slot); // Store properties. Flag for NeedsSetFunctionName() should // be in the accumulator. BytecodeArrayBuilder& StoreDataPropertyInLiteral( Register object, Register name, DataPropertyInLiteralFlags flags, int feedback_slot); // Collect type information for developer tools. The value for which we // record the type is stored in the accumulator. BytecodeArrayBuilder& CollectTypeProfile(int position); // Store a property named by a property name. The value to be stored should be // in the accumulator. BytecodeArrayBuilder& StoreNamedProperty(Register object, const AstRawString* name, int feedback_slot, LanguageMode language_mode); // Store a property named by a property name without feedback slot. The value // to be stored should be in the accumulator. BytecodeArrayBuilder& StoreNamedPropertyNoFeedback( Register object, const AstRawString* name, LanguageMode language_mode); // Store a property named by a constant from the constant pool. The value to // be stored should be in the accumulator. BytecodeArrayBuilder& StoreNamedProperty(Register object, size_t constant_pool_entry, int feedback_slot, LanguageMode language_mode); // Store an own property named by a constant from the constant pool. The // value to be stored should be in the accumulator. BytecodeArrayBuilder& StoreNamedOwnProperty(Register object, const AstRawString* name, int feedback_slot); // Store a property keyed by a value in a register. The value to be stored // should be in the accumulator. BytecodeArrayBuilder& StoreKeyedProperty(Register object, Register key, int feedback_slot, LanguageMode language_mode); // Store an own element in an array literal. The value to be stored should be // in the accumulator. BytecodeArrayBuilder& StoreInArrayLiteral(Register array, Register index, int feedback_slot); // Store the home object property. The value to be stored should be in the // accumulator. BytecodeArrayBuilder& StoreHomeObjectProperty(Register object, int feedback_slot, LanguageMode language_mode); // Store the class fields property. The initializer to be stored should // be in the accumulator. BytecodeArrayBuilder& StoreClassFieldsInitializer(Register constructor, int feedback_slot); // Load class fields property. BytecodeArrayBuilder& LoadClassFieldsInitializer(Register constructor, int feedback_slot); // Lookup the variable with |name|. BytecodeArrayBuilder& LoadLookupSlot(const AstRawString* name, TypeofMode typeof_mode); // Lookup the variable with |name|, which is known to be at |slot_index| at // |depth| in the context chain if not shadowed by a context extension // somewhere in that context chain. BytecodeArrayBuilder& LoadLookupContextSlot(const AstRawString* name, TypeofMode typeof_mode, int slot_index, int depth); // Lookup the variable with |name|, which has its feedback in |feedback_slot| // and is known to be global if not shadowed by a context extension somewhere // up to |depth| in that context chain. BytecodeArrayBuilder& LoadLookupGlobalSlot(const AstRawString* name, TypeofMode typeof_mode, int feedback_slot, int depth); // Store value in the accumulator into the variable with |name|. BytecodeArrayBuilder& StoreLookupSlot( const AstRawString* name, LanguageMode language_mode, LookupHoistingMode lookup_hoisting_mode); // Create a new closure for a SharedFunctionInfo which will be inserted at // constant pool index |shared_function_info_entry|. BytecodeArrayBuilder& CreateClosure(size_t shared_function_info_entry, int slot, int flags); // Create a new local context for a |scope|. BytecodeArrayBuilder& CreateBlockContext(const Scope* scope); // Create a new context for a catch block with |exception| and |scope|. BytecodeArrayBuilder& CreateCatchContext(Register exception, const Scope* scope); // Create a new context with the given |scope| and size |slots|. BytecodeArrayBuilder& CreateFunctionContext(const Scope* scope, int slots); // Create a new eval context with the given |scope| and size |slots|. BytecodeArrayBuilder& CreateEvalContext(const Scope* scope, int slots); // Creates a new context with the given |scope| for a with-statement // with the |object| in a register. BytecodeArrayBuilder& CreateWithContext(Register object, const Scope* scope); // Create a new arguments object in the accumulator. BytecodeArrayBuilder& CreateArguments(CreateArgumentsType type); // Literals creation. Constant elements should be in the accumulator. BytecodeArrayBuilder& CreateRegExpLiteral(const AstRawString* pattern, int literal_index, int flags); BytecodeArrayBuilder& CreateArrayLiteral(size_t constant_elements_entry, int literal_index, int flags); BytecodeArrayBuilder& CreateEmptyArrayLiteral(int literal_index); BytecodeArrayBuilder& CreateArrayFromIterable(); BytecodeArrayBuilder& CreateObjectLiteral(size_t constant_properties_entry, int literal_index, int flags, Register output); BytecodeArrayBuilder& CreateEmptyObjectLiteral(); BytecodeArrayBuilder& CloneObject(Register source, int flags, int feedback_slot); // Gets or creates the template for a TemplateObjectDescription which will // be inserted at constant pool index |template_object_description_entry|. BytecodeArrayBuilder& GetTemplateObject( size_t template_object_description_entry, int feedback_slot); // Push the context in accumulator as the new context, and store in register // |context|. BytecodeArrayBuilder& PushContext(Register context); // Pop the current context and replace with |context|. BytecodeArrayBuilder& PopContext(Register context); // Call a JS function which is known to be a property of a JS object. The // JSFunction or Callable to be called should be in |callable|. The arguments // should be in |args|, with the receiver in |args[0]|. The call type of the // expression is in |call_type|. Type feedback is recorded in the // |feedback_slot| in the type feedback vector. BytecodeArrayBuilder& CallProperty(Register callable, RegisterList args, int feedback_slot); // Call a JS function with an known undefined receiver. The JSFunction or // Callable to be called should be in |callable|. The arguments should be in // |args|, with no receiver as it is implicitly set to undefined. Type // feedback is recorded in the |feedback_slot| in the type feedback vector. BytecodeArrayBuilder& CallUndefinedReceiver(Register callable, RegisterList args, int feedback_slot); // Call a JS function with an any receiver, possibly (but not necessarily) // undefined. The JSFunction or Callable to be called should be in |callable|. // The arguments should be in |args|, with the receiver in |args[0]|. Type // feedback is recorded in the |feedback_slot| in the type feedback vector. BytecodeArrayBuilder& CallAnyReceiver(Register callable, RegisterList args, int feedback_slot); // Call a JS function with an any receiver, possibly (but not necessarily) // undefined. The JSFunction or Callable to be called should be in |callable|. // The arguments should be in |args|, with the receiver in |args[0]|. BytecodeArrayBuilder& CallNoFeedback(Register callable, RegisterList args); // Tail call into a JS function. The JSFunction or Callable to be called // should be in |callable|. The arguments should be in |args|, with the // receiver in |args[0]|. Type feedback is recorded in the |feedback_slot| in // the type feedback vector. BytecodeArrayBuilder& TailCall(Register callable, RegisterList args, int feedback_slot); // Call a JS function. The JSFunction or Callable to be called should be in // |callable|, the receiver in |args[0]| and the arguments in |args[1]| // onwards. The final argument must be a spread. BytecodeArrayBuilder& CallWithSpread(Register callable, RegisterList args, int feedback_slot); // Call the Construct operator. The accumulator holds the |new_target|. // The |constructor| is in a register and arguments are in |args|. BytecodeArrayBuilder& Construct(Register constructor, RegisterList args, int feedback_slot); // Call the Construct operator for use with a spread. The accumulator holds // the |new_target|. The |constructor| is in a register and arguments are in // |args|. The final argument must be a spread. BytecodeArrayBuilder& ConstructWithSpread(Register constructor, RegisterList args, int feedback_slot); // Call the runtime function with |function_id| and arguments |args|. BytecodeArrayBuilder& CallRuntime(Runtime::FunctionId function_id, RegisterList args); // Call the runtime function with |function_id| with single argument |arg|. BytecodeArrayBuilder& CallRuntime(Runtime::FunctionId function_id, Register arg); // Call the runtime function with |function_id| with no arguments. BytecodeArrayBuilder& CallRuntime(Runtime::FunctionId function_id); // Call the runtime function with |function_id| and arguments |args|, that // returns a pair of values. The return values will be returned in // |return_pair|. BytecodeArrayBuilder& CallRuntimeForPair(Runtime::FunctionId function_id, RegisterList args, RegisterList return_pair); // Call the runtime function with |function_id| with single argument |arg| // that returns a pair of values. The return values will be returned in // |return_pair|. BytecodeArrayBuilder& CallRuntimeForPair(Runtime::FunctionId function_id, Register arg, RegisterList return_pair); // Call the JS runtime function with |context_index| and arguments |args|, // with no receiver as it is implicitly set to undefined. BytecodeArrayBuilder& CallJSRuntime(int context_index, RegisterList args); // Operators (register holds the lhs value, accumulator holds the rhs value). // Type feedback will be recorded in the |feedback_slot| BytecodeArrayBuilder& BinaryOperation(Token::Value binop, Register reg, int feedback_slot); // Same as above, but lhs in the accumulator and rhs in |literal|. BytecodeArrayBuilder& BinaryOperationSmiLiteral(Token::Value binop, Smi literal, int feedback_slot); // Unary and Count Operators (value stored in accumulator). // Type feedback will be recorded in the |feedback_slot| BytecodeArrayBuilder& UnaryOperation(Token::Value op, int feedback_slot); enum class ToBooleanMode { kConvertToBoolean, // Perform ToBoolean conversion on accumulator. kAlreadyBoolean, // Accumulator is already a Boolean. }; // Unary Operators. BytecodeArrayBuilder& LogicalNot(ToBooleanMode mode); BytecodeArrayBuilder& TypeOf(); // Expects a heap object in the accumulator. Returns its super constructor in // the register |out| if it passes the IsConstructor test. Otherwise, it // throws a TypeError exception. BytecodeArrayBuilder& GetSuperConstructor(Register out); // Deletes property from an object. This expects that accumulator contains // the key to be deleted and the register contains a reference to the object. BytecodeArrayBuilder& Delete(Register object, LanguageMode language_mode); // JavaScript defines two kinds of 'nil'. enum NilValue { kNullValue, kUndefinedValue }; // Tests. BytecodeArrayBuilder& CompareOperation(Token::Value op, Register reg, int feedback_slot); BytecodeArrayBuilder& CompareOperation(Token::Value op, Register reg); BytecodeArrayBuilder& CompareReference(Register reg); BytecodeArrayBuilder& CompareUndetectable(); BytecodeArrayBuilder& CompareUndefined(); BytecodeArrayBuilder& CompareNull(); BytecodeArrayBuilder& CompareNil(Token::Value op, NilValue nil); BytecodeArrayBuilder& CompareTypeOf( TestTypeOfFlags::LiteralFlag literal_flag); // Converts accumulator and stores result in register |out|. BytecodeArrayBuilder& ToObject(Register out); BytecodeArrayBuilder& ToName(Register out); BytecodeArrayBuilder& ToString(); // Converts accumulator and stores result back in accumulator. BytecodeArrayBuilder& ToNumber(int feedback_slot); BytecodeArrayBuilder& ToNumeric(int feedback_slot); // Flow Control. BytecodeArrayBuilder& Bind(BytecodeLabel* label); BytecodeArrayBuilder& Bind(const BytecodeLabel& target, BytecodeLabel* label); BytecodeArrayBuilder& Bind(BytecodeJumpTable* jump_table, int case_value); BytecodeArrayBuilder& Jump(BytecodeLabel* label); BytecodeArrayBuilder& JumpLoop(BytecodeLabel* label, int loop_depth); BytecodeArrayBuilder& JumpIfTrue(ToBooleanMode mode, BytecodeLabel* label); BytecodeArrayBuilder& JumpIfFalse(ToBooleanMode mode, BytecodeLabel* label); BytecodeArrayBuilder& JumpIfNotHole(BytecodeLabel* label); BytecodeArrayBuilder& JumpIfJSReceiver(BytecodeLabel* label); BytecodeArrayBuilder& JumpIfNull(BytecodeLabel* label); BytecodeArrayBuilder& JumpIfNotNull(BytecodeLabel* label); BytecodeArrayBuilder& JumpIfUndefined(BytecodeLabel* label); BytecodeArrayBuilder& JumpIfNotUndefined(BytecodeLabel* label); BytecodeArrayBuilder& JumpIfNil(BytecodeLabel* label, Token::Value op, NilValue nil); BytecodeArrayBuilder& JumpIfNotNil(BytecodeLabel* label, Token::Value op, NilValue nil); BytecodeArrayBuilder& SwitchOnSmiNoFeedback(BytecodeJumpTable* jump_table); BytecodeArrayBuilder& StackCheck(int position); // Sets the pending message to the value in the accumulator, and returns the // previous pending message in the accumulator. BytecodeArrayBuilder& SetPendingMessage(); BytecodeArrayBuilder& Throw(); BytecodeArrayBuilder& ReThrow(); BytecodeArrayBuilder& Abort(AbortReason reason); BytecodeArrayBuilder& Return(); BytecodeArrayBuilder& ThrowReferenceErrorIfHole(const AstRawString* name); BytecodeArrayBuilder& ThrowSuperNotCalledIfHole(); BytecodeArrayBuilder& ThrowSuperAlreadyCalledIfNotHole(); // Debugger. BytecodeArrayBuilder& Debugger(); // Increment the block counter at the given slot (block code coverage). BytecodeArrayBuilder& IncBlockCounter(int slot); // Complex flow control. BytecodeArrayBuilder& ForInEnumerate(Register receiver); BytecodeArrayBuilder& ForInPrepare(RegisterList cache_info_triple, int feedback_slot); BytecodeArrayBuilder& ForInContinue(Register index, Register cache_length); BytecodeArrayBuilder& ForInNext(Register receiver, Register index, RegisterList cache_type_array_pair, int feedback_slot); BytecodeArrayBuilder& ForInStep(Register index); // Generators. BytecodeArrayBuilder& SuspendGenerator(Register generator, RegisterList registers, int suspend_id); BytecodeArrayBuilder& SwitchOnGeneratorState(Register generator, BytecodeJumpTable* jump_table); BytecodeArrayBuilder& ResumeGenerator(Register generator, RegisterList registers); // Exception handling. BytecodeArrayBuilder& MarkHandler(int handler_id, HandlerTable::CatchPrediction will_catch); BytecodeArrayBuilder& MarkTryBegin(int handler_id, Register context); BytecodeArrayBuilder& MarkTryEnd(int handler_id); // Creates a new handler table entry and returns a {hander_id} identifying the // entry, so that it can be referenced by above exception handling support. int NewHandlerEntry() { return handler_table_builder()->NewHandlerEntry(); } // Allocates a new jump table of given |size| and |case_value_base| in the // constant pool. BytecodeJumpTable* AllocateJumpTable(int size, int case_value_base); // Gets a constant pool entry. size_t GetConstantPoolEntry(const AstRawString* raw_string); size_t GetConstantPoolEntry(AstBigInt bigint); size_t GetConstantPoolEntry(const Scope* scope); size_t GetConstantPoolEntry(double number); #define ENTRY_GETTER(NAME, ...) size_t NAME##ConstantPoolEntry(); SINGLETON_CONSTANT_ENTRY_TYPES(ENTRY_GETTER) #undef ENTRY_GETTER // Allocates a slot in the constant pool which can later be set. size_t AllocateDeferredConstantPoolEntry(); // Sets the deferred value into an allocated constant pool entry. void SetDeferredConstantPoolEntry(size_t entry, Handle<Object> object); void InitializeReturnPosition(FunctionLiteral* literal); void SetStatementPosition(Statement* stmt) { if (stmt->position() == kNoSourcePosition) return; latest_source_info_.MakeStatementPosition(stmt->position()); } void SetExpressionPosition(Expression* expr) { SetExpressionPosition(expr->position()); } void SetExpressionPosition(int position) { if (position == kNoSourcePosition) return; if (!latest_source_info_.is_statement()) { // Ensure the current expression position is overwritten with the // latest value. latest_source_info_.MakeExpressionPosition(position); } } void SetExpressionAsStatementPosition(Expression* expr) { if (expr->position() == kNoSourcePosition) return; latest_source_info_.MakeStatementPosition(expr->position()); } void SetReturnPosition(int source_position, FunctionLiteral* literal) { if (source_position != kNoSourcePosition) { latest_source_info_.MakeStatementPosition(source_position); } else if (literal->return_position() != kNoSourcePosition) { latest_source_info_.MakeStatementPosition(literal->return_position()); } } bool RequiresImplicitReturn() const { return !return_seen_in_block_; } // Returns the raw operand value for the given register or register list. uint32_t GetInputRegisterOperand(Register reg); uint32_t GetOutputRegisterOperand(Register reg); uint32_t GetInputRegisterListOperand(RegisterList reg_list); uint32_t GetOutputRegisterListOperand(RegisterList reg_list); // Outputs raw register transfer bytecodes without going through the register // optimizer. void OutputLdarRaw(Register reg); void OutputStarRaw(Register reg); void OutputMovRaw(Register src, Register dest); // Accessors BytecodeRegisterAllocator* register_allocator() { return &register_allocator_; } const BytecodeRegisterAllocator* register_allocator() const { return &register_allocator_; } Zone* zone() const { return zone_; } private: friend class BytecodeRegisterAllocator; template <Bytecode bytecode, AccumulatorUse accumulator_use, OperandType... operand_types> friend class BytecodeNodeBuilder; const FeedbackVectorSpec* feedback_vector_spec() const { return feedback_vector_spec_; } // Returns the current source position for the given |bytecode|. V8_INLINE BytecodeSourceInfo CurrentSourcePosition(Bytecode bytecode); #define DECLARE_BYTECODE_OUTPUT(Name, ...) \ template <typename... Operands> \ V8_INLINE BytecodeNode Create##Name##Node(Operands... operands); \ template <typename... Operands> \ V8_INLINE void Output##Name(Operands... operands); \ template <typename... Operands> \ V8_INLINE void Output##Name(BytecodeLabel* label, Operands... operands); BYTECODE_LIST(DECLARE_BYTECODE_OUTPUT) #undef DECLARE_OPERAND_TYPE_INFO V8_INLINE void OutputSwitchOnSmiNoFeedback(BytecodeJumpTable* jump_table); bool RegisterIsValid(Register reg) const; bool RegisterListIsValid(RegisterList reg_list) const; // Sets a deferred source info which should be emitted before any future // source info (either attached to a following bytecode or as a nop). void SetDeferredSourceInfo(BytecodeSourceInfo source_info); // Either attach deferred source info to node, or emit it as a nop bytecode // if node already have valid source info. void AttachOrEmitDeferredSourceInfo(BytecodeNode* node); // Write bytecode to bytecode array. void Write(BytecodeNode* node); void WriteJump(BytecodeNode* node, BytecodeLabel* label); void WriteSwitch(BytecodeNode* node, BytecodeJumpTable* label); // Not implemented as the illegal bytecode is used inside internally // to indicate a bytecode field is not valid or an error has occurred // during bytecode generation. BytecodeArrayBuilder& Illegal(); template <Bytecode bytecode, AccumulatorUse accumulator_use> void PrepareToOutputBytecode(); void LeaveBasicBlock() { return_seen_in_block_ = false; } BytecodeArrayWriter* bytecode_array_writer() { return &bytecode_array_writer_; } ConstantArrayBuilder* constant_array_builder() { return &constant_array_builder_; } const ConstantArrayBuilder* constant_array_builder() const { return &constant_array_builder_; } HandlerTableBuilder* handler_table_builder() { return &handler_table_builder_; } Zone* zone_; FeedbackVectorSpec* feedback_vector_spec_; bool bytecode_generated_; ConstantArrayBuilder constant_array_builder_; HandlerTableBuilder handler_table_builder_; bool return_seen_in_block_; int parameter_count_; int local_register_count_; BytecodeRegisterAllocator register_allocator_; BytecodeArrayWriter bytecode_array_writer_; BytecodeRegisterOptimizer* register_optimizer_; BytecodeSourceInfo latest_source_info_; BytecodeSourceInfo deferred_source_info_; DISALLOW_COPY_AND_ASSIGN(BytecodeArrayBuilder); }; V8_EXPORT_PRIVATE std::ostream& operator<<( std::ostream& os, const BytecodeArrayBuilder::ToBooleanMode& mode); } // namespace interpreter } // namespace internal } // namespace v8 #endif // V8_INTERPRETER_BYTECODE_ARRAY_BUILDER_H_
2c2b2c3452a1a3f4915766e83eadf2b4eaff7600
ecaa999b7550e3449ad633c7e878a9f658b600c8
/Private/BlueprintChecker.cpp
805db0f3d84df6a2607b9c31ec48e2dc64f38f27
[]
no_license
Hengle/blueprint-checker
fa2edb51f2271226f0da98181c0a589a06e11506
7ee396f60956e8a48df28206b9fd68d6c4ee838a
refs/heads/master
2023-07-16T07:07:55.105112
2021-08-25T10:11:04
2021-08-25T10:11:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,561
cpp
#include "BlueprintChecker.h" #include "Util/FPlatformAgnosticChecker.h" #include "RequiredProgramMainCPPInclude.h" #include "easyargs/easyargs.h" FEngineLoop GEngineLoop; bool GIsConsoleExecutable = true; bool GIsTestMode = false; EasyArgs* EzArgs = nullptr; std::string Mode; std::string PathToFile; void ExtractFilepath() { PathToFile = EzArgs->GetValueFor("--filepath"); if (PathToFile.empty()) { PathToFile = EzArgs->GetValueFor("-f"); if (PathToFile.empty() && Mode != "StdIn") { std::wcerr << "You must provide file path!" << std::endl; exit(EXIT_FAILURE); } } } void ExtractMode() { Mode = EzArgs->GetValueFor("--mode"); if (Mode.empty()) { Mode = EzArgs->GetValueFor("-m"); if (Mode.empty()) { std::wcerr << "You must provide program run mode with -m or --mode flags!" << std::endl; exit(EXIT_FAILURE); } } } void InitializeEasyArgs(int Argc, char* Argv[]) { EzArgs = new EasyArgs(Argc, Argv); EzArgs->Version(PROGRAM_VERSION) ->Description(PROGRAM_DESCRIPTION) ->Flag("-h", "--help", "Help") ->Flag("-t", "--test", "Run all tests") ->Value("-m", "--mode", "Utility launch mode [Single|Batch|StdIn]", false) ->Value("-f", "--filepath", "Path to a file.\nIn single mode - blueprint path.\nIn batch mode - filenames file path\nLaunch in daemon-like mode", false); if (EzArgs->IsSet("-h") || EzArgs->IsSet("--help")) { EzArgs->PrintUsage(); exit(EXIT_SUCCESS); } if (EzArgs->IsSet("-t") || EzArgs->IsSet("--test")) { GIsTestMode = true; FPlatformAgnosticChecker::InitializeTestEnvironment(Argc, Argv); FPlatformAgnosticChecker::Exit(); exit(EXIT_SUCCESS); } } bool RunMain(int Argc, char* Argv[]) { InitializeEasyArgs(Argc, Argv); ExtractMode(); ExtractFilepath(); if (Mode == "Single") { return RunSingleMode(PathToFile); } if (Mode == "Batch") { return RunBatchMode(PathToFile); } if (Mode == "StdIn") { return RunStdInMode(); } std::wcerr << "Incorrect mode!" << std::endl; return false; } int main(int Argc, char* Argv[]) { if (!RunMain(Argc, Argv)) { exit(EXIT_FAILURE); } //TODO EzArgs var cleaning return 0; } // Here we explicitly say to linker which entry point to use #pragma comment(linker, "/SUBSYSTEM:CONSOLE /ENTRY:mainCRTStartup") #include <Windows.h> //TODO Get rid of two entry points in the file, but it looks like linker wants both of these functions here int WINAPI WinMain( _In_ HINSTANCE HInInstance, _In_opt_ HINSTANCE HPrevInstance, _In_ char*, _In_ int HCmdShow ) { return 0; }
e5d0029b0a8702673179bfb9725356e3dfe83df4
4eb5659ea87745215692b863ccc8007e9e6d55dc
/src/geo2d/build/temp.linux-x86_64-2.7/sip_geo2dcppstdvector0600stdvector2400.cpp
b5813353b97d1b16fd815079e75e9573d9cb7ab6
[]
no_license
rbianchi66/pyqt_md
a256bbd9f29a519d24398ee215d296780d0e354f
11d5f06c9e79cc45a0e849fdfedf73004133e792
refs/heads/master
2021-01-10T05:40:19.525779
2019-01-04T23:13:36
2019-01-04T23:13:36
44,700,909
0
1
null
null
null
null
UTF-8
C++
false
false
5,733
cpp
/* * Interface wrapper code. * * Generated by SIP 4.10.2 on Thu Mar 12 16:30:15 2015 */ #include "sipAPI_geo2dcpp.h" #line 736 "/home/rbianchi/projects/draw_areas/src/sipbin/stl.sip" #include <vector> #line 12 "sip_geo2dcppstdvector0600stdvector2400.cpp" extern "C" {static void assign_std_vector_0600std_vector_2400(void *, SIP_SSIZE_T, const void *);} static void assign_std_vector_0600std_vector_2400(void *sipDst, SIP_SSIZE_T sipDstIdx, const void *sipSrc) { reinterpret_cast<std::vector<std::vector<double> > *>(sipDst)[sipDstIdx] = *reinterpret_cast<const std::vector<std::vector<double> > *>(sipSrc); } extern "C" {static void *array_std_vector_0600std_vector_2400(SIP_SSIZE_T);} static void *array_std_vector_0600std_vector_2400(SIP_SSIZE_T sipNrElem) { return new std::vector<std::vector<double> >[sipNrElem]; } extern "C" {static void *copy_std_vector_0600std_vector_2400(const void *, SIP_SSIZE_T);} static void *copy_std_vector_0600std_vector_2400(const void *sipSrc, SIP_SSIZE_T sipSrcIdx) { return new std::vector<std::vector<double> >(reinterpret_cast<const std::vector<std::vector<double> > *>(sipSrc)[sipSrcIdx]); } /* Call the mapped type's destructor. */ extern "C" {static void release_std_vector_0600std_vector_2400(void *, int);} static void release_std_vector_0600std_vector_2400(void *ptr, int) { delete reinterpret_cast<std::vector<std::vector<double> > *>(ptr); } extern "C" {static int convertTo_std_vector_0600std_vector_2400(PyObject *, void **, int *, PyObject *);} static int convertTo_std_vector_0600std_vector_2400(PyObject *sipPy,void **sipCppPtrV,int *sipIsErr,PyObject *sipTransferObj) { std::vector<std::vector<double> > **sipCppPtr = reinterpret_cast<std::vector<std::vector<double> > **>(sipCppPtrV); #line 773 "/home/rbianchi/projects/draw_areas/src/sipbin/stl.sip" // Check the type of the Python object. We check that the type is // iterable and that the first element (if any) can be converted to // the correct type. const sipMappedType *mt = sipFindMappedType("std::vector<double>"); if (sipIsErr == NULL) { // Must be any iterable PyObject *i = PyObject_GetIter(sipPy); if (i == NULL) return false; // Make sure that we don't consume the original // sequence if it is already an iterator, otherwise we might // be missing an item later. if (i == sipPy) { Py_DECREF(i); return true; } return true; PyObject *item = PyIter_Next(i); bool convertible = !item || sipCanConvertToMappedType(item, mt, SIP_NOT_NONE); Py_DECREF(i); Py_XDECREF(item); return convertible; } // Itera sull'oggetto PyObject *iterator = PyObject_GetIter(sipPy); PyObject *item; std::vector< std::vector<double> > *V = new std::vector< std::vector<double> >(); while ((item = PyIter_Next(iterator))) { if (!sipCanConvertToMappedType(item, mt, SIP_NOT_NONE)) { PyErr_Format(PyExc_TypeError, "object in iterable cannot be converted to std::vector<double>"); *sipIsErr = 1; break; } int state; std::vector<double>* p = reinterpret_cast<std::vector<double>*>( sipConvertToMappedType(item, mt, 0, SIP_NOT_NONE, &state, sipIsErr)); if (!*sipIsErr) V->push_back(*p); sipReleaseMappedType(p, mt, state); Py_DECREF(item); } Py_DECREF(iterator); if (*sipIsErr) { delete V; return 0; } *sipCppPtr = V; return sipGetState(sipTransferObj); #line 117 "sip_geo2dcppstdvector0600stdvector2400.cpp" } extern "C" {static PyObject *convertFrom_std_vector_0600std_vector_2400(void *, PyObject *);} static PyObject *convertFrom_std_vector_0600std_vector_2400(void *sipCppV,PyObject *sipTransferObj) { std::vector<std::vector<double> > *sipCpp = reinterpret_cast<std::vector<std::vector<double> > *>(sipCppV); #line 740 "/home/rbianchi/projects/draw_areas/src/sipbin/stl.sip" PyObject *l; // Create the Python list of the correct length. if ((l = PyList_New(sipCpp -> size())) == NULL) return NULL; // Go through each element in the C++ instance and convert it to a // wrapped vector<P2d>. const sipMappedType *mt = sipFindMappedType("std::vector<double>"); for (std::vector< std::vector<double> >::size_type i = 0; i < sipCpp -> size(); ++i) { std::vector<double> *cpp = new std::vector<double>(sipCpp -> at(i)); PyObject *pobj; // Get the Python wrapper for the Type instance, creating a new // one if necessary, and handle any ownership transfer. if ((pobj = sipConvertFromMappedType(cpp, mt, sipTransferObj)) == NULL) { // There was an error so garbage collect the Python list. Py_DECREF(l); return NULL; } // Add the wrapper to the list. PyList_SET_ITEM(l, i, pobj); } // Return the Python list. return l; #line 157 "sip_geo2dcppstdvector0600stdvector2400.cpp" } sipMappedTypeDef sipTypeDef__geo2dcpp_std_vector_0600std_vector_2400 = { { -1, 0, 0, SIP_TYPE_MAPPED, sipNameNr_107, {0} }, { -1, {0, 0, 1}, 0, 0, 0, 0, 0, 0, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0} }, assign_std_vector_0600std_vector_2400, array_std_vector_0600std_vector_2400, copy_std_vector_0600std_vector_2400, release_std_vector_0600std_vector_2400, convertTo_std_vector_0600std_vector_2400, convertFrom_std_vector_0600std_vector_2400 };
75a2c7ed4123be9dae8595bb8e2c18764a067709
5afea21193abd573a5b7271c6059bec1a613cc41
/c++/1016.cpp
cc5769a0674ece90d6670c37131ccb55870a4622
[]
no_license
AugustoDipNiloy/URI-Online-Judge-Solution
8ff9cd40b493fc77928e69aa17af458437d115fa
8a15a6af86f45ae6498702012ae9c1454fbb60ef
refs/heads/master
2022-11-28T19:08:20.252312
2020-08-10T10:55:49
2020-08-10T10:55:49
283,962,707
2
1
null
null
null
null
UTF-8
C++
false
false
123
cpp
#include<stdio.h> int main () { int A,B; scanf("%d",&A); B=2*A; printf("%d minutos\n",B); return 0; }
53d2a74611445cd01af5b4dedb9b766ba6650cb2
27b2308ed09696f16580dd01c3181d86db661265
/rasterizer/CoreLib/LibIO.h
4a63f05788bd1bc2b482874b728fab6b32c3f46c
[]
no_license
cardadfar/740-project
ed32c5efc0d9692841e0047b0a38680f05183391
f2f5b9f48c63a47fea6c431c6be40645839e993c
refs/heads/main
2023-01-29T06:17:39.336379
2020-12-11T23:53:06
2020-12-11T23:53:06
300,440,791
0
1
null
null
null
null
UTF-8
C++
false
false
974
h
#ifndef CORE_LIB_IO_H #define CORE_LIB_IO_H #include "LibString.h" #include "Stream.h" #include "TextIO.h" namespace CoreLib { namespace IO { class File { public: static bool Exists(const CoreLib::Basic::String & fileName); static CoreLib::Basic::String ReadAllText(const CoreLib::Basic::String & fileName); }; class Path { public: #ifdef WIN32 static const wchar_t PathDelimiter = L'\\'; #else static const wchar_t PathDelimiter = L'/'; #endif static String TruncateExt(const String & path); static String ReplaceExt(const String & path, const wchar_t * newExt); static String GetFileName(const String & path); static String GetFileExt(const String & path); static String GetDirectoryName(const String & path); static String Combine(const String & path1, const String & path2); static String Combine(const String & path1, const String & path2, const String & path3); }; } } #endif
f094b08452c27943d54f2692ec025c7f47b3d1e5
c64e0472231bee7947145e771ddea2c1cacb9845
/uppsrc/CtrlLib/ChCoco.cpp
b415181170f971e2593e0159291c4f442c986940
[ "BSD-2-Clause", "BSD-3-Clause" ]
permissive
allenk/ultimatepp
842ff365c741f08ff4692595cba301b8ef26f924
6e0a82bddb3506670099286449235d09a1d6df5e
refs/heads/master
2021-01-03T19:36:25.758177
2020-02-12T18:35:59
2020-02-12T18:35:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,207
cpp
#include "CtrlLib.h" #include "ChCocoMM.h" #ifdef PLATFORM_COCOA namespace Upp { Image CocoImg(Color bg, int type, int value, int state) { Size isz(140, 140); ImageDraw iw(DPI(isz)); iw.DrawRect(0, 0, DPI(isz.cx), DPI(isz.cy), bg); Coco_PaintCh(iw.GetCGHandle(), type, value, state); return iw; } Image CocoImg(int type, int value = 0, int state = 0) { Image m[2]; for(int i = 0; i < 2; i++) m[i] = CocoImg(i ? Black() : White(), type, value, state); Image h = AutoCrop(RecreateAlpha(m[0], m[1])); int q = h.GetSize().cy / 4; SetHotSpots(h, Point(q, q)); return h; } Color CocoColor(int k, Color bg = SColorFace()) { return AvgColor(CocoImg(bg, COCO_NSCOLOR, k, 0)); } void SOImages(int imli, int type, int value) { Image h[4]; h[0] = CocoImg(type, value, CTRL_NORMAL); h[1] = CocoImg(type, value, CTRL_HOT); // same as Normal h[2] = CocoImg(type, value, CTRL_PRESSED); h[3] = CocoImg(type, value, CTRL_DISABLED); for(int i = 0; i < 4; i++) CtrlsImg::Set(imli++, Hot3(h[i])); } void CocoButton(Image *h, int type, int value) { h[0] = CocoImg(type, value, CTRL_NORMAL); h[1] = CocoImg(type, value, CTRL_HOT); // same as Normal h[2] = CocoImg(type, value, CTRL_PRESSED); h[3] = CocoImg(type, value, CTRL_DISABLED); } void CocoButton(Button::Style& s, int type, int value) { Image h[4]; CocoButton(h, type, value); for(int i = 0; i < 4; i++) { s.look[i] = h[i]; Image gg = CreateImage(h[i].GetSize(), SColorFace()); Over(gg, h[i]); s.monocolor[i] = s.textcolor[i] = i == CTRL_DISABLED ? SColorDisabled() : Grayscale(AvgColor(gg, h[i].GetSize().cy / 3)) > 160 ? Black() : White(); } s.overpaint = 5; s.pressoffset = Point(0, 0); } void ChHostSkin() { TIMING("ChHostSkin"); CtrlImg::Reset(); CtrlsImg::Reset(); ChReset(); GUI_GlobalStyle_Write(GUISTYLE_XP); GUI_PopUpEffect_Write(GUIEFFECT_NONE); SwapOKCancel_Write(true); SColorFace_Write(CocoColor(COCO_WINDOW, White())); SColorHighlight_Write(CocoColor(COCO_SELECTEDPAPER)); SColorHighlightText_Write(CocoColor(COCO_SELECTEDTEXT)); SColorText_Write(CocoColor(COCO_TEXT)); SColorPaper_Write(CocoColor(COCO_PAPER)); SColorDisabled_Write(CocoColor(COCO_DISABLED)); ColoredOverride(CtrlsImg::Iml(), CtrlsImg::Iml()); SOImages(CtrlsImg::I_S0, COCO_RADIOBUTTON, 0); SOImages(CtrlsImg::I_S1, COCO_RADIOBUTTON, 1); SOImages(CtrlsImg::I_O0, COCO_CHECKBOX, 0); SOImages(CtrlsImg::I_O1, COCO_CHECKBOX, 1); SOImages(CtrlsImg::I_O2, COCO_CHECKBOX, 2); CocoButton(Button::StyleNormal().Write(), COCO_BUTTON, 0); CocoButton(Button::StyleOk().Write(), COCO_BUTTON, 1); CocoButton(Button::StyleEdge().Write(), COCO_BEVELBUTTON, 0); CocoButton(Button::StyleScroll().Write(), COCO_BEVELBUTTON, 0); { auto& s = ToolButton::StyleDefault().Write(); Image h[4]; CocoButton(h, COCO_BEVELBUTTON, 0); s.look[CTRL_NORMAL] = Image(); s.look[CTRL_HOT] = h[CTRL_HOT]; s.look[CTRL_PRESSED] = h[CTRL_PRESSED]; s.look[CTRL_DISABLED] = Image(); CocoButton(h, COCO_BEVELBUTTON, 1); s.look[CTRL_CHECKED] = h[CTRL_NORMAL]; s.look[CTRL_HOTCHECKED] = h[CTRL_HOT]; } { ScrollBar::Style& s = ScrollBar::StyleDefault().Write(); s.arrowsize = 0; Image track = CocoImg(COCO_SCROLLTRACK); Image thumb = CocoImg(COCO_SCROLLTHUMB); s.barsize = track.GetHeight(); s.thumbwidth = thumb.GetHeight(); s.thumbmin = 2 * s.barsize; for(int status = CTRL_NORMAL; status <= CTRL_DISABLED; status++) { s.hupper[status] = s.hlower[status] = WithHotSpot(track, CH_SCROLLBAR_IMAGE, 0);; s.vupper[status] = s.vlower[status] = WithHotSpot(RotateAntiClockwise(track), CH_SCROLLBAR_IMAGE, 0); Image m = thumb; if(status == CTRL_HOT) Over(m, m); if(status == CTRL_PRESSED) { Over(m, m); Over(m, m); } s.hthumb[status] = WithHotSpot(m, CH_SCROLLBAR_IMAGE, 0); s.vthumb[status] = WithHotSpot(RotateClockwise(m), CH_SCROLLBAR_IMAGE, 0); } } auto field = [](int type) { Image m = CocoImg(SColorFace(), type, 0, 0); Rect r = m.GetSize(); r.left = r.top = DPI(5); r.right = min(r.left + DPI(10), r.right); r.bottom = min(r.top + DPI(5), r.bottom); return AvgColor(m, r); }; { EditString::Style& s = EditString::StyleDefault().Write(); s.focus = s.paper = field(COCO_TEXTFIELD); } { MultiButton::Style& s = MultiButton::StyleDefault().Write(); s.paper = field(COCO_POPUPBUTTON); } auto nsimg = [](int ii) { return CocoImg(COCO_NSIMAGE, ii); }; CtrlImg::Set(CtrlImg::I_information, nsimg(1)); CtrlImg::Set(CtrlImg::I_question, nsimg(0)); CtrlImg::Set(CtrlImg::I_exclamation, nsimg(0)); CtrlImg::Set(CtrlImg::I_error, nsimg(0)); Image button100x100[8]; Color text[8]; for(int i = 0; i < 8; i++) { ImageDraw iw(100, 100); const Button::Style& s = i < 4 ? Button::StyleNormal() : Button::StyleOk(); ChPaint(iw, 0, 0, 100, 100, s.look[i & 3]); button100x100[i] = iw; text[i] = s.monocolor[i & 3]; } ChSynthetic(button100x100, text, true); } }; #endif
[ "cxl@f0d560ea-af0d-0410-9eb7-867de7ffcac7" ]
cxl@f0d560ea-af0d-0410-9eb7-867de7ffcac7
d5b71acc738ed149851e119369a6bec2e12af357
fab5ce813034eb2dffa7699f72bd0c9baadfbe1f
/lab_5/lab/RangeArray.h
9e79641401175eca4251d090b468cb8e8db418c2
[]
no_license
leehuhlee/Programming-lab-1
5c100e8ac9a9bbe9d04d748df29baf8d78b37d49
18160243ced10fb496f093ab82696d32d6fce0bd
refs/heads/master
2020-09-10T16:12:58.738404
2019-11-14T17:58:32
2019-11-14T17:58:32
221,754,420
0
0
null
null
null
null
UTF-8
C++
false
false
236
h
#include "Array.h" class RangeArray : public Array{ protected: int low; int high; public: RangeArray(int, int); ~RangeArray(); int baseValue(); int endValue(); int& operator[](int); int operator[](int) const; };
ce6ef54f1f9fcf91e4b4fc2281207657d1c58507
dca653bb975528bd1b8ab2547f6ef4f48e15b7b7
/branches/wx-2.9.0.1/src/osx/core/printmac.cpp
f9ee5197cddd274628ddf3fcc7b2f6064b228dc5
[]
no_license
czxxjtu/wxPython-1
51ca2f62ff6c01722e50742d1813f4be378c0517
6a7473c258ea4105f44e31d140ea5c0ae6bc46d8
refs/heads/master
2021-01-15T12:09:59.328778
2015-01-05T20:55:10
2015-01-05T20:55:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
20,967
cpp
///////////////////////////////////////////////////////////////////////////// // Name: src/osx/core/printmac.cpp // Purpose: wxMacPrinter framework // Author: Julian Smart, Stefan Csomor // Modified by: // Created: 04/01/98 // RCS-ID: $Id$ // Copyright: (c) Julian Smart, Stefan Csomor // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// // For compilers that support precompilation, includes "wx.h". #include "wx/wxprec.h" #if wxUSE_PRINTING_ARCHITECTURE #ifdef __BORLANDC__ #pragma hdrstop #endif #ifndef WX_PRECOMP #include "wx/utils.h" #include "wx/dc.h" #include "wx/app.h" #include "wx/msgdlg.h" #include "wx/dcprint.h" #include "wx/math.h" #endif #include "wx/osx/private.h" #include "wx/osx/printmac.h" #include "wx/osx/private/print.h" #include "wx/printdlg.h" #include "wx/paper.h" #include "wx/osx/printdlg.h" #include <stdlib.h> // // move to print_osx.cpp // IMPLEMENT_DYNAMIC_CLASS(wxOSXPrintData, wxPrintNativeDataBase) bool wxOSXPrintData::IsOk() const { return (m_macPageFormat != kPMNoPageFormat) && (m_macPrintSettings != kPMNoPrintSettings) && (m_macPrintSession != kPMNoReference); } wxOSXPrintData::wxOSXPrintData() { m_macPageFormat = kPMNoPageFormat; m_macPrintSettings = kPMNoPrintSettings; m_macPrintSession = kPMNoReference ; m_macPaper = kPMNoData; } wxOSXPrintData::~wxOSXPrintData() { } void wxOSXPrintData::UpdateFromPMState() { } void wxOSXPrintData::UpdateToPMState() { } bool wxOSXPrintData::TransferFrom( const wxPrintData &data ) { PMPrinter printer; PMSessionGetCurrentPrinter(m_macPrintSession, &printer); wxSize papersize = wxDefaultSize; const wxPaperSize paperId = data.GetPaperId(); if ( paperId != wxPAPER_NONE && wxThePrintPaperDatabase ) { papersize = wxThePrintPaperDatabase->GetSize(paperId); if ( papersize != wxDefaultSize ) { papersize.x /= 10; papersize.y /= 10; } } else { papersize = data.GetPaperSize(); } if ( papersize != wxDefaultSize ) { papersize.x = (wxInt32) (papersize.x * mm2pt); papersize.y = (wxInt32) (papersize.y * mm2pt); double height, width; PMPaperGetHeight(m_macPaper, &height); PMPaperGetWidth(m_macPaper, &width); if ( fabs( width - papersize.x ) >= 5 || fabs( height - papersize.y ) >= 5 ) { // we have to change the current paper CFArrayRef paperlist = 0 ; if ( PMPrinterGetPaperList( printer, &paperlist ) == noErr ) { PMPaper bestPaper = kPMNoData ; CFIndex top = CFArrayGetCount(paperlist); for ( CFIndex i = 0 ; i < top ; ++ i ) { PMPaper paper = (PMPaper) CFArrayGetValueAtIndex( paperlist, i ); PMPaperGetHeight(paper, &height); PMPaperGetWidth(paper, &width); if ( fabs( width - papersize.x ) < 5 && fabs( height - papersize.y ) < 5 ) { // TODO test for duplicate hits and use additional // criteria for best match bestPaper = paper; } } PMPaper paper = kPMNoData; if ( bestPaper == kPMNoData ) { const PMPaperMargins margins = { 0.0, 0.0, 0.0, 0.0 }; wxString id, name(_T("Custom paper")); id.Printf(_T("wxPaperCustom%dx%d"), papersize.x, papersize.y); #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5 if ( PMPaperCreateCustom != NULL) { PMPaperCreateCustom(printer, wxCFStringRef( id, wxFont::GetDefaultEncoding() ), wxCFStringRef( name, wxFont::GetDefaultEncoding() ), papersize.x, papersize.y, &margins, &paper); } #endif #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5 if ( paper == kPMNoData ) { PMPaperCreate(printer, wxCFStringRef( id, wxFont::GetDefaultEncoding() ), wxCFStringRef( name, wxFont::GetDefaultEncoding() ), papersize.x, papersize.y, &margins, &paper); } #endif } if ( bestPaper != kPMNoData ) { PMPageFormat pageFormat; PMCreatePageFormatWithPMPaper(&pageFormat, bestPaper); PMCopyPageFormat( pageFormat, m_macPageFormat ); PMRelease(pageFormat); PMGetPageFormatPaper(m_macPageFormat, &m_macPaper); } PMRelease(paper); } } } CFArrayRef printerList; CFIndex index, count; CFStringRef name; if (PMServerCreatePrinterList(kPMServerLocal, &printerList) == noErr) { count = CFArrayGetCount(printerList); for (index = 0; index < count; index++) { printer = (PMPrinter)CFArrayGetValueAtIndex(printerList, index); if ((data.GetPrinterName().empty()) && (PMPrinterIsDefault(printer))) break; else { name = PMPrinterGetName(printer); CFRetain(name); if (data.GetPrinterName() == wxCFStringRef(name).AsString()) break; } } if (index < count) PMSessionSetCurrentPMPrinter(m_macPrintSession, printer); CFRelease(printerList); } PMSetCopies( m_macPrintSettings , data.GetNoCopies() , false ) ; PMSetCollate(m_macPrintSettings, data.GetCollate()); if ( data.IsOrientationReversed() ) PMSetOrientation( m_macPageFormat , ( data.GetOrientation() == wxLANDSCAPE ) ? kPMReverseLandscape : kPMReversePortrait , false ) ; else PMSetOrientation( m_macPageFormat , ( data.GetOrientation() == wxLANDSCAPE ) ? kPMLandscape : kPMPortrait , false ) ; PMDuplexMode mode = 0 ; switch( data.GetDuplex() ) { case wxDUPLEX_HORIZONTAL : mode = kPMDuplexNoTumble ; break ; case wxDUPLEX_VERTICAL : mode = kPMDuplexTumble ; break ; case wxDUPLEX_SIMPLEX : default : mode = kPMDuplexNone ; break ; } PMSetDuplex( m_macPrintSettings, mode ) ; // PMQualityMode not yet accessible via API if ( data.IsOrientationReversed() ) PMSetOrientation( m_macPageFormat , ( data.GetOrientation() == wxLANDSCAPE ) ? kPMReverseLandscape : kPMReversePortrait , false ) ; else PMSetOrientation( m_macPageFormat , ( data.GetOrientation() == wxLANDSCAPE ) ? kPMLandscape : kPMPortrait , false ) ; #ifndef __LP64__ // PMQualityMode not accessible via API // TODO: use our quality property to determine optimal resolution PMResolution res; PMTag tag = kPMMaxSquareResolution; PMPrinterGetPrinterResolution(printer, tag, &res); PMSetResolution( m_macPageFormat, &res); #endif // after setting the new resolution the format has to be updated, otherwise the page rect remains // at the 'old' scaling PMSessionValidatePageFormat(m_macPrintSession, m_macPageFormat, kPMDontWantBoolean); PMSessionValidatePrintSettings(m_macPrintSession, m_macPrintSettings, kPMDontWantBoolean); #if wxOSX_USE_COCOA UpdateFromPMState(); #endif return true ; } bool wxOSXPrintData::TransferTo( wxPrintData &data ) { OSStatus err = noErr ; #if wxOSX_USE_COCOA UpdateToPMState(); #endif UInt32 copies ; err = PMGetCopies( m_macPrintSettings , &copies ) ; if ( err == noErr ) data.SetNoCopies( copies ) ; PMOrientation orientation ; err = PMGetOrientation( m_macPageFormat , &orientation ) ; if ( err == noErr ) { if ( orientation == kPMPortrait || orientation == kPMReversePortrait ) { data.SetOrientation( wxPORTRAIT ); data.SetOrientationReversed( orientation == kPMReversePortrait ); } else { data.SetOrientation( wxLANDSCAPE ); data.SetOrientationReversed( orientation == kPMReverseLandscape ); } } Boolean collate; if (PMGetCollate(m_macPrintSettings, &collate) == noErr) data.SetCollate(collate); CFStringRef name; PMPrinter printer ; PMSessionGetCurrentPrinter( m_macPrintSession, &printer ); if (PMPrinterIsDefault(printer)) data.SetPrinterName(wxEmptyString); else { name = PMPrinterGetName(printer); CFRetain(name); data.SetPrinterName(wxCFStringRef(name).AsString()); } PMDuplexMode mode = 0 ; PMGetDuplex( m_macPrintSettings, &mode ) ; switch( mode ) { case kPMDuplexNoTumble : data.SetDuplex(wxDUPLEX_HORIZONTAL); break ; case kPMDuplexTumble : data.SetDuplex(wxDUPLEX_VERTICAL); break ; case kPMDuplexNone : default : data.SetDuplex(wxDUPLEX_SIMPLEX); break ; } // PMQualityMode not yet accessible via API double height, width; PMPaperGetHeight(m_macPaper, &height); PMPaperGetWidth(m_macPaper, &width); wxSize sz((int)(width * pt2mm + 0.5 ) , (int)(height * pt2mm + 0.5 )); data.SetPaperSize(sz); wxPaperSize id = wxThePrintPaperDatabase->GetSize(wxSize(sz.x* 10, sz.y * 10)); if (id != wxPAPER_NONE) { data.SetPaperId(id); } return true ; } void wxOSXPrintData::TransferFrom( wxPageSetupData *WXUNUSED(data) ) { // should we setup the page rect here ? // since MacOS sometimes has two same paper rects with different // page rects we could make it roundtrip safe perhaps } void wxOSXPrintData::TransferTo( wxPageSetupData* data ) { #if wxOSX_USE_COCOA UpdateToPMState(); #endif PMRect rPaper; OSStatus err = PMGetUnadjustedPaperRect(m_macPageFormat, &rPaper); if ( err == noErr ) { wxSize sz((int)(( rPaper.right - rPaper.left ) * pt2mm + 0.5 ) , (int)(( rPaper.bottom - rPaper.top ) * pt2mm + 0.5 )); data->SetPaperSize(sz); PMRect rPage ; err = PMGetUnadjustedPageRect(m_macPageFormat , &rPage ) ; if ( err == noErr ) { data->SetMinMarginTopLeft( wxPoint ( (int)(((double) rPage.left - rPaper.left ) * pt2mm) , (int)(((double) rPage.top - rPaper.top ) * pt2mm) ) ) ; data->SetMinMarginBottomRight( wxPoint ( (wxCoord)(((double) rPaper.right - rPage.right ) * pt2mm), (wxCoord)(((double) rPaper.bottom - rPage.bottom ) * pt2mm)) ) ; if ( data->GetMarginTopLeft().x < data->GetMinMarginTopLeft().x ) data->SetMarginTopLeft( wxPoint( data->GetMinMarginTopLeft().x , data->GetMarginTopLeft().y ) ) ; if ( data->GetMarginBottomRight().x < data->GetMinMarginBottomRight().x ) data->SetMarginBottomRight( wxPoint( data->GetMinMarginBottomRight().x , data->GetMarginBottomRight().y ) ); if ( data->GetMarginTopLeft().y < data->GetMinMarginTopLeft().y ) data->SetMarginTopLeft( wxPoint( data->GetMarginTopLeft().x , data->GetMinMarginTopLeft().y ) ); if ( data->GetMarginBottomRight().y < data->GetMinMarginBottomRight().y ) data->SetMarginBottomRight( wxPoint( data->GetMarginBottomRight().x , data->GetMinMarginBottomRight().y) ); } } } void wxOSXPrintData::TransferTo( wxPrintDialogData* data ) { #if wxOSX_USE_COCOA UpdateToPMState(); #endif UInt32 minPage , maxPage ; PMGetPageRange( m_macPrintSettings , &minPage , &maxPage ) ; data->SetMinPage( minPage ) ; data->SetMaxPage( maxPage ) ; UInt32 copies ; PMGetCopies( m_macPrintSettings , &copies ) ; data->SetNoCopies( copies ) ; UInt32 from , to ; PMGetFirstPage( m_macPrintSettings , &from ) ; PMGetLastPage( m_macPrintSettings , &to ) ; if ( to >= 0x7FFFFFFF ) // due to an OS Bug we don't get back kPMPrintAllPages { data->SetAllPages( true ) ; // This means all pages, more or less data->SetFromPage(1); data->SetToPage(9999); } else { data->SetFromPage( from ) ; data->SetToPage( to ) ; data->SetAllPages( false ); } } void wxOSXPrintData::TransferFrom( wxPrintDialogData* data ) { // Respect the value of m_printAllPages if ( data->GetAllPages() ) PMSetPageRange( m_macPrintSettings , data->GetMinPage() , (UInt32) kPMPrintAllPages ) ; else PMSetPageRange( m_macPrintSettings , data->GetMinPage() , data->GetMaxPage() ) ; PMSetCopies( m_macPrintSettings , data->GetNoCopies() , false ) ; PMSetFirstPage( m_macPrintSettings , data->GetFromPage() , false ) ; if (data->GetAllPages() || data->GetFromPage() == 0) PMSetLastPage( m_macPrintSettings , (UInt32) kPMPrintAllPages, true ) ; else PMSetLastPage( m_macPrintSettings , (UInt32) data->GetToPage() , false ) ; #if wxOSX_USE_COCOA UpdateFromPMState(); #endif } wxPrintNativeDataBase* wxOSXCreatePrintData() { #if wxOSX_USE_COCOA return new wxOSXCocoaPrintData(); #endif #if wxOSX_USE_CARBON return new wxOSXCarbonPrintData(); #endif return NULL; } /* * Printer */ IMPLEMENT_DYNAMIC_CLASS(wxMacPrinter, wxPrinterBase) wxMacPrinter::wxMacPrinter(wxPrintDialogData *data): wxPrinterBase(data) { } wxMacPrinter::~wxMacPrinter(void) { } bool wxMacPrinter::Print(wxWindow *parent, wxPrintout *printout, bool prompt) { sm_abortIt = false; sm_abortWindow = NULL; if (!printout) return false; printout->SetIsPreview(false); if (m_printDialogData.GetMinPage() < 1) m_printDialogData.SetMinPage(1); if (m_printDialogData.GetMaxPage() < 1) m_printDialogData.SetMaxPage(9999); // Create a suitable device context wxPrinterDC *dc = NULL; if (prompt) { wxMacPrintDialog dialog(parent, & m_printDialogData); if (dialog.ShowModal() == wxID_OK) { dc = wxDynamicCast(dialog.GetPrintDC(), wxPrinterDC); wxASSERT(dc); m_printDialogData = dialog.GetPrintDialogData(); } } else { dc = new wxPrinterDC( m_printDialogData.GetPrintData() ) ; } // May have pressed cancel. if (!dc || !dc->IsOk()) { delete dc; return false; } // on the mac we have always pixels as addressing mode with 72 dpi printout->SetPPIScreen(72, 72); #ifndef __LP64__ PMResolution res; wxOSXPrintData* nativeData = (wxOSXPrintData*) (m_printDialogData.GetPrintData().GetNativeData()); PMGetResolution( (nativeData->GetPageFormat()), &res); printout->SetPPIPrinter(int(res.hRes), int(res.vRes)); #endif // Set printout parameters printout->SetDC(dc); int w, h; dc->GetSize(&w, &h); printout->SetPageSizePixels((int)w, (int)h); printout->SetPaperRectPixels(dc->GetPaperRect()); wxCoord mw, mh; dc->GetSizeMM(&mw, &mh); printout->SetPageSizeMM((int)mw, (int)mh); // Create an abort window wxBeginBusyCursor(); printout->OnPreparePrinting(); // Get some parameters from the printout, if defined int fromPage, toPage; int minPage, maxPage; printout->GetPageInfo(&minPage, &maxPage, &fromPage, &toPage); if (maxPage == 0) { wxEndBusyCursor(); return false; } // Only set min and max, because from and to have been // set by the user m_printDialogData.SetMinPage(minPage); m_printDialogData.SetMaxPage(maxPage); printout->OnBeginPrinting(); bool keepGoing = true; if (!printout->OnBeginDocument(m_printDialogData.GetFromPage(), m_printDialogData.GetToPage())) { wxEndBusyCursor(); wxMessageBox(wxT("Could not start printing."), wxT("Print Error"), wxOK, parent); } int pn; for (pn = m_printDialogData.GetFromPage(); keepGoing && (pn <= m_printDialogData.GetToPage()) && printout->HasPage(pn); pn++) { if (sm_abortIt) { keepGoing = false; break; } else { dc->StartPage(); keepGoing = printout->OnPrintPage(pn); dc->EndPage(); } } printout->OnEndDocument(); printout->OnEndPrinting(); if (sm_abortWindow) { sm_abortWindow->Show(false); delete sm_abortWindow; sm_abortWindow = NULL; } wxEndBusyCursor(); delete dc; return true; } wxDC* wxMacPrinter::PrintDialog(wxWindow *parent) { wxDC* dc = NULL; wxPrintDialog dialog(parent, & m_printDialogData); int ret = dialog.ShowModal(); if (ret == wxID_OK) { dc = dialog.GetPrintDC(); m_printDialogData = dialog.GetPrintDialogData(); } return dc; } bool wxMacPrinter::Setup(wxWindow *WXUNUSED(parent)) { #if 0 wxPrintDialog dialog(parent, & m_printDialogData); dialog.GetPrintDialogData().SetSetupDialog(true); int ret = dialog.ShowModal(); if (ret == wxID_OK) m_printDialogData = dialog.GetPrintDialogData(); return (ret == wxID_OK); #endif return wxID_CANCEL; } /* * Print preview */ IMPLEMENT_CLASS(wxMacPrintPreview, wxPrintPreviewBase) wxMacPrintPreview::wxMacPrintPreview(wxPrintout *printout, wxPrintout *printoutForPrinting, wxPrintDialogData *data) : wxPrintPreviewBase(printout, printoutForPrinting, data) { DetermineScaling(); } wxMacPrintPreview::wxMacPrintPreview(wxPrintout *printout, wxPrintout *printoutForPrinting, wxPrintData *data): wxPrintPreviewBase(printout, printoutForPrinting, data) { DetermineScaling(); } wxMacPrintPreview::~wxMacPrintPreview(void) { } bool wxMacPrintPreview::Print(bool interactive) { if (!m_printPrintout) return false; wxMacPrinter printer(&m_printDialogData); return printer.Print(m_previewFrame, m_printPrintout, interactive); } void wxMacPrintPreview::DetermineScaling(void) { int screenWidth , screenHeight ; wxDisplaySize( &screenWidth , &screenHeight ) ; wxSize ppiScreen( 72 , 72 ) ; wxSize ppiPrinter( 72 , 72 ) ; // Note that with Leopard, screen dpi=72 is no longer a given m_previewPrintout->SetPPIScreen( ppiScreen.x , ppiScreen.y ) ; wxCoord w , h ; wxCoord ww, hh; wxRect paperRect; // Get a device context for the currently selected printer wxPrinterDC printerDC(m_printDialogData.GetPrintData()); if (printerDC.IsOk()) { printerDC.GetSizeMM(&ww, &hh); printerDC.GetSize( &w , &h ) ; ppiPrinter = printerDC.GetPPI() ; paperRect = printerDC.GetPaperRect(); m_isOk = true ; } else { // use some defaults w = 8 * 72 ; h = 11 * 72 ; ww = (wxCoord) (w * 25.4 / ppiPrinter.x) ; hh = (wxCoord) (h * 25.4 / ppiPrinter.y) ; paperRect = wxRect(0, 0, w, h); m_isOk = false ; } m_pageWidth = w; m_pageHeight = h; m_previewPrintout->SetPageSizePixels(w , h) ; m_previewPrintout->SetPageSizeMM(ww, hh); m_previewPrintout->SetPaperRectPixels(paperRect); m_previewPrintout->SetPPIPrinter( ppiPrinter.x , ppiPrinter.y ) ; m_previewScaleX = float(ppiScreen.x) / ppiPrinter.x; m_previewScaleY = float(ppiScreen.y) / ppiPrinter.y; } // // end of print_osx.cpp // #if wxOSX_USE_CARBON IMPLEMENT_DYNAMIC_CLASS(wxOSXCarbonPrintData, wxOSXPrintData) wxOSXCarbonPrintData::wxOSXCarbonPrintData() { if ( PMCreateSession( &m_macPrintSession ) == noErr ) { if ( PMCreatePageFormat(&m_macPageFormat) == noErr ) { PMSessionDefaultPageFormat(m_macPrintSession, m_macPageFormat); PMGetPageFormatPaper(m_macPageFormat, &m_macPaper); } if ( PMCreatePrintSettings(&m_macPrintSettings) == noErr ) { PMSessionDefaultPrintSettings(m_macPrintSession, m_macPrintSettings); } } } wxOSXCarbonPrintData::~wxOSXCarbonPrintData() { (void)PMRelease(m_macPageFormat); (void)PMRelease(m_macPrintSettings); (void)PMRelease(m_macPrintSession); } #endif #endif
[ "RD@c3d73ce0-8a6f-49c7-b76d-6d57e0e08775" ]
RD@c3d73ce0-8a6f-49c7-b76d-6d57e0e08775
5c5a31934df39ff2a7604760b2c8aa53911ee1df
13a4da50a11b58e77052bfa26fd9abc88c17f4a2
/src/mvc/surgeon.h
94ed521bfe7701c2b458d08c0143d715f3a293e6
[ "MIT" ]
permissive
ItsMoss/mSurgical
8541ac807b56700f2edd25cc05cd1b262a72f6d7
855f60ae2e171d69857e5627d4ff623a2a10e850
refs/heads/master
2020-03-27T08:43:30.155196
2018-08-27T10:58:23
2018-08-27T10:58:23
146,281,775
1
0
null
null
null
null
UTF-8
C++
false
false
1,924
h
#ifndef __SURGEON_H__ #define __SURGEON_H__ #include "surgery.h" class Surgeon { public: Surgeon(); // default constructor 0 Surgeon(QString fname, QString lname); // constructor 1 Surgeon(QString fname, QString lname, std::vector<Surgery> surgeries); // constructor 2 Surgeon(const Surgeon & rhs); // copy constructor Surgeon & operator=(const Surgeon & rhs); // assignment op ~Surgeon(); // destructor // get and set const QString & getFirstName() const; // returns variable firstName const QString & getLastName() const; // returns variable lastName const std::vector<Surgery> & getKnownSurgeries() const; // returns variable knownSurgeries const Surgery getKnownSurgery(int n) const; // returns knownSurgeries[n] const Surgery getKnownSurgery(QString n) const; // returns surgery from knownSurgeries with name n const int getCurrentScore() const; // returns variable currentScore const int getHighScore() const; // returns variable highScore void setFirstName(QString fname); // sets variable firstName void setLastName(QString lname); // sets variable lastName void setKnownSurgeries(std::vector<Surgery> surgeries); // sets variable knownSurgeries void setCurrentScore(int score); // sets variable currentScore void setHighScore(int score); // sets variable highScore // other void addSurgery(Surgery s); // adds a surgery to known surgeries protected: QString firstName; // first name of player's surgeon QString lastName; // last name of player's surgeon std::vector<Surgery> knownSurgeries; // known surgeries (should not exceed size of 16) int currentScore; // current score player's surgeon has int highScore; // highest score player's surgeon has }; #endif // !__SURGEON_H__
fb135dc1bbdd90fcf8892d8e34d2fbd5f7d389f1
be3167504c0e32d7708e7d13725c2dbc9232f2cb
/mame/src/mame/includes/suprridr.h
99c32252cd3f008e1c6de9d5ec99b65297ed1334
[]
no_license
sysfce2/MAME-Plus-Plus-Kaillera
83b52085dda65045d9f5e8a0b6f3977d75179e78
9692743849af5a808e217470abc46e813c9068a5
refs/heads/master
2023-08-10T06:12:47.451039
2016-08-01T09:44:21
2016-08-01T09:44:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,629
h
/************************************************************************* Venture Line Super Rider driver **************************************************************************/ class suprridr_state : public driver_device { public: suprridr_state(const machine_config &mconfig, device_type type, const char *tag) : driver_device(mconfig, type, tag) , m_fgram(*this, "fgram"), m_bgram(*this, "bgram"), m_spriteram(*this, "spriteram"){ } UINT8 m_nmi_enable; UINT8 m_sound_data; required_shared_ptr<UINT8> m_fgram; required_shared_ptr<UINT8> m_bgram; tilemap_t *m_fg_tilemap; tilemap_t *m_bg_tilemap; tilemap_t *m_bg_tilemap_noscroll; UINT8 m_flipx; UINT8 m_flipy; required_shared_ptr<UINT8> m_spriteram; DECLARE_WRITE8_MEMBER(nmi_enable_w); DECLARE_WRITE8_MEMBER(sound_data_w); DECLARE_WRITE8_MEMBER(sound_irq_ack_w); DECLARE_WRITE8_MEMBER(coin_lock_w); DECLARE_WRITE8_MEMBER(suprridr_flipx_w); DECLARE_WRITE8_MEMBER(suprridr_flipy_w); DECLARE_WRITE8_MEMBER(suprridr_fgdisable_w); DECLARE_WRITE8_MEMBER(suprridr_fgscrolly_w); DECLARE_WRITE8_MEMBER(suprridr_bgscrolly_w); DECLARE_WRITE8_MEMBER(suprridr_bgram_w); DECLARE_WRITE8_MEMBER(suprridr_fgram_w); DECLARE_CUSTOM_INPUT_MEMBER(suprridr_control_r); DECLARE_READ8_MEMBER(sound_data_r); TILE_GET_INFO_MEMBER(get_tile_info); TILE_GET_INFO_MEMBER(get_tile_info2); virtual void video_start(); virtual void palette_init(); }; /*----------- defined in video/suprridr.c -----------*/ int suprridr_is_screen_flipped(running_machine &machine); SCREEN_UPDATE_IND16( suprridr );
[ "mameppk@199a702f-54f1-4ac0-8451-560dfe28270b" ]
mameppk@199a702f-54f1-4ac0-8451-560dfe28270b
a4adaff600c74c7c39aec726bc6d0c8e489d2e48
d5500d19ec504f1829bdb0b44bc0a8daab523365
/primary/project1/SECTION.CPP
4b9dcc6c6a85920c4af389a485bade4926476f2e
[]
no_license
NKcell/dishui
9942d35aa655f087a6886630a590819a849ad836
690ef788ccc82dc621a2ce74a01955d50823a54d
refs/heads/master
2021-01-09T12:35:10.775459
2020-04-19T07:24:00
2020-04-19T07:24:00
242,302,052
0
0
null
null
null
null
GB18030
C++
false
false
2,522
cpp
#include <stdio.h> #include"stdafx.h" #include "resource.h" #include <commctrl.h> #include"PEDEAL.h" extern HINSTANCE happInstance; void initDialogSec(HWND hDlg){ LV_COLUMN lv; HWND hListProcess; //初始化 memset(&lv,0,sizeof(LV_COLUMN)); hListProcess = GetDlgItem(hDlg,IDC_LIST_SECTION); SendMessage(hListProcess,LVM_SETEXTENDEDLISTVIEWSTYLE,LVS_EX_FULLROWSELECT,LVS_EX_FULLROWSELECT); lv.mask = LVCF_TEXT | LVCF_WIDTH | LVCF_SUBITEM; lv.pszText = TEXT("NAME"); //列标题 lv.cx = 120; //列宽 lv.iSubItem = 0; //ListView_InsertColumn(hListProcess, 0, &lv); SendMessage(hListProcess,LVM_INSERTCOLUMN,0,(DWORD)&lv); lv.pszText = TEXT("VirtualSize"); lv.cx = 100; lv.iSubItem = 1; //ListView_InsertColumn(hListProcess, 1, &lv); SendMessage(hListProcess,LVM_INSERTCOLUMN,1,(DWORD)&lv); lv.pszText = TEXT("VirtualOffset"); lv.cx = 100; lv.iSubItem = 2; ListView_InsertColumn(hListProcess, 2, &lv); lv.pszText = TEXT("RawSize"); lv.cx = 100; lv.iSubItem = 3; ListView_InsertColumn(hListProcess, 3, &lv); lv.pszText = TEXT("RawOffset"); lv.cx = 100; lv.iSubItem = 4; ListView_InsertColumn(hListProcess, 4, &lv); lv.pszText = TEXT("Characteristics"); lv.cx = 100; lv.iSubItem = 5; ListView_InsertColumn(hListProcess, 5, &lv); setSection(hListProcess); } BOOL CALLBACK DialogSec( HWND hwndDlg, // handle to dialog box UINT uMsg, // message WPARAM wParam, // first message parameter LPARAM lParam // second message parameter ) { switch(uMsg) { case WM_INITDIALOG : { HICON hMyIcon = LoadIcon(happInstance, MAKEINTRESOURCE(IDI_ICON)); SendMessage(hwndDlg, WM_SETICON, ICON_SMALL, (DWORD)hMyIcon); SendMessage(hwndDlg, WM_SETICON, ICON_BIG, (DWORD)hMyIcon); initDialogSec(hwndDlg); return TRUE ; } case WM_CLOSE: { EndDialog(hwndDlg, wParam); return TRUE; } } return FALSE ; } void showSection(HWND hwndDlg){ DialogBox(happInstance, MAKEINTRESOURCE(IDD_DIALOG_SECTION), hwndDlg, (DLGPROC)DialogSec); }
f6d852d6a0fda2075e5da8ba8ac663fed60c490e
99d054f93c3dd45a80e99be05f3f64c2c568ea5d
/Online Judges/Neps Academy/Distância de Manhattan (OBI2013)/main.cpp
9bb26104b462dd369c883346899188c4d2dd764e
[ "MIT" ]
permissive
AnneLivia/Competitive-Programming
65972d72fc4a0b37589da408e52ada19889f7ba8
f4057e4bce37a636c85875cc80e5a53eb715f4be
refs/heads/master
2022-12-23T11:52:04.299919
2022-12-12T16:20:05
2022-12-12T16:20:05
117,617,504
74
21
MIT
2019-11-14T03:11:58
2018-01-16T01:58:28
C++
UTF-8
C++
false
false
563
cpp
#include <iostream> using namespace std; int main() { int x1, x2, y1, y2; cin >> x1 >> y1 >> x2 >> y2; /* Euclidean distance is a straight line between two points shortest path between two points (diagonal map). Manhattan distance is not likely to euclidean, suppose there are many blocks and some paths, it cannot go through the blocks, it must go through the paths; Running through streets must be used the Manhattan distance */ cout << abs(x1 - x2) + abs(y1-y2) << endl; return 0; }
6c7ad43270bf33aa0f1b2656c99b94feaecfbc63
6085caf22b55ea6541bc188c83606b81e081d398
/comancpipeline/Tools/src/diffequations.cpp
7d20061a9e6a5510d58157a3938142903f59142a
[ "MIT" ]
permissive
SharperJBCA/COMAPreduce
55f2bf38bccc46d2c5e64c4ea7dcaaff3f65f3a3
0a6bcd4c23263c732e9a126d0379bb05afad3277
refs/heads/master
2023-08-17T14:13:38.030490
2022-07-13T16:39:07
2022-07-13T16:39:07
169,560,696
5
2
MIT
2023-07-06T22:20:27
2019-02-07T11:24:07
C++
UTF-8
C++
false
false
46,428
cpp
/************************************************************************* ALGLIB 3.16.0 (source code generated 2019-12-19) Copyright (c) Sergey Bochkanov (ALGLIB project). >>> SOURCE LICENSE >>> 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 (www.fsf.org); either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. A copy of the GNU General Public License is available at http://www.fsf.org/licensing/licenses >>> END OF LICENSE >>> *************************************************************************/ #ifdef _MSC_VER #define _CRT_SECURE_NO_WARNINGS #endif #include "stdafx.h" #include "diffequations.h" // disable some irrelevant warnings #if (AE_COMPILER==AE_MSVC) && !defined(AE_ALL_WARNINGS) #pragma warning(disable:4100) #pragma warning(disable:4127) #pragma warning(disable:4611) #pragma warning(disable:4702) #pragma warning(disable:4996) #endif ///////////////////////////////////////////////////////////////////////// // // THIS SECTION CONTAINS IMPLEMENTATION OF C++ INTERFACE // ///////////////////////////////////////////////////////////////////////// namespace alglib { #if defined(AE_COMPILE_ODESOLVER) || !defined(AE_PARTIAL_BUILD) #endif #if defined(AE_COMPILE_ODESOLVER) || !defined(AE_PARTIAL_BUILD) /************************************************************************* *************************************************************************/ _odesolverstate_owner::_odesolverstate_owner() { jmp_buf _break_jump; alglib_impl::ae_state _state; alglib_impl::ae_state_init(&_state); if( setjmp(_break_jump) ) { if( p_struct!=NULL ) { alglib_impl::_odesolverstate_destroy(p_struct); alglib_impl::ae_free(p_struct); } p_struct = NULL; #if !defined(AE_NO_EXCEPTIONS) _ALGLIB_CPP_EXCEPTION(_state.error_msg); #else _ALGLIB_SET_ERROR_FLAG(_state.error_msg); return; #endif } alglib_impl::ae_state_set_break_jump(&_state, &_break_jump); p_struct = NULL; p_struct = (alglib_impl::odesolverstate*)alglib_impl::ae_malloc(sizeof(alglib_impl::odesolverstate), &_state); memset(p_struct, 0, sizeof(alglib_impl::odesolverstate)); alglib_impl::_odesolverstate_init(p_struct, &_state, ae_false); ae_state_clear(&_state); } _odesolverstate_owner::_odesolverstate_owner(const _odesolverstate_owner &rhs) { jmp_buf _break_jump; alglib_impl::ae_state _state; alglib_impl::ae_state_init(&_state); if( setjmp(_break_jump) ) { if( p_struct!=NULL ) { alglib_impl::_odesolverstate_destroy(p_struct); alglib_impl::ae_free(p_struct); } p_struct = NULL; #if !defined(AE_NO_EXCEPTIONS) _ALGLIB_CPP_EXCEPTION(_state.error_msg); #else _ALGLIB_SET_ERROR_FLAG(_state.error_msg); return; #endif } alglib_impl::ae_state_set_break_jump(&_state, &_break_jump); p_struct = NULL; alglib_impl::ae_assert(rhs.p_struct!=NULL, "ALGLIB: odesolverstate copy constructor failure (source is not initialized)", &_state); p_struct = (alglib_impl::odesolverstate*)alglib_impl::ae_malloc(sizeof(alglib_impl::odesolverstate), &_state); memset(p_struct, 0, sizeof(alglib_impl::odesolverstate)); alglib_impl::_odesolverstate_init_copy(p_struct, const_cast<alglib_impl::odesolverstate*>(rhs.p_struct), &_state, ae_false); ae_state_clear(&_state); } _odesolverstate_owner& _odesolverstate_owner::operator=(const _odesolverstate_owner &rhs) { if( this==&rhs ) return *this; jmp_buf _break_jump; alglib_impl::ae_state _state; alglib_impl::ae_state_init(&_state); if( setjmp(_break_jump) ) { #if !defined(AE_NO_EXCEPTIONS) _ALGLIB_CPP_EXCEPTION(_state.error_msg); #else _ALGLIB_SET_ERROR_FLAG(_state.error_msg); return *this; #endif } alglib_impl::ae_state_set_break_jump(&_state, &_break_jump); alglib_impl::ae_assert(p_struct!=NULL, "ALGLIB: odesolverstate assignment constructor failure (destination is not initialized)", &_state); alglib_impl::ae_assert(rhs.p_struct!=NULL, "ALGLIB: odesolverstate assignment constructor failure (source is not initialized)", &_state); alglib_impl::_odesolverstate_destroy(p_struct); memset(p_struct, 0, sizeof(alglib_impl::odesolverstate)); alglib_impl::_odesolverstate_init_copy(p_struct, const_cast<alglib_impl::odesolverstate*>(rhs.p_struct), &_state, ae_false); ae_state_clear(&_state); return *this; } _odesolverstate_owner::~_odesolverstate_owner() { if( p_struct!=NULL ) { alglib_impl::_odesolverstate_destroy(p_struct); ae_free(p_struct); } } alglib_impl::odesolverstate* _odesolverstate_owner::c_ptr() { return p_struct; } alglib_impl::odesolverstate* _odesolverstate_owner::c_ptr() const { return const_cast<alglib_impl::odesolverstate*>(p_struct); } odesolverstate::odesolverstate() : _odesolverstate_owner() ,needdy(p_struct->needdy),y(&p_struct->y),dy(&p_struct->dy),x(p_struct->x) { } odesolverstate::odesolverstate(const odesolverstate &rhs):_odesolverstate_owner(rhs) ,needdy(p_struct->needdy),y(&p_struct->y),dy(&p_struct->dy),x(p_struct->x) { } odesolverstate& odesolverstate::operator=(const odesolverstate &rhs) { if( this==&rhs ) return *this; _odesolverstate_owner::operator=(rhs); return *this; } odesolverstate::~odesolverstate() { } /************************************************************************* *************************************************************************/ _odesolverreport_owner::_odesolverreport_owner() { jmp_buf _break_jump; alglib_impl::ae_state _state; alglib_impl::ae_state_init(&_state); if( setjmp(_break_jump) ) { if( p_struct!=NULL ) { alglib_impl::_odesolverreport_destroy(p_struct); alglib_impl::ae_free(p_struct); } p_struct = NULL; #if !defined(AE_NO_EXCEPTIONS) _ALGLIB_CPP_EXCEPTION(_state.error_msg); #else _ALGLIB_SET_ERROR_FLAG(_state.error_msg); return; #endif } alglib_impl::ae_state_set_break_jump(&_state, &_break_jump); p_struct = NULL; p_struct = (alglib_impl::odesolverreport*)alglib_impl::ae_malloc(sizeof(alglib_impl::odesolverreport), &_state); memset(p_struct, 0, sizeof(alglib_impl::odesolverreport)); alglib_impl::_odesolverreport_init(p_struct, &_state, ae_false); ae_state_clear(&_state); } _odesolverreport_owner::_odesolverreport_owner(const _odesolverreport_owner &rhs) { jmp_buf _break_jump; alglib_impl::ae_state _state; alglib_impl::ae_state_init(&_state); if( setjmp(_break_jump) ) { if( p_struct!=NULL ) { alglib_impl::_odesolverreport_destroy(p_struct); alglib_impl::ae_free(p_struct); } p_struct = NULL; #if !defined(AE_NO_EXCEPTIONS) _ALGLIB_CPP_EXCEPTION(_state.error_msg); #else _ALGLIB_SET_ERROR_FLAG(_state.error_msg); return; #endif } alglib_impl::ae_state_set_break_jump(&_state, &_break_jump); p_struct = NULL; alglib_impl::ae_assert(rhs.p_struct!=NULL, "ALGLIB: odesolverreport copy constructor failure (source is not initialized)", &_state); p_struct = (alglib_impl::odesolverreport*)alglib_impl::ae_malloc(sizeof(alglib_impl::odesolverreport), &_state); memset(p_struct, 0, sizeof(alglib_impl::odesolverreport)); alglib_impl::_odesolverreport_init_copy(p_struct, const_cast<alglib_impl::odesolverreport*>(rhs.p_struct), &_state, ae_false); ae_state_clear(&_state); } _odesolverreport_owner& _odesolverreport_owner::operator=(const _odesolverreport_owner &rhs) { if( this==&rhs ) return *this; jmp_buf _break_jump; alglib_impl::ae_state _state; alglib_impl::ae_state_init(&_state); if( setjmp(_break_jump) ) { #if !defined(AE_NO_EXCEPTIONS) _ALGLIB_CPP_EXCEPTION(_state.error_msg); #else _ALGLIB_SET_ERROR_FLAG(_state.error_msg); return *this; #endif } alglib_impl::ae_state_set_break_jump(&_state, &_break_jump); alglib_impl::ae_assert(p_struct!=NULL, "ALGLIB: odesolverreport assignment constructor failure (destination is not initialized)", &_state); alglib_impl::ae_assert(rhs.p_struct!=NULL, "ALGLIB: odesolverreport assignment constructor failure (source is not initialized)", &_state); alglib_impl::_odesolverreport_destroy(p_struct); memset(p_struct, 0, sizeof(alglib_impl::odesolverreport)); alglib_impl::_odesolverreport_init_copy(p_struct, const_cast<alglib_impl::odesolverreport*>(rhs.p_struct), &_state, ae_false); ae_state_clear(&_state); return *this; } _odesolverreport_owner::~_odesolverreport_owner() { if( p_struct!=NULL ) { alglib_impl::_odesolverreport_destroy(p_struct); ae_free(p_struct); } } alglib_impl::odesolverreport* _odesolverreport_owner::c_ptr() { return p_struct; } alglib_impl::odesolverreport* _odesolverreport_owner::c_ptr() const { return const_cast<alglib_impl::odesolverreport*>(p_struct); } odesolverreport::odesolverreport() : _odesolverreport_owner() ,nfev(p_struct->nfev),terminationtype(p_struct->terminationtype) { } odesolverreport::odesolverreport(const odesolverreport &rhs):_odesolverreport_owner(rhs) ,nfev(p_struct->nfev),terminationtype(p_struct->terminationtype) { } odesolverreport& odesolverreport::operator=(const odesolverreport &rhs) { if( this==&rhs ) return *this; _odesolverreport_owner::operator=(rhs); return *this; } odesolverreport::~odesolverreport() { } /************************************************************************* Cash-Karp adaptive ODE solver. This subroutine solves ODE Y'=f(Y,x) with initial conditions Y(xs)=Ys (here Y may be single variable or vector of N variables). INPUT PARAMETERS: Y - initial conditions, array[0..N-1]. contains values of Y[] at X[0] N - system size X - points at which Y should be tabulated, array[0..M-1] integrations starts at X[0], ends at X[M-1], intermediate values at X[i] are returned too. SHOULD BE ORDERED BY ASCENDING OR BY DESCENDING! M - number of intermediate points + first point + last point: * M>2 means that you need both Y(X[M-1]) and M-2 values at intermediate points * M=2 means that you want just to integrate from X[0] to X[1] and don't interested in intermediate values. * M=1 means that you don't want to integrate :) it is degenerate case, but it will be handled correctly. * M<1 means error Eps - tolerance (absolute/relative error on each step will be less than Eps). When passing: * Eps>0, it means desired ABSOLUTE error * Eps<0, it means desired RELATIVE error. Relative errors are calculated with respect to maximum values of Y seen so far. Be careful to use this criterion when starting from Y[] that are close to zero. H - initial step lenth, it will be adjusted automatically after the first step. If H=0, step will be selected automatically (usualy it will be equal to 0.001 of min(x[i]-x[j])). OUTPUT PARAMETERS State - structure which stores algorithm state between subsequent calls of OdeSolverIteration. Used for reverse communication. This structure should be passed to the OdeSolverIteration subroutine. SEE ALSO AutoGKSmoothW, AutoGKSingular, AutoGKIteration, AutoGKResults. -- ALGLIB -- Copyright 01.09.2009 by Bochkanov Sergey *************************************************************************/ void odesolverrkck(const real_1d_array &y, const ae_int_t n, const real_1d_array &x, const ae_int_t m, const double eps, const double h, odesolverstate &state, const xparams _xparams) { jmp_buf _break_jump; alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); if( setjmp(_break_jump) ) { #if !defined(AE_NO_EXCEPTIONS) _ALGLIB_CPP_EXCEPTION(_alglib_env_state.error_msg); #else _ALGLIB_SET_ERROR_FLAG(_alglib_env_state.error_msg); return; #endif } ae_state_set_break_jump(&_alglib_env_state, &_break_jump); if( _xparams.flags!=0x0 ) ae_state_set_flags(&_alglib_env_state, _xparams.flags); alglib_impl::odesolverrkck(const_cast<alglib_impl::ae_vector*>(y.c_ptr()), n, const_cast<alglib_impl::ae_vector*>(x.c_ptr()), m, eps, h, const_cast<alglib_impl::odesolverstate*>(state.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } /************************************************************************* Cash-Karp adaptive ODE solver. This subroutine solves ODE Y'=f(Y,x) with initial conditions Y(xs)=Ys (here Y may be single variable or vector of N variables). INPUT PARAMETERS: Y - initial conditions, array[0..N-1]. contains values of Y[] at X[0] N - system size X - points at which Y should be tabulated, array[0..M-1] integrations starts at X[0], ends at X[M-1], intermediate values at X[i] are returned too. SHOULD BE ORDERED BY ASCENDING OR BY DESCENDING! M - number of intermediate points + first point + last point: * M>2 means that you need both Y(X[M-1]) and M-2 values at intermediate points * M=2 means that you want just to integrate from X[0] to X[1] and don't interested in intermediate values. * M=1 means that you don't want to integrate :) it is degenerate case, but it will be handled correctly. * M<1 means error Eps - tolerance (absolute/relative error on each step will be less than Eps). When passing: * Eps>0, it means desired ABSOLUTE error * Eps<0, it means desired RELATIVE error. Relative errors are calculated with respect to maximum values of Y seen so far. Be careful to use this criterion when starting from Y[] that are close to zero. H - initial step lenth, it will be adjusted automatically after the first step. If H=0, step will be selected automatically (usualy it will be equal to 0.001 of min(x[i]-x[j])). OUTPUT PARAMETERS State - structure which stores algorithm state between subsequent calls of OdeSolverIteration. Used for reverse communication. This structure should be passed to the OdeSolverIteration subroutine. SEE ALSO AutoGKSmoothW, AutoGKSingular, AutoGKIteration, AutoGKResults. -- ALGLIB -- Copyright 01.09.2009 by Bochkanov Sergey *************************************************************************/ #if !defined(AE_NO_EXCEPTIONS) void odesolverrkck(const real_1d_array &y, const real_1d_array &x, const double eps, const double h, odesolverstate &state, const xparams _xparams) { jmp_buf _break_jump; alglib_impl::ae_state _alglib_env_state; ae_int_t n; ae_int_t m; n = y.length(); m = x.length(); alglib_impl::ae_state_init(&_alglib_env_state); if( setjmp(_break_jump) ) _ALGLIB_CPP_EXCEPTION(_alglib_env_state.error_msg); ae_state_set_break_jump(&_alglib_env_state, &_break_jump); if( _xparams.flags!=0x0 ) ae_state_set_flags(&_alglib_env_state, _xparams.flags); alglib_impl::odesolverrkck(const_cast<alglib_impl::ae_vector*>(y.c_ptr()), n, const_cast<alglib_impl::ae_vector*>(x.c_ptr()), m, eps, h, const_cast<alglib_impl::odesolverstate*>(state.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } #endif /************************************************************************* This function provides reverse communication interface Reverse communication interface is not documented or recommended to use. See below for functions which provide better documented API *************************************************************************/ bool odesolveriteration(const odesolverstate &state, const xparams _xparams) { jmp_buf _break_jump; alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); if( setjmp(_break_jump) ) { #if !defined(AE_NO_EXCEPTIONS) _ALGLIB_CPP_EXCEPTION(_alglib_env_state.error_msg); #else _ALGLIB_SET_ERROR_FLAG(_alglib_env_state.error_msg); return 0; #endif } ae_state_set_break_jump(&_alglib_env_state, &_break_jump); if( _xparams.flags!=0x0 ) ae_state_set_flags(&_alglib_env_state, _xparams.flags); ae_bool result = alglib_impl::odesolveriteration(const_cast<alglib_impl::odesolverstate*>(state.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return *(reinterpret_cast<bool*>(&result)); } void odesolversolve(odesolverstate &state, void (*diff)(const real_1d_array &y, double x, real_1d_array &dy, void *ptr), void *ptr, const xparams _xparams){ jmp_buf _break_jump; alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); if( setjmp(_break_jump) ) { #if !defined(AE_NO_EXCEPTIONS) _ALGLIB_CPP_EXCEPTION(_alglib_env_state.error_msg); #else _ALGLIB_SET_ERROR_FLAG(_alglib_env_state.error_msg); return; #endif } ae_state_set_break_jump(&_alglib_env_state, &_break_jump); if( _xparams.flags!=0x0 ) ae_state_set_flags(&_alglib_env_state, _xparams.flags); alglib_impl::ae_assert(diff!=NULL, "ALGLIB: error in 'odesolversolve()' (diff is NULL)", &_alglib_env_state); while( alglib_impl::odesolveriteration(state.c_ptr(), &_alglib_env_state) ) { _ALGLIB_CALLBACK_EXCEPTION_GUARD_BEGIN if( state.needdy ) { diff(state.y, state.x, state.dy, ptr); continue; } goto lbl_no_callback; _ALGLIB_CALLBACK_EXCEPTION_GUARD_END lbl_no_callback: alglib_impl::ae_assert(ae_false, "ALGLIB: unexpected error in 'odesolversolve'", &_alglib_env_state); } alglib_impl::ae_state_clear(&_alglib_env_state); } /************************************************************************* ODE solver results Called after OdeSolverIteration returned False. INPUT PARAMETERS: State - algorithm state (used by OdeSolverIteration). OUTPUT PARAMETERS: M - number of tabulated values, M>=1 XTbl - array[0..M-1], values of X YTbl - array[0..M-1,0..N-1], values of Y in X[i] Rep - solver report: * Rep.TerminationType completetion code: * -2 X is not ordered by ascending/descending or there are non-distinct X[], i.e. X[i]=X[i+1] * -1 incorrect parameters were specified * 1 task has been solved * Rep.NFEV contains number of function calculations -- ALGLIB -- Copyright 01.09.2009 by Bochkanov Sergey *************************************************************************/ void odesolverresults(const odesolverstate &state, ae_int_t &m, real_1d_array &xtbl, real_2d_array &ytbl, odesolverreport &rep, const xparams _xparams) { jmp_buf _break_jump; alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); if( setjmp(_break_jump) ) { #if !defined(AE_NO_EXCEPTIONS) _ALGLIB_CPP_EXCEPTION(_alglib_env_state.error_msg); #else _ALGLIB_SET_ERROR_FLAG(_alglib_env_state.error_msg); return; #endif } ae_state_set_break_jump(&_alglib_env_state, &_break_jump); if( _xparams.flags!=0x0 ) ae_state_set_flags(&_alglib_env_state, _xparams.flags); alglib_impl::odesolverresults(const_cast<alglib_impl::odesolverstate*>(state.c_ptr()), &m, const_cast<alglib_impl::ae_vector*>(xtbl.c_ptr()), const_cast<alglib_impl::ae_matrix*>(ytbl.c_ptr()), const_cast<alglib_impl::odesolverreport*>(rep.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } #endif } ///////////////////////////////////////////////////////////////////////// // // THIS SECTION CONTAINS IMPLEMENTATION OF COMPUTATIONAL CORE // ///////////////////////////////////////////////////////////////////////// namespace alglib_impl { #if defined(AE_COMPILE_ODESOLVER) || !defined(AE_PARTIAL_BUILD) static double odesolver_odesolvermaxgrow = 3.0; static double odesolver_odesolvermaxshrink = 10.0; static void odesolver_odesolverinit(ae_int_t solvertype, /* Real */ ae_vector* y, ae_int_t n, /* Real */ ae_vector* x, ae_int_t m, double eps, double h, odesolverstate* state, ae_state *_state); #endif #if defined(AE_COMPILE_ODESOLVER) || !defined(AE_PARTIAL_BUILD) /************************************************************************* Cash-Karp adaptive ODE solver. This subroutine solves ODE Y'=f(Y,x) with initial conditions Y(xs)=Ys (here Y may be single variable or vector of N variables). INPUT PARAMETERS: Y - initial conditions, array[0..N-1]. contains values of Y[] at X[0] N - system size X - points at which Y should be tabulated, array[0..M-1] integrations starts at X[0], ends at X[M-1], intermediate values at X[i] are returned too. SHOULD BE ORDERED BY ASCENDING OR BY DESCENDING! M - number of intermediate points + first point + last point: * M>2 means that you need both Y(X[M-1]) and M-2 values at intermediate points * M=2 means that you want just to integrate from X[0] to X[1] and don't interested in intermediate values. * M=1 means that you don't want to integrate :) it is degenerate case, but it will be handled correctly. * M<1 means error Eps - tolerance (absolute/relative error on each step will be less than Eps). When passing: * Eps>0, it means desired ABSOLUTE error * Eps<0, it means desired RELATIVE error. Relative errors are calculated with respect to maximum values of Y seen so far. Be careful to use this criterion when starting from Y[] that are close to zero. H - initial step lenth, it will be adjusted automatically after the first step. If H=0, step will be selected automatically (usualy it will be equal to 0.001 of min(x[i]-x[j])). OUTPUT PARAMETERS State - structure which stores algorithm state between subsequent calls of OdeSolverIteration. Used for reverse communication. This structure should be passed to the OdeSolverIteration subroutine. SEE ALSO AutoGKSmoothW, AutoGKSingular, AutoGKIteration, AutoGKResults. -- ALGLIB -- Copyright 01.09.2009 by Bochkanov Sergey *************************************************************************/ void odesolverrkck(/* Real */ ae_vector* y, ae_int_t n, /* Real */ ae_vector* x, ae_int_t m, double eps, double h, odesolverstate* state, ae_state *_state) { _odesolverstate_clear(state); ae_assert(n>=1, "ODESolverRKCK: N<1!", _state); ae_assert(m>=1, "ODESolverRKCK: M<1!", _state); ae_assert(y->cnt>=n, "ODESolverRKCK: Length(Y)<N!", _state); ae_assert(x->cnt>=m, "ODESolverRKCK: Length(X)<M!", _state); ae_assert(isfinitevector(y, n, _state), "ODESolverRKCK: Y contains infinite or NaN values!", _state); ae_assert(isfinitevector(x, m, _state), "ODESolverRKCK: Y contains infinite or NaN values!", _state); ae_assert(ae_isfinite(eps, _state), "ODESolverRKCK: Eps is not finite!", _state); ae_assert(ae_fp_neq(eps,(double)(0)), "ODESolverRKCK: Eps is zero!", _state); ae_assert(ae_isfinite(h, _state), "ODESolverRKCK: H is not finite!", _state); odesolver_odesolverinit(0, y, n, x, m, eps, h, state, _state); } /************************************************************************* -- ALGLIB -- Copyright 01.09.2009 by Bochkanov Sergey *************************************************************************/ ae_bool odesolveriteration(odesolverstate* state, ae_state *_state) { ae_int_t n; ae_int_t m; ae_int_t i; ae_int_t j; ae_int_t k; double xc; double v; double h; double h2; ae_bool gridpoint; double err; double maxgrowpow; ae_int_t klimit; ae_bool result; /* * Reverse communication preparations * I know it looks ugly, but it works the same way * anywhere from C++ to Python. * * This code initializes locals by: * * random values determined during code * generation - on first subroutine call * * values from previous call - on subsequent calls */ if( state->rstate.stage>=0 ) { n = state->rstate.ia.ptr.p_int[0]; m = state->rstate.ia.ptr.p_int[1]; i = state->rstate.ia.ptr.p_int[2]; j = state->rstate.ia.ptr.p_int[3]; k = state->rstate.ia.ptr.p_int[4]; klimit = state->rstate.ia.ptr.p_int[5]; gridpoint = state->rstate.ba.ptr.p_bool[0]; xc = state->rstate.ra.ptr.p_double[0]; v = state->rstate.ra.ptr.p_double[1]; h = state->rstate.ra.ptr.p_double[2]; h2 = state->rstate.ra.ptr.p_double[3]; err = state->rstate.ra.ptr.p_double[4]; maxgrowpow = state->rstate.ra.ptr.p_double[5]; } else { n = 359; m = -58; i = -919; j = -909; k = 81; klimit = 255; gridpoint = ae_false; xc = -788; v = 809; h = 205; h2 = -838; err = 939; maxgrowpow = -526; } if( state->rstate.stage==0 ) { goto lbl_0; } /* * Routine body */ /* * prepare */ if( state->repterminationtype!=0 ) { result = ae_false; return result; } n = state->n; m = state->m; h = state->h; maxgrowpow = ae_pow(odesolver_odesolvermaxgrow, (double)(5), _state); state->repnfev = 0; /* * some preliminary checks for internal errors * after this we assume that H>0 and M>1 */ ae_assert(ae_fp_greater(state->h,(double)(0)), "ODESolver: internal error", _state); ae_assert(m>1, "ODESolverIteration: internal error", _state); /* * choose solver */ if( state->solvertype!=0 ) { goto lbl_1; } /* * Cask-Karp solver * Prepare coefficients table. * Check it for errors */ ae_vector_set_length(&state->rka, 6, _state); state->rka.ptr.p_double[0] = (double)(0); state->rka.ptr.p_double[1] = (double)1/(double)5; state->rka.ptr.p_double[2] = (double)3/(double)10; state->rka.ptr.p_double[3] = (double)3/(double)5; state->rka.ptr.p_double[4] = (double)(1); state->rka.ptr.p_double[5] = (double)7/(double)8; ae_matrix_set_length(&state->rkb, 6, 5, _state); state->rkb.ptr.pp_double[1][0] = (double)1/(double)5; state->rkb.ptr.pp_double[2][0] = (double)3/(double)40; state->rkb.ptr.pp_double[2][1] = (double)9/(double)40; state->rkb.ptr.pp_double[3][0] = (double)3/(double)10; state->rkb.ptr.pp_double[3][1] = -(double)9/(double)10; state->rkb.ptr.pp_double[3][2] = (double)6/(double)5; state->rkb.ptr.pp_double[4][0] = -(double)11/(double)54; state->rkb.ptr.pp_double[4][1] = (double)5/(double)2; state->rkb.ptr.pp_double[4][2] = -(double)70/(double)27; state->rkb.ptr.pp_double[4][3] = (double)35/(double)27; state->rkb.ptr.pp_double[5][0] = (double)1631/(double)55296; state->rkb.ptr.pp_double[5][1] = (double)175/(double)512; state->rkb.ptr.pp_double[5][2] = (double)575/(double)13824; state->rkb.ptr.pp_double[5][3] = (double)44275/(double)110592; state->rkb.ptr.pp_double[5][4] = (double)253/(double)4096; ae_vector_set_length(&state->rkc, 6, _state); state->rkc.ptr.p_double[0] = (double)37/(double)378; state->rkc.ptr.p_double[1] = (double)(0); state->rkc.ptr.p_double[2] = (double)250/(double)621; state->rkc.ptr.p_double[3] = (double)125/(double)594; state->rkc.ptr.p_double[4] = (double)(0); state->rkc.ptr.p_double[5] = (double)512/(double)1771; ae_vector_set_length(&state->rkcs, 6, _state); state->rkcs.ptr.p_double[0] = (double)2825/(double)27648; state->rkcs.ptr.p_double[1] = (double)(0); state->rkcs.ptr.p_double[2] = (double)18575/(double)48384; state->rkcs.ptr.p_double[3] = (double)13525/(double)55296; state->rkcs.ptr.p_double[4] = (double)277/(double)14336; state->rkcs.ptr.p_double[5] = (double)1/(double)4; ae_matrix_set_length(&state->rkk, 6, n, _state); /* * Main cycle consists of two iterations: * * outer where we travel from X[i-1] to X[i] * * inner where we travel inside [X[i-1],X[i]] */ ae_matrix_set_length(&state->ytbl, m, n, _state); ae_vector_set_length(&state->escale, n, _state); ae_vector_set_length(&state->yn, n, _state); ae_vector_set_length(&state->yns, n, _state); xc = state->xg.ptr.p_double[0]; ae_v_move(&state->ytbl.ptr.pp_double[0][0], 1, &state->yc.ptr.p_double[0], 1, ae_v_len(0,n-1)); for(j=0; j<=n-1; j++) { state->escale.ptr.p_double[j] = (double)(0); } i = 1; lbl_3: if( i>m-1 ) { goto lbl_5; } /* * begin inner iteration */ lbl_6: if( ae_false ) { goto lbl_7; } /* * truncate step if needed (beyond right boundary). * determine should we store X or not */ if( ae_fp_greater_eq(xc+h,state->xg.ptr.p_double[i]) ) { h = state->xg.ptr.p_double[i]-xc; gridpoint = ae_true; } else { gridpoint = ae_false; } /* * Update error scale maximums * * These maximums are initialized by zeros, * then updated every iterations. */ for(j=0; j<=n-1; j++) { state->escale.ptr.p_double[j] = ae_maxreal(state->escale.ptr.p_double[j], ae_fabs(state->yc.ptr.p_double[j], _state), _state); } /* * make one step: * 1. calculate all info needed to do step * 2. update errors scale maximums using values/derivatives * obtained during (1) * * Take into account that we use scaling of X to reduce task * to the form where x[0] < x[1] < ... < x[n-1]. So X is * replaced by x=xscale*t, and dy/dx=f(y,x) is replaced * by dy/dt=xscale*f(y,xscale*t). */ ae_v_move(&state->yn.ptr.p_double[0], 1, &state->yc.ptr.p_double[0], 1, ae_v_len(0,n-1)); ae_v_move(&state->yns.ptr.p_double[0], 1, &state->yc.ptr.p_double[0], 1, ae_v_len(0,n-1)); k = 0; lbl_8: if( k>5 ) { goto lbl_10; } /* * prepare data for the next update of YN/YNS */ state->x = state->xscale*(xc+state->rka.ptr.p_double[k]*h); ae_v_move(&state->y.ptr.p_double[0], 1, &state->yc.ptr.p_double[0], 1, ae_v_len(0,n-1)); for(j=0; j<=k-1; j++) { v = state->rkb.ptr.pp_double[k][j]; ae_v_addd(&state->y.ptr.p_double[0], 1, &state->rkk.ptr.pp_double[j][0], 1, ae_v_len(0,n-1), v); } state->needdy = ae_true; state->rstate.stage = 0; goto lbl_rcomm; lbl_0: state->needdy = ae_false; state->repnfev = state->repnfev+1; v = h*state->xscale; ae_v_moved(&state->rkk.ptr.pp_double[k][0], 1, &state->dy.ptr.p_double[0], 1, ae_v_len(0,n-1), v); /* * update YN/YNS */ v = state->rkc.ptr.p_double[k]; ae_v_addd(&state->yn.ptr.p_double[0], 1, &state->rkk.ptr.pp_double[k][0], 1, ae_v_len(0,n-1), v); v = state->rkcs.ptr.p_double[k]; ae_v_addd(&state->yns.ptr.p_double[0], 1, &state->rkk.ptr.pp_double[k][0], 1, ae_v_len(0,n-1), v); k = k+1; goto lbl_8; lbl_10: /* * estimate error */ err = (double)(0); for(j=0; j<=n-1; j++) { if( !state->fraceps ) { /* * absolute error is estimated */ err = ae_maxreal(err, ae_fabs(state->yn.ptr.p_double[j]-state->yns.ptr.p_double[j], _state), _state); } else { /* * Relative error is estimated */ v = state->escale.ptr.p_double[j]; if( ae_fp_eq(v,(double)(0)) ) { v = (double)(1); } err = ae_maxreal(err, ae_fabs(state->yn.ptr.p_double[j]-state->yns.ptr.p_double[j], _state)/v, _state); } } /* * calculate new step, restart if necessary */ if( ae_fp_less_eq(maxgrowpow*err,state->eps) ) { h2 = odesolver_odesolvermaxgrow*h; } else { h2 = h*ae_pow(state->eps/err, 0.2, _state); } if( ae_fp_less(h2,h/odesolver_odesolvermaxshrink) ) { h2 = h/odesolver_odesolvermaxshrink; } if( ae_fp_greater(err,state->eps) ) { h = h2; goto lbl_6; } /* * advance position */ xc = xc+h; ae_v_move(&state->yc.ptr.p_double[0], 1, &state->yn.ptr.p_double[0], 1, ae_v_len(0,n-1)); /* * update H */ h = h2; /* * break on grid point */ if( gridpoint ) { goto lbl_7; } goto lbl_6; lbl_7: /* * save result */ ae_v_move(&state->ytbl.ptr.pp_double[i][0], 1, &state->yc.ptr.p_double[0], 1, ae_v_len(0,n-1)); i = i+1; goto lbl_3; lbl_5: state->repterminationtype = 1; result = ae_false; return result; lbl_1: result = ae_false; return result; /* * Saving state */ lbl_rcomm: result = ae_true; state->rstate.ia.ptr.p_int[0] = n; state->rstate.ia.ptr.p_int[1] = m; state->rstate.ia.ptr.p_int[2] = i; state->rstate.ia.ptr.p_int[3] = j; state->rstate.ia.ptr.p_int[4] = k; state->rstate.ia.ptr.p_int[5] = klimit; state->rstate.ba.ptr.p_bool[0] = gridpoint; state->rstate.ra.ptr.p_double[0] = xc; state->rstate.ra.ptr.p_double[1] = v; state->rstate.ra.ptr.p_double[2] = h; state->rstate.ra.ptr.p_double[3] = h2; state->rstate.ra.ptr.p_double[4] = err; state->rstate.ra.ptr.p_double[5] = maxgrowpow; return result; } /************************************************************************* ODE solver results Called after OdeSolverIteration returned False. INPUT PARAMETERS: State - algorithm state (used by OdeSolverIteration). OUTPUT PARAMETERS: M - number of tabulated values, M>=1 XTbl - array[0..M-1], values of X YTbl - array[0..M-1,0..N-1], values of Y in X[i] Rep - solver report: * Rep.TerminationType completetion code: * -2 X is not ordered by ascending/descending or there are non-distinct X[], i.e. X[i]=X[i+1] * -1 incorrect parameters were specified * 1 task has been solved * Rep.NFEV contains number of function calculations -- ALGLIB -- Copyright 01.09.2009 by Bochkanov Sergey *************************************************************************/ void odesolverresults(odesolverstate* state, ae_int_t* m, /* Real */ ae_vector* xtbl, /* Real */ ae_matrix* ytbl, odesolverreport* rep, ae_state *_state) { double v; ae_int_t i; *m = 0; ae_vector_clear(xtbl); ae_matrix_clear(ytbl); _odesolverreport_clear(rep); rep->terminationtype = state->repterminationtype; if( rep->terminationtype>0 ) { *m = state->m; rep->nfev = state->repnfev; ae_vector_set_length(xtbl, state->m, _state); v = state->xscale; ae_v_moved(&xtbl->ptr.p_double[0], 1, &state->xg.ptr.p_double[0], 1, ae_v_len(0,state->m-1), v); ae_matrix_set_length(ytbl, state->m, state->n, _state); for(i=0; i<=state->m-1; i++) { ae_v_move(&ytbl->ptr.pp_double[i][0], 1, &state->ytbl.ptr.pp_double[i][0], 1, ae_v_len(0,state->n-1)); } } else { rep->nfev = 0; } } /************************************************************************* Internal initialization subroutine *************************************************************************/ static void odesolver_odesolverinit(ae_int_t solvertype, /* Real */ ae_vector* y, ae_int_t n, /* Real */ ae_vector* x, ae_int_t m, double eps, double h, odesolverstate* state, ae_state *_state) { ae_int_t i; double v; _odesolverstate_clear(state); /* * Prepare RComm */ ae_vector_set_length(&state->rstate.ia, 5+1, _state); ae_vector_set_length(&state->rstate.ba, 0+1, _state); ae_vector_set_length(&state->rstate.ra, 5+1, _state); state->rstate.stage = -1; state->needdy = ae_false; /* * check parameters. */ if( (n<=0||m<1)||ae_fp_eq(eps,(double)(0)) ) { state->repterminationtype = -1; return; } if( ae_fp_less(h,(double)(0)) ) { h = -h; } /* * quick exit if necessary. * after this block we assume that M>1 */ if( m==1 ) { state->repnfev = 0; state->repterminationtype = 1; ae_matrix_set_length(&state->ytbl, 1, n, _state); ae_v_move(&state->ytbl.ptr.pp_double[0][0], 1, &y->ptr.p_double[0], 1, ae_v_len(0,n-1)); ae_vector_set_length(&state->xg, m, _state); ae_v_move(&state->xg.ptr.p_double[0], 1, &x->ptr.p_double[0], 1, ae_v_len(0,m-1)); return; } /* * check again: correct order of X[] */ if( ae_fp_eq(x->ptr.p_double[1],x->ptr.p_double[0]) ) { state->repterminationtype = -2; return; } for(i=1; i<=m-1; i++) { if( (ae_fp_greater(x->ptr.p_double[1],x->ptr.p_double[0])&&ae_fp_less_eq(x->ptr.p_double[i],x->ptr.p_double[i-1]))||(ae_fp_less(x->ptr.p_double[1],x->ptr.p_double[0])&&ae_fp_greater_eq(x->ptr.p_double[i],x->ptr.p_double[i-1])) ) { state->repterminationtype = -2; return; } } /* * auto-select H if necessary */ if( ae_fp_eq(h,(double)(0)) ) { v = ae_fabs(x->ptr.p_double[1]-x->ptr.p_double[0], _state); for(i=2; i<=m-1; i++) { v = ae_minreal(v, ae_fabs(x->ptr.p_double[i]-x->ptr.p_double[i-1], _state), _state); } h = 0.001*v; } /* * store parameters */ state->n = n; state->m = m; state->h = h; state->eps = ae_fabs(eps, _state); state->fraceps = ae_fp_less(eps,(double)(0)); ae_vector_set_length(&state->xg, m, _state); ae_v_move(&state->xg.ptr.p_double[0], 1, &x->ptr.p_double[0], 1, ae_v_len(0,m-1)); if( ae_fp_greater(x->ptr.p_double[1],x->ptr.p_double[0]) ) { state->xscale = (double)(1); } else { state->xscale = (double)(-1); ae_v_muld(&state->xg.ptr.p_double[0], 1, ae_v_len(0,m-1), -1); } ae_vector_set_length(&state->yc, n, _state); ae_v_move(&state->yc.ptr.p_double[0], 1, &y->ptr.p_double[0], 1, ae_v_len(0,n-1)); state->solvertype = solvertype; state->repterminationtype = 0; /* * Allocate arrays */ ae_vector_set_length(&state->y, n, _state); ae_vector_set_length(&state->dy, n, _state); } void _odesolverstate_init(void* _p, ae_state *_state, ae_bool make_automatic) { odesolverstate *p = (odesolverstate*)_p; ae_touch_ptr((void*)p); ae_vector_init(&p->yc, 0, DT_REAL, _state, make_automatic); ae_vector_init(&p->escale, 0, DT_REAL, _state, make_automatic); ae_vector_init(&p->xg, 0, DT_REAL, _state, make_automatic); ae_vector_init(&p->y, 0, DT_REAL, _state, make_automatic); ae_vector_init(&p->dy, 0, DT_REAL, _state, make_automatic); ae_matrix_init(&p->ytbl, 0, 0, DT_REAL, _state, make_automatic); ae_vector_init(&p->yn, 0, DT_REAL, _state, make_automatic); ae_vector_init(&p->yns, 0, DT_REAL, _state, make_automatic); ae_vector_init(&p->rka, 0, DT_REAL, _state, make_automatic); ae_vector_init(&p->rkc, 0, DT_REAL, _state, make_automatic); ae_vector_init(&p->rkcs, 0, DT_REAL, _state, make_automatic); ae_matrix_init(&p->rkb, 0, 0, DT_REAL, _state, make_automatic); ae_matrix_init(&p->rkk, 0, 0, DT_REAL, _state, make_automatic); _rcommstate_init(&p->rstate, _state, make_automatic); } void _odesolverstate_init_copy(void* _dst, void* _src, ae_state *_state, ae_bool make_automatic) { odesolverstate *dst = (odesolverstate*)_dst; odesolverstate *src = (odesolverstate*)_src; dst->n = src->n; dst->m = src->m; dst->xscale = src->xscale; dst->h = src->h; dst->eps = src->eps; dst->fraceps = src->fraceps; ae_vector_init_copy(&dst->yc, &src->yc, _state, make_automatic); ae_vector_init_copy(&dst->escale, &src->escale, _state, make_automatic); ae_vector_init_copy(&dst->xg, &src->xg, _state, make_automatic); dst->solvertype = src->solvertype; dst->needdy = src->needdy; dst->x = src->x; ae_vector_init_copy(&dst->y, &src->y, _state, make_automatic); ae_vector_init_copy(&dst->dy, &src->dy, _state, make_automatic); ae_matrix_init_copy(&dst->ytbl, &src->ytbl, _state, make_automatic); dst->repterminationtype = src->repterminationtype; dst->repnfev = src->repnfev; ae_vector_init_copy(&dst->yn, &src->yn, _state, make_automatic); ae_vector_init_copy(&dst->yns, &src->yns, _state, make_automatic); ae_vector_init_copy(&dst->rka, &src->rka, _state, make_automatic); ae_vector_init_copy(&dst->rkc, &src->rkc, _state, make_automatic); ae_vector_init_copy(&dst->rkcs, &src->rkcs, _state, make_automatic); ae_matrix_init_copy(&dst->rkb, &src->rkb, _state, make_automatic); ae_matrix_init_copy(&dst->rkk, &src->rkk, _state, make_automatic); _rcommstate_init_copy(&dst->rstate, &src->rstate, _state, make_automatic); } void _odesolverstate_clear(void* _p) { odesolverstate *p = (odesolverstate*)_p; ae_touch_ptr((void*)p); ae_vector_clear(&p->yc); ae_vector_clear(&p->escale); ae_vector_clear(&p->xg); ae_vector_clear(&p->y); ae_vector_clear(&p->dy); ae_matrix_clear(&p->ytbl); ae_vector_clear(&p->yn); ae_vector_clear(&p->yns); ae_vector_clear(&p->rka); ae_vector_clear(&p->rkc); ae_vector_clear(&p->rkcs); ae_matrix_clear(&p->rkb); ae_matrix_clear(&p->rkk); _rcommstate_clear(&p->rstate); } void _odesolverstate_destroy(void* _p) { odesolverstate *p = (odesolverstate*)_p; ae_touch_ptr((void*)p); ae_vector_destroy(&p->yc); ae_vector_destroy(&p->escale); ae_vector_destroy(&p->xg); ae_vector_destroy(&p->y); ae_vector_destroy(&p->dy); ae_matrix_destroy(&p->ytbl); ae_vector_destroy(&p->yn); ae_vector_destroy(&p->yns); ae_vector_destroy(&p->rka); ae_vector_destroy(&p->rkc); ae_vector_destroy(&p->rkcs); ae_matrix_destroy(&p->rkb); ae_matrix_destroy(&p->rkk); _rcommstate_destroy(&p->rstate); } void _odesolverreport_init(void* _p, ae_state *_state, ae_bool make_automatic) { odesolverreport *p = (odesolverreport*)_p; ae_touch_ptr((void*)p); } void _odesolverreport_init_copy(void* _dst, void* _src, ae_state *_state, ae_bool make_automatic) { odesolverreport *dst = (odesolverreport*)_dst; odesolverreport *src = (odesolverreport*)_src; dst->nfev = src->nfev; dst->terminationtype = src->terminationtype; } void _odesolverreport_clear(void* _p) { odesolverreport *p = (odesolverreport*)_p; ae_touch_ptr((void*)p); } void _odesolverreport_destroy(void* _p) { odesolverreport *p = (odesolverreport*)_p; ae_touch_ptr((void*)p); } #endif }
ed744c5e072519770af5710c6f15b433ccbc50eb
a0dff3815ca1d52bb82d661bb400024830d7f7c7
/cpp/lib/inc/lmt84.h
948542a6be7afe4b1e8396986b35f6d1c83b13b2
[]
no_license
creator83/STM32F030K6
bf90639d281dc7eeb8db08ab4044db9db37e2116
4bc9e20eecf9633b8d70232f928e9e13b7d0c921
refs/heads/master
2020-04-12T02:28:19.329214
2017-08-13T17:42:26
2017-08-13T17:42:26
44,557,917
2
2
null
null
null
null
UTF-8
C++
false
false
301
h
#include "device.h" // Device header #ifndef LMT84_H #define LMT84_H class Lmt84 { //variables public: private: static uint16_t adcGrid [16]; static uint8_t delta [15]; public: Lmt84 (); uint16_t calcDec (uint16_t); uint8_t calc (uint16_t); private: }; #endif
5c026d099792a02ed5eb5d95e0b3a3f871de618d
ac3351c78bde37302fb21d775b179c34ca547c06
/UVA.C - CPP/10219 - Find the ways.cpp
e8a3c59033281bd89ccd513a3b0d2bc0e527d7cc
[]
no_license
sajal-jayanto/Algorithm_ACM_problems
0171e0ca03e6d8b49a15ac742a315fe9aeec54f1
8ce1cfc29686b0d69328718a29b03f9fb1e8f5e9
refs/heads/master
2021-11-23T19:06:58.815679
2021-11-13T17:46:27
2021-11-13T17:46:27
99,267,317
2
1
null
null
null
null
UTF-8
C++
false
false
1,659
cpp
#include <bits/stdc++.h> using namespace std; #define FF freopen("input.txt" , "r" , stdin); #define sf scanf #define pf printf #define fs first #define se second #define pb push_back #define ins insert #define Lb lower_bound #define Up upper_bound #define INF (1<<30) #define mem(a,b) memset(a, b, sizeof(a)) #define MAX 18 #define MAXR 100010 #define MAXC 100010 typedef long long ll; const double PI = 2.0 * acos(0.0); const double eps = 1e-9; template < class T > T Abs(T x) { return x > 0 ? x : -x; } template < class T > string toString(T n) { ostringstream ost; ost << n; ost.flush() ; return ost.str(); } template < class T > inline T gcd(T a,T b) { if(a < 0) return gcd(-a,b); if(b < 0)return gcd(a,-b); return (b == 0) ? a : gcd(b ,a % b); } template < class T > inline T lcm(T a,T b) { if(a < 0) return lcm(-a,b); if(b < 0)return lcm(a,-b); return a * (b / gcd(a , b)); } template < class T > inline T sqr(T n) { return n * n; } template < class T > T power(T n, int p) { if(!p) return 1; else { T sum = sqr( power( n , p >> 1) ); if(p & 1) sum = n; return sum; } } int main() { ios_base::sync_with_stdio(false); cin.tie(false); int n , r , dig; double a , b; while(cin >> n >> r) { a = b = 0.0; for(int i = n - r + 1 ; i <= n ; ++i) a = a + log10(i); for(int i = 1 ; i <= r ; ++i) b = b + log10(i); dig = floor( a - b ) + 1; cout << dig << endl; } return 0; }
b67ebf621d0bd0059fe19a294cb469344bfb32f8
1bd9bf74db6217b12760c14205880cd1f4b124e7
/DSA/Cpp/reverse_integer.cpp
59dd07347b4fc6182adcad8697ef43522437003e
[]
no_license
sanjanaprasad2k01/Hacktober-Fest-2021
5de191e50754cd3f1a28f6dd73861b39b01a0672
19b7b3df79ef22cb6c05b2d54d541e31353e1bab
refs/heads/master
2023-08-12T08:49:36.650356
2021-10-07T14:43:40
2021-10-07T14:43:40
414,641,759
1
0
null
null
null
null
UTF-8
C++
false
false
461
cpp
class Solution { public: int reverse(int x) { long int ans = 0; //taking digits from back 1 by 1 and adding them in answer while(x != 0) { ans = (ans * 10) + (x % 10); x = x/10; } if(ans > INT_MAX || ans < INT_MIN) // to check if there is overflow after the number is reversed { return 0; } return ans; } };
25b42e028b872d7c2019dc32ff6cf5ccd32e1c4f
a7b08b050e8fb73943893719757322295df14f7e
/CsLabAssignment7.cpp
2ec2c3948fe3303ffeff4ed92071e2bf6290c9ee
[]
no_license
BrandonMiramontes/Assignment7
e7293e97c9d8e3d714be4e90b9994b8be9d898aa
b336a9e6396163057270f08b9ff15d95a79e93a5
refs/heads/main
2023-01-01T07:52:55.993855
2020-10-26T04:29:22
2020-10-26T04:29:22
307,260,477
0
0
null
null
null
null
UTF-8
C++
false
false
564
cpp
#include <iostream> using namespace std; int main() { int row1, rowtotal = 4, plus, column; for (row1 = 0; row1 <= rowtotal; row1++) { for (column = rowtotal-row1; column >= 1; column--) { cout << " "; } for (plus = 1; plus <= 2 * row1-1; plus++) { cout << "+"; } cout << endl; } for (row1=rowtotal-1; row1>=1;row1--) { for (column = 1; column <= rowtotal-row1; column++) { cout << " "; } for (plus = 1; plus <= 2 * row1 - 1; plus++) { cout << "+"; } cout << endl; } }
f10a269459389e1f678cd37e5bbb8e10e1d3dc64
73f6151c2d014daefbdeec70ad072b6389a514ec
/windows/runner/main.cpp
59f75c4c9704ac4bda8839845f58d15c54e398be
[]
no_license
keungsong/shop_clone
3c7ed40661fa55d8596f765dc9aca23d13184a28
ad71dfba5134c9042a0b4694647c09d3af30508d
refs/heads/main
2023-07-11T05:47:27.814742
2021-08-23T16:48:49
2021-08-23T16:48:49
375,314,767
0
0
null
null
null
null
UTF-8
C++
false
false
1,220
cpp
#include <flutter/dart_project.h> #include <flutter/flutter_view_controller.h> #include <windows.h> #include "flutter_window.h" #include "run_loop.h" #include "utils.h" int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, _In_ wchar_t *command_line, _In_ int show_command) { // Attach to console when present (e.g., 'flutter run') or create a // new console when running with a debugger. if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) { CreateAndAttachConsole(); } // Initialize COM, so that it is available for use in the library and/or // plugins. ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); RunLoop run_loop; flutter::DartProject project(L"data"); std::vector<std::string> command_line_arguments = GetCommandLineArguments(); project.set_dart_entrypoint_arguments(std::move(command_line_arguments)); FlutterWindow window(&run_loop, project); Win32Window::Point origin(10, 10); Win32Window::Size size(1280, 720); if (!window.CreateAndShow(L"shop_clone", origin, size)) { return EXIT_FAILURE; } window.SetQuitOnClose(true); run_loop.Run(); ::CoUninitialize(); return EXIT_SUCCESS; }
b96fa461e38919929ea71410ed8eea5fb15d74da
59e93f9d820dc5c2731eb2d141601d9e92831414
/xy/include/mpl/equal.hpp
50bfd4d5346b0621dbe50de9b65ba15a55493752
[]
no_license
pgoodman/XY
2ec759b3080871ee5a3e773a81da75fe1f823525
6e661ceb460019770f23084ed94c3c32cbdefa20
refs/heads/master
2020-05-27T17:11:44.116358
2013-09-26T19:27:20
2013-09-26T19:27:20
1,902,085
3
0
null
null
null
null
UTF-8
C++
false
false
2,536
hpp
/* * equal.hpp * * Created on: Jun 28, 2011 * Author: Peter Goodman * * Copyright 2011 Peter Goodman, all rights reserved. */ #ifndef XY_EQUAL_HPP_ #define XY_EQUAL_HPP_ #include "xy/include/mpl/bool.hpp" namespace xy { namespace mpl { template <typename A, typename B> class equal { public: typedef false_tag result; operator bool (void) { return false; } }; template <typename A> class equal<A *, A *> { public: typedef true_tag result; operator bool (void) { return true; } }; template <typename A> class equal<A, A> { public: typedef true_tag result; operator bool (void) { return true; } }; template <typename A, typename B> class equal<A *, B *> : public equal<A, B> { }; template <typename A, typename B> class equal<const A, const B> : public equal<A, B> { }; template <typename A, typename B> class equal<const A, B> : public equal<A, B> { }; template <typename A, typename B> class equal<A, const B> : public equal<A, B> { }; template <typename A, typename B> class const_equal { public: typedef false_tag result; operator bool (void) { return false; } }; template <typename A> class const_equal<A *, A *> { public: typedef true_tag result; operator bool (void) { return true; } }; template <typename A> class const_equal<A, A> { public: typedef true_tag result; operator bool (void) { return true; } }; template <typename A, typename B> class const_equal<A *, B *> : public const_equal<A, B> { }; template <typename A, typename B> class const_equal<const A, const B> : public equal<A, B> { }; template <typename A, typename B> class const_equal<const A, B> { public: typedef false_tag result; operator bool (void) { return false; } }; template <typename A, typename B> class const_equal<A, const B> { public: typedef false_tag result; operator bool (void) { return false; } }; /* template <typename A, typename B> bool equal_p(void) { return equal<A,B>(); } template <typename A, typename B> bool const_equal_p(void) { return const_equal<A,B>(); } */ }} #endif /* XY_EQUAL_HPP_ */
cb2e7ec514a59e468001fdb4b22c0994e517b1d8
85016bd766e6a1f49986aac7b7d686a07d45ff60
/lab5/lab5.cpp
54cc962d102a314fb81d77fd464de9bdf464af58
[]
no_license
UnmovableLibrary/lab5
69d0cb96b881ea7d281a7b6ad22f51b6d71dfb00
b20a7ae584c7ccd4cd3e3b13413103eee80eea19
refs/heads/master
2020-05-09T13:24:19.685651
2015-04-29T21:26:42
2015-04-29T21:26:42
34,717,023
0
0
null
null
null
null
UTF-8
C++
false
false
15,793
cpp
#include <cmath> #include <cstdlib> #include <iostream> #include "tga.h" using namespace std; #ifdef __APPLE__ #include <GLUT/glut.h> /* glut.h includes gl.h and glu.h*/ #else #include <GL/glut.h> /* glut.h includes gl.h and glu.h*/ #endif #define X_AXIS 1 #define Y_AXIS 2 #define Z_AXIS 3 #define STOP 4 #define MAX_TEXTURES 10 // max textures displayed //***************************************************************** // Begin: Global variables about the camera location and orientation //***************************************************************** //Camera on y = 0 plan, circling around (0,0,0) //The following variable records the current angle between the vector (1,0,0) and (eyex, eyey, eyez) double C_angle; const double PI = 3.14156; //Camera on y = 0 plan, circling around (0,0,0) //The following variable records the radius of the camera's orbit double C_Radius; //Camera on y = 0 plan, circling around (0,0,0) //The following variable records the rotation speed of the camera double C_increment; double prev_C_increment; //Camera on y = 0 plan, circling around (0,0,0) //Recording the currnet position of the camera. double eyex, eyey, eyez; //Camera on y = 0 plan, circling around (0,0,0) //Specifies the position of the point looked at double centerx, centery, centerz; //Specifies the direction of the up vector. double upx, upy, upz; char currentAxis; GLuint textureArray[MAX_TEXTURES]; //***************************************************************** // End of Global variables about the camera location and orientation //***************************************************************** void drawAxesXYZ() { //Draw XYZ axes glBegin(GL_LINES); glColor3f(1,0,0); glVertex3f(0,0,0); glVertex3f(15,0,0); glColor3f(0,1,0); glVertex3f(0,0,0); glVertex3f(0,15,0); glColor3f(0,0,1); glVertex3f(0,0,0); glVertex3f(0,0,15); glEnd(); //Show the X, Y, Z letters glColor3f(1,0,0); glRasterPos3f(5, 0, 0); glutBitmapCharacter(GLUT_BITMAP_9_BY_15, 'X'); glColor3f(0, 1, 0); glRasterPos3f(0, 5, 0); glutBitmapCharacter(GLUT_BITMAP_9_BY_15, 'Y'); glColor3f(0, 0, 1); glRasterPos3f(0, 0, 5); glutBitmapCharacter(GLUT_BITMAP_9_BY_15, 'Z'); } void init() { glHint(GL_PERSPECTIVE_CORRECTION_HINT,GL_NICEST); glShadeModel(GL_SMOOTH); glEnable(GL_DEPTH_TEST); float scale = 30.0; /* set clear color to black */ glClearColor (0.0, 0.0, 0.0, 0.0); /* set fill color to white */ glColor3f(1.0, 1.0, 1.0); /* set up standard orthogonal view with clipping */ glMatrixMode (GL_PROJECTION); glLoadIdentity (); //glOrtho(-scale, scale, -scale, scale, 0.1, 5*scale); gluPerspective(90, 1, 0.1, 100); //setup all textures glEnable(GL_TEXTURE_2D); CreateTexture(textureArray,"concrete2.tga",0); CreateTexture(textureArray,"bricks.tga",1); CreateTexture(textureArray,"sky.tga",2); CreateTexture(textureArray,"grass.tga",3); } void initCameraSetting() { //The following variable records the current angle between the vector (1,0,0) and (eyex, eyey, eyez) C_angle = 0; //Camera on y = 0 plan, circling around (0,0,0) //The following variable records the radius of the camera's orbit C_Radius = 13; //Camera on y = 0 plan, circling around (0,0,0) //The following variable records the rotation speed of the camera C_increment = (2*PI / (360*2) ); //Recording the current position of the camera. eyex = 0; eyey = 0; eyez = C_Radius;//C_Radius; //Specifies the position of the point looked at as (0,0,0). centerx = 0; centery = 0; centerz=0; //Specifies the direction of the up vector. upx = 0; upy=1; upz=0; //glMatrixMode(GL_MODELVIEW); //glLoadIdentity(); //gluLookAt(eyex, eyey, eyez, centerx, centery, centerz, upx, upy, upz); //glMatrixMode (GL_PROJECTION); //specify which axis we are rotating around currentAxis = 'y'; } void moveCamera() { //Camera on y = 0 plan, circling around (0,0,0) //The following variable records the current angle between the vector (1,0,0) and (eyex, eyey, eyez) C_angle += C_increment; if ( C_angle > 2*PI) C_angle -= 2*PI; if (currentAxis == 'y') //checks what axis we are currently want to be orbiting around { eyex = C_Radius * cos(C_angle); eyey = 0; eyez = C_Radius * sin(C_angle); } else if (currentAxis == 'x') //checks what axis we are currently want to be orbiting around { eyex=0; eyey=C_Radius*cos(C_angle); eyez=C_Radius*sin(C_angle); upx=0; upy=cos(C_angle+PI/2); upz=sin(C_angle+PI/2); } else if (currentAxis == 'z') //checks what axis we are currently want to be orbiting around { eyex=C_Radius*cos(C_angle); eyey=C_Radius*sin(C_angle); eyez=0; upx=cos(C_angle+PI/2);; upy=sin(C_angle+PI/2); upz=0; } glutPostRedisplay(); } void keyboard (unsigned char key, int x, int y) { switch (key) { case 'j': //increase the rotational speed C_increment+= 0.0005; glutPostRedisplay(); break; case 'k': //decrease the rotational speed if (C_increment <= 0.0005) C_increment = 0.0; else C_increment-= 0.0005; glutPostRedisplay(); break; case 'i': //increase the radius of orbit of the rotating camera C_Radius++; glutPostRedisplay(); break; case 'm': //decrease the radius of orbit of the rotating camera C_Radius--; glutPostRedisplay(); break; case 'x': //rotate around the x axis currentAxis = 'x'; glutPostRedisplay(); break; case 'y': //rotate around the y axis currentAxis = 'y'; upx = 0; upy=1; upz=0; glutPostRedisplay(); break; case 'z': //rotate around the z axis currentAxis = 'z'; glutPostRedisplay(); break; default: break; } } //***************************************************** //A global GLUquadricObj object dynamically allocated // for drawing GLU guadric objects in display() //***************************************************** GLUquadricObj * ptrToQuadricInfo; GLUquadric * ptrToGLUquadricInfo; //*************************************************************** //OpenGL commands to regenerate the scene saved in two functions: // display() and reshape( int w, int h) //*************************************************************** void reshape(int w, int h) { float left = -5.2; float right = 5.2; float bottom = -5.2; float top = 5.2; float near = 0.1; float far = 50; glMatrixMode(GL_PROJECTION); glLoadIdentity(); if (w >= h) glOrtho( left * ( float(w)/ float(h)), right * ( float(w)/ float(h)), bottom, top, near, far ); else glOrtho( left , right , bottom*( float(h)/ float(w)), top* ( float(h)/ float(w)), near, far ); glMatrixMode(GL_MODELVIEW); } void createBell() { //sphere for the top of the bell glPushMatrix(); glColor3f(0.65,0.75,0.70); //color it glutSolidSphere(.5, 200, 50); glPopMatrix(); //cone for the bottom of the bell glPushMatrix(); glTranslatef(0.0, -0.5, 0.0); //move it glRotatef(-90, 1.0, 0.0, 0.0); //rotate it glutSolidCone(.65, 1, 75, 4); glPopMatrix(); //sphere for the ball at the bottom of the bell glPushMatrix(); glColor3f(0.65,0.75,0.70); //color it glTranslatef(0.15, -0.60, 0.0); //move it glutSolidSphere(.13, 100, 30); glPopMatrix(); //the part at the top of the bell that connects it to the columns glPushMatrix(); glColor3f(1,0.3,0.45); //color it glTranslatef(0.0, 0.70, 0.0); //move it glScalef(0.70,2,0.70); //scale it glutSolidCube(.25); glPopMatrix(); } void createBase() { glColor3f(1,0.5,0.5); glBindTexture(GL_TEXTURE_2D, textureArray[1]); glBegin(GL_QUADS); glTexCoord2f(1, 1); glVertex3f(-.5, .25, 0.5); glTexCoord2f(0, 1); glVertex3f(-.5, .25, -0.5); glTexCoord2f(0, 0); glVertex3f(-.5, -.25, -0.5); glTexCoord2f(1, 0); glVertex3f(-.5, -.25, 0.5); glEnd(); glBegin(GL_QUADS); glTexCoord2f(1, 1); glVertex3f(.5, .25, 0.5); glTexCoord2f(0, 1); glVertex3f(.5, .25, -0.5); glTexCoord2f(0, 0); glVertex3f(.5, -.25, -0.5); glTexCoord2f(1, 0); glVertex3f(.5, -.25, 0.5); glEnd(); glBegin(GL_QUADS); glTexCoord2f(1, 1); glVertex3f(.5, .25, 0.5); glTexCoord2f(1, 0); glVertex3f(.5, -.25, 0.5); glTexCoord2f(0, 0); glVertex3f(-.5, -.25, 0.5); glTexCoord2f(0, 1); glVertex3f(-.5, .25, 0.5); glEnd(); glBegin(GL_QUADS); glTexCoord2f(1, 1); glVertex3f(.5, .25, -0.5); glTexCoord2f(1, 0); glVertex3f(.5, -.25, -0.5); glTexCoord2f(0, 0); glVertex3f(-.5, -.25, -0.5); glTexCoord2f(0, 1); glVertex3f(-.5, .25, -0.5); glEnd(); } void createGrass() { glBindTexture(GL_TEXTURE_2D, textureArray[3]); glColor3f(1,1,1); glBegin(GL_QUADS); glTexCoord2f(0, 0); glVertex3f(-0.425, 0.270, 0.425); glTexCoord2f(0, 1.0); glVertex3f(-0.425, 0.270, -0.425); glTexCoord2f(1.0, 1.0); glVertex3f(0.425, 0.270, -0.425); glTexCoord2f(1.0, 0); glVertex3f(0.425, 0.270, 0.425); glEnd(); } void createSky() { glBindTexture(GL_TEXTURE_2D, textureArray[2]); glColor3f(1,1,1); glBegin(GL_QUADS); glTexCoord2f(0, 0); glVertex3f(-20, 20, 20); glTexCoord2f(0, 1.0); glVertex3f(-20, 20, -20); glTexCoord2f(1.0, 1.0); glVertex3f(20, 20, -20); glTexCoord2f(1.0, 0); glVertex3f(20, 20, 20); glEnd(); glBegin(GL_QUADS); glTexCoord2f(0, 0); glVertex3f(-20, 20, 20); glTexCoord2f(0, 1.0); glVertex3f(-20, -.27, 20); glTexCoord2f(1.0, 1.0); glVertex3f(20, -.27, 20); glTexCoord2f(1.0, 0); glVertex3f(20, 20, 20); glEnd(); glBegin(GL_QUADS); glTexCoord2f(0, 0); glVertex3f(-20, 20, -20); glTexCoord2f(0, 1.0); glVertex3f(-20, -.27, -20); glTexCoord2f(1.0, 1.0); glVertex3f(20, -.27, -20); glTexCoord2f(1.0, 0); glVertex3f(20, 20, -20); glEnd(); glBegin(GL_QUADS); glTexCoord2f(0, 0); glVertex3f(-20, 20, -20); glTexCoord2f(0, 1.0); glVertex3f(-20, -.27, -20); glTexCoord2f(1.0, 1.0); glVertex3f(-20, -.27, 20); glTexCoord2f(1.0, 0); glVertex3f(-20, 20, 20); glEnd(); glBegin(GL_QUADS); glTexCoord2f(0, 0); glVertex3f(20, 20, -20); glTexCoord2f(0, 1.0); glVertex3f(20, -.27, -20); glTexCoord2f(1.0, 1.0); glVertex3f(20, -.27, 20); glTexCoord2f(1.0, 0); glVertex3f(20, 20, 20); glEnd(); } void display() { ////Select the ModelView matrix glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt ( eyex, eyey, eyez, centerx, centery, centerz, upx, upy, upz); //View the object through the camera settings glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glBindTexture(GL_TEXTURE_2D, textureArray[0]); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_REPEAT); glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_REPEAT); //glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST); glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST); glColor3f(1,1,1); glBegin(GL_QUADS); glTexCoord2f(-7.0, -7.0); glVertex3f(-20, -.27, 20); glTexCoord2f(-7.0, 1.0); glVertex3f(-20, -.27, -20); glTexCoord2f(1.0, 1.0); glVertex3f(20, -.27, -20); glTexCoord2f(1.0, -7.0); glVertex3f(20, -.27, 20); glEnd(); //base one glPushMatrix(); glTranslatef(0, 0, -2); //move it createBase(); glPopMatrix(); //base one grass glPushMatrix(); glColor3f(0.0,1,0.0); //color it glScalef(0.85,0.60,0.85); //scale it glTranslatef(0, 0.10, -2.35); //move it glutSolidCube(1); glPopMatrix(); //base two glPushMatrix(); glTranslatef(-2, 0, 2); //move it createBase(); glPopMatrix(); //base two grass glPushMatrix(); glColor3f(0,1,0); //color it glScalef(0.85,0.60,0.85); //scale it glTranslatef(-2.35, 0.10, 2.35); //move it glutSolidCube(1); glPopMatrix(); //base three glPushMatrix(); glTranslatef(4, 0, 0); //move it createBase(); glPopMatrix(); //base three grass glPushMatrix(); glColor3f(0,1,0); //color it glScalef(0.85,0.60,0.85); //scale it glTranslatef(4.75, 0.10, 0.0); //move it glutSolidCube(1); glPopMatrix(); //tallest column glPushMatrix(); glColor3f(1,0.3,0.45); //color it glTranslatef(1.85, 3.75, 0); //move it glRotatef(32, 0.0, 0.0, 1.0); //rotate it glScalef(0.4,9.25,0.4); //scale it glutSolidCube(1); glPopMatrix(); //2nd tallest column glPushMatrix(); glColor3f(1,0.3,0.45); //color it glTranslatef(0, 3.25, -0.95); //move it glRotatef(16, 1.0, 0.0, 0.0); //rotate it glScalef(0.4,7,0.4); //scale it glutSolidCube(1); glPopMatrix(); //shortest column glPushMatrix(); glColor3f(1,0.3,0.45); //color it glTranslatef(-1, 2.25, 0.75); //move it glRotatef(-30, 1.0, 0.0, 0.0); //rotate it glRotatef(-20, 0.0, 0.0, 1.0); //rotate it glScalef(0.4,5.75,0.4); //scale it glutSolidCube(1); glPopMatrix(); //first bell glPushMatrix(); glScalef(0.85,0.85,0.85); //scale it glTranslatef(0.65, 5.60, 0); //move it createBell(); glPopMatrix(); //second bell glPushMatrix(); glScalef(0.70,0.70,0.70); //scale it glTranslatef(2, 5, 0); //move it createBell(); glPopMatrix(); //third bell glPushMatrix(); glScalef(0.60,0.60,0.60); //scale it glTranslatef(3.65, 3.90, 0); //move it createBell(); glPopMatrix(); //fourth bell glPushMatrix(); glScalef(0.45,0.45,0.45); //scale it glTranslatef(6.25, 3.20, 0); //move it createBell(); glPopMatrix(); //fifth bell glPushMatrix(); glTranslatef(-0.50, 2.30, 0); //move it createBell(); glPopMatrix(); createSky(); // grass textures glPushMatrix(); glTranslatef(0, 0.10, -2); //move it createGrass(); glPopMatrix(); glPushMatrix(); glTranslatef(-2, 0.10, 2); createGrass(); glPopMatrix(); glPushMatrix(); glTranslatef(4., 0.10, 0.0); //move it createGrass(); glPopMatrix(); drawAxesXYZ(); glutSwapBuffers(); } //************End of display function ***************** void menuEventHandler(int option) { switch (option) { //rotate around the x axis case X_AXIS : currentAxis = 'x'; if (C_increment == 0) //if the the camera is in "STOP" mode, unfreeze it C_increment = prev_C_increment; glutPostRedisplay(); break; //rotate around the y axis case Y_AXIS : currentAxis = 'y'; upx = 0; upy=1; upz=0; if (C_increment == 0) //if the the camera is in "STOP" mode, unfreeze it C_increment = prev_C_increment; glutPostRedisplay(); break; //rotate around the z axis case Z_AXIS : currentAxis = 'z'; if (C_increment == 0) //if the the camera is in "STOP" mode, unfreeze it C_increment = prev_C_increment; glutPostRedisplay(); break; //stop rotating case STOP : prev_C_increment = C_increment; C_increment = 0; break; } } void createGlutMenu() { int menu; menu = glutCreateMenu(menuEventHandler); //create a menu that looks to menuEventHandler to process the events //adds entries to the menu where the user will see the label that is in quotations glutAddMenuEntry("X Axis", X_AXIS); glutAddMenuEntry("Y Axis", Y_AXIS); glutAddMenuEntry("Z Axis", Z_AXIS); glutAddMenuEntry("Stop", STOP); glutAttachMenu(GLUT_RIGHT_BUTTON); //attaches the menu to the right button } int main(int argc, char** argv) { /* Initialize mode and open a window in upper left corner of screen */ glutInit(&argc, argv); glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGB); glutInitWindowSize (500, 500); glutInitWindowPosition (0, 0); glutCreateWindow("my scene"); glutDisplayFunc(display); glutIdleFunc(moveCamera); glutKeyboardFunc(keyboard); createGlutMenu(); ptrToQuadricInfo = gluNewQuadric(); ptrToGLUquadricInfo = gluNewQuadric(); init(); initCameraSetting(); glutMainLoop(); }
92ff6be24c45bcb0d12dab8811a0f6939b79cb44
c8496fcb2f12a32ff9b26aef021970a43213b3ff
/src/Joystick.h
b23fd428e0a13fed8ac6fa785d9b97b4dad7636f
[]
no_license
harsha7addanki/Joystick
d2dd8d0813b60045ce2dec7ec13bddcc43164bba
064fea7df3b789c87208e00636f195ac3eef2ca7
refs/heads/master
2022-11-17T06:04:40.824954
2020-07-04T20:01:23
2020-07-04T20:01:23
267,725,400
0
0
null
null
null
null
UTF-8
C++
false
false
455
h
#ifndef Joystick_h #define Joystick_h #include "Arduino.h" class Joystick { private: int SW; int VRx; int VRy; public: Joystick::Joystick(int SW2,int VRx2,int VRy2); int Joystick::GetX(); int Joystick::GetY(); int Joystick::GetBtn(); bool Joystick::ChangeXPin(int NewXPin); bool Joystick::ChangeYPin(int NewYPin); bool Joystick::ChangeSwPin(int NewSwPin); }; #endif
3374174539b94701c52e929a763476a57ecb3e16
c7043376d6aeca846bd9a43068cb929920d9cffc
/Modules/Core/Misc/xxhash.c
13669b2a4d9f0c7d72f47ca6e5fad2ab34589286
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
GameTechDev/CMAA2
c83537c31dc7d9a410bdbe40e86acc95ef689e1c
071c6b0857559f4e36f614362e6d2aab1b61938a
refs/heads/master
2023-03-31T06:23:40.810815
2023-01-03T22:53:15
2023-01-03T22:53:15
147,182,374
122
25
Apache-2.0
2019-11-22T00:33:19
2018-09-03T09:28:37
C++
UTF-8
C++
false
false
34,635
c
/* * xxHash - Fast Hash algorithm * Copyright (C) 2012-2016, Yann Collet * * BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) * * 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. * * You can contact the author at : * - xxHash homepage: http://www.xxhash.com * - xxHash source repository : https://github.com/Cyan4973/xxHash */ /* ************************************* * Tuning parameters ***************************************/ /*!XXH_FORCE_MEMORY_ACCESS : * By default, access to unaligned memory is controlled by `memcpy()`, which is safe and portable. * Unfortunately, on some target/compiler combinations, the generated assembly is sub-optimal. * The below switch allow to select different access method for improved performance. * Method 0 (default) : use `memcpy()`. Safe and portable. * Method 1 : `__packed` statement. It depends on compiler extension (ie, not portable). * This method is safe if your compiler supports it, and *generally* as fast or faster than `memcpy`. * Method 2 : direct access. This method doesn't depend on compiler but violate C standard. * It can generate buggy code on targets which do not support unaligned memory accesses. * But in some circumstances, it's the only known way to get the most performance (ie GCC + ARMv6) * See http://stackoverflow.com/a/32095106/646947 for details. * Prefer these methods in priority order (0 > 1 > 2) */ #ifndef XXH_FORCE_MEMORY_ACCESS /* can be defined externally, on command line for example */ # if defined(__GNUC__) && ( defined(__ARM_ARCH_6__) || defined(__ARM_ARCH_6J__) \ || defined(__ARM_ARCH_6K__) || defined(__ARM_ARCH_6Z__) \ || defined(__ARM_ARCH_6ZK__) || defined(__ARM_ARCH_6T2__) ) # define XXH_FORCE_MEMORY_ACCESS 2 # elif (defined(__INTEL_COMPILER) && !defined(_WIN32)) || \ (defined(__GNUC__) && ( defined(__ARM_ARCH_7__) || defined(__ARM_ARCH_7A__) \ || defined(__ARM_ARCH_7R__) || defined(__ARM_ARCH_7M__) \ || defined(__ARM_ARCH_7S__) )) # define XXH_FORCE_MEMORY_ACCESS 1 # endif #endif /*!XXH_ACCEPT_NULL_INPUT_POINTER : * If input pointer is NULL, xxHash default behavior is to dereference it, triggering a segfault. * When this macro is enabled, xxHash actively checks input for null pointer. * It it is, result for null input pointers is the same as a null-length input. */ #ifndef XXH_ACCEPT_NULL_INPUT_POINTER /* can be defined externally */ # define XXH_ACCEPT_NULL_INPUT_POINTER 0 #endif /*!XXH_FORCE_NATIVE_FORMAT : * By default, xxHash library provides endian-independent Hash values, based on little-endian convention. * Results are therefore identical for little-endian and big-endian CPU. * This comes at a performance cost for big-endian CPU, since some swapping is required to emulate little-endian format. * Should endian-independence be of no importance for your application, you may set the #define below to 1, * to improve speed for Big-endian CPU. * This option has no impact on Little_Endian CPU. */ #ifndef XXH_FORCE_NATIVE_FORMAT /* can be defined externally */ # define XXH_FORCE_NATIVE_FORMAT 0 #endif /*!XXH_FORCE_ALIGN_CHECK : * This is a minor performance trick, only useful with lots of very small keys. * It means : check for aligned/unaligned input. * The check costs one initial branch per hash; * set it to 0 when the input is guaranteed to be aligned, * or when alignment doesn't matter for performance. */ #ifndef XXH_FORCE_ALIGN_CHECK /* can be defined externally */ # if defined(__i386) || defined(_M_IX86) || defined(__x86_64__) || defined(_M_X64) # define XXH_FORCE_ALIGN_CHECK 0 # else # define XXH_FORCE_ALIGN_CHECK 1 # endif #endif /* ************************************* * Includes & Memory related functions ***************************************/ /*! Modify the local functions below should you wish to use some other memory routines * for malloc(), free() */ #include <stdlib.h> static void* XXH_malloc(size_t s) { return malloc(s); } static void XXH_free (void* p) { free(p); } /*! and for memcpy() */ #include <string.h> static void* XXH_memcpy(void* dest, const void* src, size_t size) { return memcpy(dest,src,size); } #include <assert.h> /* assert */ #define XXH_STATIC_LINKING_ONLY #include "xxhash.h" /* ************************************* * Compiler Specific Options ***************************************/ #ifdef _MSC_VER /* Visual Studio */ # pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */ # define FORCE_INLINE static __forceinline #else # if defined (__cplusplus) || defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 */ # ifdef __GNUC__ # define FORCE_INLINE static inline __attribute__((always_inline)) # else # define FORCE_INLINE static inline # endif # else # define FORCE_INLINE static # endif /* __STDC_VERSION__ */ #endif /* ************************************* * Basic Types ***************************************/ #ifndef MEM_MODULE # if !defined (__VMS) \ && (defined (__cplusplus) \ || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) ) # include <stdint.h> typedef uint8_t BYTE; typedef uint16_t U16; typedef uint32_t U32; # else typedef unsigned char BYTE; typedef unsigned short U16; typedef unsigned int U32; # endif #endif #if (defined(XXH_FORCE_MEMORY_ACCESS) && (XXH_FORCE_MEMORY_ACCESS==2)) /* Force direct memory access. Only works on CPU which support unaligned memory access in hardware */ static U32 XXH_read32(const void* memPtr) { return *(const U32*) memPtr; } #elif (defined(XXH_FORCE_MEMORY_ACCESS) && (XXH_FORCE_MEMORY_ACCESS==1)) /* __pack instructions are safer, but compiler specific, hence potentially problematic for some compilers */ /* currently only defined for gcc and icc */ typedef union { U32 u32; } __attribute__((packed)) unalign; static U32 XXH_read32(const void* ptr) { return ((const unalign*)ptr)->u32; } #else /* portable and safe solution. Generally efficient. * see : http://stackoverflow.com/a/32095106/646947 */ static U32 XXH_read32(const void* memPtr) { U32 val; memcpy(&val, memPtr, sizeof(val)); return val; } #endif /* XXH_FORCE_DIRECT_MEMORY_ACCESS */ /* **************************************** * Compiler-specific Functions and Macros ******************************************/ #define XXH_GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__) /* Note : although _rotl exists for minGW (GCC under windows), performance seems poor */ #if defined(_MSC_VER) # define XXH_rotl32(x,r) _rotl(x,r) # define XXH_rotl64(x,r) _rotl64(x,r) #else # define XXH_rotl32(x,r) ((x << r) | (x >> (32 - r))) # define XXH_rotl64(x,r) ((x << r) | (x >> (64 - r))) #endif #if defined(_MSC_VER) /* Visual Studio */ # define XXH_swap32 _byteswap_ulong #elif XXH_GCC_VERSION >= 403 # define XXH_swap32 __builtin_bswap32 #else static U32 XXH_swap32 (U32 x) { return ((x << 24) & 0xff000000 ) | ((x << 8) & 0x00ff0000 ) | ((x >> 8) & 0x0000ff00 ) | ((x >> 24) & 0x000000ff ); } #endif /* ************************************* * Architecture Macros ***************************************/ typedef enum { XXH_bigEndian=0, XXH_littleEndian=1 } XXH_endianess; /* XXH_CPU_LITTLE_ENDIAN can be defined externally, for example on the compiler command line */ #ifndef XXH_CPU_LITTLE_ENDIAN static int XXH_isLittleEndian(void) { const union { U32 u; BYTE c[4]; } one = { 1 }; /* don't use static : performance detrimental */ return one.c[0]; } # define XXH_CPU_LITTLE_ENDIAN XXH_isLittleEndian() #endif /* *************************** * Memory reads *****************************/ typedef enum { XXH_aligned, XXH_unaligned } XXH_alignment; FORCE_INLINE U32 XXH_readLE32_align(const void* ptr, XXH_endianess endian, XXH_alignment align) { if (align==XXH_unaligned) return endian==XXH_littleEndian ? XXH_read32(ptr) : XXH_swap32(XXH_read32(ptr)); else return endian==XXH_littleEndian ? *(const U32*)ptr : XXH_swap32(*(const U32*)ptr); } FORCE_INLINE U32 XXH_readLE32(const void* ptr, XXH_endianess endian) { return XXH_readLE32_align(ptr, endian, XXH_unaligned); } static U32 XXH_readBE32(const void* ptr) { return XXH_CPU_LITTLE_ENDIAN ? XXH_swap32(XXH_read32(ptr)) : XXH_read32(ptr); } /* ************************************* * Macros ***************************************/ #define XXH_STATIC_ASSERT(c) { enum { XXH_sa = 1/(int)(!!(c)) }; } /* use after variable declarations */ XXH_PUBLIC_API unsigned XXH_versionNumber (void) { return XXH_VERSION_NUMBER; } /* ******************************************************************* * 32-bit hash functions *********************************************************************/ static const U32 PRIME32_1 = 2654435761U; /* 0b10011110001101110111100110110001 */ static const U32 PRIME32_2 = 2246822519U; /* 0b10000101111010111100101001110111 */ static const U32 PRIME32_3 = 3266489917U; /* 0b11000010101100101010111000111101 */ static const U32 PRIME32_4 = 668265263U; /* 0b00100111110101001110101100101111 */ static const U32 PRIME32_5 = 374761393U; /* 0b00010110010101100110011110110001 */ static U32 XXH32_round(U32 seed, U32 input) { seed += input * PRIME32_2; seed = XXH_rotl32(seed, 13); seed *= PRIME32_1; return seed; } /* mix all bits */ static U32 XXH32_avalanche(U32 h32) { h32 ^= h32 >> 15; h32 *= PRIME32_2; h32 ^= h32 >> 13; h32 *= PRIME32_3; h32 ^= h32 >> 16; return(h32); } #define XXH_get32bits(p) XXH_readLE32_align(p, endian, align) static U32 XXH32_finalize(U32 h32, const void* ptr, size_t len, XXH_endianess endian, XXH_alignment align) { const BYTE* p = (const BYTE*)ptr; #define PROCESS1 \ h32 += (*p++) * PRIME32_5; \ h32 = XXH_rotl32(h32, 11) * PRIME32_1 ; #define PROCESS4 \ h32 += XXH_get32bits(p) * PRIME32_3; \ p+=4; \ h32 = XXH_rotl32(h32, 17) * PRIME32_4 ; switch(len&15) /* or switch(bEnd - p) */ { case 12: PROCESS4; /* fallthrough */ case 8: PROCESS4; /* fallthrough */ case 4: PROCESS4; return XXH32_avalanche(h32); case 13: PROCESS4; /* fallthrough */ case 9: PROCESS4; /* fallthrough */ case 5: PROCESS4; PROCESS1; return XXH32_avalanche(h32); case 14: PROCESS4; /* fallthrough */ case 10: PROCESS4; /* fallthrough */ case 6: PROCESS4; PROCESS1; PROCESS1; return XXH32_avalanche(h32); case 15: PROCESS4; /* fallthrough */ case 11: PROCESS4; /* fallthrough */ case 7: PROCESS4; /* fallthrough */ case 3: PROCESS1; /* fallthrough */ case 2: PROCESS1; /* fallthrough */ case 1: PROCESS1; /* fallthrough */ case 0: return XXH32_avalanche(h32); } assert(0); return h32; /* reaching this point is deemed impossible */ } FORCE_INLINE U32 XXH32_endian_align(const void* input, size_t len, U32 seed, XXH_endianess endian, XXH_alignment align) { const BYTE* p = (const BYTE*)input; const BYTE* bEnd = p + len; U32 h32; #if defined(XXH_ACCEPT_NULL_INPUT_POINTER) && (XXH_ACCEPT_NULL_INPUT_POINTER>=1) if (p==NULL) { len=0; bEnd=p=(const BYTE*)(size_t)16; } #endif if (len>=16) { const BYTE* const limit = bEnd - 15; U32 v1 = seed + PRIME32_1 + PRIME32_2; U32 v2 = seed + PRIME32_2; U32 v3 = seed + 0; U32 v4 = seed - PRIME32_1; do { v1 = XXH32_round(v1, XXH_get32bits(p)); p+=4; v2 = XXH32_round(v2, XXH_get32bits(p)); p+=4; v3 = XXH32_round(v3, XXH_get32bits(p)); p+=4; v4 = XXH32_round(v4, XXH_get32bits(p)); p+=4; } while (p < limit); h32 = XXH_rotl32(v1, 1) + XXH_rotl32(v2, 7) + XXH_rotl32(v3, 12) + XXH_rotl32(v4, 18); } else { h32 = seed + PRIME32_5; } h32 += (U32)len; return XXH32_finalize(h32, p, len&15, endian, align); } XXH_PUBLIC_API unsigned int XXH32 (const void* input, size_t len, unsigned int seed) { #if 0 /* Simple version, good for code maintenance, but unfortunately slow for small inputs */ XXH32_state_t state; XXH32_reset(&state, seed); XXH32_update(&state, input, len); return XXH32_digest(&state); #else XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN; if (XXH_FORCE_ALIGN_CHECK) { if ((((size_t)input) & 3) == 0) { /* Input is 4-bytes aligned, leverage the speed benefit */ if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT) return XXH32_endian_align(input, len, seed, XXH_littleEndian, XXH_aligned); else return XXH32_endian_align(input, len, seed, XXH_bigEndian, XXH_aligned); } } if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT) return XXH32_endian_align(input, len, seed, XXH_littleEndian, XXH_unaligned); else return XXH32_endian_align(input, len, seed, XXH_bigEndian, XXH_unaligned); #endif } /*====== Hash streaming ======*/ XXH_PUBLIC_API XXH32_state_t* XXH32_createState(void) { return (XXH32_state_t*)XXH_malloc(sizeof(XXH32_state_t)); } XXH_PUBLIC_API XXH_errorcode XXH32_freeState(XXH32_state_t* statePtr) { XXH_free(statePtr); return XXH_OK; } XXH_PUBLIC_API void XXH32_copyState(XXH32_state_t* dstState, const XXH32_state_t* srcState) { memcpy(dstState, srcState, sizeof(*dstState)); } XXH_PUBLIC_API XXH_errorcode XXH32_reset(XXH32_state_t* statePtr, unsigned int seed) { XXH32_state_t state; /* using a local state to memcpy() in order to avoid strict-aliasing warnings */ memset(&state, 0, sizeof(state)); state.v1 = seed + PRIME32_1 + PRIME32_2; state.v2 = seed + PRIME32_2; state.v3 = seed + 0; state.v4 = seed - PRIME32_1; /* do not write into reserved, planned to be removed in a future version */ memcpy(statePtr, &state, sizeof(state) - sizeof(state.reserved)); return XXH_OK; } FORCE_INLINE XXH_errorcode XXH32_update_endian(XXH32_state_t* state, const void* input, size_t len, XXH_endianess endian) { if (input==NULL) #if defined(XXH_ACCEPT_NULL_INPUT_POINTER) && (XXH_ACCEPT_NULL_INPUT_POINTER>=1) return XXH_OK; #else return XXH_ERROR; #endif { const BYTE* p = (const BYTE*)input; const BYTE* const bEnd = p + len; state->total_len_32 += (unsigned)len; state->large_len |= (len>=16) | (state->total_len_32>=16); if (state->memsize + len < 16) { /* fill in tmp buffer */ XXH_memcpy((BYTE*)(state->mem32) + state->memsize, input, len); state->memsize += (unsigned)len; return XXH_OK; } if (state->memsize) { /* some data left from previous update */ XXH_memcpy((BYTE*)(state->mem32) + state->memsize, input, 16-state->memsize); { const U32* p32 = state->mem32; state->v1 = XXH32_round(state->v1, XXH_readLE32(p32, endian)); p32++; state->v2 = XXH32_round(state->v2, XXH_readLE32(p32, endian)); p32++; state->v3 = XXH32_round(state->v3, XXH_readLE32(p32, endian)); p32++; state->v4 = XXH32_round(state->v4, XXH_readLE32(p32, endian)); } p += 16-state->memsize; state->memsize = 0; } if (p <= bEnd-16) { const BYTE* const limit = bEnd - 16; U32 v1 = state->v1; U32 v2 = state->v2; U32 v3 = state->v3; U32 v4 = state->v4; do { v1 = XXH32_round(v1, XXH_readLE32(p, endian)); p+=4; v2 = XXH32_round(v2, XXH_readLE32(p, endian)); p+=4; v3 = XXH32_round(v3, XXH_readLE32(p, endian)); p+=4; v4 = XXH32_round(v4, XXH_readLE32(p, endian)); p+=4; } while (p<=limit); state->v1 = v1; state->v2 = v2; state->v3 = v3; state->v4 = v4; } if (p < bEnd) { XXH_memcpy(state->mem32, p, (size_t)(bEnd-p)); state->memsize = (unsigned)(bEnd-p); } } return XXH_OK; } XXH_PUBLIC_API XXH_errorcode XXH32_update (XXH32_state_t* state_in, const void* input, size_t len) { XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN; if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT) return XXH32_update_endian(state_in, input, len, XXH_littleEndian); else return XXH32_update_endian(state_in, input, len, XXH_bigEndian); } FORCE_INLINE U32 XXH32_digest_endian (const XXH32_state_t* state, XXH_endianess endian) { U32 h32; if (state->large_len) { h32 = XXH_rotl32(state->v1, 1) + XXH_rotl32(state->v2, 7) + XXH_rotl32(state->v3, 12) + XXH_rotl32(state->v4, 18); } else { h32 = state->v3 /* == seed */ + PRIME32_5; } h32 += state->total_len_32; return XXH32_finalize(h32, state->mem32, state->memsize, endian, XXH_aligned); } XXH_PUBLIC_API unsigned int XXH32_digest (const XXH32_state_t* state_in) { XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN; if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT) return XXH32_digest_endian(state_in, XXH_littleEndian); else return XXH32_digest_endian(state_in, XXH_bigEndian); } /*====== Canonical representation ======*/ /*! Default XXH result types are basic unsigned 32 and 64 bits. * The canonical representation follows human-readable write convention, aka big-endian (large digits first). * These functions allow transformation of hash result into and from its canonical format. * This way, hash values can be written into a file or buffer, remaining comparable across different systems. */ XXH_PUBLIC_API void XXH32_canonicalFromHash(XXH32_canonical_t* dst, XXH32_hash_t hash) { XXH_STATIC_ASSERT(sizeof(XXH32_canonical_t) == sizeof(XXH32_hash_t)); if (XXH_CPU_LITTLE_ENDIAN) hash = XXH_swap32(hash); memcpy(dst, &hash, sizeof(*dst)); } XXH_PUBLIC_API XXH32_hash_t XXH32_hashFromCanonical(const XXH32_canonical_t* src) { return XXH_readBE32(src); } #ifndef XXH_NO_LONG_LONG /* ******************************************************************* * 64-bit hash functions *********************************************************************/ /*====== Memory access ======*/ #ifndef MEM_MODULE # define MEM_MODULE # if !defined (__VMS) \ && (defined (__cplusplus) \ || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) ) # include <stdint.h> typedef uint64_t U64; # else /* if compiler doesn't support unsigned long long, replace by another 64-bit type */ typedef unsigned long long U64; # endif #endif #if (defined(XXH_FORCE_MEMORY_ACCESS) && (XXH_FORCE_MEMORY_ACCESS==2)) /* Force direct memory access. Only works on CPU which support unaligned memory access in hardware */ static U64 XXH_read64(const void* memPtr) { return *(const U64*) memPtr; } #elif (defined(XXH_FORCE_MEMORY_ACCESS) && (XXH_FORCE_MEMORY_ACCESS==1)) /* __pack instructions are safer, but compiler specific, hence potentially problematic for some compilers */ /* currently only defined for gcc and icc */ typedef union { U32 u32; U64 u64; } __attribute__((packed)) unalign64; static U64 XXH_read64(const void* ptr) { return ((const unalign64*)ptr)->u64; } #else /* portable and safe solution. Generally efficient. * see : http://stackoverflow.com/a/32095106/646947 */ static U64 XXH_read64(const void* memPtr) { U64 val; memcpy(&val, memPtr, sizeof(val)); return val; } #endif /* XXH_FORCE_DIRECT_MEMORY_ACCESS */ #if defined(_MSC_VER) /* Visual Studio */ # define XXH_swap64 _byteswap_uint64 #elif XXH_GCC_VERSION >= 403 # define XXH_swap64 __builtin_bswap64 #else static U64 XXH_swap64 (U64 x) { return ((x << 56) & 0xff00000000000000ULL) | ((x << 40) & 0x00ff000000000000ULL) | ((x << 24) & 0x0000ff0000000000ULL) | ((x << 8) & 0x000000ff00000000ULL) | ((x >> 8) & 0x00000000ff000000ULL) | ((x >> 24) & 0x0000000000ff0000ULL) | ((x >> 40) & 0x000000000000ff00ULL) | ((x >> 56) & 0x00000000000000ffULL); } #endif FORCE_INLINE U64 XXH_readLE64_align(const void* ptr, XXH_endianess endian, XXH_alignment align) { if (align==XXH_unaligned) return endian==XXH_littleEndian ? XXH_read64(ptr) : XXH_swap64(XXH_read64(ptr)); else return endian==XXH_littleEndian ? *(const U64*)ptr : XXH_swap64(*(const U64*)ptr); } FORCE_INLINE U64 XXH_readLE64(const void* ptr, XXH_endianess endian) { return XXH_readLE64_align(ptr, endian, XXH_unaligned); } static U64 XXH_readBE64(const void* ptr) { return XXH_CPU_LITTLE_ENDIAN ? XXH_swap64(XXH_read64(ptr)) : XXH_read64(ptr); } /*====== xxh64 ======*/ static const U64 PRIME64_1 = 11400714785074694791ULL; /* 0b1001111000110111011110011011000110000101111010111100101010000111 */ static const U64 PRIME64_2 = 14029467366897019727ULL; /* 0b1100001010110010101011100011110100100111110101001110101101001111 */ static const U64 PRIME64_3 = 1609587929392839161ULL; /* 0b0001011001010110011001111011000110011110001101110111100111111001 */ static const U64 PRIME64_4 = 9650029242287828579ULL; /* 0b1000010111101011110010100111011111000010101100101010111001100011 */ static const U64 PRIME64_5 = 2870177450012600261ULL; /* 0b0010011111010100111010110010111100010110010101100110011111000101 */ static U64 XXH64_round(U64 acc, U64 input) { acc += input * PRIME64_2; acc = XXH_rotl64(acc, 31); acc *= PRIME64_1; return acc; } static U64 XXH64_mergeRound(U64 acc, U64 val) { val = XXH64_round(0, val); acc ^= val; acc = acc * PRIME64_1 + PRIME64_4; return acc; } static U64 XXH64_avalanche(U64 h64) { h64 ^= h64 >> 33; h64 *= PRIME64_2; h64 ^= h64 >> 29; h64 *= PRIME64_3; h64 ^= h64 >> 32; return h64; } #define XXH_get64bits(p) XXH_readLE64_align(p, endian, align) static U64 XXH64_finalize(U64 h64, const void* ptr, size_t len, XXH_endianess endian, XXH_alignment align) { const BYTE* p = (const BYTE*)ptr; #define PROCESS1_64 \ h64 ^= (*p++) * PRIME64_5; \ h64 = XXH_rotl64(h64, 11) * PRIME64_1; #define PROCESS4_64 \ h64 ^= (U64)(XXH_get32bits(p)) * PRIME64_1; \ p+=4; \ h64 = XXH_rotl64(h64, 23) * PRIME64_2 + PRIME64_3; #define PROCESS8_64 { \ U64 const k1 = XXH64_round(0, XXH_get64bits(p)); \ p+=8; \ h64 ^= k1; \ h64 = XXH_rotl64(h64,27) * PRIME64_1 + PRIME64_4; \ } switch(len&31) { case 24: PROCESS8_64; /* fallthrough */ case 16: PROCESS8_64; /* fallthrough */ case 8: PROCESS8_64; return XXH64_avalanche(h64); case 28: PROCESS8_64; /* fallthrough */ case 20: PROCESS8_64; /* fallthrough */ case 12: PROCESS8_64; /* fallthrough */ case 4: PROCESS4_64; return XXH64_avalanche(h64); case 25: PROCESS8_64; /* fallthrough */ case 17: PROCESS8_64; /* fallthrough */ case 9: PROCESS8_64; PROCESS1_64; return XXH64_avalanche(h64); case 29: PROCESS8_64; /* fallthrough */ case 21: PROCESS8_64; /* fallthrough */ case 13: PROCESS8_64; /* fallthrough */ case 5: PROCESS4_64; PROCESS1_64; return XXH64_avalanche(h64); case 26: PROCESS8_64; /* fallthrough */ case 18: PROCESS8_64; /* fallthrough */ case 10: PROCESS8_64; PROCESS1_64; PROCESS1_64; return XXH64_avalanche(h64); case 30: PROCESS8_64; /* fallthrough */ case 22: PROCESS8_64; /* fallthrough */ case 14: PROCESS8_64; /* fallthrough */ case 6: PROCESS4_64; PROCESS1_64; PROCESS1_64; return XXH64_avalanche(h64); case 27: PROCESS8_64; /* fallthrough */ case 19: PROCESS8_64; /* fallthrough */ case 11: PROCESS8_64; PROCESS1_64; PROCESS1_64; PROCESS1_64; return XXH64_avalanche(h64); case 31: PROCESS8_64; /* fallthrough */ case 23: PROCESS8_64; /* fallthrough */ case 15: PROCESS8_64; /* fallthrough */ case 7: PROCESS4_64; /* fallthrough */ case 3: PROCESS1_64; /* fallthrough */ case 2: PROCESS1_64; /* fallthrough */ case 1: PROCESS1_64; /* fallthrough */ case 0: return XXH64_avalanche(h64); } /* impossible to reach */ assert(0); return 0; /* unreachable, but some compilers complain without it */ } FORCE_INLINE U64 XXH64_endian_align(const void* input, size_t len, U64 seed, XXH_endianess endian, XXH_alignment align) { const BYTE* p = (const BYTE*)input; const BYTE* bEnd = p + len; U64 h64; #if defined(XXH_ACCEPT_NULL_INPUT_POINTER) && (XXH_ACCEPT_NULL_INPUT_POINTER>=1) if (p==NULL) { len=0; bEnd=p=(const BYTE*)(size_t)32; } #endif if (len>=32) { const BYTE* const limit = bEnd - 32; U64 v1 = seed + PRIME64_1 + PRIME64_2; U64 v2 = seed + PRIME64_2; U64 v3 = seed + 0; U64 v4 = seed - PRIME64_1; do { v1 = XXH64_round(v1, XXH_get64bits(p)); p+=8; v2 = XXH64_round(v2, XXH_get64bits(p)); p+=8; v3 = XXH64_round(v3, XXH_get64bits(p)); p+=8; v4 = XXH64_round(v4, XXH_get64bits(p)); p+=8; } while (p<=limit); h64 = XXH_rotl64(v1, 1) + XXH_rotl64(v2, 7) + XXH_rotl64(v3, 12) + XXH_rotl64(v4, 18); h64 = XXH64_mergeRound(h64, v1); h64 = XXH64_mergeRound(h64, v2); h64 = XXH64_mergeRound(h64, v3); h64 = XXH64_mergeRound(h64, v4); } else { h64 = seed + PRIME64_5; } h64 += (U64) len; return XXH64_finalize(h64, p, len, endian, align); } XXH_PUBLIC_API unsigned long long XXH64 (const void* input, size_t len, unsigned long long seed) { #if 0 /* Simple version, good for code maintenance, but unfortunately slow for small inputs */ XXH64_state_t state; XXH64_reset(&state, seed); XXH64_update(&state, input, len); return XXH64_digest(&state); #else XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN; if (XXH_FORCE_ALIGN_CHECK) { if ((((size_t)input) & 7)==0) { /* Input is aligned, let's leverage the speed advantage */ if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT) return XXH64_endian_align(input, len, seed, XXH_littleEndian, XXH_aligned); else return XXH64_endian_align(input, len, seed, XXH_bigEndian, XXH_aligned); } } if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT) return XXH64_endian_align(input, len, seed, XXH_littleEndian, XXH_unaligned); else return XXH64_endian_align(input, len, seed, XXH_bigEndian, XXH_unaligned); #endif } /*====== Hash Streaming ======*/ XXH_PUBLIC_API XXH64_state_t* XXH64_createState(void) { return (XXH64_state_t*)XXH_malloc(sizeof(XXH64_state_t)); } XXH_PUBLIC_API XXH_errorcode XXH64_freeState(XXH64_state_t* statePtr) { XXH_free(statePtr); return XXH_OK; } XXH_PUBLIC_API void XXH64_copyState(XXH64_state_t* dstState, const XXH64_state_t* srcState) { memcpy(dstState, srcState, sizeof(*dstState)); } XXH_PUBLIC_API XXH_errorcode XXH64_reset(XXH64_state_t* statePtr, unsigned long long seed) { XXH64_state_t state; /* using a local state to memcpy() in order to avoid strict-aliasing warnings */ memset(&state, 0, sizeof(state)); state.v1 = seed + PRIME64_1 + PRIME64_2; state.v2 = seed + PRIME64_2; state.v3 = seed + 0; state.v4 = seed - PRIME64_1; /* do not write into reserved, planned to be removed in a future version */ memcpy(statePtr, &state, sizeof(state) - sizeof(state.reserved)); return XXH_OK; } FORCE_INLINE XXH_errorcode XXH64_update_endian (XXH64_state_t* state, const void* input, size_t len, XXH_endianess endian) { if (input==NULL) #if defined(XXH_ACCEPT_NULL_INPUT_POINTER) && (XXH_ACCEPT_NULL_INPUT_POINTER>=1) return XXH_OK; #else return XXH_ERROR; #endif { const BYTE* p = (const BYTE*)input; const BYTE* const bEnd = p + len; state->total_len += len; if (state->memsize + len < 32) { /* fill in tmp buffer */ XXH_memcpy(((BYTE*)state->mem64) + state->memsize, input, len); state->memsize += (U32)len; return XXH_OK; } if (state->memsize) { /* tmp buffer is full */ XXH_memcpy(((BYTE*)state->mem64) + state->memsize, input, 32-state->memsize); state->v1 = XXH64_round(state->v1, XXH_readLE64(state->mem64+0, endian)); state->v2 = XXH64_round(state->v2, XXH_readLE64(state->mem64+1, endian)); state->v3 = XXH64_round(state->v3, XXH_readLE64(state->mem64+2, endian)); state->v4 = XXH64_round(state->v4, XXH_readLE64(state->mem64+3, endian)); p += 32-state->memsize; state->memsize = 0; } if (p+32 <= bEnd) { const BYTE* const limit = bEnd - 32; U64 v1 = state->v1; U64 v2 = state->v2; U64 v3 = state->v3; U64 v4 = state->v4; do { v1 = XXH64_round(v1, XXH_readLE64(p, endian)); p+=8; v2 = XXH64_round(v2, XXH_readLE64(p, endian)); p+=8; v3 = XXH64_round(v3, XXH_readLE64(p, endian)); p+=8; v4 = XXH64_round(v4, XXH_readLE64(p, endian)); p+=8; } while (p<=limit); state->v1 = v1; state->v2 = v2; state->v3 = v3; state->v4 = v4; } if (p < bEnd) { XXH_memcpy(state->mem64, p, (size_t)(bEnd-p)); state->memsize = (unsigned)(bEnd-p); } } return XXH_OK; } XXH_PUBLIC_API XXH_errorcode XXH64_update (XXH64_state_t* state_in, const void* input, size_t len) { XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN; if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT) return XXH64_update_endian(state_in, input, len, XXH_littleEndian); else return XXH64_update_endian(state_in, input, len, XXH_bigEndian); } FORCE_INLINE U64 XXH64_digest_endian (const XXH64_state_t* state, XXH_endianess endian) { U64 h64; if (state->total_len >= 32) { U64 const v1 = state->v1; U64 const v2 = state->v2; U64 const v3 = state->v3; U64 const v4 = state->v4; h64 = XXH_rotl64(v1, 1) + XXH_rotl64(v2, 7) + XXH_rotl64(v3, 12) + XXH_rotl64(v4, 18); h64 = XXH64_mergeRound(h64, v1); h64 = XXH64_mergeRound(h64, v2); h64 = XXH64_mergeRound(h64, v3); h64 = XXH64_mergeRound(h64, v4); } else { h64 = state->v3 /*seed*/ + PRIME64_5; } h64 += (U64) state->total_len; return XXH64_finalize(h64, state->mem64, (size_t)state->total_len, endian, XXH_aligned); } XXH_PUBLIC_API unsigned long long XXH64_digest (const XXH64_state_t* state_in) { XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN; if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT) return XXH64_digest_endian(state_in, XXH_littleEndian); else return XXH64_digest_endian(state_in, XXH_bigEndian); } /*====== Canonical representation ======*/ XXH_PUBLIC_API void XXH64_canonicalFromHash(XXH64_canonical_t* dst, XXH64_hash_t hash) { XXH_STATIC_ASSERT(sizeof(XXH64_canonical_t) == sizeof(XXH64_hash_t)); if (XXH_CPU_LITTLE_ENDIAN) hash = XXH_swap64(hash); memcpy(dst, &hash, sizeof(*dst)); } XXH_PUBLIC_API XXH64_hash_t XXH64_hashFromCanonical(const XXH64_canonical_t* src) { return XXH_readBE64(src); } #endif /* XXH_NO_LONG_LONG */
d1d18edb5aefee9b3a4390723cf608d3533f6142
c4790552abc608f491b7ac2a0b6dcd5826a5bd7c
/344A.cpp
701ad934fdd4da6100529b8f122596d8b9573d0f
[]
no_license
jeffry1829/ojcode
bd03df14360e5c00e6463c3621de0cfeef88bb11
18a6fa3aa59e0d9c274f44f7dea060f70c91cbe8
refs/heads/master
2023-02-27T00:27:04.856978
2021-02-04T09:20:58
2021-02-04T09:20:58
286,199,256
0
0
null
null
null
null
UTF-8
C++
false
false
357
cpp
#include <bits/stdc++.h> using namespace std; int n, res = 1; char s[5], _prev[5], *t; main(void) { cin.tie(0); ios_base::sync_with_stdio(0); cin >> n; cin >> _prev; strncpy(s, _prev, 2); s[3] = '\0'; for (int i = 1; i < n; i++) { cin >> s; if (strcmp(s, _prev) != 0) res++; swap(s, _prev); } cout << res << '\n'; return 0; }
0cab755dda888dc7fd7467bf9289757a1ebedb1d
9dc6cb93169af80ffc1e055eaea2a7cbd2b139ec
/o2engine/src/app/application_base_interface.h
0e5e717d8cfa9078354c1f2f7d3644b29752940b
[]
no_license
zenkovich/anphys-engine-svn
2b745f8341f1cebde1863404e8cc55a0eaeb4c91
4fac80c014a0e0c39e1f0d821be1a062c626499c
refs/heads/master
2020-06-09T16:58:33.065922
2015-01-15T17:37:05
2015-01-15T17:37:05
53,565,477
0
0
null
null
null
null
UTF-8
C++
false
false
6,442
h
#ifndef APPLICATION_BASE_INTERFACE_H #define APPLICATION_BASE_INTERFACE_H #include "public.h" #include "util/singleton.h" #include "util/input/input_message.h" #include "util/callback.h" OPEN_O2_NAMESPACE class grRenderSystem; class LogStream; class FileSystem; class Scheduler; class TimeUtil; class Timer; class uiController; class ProjectConfig; class Assets; /** Basic application class. Not implementing frame data. * Containing input message and systems: * Project configs * Application log stream, * Render system, * File system, * Scheduler, * Time utils, * UI controller */ class cApplicationBaseInterface: public Singleton<cApplicationBaseInterface> { protected: ProjectConfig* mProjectConfig; /**< Project config. */ InputMessage* mInputMessage; /**< While application user input message. */ LogStream* mLog; /**< Log stream with id "app", using only for application messages. */ grRenderSystem* mRenderSystem; /**< Render system. */ FileSystem* mFileSystem; /**< File system. */ Scheduler* mScheduler; /**< Scheduler. */ TimeUtil* mTimeUtils; /**< Time utilities. */ uiController* mUIController; /**< User interface controller host. */ Assets* mAssets; /**< Assets. */ Timer* mTimer; /**< Timer for detecting delta time for update. */ public: CallbackChain onActivatedEvent; /**< On Activated event callbacks. */ CallbackChain onDeactivatedEvent; /**< On deactivated event callbacks. */ CallbackChain onStartedEvent; /**< On started event callbacks. */ CallbackChain onClosingEvent; /**< On closing event callbacks. */ CallbackChain onResizingEvent; /**< On resized app window callbacks. Ignoring on mobiles/tables. */ CallbackChain onMovingEvent; /**< On moving app window callbacks. Ignoring on mobiles/tables. */ /** ctor. */ cApplicationBaseInterface(); /** dtor. */ virtual ~cApplicationBaseInterface(); /** Returns pointer to input message object. */ InputMessage* getInputMessage(); /** Returns pointer to render system object. */ grRenderSystem* getRenderSystem() const; /** Returns pointer to log object. */ LogStream* getLog() const; /** Returns pointer to project config object. */ ProjectConfig* getProjectConfig() const; /** Returns pointer to file system object. */ FileSystem* getFileSystem() const; /** Returns pointer to scheduler object. */ Scheduler* getScheduler() const; /** Returns pointer to time utils object. */ TimeUtil* getTimeUtils() const; /** Returns pointer to ui controller object. */ uiController* getUIController() const; /** Returns pointer to assets object. */ Assets* getAssets() const; /** Launching application cycle. */ virtual void launch() {} /** Called on updating. */ virtual void onUpdate(float dt) {} /** Called on drawing. */ virtual void onDraw() {} /** Makes application windowed. On mobiles/tablets has no effect, just ignoring. */ virtual void setWindowed() {} /** Makes application fullscreen. On mobiles/tablets has no effect, just ignoring. */ virtual void setFullscreen() {} /** Return true, if application is fullscreen On mobiles/tables always true. */ virtual bool isFullScreen() const { return true; } /** Sets application window as resizible. On mobiles/tablets has no effect, just ignoring. */ virtual void setResizible(bool resizible) {} /** Returns true, if application is resizible. On mobiles/tablets always returns false. */ virtual bool isResizible() const { return false; } /** Sets application window size. On mobiles/tablets has no effect, just ignoring. */ virtual void setWindowSize(const vec2i& size) {} /** Returns application window size. On mobiles/tablets returns content size. */ virtual vec2i getWindowSize() const { return getContentSize(); } /** Sets application window position. On mobiles/tablets has no effect, just ignoring. */ virtual void setWindowPosition(const vec2i& position) {} /** Returns application window position. On mobiles/tablets return zero vector. */ virtual vec2i getWindowPosition() const { return vec2i(); } /** Sets application window caption. On mobiles/tablets has no effect, just ignoring. */ virtual void setWindowCaption(const string& caption) {} /** Returns application window caption. On mobiles/tablets returns empty string. */ virtual string getWindowCaption() const { return ""; } /** Sets inside content size. */ virtual void setContentSize(const vec2i& size) {} /** Returns inside content size. */ virtual vec2i getContentSize() const {return vec2i(); } protected: /** Initializing all systems and log. Call it when creating applications*/ void initalizeSystems(); /** Deinitializing systems. */ void deinitializeSystems(); /** Processing frame update, drawing and input messages. */ void processFrame(); /** Calls when application activated. */ virtual void onActivated() {} /** Calls when application deactivated. */ virtual void onDeactivated() {} /** Calls when application is starting. */ virtual void onStarted() {} /** Calls when application is closing. */ virtual void onClosing() {} /** Calls when application window resized. Ignoring on mobiles/tablets. */ virtual void onResizing() {} /** Calls when application window moved. Ignoring on mobiles/tablets. */ virtual void onMoved() {} }; inline InputMessage* appInput() { return cApplicationBaseInterface::instancePtr()->getInputMessage(); } inline grRenderSystem* renderSystem() { return cApplicationBaseInterface::instancePtr()->getRenderSystem(); } inline ProjectConfig* projectConfig() { return cApplicationBaseInterface::instancePtr()->getProjectConfig(); } inline FileSystem* fileSystem() { return cApplicationBaseInterface::instancePtr()->getFileSystem(); } inline Scheduler* scheduler() { return cApplicationBaseInterface::instancePtr()->getScheduler(); } inline TimeUtil* timeUtils() { return cApplicationBaseInterface::instancePtr()->getTimeUtils(); } inline uiController* uiHost() { return cApplicationBaseInterface::instancePtr()->getUIController(); } inline Assets* assets() { return cApplicationBaseInterface::instancePtr()->getAssets(); } CLOSE_O2_NAMESPACE #endif //APPLICATION_BASE_INTERFACE_H
36dc32334f4c66f9d0b1fa7a75f2af4ebb8ee6d9
a54b76d3cf3b5ea885bb26e408f0e47237318123
/examples/httpserver/src/http_module_request_rewrite.cc
c991e55a8261b5380835889b76684b648a75f9f4
[]
no_license
jacobwpeng/fxserver
0e02a96967e8d6208f222fe3712fdd453cf85efd
a3057ec54de201fbdb095a69a5e113e342205b2b
refs/heads/master
2021-01-23T07:20:43.156133
2017-03-22T08:49:26
2017-03-22T08:49:26
17,588,075
0
0
null
null
null
null
UTF-8
C++
false
false
2,207
cc
/* * ===================================================================================== * Filename: http_module_request_rewrite.cc * Created: 10:48:04 May 13, 2014 * Author: jacobwpeng * Email: [email protected] * Description: * * ===================================================================================== */ #include "http_module_request_rewrite.h" #include <boost/foreach.hpp> #include "http_server.h" HTTPModuleRequestRewrite::HTTPModuleRequestRewrite(HTTPServer *server) :server_(server) { Init(); } HTTPModuleRequestRewrite::~HTTPModuleRequestRewrite() { } HTTPResponsePtr HTTPModuleRequestRewrite::ResolveRequestPathCandidates( HTTPRequestPtr req) { HTTPResponsePtr res; /* if original_request_path ends with a slash * then we consider it as a directory access * */ string original_request_path = req->original_request_path(); assert( not original_request_path.empty() ); char last_char = *original_request_path.rbegin(); if( last_char == '/' ) { BOOST_FOREACH(const string& suffix, dir_access_suffixes_) { /* TODO : add all suffixes in one call ? */ req->add_request_path_candidate(suffix); } /* TODO : add compressed extensions for dir access files */ } else { /* TODO : avoid add extension when request pre-compressed files */ BOOST_FOREACH(const string& extension, compressed_file_extensions_) { req->add_request_path_candidate( req->original_request_path() + extension ); } req->add_request_path_candidate( req->original_request_path() ); } return res; } RetCode HTTPModuleRequestRewrite::Init() { /* TODO : more default dir access suffixes */ dir_access_suffixes_.push_back( "/index.html" ); /* compressed file extensions */ compressed_file_extensions_.push_back(".gz"); server_->RegisterPreProcessing( boost::bind(&HTTPModuleRequestRewrite::ResolveRequestPathCandidates, this, _1) ); return kOk; }
077d8afcf99d8763bb834d5f2f5c07d1d4628fe7
f4cfafe698191c6a72fae71850dc82878a5afc3e
/third_party/gfootball_engine/src/onthepitch/player/controller/strategies/special/celebration.hpp
7efc1832d899a31fda2749b76857f1147718be2a
[ "Unlicense", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
nczempin/gfootball
3e9478a5a970f47de2fe59afd98951f1a52efed3
617e9cb6d48b4ac7187b9b3de68bd4ab44ea528e
refs/heads/master
2020-06-01T20:21:40.815706
2019-07-12T21:15:16
2019-07-12T21:15:16
190,915,700
0
0
Apache-2.0
2019-07-12T21:15:17
2019-06-08T17:22:31
Python
UTF-8
C++
false
false
966
hpp
// Copyright 2019 Google LLC & Bastiaan Konings // 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. // written by bastiaan konings schuiling 2008 - 2015 // this work is public domain. the code is undocumented, scruffy, untested, and should generally not be used for anything important. // i do not offer support, so don't ask. to be used for inspiration :) #ifndef _HPP_STRATEGY_CELEBRATION #define _HPP_STRATEGY_CELEBRATION #include "../strategy.hpp" #endif
e5634a829e54b4b0dd26a00b425d9b1f702e9f42
bf20446a240d654d856dd237434b53d98bc8c62a
/xml_result_timeout.h
e737df0013362c9e16a4535989d35772a3982557
[]
no_license
2ejm/xiz-rcz
96d32221d7dbdac8c4026a231e4268ece1110322
f5ccf784025f1e5f67861b68b61ae61fda298c95
refs/heads/master
2021-03-07T12:43:32.159442
2020-03-10T10:08:36
2020-03-10T10:08:36
246,267,263
0
0
null
null
null
null
UTF-8
C++
false
false
441
h
#ifndef _XML_RESULT_TIMEOUT_H_ #define _XML_RESULT_TIMEOUT_H_ #include "xml_result.h" /** * \brief Timeout XmlResult * * Used for File API. */ class XmlResultTimeout: public XmlResult { public: XmlResultTimeout (); XmlResultTimeout (const Glib::ustring & message); static Glib::RefPtr <XmlResult> create (); static Glib::RefPtr <XmlResult> create (const Glib::ustring & message); }; #endif /* _XML_RESULT_TIMEOUT_H_ */