hexsha stringlengths 40 40 | size int64 22 2.4M | ext stringclasses 5
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 260 | max_stars_repo_name stringlengths 5 109 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 260 | max_issues_repo_name stringlengths 5 109 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 260 | max_forks_repo_name stringlengths 5 109 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 22 2.4M | avg_line_length float64 5 169k | max_line_length int64 5 786k | alphanum_fraction float64 0.06 0.95 | matches listlengths 1 11 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9f0afea240a3337479db815e3e4e6d5296e8c53e | 316 | h | C | SSBaseKit/AMDBase/View/AMDBaseCellDataSource.h | xie244135119/SSBBaseKit | c46a1a5defe9e137c9926d1cd7b510df35910d30 | [
"MIT"
] | 1 | 2019-03-20T08:43:13.000Z | 2019-03-20T08:43:13.000Z | SSBaseKit/AMDBase/View/AMDBaseCellDataSource.h | xie244135119/SSBBaseKit | c46a1a5defe9e137c9926d1cd7b510df35910d30 | [
"MIT"
] | null | null | null | SSBaseKit/AMDBase/View/AMDBaseCellDataSource.h | xie244135119/SSBBaseKit | c46a1a5defe9e137c9926d1cd7b510df35910d30 | [
"MIT"
] | null | null | null | //
// AMDBaseCellDataSource.h
// SSBaseKit
//
// Created by SunSet on 2018/4/20.
// Copyright © 2018年 SunSet. All rights reserved.
//
#import <Foundation/Foundation.h>
@protocol AMDBaseCellDataSource <NSObject>
@optional
// 赋值数据
- (void)assignSourceModel:(id)model;
// cell高度
+ (CGFloat)cellHeight;
@end
| 13.166667 | 50 | 0.702532 | [
"model"
] |
9f13b49815e491210fb184b78ae2406a685218d0 | 2,480 | h | C | olp-cpp-sdk-core/src/network/NetworkRequestPriorityQueue.h | olrudenk/here-olp-edge-sdk-cpp | 8e1dd53ea8c59a983400635e9d91291cffc15ec2 | [
"Apache-2.0"
] | 1 | 2021-01-27T13:10:32.000Z | 2021-01-27T13:10:32.000Z | olp-cpp-sdk-core/src/network/NetworkRequestPriorityQueue.h | ystefinko/here-olp-edge-sdk-cpp | 59f814cf98acd8f6c62572104a21ebdff4027171 | [
"Apache-2.0"
] | null | null | null | olp-cpp-sdk-core/src/network/NetworkRequestPriorityQueue.h | ystefinko/here-olp-edge-sdk-cpp | 59f814cf98acd8f6c62572104a21ebdff4027171 | [
"Apache-2.0"
] | 1 | 2019-07-03T09:06:39.000Z | 2019-07-03T09:06:39.000Z | /*
* Copyright (C) 2019 HERE Europe B.V.
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
* License-Filename: LICENSE
*/
#pragma once
#include "Memory.h"
#include "RequestContext.h"
#include <algorithm>
#include <climits>
#include <cstddef>
#include <deque>
#include <iostream>
#include <iterator>
#include <map>
#include <memory>
#include <mutex>
#include <ostream>
#include <vector>
namespace olp {
namespace network {
/**
* @brief Priority queue containing requests per priority level per client
*/
class CORE_API NetworkRequestPriorityQueue {
public:
/// Unsigned integer type
using SizeType = std::deque<RequestContextPtr>::size_type;
/**
* @brief Push to the queue
* @param [in] context request context to be pushed
*/
void Push(const RequestContextPtr& context);
/**
* @brief Pop from the queue
*/
RequestContextPtr Pop();
/**
* @brief Remove all elements satisying specific criteria.
* @param f unary predicate which returns true if the element should be
* removed
*/
template <class Functor>
mem::vector<RequestContextPtr> RemoveIf(Functor f) {
using std::begin;
using std::end;
mem::vector<RequestContextPtr> removed;
std::lock_guard<std::mutex> lock(lock_);
std::for_each(
begin(requests_), end(requests_),
[&f, &removed](mem::deque<RequestContextPtr>& queue) {
std::copy_if(begin(queue), end(queue), back_inserter(removed), f);
queue.erase(std::remove_if(begin(queue), end(queue), f), end(queue));
});
return removed;
}
/**
* @brief Get number of queued requests.
* @return number of queued requests
*/
SizeType Size() const;
private:
static const size_t kArraySize =
NetworkRequest::PriorityMax - NetworkRequest::PriorityMin + 1;
mem::deque<RequestContextPtr> requests_[kArraySize];
mutable std::mutex lock_;
};
} // namespace network
} // namespace olp
| 25.833333 | 79 | 0.693145 | [
"vector"
] |
9f1b1a11540477c913579b27015c50415b88b1b1 | 1,903 | h | C | psklib/GameFileSystem.h | psk7142/DirectX2D | 1d91e8a863aab2dbf57fecd2df111261a90dd3de | [
"MIT"
] | null | null | null | psklib/GameFileSystem.h | psk7142/DirectX2D | 1d91e8a863aab2dbf57fecd2df111261a90dd3de | [
"MIT"
] | null | null | null | psklib/GameFileSystem.h | psk7142/DirectX2D | 1d91e8a863aab2dbf57fecd2df111261a90dd3de | [
"MIT"
] | 2 | 2020-03-09T15:12:11.000Z | 2020-03-09T16:04:04.000Z | #pragma once
#include <experimental/filesystem>
#include <map>
#include "Debug.h"
namespace stdfs = std::experimental::filesystem;
class GFileSystem
{
public:
static void Initialize( );
static bool InsertPathMap(const std::wstring& _path);
static bool InsertPathMap(const std::wstring& _name, const std::wstring& _path);
static stdfs::path& GetRootPath( );
static bool MoveRootPathTo(const std::wstring& _name);
static GFileSystem FindPathOrNull(const std::wstring& _name);
static stdfs::path Join(stdfs::path _path, std::wstring _name);
static bool IsExsit(const stdfs::path& _path);
static std::vector<stdfs::path> GetAllDirectories( );
static std::vector<stdfs::path> GetAllResourceFiles( );
static std::vector<stdfs::path> GetAllImgFiles( );
static std::vector<stdfs::path> GetAllImgFiles(const stdfs::path& _path);
static std::vector<stdfs::path> GetAllSoundFiles( );
GFileSystem( );
GFileSystem(const GFileSystem& _other) = default;
GFileSystem(GFileSystem&& _filesystem) = default;
GFileSystem(const stdfs::path& _path);
~GFileSystem( );
void SetPath(const std::wstring& _path);
void SetPath(const stdfs::path& _path);
stdfs::path GetAbsPath( ) const;
stdfs::path GetExtension( );
stdfs::path GetDirName( );
bool MoveToParent( );
GFileSystem& operator/=(const std::wstring& _name)
{
mPath /= _name;
return *this;
}
GFileSystem& operator=(const stdfs::path& _path)
{
std::wcout << L"Set new path... ";
if ( true == IsExsit(mPath) )
{
mPath = stdfs::path(_path);
std::wcout << mPath << std::endl;
}
else
{
std::wcout << L"fail!! (" << mPath << L")" << std::endl;
}
return *this;
}
GFileSystem& operator=(const GFileSystem& _other) = default;
GFileSystem& operator=(GFileSystem&& _filesystem) = default;
protected:
static std::map<std::wstring, GFileSystem> mMapOfPath;
static stdfs::path mRootPath;
stdfs::path mPath;
}; | 26.430556 | 81 | 0.706779 | [
"vector"
] |
9f222699807e972bcb751833f503761fd097d0af | 773 | c | C | lib/wizards/gynter/darke/city/Orcity2.c | vlehtola/questmud | 8bc3099b5ad00a9e0261faeb6637c76b521b6dbe | [
"MIT"
] | null | null | null | lib/wizards/gynter/darke/city/Orcity2.c | vlehtola/questmud | 8bc3099b5ad00a9e0261faeb6637c76b521b6dbe | [
"MIT"
] | null | null | null | lib/wizards/gynter/darke/city/Orcity2.c | vlehtola/questmud | 8bc3099b5ad00a9e0261faeb6637c76b521b6dbe | [
"MIT"
] | null | null | null | inherit "room/room";
object mob, mob1;
reset(arg) {
/* Applying mobs */
if(!mob && !random(2)) {
mob = clone_object("/wizards/gynter/darke/mobs/citizen");
move_object(mob, this_object());
}
if(!mob1 && !random(2)) {
mob1 = clone_object("/wizards/gynter/darke/mobs/citizen");
move_object(mob1, this_object());
}
if(arg) return;
/* Assigning exits */
add_exit("north","/wizards/gynter/darke/city/Orcity1");
add_exit("south","/wizards/gynter/darke/city/Orcity3");
/* setting desc */
short_desc = "The road to the old parts";
long_desc = "Everywhere there are houses missing walls, ready to collapse\n"+
"at any moment. There are shattered stones everywhere.\n"+
"The battle here must have been awful.\n";
}
| 32.208333 | 79 | 0.646831 | [
"object"
] |
9f25fe468e99543e355d5b9e6b8aaac1b61fe7cc | 885 | h | C | TVProjectionDemo2/TVProjectionDemo2/DLNA/UPnP/CCUPnPAction.h | buvtopcc/CCDLNAManager | cafd637315e0d26ebfcb58bbef21063a5b0570c3 | [
"MIT"
] | 1 | 2020-04-14T06:11:33.000Z | 2020-04-14T06:11:33.000Z | TVProjectionDemo2/TVProjectionDemo2/DLNA/UPnP/CCUPnPAction.h | buvtopcc/CCDLNAManager | cafd637315e0d26ebfcb58bbef21063a5b0570c3 | [
"MIT"
] | null | null | null | TVProjectionDemo2/TVProjectionDemo2/DLNA/UPnP/CCUPnPAction.h | buvtopcc/CCDLNAManager | cafd637315e0d26ebfcb58bbef21063a5b0570c3 | [
"MIT"
] | null | null | null | //
// CCUPnPAction.h
// hustcc
//
// Created by buvtopcc on 2019/11/7.
// Copyright © 2019 buvtopcc. All rights reserved.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
typedef NS_ENUM(NSInteger, CCUPnPServiceType) {
CCUPnPServiceTypeAVTransport, // @"urn:schemas-upnp-org:service:AVTransport:1"
CCUPnPServiceTypeRenderingControl // @"urn:schemas-upnp-org:service:RenderingControl:1"
};
@class CCUPnPDevice;
@interface CCUPnPAction : NSObject
// serviceType 默认 CCUPnPServiceTypeAVTransport
@property (nonatomic, assign) CCUPnPServiceType serviceType;
- (instancetype)initWithAction:(NSString *)action;
- (void)setArgumentValue:(NSString *)value forName:(NSString *)name;
- (NSString *)getServiceType;
- (NSString *)getSOAPAction;
- (NSString *)getPostUrlStrWith:(CCUPnPDevice *)model;
- (NSString *)getPostXMLFile;
@end
NS_ASSUME_NONNULL_END
| 25.285714 | 93 | 0.759322 | [
"model"
] |
9f26108f0e381bfa198a245bafe3927819aa5e0a | 5,127 | h | C | FEBioMix/FEBiphasic.h | AlexandraAllan23/FEBio | c94a1c30e0bae5f285c0daae40a7e893e63cff3c | [
"MIT"
] | 59 | 2020-06-15T12:38:49.000Z | 2022-03-29T19:14:47.000Z | FEBioMix/FEBiphasic.h | AlexandraAllan23/FEBio | c94a1c30e0bae5f285c0daae40a7e893e63cff3c | [
"MIT"
] | 36 | 2020-06-14T21:10:01.000Z | 2022-03-12T12:03:14.000Z | FEBioMix/FEBiphasic.h | AlexandraAllan23/FEBio | c94a1c30e0bae5f285c0daae40a7e893e63cff3c | [
"MIT"
] | 26 | 2020-06-25T15:02:13.000Z | 2022-03-10T09:14:03.000Z | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2020 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
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.*/
#pragma once
#include <FEBioMech/FEElasticMaterial.h>
#include "FEHydraulicPermeability.h"
#include "FESolventSupply.h"
#include "FEActiveMomentumSupply.h"
#include <FEBioMech/FEBodyForce.h>
#include <FECore/FEModelParam.h>
//-----------------------------------------------------------------------------
//! Biphasic material point class.
//
class FEBIOMIX_API FEBiphasicMaterialPoint : public FEMaterialPoint
{
public:
//! constructor
FEBiphasicMaterialPoint(FEMaterialPoint* ppt);
//! create a shallow copy
FEMaterialPoint* Copy() override;
//! data serialization
void Serialize(DumpStream& ar) override;
//! Data initialization
void Init() override;
public:
// poro-elastic material data
// The actual fluid pressure is the same as the effective fluid pressure
// in a poroelastic material without solute(s). The actual fluid pressure
// is included here so that models that include both poroelastic and
// solute-poroelastic domains produce plotfiles with consistent fluid
// pressure fields.
double m_p; //!< fluid pressure
vec3d m_gradp; //!< spatial gradient of p
vec3d m_gradpp; //!< gradp at previous time
vec3d m_w; //!< fluid flux
double m_pa; //!< actual fluid pressure
double m_phi0; //!< referential solid volume fraction at current time
double m_phi0p; //!< referential solid volume fraction at previous time
double m_phi0hat; //!< referential solid volume fraction supply at current time
double m_Jp; //!< determinant of solid deformation gradient at previous time
mat3ds m_ss; //!< solid (elastic or effective) stress
};
//-----------------------------------------------------------------------------
//! Base class for biphasic materials.
class FEBIOMIX_API FEBiphasic : public FEMaterial
{
public:
FEBiphasic(FEModel* pfem);
// returns a pointer to a new material point object
FEMaterialPoint* CreateMaterialPointData() override;
// Get the elastic component (overridden from FEMaterial)
FEElasticMaterial* GetElasticMaterial() { return m_pSolid; }
public:
//! calculate stress at material point
mat3ds Stress(FEMaterialPoint& pt);
//! calculate tangent stiffness at material point
tens4ds Tangent(FEMaterialPoint& pt);
//! return the permeability tensor as a matrix
void Permeability(double k[3][3], FEMaterialPoint& pt);
//! return the permeability as a tensor
mat3ds Permeability(FEMaterialPoint& pt);
//! return the permeability property
FEHydraulicPermeability* GetPermeability() { return m_pPerm; }
//! calculate actual fluid pressure
double Pressure(FEMaterialPoint& pt);
//! porosity
double Porosity(FEMaterialPoint& pt);
//! solid density
double SolidDensity(FEMaterialPoint& mp) { return m_pSolid->Density(mp); }
//! fluid density
double FluidDensity() { return m_rhoTw; }
//! get the solvent supply
double SolventSupply(FEMaterialPoint& mp) { return (m_pSupp? m_pSupp->Supply(mp) : 0); }
//! get the solvent supply property
FESolventSupply* GetSolventSupply() { return m_pSupp; }
//! Get the active momentum supply
FEActiveMomentumSupply* GetActiveMomentumSupply() { return m_pAmom; }
public: // material parameters
double m_rhoTw; //!< true fluid density
FEParamDouble m_phi0; //!< solid volume fraction in reference configuration
double m_tau; //!< characteristic time constant for stabilization
vector<FEBodyForce*> m_bf; //!< body forces acting on this biphasic material
private: // material properties
FEElasticMaterial* m_pSolid; //!< pointer to elastic solid material
FEHydraulicPermeability* m_pPerm; //!< pointer to permeability material
FESolventSupply* m_pSupp; //!< pointer to solvent supply
FEActiveMomentumSupply* m_pAmom; //!< pointer to active momentum supply
DECLARE_FECORE_CLASS();
};
| 36.884892 | 95 | 0.727716 | [
"object",
"vector",
"solid"
] |
378b52f4d33504057f5dd23cc133ddc6c7456fc7 | 22,650 | h | C | include/slib/core/java.h | emarc99/SLib | 4e492d6c550f845fd1b3f40bf10183097eb0e53c | [
"MIT"
] | 146 | 2017-03-21T07:50:43.000Z | 2022-03-19T03:32:22.000Z | include/slib/core/java.h | Crasader/SLib | 4e492d6c550f845fd1b3f40bf10183097eb0e53c | [
"MIT"
] | 50 | 2017-03-22T04:08:15.000Z | 2019-10-21T16:55:48.000Z | include/slib/core/java.h | Crasader/SLib | 4e492d6c550f845fd1b3f40bf10183097eb0e53c | [
"MIT"
] | 55 | 2017-03-21T07:52:58.000Z | 2021-12-27T13:02:08.000Z | /*
* Copyright (c) 2008-2018 SLIBIO <https://github.com/SLIBIO>
*
* 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.
*/
#ifndef CHECKHEADER_SLIB_CORE_JAVA
#define CHECKHEADER_SLIB_CORE_JAVA
/**********************************************************
This JNI library is implemented for shared JVM (one JVM)
**********************************************************/
#include "definition.h"
#if defined(SLIB_PLATFORM_USE_JNI)
#include "object.h"
#include "string.h"
#include <jni.h>
namespace slib
{
template <class T>
class SLIB_EXPORT JniLocal
{
public:
T value;
public:
JniLocal();
JniLocal(T value);
~JniLocal();
public:
operator T&();
operator T() const;
T operator=(T value);
T get() const;
sl_bool isNotNull() const;
sl_bool isNull() const;
void setNull();
void free();
};
class SLIB_EXPORT CJniGlobalBase : public Referable
{
SLIB_DECLARE_OBJECT
};
template <class T>
class SLIB_EXPORT CJniGlobal : public CJniGlobalBase
{
protected:
CJniGlobal() = default;
~CJniGlobal();
public:
static Ref< CJniGlobal<T> > from(T obj);
public:
T object;
};
template <class T>
class SLIB_EXPORT JniGlobal
{
public:
Ref< CJniGlobal<T> > ref;
SLIB_REF_WRAPPER(JniGlobal, CJniGlobal<T>)
public:
JniGlobal(T obj);
JniGlobal(const JniLocal<T>& obj);
public:
static JniGlobal<T> from(T obj);
public:
JniGlobal<T>& operator=(T obj);
JniGlobal<T>& operator=(const JniLocal<T>& obj);
public:
T get() const;
operator T() const;
};
template <class T>
class SLIB_EXPORT Atomic< JniGlobal<T> >
{
public:
AtomicRef< CJniGlobal<T> > ref;
SLIB_ATOMIC_REF_WRAPPER(CJniGlobal<T>)
public:
Atomic(T obj);
Atomic(JniLocal<T>& obj);
public:
Atomic& operator=(T obj);
Atomic& operator=(JniLocal<T>& obj);
public:
T get() const;
};
template <class T>
using AtomicJniGlobal = Atomic< JniGlobal<T> >;
class JniClass;
template <>
class SLIB_EXPORT Atomic<JniClass>
{
public:
AtomicRef< CJniGlobal<jclass> > ref;
SLIB_ATOMIC_REF_WRAPPER(CJniGlobal<jclass>)
public:
Atomic(jclass cls);
public:
Atomic& operator=(jclass cls);
};
typedef Atomic<JniClass> AtomicJniClass;
class SLIB_EXPORT JniClass
{
public:
Ref< CJniGlobal<jclass> > ref;
SLIB_REF_WRAPPER(JniClass, CJniGlobal<jclass>)
public:
JniClass(jclass cls);
public:
JniClass& operator=(jclass cls);
public:
static JniClass from(jclass cls);
static JniClass getClassOfObject(jobject object);
public:
jclass get() const;
operator jclass() const;
public:
sl_bool isInstanceOf(jobject obj) const;
/*
* Signature
* Z - boolean
* B - byte
* C - char
* S - short
* I - int
* J - long long
* F - float
* D - double
* V - void
* L<class-name>; - object
* [<type> - type[]
* (arg-types)ret-type : method type
*/
jmethodID getMethodID(const char* name, const char* sig) const;
jmethodID getStaticMethodID(const char* name, const char* sig) const;
jfieldID getFieldID(const char* name, const char* sig) const;
jfieldID getStaticFieldID(const char* name, const char* sig) const;
jobject newObject(jmethodID method, ...) const;
jobject newObject(const char* sigConstructor, ...) const;
jobject newObject() const;
jobject callObjectMethod(jmethodID method, jobject _this, ...) const;
jobject callObjectMethod(const char* name, const char* sig, jobject _this, ...) const;
jobject callStaticObjectMethod(jmethodID method, ...) const;
jobject callStaticObjectMethod(const char* name, const char* sig, ...) const;
jboolean callBooleanMethod(jmethodID method, jobject _this, ...) const;
jboolean callBooleanMethod(const char* name, const char* sig, jobject _this, ...) const;
jboolean callStaticBooleanMethod(jmethodID method, ...) const;
jboolean callStaticBooleanMethod(const char* name, const char* sig, ...) const;
jbyte callByteMethod(jmethodID method, jobject _this, ...) const;
jbyte callByteMethod(const char* name, const char* sig, jobject _this, ...) const;
jbyte callStaticByteMethod(jmethodID method, ...) const;
jbyte callStaticByteMethod(const char* name, const char* sig, ...) const;
jchar callCharMethod(jmethodID method, jobject _this, ...) const;
jchar callCharMethod(const char* name, const char* sig, jobject _this, ...) const;
jchar callStaticCharMethod(jmethodID method, ...) const;
jchar callStaticCharMethod(const char* name, const char* sig, ...) const;
jshort callShortMethod(jmethodID method, jobject _this, ...) const;
jshort callShortMethod(const char* name, const char* sig, jobject _this, ...) const;
jshort callStaticShortMethod(jmethodID method, ...) const;
jshort callStaticShortMethod(const char* name, const char* sig, ...) const;
jint callIntMethod(jmethodID method, jobject _this, ...) const;
jint callIntMethod(const char* name, const char* sig, jobject _this, ...) const;
jint callStaticIntMethod(jmethodID method, ...) const;
jint callStaticIntMethod(const char* name, const char* sig, ...) const;
jlong callLongMethod(jmethodID method, jobject _this, ...) const;
jlong callLongMethod(const char* name, const char* sig, jobject _this, ...) const;
jlong callStaticLongMethod(jmethodID method, ...) const;
jlong callStaticLongMethod(const char* name, const char* sig, ...) const;
jfloat callFloatMethod(jmethodID method, jobject _this, ...) const;
jfloat callFloatMethod(const char* name, const char* sig, jobject _this, ...) const;
jfloat callStaticFloatMethod(jmethodID method, ...) const;
jfloat callStaticFloatMethod(const char* name, const char* sig, ...) const;
jdouble callDoubleMethod(jmethodID method, jobject _this, ...) const;
jdouble callDoubleMethod(const char* name, const char* sig, jobject _this, ...) const;
jdouble callStaticDoubleMethod(jmethodID method, ...) const;
jdouble callStaticDoubleMethod(const char* name, const char* sig, ...) const;
void callVoidMethod(jmethodID method, jobject _this, ...) const;
void callVoidMethod(const char* name, const char* sig, jobject _this, ...) const;
void callStaticVoidMethod(jmethodID method, ...) const;
void callStaticVoidMethod(const char* name, const char* sig, ...) const;
String callStringMethod(jmethodID method, jobject _this, ...) const;
String callStringMethod(const char* name, const char* sig, jobject _this, ...) const;
String callStaticStringMethod(jmethodID method, ...) const;
String callStaticStringMethod(const char* name, const char* sig, ...) const;
jobject getObjectField(jfieldID field, jobject _this) const;
jobject getObjectField(const char* name, const char* sig, jobject _this) const;
void setObjectField(jfieldID field, jobject _this, jobject value) const;
void setObjectField(const char* name, const char* sig, jobject _this, jobject value) const;
jobject getStaticObjectField(jfieldID field) const;
jobject getStaticObjectField(const char* name, const char* sig) const;
void setStaticObjectField(jfieldID field, jobject value) const;
void setStaticObjectField(const char* name, const char* sig, jobject value) const;
jboolean getBooleanField(jfieldID field, jobject _this) const;
jboolean getBooleanField(const char* name, const char* sig, jobject _this) const;
void setBooleanField(jfieldID field, jobject _this, jboolean value) const;
void setBooleanField(const char* name, const char* sig, jobject _this, jboolean value) const;
jboolean getStaticBooleanField(jfieldID field) const;
jboolean getStaticBooleanField(const char* name, const char* sig) const;
void setStaticBooleanField(jfieldID field, jboolean value) const;
void setStaticBooleanField(const char* name, const char* sig, jboolean value) const;
jbyte getByteField(jfieldID field, jobject _this) const;
jbyte getByteField(const char* name, const char* sig, jobject _this) const;
void setByteField(jfieldID field, jobject _this, jbyte value) const;
void setByteField(const char* name, const char* sig, jobject _this, jbyte value) const;
jbyte getStaticByteField(jfieldID field) const;
jbyte getStaticByteField(const char* name, const char* sig) const;
void setStaticByteField(jfieldID field, jbyte value) const;
void setStaticByteField(const char* name, const char* sig, jbyte value) const;
jchar getCharField(jfieldID field, jobject _this) const;
jchar getCharField(const char* name, const char* sig, jobject _this) const;
void setCharField(jfieldID field, jobject _this, jchar value) const;
void setCharField(const char* name, const char* sig, jobject _this, jchar value) const;
jchar getStaticCharField(jfieldID field) const;
jchar getStaticCharField(const char* name, const char* sig) const;
void setStaticCharField(jfieldID field, jchar value) const;
void setStaticCharField(const char* name, const char* sig, jchar value) const;
jshort getShortField(jfieldID field, jobject _this) const;
jshort getShortField(const char* name, const char* sig, jobject _this) const;
void setShortField(jfieldID field, jobject _this, jshort value) const;
void setShortField(const char* name, const char* sig, jobject _this, jshort value) const;
jshort getStaticShortField(jfieldID field) const;
jshort getStaticShortField(const char* name, const char* sig) const;
void setStaticShortField(jfieldID field, jshort value) const;
void setStaticShortField(const char* name, const char* sig, jshort value) const;
jint getIntField(jfieldID field, jobject _this) const;
jint getIntField(const char* name, const char* sig, jobject _this) const;
void setIntField(jfieldID field, jobject _this, jint value) const;
void setIntField(const char* name, const char* sig, jobject _this, jint value) const;
jint getStaticIntField(jfieldID field) const;
jint getStaticIntField(const char* name, const char* sig) const;
void setStaticIntField(jfieldID field, jint value) const;
void setStaticIntField(const char* name, const char* sig, jint value) const;
jlong getLongField(jfieldID field, jobject _this) const;
jlong getLongField(const char* name, const char* sig, jobject _this) const;
void setLongField(jfieldID field, jobject _this, jlong value) const;
void setLongField(const char* name, const char* sig, jobject _this, jlong value) const;
jlong getStaticLongField(jfieldID field) const;
jlong getStaticLongField(const char* name, const char* sig) const;
void setStaticLongField(jfieldID field, jlong value) const;
void setStaticLongField(const char* name, const char* sig, jlong value) const;
jfloat getFloatField(jfieldID field, jobject _this) const;
jfloat getFloatField(const char* name, const char* sig, jobject _this) const;
void setFloatField(jfieldID field, jobject _this, jfloat value) const;
void setFloatField(const char* name, const char* sig, jobject _this, jfloat value) const;
jfloat getStaticFloatField(jfieldID field) const;
jfloat getStaticFloatField(const char* name, const char* sig) const;
void setStaticFloatField(jfieldID field, jfloat value) const;
void setStaticFloatField(const char* name, const char* sig, jfloat value) const;
jdouble getDoubleField(jfieldID field, jobject _this) const;
jdouble getDoubleField(const char* name, const char* sig, jobject _this) const;
void setDoubleField(jfieldID field, jobject _this, jdouble value) const;
void setDoubleField(const char* name, const char* sig, jobject _this, jdouble value) const;
jdouble getStaticDoubleField(jfieldID field) const;
jdouble getStaticDoubleField(const char* name, const char* sig) const;
void setStaticDoubleField(jfieldID field, jdouble value) const;
void setStaticDoubleField(const char* name, const char* sig, jdouble value) const;
String getStringField(jfieldID field, jobject _this) const;
String getStringField(const char* name, const char* sig, jobject _this) const;
String getStaticStringField(jfieldID field) const;
String getStaticStringField(const char* name, const char* sig) const;
void setStringField(jfieldID field, jobject _this, const StringParam& value) const;
void setStringField(const char* name, const char* sig, jobject _this, const StringParam& value) const;
void setStaticStringField(jfieldID field, const StringParam& value) const;
void setStaticStringField(const char* name, const char* sig, const StringParam& value) const;
sl_bool registerNative(const char* name, const char* sig, const void* fn) const;
};
class SLIB_EXPORT Jni
{
public:
static void initialize(JavaVM* jvm);
static void setSharedJVM(JavaVM* jvm);
static JavaVM* getSharedJVM();
// thread-storage
static JNIEnv* getCurrent();
static void setCurrent(JNIEnv* jni);
// attach and set current
static JNIEnv* attachThread(JavaVM* jvm = sl_null);
static void detachThread(JavaVM* jvm = sl_null);
// class
static JniClass getClass(const String& className);
static void registerClass(const String& className, jclass cls);
static void unregisterClass(const String& className);
static JniClass findClass(const char* className);
// object
static sl_bool isSameObject(jobject ref1, jobject ref2);
static jobjectRefType getRefType(jobject obj);
static sl_bool isInvalidRef(jobject obj);
static sl_bool isLocalRef(jobject obj);
static jobject newLocalRef(jobject obj);
static void deleteLocalRef(jobject obj);
static sl_bool isGlobalRef(jobject obj);
static jobject newGlobalRef(jobject obj);
static void deleteGlobalRef(jobject obj);
static sl_bool isWeakRef(jobject obj);
static jobject newWeakRef(jobject obj);
static void deleteWeakRef(jobject obj);
// string
static jstring getJniString(const StringParam& str);
static jstring getJniString(const sl_char16* str, const sl_size length);
static String getString(jstring str);
/*
* Array release<TYPE>ArrayElements Mode
* 0 - commit and free
* JNI_COMMIT - commit only
* JNI_ABORT - free only
*/
static sl_uint32 getArrayLength(jarray array);
static jobjectArray newObjectArray(jclass clsElement, sl_uint32 length);
static jobject getObjectArrayElement(jobjectArray array, sl_uint32 index);
static void setObjectArrayElement(jobjectArray array, sl_uint32 index, jobject value);
static jobjectArray newStringArray(sl_uint32 length);
static String getStringArrayElement(jobjectArray array, sl_uint32 index);
static void setStringArrayElement(jobjectArray array, sl_uint32 index, const StringParam& value);
static jbooleanArray newBooleanArray(sl_uint32 length);
static jboolean* getBooleanArrayElements(jbooleanArray array, jboolean* isCopy = sl_null);
static void releaseBooleanArrayElements(jbooleanArray array, jboolean* buf, jint mode = 0);
static void getBooleanArrayRegion(jbooleanArray array, sl_uint32 index, sl_uint32 len, jboolean* buf);
static void setBooleanArrayRegion(jbooleanArray array, sl_uint32 index, sl_uint32 len, jboolean* buf);
static jbyteArray newByteArray(sl_uint32 length);
static jbyte* getByteArrayElements(jbyteArray array, jboolean* isCopy);
static void releaseByteArrayElements(jbyteArray array, jbyte* buf, jint mode = 0);
static void getByteArrayRegion(jbyteArray array, sl_uint32 index, sl_uint32 len, jbyte* buf);
static void setByteArrayRegion(jbyteArray array, sl_uint32 index, sl_uint32 len, jbyte* buf);
static jcharArray newCharArray(sl_uint32 length);
static jchar* getCharArrayElements(jcharArray array, jboolean* isCopy = sl_null);
static void releaseCharArrayElements(jcharArray array, jchar* buf, jint mode = 0);
static void getCharArrayRegion(jcharArray array, sl_uint32 index, sl_uint32 len, jchar* buf);
static void setCharArrayRegion(jcharArray array, sl_uint32 index, sl_uint32 len, jchar* buf);
static jshortArray newShortArray(sl_uint32 length);
static jshort* getShortArrayElements(jshortArray array, jboolean* isCopy = sl_null);
static void releaseShortArrayElements(jshortArray array, jshort* buf, jint mode = 0);
static void getShortArrayRegion(jshortArray array, sl_uint32 index, sl_uint32 len, jshort* buf);
static void setShortArrayRegion(jshortArray array, sl_uint32 index, sl_uint32 len, jshort* buf);
static jintArray newIntArray(sl_uint32 length);
static jint* getIntArrayElements(jintArray array, jboolean* isCopy = sl_null);
static void releaseIntArrayElements(jintArray array, jint* buf, jint mode = 0);
static void getIntArrayRegion(jintArray array, sl_uint32 index, sl_uint32 len, jint* buf);
static void setIntArrayRegion(jintArray array, sl_uint32 index, sl_uint32 len, jint* buf);
static jlongArray newLongArray(sl_uint32 length);
static jlong* getLongArrayElements(jlongArray array, jboolean* isCopy = sl_null);
static void releaseLongArrayElements(jlongArray array, jlong* buf, jint mode = 0);
static void getLongArrayRegion(jlongArray array, sl_uint32 index, sl_uint32 len, jlong* buf);
static void setLongArrayRegion(jlongArray array, sl_uint32 index, sl_uint32 len, jlong* buf);
static jfloatArray newFloatArray(sl_uint32 length);
static jfloat* getFloatArrayElements(jfloatArray array, jboolean* isCopy = sl_null);
static void releaseFloatArrayElements(jfloatArray array, jfloat* buf, jint mode = 0);
static void getFloatArrayRegion(jfloatArray array, sl_uint32 index, sl_uint32 len, jfloat* buf);
static void setFloatArrayRegion(jfloatArray array, sl_uint32 index, sl_uint32 len, jfloat* buf);
static jdoubleArray newDoubleArray(sl_uint32 length);
static jdouble* getDoubleArrayElements(jdoubleArray array, jboolean* isCopy = sl_null);
static void releaseDoubleArrayElements(jdoubleArray array, jdouble* buf, jint mode = 0);
static void getDoubleArrayRegion(jdoubleArray array, sl_uint32 index, sl_uint32 len, jdouble* buf);
static void setDoubleArrayRegion(jdoubleArray array, sl_uint32 index, sl_uint32 len, jdouble* buf);
// direct buffer
static jobject newDirectByteBuffer(void* address, sl_size capacity);
static void* getDirectBufferAddress(jobject buf);
static sl_size getDirectBufferCapacity(jobject buf);
// exception
static sl_bool checkException();
static void clearException();
static void printException();
// input stream
static sl_int32 readFromInputStream(jobject stream, jbyteArray array);
static void closeInputStream(jobject stream);
};
}
#define SLIB_JNI_BEGIN_CLASS(CLASS, NAME) \
namespace CLASS \
{ \
static slib::priv::java::JClass _gcls(NAME); \
SLIB_INLINE slib::JniClass get() { \
return _gcls.cls; \
}
#define SLIB_JNI_END_CLASS \
}
#define SLIB_JNI_BEGIN_CLASS_SECTION(CLASS) \
namespace CLASS \
{ \
#define SLIB_JNI_END_CLASS_SECTION \
}
#define SLIB_JNI_NEW(VAR, SIG) static slib::priv::java::JMethod VAR(&_gcls, "<init>", SIG);
#define SLIB_JNI_METHOD(VAR, NAME, SIG) static slib::priv::java::JMethod VAR(&_gcls, NAME, SIG);
#define SLIB_JNI_STATIC_METHOD(VAR, NAME, SIG) static slib::priv::java::JStaticMethod VAR(&_gcls, NAME, SIG);
#define SLIB_JNI_FIELD(VAR, NAME, SIG) static slib::priv::java::JField VAR(&_gcls, NAME, SIG);
#define SLIB_JNI_OBJECT_FIELD(VAR, SIG) static slib::priv::java::JObjectField VAR(&_gcls, (#VAR), SIG);
#define SLIB_JNI_BOOLEAN_FIELD(VAR) static slib::priv::java::JBooleanField VAR(&_gcls, (#VAR));
#define SLIB_JNI_BYTE_FIELD(VAR) static slib::priv::java::JByteField VAR(&_gcls, (#VAR));
#define SLIB_JNI_CHAR_FIELD(VAR) static slib::priv::java::JCharField VAR(&_gcls, (#VAR));
#define SLIB_JNI_SHORT_FIELD(VAR) static slib::priv::java::JShortField VAR(&_gcls, (#VAR));
#define SLIB_JNI_INT_FIELD(VAR) static slib::priv::java::JIntField VAR(&_gcls, (#VAR));;
#define SLIB_JNI_LONG_FIELD(VAR) static slib::priv::java::JLongField VAR(&_gcls, (#VAR));
#define SLIB_JNI_FLOAT_FIELD(VAR) static slib::priv::java::JFloatField VAR(&_gcls, (#VAR));
#define SLIB_JNI_DOUBLE_FIELD(VAR) static slib::priv::java::JDoubleField VAR(&_gcls, (#VAR));
#define SLIB_JNI_STRING_FIELD(VAR) static slib::priv::java::JStringField VAR(&_gcls, (#VAR));
#define SLIB_JNI_STATIC_FIELD(VAR, NAME, SIG) static slib::priv::java::JStaticField VAR(&_gcls, NAME, SIG);
#define SLIB_JNI_STATIC_OBJECT_FIELD(VAR, SIG) static slib::priv::java::JStaticObjectField VAR(&_gcls, (#VAR), SIG);
#define SLIB_JNI_STATIC_BOOLEAN_FIELD(VAR) static slib::priv::java::JStaticBooleanField VAR(&_gcls, (#VAR));
#define SLIB_JNI_STATIC_BYTE_FIELD(VAR) static slib::priv::java::JStaticByteField VAR(&_gcls, (#VAR));
#define SLIB_JNI_STATIC_CHAR_FIELD(VAR) static slib::priv::java::JStaticCharField VAR(&_gcls, (#VAR));
#define SLIB_JNI_STATIC_SHORT_FIELD(VAR) static slib::priv::java::JStaticShortField VAR(&_gcls, (#VAR));
#define SLIB_JNI_STATIC_INT_FIELD(VAR) static slib::priv::java::JStaticIntField VAR(&_gcls, (#VAR));
#define SLIB_JNI_STATIC_LONG_FIELD(VAR) static slib::priv::java::JStaticLongField VAR(&_gcls, (#VAR));
#define SLIB_JNI_STATIC_FLOAT_FIELD(VAR) static slib::priv::java::JStaticFloatField VAR(&_gcls, (#VAR));
#define SLIB_JNI_STATIC_DOUBLE_FIELD(VAR) static slib::priv::java::JStaticDoubleField VAR(&_gcls, (#VAR));
#define SLIB_JNI_STATIC_STRING_FIELD(VAR) static slib::priv::java::JStaticStringField VAR(&_gcls, (#VAR));
#define SLIB_JNI_NATIVE(VAR, NAME, SIG, fn) static slib::priv::java::JNativeMethod VAR(&_gcls, NAME, SIG, (const void*)(fn));
#define SLIB_JNI_NATIVE_IMPL(VAR, NAME, SIG, RET, ...) \
static RET JNICALL JNativeMethodImpl_##VAR(JNIEnv* env, jobject _this, ##__VA_ARGS__); \
static slib::priv::java::JNativeMethod VAR(&_gcls, NAME, SIG, (const void*)(JNativeMethodImpl_##VAR)); \
RET JNICALL JNativeMethodImpl_##VAR(JNIEnv* env, jobject _this, ##__VA_ARGS__)
#include "detail/java.inc"
#endif
#endif
| 43.060837 | 125 | 0.753333 | [
"object"
] |
37a927fce5a05d6bf348487d585858add032d298 | 42,518 | h | C | usr/src/uts/common/io/bge/bge_impl.h | AsahiOS/gate | 283d47da4e17a5871d9d575e7ffb81e8f6c52e51 | [
"MIT"
] | null | null | null | usr/src/uts/common/io/bge/bge_impl.h | AsahiOS/gate | 283d47da4e17a5871d9d575e7ffb81e8f6c52e51 | [
"MIT"
] | null | null | null | usr/src/uts/common/io/bge/bge_impl.h | AsahiOS/gate | 283d47da4e17a5871d9d575e7ffb81e8f6c52e51 | [
"MIT"
] | 1 | 2020-12-30T00:04:16.000Z | 2020-12-30T00:04:16.000Z | /*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright (c) 2010-2013, by Broadcom, Inc.
* All Rights Reserved.
*/
/*
* Copyright (c) 2002, 2010, Oracle and/or its affiliates.
* All rights reserved.
*/
#ifndef _BGE_IMPL_H
#define _BGE_IMPL_H
#ifdef __cplusplus
extern "C" {
#endif
#include <sys/types.h>
#include <sys/stream.h>
#include <sys/strsun.h>
#include <sys/strsubr.h>
#include <sys/stat.h>
#include <sys/pci.h>
#include <sys/note.h>
#include <sys/modctl.h>
#include <sys/crc32.h>
#ifdef __sparcv9
#include <v9/sys/membar.h>
#endif /* __sparcv9 */
#include <sys/kstat.h>
#include <sys/ethernet.h>
#include <sys/errno.h>
#include <sys/dlpi.h>
#include <sys/devops.h>
#include <sys/debug.h>
#include <sys/conf.h>
#include <netinet/ip6.h>
#include <inet/common.h>
#include <inet/ip.h>
#include <inet/mi.h>
#include <inet/nd.h>
#include <sys/pattr.h>
#include <sys/disp.h>
#include <sys/cmn_err.h>
#include <sys/ddi.h>
#include <sys/sunddi.h>
#include <sys/ddifm.h>
#include <sys/fm/protocol.h>
#include <sys/fm/util.h>
#include <sys/fm/io/ddi.h>
#include <sys/mac_provider.h>
#include <sys/mac_ether.h>
#ifdef __amd64
#include <sys/x86_archext.h>
#endif
#ifndef VLAN_TAGSZ
#define VLAN_TAGSZ 4
#endif
#define BGE_STR_SIZE 32
#ifndef OFFSETOF
#define OFFSETOF(_s, _f) \
((uint32_t)((uint8_t *)(&((_s *)0)->_f) - \
(uint8_t *)((uint8_t *) 0)))
#endif
/*
* <sys/ethernet.h> *may* already have provided the typedef ether_addr_t;
* but of course C doesn't provide a way to check this directly. So here
* we rely on the fact that the symbol ETHERTYPE_AT was added to the
* header file (as a #define, which we *can* test for) at the same time
* as the typedef for ether_addr_t ;-!
*/
#ifndef ETHERTYPE_AT
typedef uchar_t ether_addr_t[ETHERADDRL];
#endif /* ETHERTYPE_AT */
/*
* Reconfiguring the network devices requires the net_config privilege
* in Solaris 10+.
*/
extern int secpolicy_net_config(const cred_t *, boolean_t);
#include <sys/miiregs.h> /* by fjlite out of intel */
#include "bge.h"
#include "bge_hw.h"
/*
* Compile-time feature switches ...
*/
#define BGE_DO_PPIO 0 /* peek/poke ioctls */
#define BGE_RX_SOFTINT 0 /* softint per receive ring */
#define BGE_CHOOSE_SEND_METHOD 0 /* send by copying only */
/*
* NOTES:
*
* #defines:
*
* BGE_PCI_CONFIG_RNUMBER and BGE_PCI_OPREGS_RNUMBER are the
* register-set numbers to use for the config space registers
* and the operating registers respectively. On an OBP-based
* machine, regset 0 refers to CONFIG space, and regset 1 will
* be the operating registers in MEMORY space. If an expansion
* ROM is fitted, it may appear as a further register set.
*
* BGE_DMA_MODE defines the mode (STREAMING/CONSISTENT) used
* for the data buffers. The descriptors are always set up
* in CONSISTENT mode.
*
* BGE_HEADROOM defines how much space we'll leave in allocated
* mblks before the first valid data byte. This should be chosen
* to be 2 modulo 4, so that once the ethernet header (14 bytes)
* has been stripped off, the packet data will be 4-byte aligned.
* The remaining space can be used by upstream modules to prepend
* any headers required.
*/
#define BGE_PCI_CONFIG_RNUMBER 0
#define BGE_PCI_OPREGS_RNUMBER 1
#define BGE_PCI_APEREGS_RNUMBER 2
#define BGE_DMA_MODE DDI_DMA_STREAMING
#define BGE_HEADROOM 34
/*
* BGE_HALFTICK is half the period of the cyclic callback (in
* nanoseconds), chosen so that 0.5s <= cyclic period <= 1s.
* Other time values are derived as odd multiples of this value
* so that there's little chance of ambiguity w.r.t. which tick
* a timeout expires on.
*
* BGE_PHY_STABLE_TIME is the period for which the contents of the
* PHY's status register must remain unchanging before we accept
* that the link has come up. [Sometimes the link comes up, only
* to go down again within a short time as the autonegotiation
* process cycles through various options before finding the best
* compatible mode. We don't want to report repeated link up/down
* cycles, so we wait until we think it's stable.]
*
* BGE_SERDES_STABLE_TIME is the analogous value for the SerDes
* interface. It's much shorter, 'cos the SerDes doesn't show
* these effects as much as the copper PHY.
*
* BGE_LINK_SETTLE_TIME is the period during which we regard link
* up/down cycles as an normal event after resetting/reprogramming
* the PHY. During this time, link up/down messages are sent to
* the log only, not the console. At any other time, link change
* events are regarded as unexpected and sent to both console & log.
*
* These latter two values have no theoretical justification, but
* are derived from observations and heuristics - the values below
* just seem to work quite well.
*/
#define BGE_HALFTICK 268435456LL /* 2**28 ns! */
#define BGE_CYCLIC_PERIOD (4*BGE_HALFTICK) /* ~1.0s */
#define BGE_CYCLIC_TIMEOUT (drv_usectohz(1000000)) /* ~1.0s */
#define BGE_SERDES_STABLE_TIME (3*BGE_HALFTICK) /* ~0.8s */
#define BGE_PHY_STABLE_TIME (11*BGE_HALFTICK) /* ~3.0s */
#define BGE_LINK_SETTLE_TIME (111*BGE_HALFTICK) /* ~30.0s */
/*
* Indices used to identify the different buffer rings internally
*/
#define BGE_STD_BUFF_RING 0
#define BGE_JUMBO_BUFF_RING 1
#define BGE_MINI_BUFF_RING 2
/*
* Current implementation limits
*/
#define BGE_BUFF_RINGS_USED 2 /* std & jumbo ring */
/* for now */
#define BGE_RECV_RINGS_USED 16 /* up to 16 rtn rings */
/* for now */
#define BGE_SEND_RINGS_USED 4 /* up to 4 tx rings */
/* for now */
#define BGE_HASH_TABLE_SIZE 128 /* may be 256 later */
/*
* Ring/buffer size parameters
*
* All of the (up to) 16 TX rings & and the corresponding buffers are the
* same size.
*
* Each of the (up to) 3 receive producer (aka buffer) rings is a different
* size and has different sized buffers associated with it too.
*
* The (up to) 16 receive return rings have no buffers associated with them.
* The number of slots per receive return ring must be 2048 if the mini
* ring is enabled, otherwise it may be 1024. See Broadcom document
* 570X-PG102-R page 56.
*
* Note: only the 5700 supported external memory (and therefore the mini
* ring); the 5702/3/4 don't. This driver doesn't support the original
* 5700, so we won't ever use the mini ring capability.
*/
#define BGE_SEND_RINGS_DEFAULT 1
#define BGE_RECV_RINGS_DEFAULT 1
#define BGE_SEND_BUFF_SIZE_DEFAULT 1536
#define BGE_SEND_BUFF_SIZE_JUMBO 9022
#define BGE_SEND_SLOTS_USED 512
#define BGE_STD_BUFF_SIZE 1536 /* 0x600 */
#define BGE_STD_SLOTS_USED 512
#define BGE_JUMBO_BUFF_SIZE 9022 /* 9k */
#define BGE_JUMBO_SLOTS_USED 256
#define BGE_MINI_BUFF_SIZE 128 /* 64? 256? */
#define BGE_MINI_SLOTS_USED 0 /* must be 0; see above */
#define BGE_RECV_BUFF_SIZE 0
#if BGE_MINI_SLOTS_USED > 0
#define BGE_RECV_SLOTS_USED 2048 /* required */
#else
#define BGE_RECV_SLOTS_USED 1024 /* could be 2048 anyway */
#endif
#define BGE_SEND_BUF_NUM 512
#define BGE_SEND_BUF_ARRAY 16
#define BGE_SEND_BUF_ARRAY_JUMBO 3
#define BGE_SEND_BUF_MAX (BGE_SEND_BUF_NUM*BGE_SEND_BUF_ARRAY)
/*
* PCI type. PCI-Express or PCI/PCIX
*/
#define BGE_PCI 0
#define BGE_PCI_E 1
#define BGE_PCI_X 2
/*
* Statistic type. There are two type of statistic:
* statistic block and statistic registers
*/
#define BGE_STAT_BLK 1
#define BGE_STAT_REG 2
/*
* MTU.for all chipsets ,the default is 1500 ,and some chipsets
* support 9k jumbo frames size
*/
#define BGE_DEFAULT_MTU 1500
#define BGE_MAXIMUM_MTU 9000
/*
* Pad the h/w defined status block (which can be up to 80 bytes long)
* to a power-of-two boundary
*/
#define BGE_STATUS_PADDING (128 - sizeof (bge_status_t))
/*
* On platforms which support DVMA, we can simply allocate one big piece
* of memory for all the Tx buffers and another for the Rx buffers, and
* then carve them up as required. It doesn't matter if they aren't just
* one physically contiguous piece each, because both the CPU *and* the
* I/O device can see them *as though they were*.
*
* However, if only physically-addressed DMA is possible, this doesn't
* work; we can't expect to get enough contiguously-addressed memory for
* all the buffers of each type, so in this case we request a number of
* smaller pieces, each still large enough for several buffers but small
* enough to fit within "an I/O page" (e.g. 64K).
*
* The #define below specifies how many pieces of memory are to be used;
* 16 has been shown to work on an i86pc architecture but this could be
* different on other non-DVMA platforms ...
*/
#ifdef _DMA_USES_VIRTADDR
#define BGE_SPLIT 1 /* no split required */
#else
#if ((BGE_BUFF_RINGS_USED > 1) || (BGE_SEND_RINGS_USED > 1) || \
(BGE_RECV_RINGS_USED > 1))
#define BGE_SPLIT 128 /* split 128 ways */
#else
#define BGE_SPLIT 16 /* split 16 ways */
#endif
#endif /* _DMA_USES_VIRTADDR */
#define BGE_RECV_RINGS_SPLIT (BGE_RECV_RINGS_MAX + 1)
/*
* STREAMS parameters
*/
#define BGE_IDNUM 0 /* zero seems to work */
#define BGE_LOWAT (256)
#define BGE_HIWAT (256*1024)
/*
* Basic data types, for clarity in distinguishing 'numbers'
* used for different purposes ...
*
* A <bge_regno_t> is a register 'address' (offset) in any one of
* various address spaces (PCI config space, PCI memory-mapped I/O
* register space, MII registers, etc). None of these exceeds 64K,
* so we could use a 16-bit representation but pointer-sized objects
* are more "natural" in most architectures; they seem to be handled
* more efficiently on SPARC and no worse on x86.
*
* BGE_REGNO_NONE represents the non-existent value in this space.
*/
typedef uintptr_t bge_regno_t; /* register # (offset) */
#define BGE_REGNO_NONE (~(uintptr_t)0u)
/*
* Describes one chunk of allocated DMA-able memory
*
* In some cases, this is a single chunk as allocated from the system;
* but we also use this structure to represent slices carved off such
* a chunk. Even when we don't really need all the information, we
* use this structure as a convenient way of correlating the various
* ways of looking at a piece of memory (kernel VA, IO space DVMA,
* handle+offset, etc).
*/
typedef struct {
ddi_acc_handle_t acc_hdl; /* handle for memory */
void *mem_va; /* CPU VA of memory */
uint32_t nslots; /* number of slots */
uint32_t size; /* size per slot */
size_t alength; /* allocated size */
/* >= product of above */
ddi_dma_handle_t dma_hdl; /* DMA handle */
offset_t offset; /* relative to handle */
ddi_dma_cookie_t cookie; /* associated cookie */
uint32_t ncookies; /* must be 1 */
uint32_t token; /* arbitrary identifier */
} dma_area_t; /* 0x50 (80) bytes */
typedef struct bge_queue_item {
struct bge_queue_item *next;
void *item;
} bge_queue_item_t;
typedef struct bge_queue {
bge_queue_item_t *head;
uint32_t count;
kmutex_t *lock;
} bge_queue_t;
/*
* Software version of the Receive Buffer Descriptor
* There's one of these for each receive buffer (up to 256/512/1024 per ring).
*/
typedef struct sw_rbd {
dma_area_t pbuf; /* (const) related */
/* buffer area */
} sw_rbd_t; /* 0x50 (80) bytes */
/*
* Software Receive Buffer (Producer) Ring Control Block
* There's one of these for each receiver producer ring (up to 3),
* but each holds buffers of a different size.
*/
typedef struct buff_ring {
dma_area_t desc; /* (const) related h/w */
/* descriptor area */
dma_area_t buf[BGE_SPLIT]; /* (const) related */
/* buffer area(s) */
bge_rcb_t hw_rcb; /* (const) image of h/w */
/* RCB, and used to */
struct bge *bgep; /* (const) containing */
/* driver soft state */
/* initialise same */
volatile uint16_t *cons_index_p; /* (const) ptr to h/w */
/* "consumer index" */
/* (in status block) */
/*
* The rf_lock must be held when updating the h/w producer index
* mailbox register (*chip_mbox_reg), or the s/w producer index
* (rf_next).
*/
bge_regno_t chip_mbx_reg; /* (const) h/w producer */
/* index mailbox offset */
kmutex_t rf_lock[1]; /* serialize refill */
uint64_t rf_next; /* next slot to refill */
/* ("producer index") */
sw_rbd_t *sw_rbds; /* software descriptors */
void *spare[4]; /* padding */
} buff_ring_t; /* 0x100 (256) bytes */
typedef struct bge_multi_mac {
int naddr; /* total supported addresses */
int naddrfree; /* free addresses slots */
ether_addr_t mac_addr[MAC_ADDRESS_REGS_MAX];
boolean_t mac_addr_set[MAC_ADDRESS_REGS_MAX];
} bge_multi_mac_t;
/*
* Software Receive (Return) Ring Control Block
* There's one of these for each receiver return ring (up to 16).
*/
typedef struct recv_ring {
/*
* The elements flagged (const) in the comments below are
* set up once during initialiation and thereafter unchanged.
*/
dma_area_t desc; /* (const) related h/w */
/* descriptor area */
bge_rcb_t hw_rcb; /* (const) image of h/w */
/* RCB, and used to */
/* initialise same */
struct bge *bgep; /* (const) containing */
/* driver soft state */
ddi_softintr_t rx_softint; /* (const) per-ring */
/* receive callback */
volatile uint16_t *prod_index_p; /* (const) ptr to h/w */
/* "producer index" */
/* (in status block) */
/*
* The rx_lock must be held when updating the h/w consumer index
* mailbox register (*chip_mbox_reg), or the s/w consumer index
* (rx_next).
*/
bge_regno_t chip_mbx_reg; /* (const) h/w consumer */
/* index mailbox offset */
kmutex_t rx_lock[1]; /* serialize receive */
uint64_t rx_next; /* next slot to examine */
mac_ring_handle_t ring_handle;
mac_group_handle_t ring_group_handle;
uint64_t ring_gen_num;
bge_rule_info_t *mac_addr_rule;
uint8_t mac_addr_val[ETHERADDRL];
int poll_flag; /* Polling flag */
/* Per-ring statistics */
uint64_t rx_pkts; /* Received Packets Count */
uint64_t rx_bytes; /* Received Bytes Count */
} recv_ring_t;
/*
* Send packet structure
*/
typedef struct send_pkt {
uint16_t vlan_tci;
uint32_t pflags;
boolean_t tx_ready;
bge_queue_item_t *txbuf_item;
} send_pkt_t;
/*
* Software version of tx buffer structure
*/
typedef struct sw_txbuf {
dma_area_t buf;
uint32_t copy_len;
} sw_txbuf_t;
/*
* Software version of the Send Buffer Descriptor
* There's one of these for each send buffer (up to 512 per ring)
*/
typedef struct sw_sbd {
dma_area_t desc; /* (const) related h/w */
/* descriptor area */
bge_queue_item_t *pbuf; /* (const) related */
/* buffer area */
} sw_sbd_t;
/*
* Software Send Ring Control Block
* There's one of these for each of (up to) 16 send rings
*/
typedef struct send_ring {
/*
* The elements flagged (const) in the comments below are
* set up once during initialiation and thereafter unchanged.
*/
dma_area_t desc; /* (const) related h/w */
/* descriptor area */
dma_area_t buf[BGE_SEND_BUF_ARRAY][BGE_SPLIT];
/* buffer area(s) */
bge_rcb_t hw_rcb; /* (const) image of h/w */
/* RCB, and used to */
/* initialise same */
struct bge *bgep; /* (const) containing */
/* driver soft state */
volatile uint16_t *cons_index_p; /* (const) ptr to h/w */
/* "consumer index" */
/* (in status block) */
bge_regno_t chip_mbx_reg; /* (const) h/w producer */
/* index mailbox offset */
/*
* Tx buffer queue
*/
bge_queue_t txbuf_queue;
bge_queue_t freetxbuf_queue;
bge_queue_t *txbuf_push_queue;
bge_queue_t *txbuf_pop_queue;
kmutex_t txbuf_lock[1];
kmutex_t freetxbuf_lock[1];
bge_queue_item_t *txbuf_head;
send_pkt_t *pktp;
uint64_t txpkt_next;
uint64_t txfill_next;
sw_txbuf_t *txbuf;
uint32_t tx_buffers;
uint32_t tx_buffers_low;
uint32_t tx_array_max;
uint32_t tx_array;
kmutex_t tx_lock[1]; /* serialize h/w update */
/* ("producer index") */
uint64_t tx_next; /* next slot to use */
uint64_t tx_flow; /* # concurrent sends */
uint64_t tx_block;
uint64_t tx_nobd;
uint64_t tx_nobuf;
uint64_t tx_alloc_fail;
/*
* These counters/indexes are manipulated in the transmit
* path using atomics rather than mutexes for speed
*/
uint64_t tx_free; /* # of slots available */
/*
* The tc_lock must be held while manipulating the s/w consumer
* index (tc_next).
*/
kmutex_t tc_lock[1]; /* serialize recycle */
uint64_t tc_next; /* next slot to recycle */
/* ("consumer index") */
sw_sbd_t *sw_sbds; /* software descriptors */
uint64_t mac_resid; /* special per resource id */
uint64_t pushed_bytes;
} send_ring_t; /* 0x100 (256) bytes */
typedef struct {
ether_addr_t addr; /* in canonical form */
uint8_t spare;
boolean_t set; /* B_TRUE => valid */
} bge_mac_addr_t;
/*
* The original 5700/01 supported only SEEPROMs. Later chips (5702+)
* support both SEEPROMs (using the same 2-wire CLK/DATA interface for
* the hardware and a backwards-compatible software access method), and
* buffered or unbuffered FLASH devices connected to the 4-wire SPI bus
* and using a new software access method.
*
* The access methods for SEEPROM and Flash are generally similar, with
* the chip handling the serialisation/deserialisation and handshaking,
* but the registers used are different, as are a few details of the
* protocol, and the timing, so we have to determine which (if any) is
* fitted.
*
* The value UNKNOWN means just that; we haven't yet tried to determine
* the device type.
*
* The value NONE can indicate either that a real and definite absence of
* any NVmem has been detected, or that there may be NVmem but we can't
* determine its type, perhaps because the NVconfig pins on the chip have
* been wired up incorrectly. In either case, access to the NVmem (if any)
* is not supported.
*/
enum bge_nvmem_type {
BGE_NVTYPE_NONE = -1, /* (or indeterminable) */
BGE_NVTYPE_UNKNOWN, /* not yet checked */
BGE_NVTYPE_SEEPROM, /* BCM5700/5701 only */
BGE_NVTYPE_LEGACY_SEEPROM, /* 5702+ */
BGE_NVTYPE_UNBUFFERED_FLASH, /* 5702+ */
BGE_NVTYPE_BUFFERED_FLASH /* 5702+ */
};
/*
* Describes the characteristics of a specific chip
*
* Note: elements from <businfo> to <latency> are filled in by during
* the first phase of chip initialisation (see bge_chip_cfg_init()).
* The remaining ones are determined just after the first RESET, in
* bge_poll_firmware(). Thereafter, the entire structure is readonly.
*/
typedef struct {
uint32_t asic_rev; /* masked from MHCR */
uint32_t asic_rev_prod_id; /* new revision ID format */
uint32_t businfo; /* from private reg */
uint16_t command; /* saved during attach */
uint16_t vendor; /* vendor-id */
uint16_t device; /* device-id */
uint16_t subven; /* subsystem-vendor-id */
uint16_t subdev; /* subsystem-id */
uint8_t revision; /* revision-id */
uint8_t clsize; /* cache-line-size */
uint8_t latency; /* latency-timer */
uint8_t flags;
uint16_t chip_label; /* numeric part only */
/* (e.g. 5703/5794/etc) */
uint32_t mbuf_base; /* Mbuf pool parameters */
uint32_t mbuf_length; /* depend on chiptype */
uint32_t pci_type;
uint32_t statistic_type;
uint32_t bge_dma_rwctrl;
uint32_t bge_mlcr_default;
uint32_t recv_slots; /* receive ring size */
enum bge_nvmem_type nvtype; /* SEEPROM or Flash */
uint16_t jumbo_slots;
uint16_t ethmax_size;
uint16_t snd_buff_size;
uint16_t recv_jumbo_size;
uint16_t std_buf_size;
uint32_t mbuf_hi_water;
uint32_t mbuf_lo_water_rmac;
uint32_t mbuf_lo_water_rdma;
uint32_t rx_rings; /* from bge.conf */
uint32_t tx_rings; /* from bge.conf */
uint32_t eee; /* from bge.conf */
uint32_t default_mtu; /* from bge.conf */
uint64_t hw_mac_addr; /* from chip register */
bge_mac_addr_t vendor_addr; /* transform of same */
boolean_t msi_enabled; /* default to true */
uint32_t rx_ticks_norm;
uint32_t rx_count_norm;
uint32_t tx_ticks_norm;
uint32_t tx_count_norm;
uint32_t mask_pci_int;
} chip_id_t;
#define CHIP_FLAG_SUPPORTED 0x80
#define CHIP_FLAG_SERDES 0x40
#define CHIP_FLAG_PARTIAL_CSUM 0x20
#define CHIP_FLAG_NO_JUMBO 0x1
/*
* Collection of physical-layer functions to:
* (re)initialise the physical layer
* update it to match software settings
* check for link status change
*/
typedef struct {
int (*phys_restart)(struct bge *, boolean_t);
int (*phys_update)(struct bge *);
boolean_t (*phys_check)(struct bge *, boolean_t);
} phys_ops_t;
/*
* Actual state of the BCM570x chip
*/
enum bge_chip_state {
BGE_CHIP_FAULT = -2, /* fault, need reset */
BGE_CHIP_ERROR, /* error, want reset */
BGE_CHIP_INITIAL, /* Initial state only */
BGE_CHIP_RESET, /* reset, need init */
BGE_CHIP_STOPPED, /* Tx/Rx stopped */
BGE_CHIP_RUNNING /* with interrupts */
};
enum bge_mac_state {
BGE_MAC_STOPPED = 0,
BGE_MAC_STARTED
};
/*
* (Internal) return values from ioctl subroutines
*/
enum ioc_reply {
IOC_INVAL = -1, /* bad, NAK with EINVAL */
IOC_DONE, /* OK, reply sent */
IOC_ACK, /* OK, just send ACK */
IOC_REPLY, /* OK, just send reply */
IOC_RESTART_ACK, /* OK, restart & ACK */
IOC_RESTART_REPLY /* OK, restart & reply */
};
/*
* (Internal) return values from send_msg subroutines
*/
enum send_status {
SEND_FAIL = -1, /* Not OK */
SEND_KEEP, /* OK, msg queued */
SEND_FREE /* OK, free msg */
};
/*
* (Internal) enumeration of this driver's kstats
*/
enum {
BGE_KSTAT_RAW = 0,
BGE_KSTAT_STATS,
BGE_KSTAT_CHIPID,
BGE_KSTAT_DRIVER,
BGE_KSTAT_PHYS,
BGE_KSTAT_COUNT
};
#define BGE_MAX_RESOURCES 255
/*
* Per-instance soft-state structure
*/
typedef struct bge {
/*
* These fields are set by attach() and unchanged thereafter ...
*/
char version[BGE_STR_SIZE];
#define BGE_FW_VER_SIZE 32
char fw_version[BGE_FW_VER_SIZE];
dev_info_t *devinfo; /* device instance */
uint32_t pci_bus; /* from "regs" prop */
uint32_t pci_dev; /* from "regs" prop */
uint32_t pci_func; /* from "regs" prop */
mac_handle_t mh; /* mac module handle */
ddi_acc_handle_t cfg_handle; /* DDI I/O handle */
ddi_acc_handle_t io_handle; /* DDI I/O handle */
void *io_regs; /* mapped registers */
ddi_acc_handle_t ape_handle; /* DDI I/O handle */
void *ape_regs; /* mapped registers */
boolean_t ape_enabled;
boolean_t ape_has_ncsi;
ddi_periodic_t periodic_id; /* periodical callback */
ddi_softintr_t factotum_id; /* factotum callback */
ddi_softintr_t drain_id; /* reschedule callback */
ddi_intr_handle_t *htable; /* For array of interrupts */
int intr_type; /* What type of interrupt */
int intr_cnt; /* # of intrs count returned */
uint_t intr_pri; /* Interrupt priority */
int intr_cap; /* Interrupt capabilities */
uint32_t progress; /* attach tracking */
uint32_t debug; /* per-instance debug */
chip_id_t chipid;
const phys_ops_t *physops;
char ifname[8]; /* "bge0" ... "bge999" */
int fm_capabilities; /* FMA capabilities */
/*
* These structures describe the blocks of memory allocated during
* attach(). They remain unchanged thereafter, although the memory
* they describe is carved up into various separate regions and may
* therefore be described by other structures as well.
*/
dma_area_t tx_desc; /* transmit descriptors */
dma_area_t rx_desc[BGE_RECV_RINGS_SPLIT];
/* receive descriptors */
dma_area_t tx_buff[BGE_SPLIT];
dma_area_t rx_buff[BGE_SPLIT];
/*
* The memory described by the <dma_area> structures above
* is carved up into various pieces, which are described by
* the structures below.
*/
dma_area_t statistics; /* describes hardware */
/* statistics area */
dma_area_t status_block; /* describes hardware */
/* status block */
/*
* For the BCM5705/5788/5721/5751/5752/5714 and 5715,
* the statistic block is not available,the statistic counter must
* be gotten from statistic registers. And bge_statistics_reg_t record
* the statistic registers value.
*/
bge_statistics_reg_t *pstats;
/*
* Runtime read-write data starts here ...
*
* 3 Buffer Rings (std/jumbo/mini)
* 16 Receive (Return) Rings
* 16 Send Rings
*
* Note: they're not necessarily all used.
*/
buff_ring_t buff[BGE_BUFF_RINGS_MAX]; /* 3*0x0100 */
/* may be obsoleted */
recv_ring_t recv[BGE_RECV_RINGS_MAX]; /* 16*0x0090 */
send_ring_t send[BGE_SEND_RINGS_MAX]; /* 16*0x0100 */
mac_resource_handle_t macRxResourceHandles[BGE_RECV_RINGS_MAX];
/*
* Locks:
*
* Each buffer ring contains its own <rf_lock> which regulates
* ring refilling.
*
* Each receive (return) ring contains its own <rx_lock> which
* protects the critical cyclic counters etc.
*
* Each send ring contains two locks: <tx_lock> for the send-path
* protocol data and <tc_lock> for send-buffer recycling.
*
* Finally <genlock> is a general lock, protecting most other
* operational data in the state structure and chip register
* accesses. It is acquired by the interrupt handler and
* most "mode-control" routines.
*
* Any of the locks can be acquired singly, but where multiple
* locks are acquired, they *must* be in the order:
*
* genlock >>> rx_lock >>> rf_lock >>> tx_lock >>> tc_lock.
*
* and within any one class of lock the rings must be locked in
* ascending order (send[0].tc_lock >>> send[1].tc_lock), etc.
*
* Note: actually I don't believe there's any need to acquire
* locks on multiple rings, or even locks of all these classes
* concurrently; but I've set out the above order so there is a
* clear definition of lock hierarchy in case it's ever needed.
*
* Note: the combinations of locks that are actually held
* concurrently are:
*
* genlock >>> (bge_chip_interrupt())
* rx_lock[i] >>> (bge_receive())
* rf_lock[n] (bge_refill())
* tc_lock[i] (bge_recycle())
*/
kmutex_t genlock[1];
krwlock_t errlock[1];
kmutex_t softintrlock[1];
/*
* Current Ethernet addresses and multicast hash (bitmap) and
* refcount tables, protected by <genlock>
*/
bge_mac_addr_t curr_addr[MAC_ADDRESS_REGS_MAX];
uint32_t mcast_hash[BGE_HASH_TABLE_SIZE/32];
uint8_t mcast_refs[BGE_HASH_TABLE_SIZE];
uint32_t unicst_addr_total; /* total unicst addresses */
uint32_t unicst_addr_avail;
/* unused unicst addr slots */
/*
* Link state data (protected by genlock)
*/
link_state_t link_state;
/*
* Physical layer: copper only
*/
bge_regno_t phy_mii_addr; /* should be (const) 1! */
uint16_t phy_gen_status;
uint16_t phy_aux_status;
/*
* Physical layer: serdes only
*/
uint32_t serdes_status;
uint32_t serdes_advert;
uint32_t serdes_lpadv;
/*
* Driver kstats, protected by <genlock> where necessary
*/
kstat_t *bge_kstats[BGE_KSTAT_COUNT];
/*
* Miscellaneous operating variables (protected by genlock)
*/
uint64_t chip_resets; /* # of chip RESETs */
uint64_t missed_dmas; /* # of missed DMAs */
uint64_t missed_updates; /* # of missed updates */
enum bge_mac_state bge_mac_state; /* definitions above */
enum bge_chip_state bge_chip_state; /* definitions above */
boolean_t send_hw_tcp_csum;
boolean_t recv_hw_tcp_csum;
boolean_t promisc;
boolean_t manual_reset;
/*
* Miscellaneous operating variables (not synchronised)
*/
uint32_t watchdog; /* watches for Tx stall */
boolean_t bge_intr_running;
boolean_t bge_dma_error;
boolean_t tx_resched_needed;
uint64_t tx_resched;
uint32_t factotum_flag; /* softint pending */
uintptr_t pagemask;
boolean_t rdma_length_bug_on_5719;
/*
* NDD parameters (protected by genlock)
*/
caddr_t nd_data_p;
/*
* A flag to prevent excessive config space accesses
* on platforms having BCM5714C/15C
*/
boolean_t lastWriteZeroData;
/*
* Spare space, plus guard element used to check data integrity
*/
uint64_t spare[5];
uint64_t bge_guard;
/*
* Receive rules configure
*/
bge_recv_rule_t recv_rules[RECV_RULES_NUM_MAX];
#ifdef BGE_IPMI_ASF
boolean_t asf_enabled;
boolean_t asf_wordswapped;
boolean_t asf_newhandshake;
boolean_t asf_pseudostop;
uint32_t asf_status;
timeout_id_t asf_timeout_id;
#endif
uint32_t param_en_pause:1,
param_en_asym_pause:1,
param_en_1000hdx:1,
param_en_1000fdx:1,
param_en_100fdx:1,
param_en_100hdx:1,
param_en_10fdx:1,
param_en_10hdx:1,
param_adv_autoneg:1,
param_adv_1000fdx:1,
param_adv_1000hdx:1,
param_adv_100fdx:1,
param_adv_100hdx:1,
param_adv_10fdx:1,
param_adv_10hdx:1,
param_lp_autoneg:1,
param_lp_pause:1,
param_lp_asym_pause:1,
param_lp_1000fdx:1,
param_lp_1000hdx:1,
param_lp_100fdx:1,
param_lp_100hdx:1,
param_lp_10fdx:1,
param_lp_10hdx:1,
param_link_up:1,
param_link_autoneg:1,
param_adv_pause:1,
param_adv_asym_pause:1,
param_link_rx_pause:1,
param_link_tx_pause:1,
param_pad_to_32:2;
uint32_t param_loop_mode;
uint32_t param_msi_cnt;
uint32_t param_drain_max;
uint64_t param_link_speed;
link_duplex_t param_link_duplex;
uint32_t eee_lpi_wait;
uint64_t timestamp;
} bge_t;
#define CATC_TRIGGER(bgep, data) bge_reg_put32(bgep, 0x0a00, (data))
/*
* 'Progress' bit flags ...
*/
#define PROGRESS_CFG 0x0001 /* config space mapped */
#define PROGRESS_REGS 0x0002 /* registers mapped */
#define PROGRESS_BUFS 0x0004 /* ring buffers allocated */
#define PROGRESS_RESCHED 0x0010 /* resched softint registered */
#define PROGRESS_FACTOTUM 0x0020 /* factotum softint registered */
#define PROGRESS_HWINT 0x0040 /* h/w interrupt registered */
/* and mutexen initialised */
#define PROGRESS_INTR 0x0080 /* Intrs enabled */
#define PROGRESS_PHY 0x0100 /* PHY initialised */
#define PROGRESS_NDD 0x1000 /* NDD parameters set up */
#define PROGRESS_KSTATS 0x2000 /* kstats created */
#define PROGRESS_READY 0x8000 /* ready for work */
/*
* Sync a DMA area described by a dma_area_t
*/
#define DMA_SYNC(area, flag) ((void) ddi_dma_sync((area).dma_hdl, \
(area).offset, (area).alength, (flag)))
/*
* Find the (kernel virtual) address of block of memory
* described by a dma_area_t
*/
#define DMA_VPTR(area) ((area).mem_va)
/*
* Zero a block of memory described by a dma_area_t
*/
#define DMA_ZERO(area) bzero(DMA_VPTR(area), (area).alength)
/*
* Next value of a cyclic index
*/
#define NEXT(index, limit) ((index)+1 < (limit) ? (index)+1 : 0)
/*
* Property lookups
*/
#define BGE_PROP_EXISTS(d, n) ddi_prop_exists(DDI_DEV_T_ANY, (d), \
DDI_PROP_DONTPASS, (n))
#define BGE_PROP_GET_INT(d, n) ddi_prop_get_int(DDI_DEV_T_ANY, (d), \
DDI_PROP_DONTPASS, (n), -1)
/*
* Copy an ethernet address
*/
#define ethaddr_copy(src, dst) bcopy((src), (dst), ETHERADDRL)
/*
* Endian swap
*/
/* BEGIN CSTYLED */
#define BGE_BSWAP_32(x) ((((x) & 0xff000000) >> 24) | \
(((x) & 0x00ff0000) >> 8) | \
(((x) & 0x0000ff00) << 8) | \
(((x) & 0x000000ff) << 24))
/* END CSTYLED */
/*
* Marker value placed at the end of the driver's state
*/
#define BGE_GUARD 0x1919306009031802
/*
* Bit flags in the 'debug' word ...
*/
#define BGE_DBG_STOP 0x00000001 /* early debug_enter() */
#define BGE_DBG_TRACE 0x00000002 /* general flow tracing */
#define BGE_DBG_APE 0x00000004 /* low-level APE access */
#define BGE_DBG_HPSD 0x00000008 /* low-level HPSD access*/
#define BGE_DBG_REGS 0x00000010 /* low-level accesses */
#define BGE_DBG_MII 0x00000020 /* low-level MII access */
#define BGE_DBG_SEEPROM 0x00000040 /* low-level SEEPROM IO */
#define BGE_DBG_CHIP 0x00000080 /* low(ish)-level code */
#define BGE_DBG_RECV 0x00000100 /* receive-side code */
#define BGE_DBG_SEND 0x00000200 /* packet-send code */
#define BGE_DBG_INT 0x00001000 /* interrupt handler */
#define BGE_DBG_FACT 0x00002000 /* factotum (softint) */
#define BGE_DBG_PHY 0x00010000 /* Copper PHY code */
#define BGE_DBG_SERDES 0x00020000 /* SerDes code */
#define BGE_DBG_PHYS 0x00040000 /* Physical layer code */
#define BGE_DBG_LINK 0x00080000 /* Link status check */
#define BGE_DBG_INIT 0x00100000 /* initialisation */
#define BGE_DBG_NEMO 0x00200000 /* nemo interaction */
#define BGE_DBG_ADDR 0x00400000 /* address-setting code */
#define BGE_DBG_STATS 0x00800000 /* statistics */
#define BGE_DBG_IOCTL 0x01000000 /* ioctl handling */
#define BGE_DBG_LOOP 0x02000000 /* loopback ioctl code */
#define BGE_DBG_PPIO 0x04000000 /* Peek/poke ioctls */
#define BGE_DBG_BADIOC 0x08000000 /* unknown ioctls */
#define BGE_DBG_MCTL 0x10000000 /* mctl (csum) code */
#define BGE_DBG_NDD 0x20000000 /* NDD operations */
#define BGE_DBG_MEM 0x40000000 /* memory allocations and chunking */
/*
* Debugging ...
*/
#ifdef DEBUG
#define BGE_DEBUGGING 1
#else
#define BGE_DEBUGGING 0
#endif /* DEBUG */
/*
* 'Do-if-debugging' macro. The parameter <command> should be one or more
* C statements (but without the *final* semicolon), which will either be
* compiled inline or completely ignored, depending on the BGE_DEBUGGING
* compile-time flag.
*
* You should get a compile-time error (at least on a DEBUG build) if
* your statement isn't actually a statement, rather than unexpected
* run-time behaviour caused by unintended matching of if-then-elses etc.
*
* Note that the BGE_DDB() macro itself can only be used as a statement,
* not an expression, and should always be followed by a semicolon.
*/
#if BGE_DEBUGGING
#define BGE_DDB(command) do { \
{ command; } \
_NOTE(CONSTANTCONDITION) \
} while (0)
#else /* BGE_DEBUGGING */
#define BGE_DDB(command) do { \
{ _NOTE(EMPTY); } \
_NOTE(CONSTANTCONDITION) \
} while (0)
#endif /* BGE_DEBUGGING */
/*
* 'Internal' macros used to construct the TRACE/DEBUG macros below.
* These provide the primitive conditional-call capability required.
* Note: the parameter <args> is a parenthesised list of the actual
* printf-style arguments to be passed to the debug function ...
*/
#define BGE_XDB(b, w, f, args) BGE_DDB(if ((b) & (w)) f args)
#define BGE_GDB(b, args) BGE_XDB(b, bge_debug, (*bge_gdb()), args)
#define BGE_LDB(b, args) BGE_XDB(b, bgep->debug, (*bge_db(bgep)), args)
#define BGE_CDB(f, args) BGE_XDB(BGE_DBG, bgep->debug, f, args)
#define DEVNAME(_sc) ((_sc)->ifname)
#define DPRINTF(f, ...) do { cmn_err(CE_NOTE, (f), __VA_ARGS__); } while (0)
/*
* Conditional-print macros.
*
* Define BGE_DBG to be the relevant member of the set of BGE_DBG_* values
* above before using the BGE_GDEBUG() or BGE_DEBUG() macros. The 'G'
* versions look at the Global debug flag word (bge_debug); the non-G
* versions look in the per-instance data (bgep->debug) and so require a
* variable called 'bgep' to be in scope (and initialised!) before use.
*
* You could redefine BGE_TRC too if you really need two different
* flavours of debugging output in the same area of code, but I don't
* really recommend it.
*
* Note: the parameter <args> is a parenthesised list of the actual
* arguments to be passed to the debug function, usually a printf-style
* format string and corresponding values to be formatted.
*/
#define BGE_TRC BGE_DBG_TRACE /* default 'trace' bit */
#define BGE_GTRACE(args) BGE_GDB(BGE_TRC, args)
#define BGE_GDEBUG(args) BGE_GDB(BGE_DBG, args)
#define BGE_TRACE(args) BGE_LDB(BGE_TRC, args)
#define BGE_DEBUG(args) BGE_LDB(BGE_DBG, args)
/*
* Debug-only action macros
*/
#define BGE_BRKPT(bgep, s) BGE_DDB(bge_dbg_enter(bgep, s))
#define BGE_MARK(bgep) BGE_DDB(bge_led_mark(bgep))
#define BGE_PCICHK(bgep) BGE_DDB(bge_pci_check(bgep))
#define BGE_PKTDUMP(args) BGE_DDB(bge_pkt_dump args)
#define BGE_REPORT(args) BGE_DDB(bge_log args)
/*
* Inter-source-file linkage ...
*/
/* bge_chip.c */
uint16_t bge_mii_get16(bge_t *bgep, bge_regno_t regno);
void bge_mii_put16(bge_t *bgep, bge_regno_t regno, uint16_t value);
uint16_t bge_phydsp_read(bge_t *bgep, bge_regno_t regno);
void bge_phydsp_write(bge_t *bgep, bge_regno_t regno, uint16_t value);
uint32_t bge_reg_get32(bge_t *bgep, bge_regno_t regno);
void bge_reg_put32(bge_t *bgep, bge_regno_t regno, uint32_t value);
void bge_reg_set32(bge_t *bgep, bge_regno_t regno, uint32_t bits);
void bge_reg_clr32(bge_t *bgep, bge_regno_t regno, uint32_t bits);
uint32_t bge_ape_get32(bge_t *bgep, bge_regno_t regno);
void bge_ape_put32(bge_t *bgep, bge_regno_t regno, uint32_t value);
void bge_mbx_put(bge_t *bgep, bge_regno_t regno, uint64_t value);
void bge_ape_lock_init(bge_t *bgep);
int bge_ape_scratchpad_read(bge_t *bgep, uint32_t *data, uint32_t base_off, uint32_t lenToRead);
int bge_ape_scratchpad_write(bge_t *bgep, uint32_t dstoff, uint32_t *data, uint32_t lenToWrite);
int bge_nvmem_read32(bge_t *bgep, bge_regno_t addr, uint32_t *dp);
int bge_nvmem_write32(bge_t *bgep, bge_regno_t addr, uint32_t *dp);
void bge_chip_cfg_init(bge_t *bgep, chip_id_t *cidp, boolean_t enable_dma);
int bge_chip_id_init(bge_t *bgep);
void bge_chip_coalesce_update(bge_t *bgep);
int bge_chip_start(bge_t *bgep, boolean_t reset_phy);
void bge_chip_stop(bge_t *bgep, boolean_t fault);
#ifndef __sparc
void bge_chip_stop_nonblocking(bge_t *bgep);
#endif
#ifdef BGE_IPMI_ASF
void bge_nic_put32(bge_t *bgep, bge_regno_t addr, uint32_t data);
#pragma inline(bge_nic_put32)
uint32_t bge_nic_read32(bge_t *bgep, bge_regno_t addr);
void bge_ind_put32(bge_t *bgep, bge_regno_t regno, uint32_t val);
#pragma inline(bge_ind_put32)
uint32_t bge_ind_get32(bge_t *bgep, bge_regno_t regno);
#pragma inline(bge_ind_get32)
void bge_asf_update_status(bge_t *bgep);
void bge_asf_heartbeat(void *bgep);
void bge_asf_stop_timer(bge_t *bgep);
void bge_asf_get_config(bge_t *bgep);
void bge_asf_pre_reset_operations(bge_t *bgep, uint32_t mode);
void bge_asf_post_reset_old_mode(bge_t *bgep, uint32_t mode);
void bge_asf_post_reset_new_mode(bge_t *bgep, uint32_t mode);
int bge_chip_reset(bge_t *bgep, boolean_t enable_dma, uint_t asf_mode);
int bge_chip_sync(bge_t *bgep, boolean_t asf_keeplive);
#else
int bge_chip_reset(bge_t *bgep, boolean_t enable_dma);
int bge_chip_sync(bge_t *bgep);
#endif
void bge_chip_blank(void *arg, time_t ticks, uint_t count, int flag);
extern mblk_t *bge_poll_ring(void *, int);
uint_t bge_chip_factotum(caddr_t arg);
void bge_chip_cyclic(void *arg);
enum ioc_reply bge_chip_ioctl(bge_t *bgep, queue_t *wq, mblk_t *mp,
struct iocblk *iocp);
uint_t bge_intr(caddr_t arg1, caddr_t arg2);
void bge_sync_mac_modes(bge_t *);
extern uint32_t bge_rx_ticks_norm;
extern uint32_t bge_tx_ticks_norm;
extern uint32_t bge_rx_count_norm;
extern uint32_t bge_tx_count_norm;
extern boolean_t bge_relaxed_ordering;
void bge_chip_msi_trig(bge_t *bgep);
/* bge_kstats.c */
void bge_init_kstats(bge_t *bgep, int instance);
void bge_fini_kstats(bge_t *bgep);
int bge_m_stat(void *arg, uint_t stat, uint64_t *val);
int bge_rx_ring_stat(mac_ring_driver_t, uint_t, uint64_t *);
/* bge_log.c */
#if BGE_DEBUGGING
void (*bge_db(bge_t *bgep))(const char *fmt, ...);
void (*bge_gdb(void))(const char *fmt, ...);
void bge_pkt_dump(bge_t *bgep, bge_rbd_t *hbp, sw_rbd_t *sdp, const char *msg);
void bge_dbg_enter(bge_t *bgep, const char *msg);
#endif /* BGE_DEBUGGING */
void bge_problem(bge_t *bgep, const char *fmt, ...);
void bge_log(bge_t *bgep, const char *fmt, ...);
void bge_error(bge_t *bgep, const char *fmt, ...);
void bge_fm_ereport(bge_t *bgep, char *detail);
extern kmutex_t bge_log_mutex[1];
extern uint32_t bge_debug;
/* bge_main.c */
int bge_restart(bge_t *bgep, boolean_t reset_phy);
int bge_check_acc_handle(bge_t *bgep, ddi_acc_handle_t handle);
int bge_check_dma_handle(bge_t *bgep, ddi_dma_handle_t handle);
void bge_init_rings(bge_t *bgep);
void bge_fini_rings(bge_t *bgep);
bge_queue_item_t *bge_alloc_txbuf_array(bge_t *bgep, send_ring_t *srp);
void bge_free_txbuf_arrays(send_ring_t *srp);
int bge_alloc_bufs(bge_t *bgep);
void bge_free_bufs(bge_t *bgep);
void bge_intr_enable(bge_t *bgep);
void bge_intr_disable(bge_t *bgep);
int bge_reprogram(bge_t *);
/* bge_mii.c */
void bge_eee_init(bge_t *bgep);
void bge_eee_enable(bge_t * bgep);
int bge_phys_init(bge_t *bgep);
void bge_phys_reset(bge_t *bgep);
int bge_phys_idle(bge_t *bgep);
int bge_phys_update(bge_t *bgep);
boolean_t bge_phys_check(bge_t *bgep);
/* bge_ndd.c */
int bge_nd_init(bge_t *bgep);
/* bge_recv.c */
void bge_receive(bge_t *bgep, bge_status_t *bsp);
/* bge_send.c */
mblk_t *bge_m_tx(void *arg, mblk_t *mp);
mblk_t *bge_ring_tx(void *arg, mblk_t *mp);
boolean_t bge_recycle(bge_t *bgep, bge_status_t *bsp);
uint_t bge_send_drain(caddr_t arg);
/* bge_atomic.c */
uint64_t bge_atomic_reserve(uint64_t *count_p, uint64_t n);
void bge_atomic_renounce(uint64_t *count_p, uint64_t n);
uint64_t bge_atomic_claim(uint64_t *count_p, uint64_t limit);
uint64_t bge_atomic_next(uint64_t *sp, uint64_t limit);
void bge_atomic_sub64(uint64_t *count_p, uint64_t n);
uint64_t bge_atomic_clr64(uint64_t *sp, uint64_t bits);
uint32_t bge_atomic_shl32(uint32_t *sp, uint_t count);
/* bge_mii_5906.c */
void bge_adj_volt_5906(bge_t *bgep);
/*
* Reset type
*/
#define BGE_SHUTDOWN_RESET 0
#define BGE_INIT_RESET 1
#define BGE_SUSPEND_RESET 2
/* For asf_status */
#define ASF_STAT_NONE 0
#define ASF_STAT_STOP 1
#define ASF_STAT_RUN 2
#define ASF_STAT_RUN_INIT 3 /* attached but don't plumb */
/* ASF modes for bge_reset() and bge_chip_reset() */
#define ASF_MODE_NONE 0 /* don't launch asf */
#define ASF_MODE_SHUTDOWN 1 /* asf shutdown mode */
#define ASF_MODE_INIT 2 /* asf init mode */
#define ASF_MODE_POST_SHUTDOWN 3 /* only do post-shutdown */
#define ASF_MODE_POST_INIT 4 /* only do post-init */
#define BGE_ASF_HEARTBEAT_INTERVAL 1500000
#ifdef __cplusplus
}
#endif
#endif /* _BGE_IMPL_H */
| 31.82485 | 96 | 0.717249 | [
"transform"
] |
37ab5fc15d7f3166495886899d0cf8a965e85772 | 4,566 | h | C | cresis-toolbox/+tomo/viterbi_lib.h | CReSIS/CRESIS-TOOLBOX | b8c5de57a7a95137e543e202c6a473a958129b04 | [
"MIT"
] | 14 | 2019-12-04T19:48:11.000Z | 2022-02-07T18:53:49.000Z | cresis-toolbox/+tomo/viterbi_lib.h | CReSIS/CRESIS-TOOLBOX | b8c5de57a7a95137e543e202c6a473a958129b04 | [
"MIT"
] | 10 | 2020-06-23T17:22:38.000Z | 2021-05-11T18:41:53.000Z | cresis-toolbox/+tomo/viterbi_lib.h | CReSIS/CRESIS-TOOLBOX | b8c5de57a7a95137e543e202c6a473a958129b04 | [
"MIT"
] | 7 | 2019-12-14T04:47:46.000Z | 2021-09-17T13:47:01.000Z | // viterbi_lib.h
//
// Layer-tracking program based on the Viterbi algorithm
//
// Adapted from original code by Mingze Xu, David Crandall, and John Paden
//
// Author: Victor Berger
// See also: viterbi.cpp
#ifndef _VITERBI_H_
#define _VITERBI_H_
#include "mex.h"
#include <cmath>
#include <limits>
const int DEF_MID = 33;
const int DEF_SIGMA = 24;
const int DEF_SCALE = 12; // scaling for smoothness constraint
const int DEF_EGT_WEIGHT = 10; // relative weight of extra GT
const int DEF_ICE_BIN_THR = 3; // icemask proximity scan threshold
const int DEF_REPULSION = 150000; // repulsion from surface
const double LARGE = 1000000000;
class detect
{
public:
detect( const int d_row, const int d_col,
const double *d_in_data, const int *d_slayer,
const int d_blayer, const double *d_mask,
const double *d_mu, const double *d_sigma,
const int d_mid, const double d_egt_weight,
const double d_smooth_weight, const double d_smooth_var,
const double *d_smooth_slope, const ptrdiff_t *d_bounds,
const size_t d_ms, const int d_num_extra_tr,
const double *d_extra_truth_x, const double *d_extra_truth_y,
double *d_result, const double *d_weight_points,
const double d_repulsion, const double d_ice_bin_thr
)
: f_row(d_row), f_col(d_col),
f_in_data(d_in_data), f_slayer(d_slayer),
f_blayer(d_blayer), f_mask(d_mask),
f_mu(d_mu), f_sigma(d_sigma),
f_mid(d_mid), f_egt_weight(d_egt_weight),
f_smooth_weight(d_smooth_weight), f_smooth_var(d_smooth_var),
f_smooth_slope(d_smooth_slope), f_bounds(d_bounds),
f_ms(d_ms), f_num_extra_tr(d_num_extra_tr),
f_extra_truth_x(d_extra_truth_x), f_extra_truth_y(d_extra_truth_y),
f_result(d_result), f_weight_points(d_weight_points),
f_repulsion(d_repulsion), f_ice_bin_thr(d_ice_bin_thr)
{
find_path();
mexPrintf("\n");
}
// VARIABLES
const int f_row, f_col, f_mid, f_blayer,
*f_slayer, f_num_extra_tr;
const double *f_in_data, *f_mask, *f_mu, *f_sigma, f_egt_weight,
*f_smooth_slope, *f_extra_truth_x, *f_extra_truth_y,
*f_weight_points,f_smooth_weight, f_smooth_var, f_repulsion, f_ice_bin_thr;
const ptrdiff_t *f_bounds;
const size_t f_ms;
double *f_result;
int depth, num_col_vis, t, start_col, end_col;
// METHODS
int calculate_best(double *path_prob);
double unary_cost(int x, int y), *find_path(void);
void viterbi_right(int *path, double *path_prob, double *path_prob_next, double *index, int path_index),
reset_arrays(double *path_prob, double *path_prob_next, double *index);
template <class T>
T sqr(T x) { return x*x; }
double norm_pdf(int x, double mu = DEF_MID,
double sigma = DEF_SIGMA, double scale = DEF_SCALE)
{
if(sigma != std::numeric_limits<double>::infinity())
return scale * (1.0/(sigma*sqrt(2*M_PI))) * exp(-0.5*sqr((x-mu)/sigma));
return scale;
}
int encode(int x, int y)
{
return x * f_row + y;
}
int vic_encode(int row, int col)
{
return depth * col + row;
}
// Distance transform calculation, adapted from David Crandall
// Every index from d1 to d2 will be set in dst and dst_ind
// dst will contain the minimum value for that destination
// dst_ind will contain the minimum source index for that destination
void dt(const double *src, double *dst, double *dst_ind, int s1, int s2,
int d1, int d2, double scale, int off = 0)
{
int d = (d1 + d2) >> 1, s = s1; // Find the midpoint of the destination
for (int p = s1; p <= s2; p++) // Search through all the sources and find the minimum
if (src[s] + sqr(s-d-off) * scale > src[p] + sqr(p-d-off) * scale)
s = p;
dst[d] = src[s] + sqr(s-d-off) * scale; // Minimum value to the midpoint
dst_ind[d] = s; // Minimum source index for the midpoint
if(d2 >= d + 1) // Recursive call, binary search (top half of destinations)
dt(src, dst, dst_ind, s, s2, d+1, d2, scale, off);
if(d-1 >= d1) // Recursive call, binary search (bottom half of destinations)
dt(src, dst, dst_ind, s1, s, d1, d-1, scale, off);
}
void dt_1d(const double *f, double scale, double *result,
double *dst_ind, int beg, int end, int off = 0)
{
dt(f, result, dst_ind, beg, end-1, beg, end-1, scale, off);
}
};
#endif
| 37.121951 | 106 | 0.648708 | [
"transform"
] |
37bce79147b09b467970104f0bff8e3123d40591 | 9,950 | h | C | fbpcs/emp_games/common/SecretSharing.h | rohantiru/fbpcs | 5685b54fd4641145b61118dcf3f2f80637c8c7e2 | [
"MIT"
] | null | null | null | fbpcs/emp_games/common/SecretSharing.h | rohantiru/fbpcs | 5685b54fd4641145b61118dcf3f2f80637c8c7e2 | [
"MIT"
] | null | null | null | fbpcs/emp_games/common/SecretSharing.h | rohantiru/fbpcs | 5685b54fd4641145b61118dcf3f2f80637c8c7e2 | [
"MIT"
] | null | null | null | /*
* 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.
*/
#ifndef SECRET_SHARING_H
#define SECRET_SHARING_H
#include <functional>
#include <optional>
#include <tuple>
#include <vector>
#include <emp-sh2pc/emp-sh2pc.h>
#include "PrivateData.h"
namespace private_measurement::secret_sharing {
/*
* Share one emp::Integer bidirectionally between both parties
*/
template <int MY_ROLE>
PrivateInt<MY_ROLE> privatelyShareInt(int64_t in);
/*
* Share an array of type T from SOURCE_ROLE to the opposite party,
* return an array of type O.
*
* O must be emp::batcher compatible. That means O must implement
* 1) O::bool_size(T val)
* 2) O::bool_data(bool* data, T val)
* 3) O(int32_t len, const emp::block* b)
*
* T must also be ostream and == compatible to support debug logging.
*
* numVals = number of items to share
* nullValue = value to initialize for the non-source role.
*/
template <
int MY_ROLE,
int SOURCE_ROLE,
typename T,
typename O,
typename... BatcherArgs>
const std::vector<O> privatelyShareArrayFrom(
const std::vector<T>& in,
size_t numVals,
T nullValue,
BatcherArgs... batcherArgs);
/*
* Share emp::Integers from SOURCE_ROLE to the opposite party
* numVals = number of items to share
*/
template <int MY_ROLE, int SOURCE_ROLE>
const std::vector<emp::Integer> privatelyShareIntsFrom(
const std::vector<int64_t>& in,
size_t numVals,
int32_t bitLen = INT_SIZE) {
return privatelyShareArrayFrom<MY_ROLE, SOURCE_ROLE, int64_t, emp::Integer>(
in, numVals, 0, bitLen);
}
/*
* Share emp::Bits from SOURCE_ROLE to the opposite party
* numVals = number of items to share
*/
template <int MY_ROLE, int SOURCE_ROLE>
const std::vector<emp::Bit> privatelyShareBitsFrom(
const std::vector<int64_t>& in,
size_t numVals) {
return privatelyShareArrayFrom<MY_ROLE, SOURCE_ROLE, int64_t, emp::Bit>(
in, numVals, 0);
}
/*
* Share an array of T arrays from SOURCE_ROLE to the opposite party,
* returning a vector of O arrays.
*
* The inner arrays will be padded to prevent the other party from
* learning how many items are in the arrays.
*
* privatelyShareArrayFrom will be used to share the inner arrays.
*
* maxArraySize = maximum inner array size
* paddingValue = value to pad the inner arrays with
* numVals = number of items to share
*/
template <int MY_ROLE, int SOURCE_ROLE, typename T, typename O>
const std::vector<std::vector<O>> privatelyShareArraysFrom(
const std::vector<std::vector<T>>& in,
size_t numVals,
size_t maxArraySize,
T paddingValue);
/*
* Same purpose as privatelyShareArraysFrom but w/o padding
*/
template <int MY_ROLE, int SOURCE_ROLE, typename T, typename O>
const std::vector<std::vector<O>> privatelyShareArraysFromNoPadding(
const std::vector<std::vector<T>>& in,
size_t numVals,
size_t maxArraySize);
/*
* Share an array of pre-padded int arrays from SOURCE_ROLE to the opposite
* party.
*
* The inner arrays must be in size arraySize. No padding will be performed.
*
* privatelyShareArrayFrom will be used to share the inner arrays.
*
* numVals = number of items to share
* arraySize = mandatory inner array size
* bitLen = number of bits each emp::integer takes to optimize memory usage
*/
template <int MY_ROLE, int SOURCE_ROLE>
const std::vector<std::vector<emp::Integer>>
privatelyShareIntArraysNoPaddingFrom(
const std::vector<std::vector<int64_t>>& in,
size_t numVals,
size_t arraySize,
int32_t bitLen);
/*
* Share emp::Integers from ALICE to BOB
* numVals = number of items to share
*/
template <int MY_ROLE>
const std::vector<emp::Integer> privatelyShareIntsFromAlice(
const std::vector<int64_t>& in,
size_t numVals,
int32_t bitLen = INT_SIZE) {
return privatelyShareIntsFrom<MY_ROLE, emp::ALICE>(in, numVals, bitLen);
}
/*
* Share emp::Integers from BOB to ALICE
* numVals = number of items to share
*/
template <int MY_ROLE>
const std::vector<emp::Integer> privatelyShareIntsFromBob(
const std::vector<int64_t>& in,
size_t numVals,
int32_t bitLen = INT_SIZE) {
return privatelyShareIntsFrom<MY_ROLE, emp::BOB>(in, numVals, bitLen);
}
/*
* Share emp::Bits from ALICE to BOB
* numVals = number of items to share
*/
template <int MY_ROLE>
const std::vector<emp::Bit> privatelyShareBitsFromAlice(
const std::vector<int64_t>& in,
size_t numVals) {
return privatelyShareBitsFrom<MY_ROLE, emp::ALICE>(in, numVals);
}
/*
* Share emp::Bits from BOB to ALICE
* numVals = number of items to share
*/
template <int MY_ROLE>
const std::vector<emp::Bit> privatelyShareBitsFromBob(
const std::vector<int64_t>& in,
size_t numVals) {
return privatelyShareBitsFrom<MY_ROLE, emp::BOB>(in, numVals);
}
/*
* Share an array of arrays from ALICE to BOB
*
* The inner arrays will be padded to prevent the other party from
* learning how many items are in the arrays.
*
* maxArraySize = maximum inner array size
* paddingValue = value to pad the inner arrays with
* numVals = number of items to share
*/
template <int MY_ROLE, typename T, typename O>
const std::vector<std::vector<O>> privatelyShareArraysFromAlice(
const std::vector<std::vector<T>>& in,
size_t numVals,
size_t maxArraySize,
T paddingValue) {
return privatelyShareArraysFrom<MY_ROLE, emp::ALICE, T, O>(
in, numVals, maxArraySize, paddingValue);
}
/*
* This has same purpose as privatelyShareArraysFromAlice
* but it does not add any padding.
*/
template <int MY_ROLE, typename T, typename O>
const std::vector<std::vector<O>> privatelyShareArraysFromAliceNoPadding(
const std::vector<std::vector<T>>& in,
size_t numVals,
size_t maxArraySize) {
return privatelyShareArraysFromNoPadding<MY_ROLE, emp::ALICE, T, O>(
in, numVals, maxArraySize);
}
/*
* Share an array of arrays from BOB to ALICE
*
* The inner arrays will be padded to prevent the other party from
* learning how many items are in the arrays.
*
* maxArraySize = maximum inner array size
* paddingValue = value to pad the inner arrays with
* numVals = number of items to share
*/
template <int MY_ROLE, typename T, typename O>
const std::vector<std::vector<O>> privatelyShareArraysFromBob(
const std::vector<std::vector<T>>& in,
size_t numVals,
size_t maxArraySize,
T paddingValue) {
return privatelyShareArraysFrom<MY_ROLE, emp::BOB, T, O>(
in, numVals, maxArraySize, paddingValue);
}
/*
* This has same purpose as privatelyShareArraysFromBob
* but it does not add any padding.
*/
template <int MY_ROLE, typename T, typename O>
const std::vector<std::vector<O>> privatelyShareArraysFromBobNoPadding(
const std::vector<std::vector<T>>& in,
size_t numVals,
size_t maxArraySize) {
return privatelyShareArraysFromNoPadding<MY_ROLE, emp::BOB, T, O>(
in, numVals, maxArraySize);
}
/*
* Share an array of pre-padded int arrays from BOB to ALICE
*
* The inner arrays must be in size arraySize. No padding will be performed.
*
* arraySize = mandatory inner array size
* numVals = number of items to share
* bitLen = number of bits each emp::integer takes to optimize memory usage
*/
template <int MY_ROLE>
const std::vector<std::vector<emp::Integer>>
privatelyShareIntArraysNoPaddingFromBob(
const std::vector<std::vector<int64_t>>& in,
size_t numVals,
size_t arraySize,
int32_t bitLen) {
return privatelyShareIntArraysNoPaddingFrom<MY_ROLE, emp::BOB>(
in, numVals, arraySize, bitLen);
}
/*
* Execute map_fn on pairwise items from vec1 and vec2
*/
template <typename T, typename S>
void zip(
const std::vector<T>& vec1,
const std::vector<S>& vec2,
std::function<void(T, S)> map_fn);
/*
* Execute map_fn on elements of vec and returns mapped values
* construct a vector of the return type of map_fn and return that to
* the caller
*/
template <typename T, typename O>
const std::vector<O> map(const std::vector<T>& vec, std::function<O(T)> map_fn);
/*
* Execute map_fn on pairwise items from vec1 and vec2
* construct a vector of the return type of map_fn and return that to
* the caller
*/
template <typename T, typename S, typename O>
const std::vector<O> zip_and_map(
const std::vector<T>& vec1,
const std::vector<S>& vec2,
std::function<O(T, S)> map_fn);
/*
* Execute map_fn on pairwise items from vec1 and vec2
* construct a vector of the return type of map_fn and return that to
* the caller.
*/
template <typename T, typename S, typename O, typename N>
const std::pair<std::vector<O>, std::vector<N>> zip_and_map(
const std::vector<T>& vec1,
const std::vector<S>& vec2,
std::function<std::pair<O, N>(T, S)> map_fn);
template <typename T, typename S, typename O1, typename O2, typename O3>
const std::tuple<std::vector<O1>, std::vector<O2>, std::vector<O3>> zip_and_map(
const std::vector<T>& vec1,
const std::vector<S>& vec2,
std::function<std::tuple<O1, O2, O3>(T, S)> map_fn);
/*
* Execute map_fn on pairwise items from vec1, vec2, and vec3
* construct a vector of the return type of map_fn and return that to
* the caller
*/
template <typename T, typename S, typename R, typename O>
const std::vector<O> zip_and_map(
const std::vector<T>& vec1,
const std::vector<S>& vec2,
const std::vector<R>& vec3,
std::function<O(T, S, R)> map_fn);
/*
* Multiply vec by the bitmask. If the mask is 1 at element i, accept
* vec[i] If the mask is 0 at element i, accept 0 (default constructed
* T, effectively)
*/
template <typename T>
const std::vector<T> multiplyBitmask(
const std::vector<T>& vec,
const std::vector<emp::Bit>& bitmask);
} // namespace private_measurement::secret_sharing
#ifndef SECRET_SHARING_HPP
#include "SecretSharing.hpp"
#endif // SECRET_SHARING_HPP
#endif // SECRET_SHARING_H
| 29.701493 | 80 | 0.712462 | [
"vector"
] |
37bceaf228ad83a2d1185cc90476c4a69c3286f4 | 3,737 | h | C | include/f1tenth_sensor_fusion/cluster_tracker.h | kovika98/f1tenth_sensor_fusion | 09a91f984a686fcdfd05d8c49954d115b3eeac73 | [
"Apache-2.0"
] | null | null | null | include/f1tenth_sensor_fusion/cluster_tracker.h | kovika98/f1tenth_sensor_fusion | 09a91f984a686fcdfd05d8c49954d115b3eeac73 | [
"Apache-2.0"
] | null | null | null | include/f1tenth_sensor_fusion/cluster_tracker.h | kovika98/f1tenth_sensor_fusion | 09a91f984a686fcdfd05d8c49954d115b3eeac73 | [
"Apache-2.0"
] | null | null | null | /* Copyright 2021 Kovács Gergely Attila
*
* 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 F1TENTH_SENSOR_FUSION__CLUSTER_TRACKER_H
#define F1TENTH_SENSOR_FUSION__CLUSTER_TRACKER_H
#include <f1tenth_sensor_fusion/tracker_config.hpp>
#include <f1tenth_sensor_fusion/KFTracker.hpp>
#include <ros/ros.h>
#include <boost/thread/mutex.hpp>
#include <sensor_msgs/PointCloud2.h>
#include <visualization_msgs/MarkerArray.h>
#include <message_filters/subscriber.h>
#include <pcl/segmentation/extract_clusters.h>
#include <opencv2/video/tracking.hpp>
namespace f1tenth_sensor_fusion
{
/// The ClusterTracker class to clusterize a point cloud (converted from a lidar scan) and track said clusters.
class ClusterTracker
{
protected:
virtual void initialize(int concurrency);
virtual int _load_params();
TrackerConfig _config;
ros::NodeHandle handle_;
ros::NodeHandle private_handle_;
private:
/**
* Publish a PointCloud to a ROS topic.
*
* @param pub the ROS publisher to said topic
* @param cluster the cluster of points to be published
*/
void publish_cloud(ros::Publisher &pub, pcl::PointCloud<pcl::PointXYZ>::Ptr &cluster);
void publish_objects(const boost::container::vector<pcl::PointXYZ> &cCentres, const boost::container::vector<int> &objIDs);
/**
* Create ROS Markers to later publish for enabling the visualization of detected objects.
*
* @param[in] pts predicted cluster centroid points (using KFilter)
* @param[in] IDs object IDs detected by filters
* @param[out] markers markers adjusted to fit points
*/
void fit_markers(const boost::container::vector<pcl::PointXYZ> &pts,
const boost::container::vector<int> &IDs, visualization_msgs::MarkerArray &markers);
void transform_centre(pcl::PointXYZ ¢re);
void sync_cluster_publishers_size(size_t num_clusters);
/**
* Process incoming point cloud data: perform clusterization and calculation of cluster centroids, publish output data using ROS
* publishers after performing the object detection.
*
* @param cloud_msg the incoming point cloud message
*/
void cloudCallback(const sensor_msgs::PointCloud2ConstPtr &cloud_msg);
void extract_cluster_data(const pcl::PointCloud<pcl::PointXYZ>::Ptr input_cloud,
boost::container::vector<pcl::PointCloud<pcl::PointXYZ>::Ptr> &cluster_vec,
boost::container::vector<pcl::PointXYZ> &cluster_centres);
pcl::EuclideanClusterExtraction<pcl::PointXYZ> cluster_extr_;
boost::mutex mutex_;
KFTracker _KFTracker;
boost::container::vector<ros::Publisher *> cluster_pubs_;
ros::Publisher obj_pub_;
ros::Publisher marker_pub_;
message_filters::Subscriber<sensor_msgs::PointCloud2> sub_;
size_t input_queue_size_;
size_t publisher_prune_ctr_ = 0;
bool transform_;
bool first_frame_ = true;
};
}
#endif // F1TENTH_SENSOR_FUSION__CLUSTER_TRACKER_H
| 38.525773 | 137 | 0.688253 | [
"object",
"vector"
] |
37bea7610dc21f96fbab2cf829b44d0f0c937bf1 | 2,430 | h | C | CommonTools/RecoUtils/interface/PFCand_NoPU_WithAM.h | pasmuss/cmssw | 566f40c323beef46134485a45ea53349f59ae534 | [
"Apache-2.0"
] | null | null | null | CommonTools/RecoUtils/interface/PFCand_NoPU_WithAM.h | pasmuss/cmssw | 566f40c323beef46134485a45ea53349f59ae534 | [
"Apache-2.0"
] | null | null | null | CommonTools/RecoUtils/interface/PFCand_NoPU_WithAM.h | pasmuss/cmssw | 566f40c323beef46134485a45ea53349f59ae534 | [
"Apache-2.0"
] | null | null | null | #ifndef PFCand_NoPU_WithAM_h
#define PFCand_NoPU_WithAM_h
// -*- C++ -*-
//
// Package: PFCand_NoPU_WithAM
// Class: PFCand_NoPU_WithAM
//
/**\class PF_PU_AssoMap PFCand_NoPU_WithAM.cc CommonTools/RecoUtils/plugins/PFCand_NoPU_WithAM.cc
Description: Produces a collection of PFCandidates associated to the first vertex based on the association map
*/
//
// Original Author: Matthias Geisler,32 4-B20,+41227676487,
// Created: Thu Dec 1 16:07:41 CET 2011
// $Id: PFCand_NoPU_WithAM.h,v 1.2 2012/04/18 15:09:23 mgeisler Exp $
//
//
#include <string>
#include "FWCore/Framework/interface/Frameworkfwd.h"
#include "FWCore/Framework/interface/EDProducer.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "FWCore/Utilities/interface/InputTag.h"
#include "DataFormats/Common/interface/AssociationMap.h"
#include "DataFormats/Common/interface/Handle.h"
#include "DataFormats/Common/interface/OneToManyWithQuality.h"
#include "DataFormats/Common/interface/OneToManyWithQualityGeneric.h"
#include "DataFormats/VertexReco/interface/Vertex.h"
#include "DataFormats/VertexReco/interface/VertexFwd.h"
#include "DataFormats/ParticleFlowCandidate/interface/PFCandidate.h"
#include "DataFormats/ParticleFlowCandidate/interface/PFCandidateFwd.h"
//
// constants, enums and typedefs
//
typedef edm::AssociationMap<edm::OneToManyWithQuality< reco::VertexCollection, reco::PFCandidateCollection, int> > PFCandToVertexAssMap;
typedef edm::AssociationMap<edm::OneToManyWithQuality< reco::PFCandidateCollection, reco::VertexCollection, int> > VertexToPFCandAssMap;
typedef std::pair<reco::PFCandidateRef, int> PFCandQualityPair;
typedef std::vector<PFCandQualityPair > PFCandQualityPairVector;
//
// class declaration
//
class PFCand_NoPU_WithAM : public edm::EDProducer {
public:
explicit PFCand_NoPU_WithAM(const edm::ParameterSet&);
~PFCand_NoPU_WithAM();
static void fillDescriptions(edm::ConfigurationDescriptions& descriptions);
private:
virtual void produce(edm::Event&, const edm::EventSetup&);
// ----------member data ---------------------------
edm::InputTag input_AssociationType_;
edm::EDGetTokenT<PFCandToVertexAssMap> token_PFCandToVertexAssMap_;
edm::EDGetTokenT<VertexToPFCandAssMap> token_VertexToPFCandAssMap_;
edm::EDGetTokenT<reco::VertexCollection> token_VertexCollection_;
int input_MinQuality_;
};
#endif
| 31.973684 | 136 | 0.765432 | [
"vector"
] |
37c0474e722eae506fb8f9f1afb8d5c77826aaee | 3,545 | h | C | Library/Library.prj/IterT.h | rrvt/RWracesDB | 4f01fed973df7dfb7ec516b2969b20fc6744d7fe | [
"MIT"
] | null | null | null | Library/Library.prj/IterT.h | rrvt/RWracesDB | 4f01fed973df7dfb7ec516b2969b20fc6744d7fe | [
"MIT"
] | 1 | 2020-05-01T00:37:31.000Z | 2020-05-01T00:37:31.000Z | Library/Library.prj/IterT.h | rrvt/RWracesDB | 4f01fed973df7dfb7ec516b2969b20fc6744d7fe | [
"MIT"
] | 1 | 2020-02-25T09:11:37.000Z | 2020-02-25T09:11:37.000Z | // Iterator
#pragma once
/*
Datum should be seen, sometimes all the data needs to be seen. The iterator class implements an
object that serves up each Datum entry in the array (not the pointer, the Datum object). It is used:
DataStoreIter iter(dataStore);
Datum* data;
for (data = iter(); data; data = iter++) {
String& s = data->get(); Use data as a pointer to the record, it is guaranteed to be non-zero
last gives a heads up when the last entry is being processed
The template requires two functions be part of Store:
int nData() -- returns number of data items in array
Datum* datum(int i) -- returns either a pointer to data (or datum) at index i in array or zero
private:
// returns either a pointer to data (or datum) at index i in array or zero
Datum* datum(int i) {return 0 <= i && i < nData() ? &data[i] : 0;} // or data[i].p
int nData() {return data.end();} // returns number of data items in array
void removeDatum(int i) {if (0 <= i && i < nData()) data.del(i);}
friend typename DataIter;
*/
template <class Store, class Datum>
class IterT {
int iterX;
Store& store;
public:
enum Dir {Fwd, Rev};
IterT(Store& dataStore) : iterX(0), store(dataStore) { }
IterT(IterT& iter) : iterX(iter.iterX), store(iter.store) { }
Datum* operator() (Dir rev = Fwd) {iterX = rev ? store.nData() : 0; return rev ? decr() : current();}
Datum* operator++ (int) {return iterX < store.nData() ? incr() : 0;}
Datum* operator-- (int) {return iterX > 0 ? decr() : 0;}
int index() {return iterX;}
Datum* current() {return store.datum(iterX);}
IterT& operator= (IterT& iter) {iterX = iter.iterX; store = iter.store;}
bool isLast() {return iterX + 1 == store.nData();}
bool isFirst() {return iterX <= 0;}
void remove(Dir rev = Fwd) {store.removeDatum(rev ? iterX++ : iterX--);}
private:
Datum* incr() {return iterX < store.nData() ? store.datum(++iterX) : 0;}
Datum* decr() {return iterX > 0 ? store.datum(--iterX) : 0;}
IterT() : store(*(Store*) 0), iterX(0) { } // This prevents an uninitizlized iterator
};
//Obj Iterator -- i.e. the actual Object is contained in the iterator, therefore use it immediately after
// a pointer is returned to it...
/*
Datum* Store::getDatum(int i, Datum& d) {
if (0 <= i && i < nData()) {<obtain data as t>; d = t; return &d;}
return 0;
}
*/
template <class Store, class Datum>
class ObjIterT {
int iterX;
Store& store;
Datum datum;
public:
enum Dir {Fwd, Rev};
ObjIterT(Store& dataStore) : store(dataStore), iterX(0) { }
Datum* operator() (Dir rev = Fwd) {iterX = rev ? store.nData() : 0; return rev ? decr() : current();}
Datum* operator++ (int) {return iterX < store.nData() ? incr() : 0;}
Datum* operator-- (int) {return iterX > 0 ? decr() : 0;}
Datum* current() {return store.getDatum(iterX, datum);}
bool isLast() {return iterX + 1 == store.nData();}
bool isFirst() {return iterX <= 0;}
void remove(Dir rev = Fwd) {store.removeDatum(rev ? iterX++ : iterX--);}
private:
Datum* incr() {return iterX < store.nData() ? store.getDatum(++iterX, datum) : 0;}
Datum* decr() {return iterX > 0 ? store.getDatum(--iterX, datum) : 0;}
ObjIterT() : store(*(Store*) 0), iterX(0) { } // This prevents an uninitizlized iterator
};
| 30.826087 | 105 | 0.593512 | [
"object"
] |
37c753fc2ca16bc3717afde3c2a467ed87f9f361 | 233 | h | C | 04_Vector/4_Exercise/exercise.h | pataya235/UdemyCpp_Template-main | 46583e2d252005eaba3a8a6f04b112454722e315 | [
"MIT"
] | null | null | null | 04_Vector/4_Exercise/exercise.h | pataya235/UdemyCpp_Template-main | 46583e2d252005eaba3a8a6f04b112454722e315 | [
"MIT"
] | null | null | null | 04_Vector/4_Exercise/exercise.h | pataya235/UdemyCpp_Template-main | 46583e2d252005eaba3a8a6f04b112454722e315 | [
"MIT"
] | null | null | null | #pragma once
#include <vector>
// Exercise 1
using Matrix = std::vector<std::vector<double>>; //alias
// Exercise 2
std::vector<double> max_row_values(Matrix &matrix);
// Exercise 3
double sort_and_max(std::vector<double> &vec);
| 17.923077 | 56 | 0.716738 | [
"vector"
] |
37c77fc444a1ef8b42c00bff72d6f9eba93d66bd | 4,810 | h | C | Medis/src/db/dblist_2.h | lxq00/public | 5834fac5ba982ff45ea810c5e4de9fe08833cf53 | [
"MIT"
] | null | null | null | Medis/src/db/dblist_2.h | lxq00/public | 5834fac5ba982ff45ea810c5e4de9fe08833cf53 | [
"MIT"
] | null | null | null | Medis/src/db/dblist_2.h | lxq00/public | 5834fac5ba982ff45ea810c5e4de9fe08833cf53 | [
"MIT"
] | null | null | null | #pragma once
#include "dbstring_1.h"
class DBList :public DBString
{
public:
DBList(const shared_ptr<IOWorker>& ioworker, const shared_ptr<DataFactory>& factory, int dbindex) :DBString(ioworker,factory , dbindex)
{
subCommand("LPUSH", CommandCallback(&DBList::lpushFunc, this));
subCommand("RPUSH", CommandCallback(&DBList::rpushFunc, this));
subCommand("LPOP", CommandCallback(&DBList::lpopFunc, this));
subCommand("RPOP", CommandCallback(&DBList::rpopFunc, this));
subCommand("LLEN", CommandCallback(&DBList::llenFunc, this));
subCommand("LRANGE", CommandCallback(&DBList::lrangeFunc, this));
}
private:
RedisValue lpushFunc(const std::vector<RedisValue> & val)
{
if (val.size() < 3) return RedisValue(false, "wrong number of arguments");
std::string key = String::tolower(val[1].toString());
shared_ptr<ValueObject> valueobject;
std::map<std::string, shared_ptr<ValueObject> >::iterator iter = valuelist.find(key);
if (iter == valuelist.end())
{
valueobject = make_shared<ValueList>(factory, key, dbindex);
valuelist[key] = valueobject;
}
else
{
valueobject = iter->second;
}
if (valueobject->type() != DataType_List) return RedisValue(0);
ValueList* listobject = (ValueList*)valueobject.get();
uint32_t count = 0;
for (uint32_t i = 2; i < val.size(); i++)
{
String data = val[i].toString();
if(data.length() == 0) continue;
listobject->push_front(data);
count++;
}
return RedisValue(count);
}
RedisValue rpushFunc(const std::vector<RedisValue> & val)
{
if (val.size() < 3) return RedisValue(false, "wrong number of arguments");
std::string key = String::tolower(val[1].toString());
shared_ptr<ValueObject> valueobject;
std::map<std::string, shared_ptr<ValueObject> >::iterator iter = valuelist.find(key);
if (iter == valuelist.end())
{
valueobject = make_shared<ValueList>(factory, key, dbindex);
valuelist[key] = valueobject;
}
else
{
valueobject = iter->second;
}
if (valueobject->type() != DataType_List) return RedisValue(0);
ValueList* listobject = (ValueList*)valueobject.get();
uint32_t count = 0;
for (uint32_t i = 2; i < val.size(); i++)
{
String data = val[i].toString();
if (data.length() == 0) continue;
listobject->push_back(data);
count++;
}
return RedisValue(count);
}
RedisValue lpopFunc(const std::vector<RedisValue> & val)
{
if (val.size() != 2) return RedisValue(false, "wrong number of arguments");
std::string key = String::tolower(val[1].toString());
std::map<std::string, shared_ptr<ValueObject> >::iterator iter = valuelist.find(key);
if (iter == valuelist.end())
{
return RedisValue(0);
}
if (iter->second->type() != DataType_List) return RedisValue(0);
ValueList* listobject = (ValueList*)iter->second.get();
String data;
listobject->pop_front(data);
return RedisValue(data);
}
RedisValue rpopFunc(const std::vector<RedisValue> & val)
{
if (val.size() != 2) return RedisValue(false, "wrong number of arguments");
std::string key = String::tolower(val[1].toString());
std::map<std::string, shared_ptr<ValueObject> >::iterator iter = valuelist.find(key);
if (iter == valuelist.end())
{
return RedisValue(0);
}
if (iter->second->type() != DataType_List) return RedisValue(0);
ValueList* listobject = (ValueList*)iter->second.get();
String data;
listobject->pop_back(data);
return RedisValue(data);
}
RedisValue llenFunc(const std::vector<RedisValue> & val)
{
if (val.size() != 2) return RedisValue(false, "wrong number of arguments");
std::string key = String::tolower(val[1].toString());
std::map<std::string, shared_ptr<ValueObject> >::iterator iter = valuelist.find(key);
if (iter == valuelist.end())
{
return RedisValue(0);
}
if (iter->second->type() != DataType_List) return RedisValue(0);
ValueList* listobject = (ValueList*)iter->second.get();
uint32_t lenval = listobject->len();
return RedisValue(lenval);
}
RedisValue lrangeFunc(const std::vector<RedisValue>& val)
{
if (val.size() != 4) return RedisValue(false, "wrong number of arguments");
std::string key = String::tolower(val[1].toString());
int32_t start = (int32_t)val[2].toInt();
int32_t stop = (int32_t)val[3].toInt();
std::map<std::string, shared_ptr<ValueObject> >::iterator iter = valuelist.find(key);
if (iter == valuelist.end())
{
return RedisValue(0);
}
if (iter->second->type() != DataType_List) return RedisValue(0);
ValueList* listobject = (ValueList*)iter->second.get();
std::vector<String> dataarray;
listobject->range(start, stop, dataarray);
std::vector<RedisValue> values;
for (uint32_t i = 0; i < dataarray.size(); i++)
{
values.push_back(RedisValue(dataarray[i]));
}
return RedisValue(values);
}
}; | 27.329545 | 136 | 0.676715 | [
"vector"
] |
37cf95d3f2118086298f279e00208e94e786a5ee | 28,749 | c | C | src/event-loop.c | gitlab-freedesktop-mirrors/wayland | af8b5c07826ed2f2624cf87c0e2da4f8e9089ee0 | [
"MIT"
] | null | null | null | src/event-loop.c | gitlab-freedesktop-mirrors/wayland | af8b5c07826ed2f2624cf87c0e2da4f8e9089ee0 | [
"MIT"
] | null | null | null | src/event-loop.c | gitlab-freedesktop-mirrors/wayland | af8b5c07826ed2f2624cf87c0e2da4f8e9089ee0 | [
"MIT"
] | null | null | null | /*
* Copyright © 2008 Kristian Høgsberg
*
* 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 (including the
* next paragraph) 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 <assert.h>
#include <stddef.h>
#include <stdio.h>
#include <errno.h>
#include <signal.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
#include <string.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/epoll.h>
#include <sys/signalfd.h>
#include <sys/timerfd.h>
#include <unistd.h>
#include "wayland-util.h"
#include "wayland-private.h"
#include "wayland-server-core.h"
#include "wayland-os.h"
/** \cond INTERNAL */
#define TIMER_REMOVED -2
struct wl_event_loop;
struct wl_event_source_interface;
struct wl_event_source_timer;
struct wl_event_source {
struct wl_event_source_interface *interface;
struct wl_event_loop *loop;
struct wl_list link;
void *data;
int fd;
};
struct wl_timer_heap {
struct wl_event_source base;
/* pointers to the user-visible event sources */
struct wl_event_source_timer **data;
int space, active, count;
};
struct wl_event_loop {
int epoll_fd;
struct wl_list check_list;
struct wl_list idle_list;
struct wl_list destroy_list;
struct wl_signal destroy_signal;
struct wl_timer_heap timers;
};
struct wl_event_source_interface {
int (*dispatch)(struct wl_event_source *source,
struct epoll_event *ep);
};
struct wl_event_source_fd {
struct wl_event_source base;
wl_event_loop_fd_func_t func;
int fd;
};
/** \endcond */
static int
wl_event_source_fd_dispatch(struct wl_event_source *source,
struct epoll_event *ep)
{
struct wl_event_source_fd *fd_source = (struct wl_event_source_fd *) source;
uint32_t mask;
mask = 0;
if (ep->events & EPOLLIN)
mask |= WL_EVENT_READABLE;
if (ep->events & EPOLLOUT)
mask |= WL_EVENT_WRITABLE;
if (ep->events & EPOLLHUP)
mask |= WL_EVENT_HANGUP;
if (ep->events & EPOLLERR)
mask |= WL_EVENT_ERROR;
return fd_source->func(fd_source->fd, mask, source->data);
}
struct wl_event_source_interface fd_source_interface = {
wl_event_source_fd_dispatch,
};
static struct wl_event_source *
add_source(struct wl_event_loop *loop,
struct wl_event_source *source, uint32_t mask, void *data)
{
struct epoll_event ep;
if (source->fd < 0) {
free(source);
return NULL;
}
source->loop = loop;
source->data = data;
wl_list_init(&source->link);
memset(&ep, 0, sizeof ep);
if (mask & WL_EVENT_READABLE)
ep.events |= EPOLLIN;
if (mask & WL_EVENT_WRITABLE)
ep.events |= EPOLLOUT;
ep.data.ptr = source;
if (epoll_ctl(loop->epoll_fd, EPOLL_CTL_ADD, source->fd, &ep) < 0) {
close(source->fd);
free(source);
return NULL;
}
return source;
}
/** Create a file descriptor event source
*
* \param loop The event loop that will process the new source.
* \param fd The file descriptor to watch.
* \param mask A bitwise-or of which events to watch for: \c WL_EVENT_READABLE,
* \c WL_EVENT_WRITABLE.
* \param func The file descriptor dispatch function.
* \param data User data.
* \return A new file descriptor event source.
*
* The given file descriptor is initially watched for the events given in
* \c mask. This can be changed as needed with wl_event_source_fd_update().
*
* If it is possible that program execution causes the file descriptor to be
* read while leaving the data in a buffer without actually processing it,
* it may be necessary to register the file descriptor source to be re-checked,
* see wl_event_source_check(). This will ensure that the dispatch function
* gets called even if the file descriptor is not readable or writable
* anymore. This is especially useful with IPC libraries that automatically
* buffer incoming data, possibly as a side-effect of other operations.
*
* \sa wl_event_loop_fd_func_t
* \memberof wl_event_source
*/
WL_EXPORT struct wl_event_source *
wl_event_loop_add_fd(struct wl_event_loop *loop,
int fd, uint32_t mask,
wl_event_loop_fd_func_t func,
void *data)
{
struct wl_event_source_fd *source;
source = zalloc(sizeof *source);
if (source == NULL)
return NULL;
source->base.interface = &fd_source_interface;
source->base.fd = wl_os_dupfd_cloexec(fd, 0);
source->func = func;
source->fd = fd;
return add_source(loop, &source->base, mask, data);
}
/** Update a file descriptor source's event mask
*
* \param source The file descriptor event source to update.
* \param mask The new mask, a bitwise-or of: \c WL_EVENT_READABLE,
* \c WL_EVENT_WRITABLE.
* \return 0 on success, -1 on failure.
*
* This changes which events, readable and/or writable, cause the dispatch
* callback to be called on.
*
* File descriptors are usually writable to begin with, so they do not need to
* be polled for writable until a write actually fails. When a write fails,
* the event mask can be changed to poll for readable and writable, delivering
* a dispatch callback when it is possible to write more. Once all data has
* been written, the mask can be changed to poll only for readable to avoid
* busy-looping on dispatch.
*
* \sa wl_event_loop_add_fd()
* \memberof wl_event_source
*/
WL_EXPORT int
wl_event_source_fd_update(struct wl_event_source *source, uint32_t mask)
{
struct wl_event_loop *loop = source->loop;
struct epoll_event ep;
memset(&ep, 0, sizeof ep);
if (mask & WL_EVENT_READABLE)
ep.events |= EPOLLIN;
if (mask & WL_EVENT_WRITABLE)
ep.events |= EPOLLOUT;
ep.data.ptr = source;
return epoll_ctl(loop->epoll_fd, EPOLL_CTL_MOD, source->fd, &ep);
}
/** \cond INTERNAL */
struct wl_event_source_timer {
struct wl_event_source base;
wl_event_loop_timer_func_t func;
struct wl_event_source_timer *next_due;
struct timespec deadline;
int heap_idx;
};
static int
noop_dispatch(struct wl_event_source *source,
struct epoll_event *ep) {
return 0;
}
struct wl_event_source_interface timer_heap_source_interface = {
noop_dispatch,
};
static bool
time_lt(struct timespec ta, struct timespec tb)
{
if (ta.tv_sec != tb.tv_sec) {
return ta.tv_sec < tb.tv_sec;
}
return ta.tv_nsec < tb.tv_nsec;
}
static int
set_timer(int timerfd, struct timespec deadline) {
struct itimerspec its;
its.it_interval.tv_sec = 0;
its.it_interval.tv_nsec = 0;
its.it_value = deadline;
return timerfd_settime(timerfd, TFD_TIMER_ABSTIME, &its, NULL);
}
static int
clear_timer(int timerfd)
{
struct itimerspec its;
its.it_interval.tv_sec = 0;
its.it_interval.tv_nsec = 0;
its.it_value.tv_sec = 0;
its.it_value.tv_nsec = 0;
return timerfd_settime(timerfd, 0, &its, NULL);
}
static void
wl_timer_heap_init(struct wl_timer_heap *timers, struct wl_event_loop *loop)
{
timers->base.fd = -1;
timers->base.data = NULL;
wl_list_init(&timers->base.link);
timers->base.interface = &timer_heap_source_interface;
timers->base.loop = loop;
loop->timers.data = NULL;
loop->timers.active = 0;
loop->timers.space = 0;
loop->timers.count = 0;
}
static void
wl_timer_heap_release(struct wl_timer_heap *timers)
{
if (timers->base.fd != -1) {
close(timers->base.fd);
}
free(timers->data);
}
static int
wl_timer_heap_ensure_timerfd(struct wl_timer_heap *timers)
{
struct epoll_event ep;
int timer_fd;
if (timers->base.fd != -1)
return 0;
memset(&ep, 0, sizeof ep);
ep.events = EPOLLIN;
ep.data.ptr = timers;
timer_fd = timerfd_create(CLOCK_MONOTONIC,
TFD_CLOEXEC | TFD_NONBLOCK);
if (timer_fd < 0)
return -1;
if (epoll_ctl(timers->base.loop->epoll_fd,
EPOLL_CTL_ADD, timer_fd, &ep) < 0) {
close(timer_fd);
return -1;
}
timers->base.fd = timer_fd;
return 0;
}
static int
wl_timer_heap_reserve(struct wl_timer_heap *timers)
{
struct wl_event_source_timer **n;
int new_space;
if (timers->count + 1 > timers->space) {
new_space = timers->space >= 8 ? timers->space * 2 : 8;
n = realloc(timers->data, (size_t)new_space * sizeof(*n));
if (!n) {
wl_log("Allocation failure when expanding timer list\n");
return -1;
}
timers->data = n;
timers->space = new_space;
}
timers->count++;
return 0;
}
static void
wl_timer_heap_unreserve(struct wl_timer_heap *timers)
{
struct wl_event_source_timer **n;
timers->count--;
if (timers->space >= 16 && timers->space >= 4 * timers->count) {
n = realloc(timers->data, (size_t)timers->space / 2 * sizeof(*n));
if (!n) {
wl_log("Reallocation failure when shrinking timer list\n");
return;
}
timers->data = n;
timers->space = timers->space / 2;
}
}
static int
heap_set(struct wl_event_source_timer **data,
struct wl_event_source_timer *a,
int idx)
{
int tmp;
tmp = a->heap_idx;
a->heap_idx = idx;
data[a->heap_idx] = a;
return tmp;
}
static void
heap_sift_down(struct wl_event_source_timer **data,
int num_active,
struct wl_event_source_timer *source)
{
struct wl_event_source_timer *child, *other_child;
int cursor_idx;
struct timespec key;
cursor_idx = source->heap_idx;
key = source->deadline;
while (1) {
int lchild_idx = cursor_idx * 2 + 1;
if (lchild_idx >= num_active) {
break;
}
child = data[lchild_idx];
if (lchild_idx + 1 < num_active) {
other_child = data[lchild_idx + 1];
if (time_lt(other_child->deadline, child->deadline))
child = other_child;
}
if (time_lt(child->deadline, key))
cursor_idx = heap_set(data, child, cursor_idx);
else
break;
}
heap_set(data, source, cursor_idx);
}
static void
heap_sift_up(struct wl_event_source_timer **data,
struct wl_event_source_timer *source)
{
int cursor_idx;
struct timespec key;
cursor_idx = source->heap_idx;
key = source->deadline;
while (cursor_idx > 0) {
struct wl_event_source_timer *parent =
data[(cursor_idx - 1) / 2];
if (time_lt(key, parent->deadline))
cursor_idx = heap_set(data, parent, cursor_idx);
else
break;
}
heap_set(data, source, cursor_idx);
}
/* requires timer be armed */
static void
wl_timer_heap_disarm(struct wl_timer_heap *timers,
struct wl_event_source_timer *source)
{
struct wl_event_source_timer *last_end_evt;
int old_source_idx;
assert(source->heap_idx >= 0);
old_source_idx = source->heap_idx;
source->heap_idx = -1;
source->deadline.tv_sec = 0;
source->deadline.tv_nsec = 0;
last_end_evt = timers->data[timers->active - 1];
timers->data[timers->active - 1] = NULL;
timers->active--;
if (old_source_idx == timers->active)
return;
timers->data[old_source_idx] = last_end_evt;
last_end_evt->heap_idx = old_source_idx;
/* Move the displaced (active) element to its proper place.
* Only one of sift-down and sift-up will have any effect */
heap_sift_down(timers->data, timers->active, last_end_evt);
heap_sift_up(timers->data, last_end_evt);
}
/* requires timer be disarmed */
static void
wl_timer_heap_arm(struct wl_timer_heap *timers,
struct wl_event_source_timer *source,
struct timespec deadline)
{
assert(source->heap_idx == -1);
source->deadline = deadline;
timers->data[timers->active] = source;
source->heap_idx = timers->active;
timers->active++;
heap_sift_up(timers->data, source);
}
static int
wl_timer_heap_dispatch(struct wl_timer_heap *timers)
{
struct timespec now;
struct wl_event_source_timer *root;
struct wl_event_source_timer *list_cursor = NULL, *list_tail = NULL;
clock_gettime(CLOCK_MONOTONIC, &now);
while (timers->active > 0) {
root = timers->data[0];
if (time_lt(now, root->deadline))
break;
wl_timer_heap_disarm(timers, root);
if (list_cursor == NULL)
list_cursor = root;
else
list_tail->next_due = root;
list_tail = root;
}
if (list_tail)
list_tail->next_due = NULL;
if (timers->active > 0) {
if (set_timer(timers->base.fd, timers->data[0]->deadline) < 0)
return -1;
} else {
if (clear_timer(timers->base.fd) < 0)
return -1;
}
/* Execute precisely the functions for events before `now`, in order.
* Because wl_event_loop_dispatch ignores return codes, do the same
* here as well */
for (; list_cursor; list_cursor = list_cursor->next_due) {
if (list_cursor->base.fd != TIMER_REMOVED)
list_cursor->func(list_cursor->base.data);
}
return 0;
}
static int
wl_event_source_timer_dispatch(struct wl_event_source *source,
struct epoll_event *ep)
{
struct wl_event_source_timer *timer;
timer = wl_container_of(source, timer, base);
return timer->func(timer->base.data);
}
struct wl_event_source_interface timer_source_interface = {
wl_event_source_timer_dispatch,
};
/** \endcond */
/** Create a timer event source
*
* \param loop The event loop that will process the new source.
* \param func The timer dispatch function.
* \param data User data.
* \return A new timer event source.
*
* The timer is initially disarmed. It needs to be armed with a call to
* wl_event_source_timer_update() before it can trigger a dispatch call.
*
* \sa wl_event_loop_timer_func_t
* \memberof wl_event_source
*/
WL_EXPORT struct wl_event_source *
wl_event_loop_add_timer(struct wl_event_loop *loop,
wl_event_loop_timer_func_t func,
void *data)
{
struct wl_event_source_timer *source;
if (wl_timer_heap_ensure_timerfd(&loop->timers) < 0)
return NULL;
source = zalloc(sizeof *source);
if (source == NULL)
return NULL;
source->base.interface = &timer_source_interface;
source->base.fd = -1;
source->func = func;
source->base.loop = loop;
source->base.data = data;
wl_list_init(&source->base.link);
source->next_due = NULL;
source->deadline.tv_sec = 0;
source->deadline.tv_nsec = 0;
source->heap_idx = -1;
if (wl_timer_heap_reserve(&loop->timers) < 0) {
free(source);
return NULL;
}
return &source->base;
}
/** Arm or disarm a timer
*
* \param source The timer event source to modify.
* \param ms_delay The timeout in milliseconds.
* \return 0 on success, -1 on failure.
*
* If the timeout is zero, the timer is disarmed.
*
* If the timeout is non-zero, the timer is set to expire after the given
* timeout in milliseconds. When the timer expires, the dispatch function
* set with wl_event_loop_add_timer() is called once from
* wl_event_loop_dispatch(). If another dispatch is desired after another
* expiry, wl_event_source_timer_update() needs to be called again.
*
* \memberof wl_event_source
*/
WL_EXPORT int
wl_event_source_timer_update(struct wl_event_source *source, int ms_delay)
{
struct wl_event_source_timer *tsource =
wl_container_of(source, tsource, base);
struct wl_timer_heap *timers = &tsource->base.loop->timers;
if (ms_delay > 0) {
struct timespec deadline;
clock_gettime(CLOCK_MONOTONIC, &deadline);
deadline.tv_nsec += (ms_delay % 1000) * 1000000L;
deadline.tv_sec += ms_delay / 1000;
if (deadline.tv_nsec >= 1000000000L) {
deadline.tv_nsec -= 1000000000L;
deadline.tv_sec += 1;
}
if (tsource->heap_idx == -1) {
wl_timer_heap_arm(timers, tsource, deadline);
} else if (time_lt(deadline, tsource->deadline)) {
tsource->deadline = deadline;
heap_sift_up(timers->data, tsource);
} else {
tsource->deadline = deadline;
heap_sift_down(timers->data, timers->active, tsource);
}
if (tsource->heap_idx == 0) {
/* Only update the timerfd if the new deadline is
* the earliest */
if (set_timer(timers->base.fd, deadline) < 0)
return -1;
}
} else {
if (tsource->heap_idx == -1)
return 0;
wl_timer_heap_disarm(timers, tsource);
if (timers->active == 0) {
/* Only update the timerfd if this was the last
* active timer */
if (clear_timer(timers->base.fd) < 0)
return -1;
}
}
return 0;
}
/** \cond INTERNAL */
struct wl_event_source_signal {
struct wl_event_source base;
int signal_number;
wl_event_loop_signal_func_t func;
};
/** \endcond */
static int
wl_event_source_signal_dispatch(struct wl_event_source *source,
struct epoll_event *ep)
{
struct wl_event_source_signal *signal_source =
(struct wl_event_source_signal *) source;
struct signalfd_siginfo signal_info;
int len;
len = read(source->fd, &signal_info, sizeof signal_info);
if (!(len == -1 && errno == EAGAIN) && len != sizeof signal_info)
/* Is there anything we can do here? Will this ever happen? */
wl_log("signalfd read error: %s\n", strerror(errno));
return signal_source->func(signal_source->signal_number,
signal_source->base.data);
}
struct wl_event_source_interface signal_source_interface = {
wl_event_source_signal_dispatch,
};
/** Create a POSIX signal event source
*
* \param loop The event loop that will process the new source.
* \param signal_number Number of the signal to watch for.
* \param func The signal dispatch function.
* \param data User data.
* \return A new signal event source.
*
* This function blocks the normal delivery of the given signal in the calling
* thread, and creates a "watch" for it. Signal delivery no longer happens
* asynchronously, but by wl_event_loop_dispatch() calling the dispatch
* callback function \c func.
*
* It is the caller's responsibility to ensure that all other threads have
* also blocked the signal.
*
* \sa wl_event_loop_signal_func_t
* \memberof wl_event_source
*/
WL_EXPORT struct wl_event_source *
wl_event_loop_add_signal(struct wl_event_loop *loop,
int signal_number,
wl_event_loop_signal_func_t func,
void *data)
{
struct wl_event_source_signal *source;
sigset_t mask;
source = zalloc(sizeof *source);
if (source == NULL)
return NULL;
source->base.interface = &signal_source_interface;
source->signal_number = signal_number;
sigemptyset(&mask);
sigaddset(&mask, signal_number);
source->base.fd = signalfd(-1, &mask, SFD_CLOEXEC | SFD_NONBLOCK);
sigprocmask(SIG_BLOCK, &mask, NULL);
source->func = func;
return add_source(loop, &source->base, WL_EVENT_READABLE, data);
}
/** \cond INTERNAL */
struct wl_event_source_idle {
struct wl_event_source base;
wl_event_loop_idle_func_t func;
};
/** \endcond */
struct wl_event_source_interface idle_source_interface = {
NULL,
};
/** Create an idle task
*
* \param loop The event loop that will process the new task.
* \param func The idle task dispatch function.
* \param data User data.
* \return A new idle task (an event source).
*
* Idle tasks are dispatched before wl_event_loop_dispatch() goes to sleep.
* See wl_event_loop_dispatch() for more details.
*
* Idle tasks fire once, and are automatically destroyed right after the
* callback function has been called.
*
* An idle task can be cancelled before the callback has been called by
* wl_event_source_remove(). Calling wl_event_source_remove() after or from
* within the callback results in undefined behaviour.
*
* \sa wl_event_loop_idle_func_t
* \memberof wl_event_source
*/
WL_EXPORT struct wl_event_source *
wl_event_loop_add_idle(struct wl_event_loop *loop,
wl_event_loop_idle_func_t func,
void *data)
{
struct wl_event_source_idle *source;
source = zalloc(sizeof *source);
if (source == NULL)
return NULL;
source->base.interface = &idle_source_interface;
source->base.loop = loop;
source->base.fd = -1;
source->func = func;
source->base.data = data;
wl_list_insert(loop->idle_list.prev, &source->base.link);
return &source->base;
}
/** Mark event source to be re-checked
*
* \param source The event source to be re-checked.
*
* This function permanently marks the event source to be re-checked after
* the normal dispatch of sources in wl_event_loop_dispatch(). Re-checking
* will keep iterating over all such event sources until the dispatch
* function for them all returns zero.
*
* Re-checking is used on sources that may become ready to dispatch as a
* side-effect of dispatching themselves or other event sources, including idle
* sources. Re-checking ensures all the incoming events have been fully drained
* before wl_event_loop_dispatch() returns.
*
* \memberof wl_event_source
*/
WL_EXPORT void
wl_event_source_check(struct wl_event_source *source)
{
wl_list_insert(source->loop->check_list.prev, &source->link);
}
/** Remove an event source from its event loop
*
* \param source The event source to be removed.
* \return Zero.
*
* The event source is removed from the event loop it was created for,
* and is effectively destroyed. This invalidates \c source .
* The dispatch function of the source will no longer be called through this
* source.
*
* \memberof wl_event_source
*/
WL_EXPORT int
wl_event_source_remove(struct wl_event_source *source)
{
struct wl_event_loop *loop = source->loop;
/* We need to explicitly remove the fd, since closing the fd
* isn't enough in case we've dup'ed the fd. */
if (source->fd >= 0) {
epoll_ctl(loop->epoll_fd, EPOLL_CTL_DEL, source->fd, NULL);
close(source->fd);
source->fd = -1;
}
if (source->interface == &timer_source_interface &&
source->fd != TIMER_REMOVED) {
/* Disarm the timer (and the loop's timerfd, if necessary),
* before removing its space in the loop timer heap */
wl_event_source_timer_update(source, 0);
wl_timer_heap_unreserve(&loop->timers);
/* Set the fd field to to indicate that the timer should NOT
* be dispatched in `wl_event_loop_dispatch` */
source->fd = TIMER_REMOVED;
}
wl_list_remove(&source->link);
wl_list_insert(&loop->destroy_list, &source->link);
return 0;
}
static void
wl_event_loop_process_destroy_list(struct wl_event_loop *loop)
{
struct wl_event_source *source, *next;
wl_list_for_each_safe(source, next, &loop->destroy_list, link)
free(source);
wl_list_init(&loop->destroy_list);
}
/** Create a new event loop context
*
* \return A new event loop context object.
*
* This creates a new event loop context. Initially this context is empty.
* Event sources need to be explicitly added to it.
*
* Normally the event loop is run by calling wl_event_loop_dispatch() in
* a loop until the program terminates. Alternatively, an event loop can be
* embedded in another event loop by its file descriptor, see
* wl_event_loop_get_fd().
*
* \memberof wl_event_loop
*/
WL_EXPORT struct wl_event_loop *
wl_event_loop_create(void)
{
struct wl_event_loop *loop;
loop = zalloc(sizeof *loop);
if (loop == NULL)
return NULL;
loop->epoll_fd = wl_os_epoll_create_cloexec();
if (loop->epoll_fd < 0) {
free(loop);
return NULL;
}
wl_list_init(&loop->check_list);
wl_list_init(&loop->idle_list);
wl_list_init(&loop->destroy_list);
wl_signal_init(&loop->destroy_signal);
wl_timer_heap_init(&loop->timers, loop);
return loop;
}
/** Destroy an event loop context
*
* \param loop The event loop to be destroyed.
*
* This emits the event loop destroy signal, closes the event loop file
* descriptor, and frees \c loop.
*
* If the event loop has existing sources, those cannot be safely removed
* afterwards. Therefore one must call wl_event_source_remove() on all
* event sources before destroying the event loop context.
*
* \memberof wl_event_loop
*/
WL_EXPORT void
wl_event_loop_destroy(struct wl_event_loop *loop)
{
wl_signal_emit(&loop->destroy_signal, loop);
wl_event_loop_process_destroy_list(loop);
wl_timer_heap_release(&loop->timers);
close(loop->epoll_fd);
free(loop);
}
static bool
post_dispatch_check(struct wl_event_loop *loop)
{
struct epoll_event ep;
struct wl_event_source *source, *next;
bool needs_recheck = false;
ep.events = 0;
wl_list_for_each_safe(source, next, &loop->check_list, link) {
int dispatch_result;
dispatch_result = source->interface->dispatch(source, &ep);
if (dispatch_result < 0) {
wl_log("Source dispatch function returned negative value!\n");
wl_log("This would previously accidentally suppress a follow-up dispatch\n");
}
needs_recheck |= dispatch_result != 0;
}
return needs_recheck;
}
/** Dispatch the idle sources
*
* \param loop The event loop whose idle sources are dispatched.
*
* \sa wl_event_loop_add_idle()
* \memberof wl_event_loop
*/
WL_EXPORT void
wl_event_loop_dispatch_idle(struct wl_event_loop *loop)
{
struct wl_event_source_idle *source;
while (!wl_list_empty(&loop->idle_list)) {
source = wl_container_of(loop->idle_list.next,
source, base.link);
source->func(source->base.data);
wl_event_source_remove(&source->base);
}
}
/** Wait for events and dispatch them
*
* \param loop The event loop whose sources to wait for.
* \param timeout The polling timeout in milliseconds.
* \return 0 for success, -1 for polling (or timer update) error.
*
* All the associated event sources are polled. This function blocks until
* any event source delivers an event (idle sources excluded), or the timeout
* expires. A timeout of -1 disables the timeout, causing the function to block
* indefinitely. A timeout of zero causes the poll to always return immediately.
*
* All idle sources are dispatched before blocking. An idle source is destroyed
* when it is dispatched. After blocking, all other ready sources are
* dispatched. Then, idle sources are dispatched again, in case the dispatched
* events created idle sources. Finally, all sources marked with
* wl_event_source_check() are dispatched in a loop until their dispatch
* functions all return zero.
*
* \memberof wl_event_loop
*/
WL_EXPORT int
wl_event_loop_dispatch(struct wl_event_loop *loop, int timeout)
{
struct epoll_event ep[32];
struct wl_event_source *source;
int i, count;
bool has_timers = false;
wl_event_loop_dispatch_idle(loop);
count = epoll_wait(loop->epoll_fd, ep, ARRAY_LENGTH(ep), timeout);
if (count < 0)
return -1;
for (i = 0; i < count; i++) {
source = ep[i].data.ptr;
if (source == &loop->timers.base)
has_timers = true;
}
if (has_timers) {
/* Dispatch timer sources before non-timer sources, so that
* the non-timer sources can not cancel (by calling
* `wl_event_source_timer_update`) the dispatching of the timers
* (Note that timer sources also can't cancel pending non-timer
* sources, since epoll_wait has already been called) */
if (wl_timer_heap_dispatch(&loop->timers) < 0)
return -1;
}
for (i = 0; i < count; i++) {
source = ep[i].data.ptr;
if (source->fd != -1)
source->interface->dispatch(source, &ep[i]);
}
wl_event_loop_process_destroy_list(loop);
wl_event_loop_dispatch_idle(loop);
while (post_dispatch_check(loop));
return 0;
}
/** Get the event loop file descriptor
*
* \param loop The event loop context.
* \return The aggregate file descriptor.
*
* This function returns the aggregate file descriptor, that represents all
* the event sources (idle sources excluded) associated with the given event
* loop context. When any event source makes an event available, it will be
* reflected in the aggregate file descriptor.
*
* When the aggregate file descriptor delivers an event, one can call
* wl_event_loop_dispatch() on the event loop context to dispatch all the
* available events.
*
* \memberof wl_event_loop
*/
WL_EXPORT int
wl_event_loop_get_fd(struct wl_event_loop *loop)
{
return loop->epoll_fd;
}
/** Register a destroy listener for an event loop context
*
* \param loop The event loop context whose destruction to listen for.
* \param listener The listener with the callback to be called.
*
* \sa wl_listener
* \memberof wl_event_loop
*/
WL_EXPORT void
wl_event_loop_add_destroy_listener(struct wl_event_loop *loop,
struct wl_listener *listener)
{
wl_signal_add(&loop->destroy_signal, listener);
}
/** Get the listener struct for the specified callback
*
* \param loop The event loop context to inspect.
* \param notify The destroy callback to find.
* \return The wl_listener registered to the event loop context with
* the given callback pointer.
*
* \memberof wl_event_loop
*/
WL_EXPORT struct wl_listener *
wl_event_loop_get_destroy_listener(struct wl_event_loop *loop,
wl_notify_func_t notify)
{
return wl_signal_get(&loop->destroy_signal, notify);
}
| 26.351054 | 80 | 0.729417 | [
"object"
] |
37d72debdfbd58793c3f13814bdc2512dbe4f42d | 932 | h | C | include/txcheckpoint/key-iterator.h | microsoft/fugue | 087db98d2e072675c272d3e5505af64d1c653585 | [
"MIT"
] | 3 | 2020-08-03T12:31:53.000Z | 2021-08-30T10:28:19.000Z | include/txcheckpoint/key-iterator.h | microsoft/fugue | 087db98d2e072675c272d3e5505af64d1c653585 | [
"MIT"
] | null | null | null | include/txcheckpoint/key-iterator.h | microsoft/fugue | 087db98d2e072675c272d3e5505af64d1c653585 | [
"MIT"
] | 3 | 2020-07-31T10:46:05.000Z | 2021-11-10T08:25:38.000Z | #ifndef TXSERVICE_TXCHECKPOINT_KEY_ITERATOR_H_
#define TXSERVICE_TXCHECKPOINT_KEY_ITERATOR_H_
#include "versiondb/key.h"
namespace txservice::txcheckpoint
{
class KeyIterator
{
public:
using Pointer = std::unique_ptr<KeyIterator>;
virtual bool HasNext() = 0;
virtual Key &Next() = 0;
KeyIterator(void *key_deserializer)
{
this->key_deserializer_ = key_deserializer;
}
KeyIterator(const KeyIterator &) = delete;
virtual ~KeyIterator()
{
}
protected:
void *key_deserializer_;
std::vector<Key::Pointer> key_container;
};
class ActiveKeyIterator : public KeyIterator
{
public:
ActiveKeyIterator(int64_t checkpoint_ts, void *key_deserializer)
: KeyIterator(key_deserializer)
{
this->checkpoint_ts_ = checkpoint_ts;
}
protected:
int64_t checkpoint_ts_;
};
} // namespace txservice::txcheckpoint
#endif // TXSERVICE_TXCHECKPOINT_KEY_ITERATOR_H_
| 22.731707 | 68 | 0.723176 | [
"vector"
] |
37e7028227a651244a02cbba80b6e7729d2880ba | 14,680 | h | C | TAO/tao/Stub.h | cflowe/ACE | 5ff60b41adbe1772372d1a43bcc1f2726ff8f810 | [
"DOC"
] | 36 | 2015-01-10T07:27:33.000Z | 2022-03-07T03:32:08.000Z | TAO/tao/Stub.h | cflowe/ACE | 5ff60b41adbe1772372d1a43bcc1f2726ff8f810 | [
"DOC"
] | 2 | 2018-08-13T07:30:51.000Z | 2019-02-25T03:04:31.000Z | TAO/tao/Stub.h | cflowe/ACE | 5ff60b41adbe1772372d1a43bcc1f2726ff8f810 | [
"DOC"
] | 38 | 2015-01-08T14:12:06.000Z | 2022-01-19T08:33:00.000Z | // -*- C++ -*-
//=============================================================================
/**
* @file Stub.h
*
* $Id: Stub.h 96783 2013-02-07 23:05:45Z mesnier_p $
*
* @author Portions Copyright 1994-1995 by Sun Microsystems Inc.
* @author Portions Copyright 1997-2002 by Washington University
*/
//=============================================================================
#ifndef TAO_STUB_H
#define TAO_STUB_H
#include /**/ "ace/pre.h"
#include "tao/ORB.h"
#if !defined (ACE_LACKS_PRAGMA_ONCE)
# pragma once
#endif /* ACE_LACKS_PRAGMA_ONCE */
#include "tao/MProfile.h"
#include "tao/ORB_Core_Auto_Ptr.h"
#include "ace/Atomic_Op.h"
#if defined (HPUX) && defined (IOR)
/* HP-UX 11.11 defines IOR in /usr/include/pa/inline.h
and we don't want that definition. See IOP_IORC.h. */
# undef IOR
#endif /* HPUX && IOR */
TAO_BEGIN_VERSIONED_NAMESPACE_DECL
// Forward declarations.
class TAO_Abstract_ServantBase;
class TAO_Policy_Set;
class TAO_Profile;
namespace TAO
{
class ObjectKey;
class Object_Proxy_Broker;
class Transport_Queueing_Strategy;
}
namespace IOP
{
struct IOR;
}
/**
* @class TAO_Stub
*
* @brief TAO_Stub
*
* Per-objref data includes the (protocol-specific) Profile, which
* is handled by placing it into a subclass of this type along
* with data that may be used in protocol-specific caching
* schemes.
* The type ID (the data specified by CORBA 2.0 that gets exposed
* "on the wire", and in stringified objrefs) is held by this
* module.
* The stub APIs are member functions of this type.
*/
class TAO_Export TAO_Stub
{
public:
#if (TAO_HAS_CORBA_MESSAGING == 1)
/**
* Returns the effective policy if @a type is a known client-exposed
* policy type. Returns the effective override for all other policy
* types.
*/
virtual CORBA::Policy_ptr get_policy (CORBA::PolicyType type);
virtual CORBA::Policy_ptr get_cached_policy (TAO_Cached_Policy_Type type);
virtual TAO_Stub* set_policy_overrides (const CORBA::PolicyList & policies,
CORBA::SetOverrideType set_add);
virtual CORBA::PolicyList *get_policy_overrides (
const CORBA::PolicyTypeSeq & types);
#endif
/// Return the queueing strategy to be used in by the transport.
/// Selection will be based on the SyncScope policies.
TAO::Transport_Queueing_Strategy *transport_queueing_strategy (void);
/// All objref representations carry around a type ID.
CORBA::String_var type_id;
/**
* All objref representations know how to hash themselves and
* compare themselves for equivalence to others. It's easily
* possible to have two objrefs that are distinct copies of data
* that refers/points to the same remote object (i.e. are
* equivalent).
*/
CORBA::ULong hash (CORBA::ULong maximum);
/// Implement the is_equivalent() method for the CORBA::Object
CORBA::Boolean is_equivalent (CORBA::Object_ptr other_obj);
// Our Constructors ...
/// Construct from a repository ID and a list of profiles.
TAO_Stub (const char *repository_id,
const TAO_MProfile &profiles,
TAO_ORB_Core *orb_core);
// = Memory management.
void _incr_refcnt (void);
void _decr_refcnt (void);
/// Return the Profile lock. This lock can be used at places where
/// profiles need to be edited.
const TAO_SYNCH_MUTEX& profile_lock (void) const;
/// Manage the base (non-forwarded) profiles.
/// Returns a pointer to the profile_in_use object. This object
/// retains ownership of this profile.
TAO_Profile *profile_in_use (void);
/// Return the ObjectKey
const TAO::ObjectKey &object_key (void) const;
/**
* Copy of the profile list, user must free memory when done.
* although the user can call make_profiles() then reorder
* the list and give it back to TAO_Stub.
*/
TAO_MProfile *make_profiles (void);
/// Obtain a reference to the basic profile set.
const TAO_MProfile& base_profiles (void) const;
/// Obtain a reference to the basic profile set.
TAO_MProfile& base_profiles (void);
/// Obtain a pointer to the forwarded profile set
const TAO_MProfile *forward_profiles (void) const;
/// Obtain a pointer to the forwarded profile set
TAO_MProfile *forward_profiles (void);
/// True if permanent location forward occured, in this case the lock must be set and the
// Manage forward and base profiles.
/**
* THREAD SAFE. If forward_profiles is null then this will
* get the next profile in the base_profiles list. If forward is not null
* then this will get the next profile for the list of forwarding
* profiles. If all profiles have been tried then 0 is returned and
* profile_in_use_ is set to the first profile in the base_profiles
* list.
*/
TAO_Profile *next_profile (void);
/**
* THREAD SAFE
* This method will reset the base profile list to reference the first
* profile and if there are anmy existing forward profiles they are
* reset.
*/
void reset_profiles (void);
/// Returns true if the profile in use is
/// the same as the profile in use after
/// reset_profiles() is called.
CORBA::Boolean at_starting_profile (void) const;
/// Returns true if a forward profile has successfully been used.
/// profile_success_ && forward_profiles_
CORBA::Boolean valid_forward_profile (void);
/// NON-THREAD-SAFE. Will set profile_success_ to true.
void set_valid_profile (void);
/// Returns true if a connection was successful with at least
/// one profile.
CORBA::Boolean valid_profile (void) const;
/// Initialize the base_profiles_ and set profile_in_use_ to
/// reference the first profile.
TAO_Profile *base_profiles (const TAO_MProfile& mprofiles);
/**
* THREAD SAFE.
* Set the forward_profiles. This object will assume ownership of
* this TAO_MProfile object!! if permanent_forward is true,
* currently used profiles will be replaced permanently, otherwise
* stub may fallback to current profiles later. The flag
* permanent_forward=true is only valid if currently used profile
* set represents a GroupObject (IOGR), otherwise this flag will be
* ignored.
*/
void add_forward_profiles (const TAO_MProfile &mprofiles,
const CORBA::Boolean permanent_forward=false);
/**
* THREAD SAFE
* Used to get the next profile after the one being used has
* failed during the initial connect or send of the message!
*/
CORBA::Boolean next_profile_retry (void);
/// Accessor.
TAO_ORB_Core* orb_core (void) const;
/// Is this stub collocated with the servant?
CORBA::Boolean is_collocated (void) const;
/// Mutator to mark this stub as being collocated with the servant.
void is_collocated (CORBA::Boolean);
/// This returns a duplicated ORB pointer.
CORBA::ORB_ptr servant_orb_ptr (void);
/// This returns the ORB var itself (generally for temporary use).
CORBA::ORB_var &servant_orb_var (void);
/**
* Accesor and mutator for the servant ORB. Notice that the mutator
* assumes the ownership of the passed in ORB and the accesor does not
* return a copy of the orb since the accessing of the ORB is considered
* temporary.
*/
void servant_orb (CORBA::ORB_ptr orb);
/// Mutator for setting the servant in collocated cases.
void collocated_servant (TAO_Abstract_ServantBase* servant);
/// Accessor for the servant reference in collocated cases.
TAO_Abstract_ServantBase* collocated_servant (void) const;
/// Mutator for setting the object proxy broker pointer.
/// CORBA::Objects using this stub will use this for standard calls
/// like is_a; get_interface; etc...
void object_proxy_broker (TAO::Object_Proxy_Broker *proxy_broker);
/// Accessor for getting the object proxy broker pointer.
/// CORBA::Objects using this stub use this for standard calls
/// like is_a; get_interface; etc...
TAO::Object_Proxy_Broker *object_proxy_broker (void) const;
/**
* Create the IOP::IOR info. We will create the info at most once.
* Get the index of the profile we are using to make the invocation.
*/
int create_ior_info (IOP::IOR *&ior_info, CORBA::ULong &index);
/// Deallocate the TAO_Stub object.
/**
* This method is intended to be used only by the CORBA::Object
* class.
*/
void destroy (void);
/// Return the cached value from the ORB_Core.
/**
* This flag indicates whether the stub code should make use of the
* collocation opportunities that are available to the ORB.
*/
CORBA::Boolean optimize_collocation_objects (void) const;
/// Needed to avoid copying forward_profiles for thread safety
CORBA::Boolean marshal (TAO_OutputCDR&);
void forwarded_on_exception (bool forwarded);
bool forwarded_on_exception () const;
protected:
/// Destructor is to be called only through _decr_refcnt() to
/// enforce proper reference counting.
virtual ~TAO_Stub (void);
/// NON-THREAD SAFE version of reset_profiles (void);
void reset_profiles_i (void);
/// NON-THREAD SAFE version of next_profile (void)
TAO_Profile *next_profile_i (void);
private:
/// Makes a copy of the profile and frees the existing profile_in_use.
/// NOT THREAD SAFE
TAO_Profile *set_profile_in_use_i (TAO_Profile *pfile);
/// NON-THREAD-SAFE. Utility method which resets or initializes
/// the base_profile list and forward flags.
void reset_base ();
/// NON-THREAD-SAFE. Utility method which unrolls (removes or pops)
/// the top most forwarding profile list.
void forward_back_one (void);
/// NOT THREAD-SAFE. Utility method which pops all forward profile
/// lists and resets the forward_profiles_ pointer.
void reset_forward ();
/// NON-THREAD-SAFE. utility method for next_profile.
TAO_Profile *next_forward_profile (void);
/// THREAD-SAFE Create the IOR info
int get_profile_ior_info (TAO_MProfile &profile, IOP::IOR *&ior_info);
private:
// = Disallow copy construction and assignment.
TAO_Stub (const TAO_Stub &);
TAO_Stub &operator = (const TAO_Stub &);
protected:
/// Automatically manage the ORB_Core reference count
/**
* The ORB_Core cannot go away until the object references it
* creates are destroyed. There are multiple reasons for this, but
* in particular, the allocators used for some of the TAO_Profile
* objects contained on each TAO_Stub are owned by the TAO_ORB_Core.
*
* This <B>must</B> be the first field of the class, otherwise the
* TAO_ORB_Core is destroyed too early!
*
*/
TAO_ORB_Core_Auto_Ptr orb_core_;
/// ORB required for reference counting. This will help us keep the
/// ORB around until the CORBA::Object we represent dies.
/**
* @todo Why do we need both a reference to the ORB_Core and its
* ORB? It think the memory management rules for the ORB_Core
* changed, in the good old days it was the CORBA::ORB class
* who owned the ORB_Core, now it is the other way around....
*/
CORBA::ORB_var orb_;
/// Flag that indicates that this stub is collocated (and that it
/// belongs to an ORB for which collocation optimisation is active).
CORBA::Boolean is_collocated_;
/**
* If this stub refers to a collocated object then we need to hold on to
* the servant's ORB (which may be different from the client ORB) so that,
* 1. we know that the ORB will stay alive long enough, and,
* 2. we can search for the servant/POA's status starting from
* the ORB's RootPOA.
*/
CORBA::ORB_var servant_orb_;
/// Servant pointer. It is 0 except for collocated objects.
TAO_Abstract_ServantBase *collocated_servant_;
/// Pointer to the Proxy Broker
/**
* This cached pointer instance takes care of routing the call for
* standard calls in CORBA::Object like _is_a (), _get_component
* () etc.
*/
TAO::Object_Proxy_Broker *object_proxy_broker_;
/// Ordered list of profiles for this object.
TAO_MProfile base_profiles_;
/// The list of forwarding profiles. This is actually implemented as a
/// linked list of TAO_MProfile objects.
TAO_MProfile *forward_profiles_;
/// The bookmark indicating permanent forward occurred,
/// the pointer is used to identify bottom of stack forward_profiles_
TAO_MProfile *forward_profiles_perm_;
/// This is the profile that we are currently sending/receiving with.
TAO_Profile *profile_in_use_;
/// Mutex to protect access to the forwarding profile.
TAO_SYNCH_MUTEX profile_lock_;
/// Have we successfully talked to the forward profile yet?
CORBA::Boolean profile_success_;
/// Reference counter.
ACE_Atomic_Op<TAO_SYNCH_MUTEX, unsigned long> refcount_;
/// The policy overrides in this object, if nil then use the default
/// policies.
TAO_Policy_Set *policies_;
/**
* The ior info. This is needed for GIOP 1.2, as the clients could
* receive an exception from the server asking for this info. The
* exception that the client receives is LOC_NEEDS_ADDRESSING_MODE.
* The data is set up here to be passed on to Invocation classes
* when they receive an exception. This info is for the base
* profiles that this class stores
*/
IOP::IOR *ior_info_;
/// Forwarded IOR info
IOP::IOR *forwarded_ior_info_;
/// TRUE if we want to take advantage of collocation optimization in
/// this ORB.
/**
* This should be the same value as cached in the ORB_Core. The
* reason for caching this helps our generated code, notably the
* stubs to be decoupled from ORB_Core. Please do not move it away.
*/
CORBA::Boolean const collocation_opt_;
/// True if forwarding request upon some specific exceptions
/// (e.g. OBJECT_NOT_EXIST) already happened.
ACE_Atomic_Op<TAO_SYNCH_MUTEX, bool> forwarded_on_exception_;
};
// Define a TAO_Stub auto_ptr class.
/**
* @class TAO_Stub_Auto_Ptr
*
* @brief Implements the draft C++ standard auto_ptr abstraction.
* This class allows one to work Stub Objects *Only*!
*/
class TAO_Export TAO_Stub_Auto_Ptr
{
public:
// = Initialization and termination methods.
explicit TAO_Stub_Auto_Ptr (TAO_Stub *p = 0);
TAO_Stub_Auto_Ptr (TAO_Stub_Auto_Ptr &ap);
TAO_Stub_Auto_Ptr &operator= (TAO_Stub_Auto_Ptr &rhs);
~TAO_Stub_Auto_Ptr (void);
// = Accessor methods.
TAO_Stub &operator *() const;
TAO_Stub *get (void) const;
TAO_Stub *release (void);
void reset (TAO_Stub *p = 0);
TAO_Stub *operator-> () const;
protected:
TAO_Stub *p_;
};
TAO_END_VERSIONED_NAMESPACE_DECL
#if defined (__ACE_INLINE__)
# include "tao/Stub.inl"
#endif /* __ACE_INLINE__ */
#include /**/ "ace/post.h"
#endif /* TAO_STUB_H */
| 32.192982 | 91 | 0.708992 | [
"object"
] |
37f775d8025ca70631aa454e5825b86dafd9a083 | 2,464 | h | C | cpp_wrappers/cpp_subsampling/grid_subsampling/grid_subsampling.h | kuramin/KPConv-PyTorch | 94b1d87e17ec339e2aad049ce5d5d175b9cd0db1 | [
"MIT"
] | 451 | 2020-04-28T01:26:08.000Z | 2022-03-31T04:39:48.000Z | cpp_wrappers/cpp_subsampling/grid_subsampling/grid_subsampling.h | kuramin/KPConv-PyTorch | 94b1d87e17ec339e2aad049ce5d5d175b9cd0db1 | [
"MIT"
] | 156 | 2020-05-07T03:40:16.000Z | 2022-03-29T14:53:57.000Z | cpp_wrappers/cpp_subsampling/grid_subsampling/grid_subsampling.h | Dashark/KPConv-PyTorch | e2b3a5d7d4f2adfe6cdc95c8e17d89b30b065278 | [
"MIT"
] | 100 | 2020-04-28T03:01:57.000Z | 2022-03-28T07:53:21.000Z |
#include "../../cpp_utils/cloud/cloud.h"
#include <set>
#include <cstdint>
using namespace std;
class SampledData
{
public:
// Elements
// ********
int count;
PointXYZ point;
vector<float> features;
vector<unordered_map<int, int>> labels;
// Methods
// *******
// Constructor
SampledData()
{
count = 0;
point = PointXYZ();
}
SampledData(const size_t fdim, const size_t ldim)
{
count = 0;
point = PointXYZ();
features = vector<float>(fdim);
labels = vector<unordered_map<int, int>>(ldim);
}
// Method Update
void update_all(const PointXYZ p, vector<float>::iterator f_begin, vector<int>::iterator l_begin)
{
count += 1;
point += p;
transform (features.begin(), features.end(), f_begin, features.begin(), plus<float>());
int i = 0;
for(vector<int>::iterator it = l_begin; it != l_begin + labels.size(); ++it)
{
labels[i][*it] += 1;
i++;
}
return;
}
void update_features(const PointXYZ p, vector<float>::iterator f_begin)
{
count += 1;
point += p;
transform (features.begin(), features.end(), f_begin, features.begin(), plus<float>());
return;
}
void update_classes(const PointXYZ p, vector<int>::iterator l_begin)
{
count += 1;
point += p;
int i = 0;
for(vector<int>::iterator it = l_begin; it != l_begin + labels.size(); ++it)
{
labels[i][*it] += 1;
i++;
}
return;
}
void update_points(const PointXYZ p)
{
count += 1;
point += p;
return;
}
};
void grid_subsampling(vector<PointXYZ>& original_points,
vector<PointXYZ>& subsampled_points,
vector<float>& original_features,
vector<float>& subsampled_features,
vector<int>& original_classes,
vector<int>& subsampled_classes,
float sampleDl,
int verbose);
void batch_grid_subsampling(vector<PointXYZ>& original_points,
vector<PointXYZ>& subsampled_points,
vector<float>& original_features,
vector<float>& subsampled_features,
vector<int>& original_classes,
vector<int>& subsampled_classes,
vector<int>& original_batches,
vector<int>& subsampled_batches,
float sampleDl,
int max_p);
| 24.156863 | 98 | 0.560471 | [
"vector",
"transform"
] |
37fdb8e0e998f5fe2a844ffc2e39b9957cb1b3c8 | 15,618 | h | C | thirdparty/vcpkg/installed/x86-windows/include/magick/studio.h | CybernetHacker14/ND-Cpp-Route-Planning | fc69cd7e43f658ad028ec573fb7f38d16634a6de | [
"Apache-2.0"
] | null | null | null | thirdparty/vcpkg/installed/x86-windows/include/magick/studio.h | CybernetHacker14/ND-Cpp-Route-Planning | fc69cd7e43f658ad028ec573fb7f38d16634a6de | [
"Apache-2.0"
] | null | null | null | thirdparty/vcpkg/installed/x86-windows/include/magick/studio.h | CybernetHacker14/ND-Cpp-Route-Planning | fc69cd7e43f658ad028ec573fb7f38d16634a6de | [
"Apache-2.0"
] | null | null | null | /*
Copyright (C) 2003 - 2020 GraphicsMagick Group
Copyright (C) 2002 ImageMagick Studio
This program is covered by multiple licenses, which are described in
Copyright.txt. You should have received a copy of Copyright.txt with this
package; otherwise see http://www.graphicsmagick.org/www/Copyright.html.
GraphicsMagick Application Programming Interface declarations.
*/
#ifndef _MAGICK_STUDIO_H
#define _MAGICK_STUDIO_H
#if defined(__cplusplus) || defined(c_plusplus)
extern "C" {
#endif
/*
This define is not used by GraphicsMagick and it causes some headers
from other installed packages (e.g. MinGW libpthread) to misbehave.
*/
#undef HAVE_CONFIG_H
/*
Note that the WIN32 and WIN64 definitions are provided by the build
configuration rather than the compiler. Definitions available from the
Windows compiler are _WIN32 and _WIN64. Note that _WIN32 is defined if
_WIN64 is defined.
*/
#if defined(WIN32) || defined(WIN64)
# define MSWINDOWS
#endif /* defined(WIN32) || defined(WIN64) */
#if !defined(MSWINDOWS)
# define POSIX
#endif /* !defined(MSWINDOWS) */
/*
Private functions and types which are not part of the published API
should only be exposed when MAGICK_IMPLEMENTATION is defined.
*/
#define MAGICK_IMPLEMENTATION 1
#include "magick/magick_config.h"
#if defined(__cplusplus) || defined(c_plusplus)
# undef inline
#endif /* defined(__cplusplus) || defined(c_plusplus) */
/*
Allow configuration of cache line size. If smaller than actual cache line
size, then performance may suffer due to false cache line sharing between
threads. Most CPUs have cache lines of 32 or 64 bytes. IBM Power CPUs have
cache lines of 128 bytes.
*/
/* C pre-processor does not support comparing strings. */
#if defined(__powerpc__)
# define MAGICK_CACHE_LINE_SIZE 128
#else
# define MAGICK_CACHE_LINE_SIZE 64
#endif
/*
Support library symbol prefixing
*/
#if defined(PREFIX_MAGICK_SYMBOLS)
# include "magick/symbols.h"
#endif /* defined(PREFIX_MAGICK_SYMBOLS) */
#if !defined(const)
/*
For some stupid reason the zlib headers define 'const' to nothing
under AIX unless STDC is defined.
*/
# define STDC
#endif /* !defined(const) */
/*
For the Windows Visual C++ DLL build, use a Windows resource based
message lookup table (i.e. use FormatMessage()).
*/
#if 0
/*
Currently disabled since feature only seems to work from
a DLL
*/
# if ((defined(MSWINDOWS) && defined(_DLL)) && !defined(__MINGW32__))
# define MAGICK_WINDOWS_MESSAGE_TABLES 1
# endif
#endif
#include <stdarg.h>
#include <stdio.h>
#if defined(MSWINDOWS) && defined(_DEBUG)
# define _CRTDBG_MAP_ALLOC
#endif
#include <stdlib.h>
#include <stddef.h> /* C'99 size_t, ptrdiff_t, NULL */
#if !defined(MSWINDOWS)
# include <unistd.h>
#else
# include <direct.h>
# include <io.h>
# if !defined(HAVE_STRERROR)
# define HAVE_STRERROR
# endif
#endif
/*
Use fseeko() and ftello() if they are available since they use
'off_t' rather than 'long'. It is wrong to use fseeko() and
ftello() only on systems with special LFS support since some systems
(e.g. FreeBSD) support a 64-bit off_t by default.
*/
#if defined(HAVE_FSEEKO)
# define fseek fseeko
# define ftell ftello
#endif
#if !defined(ExtendedSignedIntegralType)
# define ExtendedSignedIntegralType magick_int64_t
#endif
#if !defined(ExtendedUnsignedIntegralType)
# define ExtendedUnsignedIntegralType magick_uint64_t
#endif
#include <string.h>
#include <ctype.h>
#include <locale.h>
#include <errno.h>
#include <fcntl.h>
#include <math.h>
#include <time.h>
#include <limits.h>
#include <signal.h>
#include <assert.h>
#include <sys/types.h>
#include <sys/stat.h>
#if defined(HAVE_FTIME)
# include <sys/timeb.h>
#endif
#if defined(HAVE_STDINT_H)
# include <stdint.h>
#endif
#if defined(POSIX)
# if defined(HAVE_SYS_NDIR_H) || defined(HAVE_SYS_DIR_H) || defined(HAVE_NDIR_H)
# define dirent direct
# define NAMLEN(dirent) (dirent)->d_namlen
# if defined(HAVE_SYS_NDIR_H)
# include <sys/ndir.h>
# endif
# if defined(HAVE_SYS_DIR_H)
# include <sys/dir.h>
# endif
# if defined(HAVE_NDIR_H)
# include <ndir.h>
# endif
# else
# include <dirent.h>
# define NAMLEN(dirent) strlen((dirent)->d_name)
# endif
# include <sys/wait.h>
# if defined(HAVE_SYS_RESOURCE_H)
# include <sys/resource.h>
# endif /* defined(HAVE_SYS_RESOURCE_H) */
# if defined(HAVE_SYS_MMAN_H)
# include <sys/mman.h>
# endif /* defined(HAVE_SYS_MMAN_H) */
# include <pwd.h>
#endif
#if !defined(S_ISDIR)
# define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
#endif
#if !defined(S_ISREG)
# define S_ISREG(mode) (((mode) & S_IFMT) == S_IFREG)
#endif
/*
Avoid shadowing system library globals and functions.
*/
#undef gamma
#define gamma gamma_magick
#undef swab
#define swab swab_magick
#undef y1
#define y1 y1_magick
/*
Include common bits shared with api.h
*/
#include "magick/common.h"
/*
Enable use of numeric message IDs and a translation table in order
to support multiple locales.
*/
#define MAGICK_IDBASED_MESSAGES 1
#if defined(MAGICK_IDBASED_MESSAGES)
# include "magick/locale_c.h"
#endif
#include "magick/magick_types.h"
#include "magick/image.h"
#include "magick/list.h"
#include "magick/memory.h"
#if !defined(MSWINDOWS)
# include <sys/time.h>
# if defined(HAVE_SYS_TIMES_H)
# include <sys/times.h>
# endif
#endif
#if defined(POSIX)
# include "magick/unix_port.h"
#endif /* defined(POSIX) */
#if defined(MSWINDOWS)
# include "magick/nt_base.h"
#endif /* defined(MSWINDOWS) */
#if defined(HAVE_MMAP_FILEIO) && !defined(MSWINDOWS)
# include <sys/mman.h>
#endif
#if defined(HAVE_PTHREAD)
# include <pthread.h>
#endif
#if defined(HAVE_POLL)
# include <sys/poll.h>
#endif
/*
Work around OpenMP implementation bugs noticed in the Open64 5.0 compiler
These workarounds will be removed once the bugs have been fixed in a release.
Open64 5.0 provides these definitions:
__OPENCC__ 5 -- OpenCC major version
__OPENCC_MINOR__ 0 -- OpenCC minor version
__OPEN64__ "5.0" -- OpenCC stringified version
*/
#if defined(__OPENCC__)
# undef USE_STATIC_SCHEDULING_ONLY
# define USE_STATIC_SCHEDULING_ONLY 1
#endif
/*
OpenMP support requires version 2.0 (March 2002) or later.
*/
#if defined(_OPENMP) && ((_OPENMP >= 200203) || defined(__OPENCC__))
# include <omp.h>
# define HAVE_OPENMP 1
#endif
#undef index
#undef pipe
/*
If TRIO library is used, remap snprintf and vsnprintf to TRIO equivalents.
*/
#if defined(HasTRIO)
# include <trio.h>
# define snprintf trio_snprintf
# define HAVE_SNPRINTF 1
# define vsnprintf trio_vsnprintf
# define HAVE_VSNPRINTF 1
#endif
/*
Provide prototypes for several functions which are detected to be
available, but which do not provide a prototype due to interface
standards conformance (or a bug).
*/
#if defined(HAVE_PREAD) && defined(HAVE_DECL_PREAD) && !HAVE_DECL_PREAD
ssize_t pread(int fildes, void *buf, size_t nbyte, off_t offset);
#endif
#if defined(HAVE_PWRITE) && defined(HAVE_DECL_PWRITE) && !HAVE_DECL_PWRITE
ssize_t pwrite(int fildes, const void *buf, size_t nbyte, off_t offset);
#endif
#if defined(HAVE_STRLCPY) && defined(HAVE_DECL_STRLCPY) && !HAVE_DECL_STRLCPY
extern size_t strlcpy(char *dst, const char *src, size_t dstsize);
#endif
#if defined(HAVE_VSNPRINTF) && defined(HAVE_DECL_VSNPRINTF) && !HAVE_DECL_VSNPRINTF
extern int vsnprintf(char *s, size_t n, const char *format, va_list ap);
#endif
/*
Some 64-bit int support.
*/
#if defined(HAVE_STRTOLL) && (SIZEOF_SIGNED_LONG < 8)
# define MagickStrToL64(str,endptr,base) (strtoll(str,endptr,base))
#else
# define MagickStrToL64(str,endptr,base) ((magick_int64_t) strtol(str,endptr,base))
#endif
#if defined(HAVE_ATOLL) && (SIZEOF_SIGNED_LONG < 8)
# define MagickAtoL64(str) (atoll(str))
#else
# define MagickAtoL64(str) ((magick_int64_t) atol(str))
#endif
/*
Review these platform specific definitions.
*/
#if defined(POSIX)
# define DirectorySeparator "/"
# define DirectoryListSeparator ':'
# define EditorOptions " -title \"Edit Image Comment\" -e vi"
# define Exit exit
# define IsBasenameSeparator(c) ((c) == '/')
# define PreferencesDefaults "~/."
# define ProcessPendingEvents(text)
# define ReadCommandlLine(argc,argv)
# define SetNotifyHandlers
# define MagickSleep(seconds) sleep(seconds)
#endif
#if defined(MSWINDOWS)
# define DirectorySeparator "\\"
# define DirectoryListSeparator ';'
# define EditorOptions ""
# define IsBasenameSeparator(c) (((c) == '/') || ((c) == '\\'))
# define ProcessPendingEvents(text)
# if !defined(PreferencesDefaults)
# define PreferencesDefaults "~\\."
# endif /* PreferencesDefaults */
# define ReadCommandlLine(argc,argv)
# define SetNotifyHandlers \
SetErrorHandler(NTErrorHandler); \
SetWarningHandler(NTWarningHandler)
# define MagickSleep(seconds) Sleep(seconds*1000)
# if !defined(HAVE_TIFFCONF_H)
# define HAVE_TIFFCONF_H
# endif
#endif /* defined(MSWINDOWS) */
/*
Define declarations.
*/
#define AbsoluteValue(x) ((x) < 0 ? -(x) : (x))
#define ArraySize(a) (sizeof(a)/sizeof(a[0]))
#define False 0
#define DegreesToRadians(x) (MagickPI*(x)/180.0)
#define MagickIncarnate(x) InitializeMagick(x)
#define MagickEpsilon 1.0e-12
#define MagickPI 3.14159265358979323846264338327950288419716939937510
#define MagickSQ2PI 2.50662827463100024161235523934010416269302368164062
#if !defined(INFINITY) /* C'99 provides INFINITY but C'89 does not */
# define INFINITY (log(0))
#endif
#define Max(x,y) (((x) > (y)) ? (x) : (y))
#define Min(x,y) (((x) < (y)) ? (x) : (y))
#define NumberOfObjectsInArray(octets,size) (octets/size) /* rounds down */
#define QuantumTick(i,span) \
((((i) % ((Max(101,span)-1)/100)) == 0) || \
((magick_int64_t) (i) == ((magick_int64_t) (span)-1)))
#define RadiansToDegrees(x) (180.0*(x)/MagickPI)
#define RoundUpToAlignment(offset,alignment) \
(((offset)+((alignment)-1)) & ~((alignment)-1))
#define AssertAlignment(offset,alignment) \
(assert((((size_t) offset) % (size_t) alignment) == (size_t) 0))
#define NormalizeDepthToOctet(depth) (depth < 8 ? 8 : \
(depth < 16 ? 16 : (depth < 32 ? 32 : depth)))
#define ScaleColor5to8(x) (((x) << 3) | ((x) >> 2))
#define ScaleColor6to8(x) (((x) << 2) | ((x) >> 4))
#define Swap(x,y) ((x)^=(y), (y)^=(x), (x)^=(y))
#define True 1
#define DefineNameToString(value) #value
#define DefineValueToString(define) DefineNameToString(define)
#if !defined(COSF)
# if defined(HAVE_COSF)
# define COSF(f) cosf((float) (f))
# else
# define COSF(d) cos(d)
# endif
#endif /* !defined(COSF) */
#if !defined(FABSF)
# if defined(HAVE_FABSF)
# define FABSF(f) fabsf((float) (f))
# else
# define FABSF(d) fabs(d)
# endif
#endif /* !defined(FABSF) */
#if !defined(LOGF)
# if defined(HAVE_LOGF)
# define LOGF(f) logf((float) (f))
# else
# define LOGF(d) log(d)
# endif
#endif /* !defined(LOGF) */
#if !defined(SINF)
# if defined(HAVE_SINF)
# define SINF(f) sinf((float) (f))
# else
# define SINF(d) sin(d)
# endif
#endif /* !defined(SINF) */
#if !defined(SQRTF)
# if defined(HAVE_SQRTF)
# define SQRTF(f) sqrtf((float) (f))
# else
# define SQRTF(d) sqrt(d)
# endif
#endif /* !defined(SQRTF) */
/*
atof(), atoi(), and atol() are legacy functions which might not be
thread safe, might not enforce reasonable limits, and should not be
used for new code. So we implement them via strtod and strtol.
*/
#define MagickAtoF(str) (strtod(str, (char **)NULL))
#define MagickAtoI(str) ((int) strtol(str, (char **)NULL, 10))
#define MagickAtoL(str) (strtol(str, (char **)NULL, 10))
/*
3D effects.
*/
#define AccentuateModulate ScaleCharToQuantum(80)
#define HighlightModulate ScaleCharToQuantum(125)
#define ShadowModulate ScaleCharToQuantum(135)
#define DepthModulate ScaleCharToQuantum(185)
#define TroughModulate ScaleCharToQuantum(110)
/*
Define system symbols if not already defined.
*/
#if !defined(STDIN_FILENO)
# define STDIN_FILENO 0x00
#endif
#if !defined(O_BINARY)
# define O_BINARY 0x00
#endif
#if !defined(MAP_FAILED)
# define MAP_FAILED ((void *) -1)
#endif
#if !defined(PATH_MAX)
# define PATH_MAX 4096
#endif
/*
When using Autoconf configure script, BuildMagickModules is defined by
magick/magick_config.h when modules are to be built. Building modules
requires that support for shared libraries be enabled.
When using Visual Studio and when using the Autoconf configure script with
MinGW these options are supplied when compiling the associated components:
libMagick: _DLL _MAGICKMOD_ _MAGICKLIB_
module: _DLL
executable/Magick++: _DLL _MAGICKMOD_
The Visual Studio build only knows how to build a static build, or a DLL
modules-based build. The Autotools-based build knows how to build static,
shared, and modules builds.
Libtool's libltdl is required to build modules when the Autoconf configure
script is used.
*/
#if defined(HasLTDL)
//# define SupportMagickModules
#elif !defined(__MINGW32__) && !defined(__MINGW64__)
# if defined(MSWINDOWS) && defined(_DLL)
//# define SupportMagickModules
# endif
#endif
#if defined(_MAGICKMOD_)
# undef BuildMagickModules
# define BuildMagickModules
#endif
/*
C99 isblank() is not portable enough yet.
*/
#define MagickIsBlank(c) (c== ' ' || c == '\t')
#if !defined(MagickMmap)
# define MagickMmap(address,length,protection,access,file,offset) \
mmap(address,length,protection,access,file,offset)
#endif
#if !defined(MagickMsync)
# define MagickMsync(addr,len,flags) msync(addr,len,flags)
#endif
#if !defined(MagickMunmap)
# define MagickMunmap(addr,len) munmap(addr,len)
#endif
#if !defined(MagickFtruncate)
# define MagickFtruncate(filedes,length) ftruncate(filedes,length)
#endif
#if !defined(HAVE_POPEN) && defined(HAVE__POPEN)
# define HAVE_POPEN 1
# define popen _popen
#endif /* !defined(HAVE_POPEN) && defined(HAVE__POPEN) */
#if !defined(HAVE_PCLOSE) && defined(HAVE__PCLOSE)
# define HAVE_PCLOSE 1
# define pclose _pclose
#endif /* !defined(HAVE_PCLOSE) && defined(HAVE__PCLOSE) */
#if defined(HAVE__EXIT)
# define SignalHandlerExit _exit
#else
# define SignalHandlerExit Exit
#endif /* defined(HAVE__EXIT) */
/*
OpenMP function null replacements if not using OpenMP.
*/
#if !defined(HAVE_OPENMP)
# undef omp_get_max_threads
# define omp_get_max_threads() 1
# undef omp_get_num_threads
# define omp_get_num_threads() 1
# undef omp_get_thread_num
# define omp_get_thread_num() 0
# undef omp_set_num_threads
# define omp_set_num_threads(nthreads)
#endif /* !defined(HAVE_OPENMP) */
/*
Common const definitions
*/
#define BackgroundColor "#ffffffffffff" /* white */
#define BorderColor "#dfdfdfdfdfdf" /* gray */
#define DefaultTileFrame "15x15+3+3"
#define DefaultTileGeometry "120x120+4+3>"
#define DefaultTileLabel "%f\n%wx%h\n%b"
#define ForegroundColor "#000000000000" /* black */
#define HighlightColor "#f1f100001e1e" /* light red */
#define MatteColor "#bdbdbdbdbdbd" /* gray */
#define PSDensityGeometry "72.0x72.0"
#define PSPageGeometry "612x792>"
#define LoadImageText "[%s] Loading image: %lux%lu... "
#define SaveImageText "[%s] Saving image: %lux%lu... "
#define LoadImagesText "[%s] Loading images... "
#define SaveImagesText "[%s] Saving images... "
#define DefaultCompressionQuality 75U
#if defined(__cplusplus) || defined(c_plusplus)
}
#endif /* defined(__cplusplus) || defined(c_plusplus) */
#endif /* ifndef _MAGICK_STUDIO_H */
/*
* Local Variables:
* mode: c
* c-basic-offset: 2
* fill-column: 78
* End:
*/
| 27.4 | 84 | 0.715457 | [
"3d"
] |
53044458acbebf8dd182aa73f7ae3753d0612a02 | 4,735 | c | C | kubernetes/model/v1_replica_set_spec.c | fgerlits/kubernetes-client-c | 8df3411545b902d751efd96fbc616c36386dcfaa | [
"Apache-2.0"
] | 69 | 2020-03-17T13:47:05.000Z | 2022-03-30T08:25:05.000Z | kubernetes/model/v1_replica_set_spec.c | fgerlits/kubernetes-client-c | 8df3411545b902d751efd96fbc616c36386dcfaa | [
"Apache-2.0"
] | 115 | 2020-03-17T14:53:19.000Z | 2022-03-31T11:31:30.000Z | kubernetes/model/v1_replica_set_spec.c | fgerlits/kubernetes-client-c | 8df3411545b902d751efd96fbc616c36386dcfaa | [
"Apache-2.0"
] | 28 | 2020-03-17T13:42:21.000Z | 2022-03-19T23:37:16.000Z | #include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "v1_replica_set_spec.h"
v1_replica_set_spec_t *v1_replica_set_spec_create(
int min_ready_seconds,
int replicas,
v1_label_selector_t *selector,
v1_pod_template_spec_t *_template
) {
v1_replica_set_spec_t *v1_replica_set_spec_local_var = malloc(sizeof(v1_replica_set_spec_t));
if (!v1_replica_set_spec_local_var) {
return NULL;
}
v1_replica_set_spec_local_var->min_ready_seconds = min_ready_seconds;
v1_replica_set_spec_local_var->replicas = replicas;
v1_replica_set_spec_local_var->selector = selector;
v1_replica_set_spec_local_var->_template = _template;
return v1_replica_set_spec_local_var;
}
void v1_replica_set_spec_free(v1_replica_set_spec_t *v1_replica_set_spec) {
if(NULL == v1_replica_set_spec){
return ;
}
listEntry_t *listEntry;
if (v1_replica_set_spec->selector) {
v1_label_selector_free(v1_replica_set_spec->selector);
v1_replica_set_spec->selector = NULL;
}
if (v1_replica_set_spec->_template) {
v1_pod_template_spec_free(v1_replica_set_spec->_template);
v1_replica_set_spec->_template = NULL;
}
free(v1_replica_set_spec);
}
cJSON *v1_replica_set_spec_convertToJSON(v1_replica_set_spec_t *v1_replica_set_spec) {
cJSON *item = cJSON_CreateObject();
// v1_replica_set_spec->min_ready_seconds
if(v1_replica_set_spec->min_ready_seconds) {
if(cJSON_AddNumberToObject(item, "minReadySeconds", v1_replica_set_spec->min_ready_seconds) == NULL) {
goto fail; //Numeric
}
}
// v1_replica_set_spec->replicas
if(v1_replica_set_spec->replicas) {
if(cJSON_AddNumberToObject(item, "replicas", v1_replica_set_spec->replicas) == NULL) {
goto fail; //Numeric
}
}
// v1_replica_set_spec->selector
if (!v1_replica_set_spec->selector) {
goto fail;
}
cJSON *selector_local_JSON = v1_label_selector_convertToJSON(v1_replica_set_spec->selector);
if(selector_local_JSON == NULL) {
goto fail; //model
}
cJSON_AddItemToObject(item, "selector", selector_local_JSON);
if(item->child == NULL) {
goto fail;
}
// v1_replica_set_spec->_template
if(v1_replica_set_spec->_template) {
cJSON *_template_local_JSON = v1_pod_template_spec_convertToJSON(v1_replica_set_spec->_template);
if(_template_local_JSON == NULL) {
goto fail; //model
}
cJSON_AddItemToObject(item, "template", _template_local_JSON);
if(item->child == NULL) {
goto fail;
}
}
return item;
fail:
if (item) {
cJSON_Delete(item);
}
return NULL;
}
v1_replica_set_spec_t *v1_replica_set_spec_parseFromJSON(cJSON *v1_replica_set_specJSON){
v1_replica_set_spec_t *v1_replica_set_spec_local_var = NULL;
// define the local variable for v1_replica_set_spec->selector
v1_label_selector_t *selector_local_nonprim = NULL;
// define the local variable for v1_replica_set_spec->_template
v1_pod_template_spec_t *_template_local_nonprim = NULL;
// v1_replica_set_spec->min_ready_seconds
cJSON *min_ready_seconds = cJSON_GetObjectItemCaseSensitive(v1_replica_set_specJSON, "minReadySeconds");
if (min_ready_seconds) {
if(!cJSON_IsNumber(min_ready_seconds))
{
goto end; //Numeric
}
}
// v1_replica_set_spec->replicas
cJSON *replicas = cJSON_GetObjectItemCaseSensitive(v1_replica_set_specJSON, "replicas");
if (replicas) {
if(!cJSON_IsNumber(replicas))
{
goto end; //Numeric
}
}
// v1_replica_set_spec->selector
cJSON *selector = cJSON_GetObjectItemCaseSensitive(v1_replica_set_specJSON, "selector");
if (!selector) {
goto end;
}
selector_local_nonprim = v1_label_selector_parseFromJSON(selector); //nonprimitive
// v1_replica_set_spec->_template
cJSON *_template = cJSON_GetObjectItemCaseSensitive(v1_replica_set_specJSON, "template");
if (_template) {
_template_local_nonprim = v1_pod_template_spec_parseFromJSON(_template); //nonprimitive
}
v1_replica_set_spec_local_var = v1_replica_set_spec_create (
min_ready_seconds ? min_ready_seconds->valuedouble : 0,
replicas ? replicas->valuedouble : 0,
selector_local_nonprim,
_template ? _template_local_nonprim : NULL
);
return v1_replica_set_spec_local_var;
end:
if (selector_local_nonprim) {
v1_label_selector_free(selector_local_nonprim);
selector_local_nonprim = NULL;
}
if (_template_local_nonprim) {
v1_pod_template_spec_free(_template_local_nonprim);
_template_local_nonprim = NULL;
}
return NULL;
}
| 29.409938 | 108 | 0.719535 | [
"model"
] |
530455b5d629bcec466b508d62e70a5b4c743fc1 | 7,531 | h | C | include/graphics/SpriteBatch.h | caseymcc/Vorb | a2782bbff662c226002fa69bae688a44770deaf4 | [
"MIT"
] | 1 | 2018-10-17T06:37:17.000Z | 2018-10-17T06:37:17.000Z | include/graphics/SpriteBatch.h | caseymcc/Vorb | a2782bbff662c226002fa69bae688a44770deaf4 | [
"MIT"
] | null | null | null | include/graphics/SpriteBatch.h | caseymcc/Vorb | a2782bbff662c226002fa69bae688a44770deaf4 | [
"MIT"
] | null | null | null | //
// SpriteBatch.h
// Vorb Engine
//
// Created by Cristian Zaloj on 17 Jan 2015
// Refactored by Benjamin Arnold on 3 May 2015
// Copyright 2014 Regrowth Studios
// All Rights Reserved
//
/*! \file SpriteBatch.h
* @brief Defines the SpriteBatch for easy and efficient 2D rendering of Sprites.
*/
#pragma once
#ifndef Vorb_SpriteBatch_h__
//! @cond DOXY_SHOW_HEADER_GUARDS
#define Vorb_SpriteBatch_h__
//! @endcond
#ifndef VORB_USING_PCH
#include "../types.h"
#endif // !VORB_USING_PCH
#include <cfloat>
#include "../PtrRecycler.hpp"
#include "../VorbPreDecl.inl"
#include "SpriteFont.h"
#include "gtypes.h"
#define CLIP_RECT_DEFAULT f32v4(-(FLT_MAX / 2.0f), -(FLT_MAX / 2.0f), FLT_MAX, FLT_MAX)
namespace vorb {
namespace graphics {
class DepthState;
class GLProgram;
class RasterizerState;
class SamplerState;
/// Sorting mode for SpriteBatch sprites
enum class SpriteSortMode {
NONE,
FRONT_TO_BACK,
BACK_TO_FRONT,
TEXTURE
};
enum class GradientType {
NONE,
HORIZONTAL,
VERTICAL,
LEFT_DIAGONAL,
RIGHT_DIAGONAL
};
class SpriteBatch {
public:
SpriteBatch(bool isDynamic = true, bool init = false);
~SpriteBatch();
void init();
void dispose();
void begin();
void draw(VGTexture t, f32v4* uvRect, f32v2* uvTiling, const f32v2& position, const f32v2& offset, const f32v2& size, f32 rotation, const color4& tint1, const color4& tint2, GradientType grad, f32 depth = 0.0f);
void draw(VGTexture t, f32v4* uvRect, f32v2* uvTiling, const f32v2& position, const f32v2& offset, const f32v2& size, f32 rotation, const color4& tint, f32 depth = 0.0f);
void draw(VGTexture t, f32v4* uvRect, f32v2* uvTiling, const f32v2& position, const f32v2& offset, const f32v2& size, const color4& tint1, const color4& tint2, GradientType grad, f32 depth = 0.0f);
void draw(VGTexture t, f32v4* uvRect, f32v2* uvTiling, const f32v2& position, const f32v2& offset, const f32v2& size, const color4& tint, f32 depth = 0.0f);
void draw(VGTexture t, f32v4* uvRect, f32v2* uvTiling, const f32v2& position, const f32v2& size, const color4& tint1, const color4& tint2, GradientType grad, f32 depth = 0.0f);
void draw(VGTexture t, f32v4* uvRect, f32v2* uvTiling, const f32v2& position, const f32v2& size, const color4& tint, f32 depth = 0.0f);
void draw(VGTexture t, f32v4* uvRect, const f32v2& position, const f32v2& size, const color4& tint1, const color4& tint2, GradientType grad, f32 depth = 0.0f);
void draw(VGTexture t, f32v4* uvRect, const f32v2& position, const f32v2& size, const color4& tint, f32 depth = 0.0f);
void draw(VGTexture t, const f32v2& position, const f32v2& size, const color4& tint1, const color4& tint2, GradientType grad, f32 depth = 0.0f);
void draw(VGTexture t, const f32v2& position, const f32v2& size, const color4& tint, f32 depth = 0.0f);
void drawString(const SpriteFont* font, const cString s, const f32v2& position, const f32v2& scaling, const color4& tint, TextAlign textAlign = TextAlign::TOP_LEFT, f32 depth = 0.0f, const f32v4& clipRect = CLIP_RECT_DEFAULT, bool shouldWrap = true);
void drawString(const SpriteFont* font, const cString s, const f32v2& position, f32 desiredHeight, f32 scaleX, const color4& tint, TextAlign textAlign = TextAlign::TOP_LEFT, f32 depth = 0.0f, const f32v4& clipRect = CLIP_RECT_DEFAULT, bool shouldWrap = true);
void end(SpriteSortMode ssm = SpriteSortMode::TEXTURE);
void render(const f32m4& mWorld, const f32m4& mCamera, /*const BlendState* bs = nullptr,*/ const SamplerState* ss = nullptr, const DepthState* ds = nullptr, const RasterizerState* rs = nullptr, vg::GLProgram* shader = nullptr);
void render(const f32m4& mWorld, const f32v2& screenSize, /*const BlendState* bs = nullptr,*/ const SamplerState* ss = nullptr, const DepthState* ds = nullptr, const RasterizerState* rs = nullptr, vg::GLProgram* shader = nullptr);
void render(const f32v2& screenSize, /*const BlendState* bs = nullptr,*/ const SamplerState* ss = nullptr, const DepthState* ds = nullptr, const RasterizerState* rs = nullptr, vg::GLProgram* shader = nullptr);
void sortGlyphs(SpriteSortMode ssm);
void generateBatches();
static void disposeProgram();
private:
struct Glyph; struct Vertex;
typedef void(SpriteBatch::*QuadBuildFunc)(const Glyph*, Vertex*);
struct Glyph {
Glyph(QuadBuildFunc f, VGTexture tex, const f32v4& uvRect, const f32v2& uvTiling, const f32v2& position, const f32v2& offset, const f32v2& size, f32 rotation, const color4& tint, f32 depth);
Glyph(QuadBuildFunc f, VGTexture tex, const f32v4& uvRect, const f32v2& uvTiling, const f32v2& position, const f32v2& offset, const f32v2& size, f32 rotation, const color4& tint1, const color4& tint2, GradientType grad, f32 depth);
VGTexture tex;
f32v4 uvRect;
f32v2 uvTiling;
f32v2 position;
f32v2 offset;
f32v2 size;
f32 rotation;
color4 tint1;
color4 tint2;
GradientType grad;
f32 depth;
QuadBuildFunc func;
};
struct Vertex {
public:
Vertex() {};
Vertex(const f32v3& pos, const f32v2& uv, const f32v4& uvr, const color4& color);
f32v3 position;
f32v2 uv;
f32v4 uvRect;
color4 color;
};
class Batch {
public:
void set(ui32 iOff, ui32 texID);
ui32 textureID;
ui32 indices;
ui32 indexOffset;
};
/// Sorting functions
static bool SSMTexture(Glyph* g1, Glyph* g2) { return g1->tex < g2->tex; }
static bool SSMFrontToBack(Glyph* g1, Glyph* g2) { return g1->depth < g2->depth; }
static bool SSMBackToFront(Glyph* g1, Glyph* g2) { return g1->depth > g2->depth; }
/// Quad builders
void buildQuad(const Glyph* g, Vertex* verts);
void buildQuadOffset(const Glyph* g, Vertex* verts);
void buildQuadRotated(const Glyph* g, Vertex* verts);
/// For color gradients
void calcColor(Vertex& vtl, Vertex& vtr, Vertex& vbl, Vertex& vbr, const Glyph* g);
std::vector<Glyph> m_glyphs; ///< Glyph data
std::vector<Glyph*> m_glyphPtrs; ///< Pointers to glyphs for fast sorting
ui32 m_bufUsage; ///< Buffer usage hint
VGVertexArray m_vao = 0; ///< Vertex Array Object
VGBuffer m_vbo = 0; ///< Vertex Buffer Object
VGBuffer m_ibo = 0; ///< Index Buffer Object
ui32 m_indexCapacity = 0; ///< Current capacity of the m_ibo
std::vector<Batch> m_batches; ///< Vector of batches for rendering
static vg::GLProgram m_program; ///< Shader handle
ui32 m_texPixel; ///< Default White Pixel Texture
};
}
}
namespace vg = vorb::graphics;
#undef CLIP_RECT_DEFAULT
#endif // !Vorb_SpriteBatch_h__
| 45.920732 | 271 | 0.621299 | [
"render",
"object",
"vector"
] |
5307385ec778684f7e1bae17a6958db7cfb75647 | 722 | h | C | sources/2020/2020_04.h | tbielak/AoC_cpp | 69f36748536e60a1b88f9d44a285feff20df8470 | [
"MIT"
] | 2 | 2021-02-01T13:19:37.000Z | 2021-02-25T10:39:46.000Z | sources/2020/2020_04.h | tbielak/AoC_cpp | 69f36748536e60a1b88f9d44a285feff20df8470 | [
"MIT"
] | null | null | null | sources/2020/2020_04.h | tbielak/AoC_cpp | 69f36748536e60a1b88f9d44a285feff20df8470 | [
"MIT"
] | null | null | null | #ifndef __2020_04__
#define __2020_04__
#include "../shared/input_output.h"
namespace Day04_2020
{
typedef map<string, string> t_fields;
typedef vector<t_fields> t_passports;
class CheckEngine
{
public:
CheckEngine(const vector<string>& input);
size_t complete_count() const;
size_t valid_count() const;
private:
t_passports _passports;
void load_passport(const string& input);
bool is_number(const string& s) const;
bool yr_check(const string& s, int yr_min, int yr_max) const;
bool hgt_check(const string& s) const;
bool hcl_check(const string& s) const;
bool ecl_check(const string& s) const;
bool pid_check(const string& s) const;
};
t_output main(const t_input& input);
}
#endif
| 20.628571 | 63 | 0.740997 | [
"vector"
] |
531c193ac635431ff4609d5fc5f07d29e31157a9 | 2,616 | h | C | app/include/OrigYTransExperimentHCI.h | tinker-lab/AnchoredGestures | ca5ac616149e19f6db7ee493b89fc1c0109c0fb2 | [
"MIT"
] | null | null | null | app/include/OrigYTransExperimentHCI.h | tinker-lab/AnchoredGestures | ca5ac616149e19f6db7ee493b89fc1c0109c0fb2 | [
"MIT"
] | null | null | null | app/include/OrigYTransExperimentHCI.h | tinker-lab/AnchoredGestures | ca5ac616149e19f6db7ee493b89fc1c0109c0fb2 | [
"MIT"
] | null | null | null |
#ifndef OrigYTransExperimentHCI_H
#define OrigYTransExperimentHCI_H
#include "AbstractHCI.h"
#include "MVRCore/AbstractCamera.H"
#include <MVRCore/CameraOffAxis.H>
#include "CFrameMgr.H"
#include "app/include/GPUMesh.h"
#include "app/include/GLSLProgram.h"
#include <glm/glm.hpp>
#include <glm/gtc/matrix_access.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/epsilon.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <MVRCore/DataFileUtils.H>
#include "app/include/TextureMgr.h"
#include "app/include/TouchData.h"
#include <glm/gtx/string_cast.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <MVRCore/Time.h>
#include <iterator>
#include "app/include/Feedback.h"
class OrigYTransExperimentHCI : public AbstractHCI {
public:
OrigYTransExperimentHCI(MinVR::AbstractCameraRef camera, CFrameMgrRef cFrameMgr, TextureMgrRef textMan, FeedbackRef feedback);
virtual ~OrigYTransExperimentHCI();
void update(const std::vector<MinVR::EventRef> &events);
void draw(int threadId, MinVR::AbstractCameraRef camera, MinVR::WindowRef window);
virtual void initializeContextSpecificVars(int threadId,MinVR::WindowRef window);
void reset();
private:
struct movement{
string touchName;
double distance;
boost::posix_time::ptime timeStamp;
};
bool offerTouchDown(MinVR::EventRef event);
bool offerTouchUp(int id);
void offerTouchMove(MinVR::EventRef event);
void updateTrackers(const glm::dmat4 &rightTrackerFrame, const glm::dmat4 &leftTrackerFrame);
glm::dvec3 convertScreenToRoomCoordinates(glm::dvec2 screenCoords);
void determineTouchToHandCoorespondence(TouchDataRef touch);
bool testForCrazyManipulation(const glm::dmat4& xFrame);
double getTotalMovement(std::vector<movement> moves);
TextureMgrRef texMan;
std::shared_ptr<MinVR::CameraOffAxis> offAxisCamera;
glm::dvec3 _centerAxis;
bool _touch1IsValid;
bool _touch2IsValid;
TouchDataRef _touch1;
TouchDataRef _touch2;
glm::dvec3 _lastRotationAxis;
glm::dvec3 _lastLeftAxis;
glm::dvec3 _lastRightAxis;
std::vector<glm::dvec3> _leftAxisHistory;
std::vector<glm::dvec3> _rightAxisHistory;
std::vector<float> _leftAngleHistory;
std::vector<float> _rightAngleHistory;
bool _rotating;
bool _translating;
glm::dmat4 _previousRightTrackerFrame;
glm::dmat4 _previousLeftTrackerFrame;
glm::dmat4 _currentRightTrackerFrame;
glm::dmat4 _currentLeftTrackerFrame;
std::vector<movement> _touch1Moves;
std::vector<movement> _touch2Moves;
glm::dmat4 _currRotationFrame;
std::map<int, TouchDataRef> registeredTouchData;
};
#endif
| 32.7 | 128 | 0.772554 | [
"vector"
] |
531ce299beefd09c72815182e267cb9a55db323e | 7,671 | h | C | cmds/statsd/src/logd/LogEvent.h | rio-31/android_frameworks_base-1 | 091a068a3288d27d77636708679dde58b7b7fd25 | [
"Apache-2.0"
] | 164 | 2015-01-05T16:49:11.000Z | 2022-03-29T20:40:27.000Z | cmds/statsd/src/logd/LogEvent.h | rio-31/android_frameworks_base-1 | 091a068a3288d27d77636708679dde58b7b7fd25 | [
"Apache-2.0"
] | 127 | 2015-01-12T12:02:32.000Z | 2021-11-28T08:46:25.000Z | cmds/statsd/src/logd/LogEvent.h | rio-31/android_frameworks_base-1 | 091a068a3288d27d77636708679dde58b7b7fd25 | [
"Apache-2.0"
] | 1,141 | 2015-01-01T22:54:40.000Z | 2022-02-09T22:08:26.000Z | /*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include "FieldValue.h"
#include <android/frameworks/stats/1.0/types.h>
#include <android/os/StatsLogEventWrapper.h>
#include <android/util/ProtoOutputStream.h>
#include <log/log_event_list.h>
#include <log/log_read.h>
#include <private/android_logger.h>
#include <utils/Errors.h>
#include <string>
#include <vector>
using namespace android::frameworks::stats::V1_0;
namespace android {
namespace os {
namespace statsd {
struct AttributionNodeInternal {
void set_uid(int32_t id) {
mUid = id;
}
void set_tag(const std::string& value) {
mTag = value;
}
int32_t uid() const {
return mUid;
}
const std::string& tag() const {
return mTag;
}
int32_t mUid;
std::string mTag;
};
struct InstallTrainInfo {
int64_t trainVersionCode;
std::string trainName;
int32_t status;
std::vector<int64_t> experimentIds;
};
/**
* Wrapper for the log_msg structure.
*/
class LogEvent {
public:
/**
* Read a LogEvent from a log_msg.
*/
explicit LogEvent(log_msg& msg);
/**
* Creates LogEvent from StatsLogEventWrapper.
*/
static void createLogEvents(const StatsLogEventWrapper& statsLogEventWrapper,
std::vector<std::shared_ptr<LogEvent>>& logEvents);
/**
* Construct one LogEvent from a StatsLogEventWrapper with the i-th work chain. -1 if no chain.
*/
explicit LogEvent(const StatsLogEventWrapper& statsLogEventWrapper, int workChainIndex);
/**
* Constructs a LogEvent with synthetic data for testing. Must call init() before reading.
*/
explicit LogEvent(int32_t tagId, int64_t wallClockTimestampNs, int64_t elapsedTimestampNs);
// For testing. The timestamp is used as both elapsed real time and logd timestamp.
explicit LogEvent(int32_t tagId, int64_t timestampNs);
// For testing. The timestamp is used as both elapsed real time and logd timestamp.
explicit LogEvent(int32_t tagId, int64_t timestampNs, int32_t uid);
/**
* Constructs a KeyValuePairsAtom LogEvent from value maps.
*/
explicit LogEvent(int32_t tagId, int64_t wallClockTimestampNs, int64_t elapsedTimestampNs,
int32_t uid,
const std::map<int32_t, int32_t>& int_map,
const std::map<int32_t, int64_t>& long_map,
const std::map<int32_t, std::string>& string_map,
const std::map<int32_t, float>& float_map);
// Constructs a BinaryPushStateChanged LogEvent from API call.
explicit LogEvent(const std::string& trainName, int64_t trainVersionCode, bool requiresStaging,
bool rollbackEnabled, bool requiresLowLatencyMonitor, int32_t state,
const std::vector<uint8_t>& experimentIds, int32_t userId);
explicit LogEvent(int64_t wallClockTimestampNs, int64_t elapsedTimestampNs,
const VendorAtom& vendorAtom);
explicit LogEvent(int64_t wallClockTimestampNs, int64_t elapsedTimestampNs,
const InstallTrainInfo& installTrainInfo);
~LogEvent();
/**
* Get the timestamp associated with this event.
*/
inline int64_t GetLogdTimestampNs() const { return mLogdTimestampNs; }
inline int64_t GetElapsedTimestampNs() const { return mElapsedTimestampNs; }
/**
* Get the tag for this event.
*/
inline int GetTagId() const { return mTagId; }
inline uint32_t GetUid() const {
return mLogUid;
}
/**
* Get the nth value, starting at 1.
*
* Returns BAD_INDEX if the index is larger than the number of elements.
* Returns BAD_TYPE if the index is available but the data is the wrong type.
*/
int64_t GetLong(size_t key, status_t* err) const;
int GetInt(size_t key, status_t* err) const;
const char* GetString(size_t key, status_t* err) const;
bool GetBool(size_t key, status_t* err) const;
float GetFloat(size_t key, status_t* err) const;
/**
* Write test data to the LogEvent. This can only be used when the LogEvent is constructed
* using LogEvent(tagId, timestampNs). You need to call init() before you can read from it.
*/
bool write(uint32_t value);
bool write(int32_t value);
bool write(uint64_t value);
bool write(int64_t value);
bool write(const std::string& value);
bool write(float value);
bool write(const std::vector<AttributionNodeInternal>& nodes);
bool write(const AttributionNodeInternal& node);
bool writeKeyValuePairs(int32_t uid,
const std::map<int32_t, int32_t>& int_map,
const std::map<int32_t, int64_t>& long_map,
const std::map<int32_t, std::string>& string_map,
const std::map<int32_t, float>& float_map);
/**
* Return a string representation of this event.
*/
std::string ToString() const;
/**
* Write this object to a ProtoOutputStream.
*/
void ToProto(android::util::ProtoOutputStream& out) const;
/**
* Used with the constructor where tag is passed in. Converts the log_event_list to read mode
* and prepares the list for reading.
*/
void init();
/**
* Set elapsed timestamp if the original timestamp is missing.
*/
void setElapsedTimestampNs(int64_t timestampNs) {
mElapsedTimestampNs = timestampNs;
}
/**
* Set the timestamp if the original logd timestamp is missing.
*/
void setLogdWallClockTimestampNs(int64_t timestampNs) {
mLogdTimestampNs = timestampNs;
}
inline int size() const {
return mValues.size();
}
const std::vector<FieldValue>& getValues() const {
return mValues;
}
std::vector<FieldValue>* getMutableValues() {
return &mValues;
}
inline LogEvent makeCopy() {
return LogEvent(*this);
}
private:
/**
* Only use this if copy is absolutely needed.
*/
LogEvent(const LogEvent&);
/**
* Parses a log_msg into a LogEvent object.
*/
void init(android_log_context context);
// The items are naturally sorted in DFS order as we read them. this allows us to do fast
// matching.
std::vector<FieldValue> mValues;
// This field is used when statsD wants to create log event object and write fields to it. After
// calling init() function, this object would be destroyed to save memory usage.
// When the log event is created from log msg, this field is never initiated.
android_log_context mContext = NULL;
// The timestamp set by the logd.
int64_t mLogdTimestampNs;
// The elapsed timestamp set by statsd log writer.
int64_t mElapsedTimestampNs;
int mTagId;
uint32_t mLogUid;
};
void writeExperimentIdsToProto(const std::vector<int64_t>& experimentIds, std::vector<uint8_t>* protoOut);
} // namespace statsd
} // namespace os
} // namespace android
| 30.807229 | 106 | 0.663668 | [
"object",
"vector"
] |
1b2eeb16ce3877f4058b8c00ea072d2377e38312 | 2,665 | h | C | src/cpp-ethereum/libethereum/LogFilter.h | nccproject/ncc | 068ccc82a73d28136546095261ad8ccef7e541a3 | [
"MIT"
] | 42 | 2021-01-04T01:59:21.000Z | 2021-05-14T14:35:04.000Z | src/cpp-ethereum/libethereum/LogFilter.h | estxcoin/estcore | 4398b1d944373fe25668469966fa2660da454279 | [
"MIT"
] | 4 | 2018-07-17T13:33:26.000Z | 2018-08-27T07:10:49.000Z | src/cpp-ethereum/libethereum/LogFilter.h | estxcoin/estcore | 4398b1d944373fe25668469966fa2660da454279 | [
"MIT"
] | 22 | 2018-04-24T00:33:31.000Z | 2022-02-03T09:40:26.000Z | /*
This file is part of cpp-ethereum.
cpp-ethereum 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.
cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file LogFilter.h
* @author Gav Wood <i@gavwood.com>
* @date 2014
*/
#pragma once
#include <libdevcore/Common.h>
#include <libdevcore/RLP.h>
#include <libethcore/Common.h>
#include "TransactionReceipt.h"
#ifdef __INTEL_COMPILER
#pragma warning(disable:1098) //the qualifier on this friend declaration is ignored
#endif
namespace dev
{
namespace eth
{
class LogFilter;
}
namespace eth
{
/// Simple stream output for the StateDiff.
std::ostream& operator<<(std::ostream& _out, dev::eth::LogFilter const& _s);
class State;
class Block;
class LogFilter
{
public:
LogFilter(h256 _earliest = EarliestBlockHash, h256 _latest = PendingBlockHash): m_earliest(_earliest), m_latest(_latest) {}
void streamRLP(RLPStream& _s) const;
h256 sha3() const;
/// hash of earliest block which should be filtered
h256 earliest() const { return m_earliest; }
/// hash of latest block which should be filtered
h256 latest() const { return m_latest; }
/// Range filter is a filter which doesn't care about addresses or topics
/// Matches are all entries from earliest to latest
/// @returns true if addresses and topics are unspecified
bool isRangeFilter() const;
/// @returns bloom possibilities for all addresses and topics
std::vector<LogBloom> bloomPossibilities() const;
bool matches(LogBloom _bloom) const;
bool matches(Block const& _b, unsigned _i) const;
LogEntries matches(TransactionReceipt const& _r) const;
LogFilter address(Address _a) { m_addresses.insert(_a); return *this; }
LogFilter topic(unsigned _index, h256 const& _t) { if (_index < 4) m_topics[_index].insert(_t); return *this; }
LogFilter withEarliest(h256 _e) { m_earliest = _e; return *this; }
LogFilter withLatest(h256 _e) { m_latest = _e; return *this; }
friend std::ostream& dev::eth::operator<<(std::ostream& _out, dev::eth::LogFilter const& _s);
private:
AddressHash m_addresses;
std::array<h256Hash, 4> m_topics;
h256 m_earliest = EarliestBlockHash;
h256 m_latest = PendingBlockHash;
};
}
}
| 28.655914 | 124 | 0.747467 | [
"vector"
] |
1b34e4a369f8d7ee880765764b10f697b8062228 | 8,839 | h | C | 3rdparty/TooN/wls.h | jih189/object_detection_ros | 026803cbb9a12da47f524cb59670d348152bec25 | [
"BSD-3-Clause"
] | 49 | 2015-04-24T18:26:03.000Z | 2018-05-31T09:27:38.000Z | 3rdparty/TooN/wls.h | jih189/object_detection_ros | 026803cbb9a12da47f524cb59670d348152bec25 | [
"BSD-3-Clause"
] | 5 | 2015-04-13T16:00:38.000Z | 2018-03-06T05:47:10.000Z | 3rdparty/TooN/wls.h | jih189/object_detection_ros | 026803cbb9a12da47f524cb59670d348152bec25 | [
"BSD-3-Clause"
] | 32 | 2015-01-19T16:15:35.000Z | 2018-05-20T16:34:08.000Z |
/*
Copyright (C) 2005 Tom Drummond
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef __WLS_H
#define __WLS_H
#include <TooN/TooN.h>
#include <TooN/SVD.h>
#include <TooN/helpers.h>
#include <cassert>
#include <cmath>
#ifndef TOON_NO_NAMESPACE
namespace TooN {
#endif
/// Performs weighted least squares computation.
/// @param Size The number of dimensions in the system
/// @ingroup gEquations
template <int Size=-1>
class WLS {
public:
/// Default constructor
WLS(){clear();}
/// Construct using a given regularisation prior
WLS(double prior){clear(prior);}
/// Clear all the measurements and apply a constant regularisation term.
/// Equates to a prior that says all the parameters are zero with \f$\sigma^2 = \frac{1}{\text{val}}\f$.
/// @param prior The strength of the prior
void clear(double prior=0){
Identity(my_C_inv,prior);
for(int i=0; i<Size; i++){
my_vector[i]=0;
}
}
/// Applies a constant regularisation term.
/// Equates to a prior that says all the parameters are zero with \f$\sigma^2 = \frac{1}{\text{val}}\f$.
/// @param val The strength of the prior
void add_prior(double val){
for(int i=0; i<Size; i++){
my_C_inv(i,i)+=val;
}
}
/// Applies a regularisation term with a different strength for each parameter value.
/// Equates to a prior that says all the parameters are zero with \f$\sigma_i^2 = \frac{1}{\text{v}_i}\f$.
/// @param v The vector of priors
template<class Accessor>
void add_prior(const FixedVector<Size,Accessor>& v){
for(int i=0; i<Size; i++){
my_C_inv(i,i)+=v[i];
}
}
/// Applies a whole-matrix regularisation term.
/// This is the same as adding the \f$m\f$ to the inverse covariance matrix.
/// @param m The inverse covariance matrix to add
template<class Accessor>
void add_prior(const FixedMatrix<Size,Size,Accessor>& m){
my_C_inv+=m;
}
/// Add a single measurement
/// @param m The value of the measurement
/// @param J The Jacobian for the measurement \f$\frac{\partial\text{m}}{\partial\text{param}_i}\f$
/// @param weight The inverse variance of the measurement (default = 1)
template<class Accessor>
inline void add_df(double m, const FixedVector<Size,Accessor>& J, double weight = 1) {
Vector<Size> Jw = J*weight;
for(int i=0; i<Size; i++){
for(int j=0; j<Size; j++){
my_C_inv[i][j]+=J[i]*Jw[j];
}
my_vector[i]+=Jw[i]*m;
}
}
/// Add multiple measurements at once (much more efficiently)
/// @param N The number of measurements
/// @param m The measurements to add
/// @param J The Jacobian matrix \f$\frac{\partial\text{m}_i}{\partial\text{param}_j}\f$
/// @param invcov The inverse covariance of the measurement values
template<int N, class Accessor1, class Accessor2, class Accessor3>
inline void add_df(const FixedVector<N,Accessor1>& m,
const FixedMatrix<Size,N,Accessor2>& J,
const FixedMatrix<N,N,Accessor3>& invcov){
my_C_inv += J * invcov * J.T();
my_vector += J * invcov * m;
}
void compute(){
my_svd.compute(my_C_inv);
my_mu=my_svd.backsub(my_vector);
}
/// Combine measurements from two WLS systems
/// @param meas The measurements to combine with
void operator += (const WLS& meas){
my_vector+=meas.my_vector;
my_C_inv += meas.my_C_inv;
}
/// Returns the inverse covariance matrix
Matrix<Size,Size,RowMajor>& get_C_inv() {return my_C_inv;}
/// Returns the inverse covariance matrix
const Matrix<Size,Size,RowMajor>& get_C_inv() const {return my_C_inv;}
Vector<Size>& get_mu(){return my_mu;}
const Vector<Size>& get_mu() const {return my_mu;}
Vector<Size>& get_vector(){return my_vector;}
const Vector<Size>& get_vector() const {return my_vector;}
SVD<Size>& get_svd(){return my_svd;}
const SVD<Size>& get_svd() const {return my_svd;}
private:
Vector<Size> my_mu;
Matrix<Size,Size,RowMajor> my_C_inv;
Vector<Size> my_vector;
SVD<Size,Size> my_svd;
// comment out to allow bitwise copying
WLS( WLS& copyof );
int operator = ( WLS& copyof );
};
// syg21: Dynamic WLS
/// Performs weighted least squares computation.
/// @param Size The number of dimensions in the system
/// @ingroup gMaths
template<>
class WLS<-1> {
public:
/// Default constructor
//WLS(){clear();}
WLS(unsigned int s)
: Size(s), my_mu(Size), my_vector(Size), my_C_inv(Size, Size)
{
clear();
}
void Identity(Matrix<> &M, double d)
{
for(int r=0; r<M.num_rows(); r++)
{
for(int c=0; c<M.num_cols(); c++)
{
M[r][c] = 0.0;
}
M[r][r] = 1.0;
}
}
/// Clear all the measurements and apply a constant regularisation term.
/// Equates to a prior that says all the parameters are zero with \f$\sigma^2 = \frac{1}{\text{val}}\f$.
/// @param prior The strength of the prior
void clear(double prior=0){
Identity(my_C_inv,prior);
for(int i=0; i<Size; i++){
my_vector[i]=0;
}
}
/// Applies a constant regularisation term.
/// Equates to a prior that says all the parameters are zero with \f$\sigma^2 = \frac{1}{\text{val}}\f$.
/// @param val The strength of the prior
void add_prior(double val){
for(int i=0; i<Size; i++){
my_C_inv(i,i)+=val;
}
}
/// Applies a regularisation term with a different strength for each parameter value.
/// Equates to a prior that says all the parameters are zero with \f$\sigma_i^2 = \frac{1}{\text{v}_i}\f$.
/// @param v The vector of priors
template<int VSize, class Accessor>
void add_prior(const FixedVector<VSize,Accessor>& v){
assert(VSize==Size);
for(int i=0; i<VSize; i++){
my_C_inv(i,i)+=v[i];
}
}
/// Applies a whole-matrix regularisation term.
/// This is the same as adding the \f$m\f$ to the inverse covariance matrix.
/// @param m The inverse covariance matrix to add
template<int MSize, class Accessor>
void add_prior(const FixedMatrix<MSize,MSize,Accessor>& m){
my_C_inv+=m;
}
/// Add a single measurement
/// @param m The value of the measurement
/// @param J The Jacobian for the measurement \f$\frac{\partial\text{m}}{\partial\text{param}_i}\f$
/// @param weight The inverse variance of the measurement (default = 1)
template<int VSize, class Accessor>
inline void add_df(double m, const FixedVector<VSize,Accessor>& J, double weight = 1) {
assert(VSize==Size);
Vector<VSize> Jw = J*weight;
for(int i=0; i<VSize; i++){
for(int j=0; j<VSize; j++){
my_C_inv[i][j]+=J[i]*Jw[j];
}
my_vector[i]+=Jw[i]*m;
}
}
/// Add a single measurement
/// @param m The value of the measurement
/// @param J The Jacobian for the measurement \f$\frac{\partial\text{m}}{\partial\text{param}_i}\f$
/// @param weight The inverse variance of the measurement (default = 1)
template<class Accessor>
inline void add_df(double m, const DynamicVector<Accessor>& J, double weight = 1) {
Vector<> Jw(Size);
Jw = J * weight;
for(int i=0; i<Size; i++){
for(int j=0; j<Size; j++){
my_C_inv[i][j]+=J[i]*Jw[j];
}
my_vector[i]+=Jw[i]*m;
}
}
void compute(){
// create SVD
SVD<> my_svd(my_C_inv);
//my_svd.compute(my_C_inv);
my_mu=my_svd.backsub(my_vector);
}
/// Returns mu
const Vector<>& get_mu() const {return my_mu;}
Vector<>& get_mu() {return my_mu;}
/// Returns the inverse covariance matrix
const Matrix<>& get_C_inv() const {return my_C_inv;}
Matrix<>& get_C_inv() {return my_C_inv;}
/// Returns my_vector
const Vector<>& get_vector() const {return my_vector;}
Vector<>& get_vector(){return my_vector;}
private:
int Size;
Vector<> my_mu;
Vector<> my_vector;
Matrix<> my_C_inv;
// comment out to allow bitwise copying
WLS( WLS& copyof );
int operator = ( WLS& copyof );
// To return SVD, have to create a point to an SVD<> instead of creating a temporary variable in compute()
#if 0
SVD<Size>& get_svd(){return my_svd;}
const SVD<Size>& get_svd() const {return my_svd;}
#endif
};
#ifndef TOON_NO_NAMESPACE
}
#endif
#endif
| 29.268212 | 109 | 0.657767 | [
"vector"
] |
1b36f8f1d5852bee0fdf5536cf4cc003b71c2f04 | 31,931 | c | C | src/image.c | linkmauve/glfw2to3 | f5c8b25aa316f411267a5f2d617941495ec9c3cb | [
"Zlib"
] | null | null | null | src/image.c | linkmauve/glfw2to3 | f5c8b25aa316f411267a5f2d617941495ec9c3cb | [
"Zlib"
] | null | null | null | src/image.c | linkmauve/glfw2to3 | f5c8b25aa316f411267a5f2d617941495ec9c3cb | [
"Zlib"
] | null | null | null | /*************************************************************************
* GLFW 2to3 - www.glfw.org
* A library easing porting from GLFW 2 to GLFW 3.x
*------------------------------------------------------------------------
* Copyright © 2002-2006 Marcus Geelnard
* Copyright © 2006-2010 Camilla Berglund <elmindreda@elmindreda.org>
* Copyright © 2020 Emmanuel Gil Peyrot <linkmauve@linkmauve.fr>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would
* be appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not
* be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*
*************************************************************************/
#include "internal.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Image/texture I/O support */
//========================================================================
// Description:
//
// This module acts as an interface for different image file formats (the
// image file format is detected automatically).
//
// By default the loaded image is rescaled (using bilinear interpolation)
// to the next higher 2^N x 2^M resolution, unless it has a valid
// 2^N x 2^M resolution. The interpolation is quite slow, even if the
// routine has been optimized for speed (a 200x200 RGB image is scaled to
// 256x256 in ~30 ms on a P3-500).
//
// Paletted images are converted to RGB/RGBA images.
//
// A convenience function is also included (glfwLoadTexture2D), which
// loads a texture image from a file directly to OpenGL texture memory,
// with an option to generate all mipmap levels. GL_SGIS_generate_mipmap
// is used whenever available, which should give an optimal mipmap
// generation speed (possibly performed in hardware). A software fallback
// method is included when GL_SGIS_generate_mipmap is not supported (it
// generates all mipmaps of a 256x256 RGB texture in ~3 ms on a P3-500).
//
//========================================================================
//========================================================================
// Description:
//
// TGA format image file loader. This module supports version 1 Targa
// images, with these restrictions:
// - Pixel format may only be 8, 24 or 32 bits
// - Colormaps must be no longer than 256 entries
//
//========================================================================
//========================================================================
// Opens a GLFW stream with a file
//========================================================================
//------------------------------------------------------------------------
// Abstract data stream (for image I/O)
//------------------------------------------------------------------------
typedef struct {
FILE* file;
void* data;
long position;
long size;
} _GLFWstream;
static int _glfwOpenFileStream( _GLFWstream *stream, const char* name, const char* mode )
{
memset( stream, 0, sizeof(_GLFWstream) );
stream->file = fopen( name, mode );
if( stream->file == NULL )
{
return GL_FALSE;
}
return GL_TRUE;
}
//========================================================================
// Opens a GLFW stream with a memory block
//========================================================================
static int _glfwOpenBufferStream( _GLFWstream *stream, void *data, long size )
{
memset( stream, 0, sizeof(_GLFWstream) );
stream->data = data;
stream->size = size;
return GL_TRUE;
}
//========================================================================
// Reads data from a GLFW stream
//========================================================================
static long _glfwReadStream( _GLFWstream *stream, void *data, long size )
{
if( stream->file != NULL )
{
return (long) fread( data, 1, size, stream->file );
}
if( stream->data != NULL )
{
// Check for EOF
if( stream->position == stream->size )
{
return 0;
}
// Clamp read size to available data
if( stream->position + size > stream->size )
{
size = stream->size - stream->position;
}
// Perform data read
memcpy( data, (unsigned char*) stream->data + stream->position, size );
stream->position += size;
return size;
}
return 0;
}
//========================================================================
// Returns the current position of a GLFW stream
//========================================================================
static long _glfwTellStream( _GLFWstream *stream )
{
if( stream->file != NULL )
{
return ftell( stream->file );
}
if( stream->data != NULL )
{
return stream->position;
}
return 0;
}
//========================================================================
// Sets the current position of a GLFW stream
//========================================================================
static int _glfwSeekStream( _GLFWstream *stream, long offset, int whence )
{
long position;
if( stream->file != NULL )
{
if( fseek( stream->file, offset, whence ) != 0 )
{
return GL_FALSE;
}
return GL_TRUE;
}
if( stream->data != NULL )
{
position = offset;
// Handle whence parameter
if( whence == SEEK_CUR )
{
position += stream->position;
}
else if( whence == SEEK_END )
{
position += stream->size;
}
else if( whence != SEEK_SET )
{
return GL_FALSE;
}
// Clamp offset to buffer bounds and apply it
if( position > stream->size )
{
stream->position = stream->size;
}
else if( position < 0 )
{
stream->position = 0;
}
else
{
stream->position = position;
}
return GL_TRUE;
}
return GL_FALSE;
}
//========================================================================
// Closes a GLFW stream
//========================================================================
static void _glfwCloseStream( _GLFWstream *stream )
{
if( stream->file != NULL )
{
fclose( stream->file );
}
// Nothing to be done about (user allocated) memory blocks
memset( stream, 0, sizeof(_GLFWstream) );
}
//************************************************************************
//**** GLFW internal functions & declarations ****
//************************************************************************
//========================================================================
// TGA file header information
//========================================================================
typedef struct {
int idlen; // 1 byte
int cmaptype; // 1 byte
int imagetype; // 1 byte
int cmapfirstidx; // 2 bytes
int cmaplen; // 2 bytes
int cmapentrysize; // 1 byte
int xorigin; // 2 bytes
int yorigin; // 2 bytes
int width; // 2 bytes
int height; // 2 bytes
int bitsperpixel; // 1 byte
int imageinfo; // 1 byte
int _alphabits; // (derived from imageinfo)
int _origin; // (derived from imageinfo)
} _tga_header_t;
#define _TGA_CMAPTYPE_NONE 0
#define _TGA_CMAPTYPE_PRESENT 1
#define _TGA_IMAGETYPE_NONE 0
#define _TGA_IMAGETYPE_CMAP 1
#define _TGA_IMAGETYPE_TC 2
#define _TGA_IMAGETYPE_GRAY 3
#define _TGA_IMAGETYPE_CMAP_RLE 9
#define _TGA_IMAGETYPE_TC_RLE 10
#define _TGA_IMAGETYPE_GRAY_RLE 11
#define _TGA_IMAGEINFO_ALPHA_MASK 0x0f
#define _TGA_IMAGEINFO_ALPHA_SHIFT 0
#define _TGA_IMAGEINFO_ORIGIN_MASK 0x30
#define _TGA_IMAGEINFO_ORIGIN_SHIFT 4
#define _TGA_ORIGIN_BL 0
#define _TGA_ORIGIN_BR 1
#define _TGA_ORIGIN_UL 2
#define _TGA_ORIGIN_UR 3
//========================================================================
// Read TGA file header (and check that it is valid)
//========================================================================
static int ReadTGAHeader( _GLFWstream *s, _tga_header_t *h )
{
unsigned char buf[ 18 ];
int pos;
// Read TGA file header from file
pos = _glfwTellStream( s );
_glfwReadStream( s, buf, 18 );
// Interpret header (endian independent parsing)
h->idlen = (int) buf[0];
h->cmaptype = (int) buf[1];
h->imagetype = (int) buf[2];
h->cmapfirstidx = (int) buf[3] | (((int) buf[4]) << 8);
h->cmaplen = (int) buf[5] | (((int) buf[6]) << 8);
h->cmapentrysize = (int) buf[7];
h->xorigin = (int) buf[8] | (((int) buf[9]) << 8);
h->yorigin = (int) buf[10] | (((int) buf[11]) << 8);
h->width = (int) buf[12] | (((int) buf[13]) << 8);
h->height = (int) buf[14] | (((int) buf[15]) << 8);
h->bitsperpixel = (int) buf[16];
h->imageinfo = (int) buf[17];
// Extract alphabits and origin information
h->_alphabits = (int) (h->imageinfo & _TGA_IMAGEINFO_ALPHA_MASK) >>
_TGA_IMAGEINFO_ALPHA_SHIFT;
h->_origin = (int) (h->imageinfo & _TGA_IMAGEINFO_ORIGIN_MASK) >>
_TGA_IMAGEINFO_ORIGIN_SHIFT;
// Validate TGA header (is this a TGA file?)
if( (h->cmaptype == 0 || h->cmaptype == 1) &&
((h->imagetype >= 1 && h->imagetype <= 3) ||
(h->imagetype >= 9 && h->imagetype <= 11)) &&
(h->bitsperpixel == 8 || h->bitsperpixel == 24 ||
h->bitsperpixel == 32) )
{
// Skip the ID field
_glfwSeekStream( s, h->idlen, SEEK_CUR );
// Indicate that the TGA header was valid
return GL_TRUE;
}
else
{
// Restore file position
_glfwSeekStream( s, pos, SEEK_SET );
// Indicate that the TGA header was invalid
return GL_FALSE;
}
}
//========================================================================
// Read Run-Length Encoded data
//========================================================================
static void ReadTGA_RLE( unsigned char *buf, int size, int bpp,
_GLFWstream *s )
{
int repcount, bytes, k, n;
unsigned char pixel[ 4 ];
char c;
// Dummy check
if( bpp > 4 )
{
return;
}
while( size > 0 )
{
// Get repetition count
_glfwReadStream( s, &c, 1 );
repcount = (unsigned int) c;
bytes = ((repcount & 127) + 1) * bpp;
if( size < bytes )
{
bytes = size;
}
// Run-Length packet?
if( repcount & 128 )
{
_glfwReadStream( s, pixel, bpp );
for( n = 0; n < (repcount & 127) + 1; n ++ )
{
for( k = 0; k < bpp; k ++ )
{
*buf ++ = pixel[ k ];
}
}
}
else
{
// It's a Raw packet
_glfwReadStream( s, buf, bytes );
buf += bytes;
}
size -= bytes;
}
}
//========================================================================
// Read a TGA image from a file
//========================================================================
static int _glfwReadTGA( _GLFWstream *s, GLFWimage *img, int flags )
{
_tga_header_t h;
unsigned char *cmap, *pix, tmp, *src, *dst;
int cmapsize, pixsize, pixsize2;
int bpp, bpp2, k, m, n, swapx, swapy;
// Read TGA header
if( !ReadTGAHeader( s, &h ) )
{
return 0;
}
// Is there a colormap?
cmapsize = (h.cmaptype == _TGA_CMAPTYPE_PRESENT ? 1 : 0) * h.cmaplen *
((h.cmapentrysize+7) / 8);
if( cmapsize > 0 )
{
// Is it a colormap that we can handle?
if( (h.cmapentrysize != 24 && h.cmapentrysize != 32) ||
h.cmaplen == 0 || h.cmaplen > 256 )
{
return 0;
}
// Allocate memory for colormap
cmap = (unsigned char *) malloc( cmapsize );
if( cmap == NULL )
{
return 0;
}
// Read colormap from file
_glfwReadStream( s, cmap, cmapsize );
}
else
{
cmap = NULL;
}
// Size of pixel data
pixsize = h.width * h.height * ((h.bitsperpixel + 7) / 8);
// Bytes per pixel (pixel data - unexpanded)
bpp = (h.bitsperpixel + 7) / 8;
// Bytes per pixel (expanded pixels - not colormap indeces)
if( cmap )
{
bpp2 = (h.cmapentrysize + 7) / 8;
}
else
{
bpp2 = bpp;
}
// For colormaped images, the RGB/RGBA image data may use more memory
// than the stored pixel data
pixsize2 = h.width * h.height * bpp2;
// Allocate memory for pixel data
pix = (unsigned char *) malloc( pixsize2 );
if( pix == NULL )
{
if( cmap )
{
free( cmap );
}
return 0;
}
// Read pixel data from file
if( h.imagetype >= _TGA_IMAGETYPE_CMAP_RLE )
{
ReadTGA_RLE( pix, pixsize, bpp, s );
}
else
{
_glfwReadStream( s, pix, pixsize );
}
// If the image origin is not what we want, re-arrange the pixels
switch( h._origin )
{
default:
case _TGA_ORIGIN_UL:
swapx = 0;
swapy = 1;
break;
case _TGA_ORIGIN_BL:
swapx = 0;
swapy = 0;
break;
case _TGA_ORIGIN_UR:
swapx = 1;
swapy = 1;
break;
case _TGA_ORIGIN_BR:
swapx = 1;
swapy = 0;
break;
}
if( (swapy && !(flags & GLFW_ORIGIN_UL_BIT)) ||
(!swapy && (flags & GLFW_ORIGIN_UL_BIT)) )
{
src = pix;
dst = &pix[ (h.height-1)*h.width*bpp ];
for( n = 0; n < h.height/2; n ++ )
{
for( m = 0; m < h.width ; m ++ )
{
for( k = 0; k < bpp; k ++ )
{
tmp = *src;
*src ++ = *dst;
*dst ++ = tmp;
}
}
dst -= 2*h.width*bpp;
}
}
if( swapx )
{
src = pix;
dst = &pix[ (h.width-1)*bpp ];
for( n = 0; n < h.height; n ++ )
{
for( m = 0; m < h.width/2 ; m ++ )
{
for( k = 0; k < bpp; k ++ )
{
tmp = *src;
*src ++ = *dst;
*dst ++ = tmp;
}
dst -= 2*bpp;
}
src += ((h.width+1)/2)*bpp;
dst += ((3*h.width+1)/2)*bpp;
}
}
// Convert BGR/BGRA to RGB/RGBA, and optionally colormap indeces to
// RGB/RGBA values
if( cmap )
{
// Convert colormap pixel format (BGR -> RGB or BGRA -> RGBA)
if( bpp2 == 3 || bpp2 == 4 )
{
for( n = 0; n < h.cmaplen; n ++ )
{
tmp = cmap[ n*bpp2 ];
cmap[ n*bpp2 ] = cmap[ n*bpp2 + 2 ];
cmap[ n*bpp2 + 2 ] = tmp;
}
}
// Convert pixel data to RGB/RGBA data
for( m = h.width * h.height - 1; m >= 0; m -- )
{
n = pix[ m ];
for( k = 0; k < bpp2; k ++ )
{
pix[ m*bpp2 + k ] = cmap[ n*bpp2 + k ];
}
}
// Free memory for colormap (it's not needed anymore)
free( cmap );
}
else
{
// Convert image pixel format (BGR -> RGB or BGRA -> RGBA)
if( bpp2 == 3 || bpp2 == 4 )
{
src = pix;
dst = &pix[ 2 ];
for( n = 0; n < h.height * h.width; n ++ )
{
tmp = *src;
*src = *dst;
*dst = tmp;
src += bpp2;
dst += bpp2;
}
}
}
// Fill out GLFWimage struct (the Format field will be set by
// glfwReadImage)
img->Width = h.width;
img->Height = h.height;
img->BytesPerPixel = bpp2;
img->Data = pix;
return 1;
}
// We want to support automatic mipmap generation
#ifndef GL_SGIS_generate_mipmap
#define GL_GENERATE_MIPMAP_SGIS 0x8191
#define GL_GENERATE_MIPMAP_HINT_SGIS 0x8192
#define GL_SGIS_generate_mipmap 1
#endif // GL_SGIS_generate_mipmap
//************************************************************************
//**** GLFW internal functions ****
//************************************************************************
//========================================================================
// Upsample image, from size w1 x h1 to w2 x h2
//========================================================================
static void UpsampleImage( unsigned char *src, unsigned char *dst,
int w1, int h1, int w2, int h2, int bpp )
{
int m, n, k, x, y, col8;
float dx, dy, xstep, ystep, col, col1, col2;
unsigned char *src1, *src2, *src3, *src4;
// Calculate scaling factor
xstep = (float)(w1-1) / (float)(w2-1);
ystep = (float)(h1-1) / (float)(h2-1);
// Copy source data to destination data with bilinear interpolation
// Note: The rather strange look of this routine is a direct result of
// my attempts at optimizing it. Improvements are welcome!
dy = 0.0f;
y = 0;
for( n = 0; n < h2; n ++ )
{
dx = 0.0f;
src1 = &src[ y*w1*bpp ];
src3 = y < (h1-1) ? src1 + w1*bpp : src1;
src2 = src1 + bpp;
src4 = src3 + bpp;
x = 0;
for( m = 0; m < w2; m ++ )
{
for( k = 0; k < bpp; k ++ )
{
col1 = *src1 ++;
col2 = *src2 ++;
col = col1 + (col2 - col1) * dx;
col1 = *src3 ++;
col2 = *src4 ++;
col2 = col1 + (col2 - col1) * dx;
col += (col2 - col) * dy;
col8 = (int) (col + 0.5);
if( col8 >= 256 ) col8 = 255;
*dst++ = (unsigned char) col8;
}
dx += xstep;
if( dx >= 1.0f )
{
x ++;
dx -= 1.0f;
if( x >= (w1-1) )
{
src2 = src1;
src4 = src3;
}
}
else
{
src1 -= bpp;
src2 -= bpp;
src3 -= bpp;
src4 -= bpp;
}
}
dy += ystep;
if( dy >= 1.0f )
{
y ++;
dy -= 1.0f;
}
}
}
//========================================================================
// Build the next mip-map level
//========================================================================
static int HalveImage( GLubyte *src, int *width, int *height,
int components )
{
int halfwidth, halfheight, m, n, k, idx1, idx2;
GLubyte *dst;
// Last level?
if( *width <= 1 && *height <= 1 )
{
return GL_FALSE;
}
// Calculate new width and height (handle 1D case)
halfwidth = *width > 1 ? *width / 2 : 1;
halfheight = *height > 1 ? *height / 2 : 1;
// Downsample image with a simple box-filter
dst = src;
if( *width == 1 || *height == 1 )
{
// 1D case
for( m = 0; m < halfwidth+halfheight-1; m ++ )
{
for( k = 0; k < components; k ++ )
{
*dst ++ = (GLubyte) (((int)*src +
(int)src[components] + 1) >> 1);
src ++;
}
src += components;
}
}
else
{
// 2D case
idx1 = *width*components;
idx2 = (*width+1)*components;
for( m = 0; m < halfheight; m ++ )
{
for( n = 0; n < halfwidth; n ++ )
{
for( k = 0; k < components; k ++ )
{
*dst ++ = (GLubyte) (((int)*src +
(int)src[components] +
(int)src[idx1] +
(int)src[idx2] + 2) >> 2);
src ++;
}
src += components;
}
src += components * (*width);
}
}
// Return new width and height
*width = halfwidth;
*height = halfheight;
return GL_TRUE;
}
//========================================================================
// Rescales an image into power-of-two dimensions
//========================================================================
static int RescaleImage( GLFWimage* image )
{
int width, height, log2, newsize;
unsigned char *data;
// Calculate next larger 2^N width
for( log2 = 0, width = image->Width; width > 1; width >>= 1, log2 ++ )
;
width = (int) 1 << log2;
if( width < image->Width )
{
width <<= 1;
}
// Calculate next larger 2^M height
for( log2 = 0, height = image->Height; height > 1; height >>= 1, log2 ++ )
;
height = (int) 1 << log2;
if( height < image->Height )
{
height <<= 1;
}
// Do we really need to rescale?
if( width != image->Width || height != image->Height )
{
// Allocate memory for new (upsampled) image data
newsize = width * height * image->BytesPerPixel;
data = (unsigned char *) malloc( newsize );
if( data == NULL )
{
free( image->Data );
return GL_FALSE;
}
// Copy old image data to new image data with interpolation
UpsampleImage( image->Data, data, image->Width, image->Height,
width, height, image->BytesPerPixel );
// Free memory for old image data (not needed anymore)
free( image->Data );
// Set pointer to new image data, and set new image dimensions
image->Data = data;
image->Width = width;
image->Height = height;
}
return GL_TRUE;
}
//************************************************************************
//**** GLFW user functions ****
//************************************************************************
//========================================================================
// Read an image from a named file
//========================================================================
GLFWAPI int GLFWAPIENTRY glfwReadImage( const char *name, GLFWimage *img,
int flags )
{
_GLFWstream stream;
// Start with an empty image descriptor
img->Width = 0;
img->Height = 0;
img->BytesPerPixel = 0;
img->Data = NULL;
// Open file
if( !_glfwOpenFileStream( &stream, name, "rb" ) )
{
return GL_FALSE;
}
// We only support TGA files at the moment
if( !_glfwReadTGA( &stream, img, flags ) )
{
_glfwCloseStream( &stream );
return GL_FALSE;
}
// Close stream
_glfwCloseStream( &stream );
// Should we rescale the image to closest 2^N x 2^M resolution?
if( !(flags & GLFW_NO_RESCALE_BIT) )
{
if( !RescaleImage( img ) )
{
return GL_FALSE;
}
}
// Interpret BytesPerPixel as an OpenGL format
switch( img->BytesPerPixel )
{
default:
case 1:
if( flags & GLFW_ALPHA_MAP_BIT )
{
img->Format = GL_ALPHA;
}
else
{
img->Format = GL_LUMINANCE;
}
break;
case 3:
img->Format = GL_RGB;
break;
case 4:
img->Format = GL_RGBA;
break;
}
return GL_TRUE;
}
//========================================================================
// Read an image file from a memory buffer
//========================================================================
GLFWAPI int GLFWAPIENTRY glfwReadMemoryImage( const void *data, long size, GLFWimage *img, int flags )
{
_GLFWstream stream;
// Start with an empty image descriptor
img->Width = 0;
img->Height = 0;
img->BytesPerPixel = 0;
img->Data = NULL;
// Open buffer
if( !_glfwOpenBufferStream( &stream, (void*) data, size ) )
{
return GL_FALSE;
}
// We only support TGA files at the moment
if( !_glfwReadTGA( &stream, img, flags ) )
{
_glfwCloseStream( &stream );
return GL_FALSE;
}
// Close stream
_glfwCloseStream( &stream );
// Should we rescale the image to closest 2^N x 2^M resolution?
if( !(flags & GLFW_NO_RESCALE_BIT) )
{
if( !RescaleImage( img ) )
{
return GL_FALSE;
}
}
// Interpret BytesPerPixel as an OpenGL format
switch( img->BytesPerPixel )
{
default:
case 1:
if( flags & GLFW_ALPHA_MAP_BIT )
{
img->Format = GL_ALPHA;
}
else
{
img->Format = GL_LUMINANCE;
}
break;
case 3:
img->Format = GL_RGB;
break;
case 4:
img->Format = GL_RGBA;
break;
}
return GL_TRUE;
}
//========================================================================
// Free allocated memory for an image
//========================================================================
GLFWAPI void GLFWAPIENTRY glfwFreeImage( GLFWimage *img )
{
// Free memory
if( img->Data != NULL )
{
free( img->Data );
img->Data = NULL;
}
// Clear all fields
img->Width = 0;
img->Height = 0;
img->Format = 0;
img->BytesPerPixel = 0;
}
//========================================================================
// Read an image from a file, and upload it to texture memory
//========================================================================
GLFWAPI int GLFWAPIENTRY glfwLoadTexture2D( const char *name, int flags )
{
GLFWimage img;
// Is GLFW initialized?
if( !_glfw.window )
{
return GL_FALSE;
}
// Force rescaling if necessary
if( glfwExtensionSupported("GL_ARB_texture_non_power_of_two") )
{
flags &= (~GLFW_NO_RESCALE_BIT);
}
// Read image from file
if( !glfwReadImage( name, &img, flags ) )
{
return GL_FALSE;
}
if( !glfwLoadTextureImage2D( &img, flags ) )
{
return GL_FALSE;
}
// Data buffer is not needed anymore
glfwFreeImage( &img );
return GL_TRUE;
}
//========================================================================
// Read an image from a buffer, and upload it to texture memory
//========================================================================
GLFWAPI int GLFWAPIENTRY glfwLoadMemoryTexture2D( const void *data, long size, int flags )
{
GLFWimage img;
// Is GLFW initialized?
if( !_glfw.window )
{
return GL_FALSE;
}
// Force rescaling if necessary
if( glfwExtensionSupported("GL_ARB_texture_non_power_of_two") )
{
flags &= (~GLFW_NO_RESCALE_BIT);
}
// Read image from file
if( !glfwReadMemoryImage( data, size, &img, flags ) )
{
return GL_FALSE;
}
if( !glfwLoadTextureImage2D( &img, flags ) )
{
return GL_FALSE;
}
// Data buffer is not needed anymore
glfwFreeImage( &img );
return GL_TRUE;
}
//========================================================================
// Upload an image object to texture memory
//========================================================================
GLFWAPI int GLFWAPIENTRY glfwLoadTextureImage2D( GLFWimage *img, int flags )
{
GLint UnpackAlignment, GenMipMap;
int level, format, AutoGen, newsize, n;
unsigned char *data, *dataptr;
// Is GLFW initialized?
if( !_glfw.window )
{
return GL_FALSE;
}
// TODO: Use GL_MAX_TEXTURE_SIZE or GL_PROXY_TEXTURE_2D to determine
// whether the image size is valid.
// NOTE: May require box filter downsampling routine.
// Do we need to convert the alpha map to RGBA format (OpenGL 1.0)?
int glMajor, glMinor;
glfwGetGLVersion(&glMajor, &glMinor, NULL);
if( (glMajor == 1) && (glMinor == 0) &&
(img->Format == GL_ALPHA) )
{
// We go to RGBA representation instead
img->BytesPerPixel = 4;
// Allocate memory for new RGBA image data
newsize = img->Width * img->Height * img->BytesPerPixel;
data = (unsigned char *) malloc( newsize );
if( data == NULL )
{
free( img->Data );
return GL_FALSE;
}
// Convert Alpha map to RGBA
dataptr = data;
for( n = 0; n < (img->Width*img->Height); ++ n )
{
*dataptr ++ = 255;
*dataptr ++ = 255;
*dataptr ++ = 255;
*dataptr ++ = img->Data[n];
}
// Free memory for old image data (not needed anymore)
free( img->Data );
// Set pointer to new image data
img->Data = data;
}
// Set unpack alignment to one byte
_glfw.glGetIntegerv( GL_UNPACK_ALIGNMENT, &UnpackAlignment );
_glfw.glPixelStorei( GL_UNPACK_ALIGNMENT, 1 );
// Should we use automatic mipmap generation?
AutoGen = ( flags & GLFW_BUILD_MIPMAPS_BIT ) &&
glfwExtensionSupported("GL_SGIS_generate_mipmap");
// Enable automatic mipmap generation
if( AutoGen )
{
_glfw.glGetTexParameteriv( GL_TEXTURE_2D, GL_GENERATE_MIPMAP_SGIS,
&GenMipMap );
_glfw.glTexParameteri( GL_TEXTURE_2D, GL_GENERATE_MIPMAP_SGIS,
GL_TRUE );
}
// Format specification is different for OpenGL 1.0
if( glMajor == 1 && glMinor == 0 )
{
format = img->BytesPerPixel;
}
else
{
format = img->Format;
}
// Upload to texture memeory
level = 0;
do
{
// Upload this mipmap level
_glfw.glTexImage2D( GL_TEXTURE_2D, level, format,
img->Width, img->Height, 0, format,
GL_UNSIGNED_BYTE, (void*) img->Data );
// Build next mipmap level manually, if required
if( ( flags & GLFW_BUILD_MIPMAPS_BIT ) && !AutoGen )
{
level = HalveImage( img->Data, &img->Width,
&img->Height, img->BytesPerPixel ) ?
level + 1 : 0;
}
}
while( level != 0 );
// Restore old automatic mipmap generation state
if( AutoGen )
{
_glfw.glTexParameteri( GL_TEXTURE_2D, GL_GENERATE_MIPMAP_SGIS,
GenMipMap );
}
// Restore old unpack alignment
_glfw.glPixelStorei( GL_UNPACK_ALIGNMENT, UnpackAlignment );
return GL_TRUE;
}
| 27.526724 | 102 | 0.453948 | [
"object"
] |
1b3883b527a75630e4391466fc461d378e798c64 | 1,815 | h | C | Scanner/scanner.h | WeiningLi/C_Like_Compiler | e8515cc22b5f695dbb623d55100a07fe3b710e1b | [
"MIT"
] | null | null | null | Scanner/scanner.h | WeiningLi/C_Like_Compiler | e8515cc22b5f695dbb623d55100a07fe3b710e1b | [
"MIT"
] | null | null | null | Scanner/scanner.h | WeiningLi/C_Like_Compiler | e8515cc22b5f695dbb623d55100a07fe3b710e1b | [
"MIT"
] | null | null | null | #ifndef CS241_SCANNER_H
#define CS241_SCANNER_H
#include <string>
#include <vector>
#include <set>
#include <cstdint>
#include <ostream>
// This file contains helpers for asm.cc and should not need to be modified by
class Token;
/* Scans a single line of input and produces a list of tokens.
*
* Scan returns tokens with the following kinds:
* ID: identifiers and keywords.
* LABEL: labels (identifiers ending in a colon).
* WORD: the special ".word" keyword.
* COMMA: a comma.
* LPAREN: a left parenthesis.
* RPAREN: a right parenthesis.
* INT: a signed or unsigned 32-bit integer written in decimal.
* HEXINT: an unsigned 32-bit integer written in hexadecimal.
* REG: a register between $0 and $31.
*/
std::vector<Token> scan(const std::string &input);
/* A scanned token produced by the scanner.
* The "kind" tells us what kind of token it is
* while the "lexeme" tells us exactly what text
* the programmer typed. For example, the token
* "abc" might have kind "ID" and lexeme "abc".
*
* While you can create tokens with any kind and
* lexeme, the list of kinds produced by the
* starter code can be found in the documentation
* for scan above.
*/
class Token {
public:
enum Kind {
ID = 0,
NUM,
SINGLEEND,
EQ,
EQEND,
SLASH,
COMMENT,
WHITESPACE
};
private:
Kind kind;
std::string lexeme;
public:
Token(Kind kind, std::string lexeme);
Kind getKind() const;
const std::string &getLexeme() const;
int64_t toLong() const;
};
/* An exception class thrown when an error is encountered while scanning.
*/
class ScanningFailure {
std::string message;
public:
ScanningFailure(std::string message);
// Returns the message associated with the exception.
const std::string &what() const;
};
#endif
| 22.6875 | 78 | 0.687052 | [
"vector"
] |
1b38ff4ea568fdeb157ffeb39700fe5d68a74f34 | 2,727 | h | C | traffic_editor/gui/project.h | Yadunund/traffic-editor | b511f7ebff640d7b74d05abd812740f2bdf7a6a7 | [
"Apache-2.0"
] | null | null | null | traffic_editor/gui/project.h | Yadunund/traffic-editor | b511f7ebff640d7b74d05abd812740f2bdf7a6a7 | [
"Apache-2.0"
] | null | null | null | traffic_editor/gui/project.h | Yadunund/traffic-editor | b511f7ebff640d7b74d05abd812740f2bdf7a6a7 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2019-2020 Open Source Robotics Foundation
*
* 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 PROJECT_H
#define PROJECT_H
#include "building.h"
#include "editor_model.h"
#include "editor_mode_id.h"
#include "scenario.h"
#include <string>
#include <vector>
#include <yaml-cpp/yaml.h>
class QGraphicsScene;
class QGraphicsItem;
class QGraphicsLineItem;
class Project
{
public:
std::string name;
std::string filename;
Building building;
std::vector<Scenario> scenarios;
int scenario_idx = -1; // the current scenario being viewed/edited
/////////////////////////////////
Project();
~Project();
bool save();
bool load(const std::string& _filename);
void clear();
void add_scenario_vertex(int level_index, double x, double y);
void scenario_row_clicked(const int row);
void draw(
QGraphicsScene *scene,
const int level_idx,
std::vector<EditorModel>& editor_models);
void clear_selection(const int level_idx);
bool delete_selected(const int level_idx);
struct NearestItem
{
double model_dist = 1e100;
int model_idx = -1;
double vertex_dist = 1e100;
int vertex_idx = -1;
double fiducial_dist = 1e100;
int fiducial_idx = -1;
};
NearestItem nearest_items(
EditorModeId mode,
const int level_index,
const double x,
const double y);
ScenarioLevel *scenario_level(const int building_level_idx);
void set_selected_containing_polygon(
const EditorModeId mode,
const int level_idx,
const double x,
const double y);
void mouse_select_press(
const EditorModeId mode,
const int level_idx,
const double x,
const double y,
QGraphicsItem *graphics_item);
Polygon::EdgeDragPolygon polygon_edge_drag_press(
const EditorModeId mode,
const int level_idx,
const Polygon *polygon,
const double x,
const double y);
Polygon *get_selected_polygon(const EditorModeId mode, const int level_idx);
private:
bool load_yaml_file(const std::string& _filename);
bool save_yaml_file() const;
void set_selected_line_item(
const int level_idx,
QGraphicsLineItem *line_item);
};
#endif
| 23.508621 | 78 | 0.70187 | [
"vector"
] |
1b3e90bddeb9257194c16c88a4133fffed1817c5 | 4,789 | c | C | src/nvrecvproc/recvHBListener.c | DanIverson/OpenVnmrJ | 0db324603dbd8f618a6a9526b9477a999c5a4cc3 | [
"Apache-2.0"
] | 32 | 2016-06-17T05:04:26.000Z | 2022-03-28T17:54:44.000Z | src/nvrecvproc/recvHBListener.c | timburrow/openvnmrj-source | f5e65eb2db4bded3437701f0fa91abd41928579c | [
"Apache-2.0"
] | 128 | 2016-07-13T17:09:02.000Z | 2022-03-28T17:53:52.000Z | src/nvrecvproc/recvHBListener.c | timburrow/openvnmrj-source | f5e65eb2db4bded3437701f0fa91abd41928579c | [
"Apache-2.0"
] | 102 | 2016-01-23T15:27:16.000Z | 2022-03-20T05:41:54.000Z | /*
* Copyright (C) 2015 University of Oregon
*
* You may distribute under the terms of either the GNU General Public
* License or the Apache License, as specified in the LICENSE file.
*
* For more information, see the LICENSE file.
*/
/*
*/
#ifndef RTI_NDDS_4x
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <signal.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <errno.h>
#include <stdarg.h>
#ifndef LINUX
#include <thread.h>
#endif
#include <pthread.h>
#include "errLogLib.h"
#include "ndds/ndds_c.h"
#include "NDDS_Obj.h"
#include "App_HB.h"
#include "sockets.h"
#include "msgQLib.h"
#define TRUE 1
#define FALSE 0
#define FOR_EVER 1
/* hostname (i.e. NIC) attached to console */
extern char ConsoleNicHostname[];
extern char ProcName[256];
#define NDDS_DBUG_LEVEL 1
#define MULTICAST_ENABLE 1
#define NDDS_DOMAIN_NUMBER 0
NDDS_ID pMonitorPub, pMonitorSub;
static NDDSSubscriber CntlrSubscriber = NULL;
extern NDDS_ID NDDS_Domain;
/*---------------------------------------------------------------------------------- */
/*---------------------------------------------------------------------------------- */
static int DDR_HB = -1;
static int ddrCntlrType = 1;
RTIBool App_NodeCallback(const NDDSRecvInfo *issue, NDDSInstance *instance,
void *callBackRtnParam)
{
App_HB *recvIssue;
int cntlrType;
/* possible status values:
NDDS_FRESH_DATA, NDDS_DESERIALIZATION_ERROR, NDDS_UPDATE_OF_OLD_DATA,
NDDS_NO_NEW_DATA, NDDS_NEVER_RECEIVED_DATA
*/
/* cntlrType = *((int*)callBackRtnParam); */
if (issue->status == NDDS_FRESH_DATA)
{
recvIssue = (App_HB *) instance;
DPRINT6(+3, "'%s': App_NodeCallback: '%s': received AppStr: '%s', HB cnt: %lu, ThreadId: %d, AppID: %d\n",
ProcName,issue->nddsTopic,recvIssue->AppIdStr, recvIssue->HBcnt, recvIssue->ThreadId,recvIssue->AppId);
if (DDR_HB < 1)
{
DDR_HB = 1;
DPRINT2(+1,"'%s': App_NodeCallback: Issue: '%s', Is Back.\n", ProcName, issue->nddsTopic);
}
}
else if (issue->status == NDDS_NO_NEW_DATA)
{
DPRINT2(+1,"'%s': App_NodeCallback: Issue: '%s', Missed Deadline, Node must be gone.\n", ProcName, issue->nddsTopic);
DDR_HB = -1;
}
return RTI_TRUE;
}
/*---------------------------------------------------------------------------------- */
/* future call? int createAppHB_BESubscription(cntlr_t *pCntlrThr,char *subName) */
NDDS_ID createAppHB_BESubscription(char *subName, void *callbackRoutine, void *callBackRtnParam)
{
NDDS_ID pSubObj;
/* Build Data type Object for both publication and subscription to Expproc */
/* ------- malloc space for data type object --------- */
if ( (pSubObj = (NDDS_ID) malloc( sizeof(NDDS_OBJ)) ) == NULL )
{
return(NULL);
}
/* zero out structure */
memset(pSubObj,0,sizeof(NDDS_OBJ));
memcpy(pSubObj,NDDS_Domain,sizeof(NDDS_OBJ));
strcpy(pSubObj->topicName,subName);
/* fills in dataTypeName, TypeRegisterFunc, TypeAllocFunc, TypeSizeFunc */
getApp_HBInfo(pSubObj);
pSubObj->callBkRtn = (NddsCallBkRtn) callbackRoutine;
pSubObj->callBkRtnParam = (void*) callBackRtnParam;
#ifndef NO_MULTICAST
strcpy(pSubObj->MulticastSubIP,APP_HB_MULTICAST_IP);
#else
pSubObj->MulticastSubIP[0] = 0; /* use UNICAST */
#endif
pSubObj->BE_UpdateMinDeltaMillisec = 1000; /* max rate once a second */
pSubObj->BE_DeadlineMillisec = 6000; /* no HB in 6 sec then it's gone.. */
createBESubscription(pSubObj);
DPRINT1(+1,"createAppHBSubscription(): subscription: 0x%lx\n",pSubObj->subscription);
return( pSubObj );
}
/*
* Create a the Code DowndLoad pattern subscriber, to dynamicly allow subscription creation
* as controllers come on-line and publication to Sendproc download topic
*
* Author Greg Brissey 4-26-04
*/
/*cntlrNodeHB_PatternSub()
*{
* if (CntlrSubscriber == NULL)
* CntlrSubscriber = NddsSubscriberCreate(NDDS_DOMAIN_NUMBER);
*
* NddsSubscriberPatternAdd(CntlrSubscriber,
* nodeHB_PATTERN_FORMAT_STR, App_HBNDDSType , App_HBPatternSubCreate, (void *)NULL);
*}
*/
NDDS_ID createHBListener(char *subtopic, void *pParam )
{
NDDS_ID pDDRId;
pDDRId = createAppHB_BESubscription(subtopic, (void*) App_NodeCallback, (void *) pParam );
return (pDDRId);
}
startDDR_HBListener()
{
NDDS_ID pDDRId;
char subtopic[80];
sprintf(subtopic,SUB_NodeHB_TOPIC_FORMAT_STR,"ddr1");
pDDRId = createAppHB_BESubscription(subtopic, (void*) App_NodeCallback, (void *) &ddrCntlrType );
}
isDDRActive()
{
return ( (DDR_HB > -1) );
}
#endif /* RTI_NDDS_4x */
| 28.170588 | 123 | 0.642514 | [
"object"
] |
1b425267be7caf47529d321c9b40fde9112b935d | 2,364 | h | C | NFClient/Cocos/Classes/NF/Logic/NFCLoginLogic.h | schwantz/NoahGameFrame | 67764fa16f3bed646e6c14caa34b3e3bb7b09abd | [
"Apache-2.0"
] | 1 | 2018-06-13T16:39:20.000Z | 2018-06-13T16:39:20.000Z | NFClient/Cocos/Classes/NF/Logic/NFCLoginLogic.h | schwantz/NoahGameFrame | 67764fa16f3bed646e6c14caa34b3e3bb7b09abd | [
"Apache-2.0"
] | 2 | 2018-10-12T07:48:03.000Z | 2018-10-16T10:38:19.000Z | NFClient/Cocos/Classes/NF/Logic/NFCLoginLogic.h | schwantz/NoahGameFrame | 67764fa16f3bed646e6c14caa34b3e3bb7b09abd | [
"Apache-2.0"
] | 1 | 2019-09-09T21:28:15.000Z | 2019-09-09T21:28:15.000Z | // -------------------------------------------------------------------------
// @FileName : NFCLoginLogic.h
// @Author : Johance
// @Date : 2016-12-28
// @Module : NFCLoginLogic
//
// -------------------------------------------------------------------------
#ifndef NFC_LOGINLOGIC_H
#define NFC_LOGINLOGIC_H
#include "NFCLogicBase.h"
enum LoginLogicEvent
{
E_LoginEvent_LoginSuccess,
E_LoginEvent_WorldList,
E_LoginEvent_ServerList,
E_LoginEvent_RoleList,
};
class NFCLoginLogic
: public NFCLogicBase, public NFSingleton<NFCLoginLogic>
{
public:
NFCLoginLogic() {};
virtual ~NFCLoginLogic() {};
NFCLoginLogic(NFIPluginManager* p)
{
pPluginManager = p;
}
virtual bool Init();
virtual bool Shut();
virtual bool ReadyExecute();
virtual bool Execute();
virtual bool AfterInit();
// 发送消息
public:
void LoginPB(const std::string &strAccount, const std::string &strPwd, const std::string &strKey);
void RequireWorldList();
void RequireConnectWorld(int nWorldID);
void RequireVerifyWorldKey(const std::string &strAccount, const std::string &strKey);
void RequireServerList();
void RequireSelectServer(int nServerID);
void RequireRoleList();
// 接收消息
private:
void OnLoginProcess(const NFSOCK nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen);
void OnWorldList(const NFSOCK nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen);
void OnConnectWorld(const NFSOCK nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen);
void OnConnectKey(const NFSOCK nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen);
void OnSelectServer(const NFSOCK nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen);
public:
std::vector<NFMsg::ServerInfo> GetWorldList() { return m_WorldServerList; }
std::vector<NFMsg::ServerInfo> GetServerList() { return m_GameServerList; }
const std::string& GetAccount() { return m_strAccount; }
int GetServerID() { return m_nServerID; }
private:
std::string m_strAccount;
std::string m_strKey;
int m_nServerID;
std::vector<NFMsg::ServerInfo> m_WorldServerList;
std::vector<NFMsg::ServerInfo> m_GameServerList;
};
#define g_pLoginLogic (NFCLoginLogic::Instance())
#endif | 31.52 | 103 | 0.660745 | [
"vector"
] |
1b48aca65944fea35bb25adceda30cac443033d7 | 15,886 | h | C | net/third_party/quic/test_tools/quic_test_client.h | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | net/third_party/quic/test_tools/quic_test_client.h | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | net/third_party/quic/test_tools/quic_test_client.h | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef NET_THIRD_PARTY_QUIC_TEST_TOOLS_QUIC_TEST_CLIENT_H_
#define NET_THIRD_PARTY_QUIC_TEST_TOOLS_QUIC_TEST_CLIENT_H_
#include <cstdint>
#include <memory>
#include <string>
#include "base/macros.h"
#include "net/third_party/quic/core/proto/cached_network_parameters.pb.h"
#include "net/third_party/quic/core/quic_framer.h"
#include "net/third_party/quic/core/quic_packet_creator.h"
#include "net/third_party/quic/core/quic_packets.h"
#include "net/third_party/quic/platform/api/quic_containers.h"
#include "net/third_party/quic/platform/api/quic_map_util.h"
#include "net/third_party/quic/platform/api/quic_string_piece.h"
#include "net/third_party/quic/tools/quic_client.h"
#include "testing/gmock/include/gmock/gmock.h"
namespace net {
class ProofVerifier;
class QuicPacketWriterWrapper;
namespace test {
class MockableQuicClientEpollNetworkHelper;
// A quic client which allows mocking out reads and writes.
class MockableQuicClient : public QuicClient {
public:
MockableQuicClient(QuicSocketAddress server_address,
const QuicServerId& server_id,
const ParsedQuicVersionVector& supported_versions,
EpollServer* epoll_server);
MockableQuicClient(QuicSocketAddress server_address,
const QuicServerId& server_id,
const QuicConfig& config,
const ParsedQuicVersionVector& supported_versions,
EpollServer* epoll_server);
MockableQuicClient(QuicSocketAddress server_address,
const QuicServerId& server_id,
const QuicConfig& config,
const ParsedQuicVersionVector& supported_versions,
EpollServer* epoll_server,
std::unique_ptr<ProofVerifier> proof_verifier);
~MockableQuicClient() override;
QuicConnectionId GenerateNewConnectionId() override;
void UseConnectionId(QuicConnectionId connection_id);
void UseWriter(QuicPacketWriterWrapper* writer);
void set_peer_address(const QuicSocketAddress& address);
// The last incoming packet, iff |track_last_incoming_packet| is true.
const QuicReceivedPacket* last_incoming_packet();
// If true, copy each packet from ProcessPacket into |last_incoming_packet|
void set_track_last_incoming_packet(bool track);
// Casts the network helper to a MockableQuicClientEpollNetworkHelper.
MockableQuicClientEpollNetworkHelper* mockable_network_helper();
const MockableQuicClientEpollNetworkHelper* mockable_network_helper() const;
private:
QuicConnectionId override_connection_id_; // ConnectionId to use, if nonzero
CachedNetworkParameters cached_network_paramaters_;
DISALLOW_COPY_AND_ASSIGN(MockableQuicClient);
};
// A toy QUIC client used for testing.
class QuicTestClient : public QuicSpdyStream::Visitor,
public QuicClientPushPromiseIndex::Delegate {
public:
QuicTestClient(QuicSocketAddress server_address,
const std::string& server_hostname,
const ParsedQuicVersionVector& supported_versions);
QuicTestClient(QuicSocketAddress server_address,
const std::string& server_hostname,
const QuicConfig& config,
const ParsedQuicVersionVector& supported_versions);
QuicTestClient(QuicSocketAddress server_address,
const std::string& server_hostname,
const QuicConfig& config,
const ParsedQuicVersionVector& supported_versions,
std::unique_ptr<ProofVerifier> proof_verifier);
~QuicTestClient() override;
// Sets the |user_agent_id| of the |client_|.
void SetUserAgentID(const std::string& user_agent_id);
// Wraps data in a quic packet and sends it.
ssize_t SendData(const std::string& data, bool last_data);
// As above, but |delegate| will be notified when |data| is ACKed.
ssize_t SendData(
const std::string& data,
bool last_data,
QuicReferenceCountedPointer<QuicAckListenerInterface> ack_listener);
// Clears any outstanding state and sends a simple GET of 'uri' to the
// server. Returns 0 if the request failed and no bytes were written.
ssize_t SendRequest(const std::string& uri);
// Sends requests for all the urls and waits for the responses. To process
// the individual responses as they are returned, the caller should use the
// set the response_listener on the client().
void SendRequestsAndWaitForResponses(
const std::vector<std::string>& url_list);
// Sends a request containing |headers| and |body| and returns the number of
// bytes sent (the size of the serialized request headers and body).
ssize_t SendMessage(const spdy::SpdyHeaderBlock& headers,
QuicStringPiece body);
// Sends a request containing |headers| and |body| with the fin bit set to
// |fin| and returns the number of bytes sent (the size of the serialized
// request headers and body).
ssize_t SendMessage(const spdy::SpdyHeaderBlock& headers,
QuicStringPiece body,
bool fin);
// Sends a request containing |headers| and |body|, waits for the response,
// and returns the response body.
std::string SendCustomSynchronousRequest(const spdy::SpdyHeaderBlock& headers,
const std::string& body);
// Sends a GET request for |uri|, waits for the response, and returns the
// response body.
std::string SendSynchronousRequest(const std::string& uri);
void SendConnectivityProbing();
void Connect();
void ResetConnection();
void Disconnect();
QuicSocketAddress local_address() const;
void ClearPerRequestState();
bool WaitUntil(int timeout_ms, std::function<bool()> trigger);
ssize_t Send(const void* buffer, size_t size);
bool connected() const;
bool buffer_body() const;
void set_buffer_body(bool buffer_body);
// Getters for stream state. Please note, these getters are divided into two
// groups. 1) returns state which only get updated once a complete response
// is received. 2) returns state of the oldest active stream which have
// received partial response (if any).
// Group 1.
const spdy::SpdyHeaderBlock& response_trailers() const;
bool response_complete() const;
int64_t response_body_size() const;
const std::string& response_body() const;
// Group 2.
bool response_headers_complete() const;
const spdy::SpdyHeaderBlock* response_headers() const;
const spdy::SpdyHeaderBlock* preliminary_headers() const;
int64_t response_size() const;
size_t bytes_read() const;
size_t bytes_written() const;
// Returns once at least one complete response or a connection close has been
// received from the server. If responses are received for multiple (say 2)
// streams, next WaitForResponse will return immediately.
void WaitForResponse() { WaitForResponseForMs(-1); }
// Returns once some data is received on any open streams or at least one
// complete response is received from the server.
void WaitForInitialResponse() { WaitForInitialResponseForMs(-1); }
// Returns once at least one complete response or a connection close has been
// received from the server, or once the timeout expires. -1 means no timeout.
// If responses are received for multiple (say 2) streams, next
// WaitForResponseForMs will return immediately.
void WaitForResponseForMs(int timeout_ms) {
WaitUntil(timeout_ms, [this]() { return !closed_stream_states_.empty(); });
if (response_complete()) {
VLOG(1) << "Client received response:"
<< response_headers()->DebugString() << response_body();
}
}
// Returns once some data is received on any open streams or at least one
// complete response is received from the server, or once the timeout
// expires. -1 means no timeout.
void WaitForInitialResponseForMs(int timeout_ms) {
WaitUntil(timeout_ms, [this]() { return response_size() != 0; });
}
// Migrate local address to <|new_host|, a random port>.
// Return whether the migration succeeded.
bool MigrateSocket(const QuicIpAddress& new_host);
// Migrate local address to <|new_host|, |port|>.
// Return whether the migration succeeded.
bool MigrateSocketWithSpecifiedPort(const QuicIpAddress& new_host, int port);
QuicIpAddress bind_to_address() const;
void set_bind_to_address(QuicIpAddress address);
const QuicSocketAddress& address() const;
// From QuicSpdyStream::Visitor
void OnClose(QuicSpdyStream* stream) override;
// From QuicClientPushPromiseIndex::Delegate
bool CheckVary(const spdy::SpdyHeaderBlock& client_request,
const spdy::SpdyHeaderBlock& promise_request,
const spdy::SpdyHeaderBlock& promise_response) override;
void OnRendezvousResult(QuicSpdyStream*) override;
// Configures client_ to take ownership of and use the writer.
// Must be called before initial connect.
void UseWriter(QuicPacketWriterWrapper* writer);
// If the given ConnectionId is nonzero, configures client_ to use a specific
// ConnectionId instead of a random one.
void UseConnectionId(QuicConnectionId connection_id);
// Returns nullptr if the maximum number of streams have already been created.
QuicSpdyClientStream* GetOrCreateStream();
// Calls GetOrCreateStream(), sends the request on the stream, and
// stores the request in case it needs to be resent. If |headers| is
// null, only the body will be sent on the stream.
ssize_t GetOrCreateStreamAndSendRequest(
const spdy::SpdyHeaderBlock* headers,
QuicStringPiece body,
bool fin,
QuicReferenceCountedPointer<QuicAckListenerInterface> ack_listener);
QuicRstStreamErrorCode stream_error() { return stream_error_; }
QuicErrorCode connection_error();
MockableQuicClient* client();
// cert_common_name returns the common name value of the server's certificate,
// or the empty string if no certificate was presented.
const std::string& cert_common_name() const;
// cert_sct returns the signed timestamp of the server's certificate,
// or the empty string if no signed timestamp was presented.
const std::string& cert_sct() const;
// Get the server config map.
QuicTagValueMap GetServerConfig() const;
void set_auto_reconnect(bool reconnect) { auto_reconnect_ = reconnect; }
void set_priority(spdy::SpdyPriority priority) { priority_ = priority; }
void WaitForWriteToFlush();
EpollServer* epoll_server() { return &epoll_server_; }
size_t num_requests() const { return num_requests_; }
size_t num_responses() const { return num_responses_; }
void set_server_address(const QuicSocketAddress& server_address) {
client_->set_server_address(server_address);
}
void set_peer_address(const QuicSocketAddress& address) {
client_->set_peer_address(address);
}
// Explicitly set the SNI value for this client, overriding the default
// behavior which extracts the SNI value from the request URL.
void OverrideSni(const std::string& sni) {
override_sni_set_ = true;
override_sni_ = sni;
}
void Initialize();
void set_client(MockableQuicClient* client) { client_.reset(client); }
// PerStreamState of a stream is updated when it is closed.
struct PerStreamState {
PerStreamState(const PerStreamState& other);
PerStreamState(QuicRstStreamErrorCode stream_error,
bool response_complete,
bool response_headers_complete,
const spdy::SpdyHeaderBlock& response_headers,
const spdy::SpdyHeaderBlock& preliminary_headers,
const std::string& response,
const spdy::SpdyHeaderBlock& response_trailers,
uint64_t bytes_read,
uint64_t bytes_written,
int64_t response_body_size);
~PerStreamState();
QuicRstStreamErrorCode stream_error;
bool response_complete;
bool response_headers_complete;
spdy::SpdyHeaderBlock response_headers;
spdy::SpdyHeaderBlock preliminary_headers;
std::string response;
spdy::SpdyHeaderBlock response_trailers;
uint64_t bytes_read;
uint64_t bytes_written;
int64_t response_body_size;
};
// Given |uri|, populates the fields in |headers| for a simple GET
// request. If |uri| is a relative URL, the QuicServerId will be
// use to specify the authority.
bool PopulateHeaderBlockFromUrl(const std::string& uri,
spdy::SpdyHeaderBlock* headers);
// Waits for a period of time that is long enough to receive all delayed acks
// sent by peer.
void WaitForDelayedAcks();
protected:
QuicTestClient();
private:
class TestClientDataToResend : public QuicClient::QuicDataToResend {
public:
TestClientDataToResend(
std::unique_ptr<spdy::SpdyHeaderBlock> headers,
QuicStringPiece body,
bool fin,
QuicTestClient* test_client,
QuicReferenceCountedPointer<QuicAckListenerInterface> ack_listener);
~TestClientDataToResend() override;
void Resend() override;
protected:
QuicTestClient* test_client_;
QuicReferenceCountedPointer<QuicAckListenerInterface> ack_listener_;
};
bool HaveActiveStream();
// Read oldest received response and remove it from closed_stream_states_.
void ReadNextResponse();
// Clear open_streams_, closed_stream_states_ and reset
// latest_created_stream_.
void ClearPerConnectionState();
// Update latest_created_stream_, add |stream| to open_streams_ and starts
// tracking its state.
void SetLatestCreatedStream(QuicSpdyClientStream* stream);
EpollServer epoll_server_;
std::unique_ptr<MockableQuicClient> client_; // The actual client
QuicSpdyClientStream* latest_created_stream_;
std::map<QuicStreamId, QuicSpdyClientStream*> open_streams_;
// Received responses of closed streams.
QuicLinkedHashMap<QuicStreamId, PerStreamState> closed_stream_states_;
QuicRstStreamErrorCode stream_error_;
bool response_complete_;
bool response_headers_complete_;
mutable spdy::SpdyHeaderBlock preliminary_headers_;
mutable spdy::SpdyHeaderBlock response_headers_;
// Parsed response trailers (if present), copied from the stream in OnClose.
spdy::SpdyHeaderBlock response_trailers_;
spdy::SpdyPriority priority_;
std::string response_;
// bytes_read_ and bytes_written_ are updated only when stream_ is released;
// prefer bytes_read() and bytes_written() member functions.
uint64_t bytes_read_;
uint64_t bytes_written_;
// The number of HTTP body bytes received.
int64_t response_body_size_;
// True if we tried to connect already since the last call to Disconnect().
bool connect_attempted_;
// The client will auto-connect exactly once before sending data. If
// something causes a connection reset, it will not automatically reconnect
// unless auto_reconnect_ is true.
bool auto_reconnect_;
// Should we buffer the response body? Defaults to true.
bool buffer_body_;
// For async push promise rendezvous, validation may fail in which
// case the request should be retried.
std::unique_ptr<TestClientDataToResend> push_promise_data_to_resend_;
// Number of requests/responses this client has sent/received.
size_t num_requests_;
size_t num_responses_;
// If set, this value is used for the connection SNI, overriding the usual
// logic which extracts the SNI from the request URL.
bool override_sni_set_ = false;
std::string override_sni_;
DISALLOW_COPY_AND_ASSIGN(QuicTestClient);
};
} // namespace test
} // namespace net
#endif // NET_THIRD_PARTY_QUIC_TEST_TOOLS_QUIC_TEST_CLIENT_H_
| 39.914573 | 80 | 0.734546 | [
"vector"
] |
1b4b21f3e2f2b14e3d3bf2b1fd456ea0862625bc | 35,530 | c | C | lasrc/c_version/src/subaeroret.c | BeamIO-Inc/espa-surface-reflectance | 66eae6dc9983a0c12a451a1a480fabaad9a671cb | [
"Unlicense"
] | 5 | 2020-10-14T15:48:37.000Z | 2022-02-28T18:51:03.000Z | lasrc/c_version/src/subaeroret.c | BeamIO-Inc/espa-surface-reflectance | 66eae6dc9983a0c12a451a1a480fabaad9a671cb | [
"Unlicense"
] | null | null | null | lasrc/c_version/src/subaeroret.c | BeamIO-Inc/espa-surface-reflectance | 66eae6dc9983a0c12a451a1a480fabaad9a671cb | [
"Unlicense"
] | 3 | 2020-07-28T16:04:39.000Z | 2021-07-29T06:41:10.000Z | /*****************************************************************************
FILE: subaeroret.c
PURPOSE: Contains functions for handling the atmosperic corrections.
PROJECT: Land Satellites Data System Science Research and Development (LSRD)
at the USGS EROS
LICENSE TYPE: NASA Open Source Agreement Version 1.3
NOTES:
*****************************************************************************/
#include "lut_subr.h"
/******************************************************************************
MODULE: subaeroret_new
PURPOSE: Main driver for the atmospheric correction. This subroutine uses
atmospheric coefficients to determine the atmospheric variables, then performs
the atmospheric corrections. Updated algorithm to utilize semi-empirical
approach to accessing the look-up table.
RETURN VALUE:
Type = N/A
NOTES:
******************************************************************************/
void subaeroret_new
(
Sat_t sat, /* I: satellite */
bool water, /* I: water pixel flag */
int iband1, /* I: band 1 index (0-based) */
float erelc[NSR_BANDS], /* I: band ratio variable */
float troatm[NSR_BANDS], /* I: toa reflectance */
float tgo_arr[NREFL_BANDS], /* I: per-band other gaseous
transmittance */
int roatm_iaMax[NREFL_BANDS], /* I: roatm_iaMax */
float roatm_coef[NREFL_BANDS][NCOEF], /* I: per band polynomial
coefficients for roatm */
float ttatmg_coef[NREFL_BANDS][NCOEF], /* I: per band polynomial
coefficients for ttatmg */
float satm_coef[NREFL_BANDS][NCOEF], /* I: per band polynomial
coefficients for satm */
float normext_p0a3_arr[NREFL_BANDS], /* I: normext[iband][0][3] */
float *raot, /* O: AOT reflectance */
float *residual, /* O: model residual */
int *iaots, /* I/O: AOT index that is passed in and out for multiple
calls (0-based) */
float eps /* I: angstroem coefficient; spectral dependency of AOT */
)
{
int iaot; /* aerosol optical thickness (AOT) index */
int ib; /* band index */
int start_band = 0; /* starting band index for the loop */
int end_band = 0; /* ending band index for the loop */
float raot550nm=0.0; /* nearest input value of AOT */
float roslamb; /* lambertian surface reflectance */
double ros1; /* surface reflectance for bands */
double raot1, raot2; /* AOT ratios that bracket the predicted ratio */
float raotsaved; /* save the raot value */
double residual1, residual2; /* residuals for storing and comparing */
double residualm; /* local model residual */
int nbval; /* number of values meeting criteria */
bool testth; /* surface reflectance test variable */
double xa, xb; /* AOT ratio values */
double raotmin; /* minimum AOT ratio */
double point_error; /* residual differences for each pixel */
int iaot1, iaot2; /* AOT indices (0-based) */
float *tth = NULL; /* pointer to the Landsat or Sentinel tth array */
float landsat_tth[NSRL_BANDS] = {1.0e-03, 1.0e-03, 0.0, 1.0e-03, 0.0, 0.0,
1.0e-04, 0.0};
float landsat_tth_water[NSRL_BANDS] =
{1.0e-03, 1.0e-03, 0.0, 1.0e-03, 1.0e-03,
0.0, 1.0e-04, 0.0};
/* constant values for comparing against Landsat
surface reflectance */
#ifdef PROC_ALL_BANDS
/* Process all bands if turned on */
float sentinel_tth[NSRS_BANDS] = {1.0e-03, 1.0e-03, 0.0, 1.0e-03, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0e-04};
float sentinel_tth_water[NSRS_BANDS] =
{1.0e-03, 0.0, 0.0, 1.0e-03, 0.0, 0.0, 0.0,
0.0, 1.0e-3, 0.0, 0.0, 0.0, 1.0e-4};
/* ESPA - I believe the sentinel tth water should be for band 1, 4, 8a, and 12 vs. what I've commented below ... which is a duplicate of the FORTRAN array coeffs. I think that's a bug.
{1.0e-03, 1.0e-03, 0.0, 1.0e-03, 1.0e-3,
0.0, 1.0e-4, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};
*/
/* constant values for comparing against Sentinel
surface reflectance (different values for land
vs. water) */
#else
/* Skip bands 9 and 10 as default for ESPA */
float sentinel_tth[NSRS_BANDS] = {1.0e-03, 1.0e-03, 0.0, 1.0e-03, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 1.0e-04};
float sentinel_tth_water[NSRS_BANDS] =
{1.0e-03, 0.0, 0.0, 1.0e-03, 0.0, 0.0, 0.0,
0.0, 1.0e-3, 0.0, 1.0e-4};
/* constant values for comparing against Sentinel
surface reflectance (removed band 9&10) */
#endif
float aot550nm[NAOT_VALS] = {0.01, 0.05, 0.1, 0.15, 0.2, 0.3, 0.4, 0.6,
0.8, 1.0, 1.2, 1.4, 1.6, 1.8, 2.0, 2.3, 2.6,
3.0, 3.5, 4.0, 4.5, 5.0}; /* AOT values */
/* Initialize variables based on the satellite type */
if (sat == SAT_LANDSAT_8 || sat == SAT_LANDSAT_9)
{
if (water)
tth = landsat_tth_water;
else
tth = landsat_tth;
start_band = DNL_BAND1;
end_band = DNL_BAND7;
}
else if (sat == SAT_SENTINEL_2)
{
if (water)
tth = sentinel_tth_water;
else
tth = sentinel_tth;
start_band = DNS_BAND1;
end_band = DNS_BAND12;
}
/* Correct input band with increasing AOT (using pre till ratio is equal to
erelc[2]) */
iaot = *iaots;
residual1 = 2000.0;
residual2 = 1000.0;
iaot2 = 0;
iaot1 = 0;
raot2 = 1.0e-06;
raot1 = 0.0001;
ros1 = 1.0;
raot550nm = aot550nm[iaot];
testth = false;
nbval = 0;
*residual = 0.0;
/* Atmospheric correction for band 1 */
ib = iband1;
atmcorlamb2_new (sat, tgo_arr[ib], aot550nm[roatm_iaMax[ib]],
&roatm_coef[ib][0], &ttatmg_coef[ib][0], &satm_coef[ib][0], raot550nm,
ib, normext_p0a3_arr[ib], troatm[ib], &roslamb, eps);
if (roslamb - tth[iband1] < 0.0)
testth = true;
ros1 = roslamb;
/* Atmospheric correction for each band; handle residual for water-based
correction differently */
if (water)
{ /* expect that we are processing pixels over water */
for (ib = start_band; ib <= end_band; ib++)
{
/* This will process iband1, different from land */
if (erelc[ib] > 0.0)
{
atmcorlamb2_new (sat, tgo_arr[ib], aot550nm[roatm_iaMax[ib]],
&roatm_coef[ib][0], &ttatmg_coef[ib][0], &satm_coef[ib][0],
raot550nm, ib, normext_p0a3_arr[ib], troatm[ib], &roslamb,
eps);
if (roslamb - tth[ib] < 0.0)
testth = true;
*residual += roslamb*roslamb;
nbval++;
}
}
}
else
{ /* expect that we are processing pixels over land */
for (ib = start_band; ib <= end_band; ib++)
{
/* Don't reprocess iband1 */
if (ib != iband1 && erelc[ib] > 0.0)
{
atmcorlamb2_new (sat, tgo_arr[ib], aot550nm[roatm_iaMax[ib]],
&roatm_coef[ib][0], &ttatmg_coef[ib][0], &satm_coef[ib][0],
raot550nm, ib, normext_p0a3_arr[ib], troatm[ib], &roslamb,
eps);
if (roslamb - tth[ib] < 0.0)
testth = true;
point_error = roslamb - erelc[ib] * ros1;
*residual += point_error * point_error;
nbval++;
}
}
}
*residual = sqrt (*residual) / nbval;
/* Loop until we converge on a solution */
iaot++;
while ((iaot < NAOT_VALS) && (*residual < residual1) && (!testth))
{
/* Reset variables for this loop */
residual2 = residual1;
iaot2 = iaot1;
raot2 = raot1;
residual1 = *residual;
raot1 = raot550nm;
iaot1 = iaot;
raot550nm = aot550nm[iaot];
*residual = 0.0;
nbval = 0;
/* Atmospheric correction for band 1 */
ib = iband1;
testth = false;
atmcorlamb2_new (sat, tgo_arr[ib], aot550nm[roatm_iaMax[ib]],
&roatm_coef[ib][0], &ttatmg_coef[ib][0], &satm_coef[ib][0],
raot550nm, ib, normext_p0a3_arr[ib], troatm[ib], &roslamb, eps);
if (roslamb - tth[iband1] < 0.0)
testth = true;
ros1 = roslamb;
/* Atmospheric correction for each band; handle residual for water-based
correction differently */
if (water)
{ /* expect that we are processing pixels over water */
for (ib = start_band; ib <= end_band; ib++)
{
/* This will process iband1, different from land */
if (erelc[ib] > 0.0)
{
atmcorlamb2_new (sat, tgo_arr[ib],
aot550nm[roatm_iaMax[ib]], &roatm_coef[ib][0],
&ttatmg_coef[ib][0], &satm_coef[ib][0], raot550nm, ib,
normext_p0a3_arr[ib], troatm[ib], &roslamb, eps);
if (roslamb - tth[ib] < 0.0)
testth = true;
*residual += roslamb*roslamb;
nbval++;
}
}
}
else
{ /* expect that we are processing pixels over land */
for (ib = start_band; ib <= end_band; ib++)
{
/* Don't reprocess iband1 */
if (ib != iband1 && erelc[ib] > 0.0)
{
atmcorlamb2_new (sat, tgo_arr[ib],
aot550nm[roatm_iaMax[ib]], &roatm_coef[ib][0],
&ttatmg_coef[ib][0], &satm_coef[ib][0], raot550nm, ib,
normext_p0a3_arr[ib], troatm[ib], &roslamb, eps);
if (roslamb - tth[ib] < 0.0)
testth = true;
point_error = roslamb - erelc[ib] * ros1;
*residual += point_error * point_error;
nbval++;
}
}
}
*residual = sqrt (*residual) / nbval;
/* Move to the next AOT index */
iaot++;
} /* while aot */
/* If a minimum local was not reached for raot1, then just use the
raot550nm value. Otherwise continue to refine the raot. */
if (iaot == 1)
{
*raot = raot550nm;
}
else
{
/* Refine the AOT ratio. This is performed by applying a parabolic
(quadratic) fit to the three (raot, residual) pairs found above:
res = a(raot)^2 + b(raot) + c
The minimum occurs where the first derivative is zero:
res' = 2a(raot) + b = 0
raot_min = -b/2a
The a and b coefficients are solved for in the three
residual equations by eliminating c:
r_1 - r = a(raot_1^2 - raot^2) + b(raot_1 - raot)
r_2 - r = a(raot_2^2 - raot^2) + b(raot_2 - raot) */
*raot = raot550nm;
raotsaved = *raot;
xa = (residual1 - *residual)*(raot2 - *raot);
xb = (residual2 - *residual)*(raot1 - *raot);
raotmin = 0.5*(xa*(raot2 + *raot) - xb*(raot1 + *raot))/(xa - xb);
/* Validate the min AOT ratio */
if (raotmin < 0.01 || raotmin > 4.0)
raotmin = *raot;
/* Atmospheric correction for band 1 */
raot550nm = raotmin;
ib = iband1;
testth = false;
residualm = 0.0;
nbval = 0;
atmcorlamb2_new (sat, tgo_arr[ib], aot550nm[roatm_iaMax[ib]],
&roatm_coef[ib][0], &ttatmg_coef[ib][0], &satm_coef[ib][0],
raot550nm, ib, normext_p0a3_arr[ib], troatm[ib], &roslamb, eps);
if (roslamb - tth[iband1] < 0.0)
testth = true;
ros1 = roslamb;
if (water && erelc[ib] > 0.0)
{
residualm += (roslamb * roslamb);
nbval++;
}
/* Atmospheric correction for each band */
for (ib = start_band; ib <= end_band; ib++)
{
/* Don't reprocess iband1 */
if (ib != iband1 && erelc[ib] > 0.0)
{
atmcorlamb2_new (sat, tgo_arr[ib], aot550nm[roatm_iaMax[ib]],
&roatm_coef[ib][0], &ttatmg_coef[ib][0], &satm_coef[ib][0],
raot550nm, ib, normext_p0a3_arr[ib], troatm[ib], &roslamb,
eps);
if (roslamb - tth[ib] < 0.0)
testth = true;
if (water)
residualm += (roslamb * roslamb);
else
{
point_error = roslamb - erelc[ib] * ros1;
residualm += point_error * point_error;
}
nbval++;
}
}
residualm = sqrt (residualm) / nbval;
*raot = raot550nm;
/* Check the residuals and reset the AOT ratio */
if (residualm > *residual)
{
residualm = *residual;
*raot = raotsaved;
}
if (residualm > residual1)
{
residualm = residual1;
*raot = raot1;
}
if (residualm > residual2)
{
residualm = residual2;
*raot = raot2;
}
*residual = residualm;
/* Check the iaot values */
if (water && iaot == 1)
*iaots = 0;
else
*iaots = MAX ((iaot2 - 3), 0);
}
}
/******************************************************************************
MODULE: subaeroret
PURPOSE: Main driver for the atmospheric correction. This subroutine reads
the lookup table (LUT) and performs the atmospheric corrections. Traditional
FORTRAN algorithm.
RETURN VALUE:
Type = int
Value Description
----- -----------
ERROR Error occurred reading the LUT or doing the correction
SUCCESS Successful completion
NOTES:
******************************************************************************/
int subaeroret
(
Sat_t sat, /* I: satellite */
bool water, /* I: water pixel flag */
int iband1, /* I: band 1 index (0-based) */
float xts, /* I: solar zenith angle (deg) */
float xtv, /* I: observation zenith angle (deg) */
float xmus, /* I: cosine of solar zenith angle */
float xmuv, /* I: cosine of observation zenith angle */
float xfi, /* I: azimuthal difference between sun and
observation (deg) */
float cosxfi, /* I: cosine of azimuthal difference */
float pres, /* I: surface pressure */
float uoz, /* I: total column ozone */
float uwv, /* I: total column water vapor (precipital
water vapor) */
float erelc[NSR_BANDS], /* I: band ratio variable */
float troatm[NSR_BANDS], /* I: atmospheric reflectance table */
float tpres[NPRES_VALS], /* I: surface pressure table */
float *rolutt, /* I: intrinsic reflectance table
[NSR_BANDS x NPRES_VALS x NAOT_VALS x NSOLAR_VALS] */
float *transt, /* I: transmission table
[NSR_BANDS x NPRES_VALS x NAOT_VALS x NSUNANGLE_VALS] */
float xtsstep, /* I: solar zenith step value */
float xtsmin, /* I: minimum solar zenith value */
float xtvstep, /* I: observation step value */
float xtvmin, /* I: minimum observation value */
float *sphalbt, /* I: spherical albedo table
[NSR_BANDS x NPRES_VALS x NAOT_VALS] */
float *normext, /* I: aerosol extinction coefficient at the
current wavelength (normalized at 550nm)
[NSR_BANDS x NPRES_VALS x NAOT_VALS] */
float *tsmax, /* I: maximum scattering angle table
[NVIEW_ZEN_VALS x NSOLAR_ZEN_VALS] */
float *tsmin, /* I: minimum scattering angle table
[NVIEW_ZEN_VALS x NSOLAR_ZEN_VALS] */
float *nbfic, /* I: communitive number of azimuth angles
[NVIEW_ZEN_VALS x NSOLAR_ZEN_VALS] */
float *nbfi, /* I: number of azimuth angles
[NVIEW_ZEN_VALS x NSOLAR_ZEN_VALS] */
float tts[NSOLAR_ZEN_VALS], /* I: sun angle table */
int32 indts[NSUNANGLE_VALS], /* I: index for the sun angle table */
float *ttv, /* I: view angle table
[NVIEW_ZEN_VALS x NSOLAR_ZEN_VALS] */
float tauray[NSR_BANDS], /* I: molecular optical thickness coeff */
double ogtransa1[NSR_BANDS], /* I: other gases transmission coeff */
double ogtransb0[NSR_BANDS], /* I: other gases transmission coeff */
double ogtransb1[NSR_BANDS], /* I: other gases transmission coeff */
double wvtransa[NSR_BANDS], /* I: water vapor transmission coeff */
double wvtransb[NSR_BANDS], /* I: water vapor transmission coeff */
double oztransa[NSR_BANDS], /* I: ozone transmission coeff */
float *raot, /* O: AOT reflectance */
float *residual, /* O: model residual */
int *iaots, /* I/O: AOT index that is passed in and out
for multiple calls (0-based) */
float eps /* I: angstroem coefficient; spectral
dependency of the AOT */
)
{
char FUNC_NAME[] = "subaeroret"; /* function name */
char errmsg[STR_SIZE]; /* error message */
int iaot; /* aerosol optical thickness (AOT) index */
int retval; /* function return value */
int ib; /* band index */
int start_band = 0; /* starting band index for the loop */
int end_band = 0; /* ending band index for the loop */
float raot550nm=0.0; /* nearest input value of AOT */
float roslamb; /* lambertian surface reflectance */
double ros1; /* surface reflectance for bands */
double raot1, raot2; /* AOT ratios that bracket the predicted ratio */
double point_error; /* residual differences for each pixel */
float raotsaved; /* save the raot value */
float tgo; /* other gaseous transmittance */
float roatm; /* intrinsic atmospheric reflectance */
float ttatmg; /* total atmospheric transmission */
float satm; /* spherical albedo */
float xrorayp; /* reflectance of the atmosphere due to molecular
(Rayleigh) scattering */
double residual1, residual2; /* residuals for storing and comparing */
double residualm; /* local model residual */
int nbval; /* number of values meeting criteria */
bool testth; /* surface reflectance test variable */
double xa, xb; /* AOT ratio values */
double raotmin; /* minimum AOT ratio */
int iaot1, iaot2; /* AOT indices (0-based) */
float *tth = NULL; /* pointer to the Landsat or Sentinel tth array */
float landsat_tth[NSRL_BANDS] = {1.0e-03, 1.0e-03, 0.0, 1.0e-03, 0.0, 0.0,
1.0e-04, 0.0};
float landsat_tth_water[NSRL_BANDS] =
{1.0e-03, 1.0e-03, 0.0, 1.0e-03, 1.0e-03,
0.0, 1.0e-04, 0.0};
/* constant values for comparing against Landsat
surface reflectance */
#ifdef PROC_ALL_BANDS
/* Process all bands if turned on */
float sentinel_tth[NSRS_BANDS] = {1.0e-03, 1.0e-03, 0.0, 1.0e-03, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0e-04};
float sentinel_tth_water[NSRS_BANDS] =
{1.0e-03, 0.0, 0.0, 1.0e-03, 0.0, 0.0, 0.0,
0.0, 1.0e-3, 0.0, 0.0, 0.0, 1.0e-4};
/* ESPA - I believe the sentinel tth water should be for band 1, 4, 8a, and 12 vs. what I've commented below ... which is a duplicate of the FORTRAN array coeffs. I think that's a bug.
{1.0e-03, 1.0e-03, 0.0, 1.0e-03, 1.0e-3,
0.0, 1.0e-4, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};
*/
/* constant values for comparing against Sentinel
surface reflectance (different values for land
vs. water) */
#else
/* Skip bands 9 and 10 as default for ESPA */
float sentinel_tth[NSRS_BANDS] = {1.0e-03, 1.0e-03, 0.0, 1.0e-03, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 1.0e-04};
float sentinel_tth_water[NSRS_BANDS] =
{1.0e-03, 0.0, 0.0, 1.0e-03, 0.0, 0.0, 0.0,
0.0, 1.0e-3, 0.0, 1.0e-4};
/* constant values for comparing against Sentinel
surface reflectance (removed band 9&10) */
#endif
float aot550nm[NAOT_VALS] = {0.01, 0.05, 0.1, 0.15, 0.2, 0.3, 0.4, 0.6,
0.8, 1.0, 1.2, 1.4, 1.6, 1.8, 2.0, 2.3, 2.6,
3.0, 3.5, 4.0, 4.5, 5.0}; /* AOT values */
/* Initialize variables based on the satellite type */
if (sat == SAT_LANDSAT_8 || sat == SAT_LANDSAT_9)
{
if (water)
tth = landsat_tth_water;
else
tth = landsat_tth;
start_band = DNL_BAND1;
end_band = DNL_BAND7;
}
else if (sat == SAT_SENTINEL_2)
{
if (water)
tth = sentinel_tth_water;
else
tth = sentinel_tth;
start_band = DNS_BAND1;
end_band = DNS_BAND12;
}
/* Correct input band with increasing AOT (using pre till ratio is equal to
erelc[2]) */
iaot = *iaots;
residual1 = 2000.0;
residual2 = 1000.0;
iaot2 = 0;
iaot1 = 0;
raot2 = 1.0e-06;
raot1 = 0.0001;
ros1 = 1.0;
raot550nm = aot550nm[iaot];
testth = false;
nbval = 0;
*residual = 0.0;
/* Atmospheric correction for band 1 */
ib = iband1;
retval = atmcorlamb2 (sat, xts, xtv, xmus, xmuv, xfi, cosxfi, raot550nm, ib,
pres, tpres, aot550nm, rolutt, transt, xtsstep, xtsmin, xtvstep, xtvmin,
sphalbt, normext, tsmax, tsmin, nbfic, nbfi, tts, indts, ttv, uoz,
uwv, tauray, ogtransa1, ogtransb0, ogtransb1, wvtransa, wvtransb,
oztransa, troatm[ib], &roslamb, &tgo, &roatm, &ttatmg, &satm, &xrorayp,
eps);
if (retval != SUCCESS)
{
sprintf (errmsg, "Performing lambertian atmospheric correction "
"type 2.");
error_handler (true, FUNC_NAME, errmsg);
return (ERROR);
}
if (roslamb - tth[iband1] < 0.0)
testth = true;
ros1 = roslamb;
/* Atmospheric correction for each band; handle residual for water-based
correction differently */
if (water)
{ /* expect that we are processing pixels over water */
for (ib = start_band; ib <= end_band; ib++)
{
/* This will process iband1, different from land */
if (erelc[ib] > 0.0)
{
retval = atmcorlamb2 (sat, xts, xtv, xmus, xmuv, xfi, cosxfi,
raot550nm, ib, pres, tpres, aot550nm, rolutt, transt,
xtsstep, xtsmin, xtvstep, xtvmin, sphalbt, normext, tsmax,
tsmin, nbfic, nbfi, tts, indts, ttv, uoz, uwv, tauray,
ogtransa1, ogtransb0, ogtransb1, wvtransa, wvtransb,
oztransa, troatm[ib], &roslamb, &tgo, &roatm, &ttatmg,
&satm, &xrorayp, eps);
if (retval != SUCCESS)
{
sprintf (errmsg, "Performing lambertian atmospheric "
"correction type 2.");
error_handler (true, FUNC_NAME, errmsg);
return (ERROR);
}
if (roslamb - tth[ib] < 0.0)
testth = true;
*residual += roslamb*roslamb;
nbval++;
}
}
}
else
{ /* expect that we are processing pixels over land */
for (ib = start_band; ib <= end_band; ib++)
{
/* Don't reprocess iband1 */
if (ib != iband1 && erelc[ib] > 0.0)
{
retval = atmcorlamb2 (sat, xts, xtv, xmus, xmuv, xfi, cosxfi,
raot550nm, ib, pres, tpres, aot550nm, rolutt, transt,
xtsstep, xtsmin, xtvstep, xtvmin, sphalbt, normext, tsmax,
tsmin, nbfic, nbfi, tts, indts, ttv, uoz, uwv, tauray,
ogtransa1, ogtransb0, ogtransb1, wvtransa, wvtransb,
oztransa, troatm[ib], &roslamb, &tgo, &roatm, &ttatmg,
&satm, &xrorayp, eps);
if (retval != SUCCESS)
{
sprintf (errmsg, "Performing lambertian atmospheric "
"correction type 2.");
error_handler (true, FUNC_NAME, errmsg);
return (ERROR);
}
if (roslamb - tth[ib] < 0.0)
testth = true;
point_error = roslamb - erelc[ib] * ros1;
*residual += point_error * point_error;
nbval++;
}
}
}
*residual = sqrt (*residual) / nbval;
/* Loop until we converge on a solution */
iaot++;
while ((iaot < NAOT_VALS) && (*residual < residual1) && (!testth))
{
/* Reset variables for this loop */
residual2 = residual1;
iaot2 = iaot1;
raot2 = raot1;
residual1 = *residual;
raot1 = raot550nm;
iaot1 = iaot;
raot550nm = aot550nm[iaot];
*residual = 0.0;
nbval = 0;
/* Atmospheric correction for band 1 */
ib = iband1;
testth = false;
retval = atmcorlamb2 (sat, xts, xtv, xmus, xmuv, xfi, cosxfi,
raot550nm, ib, pres, tpres, aot550nm, rolutt, transt, xtsstep,
xtsmin, xtvstep, xtvmin, sphalbt, normext, tsmax, tsmin, nbfic,
nbfi, tts, indts, ttv, uoz, uwv, tauray, ogtransa1, ogtransb0,
ogtransb1, wvtransa, wvtransb, oztransa, troatm[ib], &roslamb,
&tgo, &roatm, &ttatmg, &satm, &xrorayp, eps);
if (retval != SUCCESS)
{
sprintf (errmsg, "Performing lambertian atmospheric correction "
"type 2.");
error_handler (true, FUNC_NAME, errmsg);
return (ERROR);
}
if (roslamb - tth[iband1] < 0.0)
testth = true;
ros1 = roslamb;
/* Atmospheric correction for each band; handle residual for water-based
correction differently */
if (water)
{ /* expect that we are processing pixels over water */
for (ib = start_band; ib <= end_band; ib++)
{
/* This will process iband1, different from land */
if (erelc[ib] > 0.0)
{
retval = atmcorlamb2 (sat, xts, xtv, xmus, xmuv, xfi,
cosxfi, raot550nm, ib, pres, tpres, aot550nm, rolutt,
transt, xtsstep, xtsmin, xtvstep, xtvmin, sphalbt,
normext, tsmax, tsmin, nbfic, nbfi, tts, indts, ttv,
uoz, uwv, tauray, ogtransa1, ogtransb0, ogtransb1,
wvtransa, wvtransb, oztransa, troatm[ib], &roslamb,
&tgo, &roatm, &ttatmg, &satm, &xrorayp, eps);
if (retval != SUCCESS)
{
sprintf (errmsg, "Performing lambertian atmospheric "
"correction type 2.");
error_handler (true, FUNC_NAME, errmsg);
return (ERROR);
}
if (roslamb - tth[ib] < 0.0)
testth = true;
*residual += roslamb*roslamb;
nbval++;
}
}
}
else
{ /* expect that we are processing pixels over land */
for (ib = start_band; ib <= end_band; ib++)
{
/* Don't reprocess iband1 */
if (ib != iband1 && erelc[ib] > 0.0)
{
retval = atmcorlamb2 (sat, xts, xtv, xmus, xmuv, xfi,
cosxfi, raot550nm, ib, pres, tpres, aot550nm, rolutt,
transt, xtsstep, xtsmin, xtvstep, xtvmin, sphalbt,
normext, tsmax, tsmin, nbfic, nbfi, tts, indts, ttv,
uoz, uwv, tauray, ogtransa1, ogtransb0, ogtransb1,
wvtransa, wvtransb, oztransa, troatm[ib], &roslamb,
&tgo, &roatm, &ttatmg, &satm, &xrorayp, eps);
if (retval != SUCCESS)
{
sprintf (errmsg, "Performing lambertian atmospheric "
"correction type 2.");
error_handler (true, FUNC_NAME, errmsg);
return (ERROR);
}
if (roslamb - tth[ib] < 0.0)
testth = true;
point_error = roslamb - erelc[ib] * ros1;
*residual += point_error * point_error;
nbval++;
}
}
}
*residual = sqrt (*residual) / nbval;
/* Move to the next AOT index */
iaot++;
} /* while aot */
/* If a minimum local was not reached for raot1, then just use the
raot550nm value. Otherwise continue to refine the raot. */
if (iaot == 1)
{
*raot = raot550nm;
}
else
{
/* Refine the AOT ratio. This is performed by applying a parabolic
(quadratic) fit to the three (raot, residual) pairs found above:
res = a(raot)^2 + b(raot) + c
The minimum occurs where the first derivative is zero:
res' = 2a(raot) + b = 0
raot_min = -b/2a
The a and b coefficients are solved for in the three
residual equations by eliminating c:
r_1 - r = a(raot_1^2 - raot^2) + b(raot_1 - raot)
r_2 - r = a(raot_2^2 - raot^2) + b(raot_2 - raot) */
*raot = raot550nm;
raotsaved = *raot;
xa = (residual1 - *residual)*(raot2 - *raot);
xb = (residual2 - *residual)*(raot1 - *raot);
raotmin = 0.5*(xa*(raot2 + *raot) - xb*(raot1 + *raot))/(xa - xb);
/* Validate the min AOT ratio */
if (raotmin < 0.01 || raotmin > 4.0)
raotmin = *raot;
/* Atmospheric correction for band 1 */
raot550nm = raotmin;
ib = iband1;
testth = false;
nbval = 0;
residualm = 0.0;
retval = atmcorlamb2 (sat, xts, xtv, xmus, xmuv, xfi, cosxfi, raot550nm,
ib, pres, tpres, aot550nm, rolutt, transt, xtsstep, xtsmin, xtvstep,
xtvmin, sphalbt, normext, tsmax, tsmin, nbfic, nbfi, tts, indts,
ttv, uoz, uwv, tauray, ogtransa1, ogtransb0, ogtransb1, wvtransa,
wvtransb, oztransa, troatm[ib], &roslamb, &tgo, &roatm, &ttatmg,
&satm, &xrorayp, eps);
if (retval != SUCCESS)
{
sprintf (errmsg, "Performing lambertian atmospheric correction "
"type 2.");
error_handler (true, FUNC_NAME, errmsg);
return (ERROR);
}
if (roslamb - tth[iband1] < 0.0)
testth = true;
ros1 = roslamb;
if (water && erelc[ib] > 0.0)
{
residualm += (roslamb * roslamb);
nbval++;
}
/* Atmospheric correction for each band */
for (ib = start_band; ib <= end_band; ib++)
{
/* Don't reprocess iband1 */
if (ib != iband1 && erelc[ib] > 0.0)
{
retval = atmcorlamb2 (sat, xts, xtv, xmus, xmuv, xfi, cosxfi,
raot550nm, ib, pres, tpres, aot550nm, rolutt, transt,
xtsstep, xtsmin, xtvstep, xtvmin, sphalbt, normext, tsmax,
tsmin, nbfic, nbfi, tts, indts, ttv, uoz, uwv, tauray,
ogtransa1, ogtransb0, ogtransb1, wvtransa, wvtransb,
oztransa, troatm[ib], &roslamb, &tgo, &roatm, &ttatmg,
&satm, &xrorayp, eps);
if (retval != SUCCESS)
{
sprintf (errmsg, "Performing lambertian atmospheric "
"correction type 2.");
error_handler (true, FUNC_NAME, errmsg);
return (ERROR);
}
if (roslamb - tth[ib] < 0.0)
testth = true;
if (water)
residualm += (roslamb * roslamb);
else
{
point_error = roslamb - erelc[ib] * ros1;
residualm += point_error * point_error;
}
nbval++;
}
}
residualm = sqrt (residualm) / nbval;
*raot = raot550nm;
/* Check the residuals and reset the AOT ratio */
if (residualm > *residual)
{
residualm = *residual;
*raot = raotsaved;
}
if (residualm > residual1)
{
residualm = residual1;
*raot = raot1;
}
if (residualm > residual2)
{
residualm = residual2;
*raot = raot2;
}
*residual = residualm;
/* Check the iaot values */
if (water && iaot == 1)
*iaots = 0;
else
*iaots = MAX ((iaot2 - 3), 0);
}
/* Successful completion */
return (SUCCESS);
}
| 41.362049 | 185 | 0.483648 | [
"model"
] |
1b4da3d2cef90b9eed2a720c07aadb40cf3a27cb | 2,781 | h | C | src/lib/utils/http_util/http_util.h | balabit-deps/balabit-os-6-botan1.11 | a32fe9adf894e59a056cada1f5c4baee7a8ea689 | [
"BSD-2-Clause"
] | null | null | null | src/lib/utils/http_util/http_util.h | balabit-deps/balabit-os-6-botan1.11 | a32fe9adf894e59a056cada1f5c4baee7a8ea689 | [
"BSD-2-Clause"
] | null | null | null | src/lib/utils/http_util/http_util.h | balabit-deps/balabit-os-6-botan1.11 | a32fe9adf894e59a056cada1f5c4baee7a8ea689 | [
"BSD-2-Clause"
] | null | null | null | /*
* HTTP utilities
* (C) 2013 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#ifndef BOTAN_UTILS_URLGET_H__
#define BOTAN_UTILS_URLGET_H__
#include <botan/types.h>
#include <botan/exceptn.h>
#include <vector>
#include <map>
#include <chrono>
#include <string>
namespace Botan {
namespace HTTP {
struct Response
{
public:
Response() : m_status_code(0), m_status_message("Uninitialized") {}
Response(unsigned int status_code, const std::string& status_message,
const std::vector<byte>& body,
const std::map<std::string, std::string>& headers) :
m_status_code(status_code),
m_status_message(status_message),
m_body(body),
m_headers(headers) {}
unsigned int status_code() const { return m_status_code; }
const std::vector<byte>& body() const { return m_body; }
const std::map<std::string, std::string>& headers() const { return m_headers; }
std::string status_message() const { return m_status_message; }
void throw_unless_ok()
{
if(status_code() != 200)
throw Exception("HTTP error: " + status_message());
}
private:
unsigned int m_status_code;
std::string m_status_message;
std::vector<byte> m_body;
std::map<std::string, std::string> m_headers;
};
/**
* HTTP_Error Exception
*/
struct BOTAN_DLL HTTP_Error : public Exception
{
explicit HTTP_Error(const std::string& msg) :
Exception("HTTP error " + msg)
{}
};
BOTAN_DLL std::ostream& operator<<(std::ostream& o, const Response& resp);
typedef std::function<std::string (const std::string&, const std::string&)> http_exch_fn;
BOTAN_DLL Response http_sync(http_exch_fn fn,
const std::string& verb,
const std::string& url,
const std::string& content_type,
const std::vector<byte>& body,
size_t allowable_redirects);
BOTAN_DLL Response http_sync(const std::string& verb,
const std::string& url,
const std::string& content_type,
const std::vector<byte>& body,
size_t allowable_redirects);
BOTAN_DLL Response GET_sync(const std::string& url,
size_t allowable_redirects = 1);
BOTAN_DLL Response POST_sync(const std::string& url,
const std::string& content_type,
const std::vector<byte>& body,
size_t allowable_redirects = 1);
BOTAN_DLL std::string url_encode(const std::string& url);
}
}
#endif
| 28.377551 | 89 | 0.591514 | [
"vector"
] |
1b59ba1499f741877b02793b2d9b0484243aacc3 | 760 | h | C | src/include/perspective/schema_column.h | nmichaud/perspective-X | d57e80f537d766eca5df6787fb26dfd584c4c8f0 | [
"Apache-2.0"
] | null | null | null | src/include/perspective/schema_column.h | nmichaud/perspective-X | d57e80f537d766eca5df6787fb26dfd584c4c8f0 | [
"Apache-2.0"
] | null | null | null | src/include/perspective/schema_column.h | nmichaud/perspective-X | d57e80f537d766eca5df6787fb26dfd584c4c8f0 | [
"Apache-2.0"
] | null | null | null | /******************************************************************************
*
* Copyright (c) 2017, the Perspective Authors.
*
* This file is part of the Perspective library, distributed under the terms of
* the Apache License 2.0. The full license can be found in the LICENSE file.
*
*/
#pragma once
#include <perspective/first.h>
#include <perspective/base.h>
#include <perspective/raw_types.h>
#include <vector>
namespace perspective
{
class t_schema_column
{
t_schema_column(const t_str& tblname, const t_str& name,
const t_str& altname, t_dtype dtype);
private:
t_str m_tblname;
t_str m_name;
t_str m_altname;
t_dtype m_dtype;
};
typedef std::vector<t_schema_column> t_scolvec;
} // end namespace perspective
| 22.352941 | 79 | 0.647368 | [
"vector"
] |
1b5ecfdea60cc23a07327132ac9f0c8590a6ccb1 | 6,278 | h | C | src/util/expr.h | shmarovfedor/esbmc | 3226a3d68b009d44b9535a993ac0f25e1a1fbedd | [
"BSD-3-Clause"
] | 143 | 2015-06-22T12:30:01.000Z | 2022-03-21T08:41:17.000Z | src/util/expr.h | shmarovfedor/esbmc | 3226a3d68b009d44b9535a993ac0f25e1a1fbedd | [
"BSD-3-Clause"
] | 542 | 2017-06-02T13:46:26.000Z | 2022-03-31T16:35:17.000Z | src/util/expr.h | shmarovfedor/esbmc | 3226a3d68b009d44b9535a993ac0f25e1a1fbedd | [
"BSD-3-Clause"
] | 81 | 2015-10-21T22:21:59.000Z | 2022-03-24T14:07:55.000Z | /*******************************************************************\
Module:
Author: Daniel Kroening, kroening@kroening.com
\*******************************************************************/
#ifndef CPROVER_EXPR_H
#define CPROVER_EXPR_H
#include <util/location.h>
#include <util/type.h>
#define forall_operands(it, expr) \
if((expr).has_operands()) \
for(exprt::operandst::const_iterator it = (expr).operands().begin(); \
it != (expr).operands().end(); \
it++)
#define Forall_operands(it, expr) \
if((expr).has_operands()) \
for(exprt::operandst::iterator it = (expr).operands().begin(); \
it != (expr).operands().end(); \
it++)
#define forall_expr(it, expr) \
for(exprt::operandst::const_iterator it = (expr).begin(); \
it != (expr).end(); \
it++)
#define Forall_expr(it, expr) \
for(exprt::operandst::iterator it = (expr).begin(); it != (expr).end(); it++)
#define forall_expr_list(it, expr) \
for(expr_listt::const_iterator it = (expr).begin(); it != (expr).end(); it++)
#define Forall_expr_list(it, expr) \
for(expr_listt::iterator it = (expr).begin(); it != (expr).end(); it++)
class exprt : public irept
{
public:
#ifdef USE_LIST
typedef std::list<exprt> operandst;
#else
typedef std::vector<exprt> operandst;
#endif
// constructors
exprt() = default;
explicit exprt(const irep_idt &_id) : irept(_id)
{
}
exprt(const irep_idt &_id, const typet &_type) : irept(_id)
{
type() = _type;
}
bool has_operands() const
{
return !find(o_operands).is_nil();
}
operandst &operands()
{
return (operandst &)(add(o_operands).get_sub());
}
const operandst &operands() const
{
return (const operandst &)(find(o_operands).get_sub());
}
const irep_idt &value() const
{
return get(a_value);
}
void value(irep_idt val)
{
set(a_value, val);
};
exprt &op0()
{
return operands().front();
}
exprt &op1()
#ifdef USE_LIST
{
return *(++operands().begin());
}
#else
{
return operands()[1];
}
#endif
exprt &op2()
#ifdef USE_LIST
{
return *(++++operands().begin());
}
#else
{
return operands()[2];
}
#endif
exprt &op3()
#ifdef USE_LIST
{
return *(++++++operands().begin());
}
#else
{
return operands()[3];
}
#endif
const exprt &op0() const
{
return operands().front();
}
const exprt &op1() const
#ifdef USE_LIST
{
return *(++operands().begin());
}
#else
{
return operands()[1];
}
#endif
const exprt &op2() const
#ifdef USE_LIST
{
return *(++++operands().begin());
}
#else
{
return operands()[2];
}
#endif
const exprt &op3() const
#ifdef USE_LIST
{
return *(++++++operands().begin());
}
#else
{
return operands()[3];
}
#endif
void reserve_operands(unsigned n)
#ifdef USE_LIST
{
}
#else
{
operands().reserve(n);
}
#endif
void move_to_operands(exprt &expr); // destroys expr
void move_to_operands(exprt &e1, exprt &e2); // destroys e1, e2
void move_to_operands(exprt &e1, exprt &e2, exprt &e3); // destroys e1, e2, e3
void copy_to_operands(const exprt &expr); // does not destroy expr
void
copy_to_operands(const exprt &e1, const exprt &e2); // does not destroy expr
void copy_to_operands(
const exprt &e1,
const exprt &e2,
const exprt &e3); // does not destroy expr
void make_typecast(const typet &_type);
void make_not();
void make_true();
void make_false();
void make_bool(bool value);
void negate();
bool sum(const exprt &expr);
bool mul(const exprt &expr);
bool subtract(const exprt &expr);
bool is_constant() const;
bool is_true() const;
bool is_false() const;
bool is_zero() const;
bool is_one() const;
bool is_boolean() const;
friend bool operator<(const exprt &X, const exprt &Y);
const locationt &find_location() const;
const locationt &location() const
{
return static_cast<const locationt &>(cmt_location());
}
locationt &location()
{
return static_cast<locationt &>(add(o_location));
}
exprt &add_expr(const std::string &name)
{
return static_cast<exprt &>(add(name));
}
const exprt &find_expr(const std::string &name) const
{
return static_cast<const exprt &>(find(name));
}
// Actual expression nodes
static irep_idt trans;
static irep_idt symbol;
static irep_idt plus;
static irep_idt minus;
static irep_idt mult;
static irep_idt div;
static irep_idt mod;
static irep_idt equality;
static irep_idt notequal;
static irep_idt index;
static irep_idt arrayof;
static irep_idt objdesc;
static irep_idt dynobj;
static irep_idt typecast;
static irep_idt implies;
static irep_idt i_and;
static irep_idt i_xor;
static irep_idt i_or;
static irep_idt i_not;
static irep_idt addrof;
static irep_idt deref;
static irep_idt i_if;
static irep_idt with;
static irep_idt member;
static irep_idt isnan;
static irep_idt ieee_floateq;
static irep_idt i_type;
static irep_idt constant;
static irep_idt i_true;
static irep_idt i_false;
static irep_idt i_lt;
static irep_idt i_gt;
static irep_idt i_le;
static irep_idt i_ge;
static irep_idt i_bitand;
static irep_idt i_bitor;
static irep_idt i_bitxor;
static irep_idt i_bitnand;
static irep_idt i_bitnor;
static irep_idt i_bitnxor;
static irep_idt i_bitnot;
static irep_idt i_ashr;
static irep_idt i_lshr;
static irep_idt i_shl;
static irep_idt abs;
static irep_idt argument;
// Expression attributes
static irep_idt a_value;
// Other foo
protected:
static irep_idt o_operands;
static irep_idt o_location;
};
typedef std::list<exprt> expr_listt;
#endif
| 22.105634 | 80 | 0.583147 | [
"vector"
] |
1b612cb1ab30a2201a449a1898b71ac8dda7ac35 | 604 | h | C | src/model.h | dvorontsov/software-rasterizer | 2edfb1c897a39de79ccdd34a3a36c432b5e75aab | [
"MIT"
] | null | null | null | src/model.h | dvorontsov/software-rasterizer | 2edfb1c897a39de79ccdd34a3a36c432b5e75aab | [
"MIT"
] | null | null | null | src/model.h | dvorontsov/software-rasterizer | 2edfb1c897a39de79ccdd34a3a36c432b5e75aab | [
"MIT"
] | null | null | null | #ifndef MODEL_H
#define MODEL_H
#include "texture.h"
#include "tga_image_loader.h"
#include "math_operations.h"
#include "obj_model_loader.h"
#define MAX_MODEL_COUNT_PER_SCENE 10
typedef struct
{
char* name;
Mesh* mesh;
Texture* diffuse_map;
Texture* normal_map;
Texture* specular_map;
} Model;
typedef struct
{
vec3 position;
} Light;
typedef struct
{
Model* models[MAX_MODEL_COUNT_PER_SCENE];
int modelCount;
Light light;
} Scene;
Model* load_model(
char* name,
char* obj,
char* diffuse_map,
char* normal_map,
char* specular_map);
void free_model(Model* model);
#endif // !MODEL_H | 14.731707 | 42 | 0.746689 | [
"mesh",
"model"
] |
1b63367e73f40f10bcab377ca8701cc4558ad284 | 1,076 | h | C | Source/MultiBreakpong/BreakeableBar.h | Enagan/MultiBreakPong | 509fee732ab1b2bfa3fe0e3edbbd3181ec6ea878 | [
"MIT"
] | 1 | 2018-01-31T04:10:35.000Z | 2018-01-31T04:10:35.000Z | Source/MultiBreakpong/BreakeableBar.h | Enagan/MultiBreakPong | 509fee732ab1b2bfa3fe0e3edbbd3181ec6ea878 | [
"MIT"
] | null | null | null | Source/MultiBreakpong/BreakeableBar.h | Enagan/MultiBreakPong | 509fee732ab1b2bfa3fe0e3edbbd3181ec6ea878 | [
"MIT"
] | null | null | null | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "GameFramework/Actor.h"
#include "BreakeableBar.generated.h"
// The breakeable bar is a breakout like volume, that self destroys when hit by the ball
UCLASS()
class MULTIBREAKPONG_API ABreakeableBar : public AActor
{
GENERATED_BODY()
public:
ABreakeableBar();
private:
// Function to handle logic related to collisions, the bar will self destroy upon colliding with something
UFUNCTION()
void OnHit(UPrimitiveComponent* HitComp, AActor* OtherActor, UPrimitiveComponent* OtherComp, FVector NormalImpulse, const FHitResult& Hit);
private:
// Mesh used to represent the BreakBar
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "BreakeableBar", meta = (AllowPrivateAccess = "true"))
class UStaticMeshComponent* BreakeableBarMesh;
// Dynamic material, to allow us to easily change the material color for a bit more variety on the play field
UPROPERTY(VisibleAnywhere, Category = "BreakeableBar")
UMaterialInstanceDynamic* DynamicMaterial;
};
| 34.709677 | 141 | 0.784387 | [
"mesh"
] |
1b6a5c4ba6dc13ea031c46d1a947ff108dd32765 | 2,915 | h | C | common/include/Collision/ContactConstraint.h | FikkleG/gallopingFaster | 2578980f0fbb3a2aa32054bc12cab6e156f1953f | [
"MIT"
] | null | null | null | common/include/Collision/ContactConstraint.h | FikkleG/gallopingFaster | 2578980f0fbb3a2aa32054bc12cab6e156f1953f | [
"MIT"
] | null | null | null | common/include/Collision/ContactConstraint.h | FikkleG/gallopingFaster | 2578980f0fbb3a2aa32054bc12cab6e156f1953f | [
"MIT"
] | null | null | null | /*!
* @file ContactConstraint.h
* @brief Virtual class of Contact Constraint logic
*
* To make a child class, you need to implement virtual function,
* UpdateExternalForces, UpdateQdot
*/
#ifndef CONTACT_CONSTRAINT_H
#define CONTACT_CONSTRAINT_H
#include <iostream>
#include "Collision/Collision.h"
#include "Dynamics/FloatingBaseModel.h"
#include "Utilities/Utilities_print.h"
#include "cppTypes.h"
#define CC ContactConstraint<T>
/*!
* Contact dynamics for a floating base model
*/
template <typename T>
class ContactConstraint {
public:
/*!
* Construct a contact model for the given floating base model
* @param model : FloatingBaseModel for the contact
*/
ContactConstraint(FloatingBaseModel<T>* model)
: _nContact(0), _nCollision(0) {
_model = model;
for (size_t i(0); i < _model->_nGroundContact; ++i) {
_cp_force_list.push_back(Vec3<T>::Zero());
}
}
virtual ~ContactConstraint() {}
/*!
* Add collision object
* @param collision : collision objects
*/
void AddCollision(Collision<T>* collision)
{
_collision_list.push_back(collision);
++_nCollision;
}
void StartShaking()
{
for(unsigned int i = 0;i<_collision_list.size();i++)
{
_collision_list[i]->timeFlow();
}
}
void StopShaking()
{
}
/*!
* Add external forces to the floating base model in response to collisions
* Used for spring damper based contact constraint method
* @param K : Spring constant
* @param D : Damping constant
* @param dt : time step (sec)
*/
virtual void UpdateExternalForces(T K, T D, T dt) = 0;
/*!
* Adjust q_dot on the floating base model in response to collisions
* Used for impulse based contact constraint method
* @param state : full state of a floating system full state
*/
virtual void UpdateQdot(FBModelState<T>& state) = 0;
/*!
* For visualization
* @return cp_pos_list : all contact point position in the global frame.
*/
const vectorAligned<Vec3<T>>& getContactPosList() { return _cp_pos_list; }
/*!
* For visualization
* @return cp_force_list : all linear contact force described in the global
* frame.
*/
const Vec3<T>& getGCForce(size_t idx) { return _cp_force_list[idx]; }
protected:
vectorAligned<Vec2<T>> deflectionRate;
void _groundContactWithOffset(T K, T D);
size_t _CheckContact();
vectorAligned<Vec2<T>> _tangentialDeflections;
size_t _nContact;
size_t _nCollision;
FloatingBaseModel<T>* _model;
std::vector<Collision<T>*> _collision_list;
std::vector<size_t> _idx_list;
std::vector<T> _cp_resti_list;
std::vector<T> _cp_mu_list;
std::vector<T> _cp_penetration_list;
vectorAligned<Vec3<T>> _cp_force_list; // For All contact point w.r.t Global
vectorAligned<Vec3<T>> _cp_local_force_list;
vectorAligned<Vec3<T>> _cp_pos_list;
vectorAligned<Mat3<T>> _cp_frame_list;
};
#endif
| 25.12931 | 79 | 0.697084 | [
"object",
"vector",
"model"
] |
1b75ed154c54ef61e7dbc504027e764a60583941 | 1,812 | h | C | CKKit/Classes/CKKit.framework/Headers/CKSpinnerView.h | ThreeYearOld/CKKit | 2d7504f6049c18053c29706c6c1df9151b29f36f | [
"MIT"
] | null | null | null | CKKit/Classes/CKKit.framework/Headers/CKSpinnerView.h | ThreeYearOld/CKKit | 2d7504f6049c18053c29706c6c1df9151b29f36f | [
"MIT"
] | null | null | null | CKKit/Classes/CKKit.framework/Headers/CKSpinnerView.h | ThreeYearOld/CKKit | 2d7504f6049c18053c29706c6c1df9151b29f36f | [
"MIT"
] | null | null | null | //
// CKSpinnerView.h
// CKKit
//
// Created by admin on 2019/12/16.
// Copyright © 2019 Chengkun. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "CKSpinnerCell.h"
typedef NS_ENUM(NSInteger, CKDisplayForward) {
CKDisplayForwardForUp = 1, // 在当前控制器向上展示
CKDisplayForwardForDown = 2, // 在当前控制器向下展示
CKDisplayForwardForDownOnWindow = 3 // 在window上向下展示,仅在ios13以下使用有效
};
typedef NS_ENUM(NSInteger, CKNarrowLocation) {
CKNarrowLocationForRight = 1, // 箭头在右侧
CKNarrowLocationForLeft = 2, // 箭头在左侧
CKNarrowLocationForCenter = 3 // 箭头在中间
};
@interface CKSpinnerView : UITableView <UITableViewDataSource, UITableViewDelegate>
/** 数据模型,Model或者NSString */
@property (nonatomic, strong) NSArray *datas;
/** 默认选中的序号 */
@property (nonatomic, assign) NSInteger defaultSelectedIndex;
/** 点击dim是否消失 */
@property (nonatomic, assign) BOOL touchOutsideHide;
/** 是否显示蒙层 - 默认显示 */
@property (nonatomic, assign) BOOL isDisplayCoverView;
/** 箭头的位置 - 默认在右侧 */
@property (nonatomic, assign) CKNarrowLocation narrowLocation;
/** 是否增加展示的宽度 */
@property (nonatomic, assign) CGFloat extraWidth;
/** 自定义下拉框的高度 - 高度为 0 时,高度自适应屏幕可视区域 */
@property (nonatomic, assign) CGFloat selfHeight;
/** 键盘是否显示 - 如果键盘显示,第一次点击干掉键盘,第二次干掉所有 */
@property (nonatomic, assign) BOOL iskeyboardShow;
/** 点击时的回掉 */
@property (nonatomic, copy) void(^callback)(NSIndexPath *index, id model);
/** cellForRowAtIndexPath 方法执行时 扩展block */
@property (nonatomic, copy) void(^cellForRowExtendBlock)(CKSpinnerCell *cell, id model);
/**
* spinnerView显示在哪个view下面
* @param target 显示在目标的view下面,并且宽度和目标View等宽。
*/
- (void)showBelowWith:(UIView *)target displayForward:(CKDisplayForward)forward;
/**
* 隐藏spinnerView
* @param animate 动画
*/
- (void)hideWithAnimate:(BOOL)animate;
@end
| 25.521127 | 88 | 0.715784 | [
"model"
] |
1b7e754a43367eb1849b883e08f78736bede07ad | 5,240 | h | C | src/driver/pavo_ros/sdk/include/pavo_driver.h | cuishiwei/mini_robot | a66eec5a7b1e45af724a4f509952af961fa2d3f6 | [
"Apache-2.0"
] | null | null | null | src/driver/pavo_ros/sdk/include/pavo_driver.h | cuishiwei/mini_robot | a66eec5a7b1e45af724a4f509952af961fa2d3f6 | [
"Apache-2.0"
] | null | null | null | src/driver/pavo_ros/sdk/include/pavo_driver.h | cuishiwei/mini_robot | a66eec5a7b1e45af724a4f509952af961fa2d3f6 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <string>
#include <boost/thread/thread.hpp>
#include <boost/smart_ptr.hpp>
#include <boost/asio.hpp>
#include <time.h>
#include "sys_types.h"
#include "pavo_types.h"
#include "pavo_cmd.h"
#include "utils.h"
#include "data_filters.h"
#include "pavo_exception.h"
#define SDK_VER "20191220 2.0.5"
//VS2015 does not support exception declaration
#if defined(_WIN32)
#pragma warning (disable:4290)
#endif
namespace pavo
{
class pavo_driver
{
public:
pavo_driver() throw(pavo_exception);
pavo_driver(std::string dest_ip, uint16_t dest_port) throw(pavo_exception);
pavo_driver(std::string device_ip, uint16_t device_port, std::string dest_ip, uint16_t dest_port) throw(pavo_exception);
~pavo_driver();
bool pavo_open(std::string device_ip, uint16_t device_port) throw(pavo_exception);
void pavo_close();
bool get_scanned_data(pavo_response_scan_t* data_buffer, int& count, int timeout=0);
bool get_scanned_data(std::vector<pavo_response_scan_t>& vec_buff, int timeout = 0);
bool get_scanned_data(pavo_response_pcd_t* data_buffer, int& count, int timeout=0);
bool get_scanned_data(std::vector<pavo_response_pcd_t>& vec_buff, int timeout = 0);
////////////////////////////////////////////////////////////////////////////////////////////
bool get_scanned_data_timestamp(pavo_response_scan_t* data_buffer, int& count, unsigned int & timestamp, int timeout = 0);
bool get_scanned_data_timestamp(std::vector<pavo_response_scan_t>& vec_buff, unsigned int & timestamp, int timeout = 0);
bool get_scanned_data_timestamp(pavo_response_pcd_t* data_buffer, int& count, unsigned int & timestamp, int timeout = 0);
bool get_scanned_data_timestamp(std::vector<pavo_response_pcd_t>& vec_buff, unsigned int & timestamp, int timeout = 0);
bool is_lidar_connected();
int get_device_type();
bool get_device_sn(uint32_t &sn);
bool get_device_pn(uint32_t &pn);
void enable_data(bool en);
bool get_dest_ip(std::string& dest_ip);
bool set_dest_ip(const std::string& dest_ip);
bool get_dest_port(uint16_t& dest_port);
bool set_dest_port(uint16_t dest_port);
bool get_lidar_ip(std::string& lidar_ip);
bool set_lidar_ip(const std::string& lidar_ip);
bool get_lidar_port(uint16_t& port);
bool set_lidar_port(uint16_t port);
bool apply_net_config();
bool get_motor_speed(int& motor_spped);
bool set_motor_speed(int motor_speed);
bool get_merge_coef(int& merge_coef);
bool set_merge_coef(int merge_coef);
bool get_degree_shift(int °ree_shift);
bool set_degree_shift(int degree_shift);
void get_degree_scope(int& min, int& max);
bool set_degree_scope(int min, int max);
void enable_motor(bool en);
bool reset();
bool reset(std::string device_ip, uint16_t device_port, std::string dest_ip, uint16_t dest_port);
void enable_tail_filter(int method);
private:
void StartThread();
void StopIOService();
void StartReceiveService();
void HandReceive(const boost::system::error_code& error, std::size_t rxBytes);
void ProcessPavoFiring(pavo_firing_data_t* firingData, int firingBlock, int azimuthDiff);
void ProcessPavoPacket(unsigned char *data, std::size_t bytesReceived);
void IncreaseFrameCount();
void DecreaseFrameCount();
void UpdateInterval(unsigned int tohTime, int laserPerFiring);
int SendData(const unsigned char* buffer, int size);
void DisableDataTransfer();
void EnableDataTransfer();
void EnableMotor();
void DisableMotor();
int PopFrame(int n = 1); //ret: the actual number deleted
void UnInitialize();
bool Initialize();
void EnablePassiveMode();
private:
bool ConfigRegSimp(PAVO_REG_INDEX reg_set, const char* cmd); //simplex
bool ConfigRegDual(PAVO_REG_INDEX reg_set, PAVO_REG_INDEX reg_get, const char* cmd); //dualplex
bool ReadReg(PAVO_REG_INDEX reg_get, char* read_buff);
private:
boost::asio::io_service IOService;
boost::scoped_ptr<boost::thread> Thread;
boost::asio::ip::udp::socket* ReceiveSocket;
boost::asio::ip::udp::socket* SendSocket;
boost::asio::ip::udp::endpoint LIDAREndpoint; // Endpoint data to
boost::asio::ip::udp::endpoint RemoteEndpoint; //The Endpoint data from
bool IsReceiving;
bool ShouldStop;
boost::mutex IsReceivingMtx;
boost::condition_variable IsReceivingCond;
boost::mutex DataOpMtx; //protect: IsResponseReceived, FrameCount, IsDataMode
boost::condition_variable DataOpCond;
int FrameCount;
bool IsDataMode;
bool IsResponseReceived;
unsigned char ReceiveBuffer[1500];
unsigned char SendBuffer[1500];
boost::scoped_ptr<boost::asio::io_service::work> DummyWork;
SynchronizedQueue<pavo_response_scan_t*> PacketQue;
int FrameCapacity;
int LastAzimuth;
unsigned int LastTimestamp;
unsigned int CurrentTimestamp;
unsigned int CurrentFrameTimestamp;
unsigned int time_diff;
unsigned int AzimuthDiff;
unsigned int ResponseCount;
std::string DestIp;
uint16_t DestPort;
std::string LidarIp;
uint16_t LidarPort;
int DegreeScopeMin;
int DegreeScopeMax;
bool DegreeCrop;
boost::system_time PacketTouch;
MADataFilter* Filter;
bool passive_mode;
bool ReceiveSocketStatus;
};
}
| 27.578947 | 124 | 0.736832 | [
"vector"
] |
1b82104ca3ffa95ec536f668cea7f9f87d6a07c3 | 10,248 | h | C | expression/matrix-assembly/EigenvalueExpression.h | MaxZZG/ExprLib | c35e361ef6af365e7cd6afca6548595693bd149a | [
"MIT"
] | null | null | null | expression/matrix-assembly/EigenvalueExpression.h | MaxZZG/ExprLib | c35e361ef6af365e7cd6afca6548595693bd149a | [
"MIT"
] | null | null | null | expression/matrix-assembly/EigenvalueExpression.h | MaxZZG/ExprLib | c35e361ef6af365e7cd6afca6548595693bd149a | [
"MIT"
] | null | null | null | /*
* The MIT License
*
* Copyright (c) 2016-2017 The University of Utah
*
* 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.
*/
#ifndef EIGENVALUEEXPR_H_
#define EIGENVALUEEXPR_H_
#include <limits>
#include <spatialops/structured/MatVecFields.h>
#include <spatialops/structured/MatVecOps.h>
#include <expression/Expression.h>
#include <expression/matrix-assembly/AssemblerBase.h>
namespace Expr
{
template<typename FieldType>
std::vector<FieldType> union_vectors( const std::vector<FieldType>& left,
const std::vector<FieldType>& right )
{
std::vector<FieldType> retval( left );
retval.reserve( right.size() );
for( const auto& r : right ){
retval.push_back( r );
}
return retval;
}
/**
* \class EigenvaluesExpr
*
* This Expression computes a subset of eigenvalues of a dense, pointwise matrix.
* One may request the following subsets:
*
* - all of the eigenvalues: ALL
* - the largest negative real part: MOST_NEG_REAL_PART
* - the largest positive real part: MOST_POS_REAL_PART
* - the largest imaginary part: LARGEST_IMAG_PART
* - the largest negative real part: LEAST_NEG_REAL_PART
* - the largest positive real part: LEAST_POS_REAL_PART
* - the largest imaginary part: SMALLEST_IMAG_PART
* - the largest magnitude: SMALLEST_MAG
* - the largest magnitude: SPECTRAL_RADIUS or LARGEST_MAG
* - the condition number: CONDITION_NUMBER
*
* If requesting the largest of any part or magnitude, the answer will be bounded
* by zero on one side. For instance, if all the eigenvalues are negative, then the
* largest positive real part will be zero - not the 'least negative' value.
*
* The enumeration is scoped by Expr::EigenvaluesExpr<FieldT>::Builder.
* This means if you make a typedef for Expr::EigenvaluesExpr<FieldT>::Builder, as
* is commonly done to register expressions to a factory, then you can use that
* typedef to scope the eigenvalue request.
*/
template< typename FieldT >
class EigenvalueExpression : public Expr::Expression<FieldT>
{
public:
struct Builder : public Expr::ExpressionBuilder
{
public:
enum Request
{
ALL,
MOST_NEG_REAL_PART,
MOST_POS_REAL_PART,
LEAST_NEG_REAL_PART,
LEAST_POS_REAL_PART,
LARGEST_IMAG_PART,
SMALLEST_IMAG_PART,
LARGEST_MAG,
SMALLEST_MAG,
SPECTRAL_RADIUS,
CONDITION_NUMBER
};
private:
const boost::shared_ptr<Expr::matrix::AssemblerBase<FieldT> > assembler_;
const int nrows_;
const Request request_;
public:
/**
* \brief build an eigenvalues expression to compute all of the eigenvalues
* \param realTags the tags for the resultant real parts of eigenvalues
* \param imagTags the tags for the resultant imag parts of eigenvalues
* \param assembler the matrix assembler
* \param nrows the number of rows in the matrix
*
* The number of rows must match the size of the lists of tags.
* This is checked in debug.
*/
Builder( const Expr::TagList& realTags,
const Expr::TagList& imagTags,
const boost::shared_ptr<Expr::matrix::AssemblerBase<FieldT> > assembler,
const int nrows )
: Expr::ExpressionBuilder( union_vectors( realTags, imagTags ) ),
assembler_( assembler ),
nrows_( nrows ),
request_( ALL )
{
assert( nrows_ == realTags.size() );
assert( nrows_ == imagTags.size() );
}
/**
* \brief build an eigenvalues expression to compute a single eigenvalue/norm
* \param resultTag the tag of the eigenvalue/norm field
* \param assembler the matrix assembler
* \param nrows the number of rows in the matrix
* \param request the type of eigenvalue/norm requested
*/
Builder( const Expr::Tag& resultTag,
const boost::shared_ptr<Expr::matrix::AssemblerBase<FieldT> > assembler,
const int nrows,
const Request request )
: Expr::ExpressionBuilder( resultTag ),
assembler_( assembler ),
nrows_( nrows ),
request_( request )
{}
~Builder(){}
Expr::ExpressionBase* build() const{
return new EigenvalueExpression<FieldT>( assembler_, nrows_, request_ );
}
};
private:
const boost::shared_ptr<Expr::matrix::AssemblerBase<FieldT> > assembler_;
const int nrows_;
const typename Builder::Request request_;
EigenvalueExpression( const boost::shared_ptr<Expr::matrix::AssemblerBase<FieldT> > assembler,
const int nvars,
const typename Builder::Request request )
: Expr::Expression<FieldT>(),
assembler_( assembler ),
nrows_( nvars ),
request_( request )
{
this->set_gpu_runnable(true);
assembler_->create_all_field_requests( *this );
}
public:
void evaluate()
{
using namespace SpatialOps;
typename Expr::Expression<FieldT>::ValVec& eigs = this->get_value_vec();
typedef std::vector<SpatialOps::SpatFldPtr<FieldT> > SpatFldPtrVctr;
SpatFldPtrVctr realPartPtrs, imagPartPtrs, matrixPtrs;
for( int i=0; i<nrows_; ++i ){
realPartPtrs.push_back( SpatialOps::SpatialFieldStore::get<FieldT>( *eigs[0] ) );
imagPartPtrs.push_back( SpatialOps::SpatialFieldStore::get<FieldT>( *eigs[0] ) );
for( int j=0; j<nrows_; ++j ){
matrixPtrs.push_back( SpatialOps::SpatialFieldStore::get<FieldT>( *eigs[0] ) );
}
}
SpatialOps::FieldMatrix<FieldT> matrix( matrixPtrs );
for( Expr::matrix::OrdinalType rowIdx=0; rowIdx < nrows_; ++rowIdx ){
SpatialOps::FieldVector<FieldT> row( matrix.row( rowIdx ) );
assembler_->assemble( row, rowIdx, Expr::matrix::Place() );
}
SpatialOps::FieldVector<FieldT> realPart( realPartPtrs );
SpatialOps::FieldVector<FieldT> imagPart( imagPartPtrs );
matrix.eigenvalues( realPart, imagPart );
if( request_ == Builder::ALL ){
typename Expr::Expression<FieldT>::ValVec& eigs = this->get_value_vec();
for( int i=0; i<nrows_; ++i ){
*eigs[i] <<= realPart(i);
*eigs[nrows_+i] <<= imagPart(i);
}
}
else{
const double largeNumber = std::numeric_limits<double>::max();
SpatialOps::SpatFldPtr<FieldT> smallestPtr = SpatialOps::SpatialFieldStore::get<FieldT>( *eigs[0] );
FieldT& result = this->value();
switch( request_ ){
case Builder::MOST_NEG_REAL_PART:
result <<= 0.0;
for( int i=0; i<nrows_; ++i ){
result <<= min( result, min( realPart(i), 0.0 ) );
}
break;
case Builder::MOST_POS_REAL_PART:
result <<= 0.0;
for( int i=0; i<nrows_; ++i ){
result <<= max( result, max( realPart(i), 0.0 ) );
}
break;
case Builder::LEAST_NEG_REAL_PART:
result <<= -largeNumber;
for( int i=0; i<nrows_; ++i ){
result <<= max( result, cond( realPart(i) > 0.0, -largeNumber )( realPart(i) ) );
}
break;
case Builder::LEAST_POS_REAL_PART:
result <<= largeNumber;
for( int i=0; i<nrows_; ++i ){
result <<= min( result, cond( realPart(i) < 0.0, largeNumber )( realPart(i) ) );
}
break;
case Builder::LARGEST_IMAG_PART:
result <<= 0.0;
for( int i=0; i<nrows_; ++i ){
result <<= max( result, abs( imagPart(i) ) );
}
break;
case Builder::SMALLEST_IMAG_PART:
result <<= largeNumber;
for( int i=0; i<nrows_; ++i ){
result <<= min( result, abs( imagPart(i) ) );
}
break;
case Builder::SMALLEST_MAG:
result <<= largeNumber;
for( int i=0; i<nrows_; ++i ){
result <<= min( result, realPart(i) * realPart(i) + imagPart(i) * imagPart(i) );
}
result <<= sqrt( result );
break;
case Builder::SPECTRAL_RADIUS:
case Builder::LARGEST_MAG:
result <<= 0.0;
for( int i=0; i<nrows_; ++i ){
result <<= max( result, realPart(i) * realPart(i) + imagPart(i) + imagPart(i) );
}
result <<= sqrt( result );
break;
case Builder::CONDITION_NUMBER:
result <<= 0.0;
*smallestPtr <<= largeNumber;
for( int i=0; i<nrows_; ++i ){
result <<= max( result, realPart(i) * realPart(i) + imagPart(i) * imagPart(i) );
*smallestPtr <<= min( *smallestPtr, realPart(i) * realPart(i) + imagPart(i) * imagPart(i) );
}
result <<= sqrt( result ) / sqrt( *smallestPtr );
break;
default:
break;
}
}
}
};
}
#endif /* EIGENVALUEEXPR_H_ */
| 35.460208 | 108 | 0.604899 | [
"vector"
] |
1b862741903db8fb0f1265d79cca9b394ffdf0f8 | 5,941 | h | C | Samples/Win7Samples/winbase/FSRM/SampleTextBasedClassifier/CPP/FsrmSampleClassifier.h | windows-development/Windows-classic-samples | 96f883e4c900948e39660ec14a200a5164a3c7b7 | [
"MIT"
] | 8 | 2017-04-30T17:38:27.000Z | 2021-11-29T00:59:03.000Z | Samples/Win7Samples/winbase/FSRM/SampleTextBasedClassifier/CPP/FsrmSampleClassifier.h | TomeSq/Windows-classic-samples | 96f883e4c900948e39660ec14a200a5164a3c7b7 | [
"MIT"
] | null | null | null | Samples/Win7Samples/winbase/FSRM/SampleTextBasedClassifier/CPP/FsrmSampleClassifier.h | TomeSq/Windows-classic-samples | 96f883e4c900948e39660ec14a200a5164a3c7b7 | [
"MIT"
] | 2 | 2020-08-11T13:21:49.000Z | 2021-09-01T10:41:51.000Z | // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved
// FsrmSampleClassifier.h : Declaration of the CFsrmSampleClassifier
#pragma once
#include "resource.h" // main symbols
#include "FsrmSampleClassificationModule.h"
#include <map>
#include <string>
#include <algorithm>
#include <fsrmpipeline.h>
#include <fsrmtlb.h>
using namespace std;
#if defined(_WIN32_WCE) && !defined(_CE_DCOM) && !defined(_CE_ALLOW_SINGLE_THREADED_OBJECTS_IN_MTA)
#error "Single-threaded COM objects are not properly supported on Windows CE platform, such as the Windows Mobile platforms that do not include full DCOM support. Define _CE_ALLOW_SINGLE_THREADED_OBJECTS_IN_MTA to force ATL to support creating single-thread COM object's and allow use of it's single-threaded COM object implementations. The threading model in your rgs file was set to 'Free' as that is the only threading model supported in non DCOM Windows CE platforms."
#endif
// Parameters are passed to the classifier in key value pairs
// You can set the parameters in the Classification Rule Properties UI
// Go to the Classification Tab, and click on Advanced, then go to Additional Classification Parameters
// You can enter the key/value pairs in the data grid control
// This paramter specifies the file name to look for
const WCHAR g_wszFileNameContainsKey[] = L"filenamecontains";
// This parameter specifies the string in the content of the files to search for
const WCHAR g_wszFileContentContainsKey[] = L"filecontentcontains";
/*++
class CFsrmClassificationRule
Description:
This is a container class for an Fsrm classification rule's property/value/paramter.
--*/
class CFsrmSampleClassificationRule
{
public:
// The classification property's name
CComBSTR m_strPropName;
// The value to set for the classification property
CComBSTR m_strPropValue;
// The string to search for in the file's name
CComBSTR m_strFileNameContains;
// The string to search for in the file's contents
CComBSTR m_strFileContentContains;
CFsrmSampleClassificationRule(
)
{
}
CFsrmSampleClassificationRule(
LPCWSTR pwszPropName,
LPCWSTR pwszPropValue,
LPCWSTR pwszFileNameContains,
LPCWSTR pwszFileContentContains
)
{
m_strPropName = pwszPropName;
m_strPropValue = pwszPropValue;
m_strFileNameContains = pwszFileNameContains;
m_strFileContentContains = pwszFileContentContains;
}
};
// The classification rule is identified by a GUID
typedef GUID FSRM_OBJECT_ID;
// A comparison operator for use in the lookup map for classification rules
inline bool operator<(FSRM_OBJECT_ID guid1, FSRM_OBJECT_ID guid2)
{
return memcmp(&guid1, &guid2, sizeof(FSRM_OBJECT_ID)) < 0;
}
// creating a std map to store <rule id, rule's property/value pair> pairs
// The key is a guid and needs a comparison operator defined
typedef std::map < FSRM_OBJECT_ID, CFsrmSampleClassificationRule > FsrmClassificationRulesMap;
/*++
class CFsrmSampleClassifier
Description:
This is the ATL wizard added class for the ATL object.
It implements the IFsrmClassifierModuleImplementation interface methods.
--*/
class ATL_NO_VTABLE CFsrmSampleClassifier :
public CComObjectRootEx<CComMultiThreadModel>,
public CComCoClass<CFsrmSampleClassifier, &CLSID_FsrmSampleClassifier>,
public IDispatchImpl<IFsrmClassifierModuleImplementation, &__uuidof(IFsrmClassifierModuleImplementation), &LIBID_FsrmLib, /* wMajor = */ 1>
{
public:
CFsrmSampleClassifier(
)
{
}
DECLARE_GET_CONTROLLING_UNKNOWN()
DECLARE_REGISTRY_RESOURCEID(IDR_FSRMSAMPLECLASSIFIER)
DECLARE_NOT_AGGREGATABLE(CFsrmSampleClassifier)
BEGIN_COM_MAP(CFsrmSampleClassifier)
COM_INTERFACE_ENTRY(IFsrmClassifierModuleImplementation)
COM_INTERFACE_ENTRY(IFsrmPipelineModuleImplementation)
COM_INTERFACE_ENTRY(IDispatch)
END_COM_MAP()
DECLARE_PROTECT_FINAL_CONSTRUCT()
HRESULT FinalConstruct(
)
{
return S_OK;
}
void FinalRelease(
)
{
}
public:
public:
// IFsrmClassifierModuleImplementation Methods
public:
STDMETHOD(get_LastModified)(
VARIANT * LastModified
);
STDMETHOD(UseRulesAndDefinitions)(
IFsrmCollection * Rules,
IFsrmCollection * propertyDefinitions
);
STDMETHOD(OnBeginFile)(
IFsrmPropertyBag * propertyBag,
SAFEARRAY *psaRuleIds
);
STDMETHOD(DoesPropertyValueApply)(
BSTR property,
BSTR Value,
VARIANT_BOOL * applyValue,
GUID idRule,
GUID idPropDef
);
STDMETHOD(GetPropertyValueToApply)(
BSTR property,
BSTR * Value,
GUID idRule,
GUID idPropDef
);
STDMETHOD(OnEndFile)(
);
// IFsrmPipelineModuleImplementation Methods
public:
STDMETHOD(OnLoad)(
IFsrmPipelineModuleDefinition * moduleDefinition,
IFsrmPipelineModuleConnector * * moduleConnector
);
STDMETHOD(OnUnload)(
);
private:
// to hold a reference to the Fsrm pipeline module
CComPtr<IFsrmPipelineModuleDefinition> m_spDefinition;
// map to hold all classification rules' property/value pairs
FsrmClassificationRulesMap m_mapFsrmClassificationRules;
// save a reference to the current property bag
CComPtr<IFsrmPropertyBag> m_spCurrentPropertyBag;
private:
// This method searches the filename or the content of the file
// for the parameters specified in the classification rule's parameter section
HRESULT
NameOrContentContains(
LPCWSTR szFileNameContains,
LPCWSTR szFileContentContains,
VARIANT_BOOL * bResult
);
};
OBJECT_ENTRY_AUTO(__uuidof(FsrmSampleClassifier), CFsrmSampleClassifier)
| 27.37788 | 473 | 0.752904 | [
"object",
"model"
] |
1b89e57c3469d119e89a1af5966d78b8db1212ab | 1,624 | h | C | Src/userplans.h | kingold5/Timer | df506acd5e8541d4ac7ef1dc49166d3d3801af6f | [
"MIT"
] | 1 | 2020-07-02T20:45:53.000Z | 2020-07-02T20:45:53.000Z | Src/userplans.h | kingold5/Timer | df506acd5e8541d4ac7ef1dc49166d3d3801af6f | [
"MIT"
] | null | null | null | Src/userplans.h | kingold5/Timer | df506acd5e8541d4ac7ef1dc49166d3d3801af6f | [
"MIT"
] | null | null | null | #ifndef USERPLANS_H
#define USERPLANS_H
#include <QDialog>
#include <QTableView>
#include <QDomDocument>
#include "userprojectmodel.h"
#include "showtimer.h"
#include "uisingleplan.h"
#include "database.hpp"
namespace Ui {
class UserPlans;
}
class UserPlans : public QDialog
{
Q_OBJECT
public:
explicit UserPlans(DataBase *pdata, QWidget *parent = nullptr);
~UserPlans();
public slots:
void on_pushButtonRun_clicked();
void on_pushButtonSave_clicked();
void on_pushButtonCancel_clicked();
void on_pushButtonDelete_clicked();
void update(const QString &projectName, const QString &timeLeft);
void renderProgress();
void renderProgressByIdx(int i);
signals:
void update(const QString &planName, const QString &planTime,
const int &importance, const QString &planDeadline,
const QString &description);
private:
Ui::UserPlans *ui;
DataBase *data;
QDomDocument docRef;
UserProjectModel *model;
QString fileName;
ShowTimer *showtimer;
uiSinglePlan *newPlan;
bool needEdit;
QDomElement elementToEdit;
private slots:
void on_pushButtonAdd_clicked();
void on_pushButtonEdit_clicked();
void submitData(const QString &planName, const QString &planTime,
const int &importance, const QString &planDeadline,
const QString &description);
void editSinglePlan(const QString &planName, const QString &planTime,
const int &importance, const QString &planDeadline,
const QString &description);
};
#endif // USERPLANS_H
| 26.622951 | 75 | 0.692118 | [
"model"
] |
1b8a56f946e8a1616011713911cbd0974892e04f | 3,109 | c | C | model/networking_v1beta1_ingress_backend.c | ityuhui/client-c | 1d30380d7ba0fe9b5e97626e0f7507be4ce8f96d | [
"curl",
"Apache-2.0"
] | null | null | null | model/networking_v1beta1_ingress_backend.c | ityuhui/client-c | 1d30380d7ba0fe9b5e97626e0f7507be4ce8f96d | [
"curl",
"Apache-2.0"
] | null | null | null | model/networking_v1beta1_ingress_backend.c | ityuhui/client-c | 1d30380d7ba0fe9b5e97626e0f7507be4ce8f96d | [
"curl",
"Apache-2.0"
] | null | null | null | #include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "networking_v1beta1_ingress_backend.h"
networking_v1beta1_ingress_backend_t *networking_v1beta1_ingress_backend_create(
char *serviceName,
object_t *servicePort
) {
networking_v1beta1_ingress_backend_t *networking_v1beta1_ingress_backend_local_var = malloc(sizeof(networking_v1beta1_ingress_backend_t));
if (!networking_v1beta1_ingress_backend_local_var) {
return NULL;
}
networking_v1beta1_ingress_backend_local_var->serviceName = serviceName;
networking_v1beta1_ingress_backend_local_var->servicePort = servicePort;
return networking_v1beta1_ingress_backend_local_var;
}
void networking_v1beta1_ingress_backend_free(networking_v1beta1_ingress_backend_t *networking_v1beta1_ingress_backend) {
listEntry_t *listEntry;
free(networking_v1beta1_ingress_backend->serviceName);
object_free(networking_v1beta1_ingress_backend->servicePort);
free(networking_v1beta1_ingress_backend);
}
cJSON *networking_v1beta1_ingress_backend_convertToJSON(networking_v1beta1_ingress_backend_t *networking_v1beta1_ingress_backend) {
cJSON *item = cJSON_CreateObject();
// networking_v1beta1_ingress_backend->serviceName
if (!networking_v1beta1_ingress_backend->serviceName) {
goto fail;
}
if(cJSON_AddStringToObject(item, "serviceName", networking_v1beta1_ingress_backend->serviceName) == NULL) {
goto fail; //String
}
// networking_v1beta1_ingress_backend->servicePort
if (!networking_v1beta1_ingress_backend->servicePort) {
goto fail;
}
cJSON *servicePort_object = object_convertToJSON(networking_v1beta1_ingress_backend->servicePort);
if(servicePort_object == NULL) {
goto fail; //model
}
cJSON_AddItemToObject(item, "servicePort", servicePort_object);
if(item->child == NULL) {
goto fail;
}
return item;
fail:
if (item) {
cJSON_Delete(item);
}
return NULL;
}
networking_v1beta1_ingress_backend_t *networking_v1beta1_ingress_backend_parseFromJSON(cJSON *networking_v1beta1_ingress_backendJSON){
networking_v1beta1_ingress_backend_t *networking_v1beta1_ingress_backend_local_var = NULL;
// networking_v1beta1_ingress_backend->serviceName
cJSON *serviceName = cJSON_GetObjectItemCaseSensitive(networking_v1beta1_ingress_backendJSON, "serviceName");
if (!serviceName) {
goto end;
}
if(!cJSON_IsString(serviceName))
{
goto end; //String
}
// networking_v1beta1_ingress_backend->servicePort
cJSON *servicePort = cJSON_GetObjectItemCaseSensitive(networking_v1beta1_ingress_backendJSON, "servicePort");
if (!servicePort) {
goto end;
}
object_t *servicePort_local_object = NULL;
servicePort_local_object = object_parseFromJSON(servicePort); //object
networking_v1beta1_ingress_backend_local_var = networking_v1beta1_ingress_backend_create (
strdup(serviceName->valuestring),
servicePort_local_object
);
return networking_v1beta1_ingress_backend_local_var;
end:
return NULL;
}
| 30.480392 | 139 | 0.774847 | [
"object",
"model"
] |
1b8b944a8dd6bea50854379f6a9b594b72a069f3 | 3,137 | h | C | PWGLF/RESONANCES/extra/AliRsnf0f2Task.h | maroozm/AliPhysics | 22ec256928cfdf8f800e05bfc1a6e124d90b6eaf | [
"BSD-3-Clause"
] | 114 | 2017-03-03T09:12:23.000Z | 2022-03-03T20:29:42.000Z | PWGLF/RESONANCES/extra/AliRsnf0f2Task.h | maroozm/AliPhysics | 22ec256928cfdf8f800e05bfc1a6e124d90b6eaf | [
"BSD-3-Clause"
] | 19,637 | 2017-01-16T12:34:41.000Z | 2022-03-31T22:02:40.000Z | PWGLF/RESONANCES/extra/AliRsnf0f2Task.h | maroozm/AliPhysics | 22ec256928cfdf8f800e05bfc1a6e124d90b6eaf | [
"BSD-3-Clause"
] | 1,021 | 2016-07-14T22:41:16.000Z | 2022-03-31T05:15:51.000Z | /* Copyright(c) 1998-2014, ALICE Experiment at CERN, All rights reserved. *
* See cxx source for full Copyright notice */
// Short comment describing what this class does needed!
//===========================================================
// Dummy comment, should be replaced by a real one
//===========================================================
#ifndef ALIRSNF0F2TASK_H
#define ALIRSNF0F2TASK_H
#include "AliAnalysisTaskSE.h"
#include "AliTriggerAnalysis.h"
#include "AliESDtrackCuts.h"
#include "AliESDEvent.h"
#include "AliAODEvent.h"
#include "AliPIDResponse.h"
class AliRsnf0f2RunTable {
public:
enum {kPP,kPA,kAA,kUnknownCollType};
AliRsnf0f2RunTable();
AliRsnf0f2RunTable(Int_t runnumber);
~AliRsnf0f2RunTable();
Bool_t IsPP(){
return fCollisionType==kPP;
}
Bool_t IsPA(){
return fCollisionType==kPA;
}
Bool_t IsAA(){
return fCollisionType==kAA;
}
private:
Int_t fCollisionType; //! Is proton-proton collisions?
};
class AliRsnf0f2Task : public AliAnalysisTaskSE {
public:
enum { kPion=0, kKaon, kProton, kElectron, kUnknown};
enum { kSD=0, kDD, kND, kCD, kAllProc};
//PN = unlike sign, PP and NN are like signs
enum { kPN=0, kPP, kNN, kAllSign}; //P=Positive charge, N=Negative
AliRsnf0f2Task();
AliRsnf0f2Task
(
const char *name
, const char *option
);
AliRsnf0f2Task
(
const AliRsnf0f2Task& ap
);
AliRsnf0f2Task& operator =
(
const AliRsnf0f2Task& ap
);
~AliRsnf0f2Task();
virtual void UserCreateOutputObjects();
virtual void UserExec(Option_t *);
virtual void FinishTaskOutput();
virtual void Terminate(Option_t *);
void SetOption(char * option) {fOption = option;}
Int_t GetPID(AliPIDResponse *pid, const AliVTrack *trk);
Bool_t GoodTracksSelection();
void FillTracks();
Bool_t FindPtBin(Double_t pt, UInt_t & bin);
Bool_t FindCentBin(Double_t cent, UInt_t & bin);
private:
TString fOption;
TList* fOutput; //!
AliTriggerAnalysis* fTrigger; //!
AliESDtrackCuts* fTrackCuts; //!
AliESDEvent* fEsd; //!
AliAODEvent* fAod; //!
Bool_t IsFirstEvent;
AliRsnf0f2RunTable* fRunTable; //!
Double_t fCent;
std::vector < UInt_t > goodtrackindices; //!
AliPIDResponse *fPIDResponse; //!
TH1D *fEventNumbers; //!
TH2D *fPhiEta; //!
//Histograms below are main
std::vector< std::vector< TH2D* > > fMass2D; //! signbins, centbins
ClassDef(AliRsnf0f2Task, 1);
};
#endif
| 29.046296 | 75 | 0.517373 | [
"vector"
] |
1b8f9c55bd2c8c4c8aa9bcab1f80c1b1296ae0ec | 5,884 | h | C | TestVectors/Test_Aes.h | FlyingRaijinMinato/LockdownSSL | 46f36f6add10448a6d381dd7483b96d1d3b5d004 | [
"MIT"
] | null | null | null | TestVectors/Test_Aes.h | FlyingRaijinMinato/LockdownSSL | 46f36f6add10448a6d381dd7483b96d1d3b5d004 | [
"MIT"
] | 1 | 2021-03-04T09:29:19.000Z | 2021-03-11T17:49:14.000Z | TestVectors/Test_Aes.h | FlyingRaijinMinato/LockdownSSL | 46f36f6add10448a6d381dd7483b96d1d3b5d004 | [
"MIT"
] | null | null | null | #ifndef LOCKDOWNSSL_AES_TEST
#define LOCKDOWNSSL_AES_TEST
#include <iostream>
#include "Aes.h"
#include "Modes.h"
namespace LockdownSSL
{
namespace Test
{
void ecb_aes128_test()
{
std::vector<byte> plaintext
{
0x6B,0xC1,0xBE,0xE2,0x2E,0x40,0x9F,0x96,0xE9,0x3D,
0x7E,0x11,0x73,0x93,0x17,0x2A,0xAE,0x2D,0x8A,0x57,
0x1E,0x03,0xAC,0x9C,0x9E,0xB7,0x6F,0xAC,0x45,0xAF,
0x8E,0x51,0x30,0xC8,0x1C,0x46,0xA3,0x5C,0xE4,0x11,
0xE5,0xFB,0xC1,0x19,0x1A,0x0A,0x52,0xEF,0xF6,0x9F,
0x24,0x45,0xDF,0x4F,0x9B,0x17,0xAD,0x2B,0x41,0x7B,
0xE6,0x6C,0x37,0x10,
};
std::vector<byte> ciphertext
{
0x3A,0xD7,0x7B,0xB4,0x0D,0x7A,0x36,0x60,0xA8,0x9E,0xCA,0xF3,
0x24,0x66,0xEF,0x97,0xF5,0xD3,0xD5,0x85,0x03,0xB9,0x69,0x9D,
0xE7,0x85,0x89,0x5A,0x96,0xFD,0xBA,0xAF,0x43,0xB1,0xCD,0x7F,
0x59,0x8E,0xCE,0x23,0x88,0x1B,0x00,0xE3,0xED,0x03,0x06,0x88,
0x7B,0x0C,0x78,0x5E,0x27,0xE8,0xAD,0x3F,0x82,0x23,0x20,0x71,
0x04,0x72,0x5D,0xD4,
};
byte key[16] = { 0x2B,0x7E,0x15,0x16,0x28,0xAE,0xD2,0xA6,0xAB,0xF7,0x15,0x88,0x09,0xCF,0x4F,0x3C, };
auto aes_instance = LockdownSSL::Cipher::Aes::getInstance_128(key);
std::vector<byte> encrypted_output = LockdownSSL::EncryptionModes::ECB::encrypt(aes_instance, plaintext);
for (word32 i = 0; i < ciphertext.size(); i++)
{
if (encrypted_output[i] != ciphertext[i])
{
std::cout << "Aes128 ECB encryption failed at index " << i << std::endl;
std::cin.get();
return;
}
}
std::cout << "Aes128 ECB encryption passed!" << std::endl;
std::vector<byte> decrypted_output = LockdownSSL::EncryptionModes::ECB::decrypt(aes_instance, ciphertext);
for (word32 i = 0; i < plaintext.size(); i++)
{
if (decrypted_output[i] != plaintext[i])
{
std::cout << "Aes128 ECB decryption failed at index " << i << std::endl;
std::cin.get();
return;
}
}
std::cout << "Aes128 ECB decryption passed!" << std::endl;
}
void ecb_aes192_test()
{
std::vector<byte> plaintext
{
0x6B,0xC1,0xBE,0xE2,0x2E,0x40,0x9F,0x96,0xE9,0x3D,
0x7E,0x11,0x73,0x93,0x17,0x2A,0xAE,0x2D,0x8A,0x57,
0x1E,0x03,0xAC,0x9C,0x9E,0xB7,0x6F,0xAC,0x45,0xAF,
0x8E,0x51,0x30,0xC8,0x1C,0x46,0xA3,0x5C,0xE4,0x11,
0xE5,0xFB,0xC1,0x19,0x1A,0x0A,0x52,0xEF,0xF6,0x9F,
0x24,0x45,0xDF,0x4F,0x9B,0x17,0xAD,0x2B,0x41,0x7B,
0xE6,0x6C,0x37,0x10,
};
std::vector<byte> ciphertext
{
0xBD,0x33,0x4F,0x1D,0x6E,0x45,0xF2,0x5F,0xF7,0x12,0xA2,
0x14,0x57,0x1F,0xA5,0xCC,0x97,0x41,0x04,0x84,0x6D,0x0A,
0xD3,0xAD,0x77,0x34,0xEC,0xB3,0xEC,0xEE,0x4E,0xEF,0xEF,
0x7A,0xFD,0x22,0x70,0xE2,0xE6,0x0A,0xDC,0xE0,0xBA,0x2F,
0xAC,0xE6,0x44,0x4E,0x9A,0x4B,0x41,0xBA,0x73,0x8D,0x6C,
0x72,0xFB,0x16,0x69,0x16,0x03,0xC1,0x8E,0x0E,
};
byte key[24] = { 0x8E,0x73,0xB0,0xF7,0xDA,0x0E,0x64,0x52,0xC8,0x10,0xF3,0x2B,0x80,0x90,0x79,0xE5,0x62,0xF8,0xEA,0xD2,0x52,0x2C,0x6B,0x7B, };
auto aes_instance = LockdownSSL::Cipher::Aes::getInstance_192(key);
std::vector<byte> encrypted_output = LockdownSSL::EncryptionModes::ECB::encrypt(aes_instance, plaintext);
for (word32 i = 0; i < ciphertext.size(); i++)
{
if (encrypted_output[i] != ciphertext[i])
{
std::cout << "Aes192 ECB encryption failed at index " << i << std::endl;
std::cin.get();
return;
}
}
std::cout << "Aes192 ECB encryption passed!" << std::endl;
std::vector<byte> decrypted_output = LockdownSSL::EncryptionModes::ECB::decrypt(aes_instance, ciphertext);
for (word32 i = 0; i < plaintext.size(); i++)
{
if (decrypted_output[i] != plaintext[i])
{
std::cout << "Aes192 ECB decryption failed at index " << i << std::endl;
std::cin.get();
return;
}
}
std::cout << "Aes192 ECB decryption passed!" << std::endl;
}
void ecb_aes256_test()
{
std::vector<byte> plaintext
{
0x6B,0xC1,0xBE,0xE2,0x2E,0x40,0x9F,0x96,0xE9,0x3D,
0x7E,0x11,0x73,0x93,0x17,0x2A,0xAE,0x2D,0x8A,0x57,
0x1E,0x03,0xAC,0x9C,0x9E,0xB7,0x6F,0xAC,0x45,0xAF,
0x8E,0x51,0x30,0xC8,0x1C,0x46,0xA3,0x5C,0xE4,0x11,
0xE5,0xFB,0xC1,0x19,0x1A,0x0A,0x52,0xEF,0xF6,0x9F,
0x24,0x45,0xDF,0x4F,0x9B,0x17,0xAD,0x2B,0x41,0x7B,
0xE6,0x6C,0x37,0x10,
};
std::vector<byte> ciphertext
{
0xF3,0xEE,0xD1,0xBD,0xB5,0xD2,0xA0,0x3C,0x06,0x4B,0x5A,
0x7E,0x3D,0xB1,0x81,0xF8,0x59,0x1C,0xCB,0x10,0xD4,0x10,
0xED,0x26,0xDC,0x5B,0xA7,0x4A,0x31,0x36,0x28,0x70,0xB6,
0xED,0x21,0xB9,0x9C,0xA6,0xF4,0xF9,0xF1,0x53,0xE7,0xB1,
0xBE,0xAF,0xED,0x1D,0x23,0x30,0x4B,0x7A,0x39,0xF9,0xF3,
0xFF,0x06,0x7D,0x8D,0x8F,0x9E,0x24,0xEC,0xC7,
};
byte key[32] = { 0x60,0x3D,0xEB,0x10,0x15,0xCA,0x71,0xBE,0x2B,0x73,0xAE,0xF0,0x85,0x7D,0x77,0x81,0x1F,0x35,0x2C,0x07,0x3B,0x61,0x08,0xD7,0x2D,0x98,0x10,0xA3,0x09,0x14,0xDF,0xF4, };
auto aes_instance = LockdownSSL::Cipher::Aes::getInstance_256(key);
std::vector<byte> encrypted_output = LockdownSSL::EncryptionModes::ECB::encrypt(aes_instance, plaintext);
for (word32 i = 0; i < ciphertext.size(); i++)
{
if (encrypted_output[i] != ciphertext[i])
{
std::cout << "Aes256 ECB encryption failed at index " << i << std::endl;
std::cin.get();
return;
}
}
std::cout << "Aes256 ECB encryption passed!" << std::endl;
std::vector<byte> decrypted_output = LockdownSSL::EncryptionModes::ECB::decrypt(aes_instance, ciphertext);
for (word32 i = 0; i < plaintext.size(); i++)
{
if (decrypted_output[i] != plaintext[i])
{
std::cout << "Aes256 ECB decryption failed at index " << i << std::endl;
std::cin.get();
return;
}
}
std::cout << "Aes256 ECB decryption passed!" << std::endl;
}
}
}
#endif | 33.622857 | 184 | 0.644969 | [
"vector"
] |
23e821f1d0a1435a5bcd9c927a84e36ab722495a | 1,346 | h | C | modules/DummyBoundingBoxes/src/stubs/Class_DummyBoundingBoxes_output_ObjectData_detections_boundingBox_Default.h | ConnectedVision/ConnectedVision | 210e49205ca50f73584178b6cedb298a74cea798 | [
"MIT"
] | 3 | 2017-08-12T18:14:00.000Z | 2018-11-19T09:15:35.000Z | modules/DummyBoundingBoxes/src/stubs/Class_DummyBoundingBoxes_output_ObjectData_detections_boundingBox_Default.h | ConnectedVision/ConnectedVision | 210e49205ca50f73584178b6cedb298a74cea798 | [
"MIT"
] | null | null | null | modules/DummyBoundingBoxes/src/stubs/Class_DummyBoundingBoxes_output_ObjectData_detections_boundingBox_Default.h | ConnectedVision/ConnectedVision | 210e49205ca50f73584178b6cedb298a74cea798 | [
"MIT"
] | 1 | 2018-11-09T15:57:13.000Z | 2018-11-09T15:57:13.000Z | // auto-generated header by CodeFromTemplate - Connected Vision - https://github.com/ConnectedVision
// CodeFromTemplate Version: 0.3 alpha
// stubs/Class_DummyBoundingBoxes_output_ObjectData_detections_boundingBox_Default.h
// This file contains the business logic.
// NEVER TOUCH this file!
#ifndef Class_DummyBoundingBoxes_output_ObjectData_detections_boundingBox_default
#define Class_DummyBoundingBoxes_output_ObjectData_detections_boundingBox_default
// --> Do NOT EDIT <--
namespace ConnectedVision {
namespace Module {
namespace DummyBoundingBoxes {
#ifndef Class_DummyBoundingBoxes_output_ObjectData_detections_boundingBox_extended
/**
* Class_DummyBoundingBoxes_output_ObjectData_detections_boundingBox
*
* module: DummyBoundingBoxes
* description: object meta data
*/
typedef Stub_DummyBoundingBoxes_output_ObjectData_detections_boundingBox Class_DummyBoundingBoxes_output_ObjectData_detections_boundingBox;
typedef boost::shared_ptr<Class_DummyBoundingBoxes_output_ObjectData_detections_boundingBox> Class_DummyBoundingBoxes_output_ObjectData_detections_boundingBox_p;
#endif // Class_DummyBoundingBoxes_output_ObjectData_detections_boundingBox_extended
} // namespace DummyBoundingBoxes
} // namespace Module
} // namespace ConnectedVision
#endif // Class_DummyBoundingBoxes_output_ObjectData_detections_boundingBox_default | 44.866667 | 161 | 0.876672 | [
"object"
] |
23eb6f4200207f41b4903087bf075b1f3f21f871 | 1,174 | h | C | src/PolarSSL++/Sha1Checksum.h | giriko/MCServer | a75fb13f99aff238fcc8c7471919f04e03945e47 | [
"Apache-2.0"
] | 1 | 2021-01-26T16:50:09.000Z | 2021-01-26T16:50:09.000Z | src/PolarSSL++/Sha1Checksum.h | Eliminationzx/cuberite | be916bc7e85843291c5ab8cb4f268bd1daa57b76 | [
"Apache-2.0"
] | null | null | null | src/PolarSSL++/Sha1Checksum.h | Eliminationzx/cuberite | be916bc7e85843291c5ab8cb4f268bd1daa57b76 | [
"Apache-2.0"
] | null | null | null |
// Sha1Checksum.h
// Declares the cSha1Checksum class representing the SHA-1 checksum calculator
#pragma once
#include "polarssl/sha1.h"
/** Calculates a SHA1 checksum for data stream */
class cSha1Checksum
{
public:
typedef Byte Checksum[20]; // The type used for storing the checksum
cSha1Checksum(void);
/** Adds the specified data to the checksum */
void Update(const Byte * a_Data, size_t a_Length);
/** Calculates and returns the final checksum */
void Finalize(Checksum & a_Output);
/** Returns true if the object is accepts more input data, false if Finalize()-d (need to Restart()) */
bool DoesAcceptInput(void) const { return m_DoesAcceptInput; }
/** Converts a raw 160-bit SHA1 digest into a Java Hex representation
According to http://wiki.vg/wiki/index.php?title=Protocol_Encryption&oldid=2802
*/
static void DigestToJava(const Checksum & a_Digest, AString & a_JavaOut);
/** Clears the current context and start a new checksum calculation */
void Restart(void);
protected:
/** True if the object is accepts more input data, false if Finalize()-d (need to Restart()) */
bool m_DoesAcceptInput;
sha1_context m_Sha1;
} ;
| 22.150943 | 104 | 0.73339 | [
"object"
] |
23f30ca8abf93abb1b0f04014ff143966b9b0843 | 4,439 | c | C | libvips-8.11/libvips/arithmetic/statistic.c | MFerrol/Create_Web | 76c8590ffffc6834a13f8efaf5ca7a5829cb1c32 | [
"MIT"
] | 2 | 2020-11-19T04:09:33.000Z | 2020-11-24T04:51:19.000Z | libvips-8.11/libvips/arithmetic/statistic.c | MFerrol/Create_Web | 76c8590ffffc6834a13f8efaf5ca7a5829cb1c32 | [
"MIT"
] | null | null | null | libvips-8.11/libvips/arithmetic/statistic.c | MFerrol/Create_Web | 76c8590ffffc6834a13f8efaf5ca7a5829cb1c32 | [
"MIT"
] | 1 | 2021-01-16T10:36:37.000Z | 2021-01-16T10:36:37.000Z | /* base class for all stats operations
*
* properties:
* - one image in, single value or matrix out
* - output depends on whole of input, ie. we have a sink
*
* 24/8/11
* - from im_avg.c
*/
/*
Copyright (C) 1991-2005 The National Gallery
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA
*/
/*
These files are distributed with VIPS - http://www.vips.ecs.soton.ac.uk
*/
/*
#define VIPS_DEBUG
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif /*HAVE_CONFIG_H*/
#include <vips/intl.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <vips/vips.h>
#include <vips/debug.h>
#include <vips/internal.h>
#include "statistic.h"
G_DEFINE_ABSTRACT_TYPE( VipsStatistic, vips_statistic, VIPS_TYPE_OPERATION );
static void *
vips_statistic_scan_start( VipsImage *in, void *a, void *b )
{
VipsStatistic *statistic = VIPS_STATISTIC( a );
VipsStatisticClass *class = VIPS_STATISTIC_GET_CLASS( statistic );
return( class->start( statistic ) );
}
static int
vips_statistic_scan( VipsRegion *region,
void *seq, void *a, void *b, gboolean *stop )
{
VipsStatistic *statistic = VIPS_STATISTIC( a );
VipsStatisticClass *class = VIPS_STATISTIC_GET_CLASS( statistic );
VipsRect *r = ®ion->valid;
int lsk = VIPS_REGION_LSKIP( region );
int y;
VipsPel *p;
VIPS_DEBUG_MSG( "vips_statistic_scan: %d x %d @ %d x %d\n",
r->width, r->height, r->left, r->top );
p = VIPS_REGION_ADDR( region, r->left, r->top );
for( y = 0; y < r->height; y++ ) {
if( class->scan( statistic,
seq, r->left, r->top + y, p, r->width ) )
return( -1 );
p += lsk;
}
/* If we've requested stop, pass the message on.
*/
if( statistic->stop )
*stop = TRUE;
return( 0 );
}
static int
vips_statistic_scan_stop( void *seq, void *a, void *b )
{
VipsStatistic *statistic = VIPS_STATISTIC( a );
VipsStatisticClass *class = VIPS_STATISTIC_GET_CLASS( statistic );
return( class->stop( statistic, seq ) );
}
static int
vips_statistic_build( VipsObject *object )
{
VipsStatistic *statistic = VIPS_STATISTIC( object );
VipsStatisticClass *sclass = VIPS_STATISTIC_GET_CLASS( statistic );
VipsImage **t = (VipsImage **) vips_object_local_array( object, 2 );
#ifdef DEBUG
printf( "vips_statistic_build: " );
vips_object_print_name( object );
printf( "\n" );
#endif /*DEBUG*/
if( VIPS_OBJECT_CLASS( vips_statistic_parent_class )->build( object ) )
return( -1 );
statistic->ready = statistic->in;
if( vips_image_decode( statistic->ready, &t[0] ) )
return( -1 );
statistic->ready = t[0];
/* If there's a format table, cast the input.
*/
if( sclass->format_table ) {
if( vips_cast( statistic->ready, &t[1],
sclass->format_table[statistic->in->BandFmt], NULL ) )
return( -1 );
statistic->ready = t[1];
}
if( vips_sink( statistic->ready,
vips_statistic_scan_start,
vips_statistic_scan,
vips_statistic_scan_stop,
statistic, NULL ) )
return( -1 );
return( 0 );
}
static void
vips_statistic_class_init( VipsStatisticClass *class )
{
GObjectClass *gobject_class = G_OBJECT_CLASS( class );
VipsObjectClass *vobject_class = VIPS_OBJECT_CLASS( class );
VipsOperationClass *operation_class = VIPS_OPERATION_CLASS( class );
gobject_class->set_property = vips_object_set_property;
gobject_class->get_property = vips_object_get_property;
vobject_class->nickname = "statistic";
vobject_class->description = _( "VIPS statistic operations" );
vobject_class->build = vips_statistic_build;
operation_class->flags = VIPS_OPERATION_SEQUENTIAL;
VIPS_ARG_IMAGE( class, "in", 0,
_( "Input" ),
_( "Input image" ),
VIPS_ARGUMENT_REQUIRED_INPUT,
G_STRUCT_OFFSET( VipsStatistic, in ) );
}
static void
vips_statistic_init( VipsStatistic *statistic )
{
}
| 24.938202 | 77 | 0.70624 | [
"object"
] |
23f55150803e5d7aa39af579b707fb2302b91b3c | 19,399 | c | C | src/rt/nesl/vcode/vstack.c | ghsecuritylab/db-nautilus-fork | 1d6a9fce52ad5284259e0fa50455094758da023c | [
"MIT"
] | null | null | null | src/rt/nesl/vcode/vstack.c | ghsecuritylab/db-nautilus-fork | 1d6a9fce52ad5284259e0fa50455094758da023c | [
"MIT"
] | null | null | null | src/rt/nesl/vcode/vstack.c | ghsecuritylab/db-nautilus-fork | 1d6a9fce52ad5284259e0fa50455094758da023c | [
"MIT"
] | 1 | 2020-03-07T09:46:52.000Z | 2020-03-07T09:46:52.000Z | /*
* Copyright (c) 1992, 1993, 1994, 1995 Carnegie Mellon University
*/
#include "config.h"
#include "vcode.h"
#include "vstack.h"
/* This module is responsible for managing vector memory. The memory
* management algorithm is as follows:
* 1. vector memory is divided up into various sized blocks, which may be
* active or free
* 2. corresponding to each block is a vb structure (of type vb_t)
* 3. these structures are stored in a doubly linked list which preserves
* the order of the blocks in the actual vector memory.
* 4. a set of free lists of unutilized blocks of memory is maintained, with
* each list corresponding to a range of vector sizes (powers of 2)
* 5. when memory is to be allocated, the appropriate free list is searched
* in first-fit manner for a large enough memory block. the required
* memory is allocated from the block, which may then be split into
* two pieces. the unallocated block is put on the appropriate free list.
* 6. reference counting is used to determine when a vector is no longer needed.
* 7. when a vector is freed, the adjacent memory blocks are checked to
* see if they are free. if so, the blocks are merged. free blocks are
* then put on the appropriate free list.
*/
vb_t *vblocks; /* head of list */
vec_p cvl_mem; /* vector memory */
int cvl_mem_size; /* size of vector memory */
#define NBUCKETS 32
vb_t bucket_table[NBUCKETS];
/* a bucket is empty if the next field points back to itself */
#define isempty_bucket(n) (bucket_table[n].fnext == &bucket_table[n])
static vb_t *free_list_init PROTO_((unsigned, vec_p));
static void compact_mem PROTO_((void));
/* scratch_block always points to largest free block of memory */
vb_t *scratch_block;
/* ---------- scratch space functions -------------------------------*/
/* set scratch_block to largest free block of memory */
static void find_scratch PROTO_((void))
{
int i = NBUCKETS - 1;
while ( (i > 0) && isempty_bucket(i))
i--;
if (i == 0) {
_fprintf(stderr, "vinterp: ran out of memory. Rerun with larger -m argument.\n");
vinterp_exit(1);
}
scratch_block = bucket_table[i].fprev; /* last on list */
}
/* make sure that size_needed memory units are available in heap.
* compact if not.
*/
void assert_mem_size_real(size_needed)
int size_needed;
{
assert(size_needed >= 0);
#ifndef SPEEDHACKS
if (size_needed <= scratch_block->size)
return;
#endif
if (garbage_notify) {
_fprintf(stderr, "vinterp: memory compactor: %d units requested, largest available block has size %d\n",
size_needed, scratch_block->size);
}
compact_mem(); /* try to make more room */
if (size_needed > scratch_block->size) {
_fprintf(stderr, "vinterp: ran out of memory. Rerun with larger -m argument.\n");
vinterp_exit(1);
}
}
/* ---------------- vblock constructors and destructors -----------------*/
/* We maintain an array of used vb_t's to avoid excess mallocs and frees. */
static vb_t **vb_free_list = NULL; /* array of available vb */
static int vb_free_max = 0; /* current size of free list */
static int vb_free_avail = 0; /* first empty slot for vb_t* */
#define VB_FREE_INITIAL 16 /* initial number malloc'ed */
/* initialize vb free array */
static void vb_init PROTO_((void))
{
int i;
vb_t *temp = (vb_t *) malloc (VB_FREE_INITIAL * sizeof (vb_t));
vb_free_list = (vb_t **) malloc (VB_FREE_INITIAL * sizeof (vb_t *));
if (temp == NULL || vb_free_list == NULL) {
_fprintf(stderr, "vinterp: couldn't allocate internal structures (vblock list).\n");
vinterp_exit (1);
}
for (i = 0; i < VB_FREE_INITIAL; i ++)
vb_free_list[i] = temp + i;
vb_free_max = VB_FREE_INITIAL;
vb_free_avail = VB_FREE_INITIAL;
}
/* vblock constructor: get vb off free array, or malloc more vb's
*/
static vb_t *new_vb PROTO_((void))
{
if (vb_free_avail <= 0) { /* no more available blocks */
int count; /* get some more */
vb_t *blocks = (vb_t *) malloc(VB_FREE_INITIAL * sizeof(vb_t));
if (blocks == NULL) {
_fprintf(stderr, "vinterp: error allocating internal structures (vb_t).\n");
vinterp_exit (1);
}
/* put new vb's into free table */
assert(vb_free_max >= VB_FREE_INITIAL); /* done in initialization */
for (count = 0; count < VB_FREE_INITIAL; count++) {
vb_free_list[count] = blocks + count;
}
vb_free_avail = VB_FREE_INITIAL;
}
return vb_free_list[--vb_free_avail];
}
/* vblock destructer: return to free-table, making sure table is large enough
*/
static void free_vb PROTO_((vb_t*));
static void free_vb(vb)
vb_t *vb;
{
if (vb_free_avail == vb_free_max) { /* no room in table */
vb_free_max += VB_FREE_INITIAL; /* make room for new ones */
vb_free_list = (vb_t **)realloc(vb_free_list, vb_free_max*sizeof(vb_t*));
if (vb_free_list == NULL) {
_fprintf(stderr, "vinterp: error allocating internal structures (vblock_list).\n");
vinterp_exit (1);
}
}
vb_free_list[vb_free_avail++] = vb; /* put vb on top of list */
return;
}
/* ---------------- vmem initializer -----------------------------------*/
/* Allocate vector memory, set up vblock structures.
* Try to allocate vmemsize number of doubles of vector memory
*/
void vstack_init(vmemlen)
unsigned int vmemlen;
{
int vmem_size = siz_fod((int)vmemlen);
vec_p vmem = alo_foz(vmem_size);
vb_t *vb;
if (vmem == (vec_p) NULL) {
_fprintf(stderr, "vinterp: cannot allocate vector memory of size %u.\n", vmemlen);
_fprintf(stderr, "\trerun with smaller -m argument.\n");
exit(1);
}
cvl_mem = vmem; /* set globals */
cvl_mem_size = vmem_size;
vb_init(); /* initialize vblock structures */
vblocks = new_vb();
vblocks->bprev = vblocks;
vblocks->bnext = vblocks;
vblocks->active = 1; /* don't want to coallesce this! */
vb = free_list_init(cvl_mem_size, cvl_mem); /* chop up memory */
vb->bprev = vblocks; /* link into vblocks structure */
vb->bnext = vblocks;
vblocks->bnext = vb;
vblocks->bprev = vb;
find_scratch();
}
/* ----------------- free list stuff -------------------------------------*/
/* the free list is an array of buckets, each of which is a doubly linked
* list of bucket_items.
*/
/* Given a vector size, return the index of the bucket with which it is
* associated. bucket_size[i] is the maximum size of an item in bucket[i].
* For now, we'll use power of two sized free lists. Other possibilities
* include Fibonacci numbers, or dynamically changing sizes that correspond
* to actual vector usage....
* This code gets called ALOT, so it should be fast. Hence, all the
* SPEEDHACKS mess.
*/
static int get_bucket_num PROTO_((int));
static int get_bucket_num(size)
int size;
{
#ifndef SPEEDHACKS
static const unsigned int const bucket_size[NBUCKETS] = {
0x1, 0x2, 0x4, 0x8,
0x10, 0x20, 0x40, 0x80,
0x100, 0x200, 0x400, 0x800,
0x1000, 0x2000, 0x4000, 0x8000,
0x10000, 0x20000, 0x40000, 0x80000,
0x100000, 0x200000, 0x400000, 0x800000,
0x1000000, 0x2000000, 0x4000000, 0x8000000,
0x10000000, 0x20000000, 0x40000000, 0x80000000,
};
#endif /* SPEEDHACKS */
int answer;
if (size <= 1)
answer = 0;
else {
#ifndef SPEEDHACKS
const unsigned int *b = bucket_size + 1;
while (size > *b)
b++;
answer = b - bucket_size;
#else /* SPEEDHACKS */
/* This hack is ugly, but if we're using power of 2 lists,
* it saves us a factor of two, (more on cray) on average over the above
* loop. The list we want corresponds to the highest set bit in size.
* so, if size = 5 (00101), the ugly stuff returns 2 (bits numbered
* from 0, so we add 1 to get 3, and bucket_size[3] = 8.
* The floating point format should be defined in config.h.
*/
#if cray
/* cray has a single instruction for this !! */
answer = 64 - _ldzero(size); /* position of first 1 bit */
#else /* not-cray */
/* assumes IEEE-754; exponent stored XS127 */
/* cast number to float, this normalizes number; grab exponent */
double d;
unsigned short *s;
int result;
d = size;
s = ((unsigned short *) &d);
#if vax /* D_floating format */
result = ((s[0]>>7)&0xff) - 0x81;
#else
#if FP_LITTLE_ENDIAN
result = ((s[3]>>4)&0x7ff) - 0x3ff;
#else
result = ((s[0]>>4)&0x7ff) - 0x3ff;
#endif
#endif
if (1 << result != size) result += 1; /* don't add for 2^k */
answer = result;
#endif /* cray */
#endif /* SPEEDHACKS */
}
#ifdef BUCKET_DEBUG
_fprintf(stderr, "get_bucket: requested %d; got %d\n", size, bucket_size[answer]);
#endif /* BUCKET_DEBUG */
return answer;
}
/* splice vb out of both the free and vblock lists, and free the vb
*/
static void splice_vb PROTO_((vb_t*));
static void splice_vb(vb)
vb_t *vb;
{
vb_t *vb_prev = vb->bprev; /* do CSE by hand */
vb_t *vb_next = vb->bnext;
vb_next->bprev = vb_prev; /* vblock list */
vb_prev->bnext = vb_next;
vb_prev = vb->fprev;
vb_next = vb->fnext;
vb_next->fprev = vb_prev; /* free list */
vb_prev->fnext = vb_next;
free_vb(vb);
}
/* zero out buckets, make one big block of free mem
* caller is responsible for linking result into vblocks.
*/
static vb_t *free_list_init(vmemsize, vmemstart)
unsigned vmemsize;
vec_p vmemstart;
{
int b;
vb_t *vb, *bucket;
for (b = 0, bucket = bucket_table; b < NBUCKETS; b++) {
/* make each bucket circular */
bucket->fnext = bucket;
bucket->fprev = bucket;
bucket++;
}
b = get_bucket_num((int)vmemsize);
vb = new_vb();
vb->size = vmemsize;
vb->vector = vmemstart;
vb->active = 0;
vb->fnext = &bucket_table[b];
vb->fprev = &bucket_table[b];
bucket_table[b].fnext = vb;
bucket_table[b].fprev = vb;
return vb;
}
/* --------------------- vstack_pop ----------------------------------*/
/* pop an entry off the vstack: use reference counting to see if memory
* can be freed or not.
*/
void vstack_pop_real(vb)
vb_t *vb;
{
#ifndef SPEEDHACKS
vb->count--;
if (vb->count > 0) {
return;
} else {
#endif
if (vb->pair_count != 0) return; /* still used in a pair */
else if (vb->type == Pair) {
vb_t *first = vb->first;
vb_t *second = vb->second;
assert (vb->count <= 0);
assert (vb->pair_count == 0);
/* can pop off children if both pair_count and count are 0 */
if (-- first->pair_count == 0 && first->count == 0) {
vstack_pop_real(first);
}
if (-- second->pair_count == 0 && second->count == 0) {
vstack_pop_real(second);
}
free_vb(vb); /* free the vb struct */
} else {
vb_t *bucket;
/* try to coalesce into adjacent blocks */
if (vb->bprev->active == 0) {
vb_t *vb_prev = vb->bprev;
vb->size += vb_prev->size;
vb->vector = vb_prev->vector;
splice_vb(vb_prev);
}
if (vb->bnext->active == 0) {
vb_t *vb_next = vb->bnext;
vb->size += vb_next->size;
splice_vb(vb_next);
}
vb->active = 0;
/* add to free_list */
bucket = &bucket_table[get_bucket_num(vb->size)];
vb->fnext = bucket->fnext;
vb->fprev = bucket;
bucket->fnext->fprev = vb;
bucket->fnext = vb;
/* keep scratch as biggest available block */
if (vb->size >= scratch_block->size) scratch_block = vb;
}
#ifndef SPEEDHACKS
}
#endif
}
/* --------------------- new_vector ------------------------------*/
/* allocate memory for a new vector of given type and length (and
* segmentation, if its a segd).
*/
vb_t *new_vector(len, type, seglen)
int len;
TYPE type;
int seglen; /* -1 if not type is not Segd */
{
int size = -1; /* siz_...(len), for cvl memory */
int bucket_num; /* which bucket to get from */
int b;
vb_t *vb;
/* find out how much room to allocate */
switch (type) {
case Int:
size = siz_foz(len); break;
case Bool:
size = siz_fob(len); break;
case Float:
size = siz_fod(len); break;
case Segdes:
assert(seglen != -1);
size = siz_fos(seglen, len); break;
default:
_fprintf(stderr, "vinterp: internal error: illegal type in new_vector.\n");
vinterp_exit (1);
}
/* find proper free list */
bucket_num = get_bucket_num(size);
/* Do a first fit in the free list until we find a large enough free
* block. If this list doesn't have large enough block, take
* first item in smallest, larger non-empty free list. Set vb when
* block is found.
*/
vb = NULL;
if (!(isempty_bucket(bucket_num))) {
/* first-fit: use head of list as sentinal to avoid end test
* in inner loop. This requires a check at the end.
*/
register vb_t *vb_free = bucket_table + bucket_num;
vb_free->size = size; /* sentinel */
vb_free = vb_free->fnext; /* start from next block */
while (vb_free->size < size) /* so don't check for NULL */
vb_free = vb_free->fnext;
if (vb_free != &bucket_table[bucket_num]) { /* didn't hit sentinel */
vb = vb_free; /* found it */
}
}
if (vb == NULL) { /* list empty, or no big enough block */
for (b = bucket_num+1; (b < NBUCKETS) && isempty_bucket(b); b++)
;
if (b != NBUCKETS) vb = bucket_table[b].fnext;
}
if (vb == NULL) { /* memory not available */
compact_mem();
if (scratch_block->size < size) { /* only free block is scratch */
_fprintf(stderr,
"vinterp: ran out of vector memory. Rerun using larger -m argument.\n");
vinterp_exit(1);
} else vb = scratch_block;
}
assert(vb != NULL); /* just checking.... */
assert(vb->size >= size);
assert(vb->active == 0);
if (vb->size > size) { /* split bucket in two */
vb_t *vb_free = new_vb();
int new_size = vb->size - size;
int new_b = get_bucket_num(new_size);
vb_free->size = new_size;
vb_free->vector = add_fov(vb->vector, size);
vb_free->active = 0;
vb_free->fnext = bucket_table[new_b].fnext; /* in free list */
vb_free->fprev = &bucket_table[new_b];
bucket_table[new_b].fnext->fprev = vb_free;
bucket_table[new_b].fnext = vb_free;
vb_free->bprev = vb; /* in block list */
vb_free->bnext = vb->bnext;
vb->bnext->bprev = vb_free;
vb->bnext = vb_free;
vb->size = size; /* adjust size of remaining piece */
}
vb->fnext->fprev = vb->fprev; /* remove from free list */
vb->fprev->fnext = vb->fnext;
vb->active = 1;
vb->count = 1;
vb->pair_count = 0;
vb->type = type;
vb->len = len;
vb->seg_len = seglen;
if (vb == scratch_block) /* make sure didn't trash scratch */
find_scratch();
return vb;
}
vb_t *new_pair(vb_first, vb_second)
vb_t *vb_first, *vb_second;
{
vb_t *vb_pair = new_vb();
vb_pair->count = 1;
vb_pair->type = Pair;
vb_pair->first = vb_first;
vb_pair->second = vb_second;
vb_first->pair_count++;
vb_second->pair_count++;
vb_first->count--;
vb_second->count--;
return vb_pair;
}
/* return the items in pair through pointers */
void vb_unpair(vb_pair, p_vb_first, p_vb_second)
vb_t *vb_pair;
vb_t **p_vb_first, **p_vb_second;
{
assert(vb_pair->type = Pair);
assert(vb_pair->first != NULL);
assert(vb_pair->first->pair_count > 0);
assert(vb_pair->second != NULL);
assert(vb_pair->second->pair_count > 0);
*p_vb_first = vb_pair->first;
*p_vb_second = vb_pair->second;
(*p_vb_first)->count++;
(*p_vb_first)->pair_count--;
(*p_vb_second)->count++;
(*p_vb_second)->pair_count--;
vb_pair->count--;
if (vb_pair->count == 0 && vb_pair->pair_count == 0)
free_vb(vb_pair);
}
/* to copy a vector, just increment the reference counter */
#ifndef SPEEDHACKS
void vstack_copy(vb)
vb_t *vb;
{
vb->count ++;
}
#endif
/* ---------------------- memory compaction -----------------------------*/
/* To compact memory we traverse the vb list, copying active blocks as
* far to the front as we can. This uses the fact that the vb list
* respects the order of the blocks in vector memory, so we can can always
* copy backwards. As we traverse the list, we can splice out free blocks.
* When we're done, all the free-lists should be empty, and we can start
* over. This has the property that at any time in the process, all blocks
* still on the free list are guarenteed to be free, and hence scratch space
* is still available for copying. If necessary we can complicate the
* process by expanding the free pool as vectors are removed.
*
* compact_mem() resets the scratch_block to the (only) free block.
*/
static void compact_mem PROTO_((void))
{
static int compacting = 0; /* use this to avoid recursive calls */
vec_p from; /* where vector starts */
vec_p to; /* where it goes to */
vec_p new_to; /* where next vector goes */
vb_t *vb; /* block of memory being copied */
int vmem_size; /* memory still left */
if (garbage_notify)
_fprintf(stderr, "compacting vector memory...");
if (compacting) {
/* The compactor may need scratch to do the vector copies.
* assert_mem_size() calls the compactor if there is not enough
* scratch. Thus we may recursively call the compactor.
* This is very bad.
*/
_fprintf(stderr, "vinterp: not enough memory to compact memory.\n\tRerun with larger -m argument.\n");
exit(1);
} else {
compacting = 1;
}
vmem_size = cvl_mem_size;
/* Copy vectors to top of memory */
/* Contents of active blocks are copied, and vector field is updated.
* vb_t's corresponding to free blocks are deleted from the blocks
* structure.
*/
for (vb = vblocks->bnext, to = cvl_mem; /* start at beginning */
vb != vblocks; /* do whole list */
) {
if (vb->active) { /* block is active, so copy */
from = vb->vector;
assert_mem_size(mov_fov_scratch(vb->size));
mov_fov(to, from, vb->size, SCRATCH);
new_to = add_fov(to, vb->size); /* bump pointer after to */
vb->vector = to;
to = new_to;
vmem_size -= vb->size;
vb = vb->bnext;
} else { /* free this node */
vb_t *to_free = vb; /* save pointers */
vb = vb->bnext;
splice_vb(to_free); /* remove block */
}
}
/* At this point, the free list should have been emptied out, so
* reinitialize, starting free memory at current to.
*/
vb = free_list_init((unsigned)vmem_size, to);
/* relink free node (final block) into vblocks structure */
vb->bnext = vblocks; /* circular list */
vb->bprev = vblocks->bprev;
vblocks->bprev->bnext = vb;
vblocks->bprev = vb;
/* set scratch to the free block */
/* don't bother calling, find_scratch(); just do */
scratch_block = vb;
if (garbage_notify)
_fprintf(stderr, "done\n");
compacting = 0;
}
/* -----------------------debugging routines-------------------*/
/* walk through the vblock list, printing out size of blocks and whether
* they are free or not
*/
void vb_print()
{
vb_t *vb;
_fprintf(stderr, "memory: ");
for (vb = vblocks->bnext; /* start at beginning */
vb != vblocks; /* do whole list */
vb = vb->bnext) {
_fprintf(stderr, "%d%s%s ", vb->size,
vb->active ? "" : "*",
scratch_block == vb ? "#" : "");
}
_fprintf(stderr, "\n");
}
| 29.571646 | 105 | 0.624362 | [
"vector"
] |
23f553b8ef52d400662c982e8a9df64ad4cfcc35 | 8,604 | h | C | include/greybus/greybus.h | anujdeshpande/greybus-for-zephyr | 6f8f29a4c820c1c178104790b34ded239ce24635 | [
"BSD-3-Clause"
] | null | null | null | include/greybus/greybus.h | anujdeshpande/greybus-for-zephyr | 6f8f29a4c820c1c178104790b34ded239ce24635 | [
"BSD-3-Clause"
] | 3 | 2021-06-13T18:10:02.000Z | 2021-12-13T16:18:12.000Z | include/greybus/greybus.h | anujdeshpande/greybus-for-zephyr | 6f8f29a4c820c1c178104790b34ded239ce24635 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2014-2015 Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Author: Fabien Parent <fparent@baylibre.com>
*/
#ifndef _GREYBUS_H_
#define _GREYBUS_H_
#include <stddef.h>
#include <stdbool.h>
#if defined(CONFIG_BOARD_NATIVE_POSIX_64BIT) \
|| defined(CONFIG_BOARD_NATIVE_POSIX_32BIT) \
|| defined(CONFIG_BOARD_NRF52_BSIM)
#include <pthread.h>
#include <semaphore.h>
#else
#include <posix/pthread.h>
#endif
#include <sys/atomic.h>
#include <list.h>
//#include <util.h>
#include <unipro/unipro.h>
#include <greybus/types.h>
#include <time.h>
#ifndef OK
enum {
OK
};
#endif
#define GB_MTU 2048
#define GB_MAX_PAYLOAD_SIZE (GB_MTU - sizeof(struct gb_operation_hdr))
#define GB_TIMESYNC_MAX_STROBES 0x04
#define GB_INVALID_TYPE 0x7f
enum gb_event {
GB_EVT_CONNECTED,
GB_EVT_DISCONNECTED,
};
struct gb_operation;
typedef void (*gb_operation_callback)(struct gb_operation *operation);
typedef uint8_t (*gb_operation_handler_t)(struct gb_operation *operation);
typedef void (*gb_operation_fast_handler_t)(unsigned int cport, void *data);
#define GB_HANDLER(t, h) \
{ \
.type = t, \
.handler = h, \
.name = #h, \
}
#define GB_FAST_HANDLER(t, h) \
{ \
.type = t, \
.fast_handler = h, \
.name = #h, \
}
struct gb_operation_handler {
uint8_t type;
gb_operation_handler_t handler;
gb_operation_fast_handler_t fast_handler;
const char *name;
};
struct gb_transport_backend {
void (*init)(void);
void (*exit)(void);
int (*listen)(unsigned int cport);
int (*stop_listening)(unsigned int cport);
int (*send)(unsigned int cport, const void *buf, size_t len);
int (*send_async)(unsigned int cportid, const void *buf, size_t len,
unipro_send_completion_t callback, void *priv);
void *(*alloc_buf)(size_t size);
void (*free_buf)(void *ptr);
};
struct gb_bundle {
int id; /* bundle ID */
struct device *dev; /* primary bundle device */
void *priv; /* private bundle data */
};
struct gb_operation {
unsigned int cport;
bool has_responded;
atomic_t ref_count;
struct timespec time;
void *request_buffer;
void *response_buffer;
bool is_unipro_rx_buf;
gb_operation_callback callback;
sem_t sync_sem;
void *priv_data;
struct list_head list;
struct gb_operation *response;
struct gb_bundle *bundle;
#ifdef CONFIG_GREYBUS_FEATURE_HAVE_TIMESTAMPS
struct timespec send_ts;
struct timespec recv_ts;
#endif
};
struct gb_driver {
/*
* This is the callback in which all the initialization of driver-specific
* data should be done. The driver should create struct device and assign
* it to bundle->dev. The driver should store any private data it may need
* in bundle->priv. The same bundle object will be passed to the driver in
* all subsequent greybus handler callbacks calls.
*/
int (*init)(unsigned int cport, struct gb_bundle *bundle);
/*
* This function is called upon driver deregistration. All private data
* stored in bundle should be freed and struct device should be closed.
*/
void (*exit)(unsigned int cport, struct gb_bundle *bundle);
void (*connected)(unsigned int cport);
void (*disconnected)(unsigned int cport);
struct gb_operation_handler *op_handlers;
size_t stack_size;
size_t op_handlers_count;
const char *name;
struct gb_bundle *bundle;
};
struct gb_operation_hdr {
__le16 size;
__le16 id;
__u8 type;
__u8 result; /* present in response only */
__u8 pad[2];
};
enum gb_operation_type {
GB_TYPE_RESPONSE_FLAG = 0x80,
};
enum gb_operation_result {
GB_OP_SUCCESS = 0x00,
GB_OP_INTERRUPTED = 0x01,
GB_OP_TIMEOUT = 0x02,
GB_OP_NO_MEMORY = 0x03,
GB_OP_PROTOCOL_BAD = 0x04,
GB_OP_OVERFLOW = 0x05,
GB_OP_INVALID = 0x06,
GB_OP_RETRY = 0x07,
GB_OP_NONEXISTENT = 0x08,
GB_OP_UNKNOWN_ERROR = 0xfe,
GB_OP_INTERNAL = 0xff,
};
static inline void*
gb_operation_get_response_payload(struct gb_operation *operation)
{
return (char*)operation->response_buffer + sizeof(struct gb_operation_hdr);
}
static inline void*
gb_operation_get_request_payload(struct gb_operation *operation)
{
return (char*)operation->request_buffer + sizeof(struct gb_operation_hdr);
}
static inline struct gb_operation *gb_operation_get_response_op(struct gb_operation *op) {
return op->response;
}
static inline const char *gb_driver_name(struct gb_driver *driver)
{
return driver->name;
}
static inline const char *gb_handler_name(struct gb_operation_handler *handler)
{
return handler->name;
}
int gb_init(struct gb_transport_backend *transport);
void gb_deinit(void);
int gb_unipro_init(void);
int _gb_register_driver(unsigned int cport, int bundle_id,
struct gb_driver *driver);
int gb_unregister_driver(unsigned int cport);
static inline int gb_register_named_driver(unsigned int cport, int bundle,
struct gb_driver *driver,
const char *name)
{
driver->name = name;
return _gb_register_driver(cport, bundle, driver);
}
#define gb_register_driver(cport, bundle, driver) \
gb_register_named_driver(cport, bundle, driver, __FILE__)
int gb_listen(unsigned int cport);
int gb_stop_listening(unsigned int cport);
int gb_notify(unsigned cport, enum gb_event event);
void gb_operation_destroy(struct gb_operation *operation);
void *gb_operation_alloc_response(struct gb_operation *operation, size_t size);
int gb_operation_send_response(struct gb_operation *operation, uint8_t result);
int gb_operation_send_request_nowait(struct gb_operation *operation,
gb_operation_callback callback,
bool need_response);
int gb_operation_send_request_sync(struct gb_operation *operation);
int gb_operation_send_request(struct gb_operation *operation,
gb_operation_callback callback,
bool need_response);
struct gb_operation *gb_operation_create(unsigned int cport, uint8_t type,
uint32_t req_size);
void gb_operation_ref(struct gb_operation *operation);
void gb_operation_unref(struct gb_operation *operation);
size_t gb_operation_get_request_payload_size(struct gb_operation *operation);
uint8_t gb_operation_get_request_result(struct gb_operation *operation);
struct gb_bundle *gb_operation_get_bundle(struct gb_operation *operation);
int greybus_rx_handler(unsigned int, void*, size_t);
struct i2c_dev_s;
int gb_i2c_set_dev(struct i2c_dev_s *dev);
struct i2c_dev_s *gb_i2c_get_dev(void);
uint8_t gb_errno_to_op_result(int err);
struct gb_bundle *gb_bundle_get_by_id(unsigned int bundle_id);
#endif /* _GREYBUS_H_ */
| 32.224719 | 90 | 0.704091 | [
"object"
] |
23faf8b858a5df9c1e19ebd845f347d5308c10db | 1,396 | h | C | Assignment4/Application.h | 01Track1mp3/HCI2-Assignments | 36d72d7630580901628e8f2cc79c7a24169db31a | [
"MIT"
] | 1 | 2015-06-03T22:20:00.000Z | 2015-06-03T22:20:00.000Z | Assignment4/Application.h | 01Track1mp3/HCI2-Assignments | 36d72d7630580901628e8f2cc79c7a24169db31a | [
"MIT"
] | null | null | null | Assignment4/Application.h | 01Track1mp3/HCI2-Assignments | 36d72d7630580901628e8f2cc79c7a24169db31a | [
"MIT"
] | null | null | null | #pragma once
#include <opencv2/core/core.hpp>
#include <boost/tokenizer.hpp>
#include <XnTypes.h>
class GameClient;
class GameServer;
class DepthCamera;
class KinectMotor;
class SkeletonTracker;
class Calibration;
class Application
{
public:
Application();
virtual ~Application();
void loop();
void warpCameraToUntransformed();
void warpUntransformedToTransformed();
void processFrame();
void processSkeleton(XnUserID userId);
void processTouch();
bool isFoot(std::vector<cv::Point> contour);
void drawEllipse(cv::RotatedRect box);
bool selectUnit();
bool moveUnit();
float getAngle(cv::Point vector);
cv::Point getVector(cv::Point from, cv::Point to);
float getLength(cv::Point vector);
void makeScreenshots();
void clearOutputImage();
bool isFinished();
protected:
GameClient *m_gameClient;
GameServer *m_gameServer;
DepthCamera *m_depthCamera;
KinectMotor *m_kinectMotor;
SkeletonTracker *m_skeletonTracker;
Calibration *m_calibration;
cv::Mat m_bgrImage;
cv::Mat m_depthImage;
cv::Mat m_depthImageUntransformed;
cv::Mat m_outputImage;
cv::Mat m_gameImage;
cv::Mat m_reference;
cv::Mat m_touchOutput;
bool m_isFinished;
bool isUnitSelected;
int unitIndex;
static const int uist_level;
static const char *uist_server;
}; | 20.529412 | 55 | 0.697708 | [
"vector"
] |
23fe5dcc4f205838c0d0e7b19b23f98355503d1f | 1,173 | c | C | nitan/cmds/std/follow.c | cantona/NT6 | 073f4d491b3cfe6bfbe02fbad12db8983c1b9201 | [
"MIT"
] | 1 | 2019-03-27T07:25:16.000Z | 2019-03-27T07:25:16.000Z | nitan/cmds/std/follow.c | cantona/NT6 | 073f4d491b3cfe6bfbe02fbad12db8983c1b9201 | [
"MIT"
] | null | null | null | nitan/cmds/std/follow.c | cantona/NT6 | 073f4d491b3cfe6bfbe02fbad12db8983c1b9201 | [
"MIT"
] | null | null | null | // follow.c
inherit F_CLEAN_UP;
int main(object me, string arg)
{
object ob;
if (me->is_chatter())
return 0;
if( !arg ) return notify_fail("指令格式:follow <某人>|none。\n");
if( arg=="none")
if( me->query_leader() ) {
me->set_leader(0);
write("Ok.\n");
return 1;
} else {
write("你現在並沒有跟隨任何人。\n");
return 1;
}
if( query_temp("is_riding_follow", me) )
return notify_fail("你還是先從坐騎上下來後在跟隨別人吧。 \n");
if( !objectp(ob = present(arg, environment(me))) )
return notify_fail("這裏沒有 " + arg + "。\n");
if( !ob->is_character() )
return notify_fail("什麼?跟隨...." + ob->name() + "。\n");
if( ob==me )
return notify_fail("跟隨自己?\n");
me->set_leader(ob);
message_vision("$N決定開始跟隨$n一起行動。\n", me, ob);
return 1;
}
int help (object me)
{
write(@HELP
指令格式 : follow [<生物>|none]
這個指令讓你能跟隨某人或生物。
如果輸入 follow none 則停止跟隨。
HELP
);
return 1;
}
| 21.722222 | 69 | 0.45098 | [
"object"
] |
9b075c4e400c0483b1630072935845daf5e26b07 | 2,085 | h | C | extensions/browser/api/file_system/saved_files_service_interface.h | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | extensions/browser/api/file_system/saved_files_service_interface.h | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | extensions/browser/api/file_system/saved_files_service_interface.h | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef EXTENSIONS_BROWSER_API_FILE_SYSTEM_SAVED_FILES_SERVICE_INTERFACE_H_
#define EXTENSIONS_BROWSER_API_FILE_SYSTEM_SAVED_FILES_SERVICE_INTERFACE_H_
#include <string>
#include "base/files/file_path.h"
namespace extensions {
struct SavedFileEntry;
// Provides an LRU of saved file entries that persist across app reloads.
class SavedFilesServiceInterface {
public:
virtual ~SavedFilesServiceInterface() {}
// Registers a file entry with the saved files service, making it eligible to
// be put into the queue. File entries that are in the retained files queue at
// object construction are automatically registered.
virtual void RegisterFileEntry(const std::string& extension_id,
const std::string& id,
const base::FilePath& file_path,
bool is_directory) = 0;
// If the file with |id| is not in the queue of files to be retained
// permanently, adds the file to the back of the queue, evicting the least
// recently used entry at the front of the queue if it is full. If it is
// already present, moves it to the back of the queue. The |id| must have been
// registered.
virtual void EnqueueFileEntry(const std::string& extension_id,
const std::string& id) = 0;
// Returns whether the file entry with the given |id| has been registered.
virtual bool IsRegistered(const std::string& extension_id,
const std::string& id) = 0;
// Gets a borrowed pointer to the file entry with the specified |id|. Returns
// nullptr if the file entry has not been registered.
virtual const SavedFileEntry* GetFileEntry(const std::string& extension_id,
const std::string& id) = 0;
};
} // namespace extensions
#endif // EXTENSIONS_BROWSER_API_FILE_SYSTEM_SAVED_FILES_SERVICE_INTERFACE_H_
| 41.7 | 80 | 0.693525 | [
"object"
] |
9b0c8f99c50751a272044f682d1c28e6ff4cba63 | 18,583 | h | C | dpdk-17.11/lib/librte_member/rte_member.h | kwame998/jupiter | 2d5e953f200d2b4d081b0e6efa9cddb0a0ae51b7 | [
"MIT"
] | 1 | 2018-04-30T05:58:21.000Z | 2018-04-30T05:58:21.000Z | dpdk/lib/librte_member/rte_member.h | tydhome/jupiter | 6b1206af3303ebd934df969e8894cdd93acfd09f | [
"MIT"
] | null | null | null | dpdk/lib/librte_member/rte_member.h | tydhome/jupiter | 6b1206af3303ebd934df969e8894cdd93acfd09f | [
"MIT"
] | null | null | null | /*-
* BSD LICENSE
*
* Copyright(c) 2017 Intel Corporation. All rights reserved.
* 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 Intel Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @file
*
* RTE Membership Library
*
* The Membership Library is an extension and generalization of a traditional
* filter (for example Bloom Filter and cuckoo filter) structure that has
* multiple usages in a variety of workloads and applications. The library is
* used to test if a key belongs to certain sets. Two types of such
* "set-summary" structures are implemented: hash-table based (HT) and vector
* bloom filter (vBF). For HT setsummary, two subtypes or modes are available,
* cache and non-cache modes. The table below summarize some properties of
* the different implementations.
*
* @warning
* @b EXPERIMENTAL: this API may change without prior notice
*/
/**
* <!--
* +==========+=====================+================+=========================+
* | type | vbf | HT-cache | HT-non-cache |
* +==========+=====================+==========================================+
* |structure | bloom-filter array | hash-table like without storing key |
* +----------+---------------------+------------------------------------------+
* |set id | limited by bf count | [1, 0x7fff] |
* | | up to 32. | |
* +----------+---------------------+------------------------------------------+
* |usages & | small set range, | can delete, | cache most recent keys, |
* |properties| user-specified | big set range, | have both false-positive|
* | | false-positive rate,| small false | and false-negative |
* | | no deletion support.| positive depend| depend on table size, |
* | | | on table size, | automatic overwritten. |
* | | | new key does | |
* | | | not overwrite | |
* | | | existing key. | |
* +----------+---------------------+----------------+-------------------------+
* -->
*/
#ifndef _RTE_MEMBER_H_
#define _RTE_MEMBER_H_
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
/** The set ID type that stored internally in hash table based set summary. */
typedef uint16_t member_set_t;
/** Invalid set ID used to mean no match found. */
#define RTE_MEMBER_NO_MATCH 0
/** Maximum size of hash table that can be created. */
#define RTE_MEMBER_ENTRIES_MAX (1 << 30)
/** Maximum number of keys that can be searched as a bulk */
#define RTE_MEMBER_LOOKUP_BULK_MAX 64
/** Entry count per bucket in hash table based mode. */
#define RTE_MEMBER_BUCKET_ENTRIES 16
/** Maximum number of characters in setsum name. */
#define RTE_MEMBER_NAMESIZE 32
/** @internal Hash function used by membership library. */
#if defined(RTE_ARCH_X86) || defined(RTE_MACHINE_CPUFLAG_CRC32)
#include <rte_hash_crc.h>
#define MEMBER_HASH_FUNC rte_hash_crc
#else
#include <rte_jhash.h>
#define MEMBER_HASH_FUNC rte_jhash
#endif
extern int librte_member_logtype;
#define RTE_MEMBER_LOG(level, fmt, args...) \
rte_log(RTE_LOG_ ## level, librte_member_logtype, "%s(): " fmt, \
__func__, ## args)
/** @internal setsummary structure. */
struct rte_member_setsum;
/**
* @warning
* @b EXPERIMENTAL: this API may change without prior notice
*
* Parameter struct used to create set summary
*/
struct rte_member_parameters;
/**
* @warning
* @b EXPERIMENTAL: this API may change without prior notice
*
* Define different set summary types
*/
enum rte_member_setsum_type {
RTE_MEMBER_TYPE_HT = 0, /**< Hash table based set summary. */
RTE_MEMBER_TYPE_VBF, /**< Vector of bloom filters. */
RTE_MEMBER_NUM_TYPE
};
/** @internal compare function for different arch. */
enum rte_member_sig_compare_function {
RTE_MEMBER_COMPARE_SCALAR = 0,
RTE_MEMBER_COMPARE_AVX2,
RTE_MEMBER_COMPARE_NUM
};
/** @internal setsummary structure. */
struct rte_member_setsum {
enum rte_member_setsum_type type; /* Type of the set summary. */
uint32_t key_len; /* Length of key. */
uint32_t prim_hash_seed; /* Primary hash function seed. */
uint32_t sec_hash_seed; /* Secondary hash function seed. */
/* Hash table based. */
uint32_t bucket_cnt; /* Number of buckets. */
uint32_t bucket_mask; /* Bit mask to get bucket index. */
/* For runtime selecting AVX, scalar, etc for signature comparison. */
enum rte_member_sig_compare_function sig_cmp_fn;
uint8_t cache; /* If it is cache mode for ht based. */
/* Vector bloom filter. */
uint32_t num_set; /* Number of set (bf) in vbf. */
uint32_t bits; /* Number of bits in each bf. */
uint32_t bit_mask; /* Bit mask to get bit location in bf. */
uint32_t num_hashes; /* Number of hash values to index bf. */
uint32_t mul_shift; /* vbf internal variable used during bit test. */
uint32_t div_shift; /* vbf internal variable used during bit test. */
void *table; /* This is the handler of hash table or vBF array. */
/* Second cache line should start here. */
uint32_t socket_id; /* NUMA Socket ID for memory. */
char name[RTE_MEMBER_NAMESIZE]; /* Name of this set summary. */
} __rte_cache_aligned;
/**
* @warning
* @b EXPERIMENTAL: this API may change without prior notice
*
* Parameters used when create the set summary table. Currently user can
* specify two types of setsummary: HT based and vBF. For HT based, user can
* specify cache or non-cache mode. Here is a table to describe some differences
*
*/
struct rte_member_parameters {
const char *name; /**< Name of the hash. */
/**
* User to specify the type of the setsummary from one of
* rte_member_setsum_type.
*
* HT based setsummary is implemented like a hash table. User should use
* this type when there are many sets.
*
* vBF setsummary is a vector of bloom filters. It is used when number
* of sets is not big (less than 32 for current implementation).
*/
enum rte_member_setsum_type type;
/**
* is_cache is only used for HT based setsummary.
*
* If it is HT based setsummary, user to specify the subtype or mode
* of the setsummary. It could be cache, or non-cache mode.
* Set is_cache to be 1 if to use as cache mode.
*
* For cache mode, keys can be evicted out of the HT setsummary. Keys
* with the same signature and map to the same bucket
* will overwrite each other in the setsummary table.
* This mode is useful for the case that the set-summary only
* needs to keep record of the recently inserted keys. Both
* false-negative and false-positive could happen.
*
* For non-cache mode, keys cannot be evicted out of the cache. So for
* this mode the setsummary will become full eventually. Keys with the
* same signature but map to the same bucket will still occupy multiple
* entries. This mode does not give false-negative result.
*/
uint8_t is_cache;
/**
* For HT setsummary, num_keys equals to the number of entries of the
* table. When the number of keys inserted in the HT setsummary
* approaches this number, eviction could happen. For cache mode,
* keys could be evicted out of the table. For non-cache mode, keys will
* be evicted to other buckets like cuckoo hash. The table will also
* likely to become full before the number of inserted keys equal to the
* total number of entries.
*
* For vBF, num_keys equal to the expected number of keys that will
* be inserted into the vBF. The implementation assumes the keys are
* evenly distributed to each BF in vBF. This is used to calculate the
* number of bits we need for each BF. User does not specify the size of
* each BF directly because the optimal size depends on the num_keys
* and false positive rate.
*/
uint32_t num_keys;
/**
* The length of key is used for hash calculation. Since key is not
* stored in set-summary, large key does not require more memory space.
*/
uint32_t key_len;
/**
* num_set is only used for vBF, but not used for HT setsummary.
*
* num_set is equal to the number of BFs in vBF. For current
* implementation, it only supports 1,2,4,8,16,32 BFs in one vBF set
* summary. If other number of sets are needed, for example 5, the user
* should allocate the minimum available value that larger than 5,
* which is 8.
*/
uint32_t num_set;
/**
* false_positive_rate is only used for vBF, but not used for HT
* setsummary.
*
* For vBF, false_positive_rate is the user-defined false positive rate
* given expected number of inserted keys (num_keys). It is used to
* calculate the total number of bits for each BF, and the number of
* hash values used during lookup and insertion. For details please
* refer to vBF implementation and membership library documentation.
*
* For HT, This parameter is not directly set by users.
* HT setsummary's false positive rate is in the order of:
* false_pos = (1/bucket_count)*(1/2^16), since we use 16-bit signature.
* This is because two keys needs to map to same bucket and same
* signature to have a collision (false positive). bucket_count is equal
* to number of entries (num_keys) divided by entry count per bucket
* (RTE_MEMBER_BUCKET_ENTRIES). Thus, the false_positive_rate is not
* directly set by users for HT mode.
*/
float false_positive_rate;
/**
* We use two seeds to calculate two independent hashes for each key.
*
* For HT type, one hash is used as signature, and the other is used
* for bucket location.
* For vBF type, these two hashes and their combinations are used as
* hash locations to index the bit array.
*/
uint32_t prim_hash_seed;
/**
* The secondary seed should be a different value from the primary seed.
*/
uint32_t sec_hash_seed;
int socket_id; /**< NUMA Socket ID for memory. */
};
/**
* @warning
* @b EXPERIMENTAL: this API may change without prior notice
*
* Find an existing set-summary and return a pointer to it.
*
* @param name
* Name of the set-summary.
* @return
* Pointer to the set-summary or NULL if object not found
* with rte_errno set appropriately. Possible rte_errno values include:
* - ENOENT - value not available for return
*/
struct rte_member_setsum *
rte_member_find_existing(const char *name);
/**
* @warning
* @b EXPERIMENTAL: this API may change without prior notice
*
* Create set-summary (SS).
*
* @param params
* Parameters to initialize the setsummary.
* @return
* Return the pointer to the setsummary.
* Return value is NULL if the creation failed.
*/
struct rte_member_setsum *
rte_member_create(const struct rte_member_parameters *params);
/**
* @warning
* @b EXPERIMENTAL: this API may change without prior notice
*
* Lookup key in set-summary (SS).
* Single key lookup and return as soon as the first match found
*
* @param setsum
* Pointer of a setsummary.
* @param key
* Pointer of the key to be looked up.
* @param set_id
* Output the set id matches the key.
* @return
* Return 1 for found a match and 0 for not found a match.
*/
int
rte_member_lookup(const struct rte_member_setsum *setsum, const void *key,
member_set_t *set_id);
/**
* @warning
* @b EXPERIMENTAL: this API may change without prior notice
*
* Lookup bulk of keys in set-summary (SS).
* Each key lookup returns as soon as the first match found
*
* @param setsum
* Pointer of a setsummary.
* @param keys
* Pointer of the bulk of keys to be looked up.
* @param num_keys
* Number of keys that will be lookup.
* @param set_ids
* Output set ids for all the keys to this array.
* User should preallocate array that can contain all results, which size is
* the num_keys.
* @return
* The number of keys that found a match.
*/
int
rte_member_lookup_bulk(const struct rte_member_setsum *setsum,
const void **keys, uint32_t num_keys,
member_set_t *set_ids);
/**
* @warning
* @b EXPERIMENTAL: this API may change without prior notice
*
* Lookup a key in set-summary (SS) for multiple matches.
* The key lookup will find all matched entries (multiple match).
* Note that for cache mode of HT, each key can have at most one match. This is
* because keys with same signature that maps to same bucket will overwrite
* each other. So multi-match lookup should be used for vBF and non-cache HT.
*
* @param setsum
* Pointer of a set-summary.
* @param key
* Pointer of the key that to be looked up.
* @param max_match_per_key
* User specified maximum number of matches for each key. The function returns
* as soon as this number of matches found for the key.
* @param set_id
* Output set ids for all the matches of the key. User needs to preallocate
* the array that can contain max_match_per_key number of results.
* @return
* The number of matches that found for the key.
* For cache mode HT set-summary, the number should be at most 1.
*/
int
rte_member_lookup_multi(const struct rte_member_setsum *setsum,
const void *key, uint32_t max_match_per_key,
member_set_t *set_id);
/**
* @warning
* @b EXPERIMENTAL: this API may change without prior notice
*
* Lookup a bulk of keys in set-summary (SS) for multiple matches each key.
* Each key lookup will find all matched entries (multiple match).
* Note that for cache mode HT, each key can have at most one match. So
* multi-match function is mainly used for vBF and non-cache mode HT.
*
* @param setsum
* Pointer of a setsummary.
* @param keys
* Pointer of the keys to be looked up.
* @param num_keys
* The number of keys that will be lookup.
* @param max_match_per_key
* The possible maximum number of matches for each key.
* @param match_count
* Output the number of matches for each key in an array.
* @param set_ids
* Return set ids for all the matches of all keys. Users pass in a
* preallocated 2D array with first dimension as key index and second
* dimension as match index. For example set_ids[bulk_size][max_match_per_key]
* @return
* The number of keys that found one or more matches in the set-summary.
*/
int
rte_member_lookup_multi_bulk(const struct rte_member_setsum *setsum,
const void **keys, uint32_t num_keys,
uint32_t max_match_per_key,
uint32_t *match_count,
member_set_t *set_ids);
/**
* @warning
* @b EXPERIMENTAL: this API may change without prior notice
*
* Insert key into set-summary (SS).
*
* @param setsum
* Pointer of a set-summary.
* @param key
* Pointer of the key to be added.
* @param set_id
* The set id associated with the key that needs to be added. Different mode
* supports different set_id ranges. 0 cannot be used as set_id since
* RTE_MEMBER_NO_MATCH by default is set as 0.
* For HT mode, the set_id has range as [1, 0x7FFF], MSB is reserved.
* For vBF mode the set id is limited by the num_set parameter when create
* the set-summary.
* @return
* HT (cache mode) and vBF should never fail unless the set_id is not in the
* valid range. In such case -EINVAL is returned.
* For HT (non-cache mode) it could fail with -ENOSPC error code when table is
* full.
* For success it returns different values for different modes to provide
* extra information for users.
* Return 0 for HT (cache mode) if the add does not cause
* eviction, return 1 otherwise. Return 0 for non-cache mode if success,
* -ENOSPC for full, and 1 if cuckoo eviction happens.
* Always returns 0 for vBF mode.
*/
int
rte_member_add(const struct rte_member_setsum *setsum, const void *key,
member_set_t set_id);
/**
* @warning
* @b EXPERIMENTAL: this API may change without prior notice
*
* De-allocate memory used by set-summary.
*
* @param setsum
* Pointer to the set summary.
*/
void
rte_member_free(struct rte_member_setsum *setsum);
/**
* @warning
* @b EXPERIMENTAL: this API may change without prior notice
*
* Reset the set-summary tables. E.g. reset bits to be 0 in BF,
* reset set_id in each entry to be RTE_MEMBER_NO_MATCH in HT based SS.
*
* @param setsum
* Pointer to the set-summary.
*/
void
rte_member_reset(const struct rte_member_setsum *setsum);
/**
* @warning
* @b EXPERIMENTAL: this API may change without prior notice
*
* Delete items from the set-summary. Note that vBF does not support deletion
* in current implementation. For vBF, error code of -EINVAL will be returned.
*
* @param setsum
* Pointer to the set-summary.
* @param key
* Pointer of the key to be deleted.
* @param set_id
* For HT mode, we need both key and its corresponding set_id to
* properly delete the key. Without set_id, we may delete other keys with the
* same signature.
* @return
* If no entry found to delete, an error code of -ENOENT could be returned.
*/
int
rte_member_delete(const struct rte_member_setsum *setsum, const void *key,
member_set_t set_id);
#ifdef __cplusplus
}
#endif
#endif /* _RTE_MEMBER_H_ */
| 36.153696 | 80 | 0.689178 | [
"object",
"vector"
] |
9b0f5d89c8deb1ecc31af3513a266d6179a32dc4 | 3,959 | h | C | src/AccessControlLogic/acl_internal.h | naishai/private-transaction-families | da2bf22650e6cab43c53c9b34a8a78bc0b432394 | [
"Apache-2.0"
] | 13 | 2019-01-30T17:51:19.000Z | 2021-03-12T02:32:41.000Z | src/AccessControlLogic/acl_internal.h | naishai/private-transaction-families | da2bf22650e6cab43c53c9b34a8a78bc0b432394 | [
"Apache-2.0"
] | 7 | 2019-06-12T06:34:40.000Z | 2019-09-24T19:11:26.000Z | src/AccessControlLogic/acl_internal.h | naishai/private-transaction-families | da2bf22650e6cab43c53c9b34a8a78bc0b432394 | [
"Apache-2.0"
] | 8 | 2019-01-29T17:01:11.000Z | 2022-03-20T07:32:04.000Z | /*
* Copyright 2018 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <unordered_map>
#include <map>
#include <queue>
#include "PrivateLedger.h"
#include "secure_allocator.h"
#include "config.h"
namespace acl
{
// use ordered map to keep order after serialization
using AclMemberTable = std::map<SignerPubKey, secure::vector<secure::string>>;
//singleton class used for ACL implemetation
// TODO singleton is not the best option here, don't use it
class InternalState final
{
public:
InternalState(InternalState const &) = delete; // Copy construct
InternalState(InternalState &&) = delete; // Move construct
InternalState &operator=(InternalState const &) = delete; // Copy assign
InternalState &operator=(InternalState &&) = delete; // Move assign
static InternalState &Instance();
// gropus
// GroupID StringToGroupID(const secure::string &) const;
// Result CreateNewGroup(const GroupID &);
// Result AddMemberToGroup(GroupID, const MemberID &);
// bool IsMemberInGroup(const GroupID &, const MemberID &) const;
//access control
Result SetPublicAddress(const StlAddress &);
bool IsAddressPublic(const StlAddress &) const;
bool IsAddressPublicPrefix(const secure::string &) const;
Result AllowAccess(const SignerPubKey &signer, const secure::string &addr);
Result RemoveAccess(const SignerPubKey &signer, const secure::string &addr);
bool CheckAccess(const secure::string &addr, const SignerPubKey &signer) const;
bool WriteAcl(const uint16_t &svn, const secure::string &nonce);
bool ReadAcl(const uint16_t &svn, bool is_client_reader = false, const secure::vector<uint8_t> &acl_hash = {});
void ClearAcl();
// members
// MemberID KeyToMemberID(const SignerPubKey &);
bool IsMember(const SignerPubKey &) const;
Result AddMember(const SignerPubKey &);
bool RemoveMember(const SignerPubKey &k);
bool ChangeMemberKey(const SignerPubKey &old_key, const SignerPubKey &new_key);
const SignerPubKey get_admin_key() const;
// bool update_members(const uint16_t &svn, const secure::string &nonce);
// bool read_members(const uint16_t &svn);
bool ReadFromAddress(const StlAddress &, secure::vector<uint8_t> &out_value, const uint16_t &svn, bool is_client_reader = false) const;
bool DecryptAddrData(const secure::vector<uint8_t> &toDecrypt, const StlAddress &addr, const uint16_t &svn, secure::vector<uint8_t> &out) const;
Result WriteToAddress(const secure::vector<std::pair<StlAddress, secure::vector<uint8_t>>> &addr_data_vec, const SignerPubKey &, const uint16_t &svn, const secure::string &nonce) const;
//svn
uint16_t get_cached_svn() const;
std::array<uint8_t, 64> get_acl_hash() const;
StlAddress get_svn_addr() const;
private:
InternalState();
~InternalState();
//acl
bool is_prefix(const secure::string &a_str, const secure::string &b_str) const;
//serialization
bool DeserializeAcl(const secure::vector<uint8_t> &acl_str);
const secure::vector<uint8_t> SerializeAcl() const;
// groups
// GroupsList Groups;
AclMemberTable acl_members;
SignerPubKey admin_key = {};
std::vector<StlAddress> public_address_vec;
StlAddress get_acl_addr() const;
//encryption
bool EncryptAddrData(const secure::vector<uint8_t> &toEncrypt, const StlAddress &addr, const SignerPubKey &signer, const uint16_t &svn, const secure::string &nonce, secure::string &out) const;
//SVN
std::array<uint8_t, 64> acl_hash = {};
uint16_t cached_svn = 0;
};
} // namespace acl
| 40.814433 | 193 | 0.757262 | [
"vector"
] |
9b10279469b21f96aad7a6b697063a1ad7629369 | 4,785 | h | C | ATEsystem.PIRIS-driver-Shared/include/pylon/linux/pylon/StreamGrabber.h | parezj/ATEsystem.PIRIS-driver-SDK-cpp | b74891ed848d1bcc66e367b3bed96e2d960128bf | [
"MIT"
] | 2 | 2021-02-01T11:04:16.000Z | 2021-12-26T09:31:34.000Z | ATEsystem.PIRIS-driver-Shared/include/pylon/linux/pylon/StreamGrabber.h | parezj/ATEsystem.PIRIS-driver-SDK-cpp | b74891ed848d1bcc66e367b3bed96e2d960128bf | [
"MIT"
] | 1 | 2020-01-11T12:38:19.000Z | 2020-01-14T09:19:57.000Z | baslerSDK/pylon/include/pylon/StreamGrabber.h | SummerBlack/BaslerCamera | 6a0907ee749f7e6776b65f170a655fc236750de1 | [
"Apache-2.0"
] | 3 | 2020-12-15T13:52:03.000Z | 2022-03-28T09:41:14.000Z | //-----------------------------------------------------------------------------
// Basler pylon SDK
// Copyright (c) 2006-2018 Basler AG
// http://www.baslerweb.com
// Author: Hartmut Nebelung
//-----------------------------------------------------------------------------
/*!
\file
\brief Low Level API: Definition of IStreamGrabber interface
*/
#ifndef __ISTREAMGRABBER_H__
#define __ISTREAMGRABBER_H__
#if _MSC_VER > 1000
#pragma once
#endif //_MSC_VER > 1000
#include <pylon/Platform.h>
#ifdef _MSC_VER
# pragma pack(push, PYLON_PACKING)
#endif /* _MSC_VER */
#include <GenICamFwd.h>
#include <pylon/stdinclude.h>
namespace Pylon
{
class GrabResult;
class WaitObject;
/// This opaque type represents a registered buffer.
typedef void* StreamBufferHandle;
// -------------------------------------------------------------------------
// interface IStreamGrabber
// -------------------------------------------------------------------------
/*!
\ingroup Pylon_LowLevelApi
\interface IStreamGrabber
\brief Low Level API: Interface to an (input) data stream
Data is filled into user provided buffers. Before usage
the buffers must be registered. After calling PrepareGrab()
enter them into a queue to become filled.
The streamgrabber provides a output queue which contains filled data buffers.
While the queue is not empty the associated wait object is signaled.
Get the buffer using the RetrieveResult()
method.
When FinishGrab() is called the result queue remains open, so the data may
be collected. It remains open until Close()
resp. the device
is closed.
Parameter of streamgrabber are controlled by the elements of a own NodeMap,
which can be retrieved by calling GetNodeMap().
\sa For an introduction into the usage of stream grabbers see \ref grabbingimages
in the Programmer's Guide.
*/
interface IStreamGrabber
{
/// Opens the stream grabber
//*! Opens the stream grabber and starts the result queue. */
virtual void Open(void) = 0;
/// Closes the stream grabber
/*! Flushes the result queue and stops the thread. */
virtual void Close(void) = 0;
/// Retrieve whether the stream grabber is open.
virtual bool IsOpen(void) const = 0;
/// Registers a buffer for subsequent use.
/*! Stream must be locked to register buffers The Buffer size may not exceed
the value specified when PrepareGrab was called. */
virtual StreamBufferHandle RegisterBuffer( void* Buffer, size_t BufferSize ) = 0;
/// Deregisters the buffer
/*! Deregistering fails while the buffer is in use, so retrieve the buffer from
the output queue after grabbing.
\note Do not delete buffers before they are deregistered. */
virtual const void* DeregisterBuffer( StreamBufferHandle ) = 0;
/// Prepares grabbing
/*! Allocates resources, synchronizes with the camera and locks critical parameter */
virtual void PrepareGrab(void) = 0;
/// Stops grabbing
/*! Releases the resources and camera. Pending grab requests are canceled. */
virtual void FinishGrab(void) = 0;
/// Enqueues a buffer in the input queue.
/*! PrepareGrab is required to queue buffers. The context is returned together with the
buffer and the grab result. It is not touched by the stream grabber.
It is illegal to queue a buffer a second time before it is fetched from the
result queue.*/
virtual void QueueBuffer( StreamBufferHandle, const void* Context=NULL ) = 0;
/// Cancels pending requests
/*! , resources remain allocated. Following, the results must be retrieved from the
Output Queue. */
virtual void CancelGrab(void) = 0;
/// Retrieves a grab result from the output queue
/*! \return When result was available true is returned and and the
first result is copied into the grabresult. Otherwise the grabresult remains
unchanged and false is returned. */
virtual bool RetrieveResult( GrabResult& ) = 0;
/// Returns the result event object.
/*! This object is associated with the result queue. The event is signaled when
queue is non-empty */
virtual WaitObject& GetWaitObject(void) const = 0;
/// Returns the associated stream grabber parameters.
/*! If no parameters are available, NULL is returned. */
virtual GENAPI_NAMESPACE::INodeMap* GetNodeMap(void) = 0;
};
};
#ifdef _MSC_VER
# pragma pack(pop)
#endif /* _MSC_VER */
#endif //__ISTREAMGRABBER_H__
| 38.902439 | 95 | 0.626123 | [
"object"
] |
9b165668bb1275667e52201210279540789daeb7 | 12,349 | h | C | src/add-ons/print/drivers/pdf/source/PDFWriter.h | deep-1/haiku | b273e9733d25babe5e6702dc1e24f3dff1ffd6dc | [
"MIT"
] | 4 | 2016-03-29T21:45:21.000Z | 2016-12-20T00:50:38.000Z | src/add-ons/print/drivers/pdf/source/PDFWriter.h | jessicah/haiku | c337460525c39e870d31221d205a299d9cd79c6a | [
"MIT"
] | null | null | null | src/add-ons/print/drivers/pdf/source/PDFWriter.h | jessicah/haiku | c337460525c39e870d31221d205a299d9cd79c6a | [
"MIT"
] | 1 | 2020-05-08T04:02:02.000Z | 2020-05-08T04:02:02.000Z | /*
* Copyright 2001-2009, Haiku, Inc. All Rights Reserved.
* Distributed under the terms of the MIT License.
*
* Authors:
* Philippe Houdoin
* Simon Gauvin
* Michael Pfeiffer
*/
#ifndef PDFWRITER_H
#define PDFWRITER_H
#include <AppKit.h>
#include <InterfaceKit.h>
#include <String.h>
#include <List.h>
#include <math.h>
#include "PrinterDriver.h"
#include "PictureIterator.h"
#include "Fonts.h"
#include "SubPath.h"
#include "PrintUtils.h"
#include "Link.h"
#include "ImageCache.h"
#include "PDFSystem.h"
#include "pdflib.h"
#define USE_IMAGE_CACHE 1
#define RAD2DEGREE(r) (180.0 * r / M_PI)
#define DEGREE2RAD(d) (M_PI * d / 180.0)
class DrawShape;
class WebLink;
class Bookmark;
class XRefDefs;
class XRefDests;
class PDFWriter : public PrinterDriver, public PictureIterator {
friend class DrawShape;
friend class PDFLinePathBuilder;
friend class WebLink;
friend class Link;
friend class Bookmark;
friend class LocalLink;
friend class TextLine;
public:
// constructors / destructor
PDFWriter();
~PDFWriter();
// public methods
status_t BeginJob();
status_t PrintPage(int32 pageNumber, int32 pageCount);
status_t EndJob();
status_t InitWriter();
status_t BeginPage(BRect paperRect, BRect printRect);
status_t EndPage();
void SetAttribute(const char* name, const char* value);
bool LoadBookmarkDefinitions(const char* name);
bool LoadXRefsDefinitions(const char* name);
void RecordDests(const char* s);
// PDFLib callbacks
size_t WriteData(void *data, size_t size);
void ErrorHandler(int type, const char *msg);
// Image support
int32 BytesPerPixel(int32 pixelFormat);
bool HasAlphaChannel(int32 pixelFormat);
bool NeedsBPC1Mask(int32 pixelFormat);
inline bool IsTransparentRGB32(uint8* in);
inline bool IsTransparentRGBA32(uint8* in);
inline bool IsTransparentRGB32_BIG(uint8* in);
inline bool IsTransparentRGBA32_BIG(uint8* in);
//inline bool IsTransparentRGB24(uint8* in);
//inline bool IsTransparentRGB24_BIG(uint8* in);
//inline bool IsTransparentRGB16(uint8* in);
//inline bool IsTransparentRGB16_BIG(uint8* in);
inline bool IsTransparentRGB15(uint8* in);
inline bool IsTransparentRGB15_BIG(uint8* in);
inline bool IsTransparentRGBA15(uint8* in);
inline bool IsTransparentRGBA15_BIG(uint8* in);
inline bool IsTransparentCMAP8(uint8* in);
//inline bool IsTransparentGRAY8(uint8* in);
//inline bool IsTransparentGRAY1(uint8* in);
inline uint8 AlphaFromRGBA32(uint8* in);
inline uint8 AlphaFromRGBA32_BIG(uint8* in);
inline void ConvertFromRGB32(uint8* in, uint8* out);
inline void ConvertFromRGB32_BIG(uint8* in, uint8* out);
inline void ConvertFromRGBA32(uint8* in, uint8* out);
inline void ConvertFromRGBA32_BIG(uint8* in, uint8* out);
inline void ConvertFromRGB24(uint8* in, uint8* out);
inline void ConvertFromRGB24_BIG(uint8* in, uint8* out);
inline void ConvertFromRGB16(uint8* in, uint8* out);
inline void ConvertFromRGB16_BIG(uint8* in, uint8* out);
inline void ConvertFromRGB15(uint8* in, uint8* out);
inline void ConvertFromRGBA15_BIG(uint8* in, uint8* out);
inline void ConvertFromRGB15_BIG(uint8* in, uint8* out);
inline void ConvertFromRGBA15(uint8* in, uint8* out);
inline void ConvertFromCMAP8(uint8* in, uint8* out);
inline void ConvertFromGRAY8(uint8* in, uint8* out);
inline void ConvertFromGRAY1(uint8* in, uint8* out, int8 bit);
uint8 *CreateMask(BRect src, int32 bytesPerRow, int32 pixelFormat, int32 flags, void *data);
uint8 *CreateSoftMask(BRect src, int32 bytesPerRow, int32 pixelFormat, int32 flags, void *data);
BBitmap *ConvertBitmap(BRect src, int32 bytesPerRow, int32 pixelFormat, int32 flags, void *data);
bool GetImages(BRect src, int32 width, int32 height, int32 bytesPerRow, int32 pixelFormat, int32 flags, void *data, int* mask, int* image);
// String handling
bool BeginsChar(char byte) { return BEGINS_CHAR(byte); }
void ToUtf8(uint32 encoding, const char *string, BString &utf8);
void ToUnicode(const char *string, BString &unicode);
void ToPDFUnicode(const char *string, BString &unicode);
uint16 CodePointSize(const char *s);
void DrawChar(uint16 unicode, const char *utf8, int16 size);
void ClipChar(BFont* font, const char* unicode, const char *utf8, int16 size, float width);
bool EmbedFont(const char* n);
void DeclareEncodingFiles();
void DeclareEncodingFile(BPath* path, const char* id,
const char* name);
status_t DeclareFonts();
void RecordFont(const char* family, const char* style, float size);
// BPicture playback handlers
void Op(int number);
void MovePenBy(BPoint delta);
void StrokeLine(BPoint start, BPoint end);
void StrokeRect(BRect rect);
void FillRect(BRect rect);
void StrokeRoundRect(BRect rect, BPoint radii);
void FillRoundRect(BRect rect, BPoint radii);
void StrokeBezier(BPoint *control);
void FillBezier(BPoint *control);
void StrokeArc(BPoint center, BPoint radii, float startTheta, float arcTheta);
void FillArc(BPoint center, BPoint radii, float startTheta, float arcTheta);
void StrokeEllipse(BPoint center, BPoint radii);
void FillEllipse(BPoint center, BPoint radii);
void StrokePolygon(int32 numPoints, BPoint *points, bool isClosed);
void FillPolygon(int32 numPoints, BPoint *points, bool isClosed);
void StrokeShape(BShape *shape);
void FillShape(BShape *shape);
void DrawString(char *string, float deltax, float deltay);
void DrawPixels(BRect src, BRect dest, int32 width, int32 height, int32 bytesPerRow, int32 pixelFormat, int32 flags, void *data);
void SetClippingRects(BRect *rects, uint32 numRects);
void ClipToPicture(BPicture *picture, BPoint point, bool clip_to_inverse_picture);
void PushState();
void PopState();
void EnterStateChange();
void ExitStateChange();
void EnterFontState();
void ExitFontState();
void SetOrigin(BPoint pt);
void SetPenLocation(BPoint pt);
void SetDrawingMode(drawing_mode mode);
void SetLineMode(cap_mode capMode, join_mode joinMode, float miterLimit);
void SetPenSize(float size);
void SetForeColor(rgb_color color);
void SetBackColor(rgb_color color);
void SetStipplePattern(pattern p);
void SetScale(float scale);
void SetFontFamily(char *family);
void SetFontStyle(char *style);
void SetFontSpacing(int32 spacing);
void SetFontSize(float size);
void SetFontRotate(float rotation);
void SetFontEncoding(int32 encoding);
void SetFontFlags(int32 flags);
void SetFontShear(float shear);
void SetFontFace(int32 flags);
static inline bool IsSame(const pattern &p1, const pattern &p2);
static inline bool IsSame(const rgb_color &c1, const rgb_color &c2);
private:
enum PDFVersion {
kPDF13,
kPDF14,
kPDF15
};
class State
{
public:
State *prev;
BFont beFont;
int font;
PDFSystem pdfSystem;
float penX;
float penY;
drawing_mode drawingMode;
rgb_color foregroundColor;
rgb_color backgroundColor;
rgb_color currentColor;
cap_mode capMode;
join_mode joinMode;
float miterLimit;
float penSize;
pattern pattern0;
int32 fontSpacing;
// initialize with defalt values
State(float h = a4_height, float x = 0, float y = 0)
{
static rgb_color white = {255, 255, 255, 255};
static rgb_color black = {0, 0, 0, 255};
prev = NULL;
font = 0;
pdfSystem.SetHeight(h);
pdfSystem.SetOrigin(x, y);
penX = 0;
penY = 0;
drawingMode = B_OP_COPY;
foregroundColor = white;
backgroundColor = black;
currentColor = black;
capMode = B_BUTT_CAP;
joinMode = B_MITER_JOIN;
miterLimit = B_DEFAULT_MITER_LIMIT;
penSize = 1;
pattern0 = B_SOLID_HIGH;
fontSpacing = B_STRING_SPACING;
}
State(State *prev)
{
*this = *prev;
this->prev = prev;
}
};
class Font
{
public:
Font(char *n, int f, font_encoding e) : name(n), font(f), encoding(e) { }
BString name;
int font;
font_encoding encoding;
};
class Pattern
{
public:
pattern pat;
rgb_color lowColor, highColor;
int patternId;
Pattern(const pattern &p, rgb_color low, rgb_color high, int id)
: pat(p)
, lowColor(low)
, highColor(high)
, patternId(id)
{};
inline bool Matches(const pattern &p, rgb_color low, rgb_color high) const {
return IsSame(pat, p) && IsSame(lowColor, low) && IsSame(highColor, high);
};
};
class Transparency
{
uint8 alpha;
int handle;
public:
Transparency(uint8 alpha, int handle)
: alpha(alpha)
, handle(handle)
{};
inline bool Matches(uint8 alpha) const {
return this->alpha == alpha;
};
inline int Handle() const { return handle; }
};
PDFVersion fPDFVersion;
FILE *fLog;
PDF *fPdf;
int32 fPage;
State *fState;
int32 fStateDepth;
TList<Font> fFontCache;
TList<Pattern> fPatterns;
TList<Transparency> fTransparencyCache;
TList<Transparency> fTransparencyStack;
ImageCache fImageCache;
int64 fEmbedMaxFontSize;
BScreen *fScreen;
Fonts *fFonts;
bool fCreateWebLinks;
bool fCreateBookmarks;
Bookmark *fBookmark;
bool fCreateXRefs;
XRefDefs *fXRefs;
XRefDests *fXRefDests;
font_encoding fFontSearchOrder[no_of_cjk_encodings];
TextLine fTextLine;
TList<UsedFont> fUsedFonts;
UserDefinedEncodings fUserDefinedEncodings;
enum
{
kDrawingMode,
kClippingMode
} fMode;
inline float tx(float x) { return fState->pdfSystem.tx(x); }
inline float ty(float y) { return fState->pdfSystem.ty(y); }
inline float scale(float f) { return fState->pdfSystem.scale(f); }
PDFSystem* pdfSystem() const { return &fState->pdfSystem; }
enum
{
kStroke = true,
kFill = false
};
inline bool MakesPattern() { return Pass() == 0; }
inline bool MakesPDF() { return Pass() == 1; }
inline bool IsDrawing() const { return fMode == kDrawingMode; }
inline bool IsClipping() const { return fMode == kClippingMode; }
// PDF features depending on PDF version:
inline bool SupportsSoftMask() const { return fPDFVersion >= kPDF14; }
inline bool SupportsOpacity() const { return fPDFVersion >= kPDF14; }
inline float PenSize() const { return fState->penSize; }
inline cap_mode LineCapMode() const { return fState->capMode; }
inline join_mode LineJoinMode() const { return fState->joinMode; }
inline float LineMiterLimit() const { return fState->miterLimit; }
bool StoreTranslatorBitmap(BBitmap *bitmap, const char *filename, uint32 type);
void GetFontName(BFont *font, char *fontname);
void GetFontName(BFont *font, char *fontname, bool &embed, font_encoding encoding);
int FindFont(char *fontname, bool embed, font_encoding encoding);
void MakeUserDefinedEncoding(uint16 unicode, uint8 &enc, uint8 &index);
// alpha transparency
Transparency* FindTransparency(uint8 alpha);
void BeginTransparency();
void EndTransparency();
void PushInternalState();
bool PopInternalState();
void SetColor(rgb_color toSet);
void SetColor();
void CreatePattern();
int FindPattern();
void SetPattern();
void StrokeOrClip();
void FillOrClip();
void Paint(bool stroke);
void PaintShape(BShape *shape, bool stroke);
void PaintRoundRect(BRect rect, BPoint radii, bool stroke);
void PaintArc(BPoint center, BPoint radii, float startTheta, float arcTheta, int stroke);
void PaintEllipse(BPoint center, BPoint radii, bool stroke);
};
inline bool
PDFWriter::IsSame(const pattern &p1, const pattern &p2)
{
char *a = (char*)p1.data;
char *b = (char*)p2.data;
return memcmp(a, b, 8) == 0;
}
inline bool
PDFWriter::IsSame(const rgb_color &c1, const rgb_color &c2)
{
char *a = (char*)&c1;
char *b = (char*)&c1;
return memcmp(a, b, sizeof(rgb_color)) == 0;
}
// PDFLib C callbacks class instance redirectors
size_t _WriteData(PDF *p, void *data, size_t size);
void _ErrorHandler(PDF *p, int type, const char *msg);
#endif // PDFWRITER_H
| 30.949875 | 142 | 0.695279 | [
"shape"
] |
9b1666d286c1afb978095c2ef00715b7dd59cee6 | 3,468 | h | C | core/include/mmcore/factories/CallAutoDescription.h | azuki-monster/megamol | f5d75ae5630f9a71a7fbf81624bfd4f6b253c655 | [
"BSD-3-Clause"
] | 2 | 2020-10-16T10:15:37.000Z | 2021-01-21T13:06:00.000Z | core/include/mmcore/factories/CallAutoDescription.h | azuki-monster/megamol | f5d75ae5630f9a71a7fbf81624bfd4f6b253c655 | [
"BSD-3-Clause"
] | null | null | null | core/include/mmcore/factories/CallAutoDescription.h | azuki-monster/megamol | f5d75ae5630f9a71a7fbf81624bfd4f6b253c655 | [
"BSD-3-Clause"
] | 1 | 2021-01-28T01:19:54.000Z | 2021-01-28T01:19:54.000Z | /*
* CallAutoDescription.h
* Copyright (C) 2008 - 2015 by MegaMol Consortium
* All rights reserved. Alle Rechte vorbehalten.
*/
#ifndef MEGAMOLCORE_FACTORIES_CALLAUTODESCRIPTION_H_INCLUDED
#define MEGAMOLCORE_FACTORIES_CALLAUTODESCRIPTION_H_INCLUDED
#if (defined(_MSC_VER) && (_MSC_VER > 1000))
#pragma once
#endif /* (defined(_MSC_VER) && (_MSC_VER > 1000)) */
#include "mmcore/factories/CallDescription.h"
namespace megamol {
namespace core {
namespace factories {
/**
* Description class for the call T
*/
template<class T>
class CallAutoDescription : public CallDescription {
public:
typedef T CallT;
/** Ctor. */
CallAutoDescription(void) : CallDescription() {
// intentionally empty
}
/** Dtor. */
virtual ~CallAutoDescription(void) {
// intentionally empty
}
/**
* Answer the name of the objects of this description.
*
* @return The name of the objects of this description.
*/
virtual const char *ClassName(void) const {
return T::ClassName();
}
/**
* Clones this object
*
* @return The new clone
*/
virtual CallDescription *Clone(void) const {
return new CallAutoDescription<T>();
}
/**
* Creates a new call object.
*
* @return The newly created call object.
*/
virtual Call * CreateCall(void) const {
T *thing = new T();
thing->SetClassName(this->ClassName());
return this->describeCall(thing);
}
/**
* Gets a human readable description of the module.
*
* @return A human readable description of the module.
*/
virtual const char *Description(void) const {
return T::Description();
}
/**
* Answer the number of functions used for this call.
*
* @return The number of functions used for this call.
*/
virtual unsigned int FunctionCount(void) const {
return T::FunctionCount();
}
/**
* Answer the name of the function used for this call.
*
* @param idx The index of the function to return it's name.
*
* @return The name of the requested function.
*/
virtual const char * FunctionName(unsigned int idx) const {
return T::FunctionName(idx);
}
/**
* Answers whether this description is describing the class of
* 'call'.
*
* @param call The call to test.
*
* @return 'true' if 'call' is described by this description,
* 'false' otherwise.
*/
virtual bool IsDescribing(const Call * call) const {
return dynamic_cast<const T*>(call) != NULL;
}
/**
* Assignment crowbar
*
* @param tar The targeted object
* @param src The source object
*/
virtual void AssignmentCrowbar(Call * tar, const Call * src) const {
T* t = dynamic_cast<T*>(tar);
const T* s = dynamic_cast<const T*>(src);
*t = *s;
}
};
} /* end namespace factories */
} /* end namespace core */
} /* end namespace megamol */
#endif /* MEGAMOLCORE_CALLAUTODESCRIPTION_H_INCLUDED */
| 26.883721 | 76 | 0.550173 | [
"object"
] |
9b207aa41f299f37fdb491e95ca1adf885108933 | 3,747 | h | C | third_party/webrtc/include/chromium/src/ui/android/resources/resource_manager.h | ssaroha/node-webrtc | 74335bd07cbc52484a88c8eeb336c9bd001928a8 | [
"BSD-2-Clause"
] | 3 | 2018-02-22T18:06:56.000Z | 2021-08-28T12:49:27.000Z | third_party/webrtc/include/chromium/src/ui/android/resources/resource_manager.h | ssaroha/node-webrtc | 74335bd07cbc52484a88c8eeb336c9bd001928a8 | [
"BSD-2-Clause"
] | null | null | null | third_party/webrtc/include/chromium/src/ui/android/resources/resource_manager.h | ssaroha/node-webrtc | 74335bd07cbc52484a88c8eeb336c9bd001928a8 | [
"BSD-2-Clause"
] | 2 | 2017-08-16T08:15:01.000Z | 2018-03-27T00:07:30.000Z | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_ANDROID_RESOURCES_RESOURCE_MANAGER_H_
#define UI_ANDROID_RESOURCES_RESOURCE_MANAGER_H_
#include <memory>
#include <unordered_map>
#include <unordered_set>
#include "base/android/jni_android.h"
#include "cc/resources/scoped_ui_resource.h"
#include "third_party/skia/include/core/SkColor.h"
#include "ui/android/resources/crushed_sprite_resource.h"
#include "ui/android/ui_android_export.h"
#include "ui/gfx/geometry/insets_f.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/size.h"
namespace ui {
class UIResourceProvider;
// A Java counterpart will be generated for this enum.
// GENERATED_JAVA_ENUM_PACKAGE: org.chromium.ui.resources
enum AndroidResourceType {
ANDROID_RESOURCE_TYPE_STATIC = 0,
ANDROID_RESOURCE_TYPE_DYNAMIC,
ANDROID_RESOURCE_TYPE_DYNAMIC_BITMAP,
ANDROID_RESOURCE_TYPE_SYSTEM,
ANDROID_RESOURCE_TYPE_CRUSHED_SPRITE,
ANDROID_RESOURCE_TYPE_COUNT,
ANDROID_RESOURCE_TYPE_FIRST = ANDROID_RESOURCE_TYPE_STATIC,
ANDROID_RESOURCE_TYPE_LAST = ANDROID_RESOURCE_TYPE_CRUSHED_SPRITE,
};
// The ResourceManager serves as a cache for resources obtained through Android
// APIs and consumed by the compositor.
class UI_ANDROID_EXPORT ResourceManager {
public:
struct Resource {
public:
Resource();
~Resource();
gfx::Rect Border(const gfx::Size& bounds) const;
gfx::Rect Border(const gfx::Size& bounds, const gfx::InsetsF& scale) const;
std::unique_ptr<cc::ScopedUIResource> ui_resource;
gfx::Size size;
gfx::Rect padding;
gfx::Rect aperture;
};
// Obtain a handle to the Java ResourceManager counterpart.
virtual base::android::ScopedJavaLocalRef<jobject> GetJavaObject() = 0;
// Return a handle to the resource specified by |res_type| and |res_id|.
// If the resource has not been loaded, loading will be performed
// synchronously, blocking until the load completes.
// If load fails, a null handle will be returned and it is up to the caller
// to react appropriately.
virtual Resource* GetResource(AndroidResourceType res_type, int res_id) = 0;
// Return a handle to a static resource specified by |res_id| that has a tint
// of |tint_color| applied to it.
virtual Resource* GetStaticResourceWithTint(int res_id,
SkColor tint_color) = 0;
// Remove tints that were unused in the current frame being built. This
// function takes a set |used_tints| and removes all the tints not in the set
// from the cache.
virtual void RemoveUnusedTints(const std::unordered_set<int>& used_tints) = 0;
// Trigger asynchronous loading of the resource specified by |res_type| and
// |res_id|, if it has not yet been loaded.
virtual void PreloadResource(AndroidResourceType res_type, int res_id) = 0;
// Return a handle to the CrushedSpriteResource specified by |bitmap_res_id|
// and |metadata_res_id|. If the resource has not been loaded, loading will be
// performed synchronously, blocking until the load completes. If load fails,
// a null handle will be returned and it is up to the caller to react
// appropriately.
virtual CrushedSpriteResource* GetCrushedSpriteResource(
int bitmap_res_id, int metadata_res_id) = 0;
// Convenience wrapper method.
cc::UIResourceId GetUIResourceId(AndroidResourceType res_type, int res_id) {
Resource* resource = GetResource(res_type, res_id);
return resource && resource->ui_resource ? resource->ui_resource->id() : 0;
}
protected:
virtual ~ResourceManager() {}
};
} // namespace ui
#endif // UI_ANDROID_RESOURCES_RESOURCE_MANAGER_H_
| 37.09901 | 80 | 0.755538 | [
"geometry"
] |
9b28f0429a5bde6ae6c1521930d3770c5dc66638 | 11,535 | c | C | demos/ansi.c | h2obrain/freetype-gl | b67f459ef158bb2781c03092d735c80834be93d4 | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | demos/ansi.c | h2obrain/freetype-gl | b67f459ef158bb2781c03092d735c80834be93d4 | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | demos/ansi.c | h2obrain/freetype-gl | b67f459ef158bb2781c03092d735c80834be93d4 | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | /* Freetype GL - A C OpenGL Freetype engine
*
* Distributed under the OSI-approved BSD 2-Clause License. See accompanying
* file `LICENSE` for more details.
*/
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include "freetype-gl.h"
#include "font-manager.h"
#include "vertex-buffer.h"
#include "text-buffer.h"
#include "markup.h"
#include "shader.h"
#include "mat4.h"
#include "screenshot-util.h"
#include <GLFW/glfw3.h>
// ------------------------------------------------------- global variables ---
font_manager_t * font_manager;
text_buffer_t * buffer;
mat4 model, view, projection;
GLuint text_shader;
// ------------------------------------------------------------ init_colors ---
void
init_colors( vec4 *colors ) {
vec4 defaults[16] =
{
{{ 46/256.0f, 52/256.0f, 54/256.0f, 1.0f}},
{{204/256.0f, 0/256.0f, 0/256.0f, 1.0f}},
{{ 78/256.0f, 154/256.0f, 6/256.0f, 1.0f}},
{{196/256.0f, 160/256.0f, 0/256.0f, 1.0f}},
{{ 52/256.0f, 101/256.0f, 164/256.0f, 1.0f}},
{{117/256.0f, 80/256.0f, 123/256.0f, 1.0f}},
{{ 6/256.0f, 152/256.0f, 154/256.0f, 1.0f}},
{{211/256.0f, 215/256.0f, 207/256.0f, 1.0f}},
{{ 85/256.0f, 87/256.0f, 83/256.0f, 1.0f}},
{{239/256.0f, 41/256.0f, 41/256.0f, 1.0f}},
{{138/256.0f, 226/256.0f, 52/256.0f, 1.0f}},
{{252/256.0f, 233/256.0f, 79/256.0f, 1.0f}},
{{114/256.0f, 159/256.0f, 207/256.0f, 1.0f}},
{{173/256.0f, 127/256.0f, 168/256.0f, 1.0f}},
{{ 52/256.0f, 226/256.0f, 226/256.0f, 1.0f}},
{{238/256.0f, 238/256.0f, 236/256.0f, 1.0f}}
};
size_t i = 0;
/* Default 16 colors */
for ( i=0; i< 16; ++i ) {
colors[i] = defaults[i];
}
/* Color cube */
for ( i=0; i<6*6*6; i++ ) {
vec4 color = {{ (i/6/6)/5.0f, ((i/6)%6)/5.0f, (i%6)/5.0f, 1.0f}};
colors[i+16] = color;
}
/* Grascale ramp (24 tones) */
for ( i=0; i<24; i++ ) {
vec4 color ={{i/24.0f, i/24.0f, i/24.0f, 1.0f}};
colors[232+i] = color;
}
}
// --------------------------------------------------------- ansi_to_markup ---
void
ansi_to_markup( char *sequence, size_t length, markup_t *markup ) {
size_t i;
int code = 0;
int set_bg = -1;
int set_fg = -1;
vec4 none = {{0,0,0,0}};
static vec4 * colors = 0;
if ( colors == 0 ) {
colors = (vec4 *) malloc( sizeof(vec4) * 256 );
init_colors( colors );
}
if ( length <= 1 ) {
markup->foreground_color = colors[0];
markup->underline_color = markup->foreground_color;
markup->overline_color = markup->foreground_color;
markup->strikethrough_color = markup->foreground_color;
markup->outline_color = markup->foreground_color;
markup->background_color = none;
markup->underline = 0;
markup->overline = 0;
markup->bold = 0;
markup->italic = 0;
markup->strikethrough = 0;
return;
}
for ( i=0; i<length; ++i) {
char c = *(sequence+i);
if ( c >= '0' && c <= '9' ) {
code = code * 10 + (c-'0');
} else
if ( (c == ';') || (i == (length-1)) ) {
if ( set_fg == 1 ) {
markup->foreground_color = colors[code];
set_fg = -1;
} else
if ( set_bg == 1 ) {
markup->background_color = colors[code];
set_bg = -1;
} else
if ( (set_fg == 0) && (code == 5) ) {
set_fg = 1;
code = 0;
} else
if ( (set_bg == 0) && (code == 5) ) {
set_bg = 1;
code = 0;
} else
/* Set fg color (30 + x, where x is the index of the color) */
if ( (code >= 30) && (code < 38 ) ) {
markup->foreground_color = colors[code-30];
} else
/* Set bg color (40 + x, where x is the index of the color) */
if ( (code >= 40) && (code < 48 ) ) {
markup->background_color = colors[code-40];
} else {
switch (code) {
case 0:
markup->foreground_color = colors[0];
markup->background_color = none;
markup->underline = 0;
markup->overline = 0;
markup->bold = 0;
markup->italic = 0;
markup->strikethrough = 0;
break;
case 1: markup->bold = 1; break;
case 21: markup->bold = 0; break;
case 2: markup->foreground_color.alpha = 0.5; break;
case 22: markup->foreground_color.alpha = 1.0; break;
case 3: markup->italic = 1; break;
case 23: markup->italic = 0; break;
case 4: markup->underline = 1; break;
case 24: markup->underline = 0; break;
case 8: markup->foreground_color.alpha = 0.0; break;
case 28: markup->foreground_color.alpha = 1.0; break;
case 9: markup->strikethrough = 1; break;
case 29: markup->strikethrough = 0; break;
case 53: markup->overline = 1; break;
case 55: markup->overline = 0; break;
case 39: markup->foreground_color = colors[0]; break;
case 49: markup->background_color = none; break;
case 38: set_fg = 0; break;
case 48: set_bg = 0; break;
default: break;
}
}
code = 0;
}
}
markup->underline_color = markup->foreground_color;
markup->overline_color = markup->foreground_color;
markup->strikethrough_color = markup->foreground_color;
markup->outline_color = markup->foreground_color;
if ( markup->bold && markup->italic ) {
markup->family = "fonts/VeraMoBI.ttf";
} else
if ( markup->bold ) {
markup->family = "fonts/VeraMoBd.ttf";
} else
if ( markup->italic ) {
markup->family = "fonts/VeraMoIt.ttf";
} else {
markup->family = "fonts/VeraMono.ttf";
}
}
// ------------------------------------------------------------------ print ---
void
print( text_buffer_t * buffer, vec2 * pen,
char *text, markup_t *markup ) {
char *seq_start = text, *seq_end = text;
char *p;
size_t i;
for ( p=text; p<(text+strlen(text)); ++p ) {
char *start = strstr( p, "\033[" );
char *end = NULL;
if ( start) {
end = strstr( start+1, "m" );
}
if ( (start == p) && (end > start) ) {
seq_start = start+2;
seq_end = end;
p = end;
} else {
int seq_size = (seq_end-seq_start)+1;
char * text_start = p;
int text_size = 0;
if ( start ) {
text_size = start-p;
p = start-1;
} else {
text_size = text+strlen(text)-p;
p = text+strlen(text);
}
ansi_to_markup(seq_start, seq_size, markup );
markup->font = font_manager_get_from_markup( font_manager, markup );
text_buffer_add_text( buffer, pen, markup, text_start, text_size );
}
}
}
// ------------------------------------------------------------------- init ---
void init( void ) {
text_shader = shader_load( "shaders/text.vert",
"shaders/text.frag" );
font_manager = font_manager_new( 512, 512, LCD_FILTERING_OFF );
buffer = text_buffer_new( );
vec4 black = {{0.0, 0.0, 0.0, 1.0}};
vec4 none = {{1.0, 1.0, 1.0, 0.0}};
markup_t markup;
markup.family = "fonts/VeraMono.ttf";
markup.size = 15.0;
markup.bold = 0;
markup.italic = 0;
markup.spacing = 0.0;
markup.gamma = 1.0;
markup.foreground_color = black;
markup.background_color = none;
markup.underline = 0;
markup.underline_color = black;
markup.overline = 0;
markup.overline_color = black;
markup.strikethrough = 0;
markup.strikethrough_color = black;
markup.font = 0;
vec2 pen = {{10.0, 480.0}};
FILE *file = fopen ( "data/256colors.txt", "r" );
if ( file != NULL ) {
char line[1024];
while ( fgets ( line, sizeof(line), file ) != NULL ) {
print( buffer, &pen, line, &markup );
}
fclose ( file );
}
glGenTextures( 1, &font_manager->atlas->id );
glBindTexture( GL_TEXTURE_2D, font_manager->atlas->id );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
glTexImage2D( GL_TEXTURE_2D, 0, GL_RED, font_manager->atlas->width,
font_manager->atlas->height, 0, GL_RED, GL_UNSIGNED_BYTE,
font_manager->atlas->data );
mat4_set_identity( &projection );
mat4_set_identity( &model );
mat4_set_identity( &view );
}
// ---------------------------------------------------------------- display ---
void display( GLFWwindow* window ) {
glClearColor(1.00,1.00,1.00,1.00);
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
glColor4f(1.00,1.00,1.00,1.00);
glUseProgram( text_shader );
{
glUniformMatrix4fv( glGetUniformLocation( text_shader, "model" ),
1, 0, model.data);
glUniformMatrix4fv( glGetUniformLocation( text_shader, "view" ),
1, 0, view.data);
glUniformMatrix4fv( glGetUniformLocation( text_shader, "projection" ),
1, 0, projection.data);
glUniform1i( glGetUniformLocation( text_shader, "tex" ), 0 );
glUniform3f( glGetUniformLocation( text_shader, "pixel" ),
1.0f/font_manager->atlas->width,
1.0f/font_manager->atlas->height,
(float)font_manager->atlas->depth );
glEnable( GL_BLEND );
glActiveTexture( GL_TEXTURE0 );
glBindTexture( GL_TEXTURE_2D, font_manager->atlas->id );
glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
glBlendColor( 1, 1, 1, 1 );
vertex_buffer_render( buffer->buffer, GL_TRIANGLES );
glBindTexture( GL_TEXTURE_2D, 0 );
glBlendColor( 0, 0, 0, 0 );
glUseProgram( 0 );
}
glfwSwapBuffers( window );
}
// ---------------------------------------------------------------- reshape ---
void reshape( GLFWwindow* window, int width, int height ) {
glViewport(0, 0, width, height);
mat4_set_orthographic( &projection, 0, width, 0, height, -1, 1);
}
// --------------------------------------------------------------- keyboard ---
void keyboard( GLFWwindow* window, int key, int scancode, int action, int mods ) {
if ( key == GLFW_KEY_ESCAPE && action == GLFW_PRESS ) {
glfwSetWindowShouldClose( window, GL_TRUE );
}
}
// --------------------------------------------------------- error-callback ---
void error_callback( int error, const char* description ) {
fputs( description, stderr );
}
// ------------------------------------------------------------------- main ---
int main( int argc, char **argv ) {
GLFWwindow* window;
char* screenshot_path = NULL;
if (argc > 1) {
if (argc == 3 && 0 == strcmp( "--screenshot", argv[1] ))
screenshot_path = argv[2];
else
{
fprintf( stderr, "Unknown or incomplete parameters given\n" );
exit( EXIT_FAILURE );
}
}
glfwSetErrorCallback( error_callback );
if (!glfwInit( )) {
exit( EXIT_FAILURE );
}
glfwWindowHint( GLFW_VISIBLE, GL_FALSE );
glfwWindowHint( GLFW_RESIZABLE, GL_FALSE );
window = glfwCreateWindow( 800, 500, argv[0], NULL, NULL );
if (!window) {
glfwTerminate( );
exit( EXIT_FAILURE );
}
glfwMakeContextCurrent( window );
glfwSwapInterval( 1 );
glfwSetFramebufferSizeCallback( window, reshape );
glfwSetWindowRefreshCallback( window, display );
glfwSetKeyCallback( window, keyboard );
#ifndef __APPLE__
glewExperimental = GL_TRUE;
GLenum err = glewInit();
if (GLEW_OK != err) {
/* Problem: glewInit failed, something is seriously wrong. */
fprintf( stderr, "Error: %s\n", glewGetErrorString(err) );
exit( EXIT_FAILURE );
}
fprintf( stderr, "Using GLEW %s\n", glewGetString(GLEW_VERSION) );
#endif
init();
glfwShowWindow( window );
reshape( window, 800, 500 );
while (!glfwWindowShouldClose( window )) {
display( window );
glfwPollEvents( );
if (screenshot_path) {
screenshot( window, screenshot_path );
glfwSetWindowShouldClose( window, 1 );
}
}
glDeleteProgram( text_shader );
glDeleteTextures( 1, &font_manager->atlas->id );
font_manager->atlas->id = 0;
text_buffer_delete( buffer );
font_manager_delete( font_manager );
glfwDestroyWindow( window );
glfwTerminate( );
return EXIT_SUCCESS;
}
| 28.41133 | 82 | 0.599133 | [
"model"
] |
9b318ee4ec97e07833a2f29675db9d75f8da66dd | 76,197 | h | C | src/inc/gm_ast.h | navahgar/Green-Marl | 3761cb1a3bf28e95b72d39af4d76be8c5b5a5ea2 | [
"DOC"
] | 1 | 2021-04-18T18:16:23.000Z | 2021-04-18T18:16:23.000Z | src/inc/gm_ast.h | navahgar/Green-Marl | 3761cb1a3bf28e95b72d39af4d76be8c5b5a5ea2 | [
"DOC"
] | null | null | null | src/inc/gm_ast.h | navahgar/Green-Marl | 3761cb1a3bf28e95b72d39af4d76be8c5b5a5ea2 | [
"DOC"
] | null | null | null | #ifndef GL_AST_H
#define GL_AST_H
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include <list>
#include <vector>
#include <map>
#include <set>
#include <string>
#include "gm_frontend_api.h"
extern const char* gm_get_type_string(int i);
enum AST_NODE_TYPE
{
AST_ID, //
AST_FIELD, // A.B
AST_MAPACCESS, // A[B]
AST_IDLIST, // A, B, C,
AST_TYPEDECL, // INT
AST_ARGDECL, // a,b : B
AST_PROCDEF, // proc A() {}
AST_EXPR, // c + 3
AST_EXPR_RDC, // c + 3
AST_EXPR_BUILTIN, // c + 3
AST_EXPR_FOREIGN, // Foreign Expression
AST_EXPR_MAPACCESS,
AST_SENT, //
AST_SENTBLOCK, // { ... }
AST_ASSIGN, // C =D
AST_VARDECL, // INT x;
// NODE_PROPERTY<INT>(G) x;
AST_FOREACH, // Foreach (t: G.Nodes) {...}
AST_IF, // IF (x) THEN s; ELSE z ;
AST_WHILE, // While (x) {...} or Do {...} While (x)
AST_RETURN, // Return y;
AST_BFS, // InBFS(t: G.Nodes) {....} InReverse {....}
AST_CALL, // Call to (built-in) function
AST_FOREIGN, // Foreign syntax
AST_NOP, // NOP (for backend-only)
AST_END,
};
class gm_symtab_entry;
class gm_symtab;
class gm_scope;
class ast_id;
class ast_field;
// typechecker context;
class gm_apply;
// defined in gm_traverse.h
char* gm_strdup(const char* org); // defined in gm_misc.cc
class ast_expr;
class ast_node;
class expr_list
{
public:
// temporary class used only during parsing
std::list<ast_expr*> LIST;
};
class lhs_list
{
public:
// temporary class used only during parsing
std::list<ast_node*> LIST;
};
// any information can be added to nodes
class ast_extra_info
{
public:
int ival;
bool bval;
float fval;
void* ptr1;
void* ptr2;
ast_extra_info();
ast_extra_info(bool b);
ast_extra_info(int i);
ast_extra_info(float f);
ast_extra_info(void* p1, void* p2 = NULL);
virtual ~ast_extra_info() {
}
virtual ast_extra_info* copy();
virtual void base_copy(ast_extra_info* from);
};
class ast_extra_info_string: public ast_extra_info
{
public:
char* str;
ast_extra_info_string();
virtual ~ast_extra_info_string();
ast_extra_info_string(const char* org);
const char* get_string();
virtual ast_extra_info* copy();
};
class ast_extra_info_set: public ast_extra_info
{
public:
std::set<void*> set;
ast_extra_info_set() {
}
~ast_extra_info_set() {
}
virtual ast_extra_info* copy() {
assert(false);
return NULL;
}
std::set<void*>& get_set() {
return set;
}
};
class ast_extra_info_list: public ast_extra_info
{
public:
std::list<void*> list;
ast_extra_info_list() {
}
~ast_extra_info_list() {
}
virtual ast_extra_info* copy() {
assert(false);
return NULL;
}
std::list<void*>& get_list() {
return list;
}
};
class ast_extra_info_map: public ast_extra_info
{
public:
std::map<void*, void*> map;
ast_extra_info_map() {
}
~ast_extra_info_map() {
}
virtual ast_extra_info* copy() {
assert(false);
return NULL;
}
std::map<void*, void*>& get_map() {
return map;
}
};
class ast_node
{
friend class gm_apply;
protected:
ast_node(AST_NODE_TYPE nt) :
nodetype(nt), parent(NULL), line(0), col(0), sym_vars(NULL), sym_procs(NULL), sym_fields(NULL) {
}
ast_node() :
nodetype(AST_END), parent(NULL), line(0), col(0), sym_vars(NULL), sym_procs(NULL), sym_fields(NULL) {
}
AST_NODE_TYPE nodetype;
ast_node* parent;
public:
void set_nodetype(AST_NODE_TYPE nt) {
nodetype = nt;
}
virtual ~ast_node() {
std::map<std::string, ast_extra_info*>::iterator i;
for (i = extra.begin(); i != extra.end(); i++) {
delete i->second;
}
extra.clear();
}
AST_NODE_TYPE get_nodetype() {
return nodetype;
}
ast_node* get_parent() {
return parent;
}
void set_parent(ast_node* p) {
parent = p;
}
virtual bool is_sentence() {
return false;
}
virtual bool is_expr() {
return false;
}
bool has_symtab() {
return (nodetype == AST_SENTBLOCK) || (nodetype == AST_FOREACH) || (nodetype == AST_PROCDEF) || (nodetype == AST_EXPR_RDC) || (nodetype == AST_BFS);
}
// for parser debug
virtual void reproduce(int id_level) = 0; // defined in reproduce.cc
virtual void dump_tree(int id_level) = 0; // defined in dump_tree.cc
// defined in traverse.cc
virtual void traverse(gm_apply*a, bool is_post, bool is_pre) {
assert(false);
}
void traverse_pre(gm_apply*a) {
traverse(a, false, true);
}
void traverse_post(gm_apply*a) {
traverse(a, true, false);
}
void traverse_both(gm_apply*a) {
traverse(a, true, true);
}
virtual void apply_symtabs(gm_apply*a, bool is_post_apply = false);
// scoped elements
virtual bool has_scope() {
return false;
}
virtual gm_symtab* get_symtab_var() {
assert(has_scope());
return sym_vars;
}
virtual gm_symtab* get_symtab_field() {
assert(has_scope());
return sym_fields;
}
virtual gm_symtab* get_symtab_proc() {
assert(has_scope());
return sym_procs;
}
virtual void get_this_scope(gm_scope* s);
virtual void set_symtab_var(gm_symtab* v) {
assert(has_scope());
sym_vars = v;
}
virtual void set_symtab_field(gm_symtab* f) {
assert(has_scope());
sym_fields = f;
}
virtual void set_symtab_proc(gm_symtab* p) {
assert(has_scope());
sym_procs = p;
}
// interafce for iteration definining ast-nodes
virtual void set_iter_type(int i) {assert(false);}
virtual int get_iter_type() {assert(false);return 0;}
virtual ast_id* get_source() {assert(false);return NULL;}
virtual ast_id* get_source2() {assert(false);return NULL;}
virtual bool is_source_field() {return false;}
virtual ast_field* get_source_field() {return NULL;}
protected:
gm_symtab* sym_vars;
gm_symtab* sym_fields;
gm_symtab* sym_procs;
virtual void delete_symtabs();
virtual void create_symtabs();
public:
int get_line() {
return line;
}
int get_col() {
return col;
}
void set_line(int l) {
line = l;
}
void set_col(int c) {
col = c;
}
void copy_line_info(ast_node* n) {
this->col = n->col;
this->line = n->line;
}
//--------------------------------------
// extra infomation attached to this node
//--------------------------------------
bool has_info(const char* id);
ast_extra_info* find_info(const char*id); // returns NULL if not
bool find_info_bool(const char* id);
const char* find_info_string(const char* id);
float find_info_float(const char* id);
int find_info_int(const char* id);
void* find_info_ptr(const char* id);
void* find_info_ptr2(const char* id);
void add_info(const char* id, ast_extra_info* e);
void add_info_int(const char* id, int i);
void add_info_bool(const char* id, bool b);
void add_info_ptr(const char* id, void* ptr1, void*ptr2 = NULL);
void add_info_float(const char* id, float f);
void add_info_string(const char* id, const char* str);
void remove_info(const char* id);
void remove_all_info();
bool has_info_set(const char* id);
void add_info_set_element(const char* id, void* element);
std::set<void*>& get_info_set(const char* id);
bool has_info_list(const char* id);
void add_info_list_element(const char* id, void* element);
std::list<void*>& get_info_list(const char* id);
bool has_info_map(const char* id);
void add_info_map_key_value(const char* id, void* key, void* value);
void* find_info_map_value(const char* id, void* key);
std::map<void*, void*>& get_info_map(const char* id);
void copy_info_from(ast_node* n); // [xxx] what happens to the entry with same key?
protected:
int line;
int col;
std::map<std::string, ast_extra_info*> extra;
};
// access of identifier
class ast_typedecl;
class ast_id: public ast_node
{
friend class gm_symtab_entry;
public:
virtual ~ast_id() {
delete[] name;
delete[] gen_name; // if name is not usable in generator
}
// make a copy of id reference
// [NOTE] pointer to symbol table entry is *not* copied if cp_syminfo is false
ast_id* copy(bool cp_syminfo = false) {
ast_id* cp;
cp = new ast_id(get_orgname(), line, col); // name can be null here. [xxx] WHY?
if (cp_syminfo) {
cp->info = this->info;
}
cp->set_instant_assigned(is_instantly_assigned());
return cp;
}
//-------------------------------------------------
// Type information related to this id
// set up by type-checker during local_typecheck
//-------------------------------------------------
gm_symtab_entry* getSymInfo() {
return info;
}
void setSymInfo(gm_symtab_entry* e, bool is_symtab_entry = false) {
info = e;
if (!is_symtab_entry) use_names_from_symbol();
}
ast_typedecl* getTypeInfo(); // returns Typedecl for this id
int getTypeSummary(); // returns Typedecl for this
// return TypeDecl->getTypeSummary. returns one of GMTYPE_*
// only called for property types
ast_typedecl* getTargetTypeInfo();
int getTargetTypeSummary();
private:
ast_id() :
ast_node(AST_ID), name(NULL), info(NULL), gen_name(NULL), instant_assignment(false) {
}
ast_id(const char* org, int l, int c) :
ast_node(AST_ID), info(NULL), gen_name(NULL), instant_assignment(false) {
if (org != NULL) {
name = new char[strlen(org) + 1];
strcpy(name, org);
} else {
name = NULL;
}
set_line(l);
set_col(c);
}
public:
static ast_id* new_id(const char* org, int line, int col) {
return new ast_id(org, line, col);
}
char* get_orgname(); // returns name in GM
void set_orgname(const char* c) { // copy is saved. old name is deleted
if (name != NULL) delete[] name;
name = new char[strlen(c) + 1];
strcpy(name, c);
}
char* get_genname();
void set_genname(const char* c) { // copy is saved. old name is deleted
if (gen_name != NULL) delete[] gen_name;
gen_name = new char[strlen(c) + 1];
strcpy(gen_name, c);
}
virtual void reproduce(int id_level);
virtual void dump_tree(int id_level);
bool is_instantly_assigned() {
return instant_assignment;
}
void set_instant_assigned(bool value) {
instant_assignment = value;
}
public:
char* name;
private:
gm_symtab_entry* info;
char* gen_name;
bool instant_assignment;
char* get_orgname_from_symbol(); // gm_typecheck.cc
char* get_genname_from_symbol(); // gm_typecheck.cc
public:
void use_names_from_symbol(); // gm_typecheck.cc
};
class ast_idlist: public ast_node
{
public:
ast_idlist() :
ast_node(AST_IDLIST) {
}
virtual ~ast_idlist() {
for (int i = 0; i < (int) lst.size(); i++)
delete lst[i];
lst.clear();
}
ast_idlist* copy(bool cp_sym = false) {
ast_idlist* cpy = new ast_idlist;
for (int i = 0; i < (int) lst.size(); i++)
cpy->add_id(lst[i]->copy(cp_sym));
return cpy;
}
void add_id(ast_id* id) {
lst.push_back(id);
}
int get_length() {
return lst.size();
}
ast_id* get_item(int i) {
return lst[i];
}
virtual void apply_id(gm_apply*a, bool is_post_apply = false); // defined in traverse.cc
virtual void reproduce(int id_level);
virtual void dump_tree(int id_level);
bool contains(char* id) {
for (int i = 0; i < (int) lst.size(); i++)
if (!strcmp(id, lst[i]->get_orgname())) return true;
return false;
}
int get_line() {
assert(get_length() > 0);
return lst[0]->get_line();
}
int get_col() {
assert(get_length() > 0);
return lst[0]->get_col();
}
private:
std::vector<ast_id*> lst;
};
class ast_field: public ast_node
{ // access of node/edge property
public:
virtual ~ast_field() {
delete first;
delete second;
}
virtual void reproduce(int id_level);
virtual void dump_tree(int id_level);
private:
ast_field() :
ast_node(AST_FIELD), first(NULL), second(NULL), rarrow(false) {
}
ast_field(ast_id* l, ast_id* f) :
ast_node(AST_FIELD), first(l), second(f), rarrow(false) {
first->set_parent(this);
second->set_parent(this);
this->line = first->get_line();
this->col = first->get_col();
}
public:
static ast_field* new_field(ast_id* l, ast_id* f, bool is_r_arrow = false) {
ast_field* af = new ast_field(l, f);
af->set_rarrow(is_r_arrow);
return af;
}
// FIRST.SECOND
ast_id* get_first() { // Identifier
return first;
}
ast_id* get_second() { // Field
return second;
}
bool is_rarrow() { // Is it Edge(x).y?
return rarrow;
}
void set_rarrow(bool b) {
rarrow = b;
}
// type information about source (node/edge/graph)
int getSourceTypeSummary() {
return first->getTypeSummary();
}
ast_typedecl* getSourceTypeInfo() {
return first->getTypeInfo();
}
// type information about field (nodeprop/edgeprop)
int getTypeSummary() {
return second->getTypeSummary();
}
ast_typedecl* getTypeInfo() {
return second->getTypeInfo();
}
// type information about target (primitive)
int getTargetTypeSummary() {
return second->getTargetTypeSummary();
}
ast_typedecl* getTargetTypeInfo() {
return second->getTargetTypeInfo();
}
inline void set_first(ast_id* f) {
first = f;
f->set_parent(this);
}
inline void set_second(ast_id* s) {
second = s;
s->set_parent(this);
}
ast_field* copy(bool cp_sym = false) {
ast_id* f = first->copy(cp_sym);
ast_id* s = second->copy(cp_sym);
ast_field* fld = new ast_field(f, s);
return fld;
}
private:
ast_id* first;
ast_id* second;
bool rarrow;
};
//==========================================================================
class ast_typedecl: public ast_node
{ // property or type
protected:
ast_typedecl() :
ast_node(AST_TYPEDECL), target_type(NULL), target_graph(NULL), _well_defined(false), def_node(NULL), type_id(
0) {
}
public:
// give a deep copy, except defining node
virtual ast_typedecl* copy() {
ast_typedecl *p = new ast_typedecl();
p->type_id = this->type_id;
p->target_type = (this->target_type == NULL) ? NULL : this->target_type->copy();
p->target_graph = (this->target_graph == NULL) ? NULL : this->target_graph->copy(true);
p->def_node = this->def_node;
p->line = this->line;
p->col = this->col;
p->_well_defined = this->_well_defined;
return p;
}
virtual ~ast_typedecl() {
delete target_type;
delete target_graph; //gets deleted twice (sometimes) why??? o.O
}
static ast_typedecl* new_primtype(int ptype_id) {
ast_typedecl* t = new ast_typedecl();
t->type_id = ptype_id;
return t;
}
static ast_typedecl* new_graphtype(int gtype_id) {
ast_typedecl* t = new ast_typedecl();
t->type_id = gtype_id;
return t;
}
static ast_typedecl* new_nodetype(ast_id* tg) {
ast_typedecl* t = new ast_typedecl();
t->type_id = GMTYPE_NODE;
if (tg == NULL) //no graph defined for this node - we will handle this later (typecheck step 1)
return t;
t->target_graph = tg;
tg->set_parent(t);
return t;
}
static ast_typedecl* new_edgetype(ast_id* tg) {
ast_typedecl* t = new ast_typedecl();
t->type_id = GMTYPE_EDGE;
if (tg == NULL) //no graph defined for this edge - we will handle this later (typecheck step 1)
return t;
t->target_graph = tg;
tg->set_parent(t);
return t;
}
// node iterator, edge iterator, colllection iterator
static ast_typedecl* new_iterator(ast_id* tg, int type, ast_node* defining_node) {
assert(gm_is_iterator_type(type));
ast_typedecl* t = new ast_typedecl();
t->type_id = type;
t->def_node = defining_node;
t->target_graph = tg;
return t;
}
static ast_typedecl* new_collection(ast_id* tg, int set_type) {
assert(gm_is_simple_collection_type(set_type)); // No collection of collections
ast_typedecl* t = new ast_typedecl();
t->type_id = set_type;
if (tg == NULL) //no graph defined for this set - we will handle this later (typecheck step 1)
return t;
t->target_graph = tg;
tg->set_parent(t);
return t;
}
static ast_typedecl* new_queue(ast_id* targetGraph, ast_typedecl* collectionType) { // collection of collection
ast_typedecl* typeDecl = new ast_typedecl();
typeDecl->type_id = GMTYPE_COLLECTION_OF_COLLECTION;
typeDecl->target_type = collectionType;
if (targetGraph == NULL) return typeDecl; //no graph defined for this queue - we will handle this later (typecheck step 1)
typeDecl->target_graph = targetGraph;
targetGraph->set_parent(typeDecl);
return typeDecl;
}
static ast_typedecl* new_nodeprop(ast_typedecl* type, ast_id* tg) {
ast_typedecl* t = new ast_typedecl();
t->type_id = GMTYPE_NODEPROP;
t->target_type = type;
type->set_parent(t);
if (tg == NULL) //no graph defined for this property - we will handle this later (typecheck step 1)
return t;
t->target_graph = tg;
tg->set_parent(t);
return t;
}
static ast_typedecl* new_edgeprop(ast_typedecl* type, ast_id* tg) {
ast_typedecl* t = new ast_typedecl();
t->type_id = GMTYPE_EDGEPROP;
t->target_type = type;
type->set_parent(t);
if (tg == NULL) //no graph defined for this property - we will handle this later (typecheck step 1)
return t;
t->target_graph = tg;
tg->set_parent(t);
return t;
}
static ast_typedecl* new_void() {
ast_typedecl* t = new ast_typedecl();
t->type_id = GMTYPE_VOID;
return t;
}
virtual int get_typeid() {
return type_id;
}
void set_typeid(int s) {
type_id = s;
}
// seed gm_frontend_api.h
bool is_primitive() {
return gm_is_prim_type(type_id);
}
bool is_graph() {
return gm_is_graph_type(type_id);
}
bool is_node_property() {
return gm_is_node_property_type(type_id);
}
bool is_edge_property() {
return gm_is_edge_property_type(type_id);
}
bool is_property() {
return gm_is_property_type(type_id);
}
bool is_node() {
return gm_is_node_type(type_id);
}
bool is_edge() {
return gm_is_edge_type(type_id);
}
bool is_nodeedge() {
return gm_is_nodeedge_type(type_id);
}
bool is_collection() {
return gm_is_collection_type(type_id);
}
bool is_collection_of_collection() {
return gm_is_collection_of_collection_type(type_id);
}
bool is_node_collection() {
return gm_is_node_collection_type(type_id);
}
bool is_edge_collection() {
return gm_is_edge_collection_type(type_id);
}
bool is_iterator() {
return gm_is_iterator_type(type_id);
}
bool is_collection_iterator() {
return gm_is_collection_iterator_type(type_id);
}
bool is_node_iterator() {
return gm_is_node_iterator_type(type_id);
}
bool is_edge_iterator() {
return gm_is_edge_iterator_type(type_id);
}
bool is_node_edge_iterator() {
return is_node_iterator() || is_edge_iterator();
}
bool is_numeric() {
return gm_is_numeric_type(type_id);
}
bool is_node_compatible() {
return gm_is_node_compatible_type(type_id);
}
bool is_edge_compatible() {
return gm_is_edge_compatible_type(type_id);
}
bool is_node_edge_compatible() {
return gm_is_node_edge_compatible_type(type_id);
}
bool is_boolean() {
return gm_is_boolean_type(type_id);
}
bool requires_target_graph() {
return gm_requires_target_graph_type(type_id);
}
bool is_void() {
return gm_is_void_type(type_id);
}
bool is_sequence_collection() {
return gm_is_sequence_collection_type(type_id);
}
bool is_order_collection() {
return gm_is_order_collection_type(type_id);
}
bool is_set_collection() {
return gm_is_set_collection_type(type_id);
}
bool is_inherently_unique_collection() {
return gm_is_inherently_unique_collection_type(type_id);
}
virtual bool is_map() {
return false;
}
//---------------------------------------------------------------
// (assumption this->is_iterator): check the definining node
// defined in frontend/gm_typecheck.cc
//---------------------------------------------------------------
int get_defined_iteration_from_iterator();
ast_id* get_defined_source_from_iterator(); // to be depricated
void get_iteration_source_from_iterator(ast_id*& src_id, ast_field*& src_field);
virtual void reproduce(int id_level);
virtual void dump_tree(int id_level);
// there is no copying of type
gm_symtab_entry* get_target_graph_sym() {
if (is_collection() || is_property() || is_nodeedge() ||
is_iterator() || is_collection_of_collection()) {
assert(target_graph != NULL);
assert(target_graph->getSymInfo() != NULL);
return target_graph->getSymInfo();
} else {
printf("type = %s does not have target graph symbol\n", gm_get_type_string(type_id));
assert(false);
return NULL;
}
}
ast_id* get_target_graph_id() {
return target_graph;
}
ast_typedecl* get_target_type() {
return target_type;
}
virtual int getTypeSummary() { // same as get type id
return type_id;
}
void setTypeSummary(int s) {
// type id might be overriden during type-checking
set_typeid(s);
}
int getTargetTypeSummary() {
assert(is_property() || is_collection_of_collection());
assert(target_type != NULL);
return target_type->getTypeSummary();
}
void set_target_graph_id(ast_id* i) {
assert(target_graph == NULL);
assert(i->getTypeInfo() != NULL);
target_graph = i;
i->set_parent(this);
}
bool is_well_defined() {
return _well_defined;
}
void set_well_defined(bool b) {
_well_defined = b;
}
// for the compiler generated symbols
// (when scope is not available)
void enforce_well_defined();
ast_node* get_definining_node() {
return def_node;
}
void set_defining_node(ast_node* n) {
def_node = n ;
}
private:
// defined in gm_frontend_api.h
ast_typedecl* target_type; // for property
ast_id* target_graph; // for property, node, edge, set
ast_node* def_node; // The foreach (bfs,reduce) statement that defines this iterator
protected:
int type_id;
bool _well_defined;
};
class ast_maptypedecl: public ast_typedecl
{
private:
ast_typedecl* keyType;
ast_typedecl* valueType;
ast_maptypedecl() :
ast_typedecl(), keyType(NULL), valueType(NULL) {
}
public:
~ast_maptypedecl() {
delete keyType;
delete valueType;
}
virtual void reproduce(int id_level);
static ast_maptypedecl* new_map(ast_typedecl* keyType, ast_typedecl* valueType) {
ast_maptypedecl* newMap = new ast_maptypedecl();
newMap->type_id = GMTYPE_MAP;
newMap->keyType = keyType;
newMap->valueType = valueType;
keyType->set_parent(newMap);
valueType->set_parent(newMap);
return newMap;
}
ast_typedecl* copy() {
ast_maptypedecl* clone = new ast_maptypedecl();
clone->type_id = type_id;
clone->keyType = (keyType == NULL) ? NULL : keyType->copy();
clone->valueType = (valueType == NULL) ? NULL : valueType->copy();
clone->line = line;
clone->col = col;
clone->_well_defined = this->_well_defined;
return clone;
}
void set_key_type(ast_typedecl* newKeyType) {
assert(gm_can_be_key_type((GMTYPE_T)newKeyType->getTypeSummary()));
keyType = newKeyType;
}
ast_typedecl* get_key_type() {
return keyType;
}
ast_typedecl* get_value_type() {
return valueType;
}
void set_value_type(ast_typedecl* newValueType) {
assert(gm_can_be_key_type((GMTYPE_T)newValueType->getTypeSummary()));
valueType = newValueType;
}
bool is_map() {
return true;
}
int get_typeid() {
return (int) GMTYPE_MAP;
}
int getTypeSummary() {
return get_typeid();
}
int getKeyTypeSummary() {
assert(keyType != NULL);
return keyType->getTypeSummary();
}
int getValueTypeSummary() {
assert(valueType != NULL);
return valueType->getTypeSummary();
}
};
//==========================================================================
class ast_sent: public ast_node
{
protected:
ast_sent(AST_NODE_TYPE y) :
ast_node(y), eline(0), _par(false) {
}
// save original empty lines before this sentence
public:
int get_empty_lines_before() {
return eline;
}
void set_empty_lines_before(int t) {
eline = t;
}
virtual void traverse(gm_apply*a, bool is_post, bool is_pre);
virtual void traverse_sent(gm_apply*a, bool is_post, bool is_pre) {
assert(false);
}
virtual bool is_sentence() {
return true;
}
// when to set this variable? (-> should be just before code gen.)
virtual bool is_under_parallel_execution() {
return _par;
}
virtual void set_under_parallel_execution(bool b) {
_par = b;
}
private:
ast_sent() :
ast_node(AST_SENT), eline(0), _par(false) {
}
int eline;
bool _par;
};
extern const char* gm_get_nodetype_string(int t);
class ast_sentblock: public ast_sent
{
public:
virtual ~ast_sentblock() {
std::list<ast_sent*>::iterator it;
for (it = sents.begin(); it != sents.end(); it++) {
delete *it;
}
delete_symtabs();
}
public:
static ast_sentblock* new_sentblock() {
return new ast_sentblock();
}
void add_sent(ast_sent* s) {
sents.push_back(s);
s->set_parent(this);
}
virtual void reproduce(int id_level);
virtual void dump_tree(int id_level);
virtual void traverse_sent(gm_apply*a, bool is_post, bool is_pre);
virtual bool has_scope() {
return true;
}
std::list<ast_sent*>& get_sents() {
return sents;
}
private:
ast_sentblock() :
ast_sent(AST_SENTBLOCK) {
create_symtabs();
}
private:
std::list<ast_sent*> sents;
};
class ast_argdecl: public ast_node
{
public:
virtual ~ast_argdecl() {
delete idlist;
delete type;
}
private:
ast_argdecl() :
ast_node(AST_ARGDECL), tc_finished(false), idlist(NULL), type(NULL) {
}
public:
static ast_argdecl* new_argdecl(ast_idlist* id, ast_typedecl* type) {
ast_argdecl* d = new ast_argdecl();
d->idlist = id;
d->type = type;
id->set_parent(d);
type->set_parent(d);
return d;
}
virtual void reproduce(int id_level);
virtual void dump_tree(int id_level);
ast_typedecl* get_type() {
if (!tc_finished) {
return type; // obtain type from syntax
} else {
return idlist->get_item(0)->getTypeInfo(); // obtain type from symbol table
}
}
ast_idlist* get_idlist() {
return idlist;
}
private:
ast_idlist* idlist;
ast_typedecl* type;
bool tc_finished; // is typecheck finished?
};
//-------------------------------------------------------
// Procedure declaration
//-------------------------------------------------------
class ast_procdef: public ast_node
{
public:
virtual ~ast_procdef() {
std::list<ast_argdecl*>::iterator it;
for (it = in_args.begin(); it != in_args.end(); it++)
delete *it;
for (it = out_args.begin(); it != out_args.end(); it++)
delete *it;
delete_symtabs();
delete id;
delete sents;
delete ret_type;
}
virtual void reproduce(int id_level);
virtual void dump_tree(int id_level);
virtual void traverse(gm_apply*a, bool is_post, bool is_pre);
virtual void apply_id(gm_apply*a, bool is_post_apply = false); // defined in traverse.cc
virtual bool has_scope() {
return true;
}
private:
ast_procdef() :
ast_node(AST_PROCDEF), id(NULL), sents(NULL), ret_type(NULL), local(false) {
create_symtabs();
}
public:
static ast_procdef* begin_new_procdef(ast_id* id) {
ast_procdef* d = new ast_procdef();
d->id = id;
id->set_parent(d);
return d;
}
void add_argdecl(ast_argdecl* d) {
in_args.push_back(d);
d->set_parent(this);
}
void add_out_argdecl(ast_argdecl* d) {
out_args.push_back(d);
d->set_parent(this);
}
void set_sentblock(ast_sentblock* s) {
sents = s;
s->set_parent(this);
}
void set_return_type(ast_typedecl* t) {
ret_type = t;
t->set_parent(this);
}
std::list<ast_argdecl*>& get_in_args() {
return in_args;
}
std::list<ast_argdecl*>& get_out_args() {
return out_args;
}
ast_sentblock* get_body() {
return sents;
}
ast_typedecl* get_return_type() {
return ret_type;
}
ast_id* get_procname() {
return id;
}
void set_local(bool b) {
local = b;
}
bool is_local() {
return local;
}
private:
ast_id* id; // function name
std::list<ast_argdecl*> in_args;
std::list<ast_argdecl*> out_args;
ast_sentblock* sents;
ast_typedecl* ret_type;
bool local;
};
//-------------------------------------------------------
// Class of Expressions
//-------------------------------------------------------
enum GMEXPR_CLASS
{
GMEXPR_IVAL, // integer literal
GMEXPR_FVAL, // floating literal
GMEXPR_BVAL, // boolean literal
GMEXPR_INF, // infinite literal
GMEXPR_NIL, // NIL literal
GMEXPR_ID, // identifier
GMEXPR_FIELD, // field access
GMEXPR_UOP, // unary op (neg)
GMEXPR_LUOP, // logical not
GMEXPR_BIOP, // numeric binary op
GMEXPR_LBIOP, // logical binary op
GMEXPR_COMP, // comparision ops (==, !=, <, >, <=, >=)
GMEXPR_REDUCE, // reduction ops (Sum, Product, Min, Max)
GMEXPR_BUILTIN, // builtin ops (NumNodes, NumNbrs, ...)
GMEXPR_BUILTIN_FIELD, //builtin ops on property entries
GMEXPR_TER, // ternary operation
GMEXPR_FOREIGN,
GMEXPR_MAPACCESS,
// foreign expression
};
// Numeric or boolean expression
class gm_builtin_def;
// defined in gm_builtin.h
class ast_expr: public ast_node
{
public:
virtual ~ast_expr() {
delete id1;
delete field;
delete left; // object is new-ed
delete right;
delete cond;
}
virtual void reproduce(int id_level);
virtual void dump_tree(int id_level);
virtual void traverse(gm_apply*a, bool is_post, bool is_pre);
virtual ast_expr* copy(bool cp_syminfo = false);
virtual bool is_expr() {
return true;
}
// factory methods
public:
static ast_expr* new_id_expr(ast_id* id) {
ast_expr* E = new ast_expr();
E->expr_class = GMEXPR_ID;
E->id1 = id;
id->set_parent(E);
return E;
}
static ast_expr* new_field_expr(ast_field* f) {
ast_expr* E = new ast_expr();
E->expr_class = GMEXPR_FIELD;
E->field = f;
f->set_parent(E);
return E;
}
static ast_expr* new_ival_expr(long ival) {
ast_expr* E = new ast_expr();
E->expr_class = GMEXPR_IVAL;
E->type_of_expression = GMTYPE_INT; // LONG?
E->ival = ival;
return E;
}
static ast_expr* new_fval_expr(double fval) {
ast_expr* E = new ast_expr();
E->expr_class = GMEXPR_FVAL;
E->type_of_expression = GMTYPE_FLOAT; // DOUBLE?
E->fval = fval;
return E;
}
static ast_expr* new_bval_expr(bool bval) {
ast_expr* E = new ast_expr();
E->expr_class = GMEXPR_BVAL;
E->type_of_expression = GMTYPE_BOOL;
E->bval = bval;
return E;
}
static ast_expr* new_nil_expr() {
ast_expr* E = new ast_expr();
E->expr_class = GMEXPR_NIL;
E->type_of_expression = GMTYPE_NIL_UNKNOWN;
return E;
}
static ast_expr* new_inf_expr(bool is_p) {
ast_expr* E = new ast_expr();
E->expr_class = GMEXPR_INF;
E->type_of_expression = GMTYPE_INF;
E->plus_inf = is_p;
return E;
}
static ast_expr* new_typeconv_expr(int target_type, ast_expr* l) {
ast_expr* E = new ast_expr();
E->expr_class = GMEXPR_UOP;
E->op_type = GMOP_TYPEC;
E->type_of_expression = target_type; // GMTYPE_xxx
E->left = l;
l->up = E;
l->parent = E;
return E;
}
static ast_expr* new_uop_expr(int op_type, ast_expr* l) {
ast_expr* E = new ast_expr();
E->expr_class = GMEXPR_UOP;
E->op_type = op_type;
E->type_of_expression = GMTYPE_UNKNOWN_NUMERIC;
E->left = l;
l->up = E;
l->parent = E;
return E;
}
static ast_expr* new_biop_expr(int op_type, ast_expr* l, ast_expr* r) {
ast_expr* E = new ast_expr();
E->expr_class = GMEXPR_BIOP;
E->op_type = op_type;
E->left = l;
E->right = r;
l->up = E;
r->up = E;
r->is_right = true;
E->type_of_expression = GMTYPE_UNKNOWN_NUMERIC;
l->parent = r->parent = E;
return E;
}
static ast_expr* new_luop_expr(int op_type, ast_expr* l) {
ast_expr* E = new ast_expr();
E->expr_class = GMEXPR_LUOP;
E->op_type = op_type;
E->type_of_expression = GMTYPE_BOOL;
E->left = l;
l->up = E;
l->parent = E;
return E;
}
static ast_expr* new_lbiop_expr(int op_type, ast_expr* l, ast_expr* r) {
ast_expr* E = new ast_expr();
E->expr_class = GMEXPR_LBIOP;
E->op_type = op_type;
E->left = l;
E->right = r;
l->up = E;
r->up = E;
r->is_right = true;
E->type_of_expression = GMTYPE_BOOL;
l->parent = r->parent = E;
return E;
}
static ast_expr* new_comp_expr(int op_type, ast_expr* l, ast_expr* r) {
ast_expr* E = new ast_expr();
E->expr_class = GMEXPR_COMP;
E->op_type = op_type;
E->left = l;
E->right = r;
l->up = E;
r->up = E;
r->is_right = true;
E->type_of_expression = GMTYPE_BOOL;
l->parent = r->parent = E;
return E;
}
static ast_expr* new_ternary_expr(ast_expr* cond, ast_expr* left, ast_expr* right) {
ast_expr* E = new ast_expr();
E->expr_class = GMEXPR_TER;
E->op_type = GMOP_TER;
E->left = left;
E->right = right;
E->cond = cond;
cond->up = left->up = right->up = E;
cond->parent = left->parent = right->parent = E;
right->is_right = cond->is_cond = true;
return E;
}
protected:
ast_expr() :
ast_node(AST_EXPR), expr_class(GMEXPR_ID), left(NULL), right(NULL), cond(NULL), up(NULL), id1(NULL), field(NULL), ival(0), fval(0), bval(false), plus_inf(
false), op_type(GMOP_END), is_right(false), is_cond(false), type_of_expression(GMTYPE_UNKNOWN), alternative_type_of_expression(
GMTYPE_UNKNOWN), bound_graph_sym(NULL) {
}
GMEXPR_CLASS expr_class; // GMEXPR_...
ast_expr* left;
ast_expr* right;
ast_expr* cond;
ast_expr* up;
ast_id* id1;
ast_field* field;
long ival;
double fval;
bool bval;
bool plus_inf;
int op_type;
bool is_right; // am I a right-operand?
bool is_cond; // am I a conditional-operand?
int type_of_expression; // set after local typecheck
int alternative_type_of_expression; // used for group-assignment only. (during type checking)
public:
bool is_biop() {
return (expr_class == GMEXPR_BIOP) || (expr_class == GMEXPR_LBIOP);
}
bool is_uop() {
return (expr_class == GMEXPR_UOP) || (expr_class == GMEXPR_LUOP);
}
bool is_comp() {
return (expr_class == GMEXPR_COMP);
}
bool is_id() {
return expr_class == GMEXPR_ID;
}
bool is_nil() {
return expr_class == GMEXPR_NIL;
}
bool is_field() {
return expr_class == GMEXPR_FIELD;
}
bool is_int_literal() {
return expr_class == GMEXPR_IVAL;
}
bool is_float_literal() {
return expr_class == GMEXPR_FVAL;
}
bool is_boolean_literal() {
return expr_class == GMEXPR_BVAL;
}
bool is_inf() {
return expr_class == GMEXPR_INF;
}
bool is_literal() {
return is_int_literal() || is_float_literal() || is_boolean_literal() || is_inf();
}
bool is_reduction() {
return expr_class == GMEXPR_REDUCE;
}
bool is_builtin() {
return expr_class == GMEXPR_BUILTIN || expr_class == GMEXPR_BUILTIN_FIELD;
}
bool is_terop() {
return expr_class == GMEXPR_TER;
}
bool is_foreign() {
return expr_class == GMEXPR_FOREIGN;
}
virtual bool is_mapaccess() {
return false;
}
//-----------------------------------------------
// type is set after type-checker execution
//-----------------------------------------------
int get_type_summary() {
return type_of_expression;
}
void set_type_summary(int t) {
type_of_expression = t;
} // set by type checker
gm_symtab_entry* get_bound_graph() {
if (bound_graph_sym == NULL && is_id())
return id1->getTypeInfo()->get_target_graph_sym();
else
return bound_graph_sym;
}
void set_bound_graph(gm_symtab_entry*e) {
bound_graph_sym = e;
}
long get_ival() {
return ival;
}
double get_fval() {
return fval;
}
bool get_bval() {
return bval;
}
bool is_plus_inf() {
return is_inf() && plus_inf;
} // true o
virtual ast_id* get_id() {
return id1;
}
virtual ast_field* get_field() {
return field;
}
virtual GMEXPR_CLASS get_opclass() {
return expr_class;
}
virtual int get_optype() {
return op_type;
}
bool is_right_op() {
return is_right;
}
bool is_cond_op() {
return is_cond;
}
void set_id(ast_id* i) {
id1 = i;
if (i != NULL) {
i->set_parent(this);
expr_class = GMEXPR_ID;
}
}
void set_field(ast_field* f) {
field = f;
if (f != NULL) {
f->set_parent(this);
expr_class = GMEXPR_FIELD;
}
}
bool is_type_conv() {
return op_type == GMOP_TYPEC;
}
ast_expr* get_left_op() {
return left;
}
ast_expr* get_right_op() {
return right;
}
ast_expr* get_up_op() {
return up;
} // same to parent. but expr
ast_expr* get_cond_op() {
return cond;
}
void set_left_op(ast_expr* l) {
left = l;
if (l != NULL) {
l->set_parent(this);
l->set_up_op(this);
}
}
void set_right_op(ast_expr* r) {
right = r;
if (r != NULL) {
r->set_parent(this);
r->set_up_op(this);
}
}
void set_up_op(ast_expr* e) {
up = e;
}
void set_cond_op(ast_expr* e) {
cond = e;
if (e != NULL) {
e->set_parent(this);
e->set_up_op(this);
}
}
void set_alternative_type(int i) {
alternative_type_of_expression = i;
}
int get_alternative_type() {
return alternative_type_of_expression;
}
void set_expr_class(GMEXPR_CLASS ec) {
expr_class = ec;
}
protected:
gm_symtab_entry* bound_graph_sym; // used only during typecheck
};
class ast_mapaccess: public ast_node
{
private:
ast_id* mapId;
ast_expr* keyExpr;
gm_symtab_entry* keyGraph;
gm_symtab_entry* valueGraph;
ast_mapaccess() :
ast_node(AST_MAPACCESS), mapId(NULL), keyExpr(NULL), keyGraph(NULL), valueGraph(NULL) {
}
ast_mapaccess(ast_id* map, ast_expr* key) :
ast_node(AST_MAPACCESS), mapId(map), keyExpr(key), keyGraph(NULL), valueGraph(NULL) {
}
public:
~ast_mapaccess() {
delete mapId;
delete keyExpr;
}
virtual void dump_tree(int i);
virtual void reproduce(int i);
ast_mapaccess* copy(bool cp_sym = false) {
ast_mapaccess* clone = new ast_mapaccess();
clone->mapId = mapId->copy(cp_sym);
clone->keyExpr = keyExpr->copy(cp_sym);
return clone;
}
ast_id* get_map_id() {
assert(mapId != NULL);
return mapId;
}
ast_expr* get_key_expr() {
assert(keyExpr != NULL);
return keyExpr;
}
gm_symtab_entry* get_bound_graph_for_key() {
return keyGraph;
}
void set_bound_graph_for_key(gm_symtab_entry* graphEntry) {
keyGraph = graphEntry;
}
gm_symtab_entry* get_bound_graph_for_value() {
return valueGraph;
}
void set_bound_graph_for_value(gm_symtab_entry* graphEntry) {
valueGraph = graphEntry;
}
static ast_mapaccess* new_mapaccess(ast_id* map, ast_expr* key) {
ast_mapaccess* newMapAccess = new ast_mapaccess(map, key);
assert(newMapAccess->keyExpr != NULL);
return newMapAccess;
}
};
class ast_expr_mapaccess: public ast_expr
{
private:
ast_mapaccess* mapAccess;
ast_expr_mapaccess() :
ast_expr(), mapAccess(NULL) {
set_nodetype(AST_EXPR_MAPACCESS);
}
ast_expr_mapaccess(ast_mapaccess* mapAccess, int line, int column) :
ast_expr(), mapAccess(mapAccess) {
set_nodetype(AST_EXPR_MAPACCESS);
set_line(line);
set_col(column);
}
public:
~ast_expr_mapaccess() {
delete mapAccess;
}
ast_expr_mapaccess* copy(bool cp_sym = false) {
ast_expr_mapaccess* clone = new ast_expr_mapaccess();
clone->mapAccess = mapAccess->copy(cp_sym);
return clone;
}
virtual void reproduce(int ind_level);
bool is_mapaccess() {
return true;
}
int get_optype() {
return (int) GMOP_MAPACCESS;
}
GMEXPR_CLASS get_opclass() {
return GMEXPR_MAPACCESS;
}
ast_id* get_id() {
return mapAccess->get_map_id();
}
ast_mapaccess* get_mapaccess() {
assert(mapAccess != NULL);
return mapAccess;
}
static ast_expr_mapaccess* new_expr_mapaccess(ast_mapaccess* mapAccess, int line, int column) {
ast_expr_mapaccess* newMapAccess = new ast_expr_mapaccess(mapAccess, line, column);
return newMapAccess;
}
};
class ast_expr_foreign: public ast_expr
{
public:
~ast_expr_foreign() {
std::list<ast_node*>::iterator I;
for (I = parsed_gm.begin(); I != parsed_gm.end(); I++) {
delete *I;
}
delete[] orig_text;
}
static ast_expr_foreign* new_expr_foreign(char* text) {
ast_expr_foreign* aef = new ast_expr_foreign();
aef->expr_class = GMEXPR_FOREIGN;
aef->orig_text = gm_strdup(text);
aef->type_of_expression = GMTYPE_FOREIGN_EXPR;
return aef;
}
virtual void traverse(gm_apply*a, bool is_post, bool is_pre);
virtual void reproduce(int id_level);
std::list<ast_node*>& get_parsed_nodes() {
return parsed_gm;
}
std::list<std::string>& get_parsed_text() {
return parsed_foreign;
}
void parse_foreign_syntax();
private:
ast_expr_foreign() :
orig_text(NULL) {
set_nodetype(AST_EXPR_FOREIGN);
}
char* orig_text;
// parsed foreign syntax
std::list<ast_node*> parsed_gm;
std::list<std::string> parsed_foreign;
void apply_id(gm_apply*a, bool apply2);
void apply_rhs(gm_apply*a, bool apply2);
};
class ast_expr_builtin: public ast_expr
{
public:
virtual ~ast_expr_builtin() {
delete[] orgname;
delete driver;
std::list<ast_expr*>::iterator I;
for (I = args.begin(); I != args.end(); I++)
delete *I;
}
virtual void reproduce(int id_level);
virtual void dump_tree(int id_level);
virtual void traverse(gm_apply*a, bool is_post, bool is_pre);
virtual ast_expr* copy(bool cp_syminfo = false);
virtual bool driver_is_field() {
return false;
}
virtual int get_source_type() {
return (driver == NULL) ? GMTYPE_VOID : driver->getTypeSummary();
}
virtual int get_source_iteration() {
return (driver == NULL) ? GMITER_ANY :
(driver->getTypeInfo()->is_iterator()) ?
driver->getTypeInfo()->get_defined_iteration_from_iterator():
GMITER_ANY;
}
static ast_expr_builtin* new_builtin_expr(ast_id* id, const char* orgname, expr_list* t) {
ast_expr_builtin* E = new ast_expr_builtin();
E->expr_class = GMEXPR_BUILTIN;
E->driver = id;
if (id != NULL) id->set_parent(E); // type unknown yet.
E->orgname = gm_strdup(orgname);
if (t != NULL) {
E->args = t->LIST; // shallow copy LIST
// but not set 'up' pointer.
std::list<ast_expr*>::iterator I;
for (I = E->args.begin(); I != E->args.end(); I++)
(*I)->set_parent(E);
delete t; // t is only temporary, delete it.
}
return E;
}
// defined in gm_builtin.cc
static ast_expr_builtin* new_builtin_expr(ast_id* id, gm_builtin_def* d, expr_list* t);
char* get_orgname() {
return orgname;
}
char* get_callname() {
return orgname;
}
virtual ast_id* get_driver() {
return driver;
}
void set_driver(ast_id* i) {
driver = i;
i->set_parent(this);
}
std::list<ast_expr*>& get_args() {
return args;
}
gm_builtin_def* get_builtin_def() {
return def;
}
void set_builtin_def(gm_builtin_def* d) {
def = d;
}
protected:
ast_expr_builtin() :
ast_expr(), driver(NULL), orgname(NULL), def(NULL) {
set_nodetype(AST_EXPR_BUILTIN);
}
protected:
ast_id* driver; // canbe null
char* orgname;
std::list<ast_expr*> args;
gm_builtin_def* def;
};
class ast_expr_builtin_field: public ast_expr_builtin
{
public:
virtual void reproduce(int id_level);
~ast_expr_builtin_field() {
delete field_driver;
}
ast_id* get_driver() {
assert(false);
return NULL;
}
bool driver_is_field() {
return true;
}
ast_field* get_field_driver() {
return field_driver;
}
ast_field* get_field() {
return field_driver;
}
int get_source_type() {
assert(field_driver != NULL);
return field_driver->get_second()->getTargetTypeInfo()->getTypeSummary();
}
static ast_expr_builtin_field* new_builtin_field_expr(ast_field* field, const char* orgname, expr_list* exList) {
ast_expr_builtin_field* newExpression = new ast_expr_builtin_field();
newExpression->expr_class = GMEXPR_BUILTIN_FIELD;
newExpression->field_driver = field;
newExpression->orgname = gm_strdup(orgname);
if (field != NULL) {
field->set_parent(newExpression); // type unknown yet.
}
if (exList != NULL) {
newExpression->args = exList->LIST; // shallow copy LIST
// but not set 'up' pointer.
std::list<ast_expr*>::iterator iter;
for (iter = newExpression->args.begin(); iter != newExpression->args.end(); iter++)
(*iter)->set_parent(newExpression);
delete exList; // t is only temporary, delete it.
}
return newExpression;
}
private:
ast_expr_builtin_field() :
ast_expr_builtin(), field_driver(NULL) {
}
ast_field* field_driver;
};
// Reduction expression
class ast_expr_reduce: public ast_expr
{
public:
~ast_expr_reduce() {
delete iter;
delete body;
delete filter;
delete src;
delete src2;
delete src_field;
delete_symtabs();
}
static ast_expr_reduce*
new_reduce_expr(int optype, ast_id* iter, ast_id* src, int iter_op, ast_expr* body, ast_expr* filter = NULL) {
ast_expr_reduce *e = new ast_expr_reduce();
e->iter = iter;
e->body = body;
e->filter = filter;
e->src = src;
e->expr_class = GMEXPR_REDUCE;
e->reduce_type = optype;
e->iter_type = iter_op;
e->is_src_field = false;
iter->set_parent(e);
src->set_parent(e);
body->set_parent(e);
body->set_up_op(e);
if (filter != NULL) {
filter->set_parent(e);
filter->set_up_op(e);
}
return e;
}
static ast_expr_reduce*
new_reduce_expr(int optype, ast_id* iter, ast_field* src_fld, int iter_op, ast_expr* body, ast_expr* filter = NULL) {
ast_expr_reduce *e = new ast_expr_reduce();
e->iter = iter;
e->body = body;
e->filter = filter;
e->src_field = src_fld;
e->expr_class = GMEXPR_REDUCE;
e->reduce_type = optype;
e->iter_type = iter_op;
e->is_src_field = true;
iter->set_parent(e);
src_fld->set_parent(e);
body->set_parent(e);
body->set_up_op(e);
if (filter != NULL) {
filter->set_parent(e);
filter->set_up_op(e);
}
return e;
}
virtual void reproduce(int id_level);
virtual void dump_tree(int id_level);
virtual void traverse(gm_apply*a, bool is_post, bool is_pre);
virtual bool has_scope() {
return true;
}
virtual int get_iter_type() {
return iter_type;
}
virtual void set_iter_type(int i) {
iter_type = i;
}
int get_reduce_type() {
return reduce_type;
}
virtual ast_id* get_source() {
assert(is_src_field == false);
return src;
}
virtual ast_field* get_source_field() {
assert(is_src_field == true);
return src_field;
}
virtual bool is_source_field() {
return is_src_field;
}
ast_id* get_iterator() {
return iter;
}
ast_expr* get_filter() {
return filter;
}
ast_expr* get_body() {
return body;
}
virtual ast_id* get_source2() {
return src2;
}
void set_source2(ast_id* i) {
src2 = i;
if (i != NULL) { i->set_parent(this);}
}
void set_filter(ast_expr* e) {
filter = e;
if (e != NULL) e->set_parent(this);
}
void set_body(ast_expr* e) {
body = e;
if (e != NULL) e->set_parent(this);
}
virtual ast_expr* copy(bool cp_syminfo = false);
private:
ast_expr_reduce() :
ast_expr(), iter(NULL), src(NULL), src2(NULL), body(NULL), filter(NULL), reduce_type(GMREDUCE_NULL), iter_type(0), src_field(NULL), is_src_field(false) {
set_nodetype(AST_EXPR_RDC);
create_symtabs();
}
ast_id* iter;
ast_id* src;
ast_id* src2;
ast_expr* body;
ast_expr* filter;
int reduce_type;
int iter_type;
bool is_src_field;
ast_field* src_field;
};
//-------------------------------------------------------
// Assignments
//-------------------------------------------------------
enum gm_assignment_t
{
GMASSIGN_NORMAL, GMASSIGN_REDUCE, GMASSIGN_DEFER, GMASSIGN_INVALID
};
enum gm_assignment_location_t
{
GMASSIGN_LHS_SCALA, GMASSIGN_LHS_FIELD, GMASSIGN_LHS_MAP, GMASSIGN_LHS_END
};
class ast_assign_mapentry;
class ast_assign: public ast_sent
{
public:
virtual ~ast_assign() {
delete lhs_scala;
delete lhs_field;
delete rhs;
delete bound;
}
public:
static ast_assign* new_assign_scala(ast_id* id, ast_expr* r, int assign_type = GMASSIGN_NORMAL, ast_id* itor = NULL, int reduce_type = GMREDUCE_NULL) {
// assign to scala
ast_assign* A = new ast_assign();
A->lhs_scala = id;
A->rhs = r;
id->set_parent(A);
r->set_parent(A);
A->lhs_type = GMASSIGN_LHS_SCALA;
if (itor != NULL) {
itor->set_parent(A);
}
A->bound = itor;
A->assign_type = assign_type; // normal, reduced, or deferred
A->reduce_type = reduce_type; // reduce or defer type
return A;
}
static ast_assign* new_assign_field(ast_field* id, ast_expr* r, int assign_type = GMASSIGN_NORMAL, ast_id* itor = NULL, int reduce_type = GMREDUCE_NULL) {
// assign to property
ast_assign* A = new ast_assign();
A->lhs_field = id;
A->rhs = r;
id->set_parent(A);
r->set_parent(A);
A->lhs_type = GMASSIGN_LHS_FIELD;
if (itor != NULL) {
itor->set_parent(A);
}
A->bound = itor;
A->assign_type = assign_type;
A->reduce_type = reduce_type;
return A;
}
virtual void reproduce(int id_level);
virtual void traverse_sent(gm_apply*a, bool is_post, bool is_pre);
virtual void dump_tree(int id_level);
int get_assign_type() {
return assign_type;
}
virtual int get_lhs_type() {
return lhs_type;
}
int get_reduce_type() {
return reduce_type;
}
void set_assign_type(int a) {
assign_type = a;
}
void set_reduce_type(int a) {
reduce_type = a;
}
ast_id* get_lhs_scala() {
return lhs_scala;
}
ast_field* get_lhs_field() {
return lhs_field;
}
ast_expr* get_rhs() {
return rhs;
}
ast_id* get_bound() {
return bound;
}
void set_bound(ast_id* i) {
bound = i;
if (bound != NULL) i->set_parent(this);
}
bool is_reduce_assign() {
return assign_type == GMASSIGN_REDUCE;
}
bool is_defer_assign() {
return assign_type == GMASSIGN_DEFER;
}
virtual bool is_target_scalar() {
return get_lhs_type() == GMASSIGN_LHS_SCALA;
}
virtual bool is_target_field() {
return get_lhs_type() == GMASSIGN_LHS_FIELD;
}
virtual bool is_target_map_entry() {
return false;
}
void set_rhs(ast_expr* r) {
rhs = r;
rhs->set_parent(this);
}
bool is_argminmax_assign() {
return arg_minmax;
}
void set_argminmax_assign(bool b) {
arg_minmax = b;
}
bool has_lhs_list() {
return l_list.size() > 0;
}
std::list<ast_node*>& get_lhs_list() {
return l_list;
}
std::list<ast_expr*>& get_rhs_list() {
return r_list;
}
void set_lhs_list(std::list<ast_node*>& L) {
l_list = L;
}
void set_rhs_list(std::list<ast_expr*>& R) {
r_list = R;
}
void set_lhs_scala(ast_id* new_id) {
lhs_scala = new_id;
if (new_id != NULL) lhs_type = GMASSIGN_LHS_SCALA;
}
void set_lhs_field(ast_field* new_id) {
lhs_field = new_id;
if (new_id != NULL) lhs_type = GMASSIGN_LHS_FIELD;
}
virtual bool is_map_entry_assign() {
return false;
}
virtual ast_assign_mapentry* to_assign_mapentry() {
assert(false);
return NULL;
}
void set_is_reference(bool is_ref) {
isReference = is_ref;
}
bool is_reference() {
return isReference;
}
protected:
ast_assign() :
ast_sent(AST_ASSIGN), lhs_scala(NULL), lhs_field(NULL), rhs(NULL), bound(NULL), arg_minmax(false), lhs_type(0), assign_type(0), reduce_type(0), isReference(false) {
}
private:
int assign_type; // normal, deferred, reduce
int lhs_type; // scalar, field
int reduce_type; // add, mult, min, max
ast_id* lhs_scala;
ast_field* lhs_field;
ast_id* bound; // bounding iterator
bool arg_minmax;
bool isReference;
std::list<ast_node*> l_list;
std::list<ast_expr*> r_list;
protected:
ast_expr* rhs;
};
class ast_assign_mapentry : public ast_assign {
private:
ast_mapaccess* lhs;
ast_assign_mapentry(ast_mapaccess* lhs, ast_expr* rhs) : ast_assign(), lhs(lhs) {
this->rhs = rhs;
}
ast_assign_mapentry(ast_mapaccess* lhs, ast_expr* rhs, int reduceType) : ast_assign(), lhs(lhs) {
this->rhs = rhs;
set_reduce_type(reduceType);
set_assign_type(GMASSIGN_REDUCE);
}
public:
~ast_assign_mapentry() {
delete lhs;
}
virtual void reproduce(int indLevel);
void traverse_sent(gm_apply*a, bool is_post, bool is_pre);
bool is_map_entry_assign() {
return true;
}
bool is_target_map_entry() {
return true;
}
bool is_target_scalar() {
return false;
}
virtual int get_lhs_type() {
return GMASSIGN_LHS_MAP;
}
ast_assign_mapentry* to_assign_mapentry() {
return this;
}
ast_mapaccess* get_lhs_mapaccess() {
return lhs;
}
static ast_assign_mapentry* new_mapentry_assign(ast_mapaccess* lhs, ast_expr* rhs) {
ast_assign_mapentry* newAssign = new ast_assign_mapentry(lhs, rhs);
return newAssign;
}
static ast_assign_mapentry* new_mapentry_reduce_assign(ast_mapaccess* lhs, ast_expr* rhs, int reduceType) {
ast_assign_mapentry* newAssign = new ast_assign_mapentry(lhs, rhs, reduceType);
return newAssign;
}
};
class ast_vardecl: public ast_sent
{
public:
virtual ~ast_vardecl() {
delete idlist;
delete type;
//assert(init_expr == NULL);
}
private:
ast_vardecl() :
ast_sent(AST_VARDECL), idlist(NULL), type(NULL), init_expr(NULL), tc_finished(false) {
}
public:
void set_typechecked(bool b) {
tc_finished = b;
}
static ast_vardecl* new_vardecl(ast_typedecl* type, ast_idlist* id) {
ast_vardecl* d = new ast_vardecl();
d->idlist = id;
d->type = type;
id->set_parent(d);
type->set_parent(d);
return d;
}
static ast_vardecl* new_vardecl(ast_typedecl* type, ast_id* id) {
ast_vardecl* d = new ast_vardecl();
ast_idlist* idl = new ast_idlist();
idl->add_id(id);
d->idlist = idl;
d->type = type;
idl->set_parent(d);
type->set_parent(d);
return d;
}
static ast_vardecl* new_vardecl_init(ast_typedecl* type, ast_id* id, ast_expr* init) {
ast_vardecl* d = new ast_vardecl();
ast_idlist* idl = new ast_idlist();
idl->add_id(id);
d->idlist = idl;
d->type = type;
d->init_expr = init;
id->set_parent(d);
type->set_parent(d);
if (init != NULL) init->set_parent(d);
id->set_instant_assigned(check_instant_assignment(type, init));
return d;
}
virtual void traverse_sent(gm_apply*a, bool is_post, bool is_pre);
virtual void reproduce(int id_level);
virtual void dump_tree(int id_level);
ast_idlist* get_idlist() {
return idlist;
}
ast_typedecl* get_type() {
if (!tc_finished)
return type; // obtain type from syntax
else
return idlist->get_item(0)->getTypeInfo(); // obtain type from symbol table
}
ast_expr* get_init() {
return init_expr;
}
void set_init(ast_expr* v) {
init_expr = v;
if (v != NULL) v->set_parent(this);
}
bool is_tc_finished() {
return tc_finished;
}
void set_tc_finished(bool b) {
tc_finished = b;
} // who calls it?
private:
ast_idlist* idlist;
ast_typedecl* type;
ast_expr* init_expr; // for syntax sugar.
bool tc_finished;
static bool check_instant_assignment(ast_typedecl* type, ast_expr* init) {
if (init == NULL || type == NULL) return false;
if (!type->is_collection()) return false;
if (!init->is_field()) return false;
return true;
}
};
class ast_return: public ast_sent
{
protected:
ast_return() :
ast_sent(AST_RETURN), expr(NULL) {
}
ast_expr* expr;
public:
~ast_return() {
delete expr;
}
static ast_return* new_return(ast_expr* e) {
ast_return* R = new ast_return();
R->expr = e;
if (e != NULL) e->set_parent(R);
return R;
}
ast_expr* get_expr() {
return expr;
}
void set_expr(ast_expr*e) {
expr = e;
if (e != NULL) e->set_parent(this);
}
virtual void reproduce(int id_level);
virtual void dump_tree(int id_level);
virtual void traverse_sent(gm_apply*a, bool is_post, bool is_pre);
};
class ast_foreach: public ast_sent
{
public:
virtual ~ast_foreach() {
delete body;
delete iterator;
delete source;
delete source2;
delete source_field;
delete cond;
//delete symbol info
delete_symtabs();
}
private:
ast_foreach() :
ast_sent(AST_FOREACH), body(NULL), iterator(NULL), source(NULL), source2(NULL), cond(NULL), seq_exe(false), use_reverse(false), iter_type(0) , source_field(NULL), is_src_field(false) {
create_symtabs();
}
public:
static ast_foreach* new_foreach(ast_id* it, ast_id* src, ast_sent* b, int iter_type, ast_expr* cond = NULL) {
ast_foreach* d = new ast_foreach();
d->iterator = it;
d->source = src;
d->body = b;
d->iter_type = iter_type;
d->cond = cond;
d->is_src_field = false;
src->set_parent(d);
it->set_parent(d);
b->set_parent(d);
if (cond != NULL) cond->set_parent(d);
return d;
}
static ast_foreach* new_foreach(ast_id* it, ast_field* src_field, ast_sent* b, int iter_type, ast_expr* cond = NULL) {
ast_foreach* d = new ast_foreach();
d->iterator = it;
d->source_field = src_field;
d->body = b;
d->iter_type = iter_type;
d->cond = cond;
d->is_src_field = true;
src_field->set_parent(d);
it->set_parent(d);
b->set_parent(d);
if (cond != NULL) cond->set_parent(d);
return d;
}
virtual void reproduce(int id_level);
virtual void dump_tree(int id_level);
virtual void traverse_sent(gm_apply*a, bool is_post, bool is_pre);
virtual bool is_source_field() {
return is_src_field;
}
virtual ast_field* get_source_field() {
assert(is_src_field);
return source_field;
}
virtual ast_id* get_source() {
assert(!is_src_field);
return source;
}
ast_id* get_iterator() {
return iterator;
}
void set_iterator(ast_id* newIterator) {
iterator = newIterator;
}
ast_sent* get_body() {
return body;
}
ast_expr* get_filter() {
return cond;
}
virtual int get_iter_type() {
return iter_type;
} // GM_ITERATORS
virtual void set_iter_type(int i) {
iter_type = i;
} // GM_ITERATORS
virtual ast_id* get_source2() {
return source2;
}
void set_source2(ast_id* i) {
source2 = i;
if (i != NULL) i->set_parent(this);
}
void set_filter(ast_expr* expr = NULL) {
cond = expr;
if (cond != NULL) cond->set_parent(this);
}
void set_body(ast_sent* s) {
body = s;
assert(body != NULL);
body->set_parent(this);
}
virtual bool has_scope() {
return true;
}
virtual bool is_under_parallel_execution() {
return is_parallel(); // realy?
}
// For is sequential, Foreach is parallel.
// Optimization may override parallel execution with sequential.
// sequential execution
virtual bool is_sequential() {
return seq_exe;
}
virtual void set_sequential(bool b) {
seq_exe = b;
}
// parallel execution
virtual bool is_parallel() {
return !is_sequential();
}
// for set iterator
bool is_reverse_iteration() {
return use_reverse;
}
void set_reverse_iteration(bool b) {
use_reverse = b;
}
private:
ast_sent* body;
ast_id* iterator;
ast_id* source; // graph
ast_id* source2; // common nbr
ast_field* source_field;
int iter_type; // GM_ITERATORS
ast_expr* cond;
bool seq_exe;
bool use_reverse;
bool is_src_field;
};
// BFS or DFS
class ast_bfs: public ast_sent
{
public:
~ast_bfs() {
delete f_body;
delete b_body;
delete f_filter;
delete b_filter;
delete navigator;
delete iter;
delete src;
delete root;
//delete iter2;
delete_symtabs();
}
static ast_bfs* new_bfs(ast_id* it, ast_id* src, ast_id* root, ast_expr* navigator, ast_expr* f_filter, ast_expr* b_filter, ast_sentblock* fb,
ast_sentblock* bb, bool use_tp, bool is_bfs = true) {
ast_bfs* d = new ast_bfs();
d->iter = it;
d->src = src;
d->root = root;
d->f_body = fb;
d->b_body = bb;
d->use_transpose = use_tp;
d->b_filter = b_filter;
d->f_filter = f_filter;
d->navigator = navigator;
d->_bfs = is_bfs;
src->set_parent(d);
it->set_parent(d);
root->set_parent(d);
if (fb != NULL) fb->set_parent(d);
if (bb != NULL) bb->set_parent(d);
if (navigator != NULL) navigator->set_parent(d);
if (f_filter != NULL) f_filter->set_parent(d);
if (b_filter != NULL) b_filter->set_parent(d);
return d;
}
ast_sentblock* get_fbody() {
return f_body;
}
ast_sentblock* get_bbody() {
return b_body;
}
ast_expr* get_navigator() {
return navigator;
}
ast_expr* get_f_filter() {
return f_filter;
}
ast_expr* get_b_filter() {
return b_filter;
}
ast_id* get_iterator() {
return iter;
}
//ast_id* get_iterator2() {
// return iter2;
//}
virtual ast_id* get_source() {
return src;
}
virtual ast_id* get_source2() {
return get_root();
}
ast_id* get_root() {
return root;
}
bool is_transpose() {
return use_transpose;
}
bool is_bfs() {
return _bfs;
}
//void set_iterator2(ast_id* id) {
// assert(iter2 == NULL);
// iter2 = id;
//}
void set_navigator(ast_expr* e) {
if (e != NULL) e->set_parent(this);
navigator = e;
}
void set_f_filter(ast_expr* e) {
if (e != NULL) e->set_parent(this);
f_filter = e;
}
void set_b_filter(ast_expr* e) {
if (e != NULL) e->set_parent(this);
b_filter = e;
}
void set_fbody(ast_sentblock* b) {
if (b != NULL) b->set_parent(this);
f_body = b;
}
void set_bbody(ast_sentblock* b) {
if (b != NULL) b->set_parent(this);
b_body = b;
}
virtual void reproduce(int id_level);
virtual void dump_tree(int id_level);
virtual void traverse_sent(gm_apply*a, bool is_post, bool is_pre);
virtual int get_iter_type() {
return GMITER_NODE_BFS;
}
//int get_iter_type2() {
// return is_transpose() ? GMTYPE_NODEITER_IN_NBRS : GMTYPE_NODEITER_NBRS;
//}
virtual bool has_scope() {
return true;
}
// currently BFS is always parallel. (codegen assumes there is only one BFS. also flip-edge opt does)
bool is_sequential() {
return !is_bfs();
} // sequential execution
bool is_parallel() {
return is_bfs();
} // sequential execution
protected:
ast_bfs() :
ast_sent(AST_BFS), f_body(NULL), b_body(NULL), f_filter(NULL), b_filter(NULL), navigator(NULL), iter(NULL), src(NULL), root(NULL), use_transpose(false), _bfs(true) {
create_symtabs();
}
private:
ast_sentblock* f_body;
ast_sentblock* b_body;
ast_expr* f_filter;
ast_expr* b_filter;
ast_expr* navigator;
ast_id* iter;
ast_id* src;
ast_id* root;
//ast_id* iter2; // iterator used for frontier expansion [xxx] what?
bool use_transpose;
bool _bfs;
};
class ast_call: public ast_sent
{
public:
virtual ~ast_call() {
delete b_in;
}
virtual void reproduce(int id_level);
virtual void dump_tree(int id_level);
virtual void traverse_sent(gm_apply*a, bool is_post, bool is_pre);
static ast_call* new_builtin_call(ast_expr_builtin* b) {
ast_call* C = new ast_call();
b->set_parent(C);
C->b_in = b;
C->is_blt_in = true;
return C;
}
private:
ast_call() :
ast_sent(AST_CALL), b_in(NULL), is_blt_in(false) {
}
public:
ast_expr_builtin* get_builtin() {
return b_in;
}
void set_builtin(ast_expr_builtin* b) {
b_in = b;
assert(b_in != NULL);
b_in->set_parent(this);
}
bool is_builtin_call() {
return is_blt_in;
}
private:
ast_expr_builtin* b_in;
bool is_blt_in;
};
class ast_if: public ast_sent
{
public:
virtual ~ast_if() {
delete cond;
delete then_part;
delete else_part;
}
private:
ast_if() :
ast_sent(AST_IF), then_part(NULL), else_part(NULL), cond(NULL) {
}
public:
static ast_if* new_if(ast_expr* c, ast_sent* t, ast_sent* e) {
ast_if* ifs = new ast_if();
ifs->then_part = t;
ifs->else_part = e;
ifs->cond = c;
c->set_parent(ifs);
t->set_parent(ifs);
if (e != NULL) e->set_parent(ifs);
return ifs;
}
virtual void reproduce(int id_level);
virtual void dump_tree(int id_level);
virtual void traverse_sent(gm_apply*a, bool is_post, bool is_pre);
ast_sent* get_then() {
return then_part;
}
ast_sent* get_else() {
return else_part;
}
ast_expr* get_cond() {
return cond;
}
void set_then(ast_sent* s) {
if (s!=NULL) s->set_parent(this);
then_part = s;
}
void set_else(ast_sent* s) {
if (s!=NULL) s->set_parent(this);
else_part = s;
}
void set_cond(ast_expr* c) {
cond = c;
if (c != NULL) c->set_parent(this);
}
private:
ast_sent* then_part;
ast_sent* else_part;
ast_expr* cond;
};
class ast_foreign: public ast_sent
{
public:
virtual ~ast_foreign() {
delete expr;
std::list<ast_node*>::iterator I;
for (I = modified.begin(); I != modified.end(); I++)
delete *I;
}
static ast_foreign* new_foreign(ast_expr_foreign* f) {
ast_foreign* S = new ast_foreign();
S->set_expr(f);
f->set_parent(S);
return (S);
}
static ast_foreign* new_foreign_mutate(ast_expr_foreign* f, lhs_list* l) {
ast_foreign* S = new ast_foreign();
S->set_expr(f);
f->set_parent(S);
std::list<ast_node*>&L = l->LIST;
std::list<ast_node*>::iterator I;
for (I = L.begin(); I != L.end(); I++) {
ast_node* n = *I;
n->set_parent(S);
S->modified.push_back(n);
}
delete l;
return (S);
}
virtual void reproduce(int id_level);
virtual void traverse_sent(gm_apply*a, bool is_post, bool is_pre);
virtual void dump_tree(int id_level) {
}
std::list<ast_node*>& get_modified() {
return modified;
}
ast_expr_foreign* get_expr() {
return expr;
}
void set_expr(ast_expr_foreign* f) {
expr = f;
}
private:
ast_foreign() :
ast_sent(AST_FOREIGN), expr(NULL) {
}
ast_expr_foreign* expr;
std::list<ast_node*> modified;
};
class ast_while: public ast_sent
{
public:
virtual ~ast_while() {
delete body;
delete cond;
}
private:
ast_while() :
ast_sent(AST_WHILE), body(NULL), cond(NULL), do_while(false) {
}
public:
static ast_while* new_while(ast_expr* c, ast_sentblock* s) {
ast_while* w = new ast_while();
w->cond = c;
w->body = s;
w->do_while = false;
c->set_parent(w);
s->set_parent(w);
return w;
}
static ast_while* new_do_while(ast_expr* c, ast_sentblock* s) {
ast_while* w = new ast_while();
w->cond = c;
w->body = s;
w->do_while = true;
c->set_parent(w);
s->set_parent(w);
return w;
}
// rotuines that should be implemented
virtual void reproduce(int id_level);
virtual void dump_tree(int id_level);
virtual void traverse_sent(gm_apply*a, bool is_post, bool is_pre);
ast_sent* get_body() {
return body;
}
ast_expr* get_cond() {
return cond;
}
bool is_do_while() {
return do_while;
}
void set_body(ast_sentblock* s) {
body = s;
}
void set_cond(ast_expr* e) {
cond = e;
if (e != NULL) {
e->set_parent(this);
}
}
private:
ast_sentblock* body;
ast_expr* cond;
bool do_while; // if true do_while, else while
};
// a dummy nop IR.
// May be used in back-end processing
class gm_symtab_entry;
//class gm_rwinfo;
//typedef std::list<gm_rwinfo*> gm_rwinfo_list;
//typedef std::map<gm_symtab_entry*, gm_rwinfo_list*> gm_rwinfo_map;
class ast_nop: public ast_sent
{
protected:
ast_nop() :
ast_sent(AST_NOP), subtype(0) {
}
ast_nop(int t) :
ast_sent(AST_NOP) {
set_subtype(t);
}
public:
virtual ~ast_nop() {
}
int get_subtype() {
return subtype;
}
void set_subtype(int s) {
subtype = s;
}
virtual void reproduce(int id_level);
virtual void dump_tree(int id_level);
virtual void traverse_sent(gm_apply*a, bool is_post, bool is_pre) {
}
virtual bool do_rw_analysis() {
return true;
}
private:
int subtype;
};
#endif
| 24.941735 | 196 | 0.583369 | [
"object",
"vector"
] |
9b36163cd2d5c23f0beabdec69f891835e2cedf9 | 3,677 | h | C | Crow/src/Platform/GraphicAPI/OpenGL/OpenGLShader.h | quesswho/Crow | c57df8fe6dc323acd2c5e7b14b0b65d34b4a6e94 | [
"Apache-2.0"
] | null | null | null | Crow/src/Platform/GraphicAPI/OpenGL/OpenGLShader.h | quesswho/Crow | c57df8fe6dc323acd2c5e7b14b0b65d34b4a6e94 | [
"Apache-2.0"
] | 5 | 2020-02-16T10:43:15.000Z | 2020-05-02T20:24:01.000Z | Crow/src/Platform/GraphicAPI/OpenGL/OpenGLShader.h | quesswho/Crow | c57df8fe6dc323acd2c5e7b14b0b65d34b4a6e94 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include "Crow/Common.h"
#include "Crow/Graphics/Renderer/BufferProp.h"
#include "Crow/Math/Maths.h"
#include <string>
#include <unordered_map>
#include <vector>
namespace Crow {
namespace Platform {
class OpenGLShader {
public:
enum class ShaderType { UNKNOWN = -1, VERTEX = 0, FRAGMENT = 1 };
enum class UniformType
{
UNKNOWN = -1,
INT,
FLOAT,
FLOAT2,
FLOAT3,
FLOAT4,
MAT2,
MAT3,
MAT4
};
struct TempUniform {
TempUniform(const std::string& name, UniformType type)
: m_Name(name), m_Type(type)
{}
const std::string m_Name;
UniformType m_Type;
};
struct TempShaderUniformStruct {
TempShaderUniformStruct(const std::string& name, std::vector<TempUniform> uniforms, int size)
: m_Name(name), m_Uniforms(uniforms), m_Size(size)
{}
const std::string m_Name;
std::vector<TempUniform> m_Uniforms;
int m_Size;
};
struct Uniform {
Uniform(int location, UniformType type)
: m_Location(location), m_Type(type)
{}
int m_Location;
UniformType m_Type;
};
struct ShaderUniformStruct {
ShaderUniformStruct(std::string& name, std::vector<Uniform> uniforms, int size)
: m_Name(name), m_Uniforms(uniforms), m_Size(size)
{}
std::string m_Name;
std::vector<Uniform> m_Uniforms;
int m_Size;
};
private:
uint m_ShaderID;
const char* m_Name;
std::unordered_map<const char*, int> m_UniformLocations;
std::vector<ShaderUniformStruct> m_UniformStructs;
std::unordered_map<std::string, int> m_UniformStructLocations;
public:
explicit OpenGLShader(const char* name, const char* path, const BufferProperties& shaderInput); // File path
explicit OpenGLShader(const char* name, std::string& source, const BufferProperties& shaderInput); // Shader code
~OpenGLShader();
static OpenGLShader* CreateFromPath(const char* name, const char* path, const BufferProperties& shaderInput) { return new OpenGLShader(name, path, shaderInput); }
static OpenGLShader* CreateFromSource(const char* name, std::string& source, const BufferProperties& shaderInput) { return new OpenGLShader(name, source, shaderInput); }
void Bind() const;
void Unbind() const;
void ReloadFromPath(const char* path);
void ReloadFromSource(std::string& source);
void CreateConstantBuffers() {}
const char* GetName() const { return m_Name; }
void SetUniformValue(const char* location, const int value);
void SetUniformValue(const char* location, const float value);
void SetUniformValue(const char* location, const Math::TVec2<float>& value);
void SetUniformValue(const char* location, const Math::TVec3<float>& value);
void SetUniformValue(const char* location, const Math::TVec4<float>& value);
void SetUniformValue(const char* location, const Math::Mat2& value);
void SetUniformValue(const char* location, const Math::Mat3& value);
void SetUniformValue(const char* location, const Math::Mat4& value);
void SetUniformStruct(const char* location, void* data);
inline uint GetHandle() const { return m_ShaderID; }
private:
static int StringToUniformTypeSize(std::string_view string);
static UniformType StringToUniformType(std::string_view string);
static int UniformTypeToUniformTypeSize(UniformType type);
static inline float BytesToFloat(BYTE* bytes)
{
float result;
memcpy(&result, bytes, 4);
return result;
}
void Init(std::string& fileSource);
void CompileShader(const char* vertex, const char* fragment);
void FindUniformStructs(std::string& source);
int GetLocation(const char* location);
};
}
} | 28.952756 | 172 | 0.707642 | [
"vector"
] |
9b3bf66a57e86b97f4473d5aa4027cf143221b97 | 1,270 | h | C | src/NodeIteratorImp.h | esrille/escudo | 1ba68f6930f1ddb97385a5b488644b6dfa132152 | [
"Apache-2.0"
] | 29 | 2015-01-25T15:12:02.000Z | 2021-12-01T17:58:17.000Z | src/NodeIteratorImp.h | esrille/escudo | 1ba68f6930f1ddb97385a5b488644b6dfa132152 | [
"Apache-2.0"
] | null | null | null | src/NodeIteratorImp.h | esrille/escudo | 1ba68f6930f1ddb97385a5b488644b6dfa132152 | [
"Apache-2.0"
] | 7 | 2015-04-15T02:05:21.000Z | 2020-06-16T03:53:37.000Z | // Generated by esidl 0.3.0.
// This file is expected to be modified for the Web IDL interface
// implementation. Permission to use, copy, modify and distribute
// this file in any software license is hereby granted.
#ifndef ORG_W3C_DOM_BOOTSTRAP_NODEITERATORIMP_H_INCLUDED
#define ORG_W3C_DOM_BOOTSTRAP_NODEITERATORIMP_H_INCLUDED
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <org/w3c/dom/traversal/NodeIterator.h>
#include <org/w3c/dom/Node.h>
#include <org/w3c/dom/traversal/NodeFilter.h>
namespace org
{
namespace w3c
{
namespace dom
{
namespace bootstrap
{
class NodeIteratorImp : public ObjectMixin<NodeIteratorImp>
{
public:
// NodeIterator
Node getRoot();
Node getReferenceNode();
bool getPointerBeforeReferenceNode();
unsigned int getWhatToShow();
traversal::NodeFilter getFilter();
Node nextNode();
Node previousNode();
void detach();
// Object
virtual Any message_(uint32_t selector, const char* id, int argc, Any* argv)
{
return traversal::NodeIterator::dispatch(this, selector, id, argc, argv);
}
static const char* const getMetaData()
{
return traversal::NodeIterator::getMetaData();
}
};
}
}
}
}
#endif // ORG_W3C_DOM_BOOTSTRAP_NODEITERATORIMP_H_INCLUDED
| 23.090909 | 81 | 0.729921 | [
"object"
] |
9b42347e049c993ad729db659c7e7fa16beb63db | 6,125 | h | C | src/include/H5Fed_model.h | greole/H5hut | 7833ed7877b7578b1ec3308ba2b465fc54d0c582 | [
"BSD-3-Clause-LBNL"
] | 1 | 2020-01-12T14:01:55.000Z | 2020-01-12T14:01:55.000Z | src/include/H5Fed_model.h | greole/H5hut | 7833ed7877b7578b1ec3308ba2b465fc54d0c582 | [
"BSD-3-Clause-LBNL"
] | null | null | null | src/include/H5Fed_model.h | greole/H5hut | 7833ed7877b7578b1ec3308ba2b465fc54d0c582 | [
"BSD-3-Clause-LBNL"
] | 2 | 2019-06-04T08:40:40.000Z | 2020-01-10T21:25:42.000Z | /*
Copyright (c) 2006-2016, The Regents of the University of California,
through Lawrence Berkeley National Laboratory (subject to receipt of any
required approvals from the U.S. Dept. of Energy) and the Paul Scherrer
Institut (Switzerland). All rights reserved.
License: see file COPYING in top level of source distribution.
*/
#ifndef __H5FED_MODEL_H
#define __H5FED_MODEL_H
#include "h5core/h5_types.h"
#include "h5core/h5_log.h"
#include "h5core/h5t_model.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
Get number of meshes of tetrahedral meshes in file.
\return number of tetrahedral meshes
\return \c H5_FAILURE
*/
static inline h5_ssize_t
H5FedGetNumTetrahedralMeshes (
const h5_file_t f ///< file object
) {
H5_API_ENTER (h5_err_t,
"f=%p",
(h5_file_p)f);
H5_API_RETURN (h5t_get_num_tetmeshes (f));
}
static inline h5_ssize_t
H5FedGetNumTriangleMeshes (
const h5_file_t f
) {
H5_API_ENTER (h5_err_t,
"f=%p",
(h5_file_p)f);
H5_API_RETURN (h5t_get_num_trimeshes (f));
}
/**
Get the number of hierarchical mesh levels.
\return Number of hierarchical mesh levels or error code.
*/
static inline h5_ssize_t
H5FedGetNumLevels (
h5t_mesh_t* const m ///< [in] mesh object
) {
H5_API_ENTER (h5_ssize_t, "m=%p", m);
H5_API_RETURN (h5t_get_num_leaf_levels (m));
}
/**
Get current mesh levels.
\return ID of current mesh levels or error code.
*/
static inline h5_lvl_idx_t
H5FedGetLevel (
h5t_mesh_t* const m ///< [in] mesh object
) {
H5_API_ENTER (h5_lvl_idx_t, "m=%p", m);
H5_API_RETURN (h5t_get_level (m));
}
/**
Returns the number of vertices used for defining the (sub-)mesh
at current level on this compute node.
\return Number of vertices or error code.
*/
static inline h5_ssize_t
H5FedGetNumVertices (
h5t_mesh_t* const m ///< [in] mesh object
) {
H5_API_ENTER (h5_ssize_t, "m=%p", m);
H5_API_RETURN (h5t_get_num_vertices (m, -1));
}
/**
Returns the number of vertices used for defining the (sub-)mesh
at current level on compute node \c cnode.
\return Number of vertices or error code.
*/
static inline h5_ssize_t
H5FedGetNumVerticesCnode (
h5t_mesh_t* const m, ///< [in] mesh object
const int cnode ///< [in] compute node to query
) {
H5_API_ENTER (h5_ssize_t, "m=%p, cnode=%d", m, cnode);
H5_API_RETURN (h5t_get_num_vertices (m, cnode));
}
/**
Returns the number of vertices used for defining the (sub-)mesh
at current level overl all compute nodes.
\return Total number of vertices or error code.
*/
static inline h5_ssize_t
H5FedGetNumVerticesTotal (
h5t_mesh_t* const m ///< [in] mesh object
) {
H5_API_ENTER (h5_ssize_t, "m=%p", m);
H5_API_RETURN (h5t_get_num_vertices (m, -1));
}
/**
Returns the number of elements present in the (sub-)mesh
at current level on this compute node.
\return Number of elements or error code.
*/
static inline h5_ssize_t
H5FedGetNumElements (
h5t_mesh_t* const m ///< [in] mesh object
) {
H5_API_ENTER (h5_ssize_t, "m=%p", m);
H5_API_RETURN (h5t_get_num_leaf_elems (m, -1));
}
/**
Returns the number of elements present in the (sub-)mesh
at current level on compute node \c cnode.
\return Number of elements or error code.
*/
static inline h5_ssize_t
H5FedGetNumElementsCnode (
h5t_mesh_t* const m, ///< [in] mesh object
const int cnode ///< [in] compute node to query
) {
H5_API_ENTER (h5_ssize_t, "m=%p, cnode=%d", m, cnode);
H5_API_RETURN (h5t_get_num_leaf_elems (m, cnode));
}
/**
Returns the number of elements present in the mesh
at current level over all compute nodes.
\return Number of elements or error code.
*/
static inline h5_ssize_t
H5FedGetNumElementsTotal (
h5t_mesh_t* const m ///< [in] mesh object
) {
H5_API_ENTER (h5_ssize_t, "m=%p", m);
H5_API_RETURN (h5t_get_num_leaf_elems (m, -1));
}
static inline h5_err_t
H5FedOpenTetrahedralMesh (
const h5_file_t f,
const char* name,
h5t_mesh_t** mesh
) {
H5_API_ENTER (h5_err_t,
"f=%p, name=%s, mesh=%p",
(h5_file_p)f, name, mesh);
H5_API_RETURN (h5t_open_tetrahedral_mesh (f, name, mesh));
}
static inline h5_err_t
H5FedOpenTetrahedralMeshByIndex (
const h5_file_t f,
const h5_id_t idx,
h5t_mesh_t** mesh
) {
H5_API_ENTER (h5_err_t,
"f=%p, idx=%lld, mesh=%p",
(h5_file_p)f, (long long)idx, mesh);
H5_API_RETURN (h5t_open_tetrahedral_mesh_by_idx (f, idx, mesh));
}
static inline h5_err_t
H5FedOpenTriangleMesh (
const h5_file_t f,
const char* name,
h5t_mesh_t** mesh
) {
H5_API_ENTER (h5_err_t,
"f=%p, name=%s, mesh=%p",
(h5_file_p)f, name, mesh);
H5_API_RETURN (h5t_open_triangle_mesh (f, name, mesh));
}
static inline h5_err_t
H5FedOpenTriangleMeshPart (
const h5_file_t f,
const char* name,
h5t_mesh_t** mesh,
h5_glb_idx_t* const elem_indices,
const h5_glb_idx_t num_elems
) {
H5_API_ENTER (h5_err_t,
"f=%p, name=%s, mesh=%p",
(h5_file_p)f, name, mesh);
H5_API_RETURN (h5t_open_triangle_mesh_part (f, name, mesh, elem_indices, num_elems));
}
static inline h5_err_t
H5FedOpenTriangleMeshByIndex (
const h5_file_t f,
const h5_id_t idx,
h5t_mesh_t** mesh
) {
H5_API_ENTER (h5_err_t,
"f=%p, idx=%lld, mesh=%p",
(h5_file_p)f, (long long)idx, mesh);
H5_API_RETURN (h5t_open_triangle_mesh_by_idx (f, idx, mesh));
}
static inline h5_err_t
H5FedCloseMesh (
h5t_mesh_t* const m
) {
H5_API_ENTER (h5_err_t, "m=%p", m);
H5_API_RETURN (h5t_close_mesh (m));
}
static inline h5_err_t
H5FedSetLevel (
h5t_mesh_t* const m,
const h5_lvl_idx_t level_id
) {
H5_API_ENTER (h5_err_t, "m=%p, level_id=%d", m, level_id);
H5_API_RETURN (h5t_set_level (m, level_id));
}
static inline h5_err_t
H5FedSetMeshChanged (
h5t_mesh_t* const m
) {
H5_API_ENTER (h5_err_t, "m=%p", m);
H5_API_RETURN (h5t_set_mesh_changed (m));
}
#ifdef __cplusplus
}
#endif
#endif
| 24.40239 | 86 | 0.675918 | [
"mesh",
"object"
] |
9b530d180721ec9d76bb8ae6fae53edf5a4a52c3 | 8,159 | c | C | XFree86-3.3/xc/programs/Xserver/hw/xfree86/accel/cache/xf86text.c | tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective | 1b0172cdb78757fd17898503aaf6ce03d940ef28 | [
"Apache-1.1"
] | 46 | 2015-12-04T17:12:58.000Z | 2022-03-11T04:30:49.000Z | XFree86-3.3/xc/programs/Xserver/hw/xfree86/accel/cache/xf86text.c | tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective | 1b0172cdb78757fd17898503aaf6ce03d940ef28 | [
"Apache-1.1"
] | null | null | null | XFree86-3.3/xc/programs/Xserver/hw/xfree86/accel/cache/xf86text.c | tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective | 1b0172cdb78757fd17898503aaf6ce03d940ef28 | [
"Apache-1.1"
] | 23 | 2016-10-24T09:18:14.000Z | 2022-02-25T02:11:35.000Z | /* $XFree86: xc/programs/Xserver/hw/xfree86/accel/cache/xf86text.c,v 3.1 1996/12/23 06:33:22 dawes Exp $ */
/*
* Copyright 1992 by Kevin E. Martin, Chapel Hill, North Carolina.
*
* Permission to use, copy, modify, distribute, and sell this software and its
* documentation for any purpose is hereby granted without fee, provided that
* the above copyright notice appear in all copies and that both that
* copyright notice and this permission notice appear in supporting
* documentation, and that the name of Kevin E. Martin not be used in
* advertising or publicity pertaining to distribution of the software
* without specific, written prior permission. Kevin E. Martin makes no
* representations about the suitability of this software for any purpose. It
* is provided "as is" without express or implied warranty.
*
* KEVIN E. MARTIN DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
* INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
* EVENT SHALL KEVIN E. MARTIN BE LIABLE FOR ANY SPECIAL, INDIRECT OR
* CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
* USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
* OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*
*/
/* $XConsortium: xf86text.c /main/3 1996/02/21 17:19:27 kaleb $ */
/*
* Extracted from s3fcach.c and adapted to XFree86 in X11R6 by
* Hans Nasten. ( nasten@everyware.se ).
*/
#include "X.h"
#include "Xmd.h"
#include "Xproto.h"
#include "gcstruct.h"
#include "windowstr.h"
#include "fontstruct.h"
#include "dixfontstr.h"
#include "mi.h"
#include "cfb.h"
#include "misc.h"
#include "xf86.h"
#include "xf86bcache.h"
#include "xf86fcache.h"
#include "xf86text.h"
static void (*xf86GlyphWriteFunc)();
static int (*xf86NoCPolyTextFunc)();
static int (*xf86NoCImageTextFunc)();
/*
* Init the text code by storing the callback pointers.
*/
void xf86InitText( GlyphWriteFunc, NoCPolyTextFunc, NoCImageTextFunc )
void (*GlyphWriteFunc)();
int (*NoCPolyTextFunc)();
int (*NoCImageTextFunc)();
{
xf86GlyphWriteFunc = GlyphWriteFunc;
xf86NoCPolyTextFunc = NoCPolyTextFunc;
xf86NoCImageTextFunc = NoCImageTextFunc;
}
/*
* General cached PolyText8 function.
*/
static int xf86CPolyText8(pDraw, pGC, x, y, count, chars, fentry)
DrawablePtr pDraw;
GCPtr pGC;
int x;
int y;
int count;
char *chars;
CacheFont8Ptr fentry;
{
int i;
BoxPtr pBox;
int numRects;
RegionPtr pRegion;
int yBand;
int maxAscent, maxDescent;
int minLeftBearing;
FontPtr pfont = pGC->font;
int ret_x;
{
char toload[8];
for (i = 0; i < 8; i++)
toload[i] = 0;
/*
* If miPolyText8() is to be believed, the returned new X value is
* completely independent of what happens during rendering.
*/
ret_x = x;
for (i = 0; i < count; i++) {
toload[(unsigned char)(chars[i]) / 32] = 1;
ret_x += fentry->pci[(unsigned char)(chars[i])] ?
fentry->pci[(unsigned char)(chars[i])]->metrics.characterWidth : 0;
}
for (i = 0; i < 8; i++)
if (toload[i]) {
if ((fentry->fblock[i]) == NULL) {
xf86loadFontBlock(fentry, i);
}
}
}
x += pDraw->x;
y += pDraw->y;
maxAscent = FONTMAXBOUNDS(pfont, ascent);
maxDescent = FONTMAXBOUNDS(pfont, descent);
minLeftBearing = FONTMINBOUNDS(pfont, leftSideBearing);
pRegion = ((cfbPrivGC *) (pGC->devPrivates[cfbGCPrivateIndex].ptr))->pCompositeClip;
pBox = REGION_RECTS(pRegion);
numRects = REGION_NUM_RECTS(pRegion);
while (numRects && pBox->y2 <= y - maxAscent) {
++pBox;
--numRects;
}
if (!numRects || pBox->y1 >= y + maxDescent)
return ret_x;
yBand = pBox->y1;
while (numRects && pBox->y1 == yBand && pBox->x2 <= x + minLeftBearing) {
++pBox;
--numRects;
}
if (numRects)
(xf86GlyphWriteFunc)(x, y, count, chars, fentry, pGC, pBox, numRects);
return ret_x;
}
/*
* General cached ImageText8 function.
*/
static int xf86CImageText8(pDraw, pGC, x, y, count, chars, fentry)
DrawablePtr pDraw;
GCPtr pGC;
int x;
int y;
int count;
char *chars;
CacheFont8Ptr fentry;
{
ExtentInfoRec info; /* used by QueryGlyphExtents() */
XID gcvals[3];
int oldAlu, oldFS;
unsigned long oldFG;
xRectangle backrect;
CharInfoPtr *ppci;
unsigned long n;
if (!(ppci = (CharInfoPtr *) ALLOCATE_LOCAL(count * sizeof(CharInfoPtr))))
return 0;
GetGlyphs(pGC->font, (unsigned long)count, (unsigned char *)chars,
Linear8Bit, &n, ppci);
QueryGlyphExtents(pGC->font, ppci, n, &info);
DEALLOCATE_LOCAL(ppci);
if (info.overallWidth >= 0) {
backrect.x = x;
backrect.width = info.overallWidth;
} else {
backrect.x = x + info.overallWidth;
backrect.width = -info.overallWidth;
}
backrect.y = y - FONTASCENT(pGC->font);
backrect.height = FONTASCENT(pGC->font) + FONTDESCENT(pGC->font);
oldAlu = pGC->alu;
oldFG = pGC->fgPixel;
oldFS = pGC->fillStyle;
/* fill in the background */
gcvals[0] = GXcopy;
gcvals[1] = pGC->bgPixel;
gcvals[2] = FillSolid;
DoChangeGC(pGC, GCFunction | GCForeground | GCFillStyle, gcvals, 0);
ValidateGC(pDraw, pGC);
(*pGC->ops->PolyFillRect) (pDraw, pGC, 1, &backrect);
/* put down the glyphs */
gcvals[0] = oldFG;
DoChangeGC(pGC, GCForeground, gcvals, 0);
ValidateGC(pDraw, pGC);
(void)xf86CPolyText8(pDraw, pGC, x, y, count, chars, fentry);
/* put all the toys away when done playing */
gcvals[0] = oldAlu;
gcvals[1] = oldFG;
gcvals[2] = oldFS;
DoChangeGC(pGC, GCFunction | GCForeground | GCFillStyle, gcvals, 0);
return 0;
}
/*
* General PolyText8 function.
*/
int xf86PolyText8(pDraw, pGC, x, y, count, chars)
DrawablePtr pDraw;
GCPtr pGC;
int x, y;
int count;
char *chars;
{
CacheFont8Ptr ret;
if (!xf86VTSema)
{
return(miPolyText8(pDraw, pGC, x, y, count, chars));
}
/*
* The S3 graphics engine apparently can't handle these ROPs for the
* BLT operations used to render text. The 8514 and ATI don't have a
* problem using the same code that S3 uses. The common feature of these
* ROPs is that they don't reference the source pixel.
*/
if ((pGC->fillStyle != FillSolid) ||
(pGC->alu == GXclear || pGC->alu == GXinvert || pGC->alu == GXset)) {
return miPolyText8(pDraw, pGC, x, y, count, chars);
} else {
if ((ret = xf86CacheFont8(pGC->font)) == NULL)
return (xf86NoCPolyTextFunc)(pDraw, pGC, x, y, count, chars, TRUE);
else
return xf86CPolyText8(pDraw, pGC, x, y, count, chars, ret);
}
}
/*
* General PolyText16 function.
*/
int xf86PolyText16(pDraw, pGC, x, y, count, chars)
DrawablePtr pDraw;
GCPtr pGC;
int x, y;
int count;
unsigned short *chars;
{
if (!xf86VTSema ||
(pGC->fillStyle != FillSolid) ||
(pGC->alu == GXclear || pGC->alu == GXinvert || pGC->alu == GXset)) {
return miPolyText16(pDraw, pGC, x, y, count, chars);
}
return (xf86NoCPolyTextFunc)(pDraw, pGC, x, y, count, chars, FALSE);
}
/*
* General ImageText8 function.
*/
void xf86ImageText8(pDraw, pGC, x, y, count, chars)
DrawablePtr pDraw;
GCPtr pGC;
int x, y;
int count;
char *chars;
{
CacheFont8Ptr ret;
if (!xf86VTSema)
{
miImageText8(pDraw, pGC, x, y, count, chars);
return;
}
/* Don't need to check fill style here - it isn't used in image text */
if ((ret = xf86CacheFont8(pGC->font)) == NULL)
(xf86NoCImageTextFunc)(pDraw, pGC, x, y, count, chars, TRUE);
else
xf86CImageText8(pDraw, pGC, x, y, count, chars, ret);
}
/*
* General ImageText16 function.
*/
void xf86ImageText16(pDraw, pGC, x, y, count, chars)
DrawablePtr pDraw;
GCPtr pGC;
int x, y;
int count;
unsigned short *chars;
{
if (!xf86VTSema)
miImageText16(pDraw, pGC, x, y, count, chars);
else
(xf86NoCImageTextFunc)(pDraw, pGC, x, y, count, chars, FALSE);
}
| 27.657627 | 107 | 0.643951 | [
"render"
] |
9b56a728f8d7ab2a281549acffe709b8ad50b75a | 29,203 | h | C | test/e2e/test_master/wxWidgets/include/wx/combo.h | BlueCannonBall/cppparser | 9ae5f0c21268be6696532cf5b90c0384d6eb4940 | [
"MIT"
] | null | null | null | test/e2e/test_master/wxWidgets/include/wx/combo.h | BlueCannonBall/cppparser | 9ae5f0c21268be6696532cf5b90c0384d6eb4940 | [
"MIT"
] | null | null | null | test/e2e/test_master/wxWidgets/include/wx/combo.h | BlueCannonBall/cppparser | 9ae5f0c21268be6696532cf5b90c0384d6eb4940 | [
"MIT"
] | null | null | null | ///////////////////////////////////////////////////////////////////////////////
// Name: wx/combo.h
// Purpose: wxComboCtrl declaration
// Author: Jaakko Salli
// Modified by:
// Created: Apr-30-2006
// Copyright: (c) Jaakko Salli
// Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////////
#ifndef _WX_COMBOCONTROL_H_BASE_
# define _WX_COMBOCONTROL_H_BASE_
/*
A few words about all the classes defined in this file are probably in
order: why do we need extra wxComboCtrl and wxComboPopup classes?
This is because a traditional combobox is a combination of a text control
(with a button allowing to open the pop down list) with a listbox and
wxComboBox class is exactly such control, however we want to also have other
combinations - in fact, we want to allow anything at all to be used as pop
down list, not just a wxListBox.
So we define a base wxComboCtrl which can use any control as pop down
list and wxComboBox deriving from it which implements the standard wxWidgets
combobox API. wxComboCtrl needs to be told somehow which control to use
and this is done by SetPopupControl(). However, we need something more than
just a wxControl in this method as, for example, we need to call
SetSelection("initial text value") and wxControl doesn't have such method.
So we also need a wxComboPopup which is just a very simple interface which
must be implemented by a control to be usable as a popup.
We couldn't derive wxComboPopup from wxControl as this would make it
impossible to have a class deriving from both wxListBx and from it, so
instead it is just a mix-in.
*/
# include "wx/defs.h"
# if wxUSE_COMBOCTRL
# include "wx/control.h"
# include "wx/renderer.h"
# include "wx/bitmap.h"
# include "wx/textentry.h"
# include "wx/time.h"
class WXDLLIMPEXP_FWD_CORE wxTextCtrl;
class WXDLLIMPEXP_FWD_CORE wxComboPopup;
//
// New window styles for wxComboCtrlBase
//
enum
{
// Double-clicking a read-only combo triggers call to popup's OnComboPopup.
// In wxOwnerDrawnComboBox, for instance, it cycles item.
wxCC_SPECIAL_DCLICK = 0x0100,
// Dropbutton acts like standard push button.
wxCC_STD_BUTTON = 0x0200
};
// wxComboCtrl internal flags
enum
{
// First those that can be passed to Customize.
// It is Windows style for all flags to be clear.
// Button is preferred outside the border (GTK style)
wxCC_BUTTON_OUTSIDE_BORDER = 0x0001,
// Show popup on mouse up instead of mouse down (which is the Windows style)
wxCC_POPUP_ON_MOUSE_UP = 0x0002,
// All text is not automatically selected on click
wxCC_NO_TEXT_AUTO_SELECT = 0x0004,
// Drop-button stays down as long as popup is displayed.
wxCC_BUTTON_STAYS_DOWN = 0x0008,
// Drop-button covers the entire control.
wxCC_FULL_BUTTON = 0x0010,
// Drop-button goes over the custom-border (used under WinVista).
wxCC_BUTTON_COVERS_BORDER = 0x0020,
// Internal use: signals creation is complete
wxCC_IFLAG_CREATED = 0x0100,
// Internal use: really put button outside
wxCC_IFLAG_BUTTON_OUTSIDE = 0x0200,
// Internal use: SetMargins has been successfully called
wxCC_IFLAG_LEFT_MARGIN_SET = 0x0400,
// Internal use: Set wxTAB_TRAVERSAL to parent when popup is dismissed
wxCC_IFLAG_PARENT_TAB_TRAVERSAL = 0x0800,
// Internal use: Secondary popup window type should be used (if available).
wxCC_IFLAG_USE_ALT_POPUP = 0x1000,
// Internal use: Skip popup animation.
wxCC_IFLAG_DISABLE_POPUP_ANIM = 0x2000,
// Internal use: Drop-button is a bitmap button or has non-default size
// (but can still be on either side of the control), regardless whether
// specified by the platform or the application.
wxCC_IFLAG_HAS_NONSTANDARD_BUTTON = 0x4000
};
// Flags used by PreprocessMouseEvent and HandleButtonMouseEvent
enum
{
wxCC_MF_ON_BUTTON = 0x0001,
wxCC_MF_ON_CLICK_AREA = 0x0002
};
// Namespace for wxComboCtrl feature flags
struct wxComboCtrlFeatures
{
enum
{
MovableButton = 0x0001,
BitmapButton = 0x0002,
ButtonSpacing = 0x0004,
// of the control
TextIndent = 0x0008,
// left margin.
PaintControl = 0x0010,
PaintWritable = 0x0020,
// combo control's textctrl can be custom
// painted
Borderless = 0x0040,
// There are no feature flags for...
// PushButtonBitmapBackground - if its in wxRendererNative, then it should be
// not an issue to have it automatically under the bitmap.
All = MovableButton | BitmapButton | ButtonSpacing | TextIndent | PaintControl | PaintWritable | Borderless
};
};
class WXDLLIMPEXP_CORE wxComboCtrlBase : public wxControl, public wxTextEntry
{
friend class wxComboPopup;
friend class wxComboPopupEvtHandler;
public:
// ctors and such
wxComboCtrlBase()
: wxControl()
, wxTextEntry()
{
Init();
}
bool Create(wxWindow* parent, wxWindowID id, const wxString& value, const wxPoint& pos, const wxSize& size, long style, const wxValidator& validator, const wxString& name);
virtual ~wxComboCtrlBase();
// Show/hide popup window (wxComboBox-compatible methods)
virtual void Popup();
virtual void Dismiss()
{
HidePopup(true);
}
// Show/hide popup window.
// TODO: Maybe deprecate in favor of Popup()/Dismiss().
// However, these functions are still called internally
// so it is not straightforward.
virtual void ShowPopup();
virtual void HidePopup(bool generateEvent = false);
// Override for totally custom combo action
virtual void OnButtonClick();
// return true if the popup is currently shown
bool IsPopupShown() const
{
return m_popupWinState == Visible;
}
// set interface class instance derived from wxComboPopup
// NULL popup can be used to indicate default in a derived class
void SetPopupControl(wxComboPopup* popup)
{
DoSetPopupControl(popup);
}
// get interface class instance derived from wxComboPopup
wxComboPopup* GetPopupControl()
{
EnsurePopupControl();
return m_popupInterface;
}
// get the popup window containing the popup control
wxWindow* GetPopupWindow() const
{
return m_winPopup;
}
// Get the text control which is part of the combobox.
wxTextCtrl* GetTextCtrl() const
{
return m_text;
}
// get the dropdown button which is part of the combobox
// note: its not necessarily a wxButton or wxBitmapButton
wxWindow* GetButton() const
{
return m_btn;
}
// forward these methods to all subcontrols
bool Enable(bool enable = true) override;
bool Show(bool show = true) override;
bool SetFont(const wxFont& font) override;
//
// wxTextEntry methods
//
// NB: We basically need to override all of them because there is
// no guarantee how platform-specific wxTextEntry is implemented.
//
void SetValue(const wxString& value) override
{
wxTextEntryBase::SetValue(value);
}
void ChangeValue(const wxString& value) override
{
wxTextEntryBase::ChangeValue(value);
}
void WriteText(const wxString& text) override;
void AppendText(const wxString& text) override
{
wxTextEntryBase::AppendText(text);
}
wxString GetValue() const override
{
return wxTextEntryBase::GetValue();
}
wxString GetRange(long from, long to) const override
{
return wxTextEntryBase::GetRange(from, to);
}
// Replace() and DoSetValue() need to be fully re-implemented since
// EventSuppressor utility class does not work with the way
// wxComboCtrl is implemented.
void Replace(long from, long to, const wxString& value) override;
void Remove(long from, long to) override;
void Copy() override;
void Cut() override;
void Paste() override;
void Undo() override;
void Redo() override;
bool CanUndo() const override;
bool CanRedo() const override;
void SetInsertionPoint(long pos) override;
long GetInsertionPoint() const override;
long GetLastPosition() const override;
void SetSelection(long from, long to) override;
void GetSelection(long* from, long* to) const override;
bool IsEditable() const override;
void SetEditable(bool editable) override;
bool SetHint(const wxString& hint) override;
wxString GetHint() const override;
// This method sets the text without affecting list selection
// (ie. wxComboPopup::SetStringValue doesn't get called).
void SetText(const wxString& value);
// This method sets value and also optionally sends EVT_TEXT
// (needed by combo popups)
// Changes value of the control as if user had done it by selecting an
// item from a combo box drop-down list. Needs to be public so that
// derived popup classes can call it.
void SetValueByUser(const wxString& value);
//
// Popup customization methods
//
// Sets minimum width of the popup. If wider than combo control, it will extend to the left.
// Remarks:
// * Value -1 indicates the default.
// * Custom popup may choose to ignore this (wxOwnerDrawnComboBox does not).
void SetPopupMinWidth(int width)
{
m_widthMinPopup = width;
}
// Sets preferred maximum height of the popup.
// Remarks:
// * Value -1 indicates the default.
// * Custom popup may choose to ignore this (wxOwnerDrawnComboBox does not).
void SetPopupMaxHeight(int height)
{
m_heightPopup = height;
}
// Extends popup size horizontally, relative to the edges of the combo control.
// Remarks:
// * Popup minimum width may override extLeft (ie. it has higher precedence).
// * Values 0 indicate default.
// * Custom popup may not take this fully into account (wxOwnerDrawnComboBox takes).
void SetPopupExtents(int extLeft, int extRight)
{
m_extLeft = extLeft;
m_extRight = extRight;
}
// Set width, in pixels, of custom paint area in writable combo.
// In read-only, used to indicate area that is not covered by the
// focus rectangle (which may or may not be drawn, depending on the
// popup type).
void SetCustomPaintWidth(int width);
int GetCustomPaintWidth() const
{
return m_widthCustomPaint;
}
// Set side of the control to which the popup will align itself.
// Valid values are wxLEFT, wxRIGHT and 0. The default value 0 wmeans
// that the side of the button will be used.
void SetPopupAnchor(int anchorSide)
{
m_anchorSide = anchorSide;
}
// Set position of dropdown button.
// width: button width. <= 0 for default.
// height: button height. <= 0 for default.
// side: wxLEFT or wxRIGHT, indicates on which side the button will be placed.
// spacingX: empty space on sides of the button. Default is 0.
// Remarks:
// There is no spacingY - the button will be centred vertically.
void SetButtonPosition(int width = -1, int height = -1, int side = wxRIGHT, int spacingX = 0);
// Returns current size of the dropdown button.
wxSize GetButtonSize();
//
// Sets dropbutton to be drawn with custom bitmaps.
//
// bmpNormal: drawn when cursor is not on button
// pushButtonBg: Draw push button background below the image.
// NOTE! This is usually only properly supported on platforms with appropriate
// method in wxRendererNative.
// bmpPressed: drawn when button is depressed
// bmpHover: drawn when cursor hovers on button. This is ignored on platforms
// that do not generally display hover differently.
// bmpDisabled: drawn when combobox is disabled.
void SetButtonBitmaps(const wxBitmap& bmpNormal, bool pushButtonBg = false, const wxBitmap& bmpPressed = wxNullBitmap, const wxBitmap& bmpHover = wxNullBitmap, const wxBitmap& bmpDisabled = wxNullBitmap);
//
// This will set the space in pixels between left edge of the control and the
// text, regardless whether control is read-only (ie. no wxTextCtrl) or not.
// Platform-specific default can be set with value-1.
// Remarks
// * This method may do nothing on some native implementations.
wxDEPRECATED( void SetTextIndent( int indent ) );
// Returns actual indentation in pixels.
wxDEPRECATED( wxCoord GetTextIndent() const );
#endif
// Returns area covered by the text field.
const wxRect& GetTextRect() const
{
return m_tcArea;
}
// Call with enable as true to use a type of popup window that guarantees ability
// to focus the popup control, and normal function of common native controls.
// This alternative popup window is usually a wxDialog, and as such it's parent
// frame will appear as if the focus has been lost from it.
void UseAltPopupWindow(bool enable = true)
{
wxASSERT_MSG( !m_winPopup,
wxT("call this only before SetPopupControl") );
if (enable)
{
m_iFlags |= wxCC_IFLAG_USE_ALT_POPUP;
}
else
{
m_iFlags &= ~wxCC_IFLAG_USE_ALT_POPUP;
}
}
// Call with false to disable popup animation, if any.
void EnablePopupAnimation(bool enable = true)
{
if (enable)
{
m_iFlags &= ~wxCC_IFLAG_DISABLE_POPUP_ANIM;
}
else
{
m_iFlags |= wxCC_IFLAG_DISABLE_POPUP_ANIM;
}
}
//
// Utilities needed by the popups or native implementations
//
// Returns true if given key combination should toggle the popup.
// NB: This is a separate from other keyboard handling because:
// 1) Replaceability.
// 2) Centralized code (otherwise it'd be split up between
// wxComboCtrl key handler and wxVListBoxComboPopup's
// key handler).
virtual bool IsKeyPopupToggle(const wxKeyEvent& event) const = 0;
// Prepare background of combo control or an item in a dropdown list
// in a way typical on platform. This includes painting the focus/disabled
// background and setting the clipping region.
// Unless you plan to paint your own focus indicator, you should always call this
// in your wxComboPopup::PaintComboControl implementation.
// In addition, it sets pen and text colour to what looks good and proper
// against the background.
// flags: wxRendererNative flags: wxCONTROL_ISSUBMENU: is drawing a list item instead of combo control
// wxCONTROL_SELECTED: list item is selected
// wxCONTROL_DISABLED: control/item is disabled
virtual void PrepareBackground(wxDC& dc, const wxRect& rect, int flags) const;
// Returns true if focus indicator should be drawn in the control.
bool ShouldDrawFocus() const
{
const wxWindow* curFocus = FindFocus();
return (IsPopupWindowState(Hidden) && (curFocus == m_mainCtrlWnd || (m_btn && curFocus == m_btn)) && (m_windowStyle & wxCB_READONLY));
}
// These methods return references to appropriate dropbutton bitmaps
const wxBitmap& GetBitmapNormal() const
{
return m_bmpNormal;
}
const wxBitmap& GetBitmapPressed() const
{
return m_bmpPressed;
}
const wxBitmap& GetBitmapHover() const
{
return m_bmpHover;
}
const wxBitmap& GetBitmapDisabled() const
{
return m_bmpDisabled;
}
// Set custom style flags for embedded wxTextCtrl. Usually must be used
// with two-step creation, before Create() call.
void SetTextCtrlStyle(int style);
// Return internal flags
wxUint32 GetInternalFlags() const
{
return m_iFlags;
}
// Return true if Create has finished
bool IsCreated() const
{
return m_iFlags & wxCC_IFLAG_CREATED ? true : false;
}
// Need to override to return text area background colour
wxColour GetBackgroundColour() const;
// common code to be called on popup hide/dismiss
void OnPopupDismiss(bool generateEvent);
// PopupShown states
enum
{
Hidden = 0,
Closing = 1,
Animating = 2,
Visible = 3
};
bool IsPopupWindowState(int state) const
{
return (state == m_popupWinState) ? true : false;
}
wxByte GetPopupWindowState() const
{
return m_popupWinState;
}
// Set value returned by GetMainWindowOfCompositeControl
void SetCtrlMainWnd(wxWindow* wnd)
{
m_mainCtrlWnd = wnd;
}
// This is public so we can access it from wxComboCtrlTextCtrl
wxWindow* GetMainWindowOfCompositeControl() override
{
return m_mainCtrlWnd;
}
// also set the embedded wxTextCtrl colours
bool SetForegroundColour(const wxColour& colour) override;
bool SetBackgroundColour(const wxColour& colour) override;
protected:
// Returns true if hint text should be drawn in the control
bool ShouldUseHintText(int flags = 0) const
{
return (!m_text && !(flags & wxCONTROL_ISSUBMENU) && m_valueString.empty() && !m_hintText.empty() && !ShouldDrawFocus());
}
//
// Override these for customization purposes
//
// called from wxSizeEvent handler
virtual void OnResize() = 0;
// Return native text indentation
// (i.e. text margin, for pure text, not textctrl)
virtual wxCoord GetNativeTextIndent() const;
// Called in syscolourchanged handler and base create
virtual void OnThemeChange();
// Creates wxTextCtrl.
// extraStyle: Extra style parameters
void CreateTextCtrl(int extraStyle);
// Called when text was changed programmatically
// (e.g. from WriteText())
void OnSetValue(const wxString& value);
// Installs standard input handler to combo (and optionally to the textctrl)
void InstallInputHandlers();
// Flags for DrawButton
enum
{
Button_PaintBackground = 0x0001,
Button_BitmapOnly = 0x0002
};
// Draws dropbutton. Using wxRenderer or bitmaps, as appropriate.
// Flags are defined above.
virtual void DrawButton(wxDC& dc, const wxRect& rect, int flags = Button_PaintBackground);
// Call if cursor is on button area or mouse is captured for the button.
//bool HandleButtonMouseEvent( wxMouseEvent& event, bool isInside );
bool HandleButtonMouseEvent(wxMouseEvent& event, int flags);
// returns true if event was consumed or filtered (event type is also set to 0 in this case)
bool PreprocessMouseEvent(wxMouseEvent& event, int flags);
//
// This will handle left_down and left_dclick events outside button in a Windows-like manner.
// If you need alternate behaviour, it is recommended you manipulate and filter events to it
// instead of building your own handling routine (for reference, on wxEVT_LEFT_DOWN it will
// toggle popup and on wxEVT_LEFT_DCLICK it will do the same or run the popup's dclick method,
// if defined - you should pass events of other types of it for common processing).
void HandleNormalMouseEvent(wxMouseEvent& event);
// Creates popup window, calls interface->Create(), etc
void CreatePopup();
// Destroy popup window and all related constructs
void DestroyPopup();
// override the base class virtuals involved in geometry calculations
// The common version only sets a default width, so the derived classes
// should override it and set the height and change the width as needed.
wxSize DoGetBestSize() const override;
wxSize DoGetSizeFromTextSize(int xlen, int ylen = -1) const override;
// NULL popup can be used to indicate default in a derived class
virtual void DoSetPopupControl(wxComboPopup* popup);
// ensures there is at least the default popup
void EnsurePopupControl();
// Recalculates button and textctrl areas. Called when size or button setup change.
// btnWidth: default/calculated width of the dropbutton. 0 means unchanged,
// just recalculate.
void CalculateAreas(int btnWidth = 0);
// Standard textctrl positioning routine. Just give it platform-dependent
// textctrl coordinate adjustment.
virtual void PositionTextCtrl(int textCtrlXAdjust = 0, int textCtrlYAdjust = 0);
// event handlers
void OnSizeEvent(wxSizeEvent& event);
void OnFocusEvent(wxFocusEvent& event);
void OnIdleEvent(wxIdleEvent& event);
void OnTextCtrlEvent(wxCommandEvent& event);
void OnSysColourChanged(wxSysColourChangedEvent& event);
void OnKeyEvent(wxKeyEvent& event);
void OnCharEvent(wxKeyEvent& event);
// Set customization flags (directs how wxComboCtrlBase helpers behave)
void Customize(wxUint32 flags)
{
m_iFlags |= flags;
}
// Dispatches size event and refreshes
void RecalcAndRefresh();
// Flags for DoShowPopup and AnimateShow
enum
{
ShowBelow = 0x0000,
ShowAbove = 0x0001,
CanDeferShow = 0x0002
};
// Shows and positions the popup.
virtual void DoShowPopup(const wxRect& rect, int flags);
// Implement in derived class to create a drop-down animation.
// Return true if finished immediately. Otherwise popup is only
// shown when the derived class call DoShowPopup.
// Flags are same as for DoShowPopup.
virtual bool AnimateShow(const wxRect& rect, int flags);
# if wxUSE_TOOLTIPS
void DoSetToolTip(wxToolTip* tip) override;
# endif
// protected wxTextEntry methods
void DoSetValue(const wxString& value, int flags) override;
wxString DoGetValue() const override;
wxWindow* GetEditableWindow() override
{
return this;
}
// margins functions
bool DoSetMargins(const wxPoint& pt) override;
wxPoint DoGetMargins() const override;
// This is used when m_text is hidden (readonly).
wxString m_valueString;
// This is used when control is unfocused and m_valueString is empty
wxString m_hintText;
// the text control and button we show all the time
wxTextCtrl* m_text;
wxWindow* m_btn;
// wxPopupWindow or similar containing the window managed by the interface.
wxWindow* m_winPopup;
// the popup control/panel
wxWindow* m_popup;
// popup interface
wxComboPopup* m_popupInterface;
// this is input etc. handler for the text control
wxEvtHandler* m_textEvtHandler;
// this is for the top level window
wxEvtHandler* m_toplevEvtHandler;
// this is for the control in popup
wxEvtHandler* m_popupEvtHandler;
// this is for the popup window
wxEvtHandler* m_popupWinEvtHandler;
// main (ie. topmost) window of a composite control (default = this)
wxWindow* m_mainCtrlWnd;
// used to prevent immediate re-popupping in case closed popup
// by clicking on the combo control (needed because of inconsistent
// transient implementation across platforms).
wxMilliClock_t m_timeCanAcceptClick;
// how much popup should expand to the left/right of the control
wxCoord m_extLeft;
wxCoord m_extRight;
// minimum popup width
wxCoord m_widthMinPopup;
// preferred popup height
wxCoord m_heightPopup;
// how much of writable combo is custom-paint by callback?
// also used to indicate area that is not covered by "blue"
// selection indicator.
wxCoord m_widthCustomPaint;
// left margin, in pixels
wxCoord m_marginLeft;
// side on which the popup is aligned
int m_anchorSide;
// Width of the "fake" border
wxCoord m_widthCustomBorder;
// The button and textctrl click/paint areas
wxRect m_tcArea;
wxRect m_btnArea;
// Colour of the text area, in case m_text is NULL
wxColour m_tcBgCol;
// current button state (uses renderer flags)
int m_btnState;
// button position
int m_btnWid;
int m_btnHei;
int m_btnSide;
int m_btnSpacingX;
// last default button width
int m_btnWidDefault;
// custom dropbutton bitmaps
wxBitmap m_bmpNormal;
wxBitmap m_bmpPressed;
wxBitmap m_bmpHover;
wxBitmap m_bmpDisabled;
// area used by the button
wxSize m_btnSize;
// platform-dependent customization and other flags
wxUint32 m_iFlags;
// custom style for m_text
int m_textCtrlStyle;
// draw blank button background under bitmap?
bool m_blankButtonBg;
// is the popup window currently shown?
wxByte m_popupWinState;
// should the focus be reset to the textctrl in idle time?
bool m_resetFocus;
// is the text-area background colour overridden?
bool m_hasTcBgCol;
private:
void Init();
wxByte m_ignoreEvtText;
// Is popup window wxPopupTransientWindow, wxPopupWindow or wxDialog?
wxByte m_popupWinType;
wxDECLARE_EVENT_TABLE();
wxDECLARE_ABSTRACT_CLASS(wxComboCtrlBase);
};
// ----------------------------------------------------------------------------
// wxComboPopup is the interface which must be implemented by a control to be
// used as a popup by wxComboCtrl
// ----------------------------------------------------------------------------
// wxComboPopup internal flags
enum
{
wxCP_IFLAG_CREATED = 0x0001
};
class WXDLLIMPEXP_FWD_CORE wxComboCtrl;
class WXDLLIMPEXP_CORE wxComboPopup
{
friend class wxComboCtrlBase;
public:
wxComboPopup()
{
m_combo = NULL;
m_iFlags = 0;
}
// This is called immediately after construction finishes. m_combo member
// variable has been initialized before the call.
// NOTE: It is not in constructor so the derived class doesn't need to redefine
// a default constructor of its own.
virtual void Init()
{
}
virtual ~wxComboPopup();
// Create the popup child control.
// Return true for success.
virtual bool Create(wxWindow* parent) = 0;
// Calls Destroy() for the popup control (i.e. one returned by
// GetControl()) and makes sure that 'this' is deleted at the end.
// Default implementation works for both cases where popup control
// class is multiple inherited or created on heap as a separate
// object.
virtual void DestroyPopup();
// We must have an associated control which is subclassed by the combobox.
virtual wxWindow* GetControl() = 0;
// Called immediately after the popup is shown
virtual void OnPopup();
// Called when popup is dismissed
virtual void OnDismiss();
// Called just prior to displaying popup.
// Default implementation does nothing.
virtual void SetStringValue(const wxString& value);
// Gets displayed string representation of the value.
virtual wxString GetStringValue() const = 0;
// Called to check if the popup - when an item container - actually
// has matching item. Case-sensitivity checking etc. is up to the
// implementation. If the found item matched the string, but is
// different, it should be written back to pItem. Default implementation
// always return true and does not alter trueItem.
virtual bool FindItem(const wxString& item, wxString* trueItem = NULL);
// This is called to custom paint in the combo control itself (ie. not the popup).
// Default implementation draws value as string.
virtual void PaintComboControl(wxDC& dc, const wxRect& rect);
// Receives wxEVT_KEY_DOWN key events from the parent wxComboCtrl.
// Events not handled should be skipped, as usual.
virtual void OnComboKeyEvent(wxKeyEvent& event);
// Receives wxEVT_CHAR key events from the parent wxComboCtrl.
// Events not handled should be skipped, as usual.
virtual void OnComboCharEvent(wxKeyEvent& event);
// Implement if you need to support special action when user
// double-clicks on the parent wxComboCtrl.
virtual void OnComboDoubleClick();
// Return final size of popup. Called on every popup, just prior to OnShow.
// minWidth = preferred minimum width for window
// prefHeight = preferred height. Only applies if > 0,
// maxHeight = max height for window, as limited by screen size
// and should only be rounded down, if necessary.
virtual wxSize GetAdjustedSize(int minWidth, int prefHeight, int maxHeight);
// Return true if you want delay call to Create until the popup is shown
// for the first time. It is more efficient, but note that it is often
// more convenient to have the control created immediately.
// Default returns false.
virtual bool LazyCreate();
//
// Utilities
//
// Hides the popup
void Dismiss();
// Returns true if Create has been called.
bool IsCreated() const
{
return (m_iFlags & wxCP_IFLAG_CREATED) ? true : false;
}
// Returns pointer to the associated parent wxComboCtrl.
wxComboCtrl* GetComboCtrl() const;
// Default PaintComboControl behaviour
static void DefaultPaintComboControl(wxComboCtrlBase* combo, wxDC& dc, const wxRect& rect);
protected:
wxComboCtrlBase* m_combo;
wxUint32 m_iFlags;
private:
// Called in wxComboCtrlBase::SetPopupControl
void InitBase(wxComboCtrlBase* combo)
{
m_combo = combo;
}
};
// ----------------------------------------------------------------------------
// include the platform-dependent header defining the real class
// ----------------------------------------------------------------------------
# if defined(__WXUNIVERSAL__)
// No native universal (but it must still be first in the list)
# elif defined(__WXMSW__)
# include "wx/msw/combo.h"
# endif
// Any ports may need generic as an alternative
# include "wx/generic/combo.h"
# endif
#endif
// _WX_COMBOCONTROL_H_BASE_
| 38.730769 | 206 | 0.697702 | [
"geometry",
"object"
] |
9b595f9c4b7ec8bd3070666f139e0f47d24f94fb | 1,423 | h | C | src/main_window.h | daninsky1/inkbreaker | f0e32c0ff57dd5eba85226fd5db4c45293806881 | [
"MIT"
] | null | null | null | src/main_window.h | daninsky1/inkbreaker | f0e32c0ff57dd5eba85226fd5db4c45293806881 | [
"MIT"
] | null | null | null | src/main_window.h | daninsky1/inkbreaker | f0e32c0ff57dd5eba85226fd5db4c45293806881 | [
"MIT"
] | null | null | null | #pragma once
#include <iostream>
#include <sstream>
#include <cmath>
#include <vector>
#include <FL/Fl_Double_Window.H>
#include <FL/Fl_Menu_Bar.H>
#include <FL/fl_ask.h>
#include <FL/fl_show_colormap.H>
#include <FL/Fl.H>
#include <FL/filename.H>
#include <FL/Fl_Native_File_Chooser.H>
#ifdef IO_SQLITE
#include <sqlite/sqlite3.h>
#endif
#include "view2d.h"
constexpr int V2D_DEFAULT_W = 680;
constexpr int V2D_DEFAULT_H = 360;
constexpr int MENU_BAR_H = 26;
// TODO(daniel): The main window structure needs to be better thought
struct MainWindowDefaultLayout {
int v2dw = V2D_DEFAULT_W;
int v2dh = V2D_DEFAULT_H;
int menu_bar_h = MENU_BAR_H;
};
//
// CALLBACKS
//
void new_cb(Fl_Widget* widget, void *mwv);
void save_cb(Fl_Widget* widget, void *mwv);
void saveas_cb(Fl_Widget* widget, void *mwv);
void quit_cb(Fl_Widget* widget, void *mwv);
void about_cb(Fl_Widget* widget, void*);
void clear_cb(Fl_Widget* widget, void*);
//
// MAIN WINDOW
//
class MainWindow : public Fl_Double_Window {
public:
MainWindow(int v2d_w, int v2d_h);
void set_menu_items_pointer();
void set_mode();
void set_draw_state();
bool changed();
void changed(bool c);
/* Shapes */
std::vector<Shape*> shapes;
Shape* active_selection;
ShapeInfo shape_info{ 1, FL_BLACK, FL_BLUE };
/* Widgets */
Fl_Menu_Bar *menu_bar;
View2D *v2d;
/* States*/
InkbreakerState app_state = { };
};
| 20.328571 | 69 | 0.708363 | [
"shape",
"vector"
] |
9b5ba90eb20a4555c43c27837378b3f44f3768ab | 381 | c | C | test/transform/inline/inline_19.c | vladem/tsar | 3771068d47a8a258ee4a74ad5fc9c246f8aba7cb | [
"Apache-2.0"
] | null | null | null | test/transform/inline/inline_19.c | vladem/tsar | 3771068d47a8a258ee4a74ad5fc9c246f8aba7cb | [
"Apache-2.0"
] | null | null | null | test/transform/inline/inline_19.c | vladem/tsar | 3771068d47a8a258ee4a74ad5fc9c246f8aba7cb | [
"Apache-2.0"
] | null | null | null | int foo(){
int x = 45;
return x;
}
int foo_1(){
int x = 9;
return x;
}
int main(){
int i = 0;
#pragma spf transform inline
#pragma spf transform inline
i = foo() + foo_1();
return 0;
}
//CHECK: inline_19.c:14:24: warning: unexpected directive ignored
//CHECK: #pragma spf transform inline
//CHECK: ^
//CHECK: 1 warning generated.
| 15.875 | 65 | 0.585302 | [
"transform"
] |
9b6646f69fa25ea07e9591a3815d24594fbb8fcb | 1,443 | h | C | src/operators/ai.onnx/Celu/12/operator__ai_onnx__celu__12.h | ChenHuaYou/cONNXr | aa80322ec1f53d87644ba15d5c5663e726824c95 | [
"MIT"
] | null | null | null | src/operators/ai.onnx/Celu/12/operator__ai_onnx__celu__12.h | ChenHuaYou/cONNXr | aa80322ec1f53d87644ba15d5c5663e726824c95 | [
"MIT"
] | null | null | null | src/operators/ai.onnx/Celu/12/operator__ai_onnx__celu__12.h | ChenHuaYou/cONNXr | aa80322ec1f53d87644ba15d5c5663e726824c95 | [
"MIT"
] | null | null | null | //this file was generated by ../../../../../../scripts/onnx_generator/OperatorHeader.py
# ifndef OPERATOR_OPERATOR__AI_ONNX__CELU__12_H
# define OPERATOR_OPERATOR__AI_ONNX__CELU__12_H
# include "operators/operator.h"
# include "operators/operator_stub.h"
# include "operators/operator_info.h"
/**
* ai.onnx operator 'Celu' version 12
*
* @param[in] ctx Operator context
* @return Status code
*
* Continuously Differentiable Exponential Linear Units:
* Perform the linear unit element-wise on the input tensor X
* using formula:
*
* ```
* max(0,x) + min(0,alpha*(exp(x/alpha)-1))
* ```
*
* Constraint T:
* Constrain input and output types to float32 tensors.
* Allowed Types: tensor_float
* Input T X:
* Input tensor
* Allowed Types: tensor_float
* Output T Y:
* Output tensor
* Allowed Types: tensor_float
* Attribute FLOAT alpha (optional):
* The Alpha value in Celu formula which control the shape of the unit. The
* default value is 1.0.
*
* @since version 12
*
* @see io/onnx/onnx/defs/math/defs.cc:476
* @see https://github.com/onnx/onnx/blob/master/docs/Operators.md#Celu
*/
operator_status
prepare_operator__ai_onnx__celu__12(
Onnx__NodeProto *ctx
);
extern operator_info info_operator__ai_onnx__celu__12;
typedef struct {
float alpha;
} context_operator__ai_onnx__celu__12;
operator_status
execute_operator__ai_onnx__celu__12(
Onnx__NodeProto *ctx
);
# endif | 24.457627 | 87 | 0.724879 | [
"shape"
] |
9b69c79d5cdf86fb626837fc1be8ca83759ccd27 | 5,495 | h | C | src/mecs_graph.h | LIONant-depot/MECSV2 | 6599617b0789df18c344cfe70eb0d101f1b060fb | [
"MIT"
] | 1 | 2021-03-17T13:45:46.000Z | 2021-03-17T13:45:46.000Z | src/mecs_graph.h | LIONant-depot/MECSV2 | 6599617b0789df18c344cfe70eb0d101f1b060fb | [
"MIT"
] | null | null | null | src/mecs_graph.h | LIONant-depot/MECSV2 | 6599617b0789df18c344cfe70eb0d101f1b060fb | [
"MIT"
] | null | null | null | namespace mecs::graph
{
namespace details
{
struct graph_system : mecs::system::instance
{
inline graph_system ( construct&& Construct ) noexcept;
inline void msgUpdate ( void ) noexcept;
inline void msgSyncPointStart ( mecs::sync_point::instance& ) noexcept;
virtual void qt_onDone ( void ) noexcept override;
bool m_bPause{false};
};
}
struct lock_error
{
std::array<mecs::system::instance*, 2> m_pSystems;
mecs::archetype::instance* m_pArchetype;
const char* m_pMessage;
};
struct events
{
using graph_init = xcore::types::make_unique< mecs::tools::event<world::instance&>, struct graph_init_tag >;
using frame_start = xcore::types::make_unique< mecs::tools::event<>, struct frame_start_tag >;
using frame_done = xcore::types::make_unique< mecs::tools::event<>, struct frame_done_tag >;
graph_init m_GraphInit;
frame_start m_FrameStart;
frame_done m_FrameDone;
};
struct instance
{
static constexpr auto start_sync_point_v = mecs::sync_point::instance::guid{ 1ull };
static constexpr auto end_sync_point_v = mecs::sync_point::instance::guid{ 2ull };
events m_Events;
instance( mecs::world::instance& World, mecs::universe::instance& Universe )
: m_Universe { Universe }
, m_World { World }
, m_SystemDB { World }
, m_SystemGlobalEventDB { World }
, m_ArchetypeDelegateDB { World }
, m_SystemDelegateDB { World }
, m_SyncpointDB { World }
, m_StartSyncPoint { m_SyncpointDB.Create<mecs::sync_point::instance>(start_sync_point_v) }
, m_EndSyncPoint { m_SyncpointDB.Create<mecs::sync_point::instance>(end_sync_point_v) }
, m_GraphSystem { CreateGraphConnection< mecs::graph::details::graph_system >(m_EndSyncPoint, m_StartSyncPoint) }
{
}
void Play( bool bContinuousPlay ) noexcept
{
m_bContinuousPlay = bContinuousPlay;
//
// Add the graph as the core of the graph
//
XCORE_PERF_FRAME_MARK()
auto& Scheduler = xcore::get().m_Scheduler;
Scheduler.AddJobToQuantumWorld (m_GraphSystem);
Scheduler.MainThreadStartsWorking();
}
void Stop( void ) noexcept
{
m_bGraphStarted = false;
}
template< typename T_SYSTEM, typename...T_END_SYNC_POINTS >
T_SYSTEM& CreateGraphConnection( mecs::sync_point::instance& StartSyncpoint, T_END_SYNC_POINTS&...EndSyncpoints ) noexcept;
template< typename T_ARCHETYPE_DELEGATE >
T_ARCHETYPE_DELEGATE& CreateArchetypeDelegate(mecs::archetype::delegate::overrides::guid Guid = mecs::archetype::delegate::overrides::guid{ xcore::not_null }) noexcept;
template< typename T_SYSTEM_DELEGATE >
T_SYSTEM_DELEGATE& CreateSystemDelegate(mecs::system::delegate::overrides::guid Guid = mecs::system::delegate::overrides::guid{ xcore::not_null }) noexcept;
template< typename T_DELEGATE > xforceinline
auto& CreateDelegate( void ) noexcept
{
if constexpr ( std::is_base_of_v< mecs::archetype::delegate::overrides, T_DELEGATE > )
return CreateArchetypeDelegate<T_DELEGATE>();
else
return CreateSystemDelegate<T_DELEGATE>();
}
template< typename T_SYNC_POINT = mecs::sync_point::instance >
T_SYNC_POINT& CreateSyncPoint( mecs::sync_point::instance::guid Guid = mecs::sync_point::instance::guid{ xcore::not_null} ) noexcept
{
return m_SyncpointDB.Create<T_SYNC_POINT>(Guid);
}
bool m_bContinuousPlay { false };
bool m_bGraphStarted { false };
bool m_bFrameStarted { false };
std::uint64_t m_FrameNumber {0};
time m_Time {};
mecs::universe::instance& m_Universe;
mecs::world::instance& m_World;
mecs::system::instance_data_base m_SystemDB;
mecs::sync_point::instance_data_base m_SyncpointDB;
mecs::system::event::instance_data_base m_SystemGlobalEventDB;
mecs::archetype::delegate::instance_data_base m_ArchetypeDelegateDB;
mecs::system::delegate::instance_data_base m_SystemDelegateDB;
mecs::sync_point::instance& m_StartSyncPoint;
mecs::sync_point::instance& m_EndSyncPoint;
mecs::graph::details::graph_system& m_GraphSystem;
xcore::lock::object<std::vector<lock_error>, xcore::lock::spin> m_LockErrors{};
};
} | 45.791667 | 176 | 0.546133 | [
"object",
"vector"
] |
886002246c6b9b9219892447554765ee0afc9eb0 | 6,536 | h | C | SgtSim/TimeSeries.h | dexterurbane/SmartGridToolbox | ff2eb98e28b0c0ea9690ec6f522ccf1c306f79b7 | [
"Apache-2.0"
] | null | null | null | SgtSim/TimeSeries.h | dexterurbane/SmartGridToolbox | ff2eb98e28b0c0ea9690ec6f522ccf1c306f79b7 | [
"Apache-2.0"
] | null | null | null | SgtSim/TimeSeries.h | dexterurbane/SmartGridToolbox | ff2eb98e28b0c0ea9690ec6f522ccf1c306f79b7 | [
"Apache-2.0"
] | null | null | null | // Copyright 2015 National ICT Australia Limited (NICTA)
//
// 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 TIME_SERIES_DOT_H
#define TIME_SERIES_DOT_H
#include <SgtCore/ComponentCollection.h>
#if 0 // TODO: redo spline due to license issues.
#include <SgtCore/Spline.h>
#endif
#include <SgtCore/Common.h>
#include <map>
namespace Sgt
{
template<typename T> struct TsTraits
{
static double toDouble(const T& t) {return static_cast<double>(t);}
};
template<> struct TsTraits<double>
{
static double toDouble(const double& t) {return t;}
};
template<> struct TsTraits<Time>
{
static double toDouble(const Time& t) {return dSeconds(t);}
};
class TimeSeriesBase
{
public:
virtual ~TimeSeriesBase() = default;
};
/// @brief Base class for time series objects: functions of time.
/// @ingroup SimCore
template<typename T, typename V>
class TimeSeries : public TimeSeriesBase
{
public:
using TimeTipe = T;
using ValType = V;
virtual V value(const T& t) const = 0;
};
/// @brief Time series for a constant function of time.
/// @ingroup SimCore
template<typename T, typename V>
class ConstTimeSeries : public TimeSeries<T, V>
{
public:
ConstTimeSeries(const V& val) {val_ = val;}
virtual V value(const T& t) const {return val_;}
private:
V val_;
};
/// @brief Base class for TimeSeries object that stores a time/value table.
/// @ingroup SimCore
template<typename T, typename V>
class DataTimeSeries : public TimeSeries<T, V>
{
public:
DataTimeSeries(const V& defaultV) : defaultV_(defaultV) {}
virtual void addPoint(const T& t, const V& v) {points_[t] = v;}
auto begin() const {return points_.begin();};
auto end() const {return points_.end();};
auto rbegin() const {return points_.rbegin();};
auto rend() const {return points_.rend();};
/// @brief Iterator to element with largest key <= t, or rend if no such key exists.
auto lowerBound(const T& t) const
{
// NOTE: Careful with this code.
// See the definition of map::upper_bound and map::lower_bound, which might be different to
// what one would expect.
// Also note, const_reverse_iterator(iterator) constructor shifts back by 1.
return typename decltype(points_)::const_reverse_iterator(points_.upper_bound(t));
}
/// @brief Iterator to element with smallest key >= t, or rend if no such key exists.
auto upperBound(const T& t) const
{
// NOTE: Careful with this code.
// See the definition of map::upper_bound and map::lower_bound, which might be different to
// what one would expect.
return points_.lower_bound(t);
}
void removePoint(const typename std::map<T, V>::const_iterator& it) {points_.erase(it);}
void removePoints(const typename std::map<T, V>::const_iterator& a,
const typename std::map<T, V>::const_iterator& b) {points_.erase(a, b);}
protected:
std::map<T, V> points_;
V defaultV_;
};
/// @brief TimeSeries that changes in a stepwise manner between tabulated times.
/// @ingroup SimCore
template<typename T, typename V>
class StepwiseTimeSeries : public DataTimeSeries<T, V>
{
protected:
using DataTimeSeries<T, V>::points_;
using DataTimeSeries<T, V>::defaultV_;
public:
StepwiseTimeSeries(const V& defaultV) : DataTimeSeries<T, V>(defaultV) {}
virtual V value(const T& t) const override
{
return (points_.size() == 0 || t < points_.begin()->first || t > points_.rbegin()->first)
? defaultV_
: (--points_.upper_bound(t))->second; // Highest point <= t.
}
};
/// @brief TimeSeries that uses linear interpolation between tabulated times.
/// @ingroup SimCore
template<typename T, typename V>
class LerpTimeSeries : public DataTimeSeries<T, V>
{
protected:
using DataTimeSeries<T, V>::points_;
using DataTimeSeries<T, V>::defaultV_;
public:
LerpTimeSeries(const V& defaultV) : DataTimeSeries<T, V>(defaultV) {}
virtual V value(const T& t) const override
{
if (points_.size() == 0 || t < points_.begin()->first || t > points_.rbegin()->first) return defaultV_;
auto pos2 = points_.upper_bound(t);
// pos2 -> first point > s. It can't be begin, but could be end (if t == last point).
if (pos2 == points_.end())
{
return points_.rbegin()->second;
}
else
{
// We now know that t is strictly inside the range.
auto pos1 = pos2; --pos1;
return pos1->second + (pos2->second - pos1->second) * TsTraits<T>::toDouble(t - pos1->first) /
TsTraits<T>::toDouble(pos2->first - pos1->first);
}
}
};
/// @brief TimeSeries that uses a std::function to calculate values.
/// @ingroup SimCore
template<typename T, typename V>
class FunctionTimeSeries : public TimeSeries<T, V>
{
public:
FunctionTimeSeries<T, V>(const std::function<V (T)>& func) :
func_(func)
{
// Empty.
}
virtual V value(const T& t) const override
{
return func_(t);
}
private:
std::function<V (T)> func_;
};
template<typename T> using TimeSeriesPtr = ComponentPtr<TimeSeriesBase, T>;
template<typename T> using ConstTimeSeriesPtr = ConstComponentPtr<TimeSeriesBase, T>;
}
// TODO: Reinstate SplineTimeSeries that was removed due to license issues.
#endif // TIME_SERIES_DOT_H
| 32.844221 | 115 | 0.604957 | [
"object"
] |
88607d050215965fd8fd4a581e811cc3871096a7 | 955 | h | C | editor/echo/Editor/UI/TextEditor/Area/TextEditorArea.h | Texas-C/echo | 486acc57c9149363206a2367c865a2ccbac69975 | [
"MIT"
] | 675 | 2019-02-07T01:23:19.000Z | 2022-03-28T05:45:10.000Z | editor/echo/Editor/UI/TextEditor/Area/TextEditorArea.h | Texas-C/echo | 486acc57c9149363206a2367c865a2ccbac69975 | [
"MIT"
] | 843 | 2019-01-25T01:06:46.000Z | 2022-03-16T11:15:53.000Z | editor/echo/Editor/UI/TextEditor/Area/TextEditorArea.h | blab-liuliang/Echo | ba75816e449d2f20a375ed44b0f706a6b7bc21a1 | [
"MIT"
] | 83 | 2019-02-20T06:18:46.000Z | 2022-03-20T09:36:09.000Z | #pragma once
#include <QMainWindow>
#include "TextEditor.h"
#include "ui_TextEditorArea.h"
namespace Studio
{
class TextEditorArea : public QDockWidget, public Ui_TextEditorArea
{
Q_OBJECT
public:
TextEditorArea(QWidget* parent = 0);
~TextEditorArea();
// open lua file
void open(const Echo::String& fullPath, bool isRememberOpenStates=true);
// get tab index
bool getTabIndex(const Echo::String& fullPath, int& index);
// remember|recover script open states
void rememberScriptOpenStates();
void recoverScriptOpenStates();
public slots:
// save
void save();
// on tab index changed
void onTabIdxChanged(int idx);
// on lua editor title changed
void onTextEditorTitleChanged(TextEditor* editor);
// on request close tab
void onRequestCloseTab(int idx);
private:
Echo::vector<TextEditor*>::type m_textEditors;
};
}
| 21.704545 | 74 | 0.663874 | [
"vector"
] |
886348fc108dae17edf54b3e358ac1b1c46496bd | 1,242 | h | C | iphone/src/objc/GeoLocation.h | vinay-qa/vinayit-android-server-apk | 7eb5ba48527536bb1cdee7a8b9b7a2c2483c619d | [
"Apache-2.0"
] | 2 | 2015-10-31T06:35:11.000Z | 2018-02-02T17:39:39.000Z | iphone/src/objc/GeoLocation.h | vinay-qa/vinayit-android-server-apk | 7eb5ba48527536bb1cdee7a8b9b7a2c2483c619d | [
"Apache-2.0"
] | 1 | 2021-10-18T12:23:37.000Z | 2021-10-18T12:23:37.000Z | iphone/src/objc/GeoLocation.h | vinay-qa/vinayit-android-server-apk | 7eb5ba48527536bb1cdee7a8b9b7a2c2483c619d | [
"Apache-2.0"
] | 4 | 2015-09-19T11:03:28.000Z | 2020-03-14T20:35:52.000Z | /*
Copyright 2010 WebDriver committers
Copyright 2010 Google Inc.
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.
*/
#import <CoreLocation/CoreLocation.h>
// We redefine coordinate and altitude getters to emulate geo location
// possition. it is the same if we do lazy swizzling
@interface CLLocation (Synthesize)
@end
// mock object (singleton) to keep fake geo positions
@interface GeoLocation : NSObject {
CLLocationCoordinate2D coordinate_;
CLLocationDistance altitude_;
}
+ (GeoLocation *)sharedManager;
- (CLLocationCoordinate2D)getCoordinate;
- (CLLocationDistance)getAltitude;
- (void)setCoordinate:(CLLocationDegrees)longitude
latitude:(CLLocationDegrees)latitude;
- (void)setAltitude:(CLLocationDistance)altitude;
@end
| 32.684211 | 73 | 0.778583 | [
"object"
] |
88652f58e18a3fbba56ecc5595567170f1b64771 | 3,527 | h | C | Engine/Source/Runtime/PhysXFormats/Public/IPhysXFormat.h | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | null | null | null | Engine/Source/Runtime/PhysXFormats/Public/IPhysXFormat.h | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | 2 | 2015-06-21T17:38:11.000Z | 2015-06-22T20:54:42.000Z | Engine/Source/Runtime/PhysXFormats/Public/IPhysXFormat.h | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | null | null | null | // Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
/*=============================================================================
ITextureFormatModule.h: Declares the ITextureFormatModule interface.
=============================================================================*/
#pragma once
/**
* IPhysXFormat, PhysX cooking and serialization abstraction
**/
class IPhysXFormat
{
public:
/**
* Checks whether parallel PhysX cooking is allowed.
*
* Note: This method is not currently used yet.
*
* @return true if this PhysX format can cook in parallel, false otherwise.
*/
virtual bool AllowParallelBuild( ) const
{
return false;
}
/**
* Cooks the source convex data for the platform and stores the cooked data internally.
*
* @param Format The desired format
* @param SrcBuffer The source buffer
* @param OutBuffer The resulting cooked data
* @return true on success, false otherwise.
*/
virtual bool CookConvex( FName Format, const TArray<FVector>& SrcBuffer, TArray<uint8>& OutBuffer ) const = 0;
/**
* Cooks the source Tri-Mesh data for the platform and stores the cooked data internally.
*
* @param Format The desired format.
* @param SrcBuffer The source buffer.
* @param OutBuffer The resulting cooked data.
* @param bPerPolySkeletalMesh This is a very special case that requires different cooking parameters set.
* @return true on success, false otherwise.
*/
virtual bool CookTriMesh( FName Format, const TArray<FVector>& SrcVertices, const TArray<struct FTriIndices>& SrcIndices, const TArray<uint16>& SrcMaterialIndices, const bool FlipNormals, TArray<uint8>& OutBuffer, bool bPerPolySkeletalMesh = false ) const = 0;
/**
* Cooks the source height field data for the platform and stores the cooked data internally.
*
* @param Format The desired format
* @param HFSize Size of height field [NumColumns, NumRows]
* @param Thickness Sets how thick the height field surface is
* @param SrcBuffer The source buffer
* @param OutBuffer The resulting cooked data
* @return true on success, false otherwise.
*/
virtual bool CookHeightField( FName Format, FIntPoint HFSize, float Thickness, const void* Samples, uint32 SamplesStride, TArray<uint8>& OutBuffer ) const = 0;
/**
* Serializes the BodyInstance
*
* @param Format The desired format
* @param Bodies The bodies containing the needed physx actors to serialize
* @param BodySetups The various body setups used by Bodies (could be just 1). This is needed for keeping geometry out of the serialized data
* @param PhysicalMaterials The physical materials used by Bodies (could be just 1). This is needed for keeping physical materials out of the serialized data
* @param OutBuffer The resulting cooked data
* @return true on success, false otherwise.
*/
virtual bool SerializeActors( FName Format, const TArray<struct FBodyInstance*>& Bodies, const TArray<class UBodySetup*>& BodySetups, const TArray<class UPhysicalMaterial*>& PhysicalMaterials, TArray<uint8>& OutBuffer ) const = 0;
/**
* Gets the list of supported formats.
*
* @param OutFormats Will hold the list of formats.
*/
virtual void GetSupportedFormats( TArray<FName>& OutFormats ) const = 0;
/**
* Gets the current version of the specified PhysX format.
*
* @param Format The format to get the version for.
* @return Version number.
*/
virtual uint16 GetVersion( FName Format ) const = 0;
public:
/**
* Virtual destructor.
*/
virtual ~IPhysXFormat( ) { }
};
| 36.360825 | 261 | 0.703431 | [
"mesh",
"geometry"
] |
8867e5b81715b78a374bf7ecc174d951f695ac8e | 388 | h | C | Example/DashSync/DSContactsViewController.h | ProjectHelixCoin/helixsync-iOS | 95cf2974c46033412071232fbecfdaa73633b804 | [
"MIT"
] | 2 | 2021-05-06T07:46:52.000Z | 2021-05-06T07:47:14.000Z | Example/DashSync/DSContactsViewController.h | ProjectHelixCoin/helixsync-iOS | 95cf2974c46033412071232fbecfdaa73633b804 | [
"MIT"
] | 1 | 2020-05-07T07:18:33.000Z | 2020-05-07T09:49:47.000Z | Example/DashSync/DSContactsViewController.h | ProjectHelixCoin/helixsync-iOS | 95cf2974c46033412071232fbecfdaa73633b804 | [
"MIT"
] | null | null | null | //
// DSContactsViewController.h
// DashSync_Example
//
// Created by Andrew Podkovyrin on 08/03/2019.
// Copyright © 2019 Dash Core Group. All rights reserved.
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@class DSContactsModel;
@interface DSContactsViewController : UITableViewController
@property (strong, nonatomic) DSContactsModel *model;
@end
NS_ASSUME_NONNULL_END
| 17.636364 | 59 | 0.773196 | [
"model"
] |
886d7176b5734e11b55f460a42a9e8c3f5c36081 | 2,570 | h | C | source/src/settings.h | eazee187/CoinThing | f3a39642cc18693911f195f63073cfea13a865f1 | [
"MIT"
] | 14 | 2021-03-19T15:31:12.000Z | 2022-02-10T14:24:47.000Z | source/src/settings.h | gerdmuller/CoinThing | da9d0d947813a9399c4dcfc9faed23c00b36102b | [
"MIT"
] | 12 | 2021-08-03T11:10:06.000Z | 2021-12-15T22:24:54.000Z | source/src/settings.h | gerdmuller/Coin-Ticker | f3a39642cc18693911f195f63073cfea13a865f1 | [
"MIT"
] | 7 | 2021-03-24T04:29:40.000Z | 2022-01-06T21:08:21.000Z | #pragma once
#include "utils.h"
#include <Arduino.h>
#include <ArduinoJson.h>
#define SETTINGS_FILE "/settings.json"
#define BRIGHTNESS_FILE "/brightness.json"
class Settings {
public:
enum class ChartStyle : uint8_t {
SIMPLE = 0,
HIGH_LOW,
HIGH_LOW_FIRST_LAST
};
enum class Swap : uint8_t {
INTERVAL_1 = 0, // 5s (chart), 10s (coin)
INTERVAL_2, // 30s
INTERVAL_3, // 1min
INTERVAL_4 // 5min
};
enum ChartPeriod : uint8_t {
PERIOD_NONE = 0,
PERIOD_24_H = 1,
PERIOD_48_H = 2,
PERIOD_30_D = 4,
PERIOD_60_D = 8,
ALL_PERIODS = PERIOD_24_H + PERIOD_48_H + PERIOD_30_D + PERIOD_60_D
};
enum Mode : uint8_t {
ONE_COIN = 1,
TWO_COINS,
MULTIPLE_COINS
};
struct Coin {
String id;
String symbol;
String name;
};
struct Currency {
String currency;
String symbol;
};
Settings();
void begin();
void set(const char* json);
void read();
void write() const;
void deleteFile() const;
const String& coin(uint32_t index) const;
const String& name(uint32_t index) const;
const String& symbol(uint32_t index) const;
const String& currency() const;
const String& currencySymbol() const;
const String& currency2() const;
const String& currency2Symbol() const;
Mode mode() const { return m_mode; }
uint32_t numberCoins() const;
NumberFormat numberFormat() const { return m_number_format; }
uint8_t chartPeriod() const { return m_chart_period; }
Swap swapInterval() const { return m_swap_interval; }
ChartStyle chartStyle() const { return m_chart_style; }
bool heartbeat() const { return m_heartbeat; }
bool valid() const;
void readBrightness();
void setBrightness(uint8_t b);
uint8_t brightness() const;
uint32_t lastChange() const { return m_last_change; }
private:
void set(DynamicJsonDocument& doc, bool toFile);
void trace() const;
uint32_t validCoinIndex(uint32_t index) const;
Mode m_mode { Mode::ONE_COIN };
std::vector<Coin> m_coins;
std::array<Currency, 2> m_currencies;
NumberFormat m_number_format { NumberFormat::DECIMAL_DOT };
uint8_t m_chart_period { ChartPeriod::PERIOD_24_H };
Swap m_swap_interval { Swap::INTERVAL_1 };
ChartStyle m_chart_style { ChartStyle::SIMPLE };
bool m_heartbeat { true };
uint8_t m_brightness { std::numeric_limits<uint8_t>::max() };
uint32_t m_last_change { 0 };
};
| 25.196078 | 75 | 0.641245 | [
"vector"
] |
8878404a7a3c57f96509ccb42d7ff11a8ad0a2bf | 2,340 | h | C | compiler/optim/analysis/defuse.h | Engineev/mocker | 9d3006419ea04683d0b2e6f5ccd21d464e6704e3 | [
"MIT"
] | 14 | 2019-02-18T01:41:50.000Z | 2021-08-11T00:27:51.000Z | compiler/optim/analysis/defuse.h | Engineev/mocker | 9d3006419ea04683d0b2e6f5ccd21d464e6704e3 | [
"MIT"
] | null | null | null | compiler/optim/analysis/defuse.h | Engineev/mocker | 9d3006419ea04683d0b2e6f5ccd21d464e6704e3 | [
"MIT"
] | 1 | 2021-08-11T00:28:39.000Z | 2021-08-11T00:28:39.000Z | #ifndef MOCKER_DEFUSE_H
#define MOCKER_DEFUSE_H
#include <vector>
#include "ir/helper.h"
#include "ir/module.h"
namespace mocker {
class DefUseChain {
public:
class Use {
public:
Use(std::size_t bbLabel, std::shared_ptr<ir::IRInst> inst)
: bbLabel(bbLabel), inst(std::move(inst)) {}
Use(const Use &) = default;
Use &operator=(const Use &) = default;
~Use() = default;
const std::size_t getBBLabel() const { return bbLabel; }
const std::shared_ptr<ir::IRInst> getInst() const { return inst; }
private:
std::size_t bbLabel = 0;
std::shared_ptr<ir::IRInst> inst;
};
void init(const ir::FunctionModule &func) {
for (auto &bb : func.getBBs()) {
for (auto &inst : bb.getInsts()) {
if (auto dest = ir::getDest(inst))
chain[dest] = {};
}
}
for (auto &bb : func.getBBs()) {
for (auto &inst : bb.getInsts()) {
auto operands = ir::getOperandsUsed(inst);
for (auto &operand : operands) {
auto reg = ir::dycLocalReg(operand);
if (!reg)
continue;
chain[reg].emplace_back(bb.getLabelID(), inst);
}
}
}
}
const std::vector<Use> getUses(const std::shared_ptr<ir::Reg> &def) const {
return chain.at(def);
}
private:
ir::RegMap<std::vector<Use>> chain;
};
} // namespace mocker
namespace mocker {
class UseDefChain {
public:
class Def {
public:
Def(std::size_t bbLabel, std::shared_ptr<ir::IRInst> inst)
: bbLabel(bbLabel), inst(std::move(inst)) {}
Def(const Def &) = default;
Def &operator=(const Def &) = default;
~Def() = default;
const std::size_t getBBLabel() const { return bbLabel; }
const std::shared_ptr<ir::IRInst> &getInst() const { return inst; }
private:
std::size_t bbLabel = 0;
std::shared_ptr<ir::IRInst> inst;
};
void init(const ir::FunctionModule &func) {
for (auto &bb : func.getBBs()) {
for (auto &inst : bb.getInsts()) {
auto dest = ir::getDest(inst);
if (!dest)
continue;
chain.emplace(std::make_pair(dest, Def(bb.getLabelID(), inst)));
}
}
}
const Def &getDef(const std::shared_ptr<ir::Reg> ®) const {
return chain.at(reg);
}
private:
ir::RegMap<Def> chain;
};
} // namespace mocker
#endif // MOCKER_DEFUSE_H
| 22.5 | 77 | 0.59359 | [
"vector"
] |
88794a221cad5a2a9501855e2565509c64ec3daf | 414 | h | C | src/core/World.h | onqtam/game | 08d9f2871bfd5c757d541064b77d38474123592a | [
"MIT"
] | 41 | 2016-10-12T15:54:04.000Z | 2022-01-12T04:17:20.000Z | src/core/World.h | onqtam/game | 08d9f2871bfd5c757d541064b77d38474123592a | [
"MIT"
] | null | null | null | src/core/World.h | onqtam/game | 08d9f2871bfd5c757d541064b77d38474123592a | [
"MIT"
] | 10 | 2015-09-16T19:56:36.000Z | 2021-12-27T21:12:11.000Z | #pragma once
class HAPI World : public Singleton<World>
{
HA_SINGLETON(World);
private:
float m_width = 100.f;
float m_height = 100.f;
oid m_camera;
oid m_editor;
public:
World();
void update();
oid camera() { return m_camera; }
Object& editor() { return m_editor.obj(); }
float width() const { return m_width; }
float height() const { return m_height; }
};
| 16.56 | 47 | 0.613527 | [
"object"
] |
887b5f2f7c1b962be019eb2ce75eea991dc0cf07 | 1,559 | h | C | project2D/BTSequence.h | Jeffrey-W23/AIE-CodeFolio | c1820d0a228a6111011b2d10daf885753e6d302d | [
"MIT"
] | null | null | null | project2D/BTSequence.h | Jeffrey-W23/AIE-CodeFolio | c1820d0a228a6111011b2d10daf885753e6d302d | [
"MIT"
] | null | null | null | project2D/BTSequence.h | Jeffrey-W23/AIE-CodeFolio | c1820d0a228a6111011b2d10daf885753e6d302d | [
"MIT"
] | null | null | null | // #includes, using, etc
#pragma once
#include "BTComposite.h"
#include "BTBaseNode.h"
//--------------------------------------------------------------------------------------
// BTSequence object. Inheritance from BTComposite. AND
//--------------------------------------------------------------------------------------
class BTSequence : public BTComposite
{
public:
//--------------------------------------------------------------------------------------
// Execute: A virtual function to update objects over time.
//
// Returns:
// EBehaviourResult: An enum of success, fail or pending.
// Param:
// deltaTime: Pass in deltaTime. A number that updates per second.
// pEntity: A pointer to an entity.
//--------------------------------------------------------------------------------------
EBehaviourResult Execute(Entity* pEntity, float deltaTime)
{
// Set the child to pending.
BTBaseNode* child = pendingNode;
unsigned int i = -1;
if (!child)
i = 0;
// Go through the children in the tree
for (; i < children.Size(); ++i)
{
if (i >= 0)
child = children[i];
// Get the result of each child.
EBehaviourResult result = child->Execute(pEntity, deltaTime);
// Check result of children.
if (result == EBHAVIOUR_FAILURE)
{
pendingNode = nullptr;
return EBHAVIOUR_FAILURE;
}
if (result == EBHAVIOUR_PENDING)
{
pendingNode = child;
return EBHAVIOUR_PENDING;
}
}
// if passes if statements then return success.
pendingNode = nullptr;
return EBHAVIOUR_SUCCESS;
}
}; | 26.423729 | 89 | 0.518281 | [
"object"
] |
887c1b6461ed8035d1d59d23b8b31d8489ab6577 | 10,588 | h | C | aws-cpp-sdk-signer/include/aws/signer/model/GetSigningPlatformResult.h | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-02-10T08:06:54.000Z | 2022-02-10T08:06:54.000Z | aws-cpp-sdk-signer/include/aws/signer/model/GetSigningPlatformResult.h | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-signer/include/aws/signer/model/GetSigningPlatformResult.h | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-11-09T12:02:58.000Z | 2021-11-09T12:02:58.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/signer/Signer_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/signer/model/Category.h>
#include <aws/signer/model/SigningConfiguration.h>
#include <aws/signer/model/SigningImageFormat.h>
#include <utility>
namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;
namespace Utils
{
namespace Json
{
class JsonValue;
} // namespace Json
} // namespace Utils
namespace signer
{
namespace Model
{
class AWS_SIGNER_API GetSigningPlatformResult
{
public:
GetSigningPlatformResult();
GetSigningPlatformResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
GetSigningPlatformResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
/**
* <p>The ID of the target signing platform.</p>
*/
inline const Aws::String& GetPlatformId() const{ return m_platformId; }
/**
* <p>The ID of the target signing platform.</p>
*/
inline void SetPlatformId(const Aws::String& value) { m_platformId = value; }
/**
* <p>The ID of the target signing platform.</p>
*/
inline void SetPlatformId(Aws::String&& value) { m_platformId = std::move(value); }
/**
* <p>The ID of the target signing platform.</p>
*/
inline void SetPlatformId(const char* value) { m_platformId.assign(value); }
/**
* <p>The ID of the target signing platform.</p>
*/
inline GetSigningPlatformResult& WithPlatformId(const Aws::String& value) { SetPlatformId(value); return *this;}
/**
* <p>The ID of the target signing platform.</p>
*/
inline GetSigningPlatformResult& WithPlatformId(Aws::String&& value) { SetPlatformId(std::move(value)); return *this;}
/**
* <p>The ID of the target signing platform.</p>
*/
inline GetSigningPlatformResult& WithPlatformId(const char* value) { SetPlatformId(value); return *this;}
/**
* <p>The display name of the target signing platform.</p>
*/
inline const Aws::String& GetDisplayName() const{ return m_displayName; }
/**
* <p>The display name of the target signing platform.</p>
*/
inline void SetDisplayName(const Aws::String& value) { m_displayName = value; }
/**
* <p>The display name of the target signing platform.</p>
*/
inline void SetDisplayName(Aws::String&& value) { m_displayName = std::move(value); }
/**
* <p>The display name of the target signing platform.</p>
*/
inline void SetDisplayName(const char* value) { m_displayName.assign(value); }
/**
* <p>The display name of the target signing platform.</p>
*/
inline GetSigningPlatformResult& WithDisplayName(const Aws::String& value) { SetDisplayName(value); return *this;}
/**
* <p>The display name of the target signing platform.</p>
*/
inline GetSigningPlatformResult& WithDisplayName(Aws::String&& value) { SetDisplayName(std::move(value)); return *this;}
/**
* <p>The display name of the target signing platform.</p>
*/
inline GetSigningPlatformResult& WithDisplayName(const char* value) { SetDisplayName(value); return *this;}
/**
* <p>A list of partner entities that use the target signing platform.</p>
*/
inline const Aws::String& GetPartner() const{ return m_partner; }
/**
* <p>A list of partner entities that use the target signing platform.</p>
*/
inline void SetPartner(const Aws::String& value) { m_partner = value; }
/**
* <p>A list of partner entities that use the target signing platform.</p>
*/
inline void SetPartner(Aws::String&& value) { m_partner = std::move(value); }
/**
* <p>A list of partner entities that use the target signing platform.</p>
*/
inline void SetPartner(const char* value) { m_partner.assign(value); }
/**
* <p>A list of partner entities that use the target signing platform.</p>
*/
inline GetSigningPlatformResult& WithPartner(const Aws::String& value) { SetPartner(value); return *this;}
/**
* <p>A list of partner entities that use the target signing platform.</p>
*/
inline GetSigningPlatformResult& WithPartner(Aws::String&& value) { SetPartner(std::move(value)); return *this;}
/**
* <p>A list of partner entities that use the target signing platform.</p>
*/
inline GetSigningPlatformResult& WithPartner(const char* value) { SetPartner(value); return *this;}
/**
* <p>The validation template that is used by the target signing platform.</p>
*/
inline const Aws::String& GetTarget() const{ return m_target; }
/**
* <p>The validation template that is used by the target signing platform.</p>
*/
inline void SetTarget(const Aws::String& value) { m_target = value; }
/**
* <p>The validation template that is used by the target signing platform.</p>
*/
inline void SetTarget(Aws::String&& value) { m_target = std::move(value); }
/**
* <p>The validation template that is used by the target signing platform.</p>
*/
inline void SetTarget(const char* value) { m_target.assign(value); }
/**
* <p>The validation template that is used by the target signing platform.</p>
*/
inline GetSigningPlatformResult& WithTarget(const Aws::String& value) { SetTarget(value); return *this;}
/**
* <p>The validation template that is used by the target signing platform.</p>
*/
inline GetSigningPlatformResult& WithTarget(Aws::String&& value) { SetTarget(std::move(value)); return *this;}
/**
* <p>The validation template that is used by the target signing platform.</p>
*/
inline GetSigningPlatformResult& WithTarget(const char* value) { SetTarget(value); return *this;}
/**
* <p>The category type of the target signing platform.</p>
*/
inline const Category& GetCategory() const{ return m_category; }
/**
* <p>The category type of the target signing platform.</p>
*/
inline void SetCategory(const Category& value) { m_category = value; }
/**
* <p>The category type of the target signing platform.</p>
*/
inline void SetCategory(Category&& value) { m_category = std::move(value); }
/**
* <p>The category type of the target signing platform.</p>
*/
inline GetSigningPlatformResult& WithCategory(const Category& value) { SetCategory(value); return *this;}
/**
* <p>The category type of the target signing platform.</p>
*/
inline GetSigningPlatformResult& WithCategory(Category&& value) { SetCategory(std::move(value)); return *this;}
/**
* <p>A list of configurations applied to the target platform at signing.</p>
*/
inline const SigningConfiguration& GetSigningConfiguration() const{ return m_signingConfiguration; }
/**
* <p>A list of configurations applied to the target platform at signing.</p>
*/
inline void SetSigningConfiguration(const SigningConfiguration& value) { m_signingConfiguration = value; }
/**
* <p>A list of configurations applied to the target platform at signing.</p>
*/
inline void SetSigningConfiguration(SigningConfiguration&& value) { m_signingConfiguration = std::move(value); }
/**
* <p>A list of configurations applied to the target platform at signing.</p>
*/
inline GetSigningPlatformResult& WithSigningConfiguration(const SigningConfiguration& value) { SetSigningConfiguration(value); return *this;}
/**
* <p>A list of configurations applied to the target platform at signing.</p>
*/
inline GetSigningPlatformResult& WithSigningConfiguration(SigningConfiguration&& value) { SetSigningConfiguration(std::move(value)); return *this;}
/**
* <p>The format of the target platform's signing image.</p>
*/
inline const SigningImageFormat& GetSigningImageFormat() const{ return m_signingImageFormat; }
/**
* <p>The format of the target platform's signing image.</p>
*/
inline void SetSigningImageFormat(const SigningImageFormat& value) { m_signingImageFormat = value; }
/**
* <p>The format of the target platform's signing image.</p>
*/
inline void SetSigningImageFormat(SigningImageFormat&& value) { m_signingImageFormat = std::move(value); }
/**
* <p>The format of the target platform's signing image.</p>
*/
inline GetSigningPlatformResult& WithSigningImageFormat(const SigningImageFormat& value) { SetSigningImageFormat(value); return *this;}
/**
* <p>The format of the target platform's signing image.</p>
*/
inline GetSigningPlatformResult& WithSigningImageFormat(SigningImageFormat&& value) { SetSigningImageFormat(std::move(value)); return *this;}
/**
* <p>The maximum size (in MB) of the payload that can be signed by the target
* platform.</p>
*/
inline int GetMaxSizeInMB() const{ return m_maxSizeInMB; }
/**
* <p>The maximum size (in MB) of the payload that can be signed by the target
* platform.</p>
*/
inline void SetMaxSizeInMB(int value) { m_maxSizeInMB = value; }
/**
* <p>The maximum size (in MB) of the payload that can be signed by the target
* platform.</p>
*/
inline GetSigningPlatformResult& WithMaxSizeInMB(int value) { SetMaxSizeInMB(value); return *this;}
/**
* <p>A flag indicating whether signatures generated for the signing platform can
* be revoked.</p>
*/
inline bool GetRevocationSupported() const{ return m_revocationSupported; }
/**
* <p>A flag indicating whether signatures generated for the signing platform can
* be revoked.</p>
*/
inline void SetRevocationSupported(bool value) { m_revocationSupported = value; }
/**
* <p>A flag indicating whether signatures generated for the signing platform can
* be revoked.</p>
*/
inline GetSigningPlatformResult& WithRevocationSupported(bool value) { SetRevocationSupported(value); return *this;}
private:
Aws::String m_platformId;
Aws::String m_displayName;
Aws::String m_partner;
Aws::String m_target;
Category m_category;
SigningConfiguration m_signingConfiguration;
SigningImageFormat m_signingImageFormat;
int m_maxSizeInMB;
bool m_revocationSupported;
};
} // namespace Model
} // namespace signer
} // namespace Aws
| 32.984424 | 151 | 0.671609 | [
"model"
] |
887dd35305f574b22ec1bbc93add52eed26ba41d | 15,937 | h | C | test/mock_voice_engine.h | UWNetworksLab/webrtc-mod | 5b910438baf4f7c7883996a2323d8ed809fd10e1 | [
"DOC",
"BSD-3-Clause"
] | 1 | 2017-02-20T04:24:44.000Z | 2017-02-20T04:24:44.000Z | test/mock_voice_engine.h | UWNetworksLab/webrtc-mod | 5b910438baf4f7c7883996a2323d8ed809fd10e1 | [
"DOC",
"BSD-3-Clause"
] | null | null | null | test/mock_voice_engine.h | UWNetworksLab/webrtc-mod | 5b910438baf4f7c7883996a2323d8ed809fd10e1 | [
"DOC",
"BSD-3-Clause"
] | 1 | 2016-10-17T18:34:08.000Z | 2016-10-17T18:34:08.000Z | /*
* Copyright (c) 2015 The WebRTC 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 in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifndef WEBRTC_AUDIO_MOCK_VOICE_ENGINE_H_
#define WEBRTC_AUDIO_MOCK_VOICE_ENGINE_H_
#include <memory>
#include "testing/gmock/include/gmock/gmock.h"
#include "webrtc/test/mock_voe_channel_proxy.h"
#include "webrtc/voice_engine/voice_engine_impl.h"
namespace webrtc {
namespace test {
// NOTE: This class inherits from VoiceEngineImpl so that its clients will be
// able to get the various interfaces as usual, via T::GetInterface().
class MockVoiceEngine : public VoiceEngineImpl {
public:
MockVoiceEngine() : VoiceEngineImpl(new Config(), true) {
// Increase ref count so this object isn't automatically deleted whenever
// interfaces are Release():d.
++_ref_count;
// We add this default behavior to make the mock easier to use in tests. It
// will create a NiceMock of a voe::ChannelProxy.
ON_CALL(*this, ChannelProxyFactory(testing::_))
.WillByDefault(
testing::Invoke([](int channel_id) {
return new testing::NiceMock<MockVoEChannelProxy>();
}));
}
~MockVoiceEngine() override {
// Decrease ref count before base class d-tor is called; otherwise it will
// trigger an assertion.
--_ref_count;
}
// Allows injecting a ChannelProxy factory.
MOCK_METHOD1(ChannelProxyFactory, voe::ChannelProxy*(int channel_id));
// VoiceEngineImpl
std::unique_ptr<voe::ChannelProxy> GetChannelProxy(int channel_id) override {
return std::unique_ptr<voe::ChannelProxy>(ChannelProxyFactory(channel_id));
}
// VoEAudioProcessing
MOCK_METHOD2(SetNsStatus, int(bool enable, NsModes mode));
MOCK_METHOD2(GetNsStatus, int(bool& enabled, NsModes& mode));
MOCK_METHOD2(SetAgcStatus, int(bool enable, AgcModes mode));
MOCK_METHOD2(GetAgcStatus, int(bool& enabled, AgcModes& mode));
MOCK_METHOD1(SetAgcConfig, int(AgcConfig config));
MOCK_METHOD1(GetAgcConfig, int(AgcConfig& config));
MOCK_METHOD2(SetEcStatus, int(bool enable, EcModes mode));
MOCK_METHOD2(GetEcStatus, int(bool& enabled, EcModes& mode));
MOCK_METHOD1(EnableDriftCompensation, int(bool enable));
MOCK_METHOD0(DriftCompensationEnabled, bool());
MOCK_METHOD1(SetDelayOffsetMs, void(int offset));
MOCK_METHOD0(DelayOffsetMs, int());
MOCK_METHOD2(SetAecmMode, int(AecmModes mode, bool enableCNG));
MOCK_METHOD2(GetAecmMode, int(AecmModes& mode, bool& enabledCNG));
MOCK_METHOD1(EnableHighPassFilter, int(bool enable));
MOCK_METHOD0(IsHighPassFilterEnabled, bool());
MOCK_METHOD3(SetRxNsStatus, int(int channel, bool enable, NsModes mode));
MOCK_METHOD3(GetRxNsStatus, int(int channel, bool& enabled, NsModes& mode));
MOCK_METHOD3(SetRxAgcStatus, int(int channel, bool enable, AgcModes mode));
MOCK_METHOD3(GetRxAgcStatus, int(int channel, bool& enabled, AgcModes& mode));
MOCK_METHOD2(SetRxAgcConfig, int(int channel, AgcConfig config));
MOCK_METHOD2(GetRxAgcConfig, int(int channel, AgcConfig& config));
MOCK_METHOD2(RegisterRxVadObserver,
int(int channel, VoERxVadCallback& observer));
MOCK_METHOD1(DeRegisterRxVadObserver, int(int channel));
MOCK_METHOD1(VoiceActivityIndicator, int(int channel));
MOCK_METHOD1(SetEcMetricsStatus, int(bool enable));
MOCK_METHOD1(GetEcMetricsStatus, int(bool& enabled));
MOCK_METHOD4(GetEchoMetrics, int(int& ERL, int& ERLE, int& RERL, int& A_NLP));
MOCK_METHOD3(GetEcDelayMetrics,
int(int& delay_median,
int& delay_std,
float& fraction_poor_delays));
MOCK_METHOD1(StartDebugRecording, int(const char* fileNameUTF8));
MOCK_METHOD1(StartDebugRecording, int(FILE* file_handle));
MOCK_METHOD0(StopDebugRecording, int());
MOCK_METHOD1(SetTypingDetectionStatus, int(bool enable));
MOCK_METHOD1(GetTypingDetectionStatus, int(bool& enabled));
MOCK_METHOD1(TimeSinceLastTyping, int(int& seconds));
MOCK_METHOD5(SetTypingDetectionParameters,
int(int timeWindow,
int costPerTyping,
int reportingThreshold,
int penaltyDecay,
int typeEventDelay));
MOCK_METHOD1(EnableStereoChannelSwapping, void(bool enable));
MOCK_METHOD0(IsStereoChannelSwappingEnabled, bool());
// VoEBase
MOCK_METHOD1(RegisterVoiceEngineObserver, int(VoiceEngineObserver& observer));
MOCK_METHOD0(DeRegisterVoiceEngineObserver, int());
MOCK_METHOD2(Init,
int(AudioDeviceModule* external_adm,
AudioProcessing* audioproc));
MOCK_METHOD0(audio_processing, AudioProcessing*());
MOCK_METHOD0(Terminate, int());
MOCK_METHOD0(CreateChannel, int());
MOCK_METHOD1(CreateChannel, int(const Config& config));
MOCK_METHOD1(DeleteChannel, int(int channel));
MOCK_METHOD1(StartReceive, int(int channel));
MOCK_METHOD1(StopReceive, int(int channel));
MOCK_METHOD1(StartPlayout, int(int channel));
MOCK_METHOD1(StopPlayout, int(int channel));
MOCK_METHOD1(StartSend, int(int channel));
MOCK_METHOD1(StopSend, int(int channel));
MOCK_METHOD1(GetVersion, int(char version[1024]));
MOCK_METHOD0(LastError, int());
MOCK_METHOD0(audio_transport, AudioTransport*());
MOCK_METHOD2(AssociateSendChannel,
int(int channel, int accociate_send_channel));
// VoECodec
MOCK_METHOD0(NumOfCodecs, int());
MOCK_METHOD2(GetCodec, int(int index, CodecInst& codec));
MOCK_METHOD2(SetSendCodec, int(int channel, const CodecInst& codec));
MOCK_METHOD2(GetSendCodec, int(int channel, CodecInst& codec));
MOCK_METHOD2(SetBitRate, int(int channel, int bitrate_bps));
MOCK_METHOD2(GetRecCodec, int(int channel, CodecInst& codec));
MOCK_METHOD2(SetRecPayloadType, int(int channel, const CodecInst& codec));
MOCK_METHOD2(GetRecPayloadType, int(int channel, CodecInst& codec));
MOCK_METHOD3(SetSendCNPayloadType,
int(int channel, int type, PayloadFrequencies frequency));
MOCK_METHOD2(SetFECStatus, int(int channel, bool enable));
MOCK_METHOD2(GetFECStatus, int(int channel, bool& enabled));
MOCK_METHOD4(SetVADStatus,
int(int channel, bool enable, VadModes mode, bool disableDTX));
MOCK_METHOD4(
GetVADStatus,
int(int channel, bool& enabled, VadModes& mode, bool& disabledDTX));
MOCK_METHOD2(SetOpusMaxPlaybackRate, int(int channel, int frequency_hz));
MOCK_METHOD2(SetOpusDtx, int(int channel, bool enable_dtx));
MOCK_METHOD0(GetEventLog, RtcEventLog*());
// VoEDtmf
MOCK_METHOD5(SendTelephoneEvent,
int(int channel,
int eventCode,
bool outOfBand,
int lengthMs,
int attenuationDb));
MOCK_METHOD2(SetSendTelephoneEventPayloadType,
int(int channel, unsigned char type));
MOCK_METHOD2(GetSendTelephoneEventPayloadType,
int(int channel, unsigned char& type));
MOCK_METHOD2(SetDtmfFeedbackStatus, int(bool enable, bool directFeedback));
MOCK_METHOD2(GetDtmfFeedbackStatus, int(bool& enabled, bool& directFeedback));
MOCK_METHOD3(PlayDtmfTone,
int(int eventCode, int lengthMs, int attenuationDb));
// VoEExternalMedia
MOCK_METHOD3(RegisterExternalMediaProcessing,
int(int channel,
ProcessingTypes type,
VoEMediaProcess& processObject));
MOCK_METHOD2(DeRegisterExternalMediaProcessing,
int(int channel, ProcessingTypes type));
MOCK_METHOD3(GetAudioFrame,
int(int channel, int desired_sample_rate_hz, AudioFrame* frame));
MOCK_METHOD2(SetExternalMixing, int(int channel, bool enable));
// VoEFile
MOCK_METHOD7(StartPlayingFileLocally,
int(int channel,
const char fileNameUTF8[1024],
bool loop,
FileFormats format,
float volumeScaling,
int startPointMs,
int stopPointMs));
MOCK_METHOD6(StartPlayingFileLocally,
int(int channel,
InStream* stream,
FileFormats format,
float volumeScaling,
int startPointMs,
int stopPointMs));
MOCK_METHOD1(StopPlayingFileLocally, int(int channel));
MOCK_METHOD1(IsPlayingFileLocally, int(int channel));
MOCK_METHOD6(StartPlayingFileAsMicrophone,
int(int channel,
const char fileNameUTF8[1024],
bool loop,
bool mixWithMicrophone,
FileFormats format,
float volumeScaling));
MOCK_METHOD5(StartPlayingFileAsMicrophone,
int(int channel,
InStream* stream,
bool mixWithMicrophone,
FileFormats format,
float volumeScaling));
MOCK_METHOD1(StopPlayingFileAsMicrophone, int(int channel));
MOCK_METHOD1(IsPlayingFileAsMicrophone, int(int channel));
MOCK_METHOD4(StartRecordingPlayout,
int(int channel,
const char* fileNameUTF8,
CodecInst* compression,
int maxSizeBytes));
MOCK_METHOD1(StopRecordingPlayout, int(int channel));
MOCK_METHOD3(StartRecordingPlayout,
int(int channel, OutStream* stream, CodecInst* compression));
MOCK_METHOD3(StartRecordingMicrophone,
int(const char* fileNameUTF8,
CodecInst* compression,
int maxSizeBytes));
MOCK_METHOD2(StartRecordingMicrophone,
int(OutStream* stream, CodecInst* compression));
MOCK_METHOD0(StopRecordingMicrophone, int());
// VoEHardware
MOCK_METHOD1(GetNumOfRecordingDevices, int(int& devices));
MOCK_METHOD1(GetNumOfPlayoutDevices, int(int& devices));
MOCK_METHOD3(GetRecordingDeviceName,
int(int index, char strNameUTF8[128], char strGuidUTF8[128]));
MOCK_METHOD3(GetPlayoutDeviceName,
int(int index, char strNameUTF8[128], char strGuidUTF8[128]));
MOCK_METHOD2(SetRecordingDevice,
int(int index, StereoChannel recordingChannel));
MOCK_METHOD1(SetPlayoutDevice, int(int index));
MOCK_METHOD1(SetAudioDeviceLayer, int(AudioLayers audioLayer));
MOCK_METHOD1(GetAudioDeviceLayer, int(AudioLayers& audioLayer));
MOCK_METHOD1(SetRecordingSampleRate, int(unsigned int samples_per_sec));
MOCK_CONST_METHOD1(RecordingSampleRate, int(unsigned int* samples_per_sec));
MOCK_METHOD1(SetPlayoutSampleRate, int(unsigned int samples_per_sec));
MOCK_CONST_METHOD1(PlayoutSampleRate, int(unsigned int* samples_per_sec));
MOCK_CONST_METHOD0(BuiltInAECIsAvailable, bool());
MOCK_METHOD1(EnableBuiltInAEC, int(bool enable));
MOCK_CONST_METHOD0(BuiltInAGCIsAvailable, bool());
MOCK_METHOD1(EnableBuiltInAGC, int(bool enable));
MOCK_CONST_METHOD0(BuiltInNSIsAvailable, bool());
MOCK_METHOD1(EnableBuiltInNS, int(bool enable));
// VoENetEqStats
MOCK_METHOD2(GetNetworkStatistics,
int(int channel, NetworkStatistics& stats));
MOCK_CONST_METHOD2(GetDecodingCallStatistics,
int(int channel, AudioDecodingCallStats* stats));
// VoENetwork
MOCK_METHOD2(RegisterExternalTransport,
int(int channel, Transport& transport));
MOCK_METHOD1(DeRegisterExternalTransport, int(int channel));
MOCK_METHOD3(ReceivedRTPPacket,
int(int channel, const void* data, size_t length));
MOCK_METHOD4(ReceivedRTPPacket,
int(int channel,
const void* data,
size_t length,
const PacketTime& packet_time));
MOCK_METHOD3(ReceivedRTCPPacket,
int(int channel, const void* data, size_t length));
// VoERTP_RTCP
MOCK_METHOD2(SetLocalSSRC, int(int channel, unsigned int ssrc));
MOCK_METHOD2(GetLocalSSRC, int(int channel, unsigned int& ssrc));
MOCK_METHOD2(GetRemoteSSRC, int(int channel, unsigned int& ssrc));
MOCK_METHOD3(SetSendAudioLevelIndicationStatus,
int(int channel, bool enable, unsigned char id));
MOCK_METHOD3(SetReceiveAudioLevelIndicationStatus,
int(int channel, bool enable, unsigned char id));
MOCK_METHOD3(SetSendAbsoluteSenderTimeStatus,
int(int channel, bool enable, unsigned char id));
MOCK_METHOD3(SetReceiveAbsoluteSenderTimeStatus,
int(int channel, bool enable, unsigned char id));
MOCK_METHOD2(SetRTCPStatus, int(int channel, bool enable));
MOCK_METHOD2(GetRTCPStatus, int(int channel, bool& enabled));
MOCK_METHOD2(SetRTCP_CNAME, int(int channel, const char cName[256]));
MOCK_METHOD2(GetRTCP_CNAME, int(int channel, char cName[256]));
MOCK_METHOD2(GetRemoteRTCP_CNAME, int(int channel, char cName[256]));
MOCK_METHOD7(GetRemoteRTCPData,
int(int channel,
unsigned int& NTPHigh,
unsigned int& NTPLow,
unsigned int& timestamp,
unsigned int& playoutTimestamp,
unsigned int* jitter,
unsigned short* fractionLost));
MOCK_METHOD4(GetRTPStatistics,
int(int channel,
unsigned int& averageJitterMs,
unsigned int& maxJitterMs,
unsigned int& discardedPackets));
MOCK_METHOD2(GetRTCPStatistics, int(int channel, CallStatistics& stats));
MOCK_METHOD2(GetRemoteRTCPReportBlocks,
int(int channel, std::vector<ReportBlock>* receive_blocks));
MOCK_METHOD3(SetREDStatus, int(int channel, bool enable, int redPayloadtype));
MOCK_METHOD3(GetREDStatus,
int(int channel, bool& enable, int& redPayloadtype));
MOCK_METHOD3(SetNACKStatus, int(int channel, bool enable, int maxNoPackets));
// VoEVideoSync
MOCK_METHOD1(GetPlayoutBufferSize, int(int& buffer_ms));
MOCK_METHOD2(SetMinimumPlayoutDelay, int(int channel, int delay_ms));
MOCK_METHOD3(GetDelayEstimate,
int(int channel,
int* jitter_buffer_delay_ms,
int* playout_buffer_delay_ms));
MOCK_CONST_METHOD1(GetLeastRequiredDelayMs, int(int channel));
MOCK_METHOD2(SetInitTimestamp, int(int channel, unsigned int timestamp));
MOCK_METHOD2(SetInitSequenceNumber, int(int channel, short sequenceNumber));
MOCK_METHOD2(GetPlayoutTimestamp, int(int channel, unsigned int& timestamp));
MOCK_METHOD3(GetRtpRtcp,
int(int channel,
RtpRtcp** rtpRtcpModule,
RtpReceiver** rtp_receiver));
// VoEVolumeControl
MOCK_METHOD1(SetSpeakerVolume, int(unsigned int volume));
MOCK_METHOD1(GetSpeakerVolume, int(unsigned int& volume));
MOCK_METHOD1(SetMicVolume, int(unsigned int volume));
MOCK_METHOD1(GetMicVolume, int(unsigned int& volume));
MOCK_METHOD2(SetInputMute, int(int channel, bool enable));
MOCK_METHOD2(GetInputMute, int(int channel, bool& enabled));
MOCK_METHOD1(GetSpeechInputLevel, int(unsigned int& level));
MOCK_METHOD2(GetSpeechOutputLevel, int(int channel, unsigned int& level));
MOCK_METHOD1(GetSpeechInputLevelFullRange, int(unsigned int& level));
MOCK_METHOD2(GetSpeechOutputLevelFullRange,
int(int channel, unsigned& level));
MOCK_METHOD2(SetChannelOutputVolumeScaling, int(int channel, float scaling));
MOCK_METHOD2(GetChannelOutputVolumeScaling, int(int channel, float& scaling));
MOCK_METHOD3(SetOutputVolumePan, int(int channel, float left, float right));
MOCK_METHOD3(GetOutputVolumePan, int(int channel, float& left, float& right));
};
} // namespace test
} // namespace webrtc
#endif // WEBRTC_AUDIO_MOCK_VOICE_ENGINE_H_
| 46.873529 | 80 | 0.703897 | [
"object",
"vector"
] |
887e54302eddd53f3e1f871d35045e7112aa6607 | 70,612 | c | C | src/tool/hpcrun/gpu/nvidia/sanitizer-api.c | GVProf/hpctoolkit | baf45028ead83ceba3e952bb8d0b14caf9ea5f78 | [
"BSD-3-Clause"
] | null | null | null | src/tool/hpcrun/gpu/nvidia/sanitizer-api.c | GVProf/hpctoolkit | baf45028ead83ceba3e952bb8d0b14caf9ea5f78 | [
"BSD-3-Clause"
] | null | null | null | src/tool/hpcrun/gpu/nvidia/sanitizer-api.c | GVProf/hpctoolkit | baf45028ead83ceba3e952bb8d0b14caf9ea5f78 | [
"BSD-3-Clause"
] | 2 | 2021-11-30T18:24:10.000Z | 2022-02-13T18:13:17.000Z | // -*-Mode: C++;-*- // technically C99
// * BeginRiceCopyright *****************************************************
//
// --------------------------------------------------------------------------
// Part of HPCToolkit (hpctoolkit.org)
//
// Information about sources of support for research and development of
// HPCToolkit is at 'hpctoolkit.org' and in 'README.Acknowledgments'.
// --------------------------------------------------------------------------
//
// Copyright ((c)) 2002-2019, Rice University
// 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 Rice University (RICE) 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 RICE 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 RICE 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.
//
// ******************************************************* EndRiceCopyright *
//***************************************************************************
//
// File:
// sanitizer-api.c
//
// Purpose:
// implementation of wrapper around NVIDIA's Sanitizer API
//
//***************************************************************************
//***************************************************************************
// system includes
//***************************************************************************
#include <stdio.h>
#include <errno.h> // errno
#include <fcntl.h> // open
#include <limits.h> // PATH_MAX
#include <stdio.h> // sprintf
#include <unistd.h>
#include <sys/stat.h> // mkdir
#include <string.h> // strstr
#include <pthread.h>
#include <time.h>
#ifndef HPCRUN_STATIC_LINK
#include <dlfcn.h>
#undef _GNU_SOURCE
#define _GNU_SOURCE
#include <link.h> // dl_iterate_phdr
#include <linux/limits.h> // PATH_MAX
#include <string.h> // strstr
#endif
#include <sanitizer.h>
#include <gpu-patch.h>
#include <redshow.h>
#include <vector_types.h> // dim3
#include <lib/prof-lean/spinlock.h>
#include <lib/prof-lean/stdatomic.h>
#include <hpcrun/cct2metrics.h>
#include <hpcrun/files.h>
#include <hpcrun/hpcrun_stats.h>
#include <hpcrun/module-ignore-map.h>
#include <hpcrun/main.h>
#include <hpcrun/safe-sampling.h>
#include <hpcrun/sample_event.h>
#include <hpcrun/thread_data.h>
#include <hpcrun/threadmgr.h>
#include <hpcrun/utilities/hpcrun-nanotime.h>
#include <hpcrun/gpu/gpu-application-thread-api.h>
#include <hpcrun/gpu/gpu-monitoring-thread-api.h>
#include <hpcrun/gpu/gpu-correlation-id.h>
#include <hpcrun/gpu/gpu-op-placeholders.h>
#include <hpcrun/gpu/gpu-metrics.h>
#include <hpcrun/sample-sources/libdl.h>
#include <hpcrun/sample-sources/nvidia.h>
#include "cuda-api.h"
#include "cubin-id-map.h"
#include "cubin-hash-map.h"
#include "sanitizer-api.h"
#include "sanitizer-context-map.h"
#include "sanitizer-stream-map.h"
#include "sanitizer-op-map.h"
#include "sanitizer-buffer.h"
#include "sanitizer-buffer-channel.h"
#include "sanitizer-buffer-channel-set.h"
#include "sanitizer-function-list.h"
#define SANITIZER_API_DEBUG 1
#define FUNCTION_NAME_LENGTH 1024
#if SANITIZER_API_DEBUG
#define PRINT(...) fprintf(stderr, __VA_ARGS__)
#else
#define PRINT(...)
#endif
#define MIN2(m1, m2) m1 > m2 ? m2 : m1
#define SANITIZER_FN_NAME(f) DYN_FN_NAME(f)
#define SANITIZER_FN(fn, args) \
static SanitizerResult (*SANITIZER_FN_NAME(fn)) args
#define HPCRUN_SANITIZER_CALL(fn, args) \
{ \
SanitizerResult status = SANITIZER_FN_NAME(fn) args; \
if (status != SANITIZER_SUCCESS) { \
sanitizer_error_report(status, #fn); \
} \
}
#define HPCRUN_SANITIZER_CALL_NO_CHECK(fn, args) \
{ \
SANITIZER_FN_NAME(fn) args; \
}
#define DISPATCH_CALLBACK(fn, args) if (fn) fn args
#define FORALL_SANITIZER_ROUTINES(macro) \
macro(sanitizerSubscribe) \
macro(sanitizerUnsubscribe) \
macro(sanitizerEnableAllDomains) \
macro(sanitizerEnableDomain) \
macro(sanitizerAlloc) \
macro(sanitizerMemset) \
macro(sanitizerMemcpyDeviceToHost) \
macro(sanitizerMemcpyHostToDeviceAsync) \
macro(sanitizerSetCallbackData) \
macro(sanitizerStreamSynchronize) \
macro(sanitizerAddPatchesFromFile) \
macro(sanitizerGetFunctionPcAndSize) \
macro(sanitizerPatchInstructions) \
macro(sanitizerPatchModule) \
macro(sanitizerGetResultString) \
macro(sanitizerGetStreamHandle) \
macro(sanitizerUnpatchModule)
typedef void (*sanitizer_error_callback_t)
(
const char *type,
const char *fn,
const char *error_string
);
typedef cct_node_t *(*sanitizer_correlation_callback_t)
(
uint64_t id,
uint32_t skip_frames
);
static cct_node_t *
sanitizer_correlation_callback_dummy // __attribute__((unused))
(
uint64_t id,
uint32_t skip_frames
);
static void
sanitizer_error_callback_dummy // __attribute__((unused))
(
const char *type,
const char *fn,
const char *error_string
);
typedef struct {
pthread_t thread;
pthread_mutex_t mutex;
pthread_cond_t cond;
} sanitizer_thread_t;
typedef struct {
bool flag;
int32_t persistent_id;
uint64_t correlation_id;
uint64_t start;
uint64_t end;
} sanitizer_memory_register_delegate_t;
// only subscribed by the main thread
static Sanitizer_SubscriberHandle sanitizer_subscriber_handle;
// Single background process thread, can be extended
static sanitizer_thread_t sanitizer_thread;
// Configurable variables
static int sanitizer_buffer_pool_size = 0;
static int sanitizer_pc_views = 0;
static int sanitizer_mem_views = 0;
static redshow_approx_level_t sanitizer_approx_level = REDSHOW_APPROX_NONE;
static redshow_data_type_t sanitizer_data_type = REDSHOW_DATA_FLOAT;
// CPU async
static bool sanitizer_analysis_async = false;
// Patch info (GPU)
static size_t sanitizer_gpu_patch_record_num = 0;
static size_t sanitizer_gpu_patch_record_size = 0;
static uint32_t sanitizer_gpu_patch_type = GPU_PATCH_TYPE_DEFAULT;
// Analysis info (GPU)
static int sanitizer_gpu_analysis_record_num = 0;
static size_t sanitizer_gpu_analysis_record_size = 0;
static uint32_t sanitizer_gpu_analysis_blocks = 0;
static uint32_t sanitizer_gpu_analysis_type = GPU_PATCH_TYPE_ADDRESS_ANALYSIS;
static bool sanitizer_read_trace_ignore = false;
static bool sanitizer_data_flow_hash = false;
static __thread bool sanitizer_stop_flag = false;
static __thread bool sanitizer_context_creation_flag = false;
static __thread uint32_t sanitizer_thread_id_self = (1 << 30);
static __thread uint32_t sanitizer_thread_id_local = 0;
static __thread CUcontext sanitizer_thread_context = NULL;
static __thread sanitizer_memory_register_delegate_t sanitizer_memory_register_delegate = {
.flag = false
};
// Host buffers are per-thread
static __thread gpu_patch_buffer_t *sanitizer_gpu_patch_buffer_host = NULL;
static __thread gpu_patch_buffer_t *sanitizer_gpu_patch_buffer_addr_read_host = NULL;
static __thread gpu_patch_buffer_t *sanitizer_gpu_patch_buffer_addr_write_host = NULL;
static __thread gpu_patch_aux_address_dict_t *sanitizer_gpu_patch_aux_addr_dict_host = NULL;
// Reset and device buffers are per-context
static __thread gpu_patch_buffer_t *sanitizer_gpu_patch_buffer_reset = NULL;
static __thread gpu_patch_buffer_t *sanitizer_gpu_patch_buffer_addr_read_reset = NULL;
static __thread gpu_patch_buffer_t *sanitizer_gpu_patch_buffer_addr_write_reset = NULL;
static __thread gpu_patch_aux_address_dict_t *sanitizer_gpu_patch_aux_addr_dict_reset = NULL;
static __thread gpu_patch_buffer_t *sanitizer_gpu_patch_buffer_device = NULL;
static __thread gpu_patch_buffer_t *sanitizer_gpu_patch_buffer_addr_read_device = NULL;
static __thread gpu_patch_buffer_t *sanitizer_gpu_patch_buffer_addr_write_device = NULL;
static __thread gpu_patch_aux_address_dict_t *sanitizer_gpu_patch_aux_addr_dict_device = NULL;
static sanitizer_correlation_callback_t sanitizer_correlation_callback =
sanitizer_correlation_callback_dummy;
static sanitizer_error_callback_t sanitizer_error_callback =
sanitizer_error_callback_dummy;
static atomic_uint sanitizer_thread_id = ATOMIC_VAR_INIT(0);
static atomic_uint sanitizer_process_thread_counter = ATOMIC_VAR_INIT(0);
static atomic_bool sanitizer_process_awake_flag = ATOMIC_VAR_INIT(0);
static atomic_bool sanitizer_process_stop_flag = ATOMIC_VAR_INIT(0);
static sanitizer_function_list_entry_t *sanitizer_whitelist = NULL;
static sanitizer_function_list_entry_t *sanitizer_blacklist = NULL;
//----------------------------------------------------------
// sanitizer function pointers for late binding
//----------------------------------------------------------
SANITIZER_FN
(
sanitizerSubscribe,
(
Sanitizer_SubscriberHandle* subscriber,
Sanitizer_CallbackFunc callback,
void* userdata
)
);
SANITIZER_FN
(
sanitizerUnsubscribe,
(
Sanitizer_SubscriberHandle subscriber
)
);
SANITIZER_FN
(
__attribute__((unused)) sanitizerEnableAllDomains,
(
uint32_t enable,
Sanitizer_SubscriberHandle subscriber
)
);
SANITIZER_FN
(
sanitizerEnableDomain,
(
uint32_t enable,
Sanitizer_SubscriberHandle subscriber,
Sanitizer_CallbackDomain domain
)
);
SANITIZER_FN
(
sanitizerAlloc,
(
CUcontext ctx,
void** devPtr,
size_t size
)
);
SANITIZER_FN
(
sanitizerMemset,
(
void* devPtr,
int value,
size_t count,
Sanitizer_StreamHandle stream
)
);
SANITIZER_FN
(
sanitizerStreamSynchronize,
(
Sanitizer_StreamHandle stream
)
);
SANITIZER_FN
(
sanitizerMemcpyDeviceToHost,
(
void* dst,
void* src,
size_t count,
Sanitizer_StreamHandle stream
)
);
SANITIZER_FN
(
sanitizerMemcpyHostToDeviceAsync,
(
void* dst,
void* src,
size_t count,
Sanitizer_StreamHandle stream
)
);
SANITIZER_FN
(
sanitizerSetCallbackData,
(
CUfunction function,
const void* userdata
)
);
SANITIZER_FN
(
sanitizerAddPatchesFromFile,
(
const char* filename,
CUcontext ctx
)
);
SANITIZER_FN
(
sanitizerPatchInstructions,
(
const Sanitizer_InstructionId instructionId,
CUmodule module,
const char* deviceCallbackName
)
);
SANITIZER_FN
(
sanitizerPatchModule,
(
CUmodule module
)
);
SANITIZER_FN
(
__attribute__((unused)) sanitizerUnpatchModule,
(
CUmodule module
)
);
SANITIZER_FN
(
sanitizerGetResultString,
(
SanitizerResult result,
const char **str
)
);
SANITIZER_FN
(
sanitizerGetFunctionPcAndSize,
(
CUmodule module,
const char *functionName,
uint64_t* pc,
uint64_t* size
)
);
SANITIZER_FN
(
sanitizerGetStreamHandle,
(
CUcontext ctx,
CUstream stream,
Sanitizer_StreamHandle *hStream
)
);
//******************************************************************************
// forward declaration operations
//******************************************************************************
static Sanitizer_StreamHandle sanitizer_priority_stream_get(CUcontext context);
static Sanitizer_StreamHandle sanitizer_kernel_stream_get(CUcontext context);
static void sanitizer_kernel_launch(CUcontext context);
//******************************************************************************
// private operations
//******************************************************************************
static cct_node_t *
sanitizer_correlation_callback_dummy // __attribute__((unused))
(
uint64_t id,
uint32_t skip_frames
)
{
return NULL;
}
static void
sanitizer_error_callback_dummy // __attribute__((unused))
(
const char *type,
const char *fn,
const char *error_string
)
{
PRINT("Sanitizer-> %s: function %s failed with error %s\n", type, fn, error_string);
exit(-1);
}
static void
sanitizer_error_report
(
SanitizerResult error,
const char *fn
)
{
const char *error_string;
SANITIZER_FN_NAME(sanitizerGetResultString)(error, &error_string);
sanitizer_error_callback("Sanitizer result error", fn, error_string);
}
static void
sanitizer_log_data_callback
(
int32_t kernel_id,
gpu_patch_buffer_t *trace_data
)
{
}
static void
sanitizer_dtoh
(
uint64_t host,
uint64_t device,
uint64_t len
)
{
Sanitizer_StreamHandle priority_stream = sanitizer_priority_stream_get(sanitizer_thread_context);
// sanitizerMemcpyDeviceToHost is thread safe
HPCRUN_SANITIZER_CALL(sanitizerMemcpyDeviceToHost,
((void *)host, (void *)device, len, priority_stream));
}
static void
sanitizer_record_data_callback
(
uint32_t cubin_id,
int32_t kernel_id,
redshow_record_data_t *record_data
)
{
gpu_activity_t ga;
ga.kind = GPU_ACTIVITY_REDUNDANCY;
if (record_data->analysis_type == REDSHOW_ANALYSIS_SPATIAL_REDUNDANCY &&
record_data->access_type == REDSHOW_ACCESS_READ) {
ga.details.redundancy.type = GPU_RED_SPATIAL_READ_RED;
} else if (record_data->analysis_type == REDSHOW_ANALYSIS_SPATIAL_REDUNDANCY &&
record_data->access_type == REDSHOW_ACCESS_WRITE) {
ga.details.redundancy.type = GPU_RED_SPATIAL_WRITE_RED;
} else if (record_data->analysis_type == REDSHOW_ANALYSIS_TEMPORAL_REDUNDANCY &&
record_data->access_type == REDSHOW_ACCESS_READ) {
ga.details.redundancy.type = GPU_RED_TEMPORAL_READ_RED;
} else if (record_data->analysis_type == REDSHOW_ANALYSIS_TEMPORAL_REDUNDANCY &&
record_data->access_type == REDSHOW_ACCESS_WRITE) {
ga.details.redundancy.type = GPU_RED_TEMPORAL_WRITE_RED;
} else {
assert(0);
}
cstack_ptr_set(&(ga.next), 0);
uint32_t num_views = record_data->num_views;
uint32_t i;
for (i = 0; i < num_views; ++i) {
uint32_t function_index = record_data->views[i].function_index;
uint64_t pc_offset = record_data->views[i].pc_offset;
uint64_t red_count = record_data->views[i].red_count;
uint64_t access_count = record_data->views[i].access_count;
ip_normalized_t ip = cubin_id_transform(cubin_id, function_index, pc_offset);
sanitizer_op_map_entry_t *entry = sanitizer_op_map_lookup(kernel_id);
if (entry != NULL) {
cct_node_t *host_op_node = sanitizer_op_map_op_get(entry);
ga.cct_node = hpcrun_cct_insert_ip_norm(host_op_node, ip);
ga.details.redundancy.red_count = red_count;
ga.details.redundancy.access_count = access_count;
// Associate record_data with calling context (kernel_id)
gpu_metrics_attribute(&ga);
} else {
PRINT("Sanitizer-> NULL cct_node with kernel_id %d\n", kernel_id);
}
}
}
#ifndef HPCRUN_STATIC_LINK
static const char *
sanitizer_path
(
void
)
{
const char *path = "libsanitizer-public.so";
static char buffer[PATH_MAX];
buffer[0] = 0;
// open an NVIDIA library to find the CUDA path with dl_iterate_phdr
// note: a version of this file with a more specific name may
// already be loaded. thus, even if the dlopen fails, we search with
// dl_iterate_phdr.
void *h = monitor_real_dlopen("libcudart.so", RTLD_LOCAL | RTLD_LAZY);
if (cuda_path(buffer)) {
// invariant: buffer contains CUDA home
strcat(buffer, "compute-sanitizer/libsanitizer-public.so");
path = buffer;
}
if (h) monitor_real_dlclose(h);
return path;
}
#endif
//******************************************************************************
// asynchronous process thread
//******************************************************************************
void
sanitizer_process_signal
(
)
{
pthread_cond_t *cond = &(sanitizer_thread.cond);
pthread_mutex_t *mutex = &(sanitizer_thread.mutex);
pthread_mutex_lock(mutex);
atomic_store(&sanitizer_process_awake_flag, true);
pthread_cond_signal(cond);
pthread_mutex_unlock(mutex);
}
static void
sanitizer_process_await
(
)
{
pthread_cond_t *cond = &(sanitizer_thread.cond);
pthread_mutex_t *mutex = &(sanitizer_thread.mutex);
pthread_mutex_lock(mutex);
while (!atomic_load(&sanitizer_process_awake_flag)) {
pthread_cond_wait(cond, mutex);
}
atomic_store(&sanitizer_process_awake_flag, false);
pthread_mutex_unlock(mutex);
}
static void*
sanitizer_process_thread
(
void *arg
)
{
pthread_cond_t *cond = &(sanitizer_thread.cond);
pthread_mutex_t *mutex = &(sanitizer_thread.mutex);
while (!atomic_load(&sanitizer_process_stop_flag)) {
redshow_analysis_begin();
sanitizer_buffer_channel_set_consume();
redshow_analysis_end();
sanitizer_process_await();
}
// Last records
sanitizer_buffer_channel_set_consume();
// Create thread data
thread_data_t* td = NULL;
int id = sanitizer_thread_id_self;
hpcrun_threadMgr_non_compact_data_get(id, NULL, &td);
hpcrun_set_thread_data(td);
atomic_fetch_add(&sanitizer_process_thread_counter, -1);
pthread_mutex_destroy(mutex);
pthread_cond_destroy(cond);
return NULL;
}
//******************************************************************************
// Cubins
//******************************************************************************
static void
sanitizer_buffer_init
(
CUcontext context
)
{
if (sanitizer_gpu_patch_buffer_device != NULL) {
// All entries have been initialized
return;
}
// Get cached entry
sanitizer_context_map_entry_t *entry = sanitizer_context_map_init(context);
Sanitizer_StreamHandle priority_stream = sanitizer_priority_stream_get(context);
sanitizer_gpu_patch_buffer_device = sanitizer_context_map_entry_buffer_device_get(entry);
sanitizer_gpu_patch_buffer_addr_read_device = sanitizer_context_map_entry_buffer_addr_read_device_get(entry);
sanitizer_gpu_patch_buffer_addr_write_device = sanitizer_context_map_entry_buffer_addr_write_device_get(entry);
sanitizer_gpu_patch_aux_addr_dict_device = sanitizer_context_map_entry_aux_addr_dict_device_get(entry);
sanitizer_gpu_patch_buffer_reset = sanitizer_context_map_entry_buffer_reset_get(entry);
sanitizer_gpu_patch_buffer_addr_read_reset = sanitizer_context_map_entry_buffer_addr_read_reset_get(entry);
sanitizer_gpu_patch_buffer_addr_write_reset = sanitizer_context_map_entry_buffer_addr_write_reset_get(entry);
sanitizer_gpu_patch_aux_addr_dict_reset = sanitizer_context_map_entry_aux_addr_dict_reset_get(entry);
if (sanitizer_gpu_patch_buffer_device == NULL) {
// Allocated buffer
void *gpu_patch_records = NULL;
// gpu_patch_buffer
HPCRUN_SANITIZER_CALL(sanitizerAlloc, (context, (void **)(&(sanitizer_gpu_patch_buffer_device)), sizeof(gpu_patch_buffer_t)));
HPCRUN_SANITIZER_CALL(sanitizerMemset, (sanitizer_gpu_patch_buffer_device, 0, sizeof(gpu_patch_buffer_t), priority_stream));
PRINT("Sanitizer-> Allocate gpu_patch_buffer %p, size %zu\n", sanitizer_gpu_patch_buffer_device, sizeof(gpu_patch_buffer_t));
// gpu_patch_buffer_t->records
HPCRUN_SANITIZER_CALL(sanitizerAlloc,
(context, &gpu_patch_records, sanitizer_gpu_patch_record_num * sanitizer_gpu_patch_record_size));
HPCRUN_SANITIZER_CALL(sanitizerMemset,
(gpu_patch_records, 0, sanitizer_gpu_patch_record_num * sanitizer_gpu_patch_record_size, priority_stream));
PRINT("Sanitizer-> Allocate gpu_patch_records %p, size %zu\n", \
gpu_patch_records, sanitizer_gpu_patch_record_num * sanitizer_gpu_patch_record_size);
// Allocate reset record
sanitizer_gpu_patch_buffer_reset = (gpu_patch_buffer_t *)hpcrun_malloc_safe(sizeof(gpu_patch_buffer_t));
sanitizer_gpu_patch_buffer_reset->full = 0;
sanitizer_gpu_patch_buffer_reset->analysis = 0;
sanitizer_gpu_patch_buffer_reset->head_index = 0;
sanitizer_gpu_patch_buffer_reset->tail_index = 0;
sanitizer_gpu_patch_buffer_reset->size = sanitizer_gpu_patch_record_num;
sanitizer_gpu_patch_buffer_reset->num_threads = 0;
sanitizer_gpu_patch_buffer_reset->type = sanitizer_gpu_patch_type;
sanitizer_gpu_patch_buffer_reset->flags = GPU_PATCH_NONE;
sanitizer_gpu_patch_buffer_reset->aux = NULL;
sanitizer_gpu_patch_buffer_reset->records = gpu_patch_records;
if (sanitizer_gpu_analysis_blocks != 0) {
sanitizer_gpu_patch_buffer_reset->flags |= GPU_PATCH_ANALYSIS;
}
if (sanitizer_read_trace_ignore) {
void *gpu_patch_aux = NULL;
// Use a dict to filter read trace
HPCRUN_SANITIZER_CALL(sanitizerAlloc, (context, (void **)(&(gpu_patch_aux)), sizeof(gpu_patch_aux_address_dict_t)));
HPCRUN_SANITIZER_CALL(sanitizerMemset, (gpu_patch_aux, 0, sizeof(gpu_patch_aux_address_dict_t), priority_stream));
PRINT("Sanitizer-> Allocate gpu_patch_aux %p, size %zu\n", gpu_patch_aux, sizeof(gpu_patch_aux_address_dict_t));
// Update map
sanitizer_gpu_patch_buffer_reset->aux = gpu_patch_aux;
sanitizer_context_map_aux_addr_dict_device_update(context, gpu_patch_aux);
}
HPCRUN_SANITIZER_CALL(sanitizerMemcpyHostToDeviceAsync,
(sanitizer_gpu_patch_buffer_device, sanitizer_gpu_patch_buffer_reset, sizeof(gpu_patch_buffer_t), priority_stream));
// Update map
sanitizer_context_map_buffer_device_update(context, sanitizer_gpu_patch_buffer_device);
sanitizer_context_map_buffer_reset_update(context, sanitizer_gpu_patch_buffer_reset);
if (sanitizer_gpu_analysis_blocks != 0) {
// Read
HPCRUN_SANITIZER_CALL(sanitizerAlloc, (context, (void **)(&(sanitizer_gpu_patch_buffer_addr_read_device)),
sizeof(gpu_patch_buffer_t)));
HPCRUN_SANITIZER_CALL(sanitizerMemset, (sanitizer_gpu_patch_buffer_addr_read_device, 0,
sizeof(gpu_patch_buffer_t), priority_stream));
PRINT("Sanitizer-> Allocate sanitizer_gpu_patch_buffer_addr_read_device %p, size %zu\n", \
sanitizer_gpu_patch_buffer_addr_read_device, sizeof(gpu_patch_buffer_t));
// gpu_patch_buffer_t->records
HPCRUN_SANITIZER_CALL(sanitizerAlloc,
(context, &gpu_patch_records, sanitizer_gpu_analysis_record_num * sanitizer_gpu_analysis_record_size));
HPCRUN_SANITIZER_CALL(sanitizerMemset,
(gpu_patch_records, 0, sanitizer_gpu_analysis_record_num * sanitizer_gpu_analysis_record_size, priority_stream));
PRINT("Sanitizer-> Allocate gpu_patch_records %p, size %zu\n", \
gpu_patch_records, sanitizer_gpu_analysis_record_num * sanitizer_gpu_analysis_record_size);
sanitizer_gpu_patch_buffer_addr_read_reset = (gpu_patch_buffer_t *)hpcrun_malloc_safe(sizeof(gpu_patch_buffer_t));
sanitizer_gpu_patch_buffer_addr_read_reset->full = 0;
sanitizer_gpu_patch_buffer_addr_read_reset->analysis = 0;
sanitizer_gpu_patch_buffer_addr_read_reset->head_index = 0;
sanitizer_gpu_patch_buffer_addr_read_reset->tail_index = 0;
sanitizer_gpu_patch_buffer_addr_read_reset->size = sanitizer_gpu_analysis_record_num;
sanitizer_gpu_patch_buffer_addr_read_reset->num_threads = GPU_PATCH_ANALYSIS_THREADS;
sanitizer_gpu_patch_buffer_addr_read_reset->type = GPU_PATCH_TYPE_ADDRESS_ANALYSIS;
sanitizer_gpu_patch_buffer_addr_read_reset->flags = GPU_PATCH_READ | GPU_PATCH_ANALYSIS;
sanitizer_gpu_patch_buffer_addr_read_reset->aux = NULL;
sanitizer_gpu_patch_buffer_addr_read_reset->records = gpu_patch_records;
HPCRUN_SANITIZER_CALL(sanitizerMemcpyHostToDeviceAsync, (sanitizer_gpu_patch_buffer_addr_read_device,
sanitizer_gpu_patch_buffer_addr_read_reset, sizeof(gpu_patch_buffer_t), priority_stream));
// Write
HPCRUN_SANITIZER_CALL(sanitizerAlloc, (context, (void **)(&(sanitizer_gpu_patch_buffer_addr_write_device)),
sizeof(gpu_patch_buffer_t)));
HPCRUN_SANITIZER_CALL(sanitizerMemset, (sanitizer_gpu_patch_buffer_addr_write_device, 0,
sizeof(gpu_patch_buffer_t), priority_stream));
PRINT("Sanitizer-> Allocate sanitizer_gpu_patch_buffer_addr_write_device %p, size %zu\n",
sanitizer_gpu_patch_buffer_addr_write_device, sizeof(gpu_patch_buffer_t));
// gpu_patch_buffer_t->records
HPCRUN_SANITIZER_CALL(sanitizerAlloc,
(context, &gpu_patch_records, sanitizer_gpu_analysis_record_num * sanitizer_gpu_analysis_record_size));
HPCRUN_SANITIZER_CALL(sanitizerMemset,
(gpu_patch_records, 0, sanitizer_gpu_analysis_record_num * sanitizer_gpu_analysis_record_size, priority_stream));
PRINT("Sanitizer-> Allocate gpu_patch_records %p, size %zu\n", \
gpu_patch_records, sanitizer_gpu_analysis_record_num * sanitizer_gpu_analysis_record_size);
sanitizer_gpu_patch_buffer_addr_write_reset = (gpu_patch_buffer_t *)hpcrun_malloc_safe(sizeof(gpu_patch_buffer_t));
sanitizer_gpu_patch_buffer_addr_write_reset->full = 0;
sanitizer_gpu_patch_buffer_addr_write_reset->analysis = 0;
sanitizer_gpu_patch_buffer_addr_write_reset->head_index = 0;
sanitizer_gpu_patch_buffer_addr_write_reset->tail_index = 0;
sanitizer_gpu_patch_buffer_addr_write_reset->size = sanitizer_gpu_analysis_record_num;
sanitizer_gpu_patch_buffer_addr_write_reset->num_threads = GPU_PATCH_ANALYSIS_THREADS;
sanitizer_gpu_patch_buffer_addr_write_reset->type = GPU_PATCH_TYPE_ADDRESS_ANALYSIS;
sanitizer_gpu_patch_buffer_addr_write_reset->flags = GPU_PATCH_WRITE | GPU_PATCH_ANALYSIS;
sanitizer_gpu_patch_buffer_addr_write_reset->aux = NULL;
sanitizer_gpu_patch_buffer_addr_write_reset->records = gpu_patch_records;
HPCRUN_SANITIZER_CALL(sanitizerMemcpyHostToDeviceAsync, (sanitizer_gpu_patch_buffer_addr_write_device,
sanitizer_gpu_patch_buffer_addr_write_reset, sizeof(gpu_patch_buffer_t), priority_stream));
// Update map
sanitizer_context_map_buffer_addr_read_device_update(context, sanitizer_gpu_patch_buffer_addr_read_device);
sanitizer_context_map_buffer_addr_write_device_update(context, sanitizer_gpu_patch_buffer_addr_write_device);
sanitizer_context_map_buffer_addr_read_reset_update(context, sanitizer_gpu_patch_buffer_addr_read_reset);
sanitizer_context_map_buffer_addr_write_reset_update(context, sanitizer_gpu_patch_buffer_addr_write_reset);
}
// Ensure data copy is done
HPCRUN_SANITIZER_CALL(sanitizerStreamSynchronize, (priority_stream));
}
}
static void
sanitizer_load_callback
(
CUcontext context,
CUmodule module,
const void *cubin,
size_t cubin_size
)
{
hpctoolkit_cumod_st_t *cumod = (hpctoolkit_cumod_st_t *)module;
uint32_t cubin_id = cumod->cubin_id;
uint32_t mod_id = cumod->mod_id;
// Compute hash for cubin and store it into a map
cubin_hash_map_entry_t *cubin_hash_entry = cubin_hash_map_lookup(cubin_id);
unsigned char *hash;
unsigned int hash_len;
if (cubin_hash_entry == NULL) {
cubin_hash_map_insert(cubin_id, cubin, cubin_size);
cubin_hash_entry = cubin_hash_map_lookup(cubin_id);
}
hash = cubin_hash_map_entry_hash_get(cubin_hash_entry, &hash_len);
// Create file name
char file_name[PATH_MAX];
size_t i;
size_t used = 0;
used += sprintf(&file_name[used], "%s", hpcrun_files_output_directory());
used += sprintf(&file_name[used], "%s", "/cubins/");
mkdir(file_name, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
for (i = 0; i < hash_len; ++i) {
used += sprintf(&file_name[used], "%02x", hash[i]);
}
used += sprintf(&file_name[used], "%s", ".cubin");
PRINT("Sanitizer-> cubin_id %d hash %s\n", cubin_id, file_name);
uint32_t hpctoolkit_module_id;
load_module_t *load_module = NULL;
hpcrun_loadmap_lock();
if ((load_module = hpcrun_loadmap_findByName(file_name)) == NULL) {
hpctoolkit_module_id = hpcrun_loadModule_add(file_name);
} else {
hpctoolkit_module_id = load_module->id;
}
hpcrun_loadmap_unlock();
PRINT("Sanitizer-> <cubin_id %d, mod_id %d> -> hpctoolkit_module_id %d\n", cubin_id, mod_id, hpctoolkit_module_id);
// Compute elf vector
Elf_SymbolVector *elf_vector = computeCubinFunctionOffsets(cubin, cubin_size);
// Register cubin module
cubin_id_map_insert(cubin_id, hpctoolkit_module_id, elf_vector);
// Query cubin function offsets
uint64_t *addrs = (uint64_t *)hpcrun_malloc_safe(sizeof(uint64_t) * elf_vector->nsymbols);
for (i = 0; i < elf_vector->nsymbols; ++i) {
addrs[i] = 0;
if (elf_vector->symbols[i] != 0) {
uint64_t pc;
uint64_t size;
// do not check error
HPCRUN_SANITIZER_CALL_NO_CHECK(sanitizerGetFunctionPcAndSize, (module, elf_vector->names[i], &pc, &size));
addrs[i] = pc;
}
}
redshow_cubin_cache_register(cubin_id, mod_id, elf_vector->nsymbols, addrs, file_name);
PRINT("Sanitizer-> Context %p Patch CUBIN: \n", context);
PRINT("Sanitizer-> %s\n", HPCTOOLKIT_GPU_PATCH);
// patch binary
if (sanitizer_gpu_patch_type == GPU_PATCH_TYPE_ADDRESS_PATCH) {
// Only analyze global memory
HPCRUN_SANITIZER_CALL(sanitizerAddPatchesFromFile, (HPCTOOLKIT_GPU_PATCH "gpu-patch-address.fatbin", context));
HPCRUN_SANITIZER_CALL(sanitizerPatchInstructions,
(SANITIZER_INSTRUCTION_GLOBAL_MEMORY_ACCESS, module, "sanitizer_global_memory_access_callback"));
} else {
HPCRUN_SANITIZER_CALL(sanitizerAddPatchesFromFile, (HPCTOOLKIT_GPU_PATCH "gpu-patch.fatbin", context));
HPCRUN_SANITIZER_CALL(sanitizerPatchInstructions,
(SANITIZER_INSTRUCTION_GLOBAL_MEMORY_ACCESS, module, "sanitizer_global_memory_access_callback"));
HPCRUN_SANITIZER_CALL(sanitizerPatchInstructions,
(SANITIZER_INSTRUCTION_SHARED_MEMORY_ACCESS, module, "sanitizer_shared_memory_access_callback"));
HPCRUN_SANITIZER_CALL(sanitizerPatchInstructions,
(SANITIZER_INSTRUCTION_LOCAL_MEMORY_ACCESS, module, "sanitizer_local_memory_access_callback"));
HPCRUN_SANITIZER_CALL(sanitizerPatchInstructions,
(SANITIZER_INSTRUCTION_BLOCK_ENTER, module, "sanitizer_block_enter_callback"));
}
HPCRUN_SANITIZER_CALL(sanitizerPatchInstructions,
(SANITIZER_INSTRUCTION_BLOCK_EXIT, module, "sanitizer_block_exit_callback"));
HPCRUN_SANITIZER_CALL(sanitizerPatchModule, (module));
sanitizer_buffer_init(context);
}
static void
sanitizer_unload_callback
(
const void *module,
const void *cubin,
size_t cubin_size
)
{
hpctoolkit_cumod_st_t *cumod = (hpctoolkit_cumod_st_t *)module;
cuda_unload_callback(cumod->cubin_id);
// We cannot unregister cubins
//redshow_cubin_unregister(cumod->cubin_id, cumod->mod_id);
}
//******************************************************************************
// record handlers
//******************************************************************************
static void __attribute__((unused))
dim3_id_transform
(
dim3 dim,
uint32_t flat_id,
uint32_t *id_x,
uint32_t *id_y,
uint32_t *id_z
)
{
*id_z = flat_id / (dim.x * dim.y);
*id_y = (flat_id - (*id_z) * dim.x * dim.y) / (dim.x);
*id_x = (flat_id - (*id_z) * dim.x * dim.y - (*id_y) * dim.x);
}
static Sanitizer_StreamHandle
sanitizer_priority_stream_get
(
CUcontext context
)
{
sanitizer_context_map_entry_t *entry = sanitizer_context_map_init(context);
Sanitizer_StreamHandle priority_stream_handle =
sanitizer_context_map_entry_priority_stream_handle_get(entry);
if (priority_stream_handle == NULL) {
// First time
// Update priority stream
CUstream priority_stream = sanitizer_context_map_entry_priority_stream_get(entry);
HPCRUN_SANITIZER_CALL(sanitizerGetStreamHandle, (context, priority_stream, &priority_stream_handle));
sanitizer_context_map_priority_stream_handle_update(context, priority_stream_handle);
}
return priority_stream_handle;
}
static Sanitizer_StreamHandle
sanitizer_kernel_stream_get
(
CUcontext context
)
{
sanitizer_context_map_entry_t *entry = sanitizer_context_map_init(context);
Sanitizer_StreamHandle kernel_stream_handle =
sanitizer_context_map_entry_kernel_stream_handle_get(entry);
if (kernel_stream_handle == NULL) {
// First time
// Update kernel stream
CUstream kernel_stream = sanitizer_context_map_entry_kernel_stream_get(entry);
HPCRUN_SANITIZER_CALL(sanitizerGetStreamHandle, (context, kernel_stream, &kernel_stream_handle));
sanitizer_context_map_kernel_stream_handle_update(context, kernel_stream_handle);
}
return kernel_stream_handle;
}
static void
sanitizer_module_load
(
CUcontext context
)
{
CUmodule analysis_module = NULL;
CUfunction analysis_function = NULL;
cuda_module_load(&analysis_module, HPCTOOLKIT_GPU_PATCH "gpu-analysis.fatbin");
cuda_module_function_get(&analysis_function, analysis_module, "gpu_analysis_interval_merge");
sanitizer_context_map_analysis_function_update(context, analysis_function);
PRINT("Sanitizer-> context %p load function gpu_analysis_interval_merge %p\n", context, analysis_function);
}
static void
sanitizer_kernel_launch
(
CUcontext context
)
{
sanitizer_context_map_entry_t *entry = sanitizer_context_map_init(context);
// Get raw priority stream and function
CUfunction analysis_function = sanitizer_context_map_entry_analysis_function_get(entry);
CUstream kernel_stream = sanitizer_context_map_entry_kernel_stream_get(entry);
// First time get function
if (analysis_function == NULL) {
sanitizer_module_load(context);
}
// Launch analysis function
if (analysis_function != NULL) {
void *args[] = { (void *)&sanitizer_gpu_patch_buffer_device, (void *)&sanitizer_gpu_patch_buffer_addr_read_device,
(void *)&sanitizer_gpu_patch_buffer_addr_write_device };
cuda_kernel_launch(analysis_function, sanitizer_gpu_analysis_blocks, 1, 1,
GPU_PATCH_ANALYSIS_THREADS, 1, 1, 0, kernel_stream, args);
PRINT("Sanitizer-> context %p launch function gpu_analysis_interval_merge %p <%u, %u>\n", \
context, analysis_function, sanitizer_gpu_analysis_blocks, GPU_PATCH_ANALYSIS_THREADS);
}
}
static void
buffer_analyze
(
int32_t persistent_id,
uint64_t correlation_id,
uint32_t cubin_id,
uint32_t mod_id,
uint32_t gpu_patch_type,
size_t record_size,
gpu_patch_buffer_t *gpu_patch_buffer_host,
gpu_patch_buffer_t *gpu_patch_buffer_device,
Sanitizer_StreamHandle priority_stream
)
{
sanitizer_buffer_t *sanitizer_buffer = sanitizer_buffer_channel_produce(
sanitizer_thread_id_local, cubin_id, mod_id, persistent_id, correlation_id, gpu_patch_type,
sanitizer_gpu_patch_record_num, sanitizer_analysis_async);
gpu_patch_buffer_t *gpu_patch_buffer = sanitizer_buffer_entry_gpu_patch_buffer_get(sanitizer_buffer);
// If sync mode and not enough buffer, empty current buffer
if (gpu_patch_buffer == NULL && !sanitizer_analysis_async) {
sanitizer_buffer_channel_t *channel = sanitizer_buffer_channel_get(gpu_patch_type);
sanitizer_buffer_channel_consume(channel);
// Get it again
sanitizer_buffer = sanitizer_buffer_channel_produce(
sanitizer_thread_id_local, cubin_id, mod_id, persistent_id, correlation_id, gpu_patch_type,
sanitizer_gpu_patch_record_num, sanitizer_analysis_async);
gpu_patch_buffer = sanitizer_buffer_entry_gpu_patch_buffer_get(sanitizer_buffer);
}
// Move host buffer to a cache
memcpy(gpu_patch_buffer, gpu_patch_buffer_host, offsetof(gpu_patch_buffer_t, records));
// Copy all records to the cache
size_t num_records = gpu_patch_buffer_host->head_index;
void *gpu_patch_record_device = gpu_patch_buffer_host->records;
if (num_records != 0) {
HPCRUN_SANITIZER_CALL(sanitizerMemcpyDeviceToHost,
(gpu_patch_buffer->records, gpu_patch_record_device, record_size * num_records, priority_stream));
PRINT("Sanitizer-> copy num_records %zu\n", num_records);
}
// Tell kernel to continue
// Do not need to sync stream.
// The function will return once the pageable buffer has been copied to the staging memory.
// for DMA transfer to device memory, but the DMA to final destination may not have completed.
// Only copy the first field because other fields are being updated by the GPU.
gpu_patch_buffer_host->full = 0;
HPCRUN_SANITIZER_CALL(sanitizerMemcpyHostToDeviceAsync, (gpu_patch_buffer_device, gpu_patch_buffer_host,
sizeof(gpu_patch_buffer_host->full), priority_stream));
sanitizer_buffer_channel_push(sanitizer_buffer, gpu_patch_type);
}
static void
sanitizer_kernel_analyze
(
int32_t persistent_id,
uint64_t correlation_id,
uint32_t cubin_id,
uint32_t mod_id,
Sanitizer_StreamHandle priority_stream,
Sanitizer_StreamHandle kernel_stream,
bool analysis_end
)
{
if (analysis_end) {
HPCRUN_SANITIZER_CALL(sanitizerMemcpyDeviceToHost,
(sanitizer_gpu_patch_buffer_addr_read_host, sanitizer_gpu_patch_buffer_addr_read_device,
sizeof(gpu_patch_buffer_t), priority_stream));
HPCRUN_SANITIZER_CALL(sanitizerMemcpyDeviceToHost,
(sanitizer_gpu_patch_buffer_addr_write_host, sanitizer_gpu_patch_buffer_addr_write_device,
sizeof(gpu_patch_buffer_t), priority_stream));
while (sanitizer_gpu_patch_buffer_addr_read_host->num_threads != 0) {
if (sanitizer_gpu_patch_buffer_addr_read_host->full != 0) {
PRINT("Sanitizer-> read analysis address\n");
buffer_analyze(persistent_id, correlation_id, cubin_id, mod_id, GPU_PATCH_TYPE_ADDRESS_ANALYSIS,
sanitizer_gpu_analysis_record_size, sanitizer_gpu_patch_buffer_addr_read_host,
sanitizer_gpu_patch_buffer_addr_read_device, priority_stream);
}
if (sanitizer_gpu_patch_buffer_addr_write_host->full != 0) {
PRINT("Sanitizer-> write analysis address\n");
buffer_analyze(persistent_id, correlation_id, cubin_id, mod_id, GPU_PATCH_TYPE_ADDRESS_ANALYSIS,
sanitizer_gpu_analysis_record_size, sanitizer_gpu_patch_buffer_addr_write_host,
sanitizer_gpu_patch_buffer_addr_write_device, priority_stream);
}
HPCRUN_SANITIZER_CALL(sanitizerMemcpyDeviceToHost,
(sanitizer_gpu_patch_buffer_addr_read_host, sanitizer_gpu_patch_buffer_addr_read_device,
sizeof(gpu_patch_buffer_t), priority_stream));
HPCRUN_SANITIZER_CALL(sanitizerMemcpyDeviceToHost,
(sanitizer_gpu_patch_buffer_addr_write_host, sanitizer_gpu_patch_buffer_addr_write_device,
sizeof(gpu_patch_buffer_t), priority_stream));
}
// To ensure analysis is done
HPCRUN_SANITIZER_CALL(sanitizerStreamSynchronize, (kernel_stream));
// Last analysis
PRINT("Sanitizer-> read analysis address\n");
buffer_analyze(persistent_id, correlation_id, cubin_id, mod_id, GPU_PATCH_TYPE_ADDRESS_ANALYSIS,
sanitizer_gpu_analysis_record_size, sanitizer_gpu_patch_buffer_addr_read_host,
sanitizer_gpu_patch_buffer_addr_read_device, priority_stream);
PRINT("Sanitizer-> write analysis address\n");
buffer_analyze(persistent_id, correlation_id, cubin_id, mod_id, GPU_PATCH_TYPE_ADDRESS_ANALYSIS,
sanitizer_gpu_analysis_record_size, sanitizer_gpu_patch_buffer_addr_write_host,
sanitizer_gpu_patch_buffer_addr_write_device, priority_stream);
// Do not enter later code
PRINT("Sanitizer-> analysis gpu done\n");
return;
}
HPCRUN_SANITIZER_CALL(sanitizerMemcpyDeviceToHost,
(sanitizer_gpu_patch_buffer_addr_read_host, sanitizer_gpu_patch_buffer_addr_read_device,
sizeof(gpu_patch_buffer_t), priority_stream));
if (sanitizer_gpu_patch_buffer_addr_read_host->full != 0) {
PRINT("Sanitizer-> read analysis address\n");
buffer_analyze(persistent_id, correlation_id, cubin_id, mod_id, GPU_PATCH_TYPE_ADDRESS_ANALYSIS,
sanitizer_gpu_analysis_record_size, sanitizer_gpu_patch_buffer_addr_read_host,
sanitizer_gpu_patch_buffer_addr_read_device, priority_stream);
PRINT("Sanitizer-> analysis gpu in process\n");
}
HPCRUN_SANITIZER_CALL(sanitizerMemcpyDeviceToHost,
(sanitizer_gpu_patch_buffer_addr_write_host, sanitizer_gpu_patch_buffer_addr_write_device,
sizeof(gpu_patch_buffer_t), priority_stream));
if (sanitizer_gpu_patch_buffer_addr_write_host->full != 0) {
PRINT("Sanitizer-> write analysis address\n");
buffer_analyze(persistent_id, correlation_id, cubin_id, mod_id, GPU_PATCH_TYPE_ADDRESS_ANALYSIS,
sanitizer_gpu_analysis_record_size, sanitizer_gpu_patch_buffer_addr_write_host,
sanitizer_gpu_patch_buffer_addr_write_device, priority_stream);
PRINT("Sanitizer-> analysis gpu in process\n");
}
}
static void
sanitizer_kernel_launch_sync
(
int32_t persistent_id,
uint64_t correlation_id,
CUcontext context,
CUmodule module,
CUfunction function,
Sanitizer_StreamHandle priority_stream,
Sanitizer_StreamHandle kernel_stream,
dim3 grid_size,
dim3 block_size
)
{
// Look up module id
hpctoolkit_cumod_st_t *cumod = (hpctoolkit_cumod_st_t *)module;
uint32_t cubin_id = cumod->cubin_id;
uint32_t mod_id = cumod->mod_id;
// TODO(Keren): correlate metrics with api_node
int block_sampling_frequency = sanitizer_block_sampling_frequency_get();
int grid_dim = grid_size.x * grid_size.y * grid_size.z;
int block_dim = block_size.x * block_size.y * block_size.z;
uint64_t num_threads = grid_dim * block_dim;
size_t num_left_threads = 0;
// If block sampling is set
if (block_sampling_frequency != 0) {
// Uniform sampling
int sampling_offset = sanitizer_gpu_patch_buffer_reset->block_sampling_offset;
int mod_blocks = grid_dim % block_sampling_frequency;
int sampling_blocks = 0;
if (mod_blocks == 0) {
sampling_blocks = (grid_dim - 1) / block_sampling_frequency + 1;
} else {
sampling_blocks = (grid_dim - 1) / block_sampling_frequency + (sampling_offset >= mod_blocks ? 0 : 1);
}
num_left_threads = num_threads - sampling_blocks * block_dim;
}
// Init a buffer on host
if (sanitizer_gpu_patch_buffer_host == NULL) {
sanitizer_gpu_patch_buffer_host = (gpu_patch_buffer_t *)hpcrun_malloc_safe(sizeof(gpu_patch_buffer_t));
if (sanitizer_gpu_analysis_blocks != 0) {
sanitizer_gpu_patch_buffer_addr_read_host = (gpu_patch_buffer_t *)hpcrun_malloc_safe(sizeof(gpu_patch_buffer_t));
sanitizer_gpu_patch_buffer_addr_write_host = (gpu_patch_buffer_t *)hpcrun_malloc_safe(sizeof(gpu_patch_buffer_t));
}
}
// Reserve for debugging correctness
//PRINT("head_index %u, tail_index %u, num_left_threads %lu\n",
// sanitizer_gpu_patch_buffer_host->head_index, sanitizer_gpu_patch_buffer_host->tail_index, num_threads);
while (true) {
// Copy buffer
HPCRUN_SANITIZER_CALL(sanitizerMemcpyDeviceToHost,
(sanitizer_gpu_patch_buffer_host, sanitizer_gpu_patch_buffer_device, sizeof(gpu_patch_buffer_t), priority_stream));
size_t num_records = sanitizer_gpu_patch_buffer_host->head_index;
// Reserve for debugging correctness
//PRINT("head_index %u, tail_index %u, num_left_threads %u expected %zu\n",
// sanitizer_gpu_patch_buffer_host->head_index, sanitizer_gpu_patch_buffer_host->tail_index, sanitizer_gpu_patch_buffer_host->num_threads, num_left_threads);
if (sanitizer_gpu_analysis_blocks != 0) {
sanitizer_kernel_analyze(persistent_id, correlation_id, cubin_id, mod_id, priority_stream, kernel_stream, false);
}
// Wait until the buffer is full or the kernel is finished
if (!(sanitizer_gpu_patch_buffer_host->num_threads == num_left_threads || sanitizer_gpu_patch_buffer_host->full)) {
continue;
}
// Reserve for debugging correctness
//PRINT("num_records %zu\n", num_records);
if (sanitizer_gpu_analysis_blocks == 0) {
buffer_analyze(persistent_id, correlation_id, cubin_id, mod_id, sanitizer_gpu_patch_type,
sanitizer_gpu_patch_record_size, sanitizer_gpu_patch_buffer_host,
sanitizer_gpu_patch_buffer_device, priority_stream);
PRINT("Sanitizer-> analysis cpu in process\n");
}
// Awake background thread
if (sanitizer_analysis_async) {
// If multiple application threads are created, it might miss a signal,
// but we finally still process all the records
sanitizer_process_signal();
}
// Finish all the threads
if (sanitizer_gpu_patch_buffer_host->num_threads == num_left_threads) {
break;
}
}
if (sanitizer_gpu_analysis_blocks != 0) {
// Kernel is done
sanitizer_kernel_analyze(persistent_id, correlation_id, cubin_id, mod_id, priority_stream, kernel_stream, true);
}
// To ensure previous copies are done
HPCRUN_SANITIZER_CALL(sanitizerStreamSynchronize, (priority_stream));
if (!sanitizer_analysis_async) {
// Empty current buffer
sanitizer_buffer_channel_t *channel = sanitizer_buffer_channel_get(sanitizer_gpu_patch_type);
sanitizer_buffer_channel_consume(channel);
if (sanitizer_gpu_analysis_blocks != 0) {
channel = sanitizer_buffer_channel_get(sanitizer_gpu_analysis_type);
sanitizer_buffer_channel_consume(channel);
}
}
}
//******************************************************************************
// callbacks
//******************************************************************************
static void
sanitizer_kernel_launch_callback
(
uint64_t correlation_id,
CUcontext context,
Sanitizer_StreamHandle priority_stream,
CUfunction function,
dim3 grid_size,
dim3 block_size,
bool kernel_sampling
)
{
int grid_dim = grid_size.x * grid_size.y * grid_size.z;
int block_dim = block_size.x * block_size.y * block_size.z;
int block_sampling_frequency = kernel_sampling ? sanitizer_block_sampling_frequency_get() : 0;
int block_sampling_offset = kernel_sampling ? rand() % grid_dim % block_sampling_frequency : 0;
PRINT("Sanitizer-> kernel sampling %d\n", kernel_sampling);
PRINT("Sanitizer-> sampling offset %d\n", block_sampling_offset);
PRINT("Sanitizer-> sampling frequency %d\n", block_sampling_frequency);
// Get cached entries, already locked
sanitizer_buffer_init(context);
// reset buffer
sanitizer_gpu_patch_buffer_reset->num_threads = grid_dim * block_dim;
sanitizer_gpu_patch_buffer_reset->block_sampling_frequency = block_sampling_frequency;
sanitizer_gpu_patch_buffer_reset->block_sampling_offset = block_sampling_offset;
HPCRUN_SANITIZER_CALL(sanitizerMemcpyHostToDeviceAsync,
(sanitizer_gpu_patch_buffer_device, sanitizer_gpu_patch_buffer_reset,
sizeof(gpu_patch_buffer_t), priority_stream));
if (sanitizer_gpu_analysis_blocks != 0) {
HPCRUN_SANITIZER_CALL(sanitizerMemcpyHostToDeviceAsync, (sanitizer_gpu_patch_buffer_addr_read_device,
sanitizer_gpu_patch_buffer_addr_read_reset, sizeof(gpu_patch_buffer_t), priority_stream));
HPCRUN_SANITIZER_CALL(sanitizerMemcpyHostToDeviceAsync, (sanitizer_gpu_patch_buffer_addr_write_device,
sanitizer_gpu_patch_buffer_addr_write_reset, sizeof(gpu_patch_buffer_t), priority_stream));
}
if (sanitizer_read_trace_ignore) {
if (sanitizer_gpu_patch_aux_addr_dict_host == NULL) {
sanitizer_gpu_patch_aux_addr_dict_host = (gpu_patch_aux_address_dict_t *)
hpcrun_malloc_safe(sizeof(gpu_patch_aux_address_dict_t));
}
memset(sanitizer_gpu_patch_aux_addr_dict_host->hit, 0, sizeof(uint32_t) * GPU_PATCH_ADDRESS_DICT_SIZE);
// Get memory ranges from redshow
uint64_t limit = GPU_PATCH_ADDRESS_DICT_SIZE;
redshow_memory_ranges_get(correlation_id, limit, sanitizer_gpu_patch_aux_addr_dict_host->start_end,
&sanitizer_gpu_patch_aux_addr_dict_host->size);
// Copy
HPCRUN_SANITIZER_CALL(sanitizerMemcpyHostToDeviceAsync,
(sanitizer_gpu_patch_buffer_reset->aux, sanitizer_gpu_patch_aux_addr_dict_host,
sizeof(gpu_patch_aux_address_dict_t), priority_stream));
}
HPCRUN_SANITIZER_CALL(sanitizerSetCallbackData, (function, sanitizer_gpu_patch_buffer_device));
HPCRUN_SANITIZER_CALL(sanitizerStreamSynchronize, (priority_stream));
}
//-------------------------------------------------------------
// callback controls
//-------------------------------------------------------------
static void
sanitizer_subscribe_callback
(
void* userdata,
Sanitizer_CallbackDomain domain,
Sanitizer_CallbackId cbid,
const void* cbdata
)
{
if (cuda_api_internal()) {
return;
}
if (!sanitizer_stop_flag) {
sanitizer_thread_id_local = atomic_fetch_add(&sanitizer_thread_id, 1);
sanitizer_stop_flag_set();
}
if (domain == SANITIZER_CB_DOMAIN_DRIVER_API) {
Sanitizer_CallbackData *cb = (Sanitizer_CallbackData *)cbdata;
if (cb->callbackSite == SANITIZER_API_ENTER) {
// Reserve for debug
//PRINT("Sanitizer-> Thread %u enter context %p function %s\n", sanitizer_thread_id_local, cb->context, cb->functionName);
sanitizer_context_map_context_lock(cb->context, sanitizer_thread_id_local);
sanitizer_thread_context = cb->context;
} else {
// Reserve for debug
//PRINT("Sanitizer-> Thread %u exit context %p function %s\n", sanitizer_thread_id_local, cb->context, cb->functionName);
// Caution, do not use cb->context. When cuCtxGetCurrent is used, cb->context != sanitizer_thread_context
sanitizer_context_map_context_unlock(sanitizer_thread_context, sanitizer_thread_id_local);
sanitizer_thread_context = NULL;
}
return;
}
// XXX(keren): assume single thread per stream
if (domain == SANITIZER_CB_DOMAIN_RESOURCE) {
switch (cbid) {
case SANITIZER_CBID_RESOURCE_MODULE_LOADED:
{
// single thread
Sanitizer_ResourceModuleData *md = (Sanitizer_ResourceModuleData *)cbdata;
sanitizer_load_callback(md->context, md->module, md->pCubin, md->cubinSize);
break;
}
case SANITIZER_CBID_RESOURCE_MODULE_UNLOAD_STARTING:
{
// single thread
Sanitizer_ResourceModuleData *md = (Sanitizer_ResourceModuleData *)cbdata;
sanitizer_unload_callback(md->module, md->pCubin, md->cubinSize);
break;
}
case SANITIZER_CBID_RESOURCE_STREAM_CREATED:
{
// single thread
PRINT("Sanitizer-> Stream create starting\n");
break;
}
case SANITIZER_CBID_RESOURCE_STREAM_DESTROY_STARTING:
{
// single thread
// TODO
PRINT("Sanitizer-> Stream destroy starting\n");
break;
}
case SANITIZER_CBID_RESOURCE_CONTEXT_CREATION_STARTING:
{
PRINT("Sanitizer-> Context creation starting\n");
sanitizer_context_creation_flag = true;
break;
}
case SANITIZER_CBID_RESOURCE_CONTEXT_CREATION_FINISHED:
{
PRINT("Sanitizer-> Context creation finished\n");
sanitizer_context_creation_flag = false;
sanitizer_priority_stream_get(sanitizer_thread_context);
sanitizer_kernel_stream_get(sanitizer_thread_context);
sanitizer_module_load(sanitizer_thread_context);
if (sanitizer_memory_register_delegate.flag) {
redshow_memory_register(
sanitizer_memory_register_delegate.persistent_id,
sanitizer_memory_register_delegate.correlation_id,
sanitizer_memory_register_delegate.start,
sanitizer_memory_register_delegate.end);
sanitizer_memory_register_delegate.flag = false;
}
break;
}
case SANITIZER_CBID_RESOURCE_CONTEXT_DESTROY_STARTING:
{
// single thread
// TODO
PRINT("Sanitizer-> Context destroy starting\n");
break;
}
case SANITIZER_CBID_RESOURCE_HOST_MEMORY_ALLOC:
{
Sanitizer_ResourceMemoryData *md = (Sanitizer_ResourceMemoryData *)cbdata;
PRINT("Sanitizer-> Allocate memory address %p, size %zu\n", (void *)md->address, md->size);
break;
}
case SANITIZER_CBID_RESOURCE_HOST_MEMORY_FREE:
{
Sanitizer_ResourceMemoryData *md = (Sanitizer_ResourceMemoryData *)cbdata;
PRINT("Sanitizer-> Free memory address %p, size %zu\n", (void *)md->address, md->size);
break;
}
case SANITIZER_CBID_RESOURCE_DEVICE_MEMORY_ALLOC:
{
Sanitizer_ResourceMemoryData *md = (Sanitizer_ResourceMemoryData *)cbdata;
uint64_t correlation_id = gpu_correlation_id();
cct_node_t *api_node = sanitizer_correlation_callback(correlation_id, 0);
hpcrun_cct_retain(api_node);
hpcrun_safe_enter();
gpu_op_ccts_t gpu_op_ccts;
gpu_op_placeholder_flags_t gpu_op_placeholder_flags = 0;
gpu_op_placeholder_flags_set(&gpu_op_placeholder_flags,
gpu_placeholder_type_alloc);
gpu_op_ccts_insert(api_node, &gpu_op_ccts, gpu_op_placeholder_flags);
api_node = gpu_op_ccts_get(&gpu_op_ccts, gpu_placeholder_type_alloc);
hpcrun_cct_retain(api_node);
hpcrun_safe_exit();
int32_t persistent_id = hpcrun_cct_persistent_id(api_node);
if (sanitizer_context_creation_flag) {
// For some driver versions, the primary context is not fully initialized here.
// So we have to delay memory register to the point when context initialization is done.
//
// CUDA context is often initalized lazily.
// The primary context is only initialized when seeing cudaDeviceReset or the first CUDA
// runtime API (e.g., cudaMemalloc).
sanitizer_memory_register_delegate.flag = true;
sanitizer_memory_register_delegate.persistent_id = persistent_id;
sanitizer_memory_register_delegate.correlation_id = correlation_id;
sanitizer_memory_register_delegate.start = md->address;
sanitizer_memory_register_delegate.end = md->address + md->size;
} else {
redshow_memory_register(persistent_id, correlation_id, md->address, md->address + md->size);
}
PRINT("Sanitizer-> Allocate memory address %p, size %zu, op %lu, id %d\n",
(void *)md->address, md->size, correlation_id, persistent_id);
break;
}
case SANITIZER_CBID_RESOURCE_DEVICE_MEMORY_FREE:
{
Sanitizer_ResourceMemoryData *md = (Sanitizer_ResourceMemoryData *)cbdata;
uint64_t correlation_id = gpu_correlation_id();
redshow_memory_unregister(correlation_id, md->address, md->address + md->size);
PRINT("Sanitizer-> Free memory address %p, size %zu, op %lu\n", (void *)md->address, md->size, correlation_id);
break;
}
default:
{
break;
}
}
} else if (domain == SANITIZER_CB_DOMAIN_LAUNCH) {
Sanitizer_LaunchData *ld = (Sanitizer_LaunchData *)cbdata;
static __thread dim3 grid_size = { .x = 0, .y = 0, .z = 0};
static __thread dim3 block_size = { .x = 0, .y = 0, .z = 0};
static __thread Sanitizer_StreamHandle priority_stream = NULL;
static __thread Sanitizer_StreamHandle kernel_stream = NULL;
static __thread bool kernel_sampling = true;
static __thread uint64_t correlation_id = 0;
static __thread int32_t persistent_id = 0;
if (cbid == SANITIZER_CBID_LAUNCH_BEGIN) {
// Use function list to filter functions
if (sanitizer_whitelist != NULL) {
if (sanitizer_function_list_lookup(sanitizer_whitelist, ld->functionName) == NULL) {
kernel_sampling = false;
}
}
if (sanitizer_blacklist != NULL) {
if (sanitizer_function_list_lookup(sanitizer_blacklist, ld->functionName) != NULL) {
kernel_sampling = false;
}
}
// Get a place holder cct node
correlation_id = gpu_correlation_id();
// TODO(Keren): why two extra layers?
cct_node_t *api_node = sanitizer_correlation_callback(correlation_id, 0);
hpcrun_cct_retain(api_node);
// Insert a function cct node
hpcrun_safe_enter();
gpu_op_ccts_t gpu_op_ccts;
gpu_op_placeholder_flags_t gpu_op_placeholder_flags = 0;
gpu_op_placeholder_flags_set(&gpu_op_placeholder_flags,
gpu_placeholder_type_kernel);
gpu_op_ccts_insert(api_node, &gpu_op_ccts, gpu_op_placeholder_flags);
api_node = gpu_op_ccts_get(&gpu_op_ccts, gpu_placeholder_type_kernel);
hpcrun_cct_retain(api_node);
hpcrun_safe_exit();
// Look up persisitent id
persistent_id = hpcrun_cct_persistent_id(api_node);
if (kernel_sampling) {
// Kernel is not ignored
// By default ignored this kernel
kernel_sampling = false;
int kernel_sampling_frequency = sanitizer_kernel_sampling_frequency_get();
// TODO(Keren): thread safe rand
kernel_sampling = rand() % kernel_sampling_frequency == 0;
// First time must be sampled
if (sanitizer_op_map_lookup(persistent_id) == NULL) {
kernel_sampling = true;
sanitizer_op_map_init(persistent_id, api_node);
}
}
grid_size.x = ld->gridDim_x;
grid_size.y = ld->gridDim_y;
grid_size.z = ld->gridDim_z;
block_size.x = ld->blockDim_x;
block_size.y = ld->blockDim_y;
block_size.z = ld->blockDim_z;
PRINT("Sanitizer-> Launch kernel %s <%d, %d, %d>:<%d, %d, %d>, op %lu, id %d, mod_id %u\n", ld->functionName,
ld->gridDim_x, ld->gridDim_y, ld->gridDim_z, ld->blockDim_x, ld->blockDim_y, ld->blockDim_z,
correlation_id, persistent_id, ((hpctoolkit_cumod_st_t *)ld->module)->mod_id);
// thread-safe
// Create a high priority stream for the context at the first time
// TODO(Keren): change stream->hstream
redshow_kernel_begin(sanitizer_thread_id_local, persistent_id, correlation_id);
priority_stream = sanitizer_priority_stream_get(ld->context);
sanitizer_kernel_launch_callback(correlation_id, ld->context, priority_stream, ld->function,
grid_size, block_size, kernel_sampling);
} else if (cbid == SANITIZER_CBID_LAUNCH_AFTER_SYSCALL_SETUP) {
if (sanitizer_gpu_analysis_blocks != 0 && kernel_sampling) {
sanitizer_kernel_launch(ld->context);
}
} else if (cbid == SANITIZER_CBID_LAUNCH_END) {
if (kernel_sampling) {
PRINT("Sanitizer-> Sync kernel %s\n", ld->functionName);
kernel_stream = sanitizer_kernel_stream_get(ld->context);
sanitizer_kernel_launch_sync(persistent_id, correlation_id,
ld->context, ld->module, ld->function, priority_stream,
kernel_stream, grid_size, block_size);
}
// NOTICE: Need to synchronize this stream even when this kernel is not sampled.
// TO prevent data is incorrectly copied in the next round
HPCRUN_SANITIZER_CALL(sanitizerStreamSynchronize, (ld->hStream));
redshow_kernel_end(sanitizer_thread_id_local, persistent_id, correlation_id);
kernel_sampling = true;
PRINT("Sanitizer-> kernel %s done\n", ld->functionName);
}
} else if (domain == SANITIZER_CB_DOMAIN_MEMCPY) {
Sanitizer_MemcpyData *md = (Sanitizer_MemcpyData *)cbdata;
bool src_host = false;
bool dst_host = false;
if (md->direction == SANITIZER_MEMCPY_DIRECTION_HOST_TO_DEVICE) {
src_host = true;
} else if (md->direction == SANITIZER_MEMCPY_DIRECTION_HOST_TO_HOST) {
src_host = true;
dst_host = true;
} else if (md->direction == SANITIZER_MEMCPY_DIRECTION_DEVICE_TO_HOST) {
dst_host = true;
}
uint64_t correlation_id = gpu_correlation_id();
cct_node_t *api_node = sanitizer_correlation_callback(correlation_id, 0);
hpcrun_cct_retain(api_node);
int32_t persistent_id = hpcrun_cct_persistent_id(api_node);
if (sanitizer_op_map_lookup(persistent_id) == NULL) {
sanitizer_op_map_init(persistent_id, api_node);
}
PRINT("Sanitizer-> Memcpy async %d direction %d from %p to %p, op %lu, id %d\n", md->isAsync, md->direction,
(void *)md->srcAddress, (void *)md->dstAddress, correlation_id, persistent_id);
// Avoid memcpy to symbol without allocation
// Let redshow update shadow memory
redshow_memcpy_register(persistent_id, correlation_id, src_host, md->srcAddress,
dst_host, md->dstAddress, md->size);
} else if (domain == SANITIZER_CB_DOMAIN_MEMSET) {
Sanitizer_MemsetData *md = (Sanitizer_MemsetData *)cbdata;
uint64_t correlation_id = gpu_correlation_id();
cct_node_t *api_node = sanitizer_correlation_callback(correlation_id, 0);
hpcrun_cct_retain(api_node);
// Let redshow update shadow
int32_t persistent_id = hpcrun_cct_persistent_id(api_node);
redshow_memset_register(persistent_id, correlation_id, md->address, md->value, md->width);
} else if (domain == SANITIZER_CB_DOMAIN_SYNCHRONIZE) {
// TODO(Keren): sync data
}
}
//******************************************************************************
// interfaces
//******************************************************************************
int
sanitizer_bind()
{
#ifndef HPCRUN_STATIC_LINK
// dynamic libraries only availabile in non-static case
hpcrun_force_dlopen(true);
CHK_DLOPEN(sanitizer, sanitizer_path(), RTLD_NOW | RTLD_GLOBAL);
hpcrun_force_dlopen(false);
#define SANITIZER_BIND(fn) \
CHK_DLSYM(sanitizer, fn);
FORALL_SANITIZER_ROUTINES(SANITIZER_BIND)
#undef SANITIZER_BIND
return 0;
#else
return -1;
#endif // ! HPCRUN_STATIC_LINK
}
static void
output_dir_config(char *dir_name, char *suffix) {
size_t used = 0;
used += sprintf(&dir_name[used], "%s", hpcrun_files_output_directory());
used += sprintf(&dir_name[used], "%s", suffix);
mkdir(dir_name, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
}
void
sanitizer_redundancy_analysis_enable()
{
redshow_analysis_enable(REDSHOW_ANALYSIS_SPATIAL_REDUNDANCY);
redshow_analysis_enable(REDSHOW_ANALYSIS_TEMPORAL_REDUNDANCY);
char dir_name[PATH_MAX];
output_dir_config(dir_name, "/redundancy/");
redshow_output_dir_config(REDSHOW_ANALYSIS_SPATIAL_REDUNDANCY, dir_name);
redshow_output_dir_config(REDSHOW_ANALYSIS_TEMPORAL_REDUNDANCY, dir_name);
sanitizer_gpu_patch_record_size = sizeof(gpu_patch_record_t);
}
void
sanitizer_data_flow_analysis_enable()
{
redshow_analysis_enable(REDSHOW_ANALYSIS_DATA_FLOW);
// XXX(Keren): value flow analysis must be sync
sanitizer_analysis_async = false;
char dir_name[PATH_MAX];
output_dir_config(dir_name, "/data_flow/");
redshow_output_dir_config(REDSHOW_ANALYSIS_DATA_FLOW, dir_name);
redshow_analysis_config(REDSHOW_ANALYSIS_DATA_FLOW, REDSHOW_ANALYSIS_DATA_FLOW_HASH, sanitizer_data_flow_hash);
redshow_analysis_config(REDSHOW_ANALYSIS_DATA_FLOW, REDSHOW_ANALYSIS_READ_TRACE_IGNORE, sanitizer_read_trace_ignore);
sanitizer_gpu_patch_type = GPU_PATCH_TYPE_ADDRESS_PATCH;
sanitizer_gpu_patch_record_size = sizeof(gpu_patch_record_address_t);
sanitizer_gpu_analysis_type = GPU_PATCH_TYPE_ADDRESS_ANALYSIS;
sanitizer_gpu_analysis_record_size = sizeof(gpu_patch_analysis_address_t);
}
void
sanitizer_value_pattern_analysis_enable()
{
redshow_analysis_enable(REDSHOW_ANALYSIS_VALUE_PATTERN);
char dir_name[PATH_MAX];
output_dir_config(dir_name, "/value_pattern/");
redshow_output_dir_config(REDSHOW_ANALYSIS_VALUE_PATTERN, dir_name);
sanitizer_gpu_patch_record_size = sizeof(gpu_patch_record_t);
}
void
sanitizer_callbacks_subscribe()
{
sanitizer_correlation_callback = gpu_application_thread_correlation_callback;
redshow_log_data_callback_register(sanitizer_log_data_callback);
redshow_record_data_callback_register(sanitizer_record_data_callback, sanitizer_pc_views, sanitizer_mem_views);
redshow_tool_dtoh_register(sanitizer_dtoh);
HPCRUN_SANITIZER_CALL(sanitizerSubscribe,
(&sanitizer_subscriber_handle, sanitizer_subscribe_callback, NULL));
HPCRUN_SANITIZER_CALL(sanitizerEnableDomain,
(1, sanitizer_subscriber_handle, SANITIZER_CB_DOMAIN_DRIVER_API));
HPCRUN_SANITIZER_CALL(sanitizerEnableDomain,
(1, sanitizer_subscriber_handle, SANITIZER_CB_DOMAIN_RESOURCE));
HPCRUN_SANITIZER_CALL(sanitizerEnableDomain,
(1, sanitizer_subscriber_handle, SANITIZER_CB_DOMAIN_LAUNCH));
HPCRUN_SANITIZER_CALL(sanitizerEnableDomain,
(1, sanitizer_subscriber_handle, SANITIZER_CB_DOMAIN_MEMCPY));
HPCRUN_SANITIZER_CALL(sanitizerEnableDomain,
(1, sanitizer_subscriber_handle, SANITIZER_CB_DOMAIN_MEMSET));
}
void
sanitizer_callbacks_unsubscribe()
{
sanitizer_correlation_callback = 0;
HPCRUN_SANITIZER_CALL(sanitizerUnsubscribe, (sanitizer_subscriber_handle));
HPCRUN_SANITIZER_CALL(sanitizerEnableDomain,
(0, sanitizer_subscriber_handle, SANITIZER_CB_DOMAIN_DRIVER_API));
HPCRUN_SANITIZER_CALL(sanitizerEnableDomain,
(0, sanitizer_subscriber_handle, SANITIZER_CB_DOMAIN_RESOURCE));
HPCRUN_SANITIZER_CALL(sanitizerEnableDomain,
(0, sanitizer_subscriber_handle, SANITIZER_CB_DOMAIN_LAUNCH));
HPCRUN_SANITIZER_CALL(sanitizerEnableDomain,
(0, sanitizer_subscriber_handle, SANITIZER_CB_DOMAIN_MEMCPY));
HPCRUN_SANITIZER_CALL(sanitizerEnableDomain,
(0, sanitizer_subscriber_handle, SANITIZER_CB_DOMAIN_MEMSET));
}
void
sanitizer_async_config
(
bool async
)
{
sanitizer_analysis_async = async;
}
static void
function_list_add
(
sanitizer_function_list_entry_t *head,
char *file_name
)
{
FILE *fp = NULL;
fp = fopen(file_name, "r");
if (fp != NULL) {
char function[FUNCTION_NAME_LENGTH];
while (fgets(function, FUNCTION_NAME_LENGTH, fp) != NULL) {
char *pos = NULL;
if ((pos=strchr(function, '\n')) != NULL)
*pos = '\0';
PRINT("Sanitizer-> Add function %s from %s\n", function, file_name);
sanitizer_function_list_register(head, function);
}
fclose(fp);
}
}
void
sanitizer_function_config
(
char *file_whitelist,
char *file_blacklist
)
{
if (file_whitelist != NULL) {
sanitizer_function_list_init(&sanitizer_whitelist);
function_list_add(sanitizer_whitelist, file_whitelist);
}
if (file_blacklist != NULL) {
sanitizer_function_list_init(&sanitizer_blacklist);
function_list_add(sanitizer_blacklist, file_blacklist);
}
}
void
sanitizer_buffer_config
(
int gpu_patch_record_num,
int buffer_pool_size
)
{
sanitizer_gpu_patch_record_num = gpu_patch_record_num;
sanitizer_gpu_analysis_record_num = gpu_patch_record_num * GPU_PATCH_WARP_SIZE * 4;
sanitizer_buffer_pool_size = buffer_pool_size;
}
void
sanitizer_approx_level_config
(
int approx_level
)
{
sanitizer_approx_level = approx_level;
redshow_approx_level_config(sanitizer_approx_level);
}
void
sanitizer_views_config
(
int pc_views,
int mem_views
)
{
sanitizer_pc_views = pc_views;
sanitizer_mem_views = mem_views;
}
void
sanitizer_data_type_config
(
char *data_type
)
{
if (data_type == NULL) {
sanitizer_data_type = REDSHOW_DATA_UNKNOWN;
} else if (strcmp(data_type, "float") == 0 || strcmp(data_type, "FLOAT") == 0) {
sanitizer_data_type = REDSHOW_DATA_FLOAT;
} else if (strcmp(data_type, "int") == 0 || strcmp(data_type, "INT") == 0) {
sanitizer_data_type = REDSHOW_DATA_INT;
} else {
sanitizer_data_type = REDSHOW_DATA_UNKNOWN;
}
PRINT("Sanitizer-> Config data type %u\n", sanitizer_data_type);
redshow_data_type_config(sanitizer_data_type);
}
size_t
sanitizer_gpu_patch_record_num_get()
{
return sanitizer_gpu_patch_record_num;
}
size_t
sanitizer_gpu_analysis_record_num_get()
{
return sanitizer_gpu_analysis_record_num;
}
int
sanitizer_buffer_pool_size_get()
{
return sanitizer_buffer_pool_size;
}
void
sanitizer_stop_flag_set()
{
sanitizer_stop_flag = true;
}
void
sanitizer_stop_flag_unset()
{
sanitizer_stop_flag = false;
}
void
sanitizer_gpu_analysis_config(int gpu_analysis_blocks)
{
sanitizer_gpu_analysis_blocks = gpu_analysis_blocks;
}
void
sanitizer_read_trace_ignore_config(int read_trace_ignore)
{
sanitizer_read_trace_ignore = read_trace_ignore == 1 ? true : false;
}
void
sanitizer_data_flow_hash_config(int data_flow_hash)
{
sanitizer_data_flow_hash = data_flow_hash == 1 ? true : false;
}
void
sanitizer_device_flush(void *args)
{
if (sanitizer_stop_flag) {
sanitizer_stop_flag_unset();
if (sanitizer_analysis_async) {
// Spin wait
sanitizer_buffer_channel_flush(sanitizer_gpu_patch_type);
if (sanitizer_gpu_analysis_blocks != 0) {
sanitizer_buffer_channel_flush(sanitizer_gpu_analysis_type);
}
sanitizer_process_signal();
while (sanitizer_buffer_channel_finish(sanitizer_gpu_patch_type) == false) {}
while (sanitizer_buffer_channel_finish(sanitizer_gpu_analysis_type) == false) {}
}
// Attribute performance metrics to CCTs
redshow_flush_thread(sanitizer_thread_id_local);
}
}
void
sanitizer_device_shutdown(void *args)
{
sanitizer_callbacks_unsubscribe();
if (sanitizer_analysis_async) {
atomic_store(&sanitizer_process_stop_flag, true);
// Spin wait
sanitizer_buffer_channel_flush(sanitizer_gpu_patch_type);
sanitizer_process_signal();
while (sanitizer_buffer_channel_finish(sanitizer_gpu_analysis_type) == false) {}
}
// Attribute performance metrics to CCTs
redshow_flush();
while (atomic_load(&sanitizer_process_thread_counter));
}
void
sanitizer_init
(
)
{
sanitizer_stop_flag = false;
sanitizer_thread_id_local = 0;
sanitizer_thread_context = NULL;
sanitizer_gpu_patch_buffer_device = NULL;
sanitizer_gpu_patch_buffer_addr_read_device = NULL;
sanitizer_gpu_patch_buffer_addr_write_device = NULL;
sanitizer_gpu_patch_buffer_host = NULL;
sanitizer_gpu_patch_buffer_addr_read_host = NULL;
sanitizer_gpu_patch_buffer_addr_write_host = NULL;
atomic_store(&sanitizer_process_awake_flag, false);
atomic_store(&sanitizer_process_stop_flag, false);
}
void
sanitizer_process_init
(
)
{
if (sanitizer_analysis_async) {
pthread_t *thread = &(sanitizer_thread.thread);
pthread_mutex_t *mutex = &(sanitizer_thread.mutex);
pthread_cond_t *cond = &(sanitizer_thread.cond);
// Create a new thread for the context without libmonitor watching
monitor_disable_new_threads();
atomic_fetch_add(&sanitizer_process_thread_counter, 1);
pthread_mutex_init(mutex, NULL);
pthread_cond_init(cond, NULL);
pthread_create(thread, NULL, sanitizer_process_thread, NULL);
monitor_enable_new_threads();
}
}
| 32.827522 | 162 | 0.740327 | [
"vector"
] |
88852403f9c24e84264b2ee274c34f52ab63aa66 | 3,713 | h | C | ros/src/fastrack/include/fastrack/state/state.h | kyrajeep/fastrack | b2958d90e7d9cbc2e7918cfa307f0c07d49f268a | [
"BSD-3-Clause"
] | 68 | 2018-04-17T19:37:26.000Z | 2022-03-09T03:33:16.000Z | ros/src/fastrack/include/fastrack/state/state.h | Wayne-xixi/fastrack | 7cb5a898144404b2cb0a301f8ea440852d32f3eb | [
"BSD-3-Clause"
] | 9 | 2018-04-17T19:50:05.000Z | 2020-08-14T19:05:49.000Z | ros/src/fastrack/include/fastrack/state/state.h | Wayne-xixi/fastrack | 7cb5a898144404b2cb0a301f8ea440852d32f3eb | [
"BSD-3-Clause"
] | 16 | 2018-04-18T18:33:59.000Z | 2022-03-09T03:33:18.000Z | /*
* Copyright (c) 2018, The Regents of the University of California (Regents).
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Please contact the author(s) of this library if you have any questions.
* Authors: David Fridovich-Keil ( dfk@eecs.berkeley.edu )
*/
///////////////////////////////////////////////////////////////////////////////
//
// Base class for all state types. All states must be able to output a position
// in 3D space and an arbitrary-dimensional configuration. This configuration
// will be used for geometric planning.
//
///////////////////////////////////////////////////////////////////////////////
#ifndef FASTRACK_STATE_STATE_H
#define FASTRACK_STATE_STATE_H
#include <fastrack/utils/types.h>
#include <fastrack_msgs/State.h>
namespace fastrack {
namespace state {
class State {
public:
virtual ~State() {}
// Accessors. All states must be able to output a position in 3D space
// and an arbitrary-dimensional configuration. This configuration will
// be used for geometric planning.
virtual double X() const = 0;
virtual double Y() const = 0;
virtual double Z() const = 0;
virtual Vector3d Position() const = 0;
virtual VectorXd Configuration() const = 0;
// What are the positions that the system occupies at the current state.
// NOTE! For simplicity, this is a finite set. In future, this could
// be generalized to a collection of generic obstacles.
virtual std::vector<Vector3d> OccupiedPositions() const = 0;
// Convert from/to VectorXd.
virtual void FromVector(const VectorXd& x) = 0;
virtual VectorXd ToVector() const = 0;
// Convert from/to ROS message.
void FromRosPtr(const fastrack_msgs::State::ConstPtr& msg) { FromRos(*msg); }
virtual void FromRos(const fastrack_msgs::State& msg) = 0;
virtual fastrack_msgs::State ToRos() const = 0;
// Re-seed the random engine.
static inline void Seed(unsigned int seed) { rng_.seed(seed); }
protected:
explicit State() {}
// Random number generator shared across all instances of states.
static std::random_device rd_;
static std::default_random_engine rng_;
}; //\class State
} //\namespace state
} //\namespace fastrack
#endif
| 38.677083 | 79 | 0.706437 | [
"vector",
"3d"
] |
888ba317fa444e10fb87d9cce902dae1ee4f2fcf | 13,223 | h | C | gpu-simulator/gpgpu-sim/src/gpuwattch/processor.h | tgrogers/accel-sim-framework | ea3d64183bc5d9ff41963ba89a051e0871f243ca | [
"BSD-2-Clause"
] | null | null | null | gpu-simulator/gpgpu-sim/src/gpuwattch/processor.h | tgrogers/accel-sim-framework | ea3d64183bc5d9ff41963ba89a051e0871f243ca | [
"BSD-2-Clause"
] | null | null | null | gpu-simulator/gpgpu-sim/src/gpuwattch/processor.h | tgrogers/accel-sim-framework | ea3d64183bc5d9ff41963ba89a051e0871f243ca | [
"BSD-2-Clause"
] | 4 | 2021-04-24T00:08:23.000Z | 2021-05-13T06:30:21.000Z | /*****************************************************************************
* McPAT
* SOFTWARE LICENSE AGREEMENT
* Copyright 2012 Hewlett-Packard Development Company, L.P.
* 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 holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.”
*
***************************************************************************/
/********************************************************************
* Modified by:
** Jingwen Leng, Univeristy of Texas, Austin * Syed Gilani,
*University of Wisconsin–Madison * Tayler Hetherington,
*University of British Columbia * Ahmed ElTantawy, University of
*British Columbia *
********************************************************************/
#ifndef PROCESSOR_H_
#define PROCESSOR_H_
#include <vector>
#include "../gpgpu-sim/visualizer.h"
#include "XML_Parse.h"
#include "array.h"
#include "basic_components.h"
#include "cacti/arbiter.h"
#include "cacti/area.h"
#include "cacti/decoder.h"
#include "cacti/parameter.h"
#include "cacti/router.h"
#include "core.h"
#include "iocontrollers.h"
#include "memoryctrl.h"
#include "noc.h"
#include "sharedcache.h"
class Processor : public Component {
public:
ParseXML *XML;
vector<Core *> cores;
vector<SharedCache *> l2array;
vector<SharedCache *> l3array;
vector<SharedCache *> l1dirarray;
vector<SharedCache *> l2dirarray;
vector<NoC *> nocs;
MemoryController *mc;
NIUController *niu;
PCIeController *pcie;
FlashController *flashcontroller;
InputParameter interface_ip;
double exClockRate;
ProcParam procdynp;
// for debugging nonlinear model
double dyn_power_before_scaling;
// wire globalInterconnect;
// clock_network globalClock;
Component core, l2, l3, l1dir, l2dir, noc, mcs, cc, nius, pcies,
flashcontrollers;
int numCore, numL2, numL3, numNOC, numL1Dir, numL2Dir;
Processor(ParseXML *XML_interface);
void compute();
void set_proc_param();
void visualizer_print(gzFile visualizer_file);
void displayEnergy(uint32_t indent = 0, int plevel = 100,
bool is_tdp_parm = true);
void displayDeviceType(int device_type_, uint32_t indent = 0);
void displayInterconnectType(int interconnect_type_, uint32_t indent = 0);
double l2_power;
double idle_core_power;
double get_const_dynamic_power() {
double constpart = 0;
constpart += (mc->frontend->power.readOp.dynamic * 0.1 *
mc->frontend->mcp.clockRate * mc->frontend->mcp.num_mcs *
mc->frontend->mcp.executionTime);
constpart +=
(mc->transecEngine->power.readOp.dynamic * 0.1 *
mc->transecEngine->mcp.clockRate * mc->transecEngine->mcp.num_mcs *
mc->transecEngine->mcp.executionTime);
constpart += (mc->PHY->power.readOp.dynamic * 0.1 * mc->PHY->mcp.clockRate *
mc->PHY->mcp.num_mcs * mc->PHY->mcp.executionTime);
constpart +=
(cores[0]->exu->exeu->base_energy / cores[0]->exu->exeu->clockRate) *
(cores[0]->exu->rf_fu_clockRate / cores[0]->exu->clockRate);
constpart +=
(cores[0]->exu->mul->base_energy / cores[0]->exu->mul->clockRate);
constpart +=
(cores[0]->exu->fp_u->base_energy / cores[0]->exu->fp_u->clockRate);
return constpart;
}
#define COALESCE_SCALE 1
double get_coefficient_readcoalescing() {
double value = 0;
double perAccessCoalescingEnergy =
COALESCE_SCALE *
((0.443e-3) * (0.5e-9) * g_tp.peri_global.Vdd * g_tp.peri_global.Vdd) /
(1 * 1);
value += mc->frontend->PRT->local_result.power.readOp.dynamic;
value += mc->frontend->threadMasks->local_result.power.readOp.dynamic;
value += mc->frontend->PRC->local_result.power.readOp.dynamic;
value += perAccessCoalescingEnergy;
return value;
}
double get_coefficient_writecoalescing() {
double value = 0;
double perAccessCoalescingEnergy =
COALESCE_SCALE *
((0.443e-3) * (0.5e-9) * g_tp.peri_global.Vdd * g_tp.peri_global.Vdd) /
(1 * 1);
value += (mc->frontend->PRT->local_result.power.writeOp.dynamic);
value += mc->frontend->threadMasks->local_result.power.writeOp.dynamic;
value += mc->frontend->PRC->local_result.power.writeOp.dynamic;
value += perAccessCoalescingEnergy;
return value;
}
double get_coefficient_noc_accesses() {
double read_coef = 0;
// the 32/4 is applied to the NoC access counters (32/4*L2 cache access)
read_coef += nocs[0]->router->buffer.power.readOp.dynamic;
read_coef += nocs[0]->router->buffer.power.writeOp.dynamic;
read_coef += nocs[0]->router->crossbar.power.readOp.dynamic;
read_coef += nocs[0]->router->arbiter.power.readOp.dynamic;
return read_coef;
}
double get_coefficient_l2_read_hits() {
double read_coef = 0;
if (XML->sys.number_of_L2s > 0)
read_coef =
l2array[0]->unicache.caches->local_result.power.readOp.dynamic;
return read_coef;
}
double get_coefficient_l2_read_misses() {
double read_coef = 0;
if (XML->sys.number_of_L2s > 0)
read_coef =
l2array[0]
->unicache.caches->local_result.tag_array2->power.readOp.dynamic;
return read_coef;
}
double get_coefficient_l2_write_hits() {
double read_coef = 0;
if (XML->sys.number_of_L2s > 0)
read_coef =
l2array[0]->unicache.caches->local_result.power.writeOp.dynamic;
return read_coef;
}
double get_coefficient_l2_write_misses() {
double read_coef = 0;
if (XML->sys.number_of_L2s > 0) {
read_coef = l2array[0]
->unicache.caches->local_result.tag_array2->power.writeOp
.dynamic; //*(32/4); // removed by Jingwen, the scaling
// of 32/4 is not used in the mcpat
read_coef +=
l2array[0]->unicache.caches->local_result.power.writeOp.dynamic;
read_coef +=
l2array[0]->unicache.missb->local_result.power.searchOp.dynamic;
read_coef +=
l2array[0]->unicache.missb->local_result.power.writeOp.dynamic;
read_coef +=
l2array[0]->unicache.ifb->local_result.power.searchOp.dynamic;
read_coef += l2array[0]->unicache.ifb->local_result.power.writeOp.dynamic;
read_coef +=
l2array[0]->unicache.prefetchb->local_result.power.searchOp.dynamic;
read_coef +=
l2array[0]->unicache.prefetchb->local_result.power.writeOp.dynamic;
read_coef +=
l2array[0]->unicache.wbb->local_result.power.searchOp.dynamic;
read_coef += l2array[0]->unicache.wbb->local_result.power.writeOp.dynamic;
}
return read_coef;
}
double get_coefficient_mem_reads() {
double value = 0;
value +=
(mc->frontend->mcp.llcBlockSize * 8.0 / mc->frontend->mcp.dataBusWidth *
mc->frontend->mcp.dataBusWidth / 72) *
(mc->frontend->frontendBuffer->local_result.power.searchOp.dynamic);
value +=
(mc->frontend->mcp.llcBlockSize * 8.0 / mc->frontend->mcp.dataBusWidth *
mc->frontend->mcp.dataBusWidth / 72) *
(mc->frontend->frontendBuffer->local_result.power.readOp.dynamic);
// TODO: Jingwen this should only compute for one time?
// value+=(mc->frontend->mcp.llcBlockSize*8.0/mc->frontend->mcp.dataBusWidth*mc->frontend->mcp.dataBusWidth/72)
//*(mc->frontend->frontendBuffer->local_result.power.readOp.dynamic);
value += (mc->frontend->mcp.llcBlockSize * 8.0 / mc->mcp.dataBusWidth) *
(mc->frontend->readBuffer->local_result.power.readOp.dynamic);
value += (mc->frontend->mcp.llcBlockSize * 8.0 / mc->mcp.dataBusWidth) *
(mc->frontend->readBuffer->local_result.power.writeOp.dynamic);
value += mc->dram->dramp.rd_coeff;
/*
value+=mc->frontend->PRT->local_result.power.readOp.dynamic;
value+=mc->frontend->threadMasks->local_result.power.readOp.dynamic;
value+=mc->frontend->PRC->local_result.power.readOp.dynamic;
value+=perAccessCoalescingEnergy;
*/
value += (mc->transecEngine->mcp.llcBlockSize * 8.0 /
mc->transecEngine->mcp.dataBusWidth *
mc->transecEngine->power_t.readOp.dynamic);
// if mcp.type ==1 TODO: add this check here
value += (mc->PHY->power_t.readOp.dynamic) * (mc->PHY->mcp.llcBlockSize) *
8 / 1e9 / mc->PHY->mcp.executionTime *
(mc->PHY->mcp.executionTime);
// printf("MC PHY read power coeff:
// %f\n",(mc->PHY->power_t.readOp.dynamic)*(mc->PHY->mcp.llcBlockSize)*8/1e9/mc->PHY->mcp.executionTime*(mc->PHY->mcp.executionTime));
// printf("MC trans read power coeff:
// %f\n",(mc->transecEngine->mcp.llcBlockSize*8.0/mc->transecEngine->mcp.dataBusWidth*mc->transecEngine->power_t.readOp.dynamic));
// TODO: Jingwen nocs stats should not be here
// value+= nocs[0]->router->buffer.power.readOp.dynamic*(32/4);
// value+= nocs[0]->router->buffer.power.writeOp.dynamic*(32/4);
// value+= nocs[0]->router->crossbar.power.readOp.dynamic*(32/4);
// value+= nocs[0]->router->arbiter.power.readOp.dynamic*(32/4);
// return 0.4*value;
return value;
}
double get_coefficient_mem_writes() {
double value = 0;
value +=
(mc->frontend->mcp.llcBlockSize * 8.0 / mc->frontend->mcp.dataBusWidth *
mc->frontend->mcp.dataBusWidth / 72) *
(mc->frontend->frontendBuffer->local_result.power.searchOp.dynamic);
value +=
(mc->frontend->mcp.llcBlockSize * 8.0 / mc->frontend->mcp.dataBusWidth *
mc->frontend->mcp.dataBusWidth / 72) *
(mc->frontend->frontendBuffer->local_result.power.writeOp.dynamic);
// value+=(mc->frontend->mcp.llcBlockSize*8.0/mc->frontend->mcp.dataBusWidth*mc->frontend->mcp.dataBusWidth/72)*
// (mc->frontend->frontendBuffer->local_result.power.writeOp.dynamic);
value += (mc->frontend->mcp.llcBlockSize * 8.0 /
mc->frontend->mcp.dataBusWidth) *
(mc->frontend->writeBuffer->local_result.power.readOp.dynamic);
value += (mc->frontend->mcp.llcBlockSize * 8.0 /
mc->frontend->mcp.dataBusWidth) *
(mc->frontend->writeBuffer->local_result.power.writeOp.dynamic);
value += mc->dram->dramp.wr_coeff;
/*
value+=(mc->frontend->PRT->local_result.power.writeOp.dynamic);
value+=mc->frontend->threadMasks->local_result.power.writeOp.dynamic;
value+=mc->frontend->PRC->local_result.power.writeOp.dynamic;
value+=perAccessCoalescingEnergy;
*/
value += (mc->transecEngine->mcp.llcBlockSize * 8.0 /
mc->transecEngine->mcp.dataBusWidth *
mc->transecEngine->power_t.readOp.dynamic);
// if mcp.type ==1 TODO: add this check here
value += (mc->PHY->power_t.readOp.dynamic) * (mc->PHY->mcp.llcBlockSize) *
8 / 1e9 / mc->PHY->mcp.executionTime *
(mc->PHY->mcp.executionTime);
// TODO: Jingwen nocs stats should not be here
// value+= nocs[0]->router->buffer.power.readOp.dynamic*(32/4);
//
// value+= nocs[0]->router->buffer.power.writeOp.dynamic*(32/4);
//
// value+= nocs[0]->router->crossbar.power.readOp.dynamic*(32/4);
//
// value+= nocs[0]->router->arbiter.power.readOp.dynamic*(32/4);
//
// return 0.4*value;
return value;
}
double get_coefficient_mem_pre() {
double value = 0;
value += mc->dram->dramp.pre_coeff;
// return 0.4*value;
return value;
}
// nonlinear scale
void nonlinear_scale(int, double, int);
void coefficient_scale();
void iterative_lse(double *, double *);
~Processor();
};
#endif /* PROCESSOR_H_ */
| 40.686154 | 138 | 0.646525 | [
"vector",
"model"
] |
8893870b2b60e3ec9164dbdaeed3dbf46536de6c | 1,056 | h | C | LivingCity/roadGraphB2018Loader.h | pavyedav/manta | 575d4395ad8a6000e8ca1de8c450fad2a541f19b | [
"BSD-3-Clause"
] | null | null | null | LivingCity/roadGraphB2018Loader.h | pavyedav/manta | 575d4395ad8a6000e8ca1de8c450fad2a541f19b | [
"BSD-3-Clause"
] | null | null | null | LivingCity/roadGraphB2018Loader.h | pavyedav/manta | 575d4395ad8a6000e8ca1de8c450fad2a541f19b | [
"BSD-3-Clause"
] | null | null | null |
/************************************************************************************************
* @desc Class to load the B2018 road graph
* @author igarciad
************************************************************************************************/
#pragma once
#include "RoadGraph/roadGraph.h"
#include <QString>
#include "traffic/b18TrafficSP.h"
#include "traffic/sp/graph.h"
namespace LC {
class DemandB2018 {
public:
int num_people;
int src_vertex;
int tgt_vertex;
DemandB2018(int num_people, int src_vertex, int tgt_vertex):
num_people(num_people), src_vertex(src_vertex), tgt_vertex(tgt_vertex) {}
};
/**
* RoadGraph.
**/
class RoadGraphB2018 {
public:
/**
* Load
**/
static void loadB2018RoadGraph(RoadGraph &inRoadGraph, QString networkPath);
static std::string loadABMGraph(const std::string& networkPath, const std::shared_ptr<abm::Graph>& graph_, int start_time, int end_time);
static std::vector<DemandB2018> demandB2018;
static int totalNumPeople;
static QHash<int, uint64_t> indToOsmid;
};
}
| 24.55814 | 139 | 0.597538 | [
"vector"
] |
8893c85940d0cc913afa203ce5057ec8dc9c7d1d | 582 | h | C | Foundation/Source/fdpch.h | TrashCoder94/Foundation | 431e4b2b6d01fea570942dc40c93a3a08d23890f | [
"Apache-2.0"
] | null | null | null | Foundation/Source/fdpch.h | TrashCoder94/Foundation | 431e4b2b6d01fea570942dc40c93a3a08d23890f | [
"Apache-2.0"
] | null | null | null | Foundation/Source/fdpch.h | TrashCoder94/Foundation | 431e4b2b6d01fea570942dc40c93a3a08d23890f | [
"Apache-2.0"
] | null | null | null | #pragma once
#include "Foundation/Core/PlatformDetection.h"
// Common
#include <algorithm>
#include <chrono>
#include <filesystem>
#include <functional>
#include <iostream>
#include <memory>
#include <utility>
// Data Structures
#include <fstream>
#include <ostream>
#include <string>
#include <sstream>
#include <array>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include "Foundation/Core/Base.h"
#include "Foundation/Core/Log.h"
#include "Foundation/Debug/Instrumentor.h"
// Platform Specific
#ifdef FD_PLATFORM_WINDOWS
#include <Windows.h>
#endif
| 18.1875 | 46 | 0.756014 | [
"vector"
] |
8894040c27849746a43b55cda125a751b8c6ea2a | 27,827 | c | C | src/libs/zbxmemory/memalloc.c | canghai908/zabbix | a921334695d91430805cc4309b47de9de58df6d2 | [
"BSD-2-Clause"
] | null | null | null | src/libs/zbxmemory/memalloc.c | canghai908/zabbix | a921334695d91430805cc4309b47de9de58df6d2 | [
"BSD-2-Clause"
] | null | null | null | src/libs/zbxmemory/memalloc.c | canghai908/zabbix | a921334695d91430805cc4309b47de9de58df6d2 | [
"BSD-2-Clause"
] | null | null | null | /*
** Zabbix
** Copyright (C) 2001-2015 Zabbix SIA
**
** 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 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.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
**/
#include "common.h"
#include "mutexs.h"
#include "ipc.h"
#include "log.h"
#include "memalloc.h"
/******************************************************************************
* *
* Some information on memory layout *
* --------------------------------------- *
* *
* *
* (*) chunk: a contiguous piece of memory that is either free or used *
* *
* *
* +-------- size of + --------------+ *
* | (8 bytes) | | *
* | v | *
* | | *
* | +- allocatable memory --+ | *
* | | (user data goes here) | | *
* v v v v *
* *
* |--------|----------------...----|--------| *
* *
* ^ ^ ^ ^ *
* 8-aligned | | 8-aligned *
* *
* 8-aligned 8-aligned *
* *
* *
* when a chunk is used, `size' fields have MEM_FLG_USED bit set *
* *
* when a chunk is free, the first 2 * ZBX_PTR_SIZE bytes of allocatable *
* memory contain pointers to the previous and next chunks, in that order *
* *
* notes: *
* *
* - user data is nicely 8-aligned *
* *
* - size is kept on both left and right ends for quick merging *
* (when freeing a chunk, we can quickly see if the previous *
* and next chunks are free, those will not have MEM_FLG_USED) *
* *
* *
* (*) free chunks are stored in doubly-linked lists according to their sizes *
* *
* a typical situation is thus as follows (1 used chunk, 2 free chunks) *
* *
* *
* +--------------------------- shared memory ----------------------------+ *
* | (can be misaligned) | *
* | | *
* | | *
* | +------ chunk A ------+------ chunk B -----+------ chunk C ------+ | *
* | | (free) | (used) | (free) | | *
* | | | | | | *
* v v v v v v *
* prevnext user data prevnext *
* #--|----|--------...|----|----|---....---|----|----|--------...|----|--# *
* NULL | | NULL *
* ^ | ^ | ^ *
* | | | | | *
* | +------------------------------+ | | *
* | | | *
* +-------------------------------------------------+ | *
* | | *
* *
* lo_bound `size' fields in chunk B hi_bound *
* (aligned) have MEM_FLG_USED bit set (aligned) *
* *
******************************************************************************/
#define LOCK_INFO if (info->use_lock) zbx_mutex_lock(&info->mem_lock)
#define UNLOCK_INFO if (info->use_lock) zbx_mutex_unlock(&info->mem_lock)
static void *ALIGN4(void *ptr);
static void *ALIGN8(void *ptr);
static void *ALIGNPTR(void *ptr);
static zbx_uint64_t mem_proper_alloc_size(zbx_uint64_t size);
static int mem_bucket_by_size(zbx_uint64_t size);
static void mem_set_chunk_size(void *chunk, zbx_uint64_t size);
static void mem_set_used_chunk_size(void *chunk, zbx_uint64_t size);
static void *mem_get_prev_chunk(void *chunk);
static void mem_set_prev_chunk(void *chunk, void *prev);
static void *mem_get_next_chunk(void *chunk);
static void mem_set_next_chunk(void *chunk, void *next);
static void **mem_ptr_to_prev_field(void *chunk);
static void **mem_ptr_to_next_field(void *chunk, void **first_chunk);
static void mem_link_chunk(zbx_mem_info_t *info, void *chunk);
static void mem_unlink_chunk(zbx_mem_info_t *info, void *chunk);
static void *__mem_malloc(zbx_mem_info_t *info, zbx_uint64_t size);
static void *__mem_realloc(zbx_mem_info_t *info, void *old, zbx_uint64_t size);
static void __mem_free(zbx_mem_info_t *info, void *ptr);
#define MEM_SIZE_FIELD sizeof(zbx_uint64_t)
#define MEM_FLG_USED ((__UINT64_C(1))<<63)
#define FREE_CHUNK(ptr) (((*(zbx_uint64_t *)(ptr)) & MEM_FLG_USED) == 0)
#define CHUNK_SIZE(ptr) ((*(zbx_uint64_t *)(ptr)) & ~MEM_FLG_USED)
#define MEM_MIN_SIZE __UINT64_C(128)
#define MEM_MAX_SIZE __UINT64_C(0x1000000000) /* 64 GB */
#define MEM_MIN_ALLOC 24 /* should be a multiple of 8 and at least (2 * ZBX_PTR_SIZE) */
#define MEM_MIN_BUCKET_SIZE MEM_MIN_ALLOC
#define MEM_MAX_BUCKET_SIZE 256 /* starting from this size all free chunks are put into the same bucket */
#define MEM_BUCKET_COUNT ((MEM_MAX_BUCKET_SIZE - MEM_MIN_BUCKET_SIZE) / 8 + 1)
/* helper functions */
static void *ALIGN4(void *ptr)
{
return (void *)((uintptr_t)((char *)ptr + 3) & (uintptr_t)~3);
}
static void *ALIGN8(void *ptr)
{
return (void *)((uintptr_t)((char *)ptr + 7) & (uintptr_t)~7);
}
static void *ALIGNPTR(void *ptr)
{
if (4 == ZBX_PTR_SIZE)
return ALIGN4(ptr);
if (8 == ZBX_PTR_SIZE)
return ALIGN8(ptr);
assert(0);
}
static zbx_uint64_t mem_proper_alloc_size(zbx_uint64_t size)
{
if (size >= MEM_MIN_ALLOC)
return size + ((8 - (size & 7)) & 7); /* allocate in multiples of 8... */
else
return MEM_MIN_ALLOC; /* ...and at least MEM_MIN_ALLOC */
}
static int mem_bucket_by_size(zbx_uint64_t size)
{
if (size < MEM_MIN_BUCKET_SIZE)
return 0;
if (size < MEM_MAX_BUCKET_SIZE)
return (size - MEM_MIN_BUCKET_SIZE) >> 3;
return MEM_BUCKET_COUNT - 1;
}
static void mem_set_chunk_size(void *chunk, zbx_uint64_t size)
{
*(zbx_uint64_t *)chunk = size;
*(zbx_uint64_t *)((char *)chunk + MEM_SIZE_FIELD + size) = size;
}
static void mem_set_used_chunk_size(void *chunk, zbx_uint64_t size)
{
*(zbx_uint64_t *)chunk = MEM_FLG_USED | size;
*(zbx_uint64_t *)((char *)chunk + MEM_SIZE_FIELD + size) = MEM_FLG_USED | size;
}
static void *mem_get_prev_chunk(void *chunk)
{
return *(void **)((char *)chunk + MEM_SIZE_FIELD);
}
static void mem_set_prev_chunk(void *chunk, void *prev)
{
*(void **)((char *)chunk + MEM_SIZE_FIELD) = prev;
}
static void *mem_get_next_chunk(void *chunk)
{
return *(void **)((char *)chunk + MEM_SIZE_FIELD + ZBX_PTR_SIZE);
}
static void mem_set_next_chunk(void *chunk, void *next)
{
*(void **)((char *)chunk + MEM_SIZE_FIELD + ZBX_PTR_SIZE) = next;
}
static void **mem_ptr_to_prev_field(void *chunk)
{
return (NULL != chunk ? (void **)((char *)chunk + MEM_SIZE_FIELD) : NULL);
}
static void **mem_ptr_to_next_field(void *chunk, void **first_chunk)
{
return (NULL != chunk ? (void **)((char *)chunk + MEM_SIZE_FIELD + ZBX_PTR_SIZE) : first_chunk);
}
static void mem_link_chunk(zbx_mem_info_t *info, void *chunk)
{
int index;
index = mem_bucket_by_size(CHUNK_SIZE(chunk));
if (NULL != info->buckets[index])
mem_set_prev_chunk(info->buckets[index], chunk);
mem_set_prev_chunk(chunk, NULL);
mem_set_next_chunk(chunk, info->buckets[index]);
info->buckets[index] = chunk;
}
static void mem_unlink_chunk(zbx_mem_info_t *info, void *chunk)
{
int index;
void *prev_chunk, *next_chunk;
void **next_in_prev_chunk, **prev_in_next_chunk;
index = mem_bucket_by_size(CHUNK_SIZE(chunk));
prev_chunk = mem_get_prev_chunk(chunk);
next_chunk = mem_get_next_chunk(chunk);
next_in_prev_chunk = mem_ptr_to_next_field(prev_chunk, &info->buckets[index]);
prev_in_next_chunk = mem_ptr_to_prev_field(next_chunk);
*next_in_prev_chunk = next_chunk;
if (NULL != prev_in_next_chunk)
*prev_in_next_chunk = prev_chunk;
}
/* private memory functions */
static void *__mem_malloc(zbx_mem_info_t *info, zbx_uint64_t size)
{
int index;
void *chunk;
zbx_uint64_t chunk_size;
size = mem_proper_alloc_size(size);
/* try to find an appropriate chunk in special buckets */
index = mem_bucket_by_size(size);
while (index < MEM_BUCKET_COUNT - 1 && NULL == info->buckets[index])
index++;
chunk = info->buckets[index];
if (index == MEM_BUCKET_COUNT - 1)
{
/* otherwise, find a chunk big enough according to first-fit strategy */
int counter = 0;
zbx_uint64_t skip_min = __UINT64_C(0xffffffffffffffff), skip_max = __UINT64_C(0);
while (NULL != chunk && CHUNK_SIZE(chunk) < size)
{
counter++;
skip_min = MIN(skip_min, CHUNK_SIZE(chunk));
skip_max = MAX(skip_max, CHUNK_SIZE(chunk));
chunk = mem_get_next_chunk(chunk);
}
/* don't log errors if malloc can return null in low memory situations */
if (0 == info->allow_oom)
{
if (NULL == chunk)
{
zabbix_log(LOG_LEVEL_CRIT, "__mem_malloc: skipped %d asked %u skip_min %u skip_max %u",
counter, size, skip_min, skip_max);
}
else if (counter >= 100)
{
zabbix_log(LOG_LEVEL_DEBUG, "__mem_malloc: skipped %d asked %u skip_min %u skip_max %u"
" size %u", counter, size, skip_min, skip_max, CHUNK_SIZE(chunk));
}
}
}
if (NULL == chunk)
return NULL;
chunk_size = CHUNK_SIZE(chunk);
mem_unlink_chunk(info, chunk);
/* either use the full chunk or split it */
if (chunk_size < size + 2 * MEM_SIZE_FIELD + MEM_MIN_ALLOC)
{
info->used_size += chunk_size;
info->free_size -= chunk_size;
mem_set_used_chunk_size(chunk, chunk_size);
}
else
{
void *new_chunk;
zbx_uint64_t new_chunk_size;
new_chunk = (void *)((char *)chunk + MEM_SIZE_FIELD + size + MEM_SIZE_FIELD);
new_chunk_size = chunk_size - size - 2 * MEM_SIZE_FIELD;
mem_set_chunk_size(new_chunk, new_chunk_size);
mem_link_chunk(info, new_chunk);
info->used_size += size;
info->free_size -= chunk_size;
info->free_size += new_chunk_size;
mem_set_used_chunk_size(chunk, size);
}
return chunk;
}
static void *__mem_realloc(zbx_mem_info_t *info, void *old, zbx_uint64_t size)
{
void *chunk, *new_chunk, *next_chunk;
zbx_uint64_t chunk_size, new_chunk_size;
int next_free;
size = mem_proper_alloc_size(size);
chunk = (void *)((char *)old - MEM_SIZE_FIELD);
chunk_size = CHUNK_SIZE(chunk);
next_chunk = (void *)((char *)chunk + MEM_SIZE_FIELD + chunk_size + MEM_SIZE_FIELD);
next_free = (next_chunk < info->hi_bound && FREE_CHUNK(next_chunk));
if (size <= chunk_size)
{
/* do not reallocate if not much is freed */
/* we are likely to want more memory again */
if (size > chunk_size / 4)
return chunk;
if (next_free)
{
/* merge with next chunk */
info->used_size -= chunk_size - size;
info->free_size += chunk_size - size;
new_chunk = (void *)((char *)chunk + MEM_SIZE_FIELD + size + MEM_SIZE_FIELD);
new_chunk_size = CHUNK_SIZE(next_chunk) + (chunk_size - size);
mem_unlink_chunk(info, next_chunk);
mem_set_chunk_size(new_chunk, new_chunk_size);
mem_link_chunk(info, new_chunk);
mem_set_used_chunk_size(chunk, size);
}
else
{
/* split the current one */
info->used_size -= chunk_size - size;
info->free_size += chunk_size - size - 2 * MEM_SIZE_FIELD;
new_chunk = (void *)((char *)chunk + MEM_SIZE_FIELD + size + MEM_SIZE_FIELD);
new_chunk_size = chunk_size - size - 2 * MEM_SIZE_FIELD;
mem_set_chunk_size(new_chunk, new_chunk_size);
mem_link_chunk(info, new_chunk);
mem_set_used_chunk_size(chunk, size);
}
return chunk;
}
if (next_free && chunk_size + 2 * MEM_SIZE_FIELD + CHUNK_SIZE(next_chunk) >= size)
{
info->used_size -= chunk_size;
info->free_size += chunk_size + 2 * MEM_SIZE_FIELD;
chunk_size += 2 * MEM_SIZE_FIELD + CHUNK_SIZE(next_chunk);
mem_unlink_chunk(info, next_chunk);
/* either use the full next_chunk or split it */
if (chunk_size < size + 2 * MEM_SIZE_FIELD + MEM_MIN_ALLOC)
{
info->used_size += chunk_size;
info->free_size -= chunk_size;
mem_set_used_chunk_size(chunk, chunk_size);
}
else
{
new_chunk = (void *)((char *)chunk + MEM_SIZE_FIELD + size + MEM_SIZE_FIELD);
new_chunk_size = chunk_size - size - 2 * MEM_SIZE_FIELD;
mem_set_chunk_size(new_chunk, new_chunk_size);
mem_link_chunk(info, new_chunk);
info->used_size += size;
info->free_size -= chunk_size;
info->free_size += new_chunk_size;
mem_set_used_chunk_size(chunk, size);
}
return chunk;
}
else if (NULL != (new_chunk = __mem_malloc(info, size)))
{
memcpy((char *)new_chunk + MEM_SIZE_FIELD, (char *)chunk + MEM_SIZE_FIELD, chunk_size);
__mem_free(info, old);
return new_chunk;
}
else
{
void *tmp = NULL;
/* check if there would be enough space if the current chunk */
/* would be freed before allocating a new one */
new_chunk_size = chunk_size;
if (0 != next_free)
new_chunk_size += CHUNK_SIZE(next_chunk) + 2 * MEM_SIZE_FIELD;
if (info->lo_bound < chunk && FREE_CHUNK((char *)chunk - MEM_SIZE_FIELD))
new_chunk_size += CHUNK_SIZE((char *)chunk - MEM_SIZE_FIELD) + 2 * MEM_SIZE_FIELD;
if (size > new_chunk_size)
return NULL;
tmp = zbx_malloc(tmp, chunk_size);
memcpy(tmp, (char *)chunk + MEM_SIZE_FIELD, chunk_size);
__mem_free(info, old);
if (NULL == (new_chunk = __mem_malloc(info, size)))
{
THIS_SHOULD_NEVER_HAPPEN;
exit(EXIT_FAILURE);
}
memcpy((char *)new_chunk + MEM_SIZE_FIELD, tmp, chunk_size);
zbx_free(tmp);
return new_chunk;
}
}
static void __mem_free(zbx_mem_info_t *info, void *ptr)
{
void *chunk;
void *prev_chunk, *next_chunk;
zbx_uint64_t chunk_size;
int prev_free, next_free;
chunk = (void *)((char *)ptr - MEM_SIZE_FIELD);
chunk_size = CHUNK_SIZE(chunk);
info->used_size -= chunk_size;
info->free_size += chunk_size;
/* see if we can merge with previous and next chunks */
next_chunk = (void *)((char *)chunk + MEM_SIZE_FIELD + chunk_size + MEM_SIZE_FIELD);
prev_free = (info->lo_bound < chunk && FREE_CHUNK((char *)chunk - MEM_SIZE_FIELD));
next_free = (next_chunk < info->hi_bound && FREE_CHUNK(next_chunk));
if (prev_free && next_free)
{
info->free_size += 4 * MEM_SIZE_FIELD;
prev_chunk = (char *)chunk - MEM_SIZE_FIELD - CHUNK_SIZE((char *)chunk - MEM_SIZE_FIELD) -
MEM_SIZE_FIELD;
chunk_size += 4 * MEM_SIZE_FIELD + CHUNK_SIZE(prev_chunk) + CHUNK_SIZE(next_chunk);
mem_unlink_chunk(info, prev_chunk);
mem_unlink_chunk(info, next_chunk);
chunk = prev_chunk;
mem_set_chunk_size(chunk, chunk_size);
mem_link_chunk(info, chunk);
}
else if (prev_free)
{
info->free_size += 2 * MEM_SIZE_FIELD;
prev_chunk = (void *)((char *)chunk - MEM_SIZE_FIELD - CHUNK_SIZE((char *)chunk - MEM_SIZE_FIELD) -
MEM_SIZE_FIELD);
chunk_size += 2 * MEM_SIZE_FIELD + CHUNK_SIZE(prev_chunk);
mem_unlink_chunk(info, prev_chunk);
chunk = prev_chunk;
mem_set_chunk_size(chunk, chunk_size);
mem_link_chunk(info, chunk);
}
else if (next_free)
{
info->free_size += 2 * MEM_SIZE_FIELD;
chunk_size += 2 * MEM_SIZE_FIELD + CHUNK_SIZE(next_chunk);
mem_unlink_chunk(info, next_chunk);
mem_set_chunk_size(chunk, chunk_size);
mem_link_chunk(info, chunk);
}
else
{
mem_set_chunk_size(chunk, chunk_size);
mem_link_chunk(info, chunk);
}
}
/* public memory interface */
void zbx_mem_create(zbx_mem_info_t **info, key_t shm_key, int lock_name, zbx_uint64_t size,
const char *descr, const char *param, int allow_oom)
{
const char *__function_name = "zbx_mem_create";
int shm_id, index;
void *base;
descr = ZBX_NULL2STR(descr);
param = ZBX_NULL2STR(param);
zabbix_log(LOG_LEVEL_DEBUG, "In %s() descr:'%s' param:'%s' size:" ZBX_FS_SIZE_T,
__function_name, descr, param, (zbx_fs_size_t)size);
/* allocate shared memory */
if (4 != ZBX_PTR_SIZE && 8 != ZBX_PTR_SIZE)
{
zabbix_log(LOG_LEVEL_CRIT, "failed assumption about pointer size (" ZBX_FS_SIZE_T " not in {4, 8})",
(zbx_fs_size_t)ZBX_PTR_SIZE);
exit(EXIT_FAILURE);
}
if (!(MEM_MIN_SIZE <= size && size <= MEM_MAX_SIZE))
{
zabbix_log(LOG_LEVEL_CRIT, "requested size " ZBX_FS_SIZE_T " not within bounds [" ZBX_FS_UI64
" <= size <= " ZBX_FS_UI64 "]", (zbx_fs_size_t)size, MEM_MIN_SIZE, MEM_MAX_SIZE);
exit(EXIT_FAILURE);
}
if (-1 == (shm_id = zbx_shmget(shm_key, size)))
{
zabbix_log(LOG_LEVEL_CRIT, "cannot allocate shared memory for %s", descr);
exit(EXIT_FAILURE);
}
if ((void *)(-1) == (base = shmat(shm_id, NULL, 0)))
{
zabbix_log(LOG_LEVEL_CRIT, "cannot attach shared memory for %s: %s", descr, zbx_strerror(errno));
exit(EXIT_FAILURE);
}
/* allocate zbx_mem_info_t structure, its buckets, and description inside shared memory */
*info = ALIGN8(base);
(*info)->shm_id = shm_id;
(*info)->orig_size = size;
size -= (char *)(*info + 1) - (char *)base;
base = (void *)(*info + 1);
(*info)->buckets = ALIGNPTR(base);
memset((*info)->buckets, 0, MEM_BUCKET_COUNT * ZBX_PTR_SIZE);
size -= (char *)((*info)->buckets + MEM_BUCKET_COUNT) - (char *)base;
base = (void *)((*info)->buckets + MEM_BUCKET_COUNT);
zbx_strlcpy(base, descr, size);
(*info)->mem_descr = base;
size -= strlen(descr) + 1;
base = (void *)((char *)base + strlen(descr) + 1);
zbx_strlcpy(base, param, size);
(*info)->mem_param = base;
size -= strlen(param) + 1;
base = (void *)((char *)base + strlen(param) + 1);
(*info)->allow_oom = allow_oom;
/* allocate mutex */
if (ZBX_NO_MUTEX != lock_name)
{
(*info)->use_lock = 1;
if (ZBX_MUTEX_ERROR == zbx_mutex_create_force(&((*info)->mem_lock), lock_name))
{
zabbix_log(LOG_LEVEL_CRIT, "cannot create mutex for %s", descr);
exit(EXIT_FAILURE);
}
}
else
(*info)->use_lock = 0;
/* prepare shared memory for further allocation by creating one big chunk */
(*info)->lo_bound = ALIGN8(base);
(*info)->hi_bound = ALIGN8((char *)base + size - 8);
(*info)->total_size = (zbx_uint64_t)((char *)((*info)->hi_bound) - (char *)((*info)->lo_bound) -
2 * MEM_SIZE_FIELD);
index = mem_bucket_by_size((*info)->total_size);
(*info)->buckets[index] = (*info)->lo_bound;
mem_set_chunk_size((*info)->buckets[index], (*info)->total_size);
mem_set_prev_chunk((*info)->buckets[index], NULL);
mem_set_next_chunk((*info)->buckets[index], NULL);
(*info)->used_size = 0;
(*info)->free_size = (*info)->total_size;
zabbix_log(LOG_LEVEL_DEBUG, "valid user addresses: [%p, %p] total size: " ZBX_FS_SIZE_T,
(char *)(*info)->lo_bound + MEM_SIZE_FIELD,
(char *)(*info)->hi_bound - MEM_SIZE_FIELD,
(zbx_fs_size_t)(*info)->total_size);
zabbix_log(LOG_LEVEL_DEBUG, "End of %s()", __function_name);
}
void zbx_mem_destroy(zbx_mem_info_t *info)
{
const char *__function_name = "zbx_mem_destroy";
zabbix_log(LOG_LEVEL_DEBUG, "In %s() descr:'%s'", __function_name, info->mem_descr);
if (info->use_lock)
zbx_mutex_destroy(&info->mem_lock);
if (-1 == shmctl(info->shm_id, IPC_RMID, 0))
{
zabbix_log(LOG_LEVEL_WARNING, "cannot remove shared memory for %s: %s",
info->mem_descr, zbx_strerror(errno));
}
zabbix_log(LOG_LEVEL_DEBUG, "End of %s()", __function_name);
}
void *__zbx_mem_malloc(const char *file, int line, zbx_mem_info_t *info, const void *old, size_t size)
{
const char *__function_name = "zbx_mem_malloc";
void *chunk;
if (NULL != old)
{
zabbix_log(LOG_LEVEL_CRIT, "[file:%s,line:%d] %s(): allocating already allocated memory",
file, line, __function_name);
exit(EXIT_FAILURE);
}
if (0 == size || size > MEM_MAX_SIZE)
{
zabbix_log(LOG_LEVEL_CRIT, "[file:%s,line:%d] %s(): asking for a bad number of bytes (" ZBX_FS_SIZE_T
")", file, line, __function_name, (zbx_fs_size_t)size);
exit(EXIT_FAILURE);
}
LOCK_INFO;
chunk = __mem_malloc(info, size);
UNLOCK_INFO;
if (NULL == chunk)
{
if (1 == info->allow_oom)
return NULL;
zabbix_log(LOG_LEVEL_CRIT, "[file:%s,line:%d] %s(): out of memory (requested " ZBX_FS_SIZE_T " bytes)",
file, line, __function_name, (zbx_fs_size_t)size);
zabbix_log(LOG_LEVEL_CRIT, "[file:%s,line:%d] %s(): please increase %s configuration parameter",
file, line, __function_name, info->mem_param);
exit(EXIT_FAILURE);
}
return (void *)((char *)chunk + MEM_SIZE_FIELD);
}
void *__zbx_mem_realloc(const char *file, int line, zbx_mem_info_t *info, void *old, size_t size)
{
const char *__function_name = "zbx_mem_realloc";
void *chunk;
if (0 == size || size > MEM_MAX_SIZE)
{
zabbix_log(LOG_LEVEL_CRIT, "[file:%s,line:%d] %s(): asking for a bad number of bytes (" ZBX_FS_SIZE_T
")", file, line, __function_name, (zbx_fs_size_t)size);
exit(EXIT_FAILURE);
}
LOCK_INFO;
if (NULL == old)
chunk = __mem_malloc(info, size);
else
chunk = __mem_realloc(info, old, size);
UNLOCK_INFO;
if (NULL == chunk)
{
if (1 == info->allow_oom)
return NULL;
zabbix_log(LOG_LEVEL_CRIT, "[file:%s,line:%d] %s(): out of memory (requested " ZBX_FS_SIZE_T " bytes)",
file, line, __function_name, (zbx_fs_size_t)size);
zabbix_log(LOG_LEVEL_CRIT, "[file:%s,line:%d] %s(): please increase %s configuration parameter",
file, line, __function_name, info->mem_param);
exit(EXIT_FAILURE);
}
return (void *)((char *)chunk + MEM_SIZE_FIELD);
}
void __zbx_mem_free(const char *file, int line, zbx_mem_info_t *info, void *ptr)
{
const char *__function_name = "zbx_mem_free";
if (NULL == ptr)
{
zabbix_log(LOG_LEVEL_CRIT, "[file:%s,line:%d] %s(): freeing a NULL pointer",
file, line, __function_name);
exit(EXIT_FAILURE);
}
LOCK_INFO;
__mem_free(info, ptr);
UNLOCK_INFO;
}
void zbx_mem_clear(zbx_mem_info_t *info)
{
const char *__function_name = "zbx_mem_clear";
int index;
zabbix_log(LOG_LEVEL_DEBUG, "In %s()", __function_name);
LOCK_INFO;
memset(info->buckets, 0, MEM_BUCKET_COUNT * ZBX_PTR_SIZE);
index = mem_bucket_by_size(info->total_size);
info->buckets[index] = info->lo_bound;
mem_set_chunk_size(info->buckets[index], info->total_size);
mem_set_prev_chunk(info->buckets[index], NULL);
mem_set_next_chunk(info->buckets[index], NULL);
info->used_size = 0;
info->free_size = info->total_size;
UNLOCK_INFO;
zabbix_log(LOG_LEVEL_DEBUG, "End of %s()", __function_name);
}
void zbx_mem_dump_stats(zbx_mem_info_t *info)
{
void *chunk;
int index;
zbx_uint64_t counter, total, total_free = 0;
zbx_uint64_t min_size = __UINT64_C(0xffffffffffffffff), max_size = __UINT64_C(0);
LOCK_INFO;
zabbix_log(LOG_LEVEL_DEBUG, "=== memory statistics for %s ===", info->mem_descr);
for (index = 0; index < MEM_BUCKET_COUNT; index++)
{
counter = 0;
chunk = info->buckets[index];
while (NULL != chunk)
{
counter++;
min_size = MIN(min_size, CHUNK_SIZE(chunk));
max_size = MAX(max_size, CHUNK_SIZE(chunk));
chunk = mem_get_next_chunk(chunk);
}
if (counter > 0)
{
total_free += counter;
zabbix_log(LOG_LEVEL_DEBUG, "free chunks of size %2s %3d bytes: %8d",
index == MEM_BUCKET_COUNT - 1 ? ">=" : "",
MEM_MIN_BUCKET_SIZE + 8 * index, counter);
}
}
zabbix_log(LOG_LEVEL_DEBUG, "min chunk size: %10u bytes", min_size);
zabbix_log(LOG_LEVEL_DEBUG, "max chunk size: %10u bytes", max_size);
total = (info->total_size - info->used_size - info->free_size) / (2 * MEM_SIZE_FIELD) + 1;
zabbix_log(LOG_LEVEL_DEBUG, "memory of total size %u bytes fragmented into %d chunks", info->total_size, total);
zabbix_log(LOG_LEVEL_DEBUG, "of those, %10u bytes are in %8d free chunks", info->free_size, total_free);
zabbix_log(LOG_LEVEL_DEBUG, "of those, %10u bytes are in %8d used chunks", info->used_size, total - total_free);
zabbix_log(LOG_LEVEL_DEBUG, "================================");
UNLOCK_INFO;
}
size_t zbx_mem_required_size(int chunks_num, const char *descr, const char *param)
{
const char *__function_name = "zbx_mem_required_size";
size_t size = 0;
zabbix_log(LOG_LEVEL_DEBUG, "In %s() size:" ZBX_FS_SIZE_T " chunks_num:%d descr:'%s' param:'%s'",
__function_name, (zbx_fs_size_t)size, chunks_num, descr, param);
/* shared memory of what size should we allocate so that there is a guarantee */
/* that we will be able to get ourselves 'chunks_num' pieces of memory with a */
/* total size of 'size', given that we also have to store 'descr' and 'param'? */
size += 7; /* ensure we allocate enough to 8-align zbx_mem_info_t */
size += sizeof(zbx_mem_info_t);
size += ZBX_PTR_SIZE - 1; /* ensure we allocate enough to align bucket pointers */
size += ZBX_PTR_SIZE * MEM_BUCKET_COUNT;
size += strlen(descr) + 1;
size += strlen(param) + 1;
size += (MEM_SIZE_FIELD - 1) + 8; /* ensure we allocate enough to align the first chunk */
size += (MEM_SIZE_FIELD - 1) + 8; /* ensure we allocate enough to align right size field */
size += (chunks_num - 1) * MEM_SIZE_FIELD * 2; /* each additional chunk requires 16 bytes of overhead */
size += chunks_num * (MEM_MIN_ALLOC - 1); /* each chunk has size of at least MEM_MIN_ALLOC bytes */
zabbix_log(LOG_LEVEL_DEBUG, "End of %s() size:" ZBX_FS_SIZE_T, __function_name, (zbx_fs_size_t)size);
return size;
}
| 32.244496 | 113 | 0.594602 | [
"3d"
] |
889ecaa0a443fd7ddcfd494fca0f4eabfcf79fef | 3,522 | h | C | src/cwb/cqp/variables.h | cran/RcppCWB | aa4440b068dcc16fc378af23d3d63c2683a2e366 | [
"BSD-3-Clause"
] | null | null | null | src/cwb/cqp/variables.h | cran/RcppCWB | aa4440b068dcc16fc378af23d3d63c2683a2e366 | [
"BSD-3-Clause"
] | 58 | 2018-03-11T11:14:26.000Z | 2022-03-28T21:19:21.000Z | src/cwb/cqp/variables.h | cran/RcppCWB | aa4440b068dcc16fc378af23d3d63c2683a2e366 | [
"BSD-3-Clause"
] | 4 | 2018-07-11T23:15:55.000Z | 2021-02-02T16:33:32.000Z | /*
* IMS Open Corpus Workbench (CWB)
* Copyright (C) 1993-2006 by IMS, University of Stuttgart
* Copyright (C) 2007- by the respective contributers (see file AUTHORS)
*
* 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 2, 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 (in the file "COPYING", or available via
* WWW at http://www.gnu.org/copyleft/gpl.html).
*/
#ifndef _VARIABLES_H_
#define _VARIABLES_H_
/* ---------------------------------------------------------------------- */
#include "../cl/corpus.h"
#include "../cl/attributes.h"
/* ---------------------------------------------------------------------- */
/** VariableItem object: an item within a variable */
typedef struct _variable_item {
int free; /**< Boolean flag: is this item empty? */
char *sval; /**< The actual string value of the item. */
int ival; /**< Lexicon number associated with the item.
Set to -1 on creation, but when the variable is verified
against a corpus attribute, it is set to the lexicon number
from that attribute. */
} VariableItem;
/**
* The Variable object: a list of strings that can be used as a variable within
* a query (to match all tokens whose type is identical to one of the strings
* on the list).
*
* (Plus also VariableBuffer: the former is a pointer to the latter.)
*/
typedef struct _variable_buf {
int valid; /**< flag: whether I'm valid or not (valid = associated with a corpus/attribute,
and known to match at least one entry in that attribute's lexicon) */
char *my_name; /**< my name */
char *my_corpus; /**< name of corpus I'm valid for */
char *my_attribute; /**< name of attribute I'm valid for */
int nr_valid_items; /**< only valid after validation */
int nr_invalid_items;
int nr_items; /**< number of items (size of the "items" array) */
VariableItem *items; /**< array of items - the set of strings within the variable. */
} VariableBuffer, *Variable;
extern int nr_variables;
extern Variable *VariableSpace;
/* ---------------------------------------------------------------------- */
/* Variable methods */
Variable FindVariable(char *varname);
int VariableItemMember(Variable v, char *item);
int VariableAddItem(Variable v, char *item);
int VariableSubtractItem(Variable v, const char *item);
int VariableDeleteItems(Variable v);
int DropVariable(Variable *vp);
Variable NewVariable(char *varname);
int
SetVariableValue(char *varName,
char operator,
char *varValues);
/* variable iterator functions */
void variables_iterator_new(void);
Variable variables_iterator_next(void);
int
VerifyVariable(Variable v, Corpus *corpus, Attribute *attribute);
int *
GetVariableItems(Variable v,
Corpus *corpus,
Attribute *attribute,
/* returned: */
int *nr_items);
char **GetVariableStrings(Variable v, int *nr_items);
#endif
| 33.226415 | 106 | 0.61272 | [
"object"
] |
88a1041c5b797a7ad3c4da451c18fb8e5c641f06 | 1,482 | h | C | src/Examples/navier-stokes/navierStokesSetter_impl.h | grinisrit/tnl-dev | 4403b2dca895e2c32636395d6f1c1210c7afcefd | [
"MIT"
] | null | null | null | src/Examples/navier-stokes/navierStokesSetter_impl.h | grinisrit/tnl-dev | 4403b2dca895e2c32636395d6f1c1210c7afcefd | [
"MIT"
] | null | null | null | src/Examples/navier-stokes/navierStokesSetter_impl.h | grinisrit/tnl-dev | 4403b2dca895e2c32636395d6f1c1210c7afcefd | [
"MIT"
] | null | null | null | #ifndef NAVIERSTOKESSETTER_IMPL_H_
#define NAVIERSTOKESSETTER_IMPL_H_
#include <TNL/Meshes/Grid.h>
#include <TNL/Meshes/tnlLinearGridGeometry.h>
#include <TNL/Operators/euler/fvm/LaxFridrichs.h>
#include <TNL/Operators/gradient/tnlCentralFDMGradient.h>
template< typename MeshType, typename SolverStarter >
template< typename RealType,
typename DeviceType,
typename IndexType >
bool navierStokesSetter< MeshType, SolverStarter > :: run( const Config::ParameterContainer& parameters )
{
std::cerr << "The solver is not implemented for the mesh " << getType< MeshType >() << "." << std::endl;
return false;
}
template< typename MeshReal, typename Device, typename MeshIndex, typename SolverStarter >
template< typename RealType,
typename DeviceType,
typename IndexType >
bool navierStokesSetter< Meshes::Grid< 2, MeshReal, Device, MeshIndex >, SolverStarter >::run( const Config::ParameterContainer& parameters )
{
SolverStarter solverStarter;
const String& schemeName = parameters. getParameter< String >( "scheme" );
if( schemeName == "lax-fridrichs" )
return solverStarter. run< navierStokesSolver< MeshType,
LaxFridrichs< MeshType,
tnlCentralFDMGradient< MeshType > > > >
( parameters );
};
#endif /* NAVIERSTOKESSETTER_IMPL_H_ */
| 42.342857 | 141 | 0.651147 | [
"mesh"
] |
88a12cc3db19aa8f43bf8a9128d5f770a8da4f7c | 45,626 | h | C | aws-cpp-sdk-datapipeline/include/aws/datapipeline/DataPipelineClient.h | Nexuscompute/aws-sdk-cpp | e7ef485e46e6962c9e084b8c9b104c1bfcceaf26 | [
"Apache-2.0"
] | 1 | 2022-01-05T18:20:03.000Z | 2022-01-05T18:20:03.000Z | aws-cpp-sdk-datapipeline/include/aws/datapipeline/DataPipelineClient.h | Nexuscompute/aws-sdk-cpp | e7ef485e46e6962c9e084b8c9b104c1bfcceaf26 | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-datapipeline/include/aws/datapipeline/DataPipelineClient.h | Nexuscompute/aws-sdk-cpp | e7ef485e46e6962c9e084b8c9b104c1bfcceaf26 | [
"Apache-2.0"
] | 1 | 2021-11-09T12:02:58.000Z | 2021-11-09T12:02:58.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/datapipeline/DataPipeline_EXPORTS.h>
#include <aws/datapipeline/DataPipelineErrors.h>
#include <aws/core/client/AWSError.h>
#include <aws/core/client/ClientConfiguration.h>
#include <aws/core/client/AWSClient.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/datapipeline/model/ActivatePipelineResult.h>
#include <aws/datapipeline/model/AddTagsResult.h>
#include <aws/datapipeline/model/CreatePipelineResult.h>
#include <aws/datapipeline/model/DeactivatePipelineResult.h>
#include <aws/datapipeline/model/DescribeObjectsResult.h>
#include <aws/datapipeline/model/DescribePipelinesResult.h>
#include <aws/datapipeline/model/EvaluateExpressionResult.h>
#include <aws/datapipeline/model/GetPipelineDefinitionResult.h>
#include <aws/datapipeline/model/ListPipelinesResult.h>
#include <aws/datapipeline/model/PollForTaskResult.h>
#include <aws/datapipeline/model/PutPipelineDefinitionResult.h>
#include <aws/datapipeline/model/QueryObjectsResult.h>
#include <aws/datapipeline/model/RemoveTagsResult.h>
#include <aws/datapipeline/model/ReportTaskProgressResult.h>
#include <aws/datapipeline/model/ReportTaskRunnerHeartbeatResult.h>
#include <aws/datapipeline/model/SetTaskStatusResult.h>
#include <aws/datapipeline/model/ValidatePipelineDefinitionResult.h>
#include <aws/core/NoResult.h>
#include <aws/core/client/AsyncCallerContext.h>
#include <aws/core/http/HttpTypes.h>
#include <future>
#include <functional>
namespace Aws
{
namespace Http
{
class HttpClient;
class HttpClientFactory;
} // namespace Http
namespace Utils
{
template< typename R, typename E> class Outcome;
namespace Threading
{
class Executor;
} // namespace Threading
} // namespace Utils
namespace Auth
{
class AWSCredentials;
class AWSCredentialsProvider;
} // namespace Auth
namespace Client
{
class RetryStrategy;
} // namespace Client
namespace DataPipeline
{
namespace Model
{
class ActivatePipelineRequest;
class AddTagsRequest;
class CreatePipelineRequest;
class DeactivatePipelineRequest;
class DeletePipelineRequest;
class DescribeObjectsRequest;
class DescribePipelinesRequest;
class EvaluateExpressionRequest;
class GetPipelineDefinitionRequest;
class ListPipelinesRequest;
class PollForTaskRequest;
class PutPipelineDefinitionRequest;
class QueryObjectsRequest;
class RemoveTagsRequest;
class ReportTaskProgressRequest;
class ReportTaskRunnerHeartbeatRequest;
class SetStatusRequest;
class SetTaskStatusRequest;
class ValidatePipelineDefinitionRequest;
typedef Aws::Utils::Outcome<ActivatePipelineResult, DataPipelineError> ActivatePipelineOutcome;
typedef Aws::Utils::Outcome<AddTagsResult, DataPipelineError> AddTagsOutcome;
typedef Aws::Utils::Outcome<CreatePipelineResult, DataPipelineError> CreatePipelineOutcome;
typedef Aws::Utils::Outcome<DeactivatePipelineResult, DataPipelineError> DeactivatePipelineOutcome;
typedef Aws::Utils::Outcome<Aws::NoResult, DataPipelineError> DeletePipelineOutcome;
typedef Aws::Utils::Outcome<DescribeObjectsResult, DataPipelineError> DescribeObjectsOutcome;
typedef Aws::Utils::Outcome<DescribePipelinesResult, DataPipelineError> DescribePipelinesOutcome;
typedef Aws::Utils::Outcome<EvaluateExpressionResult, DataPipelineError> EvaluateExpressionOutcome;
typedef Aws::Utils::Outcome<GetPipelineDefinitionResult, DataPipelineError> GetPipelineDefinitionOutcome;
typedef Aws::Utils::Outcome<ListPipelinesResult, DataPipelineError> ListPipelinesOutcome;
typedef Aws::Utils::Outcome<PollForTaskResult, DataPipelineError> PollForTaskOutcome;
typedef Aws::Utils::Outcome<PutPipelineDefinitionResult, DataPipelineError> PutPipelineDefinitionOutcome;
typedef Aws::Utils::Outcome<QueryObjectsResult, DataPipelineError> QueryObjectsOutcome;
typedef Aws::Utils::Outcome<RemoveTagsResult, DataPipelineError> RemoveTagsOutcome;
typedef Aws::Utils::Outcome<ReportTaskProgressResult, DataPipelineError> ReportTaskProgressOutcome;
typedef Aws::Utils::Outcome<ReportTaskRunnerHeartbeatResult, DataPipelineError> ReportTaskRunnerHeartbeatOutcome;
typedef Aws::Utils::Outcome<Aws::NoResult, DataPipelineError> SetStatusOutcome;
typedef Aws::Utils::Outcome<SetTaskStatusResult, DataPipelineError> SetTaskStatusOutcome;
typedef Aws::Utils::Outcome<ValidatePipelineDefinitionResult, DataPipelineError> ValidatePipelineDefinitionOutcome;
typedef std::future<ActivatePipelineOutcome> ActivatePipelineOutcomeCallable;
typedef std::future<AddTagsOutcome> AddTagsOutcomeCallable;
typedef std::future<CreatePipelineOutcome> CreatePipelineOutcomeCallable;
typedef std::future<DeactivatePipelineOutcome> DeactivatePipelineOutcomeCallable;
typedef std::future<DeletePipelineOutcome> DeletePipelineOutcomeCallable;
typedef std::future<DescribeObjectsOutcome> DescribeObjectsOutcomeCallable;
typedef std::future<DescribePipelinesOutcome> DescribePipelinesOutcomeCallable;
typedef std::future<EvaluateExpressionOutcome> EvaluateExpressionOutcomeCallable;
typedef std::future<GetPipelineDefinitionOutcome> GetPipelineDefinitionOutcomeCallable;
typedef std::future<ListPipelinesOutcome> ListPipelinesOutcomeCallable;
typedef std::future<PollForTaskOutcome> PollForTaskOutcomeCallable;
typedef std::future<PutPipelineDefinitionOutcome> PutPipelineDefinitionOutcomeCallable;
typedef std::future<QueryObjectsOutcome> QueryObjectsOutcomeCallable;
typedef std::future<RemoveTagsOutcome> RemoveTagsOutcomeCallable;
typedef std::future<ReportTaskProgressOutcome> ReportTaskProgressOutcomeCallable;
typedef std::future<ReportTaskRunnerHeartbeatOutcome> ReportTaskRunnerHeartbeatOutcomeCallable;
typedef std::future<SetStatusOutcome> SetStatusOutcomeCallable;
typedef std::future<SetTaskStatusOutcome> SetTaskStatusOutcomeCallable;
typedef std::future<ValidatePipelineDefinitionOutcome> ValidatePipelineDefinitionOutcomeCallable;
} // namespace Model
class DataPipelineClient;
typedef std::function<void(const DataPipelineClient*, const Model::ActivatePipelineRequest&, const Model::ActivatePipelineOutcome&, const std::shared_ptr<const Aws::Client::AsyncCallerContext>&) > ActivatePipelineResponseReceivedHandler;
typedef std::function<void(const DataPipelineClient*, const Model::AddTagsRequest&, const Model::AddTagsOutcome&, const std::shared_ptr<const Aws::Client::AsyncCallerContext>&) > AddTagsResponseReceivedHandler;
typedef std::function<void(const DataPipelineClient*, const Model::CreatePipelineRequest&, const Model::CreatePipelineOutcome&, const std::shared_ptr<const Aws::Client::AsyncCallerContext>&) > CreatePipelineResponseReceivedHandler;
typedef std::function<void(const DataPipelineClient*, const Model::DeactivatePipelineRequest&, const Model::DeactivatePipelineOutcome&, const std::shared_ptr<const Aws::Client::AsyncCallerContext>&) > DeactivatePipelineResponseReceivedHandler;
typedef std::function<void(const DataPipelineClient*, const Model::DeletePipelineRequest&, const Model::DeletePipelineOutcome&, const std::shared_ptr<const Aws::Client::AsyncCallerContext>&) > DeletePipelineResponseReceivedHandler;
typedef std::function<void(const DataPipelineClient*, const Model::DescribeObjectsRequest&, const Model::DescribeObjectsOutcome&, const std::shared_ptr<const Aws::Client::AsyncCallerContext>&) > DescribeObjectsResponseReceivedHandler;
typedef std::function<void(const DataPipelineClient*, const Model::DescribePipelinesRequest&, const Model::DescribePipelinesOutcome&, const std::shared_ptr<const Aws::Client::AsyncCallerContext>&) > DescribePipelinesResponseReceivedHandler;
typedef std::function<void(const DataPipelineClient*, const Model::EvaluateExpressionRequest&, const Model::EvaluateExpressionOutcome&, const std::shared_ptr<const Aws::Client::AsyncCallerContext>&) > EvaluateExpressionResponseReceivedHandler;
typedef std::function<void(const DataPipelineClient*, const Model::GetPipelineDefinitionRequest&, const Model::GetPipelineDefinitionOutcome&, const std::shared_ptr<const Aws::Client::AsyncCallerContext>&) > GetPipelineDefinitionResponseReceivedHandler;
typedef std::function<void(const DataPipelineClient*, const Model::ListPipelinesRequest&, const Model::ListPipelinesOutcome&, const std::shared_ptr<const Aws::Client::AsyncCallerContext>&) > ListPipelinesResponseReceivedHandler;
typedef std::function<void(const DataPipelineClient*, const Model::PollForTaskRequest&, const Model::PollForTaskOutcome&, const std::shared_ptr<const Aws::Client::AsyncCallerContext>&) > PollForTaskResponseReceivedHandler;
typedef std::function<void(const DataPipelineClient*, const Model::PutPipelineDefinitionRequest&, const Model::PutPipelineDefinitionOutcome&, const std::shared_ptr<const Aws::Client::AsyncCallerContext>&) > PutPipelineDefinitionResponseReceivedHandler;
typedef std::function<void(const DataPipelineClient*, const Model::QueryObjectsRequest&, const Model::QueryObjectsOutcome&, const std::shared_ptr<const Aws::Client::AsyncCallerContext>&) > QueryObjectsResponseReceivedHandler;
typedef std::function<void(const DataPipelineClient*, const Model::RemoveTagsRequest&, const Model::RemoveTagsOutcome&, const std::shared_ptr<const Aws::Client::AsyncCallerContext>&) > RemoveTagsResponseReceivedHandler;
typedef std::function<void(const DataPipelineClient*, const Model::ReportTaskProgressRequest&, const Model::ReportTaskProgressOutcome&, const std::shared_ptr<const Aws::Client::AsyncCallerContext>&) > ReportTaskProgressResponseReceivedHandler;
typedef std::function<void(const DataPipelineClient*, const Model::ReportTaskRunnerHeartbeatRequest&, const Model::ReportTaskRunnerHeartbeatOutcome&, const std::shared_ptr<const Aws::Client::AsyncCallerContext>&) > ReportTaskRunnerHeartbeatResponseReceivedHandler;
typedef std::function<void(const DataPipelineClient*, const Model::SetStatusRequest&, const Model::SetStatusOutcome&, const std::shared_ptr<const Aws::Client::AsyncCallerContext>&) > SetStatusResponseReceivedHandler;
typedef std::function<void(const DataPipelineClient*, const Model::SetTaskStatusRequest&, const Model::SetTaskStatusOutcome&, const std::shared_ptr<const Aws::Client::AsyncCallerContext>&) > SetTaskStatusResponseReceivedHandler;
typedef std::function<void(const DataPipelineClient*, const Model::ValidatePipelineDefinitionRequest&, const Model::ValidatePipelineDefinitionOutcome&, const std::shared_ptr<const Aws::Client::AsyncCallerContext>&) > ValidatePipelineDefinitionResponseReceivedHandler;
/**
* <p>AWS Data Pipeline configures and manages a data-driven workflow called a
* pipeline. AWS Data Pipeline handles the details of scheduling and ensuring that
* data dependencies are met so that your application can focus on processing the
* data.</p> <p>AWS Data Pipeline provides a JAR implementation of a task runner
* called AWS Data Pipeline Task Runner. AWS Data Pipeline Task Runner provides
* logic for common data management scenarios, such as performing database queries
* and running data analysis using Amazon Elastic MapReduce (Amazon EMR). You can
* use AWS Data Pipeline Task Runner as your task runner, or you can write your own
* task runner to provide custom data management.</p> <p>AWS Data Pipeline
* implements two main sets of functionality. Use the first set to create a
* pipeline and define data sources, schedules, dependencies, and the transforms to
* be performed on the data. Use the second set in your task runner application to
* receive the next task ready for processing. The logic for performing the task,
* such as querying the data, running data analysis, or converting the data from
* one format to another, is contained within the task runner. The task runner
* performs the task assigned to it by the web service, reporting progress to the
* web service as it does so. When the task is done, the task runner reports the
* final success or failure of the task to the web service.</p>
*/
class AWS_DATAPIPELINE_API DataPipelineClient : public Aws::Client::AWSJsonClient
{
public:
typedef Aws::Client::AWSJsonClient BASECLASS;
/**
* Initializes client to use DefaultCredentialProviderChain, with default http client factory, and optional client config. If client config
* is not specified, it will be initialized to default values.
*/
DataPipelineClient(const Aws::Client::ClientConfiguration& clientConfiguration = Aws::Client::ClientConfiguration());
/**
* Initializes client to use SimpleAWSCredentialsProvider, with default http client factory, and optional client config. If client config
* is not specified, it will be initialized to default values.
*/
DataPipelineClient(const Aws::Auth::AWSCredentials& credentials, const Aws::Client::ClientConfiguration& clientConfiguration = Aws::Client::ClientConfiguration());
/**
* Initializes client to use specified credentials provider with specified client config. If http client factory is not supplied,
* the default http client factory will be used
*/
DataPipelineClient(const std::shared_ptr<Aws::Auth::AWSCredentialsProvider>& credentialsProvider,
const Aws::Client::ClientConfiguration& clientConfiguration = Aws::Client::ClientConfiguration());
virtual ~DataPipelineClient();
/**
* <p>Validates the specified pipeline and starts processing pipeline tasks. If the
* pipeline does not pass validation, activation fails.</p> <p>If you need to pause
* the pipeline to investigate an issue with a component, such as a data source or
* script, call <a>DeactivatePipeline</a>.</p> <p>To activate a finished pipeline,
* modify the end date for the pipeline and then activate it.</p><p><h3>See
* Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/ActivatePipeline">AWS
* API Reference</a></p>
*/
virtual Model::ActivatePipelineOutcome ActivatePipeline(const Model::ActivatePipelineRequest& request) const;
/**
* A Callable wrapper for ActivatePipeline that returns a future to the operation so that it can be executed in parallel to other requests.
*/
virtual Model::ActivatePipelineOutcomeCallable ActivatePipelineCallable(const Model::ActivatePipelineRequest& request) const;
/**
* An Async wrapper for ActivatePipeline that queues the request into a thread executor and triggers associated callback when operation has finished.
*/
virtual void ActivatePipelineAsync(const Model::ActivatePipelineRequest& request, const ActivatePipelineResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const;
/**
* <p>Adds or modifies tags for the specified pipeline.</p><p><h3>See Also:</h3>
* <a
* href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/AddTags">AWS
* API Reference</a></p>
*/
virtual Model::AddTagsOutcome AddTags(const Model::AddTagsRequest& request) const;
/**
* A Callable wrapper for AddTags that returns a future to the operation so that it can be executed in parallel to other requests.
*/
virtual Model::AddTagsOutcomeCallable AddTagsCallable(const Model::AddTagsRequest& request) const;
/**
* An Async wrapper for AddTags that queues the request into a thread executor and triggers associated callback when operation has finished.
*/
virtual void AddTagsAsync(const Model::AddTagsRequest& request, const AddTagsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const;
/**
* <p>Creates a new, empty pipeline. Use <a>PutPipelineDefinition</a> to populate
* the pipeline.</p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/CreatePipeline">AWS
* API Reference</a></p>
*/
virtual Model::CreatePipelineOutcome CreatePipeline(const Model::CreatePipelineRequest& request) const;
/**
* A Callable wrapper for CreatePipeline that returns a future to the operation so that it can be executed in parallel to other requests.
*/
virtual Model::CreatePipelineOutcomeCallable CreatePipelineCallable(const Model::CreatePipelineRequest& request) const;
/**
* An Async wrapper for CreatePipeline that queues the request into a thread executor and triggers associated callback when operation has finished.
*/
virtual void CreatePipelineAsync(const Model::CreatePipelineRequest& request, const CreatePipelineResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const;
/**
* <p>Deactivates the specified running pipeline. The pipeline is set to the
* <code>DEACTIVATING</code> state until the deactivation process completes.</p>
* <p>To resume a deactivated pipeline, use <a>ActivatePipeline</a>. By default,
* the pipeline resumes from the last completed execution. Optionally, you can
* specify the date and time to resume the pipeline.</p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/DeactivatePipeline">AWS
* API Reference</a></p>
*/
virtual Model::DeactivatePipelineOutcome DeactivatePipeline(const Model::DeactivatePipelineRequest& request) const;
/**
* A Callable wrapper for DeactivatePipeline that returns a future to the operation so that it can be executed in parallel to other requests.
*/
virtual Model::DeactivatePipelineOutcomeCallable DeactivatePipelineCallable(const Model::DeactivatePipelineRequest& request) const;
/**
* An Async wrapper for DeactivatePipeline that queues the request into a thread executor and triggers associated callback when operation has finished.
*/
virtual void DeactivatePipelineAsync(const Model::DeactivatePipelineRequest& request, const DeactivatePipelineResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const;
/**
* <p>Deletes a pipeline, its pipeline definition, and its run history. AWS Data
* Pipeline attempts to cancel instances associated with the pipeline that are
* currently being processed by task runners.</p> <p>Deleting a pipeline cannot be
* undone. You cannot query or restore a deleted pipeline. To temporarily pause a
* pipeline instead of deleting it, call <a>SetStatus</a> with the status set to
* <code>PAUSE</code> on individual components. Components that are paused by
* <a>SetStatus</a> can be resumed.</p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/DeletePipeline">AWS
* API Reference</a></p>
*/
virtual Model::DeletePipelineOutcome DeletePipeline(const Model::DeletePipelineRequest& request) const;
/**
* A Callable wrapper for DeletePipeline that returns a future to the operation so that it can be executed in parallel to other requests.
*/
virtual Model::DeletePipelineOutcomeCallable DeletePipelineCallable(const Model::DeletePipelineRequest& request) const;
/**
* An Async wrapper for DeletePipeline that queues the request into a thread executor and triggers associated callback when operation has finished.
*/
virtual void DeletePipelineAsync(const Model::DeletePipelineRequest& request, const DeletePipelineResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const;
/**
* <p>Gets the object definitions for a set of objects associated with the
* pipeline. Object definitions are composed of a set of fields that define the
* properties of the object.</p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/DescribeObjects">AWS
* API Reference</a></p>
*/
virtual Model::DescribeObjectsOutcome DescribeObjects(const Model::DescribeObjectsRequest& request) const;
/**
* A Callable wrapper for DescribeObjects that returns a future to the operation so that it can be executed in parallel to other requests.
*/
virtual Model::DescribeObjectsOutcomeCallable DescribeObjectsCallable(const Model::DescribeObjectsRequest& request) const;
/**
* An Async wrapper for DescribeObjects that queues the request into a thread executor and triggers associated callback when operation has finished.
*/
virtual void DescribeObjectsAsync(const Model::DescribeObjectsRequest& request, const DescribeObjectsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const;
/**
* <p>Retrieves metadata about one or more pipelines. The information retrieved
* includes the name of the pipeline, the pipeline identifier, its current state,
* and the user account that owns the pipeline. Using account credentials, you can
* retrieve metadata about pipelines that you or your IAM users have created. If
* you are using an IAM user account, you can retrieve metadata about only those
* pipelines for which you have read permissions.</p> <p>To retrieve the full
* pipeline definition instead of metadata about the pipeline, call
* <a>GetPipelineDefinition</a>.</p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/DescribePipelines">AWS
* API Reference</a></p>
*/
virtual Model::DescribePipelinesOutcome DescribePipelines(const Model::DescribePipelinesRequest& request) const;
/**
* A Callable wrapper for DescribePipelines that returns a future to the operation so that it can be executed in parallel to other requests.
*/
virtual Model::DescribePipelinesOutcomeCallable DescribePipelinesCallable(const Model::DescribePipelinesRequest& request) const;
/**
* An Async wrapper for DescribePipelines that queues the request into a thread executor and triggers associated callback when operation has finished.
*/
virtual void DescribePipelinesAsync(const Model::DescribePipelinesRequest& request, const DescribePipelinesResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const;
/**
* <p>Task runners call <code>EvaluateExpression</code> to evaluate a string in the
* context of the specified object. For example, a task runner can evaluate SQL
* queries stored in Amazon S3.</p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/EvaluateExpression">AWS
* API Reference</a></p>
*/
virtual Model::EvaluateExpressionOutcome EvaluateExpression(const Model::EvaluateExpressionRequest& request) const;
/**
* A Callable wrapper for EvaluateExpression that returns a future to the operation so that it can be executed in parallel to other requests.
*/
virtual Model::EvaluateExpressionOutcomeCallable EvaluateExpressionCallable(const Model::EvaluateExpressionRequest& request) const;
/**
* An Async wrapper for EvaluateExpression that queues the request into a thread executor and triggers associated callback when operation has finished.
*/
virtual void EvaluateExpressionAsync(const Model::EvaluateExpressionRequest& request, const EvaluateExpressionResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const;
/**
* <p>Gets the definition of the specified pipeline. You can call
* <code>GetPipelineDefinition</code> to retrieve the pipeline definition that you
* provided using <a>PutPipelineDefinition</a>.</p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/GetPipelineDefinition">AWS
* API Reference</a></p>
*/
virtual Model::GetPipelineDefinitionOutcome GetPipelineDefinition(const Model::GetPipelineDefinitionRequest& request) const;
/**
* A Callable wrapper for GetPipelineDefinition that returns a future to the operation so that it can be executed in parallel to other requests.
*/
virtual Model::GetPipelineDefinitionOutcomeCallable GetPipelineDefinitionCallable(const Model::GetPipelineDefinitionRequest& request) const;
/**
* An Async wrapper for GetPipelineDefinition that queues the request into a thread executor and triggers associated callback when operation has finished.
*/
virtual void GetPipelineDefinitionAsync(const Model::GetPipelineDefinitionRequest& request, const GetPipelineDefinitionResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const;
/**
* <p>Lists the pipeline identifiers for all active pipelines that you have
* permission to access.</p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/ListPipelines">AWS
* API Reference</a></p>
*/
virtual Model::ListPipelinesOutcome ListPipelines(const Model::ListPipelinesRequest& request) const;
/**
* A Callable wrapper for ListPipelines that returns a future to the operation so that it can be executed in parallel to other requests.
*/
virtual Model::ListPipelinesOutcomeCallable ListPipelinesCallable(const Model::ListPipelinesRequest& request) const;
/**
* An Async wrapper for ListPipelines that queues the request into a thread executor and triggers associated callback when operation has finished.
*/
virtual void ListPipelinesAsync(const Model::ListPipelinesRequest& request, const ListPipelinesResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const;
/**
* <p>Task runners call <code>PollForTask</code> to receive a task to perform from
* AWS Data Pipeline. The task runner specifies which tasks it can perform by
* setting a value for the <code>workerGroup</code> parameter. The task returned
* can come from any of the pipelines that match the <code>workerGroup</code> value
* passed in by the task runner and that was launched using the IAM user
* credentials specified by the task runner.</p> <p>If tasks are ready in the work
* queue, <code>PollForTask</code> returns a response immediately. If no tasks are
* available in the queue, <code>PollForTask</code> uses long-polling and holds on
* to a poll connection for up to a 90 seconds, during which time the first newly
* scheduled task is handed to the task runner. To accomodate this, set the socket
* timeout in your task runner to 90 seconds. The task runner should not call
* <code>PollForTask</code> again on the same <code>workerGroup</code> until it
* receives a response, and this can take up to 90 seconds. </p><p><h3>See
* Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/PollForTask">AWS
* API Reference</a></p>
*/
virtual Model::PollForTaskOutcome PollForTask(const Model::PollForTaskRequest& request) const;
/**
* A Callable wrapper for PollForTask that returns a future to the operation so that it can be executed in parallel to other requests.
*/
virtual Model::PollForTaskOutcomeCallable PollForTaskCallable(const Model::PollForTaskRequest& request) const;
/**
* An Async wrapper for PollForTask that queues the request into a thread executor and triggers associated callback when operation has finished.
*/
virtual void PollForTaskAsync(const Model::PollForTaskRequest& request, const PollForTaskResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const;
/**
* <p>Adds tasks, schedules, and preconditions to the specified pipeline. You can
* use <code>PutPipelineDefinition</code> to populate a new pipeline.</p> <p>
* <code>PutPipelineDefinition</code> also validates the configuration as it adds
* it to the pipeline. Changes to the pipeline are saved unless one of the
* following three validation errors exists in the pipeline. </p> <ol> <li>An
* object is missing a name or identifier field.</li> <li>A string or reference
* field is empty.</li> <li>The number of objects in the pipeline exceeds the
* maximum allowed objects.</li> <li>The pipeline is in a FINISHED state.</li>
* </ol> <p> Pipeline object definitions are passed to the
* <code>PutPipelineDefinition</code> action and returned by the
* <a>GetPipelineDefinition</a> action. </p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/PutPipelineDefinition">AWS
* API Reference</a></p>
*/
virtual Model::PutPipelineDefinitionOutcome PutPipelineDefinition(const Model::PutPipelineDefinitionRequest& request) const;
/**
* A Callable wrapper for PutPipelineDefinition that returns a future to the operation so that it can be executed in parallel to other requests.
*/
virtual Model::PutPipelineDefinitionOutcomeCallable PutPipelineDefinitionCallable(const Model::PutPipelineDefinitionRequest& request) const;
/**
* An Async wrapper for PutPipelineDefinition that queues the request into a thread executor and triggers associated callback when operation has finished.
*/
virtual void PutPipelineDefinitionAsync(const Model::PutPipelineDefinitionRequest& request, const PutPipelineDefinitionResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const;
/**
* <p>Queries the specified pipeline for the names of objects that match the
* specified set of conditions.</p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/QueryObjects">AWS
* API Reference</a></p>
*/
virtual Model::QueryObjectsOutcome QueryObjects(const Model::QueryObjectsRequest& request) const;
/**
* A Callable wrapper for QueryObjects that returns a future to the operation so that it can be executed in parallel to other requests.
*/
virtual Model::QueryObjectsOutcomeCallable QueryObjectsCallable(const Model::QueryObjectsRequest& request) const;
/**
* An Async wrapper for QueryObjects that queues the request into a thread executor and triggers associated callback when operation has finished.
*/
virtual void QueryObjectsAsync(const Model::QueryObjectsRequest& request, const QueryObjectsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const;
/**
* <p>Removes existing tags from the specified pipeline.</p><p><h3>See Also:</h3>
* <a
* href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/RemoveTags">AWS
* API Reference</a></p>
*/
virtual Model::RemoveTagsOutcome RemoveTags(const Model::RemoveTagsRequest& request) const;
/**
* A Callable wrapper for RemoveTags that returns a future to the operation so that it can be executed in parallel to other requests.
*/
virtual Model::RemoveTagsOutcomeCallable RemoveTagsCallable(const Model::RemoveTagsRequest& request) const;
/**
* An Async wrapper for RemoveTags that queues the request into a thread executor and triggers associated callback when operation has finished.
*/
virtual void RemoveTagsAsync(const Model::RemoveTagsRequest& request, const RemoveTagsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const;
/**
* <p>Task runners call <code>ReportTaskProgress</code> when assigned a task to
* acknowledge that it has the task. If the web service does not receive this
* acknowledgement within 2 minutes, it assigns the task in a subsequent
* <a>PollForTask</a> call. After this initial acknowledgement, the task runner
* only needs to report progress every 15 minutes to maintain its ownership of the
* task. You can change this reporting time from 15 minutes by specifying a
* <code>reportProgressTimeout</code> field in your pipeline.</p> <p>If a task
* runner does not report its status after 5 minutes, AWS Data Pipeline assumes
* that the task runner is unable to process the task and reassigns the task in a
* subsequent response to <a>PollForTask</a>. Task runners should call
* <code>ReportTaskProgress</code> every 60 seconds.</p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/ReportTaskProgress">AWS
* API Reference</a></p>
*/
virtual Model::ReportTaskProgressOutcome ReportTaskProgress(const Model::ReportTaskProgressRequest& request) const;
/**
* A Callable wrapper for ReportTaskProgress that returns a future to the operation so that it can be executed in parallel to other requests.
*/
virtual Model::ReportTaskProgressOutcomeCallable ReportTaskProgressCallable(const Model::ReportTaskProgressRequest& request) const;
/**
* An Async wrapper for ReportTaskProgress that queues the request into a thread executor and triggers associated callback when operation has finished.
*/
virtual void ReportTaskProgressAsync(const Model::ReportTaskProgressRequest& request, const ReportTaskProgressResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const;
/**
* <p>Task runners call <code>ReportTaskRunnerHeartbeat</code> every 15 minutes to
* indicate that they are operational. If the AWS Data Pipeline Task Runner is
* launched on a resource managed by AWS Data Pipeline, the web service can use
* this call to detect when the task runner application has failed and restart a
* new instance.</p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/ReportTaskRunnerHeartbeat">AWS
* API Reference</a></p>
*/
virtual Model::ReportTaskRunnerHeartbeatOutcome ReportTaskRunnerHeartbeat(const Model::ReportTaskRunnerHeartbeatRequest& request) const;
/**
* A Callable wrapper for ReportTaskRunnerHeartbeat that returns a future to the operation so that it can be executed in parallel to other requests.
*/
virtual Model::ReportTaskRunnerHeartbeatOutcomeCallable ReportTaskRunnerHeartbeatCallable(const Model::ReportTaskRunnerHeartbeatRequest& request) const;
/**
* An Async wrapper for ReportTaskRunnerHeartbeat that queues the request into a thread executor and triggers associated callback when operation has finished.
*/
virtual void ReportTaskRunnerHeartbeatAsync(const Model::ReportTaskRunnerHeartbeatRequest& request, const ReportTaskRunnerHeartbeatResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const;
/**
* <p>Requests that the status of the specified physical or logical pipeline
* objects be updated in the specified pipeline. This update might not occur
* immediately, but is eventually consistent. The status that can be set depends on
* the type of object (for example, DataNode or Activity). You cannot perform this
* operation on <code>FINISHED</code> pipelines and attempting to do so returns
* <code>InvalidRequestException</code>.</p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/SetStatus">AWS
* API Reference</a></p>
*/
virtual Model::SetStatusOutcome SetStatus(const Model::SetStatusRequest& request) const;
/**
* A Callable wrapper for SetStatus that returns a future to the operation so that it can be executed in parallel to other requests.
*/
virtual Model::SetStatusOutcomeCallable SetStatusCallable(const Model::SetStatusRequest& request) const;
/**
* An Async wrapper for SetStatus that queues the request into a thread executor and triggers associated callback when operation has finished.
*/
virtual void SetStatusAsync(const Model::SetStatusRequest& request, const SetStatusResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const;
/**
* <p>Task runners call <code>SetTaskStatus</code> to notify AWS Data Pipeline that
* a task is completed and provide information about the final status. A task
* runner makes this call regardless of whether the task was sucessful. A task
* runner does not need to call <code>SetTaskStatus</code> for tasks that are
* canceled by the web service during a call to
* <a>ReportTaskProgress</a>.</p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/SetTaskStatus">AWS
* API Reference</a></p>
*/
virtual Model::SetTaskStatusOutcome SetTaskStatus(const Model::SetTaskStatusRequest& request) const;
/**
* A Callable wrapper for SetTaskStatus that returns a future to the operation so that it can be executed in parallel to other requests.
*/
virtual Model::SetTaskStatusOutcomeCallable SetTaskStatusCallable(const Model::SetTaskStatusRequest& request) const;
/**
* An Async wrapper for SetTaskStatus that queues the request into a thread executor and triggers associated callback when operation has finished.
*/
virtual void SetTaskStatusAsync(const Model::SetTaskStatusRequest& request, const SetTaskStatusResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const;
/**
* <p>Validates the specified pipeline definition to ensure that it is well formed
* and can be run without error.</p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/datapipeline-2012-10-29/ValidatePipelineDefinition">AWS
* API Reference</a></p>
*/
virtual Model::ValidatePipelineDefinitionOutcome ValidatePipelineDefinition(const Model::ValidatePipelineDefinitionRequest& request) const;
/**
* A Callable wrapper for ValidatePipelineDefinition that returns a future to the operation so that it can be executed in parallel to other requests.
*/
virtual Model::ValidatePipelineDefinitionOutcomeCallable ValidatePipelineDefinitionCallable(const Model::ValidatePipelineDefinitionRequest& request) const;
/**
* An Async wrapper for ValidatePipelineDefinition that queues the request into a thread executor and triggers associated callback when operation has finished.
*/
virtual void ValidatePipelineDefinitionAsync(const Model::ValidatePipelineDefinitionRequest& request, const ValidatePipelineDefinitionResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const;
void OverrideEndpoint(const Aws::String& endpoint);
private:
void init(const Aws::Client::ClientConfiguration& clientConfiguration);
void ActivatePipelineAsyncHelper(const Model::ActivatePipelineRequest& request, const ActivatePipelineResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const;
void AddTagsAsyncHelper(const Model::AddTagsRequest& request, const AddTagsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const;
void CreatePipelineAsyncHelper(const Model::CreatePipelineRequest& request, const CreatePipelineResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const;
void DeactivatePipelineAsyncHelper(const Model::DeactivatePipelineRequest& request, const DeactivatePipelineResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const;
void DeletePipelineAsyncHelper(const Model::DeletePipelineRequest& request, const DeletePipelineResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const;
void DescribeObjectsAsyncHelper(const Model::DescribeObjectsRequest& request, const DescribeObjectsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const;
void DescribePipelinesAsyncHelper(const Model::DescribePipelinesRequest& request, const DescribePipelinesResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const;
void EvaluateExpressionAsyncHelper(const Model::EvaluateExpressionRequest& request, const EvaluateExpressionResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const;
void GetPipelineDefinitionAsyncHelper(const Model::GetPipelineDefinitionRequest& request, const GetPipelineDefinitionResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const;
void ListPipelinesAsyncHelper(const Model::ListPipelinesRequest& request, const ListPipelinesResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const;
void PollForTaskAsyncHelper(const Model::PollForTaskRequest& request, const PollForTaskResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const;
void PutPipelineDefinitionAsyncHelper(const Model::PutPipelineDefinitionRequest& request, const PutPipelineDefinitionResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const;
void QueryObjectsAsyncHelper(const Model::QueryObjectsRequest& request, const QueryObjectsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const;
void RemoveTagsAsyncHelper(const Model::RemoveTagsRequest& request, const RemoveTagsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const;
void ReportTaskProgressAsyncHelper(const Model::ReportTaskProgressRequest& request, const ReportTaskProgressResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const;
void ReportTaskRunnerHeartbeatAsyncHelper(const Model::ReportTaskRunnerHeartbeatRequest& request, const ReportTaskRunnerHeartbeatResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const;
void SetStatusAsyncHelper(const Model::SetStatusRequest& request, const SetStatusResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const;
void SetTaskStatusAsyncHelper(const Model::SetTaskStatusRequest& request, const SetTaskStatusResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const;
void ValidatePipelineDefinitionAsyncHelper(const Model::ValidatePipelineDefinitionRequest& request, const ValidatePipelineDefinitionResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const;
Aws::String m_uri;
Aws::String m_configScheme;
std::shared_ptr<Aws::Utils::Threading::Executor> m_executor;
};
} // namespace DataPipeline
} // namespace Aws
| 71.738994 | 271 | 0.743392 | [
"object",
"model"
] |
88a3112e8821e1164fdfb44f85d4eed61293489b | 32,577 | h | C | Linux/sample/FaceDemo/src/Opencv/opencv2/videoio/videoio_c.h | iotbo/TengineKit | b82c3758360ef37cb219d487d3858a4c1b4effe7 | [
"Apache-2.0"
] | null | null | null | Linux/sample/FaceDemo/src/Opencv/opencv2/videoio/videoio_c.h | iotbo/TengineKit | b82c3758360ef37cb219d487d3858a4c1b4effe7 | [
"Apache-2.0"
] | null | null | null | Linux/sample/FaceDemo/src/Opencv/opencv2/videoio/videoio_c.h | iotbo/TengineKit | b82c3758360ef37cb219d487d3858a4c1b4effe7 | [
"Apache-2.0"
] | null | null | null | /*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.
//
//
// Intel License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000, Intel Corporation, 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 Intel Corporation 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*/
#ifndef OPENCV_VIDEOIO_H
#define OPENCV_VIDEOIO_H
#include "opencv2/core/core_c.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
/**
@addtogroup videoio_c
@{
*/
/****************************************************************************************\
* Working with Video Files and Cameras *
\****************************************************************************************/
/** @brief "black box" capture structure
In C++ use cv::VideoCapture
*/
typedef struct CvCapture CvCapture;
/** @brief start capturing frames from video file
*/
CVAPI(CvCapture *) cvCreateFileCapture(const char *filename);
/** @brief start capturing frames from video file. allows specifying a preferred
* API to use
*/
CVAPI(CvCapture *)
cvCreateFileCaptureWithPreference(const char *filename, int apiPreference);
enum {
CV_CAP_ANY = 0, // autodetect
CV_CAP_MIL = 100, // MIL proprietary drivers
CV_CAP_VFW = 200, // platform native
CV_CAP_V4L = 200,
CV_CAP_V4L2 = 200,
CV_CAP_FIREWARE = 300, // IEEE 1394 drivers
CV_CAP_FIREWIRE = 300,
CV_CAP_IEEE1394 = 300,
CV_CAP_DC1394 = 300,
CV_CAP_CMU1394 = 300,
CV_CAP_STEREO = 400, // TYZX proprietary drivers
CV_CAP_TYZX = 400,
CV_TYZX_LEFT = 400,
CV_TYZX_RIGHT = 401,
CV_TYZX_COLOR = 402,
CV_TYZX_Z = 403,
CV_CAP_QT = 500, // QuickTime
CV_CAP_UNICAP = 600, // Unicap drivers
CV_CAP_DSHOW = 700, // DirectShow (via videoInput)
CV_CAP_MSMF = 1400, // Microsoft Media Foundation (via videoInput)
CV_CAP_PVAPI = 800, // PvAPI, Prosilica GigE SDK
CV_CAP_OPENNI = 900, // OpenNI (for Kinect)
CV_CAP_OPENNI_ASUS = 910, // OpenNI (for Asus Xtion)
CV_CAP_ANDROID = 1000, // Android - not used
CV_CAP_ANDROID_BACK = CV_CAP_ANDROID + 99, // Android back camera - not used
CV_CAP_ANDROID_FRONT = CV_CAP_ANDROID + 98, // Android front camera - not used
CV_CAP_XIAPI = 1100, // XIMEA Camera API
CV_CAP_AVFOUNDATION =
1200, // AVFoundation framework for iOS (OS X Lion will have the same API)
CV_CAP_GIGANETIX = 1300, // Smartek Giganetix GigEVisionSDK
CV_CAP_INTELPERC = 1500, // Intel Perceptual Computing
CV_CAP_OPENNI2 = 1600, // OpenNI2 (for Kinect)
CV_CAP_GPHOTO2 = 1700,
CV_CAP_GSTREAMER = 1800, // GStreamer
CV_CAP_FFMPEG = 1900, // FFMPEG
CV_CAP_IMAGES = 2000, // OpenCV Image Sequence (e.g. img_%02d.jpg)
CV_CAP_ARAVIS = 2100 // Aravis GigE SDK
};
/** @brief start capturing frames from camera: index = camera_index +
* domain_offset (CV_CAP_*)
*/
CVAPI(CvCapture *) cvCreateCameraCapture(int index);
/** @brief grab a frame, return 1 on success, 0 on fail.
this function is thought to be fast
*/
CVAPI(int) cvGrabFrame(CvCapture *capture);
/** @brief get the frame grabbed with cvGrabFrame(..)
This function may apply some frame processing like
frame decompression, flipping etc.
@warning !!!DO NOT RELEASE or MODIFY the retrieved frame!!!
*/
CVAPI(IplImage *)
cvRetrieveFrame(CvCapture *capture, int streamIdx CV_DEFAULT(0));
/** @brief Just a combination of cvGrabFrame and cvRetrieveFrame
@warning !!!DO NOT RELEASE or MODIFY the retrieved frame!!!
*/
CVAPI(IplImage *) cvQueryFrame(CvCapture *capture);
/** @brief stop capturing/reading and free resources
*/
CVAPI(void) cvReleaseCapture(CvCapture **capture);
enum {
// modes of the controlling registers (can be: auto, manual, auto single push,
// absolute Latter allowed with any other mode) every feature can have only
// one mode turned on at a time
CV_CAP_PROP_DC1394_OFF =
-4, // turn the feature off (not controlled manually nor automatically)
CV_CAP_PROP_DC1394_MODE_MANUAL =
-3, // set automatically when a value of the feature is set by the user
CV_CAP_PROP_DC1394_MODE_AUTO = -2,
CV_CAP_PROP_DC1394_MODE_ONE_PUSH_AUTO = -1,
CV_CAP_PROP_POS_MSEC = 0,
CV_CAP_PROP_POS_FRAMES = 1,
CV_CAP_PROP_POS_AVI_RATIO = 2,
CV_CAP_PROP_FRAME_WIDTH = 3,
CV_CAP_PROP_FRAME_HEIGHT = 4,
CV_CAP_PROP_FPS = 5,
CV_CAP_PROP_FOURCC = 6,
CV_CAP_PROP_FRAME_COUNT = 7,
CV_CAP_PROP_FORMAT = 8,
CV_CAP_PROP_MODE = 9,
CV_CAP_PROP_BRIGHTNESS = 10,
CV_CAP_PROP_CONTRAST = 11,
CV_CAP_PROP_SATURATION = 12,
CV_CAP_PROP_HUE = 13,
CV_CAP_PROP_GAIN = 14,
CV_CAP_PROP_EXPOSURE = 15,
CV_CAP_PROP_CONVERT_RGB = 16,
CV_CAP_PROP_WHITE_BALANCE_BLUE_U = 17,
CV_CAP_PROP_RECTIFICATION = 18,
CV_CAP_PROP_MONOCHROME = 19,
CV_CAP_PROP_SHARPNESS = 20,
CV_CAP_PROP_AUTO_EXPOSURE = 21, // exposure control done by camera,
// user can adjust reference level
// using this feature
CV_CAP_PROP_GAMMA = 22,
CV_CAP_PROP_TEMPERATURE = 23,
CV_CAP_PROP_TRIGGER = 24,
CV_CAP_PROP_TRIGGER_DELAY = 25,
CV_CAP_PROP_WHITE_BALANCE_RED_V = 26,
CV_CAP_PROP_ZOOM = 27,
CV_CAP_PROP_FOCUS = 28,
CV_CAP_PROP_GUID = 29,
CV_CAP_PROP_ISO_SPEED = 30,
CV_CAP_PROP_MAX_DC1394 = 31,
CV_CAP_PROP_BACKLIGHT = 32,
CV_CAP_PROP_PAN = 33,
CV_CAP_PROP_TILT = 34,
CV_CAP_PROP_ROLL = 35,
CV_CAP_PROP_IRIS = 36,
CV_CAP_PROP_SETTINGS = 37,
CV_CAP_PROP_BUFFERSIZE = 38,
CV_CAP_PROP_AUTOFOCUS = 39,
CV_CAP_PROP_SAR_NUM = 40,
CV_CAP_PROP_SAR_DEN = 41,
CV_CAP_PROP_AUTOGRAB =
1024, // property for videoio class CvCapture_Android only
CV_CAP_PROP_SUPPORTED_PREVIEW_SIZES_STRING =
1025, // readonly, tricky property, returns cpnst char* indeed
CV_CAP_PROP_PREVIEW_FORMAT =
1026, // readonly, tricky property, returns cpnst char* indeed
// OpenNI map generators
CV_CAP_OPENNI_DEPTH_GENERATOR = 1 << 31,
CV_CAP_OPENNI_IMAGE_GENERATOR = 1 << 30,
CV_CAP_OPENNI_IR_GENERATOR = 1 << 29,
CV_CAP_OPENNI_GENERATORS_MASK = CV_CAP_OPENNI_DEPTH_GENERATOR +
CV_CAP_OPENNI_IMAGE_GENERATOR +
CV_CAP_OPENNI_IR_GENERATOR,
// Properties of cameras available through OpenNI interfaces
CV_CAP_PROP_OPENNI_OUTPUT_MODE = 100,
CV_CAP_PROP_OPENNI_FRAME_MAX_DEPTH = 101, // in mm
CV_CAP_PROP_OPENNI_BASELINE = 102, // in mm
CV_CAP_PROP_OPENNI_FOCAL_LENGTH = 103, // in pixels
CV_CAP_PROP_OPENNI_REGISTRATION = 104, // flag
CV_CAP_PROP_OPENNI_REGISTRATION_ON =
CV_CAP_PROP_OPENNI_REGISTRATION, // flag that synchronizes the remapping
// depth map to image map by changing
// depth generator's view point (if the
// flag is "on") or sets this view point
// to its normal one (if the flag is
// "off").
CV_CAP_PROP_OPENNI_APPROX_FRAME_SYNC = 105,
CV_CAP_PROP_OPENNI_MAX_BUFFER_SIZE = 106,
CV_CAP_PROP_OPENNI_CIRCLE_BUFFER = 107,
CV_CAP_PROP_OPENNI_MAX_TIME_DURATION = 108,
CV_CAP_PROP_OPENNI_GENERATOR_PRESENT = 109,
CV_CAP_PROP_OPENNI2_SYNC = 110,
CV_CAP_PROP_OPENNI2_MIRROR = 111,
CV_CAP_OPENNI_IMAGE_GENERATOR_PRESENT =
CV_CAP_OPENNI_IMAGE_GENERATOR + CV_CAP_PROP_OPENNI_GENERATOR_PRESENT,
CV_CAP_OPENNI_IMAGE_GENERATOR_OUTPUT_MODE =
CV_CAP_OPENNI_IMAGE_GENERATOR + CV_CAP_PROP_OPENNI_OUTPUT_MODE,
CV_CAP_OPENNI_DEPTH_GENERATOR_PRESENT =
CV_CAP_OPENNI_DEPTH_GENERATOR + CV_CAP_PROP_OPENNI_GENERATOR_PRESENT,
CV_CAP_OPENNI_DEPTH_GENERATOR_BASELINE =
CV_CAP_OPENNI_DEPTH_GENERATOR + CV_CAP_PROP_OPENNI_BASELINE,
CV_CAP_OPENNI_DEPTH_GENERATOR_FOCAL_LENGTH =
CV_CAP_OPENNI_DEPTH_GENERATOR + CV_CAP_PROP_OPENNI_FOCAL_LENGTH,
CV_CAP_OPENNI_DEPTH_GENERATOR_REGISTRATION =
CV_CAP_OPENNI_DEPTH_GENERATOR + CV_CAP_PROP_OPENNI_REGISTRATION,
CV_CAP_OPENNI_DEPTH_GENERATOR_REGISTRATION_ON =
CV_CAP_OPENNI_DEPTH_GENERATOR_REGISTRATION,
CV_CAP_OPENNI_IR_GENERATOR_PRESENT =
CV_CAP_OPENNI_IR_GENERATOR + CV_CAP_PROP_OPENNI_GENERATOR_PRESENT,
// Properties of cameras available through GStreamer interface
CV_CAP_GSTREAMER_QUEUE_LENGTH = 200, // default is 1
// PVAPI
CV_CAP_PROP_PVAPI_MULTICASTIP =
300, // ip for anable multicast master mode. 0 for disable multicast
CV_CAP_PROP_PVAPI_FRAMESTARTTRIGGERMODE =
301, // FrameStartTriggerMode: Determines how a frame is initiated
CV_CAP_PROP_PVAPI_DECIMATIONHORIZONTAL =
302, // Horizontal sub-sampling of the image
CV_CAP_PROP_PVAPI_DECIMATIONVERTICAL =
303, // Vertical sub-sampling of the image
CV_CAP_PROP_PVAPI_BINNINGX = 304, // Horizontal binning factor
CV_CAP_PROP_PVAPI_BINNINGY = 305, // Vertical binning factor
CV_CAP_PROP_PVAPI_PIXELFORMAT = 306, // Pixel format
// Properties of cameras available through XIMEA SDK interface
CV_CAP_PROP_XI_DOWNSAMPLING =
400, // Change image resolution by binning or skipping.
CV_CAP_PROP_XI_DATA_FORMAT = 401, // Output data format.
CV_CAP_PROP_XI_OFFSET_X = 402, // Horizontal offset from the origin to the
// area of interest (in pixels).
CV_CAP_PROP_XI_OFFSET_Y = 403, // Vertical offset from the origin to the area
// of interest (in pixels).
CV_CAP_PROP_XI_TRG_SOURCE = 404, // Defines source of trigger.
CV_CAP_PROP_XI_TRG_SOFTWARE =
405, // Generates an internal trigger. PRM_TRG_SOURCE must be set to
// TRG_SOFTWARE.
CV_CAP_PROP_XI_GPI_SELECTOR = 406, // Selects general purpose input
CV_CAP_PROP_XI_GPI_MODE = 407, // Set general purpose input mode
CV_CAP_PROP_XI_GPI_LEVEL = 408, // Get general purpose level
CV_CAP_PROP_XI_GPO_SELECTOR = 409, // Selects general purpose output
CV_CAP_PROP_XI_GPO_MODE = 410, // Set general purpose output mode
CV_CAP_PROP_XI_LED_SELECTOR = 411, // Selects camera signalling LED
CV_CAP_PROP_XI_LED_MODE = 412, // Define camera signalling LED functionality
CV_CAP_PROP_XI_MANUAL_WB =
413, // Calculates White Balance(must be called during acquisition)
CV_CAP_PROP_XI_AUTO_WB = 414, // Automatic white balance
CV_CAP_PROP_XI_AEAG = 415, // Automatic exposure/gain
CV_CAP_PROP_XI_EXP_PRIORITY =
416, // Exposure priority (0.5 - exposure 50%, gain 50%).
CV_CAP_PROP_XI_AE_MAX_LIMIT =
417, // Maximum limit of exposure in AEAG procedure
CV_CAP_PROP_XI_AG_MAX_LIMIT = 418, // Maximum limit of gain in AEAG procedure
CV_CAP_PROP_XI_AEAG_LEVEL =
419, // Average intensity of output signal AEAG should achieve(in %)
CV_CAP_PROP_XI_TIMEOUT = 420, // Image capture timeout in milliseconds
CV_CAP_PROP_XI_EXPOSURE = 421, // Exposure time in microseconds
CV_CAP_PROP_XI_EXPOSURE_BURST_COUNT =
422, // Sets the number of times of exposure in one frame.
CV_CAP_PROP_XI_GAIN_SELECTOR = 423, // Gain selector for parameter Gain allows
// to select different type of gains.
CV_CAP_PROP_XI_GAIN = 424, // Gain in dB
CV_CAP_PROP_XI_DOWNSAMPLING_TYPE = 426, // Change image downsampling type.
CV_CAP_PROP_XI_BINNING_SELECTOR = 427, // Binning engine selector.
CV_CAP_PROP_XI_BINNING_VERTICAL =
428, // Vertical Binning - number of vertical photo-sensitive cells to
// combine together.
CV_CAP_PROP_XI_BINNING_HORIZONTAL =
429, // Horizontal Binning - number of horizontal photo-sensitive cells to
// combine together.
CV_CAP_PROP_XI_BINNING_PATTERN = 430, // Binning pattern type.
CV_CAP_PROP_XI_DECIMATION_SELECTOR = 431, // Decimation engine selector.
CV_CAP_PROP_XI_DECIMATION_VERTICAL =
432, // Vertical Decimation - vertical sub-sampling of the image - reduces
// the vertical resolution of the image by the specified vertical
// decimation factor.
CV_CAP_PROP_XI_DECIMATION_HORIZONTAL =
433, // Horizontal Decimation - horizontal sub-sampling of the image -
// reduces the horizontal resolution of the image by the specified
// vertical decimation factor.
CV_CAP_PROP_XI_DECIMATION_PATTERN = 434, // Decimation pattern type.
CV_CAP_PROP_XI_TEST_PATTERN_GENERATOR_SELECTOR =
587, // Selects which test pattern generator is controlled by the
// TestPattern feature.
CV_CAP_PROP_XI_TEST_PATTERN = 588, // Selects which test pattern type is
// generated by the selected generator.
CV_CAP_PROP_XI_IMAGE_DATA_FORMAT = 435, // Output data format.
CV_CAP_PROP_XI_SHUTTER_TYPE = 436, // Change sensor shutter type(CMOS sensor).
CV_CAP_PROP_XI_SENSOR_TAPS = 437, // Number of taps
CV_CAP_PROP_XI_AEAG_ROI_OFFSET_X =
439, // Automatic exposure/gain ROI offset X
CV_CAP_PROP_XI_AEAG_ROI_OFFSET_Y =
440, // Automatic exposure/gain ROI offset Y
CV_CAP_PROP_XI_AEAG_ROI_WIDTH = 441, // Automatic exposure/gain ROI Width
CV_CAP_PROP_XI_AEAG_ROI_HEIGHT = 442, // Automatic exposure/gain ROI Height
CV_CAP_PROP_XI_BPC = 445, // Correction of bad pixels
CV_CAP_PROP_XI_WB_KR = 448, // White balance red coefficient
CV_CAP_PROP_XI_WB_KG = 449, // White balance green coefficient
CV_CAP_PROP_XI_WB_KB = 450, // White balance blue coefficient
CV_CAP_PROP_XI_WIDTH =
451, // Width of the Image provided by the device (in pixels).
CV_CAP_PROP_XI_HEIGHT =
452, // Height of the Image provided by the device (in pixels).
CV_CAP_PROP_XI_REGION_SELECTOR =
589, // Selects Region in Multiple ROI which parameters are set by width,
// height, ... ,region mode
CV_CAP_PROP_XI_REGION_MODE =
595, // Activates/deactivates Region selected by Region Selector
CV_CAP_PROP_XI_LIMIT_BANDWIDTH =
459, // Set/get bandwidth(datarate)(in Megabits)
CV_CAP_PROP_XI_SENSOR_DATA_BIT_DEPTH = 460, // Sensor output data bit depth.
CV_CAP_PROP_XI_OUTPUT_DATA_BIT_DEPTH = 461, // Device output data bit depth.
CV_CAP_PROP_XI_IMAGE_DATA_BIT_DEPTH =
462, // bitdepth of data returned by function xiGetImage
CV_CAP_PROP_XI_OUTPUT_DATA_PACKING =
463, // Device output data packing (or grouping) enabled. Packing could be
// enabled if output_data_bit_depth > 8 and packing capability is
// available.
CV_CAP_PROP_XI_OUTPUT_DATA_PACKING_TYPE =
464, // Data packing type. Some cameras supports only specific packing
// type.
CV_CAP_PROP_XI_IS_COOLED = 465, // Returns 1 for cameras that support cooling.
CV_CAP_PROP_XI_COOLING = 466, // Start camera cooling.
CV_CAP_PROP_XI_TARGET_TEMP =
467, // Set sensor target temperature for cooling.
CV_CAP_PROP_XI_CHIP_TEMP = 468, // Camera sensor temperature
CV_CAP_PROP_XI_HOUS_TEMP = 469, // Camera housing tepmerature
CV_CAP_PROP_XI_HOUS_BACK_SIDE_TEMP =
590, // Camera housing back side tepmerature
CV_CAP_PROP_XI_SENSOR_BOARD_TEMP = 596, // Camera sensor board temperature
CV_CAP_PROP_XI_CMS = 470, // Mode of color management system.
CV_CAP_PROP_XI_APPLY_CMS =
471, // Enable applying of CMS profiles to xiGetImage (see
// XI_PRM_INPUT_CMS_PROFILE, XI_PRM_OUTPUT_CMS_PROFILE).
CV_CAP_PROP_XI_IMAGE_IS_COLOR = 474, // Returns 1 for color cameras.
CV_CAP_PROP_XI_COLOR_FILTER_ARRAY =
475, // Returns color filter array type of RAW data.
CV_CAP_PROP_XI_GAMMAY = 476, // Luminosity gamma
CV_CAP_PROP_XI_GAMMAC = 477, // Chromaticity gamma
CV_CAP_PROP_XI_SHARPNESS = 478, // Sharpness Strength
CV_CAP_PROP_XI_CC_MATRIX_00 = 479, // Color Correction Matrix element [0][0]
CV_CAP_PROP_XI_CC_MATRIX_01 = 480, // Color Correction Matrix element [0][1]
CV_CAP_PROP_XI_CC_MATRIX_02 = 481, // Color Correction Matrix element [0][2]
CV_CAP_PROP_XI_CC_MATRIX_03 = 482, // Color Correction Matrix element [0][3]
CV_CAP_PROP_XI_CC_MATRIX_10 = 483, // Color Correction Matrix element [1][0]
CV_CAP_PROP_XI_CC_MATRIX_11 = 484, // Color Correction Matrix element [1][1]
CV_CAP_PROP_XI_CC_MATRIX_12 = 485, // Color Correction Matrix element [1][2]
CV_CAP_PROP_XI_CC_MATRIX_13 = 486, // Color Correction Matrix element [1][3]
CV_CAP_PROP_XI_CC_MATRIX_20 = 487, // Color Correction Matrix element [2][0]
CV_CAP_PROP_XI_CC_MATRIX_21 = 488, // Color Correction Matrix element [2][1]
CV_CAP_PROP_XI_CC_MATRIX_22 = 489, // Color Correction Matrix element [2][2]
CV_CAP_PROP_XI_CC_MATRIX_23 = 490, // Color Correction Matrix element [2][3]
CV_CAP_PROP_XI_CC_MATRIX_30 = 491, // Color Correction Matrix element [3][0]
CV_CAP_PROP_XI_CC_MATRIX_31 = 492, // Color Correction Matrix element [3][1]
CV_CAP_PROP_XI_CC_MATRIX_32 = 493, // Color Correction Matrix element [3][2]
CV_CAP_PROP_XI_CC_MATRIX_33 = 494, // Color Correction Matrix element [3][3]
CV_CAP_PROP_XI_DEFAULT_CC_MATRIX = 495, // Set default Color Correction Matrix
CV_CAP_PROP_XI_TRG_SELECTOR = 498, // Selects the type of trigger.
CV_CAP_PROP_XI_ACQ_FRAME_BURST_COUNT =
499, // Sets number of frames acquired by burst. This burst is used only
// if trigger is set to FrameBurstStart
CV_CAP_PROP_XI_DEBOUNCE_EN = 507, // Enable/Disable debounce to selected GPI
CV_CAP_PROP_XI_DEBOUNCE_T0 = 508, // Debounce time (x * 10us)
CV_CAP_PROP_XI_DEBOUNCE_T1 = 509, // Debounce time (x * 10us)
CV_CAP_PROP_XI_DEBOUNCE_POL =
510, // Debounce polarity (pol = 1 t0 - falling edge, t1 - rising edge)
CV_CAP_PROP_XI_LENS_MODE =
511, // Status of lens control interface. This shall be set to XI_ON
// before any Lens operations.
CV_CAP_PROP_XI_LENS_APERTURE_VALUE =
512, // Current lens aperture value in stops. Examples: 2.8, 4, 5.6, 8, 11
CV_CAP_PROP_XI_LENS_FOCUS_MOVEMENT_VALUE =
513, // Lens current focus movement value to be used by
// XI_PRM_LENS_FOCUS_MOVE in motor steps.
CV_CAP_PROP_XI_LENS_FOCUS_MOVE = 514, // Moves lens focus motor by steps set
// in XI_PRM_LENS_FOCUS_MOVEMENT_VALUE.
CV_CAP_PROP_XI_LENS_FOCUS_DISTANCE = 515, // Lens focus distance in cm.
CV_CAP_PROP_XI_LENS_FOCAL_LENGTH = 516, // Lens focal distance in mm.
CV_CAP_PROP_XI_LENS_FEATURE_SELECTOR =
517, // Selects the current feature which is accessible by
// XI_PRM_LENS_FEATURE.
CV_CAP_PROP_XI_LENS_FEATURE =
518, // Allows access to lens feature value currently selected by
// XI_PRM_LENS_FEATURE_SELECTOR.
CV_CAP_PROP_XI_DEVICE_MODEL_ID = 521, // Return device model id
CV_CAP_PROP_XI_DEVICE_SN = 522, // Return device serial number
CV_CAP_PROP_XI_IMAGE_DATA_FORMAT_RGB32_ALPHA =
529, // The alpha channel of RGB32 output image format.
CV_CAP_PROP_XI_IMAGE_PAYLOAD_SIZE =
530, // Buffer size in bytes sufficient for output image returned by
// xiGetImage
CV_CAP_PROP_XI_TRANSPORT_PIXEL_FORMAT =
531, // Current format of pixels on transport layer.
CV_CAP_PROP_XI_SENSOR_CLOCK_FREQ_HZ = 532, // Sensor clock frequency in Hz.
CV_CAP_PROP_XI_SENSOR_CLOCK_FREQ_INDEX =
533, // Sensor clock frequency index. Sensor with selected frequencies
// have possibility to set the frequency only by this index.
CV_CAP_PROP_XI_SENSOR_OUTPUT_CHANNEL_COUNT =
534, // Number of output channels from sensor used for data transfer.
CV_CAP_PROP_XI_FRAMERATE = 535, // Define framerate in Hz
CV_CAP_PROP_XI_COUNTER_SELECTOR = 536, // Select counter
CV_CAP_PROP_XI_COUNTER_VALUE = 537, // Counter status
CV_CAP_PROP_XI_ACQ_TIMING_MODE = 538, // Type of sensor frames timing.
CV_CAP_PROP_XI_AVAILABLE_BANDWIDTH =
539, // Calculate and return available interface bandwidth(int Megabits)
CV_CAP_PROP_XI_BUFFER_POLICY = 540, // Data move policy
CV_CAP_PROP_XI_LUT_EN = 541, // Activates LUT.
CV_CAP_PROP_XI_LUT_INDEX = 542, // Control the index (offset) of the
// coefficient to access in the LUT.
CV_CAP_PROP_XI_LUT_VALUE = 543, // Value at entry LUTIndex of the LUT
CV_CAP_PROP_XI_TRG_DELAY =
544, // Specifies the delay in microseconds (us) to apply after the
// trigger reception before activating it.
CV_CAP_PROP_XI_TS_RST_MODE =
545, // Defines how time stamp reset engine will be armed
CV_CAP_PROP_XI_TS_RST_SOURCE =
546, // Defines which source will be used for timestamp reset. Writing
// this parameter will trigger settings of engine (arming)
CV_CAP_PROP_XI_IS_DEVICE_EXIST =
547, // Returns 1 if camera connected and works properly.
CV_CAP_PROP_XI_ACQ_BUFFER_SIZE =
548, // Acquisition buffer size in buffer_size_unit. Default bytes.
CV_CAP_PROP_XI_ACQ_BUFFER_SIZE_UNIT =
549, // Acquisition buffer size unit in bytes. Default 1. E.g. Value 1024
// means that buffer_size is in KiBytes
CV_CAP_PROP_XI_ACQ_TRANSPORT_BUFFER_SIZE =
550, // Acquisition transport buffer size in bytes
CV_CAP_PROP_XI_BUFFERS_QUEUE_SIZE = 551, // Queue of field/frame buffers
CV_CAP_PROP_XI_ACQ_TRANSPORT_BUFFER_COMMIT =
552, // Number of buffers to commit to low level
CV_CAP_PROP_XI_RECENT_FRAME = 553, // GetImage returns most recent frame
CV_CAP_PROP_XI_DEVICE_RESET = 554, // Resets the camera to default state.
CV_CAP_PROP_XI_COLUMN_FPN_CORRECTION = 555, // Correction of column FPN
CV_CAP_PROP_XI_ROW_FPN_CORRECTION = 591, // Correction of row FPN
CV_CAP_PROP_XI_SENSOR_MODE =
558, // Current sensor mode. Allows to select sensor mode by one integer.
// Setting of this parameter affects: image dimensions and
// downsampling.
CV_CAP_PROP_XI_HDR = 559, // Enable High Dynamic Range feature.
CV_CAP_PROP_XI_HDR_KNEEPOINT_COUNT =
560, // The number of kneepoints in the PWLR.
CV_CAP_PROP_XI_HDR_T1 =
561, // position of first kneepoint(in % of XI_PRM_EXPOSURE)
CV_CAP_PROP_XI_HDR_T2 =
562, // position of second kneepoint (in % of XI_PRM_EXPOSURE)
CV_CAP_PROP_XI_KNEEPOINT1 =
563, // value of first kneepoint (% of sensor saturation)
CV_CAP_PROP_XI_KNEEPOINT2 =
564, // value of second kneepoint (% of sensor saturation)
CV_CAP_PROP_XI_IMAGE_BLACK_LEVEL =
565, // Last image black level counts. Can be used for Offline processing
// to recall it.
CV_CAP_PROP_XI_HW_REVISION = 571, // Returns hardware revision number.
CV_CAP_PROP_XI_DEBUG_LEVEL = 572, // Set debug level
CV_CAP_PROP_XI_AUTO_BANDWIDTH_CALCULATION =
573, // Automatic bandwidth calculation,
CV_CAP_PROP_XI_FFS_FILE_ID = 594, // File number.
CV_CAP_PROP_XI_FFS_FILE_SIZE = 580, // Size of file.
CV_CAP_PROP_XI_FREE_FFS_SIZE = 581, // Size of free camera FFS.
CV_CAP_PROP_XI_USED_FFS_SIZE = 582, // Size of used camera FFS.
CV_CAP_PROP_XI_FFS_ACCESS_KEY =
583, // Setting of key enables file operations on some cameras.
CV_CAP_PROP_XI_SENSOR_FEATURE_SELECTOR =
585, // Selects the current feature which is accessible by
// XI_PRM_SENSOR_FEATURE_VALUE.
CV_CAP_PROP_XI_SENSOR_FEATURE_VALUE =
586, // Allows access to sensor feature value currently selected by
// XI_PRM_SENSOR_FEATURE_SELECTOR.
// Properties for Android cameras
CV_CAP_PROP_ANDROID_FLASH_MODE = 8001,
CV_CAP_PROP_ANDROID_FOCUS_MODE = 8002,
CV_CAP_PROP_ANDROID_WHITE_BALANCE = 8003,
CV_CAP_PROP_ANDROID_ANTIBANDING = 8004,
CV_CAP_PROP_ANDROID_FOCAL_LENGTH = 8005,
CV_CAP_PROP_ANDROID_FOCUS_DISTANCE_NEAR = 8006,
CV_CAP_PROP_ANDROID_FOCUS_DISTANCE_OPTIMAL = 8007,
CV_CAP_PROP_ANDROID_FOCUS_DISTANCE_FAR = 8008,
CV_CAP_PROP_ANDROID_EXPOSE_LOCK = 8009,
CV_CAP_PROP_ANDROID_WHITEBALANCE_LOCK = 8010,
// Properties of cameras available through AVFOUNDATION interface
CV_CAP_PROP_IOS_DEVICE_FOCUS = 9001,
CV_CAP_PROP_IOS_DEVICE_EXPOSURE = 9002,
CV_CAP_PROP_IOS_DEVICE_FLASH = 9003,
CV_CAP_PROP_IOS_DEVICE_WHITEBALANCE = 9004,
CV_CAP_PROP_IOS_DEVICE_TORCH = 9005,
// Properties of cameras available through Smartek Giganetix Ethernet Vision
// interface
/* --- Vladimir Litvinenko (litvinenko.vladimir@gmail.com) --- */
CV_CAP_PROP_GIGA_FRAME_OFFSET_X = 10001,
CV_CAP_PROP_GIGA_FRAME_OFFSET_Y = 10002,
CV_CAP_PROP_GIGA_FRAME_WIDTH_MAX = 10003,
CV_CAP_PROP_GIGA_FRAME_HEIGH_MAX = 10004,
CV_CAP_PROP_GIGA_FRAME_SENS_WIDTH = 10005,
CV_CAP_PROP_GIGA_FRAME_SENS_HEIGH = 10006,
CV_CAP_PROP_INTELPERC_PROFILE_COUNT = 11001,
CV_CAP_PROP_INTELPERC_PROFILE_IDX = 11002,
CV_CAP_PROP_INTELPERC_DEPTH_LOW_CONFIDENCE_VALUE = 11003,
CV_CAP_PROP_INTELPERC_DEPTH_SATURATION_VALUE = 11004,
CV_CAP_PROP_INTELPERC_DEPTH_CONFIDENCE_THRESHOLD = 11005,
CV_CAP_PROP_INTELPERC_DEPTH_FOCAL_LENGTH_HORZ = 11006,
CV_CAP_PROP_INTELPERC_DEPTH_FOCAL_LENGTH_VERT = 11007,
// Intel PerC streams
CV_CAP_INTELPERC_DEPTH_GENERATOR = 1 << 29,
CV_CAP_INTELPERC_IMAGE_GENERATOR = 1 << 28,
CV_CAP_INTELPERC_GENERATORS_MASK =
CV_CAP_INTELPERC_DEPTH_GENERATOR + CV_CAP_INTELPERC_IMAGE_GENERATOR
};
// Generic camera output modes.
// Currently, these are supported through the libv4l interface only.
enum {
CV_CAP_MODE_BGR = 0, // BGR24 (default)
CV_CAP_MODE_RGB = 1, // RGB24
CV_CAP_MODE_GRAY = 2, // Y8
CV_CAP_MODE_YUYV = 3 // YUYV
};
enum {
// Data given from depth generator.
CV_CAP_OPENNI_DEPTH_MAP = 0, // Depth values in mm (CV_16UC1)
CV_CAP_OPENNI_POINT_CLOUD_MAP = 1, // XYZ in meters (CV_32FC3)
CV_CAP_OPENNI_DISPARITY_MAP = 2, // Disparity in pixels (CV_8UC1)
CV_CAP_OPENNI_DISPARITY_MAP_32F = 3, // Disparity in pixels (CV_32FC1)
CV_CAP_OPENNI_VALID_DEPTH_MASK = 4, // CV_8UC1
// Data given from RGB image generator.
CV_CAP_OPENNI_BGR_IMAGE = 5,
CV_CAP_OPENNI_GRAY_IMAGE = 6,
// Data given from IR image generator.
CV_CAP_OPENNI_IR_IMAGE = 7
};
// Supported output modes of OpenNI image generator
enum {
CV_CAP_OPENNI_VGA_30HZ = 0,
CV_CAP_OPENNI_SXGA_15HZ = 1,
CV_CAP_OPENNI_SXGA_30HZ = 2,
CV_CAP_OPENNI_QVGA_30HZ = 3,
CV_CAP_OPENNI_QVGA_60HZ = 4
};
enum {
CV_CAP_INTELPERC_DEPTH_MAP =
0, // Each pixel is a 16-bit integer. The value indicates the distance
// from an object to the camera's XY plane or the Cartesian depth.
CV_CAP_INTELPERC_UVDEPTH_MAP =
1, // Each pixel contains two 32-bit floating point values in the range of
// 0-1, representing the mapping of depth coordinates to the color
// coordinates.
CV_CAP_INTELPERC_IR_MAP =
2, // Each pixel is a 16-bit integer. The value indicates the intensity of
// the reflected laser beam.
CV_CAP_INTELPERC_IMAGE = 3
};
// gPhoto2 properties, if propertyId is less than 0 then work on widget with
// that __additive inversed__ camera setting ID Get IDs by using
// CAP_PROP_GPHOTO2_WIDGET_ENUMERATE.
// @see CvCaptureCAM_GPHOTO2 for more info
enum {
CV_CAP_PROP_GPHOTO2_PREVIEW =
17001, // Capture only preview from liveview mode.
CV_CAP_PROP_GPHOTO2_WIDGET_ENUMERATE =
17002, // Readonly, returns (const char *).
CV_CAP_PROP_GPHOTO2_RELOAD_CONFIG =
17003, // Trigger, only by set. Reload camera settings.
CV_CAP_PROP_GPHOTO2_RELOAD_ON_CHANGE = 17004, // Reload all settings on set.
CV_CAP_PROP_GPHOTO2_COLLECT_MSGS = 17005, // Collect messages with details.
CV_CAP_PROP_GPHOTO2_FLUSH_MSGS = 17006, // Readonly, returns (const char *).
CV_CAP_PROP_SPEED =
17007, // Exposure speed. Can be readonly, depends on camera program.
CV_CAP_PROP_APERTURE =
17008, // Aperture. Can be readonly, depends on camera program.
CV_CAP_PROP_EXPOSUREPROGRAM = 17009, // Camera exposure program.
CV_CAP_PROP_VIEWFINDER = 17010 // Enter liveview mode.
};
/** @brief retrieve capture properties
*/
CVAPI(double) cvGetCaptureProperty(CvCapture *capture, int property_id);
/** @brief set capture properties
*/
CVAPI(int)
cvSetCaptureProperty(CvCapture *capture, int property_id, double value);
/** @brief Return the type of the capturer (eg, ::CV_CAP_VFW, ::CV_CAP_UNICAP)
It is unknown if created with ::CV_CAP_ANY
*/
CVAPI(int) cvGetCaptureDomain(CvCapture *capture);
/** @brief "black box" video file writer structure
In C++ use cv::VideoWriter
*/
typedef struct CvVideoWriter CvVideoWriter;
//! Macro to construct the fourcc code of the codec. Same as CV_FOURCC()
#define CV_FOURCC_MACRO(c1, c2, c3, c4) \
(((c1)&255) + (((c2)&255) << 8) + (((c3)&255) << 16) + (((c4)&255) << 24))
/** @brief Constructs the fourcc code of the codec function
Simply call it with 4 chars fourcc code like `CV_FOURCC('I', 'Y', 'U', 'V')`
List of codes can be obtained at [Video Codecs by
FOURCC](http://www.fourcc.org/codecs.php) page. FFMPEG backend with MP4
container natively uses other values as fourcc code: see
[ObjectType](http://www.mp4ra.org/codecs.html).
*/
CV_INLINE int CV_FOURCC(char c1, char c2, char c3, char c4) {
return CV_FOURCC_MACRO(c1, c2, c3, c4);
}
//! (Windows only) Open Codec Selection Dialog
#define CV_FOURCC_PROMPT -1
//! (Linux only) Use default codec for specified filename
#define CV_FOURCC_DEFAULT CV_FOURCC('I', 'Y', 'U', 'V')
/** @brief initialize video file writer
*/
CVAPI(CvVideoWriter *)
cvCreateVideoWriter(const char *filename, int fourcc, double fps,
CvSize frame_size, int is_color CV_DEFAULT(1));
/** @brief write frame to video file
*/
CVAPI(int) cvWriteFrame(CvVideoWriter *writer, const IplImage *image);
/** @brief close video file writer
*/
CVAPI(void) cvReleaseVideoWriter(CvVideoWriter **writer);
// ***************************************************************************************
//! @name Obsolete functions/synonyms
//! @{
#define cvCaptureFromCAM \
cvCreateCameraCapture //!< @deprecated use cvCreateCameraCapture() instead
#define cvCaptureFromFile \
cvCreateFileCapture //!< @deprecated use cvCreateFileCapture() instead
#define cvCaptureFromAVI \
cvCaptureFromFile //!< @deprecated use cvCreateFileCapture() instead
#define cvCreateAVIWriter \
cvCreateVideoWriter //!< @deprecated use cvCreateVideoWriter() instead
#define cvWriteToAVI cvWriteFrame //!< @deprecated use cvWriteFrame() instead
//! @} Obsolete...
//! @} videoio_c
#ifdef __cplusplus
}
#endif
#endif // OPENCV_VIDEOIO_H
| 44.687243 | 90 | 0.716671 | [
"object",
"model"
] |
88a3e54c82a13e364eef8e586e377ab10302e590 | 11,439 | h | C | secp256k1-sys/depend/secp256k1/include/secp256k1_extrakeys.h | rishflab/rust-secp256k1 | c534b54e118560fdb10ec2fa796ed3b3140a2dfc | [
"CC0-1.0"
] | 19 | 2015-04-12T08:38:08.000Z | 2018-03-04T01:12:59.000Z | secp256k1-sys/depend/secp256k1/include/secp256k1_extrakeys.h | rishflab/rust-secp256k1 | c534b54e118560fdb10ec2fa796ed3b3140a2dfc | [
"CC0-1.0"
] | 17 | 2015-07-28T16:05:45.000Z | 2017-12-22T09:56:01.000Z | secp256k1-sys/depend/secp256k1/include/secp256k1_extrakeys.h | rishflab/rust-secp256k1 | c534b54e118560fdb10ec2fa796ed3b3140a2dfc | [
"CC0-1.0"
] | 20 | 2015-10-11T04:30:53.000Z | 2018-03-04T01:13:04.000Z | #ifndef SECP256K1_EXTRAKEYS_H
#define SECP256K1_EXTRAKEYS_H
#include "secp256k1.h"
#ifdef __cplusplus
extern "C" {
#endif
/** Opaque data structure that holds a parsed and valid "x-only" public key.
* An x-only pubkey encodes a point whose Y coordinate is even. It is
* serialized using only its X coordinate (32 bytes). See BIP-340 for more
* information about x-only pubkeys.
*
* The exact representation of data inside is implementation defined and not
* guaranteed to be portable between different platforms or versions. It is
* however guaranteed to be 64 bytes in size, and can be safely copied/moved.
* If you need to convert to a format suitable for storage, transmission, or
* comparison, use rustsecp256k1_v0_3_1_xonly_pubkey_serialize and
* rustsecp256k1_v0_3_1_xonly_pubkey_parse.
*/
typedef struct {
unsigned char data[64];
} rustsecp256k1_v0_3_1_xonly_pubkey;
/** Opaque data structure that holds a keypair consisting of a secret and a
* public key.
*
* The exact representation of data inside is implementation defined and not
* guaranteed to be portable between different platforms or versions. It is
* however guaranteed to be 96 bytes in size, and can be safely copied/moved.
*/
typedef struct {
unsigned char data[96];
} rustsecp256k1_v0_3_1_keypair;
/** Parse a 32-byte sequence into a xonly_pubkey object.
*
* Returns: 1 if the public key was fully valid.
* 0 if the public key could not be parsed or is invalid.
*
* Args: ctx: a secp256k1 context object (cannot be NULL).
* Out: pubkey: pointer to a pubkey object. If 1 is returned, it is set to a
* parsed version of input. If not, it's set to an invalid value.
* (cannot be NULL).
* In: input32: pointer to a serialized xonly_pubkey (cannot be NULL)
*/
SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int rustsecp256k1_v0_3_1_xonly_pubkey_parse(
const rustsecp256k1_v0_3_1_context* ctx,
rustsecp256k1_v0_3_1_xonly_pubkey* pubkey,
const unsigned char *input32
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3);
/** Serialize an xonly_pubkey object into a 32-byte sequence.
*
* Returns: 1 always.
*
* Args: ctx: a secp256k1 context object (cannot be NULL).
* Out: output32: a pointer to a 32-byte array to place the serialized key in
* (cannot be NULL).
* In: pubkey: a pointer to a rustsecp256k1_v0_3_1_xonly_pubkey containing an
* initialized public key (cannot be NULL).
*/
SECP256K1_API int rustsecp256k1_v0_3_1_xonly_pubkey_serialize(
const rustsecp256k1_v0_3_1_context* ctx,
unsigned char *output32,
const rustsecp256k1_v0_3_1_xonly_pubkey* pubkey
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3);
/** Converts a rustsecp256k1_v0_3_1_pubkey into a rustsecp256k1_v0_3_1_xonly_pubkey.
*
* Returns: 1 if the public key was successfully converted
* 0 otherwise
*
* Args: ctx: pointer to a context object (cannot be NULL)
* Out: xonly_pubkey: pointer to an x-only public key object for placing the
* converted public key (cannot be NULL)
* pk_parity: pointer to an integer that will be set to 1 if the point
* encoded by xonly_pubkey is the negation of the pubkey and
* set to 0 otherwise. (can be NULL)
* In: pubkey: pointer to a public key that is converted (cannot be NULL)
*/
SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int rustsecp256k1_v0_3_1_xonly_pubkey_from_pubkey(
const rustsecp256k1_v0_3_1_context* ctx,
rustsecp256k1_v0_3_1_xonly_pubkey *xonly_pubkey,
int *pk_parity,
const rustsecp256k1_v0_3_1_pubkey *pubkey
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(4);
/** Tweak an x-only public key by adding the generator multiplied with tweak32
* to it.
*
* Note that the resulting point can not in general be represented by an x-only
* pubkey because it may have an odd Y coordinate. Instead, the output_pubkey
* is a normal rustsecp256k1_v0_3_1_pubkey.
*
* Returns: 0 if the arguments are invalid or the resulting public key would be
* invalid (only when the tweak is the negation of the corresponding
* secret key). 1 otherwise.
*
* Args: ctx: pointer to a context object initialized for verification
* (cannot be NULL)
* Out: output_pubkey: pointer to a public key to store the result. Will be set
* to an invalid value if this function returns 0 (cannot
* be NULL)
* In: internal_pubkey: pointer to an x-only pubkey to apply the tweak to.
* (cannot be NULL).
* tweak32: pointer to a 32-byte tweak. If the tweak is invalid
* according to rustsecp256k1_v0_3_1_ec_seckey_verify, this function
* returns 0. For uniformly random 32-byte arrays the
* chance of being invalid is negligible (around 1 in
* 2^128) (cannot be NULL).
*/
SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int rustsecp256k1_v0_3_1_xonly_pubkey_tweak_add(
const rustsecp256k1_v0_3_1_context* ctx,
rustsecp256k1_v0_3_1_pubkey *output_pubkey,
const rustsecp256k1_v0_3_1_xonly_pubkey *internal_pubkey,
const unsigned char *tweak32
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4);
/** Checks that a tweaked pubkey is the result of calling
* rustsecp256k1_v0_3_1_xonly_pubkey_tweak_add with internal_pubkey and tweak32.
*
* The tweaked pubkey is represented by its 32-byte x-only serialization and
* its pk_parity, which can both be obtained by converting the result of
* tweak_add to a rustsecp256k1_v0_3_1_xonly_pubkey.
*
* Note that this alone does _not_ verify that the tweaked pubkey is a
* commitment. If the tweak is not chosen in a specific way, the tweaked pubkey
* can easily be the result of a different internal_pubkey and tweak.
*
* Returns: 0 if the arguments are invalid or the tweaked pubkey is not the
* result of tweaking the internal_pubkey with tweak32. 1 otherwise.
* Args: ctx: pointer to a context object initialized for verification
* (cannot be NULL)
* In: tweaked_pubkey32: pointer to a serialized xonly_pubkey (cannot be NULL)
* tweaked_pk_parity: the parity of the tweaked pubkey (whose serialization
* is passed in as tweaked_pubkey32). This must match the
* pk_parity value that is returned when calling
* rustsecp256k1_v0_3_1_xonly_pubkey with the tweaked pubkey, or
* this function will fail.
* internal_pubkey: pointer to an x-only public key object to apply the
* tweak to (cannot be NULL)
* tweak32: pointer to a 32-byte tweak (cannot be NULL)
*/
SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int rustsecp256k1_v0_3_1_xonly_pubkey_tweak_add_check(
const rustsecp256k1_v0_3_1_context* ctx,
const unsigned char *tweaked_pubkey32,
int tweaked_pk_parity,
const rustsecp256k1_v0_3_1_xonly_pubkey *internal_pubkey,
const unsigned char *tweak32
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(4) SECP256K1_ARG_NONNULL(5);
/** Compute the keypair for a secret key.
*
* Returns: 1: secret was valid, keypair is ready to use
* 0: secret was invalid, try again with a different secret
* Args: ctx: pointer to a context object, initialized for signing (cannot be NULL)
* Out: keypair: pointer to the created keypair (cannot be NULL)
* In: seckey: pointer to a 32-byte secret key (cannot be NULL)
*/
SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int rustsecp256k1_v0_3_1_keypair_create(
const rustsecp256k1_v0_3_1_context* ctx,
rustsecp256k1_v0_3_1_keypair *keypair,
const unsigned char *seckey
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3);
/** Get the public key from a keypair.
*
* Returns: 0 if the arguments are invalid. 1 otherwise.
* Args: ctx: pointer to a context object (cannot be NULL)
* Out: pubkey: pointer to a pubkey object. If 1 is returned, it is set to
* the keypair public key. If not, it's set to an invalid value.
* (cannot be NULL)
* In: keypair: pointer to a keypair (cannot be NULL)
*/
SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int rustsecp256k1_v0_3_1_keypair_pub(
const rustsecp256k1_v0_3_1_context* ctx,
rustsecp256k1_v0_3_1_pubkey *pubkey,
const rustsecp256k1_v0_3_1_keypair *keypair
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3);
/** Get the x-only public key from a keypair.
*
* This is the same as calling rustsecp256k1_v0_3_1_keypair_pub and then
* rustsecp256k1_v0_3_1_xonly_pubkey_from_pubkey.
*
* Returns: 0 if the arguments are invalid. 1 otherwise.
* Args: ctx: pointer to a context object (cannot be NULL)
* Out: pubkey: pointer to an xonly_pubkey object. If 1 is returned, it is set
* to the keypair public key after converting it to an
* xonly_pubkey. If not, it's set to an invalid value (cannot be
* NULL).
* pk_parity: pointer to an integer that will be set to the pk_parity
* argument of rustsecp256k1_v0_3_1_xonly_pubkey_from_pubkey (can be NULL).
* In: keypair: pointer to a keypair (cannot be NULL)
*/
SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int rustsecp256k1_v0_3_1_keypair_xonly_pub(
const rustsecp256k1_v0_3_1_context* ctx,
rustsecp256k1_v0_3_1_xonly_pubkey *pubkey,
int *pk_parity,
const rustsecp256k1_v0_3_1_keypair *keypair
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(4);
/** Tweak a keypair by adding tweak32 to the secret key and updating the public
* key accordingly.
*
* Calling this function and then rustsecp256k1_v0_3_1_keypair_pub results in the same
* public key as calling rustsecp256k1_v0_3_1_keypair_xonly_pub and then
* rustsecp256k1_v0_3_1_xonly_pubkey_tweak_add.
*
* Returns: 0 if the arguments are invalid or the resulting keypair would be
* invalid (only when the tweak is the negation of the keypair's
* secret key). 1 otherwise.
*
* Args: ctx: pointer to a context object initialized for verification
* (cannot be NULL)
* In/Out: keypair: pointer to a keypair to apply the tweak to. Will be set to
* an invalid value if this function returns 0 (cannot be
* NULL).
* In: tweak32: pointer to a 32-byte tweak. If the tweak is invalid according
* to rustsecp256k1_v0_3_1_ec_seckey_verify, this function returns 0. For
* uniformly random 32-byte arrays the chance of being invalid
* is negligible (around 1 in 2^128) (cannot be NULL).
*/
SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int rustsecp256k1_v0_3_1_keypair_xonly_tweak_add(
const rustsecp256k1_v0_3_1_context* ctx,
rustsecp256k1_v0_3_1_keypair *keypair,
const unsigned char *tweak32
) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3);
#ifdef __cplusplus
}
#endif
#endif /* SECP256K1_EXTRAKEYS_H */
| 48.265823 | 102 | 0.717108 | [
"object"
] |
88a5182c1d23ae32b3e4436d286a3211138732c6 | 9,281 | c | C | test/cpuid/main.c | jcsora/occlum | fd950132ceb6103f06d3bcf7b0339b95cfaf3bb0 | [
"BSD-3-Clause-Clear"
] | 37 | 2019-02-20T13:19:36.000Z | 2019-06-30T05:43:27.000Z | test/cpuid/main.c | jcsora/occlum | fd950132ceb6103f06d3bcf7b0339b95cfaf3bb0 | [
"BSD-3-Clause-Clear"
] | 53 | 2019-02-20T12:57:53.000Z | 2019-07-01T06:58:24.000Z | test/cpuid/main.c | jcsora/occlum | fd950132ceb6103f06d3bcf7b0339b95cfaf3bb0 | [
"BSD-3-Clause-Clear"
] | 13 | 2019-02-20T11:50:40.000Z | 2019-06-19T02:21:01.000Z | #include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "test.h"
// ============================================================================
// Helper struct & functions for cpuid
// ============================================================================
typedef struct t_cpuid {
unsigned int eax;
unsigned int ebx;
unsigned int ecx;
unsigned int edx;
} t_cpuid_t;
static inline void native_cpuid(int leaf, int subleaf, t_cpuid_t *p) {
memset(p, 0, sizeof(*p));
/* ecx is often an input as well as an output. */
asm volatile("cpuid"
: "=a" (p->eax),
"=b" (p->ebx),
"=c" (p->ecx),
"=d" (p->edx)
: "a" (leaf), "c" (subleaf));
}
static bool is_cpuidinfo_equal(int leaf, t_cpuid_t *cpu, t_cpuid_t *cpu_sgx) {
/* Leaf 01H CPUID.EBX is related with logical processor. */
if (leaf == 1) {
return ((cpu->eax == cpu_sgx->eax) &&
(cpu->ecx == cpu_sgx->ecx) &&
(cpu->edx == cpu_sgx->edx));
}
/* Leaf 0BH and 06H CPUID.EDX is related with logical processor. */
if (leaf == 0xB || leaf == 0x6) {
return ((cpu->eax == cpu_sgx->eax) &&
(cpu->ebx == cpu_sgx->ebx) &&
(cpu->ecx == cpu_sgx->ecx));
}
/* Leaf 0x8000001E is for threads/core_id/apic_ids/socket_id */
if (leaf == 0x8000001E) {
return cpu->edx == cpu_sgx->edx;
}
return ((cpu->eax == cpu_sgx->eax) &&
(cpu->ebx == cpu_sgx->ebx) &&
(cpu->ecx == cpu_sgx->ecx) &&
(cpu->edx == cpu_sgx->edx));
}
static int g_max_basic_leaf = 0;
static int g_max_extend_leaf = 0;
static bool g_sgx_supported = true;
#define SGX_LEAF 0x12
#define CPUID_FEATURE_FLAGS 0x7
#define SGX_FEATURE_SHIFT 2
#define SGX1_SHIFT 0
static bool is_sgx_supported(void) {
t_cpuid_t cpu;
// check sgx feature supported
native_cpuid(CPUID_FEATURE_FLAGS, 0, &cpu);
if (!(cpu.ebx & (1 << SGX_FEATURE_SHIFT))) {
return false;
}
// check sgx1 supported
native_cpuid(SGX_LEAF, 0, &cpu);
if (!(cpu.eax & (1 << SGX1_SHIFT))) {
return false;
}
return true;
}
#define SKIP_IF_SGX_NOT_SUPPORTED() do { \
if (!g_sgx_supported) { \
printf("Warning: SGX is not supported. Skip %s\n", __func__); \
return 0; \
} \
} while (0)
// ============================================================================
// Test cases for cpuid
// ============================================================================
static int test_cpuid_with_basic_leaf_zero() {
t_cpuid_t cpu;
int leaf = 0;
int subleaf = 0;
native_cpuid(leaf, subleaf, &cpu);
// check if max basic leaf is valid
if (cpu.eax < 0 || cpu.eax >= 0xFF) {
THROW_ERROR("max basic leaf is invalid");
}
g_max_basic_leaf = cpu.eax;
return 0;
}
static int test_cpuid_with_basic_leaf_zero_with_subleaf() {
t_cpuid_t cpu;
int leaf = 0;
int subleaf = 256;
native_cpuid(leaf, subleaf, &cpu);
if (cpu.eax != g_max_basic_leaf) {
THROW_ERROR("failed to call cpuid with eax=0 and subleaf");
}
return 0;
}
static int test_cpuid_with_extend_leaf_zero() {
t_cpuid_t cpu;
int leaf = 0x80000000;
int subleaf = 0;
native_cpuid(leaf, subleaf, &cpu);
if (cpu.eax < 0x80000000) {
THROW_ERROR("failed to call cpuid with eax=0x80000000");
}
g_max_extend_leaf = cpu.eax;
return 0;
}
static int test_cpuid_with_extend_leaf_zero_with_subleaf() {
t_cpuid_t cpu;
int leaf = 0x80000000;
int subleaf = 256;
native_cpuid(leaf, subleaf, &cpu);
if (cpu.eax != g_max_extend_leaf) {
THROW_ERROR("failed to call cpuid with eax=0x80000000");
}
return 0;
}
static int test_cpuid_with_basic_leaf_one() {
t_cpuid_t cpu;
int leaf = 0x1;
int subleaf = 0;
native_cpuid(leaf, subleaf, &cpu);
printf("Stepping %d\n", cpu.eax & 0xF); // Bit 3-0
printf("Model %d\n", (cpu.eax >> 4) & 0xF); // Bit 7-4
printf("Family %d\n", (cpu.eax >> 8) & 0xF); // Bit 11-8
printf("Processor Type %d\n", (cpu.eax >> 12) & 0x3); // Bit 13-12
printf("Extended Model %d\n", (cpu.eax >> 16) & 0xF); // Bit 19-16
printf("Extended Family %d\n", (cpu.eax >> 20) & 0xFF); // Bit 27-20
if (cpu.eax == 0) {
THROW_ERROR("faild to call cpuid with eax=1");
}
return 0;
}
static int test_cpuid_with_sgx_verify() {
t_cpuid_t cpu;
int leaf = CPUID_FEATURE_FLAGS;
int subleaf = 0;
SKIP_IF_SGX_NOT_SUPPORTED();
native_cpuid(leaf, subleaf, &cpu);
//CPUID.(EAX=07H, ECX=0H):EBX.SGX = 1,
// Bit 02: SGX. Supports Intel® Software Guard Extensions (Intel® SGX Extensions) if 1.
if (((cpu.ebx >> 2) & 0x1) != 1) {
THROW_ERROR("failed to call cpuid to verify sgx");
}
return 0;
}
static int test_cpuid_with_sgx_enumeration() {
t_cpuid_t cpu;
int leaf = SGX_LEAF;
int subleaf = 0;
SKIP_IF_SGX_NOT_SUPPORTED();
native_cpuid(leaf, subleaf, &cpu);
printf("Sgx 1 supported: %d\n", cpu.eax & 0x1);
printf("Sgx 2 supported: %d\n", (cpu.eax >> 1) & 0x1);
if (((cpu.eax & 0x1) | ((cpu.eax >> 1) & 0x1)) == 0) {
THROW_ERROR("failed to call cpuid to get SGX Capbilities");
}
if (((cpu.edx & 0xFF) | ((cpu.edx >> 8) & 0xFF)) == 0) {
THROW_ERROR("get MaxEnclaveSize failed");
}
leaf = SGX_LEAF;
subleaf = 1;
native_cpuid(leaf, subleaf, &cpu);
if ((cpu.eax | cpu.ebx | cpu.ecx | cpu.edx) == 0) {
THROW_ERROR("failed to call cpuid to get SGX Attributes");
}
return 0;
}
static int test_cpuid_with_invalid_leaf() {
t_cpuid_t cpu;
int leaf[] = {0x8, 0xC, 0xE, 0x11};
int subleaf = 0;
for (int i = 0; i < sizeof(leaf) / sizeof(leaf[0]); i++) {
if (leaf[i] > g_max_basic_leaf) {
printf("Warning: test leaf 0x%x is greater than CPU max basic leaf. Skipped.\n", leaf[i]);
continue;
}
native_cpuid(leaf[i], subleaf, &cpu);
if (cpu.eax | cpu.ebx | cpu.ecx | cpu.edx) {
THROW_ERROR("faild to call cpuid with invalid leaf 0x%x", leaf[i]);
}
}
return 0;
}
static int test_cpuid_with_oversized_leaf() {
t_cpuid_t cpu;
int leaf = g_max_extend_leaf + 1;
int subleaf = 1;
native_cpuid(leaf, subleaf, &cpu);
t_cpuid_t cpu_max;
leaf = g_max_basic_leaf + 1;
subleaf = 1;
native_cpuid(leaf, subleaf, &cpu_max);
if ((cpu.eax != cpu_max.eax) || (cpu.ebx != cpu_max.ebx) ||
(cpu.ecx != cpu_max.ecx) || (cpu.edx != cpu_max.edx)) {
THROW_ERROR("failed to call cpuid with oversize leaf");
}
return 0;
}
static int test_cpuid_with_random_leaf() {
t_cpuid_t cpu;
srand((int)time(NULL));
int leaf = 0;
int subleaf = 0;
for (int i = 0; i < 5; i++) {
leaf = rand();
subleaf = rand();
native_cpuid(leaf, subleaf, &cpu);
printf("random leaf:%x, subleaf:%x \n", leaf, subleaf);
printf("eax: %x ebx: %x ecx: %x edx: %x\n", cpu.eax, cpu.ebx, cpu.ecx, cpu.edx);
}
return 0;
}
#define BUFF_SIZE (1024)
static int test_cpuid_with_host_cpuidinfo() {
char buff[BUFF_SIZE] = {0};
FILE *fp = fopen("./test_cpuid.txt", "r");
if (fp == NULL) {
THROW_ERROR("failed to open host cpuid.txt");
}
while (fgets(buff, BUFF_SIZE, fp)) {
uint32_t leaf = 0;
uint32_t subleaf = 0;
t_cpuid_t cpu = {0};
int num = sscanf(buff, " %x %x: eax=%x ebx=%x ecx=%x edx=%x", &leaf, &subleaf,
&cpu.eax, &cpu.ebx, &cpu.ecx, &cpu.edx);
if (num != 6) {
continue;
}
t_cpuid_t cpu_sgx = {0};
native_cpuid(leaf, subleaf, &cpu_sgx);
if (!is_cpuidinfo_equal(leaf, &cpu, &cpu_sgx)) {
printf("leaf:0x%x subleaf:0x%x\n", leaf, subleaf);
printf("ori_eax:0x%x ori_ebx:0x%x ori_ecx:0x%x ori_edx:0x%x\n",
cpu.eax, cpu.ebx, cpu.ecx, cpu.edx);
printf("sgx_eax:0x%x sgx_ebx:0x%x sgx_ecx:0x%x sgx_edx:0x%x\n",
cpu_sgx.eax, cpu_sgx.ebx, cpu_sgx.ecx, cpu_sgx.edx);
THROW_ERROR("failed to check cpuid info");
}
}
fclose(fp);
return 0;
}
// ============================================================================
// Test suite main
// ============================================================================
static test_case_t test_cases[] = {
TEST_CASE(test_cpuid_with_basic_leaf_zero),
TEST_CASE(test_cpuid_with_basic_leaf_zero_with_subleaf),
TEST_CASE(test_cpuid_with_extend_leaf_zero),
TEST_CASE(test_cpuid_with_extend_leaf_zero_with_subleaf),
TEST_CASE(test_cpuid_with_basic_leaf_one),
TEST_CASE(test_cpuid_with_sgx_verify),
TEST_CASE(test_cpuid_with_sgx_enumeration),
TEST_CASE(test_cpuid_with_invalid_leaf),
TEST_CASE(test_cpuid_with_oversized_leaf),
TEST_CASE(test_cpuid_with_random_leaf),
TEST_CASE(test_cpuid_with_host_cpuidinfo),
};
int main() {
g_sgx_supported = is_sgx_supported();
return test_suite_run(test_cases, ARRAY_SIZE(test_cases));
}
| 30.035599 | 102 | 0.564594 | [
"model"
] |
88b01c026dbf8d3751ccbb3300347bc5fb1e47ae | 478 | h | C | decompiler/analysis/expression_build.h | 0x715C/jak-project | 490633d434fbb09b938d4a064a32b4bea14e7d80 | [
"0BSD"
] | null | null | null | decompiler/analysis/expression_build.h | 0x715C/jak-project | 490633d434fbb09b938d4a064a32b4bea14e7d80 | [
"0BSD"
] | 15 | 2020-09-08T23:20:56.000Z | 2022-03-29T00:36:47.000Z | decompiler/analysis/expression_build.h | 0x715C/jak-project | 490633d434fbb09b938d4a064a32b4bea14e7d80 | [
"0BSD"
] | null | null | null | #pragma once
#include <unordered_map>
#include <vector>
#include <string>
namespace decompiler {
class Form;
class Function;
class FormPool;
class DecompilerTypeSystem;
struct LocalVarOverride;
bool convert_to_expressions(
Form* top_level_form,
FormPool& pool,
Function& f,
const std::vector<std::string>& arg_names,
const std::unordered_map<std::string, LocalVarOverride>& var_override_map,
const DecompilerTypeSystem& dts);
} // namespace decompiler | 23.9 | 78 | 0.759414 | [
"vector"
] |
88b7487fde300ed8aac8d26e7f8396cea5fed336 | 1,854 | h | C | rts-c/parser.h | mtullsen/daedalus | e06f06e755522e6df8708ae02857808f2e5b3981 | [
"BSD-3-Clause"
] | null | null | null | rts-c/parser.h | mtullsen/daedalus | e06f06e755522e6df8708ae02857808f2e5b3981 | [
"BSD-3-Clause"
] | null | null | null | rts-c/parser.h | mtullsen/daedalus | e06f06e755522e6df8708ae02857808f2e5b3981 | [
"BSD-3-Clause"
] | null | null | null | #ifndef DDL_PARSER_H
#define DDL_PARSER_H
#include <cstdint>
#include <iostream>
#include <vector>
#include "input.h"
// #include "closure.h"
// #include "ddl_thread.h"
typedef size_t ThreadId;
// `T` is the type of the result for the entry-point parser.
// The methods in this class correspond to the VM instructions, c.f. Daedalus.VM
template <class T>
class Parser {
Input input;
std::vector<T> results;
// std::vector<Thread> suspended;
size_t fail_offset;
public:
Parser(Input i)
: input(i)
, fail_offset(0)
{}
void setInput(Input i) { input = i; }
// Returns a copy of the current input
Input getInput() { return input; }
// For debug
void say(const char *msg) { std::cout << msg << std::endl; }
// Called when we find a successful parse
void output(T v) { results.push_back(v); }
// Add to wainting threads
// We become the owner of the closure.
// ThreadId spawn(std::unique_ptr<Closure1<bool>> clo) {
// ThreadId id = suspended.size();
// suspended.push_back(Thread(clo));
// return id;
// }
// Assumes that there is a suspended thread.
void yield() {
// auto t = suspended.back();
// auto b = t.getNotified();
// auto c = t.getClosure();
// suspended.pop_back();
// (*c)(b);
}
// Set the "sibling failied" flag in the given thread.
// Assumes: valid id (i.e., thread has not been resumed)
// void notify(ThreadId id) { suspended[id].notify(); }
// Set the "furtherest fail" location.
// XXX: This is not quite right because, in principle, the failurs
// may be in different inputs. For the moment, we ignore this, which
// could result in confusing error locations.
void noteFail() {
size_t offset = input.getOffset();
if (offset > fail_offset) fail_offset = offset;
}
};
#endif
| 24.394737 | 80 | 0.637001 | [
"vector"
] |
88b93d620ac16db9d6a9601d2a92e4939b4312a8 | 4,235 | h | C | include/fox/FXObjectList.h | ldematte/beppe | 53369e0635d37d2dc58aa0b6317e664b3cf67547 | [
"BSD-3-Clause"
] | 1 | 2022-01-25T19:13:22.000Z | 2022-01-25T19:13:22.000Z | include/fox/FXObjectList.h | ldematte/beppe | 53369e0635d37d2dc58aa0b6317e664b3cf67547 | [
"BSD-3-Clause"
] | null | null | null | include/fox/FXObjectList.h | ldematte/beppe | 53369e0635d37d2dc58aa0b6317e664b3cf67547 | [
"BSD-3-Clause"
] | null | null | null | /********************************************************************************
* *
* O b j e c t L i s t *
* *
*********************************************************************************
* Copyright (C) 1997,2002 by Jeroen van der Zijp. All Rights Reserved. *
*********************************************************************************
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Lesser General Public *
* License as published by the Free Software Foundation; either *
* version 2.1 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public *
* License along with this library; if not, write to the Free Software *
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
*********************************************************************************
* $Id: FXObjectList.h,v 1.16 2002/01/18 22:42:54 jeroen Exp $ *
********************************************************************************/
#ifndef FXOBJECTLIST_H
#define FXOBJECTLIST_H
/// List of pointers to objects
class FXAPI FXObjectList {
protected:
FXObject **data; /// List of items
FXint num; /// Used slots
FXint max; /// Total slots
public:
/// Default constructor
FXObjectList();
/// Copy constructor
FXObjectList(const FXObjectList& orig);
/// Assignment operator
FXObjectList& operator=(const FXObjectList& orig);
/// Return number of elements
FXint no() const { return num; }
/// Set number of elements
void no(FXint n);
/// Return size of list
FXint size() const { return max; }
/// Set max number of elements
void size(FXint m);
/// Indexing operator
FXObject*& operator[](FXint i){ return data[i]; }
FXObject* const& operator[](FXint i) const { return data[i]; }
/// Access to list
FXObject*& list(FXint i){ return data[i]; }
FXObject* const& list(FXint i) const { return data[i]; }
/// Access to content array
FXObject** list() const { return data; }
/// Insert element at certain position
void insert(FXint pos,FXObject* p);
/// Prepend element
void prepend(FXObject* p);
/// Append element
void append(FXObject* p);
/// Replace element
void replace(FXint pos,FXObject* p);
/// Remove element at pos
void remove(FXint pos);
/// Remove element p
void remove(const FXObject* p);
/// Find object in list, searching forward; return position or -1
FXint findf(const FXObject *p,FXint pos=0) const;
/// Find object in list, searching backward; return position or -1
FXint findb(const FXObject *p,FXint pos=2147483647) const;
/// Remove all elements
void clear();
/// Save to a stream
void save(FXStream& store) const;
/// Load from a stream
void load(FXStream& store);
/// Destructor
virtual ~FXObjectList();
};
/// Specialize list to pointers to TYPE
template<class TYPE>
class FXObjectListOf : public FXObjectList {
public:
FXObjectListOf(){}
/// Indexing operator
TYPE*& operator[](FXint i){ return (TYPE*&)data[i]; }
TYPE *const& operator[](FXint i) const { return (TYPE*const&)data[i]; }
/// Access to list
TYPE*& list(FXint i){ return (TYPE*&)data[i]; }
TYPE *const& list(FXint i) const { return (TYPE*const&)data[i]; }
/// Access to content array
TYPE** list() const { return (TYPE**)data; }
};
#endif
| 33.88 | 81 | 0.523259 | [
"object"
] |
88bce5a90bd8ce12615e0105d1bdf337f7d7bb78 | 10,860 | h | C | MyLayout/Lib/MyLayoutPos.h | LAnqxpp/MyLinearLayout | 83f1536fece7850b290ce6bba11d7b9f3b46f151 | [
"MIT"
] | 83 | 2016-01-03T09:49:37.000Z | 2019-08-11T07:57:15.000Z | MyLayout/Lib/MyLayoutPos.h | LAnqxpp/MyLinearLayout | 83f1536fece7850b290ce6bba11d7b9f3b46f151 | [
"MIT"
] | null | null | null | MyLayout/Lib/MyLayoutPos.h | LAnqxpp/MyLinearLayout | 83f1536fece7850b290ce6bba11d7b9f3b46f151 | [
"MIT"
] | 1 | 2020-08-30T04:04:24.000Z | 2020-08-30T04:04:24.000Z | //
// MyLayoutPos.h
// MyLayout
//
// Created by oybq on 15/6/14.
// Copyright (c) 2015年 YoungSoft. All rights reserved.
//
#import "MyLayoutDef.h"
/**
*视图的布局位置类,用于定位视图在布局视图中的位置。位置可分为水平方向的位置和垂直方向的位置,在视图定位时必要同时指定水平方向的位置和垂直方向的位置。水平方向的位置可以分为左,水平居中,右三种位置,垂直方向的位置可以分为上,垂直居中,下三种位置。
其中的offset方法可以用来设置布局位置的偏移值,一般只在equalTo设置为MyLayoutPos或者NSArray时配合使用。比如A.leftPos.equalTo(B.rightPos).offset(5)表示A在B的右边再偏移5个点
其中的min,max表示用来设置布局位置的最大最小值。比如A.leftPos.min(10).max(40)表示左边边界值最小是10最大是40。最大最小值一般和线性布局和框架布局中的子视图的位置设置为相对间距的情况下搭配着用。
下面的表格描述了各种布局下的子视图的布局位置对象的equalTo方法可以设置的值。
为了表示方便我们把:线性布局简写为L、相对布局简写为R、表格布局简写为T、框架布局简写为FR、流式布局简写为FL、浮动布局简写为FO、全部简写为ALL,不支持为-
+-----------+--------+---------------------+-------+------+--------+---------+----------+----------+---------------+------+
|method\val |NSNumber|NSArray<MyLayoutPos*>|leftPos|topPos|rightPos|bottomPos|centerXPos|centerYPos|UILayoutSupport|UIView|
+-----------+--------+---------------------+-------+------+--------+---------+----------+----------+---------------+------+
| topPos | ALL | - | - | R | - | R | - | R | L/R/FR/FO/FL |ALL |
+-----------+--------+---------------------+-------+------+--------+---------+----------+----------+---------------+------+
|leftPos | ALL | - | R | - | R | - | R | - | - |ALL |
+-----------+--------+---------------------+-------+------+--------+---------+----------+----------+---------------+------+
|bottomPos | ALL | - | - | R | - | R | - | R | L/R/FR/FO/FL |ALL |
+-----------+--------+---------------------+-------+------+--------+---------+----------+----------+---------------+------+
|rightPos | ALL | - | R | - | R | - | R | - | - |ALL |
+-----------+--------+---------------------+-------+------+--------+---------+----------+----------+---------------+------+
|centerXPos | ALL | R | R | - | R | - | R | - | - |ALL |
+-----------+--------+---------------------+-------+------+--------+---------+----------+----------+---------------+------+
|centerYPos | ALL | R | - | R | - | R | - | R | - |ALL |
+-----------+--------+---------------------+-------+------+--------+---------+----------+----------+---------------+------+
上表中所有布局下的子视图的布局位置都支持设置为数值,而数值对于线性布局,表格布局,框架布局这三种布局来说当设置的结果>0且<1时表示的是相对的边界值
比如一个框架布局的宽度是100,而其中的一个子视图的leftPos.equalTo(@0.1)则表示这个子视图左边距离框架布局的左边的宽度是100*0.1
*/
/*
The MyLayoutPos is the layout position object of the UIView. It is used to set the position relationship at the six directions of left, top, right, bottom, horizontal center, vertical center between the view and sibling views or Layoutview.
you can use the equalTo() method of MyLayoutPos to set as below:
1.NSNumber: the layout position is equal to a number. e.g. leftPos.equalTo (@100) indicates that the value of the left boundary is 100.
2.MyLayoutPos: the layout position depends on aother layout position. e.g. A.leftPos.equalTo(B.rightPos) indicates that A is on the right side of B.
3.NSArray<MyLayoutPos*>: all views in the array and View are centered. e.g. A.centerXPos.equalTo(@[B.centerXPos, C.centerXPos]) indicates that A,B,C are overall horizontal centered.
4.id<UILayoutSupport>: you can only set topPos equalTo UIViewController‘s topLayoutGuide or bottomPos equalTo UIViewController‘s bottomLayoutGuide, then the view will always below the nav。
5.UIView: the layout position is depends view's relevant position.
6.nil: the layout position value is clear.
you can use offset() method of MyLayoutPos to set offset of the layout position,but it is generally used together when equalTo() is set at MyLayoutPos or NSArray. e.g. A.leftPos.equalTo(B.rightPos).offset(5) indicates that A is on the right side of B and increase 5 point offset.
you can use max and min method of MyLayoutPos to limit the maximum and minimum postion value. e.g. A.leftPos.min (10).Max (40) indicates that the minimum value of the left boundary is 10 and the maximum is 40. The min and max method always be used together when the subview' position of MyLinearLayout or MyFrameLayout is set at the relative position(0,1].
The above table describes the value the equalTo method can be set by the of the layout location object of the subview in MyLayout.
For convenience we set MyLinearLayout abbreviated as L, MyRelativeLayout abbreviated as R, MyTableLayout abbreviated as T, MyFrameLayout abbreviated as FR, MyFlowLayout abbreviated as FL, MyFloatLayout abbreviated as FO, not support set to - support all set to ALL.
*/
/**
视图的布局位置类是用来描述视图与其他视图之间的位置关系的类。视图在进行定位时需要明确的指出其在父视图坐标轴上的水平位置(x轴上的位置)和垂直位置(y轴上的位置)。
视图的水平位置可以用左、水平中、右三个方位的值来描述,垂直位置则可以用上、垂直中、下三个方位的值来描述。
也就是说一个视图的位置需要用水平的某个方位的值以及垂直的某个方位的值来确定。一个位置的值可以是一个具体的数值,也可以依赖于另外一个视图的位置来确定。
@code
一个布局位置对象的最终位置值 = min(max(posVal + offsetVal, lBound.posVal+lBound.offsetVal), uBound.posVal+uBound.offsetVal)
其中:
posVal是通过equalTo方法设置。
offsetVal是通过offset方法设置。
lBound.posVal,lBound.offsetVal是通过lBound方法设置。
uBound.posVal,uBound.offsetVal是通过uBound方法设置。
@endcode
*/
@interface MyLayoutPos : NSObject<NSCopying>
#if UIKIT_DEFINE_AS_PROPERTIES
/**
特殊的位置。只用在布局视图和非布局父视图之间的位置约束和没有导航条时的布局视图内子视图的padding设置上。
iOS11以后提出了安全区域的概念,因此对于iOS11以下的版本就需要兼容处理,尤其是在那些没有导航条的情况下。通过将布局视图的边距设置为这个特殊值就可以实现在任何版本中都能完美的实现位置的偏移而且各版本保持统一。比如下面的例子:
@code
//这里设置布局视图的左边和右边以及顶部的边距都是在父视图的安全区域外再缩进10个点的位置。你会注意到这里面定义了一个特殊的位置MyLayoutPos.safeAreaMargin。
//MyLayoutPos.safeAreaMargin表示视图的边距不是一个固定的值而是所在的父视图的安全区域。这样布局视图就不会延伸到安全区域以外去了。
//MyLayoutPos.safeAreaMargin是同时支持iOS11和以下的版本的,对于iOS11以下的版本则顶部安全区域是状态栏以下的位置。
//因此只要你设置边距为MyLayoutPos.safeAreaMargin则可以同时兼容所有iOS的版本。。
layoutView.leadingPos.equalTo(@(MyLayoutPos.safeAreaMargin)).offset(10);
layoutView.trailingPos.equalTo(@(MyLayoutPos.safeAreaMargin)).offset(10);
layoutView.topPos.equalTo(@(MyLayoutPos.safeAreaMargin)).offset(10);
//如果你的左右边距都是安全区域,那么可以用下面的方法来简化设置。您可以注释掉这句代码看看效果。
// layoutView.myLeading = layoutView.myTrailing = MyLayoutPos.safeAreaMargin;
@endcode
@code
//在一个没有导航条的界面中,因为iPhoneX和其他设备的状态栏的高度不一致。所以你可以让布局视图的topPadding设置如下:
layoutView.topPadding = MyLayoutPos.safeAreaMargin + 10; //顶部内边距是安全区域外加10。那么这个和设置如下的:
layoutView.topPadding = CGRectGetHeight([UIApplication sharedApplication].statusBarFrame) + 10;
//这两者之间的区别后者是一个设置好的常数,一旦你的设备要支持横竖屏则不管横屏下是否有状态栏都会缩进固定的内边距,而前者则会根据当前是否状态栏而进行动态调整。
//当然如果你的顶部就是要固定缩进状态栏的高度的话那么你可以直接直接用后者。
@endcode
@note
需要注意的是这个值并不是一个真值,只是一个特殊值,不能用于读取。而且只能用于在MyLayoutPos的equalTo方法和布局视图上的padding属性上使用,其他地方使用后果未可知。
*/
@property(class, nonatomic, assign,readonly) CGFloat safeAreaMargin;
#else
+(CGFloat)safeAreaMargin;
#endif
//because masonry defined macro MAS_SHORTHAND_GLOBALS. the equalTo, offset may conflict with below method. so
//if you used MyLayout and Masonry concurrently and you defined MAS_SHORTHAND_GLOBALS in masonry, then you can define MY_USEPREFIXMETHOD to solve the conflict.
#ifdef MY_USEPREFIXMETHOD
-(MyLayoutPos* (^)(id val))myEqualTo;
-(MyLayoutPos* (^)(CGFloat val))myOffset;
-(MyLayoutPos* (^)(CGFloat val))myMin;
-(MyLayoutPos* (^)(id posVal, CGFloat offset))myLBound;
-(MyLayoutPos* (^)(CGFloat val))myMax;
-(MyLayoutPos* (^)(id posVal, CGFloat offset))myUBound;
-(void)myClear;
#else
/**
设置布局位置的值。参数val可以接收下面六种类型的值:
1. NSNumber表示位置是一个具体的数值。
对于框架布局和线性布局中的子视图来说,如果数值是一个大于0而小于1的数值时表示的是相对的间距或者边距。如果是相对边距那么真实的位置 = 布局视图尺寸*相对边距值;如果是相对间距那么真实的位置 = 布局视图剩余尺寸 * 相对间距值 /(所有相对间距值的总和)。
2. MyLayoutPos表示位置依赖于另外一个位置。
3. NSArray<MyLayoutPos*>表示位置和数组里面的其他位置整体居中。
4. id<UILayoutSupport> 对于iOS7以后视图控制器会根据导航条是否半透明而确定是占据整个屏幕。因此当topPos,bottomPos设置为视图控制器的topLayoutGuide或者bottomLayoutGuide时这样子视图就会偏移出导航条的高度,而如果没有导航条时则不会偏移出导航条的高度。注意的是这个值不能设置在非布局父视图的布局视图中。
5. UIView表示位置依赖指定视图的对应位置。
6. nil表示位置的值被清除。
*/
-(MyLayoutPos* (^)(id val))equalTo;
/**
设置布局位置值的偏移量。 所谓偏移量是指布局位置在设置了某种值后增加或减少的偏移值。
这里偏移值的正负值所表示的意义是根据位置的不同而不同的:
1.如果是leftPos和centerXPos那么正数表示往右偏移,负数表示往左偏移。
2.如果是topPos和centerYPos那么正数表示往下偏移,负数表示往上偏移。
3.如果是rightPos那么正数表示往左偏移,负数表示往右偏移。
4.如果是bottomPos那么正数表示往上偏移,负数表示往下偏移。
@code
示例代码:
1.比如:A.leftPos.equalTo(@10).offset(5)表示A视图的左边边距等于10再往右偏移5,也就是最终的左边边距是15。
2.比如:A.rightPos.equalTo(B.rightPos).offset(5)表示A视图的右边位置等于B视图的右边位置再往左偏移5。
@endcode
*/
-(MyLayoutPos* (^)(CGFloat val))offset;
/**
*设置位置的最小边界数值,min方法是lBound方法的简化版本。比如:A.min(10) <==> A.lBound(@10, 0)
*/
-(MyLayoutPos* (^)(CGFloat val))min;
/**
*设置布局位置的最小边界值。 如果位置对象没有设置最小边界值,那么最小边界默认就是无穷小-CGFLOAT_MAX。lBound方法除了能设置为NSNumber外,还可以设置为MyLayoutPos值,并且还可以指定最小位置的偏移量值。只有在相对布局中的子视图的位置对象才能设置最小边界值为MyLayoutPos类型的值,其他类型布局中的子视图只支持NSNumber类型的最小边界值。
posVal: 指定位置边界值。可设置的类型有NSNumber和MyLayoutPos类型,前者表示最小位置不能小于某个常量值,而后者表示最小位置不能小于另外一个位置对象所表示的位置值。
offsetVal: 指定位置边界值的偏移量。
1.比如某个视图A的左边位置最小不能小于30则设置为:
@code
A.leftPos.lBound(30,0); 或者A.leftPos.lBound(20,10);
@endcode
2.对于相对布局中的子视图来说可以通过lBound值来实现那些尺寸不确定但是最小边界不能低于某个关联的视图的位置的场景,比如说视图B的位置和宽度固定,而A视图的右边位置固定,但是A视图的宽度不确定,且A的最左边不能小于B视图的右边边界加20,那么A就可以设置为:
@code
A.leftPos.lBound(B.rightPos, 20); //这时A是不必要指定明确的宽度的。
@endcode
*/
-(MyLayoutPos* (^)(id posVal, CGFloat offsetVal))lBound;
/**
*设置位置的最大边界数值,max方法是uBound方法的简化版本。比如:A.max(10) <==> A.uBound(@10, 0)
*/
-(MyLayoutPos* (^)(CGFloat val))max;
/**
设置布局位置的最大边界值。 如果位置对象没有设置最大边界值,那么最大边界默认就是无穷大CGFLOAT_MAX。uBound方法除了能设置为NSNumber外,还可以设置为MyLayoutPos值,并且还可以指定最大位置的偏移量值。只有在相对布局中的子视图的位置对象才能设置最大边界值为MyLayoutPos类型的值,其他类型布局中的子视图只支持NSNumber类型的最大边界值。
1.比如某个视图A的左边位置最大不能超过30则设置为:
@code
A.leftPos.uBound(30,0); 或者A.leftPos.uBound(30,10);
@endcode
2.对于相对布局中的子视图来说可以通过uBound值来实现那些尺寸不确定但是最大边界不能超过某个关联的视图的位置的场景,比如说视图B的位置和宽度固定,而A视图的左边位置固定,但是A视图的宽度不确定,且A的最右边不能超过B视图的左边边界减20,那么A就可以设置为:
@code
A.reftPos.uBound(B.leftPos, -20); //这时A是不必要指定明确的宽度的。
@endcode
3.对于相对布局中的子视图来说可以同时通过lBound,uBound方法的设置来实现某个子视图总是在对应的两个其他的子视图中央显示且尺寸不能超过其他两个子视图边界的场景。比如说视图B要放置在A和C之间水平居中显示且不能超过A和C的边界。那么就可以设置为:
@code
B.leftPos.lBound(A.rightPos,0); B.rightPos.uBound(C.leftPos,0); //这时B不用指定宽度,而且总是在A和C的水平中间显示。
@endcode
posVal 指定位置边界值。可设置的类型有NSNumber和MyLayoutPos类型,前者表示最大位置不能大于某个常量值,而后者表示最大位置不能大于另外一个位置对象所表示的位置值。
offsetVal 指定位置边界值的偏移量。
*/
-(MyLayoutPos* (^)(id posVal, CGFloat offsetVal))uBound;
/**
*清除所有设置的约束值,这样位置对象将不会再生效了。
*/
-(void)clear;
#endif
/**
*设置布局位置是否是活动的,默认是YES表示活动的,如果设置为NO则表示这个布局位置对象设置的约束值将不会起作用。
*active设置为YES和clear的相同点是位置对象设置的约束值都不会生效了,区别是前者不会清除所有设置的约束,而后者则会清除所有设置的约束。
*/
@property(nonatomic, assign, getter=isActive) BOOL active;
//通过如下属性获取上面方法设置的值。
@property(nonatomic, strong, readonly) id posVal;
@property(nonatomic, assign, readonly) CGFloat offsetVal;
@property(nonatomic, assign, readonly) CGFloat minVal;
@property(nonatomic, assign, readonly) CGFloat maxVal;
@end
| 43.790323 | 357 | 0.688582 | [
"object"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.