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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
de59e206f127a4ee8e58123e87f7e9ea522d0cb6 | 7,423 | c | C | vendor/samsung/external/glib-2.0/gio/ginitable.c | cesarmo759/android_kernel_samsung_msm8916 | f19717ef6c984b64a75ea600a735dc937b127c25 | [
"Apache-2.0"
] | 1 | 2020-06-28T00:49:21.000Z | 2020-06-28T00:49:21.000Z | vendor/samsung/external/glib-2.0/gio/ginitable.c | cesarmo759/android_kernel_samsung_msm8916 | f19717ef6c984b64a75ea600a735dc937b127c25 | [
"Apache-2.0"
] | null | null | null | vendor/samsung/external/glib-2.0/gio/ginitable.c | cesarmo759/android_kernel_samsung_msm8916 | f19717ef6c984b64a75ea600a735dc937b127c25 | [
"Apache-2.0"
] | 1 | 2021-03-05T16:54:52.000Z | 2021-03-05T16:54:52.000Z | /* GIO - GLib Input, Output and Streaming Library
*
* Copyright (C) 2009 Red Hat, Inc.
*
* 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 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.
*
* Author: Alexander Larsson <alexl@redhat.com>
*/
#include "config.h"
#include "ginitable.h"
#include "glibintl.h"
/**
* SECTION:ginitable
* @short_description: Failable object initialization interface
* @include: gio/gio.h
* @see_also: #GAsyncInitable
*
* #GInitable is implemented by objects that can fail during
* initialization. If an object implements this interface the
* g_initable_init() function must be called as the first thing
* after construction. If g_initable_init() is not called, or if
* it returns an error, all further operations on the object
* should fail, generally with a %G_IO_ERROR_NOT_INITIALIZED error.
*
* Users of objects implementing this are not intended to use
* the interface method directly, instead it will be used automatically
* in various ways. For C applications you generally just call
* g_initable_new() directly, or indirectly via a foo_thing_new() wrapper.
* This will call g_initable_init() under the cover, returning %NULL and
* setting a %GError on failure.
*
* For bindings in languages where the native constructor supports
* exceptions the binding could check for objects implemention %GInitable
* during normal construction and automatically initialize them, throwing
* an exception on failure.
*/
typedef GInitableIface GInitableInterface;
G_DEFINE_INTERFACE (GInitable, g_initable, G_TYPE_OBJECT)
static void
g_initable_default_init (GInitableInterface *iface)
{
}
/**
* g_initable_init:
* @initable: a #GInitable.
* @cancellable: optional #GCancellable object, %NULL to ignore.
* @error: a #GError location to store the error occuring, or %NULL to
* ignore.
*
* Initializes the object implementing the interface. This must be
* done before any real use of the object after initial construction.
*
* Implementations may also support cancellation. If @cancellable is not %NULL,
* then initialization can be cancelled by triggering the cancellable object
* from another thread. If the operation was cancelled, the error
* %G_IO_ERROR_CANCELLED will be returned. If @cancellable is not %NULL and
* the object doesn't support cancellable initialization the error
* %G_IO_ERROR_NOT_SUPPORTED will be returned.
*
* If this function is not called, or returns with an error then all
* operations on the object should fail, generally returning the
* error %G_IO_ERROR_NOT_INITIALIZED.
*
* Implementations of this method must be idempotent, i.e. multiple calls
* to this function with the same argument should return the same results.
* Only the first call initializes the object, further calls return the result
* of the first call. This is so that its safe to implement the singleton
* pattern in the GObject constructor function.
*
* Returns: %TRUE if successful. If an error has occurred, this function will
* return %FALSE and set @error appropriately if present.
*
* Since: 2.22
*/
gboolean
g_initable_init (GInitable *initable,
GCancellable *cancellable,
GError **error)
{
GInitableIface *iface;
g_return_val_if_fail (G_IS_INITABLE (initable), FALSE);
iface = G_INITABLE_GET_IFACE (initable);
return (* iface->init) (initable, cancellable, error);
}
/**
* g_initable_new:
* @object_type: a #GType supporting #GInitable.
* @cancellable: optional #GCancellable object, %NULL to ignore.
* @error: a #GError location to store the error occuring, or %NULL to
* ignore.
* @first_property_name: the name of the first property, or %NULL if no
* properties
* @...: the value if the first property, followed by and other property
* value pairs, and ended by %NULL.
*
* Helper function for constructing #GInitiable object. This is
* similar to g_object_new() but also initializes the object
* and returns %NULL, setting an error on failure.
*
* Return value: a newly allocated #GObject, or %NULL on error
*
* Since: 2.22
*/
gpointer
g_initable_new (GType object_type,
GCancellable *cancellable,
GError **error,
const gchar *first_property_name,
...)
{
GObject *object;
va_list var_args;
va_start (var_args, first_property_name);
object = g_initable_new_valist (object_type,
first_property_name, var_args,
cancellable, error);
va_end (var_args);
return object;
}
/**
* g_initable_newv:
* @object_type: a #GType supporting #GInitable.
* @n_parameters: the number of parameters in @parameters
* @parameters: the parameters to use to construct the object
* @cancellable: optional #GCancellable object, %NULL to ignore.
* @error: a #GError location to store the error occuring, or %NULL to
* ignore.
*
* Helper function for constructing #GInitiable object. This is
* similar to g_object_newv() but also initializes the object
* and returns %NULL, setting an error on failure.
*
* Return value: a newly allocated #GObject, or %NULL on error
*
* Since: 2.22
*/
gpointer
g_initable_newv (GType object_type,
guint n_parameters,
GParameter *parameters,
GCancellable *cancellable,
GError **error)
{
GObject *obj;
g_return_val_if_fail (G_TYPE_IS_INITABLE (object_type), NULL);
obj = g_object_newv (object_type, n_parameters, parameters);
if (!g_initable_init (G_INITABLE (obj), cancellable, error))
{
g_object_unref (obj);
return NULL;
}
return (gpointer)obj;
}
/**
* g_initable_new_valist:
* @object_type: a #GType supporting #GInitable.
* @first_property_name: the name of the first property, followed by
* the value, and other property value pairs, and ended by %NULL.
* @var_args: The var args list generated from @first_property_name.
* @cancellable: optional #GCancellable object, %NULL to ignore.
* @error: a #GError location to store the error occuring, or %NULL to
* ignore.
*
* Helper function for constructing #GInitiable object. This is
* similar to g_object_new_valist() but also initializes the object
* and returns %NULL, setting an error on failure.
*
* Return value: a newly allocated #GObject, or %NULL on error
*
* Since: 2.22
*/
GObject*
g_initable_new_valist (GType object_type,
const gchar *first_property_name,
va_list var_args,
GCancellable *cancellable,
GError **error)
{
GObject *obj;
g_return_val_if_fail (G_TYPE_IS_INITABLE (object_type), NULL);
obj = g_object_new_valist (object_type,
first_property_name,
var_args);
if (!g_initable_init (G_INITABLE (obj), cancellable, error))
{
g_object_unref (obj);
return NULL;
}
return obj;
}
| 32.845133 | 79 | 0.727738 | [
"object"
] |
de655ea1a81dfa0a72c6ee17f92929af26cc3316 | 1,721 | h | C | ElementEngine/enginelib/src/VknSprite.h | lbondi7/Element-2.0 | ecba7a5f4402167643984d15b7a1b3bcff951907 | [
"MIT"
] | null | null | null | ElementEngine/enginelib/src/VknSprite.h | lbondi7/Element-2.0 | ecba7a5f4402167643984d15b7a1b3bcff951907 | [
"MIT"
] | null | null | null | ElementEngine/enginelib/src/VknSprite.h | lbondi7/Element-2.0 | ecba7a5f4402167643984d15b7a1b3bcff951907 | [
"MIT"
] | null | null | null | #pragma once
#include <element/Sprite.h>
#include "VknPipeline.h"
#include "Mesh.h"
#include "Texture.h"
#include "DescriptorSet.h"
namespace Element {
class VknSprite final :
public Sprite
{
public:
VknSprite() = default;
explicit VknSprite(VknPipeline* pipeline, Mesh* mesh, uint32_t imageCount);
~VknSprite() override;
Mesh* GetMesh();
Texture* GetTexture() noexcept override;
VknPipeline* GetPipeline() noexcept override;
const Mesh* GetMesh() const override;
const Texture* GetTexture() const noexcept override;
const VknPipeline* GetPipeline() const noexcept override;
void SetTexture(Texture* texture, bool keepSize) override;
void SetPipeline(VknPipeline* pipeline) override;
const VknPipeline* GetOldPipeline() const noexcept;
DirtyFlags isDirty();
void setDirty(DirtyFlags flag);
void updateUniformBuffers(bool cameraChanged, const glm::mat4& viewMatrix, const glm::mat4& projMatrix, uint32_t imageIndex);
void setEntityState(EntityState state);
EntityState getEntityState();
EntityState getPrevEntityState();
void destroy();
void init(VknPipeline* pipeline, Mesh* mesh, uint32_t imageCount);
void reInit(uint32_t imageCount);
//void setEntityState(EntityState state) override;
//EntityState getEntityState() override;
std::unique_ptr<DescriptorSet> descriptorSet;
private:
EntityState entityState;
EntityState prevEntityState;
VknPipeline* oldPipeline{};
std::vector<Buffer> uniformBuffers;
DirtyFlags dirty = DirtyFlags::CLEAN;
};
}
| 28.683333 | 133 | 0.672284 | [
"mesh",
"vector"
] |
de6673aecf53bf52f861df63ad59b9bfa065b0e4 | 1,016 | h | C | src/al_graphic/include/Filter.h | imalimin/FilmKilns | 2146487c4292d8c7453a53c54d1e24417902f8b7 | [
"MIT"
] | 83 | 2020-11-13T01:35:13.000Z | 2022-03-25T02:12:13.000Z | src/al_graphic/include/Filter.h | mohsinnaqvi110/FilmKilns | 2146487c4292d8c7453a53c54d1e24417902f8b7 | [
"MIT"
] | 3 | 2020-03-23T07:28:29.000Z | 2020-09-11T17:16:48.000Z | src/al_graphic/include/Filter.h | lmylr/hwvc | 2146487c4292d8c7453a53c54d1e24417902f8b7 | [
"MIT"
] | 32 | 2020-11-09T04:20:35.000Z | 2022-03-22T04:11:45.000Z | //
// Created by limin on 2018/12/16.
//
#ifndef HARDWAREVIDEOCODEC_FILTER_H
#define HARDWAREVIDEOCODEC_FILTER_H
#include <string>
#include "Object.h"
#include "HwAbsFrameBuffer.h"
#include "BaseDrawer.h"
using namespace std;
const int FILTER_BASE = 100;
const int FILTER_NONE = 2333;
class Filter : public Object {
public:
string name;
Filter();
#ifdef ANDROID
/**
* Enable direct texture for android, if device supports.
* Default disable.
*/
Filter(bool requestHwMode);
#endif
virtual ~Filter();
virtual bool init(int w, int h);
virtual void draw(GLuint texture);
virtual void bindResources();
HwAbsFrameBuffer *getFrameBuffer();
virtual void setParams(int *params);
virtual void setParam(int key, int value);
protected:
BaseDrawer *drawer = nullptr;
private:
HwAbsFrameBuffer *fbo = nullptr;
bool initialized = false;
#ifdef ANDROID
private:
bool requestHwMode = false;
#endif
};
#endif //HARDWAREVIDEOCODEC_FILTER_H
| 16.387097 | 61 | 0.69685 | [
"object"
] |
de6dbad5703b27625f77286f37894daca8a9217d | 3,640 | h | C | src/GameStatePause.h | MaxSavenkov/drdestructo2 | a8c0d506ea7280e60d4b6bb3045ea9b471c3e314 | [
"MIT"
] | 33 | 2015-04-15T16:58:00.000Z | 2021-06-06T13:58:14.000Z | src/GameStatePause.h | MaxSavenkov/drdestructo2 | a8c0d506ea7280e60d4b6bb3045ea9b471c3e314 | [
"MIT"
] | 3 | 2015-04-15T17:11:01.000Z | 2021-01-08T14:08:52.000Z | src/GameStatePause.h | MaxSavenkov/drdestructo2 | a8c0d506ea7280e60d4b6bb3045ea9b471c3e314 | [
"MIT"
] | 6 | 2015-05-07T14:41:53.000Z | 2022-01-27T12:19:58.000Z | #pragma once
#include "BaseGameState.h"
#include "BaseMenu.h"
#include "MenuHelpers.h"
#include "OptionsMenu.h"
#include "Common.h"
/*
Pause menu is just like main menu, only with fewer options
and an option to resume game.
*/
class IPauseMenuCallback
{
public:
virtual void ResumeGame() = 0;
virtual void ShowOptions() = 0;
virtual void ExitToMenu() = 0;
};
class PauseMenu : public GameMenu, public ButtonMenuEntry::ICallback
{
public:
static const int EID_RESUME = 1;
static const int EID_OPTIONS = 3;
static const int EID_EXIT = 6;
private:
VerticalButtonEntry m_resumeGame;
VerticalButtonEntry m_options;
FooterAcceptButtonEntry m_exit;
IPauseMenuCallback *m_pCallback;
public:
PauseMenu( IPauseMenuCallback *pCallback )
: GameMenu( "Pause", SCREEN_W/2 - 450/2, 120, 450, 320 )
, m_pCallback( pCallback )
, m_resumeGame ( this, 0, "Resume game", EID_RESUME, this )
, m_options ( this, 1, "Options", EID_OPTIONS, this )
, m_exit ( this, 2, "Exit to title", EID_EXIT, this )
{
SetSelected( &m_resumeGame );
}
void operator()( int id );
};
class GameStatePause : public BaseGameState, public IPauseMenuCallback, public IOptionsMenuCallback, public IControlTypeCallback
{
BaseMenu *m_pMenu;
PauseMenu m_pauseMenu;
bool m_resumeGame;
bool m_showOptions;
bool m_exitGame;
PauseMenuOptions m_options;
VideoOptionsMenu m_vidOptions;
SoundOptionsMenu m_sndOptions;
ControlOptionsMenu_Keyboard m_ctrlOptionsKbd;
ControlOptionsMenu_Gamepad m_ctrlOptionsPad;
ControlOptionsMenu_Touch m_ctrlOptionsTouch;
GameplayOptionsMenu m_gameOptions;
bool m_backFromOptions;
bool m_backFromSubOptions;
EOptions m_showSubOptions;
public:
GameStatePause()
: BaseGameState( GAMESTATE_PAUSE )
, m_pauseMenu( this )
, m_resumeGame( false )
, m_showOptions( false )
, m_showSubOptions( OPTIONS_NONE )
, m_exitGame( false )
, m_options( 300, 200, this )
, m_vidOptions( 300, 200, this )
, m_sndOptions( 300, 200, this )
, m_ctrlOptionsKbd( 300, 200, this, this )
, m_ctrlOptionsPad( 300, 200, this, this )
, m_ctrlOptionsTouch( 300, 200, this, this )
, m_gameOptions( 300, 200, this )
, m_backFromOptions( false )
, m_backFromSubOptions( false )
, m_pMenu( &m_pauseMenu )
{
}
void RenderBefore( IRender & render, const IGameContext & context );
void RenderAfter( IRender & render, const IGameContext & context );
void Update( float dt, IGameContext & context );
void ProcessInput( IInput & input ) { m_pMenu->ProcessInput( &input ); }
bool AllowPhysicsUpdate() const { return false; }
bool AllowGraphicsUpdate() const { return false; }
bool AllowGraphicsRender() const { return false; }
bool AllowAIUpdate() const { return false; }
void OnPush( IGameContext & context );
void OnRemove( IGameContext & context ) {}
void ResumeGame()
{
m_resumeGame = true;
}
void ShowOptions()
{
m_showOptions = true;
}
void ExitToMenu()
{
m_exitGame = true;
}
void BackFromOptions()
{
m_backFromOptions = true;
}
void BackFromSubOptions()
{
m_backFromSubOptions = true;
}
void ShowSubOptions( EOptions opt )
{
m_showSubOptions = opt;
}
void ChangeControlType( EControlType type )
{
switch( type )
{
case CONTROLTYPE_KEYBOARD:
m_showSubOptions = OPTIONS_CONTROLS_KEYBOARD;
break;
case CONTROLTYPE_GAMEPAD:
m_showSubOptions = OPTIONS_CONTROLS_GAMEPAD;
break;
case CONTROLTYPE_TOUCH:
m_showSubOptions = OPTIONS_CONTROLS_TOUCH;
break;
}
}
};
| 24.10596 | 129 | 0.697253 | [
"render"
] |
de70fdc93006586b781383fa5dac282afac809ad | 1,213 | h | C | src/tdme/math/Matrix4x4Negative.h | mahula/tdme2 | 0f74d35ae5d2cd33b1a410c09f0d45f250ca7a64 | [
"BSD-3-Clause"
] | null | null | null | src/tdme/math/Matrix4x4Negative.h | mahula/tdme2 | 0f74d35ae5d2cd33b1a410c09f0d45f250ca7a64 | [
"BSD-3-Clause"
] | null | null | null | src/tdme/math/Matrix4x4Negative.h | mahula/tdme2 | 0f74d35ae5d2cd33b1a410c09f0d45f250ca7a64 | [
"BSD-3-Clause"
] | null | null | null | #pragma once
#include <tdme/tdme.h>
#include <tdme/math/fwd-tdme.h>
#include <tdme/math/Vector3.h>
#include <tdme/math/Matrix4x4.h>
using tdme::math::Matrix4x4;
using tdme::math::Vector3;
/**
* Simple class to determine if a transform is negative
* @author Andreas Drewke
* @version $Id$
*/
class tdme::math::Matrix4x4Negative
{
private:
Vector3 xAxis;
Vector3 yAxis;
Vector3 zAxis;
Vector3 tmpAxis;
public:
/**
* Check if matrix is negative
* @param matrix matrix
* @return negative
*/
inline bool isNegative(Matrix4x4& matrix) {
// check if negative scale and rotation
auto& transformationsMatrixData = matrix.getArray();
// copy into x,y,z axes
xAxis.set(transformationsMatrixData[0], transformationsMatrixData[1], transformationsMatrixData[2]);
yAxis.set(transformationsMatrixData[4], transformationsMatrixData[5], transformationsMatrixData[6]);
zAxis.set(transformationsMatrixData[8], transformationsMatrixData[9], transformationsMatrixData[10]);
// check if inverted/negative transformation
return Vector3::computeDotProduct(Vector3::computeCrossProduct(xAxis, yAxis, tmpAxis), zAxis) < 0.0f;
}
/**
* Public constructor
*/
inline Matrix4x4Negative() {
}
};
| 25.270833 | 103 | 0.741138 | [
"transform"
] |
de7c5d26b2398040805e783eecc44c228c735c26 | 631 | h | C | src/HitBoxComponent.h | firststef/ECSlib | 25997c4bac994ac2559194be7b2162fa53af6346 | [
"MIT"
] | 3 | 2021-03-09T05:07:02.000Z | 2021-07-23T12:09:15.000Z | src/HitBoxComponent.h | firststef/ECSlib | 25997c4bac994ac2559194be7b2162fa53af6346 | [
"MIT"
] | null | null | null | src/HitBoxComponent.h | firststef/ECSlib | 25997c4bac994ac2559194be7b2162fa53af6346 | [
"MIT"
] | null | null | null | #pragma once
struct HitBoxComponent : IComponent
{
std::vector<ShapeContainer> containers;
ShapeContainer* current_container = nullptr;
Vector2 last_origin_position;
HitBoxComponent(std::vector<ShapeContainer> containers, Vector2 origin_position)
:containers(std::move(containers)), last_origin_position(origin_position)
{
if (!this->containers.empty())
current_container = &(this->containers[0]);
}
void Update()
{
for (auto& c : containers)
{
c.Update();
}
}
void Mirror(Vector2 orientation)
{
for (auto& c : containers)
{
c.Mirror(orientation);
}
}
}; | 20.354839 | 84 | 0.670365 | [
"vector"
] |
de93bd3128b0e2f880e1a02435f4b475765af63c | 175,561 | h | C | Submodules/Peano/src/peano/grid/tests/records/TestVertex.h | linusseelinger/ExaHyPE-Tsunami | 92a6e14926862e1584ef1e935874c91d252e8112 | [
"BSD-3-Clause"
] | 2 | 2019-08-14T22:41:26.000Z | 2020-02-04T19:30:24.000Z | Submodules/Peano/src/peano/grid/tests/records/TestVertex.h | linusseelinger/ExaHyPE-Tsunami | 92a6e14926862e1584ef1e935874c91d252e8112 | [
"BSD-3-Clause"
] | null | null | null | Submodules/Peano/src/peano/grid/tests/records/TestVertex.h | linusseelinger/ExaHyPE-Tsunami | 92a6e14926862e1584ef1e935874c91d252e8112 | [
"BSD-3-Clause"
] | 3 | 2019-07-22T10:27:36.000Z | 2020-05-11T12:25:29.000Z | #ifndef _PEANO_GRID_TESTS_RECORDS_TESTVERTEX_H
#define _PEANO_GRID_TESTS_RECORDS_TESTVERTEX_H
#include "peano/utils/Globals.h"
#include "tarch/compiler/CompilerSpecificSettings.h"
#include "peano/utils/PeanoOptimisations.h"
#ifdef Parallel
#include "tarch/parallel/Node.h"
#endif
#ifdef Parallel
#include <mpi.h>
#endif
#include "tarch/logging/Log.h"
#include "tarch/la/Vector.h"
#include <bitset>
#include <complex>
#include <string>
#include <iostream>
namespace peano {
namespace grid {
namespace tests {
namespace records {
class TestVertex;
class TestVertexPacked;
}
}
}
}
#if defined(Parallel) && defined(PersistentRegularSubtrees) && defined(Asserts)
/**
* @author This class is generated by DaStGen
* DataStructureGenerator (DaStGen)
* 2007-2009 Wolfgang Eckhardt
* 2012 Tobias Weinzierl
*
* build date: 09-02-2014 14:40
*
* @date 31/03/2018 18:55
*/
class peano::grid::tests::records::TestVertex {
public:
typedef peano::grid::tests::records::TestVertexPacked Packed;
enum InsideOutsideDomain {
Inside = 0, Boundary = 1, Outside = 2
};
enum RefinementControl {
Unrefined = 0, Refined = 1, RefinementTriggered = 2, Refining = 3, EraseTriggered = 4, Erasing = 5, RefineDueToJoinThoughWorkerIsAlreadyErasing = 6, EnforceRefinementTriggered = 7
};
struct PersistentRecords {
bool _isHangingNode;
RefinementControl _refinementControl;
int _adjacentCellsHeight;
InsideOutsideDomain _insideOutsideDomain;
tarch::la::Vector<DIMENSIONS,double> _x;
int _level;
tarch::la::Vector<TWO_POWER_D,int> _adjacentRanks;
bool _adjacentSubtreeForksIntoOtherRank;
bool _parentRegularPersistentSubgrid;
bool _parentRegularPersistentSubgridInPreviousIteration;
/**
* Generated
*/
PersistentRecords();
/**
* Generated
*/
PersistentRecords(const bool& isHangingNode, const RefinementControl& refinementControl, const int& adjacentCellsHeight, const InsideOutsideDomain& insideOutsideDomain, const tarch::la::Vector<DIMENSIONS,double>& x, const int& level, const tarch::la::Vector<TWO_POWER_D,int>& adjacentRanks, const bool& adjacentSubtreeForksIntoOtherRank, const bool& parentRegularPersistentSubgrid, const bool& parentRegularPersistentSubgridInPreviousIteration);
/**
* Generated
*/
bool getIsHangingNode() const ;
/**
* Generated
*/
void setIsHangingNode(const bool& isHangingNode) ;
/**
* Generated
*/
RefinementControl getRefinementControl() const ;
/**
* Generated
*/
void setRefinementControl(const RefinementControl& refinementControl) ;
/**
* Generated
*/
int getAdjacentCellsHeight() const ;
/**
* Generated
*/
void setAdjacentCellsHeight(const int& adjacentCellsHeight) ;
/**
* Generated
*/
InsideOutsideDomain getInsideOutsideDomain() const ;
/**
* Generated
*/
void setInsideOutsideDomain(const InsideOutsideDomain& insideOutsideDomain) ;
tarch::la::Vector<DIMENSIONS,double> getX() const ;
void setX(const tarch::la::Vector<DIMENSIONS,double>& x) ;
/**
* Generated
*/
int getLevel() const ;
/**
* Generated
*/
void setLevel(const int& level) ;
tarch::la::Vector<TWO_POWER_D,int> getAdjacentRanks() const ;
void setAdjacentRanks(const tarch::la::Vector<TWO_POWER_D,int>& adjacentRanks) ;
/**
* Generated
*/
bool getAdjacentSubtreeForksIntoOtherRank() const ;
/**
* Generated
*/
void setAdjacentSubtreeForksIntoOtherRank(const bool& adjacentSubtreeForksIntoOtherRank) ;
/**
* Generated
*/
bool getParentRegularPersistentSubgrid() const ;
/**
* Generated
*/
void setParentRegularPersistentSubgrid(const bool& parentRegularPersistentSubgrid) ;
/**
* Generated
*/
bool getParentRegularPersistentSubgridInPreviousIteration() const ;
/**
* Generated
*/
void setParentRegularPersistentSubgridInPreviousIteration(const bool& parentRegularPersistentSubgridInPreviousIteration) ;
};
private:
PersistentRecords _persistentRecords;
int _adjacentCellsHeightOfPreviousIteration;
int _numberOfAdjacentRefinedCells;
public:
/**
* Generated
*/
TestVertex();
/**
* Generated
*/
TestVertex(const PersistentRecords& persistentRecords);
/**
* Generated
*/
TestVertex(const bool& isHangingNode, const RefinementControl& refinementControl, const int& adjacentCellsHeight, const InsideOutsideDomain& insideOutsideDomain, const tarch::la::Vector<DIMENSIONS,double>& x, const int& level, const tarch::la::Vector<TWO_POWER_D,int>& adjacentRanks, const bool& adjacentSubtreeForksIntoOtherRank, const bool& parentRegularPersistentSubgrid, const bool& parentRegularPersistentSubgridInPreviousIteration);
/**
* Generated
*/
TestVertex(const bool& isHangingNode, const RefinementControl& refinementControl, const int& adjacentCellsHeight, const int& adjacentCellsHeightOfPreviousIteration, const int& numberOfAdjacentRefinedCells, const InsideOutsideDomain& insideOutsideDomain, const tarch::la::Vector<DIMENSIONS,double>& x, const int& level, const tarch::la::Vector<TWO_POWER_D,int>& adjacentRanks, const bool& adjacentSubtreeForksIntoOtherRank, const bool& parentRegularPersistentSubgrid, const bool& parentRegularPersistentSubgridInPreviousIteration);
/**
* Generated
*/
virtual ~TestVertex();
/**
* Generated
*/
bool getIsHangingNode() const ;
/**
* Generated
*/
void setIsHangingNode(const bool& isHangingNode) ;
/**
* Generated
*/
RefinementControl getRefinementControl() const ;
/**
* Generated
*/
void setRefinementControl(const RefinementControl& refinementControl) ;
/**
* Generated
*/
int getAdjacentCellsHeight() const ;
/**
* Generated
*/
void setAdjacentCellsHeight(const int& adjacentCellsHeight) ;
/**
* Generated
*/
int getAdjacentCellsHeightOfPreviousIteration() const ;
/**
* Generated
*/
void setAdjacentCellsHeightOfPreviousIteration(const int& adjacentCellsHeightOfPreviousIteration) ;
/**
* Generated
*/
int getNumberOfAdjacentRefinedCells() const ;
/**
* Generated
*/
void setNumberOfAdjacentRefinedCells(const int& numberOfAdjacentRefinedCells) ;
/**
* Generated
*/
InsideOutsideDomain getInsideOutsideDomain() const ;
/**
* Generated
*/
void setInsideOutsideDomain(const InsideOutsideDomain& insideOutsideDomain) ;
tarch::la::Vector<DIMENSIONS,double> getX() const ;
void setX(const tarch::la::Vector<DIMENSIONS,double>& x) ;
double getX(int elementIndex) const ;
void setX(int elementIndex, const double& x) ;
/**
* Generated
*/
int getLevel() const ;
/**
* Generated
*/
void setLevel(const int& level) ;
tarch::la::Vector<TWO_POWER_D,int> getAdjacentRanks() const ;
void setAdjacentRanks(const tarch::la::Vector<TWO_POWER_D,int>& adjacentRanks) ;
int getAdjacentRanks(int elementIndex) const ;
void setAdjacentRanks(int elementIndex, const int& adjacentRanks) ;
/**
* Generated
*/
bool getAdjacentSubtreeForksIntoOtherRank() const ;
/**
* Generated
*/
void setAdjacentSubtreeForksIntoOtherRank(const bool& adjacentSubtreeForksIntoOtherRank) ;
/**
* Generated
*/
bool getParentRegularPersistentSubgrid() const ;
/**
* Generated
*/
void setParentRegularPersistentSubgrid(const bool& parentRegularPersistentSubgrid) ;
/**
* Generated
*/
bool getParentRegularPersistentSubgridInPreviousIteration() const ;
/**
* Generated
*/
void setParentRegularPersistentSubgridInPreviousIteration(const bool& parentRegularPersistentSubgridInPreviousIteration) ;
/**
* Generated
*/
static std::string toString(const InsideOutsideDomain& param);
/**
* Generated
*/
static std::string getInsideOutsideDomainMapping();
/**
* Generated
*/
static std::string toString(const RefinementControl& param);
/**
* Generated
*/
static std::string getRefinementControlMapping();
/**
* Generated
*/
std::string toString() const;
/**
* Generated
*/
void toString(std::ostream& out) const;
PersistentRecords getPersistentRecords() const;
/**
* Generated
*/
TestVertexPacked convert() const;
#ifdef Parallel
protected:
static tarch::logging::Log _log;
int _senderDestinationRank;
public:
/**
* Global that represents the mpi datatype.
* There are two variants: Datatype identifies only those attributes marked with
* parallelise. FullDatatype instead identifies the whole record with all fields.
*/
static MPI_Datatype Datatype;
static MPI_Datatype FullDatatype;
/**
* Initializes the data type for the mpi operations. Has to be called
* before the very first send or receive operation is called.
*/
static void initDatatype();
static void shutdownDatatype();
enum class ExchangeMode { Blocking, NonblockingWithPollingLoopOverTests, LoopOverProbeWithBlockingReceive };
void send(int destination, int tag, bool exchangeOnlyAttributesMarkedWithParallelise, ExchangeMode mode );
void receive(int source, int tag, bool exchangeOnlyAttributesMarkedWithParallelise, ExchangeMode mode );
static bool isMessageInQueue(int tag, bool exchangeOnlyAttributesMarkedWithParallelise);
int getSenderRank() const;
#endif
};
/**
* @author This class is generated by DaStGen
* DataStructureGenerator (DaStGen)
* 2007-2009 Wolfgang Eckhardt
* 2012 Tobias Weinzierl
*
* build date: 09-02-2014 14:40
*
* @date 31/03/2018 18:55
*/
class peano::grid::tests::records::TestVertexPacked {
public:
typedef peano::grid::tests::records::TestVertex::InsideOutsideDomain InsideOutsideDomain;
typedef peano::grid::tests::records::TestVertex::RefinementControl RefinementControl;
struct PersistentRecords {
int _adjacentCellsHeight;
tarch::la::Vector<DIMENSIONS,double> _x;
int _level;
tarch::la::Vector<TWO_POWER_D,int> _adjacentRanks;
bool _adjacentSubtreeForksIntoOtherRank;
bool _parentRegularPersistentSubgrid;
bool _parentRegularPersistentSubgridInPreviousIteration;
/** mapping of records:
|| Member || startbit || length
| isHangingNode | startbit 0 | #bits 1
| refinementControl | startbit 1 | #bits 3
| insideOutsideDomain | startbit 4 | #bits 2
*/
int _packedRecords0;
/**
* Generated
*/
PersistentRecords();
/**
* Generated
*/
PersistentRecords(const bool& isHangingNode, const RefinementControl& refinementControl, const int& adjacentCellsHeight, const InsideOutsideDomain& insideOutsideDomain, const tarch::la::Vector<DIMENSIONS,double>& x, const int& level, const tarch::la::Vector<TWO_POWER_D,int>& adjacentRanks, const bool& adjacentSubtreeForksIntoOtherRank, const bool& parentRegularPersistentSubgrid, const bool& parentRegularPersistentSubgridInPreviousIteration);
/**
* Generated
*/
bool getIsHangingNode() const ;
/**
* Generated
*/
void setIsHangingNode(const bool& isHangingNode) ;
/**
* Generated
*/
RefinementControl getRefinementControl() const ;
/**
* Generated
*/
void setRefinementControl(const RefinementControl& refinementControl) ;
/**
* Generated
*/
int getAdjacentCellsHeight() const ;
/**
* Generated
*/
void setAdjacentCellsHeight(const int& adjacentCellsHeight) ;
/**
* Generated
*/
InsideOutsideDomain getInsideOutsideDomain() const ;
/**
* Generated
*/
void setInsideOutsideDomain(const InsideOutsideDomain& insideOutsideDomain) ;
tarch::la::Vector<DIMENSIONS,double> getX() const ;
void setX(const tarch::la::Vector<DIMENSIONS,double>& x) ;
/**
* Generated
*/
int getLevel() const ;
/**
* Generated
*/
void setLevel(const int& level) ;
tarch::la::Vector<TWO_POWER_D,int> getAdjacentRanks() const ;
void setAdjacentRanks(const tarch::la::Vector<TWO_POWER_D,int>& adjacentRanks) ;
/**
* Generated
*/
bool getAdjacentSubtreeForksIntoOtherRank() const ;
/**
* Generated
*/
void setAdjacentSubtreeForksIntoOtherRank(const bool& adjacentSubtreeForksIntoOtherRank) ;
/**
* Generated
*/
bool getParentRegularPersistentSubgrid() const ;
/**
* Generated
*/
void setParentRegularPersistentSubgrid(const bool& parentRegularPersistentSubgrid) ;
/**
* Generated
*/
bool getParentRegularPersistentSubgridInPreviousIteration() const ;
/**
* Generated
*/
void setParentRegularPersistentSubgridInPreviousIteration(const bool& parentRegularPersistentSubgridInPreviousIteration) ;
};
private:
PersistentRecords _persistentRecords;
int _adjacentCellsHeightOfPreviousIteration;
int _numberOfAdjacentRefinedCells;
public:
/**
* Generated
*/
TestVertexPacked();
/**
* Generated
*/
TestVertexPacked(const PersistentRecords& persistentRecords);
/**
* Generated
*/
TestVertexPacked(const bool& isHangingNode, const RefinementControl& refinementControl, const int& adjacentCellsHeight, const InsideOutsideDomain& insideOutsideDomain, const tarch::la::Vector<DIMENSIONS,double>& x, const int& level, const tarch::la::Vector<TWO_POWER_D,int>& adjacentRanks, const bool& adjacentSubtreeForksIntoOtherRank, const bool& parentRegularPersistentSubgrid, const bool& parentRegularPersistentSubgridInPreviousIteration);
/**
* Generated
*/
TestVertexPacked(const bool& isHangingNode, const RefinementControl& refinementControl, const int& adjacentCellsHeight, const int& adjacentCellsHeightOfPreviousIteration, const int& numberOfAdjacentRefinedCells, const InsideOutsideDomain& insideOutsideDomain, const tarch::la::Vector<DIMENSIONS,double>& x, const int& level, const tarch::la::Vector<TWO_POWER_D,int>& adjacentRanks, const bool& adjacentSubtreeForksIntoOtherRank, const bool& parentRegularPersistentSubgrid, const bool& parentRegularPersistentSubgridInPreviousIteration);
/**
* Generated
*/
virtual ~TestVertexPacked();
/**
* Generated
*/
bool getIsHangingNode() const ;
/**
* Generated
*/
void setIsHangingNode(const bool& isHangingNode) ;
/**
* Generated
*/
RefinementControl getRefinementControl() const ;
/**
* Generated
*/
void setRefinementControl(const RefinementControl& refinementControl) ;
/**
* Generated
*/
int getAdjacentCellsHeight() const ;
/**
* Generated
*/
void setAdjacentCellsHeight(const int& adjacentCellsHeight) ;
/**
* Generated
*/
int getAdjacentCellsHeightOfPreviousIteration() const ;
/**
* Generated
*/
void setAdjacentCellsHeightOfPreviousIteration(const int& adjacentCellsHeightOfPreviousIteration) ;
/**
* Generated
*/
int getNumberOfAdjacentRefinedCells() const ;
/**
* Generated
*/
void setNumberOfAdjacentRefinedCells(const int& numberOfAdjacentRefinedCells) ;
/**
* Generated
*/
InsideOutsideDomain getInsideOutsideDomain() const ;
/**
* Generated
*/
void setInsideOutsideDomain(const InsideOutsideDomain& insideOutsideDomain) ;
tarch::la::Vector<DIMENSIONS,double> getX() const ;
void setX(const tarch::la::Vector<DIMENSIONS,double>& x) ;
double getX(int elementIndex) const ;
void setX(int elementIndex, const double& x) ;
/**
* Generated
*/
int getLevel() const ;
/**
* Generated
*/
void setLevel(const int& level) ;
tarch::la::Vector<TWO_POWER_D,int> getAdjacentRanks() const ;
void setAdjacentRanks(const tarch::la::Vector<TWO_POWER_D,int>& adjacentRanks) ;
int getAdjacentRanks(int elementIndex) const ;
void setAdjacentRanks(int elementIndex, const int& adjacentRanks) ;
/**
* Generated
*/
bool getAdjacentSubtreeForksIntoOtherRank() const ;
/**
* Generated
*/
void setAdjacentSubtreeForksIntoOtherRank(const bool& adjacentSubtreeForksIntoOtherRank) ;
/**
* Generated
*/
bool getParentRegularPersistentSubgrid() const ;
/**
* Generated
*/
void setParentRegularPersistentSubgrid(const bool& parentRegularPersistentSubgrid) ;
/**
* Generated
*/
bool getParentRegularPersistentSubgridInPreviousIteration() const ;
/**
* Generated
*/
void setParentRegularPersistentSubgridInPreviousIteration(const bool& parentRegularPersistentSubgridInPreviousIteration) ;
/**
* Generated
*/
static std::string toString(const InsideOutsideDomain& param);
/**
* Generated
*/
static std::string getInsideOutsideDomainMapping();
/**
* Generated
*/
static std::string toString(const RefinementControl& param);
/**
* Generated
*/
static std::string getRefinementControlMapping();
/**
* Generated
*/
std::string toString() const;
/**
* Generated
*/
void toString(std::ostream& out) const;
PersistentRecords getPersistentRecords() const;
/**
* Generated
*/
TestVertex convert() const;
#ifdef Parallel
protected:
static tarch::logging::Log _log;
int _senderDestinationRank;
public:
/**
* Global that represents the mpi datatype.
* There are two variants: Datatype identifies only those attributes marked with
* parallelise. FullDatatype instead identifies the whole record with all fields.
*/
static MPI_Datatype Datatype;
static MPI_Datatype FullDatatype;
/**
* Initializes the data type for the mpi operations. Has to be called
* before the very first send or receive operation is called.
*/
static void initDatatype();
static void shutdownDatatype();
enum class ExchangeMode { Blocking, NonblockingWithPollingLoopOverTests, LoopOverProbeWithBlockingReceive };
void send(int destination, int tag, bool exchangeOnlyAttributesMarkedWithParallelise, ExchangeMode mode );
void receive(int source, int tag, bool exchangeOnlyAttributesMarkedWithParallelise, ExchangeMode mode );
static bool isMessageInQueue(int tag, bool exchangeOnlyAttributesMarkedWithParallelise);
int getSenderRank() const;
#endif
};
#elif defined(PersistentRegularSubtrees) && defined(Asserts) && !defined(Parallel)
/**
* @author This class is generated by DaStGen
* DataStructureGenerator (DaStGen)
* 2007-2009 Wolfgang Eckhardt
* 2012 Tobias Weinzierl
*
* build date: 09-02-2014 14:40
*
* @date 31/03/2018 18:55
*/
class peano::grid::tests::records::TestVertex {
public:
typedef peano::grid::tests::records::TestVertexPacked Packed;
enum InsideOutsideDomain {
Inside = 0, Boundary = 1, Outside = 2
};
enum RefinementControl {
Unrefined = 0, Refined = 1, RefinementTriggered = 2, Refining = 3, EraseTriggered = 4, Erasing = 5, RefineDueToJoinThoughWorkerIsAlreadyErasing = 6, EnforceRefinementTriggered = 7
};
struct PersistentRecords {
bool _isHangingNode;
RefinementControl _refinementControl;
int _adjacentCellsHeight;
InsideOutsideDomain _insideOutsideDomain;
tarch::la::Vector<DIMENSIONS,double> _x;
int _level;
bool _parentRegularPersistentSubgrid;
bool _parentRegularPersistentSubgridInPreviousIteration;
/**
* Generated
*/
PersistentRecords();
/**
* Generated
*/
PersistentRecords(const bool& isHangingNode, const RefinementControl& refinementControl, const int& adjacentCellsHeight, const InsideOutsideDomain& insideOutsideDomain, const tarch::la::Vector<DIMENSIONS,double>& x, const int& level, const bool& parentRegularPersistentSubgrid, const bool& parentRegularPersistentSubgridInPreviousIteration);
/**
* Generated
*/
bool getIsHangingNode() const ;
/**
* Generated
*/
void setIsHangingNode(const bool& isHangingNode) ;
/**
* Generated
*/
RefinementControl getRefinementControl() const ;
/**
* Generated
*/
void setRefinementControl(const RefinementControl& refinementControl) ;
/**
* Generated
*/
int getAdjacentCellsHeight() const ;
/**
* Generated
*/
void setAdjacentCellsHeight(const int& adjacentCellsHeight) ;
/**
* Generated
*/
InsideOutsideDomain getInsideOutsideDomain() const ;
/**
* Generated
*/
void setInsideOutsideDomain(const InsideOutsideDomain& insideOutsideDomain) ;
tarch::la::Vector<DIMENSIONS,double> getX() const ;
void setX(const tarch::la::Vector<DIMENSIONS,double>& x) ;
/**
* Generated
*/
int getLevel() const ;
/**
* Generated
*/
void setLevel(const int& level) ;
/**
* Generated
*/
bool getParentRegularPersistentSubgrid() const ;
/**
* Generated
*/
void setParentRegularPersistentSubgrid(const bool& parentRegularPersistentSubgrid) ;
/**
* Generated
*/
bool getParentRegularPersistentSubgridInPreviousIteration() const ;
/**
* Generated
*/
void setParentRegularPersistentSubgridInPreviousIteration(const bool& parentRegularPersistentSubgridInPreviousIteration) ;
};
private:
PersistentRecords _persistentRecords;
int _adjacentCellsHeightOfPreviousIteration;
int _numberOfAdjacentRefinedCells;
public:
/**
* Generated
*/
TestVertex();
/**
* Generated
*/
TestVertex(const PersistentRecords& persistentRecords);
/**
* Generated
*/
TestVertex(const bool& isHangingNode, const RefinementControl& refinementControl, const int& adjacentCellsHeight, const InsideOutsideDomain& insideOutsideDomain, const tarch::la::Vector<DIMENSIONS,double>& x, const int& level, const bool& parentRegularPersistentSubgrid, const bool& parentRegularPersistentSubgridInPreviousIteration);
/**
* Generated
*/
TestVertex(const bool& isHangingNode, const RefinementControl& refinementControl, const int& adjacentCellsHeight, const int& adjacentCellsHeightOfPreviousIteration, const int& numberOfAdjacentRefinedCells, const InsideOutsideDomain& insideOutsideDomain, const tarch::la::Vector<DIMENSIONS,double>& x, const int& level, const bool& parentRegularPersistentSubgrid, const bool& parentRegularPersistentSubgridInPreviousIteration);
/**
* Generated
*/
virtual ~TestVertex();
/**
* Generated
*/
bool getIsHangingNode() const ;
/**
* Generated
*/
void setIsHangingNode(const bool& isHangingNode) ;
/**
* Generated
*/
RefinementControl getRefinementControl() const ;
/**
* Generated
*/
void setRefinementControl(const RefinementControl& refinementControl) ;
/**
* Generated
*/
int getAdjacentCellsHeight() const ;
/**
* Generated
*/
void setAdjacentCellsHeight(const int& adjacentCellsHeight) ;
/**
* Generated
*/
int getAdjacentCellsHeightOfPreviousIteration() const ;
/**
* Generated
*/
void setAdjacentCellsHeightOfPreviousIteration(const int& adjacentCellsHeightOfPreviousIteration) ;
/**
* Generated
*/
int getNumberOfAdjacentRefinedCells() const ;
/**
* Generated
*/
void setNumberOfAdjacentRefinedCells(const int& numberOfAdjacentRefinedCells) ;
/**
* Generated
*/
InsideOutsideDomain getInsideOutsideDomain() const ;
/**
* Generated
*/
void setInsideOutsideDomain(const InsideOutsideDomain& insideOutsideDomain) ;
tarch::la::Vector<DIMENSIONS,double> getX() const ;
void setX(const tarch::la::Vector<DIMENSIONS,double>& x) ;
double getX(int elementIndex) const ;
void setX(int elementIndex, const double& x) ;
/**
* Generated
*/
int getLevel() const ;
/**
* Generated
*/
void setLevel(const int& level) ;
/**
* Generated
*/
bool getParentRegularPersistentSubgrid() const ;
/**
* Generated
*/
void setParentRegularPersistentSubgrid(const bool& parentRegularPersistentSubgrid) ;
/**
* Generated
*/
bool getParentRegularPersistentSubgridInPreviousIteration() const ;
/**
* Generated
*/
void setParentRegularPersistentSubgridInPreviousIteration(const bool& parentRegularPersistentSubgridInPreviousIteration) ;
/**
* Generated
*/
static std::string toString(const InsideOutsideDomain& param);
/**
* Generated
*/
static std::string getInsideOutsideDomainMapping();
/**
* Generated
*/
static std::string toString(const RefinementControl& param);
/**
* Generated
*/
static std::string getRefinementControlMapping();
/**
* Generated
*/
std::string toString() const;
/**
* Generated
*/
void toString(std::ostream& out) const;
PersistentRecords getPersistentRecords() const;
/**
* Generated
*/
TestVertexPacked convert() const;
#ifdef Parallel
protected:
static tarch::logging::Log _log;
int _senderDestinationRank;
public:
/**
* Global that represents the mpi datatype.
* There are two variants: Datatype identifies only those attributes marked with
* parallelise. FullDatatype instead identifies the whole record with all fields.
*/
static MPI_Datatype Datatype;
static MPI_Datatype FullDatatype;
/**
* Initializes the data type for the mpi operations. Has to be called
* before the very first send or receive operation is called.
*/
static void initDatatype();
static void shutdownDatatype();
enum class ExchangeMode { Blocking, NonblockingWithPollingLoopOverTests, LoopOverProbeWithBlockingReceive };
void send(int destination, int tag, bool exchangeOnlyAttributesMarkedWithParallelise, ExchangeMode mode );
void receive(int source, int tag, bool exchangeOnlyAttributesMarkedWithParallelise, ExchangeMode mode );
static bool isMessageInQueue(int tag, bool exchangeOnlyAttributesMarkedWithParallelise);
int getSenderRank() const;
#endif
};
/**
* @author This class is generated by DaStGen
* DataStructureGenerator (DaStGen)
* 2007-2009 Wolfgang Eckhardt
* 2012 Tobias Weinzierl
*
* build date: 09-02-2014 14:40
*
* @date 31/03/2018 18:55
*/
class peano::grid::tests::records::TestVertexPacked {
public:
typedef peano::grid::tests::records::TestVertex::InsideOutsideDomain InsideOutsideDomain;
typedef peano::grid::tests::records::TestVertex::RefinementControl RefinementControl;
struct PersistentRecords {
int _adjacentCellsHeight;
tarch::la::Vector<DIMENSIONS,double> _x;
int _level;
bool _parentRegularPersistentSubgrid;
bool _parentRegularPersistentSubgridInPreviousIteration;
/** mapping of records:
|| Member || startbit || length
| isHangingNode | startbit 0 | #bits 1
| refinementControl | startbit 1 | #bits 3
| insideOutsideDomain | startbit 4 | #bits 2
*/
int _packedRecords0;
/**
* Generated
*/
PersistentRecords();
/**
* Generated
*/
PersistentRecords(const bool& isHangingNode, const RefinementControl& refinementControl, const int& adjacentCellsHeight, const InsideOutsideDomain& insideOutsideDomain, const tarch::la::Vector<DIMENSIONS,double>& x, const int& level, const bool& parentRegularPersistentSubgrid, const bool& parentRegularPersistentSubgridInPreviousIteration);
/**
* Generated
*/
bool getIsHangingNode() const ;
/**
* Generated
*/
void setIsHangingNode(const bool& isHangingNode) ;
/**
* Generated
*/
RefinementControl getRefinementControl() const ;
/**
* Generated
*/
void setRefinementControl(const RefinementControl& refinementControl) ;
/**
* Generated
*/
int getAdjacentCellsHeight() const ;
/**
* Generated
*/
void setAdjacentCellsHeight(const int& adjacentCellsHeight) ;
/**
* Generated
*/
InsideOutsideDomain getInsideOutsideDomain() const ;
/**
* Generated
*/
void setInsideOutsideDomain(const InsideOutsideDomain& insideOutsideDomain) ;
tarch::la::Vector<DIMENSIONS,double> getX() const ;
void setX(const tarch::la::Vector<DIMENSIONS,double>& x) ;
/**
* Generated
*/
int getLevel() const ;
/**
* Generated
*/
void setLevel(const int& level) ;
/**
* Generated
*/
bool getParentRegularPersistentSubgrid() const ;
/**
* Generated
*/
void setParentRegularPersistentSubgrid(const bool& parentRegularPersistentSubgrid) ;
/**
* Generated
*/
bool getParentRegularPersistentSubgridInPreviousIteration() const ;
/**
* Generated
*/
void setParentRegularPersistentSubgridInPreviousIteration(const bool& parentRegularPersistentSubgridInPreviousIteration) ;
};
private:
PersistentRecords _persistentRecords;
int _adjacentCellsHeightOfPreviousIteration;
int _numberOfAdjacentRefinedCells;
public:
/**
* Generated
*/
TestVertexPacked();
/**
* Generated
*/
TestVertexPacked(const PersistentRecords& persistentRecords);
/**
* Generated
*/
TestVertexPacked(const bool& isHangingNode, const RefinementControl& refinementControl, const int& adjacentCellsHeight, const InsideOutsideDomain& insideOutsideDomain, const tarch::la::Vector<DIMENSIONS,double>& x, const int& level, const bool& parentRegularPersistentSubgrid, const bool& parentRegularPersistentSubgridInPreviousIteration);
/**
* Generated
*/
TestVertexPacked(const bool& isHangingNode, const RefinementControl& refinementControl, const int& adjacentCellsHeight, const int& adjacentCellsHeightOfPreviousIteration, const int& numberOfAdjacentRefinedCells, const InsideOutsideDomain& insideOutsideDomain, const tarch::la::Vector<DIMENSIONS,double>& x, const int& level, const bool& parentRegularPersistentSubgrid, const bool& parentRegularPersistentSubgridInPreviousIteration);
/**
* Generated
*/
virtual ~TestVertexPacked();
/**
* Generated
*/
bool getIsHangingNode() const ;
/**
* Generated
*/
void setIsHangingNode(const bool& isHangingNode) ;
/**
* Generated
*/
RefinementControl getRefinementControl() const ;
/**
* Generated
*/
void setRefinementControl(const RefinementControl& refinementControl) ;
/**
* Generated
*/
int getAdjacentCellsHeight() const ;
/**
* Generated
*/
void setAdjacentCellsHeight(const int& adjacentCellsHeight) ;
/**
* Generated
*/
int getAdjacentCellsHeightOfPreviousIteration() const ;
/**
* Generated
*/
void setAdjacentCellsHeightOfPreviousIteration(const int& adjacentCellsHeightOfPreviousIteration) ;
/**
* Generated
*/
int getNumberOfAdjacentRefinedCells() const ;
/**
* Generated
*/
void setNumberOfAdjacentRefinedCells(const int& numberOfAdjacentRefinedCells) ;
/**
* Generated
*/
InsideOutsideDomain getInsideOutsideDomain() const ;
/**
* Generated
*/
void setInsideOutsideDomain(const InsideOutsideDomain& insideOutsideDomain) ;
tarch::la::Vector<DIMENSIONS,double> getX() const ;
void setX(const tarch::la::Vector<DIMENSIONS,double>& x) ;
double getX(int elementIndex) const ;
void setX(int elementIndex, const double& x) ;
/**
* Generated
*/
int getLevel() const ;
/**
* Generated
*/
void setLevel(const int& level) ;
/**
* Generated
*/
bool getParentRegularPersistentSubgrid() const ;
/**
* Generated
*/
void setParentRegularPersistentSubgrid(const bool& parentRegularPersistentSubgrid) ;
/**
* Generated
*/
bool getParentRegularPersistentSubgridInPreviousIteration() const ;
/**
* Generated
*/
void setParentRegularPersistentSubgridInPreviousIteration(const bool& parentRegularPersistentSubgridInPreviousIteration) ;
/**
* Generated
*/
static std::string toString(const InsideOutsideDomain& param);
/**
* Generated
*/
static std::string getInsideOutsideDomainMapping();
/**
* Generated
*/
static std::string toString(const RefinementControl& param);
/**
* Generated
*/
static std::string getRefinementControlMapping();
/**
* Generated
*/
std::string toString() const;
/**
* Generated
*/
void toString(std::ostream& out) const;
PersistentRecords getPersistentRecords() const;
/**
* Generated
*/
TestVertex convert() const;
#ifdef Parallel
protected:
static tarch::logging::Log _log;
int _senderDestinationRank;
public:
/**
* Global that represents the mpi datatype.
* There are two variants: Datatype identifies only those attributes marked with
* parallelise. FullDatatype instead identifies the whole record with all fields.
*/
static MPI_Datatype Datatype;
static MPI_Datatype FullDatatype;
/**
* Initializes the data type for the mpi operations. Has to be called
* before the very first send or receive operation is called.
*/
static void initDatatype();
static void shutdownDatatype();
enum class ExchangeMode { Blocking, NonblockingWithPollingLoopOverTests, LoopOverProbeWithBlockingReceive };
void send(int destination, int tag, bool exchangeOnlyAttributesMarkedWithParallelise, ExchangeMode mode );
void receive(int source, int tag, bool exchangeOnlyAttributesMarkedWithParallelise, ExchangeMode mode );
static bool isMessageInQueue(int tag, bool exchangeOnlyAttributesMarkedWithParallelise);
int getSenderRank() const;
#endif
};
#elif defined(Parallel) && !defined(PersistentRegularSubtrees) && defined(Asserts)
/**
* @author This class is generated by DaStGen
* DataStructureGenerator (DaStGen)
* 2007-2009 Wolfgang Eckhardt
* 2012 Tobias Weinzierl
*
* build date: 09-02-2014 14:40
*
* @date 31/03/2018 18:55
*/
class peano::grid::tests::records::TestVertex {
public:
typedef peano::grid::tests::records::TestVertexPacked Packed;
enum InsideOutsideDomain {
Inside = 0, Boundary = 1, Outside = 2
};
enum RefinementControl {
Unrefined = 0, Refined = 1, RefinementTriggered = 2, Refining = 3, EraseTriggered = 4, Erasing = 5, RefineDueToJoinThoughWorkerIsAlreadyErasing = 6, EnforceRefinementTriggered = 7
};
struct PersistentRecords {
bool _isHangingNode;
RefinementControl _refinementControl;
int _adjacentCellsHeight;
InsideOutsideDomain _insideOutsideDomain;
tarch::la::Vector<DIMENSIONS,double> _x;
int _level;
tarch::la::Vector<TWO_POWER_D,int> _adjacentRanks;
bool _adjacentSubtreeForksIntoOtherRank;
/**
* Generated
*/
PersistentRecords();
/**
* Generated
*/
PersistentRecords(const bool& isHangingNode, const RefinementControl& refinementControl, const int& adjacentCellsHeight, const InsideOutsideDomain& insideOutsideDomain, const tarch::la::Vector<DIMENSIONS,double>& x, const int& level, const tarch::la::Vector<TWO_POWER_D,int>& adjacentRanks, const bool& adjacentSubtreeForksIntoOtherRank);
/**
* Generated
*/
bool getIsHangingNode() const ;
/**
* Generated
*/
void setIsHangingNode(const bool& isHangingNode) ;
/**
* Generated
*/
RefinementControl getRefinementControl() const ;
/**
* Generated
*/
void setRefinementControl(const RefinementControl& refinementControl) ;
/**
* Generated
*/
int getAdjacentCellsHeight() const ;
/**
* Generated
*/
void setAdjacentCellsHeight(const int& adjacentCellsHeight) ;
/**
* Generated
*/
InsideOutsideDomain getInsideOutsideDomain() const ;
/**
* Generated
*/
void setInsideOutsideDomain(const InsideOutsideDomain& insideOutsideDomain) ;
tarch::la::Vector<DIMENSIONS,double> getX() const ;
void setX(const tarch::la::Vector<DIMENSIONS,double>& x) ;
/**
* Generated
*/
int getLevel() const ;
/**
* Generated
*/
void setLevel(const int& level) ;
tarch::la::Vector<TWO_POWER_D,int> getAdjacentRanks() const ;
void setAdjacentRanks(const tarch::la::Vector<TWO_POWER_D,int>& adjacentRanks) ;
/**
* Generated
*/
bool getAdjacentSubtreeForksIntoOtherRank() const ;
/**
* Generated
*/
void setAdjacentSubtreeForksIntoOtherRank(const bool& adjacentSubtreeForksIntoOtherRank) ;
};
private:
PersistentRecords _persistentRecords;
int _adjacentCellsHeightOfPreviousIteration;
int _numberOfAdjacentRefinedCells;
public:
/**
* Generated
*/
TestVertex();
/**
* Generated
*/
TestVertex(const PersistentRecords& persistentRecords);
/**
* Generated
*/
TestVertex(const bool& isHangingNode, const RefinementControl& refinementControl, const int& adjacentCellsHeight, const InsideOutsideDomain& insideOutsideDomain, const tarch::la::Vector<DIMENSIONS,double>& x, const int& level, const tarch::la::Vector<TWO_POWER_D,int>& adjacentRanks, const bool& adjacentSubtreeForksIntoOtherRank);
/**
* Generated
*/
TestVertex(const bool& isHangingNode, const RefinementControl& refinementControl, const int& adjacentCellsHeight, const int& adjacentCellsHeightOfPreviousIteration, const int& numberOfAdjacentRefinedCells, const InsideOutsideDomain& insideOutsideDomain, const tarch::la::Vector<DIMENSIONS,double>& x, const int& level, const tarch::la::Vector<TWO_POWER_D,int>& adjacentRanks, const bool& adjacentSubtreeForksIntoOtherRank);
/**
* Generated
*/
virtual ~TestVertex();
/**
* Generated
*/
bool getIsHangingNode() const ;
/**
* Generated
*/
void setIsHangingNode(const bool& isHangingNode) ;
/**
* Generated
*/
RefinementControl getRefinementControl() const ;
/**
* Generated
*/
void setRefinementControl(const RefinementControl& refinementControl) ;
/**
* Generated
*/
int getAdjacentCellsHeight() const ;
/**
* Generated
*/
void setAdjacentCellsHeight(const int& adjacentCellsHeight) ;
/**
* Generated
*/
int getAdjacentCellsHeightOfPreviousIteration() const ;
/**
* Generated
*/
void setAdjacentCellsHeightOfPreviousIteration(const int& adjacentCellsHeightOfPreviousIteration) ;
/**
* Generated
*/
int getNumberOfAdjacentRefinedCells() const ;
/**
* Generated
*/
void setNumberOfAdjacentRefinedCells(const int& numberOfAdjacentRefinedCells) ;
/**
* Generated
*/
InsideOutsideDomain getInsideOutsideDomain() const ;
/**
* Generated
*/
void setInsideOutsideDomain(const InsideOutsideDomain& insideOutsideDomain) ;
tarch::la::Vector<DIMENSIONS,double> getX() const ;
void setX(const tarch::la::Vector<DIMENSIONS,double>& x) ;
double getX(int elementIndex) const ;
void setX(int elementIndex, const double& x) ;
/**
* Generated
*/
int getLevel() const ;
/**
* Generated
*/
void setLevel(const int& level) ;
tarch::la::Vector<TWO_POWER_D,int> getAdjacentRanks() const ;
void setAdjacentRanks(const tarch::la::Vector<TWO_POWER_D,int>& adjacentRanks) ;
int getAdjacentRanks(int elementIndex) const ;
void setAdjacentRanks(int elementIndex, const int& adjacentRanks) ;
/**
* Generated
*/
bool getAdjacentSubtreeForksIntoOtherRank() const ;
/**
* Generated
*/
void setAdjacentSubtreeForksIntoOtherRank(const bool& adjacentSubtreeForksIntoOtherRank) ;
/**
* Generated
*/
static std::string toString(const InsideOutsideDomain& param);
/**
* Generated
*/
static std::string getInsideOutsideDomainMapping();
/**
* Generated
*/
static std::string toString(const RefinementControl& param);
/**
* Generated
*/
static std::string getRefinementControlMapping();
/**
* Generated
*/
std::string toString() const;
/**
* Generated
*/
void toString(std::ostream& out) const;
PersistentRecords getPersistentRecords() const;
/**
* Generated
*/
TestVertexPacked convert() const;
#ifdef Parallel
protected:
static tarch::logging::Log _log;
int _senderDestinationRank;
public:
/**
* Global that represents the mpi datatype.
* There are two variants: Datatype identifies only those attributes marked with
* parallelise. FullDatatype instead identifies the whole record with all fields.
*/
static MPI_Datatype Datatype;
static MPI_Datatype FullDatatype;
/**
* Initializes the data type for the mpi operations. Has to be called
* before the very first send or receive operation is called.
*/
static void initDatatype();
static void shutdownDatatype();
enum class ExchangeMode { Blocking, NonblockingWithPollingLoopOverTests, LoopOverProbeWithBlockingReceive };
void send(int destination, int tag, bool exchangeOnlyAttributesMarkedWithParallelise, ExchangeMode mode );
void receive(int source, int tag, bool exchangeOnlyAttributesMarkedWithParallelise, ExchangeMode mode );
static bool isMessageInQueue(int tag, bool exchangeOnlyAttributesMarkedWithParallelise);
int getSenderRank() const;
#endif
};
/**
* @author This class is generated by DaStGen
* DataStructureGenerator (DaStGen)
* 2007-2009 Wolfgang Eckhardt
* 2012 Tobias Weinzierl
*
* build date: 09-02-2014 14:40
*
* @date 31/03/2018 18:55
*/
class peano::grid::tests::records::TestVertexPacked {
public:
typedef peano::grid::tests::records::TestVertex::InsideOutsideDomain InsideOutsideDomain;
typedef peano::grid::tests::records::TestVertex::RefinementControl RefinementControl;
struct PersistentRecords {
int _adjacentCellsHeight;
tarch::la::Vector<DIMENSIONS,double> _x;
int _level;
tarch::la::Vector<TWO_POWER_D,int> _adjacentRanks;
bool _adjacentSubtreeForksIntoOtherRank;
/** mapping of records:
|| Member || startbit || length
| isHangingNode | startbit 0 | #bits 1
| refinementControl | startbit 1 | #bits 3
| insideOutsideDomain | startbit 4 | #bits 2
*/
int _packedRecords0;
/**
* Generated
*/
PersistentRecords();
/**
* Generated
*/
PersistentRecords(const bool& isHangingNode, const RefinementControl& refinementControl, const int& adjacentCellsHeight, const InsideOutsideDomain& insideOutsideDomain, const tarch::la::Vector<DIMENSIONS,double>& x, const int& level, const tarch::la::Vector<TWO_POWER_D,int>& adjacentRanks, const bool& adjacentSubtreeForksIntoOtherRank);
/**
* Generated
*/
bool getIsHangingNode() const ;
/**
* Generated
*/
void setIsHangingNode(const bool& isHangingNode) ;
/**
* Generated
*/
RefinementControl getRefinementControl() const ;
/**
* Generated
*/
void setRefinementControl(const RefinementControl& refinementControl) ;
/**
* Generated
*/
int getAdjacentCellsHeight() const ;
/**
* Generated
*/
void setAdjacentCellsHeight(const int& adjacentCellsHeight) ;
/**
* Generated
*/
InsideOutsideDomain getInsideOutsideDomain() const ;
/**
* Generated
*/
void setInsideOutsideDomain(const InsideOutsideDomain& insideOutsideDomain) ;
tarch::la::Vector<DIMENSIONS,double> getX() const ;
void setX(const tarch::la::Vector<DIMENSIONS,double>& x) ;
/**
* Generated
*/
int getLevel() const ;
/**
* Generated
*/
void setLevel(const int& level) ;
tarch::la::Vector<TWO_POWER_D,int> getAdjacentRanks() const ;
void setAdjacentRanks(const tarch::la::Vector<TWO_POWER_D,int>& adjacentRanks) ;
/**
* Generated
*/
bool getAdjacentSubtreeForksIntoOtherRank() const ;
/**
* Generated
*/
void setAdjacentSubtreeForksIntoOtherRank(const bool& adjacentSubtreeForksIntoOtherRank) ;
};
private:
PersistentRecords _persistentRecords;
int _adjacentCellsHeightOfPreviousIteration;
int _numberOfAdjacentRefinedCells;
public:
/**
* Generated
*/
TestVertexPacked();
/**
* Generated
*/
TestVertexPacked(const PersistentRecords& persistentRecords);
/**
* Generated
*/
TestVertexPacked(const bool& isHangingNode, const RefinementControl& refinementControl, const int& adjacentCellsHeight, const InsideOutsideDomain& insideOutsideDomain, const tarch::la::Vector<DIMENSIONS,double>& x, const int& level, const tarch::la::Vector<TWO_POWER_D,int>& adjacentRanks, const bool& adjacentSubtreeForksIntoOtherRank);
/**
* Generated
*/
TestVertexPacked(const bool& isHangingNode, const RefinementControl& refinementControl, const int& adjacentCellsHeight, const int& adjacentCellsHeightOfPreviousIteration, const int& numberOfAdjacentRefinedCells, const InsideOutsideDomain& insideOutsideDomain, const tarch::la::Vector<DIMENSIONS,double>& x, const int& level, const tarch::la::Vector<TWO_POWER_D,int>& adjacentRanks, const bool& adjacentSubtreeForksIntoOtherRank);
/**
* Generated
*/
virtual ~TestVertexPacked();
/**
* Generated
*/
bool getIsHangingNode() const ;
/**
* Generated
*/
void setIsHangingNode(const bool& isHangingNode) ;
/**
* Generated
*/
RefinementControl getRefinementControl() const ;
/**
* Generated
*/
void setRefinementControl(const RefinementControl& refinementControl) ;
/**
* Generated
*/
int getAdjacentCellsHeight() const ;
/**
* Generated
*/
void setAdjacentCellsHeight(const int& adjacentCellsHeight) ;
/**
* Generated
*/
int getAdjacentCellsHeightOfPreviousIteration() const ;
/**
* Generated
*/
void setAdjacentCellsHeightOfPreviousIteration(const int& adjacentCellsHeightOfPreviousIteration) ;
/**
* Generated
*/
int getNumberOfAdjacentRefinedCells() const ;
/**
* Generated
*/
void setNumberOfAdjacentRefinedCells(const int& numberOfAdjacentRefinedCells) ;
/**
* Generated
*/
InsideOutsideDomain getInsideOutsideDomain() const ;
/**
* Generated
*/
void setInsideOutsideDomain(const InsideOutsideDomain& insideOutsideDomain) ;
tarch::la::Vector<DIMENSIONS,double> getX() const ;
void setX(const tarch::la::Vector<DIMENSIONS,double>& x) ;
double getX(int elementIndex) const ;
void setX(int elementIndex, const double& x) ;
/**
* Generated
*/
int getLevel() const ;
/**
* Generated
*/
void setLevel(const int& level) ;
tarch::la::Vector<TWO_POWER_D,int> getAdjacentRanks() const ;
void setAdjacentRanks(const tarch::la::Vector<TWO_POWER_D,int>& adjacentRanks) ;
int getAdjacentRanks(int elementIndex) const ;
void setAdjacentRanks(int elementIndex, const int& adjacentRanks) ;
/**
* Generated
*/
bool getAdjacentSubtreeForksIntoOtherRank() const ;
/**
* Generated
*/
void setAdjacentSubtreeForksIntoOtherRank(const bool& adjacentSubtreeForksIntoOtherRank) ;
/**
* Generated
*/
static std::string toString(const InsideOutsideDomain& param);
/**
* Generated
*/
static std::string getInsideOutsideDomainMapping();
/**
* Generated
*/
static std::string toString(const RefinementControl& param);
/**
* Generated
*/
static std::string getRefinementControlMapping();
/**
* Generated
*/
std::string toString() const;
/**
* Generated
*/
void toString(std::ostream& out) const;
PersistentRecords getPersistentRecords() const;
/**
* Generated
*/
TestVertex convert() const;
#ifdef Parallel
protected:
static tarch::logging::Log _log;
int _senderDestinationRank;
public:
/**
* Global that represents the mpi datatype.
* There are two variants: Datatype identifies only those attributes marked with
* parallelise. FullDatatype instead identifies the whole record with all fields.
*/
static MPI_Datatype Datatype;
static MPI_Datatype FullDatatype;
/**
* Initializes the data type for the mpi operations. Has to be called
* before the very first send or receive operation is called.
*/
static void initDatatype();
static void shutdownDatatype();
enum class ExchangeMode { Blocking, NonblockingWithPollingLoopOverTests, LoopOverProbeWithBlockingReceive };
void send(int destination, int tag, bool exchangeOnlyAttributesMarkedWithParallelise, ExchangeMode mode );
void receive(int source, int tag, bool exchangeOnlyAttributesMarkedWithParallelise, ExchangeMode mode );
static bool isMessageInQueue(int tag, bool exchangeOnlyAttributesMarkedWithParallelise);
int getSenderRank() const;
#endif
};
#elif defined(Parallel) && defined(PersistentRegularSubtrees) && !defined(Asserts)
/**
* @author This class is generated by DaStGen
* DataStructureGenerator (DaStGen)
* 2007-2009 Wolfgang Eckhardt
* 2012 Tobias Weinzierl
*
* build date: 09-02-2014 14:40
*
* @date 31/03/2018 18:55
*/
class peano::grid::tests::records::TestVertex {
public:
typedef peano::grid::tests::records::TestVertexPacked Packed;
enum InsideOutsideDomain {
Inside = 0, Boundary = 1, Outside = 2
};
enum RefinementControl {
Unrefined = 0, Refined = 1, RefinementTriggered = 2, Refining = 3, EraseTriggered = 4, Erasing = 5, RefineDueToJoinThoughWorkerIsAlreadyErasing = 6, EnforceRefinementTriggered = 7
};
struct PersistentRecords {
bool _isHangingNode;
RefinementControl _refinementControl;
int _adjacentCellsHeight;
InsideOutsideDomain _insideOutsideDomain;
tarch::la::Vector<TWO_POWER_D,int> _adjacentRanks;
bool _adjacentSubtreeForksIntoOtherRank;
bool _parentRegularPersistentSubgrid;
bool _parentRegularPersistentSubgridInPreviousIteration;
/**
* Generated
*/
PersistentRecords();
/**
* Generated
*/
PersistentRecords(const bool& isHangingNode, const RefinementControl& refinementControl, const int& adjacentCellsHeight, const InsideOutsideDomain& insideOutsideDomain, const tarch::la::Vector<TWO_POWER_D,int>& adjacentRanks, const bool& adjacentSubtreeForksIntoOtherRank, const bool& parentRegularPersistentSubgrid, const bool& parentRegularPersistentSubgridInPreviousIteration);
/**
* Generated
*/
bool getIsHangingNode() const ;
/**
* Generated
*/
void setIsHangingNode(const bool& isHangingNode) ;
/**
* Generated
*/
RefinementControl getRefinementControl() const ;
/**
* Generated
*/
void setRefinementControl(const RefinementControl& refinementControl) ;
/**
* Generated
*/
int getAdjacentCellsHeight() const ;
/**
* Generated
*/
void setAdjacentCellsHeight(const int& adjacentCellsHeight) ;
/**
* Generated
*/
InsideOutsideDomain getInsideOutsideDomain() const ;
/**
* Generated
*/
void setInsideOutsideDomain(const InsideOutsideDomain& insideOutsideDomain) ;
tarch::la::Vector<TWO_POWER_D,int> getAdjacentRanks() const ;
void setAdjacentRanks(const tarch::la::Vector<TWO_POWER_D,int>& adjacentRanks) ;
/**
* Generated
*/
bool getAdjacentSubtreeForksIntoOtherRank() const ;
/**
* Generated
*/
void setAdjacentSubtreeForksIntoOtherRank(const bool& adjacentSubtreeForksIntoOtherRank) ;
/**
* Generated
*/
bool getParentRegularPersistentSubgrid() const ;
/**
* Generated
*/
void setParentRegularPersistentSubgrid(const bool& parentRegularPersistentSubgrid) ;
/**
* Generated
*/
bool getParentRegularPersistentSubgridInPreviousIteration() const ;
/**
* Generated
*/
void setParentRegularPersistentSubgridInPreviousIteration(const bool& parentRegularPersistentSubgridInPreviousIteration) ;
};
private:
PersistentRecords _persistentRecords;
int _adjacentCellsHeightOfPreviousIteration;
int _numberOfAdjacentRefinedCells;
public:
/**
* Generated
*/
TestVertex();
/**
* Generated
*/
TestVertex(const PersistentRecords& persistentRecords);
/**
* Generated
*/
TestVertex(const bool& isHangingNode, const RefinementControl& refinementControl, const int& adjacentCellsHeight, const InsideOutsideDomain& insideOutsideDomain, const tarch::la::Vector<TWO_POWER_D,int>& adjacentRanks, const bool& adjacentSubtreeForksIntoOtherRank, const bool& parentRegularPersistentSubgrid, const bool& parentRegularPersistentSubgridInPreviousIteration);
/**
* Generated
*/
TestVertex(const bool& isHangingNode, const RefinementControl& refinementControl, const int& adjacentCellsHeight, const int& adjacentCellsHeightOfPreviousIteration, const int& numberOfAdjacentRefinedCells, const InsideOutsideDomain& insideOutsideDomain, const tarch::la::Vector<TWO_POWER_D,int>& adjacentRanks, const bool& adjacentSubtreeForksIntoOtherRank, const bool& parentRegularPersistentSubgrid, const bool& parentRegularPersistentSubgridInPreviousIteration);
/**
* Generated
*/
virtual ~TestVertex();
/**
* Generated
*/
bool getIsHangingNode() const ;
/**
* Generated
*/
void setIsHangingNode(const bool& isHangingNode) ;
/**
* Generated
*/
RefinementControl getRefinementControl() const ;
/**
* Generated
*/
void setRefinementControl(const RefinementControl& refinementControl) ;
/**
* Generated
*/
int getAdjacentCellsHeight() const ;
/**
* Generated
*/
void setAdjacentCellsHeight(const int& adjacentCellsHeight) ;
/**
* Generated
*/
int getAdjacentCellsHeightOfPreviousIteration() const ;
/**
* Generated
*/
void setAdjacentCellsHeightOfPreviousIteration(const int& adjacentCellsHeightOfPreviousIteration) ;
/**
* Generated
*/
int getNumberOfAdjacentRefinedCells() const ;
/**
* Generated
*/
void setNumberOfAdjacentRefinedCells(const int& numberOfAdjacentRefinedCells) ;
/**
* Generated
*/
InsideOutsideDomain getInsideOutsideDomain() const ;
/**
* Generated
*/
void setInsideOutsideDomain(const InsideOutsideDomain& insideOutsideDomain) ;
tarch::la::Vector<TWO_POWER_D,int> getAdjacentRanks() const ;
void setAdjacentRanks(const tarch::la::Vector<TWO_POWER_D,int>& adjacentRanks) ;
int getAdjacentRanks(int elementIndex) const ;
void setAdjacentRanks(int elementIndex, const int& adjacentRanks) ;
/**
* Generated
*/
bool getAdjacentSubtreeForksIntoOtherRank() const ;
/**
* Generated
*/
void setAdjacentSubtreeForksIntoOtherRank(const bool& adjacentSubtreeForksIntoOtherRank) ;
/**
* Generated
*/
bool getParentRegularPersistentSubgrid() const ;
/**
* Generated
*/
void setParentRegularPersistentSubgrid(const bool& parentRegularPersistentSubgrid) ;
/**
* Generated
*/
bool getParentRegularPersistentSubgridInPreviousIteration() const ;
/**
* Generated
*/
void setParentRegularPersistentSubgridInPreviousIteration(const bool& parentRegularPersistentSubgridInPreviousIteration) ;
/**
* Generated
*/
static std::string toString(const InsideOutsideDomain& param);
/**
* Generated
*/
static std::string getInsideOutsideDomainMapping();
/**
* Generated
*/
static std::string toString(const RefinementControl& param);
/**
* Generated
*/
static std::string getRefinementControlMapping();
/**
* Generated
*/
std::string toString() const;
/**
* Generated
*/
void toString(std::ostream& out) const;
PersistentRecords getPersistentRecords() const;
/**
* Generated
*/
TestVertexPacked convert() const;
#ifdef Parallel
protected:
static tarch::logging::Log _log;
int _senderDestinationRank;
public:
/**
* Global that represents the mpi datatype.
* There are two variants: Datatype identifies only those attributes marked with
* parallelise. FullDatatype instead identifies the whole record with all fields.
*/
static MPI_Datatype Datatype;
static MPI_Datatype FullDatatype;
/**
* Initializes the data type for the mpi operations. Has to be called
* before the very first send or receive operation is called.
*/
static void initDatatype();
static void shutdownDatatype();
enum class ExchangeMode { Blocking, NonblockingWithPollingLoopOverTests, LoopOverProbeWithBlockingReceive };
void send(int destination, int tag, bool exchangeOnlyAttributesMarkedWithParallelise, ExchangeMode mode );
void receive(int source, int tag, bool exchangeOnlyAttributesMarkedWithParallelise, ExchangeMode mode );
static bool isMessageInQueue(int tag, bool exchangeOnlyAttributesMarkedWithParallelise);
int getSenderRank() const;
#endif
};
/**
* @author This class is generated by DaStGen
* DataStructureGenerator (DaStGen)
* 2007-2009 Wolfgang Eckhardt
* 2012 Tobias Weinzierl
*
* build date: 09-02-2014 14:40
*
* @date 31/03/2018 18:55
*/
class peano::grid::tests::records::TestVertexPacked {
public:
typedef peano::grid::tests::records::TestVertex::InsideOutsideDomain InsideOutsideDomain;
typedef peano::grid::tests::records::TestVertex::RefinementControl RefinementControl;
struct PersistentRecords {
int _adjacentCellsHeight;
tarch::la::Vector<TWO_POWER_D,int> _adjacentRanks;
bool _adjacentSubtreeForksIntoOtherRank;
bool _parentRegularPersistentSubgrid;
bool _parentRegularPersistentSubgridInPreviousIteration;
/** mapping of records:
|| Member || startbit || length
| isHangingNode | startbit 0 | #bits 1
| refinementControl | startbit 1 | #bits 3
| insideOutsideDomain | startbit 4 | #bits 2
*/
int _packedRecords0;
/**
* Generated
*/
PersistentRecords();
/**
* Generated
*/
PersistentRecords(const bool& isHangingNode, const RefinementControl& refinementControl, const int& adjacentCellsHeight, const InsideOutsideDomain& insideOutsideDomain, const tarch::la::Vector<TWO_POWER_D,int>& adjacentRanks, const bool& adjacentSubtreeForksIntoOtherRank, const bool& parentRegularPersistentSubgrid, const bool& parentRegularPersistentSubgridInPreviousIteration);
/**
* Generated
*/
bool getIsHangingNode() const ;
/**
* Generated
*/
void setIsHangingNode(const bool& isHangingNode) ;
/**
* Generated
*/
RefinementControl getRefinementControl() const ;
/**
* Generated
*/
void setRefinementControl(const RefinementControl& refinementControl) ;
/**
* Generated
*/
int getAdjacentCellsHeight() const ;
/**
* Generated
*/
void setAdjacentCellsHeight(const int& adjacentCellsHeight) ;
/**
* Generated
*/
InsideOutsideDomain getInsideOutsideDomain() const ;
/**
* Generated
*/
void setInsideOutsideDomain(const InsideOutsideDomain& insideOutsideDomain) ;
tarch::la::Vector<TWO_POWER_D,int> getAdjacentRanks() const ;
void setAdjacentRanks(const tarch::la::Vector<TWO_POWER_D,int>& adjacentRanks) ;
/**
* Generated
*/
bool getAdjacentSubtreeForksIntoOtherRank() const ;
/**
* Generated
*/
void setAdjacentSubtreeForksIntoOtherRank(const bool& adjacentSubtreeForksIntoOtherRank) ;
/**
* Generated
*/
bool getParentRegularPersistentSubgrid() const ;
/**
* Generated
*/
void setParentRegularPersistentSubgrid(const bool& parentRegularPersistentSubgrid) ;
/**
* Generated
*/
bool getParentRegularPersistentSubgridInPreviousIteration() const ;
/**
* Generated
*/
void setParentRegularPersistentSubgridInPreviousIteration(const bool& parentRegularPersistentSubgridInPreviousIteration) ;
};
private:
PersistentRecords _persistentRecords;
int _adjacentCellsHeightOfPreviousIteration;
int _numberOfAdjacentRefinedCells;
public:
/**
* Generated
*/
TestVertexPacked();
/**
* Generated
*/
TestVertexPacked(const PersistentRecords& persistentRecords);
/**
* Generated
*/
TestVertexPacked(const bool& isHangingNode, const RefinementControl& refinementControl, const int& adjacentCellsHeight, const InsideOutsideDomain& insideOutsideDomain, const tarch::la::Vector<TWO_POWER_D,int>& adjacentRanks, const bool& adjacentSubtreeForksIntoOtherRank, const bool& parentRegularPersistentSubgrid, const bool& parentRegularPersistentSubgridInPreviousIteration);
/**
* Generated
*/
TestVertexPacked(const bool& isHangingNode, const RefinementControl& refinementControl, const int& adjacentCellsHeight, const int& adjacentCellsHeightOfPreviousIteration, const int& numberOfAdjacentRefinedCells, const InsideOutsideDomain& insideOutsideDomain, const tarch::la::Vector<TWO_POWER_D,int>& adjacentRanks, const bool& adjacentSubtreeForksIntoOtherRank, const bool& parentRegularPersistentSubgrid, const bool& parentRegularPersistentSubgridInPreviousIteration);
/**
* Generated
*/
virtual ~TestVertexPacked();
/**
* Generated
*/
bool getIsHangingNode() const ;
/**
* Generated
*/
void setIsHangingNode(const bool& isHangingNode) ;
/**
* Generated
*/
RefinementControl getRefinementControl() const ;
/**
* Generated
*/
void setRefinementControl(const RefinementControl& refinementControl) ;
/**
* Generated
*/
int getAdjacentCellsHeight() const ;
/**
* Generated
*/
void setAdjacentCellsHeight(const int& adjacentCellsHeight) ;
/**
* Generated
*/
int getAdjacentCellsHeightOfPreviousIteration() const ;
/**
* Generated
*/
void setAdjacentCellsHeightOfPreviousIteration(const int& adjacentCellsHeightOfPreviousIteration) ;
/**
* Generated
*/
int getNumberOfAdjacentRefinedCells() const ;
/**
* Generated
*/
void setNumberOfAdjacentRefinedCells(const int& numberOfAdjacentRefinedCells) ;
/**
* Generated
*/
InsideOutsideDomain getInsideOutsideDomain() const ;
/**
* Generated
*/
void setInsideOutsideDomain(const InsideOutsideDomain& insideOutsideDomain) ;
tarch::la::Vector<TWO_POWER_D,int> getAdjacentRanks() const ;
void setAdjacentRanks(const tarch::la::Vector<TWO_POWER_D,int>& adjacentRanks) ;
int getAdjacentRanks(int elementIndex) const ;
void setAdjacentRanks(int elementIndex, const int& adjacentRanks) ;
/**
* Generated
*/
bool getAdjacentSubtreeForksIntoOtherRank() const ;
/**
* Generated
*/
void setAdjacentSubtreeForksIntoOtherRank(const bool& adjacentSubtreeForksIntoOtherRank) ;
/**
* Generated
*/
bool getParentRegularPersistentSubgrid() const ;
/**
* Generated
*/
void setParentRegularPersistentSubgrid(const bool& parentRegularPersistentSubgrid) ;
/**
* Generated
*/
bool getParentRegularPersistentSubgridInPreviousIteration() const ;
/**
* Generated
*/
void setParentRegularPersistentSubgridInPreviousIteration(const bool& parentRegularPersistentSubgridInPreviousIteration) ;
/**
* Generated
*/
static std::string toString(const InsideOutsideDomain& param);
/**
* Generated
*/
static std::string getInsideOutsideDomainMapping();
/**
* Generated
*/
static std::string toString(const RefinementControl& param);
/**
* Generated
*/
static std::string getRefinementControlMapping();
/**
* Generated
*/
std::string toString() const;
/**
* Generated
*/
void toString(std::ostream& out) const;
PersistentRecords getPersistentRecords() const;
/**
* Generated
*/
TestVertex convert() const;
#ifdef Parallel
protected:
static tarch::logging::Log _log;
int _senderDestinationRank;
public:
/**
* Global that represents the mpi datatype.
* There are two variants: Datatype identifies only those attributes marked with
* parallelise. FullDatatype instead identifies the whole record with all fields.
*/
static MPI_Datatype Datatype;
static MPI_Datatype FullDatatype;
/**
* Initializes the data type for the mpi operations. Has to be called
* before the very first send or receive operation is called.
*/
static void initDatatype();
static void shutdownDatatype();
enum class ExchangeMode { Blocking, NonblockingWithPollingLoopOverTests, LoopOverProbeWithBlockingReceive };
void send(int destination, int tag, bool exchangeOnlyAttributesMarkedWithParallelise, ExchangeMode mode );
void receive(int source, int tag, bool exchangeOnlyAttributesMarkedWithParallelise, ExchangeMode mode );
static bool isMessageInQueue(int tag, bool exchangeOnlyAttributesMarkedWithParallelise);
int getSenderRank() const;
#endif
};
#elif defined(PersistentRegularSubtrees) && !defined(Asserts) && !defined(Parallel)
/**
* @author This class is generated by DaStGen
* DataStructureGenerator (DaStGen)
* 2007-2009 Wolfgang Eckhardt
* 2012 Tobias Weinzierl
*
* build date: 09-02-2014 14:40
*
* @date 31/03/2018 18:55
*/
class peano::grid::tests::records::TestVertex {
public:
typedef peano::grid::tests::records::TestVertexPacked Packed;
enum InsideOutsideDomain {
Inside = 0, Boundary = 1, Outside = 2
};
enum RefinementControl {
Unrefined = 0, Refined = 1, RefinementTriggered = 2, Refining = 3, EraseTriggered = 4, Erasing = 5, RefineDueToJoinThoughWorkerIsAlreadyErasing = 6, EnforceRefinementTriggered = 7
};
struct PersistentRecords {
bool _isHangingNode;
RefinementControl _refinementControl;
int _adjacentCellsHeight;
InsideOutsideDomain _insideOutsideDomain;
bool _parentRegularPersistentSubgrid;
bool _parentRegularPersistentSubgridInPreviousIteration;
/**
* Generated
*/
PersistentRecords();
/**
* Generated
*/
PersistentRecords(const bool& isHangingNode, const RefinementControl& refinementControl, const int& adjacentCellsHeight, const InsideOutsideDomain& insideOutsideDomain, const bool& parentRegularPersistentSubgrid, const bool& parentRegularPersistentSubgridInPreviousIteration);
/**
* Generated
*/
bool getIsHangingNode() const ;
/**
* Generated
*/
void setIsHangingNode(const bool& isHangingNode) ;
/**
* Generated
*/
RefinementControl getRefinementControl() const ;
/**
* Generated
*/
void setRefinementControl(const RefinementControl& refinementControl) ;
/**
* Generated
*/
int getAdjacentCellsHeight() const ;
/**
* Generated
*/
void setAdjacentCellsHeight(const int& adjacentCellsHeight) ;
/**
* Generated
*/
InsideOutsideDomain getInsideOutsideDomain() const ;
/**
* Generated
*/
void setInsideOutsideDomain(const InsideOutsideDomain& insideOutsideDomain) ;
/**
* Generated
*/
bool getParentRegularPersistentSubgrid() const ;
/**
* Generated
*/
void setParentRegularPersistentSubgrid(const bool& parentRegularPersistentSubgrid) ;
/**
* Generated
*/
bool getParentRegularPersistentSubgridInPreviousIteration() const ;
/**
* Generated
*/
void setParentRegularPersistentSubgridInPreviousIteration(const bool& parentRegularPersistentSubgridInPreviousIteration) ;
};
private:
PersistentRecords _persistentRecords;
int _adjacentCellsHeightOfPreviousIteration;
int _numberOfAdjacentRefinedCells;
public:
/**
* Generated
*/
TestVertex();
/**
* Generated
*/
TestVertex(const PersistentRecords& persistentRecords);
/**
* Generated
*/
TestVertex(const bool& isHangingNode, const RefinementControl& refinementControl, const int& adjacentCellsHeight, const InsideOutsideDomain& insideOutsideDomain, const bool& parentRegularPersistentSubgrid, const bool& parentRegularPersistentSubgridInPreviousIteration);
/**
* Generated
*/
TestVertex(const bool& isHangingNode, const RefinementControl& refinementControl, const int& adjacentCellsHeight, const int& adjacentCellsHeightOfPreviousIteration, const int& numberOfAdjacentRefinedCells, const InsideOutsideDomain& insideOutsideDomain, const bool& parentRegularPersistentSubgrid, const bool& parentRegularPersistentSubgridInPreviousIteration);
/**
* Generated
*/
virtual ~TestVertex();
/**
* Generated
*/
bool getIsHangingNode() const ;
/**
* Generated
*/
void setIsHangingNode(const bool& isHangingNode) ;
/**
* Generated
*/
RefinementControl getRefinementControl() const ;
/**
* Generated
*/
void setRefinementControl(const RefinementControl& refinementControl) ;
/**
* Generated
*/
int getAdjacentCellsHeight() const ;
/**
* Generated
*/
void setAdjacentCellsHeight(const int& adjacentCellsHeight) ;
/**
* Generated
*/
int getAdjacentCellsHeightOfPreviousIteration() const ;
/**
* Generated
*/
void setAdjacentCellsHeightOfPreviousIteration(const int& adjacentCellsHeightOfPreviousIteration) ;
/**
* Generated
*/
int getNumberOfAdjacentRefinedCells() const ;
/**
* Generated
*/
void setNumberOfAdjacentRefinedCells(const int& numberOfAdjacentRefinedCells) ;
/**
* Generated
*/
InsideOutsideDomain getInsideOutsideDomain() const ;
/**
* Generated
*/
void setInsideOutsideDomain(const InsideOutsideDomain& insideOutsideDomain) ;
/**
* Generated
*/
bool getParentRegularPersistentSubgrid() const ;
/**
* Generated
*/
void setParentRegularPersistentSubgrid(const bool& parentRegularPersistentSubgrid) ;
/**
* Generated
*/
bool getParentRegularPersistentSubgridInPreviousIteration() const ;
/**
* Generated
*/
void setParentRegularPersistentSubgridInPreviousIteration(const bool& parentRegularPersistentSubgridInPreviousIteration) ;
/**
* Generated
*/
static std::string toString(const InsideOutsideDomain& param);
/**
* Generated
*/
static std::string getInsideOutsideDomainMapping();
/**
* Generated
*/
static std::string toString(const RefinementControl& param);
/**
* Generated
*/
static std::string getRefinementControlMapping();
/**
* Generated
*/
std::string toString() const;
/**
* Generated
*/
void toString(std::ostream& out) const;
PersistentRecords getPersistentRecords() const;
/**
* Generated
*/
TestVertexPacked convert() const;
#ifdef Parallel
protected:
static tarch::logging::Log _log;
int _senderDestinationRank;
public:
/**
* Global that represents the mpi datatype.
* There are two variants: Datatype identifies only those attributes marked with
* parallelise. FullDatatype instead identifies the whole record with all fields.
*/
static MPI_Datatype Datatype;
static MPI_Datatype FullDatatype;
/**
* Initializes the data type for the mpi operations. Has to be called
* before the very first send or receive operation is called.
*/
static void initDatatype();
static void shutdownDatatype();
enum class ExchangeMode { Blocking, NonblockingWithPollingLoopOverTests, LoopOverProbeWithBlockingReceive };
void send(int destination, int tag, bool exchangeOnlyAttributesMarkedWithParallelise, ExchangeMode mode );
void receive(int source, int tag, bool exchangeOnlyAttributesMarkedWithParallelise, ExchangeMode mode );
static bool isMessageInQueue(int tag, bool exchangeOnlyAttributesMarkedWithParallelise);
int getSenderRank() const;
#endif
};
/**
* @author This class is generated by DaStGen
* DataStructureGenerator (DaStGen)
* 2007-2009 Wolfgang Eckhardt
* 2012 Tobias Weinzierl
*
* build date: 09-02-2014 14:40
*
* @date 31/03/2018 18:55
*/
class peano::grid::tests::records::TestVertexPacked {
public:
typedef peano::grid::tests::records::TestVertex::InsideOutsideDomain InsideOutsideDomain;
typedef peano::grid::tests::records::TestVertex::RefinementControl RefinementControl;
struct PersistentRecords {
int _adjacentCellsHeight;
bool _parentRegularPersistentSubgrid;
bool _parentRegularPersistentSubgridInPreviousIteration;
/** mapping of records:
|| Member || startbit || length
| isHangingNode | startbit 0 | #bits 1
| refinementControl | startbit 1 | #bits 3
| insideOutsideDomain | startbit 4 | #bits 2
*/
int _packedRecords0;
/**
* Generated
*/
PersistentRecords();
/**
* Generated
*/
PersistentRecords(const bool& isHangingNode, const RefinementControl& refinementControl, const int& adjacentCellsHeight, const InsideOutsideDomain& insideOutsideDomain, const bool& parentRegularPersistentSubgrid, const bool& parentRegularPersistentSubgridInPreviousIteration);
/**
* Generated
*/
bool getIsHangingNode() const ;
/**
* Generated
*/
void setIsHangingNode(const bool& isHangingNode) ;
/**
* Generated
*/
RefinementControl getRefinementControl() const ;
/**
* Generated
*/
void setRefinementControl(const RefinementControl& refinementControl) ;
/**
* Generated
*/
int getAdjacentCellsHeight() const ;
/**
* Generated
*/
void setAdjacentCellsHeight(const int& adjacentCellsHeight) ;
/**
* Generated
*/
InsideOutsideDomain getInsideOutsideDomain() const ;
/**
* Generated
*/
void setInsideOutsideDomain(const InsideOutsideDomain& insideOutsideDomain) ;
/**
* Generated
*/
bool getParentRegularPersistentSubgrid() const ;
/**
* Generated
*/
void setParentRegularPersistentSubgrid(const bool& parentRegularPersistentSubgrid) ;
/**
* Generated
*/
bool getParentRegularPersistentSubgridInPreviousIteration() const ;
/**
* Generated
*/
void setParentRegularPersistentSubgridInPreviousIteration(const bool& parentRegularPersistentSubgridInPreviousIteration) ;
};
private:
PersistentRecords _persistentRecords;
int _adjacentCellsHeightOfPreviousIteration;
int _numberOfAdjacentRefinedCells;
public:
/**
* Generated
*/
TestVertexPacked();
/**
* Generated
*/
TestVertexPacked(const PersistentRecords& persistentRecords);
/**
* Generated
*/
TestVertexPacked(const bool& isHangingNode, const RefinementControl& refinementControl, const int& adjacentCellsHeight, const InsideOutsideDomain& insideOutsideDomain, const bool& parentRegularPersistentSubgrid, const bool& parentRegularPersistentSubgridInPreviousIteration);
/**
* Generated
*/
TestVertexPacked(const bool& isHangingNode, const RefinementControl& refinementControl, const int& adjacentCellsHeight, const int& adjacentCellsHeightOfPreviousIteration, const int& numberOfAdjacentRefinedCells, const InsideOutsideDomain& insideOutsideDomain, const bool& parentRegularPersistentSubgrid, const bool& parentRegularPersistentSubgridInPreviousIteration);
/**
* Generated
*/
virtual ~TestVertexPacked();
/**
* Generated
*/
bool getIsHangingNode() const ;
/**
* Generated
*/
void setIsHangingNode(const bool& isHangingNode) ;
/**
* Generated
*/
RefinementControl getRefinementControl() const ;
/**
* Generated
*/
void setRefinementControl(const RefinementControl& refinementControl) ;
/**
* Generated
*/
int getAdjacentCellsHeight() const ;
/**
* Generated
*/
void setAdjacentCellsHeight(const int& adjacentCellsHeight) ;
/**
* Generated
*/
int getAdjacentCellsHeightOfPreviousIteration() const ;
/**
* Generated
*/
void setAdjacentCellsHeightOfPreviousIteration(const int& adjacentCellsHeightOfPreviousIteration) ;
/**
* Generated
*/
int getNumberOfAdjacentRefinedCells() const ;
/**
* Generated
*/
void setNumberOfAdjacentRefinedCells(const int& numberOfAdjacentRefinedCells) ;
/**
* Generated
*/
InsideOutsideDomain getInsideOutsideDomain() const ;
/**
* Generated
*/
void setInsideOutsideDomain(const InsideOutsideDomain& insideOutsideDomain) ;
/**
* Generated
*/
bool getParentRegularPersistentSubgrid() const ;
/**
* Generated
*/
void setParentRegularPersistentSubgrid(const bool& parentRegularPersistentSubgrid) ;
/**
* Generated
*/
bool getParentRegularPersistentSubgridInPreviousIteration() const ;
/**
* Generated
*/
void setParentRegularPersistentSubgridInPreviousIteration(const bool& parentRegularPersistentSubgridInPreviousIteration) ;
/**
* Generated
*/
static std::string toString(const InsideOutsideDomain& param);
/**
* Generated
*/
static std::string getInsideOutsideDomainMapping();
/**
* Generated
*/
static std::string toString(const RefinementControl& param);
/**
* Generated
*/
static std::string getRefinementControlMapping();
/**
* Generated
*/
std::string toString() const;
/**
* Generated
*/
void toString(std::ostream& out) const;
PersistentRecords getPersistentRecords() const;
/**
* Generated
*/
TestVertex convert() const;
#ifdef Parallel
protected:
static tarch::logging::Log _log;
int _senderDestinationRank;
public:
/**
* Global that represents the mpi datatype.
* There are two variants: Datatype identifies only those attributes marked with
* parallelise. FullDatatype instead identifies the whole record with all fields.
*/
static MPI_Datatype Datatype;
static MPI_Datatype FullDatatype;
/**
* Initializes the data type for the mpi operations. Has to be called
* before the very first send or receive operation is called.
*/
static void initDatatype();
static void shutdownDatatype();
enum class ExchangeMode { Blocking, NonblockingWithPollingLoopOverTests, LoopOverProbeWithBlockingReceive };
void send(int destination, int tag, bool exchangeOnlyAttributesMarkedWithParallelise, ExchangeMode mode );
void receive(int source, int tag, bool exchangeOnlyAttributesMarkedWithParallelise, ExchangeMode mode );
static bool isMessageInQueue(int tag, bool exchangeOnlyAttributesMarkedWithParallelise);
int getSenderRank() const;
#endif
};
#elif !defined(PersistentRegularSubtrees) && defined(Asserts) && !defined(Parallel)
/**
* @author This class is generated by DaStGen
* DataStructureGenerator (DaStGen)
* 2007-2009 Wolfgang Eckhardt
* 2012 Tobias Weinzierl
*
* build date: 09-02-2014 14:40
*
* @date 31/03/2018 18:55
*/
class peano::grid::tests::records::TestVertex {
public:
typedef peano::grid::tests::records::TestVertexPacked Packed;
enum InsideOutsideDomain {
Inside = 0, Boundary = 1, Outside = 2
};
enum RefinementControl {
Unrefined = 0, Refined = 1, RefinementTriggered = 2, Refining = 3, EraseTriggered = 4, Erasing = 5, RefineDueToJoinThoughWorkerIsAlreadyErasing = 6, EnforceRefinementTriggered = 7
};
struct PersistentRecords {
bool _isHangingNode;
RefinementControl _refinementControl;
int _adjacentCellsHeight;
InsideOutsideDomain _insideOutsideDomain;
tarch::la::Vector<DIMENSIONS,double> _x;
int _level;
/**
* Generated
*/
PersistentRecords();
/**
* Generated
*/
PersistentRecords(const bool& isHangingNode, const RefinementControl& refinementControl, const int& adjacentCellsHeight, const InsideOutsideDomain& insideOutsideDomain, const tarch::la::Vector<DIMENSIONS,double>& x, const int& level);
/**
* Generated
*/
bool getIsHangingNode() const ;
/**
* Generated
*/
void setIsHangingNode(const bool& isHangingNode) ;
/**
* Generated
*/
RefinementControl getRefinementControl() const ;
/**
* Generated
*/
void setRefinementControl(const RefinementControl& refinementControl) ;
/**
* Generated
*/
int getAdjacentCellsHeight() const ;
/**
* Generated
*/
void setAdjacentCellsHeight(const int& adjacentCellsHeight) ;
/**
* Generated
*/
InsideOutsideDomain getInsideOutsideDomain() const ;
/**
* Generated
*/
void setInsideOutsideDomain(const InsideOutsideDomain& insideOutsideDomain) ;
tarch::la::Vector<DIMENSIONS,double> getX() const ;
void setX(const tarch::la::Vector<DIMENSIONS,double>& x) ;
/**
* Generated
*/
int getLevel() const ;
/**
* Generated
*/
void setLevel(const int& level) ;
};
private:
PersistentRecords _persistentRecords;
int _adjacentCellsHeightOfPreviousIteration;
int _numberOfAdjacentRefinedCells;
public:
/**
* Generated
*/
TestVertex();
/**
* Generated
*/
TestVertex(const PersistentRecords& persistentRecords);
/**
* Generated
*/
TestVertex(const bool& isHangingNode, const RefinementControl& refinementControl, const int& adjacentCellsHeight, const InsideOutsideDomain& insideOutsideDomain, const tarch::la::Vector<DIMENSIONS,double>& x, const int& level);
/**
* Generated
*/
TestVertex(const bool& isHangingNode, const RefinementControl& refinementControl, const int& adjacentCellsHeight, const int& adjacentCellsHeightOfPreviousIteration, const int& numberOfAdjacentRefinedCells, const InsideOutsideDomain& insideOutsideDomain, const tarch::la::Vector<DIMENSIONS,double>& x, const int& level);
/**
* Generated
*/
virtual ~TestVertex();
/**
* Generated
*/
bool getIsHangingNode() const ;
/**
* Generated
*/
void setIsHangingNode(const bool& isHangingNode) ;
/**
* Generated
*/
RefinementControl getRefinementControl() const ;
/**
* Generated
*/
void setRefinementControl(const RefinementControl& refinementControl) ;
/**
* Generated
*/
int getAdjacentCellsHeight() const ;
/**
* Generated
*/
void setAdjacentCellsHeight(const int& adjacentCellsHeight) ;
/**
* Generated
*/
int getAdjacentCellsHeightOfPreviousIteration() const ;
/**
* Generated
*/
void setAdjacentCellsHeightOfPreviousIteration(const int& adjacentCellsHeightOfPreviousIteration) ;
/**
* Generated
*/
int getNumberOfAdjacentRefinedCells() const ;
/**
* Generated
*/
void setNumberOfAdjacentRefinedCells(const int& numberOfAdjacentRefinedCells) ;
/**
* Generated
*/
InsideOutsideDomain getInsideOutsideDomain() const ;
/**
* Generated
*/
void setInsideOutsideDomain(const InsideOutsideDomain& insideOutsideDomain) ;
tarch::la::Vector<DIMENSIONS,double> getX() const ;
void setX(const tarch::la::Vector<DIMENSIONS,double>& x) ;
double getX(int elementIndex) const ;
void setX(int elementIndex, const double& x) ;
/**
* Generated
*/
int getLevel() const ;
/**
* Generated
*/
void setLevel(const int& level) ;
/**
* Generated
*/
static std::string toString(const InsideOutsideDomain& param);
/**
* Generated
*/
static std::string getInsideOutsideDomainMapping();
/**
* Generated
*/
static std::string toString(const RefinementControl& param);
/**
* Generated
*/
static std::string getRefinementControlMapping();
/**
* Generated
*/
std::string toString() const;
/**
* Generated
*/
void toString(std::ostream& out) const;
PersistentRecords getPersistentRecords() const;
/**
* Generated
*/
TestVertexPacked convert() const;
#ifdef Parallel
protected:
static tarch::logging::Log _log;
int _senderDestinationRank;
public:
/**
* Global that represents the mpi datatype.
* There are two variants: Datatype identifies only those attributes marked with
* parallelise. FullDatatype instead identifies the whole record with all fields.
*/
static MPI_Datatype Datatype;
static MPI_Datatype FullDatatype;
/**
* Initializes the data type for the mpi operations. Has to be called
* before the very first send or receive operation is called.
*/
static void initDatatype();
static void shutdownDatatype();
enum class ExchangeMode { Blocking, NonblockingWithPollingLoopOverTests, LoopOverProbeWithBlockingReceive };
void send(int destination, int tag, bool exchangeOnlyAttributesMarkedWithParallelise, ExchangeMode mode );
void receive(int source, int tag, bool exchangeOnlyAttributesMarkedWithParallelise, ExchangeMode mode );
static bool isMessageInQueue(int tag, bool exchangeOnlyAttributesMarkedWithParallelise);
int getSenderRank() const;
#endif
};
/**
* @author This class is generated by DaStGen
* DataStructureGenerator (DaStGen)
* 2007-2009 Wolfgang Eckhardt
* 2012 Tobias Weinzierl
*
* build date: 09-02-2014 14:40
*
* @date 31/03/2018 18:55
*/
class peano::grid::tests::records::TestVertexPacked {
public:
typedef peano::grid::tests::records::TestVertex::InsideOutsideDomain InsideOutsideDomain;
typedef peano::grid::tests::records::TestVertex::RefinementControl RefinementControl;
struct PersistentRecords {
int _adjacentCellsHeight;
tarch::la::Vector<DIMENSIONS,double> _x;
int _level;
/** mapping of records:
|| Member || startbit || length
| isHangingNode | startbit 0 | #bits 1
| refinementControl | startbit 1 | #bits 3
| insideOutsideDomain | startbit 4 | #bits 2
*/
int _packedRecords0;
/**
* Generated
*/
PersistentRecords();
/**
* Generated
*/
PersistentRecords(const bool& isHangingNode, const RefinementControl& refinementControl, const int& adjacentCellsHeight, const InsideOutsideDomain& insideOutsideDomain, const tarch::la::Vector<DIMENSIONS,double>& x, const int& level);
/**
* Generated
*/
bool getIsHangingNode() const ;
/**
* Generated
*/
void setIsHangingNode(const bool& isHangingNode) ;
/**
* Generated
*/
RefinementControl getRefinementControl() const ;
/**
* Generated
*/
void setRefinementControl(const RefinementControl& refinementControl) ;
/**
* Generated
*/
int getAdjacentCellsHeight() const ;
/**
* Generated
*/
void setAdjacentCellsHeight(const int& adjacentCellsHeight) ;
/**
* Generated
*/
InsideOutsideDomain getInsideOutsideDomain() const ;
/**
* Generated
*/
void setInsideOutsideDomain(const InsideOutsideDomain& insideOutsideDomain) ;
tarch::la::Vector<DIMENSIONS,double> getX() const ;
void setX(const tarch::la::Vector<DIMENSIONS,double>& x) ;
/**
* Generated
*/
int getLevel() const ;
/**
* Generated
*/
void setLevel(const int& level) ;
};
private:
PersistentRecords _persistentRecords;
int _adjacentCellsHeightOfPreviousIteration;
int _numberOfAdjacentRefinedCells;
public:
/**
* Generated
*/
TestVertexPacked();
/**
* Generated
*/
TestVertexPacked(const PersistentRecords& persistentRecords);
/**
* Generated
*/
TestVertexPacked(const bool& isHangingNode, const RefinementControl& refinementControl, const int& adjacentCellsHeight, const InsideOutsideDomain& insideOutsideDomain, const tarch::la::Vector<DIMENSIONS,double>& x, const int& level);
/**
* Generated
*/
TestVertexPacked(const bool& isHangingNode, const RefinementControl& refinementControl, const int& adjacentCellsHeight, const int& adjacentCellsHeightOfPreviousIteration, const int& numberOfAdjacentRefinedCells, const InsideOutsideDomain& insideOutsideDomain, const tarch::la::Vector<DIMENSIONS,double>& x, const int& level);
/**
* Generated
*/
virtual ~TestVertexPacked();
/**
* Generated
*/
bool getIsHangingNode() const ;
/**
* Generated
*/
void setIsHangingNode(const bool& isHangingNode) ;
/**
* Generated
*/
RefinementControl getRefinementControl() const ;
/**
* Generated
*/
void setRefinementControl(const RefinementControl& refinementControl) ;
/**
* Generated
*/
int getAdjacentCellsHeight() const ;
/**
* Generated
*/
void setAdjacentCellsHeight(const int& adjacentCellsHeight) ;
/**
* Generated
*/
int getAdjacentCellsHeightOfPreviousIteration() const ;
/**
* Generated
*/
void setAdjacentCellsHeightOfPreviousIteration(const int& adjacentCellsHeightOfPreviousIteration) ;
/**
* Generated
*/
int getNumberOfAdjacentRefinedCells() const ;
/**
* Generated
*/
void setNumberOfAdjacentRefinedCells(const int& numberOfAdjacentRefinedCells) ;
/**
* Generated
*/
InsideOutsideDomain getInsideOutsideDomain() const ;
/**
* Generated
*/
void setInsideOutsideDomain(const InsideOutsideDomain& insideOutsideDomain) ;
tarch::la::Vector<DIMENSIONS,double> getX() const ;
void setX(const tarch::la::Vector<DIMENSIONS,double>& x) ;
double getX(int elementIndex) const ;
void setX(int elementIndex, const double& x) ;
/**
* Generated
*/
int getLevel() const ;
/**
* Generated
*/
void setLevel(const int& level) ;
/**
* Generated
*/
static std::string toString(const InsideOutsideDomain& param);
/**
* Generated
*/
static std::string getInsideOutsideDomainMapping();
/**
* Generated
*/
static std::string toString(const RefinementControl& param);
/**
* Generated
*/
static std::string getRefinementControlMapping();
/**
* Generated
*/
std::string toString() const;
/**
* Generated
*/
void toString(std::ostream& out) const;
PersistentRecords getPersistentRecords() const;
/**
* Generated
*/
TestVertex convert() const;
#ifdef Parallel
protected:
static tarch::logging::Log _log;
int _senderDestinationRank;
public:
/**
* Global that represents the mpi datatype.
* There are two variants: Datatype identifies only those attributes marked with
* parallelise. FullDatatype instead identifies the whole record with all fields.
*/
static MPI_Datatype Datatype;
static MPI_Datatype FullDatatype;
/**
* Initializes the data type for the mpi operations. Has to be called
* before the very first send or receive operation is called.
*/
static void initDatatype();
static void shutdownDatatype();
enum class ExchangeMode { Blocking, NonblockingWithPollingLoopOverTests, LoopOverProbeWithBlockingReceive };
void send(int destination, int tag, bool exchangeOnlyAttributesMarkedWithParallelise, ExchangeMode mode );
void receive(int source, int tag, bool exchangeOnlyAttributesMarkedWithParallelise, ExchangeMode mode );
static bool isMessageInQueue(int tag, bool exchangeOnlyAttributesMarkedWithParallelise);
int getSenderRank() const;
#endif
};
#elif defined(Parallel) && !defined(PersistentRegularSubtrees) && !defined(Asserts)
/**
* @author This class is generated by DaStGen
* DataStructureGenerator (DaStGen)
* 2007-2009 Wolfgang Eckhardt
* 2012 Tobias Weinzierl
*
* build date: 09-02-2014 14:40
*
* @date 31/03/2018 18:55
*/
class peano::grid::tests::records::TestVertex {
public:
typedef peano::grid::tests::records::TestVertexPacked Packed;
enum InsideOutsideDomain {
Inside = 0, Boundary = 1, Outside = 2
};
enum RefinementControl {
Unrefined = 0, Refined = 1, RefinementTriggered = 2, Refining = 3, EraseTriggered = 4, Erasing = 5, RefineDueToJoinThoughWorkerIsAlreadyErasing = 6, EnforceRefinementTriggered = 7
};
struct PersistentRecords {
bool _isHangingNode;
RefinementControl _refinementControl;
int _adjacentCellsHeight;
InsideOutsideDomain _insideOutsideDomain;
tarch::la::Vector<TWO_POWER_D,int> _adjacentRanks;
bool _adjacentSubtreeForksIntoOtherRank;
/**
* Generated
*/
PersistentRecords();
/**
* Generated
*/
PersistentRecords(const bool& isHangingNode, const RefinementControl& refinementControl, const int& adjacentCellsHeight, const InsideOutsideDomain& insideOutsideDomain, const tarch::la::Vector<TWO_POWER_D,int>& adjacentRanks, const bool& adjacentSubtreeForksIntoOtherRank);
/**
* Generated
*/
bool getIsHangingNode() const ;
/**
* Generated
*/
void setIsHangingNode(const bool& isHangingNode) ;
/**
* Generated
*/
RefinementControl getRefinementControl() const ;
/**
* Generated
*/
void setRefinementControl(const RefinementControl& refinementControl) ;
/**
* Generated
*/
int getAdjacentCellsHeight() const ;
/**
* Generated
*/
void setAdjacentCellsHeight(const int& adjacentCellsHeight) ;
/**
* Generated
*/
InsideOutsideDomain getInsideOutsideDomain() const ;
/**
* Generated
*/
void setInsideOutsideDomain(const InsideOutsideDomain& insideOutsideDomain) ;
tarch::la::Vector<TWO_POWER_D,int> getAdjacentRanks() const ;
void setAdjacentRanks(const tarch::la::Vector<TWO_POWER_D,int>& adjacentRanks) ;
/**
* Generated
*/
bool getAdjacentSubtreeForksIntoOtherRank() const ;
/**
* Generated
*/
void setAdjacentSubtreeForksIntoOtherRank(const bool& adjacentSubtreeForksIntoOtherRank) ;
};
private:
PersistentRecords _persistentRecords;
int _adjacentCellsHeightOfPreviousIteration;
int _numberOfAdjacentRefinedCells;
public:
/**
* Generated
*/
TestVertex();
/**
* Generated
*/
TestVertex(const PersistentRecords& persistentRecords);
/**
* Generated
*/
TestVertex(const bool& isHangingNode, const RefinementControl& refinementControl, const int& adjacentCellsHeight, const InsideOutsideDomain& insideOutsideDomain, const tarch::la::Vector<TWO_POWER_D,int>& adjacentRanks, const bool& adjacentSubtreeForksIntoOtherRank);
/**
* Generated
*/
TestVertex(const bool& isHangingNode, const RefinementControl& refinementControl, const int& adjacentCellsHeight, const int& adjacentCellsHeightOfPreviousIteration, const int& numberOfAdjacentRefinedCells, const InsideOutsideDomain& insideOutsideDomain, const tarch::la::Vector<TWO_POWER_D,int>& adjacentRanks, const bool& adjacentSubtreeForksIntoOtherRank);
/**
* Generated
*/
virtual ~TestVertex();
/**
* Generated
*/
bool getIsHangingNode() const ;
/**
* Generated
*/
void setIsHangingNode(const bool& isHangingNode) ;
/**
* Generated
*/
RefinementControl getRefinementControl() const ;
/**
* Generated
*/
void setRefinementControl(const RefinementControl& refinementControl) ;
/**
* Generated
*/
int getAdjacentCellsHeight() const ;
/**
* Generated
*/
void setAdjacentCellsHeight(const int& adjacentCellsHeight) ;
/**
* Generated
*/
int getAdjacentCellsHeightOfPreviousIteration() const ;
/**
* Generated
*/
void setAdjacentCellsHeightOfPreviousIteration(const int& adjacentCellsHeightOfPreviousIteration) ;
/**
* Generated
*/
int getNumberOfAdjacentRefinedCells() const ;
/**
* Generated
*/
void setNumberOfAdjacentRefinedCells(const int& numberOfAdjacentRefinedCells) ;
/**
* Generated
*/
InsideOutsideDomain getInsideOutsideDomain() const ;
/**
* Generated
*/
void setInsideOutsideDomain(const InsideOutsideDomain& insideOutsideDomain) ;
tarch::la::Vector<TWO_POWER_D,int> getAdjacentRanks() const ;
void setAdjacentRanks(const tarch::la::Vector<TWO_POWER_D,int>& adjacentRanks) ;
int getAdjacentRanks(int elementIndex) const ;
void setAdjacentRanks(int elementIndex, const int& adjacentRanks) ;
/**
* Generated
*/
bool getAdjacentSubtreeForksIntoOtherRank() const ;
/**
* Generated
*/
void setAdjacentSubtreeForksIntoOtherRank(const bool& adjacentSubtreeForksIntoOtherRank) ;
/**
* Generated
*/
static std::string toString(const InsideOutsideDomain& param);
/**
* Generated
*/
static std::string getInsideOutsideDomainMapping();
/**
* Generated
*/
static std::string toString(const RefinementControl& param);
/**
* Generated
*/
static std::string getRefinementControlMapping();
/**
* Generated
*/
std::string toString() const;
/**
* Generated
*/
void toString(std::ostream& out) const;
PersistentRecords getPersistentRecords() const;
/**
* Generated
*/
TestVertexPacked convert() const;
#ifdef Parallel
protected:
static tarch::logging::Log _log;
int _senderDestinationRank;
public:
/**
* Global that represents the mpi datatype.
* There are two variants: Datatype identifies only those attributes marked with
* parallelise. FullDatatype instead identifies the whole record with all fields.
*/
static MPI_Datatype Datatype;
static MPI_Datatype FullDatatype;
/**
* Initializes the data type for the mpi operations. Has to be called
* before the very first send or receive operation is called.
*/
static void initDatatype();
static void shutdownDatatype();
enum class ExchangeMode { Blocking, NonblockingWithPollingLoopOverTests, LoopOverProbeWithBlockingReceive };
void send(int destination, int tag, bool exchangeOnlyAttributesMarkedWithParallelise, ExchangeMode mode );
void receive(int source, int tag, bool exchangeOnlyAttributesMarkedWithParallelise, ExchangeMode mode );
static bool isMessageInQueue(int tag, bool exchangeOnlyAttributesMarkedWithParallelise);
int getSenderRank() const;
#endif
};
/**
* @author This class is generated by DaStGen
* DataStructureGenerator (DaStGen)
* 2007-2009 Wolfgang Eckhardt
* 2012 Tobias Weinzierl
*
* build date: 09-02-2014 14:40
*
* @date 31/03/2018 18:55
*/
class peano::grid::tests::records::TestVertexPacked {
public:
typedef peano::grid::tests::records::TestVertex::InsideOutsideDomain InsideOutsideDomain;
typedef peano::grid::tests::records::TestVertex::RefinementControl RefinementControl;
struct PersistentRecords {
int _adjacentCellsHeight;
tarch::la::Vector<TWO_POWER_D,int> _adjacentRanks;
bool _adjacentSubtreeForksIntoOtherRank;
/** mapping of records:
|| Member || startbit || length
| isHangingNode | startbit 0 | #bits 1
| refinementControl | startbit 1 | #bits 3
| insideOutsideDomain | startbit 4 | #bits 2
*/
int _packedRecords0;
/**
* Generated
*/
PersistentRecords();
/**
* Generated
*/
PersistentRecords(const bool& isHangingNode, const RefinementControl& refinementControl, const int& adjacentCellsHeight, const InsideOutsideDomain& insideOutsideDomain, const tarch::la::Vector<TWO_POWER_D,int>& adjacentRanks, const bool& adjacentSubtreeForksIntoOtherRank);
/**
* Generated
*/
bool getIsHangingNode() const ;
/**
* Generated
*/
void setIsHangingNode(const bool& isHangingNode) ;
/**
* Generated
*/
RefinementControl getRefinementControl() const ;
/**
* Generated
*/
void setRefinementControl(const RefinementControl& refinementControl) ;
/**
* Generated
*/
int getAdjacentCellsHeight() const ;
/**
* Generated
*/
void setAdjacentCellsHeight(const int& adjacentCellsHeight) ;
/**
* Generated
*/
InsideOutsideDomain getInsideOutsideDomain() const ;
/**
* Generated
*/
void setInsideOutsideDomain(const InsideOutsideDomain& insideOutsideDomain) ;
tarch::la::Vector<TWO_POWER_D,int> getAdjacentRanks() const ;
void setAdjacentRanks(const tarch::la::Vector<TWO_POWER_D,int>& adjacentRanks) ;
/**
* Generated
*/
bool getAdjacentSubtreeForksIntoOtherRank() const ;
/**
* Generated
*/
void setAdjacentSubtreeForksIntoOtherRank(const bool& adjacentSubtreeForksIntoOtherRank) ;
};
private:
PersistentRecords _persistentRecords;
int _adjacentCellsHeightOfPreviousIteration;
int _numberOfAdjacentRefinedCells;
public:
/**
* Generated
*/
TestVertexPacked();
/**
* Generated
*/
TestVertexPacked(const PersistentRecords& persistentRecords);
/**
* Generated
*/
TestVertexPacked(const bool& isHangingNode, const RefinementControl& refinementControl, const int& adjacentCellsHeight, const InsideOutsideDomain& insideOutsideDomain, const tarch::la::Vector<TWO_POWER_D,int>& adjacentRanks, const bool& adjacentSubtreeForksIntoOtherRank);
/**
* Generated
*/
TestVertexPacked(const bool& isHangingNode, const RefinementControl& refinementControl, const int& adjacentCellsHeight, const int& adjacentCellsHeightOfPreviousIteration, const int& numberOfAdjacentRefinedCells, const InsideOutsideDomain& insideOutsideDomain, const tarch::la::Vector<TWO_POWER_D,int>& adjacentRanks, const bool& adjacentSubtreeForksIntoOtherRank);
/**
* Generated
*/
virtual ~TestVertexPacked();
/**
* Generated
*/
bool getIsHangingNode() const ;
/**
* Generated
*/
void setIsHangingNode(const bool& isHangingNode) ;
/**
* Generated
*/
RefinementControl getRefinementControl() const ;
/**
* Generated
*/
void setRefinementControl(const RefinementControl& refinementControl) ;
/**
* Generated
*/
int getAdjacentCellsHeight() const ;
/**
* Generated
*/
void setAdjacentCellsHeight(const int& adjacentCellsHeight) ;
/**
* Generated
*/
int getAdjacentCellsHeightOfPreviousIteration() const ;
/**
* Generated
*/
void setAdjacentCellsHeightOfPreviousIteration(const int& adjacentCellsHeightOfPreviousIteration) ;
/**
* Generated
*/
int getNumberOfAdjacentRefinedCells() const ;
/**
* Generated
*/
void setNumberOfAdjacentRefinedCells(const int& numberOfAdjacentRefinedCells) ;
/**
* Generated
*/
InsideOutsideDomain getInsideOutsideDomain() const ;
/**
* Generated
*/
void setInsideOutsideDomain(const InsideOutsideDomain& insideOutsideDomain) ;
tarch::la::Vector<TWO_POWER_D,int> getAdjacentRanks() const ;
void setAdjacentRanks(const tarch::la::Vector<TWO_POWER_D,int>& adjacentRanks) ;
int getAdjacentRanks(int elementIndex) const ;
void setAdjacentRanks(int elementIndex, const int& adjacentRanks) ;
/**
* Generated
*/
bool getAdjacentSubtreeForksIntoOtherRank() const ;
/**
* Generated
*/
void setAdjacentSubtreeForksIntoOtherRank(const bool& adjacentSubtreeForksIntoOtherRank) ;
/**
* Generated
*/
static std::string toString(const InsideOutsideDomain& param);
/**
* Generated
*/
static std::string getInsideOutsideDomainMapping();
/**
* Generated
*/
static std::string toString(const RefinementControl& param);
/**
* Generated
*/
static std::string getRefinementControlMapping();
/**
* Generated
*/
std::string toString() const;
/**
* Generated
*/
void toString(std::ostream& out) const;
PersistentRecords getPersistentRecords() const;
/**
* Generated
*/
TestVertex convert() const;
#ifdef Parallel
protected:
static tarch::logging::Log _log;
int _senderDestinationRank;
public:
/**
* Global that represents the mpi datatype.
* There are two variants: Datatype identifies only those attributes marked with
* parallelise. FullDatatype instead identifies the whole record with all fields.
*/
static MPI_Datatype Datatype;
static MPI_Datatype FullDatatype;
/**
* Initializes the data type for the mpi operations. Has to be called
* before the very first send or receive operation is called.
*/
static void initDatatype();
static void shutdownDatatype();
enum class ExchangeMode { Blocking, NonblockingWithPollingLoopOverTests, LoopOverProbeWithBlockingReceive };
void send(int destination, int tag, bool exchangeOnlyAttributesMarkedWithParallelise, ExchangeMode mode );
void receive(int source, int tag, bool exchangeOnlyAttributesMarkedWithParallelise, ExchangeMode mode );
static bool isMessageInQueue(int tag, bool exchangeOnlyAttributesMarkedWithParallelise);
int getSenderRank() const;
#endif
};
#elif !defined(PersistentRegularSubtrees) && !defined(Asserts) && !defined(Parallel)
/**
* @author This class is generated by DaStGen
* DataStructureGenerator (DaStGen)
* 2007-2009 Wolfgang Eckhardt
* 2012 Tobias Weinzierl
*
* build date: 09-02-2014 14:40
*
* @date 31/03/2018 18:55
*/
class peano::grid::tests::records::TestVertex {
public:
typedef peano::grid::tests::records::TestVertexPacked Packed;
enum InsideOutsideDomain {
Inside = 0, Boundary = 1, Outside = 2
};
enum RefinementControl {
Unrefined = 0, Refined = 1, RefinementTriggered = 2, Refining = 3, EraseTriggered = 4, Erasing = 5, RefineDueToJoinThoughWorkerIsAlreadyErasing = 6, EnforceRefinementTriggered = 7
};
struct PersistentRecords {
bool _isHangingNode;
RefinementControl _refinementControl;
int _adjacentCellsHeight;
InsideOutsideDomain _insideOutsideDomain;
/**
* Generated
*/
PersistentRecords();
/**
* Generated
*/
PersistentRecords(const bool& isHangingNode, const RefinementControl& refinementControl, const int& adjacentCellsHeight, const InsideOutsideDomain& insideOutsideDomain);
/**
* Generated
*/
bool getIsHangingNode() const ;
/**
* Generated
*/
void setIsHangingNode(const bool& isHangingNode) ;
/**
* Generated
*/
RefinementControl getRefinementControl() const ;
/**
* Generated
*/
void setRefinementControl(const RefinementControl& refinementControl) ;
/**
* Generated
*/
int getAdjacentCellsHeight() const ;
/**
* Generated
*/
void setAdjacentCellsHeight(const int& adjacentCellsHeight) ;
/**
* Generated
*/
InsideOutsideDomain getInsideOutsideDomain() const ;
/**
* Generated
*/
void setInsideOutsideDomain(const InsideOutsideDomain& insideOutsideDomain) ;
};
private:
PersistentRecords _persistentRecords;
int _adjacentCellsHeightOfPreviousIteration;
int _numberOfAdjacentRefinedCells;
public:
/**
* Generated
*/
TestVertex();
/**
* Generated
*/
TestVertex(const PersistentRecords& persistentRecords);
/**
* Generated
*/
TestVertex(const bool& isHangingNode, const RefinementControl& refinementControl, const int& adjacentCellsHeight, const InsideOutsideDomain& insideOutsideDomain);
/**
* Generated
*/
TestVertex(const bool& isHangingNode, const RefinementControl& refinementControl, const int& adjacentCellsHeight, const int& adjacentCellsHeightOfPreviousIteration, const int& numberOfAdjacentRefinedCells, const InsideOutsideDomain& insideOutsideDomain);
/**
* Generated
*/
virtual ~TestVertex();
/**
* Generated
*/
bool getIsHangingNode() const ;
/**
* Generated
*/
void setIsHangingNode(const bool& isHangingNode) ;
/**
* Generated
*/
RefinementControl getRefinementControl() const ;
/**
* Generated
*/
void setRefinementControl(const RefinementControl& refinementControl) ;
/**
* Generated
*/
int getAdjacentCellsHeight() const ;
/**
* Generated
*/
void setAdjacentCellsHeight(const int& adjacentCellsHeight) ;
/**
* Generated
*/
int getAdjacentCellsHeightOfPreviousIteration() const ;
/**
* Generated
*/
void setAdjacentCellsHeightOfPreviousIteration(const int& adjacentCellsHeightOfPreviousIteration) ;
/**
* Generated
*/
int getNumberOfAdjacentRefinedCells() const ;
/**
* Generated
*/
void setNumberOfAdjacentRefinedCells(const int& numberOfAdjacentRefinedCells) ;
/**
* Generated
*/
InsideOutsideDomain getInsideOutsideDomain() const ;
/**
* Generated
*/
void setInsideOutsideDomain(const InsideOutsideDomain& insideOutsideDomain) ;
/**
* Generated
*/
static std::string toString(const InsideOutsideDomain& param);
/**
* Generated
*/
static std::string getInsideOutsideDomainMapping();
/**
* Generated
*/
static std::string toString(const RefinementControl& param);
/**
* Generated
*/
static std::string getRefinementControlMapping();
/**
* Generated
*/
std::string toString() const;
/**
* Generated
*/
void toString(std::ostream& out) const;
PersistentRecords getPersistentRecords() const;
/**
* Generated
*/
TestVertexPacked convert() const;
#ifdef Parallel
protected:
static tarch::logging::Log _log;
int _senderDestinationRank;
public:
/**
* Global that represents the mpi datatype.
* There are two variants: Datatype identifies only those attributes marked with
* parallelise. FullDatatype instead identifies the whole record with all fields.
*/
static MPI_Datatype Datatype;
static MPI_Datatype FullDatatype;
/**
* Initializes the data type for the mpi operations. Has to be called
* before the very first send or receive operation is called.
*/
static void initDatatype();
static void shutdownDatatype();
enum class ExchangeMode { Blocking, NonblockingWithPollingLoopOverTests, LoopOverProbeWithBlockingReceive };
void send(int destination, int tag, bool exchangeOnlyAttributesMarkedWithParallelise, ExchangeMode mode );
void receive(int source, int tag, bool exchangeOnlyAttributesMarkedWithParallelise, ExchangeMode mode );
static bool isMessageInQueue(int tag, bool exchangeOnlyAttributesMarkedWithParallelise);
int getSenderRank() const;
#endif
};
/**
* @author This class is generated by DaStGen
* DataStructureGenerator (DaStGen)
* 2007-2009 Wolfgang Eckhardt
* 2012 Tobias Weinzierl
*
* build date: 09-02-2014 14:40
*
* @date 31/03/2018 18:55
*/
class peano::grid::tests::records::TestVertexPacked {
public:
typedef peano::grid::tests::records::TestVertex::InsideOutsideDomain InsideOutsideDomain;
typedef peano::grid::tests::records::TestVertex::RefinementControl RefinementControl;
struct PersistentRecords {
int _adjacentCellsHeight;
/** mapping of records:
|| Member || startbit || length
| isHangingNode | startbit 0 | #bits 1
| refinementControl | startbit 1 | #bits 3
| insideOutsideDomain | startbit 4 | #bits 2
*/
int _packedRecords0;
/**
* Generated
*/
PersistentRecords();
/**
* Generated
*/
PersistentRecords(const bool& isHangingNode, const RefinementControl& refinementControl, const int& adjacentCellsHeight, const InsideOutsideDomain& insideOutsideDomain);
/**
* Generated
*/
bool getIsHangingNode() const ;
/**
* Generated
*/
void setIsHangingNode(const bool& isHangingNode) ;
/**
* Generated
*/
RefinementControl getRefinementControl() const ;
/**
* Generated
*/
void setRefinementControl(const RefinementControl& refinementControl) ;
/**
* Generated
*/
int getAdjacentCellsHeight() const ;
/**
* Generated
*/
void setAdjacentCellsHeight(const int& adjacentCellsHeight) ;
/**
* Generated
*/
InsideOutsideDomain getInsideOutsideDomain() const ;
/**
* Generated
*/
void setInsideOutsideDomain(const InsideOutsideDomain& insideOutsideDomain) ;
};
private:
PersistentRecords _persistentRecords;
int _adjacentCellsHeightOfPreviousIteration;
int _numberOfAdjacentRefinedCells;
public:
/**
* Generated
*/
TestVertexPacked();
/**
* Generated
*/
TestVertexPacked(const PersistentRecords& persistentRecords);
/**
* Generated
*/
TestVertexPacked(const bool& isHangingNode, const RefinementControl& refinementControl, const int& adjacentCellsHeight, const InsideOutsideDomain& insideOutsideDomain);
/**
* Generated
*/
TestVertexPacked(const bool& isHangingNode, const RefinementControl& refinementControl, const int& adjacentCellsHeight, const int& adjacentCellsHeightOfPreviousIteration, const int& numberOfAdjacentRefinedCells, const InsideOutsideDomain& insideOutsideDomain);
/**
* Generated
*/
virtual ~TestVertexPacked();
/**
* Generated
*/
bool getIsHangingNode() const ;
/**
* Generated
*/
void setIsHangingNode(const bool& isHangingNode) ;
/**
* Generated
*/
RefinementControl getRefinementControl() const ;
/**
* Generated
*/
void setRefinementControl(const RefinementControl& refinementControl) ;
/**
* Generated
*/
int getAdjacentCellsHeight() const ;
/**
* Generated
*/
void setAdjacentCellsHeight(const int& adjacentCellsHeight) ;
/**
* Generated
*/
int getAdjacentCellsHeightOfPreviousIteration() const ;
/**
* Generated
*/
void setAdjacentCellsHeightOfPreviousIteration(const int& adjacentCellsHeightOfPreviousIteration) ;
/**
* Generated
*/
int getNumberOfAdjacentRefinedCells() const ;
/**
* Generated
*/
void setNumberOfAdjacentRefinedCells(const int& numberOfAdjacentRefinedCells) ;
/**
* Generated
*/
InsideOutsideDomain getInsideOutsideDomain() const ;
/**
* Generated
*/
void setInsideOutsideDomain(const InsideOutsideDomain& insideOutsideDomain) ;
/**
* Generated
*/
static std::string toString(const InsideOutsideDomain& param);
/**
* Generated
*/
static std::string getInsideOutsideDomainMapping();
/**
* Generated
*/
static std::string toString(const RefinementControl& param);
/**
* Generated
*/
static std::string getRefinementControlMapping();
/**
* Generated
*/
std::string toString() const;
/**
* Generated
*/
void toString(std::ostream& out) const;
PersistentRecords getPersistentRecords() const;
/**
* Generated
*/
TestVertex convert() const;
#ifdef Parallel
protected:
static tarch::logging::Log _log;
int _senderDestinationRank;
public:
/**
* Global that represents the mpi datatype.
* There are two variants: Datatype identifies only those attributes marked with
* parallelise. FullDatatype instead identifies the whole record with all fields.
*/
static MPI_Datatype Datatype;
static MPI_Datatype FullDatatype;
/**
* Initializes the data type for the mpi operations. Has to be called
* before the very first send or receive operation is called.
*/
static void initDatatype();
static void shutdownDatatype();
enum class ExchangeMode { Blocking, NonblockingWithPollingLoopOverTests, LoopOverProbeWithBlockingReceive };
void send(int destination, int tag, bool exchangeOnlyAttributesMarkedWithParallelise, ExchangeMode mode );
void receive(int source, int tag, bool exchangeOnlyAttributesMarkedWithParallelise, ExchangeMode mode );
static bool isMessageInQueue(int tag, bool exchangeOnlyAttributesMarkedWithParallelise);
int getSenderRank() const;
#endif
};
#endif
#endif
| 35.953512 | 548 | 0.46066 | [
"vector"
] |
dea1df1e59b96104b497decf1e916d11ced341e6 | 26,291 | h | C | il/container/1d/Array.h | insideloop/InsideLoop | 5385e908d85697e32fa065b45f608df84d3177a3 | [
"Apache-2.0"
] | 19 | 2016-12-08T14:16:28.000Z | 2017-08-18T01:26:52.000Z | il/container/1d/Array.h | insideloop/InsideLoop | 5385e908d85697e32fa065b45f608df84d3177a3 | [
"Apache-2.0"
] | 1 | 2017-03-10T17:28:33.000Z | 2017-03-14T11:08:32.000Z | il/container/1d/Array.h | insideloop/InsideLoop | 5385e908d85697e32fa065b45f608df84d3177a3 | [
"Apache-2.0"
] | null | null | null | //==============================================================================
//
// Copyright 2018 The InsideLoop Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//==============================================================================
#ifndef IL_ARRAY_H
#define IL_ARRAY_H
// <cstring> is needed for memcpy
#include <cstring>
// <initializer_list> is needed for std::initializer_list<T>
#include <initializer_list>
// <new> is needed for placement new
#include <new>
// <utility> is needed for std::move
#include <utility>
#include <il/container/1d/ArrayView.h>
#include <il/core/memory/allocate.h>
namespace il {
template <typename T>
class Array {
private:
T* data_;
T* size_;
T* capacity_;
short alignment_;
short align_r_;
short align_mod_;
short shift_;
public:
/* \brief Default constructor
// \details The size and the capacity of the array are set to 0. The alignment
// is undefined. No memory allocation is done during the process.
*/
Array();
/* \brief Construct an array of n elements
// \details The size and the capacity of the array are set to n.
// - If T is a numeric value, the memory is
// - (Debug mode) initialized to il::defaultValue<T>(). It is usually
NaN
// if T is a floating point number or 666..666 if T is an integer.
// - (Release mode) left uninitialized. This behavior is different from
// std::vector from the standard library which initializes all numeric
// values to 0.
// - If T is an object with a default constructor, all objects are default
// constructed. A compile-time error is raised if T has no default
// constructor.
//
// // Construct an array of double of size 5
// il::Array<double> v{5};
*/
explicit Array(il::int_t n);
/* \brief Construct an aligned array of n elements
// \details The pointer data, when considered as an integer, satisfies
// data_ = 0 (Modulo align_mod)
*/
explicit Array(il::int_t n, il::align_t, il::int_t alignment);
/* \brief Construct an aligned array of n elements
// \details The pointer data, when considered as an integer, satisfies
// data_ = align_r (Modulo align_mod)
*/
explicit Array(il::int_t n, il::align_t, il::int_t alignment,
il::int_t align_r, il::int_t align_mod);
/* \brief Construct an array of n elements with a value
//
// // Construct an array of double of length 5, initialized with 3.14
// il::Array<double> v{5, 3.14};
*/
explicit Array(il::int_t n, const T& x);
template <typename... Args>
explicit Array(il::int_t n, il::emplace_t, Args&&... args);
/* \brief Construct an array of n elements with a value
//
// // Construct an array of double of length 5, initialized with 3.14
// il::Array<double> v{5, 3.14};
*/
explicit Array(il::int_t n, const T& x, il::align_t, il::int_t alignment,
il::int_t align_r, il::int_t align_mod);
explicit Array(il::int_t n, const T& x, il::align_t, il::int_t alignment);
explicit Array(il::ArrayView<T> v);
/* \brief Construct an array from a brace-initialized list
// \details The size and the capacity of the il::Array<T> is adjusted
to
// the size of the initializer list. The tag il::value is used to allow brace
// initialization of il::Array<T> everywhere.
//
// // Construct an array of double from a list
// il::Array<double> v{il::value, {2.0, 3.14, 5.0, 7.0}};
*/
Array(il::value_t, std::initializer_list<T> list);
/* \brief The copy constructor
// \details The size and the capacity of the constructed il::Array<T>
are
// equal to the size of the source array.
*/
Array(const Array<T>& v);
/* \brief The move constructor
*/
Array(Array<T>&& v);
/* \brief The copy assignment
// \details The size is the same as the one for the source array. The
// capacity is not changed if it is enough for the copy to happen and is
// set to the size of the source array if the initial capacity is too low.
*/
Array& operator=(const Array<T>& v);
/* \brief The move assignment
*/
Array& operator=(Array<T>&& v);
/* \brief The destructor
*/
~Array();
/* \brief Accessor for a const il::Array<T>
// \details Access (read only) the i-th element of the array. Bound checking
// is done in debug mode but not in release mode.
//
// il::Array<double> v{4};
// std::cout << v[0] << std::endl;
*/
const T& operator[](il::int_t i) const;
/* \brief Accessor for an il::Array<T>
// \details Access (read or write) the i-th element of the array. Bound
// checking is done in debug mode but not in release mode.
//
// il::Array<double> v{4};
// v[0] = 0.0;
// v[4] = 0.0; // Program is aborted in debug mode and has undefined
// // behavior in release mode
*/
T& operator[](il::int_t i);
void Set(const T& x);
/* \brief Accessor to the last element of a const il::Array<T>
// \details In debug mode, calling this method on an array of size 0 aborts
// the program. In release mode, it will lead to undefined behavior.
*/
const T& back() const;
/* \brief Accessor to the last element of a il::Array<T>
// \details In debug mode, calling this method on an array of size 0 aborts
// the program. In release mode, it will lead to undefined behavior.
*/
T& Back();
/* \brief Get the size of the il::Array<T>
// \details The library has been designed in a way that any compiler can prove
// that modifying v[k] can't change the result of v.size(). As a consequence
// a call to v.size() is made just once at the very beginning of the loop
// in the following example. It allows many optimizations from the compiler,
// including automatic vectorization.
//
// il::Array<double> v{n};
// for (il::int_t k = 0; k < v.size(); ++k) {
// v[k] = 1.0 / (k + 1);
// }
*/
il::int_t size() const;
/* \brief Resizing an il::Array<T>
// \details No reallocation is performed if the new size is <= to the
// capacity. In this case, the capacity is unchanged. When the size is > than
// the current capacity, reallocation is done and the array gets the same
// capacity as its size.
*/
void Resize(il::int_t n);
void Resize(il::int_t n, const T& x);
template <typename... Args>
void Resize(il::int_t n, il::emplace_t, Args&&... args);
/* \brief Get the capacity of the il::Array<T>
*/
il::int_t capacity() const;
/* \brief Change the capacity of the array to at least p
// \details If the capacity is >= to p, nothing is done. Otherwise,
// reallocation is done and the new capacity is set to p.
*/
void Reserve(il::int_t r);
/* \brief Add an element at the end of the array
// \details Reallocation is done only if it is needed. In case reallocation
// happens, then new capacity is roughly (3/2) the previous capacity.
*/
void Append(const T& x);
/* \brief Add an element at the end of the array
// \details Reallocation is done only if it is needed. In case reallocation
// happens, then new capacity is roughly (3/2) the previous capacity.
*/
void Append(T&& x);
/* \brief Construct an element at the end of the array
// \details Reallocation is done only if it is needed. In case reallocation
// happens, then new capacity is roughly (3/2) the previous capacity.
*/
template <typename... Args>
void Append(il::emplace_t, Args&&... args);
/* \brief Get the alignment of the pointer returned by data()
*/
il::int_t alignment() const;
il::ArrayView<T> view() const;
il::ArrayView<T> view(il::Range range) const;
il::ArrayEdit<T> Edit();
il::ArrayEdit<T> Edit(il::Range range);
/* \brief Get a pointer to const to the first element of the array
// \details One should use this method only when using C-style API
*/
const T* data() const;
/* \brief Get a pointer to the first element of the array
// \details One should use this method only when using C-style API
*/
T* Data();
const T* begin() const;
const T* cbegin() const;
T* begin();
const T* end() const;
const T* cend() const;
T* end();
private:
/* \brief Used internally to increase the capacity of the array
*/
void IncreaseCapacity(il::int_t r);
/* \brief Used internally in debug mode to check the invariance of the object
*/
bool invariance() const;
};
template <typename T>
Array<T>::Array() {
data_ = nullptr;
size_ = nullptr;
capacity_ = nullptr;
alignment_ = 0;
align_r_ = 0;
align_mod_ = 0;
shift_ = 0;
}
template <typename T>
Array<T>::Array(il::int_t n) {
IL_EXPECT_FAST(n >= 0);
if (n > 0) {
data_ = il::allocateArray<T>(n);
if (il::isTrivial<T>::value) {
#ifdef IL_DEFAULT_VALUE
for (il::int_t i = 0; i < n; ++i) {
data_[i] = il::defaultValue<T>();
}
#endif
} else {
for (il::int_t i = 0; i < n; ++i) {
new (data_ + i) T{};
}
}
} else {
data_ = nullptr;
}
size_ = data_ + n;
capacity_ = data_ + n;
alignment_ = 0;
align_r_ = 0;
align_mod_ = 0;
shift_ = 0;
}
template <typename T>
Array<T>::Array(il::int_t n, il::align_t, il::int_t alignment,
il::int_t align_r, il::int_t align_mod) {
IL_EXPECT_FAST(il::isTrivial<T>::value);
IL_EXPECT_FAST(sizeof(T) % alignof(T) == 0);
IL_EXPECT_FAST(n >= 0);
IL_EXPECT_FAST(alignment > 0);
IL_EXPECT_FAST(alignment % alignof(T) == 0);
IL_EXPECT_FAST(alignment <= SHRT_MAX);
IL_EXPECT_FAST(align_mod > 0);
IL_EXPECT_FAST(align_mod % alignof(T) == 0);
IL_EXPECT_FAST(align_mod % alignment == 0);
IL_EXPECT_FAST(align_mod <= SHRT_MAX);
IL_EXPECT_FAST(align_r >= 0);
IL_EXPECT_FAST(align_r < align_mod);
IL_EXPECT_FAST(align_r % alignof(T) == 0);
IL_EXPECT_FAST(align_r % alignment == 0);
IL_EXPECT_FAST(align_r <= SHRT_MAX);
if (n > 0) {
il::int_t shift;
data_ = il::allocateArray<T>(n, align_r, align_mod, il::io, shift);
alignment_ = static_cast<short>(alignment);
align_r_ = static_cast<short>(align_r);
align_mod_ = static_cast<short>(align_mod);
shift_ = static_cast<short>(shift);
#ifdef IL_DEFAULT_VALUE
for (il::int_t i = 0; i < n; ++i) {
data_[i] = il::defaultValue<T>();
}
#endif
} else {
data_ = nullptr;
alignment_ = 0;
align_r_ = 0;
align_mod_ = 0;
shift_ = 0;
}
size_ = data_ + n;
capacity_ = data_ + n;
}
template <typename T>
Array<T>::Array(il::int_t n, il::align_t, il::int_t alignment)
: Array{n, il::align, alignment, 0, alignment} {}
template <typename T>
Array<T>::Array(il::int_t n, const T& x) {
IL_EXPECT_FAST(n >= 0);
if (n > 0) {
data_ = il::allocateArray<T>(n);
for (il::int_t i = 0; i < n; ++i) {
new (data_ + i) T(x);
}
} else {
data_ = nullptr;
}
size_ = data_ + n;
capacity_ = data_ + n;
alignment_ = 0;
align_r_ = 0;
align_mod_ = 0;
shift_ = 0;
}
template <typename T>
template <typename... Args>
Array<T>::Array(il::int_t n, il::emplace_t, Args&&... args) {
IL_EXPECT_FAST(n >= 0);
if (n > 0) {
data_ = il::allocateArray<T>(n);
for (il::int_t i = 0; i < n; ++i) {
new (data_ + i) T(std::forward<Args>(args)...);
}
} else {
data_ = nullptr;
}
size_ = data_ + n;
capacity_ = data_ + n;
alignment_ = 0;
align_r_ = 0;
align_mod_ = 0;
shift_ = 0;
}
template <typename T>
Array<T>::Array(il::int_t n, const T& x, il::align_t, il::int_t alignment,
il::int_t align_r, il::int_t align_mod) {
IL_EXPECT_FAST(il::isTrivial<T>::value);
IL_EXPECT_FAST(sizeof(T) % alignof(T) == 0);
IL_EXPECT_FAST(n >= 0);
IL_EXPECT_FAST(alignment > 0);
IL_EXPECT_FAST(alignment % alignof(T) == 0);
IL_EXPECT_FAST(alignment <= SHRT_MAX);
IL_EXPECT_FAST(align_mod > 0);
IL_EXPECT_FAST(align_mod % alignof(T) == 0);
IL_EXPECT_FAST(align_mod % alignment == 0);
IL_EXPECT_FAST(align_mod <= SHRT_MAX);
IL_EXPECT_FAST(align_r >= 0);
IL_EXPECT_FAST(align_r < align_mod);
IL_EXPECT_FAST(align_r % alignof(T) == 0);
IL_EXPECT_FAST(align_r % alignment == 0);
IL_EXPECT_FAST(align_r <= SHRT_MAX);
if (n > 0) {
il::int_t shift;
data_ = il::allocateArray<T>(n, align_r, align_mod, il::io, shift);
alignment_ = static_cast<short>(alignment);
align_r_ = static_cast<short>(align_r);
align_mod_ = static_cast<short>(align_mod);
shift_ = static_cast<short>(shift);
for (il::int_t i = 0; i < n; ++i) {
data_[i] = x;
}
} else {
data_ = nullptr;
alignment_ = 0;
align_r_ = 0;
align_mod_ = 0;
shift_ = 0;
}
size_ = data_ + n;
capacity_ = data_ + n;
}
template <typename T>
Array<T>::Array(il::int_t n, const T& x, il::align_t, il::int_t alignment)
: Array{n, x, il::align, alignment, 0, alignment} {}
template <typename T>
Array<T>::Array(il::ArrayView<T> v) {
const il::int_t n = v.size();
if (n > 0) {
data_ = il::allocateArray<T>(n);
for (il::int_t i = 0; i < n; ++i) {
new (data_ + i) T{v[i]};
}
} else {
data_ = nullptr;
}
size_ = data_ + n;
capacity_ = data_ + n;
alignment_ = 0;
align_r_ = 0;
align_mod_ = 0;
shift_ = 0;
}
template <typename T>
Array<T>::Array(il::value_t, std::initializer_list<T> list) {
bool error = false;
const il::int_t n = il::safeConvert<il::int_t>(list.size(), il::io, error);
if (error) {
il::abort();
}
if (n > 0) {
data_ = il::allocateArray<T>(n);
if (il::isTrivial<T>::value) {
memcpy(data_, list.begin(), n * sizeof(T));
} else {
for (il::int_t i = 0; i < n; ++i) {
new (data_ + i) T(*(list.begin() + i));
}
}
} else {
data_ = nullptr;
}
size_ = data_ + n;
capacity_ = data_ + n;
alignment_ = 0;
align_r_ = 0;
align_mod_ = 0;
shift_ = 0;
}
template <typename T>
Array<T>::Array(const Array<T>& v) {
const il::int_t n = v.size();
const il::int_t alignment = v.alignment_;
const il::int_t align_r = v.align_r_;
const il::int_t align_mod = v.align_mod_;
if (alignment == 0) {
data_ = il::allocateArray<T>(n);
alignment_ = 0;
align_r_ = 0;
align_mod_ = 0;
shift_ = 0;
} else {
il::int_t shift;
data_ = il::allocateArray<T>(n, align_r, align_mod, il::io, shift);
alignment_ = static_cast<short>(alignment);
align_r_ = static_cast<short>(align_r);
align_mod_ = static_cast<short>(align_mod);
shift_ = static_cast<short>(shift);
}
if (il::isTrivial<T>::value) {
memcpy(data_, v.data_, n * sizeof(T));
} else {
for (il::int_t i = 0; i < n; ++i) {
new (data_ + i) T(v.data_[i]);
}
}
size_ = data_ + n;
capacity_ = data_ + n;
}
template <typename T>
Array<T>::Array(Array<T>&& v) {
data_ = v.data_;
size_ = v.size_;
capacity_ = v.capacity_;
alignment_ = v.alignment_;
align_r_ = v.align_r_;
align_mod_ = v.align_mod_;
shift_ = v.shift_;
v.data_ = nullptr;
v.size_ = nullptr;
v.capacity_ = nullptr;
v.alignment_ = 0;
v.align_r_ = 0;
v.align_mod_ = 0;
v.shift_ = 0;
}
template <typename T>
Array<T>& Array<T>::operator=(const Array<T>& v) {
if (this == &v) {
return *this;
}
const il::int_t n = v.size();
const il::int_t alignment = v.alignment_;
const il::int_t align_r = v.align_r_;
const il::int_t align_mod = v.align_mod_;
const bool needs_memory = n > capacity() || alignment_ != alignment ||
align_r_ != align_r || align_mod_ != align_mod;
if (needs_memory) {
if (data_) {
if (!il::isTrivial<T>::value) {
for (il::int_t i = size() - 1; i >= 0; --i) {
(data_ + i)->~T();
}
}
il::deallocate(data_ - shift_);
}
if (alignment == 0) {
data_ = il::allocateArray<T>(n);
alignment_ = 0;
align_r_ = 0;
align_mod_ = 0;
shift_ = 0;
} else {
il::int_t shift;
data_ = il::allocateArray<T>(n, align_r, align_mod, il::io, shift);
alignment_ = static_cast<short>(alignment);
align_r_ = static_cast<short>(align_r);
align_mod_ = static_cast<short>(align_mod);
shift_ = static_cast<short>(shift);
}
if (il::isTrivial<T>::value) {
memcpy(data_, v.data_, n * sizeof(T));
} else {
for (il::int_t i = 0; i < n; ++i) {
new (data_ + i) T(v.data_[i]);
}
}
size_ = data_ + n;
capacity_ = data_ + n;
} else {
if (il::isTrivial<T>::value) {
memcpy(data_, v.data_, n * sizeof(T));
} else {
for (il::int_t i = 0; i < n; ++i) {
data_[i] = v.data_[i];
}
for (il::int_t i = size() - 1; i >= n; --i) {
(data_ + i)->~T();
}
}
size_ = data_ + n;
}
return *this;
}
template <typename T>
Array<T>& Array<T>::operator=(Array<T>&& v) {
if (this == &v) {
return *this;
}
if (data_) {
if (!il::isTrivial<T>::value) {
for (il::int_t i = size() - 1; i >= 0; --i) {
(data_ + i)->~T();
}
}
il::deallocate(data_ - shift_);
}
data_ = v.data_;
size_ = v.size_;
capacity_ = v.capacity_;
alignment_ = v.alignment_;
align_r_ = v.align_r_;
align_mod_ = v.align_mod_;
shift_ = v.shift_;
v.data_ = nullptr;
v.size_ = nullptr;
v.capacity_ = nullptr;
v.alignment_ = 0;
v.align_r_ = 0;
v.align_mod_ = 0;
v.shift_ = 0;
return *this;
}
template <typename T>
Array<T>::~Array() {
IL_EXPECT_FAST_NOTHROW(invariance());
if (data_) {
if (!il::isTrivial<T>::value) {
for (il::int_t i = size() - 1; i >= 0; --i) {
(data_ + i)->~T();
}
}
il::deallocate(data_ - shift_);
}
}
template <typename T>
const T& Array<T>::operator[](il::int_t i) const {
IL_EXPECT_MEDIUM(static_cast<std::size_t>(i) <
static_cast<std::size_t>(size()));
return data_[i];
}
template <typename T>
T& Array<T>::operator[](il::int_t i) {
IL_EXPECT_MEDIUM(static_cast<std::size_t>(i) <
static_cast<std::size_t>(size()));
return data_[i];
}
template <typename T>
void Array<T>::Set(const T& x) {
for (il::int_t i = 0; i < capacity_ - data_; ++i) {
data_[i] = x;
}
}
template <typename T>
const T& Array<T>::back() const {
IL_EXPECT_MEDIUM(size() > 0);
return size_[-1];
}
template <typename T>
T& Array<T>::Back() {
IL_EXPECT_MEDIUM(size() > 0);
return size_[-1];
}
template <typename T>
il::int_t Array<T>::size() const {
return size_ - data_;
}
template <typename T>
void Array<T>::Resize(il::int_t n) {
IL_EXPECT_FAST(n >= 0);
if (n <= capacity()) {
if (il::isTrivial<T>::value) {
#ifdef IL_DEFAULT_VALUE
for (il::int_t i = size(); i < n; ++i) {
data_[i] = il::defaultValue<T>();
}
#endif
} else {
for (il::int_t i = size() - 1; i >= n; --i) {
(data_ + i)->~T();
}
for (il::int_t i = size(); i < n; ++i) {
new (data_ + i) T();
}
}
} else {
const il::int_t n_old = size();
IncreaseCapacity(n);
if (il::isTrivial<T>::value) {
#ifdef IL_DEFAULT_VALUE
for (il::int_t i = n_old; i < n; ++i) {
data_[i] = il::defaultValue<T>();
}
#endif
} else {
for (il::int_t i = n_old; i < n; ++i) {
new (data_ + i) T{};
}
}
}
size_ = data_ + n;
}
template <typename T>
void Array<T>::Resize(il::int_t n, const T& x) {
IL_EXPECT_FAST(n >= 0);
if (n <= capacity()) {
if (il::isTrivial<T>::value) {
for (il::int_t i = size(); i < n; ++i) {
data_[i] = x;
}
} else {
for (il::int_t i = size() - 1; i >= n; --i) {
(data_ + i)->~T();
}
for (il::int_t i = size(); i < n; ++i) {
new (data_ + i) T{x};
}
}
} else {
const il::int_t n_old = size();
IncreaseCapacity(n);
if (il::isTrivial<T>::value) {
for (il::int_t i = n_old; i < n; ++i) {
data_[i] = x;
}
} else {
for (il::int_t i = n_old; i < n; ++i) {
new (data_ + i) T{x};
}
}
}
size_ = data_ + n;
}
template <typename T>
template <typename... Args>
void Array<T>::Resize(il::int_t n, il::emplace_t, Args&&... args) {
IL_EXPECT_FAST(n >= 0);
if (n <= capacity()) {
if (il::isTrivial<T>::value) {
for (il::int_t i = size(); i < n; ++i) {
data_[i] = T(std::forward<Args>(args)...);
}
} else {
for (il::int_t i = size() - 1; i >= n; --i) {
(data_ + i)->~T();
}
for (il::int_t i = size(); i < n; ++i) {
new (data_ + i) T(std::forward<Args>(args)...);
}
}
} else {
const il::int_t n_old = size();
IncreaseCapacity(n);
if (il::isTrivial<T>::value) {
for (il::int_t i = n_old; i < n; ++i) {
data_[i] = T(std::forward<Args>(args)...);
}
} else {
for (il::int_t i = n_old; i < n; ++i) {
new (data_ + i) T(std::forward<Args>(args)...);
}
}
}
size_ = data_ + n;
};
template <typename T>
il::int_t Array<T>::capacity() const {
return capacity_ - data_;
}
template <typename T>
void Array<T>::Reserve(il::int_t r) {
IL_EXPECT_FAST(r >= 0);
if (r > capacity()) {
IncreaseCapacity(r);
}
}
template <typename T>
void Array<T>::Append(const T& x) {
if (size_ == capacity_) {
const il::int_t n = size();
bool error = false;
il::int_t new_capacity =
n > 1 ? il::safeProduct(static_cast<il::int_t>(2), n, il::io, error)
: il::safeSum(n, static_cast<il::int_t>(1), il::io, error);
if (error) {
il::abort();
}
T x_copy = x;
IncreaseCapacity(new_capacity);
new (size_) T(std::move(x_copy));
} else {
new (size_) T(x);
}
++size_;
}
template <typename T>
void Array<T>::Append(T&& x) {
if (size_ == capacity_) {
const il::int_t n = size();
bool error = false;
il::int_t new_capacity =
n > 1 ? il::safeProduct(static_cast<il::int_t>(2), n, il::io, error)
: il::safeSum(n, static_cast<il::int_t>(1), il::io, error);
if (error) {
il::abort();
}
IncreaseCapacity(new_capacity);
}
// if (il::isTrivial<T>::value) {
// *size_ = std::move(x);
// } else {
new (size_) T(std::move(x));
// }
++size_;
}
template <typename T>
template <typename... Args>
void Array<T>::Append(il::emplace_t, Args&&... args) {
if (size_ == capacity_) {
const il::int_t n = size();
bool error = false;
il::int_t new_capacity =
n > 1 ? il::safeProduct(static_cast<il::int_t>(2), n, il::io, error)
: il::safeSum(n, static_cast<il::int_t>(1), il::io, error);
if (error) {
il::abort();
}
IncreaseCapacity(new_capacity);
};
new (size_) T(std::forward<Args>(args)...);
++size_;
}
template <typename T>
il::int_t Array<T>::alignment() const {
return alignment_;
}
template <typename T>
il::ArrayView<T> Array<T>::view() const {
return il::ArrayView<T>{data_, size()};
};
template <typename T>
il::ArrayView<T> Array<T>::view(il::Range range) const {
IL_EXPECT_MEDIUM(static_cast<std::size_t>(range.begin) <
static_cast<std::size_t>(size()));
IL_EXPECT_MEDIUM(static_cast<std::size_t>(range.end) <=
static_cast<std::size_t>(size()));
return il::ArrayView<T>{data_ + range.begin, range.end - range.begin};
};
template <typename T>
il::ArrayEdit<T> Array<T>::Edit() {
return il::ArrayEdit<T>{data_, size()};
};
template <typename T>
il::ArrayEdit<T> Array<T>::Edit(il::Range range) {
IL_EXPECT_MEDIUM(static_cast<std::size_t>(range.begin) <
static_cast<std::size_t>(size()));
IL_EXPECT_MEDIUM(static_cast<std::size_t>(range.end) <=
static_cast<std::size_t>(size()));
return il::ArrayEdit<T>{data_ + range.begin, range.end - range.begin};
};
template <typename T>
const T* Array<T>::data() const {
return data_;
}
template <typename T>
T* Array<T>::Data() {
return data_;
}
template <typename T>
const T* Array<T>::begin() const {
return data_;
}
template <typename T>
const T* Array<T>::cbegin() const {
return data_;
}
template <typename T>
T* Array<T>::begin() {
return data_;
}
template <typename T>
const T* Array<T>::end() const {
return size_;
}
template <typename T>
const T* Array<T>::cend() const {
return size_;
}
template <typename T>
T* Array<T>::end() {
return size_;
}
template <typename T>
void Array<T>::IncreaseCapacity(il::int_t r) {
IL_EXPECT_FAST(capacity() < r);
const il::int_t n = size();
T* new_data;
il::int_t new_shift;
if (alignment_ == 0) {
new_data = il::allocateArray<T>(r);
new_shift = 0;
} else {
new_data = il::allocateArray<T>(n, align_r_, align_mod_, il::io, new_shift);
}
if (data_) {
if (il::isTrivial<T>::value) {
memcpy(new_data, data_, n * sizeof(T));
} else {
for (il::int_t i = n - 1; i >= 0; --i) {
new (new_data + i) T(std::move(data_[i]));
(data_ + i)->~T();
}
}
il::deallocate(data_ - shift_);
}
data_ = new_data;
size_ = data_ + n;
capacity_ = data_ + r;
shift_ = static_cast<short>(new_shift);
}
template <typename T>
bool Array<T>::invariance() const {
bool ans = true;
if (data_ == nullptr) {
ans = ans && (size_ == nullptr);
ans = ans && (capacity_ == nullptr);
} else {
ans = ans && (size_ != nullptr);
ans = ans && (capacity_ != nullptr);
ans = ans && ((size_ - data_) <= (capacity_ - data_));
}
if (!il::isTrivial<T>::value) {
ans = ans && (align_mod_ == 0);
}
if (align_mod_ == 0) {
ans = ans && (align_r_ == 0);
ans = ans && (shift_ == 0);
} else {
ans = ans && (align_r_ < align_mod_);
ans = ans && (reinterpret_cast<std::size_t>(data_) %
static_cast<std::size_t>(align_mod_) ==
static_cast<std::size_t>(align_r_));
}
return ans;
}
} // namespace il
#endif // IL_ARRAY_H
| 26.317317 | 80 | 0.591799 | [
"object",
"vector"
] |
deaa25d56d6717805d64a2f5bb406c3cff9918f3 | 1,212 | h | C | src/software/jetson_nano/redis/redis_client.h | jonl112/Software | 61a028a98d5c0dd5e79bf055b231633290ddbf9f | [
"MIT"
] | null | null | null | src/software/jetson_nano/redis/redis_client.h | jonl112/Software | 61a028a98d5c0dd5e79bf055b231633290ddbf9f | [
"MIT"
] | null | null | null | src/software/jetson_nano/redis/redis_client.h | jonl112/Software | 61a028a98d5c0dd5e79bf055b231633290ddbf9f | [
"MIT"
] | null | null | null | #pragma once
#include "chrono"
#include "cpp_redis/cpp_redis"
#include "shared/constants.h"
#include "software/logger/logger.h"
#include "string"
#include "unordered_map"
class RedisClient
{
public:
/**
* Client that communicates with the a redis server
* @param value The IP of the Redis server, default localhost
* @param key the key of the Redis server, default 6379
*/
explicit RedisClient(std::string value, size_t key);
virtual ~RedisClient();
/**
* gets the value corresponding to the key; blocking
* @param key
* @return a redis reply object
*/
cpp_redis::reply get(const std::string &key);
/**
* sets a key value pair in the redis database
* @param key
* @param value
*/
void set(const std::string &key, const std::string &value);
/**
* @return a map of all the key value pairs in redis server
*/
std::unordered_map<std::string, std::string> getAllKeyValuePairs();
private:
cpp_redis::subscriber subscriber_;
cpp_redis::client client_;
std::unordered_map<std::string, std::string> key_value_set_;
// Connection Parameters
std::string host_;
size_t port_;
};
| 23.764706 | 71 | 0.655116 | [
"object"
] |
deaa615685941d47d6f494cc629631cafffde5e3 | 5,994 | c | C | orte/mca/db/dbase/db_dbase.c | bringhurst/ompi | 7da12594dc72085162265188b505aca0d0cfe811 | [
"BSD-3-Clause-Open-MPI"
] | 1 | 2016-05-01T09:37:07.000Z | 2016-05-01T09:37:07.000Z | orte/mca/db/dbase/db_dbase.c | bringhurst/ompi | 7da12594dc72085162265188b505aca0d0cfe811 | [
"BSD-3-Clause-Open-MPI"
] | null | null | null | orte/mca/db/dbase/db_dbase.c | bringhurst/ompi | 7da12594dc72085162265188b505aca0d0cfe811 | [
"BSD-3-Clause-Open-MPI"
] | null | null | null | /*
* Copyright (c) 2010 Cisco Systems, Inc. All rights reserved.
* $COPYRIGHT$
*
* Additional copyrights may follow
*
* $HEADER$
*
*/
#include "orte_config.h"
#include "orte/constants.h"
#include <string.h>
#include <sys/types.h>
#ifdef HAVE_LIMITS_H
#include <limits.h>
#endif
#include <stdio.h>
#ifdef HAVE_FCNTL_H
#include <fcntl.h>
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <db.h>
#include "opal/dss/dss_types.h"
#include "opal/util/os_dirpath.h"
#include "opal/util/os_path.h"
#include "opal/util/output.h"
#include "opal/util/malloc.h"
#include "opal/util/basename.h"
#include "opal/mca/pstat/base/base.h"
#include "opal/mca/paffinity/base/base.h"
#include "opal/mca/sysinfo/base/base.h"
#include "orte/util/show_help.h"
#include "orte/mca/errmgr/base/base.h"
#include "orte/runtime/orte_globals.h"
#include "db_dbase.h"
static int init(void);
static int finalize(void);
static int insert(char *key, void *object, opal_data_type_t type);
static int set_recover_source(orte_process_name_t *name);
static int select_data(char *key, void *object, opal_data_type_t type);
static int update(char *key, void *object, opal_data_type_t type);
static int delete_data(char *key);
orte_db_base_module_t orte_db_dbase_module = {
init,
finalize,
insert,
set_recover_source,
select_data,
update,
delete_data
};
/* local variables */
static DB *save_dbase=NULL, *recover_dbase=NULL;
static int init(void)
{
char *path, *name;
/* setup the database */
if (ORTE_SUCCESS != opal_os_dirpath_create(orte_db_dbase_directory, S_IRWXU)) {
orte_show_help("help-db-dbase.txt", "cannot-create-dir", true,
orte_db_dbase_directory);
return ORTE_ERR_FILE_OPEN_FAILURE;
}
orte_util_convert_process_name_to_string(&name, ORTE_PROC_MY_NAME);
path = opal_os_path(false, orte_db_dbase_directory, name, NULL);
free(name);
if (NULL == (save_dbase = dbaseopen(path, O_CREAT | O_RDWR | O_TRUNC, S_IRWXU, DB_HASH, NULL))) {
orte_show_help("help-db-dbase.txt", "cannot-create-dbase", true, path);
free(path);
return ORTE_ERR_FILE_OPEN_FAILURE;
}
free(path);
return ORTE_SUCCESS;
}
static int finalize(void)
{
/* if we are normally terminating, remove the recovery file */
return ORTE_SUCCESS;
}
static int insert(char *inkey, void *object, opal_data_type_t type)
{
DBT key, data;
opal_buffer_t buf;
orte_job_t *jdata;
orte_proc_t *proc;
int rc=ORTE_SUCCESS, size;
/* construct the buffer we will use for packing the data */
OBJ_CONSTRUCT(&buf, opal_buffer_t);
key.data = inkey;
key.size = strlen(key.data);
switch (type) {
case ORTE_JOB:
jdata = (orte_job_t*)object;
opal_dss.pack(&buf, &jdata, 1, ORTE_JOB);
break;
case ORTE_PROC:
proc = (orte_proc_t*)object;
opal_dss.pack(&buf, &proc, 1, ORTE_PROC);
break;
default:
orte_show_help("help-db-dbase.txt", "unrecognized-type", true, type);
rc = ORTE_ERR_BAD_PARAM;
goto cleanup;
break;
}
/* unload the data */
opal_dss.unload(&buf, (void**)&data.data, &size);
data.size = size;
OBJ_DESTRUCT(&buf);
/* put the info into the dbase */
if (0 > save_dbase->put(save_dbase, &key, &data, 0)) {
orte_show_help("help-db-dbase.txt", "error-writing-dbase", true, (char*)key.data, strerror(errno));
rc = ORTE_ERR_FILE_WRITE_FAILURE;
}
/* sync it to force it to disk */
if (0 > save_dbase->sync(save_dbase, 0)) {
orte_show_help("help-db-dbase.txt", "error-syncing-dbase", true, (char*)key.data, strerror(errno));
rc = ORTE_ERR_FILE_WRITE_FAILURE;
}
cleanup:
/* cleanup */
if (NULL != key.data) {
free(key.data);
}
if (NULL != data.data) {
free(data.data);
}
return rc;
}
static int set_recover_source(orte_process_name_t *name)
{
char *path, *pname;
int rc=ORTE_SUCCESS;
/* setup the database */
orte_util_convert_process_name_to_string(&pname, name);
path = opal_os_path(false, orte_db_dbase_directory, pname, NULL);
free(pname);
if (NULL == (recover_dbase = dbaseopen(path, O_RDONLY, S_IRWXU, DB_HASH, NULL))) {
orte_show_help("help-db-dbase.txt", "cannot-open-dbase", true, path);
free(path);
return ORTE_ERR_FILE_OPEN_FAILURE;
}
free(path);
return rc;
}
static int select_data(char *inkey, void *object, opal_data_type_t type)
{
DBT key, data;
opal_buffer_t buf;
orte_job_t *jdata;
orte_proc_t *proc;
int rc=ORTE_SUCCESS;
int32_t n;
if (NULL == recover_dbase) {
orte_show_help("help-db-dbase.txt", "recover-source-undef", true);
rc = ORTE_ERR_NOT_FOUND;
}
/* construct the buffer we will use for unpacking the data */
OBJ_CONSTRUCT(&buf, opal_buffer_t);
key.data = inkey;
key.size = strlen(key.data);
/* get the specified data */
if (0 > recover_dbase->get(recover_dbase, &key, &data, 0)) {
orte_show_help("help-db-dbase.txt", "error-reading-dbase", true, (char*)key.data, strerror(errno));
rc = ORTE_ERR_FILE_READ_FAILURE;
goto cleanup;
}
/* populate the recovered info */
opal_dss.load(&buf, data.data, data.size);
switch (type) {
case ORTE_JOB:
n=1;
opal_dss.unpack(&buf, &jdata, &n, ORTE_JOB);
break;
case ORTE_PROC:
n=1;
opal_dss.unpack(&buf, &proc, &n, ORTE_PROC);
break;
default:
break;
}
cleanup:
OBJ_DESTRUCT(&buf);
return rc;
}
static int update(char *key, void *object, opal_data_type_t type)
{
return ORTE_ERR_NOT_IMPLEMENTED;
}
static int delete_data(char *key)
{
return ORTE_ERR_NOT_IMPLEMENTED;
}
| 26.64 | 107 | 0.637304 | [
"object"
] |
deaf289ca4a19bdb35b568965c0da540acce67ab | 755 | h | C | 3dPlot/geometryPool.h | IronFox/GridSim | bf923e6ca5056f3965c6b739b6b028630c576ef7 | [
"MIT"
] | null | null | null | 3dPlot/geometryPool.h | IronFox/GridSim | bf923e6ca5056f3965c6b739b6b028630c576ef7 | [
"MIT"
] | null | null | null | 3dPlot/geometryPool.h | IronFox/GridSim | bf923e6ca5056f3965c6b739b6b028630c576ef7 | [
"MIT"
] | null | null | null | #pragma once
#include <memory>
#include <geometry/cgs.h>
#include <math/matrix.h>
#include <engine/renderer/opengl.h>
#include <engine/display.h>
#include <container/buffer.h>
using namespace DeltaWorks;
typedef Engine::OpenGL Renderer;
extern Engine::Display<Renderer> display;
class Geometry
{
public:
void Render();
index_t Embed(const CGS::Constructor<>::Object&);
void Remove(index_t&);
void RebuildIfNeeded();
private:
Renderer::IBO ibo;
Renderer::VBO vbo;
Engine::VertexBinding vertexBinding;
struct TSection
{
M::TIntRange<index_t> vRange,
iRange;
};
IndexTable<TSection>sectionMap;
bool isDirty = true;
index_t idxCounter = 0;
Buffer0<float> vertexData;
Buffer0<UINT32> indexData;
};
| 15.729167 | 53 | 0.707285 | [
"geometry",
"render",
"object"
] |
deb1018145f84524c08b9694d307be6b08c5252b | 559 | h | C | unit_tests/bind_classes/expose_vector_int.h | SoapyMan/oolua | 9d25a865b05bbb6aaff56726b46e5b746572e490 | [
"MIT"
] | 4 | 2018-12-19T09:30:24.000Z | 2021-06-26T05:38:11.000Z | unit_tests/bind_classes/expose_vector_int.h | SoapyMan/oolua | 9d25a865b05bbb6aaff56726b46e5b746572e490 | [
"MIT"
] | null | null | null | unit_tests/bind_classes/expose_vector_int.h | SoapyMan/oolua | 9d25a865b05bbb6aaff56726b46e5b746572e490 | [
"MIT"
] | 2 | 2020-10-24T09:11:36.000Z | 2021-08-07T15:47:55.000Z | #ifndef EXPOSE_VECTOR_INT_H_
# define EXPOSE_VECTOR_INT_H_
# include <vector>
# include "oolua_dsl.h"
/**[StdVectorProxy]*/
//typedef the type of vector into the global namespace
//This is required as a vector has more than one template type
//and the commas in the template confuse a macro.
typedef std::vector<int> vector_int;
OOLUA_PROXY(vector_int)
//C++11 adds an overload
//OOLUA_MFUNC(push_back)
OOLUA_MEM_FUNC(void, push_back, class_::const_reference)
OOLUA_MFUNC(pop_back)
OOLUA_MFUNC_CONST(size)
OOLUA_PROXY_END
/**[StdVectorProxy]*/
#endif
| 25.409091 | 62 | 0.779964 | [
"vector"
] |
deb3c55db71b1f9248b2a27643abc571ae4d2b04 | 2,913 | h | C | Source/Dynamics/ParticleSystem/PositionBasedFluidModel.h | weikm/sandcarSimulation2 | fe499d0a3289c0ac1acce69c7dc78d8ce1b2708a | [
"Apache-2.0"
] | null | null | null | Source/Dynamics/ParticleSystem/PositionBasedFluidModel.h | weikm/sandcarSimulation2 | fe499d0a3289c0ac1acce69c7dc78d8ce1b2708a | [
"Apache-2.0"
] | null | null | null | Source/Dynamics/ParticleSystem/PositionBasedFluidModel.h | weikm/sandcarSimulation2 | fe499d0a3289c0ac1acce69c7dc78d8ce1b2708a | [
"Apache-2.0"
] | null | null | null | /**
* @author : He Xiaowei (Clouddon@sina.com)
* @date : 2019-05-14
* @description: Declaration of PositionBasedFluidModel class, which implements Position-based fluid model
* @version : 1.0
*
* @author : Zhu Fei (feizhu@pku.edu.cn)
* @date : 2021-07-27
* @description: poslish code
* @version : 1.1
*/
#pragma once
#include "Framework/Framework/NumericalModel.h"
#include "Framework/Framework/FieldVar.h"
#include "Framework/Framework/FieldArray.h"
#include "DensityPBD.h"
namespace PhysIKA {
template <typename TDataType>
class ParticleIntegrator;
template <typename TDataType>
class NeighborQuery;
template <typename TDataType>
class ImplicitViscosity;
class ForceModule;
class ConstraintModule;
/**
* PositionBasedFluidModel, implementation of the paper <Position Based Fluids>
* Usage:
* 1. Define a PositionBasedFluidModel instance
* 2. Bind the instance with a ParticleFluid node by calling Node::setNumericalModel()
* 3. Connect fields of ParticleFluid with PositionBasedFluidModel by calling Field::connect()
* We're done. PositionBasedFluidModel will be employed in advance() of the ParticleFluid.
*
* TODO(Zhu Fei): complete the code comments.
*/
template <typename TDataType>
class PositionBasedFluidModel : public NumericalModel
{
DECLARE_CLASS_1(PositionBasedFluidModel, TDataType)
public:
typedef typename TDataType::Real Real;
typedef typename TDataType::Coord Coord;
PositionBasedFluidModel();
virtual ~PositionBasedFluidModel();
void step(Real dt) override;
void setSmoothingLength(Real len)
{
m_smoothingLength.setValue(len);
}
void setRestDensity(Real rho)
{
m_restRho = rho;
}
void setIncompressibilitySolver(std::shared_ptr<ConstraintModule> solver);
void setViscositySolver(std::shared_ptr<ConstraintModule> solver);
void setSurfaceTensionSolver(std::shared_ptr<ForceModule> solver);
DeviceArrayField<Real>* getDensityField()
{
return m_pbdModule->outDensity();
}
public:
VarField<Real> m_smoothingLength;
DeviceArrayField<Coord> m_position;
DeviceArrayField<Coord> m_velocity;
DeviceArrayField<Coord> m_forceDensity;
protected:
bool initializeImpl() override;
private:
int m_pNum;
Real m_restRho;
std::shared_ptr<ForceModule> m_surfaceTensionSolver;
std::shared_ptr<ConstraintModule> m_viscositySolver;
std::shared_ptr<ConstraintModule> m_incompressibilitySolver;
std::shared_ptr<DensityPBD<TDataType>> m_pbdModule;
std::shared_ptr<ImplicitViscosity<TDataType>> m_visModule;
std::shared_ptr<ParticleIntegrator<TDataType>> m_integrator;
std::shared_ptr<NeighborQuery<TDataType>> m_nbrQuery;
};
#ifdef PRECISION_FLOAT
template class PositionBasedFluidModel<DataType3f>;
#else
template class PositionBasedFluidModel<DataType3d>;
#endif
} // namespace PhysIKA | 28.841584 | 106 | 0.744936 | [
"model"
] |
deb8cbb3c10a98dbeb448610cdba2acb8f5f9f12 | 858 | h | C | LJ1/Engine_LJ1/TextComponent.h | huwlloyd-mmu/LockdownEngine | 34a6c3a797173cfc2ce98b01643c64d4ec3bcec2 | [
"MIT"
] | null | null | null | LJ1/Engine_LJ1/TextComponent.h | huwlloyd-mmu/LockdownEngine | 34a6c3a797173cfc2ce98b01643c64d4ec3bcec2 | [
"MIT"
] | null | null | null | LJ1/Engine_LJ1/TextComponent.h | huwlloyd-mmu/LockdownEngine | 34a6c3a797173cfc2ce98b01643c64d4ec3bcec2 | [
"MIT"
] | null | null | null | #pragma once
#include <SFML/Graphics.hpp>
#include "Component.h"
#include "Texture.h"
#include "game.h"
namespace LE
{
class TextComponent : public Component
{
int charSize;
sf::Text text;
std::string fontName;
public:
virtual TextComponent* Clone() const
{
TextComponent* newText = new TextComponent(fontName, charSize);
return newText;
}
TextComponent(std::string fontName, int charSize) : fontName(fontName), charSize(charSize)
{
text.setFont(*Game::Assets().GetFont(fontName));
text.setCharacterSize(charSize);
}
virtual void Draw(sf::RenderWindow& window, const sf::Transform& transform)
{
sf::Transform t = transform;
window.draw(text, t);
}
void SetText(const std::string& t) { text.setString(t); }
void SetColor(const sf::Color& color) { text.setFillColor(color); text.setOutlineColor(color); }
};
} | 26 | 98 | 0.706294 | [
"transform"
] |
debaa31676e546e19fcb1fe5f7dfdcfc3d86492b | 4,109 | h | C | src/RootInputDesc.h | fermi-lat/RootIo | 6ee6a08b29daa1ec9acac5655f5c8485a3ed4cf0 | [
"BSD-3-Clause"
] | null | null | null | src/RootInputDesc.h | fermi-lat/RootIo | 6ee6a08b29daa1ec9acac5655f5c8485a3ed4cf0 | [
"BSD-3-Clause"
] | null | null | null | src/RootInputDesc.h | fermi-lat/RootIo | 6ee6a08b29daa1ec9acac5655f5c8485a3ed4cf0 | [
"BSD-3-Clause"
] | null | null | null | /**
* @file RootInputDesc.h
* @brief definition of the class RootInputDesc
* This class is used to set up and handle the actual root IO
*
* $Header: /nfs/slac/g/glast/ground/cvs/RootIo/src/RootInputDesc.h,v 1.16 2010/07/18 00:22:53 lsrea Exp $
* Original author: Heather Kelly heather@lheapop.gsfc.nasa.gov
*/
#ifndef RootInputDesc_h
#define RootInputDesc_h
#include "GaudiKernel/Property.h"
#include "TChain.h"
#include "TChainIndex.h"
#include "TFile.h"
#include "TObject.h"
#include <string>
class RootInputDesc
{
public:
RootInputDesc
( const StringArrayProperty& fileList,
const std::string& treeName,
const std::string& branchName,
int readRetries = 3,
TObject** branchPtr = 0,
bool rebuildIndex = true,
bool verbose=false ) ;
RootInputDesc
( TChain *t,
const std::string& treename,
const std::string& branchName,
int readRetries = 3,
TObject** branchPtr = 0,
bool rebuildIndex = true,
bool verbose=false);
~RootInputDesc() ;
/// Methods to return information about the TTree/TChain being accessed
const StringArrayProperty& getFileList() const { return m_fileList ; }
const std::string& getTreeName() const { return m_tree ; }
const std::string& getBranchName() const { return m_branch ; }
const int getNumEvents() const { return m_numEvents ; }
TChain* getTChain() { return m_chain ; }
TObject* getTObject() { return *m_dataObject ; }
/// Methods to handle reading and clearing events
TObject* getEvent( Long64_t index ) ;
TObject* getEvent( int runNum, int evtNum ) ;
bool checkEventAvailability( Long64_t index );
bool checkEventAvailability( int runNum, int evtNum );
unsigned int getIndexByEventID(int runNum, int evtNum);
void clearEvent() ;
/// Method to change the list of files in this TChain
Long64_t setFileList( const StringArrayProperty & fileList, bool verbose = false ) ;
/// Setup to read from an event collection
Long64_t setEventCollection( );
bool setBranchStatus(const std::string& branch, int status);
private :
/// Checks to see if the filename exists and can be opened
/// if treeName is non-NULL, the TTree object is checked to be sure
/// there are entries. If either fails, false is returned
bool fileExists( const std::string & filename, const char* treeName=0 ) ;
bool checkForEnvVar( const StringArrayProperty & fileList);
StringArrayProperty m_fileList ; // A list of files (fully qualified) associated to this TChain
std::string m_tree ; // The name of the tree being accessed
std::string m_branch ; // Branch name for this tree
TChain* m_chain ; // Pointer to the TChain
TTree* m_treePtr ; // For use with EventCollections
TObject** m_dataObject ; // A pointer to the pointer to the data
bool m_myDataObject; // Flag to indicate ownership of the data object pointer
Long64_t m_numEvents ; // Number of events in current TChain
bool m_verbose;
bool m_rebuildIndex; ///Flag denoting that we should force
/// the rebuild of the input files' index
TVirtualIndex* m_runEvtIndex; /// Save the RunId/EventId Index in case other indices are in use such as CompositeEventList
TChainIndex* m_chainIndex;
int m_readRetries; /// Number of times to retry ROOT read
/// in case we're dealing with a
/// transient failure
} ;
#endif
| 39.893204 | 132 | 0.584814 | [
"object"
] |
25a3e017a6a6fb6999bd2f5c9687cf3df76178a6 | 5,772 | h | C | src/common/unportable.h | jbanaszczyk/CCFinderX | 118aa3bdde30b3feff88e9fbb642389c7e19d17d | [
"MIT"
] | 2 | 2019-10-27T08:01:19.000Z | 2021-12-20T07:53:02.000Z | src/common/unportable.h | jbanaszczyk/CCFinderX | 118aa3bdde30b3feff88e9fbb642389c7e19d17d | [
"MIT"
] | 5 | 2019-05-02T16:36:39.000Z | 2019-05-12T16:04:45.000Z | src/common/unportable.h | jbanaszczyk/CCFinderX | 118aa3bdde30b3feff88e9fbb642389c7e19d17d | [
"MIT"
] | 2 | 2019-08-04T13:21:51.000Z | 2021-03-07T00:18:36.000Z | #if ! defined UNPORTABLE_H__
#define UNPORTABLE_H__
#if defined OS_UBUNTU
#define OS_UNIX
#endif
#if defined OS_WIN32
#elif defined OS_UNIX
#else
#error "OS IS NOT SPECIFIED"
#endif
#if defined _MSC_VER
#elif defined __GNUC__
#else
#error "COMPILER IS NOT SPECIFIED"
#endif
#if ! (defined BIG_ENDIAN || defined LITTLE_ENDIAN)
#error "ENDIAN IS NOT SPECIFIED"
#endif
#if defined _MSC_VER
#include <windows.h>
#define my_sleep(x) Sleep(x)
#elif defined __GNUC__
#include <unistd.h>
#define my_sleep(x) usleep(x / 1000)
#endif
#include <string>
#include <set>
#include <vector>
#include <limits>
#include <boost/optional.hpp>
#if defined _MSC_VER
#undef max
#undef min
#endif
std::string escape_spaces(const std::string &str);
bool splitpath(const std:: string &path, std:: string *pDir, std:: string *pFname, std:: string *pExt);
std:: string make_temp_file_on_the_same_directory(
const std:: string &filePath, const std:: string &base, const std:: string &ext);
std:: string make_filename_on_the_same_directory(
const std:: string &fileName, const std:: string &targetPathFile);
bool find_files(std:: vector<std:: string> *pFiles, const std:: set<std:: string> &extensions, const std:: string &directory);
bool find_named_directories(std:: vector<std:: string> *pFiles, const std:: set<std:: string> &names, const std:: string &directory);
std::string get_application_data_path();
struct PathTime {
public:
std:: string path;
time_t mtime;
public:
static bool getFileMTime(const std:: string &path, PathTime *pPathTime);
public:
bool operator==(const PathTime &right) const
{
return path == right.path && mtime == right.mtime;
}
bool operator!=(const PathTime &right) const { return ! operator==(right); }
};
#if defined _MSC_VER
class MappedFileReader {
private:
std:: string fileName;
HANDLE hMapping;
LARGE_INTEGER size;
const char *aByte;
bool opened;
public:
MappedFileReader()
: hMapping(NULL), size(), aByte(NULL), opened(false)
{
}
~MappedFileReader()
{
close();
}
void swap(MappedFileReader &right)
{
fileName.swap(right.fileName);
std:: swap(hMapping, right.hMapping);
std:: swap(size, right.size);
std:: swap(aByte, right.aByte);
std:: swap(opened, right.opened);
}
bool open(const std:: string &fileName_)
{
if (opened) {
close();
}
fileName = fileName_;
opened = false;
HANDLE hFile = ::CreateFile(
fileName.c_str(),
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ,
NULL,
OPEN_EXISTING,
0,
NULL
);
if (hFile == 0) {
return false; // fail
}
if (! ::GetFileSizeEx(hFile, &size)) {
return false; // fail
}
hMapping = ::CreateFileMapping(
hFile,
NULL,
PAGE_READWRITE,
0,
0,
NULL
);
::CloseHandle(hFile);
aByte = (const char *)::MapViewOfFile(
hMapping,
FILE_MAP_READ | FILE_MAP_WRITE,
0,
0,
0
);
opened = true;
return true;
}
void close()
{
if (opened) {
opened = false;
::CloseHandle(hMapping);
hMapping = NULL;
::UnmapViewOfFile(aByte);
aByte = NULL;
fileName.clear();
}
}
size_t getSize() const
{
if (opened) {
assert(size.QuadPart <= std::numeric_limits<size_t>::max());
return (size_t)size.QuadPart;
}
else {
return 0;
}
}
const char *ref() const
{
if (opened) {
return aByte;
}
else {
return NULL;
}
}
bool isOpened() const
{
return opened;
}
const std:: string getFileName() const
{
return fileName;
}
};
#elif defined __GNUC__
#endif
std::string file_separator();
bool path_is_relative(const std::string &path);
//void split_path(const std::string &path, std::string *pDirectory, std::string *pFileName);
std::string join_path(const std::string &s1, const std::string &s2);
bool path_exists(const std::string &path);
bool path_is_file(const std::string &path);
//template <typename IntegerType>
//void flip_endian(IntegerType *pValue)
//{
// flip_endian((void *)pValue, (size_t)sizeof(IntegerType));
//}
void flip_endian(void *pIntegerValue, size_t sizeofIntegerType);
#if defined _MSC_VER
void nice(int vaule); // make own process priority low, when value > 10.
bool allocWorkingSetMemory(long long size);
#else
#define nice(value)
#define allocWorkingSetMemory(size)
#endif
#if defined _MSC_VER
#define ALLOC_TRICK_IN_CLASS_DECLARATION(className) \
private: \
static HANDLE s_hHeap; \
static UINT s_uNumAllocsInHeap; \
public: \
void *operator new(size_t size); \
void operator delete(void *p); \
private:
#define ALLOC_TRICK_DEFINITIONS(className) \
HANDLE className::s_hHeap = NULL; \
UINT className::s_uNumAllocsInHeap = 0; \
\
void *className::operator new(size_t size) \
{ \
if (s_hHeap == NULL) { \
s_hHeap = HeapCreate(HEAP_NO_SERIALIZE, 0, 0); \
\
if (s_hHeap == NULL) { \
return NULL; \
} \
} \
\
void *p = HeapAlloc(s_hHeap, 0, size); \
\
if (p != NULL) { \
s_uNumAllocsInHeap++; \
} \
\
return p; \
} \
\
void className::operator delete(void *p) \
{ \
if (HeapFree(s_hHeap, 0, p)) { \
--s_uNumAllocsInHeap; \
} \
\
if (s_uNumAllocsInHeap == 0) { \
if (HeapDestroy(s_hHeap)) { \
s_hHeap = NULL; \
} \
} \
}
#else
#define ALLOC_TRICK_IN_CLASS_DECL(className)
#define ALLOC_TRICK_DEFINITIONS(className)
#endif
#if defined _MSC_VER
#define F_SEQUENTIAL_ACCESS_OPTIMIZATION "S"
#define F_TEMPORARY_FILE_OPTIMIZATION "T"
#else
#define F_SEQUENTIAL_ACCESS_OPTIMIZATION
#define F_TEMPORARY_FILE_OPTIMIZATION
#endif
#if defined __GNUC__
int systemv(const std::vector<std::string> &argv);
#endif
boost::optional<std::string> getenvironmentvariable(const std::string &name);
#if defined _MSC_VER
boost::optional<std::string> get_short_path_name(const std::string &path);
#endif
#endif // UNPORTABLE_H__
| 18.92459 | 133 | 0.687457 | [
"vector"
] |
25b77295dbd0f9dde42d0bc9c4a9382a5ac91679 | 1,554 | h | C | includes/computation.h | danmohedano/fourier_drawing | 2abb40793590472fed53924cd7b16331b3208588 | [
"MIT"
] | null | null | null | includes/computation.h | danmohedano/fourier_drawing | 2abb40793590472fed53924cd7b16331b3208588 | [
"MIT"
] | null | null | null | includes/computation.h | danmohedano/fourier_drawing | 2abb40793590472fed53924cd7b16331b3208588 | [
"MIT"
] | null | null | null | /**
* 29/07/2021
* Module: computation
* -----------------------------------------------------------------------------
* Authors:
* - Daniel Mohedano <https://github.com/danmohedano>
* -----------------------------------------------------------------------------
* Module responsible for the computation of the Fourier transform
*/
#ifndef COMPUTATION_H
#define COMPUTATION_H
#include "../includes/data.h"
#include <complex>
#include <vector>
/**
* Function: compute
* ----------------------------------------------------------------------------
* Computes the n vectors requested to represent the function described by
* the points provided. The operation is made using the following integral:
* Vector_n = Cn*e^(n*2*PI*i*t)
* Cn = integral[0,1](f(t)*e^(-n*2*PI*i*t)*dt)
*
* params:
* - n: number of vectors requested
* - points: function described by its points
* - dt: time step used for the integral
*
* returns: vector of DrawingVectors
*/
std::vector<DrawingVector> compute(uint16_t n, std::vector<std::complex<double>> points, double dt);
/**
* Function: integral
* ----------------------------------------------------------------------------
* Computes the integral for the initialization constant vector of index "index"
*
* params:
* - index: index of the vector
* - points: function described by its points
* - dt: time step used for the integral
*
* returns: DrawingVector with the result
*/
DrawingVector integral(int16_t index, std::vector<std::complex<double>> points, double dt);
#endif | 31.714286 | 100 | 0.557272 | [
"vector",
"transform"
] |
25bb240e9a3429bdb2a94aa7419ca3912af09b10 | 6,982 | h | C | databaseBuild/codebase/rbf/rbfm.h | AllenInWood/databaseBuild | 7eb0e4588f3b797ddceec6f3be6cb74a11e5447d | [
"Apache-2.0"
] | 3 | 2018-06-11T09:20:26.000Z | 2019-02-24T18:26:02.000Z | databaseBuild/codebase/rbf/rbfm.h | AllenInWood/databaseBuild | 7eb0e4588f3b797ddceec6f3be6cb74a11e5447d | [
"Apache-2.0"
] | null | null | null | databaseBuild/codebase/rbf/rbfm.h | AllenInWood/databaseBuild | 7eb0e4588f3b797ddceec6f3be6cb74a11e5447d | [
"Apache-2.0"
] | null | null | null | #ifndef _rbfm_h_
#define _rbfm_h_
#include <bitset>
#include <vector>
#include <climits>
#include "../rbf/pfm.h"
using namespace std;
/* Record ID */
typedef struct
{
unsigned pageNum; /* page number */
unsigned slotNum; /* slot number in the page */
} RID;
/* Attribute */
typedef enum { TypeInt = 0, TypeReal, TypeVarChar } AttrType; /* Int and Real are 4 bytes, but for VarChar */
typedef unsigned AttrLength;
struct Attribute {
string name; /* attribute name */
AttrType type; /* attribute type */
AttrLength length; /* attribute length */
};
/* Comparison Operator (NOT needed for part 1 of the project) */
typedef enum { EQ_OP = 0, /* no condition// = */
LT_OP, /* < */
LE_OP, /* <= */
GT_OP, /* > */
GE_OP, /* >= */
NE_OP, /* != */
NO_OP /* no condition */
} CompOp;
/********************************************************************************
* The scan iterator is NOT required to be implemented for the part 1 of the project
********************************************************************************/
#define RBFM_EOF (-1) /* end of a scan operator */
/*
* RBFM_ScanIterator is an iterator to go through records
* The way to use it is like the following:
* RBFM_ScanIterator rbfmScanIterator;
* rbfm.open(..., rbfmScanIterator);
* while (rbfmScanIterator.getNextRecord(rid, data) != RBFM_EOF) {
* process the data;
* }
* rbfmScanIterator.close();
*/
class RBFM_ScanIterator {
public:
RBFM_ScanIterator()
{
index = 0;
};
~RBFM_ScanIterator()
{
};
vector<RID> returnedRID;
vector<vector<char> > returnedData;
/*
* Never keep the results in the memory. When getNextRecord() is called,
* a satisfying record needs to be fetched from the file.
* "data" follows the same format as RecordBasedFileManager::insertRecord().
*/
RC getNextRecord( RID &rid, void *data )
{
if ( index >= (int) returnedRID.size() )
{
return(RBFM_EOF);
}
rid = returnedRID[index];
vector<char> vData = returnedData[index];
for ( unsigned int i = 0; i < vData.size(); i++ )
{
memcpy( (char *) data + i, &vData[i], sizeof(char) );
}
index++;
return(0);
};
RC close()
{
returnedRID.clear();
returnedData.clear();
return(0);
};
private:
int index;
};
class RecordBasedFileManager : public PagedFileManager
{
public:
static RecordBasedFileManager* instance();
static void destroyInstance();
RC createFile( const string &fileName );
RC destroyFile( const string &fileName );
RC openFile( const string &fileName, FileHandle &fileHandle );
RC closeFile( FileHandle &fileHandle );
RC recordConverter( FileHandle &fileHandle, const vector<Attribute> &recordDescriptor, const void *data, void *record, short int &recordSize );
RC recordWrapper( FileHandle &fileHandle, const vector<Attribute> &recordDescriptor, const void *record, void *data, const short int recordSize, int &newSize );
/*
* Format of the data passed into the function is the following:
* [n byte-null-indicators for y fields] [actual value for the first field] [actual value for the second field] ...
* 1) For y fields, there is n-byte-null-indicators in the beginning of each record.
* The value n can be calculated as: ceil(y / 8). (e.g., 5 fields => ceil(5 / 8) = 1. 12 fields => ceil(12 / 8) = 2.)
* Each bit represents whether each field value is null or not.
* If k-th bit from the left is set to 1, k-th field value is null. We do not include anything in the actual data part.
* If k-th bit from the left is set to 0, k-th field contains non-null values.
* If there are more than 8 fields, then you need to find the corresponding byte first,
* then find a corresponding bit inside that byte.
* 2) Actual data is a concatenation of values of the attributes.
* 3) For Int and Real: use 4 bytes to store the value;
* For Varchar: use 4 bytes to store the length of characters, then store the actual characters.
* !!! The same format is used for updateRecord(), the returned data of readRecord(), and readAttribute().
* For example, refer to the Q8 of Project 1 wiki page.
*/
RC insertRecord( FileHandle &fileHandle, const vector<Attribute> &recordDescriptor, const void *data, RID &rid );
RC readRecord( FileHandle &fileHandle, const vector<Attribute> &recordDescriptor, const RID &rid, void *data );
/*
* This method will be mainly used for debugging/testing.
* The format is as follows:
* field1-name: field1-value field2-name: field2-value ... \n
* (e.g., age: 24 height: 6.1 salary: 9000
* age: NULL height: 7.5 salary: 7500)
*/
RC printRecord( const vector<Attribute> &recordDescriptor, const void *data );
/******************************************************************************************************************************************************************
* IMPORTANT, PLEASE READ: All methods below this comment (other than the constructor and destructor) are NOT required to be implemented for the part 1 of the project
******************************************************************************************************************************************************************/
RC deleteRecord( FileHandle &fileHandle, const vector<Attribute> &recordDescriptor, const RID &rid );
/* Assume the RID does not change after an update */
RC updateRecord( FileHandle &fileHandle, const vector<Attribute> &recordDescriptor, const void *data, const RID &rid );
RC readAttribute( FileHandle &fileHandle, const vector<Attribute> &recordDescriptor, const RID &rid, const string &attributeName, void *data );
/* Scan returns an iterator to allow the caller to go through the results one by one. */
RC scan( FileHandle &fileHandle,
const vector<Attribute> &recordDescriptor,
const string &conditionAttribute,
const CompOp compOp, /* comparision type such as "<" and "=" */
const void *value, /* used in the comparison */
const vector<string> &attributeNames, /* a list of projected attributes */
RBFM_ScanIterator &rbfm_ScanIterator );
public:
protected:
RecordBasedFileManager();
~RecordBasedFileManager();
private:
static RecordBasedFileManager *_rbf_manager;
bool Comp( void *m1, const void *m2, AttrType type, const CompOp compop );
};
#endif
| 35.805128 | 166 | 0.578058 | [
"vector"
] |
25c58753e513a232d66635d7102b36592d8652e7 | 1,885 | h | C | ios/chrome/browser/ui/settings/save_passwords_collection_view_controller.h | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | ios/chrome/browser/ui/settings/save_passwords_collection_view_controller.h | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | ios/chrome/browser/ui/settings/save_passwords_collection_view_controller.h | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // Copyright 2015 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 IOS_CHROME_BROWSER_UI_SETTINGS_SAVE_PASSWORDS_COLLECTION_VIEW_CONTROLLER_H_
#define IOS_CHROME_BROWSER_UI_SETTINGS_SAVE_PASSWORDS_COLLECTION_VIEW_CONTROLLER_H_
#import "ios/chrome/browser/ui/settings/password_details_collection_view_controller_delegate.h"
#import "ios/chrome/browser/ui/settings/settings_root_collection_view_controller.h"
#include <memory>
#include <vector>
namespace autofill {
struct PasswordForm;
} // namespace autofill
namespace ios {
class ChromeBrowserState;
} // namespace ios
@protocol ReauthenticationProtocol;
@class PasswordExporter;
@interface SavePasswordsCollectionViewController
: SettingsRootCollectionViewController
// The designated initializer. |browserState| must not be nil.
- (instancetype)initWithBrowserState:(ios::ChromeBrowserState*)browserState
NS_DESIGNATED_INITIALIZER;
- (instancetype)initWithLayout:(UICollectionViewLayout*)layout
style:(CollectionViewControllerStyle)style
NS_UNAVAILABLE;
@end
@interface SavePasswordsCollectionViewController (
Testing)<PasswordDetailsCollectionViewControllerDelegate>
// Callback called when the async request launched from
// |getLoginsFromPasswordStore| finishes.
- (void)onGetPasswordStoreResults:
(const std::vector<std::unique_ptr<autofill::PasswordForm>>&)result;
// Initializes the password exporter with a (fake) |reauthenticationModule|.
- (void)setReauthenticationModuleForExporter:
(id<ReauthenticationProtocol>)reauthenticationModule;
// Returns the password exporter to allow setting fake testing objects on it.
- (PasswordExporter*)getPasswordExporter;
@end
#endif // IOS_CHROME_BROWSER_UI_SETTINGS_SAVE_PASSWORDS_COLLECTION_VIEW_CONTROLLER_H_
| 33.660714 | 95 | 0.818568 | [
"vector"
] |
25c7ab83add384e6526b9887cbd4ea7f0f7f7d69 | 1,077 | h | C | TTPMLPPmoon/AddLibrary/MosaiKe/MosaiView/MosaiView.h | Ropponngi/TTPMLPPmoon | 877bfc63f530adfa5542724545c81f5cfd6f1866 | [
"MIT"
] | 220 | 2021-02-11T01:59:29.000Z | 2021-04-25T02:36:13.000Z | TTPMLPPmoon/AddLibrary/MosaiKe/MosaiView/MosaiView.h | Ropponngi/TTPMLPPmoon | 877bfc63f530adfa5542724545c81f5cfd6f1866 | [
"MIT"
] | null | null | null | TTPMLPPmoon/AddLibrary/MosaiKe/MosaiView/MosaiView.h | Ropponngi/TTPMLPPmoon | 877bfc63f530adfa5542724545c81f5cfd6f1866 | [
"MIT"
] | null | null | null | //
// MosaiView.h
// MosaiDemo
//
// Created by Sylar on 2018/4/2.
// Copyright © 2018年 Sylar. All rights reserved.
//
#import <UIKit/UIKit.h>
@protocol MosaiViewDelegate;
@interface MosaiView : UIView
//底图为马赛克图
@property (nonatomic, strong) UIImage *mosaicImage;
//表图为正常图片
@property (nonatomic, strong) UIImage *originalImage;
//OperationCount
@property (nonatomic, assign, readonly) NSInteger operationCount;
//CurrentIndex
@property (nonatomic, assign, readonly) NSInteger currentIndex;
//Delegate
@property (nonatomic, weak) id<MosaiViewDelegate> deleagate;
//ResetMosai
-(void)resetMosaiImage;
-(void)updateLineWidth;
//Redo
-(void)redo;
//Undo
-(void)undo;
-(BOOL)canUndo;
-(BOOL)canRedo;
//Render
-(UIImage*)render;
@end
@protocol MosaiViewDelegate<NSObject>
-(void)mosaiView:(MosaiView*)view TouchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event;
-(void)mosaiView:(MosaiView*)view TouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;
-(void)mosaiView:(MosaiView*)view TouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
@end
| 20.320755 | 102 | 0.744661 | [
"render"
] |
25cf2938ecfc77181a2d458fc5336b029fd50b42 | 9,265 | h | C | src/engine/Playout.h | dsmic/oakfoam | f4093d57ea173d5dc00e0f6031ed16f169258456 | [
"BSD-2-Clause"
] | 2 | 2019-08-27T04:18:45.000Z | 2021-04-20T23:14:24.000Z | src/engine/Playout.h | dsmic/oakfoam | f4093d57ea173d5dc00e0f6031ed16f169258456 | [
"BSD-2-Clause"
] | null | null | null | src/engine/Playout.h | dsmic/oakfoam | f4093d57ea173d5dc00e0f6031ed16f169258456 | [
"BSD-2-Clause"
] | null | null | null | #ifndef DEF_OAKFOAM_PLAYOUT_H
#define DEF_OAKFOAM_PLAYOUT_H
#include "Go.h"
#include <boost/bimap.hpp>
#include <unordered_map>
#include <boost/random.hpp>
//from "Parameters.h":
class Parameters;
//from "Tree.h":
class Tree;
//from "Worker.h":
namespace Worker
{
class Settings;
};
#include "../gtp/Gtp.h"
typedef struct
{
float crit;
float ownselfblack;
float ownselfwhite;
float ownblack;
float ownwhite;
bool isbadwhite; //marked if in one playout was bad, so that not many times with low prob lead to always move
bool isbadblack;
float slopewhite;
float slopeblack;
} critstruct;
/** Playouts. */
class Playout
{
public:
/** Create a playout instance with given parameters. */
Playout(Parameters *prms);
~Playout();
/** Perform a playout.
* @param[in] settings Settings of this worker thread.
* @param[in] board Board to perform the playout on.
* @param[out] finalscore Final score of the playout.
* @param[in] playouttree Tree leaf node that the playout is started from.
* @param[in] playoutmoves List of moves leading up to the start of the playout.
* @param[in] colfirst Color to move first.
* @param[out] firstlist List of location where the first color played.
* @param[out] secondlist List of location where the other color played.
* @param[out] movereasons List of reasons for making moves.
*/
void doPlayout(Worker::Settings *settings, Go::Board *board, float &finalscore, float &cnn_winrate, Tree *playouttree, std::list<Go::Move> &playoutmoves, Go::Color colfirst, Go::IntBoard *firstlist, Go::IntBoard *secondlist, Go::IntBoard *earlyfirstlist, Go::IntBoard *earlysecondlist, std::list<std::string> *movereasons=NULL);
/** Get a playout move for a given situation. */
void getPlayoutMove(Worker::Settings *settings, Go::Board *board, Go::Color col, Go::Move &move, critstruct critarray[], float ravearray[], int passes=0, std::vector<int> *pool=NULL, std::vector<int> *poolcrit=NULL, std::string *reason=NULL,float *trylocal_p=NULL, float *black_gammas=NULL, float *white_gammas=NULL, bool *earlymoves=NULL,Go::IntBoard *firstlist=NULL,int playoutmovescount=0, bool *nonlocalmove=NULL,Go::IntBoard *treeboardBlack=NULL,Go::IntBoard *treeboardWhite=NULL, int used_playouts=0, boost::bimap<int,float> *cnn_moves=NULL,float *gamma_gradient_local=NULL) __attribute__((hot));
/** Check for a useless move according to the Crazy Stone heuristic.
* @todo Consider incorporating this into getPlayoutMove()
*/
void checkUselessMove(Worker::Settings *settings, Go::Board *board, Go::Color col, Go::Move &move, std::string *reason=NULL);
/** Reset LGRF values. */
void resetLGRF();
private:
Parameters *const params;
Gtp::Engine *gtpe;
int *lgrf1,*lgrf1o,*lgrf2;
bool *lbm; //last bad move
unsigned char *lgrf1n;
unsigned int *lgrf1hash,*lgrf1hash2,*lgrf2hash;
int *lgrf1count,*lgrf2count;
unsigned int *lgpf; // last good play with forgetting
unsigned long int *lgpf_b;
bool *badpassanswer;
int lgrfpositionmax;
//boost::random::lagged_fibonacci607 *rng;
//boost::uniform_01<boost::random::lagged_fibonacci607> *randomgen;
void getPlayoutMove(Worker::Settings *settings, Go::Board *board, Go::Color col, Go::Move &move, int *posarray, critstruct critarray[], float ravearray[], int passes=0, std::vector<int> *pool=NULL, std::vector<int> *poolcrit=NULL, std::string *reason=NULL,float *trylocal_p=NULL,float *black_gammas=NULL,float *white_gammas=NULL, bool *earlymoves=NULL,Go::IntBoard *firstlist=NULL,int playoutmovescount=0, bool *nonlocalmove=NULL,Go::IntBoard *treeboardBlack=NULL,Go::IntBoard *treeboardWhite=NULL, int used_playouts=0, boost::bimap<int,float> *cnn_moves=NULL,float *gamma_gradient_local=NULL);
void checkUselessMove(Worker::Settings *settings, Go::Board *board, Go::Color col, Go::Move &move, int *posarray, std::string *reason=NULL);
void getPoolRAVEMove(Worker::Settings *settings, Go::Board *board, Go::Color col, Go::Move &move, std::vector<int> *pool=NULL);
void getLGRF2Move(Worker::Settings *settings, Go::Board *board, Go::Color col, Go::Move &move);
void getLGRF1Move(Worker::Settings *settings, Go::Board *board, Go::Color col, Go::Move &move);
void getLGRF1oMove(Worker::Settings *settings, Go::Board *board, Go::Color col, Go::Move &move);
void getLGPFMove(Worker::Settings *settings, Go::Board *board, Go::Color col, Go::Move &move, int *posarray);
void getFeatureMove(Worker::Settings *settings, Go::Board *board, Go::Color col, Go::Move &move);
void getAnyCaptureMove(Worker::Settings *settings, Go::Board *board, Go::Color col, Go::Move &move, int *posarray);
void getPatternMove(Worker::Settings *settings, Go::Board *board, Go::Color col, Go::Move &move, int *posarray, int passes, critstruct critarray[]=NULL, float *bgamma=NULL) __attribute__((hot));
void getFillBoardMove(Worker::Settings *settings, Go::Board *board, Go::Color col, Go::Move &move, int *posarray, int passes, std::string *reason);
void getFillBoardMoveBestPattern(Worker::Settings *settings, Go::Board *board, Go::Color col, Go::Move &move, int *posarray, int passes, std::string *reason);
void getNakadeMove(Worker::Settings *settings, Go::Board *board, Go::Color col, Go::Move &move, int *posarray);
void getLast2LibAtariMove(Worker::Settings *settings, Go::Board *board, Go::Color col, Go::Move &move, int *posarray, int *blevel=NULL) __attribute__((hot));
void getLastCaptureMove(Worker::Settings *settings, Go::Board *board, Go::Color col, Go::Move &move, int *posarray, std::set<int> *capturemoves=NULL);
void getLastAtariMove(Worker::Settings *settings, Go::Board *board, Go::Color col, Go::Move &move, int *posarray,float p, std::set<int> *capturemoves=NULL);
void getAtariMove(Worker::Settings *settings, Go::Board *board, Go::Color col, Go::Move &move, int *posarray);
void getNearbyMove(Worker::Settings *settings, Go::Board *board, Go::Color col, Go::Move &move);
void checkEyeMove(Worker::Settings *settings, Go::Board *board, Go::Color col, Go::Move &move, int *posarray, Go::Move &replacemove);
void checkAntiEyeMove(Worker::Settings *settings, Go::Board *board, Go::Color col, Go::Move &move, int *posarray, Go::Move &replacemove);
void checkEmptyTriangleMove(Worker::Settings *settings, Go::Board *board, Go::Color col, Go::Move &move, int *posarray, Go::Move &replacemove);
bool isBadMove(Worker::Settings *settings, Go::Board *board, Go::Color col, int pos, float lbr_p=0.0, float lbm_p=0.0, float lbpr_p=0.0, int passes=0, Go::IntBoard *firstlist=NULL, int playoutmovescount=0, critstruct critarray[]=NULL) __attribute__((hot));
bool isEyeFillMove(Go::Board *board, Go::Color col, int pos);
float getTwoLibertyMoveLevel(Go::Board *board, Go::Move move, Go::Group *group, bool only_bigger_7=false);
//inline int getOtherOneOfTwoLiberties(Go::Board *board,Go::Group *g, int pos);
int getLGRF1(Go::Color col, int pos1) const;
unsigned int getLGRF1hash(Go::Color col, int pos1) const;
unsigned int getLGRF1hash2(Go::Color col, int pos1) const;
//int getLGRF1n_l(Go::Color col, int pos1) const;
int getLGRF1o(Go::Color col, int pos1) const;
int getLGRF2(Go::Color col, int pos1, int pos2) const;
unsigned int getLGRF2hash(Go::Color col, int pos1, int pos2) const;
void setLGRF1(Go::Color col, int pos1, int val);
void setLGRF1(Go::Color col, int pos1, int val, unsigned int hash, unsigned int hash2);
void setLGRF1n(Go::Color col, int pos1, int val);
void setLGRF1o(Go::Color col, int pos1, int val);
void setLGRF2(Go::Color col, int pos1, int pos2, int val);
void setLGRF2(Go::Color col, int pos1, int pos2, int val, unsigned int hash);
void setLGPF(Worker::Settings *settings, Go::Color col, int pos1, unsigned int val);
void setLGPF(Worker::Settings *settings, Go::Color col, int pos1, unsigned int val, unsigned long int val_b);
bool hasLGRF1(Go::Color col, int pos1) const;
bool hasLGRF1n(Go::Color col, int pos1, int pos) const;
bool hasLBM(Go::Color col, int val) const;
bool hasLGRF1o(Go::Color col, int pos1) const;
bool hasLGRF2(Go::Color col, int pos1, int pos2) const;
bool hasLGPF(Go::Color col, int pos1, unsigned int hash) const;
bool hasLGPF(Go::Color col, int pos1, unsigned int hash, unsigned long int hash_b) const;
void clearLGRF1(Go::Color col, int pos1);
//void clearLGRF1n(Go::Color col, int pos1);
void clearLGRF1n(Go::Color col, int pos1, int val);
void clearLGRF1o(Go::Color col, int pos1);
void clearLGRF2(Go::Color col, int pos1, int pos2);
void clearLGPF(Go::Color col, int pos1);
void clearLGPF(Go::Color col, int pos1, unsigned int hash);
void clearLGPF(Go::Color col, int pos1, unsigned int hash, unsigned long int hash_b);
void clearBadPassAnswer(Go::Color col, int pos1);
void setBadPassAnswer(Go::Color col, int pos1);
bool isBadPassAnswer(Go::Color col, int pos1);
inline void replaceWithApproachMove(Worker::Settings *settings, Go::Board *board, Go::Color col, int &pos);
};
#endif
| 61.766667 | 607 | 0.709336 | [
"vector"
] |
25da504f3e3bc181ef9d323b70f9589e2bc493e3 | 403 | h | C | include/snap/readers.h | dkw-aau/trident-clone | 18f896db2be05870069ae7b3aa6b4837c74fff0f | [
"Apache-2.0"
] | 20 | 2018-10-17T21:39:40.000Z | 2021-11-10T11:07:23.000Z | include/snap/readers.h | dkw-aau/trident-clone | 18f896db2be05870069ae7b3aa6b4837c74fff0f | [
"Apache-2.0"
] | 5 | 2020-07-06T22:50:04.000Z | 2022-03-17T10:34:15.000Z | include/snap/readers.h | dkw-aau/trident-clone | 18f896db2be05870069ae7b3aa6b4837c74fff0f | [
"Apache-2.0"
] | 9 | 2018-09-18T11:37:35.000Z | 2022-03-29T07:46:41.000Z | #ifndef _READERS_H
#define _READERS_H
#include <trident/binarytables/factorytables.h>
#include <vector>
class KB;
class SnapReaders {
public:
typedef int64_t (*pReader)(const char*, const int64_t);
const static pReader readers[256];
static std::vector<const char*> f_sop;
static std::vector<const char*> f_osp;
static void loadAllFiles(KB *kb);
};
#endif
| 21.210526 | 63 | 0.677419 | [
"vector"
] |
25ddbfa443d8aa89f1cf1a2ca46ff8d403295772 | 7,023 | h | C | src/HSADebugAgent/Include/AgentBreakpoint.h | HSAFoundation/HSA-Debugger-Source-AMD | 47d41b74bfb51f1bec02763feb7ab752ce80272a | [
"MIT"
] | 2 | 2017-05-22T17:22:22.000Z | 2019-05-16T01:45:06.000Z | src/HSADebugAgent/Include/AgentBreakpoint.h | HSAFoundation/HSA-Debugger-Source-AMD | 47d41b74bfb51f1bec02763feb7ab752ce80272a | [
"MIT"
] | 2 | 2016-01-28T15:22:07.000Z | 2016-01-28T15:43:42.000Z | src/HSADebugAgent/Include/AgentBreakpoint.h | HSAFoundation/HSA-Debugger-Source-AMD | 47d41b74bfb51f1bec02763feb7ab752ce80272a | [
"MIT"
] | 2 | 2016-02-07T18:46:52.000Z | 2020-05-03T22:18:06.000Z | //==============================================================================
// Copyright (c) 2015 Advanced Micro Devices, Inc. All rights reserved.
//
/// \author AMD Developer Tools
/// \file AgentBreakpoint.h
/// \brief Agent breakpoint structure
//==============================================================================
#ifndef _AGENT_BREAKPOINT_H_
#define _AGENT_BREAKPOINT_H_
#include "AgentContext.h"
#include "AgentLogging.h"
#include "CommunicationControl.h"
namespace HwDbgAgent
{
/// GDB assigns a integer breakpoint id to each breakpoint
typedef int GdbBkptId;
const GdbBkptId g_UNKOWN_GDB_BKPT_ID = -9999;
typedef enum
{
HSAIL_BREAKPOINT_STATE_UNKNOWN, ///< We havent set breakpoint state yet
HSAIL_BREAKPOINT_STATE_PENDING, ///< HSAIL breakpoint received and not yet been created
HSAIL_BREAKPOINT_STATE_DISABLED, ///< HSAIL Breakpoint has been created but is disabled
HSAIL_BREAKPOINT_STATE_ENABLED, ///< HSAIL Breakpoint has been created and is enabled
} HsailBkptState;
typedef enum
{
HSAIL_BREAKPOINT_TYPE_UNKNOWN, ///< We havent set breakpoint type yet
HSAIL_BREAKPOINT_TYPE_TEMP_PC_BP, ///< This is a temp PC breakpoint
HSAIL_BREAKPOINT_TYPE_PC_BP, ///< A program counter breakpoint
HSAIL_BREAKPOINT_TYPE_DATA_BP, ///< A data breakpoint
HSAIL_BREAKPOINT_TYPE_KERNEL_NAME_BP,///< A kernel name breakpoint
} HsailBkptType;
/// A single condition for a breakpoint.
/// This class is stored within a AgentBreakpoint.
/// The condition is evaluated by calling CheckCondition() calls
class AgentBreakpointCondition
{
public:
AgentBreakpointCondition():
m_workitemID(g_UNKNOWN_HWDBGDIM3),
m_workgroupID(g_UNKNOWN_HWDBGDIM3),
m_conditionCode(HSAIL_BREAKPOINT_CONDITION_ANY)
{
AGENT_LOG("Allocate an AgentBreakpointCondition");
}
~AgentBreakpointCondition()
{
}
/// Populate from the condition packet we get from GDB
/// \param[in] The condition packet we get from GDB
/// \return HSAIL agent status
HsailAgentStatus SetCondition(const HsailConditionPacket& pCondition);
/// Check the condition against a workgroup and workitem pair
HsailAgentStatus CheckCondition(const HwDbgDim3 ipWorkGroup, const HwDbgDim3 ipWorkItem, bool& conditionCodeOut) const;
/// Check the condition against a wavefront
/// It is easier to just check the waveinfo structure directly.
/// The checkCondition function can be implemented in multiple forms, with the SIMT model
///
/// \param[in] pWaveInfo An entry from the waveinfo buffer
/// \param[out] conditionCodeOut Return true if the condition matches
/// \param[out] conditionTypeOut The type of condition. Based on this type the focus control changes focus
/// \return HSAIL agent status
HsailAgentStatus CheckCondition(const HwDbgWavefrontInfo* pWaveInfo,
bool& conditionCodeOut,
HsailConditionCode& conditionTypeOut) const;
/// Get function to get the workgroup, used for FocusControl
/// \return The work group used for this condition
HwDbgDim3 GetWG() const;
/// Get function to get the workitem, used for FocusControl
/// \return The work item used for this condition
HwDbgDim3 GetWI() const;
/// Print the condition to the AGENT_OP
void PrintCondition() const;
private:
/// Disable copy constructor
AgentBreakpointCondition(const AgentBreakpointCondition&);
/// Disable assignment operator
AgentBreakpointCondition& operator=(const AgentBreakpointCondition&);
/// The work group used to match this condition
HwDbgDim3 m_workitemID;
/// The work item used to match this condition
HwDbgDim3 m_workgroupID;
/// The type of condition
HsailConditionCode m_conditionCode;
};
/// A single HSAIL breakpoint, includes the GDB::DBE handle information
class AgentBreakpoint
{
public:
/// The present state of the breakpoint
/// \todo make this private since it should only be changed by the DBE functions
HsailBkptState m_bpState;
/// Number of times the BP was hit (unit reported in: wavefronts)
int m_hitcount;
/// The GDB IDs that map to this PC
std::vector<GdbBkptId> m_GdbId;
/// The PC we set the breakpoint on
HwDbgCodeAddress m_pc;
/// The type of the breakpoint
HsailBkptType m_type;
/// The line message that will be printed
/// The constant g_HSAIL_BKPT_MESSAGE_LEN will limit the length of this string since
/// it is sent within a packet from GDB
std::string m_lineName;
/// The HSAIL source line number
int m_lineNum;
/// Kernel name - used for function breakpoints
std::string m_kernelName;
/// The condition that will be checked for this breakpoint.
/// Presently hsail-gdb supports only one condition at a time per breakable line
AgentBreakpointCondition m_condition;
AgentBreakpoint():
m_bpState(HSAIL_BREAKPOINT_STATE_UNKNOWN),
m_hitcount(0),
m_GdbId(),
m_pc(HSAIL_ISA_PC_UNKOWN),
m_type(HSAIL_BREAKPOINT_TYPE_UNKNOWN),
m_lineName("Unknown Line"),
m_lineNum(-1),
m_kernelName(""),
m_condition(),
m_handle(nullptr)
{
AGENT_LOG("Allocate an AgentBreakpoint");
}
/// Find a position in the payload and updates the payload with its hitcount
HsailAgentStatus UpdateNotificationPayload(HsailNotificationPayload* payload) const;
/// Just print the appropriate message for the breakpoint type
void PrintHitMessage() const;
/// This function calls the DBE for the first time, otherwise it remembers the GDB ID
/// \param[in] The DBE context handle
/// \param[in] The GDB ID for this breakpoint
/// \return HSAIL agent status
HsailAgentStatus CreateBreakpointDBE(const HwDbgContextHandle DbeContextHandle,
const GdbBkptId gdbId = g_UNKOWN_GDB_BKPT_ID);
/// Delete breakpoint - for kernel source
/// This function deletes the breakpoint in DBE only if no more GDB IDs are left
///
/// \param[in] The GDB ID that we want to delete for this breakpoint
/// \return HSAIL agent status
HsailAgentStatus DeleteBreakpointDBE(const HwDbgContextHandle dbeHandle,
const GdbBkptId gdbId = g_UNKOWN_GDB_BKPT_ID);
/// Delete breakpoint - for kernel name
/// \param[in] The GDB ID that we want to delete for this breakpoint
/// \return HSAIL agent status
HsailAgentStatus DeleteBreakpointKernelName(const GdbBkptId gdbID);
private:
/// Disable copy constructor
AgentBreakpoint(const AgentBreakpoint&);
/// Disable assignment operator
AgentBreakpoint& operator=(const AgentBreakpoint&);
/// The BP handle for the DBE
HwDbgCodeBreakpointHandle m_handle;
};
}
#endif // #ifndef _AGENT_BREAKPOINT_H_
| 34.940299 | 123 | 0.688167 | [
"vector",
"model"
] |
25ec7bc910e722fc090b3e63d3bc67b1967c1b64 | 44,664 | c | C | src/shared_int.c | bkarr/libshr | c2bdac526f6a0b6b520c77a02269befc0b9e682c | [
"MIT"
] | 2 | 2015-05-17T03:39:48.000Z | 2018-03-29T15:47:36.000Z | src/shared_int.c | bkarr/libshr | c2bdac526f6a0b6b520c77a02269befc0b9e682c | [
"MIT"
] | 4 | 2018-04-01T02:09:54.000Z | 2018-07-20T19:05:41.000Z | src/shared_int.c | bkarr/libshr | c2bdac526f6a0b6b520c77a02269befc0b9e682c | [
"MIT"
] | null | null | null | /*
The MIT License (MIT)
Copyright (c) 2018-2022 Bryan Karr
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <linux/limits.h>
#include <sys/mman.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include "shared_int.h"
#ifdef __x86_64__
typedef int32_t halfword;
#else
typedef int16_t halfword;
#endif
// define useful integer constants (mostly sizes and offsets)
enum shr_int_constants
{
IDX_SIZE = 4, // index node slot count
};
/*
reference to critbit trie node
*/
struct idx_ref
{
long next;
union {
struct {
int8_t flag;
uint8_t bits;
uint8_t spares[ sizeof(halfword) - 2 ];
halfword byte;
};
long diff;
};
};
/*
internal node of critbit trie index
*/
struct idx_node
{
idx_ref_s child[ 2 ];
};
/*
leaf node of critbit trie index
*/
struct idx_leaf
{
union
{
uint8_t key[ sizeof(long) ];
long count;
};
long pad;
long allocs;
long allocs_count;
};
// static null value for use in CAS
static void *null = NULL;
/*
convert_to_status -- converts errno value to sh_status_e value
returns sh_status_e:
SH_ERR_ARG invalid argument
SH_ERR_ACCESS permission denied or operation not permitted
SH_ERR_EXIST no such file or file exists
SH_ERR_SYS input/output error or too many open files
SH_ERR_NOMEM not enough memory
SH_ERR_PATH problem with name too long, or with path
SH_ERR_STATE errno value not recognized
*/
extern sh_status_e convert_to_status(
int err // errno value
) {
switch( err ) {
case EINVAL :
return SH_ERR_ARG;
case EPERM :
case EACCES :
return SH_ERR_ACCESS;
case EEXIST :
case ENOENT :
return SH_ERR_EXIST;
case ENOMEM :
return SH_ERR_NOMEM;
case EBADF :
case ELOOP :
case ENOTDIR :
case ENAMETOOLONG :
return SH_ERR_PATH;
case ENFILE:
case EMFILE:
case EIO :
return SH_ERR_SYS;
default :
return SH_ERR_STATE;
}
}
/*
validate_name -- insure name is string of valid length
returns sh_status_e:
SH_OK on success
SH_ERR_PATH if name is invalid
*/
extern sh_status_e validate_name(
char const * const name
) {
if ( name == NULL ) {
return SH_ERR_PATH;
}
size_t len = strlen( name );
if ( len == 0 ) {
return SH_ERR_PATH;
}
if ( len > PATH_MAX ) {
return SH_ERR_PATH;
}
return SH_OK;
}
/*
build_file_path -- builds path to shared memory file in buffer
effects:
buffer is cleared for length, and the name of the shared memory
file is appended to shared memory directory in the buffer
*/
static void build_file_path(
char const * const name, // name string of shared memory file
char *buffer, // buffer
int size // buffer size
) {
// initialize buffer
memset( buffer, 0, size );
// copy shared memory directory
memcpy( buffer, SHR_OBJ_DIR, sizeof(SHR_OBJ_DIR) );
// index to end of data in buffer
int index = sizeof(SHR_OBJ_DIR) - 1;
// does name start with '/'?
if ( name[ 0 ] == '/' ) {
// backup in buffer
index--;
}
// copy name into buffer
memcpy( &buffer[ index ], name, strlen( name ) );
}
/*
validate_existence -- validate that shared memory file does exist
effects:
if size pointer is not NULL, the size field will be zero on error,
otherwise, it will contain the size of the existing shared memory file
returns sh_status_e:
SH_OK shared memory file exists
SH_ERR_ARG invalid argument
SH_ERR_ACCESS permission denied or operation not permitted
SH_ERR_EXIST no such file or file exists
SH_ERR_SYS input/output error
SH_ERR_NOMEM not enough memory
SH_ERR_PATH problem with name too long, or with path
SH_ERR_STATE size != NULL and file has a length, or length is not page
size multiple
*/
extern sh_status_e validate_existence(
char const * const name, // name string of shared memory file
size_t *size // pointer to size field -- possibly NULL
) {
if ( size ) {
*size = 0;
}
if ( name == NULL ) {
return SH_ERR_ARG;
}
// build file path
int bsize = sizeof(SHR_OBJ_DIR) + strlen( name );
char nm_buffer[ bsize ];
build_file_path( name, &nm_buffer[ 0 ], bsize );
// check file status
struct stat statbuf;
int rc = stat( &nm_buffer[ 0 ], &statbuf );
if ( rc < 0 ) {
// error performing stat
return convert_to_status( errno );
}
if ( size == NULL || !S_ISREG( statbuf.st_mode ) ) {
return SH_ERR_STATE;
}
*size = statbuf.st_size;
if ( ( *size < PAGE_SIZE ) || ( *size % PAGE_SIZE != 0 ) ) {
return SH_ERR_STATE;
}
return SH_OK;
}
/*
init_base_struct -- allocate and initialize the sh_base_s struct
effects:
if allocation and initialization succeeds, *base with have a valid
pointer to struct, otherwise, on error *base will be NULL
returns sh_status_e:
SH_OK successful allocation/initialization
SH_ERR_NOMEM not enough memory
*/
static sh_status_e init_base_struct(
shr_base_s **base, // address of base struct pointer -- not NULL
size_t size, // size of structure to allocate
char const * const name,// name of base as a null terminated string -- not NULL
int prot, // protection indicators
int flags // sharing flags
) {
// allocate base structure
*base = calloc( 1, size );
if ( *base == NULL ) {
return SH_ERR_NOMEM;
}
// initialize base structure
(*base)->name = strdup( name );
if ( (*base)->name == NULL ) {
free( *base );
*base = NULL;
return SH_ERR_NOMEM;
}
(*base)->prot = prot;
(*base)->flags = flags;
return SH_OK;
}
/*
allocate_shared_memory -- creates and sets initial size of shared memory object
effects:
on success, the shared memory object will exist and be set to the specified
size, otherwise, no shared memory object will exist
returns sh_status_e:
SH_OK successful open and sizing
SH_ERR_PATH invalid path name
SH_ERR_EXIST shared object already exists
*/
static sh_status_e allocate_shared_memory(
shr_base_s *base, // address of base struct pointer -- not NULL
char const * const name,// name of base as a null terminated string -- not NULL
long size // requested size for shared memory object
) {
// create initial shared memory object
base->fd = shm_open( name, O_RDWR | O_CREAT | O_EXCL, FILE_MODE );
if ( base->fd < 0 ) {
if ( errno == EINVAL ) {
return SH_ERR_PATH;
}
return convert_to_status( errno );
}
// set initial size
int rc = ftruncate( base->fd, size );
if ( rc < 0 ) {
shm_unlink( name );
base->fd = -1;
return convert_to_status( errno );
}
return SH_OK;
}
/*
create_extent -- creates new extent with mmapped array of specified size
effects:
*current will contain new extent instance with current->array pointing
at mmapped memory array, otherwise, on error extent will not be allocated
returns sh_status_e:
SH_OK successful extent mapping
SH_ERR_NOMEM not enough memory
*/
static sh_status_e create_extent(
extent_s **current, // address of extent pointer
long slots, // slots in extent
int fd, // file descriptor
int prot, // protection indicators
int flags // sharing flags
) {
*current = calloc( 1, sizeof(extent_s) );
if ( *current == NULL ) {
return SH_ERR_NOMEM;
}
(*current)->size = slots << SZ_SHIFT;
(*current)->slots = slots;
(*current)->array = mmap( 0, (*current)->size, prot, flags, fd, 0 );
if ( (*current)->array == (void*) -1 ) {
free( *current );
return convert_to_status( errno );
}
return SH_OK;
}
/*
create_base_object -- creates and initializes base shared memory object
effects:
creates base structure with an extent that maps to an intitial allocation
of shared memory
returns sh_status_e:
SH_OK successful allocation/initialization
SH_ERR_NOMEM not enough memory
SH_ERR_PATH invalid path name
SH_ERR_EXIST shared object already exists
*/
extern sh_status_e create_base_object(
shr_base_s **base, // address of base struct pointer -- not NULL
size_t size, // size of structure to allocate
char const * const name,// name of base as a null terminated string -- not NULL
char const * const tag, // tag to initialize base shared memory structure
int tag_len, // length of tag
long version // version for memory layout
) {
if ( base == NULL || size < sizeof(shr_base_s) || name == NULL ||
tag == NULL || tag_len <= 0 ) {
return SH_ERR_ARG;
}
sh_status_e status = init_base_struct( base, size, name,
PROT_READ | PROT_WRITE, MAP_SHARED );
if ( status != SH_OK ) {
return status;
}
status = allocate_shared_memory( *base, name, PAGE_SIZE );
if ( status != SH_OK ) {
free( *base );
*base = NULL;
return status;
}
status = create_extent( &(*base)->current, PAGE_SIZE >> SZ_SHIFT,
(*base)->fd, (*base)->prot, (*base)->flags );
if ( status != SH_OK ) {
free( *base );
*base = NULL;
return status;
}
(*base)->prev = (*base)->current;
// initialize base shared memory object
(*base)->current->array[ SIZE ] = (*base)->current->slots;
(*base)->current->array[ EXPAND_SIZE ] = (*base)->current->size;
(*base)->current->array[ DATA_ALLOC ] = BASE;
(*base)->current->array[ VERSION ] = version;
memcpy(&(*base)->current->array[ TAG ], tag, tag_len);
return SH_OK;
}
/*
prime_list -- intializes linked list with a single empty item
Note: should only be called as part of intialization at creation
*/
extern void prime_list(
shr_base_s *base, // pointer to base struct -- not NULL
long slot_count, // size of item in array slots
long head, // queue head slot number
long head_counter, // queue head gen counter
long tail, // queue tail slot number
long tail_counter // queue tail gen counter
) {
long *array = base->current->array;
view_s view = alloc_new_data( base, slot_count );
array[ head ] = view.slot;
array[ head_counter ] = AFA( &array[ ID_CNTR ], 1 );
array[ tail ] = view.slot;
array[ tail_counter ] = array[ head_counter ];
// init item on queue
array[ array[ head ] ] = array[ tail ];
array[ array[ head ] + 1] = array[ tail_counter ];
}
/*
init_data_allocator -- initializes base structures needed for data
allocation
*/
extern void init_data_allocator(
shr_base_s *base, // pointer to base struct -- not NULL
long start // start location for data allocations
) {
long *array = base->current->array;
array[ DATA_ALLOC ] = start;
// intialize free index item pool
prime_list( base, IDX_SIZE, FREE_HEAD, FREE_HD_CNT, FREE_TAIL, FREE_TL_CNT );
}
/*
resize_extent -- resize current mapped extent to match shared memory
object size
effects:
if the underlying shared memory object has been expanded, a new extent
is created and appended as the current extent at the end of linked list
of recent extents
returns view_s where view.status:
SH_OK if view reflects latest state of current extent
SH_ERR_NOMEM if not enough memory to resize extent to match shared memory
*/
extern view_s resize_extent(
shr_base_s *base, // pointer to base struct -- not NULL
extent_s *extent // pointer to working extent -- not NULL
) {
view_s view = { .status = SH_OK, .slot = 0, .extent = base->current };
// did another thread change current extent?
if ( extent != view.extent ) {
return view;
}
// did another process change size of shared object?
long *array = view.extent->array;
if ( extent->slots == array[ SIZE ] ) {
// no, return current view
return view;
}
// allocate next extent
extent_s *next = NULL;
view.status = create_extent( &next, array[ SIZE ], base->fd, base->prot,
base->flags );
if ( view.status != SH_OK ) {
return view;
}
// update current extent
extent_s *tail = view.extent;
if ( CAS( (long*) &tail->next, (long*) &null, (long) next ) ) {
CAS( (long*) &base->current, (long*) &tail, (long) next );
} else {
CAS( (long*) &base->current, (long*) &tail, (long) tail->next );
munmap( next->array, next->size );
free( next );
}
view.extent = base->current;
return view;
}
/*
calculate_realloc_size -- calculate page size needed based on
requested number of slots
returns new page aligned size
*/
static long calculate_realloc_size(
extent_s *extent, // pointer to current extent -- not NULL
long slots // number of slots to allocate
) {
// divide by page size
long current_pages = extent->size >> 12;
long needed_pages = ( (slots << SZ_SHIFT) >> 12 ) + 1;
return ( current_pages + needed_pages ) * PAGE_SIZE;
}
/*
expand -- expand the shared memory object without locking
returns view_s where view.status:
SH_OK if view reflects latest state of current extent
SH_ERR_NOMEM if not enough memory to resize extent to match shared memory
*/
extern view_s expand(
shr_base_s *base, // pointer to base struct -- not NULL
extent_s *extent, // pointer to current extent -- not NULL
long slots // number of slots to allocate
) {
assert(base != NULL);
assert(extent != NULL);
assert(slots > 0);
view_s view = { .status = SH_OK, .extent = extent };
if ( extent != base->current ) {
view.extent = base->current;
return view;
}
atomictype *array = (atomictype*) extent->array;
if ( extent->slots != array[ SIZE ] ) {
return resize_extent( (shr_base_s*) base, extent );
}
long size = calculate_realloc_size( extent, slots );
long prev = array[ SIZE ] << SZ_SHIFT;
// attempt to update expansion size
if ( size > prev ) {
CAS( &array[ EXPAND_SIZE ], &prev, size );
}
// attempt to extend shared memory
while ( ftruncate( base->fd, array[ EXPAND_SIZE ] ) < 0 ) {
if ( errno != EINTR ) {
view.status = SH_ERR_NOMEM;
return view;
}
}
// attempt to update size with reallocated value
prev >>= SZ_SHIFT;
CAS( &array[ SIZE ], &prev, size >> SZ_SHIFT );
if ( extent->slots != array[ SIZE ] ) {
view = resize_extent( (shr_base_s*) base, extent );
}
return view;
}
/*
insure_in_range -- validates that slot is within the current extent
effects:
updates current extent if specified slot exceeds size of current extent
returns view_s with view_s.status:
SH_OK slot is in current extent
SH_ERR_NOMEM not enough memory to map slot into extent
*/
extern view_s insure_in_range(
shr_base_s *base, // pointer to base struct -- not NULL
long slot // starting slot
) {
assert(base != NULL);
assert(slot > 0);
if ( slot < base->current->slots ) {
return (view_s) { .status = SH_OK, .slot = slot, .extent = base->current };
}
view_s view = resize_extent( base, base->current) ;
if ( view.status == SH_OK ) {
view.slot = slot;
}
return view;
}
/*
insure_fit -- validates that the number of slots at start are in range
of current extent
effects:
expands shared memory object if slot range at start location does not fit,
otherwise, returns view with current extent
returns view_s with view_s.status:
SH_OK slot is in current extent
SH_ERR_NOMEM not enough memory to map slot into extent
*/
static inline view_s insure_fit(
shr_base_s *base, // pointer to base struct -- not NULL
long start, // starting slot
long slots // slot count
) {
assert(base != NULL);
assert(start >= BASE);
assert(slots > 0);
view_s view = { .status = SH_OK, .slot = 0, .extent = base->current };
long end = start + slots;
while ( end >= view.extent->slots ) {
view = expand( (shr_base_s*) base, view.extent, slots );
if ( view.status != SH_OK ) {
return view;
}
}
view.extent = base->current;
view.slot = start;
return view;
}
/*
set_flag -- set indicator bits in flag slot to true
effect:
loops until indicator bit are set to true in array[FLAGS]
returns true if able to set, otherwise, false
Note: a false return does not mean bit was not set, only that
the calling process was not the one to set it
*/
extern bool set_flag(
long *array,
long indicator
) {
assert(array != NULL);
assert(indicator != 0);
volatile long prev = (volatile long) array[ FLAGS ];
while ( !( prev & indicator ) ) {
if ( CAS( &array[ FLAGS ], &prev, prev | indicator ) ) {
return true;
}
prev = (volatile long) array[ FLAGS ];
}
return false;
}
/*
clear_flag -- clears indicator bits in flag slot to false
effect:
loops until indicator bits are set to false in array[FLAGS]
returns true if able to clear, otherwise, false
Note: a false return does not mean bit was not cleared, only that
the calling process was not the one to clear it
*/
extern bool clear_flag(
long *array,
long indicator
) {
assert(array != NULL);
assert(indicator != 0);
long mask = ~indicator;
volatile long prev = (volatile long) array[ FLAGS ];
while ( prev & indicator ) {
if ( CAS( &array[ FLAGS ], &prev, prev & mask ) ) {
return true;
}
prev = (volatile long) array[ FLAGS ];
}
return false;
}
/*
update_buffer_size -- attempts to store the largest buffer size
in shared memory
*/
extern void update_buffer_size(
long *array, // pointer to array -- not NUL
long space, // slots used for data
long vec_sz // size needed for vectors
) {
long total = space << SZ_SHIFT;
total += vec_sz;
long buff_sz = array[ BUFFER ];
while ( total > buff_sz ) {
if ( CAS( &array[ BUFFER ], &buff_sz, total ) ) {
break;
}
buff_sz = array[ BUFFER ];
}
}
/*
add_end -- lock-free append memory to end of linked list
effect:
memory at slot is appended to last item in list and the tail
reference is also updated to point to newly added item
*/
extern void add_end(
shr_base_s *base, // pointer to base struct -- not NULL
long slot, // slot reference
long tail // tail slot of list
) {
// assert(base != NULL);
// assert(slot >= BASE);
// assert(tail > 0);
atomictype * volatile array = (atomictype*) base->current->array;
long gen = AFA( &array[ ID_CNTR ], 1 );
array[ slot ] = slot;
array[ slot + 1 ] = gen;
DWORD next_after = { .low = slot, .high = gen };
while( true ) {
DWORD tail_before = *( (DWORD * volatile) &array[ tail ] );
long next = tail_before.low;
view_s view = insure_in_range( base, next );
array = (atomictype * volatile) view.extent->array;
if ( tail_before.low == array[ next ] ) {
if ( DWCAS( (DWORD*) &array[ next ], &tail_before, next_after ) ) {
DWCAS( (DWORD*) &array[ tail ], &tail_before, next_after );
return;
}
} else {
DWORD tail_after = *( (DWORD* volatile) &array[ next ] );
DWCAS( (DWORD*) &array[ tail ], &tail_before, tail_after );
}
}
}
/*
remove_front -- lock-free remove memory from front of linked list
effect:
memory at ref slot is removed from front of list with first two slots
of memory zeroed out, otherwise, no change to memory
returns slot of memory being returned if successful, otherwise, 0
*/
extern long remove_front(
shr_base_s *base, // pointer to base struct -- not NULL
long ref, // expected slot number
long gen, // generation count
long head, // head slot of list
long tail // tail slot of list
) {
assert(base != NULL);
volatile long * volatile array = base->current->array;
DWORD before;
DWORD after;
if ( ref >= BASE && ref != array[ tail ] ) {
view_s view = insure_in_range( base, ref );
array = view.extent->array;
after.low = array[ ref ];
before.high = gen;
after.high = before.high + 1;
before.low = (ulong) ref;
if ( DWCAS( (DWORD*) &array[ head ], &before, after ) ) {
memset( (void*) &array[ ref ], 0, 2 << SZ_SHIFT );
return ref;
}
}
return 0;
}
/*
alloc_new_data -- allocates the number of required slots by advancing the
data allocaction counter from previously unused space in share memory
returns view_s where view_s.slot will contain slot index to start of
memory if successful, otherwise, slot will be 0
*/
extern view_s alloc_new_data(
shr_base_s *base, // pointer to base struct -- not NULL
long slots // number of slots to allocate
) {
long *array = base->current->array;
long node_alloc = array[ DATA_ALLOC ];
long alloc_end = node_alloc + slots;
view_s view = insure_fit( base, node_alloc, slots );
if ( view.status != SH_OK ) {
return view;
}
array = view.extent->array;
while ( view.status == SH_OK && alloc_end < array[ SIZE ] ) {
if ( CAS( &array[ DATA_ALLOC ], &node_alloc, alloc_end ) ) {
view.slot = node_alloc;
array[ node_alloc ] = slots;
return view;
}
view.extent = base->current;
array = view.extent->array;
node_alloc = array[ DATA_ALLOC ];
alloc_end = node_alloc + slots;
view = insure_fit( base, node_alloc, slots );
array = view.extent->array;
}
return (view_s) { .status = SH_ERR_NOMEM };
}
/*
realloc_pooled_mem -- attempt to allocate previously freed slots
*/
extern view_s realloc_pooled_mem(
shr_base_s *base, // pointer to base struct -- not NULL
long slot_count, // size as number of slots
long head, // list head slot
long head_counter, // list head counter slot
long tail // list tail slot
) {
view_s view = { .status = SH_OK, .extent = base->current, .slot = 0 };
long *array = view.extent->array;
// attempt to remove from free index node list
long gen = array[ head_counter ];
long node_alloc = array[ head ];
while ( node_alloc != array[ tail ] ) {
node_alloc = remove_front( base, node_alloc, gen, head, tail );
if ( node_alloc > 0 ) {
view = insure_fit( base, node_alloc, slot_count );
array = view.extent->array;
if ( view.slot != 0 ) {
memset( (idx_leaf_s*)&array[ node_alloc ], 0, slot_count << SZ_SHIFT );
}
break;
}
gen = array[ head_counter ];
node_alloc = array[ head ];
}
return view;
}
/*
alloc_idx_slots -- allocate idx node slots
*/
extern view_s alloc_idx_slots(
shr_base_s *base // pointer to base struct -- not NULL
) {
// attempt to remove from free index node list
view_s view = realloc_pooled_mem( base, IDX_SIZE, FREE_HEAD, FREE_HD_CNT, FREE_TAIL );
if ( view.slot != 0 ) {
return view;
}
// attempt to allocate new node from current extent
view = alloc_new_data( base, IDX_SIZE );
return view;
}
/*
find_leaf -- return leaf that matches count as key
*/
static long find_leaf(
shr_base_s *base, // pointer to base struct -- not NULL
long count, // number of slots to return
long ref_index // index node reference to begin search
) {
assert(base != NULL);
assert(count > 0);
assert(ref_index > 0);
view_s view = { .status = SH_OK, .extent = base->current, .slot = 0 };
long *array = view.extent->array;
idx_ref_s *ref = (idx_ref_s*) &array[ ref_index ];
uint8_t *key = (uint8_t*) &count;
long node_slot = ref_index;
while ( ref->flag < 0 ) {
node_slot = ref->next;
view = insure_in_range( base, node_slot );
if ( view.slot == 0 ) {
return 0;
}
array = view.extent->array;
idx_node_s *node = (idx_node_s*) &array[ node_slot ];
long direction = ( 1 + ( ref->bits | key[ ref->byte ] ) ) >> 8;
ref = &node->child[ direction ];
}
view = insure_in_range( base, ref->next );
if ( view.slot == 0 ) {
return 0;
}
return ref->next;
}
static sh_status_e add_idx_root(
shr_base_s *base, // pointer to base struct -- not NULL
long slot, // start of slot range
long count // number of slots to return
) {
assert(base != NULL);
assert(slot >= BASE);
assert(count >= 2);
view_s view = alloc_idx_slots( base );
if ( view.slot == 0 ) {
return SH_ERR_NOMEM;
}
long node = view.slot;
long *array = view.extent->array;
idx_ref_s *ref = (idx_ref_s*) &array[ ROOT_FREE ];
idx_leaf_s *leaf = (idx_leaf_s*) &array[ node ];
leaf->count = count;
leaf->allocs = slot;
leaf->allocs_count = 1;
array[ slot ] = 0;
array[ slot + 1 ] = 0;
DWORD before = { 0, 0 };
DWORD after = { .low = node, .high = 0 };
if ( !DWCAS( (DWORD*) ref, &before, after ) ) {
add_end( base, node, FREE_TAIL );
return SH_RETRY;
}
return SH_OK;
}
static sh_status_e add_to_leaf(
shr_base_s *base, // pointer to base struct -- not NULL
idx_leaf_s *leaf,
long slot
) {
assert(base != NULL);
assert(leaf != NULL);
assert(slot >= BASE);
view_s view = insure_in_range( base, slot );
if ( view.slot == 0 ) {
return SH_ERR_NOMEM;
}
volatile long * volatile array = view.extent->array;
DWORD before = { 0 };
DWORD after = { 0 };
after.low = slot;
do {
// point current memory at next allocation
array[ slot + 1 ] = leaf->allocs_count;
array[ slot ] = leaf->allocs;
// init previous value
before.high = (volatile long) array[ slot + 1 ];
before.low = (volatile long) array[ slot ];
// init next leaf value
after.high = before.high + 1;
after.low = slot;
} while ( !DWCAS( (DWORD*) &leaf->allocs, &before, after ) ); // push down stack
return SH_OK;
}
static void diff_key(
idx_leaf_s *leaf, // pointer to leaf -- not NULL
uint8_t *key, // pointer to key -- not NULL
long *byte, // byte displacement pointer -- not NULL
uint8_t *bits // bit difference pointer -- not NULL
) {
/*
different orderings needed for endianness
*/
#if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
for ( *byte = 0; *byte < sizeof(long) ; (*byte)++ ) {
#else
for ( *byte = sizeof(long) - 1; *byte >= 0 ; (*byte)-- ) {
#endif
*bits = key[ *byte ] ^ leaf->key[ *byte ];
if ( *bits ) {
break;
}
}
}
static idx_ref_s *find_insertion_point(
shr_base_s *base, // pointer to base struct -- not NULL
uint8_t *key, // key of value being inserted
long ref_index, // current trie node reference index
long byte, // key byte index
uint8_t bits // key bit differential
) {
view_s view = insure_in_range( base, ref_index );
long *array = view.extent->array;
idx_ref_s *parent = (idx_ref_s*) &array[ ref_index ];
while ( true ) {
// check for leaf
if ( parent->flag >= 0 ) {
break;
}
// check if key differential offset is less than parent
if ( parent->byte < byte ) {
break;
}
// check if key differential bits are greater than parent
if ( parent->byte == byte && parent->bits > bits ) {
break;
}
//advance to next child node
long direction = ( (1 + ( parent->bits | key[ parent->byte ] ) ) >> 8 );
view = insure_in_range( base, parent->next );
array = view.extent->array;
idx_node_s *pnode = (idx_node_s*) &array[ parent->next ];
parent = &pnode->child[ direction ];
}
return parent;
}
static view_s init_leaf(
shr_base_s *base, // pointer to base struct -- not NULL
long slot, // start of slot range
long count // number of slots being freed
) {
view_s view = alloc_idx_slots( base );
if ( view.slot == 0 ) {
view.status = SH_ERR_NOMEM;
return view;
}
long leaf_index = view.slot;
long *array = view.extent->array;
array[ slot ] = 0;
array[ slot + 1 ] = 0;
idx_leaf_s *leaf = (idx_leaf_s*) &array[ leaf_index ];
leaf->count = count;
leaf->allocs = slot;
leaf->allocs_count = 1;
return view;
}
static view_s init_node(
shr_base_s *base, // pointer to base struct -- not NULL
long leaf_index, // index of new leaf
long direction, // child ref direction for new leaf
idx_ref_s *parent
) {
view_s view = alloc_idx_slots( base );
if ( view.slot == 0 ) {
view.status = SH_ERR_NOMEM;
return view;
}
long node_index = view.slot;
long *array = view.extent->array;
idx_node_s *node = (idx_node_s*) &array[ node_index ];
idx_ref_s *ref = &node->child[ direction ];
ref->next = leaf_index;
ref = &node->child[ 1 - direction ];
ref->next = parent->next;
ref->diff = parent->diff;
return view;
}
static sh_status_e insert_node(
shr_base_s *base, // pointer to base struct -- not NULL
idx_ref_s *parent, // pointer to parent reference
long node_index, // index of internal node
long byte, // key byte index
uint8_t bits // key bit differential
) {
DWORD before = { .low = parent->next, .high = parent->diff };
DWORD after = { 0 };
idx_ref_s *ref = (idx_ref_s*) &after;
ref->next = node_index;
ref->byte = byte;
ref->bits = bits;
ref->flag = -1;
if ( !DWCAS( (DWORD*) parent, &before, after ) ) {
return SH_RETRY;
}
return SH_OK;
}
static sh_status_e add_new_leaf(
shr_base_s *base, // pointer to base struct -- not NULL
long slot, // start of slot range
long count, // number of slots being freed
long ref_index, // current trie node reference index
long byte, // key byte index
uint8_t bits // key bit differential
) {
// calculate bit differential mask and direction
uint8_t *key = (uint8_t*) &count;
bits = (uint8_t) ~( 1 << ( 31 - __builtin_clz( bits ) ) );
long direction = ( 1 + ( bits | key[ byte ] ) ) >> 8;
// find place to insert new node in trie
idx_ref_s *parent = find_insertion_point(base, key, ref_index, byte, bits);
// create and initialize new leaf
view_s view = init_leaf( base, slot, count );
if ( view.slot == 0 ) {
return SH_ERR_NOMEM;
}
long leaf_index = view.slot;
// create and initialize new internal node
view = init_node( base, leaf_index, direction, parent );
if ( view.slot == 0 ) {
add_end( base, leaf_index, FREE_TAIL );
return SH_ERR_NOMEM;
}
long node_index = view.slot;
// insert new node in tree
sh_status_e status = insert_node( base, parent, node_index, byte, bits );
if ( status == SH_RETRY ) {
// insertion failed, free trie node allocations
add_end( base, leaf_index, FREE_TAIL );
add_end( base, node_index, FREE_TAIL );
}
return status;
}
extern sh_status_e free_data_slots(
shr_base_s *base, // pointer to base struct -- not NULL
long slot // start of slot range
) {
sh_status_e status = SH_RETRY;
long *array = base->current->array;
long count = array[ slot ];
do {
// check if tree is empty
if (array[ ROOT_FREE ] == 0) {
status = add_idx_root( base, slot, count );
if ( status != SH_RETRY ) {
return status;
}
}
long leaf = find_leaf( base, count, ROOT_FREE );
if ( leaf == 0 ) {
return SH_ERR_NOMEM;
}
// evaluate differences in keys
long byte;
uint8_t bits;
diff_key( (idx_leaf_s*) &base->current->array[ leaf ],
(uint8_t*) &count, &byte, &bits );
if ( bits == 0 ) {
// keys are equal
return add_to_leaf( base, (idx_leaf_s*)&base->current->array[ leaf ],
slot );
}
// keys do not match, insert new internal node with new leaf
status = add_new_leaf( base, slot, count, ROOT_FREE, byte, bits );
} while ( status == SH_RETRY );
return status;
}
static void stack_push(
long *stack,
long value
) {
if ( stack[ 0 ] < TSTACK_DEPTH ) {
stack[ stack [ 0 ]++ ] = value;
} else {
memmove( stack + 1, stack + 2, ( TSTACK_DEPTH - 2 ) * sizeof(long) );
stack[ TSTACK_DEPTH - 1 ] = value;
}
}
static long stack_pop(
long *stack
) {
return stack[ --stack[ 0 ] ];
}
static void stack_init(
long *stack
) {
stack[ 0 ] = 1;
}
static bool stack_empty(
long *stack
) {
return ( stack[ 0 ] <= 1 );
}
static long walk_trie(
shr_base_s *base, // pointer to base struct -- not NULL
long count, // number of slots to return
long *stack // stack of node branches to search
) {
while ( !stack_empty( stack ) ) {
long ref_index = stack_pop( stack );
view_s view = insure_in_range( base, ref_index );
if ( view.slot != ref_index ) {
return 0;
}
long *array = view.extent->array;
idx_ref_s *ref = (idx_ref_s*) &array[ ref_index ];
if ( ref->flag >= 0 ) {
view = insure_in_range( base, ref->next );
if ( view.slot != ref->next ) {
return 0;
}
array = view.extent->array;
idx_leaf_s *leaf = (idx_leaf_s*) &array[ ref->next ];
if ( leaf->count >= count && leaf->allocs != 0 ) {
return ref->next;
}
continue;
}
view = insure_in_range( base, ref->next );
if ( view.slot != ref->next ) {
return 0;
}
array = view.extent->array;
stack_push( stack, ref->next + 2 );
stack_push( stack, ref->next );
}
return 0;
}
static long find_first_fit(
shr_base_s *base, // pointer to base struct -- not NULL
long count, // number of slots to return
long ref_index // index node reference to begin search
) {
long stack[ TSTACK_DEPTH ] = { 0 };
stack_init( stack );
view_s view = { .status = SH_OK, .extent = base->current, .slot = 0 };
long *array = view.extent->array;
idx_ref_s *ref = (idx_ref_s*) &array[ ref_index ];
uint8_t *key = (uint8_t*) &count;
while ( ref->flag < 0 ) {
long node_slot = ref->next;
view = insure_in_range( base, node_slot );
if ( view.slot == 0 ) {
return 0;
}
array = view.extent->array;
idx_node_s *node = (idx_node_s*) &array[ node_slot ];
long direction = ( 1 + (ref->bits | key[ ref->byte ] ) ) >> 8;
ref = &node->child[ direction ];
// save branch not taken on stack
if ( !direction ) {
stack_push( stack, node_slot + 2 );
}
}
view = insure_in_range( base, ref->next) ;
if ( view.slot == 0 ) {
return 0;
}
array = view.extent->array;
idx_leaf_s *leaf = (idx_leaf_s*) &array[ view.slot ];
if ( leaf->count >= count && leaf->allocs != 0 ) {
return ref->next;
}
return walk_trie( base, count, stack );
}
/*
lookup_freed_data -- looks for leaf that has first available
allocation that is larger than requested numbers slots and
attempts to allocate from leaf
returns index slot of allocated memory, otherwise, 0
*/
static long lookup_freed_data(
shr_base_s *base, // pointer to base struct -- not NULL
long slots // number of slots to allocate
) {
DWORD before;
DWORD after;
long index = find_first_fit( base, slots, ROOT_FREE );
if ( index == 0 ) {
return 0;
}
view_s view = insure_in_range( base, index );
long *array = view.extent->array;
idx_leaf_s *leaf = (idx_leaf_s*) &array[ index ];
do {
before.low = leaf->allocs;
before.high = leaf->allocs_count;
if ( before.low == 0 ) {
return 0;
}
view = insure_in_range( base, before.low );
array = view.extent->array;
after.low = (volatile long) array[ before.low ];
after.high = before.high + 1;
} while ( !DWCAS( (DWORD*) &leaf->allocs, &before, after ) );
array[ before.low ] = leaf->count;
return before.low;
}
/*
realloc_data_slots -- reallocate previously released memory slots
that are at least as large as the requested number of slots
returns view_s where view_s.slot will contain slot index to start of
memory if successful, otherwise, slot will be 0
*/
static view_s realloc_data_slots(
shr_base_s *base, // pointer to base struct -- not NULL
long slots // number of slots to allocate
) {
view_s view = { .status = SH_OK, .extent = base->current, .slot = 0 };
long *array = view.extent->array;
if (array[ ROOT_FREE ] != 0) {
long alloc_end = lookup_freed_data( base, slots );
if ( alloc_end > 0 ) {
view = insure_fit( base, alloc_end, slots );
array = view.extent->array;
if ( view.slot != 0 ) {
memset( &array[ alloc_end + 1 ], 0, ( slots - 1 ) << SZ_SHIFT );
}
}
}
return view;
}
/*
alloc_data_slots -- attempts to allocate previously freed memory before
allocating out of previously unallocated space
returns view_s where view_s.slot will contain slot index to start of
memory if successful, otherwise, slot will be 0
*/
extern view_s alloc_data_slots(
shr_base_s *base, // pointer to base struct -- not NULL
long slots // number of slots to allocate
) {
view_s view = realloc_data_slots( base, slots );
if ( view.slot != 0 ) {
return view;
}
// check to see if power of 2 to reduce fragmentation
if ( __builtin_popcountl( slots ) > 1 ) {
// round up to next power of 2
slots = 1 << (LONG_BIT - __builtin_clzl( slots ) );
}
view = alloc_new_data( base, slots );
return view;
}
extern void release_prev_extents(
shr_base_s *base // pointer to base struct -- not NULL
) {
extent_s *head = base->prev;
while ( head != base->current ) {
if ( base->accessors > 1 ) {
return;
}
extent_s *next = head->next;
if ( !CAS( (long*) &base->prev, (long*) &head, (long) next ) ) {
return;
}
munmap( head->array, head->size );
free( head );
head = next;
}
}
extern sh_status_e perform_name_validations(
char const * const name, // name string of shared memory file
size_t *size // pointer to size field -- possibly NULL
) {
sh_status_e status = validate_name( name );
if ( status ) {
return status;
}
return validate_existence( name, size );
}
extern sh_status_e release_mapped_memory(
shr_base_s **base // address of base struct pointer-- not NULL
) {
if ( (*base)->current ) {
if ( (*base)->current->array ) {
munmap( (*base)->current->array, (*base)->current->size );
}
free( (*base)->current );
}
if ( (*base)->fd > 0 ) {
close( (*base)->fd );
}
if ( (*base)->name ) {
int rc = shm_unlink( (*base)->name );
if ( rc < 0 ) {
return SH_ERR_SYS;
}
free( (*base)->name );
}
return SH_OK;
}
extern sh_status_e map_shared_memory(
shr_base_s **base, // address of base struct pointer-- not NULL
char const * const name, // name as null terminated string -- not NULL
size_t size // size of shared memory
) {
(*base)->name = strdup( name );
(*base)->prot = PROT_READ | PROT_WRITE;
(*base)->flags = MAP_SHARED;
(*base)->fd = shm_open( (*base)->name, O_RDWR, FILE_MODE );
if ( (*base)->fd < 0 ) {
free( *base );
*base = NULL;
return convert_to_status( errno );
}
while ( true ) {
(*base)->current->array = mmap( 0, size, (*base)->prot, (*base)->flags,
(*base)->fd, 0 );
if ( (*base)->current->array == (void*) -1 ) {
free( (*base)->current );
free( *base );
*base = NULL;
return convert_to_status( errno );
}
if ( size == (*base)->current->array[ SIZE ] << SZ_SHIFT ) {
break;
}
size_t alt_size = (*base)->current->array[ SIZE ] << SZ_SHIFT;
munmap( (*base)->current->array, size );
size = alt_size;
}
(*base)->current->size = size;
(*base)->current->slots = size >> SZ_SHIFT;
return SH_OK;
}
extern void close_base(
shr_base_s *base // pointer to base struct -- not NULL
) {
release_prev_extents( base );
if ( base->current ) {
if ( base->current->array ) {
munmap(base->current->array, base->current->size);
}
free( base->current );
}
if ( base->fd > 0 ) {
close( base->fd );
}
if ( base->name ){
free(base->name);
}
}
| 21.808594 | 90 | 0.576997 | [
"object"
] |
25f6a911a6f77ab6a9832798013b40ed50b3a8a2 | 2,290 | h | C | oneflow/core/job/sbp_parallel.h | JasenWangLab/oneflow | 0131e6ec282a426c2de98825de5fab95c853d8cf | [
"Apache-2.0"
] | null | null | null | oneflow/core/job/sbp_parallel.h | JasenWangLab/oneflow | 0131e6ec282a426c2de98825de5fab95c853d8cf | [
"Apache-2.0"
] | null | null | null | oneflow/core/job/sbp_parallel.h | JasenWangLab/oneflow | 0131e6ec282a426c2de98825de5fab95c853d8cf | [
"Apache-2.0"
] | 1 | 2021-11-10T07:57:01.000Z | 2021-11-10T07:57:01.000Z | /*
Copyright 2020 The OneFlow Authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef ONEFLOW_CORE_JOB_SBP_PARALLEL_H_
#define ONEFLOW_CORE_JOB_SBP_PARALLEL_H_
#include "oneflow/core/job/sbp_parallel.pb.h"
#include "oneflow/core/job/sbp_infer_hint.h"
namespace oneflow {
bool operator==(const SbpParallel& lhs, const SbpParallel& rhs);
bool operator!=(const SbpParallel& lhs, const SbpParallel& rhs);
bool operator==(const SbpSignature& lhs, const SbpSignature& rhs);
bool operator!=(const SbpSignature& lhs, const SbpSignature& rhs);
SbpParallel GetDualSbpParallel(const SbpParallel&);
bool IsSbpSignatureContaining(const SbpSignature& bigger, const SbpSignature& smaller);
void FilterSbpSignatureList(const SbpSignatureList& sbp_sig_list, const SbpSignature& sbp_sig_conf,
SbpSignatureList* filtered_sbp_sig_list);
void SortSbpSignatureListByCopyCost(
const SbpSignatureList& sbp_sig_list, const PbRpf<std::string>& ibns,
const std::function<Maybe<const SbpInferHint*>(const std::string&)>& SbpInferHint4Ibn,
const std::function<int32_t(const SbpSignature&)>& OrderValue4SbpSig,
std::vector<const SbpSignature*>* sorted_sbp_signatures);
bool IsValidSbpParallelString(const std::string& sbp_str);
bool ParseSbpParallelFromString(const std::string& sbp_str, SbpParallel* sbp_parallel);
std::string SbpParallelToString(const SbpParallel& sbp_parallel);
} // namespace oneflow
namespace std {
template<>
struct hash<oneflow::SbpSignature> {
size_t operator()(const oneflow::SbpSignature& signature) const {
std::string serialized_string;
signature.SerializeToString(&serialized_string);
return std::hash<std::string>()(serialized_string);
}
};
} // namespace std
#endif // ONEFLOW_CORE_JOB_SBP_PARALLEL_H_
| 36.935484 | 99 | 0.782096 | [
"vector"
] |
d30bf669d4c9dd18c14bf89a7e414406696191d7 | 2,598 | h | C | source/app/timer_task.h | TencentOpen/Pebble | 0f32f94db47b3bc1955ac2843bfa10372eeba1fb | [
"BSD-2-Clause"
] | 233 | 2016-05-12T02:28:44.000Z | 2020-08-24T18:11:49.000Z | source/app/timer_task.h | TencentOpen/Pebble | 0f32f94db47b3bc1955ac2843bfa10372eeba1fb | [
"BSD-2-Clause"
] | 1 | 2016-06-07T04:18:16.000Z | 2016-06-07T06:09:08.000Z | source/app/timer_task.h | TencentOpen/Pebble | 0f32f94db47b3bc1955ac2843bfa10372eeba1fb | [
"BSD-2-Clause"
] | 116 | 2016-05-24T10:55:49.000Z | 2019-11-24T06:57:08.000Z | /*
* Tencent is pleased to support the open source community by making Pebble available.
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* 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 SOURCE_APP_TIMER_TASK_H_
#define SOURCE_APP_TIMER_TASK_H_
#include <iostream>
#include <map>
#include <vector>
#include "source/app/pebble_server.h"
#include "source/common/coroutine.h"
class CoroutineSchedule;
class CoroutineTask;
namespace pebble {
class TimerTaskInterface;
class CoroutineTimerTask : public CoroutineTask {
friend class TaskTimer;
public:
CoroutineTimerTask();
int Init(TimerTaskInterface* task, int interval, int task_id, uint64_t now);
virtual void Run();
void Stop();
bool IsTimeout(uint64_t now) {
uint64_t this_interval = now - last_time_;
if (this_interval > interval_) {
last_time_ = now;
return true;
}
return false;
}
inline int task_id() {
return task_id_;
}
private:
TimerTaskInterface* task_;
uint64_t interval_;
uint64_t last_time_;
int task_id_;
};
struct PreStartTask {
pebble::TimerTaskInterface* task;
int interval;
int task_id;
};
class TaskTimer : public UpdaterInterface {
public:
static const int kDefaultTimerTaskNumber;
TaskTimer();
int Init(CoroutineSchedule* schedule, uint64_t* sys_time,
int max_task_num = kDefaultTimerTaskNumber);
virtual ~TaskTimer();
virtual int Update(PebbleServer *pebble_server);
int AddTask(pebble::TimerTaskInterface* task, int interval);
int RemoveTask(int task_id);
private:
int CreateTaskId(); // 找一个数字作为task_id
int CloseTask();
std::map<int, CoroutineTimerTask*> tasks_; // 正在运行的定时任务
std::vector<PreStartTask> pre_start_tasks_; // 准备启动的任务
std::vector<int> wait_close_tasks_; // 等待关闭的任务
CoroutineSchedule* schedule_; // 协程管理器对象
uint64_t* sys_time_; // 从此指针读取系统时间,单位微秒
size_t max_tasks_; // 最大任务数限制
int last_task_id_; // 最大任务ID,生成ID用
};
} // namespace pebble
#endif // SOURCE_APP_TIMER_TASK_H_
| 28.23913 | 100 | 0.712856 | [
"vector"
] |
d315f758edee7812234e31096d7cf24a908751f2 | 17,844 | h | C | avocadod/Aql/Functions.h | jjzhang166/avocadodb | 948d94592c10731857c8617b133bda840b8e833e | [
"BSL-1.0",
"Zlib",
"Apache-2.0"
] | null | null | null | avocadod/Aql/Functions.h | jjzhang166/avocadodb | 948d94592c10731857c8617b133bda840b8e833e | [
"BSL-1.0",
"Zlib",
"Apache-2.0"
] | null | null | null | avocadod/Aql/Functions.h | jjzhang166/avocadodb | 948d94592c10731857c8617b133bda840b8e833e | [
"BSL-1.0",
"Zlib",
"Apache-2.0"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Jan Steemann
////////////////////////////////////////////////////////////////////////////////
#ifndef AVOCADOD_AQL_FUNCTIONS_H
#define AVOCADOD_AQL_FUNCTIONS_H 1
#include "Basics/Common.h"
#include "Basics/SmallVector.h"
#include "Aql/AqlValue.h"
namespace avocadodb {
namespace transaction {
class Methods;
}
namespace basics {
class VPackStringBufferAdapter;
}
namespace aql {
class Query;
typedef std::function<bool()> ExecutionCondition;
typedef SmallVector<AqlValue> VPackFunctionParameters;
typedef std::function<AqlValue(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&)>
FunctionImplementation;
struct Functions {
protected:
/// @brief validate the number of parameters
static void ValidateParameters(VPackFunctionParameters const& parameters,
char const* function, int minParams,
int maxParams);
static void ValidateParameters(VPackFunctionParameters const& parameters,
char const* function, int minParams);
/// @brief extract a function parameter from the arguments
static AqlValue ExtractFunctionParameterValue(
transaction::Methods*, VPackFunctionParameters const& parameters,
size_t position);
/// @brief extra a collection name from an AqlValue
static std::string ExtractCollectionName(
transaction::Methods* trx, VPackFunctionParameters const& parameters,
size_t position);
/// @brief extract attribute names from the arguments
static void ExtractKeys(std::unordered_set<std::string>& names,
avocadodb::aql::Query* query,
transaction::Methods* trx,
VPackFunctionParameters const& parameters,
size_t startParameter, char const* functionName);
/// @brief Helper function to merge given parameters
/// Works for an array of objects as first parameter or arbitrary many
/// object parameters
static AqlValue MergeParameters(avocadodb::aql::Query* query,
transaction::Methods* trx,
VPackFunctionParameters const& parameters,
char const* funcName, bool recursive);
public:
/// @brief called before a query starts
/// has the chance to set up any thread-local storage
static void InitializeThreadContext();
/// @brief called when a query ends
/// its responsibility is to clear any thread-local storage
static void DestroyThreadContext();
/// @brief helper function. not callable as a "normal" AQL function
static void Stringify(transaction::Methods* trx,
avocadodb::basics::VPackStringBufferAdapter& buffer,
VPackSlice const& slice);
static AqlValue IsNull(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue IsBool(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue IsNumber(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue IsString(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue IsArray(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue IsObject(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue Typename(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue ToNumber(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue ToString(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue ToBool(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue ToArray(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue Length(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue First(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue Last(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue Nth(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue Contains(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue Concat(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue ConcatSeparator(avocadodb::aql::Query*,
transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue CharLength(avocadodb::aql::Query*,
transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue Lower(avocadodb::aql::Query*,
transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue Upper(avocadodb::aql::Query*,
transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue Like(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue RegexTest(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue RegexReplace(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue Passthru(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue Unset(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue UnsetRecursive(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue Keep(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue Merge(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue MergeRecursive(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue Has(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue Attributes(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue Values(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue Min(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue Max(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue Sum(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue Average(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue Sleep(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue RandomToken(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue Md5(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue Sha1(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue Hash(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue Unique(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue SortedUnique(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue Union(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue UnionDistinct(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue Intersection(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue Outersection(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue Distance(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue Flatten(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue Zip(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue JsonStringify(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue JsonParse(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue ParseIdentifier(avocadodb::aql::Query*,
transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue Slice(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue Minus(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue Document(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue Round(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue Abs(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue Ceil(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue Floor(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue Sqrt(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue Pow(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue Log(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue Log2(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue Log10(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue Exp(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue Exp2(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue Sin(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue Cos(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue Tan(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue Asin(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue Acos(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue Atan(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue Atan2(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue Radians(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue Degrees(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue Pi(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue Rand(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue FirstDocument(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue FirstList(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue Push(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue Pop(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue Append(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue Unshift(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue Shift(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue RemoveValue(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue RemoveValues(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue RemoveNth(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue NotNull(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue CurrentDatabase(avocadodb::aql::Query*,
transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue CollectionCount(avocadodb::aql::Query*,
transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue VarianceSample(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue PregelResult(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue VariancePopulation(avocadodb::aql::Query*,
transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue StdDevSample(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue StdDevPopulation(avocadodb::aql::Query*,
transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue Median(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue Percentile(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue Range(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue Position(avocadodb::aql::Query*, transaction::Methods*,
VPackFunctionParameters const&);
static AqlValue IsSameCollection(avocadodb::aql::Query*,
transaction::Methods*,
VPackFunctionParameters const&);
};
}
}
#endif
| 55.588785 | 80 | 0.617014 | [
"object"
] |
d328fa12fee1a6767e2970f409462d8b2270fdc2 | 3,708 | h | C | src/script.h | Geo-Linux-Calculations/CadZinho | 2714711b05540aa9481c2d65991e318f43cc671d | [
"MIT"
] | null | null | null | src/script.h | Geo-Linux-Calculations/CadZinho | 2714711b05540aa9481c2d65991e318f43cc671d | [
"MIT"
] | null | null | null | src/script.h | Geo-Linux-Calculations/CadZinho | 2714711b05540aa9481c2d65991e318f43cc671d | [
"MIT"
] | null | null | null | #ifndef _CZ_SCRIPT_LIB
#define _CZ_SCRIPT_LIB
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
#include "dxf.h"
#include <time.h>
struct script_obj{
lua_State *L; /* main lua state */
lua_State *T; /* thread for execution */
int status;
int active;
int dynamic;
int do_init;
int n_results;
int wait_gui_resume;
char path[DXF_MAX_CHARS];
clock_t time;
double timeout;
char win[DXF_MAX_CHARS];
char win_title[DXF_MAX_CHARS];
int win_x, win_y, win_w, win_h;
char dyn_func[DXF_MAX_CHARS];
};
struct ent_lua { /* DXF entity object, in Lua userdata */
dxf_node *curr_ent;
dxf_node *orig_ent;
int sel;
dxf_drawing *drawing;
};
enum script_yield_reason {
YIELD_NONE,
YIELD_DRWG_OPEN,
YIELD_DRWG_SAVE,
YIELD_DRWG_PRINT,
YIELD_GUI_REFRESH
};
#include "gui.h"
int set_timeout (lua_State *L);
int debug_print (lua_State *L);
int script_get_sel (lua_State *L);
int script_ent_write (lua_State *L);
int script_get_ent_typ (lua_State *L);
int script_get_blk_name (lua_State *L);
int script_get_ins_data (lua_State *L);
int script_count_attrib (lua_State *L);
int script_get_attrib_i (lua_State *L);
int script_get_attribs (lua_State *L);
int script_get_points (lua_State *L);
int script_get_bound (lua_State *L);
int script_get_ext (lua_State *L);
int script_get_blk_ents (lua_State *L);
int script_get_all (lua_State *L);
int script_get_text_data (lua_State *L);
int script_edit_attr (lua_State *L);
int script_add_ext (lua_State *L);
int script_edit_ext_i (lua_State *L);
int script_del_ext_i (lua_State *L);
int script_del_ext_all (lua_State *L);
//int script_ent_append (lua_State *L);
int script_new_line (lua_State *L);
int script_new_pline (lua_State *L);
int script_pline_append (lua_State *L);
int script_pline_close (lua_State *L);
int script_new_circle (lua_State *L);
int script_new_hatch (lua_State *L);
int script_new_text (lua_State *L);
int script_new_block (lua_State *L);
int script_new_block_file (lua_State *L) ;
int script_get_dwg_appids (lua_State *L);
int script_set_layer (lua_State *L);
int script_set_color (lua_State *L);
int script_set_ltype (lua_State *L);
int script_set_style (lua_State *L);
int script_set_lw (lua_State *L);
int script_set_modal (lua_State *L) ;
int script_new_appid (lua_State *L);
int script_open_drwg (lua_State *L);
int script_save_drwg (lua_State *L);
int script_start_dynamic (lua_State *L);
int script_stop_dynamic (lua_State *L);
int script_ent_draw (lua_State *L);
int script_win_show (lua_State *L);
int script_win_close (lua_State *L);
int script_nk_layout (lua_State *L);
int script_nk_button (lua_State *L);
int script_nk_label (lua_State *L);
int script_nk_edit (lua_State *L);
int script_miniz_open (lua_State *L);
int script_miniz_close (lua_State *L);
int script_miniz_read (lua_State *L);
int script_miniz_write(lua_State *L);
int script_yxml_new (lua_State *L);
int script_yxml_close (lua_State *L);
int script_yxml_read (lua_State *L);
int script_fs_dir (lua_State *L);
int script_fs_chdir (lua_State *L);
int script_fs_cwd (lua_State *L);
int script_fs_script_path(lua_State *L);
int script_unique_id (lua_State *L);
int script_last_blk (lua_State *L);
/*========== lazy sqlite =====================*/
/* Adapted from https://github.com/katlogic/lsqlite */
#include "sqlite3.h"
int script_sqlite_exec(lua_State *L);
int script_sqlite_stmt_gc(lua_State *L);
int script_sqlite_changes(lua_State *L);
int script_sqlite_cols(lua_State *L);
int script_sqlite_rows(lua_State *L);
int script_sqlite_open(lua_State *L);
int script_sqlite_close(lua_State *L);
#endif | 27.065693 | 58 | 0.735437 | [
"object"
] |
d3290853e53f6248aea258be4174531c4f52d983 | 57,212 | c | C | src/sys/kern/kern_cpuset.c | lastweek/source-freebsd | 0821950b0c40cbc891a27964b342e0202a3859ec | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | src/sys/kern/kern_cpuset.c | lastweek/source-freebsd | 0821950b0c40cbc891a27964b342e0202a3859ec | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | src/sys/kern/kern_cpuset.c | lastweek/source-freebsd | 0821950b0c40cbc891a27964b342e0202a3859ec | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | /*-
* SPDX-License-Identifier: BSD-2-Clause-FreeBSD
*
* Copyright (c) 2008, Jeffrey Roberson <jeff@freebsd.org>
* All rights reserved.
*
* Copyright (c) 2008 Nokia Corporation
* 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 unmodified, 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.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <sys/cdefs.h>
__FBSDID("$FreeBSD$");
#include "opt_ddb.h"
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/sysctl.h>
#include <sys/ctype.h>
#include <sys/sysproto.h>
#include <sys/jail.h>
#include <sys/kernel.h>
#include <sys/lock.h>
#include <sys/malloc.h>
#include <sys/mutex.h>
#include <sys/priv.h>
#include <sys/proc.h>
#include <sys/refcount.h>
#include <sys/sched.h>
#include <sys/smp.h>
#include <sys/syscallsubr.h>
#include <sys/capsicum.h>
#include <sys/cpuset.h>
#include <sys/domainset.h>
#include <sys/sx.h>
#include <sys/queue.h>
#include <sys/libkern.h>
#include <sys/limits.h>
#include <sys/bus.h>
#include <sys/interrupt.h>
#include <sys/vmmeter.h>
#include <vm/uma.h>
#include <vm/vm.h>
#include <vm/vm_object.h>
#include <vm/vm_page.h>
#include <vm/vm_pageout.h>
#include <vm/vm_extern.h>
#include <vm/vm_param.h>
#include <vm/vm_phys.h>
#include <vm/vm_pagequeue.h>
#ifdef DDB
#include <ddb/ddb.h>
#endif /* DDB */
/*
* cpusets provide a mechanism for creating and manipulating sets of
* processors for the purpose of constraining the scheduling of threads to
* specific processors.
*
* Each process belongs to an identified set, by default this is set 1. Each
* thread may further restrict the cpus it may run on to a subset of this
* named set. This creates an anonymous set which other threads and processes
* may not join by number.
*
* The named set is referred to herein as the 'base' set to avoid ambiguity.
* This set is usually a child of a 'root' set while the anonymous set may
* simply be referred to as a mask. In the syscall api these are referred to
* as the ROOT, CPUSET, and MASK levels where CPUSET is called 'base' here.
*
* Threads inherit their set from their creator whether it be anonymous or
* not. This means that anonymous sets are immutable because they may be
* shared. To modify an anonymous set a new set is created with the desired
* mask and the same parent as the existing anonymous set. This gives the
* illusion of each thread having a private mask.
*
* Via the syscall apis a user may ask to retrieve or modify the root, base,
* or mask that is discovered via a pid, tid, or setid. Modifying a set
* modifies all numbered and anonymous child sets to comply with the new mask.
* Modifying a pid or tid's mask applies only to that tid but must still
* exist within the assigned parent set.
*
* A thread may not be assigned to a group separate from other threads in
* the process. This is to remove ambiguity when the setid is queried with
* a pid argument. There is no other technical limitation.
*
* This somewhat complex arrangement is intended to make it easy for
* applications to query available processors and bind their threads to
* specific processors while also allowing administrators to dynamically
* reprovision by changing sets which apply to groups of processes.
*
* A simple application should not concern itself with sets at all and
* rather apply masks to its own threads via CPU_WHICH_TID and a -1 id
* meaning 'curthread'. It may query available cpus for that tid with a
* getaffinity call using (CPU_LEVEL_CPUSET, CPU_WHICH_PID, -1, ...).
*/
LIST_HEAD(domainlist, domainset);
struct domainset __read_mostly domainset_fixed[MAXMEMDOM];
struct domainset __read_mostly domainset_prefer[MAXMEMDOM];
struct domainset __read_mostly domainset_roundrobin;
static uma_zone_t cpuset_zone;
static uma_zone_t domainset_zone;
static struct mtx cpuset_lock;
static struct setlist cpuset_ids;
static struct domainlist cpuset_domains;
static struct unrhdr *cpuset_unr;
static struct cpuset *cpuset_zero, *cpuset_default, *cpuset_kernel;
static struct domainset domainset0, domainset2;
/* Return the size of cpuset_t at the kernel level */
SYSCTL_INT(_kern_sched, OID_AUTO, cpusetsize, CTLFLAG_RD | CTLFLAG_CAPRD,
SYSCTL_NULL_INT_PTR, sizeof(cpuset_t), "sizeof(cpuset_t)");
cpuset_t *cpuset_root;
cpuset_t cpuset_domain[MAXMEMDOM];
static int domainset_valid(const struct domainset *, const struct domainset *);
/*
* Find the first non-anonymous set starting from 'set'.
*/
static struct cpuset *
cpuset_getbase(struct cpuset *set)
{
if (set->cs_id == CPUSET_INVALID)
set = set->cs_parent;
return (set);
}
/*
* Walks up the tree from 'set' to find the root.
*/
static struct cpuset *
cpuset_getroot(struct cpuset *set)
{
while ((set->cs_flags & CPU_SET_ROOT) == 0 && set->cs_parent != NULL)
set = set->cs_parent;
return (set);
}
/*
* Acquire a reference to a cpuset, all pointers must be tracked with refs.
*/
struct cpuset *
cpuset_ref(struct cpuset *set)
{
refcount_acquire(&set->cs_ref);
return (set);
}
/*
* Walks up the tree from 'set' to find the root. Returns the root
* referenced.
*/
static struct cpuset *
cpuset_refroot(struct cpuset *set)
{
return (cpuset_ref(cpuset_getroot(set)));
}
/*
* Find the first non-anonymous set starting from 'set'. Returns this set
* referenced. May return the passed in set with an extra ref if it is
* not anonymous.
*/
static struct cpuset *
cpuset_refbase(struct cpuset *set)
{
return (cpuset_ref(cpuset_getbase(set)));
}
/*
* Release a reference in a context where it is safe to allocate.
*/
void
cpuset_rel(struct cpuset *set)
{
cpusetid_t id;
if (refcount_release(&set->cs_ref) == 0)
return;
mtx_lock_spin(&cpuset_lock);
LIST_REMOVE(set, cs_siblings);
id = set->cs_id;
if (id != CPUSET_INVALID)
LIST_REMOVE(set, cs_link);
mtx_unlock_spin(&cpuset_lock);
cpuset_rel(set->cs_parent);
uma_zfree(cpuset_zone, set);
if (id != CPUSET_INVALID)
free_unr(cpuset_unr, id);
}
/*
* Deferred release must be used when in a context that is not safe to
* allocate/free. This places any unreferenced sets on the list 'head'.
*/
static void
cpuset_rel_defer(struct setlist *head, struct cpuset *set)
{
if (refcount_release(&set->cs_ref) == 0)
return;
mtx_lock_spin(&cpuset_lock);
LIST_REMOVE(set, cs_siblings);
if (set->cs_id != CPUSET_INVALID)
LIST_REMOVE(set, cs_link);
LIST_INSERT_HEAD(head, set, cs_link);
mtx_unlock_spin(&cpuset_lock);
}
/*
* Complete a deferred release. Removes the set from the list provided to
* cpuset_rel_defer.
*/
static void
cpuset_rel_complete(struct cpuset *set)
{
LIST_REMOVE(set, cs_link);
cpuset_rel(set->cs_parent);
uma_zfree(cpuset_zone, set);
}
/*
* Find a set based on an id. Returns it with a ref.
*/
static struct cpuset *
cpuset_lookup(cpusetid_t setid, struct thread *td)
{
struct cpuset *set;
if (setid == CPUSET_INVALID)
return (NULL);
mtx_lock_spin(&cpuset_lock);
LIST_FOREACH(set, &cpuset_ids, cs_link)
if (set->cs_id == setid)
break;
if (set)
cpuset_ref(set);
mtx_unlock_spin(&cpuset_lock);
KASSERT(td != NULL, ("[%s:%d] td is NULL", __func__, __LINE__));
if (set != NULL && jailed(td->td_ucred)) {
struct cpuset *jset, *tset;
jset = td->td_ucred->cr_prison->pr_cpuset;
for (tset = set; tset != NULL; tset = tset->cs_parent)
if (tset == jset)
break;
if (tset == NULL) {
cpuset_rel(set);
set = NULL;
}
}
return (set);
}
/*
* Create a set in the space provided in 'set' with the provided parameters.
* The set is returned with a single ref. May return EDEADLK if the set
* will have no valid cpu based on restrictions from the parent.
*/
static int
_cpuset_create(struct cpuset *set, struct cpuset *parent,
const cpuset_t *mask, struct domainset *domain, cpusetid_t id)
{
if (domain == NULL)
domain = parent->cs_domain;
if (mask == NULL)
mask = &parent->cs_mask;
if (!CPU_OVERLAP(&parent->cs_mask, mask))
return (EDEADLK);
/* The domain must be prepared ahead of time. */
if (!domainset_valid(parent->cs_domain, domain))
return (EDEADLK);
CPU_COPY(mask, &set->cs_mask);
LIST_INIT(&set->cs_children);
refcount_init(&set->cs_ref, 1);
set->cs_flags = 0;
mtx_lock_spin(&cpuset_lock);
set->cs_domain = domain;
CPU_AND(&set->cs_mask, &parent->cs_mask);
set->cs_id = id;
set->cs_parent = cpuset_ref(parent);
LIST_INSERT_HEAD(&parent->cs_children, set, cs_siblings);
if (set->cs_id != CPUSET_INVALID)
LIST_INSERT_HEAD(&cpuset_ids, set, cs_link);
mtx_unlock_spin(&cpuset_lock);
return (0);
}
/*
* Create a new non-anonymous set with the requested parent and mask. May
* return failures if the mask is invalid or a new number can not be
* allocated.
*/
static int
cpuset_create(struct cpuset **setp, struct cpuset *parent, const cpuset_t *mask)
{
struct cpuset *set;
cpusetid_t id;
int error;
id = alloc_unr(cpuset_unr);
if (id == -1)
return (ENFILE);
*setp = set = uma_zalloc(cpuset_zone, M_WAITOK | M_ZERO);
error = _cpuset_create(set, parent, mask, NULL, id);
if (error == 0)
return (0);
free_unr(cpuset_unr, id);
uma_zfree(cpuset_zone, set);
return (error);
}
static void
cpuset_freelist_add(struct setlist *list, int count)
{
struct cpuset *set;
int i;
for (i = 0; i < count; i++) {
set = uma_zalloc(cpuset_zone, M_ZERO | M_WAITOK);
LIST_INSERT_HEAD(list, set, cs_link);
}
}
static void
cpuset_freelist_init(struct setlist *list, int count)
{
LIST_INIT(list);
cpuset_freelist_add(list, count);
}
static void
cpuset_freelist_free(struct setlist *list)
{
struct cpuset *set;
while ((set = LIST_FIRST(list)) != NULL) {
LIST_REMOVE(set, cs_link);
uma_zfree(cpuset_zone, set);
}
}
static void
domainset_freelist_add(struct domainlist *list, int count)
{
struct domainset *set;
int i;
for (i = 0; i < count; i++) {
set = uma_zalloc(domainset_zone, M_ZERO | M_WAITOK);
LIST_INSERT_HEAD(list, set, ds_link);
}
}
static void
domainset_freelist_init(struct domainlist *list, int count)
{
LIST_INIT(list);
domainset_freelist_add(list, count);
}
static void
domainset_freelist_free(struct domainlist *list)
{
struct domainset *set;
while ((set = LIST_FIRST(list)) != NULL) {
LIST_REMOVE(set, ds_link);
uma_zfree(domainset_zone, set);
}
}
/* Copy a domainset preserving mask and policy. */
static void
domainset_copy(const struct domainset *from, struct domainset *to)
{
DOMAINSET_COPY(&from->ds_mask, &to->ds_mask);
to->ds_policy = from->ds_policy;
to->ds_prefer = from->ds_prefer;
}
/* Return 1 if mask and policy are equal, otherwise 0. */
static int
domainset_equal(const struct domainset *one, const struct domainset *two)
{
return (DOMAINSET_CMP(&one->ds_mask, &two->ds_mask) == 0 &&
one->ds_policy == two->ds_policy &&
one->ds_prefer == two->ds_prefer);
}
/* Return 1 if child is a valid subset of parent. */
static int
domainset_valid(const struct domainset *parent, const struct domainset *child)
{
if (child->ds_policy != DOMAINSET_POLICY_PREFER)
return (DOMAINSET_SUBSET(&parent->ds_mask, &child->ds_mask));
return (DOMAINSET_ISSET(child->ds_prefer, &parent->ds_mask));
}
static int
domainset_restrict(const struct domainset *parent,
const struct domainset *child)
{
if (child->ds_policy != DOMAINSET_POLICY_PREFER)
return (DOMAINSET_OVERLAP(&parent->ds_mask, &child->ds_mask));
return (DOMAINSET_ISSET(child->ds_prefer, &parent->ds_mask));
}
/*
* Lookup or create a domainset. The key is provided in ds_mask and
* ds_policy. If the domainset does not yet exist the storage in
* 'domain' is used to insert. Otherwise this storage is freed to the
* domainset_zone and the existing domainset is returned.
*/
static struct domainset *
_domainset_create(struct domainset *domain, struct domainlist *freelist)
{
struct domainset *ndomain;
int i, j;
KASSERT(domain->ds_cnt <= vm_ndomains,
("invalid domain count in domainset %p", domain));
KASSERT(domain->ds_policy != DOMAINSET_POLICY_PREFER ||
domain->ds_prefer < vm_ndomains,
("invalid preferred domain in domains %p", domain));
mtx_lock_spin(&cpuset_lock);
LIST_FOREACH(ndomain, &cpuset_domains, ds_link)
if (domainset_equal(ndomain, domain))
break;
/*
* If the domain does not yet exist we insert it and initialize
* various iteration helpers which are not part of the key.
*/
if (ndomain == NULL) {
LIST_INSERT_HEAD(&cpuset_domains, domain, ds_link);
domain->ds_cnt = DOMAINSET_COUNT(&domain->ds_mask);
for (i = 0, j = 0; i < DOMAINSET_FLS(&domain->ds_mask); i++)
if (DOMAINSET_ISSET(i, &domain->ds_mask))
domain->ds_order[j++] = i;
}
mtx_unlock_spin(&cpuset_lock);
if (ndomain == NULL)
return (domain);
if (freelist != NULL)
LIST_INSERT_HEAD(freelist, domain, ds_link);
else
uma_zfree(domainset_zone, domain);
return (ndomain);
}
/*
* Are any of the domains in the mask empty? If so, silently
* remove them and update the domainset accordingly. If only empty
* domains are present, we must return failure.
*/
static bool
domainset_empty_vm(struct domainset *domain)
{
domainset_t empty;
int i, j;
DOMAINSET_ZERO(&empty);
for (i = 0; i < vm_ndomains; i++)
if (VM_DOMAIN_EMPTY(i))
DOMAINSET_SET(i, &empty);
if (DOMAINSET_SUBSET(&empty, &domain->ds_mask))
return (true);
/* Remove empty domains from the set and recompute. */
DOMAINSET_ANDNOT(&domain->ds_mask, &empty);
domain->ds_cnt = DOMAINSET_COUNT(&domain->ds_mask);
for (i = j = 0; i < DOMAINSET_FLS(&domain->ds_mask); i++)
if (DOMAINSET_ISSET(i, &domain->ds_mask))
domain->ds_order[j++] = i;
/* Convert a PREFER policy referencing an empty domain to RR. */
if (domain->ds_policy == DOMAINSET_POLICY_PREFER &&
DOMAINSET_ISSET(domain->ds_prefer, &empty)) {
domain->ds_policy = DOMAINSET_POLICY_ROUNDROBIN;
domain->ds_prefer = -1;
}
return (false);
}
/*
* Create or lookup a domainset based on the key held in 'domain'.
*/
struct domainset *
domainset_create(const struct domainset *domain)
{
struct domainset *ndomain;
/*
* Validate the policy. It must specify a useable policy number with
* only valid domains. Preferred must include the preferred domain
* in the mask.
*/
if (domain->ds_policy <= DOMAINSET_POLICY_INVALID ||
domain->ds_policy > DOMAINSET_POLICY_MAX)
return (NULL);
if (domain->ds_policy == DOMAINSET_POLICY_PREFER &&
!DOMAINSET_ISSET(domain->ds_prefer, &domain->ds_mask))
return (NULL);
if (!DOMAINSET_SUBSET(&domainset0.ds_mask, &domain->ds_mask))
return (NULL);
ndomain = uma_zalloc(domainset_zone, M_WAITOK | M_ZERO);
domainset_copy(domain, ndomain);
return _domainset_create(ndomain, NULL);
}
/*
* Update thread domainset pointers.
*/
static void
domainset_notify(void)
{
struct thread *td;
struct proc *p;
sx_slock(&allproc_lock);
FOREACH_PROC_IN_SYSTEM(p) {
PROC_LOCK(p);
if (p->p_state == PRS_NEW) {
PROC_UNLOCK(p);
continue;
}
FOREACH_THREAD_IN_PROC(p, td) {
thread_lock(td);
td->td_domain.dr_policy = td->td_cpuset->cs_domain;
thread_unlock(td);
}
PROC_UNLOCK(p);
}
sx_sunlock(&allproc_lock);
kernel_object->domain.dr_policy = cpuset_kernel->cs_domain;
}
/*
* Create a new set that is a subset of a parent.
*/
static struct domainset *
domainset_shadow(const struct domainset *pdomain,
const struct domainset *domain, struct domainlist *freelist)
{
struct domainset *ndomain;
ndomain = LIST_FIRST(freelist);
LIST_REMOVE(ndomain, ds_link);
/*
* Initialize the key from the request.
*/
domainset_copy(domain, ndomain);
/*
* Restrict the key by the parent.
*/
DOMAINSET_AND(&ndomain->ds_mask, &pdomain->ds_mask);
return _domainset_create(ndomain, freelist);
}
/*
* Recursively check for errors that would occur from applying mask to
* the tree of sets starting at 'set'. Checks for sets that would become
* empty as well as RDONLY flags.
*/
static int
cpuset_testupdate(struct cpuset *set, cpuset_t *mask, int check_mask)
{
struct cpuset *nset;
cpuset_t newmask;
int error;
mtx_assert(&cpuset_lock, MA_OWNED);
if (set->cs_flags & CPU_SET_RDONLY)
return (EPERM);
if (check_mask) {
if (!CPU_OVERLAP(&set->cs_mask, mask))
return (EDEADLK);
CPU_COPY(&set->cs_mask, &newmask);
CPU_AND(&newmask, mask);
} else
CPU_COPY(mask, &newmask);
error = 0;
LIST_FOREACH(nset, &set->cs_children, cs_siblings)
if ((error = cpuset_testupdate(nset, &newmask, 1)) != 0)
break;
return (error);
}
/*
* Applies the mask 'mask' without checking for empty sets or permissions.
*/
static void
cpuset_update(struct cpuset *set, cpuset_t *mask)
{
struct cpuset *nset;
mtx_assert(&cpuset_lock, MA_OWNED);
CPU_AND(&set->cs_mask, mask);
LIST_FOREACH(nset, &set->cs_children, cs_siblings)
cpuset_update(nset, &set->cs_mask);
return;
}
/*
* Modify the set 'set' to use a copy of the mask provided. Apply this new
* mask to restrict all children in the tree. Checks for validity before
* applying the changes.
*/
static int
cpuset_modify(struct cpuset *set, cpuset_t *mask)
{
struct cpuset *root;
int error;
error = priv_check(curthread, PRIV_SCHED_CPUSET);
if (error)
return (error);
/*
* In case we are called from within the jail
* we do not allow modifying the dedicated root
* cpuset of the jail but may still allow to
* change child sets.
*/
if (jailed(curthread->td_ucred) &&
set->cs_flags & CPU_SET_ROOT)
return (EPERM);
/*
* Verify that we have access to this set of
* cpus.
*/
root = cpuset_getroot(set);
mtx_lock_spin(&cpuset_lock);
if (root && !CPU_SUBSET(&root->cs_mask, mask)) {
error = EINVAL;
goto out;
}
error = cpuset_testupdate(set, mask, 0);
if (error)
goto out;
CPU_COPY(mask, &set->cs_mask);
cpuset_update(set, mask);
out:
mtx_unlock_spin(&cpuset_lock);
return (error);
}
/*
* Recursively check for errors that would occur from applying mask to
* the tree of sets starting at 'set'. Checks for sets that would become
* empty as well as RDONLY flags.
*/
static int
cpuset_testupdate_domain(struct cpuset *set, struct domainset *dset,
struct domainset *orig, int *count, int check_mask)
{
struct cpuset *nset;
struct domainset *domain;
struct domainset newset;
int error;
mtx_assert(&cpuset_lock, MA_OWNED);
if (set->cs_flags & CPU_SET_RDONLY)
return (EPERM);
domain = set->cs_domain;
domainset_copy(domain, &newset);
if (!domainset_equal(domain, orig)) {
if (!domainset_restrict(domain, dset))
return (EDEADLK);
DOMAINSET_AND(&newset.ds_mask, &dset->ds_mask);
/* Count the number of domains that are changing. */
(*count)++;
}
error = 0;
LIST_FOREACH(nset, &set->cs_children, cs_siblings)
if ((error = cpuset_testupdate_domain(nset, &newset, domain,
count, 1)) != 0)
break;
return (error);
}
/*
* Applies the mask 'mask' without checking for empty sets or permissions.
*/
static void
cpuset_update_domain(struct cpuset *set, struct domainset *domain,
struct domainset *orig, struct domainlist *domains)
{
struct cpuset *nset;
mtx_assert(&cpuset_lock, MA_OWNED);
/*
* If this domainset has changed from the parent we must calculate
* a new set. Otherwise it simply inherits from the parent. When
* we inherit from the parent we get a new mask and policy. If the
* set is modified from the parent we keep the policy and only
* update the mask.
*/
if (set->cs_domain != orig) {
orig = set->cs_domain;
set->cs_domain = domainset_shadow(domain, orig, domains);
} else
set->cs_domain = domain;
LIST_FOREACH(nset, &set->cs_children, cs_siblings)
cpuset_update_domain(nset, set->cs_domain, orig, domains);
return;
}
/*
* Modify the set 'set' to use a copy the domainset provided. Apply this new
* mask to restrict all children in the tree. Checks for validity before
* applying the changes.
*/
static int
cpuset_modify_domain(struct cpuset *set, struct domainset *domain)
{
struct domainlist domains;
struct domainset temp;
struct domainset *dset;
struct cpuset *root;
int ndomains, needed;
int error;
error = priv_check(curthread, PRIV_SCHED_CPUSET);
if (error)
return (error);
/*
* In case we are called from within the jail
* we do not allow modifying the dedicated root
* cpuset of the jail but may still allow to
* change child sets.
*/
if (jailed(curthread->td_ucred) &&
set->cs_flags & CPU_SET_ROOT)
return (EPERM);
domainset_freelist_init(&domains, 0);
domain = domainset_create(domain);
ndomains = needed = 0;
do {
if (ndomains < needed) {
domainset_freelist_add(&domains, needed - ndomains);
ndomains = needed;
}
root = cpuset_getroot(set);
mtx_lock_spin(&cpuset_lock);
dset = root->cs_domain;
/*
* Verify that we have access to this set of domains.
*/
if (!domainset_valid(dset, domain)) {
error = EINVAL;
goto out;
}
/*
* If applying prefer we keep the current set as the fallback.
*/
if (domain->ds_policy == DOMAINSET_POLICY_PREFER)
DOMAINSET_COPY(&set->cs_domain->ds_mask,
&domain->ds_mask);
/*
* Determine whether we can apply this set of domains and
* how many new domain structures it will require.
*/
domainset_copy(domain, &temp);
needed = 0;
error = cpuset_testupdate_domain(set, &temp, set->cs_domain,
&needed, 0);
if (error)
goto out;
} while (ndomains < needed);
dset = set->cs_domain;
cpuset_update_domain(set, domain, dset, &domains);
out:
mtx_unlock_spin(&cpuset_lock);
domainset_freelist_free(&domains);
if (error == 0)
domainset_notify();
return (error);
}
/*
* Resolve the 'which' parameter of several cpuset apis.
*
* For WHICH_PID and WHICH_TID return a locked proc and valid proc/tid. Also
* checks for permission via p_cansched().
*
* For WHICH_SET returns a valid set with a new reference.
*
* -1 may be supplied for any argument to mean the current proc/thread or
* the base set of the current thread. May fail with ESRCH/EPERM.
*/
int
cpuset_which(cpuwhich_t which, id_t id, struct proc **pp, struct thread **tdp,
struct cpuset **setp)
{
struct cpuset *set;
struct thread *td;
struct proc *p;
int error;
*pp = p = NULL;
*tdp = td = NULL;
*setp = set = NULL;
switch (which) {
case CPU_WHICH_PID:
if (id == -1) {
PROC_LOCK(curproc);
p = curproc;
break;
}
if ((p = pfind(id)) == NULL)
return (ESRCH);
break;
case CPU_WHICH_TID:
if (id == -1) {
PROC_LOCK(curproc);
p = curproc;
td = curthread;
break;
}
td = tdfind(id, -1);
if (td == NULL)
return (ESRCH);
p = td->td_proc;
break;
case CPU_WHICH_CPUSET:
if (id == -1) {
thread_lock(curthread);
set = cpuset_refbase(curthread->td_cpuset);
thread_unlock(curthread);
} else
set = cpuset_lookup(id, curthread);
if (set) {
*setp = set;
return (0);
}
return (ESRCH);
case CPU_WHICH_JAIL:
{
/* Find `set' for prison with given id. */
struct prison *pr;
sx_slock(&allprison_lock);
pr = prison_find_child(curthread->td_ucred->cr_prison, id);
sx_sunlock(&allprison_lock);
if (pr == NULL)
return (ESRCH);
cpuset_ref(pr->pr_cpuset);
*setp = pr->pr_cpuset;
mtx_unlock(&pr->pr_mtx);
return (0);
}
case CPU_WHICH_IRQ:
case CPU_WHICH_DOMAIN:
return (0);
default:
return (EINVAL);
}
error = p_cansched(curthread, p);
if (error) {
PROC_UNLOCK(p);
return (error);
}
if (td == NULL)
td = FIRST_THREAD_IN_PROC(p);
*pp = p;
*tdp = td;
return (0);
}
static int
cpuset_testshadow(struct cpuset *set, const cpuset_t *mask,
const struct domainset *domain)
{
struct cpuset *parent;
struct domainset *dset;
parent = cpuset_getbase(set);
/*
* If we are restricting a cpu mask it must be a subset of the
* parent or invalid CPUs have been specified.
*/
if (mask != NULL && !CPU_SUBSET(&parent->cs_mask, mask))
return (EINVAL);
/*
* If we are restricting a domain mask it must be a subset of the
* parent or invalid domains have been specified.
*/
dset = parent->cs_domain;
if (domain != NULL && !domainset_valid(dset, domain))
return (EINVAL);
return (0);
}
/*
* Create an anonymous set with the provided mask in the space provided by
* 'nset'. If the passed in set is anonymous we use its parent otherwise
* the new set is a child of 'set'.
*/
static int
cpuset_shadow(struct cpuset *set, struct cpuset **nsetp,
const cpuset_t *mask, const struct domainset *domain,
struct setlist *cpusets, struct domainlist *domains)
{
struct cpuset *parent;
struct cpuset *nset;
struct domainset *dset;
struct domainset *d;
int error;
error = cpuset_testshadow(set, mask, domain);
if (error)
return (error);
parent = cpuset_getbase(set);
dset = parent->cs_domain;
if (mask == NULL)
mask = &set->cs_mask;
if (domain != NULL)
d = domainset_shadow(dset, domain, domains);
else
d = set->cs_domain;
nset = LIST_FIRST(cpusets);
error = _cpuset_create(nset, parent, mask, d, CPUSET_INVALID);
if (error == 0) {
LIST_REMOVE(nset, cs_link);
*nsetp = nset;
}
return (error);
}
static struct cpuset *
cpuset_update_thread(struct thread *td, struct cpuset *nset)
{
struct cpuset *tdset;
tdset = td->td_cpuset;
td->td_cpuset = nset;
td->td_domain.dr_policy = nset->cs_domain;
sched_affinity(td);
return (tdset);
}
static int
cpuset_setproc_test_maskthread(struct cpuset *tdset, cpuset_t *mask,
struct domainset *domain)
{
struct cpuset *parent;
parent = cpuset_getbase(tdset);
if (mask == NULL)
mask = &tdset->cs_mask;
if (domain == NULL)
domain = tdset->cs_domain;
return cpuset_testshadow(parent, mask, domain);
}
static int
cpuset_setproc_maskthread(struct cpuset *tdset, cpuset_t *mask,
struct domainset *domain, struct cpuset **nsetp,
struct setlist *freelist, struct domainlist *domainlist)
{
struct cpuset *parent;
parent = cpuset_getbase(tdset);
if (mask == NULL)
mask = &tdset->cs_mask;
if (domain == NULL)
domain = tdset->cs_domain;
return cpuset_shadow(parent, nsetp, mask, domain, freelist,
domainlist);
}
static int
cpuset_setproc_setthread_mask(struct cpuset *tdset, struct cpuset *set,
cpuset_t *mask, struct domainset *domain)
{
struct cpuset *parent;
parent = cpuset_getbase(tdset);
/*
* If the thread restricted its mask then apply that same
* restriction to the new set, otherwise take it wholesale.
*/
if (CPU_CMP(&tdset->cs_mask, &parent->cs_mask) != 0) {
CPU_COPY(&tdset->cs_mask, mask);
CPU_AND(mask, &set->cs_mask);
} else
CPU_COPY(&set->cs_mask, mask);
/*
* If the thread restricted the domain then we apply the
* restriction to the new set but retain the policy.
*/
if (tdset->cs_domain != parent->cs_domain) {
domainset_copy(tdset->cs_domain, domain);
DOMAINSET_AND(&domain->ds_mask, &set->cs_domain->ds_mask);
} else
domainset_copy(set->cs_domain, domain);
if (CPU_EMPTY(mask) || DOMAINSET_EMPTY(&domain->ds_mask))
return (EDEADLK);
return (0);
}
static int
cpuset_setproc_test_setthread(struct cpuset *tdset, struct cpuset *set)
{
struct domainset domain;
cpuset_t mask;
if (tdset->cs_id != CPUSET_INVALID)
return (0);
return cpuset_setproc_setthread_mask(tdset, set, &mask, &domain);
}
static int
cpuset_setproc_setthread(struct cpuset *tdset, struct cpuset *set,
struct cpuset **nsetp, struct setlist *freelist,
struct domainlist *domainlist)
{
struct domainset domain;
cpuset_t mask;
int error;
/*
* If we're replacing on a thread that has not constrained the
* original set we can simply accept the new set.
*/
if (tdset->cs_id != CPUSET_INVALID) {
*nsetp = cpuset_ref(set);
return (0);
}
error = cpuset_setproc_setthread_mask(tdset, set, &mask, &domain);
if (error)
return (error);
return cpuset_shadow(tdset, nsetp, &mask, &domain, freelist,
domainlist);
}
/*
* Handle three cases for updating an entire process.
*
* 1) Set is non-null. This reparents all anonymous sets to the provided
* set and replaces all non-anonymous td_cpusets with the provided set.
* 2) Mask is non-null. This replaces or creates anonymous sets for every
* thread with the existing base as a parent.
* 3) domain is non-null. This creates anonymous sets for every thread
* and replaces the domain set.
*
* This is overly complicated because we can't allocate while holding a
* spinlock and spinlocks must be held while changing and examining thread
* state.
*/
static int
cpuset_setproc(pid_t pid, struct cpuset *set, cpuset_t *mask,
struct domainset *domain)
{
struct setlist freelist;
struct setlist droplist;
struct domainlist domainlist;
struct cpuset *nset;
struct thread *td;
struct proc *p;
int threads;
int nfree;
int error;
/*
* The algorithm requires two passes due to locking considerations.
*
* 1) Lookup the process and acquire the locks in the required order.
* 2) If enough cpusets have not been allocated release the locks and
* allocate them. Loop.
*/
cpuset_freelist_init(&freelist, 1);
domainset_freelist_init(&domainlist, 1);
nfree = 1;
LIST_INIT(&droplist);
nfree = 0;
for (;;) {
error = cpuset_which(CPU_WHICH_PID, pid, &p, &td, &nset);
if (error)
goto out;
if (nfree >= p->p_numthreads)
break;
threads = p->p_numthreads;
PROC_UNLOCK(p);
if (nfree < threads) {
cpuset_freelist_add(&freelist, threads - nfree);
domainset_freelist_add(&domainlist, threads - nfree);
nfree = threads;
}
}
PROC_LOCK_ASSERT(p, MA_OWNED);
/*
* Now that the appropriate locks are held and we have enough cpusets,
* make sure the operation will succeed before applying changes. The
* proc lock prevents td_cpuset from changing between calls.
*/
error = 0;
FOREACH_THREAD_IN_PROC(p, td) {
thread_lock(td);
if (set != NULL)
error = cpuset_setproc_test_setthread(td->td_cpuset,
set);
else
error = cpuset_setproc_test_maskthread(td->td_cpuset,
mask, domain);
thread_unlock(td);
if (error)
goto unlock_out;
}
/*
* Replace each thread's cpuset while using deferred release. We
* must do this because the thread lock must be held while operating
* on the thread and this limits the type of operations allowed.
*/
FOREACH_THREAD_IN_PROC(p, td) {
thread_lock(td);
if (set != NULL)
error = cpuset_setproc_setthread(td->td_cpuset, set,
&nset, &freelist, &domainlist);
else
error = cpuset_setproc_maskthread(td->td_cpuset, mask,
domain, &nset, &freelist, &domainlist);
if (error) {
thread_unlock(td);
break;
}
cpuset_rel_defer(&droplist, cpuset_update_thread(td, nset));
thread_unlock(td);
}
unlock_out:
PROC_UNLOCK(p);
out:
while ((nset = LIST_FIRST(&droplist)) != NULL)
cpuset_rel_complete(nset);
cpuset_freelist_free(&freelist);
domainset_freelist_free(&domainlist);
return (error);
}
static int
bitset_strprint(char *buf, size_t bufsiz, const struct bitset *set, int setlen)
{
size_t bytes;
int i, once;
char *p;
once = 0;
p = buf;
for (i = 0; i < __bitset_words(setlen); i++) {
if (once != 0) {
if (bufsiz < 1)
return (0);
*p = ',';
p++;
bufsiz--;
} else
once = 1;
if (bufsiz < sizeof(__STRING(ULONG_MAX)))
return (0);
bytes = snprintf(p, bufsiz, "%lx", set->__bits[i]);
p += bytes;
bufsiz -= bytes;
}
return (p - buf);
}
static int
bitset_strscan(struct bitset *set, int setlen, const char *buf)
{
int i, ret;
const char *p;
BIT_ZERO(setlen, set);
p = buf;
for (i = 0; i < __bitset_words(setlen); i++) {
if (*p == ',') {
p++;
continue;
}
ret = sscanf(p, "%lx", &set->__bits[i]);
if (ret == 0 || ret == -1)
break;
while (isxdigit(*p))
p++;
}
return (p - buf);
}
/*
* Return a string representing a valid layout for a cpuset_t object.
* It expects an incoming buffer at least sized as CPUSETBUFSIZ.
*/
char *
cpusetobj_strprint(char *buf, const cpuset_t *set)
{
bitset_strprint(buf, CPUSETBUFSIZ, (const struct bitset *)set,
CPU_SETSIZE);
return (buf);
}
/*
* Build a valid cpuset_t object from a string representation.
* It expects an incoming buffer at least sized as CPUSETBUFSIZ.
*/
int
cpusetobj_strscan(cpuset_t *set, const char *buf)
{
char p;
if (strlen(buf) > CPUSETBUFSIZ - 1)
return (-1);
p = buf[bitset_strscan((struct bitset *)set, CPU_SETSIZE, buf)];
if (p != '\0')
return (-1);
return (0);
}
/*
* Handle a domainset specifier in the sysctl tree. A poiner to a pointer to
* a domainset is in arg1. If the user specifies a valid domainset the
* pointer is updated.
*
* Format is:
* hex mask word 0,hex mask word 1,...:decimal policy:decimal preferred
*/
int
sysctl_handle_domainset(SYSCTL_HANDLER_ARGS)
{
char buf[DOMAINSETBUFSIZ];
struct domainset *dset;
struct domainset key;
int policy, prefer, error;
char *p;
dset = *(struct domainset **)arg1;
error = 0;
if (dset != NULL) {
p = buf + bitset_strprint(buf, DOMAINSETBUFSIZ,
(const struct bitset *)&dset->ds_mask, DOMAINSET_SETSIZE);
sprintf(p, ":%d:%d", dset->ds_policy, dset->ds_prefer);
} else
sprintf(buf, "<NULL>");
error = sysctl_handle_string(oidp, buf, sizeof(buf), req);
if (error != 0 || req->newptr == NULL)
return (error);
/*
* Read in and validate the string.
*/
memset(&key, 0, sizeof(key));
p = &buf[bitset_strscan((struct bitset *)&key.ds_mask,
DOMAINSET_SETSIZE, buf)];
if (p == buf)
return (EINVAL);
if (sscanf(p, ":%d:%d", &policy, &prefer) != 2)
return (EINVAL);
key.ds_policy = policy;
key.ds_prefer = prefer;
/* Domainset_create() validates the policy.*/
dset = domainset_create(&key);
if (dset == NULL)
return (EINVAL);
*(struct domainset **)arg1 = dset;
return (error);
}
/*
* Apply an anonymous mask or a domain to a single thread.
*/
static int
_cpuset_setthread(lwpid_t id, cpuset_t *mask, struct domainset *domain)
{
struct setlist cpusets;
struct domainlist domainlist;
struct cpuset *nset;
struct cpuset *set;
struct thread *td;
struct proc *p;
int error;
cpuset_freelist_init(&cpusets, 1);
domainset_freelist_init(&domainlist, domain != NULL);
error = cpuset_which(CPU_WHICH_TID, id, &p, &td, &set);
if (error)
goto out;
set = NULL;
thread_lock(td);
error = cpuset_shadow(td->td_cpuset, &nset, mask, domain,
&cpusets, &domainlist);
if (error == 0)
set = cpuset_update_thread(td, nset);
thread_unlock(td);
PROC_UNLOCK(p);
if (set)
cpuset_rel(set);
out:
cpuset_freelist_free(&cpusets);
domainset_freelist_free(&domainlist);
return (error);
}
/*
* Apply an anonymous mask to a single thread.
*/
int
cpuset_setthread(lwpid_t id, cpuset_t *mask)
{
return _cpuset_setthread(id, mask, NULL);
}
/*
* Apply new cpumask to the ithread.
*/
int
cpuset_setithread(lwpid_t id, int cpu)
{
cpuset_t mask;
CPU_ZERO(&mask);
if (cpu == NOCPU)
CPU_COPY(cpuset_root, &mask);
else
CPU_SET(cpu, &mask);
return _cpuset_setthread(id, &mask, NULL);
}
/*
* Initialize static domainsets after NUMA information is available. This is
* called before memory allocators are initialized.
*/
void
domainset_init(void)
{
struct domainset *dset;
int i;
dset = &domainset_roundrobin;
DOMAINSET_COPY(&all_domains, &dset->ds_mask);
dset->ds_policy = DOMAINSET_POLICY_ROUNDROBIN;
dset->ds_prefer = -1;
_domainset_create(dset, NULL);
for (i = 0; i < vm_ndomains; i++) {
dset = &domainset_fixed[i];
DOMAINSET_ZERO(&dset->ds_mask);
DOMAINSET_SET(i, &dset->ds_mask);
dset->ds_policy = DOMAINSET_POLICY_ROUNDROBIN;
_domainset_create(dset, NULL);
dset = &domainset_prefer[i];
DOMAINSET_COPY(&all_domains, &dset->ds_mask);
dset->ds_policy = DOMAINSET_POLICY_PREFER;
dset->ds_prefer = i;
_domainset_create(dset, NULL);
}
}
/*
* Create the domainset for cpuset 0, 1 and cpuset 2.
*/
void
domainset_zero(void)
{
struct domainset *dset, *tmp;
mtx_init(&cpuset_lock, "cpuset", NULL, MTX_SPIN | MTX_RECURSE);
dset = &domainset0;
DOMAINSET_COPY(&all_domains, &dset->ds_mask);
dset->ds_policy = DOMAINSET_POLICY_FIRSTTOUCH;
dset->ds_prefer = -1;
curthread->td_domain.dr_policy = _domainset_create(dset, NULL);
domainset_copy(dset, &domainset2);
domainset2.ds_policy = DOMAINSET_POLICY_INTERLEAVE;
kernel_object->domain.dr_policy = _domainset_create(&domainset2, NULL);
/* Remove empty domains from the global policies. */
LIST_FOREACH_SAFE(dset, &cpuset_domains, ds_link, tmp)
if (domainset_empty_vm(dset))
LIST_REMOVE(dset, ds_link);
}
/*
* Creates system-wide cpusets and the cpuset for thread0 including three
* sets:
*
* 0 - The root set which should represent all valid processors in the
* system. It is initially created with a mask of all processors
* because we don't know what processors are valid until cpuset_init()
* runs. This set is immutable.
* 1 - The default set which all processes are a member of until changed.
* This allows an administrator to move all threads off of given cpus to
* dedicate them to high priority tasks or save power etc.
* 2 - The kernel set which allows restriction and policy to be applied only
* to kernel threads and the kernel_object.
*/
struct cpuset *
cpuset_thread0(void)
{
struct cpuset *set;
int i;
int error __unused;
cpuset_zone = uma_zcreate("cpuset", sizeof(struct cpuset), NULL, NULL,
NULL, NULL, UMA_ALIGN_CACHE, 0);
domainset_zone = uma_zcreate("domainset", sizeof(struct domainset),
NULL, NULL, NULL, NULL, UMA_ALIGN_CACHE, 0);
/*
* Create the root system set (0) for the whole machine. Doesn't use
* cpuset_create() due to NULL parent.
*/
set = uma_zalloc(cpuset_zone, M_WAITOK | M_ZERO);
CPU_COPY(&all_cpus, &set->cs_mask);
LIST_INIT(&set->cs_children);
LIST_INSERT_HEAD(&cpuset_ids, set, cs_link);
set->cs_ref = 1;
set->cs_flags = CPU_SET_ROOT | CPU_SET_RDONLY;
set->cs_domain = &domainset0;
cpuset_zero = set;
cpuset_root = &set->cs_mask;
/*
* Now derive a default (1), modifiable set from that to give out.
*/
set = uma_zalloc(cpuset_zone, M_WAITOK | M_ZERO);
error = _cpuset_create(set, cpuset_zero, NULL, NULL, 1);
KASSERT(error == 0, ("Error creating default set: %d\n", error));
cpuset_default = set;
/*
* Create the kernel set (2).
*/
set = uma_zalloc(cpuset_zone, M_WAITOK | M_ZERO);
error = _cpuset_create(set, cpuset_zero, NULL, NULL, 2);
KASSERT(error == 0, ("Error creating kernel set: %d\n", error));
set->cs_domain = &domainset2;
cpuset_kernel = set;
/*
* Initialize the unit allocator. 0 and 1 are allocated above.
*/
cpuset_unr = new_unrhdr(3, INT_MAX, NULL);
/*
* If MD code has not initialized per-domain cpusets, place all
* CPUs in domain 0.
*/
for (i = 0; i < MAXMEMDOM; i++)
if (!CPU_EMPTY(&cpuset_domain[i]))
goto domains_set;
CPU_COPY(&all_cpus, &cpuset_domain[0]);
domains_set:
return (cpuset_default);
}
void
cpuset_kernthread(struct thread *td)
{
struct cpuset *set;
thread_lock(td);
set = td->td_cpuset;
td->td_cpuset = cpuset_ref(cpuset_kernel);
thread_unlock(td);
cpuset_rel(set);
}
/*
* Create a cpuset, which would be cpuset_create() but
* mark the new 'set' as root.
*
* We are not going to reparent the td to it. Use cpuset_setproc_update_set()
* for that.
*
* In case of no error, returns the set in *setp locked with a reference.
*/
int
cpuset_create_root(struct prison *pr, struct cpuset **setp)
{
struct cpuset *set;
int error;
KASSERT(pr != NULL, ("[%s:%d] invalid pr", __func__, __LINE__));
KASSERT(setp != NULL, ("[%s:%d] invalid setp", __func__, __LINE__));
error = cpuset_create(setp, pr->pr_cpuset, &pr->pr_cpuset->cs_mask);
if (error)
return (error);
KASSERT(*setp != NULL, ("[%s:%d] cpuset_create returned invalid data",
__func__, __LINE__));
/* Mark the set as root. */
set = *setp;
set->cs_flags |= CPU_SET_ROOT;
return (0);
}
int
cpuset_setproc_update_set(struct proc *p, struct cpuset *set)
{
int error;
KASSERT(p != NULL, ("[%s:%d] invalid proc", __func__, __LINE__));
KASSERT(set != NULL, ("[%s:%d] invalid set", __func__, __LINE__));
cpuset_ref(set);
error = cpuset_setproc(p->p_pid, set, NULL, NULL);
if (error)
return (error);
cpuset_rel(set);
return (0);
}
#ifndef _SYS_SYSPROTO_H_
struct cpuset_args {
cpusetid_t *setid;
};
#endif
int
sys_cpuset(struct thread *td, struct cpuset_args *uap)
{
struct cpuset *root;
struct cpuset *set;
int error;
thread_lock(td);
root = cpuset_refroot(td->td_cpuset);
thread_unlock(td);
error = cpuset_create(&set, root, &root->cs_mask);
cpuset_rel(root);
if (error)
return (error);
error = copyout(&set->cs_id, uap->setid, sizeof(set->cs_id));
if (error == 0)
error = cpuset_setproc(-1, set, NULL, NULL);
cpuset_rel(set);
return (error);
}
#ifndef _SYS_SYSPROTO_H_
struct cpuset_setid_args {
cpuwhich_t which;
id_t id;
cpusetid_t setid;
};
#endif
int
sys_cpuset_setid(struct thread *td, struct cpuset_setid_args *uap)
{
return (kern_cpuset_setid(td, uap->which, uap->id, uap->setid));
}
int
kern_cpuset_setid(struct thread *td, cpuwhich_t which,
id_t id, cpusetid_t setid)
{
struct cpuset *set;
int error;
/*
* Presently we only support per-process sets.
*/
if (which != CPU_WHICH_PID)
return (EINVAL);
set = cpuset_lookup(setid, td);
if (set == NULL)
return (ESRCH);
error = cpuset_setproc(id, set, NULL, NULL);
cpuset_rel(set);
return (error);
}
#ifndef _SYS_SYSPROTO_H_
struct cpuset_getid_args {
cpulevel_t level;
cpuwhich_t which;
id_t id;
cpusetid_t *setid;
};
#endif
int
sys_cpuset_getid(struct thread *td, struct cpuset_getid_args *uap)
{
return (kern_cpuset_getid(td, uap->level, uap->which, uap->id,
uap->setid));
}
int
kern_cpuset_getid(struct thread *td, cpulevel_t level, cpuwhich_t which,
id_t id, cpusetid_t *setid)
{
struct cpuset *nset;
struct cpuset *set;
struct thread *ttd;
struct proc *p;
cpusetid_t tmpid;
int error;
if (level == CPU_LEVEL_WHICH && which != CPU_WHICH_CPUSET)
return (EINVAL);
error = cpuset_which(which, id, &p, &ttd, &set);
if (error)
return (error);
switch (which) {
case CPU_WHICH_TID:
case CPU_WHICH_PID:
thread_lock(ttd);
set = cpuset_refbase(ttd->td_cpuset);
thread_unlock(ttd);
PROC_UNLOCK(p);
break;
case CPU_WHICH_CPUSET:
case CPU_WHICH_JAIL:
break;
case CPU_WHICH_IRQ:
case CPU_WHICH_DOMAIN:
return (EINVAL);
}
switch (level) {
case CPU_LEVEL_ROOT:
nset = cpuset_refroot(set);
cpuset_rel(set);
set = nset;
break;
case CPU_LEVEL_CPUSET:
break;
case CPU_LEVEL_WHICH:
break;
}
tmpid = set->cs_id;
cpuset_rel(set);
if (error == 0)
error = copyout(&tmpid, setid, sizeof(tmpid));
return (error);
}
#ifndef _SYS_SYSPROTO_H_
struct cpuset_getaffinity_args {
cpulevel_t level;
cpuwhich_t which;
id_t id;
size_t cpusetsize;
cpuset_t *mask;
};
#endif
int
sys_cpuset_getaffinity(struct thread *td, struct cpuset_getaffinity_args *uap)
{
return (kern_cpuset_getaffinity(td, uap->level, uap->which,
uap->id, uap->cpusetsize, uap->mask));
}
int
kern_cpuset_getaffinity(struct thread *td, cpulevel_t level, cpuwhich_t which,
id_t id, size_t cpusetsize, cpuset_t *maskp)
{
struct thread *ttd;
struct cpuset *nset;
struct cpuset *set;
struct proc *p;
cpuset_t *mask;
int error;
size_t size;
if (cpusetsize < sizeof(cpuset_t) || cpusetsize > CPU_MAXSIZE / NBBY)
return (ERANGE);
/* In Capability mode, you can only get your own CPU set. */
if (IN_CAPABILITY_MODE(td)) {
if (level != CPU_LEVEL_WHICH)
return (ECAPMODE);
if (which != CPU_WHICH_TID && which != CPU_WHICH_PID)
return (ECAPMODE);
if (id != -1)
return (ECAPMODE);
}
size = cpusetsize;
mask = malloc(size, M_TEMP, M_WAITOK | M_ZERO);
error = cpuset_which(which, id, &p, &ttd, &set);
if (error)
goto out;
switch (level) {
case CPU_LEVEL_ROOT:
case CPU_LEVEL_CPUSET:
switch (which) {
case CPU_WHICH_TID:
case CPU_WHICH_PID:
thread_lock(ttd);
set = cpuset_ref(ttd->td_cpuset);
thread_unlock(ttd);
break;
case CPU_WHICH_CPUSET:
case CPU_WHICH_JAIL:
break;
case CPU_WHICH_IRQ:
case CPU_WHICH_INTRHANDLER:
case CPU_WHICH_ITHREAD:
case CPU_WHICH_DOMAIN:
error = EINVAL;
goto out;
}
if (level == CPU_LEVEL_ROOT)
nset = cpuset_refroot(set);
else
nset = cpuset_refbase(set);
CPU_COPY(&nset->cs_mask, mask);
cpuset_rel(nset);
break;
case CPU_LEVEL_WHICH:
switch (which) {
case CPU_WHICH_TID:
thread_lock(ttd);
CPU_COPY(&ttd->td_cpuset->cs_mask, mask);
thread_unlock(ttd);
break;
case CPU_WHICH_PID:
FOREACH_THREAD_IN_PROC(p, ttd) {
thread_lock(ttd);
CPU_OR(mask, &ttd->td_cpuset->cs_mask);
thread_unlock(ttd);
}
break;
case CPU_WHICH_CPUSET:
case CPU_WHICH_JAIL:
CPU_COPY(&set->cs_mask, mask);
break;
case CPU_WHICH_IRQ:
case CPU_WHICH_INTRHANDLER:
case CPU_WHICH_ITHREAD:
error = intr_getaffinity(id, which, mask);
break;
case CPU_WHICH_DOMAIN:
if (id < 0 || id >= MAXMEMDOM)
error = ESRCH;
else
CPU_COPY(&cpuset_domain[id], mask);
break;
}
break;
default:
error = EINVAL;
break;
}
if (set)
cpuset_rel(set);
if (p)
PROC_UNLOCK(p);
if (error == 0)
error = copyout(mask, maskp, size);
out:
free(mask, M_TEMP);
return (error);
}
#ifndef _SYS_SYSPROTO_H_
struct cpuset_setaffinity_args {
cpulevel_t level;
cpuwhich_t which;
id_t id;
size_t cpusetsize;
const cpuset_t *mask;
};
#endif
int
sys_cpuset_setaffinity(struct thread *td, struct cpuset_setaffinity_args *uap)
{
return (kern_cpuset_setaffinity(td, uap->level, uap->which,
uap->id, uap->cpusetsize, uap->mask));
}
int
kern_cpuset_setaffinity(struct thread *td, cpulevel_t level, cpuwhich_t which,
id_t id, size_t cpusetsize, const cpuset_t *maskp)
{
struct cpuset *nset;
struct cpuset *set;
struct thread *ttd;
struct proc *p;
cpuset_t *mask;
int error;
if (cpusetsize < sizeof(cpuset_t) || cpusetsize > CPU_MAXSIZE / NBBY)
return (ERANGE);
/* In Capability mode, you can only set your own CPU set. */
if (IN_CAPABILITY_MODE(td)) {
if (level != CPU_LEVEL_WHICH)
return (ECAPMODE);
if (which != CPU_WHICH_TID && which != CPU_WHICH_PID)
return (ECAPMODE);
if (id != -1)
return (ECAPMODE);
}
mask = malloc(cpusetsize, M_TEMP, M_WAITOK | M_ZERO);
error = copyin(maskp, mask, cpusetsize);
if (error)
goto out;
/*
* Verify that no high bits are set.
*/
if (cpusetsize > sizeof(cpuset_t)) {
char *end;
char *cp;
end = cp = (char *)&mask->__bits;
end += cpusetsize;
cp += sizeof(cpuset_t);
while (cp != end)
if (*cp++ != 0) {
error = EINVAL;
goto out;
}
}
switch (level) {
case CPU_LEVEL_ROOT:
case CPU_LEVEL_CPUSET:
error = cpuset_which(which, id, &p, &ttd, &set);
if (error)
break;
switch (which) {
case CPU_WHICH_TID:
case CPU_WHICH_PID:
thread_lock(ttd);
set = cpuset_ref(ttd->td_cpuset);
thread_unlock(ttd);
PROC_UNLOCK(p);
break;
case CPU_WHICH_CPUSET:
case CPU_WHICH_JAIL:
break;
case CPU_WHICH_IRQ:
case CPU_WHICH_INTRHANDLER:
case CPU_WHICH_ITHREAD:
case CPU_WHICH_DOMAIN:
error = EINVAL;
goto out;
}
if (level == CPU_LEVEL_ROOT)
nset = cpuset_refroot(set);
else
nset = cpuset_refbase(set);
error = cpuset_modify(nset, mask);
cpuset_rel(nset);
cpuset_rel(set);
break;
case CPU_LEVEL_WHICH:
switch (which) {
case CPU_WHICH_TID:
error = cpuset_setthread(id, mask);
break;
case CPU_WHICH_PID:
error = cpuset_setproc(id, NULL, mask, NULL);
break;
case CPU_WHICH_CPUSET:
case CPU_WHICH_JAIL:
error = cpuset_which(which, id, &p, &ttd, &set);
if (error == 0) {
error = cpuset_modify(set, mask);
cpuset_rel(set);
}
break;
case CPU_WHICH_IRQ:
case CPU_WHICH_INTRHANDLER:
case CPU_WHICH_ITHREAD:
error = intr_setaffinity(id, which, mask);
break;
default:
error = EINVAL;
break;
}
break;
default:
error = EINVAL;
break;
}
out:
free(mask, M_TEMP);
return (error);
}
#ifndef _SYS_SYSPROTO_H_
struct cpuset_getdomain_args {
cpulevel_t level;
cpuwhich_t which;
id_t id;
size_t domainsetsize;
domainset_t *mask;
int *policy;
};
#endif
int
sys_cpuset_getdomain(struct thread *td, struct cpuset_getdomain_args *uap)
{
return (kern_cpuset_getdomain(td, uap->level, uap->which,
uap->id, uap->domainsetsize, uap->mask, uap->policy));
}
int
kern_cpuset_getdomain(struct thread *td, cpulevel_t level, cpuwhich_t which,
id_t id, size_t domainsetsize, domainset_t *maskp, int *policyp)
{
struct domainset outset;
struct thread *ttd;
struct cpuset *nset;
struct cpuset *set;
struct domainset *dset;
struct proc *p;
domainset_t *mask;
int error;
if (domainsetsize < sizeof(domainset_t) ||
domainsetsize > DOMAINSET_MAXSIZE / NBBY)
return (ERANGE);
/* In Capability mode, you can only get your own domain set. */
if (IN_CAPABILITY_MODE(td)) {
if (level != CPU_LEVEL_WHICH)
return (ECAPMODE);
if (which != CPU_WHICH_TID && which != CPU_WHICH_PID)
return (ECAPMODE);
if (id != -1)
return (ECAPMODE);
}
mask = malloc(domainsetsize, M_TEMP, M_WAITOK | M_ZERO);
bzero(&outset, sizeof(outset));
error = cpuset_which(which, id, &p, &ttd, &set);
if (error)
goto out;
switch (level) {
case CPU_LEVEL_ROOT:
case CPU_LEVEL_CPUSET:
switch (which) {
case CPU_WHICH_TID:
case CPU_WHICH_PID:
thread_lock(ttd);
set = cpuset_ref(ttd->td_cpuset);
thread_unlock(ttd);
break;
case CPU_WHICH_CPUSET:
case CPU_WHICH_JAIL:
break;
case CPU_WHICH_IRQ:
case CPU_WHICH_INTRHANDLER:
case CPU_WHICH_ITHREAD:
case CPU_WHICH_DOMAIN:
error = EINVAL;
goto out;
}
if (level == CPU_LEVEL_ROOT)
nset = cpuset_refroot(set);
else
nset = cpuset_refbase(set);
domainset_copy(nset->cs_domain, &outset);
cpuset_rel(nset);
break;
case CPU_LEVEL_WHICH:
switch (which) {
case CPU_WHICH_TID:
thread_lock(ttd);
domainset_copy(ttd->td_cpuset->cs_domain, &outset);
thread_unlock(ttd);
break;
case CPU_WHICH_PID:
FOREACH_THREAD_IN_PROC(p, ttd) {
thread_lock(ttd);
dset = ttd->td_cpuset->cs_domain;
/* Show all domains in the proc. */
DOMAINSET_OR(&outset.ds_mask, &dset->ds_mask);
/* Last policy wins. */
outset.ds_policy = dset->ds_policy;
outset.ds_prefer = dset->ds_prefer;
thread_unlock(ttd);
}
break;
case CPU_WHICH_CPUSET:
case CPU_WHICH_JAIL:
domainset_copy(set->cs_domain, &outset);
break;
case CPU_WHICH_IRQ:
case CPU_WHICH_INTRHANDLER:
case CPU_WHICH_ITHREAD:
case CPU_WHICH_DOMAIN:
error = EINVAL;
break;
}
break;
default:
error = EINVAL;
break;
}
if (set)
cpuset_rel(set);
if (p)
PROC_UNLOCK(p);
/*
* Translate prefer into a set containing only the preferred domain,
* not the entire fallback set.
*/
if (outset.ds_policy == DOMAINSET_POLICY_PREFER) {
DOMAINSET_ZERO(&outset.ds_mask);
DOMAINSET_SET(outset.ds_prefer, &outset.ds_mask);
}
DOMAINSET_COPY(&outset.ds_mask, mask);
if (error == 0)
error = copyout(mask, maskp, domainsetsize);
if (error == 0)
if (suword32(policyp, outset.ds_policy) != 0)
error = EFAULT;
out:
free(mask, M_TEMP);
return (error);
}
#ifndef _SYS_SYSPROTO_H_
struct cpuset_setdomain_args {
cpulevel_t level;
cpuwhich_t which;
id_t id;
size_t domainsetsize;
domainset_t *mask;
int policy;
};
#endif
int
sys_cpuset_setdomain(struct thread *td, struct cpuset_setdomain_args *uap)
{
return (kern_cpuset_setdomain(td, uap->level, uap->which,
uap->id, uap->domainsetsize, uap->mask, uap->policy));
}
int
kern_cpuset_setdomain(struct thread *td, cpulevel_t level, cpuwhich_t which,
id_t id, size_t domainsetsize, const domainset_t *maskp, int policy)
{
struct cpuset *nset;
struct cpuset *set;
struct thread *ttd;
struct proc *p;
struct domainset domain;
domainset_t *mask;
int error;
if (domainsetsize < sizeof(domainset_t) ||
domainsetsize > DOMAINSET_MAXSIZE / NBBY)
return (ERANGE);
if (policy <= DOMAINSET_POLICY_INVALID ||
policy > DOMAINSET_POLICY_MAX)
return (EINVAL);
/* In Capability mode, you can only set your own CPU set. */
if (IN_CAPABILITY_MODE(td)) {
if (level != CPU_LEVEL_WHICH)
return (ECAPMODE);
if (which != CPU_WHICH_TID && which != CPU_WHICH_PID)
return (ECAPMODE);
if (id != -1)
return (ECAPMODE);
}
memset(&domain, 0, sizeof(domain));
mask = malloc(domainsetsize, M_TEMP, M_WAITOK | M_ZERO);
error = copyin(maskp, mask, domainsetsize);
if (error)
goto out;
/*
* Verify that no high bits are set.
*/
if (domainsetsize > sizeof(domainset_t)) {
char *end;
char *cp;
end = cp = (char *)&mask->__bits;
end += domainsetsize;
cp += sizeof(domainset_t);
while (cp != end)
if (*cp++ != 0) {
error = EINVAL;
goto out;
}
}
DOMAINSET_COPY(mask, &domain.ds_mask);
domain.ds_policy = policy;
/*
* Sanitize the provided mask.
*/
if (!DOMAINSET_SUBSET(&all_domains, &domain.ds_mask)) {
error = EINVAL;
goto out;
}
/* Translate preferred policy into a mask and fallback. */
if (policy == DOMAINSET_POLICY_PREFER) {
/* Only support a single preferred domain. */
if (DOMAINSET_COUNT(&domain.ds_mask) != 1) {
error = EINVAL;
goto out;
}
domain.ds_prefer = DOMAINSET_FFS(&domain.ds_mask) - 1;
/* This will be constrained by domainset_shadow(). */
DOMAINSET_COPY(&all_domains, &domain.ds_mask);
}
/*
* When given an impossible policy, fall back to interleaving
* across all domains.
*/
if (domainset_empty_vm(&domain))
domainset_copy(&domainset2, &domain);
switch (level) {
case CPU_LEVEL_ROOT:
case CPU_LEVEL_CPUSET:
error = cpuset_which(which, id, &p, &ttd, &set);
if (error)
break;
switch (which) {
case CPU_WHICH_TID:
case CPU_WHICH_PID:
thread_lock(ttd);
set = cpuset_ref(ttd->td_cpuset);
thread_unlock(ttd);
PROC_UNLOCK(p);
break;
case CPU_WHICH_CPUSET:
case CPU_WHICH_JAIL:
break;
case CPU_WHICH_IRQ:
case CPU_WHICH_INTRHANDLER:
case CPU_WHICH_ITHREAD:
case CPU_WHICH_DOMAIN:
error = EINVAL;
goto out;
}
if (level == CPU_LEVEL_ROOT)
nset = cpuset_refroot(set);
else
nset = cpuset_refbase(set);
error = cpuset_modify_domain(nset, &domain);
cpuset_rel(nset);
cpuset_rel(set);
break;
case CPU_LEVEL_WHICH:
switch (which) {
case CPU_WHICH_TID:
error = _cpuset_setthread(id, NULL, &domain);
break;
case CPU_WHICH_PID:
error = cpuset_setproc(id, NULL, NULL, &domain);
break;
case CPU_WHICH_CPUSET:
case CPU_WHICH_JAIL:
error = cpuset_which(which, id, &p, &ttd, &set);
if (error == 0) {
error = cpuset_modify_domain(set, &domain);
cpuset_rel(set);
}
break;
case CPU_WHICH_IRQ:
case CPU_WHICH_INTRHANDLER:
case CPU_WHICH_ITHREAD:
default:
error = EINVAL;
break;
}
break;
default:
error = EINVAL;
break;
}
out:
free(mask, M_TEMP);
return (error);
}
#ifdef DDB
static void
ddb_display_bitset(const struct bitset *set, int size)
{
int bit, once;
for (once = 0, bit = 0; bit < size; bit++) {
if (CPU_ISSET(bit, set)) {
if (once == 0) {
db_printf("%d", bit);
once = 1;
} else
db_printf(",%d", bit);
}
}
if (once == 0)
db_printf("<none>");
}
void
ddb_display_cpuset(const cpuset_t *set)
{
ddb_display_bitset((const struct bitset *)set, CPU_SETSIZE);
}
static void
ddb_display_domainset(const domainset_t *set)
{
ddb_display_bitset((const struct bitset *)set, DOMAINSET_SETSIZE);
}
DB_SHOW_COMMAND(cpusets, db_show_cpusets)
{
struct cpuset *set;
LIST_FOREACH(set, &cpuset_ids, cs_link) {
db_printf("set=%p id=%-6u ref=%-6d flags=0x%04x parent id=%d\n",
set, set->cs_id, set->cs_ref, set->cs_flags,
(set->cs_parent != NULL) ? set->cs_parent->cs_id : 0);
db_printf(" cpu mask=");
ddb_display_cpuset(&set->cs_mask);
db_printf("\n");
db_printf(" domain policy %d prefer %d mask=",
set->cs_domain->ds_policy, set->cs_domain->ds_prefer);
ddb_display_domainset(&set->cs_domain->ds_mask);
db_printf("\n");
if (db_pager_quit)
break;
}
}
DB_SHOW_COMMAND(domainsets, db_show_domainsets)
{
struct domainset *set;
LIST_FOREACH(set, &cpuset_domains, ds_link) {
db_printf("set=%p policy %d prefer %d cnt %d\n",
set, set->ds_policy, set->ds_prefer, set->ds_cnt);
db_printf(" mask =");
ddb_display_domainset(&set->ds_mask);
db_printf("\n");
}
}
#endif /* DDB */
| 24.702936 | 80 | 0.699853 | [
"object"
] |
d32c7ff3564a120c6b6e4f45ef27d022ca4972c9 | 3,345 | h | C | archive/CPPHelloSpeech/packages/Microsoft.CognitiveServices.Speech.0.2.12733/build/native/include/cxx_api/speechapi_cxx_intent_trigger.h | akashdeepbansal/eBookNavigator | 429204fb2d1e69b2918c7be9084c57ecf676975f | [
"MIT"
] | null | null | null | archive/CPPHelloSpeech/packages/Microsoft.CognitiveServices.Speech.0.2.12733/build/native/include/cxx_api/speechapi_cxx_intent_trigger.h | akashdeepbansal/eBookNavigator | 429204fb2d1e69b2918c7be9084c57ecf676975f | [
"MIT"
] | null | null | null | archive/CPPHelloSpeech/packages/Microsoft.CognitiveServices.Speech.0.2.12733/build/native/include/cxx_api/speechapi_cxx_intent_trigger.h | akashdeepbansal/eBookNavigator | 429204fb2d1e69b2918c7be9084c57ecf676975f | [
"MIT"
] | 1 | 2020-12-29T09:02:56.000Z | 2020-12-29T09:02:56.000Z | //
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
//
// speechapi_cxx_intent_trigger.h: Public API declarations for IntentTrigger C++ class
//
#pragma once
#include <speechapi_cxx_common.h>
#include <speechapi_c.h>
#include <speechapi_cxx_common.h>
#include <speechapi_cxx_language_understanding_model.h>
namespace Microsoft {
namespace CognitiveServices {
namespace Speech {
namespace Intent {
/// <summary>
/// Represents an intent trigger.
/// </summary>
class IntentTrigger
{
public:
/// <summary>
/// Creates an intent trigger using the specified phrase.
/// </summary>
/// <param name="simplePhrase">The simple phrase to create an intent trigger for.</param>
/// <returns>A shared pointer to an intent trigger.</returns>
static std::shared_ptr<IntentTrigger> From(const std::wstring& simplePhrase)
{
SPXTRIGGERHANDLE htrigger = SPXHANDLE_INVALID;
SPX_THROW_ON_FAIL(IntentTrigger_Create_From_Phrase(simplePhrase.c_str(), &htrigger));
return std::make_shared<IntentTrigger>(htrigger);
}
/// <summary>
/// Creates an intent trigger using the specified LanguageUnderstandingModel.
/// </summary>
/// <param name="model">The LanguageUnderstandingModel to create an intent trigger for.</param>
/// <returns>A shared pointer to an intent trigger.</returns>
static std::shared_ptr<IntentTrigger> From(std::shared_ptr<LanguageUnderstandingModel> model)
{
SPXTRIGGERHANDLE htrigger = SPXHANDLE_INVALID;
SPX_THROW_ON_FAIL(IntentTrigger_Create_From_LanguageUnderstandingModel((SPXLUMODELHANDLE)(*model.get()), &htrigger));
return std::make_shared<IntentTrigger>(htrigger);
}
/// <summary>
/// Creates an intent trigger using the specified LanguageUnderstandingModel and an intent name.
/// </summary>
/// <param name="model">The LanguageUnderstandingModel to create an intent trigger for.</param>
/// <param name="model">The intent name to create an intent trigger for.</param>
/// <returns>A shared pointer to an intent trigger.</returns>
static std::shared_ptr<IntentTrigger> From(std::shared_ptr<LanguageUnderstandingModel> model, const std::wstring& intentName)
{
SPXTRIGGERHANDLE htrigger = SPXHANDLE_INVALID;
SPX_THROW_ON_FAIL(IntentTrigger_Create_From_LanguageUnderstandingModel_Intent((SPXLUMODELHANDLE)(*model.get()), intentName.c_str(), &htrigger));
return std::make_shared<IntentTrigger>(htrigger);
}
/// <summary>
/// Virtual destructor
/// </summary>
virtual ~IntentTrigger() { IntentTrigger_Handle_Close(m_htrigger); m_htrigger = SPXHANDLE_INVALID; }
/// <summary>
/// Internal constructor. Creates a new instance using the provided handle.
/// </summary>
explicit IntentTrigger(SPXTRIGGERHANDLE htrigger) : m_htrigger(htrigger) { };
/// <summary>
/// Internal. Explicit conversion operator.
/// </summary>
explicit operator SPXTRIGGERHANDLE() { return m_htrigger; }
private:
DISABLE_DEFAULT_CTORS(IntentTrigger);
SPXTRIGGERHANDLE m_htrigger;
};
} } } } // Microsoft::CognitiveServices::Speech::Intent
| 38.448276 | 153 | 0.701644 | [
"model"
] |
d32e347dec2529253235d5fd10f745e8919da644 | 10,523 | h | C | src/toolbox.h | miriammenzel/PLImig | d1ef5265368c2902b4fffea69dcaeb253e4c9a97 | [
"MIT"
] | null | null | null | src/toolbox.h | miriammenzel/PLImig | d1ef5265368c2902b4fffea69dcaeb253e4c9a97 | [
"MIT"
] | null | null | null | src/toolbox.h | miriammenzel/PLImig | d1ef5265368c2902b4fffea69dcaeb253e4c9a97 | [
"MIT"
] | 1 | 2022-02-13T03:59:40.000Z | 2022-02-13T03:59:40.000Z | /*
MIT License
Copyright (c) 2021 Forschungszentrum Jülich / Jan André Reuter.
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 PLIMG_TOOLBOX_H
#define PLIMG_TOOLBOX_H
#include "cuda/cuda_toolbox.h"
#include "cuda/define.h"
#include "cuda/exceptions.h"
#include <chrono>
#include <numeric>
#include <omp.h>
#include <opencv2/opencv.hpp>
#include <random>
#include <set>
#include <thrust/device_vector.h>
#include <thrust/unique.h>
#include <vector>
/// Minimum number of bins used for the calculation of tRet() and tTra()
constexpr auto MIN_NUMBER_OF_BINS = 64;
/// Maximum number of bins used for the calculation of tRet() and tTra(). This value will also be used as the default number of bins for all other operations.
constexpr auto MAX_NUMBER_OF_BINS = 256;
/**
* @file
* @brief PLImg histogram toolbox functions
*/
namespace PLImg {
namespace Histogram {
/**
* @brief Determine the one-sided peak width of a given peak position based on its height.
* @param hist Histogram which was calculated using OpenCV functions
* @param peakPosition Peak position in histogram of which the width shall be calculated
* @param direction +1 -> ++peakPosition , -1 -> --peakPosition
* @param targetHeight Target height for the peak width. 0.5 = 50%.
* @return Integer number describing the width in bins
*/
int peakWidth(cv::Mat hist, int peakPosition, float direction, float targetHeight = 0.5f);
/**
* This method calculates the floating point value of the curvature in a given histogram.
* To achieve this, the curvature is determined using numerical differentiation with the following formula
* \f[ \kappa = \frac{y^{''}}{(1+(y^{'})^2)^{3/2}} \f]
* The maximum position of \f$ \kappa \f$ is our maximum curvature and will be returned.
* @brief Calculate the maximum curvature floating point value of a histogram
* @param hist OpenCV calculated histogram
*/
cv::Mat curvature(cv::Mat hist, float histHigh, float histLow);
/**
* Histograms can be interpreted as a discrete function with extrema like any normal function. This method
* allows to calculate the peak positions in between an interval (start, stop) with an additional threshold
* which is the prominence of detected peaks.
* The implementation is similar to the implementation of peak finding in SciPy.
* @brief Calculate the peak positions within a histogram filtered with prominence values
* @param hist OpenCV histogram
* @param start Start bin
* @param stop End bin
* @param minSignificance Minimal prominence value for a peak to be considered as such.
* @return Vector with the peak positions in between start and stop
*/
std::vector<unsigned> peaks(cv::Mat hist, int start, int stop, float minSignificance = 0.01f);
}
namespace Image {
std::array<cv::Mat, 2> randomizedModalities(std::shared_ptr<cv::Mat>& transmittance, std::shared_ptr<cv::Mat>& retardation, float scalingValue=0.25f);
unsigned long long maskCountNonZero(const cv::Mat& mask);
}
namespace cuda {
/**
* @brief Execute some CUDA checks to ensure that the rest of the program should run as expected.
* @return true if all checks were run successfully
*/
bool runCUDAchecks();
/**
* @brief Get the total amount of memory in bytes.
* @return Total amount of VRAM in bytes.
*/
size_t getTotalMemory();
/**
* @brief Get the free amount of memory in bytes.
* @return Total amount of free VRAM in bytes.
*/
size_t getFreeMemory();
size_t getHistogramMemoryEstimation(const cv::Mat& image, uint numBins);
cv::Mat histogram(const cv::Mat& image, float minLabel, float maxLabel, uint numBins);
namespace filters {
size_t getMedianFilterMemoryEstimation(const std::shared_ptr<cv::Mat>& image);
size_t getMedianFilterMaskedMemoryEstimation(const std::shared_ptr<cv::Mat>& image, const std::shared_ptr<cv::Mat>& mask);
/**
* This method applies a circular median filter with a radius of 10 to the given image.
* @brief Apply circular median filter with a radius of 10 to the image
* @param image Image on which the median filter will be applied.
* @return Shared pointer of the filtered image.
*/
std::shared_ptr<cv::Mat> medianFilter(const std::shared_ptr<cv::Mat>& image);
/**
* This method applies a circular median filter with a radius of 10 to the given image. In addition
* only masked pixels will be filtered.
* Let's take the following example for a small mask:
* | 1 | 1 | 1 |
* | 0 | 1 | 0 |
* | 0 | 0 | 0 |
* When we are at a pixel which is masked with a 1, we will only look at pixels within the radius which is
* also a 1. When we are at a pixel which is masked with a 0, we will only look at pixels within the radius
* which is also a 0.
* @brief Apply circular median filter with a radius of 10 to the image while applying a separation mask.
* @param image Image on which the masked median filter will be applied.
* @param mask 8-bit mask for the median filter.
* @return Shared pointer of the filtered image.
*/
std::shared_ptr<cv::Mat> medianFilterMasked(const std::shared_ptr<cv::Mat>& image, const std::shared_ptr<cv::Mat>& mask);
}
namespace labeling {
size_t getLargestAreaConnectedComponentsMemoryEstimation(const cv::Mat& image);
size_t getConnectedComponentsMemoryEstimation(const cv::Mat& image);
size_t getConnectedComponentsLargestComponentMemoryEstimation(const cv::Mat& image);
/**
* This method allows to search the largest connected component in an image. This connected component will
* represent the largest area with the highest image values consisting of at least
* \f$ percentPixels / 100 * image.size() \f$ pixels. The threshold is determined through the number of image bins
* which need to be used to find a valid mask with enough pixels.
* @brief Search for the largest connected components area which fills at least percentPixels of the image size.
* @param image OpenCV image which will be used for the connected components algorithm.
* @param mask
* @param percentPixels Percent of pixels which are needed for the algorithm to succeed.
* @return OpenCV matrix masking the connected components area with the largest pixels
*/
cv::Mat largestAreaConnectedComponents(const cv::Mat& image, cv::Mat mask = cv::Mat(), float percentPixels = 0.01f);
/**
* Execute the connected components algorithm on an 8-bit image. This method will use the CUDA NPP library
* to detect connected regions and will return a mask with the resulting labels. If the input image is too
* large this method will use chunks to reduce the memory load. However, this will increase the computing
* time significantly.
* @brief Run connected components algorithm on an 8-bit image
* @param image 8-bit OpenCV matrix
* @return OpenCV matrix with the resulting labels of the input image
*/
cv::Mat connectedComponents (const cv::Mat& image);
/**
* If the original image is too large for the connected component algorithm on the GPU the image will be
* split into chunks to allow the execution. However, labels on the edges of the chunks might be
* wrong because they are split due to the chunk choice. This method fixes the wrong labels by checking
* border regions for labels on both sides and creating a lookup table to fix those labels.
* The input image itself will be altered in this operation. Please keep this in mind.
* @param image Chunked image which contains possible wrong labeling
* @param numberOfChunks Number of chunks which were used to generate the image.
*/
void connectedComponentsMergeChunks(cv::Mat& image, int numberOfChunks);
/**
* connectedComponents (const cv::Mat& image) will return a labeled image which can be further analyzed.
* This functions allows to find the largest region and will return a mask of it in combination with its
* size as an integer value. This method will use the CUDA NPP library to create a histogram of the labels
* @brief Get mask and size of the largest component from connected components mask
* @param connetedComponentsImage Output image of connectedComponents (const cv::Mat& image)
* @return Pair of the largest region mask and the number of pixels in the mask.
*/
std::pair<cv::Mat, int> largestComponent(const cv::Mat& connectedComponentsImage);
}
}
}
#endif //PLIMG_TOOLBOX_H
| 55.094241 | 158 | 0.662834 | [
"vector"
] |
d333f2d8c93c0b149127051b63c2d8af5c419f90 | 2,811 | c | C | Alistra/Math/Camera.c | Vertver/Alistra | 2e58bdc6af79f40bb46f6ce31b5f42a1974e94b9 | [
"MIT"
] | 1 | 2019-09-03T19:42:26.000Z | 2019-09-03T19:42:26.000Z | Alistra/Math/Camera.c | Vertver/Alistra | 2e58bdc6af79f40bb46f6ce31b5f42a1974e94b9 | [
"MIT"
] | null | null | null | Alistra/Math/Camera.c | Vertver/Alistra | 2e58bdc6af79f40bb46f6ce31b5f42a1974e94b9 | [
"MIT"
] | 1 | 2020-06-28T16:57:54.000Z | 2020-06-28T16:57:54.000Z | #include "Camera.h"
#include "Vector.h"
MATRIX4 OrtographicLH(float ViewWidth, float ViewHeight, float NearZ, float FarZ)
{
const float range = 1.0f / (FarZ - NearZ);
MATRIX4 m;
m.m[0][0] = 2.0f / ViewWidth;
m.m[0][1] = 0.0f;
m.m[0][2] = 0.0f;
m.m[0][3] = 0.0f;
m.m[1][0] = 0.0f;
m.m[1][1] = 2.0f / ViewHeight;
m.m[1][2] = 0.0f;
m.m[1][3] = 0.0f;
m.m[2][0] = 0.0f;
m.m[2][1] = 0.0f;
m.m[2][2] = range;
m.m[2][3] = 0.0f;
m.m[3][0] = 0.0f;
m.m[3][1] = 0.0f;
m.m[3][2] = -range * NearZ;
m.m[3][3] = 1.0f;
return m;
}
MATRIX4 OrtographicRH(float ViewWidth, float ViewHeight, float NearZ, float FarZ)
{
const float range = 1.0f / (NearZ - FarZ);
MATRIX4 m;
m.m[0][0] = 2.0f / ViewWidth;
m.m[0][1] = 0.0f;
m.m[0][2] = 0.0f;
m.m[0][3] = 0.0f;
m.m[1][0] = 0.0f;
m.m[1][1] = 2.0f / ViewHeight;
m.m[1][2] = 0.0f;
m.m[1][3] = 0.0f;
m.m[2][0] = 0.0f;
m.m[2][1] = 0.0f;
m.m[2][2] = range;
m.m[2][3] = 0.0f;
m.m[3][0] = 0.0f;
m.m[3][1] = 0.0f;
m.m[3][2] = range * NearZ;
m.m[3][3] = 1.0f;
return m;
}
MATRIX4 OrtographicOffCenterLH(float ViewLeft, float ViewRight, float ViewBottom, float ViewTop, float NearZ,
float FarZ)
{
const float ReciprocalWidth = 1.0f / (ViewRight - ViewLeft);
const float ReciprocalHeight = 1.0f / (ViewTop - ViewBottom);
const float range = 1.0f / (FarZ - NearZ);
MATRIX4 m;
m.m[0][0] = ReciprocalWidth + ReciprocalWidth;
m.m[0][1] = 0.0f;
m.m[0][2] = 0.0f;
m.m[0][3] = 0.0f;
m.m[1][0] = 0.0f;
m.m[1][1] = ReciprocalHeight + ReciprocalHeight;
m.m[1][2] = 0.0f;
m.m[1][3] = 0.0f;
m.m[2][0] = 0.0f;
m.m[2][1] = 0.0f;
m.m[2][2] = range;
m.m[2][3] = 0.0f;
m.m[3][0] = -(ViewLeft + ViewRight) * ReciprocalWidth;
m.m[3][1] = -(ViewTop + ViewBottom) * ReciprocalHeight;
m.m[3][2] = -range * NearZ;
m.m[3][3] = 1.0f;
return m;
}
MATRIX4 OrtographicOffCenterRH(float ViewLeft, float ViewRight, float ViewBottom, float ViewTop, float NearZ,
float FarZ)
{
const float ReciprocalWidth = 1.0f / (ViewRight - ViewLeft);
const float ReciprocalHeight = 1.0f / (ViewTop - ViewBottom);
const float range = 1.0f / (NearZ - FarZ);
MATRIX4 M;
M.m[0][0] = ReciprocalWidth + ReciprocalWidth;
M.m[0][1] = 0.0f;
M.m[0][2] = 0.0f;
M.m[0][3] = 0.0f;
M.m[1][0] = 0.0f;
M.m[1][1] = ReciprocalHeight + ReciprocalHeight;
M.m[1][2] = 0.0f;
M.m[1][3] = 0.0f;
M.m[2][0] = 0.0f;
M.m[2][1] = 0.0f;
M.m[2][2] = range;
M.m[2][3] = 0.0f;
M.r[3] = VECTORSet(-(ViewLeft + ViewRight) * ReciprocalWidth,
-(ViewTop + ViewBottom) * ReciprocalHeight,
range * NearZ,
1.0f);
return M;
}
| 24.232759 | 109 | 0.521523 | [
"vector"
] |
d33860c8bc3a809a9bfb595f7744a4293cbe907b | 2,489 | h | C | common/rediscommand.h | andriymoroz-mlnx/sonic-swss-common | e06988dd2c44f6c5200f16c765a0e9a64a0ce274 | [
"Apache-2.0"
] | null | null | null | common/rediscommand.h | andriymoroz-mlnx/sonic-swss-common | e06988dd2c44f6c5200f16c765a0e9a64a0ce274 | [
"Apache-2.0"
] | null | null | null | common/rediscommand.h | andriymoroz-mlnx/sonic-swss-common | e06988dd2c44f6c5200f16c765a0e9a64a0ce274 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <string.h>
#include <tuple>
namespace swss {
typedef std::tuple<std::string, std::string> FieldValueTuple;
#define fvField std::get<0>
#define fvValue std::get<1>
typedef std::tuple<std::string, std::string, std::vector<FieldValueTuple> > KeyOpFieldsValuesTuple;
#define kfvKey std::get<0>
#define kfvOp std::get<1>
#define kfvFieldsValues std::get<2>
class RedisCommand {
public:
RedisCommand() : temp(NULL) { }
~RedisCommand() { redisFreeCommand(temp); }
RedisCommand(RedisCommand& that);
RedisCommand& operator=(RedisCommand& that);
void format(const char *fmt, ...) {
va_list ap;
va_start(ap, fmt);
int len = redisvFormatCommand(&temp, fmt, ap);
if (len == -1) {
throw std::bad_alloc();
} else if (len == -2) {
throw std::invalid_argument("fmt");
}
}
void formatArgv(int argc, const char **argv, const size_t *argvlen) {
int len = redisFormatCommandArgv(&temp, argc, argv, argvlen);
if (len == -1) {
throw std::bad_alloc();
}
}
/* Format HMSET key multiple field value command */
void formatHMSET(const std::string &key,
const std::vector<FieldValueTuple> &values)
{
if (values.empty()) throw std::invalid_argument("empty values");
const char* cmd = "HMSET";
std::vector<const char*> args = { cmd, key.c_str() };
for (const auto &fvt: values)
{
args.push_back(fvField(fvt).c_str());
args.push_back(fvValue(fvt).c_str());
}
formatArgv((int)args.size(), args.data(), NULL);
}
/* Format HSET key field value command */
void formatHSET(const std::string& key, const std::string& field,
const std::string& value)
{
format("HSET %s %s %s", key.c_str(), field.c_str(), value.c_str());
}
/* Format HGET key field command */
void formatHGET(const std::string& key, const std::string& field)
{
format("HGET %s %s", key.c_str(), field.c_str());
}
/* Format HDEL key field command */
void formatHDEL(const std::string& key, const std::string& field)
{
return format("HDEL %s %s", key.c_str(), field.c_str());
}
const char *c_str() const
{
return temp;
}
size_t length() const
{
return strlen(temp);
}
private:
char *temp;
};
} | 27.054348 | 99 | 0.573323 | [
"vector"
] |
50d94b8c3370b5471e64090fb46a1799c1333b14 | 615 | h | C | net/ip-encoding.h | iceb0y/trunk | 8d21be238d8478691f947ce1ecf905ac9b75787b | [
"Apache-2.0"
] | 6 | 2019-12-01T00:49:31.000Z | 2020-07-26T07:35:07.000Z | net/ip-encoding.h | iceboy233/trunk | 83024a83f07a587e00a3f2e1906361de521d8f12 | [
"Apache-2.0"
] | null | null | null | net/ip-encoding.h | iceboy233/trunk | 83024a83f07a587e00a3f2e1906361de521d8f12 | [
"Apache-2.0"
] | 1 | 2020-07-26T06:39:30.000Z | 2020-07-26T06:39:30.000Z | #ifndef _NET_IP_ENCODING_H
#define _NET_IP_ENCODING_H
#include <cstdint>
#include <vector>
#include "absl/types/span.h"
#include "net/asio.h"
namespace net {
void encode(const address &address, std::vector<uint8_t> &bytes);
void encode(const address_v4 &address, std::vector<uint8_t> &bytes);
void encode(const address_v6 &address, std::vector<uint8_t> &bytes);
bool decode(absl::Span<const uint8_t> bytes, address &address);
bool decode(absl::Span<const uint8_t> bytes, address_v4 &address);
bool decode(absl::Span<const uint8_t> bytes, address_v6 &address);
} // namespace net
#endif // _NET_IP_ENCODING_H
| 29.285714 | 68 | 0.75935 | [
"vector"
] |
50ebaf866cbfb69723bf3a2da22b1d7adf386e31 | 3,509 | h | C | peridot/bin/module_resolver/local_module_resolver.h | zhangpf/fuchsia-rs | 903568f28ddf45f09157ead36d61b50322c9cf49 | [
"BSD-3-Clause"
] | 1 | 2019-10-09T10:50:57.000Z | 2019-10-09T10:50:57.000Z | peridot/bin/module_resolver/local_module_resolver.h | zhangpf/fuchsia-rs | 903568f28ddf45f09157ead36d61b50322c9cf49 | [
"BSD-3-Clause"
] | 5 | 2020-09-06T09:02:06.000Z | 2022-03-02T04:44:22.000Z | peridot/bin/module_resolver/local_module_resolver.h | ZVNexus/fuchsia | c5610ad15208208c98693618a79c705af935270c | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2017 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef PERIDOT_BIN_MODULE_RESOLVER_LOCAL_MODULE_RESOLVER_H_
#define PERIDOT_BIN_MODULE_RESOLVER_LOCAL_MODULE_RESOLVER_H_
#include <functional>
#include <memory>
#include <set>
#include <vector>
#include <fuchsia/modular/cpp/fidl.h>
#include <lib/async/cpp/operation.h>
#include <lib/fidl/cpp/binding_set.h>
#include <src/lib/fxl/memory/weak_ptr.h>
#include "peridot/lib/module_manifest_source/module_manifest_source.h"
namespace modular {
class LocalModuleResolver : fuchsia::modular::ModuleResolver {
public:
LocalModuleResolver();
~LocalModuleResolver() override;
// Adds a source of Module manifests to index. It is not allowed to call
// AddSource() after Connect(). |name| must be unique.
void AddSource(std::string name, std::unique_ptr<ModuleManifestSource> repo);
void Connect(
fidl::InterfaceRequest<fuchsia::modular::ModuleResolver> request);
// |ModuleResolver|
void FindModules(fuchsia::modular::FindModulesQuery query,
FindModulesCallback callback) override;
private:
class FindModulesCall;
class FindModulesByTypesCall;
using ModuleUri = std::string;
using RepoSource = std::string;
// We use the module URI to identify the module manifest.
using ManifestId = std::tuple<RepoSource, ModuleUri>;
using ParameterName = std::string;
using ParameterType = std::string;
using Action = std::string;
std::set<ManifestId> FindHandlers(ModuleUri handler);
void OnSourceIdle(const std::string& source_name);
void OnNewManifestEntry(const std::string& source_name, std::string id_in,
fuchsia::modular::ModuleManifest new_entry);
void OnRemoveManifestEntry(const std::string& source_name, std::string id_in);
void PeriodicCheckIfSourcesAreReady();
bool AllSourcesAreReady() const {
return ready_sources_.size() == sources_.size();
}
// TODO(thatguy): At some point, factor the index functions out of
// LocalModuleResolver so that they can be re-used by the general all-modules
// Ask handler.
std::map<std::string, std::unique_ptr<ModuleManifestSource>> sources_;
// Set of sources that have told us they are idle, meaning they have
// sent us all manifests they knew about at construction time.
std::set<std::string> ready_sources_;
// Map of module manifest ID -> module manifest.
using ManifestMap = std::map<ManifestId, fuchsia::modular::ModuleManifest>;
ManifestMap manifests_;
// action -> key in |manifests_|
std::map<Action, std::set<ManifestId>> action_to_manifests_;
// (parameter type, parameter name) -> key in |manifests_|
std::map<std::pair<ParameterType, ParameterName>, std::set<ManifestId>>
parameter_type_and_name_to_manifests_;
// (parameter type) -> keys in |manifests_|.
std::map<ParameterType, std::set<ManifestId>> parameter_type_to_manifests_;
fidl::BindingSet<fuchsia::modular::ModuleResolver> bindings_;
// These are buffered until AllSourcesAreReady() == true.
std::vector<fidl::InterfaceRequest<fuchsia::modular::ModuleResolver>>
pending_bindings_;
bool already_checking_if_sources_are_ready_;
OperationCollection operations_;
fxl::WeakPtrFactory<LocalModuleResolver> weak_factory_;
FXL_DISALLOW_COPY_AND_ASSIGN(LocalModuleResolver);
};
} // namespace modular
#endif // PERIDOT_BIN_MODULE_RESOLVER_LOCAL_MODULE_RESOLVER_H_
| 35.444444 | 80 | 0.753491 | [
"vector"
] |
50ee27bbd04ec288341df8d8401a02336df9c21c | 13,376 | c | C | drivers/iommu/ioasid.c | jainsakshi2395/linux | 7ccb860232bb83fb60cd6bcf5aaf0c008d903acb | [
"Linux-OpenIB"
] | 5 | 2020-07-08T01:35:16.000Z | 2021-04-12T16:35:29.000Z | drivers/iommu/ioasid.c | jainsakshi2395/linux | 7ccb860232bb83fb60cd6bcf5aaf0c008d903acb | [
"Linux-OpenIB"
] | 1 | 2021-01-27T01:29:47.000Z | 2021-01-27T01:29:47.000Z | drivers/iommu/ioasid.c | jainsakshi2395/linux | 7ccb860232bb83fb60cd6bcf5aaf0c008d903acb | [
"Linux-OpenIB"
] | null | null | null | // SPDX-License-Identifier: GPL-2.0
/*
* I/O Address Space ID allocator. There is one global IOASID space, split into
* subsets. Users create a subset with DECLARE_IOASID_SET, then allocate and
* free IOASIDs with ioasid_alloc and ioasid_put.
*/
#include <linux/ioasid.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/xarray.h>
struct ioasid_data {
ioasid_t id;
struct ioasid_set *set;
void *private;
struct rcu_head rcu;
refcount_t refs;
};
/*
* struct ioasid_allocator_data - Internal data structure to hold information
* about an allocator. There are two types of allocators:
*
* - Default allocator always has its own XArray to track the IOASIDs allocated.
* - Custom allocators may share allocation helpers with different private data.
* Custom allocators that share the same helper functions also share the same
* XArray.
* Rules:
* 1. Default allocator is always available, not dynamically registered. This is
* to prevent race conditions with early boot code that want to register
* custom allocators or allocate IOASIDs.
* 2. Custom allocators take precedence over the default allocator.
* 3. When all custom allocators sharing the same helper functions are
* unregistered (e.g. due to hotplug), all outstanding IOASIDs must be
* freed. Otherwise, outstanding IOASIDs will be lost and orphaned.
* 4. When switching between custom allocators sharing the same helper
* functions, outstanding IOASIDs are preserved.
* 5. When switching between custom allocator and default allocator, all IOASIDs
* must be freed to ensure unadulterated space for the new allocator.
*
* @ops: allocator helper functions and its data
* @list: registered custom allocators
* @slist: allocators share the same ops but different data
* @flags: attributes of the allocator
* @xa: xarray holds the IOASID space
* @rcu: used for kfree_rcu when unregistering allocator
*/
struct ioasid_allocator_data {
struct ioasid_allocator_ops *ops;
struct list_head list;
struct list_head slist;
#define IOASID_ALLOCATOR_CUSTOM BIT(0) /* Needs framework to track results */
unsigned long flags;
struct xarray xa;
struct rcu_head rcu;
};
static DEFINE_SPINLOCK(ioasid_allocator_lock);
static LIST_HEAD(allocators_list);
static ioasid_t default_alloc(ioasid_t min, ioasid_t max, void *opaque);
static void default_free(ioasid_t ioasid, void *opaque);
static struct ioasid_allocator_ops default_ops = {
.alloc = default_alloc,
.free = default_free,
};
static struct ioasid_allocator_data default_allocator = {
.ops = &default_ops,
.flags = 0,
.xa = XARRAY_INIT(ioasid_xa, XA_FLAGS_ALLOC),
};
static struct ioasid_allocator_data *active_allocator = &default_allocator;
static ioasid_t default_alloc(ioasid_t min, ioasid_t max, void *opaque)
{
ioasid_t id;
if (xa_alloc(&default_allocator.xa, &id, opaque, XA_LIMIT(min, max), GFP_ATOMIC)) {
pr_err("Failed to alloc ioasid from %d to %d\n", min, max);
return INVALID_IOASID;
}
return id;
}
static void default_free(ioasid_t ioasid, void *opaque)
{
struct ioasid_data *ioasid_data;
ioasid_data = xa_erase(&default_allocator.xa, ioasid);
kfree_rcu(ioasid_data, rcu);
}
/* Allocate and initialize a new custom allocator with its helper functions */
static struct ioasid_allocator_data *ioasid_alloc_allocator(struct ioasid_allocator_ops *ops)
{
struct ioasid_allocator_data *ia_data;
ia_data = kzalloc(sizeof(*ia_data), GFP_ATOMIC);
if (!ia_data)
return NULL;
xa_init_flags(&ia_data->xa, XA_FLAGS_ALLOC);
INIT_LIST_HEAD(&ia_data->slist);
ia_data->flags |= IOASID_ALLOCATOR_CUSTOM;
ia_data->ops = ops;
/* For tracking custom allocators that share the same ops */
list_add_tail(&ops->list, &ia_data->slist);
return ia_data;
}
static bool use_same_ops(struct ioasid_allocator_ops *a, struct ioasid_allocator_ops *b)
{
return (a->free == b->free) && (a->alloc == b->alloc);
}
/**
* ioasid_register_allocator - register a custom allocator
* @ops: the custom allocator ops to be registered
*
* Custom allocators take precedence over the default xarray based allocator.
* Private data associated with the IOASID allocated by the custom allocators
* are managed by IOASID framework similar to data stored in xa by default
* allocator.
*
* There can be multiple allocators registered but only one is active. In case
* of runtime removal of a custom allocator, the next one is activated based
* on the registration ordering.
*
* Multiple allocators can share the same alloc() function, in this case the
* IOASID space is shared.
*/
int ioasid_register_allocator(struct ioasid_allocator_ops *ops)
{
struct ioasid_allocator_data *ia_data;
struct ioasid_allocator_data *pallocator;
int ret = 0;
spin_lock(&ioasid_allocator_lock);
ia_data = ioasid_alloc_allocator(ops);
if (!ia_data) {
ret = -ENOMEM;
goto out_unlock;
}
/*
* No particular preference, we activate the first one and keep
* the later registered allocators in a list in case the first one gets
* removed due to hotplug.
*/
if (list_empty(&allocators_list)) {
WARN_ON(active_allocator != &default_allocator);
/* Use this new allocator if default is not active */
if (xa_empty(&active_allocator->xa)) {
rcu_assign_pointer(active_allocator, ia_data);
list_add_tail(&ia_data->list, &allocators_list);
goto out_unlock;
}
pr_warn("Default allocator active with outstanding IOASID\n");
ret = -EAGAIN;
goto out_free;
}
/* Check if the allocator is already registered */
list_for_each_entry(pallocator, &allocators_list, list) {
if (pallocator->ops == ops) {
pr_err("IOASID allocator already registered\n");
ret = -EEXIST;
goto out_free;
} else if (use_same_ops(pallocator->ops, ops)) {
/*
* If the new allocator shares the same ops,
* then they will share the same IOASID space.
* We should put them under the same xarray.
*/
list_add_tail(&ops->list, &pallocator->slist);
goto out_free;
}
}
list_add_tail(&ia_data->list, &allocators_list);
spin_unlock(&ioasid_allocator_lock);
return 0;
out_free:
kfree(ia_data);
out_unlock:
spin_unlock(&ioasid_allocator_lock);
return ret;
}
EXPORT_SYMBOL_GPL(ioasid_register_allocator);
/**
* ioasid_unregister_allocator - Remove a custom IOASID allocator ops
* @ops: the custom allocator to be removed
*
* Remove an allocator from the list, activate the next allocator in
* the order it was registered. Or revert to default allocator if all
* custom allocators are unregistered without outstanding IOASIDs.
*/
void ioasid_unregister_allocator(struct ioasid_allocator_ops *ops)
{
struct ioasid_allocator_data *pallocator;
struct ioasid_allocator_ops *sops;
spin_lock(&ioasid_allocator_lock);
if (list_empty(&allocators_list)) {
pr_warn("No custom IOASID allocators active!\n");
goto exit_unlock;
}
list_for_each_entry(pallocator, &allocators_list, list) {
if (!use_same_ops(pallocator->ops, ops))
continue;
if (list_is_singular(&pallocator->slist)) {
/* No shared helper functions */
list_del(&pallocator->list);
/*
* All IOASIDs should have been freed before
* the last allocator that shares the same ops
* is unregistered.
*/
WARN_ON(!xa_empty(&pallocator->xa));
if (list_empty(&allocators_list)) {
pr_info("No custom IOASID allocators, switch to default.\n");
rcu_assign_pointer(active_allocator, &default_allocator);
} else if (pallocator == active_allocator) {
rcu_assign_pointer(active_allocator,
list_first_entry(&allocators_list,
struct ioasid_allocator_data, list));
pr_info("IOASID allocator changed");
}
kfree_rcu(pallocator, rcu);
break;
}
/*
* Find the matching shared ops to delete,
* but keep outstanding IOASIDs
*/
list_for_each_entry(sops, &pallocator->slist, list) {
if (sops == ops) {
list_del(&ops->list);
break;
}
}
break;
}
exit_unlock:
spin_unlock(&ioasid_allocator_lock);
}
EXPORT_SYMBOL_GPL(ioasid_unregister_allocator);
/**
* ioasid_set_data - Set private data for an allocated ioasid
* @ioasid: the ID to set data
* @data: the private data
*
* For IOASID that is already allocated, private data can be set
* via this API. Future lookup can be done via ioasid_find.
*/
int ioasid_set_data(ioasid_t ioasid, void *data)
{
struct ioasid_data *ioasid_data;
int ret = 0;
spin_lock(&ioasid_allocator_lock);
ioasid_data = xa_load(&active_allocator->xa, ioasid);
if (ioasid_data)
rcu_assign_pointer(ioasid_data->private, data);
else
ret = -ENOENT;
spin_unlock(&ioasid_allocator_lock);
/*
* Wait for readers to stop accessing the old private data, so the
* caller can free it.
*/
if (!ret)
synchronize_rcu();
return ret;
}
EXPORT_SYMBOL_GPL(ioasid_set_data);
/**
* ioasid_alloc - Allocate an IOASID
* @set: the IOASID set
* @min: the minimum ID (inclusive)
* @max: the maximum ID (inclusive)
* @private: data private to the caller
*
* Allocate an ID between @min and @max. The @private pointer is stored
* internally and can be retrieved with ioasid_find().
*
* Return: the allocated ID on success, or %INVALID_IOASID on failure.
*/
ioasid_t ioasid_alloc(struct ioasid_set *set, ioasid_t min, ioasid_t max,
void *private)
{
struct ioasid_data *data;
void *adata;
ioasid_t id;
data = kzalloc(sizeof(*data), GFP_ATOMIC);
if (!data)
return INVALID_IOASID;
data->set = set;
data->private = private;
refcount_set(&data->refs, 1);
/*
* Custom allocator needs allocator data to perform platform specific
* operations.
*/
spin_lock(&ioasid_allocator_lock);
adata = active_allocator->flags & IOASID_ALLOCATOR_CUSTOM ? active_allocator->ops->pdata : data;
id = active_allocator->ops->alloc(min, max, adata);
if (id == INVALID_IOASID) {
pr_err("Failed ASID allocation %lu\n", active_allocator->flags);
goto exit_free;
}
if ((active_allocator->flags & IOASID_ALLOCATOR_CUSTOM) &&
xa_alloc(&active_allocator->xa, &id, data, XA_LIMIT(id, id), GFP_ATOMIC)) {
/* Custom allocator needs framework to store and track allocation results */
pr_err("Failed to alloc ioasid from %d\n", id);
active_allocator->ops->free(id, active_allocator->ops->pdata);
goto exit_free;
}
data->id = id;
spin_unlock(&ioasid_allocator_lock);
return id;
exit_free:
spin_unlock(&ioasid_allocator_lock);
kfree(data);
return INVALID_IOASID;
}
EXPORT_SYMBOL_GPL(ioasid_alloc);
/**
* ioasid_get - obtain a reference to the IOASID
*/
void ioasid_get(ioasid_t ioasid)
{
struct ioasid_data *ioasid_data;
spin_lock(&ioasid_allocator_lock);
ioasid_data = xa_load(&active_allocator->xa, ioasid);
if (ioasid_data)
refcount_inc(&ioasid_data->refs);
else
WARN_ON(1);
spin_unlock(&ioasid_allocator_lock);
}
EXPORT_SYMBOL_GPL(ioasid_get);
/**
* ioasid_put - Release a reference to an ioasid
* @ioasid: the ID to remove
*
* Put a reference to the IOASID, free it when the number of references drops to
* zero.
*
* Return: %true if the IOASID was freed, %false otherwise.
*/
bool ioasid_put(ioasid_t ioasid)
{
bool free = false;
struct ioasid_data *ioasid_data;
spin_lock(&ioasid_allocator_lock);
ioasid_data = xa_load(&active_allocator->xa, ioasid);
if (!ioasid_data) {
pr_err("Trying to free unknown IOASID %u\n", ioasid);
goto exit_unlock;
}
free = refcount_dec_and_test(&ioasid_data->refs);
if (!free)
goto exit_unlock;
active_allocator->ops->free(ioasid, active_allocator->ops->pdata);
/* Custom allocator needs additional steps to free the xa element */
if (active_allocator->flags & IOASID_ALLOCATOR_CUSTOM) {
ioasid_data = xa_erase(&active_allocator->xa, ioasid);
kfree_rcu(ioasid_data, rcu);
}
exit_unlock:
spin_unlock(&ioasid_allocator_lock);
return free;
}
EXPORT_SYMBOL_GPL(ioasid_put);
/**
* ioasid_find - Find IOASID data
* @set: the IOASID set
* @ioasid: the IOASID to find
* @getter: function to call on the found object
*
* The optional getter function allows to take a reference to the found object
* under the rcu lock. The function can also check if the object is still valid:
* if @getter returns false, then the object is invalid and NULL is returned.
*
* If the IOASID exists, return the private pointer passed to ioasid_alloc.
* Private data can be NULL if not set. Return an error if the IOASID is not
* found, or if @set is not NULL and the IOASID does not belong to the set.
*/
void *ioasid_find(struct ioasid_set *set, ioasid_t ioasid,
bool (*getter)(void *))
{
void *priv;
struct ioasid_data *ioasid_data;
struct ioasid_allocator_data *idata;
rcu_read_lock();
idata = rcu_dereference(active_allocator);
ioasid_data = xa_load(&idata->xa, ioasid);
if (!ioasid_data) {
priv = ERR_PTR(-ENOENT);
goto unlock;
}
if (set && ioasid_data->set != set) {
/* data found but does not belong to the set */
priv = ERR_PTR(-EACCES);
goto unlock;
}
/* Now IOASID and its set is verified, we can return the private data */
priv = rcu_dereference(ioasid_data->private);
if (getter && !getter(priv))
priv = NULL;
unlock:
rcu_read_unlock();
return priv;
}
EXPORT_SYMBOL_GPL(ioasid_find);
MODULE_AUTHOR("Jean-Philippe Brucker <jean-philippe.brucker@arm.com>");
MODULE_AUTHOR("Jacob Pan <jacob.jun.pan@linux.intel.com>");
MODULE_DESCRIPTION("IO Address Space ID (IOASID) allocator");
MODULE_LICENSE("GPL");
| 29.527594 | 97 | 0.737141 | [
"object"
] |
50fd268ab54a49d9ce9a5bc3a84486ef90457b97 | 1,848 | h | C | public/src/header/assimp.h | aliabbas299792/wasm-ball-game | 3be314aa0b702300db0a303c402433047380506d | [
"MIT"
] | 1 | 2022-03-28T02:24:29.000Z | 2022-03-28T02:24:29.000Z | public/src/header/assimp.h | aliabbas299792/wasm-ball-game | 3be314aa0b702300db0a303c402433047380506d | [
"MIT"
] | null | null | null | public/src/header/assimp.h | aliabbas299792/wasm-ball-game | 3be314aa0b702300db0a303c402433047380506d | [
"MIT"
] | null | null | null | #ifndef ASSIMP
#define ASSIMP
#include "header/shader.h"
#include <vector>
#include <glm/glm.hpp>
#include <emscripten.h>
#include <assimp/Importer.hpp>
#include <assimp/scene.h>
#include <assimp/postprocess.h>
#include "ecs/ecs.h"
struct vertex {
glm::vec3 position;
glm::vec3 normal;
glm::vec2 texCoords;
};
struct texture {
unsigned int id;
std::string type; //diffuse/specular type
std::string path; //store the path to compare with other textures and prevent duplicates
};
class mesh{
public:
//mesh data
std::vector<vertex> vertices;
std::vector<unsigned int> indices;
std::vector<texture> textures;
mesh(std::vector<vertex> vertices, std::vector<unsigned int> indices, std::vector<texture> textures);
void draw();
~mesh(){
vertices.clear();
indices.clear();
textures.clear();
}
void setInstancing(const std::array<glm::mat4, MAX_ENTITIES> *transformationMatrices, unsigned int maxIndex);
private:
unsigned int VAO{}, VBO{}, EBO{}, instancedVBO = -1, instances = 0; //render data
void setupMesh();
};
class model{
private:
//model data
std::vector<texture> textures_loaded;
std::vector<mesh> meshes;
std::string directory;
int vertices = 0;
int indices = 0;
void loadModel(const std::string& path);
void processNode(aiNode *node, const aiScene *scene);
mesh processMesh(aiMesh *mesh, const aiScene *scene);
std::vector<texture> loadMaterialTextures(aiMaterial *mat, aiTextureType type, const std::string& typeName);
public:
model(const std::string& path = "");
void setInstancing(const std::array<glm::mat4, MAX_ENTITIES> *transformationMatrices, unsigned int maxIndex);
void draw();
~model(){
textures_loaded.clear();
meshes.clear();
directory = "";
}
};
#endif
| 24 | 113 | 0.672619 | [
"mesh",
"render",
"vector",
"model"
] |
dd017380c042c652b8b43f1a7a1972e4a7c9c5d4 | 598 | h | C | sail/csrc/core/kernels/kernel_utils.h | sail-ml/sail | e261ef22661aa267bcf32d1552be95d8b7255220 | [
"BSD-3-Clause"
] | 1 | 2021-04-28T16:29:02.000Z | 2021-04-28T16:29:02.000Z | sail/csrc/core/kernels/kernel_utils.h | sail-ml/sail | e261ef22661aa267bcf32d1552be95d8b7255220 | [
"BSD-3-Clause"
] | 56 | 2021-04-28T16:39:05.000Z | 2021-07-29T01:13:25.000Z | sail/csrc/core/kernels/kernel_utils.h | sail-ml/sail | e261ef22661aa267bcf32d1552be95d8b7255220 | [
"BSD-3-Clause"
] | null | null | null | // allow-no-source
#pragma once
#include <immintrin.h>
#include <omp.h>
#include <algorithm>
#include <vector>
#include "Tensor.h"
#include "dtypes.h"
#include "utils.h"
inline Dtype avx_support[3] = {Dtype::sInt32, Dtype::sFloat32, Dtype::sFloat64};
template <std::size_t N, typename T, typename... types>
struct get_Nth_type {
using type = typename get_Nth_type<N - 1, types...>::type;
};
template <typename T, typename... types>
struct get_Nth_type<0, T, types...> {
using type = T;
};
template <std::size_t N, typename... Args>
using get = typename get_Nth_type<N, Args...>::type;
| 23 | 80 | 0.687291 | [
"vector"
] |
dd032a2b041ce7ac8be7c7cbd494042197737c43 | 877 | h | C | lib/models/Leaderboard.h | gamespice/gamespicex | 512bb90de1b831d9db05e81ec0a7f1a112ea6cb5 | [
"MIT"
] | 3 | 2015-05-18T11:27:15.000Z | 2017-01-06T12:04:18.000Z | lib/models/Leaderboard.h | gamespice/gamespicex | 512bb90de1b831d9db05e81ec0a7f1a112ea6cb5 | [
"MIT"
] | null | null | null | lib/models/Leaderboard.h | gamespice/gamespicex | 512bb90de1b831d9db05e81ec0a7f1a112ea6cb5 | [
"MIT"
] | null | null | null | #ifndef LEADERBOARD_H_
#define LEADERBOARD_H_
#include <string>
#include "../JSON.h"
#include <vector>
namespace gamespice {
class HighScore {
public:
HighScore(int score);
static HighScore fromJSON(JSON json);
const int getScore();
virtual ~HighScore();
private:
int score;
};
class Score {
public:
Score(int score);
static Score fromJSON(JSON json);
const int getScore();
const int getPlace();
const std::string getUsername();
const std::string getUserId();
virtual ~Score();
private:
int score;std::string userId;
int place;std::string username;
};
class Leaderboard {
public:
Leaderboard(const std::vector<Score> scores);
static Leaderboard fromJSON(JSON json);
const std::vector<Score> getScores();
virtual ~Leaderboard();
private:
std::string id_;std::vector<Score> scores;
};
} /* namespace gamespice */
#endif /* LEADERBOARD_H_ */
| 14.864407 | 46 | 0.714937 | [
"vector"
] |
dd03eb82b93f2ad4f47205b36842f291574b8b27 | 233 | h | C | JackPi/header/micHandler.h | enrico-car/JackPi | 4597ed1489cdcbb5f49d8c2a1ed3447ae9afded1 | [
"MIT"
] | null | null | null | JackPi/header/micHandler.h | enrico-car/JackPi | 4597ed1489cdcbb5f49d8c2a1ed3447ae9afded1 | [
"MIT"
] | null | null | null | JackPi/header/micHandler.h | enrico-car/JackPi | 4597ed1489cdcbb5f49d8c2a1ed3447ae9afded1 | [
"MIT"
] | null | null | null | #pragma once
#include <iostream>
#include <pigpio.h>
#include <functional>
#include <vector>
class MicHandler {
private:
int pin;
std::vector<std::function<void()>> callOnHigh;
public:
MicHandler(int _pin);
int getPin();
};
| 13.705882 | 47 | 0.699571 | [
"vector"
] |
dd06ad5b4fa74cb32c9e8d7ab07ec9d86a4d6c1b | 41,149 | h | C | svntrunk/src/BlueMatter/blrudp/blrudp/blrudp.h | Bhaskers-Blu-Org1/BlueMatter | 1ab2c41af870c19e2e1b1095edd1d5c85eeb9b5e | [
"BSD-2-Clause"
] | 7 | 2020-02-25T15:46:18.000Z | 2022-02-25T07:04:47.000Z | svntrunk/src/BlueMatter/blrudp/blrudp/blrudp.h | IBM/BlueMatter | 5243c0ef119e599fc3e9b7c4213ecfe837de59f3 | [
"BSD-2-Clause"
] | null | null | null | svntrunk/src/BlueMatter/blrudp/blrudp/blrudp.h | IBM/BlueMatter | 5243c0ef119e599fc3e9b7c4213ecfe837de59f3 | [
"BSD-2-Clause"
] | 5 | 2019-06-06T16:30:21.000Z | 2020-11-16T19:43:01.000Z | /* Copyright 2001, 2019 IBM Corporation
*
* 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.
*
* 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.
*/
#ifndef _BLRUDP_H_
#define _BLRUDP_H_
/////////////////////////////////////////////////////////////////////////////////////////
//
//
// This File contains the definition and document of the Blue Light Reliable UDP
// library (BlRudp).
//
// The BlRudp library implements the BlRudp protocol. This protocol is designed
// to provide high bandwidth utilization of either a 100Mb or 1000Mb link between
// two points. It is designed to run on top of UDP.
//
// For a complete description of this protocol please see:
// "Blue Light Reliable UDP Network Protocol_e.doc"
//
//
// Functions defined in this module:
//
// BlrudpNew
// BlrudpDelete
// BlrudpSetOptions
// BlrudpGetOptions
// BlrudpSetOptionLong
// BlrudpGetOptionLong
// BlrudpGetPollList
// BlrudpGetSelectSet
// BlrudpRun
// BlrudpListen
// BlrudpAccept
// BlrudpReject
// BlrudpUnlisten
// BlrudpConnect
// BlrudpDisconnect
// BlrudpGetContextState
// BlrudpGetContextAddr
// BlrudpGetContextAddrStr
// BlrudpGetStatus
// BlrudpReqDiagInfo
// BlrudpGetDiagInfo
// BlrudpRecvFromContext
// BlrudpRecvBufferFromContext
// BlrudpReleaseRecvBuffer
// BlrudpSendTo
// BlrudpBufferSendToContext
// BlrudpGetSendBuffer
// BlrudpGetMaxPayloadLen
// BlrudpGetMaxBufferSize
// BlrudpGetDataSize
// BlrudpGetDataPointer
// BlrudpShutdown
//
//
// Parameter Type ID's.
// These ID's are use to override default paramters for an entire instance of
// the library or just an individual connection.
//
//
#include "hostcfg.h"
#if defined(WIN32) || defined(CYGWIN)
#include <winsock.h>
#endif
#if HAVE_STDINT_H
#include <stdint.h>
#elif USE_GDB_STDINT_H
#include "gdb_stdint.h"
#endif
#if HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#endif
#if HAVE_SYS_POLL_H
#include <sys/poll.h>
#endif
#ifdef __cplusplus
extern "C" {
#endif
#if HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#endif
#if HAVE_SYS_POLL_H
#include <sys/poll.h>
#endif
#if HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
typedef void *BLRUDP_HANDLE; // generic handle used in the BlRudp library to
// refer to opaque objects.
typedef void *BLRUDP_HCONTEXT; // handle to an opaque context object.
typedef void *BLRUDP_HIOBUFFER; // handle to an io buffer.
//
// Make sure we have defined these types....
// but don't reqire the entire stdint.h or gdb_stdint.h files.
#if ((!defined(_STDINT_H)) && (!defined(_LINUX_TYPES_H)) && (!defined (_H_INTTYPES)) )
#ifdef WIN32
typedef __int64 int64_t;
typedef unsigned __int64 uint64_t;
#else
typedef long long int64_t;
typedef unsigned long long uint64_t;
#endif
#endif
////////////////////////////////////////////////////////////////
// published diagnostic information...
//
typedef struct {
int bDiagValid; // diagnostic information valid.
uint64_t llNumRetrans; // total number of retransmissions.
uint64_t llDataXmit; // amount of data transmitted
uint64_t llDataRecv; // amount of data received.
} BLRUDP_DIAG;
/////////////////////////////////////////////////////////////////////////////////////////
// Callback function prototypes.
//
////////////////////////////////////////////////////////////////////////////////
typedef void (* PFN_BLRUDP_CONTEXT_RECV)(BLRUDP_HCONTEXT hContext,
void *pUserData);
//
// Notification to the client that there are packets waiting to be received
// in the receive queue for the context hContext.
//
// inputs:
// hContext -- context that has data to receive.
// pUserData -- pointer to user data passed in when the callback was setup.
// outputs:
// none.
///////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
typedef void (* PFN_BLRUDP_CONTEXT_CHANGED)(BLRUDP_HCONTEXT hContext,
int nOldState,
int nNewState,
int nBlError,
void *pUserData);
//
// Callback indicating the state of the indicated context has changed.
//
// inputs:
// nOldState -- the previous state of the context.
// nNewState -- the new state of the context.
// nBlError -- bluelight error condition.
// pUserData -- pointer to user data passed in when the callback was setup.
// outputs:
// none.
//
// NOTES:
// Most all state transitions will report Blerror == BLERR_SUCCESS however,
// some transitions to the CLOSED state are due to error conditions and
// these are reported by the nBlError variable.
//
//
////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
typedef void (* PFN_BLRUDP_LISTEN_CONNECT_REQ)(BLRUDP_HCONTEXT hListenContext,
BLRUDP_HCONTEXT hNewContext,
unsigned long nAddr,
unsigned short nPort,
void *pUserData);
//
// Callback indicating the listening port has an incomming connection
// reqest that the client application has to either accept or reject.
//
// The callback either calls BlrudpAccept or BlrudpReject
// to accept or reject the conversation.
//
// If neither accept or reject is called on the context during this call
// then Reject is assumed.
//
// inputs:
// hContext -- listening context
// hNewContext -- new incomming context.
// nAddr -- remote address of the incomming connection.
// nRemotePort -- remote port of the incomming connection.
// pUserData -- pointer to user data passed in when the callback was setup.
// outputs:
// A BLRUDP_CONTEXT_CHANGED callback will be called
// when a new Active context is created and placed into
// the ...CONNECTING state.
//
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
typedef void (* PFN_BLRUDP_SEND_BUFFER_DONE)(BLRUDP_HCONTEXT hContext,
unsigned long ulSendBufferID,
void *pUserData);
//
// Callback indicating that a buffer sent by BlrudpSend...
// has been sent and acknowledged. The buffer has actually been returned
// to the free pool of send buffers.
//
// inputs:
// hContext -- context this buffer corresponds to.
// ulSendBufferID -- identifier passed into the BlrudpSend.. function.
// pUserData -- pointer to user data passed in when the callback was setup.
// outputs:
// none.
//
/////////////////////////////////////////////////////////////////////////
enum {
BLRUDP_WINDOW_SIZE = 0, // The maximum amount of data that
// a receiver can receive without sending an acknowledgement
// size is in bytes, rounded up to the nearest MTU size.
BLRUDP_RETRY_COUNT = 1, // Maximum number of retransmissions allowed before a
// connection is declared dead.
BLRUDP_TRANSMIT_RATE = 2, // The maximum rate between bursts of packets that data can be
// transmitted before having to wait. This is used for rate control.
// Defaults to unlimited.
BLRUDP_BURST_SIZE = 3, // Maximum number of packets that can be sent in a single burst
// if the Valid only if the transmit rate is set.
BLRUDP_DEFAULT_SRC_PORT = 4, // Default Source port to use for all connections.
BLRUDP_SOURCE_IP_ADDR = 5, // Default source IP address, or possible name of the NIC card
// or NIC number indicating which NIC card should be used.
// Not sure of the best way to do this one.
BLRUDP_INITIAL_ROUND_TRIP_DELAY = 6, // Initial estimated round trip delay when starting the connection.
// Initial timeout values will be selected by this.
// After the connection is running, it will be actually measured.
BLRUDP_MAXIMUM_TIME_TO_LIVE = 7, // Maximum time a packet can live on the network.
// Determines how long a given connection context stays in
// the zombie state.
BLRUDP_IN_ORDER_DELIVERY = 8, // When set to true, this client requires in order deliver,
// false, then packets may be delivered out of order.
BLRUDP_MTU_SIZE = 9, // Maximum MTU size to use. This will probably only be useful
// if we can support Jumbo packets and which to tune the protocol
// by using smaller packet sizes.
BLRUDP_DEDICATED_BUFFERS = 10, // If true then each connection context gets its own
// transmit and receive buffers to work with. If false,
// then they share a common buffer pool.
BLRUDP_USE_RAW_SOCKETS = 11, // If true then the RlRudp library will use the RAW sockets
// interface, where it fills out the UDP header.
// This can further reduce the data copying that is required.
BLRUDP_CHECKSUM = 12, // Checksum the packets. This is a redundant checksum on
// all the packet traffic which is used to validate the contents
// and make sure that the underlying protocol stack did
// not screw the data up.
BLRUDP_APPLEVEL_FLOW_CNTRL = 13, // if this value is non zero then we are using application level
// flow control. The receive sequence number does not advance
// until the application receives and releases the data.
COMMA_DUMMY
};
//
// context states.
//
enum {
BLRUDP_STATE_CLOSED = 0, // state of this context is closed.
BLRUDP_STATE_LISTENING = 1, // state of this context is listening.
BLRUDP_STATE_CONNECTING = 2 , // context is in the process of connecting to the remote end.
BLRUDP_STATE_CONNECT = 3, // context is connected, sends are receives are valid.
BLRUDP_STATE_CLOSING = 4, // the context is closing down, wont' accept any more writes,
// but you can still read.
BLRUD_MAX_STATE = 5
};
//
// Paramter passing structure.
//
// An array of these are used to override default paramters for Blue Light RUDP functions.
//
typedef struct {
int nOptionId; // Option identifer
union {
long lValue; // Option value integer value.
unsigned long ulValue;
char *pszValue; // Option string pointer value.
} v;
} BLRUDP_OPTIONS;
////////////////////////////////////////////////////////////////////////
int BlrudpNew(BLRUDP_HANDLE *phBlrudp,
int nNumOptions,
BLRUDP_OPTIONS pOptions[]);
//
// Create a new Blue Light RUDP manager.
//
// inputs:
// *phBlrudp -- pointer to where to stuff the handle for the instance to this
// library.
// nNumOptions -- number of paramters that we wish to override the default values for.
// pOptions -- pointer to list of parameters.
//
// outputs
// returns BLERR_SUCCESS if successful,
// error codes TBD..
// pHandle Pointer to where to stuff the Handle to the newly created Blrudp library.
////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
int BlrudpDelete(BLRUDP_HANDLE hBlrudp);
//
// Delete the Blue Light RUDP manager created by BlRudpNew.
//
// inputs:
// hBlrudp -- handle to the instance to delete.
//
// outputs:
// return BLERR_SUCCESS if successful.
//
///////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
void BlrudpShutdown();
//
// Call this when the program shuts down. This will go through all the outstanding
// Blrudp objets and attempt close any outstanding socket handles associated
// with it.
//
// inputs:
// none.
// outputs:
// none.
///////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
int BlrudpSetOptions(BLRUDP_HANDLE hBlrudp,
int nNumOptions,
BLRUDP_OPTIONS pOptions[]);
//
// set the connection options associated with this UDP manager.
// Options apply to all subsequent connections managed by this manager.
//
// inputs:
// hBlrudp -- instance to the instance to apply these options to.
// nNumOptions -- Number of paramters in the parameter list.
// pOptions -- Paramter list containing the parameters the client
// application wishes to override.
// outputs:
// returns BLERR_SUCCESS if successful,
// error codes TBD..
//////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
int BlrudpGetOptions(BLRUDP_HANDLE hBlrudp,
int nNumOptions,
BLRUDP_OPTIONS pOptions[]);
//
// Retrieve the current option values.
//
// inputs:
// hBlrudp -- instance to the instance to apply these options to.
// nNumOptions -- Number of paramters in the parameter list.
// pOptions -- Paramter list containing the parameters the client
// application wishes to query.
// outputs:
// returns BLERR_SUCCESS if successful,
// error codes TBD..
//
// NOTE:
// Pointer values returned belong to the Blrudp library.
// DON'T MODIFY THEM.
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
int BlrudpSetOptionLong(BLRUDP_HANDLE hBlrudp,
int nOptionID,
long lValue);
//
// Set a single option (long values only).
//
// inputs:
// hBlrudp -- instance to the instance to apply these options to.
// nOptionID -- identifier of the option to return.
// lValue -- Value to set.
// outputs:
// returns BLERR_SUCCESS if successful.
//
////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
int BlrudpGetOptionLong(BLRUDP_HANDLE hBlrudp,
int nOptionId,
long *plValue);
//
// Retrieve a single option (long values only).
//
// inputs:
// hBlrudp -- instance to the instance to apply these options to.
// nOptionId -- identifier of the option to return.
// plValue -- place to stuff the option value.
// outputs:
// returns BLERR_SUCCESS if successful.
// *plValue -- Value returned by the option.
//
////////////////////////////////////////////////////////////////////////
#if (!defined(BLHPK)) && (!defined(WIN32))
//////////////////////////////////////////////////////////////////////
int BlrudpGetPollList(BLRUDP_HANDLE hBlrudp,
unsigned int nMaxPollDescriptors,
unsigned int *pnNumPollDescriptors,
struct pollfd *pPollFd,
struct timeval * pTimeout);
//
// Return a list of pollfd structures containing and the timeout value to
// use if the calling function wishes to put the application to sleep until
// something interesting happens. Also returns the
// time the application wishes to wake up for a timeout.
//
// this allows the client application to go to sleep until something
// of interest in this library or something else the client is interested
// in pops up.
//
// inputs:
// hBlrudp -- instance to the instance to apply these options to.
// nMaxPollDescriptors -- maximum number of poll descriptors that there is
// space to return.
// pnNumPollDescriptors -- pointer to where to stuffnumber of poll
// descriptors actually in the list.
// pPollFd -- pointer to an array of pollfd structs where we can stuff
// the list.
// if (pPollFd == NULL, then just stuff the number of maximum descriptors
// we would have retruned...)
// pTimeout -- pointer where to stuff the current timeout value.
//
// outputs:
// return -- BLERR_SUCCESS if successful.
// BLERR_STRUCT_TOO_SMALL if pPollfd area is too small to contain the
// number of poll structs.
// pnNumPollDescriptors -- contains the number
// that would be returned if there was enough space.
// *pnNumPollDescriptors -- number of poll fd structs in the list.
// *pTimeout -- stuff the current timeout value.
//
//
//////////////////////////////////////////////////////////////////////////////////
#endif
#if (!defined(BLHPK))
////////////////////////////////////////////////////////////////////////////////
int BlrudpGetSelectSet(BLRUDP_HANDLE hBlrudp,
int *pnFds,
fd_set * pReadFds,
fd_set * pWriteFds,
fd_set * pExceptFds,
struct timeval * pTimeout);
//
// returns read, write and except File Descriptor sets which can then be used to call
// select and block the application until something interesting happens
// in the protocol.
//
// inputs:
// hBlrudp -- instance to the instance to apply these options to.
// pnFds -- pointer where to stuff the highest numbered descriptor in
// any of the FDsets.
// pReadFds -- pointer where to stuff the read file descriptor set.
// pWriteFds -- pointer where to stuff the write file descriptor set.
// pExceptFds -- pointer where to stuff the except file descriptor set.
// pTimeout -- pointer where to stuff the current timeout value.
// outputs:
// returns -- BLERR_SUCCESS if successful.
//
// pnFds -- the highest numbered descriptor in
// any of the FDsets.
// pReadFds -- the read file descriptor set.
// pWriteFds -- the write file descriptor set.
// pExceptFds -- the except file descriptor set.
// pTimeout -- stuff the current timeout value.
//
//////////////////////////////////////////////////////////////////////////////////
#endif
///////////////////////////////////////////////////////////////////////////////////
int BlrudpRun(BLRUDP_HANDLE hBlrudp,
int bSleep);
//
// Give the RudpManager time to run.
// The manager does all its work of receiving data here.
//
// If the client application has programmed any callbacks, they will be called
// from within this function so we don't have to worry about problems
// re-entrancy and interrupt contexts.
//
// inputs:
// hBlrudp -- instance to the instance to apply these options to.
// bSleep -- if TRUE the run command will sleep until there is
// something interesting to do. Incomming connection,
// timeout, receive data, send buffer done etc...
// outputs:
// returns -- BLERR_SUCCESS if successful.
////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
int BlrudpListen(BLRUDP_HANDLE hBlrudp,
BLRUDP_HCONTEXT *phContext,
unsigned long ulIpAddr,
unsigned short nPort,
int nNumOptions,
BLRUDP_OPTIONS pOptions[],
PFN_BLRUDP_LISTEN_CONNECT_REQ pfnListenConnectReq,
void *pUserData);
//
// Listen for incoming connections.
//
// This causes the Blrudp manager to listen for incomming connections on
// a designated port. Nothing in this computer can be listenening
// to this IP address and port combination.
//
// inputs:
// hBlrudp -- instance to the instance to apply these options to.
// phContext -- pointer to where to stuff the context handle to refer
// to this listening context.
// ulIpAddr -- source IP address in network byte order.
// (same as returned by inet_addr()..)
// if zero, use the default ip Address.
// nPort -- port to listen for incomming connections on.
// if 0 then use the default port.
// nNumOptions -- number of paramters that we wish to override the default values for.
// pOptions -- pointer to list of parameters.
// pfnListenConnectReq -- callback to call when a connect request comes in.
// pUserData -- pointer to user data associated with this callback context.
//
// outputs:
// returns -- BLERR_SUCCESS if successful.
// *phContext -- newly created listening context.
////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
int BlrudpAccept(BLRUDP_HCONTEXT hContext,
PFN_BLRUDP_CONTEXT_CHANGED pfnContextChanged,
PFN_BLRUDP_CONTEXT_RECV pfnContextRecv,
PFN_BLRUDP_SEND_BUFFER_DONE pfnSendBufferDone,
void *pUserData);
//
// Accept the incomming connection.
//
// inputs:
// hContext -- handle to context that we are accepting.
// pfnContextChanged -- pointer to context changed callback function.
// pfnContextRecv -- pointer to context receive data callback function.
// pfnSndBufferdone -- pointer to Send buffer done callback function.
// outputs:
// returns -- BLERR_SUCCESS if successful.
//
///////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
int BlrudpReject(BLRUDP_HCONTEXT hContext);
//
// Reject the incomming connection.
//
// inputs:
// hContext -- handle to context that we are accepting.
// outputs:
// returns -- BLERR_SUCCESS if successful.
//
///////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
int BlrudpUnlisten(BLRUDP_HCONTEXT hContext);
//
// stop listening for incomming connections for the given listening context.
//
// inputs
// hContext -- hContext handle to listening context.
// outputs:
// returns -- BLERR_SUCCESS if successful.
////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
int BlrudpConnect(BLRUDP_HANDLE hBlrudp,
BLRUDP_HCONTEXT *phContext,
unsigned long ulIpSrcAddr,
unsigned short nSrcPort,
unsigned long ulIpDestAddr,
unsigned short nDestPort,
int nNumOptions,
BLRUDP_OPTIONS pOptions[],
PFN_BLRUDP_CONTEXT_CHANGED pfnContextChanged,
PFN_BLRUDP_CONTEXT_RECV pfnContextRecv,
PFN_BLRUDP_SEND_BUFFER_DONE pfnSendBufferDone,
void *pUserData);
//
// Request the Blrudp manager establish a connection with the remote SAP.
//
// inputs:
// hBlrudp -- instance to the instance to apply these options to.
// phContext -- pointer to where to stuff the new active context.
// ulIpSrcAddr -- source IP address in network byte order.
// (same as returned by inet_addr()..)
// if zero, use the default port.
// nSrcPort -- source port number to use, if zero use the default port.
// ulIpDestAddr -- destination IP address in network byte order.
// (same as returned by inet_addr()..)
// if zero, use the default port.
// nDestPort -- pointer to the port to use.
// nNumOptions -- number of paramters that we wish to override the default values for.
// pOptions -- pointer to list of parameters.
// pfnContextChanged -- pointer to context changed callback function.
// pfnContextRecv -- pointer to context receive data callback function.
// pfnSndBufferdone -- pointer to Send buffer done callback function.
// outputs:
// returns -- BLERR_SUCCESS if successful.
// phContext -- newly created active context (NOTE, this won't
// be in the state needed to actually send data
// until BlrudpRun has been called a few times.
//
/////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
int BlrudpDisconnect(BLRUDP_HCONTEXT hContext,
int bImmediate);
//
// disconnect from a connected context.
//
// inputs:
// hContext -- Context to disconnect from.
// bImmediate -- disconnect immediatly....
// outputs:
// returns -- BLERR_SUCCESS if successful.
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
int BlrudpGetContextState(BLRUDP_HCONTEXT hContext);
//
// Return the current state of the context.
//
// inptus:
// hContext -- context we are inetersted in.
// outputs:
// returns -- the current state of the context.
//
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
unsigned long BlrudpGetContextId(BLRUDP_HCONTEXT hContext);
//
// return an internal context identifier. This is an identifier
// which increments monotonically each time a new context is created.
// It is used to help identify each context for debugging purposeds.
//
// inputs:
// hContex -- the context handle we are interested in.
// outputs:
// returns -- the context Identifier.
//
/////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////
int BlrudpGetContextAddr(BLRUDP_HCONTEXT hContext,
unsigned long *pulSrcAddr,
unsigned short *pnSrcPort,
unsigned long *pulDestAddr,
unsigned short *pnDestPort);
//
// Retrieve the address and port number assocaited with this
// device.
//
// The context passed can be either an active or passive context.
// If a passive context is passed in the pulDestAddr and pulDestPort will
// be returned as zero...
//
//
// The address and port number are returned in the native byte order.
//
// inputs:
// hContext -- context containing the address to return.
// pulSrcAddr -- pointer to where to stuff the source adderss.
// pnSrcPort -- pointer to where to stuff the source port number.
// pulDestAddr -- pointer to where to stuff the destination adderss.
// pnDestPort -- pointer to where to stuff the destination port number.
// outputs:
// returns -- BLERR_SUCCESS if successful.
// *pulSrcAddr -- Address of port in native byte order.
// *pnSrcPort -- Port number.
// *pulDestAddr -- Address of port in native byte order.
// *pnDestPort -- Port number.
//
///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
int BlrudpGetStatus(BLRUDP_HCONTEXT hContext,
int *pnState,
int *pnRecvCount,
int *pnSendCount);
//
// Retrieve status about a given connection context.
//
// inputs:
// hContext -- Context to disconnect from.
// pnState -- pointer of where to stuff the state of the context.
// pnRecvCount -- pointer of where to stuff the number of receive buffers
// waiting to be received.
// pnSendCount -- pointer of where to stuff the number of send buffers
// available for sending data.
// outputs:
// returns -- BLERR_SUCCESS if successful.
// *pnState -- the state of the context.
// *pnRecvCount -- the number of receive buffers
// waiting to be received.
// *pnSendCount -- the number of send buffers
// available for sending data.
//
////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
int BlrudpReqDiagInfo(BLRUDP_HCONTEXT hContext);
//
// Request diagnostic information from the remote context.
//
// This causes a low priority diagnostic information message to be
// sent to the remote end. The client will be notified of the return
// message via callback.
//
// inputs:
// hContext -- Context to disconnect from.
// outputs:
// returns -- BLERR_SUCCESS if successful.
//
////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
int BlrudpGetDiagInfo(BLRUDP_HCONTEXT hContext,
int bRemote,
BLRUDP_DIAG *pDiag);
//
// Retrieve the current diagnostic information.
//
// this retrieves the local diagnostic information or the
// last received remote diagnostic information from the remote host.
//
// inputs:
// hContext -- Context to disconnect from.
// bRemote -- if TRUE, we are requesting the remote context information.
// if FALSE, we are requesting the local context information.
// pDiag -- poniter to where to stuff the diagnostic information.
// outputs:
// returns - BLERR_SUCCESS if successful.
// *pDiag -- diagnostic information...
//
////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
int BlrudpRecvFromContext(BLRUDP_HCONTEXT hContext,
unsigned char *pData,
int nBufferLen,
int *pnDataLen);
//
// Receive data from a specific context copying the data into the
// buffer provided by the client.
//
// Call this with a NULL pData pointer and a pnDataLen and
// this will return the length of the data in the buffer.
//
// inputs:
// hContext -- Context handle to receive data from.
// pData -- pointer to where to stuff the data.
// nBufferLen -- maximum length of the buffer, should the MTU size.
// pnDataLen -- pointer of where to stuff the actual data packet length.
//
// outputs:
// returns BLERR_SUCCESS if successful.
// BLERR_BLRUDP_NO_RECVDATA when there is no more data to receive.
// *pData -- data filled out.
// *pnDataLen -- length of the received data packet.
/////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
int BlrudpRecvBufferFromContext(BLRUDP_HCONTEXT hContext,
BLRUDP_HIOBUFFER *phIoBuffer,
unsigned char **ppData,
int *pnDataLen);
//
// Receive an entire receive buffer from any context.
//
// This allows the caller to receive the data without having to Blrudp
// manager do a copy operation. It meerely returns the buffer. When
// doing this kind of receive, the caller MUST release the buffer when
// it is done with it.
//
// inputs:
// hContext -- Context handle to receive data from.
// phIoBuffer -- pointer to where to stuff the io buffer handle
// *pData -- pointer to where to stuff the buffer pointer.
// pnDataLen -- pointer of where to stuff the actual data packet length.
//
// outputs:
// returns BLERR_SUCCESS if successful.
// *phIoBuffer -- io buffer handle.
// **pData -- pointer ot data buffer.
// *pnDataLen -- length of the received data packet.
/////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
int BlrudpReleaseRecvBuffer(BLRUDP_HIOBUFFER hIoBuffer);
//
// Release a buffer received with either BlrudpRecvBufferFromContext
//
// After this call the Blrudp manager is free to re-use this buffer. This
// is the signal that is used to signal the other end that the program
// is done using the buffer.
//
// inputs:
// hIoBuffer -- buffer handle.
// outputs:
// returns BLERR_SUCCESS if successful.
///////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
int BlrudpSendToContext(BLRUDP_HCONTEXT hContext,
const unsigned char *pData,
unsigned int nLen,
unsigned long ulSendBufferID);
//
//
// Send data to a connected context. This actually copies the data
// to a free send buffer. Note: there has to be a free send buffer to
// copy the data to for this to succeed. Buffers may be exausted because
// the receiving end has not acknowledged the date in the send pipe.
//
// inputs:
// hContext -- Context handle to receive data from.
// *pData -- pointer to where to stuff the buffer pointer.
// nLen -- lenght of the data to send.
// ulSendBufferID -- identification used to identify this
// send buffer when it has been transmmitted
// and acknowleged.
// outputs:
// returns BLERR_SUCCESS if successful.
//
///////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
int BlrudpBufferSendToContext(BLRUDP_HCONTEXT hContext,
BLRUDP_HIOBUFFER hIoBuffer,
unsigned int nLen,
unsigned long ulSendBufferID);
//
//
// Send a Data buffer to a connected context. The Blrudp manager
// takes responsibility for this buffer and when done it returns it
// to the free send buffer pool.
//
// inputs:
// hContext -- Context handle to receive data from.
// hIoBuffer -- handle of IO buffer to send...
// nLen -- lenght of the data to send.
// ulSendBufferID -- identification used to identify this
// send buffer when it has been transmmitted
// and acknowleged.
// outputs:
// returns BLERR_SUCCESS if successful.
//
///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
int BlrudpGetSendBuffer(BLRUDP_HCONTEXT hContext,
BLRUDP_HIOBUFFER *phIoBuffer,
unsigned char **ppDataBuffer,
unsigned long *pulBufferLen);
//
// Request a send buffer from the free buffer pool associated with this context.
// Each buffer will be MTU size large (see BlrudpGetMaxPayloadLen()... call).
// Buffers can also be queried for their data size and actuall size.
//
// These buffers remain under the control of the context. They are
// automatically freed when the context closes... Therefore, when a given
// context goes to the closed state, any send buffers the client has
// become invalid...
//
// inputs:
// hContext -- Context handle to receive data from.
// *ppDataBuffer -- to where to stuff the data buffer pointer.
// pnBufferLen -- pointer to the data buffer length.
// nLen -- lenght of the data to send.
//
// outputs:
// returns BLERR_SUCCESS if successful.
// *phIOBuffer io buffer handle
// *ppDataBuffer -- data buffer.
// *pnBufferLen -- buffer length.
//
//////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
int BlrudpReleaseSendBuffer(BLRUDP_HIOBUFFER hIoBuffer);
//
// Release a send buffer that was obtained by BlrudpGetSendbuffer.
//
// The client calls this when it wishes to give the buffer back to the context
// without sending data..
//
// inputs:
// hIoBuffer -- buffer handle.
// outputs:
// returns BLERR_SUCCESS if successful.
//
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
int BlrudpGetMaxPayloadLen(BLRUDP_HCONTEXT hContext,
unsigned long *pulMaxPayloadLen);
//
// Retrieve the maxium payload size assocaied with a given context.
//
// inputs:
// hContext -- context to retrieve the max payload length
// pulMTUSize -- pointer of where to stuff the max payload length
// outputs:
// returns BLERR_SUCCESS if successful.
// *pulMTUSize -- the MTU size.
/////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////
int BlrudpGetMaxBufferSize(BLRUDP_HIOBUFFER hIoBuffer,
unsigned long *pulBufferSize);
//
// Return the maximum size of this data buffer.
//
// inputs:
// hIOBuffer -- io buffer handle
// pulBufferSize -- pointer where to stuff the buffer size.
// outputs:
// returns BLERR_SUCCESS if successful.
// *pulBufferSize -- The maximum buffer size.
/////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////
int BlrudpGetDataSize(BLRUDP_HIOBUFFER hIoBuffer,
unsigned long *pulDataSize);
//
// Return the size of the data contained in this buffer.
//
// inputs:
// hBlrudp -- instance to the Blrudp instance
// hIOBuffer -- io buffer handle
// pulDataSize -- pointer where to stuff the buffer size.
// outputs:
// returns BLERR_SUCCESS if successful.
// *pulDataSize -- The size of the data buffer.
/////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////
int BlrudpGetDataPointer(BLRUDP_HIOBUFFER hIoBuffer,
unsigned char **ppDataBuffer);
//
// return the pointer to the data buffer assicagted with this IO buffer.
//
// inputs:
// hBlrudp -- instance to the Blrudp instance
// hIOBuffer -- io buffer handle
// pulDataSize -- pointer where to stuff the buffer size.
// outputs:
// returns BLERR_SUCCESS if successful.
// *pulDataSize -- The size of the data buffer.
/////////////////////////////////////////////////////////////////////////
#ifdef __cplusplus
};
#endif
#endif
| 39.950485 | 118 | 0.545238 | [
"object"
] |
dd08a02df926d4ea2f87f3ae9c2b1ebbb3e4a037 | 7,504 | h | C | plugins/community/repos/AudibleInstruments/eurorack/plaits/dsp/drums/hi_hat.h | guillaume-plantevin/VeeSeeVSTRack | 76fafc8e721613669d6f5ae82a0f58ce923a91e1 | [
"Zlib",
"BSD-3-Clause"
] | 233 | 2018-07-02T16:49:36.000Z | 2022-02-27T21:45:39.000Z | plugins/community/repos/AudibleInstruments/eurorack/plaits/dsp/drums/hi_hat.h | guillaume-plantevin/VeeSeeVSTRack | 76fafc8e721613669d6f5ae82a0f58ce923a91e1 | [
"Zlib",
"BSD-3-Clause"
] | 24 | 2018-07-09T11:32:15.000Z | 2022-01-07T01:45:43.000Z | plugins/community/repos/AudibleInstruments/eurorack/plaits/dsp/drums/hi_hat.h | guillaume-plantevin/VeeSeeVSTRack | 76fafc8e721613669d6f5ae82a0f58ce923a91e1 | [
"Zlib",
"BSD-3-Clause"
] | 24 | 2018-07-14T21:55:30.000Z | 2021-05-04T04:20:34.000Z | // Copyright 2016 Olivier Gillet.
//
// Author: Olivier Gillet (ol.gillet@gmail.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// See http://creativecommons.org/licenses/MIT/ for more information.
//
// -----------------------------------------------------------------------------
//
// 808 HH, with a few extra parameters to push things to the CY territory...
// The template parameter MetallicNoiseSource allows another kind of "metallic
// noise" to be used, for results which are more similar to KR-55 or FM hi-hats.
#ifndef PLAITS_DSP_DRUMS_HI_HAT_H_
#define PLAITS_DSP_DRUMS_HI_HAT_H_
#include <algorithm>
#include "stmlib/dsp/dsp.h"
#include "stmlib/dsp/filter.h"
#include "stmlib/dsp/parameter_interpolator.h"
#include "stmlib/dsp/units.h"
#include "stmlib/utils/random.h"
#include "plaits/dsp/dsp.h"
#include "plaits/dsp/oscillator/oscillator.h"
namespace plaits {
// 808 style "metallic noise" with 6 square oscillators.
class SquareNoise {
public:
SquareNoise() { }
~SquareNoise() { }
void Init() {
std::fill(&phase_[0], &phase_[6], 0);
}
void Render(float f0, float* temp_1, float* temp_2, float* out, size_t size) {
const float ratios[6] = {
// Nominal f0: 414 Hz
1.0f, 1.304f, 1.466f, 1.787f, 1.932f, 2.536f
};
uint32_t increment[6];
uint32_t phase[6];
for (int i = 0; i < 6; ++i) {
float f = f0 * ratios[i];
if (f >= 0.499f) f = 0.499f;
increment[i] = static_cast<uint32_t>(f * 4294967296.0f);
phase[i] = phase_[i];
}
while (size--) {
phase[0] += increment[0];
phase[1] += increment[1];
phase[2] += increment[2];
phase[3] += increment[3];
phase[4] += increment[4];
phase[5] += increment[5];
uint32_t noise = 0;
noise += (phase[0] >> 31);
noise += (phase[1] >> 31);
noise += (phase[2] >> 31);
noise += (phase[3] >> 31);
noise += (phase[4] >> 31);
noise += (phase[5] >> 31);
*out++ = 0.33f * static_cast<float>(noise) - 1.0f;
}
for (int i = 0; i < 6; ++i) {
phase_[i] = phase[i];
}
}
private:
uint32_t phase_[6];
DISALLOW_COPY_AND_ASSIGN(SquareNoise);
};
class RingModNoise {
public:
RingModNoise() { }
~RingModNoise() { }
void Init() {
for (int i = 0; i < 6; ++i) {
oscillator_[i].Init();
}
}
void Render(float f0, float* temp_1, float* temp_2, float* out, size_t size) {
const float ratio = f0 / (0.01f + f0);
const float f1a = 200.0f / kSampleRate * ratio;
const float f1b = 7530.0f / kSampleRate * ratio;
const float f2a = 510.0f / kSampleRate * ratio;
const float f2b = 8075.0f / kSampleRate * ratio;
const float f3a = 730.0f / kSampleRate * ratio;
const float f3b = 10500.0f / kSampleRate * ratio;
std::fill(&out[0], &out[size], 0.0f);
RenderPair(&oscillator_[0], f1a, f1b, temp_1, temp_2, out, size);
RenderPair(&oscillator_[2], f2a, f2b, temp_1, temp_2, out, size);
RenderPair(&oscillator_[4], f3a, f3b, temp_1, temp_2, out, size);
}
private:
void RenderPair(
Oscillator* osc,
float f1,
float f2,
float* temp_1,
float* temp_2,
float* out,
size_t size) {
osc[0].Render<OSCILLATOR_SHAPE_SQUARE>(f1, 0.5f, temp_1, size);
osc[1].Render<OSCILLATOR_SHAPE_SAW>(f2, 0.5f, temp_2, size);
while (size--) {
*out++ += *temp_1++ * *temp_2++;
}
}
Oscillator oscillator_[6];
DISALLOW_COPY_AND_ASSIGN(RingModNoise);
};
class SwingVCA {
public:
float operator()(float s, float gain) {
s *= s > 0.0f ? 10.0f : 0.1f;
s = s / (1.0f + fabsf(s));
return (s + 1.0f) * gain;
}
};
class LinearVCA {
public:
float operator()(float s, float gain) {
return s * gain;
}
};
template<typename MetallicNoiseSource, typename VCA, bool resonance>
class HiHat {
public:
HiHat() { }
~HiHat() { }
void Init() {
envelope_ = 0.0f;
noise_clock_ = 0.0f;
noise_sample_ = 0.0f;
sustain_gain_ = 0.0f;
metallic_noise_.Init();
noise_coloration_svf_.Init();
hpf_.Init();
}
void Render(
bool sustain,
bool trigger,
float accent,
float f0,
float tone,
float decay,
float noisiness,
float* temp_1,
float* temp_2,
float* out,
size_t size) {
const float envelope_decay = 1.0f - 0.003f * stmlib::SemitonesToRatio(
-decay * 84.0f);
const float cut_decay = 1.0f - 0.0025f * stmlib::SemitonesToRatio(
-decay * 36.0f);
if (trigger) {
envelope_ = (1.5f + 0.5f * (1.0f - decay)) * (0.3f + 0.7f * accent);
}
// Render the metallic noise.
metallic_noise_.Render(2.0f * f0, temp_1, temp_2, out, size);
// Apply BPF on the metallic noise.
float cutoff = 150.0f / kSampleRate * stmlib::SemitonesToRatio(
tone * 72.0f);
CONSTRAIN(cutoff, 0.0f, 16000.0f / kSampleRate);
noise_coloration_svf_.set_f_q<stmlib::FREQUENCY_ACCURATE>(
cutoff, resonance ? 3.0f + 6.0f * tone : 1.0f);
noise_coloration_svf_.Process<stmlib::FILTER_MODE_BAND_PASS>(
out, out, size);
// This is not at all part of the 808 circuit! But to add more variety, we
// add a variable amount of clocked noise to the output of the 6 schmitt
// trigger oscillators.
noisiness *= noisiness;
float noise_f = f0 * (16.0f + 16.0f * (1.0f - noisiness));
CONSTRAIN(noise_f, 0.0f, 0.5f);
for (size_t i = 0; i < size; ++i) {
noise_clock_ += noise_f;
if (noise_clock_ >= 1.0f) {
noise_clock_ -= 1.0f;
noise_sample_ = stmlib::Random::GetFloat() - 0.5f;
}
out[i] += noisiness * (noise_sample_ - out[i]);
}
// Apply VCA.
stmlib::ParameterInterpolator sustain_gain(
&sustain_gain_,
accent * decay,
size);
for (size_t i = 0; i < size; ++i) {
VCA vca;
envelope_ *= envelope_ > 0.5f ? envelope_decay : cut_decay;
out[i] = vca(out[i], sustain ? sustain_gain.Next() : envelope_);
}
hpf_.set_f_q<stmlib::FREQUENCY_ACCURATE>(cutoff, 0.5f);
hpf_.Process<stmlib::FILTER_MODE_HIGH_PASS>(out, out, size);
}
private:
float envelope_;
float noise_clock_;
float noise_sample_;
float sustain_gain_;
MetallicNoiseSource metallic_noise_;
stmlib::Svf noise_coloration_svf_;
stmlib::Svf hpf_;
DISALLOW_COPY_AND_ASSIGN(HiHat);
};
} // namespace plaits
#endif // PLAITS_DSP_DRUMS_HI_HAT_H_
| 28.861538 | 80 | 0.622601 | [
"render"
] |
dd0d05fd233243a4c50e301d29885bfdb12e7777 | 2,675 | h | C | cras/src/server/cras_hfp_slc.h | khadas/android_external_adhd | 0702ba2786f5bedc375b9b7c8120d212c02c08f6 | [
"BSD-1-Clause",
"BSD-3-Clause"
] | null | null | null | cras/src/server/cras_hfp_slc.h | khadas/android_external_adhd | 0702ba2786f5bedc375b9b7c8120d212c02c08f6 | [
"BSD-1-Clause",
"BSD-3-Clause"
] | null | null | null | cras/src/server/cras_hfp_slc.h | khadas/android_external_adhd | 0702ba2786f5bedc375b9b7c8120d212c02c08f6 | [
"BSD-1-Clause",
"BSD-3-Clause"
] | null | null | null | /* Copyright (c) 2013 The Chromium OS 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 CRAS_HFP_SLC_H_
#define CRAS_HFP_SLC_H_
struct hfp_slc_handle;
/* Callback to call when service level connection initialized. */
typedef int (*hfp_slc_init_cb)(struct hfp_slc_handle *handle);
/* Callback to call when service level connection disconnected. */
typedef int (*hfp_slc_disconnect_cb)(struct hfp_slc_handle *handle);
/* Creates an hfp_slc_handle to poll the RFCOMM file descriptor
* to read and handle received AT commands.
* Args:
* fd - the rfcomm fd used to initialize service level connection
* is_hsp - if the slc handle is created for headset profile
* device - The bt device associated with the created slc object
* init_cb - the callback function to be triggered when a service level
* connection is initialized.
* disconnect_cb - the callback function to be triggered when the service
* level connection is disconnected.
*/
struct hfp_slc_handle *hfp_slc_create(int fd, int is_hsp,
struct cras_bt_device *device,
hfp_slc_init_cb init_cb,
hfp_slc_disconnect_cb disconnect_cb);
/* Destroys an hfp_slc_handle. */
void hfp_slc_destroy(struct hfp_slc_handle *handle);
/* Sets the call status to notify handsfree device. */
int hfp_set_call_status(struct hfp_slc_handle *handle, int call);
/* Fakes the incoming call event for qualification test. */
int hfp_event_incoming_call(struct hfp_slc_handle *handle,
const char *number,
int type);
/* Handles the call status changed event.
* AG will send notification to HF accordingly. */
int hfp_event_update_call(struct hfp_slc_handle *handle);
/* Handles the call setup status changed event.
* AG will send notification to HF accordingly. */
int hfp_event_update_callsetup(struct hfp_slc_handle *handle);
/* Handles the call held status changed event.
* AG will send notification to HF accordingly. */
int hfp_event_update_callheld(struct hfp_slc_handle *handle);
/* Sets battery level which is required for qualification test. */
int hfp_event_set_battery(struct hfp_slc_handle *handle, int value);
/* Sets signal strength which is required for qualification test. */
int hfp_event_set_signal(struct hfp_slc_handle *handle, int value);
/* Sets service availability which is required for qualification test. */
int hfp_event_set_service(struct hfp_slc_handle *handle, int value);
/* Sets speaker gain value to headsfree device. */
int hfp_event_speaker_gain(struct hfp_slc_handle *handle, int gain);
#endif /* CRAS_HFP_SLC_H_ */
| 38.768116 | 76 | 0.763364 | [
"object"
] |
dd23b887269995b55db9d4be16b0cdd8772ba9d1 | 7,728 | h | C | src/frameworks/native/services/surfaceflinger/Scheduler/EventThread.h | dAck2cC2/m3e | 475b89b59d5022a94e00b636438b25e27e4eaab2 | [
"Apache-2.0"
] | null | null | null | src/frameworks/native/services/surfaceflinger/Scheduler/EventThread.h | dAck2cC2/m3e | 475b89b59d5022a94e00b636438b25e27e4eaab2 | [
"Apache-2.0"
] | null | null | null | src/frameworks/native/services/surfaceflinger/Scheduler/EventThread.h | dAck2cC2/m3e | 475b89b59d5022a94e00b636438b25e27e4eaab2 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2011 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 <sys/types.h>
#include <condition_variable>
#include <cstdint>
#include <deque>
#include <mutex>
#include <optional>
#include <thread>
#include <vector>
#include <android-base/thread_annotations.h>
#include <gui/DisplayEventReceiver.h>
#include <gui/IDisplayEventConnection.h>
#include <private/gui/BitTube.h>
#include <utils/Errors.h>
// ---------------------------------------------------------------------------
namespace android {
// ---------------------------------------------------------------------------
class EventThread;
class EventThreadTest;
class SurfaceFlinger;
// ---------------------------------------------------------------------------
using ResyncCallback = std::function<void()>;
enum class VSyncRequest {
None = -1,
Single = 0,
Periodic = 1,
// Subsequent values are periods.
};
class VSyncSource {
public:
class Callback {
public:
virtual ~Callback() {}
virtual void onVSyncEvent(nsecs_t when) = 0;
};
virtual ~VSyncSource() {}
virtual void setVSyncEnabled(bool enable) = 0;
virtual void setCallback(Callback* callback) = 0;
virtual void setPhaseOffset(nsecs_t phaseOffset) = 0;
};
class EventThreadConnection : public BnDisplayEventConnection {
public:
EventThreadConnection(EventThread*, ResyncCallback,
ISurfaceComposer::ConfigChanged configChanged);
virtual ~EventThreadConnection();
virtual status_t postEvent(const DisplayEventReceiver::Event& event);
status_t stealReceiveChannel(gui::BitTube* outChannel) override;
status_t setVsyncRate(uint32_t rate) override;
void requestNextVsync() override; // asynchronous
// Called in response to requestNextVsync.
const ResyncCallback resyncCallback;
VSyncRequest vsyncRequest = VSyncRequest::None;
const ISurfaceComposer::ConfigChanged configChanged;
private:
virtual void onFirstRef();
EventThread* const mEventThread;
gui::BitTube mChannel;
};
class EventThread {
public:
virtual ~EventThread();
virtual sp<EventThreadConnection> createEventConnection(
ResyncCallback, ISurfaceComposer::ConfigChanged configChanged) const = 0;
// called before the screen is turned off from main thread
virtual void onScreenReleased() = 0;
// called after the screen is turned on from main thread
virtual void onScreenAcquired() = 0;
virtual void onHotplugReceived(PhysicalDisplayId displayId, bool connected) = 0;
// called when SF changes the active config and apps needs to be notified about the change
virtual void onConfigChanged(PhysicalDisplayId displayId, int32_t configId) = 0;
virtual void dump(std::string& result) const = 0;
virtual void setPhaseOffset(nsecs_t phaseOffset) = 0;
virtual status_t registerDisplayEventConnection(
const sp<EventThreadConnection>& connection) = 0;
virtual void setVsyncRate(uint32_t rate, const sp<EventThreadConnection>& connection) = 0;
// Requests the next vsync. If resetIdleTimer is set to true, it resets the idle timer.
virtual void requestNextVsync(const sp<EventThreadConnection>& connection) = 0;
};
namespace impl {
class EventThread : public android::EventThread, private VSyncSource::Callback {
public:
using InterceptVSyncsCallback = std::function<void(nsecs_t)>;
// TODO(b/128863962): Once the Scheduler is complete this constructor will become obsolete.
EventThread(VSyncSource*, InterceptVSyncsCallback, const char* threadName);
EventThread(std::unique_ptr<VSyncSource>, InterceptVSyncsCallback, const char* threadName);
~EventThread();
sp<EventThreadConnection> createEventConnection(
ResyncCallback, ISurfaceComposer::ConfigChanged configChanged) const override;
status_t registerDisplayEventConnection(const sp<EventThreadConnection>& connection) override;
void setVsyncRate(uint32_t rate, const sp<EventThreadConnection>& connection) override;
void requestNextVsync(const sp<EventThreadConnection>& connection) override;
// called before the screen is turned off from main thread
void onScreenReleased() override;
// called after the screen is turned on from main thread
void onScreenAcquired() override;
void onHotplugReceived(PhysicalDisplayId displayId, bool connected) override;
void onConfigChanged(PhysicalDisplayId displayId, int32_t configId) override;
void dump(std::string& result) const override;
void setPhaseOffset(nsecs_t phaseOffset) override;
private:
friend EventThreadTest;
using DisplayEventConsumers = std::vector<sp<EventThreadConnection>>;
// TODO(b/128863962): Once the Scheduler is complete this constructor will become obsolete.
EventThread(VSyncSource* src, std::unique_ptr<VSyncSource> uniqueSrc,
InterceptVSyncsCallback interceptVSyncsCallback, const char* threadName);
void threadMain(std::unique_lock<std::mutex>& lock) REQUIRES(mMutex);
bool shouldConsumeEvent(const DisplayEventReceiver::Event& event,
const sp<EventThreadConnection>& connection) const REQUIRES(mMutex);
void dispatchEvent(const DisplayEventReceiver::Event& event,
const DisplayEventConsumers& consumers) REQUIRES(mMutex);
void removeDisplayEventConnectionLocked(const wp<EventThreadConnection>& connection)
REQUIRES(mMutex);
// Implements VSyncSource::Callback
void onVSyncEvent(nsecs_t timestamp) override;
// TODO(b/128863962): Once the Scheduler is complete this pointer will become obsolete.
VSyncSource* mVSyncSource GUARDED_BY(mMutex) = nullptr;
std::unique_ptr<VSyncSource> mVSyncSourceUnique GUARDED_BY(mMutex) = nullptr;
const InterceptVSyncsCallback mInterceptVSyncsCallback;
const char* const mThreadName;
std::thread mThread;
mutable std::mutex mMutex;
mutable std::condition_variable mCondition;
std::vector<wp<EventThreadConnection>> mDisplayEventConnections GUARDED_BY(mMutex);
std::deque<DisplayEventReceiver::Event> mPendingEvents GUARDED_BY(mMutex);
// VSYNC state of connected display.
struct VSyncState {
explicit VSyncState(PhysicalDisplayId displayId) : displayId(displayId) {}
const PhysicalDisplayId displayId;
// Number of VSYNC events since display was connected.
uint32_t count = 0;
// True if VSYNC should be faked, e.g. when display is off.
bool synthetic = false;
};
// TODO(b/74619554): Create per-display threads waiting on respective VSYNC signals,
// and support headless mode by injecting a fake display with synthetic VSYNC.
std::optional<VSyncState> mVSyncState GUARDED_BY(mMutex);
// State machine for event loop.
enum class State {
Idle,
Quit,
SyntheticVSync,
VSync,
};
State mState GUARDED_BY(mMutex) = State::Idle;
static const char* toCString(State);
};
// ---------------------------------------------------------------------------
} // namespace impl
} // namespace android
| 34.346667 | 98 | 0.703934 | [
"vector"
] |
dd2d2cb0e801e0c119c7ac4ed939008a92ade17a | 2,440 | c | C | src/lib/vm/c/common/jstring.c | BigstarPie/WuKongProject | e8e4a9d3f56732b2fdc8c5c48d0be93d31f57376 | [
"BSD-2-Clause-FreeBSD"
] | 16 | 2015-01-07T10:32:47.000Z | 2019-01-16T16:13:51.000Z | src/lib/vm/c/common/jstring.c | BigstarPie/WuKongProject | e8e4a9d3f56732b2fdc8c5c48d0be93d31f57376 | [
"BSD-2-Clause-FreeBSD"
] | 14 | 2015-05-01T04:45:45.000Z | 2016-05-11T01:29:23.000Z | src/lib/vm/c/common/jstring.c | BigstarPie/WuKongProject | e8e4a9d3f56732b2fdc8c5c48d0be93d31f57376 | [
"BSD-2-Clause-FreeBSD"
] | 13 | 2015-06-17T06:42:17.000Z | 2020-11-27T18:23:08.000Z | #include "string.h"
#include "jstring.h"
#include "jlib_base.h"
#include "execution.h"
#include "array.h"
dj_object * dj_jstring_create(dj_vm *vm, int length)
{
dj_object * jstring;
// create java String object
uint8_t runtime_id = dj_vm_getSysLibClassRuntimeId(vm, BASE_CDEF_java_lang_String);
dj_di_pointer classDef = dj_vm_getRuntimeClassDefinition(vm, runtime_id);
jstring = dj_object_create(runtime_id, dj_di_classDefinition_getNrRefs(classDef), dj_di_classDefinition_getOffsetOfFirstReference(classDef));
// throw OutOfMemoryError if dj_object_create returns NULL
if (jstring == NULL) return NULL;
// add the string pointer to the safe memory pool to avoid it becoming invalid in case dj_int_array_create triggers a GC
dj_mem_addSafePointer((void**)&jstring);
// create charArray
dj_int_array * charArray = dj_int_array_create(T_CHAR, length);
// throw OutOfMemoryError
if (charArray == NULL)
{
dj_mem_free(jstring);
return NULL;
} else
{
BASE_STRUCT_java_lang_String * stringObject = (BASE_STRUCT_java_lang_String*)jstring;
stringObject->offset = 0;
stringObject->count = length;
stringObject->value = VOIDP_TO_REF(charArray);
}
// Remove the string object pointer from the safe memory pool.
dj_mem_removeSafePointer((void**)&jstring);
return jstring;
}
dj_object * dj_jstring_createFromStr(dj_vm *vm, char * str)
{
uint16_t i;
BASE_STRUCT_java_lang_String * jstring = (BASE_STRUCT_java_lang_String*)dj_jstring_create(vm, strlen(str));
dj_int_array * charArray = REF_TO_VOIDP(jstring->value);
// Copy ASCII from program space to the array
for (i = 0; i < strlen(str); i++) charArray->data.bytes[i] = str[i];
return (dj_object *)jstring;
}
dj_object * dj_jstring_createFromGlobalId(dj_vm *vm, dj_global_id stringId)
{
uint16_t i;
// get pointer to the ASCII string in program memory and the string length
dj_di_pointer stringBytes = dj_di_stringtable_getElementBytes(stringId.infusion->stringTable, stringId.entity_id);
uint16_t stringLength = dj_di_stringtable_getElementLength(stringId.infusion->stringTable, stringId.entity_id);
BASE_STRUCT_java_lang_String * jstring = (BASE_STRUCT_java_lang_String*)dj_jstring_create(vm, stringLength);
dj_int_array * charArray = REF_TO_VOIDP(jstring->value);
// Copy ASCII from program space to the array
for (i = 0; i < stringLength; i++)
charArray->data.bytes[i] = dj_di_getU8(stringBytes++);
return (dj_object *)jstring;
}
| 31.688312 | 142 | 0.773361 | [
"object"
] |
dd3554bb7cca6a4e9e7dc0d3965f136c6b078571 | 2,630 | h | C | src/usbhost/messenger-usbhost.h | apuzhevi/librealsense | b608db6177c678c480b73352c456e98abd150ea1 | [
"Apache-2.0"
] | 2 | 2019-08-12T05:40:18.000Z | 2019-08-12T06:32:38.000Z | src/usbhost/messenger-usbhost.h | apuzhevi/librealsense | b608db6177c678c480b73352c456e98abd150ea1 | [
"Apache-2.0"
] | null | null | null | src/usbhost/messenger-usbhost.h | apuzhevi/librealsense | b608db6177c678c480b73352c456e98abd150ea1 | [
"Apache-2.0"
] | 1 | 2019-10-01T07:29:47.000Z | 2019-10-01T07:29:47.000Z | // License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2015 Intel Corporation. All Rights Reserved.
#pragma once
#include "usbhost.h"
#include "../usb/usb-types.h"
#include "../backend.h"
#include "../usb/usb-messenger.h"
#include "../usb/usb-device.h"
#include "endpoint-usbhost.h"
#include "../concurrency.h"
#include <mutex>
#include <map>
namespace librealsense
{
namespace platform
{
class usb_device_usbhost;
class usb_request_callback{
std::function<void(usb_request*)> _callback;
std::mutex _mutex;
public:
usb_request_callback(std::function<void(usb_request*)> callback)
{
_callback = callback;
}
~usb_request_callback()
{
cancel();
}
void cancel(){
std::lock_guard<std::mutex> lk(_mutex);
_callback = nullptr;
}
void callback(usb_request* response){
std::lock_guard<std::mutex> lk(_mutex);
if(_callback)
_callback(response);
}
};
class usb_messenger_usbhost : public usb_messenger
{
public:
usb_messenger_usbhost(const std::shared_ptr<usb_device_usbhost>& device);
virtual ~usb_messenger_usbhost();
virtual usb_status control_transfer(int request_type, int request, int value, int index, uint8_t* buffer, uint32_t length, uint32_t& transferred, uint32_t timeout_ms) override;
virtual usb_status bulk_transfer(const std::shared_ptr<usb_endpoint>& endpoint, uint8_t* buffer, uint32_t length, uint32_t& transferred, uint32_t timeout_ms) override;
virtual usb_status reset_endpoint(const rs_usb_endpoint& endpoint, uint32_t timeout_ms) override;
usb_status submit_request(std::shared_ptr<usb_request> request);
usb_status cancel_request(std::shared_ptr<usb_request> request);
private:
std::shared_ptr<dispatcher> _dispatcher;
std::shared_ptr<usb_device_usbhost> _device;
std::shared_ptr<usb_endpoint_usbhost> _interrupt_endpoint;
std::mutex _mutex;
std::vector<uint8_t> _interrupt_buffer;
std::shared_ptr<usb_request_callback> _interrupt_callback;
std::shared_ptr<usb_request> _interrupt_request;
void claim_interface(int interface);
void queue_interrupt_request();
void listen_to_interrupts();
void repeating_request();
};
}
}
| 33.291139 | 188 | 0.622053 | [
"vector"
] |
dd416c799182faf826e5ff38c903925a3aba4e20 | 6,743 | h | C | src/apps/localization/modules/refinement/localization_iter_lateration_module.h | itm/shawn | 49cb715d0044a20a01a19bc4d7b62f9f209df83c | [
"BSD-3-Clause"
] | 15 | 2015-07-07T15:48:30.000Z | 2019-10-27T18:49:49.000Z | src/apps/localization/modules/refinement/localization_iter_lateration_module.h | itm/shawn | 49cb715d0044a20a01a19bc4d7b62f9f209df83c | [
"BSD-3-Clause"
] | null | null | null | src/apps/localization/modules/refinement/localization_iter_lateration_module.h | itm/shawn | 49cb715d0044a20a01a19bc4d7b62f9f209df83c | [
"BSD-3-Clause"
] | 4 | 2016-11-23T05:50:01.000Z | 2019-09-18T12:44:36.000Z | /************************************************************************
** This file is part of the network simulator Shawn. **
** Copyright (C) 2004-2007 by the SwarmNet (www.swarmnet.de) project **
** Shawn is free software; you can redistribute it and/or modify it **
** under the terms of the BSD License. Refer to the shawn-licence.txt **
** file in the root of the Shawn source tree for further details. **
************************************************************************/
#ifndef __SHAWN_APPS_LOCALIZATION_MODULES_REFINEMENT_ITER_LATERATION_MODULE_H
#define __SHAWN_APPS_LOCALIZATION_MODULES_REFINEMENT_ITER_LATERATION_MODULE_H
#include "_apps_enable_cmake.h"
#ifdef ENABLE_LOCALIZATION
#include "apps/localization/modules/localization_module.h"
#include "apps/localization/messages/refinement/localization_iter_lateration_messages.h"
namespace localization
{
/// Module implementing refinement by iterative lateration
/** This module implements refinement by iterative lateration. Idea is to
* take into account all neighbors, respectively their distances and
* positions, and start lateration with this information. After that the
* new position is broadcasted, so that neighbors are able to start
* lateration again with this new data, and so on.
*
* The process finished, either after a given number of steps, or, if the
* position update becomes very small.
*
* Main problem of this procedere are nodes with inaccurate information.
* To filter out most of these cases, there are different methods.
*
* At first, there is the use of confidences. This means, that every node
* is associated with a special confidence level between 0 and 1. Unknowns
* start with a low confidence like 0.1, anchors with a high one like 1.
* These values are used in the
* \ref localization::est_pos_lateration "lateration" by a weighted least
* squares approach. Instead of solving \f$ Ax = b\f$,
* \f$ \omega Ax = \omega b\f$ is solved, where \f$\omega\f$ is the vector
* of confidences. After a successful lateration a node sets its
* confidence to the average of its neighbors confidences. This will, in
* general, increase the confidence level.
*
* Second issue is filtering out ill-connected nodes.\n
* To take part in refinement phase, a node has to be \em sound. This
* means, that there are \em independent references to at least three/four
* anchors. That is, information about anchors has to be get from
* different neighbors. Moreover, if a node becomes sound, it sends this
* out. The neighbors again receiving this information, add the sound node
* to an own list, so that an unsound node is able to become sound, if
* the size of intersection between sound and references becomes greater
* or equal three/four.
*
* Third, the twin neighbors should be filtered out. This means, that one
* neighbor, that is very close to another, is set to be a twin and is
* ignored in further computation. The twin check has to be done in every
* iteration, because in most cases their position change.
*
* At least, there is the
* \ref localization::check_residue "residuen check" to check the validity
* of the new position. To avoid being trapped in a local minimum, there
* is a given chance to accept a failed check anyway. If this happens, the
* confidence of affected node is reduced by 50 percent.
*/
class LocalizationIterLaterationModule
: public LocalizationModule
{
public:
///@name construction / destruction
///@{
///
LocalizationIterLaterationModule();
///
virtual ~LocalizationIterLaterationModule();
///@}
///@name standard methods startup/simulation steps
///@{
/** Read given parameters.
*
* \sa LocalizationModule::boot()
*/
virtual void boot( void ) throw();
/** Handling of Iter-Lateration-Messages.
*
* \sa LocalizationModule::process_message()
*/
virtual bool process_message( const shawn::ConstMessageHandle& ) throw();
/** Check, whether state can be set to finished or not. Moreover, send
* initial messages and check on first pass, whether node is sound or
* not.
*
* \sa LocalizationModule::work()
*/
virtual void work( void ) throw();
///@}
///@name module status info
///@{
/** \return \c true, if module is finished. \c false otherwise
* \sa LocalizationModule::finished()
*/
virtual bool finished( void ) throw();
///@}
virtual void rollback( void ) throw();
protected:
///@name processing iterative lateration messages
///@{
/** This method processes sound messages. Message source is added to
* sound nodes and, if necessary, the sound check is started again.
*
* \sa LocalizationIterLaterationSoundMessage
*/
virtual bool process_iter_lateration_sound_message(
const LocalizationIterLaterationSoundMessage& )
throw();
/** This method processes normal messages. The received information is
* updated in own neighborhood.
*
* \sa LocalizationIterLaterationMessage
*/
virtual bool process_iter_lateration_message(
const LocalizationIterLaterationMessage& )
throw();
///@}
///@name main refinement step
///@{
/** This method executes the iterative lateration step. There are passed
* all checks mentioned in the \em Detailed \em Description above.
*/
virtual void iter_lateration_step( void ) throw();
///@}
private:
enum IterLaterationState
{
il_init,
il_work,
il_finished
};
IterLaterationState state_;
int last_useful_msg_;
int iteration_limit_;
int iteration_cnt_;
int min_confident_nbrs_;
double twin_measure_;
double abort_pos_update_;
double res_acceptance_;
bool sound_;
};
}// namespace localization
#endif
#endif
/*-----------------------------------------------------------------------
* Source $Source: /cvs/shawn/shawn/apps/localization/modules/refinement/localization_iter_lateration_module.h,v $
* Version $Revision: 197 $
* Date $Date: 2008-04-29 17:40:51 +0200 (Tue, 29 Apr 2008) $
*-----------------------------------------------------------------------
* $Log: localization_iter_lateration_module.h,v $
*-----------------------------------------------------------------------*/
| 38.531429 | 115 | 0.634436 | [
"vector"
] |
dd625dfe32fe6002fe3de310bb34bf7af0042b87 | 10,111 | h | C | vod/include/tencentcloud/vod/v20180717/model/DomainDetailInfo.h | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 43 | 2019-08-14T08:14:12.000Z | 2022-03-30T12:35:09.000Z | vod/include/tencentcloud/vod/v20180717/model/DomainDetailInfo.h | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 12 | 2019-07-15T10:44:59.000Z | 2021-11-02T12:35:00.000Z | vod/include/tencentcloud/vod/v20180717/model/DomainDetailInfo.h | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 28 | 2019-07-12T09:06:22.000Z | 2022-03-30T08:04:18.000Z | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef TENCENTCLOUD_VOD_V20180717_MODEL_DOMAINDETAILINFO_H_
#define TENCENTCLOUD_VOD_V20180717_MODEL_DOMAINDETAILINFO_H_
#include <string>
#include <vector>
#include <map>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
#include <tencentcloud/core/AbstractModel.h>
#include <tencentcloud/vod/v20180717/model/AccelerateAreaInfo.h>
#include <tencentcloud/vod/v20180717/model/DomainHTTPSConfig.h>
#include <tencentcloud/vod/v20180717/model/UrlSignatureAuthPolicy.h>
#include <tencentcloud/vod/v20180717/model/RefererAuthPolicy.h>
namespace TencentCloud
{
namespace Vod
{
namespace V20180717
{
namespace Model
{
/**
* 域名信息
*/
class DomainDetailInfo : public AbstractModel
{
public:
DomainDetailInfo();
~DomainDetailInfo() = default;
void ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const;
CoreInternalOutcome Deserialize(const rapidjson::Value &value);
/**
* 获取域名名称。
* @return Domain 域名名称。
*/
std::string GetDomain() const;
/**
* 设置域名名称。
* @param Domain 域名名称。
*/
void SetDomain(const std::string& _domain);
/**
* 判断参数 Domain 是否已赋值
* @return Domain 是否已赋值
*/
bool DomainHasBeenSet() const;
/**
* 获取加速地区信息。
注意:此字段可能返回 null,表示取不到有效值。
* @return AccelerateAreaInfos 加速地区信息。
注意:此字段可能返回 null,表示取不到有效值。
*/
std::vector<AccelerateAreaInfo> GetAccelerateAreaInfos() const;
/**
* 设置加速地区信息。
注意:此字段可能返回 null,表示取不到有效值。
* @param AccelerateAreaInfos 加速地区信息。
注意:此字段可能返回 null,表示取不到有效值。
*/
void SetAccelerateAreaInfos(const std::vector<AccelerateAreaInfo>& _accelerateAreaInfos);
/**
* 判断参数 AccelerateAreaInfos 是否已赋值
* @return AccelerateAreaInfos 是否已赋值
*/
bool AccelerateAreaInfosHasBeenSet() const;
/**
* 获取部署状态,取值有:
<li>Online:上线;</li>
<li>Deploying:部署中;</li>
<li>Locked: 锁定中,出现该状态时,无法对该域名进行部署变更。</li>
* @return DeployStatus 部署状态,取值有:
<li>Online:上线;</li>
<li>Deploying:部署中;</li>
<li>Locked: 锁定中,出现该状态时,无法对该域名进行部署变更。</li>
*/
std::string GetDeployStatus() const;
/**
* 设置部署状态,取值有:
<li>Online:上线;</li>
<li>Deploying:部署中;</li>
<li>Locked: 锁定中,出现该状态时,无法对该域名进行部署变更。</li>
* @param DeployStatus 部署状态,取值有:
<li>Online:上线;</li>
<li>Deploying:部署中;</li>
<li>Locked: 锁定中,出现该状态时,无法对该域名进行部署变更。</li>
*/
void SetDeployStatus(const std::string& _deployStatus);
/**
* 判断参数 DeployStatus 是否已赋值
* @return DeployStatus 是否已赋值
*/
bool DeployStatusHasBeenSet() const;
/**
* 获取HTTPS 配置信息。
注意:此字段可能返回 null,表示取不到有效值。
* @return HTTPSConfig HTTPS 配置信息。
注意:此字段可能返回 null,表示取不到有效值。
*/
DomainHTTPSConfig GetHTTPSConfig() const;
/**
* 设置HTTPS 配置信息。
注意:此字段可能返回 null,表示取不到有效值。
* @param HTTPSConfig HTTPS 配置信息。
注意:此字段可能返回 null,表示取不到有效值。
*/
void SetHTTPSConfig(const DomainHTTPSConfig& _hTTPSConfig);
/**
* 判断参数 HTTPSConfig 是否已赋值
* @return HTTPSConfig 是否已赋值
*/
bool HTTPSConfigHasBeenSet() const;
/**
* 获取[Key 防盗链](https://cloud.tencent.com/document/product/266/14047)配置信息。
注意:此字段可能返回 null,表示取不到有效值。
* @return UrlSignatureAuthPolicy [Key 防盗链](https://cloud.tencent.com/document/product/266/14047)配置信息。
注意:此字段可能返回 null,表示取不到有效值。
*/
UrlSignatureAuthPolicy GetUrlSignatureAuthPolicy() const;
/**
* 设置[Key 防盗链](https://cloud.tencent.com/document/product/266/14047)配置信息。
注意:此字段可能返回 null,表示取不到有效值。
* @param UrlSignatureAuthPolicy [Key 防盗链](https://cloud.tencent.com/document/product/266/14047)配置信息。
注意:此字段可能返回 null,表示取不到有效值。
*/
void SetUrlSignatureAuthPolicy(const UrlSignatureAuthPolicy& _urlSignatureAuthPolicy);
/**
* 判断参数 UrlSignatureAuthPolicy 是否已赋值
* @return UrlSignatureAuthPolicy 是否已赋值
*/
bool UrlSignatureAuthPolicyHasBeenSet() const;
/**
* 获取[Referer 防盗链](https://cloud.tencent.com/document/product/266/14046)配置信息。
注意:此字段可能返回 null,表示取不到有效值。
* @return RefererAuthPolicy [Referer 防盗链](https://cloud.tencent.com/document/product/266/14046)配置信息。
注意:此字段可能返回 null,表示取不到有效值。
*/
RefererAuthPolicy GetRefererAuthPolicy() const;
/**
* 设置[Referer 防盗链](https://cloud.tencent.com/document/product/266/14046)配置信息。
注意:此字段可能返回 null,表示取不到有效值。
* @param RefererAuthPolicy [Referer 防盗链](https://cloud.tencent.com/document/product/266/14046)配置信息。
注意:此字段可能返回 null,表示取不到有效值。
*/
void SetRefererAuthPolicy(const RefererAuthPolicy& _refererAuthPolicy);
/**
* 判断参数 RefererAuthPolicy 是否已赋值
* @return RefererAuthPolicy 是否已赋值
*/
bool RefererAuthPolicyHasBeenSet() const;
/**
* 获取域名添加到腾讯云点播系统中的时间。
<li>格式按照 ISO 8601标准表示,详见 [ISO 日期格式说明](https://cloud.tencent.com/document/product/266/11732#iso-.E6.97.A5.E6.9C.9F.E6.A0.BC.E5.BC.8F)。</li>
* @return CreateTime 域名添加到腾讯云点播系统中的时间。
<li>格式按照 ISO 8601标准表示,详见 [ISO 日期格式说明](https://cloud.tencent.com/document/product/266/11732#iso-.E6.97.A5.E6.9C.9F.E6.A0.BC.E5.BC.8F)。</li>
*/
std::string GetCreateTime() const;
/**
* 设置域名添加到腾讯云点播系统中的时间。
<li>格式按照 ISO 8601标准表示,详见 [ISO 日期格式说明](https://cloud.tencent.com/document/product/266/11732#iso-.E6.97.A5.E6.9C.9F.E6.A0.BC.E5.BC.8F)。</li>
* @param CreateTime 域名添加到腾讯云点播系统中的时间。
<li>格式按照 ISO 8601标准表示,详见 [ISO 日期格式说明](https://cloud.tencent.com/document/product/266/11732#iso-.E6.97.A5.E6.9C.9F.E6.A0.BC.E5.BC.8F)。</li>
*/
void SetCreateTime(const std::string& _createTime);
/**
* 判断参数 CreateTime 是否已赋值
* @return CreateTime 是否已赋值
*/
bool CreateTimeHasBeenSet() const;
private:
/**
* 域名名称。
*/
std::string m_domain;
bool m_domainHasBeenSet;
/**
* 加速地区信息。
注意:此字段可能返回 null,表示取不到有效值。
*/
std::vector<AccelerateAreaInfo> m_accelerateAreaInfos;
bool m_accelerateAreaInfosHasBeenSet;
/**
* 部署状态,取值有:
<li>Online:上线;</li>
<li>Deploying:部署中;</li>
<li>Locked: 锁定中,出现该状态时,无法对该域名进行部署变更。</li>
*/
std::string m_deployStatus;
bool m_deployStatusHasBeenSet;
/**
* HTTPS 配置信息。
注意:此字段可能返回 null,表示取不到有效值。
*/
DomainHTTPSConfig m_hTTPSConfig;
bool m_hTTPSConfigHasBeenSet;
/**
* [Key 防盗链](https://cloud.tencent.com/document/product/266/14047)配置信息。
注意:此字段可能返回 null,表示取不到有效值。
*/
UrlSignatureAuthPolicy m_urlSignatureAuthPolicy;
bool m_urlSignatureAuthPolicyHasBeenSet;
/**
* [Referer 防盗链](https://cloud.tencent.com/document/product/266/14046)配置信息。
注意:此字段可能返回 null,表示取不到有效值。
*/
RefererAuthPolicy m_refererAuthPolicy;
bool m_refererAuthPolicyHasBeenSet;
/**
* 域名添加到腾讯云点播系统中的时间。
<li>格式按照 ISO 8601标准表示,详见 [ISO 日期格式说明](https://cloud.tencent.com/document/product/266/11732#iso-.E6.97.A5.E6.9C.9F.E6.A0.BC.E5.BC.8F)。</li>
*/
std::string m_createTime;
bool m_createTimeHasBeenSet;
};
}
}
}
}
#endif // !TENCENTCLOUD_VOD_V20180717_MODEL_DOMAINDETAILINFO_H_
| 37.448148 | 138 | 0.524874 | [
"vector",
"model"
] |
dd6687c02271fbcf115041c0be962d19a9b7dbc3 | 3,583 | h | C | DeviceCode/Targets/Native/Interop/GHI_Hardware/Lib_GHI_IO_ControllerAreaNetwork.h | ghi-electronics/NETMF-Open-Firmware | ac310dae730ab58ad86932de6153318b619c7f16 | [
"Apache-2.0"
] | 2 | 2017-12-05T12:58:22.000Z | 2019-05-31T13:49:02.000Z | DeviceCode/Targets/Native/Interop/GHI_Hardware/Lib_GHI_IO_ControllerAreaNetwork.h | ghi-electronics/NETMF-Open-Firmware | ac310dae730ab58ad86932de6153318b619c7f16 | [
"Apache-2.0"
] | null | null | null | DeviceCode/Targets/Native/Interop/GHI_Hardware/Lib_GHI_IO_ControllerAreaNetwork.h | ghi-electronics/NETMF-Open-Firmware | ac310dae730ab58ad86932de6153318b619c7f16 | [
"Apache-2.0"
] | 6 | 2017-11-09T11:48:10.000Z | 2020-05-24T09:43:07.000Z | //-----------------------------------------------------------------------------
//
// ** WARNING! **
// This file was generated automatically by a tool.
// Re-running the tool will overwrite this file.
// You should copy this file to a custom location
// before adding any customization in the copy to
// prevent loss of your changes when the tool is
// re-run.
//
//-----------------------------------------------------------------------------
#ifndef _LIB_GHI_IO_CONTROLLERAREANETWORK_H_
#define _LIB_GHI_IO_CONTROLLERAREANETWORK_H_
namespace GHI
{
namespace IO
{
struct ControllerAreaNetwork
{
// Helper Functions to access fields of managed object
static INT8& Get_disposed( CLR_RT_HeapBlock* pMngObj ) { return Interop_Marshal_GetField_INT8( pMngObj, Library_Lib_GHI_IO_ControllerAreaNetwork::FIELD__disposed ); }
static INT8& Get_enabled( CLR_RT_HeapBlock* pMngObj ) { return Interop_Marshal_GetField_INT8( pMngObj, Library_Lib_GHI_IO_ControllerAreaNetwork::FIELD__enabled ); }
static UINT8& Get_channel( CLR_RT_HeapBlock* pMngObj ) { return Interop_Marshal_GetField_UINT8( pMngObj, Library_Lib_GHI_IO_ControllerAreaNetwork::FIELD__channel ); }
static INT32& Get_receiveBufferSize( CLR_RT_HeapBlock* pMngObj ) { return Interop_Marshal_GetField_INT32( pMngObj, Library_Lib_GHI_IO_ControllerAreaNetwork::FIELD__receiveBufferSize ); }
static UINT32& Get_baudRateRegister( CLR_RT_HeapBlock* pMngObj ) { return Interop_Marshal_GetField_UINT32( pMngObj, Library_Lib_GHI_IO_ControllerAreaNetwork::FIELD__baudRateRegister ); }
static UNSUPPORTED_TYPE& Get_MessageAvailable( CLR_RT_HeapBlock* pMngObj ) { return Interop_Marshal_GetField_UNSUPPORTED_TYPE( pMngObj, Library_Lib_GHI_IO_ControllerAreaNetwork::FIELD__MessageAvailable ); }
static UNSUPPORTED_TYPE& Get_ErrorReceived( CLR_RT_HeapBlock* pMngObj ) { return Interop_Marshal_GetField_UNSUPPORTED_TYPE( pMngObj, Library_Lib_GHI_IO_ControllerAreaNetwork::FIELD__ErrorReceived ); }
// Declaration of stubs. These functions are implemented by Interop code developers
static void NativeSetExplicitFilters( CLR_RT_HeapBlock* pMngObj, CLR_RT_TypedArray_UINT32 param0, HRESULT &hr );
static void NativeSetGroupFilters( CLR_RT_HeapBlock* pMngObj, CLR_RT_TypedArray_UINT32 param0, CLR_RT_TypedArray_UINT32 param1, HRESULT &hr );
static INT8 NativeEnable( CLR_RT_HeapBlock* pMngObj, HRESULT &hr );
static INT8 NativeDisable( CLR_RT_HeapBlock* pMngObj, HRESULT &hr );
static INT8 NativeReset( CLR_RT_HeapBlock* pMngObj, HRESULT &hr );
static INT32 NativeReceiveErrorCount( CLR_RT_HeapBlock* pMngObj, HRESULT &hr );
static INT32 NativeTransmitErrorCount( CLR_RT_HeapBlock* pMngObj, HRESULT &hr );
static INT32 NativeReceivedMessageCount( CLR_RT_HeapBlock* pMngObj, HRESULT &hr );
static INT8 NativeTransmittedMessagesSent( CLR_RT_HeapBlock* pMngObj, HRESULT &hr );
static INT8 NativeTransmissionAllowed( CLR_RT_HeapBlock* pMngObj, HRESULT &hr );
static void NativeDiscardIncomingMessages( CLR_RT_HeapBlock* pMngObj, HRESULT &hr );
static INT32 NativeSourceClock( HRESULT &hr );
static UINT32 NativeCalculateRegisterValue( INT32 param0, INT32 param1, INT32 param2, INT32 param3, INT32 param4, INT8 param5, HRESULT &hr );
};
}
}
#endif //_LIB_GHI_IO_CONTROLLERAREANETWORK_H_
| 63.982143 | 221 | 0.708903 | [
"object"
] |
dd68aa01ed03bfd52f2dd8c1aac76eb7a12fc73d | 2,338 | h | C | src/cpp-ethereum/test/tools/libtesteth/TestOutputHelper.h | nccproject/ncc | 068ccc82a73d28136546095261ad8ccef7e541a3 | [
"MIT"
] | 42 | 2021-01-04T01:59:21.000Z | 2021-05-14T14:35:04.000Z | src/cpp-ethereum/test/tools/libtesteth/TestOutputHelper.h | estxcoin/estcore | 4398b1d944373fe25668469966fa2660da454279 | [
"MIT"
] | 2 | 2021-01-04T02:08:47.000Z | 2021-01-04T02:36:08.000Z | src/cpp-ethereum/test/tools/libtesteth/TestOutputHelper.h | estxcoin/estcore | 4398b1d944373fe25668469966fa2660da454279 | [
"MIT"
] | 15 | 2021-01-04T02:00:21.000Z | 2021-01-06T02:06:43.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
* Fixture class for boost output when running testeth
*/
#pragma once
#include <test/tools/libtestutils/Common.h>
#include <test/tools/libtesteth/JsonSpiritHeaders.h>
namespace dev
{
namespace test
{
class TestOutputHelper
{
public:
static TestOutputHelper& get()
{
static TestOutputHelper instance;
return instance;
}
TestOutputHelper(TestOutputHelper const&) = delete;
void operator=(TestOutputHelper const&) = delete;
void initTest(size_t _maxTests = 1);
// Display percantage of completed tests to std::out. Has to be called before execution of every test.
void showProgress();
void finishTest();
//void setMaxTests(int _count) { m_maxTests = _count; }
bool checkTest(std::string const& _testName);
void setCurrentTestFile(boost::filesystem::path const& _name) { m_currentTestFileName = _name; }
void setCurrentTestName(std::string const& _name) { m_currentTestName = _name; }
std::string const& testName() { return m_currentTestName; }
std::string const& caseName() { return m_currentTestCaseName; }
boost::filesystem::path const& testFile() { return m_currentTestFileName; }
void printTestExecStats();
private:
TestOutputHelper() {}
Timer m_timer;
size_t m_currTest;
size_t m_maxTests;
std::string m_currentTestName;
std::string m_currentTestCaseName;
boost::filesystem::path m_currentTestFileName;
typedef std::pair<double, std::string> execTimeName;
std::vector<execTimeName> m_execTimeResults;
};
class TestOutputHelperFixture
{
public:
TestOutputHelperFixture() { TestOutputHelper::get().initTest(); }
~TestOutputHelperFixture() { TestOutputHelper::get().finishTest(); }
};
} //namespace test
} //namespace dev
| 30.763158 | 103 | 0.763473 | [
"vector"
] |
1cbc92f34d2b390bdf3bbe9011d2a3969fc502de | 10,079 | c | C | components/micropython/port/src/moducryptolib_maix.c | mongonta0716/MaixPy | b1a1c5c5de0b3fbb20c2cbe073803a03ea1b1ea1 | [
"Apache-2.0"
] | 1,448 | 2018-10-26T13:55:40.000Z | 2022-03-31T06:15:16.000Z | components/micropython/port/src/moducryptolib_maix.c | mongonta0716/MaixPy | b1a1c5c5de0b3fbb20c2cbe073803a03ea1b1ea1 | [
"Apache-2.0"
] | 418 | 2018-10-26T14:18:26.000Z | 2022-03-31T21:40:25.000Z | components/micropython/port/src/moducryptolib_maix.c | mongonta0716/MaixPy | b1a1c5c5de0b3fbb20c2cbe073803a03ea1b1ea1 | [
"Apache-2.0"
] | 419 | 2018-11-02T09:53:19.000Z | 2022-03-31T15:43:03.000Z | /*
* This file is part of the MicroPython K210 project, https://github.com/loboris/MicroPython_K210_LoBo
*
* The MIT License (MIT)
*
* Copyright (c) 2019 LoBo (https://github.com/loboris)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "py/mpconfig.h"
#if MICROPY_PY_UCRYPTOLIB_MAIX
#include <string.h>
#include "aes.h"
#include "py/objstr.h"
#include "py/runtime.h"
enum {
UCRYPTOLIB_MODE_MIN = 0,
UCRYPTOLIB_MODE_GCM,
UCRYPTOLIB_MODE_CBC,
UCRYPTOLIB_MODE_ECB,
UCRYPTOLIB_MODE_MAX,
};
#define AES_KEYLEN_128 0
#define AES_KEYLEN_192 1
#define AES_KEYLEN_256 2
typedef struct _context
{
/* The buffer holding the encryption or decryption key. */
uint8_t *input_key;
/* The initialization vector. must be 96 bit for gcm, 128 bit for cbc*/
uint8_t iv[16];
} context_t;
typedef struct _mp_obj_aes_t {
mp_obj_base_t base;
context_t ctx;
uint8_t mode;
uint8_t key_len;
} mp_obj_aes_t;
const mp_obj_module_t mp_module_ucryptolib;
//------------------------------------------------------------------------------------------------------------------
STATIC mp_obj_t ucryptolib_aes_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args)
{
mp_arg_check_num(n_args, n_kw, 2, 3, false);
uint8_t iv_len = 12;
// create aes object
mp_obj_aes_t *o = m_new_obj(mp_obj_aes_t);
o->base.type = type;
// get mode
o->mode = mp_obj_get_int(args[1]);
if (o->mode <= UCRYPTOLIB_MODE_MIN || o->mode >= UCRYPTOLIB_MODE_MAX) {
mp_raise_ValueError("wrong mode");
}
if (o->mode == UCRYPTOLIB_MODE_CBC) iv_len = 16;
// get key
mp_buffer_info_t keyinfo;
mp_get_buffer_raise(args[0], &keyinfo, MP_BUFFER_READ);
if ((32 != keyinfo.len) && (24 != keyinfo.len) && (16 != keyinfo.len)) {
mp_raise_ValueError("wrong key length");
}
o->ctx.input_key = keyinfo.buf;
if (keyinfo.len == 32) o->key_len = AES_KEYLEN_256;
else if (keyinfo.len == 24) o->key_len = AES_KEYLEN_192;
else o->key_len = AES_KEYLEN_128;
// get the (optional) IV
memset(o->ctx.iv, 0, sizeof(o->ctx.iv));
for (uint8_t i=0; i<iv_len; i++) {
o->ctx.iv[i] = i;
}
mp_buffer_info_t ivinfo;
ivinfo.buf = NULL;
if ((n_args > 2) && (args[2] != mp_const_none)) {
mp_get_buffer_raise(args[2], &ivinfo, MP_BUFFER_READ);
if (iv_len != ivinfo.len) {
mp_raise_ValueError("wrong IV length");
}
memcpy(o->ctx.iv, ivinfo.buf, iv_len);
}
return MP_OBJ_FROM_PTR(o);
}
//----------------------------------------------------------------------------
STATIC mp_obj_t AES_run(size_t n_args, const mp_obj_t *args, bool encrypt)
{
mp_obj_aes_t *self = MP_OBJ_TO_PTR(args[0]);
// get input
mp_obj_t in_buf = args[1];
mp_obj_t out_buf = MP_OBJ_NULL;
if (n_args > 2) {
// separate output is used
out_buf = args[2];
}
// create output buffer
mp_buffer_info_t in_bufinfo;
mp_get_buffer_raise(in_buf, &in_bufinfo, MP_BUFFER_READ);
if ((in_bufinfo.len % 16) != 0) {
mp_raise_ValueError("input length must be multiple of 16");
}
vstr_t vstr;
mp_buffer_info_t out_bufinfo;
uint8_t *out_buf_ptr;
if (out_buf != MP_OBJ_NULL) {
mp_get_buffer_raise(out_buf, &out_bufinfo, MP_BUFFER_WRITE);
if (out_bufinfo.len < in_bufinfo.len) {
mp_raise_ValueError("output too small");
}
out_buf_ptr = out_bufinfo.buf;
}
else {
vstr_init_len(&vstr, in_bufinfo.len);
out_buf_ptr = (uint8_t*)vstr.buf;
}
if (self->mode == UCRYPTOLIB_MODE_GCM) {
uint8_t gcm_tag[4];
gcm_context_t ctx;
ctx.input_key = self->ctx.input_key;
ctx.iv = self->ctx.iv;
ctx.gcm_aad = NULL;
ctx.gcm_aad_len = 0;
if (!encrypt) {
if (self->key_len == AES_KEYLEN_256) aes_gcm256_hard_decrypt(&ctx, in_bufinfo.buf, in_bufinfo.len, out_buf_ptr, gcm_tag);
else if (self->key_len == AES_KEYLEN_192) aes_gcm192_hard_decrypt(&ctx, in_bufinfo.buf, in_bufinfo.len, out_buf_ptr, gcm_tag);
else aes_gcm128_hard_decrypt(&ctx, in_bufinfo.buf, in_bufinfo.len, out_buf_ptr, gcm_tag);
}
else {
if (self->key_len == AES_KEYLEN_256) aes_gcm256_hard_encrypt(&ctx, in_bufinfo.buf, in_bufinfo.len, out_buf_ptr, gcm_tag);
else if (self->key_len == AES_KEYLEN_192) aes_gcm192_hard_encrypt(&ctx, in_bufinfo.buf, in_bufinfo.len, out_buf_ptr, gcm_tag);
else aes_gcm128_hard_encrypt(&ctx, in_bufinfo.buf, in_bufinfo.len, out_buf_ptr, gcm_tag);
}
}
else if (self->mode == UCRYPTOLIB_MODE_CBC) {
cbc_context_t ctx;
ctx.input_key = self->ctx.input_key;
ctx.iv = self->ctx.iv;
if (!encrypt) {
if (self->key_len == AES_KEYLEN_256) aes_cbc256_hard_decrypt(&ctx, in_bufinfo.buf, in_bufinfo.len, out_buf_ptr);
else if (self->key_len == AES_KEYLEN_192) aes_cbc192_hard_decrypt(&ctx, in_bufinfo.buf, in_bufinfo.len, out_buf_ptr);
else aes_cbc128_hard_decrypt(&ctx, in_bufinfo.buf, in_bufinfo.len, out_buf_ptr);
}
else {
if (self->key_len == AES_KEYLEN_256) aes_cbc256_hard_encrypt(&ctx, in_bufinfo.buf, in_bufinfo.len, out_buf_ptr);
else if (self->key_len == AES_KEYLEN_192) aes_cbc192_hard_encrypt(&ctx, in_bufinfo.buf, in_bufinfo.len, out_buf_ptr);
else aes_cbc128_hard_encrypt(&ctx, in_bufinfo.buf, in_bufinfo.len, out_buf_ptr);
}
}
else {
if (!encrypt) {
if (self->key_len == AES_KEYLEN_256) aes_ecb256_hard_decrypt(self->ctx.input_key, in_bufinfo.buf, in_bufinfo.len, out_buf_ptr);
else if (self->key_len == AES_KEYLEN_192) aes_ecb192_hard_decrypt(self->ctx.input_key, in_bufinfo.buf, in_bufinfo.len, out_buf_ptr);
else aes_ecb128_hard_decrypt(self->ctx.input_key, in_bufinfo.buf, in_bufinfo.len, out_buf_ptr);
}
else {
if (self->key_len == AES_KEYLEN_256) aes_ecb256_hard_encrypt(self->ctx.input_key, in_bufinfo.buf, in_bufinfo.len, out_buf_ptr);
else if (self->key_len == AES_KEYLEN_192) aes_ecb192_hard_encrypt(self->ctx.input_key, in_bufinfo.buf, in_bufinfo.len, out_buf_ptr);
else aes_ecb128_hard_encrypt(self->ctx.input_key, in_bufinfo.buf, in_bufinfo.len, out_buf_ptr);
}
}
if (out_buf != MP_OBJ_NULL) {
return out_buf;
}
return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr);
}
//-------------------------------------------------------------------------
STATIC mp_obj_t ucryptolib_aes_encrypt(size_t n_args, const mp_obj_t *args)
{
return AES_run(n_args, args, true);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(ucryptolib_aes_encrypt_obj, 2, 3, ucryptolib_aes_encrypt);
//-------------------------------------------------------------------------
STATIC mp_obj_t ucryptolib_aes_decrypt(size_t n_args, const mp_obj_t *args)
{
return AES_run(n_args, args, false);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(ucryptolib_aes_decrypt_obj, 2, 3, ucryptolib_aes_decrypt);
/*
//----------------------------------------------------
STATIC mp_obj_t ucryptolib_aes_getIV(mp_obj_t self_in)
{
mp_obj_aes_t *self = MP_OBJ_TO_PTR(self_in);
return mp_obj_new_str_of_type(&mp_type_bytes, self->ctx.iv, (self->mode == UCRYPTOLIB_MODE_GCM) ? 12 : 16);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(ucryptolib_aes_getIV_obj, ucryptolib_aes_getIV);
*/
//===================================================================
STATIC const mp_rom_map_elem_t ucryptolib_aes_locals_dict_table[] = {
{ MP_ROM_QSTR(MP_QSTR_encrypt), MP_ROM_PTR(&ucryptolib_aes_encrypt_obj) },
{ MP_ROM_QSTR(MP_QSTR_decrypt), MP_ROM_PTR(&ucryptolib_aes_decrypt_obj) },
//{ MP_ROM_QSTR(MP_QSTR_getIV), MP_ROM_PTR(&ucryptolib_aes_getIV_obj) },
};
STATIC MP_DEFINE_CONST_DICT(ucryptolib_aes_locals_dict, ucryptolib_aes_locals_dict_table);
//================================================
STATIC const mp_obj_type_t ucryptolib_aes_type = {
{ &mp_type_type },
.name = MP_QSTR_aes,
.make_new = ucryptolib_aes_make_new,
.locals_dict = (void*)&ucryptolib_aes_locals_dict,
};
//=====================================================================
STATIC const mp_rom_map_elem_t mp_module_ucryptolib_globals_table[] = {
{ MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_ucryptolib) },
{ MP_ROM_QSTR(MP_QSTR_aes), MP_ROM_PTR(&ucryptolib_aes_type) },
{ MP_ROM_QSTR(MP_QSTR_MODE_GCM), MP_ROM_INT(UCRYPTOLIB_MODE_GCM) },
{ MP_ROM_QSTR(MP_QSTR_MODE_CBC), MP_ROM_INT(UCRYPTOLIB_MODE_CBC) },
{ MP_ROM_QSTR(MP_QSTR_MODE_ECB), MP_ROM_INT(UCRYPTOLIB_MODE_ECB) },
};
STATIC MP_DEFINE_CONST_DICT(mp_module_ucryptolib_globals, mp_module_ucryptolib_globals_table);
const mp_obj_module_t mp_module_ucryptolib = {
.base = { &mp_type_module },
.globals = (mp_obj_dict_t*)&mp_module_ucryptolib_globals,
};
#endif //MICROPY_PY_UCRYPTOLIB
| 39.065891 | 144 | 0.658299 | [
"object",
"vector"
] |
1cd163a052010a1048ce246c1eee5ca096e38241 | 1,700 | c | C | paddle.c | fudgenuggets12/OriginalPong | 95bcd7b3c044669570775fb5ba7a2bf9cc0c0af9 | [
"CC0-1.0"
] | null | null | null | paddle.c | fudgenuggets12/OriginalPong | 95bcd7b3c044669570775fb5ba7a2bf9cc0c0af9 | [
"CC0-1.0"
] | null | null | null | paddle.c | fudgenuggets12/OriginalPong | 95bcd7b3c044669570775fb5ba7a2bf9cc0c0af9 | [
"CC0-1.0"
] | null | null | null | #include <stdlib.h>
#include <stdio.h>
#include "SDL2\SDL.h"
#include "paddle.h"
void drawPaddle(SDL_Renderer *render, Paddle *paddle)
{
SDL_SetRenderDrawColor(paddle->rendi, paddle->r, paddle->g, paddle->b, paddle->o);
SDL_RenderDrawRect(render, paddle->rect);
SDL_RenderFillRect(render, paddle->rect);
}
void moveUp(Paddle *paddle)
{
paddle->yvel = -4;
}
void moveDown(Paddle *paddle)
{
paddle->yvel = 4;
puts("moving down");
}
void stop(Paddle *paddle)
{
paddle->yvel = 0;
}
Paddle *createPaddle(int w, int h, SDL_Renderer *rend, Uint8 r, Uint8 g, Uint8 b, Uint8 o, int xpos, int ypos)
{
Paddle *paddle = (Paddle*)malloc(sizeof(Paddle));
paddle->width = w;
paddle->height = h;
paddle->rendi = rend;
paddle->xpos = xpos;
paddle->ypos = ypos;
SDL_Rect *rec = (SDL_Rect*)malloc(sizeof(SDL_Rect));
rec->w = w;
rec->h = h;
rec->x = xpos;
rec->y = ypos;
paddle->rect = rec;
paddle->r = r;
paddle->g = g;
paddle->b = b;
paddle->o = o;
paddle->score = 0;
paddle->yvel = 0;
return paddle;
}
void moves(SDL_Renderer *render, Paddle *paddle)
{
paddle->ypos = paddle->ypos + paddle->yvel;
paddle->rect->y = paddle->rect->y + paddle->yvel;
if((paddle->ypos < 0))
{
paddle->ypos = 0;
paddle->rect->y = 0;
}
if((paddle->ypos+paddle->height) > 600)
{
paddle->ypos = 600-paddle->height - 1;
paddle->rect->y = 600-paddle->height - 1;
}
SDL_SetRenderDrawColor(paddle->rendi, paddle->r, paddle->g, paddle->b, paddle->o);
SDL_RenderDrawRect(render, paddle->rect);
SDL_RenderFillRect(render, paddle->rect);
}
| 24.285714 | 110 | 0.598235 | [
"render"
] |
1ce17cd2f88a94ec177aaba06d3d403f5bbc413a | 4,921 | h | C | libraries/VAL/include/FastEnvironment.h | amessing/VAL | 723e6707ff2ef36a732ad1aecc98994edbf5843f | [
"BSD-3-Clause"
] | 65 | 2015-01-08T09:58:01.000Z | 2021-11-16T11:08:31.000Z | libraries/VAL/include/FastEnvironment.h | amessing/VAL | 723e6707ff2ef36a732ad1aecc98994edbf5843f | [
"BSD-3-Clause"
] | 48 | 2015-01-19T01:07:16.000Z | 2021-07-29T18:26:54.000Z | libraries/VAL/include/FastEnvironment.h | amessing/VAL | 723e6707ff2ef36a732ad1aecc98994edbf5843f | [
"BSD-3-Clause"
] | 45 | 2016-01-08T01:57:01.000Z | 2022-03-07T04:00:36.000Z | // Copyright 2019 - University of Strathclyde, King's College London and Schlumberger Ltd
// This source code is licensed under the BSD license found in the LICENSE file in the root directory of this source tree.
#ifndef __FASTENV
#define __FASTENV
#include <vector>
using std::vector;
#include <iterator>
#include <list>
#include "ptree.h"
namespace VAL {
template < class U >
class IDsymbol : public U {
private:
int symId;
public:
IDsymbol(const string &nm, int Id) : U(nm), symId(Id){};
int getId() const { return symId; };
};
template < class T, class U = T >
class IDSymbolFactory : public SymbolFactory< T > {
private:
static int cnt;
int symId;
public:
IDSymbolFactory() : symId(0) { cnt = 0; };
IDSymbolFactory(int n) : symId(n){};
T *build(const string &nm) {
++cnt;
return new IDsymbol< U >(nm, symId++);
};
int numSyms() const { return symId; };
static int getCount() { return cnt; };
};
template < class T, class U >
int IDSymbolFactory< T, U >::cnt = 0;
class id_var_symbol_table : public var_symbol_table {
private:
std::shared_ptr<IDSymbolFactory< var_symbol >> symFac;
public:
id_var_symbol_table() : symFac( std::make_shared<IDSymbolFactory< var_symbol>>()) {
setFactory(symFac);
};
id_var_symbol_table(id_var_symbol_table *i)
: symFac(new IDSymbolFactory< var_symbol >(
IDSymbolFactory< var_symbol >::getCount())) {
setFactory(symFac);
};
int numSyms() const { return symFac->numSyms(); };
};
class IDopTabFactory : public VarTabFactory {
private:
id_var_symbol_table *idv;
public:
var_symbol_table *buildOpTab() {
idv = new id_var_symbol_table;
return idv;
};
var_symbol_table *buildRuleTab() {
idv = new id_var_symbol_table;
return idv;
};
var_symbol_table *buildExistsTab() { return new id_var_symbol_table(idv); };
var_symbol_table *buildForallTab() { return new id_var_symbol_table(idv); };
};
class FastEnvironment {
private:
vector< const_symbol * > syms;
public:
FastEnvironment(int x) : syms(x, static_cast< const_symbol * >(0)){};
FastEnvironment(const FastEnvironment &other) : syms(other.syms){};
void extend(int x) {
syms.resize(syms.size() + x, static_cast< const_symbol * >(0));
};
FastEnvironment *copy() const { return new FastEnvironment(*this); };
const_symbol *operator[](const symbol *s) const {
if (const const_symbol *c = dynamic_cast< const const_symbol * >(s)) {
return const_cast< const_symbol * >(c);
};
return syms[static_cast< const IDsymbol< var_symbol > * >(s)->getId()];
};
const_symbol *&operator[](const symbol *s) {
static const_symbol *c;
if ((c = const_cast< const_symbol * >(
dynamic_cast< const const_symbol * >(s)))) {
return c;
};
return syms[static_cast< const IDsymbol< var_symbol > * >(s)->getId()];
};
typedef vector< const_symbol * >::const_iterator const_iterator;
const_iterator begin() const { return syms.begin(); };
const_iterator end() const { return syms.end(); };
const vector< const_symbol * > &getCore() const { return syms; };
};
template < class TI >
class LiteralParameterIterator {
private:
FastEnvironment *env;
TI pi;
public:
LiteralParameterIterator(FastEnvironment *f, TI p) : env(f), pi(p){};
const_symbol *operator*() { return (*env)[*pi]; };
LiteralParameterIterator &operator++() {
++pi;
return *this;
};
bool operator==(const LiteralParameterIterator< TI > &li) const {
return pi == li.pi;
};
bool operator!=(const LiteralParameterIterator< TI > &li) const {
return pi != li.pi;
};
LiteralParameterIterator< TI > operator+(int x);
};
template < typename TI, typename T >
struct plusIt {
LiteralParameterIterator< TI > operator()(TI pi, FastEnvironment *env,
int x) const {
for (int c = 0; c < x; ++c, ++pi)
;
return LiteralParameterIterator< TI >(env, pi);
};
};
template < typename TI >
struct plusIt< TI, std::random_access_iterator_tag > {
LiteralParameterIterator< TI > operator()(TI pi, FastEnvironment *env,
int x) const {
return LiteralParameterIterator< TI >(env, pi + x);
};
};
template < typename TI >
LiteralParameterIterator< TI > LiteralParameterIterator< TI >::operator+(
int x) {
return plusIt< TI,
typename std::iterator_traits< TI >::iterator_category >()(
pi, env, x);
};
template < class TI >
LiteralParameterIterator< TI > makeIterator(FastEnvironment *f, TI p) {
return LiteralParameterIterator< TI >(f, p);
};
}; // namespace VAL
#endif
| 27.646067 | 122 | 0.620809 | [
"vector"
] |
1cef2f32450fb456181e479485bb932cf36ec27b | 3,264 | h | C | HJQAssetsPicker/HJQImageManager.h | xiaohange/HJQAssetsPicker | 756d0641b6f42c4aa352634fea06297a0340ddf7 | [
"MIT"
] | 5 | 2017-06-20T08:42:54.000Z | 2019-10-25T01:31:52.000Z | HJQAssetsPicker/HJQImageManager.h | XiaoHanGe/HJQAssetsPicker | 756d0641b6f42c4aa352634fea06297a0340ddf7 | [
"MIT"
] | null | null | null | HJQAssetsPicker/HJQImageManager.h | XiaoHanGe/HJQAssetsPicker | 756d0641b6f42c4aa352634fea06297a0340ddf7 | [
"MIT"
] | null | null | null | //
// HJQImageManager.h
// purchasingManager
//
// Created by HaRi on 16/2/18.
// Copyright © 2016年 郑州悉知. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <Photos/Photos.h>
#import <AssetsLibrary/AssetsLibrary.h>
#define IOS9Later ([UIDevice currentDevice].systemVersion.floatValue >= 9.0f)
@class PHFetchResult;
@interface YAlbumModel : NSObject
@property (nonatomic, strong) NSString *name; ///< The album name
@property (nonatomic, assign) NSInteger count; ///< Count of photos the album contain
@property (nonatomic, strong) id result; ///< PHFetchResult<PHAsset> or ALAssetsGroup<ALAsset>
@end
@class PHAsset;
@interface YAssetsModel : NSObject
@property (nonatomic, strong) id asset; ///< PHAsset or ALAsset
@end
@interface HJQImageManager : NSObject<UIAlertViewDelegate>
{
UIAlertView *rightAlertView;
}
@property (nonatomic, strong) ALAssetsLibrary *assetLibrary;
@property (nonatomic, strong) PHCachingImageManager *cachingImageManager;
+ (instancetype)manager;
/// Return YES if Authorized 返回YES如果得到了授权
- (BOOL)authorizationStatusAuthorized;
/**
* 获取相册最后一张图片
*
* @param completion <#completion description#>
*/
- (void)getCameraRollAlbumLastImage:(void(^)(UIImage *placeHoderImage,id asset))completion;
/// Get Album 获得相册/相册数组
- (void)getCameraRollAlbumcompletion:(void (^)(YAlbumModel *model))completion;
/**
* 获取所有相册数据
*
* @param completion <#completion description#>
*/
- (void)getAllAlbumscompletion:(void (^)(NSArray<YAlbumModel *> *models))completion;
/**
* 获取某个相册里所有照片
*
* @param result <#result description#>
* @param completion <#completion description#>
*/
- (void)getAssetsFromFetchResult:(id)result completion:(void (^)(NSArray<YAssetsModel *> *models))completion;
- (void)getAssetFromFetchResult:(id)result atIndex:(NSInteger)index completion:(void (^)(YAssetsModel *model))completion;
/**
* /// Get photo 获得照片封面
*
* @param model <#model description#>
* @param completion <#completion description#>
*/
- (void)getPostImageWithAlbumModel:(YAlbumModel *)model completion:(void (^)(UIImage *postImage))completion;
/**
* 获取屏幕大小尺寸图片
*
* @param asset <#asset description#>
* @param completion <#completion description#>
*/
- (void)getPhotoWithAsset:(id)asset completion:(void (^)(UIImage *photo,NSDictionary *info,BOOL isDegraded))completion;
/**
* 获取制定宽度的图片
*
* @param asset <#asset description#>
* @param photoWidth <#photoWidth description#>
* @param isSynchronous <#isSynchronous description#>
* @param completion <#completion description#>
*/
- (void)getPhotoWithAsset:(id)asset photoWidth:(CGFloat)photoWidth isSynchronous:(BOOL)isSynchronous completion:(void (^)(UIImage *photo,NSDictionary *info,BOOL isDegraded))completion;
/**
* 获取原图
*
* @param asset <#asset description#>
* @param completion <#completion description#>
*/
- (void)getOriginalPhotoWithAsset:(id)asset completion:(void (^)(UIImage *photo,NSDictionary *info))completion;
/**
* 获取系统图片的Data
*
* @param asset <#asset description#>
* @param completion <#completion description#>
*/
- (void)getImageDataWithAsset:(id)asset completion:(void (^)(NSData *imageData))completion;
@end
| 26.322581 | 184 | 0.710478 | [
"model"
] |
1cef3f7efd0d9634ff4350b0c43520200160d5ac | 512 | h | C | iOSOpenDev/frameworks/iTunesStoreUI.framework/Headers/SUScriptViewControllerNativeObject.h | bzxy/cydia | f8c838cdbd86e49dddf15792e7aa56e2af80548d | [
"MIT"
] | 678 | 2017-11-17T08:33:19.000Z | 2022-03-26T10:40:20.000Z | iOSOpenDev/frameworks/iTunesStoreUI.framework/Headers/SUScriptViewControllerNativeObject.h | chenfanfang/Cydia | 5efce785bfd5f1064b9c0f0e29a9cc05aa24cad0 | [
"MIT"
] | 22 | 2019-04-16T05:51:53.000Z | 2021-11-08T06:18:45.000Z | iOSOpenDev/frameworks/iTunesStoreUI.framework/Headers/SUScriptViewControllerNativeObject.h | chenfanfang/Cydia | 5efce785bfd5f1064b9c0f0e29a9cc05aa24cad0 | [
"MIT"
] | 170 | 2018-06-10T07:59:20.000Z | 2022-03-22T16:19:33.000Z | /**
* This header is generated by class-dump-z 0.2b.
*
* Source: /System/Library/PrivateFrameworks/iTunesStoreUI.framework/iTunesStoreUI
*/
#import <iTunesStoreUI/SUScriptNativeObject.h>
@interface SUScriptViewControllerNativeObject : SUScriptNativeObject {
}
- (void)_reloadVisibility; // 0x5e161
- (void)_parentViewControllerChangeNotification:(id)notification; // 0x5e151
- (void)setupNativeObject; // 0x5e0b1
- (void)setScriptObject:(id)object; // 0x5e059
- (void)destroyNativeObject; // 0x5dfc5
@end
| 28.444444 | 82 | 0.775391 | [
"object"
] |
1cf9a3367dc2a22d6a5e174b62970b1ed18ce1f6 | 6,114 | h | C | CPP/Targets/WayFinder/symbian-r6/GuidePreviewPopUpContent.h | wayfinder/Wayfinder-S60-Navigator | 14d1b729b2cea52f726874687e78f17492949585 | [
"BSD-3-Clause"
] | 6 | 2015-12-01T01:12:33.000Z | 2021-07-24T09:02:34.000Z | CPP/Targets/WayFinder/symbian-r6/GuidePreviewPopUpContent.h | wayfinder/Wayfinder-S60-Navigator | 14d1b729b2cea52f726874687e78f17492949585 | [
"BSD-3-Clause"
] | null | null | null | CPP/Targets/WayFinder/symbian-r6/GuidePreviewPopUpContent.h | wayfinder/Wayfinder-S60-Navigator | 14d1b729b2cea52f726874687e78f17492949585 | [
"BSD-3-Clause"
] | 2 | 2017-02-02T19:31:29.000Z | 2018-12-17T21:00:45.000Z | /*
Copyright (c) 1999 - 2010, Vodafone Group Services Ltd
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* 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 Vodafone Group Services Ltd 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.
*/
#ifndef _GUIDE_PREVIEW_POP_UP_CONTENT_H_
#define _GUIDE_PREVIEW_POP_UP_CONTENT_H_
#include <coecntrl.h>
class CGuidePreviewPopUpContent : public CCoeControl
{
public:
/**
* NewL.
* Two-phased constructor.
* Create a CGuidePreviewPopUpContent, which will draw itself to aRect.
*
* @return a pointer to the created instance of CGuidePreviewPopUpContent.
*/
static CGuidePreviewPopUpContent* NewL();
/**
* NewLC.
* Two-phased constructor.
* Create a CGuidePreviewPopUpContent object, which will draw itself
* to aRect.
*
* @return A pointer to the created instance of CGuidePreviewPopUpContent.
*/
static CGuidePreviewPopUpContent* NewLC();
/**
* ~CGuidePreviewPopUpContent
* Virtual Destructor.
*/
virtual ~CGuidePreviewPopUpContent();
protected:
/**
* CGuidePreviewPopUpContent.
* C++ default constructor.
*/
CGuidePreviewPopUpContent();
private:
/**
* ConstructL
* 2nd phase constructor.
* Perform the second phase construction of a
* CGuidePreviewPopUpContent object.
*
* @param aRect The initial rect for the content.
*/
void ConstructL();
private: // Functions from base classes
/**
* From CCoeControl, Draw
* Draw this CGuidePreviewPopUpContent to the screen.
* If the user has given a text, it is also printed to the center of
* the screen.
*
* @param aRect the rectangle of this view that needs updating
*/
virtual void Draw(const TRect& aRect) const;
protected: // Functions from base classes
/**
* From CoeControl, SizeChanged.
* Called by framework when the view size is changed.
*/
virtual void SizeChanged();
public: // Functions from base classes
/**
* From CoeControl, MinimumSize.
*/
virtual TSize MinimumSize();
public: // Public functions
void InitialiseL(const TRect& aRect);
/**
* Set up the size and layout of the preview pop up control.
*
* @param aRect The rect that is available to the control.
* @param aPadding The padding to use between labels and borders.
*/
void SetSizeAndLayout(TRect aRect, TInt aPadding);
/**
* Set the current and next street labels.
*/
void SetStreetsL(const TDesC& aCurrName, const TDesC& aNextName);
/**
* Sets the distance to goal label.
*/
void SetDistanceToGoalL(const TDesC& aDistance);
/**
* Sets the estimated time to goal label.
*/
void SetEtgL(const TDesC& aTimeLeft);
/**
* Sets the estimated time of arrival label.
*/
void SetEtaL(const TDesC& aArrivalTime);
/**
* Switches night mode on and off.
*/
void SetNightModeL(TBool aNightMode, TRgb aFgColor, TRgb aBgColor);
private:
/**
* Convenience function to set the correct font in the labels.
*/
void UpdateLabelsFont();
/**
* Function to hide and unhide labels based on available space.
*/
void UpdateLabelsVisibility();
private: // Private members
/// Label that writes the current street title text
class CEikLabel* iCurrStreetTitle;
/// Label that writes the actaul name of the current street
class CEikLabel* iCurrStreetLabel;
/// Label that writes the next street title text
class CEikLabel* iNextStreetTitle;
/// Label that writes the actual name of the next street
class CEikLabel* iNextStreetLabel;
/// Label that writes the distance left title text
class CEikLabel* iDistLeftTitle;
/// Label that writes the distance left
class CEikLabel* iDistLeftLabel;
/// Label that writes the time left title text
class CEikLabel* iTimeLeftTitle;
/// Label that writes the time left
class CEikLabel* iTimeLeftLabel;
/// Label that writes the arrival time title text
class CEikLabel* iArrTimeTitle;
/// Label that writes the arrival time
class CEikLabel* iArrTimeLabel;
/// The rect available to the different components in the container
TRect iComponentRect;
/// The padding to use between the components
TInt iPadding;
/// The text color according to the current skin.
TRgb iSkinTextColor;
/// Bool flag for night mode true or false.
TBool iIsNightMode;
/// The night mode text color.
TRgb iNightTextColor;
/// The night mode background color.
TRgb iNightBackColor;
};
#endif // _GUIDE_PREVIEW_POP_UP_CONTAINER_H_
| 32.521277 | 756 | 0.695126 | [
"object"
] |
f79b8952f8efa1a7890c1d5582e6577250bf5979 | 3,631 | h | C | include/hdlConvertor/verilogConvertor/exprParser.h | zegervdv/hdlConvertor | 1f16295d46243563cdf97b7594198f24b7121ff7 | [
"MIT"
] | null | null | null | include/hdlConvertor/verilogConvertor/exprParser.h | zegervdv/hdlConvertor | 1f16295d46243563cdf97b7594198f24b7121ff7 | [
"MIT"
] | null | null | null | include/hdlConvertor/verilogConvertor/exprParser.h | zegervdv/hdlConvertor | 1f16295d46243563cdf97b7594198f24b7121ff7 | [
"MIT"
] | null | null | null | #pragma once
#include <antlr4-runtime.h>
#include <vector>
#include <string>
#include <memory>
#include <hdlConvertor/verilogConvertor/Verilog2001Parser/Verilog2001Parser.h>
#include <hdlConvertor/hdlObjects/operatorType.h>
#include <hdlConvertor/hdlObjects/expr.h>
#include <hdlConvertor/notImplementedLogger.h>
#include <hdlConvertor/verilogConvertor/literalParser.h>
#include <hdlConvertor/verilogConvertor/attributeParser.h>
namespace hdlConvertor {
namespace verilog {
class VerExprParser {
public:
typedef hdlObjects::Expr Expr;
typedef hdlObjects::OperatorType OperatorType;
typedef Verilog2001_antlr::Verilog2001Parser Verilog2001Parser;
static Expr * visitExpression(Verilog2001Parser::ExpressionContext * ctx);
static Expr * visitNet_lvalue(Verilog2001Parser::Net_lvalueContext * ctx);
static Expr * visitNet_concatenation(
Verilog2001Parser::Net_concatenationContext * ctx);
static Expr * visitHierarchical_net_identifier(
Verilog2001Parser::Hierarchical_net_identifierContext * ctx);
static Expr * visitConstant_expression(
Verilog2001Parser::Constant_expressionContext * ctx);
static Expr * visitDimension(Verilog2001Parser::DimensionContext * ctx);
static Expr * visitDimension_constant_expression(
Verilog2001Parser::Dimension_constant_expressionContext * ctx);
static Expr * visitRange_expression(
Verilog2001Parser::Range_expressionContext * ctx);
static Expr * visitRange_(Verilog2001Parser::Range_Context * ctx);
static OperatorType visitUnary_operator(
Verilog2001Parser::Unary_operatorContext * ctx);
static OperatorType visitBinary_operator(
Verilog2001Parser::Binary_operatorContext * ctx);
static Expr * visitTerm(Verilog2001Parser::TermContext * ctx);
static Expr * visitPrimary(Verilog2001Parser::PrimaryContext * ctx);
static Expr * visitConstant_function_call(
Verilog2001Parser::Constant_function_callContext * ctx);
static Expr * visitSystem_function_call(
Verilog2001Parser::System_function_callContext * ctx);
static Expr * visitFunction_call(
Verilog2001Parser::Function_callContext * ctx);
static Expr * visitHierarchical_function_identifier(
Verilog2001Parser::Hierarchical_function_identifierContext * ctx);
static Expr * visitMultiple_concatenation(
Verilog2001Parser::Multiple_concatenationContext * ctx);
static Expr * visitConcatenation(
Verilog2001Parser::ConcatenationContext * ctx);
static Expr * visitHierarchical_identifier(
Verilog2001Parser::Hierarchical_identifierContext * ctx);
static Expr * visitEscaped_hierarchical_identifier(
Verilog2001Parser::Escaped_hierarchical_identifierContext * ctx);
static Expr * visitSimple_hierarchical_identifier(
Verilog2001Parser::Simple_hierarchical_identifierContext * ctx);
static Expr * visitSimple_hierarchical_branch(
Verilog2001Parser::Simple_hierarchical_branchContext * ctx);
static Expr * visitIdentifier(Verilog2001Parser::IdentifierContext * ctx);
static Expr * visitEscaped_hierarchical_branch(
Verilog2001Parser::Escaped_hierarchical_branchContext * ctx);
static Expr * visitMintypmax_expression(
Verilog2001Parser::Mintypmax_expressionContext * ctx);
static std::vector<Expr*> * visitEvent_expression(
Verilog2001Parser::Event_expressionContext * ctx);
static Expr * visitEvent_primary(
Verilog2001Parser::Event_primaryContext * ctx);
static Expr * visitVariable_lvalue(
Verilog2001Parser::Variable_lvalueContext * ctx);
static Expr * visitVariable_concatenation(
Verilog2001Parser::Variable_concatenationContext* ctx);
static Expr * visitArrayed_identifier(
Verilog2001Parser::Arrayed_identifierContext * ctx);
};
}
}
| 43.746988 | 78 | 0.820711 | [
"vector"
] |
f79ddd61d552ee7e03efbc7eeb02c9116b50e0c0 | 1,315 | h | C | 3p/ClassLib/Windows/Common Dialogs/fontdialog.h | stbrenner/NiLogViewer | e6fe2b57da6d7bd61983cf7e8f0ee3139cc0ce20 | [
"MIT"
] | 2 | 2018-11-20T15:58:08.000Z | 2021-12-15T14:51:10.000Z | 3p/ClassLib/Windows/Common Dialogs/fontdialog.h | ymx/NiLogViewer | e6fe2b57da6d7bd61983cf7e8f0ee3139cc0ce20 | [
"MIT"
] | 1 | 2016-08-12T10:34:04.000Z | 2016-08-12T10:34:04.000Z | 3p/ClassLib/Windows/Common Dialogs/fontdialog.h | ymx/NiLogViewer | e6fe2b57da6d7bd61983cf7e8f0ee3139cc0ce20 | [
"MIT"
] | 1 | 2016-08-09T10:44:48.000Z | 2016-08-09T10:44:48.000Z | #ifndef _FONTDIALOG_H_
#define _FONTDIALOG_H_
//
// fontdialog.h
//
// (C) Copyright 2000 Jan van den Baard.
// All Rights Reserved.
//
#include "commondialog.h"
// A wrapper for the Font common dialog.
class ClsFontDialog : public ClsCommonDialog
{
_NO_COPY( ClsFontDialog );
public:
// Constructor. Initialize members.
ClsFontDialog()
{
// Set font color to black.
m_crColor = RGB( 0, 0, 0 );
// Clear LOGFONT structure.
memset(( void * )&m_LogFont, 0, sizeof( LOGFONT ));
}
// Destructor. Does nothing.
virtual ~ClsFontDialog()
{;}
// Get the font color.
inline COLORREF GetColor() const
{ return m_crColor; }
// Popup the font dialog.
BOOL DoModal( ClsWindow *parent, LOGFONT *pLogFont = NULL, DWORD dwFlags = CF_BOTH | CF_EFFECTS, int x = CW_USEDEFAULT, int y = CW_USEDEFAULT );
// Operator overloads.
operator COLORREF() const
{ return m_crColor; }
operator LOGFONT*()
{ return &m_LogFont; }
protected:
// Hook procedure. This will attach the dialog
// to the object.
static UINT CALLBACK HookProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam );
// Overidable. Called just before the dialog is opened.
virtual BOOL PreShowDialog( LPCHOOSEFONT pChooseFont )
{ return TRUE; }
// Data.
COLORREF m_crColor;
LOGFONT m_LogFont;
};
#endif // _FONTDIALOG_H_ | 22.672414 | 145 | 0.704183 | [
"object"
] |
f79e91c93fcc811baea8c605ac773b83e93d1eb3 | 8,084 | h | C | toolkit/viewer.h | teenylasers/eggshell | 7d1239eb1b143b11b5ccd1029d9bacdd601c8e4e | [
"ICU",
"OpenSSL"
] | null | null | null | toolkit/viewer.h | teenylasers/eggshell | 7d1239eb1b143b11b5ccd1029d9bacdd601c8e4e | [
"ICU",
"OpenSSL"
] | null | null | null | toolkit/viewer.h | teenylasers/eggshell | 7d1239eb1b143b11b5ccd1029d9bacdd601c8e4e | [
"ICU",
"OpenSSL"
] | null | null | null | // Copyright (C) 2014-2020 Russell Smith.
//
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the Free
// Software Foundation, either version 3 of the License, or (at your option)
// any later version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
// more details.
#ifndef __TOOLKIT_VIEWER_H__
#define __TOOLKIT_VIEWER_H__
#include "camera.h"
#include "error.h"
// An opengl window that maintains camera state and allows camera motion via
// mouse and key commands:
//
// * Pan: Right button drag, or on a mac trackpad use cmd + two-finger swipe.
// * Zoom: Scroll wheel, or ctrl + right button drag, or on a mac use a
// two-finger swipe.
// * Rotate: Middle button drag, or on mac use cmd + left click to start a
// rotation, continue holding down cmd and move the mouse to complete the
// rotation.
class GLViewerBase {
public:
GLViewerBase();
// The maximum number of independently movable cameras.
enum { MAX_CAMERAS = 10 };
// Return the current camera, and its index for SwitchCamera().
Camera &GetCamera() const { return *camera_; }
int GetCameraIndex() const { return camera_ - cameras_; };
// Set/get the perspective flag for the current camera. True means a
// perspective projection, false means an orthographic projection. The
// default is perspective.
void SetPerspective(bool perspective);
bool GetPerspective() const { return camera_->perspective; }
// Set the perspective view angle for the current camera. The default is 45
// degrees.
void SetViewAngle(double angle);
// Allow or disallow camera rotation. Disallowing it is useful in
// orthographic mode when dealing with strictly 2D content. The default is
// allowed.
void AllowCameraRotation(bool allow) { allow_rotation_ = allow; }
// Ensure that the entire bounding box defined by GetBoundingBox() is
// visible. This maintains the current camera orientation.
void ZoomExtents();
// Zoom in or out, enlarging the view around the center point by the given
// scale factor. A scale factor less than 1 zooms in. If 'center' is given it
// is used as the center point, otherwise the center point is read from the
// current GL window size and depth buffer.
void Zoom(double scale_factor, Eigen::Vector3d center);
void Zoom(double scale_factor);
// Switch to the given camera (0..MAX_CAMERAS-1).
void SwitchCamera(int camera_number);
// Adjust the camera direction as specified and ensure that the entire
// bounding box defined by GetBoundingBox() is visible.
enum Direction {
LOOK_AT_XY_PLANE_FROM_PLUS_Z, LOOK_AT_YX_PLANE_FROM_PLUS_Z,
LOOK_AT_XY_PLANE_FROM_MINUS_Z, LOOK_AT_YX_PLANE_FROM_MINUS_Z,
LOOK_AT_XZ_PLANE_FROM_PLUS_Y, LOOK_AT_ZX_PLANE_FROM_PLUS_Y,
LOOK_AT_XZ_PLANE_FROM_MINUS_Y, LOOK_AT_ZX_PLANE_FROM_MINUS_Y,
LOOK_AT_YZ_PLANE_FROM_PLUS_X, LOOK_AT_ZY_PLANE_FROM_PLUS_X,
LOOK_AT_YZ_PLANE_FROM_MINUS_X, LOOK_AT_ZY_PLANE_FROM_MINUS_X,
};
void Look(Direction direction);
// Convert window pixel coordinates to/from model coordinates. If no depth
// buffer is available then PixelToModelCoords() chooses a depth to get a
// model z coordinate of zero. This generally only makes sense with an
// orthographic camera. ModelToPixelCoords() returns false if the resulting
// pixel/depth is outside the view frustum, but in that case it will still
// try to return useful coordinates.
void PixelToModelCoords(int x, int y, Eigen::Vector3d *model_pt);
bool ModelToPixelCoords(const Eigen::Vector3d &model_pt,
double *px, double *py);
// ********** Virtual functions supplied in subclasses. Most non-abstract
// functions have default implementations that do nothing.
// Draw everything into the current GL context. 2D objects render themselves
// in the Z=0 plane but are otherwise indistinguishable from 3D objects.
virtual void Draw() = 0;
// Call this from Draw() to apply the camera transformation M * projection *
// model-view to the current program.
void ApplyCameraTransformations(const Eigen::Matrix4d &M =
Eigen::Matrix4d::Identity());
// Return the bounding box of the entire scene so that e.g. ZoomExtents()
// knows what region to display. The array elements are [xmin, xmax, ymin,
// ymax, zmin, zmax].
virtual void GetBoundingBox(double bounds[6]) = 0;
// Handle mouse events at x,y (in opengl viewport coordinates). If button is
// true the mouse button was pressed, otherwise it was released. The model_pt
// is the model point corresponding to the mouse location at the last button
// press or scroll wheel motion. All camera-moving mouse actions will be
// filtered out.
virtual void HandleClick(int x, int y, bool button,
const Eigen::Vector3d &model_pt);
virtual void HandleDrag(int x, int y, const Eigen::Vector3d &model_pt);
// Trigger a windowing system redraw of the window.
virtual void Redraw() = 0;
// Allow use of OpenGL outside of painting functions.
virtual void MakeOpenGLContextCurrent() = 0;
// Return the OpenGL viewport size in raw pixels not points (e.g. on retina
// displays each point can be 2x2 pixels).
virtual void GetScaledClientSize(int *window_width, int *window_height) = 0;
// Find the model point that was clicked on. The x,y are window coordinates.
// The default implementation calls PixelToModelCoords() but this may not
// generate sensible model coordinates for all renderings.
virtual void FindModelPoint(int x, int y, Eigen::Vector3d *model_pt);
// The framebuffer object that we render into. The default implementation
// returns 0.
virtual uint32_t FramebufferObject();
protected:
// Drawing state.
bool have_depth_buffer_; // Property of current GL context
Camera cameras_[MAX_CAMERAS]; // All cameras
Camera *camera_; // Current camera, points into cameras_
bool allow_rotation_; // Allow camera rotation
int last_x_, last_y_; // Last mouse position
int buttons_; // Mask of currently pressed buttons
int the_button_; // The button that is UI-active
Eigen::Vector3d model_pt_; // Model coords at start of drag
bool rotate_click_; // Modified left click to rotate?
bool pan_click_; // Modified left click to pan?
// Get the current window aspect ratio (width/height).
double GetAspectRatio();
// Apply the viewport transformation.
void ApplyViewport();
};
//***************************************************************************
// Qt implementation.
#ifdef QT_CORE_LIB
#include <QOpenGLWidget>
#include <QGestureEvent>
class GLViewer : public QOpenGLWidget, public GLViewerBase {
public:
typedef QWidget ParentType;
explicit GLViewer(ParentType *parent);
// Event handling functions.
void mouseDoubleClickEvent(QMouseEvent *event) override;
void mouseMoveEvent(QMouseEvent *event) override;
void mousePressEvent(QMouseEvent *event) override;
void mouseReleaseEvent(QMouseEvent *event) override;
void wheelEvent(QWheelEvent *event) override;
void leaveEvent(QEvent *event) override;
void gestureEvent(QGestureEvent *event);
bool event(QEvent *event) override;
void MouseEvent(QMouseEvent *event, bool move_event, const char *name);
// Overridden virtual functions of GLViewerBase.
void Redraw() override;
void MakeOpenGLContextCurrent() override;
void GetScaledClientSize(int *window_width, int *window_height) override;
uint32_t FramebufferObject() override;
private:
void initializeGL() override;
void resizeGL(int w, int h) override;
void paintGL() override;
};
#endif // QT_CORE_LIB
#endif
| 41.45641 | 79 | 0.716848 | [
"render",
"object",
"model",
"3d"
] |
f7a6ad75dd75b2b74faaf589c905c6ccf7c7905c | 2,649 | h | C | ace/tao/orbsvcs/orbsvcs/Notify/Notify_Collection.h | tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective | 1b0172cdb78757fd17898503aaf6ce03d940ef28 | [
"Apache-1.1"
] | 46 | 2015-12-04T17:12:58.000Z | 2022-03-11T04:30:49.000Z | ace/tao/orbsvcs/orbsvcs/Notify/Notify_Collection.h | tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective | 1b0172cdb78757fd17898503aaf6ce03d940ef28 | [
"Apache-1.1"
] | null | null | null | ace/tao/orbsvcs/orbsvcs/Notify/Notify_Collection.h | tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective | 1b0172cdb78757fd17898503aaf6ce03d940ef28 | [
"Apache-1.1"
] | 23 | 2016-10-24T09:18:14.000Z | 2022-02-25T02:11:35.000Z | // Notify_Collection.h,v 1.2 2000/07/30 03:04:48 bala Exp
// ==========================================================================
//
// = LIBRARY
// Orbsvcs
//
// = FILENAME
// Notify_Collection.h
//
// = DESCRIPTION
// Collection types used by Notify
//
// = AUTHOR
// Pradeep Gore <pradeep@cs.wustl.edu>
//
// ==========================================================================
#ifndef TAO_NOTIFY_COLLECTION_H
#define TAO_NOTIFY_COLLECTION_H
#include "ace/pre.h"
#include "orbsvcs/CosNotifyCommC.h"
#if !defined (ACE_LACKS_PRAGMA_ONCE)
# pragma once
#endif /* ACE_LACKS_PRAGMA_ONCE */
#include "orbsvcs/ESF/ESF_Worker.h"
#include "notify_export.h"
#include "Notify_Event.h"
template<class PROXY> class TAO_ESF_Proxy_Collection;
template<class T> class ACE_Unbounded_Set;
class TAO_Notify_EventListener;
class TAO_Notify_UpdateListener;
class TAO_Notify_EventType;
typedef TAO_ESF_Proxy_Collection<TAO_Notify_EventListener> TAO_Notify_EventListener_List;
// A list of event listeners that are looking for the same event type.
typedef TAO_ESF_Proxy_Collection<TAO_Notify_UpdateListener> TAO_Notify_UpdateListener_List;
// A list of update listeners who want to be notified about publish/subscribe changes.
class TAO_Notify_Export TAO_Notify_EventType_List : public ACE_Unbounded_Set <TAO_Notify_EventType>
{
// = TITLE
// TAO_Notify_EventType_List
//
// = DESCRIPTION
// Allows operations using the CosNotification::EventTypeSeq type.
//
typedef ACE_Unbounded_Set <TAO_Notify_EventType> inherited;
public:
void populate (CosNotification::EventTypeSeq& event_type_seq);
// Populate <event_type_seq> with the contents of this object.
void insert_seq (const CosNotification::EventTypeSeq& event_type_seq);
// insert the contents of <event_type_seq> into this object.
void remove_seq (const CosNotification::EventTypeSeq& event_type_seq);
// remove the contents of <event_type_seq> from this object.
};
// ****************************************************************
// = Collection Iterators.
class TAO_Notify_Export TAO_Notify_Shutdown_Worker : public TAO_ESF_Worker<TAO_Notify_EventListener>
{
// = TITLE
// TAO_Notify_Shutdown_Worker
//
// = DESCRIPTION
// Shutdown each listener
//
public:
TAO_Notify_Shutdown_Worker (void);
// = TAO_ESF_Worker method
void work (TAO_Notify_EventListener* listener, CORBA::Environment &ACE_TRY_ENV);
};
// ****************************************************************
#include "ace/post.h"
#endif /* TAO_NOTIFY_COLLECTION_H */
| 29.764045 | 101 | 0.660627 | [
"object"
] |
f7c0117dca5709d7eb272ee495c4a14e264167c9 | 3,630 | h | C | include/RuntimeDatabase/RuntimeDatabase.h | MisterVento3/SteelEngine | 403511b53b6575eb869b4ccfbda18514f0838e8d | [
"MIT"
] | 3 | 2017-05-10T10:58:17.000Z | 2018-10-30T09:50:26.000Z | include/RuntimeDatabase/RuntimeDatabase.h | mVento3/SteelEngine | 403511b53b6575eb869b4ccfbda18514f0838e8d | [
"MIT"
] | 3 | 2017-05-09T21:17:09.000Z | 2020-02-24T14:46:22.000Z | include/RuntimeDatabase/RuntimeDatabase.h | mVento3/SteelEngine | 403511b53b6575eb869b4ccfbda18514f0838e8d | [
"MIT"
] | null | null | null | #pragma once
#include "RuntimeDatabase/IRuntimeDatabase.h"
#include "vector"
#include "unordered_map"
#include "map"
#include "stack"
#include "Memory/Allocator.h"
#include "Memory/LinearAllocator.h"
#include "Memory/PoolAllocator.h"
#include "Memory/Internal/PoolAllocator.h"
#include "Memory/Container/Vector.h"
#include "Memory/Container/Stack.h"
#include "Utils/TupleMaker.h"
#if defined(SE_WINDOWS) || defined(_WINDOWS)
#undef max
#undef min
#endif
#define SE_MAX_TYPES 100
#define SE_MAX_TYPE_SIZE 512
#define SE_MAX_OBJECTS 512
#define SE_MAX_VARIANTS 2000
#define SE_MAX_VARIANT_SIZE 512
int main(int argc, char* argv[]);
namespace SteelEngine {
struct IReflectionData;
class Reflection;
class RelfectionRecorder;
class Variant;
class MetaDataInfo;
namespace HotReloader {
struct IRuntimeObject;
struct RuntimeReloader;
}
namespace Graphics {
namespace Utils {
class Renderer3D;
}
}
namespace Utils {
class RenderContext;
}
struct ConstrucedObject
{
size_t m_ObjectID;
size_t m_ConstructorID;
size_t m_TypeID;
ITuple* m_Args;
HotReloader::IRuntimeObject* m_Object;
ConstrucedObject(size_t objectID, size_t constructorID, size_t typeID, ITuple* args, HotReloader::IRuntimeObject* obj) :
m_ObjectID(objectID),
m_ConstructorID(constructorID),
m_TypeID(typeID),
m_Args(args),
m_Object(obj)
{
}
};
class RuntimeDatabase : public IRuntimeDatabase
{
friend int ::main(int argc, char* argv[]);
public:
typedef void*(*GetStateCallback)();
typedef Container::Vector<ConstrucedObject> ConstructedObjectsVector;
static const size_t s_InvalidID = std::numeric_limits<size_t>::max();
struct ISubDatabase
{
virtual void Init(Memory::Allocator* allocator) = 0;
};
struct Reflection : public ISubDatabase
{
friend class RuntimeDatabase;
friend struct IReflectionData;
friend class SteelEngine::Reflection;
friend class ReflectionRecorder;
private:
Memory::Allocator* m_TypesAllocator;
IReflectionData** m_Types;
size_t m_TypesSize;
void Init(Memory::Allocator* allocator) override;
};
struct HotReloader : public ISubDatabase
{
friend class RuntimeDatabase;
friend struct IReflectionData;
friend class SteelEngine::HotReloader::RuntimeReloader;
private:
Container::Vector<ConstrucedObject>* m_Objects;
Container::Stack<size_t>* m_AvailablePerObjectIDs;
void Init(Memory::Allocator* allocator) override;
};
struct Variant : public ISubDatabase
{
friend class RuntimeDatabase;
friend class SteelEngine::Variant;
private:
Memory::Allocator* m_VariantsAllocator;
Container::Stack<size_t>* m_AvailablePerVariantIDs;
void Init(Memory::Allocator* allocator) override;
};
struct RenderContext : public ISubDatabase
{
friend class RuntimeDatabase;
friend class SteelEngine::Graphics::Utils::Renderer3D;
friend struct SteelEngine::Utils::RenderContext;
private:
Utils::RenderContext* m_Context;
void Init(Memory::Allocator* allocator) override;
};
private:
void Init() override;
public:
RuntimeDatabase();
~RuntimeDatabase();
void* m_RootMemory;
size_t m_RootMemorySize;
Memory::Allocator* m_RootMemoryAllocator;
RuntimeDatabase::Reflection* m_ReflectionDatabase;
RuntimeDatabase::HotReloader* m_HotReloaderDatabase;
RuntimeDatabase::Variant* m_VariantDatabase;
RuntimeDatabase::RenderContext* m_RenderContextDatabase;
size_t GetNextPerVariantID() override;
void PushPerVariantID(size_t id) override;
size_t GetNextPerObjectID() override;
void PushPerObjectID(size_t id) override;
};
} | 21.22807 | 122 | 0.753444 | [
"vector"
] |
f7c16553c2b27d738ff99d9aaf7d3fc15ba839d8 | 5,355 | h | C | Extensions/PathBehavior/PathBehavior.h | sutao80216/GDevelop | 79461bf01cc0c626e2f094d3fca940d643f93d76 | [
"MIT"
] | 1 | 2018-11-23T11:56:08.000Z | 2018-11-23T11:56:08.000Z | Extensions/PathBehavior/PathBehavior.h | sutao80216/GDevelop | 79461bf01cc0c626e2f094d3fca940d643f93d76 | [
"MIT"
] | 9 | 2020-04-04T19:26:47.000Z | 2022-03-25T18:41:20.000Z | Extensions/PathBehavior/PathBehavior.h | sutao80216/GDevelop | 79461bf01cc0c626e2f094d3fca940d643f93d76 | [
"MIT"
] | 2 | 2020-03-02T05:20:41.000Z | 2021-05-10T03:59:05.000Z | /**
GDevelop - Path Behavior Extension
Copyright (c) 2010-2016 Florian Rival (Florian.Rival@gmail.com)
This project is released under the MIT License.
*/
#ifndef PATHBEHAVIOR_H
#define PATHBEHAVIOR_H
#include <SFML/System/Vector2.hpp>
#include <map>
#include "GDCpp/Runtime/Project/Behavior.h"
#include "GDCpp/Runtime/Project/Object.h"
class RuntimeScene;
namespace gd {
class SerializerElement;
}
namespace gd {
class Layout;
}
class PathBehaviorEditor;
class RuntimeScenePathDatas;
/**
* Behavior that position object on a predefined path.
*/
class GD_EXTENSION_API PathBehavior : public Behavior {
friend class PathBehaviorEditor;
public:
PathBehavior();
PathBehavior(const PathBehavior &cl);
PathBehavior &operator=(const PathBehavior &cl);
void Init(const PathBehavior &cl);
virtual ~PathBehavior();
virtual Behavior *Clone() const { return new PathBehavior(*this); }
#if defined(GD_IDE_ONLY)
/**
* Serialize the behavior
*/
virtual void SerializeTo(gd::SerializerElement &element) const;
void SerializePathsTo(gd::SerializerElement &element) const;
#endif
/**
* Unserialize the behavior
*/
virtual void UnserializeFrom(const gd::SerializerElement &element);
void UnserializePathsFrom(const gd::SerializerElement &element);
#if defined(GD_IDE_ONLY)
/**
* Called when user wants to edit the behavior.
*/
virtual void EditBehavior(wxWindow *parent,
gd::Project &game_,
gd::Layout *scene,
gd::MainFrameWrapper &mainFrameWrapper_);
#endif
void Reset();
void EnterSegment(std::size_t segmentNumber);
float GetOffsetX() const;
void SetOffsetX(float off);
float GetOffsetY() const;
void SetOffsetY(float off);
void SetReverseAtEnd(bool set = true) { reverseAtEnd = set; };
bool ReverseAtEnd() const { return reverseAtEnd; };
void SetStopAtEnd(bool set = true) { stopAtEnd = set; };
bool StopAtEnd() const { return stopAtEnd; };
void SetFollowAngle(bool set = true) { followAngle = set; };
bool FollowAngle() const { return followAngle; };
void SetSpeed(float sp);
float GetSpeed() const;
void SetAngleOffset(float off);
float GetAngleOffset() const;
void Reverse();
/**
Get a path stored by the behavior
*/
const std::vector<sf::Vector2f> &GetPath(const gd::String &_name) const;
/**
Modify a path of the behavior but doesn't change the current path
(note : need to call ChangeCurrentPath even if the path is the current.)
*/
void SetPath(const gd::String &_name, std::vector<sf::Vector2f> _path);
/**
Set a new path to the behavior
*/
void ChangeCurrentPath(const gd::String &_name);
const gd::String &GetCurrentPathName() const;
/**
Make a copy of the path to make it usable to the behavior.
Don't need to be called (already call by DoPreStepEvent and DoPostStepEvent if
the needed path isn't loaded).
*/
void LoadPath(RuntimeScene &scene);
void DeleteAllPaths(); ///< Only used by the editor
/**
Return a vector containing the name of all the local paths.
*/
std::vector<gd::String> GetListOfPathsNames() const;
void SetCurrentSegment(std::size_t seg);
int GetCurrentSegment();
float GetPositionOnSegment(); ///< position belongs to 0 to 1 (percentage of
///< the current segment)
void SetPositionOnSegment(float pos);
static gd::String GetStringFromCoordsVector(
const std::vector<sf::Vector2f> &vec,
char32_t coordsSep = U'\n',
char32_t composantSep = U';');
static std::vector<sf::Vector2f> GetCoordsVectorFromString(
const gd::String &str,
char32_t coordsSep = U'\n',
char32_t composantSep = U';');
private:
virtual void DoStepPreEvents(RuntimeScene &scene);
virtual void DoStepPostEvents(RuntimeScene &scene);
float GetAngleOfSegment(sf::Vector2f &seg);
// sf::Vector2f has been chosen to represent position, but any simple vector2
// class would do the job.
gd::String pathName; ///< Name of the current path (the path may be not
///< loaded, especially in Edit mode)
std::vector<sf::Vector2f> path; ///< Copy of current path (used for movement
///< to allow the behavior to reverse it)
sf::Vector2f offset; ///< Offset of the path relative to the scene's origin
float speed;
float timeOnSegment;
float totalSegmentTime;
std::size_t currentSegment;
bool stopAtEnd;
bool reverseAtEnd;
bool followAngle; ///< If true, the object is rotated according to the
///< current segment's angle.
float angleOffset; ///< Angle offset (added to the angle calculated with the
///< segment)
bool isPathLoaded; ///< True if the path is already loaded, otherwise false.
int futureSegment; ///< if the current segment has to be changed, it contains
///< a positive number, otherwise -1.
float futurePosition; ///< if the current position on segment has to be
///< changed, it contains a positive number, otherwise
///< -1.
std::map<gd::String, std::vector<sf::Vector2f> >
localePaths; ///< Contains all the object path
RuntimeScenePathDatas *runtimeScenesPathDatas;
};
#endif // PATHBEHAVIOR_H
| 30.426136 | 80 | 0.678058 | [
"object",
"vector"
] |
f7c6499f19ab2e17eecbc952abdbdce2c7e60d56 | 407 | h | C | YareEngine/Source/Utilities/IOHelper.h | Resoona/Yare | fc94403575285099ce93ef556f68c77b815577d9 | [
"MIT"
] | 2 | 2020-03-01T13:56:45.000Z | 2020-03-06T01:41:00.000Z | YareEngine/Source/Utilities/IOHelper.h | Riyusuna/Yare | fc94403575285099ce93ef556f68c77b815577d9 | [
"MIT"
] | null | null | null | YareEngine/Source/Utilities/IOHelper.h | Riyusuna/Yare | fc94403575285099ce93ef556f68c77b815577d9 | [
"MIT"
] | null | null | null | #ifndef YARE_IOHELPER_H
#define YARE_IOHELPER_H
#include <fstream>
#include <string>
#include <vector>
#include "Core/DataStructures.h"
namespace Yare::Utilities {
std::vector<std::string> readFile(const std::string& filename);
void loadMesh(const std::string& filePath, std::vector<Vertex>& vertices, std::vector<uint32_t>& indices);
} // namespace Yare::Utilities
#endif // YARE_IOHELPER_H
| 23.941176 | 110 | 0.739558 | [
"vector"
] |
f7c97920afe0e29e5b0032d972fbb06c724a7318 | 1,689 | h | C | OneCodeTeam/How to bind command to a button in the DataTemplate in universal Windows apps/[C++]-How to bind command to a button in the DataTemplate in universal Windows apps/C++/CppUnvsAppCommandBindInDT/CppUnvsAppCommandBindInDT.Shared/BoolToStringConverter.h | zzgchina888/msdn-code-gallery-microsoft | 21cb9b6bc0da3b234c5854ecac449cb3bd261f29 | [
"MIT"
] | 2 | 2022-01-21T01:40:58.000Z | 2022-01-21T01:41:10.000Z | OneCodeTeam/How to bind command to a button in the DataTemplate in universal Windows apps/[C++]-How to bind command to a button in the DataTemplate in universal Windows apps/C++/CppUnvsAppCommandBindInDT/CppUnvsAppCommandBindInDT.Shared/BoolToStringConverter.h | zzgchina888/msdn-code-gallery-microsoft | 21cb9b6bc0da3b234c5854ecac449cb3bd261f29 | [
"MIT"
] | 1 | 2022-03-15T04:21:41.000Z | 2022-03-15T04:21:41.000Z | OneCodeTeam/How to bind command to a button in the DataTemplate in universal Windows apps/[C++]-How to bind command to a button in the DataTemplate in universal Windows apps/C++/CppUnvsAppCommandBindInDT/CppUnvsAppCommandBindInDT.Shared/BoolToStringConverter.h | zzgchina888/msdn-code-gallery-microsoft | 21cb9b6bc0da3b234c5854ecac449cb3bd261f29 | [
"MIT"
] | null | null | null | /****************************** Module Header ******************************\
* Module Name: BoolToStringConverter.h
* Project: CppUnvsAppCommandBindInDT
* Copyright (c) Microsoft Corporation.
*
* This is a Converter which converts between Boolean type and String type
*
* This source is subject to the Microsoft Public License.
* See http://www.microsoft.com/en-us/openness/licenses.aspx#MPL.
* All other rights reserved.
*
* 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.
\***************************************************************************/
#pragma once
using namespace Platform;
using namespace Windows::UI::Xaml::Interop;
namespace CppUnvsAppCommandBindInDT
{
[Windows::Foundation::Metadata::WebHostHidden]
public ref class BoolToSexConverter sealed : Windows::UI::Xaml::Data::IValueConverter
{
public:
BoolToSexConverter();
virtual Object^ Convert(Object^ value, TypeName targetType, Object^ parameter, String^ language);
virtual Object^ ConvertBack(Object^ value, TypeName targetType, Object^ parameter, String^ language);
private:
~BoolToSexConverter();
};
[Windows::Foundation::Metadata::WebHostHidden]
public ref class BoolToVipConverter sealed : Windows::UI::Xaml::Data::IValueConverter
{
public:
BoolToVipConverter();
virtual Object^ Convert(Object^ value, TypeName targetType, Object^ parameter, String^ language);
virtual Object^ ConvertBack(Object^ value, TypeName targetType, Object^ parameter, String^ language);
private:
~BoolToVipConverter();
};
}
| 38.386364 | 103 | 0.707519 | [
"object"
] |
f7d2968cd36e8d910421a7c9c0ae70e29ca56a36 | 22,122 | h | C | cnpy.h | dankoschier/cnpy | 75e6a97c732d37f2246b76aecead34fdbcbbb5fc | [
"MIT"
] | 2 | 2018-08-28T15:13:30.000Z | 2018-08-28T15:53:52.000Z | cnpy.h | dankoschier/cnpy | 75e6a97c732d37f2246b76aecead34fdbcbbb5fc | [
"MIT"
] | null | null | null | cnpy.h | dankoschier/cnpy | 75e6a97c732d37f2246b76aecead34fdbcbbb5fc | [
"MIT"
] | null | null | null | //Copyright (C) 2011 Carl Rogers
//Released under MIT License
//license available in LICENSE file, or at http://www.opensource.org/licenses/mit-license.php
#ifndef LIBCNPY_H_
#define LIBCNPY_H_
#include <string>
#include <vector>
#include <iostream>
#include <cassert>
#include <map>
#include <memory>
#include <numeric>
#include <complex>
#include <regex>
#ifdef CNPY_USE_ZLIB
#include <zlib.h>
#endif
namespace cnpy
{
struct NpyArray
{
NpyArray(const std::vector<size_t> &_shape, size_t _word_size, bool _fortran_order) : shape(_shape), word_size(_word_size), fortran_order(_fortran_order)
{
num_vals = 1;
for (size_t i = 0; i < shape.size(); i++)
num_vals *= shape[i];
data_holder = std::shared_ptr<std::vector<char>>(
new std::vector<char>(num_vals * word_size));
}
NpyArray() : shape(0), word_size(0), fortran_order(0), num_vals(0) {}
template <typename T>
T *data()
{
return reinterpret_cast<T *>(&(*data_holder)[0]);
}
template <typename T>
const T *data() const
{
return reinterpret_cast<T *>(&(*data_holder)[0]);
}
template <typename T>
std::vector<T> as_vec() const
{
const T *p = data<T>();
return std::vector<T>(p, p + num_vals);
}
size_t num_bytes() const
{
return data_holder->size();
}
std::shared_ptr<std::vector<char>> data_holder;
std::vector<size_t> shape;
size_t word_size;
bool fortran_order;
size_t num_vals;
};
using npz_t = std::map<std::string, NpyArray>;
inline constexpr char is_big_endian()
{
auto const x = 1;
return (((char *)&x)[0]) ? '<' : '>';
}
template <typename T>
std::vector<char> create_npy_header(const std::vector<size_t> &shape);
inline void parse_npy_header(FILE *fp, size_t &word_size, std::vector<size_t> &shape, bool &fortran_order)
{
char buffer[256];
size_t res = fread(buffer, sizeof(char), 11, fp);
if (res != 11)
throw std::runtime_error("parse_npy_header: failed fread");
std::string header = fgets(buffer, 256, fp);
assert(header[header.size() - 1] == '\n');
size_t loc1, loc2;
//fortran order
loc1 = header.find("fortran_order");
if (loc1 == std::string::npos)
throw std::runtime_error("parse_npy_header: failed to find header keyword: 'fortran_order'");
loc1 += 16;
fortran_order = (header.substr(loc1, 4) == "True" ? true : false);
//shape
loc1 = header.find("(");
loc2 = header.find(")");
if (loc1 == std::string::npos || loc2 == std::string::npos)
throw std::runtime_error("parse_npy_header: failed to find header keyword: '(' or ')'");
std::regex num_regex("[0-9][0-9]*");
std::smatch sm;
shape.clear();
std::string str_shape = header.substr(loc1 + 1, loc2 - loc1 - 1);
while (std::regex_search(str_shape, sm, num_regex))
{
shape.push_back(std::stoi(sm[0].str()));
str_shape = sm.suffix().str();
}
//endian, word size, data type
//byte order code | stands for not applicable.
//not sure when this applies except for byte array
loc1 = header.find("descr");
if (loc1 == std::string::npos)
throw std::runtime_error("parse_npy_header: failed to find header keyword: 'descr'");
loc1 += 9;
bool littleEndian = (header[loc1] == '<' || header[loc1] == '|' ? true : false);
assert(littleEndian);
//char type = header[loc1+1];
//assert(type == map_type(T));
std::string str_ws = header.substr(loc1 + 2);
loc2 = str_ws.find("'");
word_size = atoi(str_ws.substr(0, loc2).c_str());
}
inline void parse_npy_header(unsigned char *buffer, size_t &word_size, std::vector<size_t> &shape, bool &fortran_order)
{
//std::string magic_string(buffer,6);
uint8_t major_version = *reinterpret_cast<uint8_t *>(buffer + 6);
uint8_t minor_version = *reinterpret_cast<uint8_t *>(buffer + 7);
uint16_t header_len = *reinterpret_cast<uint16_t *>(buffer + 8);
std::string header(reinterpret_cast<char *>(buffer + 9), header_len);
size_t loc1, loc2;
//fortran order
loc1 = header.find("fortran_order") + 16;
fortran_order = (header.substr(loc1, 4) == "True" ? true : false);
//shape
loc1 = header.find("(");
loc2 = header.find(")");
std::regex num_regex("[0-9][0-9]*");
std::smatch sm;
shape.clear();
std::string str_shape = header.substr(loc1 + 1, loc2 - loc1 - 1);
while (std::regex_search(str_shape, sm, num_regex))
{
shape.push_back(std::stoi(sm[0].str()));
str_shape = sm.suffix().str();
}
//endian, word size, data type
//byte order code | stands for not applicable.
//not sure when this applies except for byte array
loc1 = header.find("descr") + 9;
bool littleEndian = (header[loc1] == '<' || header[loc1] == '|' ? true : false);
assert(littleEndian);
//char type = header[loc1+1];
//assert(type == map_type(T));
std::string str_ws = header.substr(loc1 + 2);
loc2 = str_ws.find("'");
word_size = atoi(str_ws.substr(0, loc2).c_str());
}
inline void parse_zip_footer(FILE *fp, uint16_t &nrecs, size_t &global_header_size, size_t &global_header_offset)
{
std::vector<char> footer(22);
fseek(fp, -22, SEEK_END);
size_t res = fread(&footer[0], sizeof(char), 22, fp);
if (res != 22)
throw std::runtime_error("parse_zip_footer: failed fread");
uint16_t disk_no, disk_start, nrecs_on_disk, comment_len;
disk_no = *(uint16_t *)&footer[4];
disk_start = *(uint16_t *)&footer[6];
nrecs_on_disk = *(uint16_t *)&footer[8];
nrecs = *(uint16_t *)&footer[10];
global_header_size = *(uint32_t *)&footer[12];
global_header_offset = *(uint32_t *)&footer[16];
comment_len = *(uint16_t *)&footer[20];
assert(disk_no == 0);
assert(disk_start == 0);
assert(nrecs_on_disk == nrecs);
assert(comment_len == 0);
}
#ifdef CNPY_USE_ZLIB
inline NpyArray load_the_npz_array(FILE *fp, uint32_t compr_bytes, uint32_t uncompr_bytes)
{
std::vector<unsigned char> buffer_compr(compr_bytes);
std::vector<unsigned char> buffer_uncompr(uncompr_bytes);
size_t nread = fread(&buffer_compr[0], 1, compr_bytes, fp);
if (nread != compr_bytes)
throw std::runtime_error("load_the_npy_file: failed fread");
int err;
z_stream d_stream;
d_stream.zalloc = Z_NULL;
d_stream.zfree = Z_NULL;
d_stream.opaque = Z_NULL;
d_stream.avail_in = 0;
d_stream.next_in = Z_NULL;
err = inflateInit2(&d_stream, -MAX_WBITS);
d_stream.avail_in = compr_bytes;
d_stream.next_in = &buffer_compr[0];
d_stream.avail_out = uncompr_bytes;
d_stream.next_out = &buffer_uncompr[0];
err = inflate(&d_stream, Z_FINISH);
err = inflateEnd(&d_stream);
std::vector<size_t> shape;
size_t word_size;
bool fortran_order;
cnpy::parse_npy_header(&buffer_uncompr[0], word_size, shape, fortran_order);
cnpy::NpyArray array(shape, word_size, fortran_order);
size_t offset = uncompr_bytes - array.num_bytes();
memcpy(array.data<unsigned char>(), &buffer_uncompr[0] + offset, array.num_bytes());
return array;
}
#endif
inline NpyArray load_the_npy_file(FILE *fp)
{
std::vector<size_t> shape;
size_t word_size;
bool fortran_order;
cnpy::parse_npy_header(fp, word_size, shape, fortran_order);
cnpy::NpyArray arr(shape, word_size, fortran_order);
size_t nread = fread(arr.data<char>(), 1, arr.num_bytes(), fp);
if (nread != arr.num_bytes())
throw std::runtime_error("load_the_npy_file: failed fread");
return arr;
}
inline npz_t npz_load(std::string fname)
{
FILE *fp = fopen(fname.c_str(), "rb");
if (!fp)
{
throw std::runtime_error("npz_load: Error! Unable to open file " + fname + "!");
}
cnpy::npz_t arrays;
while (1)
{
std::vector<char> local_header(30);
size_t headerres = fread(&local_header[0], sizeof(char), 30, fp);
if (headerres != 30)
throw std::runtime_error("npz_load: failed fread");
//if we've reached the global header, stop reading
if (local_header[2] != 0x03 || local_header[3] != 0x04)
break;
//read in the variable name
uint16_t name_len = *(uint16_t *)&local_header[26];
std::string varname(name_len, ' ');
size_t vname_res = fread(&varname[0], sizeof(char), name_len, fp);
if (vname_res != name_len)
throw std::runtime_error("npz_load: failed fread");
//erase the lagging .npy
varname.erase(varname.end() - 4, varname.end());
//read in the extra field
uint16_t extra_field_len = *(uint16_t *)&local_header[28];
if (extra_field_len > 0)
{
std::vector<char> buff(extra_field_len);
size_t efield_res = fread(&buff[0], sizeof(char), extra_field_len, fp);
if (efield_res != extra_field_len)
throw std::runtime_error("npz_load: failed fread");
}
uint16_t compr_method = *reinterpret_cast<uint16_t *>(&local_header[0] + 8);
uint32_t compr_bytes = *reinterpret_cast<uint32_t *>(&local_header[0] + 18);
uint32_t uncompr_bytes = *reinterpret_cast<uint32_t *>(&local_header[0] + 22);
if (compr_method == 0)
{
arrays[varname] = load_the_npy_file(fp);
}
else
{
#ifdef CNPY_USE_ZLIB
arrays[varname] = load_the_npz_array(fp, compr_bytes, uncompr_bytes);
#else
throw std::runtime_error("npz_load: archive compressed and zlib not available");
#endif
}
}
fclose(fp);
return arrays;
}
inline NpyArray npz_load(std::string fname, std::string varname)
{
FILE *fp = fopen(fname.c_str(), "rb");
if (!fp)
throw std::runtime_error("npz_load: Unable to open file " + fname);
while (1)
{
std::vector<char> local_header(30);
size_t header_res = fread(&local_header[0], sizeof(char), 30, fp);
if (header_res != 30)
throw std::runtime_error("npz_load: failed fread");
//if we've reached the global header, stop reading
if (local_header[2] != 0x03 || local_header[3] != 0x04)
break;
//read in the variable name
uint16_t name_len = *(uint16_t *)&local_header[26];
std::string vname(name_len, ' ');
size_t vname_res = fread(&vname[0], sizeof(char), name_len, fp);
if (vname_res != name_len)
throw std::runtime_error("npz_load: failed fread");
vname.erase(vname.end() - 4, vname.end()); //erase the lagging .npy
//read in the extra field
uint16_t extra_field_len = *(uint16_t *)&local_header[28];
fseek(fp, extra_field_len, SEEK_CUR); //skip past the extra field
uint16_t compr_method = *reinterpret_cast<uint16_t *>(&local_header[0] + 8);
uint32_t compr_bytes = *reinterpret_cast<uint32_t *>(&local_header[0] + 18);
uint32_t uncompr_bytes = *reinterpret_cast<uint32_t *>(&local_header[0] + 22);
if (vname == varname)
{
NpyArray array;
if (compr_method == 0)
{
array = load_the_npy_file(fp);
}
else
{
#ifdef CNPY_USE_ZLIB
array = load_the_npz_array(fp, compr_bytes, uncompr_bytes);
#else
throw std::runtime_error("npz_load: archive compressed and zlib not available");
#endif
}
fclose(fp);
return array;
}
else
{
//skip past the data
uint32_t size = *(uint32_t *)&local_header[22];
fseek(fp, size, SEEK_CUR);
}
}
fclose(fp);
//if we get here, we haven't found the variable in the file
throw std::runtime_error("npz_load: Variable name " + varname + " not found in " + fname);
}
inline NpyArray npy_load(std::string fname)
{
FILE *fp = fopen(fname.c_str(), "rb");
if (!fp)
throw std::runtime_error("npy_load: Unable to open file " + fname);
NpyArray arr = load_the_npy_file(fp);
fclose(fp);
return arr;
}
template <typename T>
inline std::vector<char> &operator+=(std::vector<char> &lhs, const T rhs)
{
//write in little endian
for (size_t byte = 0; byte < sizeof(T); byte++)
{
char val = *((char *)&rhs + byte);
lhs.push_back(val);
}
return lhs;
}
template <>
inline std::vector<char> &operator+=(std::vector<char> &lhs, const std::string rhs)
{
lhs.insert(lhs.end(), rhs.begin(), rhs.end());
return lhs;
}
template <>
inline std::vector<char> &operator+=(std::vector<char> &lhs, const char *rhs)
{
//write in little endian
size_t len = strlen(rhs);
lhs.reserve(len);
for (size_t byte = 0; byte < len; byte++)
{
lhs.push_back(rhs[byte]);
}
return lhs;
}
template <typename T>
inline void npy_save(std::string fname, const T *data, const std::vector<size_t> shape, std::string mode = "w")
{
FILE *fp = NULL;
std::vector<size_t> true_data_shape; //if appending, the shape of existing + new data
if (mode == "a")
fp = fopen(fname.c_str(), "r+b");
if (fp)
{
//file exists. we need to append to it. read the header, modify the array size
size_t word_size;
bool fortran_order;
parse_npy_header(fp, word_size, true_data_shape, fortran_order);
assert(!fortran_order);
if (word_size != sizeof(T))
{
std::cout << "libcnpy error: " << fname << " has word size " << word_size << " but npy_save appending data sized " << sizeof(T) << "\n";
assert(word_size == sizeof(T));
}
if (true_data_shape.size() != shape.size())
{
std::cout << "libcnpy error: npy_save attempting to append misdimensioned data to " << fname << "\n";
assert(true_data_shape.size() != shape.size());
}
for (size_t i = 1; i < shape.size(); i++)
{
if (shape[i] != true_data_shape[i])
{
std::cout << "libcnpy error: npy_save attempting to append misshaped data to " << fname << "\n";
assert(shape[i] == true_data_shape[i]);
}
}
true_data_shape[0] += shape[0];
}
else
{
fp = fopen(fname.c_str(), "wb");
true_data_shape = shape;
}
std::vector<char> header = create_npy_header<T>(true_data_shape);
size_t nels = std::accumulate(shape.begin(), shape.end(), 1, std::multiplies<size_t>());
fseek(fp, 0, SEEK_SET);
fwrite(&header[0], sizeof(char), header.size(), fp);
fseek(fp, 0, SEEK_END);
fwrite(data, sizeof(T), nels, fp);
fclose(fp);
}
inline uint32_t crc32_(uint32_t crc, const uint8_t *buf, size_t len)
{
int k;
crc = ~crc;
while (len--)
{
crc ^= *buf++;
for (k = 0; k < 8; k++)
crc = crc & 1 ? (crc >> 1) ^ 0xedb88320 : crc >> 1;
}
return ~crc;
}
template <typename T>
inline void npz_save(std::string zipname, std::string fname, const T *data, const std::vector<size_t> &shape, std::string mode = "w")
{
//first, append a .npy to the fname
fname += ".npy";
//now, on with the show
FILE *fp = NULL;
uint16_t nrecs = 0;
size_t global_header_offset = 0;
std::vector<char> global_header;
if (mode == "a")
fp = fopen(zipname.c_str(), "r+b");
if (fp)
{
//zip file exists. we need to add a new npy file to it.
//first read the footer. this gives us the offset and size of the global header
//then read and store the global header.
//below, we will write the the new data at the start of the global header then append the global header and footer below it
size_t global_header_size;
parse_zip_footer(fp, nrecs, global_header_size, global_header_offset);
fseek(fp, global_header_offset, SEEK_SET);
global_header.resize(global_header_size);
size_t res = fread(&global_header[0], sizeof(char), global_header_size, fp);
if (res != global_header_size)
{
throw std::runtime_error("npz_save: header read error while adding to existing zip");
}
fseek(fp, global_header_offset, SEEK_SET);
}
else
{
fp = fopen(zipname.c_str(), "wb");
}
std::vector<char> npy_header = create_npy_header<T>(shape);
size_t nels = std::accumulate(shape.begin(), shape.end(), 1, std::multiplies<size_t>());
size_t nbytes = nels * sizeof(T) + npy_header.size();
//get the CRC of the data to be added
uint32_t crc = crc32_(0, (uint8_t *)&npy_header[0], npy_header.size());
crc = crc32_(crc, (uint8_t *)data, nels * sizeof(T));
//build the local header
std::vector<char> local_header;
local_header += "PK"; //first part of sig
local_header += (uint16_t)0x0403; //second part of sig
local_header += (uint16_t)20; //min version to extract
local_header += (uint16_t)0; //general purpose bit flag
local_header += (uint16_t)0; //compression method
local_header += (uint16_t)0; //file last mod time
local_header += (uint16_t)0; //file last mod date
local_header += (uint32_t)crc; //crc
local_header += (uint32_t)nbytes; //compressed size
local_header += (uint32_t)nbytes; //uncompressed size
local_header += (uint16_t)fname.size(); //fname length
local_header += (uint16_t)0; //extra field length
local_header += fname;
//build global header
global_header += "PK"; //first part of sig
global_header += (uint16_t)0x0201; //second part of sig
global_header += (uint16_t)20; //version made by
global_header.insert(global_header.end(), local_header.begin() + 4, local_header.begin() + 30);
global_header += (uint16_t)0; //file comment length
global_header += (uint16_t)0; //disk number where file starts
global_header += (uint16_t)0; //internal file attributes
global_header += (uint32_t)0; //external file attributes
global_header += (uint32_t)global_header_offset; //relative offset of local file header, since it begins where the global header used to begin
global_header += fname;
//build footer
std::vector<char> footer;
footer += "PK"; //first part of sig
footer += (uint16_t)0x0605; //second part of sig
footer += (uint16_t)0; //number of this disk
footer += (uint16_t)0; //disk where footer starts
footer += (uint16_t)(nrecs + 1); //number of records on this disk
footer += (uint16_t)(nrecs + 1); //total number of records
footer += (uint32_t)global_header.size(); //nbytes of global headers
footer += (uint32_t)(global_header_offset + nbytes + local_header.size()); //offset of start of global headers, since global header now starts after newly written array
footer += (uint16_t)0; //zip file comment length
//write everything
fwrite(&local_header[0], sizeof(char), local_header.size(), fp);
fwrite(&npy_header[0], sizeof(char), npy_header.size(), fp);
fwrite(data, sizeof(T), nels, fp);
fwrite(&global_header[0], sizeof(char), global_header.size(), fp);
fwrite(&footer[0], sizeof(char), footer.size(), fp);
fclose(fp);
}
template <typename T>
inline void npy_save(std::string fname, const std::vector<T> data, std::string mode = "w")
{
std::vector<size_t> shape;
shape.push_back(data.size());
npy_save(fname, &data[0], shape, mode);
}
template <typename T>
inline void npz_save(std::string zipname, std::string fname, const std::vector<T> data, std::string mode = "w")
{
std::vector<size_t> shape;
shape.push_back(data.size());
npz_save(zipname, fname, &data[0], shape, mode);
}
template <typename T>
inline constexpr char map_type()
{
if constexpr (std::is_floating_point<T>::value)
{
return 'f';
}
if constexpr (std::is_integral<T>::value)
{
if (std::is_signed<T>::value)
{
return 'i';
}
else
{
return 'u';
}
}
if constexpr (std::is_same<T, bool>::value)
{
return 'b';
}
if constexpr (std::is_same<std::complex<double>, T>::value ||
std::is_same<std::complex<long double>, T>::value ||
std::is_same<std::complex<float>, T>::value)
{
return 'c';
}
return '?';
}
template <typename T>
inline std::vector<char>
create_npy_header(const std::vector<size_t> &shape)
{
std::vector<char> dict;
dict += "{'descr': '";
dict += is_big_endian();
dict += map_type<T>();
dict += std::to_string(sizeof(T));
dict += "', 'fortran_order': False, 'shape': (";
dict += std::to_string(shape[0]);
for (size_t i = 1; i < shape.size(); i++)
{
dict += ", ";
dict += std::to_string(shape[i]);
}
if (shape.size() == 1)
dict += ",";
dict += "), }";
//pad with spaces so that preamble+dict is modulo 16 bytes. preamble is 10 bytes. dict needs to end with \n
int remainder = 16 - (10 + dict.size()) % 16;
dict.insert(dict.end(), remainder, ' ');
dict.back() = '\n';
std::vector<char> header;
header += (char)0x93;
header += "NUMPY";
header += (char)0x01; //major version of numpy format
header += (char)0x00; //minor version of numpy format
header += (uint16_t)dict.size();
header.insert(header.end(), dict.begin(), dict.end());
return header;
}
} // namespace cnpy
#endif
| 32.532353 | 172 | 0.598544 | [
"shape",
"vector"
] |
f7d3a3fdf1338c602861db8a0775417e4a8ab961 | 9,059 | h | C | include/math_functions.h | chenxuhao/GraphAIBench | ba799487946eed92d9e616b079b6dc17650dcc67 | [
"MIT"
] | 2 | 2022-01-19T14:44:50.000Z | 2022-02-05T09:38:45.000Z | include/math_functions.h | chenxuhao/GraphAIBench | ba799487946eed92d9e616b079b6dc17650dcc67 | [
"MIT"
] | null | null | null | include/math_functions.h | chenxuhao/GraphAIBench | ba799487946eed92d9e616b079b6dc17650dcc67 | [
"MIT"
] | null | null | null | #pragma once
#include "global.h"
#ifdef USE_MKL
#include <mkl.h>
inline void* _malloc(size_t size) {return mkl_malloc(size,64);}
inline void _free(void* ptr) {return mkl_free(ptr);}
#else
#include <cblas.h>
inline void* _malloc(size_t size) {return malloc(size);}
inline void _free(void* ptr) {return free(ptr);}
#endif
void init_glorot(size_t dim_x, size_t dim_y, vec_t &weight, unsigned seed);
// symmetric sparse matrix transpose
void symmetric_csr_transpose(int N, int nnz, int* A_idx_ptr, int* A_nnz_idx,
float* A_nonzeros, float* &B_nonzeros);
// get accuracy for single-class problems
float masked_accuracy_single(int begin, int end, int count, int num_classes,
mask_t* masks, float* preds, label_t* ground_truth);
// get accuracy for multi-class problems
float masked_accuracy_multi(int begin, int end, int count, int num_classes,
mask_t* masks, float* preds, label_t* ground_truth);
void matmul_naive(const size_t x, const size_t y, const size_t z,
const float* A, const float* B, float* C);
void matmul(const size_t x, const size_t y, const size_t z,
const float_t* A, const float_t* B, float* C,
bool transA = false, bool transB = false, bool accum = false);
void l2norm(int n, int dim, const float* in, float* out);
void d_l2norm(int n, int dim, const float* feat_in, const float* grad_in, float* grad_out);
void bias_mv(int n, int len, float* x, float* b);
void reduce_sum(int n, int len, float* x, float* a);
void reduce_sum(int n, int len, float* x, vec_t &a);
// single-precision dense matrix multiply
void sgemm_cpu(const CBLAS_TRANSPOSE TransA, const CBLAS_TRANSPOSE TransB,
const int M, const int N, const int K, const float alpha,
const float* A, const float* B, const float beta, float* C);
void csr2csc(int nrows, int ncols, int nnz,
const float* values, const int* rowptr, const int* colidx,
float* valuesT, int* rowptrT, int* colidxT);
// single-precision sparse matrix dense matrix multiply, C = A * B, A is sparse
void csrmm_cpu(const int M, const int N, const int K, const int nnz,
const float alpha, float* A_nonzeros, int* A_idx_ptr,
int* A_nonzero_idx, const float* B, const float beta, float* C, bool transA = false);
void spmm(size_t x, size_t y, size_t z, size_t nnz,
float* A_nonzeros, int* A_idx_ptr, int* A_nnz_idx,
const float* B, float* C, float* temp = NULL,
bool transA = false, bool transB = false, bool accum = false);
// matrix-vector multiply
void mvmul(const CBLAS_TRANSPOSE TransA, const int M, const int N,
const float alpha, const float* A, const float* x, const float beta, float* y);
//! add 2 arrays for n elements
void vadd_cpu(int n, const float* a, const float* b, float* out);
void scaled_vadd_cpu(int n, const float a, const float* x, const float* y, float* z);
// atomic y[i] += x[i]
void atomic_vreduce_cpu(size_t n, const float* x, float* y);
//! multiply n elements of vector by scalar
void scal(size_t n, const float alpha, float* x);
void scale(int n, const float alpha, const float* x, float* y);
void mul_scalar(size_t n, const float alpha, const float* x, float* y);
//! do dot product of 2 vectors
float dot(int n, const float* x, const float* y);
// concatenation of two vectors into one
void concat(size_t n, const float* x, const float* y, float* z);
// SAXPY stands for Single-precision A*X Plus Y"
void axpy(size_t n, const float a, float* x, float* y);
// Returns the index of the maximum value
int argmax(int num, const float* arr);
//! clear n elements of a vector
void clear_cpu(int n, float* in);
//! copy vector from in -> out; first len elements
void copy_cpu(size_t len, const float* in, float* out);
// dropout functions randomly remove weights
void dropout_cpu(size_t n, size_t m, float scale, float dropout_rate,
const float* in, mask_t* mask, float* out);
// dropout derivative: use existing dropouts in masks instead of generating them;
void d_dropout_cpu(size_t n, size_t m, float scale, const float* in,
const mask_t* mask, float* out);
void leaky_relu(float epsilon, float in, float &out);
void d_leaky_relu(float epsilon, float in, float data, float &out);
void relu_cpu(size_t n, const float* in, float* out);
void d_relu_cpu(size_t n, const float* in, const float* data, float* out);
void leaky_relu_cpu(size_t n, float epsilon, const float* in, float* out);
void d_leaky_relu_cpu(size_t n, float epsilon, const float* in, const float* data, float* out);
void softmax(size_t n, const float* in, float* out);
void d_softmax(int n, const float* p, const float* dp, float* dy);
void sigmoid(size_t n, const float* in, float* out);
void d_sigmoid(size_t n, const float*, const float* p, float* dy, const float* dp);
float cross_entropy(size_t n, const float* y, const float* p);
void d_cross_entropy(size_t n, const float* y, const float* p, float* d);
float sigmoid_cross_entropy(size_t n, const label_t* y, const float* p);
// use sigmoid instead of softmax for multi-class datasets, e.g. ppi, yelp and amazon
//inline float sigmoid_func(float x) { return 0.5 * tanh(0.5 * x) + 0.5; }
inline float sigmoid_func(float x) { return 1. / (1. + expf(-x)); }
// GPU operators
bool isnan_gpu(int n, const float_t* array); // does array contain any 'nan' element
void init_const_gpu(int n, float_t value, float_t* array);
void copy_gpu(int len, const float_t* in, float_t* out);
void vadd_gpu(const int n, const float_t* a, const float_t* b, float_t* out); // vector add
void axpy_gpu(const int n, const float_t a, const float_t* x, float_t* y); // axpy
void relu_gpu(const int n, const float_t* in, float_t* out); // ReLU
void d_relu_gpu(const int n, const float_t* in_diff, const float_t* data, float_t* out_diff); // ReLU derivative
void leaky_relu_gpu(const int n, const float_t epsilon, const float_t* in, float_t* out); // Leaky ReLU
void d_leaky_relu_gpu(const int n, const float_t epsilon,
const float_t* in_diff, const float_t* data,
float_t* out_diff); // Leaky ReLU derivative
void dropout_gpu(int n, float scale, float drop_rate, const float* in, mask_t* masks, float* out); // dropout
void d_dropout_gpu(int n, float scale, const float* in, const mask_t* masks, float* out); // dropout derivative
void sgemm_gpu(const CBLAS_TRANSPOSE TransA, const CBLAS_TRANSPOSE TransB,
const int M, const int N, const int K, const float alpha,
const float* A, const float* B, const float beta, float* C);
void csrmm_gpu(const int M, const int N, const int K, const int nnz,
const float alpha, const float* A_nonzeros, const int* A_idx_ptr,
const int* A_nonzero_idx, const float* B, const float beta,
float* trans_C, float* C);
void softmax_cross_entropy_gpu(int len, int begin, int end,
const float_t* in_data, const mask_t* masks,
const label_t* labels, float_t* loss,
float_t* out_data);
void d_softmax_cross_entropy_gpu(int len, int bengin, int end,
const mask_t* masks, const label_t* labels,
const float_t* out_data, float_t* diff);
void sigmoid_cross_entropy_gpu(int len, int begin, int end,
const float_t* in_data, const mask_t* masks,
const label_t* labels, float_t* loss,
float_t* out_data);
void d_sigmoid_cross_entropy_gpu(int len, int bengin, int end,
const mask_t* masks, const label_t* labels,
const float_t* out_data, float_t* diff);
void scal_gpu(const int n, const float alpha, float* X);
void add_scalar_gpu(const int n, const float_t alpha, float_t* Y);
void rng_uniform_gpu(size_t n, const float_t a, const float_t b, float_t* r);
void l2_norm_gpu(size_t x, size_t y, const float_t* in, float_t* out);
void d_l2_norm_gpu(size_t x, size_t y, const float_t* in_data, float_t* in_diff, float_t* out_diff);
acc_t l2_norm_gpu(int n, const float_t* in);
acc_t masked_avg_loss_gpu(int begin, int end, int count, mask_t* masks, float_t* loss);
bool is_allocated_device(float_t* data);
void copy_masks_device(int n, mask_t* h_masks, mask_t*& d_masks);
void float_malloc_device(int n, float_t*& ptr);
void float_free_device(float_t*& ptr);
void copy_float_device(int n, float* h_ptr, float* d_ptr);
void copy_float_host(int n, const float* d_ptr, float* h_ptr);
void uint_malloc_device(int n, uint32_t*& ptr);
void uint_free_device(uint32_t*& ptr);
void copy_uint_device(int n, uint32_t* h_ptr, uint32_t* d_ptr);
void uint8_malloc_device(int n, uint8_t*& ptr);
void uint8_free_device(uint8_t*& ptr);
void copy_uint8_device(int n, uint8_t* h_ptr, uint8_t* d_ptr);
void gpu_rng_uniform(size_t n, float* r);
| 51.765714 | 112 | 0.684292 | [
"vector"
] |
f7f2a9eef7efbabd57daf8ff59d51e43e8faf523 | 2,207 | c | C | contrib/shuffle_neon/unshuffle2_neon/unshuffle2_neon_bucle.c | DimitriPapadopoulos/c-blosc2 | 0531e8a988738e09672fd6bff78b119565ea9236 | [
"BSD-3-Clause"
] | 245 | 2015-08-20T23:05:27.000Z | 2022-03-31T19:20:56.000Z | contrib/shuffle_neon/unshuffle2_neon/unshuffle2_neon_bucle.c | DimitriPapadopoulos/c-blosc2 | 0531e8a988738e09672fd6bff78b119565ea9236 | [
"BSD-3-Clause"
] | 260 | 2015-09-04T16:25:59.000Z | 2022-03-30T16:26:17.000Z | contrib/shuffle_neon/unshuffle2_neon/unshuffle2_neon_bucle.c | DimitriPapadopoulos/c-blosc2 | 0531e8a988738e09672fd6bff78b119565ea9236 | [
"BSD-3-Clause"
] | 53 | 2015-09-01T14:43:18.000Z | 2022-03-11T16:05:10.000Z | #include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <arm_neon.h>
#include <string.h>
static void printmem16(uint8x16_t buf)
{
printf("%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x\n",
buf[15], buf[14], buf[13], buf[12],
buf[11], buf[10], buf[9], buf[8],
buf[7], buf[6], buf[5], buf[4],
buf[3], buf[2], buf[1], buf[0]);
}
static void printmem(uint8_t* buf)
{
printf("%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,"
"%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x\n",
buf[31], buf[30], buf[29], buf[28],
buf[27], buf[26], buf[25], buf[24],
buf[23], buf[22], buf[21], buf[20],
buf[19], buf[18], buf[17], buf[16],
buf[15], buf[14], buf[13], buf[12],
buf[11], buf[10], buf[9], buf[8],
buf[7], buf[6], buf[5], buf[4],
buf[3], buf[2], buf[1], buf[0]);
}
static void
unshuffle2_neon(uint8_t* const dest, const uint8_t* const src,
const size_t vectorizable_elements, const size_t total_elements)
{
size_t i, j, k;
static const size_t bytesoftype = 2;
uint8x16x2_t r0;
for(i = 0, k = 0; i < vectorizable_elements*bytesoftype; i += sizeof(r0), k++) {
/* Load 32 bytes to the structure r0 */
for(j = 0; j < 2; j++) {
r0.val[j] = vld1q_u8(src + total_elements*j + k*sizeof(r0.val[j]));
}
/* Store (with permutation) the results in the destination vector */
vst2q_u8(dest+k*sizeof(r0),r0);
}
}
main() {
uint8_t *src = "\xcb\xf1\x24\xb1\x69\xee\x99\x7a\x45\x5f\xa2\x41\x77\xfd\x19\x38"
"\x56\xab\x61\x7d\xbb\xf6\x29\xe7\x73\xd3\x3f\x46\xba\x49\x71\x35"
"\x13\x21\x17"
"\xff\x79\x7c\x58\xd2\xdd\x9a\x86\x3e\xdf\x43\x25\xae\x22\x1a\x2b"
"\x93\xc3\xa8\xfc\x98\xd1\xce\x58\x4c\x12\xcf\x94\xfa\x83\x1e\x5f"
"\xc8\xc9\x34";
uint8_t *dest = calloc(70,2);
size_t vectorizable_elements = 32;
size_t total_elements = 35;
unshuffle2_neon(dest, src, vectorizable_elements, total_elements);
printf("\n");
printmem(dest);
printmem(dest+32);
printmem(dest+64);
printmem(dest+96);
printmem(dest+128);
free(dest);
}
| 31.084507 | 83 | 0.555052 | [
"vector"
] |
97127fcf4d7e47843b7cd559043718f76ebb81c0 | 10,708 | h | C | src/include/access/bitmap.h | JunfengYang/gpdb | 7f1589a786e7fd9cac950ee104a729e370ec3606 | [
"PostgreSQL",
"Apache-2.0"
] | 1 | 2021-03-04T03:29:00.000Z | 2021-03-04T03:29:00.000Z | src/include/access/bitmap.h | JunfengYang/gpdb | 7f1589a786e7fd9cac950ee104a729e370ec3606 | [
"PostgreSQL",
"Apache-2.0"
] | 16 | 2020-10-21T18:37:47.000Z | 2021-01-13T01:01:15.000Z | src/include/access/bitmap.h | JunfengYang/gpdb | 7f1589a786e7fd9cac950ee104a729e370ec3606 | [
"PostgreSQL",
"Apache-2.0"
] | 1 | 2020-03-26T02:47:22.000Z | 2020-03-26T02:47:22.000Z | /*-------------------------------------------------------------------------
*
* bitmap.h
* header file for on-disk bitmap index access method implementation.
*
* Copyright (c) 2006-2008, PostgreSQL Global Development Group
*
* IDENTIFICATION
* src/include/access/bitmap.h
*
*-------------------------------------------------------------------------
*/
#ifndef BITMAP_H
#define BITMAP_H
#include "storage/bufmgr.h"
#include "storage/bufpage.h"
#define BM_READ BUFFER_LOCK_SHARE
#define BM_WRITE BUFFER_LOCK_EXCLUSIVE
#define BM_NOLOCK (-1)
/*
* The size in bits of a hybrid run-length(HRL) word.
* If you change this, you should change the type for
* a HRL word as well.
*/
#define BM_HRL_WORD_SIZE 64
/* the type for a HRL word */
typedef uint64 BM_HRL_WORD;
#define BM_HRL_WORD_LEFTMOST (BM_HRL_WORD_SIZE-1)
#define BITMAP_VERSION 2
#define BITMAP_MAGIC 0x4249544D
/*
* Metapage, always the first page (page 0) in the index.
*
* This page stores some meta-data information about this index.
*/
typedef struct BMMetaPageData
{
/*
* The magic and version of the bitmap index. Using the Oid type is to
* overcome the problem that the version is not stored in
* the index before GPDB 3.4.
*/
Oid bm_magic;
Oid bm_version; /* the version of the index */
/*
* The relation ids for a heap and a btree on this heap. They are
* used to speed up finding the bitmap vector for given attribute
* value(s), see the comments for LOV pages below for more
* information. We consider these as the metadata for LOV pages.
*/
Oid bm_lov_heapId; /* the relation id for the heap */
Oid bm_lov_indexId; /* the relation id for the index */
/* the block number for the last LOV pages. */
BlockNumber bm_lov_lastpage;
} BMMetaPageData;
typedef BMMetaPageData *BMMetaPage;
/*
* The meta page is always the first block of the index
*/
#define BM_METAPAGE 0
/*
* The maximum number of heap tuples in one page that is considered
* in the bitmap index. We set this number to be a multiplication
* of BM_HRL_WORD_SIZE because we can then bits for heap
* tuples in different heap pages are stored in different words.
* This makes it easier during the search.
*
* Because the tid value for AO tables can be more than MaxHeapTuplesPerPage,
* we use the maximum possible offset number here.
*/
#define BM_MAX_TUPLES_PER_PAGE \
(((((1 << (8 * sizeof(OffsetNumber))) - 1) / BM_HRL_WORD_SIZE) + 1) * \
BM_HRL_WORD_SIZE)
/*
* LOV (List Of Values) page -- pages to store a list of distinct
* values for attribute(s) to be indexed, some metadata related to
* their corresponding bitmap vectors, and the pointers to their
* bitmap vectors. For each distinct value, there is a BMLOVItemData
* associated with it. A LOV page maintains an array of BMLOVItemData
* instances, called lov items.
*
* To speed up finding the lov item for a given value, we
* create a heap to maintain all distinct values along with the
* block numbers and offset numbers for their lov items in LOV pages.
* That is, there are total "<number_of_attributes> + 2" attributes
* in this new heap. Along with this heap, we also create a new btree
* index on this heap using attribute(s) as btree keys. In this way,
* for any given value, we search this btree to find
* the block number and offset number for its corresponding lov item.
*/
/*
* The first LOV page is reserved for NULL keys
*/
#define BM_LOV_STARTPAGE 1
/*
* Items in a LOV page.
*
* Each item is corresponding to a distinct value for attribute(s)
* to be indexed. For multi-column indexes on (a_1,a_2,...,a_n), we say
* two values (l_1,l_2,...,l_n) and (k_1,k_2,...,k_n) for (a_1,a_2,...,a_n)
* are the same if and only if for all i, l_i=k_i.
*
*/
typedef struct BMLOVItemData
{
/* the first page and last page of the bitmap vector. */
BlockNumber bm_lov_head;
BlockNumber bm_lov_tail;
/*
* Additional information to be used to append new bits into
* existing bitmap vector that this distinct value is associated with.
* The following two words do not store in the regular bitmap page,
* defined below.
*/
/* the last complete word in its bitmap vector. */
BM_HRL_WORD bm_last_compword;
/*
* the last word in its bitmap vector. This word is not
* a complete word. If a new appending bit makes this word
* to be complete, this word will merge with bm_last_compword.
*/
BM_HRL_WORD bm_last_word;
/*
* the tid location for the last bit stored in bm_last_compword.
* A tid location represents the index position for a bit in a
* bitmap vector, which is conceptualized as an array
* of bits. This value -- the index position starts from 1, and
* is calculated through (block#)*BM_MAX_TUPLES_PER_PAGE + (offset#),
* where (block#) and (offset#) are from the heap tuple ctid.
* This value is used while updating a bit in the middle of
* its bitmap vector. When moving the last complete word to
* the bitmap page, this value will also be written to that page.
* Each bitmap page maintains a similar value -- the tid location
* for the last bit stored in that page. This will help us
* know the range of tid locations for bits in a bitmap page
* without decompressing all bits.
*/
uint64 bm_last_tid_location;
/*
* the tid location of the last bit whose value is 1 (a set bit).
* Each bitmap vector will be visited only when there is a new
* set bit to be appended/updated. In the appending case, a new
* tid location is presented. With this value, we can calculate
* how many bits are 0s between this new set bit and the previous
* set bit.
*/
uint64 bm_last_setbit;
/*
* Only two least-significant bits in this byte are used.
*
* If the first least-significant bit is 1, then it represents
* that bm_last_word is a fill word. If the second least-significant
* bit is 1, it represents that bm_last_compword is a fill word.
*/
uint8 lov_words_header;
} BMLOVItemData;
typedef BMLOVItemData *BMLOVItem;
#define BM_MAX_LOVITEMS_PER_PAGE \
((BLCKSZ - sizeof(PageHeaderData)) / sizeof(BMLOVItemData))
#define BM_LAST_WORD_BIT 1
#define BM_LAST_COMPWORD_BIT 2
#define BM_LASTWORD_IS_FILL(lov) \
(bool) (lov->lov_words_header & BM_LAST_WORD_BIT ? true : false)
#define BM_LAST_COMPWORD_IS_FILL(lov) \
(bool) (lov->lov_words_header & BM_LAST_COMPWORD_BIT ? true : false)
#define BM_BOTH_LOV_WORDS_FILL(lov) \
(BM_LASTWORD_IS_FILL(lov) && BM_LAST_COMPWORD_IS_FILL(lov))
/*
* Bitmap page -- pages to store bits in a bitmap vector.
*
* Each bitmap page stores two parts of information: header words and
* content words. Each bit in the header words is corresponding to
* a word in the content words. If a bit in the header words is 1,
* then its corresponding content word is a compressed word. Otherwise,
* it is a literal word.
*
* If a content word is a fill word, it means that there is a sequence
* of 0 bits or 1 bits. The most significant bit in this content word
* represents the bits in this sequence are 0s or 1s. The rest of bits
* stores the value of "the number of bits / BM_HRL_WORD_SIZE".
*/
/*
* Opaque data for a bitmap page.
*/
typedef struct BMBitmapOpaqueData
{
uint32 bm_hrl_words_used; /* the number of words used */
BlockNumber bm_bitmap_next; /* the next page for this bitmap */
/*
* the tid location for the last bit in this page.
*/
uint64 bm_last_tid_location;
} BMBitmapOpaqueData;
typedef BMBitmapOpaqueData *BMBitmapOpaque;
/*
* Approximately 4078 words per 8K page
*/
#define BM_MAX_NUM_OF_HRL_WORDS_PER_PAGE \
((BLCKSZ - \
MAXALIGN(sizeof(PageHeaderData)) - \
MAXALIGN(sizeof(BMBitmapOpaqueData)))/sizeof(BM_HRL_WORD))
/* approx 255 */
#define BM_MAX_NUM_OF_HEADER_WORDS \
(((BM_MAX_NUM_OF_HRL_WORDS_PER_PAGE-1)/BM_HRL_WORD_SIZE) + 1)
/*
* To make the last header word a complete word, we limit this number to
* the multiplication of the word size.
*/
#define BM_NUM_OF_HRL_WORDS_PER_PAGE \
(((BM_MAX_NUM_OF_HRL_WORDS_PER_PAGE - \
BM_MAX_NUM_OF_HEADER_WORDS)/BM_HRL_WORD_SIZE) * BM_HRL_WORD_SIZE)
#define BM_NUM_OF_HEADER_WORDS \
(((BM_NUM_OF_HRL_WORDS_PER_PAGE-1)/BM_HRL_WORD_SIZE) + 1)
/*
* A page of a compressed bitmap
*/
typedef struct BMBitmapData
{
BM_HRL_WORD hwords[BM_NUM_OF_HEADER_WORDS];
BM_HRL_WORD cwords[BM_NUM_OF_HRL_WORDS_PER_PAGE];
} BMBitmapData;
typedef BMBitmapData *BMBitmap;
/*
* The number of tid locations to be found at once during query processing.
*/
#define BM_BATCH_TIDS 16*1024
/*
* the maximum number of words to be retrieved during BitmapIndexScan.
*/
#define BM_MAX_WORDS BM_NUM_OF_HRL_WORDS_PER_PAGE*4
/* Some macros for manipulating a bitmap word. */
#define LITERAL_ALL_ZERO 0
#define LITERAL_ALL_ONE ((BM_HRL_WORD)(~((BM_HRL_WORD)0)))
#define FILL_MASK ~(((BM_HRL_WORD)1) << (BM_HRL_WORD_SIZE - 1))
#define BM_MAKE_FILL_WORD(bit, length) \
((((BM_HRL_WORD)bit) << (BM_HRL_WORD_SIZE-1)) | (length))
#define FILL_LENGTH(w) (((BM_HRL_WORD)(w)) & FILL_MASK)
#define MAX_FILL_LENGTH ((((BM_HRL_WORD)1)<<(BM_HRL_WORD_SIZE-1))-1)
/* get the left most bit of the word */
#define GET_FILL_BIT(w) (((BM_HRL_WORD)(w))>>BM_HRL_WORD_LEFTMOST)
/*
* Given a word number, determine the bit position it that holds in its
* header word.
*/
#define WORDNO_GET_HEADER_BIT(cw_no) \
((BM_HRL_WORD)1 << (BM_HRL_WORD_SIZE - 1 - ((cw_no) % BM_HRL_WORD_SIZE)))
/* A simplified interface to IS_FILL_WORD */
#define CUR_WORD_IS_FILL(b) \
IS_FILL_WORD(b->hwords, b->startNo)
/*
* Calculate the number of header words we need given the number of
* content words
*/
#define BM_CALC_H_WORDS(c_words) \
(c_words == 0 ? c_words : (((c_words - 1)/BM_HRL_WORD_SIZE) + 1))
/*
* Convert an ItemPointer to and from an integer representation
*/
#define BM_IPTR_TO_INT(iptr) \
((uint64)ItemPointerGetBlockNumber(iptr) * BM_MAX_TUPLES_PER_PAGE + \
(uint64)ItemPointerGetOffsetNumber(iptr))
#define BM_INT_GET_BLOCKNO(i) \
((i - 1)/BM_MAX_TUPLES_PER_PAGE)
#define BM_INT_GET_OFFSET(i) \
(((i - 1) % BM_MAX_TUPLES_PER_PAGE) + 1)
/*
* To see if the content word at wordno is a compressed word or not we must look
* in the header words. Each bit in the header words corresponds to a word
* amongst the content words. If the bit is 1, the word is compressed (i.e., it
* is a fill word) otherwise it is uncompressed.
*
* See src/backend/access/bitmap/README for more details
*/
static inline bool
IS_FILL_WORD(const BM_HRL_WORD *words, int16 wordno)
{
return (words[wordno / BM_HRL_WORD_SIZE] & WORDNO_GET_HEADER_BIT(wordno)) > 0;
}
/* reloptions.c */
#define BITMAP_MIN_FILLFACTOR 10
#define BITMAP_DEFAULT_FILLFACTOR 100
#endif
| 31.494118 | 80 | 0.719089 | [
"vector"
] |
97143829f8b65cc9ed80f9300e8c7ca4482ab881 | 3,160 | h | C | doc/pseudosrc/oscore_native/crypto_type.h | chrysn/liboscore | 8fea37c419582a2a9af4ed07c621d1fc1506d856 | [
"BSD-3-Clause"
] | 2 | 2020-01-30T04:40:22.000Z | 2020-04-16T00:01:13.000Z | doc/pseudosrc/oscore_native/crypto_type.h | chrysn/liboscore | 8fea37c419582a2a9af4ed07c621d1fc1506d856 | [
"BSD-3-Clause"
] | null | null | null | doc/pseudosrc/oscore_native/crypto_type.h | chrysn/liboscore | 8fea37c419582a2a9af4ed07c621d1fc1506d856 | [
"BSD-3-Clause"
] | null | null | null | /** @file */
/** @ingroup oscore_native_types
* @addtogroup oscore_native_crypto_types Native cryptography types
* @{ */
/** @brief Type of COSE AEAD algorithms
*
* This can be an enum, an unsigned integer (typically used when
* string-labelled algorithms are not supported anyway) or even a pointer to a
* static key description.
*
* It must be defined in the backend's own ``oscore_native/crypto_type.h``.
*/
typedef int32_t oscore_crypto_aeadalg_t;
// We might want to merge this with decryptstate to avoid duplication in AAD feeding
//
/** @brief State of an ongoing AEAD operation
*
* This contains all state that is held in an ongoing AEAD encrypt operation.
* It is recommended to make this a struct or pointer to a fixed-size
* allocation that is sufficiently large for all supported ciphers. That helps
* avoiding unpleasant surprises in low-memory application situations after a
* cipher suite change (see @ref stack_allocation_sizes).
*
* See @ref oscore_crypto_aead_encrypt_start for details and usage.
*
* It must be defined in the backend's own ``oscore_native/crypto_type.h``.
*/
typedef struct example_encryptstate oscore_crypto_aead_encryptstate_t;
/** @brief State of an ongoing AEAD operation
*
* This contains all state that is held in an ongoing AEAD decrypt operation,
* and is fully anologous to @ref oscore_crypto_aead_encryptstate_t, and is
* expected to often be a type alias of it.
*
* It must be defined in the backend's own ``oscore_native/crypto_type.h``.
*/
typedef struct example_decryptstate oscore_crypto_aead_decryptstate_t;
/** @brief Maximum length of an AEAD nonce (IV)
*
* This defines the maximum length of AEAD nonce (initialization vector, IV)
* any supported algorithm has. It is used for stack allocations where a
* message's IV is constructed during encryption and decryption.
*
* It must be defined in the backend's own ``oscore_native/crypto_type.h``.
*/
#define OSCORE_CRYPTO_AEAD_IV_MAXLEN ((size_t)13)
/** @brief Maximum length of an AEAD key
*
* This defines the maximum length of AEAD key any supported algorithm has. It
* is used in allocations of security contexts.
*
* It must be defined in the backend's own ``oscore_native/crypto_type.h``.
*/
#define OSCORE_CRYPTO_AEAD_KEY_MAXLEN ((size_t)16)
/** @brief Type of COSE HKDF algorithms
*
* This describes a KDF that can be used as HKDF algorithm in an OSCORE
* Security Context. It corresponds to a COSE "Direct Key with KDF" algorithm,
* and is constructed from those.
*
* This can be an enum, an unsigned integer (typically used when
* string-labelled algorithms are not supported anyway) or even a pointer to a
* static key description.
*
* It must be defined in the backend's own ``oscore_native/crypto_type.h``.
*/
typedef int32_t oscore_crypto_hkdfalg_t;
/** @brief Error type for cryptography operaitons
*
* This error type is returned by operations on the cryptography backend, and
* usually only evalued using the @ref oscore_cryptoerr_is_error function.
*
* It must be defined in the backend's own ``oscore_native/crypto_type.h``.
*/
typedef bool oscore_cryptoerr_t;
/** @} */
| 36.744186 | 84 | 0.755696 | [
"vector"
] |
971fc609644957f9041f993c036cbd50a7f212b2 | 4,440 | h | C | laser_odometry_core/include/laser_odometry_core/laser_odometry_utils.h | Mastro93/laser_odometry | e580f3ab736ca8ebf8692e660d27272e2c56c403 | [
"Apache-2.0"
] | 1 | 2021-11-29T10:32:55.000Z | 2021-11-29T10:32:55.000Z | laser_odometry_core/include/laser_odometry_core/laser_odometry_utils.h | NamDinhRobotics/laser_odometry | 464ce3de9671ac0f1cf3f9c583fb65974aaab929 | [
"Apache-2.0"
] | null | null | null | laser_odometry_core/include/laser_odometry_core/laser_odometry_utils.h | NamDinhRobotics/laser_odometry | 464ce3de9671ac0f1cf3f9c583fb65974aaab929 | [
"Apache-2.0"
] | null | null | null | #ifndef _LASER_ODOMETRY_CORE_LASER_ODOMETRY_UTILS_H_
#define _LASER_ODOMETRY_CORE_LASER_ODOMETRY_UTILS_H_
#include "laser_odometry_core/laser_odometry_transform.h"
#include <Eigen/Eigenvalues>
namespace laser_odometry
{
namespace utils
{
void tfFromXYTheta(const double x, const double y,
const double theta, Transform& t);
template <typename T>
bool all_positive(const std::vector<T> vec)
{
for (const auto v : vec)
{
if (v < 0) return false;
}
return true;
}
template<typename T>
inline Eigen::Matrix<T, 3, 3> matrixRollPitchYaw(const T roll,
const T pitch,
const T yaw)
{
const Eigen::AngleAxis<T> ax = Eigen::AngleAxis<T>(roll, Eigen::Matrix<T, 3, 1>::UnitX());
const Eigen::AngleAxis<T> ay = Eigen::AngleAxis<T>(pitch, Eigen::Matrix<T, 3, 1>::UnitY());
const Eigen::AngleAxis<T> az = Eigen::AngleAxis<T>(yaw, Eigen::Matrix<T, 3, 1>::UnitZ());
return (az * ay * ax).toRotationMatrix().matrix();
}
template<typename T>
inline Eigen::Matrix<T, 3, 3> matrixYaw(const T yaw)
{
return matrixRollPitchYaw<T>(0, 0, yaw);
}
template <typename Derived>
Eigen::Matrix<typename Derived::Scalar, 6, 6>
covariance2dTo3d(const Eigen::MatrixBase<Derived>& cov_2d)
{
static_assert(Eigen::MatrixBase<Derived>::RowsAtCompileTime == 3, "Input arg must be of size 3*3");
static_assert(Eigen::MatrixBase<Derived>::ColsAtCompileTime == 3, "Input arg must be of size 3*3");
using T = typename Derived::Scalar;
Eigen::Matrix<T, 6, 6> cov_3d = Eigen::Matrix<T, 6, 6>::Zero();
cov_3d.block(0,0,2,2) = cov_2d.block(0,0,2,2);
cov_3d.block(0,5,2,1) = cov_2d.block(0,2,2,1);
cov_3d.block(5,0,1,2) = cov_2d.block(2,0,1,2);
cov_3d(5,5) = cov_2d(2,2);
return cov_3d;
}
/// Some helper functions ///
template<typename T>
inline T anyabs(const T& v)
{
return (v < T(0))? -v : v;
}
template <typename Derived>
inline typename Eigen::MatrixBase<Derived>::Scalar
getYaw(const Eigen::MatrixBase<Derived>& r)
{
return std::atan2( r(1, 0), r(0, 0) );
}
template <typename T, int Dim>
inline bool isIdentity(const Isometry<T, Dim>& t,
const T epsilon = eps)
{
return t.isApprox(Isometry<T, Dim>::Identity(), epsilon);
}
template <typename T, int Dim>
inline bool isOthogonal(const Isometry<T, Dim>& t,
const T epsilon = eps)
{
// Calling t.rotation() normalizes the rotation already
// so that T(1) - R.rotation().determinant() = 0
// is always true.
return (anyabs(T(1) - anyabs(t.linear().determinant())) > epsilon) ? false : true;
}
template <typename T, int Dim>
inline bool isRotationProper(const Isometry<T, Dim>& t,
const T epsilon = eps)
{
// Calling t.rotation() normalizes the rotation already
// so that T(1) - R.rotation().determinant() = 0
// is always true.
return (anyabs(T(1) - t.linear().determinant()) > epsilon) ? false : true;
}
template <typename T, int N>
inline bool isSymmetric(const Eigen::Matrix<T, N, N>& M,
const T epsilon = eps)
{
return M.isApprox(M.transpose(), epsilon);
}
template <typename T, int N>
inline bool isPositiveSemiDefinite(const Eigen::Matrix<T, N, N>& M)
{
Eigen::SelfAdjointEigenSolver<Eigen::Matrix<T, N, N> > eigensolver(M);
if (eigensolver.info() == Eigen::Success)
{
// All eigenvalues must be >= 0:
return (eigensolver.eigenvalues().array() >= T(0)).all();
}
return false;
}
template <typename T, int N>
inline bool isCovariance(const Eigen::Matrix<T, N, N>& M)
{
return isSymmetric(M) && isPositiveSemiDefinite(M);
}
template <typename T, int Dim>
inline void makeOrthogonal(Isometry<T, Dim>& t)
{
const Isometry<T, Dim> tmp = t;
t = tmp.rotation();
t.translation() = tmp.translation();
}
template<typename Derived>
inline Eigen::Matrix<typename Derived::Scalar, 3, 3>
skew(const Eigen::MatrixBase<Derived>& v)
{
static_assert(v.ColsAtCompileTime == 1, "Function 'skew' expect a vector.");
static_assert(v.RowsAtCompileTime == 3, "Function 'skew' expect a vector of size 3.");
typedef typename Derived::Scalar T;
return (Eigen::Matrix<T, 3, 3>() <<
0.0, -v(2), +v(1),
+v(2), 0.0, -v(0),
-v(1), +v(0), 0.0 ).finished();
}
} /* namespace utils */
} /* namespace laser_odometry */
#endif /* _LASER_ODOMETRY_CORE_LASER_ODOMETRY_UTILS_H_ */
| 27.239264 | 101 | 0.645495 | [
"vector",
"transform"
] |
972525297262deb8fbfbfaf0aeac6d1f87e91caa | 16,424 | c | C | usr/src/cmd/tar/tar.c | r1mikey/research-unix-v7 | 8b0bf75e2f5cf013ff7f236c4589711cbc3a12ff | [
"MIT"
] | 43 | 2020-02-12T08:14:49.000Z | 2022-03-30T19:25:52.000Z | usr/src/cmd/tar/tar.c | r1mikey/research-unix-v7 | 8b0bf75e2f5cf013ff7f236c4589711cbc3a12ff | [
"MIT"
] | null | null | null | usr/src/cmd/tar/tar.c | r1mikey/research-unix-v7 | 8b0bf75e2f5cf013ff7f236c4589711cbc3a12ff | [
"MIT"
] | 6 | 2020-02-13T12:56:27.000Z | 2022-02-11T20:59:46.000Z | #include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/dir.h>
#include <signal.h>
char *sprintf();
char *strcat();
daddr_t bsrch();
#define TBLOCK 512
#define NBLOCK 20
#define NAMSIZ 100
union hblock {
char dummy[TBLOCK];
struct header {
char name[NAMSIZ];
char mode[8];
char uid[8];
char gid[8];
char size[12];
char mtime[12];
char chksum[8];
char linkflag;
char linkname[NAMSIZ];
} dbuf;
} dblock, tbuf[NBLOCK];
struct linkbuf {
ino_t inum;
dev_t devnum;
int count;
char pathname[NAMSIZ];
struct linkbuf *nextp;
} *ihead;
struct stat stbuf;
int rflag, xflag, vflag, tflag, mt, cflag, mflag;
int term, chksum, wflag, recno, first, linkerrok;
int freemem = 1;
int nblock = 1;
daddr_t low;
daddr_t high;
FILE *tfile;
char tname[] = "/tmp/tarXXXXXX";
char *usefile;
char magtape[] = "/dev/mt1";
char *malloc();
main(argc, argv)
int argc;
char *argv[];
{
char *cp;
int onintr(), onquit(), onhup(), onterm();
if (argc < 2)
usage();
tfile = NULL;
usefile = magtape;
argv[argc] = 0;
argv++;
for (cp = *argv++; *cp; cp++)
switch(*cp) {
case 'f':
usefile = *argv++;
if (nblock == 1)
nblock = 0;
break;
case 'c':
cflag++;
rflag++;
break;
case 'u':
mktemp(tname);
if ((tfile = fopen(tname, "w")) == NULL) {
fprintf(stderr, "Tar: cannot create temporary file (%s)\n", tname);
done(1);
}
fprintf(tfile, "!!!!!/!/!/!/!/!/!/! 000\n");
/* FALL THROUGH */
case 'r':
rflag++;
if (nblock != 1 && cflag == 0) {
noupdate:
fprintf(stderr, "Tar: Blocked tapes cannot be updated (yet)\n");
done(1);
}
break;
case 'v':
vflag++;
break;
case 'w':
wflag++;
break;
case 'x':
xflag++;
break;
case 't':
tflag++;
break;
case 'm':
mflag++;
break;
case '-':
break;
case '0':
case '1':
magtape[7] = *cp;
usefile = magtape;
break;
case 'b':
nblock = atoi(*argv++);
if (nblock > NBLOCK || nblock <= 0) {
fprintf(stderr, "Invalid blocksize. (Max %d)\n", NBLOCK);
done(1);
}
if (rflag && !cflag)
goto noupdate;
break;
case 'l':
linkerrok++;
break;
default:
fprintf(stderr, "tar: %c: unknown option\n", *cp);
usage();
}
if (rflag) {
if (cflag && tfile != NULL) {
usage();
done(1);
}
if (signal(SIGINT, SIG_IGN) != SIG_IGN)
signal(SIGINT, onintr);
if (signal(SIGHUP, SIG_IGN) != SIG_IGN)
signal(SIGHUP, onhup);
if (signal(SIGQUIT, SIG_IGN) != SIG_IGN)
signal(SIGQUIT, onquit);
/*
if (signal(SIGTERM, SIG_IGN) != SIG_IGN)
signal(SIGTERM, onterm);
*/
if (strcmp(usefile, "-") == 0) {
if (cflag == 0) {
fprintf(stderr, "Can only create standard output archives\n");
done(1);
}
mt = dup(1);
nblock = 1;
}
else if ((mt = open(usefile, 2)) < 0) {
if (cflag == 0 || (mt = creat(usefile, 0666)) < 0) {
fprintf(stderr, "tar: cannot open %s\n", usefile);
done(1);
}
}
if (cflag == 0 && nblock == 0)
nblock = 1;
dorep(argv);
}
else if (xflag) {
if (strcmp(usefile, "-") == 0) {
mt = dup(0);
nblock = 1;
}
else if ((mt = open(usefile, 0)) < 0) {
fprintf(stderr, "tar: cannot open %s\n", usefile);
done(1);
}
doxtract(argv);
}
else if (tflag) {
if (strcmp(usefile, "-") == 0) {
mt = dup(0);
nblock = 1;
}
else if ((mt = open(usefile, 0)) < 0) {
fprintf(stderr, "tar: cannot open %s\n", usefile);
done(1);
}
dotable();
}
else
usage();
done(0);
}
usage()
{
fprintf(stderr, "tar: usage tar -{txru}[cvfblm] [tapefile] [blocksize] file1 file2...\n");
done(1);
}
dorep(argv)
char *argv[];
{
register char *cp, *cp2;
char wdir[60];
if (!cflag) {
getdir();
do {
passtape();
if (term)
done(0);
getdir();
} while (!endtape());
if (tfile != NULL) {
char buf[200];
strcat(buf, "sort +0 -1 +1nr ");
strcat(buf, tname);
strcat(buf, " -o ");
strcat(buf, tname);
sprintf(buf, "sort +0 -1 +1nr %s -o %s; awk '$1 != prev {print; prev=$1}' %s >%sX;mv %sX %s",
tname, tname, tname, tname, tname, tname);
fflush(tfile);
system(buf);
freopen(tname, "r", tfile);
fstat(fileno(tfile), &stbuf);
high = stbuf.st_size;
}
}
getwdir(wdir);
while (*argv && ! term) {
cp2 = *argv;
for (cp = *argv; *cp; cp++)
if (*cp == '/')
cp2 = cp;
if (cp2 != *argv) {
*cp2 = '\0';
chdir(*argv);
*cp2 = '/';
cp2++;
}
putfile(*argv++, cp2);
chdir(wdir);
}
putempty();
putempty();
flushtape();
if (linkerrok == 1)
for (; ihead != NULL; ihead = ihead->nextp)
if (ihead->count != 0)
fprintf(stderr, "Missing links to %s\n", ihead->pathname);
}
endtape()
{
if (dblock.dbuf.name[0] == '\0') {
backtape();
return(1);
}
else
return(0);
}
getdir()
{
register struct stat *sp;
int i;
readtape( (char *) &dblock);
if (dblock.dbuf.name[0] == '\0')
return;
sp = &stbuf;
sscanf(dblock.dbuf.mode, "%o", &i);
sp->st_mode = i;
sscanf(dblock.dbuf.uid, "%o", &i);
sp->st_uid = i;
sscanf(dblock.dbuf.gid, "%o", &i);
sp->st_gid = i;
sscanf(dblock.dbuf.size, "%lo", &sp->st_size);
sscanf(dblock.dbuf.mtime, "%lo", &sp->st_mtime);
sscanf(dblock.dbuf.chksum, "%o", &chksum);
if (chksum != checksum()) {
fprintf(stderr, "directory checksum error\n");
done(2);
}
if (tfile != NULL)
fprintf(tfile, "%s %s\n", dblock.dbuf.name, dblock.dbuf.mtime);
}
passtape()
{
long blocks;
char buf[TBLOCK];
if (dblock.dbuf.linkflag == '1')
return;
blocks = stbuf.st_size;
blocks += TBLOCK-1;
blocks /= TBLOCK;
while (blocks-- > 0)
readtape(buf);
}
putfile(longname, shortname)
char *longname;
char *shortname;
{
int infile;
long blocks;
char buf[TBLOCK];
register char *cp, *cp2;
struct direct dbuf;
int i, j;
infile = open(shortname, 0);
if (infile < 0) {
fprintf(stderr, "tar: %s: cannot open file\n", longname);
return;
}
fstat(infile, &stbuf);
if (tfile != NULL && checkupdate(longname) == 0) {
close(infile);
return;
}
if (checkw('r', longname) == 0) {
close(infile);
return;
}
if ((stbuf.st_mode & S_IFMT) == S_IFDIR) {
for (i = 0, cp = buf; *cp++ = longname[i++];);
*--cp = '/';
cp++;
i = 0;
chdir(shortname);
while (read(infile, (char *)&dbuf, sizeof(dbuf)) > 0 && !term) {
if (dbuf.d_ino == 0) {
i++;
continue;
}
if (strcmp(".", dbuf.d_name) == 0 || strcmp("..", dbuf.d_name) == 0) {
i++;
continue;
}
cp2 = cp;
for (j=0; j < DIRSIZ; j++)
*cp2++ = dbuf.d_name[j];
*cp2 = '\0';
close(infile);
putfile(buf, cp);
infile = open(".", 0);
i++;
lseek(infile, (long) (sizeof(dbuf) * i), 0);
}
close(infile);
chdir("..");
return;
}
if ((stbuf.st_mode & S_IFMT) != S_IFREG) {
fprintf(stderr, "tar: %s is not a file. Not dumped\n", longname);
return;
}
tomodes(&stbuf);
cp2 = longname;
for (cp = dblock.dbuf.name, i=0; (*cp++ = *cp2++) && i < NAMSIZ; i++);
if (i >= NAMSIZ) {
fprintf(stderr, "%s: file name too long\n", longname);
close(infile);
return;
}
if (stbuf.st_nlink > 1) {
struct linkbuf *lp;
int found = 0;
for (lp = ihead; lp != NULL; lp = lp->nextp) {
if (lp->inum == stbuf.st_ino && lp->devnum == stbuf.st_dev) {
found++;
break;
}
}
if (found) {
strcpy(dblock.dbuf.linkname, lp->pathname);
dblock.dbuf.linkflag = '1';
sprintf(dblock.dbuf.chksum, "%6o", checksum());
writetape( (char *) &dblock);
if (vflag) {
fprintf(stderr, "a %s ", longname);
fprintf(stderr, "link to %s\n", lp->pathname);
}
lp->count--;
close(infile);
return;
}
else {
lp = (struct linkbuf *) malloc(sizeof(*lp));
if (lp == NULL) {
if (freemem) {
fprintf(stderr, "Out of memory. Link information lost\n");
freemem = 0;
}
}
else {
lp->nextp = ihead;
ihead = lp;
lp->inum = stbuf.st_ino;
lp->devnum = stbuf.st_dev;
lp->count = stbuf.st_nlink - 1;
strcpy(lp->pathname, longname);
}
}
}
blocks = (stbuf.st_size + (TBLOCK-1)) / TBLOCK;
if (vflag) {
fprintf(stderr, "a %s ", longname);
fprintf(stderr, "%ld blocks\n", blocks);
}
sprintf(dblock.dbuf.chksum, "%6o", checksum());
writetape( (char *) &dblock);
while ((i = read(infile, buf, TBLOCK)) > 0 && blocks > 0) {
writetape(buf);
blocks--;
}
close(infile);
if (blocks != 0 || i != 0)
fprintf(stderr, "%s: file changed size\n", longname);
while (blocks-- > 0)
putempty();
}
doxtract(argv)
char *argv[];
{
long blocks, bytes;
char buf[TBLOCK];
char **cp;
int ofile;
for (;;) {
getdir();
if (endtape())
break;
if (*argv == 0)
goto gotit;
for (cp = argv; *cp; cp++)
if (prefix(*cp, dblock.dbuf.name))
goto gotit;
passtape();
continue;
gotit:
if (checkw('x', dblock.dbuf.name) == 0) {
passtape();
continue;
}
checkdir(dblock.dbuf.name);
if (dblock.dbuf.linkflag == '1') {
unlink(dblock.dbuf.name);
if (link(dblock.dbuf.linkname, dblock.dbuf.name) < 0) {
fprintf(stderr, "%s: cannot link\n", dblock.dbuf.name);
continue;
}
if (vflag)
fprintf(stderr, "%s linked to %s\n", dblock.dbuf.name, dblock.dbuf.linkname);
continue;
}
if ((ofile = creat(dblock.dbuf.name, stbuf.st_mode & 07777)) < 0) {
fprintf(stderr, "tar: %s - cannot create\n", dblock.dbuf.name);
passtape();
continue;
}
chown(dblock.dbuf.name, stbuf.st_uid, stbuf.st_gid);
blocks = ((bytes = stbuf.st_size) + TBLOCK-1)/TBLOCK;
if (vflag)
fprintf(stderr, "x %s, %ld bytes, %ld tape blocks\n", dblock.dbuf.name, bytes, blocks);
while (blocks-- > 0) {
readtape(buf);
if (bytes > TBLOCK) {
if (write(ofile, buf, TBLOCK) < 0) {
fprintf(stderr, "tar: %s: HELP - extract write error\n", dblock.dbuf.name);
done(2);
}
} else
if (write(ofile, buf, (int) bytes) < 0) {
fprintf(stderr, "tar: %s: HELP - extract write error\n", dblock.dbuf.name);
done(2);
}
bytes -= TBLOCK;
}
close(ofile);
if (mflag == 0) {
time_t timep[2];
timep[0] = time(NULL);
timep[1] = stbuf.st_mtime;
utime(dblock.dbuf.name, timep);
}
}
}
dotable()
{
for (;;) {
getdir();
if (endtape())
break;
if (vflag)
longt(&stbuf);
printf("%s", dblock.dbuf.name);
if (dblock.dbuf.linkflag == '1')
printf(" linked to %s", dblock.dbuf.linkname);
printf("\n");
passtape();
}
}
putempty()
{
char buf[TBLOCK];
char *cp;
for (cp = buf; cp < &buf[TBLOCK]; )
*cp++ = '\0';
writetape(buf);
}
longt(st)
register struct stat *st;
{
register char *cp;
char *ctime();
pmode(st);
printf("%3d/%1d", st->st_uid, st->st_gid);
printf("%7D", st->st_size);
cp = ctime(&st->st_mtime);
printf(" %-12.12s %-4.4s ", cp+4, cp+20);
}
#define SUID 04000
#define SGID 02000
#define ROWN 0400
#define WOWN 0200
#define XOWN 0100
#define RGRP 040
#define WGRP 020
#define XGRP 010
#define ROTH 04
#define WOTH 02
#define XOTH 01
#define STXT 01000
int m1[] = { 1, ROWN, 'r', '-' };
int m2[] = { 1, WOWN, 'w', '-' };
int m3[] = { 2, SUID, 's', XOWN, 'x', '-' };
int m4[] = { 1, RGRP, 'r', '-' };
int m5[] = { 1, WGRP, 'w', '-' };
int m6[] = { 2, SGID, 's', XGRP, 'x', '-' };
int m7[] = { 1, ROTH, 'r', '-' };
int m8[] = { 1, WOTH, 'w', '-' };
int m9[] = { 2, STXT, 't', XOTH, 'x', '-' };
int *m[] = { m1, m2, m3, m4, m5, m6, m7, m8, m9};
pmode(st)
register struct stat *st;
{
register int **mp;
for (mp = &m[0]; mp < &m[9];)
select(*mp++, st);
}
select(pairp, st)
int *pairp;
struct stat *st;
{
register int n, *ap;
ap = pairp;
n = *ap++;
while (--n>=0 && (st->st_mode&*ap++)==0)
ap++;
printf("%c", *ap);
}
checkdir(name)
register char *name;
{
register char *cp;
int i;
for (cp = name; *cp; cp++) {
if (*cp == '/') {
*cp = '\0';
if (access(name, 01) < 0) {
if (fork() == 0) {
execl("/bin/mkdir", "mkdir", name, 0);
execl("/usr/bin/mkdir", "mkdir", name, 0);
fprintf(stderr, "tar: cannot find mkdir!\n");
done(0);
}
while (wait(&i) >= 0);
chown(name, stbuf.st_uid, stbuf.st_gid);
}
*cp = '/';
}
}
}
onintr()
{
signal(SIGINT, SIG_IGN);
term++;
}
onquit()
{
signal(SIGQUIT, SIG_IGN);
term++;
}
onhup()
{
signal(SIGHUP, SIG_IGN);
term++;
}
onterm()
{
signal(SIGTERM, SIG_IGN);
term++;
}
tomodes(sp)
register struct stat *sp;
{
register char *cp;
for (cp = dblock.dummy; cp < &dblock.dummy[TBLOCK]; cp++)
*cp = '\0';
sprintf(dblock.dbuf.mode, "%6o ", sp->st_mode & 07777);
sprintf(dblock.dbuf.uid, "%6o ", sp->st_uid);
sprintf(dblock.dbuf.gid, "%6o ", sp->st_gid);
sprintf(dblock.dbuf.size, "%11lo ", sp->st_size);
sprintf(dblock.dbuf.mtime, "%11lo ", sp->st_mtime);
}
checksum()
{
register i;
register char *cp;
for (cp = dblock.dbuf.chksum; cp < &dblock.dbuf.chksum[sizeof(dblock.dbuf.chksum)]; cp++)
*cp = ' ';
i = 0;
for (cp = dblock.dummy; cp < &dblock.dummy[TBLOCK]; cp++)
i += *cp;
return(i);
}
checkw(c, name)
char *name;
{
if (wflag) {
printf("%c ", c);
if (vflag)
longt(&stbuf);
printf("%s: ", name);
if (response() == 'y'){
return(1);
}
return(0);
}
return(1);
}
response()
{
char c;
c = getchar();
if (c != '\n')
while (getchar() != '\n');
else c = 'n';
return(c);
}
checkupdate(arg)
char *arg;
{
char name[100];
long mtime;
daddr_t seekp;
daddr_t lookup();
rewind(tfile);
for (;;) {
if ((seekp = lookup(arg)) < 0)
return(1);
fseek(tfile, seekp, 0);
fscanf(tfile, "%s %lo", name, &mtime);
if (stbuf.st_mtime > mtime)
return(1);
else
return(0);
}
}
done(n)
{
unlink(tname);
exit(n);
}
prefix(s1, s2)
register char *s1, *s2;
{
while (*s1)
if (*s1++ != *s2++)
return(0);
if (*s2)
return(*s2 == '/');
return(1);
}
getwdir(s)
char *s;
{
int i;
int pipdes[2];
pipe(pipdes);
if ((i = fork()) == 0) {
close(1);
dup(pipdes[1]);
execl("/bin/pwd", "pwd", 0);
execl("/usr/bin/pwd", "pwd", 0);
fprintf(stderr, "pwd failed!\n");
printf("/\n");
exit(1);
}
while (wait((int *)NULL) != -1)
;
read(pipdes[0], s, 50);
while(*s != '\n')
s++;
*s = '\0';
close(pipdes[0]);
close(pipdes[1]);
}
#define N 200
int njab;
daddr_t
lookup(s)
char *s;
{
register i;
daddr_t a;
for(i=0; s[i]; i++)
if(s[i] == ' ')
break;
a = bsrch(s, i, low, high);
return(a);
}
daddr_t
bsrch(s, n, l, h)
daddr_t l, h;
char *s;
{
register i, j;
char b[N];
daddr_t m, m1;
njab = 0;
loop:
if(l >= h)
return(-1L);
m = l + (h-l)/2 - N/2;
if(m < l)
m = l;
fseek(tfile, m, 0);
fread(b, 1, N, tfile);
njab++;
for(i=0; i<N; i++) {
if(b[i] == '\n')
break;
m++;
}
if(m >= h)
return(-1L);
m1 = m;
j = i;
for(i++; i<N; i++) {
m1++;
if(b[i] == '\n')
break;
}
i = cmp(b+j, s, n);
if(i < 0) {
h = m;
goto loop;
}
if(i > 0) {
l = m1;
goto loop;
}
return(m);
}
cmp(b, s, n)
char *b, *s;
{
register i;
if(b[0] != '\n')
exit(2);
for(i=0; i<n; i++) {
if(b[i+1] > s[i])
return(-1);
if(b[i+1] < s[i])
return(1);
}
return(b[i+1] == ' '? 0 : -1);
}
readtape(buffer)
char *buffer;
{
int i, j;
if (recno >= nblock || first == 0) {
if (first == 0 && nblock == 0)
j = NBLOCK;
else
j = nblock;
if ((i = read(mt, tbuf, TBLOCK*j)) < 0) {
fprintf(stderr, "Tar: tape read error\n");
done(3);
}
if (first == 0) {
if ((i % TBLOCK) != 0) {
fprintf(stderr, "Tar: tape blocksize error\n");
done(3);
}
i /= TBLOCK;
if (rflag && i != 1) {
fprintf(stderr, "Tar: Cannot update blocked tapes (yet)\n");
done(4);
}
if (i != nblock && i != 1) {
fprintf(stderr, "Tar: blocksize = %d\n", i);
nblock = i;
}
}
recno = 0;
}
first = 1;
copy(buffer, &tbuf[recno++]);
return(TBLOCK);
}
writetape(buffer)
char *buffer;
{
first = 1;
if (nblock == 0)
nblock = 1;
if (recno >= nblock) {
if (write(mt, tbuf, TBLOCK*nblock) < 0) {
fprintf(stderr, "Tar: tape write error\n");
done(2);
}
recno = 0;
}
copy(&tbuf[recno++], buffer);
if (recno >= nblock) {
if (write(mt, tbuf, TBLOCK*nblock) < 0) {
fprintf(stderr, "Tar: tape write error\n");
done(2);
}
recno = 0;
}
return(TBLOCK);
}
backtape()
{
lseek(mt, (long) -TBLOCK, 1);
if (recno >= nblock) {
recno = nblock - 1;
if (read(mt, tbuf, TBLOCK*nblock) < 0) {
fprintf(stderr, "Tar: tape read error after seek\n");
done(4);
}
lseek(mt, (long) -TBLOCK, 1);
}
}
flushtape()
{
write(mt, tbuf, TBLOCK*nblock);
}
copy(to, from)
register char *to, *from;
{
register i;
i = TBLOCK;
do {
*to++ = *from++;
} while (--i);
}
| 17.584582 | 96 | 0.547309 | [
"3d"
] |
9725d68ade568e06ff9a1bd68cc350e90016c20e | 25,037 | c | C | miui/src/libs/miui_freetype.c | thenameisnigel/miui_recovery | 169c371b0d9a1b5750c94e7c909aaa477643d76e | [
"BSD-2-Clause"
] | null | null | null | miui/src/libs/miui_freetype.c | thenameisnigel/miui_recovery | 169c371b0d9a1b5750c94e7c909aaa477643d76e | [
"BSD-2-Clause"
] | null | null | null | miui/src/libs/miui_freetype.c | thenameisnigel/miui_recovery | 169c371b0d9a1b5750c94e7c909aaa477643d76e | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright (C) 2011 xiaomi MIUI ( http://xiaomi.com/ )
*
* 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.
*/
/*
* Descriptions:
* -------------
* Freetype Font Handler
*
*/
#include "../miui_inter.h"
/*****************************[ GLOBAL VARIABLES ]*****************************/
static FT_Library aft_lib; // Freetype Library
static byte aft_initialized=0; // Is Library Initialized
static byte aft_locked=0; // On Lock
static AFTFAMILY aft_big; // Big Font Family
static AFTFAMILY aft_small; // Small Font Family
/******************************[ LOCK FUNCTIONS ]******************************/
void aft_waitlock(){ while (aft_locked) usleep(50); aft_locked=1; }
void aft_unlock(){ aft_locked=0; }
/*******************************[ RTL FUNCTION ]*******************************/
//*
//* RTL CHECKER
//*
byte aft_isrtl(int c, byte checkleft){
if (
(c==0x5BE)||(c==0x5C0)||(c==0x5C3)||(c==0x5C6)||((c>=0x5D0)&&(c<=0x5F4))||(c==0x608)||(c==0x60B)||(c==0x60D)||
((c>=0x61B)&&(c<=0x64A))||((c>=0x66D)&&(c<=0x66F))||((c>=0x671)&&(c<=0x6D5))||((c>=0x6E5)&&(c<=0x6E6))||
((c>=0x6EE)&&(c<=0x6EF))||((c>=0x6FA)&&(c<=0x710))||((c>=0x712)&&(c<=0x72F))||((c>=0x74D)&&(c<=0x7A5))||
((c>=0x7B1)&&(c<=0x7EA))||((c>=0x7F4)&&(c<=0x7F5))||((c>=0x7FA)&&(c<=0x815))||(c==0x81A)||(c==0x824)||(c==0x828)||
((c>=0x830)&&(c<=0x858))||((c>=0x85E)&&(c<=0x8AC))||(c==0x200F)||(c==0xFB1D)||((c>=0xFB1F)&&(c<=0xFB28))||
((c>=0xFB2A)&&(c<=0xFD3D))||((c>=0xFD50)&&(c<=0xFDFC))||((c>=0xFE70)&&(c<=0xFEFC))||((c>=0x10800)&&(c<=0x1091B))||
((c>=0x10920)&&(c<=0x10A00))||((c>=0x10A10)&&(c<=0x10A33))||((c>=0x10A40)&&(c<=0x10B35))||((c>=0x10B40)&&(c<=0x10C48))||
((c>=0x1EE00)&&(c<=0x1EEBB))
) return 1;
else if (checkleft){
if (
((c>=0x41)&&(c<=0x5A))||((c>=0x61)&&(c<=0x7A))||(c==0xAA)||(c==0xB5)||(c==0xBA)||((c>=0xC0)&&(c<=0xD6))||
((c>=0xD8)&&(c<=0xF6))||((c>=0xF8)&&(c<=0x2B8))||((c>=0x2BB)&&(c<=0x2C1))||((c>=0x2D0)&&(c<=0x2D1))||
((c>=0x2E0)&&(c<=0x2E4))||(c==0x2EE)||((c>=0x370)&&(c<=0x373))||((c>=0x376)&&(c<=0x37D))||(c==0x386)||
((c>=0x388)&&(c<=0x3F5))||((c>=0x3F7)&&(c<=0x482))||((c>=0x48A)&&(c<=0x589))||((c>=0x903)&&(c<=0x939))||
(c==0x93B)||((c>=0x93D)&&(c<=0x940))||((c>=0x949)&&(c<=0x94C))||((c>=0x94E)&&(c<=0x950))||((c>=0x958)&&(c<=0x961))||
((c>=0x964)&&(c<=0x97F))||((c>=0x982)&&(c<=0x9B9))||((c>=0x9BD)&&(c<=0x9C0))||((c>=0x9C7)&&(c<=0x9CC))||
((c>=0x9CE)&&(c<=0x9E1))||((c>=0x9E6)&&(c<=0x9F1))||((c>=0x9F4)&&(c<=0x9FA))||((c>=0xA03)&&(c<=0xA39))||
((c>=0xA3E)&&(c<=0xA40))||((c>=0xA59)&&(c<=0xA6F))||((c>=0xA72)&&(c<=0xA74))||((c>=0xA83)&&(c<=0xAB9))||
((c>=0xABD)&&(c<=0xAC0))||((c>=0xAC9)&&(c<=0xACC))||((c>=0xAD0)&&(c<=0xAE1))||((c>=0xAE6)&&(c<=0xAF0))||
((c>=0xB02)&&(c<=0xB39))||((c>=0xB3D)&&(c<=0xB3E))||(c==0xB40)||((c>=0xB47)&&(c<=0xB4C))||((c>=0xB57)&&(c<=0xB61))||
((c>=0xB66)&&(c<=0xB77))||((c>=0xB83)&&(c<=0xBBF))||((c>=0xBC1)&&(c<=0xBCC))||((c>=0xBD0)&&(c<=0xBF2))||
((c>=0xC01)&&(c<=0xC3D))||((c>=0xC41)&&(c<=0xC44))||((c>=0xC58)&&(c<=0xC61))||((c>=0xC66)&&(c<=0xC6F))||
((c>=0xC7F)&&(c<=0xCB9))||((c>=0xCBD)&&(c<=0xCCB))||((c>=0xCD5)&&(c<=0xCE1))||((c>=0xCE6)&&(c<=0xD40))||
((c>=0xD46)&&(c<=0xD4C))||((c>=0xD4E)&&(c<=0xD61))||((c>=0xD66)&&(c<=0xDC6))||((c>=0xDCF)&&(c<=0xDD1))||
((c>=0xDD8)&&(c<=0xE30))||(c==0xE32)||(c==0xE40)||((c>=0xE4F)&&(c<=0xEB0))||((c>=0xEB2)&&(c<=0xEB3))||
((c>=0xEBD)&&(c<=0xEC6))||((c>=0xED0)&&(c<=0xF17))||((c>=0xF1A)&&(c<=0xF34))||(c==0xF36)||(c==0xF38)||
((c>=0xF3E)&&(c<=0xF6C))||(c==0xF7F)||(c==0xF85)||((c>=0xF88)&&(c<=0xF8C))||((c>=0xFBE)&&(c<=0xFC5))||
((c>=0xFC7)&&(c<=0x102C))||(c==0x1031)||(c==0x1038)||((c>=0x103B)&&(c<=0x103C))||((c>=0x103F)&&(c<=0x1057))||
((c>=0x105A)&&(c<=0x105D))||((c>=0x1061)&&(c<=0x1070))||((c>=0x1075)&&(c<=0x1081))||((c>=0x1083)&&(c<=0x1084))||
((c>=0x1087)&&(c<=0x108C))||((c>=0x108E)&&(c<=0x109C))||((c>=0x109E)&&(c<=0x135A))||((c>=0x1360)&&(c<=0x138F))||
((c>=0x13A0)&&(c<=0x13F4))||((c>=0x1401)&&(c<=0x167F))||((c>=0x1681)&&(c<=0x169A))||((c>=0x16A0)&&(c<=0x1711))||
((c>=0x1720)&&(c<=0x1731))||((c>=0x1735)&&(c<=0x1751))||((c>=0x1760)&&(c<=0x1770))||((c>=0x1780)&&(c<=0x17B3))||
(c==0x17B6)||((c>=0x17BE)&&(c<=0x17C5))||((c>=0x17C7)&&(c<=0x17C8))||((c>=0x17D4)&&(c<=0x17DA))||(c==0x17DC)||
((c>=0x17E0)&&(c<=0x17E9))||((c>=0x1810)&&(c<=0x18A8))||((c>=0x18AA)&&(c<=0x191C))||((c>=0x1923)&&(c<=0x1926))||
((c>=0x1929)&&(c<=0x1931))||((c>=0x1933)&&(c<=0x1938))||((c>=0x1946)&&(c<=0x19DA))||((c>=0x1A00)&&(c<=0x1A16))||
((c>=0x1A19)&&(c<=0x1A55))||(c==0x1A57)||(c==0x1A61)||((c>=0x1A63)&&(c<=0x1A64))||((c>=0x1A6D)&&(c<=0x1A72))||
((c>=0x1A80)&&(c<=0x1AAD))||((c>=0x1B04)&&(c<=0x1B33))||(c==0x1B35)||(c==0x1B3B)||((c>=0x1B3D)&&(c<=0x1B41))||
((c>=0x1B43)&&(c<=0x1B6A))||((c>=0x1B74)&&(c<=0x1B7C))||((c>=0x1B82)&&(c<=0x1BA1))||((c>=0x1BA6)&&(c<=0x1BA7))||
(c==0x1BAA)||((c>=0x1BAC)&&(c<=0x1BE5))||(c==0x1BE7)||((c>=0x1BEA)&&(c<=0x1BEC))||(c==0x1BEE)||((c>=0x1BF2)&&(c<=0x1C2B))||
((c>=0x1C34)&&(c<=0x1C35))||((c>=0x1C3B)&&(c<=0x1CC7))||(c==0x1CD3)||(c==0x1CE1)||((c>=0x1CE9)&&(c<=0x1CEC))||
((c>=0x1CEE)&&(c<=0x1CF3))||((c>=0x1CF5)&&(c<=0x1DBF))||((c>=0x1E00)&&(c<=0x1FBC))||(c==0x1FBE)||((c>=0x1FC2)&&(c<=0x1FCC))||
((c>=0x1FD0)&&(c<=0x1FDB))||((c>=0x1FE0)&&(c<=0x1FEC))||((c>=0x1FF2)&&(c<=0x1FFC))||(c==0x200E)||(c==0x2071)||(c==0x207F)||
((c>=0x2090)&&(c<=0x209C))||(c==0x2102)||(c==0x2107)||((c>=0x210A)&&(c<=0x2113))||(c==0x2115)||((c>=0x2119)&&(c<=0x211D))||
(c==0x2124)||(c==0x2126)||(c==0x2128)||((c>=0x212A)&&(c<=0x212D))||((c>=0x212F)&&(c<=0x2139))||((c>=0x213C)&&(c<=0x213F))||
((c>=0x2145)&&(c<=0x2149))||((c>=0x214E)&&(c<=0x214F))||((c>=0x2160)&&(c<=0x2188))||((c>=0x2336)&&(c<=0x237A))||(c==0x2395)||
((c>=0x249C)&&(c<=0x24E9))||(c==0x26AC)||((c>=0x2800)&&(c<=0x28FF))||((c>=0x2C00)&&(c<=0x2CE4))||((c>=0x2CEB)&&(c<=0x2CEE))||
((c>=0x2CF2)&&(c<=0x2CF3))||((c>=0x2D00)&&(c<=0x2D70))||((c>=0x2D80)&&(c<=0x2DDE))||((c>=0x3005)&&(c<=0x3007))||
((c>=0x3021)&&(c<=0x3029))||((c>=0x302E)&&(c<=0x302F))||((c>=0x3031)&&(c<=0x3035))||((c>=0x3038)&&(c<=0x303C))||
((c>=0x3041)&&(c<=0x3096))||((c>=0x309D)&&(c<=0x309F))||((c>=0x30A1)&&(c<=0x30FA))||((c>=0x30FC)&&(c<=0x31BA))||
((c>=0x31F0)&&(c<=0x321C))||((c>=0x3220)&&(c<=0x324F))||((c>=0x3260)&&(c<=0x327B))||((c>=0x327F)&&(c<=0x32B0))||
((c>=0x32C0)&&(c<=0x32CB))||((c>=0x32D0)&&(c<=0x3376))||((c>=0x337B)&&(c<=0x33DD))||((c>=0x33E0)&&(c<=0x33FE))||
((c>=0x3400)&&(c<=0x4DB5))||((c>=0x4E00)&&(c<=0xA48C))||((c>=0xA4D0)&&(c<=0xA60C))||((c>=0xA610)&&(c<=0xA66E))||
((c>=0xA680)&&(c<=0xA697))||((c>=0xA6A0)&&(c<=0xA6EF))||((c>=0xA6F2)&&(c<=0xA6F7))||((c>=0xA722)&&(c<=0xA787))||
((c>=0xA789)&&(c<=0xA801))||((c>=0xA803)&&(c<=0xA805))||((c>=0xA807)&&(c<=0xA80A))||((c>=0xA80C)&&(c<=0xA824))||(c==0xA827)||
((c>=0xA830)&&(c<=0xA837))||((c>=0xA840)&&(c<=0xA873))||((c>=0xA880)&&(c<=0xA8C3))||((c>=0xA8CE)&&(c<=0xA8D9))||
((c>=0xA8F2)&&(c<=0xA925))||((c>=0xA92E)&&(c<=0xA946))||((c>=0xA952)&&(c<=0xA97C))||((c>=0xA983)&&(c<=0xA9B2))||
((c>=0xA9B4)&&(c<=0xA9B5))||((c>=0xA9BA)&&(c<=0xA9BB))||((c>=0xA9BD)&&(c<=0xAA28))||((c>=0xAA2F)&&(c<=0xAA30))||
((c>=0xAA33)&&(c<=0xAA34))||((c>=0xAA40)&&(c<=0xAA42))||((c>=0xAA44)&&(c<=0xAA4B))||((c>=0xAA4D)&&(c<=0xAAAF))||
(c==0xAAB1)||((c>=0xAAB5)&&(c<=0xAAB6))||((c>=0xAAB9)&&(c<=0xAABD))||(c==0xAAC0)||((c>=0xAAC2)&&(c<=0xAAEB))||
((c>=0xAAEE)&&(c<=0xAAF5))||((c>=0xAB01)&&(c<=0xABE4))||((c>=0xABE6)&&(c<=0xABE7))||((c>=0xABE9)&&(c<=0xABEC))||
((c>=0xABF0)&&(c<=0xFB17))||((c>=0xFF21)&&(c<=0xFF3A))||((c>=0xFF41)&&(c<=0xFF5A))||((c>=0xFF66)&&(c<=0xFFDC))||
((c>=0x10000)&&(c<=0x10100))||((c>=0x10102)&&(c<=0x1013F))||((c>=0x101D0)&&(c<=0x101FC))||((c>=0x10280)&&(c<=0x104A9))||
(c==0x11000)||((c>=0x11002)&&(c<=0x11037))||((c>=0x11047)&&(c<=0x1104D))||((c>=0x11066)&&(c<=0x1106F))||((c>=0x11082)&&(c<=0x110B2))||
((c>=0x110B7)&&(c<=0x110B8))||((c>=0x110BB)&&(c<=0x110F9))||((c>=0x11103)&&(c<=0x11126))||(c==0x1112C)||((c>=0x11136)&&(c<=0x11143))||
((c>=0x11182)&&(c<=0x111B5))||((c>=0x111BF)&&(c<=0x116AA))||(c==0x116AC)||((c>=0x116AE)&&(c<=0x116AF))||(c==0x116B6)||
((c>=0x116C0)&&(c<=0x16F7E))||((c>=0x16F93)&&(c<=0x1D166))||((c>=0x1D16A)&&(c<=0x1D172))||((c>=0x1D183)&&(c<=0x1D184))||
((c>=0x1D18C)&&(c<=0x1D1A9))||((c>=0x1D1AE)&&(c<=0x1D1DD))||((c>=0x1D360)&&(c<=0x1D6DA))||((c>=0x1D6DC)&&(c<=0x1D714))||
((c>=0x1D716)&&(c<=0x1D74E))||((c>=0x1D750)&&(c<=0x1D788))||((c>=0x1D78A)&&(c<=0x1D7C2))||((c>=0x1D7C4)&&(c<=0x1D7CB))||
((c>=0x1F110)&&(c<=0x1F169))||((c>=0x1F170)&&(c<=0x1F251))||((c>=0x20000)&&(c<=0x2FA1D))
) return 0;
}
return (checkleft?2:0);
}
/*****************************[ ARABIC FUNCTIONS ]****************************/
//*
//* ARABIC MACROS
//*
#define AFT_ARABIC_PROP_ISOLATED 0
#define AFT_ARABIC_PROP_INITIAL 1
#define AFT_ARABIC_PROP_MEDIAL 2
#define AFT_ARABIC_PROP_FINAL 3
#define AFT_ARABIC_CLASS_NONE 0
#define AFT_ARABIC_CLASS_TRANSPARENT 1
#define AFT_ARABIC_CLASS_RIGHT 2
#define AFT_ARABIC_CLASS_DUAL 3
#define AFT_ARABIC_CLASS_CAUSING 4
//*
//* ARABIC CONSTANT
//*
static const byte AFT_ARABIC[] = {
/* U+0620 */ 0, 0, 2, 2, 2, 2, 3, 2, 3, 2, 3, 3, 3, 3, 3, 2,
/* U+0630 */ 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0,
/* U+0640 */ 4, 3, 3, 3, 3, 3, 3, 3, 2, 3, 3, 1, 1, 1, 1, 1,
/* U+0650 */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0,
/* U+0660 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3,
/* U+0670 */ 1, 2, 2, 2, 0, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3,
/* U+0680 */ 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2,
/* U+0690 */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3,
/* U+06A0 */ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
/* U+06B0 */ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
/* U+06C0 */ 2, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 2, 3, 2,
/* U+06D0 */ 3, 3, 2, 2, 0, 2, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1,
/* U+06E0 */ 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 2, 2,
/* U+06F0 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 0, 0, 3
};
static const byte AFT_ARABIC_SUP[] = {
/* U+0750 */ 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 3, 3, 3, 3,
/* U+0760 */ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 0, 0,
/* U+0770 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
static const byte AFT_ARABIC_NKO[] =
{
/* U+07C0 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 3, 3, 3,
/* U+07D0 */ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
/* U+07E0 */ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1,
/* U+07F0 */ 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0,
};
static const int AFT_ARABIC_PRES[]={
0xFE81, 0xFE82, 0, 0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0xFE8D, 0xFE8E, 0, 0, 0xFE8F, 0xFE90, 0xFE92, 0xFE91,
0xFE93, 0xFE94, 0, 0, 0xFE95, 0xFE96, 0xFE98, 0xFE97, 0xFE99, 0xFE9A, 0xFE9C, 0xFE9B, 0xFE9D, 0xFE9E, 0xFEA0, 0xFE9F,
0xFEA1, 0xFEA2, 0xFEA4, 0xFEA3, 0xFEA5, 0xFEA6, 0xFEA8, 0xFEA7, 0xFEA9, 0xFEAA, 0, 0, 0xFEAB, 0xFEAC, 0, 0,
0xFEAD, 0xFEAE, 0, 0, 0xFEAF, 0xFEB0, 0, 0, 0xFEB1, 0xFEB2, 0xFEB4, 0xFEB3, 0xFEB5, 0xFEB6, 0xFEB8, 0xFEB7,
0xFEB9, 0xFEBA, 0xFEBC, 0xFEBB, 0xFEBD, 0xFEBE, 0xFEC0, 0xFEBF, 0xFEC1, 0xFEC2, 0xFEC4, 0xFEC3, 0xFEC5, 0xFEC6, 0xFEC8, 0xFEC7,
0xFEC9, 0xFECA, 0xFECC, 0xFECB, 0xFECD, 0xFECE, 0xFED0, 0xFECF, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,
0,0,0,0, 0xFED1, 0xFED2, 0xFED4, 0xFED3, 0xFED5, 0xFED6, 0xFED8, 0xFED7, 0xFED9, 0xFEDA, 0xFEDC, 0xFEDB,
0xFEDD, 0xFEDE, 0xFEE0, 0xFEDF, 0xFEE1, 0xFEE2, 0xFEE4, 0xFEE3, 0xFEE5, 0xFEE6, 0xFEE8, 0xFEE7, 0xFEE9, 0xFEEA, 0xFEEC, 0xFEEB,
0xFEED, 0xFEEE, 0, 0, 0xFEEF, 0xFEF0, 0, 0, 0xFEF1, 0xFEF2, 0xFEF4, 0xFEF3
};
//*
//* Get Arabic Character Class
//*
static byte AFT_ARABIC_GETCLASS(int * string, int pos, int length, int direction){
byte j=0;
while (1) {
if (pos==0&&direction<0) return AFT_ARABIC_CLASS_NONE;
pos += direction;
if (pos >= length) return AFT_ARABIC_CLASS_NONE;
if (string[pos]>=0x0620 && string[pos] < 0x0700) j = AFT_ARABIC[string[pos] - 0x0620];
else if (string[pos]>=0x0750 && string[pos]<0x0780) j = AFT_ARABIC_SUP[string[pos] - 0x0750];
else if (string[pos]>=0x07C0 && string[pos]<0x0800) j = AFT_ARABIC_NKO[string[pos] - 0x07C0];
else if (string[pos]==0x200D) return AFT_ARABIC_CLASS_CAUSING;
else return AFT_ARABIC_CLASS_NONE;
if (!direction||j!=AFT_ARABIC_CLASS_TRANSPARENT) return j;
}
return AFT_ARABIC_CLASS_NONE;
}
//*
//* Get Arabic Character Properties
//*
static byte AFT_ARABIC_GETPROP(int *string, byte *prop, int length){
byte cp, cc, cn;
int i;
if (!string||!prop||length==0) return 0;
for (i = 0; i < length; i++) {
cp = AFT_ARABIC_GETCLASS(string, i, length, -1);
cc = AFT_ARABIC_GETCLASS(string, i, length, 0);
cn = AFT_ARABIC_GETCLASS(string, i, length, 1);
if (cc==AFT_ARABIC_CLASS_TRANSPARENT) {
prop[i] = AFT_ARABIC_PROP_ISOLATED;
continue;
}
if (cp==AFT_ARABIC_CLASS_CAUSING || cp==AFT_ARABIC_CLASS_DUAL){
if (cc==AFT_ARABIC_CLASS_RIGHT){
prop[i] = AFT_ARABIC_PROP_FINAL;
continue;
}
}
if (cp==AFT_ARABIC_CLASS_CAUSING || cp==AFT_ARABIC_CLASS_DUAL){
if (cc==AFT_ARABIC_CLASS_DUAL){
if (cn==AFT_ARABIC_CLASS_CAUSING||cn==AFT_ARABIC_CLASS_RIGHT||cn==AFT_ARABIC_CLASS_DUAL){
prop[i] = AFT_ARABIC_PROP_MEDIAL;
continue;
}
}
}
if (cp==AFT_ARABIC_CLASS_CAUSING || cp==AFT_ARABIC_CLASS_DUAL){
if (cc==AFT_ARABIC_CLASS_DUAL){
if (!(cn==AFT_ARABIC_CLASS_CAUSING||cn==AFT_ARABIC_CLASS_RIGHT||cn==AFT_ARABIC_CLASS_DUAL)){
prop[i] = AFT_ARABIC_PROP_FINAL;
continue;
}
}
}
if (!(cp==AFT_ARABIC_CLASS_CAUSING||cp==AFT_ARABIC_CLASS_DUAL)){
if (cc==AFT_ARABIC_CLASS_DUAL){
if (cn==AFT_ARABIC_CLASS_CAUSING||cn==AFT_ARABIC_CLASS_RIGHT||cn==AFT_ARABIC_CLASS_DUAL){
prop[i] = AFT_ARABIC_PROP_INITIAL;
continue;
}
}
}
prop[i] = AFT_ARABIC_PROP_ISOLATED;
}
return 1;
}
//*
//* Is Character was Arabic Character?
//*
byte AFT_ISARABIC(int c){
if (c >= 0x0620 && c < 0x0700) return 1;
else if (c >= 0x0750 && c < 0x0780) return 1;
else if (c >= 0x07C0 && c < 0x0800) return 1;
else if (c == 0x200D) return 1;
return 0;
}
//*
//* Read and Convert Arabic Unicode Chars
//*
byte aft_read_arabic(int * soff, const char * src, const char ** ss, int * string, byte * prop, int maxlength, int * outlength, int * move){
if (!AFT_ISARABIC(*soff)) return 0;
int off=*soff;
int i=0;
memset(string, 0, sizeof(int) *maxlength);
memset(prop, 0, sizeof(byte)*maxlength);
const char * read_buffer = src;
const char * readed_buffer= src;
int readed_off = off;
int last_movesz= 0;
do{
if (i>=maxlength) break;
string[i++] = off;
int movesz= 0;
readed_buffer = read_buffer;
readed_off = off;
off=utf8c(read_buffer,&read_buffer,&movesz);
*move+=movesz;
last_movesz=movesz;
}while(AFT_ISARABIC(off));
if (ss!=NULL) *ss = readed_buffer;
*soff = readed_off;
*outlength = i;
*move-=last_movesz;
//-- FETCH ARABIC PROP
AFT_ARABIC_GETPROP(string,prop,i);
int j=0;
for (j=0;j<i;j++){
int cs = string[j];
byte ps= prop[j];
if ((cs>=0x622)&&(cs<=0x64A)){
int psub = ((cs-0x622)*4);
if (ps==AFT_ARABIC_PROP_INITIAL) psub+=3;
else if (ps==AFT_ARABIC_PROP_MEDIAL) psub+=2;
else if (ps==AFT_ARABIC_PROP_FINAL) psub+=1;
int csub = AFT_ARABIC_PRES[psub];
if (csub!=0) string[j]=csub;
}
}
return 1;
}
/**************************[ GLYPH CACHE MANAGEMENT ]***************************/
//*
//* Create Glyph Cache for given face
//*
byte aft_createglyph(AFTFACEP f){
if (!aft_initialized) return 0;
if (f==NULL) return 0;
f->cache_n = f->face->num_glyphs;
int sz = f->cache_n * sizeof(AFTGLYPH);
f->cache = (AFTGLYPHP) malloc(sz);
memset(f->cache,0,sz);
return 1;
}
//*
//* Close Glyph Cache for given face
//*
byte aft_closeglyph(AFTFACEP f){
if (!aft_initialized) return 0;
if (f==NULL) return 0;
if (f->cache!=NULL){
long i=0;
for (i=0;i<f->cache_n;i++){
if (f->cache[i].init){
FT_Done_Glyph(f->cache[i].g);
f->cache[i].init=0;
}
}
free(f->cache);
f->cache=NULL;
f->cache_n=0;
}
return 1;
}
//*
//* Cache Readed Glyph
//*
byte aft_cacheglyph(AFTFACEP f, long id){
if (!aft_initialized) return 0;
if (f==NULL) return 0;
if (f->cache_n<id) return 0;
if (!f->cache[id].init){
FT_Get_Glyph(f->face->glyph, &f->cache[id].g);
f->cache[id].w = f->face->glyph->advance.x >> 6;
f->cache[id].init = 1;
}
return 1;
}
/**************************[ FONT FAMILY MANAGEMENT ]***************************/
//*
//* Get glyph index & face for given character
//*
long aft_id(AFTFACEP * f, int c, byte isbig){
if (!aft_initialized) return 0;
if (c==0xfeff) return 0;
AFTFAMILYP m = (isbig!=0)?&aft_big:&aft_small;
if (!m->init) return 0;
if (m->facen>0){
aft_waitlock();
long id = 0;
int i = 0;
for (i=0;i<m->facen;i++){
id = FT_Get_Char_Index(m->faces[i].face,c);
if (id!=0){
*f = &(m->faces[i]);
aft_unlock();
return id;
}
}
*f = &(m->faces[0]);
aft_unlock();
return 0;
}
return 0;
}
//*
//* Get horizontal kerning size for given chars
//*
int aft_kern(int c, int p, byte isbig){
if (!aft_initialized) return 0;
if ((c==0xfeff)||(p==0xfeff)) return 0;
AFTFAMILYP m = (isbig!=0)?&aft_big:&aft_small;
if (!m->init) return 0;
AFTFACEP cf=NULL;
AFTFACEP pf=NULL;
long up = aft_id(&pf,p,isbig);
long uc = aft_id(&cf,c,isbig);
if (up&&uc&&cf&&pf){
if (cf==pf){
if (cf->kern==1){
aft_waitlock();
FT_Vector delta;
FT_Get_Kerning(cf->face, up, uc, FT_KERNING_DEFAULT, &delta );
aft_unlock();
return (delta.x >> 6);
}
}
}
return 0;
}
//*
//* Free Font Family
//*
byte aft_free(AFTFAMILYP m){
if (!aft_initialized) return 0;
if (m==NULL) return 0;
if (!m->init) return 0;
int fn = m->facen;
m->facen=0;
m->init=0;
if (fn>0){
int i;
for (i=0;i<fn;i++){
aft_closeglyph(&(m->faces[i]));
FT_Done_Face(m->faces[i].face);
free(m->faces[i].mem);
}
free(m->faces);
}
return 1;
}
//*
//* Load Font Family
//*
byte aft_load(const char * source_name, int size, byte isbig,char * relativeto){
if (!aft_initialized) return 0;
const char * zip_paths = source_name;
char vc=0;
char zpaths[10][256];
int count = 0;
int zpath_n = 0;
while ((vc=*zip_paths++)){
if ((zpath_n>=255)||(count>=10)) break;
if (zpath_n==0) count++;
if (vc==';'){
zpaths[count-1][zpath_n] =0;
zpath_n=0;
}
else{
zpaths[count-1][zpath_n++]=vc;
zpaths[count-1][zpath_n] =0;
}
}
//-- Calculating Size
if (!size) size = 12; //-- Default Font Size
if (count>10) count = 10; //-- Maximum Font per Family
byte m_s = size;
byte m_p = ceil((agdp() * m_s) / 2);
byte m_h = ceil(m_p * 1.1);
byte m_y = (m_h-m_p)*2;
//-- Load Faces
int i=0;
int c=0;
FT_Face ftfaces[10];
char * ftmem[10];
for (i=0;i<count;i++){
if (strlen(zpaths[i])>0){
char zpath[256];
snprintf(zpath,256,"%s%s",relativeto,zpaths[i]);
AZMEM mem;
if (az_readmem(&mem,zpath,1)){
if (FT_New_Memory_Face(aft_lib,mem.data,mem.sz,0,&ftfaces[c])==0){
if (FT_Set_Pixel_Sizes(ftfaces[c], 0, m_p)==0){
ftmem[c]=(char*)mem.data;
c++;
}
else{
FT_Done_Face(ftfaces[c]);
free(mem.data);
}
}
else
free(mem.data);
}
}
}
if (c>0){
aft_waitlock();
AFTFAMILYP m = (isbig!=0)?&aft_big:&aft_small;
//-- Cleanup Font
aft_free(m);
m->s = m_s;
m->p = m_p;
m->h = m_h;
m->y = m_y;
m->faces = malloc(sizeof(AFTFACE) * c);
memset(m->faces,0,sizeof(AFTFACE) * c);
for (i=0;i<c;i++){
m->faces[i].face=ftfaces[i];
m->faces[i].mem =ftmem[i];
m->faces[i].kern=FT_HAS_KERNING(m->faces[i].face)?1:0;
aft_createglyph(&(m->faces[i]));
}
m->facen = c;
m->init = 1;
miui_debug("(%i) Freetype fonts loaded as Font Family\n",c);
aft_unlock();
return 1;
}
LOGS("No Freetype fonts loaded. Using png font.\n");
return 0;
}
//*
//* Open Freetype Library
//*
byte aft_open(){
miui_debug("function %s entry...\n", __FUNCTION__);
if (aft_initialized) return 0;
aft_big.init=0;
aft_small.init=0;
if (FT_Init_FreeType( &aft_lib )==0){
aft_initialized=1;
return 1;
}
return 0;
}
//*
//* Is Font Ready?
//*
byte aft_fontready(byte isbig){
if (!aft_initialized) return 0;
AFTFAMILYP m = (isbig)?&aft_big:&aft_small;
if (!m->init) return 0;
return 1;
}
//*
//* Close Freetype Library
//*
byte aft_close(){
if (!aft_initialized) return 0;
//-- Release All Font Family
aft_free(&aft_big);
aft_free(&aft_small);
if (FT_Done_FreeType( aft_lib )==0){
aft_initialized = 0;
return 1;
}
return 0;
}
//*
//* Font Width - No Auto Unlock
//*
int aft_fontwidth_lock(int c,byte isbig,AFTGLYPHP * ch,byte * onlock){
if (!aft_initialized) return 0;
if (c==0xfeff) return 0;
AFTFACEP f = NULL;
long uc = aft_id(&f, c, isbig);
if (f==NULL) return 0;
if (f->cache==NULL) return 0;
if (uc>f->cache_n) return 0;
aft_waitlock();
*onlock=1;
if (f->cache[uc].init){
if (ch!=NULL) *ch=&f->cache[uc];
return f->cache[uc].w;
}
if (FT_Load_Glyph(f->face,uc,FT_LOAD_DEFAULT)==0){
if (aft_cacheglyph(f,uc)){
if (ch!=NULL) *ch=&f->cache[uc];
return f->cache[uc].w;
}
return 0;
}
return 0;
}
//*
//* Font Width - Auto Unlock
//*
int aft_fontwidth(int c,byte isbig){
if (!aft_initialized) return 0;
byte onlock=0;
int w=aft_fontwidth_lock(c,isbig,NULL,&onlock);
if (onlock) aft_unlock();
return w;
}
//*
//* Space Width
//*
int aft_spacewidth(byte isbig){
if (!aft_initialized) return 0;
return aft_fontwidth(' ',isbig);
}
//*
//* Font Height
//*
byte aft_fontheight(byte isbig){
if (!aft_initialized) return 0;
AFTFAMILYP m = (isbig)?&aft_big:&aft_small;
if (!m->init) return 0;
return m->h;
}
//*
//* Draw Font
//*
byte aft_drawfont(CANVAS * _b, byte isbig, int fpos, int xpos, int ypos, color cl,byte underline,byte bold){
if (!aft_initialized) return 0;
//-- Is Default Canvas?
if (_b==NULL) _b=agc();
//-- Get Font Glyph
AFTFAMILYP m = (isbig)?&aft_big:&aft_small;
if (!m->init) return 0;
AFTGLYPHP ch = NULL;
byte onlock = 0;
int fw = aft_fontwidth_lock(fpos,isbig,&ch,&onlock);
int fh = aft_fontheight(isbig);
//-- Check Validity
if ((fw==0)||(ch==NULL)){
if (onlock) aft_unlock();
return 0;
}
if (!ch->init){
if (onlock) aft_unlock();
return 0;
}
//-- Copy & Render
FT_Glyph glyph;
FT_Glyph_Copy(ch->g,&glyph);
FT_Glyph_To_Bitmap(&glyph,FT_RENDER_MODE_NORMAL,0,1);
//-- Prepare Raster Glyph
FT_BitmapGlyph bit = (FT_BitmapGlyph) glyph;
//-- Draw
int xx, yy;
int fhalf=ceil(fh/2);
for (yy=0; yy < bit->bitmap.rows; yy++) {
for (xx=0; xx < bit->bitmap.width; xx++) {
byte a = bit->bitmap.buffer[ (yy * bit->bitmap.pitch) + xx ];
if (a>0){
int bx = xpos+bit->left+xx;
int by = (ypos+yy+fh-m->y)-bit->top;
ag_subpixel(_b,bx,by,cl,a);
if (bold){
ag_subpixel(_b,bx-1,by-1,cl,a/4);
ag_subpixel(_b,bx, by-1,cl,a/2);
ag_subpixel(_b,bx+1,by-1,cl,a/4);
ag_subpixel(_b,bx-1,by,cl,a/2);
ag_subpixel(_b,bx,by,cl,a);
}
}
}
}
//-- Release Glyph
FT_Done_Glyph(glyph);
//-- Draw Underline
if (underline){
int usz = ceil(m->p/12);
int ux,uy;
for (uy=m->p-usz;uy<m->p;uy++){
for (ux=0;ux<fw;ux++){
ag_setpixel(_b,xpos+ux,ypos+uy,cl);
}
}
}
//-- Unlock
if (onlock) aft_unlock();
return 1;
}
| 35.164326 | 140 | 0.53373 | [
"render"
] |
973ebbf9d111dacf168e2e968320cc0c5ecd6962 | 4,517 | h | C | vtools/ContourLab/src/Contour.Pretext.gen.h | SergeyStrukov/CCore-3-xx | 820507e78f8aa35ca05761e00e060c8f64c59af5 | [
"BSL-1.0"
] | 8 | 2017-12-21T07:00:16.000Z | 2020-04-02T09:05:55.000Z | vtools/ContourLab/src/Contour.Pretext.gen.h | SergeyStrukov/CCore-3-xx | 820507e78f8aa35ca05761e00e060c8f64c59af5 | [
"BSL-1.0"
] | null | null | null | vtools/ContourLab/src/Contour.Pretext.gen.h | SergeyStrukov/CCore-3-xx | 820507e78f8aa35ca05761e00e060c8f64c59af5 | [
"BSL-1.0"
] | 1 | 2020-03-30T09:54:18.000Z | 2020-03-30T09:54:18.000Z | " \n"
" \n"
" \n"
" \n"
" \n"
" \n"
" \n"
" \n"
" \n"
" \n"
" \n"
" \n"
"\n"
" \n"
"\n"
"type Bool = uint8 ;\n"
"\n"
"Bool True = 1 ;\n"
"\n"
"Bool False = 0 ;\n"
"\n"
"struct Label\n"
" {\n"
" text name;\n"
"\n"
" Bool show;\n"
" Bool gray;\n"
" Bool show_name;\n"
" };\n"
"\n"
"type Exception = uint8 ;\n"
"\n"
" \n"
"\n"
"struct Real\n"
" {\n"
" sint64 mantissa;\n"
" sint16 exp;\n"
" };\n"
" \n"
"struct Ratio\n"
" {\n"
" Real val;\n"
" Exception rex;\n"
" };\n"
" \n"
"struct Length\n"
" {\n"
" Real val;\n"
" Exception rex;\n"
" }; \n"
" \n"
"struct Angle\n"
" {\n"
" Real val;\n"
" Exception rex;\n"
" };\n"
" \n"
"struct Point\n"
" {\n"
" Real x;\n"
" Real y;\n"
" Exception rex;\n"
" }; \n"
" \n"
"struct Line\n"
" {\n"
" Point a;\n"
" Point ort;\n"
" Exception rex;\n"
" };\n"
" \n"
"struct Circle \n"
" {\n"
" Point center;\n"
" Length radius;\n"
" Exception rex;\n"
" };\n"
" \n"
"struct Couple\n"
" {\n"
" Point a;\n"
" Point b;\n"
" Exception rex;\n"
" };\n"
" \n"
"struct Dot \n"
" {\n"
" Point point;\n"
" Bool break_flag;\n"
" };\n"
" \n"
"struct Step \n"
" {\n"
" Point[] points;\n"
" Exception rex;\n"
" };\n"
" \n"
"struct Path\n"
" {\n"
" Dot[] dots;\n"
" Exception rex;\n"
" };\n"
" \n"
"struct Loop\n"
" {\n"
" Dot[] dots;\n"
" Exception rex;\n"
" };\n"
" \n"
"struct Solid\n"
" {\n"
" Dot[] dots;\n"
" Exception rex;\n"
" };\n"
"\n"
" \n"
"\n"
"struct Pad\n"
" {\n"
" Label label;\n"
" ulen index;\n"
" \n"
" {Ratio,Length,Angle,Point} *object;\n"
" };\n"
"\n"
" \n"
"\n"
"struct Neg\n"
" {\n"
" Arg a;\n"
" };\n"
" \n"
"struct Add\n"
" {\n"
" Arg a;\n"
" Arg b; \n"
" };\n"
" \n"
"struct Sub\n"
" {\n"
" Arg a;\n"
" Arg b; \n"
" };\n"
" \n"
"struct Mul\n"
" {\n"
" Arg a;\n"
" Arg b; \n"
" };\n"
" \n"
"struct Div\n"
" {\n"
" Arg a;\n"
" Arg b; \n"
" };\n"
"\n"
"struct LengthOf\n"
" {\n"
" Arg a;\n"
" Arg b; \n"
" };\n"
" \n"
"struct AngleOf\n"
" {\n"
" Arg a;\n"
" Arg b;\n"
" Arg c; \n"
" };\n"
" \n"
"struct LineOf\n"
" {\n"
" Arg a;\n"
" Arg b; \n"
" }; \n"
" \n"
"struct Middle\n"
" {\n"
" Arg a;\n"
" Arg b; \n"
" };\n"
" \n"
"struct Part\n"
" {\n"
" Arg a;\n"
" Arg b; \n"
" Arg c; \n"
" };\n"
" \n"
"struct MidOrt \n"
" {\n"
" Arg a;\n"
" Arg b; \n"
" };\n"
" \n"
"struct CircleOf \n"
" {\n"
" Arg a;\n"
" Arg b; \n"
" };\n"
" \n"
"struct CircleOuter \n"
" {\n"
" Arg a;\n"
" Arg b; \n"
" Arg c; \n"
" };\n"
" \n"
"struct Proj \n"
" {\n"
" Arg a;\n"
" Arg b; \n"
" };\n"
" \n"
"struct AngleC \n"
" {\n"
" Arg a;\n"
" Arg b; \n"
" Arg c; \n"
" };\n"
" \n"
"struct Meet \n"
" {\n"
" Arg a;\n"
" Arg b; \n"
" };\n"
" \n"
"struct MeetCircle\n"
" {\n"
" Arg a;\n"
" Arg b; \n"
" };\n"
" \n"
"struct MeetCircles\n"
" {\n"
" Arg a;\n"
" Arg b; \n"
" };\n"
" \n"
"struct Rotate \n"
" {\n"
" Arg a;\n"
" Arg b; \n"
" Arg c; \n"
" };\n"
"\n"
"struct RotateOrt\n"
" {\n"
" Arg a;\n"
" Arg b; \n"
" };\n"
"\n"
"struct Move\n"
" {\n"
" Arg a;\n"
" Arg b; \n"
" Arg c; \n"
" };\n"
" \n"
"struct MoveLen\n"
" {\n"
" Arg a;\n"
" Arg b; \n"
" Arg c; \n"
" };\n"
" \n"
"struct Mirror \n"
" {\n"
" Arg a;\n"
" Arg b; \n"
" };\n"
" \n"
"struct First\n"
" {\n"
" Arg a;\n"
" };\n"
" \n"
"struct Second\n"
" {\n"
" Arg a;\n"
" }; \n"
" \n"
"struct Up \n"
" {\n"
" Arg a;\n"
" Arg b; \n"
" };\n"
" \n"
"struct Down \n"
" {\n"
" Arg a;\n"
" Arg b; \n"
" };\n"
" \n"
"struct Left \n"
" {\n"
" Arg a;\n"
" Arg b; \n"
" };\n"
" \n"
"struct Right \n"
" {\n"
" Arg a;\n"
" Arg b; \n"
" };\n"
" \n"
"struct StepOf\n"
" {\n"
" Arg[] args;\n"
" }; \n"
" \n"
"struct PathOf\n"
" {\n"
" Arg[] args;\n"
" };\n"
" \n"
"struct BPathOf\n"
" {\n"
" Arg[] args;\n"
" };\n"
" \n"
"struct LoopOf\n"
" {\n"
" Arg[] args;\n"
" };\n"
" \n"
"struct BLoopOf\n"
" {\n"
" Arg[] args;\n"
" };\n"
" \n"
"struct SolidOf \n"
" {\n"
" Arg a;\n"
" }; \n"
" \n"
"type Arg = {\n"
" Ratio,Length,Angle,Point,Pad,Formula,\n"
" Neg,Add,Sub,Mul,Div, \n"
" LengthOf,AngleOf,LineOf,Middle,Part,MidOrt,CircleOf,CircleOuter,\n"
" Proj,AngleC,Meet,MeetCircle,MeetCircles,Rotate,RotateOrt,Move,MoveLen,\n"
" Mirror,First,Second,Up,Down,Left,Right,\n"
" StepOf,PathOf,BPathOf,LoopOf,BLoopOf,SolidOf\n"
" } * ;\n"
"\n"
"struct Formula\n"
" {\n"
" Label label;\n"
" ulen index;\n"
" \n"
" Arg object;\n"
" };\n"
"\n"
" \n"
" \n"
"struct Contour\n"
" {\n"
" Pad[] pads;\n"
" Formula[] formulas;\n"
" };\n"
"\n"
"\n"
" \n"
| 12.409341 | 86 | 0.43458 | [
"object",
"solid"
] |
974c7d7f334f1b4174874cf1043293893ae4eb0a | 4,038 | h | C | src/hvpp/ia32/cpuid/cpuid_eax_01.h | FlyBly/123 | f801c0714c269eda2071442d219ae8349e97ec37 | [
"MIT"
] | 2 | 2021-01-09T18:11:52.000Z | 2021-04-20T13:46:59.000Z | src/hvpp/ia32/cpuid/cpuid_eax_01.h | FlyBly/123 | f801c0714c269eda2071442d219ae8349e97ec37 | [
"MIT"
] | null | null | null | src/hvpp/ia32/cpuid/cpuid_eax_01.h | FlyBly/123 | f801c0714c269eda2071442d219ae8349e97ec37 | [
"MIT"
] | 2 | 2021-01-09T18:11:55.000Z | 2021-07-06T09:24:44.000Z | #pragma once
#include <cstdint>
namespace ia32 {
struct cpuid_eax_01
{
union
{
struct
{
uint32_t cpu_info[4];
};
struct
{
uint32_t eax;
uint32_t ebx;
uint32_t ecx;
uint32_t edx;
};
struct
{
union
{
uint32_t flags;
struct
{
uint32_t stepping_id : 4;
uint32_t model : 4;
uint32_t family_id : 4;
uint32_t processor_type : 2;
uint32_t reserved1 : 2;
uint32_t extended_model_id : 4;
uint32_t extended_family_id : 8;
uint32_t reserved2 : 4;
};
} version_information;
union
{
uint32_t flags;
struct
{
uint32_t brand_index : 8;
uint32_t clflush_line_size : 8;
uint32_t max_addressable_ids : 8;
uint32_t initial_apic_id : 8;
};
} additional_information;
union
{
uint32_t flags;
struct
{
uint32_t streaming_simd_extensions_3 : 1;
uint32_t pclmulqdq_instruction : 1;
uint32_t ds_area_64bit_layout : 1;
uint32_t monitor_mwait_instruction : 1;
uint32_t cpl_qualified_debug_store : 1;
uint32_t virtual_machine_extensions : 1;
uint32_t safer_mode_extensions : 1;
uint32_t enhanced_intel_speedstep_technology : 1;
uint32_t thermal_monitor_2 : 1;
uint32_t supplemental_streaming_simd_extensions_3 : 1;
uint32_t l1_context_id : 1;
uint32_t silicon_debug : 1;
uint32_t fma_extensions : 1;
uint32_t cmpxchg16b_instruction : 1;
uint32_t xtpr_update_control : 1;
uint32_t perfmon_and_debug_capability : 1;
uint32_t reserved1 : 1;
uint32_t process_context_identifiers : 1;
uint32_t direct_cache_access : 1;
uint32_t sse41_support : 1;
uint32_t sse42_support : 1;
uint32_t x2apic_support : 1;
uint32_t movbe_instruction : 1;
uint32_t popcnt_instruction : 1;
uint32_t tsc_deadline : 1;
uint32_t aesni_instruction_extensions : 1;
uint32_t xsave_xrstor_instruction : 1;
uint32_t osx_save : 1;
uint32_t avx_support : 1;
uint32_t half_precision_conversion_instructions : 1;
uint32_t rdrand_instruction : 1;
uint32_t reserved2 : 1;
};
} feature_information_ecx;
union
{
uint32_t flags;
struct
{
uint32_t floating_point_unit_on_chip : 1;
uint32_t virtual_8086_mode_enhancements : 1;
uint32_t debugging_extensions : 1;
uint32_t page_size_extension : 1;
uint32_t timestamp_counter : 1;
uint32_t rdmsr_wrmsr_instructions : 1;
uint32_t physical_address_extension : 1;
uint32_t machine_check_exception : 1;
uint32_t cmpxchg8b : 1;
uint32_t apic_on_chip : 1;
uint32_t reserved1 : 1;
uint32_t sysenter_sysexit_instructions : 1;
uint32_t memory_type_range_registers : 1;
uint32_t page_global_bit : 1;
uint32_t machine_check_architecture : 1;
uint32_t conditional_move_instructions : 1;
uint32_t page_attribute_table : 1;
uint32_t page_size_extension_36bit : 1;
uint32_t processor_serial_number : 1;
uint32_t clflush : 1;
uint32_t reserved2 : 1;
uint32_t debug_store : 1;
uint32_t thermal_control_msrs_for_acpi : 1;
uint32_t mmx_support : 1;
uint32_t fxsave_fxrstor_instructions : 1;
uint32_t sse_support : 1;
uint32_t sse2_support : 1;
uint32_t self_snoop : 1;
uint32_t hyper_threading_technology : 1;
uint32_t thermal_monitor : 1;
uint32_t reserved3 : 1;
uint32_t pending_break_enable : 1;
};
} feature_information_edx;
};
};
};
}
| 28.43662 | 64 | 0.597078 | [
"model"
] |
9757d657e5a5930cf2e329aa8de8e8e174ebc1f2 | 2,312 | h | C | Geometry/MTDNumberingBuilder/interface/GeometricTimingDetExtra.h | gputtley/cmssw | c1ef8454804e4ebea8b65f59c4a952a6c94fde3b | [
"Apache-2.0"
] | 2 | 2020-05-09T16:03:43.000Z | 2020-05-09T16:03:50.000Z | Geometry/MTDNumberingBuilder/interface/GeometricTimingDetExtra.h | gputtley/cmssw | c1ef8454804e4ebea8b65f59c4a952a6c94fde3b | [
"Apache-2.0"
] | 26 | 2018-10-30T12:47:58.000Z | 2022-03-29T08:39:00.000Z | Geometry/MTDNumberingBuilder/interface/GeometricTimingDetExtra.h | gputtley/cmssw | c1ef8454804e4ebea8b65f59c4a952a6c94fde3b | [
"Apache-2.0"
] | 3 | 2017-06-07T15:22:28.000Z | 2019-02-28T20:48:30.000Z | #ifndef Geometry_MTDNumberingBuilder_GeometricTimingDetExtra_H
#define Geometry_MTDNumberingBuilder_GeometricTimingDetExtra_H
#include "Geometry/MTDNumberingBuilder/interface/GeometricTimingDet.h"
#include "DetectorDescription/Core/interface/DDExpandedView.h"
#include "DataFormats/DetId/interface/DetId.h"
#include <vector>
#include "FWCore/ParameterSet/interface/types.h"
#include <ext/pool_allocator.h>
class GeometricTimingDetExtra {
public:
#ifdef PoolAlloc
using GeoHistory = std::vector<DDExpandedNode, PoolAlloc<DDExpandedNode> >;
#else
using GeoHistory = std::vector<DDExpandedNode>;
#endif
explicit GeometricTimingDetExtra(GeometricTimingDet const* gd,
DetId id,
GeoHistory& gh,
double vol,
double dens,
double wgt,
double cpy,
const std::string& mat,
const std::string& name,
bool dd = false);
/**
*
*/
~GeometricTimingDetExtra();
/**
* get and set associated GeometricTimingDet
* DOES NO CHECKING!
*/
GeometricTimingDet const* geometricDet() const { return _mygd; }
/**
* set or add or clear components
*/
void setGeographicalId(DetId id) { _geographicalId = id; }
DetId geographicalId() const { return _geographicalId; }
GeoHistory const& parents() const { return _parents; }
//rr
int copyno() const { return _copy; }
double volume() const { return _volume; }
double density() const { return _density; }
double weight() const { return _weight; }
std::string const& material() const { return _material; }
/**
* what it says... used the DD in memory model to build the geometry... or not.
*/
bool wasBuiltFromDD() const { return _fromDD; }
std::string const& name() const { return _name; }
private:
/** Data members **/
GeometricTimingDet const* _mygd;
DetId _geographicalId;
GeoHistory _parents;
double _volume;
double _density;
double _weight;
int _copy;
std::string _material;
std::string _name;
bool _fromDD; // may not need this, keep an eye on it.
};
#undef PoolAlloc
#endif
| 28.54321 | 81 | 0.628893 | [
"geometry",
"vector",
"model"
] |
976248f855ddb1fed6962673174079fca0fd3055 | 10,335 | h | C | mindspore/lite/micro/example/mnist_stm32f746/mnist_stm32f746/include/lite_utils.h | kungfu-team/mindspore-bert | 71501cf52ae01db9d6a73fb64bcfe68a6509dc32 | [
"Apache-2.0"
] | 2 | 2021-07-08T13:10:42.000Z | 2021-11-08T02:48:57.000Z | mindspore/lite/micro/example/mnist_stm32f746/mnist_stm32f746/include/lite_utils.h | peixinhou/mindspore | fcb2ec2779b753e95c762cf292b23bd81d1f561b | [
"Apache-2.0"
] | null | null | null | mindspore/lite/micro/example/mnist_stm32f746/mnist_stm32f746/include/lite_utils.h | peixinhou/mindspore | fcb2ec2779b753e95c762cf292b23bd81d1f561b | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2020 Huawei Technologies Co., Ltd
*
* 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 MINDSPORE_LITE_INCLUDE_LITE_UTILS_H_
#define MINDSPORE_LITE_INCLUDE_LITE_UTILS_H_
#ifndef NOT_USE_STL
#include <vector>
#include <string>
#include <memory>
#include <functional>
#else
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <new>
#endif // NOT_USE_STL
#ifndef MS_API
#ifdef _WIN32
#define MS_API __declspec(dllexport)
#else
#define MS_API __attribute__((visibility("default")))
#endif
#endif
namespace mindspore {
namespace schema {
struct Tensor;
} // namespace schema
namespace tensor {
class MSTensor;
} // namespace tensor
namespace lite {
struct DeviceContext;
} // namespace lite
#ifdef NOT_USE_STL
class String {
public:
String();
String(size_t count, char ch);
String(const char *s, size_t count);
explicit String(const char *s);
String(const String &other);
String(const String &other, size_t pos, size_t count = npos);
~String();
String &operator=(const String &str);
String &operator=(const char *str);
char &at(size_t pos);
const char &at(size_t pos) const;
inline char &operator[](size_t pos);
inline const char &operator[](size_t pos) const;
char *data() noexcept;
const char *data() const noexcept;
const char *c_str() const noexcept;
// capacity
bool empty() const noexcept;
size_t size() const noexcept;
size_t length() const noexcept;
// operations
void clear() noexcept;
String &append(size_t count, const char ch);
String &append(const String &str);
String &append(const char *s);
String &operator+(const String &str);
String &operator+=(const String &str);
String &operator+=(const char *str);
String &operator+=(const char ch);
int compare(const String &str) const;
int compare(const char *str) const;
String substr(size_t pos = 0, size_t count = npos) const;
static const size_t npos = -1;
private:
size_t size_;
char *buffer_;
};
String operator+(const String &lhs, const char *rhs);
String operator+(const char *lhs, const String &rhs);
bool operator==(const String &lhs, const String &rhs);
bool operator==(const String &lhs, const char *rhs);
bool operator==(const char *lhs, const String &rhs);
String to_string(int32_t value);
String to_string(float value);
#define DEFAULT_CAPACITY 4
#define MS_C_EXCEPTION(...) exit(1)
#define MIN(x, y) ((x < y) ? (x) : (y))
template <typename T>
class Vector {
public:
Vector() {
size_ = 0;
capacity_ = DEFAULT_CAPACITY;
elem_size_ = sizeof(T);
data_ = nullptr;
}
explicit Vector(size_t size) {
size_ = size;
elem_size_ = sizeof(T);
capacity_ = (size == 0 ? DEFAULT_CAPACITY : size);
data_ = new (std::nothrow) T[capacity_];
if (data_ == nullptr) {
MS_C_EXCEPTION("malloc data failed");
}
}
Vector(size_t size, const T &value) {
size_ = size;
elem_size_ = sizeof(T);
capacity_ = (size == 0 ? DEFAULT_CAPACITY : size);
data_ = new (std::nothrow) T[capacity_];
if (data_ == nullptr) {
MS_C_EXCEPTION("malloc data failed");
}
for (int i = 0; i < static_cast<int>(size_); ++i) {
data_[i] = value;
}
}
Vector(const Vector<T> &vec) {
size_ = vec.size_;
elem_size_ = sizeof(T);
capacity_ = vec.capacity_;
data_ = new (std::nothrow) T[capacity_];
if (data_ == nullptr) {
MS_C_EXCEPTION("malloc data failed");
}
for (int i = 0; i < static_cast<int>(size_); ++i) {
data_[i] = vec.data_[i];
}
}
~Vector() {
if (data_ != nullptr) {
delete[] data_;
}
}
void clear() {
size_ = 0;
if (data_ != nullptr) {
delete[] data_;
data_ = nullptr;
}
}
void push_back(const T &elem) {
if (data_ == nullptr) {
data_ = new (std::nothrow) T[capacity_];
if (data_ == nullptr) {
MS_C_EXCEPTION("malloc data failed");
}
} else if (size_ == capacity_) {
resize(size_ + 1);
--size_;
}
data_[size_] = elem;
++size_;
}
void push_back(T &&elem) {
if (data_ == nullptr) {
data_ = new (std::nothrow) T[capacity_];
if (data_ == nullptr) {
MS_C_EXCEPTION("malloc data failed");
}
} else if (size_ == capacity_) {
resize(size_ + 1);
--size_;
}
data_[size_] = elem;
++size_;
}
void pop_back() {
if (size_ > 0) {
--size_;
} else {
MS_C_EXCEPTION("Index is out of range!");
}
}
void insert(const T &elem, size_t index) {
if (index <= size_) {
++size_;
if (size_ > capacity_) {
resize(size_);
}
if (index == size_ - 1) {
push_back(elem);
} else {
for (int i = static_cast<int>(size_) - 1; i > static_cast<int>(index); --i) {
data_[i + 1] = data_[i];
}
data_[index] = elem;
}
} else {
MS_C_EXCEPTION("Input index is out of range!");
}
}
T *begin() { return data_; }
const T *begin() const { return data_; }
T *end() { return data_ + size_; }
const T *end() const { return data_ + size_; }
T &front() {
if (size_ > 0) {
return data_[0];
}
MS_C_EXCEPTION("Index is out of range!");
}
const T &front() const {
if (size_ > 0) {
return data_[0];
}
MS_C_EXCEPTION("Index is out of range!");
}
T &back() {
if (size_ > 0) {
return data_[size_ - 1];
}
MS_C_EXCEPTION("Index is out of range!");
}
const T &back() const {
if (size_ > 0) {
return data_[size_ - 1];
}
MS_C_EXCEPTION("Index is out of range!");
}
T &at(size_t index) {
if (index < size_) {
return data_[index];
}
MS_C_EXCEPTION("Input index is out of range!");
}
const T &at(size_t index) const {
if (index < size_) {
return data_[index];
}
MS_C_EXCEPTION("Input index is out of range!");
}
T &operator[](size_t index) {
if (index < size_) {
return data_[index];
}
MS_C_EXCEPTION("Input index is out of range!");
}
const T &operator[](size_t index) const {
if (index < size_) {
return data_[index];
}
MS_C_EXCEPTION("Input index is out of range!");
}
T *data() { return data_; }
const T *data() const { return data_; }
size_t size() const { return size_; }
size_t capacity() const { return capacity_; }
bool empty() const { return size_ == 0; }
void erase(size_t index) {
if (index == size_ - 1) {
--size_;
} else if (index < size_) {
for (int i = index; i < static_cast<int>(size_); ++i) {
data_[i] = data_[i + 1];
}
--size_;
} else {
MS_C_EXCEPTION("Input index is out of range!");
}
}
void resize(size_t size) {
while (size > capacity_) {
capacity_ *= 2;
}
T *tmp = data_;
data_ = new (std::nothrow) T[capacity_];
if (data_ == nullptr) {
MS_C_EXCEPTION("malloc data failed");
}
for (int i = 0; i < MIN(static_cast<int>(size), static_cast<int>(size_)); ++i) {
data_[i] = tmp[i];
}
size_ = size;
delete[] tmp;
}
void reserve(size_t capacity) {
if (capacity > capacity_) {
capacity_ = capacity;
}
}
Vector<T> &operator=(const Vector<T> &vec) {
if (this == &vec) {
return *this;
}
size_ = vec.size_;
elem_size_ = sizeof(T);
capacity_ = vec.capacity_;
data_ = new (std::nothrow) T[capacity_];
if (data_ == nullptr) {
MS_C_EXCEPTION("malloc data failed");
}
for (int i = 0; i < static_cast<int>(size_); ++i) {
data_[i] = vec.data_[i];
}
return *this;
}
private:
size_t size_;
size_t elem_size_;
size_t capacity_;
T *data_;
};
using TensorPtrVector = Vector<mindspore::schema::Tensor *>;
using Uint32Vector = Vector<uint32_t>;
using AllocatorPtr = void *;
using DeviceContextVector = Vector<lite::DeviceContext>;
using KernelCallBack = void (*)(void *, void *);
#else
/// \brief Allocator defined a memory pool for malloc memory and free memory dynamically.
///
/// \note List public class and interface for reference.
class Allocator;
using AllocatorPtr = std::shared_ptr<Allocator>;
using TensorPtrVector = std::vector<mindspore::schema::Tensor *>;
using Uint32Vector = std::vector<uint32_t>;
template <typename T>
using Vector = std::vector<T>;
template <typename T>
inline std::string to_string(T t) {
return std::to_string(t);
}
namespace tensor {
using String = std::string;
} // namespace tensor
namespace session {
using String = std::string;
} // namespace session
/// \brief CallBackParam defined input arguments for callBack function.
struct CallBackParam {
session::String node_name; /**< node name argument */
session::String node_type; /**< node type argument */
};
struct GPUCallBackParam : CallBackParam {
double execute_time{-1.f};
};
/// \brief KernelCallBack defined the function pointer for callBack.
using KernelCallBack = std::function<bool(Vector<tensor::MSTensor *> inputs, Vector<tensor::MSTensor *> outputs,
const CallBackParam &opInfo)>;
namespace lite {
using String = std::string;
using DeviceContextVector = std::vector<DeviceContext>;
/// \brief Set data of MSTensor from string vector.
///
/// \param[in] input string vector.
/// \param[out] MSTensor.
///
/// \return STATUS as an error code of this interface, STATUS is defined in errorcode.h.
int MS_API StringsToMSTensor(const Vector<String> &inputs, tensor::MSTensor *tensor);
/// \brief Get string vector from MSTensor.
/// \param[in] MSTensor.
/// \return string vector.
Vector<String> MS_API MSTensorToStrings(const tensor::MSTensor *tensor);
} // namespace lite
#endif // NOT_USE_STL
} // namespace mindspore
#endif // MINDSPORE_LITE_INCLUDE_LITE_UTILS_H_
| 24.203747 | 112 | 0.627189 | [
"vector"
] |
977bf87df14197b2414a1132f3055d8f65acb1e3 | 1,338 | h | C | PacManState/include/field/object/FieldObject.h | BeardedPlatypus/PacMan | 319e9776582cf9118b38c72d31855fb4c598e986 | [
"MIT"
] | 5 | 2019-12-23T22:45:46.000Z | 2021-11-11T06:27:12.000Z | PacManState/include/field/object/FieldObject.h | BeardedPlatypus/PacMan | 319e9776582cf9118b38c72d31855fb4c598e986 | [
"MIT"
] | null | null | null | PacManState/include/field/object/FieldObject.h | BeardedPlatypus/PacMan | 319e9776582cf9118b38c72d31855fb4c598e986 | [
"MIT"
] | 1 | 2021-11-11T06:27:14.000Z | 2021-11-11T06:27:14.000Z | #pragma once
#define DllExport __declspec( dllexport )
#include "field/object/FieldObjectType.h"
namespace pacman {
namespace state {
namespace field {
/// <summary>
/// <see cref="FieldObject"/> defines a single field object as having a
/// <see cref="FieldObjectType"/> and a location consisting of an x and y
/// integer index.
/// </summary>
class DllExport FieldObject final {
public:
/// <summary>
/// Creates a new <see cref="FieldObject"/>.
/// </summary>
/// <param name="x"> The x location. </param>
/// <param name="y"> The y location. </param>
/// <param name="type"> The type. </param>
FieldObject(int x, int y, FieldObjectType type) :
_x(x), _y(y), _type(type) { }
/// <summary>
/// Gets the type of this <see cref="FieldObject"/>.
/// </summary>
/// <returns> The type. </returns>
inline FieldObjectType GetType() const { return this->_type; }
/// <summary>
/// Gets the x location of this <see cref="FieldObject"/>.
/// </summary>
/// <returns> The x location. </returns>
inline int GetX() const { return this->_x; }
/// <summary>
/// Gets the y location of this <see cref="FieldObject"/>.
/// </summary>
/// <returns> The y location. </returns>
inline int GetY() const { return this->_y; }
private:
int _x;
int _y;
FieldObjectType _type;
};
}
}
}
| 24.777778 | 73 | 0.626308 | [
"object"
] |
9780e201385d477c23ee8be9cfee66d61c1ed99b | 5,089 | h | C | dev/Gems/CryLegacy/Code/Source/CryAction/PlayerProfiles/PlayerProfileImplNoSave.h | CJoriginal/cjlumberyard | 2e3184a7d8e59ba05e5707371b8cb6fe40b0ca60 | [
"AML"
] | 5 | 2018-08-17T21:05:55.000Z | 2021-04-17T10:48:26.000Z | dev/Code/CryEngine/CryAction/PlayerProfiles/PlayerProfileImplNoSave.h | JulianoCristian/Lumberyard-3 | dc523dd780f3cd1874251181b7cf6848b8db9959 | [
"AML"
] | null | null | null | dev/Code/CryEngine/CryAction/PlayerProfiles/PlayerProfileImplNoSave.h | JulianoCristian/Lumberyard-3 | dc523dd780f3cd1874251181b7cf6848b8db9959 | [
"AML"
] | 5 | 2020-08-27T20:44:18.000Z | 2021-08-21T22:54:11.000Z | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
// Description : Player profile implementation for console demo releases.
// Doesn't save player profile data!
#ifndef CRYINCLUDE_CRYACTION_PLAYERPROFILES_PLAYERPROFILEIMPLNOSAVE_H
#define CRYINCLUDE_CRYACTION_PLAYERPROFILES_PLAYERPROFILEIMPLNOSAVE_H
#pragma once
#include "PlayerProfileImplConsole.h"
#include "PlayerProfile.h"
#include <IPlatformOS.h>
class CPlayerProfileImplNoSave
: public CPlayerProfileImplConsole
{
public:
// CPlayerProfileManager::IPlatformImpl
virtual bool LoginUser(SUserEntry* pEntry);
virtual bool SaveProfile(SUserEntry* pEntry, CPlayerProfile* pProfile, const char* name);
virtual bool LoadProfile(SUserEntry* pEntry, CPlayerProfile* pProfile, const char* name);
virtual bool DeleteProfile(SUserEntry* pEntry, const char* name);
virtual bool DeleteSaveGame(SUserEntry* pEntry, const char* name);
// ~CPlayerProfileManager::IPlatformImpl
// ICommonProfileImpl
// ~ICommonProfileImpl
protected:
virtual ~CPlayerProfileImplNoSave() { }
private:
CPlayerProfileManager* m_pMgr;
};
//------------------------------------------------------------------------
bool CPlayerProfileImplNoSave::SaveProfile(SUserEntry* pEntry, CPlayerProfile* pProfile, const char* name)
{
// This would cause a delete from disk - but we have READ ONLY media in this case
if (m_pMgr->HasEnabledOnlineAttributes() && m_pMgr->CanProcessOnlineAttributes() && !pProfile->IsDefault())
{
m_pMgr->SaveOnlineAttributes(pProfile);
}
return true;
}
//------------------------------------------------------------------------
bool CPlayerProfileImplNoSave::LoadProfile(SUserEntry* pEntry, CPlayerProfile* pProfile, const char* name)
{
// load the profile from a specific location. Only load the default profile since there is no saving!
using namespace PlayerProfileImpl;
if (0 == strcmp(name, "default"))
{
// XML for now
string path;
InternalMakeFSPath(pEntry, name, path);
XmlNodeRef rootNode = GetISystem()->CreateXmlNode(PROFILE_ROOT_TAG);
CSerializerXML serializer(rootNode, true);
XmlNodeRef attrNode = LoadXMLFile(path + "attributes.xml");
XmlNodeRef actionNode = LoadXMLFile(path + "actionmaps.xml");
// serializer.AddSection(attrNode);
// serializer.AddSection(actionNode);
serializer.SetSection(CPlayerProfileManager::ePPS_Attribute, attrNode);
serializer.SetSection(CPlayerProfileManager::ePPS_Actionmap, actionNode);
bool ok = pProfile->SerializeXML(&serializer);
return ok;
}
return true;
}
//------------------------------------------------------------------------
bool CPlayerProfileImplNoSave::LoginUser(SUserEntry* pEntry)
{
// lookup stored profiles of the user (pEntry->userId) and fill in the pEntry->profileDesc
// vector
pEntry->profileDesc.clear();
IPlatformOS* os = gEnv->pSystem->GetPlatformOS();
bool signedIn = os->UserIsSignedIn(pEntry->userIndex);
CryLogAlways("LoginUser::UserIsSignedIn %d\n", signedIn);
if (!signedIn)
{
#if !defined(_RELEASE)
if (!CCryActionCVars::Get().g_userNeverAutoSignsIn)
#endif
{
signedIn = os->UserDoSignIn(1, m_pMgr->GetExclusiveControllerDeviceIndex()); // disable this on a cvar to remove the signin box during autotests
CryLogAlways("LoginUser::UserDoSignIn %d\n", signedIn);
}
}
if (signedIn)
{
IPlatformOS::TUserName profileName;
if (os->UserGetName(pEntry->userIndex, profileName))
{
pEntry->profileDesc.push_back(SLocalProfileInfo(profileName.c_str()));
}
else
{
printf("OS FAILED to get signed in User name\n");
}
}
else
{
printf("OS No User signed in\n");
}
return signedIn;
}
//------------------------------------------------------------------------
bool CPlayerProfileImplNoSave::DeleteProfile(SUserEntry* pEntry, const char* name)
{
// This would cause a delete from disk - but we have READ ONLY media in this case
return true;
}
//------------------------------------------------------------------------
bool CPlayerProfileImplNoSave::DeleteSaveGame(SUserEntry* pEntry, const char* name)
{
// This would cause a delete from disk - but we have READ ONLY media in this case
return true;
}
#endif // CRYINCLUDE_CRYACTION_PLAYERPROFILES_PLAYERPROFILEIMPLNOSAVE_H
| 35.096552 | 159 | 0.658676 | [
"vector"
] |
9785443e7bf3859d4917496ca53a6978b8a0f864 | 735 | h | C | src/HardMaskManager.h | hawk2411/Lemmings | 0a1e3a3cd5e45c1bf1688e16267fcfaf367518c4 | [
"MIT"
] | null | null | null | src/HardMaskManager.h | hawk2411/Lemmings | 0a1e3a3cd5e45c1bf1688e16267fcfaf367518c4 | [
"MIT"
] | 3 | 2021-05-26T18:19:09.000Z | 2021-05-28T21:15:53.000Z | src/HardMaskManager.h | hawk2411/Lemmings | 0a1e3a3cd5e45c1bf1688e16267fcfaf367518c4 | [
"MIT"
] | null | null | null | #ifndef _HARDMASKMANAGER_INCLUDE
#define _HARDMASKMANAGER_INCLUDE
#include <vector>
#include "IMaskManager.h"
class HardMaskManager : public IMaskManager {
public:
explicit HardMaskManager(Level* level) : IMaskManager(level){}
void init() override;
void update(int time) override;
void eraseMask(int x, int y, int time) override;
void applyMask(int x, int y) override;
void eraseSpecialMask(int x, int y) override;
void applySpecialMask(int x, int y) override;
char getPixel(int x, int y) override;
private:
void regenerateMask(int x, int y);
std::vector<std::vector<int>> _timeWhenDisappear;
std::vector<std::vector<int>> _timeToAppear;
};
#endif // _HARDMASKMANAGER_INCLUDE
| 20.416667 | 66 | 0.718367 | [
"vector"
] |
978b36dfdcce4ad29bc5c956a2524663cab3f222 | 1,739 | h | C | src/Utility.h | gddavis21/CarND-Term2-Controls-MPC | 89016a391f0ddd9ca4bc91c2b1bedc407e16fbb9 | [
"MIT"
] | null | null | null | src/Utility.h | gddavis21/CarND-Term2-Controls-MPC | 89016a391f0ddd9ca4bc91c2b1bedc407e16fbb9 | [
"MIT"
] | null | null | null | src/Utility.h | gddavis21/CarND-Term2-Controls-MPC | 89016a391f0ddd9ca4bc91c2b1bedc407e16fbb9 | [
"MIT"
] | null | null | null | #ifndef UTILITY_H
#define UTILITY_H
#include <math.h>
#include "Eigen/Dense"
#include <cppad/cppad.hpp>
inline double clamp(double x, double lo, double hi)
{
return std::max(lo, std::min(x, hi));
}
// conversions between degrees and radians
double deg_to_rad(double deg);
double rad_to_deg(double rad);
// conversions between miles/hour and meters/sec
double mph_to_mps(double mph);
double mps_to_mph(double mps);
// Apply rigid-body transformation
class CoordFrame2D
{
public:
CoordFrame2D(double x_offs, double y_offs, double orient);
void GlobalToLocal(double &x, double &y) const;
void LocalToGlobal(double &x, double &y) const;
void GlobalToLocal(size_t count, double *x, double *y) const;
void LocalToGlobal(size_t count, double *x, double *y) const;
private:
double _xoffs, _yoffs, _cosA, _sinA;
};
class Polynomial
{
public:
// best-fit polynomial to sample data (simple polynomial regression)
Polynomial(
size_t degree,
size_t count,
const double *xvals,
const double *yvals);
// evaluate polynomial at x
double Evaluate(double x) const;
// evaluate polynomial 1st derivative at x
double Derivative(double x) const;
// CppAD::AD<double> Evaluate(const CppAD::AD<double> &x) const;
// CppAD::AD<double> Derivative(const CppAD::AD<double> &x) const;
Eigen::VectorXd GetCoefficients() const;
private:
Eigen::VectorXd _coeffs;
};
class LinearInterpolator1D
{
public:
LinearInterpolator1D(
size_t count,
const double *xvals,
const double *yvals);
double Interpolate(double x) const;
private:
std::vector<double> _xvals;
std::vector<double> _yvals;
};
#endif /* UTILITY_H */ | 22.584416 | 72 | 0.692352 | [
"vector"
] |
9794e0235c8a575e264e0066aeff8d7b3bf3fb45 | 1,449 | h | C | ProjectModellib/JavaModelLib/internal/core/IMember.h | kuafuwang/JCDT | 2b009ea887b4816303fed9e6e1dc104a90c67d16 | [
"MIT"
] | 1 | 2021-04-17T01:55:27.000Z | 2021-04-17T01:55:27.000Z | ProjectModellib/JavaModelLib/internal/core/IMember.h | kuafuwang/JCDT | 2b009ea887b4816303fed9e6e1dc104a90c67d16 | [
"MIT"
] | null | null | null | ProjectModellib/JavaModelLib/internal/core/IMember.h | kuafuwang/JCDT | 2b009ea887b4816303fed9e6e1dc104a90c67d16 | [
"MIT"
] | 1 | 2022-02-18T12:02:00.000Z | 2022-02-18T12:02:00.000Z |
#ifndef IMember_java_model_INCLUDED_INCLUDED
#define IMember_java_model_INCLUDED_INCLUDED
#include <vector>
#include <string>
#include "ISourceReference.h"
#include <JavaModelLib/internal/info/MemberElementInfo.h>
#include <boost/algorithm/string.hpp>
#include <JavaModelLib/internal/core/IJavaCardDocType.h>
using std::wstring;
namespace Jikes { // Open namespace Jikes block
class AccessFlags;
namespace JavaModel{
class ISourceRange;
class IType;
class IMember :public ISourceReference
{
public:
IMember();
IMember(IMember& o);
virtual ~IMember();
virtual bool isBinary();
virtual IType* getDeclaringType() = 0;
virtual void setAccessFlags(unsigned flag) = 0;
virtual const std::vector< std::wstring>* const getModfiers() = 0;
virtual wstring getModifersString(wchar_t seperator = ' ') = 0;
virtual AccessFlags getAccessFlags() = 0;
virtual wstring getOutLineName() = 0;
virtual wstring getOutLineIdentity() = 0;
virtual MemberElementInfo* getElementInfo() = 0;
inline wstring getFullyQualifiedName(wchar_t enclosingTypeSeparator){
auto info = getElementInfo();
auto type_part = boost::join(info->qualifiedTypeNames, wstring(1,enclosingTypeSeparator));
if(!type_part.empty()){
wstring temp(L".");
temp += info->name;
return type_part + temp;
}
return type_part;
}
};
}// Close namespace JavaModel block
} // Close namespace Jikes block
#endif // _INCLUDED
| 23.754098 | 93 | 0.73499 | [
"vector"
] |
97960a52ece32abbb4e2d14713ed67983c6f6188 | 4,310 | h | C | lark_xr/include/lark_xr/xr_video_frame.h | pingxingyun/larkxr_native_android_app | 464fc5eecb011325b553adf82ef83c1659b05c20 | [
"Apache-2.0"
] | 4 | 2021-08-25T05:51:58.000Z | 2022-02-09T06:34:12.000Z | lark_xr/include/lark_xr/xr_video_frame.h | pingxingyun/larkxr_native_android_app | 464fc5eecb011325b553adf82ef83c1659b05c20 | [
"Apache-2.0"
] | 1 | 2021-09-03T01:18:45.000Z | 2021-09-03T01:18:45.000Z | lark_xr/include/lark_xr/xr_video_frame.h | pingxingyun/larkxr_native_android_app | 464fc5eecb011325b553adf82ef83c1659b05c20 | [
"Apache-2.0"
] | null | null | null | //
// Created by fcx@pingxingyun.com
// 2020-04-07 17:05
//
#pragma once
#ifndef XR_IMAGE_BUFFER_INCLUDE
#define XR_IMAGE_BUFFER_INCLUDE
#include <cstdint>
#include "lark_xr/types.h"
#include "lark_xr/lark_xr.h"
namespace lark {
const int VIDEO_FRAME_NUM_DATA_POINTERS = 3;
const int VIDEO_FRAME_Y_PLANE_INDEX = 0;
const int VIDEO_FRAME_U_PLANE_INDEX = 1;
const int VIDEO_FRAME_V_PLANE_INDEX = 2;
class XRVideoFrameImp;
// RGB24 pix fomat
/**
* 视频帧可包括
*/
class LARK_XR_API XRVideoFrame {
public:
enum class FrameType
{
kNone = larkxrHwRenderTextureType_None,
kYUV420P, ///< planar YUV 4:2:0, 12bpp, (1 Cr & Cb sample per 2x2 Y samples)
kRGB24, ///< packed RGB 8:8:8, 24bpp, RGBRGB...
kNV12, ///< planar YUV 4:2:0, 12bpp, 1 plane for Y and 1 plane for the UV components, which are interleaved (first byte U and the following byte V)
kNV21, ///< as above, but U and V bytes are swapped
// hw
kNative_Multiview = larkxrHwRenderTextureType_Android_Multiview, /// android opengl multiview 左右眼在一起
kNative_Stereo = larkxrHwRenderTextureType_Android_Stereo, /// android opengl 双面分开,左眼一个纹理右眼一个纹理
kNative_D3D11_Multiview = larkxrHwRenderTextureType_D3D11_Multiview, /// windows d3d11 native texture 左右眼在一起
kNative_D3D11_Stereo = larkxrHwRenderTextureType_D3D11_Stereo, /// windows d3d11 native texture 左右眼在一起
kNative_D3D11_NV12 = larkxrHwRenderTextureType_D3D11_NV12, /// windows d3d11 nv12 native texture 左右眼在一起
kNative_D3D11_Y_UV = larkxrHwRenderTextureType_D3D11_Y_UV_SRV, /// windows d3d11 nv12 native texture 左右眼在一起
};
// copy
XRVideoFrame(const XRVideoFrame& videoFrame);
// move
XRVideoFrame(XRVideoFrame&& videoFrame) noexcept;
// create empty video frame
XRVideoFrame(uint64_t frame_index);
// create video frame with rgb24 buffer
XRVideoFrame(const uint8_t* data, uint64_t frame_index, int width, int height);
// create video frame with rgb24 buffer and copy
XRVideoFrame(const uint8_t* data, uint64_t frame_index, int width, int height, bool copy);
// create video frame with yuv buffer
XRVideoFrame(uint8_t* data[], int stride[], uint64_t frame_index, int width, int height);
// create video frame with yuv buffer and copy
XRVideoFrame(uint8_t* data[], int stride[], uint64_t frame_index, int width, int height, bool copy);
// create video frame with yuv buffer and copy
XRVideoFrame(uint8_t* data[], int stride[], uint64_t frame_index, int width, int height, bool copy, FrameType frameType);
// android opengl native multiview texture.
XRVideoFrame(int texture, uint64_t frameIndex);
// android opengl native stereo view texture;
XRVideoFrame(int textureLeft, int textureRight, uint64_t frameIndex);
// d3d11 nv12 native texture
XRVideoFrame(void* d3d11_texture, int width, int height, uint64_t frameIndex);
// larkxrHwRenderTextureType_D3D11_Y_UV_SRV
XRVideoFrame(void* d3d11_texture_left, void* d3d11_texture_right, int width, int height, uint64_t frameIndex);
~XRVideoFrame();
XRVideoFrame& operator=(const XRVideoFrame& other);
// warning render under opengl context.
void Render() const;
void Resize(int width, int height);
int GetBufferByteSize() const;
int width() const;
int height() const;
int ChromaWidth() const;
int ChromaHeight() const;
const uint8_t* DataRGB() const;
uint64_t frame_index() const;
void set_frame_index(uint64_t frame_index);
bool copy() const;
FrameType frame_type() const;
const uint8_t* MutableDataY() const;
const uint8_t* MutableDataU() const;
const uint8_t* MutableDataV() const;
int StrideY() const;
int StrideU() const;
int StrideV() const;
// native texture
int texture() const;
int texture_left() const;
int texture_right() const;
int texture_type() const;
bool IsNative() const;
const void* d3d11_texture() const;
const void* d3d11_texture_left() const;
const void* d3d11_texture_right() const;
larkxrHwRenderTexture GetHwVideoFrame() const;
private:
XRVideoFrameImp* xr_video_frame_imp_;
};
}
#endif // XR_IMAGE_BUFFER_INCLUDE | 41.047619 | 168 | 0.709049 | [
"render"
] |
9796a5abda32385f9d16cab9f4cd6ace3547044a | 1,452 | h | C | Geometry/HcalCommonData/interface/HcalGeomParameters.h | NTrevisani/cmssw | a212a27526f34eb9507cf8b875c93896e6544781 | [
"Apache-2.0"
] | 1 | 2021-01-04T10:25:39.000Z | 2021-01-04T10:25:39.000Z | Geometry/HcalCommonData/interface/HcalGeomParameters.h | NTrevisani/cmssw | a212a27526f34eb9507cf8b875c93896e6544781 | [
"Apache-2.0"
] | 7 | 2016-07-17T02:34:54.000Z | 2019-08-13T07:58:37.000Z | Geometry/HcalCommonData/interface/HcalGeomParameters.h | NTrevisani/cmssw | a212a27526f34eb9507cf8b875c93896e6544781 | [
"Apache-2.0"
] | 2 | 2019-09-27T08:33:22.000Z | 2019-11-14T10:52:30.000Z | #ifndef HcalCommonData_HcalGeomParameters_h
#define HcalCommonData_HcalGeomParameters_h
/** \class HcalGeomParameters
*
* this class extracts some geometry constants from CompactView
* to be used by Reco Geometry/Topology
*
* $Date: 2015/06/25 00:06:50 $
* \author Sunanda Banerjee, Fermilab <sunanda.banerjee@cern.ch>
*
*/
#include <string>
#include <vector>
#include <iostream>
#include "DetectorDescription/Core/interface/DDsvalues.h"
#include "Geometry/HcalCommonData/interface/HcalCellType.h"
#include "DataFormats/HcalDetId/interface/HcalSubdetector.h"
class DDCompactView;
class DDFilteredView;
class HcalParameters;
class HcalGeomParameters {
public:
HcalGeomParameters();
~HcalGeomParameters();
double getConstDzHF() const { return dzVcal; }
void getConstRHO(std::vector<double>&) const;
std::vector<int> getModHalfHBHE(const int type) const;
void loadGeometry(const DDFilteredView& _fv, HcalParameters& php);
private:
unsigned find(int element, std::vector<int>& array) const;
double getEta(double r, double z) const;
int nzHB, nmodHB; // Number of halves and modules in HB
int nzHE, nmodHE; // Number of halves and modules in HE
double etaHO[4], rminHO; // eta in HO ring boundaries
double zVcal; // Z-position of the front of HF
double dzVcal; // Half length of the HF
double dlShort; // Diference of length between long and short
};
#endif
| 29.632653 | 73 | 0.72865 | [
"geometry",
"vector"
] |
979ace0d38e9297fa1fae526d533cc508a8d8f89 | 2,375 | h | C | include/dfesnippets/sparse/common.h | custom-computing-ic/dfe-snippets | 8721e6272c25f77360e2de423d8ff5a9299ee5b2 | [
"MIT"
] | 17 | 2015-02-02T13:23:49.000Z | 2021-02-09T11:04:40.000Z | include/dfesnippets/sparse/common.h | custom-computing-ic/dfe-snippets | 8721e6272c25f77360e2de423d8ff5a9299ee5b2 | [
"MIT"
] | 14 | 2015-07-02T10:13:05.000Z | 2017-05-30T15:59:43.000Z | include/dfesnippets/sparse/common.h | custom-computing-ic/dfe-snippets | 8721e6272c25f77360e2de423d8ff5a9299ee5b2 | [
"MIT"
] | 8 | 2015-04-08T13:27:50.000Z | 2016-12-16T14:38:52.000Z | #ifndef COMMON_BENCHMARK_H
#define COMMON_BENCHMARK_H
#include "mmio.h"
#ifdef __cplusplus
extern "C" {
#endif
void print_array(const char* message, double *values, int size);
void print_array_int(const char* message, int *values, int size);
void print_matrix(const char* message, double *values, int size);
/** Reads the dimensions of the matrix (n - number of rows, m - number
of columns, nnzs - number of non-zeros) from the given Matrix
Market file. If the given file contains an array rather than a
COO matrix, nnzs will be set to n;
*/
void read_mm_matrix_size(FILE *f, int *n, int *m, int *nnzs, MM_typecode* mcode);
/** Reads a matrix market file for a symmetric real valued sparse
matrix and returns the matrix in 0-indexed CSR form. */
void read_mm_sym_matrix(FILE* f, MM_typecode mcode,
int n, int nnzs,
double *values, int* col_ind, int *row_ptr
);
/** Reads a matrix market file for a symmetric real valued sparse
matrix and returns the matrix in 1-indexed CSR form, with ALL
VALUES INCLUDED (i.e. when setting A(i, j), we also set A(j, i)).
*/
void read_mm_unsym_matrix(FILE* f, MM_typecode mcode,
int n, int *nnzs,
double *values, int* col_ind, int *row_ptr);
/** Returns the zero indexed array of values. */
void read_mm_array(FILE *f, MM_typecode code, int nnzs, double *values);
double* read_rhs(FILE* g, int* n, int *nnzs);
void read_system_matrix_sym_csr(FILE* f, int* n, int *nnzs, int** col_ind, int** row_ptr, double** values);
void read_system_matrix_unsym_csr(FILE* f,
int* n, int *nnzs,
int** col_ind, int** row_ptr, double** values);
/** Reads a generic sparse matrix in Matrix Market format and converts it to 1 indexed CSR. */
void read_ge_mm_csr(char* fname,
int* n, int *nnzs,
int** col_ind, int** row_ptr, double** values);
void write_vector_to_file(const char* filename, double* vector, int size);
/**
Implements element-wise multiplication of two vectors (treats first vector as
diagonal matrix and multiplies it to second vector): z = x (*) y.
*/
void elementwise_xty(const int n, const double *x, const double *y, double *z);
#ifdef __cplusplus
}
#endif
#endif
| 37.698413 | 107 | 0.654737 | [
"vector"
] |
979ed53e3ee7531d9f287b7aa4756e9fe0a8ae72 | 36,110 | c | C | dlls/mshtml/htmlwindow.c | devyn/wine | 76bb12558beaece005419feb98f024a1eb1f74e8 | [
"MIT"
] | 1 | 2016-05-08T19:53:43.000Z | 2016-05-08T19:53:43.000Z | dlls/mshtml/htmlwindow.c | devyn/wine | 76bb12558beaece005419feb98f024a1eb1f74e8 | [
"MIT"
] | null | null | null | dlls/mshtml/htmlwindow.c | devyn/wine | 76bb12558beaece005419feb98f024a1eb1f74e8 | [
"MIT"
] | null | null | null | /*
* Copyright 2006 Jacek Caban for CodeWeavers
*
* 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 St, Fifth Floor, Boston, MA 02110-1301, USA
*/
#include <stdarg.h>
#define COBJMACROS
#include "windef.h"
#include "winbase.h"
#include "winuser.h"
#include "ole2.h"
#include "wine/debug.h"
#include "wine/unicode.h"
#include "mshtml_private.h"
#include "resource.h"
WINE_DEFAULT_DEBUG_CHANNEL(mshtml);
static struct list window_list = LIST_INIT(window_list);
#define HTMLWINDOW2_THIS(iface) DEFINE_THIS(HTMLWindow, HTMLWindow2, iface)
static HRESULT WINAPI HTMLWindow2_QueryInterface(IHTMLWindow2 *iface, REFIID riid, void **ppv)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
*ppv = NULL;
if(IsEqualGUID(&IID_IUnknown, riid)) {
TRACE("(%p)->(IID_IUnknown %p)\n", This, ppv);
*ppv = HTMLWINDOW2(This);
}else if(IsEqualGUID(&IID_IDispatch, riid)) {
TRACE("(%p)->(IID_IDispatch %p)\n", This, ppv);
*ppv = HTMLWINDOW2(This);
}else if(IsEqualGUID(&IID_IDispatchEx, riid)) {
TRACE("(%p)->(IID_IDispatchEx %p)\n", This, ppv);
*ppv = DISPATCHEX(This);
}else if(IsEqualGUID(&IID_IHTMLFramesCollection2, riid)) {
TRACE("(%p)->(IID_IHTMLFramesCollection2 %p)\n", This, ppv);
*ppv = HTMLWINDOW2(This);
}else if(IsEqualGUID(&IID_IHTMLWindow2, riid)) {
TRACE("(%p)->(IID_IHTMLWindow2 %p)\n", This, ppv);
*ppv = HTMLWINDOW2(This);
}else if(IsEqualGUID(&IID_IHTMLWindow3, riid)) {
TRACE("(%p)->(IID_IHTMLWindow2 %p)\n", This, ppv);
*ppv = HTMLWINDOW3(This);
}else if(dispex_query_interface(&This->dispex, riid, ppv)) {
return *ppv ? S_OK : E_NOINTERFACE;
}
if(*ppv) {
IUnknown_AddRef((IUnknown*)*ppv);
return S_OK;
}
WARN("(%p)->(%s %p)\n", This, debugstr_guid(riid), ppv);
return E_NOINTERFACE;
}
static ULONG WINAPI HTMLWindow2_AddRef(IHTMLWindow2 *iface)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
LONG ref = InterlockedIncrement(&This->ref);
TRACE("(%p) ref=%d\n", This, ref);
return ref;
}
static ULONG WINAPI HTMLWindow2_Release(IHTMLWindow2 *iface)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
LONG ref = InterlockedDecrement(&This->ref);
TRACE("(%p) ref=%d\n", This, ref);
if(!ref) {
list_remove(&This->entry);
heap_free(This);
}
return ref;
}
static HRESULT WINAPI HTMLWindow2_GetTypeInfoCount(IHTMLWindow2 *iface, UINT *pctinfo)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
return IDispatchEx_GetTypeInfoCount(DISPATCHEX(This), pctinfo);
}
static HRESULT WINAPI HTMLWindow2_GetTypeInfo(IHTMLWindow2 *iface, UINT iTInfo,
LCID lcid, ITypeInfo **ppTInfo)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
return IDispatchEx_GetTypeInfo(DISPATCHEX(This), iTInfo, lcid, ppTInfo);
}
static HRESULT WINAPI HTMLWindow2_GetIDsOfNames(IHTMLWindow2 *iface, REFIID riid,
LPOLESTR *rgszNames, UINT cNames,
LCID lcid, DISPID *rgDispId)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
return IDispatchEx_GetIDsOfNames(DISPATCHEX(This), riid, rgszNames, cNames, lcid, rgDispId);
}
static HRESULT WINAPI HTMLWindow2_Invoke(IHTMLWindow2 *iface, DISPID dispIdMember,
REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS *pDispParams,
VARIANT *pVarResult, EXCEPINFO *pExcepInfo, UINT *puArgErr)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
return IDispatchEx_Invoke(DISPATCHEX(This), dispIdMember, riid, lcid, wFlags, pDispParams,
pVarResult, pExcepInfo, puArgErr);
}
static HRESULT WINAPI HTMLWindow2_item(IHTMLWindow2 *iface, VARIANT *pvarIndex, VARIANT *pvarResult)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
FIXME("(%p)->(%p %p)\n", This, pvarIndex, pvarResult);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLWindow2_get_length(IHTMLWindow2 *iface, long *p)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLWindow2_get_frames(IHTMLWindow2 *iface, IHTMLFramesCollection2 **p)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLWindow2_put_defaultStatus(IHTMLWindow2 *iface, BSTR v)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLWindow2_get_defaultStatus(IHTMLWindow2 *iface, BSTR *p)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLWindow2_put_status(IHTMLWindow2 *iface, BSTR v)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLWindow2_get_status(IHTMLWindow2 *iface, BSTR *p)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLWindow2_setTimeout(IHTMLWindow2 *iface, BSTR expression,
long msec, VARIANT *language, long *timerID)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
VARIANT expr_var;
TRACE("(%p)->(%s %ld %p %p)\n", This, debugstr_w(expression), msec, language, timerID);
V_VT(&expr_var) = VT_BSTR;
V_BSTR(&expr_var) = expression;
return IHTMLWindow3_setTimeout(HTMLWINDOW3(This), &expr_var, msec, language, timerID);
}
static HRESULT WINAPI HTMLWindow2_clearTimeout(IHTMLWindow2 *iface, long timerID)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
TRACE("(%p)->(%ld)\n", This, timerID);
return clear_task_timer(This->doc, FALSE, timerID);
}
static HRESULT WINAPI HTMLWindow2_alert(IHTMLWindow2 *iface, BSTR message)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
WCHAR wszTitle[100];
TRACE("(%p)->(%s)\n", This, debugstr_w(message));
if(!LoadStringW(get_shdoclc(), IDS_MESSAGE_BOX_TITLE, wszTitle,
sizeof(wszTitle)/sizeof(WCHAR))) {
WARN("Could not load message box title: %d\n", GetLastError());
return S_OK;
}
MessageBoxW(This->doc->hwnd, message, wszTitle, MB_ICONWARNING);
return S_OK;
}
static HRESULT WINAPI HTMLWindow2_confirm(IHTMLWindow2 *iface, BSTR message,
VARIANT_BOOL *confirmed)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
FIXME("(%p)->(%s %p)\n", This, debugstr_w(message), confirmed);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLWindow2_prompt(IHTMLWindow2 *iface, BSTR message,
BSTR dststr, VARIANT *textdata)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
FIXME("(%p)->(%s %s %p)\n", This, debugstr_w(message), debugstr_w(dststr), textdata);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLWindow2_get_Image(IHTMLWindow2 *iface, IHTMLImageElementFactory **p)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLWindow2_get_location(IHTMLWindow2 *iface, IHTMLLocation **p)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
TRACE("(%p)->(%p)\n", This, p);
if(!This->doc) {
FIXME("This->doc is NULL\n");
return E_FAIL;
}
return IHTMLDocument2_get_location(HTMLDOC(This->doc), p);
}
static HRESULT WINAPI HTMLWindow2_get_history(IHTMLWindow2 *iface, IOmHistory **p)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLWindow2_close(IHTMLWindow2 *iface)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
FIXME("(%p)->()\n", This);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLWindow2_put_opener(IHTMLWindow2 *iface, VARIANT v)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
FIXME("(%p)->(v(%d))\n", This, V_VT(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLWindow2_get_opener(IHTMLWindow2 *iface, VARIANT *p)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLWindow2_get_navigator(IHTMLWindow2 *iface, IOmNavigator **p)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
TRACE("(%p)->(%p)\n", This, p);
*p = OmNavigator_Create();
return S_OK;
}
static HRESULT WINAPI HTMLWindow2_put_name(IHTMLWindow2 *iface, BSTR v)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLWindow2_get_name(IHTMLWindow2 *iface, BSTR *p)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLWindow2_get_parent(IHTMLWindow2 *iface, IHTMLWindow2 **p)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLWindow2_open(IHTMLWindow2 *iface, BSTR url, BSTR name,
BSTR features, VARIANT_BOOL replace, IHTMLWindow2 **pomWindowResult)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
FIXME("(%p)->(%s %s %s %x %p)\n", This, debugstr_w(url), debugstr_w(name),
debugstr_w(features), replace, pomWindowResult);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLWindow2_get_self(IHTMLWindow2 *iface, IHTMLWindow2 **p)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
TRACE("(%p)->(%p)\n", This, p);
/* FIXME: We should return kind of proxy window here. */
IHTMLWindow2_AddRef(HTMLWINDOW2(This));
*p = HTMLWINDOW2(This);
return S_OK;
}
static HRESULT WINAPI HTMLWindow2_get_top(IHTMLWindow2 *iface, IHTMLWindow2 **p)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLWindow2_get_window(IHTMLWindow2 *iface, IHTMLWindow2 **p)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
TRACE("(%p)->(%p)\n", This, p);
/* FIXME: We should return kind of proxy window here. */
IHTMLWindow2_AddRef(HTMLWINDOW2(This));
*p = HTMLWINDOW2(This);
return S_OK;
}
static HRESULT WINAPI HTMLWindow2_navigate(IHTMLWindow2 *iface, BSTR url)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(url));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLWindow2_put_onfocus(IHTMLWindow2 *iface, VARIANT v)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
FIXME("(%p)->(v(%d))\n", This, V_VT(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLWindow2_get_onfocus(IHTMLWindow2 *iface, VARIANT *p)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLWindow2_put_onblur(IHTMLWindow2 *iface, VARIANT v)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
FIXME("(%p)->(v(%d))\n", This, V_VT(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLWindow2_get_onblur(IHTMLWindow2 *iface, VARIANT *p)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLWindow2_put_onload(IHTMLWindow2 *iface, VARIANT v)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
FIXME("(%p)->(v(%d))\n", This, V_VT(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLWindow2_get_onload(IHTMLWindow2 *iface, VARIANT *p)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLWindow2_put_onbeforeunload(IHTMLWindow2 *iface, VARIANT v)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
FIXME("(%p)->(v(%d))\n", This, V_VT(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLWindow2_get_onbeforeunload(IHTMLWindow2 *iface, VARIANT *p)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLWindow2_put_onunload(IHTMLWindow2 *iface, VARIANT v)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
FIXME("(%p)->(v(%d))\n", This, V_VT(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLWindow2_get_onunload(IHTMLWindow2 *iface, VARIANT *p)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLWindow2_put_onhelp(IHTMLWindow2 *iface, VARIANT v)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
FIXME("(%p)->(v(%d))\n", This, V_VT(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLWindow2_get_onhelp(IHTMLWindow2 *iface, VARIANT *p)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLWindow2_put_onerror(IHTMLWindow2 *iface, VARIANT v)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
FIXME("(%p)->(v(%d))\n", This, V_VT(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLWindow2_get_onerror(IHTMLWindow2 *iface, VARIANT *p)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLWindow2_put_onresize(IHTMLWindow2 *iface, VARIANT v)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
FIXME("(%p)->(v(%d))\n", This, V_VT(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLWindow2_get_onresize(IHTMLWindow2 *iface, VARIANT *p)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLWindow2_put_onscroll(IHTMLWindow2 *iface, VARIANT v)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
FIXME("(%p)->(v(%d))\n", This, V_VT(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLWindow2_get_onscroll(IHTMLWindow2 *iface, VARIANT *p)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLWindow2_get_document(IHTMLWindow2 *iface, IHTMLDocument2 **p)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
TRACE("(%p)->(%p)\n", This, p);
if(This->doc) {
/* FIXME: We should return a wrapper object here */
*p = HTMLDOC(This->doc);
IHTMLDocument2_AddRef(*p);
}else {
*p = NULL;
}
return S_OK;
}
static HRESULT WINAPI HTMLWindow2_get_event(IHTMLWindow2 *iface, IHTMLEventObj **p)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
TRACE("(%p)->(%p)\n", This, p);
if(This->event)
IHTMLEventObj_AddRef(This->event);
*p = This->event;
return S_OK;
}
static HRESULT WINAPI HTMLWindow2_get__newEnum(IHTMLWindow2 *iface, IUnknown **p)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLWindow2_showModalDialog(IHTMLWindow2 *iface, BSTR dialog,
VARIANT *varArgIn, VARIANT *varOptions, VARIANT *varArgOut)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
FIXME("(%p)->(%s %p %p %p)\n", This, debugstr_w(dialog), varArgIn, varOptions, varArgOut);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLWindow2_showHelp(IHTMLWindow2 *iface, BSTR helpURL, VARIANT helpArg,
BSTR features)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
FIXME("(%p)->(%s v(%d) %s)\n", This, debugstr_w(helpURL), V_VT(&helpArg), debugstr_w(features));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLWindow2_get_screen(IHTMLWindow2 *iface, IHTMLScreen **p)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLWindow2_get_Option(IHTMLWindow2 *iface, IHTMLOptionElementFactory **p)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
TRACE("(%p)->(%p)\n", This, p);
if(!This->doc->option_factory)
This->doc->option_factory = HTMLOptionElementFactory_Create(This->doc);
*p = HTMLOPTFACTORY(This->doc->option_factory);
IHTMLOptionElementFactory_AddRef(*p);
return S_OK;
}
static HRESULT WINAPI HTMLWindow2_focus(IHTMLWindow2 *iface)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
FIXME("(%p)->()\n", This);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLWindow2_get_closed(IHTMLWindow2 *iface, VARIANT_BOOL *p)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLWindow2_blur(IHTMLWindow2 *iface)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
FIXME("(%p)->()\n", This);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLWindow2_scroll(IHTMLWindow2 *iface, long x, long y)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
FIXME("(%p)->(%ld %ld)\n", This, x, y);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLWindow2_get_clientInformation(IHTMLWindow2 *iface, IOmNavigator **p)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLWindow2_setInterval(IHTMLWindow2 *iface, BSTR expression,
long msec, VARIANT *language, long *timerID)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
VARIANT expr;
TRACE("(%p)->(%s %ld %p %p)\n", This, debugstr_w(expression), msec, language, timerID);
V_VT(&expr) = VT_BSTR;
V_BSTR(&expr) = expression;
return IHTMLWindow3_setInterval(HTMLWINDOW3(This), &expr, msec, language, timerID);
}
static HRESULT WINAPI HTMLWindow2_clearInterval(IHTMLWindow2 *iface, long timerID)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
TRACE("(%p)->(%ld)\n", This, timerID);
return clear_task_timer(This->doc, TRUE, timerID);
}
static HRESULT WINAPI HTMLWindow2_put_offscreenBuffering(IHTMLWindow2 *iface, VARIANT v)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
FIXME("(%p)->(v(%d))\n", This, V_VT(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLWindow2_get_offscreenBuffering(IHTMLWindow2 *iface, VARIANT *p)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLWindow2_execScript(IHTMLWindow2 *iface, BSTR scode, BSTR language,
VARIANT *pvarRet)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
FIXME("(%p)->(%s %s %p)\n", This, debugstr_w(scode), debugstr_w(language), pvarRet);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLWindow2_toString(IHTMLWindow2 *iface, BSTR *String)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
FIXME("(%p)->(%p)\n", This, String);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLWindow2_scrollBy(IHTMLWindow2 *iface, long x, long y)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
nsresult nsres;
TRACE("(%p)->(%ld %ld)\n", This, x, y);
nsres = nsIDOMWindow_ScrollBy(This->nswindow, x, y);
if(NS_FAILED(nsres))
ERR("ScrollBy failed: %08x\n", nsres);
return S_OK;
}
static HRESULT WINAPI HTMLWindow2_scrollTo(IHTMLWindow2 *iface, long x, long y)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
nsresult nsres;
TRACE("(%p)->(%ld %ld)\n", This, x, y);
nsres = nsIDOMWindow_ScrollTo(This->nswindow, x, y);
if(NS_FAILED(nsres))
ERR("ScrollTo failed: %08x\n", nsres);
return S_OK;
}
static HRESULT WINAPI HTMLWindow2_moveTo(IHTMLWindow2 *iface, long x, long y)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
FIXME("(%p)->(%ld %ld)\n", This, x, y);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLWindow2_moveBy(IHTMLWindow2 *iface, long x, long y)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
FIXME("(%p)->(%ld %ld)\n", This, x, y);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLWindow2_resizeTo(IHTMLWindow2 *iface, long x, long y)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
FIXME("(%p)->(%ld %ld)\n", This, x, y);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLWindow2_resizeBy(IHTMLWindow2 *iface, long x, long y)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
FIXME("(%p)->(%ld %ld)\n", This, x, y);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLWindow2_get_external(IHTMLWindow2 *iface, IDispatch **p)
{
HTMLWindow *This = HTMLWINDOW2_THIS(iface);
TRACE("(%p)->(%p)\n", This, p);
*p = NULL;
if(!This->doc->hostui)
return S_OK;
return IDocHostUIHandler_GetExternal(This->doc->hostui, p);
}
#undef HTMLWINDOW2_THIS
static const IHTMLWindow2Vtbl HTMLWindow2Vtbl = {
HTMLWindow2_QueryInterface,
HTMLWindow2_AddRef,
HTMLWindow2_Release,
HTMLWindow2_GetTypeInfoCount,
HTMLWindow2_GetTypeInfo,
HTMLWindow2_GetIDsOfNames,
HTMLWindow2_Invoke,
HTMLWindow2_item,
HTMLWindow2_get_length,
HTMLWindow2_get_frames,
HTMLWindow2_put_defaultStatus,
HTMLWindow2_get_defaultStatus,
HTMLWindow2_put_status,
HTMLWindow2_get_status,
HTMLWindow2_setTimeout,
HTMLWindow2_clearTimeout,
HTMLWindow2_alert,
HTMLWindow2_confirm,
HTMLWindow2_prompt,
HTMLWindow2_get_Image,
HTMLWindow2_get_location,
HTMLWindow2_get_history,
HTMLWindow2_close,
HTMLWindow2_put_opener,
HTMLWindow2_get_opener,
HTMLWindow2_get_navigator,
HTMLWindow2_put_name,
HTMLWindow2_get_name,
HTMLWindow2_get_parent,
HTMLWindow2_open,
HTMLWindow2_get_self,
HTMLWindow2_get_top,
HTMLWindow2_get_window,
HTMLWindow2_navigate,
HTMLWindow2_put_onfocus,
HTMLWindow2_get_onfocus,
HTMLWindow2_put_onblur,
HTMLWindow2_get_onblur,
HTMLWindow2_put_onload,
HTMLWindow2_get_onload,
HTMLWindow2_put_onbeforeunload,
HTMLWindow2_get_onbeforeunload,
HTMLWindow2_put_onunload,
HTMLWindow2_get_onunload,
HTMLWindow2_put_onhelp,
HTMLWindow2_get_onhelp,
HTMLWindow2_put_onerror,
HTMLWindow2_get_onerror,
HTMLWindow2_put_onresize,
HTMLWindow2_get_onresize,
HTMLWindow2_put_onscroll,
HTMLWindow2_get_onscroll,
HTMLWindow2_get_document,
HTMLWindow2_get_event,
HTMLWindow2_get__newEnum,
HTMLWindow2_showModalDialog,
HTMLWindow2_showHelp,
HTMLWindow2_get_screen,
HTMLWindow2_get_Option,
HTMLWindow2_focus,
HTMLWindow2_get_closed,
HTMLWindow2_blur,
HTMLWindow2_scroll,
HTMLWindow2_get_clientInformation,
HTMLWindow2_setInterval,
HTMLWindow2_clearInterval,
HTMLWindow2_put_offscreenBuffering,
HTMLWindow2_get_offscreenBuffering,
HTMLWindow2_execScript,
HTMLWindow2_toString,
HTMLWindow2_scrollBy,
HTMLWindow2_scrollTo,
HTMLWindow2_moveTo,
HTMLWindow2_moveBy,
HTMLWindow2_resizeTo,
HTMLWindow2_resizeBy,
HTMLWindow2_get_external
};
#define HTMLWINDOW3_THIS(iface) DEFINE_THIS(HTMLWindow, HTMLWindow3, iface)
static HRESULT WINAPI HTMLWindow3_QueryInterface(IHTMLWindow3 *iface, REFIID riid, void **ppv)
{
HTMLWindow *This = HTMLWINDOW3_THIS(iface);
return IHTMLWindow2_QueryInterface(HTMLWINDOW2(This), riid, ppv);
}
static ULONG WINAPI HTMLWindow3_AddRef(IHTMLWindow3 *iface)
{
HTMLWindow *This = HTMLWINDOW3_THIS(iface);
return IHTMLWindow2_AddRef(HTMLWINDOW2(This));
}
static ULONG WINAPI HTMLWindow3_Release(IHTMLWindow3 *iface)
{
HTMLWindow *This = HTMLWINDOW3_THIS(iface);
return IHTMLWindow2_Release(HTMLWINDOW2(This));
}
static HRESULT WINAPI HTMLWindow3_GetTypeInfoCount(IHTMLWindow3 *iface, UINT *pctinfo)
{
HTMLWindow *This = HTMLWINDOW3_THIS(iface);
return IDispatchEx_GetTypeInfoCount(DISPATCHEX(This), pctinfo);
}
static HRESULT WINAPI HTMLWindow3_GetTypeInfo(IHTMLWindow3 *iface, UINT iTInfo,
LCID lcid, ITypeInfo **ppTInfo)
{
HTMLWindow *This = HTMLWINDOW3_THIS(iface);
return IDispatchEx_GetTypeInfo(DISPATCHEX(This), iTInfo, lcid, ppTInfo);
}
static HRESULT WINAPI HTMLWindow3_GetIDsOfNames(IHTMLWindow3 *iface, REFIID riid,
LPOLESTR *rgszNames, UINT cNames,
LCID lcid, DISPID *rgDispId)
{
HTMLWindow *This = HTMLWINDOW3_THIS(iface);
return IDispatchEx_GetIDsOfNames(DISPATCHEX(This), riid, rgszNames, cNames, lcid, rgDispId);
}
static HRESULT WINAPI HTMLWindow3_Invoke(IHTMLWindow3 *iface, DISPID dispIdMember,
REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS *pDispParams,
VARIANT *pVarResult, EXCEPINFO *pExcepInfo, UINT *puArgErr)
{
HTMLWindow *This = HTMLWINDOW3_THIS(iface);
return IDispatchEx_Invoke(DISPATCHEX(This), dispIdMember, riid, lcid, wFlags, pDispParams,
pVarResult, pExcepInfo, puArgErr);
}
static HRESULT WINAPI HTMLWindow3_get_screenLeft(IHTMLWindow3 *iface, long *p)
{
HTMLWindow *This = HTMLWINDOW3_THIS(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLWindow3_get_screenTop(IHTMLWindow3 *iface, long *p)
{
HTMLWindow *This = HTMLWINDOW3_THIS(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLWindow3_attachEvent(IHTMLWindow3 *iface, BSTR event, IDispatch *pDisp, VARIANT_BOOL *pfResult)
{
HTMLWindow *This = HTMLWINDOW3_THIS(iface);
FIXME("(%p)->(%s %p %p)\n", This, debugstr_w(event), pDisp, pfResult);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLWindow3_detachEvent(IHTMLWindow3 *iface, BSTR event, IDispatch *pDisp)
{
HTMLWindow *This = HTMLWINDOW3_THIS(iface);
FIXME("(%p)->()\n", This);
return E_NOTIMPL;
}
static HRESULT window_set_timer(HTMLWindow *This, VARIANT *expr, long msec, VARIANT *language,
BOOL interval, long *timer_id)
{
IDispatch *disp = NULL;
switch(V_VT(expr)) {
case VT_DISPATCH:
disp = V_DISPATCH(expr);
IDispatch_AddRef(disp);
break;
case VT_BSTR:
disp = script_parse_event(This->doc, V_BSTR(expr));
break;
default:
FIXME("unimplemented vt=%d\n", V_VT(expr));
return E_NOTIMPL;
}
if(!disp)
return E_FAIL;
*timer_id = set_task_timer(This->doc, msec, interval, disp);
IDispatch_Release(disp);
return S_OK;
}
static HRESULT WINAPI HTMLWindow3_setTimeout(IHTMLWindow3 *iface, VARIANT *expression, long msec,
VARIANT *language, long *timerID)
{
HTMLWindow *This = HTMLWINDOW3_THIS(iface);
TRACE("(%p)->(%p(%d) %ld %p %p)\n", This, expression, V_VT(expression), msec, language, timerID);
return window_set_timer(This, expression, msec, language, FALSE, timerID);
}
static HRESULT WINAPI HTMLWindow3_setInterval(IHTMLWindow3 *iface, VARIANT *expression, long msec,
VARIANT *language, long *timerID)
{
HTMLWindow *This = HTMLWINDOW3_THIS(iface);
TRACE("(%p)->(%p %ld %p %p)\n", This, expression, msec, language, timerID);
return window_set_timer(This, expression, msec, language, TRUE, timerID);
}
static HRESULT WINAPI HTMLWindow3_print(IHTMLWindow3 *iface)
{
HTMLWindow *This = HTMLWINDOW3_THIS(iface);
FIXME("(%p)\n", This);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLWindow3_put_onbeforeprint(IHTMLWindow3 *iface, VARIANT v)
{
HTMLWindow *This = HTMLWINDOW3_THIS(iface);
FIXME("(%p)->()\n", This);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLWindow3_get_onbeforeprint(IHTMLWindow3 *iface, VARIANT *p)
{
HTMLWindow *This = HTMLWINDOW3_THIS(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLWindow3_put_onafterprint(IHTMLWindow3 *iface, VARIANT v)
{
HTMLWindow *This = HTMLWINDOW3_THIS(iface);
FIXME("(%p)->()\n", This);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLWindow3_get_onafterprint(IHTMLWindow3 *iface, VARIANT *p)
{
HTMLWindow *This = HTMLWINDOW3_THIS(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLWindow3_get_clipboardData(IHTMLWindow3 *iface, IHTMLDataTransfer **p)
{
HTMLWindow *This = HTMLWINDOW3_THIS(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLWindow3_showModelessDialog(IHTMLWindow3 *iface, BSTR url,
VARIANT *varArgIn, VARIANT *options, IHTMLWindow2 **pDialog)
{
HTMLWindow *This = HTMLWINDOW3_THIS(iface);
FIXME("(%p)->(%s %p %p %p)\n", This, debugstr_w(url), varArgIn, options, pDialog);
return E_NOTIMPL;
}
#undef HTMLWINDOW3_THIS
static const IHTMLWindow3Vtbl HTMLWindow3Vtbl = {
HTMLWindow3_QueryInterface,
HTMLWindow3_AddRef,
HTMLWindow3_Release,
HTMLWindow3_GetTypeInfoCount,
HTMLWindow3_GetTypeInfo,
HTMLWindow3_GetIDsOfNames,
HTMLWindow3_Invoke,
HTMLWindow3_get_screenLeft,
HTMLWindow3_get_screenTop,
HTMLWindow3_attachEvent,
HTMLWindow3_detachEvent,
HTMLWindow3_setTimeout,
HTMLWindow3_setInterval,
HTMLWindow3_print,
HTMLWindow3_put_onbeforeprint,
HTMLWindow3_get_onbeforeprint,
HTMLWindow3_put_onafterprint,
HTMLWindow3_get_onafterprint,
HTMLWindow3_get_clipboardData,
HTMLWindow3_showModelessDialog
};
#define DISPEX_THIS(iface) DEFINE_THIS(HTMLWindow, IDispatchEx, iface)
static HRESULT WINAPI WindowDispEx_QueryInterface(IDispatchEx *iface, REFIID riid, void **ppv)
{
HTMLWindow *This = DISPEX_THIS(iface);
return IHTMLWindow2_QueryInterface(HTMLWINDOW2(This), riid, ppv);
}
static ULONG WINAPI WindowDispEx_AddRef(IDispatchEx *iface)
{
HTMLWindow *This = DISPEX_THIS(iface);
return IHTMLWindow2_AddRef(HTMLWINDOW2(This));
}
static ULONG WINAPI WindowDispEx_Release(IDispatchEx *iface)
{
HTMLWindow *This = DISPEX_THIS(iface);
return IHTMLWindow2_Release(HTMLWINDOW2(This));
}
static HRESULT WINAPI WindowDispEx_GetTypeInfoCount(IDispatchEx *iface, UINT *pctinfo)
{
HTMLWindow *This = DISPEX_THIS(iface);
TRACE("(%p)->(%p)\n", This, pctinfo);
return IDispatchEx_GetTypeInfoCount(DISPATCHEX(&This->dispex), pctinfo);
}
static HRESULT WINAPI WindowDispEx_GetTypeInfo(IDispatchEx *iface, UINT iTInfo,
LCID lcid, ITypeInfo **ppTInfo)
{
HTMLWindow *This = DISPEX_THIS(iface);
TRACE("(%p)->(%u %u %p)\n", This, iTInfo, lcid, ppTInfo);
return IDispatchEx_GetTypeInfo(DISPATCHEX(&This->dispex), iTInfo, lcid, ppTInfo);
}
static HRESULT WINAPI WindowDispEx_GetIDsOfNames(IDispatchEx *iface, REFIID riid,
LPOLESTR *rgszNames, UINT cNames,
LCID lcid, DISPID *rgDispId)
{
HTMLWindow *This = DISPEX_THIS(iface);
TRACE("(%p)->(%s %p %u %u %p)\n", This, debugstr_guid(riid), rgszNames, cNames,
lcid, rgDispId);
/* FIXME: Use script dispatch */
return IDispatchEx_GetIDsOfNames(DISPATCHEX(&This->dispex), riid, rgszNames, cNames, lcid, rgDispId);
}
static HRESULT WINAPI WindowDispEx_Invoke(IDispatchEx *iface, DISPID dispIdMember,
REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS *pDispParams,
VARIANT *pVarResult, EXCEPINFO *pExcepInfo, UINT *puArgErr)
{
HTMLWindow *This = DISPEX_THIS(iface);
TRACE("(%p)->(%d %s %d %d %p %p %p %p)\n", This, dispIdMember, debugstr_guid(riid),
lcid, wFlags, pDispParams, pVarResult, pExcepInfo, puArgErr);
/* FIXME: Use script dispatch */
return IDispatchEx_Invoke(DISPATCHEX(&This->dispex), dispIdMember, riid, lcid, wFlags, pDispParams,
pVarResult, pExcepInfo, puArgErr);
}
static HRESULT WINAPI WindowDispEx_GetDispID(IDispatchEx *iface, BSTR bstrName, DWORD grfdex, DISPID *pid)
{
HTMLWindow *This = DISPEX_THIS(iface);
TRACE("(%p)->(%s %x %p)\n", This, debugstr_w(bstrName), grfdex, pid);
return IDispatchEx_GetDispID(DISPATCHEX(&This->dispex), bstrName, grfdex, pid);
}
static HRESULT WINAPI WindowDispEx_InvokeEx(IDispatchEx *iface, DISPID id, LCID lcid, WORD wFlags, DISPPARAMS *pdp,
VARIANT *pvarRes, EXCEPINFO *pei, IServiceProvider *pspCaller)
{
HTMLWindow *This = DISPEX_THIS(iface);
TRACE("(%p)->(%x %x %x %p %p %p %p)\n", This, id, lcid, wFlags, pdp, pvarRes, pei, pspCaller);
return IDispatchEx_InvokeEx(DISPATCHEX(&This->dispex), id, lcid, wFlags, pdp, pvarRes, pei, pspCaller);
}
static HRESULT WINAPI WindowDispEx_DeleteMemberByName(IDispatchEx *iface, BSTR bstrName, DWORD grfdex)
{
HTMLWindow *This = DISPEX_THIS(iface);
TRACE("(%p)->(%s %x)\n", This, debugstr_w(bstrName), grfdex);
return IDispatchEx_DeleteMemberByName(DISPATCHEX(&This->dispex), bstrName, grfdex);
}
static HRESULT WINAPI WindowDispEx_DeleteMemberByDispID(IDispatchEx *iface, DISPID id)
{
HTMLWindow *This = DISPEX_THIS(iface);
TRACE("(%p)->(%x)\n", This, id);
return IDispatchEx_DeleteMemberByDispID(DISPATCHEX(&This->dispex), id);
}
static HRESULT WINAPI WindowDispEx_GetMemberProperties(IDispatchEx *iface, DISPID id, DWORD grfdexFetch, DWORD *pgrfdex)
{
HTMLWindow *This = DISPEX_THIS(iface);
TRACE("(%p)->(%x %x %p)\n", This, id, grfdexFetch, pgrfdex);
return IDispatchEx_GetMemberProperties(DISPATCHEX(&This->dispex), id, grfdexFetch, pgrfdex);
}
static HRESULT WINAPI WindowDispEx_GetMemberName(IDispatchEx *iface, DISPID id, BSTR *pbstrName)
{
HTMLWindow *This = DISPEX_THIS(iface);
TRACE("(%p)->(%x %p)\n", This, id, pbstrName);
return IDispatchEx_GetMemberName(DISPATCHEX(&This->dispex), id, pbstrName);
}
static HRESULT WINAPI WindowDispEx_GetNextDispID(IDispatchEx *iface, DWORD grfdex, DISPID id, DISPID *pid)
{
HTMLWindow *This = DISPEX_THIS(iface);
TRACE("(%p)->(%x %x %p)\n", This, grfdex, id, pid);
return IDispatchEx_GetNextDispID(DISPATCHEX(&This->dispex), grfdex, id, pid);
}
static HRESULT WINAPI WindowDispEx_GetNameSpaceParent(IDispatchEx *iface, IUnknown **ppunk)
{
HTMLWindow *This = DISPEX_THIS(iface);
TRACE("(%p)->(%p)\n", This, ppunk);
*ppunk = NULL;
return S_OK;
}
#undef DISPEX_THIS
static const IDispatchExVtbl WindowDispExVtbl = {
WindowDispEx_QueryInterface,
WindowDispEx_AddRef,
WindowDispEx_Release,
WindowDispEx_GetTypeInfoCount,
WindowDispEx_GetTypeInfo,
WindowDispEx_GetIDsOfNames,
WindowDispEx_Invoke,
WindowDispEx_GetDispID,
WindowDispEx_InvokeEx,
WindowDispEx_DeleteMemberByName,
WindowDispEx_DeleteMemberByDispID,
WindowDispEx_GetMemberProperties,
WindowDispEx_GetMemberName,
WindowDispEx_GetNextDispID,
WindowDispEx_GetNameSpaceParent
};
static const tid_t HTMLWindow_iface_tids[] = {
IHTMLWindow2_tid,
IHTMLWindow3_tid,
0
};
static dispex_static_data_t HTMLWindow_dispex = {
NULL,
DispHTMLWindow2_tid,
NULL,
HTMLWindow_iface_tids
};
HRESULT HTMLWindow_Create(HTMLDocument *doc, nsIDOMWindow *nswindow, HTMLWindow **ret)
{
HTMLWindow *window;
window = heap_alloc_zero(sizeof(HTMLWindow));
if(!window)
return E_OUTOFMEMORY;
window->lpHTMLWindow2Vtbl = &HTMLWindow2Vtbl;
window->lpHTMLWindow3Vtbl = &HTMLWindow3Vtbl;
window->lpIDispatchExVtbl = &WindowDispExVtbl;
window->ref = 1;
window->doc = doc;
init_dispex(&window->dispex, (IUnknown*)HTMLWINDOW2(window), &HTMLWindow_dispex);
if(nswindow) {
nsIDOMWindow_AddRef(nswindow);
window->nswindow = nswindow;
}
list_add_head(&window_list, &window->entry);
*ret = window;
return S_OK;
}
HTMLWindow *nswindow_to_window(const nsIDOMWindow *nswindow)
{
HTMLWindow *iter;
LIST_FOR_EACH_ENTRY(iter, &window_list, HTMLWindow, entry) {
if(iter->nswindow == nswindow)
return iter;
}
return NULL;
}
| 29.357724 | 120 | 0.691831 | [
"object"
] |
97a4efb59dd97f2476731eda5d69f4de92b02596 | 14,590 | h | C | include/roscpp_tutorials/SimpleLatDebug.h | cuiDarchan/Lio_sam_modify | 455047a887d51e1cb9f4285fbba3a05aa599eadf | [
"BSD-3-Clause"
] | 1 | 2021-11-19T02:31:45.000Z | 2021-11-19T02:31:45.000Z | include/roscpp_tutorials/SimpleLatDebug.h | cuiDarchan/Lio_sam_modify | 455047a887d51e1cb9f4285fbba3a05aa599eadf | [
"BSD-3-Clause"
] | null | null | null | include/roscpp_tutorials/SimpleLatDebug.h | cuiDarchan/Lio_sam_modify | 455047a887d51e1cb9f4285fbba3a05aa599eadf | [
"BSD-3-Clause"
] | null | null | null | // Generated by gencpp from file roscpp_tutorials/SimpleLatDebug.msg
// DO NOT EDIT!
#ifndef ROSCPP_TUTORIALS_MESSAGE_SIMPLELATDEBUG_H
#define ROSCPP_TUTORIALS_MESSAGE_SIMPLELATDEBUG_H
#include <string>
#include <vector>
#include <map>
#include <ros/types.h>
#include <ros/serialization.h>
#include <ros/builtin_message_traits.h>
#include <ros/message_operations.h>
namespace roscpp_tutorials
{
template <class ContainerAllocator>
struct SimpleLatDebug_
{
typedef SimpleLatDebug_<ContainerAllocator> Type;
SimpleLatDebug_()
: lateral_error(0.0)
, ref_heading(0.0)
, heading(0.0)
, heading_error(0.0)
, heading_error_rate(0.0)
, lateral_error_rate(0.0)
, curvature(0.0)
, steer_angle(0.0)
, steer_angle_feedforward(0.0)
, steer_angle_lateral_contribution(0.0)
, steer_angle_lateral_rate_contribution(0.0)
, steer_angle_heading_contribution(0.0)
, steer_angle_heading_rate_contribution(0.0)
, steer_angle_feedback(0.0)
, steering_position(0.0)
, ref_speed(0.0)
, steer_angle_limited(0.0)
, steer_angle_integral(0.0)
, steer_angle_correct(0.0)
, steer_angle_roll_compensate(0.0)
, ref_x(0.0)
, ref_y(0.0)
, real_speed(0.0)
, matrix_k1(0.0)
, matrix_k2(0.0)
, matrix_k3(0.0)
, matrix_k4(0.0)
, matched_lat_acceleration(0.0)
, matched_lat_speed(0.0)
, matched_lat_station(0.0) {
}
SimpleLatDebug_(const ContainerAllocator& _alloc)
: lateral_error(0.0)
, ref_heading(0.0)
, heading(0.0)
, heading_error(0.0)
, heading_error_rate(0.0)
, lateral_error_rate(0.0)
, curvature(0.0)
, steer_angle(0.0)
, steer_angle_feedforward(0.0)
, steer_angle_lateral_contribution(0.0)
, steer_angle_lateral_rate_contribution(0.0)
, steer_angle_heading_contribution(0.0)
, steer_angle_heading_rate_contribution(0.0)
, steer_angle_feedback(0.0)
, steering_position(0.0)
, ref_speed(0.0)
, steer_angle_limited(0.0)
, steer_angle_integral(0.0)
, steer_angle_correct(0.0)
, steer_angle_roll_compensate(0.0)
, ref_x(0.0)
, ref_y(0.0)
, real_speed(0.0)
, matrix_k1(0.0)
, matrix_k2(0.0)
, matrix_k3(0.0)
, matrix_k4(0.0)
, matched_lat_acceleration(0.0)
, matched_lat_speed(0.0)
, matched_lat_station(0.0) {
(void)_alloc;
}
typedef float _lateral_error_type;
_lateral_error_type lateral_error;
typedef float _ref_heading_type;
_ref_heading_type ref_heading;
typedef float _heading_type;
_heading_type heading;
typedef float _heading_error_type;
_heading_error_type heading_error;
typedef float _heading_error_rate_type;
_heading_error_rate_type heading_error_rate;
typedef float _lateral_error_rate_type;
_lateral_error_rate_type lateral_error_rate;
typedef float _curvature_type;
_curvature_type curvature;
typedef float _steer_angle_type;
_steer_angle_type steer_angle;
typedef float _steer_angle_feedforward_type;
_steer_angle_feedforward_type steer_angle_feedforward;
typedef float _steer_angle_lateral_contribution_type;
_steer_angle_lateral_contribution_type steer_angle_lateral_contribution;
typedef float _steer_angle_lateral_rate_contribution_type;
_steer_angle_lateral_rate_contribution_type steer_angle_lateral_rate_contribution;
typedef float _steer_angle_heading_contribution_type;
_steer_angle_heading_contribution_type steer_angle_heading_contribution;
typedef float _steer_angle_heading_rate_contribution_type;
_steer_angle_heading_rate_contribution_type steer_angle_heading_rate_contribution;
typedef float _steer_angle_feedback_type;
_steer_angle_feedback_type steer_angle_feedback;
typedef float _steering_position_type;
_steering_position_type steering_position;
typedef float _ref_speed_type;
_ref_speed_type ref_speed;
typedef float _steer_angle_limited_type;
_steer_angle_limited_type steer_angle_limited;
typedef float _steer_angle_integral_type;
_steer_angle_integral_type steer_angle_integral;
typedef float _steer_angle_correct_type;
_steer_angle_correct_type steer_angle_correct;
typedef float _steer_angle_roll_compensate_type;
_steer_angle_roll_compensate_type steer_angle_roll_compensate;
typedef float _ref_x_type;
_ref_x_type ref_x;
typedef float _ref_y_type;
_ref_y_type ref_y;
typedef float _real_speed_type;
_real_speed_type real_speed;
typedef float _matrix_k1_type;
_matrix_k1_type matrix_k1;
typedef float _matrix_k2_type;
_matrix_k2_type matrix_k2;
typedef float _matrix_k3_type;
_matrix_k3_type matrix_k3;
typedef float _matrix_k4_type;
_matrix_k4_type matrix_k4;
typedef float _matched_lat_acceleration_type;
_matched_lat_acceleration_type matched_lat_acceleration;
typedef float _matched_lat_speed_type;
_matched_lat_speed_type matched_lat_speed;
typedef float _matched_lat_station_type;
_matched_lat_station_type matched_lat_station;
typedef boost::shared_ptr< ::roscpp_tutorials::SimpleLatDebug_<ContainerAllocator> > Ptr;
typedef boost::shared_ptr< ::roscpp_tutorials::SimpleLatDebug_<ContainerAllocator> const> ConstPtr;
}; // struct SimpleLatDebug_
typedef ::roscpp_tutorials::SimpleLatDebug_<std::allocator<void> > SimpleLatDebug;
typedef boost::shared_ptr< ::roscpp_tutorials::SimpleLatDebug > SimpleLatDebugPtr;
typedef boost::shared_ptr< ::roscpp_tutorials::SimpleLatDebug const> SimpleLatDebugConstPtr;
// constants requiring out of line definition
template<typename ContainerAllocator>
std::ostream& operator<<(std::ostream& s, const ::roscpp_tutorials::SimpleLatDebug_<ContainerAllocator> & v)
{
ros::message_operations::Printer< ::roscpp_tutorials::SimpleLatDebug_<ContainerAllocator> >::stream(s, "", v);
return s;
}
} // namespace roscpp_tutorials
namespace ros
{
namespace message_traits
{
// BOOLTRAITS {'IsFixedSize': True, 'IsMessage': True, 'HasHeader': False}
// {'std_msgs': ['/opt/ros/kinetic/share/std_msgs/cmake/../msg'], 'roscpp_tutorials': ['/home/cui-dell/catkin_ws/src/roscpp_tutorials/msg']}
// !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types']
template <class ContainerAllocator>
struct IsFixedSize< ::roscpp_tutorials::SimpleLatDebug_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsFixedSize< ::roscpp_tutorials::SimpleLatDebug_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::roscpp_tutorials::SimpleLatDebug_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::roscpp_tutorials::SimpleLatDebug_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct HasHeader< ::roscpp_tutorials::SimpleLatDebug_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct HasHeader< ::roscpp_tutorials::SimpleLatDebug_<ContainerAllocator> const>
: FalseType
{ };
template<class ContainerAllocator>
struct MD5Sum< ::roscpp_tutorials::SimpleLatDebug_<ContainerAllocator> >
{
static const char* value()
{
return "128a427479b4be8a3bf5bc243cda58d6";
}
static const char* value(const ::roscpp_tutorials::SimpleLatDebug_<ContainerAllocator>&) { return value(); }
static const uint64_t static_value1 = 0x128a427479b4be8aULL;
static const uint64_t static_value2 = 0x3bf5bc243cda58d6ULL;
};
template<class ContainerAllocator>
struct DataType< ::roscpp_tutorials::SimpleLatDebug_<ContainerAllocator> >
{
static const char* value()
{
return "roscpp_tutorials/SimpleLatDebug";
}
static const char* value(const ::roscpp_tutorials::SimpleLatDebug_<ContainerAllocator>&) { return value(); }
};
template<class ContainerAllocator>
struct Definition< ::roscpp_tutorials::SimpleLatDebug_<ContainerAllocator> >
{
static const char* value()
{
return "float32 lateral_error\n\
float32 ref_heading\n\
float32 heading\n\
float32 heading_error\n\
float32 heading_error_rate\n\
float32 lateral_error_rate\n\
float32 curvature\n\
float32 steer_angle\n\
float32 steer_angle_feedforward\n\
float32 steer_angle_lateral_contribution\n\
float32 steer_angle_lateral_rate_contribution\n\
float32 steer_angle_heading_contribution\n\
float32 steer_angle_heading_rate_contribution\n\
float32 steer_angle_feedback\n\
float32 steering_position\n\
float32 ref_speed\n\
float32 steer_angle_limited\n\
float32 steer_angle_integral\n\
float32 steer_angle_correct\n\
float32 steer_angle_roll_compensate\n\
float32 ref_x\n\
float32 ref_y\n\
float32 real_speed\n\
float32 matrix_k1\n\
float32 matrix_k2\n\
float32 matrix_k3\n\
float32 matrix_k4\n\
float32 matched_lat_acceleration\n\
float32 matched_lat_speed\n\
float32 matched_lat_station\n\
";
}
static const char* value(const ::roscpp_tutorials::SimpleLatDebug_<ContainerAllocator>&) { return value(); }
};
} // namespace message_traits
} // namespace ros
namespace ros
{
namespace serialization
{
template<class ContainerAllocator> struct Serializer< ::roscpp_tutorials::SimpleLatDebug_<ContainerAllocator> >
{
template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m)
{
stream.next(m.lateral_error);
stream.next(m.ref_heading);
stream.next(m.heading);
stream.next(m.heading_error);
stream.next(m.heading_error_rate);
stream.next(m.lateral_error_rate);
stream.next(m.curvature);
stream.next(m.steer_angle);
stream.next(m.steer_angle_feedforward);
stream.next(m.steer_angle_lateral_contribution);
stream.next(m.steer_angle_lateral_rate_contribution);
stream.next(m.steer_angle_heading_contribution);
stream.next(m.steer_angle_heading_rate_contribution);
stream.next(m.steer_angle_feedback);
stream.next(m.steering_position);
stream.next(m.ref_speed);
stream.next(m.steer_angle_limited);
stream.next(m.steer_angle_integral);
stream.next(m.steer_angle_correct);
stream.next(m.steer_angle_roll_compensate);
stream.next(m.ref_x);
stream.next(m.ref_y);
stream.next(m.real_speed);
stream.next(m.matrix_k1);
stream.next(m.matrix_k2);
stream.next(m.matrix_k3);
stream.next(m.matrix_k4);
stream.next(m.matched_lat_acceleration);
stream.next(m.matched_lat_speed);
stream.next(m.matched_lat_station);
}
ROS_DECLARE_ALLINONE_SERIALIZER
}; // struct SimpleLatDebug_
} // namespace serialization
} // namespace ros
namespace ros
{
namespace message_operations
{
template<class ContainerAllocator>
struct Printer< ::roscpp_tutorials::SimpleLatDebug_<ContainerAllocator> >
{
template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::roscpp_tutorials::SimpleLatDebug_<ContainerAllocator>& v)
{
s << indent << "lateral_error: ";
Printer<float>::stream(s, indent + " ", v.lateral_error);
s << indent << "ref_heading: ";
Printer<float>::stream(s, indent + " ", v.ref_heading);
s << indent << "heading: ";
Printer<float>::stream(s, indent + " ", v.heading);
s << indent << "heading_error: ";
Printer<float>::stream(s, indent + " ", v.heading_error);
s << indent << "heading_error_rate: ";
Printer<float>::stream(s, indent + " ", v.heading_error_rate);
s << indent << "lateral_error_rate: ";
Printer<float>::stream(s, indent + " ", v.lateral_error_rate);
s << indent << "curvature: ";
Printer<float>::stream(s, indent + " ", v.curvature);
s << indent << "steer_angle: ";
Printer<float>::stream(s, indent + " ", v.steer_angle);
s << indent << "steer_angle_feedforward: ";
Printer<float>::stream(s, indent + " ", v.steer_angle_feedforward);
s << indent << "steer_angle_lateral_contribution: ";
Printer<float>::stream(s, indent + " ", v.steer_angle_lateral_contribution);
s << indent << "steer_angle_lateral_rate_contribution: ";
Printer<float>::stream(s, indent + " ", v.steer_angle_lateral_rate_contribution);
s << indent << "steer_angle_heading_contribution: ";
Printer<float>::stream(s, indent + " ", v.steer_angle_heading_contribution);
s << indent << "steer_angle_heading_rate_contribution: ";
Printer<float>::stream(s, indent + " ", v.steer_angle_heading_rate_contribution);
s << indent << "steer_angle_feedback: ";
Printer<float>::stream(s, indent + " ", v.steer_angle_feedback);
s << indent << "steering_position: ";
Printer<float>::stream(s, indent + " ", v.steering_position);
s << indent << "ref_speed: ";
Printer<float>::stream(s, indent + " ", v.ref_speed);
s << indent << "steer_angle_limited: ";
Printer<float>::stream(s, indent + " ", v.steer_angle_limited);
s << indent << "steer_angle_integral: ";
Printer<float>::stream(s, indent + " ", v.steer_angle_integral);
s << indent << "steer_angle_correct: ";
Printer<float>::stream(s, indent + " ", v.steer_angle_correct);
s << indent << "steer_angle_roll_compensate: ";
Printer<float>::stream(s, indent + " ", v.steer_angle_roll_compensate);
s << indent << "ref_x: ";
Printer<float>::stream(s, indent + " ", v.ref_x);
s << indent << "ref_y: ";
Printer<float>::stream(s, indent + " ", v.ref_y);
s << indent << "real_speed: ";
Printer<float>::stream(s, indent + " ", v.real_speed);
s << indent << "matrix_k1: ";
Printer<float>::stream(s, indent + " ", v.matrix_k1);
s << indent << "matrix_k2: ";
Printer<float>::stream(s, indent + " ", v.matrix_k2);
s << indent << "matrix_k3: ";
Printer<float>::stream(s, indent + " ", v.matrix_k3);
s << indent << "matrix_k4: ";
Printer<float>::stream(s, indent + " ", v.matrix_k4);
s << indent << "matched_lat_acceleration: ";
Printer<float>::stream(s, indent + " ", v.matched_lat_acceleration);
s << indent << "matched_lat_speed: ";
Printer<float>::stream(s, indent + " ", v.matched_lat_speed);
s << indent << "matched_lat_station: ";
Printer<float>::stream(s, indent + " ", v.matched_lat_station);
}
};
} // namespace message_operations
} // namespace ros
#endif // ROSCPP_TUTORIALS_MESSAGE_SIMPLELATDEBUG_H
| 32.494432 | 441 | 0.732831 | [
"vector"
] |
97a565c2b8033523cb52cd0ff64a017e309d87f7 | 4,764 | h | C | snap-adv/utilities.h | VandinLab/odeN | 46b0cd799e9da57be5429b02f255cdedb14b1e35 | [
"MIT"
] | 2 | 2021-08-19T21:02:21.000Z | 2021-08-20T05:55:00.000Z | snap-adv/utilities.h | VandinLab/odeN | 46b0cd799e9da57be5429b02f255cdedb14b1e35 | [
"MIT"
] | null | null | null | snap-adv/utilities.h | VandinLab/odeN | 46b0cd799e9da57be5429b02f255cdedb14b1e35 | [
"MIT"
] | null | null | null | #ifndef utilities_h
#define utilities_h
#include "datastructures.h"
#include "temporalmotiftypes.h"
#include "Snap.h"
#include <random>
#include <unordered_set>
#include <unordered_map>
#include <functional>
#include <vector>
#include <algorithm>
#include <utility>
#include <boost/functional/hash.hpp>
#include <fstream>
#include <sstream>
#include <iterator>
#include <iostream>
#include <cstdlib>
// TODO: REPLACE THIS WITH SNAP STRUCTURES
using DataStructures::TEdge;
namespace Utils {
int LoadEdgeList(const std::string& filenameG, std::vector<TEdge>& edges_, std::vector<size_t>& temporal_degrees_);
int LoadEdgeList(const std::string& filenameG, TVec< THash<TInt, TVec<TInt64> >> &temporal_data, std::vector<size_t>& temporal_degrees_, long long int& totedges, timestamp_t& timespan);
int LoadTemporalMotif(const std::string& filenameM, std::vector<std::pair<int, int>>& edgesM_, int& Vm_, int& l_);
int RemapNodes(std::vector<TEdge>& edgeList);
int PrintGraph(std::vector<TEdge>& edgeList);
int GetTrianglesFromNode(PUNGraph graph, const int startingNode, std::vector<std::vector<std::pair<node_t, node_t> > >& triangles);
int GetTrianglesFromEdge(const PUNGraph graph, const std::pair<node_t,node_t>& sampledEdge, std::vector<std::vector<std::pair<node_t, node_t> > >& triangles);
int GetTrianglesFromEdgeThreads(const PUNGraph& graph, const std::pair<node_t,node_t>& sampledEdge, std::vector<std::vector<std::pair<node_t, node_t> > >& triangles);
int GetWedgesFromEdge(PUNGraph graph, const std::pair<node_t,node_t>& sampledEdge, std::vector<std::vector<std::pair<node_t, node_t> > >& wedges);
int GetSquaresFromEdge(PUNGraph graph, const std::pair<node_t,node_t>& sampledEdge, std::vector<std::vector<std::pair<node_t, node_t> > >& squares);
int GetSquaresFromEdgeMin(PUNGraph graph, const std::pair<node_t,node_t>& sampledEdge, std::vector<std::vector<std::pair<node_t, node_t> > >& squares);
}
// Object to represent a static directed edge src -> dst and all the timestamps that are mapped on such static edges
class StaticEdge{
private:
std::pair<node_t, node_t> m_srcdst;
public:
StaticEdge(const TEdge edge) {
m_srcdst.first = edge.src;
m_srcdst.second = edge.dst;
}
node_t getSrc() { return m_srcdst.first; }
node_t getDst() { return m_srcdst.second; }
/*
void addTimestamp(const timestamp_t time) { m_timestamps.insert(time); };
std::vector<TEdge> getTemporalEdges()
{
std::vector<TEdge> temporal_edges;
long long ID = 0;
for(auto it = m_timestamps.begin(); it != m_timestamps.end(); ++it)
{
TEdge tmp = {.src = m_src, .dst = m_dst, .tim = *it, .id=ID++};
temporal_edges.push_back(tmp);
}
std::sort(temporal_edges.begin(), temporal_edges.end());
return temporal_edges;
}
*/
};
struct hash_pair
{
template <class T1, class T2>
size_t operator()(const std::pair<T1, T2>& p) const
{
auto hash1 = std::hash<T1>{}(p.first);
auto hash2 = std::hash<T2>{}(p.second);
size_t seed = 0;
boost::hash_combine(seed, hash1);
boost::hash_combine(seed, hash2);
return seed;
//return hash1 ^ hash2;
}
};
struct hash_vector
{
template <class T1>
size_t operator()(const std::vector<T1>& v) const
{
std::hash<T1> hasher;
size_t seed = 0;
for(T1 el : v)
{
seed ^= hasher(el) + 0x9e3779b9 + (seed<<6) + (seed>>2);
}
return seed;
}
};
class StaticGraph{
private:
//std::unordered_map<std::pair<node_t, node_t>, std::vector<timestamp_t>, boost::hash<std::pair<node_t, node_t>> > m_edges;
std::unordered_map<std::pair<node_t, node_t>, std::vector<timestamp_t>, hash_pair> m_edges;
public:
StaticGraph() {};
StaticGraph(const std::vector<TEdge>& temporal_graph)
{
for(auto& edge : temporal_graph)
{
std::pair<node_t, node_t> srcdst = std::make_pair(edge.src, edge.dst);
if(m_edges.find(srcdst) != m_edges.end())
{
m_edges.at(srcdst).push_back(edge.tim);
}
else
{
std::vector<timestamp_t> mytime{edge.tim};
m_edges.insert(std::make_pair(srcdst, mytime));
}
}
};
long long getNumberOfEdges() { return m_edges.size(); };
std::vector<std::pair<std::pair<node_t, node_t>, std::vector<timestamp_t>> > getFullVector()
{
std::vector<std::pair<std::pair<node_t, node_t>, std::vector<timestamp_t>> > toreturn;
for(auto& entry : m_edges)
{
toreturn.push_back(entry);
}
for(auto& element : toreturn)
{
std::sort(element.second.begin(), element.second.end());
}
return toreturn;
}
};
class Permutation{
private:
std::random_device m_rd;
std::mt19937 m_g;
public:
Permutation() : m_g{m_rd()} {};
void GetPermutation(std::vector<int>& input){
std::shuffle(input.begin(), input.end(), m_g);
}
};
#endif // utiilities_h
| 29.407407 | 186 | 0.690596 | [
"object",
"vector"
] |
97ad6dea99db048760aa568676eeb9514305216d | 4,547 | c | C | src/lq-wrkTime.c | LooUQ/LooUQ-DeviceCommon | 80eaa2f99734be81d82a4982dd2d98a96815ed5d | [
"MIT"
] | null | null | null | src/lq-wrkTime.c | LooUQ/LooUQ-DeviceCommon | 80eaa2f99734be81d82a4982dd2d98a96815ed5d | [
"MIT"
] | null | null | null | src/lq-wrkTime.c | LooUQ/LooUQ-DeviceCommon | 80eaa2f99734be81d82a4982dd2d98a96815ed5d | [
"MIT"
] | null | null | null | /******************************************************************************
* \file lq-wrkTime.c
* \author Greg Terrell
* \license MIT License
*
* Copyright (c) 2020, 2021 LooUQ Incorporated.
*
* 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.
*
******************************************************************************
* LooUQ LQCloud Client Work-Time Services
*****************************************************************************/
#define _DEBUG 0 // set to non-zero value for PRINTF debugging output,
// debugging output options // LTEm1c will satisfy PRINTF references with empty definition if not already resolved
#if defined(_DEBUG) && _DEBUG > 0
asm(".global _printf_float"); // forces build to link in float support for printf
#if _DEBUG == 1
#define SERIAL_DBG 1 // enable serial port output using devl host platform serial, 1=wait for port
#elif _DEBUG == 2
#include <jlinkRtt.h> // output debug PRINTF macros to J-Link RTT channel
#endif
#else
#define PRINTF(c_, f_, ...) ;
#endif
#include "lq-wrkTime.h"
#define MILLIS() millis()
/**
* \brief Initialize a workSchedule object (struct) to track periodic events at regular intervals.
*
* \param intervalMillis [in] - Interval period in milliseconds.
*/
wrkTime_t wrkTime_create(unsigned long intervalMillis)
{
wrkTime_t schedObj;
schedObj.enabled = true;
schedObj.period = intervalMillis;
schedObj.lastAtMillis = MILLIS();
return schedObj;
}
/**
* \brief Reset a workSchedule object's internal timekeeping to now. If invoked mid-interval, sets the next event to a full-interval duration.
*
* \param schedObj [in] - workSchedule object (struct) to reset.
*/
void wrkTime_start(wrkTime_t *schedObj)
{
schedObj->enabled = true;
schedObj->lastAtMillis = MILLIS();
}
/**
* \brief Reset a workSchedule object's internal timekeeping to now. If invoked mid-interval, sets the next event to a full-interval duration.
*
* \param schedObj [in] - workSchedule object (struct) to reset.
*/
void wrkTime_stop(wrkTime_t *schedObj)
{
schedObj->enabled = false;
schedObj->lastAtMillis = 0;
}
/**
* \brief Query wrkTime object to see if running.
*
* \param schedObj [in] - workSchedule object (struct) to reset.
*
* \return true if timer running
*/
bool wrkTime_isRunning(wrkTime_t *schedObj)
{
return schedObj->enabled;
}
/**
* \brief Tests if the internal timing for a workSchedule object has completed and it is time to do the work.
*
* \param schedObj [in] - workSchedule object (struct) to test.
*/
bool wrkTime_doNow(wrkTime_t *schedObj)
{
if (schedObj->enabled)
{
unsigned long now = MILLIS();
if (now - schedObj->lastAtMillis > schedObj->period)
{
// schedObj->enabled = (schedObj->schedType != wrkTimeType_timer);
schedObj->lastAtMillis = now;
return true;
}
}
return false;
}
/**
* \brief Simple helper for testing a start time to see if a duration has been satisfied.
*
* \param startTime [in] - A point in time (measured by millis)
* \param reqdDuration [in] - A target elapsed time in milliseconds
*
* \returns true if the reqdDuration has been reached, returns false if the startTime has not been set (=0)
*/
bool wrkTime_isElapsed(millisTime_t startTime, millisDuration_t reqdDuration)
{
return (startTime) ? millis() - startTime > reqdDuration : false;
}
| 33.932836 | 142 | 0.661755 | [
"object"
] |
97b3c34619ae576bff5269f10bd8fc67f34da44a | 8,053 | h | C | Trash/sandbox/hmm/ghmm-0.9-rc3/ghmm/mes.h | ruslankuzmin/julia | 2ad5bfb9c9684b1c800e96732a9e2f1e844b856f | [
"BSD-3-Clause"
] | 7 | 2017-03-13T17:32:26.000Z | 2021-09-27T16:51:22.000Z | Trash/sandbox/hmm/ghmm-0.9-rc3/ghmm/mes.h | ruslankuzmin/julia | 2ad5bfb9c9684b1c800e96732a9e2f1e844b856f | [
"BSD-3-Clause"
] | 1 | 2021-05-29T19:54:02.000Z | 2021-05-29T19:54:52.000Z | Trash/sandbox/hmm/ghmm-0.9-rc3/ghmm/mes.h | ruslankuzmin/julia | 2ad5bfb9c9684b1c800e96732a9e2f1e844b856f | [
"BSD-3-Clause"
] | 25 | 2016-10-18T03:31:44.000Z | 2020-12-29T13:23:10.000Z | /*******************************************************************************
*
* This file is part of the General Hidden Markov Model Library,
* GHMM version __VERSION__, see http://ghmm.org
*
* Filename: ghmm/ghmm/mes.h
* Authors: Frank Nuebel, Benjamin Georgi, Janne Grunau
*
* Copyright (C) 1998-2004 Alexander Schliep
* Copyright (C) 1998-2001 ZAIK/ZPR, Universitaet zu Koeln
* Copyright (C) 2002-2004 Max-Planck-Institut fuer Molekulare Genetik,
* Berlin
*
* Contact: schliep@ghmm.org
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the Free
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*
* This file is version $Revision: 1713 $
* from $Date: 2006-10-16 10:06:28 -0400 (Mon, 16 Oct 2006) $
* last change by $Author: grunau $.
*
*******************************************************************************/
#ifndef GHMM_MES_H
#define GHMM_MES_H
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include "ghmm_internals.h"
#ifdef __cplusplus
extern "C" {
#endif /*__cplusplus*/
/**
@name Help functions concerning memory and small calculations.
*/
#define MES_0_PTR 0
#define MES_NEG_ARG 1
#define MES_BIG_ARG 2
#define MES_0_ARG 3
#define MES_FALSE_ARG 4
#define MES_FLAG_TIME 1
#define MES_FLAG_WIN 4
#define MES_FLAG_FILE 16
#define MES_FLAG_FILE_WIN ( MES_FLAG_FILE | MES_FLAG_WIN )
#define MES_FLAG_TIME_WIN ( MES_FLAG_TIME | MES_FLAG_FILE | MES_FLAG_WIN )
#define MES_MODUL_INFO "(" __DATE__ ":" __FILE__ ")"
#define MES_PROC_INFO "(" __DATE__ ":" __FILE__ ":" CUR_PROC ")"
#define MES_WIN MES_FLAG_WIN, -1, NULL, NULL
#define MES_FILE MES_FLAG_FILE, -1, NULL, NULL
#define MES_TIME (MES_FLAG_TIME | MES_FLAG_FILE), -1, NULL, NULL
#define MES_FILE_WIN MES_FLAG_FILE_WIN, -1, NULL, NULL
#define MES_TIME_WIN MES_FLAG_TIME_WIN, -1, NULL, NULL
#define MES_PROT_WIN MES_FLAG_WIN, __LINE__ ,MES_PROC_INFO, CUR_PROC
#define MES_PROT_FILE MES_FLAG_FILE, __LINE__ ,MES_PROC_INFO, CUR_PROC
#define MES_PROT MES_FLAG_FILE_WIN, __LINE__ ,MES_PROC_INFO, CUR_PROC
#define MES_PROT_TIME MES_FLAG_TIME_WIN, __LINE__ ,MES_PROC_INFO, CUR_PROC
/* stuff from sys.h */
#if defined(_WIN32)
# define getthreadid() GetCurrentThreadId()
# define getprocessid() GetCurrentProcessId()
#else
# include <unistd.h>
# define getthreadid() 1
# define getprocessid() 1
#endif /* defined(WIN32) */
/* end stuff from sys.h */
/* stuff from stdmacro.h */
#ifndef strtoupper
#define strtoupper(str) if(1){char*p=(str);if(p)for(;*p;p++)*p=toupper(*p);}else
#endif
#ifndef strtolower
#define strtolower(str) if(1){char*p=(str);if(p)for(;*p;p++)*p=tolower(*p);}else
#endif
#ifndef m_max
#define m_max( a, b ) ( ( (a) > (b) ) ? (a) : (b) )
#endif
#ifndef m_min
#define m_min( a, b ) ( ( (a) < (b) ) ? (a) : (b) )
#endif
#ifndef m_int
#define m_int( x ) ( ((x)>=0) ? (int)((x)+0.5) : (int)((x)-0.5) )
#endif
#ifndef m_integer
#define m_integer( x ) ( ((x)>=0) ? floor(x) : ceil(x) )
#endif
#ifndef m_frac
#define m_frac( x ) ( (x) - m_integer(x) )
#endif
#ifndef m_sqr
#define m_sqr( x ) ( (x)*(x) )
#endif
#ifndef m_bitget
#define m_bitget( BitStr, Bit ) (((char*)(BitStr))[(Bit)>>3] & (1<<((Bit)&7)) )
#endif
#ifndef m_bitset
#define m_bitset( BitStr, Bit ) (((char*)(BitStr))[(Bit)>>3] |= (1<<((Bit)&7)) )
#endif
#ifndef m_bitclr
#define m_bitclr( BitStr, Bit ) (((char*)(BitStr))[(Bit)>>3] &= ~(1<<((Bit)&7)))
#endif
#ifndef m_bitinv
#define m_bitinv( BitStr, Bit ) (((char*)(BitStr))[(Bit)>>3] ^= ~(1<<((Bit)&7)))
#endif
/* */
#ifndef m_free
#define m_free( p ) {if(p) {free(p); (p) = NULL;} else {GHMM_LOG(LCRITIC, "Attempted m_free on NULL pointer. Bad program, BAD! No cookie for you."); /*abort();*/}}
#endif
#ifndef m_strlen
#define m_strlen( src, cnt ) ( (src) ? ( (cnt<0) ? strlen(src) : cnt) : -1 )
#endif
#ifndef m_align
#define m_align( a, n ) ( ((n)&&((a)%(n))) ? ((a)+(n)-((a)%(n))) : (a) )
#endif
#ifndef m_ispow2
#define m_ispow2( n ) ( !((n)&((n)-1)) )
#endif
#ifndef m_gauss
#define m_gauss( a, n ) ( ((n)&&((a)%(n))) ? ((a)-((a)%(n))) : (a) )
#endif
#ifndef m_approx
#define m_approx( a, b, eps ) ( ( (a) - (eps) <= (b) && (a) + (eps) >= (b) ) ? 1 : 0)
#endif
#ifndef m_ptr
#define m_ptr( p, offs ) ( (void*)((char*)(p)+(offs)) )
#endif
#ifndef m_memset
#define m_memset(dst, c, entries) memset( (dst), (c), sizeof(*(dst))*(entries))
#endif
#ifndef m_memcpy
#define m_memcpy(dst, src, entries) memcpy((dst),(src),sizeof(*(dst))*(entries))
#endif
#ifndef m_fclose
#define m_fclose( fp ) \
if((fp) && (fp) - stdout) { fclose(fp); (fp) = NULL; } else
#endif
#ifndef m_fread
#define m_fread( fp, dest, cnt ) ighmm_mes_fread((fp),(dest),(cnt)*sizeof(*(dest)) )
#endif
#ifndef m_fwrite
#define m_fwrite( fp, src, cnt ) ighmm_mes_fwrite((fp),(src),(cnt)*sizeof(*(src)) )
#endif
/* neu fuer hmm: ungefaehr gleiche Werte, (BW) */
#ifndef m_approx
#define m_approx( a, b, eps ) ( ( (a) - (eps) <= (b) && (a) + (eps) >= (b) ) ? 1 : 0)
#endif
/* end of things from stdmacro.h */
/**
*/
#define mes_check_ptr(arg, call) \
if (!(arg)) { ighmm_mes_err( #arg, MES_0_PTR, MES_PROC_INFO ); call; }
/**
*/
#define mes_check_bnd( arg, bnd, call ) \
if((arg) > (bnd)){ ighmm_mes_err( #arg, MES_BIG_ARG, MES_PROC_INFO ); call;} else
/**
*/
#define mes_check_0( arg, call ) \
if(!(arg)) { ighmm_mes_err( #arg, MES_0_ARG, MES_PROC_INFO ); call;} else
/**
*/
#define mes_check_neg( arg, call ) \
if((arg)<0){ ighmm_mes_err( #arg, MES_NEG_ARG, MES_PROC_INFO );call;} else
/**
*/
#define mes_check_expr( arg, call ) \
if(!(arg)){ ighmm_mes_err( #arg, MES_FALSE_ARG, MES_PROC_INFO );call;} else
/**
*/
#define mes_file( txt ) ighmm_mes_smart( MES_FLAG_FILE, txt, -1 )
/**
*/
#define mes_file_win( txt ) ighmm_mes_smart( MES_FLAG_FILE_WIN, txt, -1 )
/**
*/
#define mes_win( txt ) ighmm_mes_smart( MES_FLAG_WIN, txt, -1 )
/**
*/
char *ighmm_mes_get_std_path (void);
/**
*/
void ighmm_mes (int flags, int line, char *xproc, char *proc, char *format, ...);
/**
*/
void ighmm_mes_smart (int flags, const char *txt, int bytes);
/**
*/
int ighmm_mes_ability (int on);
/**
*/
void ighmm_mes_err (char *txt, int error_nr, char *proc_info);
/**
*/
void ighmm_mes_exit (void);
/**
*/
void ighmm_mes_init (char *logfile, void (*winfct) (const char *), int argc,
char *argv[]);
/**
*/
void ighmm_mes_init_args (int argc, char *argv[]);
/**
*/
void ighmm_mes_init_logfile (char *file_name);
/**
*/
void ighmm_mes_init_winfct (void (*win_fct) (const char *));
/**
*/
void ighmm_mes_time (void);
/**
*/
void ighmm_mes_va (int flags, int line, char *xproc, char *proc, char *format,
va_list args);
/**
*/
int ighmm_mes_win_ability (int on);
/**
*/
void *ighmm_calloc (int bytes);
/**
*/
FILE *ighmm_mes_fopen (const char *filename, char *attribute_string);
/**
*/
void *ighmm_malloc (int bytes);
/**
*/
int ighmm_realloc (void **mem, int bytes);
#ifdef __cplusplus
}
#endif /*__cplusplus*/
#endif /* GHMM_MES_H */
| 27.67354 | 164 | 0.604619 | [
"model"
] |
97b8042d8d523f04942caed89d6fdce02598843a | 8,957 | c | C | jorm/jorm_unit.c | ganeshkamath89/redfish | e42d67d2f8be8b4dbfe57cb756f24a1b3deaadd7 | [
"Apache-2.0"
] | 4 | 2016-09-18T09:03:37.000Z | 2018-07-17T08:49:46.000Z | jorm/jorm_unit.c | ganeshkamath89/redfish | e42d67d2f8be8b4dbfe57cb756f24a1b3deaadd7 | [
"Apache-2.0"
] | null | null | null | jorm/jorm_unit.c | ganeshkamath89/redfish | e42d67d2f8be8b4dbfe57cb756f24a1b3deaadd7 | [
"Apache-2.0"
] | 5 | 2016-09-18T09:03:39.000Z | 2018-10-12T05:01:19.000Z | /*
* Copyright 2011-2012 the Redfish authors
*
* 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.
*/
#include "jorm/jorm_unit.h"
#include "util/test.h"
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define JORM_CUR_FILE "jorm/jorm_unit.jorm"
#include "jorm/jorm_generate_body.h"
#undef JORM_CUR_FILE
#define TEST2_NUM_ABBIE 3
static int test_jorm_init(void)
{
struct bob *b1 = JORM_INIT_bob();
EXPECT_NOT_EQ(b1, NULL);
EXPECT_EQ(b1->a, JORM_INVAL_INT);
EXPECT_EQ(b1->b, JORM_INVAL_DOUBLE);
EXPECT_EQ(b1->c, JORM_INVAL_STR);
EXPECT_EQ(b1->d, JORM_INVAL_NESTED);
EXPECT_EQ(b1->e, JORM_INVAL_BOOL);
JORM_FREE_bob(b1);
return 0;
}
static int test1(void)
{
int ret;
const char *str;
struct json_object *jo = NULL;
struct abbie *my_abbie = JORM_INIT_abbie();
my_abbie->a = 456;
jo = JORM_TOJSON_abbie(my_abbie);
if (!jo) {
ret = EXIT_FAILURE;
goto done;
}
str = json_object_to_json_string(jo);
if (strcmp(str, "{ \"a\": 456 }") != 0) {
ret = EXIT_FAILURE;
goto done;
}
ret = 0;
done:
if (jo) {
json_object_put(jo);
jo = NULL;
}
free(my_abbie);
return ret;
}
static int test2(void)
{
int i, ret;
const char *str;
struct json_object *jo = NULL;
struct abbie *my_abbie[TEST2_NUM_ABBIE] = { 0 };
struct bob *my_bob = NULL;
EXPECT_NOT_EQ(my_abbie, NULL);
for (i = 0; i < TEST2_NUM_ABBIE; ++i) {
my_abbie[i] = JORM_INIT_abbie();
EXPECT_NOT_EQ(my_abbie[i], NULL);
my_abbie[i]->a = i;
}
my_bob = JORM_INIT_bob();
EXPECT_NOT_EQ(my_bob, NULL);
my_bob->a = 1;
my_bob->b = 2.5;
my_bob->c = strdup("hi there");
EXPECT_NOT_EQ(my_bob->c, NULL);
my_bob->d = my_abbie[0];
my_bob->e = 0;
my_bob->f = calloc(3, sizeof(struct abbie*));
EXPECT_NOT_EQ(my_bob->f, NULL);
my_bob->f[0] = my_abbie[1];
my_bob->f[1] = my_abbie[2];
my_bob->f[2] = NULL;
my_bob->extra_data = 404;
my_bob->g = JORM_INIT_carrie();
EXPECT_NOT_EQ(my_bob->g, NULL);
my_bob->h = calloc(3, sizeof(char*));
my_bob->h[0] = strdup("fee");
my_bob->h[1] = strdup("fie");
EXPECT_NOT_EQ(my_bob->g, NULL);
my_bob->g->x = 101;
my_bob->g->y = 5.0;
jo = JORM_TOJSON_bob(my_bob);
if (!jo) {
ret = EXIT_FAILURE;
goto done;
}
str = json_object_to_json_string(jo);
if (strcmp(str, "{ \"a\": 1, \"b\": 2.500000, \"c\": \"hi there\", "
"\"d\": { \"a\": 0 }, \"e\": false, \"f\": [ { \"a\": 1 }, "
"{ \"a\": 2 } ], \"x\": 101, \"y\": 5.000000, "
"\"h\": [ \"fee\", \"fie\" ] }") != 0)
{
fprintf(stderr, "got str = '%s'\n", str);
ret = EXIT_FAILURE;
goto done;
}
ret = 0;
done:
if (jo) {
json_object_put(jo);
jo = NULL;
}
if (my_bob)
JORM_FREE_bob(my_bob);
return ret;
}
static int test3(void)
{
size_t i;
int ret;
char err[512] = { 0 };
const char in_str[] = "{ \"a\": 1, \"b\": 2.500000, "
"\"c\": \"hi there\", \"d\": { \"a\": 0 }, "
"\"e\": false, \"f\": [ { \"a\": 1 }, "
"{ \"a\": 2 } ], \"x\" : 5, \"y\" : 1.5, "
"\"h\" : [ \"wow\" ] }";
int expected_array_val[] = { 1, 2, 6 };
struct json_object* jo = NULL;
struct bob *my_bob = NULL;
struct abbie* final_abbie;
jo = parse_json_string(in_str, err, sizeof(err));
if (err[0]) {
fprintf(stderr, "parse_json_string error: %s\n", err);
ret = EXIT_FAILURE;
goto done;
}
my_bob = JORM_FROMJSON_bob(jo);
if (!my_bob) {
fprintf(stderr, "JORM_FROMJSON: OOM\n");
ret = EXIT_FAILURE;
goto done;
}
ret = 0;
EXPECT_NONZERO(my_bob->a == 1);
EXPECT_NONZERO(my_bob->b == 2.5);
EXPECT_ZERO(my_bob->extra_data);
final_abbie = JORM_OARRAY_APPEND_abbie(&my_bob->f);
EXPECT_NOT_EQ(final_abbie, NULL);
final_abbie->a = 6;
for (i = 0; i < sizeof(expected_array_val) /
sizeof(expected_array_val[0]); ++i) {
EXPECT_EQ(my_bob->f[i]->a, expected_array_val[i]);
}
EXPECT_EQ(my_bob->g->x, 5);
EXPECT_EQ(my_bob->g->y, 1.5);
EXPECT_NOT_EQ(my_bob->h, JORM_INVAL_ARRAY);
EXPECT_NOT_EQ(my_bob->h[0], NULL);
EXPECT_EQ(my_bob->h[1], NULL);
EXPECT_ZERO(strcmp(my_bob->h[0], "wow"));
done:
if (jo) {
json_object_put(jo);
jo = NULL;
}
if (my_bob) {
JORM_FREE_bob(my_bob);
my_bob = NULL;
}
return ret;
}
static int test4(void)
{
struct bob *b1 = JORM_INIT_bob();
struct bob *b2 = JORM_INIT_bob();
struct bob *b3 = JORM_INIT_bob();
struct abbie **abbie_arr = NULL;
EXPECT_NOT_EQ(b1, NULL);
EXPECT_NOT_EQ(b2, NULL);
EXPECT_NOT_EQ(b3, NULL);
EXPECT_EQ(b3->a, JORM_INVAL_INT);
b1->a = 101;
EXPECT_ZERO(JORM_COPY_bob(b1, b3));
EXPECT_EQ(b3->a, 101);
b2->a = JORM_INVAL_INT;
b2->b = 50;
b2->d = JORM_INIT_abbie();
b2->d->a = 9000;
EXPECT_ZERO(JORM_COPY_bob(b2, b3));
EXPECT_EQ(b3->b, 50);
EXPECT_NOT_EQ(b3->d, NULL);
EXPECT_EQ(b3->d->a, 9000);
EXPECT_EQ(b3->a, 101);
b1->f = calloc(3, sizeof(struct abbie*));
EXPECT_NOT_EQ(b1->f, NULL);
b1->f[0] = JORM_INIT_abbie();
EXPECT_NOT_EQ(b1->f[0], NULL);
b1->f[1] = JORM_INIT_abbie();
EXPECT_NOT_EQ(b1->f[1], NULL);
b1->f[2] = NULL;
b1->f[0]->a = 100;
b1->f[1]->a = 200;
EXPECT_ZERO(JORM_COPY_bob(b1, b3));
EXPECT_NOT_EQ(b3->f, NULL);
EXPECT_NOT_EQ(b3->f[0], NULL);
EXPECT_EQ(b3->f[0]->a, 100);
EXPECT_NOT_EQ(b3->f[1], NULL);
EXPECT_EQ(b3->f[1]->a, 200);
EXPECT_EQ(b3->f[2], NULL);
abbie_arr = JORM_OARRAY_COPY_abbie(b3->f);
EXPECT_NOT_EQ(abbie_arr, NULL);
EXPECT_NOT_EQ(abbie_arr[0], NULL);
EXPECT_EQ(abbie_arr[0]->a, 100);
EXPECT_NOT_EQ(abbie_arr[1], NULL);
EXPECT_EQ(abbie_arr[1]->a, 200);
EXPECT_EQ(abbie_arr[2], NULL);
JORM_OARRAY_FREE_abbie(&abbie_arr);
JORM_FREE_bob(b1);
JORM_FREE_bob(b2);
JORM_FREE_bob(b3);
return 0;
}
static int test5(void)
{
int ret;
char acc[512] = { 0 }, err[512] = { 0 };
struct json_object *jo = NULL;
const char in_str[] = "{ \"a\": \"1\", \"b\": 2.500000, "
"\"c\": 5.0, \"d\": { \"a\": false }, "
"\"e\": false, \"f\": [ { \"a\": 1 }, "
"{ \"a\": 2 } ], \"x\" : 5, \"y\" : 1 }";
const char in_str2[] = "{ \"d\": false, \"f\" : 1 }";
const char in_str3[] = "{ \"f\" : [ { \"a\" : 2.5 }, 1 ] }";
jo = parse_json_string(in_str, err, sizeof(err));
if (err[0]) {
fprintf(stderr, "parse_json_string error: %s\n", err);
ret = EXIT_FAILURE;
goto done;
}
JORM_TYCHECK_bob(jo, acc, sizeof(acc), err, sizeof(err));
EXPECT_ZERO(strcmp(err, "WARNING: ignoring field \"a\" because "
"it has type string, but it should have type int.\n"
"WARNING: ignoring field \"c\" because it has type double, "
"but it should have type string.\n"
"WARNING: ignoring field \"d/a\" because it has type boolean, "
"but it should have type int.\n"
"WARNING: ignoring field \"y\" because it has type int, "
"but it should have type double.\n"));
acc[0] = '\0';
err[0] = '\0';
json_object_put(jo);
jo = parse_json_string(in_str2, err, sizeof(err));
if (err[0]) {
fprintf(stderr, "parse_json_string2 error: %s\n", err);
ret = EXIT_FAILURE;
goto done;
}
JORM_TYCHECK_bob(jo, acc, sizeof(acc), err, sizeof(err));
EXPECT_ZERO(strcmp(err, "WARNING: ignoring field \"d\" because "
"it has type boolean, but it should have type object.\n"
"WARNING: ignoring field \"f\" because it has type "
"int, but it should have type array.\n"));
acc[0] = '\0';
err[0] = '\0';
json_object_put(jo);
jo = parse_json_string(in_str3, err, sizeof(err));
if (err[0]) {
fprintf(stderr, "parse_json_string3 error: %s\n", err);
ret = EXIT_FAILURE;
goto done;
}
JORM_TYCHECK_bob(jo, acc, sizeof(acc), err, sizeof(err));
EXPECT_ZERO(strcmp(err, "WARNING: ignoring field \"f[0]/a\" because "
"it has type double, but it should have type int.\n"
"WARNING: ignoring field \"f[1]\" because "
"it has type array, but it should have type int.\n"));
ret = 0;
done:
if (jo)
json_object_put(jo);
return ret;
}
static int test_jorm_array_manipulations(void)
{
struct bob **a1 = NULL, **a2 = NULL;
struct bob *b, *b2, *b3;
b = JORM_OARRAY_APPEND_bob(&a1);
EXPECT_NOT_EQ(b, NULL);
EXPECT_EQ(b->a, JORM_INVAL_INT);
EXPECT_NOT_EQ(a1[0], NULL);
JORM_OARRAY_REMOVE_bob(&a1, b);
EXPECT_EQ(a1[0], NULL);
b = JORM_OARRAY_APPEND_bob(&a2);
b->a = 1;
b2 = JORM_OARRAY_APPEND_bob(&a2);
b2->a = 2;
b3 = JORM_OARRAY_APPEND_bob(&a2);
b3->a = 3;
JORM_OARRAY_REMOVE_bob(&a2, b2);
EXPECT_EQ(a2[0], b);
EXPECT_EQ(a2[1], b3);
EXPECT_EQ(a2[2], NULL);
JORM_OARRAY_FREE_bob(&a1);
JORM_OARRAY_FREE_bob(&a2);
return 0;
}
int main(void)
{
EXPECT_ZERO(test_jorm_init());
EXPECT_ZERO(test1());
EXPECT_ZERO(test2());
EXPECT_ZERO(test3());
EXPECT_ZERO(test4());
EXPECT_ZERO(test5());
EXPECT_ZERO(test_jorm_array_manipulations());
return EXIT_SUCCESS;
}
| 25.738506 | 75 | 0.639611 | [
"object"
] |
97d65bdd01396f4bd319fdabe030dfb5332c68d9 | 7,311 | h | C | MMOCoreORB/src/server/zone/objects/manufactureschematic/craftingvalues/CraftingValues.h | V-Fib/FlurryClone | 40e0ca7245ec31b3815eb6459329fd9e70f88936 | [
"Zlib",
"OpenSSL"
] | 18 | 2017-02-09T15:36:05.000Z | 2021-12-21T04:22:15.000Z | MMOCoreORB/src/server/zone/objects/manufactureschematic/craftingvalues/CraftingValues.h | V-Fib/FlurryClone | 40e0ca7245ec31b3815eb6459329fd9e70f88936 | [
"Zlib",
"OpenSSL"
] | 61 | 2016-12-30T21:51:10.000Z | 2021-12-10T20:25:56.000Z | MMOCoreORB/src/server/zone/objects/manufactureschematic/craftingvalues/CraftingValues.h | V-Fib/FlurryClone | 40e0ca7245ec31b3815eb6459329fd9e70f88936 | [
"Zlib",
"OpenSSL"
] | 71 | 2017-01-01T05:34:38.000Z | 2022-03-29T01:04:00.000Z | /*
Copyright <SWGEmu>
See file COPYING for copying conditions.*/
#ifndef CRAFTINGVALUES_H_
#define CRAFTINGVALUES_H_
#include "templates/crafting/ValuesMap.h"
#include "engine/engine.h"
namespace server {
namespace zone {
namespace objects {
namespace manufactureschematic {
class ManufactureSchematic;
}
}
}
}
using namespace server::zone::objects::manufactureschematic;
namespace server {
namespace zone {
namespace objects {
namespace creature {
class CreatureObject;
}
}
}
}
using namespace server::zone::objects::creature;
namespace server {
namespace zone {
namespace objects {
namespace manufactureschematic {
namespace craftingvalues {
class CraftingValues : public Serializable, public Logger {
ValuesMap experimentalValuesMap;
Vector<String> valuesToSend;
bool doHide;
ManagedWeakReference<ManufactureSchematic*> schematic;
ManagedWeakReference<CreatureObject*> player;
VectorMap<String, bool> slots;
public:
enum {
NORMAL = 1,
HIDDEN = 2
};
public:
CraftingValues();
CraftingValues(const CraftingValues& values);
CraftingValues(const ValuesMap& values);
~CraftingValues();
void setManufactureSchematic(ManufactureSchematic* manu);
ManufactureSchematic* getManufactureSchematic();
void setPlayer(CreatureObject* play);
CreatureObject* getPlayer();
// Experimental Titles
void addExperimentalProperty(const String& title, const String& subtitle,
const float min, const float max, const int precision,
const bool filler, const int combine) {
experimentalValuesMap.addExperimentalProperty(title, subtitle, min, max, precision, filler, combine);
}
const String& getExperimentalPropertyTitle(const String& subtitle) const {
return experimentalValuesMap.getExperimentalPropertyTitle(subtitle);
}
const String& getExperimentalPropertyTitle(const int i) const {
return experimentalValuesMap.getExperimentalPropertyTitle(i);
}
const String& getVisibleExperimentalPropertyTitle(const int i) const {
return experimentalValuesMap.getVisibleExperimentalPropertyTitle(i);
}
const String& getExperimentalPropertySubtitlesTitle(const int i) const {
return experimentalValuesMap.getExperimentalPropertySubtitlesTitle(i);
}
const String& getExperimentalPropertySubtitle(const int i) const {
return experimentalValuesMap.getExperimentalPropertySubtitle(i);
}
const String& getExperimentalPropertySubtitle(const String title, const int i) const {
return experimentalValuesMap.getExperimentalPropertySubtitle(title, i);
}
int getExperimentalPropertySubtitleSize() const {
return experimentalValuesMap.getExperimentalPropertySubtitleSize();
}
int getExperimentalPropertySubtitleSize(const String title) const {
return experimentalValuesMap.getExperimentalPropertySubtitleSize(title);
}
bool hasProperty(const String& attribute) const {
return experimentalValuesMap.hasProperty(attribute);
}
bool isHidden(const String& attribute) const {
return experimentalValuesMap.isHidden(attribute);
}
void setHidden(const String& attribute) {
experimentalValuesMap.setHidden(attribute);
}
void unsetHidden(const String& attribute) {
experimentalValuesMap.unsetHidden(attribute);
}
short getCombineType(const String& attribute) const {
return experimentalValuesMap.getCombineType(attribute);
}
void setCurrentValue(const String& attribute, const float value) {
experimentalValuesMap.setCurrentValue(attribute, value);
}
void setCurrentValue(const String& attribute, const float value, const float min, const float max) {
experimentalValuesMap.setCurrentValue(attribute, value, min, max);
}
float getCurrentValue(const String& attribute) const {
return experimentalValuesMap.getCurrentValue(attribute);
}
float getCurrentValue(const int i) const {
return experimentalValuesMap.getCurrentValue(i);
}
void lockValue(const String& attribute) {
experimentalValuesMap.lockValue(attribute);
}
void unlockValue(const String& attribute) {
experimentalValuesMap.unlockValue(attribute);
}
void resetValue(const String& attribute) {
experimentalValuesMap.resetValue(attribute);
}
void setCurrentPercentage(const String& subtitle, const float value) {
experimentalValuesMap.setCurrentPercentage(subtitle, value);
}
void setCurrentPercentage(const String& subtitle, const float value, const float max) {
experimentalValuesMap.setCurrentPercentage(subtitle, value, max);
}
float getCurrentPercentage(const String& attribute) const {
return experimentalValuesMap.getCurrentPercentage(attribute);
}
float getCurrentPercentage(const int i) const {
return experimentalValuesMap.getCurrentPercentage(i);
}
float getCurrentVisiblePercentage(const String title) const {
return experimentalValuesMap.getCurrentVisiblePercentage(title);
}
void setMaxPercentage(const String& attribute, const float value) {
experimentalValuesMap.setMaxPercentage(attribute, value);
}
float getMaxPercentage(const String& attribute) const {
return experimentalValuesMap.getMaxPercentage(attribute);
}
float getMaxPercentage(const int i) const {
return experimentalValuesMap.getMaxPercentage(i);
}
float getMaxVisiblePercentage(const int i) const {
return experimentalValuesMap.getMaxVisiblePercentage(i);
}
float getMinValue(const String& attribute) const {
return experimentalValuesMap.getMinValue(attribute);
}
float getMaxValue(const String& attribute) const {
return experimentalValuesMap.getMaxValue(attribute);
}
void setMinValue(const String& attribute, const float value) {
experimentalValuesMap.setMinValue(attribute, value);
}
void setMaxValue(const String& attribute, const float value) {
experimentalValuesMap.setMaxValue(attribute, value);
}
int getPrecision(const String& attribute) const {
return experimentalValuesMap.getPrecision(attribute);
}
void setPrecision(const String& attribute, const int precision) {
experimentalValuesMap.setPrecision(attribute, precision);
}
void recalculateValues(bool initial);
String toString();
inline int getExperimentalPropertyTitleSize() const {
return experimentalValuesMap.size();
}
inline void setSlot(const String& value, bool filled) {
slots.put(value, filled);
}
inline void clearSlots() {
slots.removeAll();
}
inline bool hasSlotFilled(const String& name) const {
if (!slots.contains(name))
return false;
return slots.get(name);
}
inline int getVisibleExperimentalPropertyTitleSize() const {
return experimentalValuesMap.getVisibleExperimentalPropertyTitleSize();
}
inline int getSubtitleCount() const {
return experimentalValuesMap.getSubtitleCount();
}
inline int getValuesToSendSize() const {
return valuesToSend.size();
}
inline int getTitleLine(const String& title) const {
return experimentalValuesMap.getTitleLine(title);
}
const String& getValuesToSend(const int i) const {
return valuesToSend.get(i);
}
float getAttributeAndValue(const String& attribute, const int i) const {
String attributeName = getExperimentalPropertySubtitle(i);
return getCurrentValue(attributeName);
}
// Clear
inline void clear() {
valuesToSend.removeAll();
}
void clearAll();
};
}
}
}
}
}
using namespace server::zone::objects::manufactureschematic::craftingvalues;
#endif /*CRAFTINGVALUES_H_*/
| 25.210345 | 103 | 0.784845 | [
"vector"
] |
97ef991378c8e99d66375b91ec1d053b894afef7 | 6,380 | h | C | src/include/execution/sql/thread_state_container.h | algebra2k/terrier | 8b6f4b0b0c30dc94411f197e610f634ce0ab5b0b | [
"MIT"
] | 1 | 2019-03-08T18:59:57.000Z | 2019-03-08T18:59:57.000Z | src/include/execution/sql/thread_state_container.h | LiuXiaoxuanPKU/terrier | 35916e9435201016903d8a01e3f587b8edb36f0b | [
"MIT"
] | 34 | 2019-03-21T20:47:59.000Z | 2019-05-17T06:06:46.000Z | src/include/execution/sql/thread_state_container.h | LiuXiaoxuanPKU/terrier | 35916e9435201016903d8a01e3f587b8edb36f0b | [
"MIT"
] | 3 | 2020-11-10T11:06:20.000Z | 2022-03-26T15:30:55.000Z | #pragma once
#include <functional>
#include <memory>
#include <vector>
#include "common/strong_typedef.h"
#include "execution/sql/memory_pool.h"
namespace terrier::execution::sql {
/**
* This class serves as a container for thread-local data required during query
* execution. Users create an instance of this class and call @em Reset() to
* configure it to store thread-local structures of an opaque type with a given
* size.
*
* During query execution, threads can access their thread-local state by
* calling @em AccessThreadStateOfCurrentThread(). Thread-local state is
* constructed lazily upon first access and destroyed on a subsequent call to
* @em Reset() or when the container itself is destroyed.
*/
class EXPORT ThreadStateContainer {
public:
/**
* Function used to initialize a thread's local state upon first use
*/
using InitFn = void (*)(void *, void *);
/**
* Function used to destroy a thread's local state if the container is
* destructed, or if the states are reset.
*/
using DestroyFn = void (*)(void *, void *);
/**
* Function to iterate over all thread-local states in this container.
*/
using IterateFn = void (*)(void *, void *);
/**
* Construct a container for all thread state using the given allocator
* @param memory The memory allocator to use to allocate thread states
*/
explicit ThreadStateContainer(MemoryPool *memory);
/**
* This class cannot be copied or moved.
*/
DISALLOW_COPY_AND_MOVE(ThreadStateContainer);
/**
* Destructor
*/
~ThreadStateContainer();
/**
* Clear all thread local data
*/
void Clear();
/**
* Reset this container to store thread-local state whose size in bytes is
* @em state_size given size, and use the optional initialization and
* destruction functions @em init_fn and @em destroy_fn, respectively, to
* initialize the thread-state exactly once upon first access, and destroy
* the state upon last access. Both functions will be passed in the given
* opaque context object @em ctx as the first argument.
* @param state_size The size in bytes of the state
* @param init_fn The (optional) initialization function to call on first
* access. This is called in the thread that first accesses it.
* @param destroy_fn The (optional) destruction function called to destroy the
* state.
* @param ctx The (optional) context object to pass to both initialization and
* destruction functions.
*/
void Reset(std::size_t state_size, InitFn init_fn, DestroyFn destroy_fn, void *ctx);
/**
* Access the calling thread's thread-local state.
*/
byte *AccessThreadStateOfCurrentThread();
/**
* Access the calling thread's thread-local state and interpret it as the
* templated type.
*/
template <typename T>
T *AccessThreadStateOfCurrentThreadAs() {
return reinterpret_cast<T *>(AccessThreadStateOfCurrentThread());
}
/**
* Collect all thread-local states and store pointers in the output container
* @em container.
* @param container The output container to store the results.
*/
void CollectThreadLocalStates(std::vector<byte *> *container) const;
/**
* Collect an element at offset @em element_offset from all thread-local
* states in this container and store pointers in the output container.
* @param[out] container The output container to store the results.
* @param element_offset The offset of the element in the thread-local state
*/
void CollectThreadLocalStateElements(std::vector<byte *> *container, std::size_t element_offset) const;
/**
* Collect an element at offset @em element_offset from all thread-local
* states, interpret them as @em T, and store pointers in the output
* container.
* NOTE: This is a little inefficient because it will perform two copies: one
* into a temporary vector, and a final copy into the output container.
* Don't use in performance-critical code.
* @tparam T The compile-time type to interpret the state element as
* @param[out] container The output container to store the results.
* @param element_offset The offset of the element in the thread-local state
*/
template <typename T>
void CollectThreadLocalStateElementsAs(std::vector<T *> *container, std::size_t element_offset) const {
std::vector<byte *> tmp;
CollectThreadLocalStateElements(&tmp, element_offset);
container->clear();
container->resize(tmp.size());
for (uint32_t idx = 0; idx < tmp.size(); idx++) {
(*container)[idx] = reinterpret_cast<T *>(tmp[idx]);
}
}
/**
* Iterate over all thread-local states in this container invoking the given
* callback function @em iterate_fn for each such state.
* @param ctx An opaque context object.
* @param iterate_fn The function to call for each state.
*/
void IterateStates(void *ctx, IterateFn iterate_fn) const;
/**
* Apply a function on each thread local state. This is mostly for tests from
* C++.
* @tparam F Functor with signature void(const void*)
* @param fn The function to apply
*/
template <typename T, typename F>
void ForEach(const F &fn) const {
IterateStates(const_cast<F *>(&fn), [](void *ctx, void *raw_state) {
auto *state = reinterpret_cast<T *>(raw_state);
std::invoke(*reinterpret_cast<const F *>(ctx), state);
});
}
private:
/**
* A handle to a single thread's state
*/
class TLSHandle {
public:
// No-arg constructor
TLSHandle();
// Constructor
explicit TLSHandle(ThreadStateContainer *container);
// Destructor
~TLSHandle();
// Thread-local state
byte *State() { return state_; }
private:
// Handle to container
ThreadStateContainer *container_{nullptr};
// Owned memory
byte *state_{nullptr};
};
private:
// Memory allocator
MemoryPool *memory_;
// Size of each thread's state
std::size_t state_size_;
// The function to initialize a thread's local state upon first use
InitFn init_fn_;
// The function to destroy a thread's local state when no longer needed
DestroyFn destroy_fn_;
// An opaque context that passed into the constructor and destructor
void *ctx_;
// PIMPL
struct Impl;
std::unique_ptr<Impl> impl_;
};
} // namespace terrier::execution::sql
| 32.717949 | 105 | 0.695925 | [
"object",
"vector"
] |
97f81e0d79d1e26aa43132bcc174de1676cbdb27 | 19,622 | c | C | app/modules/pixbuf.c | nwf/nodemcu-firmware | 726818ef8bc753114dc22556d75d813a216cbde3 | [
"MIT"
] | 1 | 2017-12-28T17:33:14.000Z | 2017-12-28T17:33:14.000Z | app/modules/pixbuf.c | nwf/nodemcu-firmware | 726818ef8bc753114dc22556d75d813a216cbde3 | [
"MIT"
] | null | null | null | app/modules/pixbuf.c | nwf/nodemcu-firmware | 726818ef8bc753114dc22556d75d813a216cbde3 | [
"MIT"
] | 1 | 2018-03-18T10:55:20.000Z | 2018-03-18T10:55:20.000Z | #include "module.h"
#include "lauxlib.h"
#include <string.h>
#include "pixbuf.h"
#define PIXBUF_METATABLE "pixbuf.buf"
#ifndef MIN
#define MIN(a,b) ((a) < (b) ? (a) : (b))
#endif
#ifndef MAX
#define MAX(a,b) ((a) > (b) ? (a) : (b))
#endif
pixbuf *pixbuf_from_lua_arg(lua_State *L, int arg) {
return luaL_checkudata(L, arg, PIXBUF_METATABLE);
}
pixbuf *pixbuf_opt_from_lua_arg(lua_State *L, int arg) {
return luaL_testudata(L, arg, PIXBUF_METATABLE);
}
static ssize_t posrelat(ssize_t pos, size_t len) {
/* relative string position: negative means back from end */
if (pos < 0)
pos += (ssize_t)len + 1;
return MIN(MAX(pos, 1), len);
}
const size_t pixbuf_channels(pixbuf *p) {
return p->nchan;
}
const size_t pixbuf_size(pixbuf *p) {
return p->npix * p->nchan;
}
/*
* Construct a pixbuf newuserdata using C arguments.
*
* Allocates, so may throw! Leaves new buffer at the top of the Lua stack
* and returns a C pointer.
*/
static pixbuf *pixbuf_new(lua_State *L, size_t leds, size_t chans) {
// Allocate memory
// A crude hack of an overflow check, but unlikely to be reached in practice
if ((leds > 8192) || (chans > 8)) {
luaL_error(L, "pixbuf size limits exeeded");
return NULL; // UNREACHED
}
size_t size = sizeof(pixbuf) + leds * chans;
pixbuf *buffer = (pixbuf*)lua_newuserdata(L, size);
// Associate its metatable
luaL_getmetatable(L, PIXBUF_METATABLE);
lua_setmetatable(L, -2);
// Save led strip size
*(size_t *)&buffer->npix = leds;
*(size_t *)&buffer->nchan = chans;
memset(buffer->values, 0, leds * chans);
return buffer;
}
// Handle a buffer where we can store led values
int pixbuf_new_lua(lua_State *L) {
const int leds = luaL_checkint(L, 1);
const int chans = luaL_checkint(L, 2);
luaL_argcheck(L, leds > 0, 1, "should be a positive integer");
luaL_argcheck(L, chans > 0, 2, "should be a positive integer");
pixbuf_new(L, leds, chans);
return 1;
}
static int pixbuf_concat_lua(lua_State *L) {
pixbuf *lhs = pixbuf_from_lua_arg(L, 1);
pixbuf *rhs = pixbuf_from_lua_arg(L, 2);
luaL_argcheck(L, lhs->nchan == rhs->nchan, 1,
"can only concatenate buffers with same channel count");
size_t osize = lhs->npix + rhs->npix;
if (lhs->npix > osize) {
return luaL_error(L, "size sum overflow");
}
pixbuf *buffer = pixbuf_new(L, osize, lhs->nchan);
memcpy(buffer->values, lhs->values, pixbuf_size(lhs));
memcpy(buffer->values + pixbuf_size(lhs), rhs->values, pixbuf_size(rhs));
return 1;
}
static int pixbuf_channels_lua(lua_State *L) {
pixbuf *buffer = pixbuf_from_lua_arg(L, 1);
lua_pushinteger(L, buffer->nchan);
return 1;
}
static int pixbuf_dump_lua(lua_State *L) {
pixbuf *buffer = pixbuf_from_lua_arg(L, 1);
lua_pushlstring(L, (char*)buffer->values, pixbuf_size(buffer));
return 1;
}
static int pixbuf_eq_lua(lua_State *L) {
bool res;
pixbuf *lhs = pixbuf_from_lua_arg(L, 1);
pixbuf *rhs = pixbuf_from_lua_arg(L, 2);
if (lhs->npix != rhs->npix) {
res = false;
} else if (lhs->nchan != rhs->nchan) {
res = false;
} else {
res = true;
for(size_t i = 0; i < pixbuf_size(lhs); i++) {
if(lhs->values[i] != rhs->values[i]) {
res = false;
break;
}
}
}
lua_pushboolean(L, res);
return 1;
}
static int pixbuf_fade_lua(lua_State *L) {
pixbuf *buffer = pixbuf_from_lua_arg(L, 1);
const int fade = luaL_checkinteger(L, 2);
unsigned direction = luaL_optinteger( L, 3, PIXBUF_FADE_OUT );
luaL_argcheck(L, fade > 0, 2, "fade value should be a strictly positive int");
uint8_t *p = &buffer->values[0];
for (size_t i = 0; i < pixbuf_size(buffer); i++)
{
if (direction == PIXBUF_FADE_OUT)
{
*p++ /= fade;
}
else
{
// as fade in can result in value overflow, an int is used to perform the check afterwards
int val = *p * fade;
*p++ = MIN(255, val);
}
}
return 0;
}
/* Fade an Ixxx-type strip by just manipulating the I bytes */
static int pixbuf_fadeI_lua(lua_State *L) {
pixbuf *buffer = pixbuf_from_lua_arg(L, 1);
const int fade = luaL_checkinteger(L, 2);
unsigned direction = luaL_optinteger( L, 3, PIXBUF_FADE_OUT );
luaL_argcheck(L, fade > 0, 2, "fade value should be a strictly positive int");
uint8_t *p = &buffer->values[0];
for (size_t i = 0; i < buffer->npix; i++, p+=buffer->nchan) {
if (direction == PIXBUF_FADE_OUT) {
*p /= fade;
} else {
int val = *p * fade;
*p++ = MIN(255, val);
}
}
return 0;
}
static int pixbuf_fill_lua(lua_State *L) {
pixbuf *buffer = pixbuf_from_lua_arg(L, 1);
if (buffer->npix == 0) {
goto out;
}
if (lua_gettop(L) != (1 + buffer->nchan)) {
return luaL_argerror(L, 1, "need as many values as colors per pixel");
}
/* Fill the first pixel from the Lua stack */
for (size_t i = 0; i < buffer->nchan; i++) {
buffer->values[i] = luaL_checkinteger(L, 2+i);
}
/* Fill the rest of the pixels from the first */
for (size_t i = 1; i < buffer->npix; i++) {
memcpy(&buffer->values[i * buffer->nchan], buffer->values, buffer->nchan);
}
out:
lua_settop(L, 1);
return 1;
}
static int pixbuf_get_lua(lua_State *L) {
pixbuf *buffer = pixbuf_from_lua_arg(L, 1);
const int led = luaL_checkinteger(L, 2) - 1;
size_t channels = buffer->nchan;
luaL_argcheck(L, led >= 0 && led < buffer->npix, 2, "index out of range");
uint8_t tmp[channels];
memcpy(tmp, &buffer->values[channels*led], channels);
for (size_t i = 0; i < channels; i++)
{
lua_pushinteger(L, tmp[i]);
}
return channels;
}
/* :map(f, buf1, ilo, ihi, [buf2, ilo2]) */
static int pixbuf_map_lua(lua_State *L) {
pixbuf *outbuf = pixbuf_from_lua_arg(L, 1);
/* f at index 2 */
pixbuf *buffer1 = pixbuf_opt_from_lua_arg(L, 3);
if (!buffer1)
buffer1 = outbuf;
const int ilo = posrelat(luaL_optinteger(L, 4, 1), buffer1->npix) - 1;
const int ihi = posrelat(luaL_optinteger(L, 5, buffer1->npix), buffer1->npix) - 1;
luaL_argcheck(L, ihi > ilo, 3, "Buffer limits out of order");
size_t npix = ihi - ilo + 1;
luaL_argcheck(L, npix == outbuf->npix, 1, "Output buffer wrong size");
pixbuf *buffer2 = pixbuf_opt_from_lua_arg(L, 6);
const int ilo2 = buffer2 ? posrelat(luaL_optinteger(L, 7, 1), buffer2->npix) - 1 : 0;
if (buffer2) {
luaL_argcheck(L, ilo2 + npix <= buffer2->npix, 6, "Second buffer too short");
}
for (size_t p = 0; p < npix; p++) {
lua_pushvalue(L, 2);
for (size_t c = 0; c < buffer1->nchan; c++) {
lua_pushinteger(L, buffer1->values[(ilo + p) * buffer1->nchan + c]);
}
if (buffer2) {
for (size_t c = 0; c < buffer2->nchan; c++) {
lua_pushinteger(L, buffer2->values[(ilo2 + p) * buffer2->nchan + c]);
}
}
lua_call(L, buffer1->nchan + (buffer2 ? buffer2->nchan : 0), outbuf->nchan);
for (size_t c = 0; c < outbuf->nchan; c++) {
outbuf->values[(p + 1) * outbuf->nchan - c - 1] = luaL_checkinteger(L, -1);
lua_pop(L, 1);
}
}
lua_settop(L, 1);
return 1;
}
struct mix_source {
int factor;
const uint8_t *values;
};
static uint32_t pixbuf_mix_clamp(int32_t v) {
if (v < 0) { return 0; }
if (v > 255) { return 255; }
return v;
}
/* This one can sum straightforwardly, channel by channel */
static void pixbuf_mix_raw(pixbuf *out, size_t n_src, struct mix_source* src) {
size_t cells = pixbuf_size(out);
for (size_t c = 0; c < cells; c++) {
int32_t val = 0;
for (size_t s = 0; s < n_src; s++) {
val += (int32_t)src[s].values[c] * src[s].factor;
}
val += 128; // rounding instead of floor
val /= 256; // do not use implemetation dependant right shift
out->values[c] = (uint8_t)pixbuf_mix_clamp(val);
}
}
/* Mix intensity-mediated three-color pixbufs.
*
* XXX This is untested in real hardware; do they actually behave like this?
*/
static void pixbuf_mix_i3(pixbuf *out, size_t ibits, size_t n_src,
struct mix_source* src) {
for(size_t p = 0; p < out->npix; p++) {
int32_t sums[3] = { 0, 0, 0 };
for (size_t s = 0; s < n_src; s++) {
for (size_t c = 0; c < 3; c++) {
sums[c] += (int32_t)src[s].values[4*p+c+1] // color channel
* src[s].values[4*p] // global intensity
* src[s].factor; // user factor
}
}
uint32_t pmaxc = 0;
for (size_t c = 0; c < 3; c++) {
pmaxc = sums[c] > pmaxc ? sums[c] : pmaxc;
}
size_t maxgi;
if (pmaxc == 0) {
/* Zero value */
memset(&out->values[4*p], 0, 4);
return;
} else if (pmaxc <= (1 << 16)) {
/* Minimum global factor */
maxgi = 1;
} else if (pmaxc >= ((1 << ibits) - 1) << 16) {
/* Maximum global factor */
maxgi = (1 << ibits) - 1;
} else {
maxgi = (pmaxc >> 16) + 1;
}
// printf("mixi3: %x %x %x -> %x, %zx\n", sums[0], sums[1], sums[2], pmaxc, maxgi);
out->values[4*p] = maxgi;
for (size_t c = 0; c < 3; c++) {
out->values[4*p+c+1] = pixbuf_mix_clamp((sums[c] + 256 * maxgi - 127) / (256 * maxgi));
}
}
}
// buffer:mix(factor1, buffer1, ..)
// factor is 256 for 100%
// uses saturating arithmetic (one buffer at a time)
static int pixbuf_mix_core(lua_State *L, size_t ibits) {
pixbuf *buffer = pixbuf_from_lua_arg(L, 1);
pixbuf *src_buffer;
int pos = 2;
size_t n_sources = (lua_gettop(L) - 1) / 2;
struct mix_source sources[n_sources];
if (n_sources == 0) {
lua_settop(L, 1);
return 1;
}
for (size_t src = 0; src < n_sources; src++, pos += 2) {
int factor = luaL_checkinteger(L, pos);
src_buffer = pixbuf_from_lua_arg(L, pos + 1);
luaL_argcheck(L, src_buffer->npix == buffer->npix &&
src_buffer->nchan == buffer->nchan,
pos + 1, "buffer not same size or shape");
sources[src].factor = factor;
sources[src].values = src_buffer->values;
}
if (ibits != 0) {
luaL_argcheck(L, src_buffer->nchan == 4, 2, "Requires 4 channel pixbuf");
pixbuf_mix_i3(buffer, ibits, n_sources, sources);
} else {
pixbuf_mix_raw(buffer, n_sources, sources);
}
lua_settop(L, 1);
return 1;
}
static int pixbuf_mix_lua(lua_State *L) {
return pixbuf_mix_core(L, 0);
}
static int pixbuf_mix4I5_lua(lua_State *L) {
return pixbuf_mix_core(L, 5);
}
// Returns the total of all channels
static int pixbuf_power_lua(lua_State *L) {
pixbuf *buffer = pixbuf_from_lua_arg(L, 1);
int total = 0;
size_t p = 0;
for (size_t i = 0; i < buffer->npix; i++) {
for (size_t j = 0; j < buffer->nchan; j++, p++) {
total += buffer->values[p];
}
}
lua_pushinteger(L, total);
return 1;
}
// Returns the total of all channels, intensity-style
static int pixbuf_powerI_lua(lua_State *L) {
pixbuf *buffer = pixbuf_from_lua_arg(L, 1);
int total = 0;
size_t p = 0;
for (size_t i = 0; i < buffer->npix; i++) {
int inten = buffer->values[p++];
for (size_t j = 0; j < buffer->nchan - 1; j++, p++) {
total += inten * buffer->values[p];
}
}
lua_pushinteger(L, total);
return 1;
}
static int pixbuf_replace_lua(lua_State *L) {
pixbuf *buffer = pixbuf_from_lua_arg(L, 1);
ptrdiff_t start = posrelat(luaL_optinteger(L, 3, 1), buffer->npix);
size_t channels = buffer->nchan;
uint8_t *src;
size_t srcLen;
if (lua_type(L, 2) == LUA_TSTRING) {
size_t length;
src = (uint8_t *) lua_tolstring(L, 2, &length);
srcLen = length / channels;
} else {
pixbuf *rhs = pixbuf_from_lua_arg(L, 2);
luaL_argcheck(L, rhs->nchan == buffer->nchan, 2, "buffers have different channels");
src = rhs->values;
srcLen = rhs->npix;
}
luaL_argcheck(L, srcLen + start - 1 <= buffer->npix, 2, "does not fit into destination");
memcpy(buffer->values + (start - 1) * channels, src, srcLen * channels);
return 0;
}
static int pixbuf_set_lua(lua_State *L) {
pixbuf *buffer = pixbuf_from_lua_arg(L, 1);
const int led = luaL_checkinteger(L, 2) - 1;
const size_t channels = buffer->nchan;
luaL_argcheck(L, led >= 0 && led < buffer->npix, 2, "index out of range");
int type = lua_type(L, 3);
if(type == LUA_TTABLE)
{
for (size_t i = 0; i < channels; i++)
{
lua_rawgeti(L, 3, i+1);
buffer->values[channels*led+i] = lua_tointeger(L, -1);
lua_pop(L, 1);
}
}
else if(type == LUA_TSTRING)
{
size_t len;
const char *buf = lua_tolstring(L, 3, &len);
// Overflow check
if( channels*led + len > channels*buffer->npix ) {
return luaL_error(L, "string size will exceed strip length");
}
if ( len % channels != 0 ) {
return luaL_error(L, "string does not contain whole LEDs");
}
memcpy(&buffer->values[channels*led], buf, len);
}
else
{
luaL_argcheck(L, lua_gettop(L) <= 2 + channels, 2 + channels,
"extra values given");
for (size_t i = 0; i < channels; i++)
{
buffer->values[channels*led+i] = luaL_checkinteger(L, 3+i);
}
}
lua_settop(L, 1);
return 1;
}
static void pixbuf_shift_circular(pixbuf *buffer, struct pixbuf_shift_params *sp) {
/* Move a buffer of pixels per iteration; loop repeatedly if needed */
uint8_t tmpbuf[32];
uint8_t *v = buffer->values;
size_t shiftRemaining = sp->shift;
size_t cursor = sp->offset;
do {
size_t shiftNow = MIN(shiftRemaining, sizeof tmpbuf);
if (sp->shiftLeft) {
memcpy(tmpbuf, &v[cursor], shiftNow);
memmove(&v[cursor], &v[cursor+shiftNow], sp->window - shiftNow);
memcpy(&v[cursor+sp->window-shiftNow], tmpbuf, shiftNow);
} else {
memcpy(tmpbuf, &v[cursor+sp->window-shiftNow], shiftNow);
memmove(&v[cursor+shiftNow], &v[cursor], sp->window - shiftNow);
memcpy(&v[cursor], tmpbuf, shiftNow);
}
cursor += shiftNow;
shiftRemaining -= shiftNow;
} while(shiftRemaining > 0);
}
static void pixbuf_shift_logical(pixbuf *buffer, struct pixbuf_shift_params *sp) {
/* Logical shifts don't require a temporary buffer, so we just move bytes */
uint8_t *v = buffer->values;
if (sp->shiftLeft) {
memmove(&v[sp->offset], &v[sp->offset+sp->shift], sp->window - sp->shift);
bzero(&v[sp->offset+sp->window-sp->shift], sp->shift);
} else {
memmove(&v[sp->offset+sp->shift], &v[sp->offset], sp->window - sp->shift);
bzero(&v[sp->offset], sp->shift);
}
}
void pixbuf_shift(pixbuf *b, struct pixbuf_shift_params *sp) {
#if 0
printf("Pixbuf %p shifting %s %s by %zd from %zd with window %zd\n",
b,
sp->shiftLeft ? "left" : "right",
sp->type == PIXBUF_SHIFT_LOGICAL ? "logically" : "circularly",
sp->shift, sp->offset, sp->window);
#endif
switch(sp->type) {
case PIXBUF_SHIFT_LOGICAL: return pixbuf_shift_logical(b, sp);
case PIXBUF_SHIFT_CIRCULAR: return pixbuf_shift_circular(b, sp);
}
}
int pixbuf_shift_lua(lua_State *L) {
struct pixbuf_shift_params sp;
pixbuf *buffer = pixbuf_from_lua_arg(L, 1);
const int shift_shift = luaL_checkinteger(L, 2) * buffer->nchan;
const unsigned shift_type = luaL_optinteger(L, 3, PIXBUF_SHIFT_LOGICAL);
const int pos_start = posrelat(luaL_optinteger(L, 4, 1), buffer->npix);
const int pos_end = posrelat(luaL_optinteger(L, 5, -1), buffer->npix);
if (shift_shift < 0) {
sp.shiftLeft = true;
sp.shift = -shift_shift;
} else {
sp.shiftLeft = false;
sp.shift = shift_shift;
}
switch(shift_type) {
case PIXBUF_SHIFT_LOGICAL:
case PIXBUF_SHIFT_CIRCULAR:
sp.type = shift_type;
break;
default:
return luaL_argerror(L, 3, "invalid shift type");
}
if (pos_start < 1) {
return luaL_argerror(L, 4, "start position must be >= 1");
}
if (pos_end < pos_start) {
return luaL_argerror(L, 5, "end position must be >= start");
}
sp.offset = (pos_start - 1) * buffer->nchan;
sp.window = (pos_end - pos_start + 1) * buffer->nchan;
if (sp.shift > pixbuf_size(buffer)) {
return luaL_argerror(L, 2, "shifting more elements than buffer size");
}
if (sp.shift > sp.window) {
return luaL_argerror(L, 2, "shifting more than sliced window");
}
pixbuf_shift(buffer, &sp);
return 0;
}
/* XXX for backwards-compat with ws2812_effects; deprecated and should be removed */
void pixbuf_prepare_shift(pixbuf *buffer, struct pixbuf_shift_params *sp,
int shift, enum pixbuf_shift type, int start, int end)
{
start = posrelat(start, buffer->npix);
end = posrelat(end, buffer->npix);
lua_assert((end > start) && (start > 0) && (end < buffer->npix));
sp->type = type;
sp->offset = (start - 1) * buffer->nchan;
sp->window = (end - start + 1) * buffer->nchan;
if (shift < 0) {
sp->shiftLeft = true;
sp->shift = -shift * buffer->nchan;
} else {
sp->shiftLeft = false;
sp->shift = shift * buffer->nchan;
}
}
static int pixbuf_size_lua(lua_State *L) {
pixbuf *buffer = pixbuf_from_lua_arg(L, 1);
lua_pushinteger(L, buffer->npix);
return 1;
}
static int pixbuf_sub_lua(lua_State *L) {
pixbuf *lhs = pixbuf_from_lua_arg(L, 1);
size_t l = lhs->npix;
ssize_t start = posrelat(luaL_checkinteger(L, 2), l);
ssize_t end = posrelat(luaL_optinteger(L, 3, -1), l);
if (start <= end) {
pixbuf *result = pixbuf_new(L, end - start + 1, lhs->nchan);
memcpy(result->values, lhs->values + lhs->nchan * (start - 1),
lhs->nchan * (end - start + 1));
return 1;
} else {
pixbuf_new(L, 0, lhs->nchan);
return 1;
}
}
static int pixbuf_tostring_lua(lua_State *L) {
pixbuf *buffer = pixbuf_from_lua_arg(L, 1);
luaL_Buffer result;
luaL_buffinit(L, &result);
luaL_addchar(&result, '[');
int p = 0;
for (size_t i = 0; i < buffer->npix; i++) {
if (i > 0) {
luaL_addchar(&result, ',');
}
luaL_addchar(&result, '(');
for (size_t j = 0; j < buffer->nchan; j++, p++) {
if (j > 0) {
luaL_addchar(&result, ',');
}
char numbuf[5];
sprintf(numbuf, "%d", buffer->values[p]);
luaL_addstring(&result, numbuf);
}
luaL_addchar(&result, ')');
}
luaL_addchar(&result, ']');
luaL_pushresult(&result);
return 1;
}
LROT_BEGIN(pixbuf_map, NULL, LROT_MASK_INDEX | LROT_MASK_EQ)
LROT_TABENTRY ( __index, pixbuf_map )
LROT_FUNCENTRY( __eq, pixbuf_eq_lua )
LROT_FUNCENTRY( __concat, pixbuf_concat_lua )
LROT_FUNCENTRY( __tostring, pixbuf_tostring_lua )
LROT_FUNCENTRY( channels, pixbuf_channels_lua )
LROT_FUNCENTRY( dump, pixbuf_dump_lua )
LROT_FUNCENTRY( fade, pixbuf_fade_lua )
LROT_FUNCENTRY( fadeI, pixbuf_fadeI_lua )
LROT_FUNCENTRY( fill, pixbuf_fill_lua )
LROT_FUNCENTRY( get, pixbuf_get_lua )
LROT_FUNCENTRY( replace, pixbuf_replace_lua )
LROT_FUNCENTRY( map, pixbuf_map_lua )
LROT_FUNCENTRY( mix, pixbuf_mix_lua )
LROT_FUNCENTRY( mix4I5, pixbuf_mix4I5_lua )
LROT_FUNCENTRY( power, pixbuf_power_lua )
LROT_FUNCENTRY( powerI, pixbuf_powerI_lua )
LROT_FUNCENTRY( set, pixbuf_set_lua )
LROT_FUNCENTRY( shift, pixbuf_shift_lua )
LROT_FUNCENTRY( size, pixbuf_size_lua )
LROT_FUNCENTRY( sub, pixbuf_sub_lua )
LROT_END(pixbuf_map, NULL, LROT_MASK_INDEX | LROT_MASK_EQ)
LROT_BEGIN(pixbuf, NULL, 0)
LROT_NUMENTRY( FADE_IN, PIXBUF_FADE_IN )
LROT_NUMENTRY( FADE_OUT, PIXBUF_FADE_OUT )
LROT_NUMENTRY( SHIFT_CIRCULAR, PIXBUF_SHIFT_CIRCULAR )
LROT_NUMENTRY( SHIFT_LOGICAL, PIXBUF_SHIFT_LOGICAL )
LROT_FUNCENTRY( newBuffer, pixbuf_new_lua )
LROT_END(pixbuf, NULL, 0)
int luaopen_pixbuf(lua_State *L) {
luaL_rometatable(L, PIXBUF_METATABLE, LROT_TABLEREF(pixbuf_map));
lua_pushrotable(L, LROT_TABLEREF(pixbuf));
return 1;
}
NODEMCU_MODULE(PIXBUF, "pixbuf", pixbuf, luaopen_pixbuf);
| 27.10221 | 96 | 0.633218 | [
"shape"
] |
97fad5ca5abf77c03bbafc4eb1de1c3ad3f00706 | 1,451 | h | C | ParallelTripleBit/TripleBit/util/HashJoin.h | oeljeklaus-you/ParallelTripleBit | cf17d20bed95b984f0464ff2f85e8ecae5c651f6 | [
"MIT"
] | null | null | null | ParallelTripleBit/TripleBit/util/HashJoin.h | oeljeklaus-you/ParallelTripleBit | cf17d20bed95b984f0464ff2f85e8ecae5c651f6 | [
"MIT"
] | null | null | null | ParallelTripleBit/TripleBit/util/HashJoin.h | oeljeklaus-you/ParallelTripleBit | cf17d20bed95b984f0464ff2f85e8ecae5c651f6 | [
"MIT"
] | null | null | null | /*
* HashJoin.h
*
* Created on: Jul 14, 2010
* Author: root
*/
#ifndef HASHJOIN_H_
#define HASHJOIN_H_
#include "../TripleBit.h"
#include "../ThreadPool.h"
class EntityIDBuffer;
class HashJoinTask;
class BuildHashIndexTask;
struct HashJoinArg;
class HashJoin {
private:
//CThreadPool* pool;
public:
friend class HashJoinTask;
HashJoin();
virtual ~HashJoin();
static ID HashFunction(ID id, ID hashKey);
static ID GetHashKey2(ID size);
void Join(EntityIDBuffer* entBuffer1, EntityIDBuffer* entBuffer2, int joinKey1, int joinKey2);
static ID GetHashKey(ID size);
static void BuildHashIndex(ID* p ,int joinKey, ID hashKey, vector<int>& hashTrack, vector<int>& prefixSum, int size, int IDCount);
static void HashJoinInit(EntityIDBuffer* buffer,ID& hashKey, vector<vector<int>* >& hashTrack, int joinKey);
static void SortMergeJoin(ID* buffer1, ID * buffer2, int IDCount1, int IDCount2, int joinKey1, int joinKey2,
int size1, int size2, char* flagVector1, char* flagVector2);
static void SortMergeJoin(ID* buffer1, ID * buffer2, int IDCount1, int IDCount2, int joinKey1, int joinKey2,
int size1, int size2, char* flagVector1);
static void run(HashJoinArg* arg);
};
struct HashJoinArg
{
char* flag1;
char* flag2;
EntityIDBuffer* buffer1;
EntityIDBuffer* buffer2;
//the start pos in the buffer;
int startPos1;
int length1;
int startPos2;
int length2;
int joinKey1;
int joinKey2;
};
#endif /* HASHJOIN_H_ */
| 24.183333 | 131 | 0.736044 | [
"vector"
] |
1c1be1b15dc7e5586364737e6626b6410922f4a4 | 1,980 | h | C | src/node/node_signature_verify.h | kiromaru/CCF | 3cf8636bebce05ec2c7c5d2012fad26c25346814 | [
"Apache-2.0"
] | 530 | 2019-05-07T03:07:15.000Z | 2022-03-29T16:33:06.000Z | src/node/node_signature_verify.h | kiromaru/CCF | 3cf8636bebce05ec2c7c5d2012fad26c25346814 | [
"Apache-2.0"
] | 3,393 | 2019-05-07T08:33:32.000Z | 2022-03-31T14:57:14.000Z | src/node/node_signature_verify.h | beejones/CCF | 335fc3613c2dd4a3bda38e10e8e8196dba52465e | [
"Apache-2.0"
] | 158 | 2019-05-07T09:17:56.000Z | 2022-03-25T16:45:04.000Z | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the Apache 2.0 License.
#pragma once
#include "ccf/tx.h"
#include "crypto/verifier.h"
#include "node_signature_verify.h"
namespace ccf
{
static bool verify_node_signature(
kv::ReadOnlyTx& tx,
const NodeId& node_id,
const uint8_t* expected_sig,
size_t expected_sig_size,
const uint8_t* expected_root,
size_t expected_root_size)
{
crypto::Pem node_cert;
auto node_endorsed_certs = tx.template ro<ccf::NodeEndorsedCertificates>(
ccf::Tables::NODE_ENDORSED_CERTIFICATES);
auto node_endorsed_cert = node_endorsed_certs->get(node_id);
if (!node_endorsed_cert.has_value())
{
// No endorsed certificate for node. Its (self-signed) certificate
// must be stored in the nodes table (1.x ledger only)
auto nodes = tx.template ro<ccf::Nodes>(ccf::Tables::NODES);
auto node = nodes->get(node_id);
if (!node.has_value())
{
LOG_FAIL_FMT(
"Signature cannot be verified: no certificate found for node {}",
node_id);
return false;
}
CCF_ASSERT_FMT(
node->cert.has_value(),
"No certificate recorded in nodes table for {} (1.x ledger)",
node_id);
node_cert = node->cert.value();
}
else
{
node_cert = node_endorsed_cert.value();
}
crypto::VerifierPtr from_cert = crypto::make_verifier(node_cert);
return from_cert->verify_hash(
expected_root,
expected_root_size,
expected_sig,
expected_sig_size,
crypto::MDType::SHA256);
}
static bool verify_node_signature(
kv::ReadOnlyTx& tx,
const NodeId& node_id,
const std::vector<uint8_t>& expected_sig,
const crypto::Sha256Hash& expected_root)
{
return verify_node_signature(
tx,
node_id,
expected_sig.data(),
expected_sig.size(),
expected_root.h.data(),
expected_root.h.size());
}
} | 27.123288 | 77 | 0.657576 | [
"vector"
] |
1c1e0e142da3ab6f5726b7e4281df8ea7f1b6783 | 456 | h | C | Source/Mesh.h | RPKQ/OpenGL_scratchUp | cbe0268d6bb86bc0de49fafdcf078e5b85395964 | [
"CC-BY-3.0"
] | null | null | null | Source/Mesh.h | RPKQ/OpenGL_scratchUp | cbe0268d6bb86bc0de49fafdcf078e5b85395964 | [
"CC-BY-3.0"
] | null | null | null | Source/Mesh.h | RPKQ/OpenGL_scratchUp | cbe0268d6bb86bc0de49fafdcf078e5b85395964 | [
"CC-BY-3.0"
] | null | null | null | #ifndef GPA_ASS2_MESH_H
#define GPA_ASS2_MESH_H
#include "Program.h"
#include "GLIncludes.h"
class Mesh
{
public:
Mesh(GLuint VAO, GLuint VBO_POS, GLuint VBO_NORMAL,
GLuint VBO_TEXCOORD, GLuint EBO, GLuint TEXTURE, int MATERIAL_ID, int INDEX_COUNT);
~Mesh();
void draw(Program* program);
private:
GLuint vao;
GLuint vbo_pos, vbo_normal, vbo_texCoord;
GLuint ebo; // ELEMENT_ARRAY_BUFFER
GLuint texure;
int materialID, indexCount;
};
#endif
| 19 | 85 | 0.758772 | [
"mesh"
] |
1c228be3fee1b37a4038eafcae6f817844690125 | 1,949 | h | C | include/BingoCpp/training_data.h | imikejackson/bingocpp | 6ba00a490c8cb46edebfd78f56b1604a76d668e9 | [
"Apache-2.0"
] | 13 | 2019-03-14T09:54:02.000Z | 2021-09-26T14:01:30.000Z | include/BingoCpp/training_data.h | imikejackson/bingocpp | 6ba00a490c8cb46edebfd78f56b1604a76d668e9 | [
"Apache-2.0"
] | 35 | 2019-08-29T19:12:05.000Z | 2021-07-15T22:17:53.000Z | include/BingoCpp/training_data.h | imikejackson/bingocpp | 6ba00a490c8cb46edebfd78f56b1604a76d668e9 | [
"Apache-2.0"
] | 9 | 2018-10-18T02:43:03.000Z | 2021-09-02T22:08:39.000Z | /*!
* \file training_data.h
*
* \author Ethan Adams
* \date
*
* This file contains the cpp version of training_data.py
*
* Copyright 2018 United States Government as represented by the Administrator
* of the National Aeronautics and Space Administration. No copyright is claimed
* in the United States under Title 17, U.S. Code. All Other Rights Reserved.
*
* The Bingo Mini-app platform is 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 INCLUDE_BINGOCPP_TRAINING_DATA_H_
#define INCLUDE_BINGOCPP_TRAINING_DATA_H_
#include <vector>
#include <Eigen/Dense>
#include <Eigen/Core>
namespace bingo {
/*! \struct TrainingData
*
* An abstract struct to hold the data for fitness calculations
*
* \note TrainingData includes : Implicit and Explicit data
*
* \fn TrainingData* get_item(std::list<int> items)
* \fn int size()
*/
struct TrainingData {
public:
TrainingData() { }
virtual ~TrainingData() { }
virtual TrainingData *GetItem(int item) = 0 ;
/*! \brief gets a new training data with certain rows
*
* \param[in] items The rows to retrieve. std::list<int>
* \return TrainingData* with the selected data
*/
virtual TrainingData *GetItem(const std::vector<int> &items) = 0;
/*! \brief gets the size of x
*
* \return int the amount of rows in x
*/
virtual int Size() = 0;
};
} // namespace bingo
#endif
| 29.530303 | 82 | 0.691637 | [
"vector"
] |
1c264ee81dd33ae7f4dd394870de8c38c688a16f | 5,789 | h | C | include/IECore/InverseDistanceWeightedInterpolation.h | gcodebackups/cortex-vfx | 72fa6c6eb3327fce4faf01361c8fcc2e1e892672 | [
"BSD-3-Clause"
] | 5 | 2016-07-26T06:09:28.000Z | 2022-03-07T03:58:51.000Z | include/IECore/InverseDistanceWeightedInterpolation.h | turbosun/cortex | 4bdc01a692652cd562f3bfa85f3dae99d07c0b15 | [
"BSD-3-Clause"
] | null | null | null | include/IECore/InverseDistanceWeightedInterpolation.h | turbosun/cortex | 4bdc01a692652cd562f3bfa85f3dae99d07c0b15 | [
"BSD-3-Clause"
] | 3 | 2015-03-25T18:45:24.000Z | 2020-02-15T15:37:18.000Z | //////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2008-2011, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of Image Engine Design nor the names of any
// other contributors to this software 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.
//
//////////////////////////////////////////////////////////////////////////
#ifndef IE_CORE_INVERSEDISTANCEWEIGHTEDINTERPOLATION_H
#define IE_CORE_INVERSEDISTANCEWEIGHTEDINTERPOLATION_H
#include <map>
#include "IECore/KDTree.h"
namespace IECore
{
/// The InverseDistanceWeightedInterpolation class provides interpolation of scattered data. It is
/// templated so that it can operate on a wide variety of point/value types.
/// NB. The Value must be default constructible, and define sensible value=value+value, and value=value*scalar operators
/// \ingroup mathGroup
template< typename PointIterator, typename ValueIterator >
class InverseDistanceWeightedInterpolation
{
public :
typedef typename std::iterator_traits<PointIterator>::value_type Point;
typedef typename VectorTraits<Point>::BaseType PointBaseType;
typedef KDTree<PointIterator> Tree;
typedef std::vector<typename Tree::Neighbour> NeighbourVector;
typedef typename std::iterator_traits<ValueIterator>::value_type Value;
/// Creates the interpolator. Note that it does not own the passed points or values -
/// it is up to you to ensure that they remain valid and unchanged as long as the
/// interpolator is in use.
/// \param firstPoint RandomAccessIterator to first point
/// \param lastPoint RandomAccessIterator to last point
/// \param firstValue RandomAccessIterator to first value
/// \param lastValue RandomAccessIterator to last value
/// \param numNeighbours The amount of nearest-neighbour points to consider when performing interpolation. More usually yields slower, but better results.
/// \param maxLeafSize The number of points to store in each KDTree bucket
InverseDistanceWeightedInterpolation(
PointIterator firstPoint,
PointIterator lastPoint,
ValueIterator firstValue,
ValueIterator lastValue,
unsigned int numNeighbours,
int maxLeafSize=4
);
virtual ~InverseDistanceWeightedInterpolation();
/// Evaluate the interpolated value for the specified point.
Value operator()( const Point &p ) const;
/// As above, but returning information about which neighbours contributed to
/// the result. Note that for repeated queries it is quicker to call this method
/// reusing the same NeighbourVector than it is to call the version above, which
/// has to allocate a NeighbourVector each time.
Value operator()( const Point &p, NeighbourVector &neighbours ) const;
private :
Tree *m_tree;
PointIterator m_firstPoint;
ValueIterator m_firstValue;
unsigned int m_numNeighbours;
};
typedef InverseDistanceWeightedInterpolation< std::vector<Imath::V2f>::const_iterator, std::vector<float>::const_iterator > InverseDistanceWeightedInterpolationV2ff;
typedef InverseDistanceWeightedInterpolation< std::vector<Imath::V2d>::const_iterator, std::vector<double>::const_iterator > InverseDistanceWeightedInterpolationV2dd;
typedef InverseDistanceWeightedInterpolation< std::vector<Imath::V3f>::const_iterator, std::vector<float>::const_iterator > InverseDistanceWeightedInterpolationV3ff;
typedef InverseDistanceWeightedInterpolation< std::vector<Imath::V3d>::const_iterator, std::vector<double>::const_iterator > InverseDistanceWeightedInterpolationV3dd;
typedef InverseDistanceWeightedInterpolation< std::vector<Imath::V2f>::const_iterator, std::vector<Imath::V2f>::const_iterator > InverseDistanceWeightedInterpolationV2fV2f;
typedef InverseDistanceWeightedInterpolation< std::vector<Imath::V2d>::const_iterator, std::vector<Imath::V2d>::const_iterator > InverseDistanceWeightedInterpolationV2dV2d;
typedef InverseDistanceWeightedInterpolation< std::vector<Imath::V3f>::const_iterator, std::vector<Imath::V3f>::const_iterator > InverseDistanceWeightedInterpolationV3fV3f;
typedef InverseDistanceWeightedInterpolation< std::vector<Imath::V3d>::const_iterator, std::vector<Imath::V3d>::const_iterator > InverseDistanceWeightedInterpolationV3dV3d;
} // namespace IECore
#include "InverseDistanceWeightedInterpolation.inl"
#endif // IE_CORE_INVERSEDISTANCEWEIGHTEDINTERPOLATION_H
| 49.905172 | 172 | 0.766454 | [
"vector"
] |
1c2c117798203931cdd9ca4320065d34363542b2 | 33,819 | c | C | redis_link.c | fkfk000/redis_link | 536c1ac28df6a09d2cb427900fd00896cd398630 | [
"BSD-2-Clause"
] | 2 | 2021-03-15T02:25:44.000Z | 2021-03-15T17:30:43.000Z | redis_link.c | fkfk000/redis_link | 536c1ac28df6a09d2cb427900fd00896cd398630 | [
"BSD-2-Clause"
] | null | null | null | redis_link.c | fkfk000/redis_link | 536c1ac28df6a09d2cb427900fd00896cd398630 | [
"BSD-2-Clause"
] | null | null | null | #include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#include <hiredis/hiredis.h>
#include "postgres.h"
#include "funcapi.h"
#include "access/htup_details.h"
#include "access/reloptions.h"
#include "access/sysattr.h"
#include "catalog/indexing.h"
#include "catalog/pg_attribute.h"
#include "catalog/pg_cast.h"
#include "catalog/pg_foreign_data_wrapper.h"
#include "catalog/pg_foreign_server.h"
#include "catalog/pg_foreign_table.h"
#include "catalog/pg_namespace.h"
#include "catalog/pg_operator.h"
#include "catalog/pg_proc.h"
#include "catalog/pg_user_mapping.h"
#include "catalog/pg_type.h"
#include "commands/defrem.h"
#include "commands/explain.h"
#include "foreign/fdwapi.h"
#include "foreign/foreign.h"
#include "miscadmin.h"
#include "nodes/bitmapset.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "nodes/pg_list.h"
#include "optimizer/cost.h"
#include "optimizer/pathnode.h"
#include "optimizer/planmain.h"
#include "optimizer/restrictinfo.h"
#if PG_VERSION_NUM < 120000
#include "optimizer/var.h"
#else
#include "access/table.h"
#include "optimizer/optimizer.h"
#endif
#include "parser/parse_relation.h"
#include "parser/parsetree.h"
#include "utils/builtins.h"
#include "utils/elog.h"
#include "utils/fmgroids.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/rel.h"
#include "utils/syscache.h"
// Here are things needed for declaration
Datum redis_link_handler(PG_FUNCTION_ARGS);
Datum redis_link_validator(PG_FUNCTION_ARGS);
PG_FUNCTION_INFO_V1(redis_link_handler);
PG_FUNCTION_INFO_V1(redis_link_validator);
PG_MODULE_MAGIC;
/* For fdw_private
*/
#define MAX_CACHED_MEMORY 8 * 1024 * 1024 // 8MB
// For now, we actually only support string.
enum REDIS_TABLE_TYPE
{
REDIS_TABLE_INVALID = -1,
REDIS_TABLE_STRING,
REDIS_TABLE_HSET
};
typedef struct redisColumn
{
char *column_name;
int attnum;
Oid atttypid;
Oid atttypmod;
regproc typoutput; // type output conversion function
regproc typinput; // type input conversion function
} redisColumn;
typedef struct redisTableInfo
{
char *tablename;
int column_num;
redisColumn *columns;
} redisTableInfo;
typedef struct redisCtx
{
// Infromation for connection.
char *host;
char *password;
int port;
// Infromation for foreign server and table.
ForeignServer *foreign_server;
ForeignTable *foreign_table;
int table_type;
char *prefix_name;
redisTableInfo *table_info;
// redis related object.
redisContext *connection_context;
//redisReply *reply;
// Infromation for operation type
CmdType cmd_type;
// section for select
char *where_claus; // only be useful to key.
// General ifromation for the foreign table
double rows;
} redisCtx;
typedef struct redisScanState
{
redisCtx *redis_ctx;
redisReply *redis_reply; // used for retrive all the keys.
redisReply *iter_reply; // used for iter in redisGetReply.
char *search_name;
int current_cursor; // scan cursor
int list_capacity;
int list_current;
char **keys; // store all the keys returned from one scan operation.
MemoryContext upper_context; // beacuse in iter scan, memory would be cleared. we need this to save some infromation.
} redisScanState;
typedef struct redisInsertState
{
redisCtx *redis_ctx;
int current_buffered_data; // how much data is cached.
int cached_cmd; // how many redisAppendCommand is memory.
redisReply *iter_reply; // used for consume the retruned value from redisAppendCommand.
AttInMetadata *attmeta; // description of the tuple.
MemoryContext tmp_context; // used in each iter of insert.
// used for sotore values from slot.
// we used use them in tmp context, keep them shot-lived.
char *key;
char *value;
char *ttl;
} redisInsertState;
// current we only support these.
enum REDIS_WHERE_OP
{
OPERATION_INVALID = -1,
OPERATION_LIKE, // ~~ in op name
OPERATION_EQUAL // = in op name
};
// Helper function declaration
static bool redis_is_valid_option(const char *option_name, Oid option_typpe);
void set_redis_ctx(Oid foreigntableid, redisCtx *redis_ctx);
void set_redis_table_column(Oid foreigntableid, redisCtx *redis_ctx);
void set_type_inout_function(Oid typeid, regproc *typinput, regproc *typoutput);
void set_where_clause(RelOptInfo *baserel, redisCtx *redis_ctx, List *baserestrictinfo);
bool is_valid_key_type(Oid key_type);
void get_operation_infromation(OpExpr *expr, Oid *left_oid, Oid *rght_oid, Oid *operation_type);
void parse_where(redisCtx *redis_ctx, Expr *expr);
int get_operation_type(char *name); // to identify = in where a = 1;
char *make_tablename_into_where_clause(redisCtx *redis_ctx);
// Declaration of functions
void redisLinkGetForeignRelSize(PlannerInfo *root,
RelOptInfo *baserel, Oid foreigntableid);
void redisLinkGetForeignPaths(PlannerInfo *root, RelOptInfo *baserel, Oid foreigntableid);
ForeignScan *redisLinkGetForeignPlan(PlannerInfo *root, RelOptInfo *baserel,
Oid foreigntableid, ForeignPath *best_path,
List *tlist, List *scan_clauses, Plan *outer_plan);
void redisLinkBeginForeignScan(ForeignScanState *node, int eflags);
static TupleTableSlot *redisLinkIterateForeignScan(ForeignScanState *node);
static void redisLinkReScanForeignScan(ForeignScanState *node);
static void redisLinkEndForeignScan(ForeignScanState *node);
static List *redisLinkPlanForeignModify(PlannerInfo *root, ModifyTable *plan,
Index resultRelation,
int subplan_index);
static TupleTableSlot *redisLinkExecForeignInsert(EState *estate,
ResultRelInfo *rinfo,
TupleTableSlot *slot,
TupleTableSlot *planSlot);
static void redisLinkBeginForeignModify(ModifyTableState *mtstate,
ResultRelInfo *rinfo,
List *fdw_private,
int subplan_index,
int eflags);
static void redisLinkEndForeignModify(EState *estate,
ResultRelInfo *rinfo);
static void redisLinkBeginForeignInsert(ModifyTableState *mtstate,
ResultRelInfo *rinfo);
static void redisLinkEndForeignInsert(EState *estate,
ResultRelInfo *rinfo);
// Declaration of macros
#define OPT_KEY "key"
#define OPT_VALUE "value"
#define OPT_TTL "ttl"
#define OPT_COLUMN "column"
#define OPT_TABLE_TYPE "tabletype"
#define OPT_PREFIX_NAME "prefixname"
#define OPT_HOST "host"
// Declaration of various structs
// used in valid process of settings
typedef struct redis_various_option
{
char *option_name;
Oid option_type;
} redis_various_option;
static redis_various_option redis_avaliable_options[] = {
{OPT_KEY, ForeignTableRelidIndexId},
{OPT_VALUE, ForeignTableRelidIndexId},
{OPT_PREFIX_NAME, ForeignTableRelationId},
{OPT_TTL, ForeignTableRelidIndexId},
{OPT_COLUMN, AttributeRelationId},
{OPT_TABLE_TYPE, ForeignTableRelationId},
{OPT_HOST, ForeignTableRelationId},
// This is for iteration
{NULL, InvalidOid}};
// We just iter through the redis_various_option to see whether the option and option type exist
// in predefined tables.
static bool redis_is_valid_option(const char *option_name, Oid option_typpe)
{
//elog(INFO, "*** %s", __FUNCTION__);
redis_various_option *option;
for (option = redis_avaliable_options; option->option_name != NULL; option++)
{
if (strcmp(option->option_name, option_name) == 0 && option_typpe == option->option_type)
{
return true;
}
}
return false;
}
Datum redis_link_validator(PG_FUNCTION_ARGS)
{
//elog(INFO, "*** %s", __FUNCTION__);
// we now start to do somethig.
List *options = untransformRelOptions(PG_GETARG_DATUM(0));
Oid option_type = PG_GETARG_OID(1);
ListCell *lc;
foreach (lc, options)
{
DefElem *def = (DefElem *)lfirst(lc);
if (!redis_is_valid_option(def->defname, option_type))
{
elog(ERROR, "not support this. The name is %s and the option is %u", def->defname, option_type);
}
}
PG_RETURN_VOID();
}
/* Internal function implement
*/
bool is_valid_key_type(Oid key_type)
{
//elog(INFO, "*** %s", __FUNCTION__);
if (key_type == TEXTOID || key_type == CHAROID || key_type == BPCHAROID || key_type == VARCHAROID)
{
return true;
}
return false;
}
int get_operation_type(char *name)
{
//elog(INFO, "*** %s", __FUNCTION__);
if (strcmp(name, "~~") == 0)
{
return OPERATION_LIKE;
}
else if (strcmp(name, "=") == 0)
{
return OPERATION_EQUAL;
}
else
{
return OPERATION_INVALID;
}
}
/*
Because the real key in redis would be like tablename+key:value.
So, when we need to lookup for some data, we shou do this by
lookup the key in tablename+whereclause.
the char * is palloced.
*/
char *make_tablename_into_where_clause(redisCtx *redis_ctx)
{
//elog(INFO, "*** %s", __FUNCTION__);
int name_len = strlen(redis_ctx->prefix_name) + strlen(redis_ctx->where_claus);
char *full_name = (char *)palloc0(name_len + 1);
strcpy(full_name, redis_ctx->prefix_name);
strcat(full_name, redis_ctx->where_claus);
full_name[name_len] = '\0';
// previous where_claus is palloced, so it shoule be fine.
return full_name;
}
void get_operation_infromation(OpExpr *expr, Oid *left_oid, Oid *right_oid, Oid *operation_type)
{
//elog(INFO, "*** %s", __FUNCTION__);
HeapTuple tuple;
Form_pg_operator form;
char *op_name;
*left_oid = InvalidOid;
*right_oid = InvalidOid;
tuple = SearchSysCache1(OPEROID, ObjectIdGetDatum(expr->opno));
if (!HeapTupleIsValid(tuple))
{
elog(ERROR, "ERROR when look up for system cache for get_left_type");
}
form = (Form_pg_operator)GETSTRUCT(tuple);
*left_oid = form->oprleft;
*right_oid = form->oprright;
op_name = NameStr(form->oprname);
*operation_type = get_operation_type(op_name);
ReleaseSysCache(tuple);
if (*left_oid == InvalidOid || *right_oid == InvalidOid || *operation_type == OPERATION_INVALID)
{
elog(ERROR, "ERROR during getting the oid of both side of operand, or failed to get operation name");
}
}
// This function will set the proper values for redis_ctx and try to connect to redis.
void set_redis_ctx(Oid foreigntableid, redisCtx *redis_ctx)
{
//elog(INFO, "*** %s", __FUNCTION__);
redis_ctx->foreign_table = GetForeignTable(foreigntableid);
redis_ctx->foreign_server = GetForeignServer(redis_ctx->foreign_table->serverid);
redis_ctx->table_type = REDIS_TABLE_INVALID;
redis_ctx->host = NULL;
redis_ctx->table_info = (redisTableInfo *)palloc(sizeof(redisTableInfo));
List *options = redis_ctx->foreign_table->options;
ListCell *lc;
redis_ctx->port = 6379;
foreach (lc, options)
{
DefElem *def = (DefElem *)lfirst(lc);
if (strcmp(def->defname, "host") == 0)
{
redis_ctx->host = defGetString(def);
}
else if (strcmp(def->defname, "password") == 0)
{
redis_ctx->password = defGetString(def);
}
else if (strcmp(def->defname, "port") == 0)
{
redis_ctx->port = defGetInt32(def);
}
else if (strcmp(def->defname, "tabletype") == 0)
{
char *table_type = defGetString(def);
if (strcmp(table_type, "string") == 0)
{
redis_ctx->table_type = REDIS_TABLE_STRING;
}
else if (strcmp(table_type, "hset") == 0)
{
redis_ctx->table_type = REDIS_TABLE_HSET;
}
else
{
redis_ctx->table_type = REDIS_TABLE_INVALID;
}
}
else if (strcmp(def->defname, "prefixname") == 0)
{
redis_ctx->prefix_name = defGetString(def);
}
else
{
elog(ERROR, "run into unknow database configuration. def is %s", def->defname);
}
}
if (redis_ctx->host == NULL)
{
int len_locahost = strlen("localhost");
redis_ctx->host = palloc(len_locahost + 1);
memcpy(redis_ctx->host, "localhost", len_locahost);
redis_ctx->host[len_locahost] = '\0';
}
if (redis_ctx->table_type == REDIS_TABLE_INVALID)
{
elog(ERROR, "Unknown table type");
}
redis_ctx->connection_context = redisConnect(redis_ctx->host, redis_ctx->port);
if (redis_ctx->connection_context == NULL)
{
elog(ERROR, "Could not connect to redis server");
}
set_redis_table_column(foreigntableid, redis_ctx);
}
// For now, we just record all the
void set_redis_table_column(Oid foreigntableid, redisCtx *redis_ctx)
{
//elog(INFO, "*** %s", __FUNCTION__);
Relation rel;
TupleDesc tupledesc;
redisTableInfo *table_info = redis_ctx->table_info;
table_info->tablename = get_rel_name(foreigntableid);
rel = heap_open(foreigntableid, NoLock);
tupledesc = rel->rd_att;
table_info->column_num = tupledesc->natts;
table_info->columns = (redisColumn *)palloc(table_info->column_num * sizeof(redisColumn));
for (int i = 0; i < table_info->column_num; i++)
{
Form_pg_attribute att = &tupledesc->attrs[i];
table_info->columns[i].column_name = pstrdup(NameStr(att->attname));
table_info->columns[i].atttypid = att->atttypid;
table_info->columns[i].atttypmod = att->atttypmod;
set_type_inout_function(table_info->columns[i].atttypid, &table_info->columns[i].typinput, &table_info->columns[i].typoutput);
}
heap_close(rel, NoLock);
}
void set_type_inout_function(Oid typeid, regproc *typinput, regproc *typoutput)
{
//elog(INFO, "*** %s", __FUNCTION__);
HeapTuple tuple;
tuple = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typeid));
if (!HeapTupleIsValid(tuple))
{
elog(ERROR, "ERROR when open the catalog for inout function");
}
Form_pg_type pg_type = (Form_pg_type)GETSTRUCT(tuple);
*typinput = pg_type->typinput;
*typoutput = pg_type->typoutput;
ReleaseSysCache(tuple);
}
// parse_where
//
void parse_where(redisCtx *redis_ctx, Expr *expr)
{
//elog(INFO, "*** %s", __FUNCTION__);
Oid left_oid;
Oid right_oid;
Oid operation_type;
Const *left_const;
OpExpr *opexpr;
switch (nodeTag(expr))
{
case T_OpExpr:
get_operation_infromation((OpExpr *)expr, &left_oid, &right_oid, &operation_type);
if (operation_type == OPERATION_LIKE)
{
opexpr = (OpExpr *)expr;
left_const = lsecond(opexpr->args);
char *arg = TextDatumGetCString(left_const->constvalue);
redis_ctx->where_claus = pstrdup(arg);
for (int i = 0; i < strlen(redis_ctx->where_claus); i++)
{
if (redis_ctx->where_claus[i] == '%')
{
redis_ctx->where_claus[i] = '*';
}
}
}
else
{
elog(ERROR, "sorry, we only support like operation at this stage.");
}
break;
default:
break;
}
}
// This function is to parse where claus for keys in select statements.
// for value or ttl, we don't do this because in this situation, we need to retrive all the tuples.
void set_where_clause(RelOptInfo *baserel, redisCtx *redis_ctx, List *baserestrictinfo)
{
//elog(INFO, "*** %s", __FUNCTION__);
Expr *expr;
RestrictInfo *rinfo;
ListCell *lc;
if (baserestrictinfo == NULL)
{
redis_ctx->where_claus = NULL;
return;
}
if (list_length(baserestrictinfo) == 1)
{
// we only need to run once.
foreach (lc, baserestrictinfo)
{
rinfo = (RestrictInfo *)lfirst(lc);
expr = rinfo->clause;
parse_where(redis_ctx, expr);
}
}
else
{
elog(ERROR, "sorry, currently we only support one where clues");
}
}
/* Here is the main part of the programme
*/
// Base for any other function and get realtion size
// in this function, we also set for the table name.
void redisLinkGetForeignRelSize(PlannerInfo *root,
RelOptInfo *baserel, Oid foreigntableid)
{
//elog(INFO, "*** %s", __FUNCTION__);
redisCtx *redis_ctx = (redisCtx *)palloc(sizeof(redisCtx));
baserel->fdw_private = redis_ctx;
set_redis_ctx(foreigntableid, redis_ctx);
redisReply *redis_reply = redisCommand(redis_ctx->connection_context, "dbsize");
if (redis_reply == NULL)
{
// seems not going to happen, but just in case
elog(ERROR, "could not execute dbsize");
}
double size = (double)redis_reply->integer;
baserel->rows = size;
baserel->tuples = size;
if (root->parse->commandType == CMD_SELECT)
{
set_where_clause(baserel, redis_ctx, baserel->baserestrictinfo);
}
else
{
elog(ERROR, "Sorry, we don't support command beyond select right now");
}
}
void redisLinkGetForeignPaths(PlannerInfo *root, RelOptInfo *baserel, Oid foreigntableid)
{
//elog(INFO, "*** %s", __FUNCTION__);
Cost startup_cost;
Cost total_cost;
redisCtx *redis_ctx = (redisCtx *)baserel->fdw_private;
startup_cost = 25; // randomly picked up.
if (redis_ctx->cmd_type == CMD_SELECT)
{
total_cost = startup_cost + baserel->rows;
}
else
{
total_cost = 1500; // temp setting.
}
Path *path = (Path *)create_foreignscan_path(root, baserel, NULL, baserel->rows, startup_cost, total_cost, NIL, NULL, NULL, NIL);
add_path(baserel, path);
}
ForeignScan *redisLinkGetForeignPlan(PlannerInfo *root, RelOptInfo *baserel,
Oid foreigntableid, ForeignPath *best_path,
List *tlist, List *scan_clauses, Plan *outer_plan)
{
//elog(INFO, "*** %s", __FUNCTION__);
scan_clauses = extract_actual_clauses(scan_clauses, false);
redisCtx *redis_ctx = baserel->fdw_private;
return make_foreignscan(tlist, scan_clauses, baserel->relid, NIL, (List *)redis_ctx, NIL, NIL, NULL);
}
void redisLinkBeginForeignScan(ForeignScanState *node, int eflags)
{
//elog(INFO, "*** %s", __FUNCTION__);
redisScanState *redis_scan_state = (redisScanState *)palloc0(sizeof(redisScanState));
ForeignScan *plan = (ForeignScan *)node->ss.ps.plan;
redis_scan_state->redis_ctx = (redisCtx *)plan->fdw_private;
redisCtx *redis_ctx = redis_scan_state->redis_ctx;
char *search_name; // tablename+key condition. like tablename:*
// This means that we are going to retrive all the keys under that table.
if (redis_scan_state->redis_ctx->where_claus == NULL)
{
char *where_clause = (char *)palloc0(2);
where_clause[0] = '*';
where_clause[1] = '\0';
redis_ctx->where_claus = where_clause;
}
search_name = make_tablename_into_where_clause(redis_ctx);
redis_scan_state->search_name = search_name;
redis_scan_state->redis_reply = redisCommand(redis_ctx->connection_context, "scan 0 match %s", redis_scan_state->search_name);
if (redis_scan_state->redis_reply == NULL)
{
elog(ERROR, "failed in begin scan. we could not get reply from redis");
}
redis_scan_state->current_cursor = atoi(redis_scan_state->redis_reply->element[0]->str);
redis_scan_state->list_capacity = (int)redis_scan_state->redis_reply->element[1]->elements;
redis_scan_state->list_current = 0;
redis_scan_state->upper_context = CurrentMemoryContext;
node->fdw_state = (void *)redis_scan_state;
}
TupleTableSlot *redisLinkIterateForeignScan(ForeignScanState *node)
{
//elog(INFO, "*** %s", __FUNCTION__);
MemoryContext old_context;
HeapTuple tuple;
TupleTableSlot *slot = node->ss.ss_ScanTupleSlot;
AttInMetadata *att;
char **keys; // we need first extract all the keys from a single scan operation.
char *value;
int ttl;
int i;
int list_capacity; //denote the returned length of list from a single scan.
int iter_redis_reply_status;
char **slot_build_strings;
char *buffer_ltoa;
att = TupleDescGetAttInMetadata(node->ss.ss_currentRelation->rd_att);
redisScanState *redis_scan_state = (redisScanState *)node->fdw_state;
ExecClearTuple(slot);
if (redis_scan_state->current_cursor == 0 && redis_scan_state->list_current == redis_scan_state->list_capacity)
{
return slot;
}
while (redis_scan_state->current_cursor != 0 && redis_scan_state->list_current == 0 && redis_scan_state->list_capacity == 0)
{
freeReplyObject(redis_scan_state->redis_reply);
redis_scan_state->redis_reply = redisCommand(redis_scan_state->redis_ctx->connection_context, "scan %d match %s", redis_scan_state->current_cursor, redis_scan_state->search_name);
if (redis_scan_state->redis_reply == NULL)
{
elog(ERROR, "failed in begin scan. we could not get reply from redis");
}
redis_scan_state->current_cursor = atoi(redis_scan_state->redis_reply->element[0]->str);
redis_scan_state->list_capacity = (int)redis_scan_state->redis_reply->element[1]->elements;
redis_scan_state->list_current = 0;
}
if (redis_scan_state->current_cursor == 0 && redis_scan_state->list_current == redis_scan_state->list_capacity)
{
return slot;
}
keys = redis_scan_state->keys;
// for now, we only support key value ttl in table column.
// so the magic number 3 is for 3 supported columns.
if (redis_scan_state->list_current == 0)
{
old_context = MemoryContextSwitchTo(redis_scan_state->upper_context);
if (keys != NULL)
{
// it seems that pfree is quite efficient
// and has less over then free from std.
pfree(keys);
}
keys = (char **)palloc(sizeof(char **) * redis_scan_state->list_capacity);
list_capacity = redis_scan_state->list_capacity;
for (i = 0; i < list_capacity; i++)
{
keys[i] = redis_scan_state->redis_reply->element[1]->element[i]->str;
redisAppendCommand(redis_scan_state->redis_ctx->connection_context, "get %s", keys[i]);
redisAppendCommand(redis_scan_state->redis_ctx->connection_context, "ttl %s", keys[i]);
}
redis_scan_state->keys = keys;
MemoryContextSwitchTo(old_context);
}
iter_redis_reply_status = redisGetReply(redis_scan_state->redis_ctx->connection_context, (void **)&redis_scan_state->iter_reply);
if (iter_redis_reply_status == REDIS_ERR)
{
elog(ERROR, "error during iter");
}
value = pstrdup(redis_scan_state->iter_reply->str);
freeReplyObject(redis_scan_state->iter_reply);
iter_redis_reply_status = redisGetReply(redis_scan_state->redis_ctx->connection_context, (void **)&redis_scan_state->iter_reply);
if (iter_redis_reply_status == REDIS_ERR)
{
elog(ERROR, "error during iter");
}
ttl = (int)redis_scan_state->iter_reply->integer;
freeReplyObject(redis_scan_state->iter_reply);
slot_build_strings = (char **)palloc(3 * sizeof(char **));
slot_build_strings[0] = keys[redis_scan_state->list_current];
slot_build_strings[1] = value;
buffer_ltoa = (char *)palloc(20 * sizeof(char)); // enough to hold int?
pg_ltoa(ttl, buffer_ltoa);
slot_build_strings[2] = buffer_ltoa;
tuple = BuildTupleFromCStrings(att, slot_build_strings);
redis_scan_state->list_current++;
ExecStoreTuple(tuple, slot, InvalidBuffer, false);
if (redis_scan_state->list_current == redis_scan_state->list_capacity && redis_scan_state->current_cursor != 0)
{
freeReplyObject(redis_scan_state->redis_reply);
redis_scan_state->redis_reply = redisCommand(redis_scan_state->redis_ctx->connection_context, "scan %d match %s", redis_scan_state->current_cursor, redis_scan_state->search_name);
if (redis_scan_state->redis_reply == NULL)
{
elog(ERROR, "failed in begin scan. we could not get reply from redis");
}
redis_scan_state->current_cursor = atoi(redis_scan_state->redis_reply->element[0]->str);
redis_scan_state->list_capacity = (int)redis_scan_state->redis_reply->element[1]->elements;
redis_scan_state->list_current = 0;
}
return slot;
}
void redisLinkReScanForeignScan(ForeignScanState *node)
{
//elog(INFO, "*** %s", __FUNCTION__);
redisScanState *redis_scan_state = (redisScanState *)node->fdw_state;
redis_scan_state->current_cursor = 0;
redis_scan_state->list_capacity = 0;
redis_scan_state->list_current = 0;
}
void redisLinkEndForeignScan(ForeignScanState *node)
{
//elog(INFO, "*** %s", __FUNCTION__);
redisScanState *redis_scan_state = (redisScanState *)node->fdw_state;
freeReplyObject(redis_scan_state->redis_reply);
redisFree(redis_scan_state->redis_ctx->connection_context);
}
static List *redisLinkPlanForeignModify(PlannerInfo *root, ModifyTable *plan,
Index resultRelation,
int subplan_index)
{
//elog(INFO, "*** %s", __FUNCTION__);
RangeTblEntry *rte;
Oid foreigntableid;
CmdType cmdtype = plan->operation;
if (cmdtype != CMD_INSERT)
{
elog(ERROR, "Sorry, currently we only support insert operation.");
}
redisCtx *redis_ctx = (redisCtx *)palloc(sizeof(redisCtx));
rte = planner_rt_fetch(resultRelation, root);
foreigntableid = rte->relid;
set_redis_ctx(foreigntableid, redis_ctx);
return (List *)redis_ctx;
}
static void
redisLinkBeginForeignModify(ModifyTableState *mtstate,
ResultRelInfo *rinfo,
List *fdw_private,
int subplan_index,
int eflags)
{
//elog(INFO, "*** %s", __FUNCTION__);
CmdType operation = mtstate->operation;
if (operation != CMD_INSERT)
{
elog(ERROR, "Sorry, for now we only support insert. beginmodify");
}
redisCtx *redis_ctx = (redisCtx *)fdw_private;
redisInsertState *insert_state = (redisInsertState *)palloc0(sizeof(redisInsertState));
insert_state->redis_ctx = redis_ctx;
insert_state->tmp_context = AllocSetContextCreate(mtstate->ps.state->es_query_cxt, "redis insert iter tmp memory", ALLOCSET_DEFAULT_SIZES);
rinfo->ri_FdwState = (void *)insert_state;
}
static TupleTableSlot *redisLinkExecForeignInsert(EState *estate,
ResultRelInfo *rinfo,
TupleTableSlot *slot,
TupleTableSlot *planSlot)
{
//elog(INFO, "*** %s", __FUNCTION__);
MemoryContext old_context;
Datum datum;
redisInsertState *insert_info = (redisInsertState *)rinfo->ri_FdwState;
redisTableInfo *table_info = insert_info->redis_ctx->table_info;
char *key;
char *value;
char *ttl;
int128 ttl_in_long;
int iter_redis_reply_status;
if (insert_info->attmeta == NULL)
{
insert_info->attmeta = TupleDescGetAttInMetadata(slot->tts_tupleDescriptor);
}
old_context = MemoryContextSwitchTo(insert_info->tmp_context);
for (int i = 0; i < table_info->column_num; i++)
{
bool isNull;
datum = slot_getattr(slot, i + 1, &isNull);
// TODO: we really need to set proper identifier in column instead of 0/1/2.
switch (i)
{
case 0:
key = DatumGetCString(OidFunctionCall1(table_info->columns[i].typoutput, datum));
break;
case 1:
value = DatumGetCString(OidFunctionCall1(table_info->columns[i].typoutput, datum));
break;
case 2:
if (isNull)
{
ttl_in_long = -1;
}
else
{
ttl = DatumGetCString(OidFunctionCall1(table_info->columns[i].typoutput, datum));
ttl_in_long = atoll(ttl);
}
break;
default:
elog(ERROR, "????? we should not be here.");
break;
}
}
if (ttl_in_long == -1)
{
redisAppendCommand(insert_info->redis_ctx->connection_context, "set %s %s", key, value);
}
else
{
redisAppendCommand(insert_info->redis_ctx->connection_context, "set %s %s ex %ld", key, value, ttl_in_long);
}
insert_info->cached_cmd++;
insert_info->current_buffered_data += strlen(key) + strlen(value);
if (insert_info->current_buffered_data > MAX_CACHED_MEMORY)
{
while (insert_info->cached_cmd > 0)
{
iter_redis_reply_status = redisGetReply(insert_info->redis_ctx->connection_context, (void **)&insert_info->iter_reply);
if (iter_redis_reply_status == REDIS_ERR)
{
elog(ERROR, "error during insert iter end");
}
freeReplyObject(insert_info->iter_reply);
insert_info->cached_cmd--;
}
insert_info->current_buffered_data = 0;
MemoryContextReset(CurrentMemoryContext);
}
MemoryContextSwitchTo(old_context);
return slot;
}
static void
redisLinkEndForeignModify(EState *estate,
ResultRelInfo *rinfo)
{
//elog(INFO, "*** %s", __FUNCTION__);
MemoryContext old_context;
int iter_redis_reply_status;
redisInsertState *insert_info = (redisInsertState *)rinfo->ri_FdwState;
old_context = MemoryContextSwitchTo(insert_info->tmp_context);
while (insert_info->cached_cmd > 0)
{
iter_redis_reply_status = redisGetReply(insert_info->redis_ctx->connection_context, (void **)&insert_info->iter_reply);
if (iter_redis_reply_status == REDIS_ERR)
{
elog(ERROR, "error during insert iter end");
}
freeReplyObject(insert_info->iter_reply);
insert_info->cached_cmd--;
}
redisFree(insert_info->redis_ctx->connection_context);
MemoryContextReset(CurrentMemoryContext);
MemoryContextSwitchTo(old_context);
}
static void
redisLinkBeginForeignInsert(ModifyTableState *mtstate,
ResultRelInfo *rinfo)
{
//elog(INFO, "*** %s", __FUNCTION__);
CmdType operation = mtstate->operation;
RangeTblEntry *rte;
Index result_table_index;
EState *estate;
Oid foreigntableid;
if (operation != CMD_INSERT)
{
elog(ERROR, "Sorry, for now we only support insert. beginmodify");
}
result_table_index = rinfo->ri_RangeTableIndex;
estate = mtstate->ps.state;
// get the rte of the foreign table.
// because we don't support partition table. it seems for now, it is ok.
rte = list_nth(estate->es_range_table, result_table_index - 1);
foreigntableid = rte->relid;
redisCtx *redis_ctx = (redisCtx *)palloc(sizeof(redisCtx));
set_redis_ctx(foreigntableid, redis_ctx);
redisInsertState *insert_state = (redisInsertState *)palloc0(sizeof(redisInsertState));
insert_state->redis_ctx = redis_ctx;
insert_state->tmp_context = AllocSetContextCreate(mtstate->ps.state->es_query_cxt, "redis insert iter tmp memory", ALLOCSET_DEFAULT_SIZES);
rinfo->ri_FdwState = (void *)insert_state;
}
static void redisLinkEndForeignInsert(EState *estate,
ResultRelInfo *rinfo)
{
//elog(INFO, "*** %s", __FUNCTION__);
MemoryContext old_context;
int iter_redis_reply_status;
redisInsertState *insert_info = (redisInsertState *)rinfo->ri_FdwState;
old_context = MemoryContextSwitchTo(insert_info->tmp_context);
while (insert_info->cached_cmd > 0)
{
iter_redis_reply_status = redisGetReply(insert_info->redis_ctx->connection_context, (void **)&insert_info->iter_reply);
if (iter_redis_reply_status == REDIS_ERR)
{
elog(ERROR, "error during insert iter end");
}
freeReplyObject(insert_info->iter_reply);
insert_info->cached_cmd--;
}
redisFree(insert_info->redis_ctx->connection_context);
MemoryContextReset(CurrentMemoryContext);
MemoryContextSwitchTo(old_context);
}
Datum redis_link_handler(PG_FUNCTION_ARGS)
{
FdwRoutine *froutine = makeNode(FdwRoutine);
froutine->GetForeignRelSize = redisLinkGetForeignRelSize;
froutine->GetForeignPaths = redisLinkGetForeignPaths;
froutine->GetForeignPlan = redisLinkGetForeignPlan;
froutine->BeginForeignScan = redisLinkBeginForeignScan;
froutine->IterateForeignScan = redisLinkIterateForeignScan;
froutine->ReScanForeignScan = redisLinkReScanForeignScan;
froutine->EndForeignScan = redisLinkEndForeignScan;
froutine->AddForeignUpdateTargets = NULL; // Currently we only want to support insert.
froutine->PlanForeignModify = redisLinkPlanForeignModify;
froutine->BeginForeignModify = redisLinkBeginForeignModify;
froutine->ExecForeignInsert = redisLinkExecForeignInsert;
froutine->EndForeignModify = redisLinkEndForeignModify;
froutine->BeginForeignInsert = redisLinkBeginForeignInsert;
froutine->EndForeignInsert = redisLinkEndForeignInsert;
PG_RETURN_POINTER(froutine);
} | 35.449686 | 187 | 0.661906 | [
"object"
] |
1c427f0edcdf1cbdf7b1b2002102a61fbc8da780 | 2,857 | h | C | src/Cpl/Io/File/Input.h | johnttaylor/foxtail | 86e4e1d19d5e8f9c1d1064cf0939f4bf62615400 | [
"BSD-3-Clause"
] | null | null | null | src/Cpl/Io/File/Input.h | johnttaylor/foxtail | 86e4e1d19d5e8f9c1d1064cf0939f4bf62615400 | [
"BSD-3-Clause"
] | null | null | null | src/Cpl/Io/File/Input.h | johnttaylor/foxtail | 86e4e1d19d5e8f9c1d1064cf0939f4bf62615400 | [
"BSD-3-Clause"
] | null | null | null | #ifndef Cpl_Io_File_Input_h_
#define Cpl_Io_File_Input_h_
/*-----------------------------------------------------------------------------
* This file is part of the Colony.Core Project. The Colony.Core Project is an
* open source project with a BSD type of licensing agreement. See the license
* agreement (license.txt) in the top/ directory or on the Internet at
* http://integerfox.com/colony.core/license.txt
*
* Copyright (c) 2014-2020 John T. Taylor
*
* Redistributions of the source code must retain the above copyright notice.
*----------------------------------------------------------------------------*/
/** @file */
#include "Cpl/Io/File/InputApi.h"
#include "Cpl/Io/Stdio/Input_.h"
///
namespace Cpl {
///
namespace Io {
///
namespace File {
/** This concrete class provides a platform independent 'standard'
implementation of a Cpl::Io::File::Input object.
NOTE: All the read operations return 'false' if an error occurred, this
INCLUDES the end-of-file condition (which is error when dealing
with streams). To differentiate between a true error and EOF, the
client must call isEof().
*/
class Input : public InputApi
{
protected:
/// Provides core read functionality
Cpl::Io::Stdio::Input_ m_stream;
public:
/// Constructor -->Opens the file
Input( const char* fileName );
/// Constructor. 'streamfd' is a the file descriptor of a existing/opened file.
Input( Cpl::Io::Descriptor streamfd );
/// Destructor -->Will insure the file gets closed
~Input();
public:
/** This method returns true if the file was successfully open and/or
is still opened (i.e. close() has not been called). Note: it is okay
to call other methods in the class if the file is not open - i.e.
nothing 'bad' will happen and the method will return 'failed'
status (when appropriate).
*/
bool isOpened();
public:
/// See Cpl::Io::Input
bool read( char& c );
/// See Cpl::Io::Input
bool read( Cpl::Text::String& destString );
/// See Cpl::Io::Input
bool read( void* buffer, int numBytes, int& bytesRead );
/// See Cpl::Io::Input
bool available();
/// See Cpl::Io::IsEos (is equivalent to isEof())
bool isEos();
/// See Cpl::Io::Close
void close();
public:
/// See Cpl::Io::File::ObjectApi (is quantile to isEos())
bool isEof();
/// See Cpl::Io::File::ObjectApi
bool length( unsigned long& len);
/// See Cpl::Io::File::ObjectApi
bool currentPos( unsigned long& curPos );
/// See Cpl::Io::File::ObjectApi
bool setRelativePos( long deltaOffset );
/// See Cpl::Io::File::ObjectApi
bool setAbsolutePos( unsigned long newoffset );
/// See Cpl::Io::File::ObjectApi
bool setToEof();
};
}; // end namespaces
};
};
#endif // end header latch
| 26.453704 | 83 | 0.618831 | [
"object"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.